This is python.info, produced by makeinfo version 6.5 from python.texi.

     Python 3.9.9, 1月 14, 2022

     unknown

     Copyright © 2001-2022, Python Software Foundation

INFO-DIR-SECTION Miscellaneous
START-INFO-DIR-ENTRY
* python: (python.info). One line description of project
END-INFO-DIR-ENTRY


   Generated by Sphinx 2.4.4.


File: python.info,  Node: Top,  Next: Python 有什麼新功能？,  Up: (dir)

Python
******

     Python 3.9.9, 1月 14, 2022

     unknown

     Copyright © 2001-2022, Python Software Foundation

* Menu:

* Python 有什麼新功能？::
* Python 教學::
* Python 的設置與使用::
* Python 語言參考手冊::
* Python 標準函式庫 (Standard Library): Python 標準函式庫 Standard Library.
* 擴充和嵌入 Python 直譯器::
* Python/C API 參考手冊::
* 發布 Python 模組::
* 安裝 Python 模組::
* Python 如何達成任務::
* Python 常見問題::
* 術語表::
* 關於這些說明文件::
* 處理錯誤 (Bug): 處理錯誤 Bug.
* 版權宣告::
* 沿革與授權::
* 發布 Python 模組（舊版）::
* 安裝 Python 模組（舊版）::
* Python 模組索引::
* 索引::

 — 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 有什么新变化.
* Changelog（更動日誌）::

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 中的重要变化.

新的特性

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

新增模块

* 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>.

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 中的重要变化.
* Notable changes in Python 3.8.12: Notable changes in 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::
* 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<2>.
* 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<3>.
* 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 changes::

PEP 393: 灵活的字符串表示

* Functionality::
* Performance and resource usage::

PEP 421: 添加 sys.implementation

* SimpleNamespace::

Using importlib as the Implementation of Import

* New APIs::
* Visible Changes::

新增模块

* 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<4>.
* 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 changes: API changes<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<5>.
* 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 有什么新变化

* 常见的绊脚石::
* Overview Of Syntax Changes::
* Changes Already Present In Python 2.6: Changes Already Present In Python 2 6.
* Library Changes::
* 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 Is A Function::
* Views And Iterators Instead Of Lists::
* Ordering Comparisons::
* 整数::
* Text Vs. Data Instead Of Unicode Vs. 8-bit: Text Vs Data Instead Of Unicode Vs 8-bit.

Overview Of Syntax Changes

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

Miscellaneous Other Changes

* Operators And Special Methods::
* Builtins::

Python 2.7 有什么新变化

* Python 2.x的未来: Python 2 x的未来.
* Changes to the Handling of Deprecation Warnings::
* Python 3.1 Features: Python 3 1 Features.
* 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; Dictionary Views: PEP 3106 Dictionary Views.
* PEP 3137; The memoryview Object: PEP 3137 The memoryview Object.
* 其他语言特性修改: 其他语言特性修改<10>.
* 新增和改进的模块::
* 构建和 C API 的改变: 构建和 C API 的改变<8>.
* Other Changes and Fixes::
* 移植到 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>.

开发过程的变化

* New Issue Tracker; Roundup: New Issue Tracker Roundup.
* 新的文档格式：使用 Sphinx 的 reStructuredText::

PEP 343: "with" 语句

* Writing Context Managers::
* 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" 语句

* Writing Context Managers: Writing Context Managers<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; Simpler String Substitutions: PEP 292 Simpler String Substitutions.
* PEP 318; Decorators for Functions and Methods: PEP 318 Decorators for Functions and Methods.
* 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; A Standard Set Datatype: PEP 218 A Standard Set Datatype.
* PEP 255; Simple Generators: PEP 255 Simple Generators.
* PEP 263; Source Code Encodings: PEP 263 Source Code Encodings.
* PEP 273; 从ZIP压缩包导入模块: PEP 273 从ZIP压缩包导入模块.
* PEP 277; Unicode file name support for Windows NT: PEP 277 Unicode file name support for Windows NT.
* 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; New Import Hooks: PEP 302 New Import Hooks.
* 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>.
* Other Changes and Fixes: Other Changes and Fixes<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 有什么新变化

* 簡介::
* PEPs 252 and 253; Type and Class Changes: PEPs 252 and 253 Type and Class Changes.
* PEP 234; Iterators: PEP 234 Iterators.
* PEP 255; Simple Generators: PEP 255 Simple Generators<2>.
* PEP 237; 统一长整数和整数: PEP 237 统一长整数和整数<2>.
* PEP 238; Changing the Division Operator: PEP 238 Changing the Division Operator.
* Unicode Changes::
* PEP 227; Nested Scopes: PEP 227 Nested Scopes.
* 新增和改进的模块: 新增和改进的模块<3>.
* Interpreter Changes and Fixes::
* Other Changes and Fixes: Other Changes and Fixes<3>.
* 致谢: 致谢<6>.

PEPs 252 and 253: Type and Class Changes

* Old and New Classes::
* Descriptors::
* Multiple Inheritance; The Diamond Rule: Multiple Inheritance The Diamond Rule.
* Attribute Access::
* Related Links::

Python 2.1 有什么新变化

* 簡介: 簡介<2>.
* PEP 227; Nested Scopes: PEP 227 Nested Scopes<2>.
* PEP 236; __future__ Directives: PEP 236 __future__ Directives.
* PEP 207; Rich Comparisons: PEP 207 Rich Comparisons.
* PEP 230; Warning Framework: PEP 230 Warning Framework.
* PEP 229; New Build System: PEP 229 New Build System.
* PEP 205; Weak References: PEP 205 Weak References.
* PEP 232; Function Attributes: PEP 232 Function Attributes.
* PEP 235; Importing Modules on Case-Insensitive Platforms: PEP 235 Importing Modules on Case-Insensitive Platforms.
* 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>.
* Other Changes and Fixes: Other Changes and Fixes<4>.
* 致谢: 致谢<7>.

Python 2.0 有什么新变化

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

其他核心变化

* Minor Language Changes::
* Changes to Built-in Functions::

XML 模块

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

Changelog（更動日誌）

* Python 下一版::
* 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 最终版: Python 3 9 6 最终版.
* Python 3.9.5 最终版: Python 3 9 5 最终版.
* 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 发布候选版 1: Python 3 9 2 发布候选版 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 发布候选版 1: Python 3 9 0 发布候选版 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 正式版: Python 3 7 0 正式版.
* Python 3.7.0 rc1: Python 3 7 0 rc1.
* 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 正式版: Python 3 6 6 正式版.
* Python 3.6.6 rc1: Python 3 6 6 rc1.
* Python 3.6.5 正式版: Python 3 6 5 正式版.
* Python 3.6.5 rc1: Python 3 6 5 rc1.
* Python 3.6.4 正式版: Python 3 6 4 正式版.
* Python 3.6.4 rc1: Python 3 6 4 rc1.
* Python 3.6.3 正式版: Python 3 6 3 正式版.
* Python 3.6.3 rc1: Python 3 6 3 rc1.
* Python 3.6.2 正式版: Python 3 6 2 正式版.
* Python 3.6.2 rc2: Python 3 6 2 rc2.
* Python 3.6.2 rc1: Python 3 6 2 rc1.
* Python 3.6.1 正式版: Python 3 6 1 正式版.
* Python 3.6.1 rc1: Python 3 6 1 rc1.
* Python 3.6.0 正式版: Python 3 6 0 正式版.
* Python 3.6.0 rc2: Python 3 6 0 rc2.
* Python 3.6.0 rc1: Python 3 6 0 rc1.
* 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 正式版: Python 3 5 5 正式版.
* Python 3.5.5 rc1: Python 3 5 5 rc1.
* Python 3.5.4 正式版: Python 3 5 4 正式版.
* Python 3.5.4 rc1: Python 3 5 4 rc1.
* Python 3.5.3 正式版: Python 3 5 3 正式版.
* Python 3.5.3 rc1: Python 3 5 3 rc1.
* Python 3.5.2 正式版: Python 3 5 2 正式版.
* Python 3.5.2 rc1: Python 3 5 2 rc1.
* Python 3.5.1 正式版: Python 3 5 1 正式版.
* Python 3.5.1 rc1: Python 3 5 1 rc1.
* Python 3.5.0 正式版: Python 3 5 0 正式版.
* Python 3.5.0 rc4: Python 3 5 0 rc4.
* Python 3.5.0 rc3: Python 3 5 0 rc3.
* Python 3.5.0 rc2: Python 3 5 0 rc2.
* Python 3.5.0 rc1: Python 3 5 0 rc1.
* 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 下一版

* 核心与内置函数::
* 库::
* 文档: 文档<2>.
* 测试::
* 构建::
* Windows::
* macOS::
* 工具/示例::
* C API::

Python 3.9.9 final

* 核心与内置函数: 核心与内置函数<2>.
* 库: 库<2>.
* 文档: 文档<3>.
* Windows: Windows<2>.

Python 3.9.8 final

* 核心与内置函数: 核心与内置函数<3>.
* 库: 库<3>.
* 文档: 文档<4>.
* 测试: 测试<2>.
* 构建: 构建<2>.
* Windows: Windows<3>.
* macOS: macOS<2>.
* IDLE: IDLE<3>.
* C API: C API<2>.

Python 3.9.7 final

* 安全性::
* 核心与内置函数: 核心与内置函数<4>.
* 库: 库<4>.
* 文档: 文档<5>.
* 测试: 测试<3>.
* 构建: 构建<3>.
* Windows: Windows<4>.
* macOS: macOS<3>.

Python 3.9.6 最终版

* 安全性: 安全性<2>.
* 核心与内置函数: 核心与内置函数<5>.
* 库: 库<5>.
* 文档: 文档<6>.
* 测试: 测试<4>.
* 构建: 构建<4>.
* Windows: Windows<5>.
* macOS: macOS<4>.
* IDLE: IDLE<4>.
* 工具/示例: 工具/示例<2>.
* C API: C API<3>.

Python 3.9.5 最终版

* 安全性: 安全性<3>.
* 核心与内置函数: 核心与内置函数<6>.
* 库: 库<6>.
* 文档: 文档<7>.
* 测试: 测试<5>.
* Windows: Windows<6>.
* macOS: macOS<5>.
* IDLE: IDLE<5>.

Python 3.9.4 final

* 核心与内置函数: 核心与内置函数<7>.
* 库: 库<7>.

Python 3.9.3 final

* 安全性: 安全性<4>.
* 核心与内置函数: 核心与内置函数<8>.
* 库: 库<8>.
* 文档: 文档<8>.
* 测试: 测试<6>.
* 构建: 构建<5>.
* macOS: macOS<6>.
* IDLE: IDLE<6>.

Python 3.9.2 final

* Windows: Windows<7>.

Python 3.9.2 发布候选版 1

* 安全性: 安全性<5>.
* 核心与内置函数: 核心与内置函数<9>.
* 库: 库<9>.
* 文档: 文档<9>.
* 测试: 测试<7>.
* 构建: 构建<6>.
* Windows: Windows<8>.
* macOS: macOS<7>.
* IDLE: IDLE<7>.
* 工具/示例: 工具/示例<3>.
* C API: C API<4>.

Python 3.9.1 final

* 核心与内置函数: 核心与内置函数<10>.
* 库: 库<10>.
* 测试: 测试<8>.
* macOS: macOS<8>.
* IDLE: IDLE<8>.

Python 3.9.1 release candidate 1

* 安全性: 安全性<6>.
* 核心与内置函数: 核心与内置函数<11>.
* 库: 库<11>.
* 文档: 文档<10>.
* 测试: 测试<9>.
* 构建: 构建<7>.
* Windows: Windows<9>.
* macOS: macOS<9>.
* IDLE: IDLE<9>.
* C API: C API<5>.

Python 3.9.0 final

* 库: 库<12>.
* 测试: 测试<10>.
* 构建: 构建<8>.

Python 3.9.0 release candidate 2

* 核心与内置函数: 核心与内置函数<12>.
* 库: 库<13>.
* 文档: 文档<11>.
* 测试: 测试<11>.
* 构建: 构建<9>.
* Windows: Windows<10>.
* C API: C API<6>.

Python 3.9.0 发布候选版 1

* 核心与内置函数: 核心与内置函数<13>.
* 库: 库<14>.
* 文档: 文档<12>.
* Windows: Windows<11>.
* IDLE: IDLE<10>.

Python 3.9.0 beta 5

* 安全性: 安全性<7>.
* 核心与内置函数: 核心与内置函数<14>.
* 库: 库<15>.
* 文档: 文档<13>.
* macOS: macOS<10>.
* IDLE: IDLE<11>.
* C API: C API<7>.

Python 3.9.0 beta 4

* 安全性: 安全性<8>.
* 核心与内置函数: 核心与内置函数<15>.
* 库: 库<16>.
* 测试: 测试<12>.
* 构建: 构建<10>.
* Windows: Windows<12>.
* macOS: macOS<11>.
* IDLE: IDLE<12>.
* C API: C API<8>.

Python 3.9.0 beta 3

* 库: 库<17>.
* 构建: 构建<11>.

Python 3.9.0 beta 2

* 核心与内置函数: 核心与内置函数<16>.
* 库: 库<18>.
* 测试: 测试<13>.
* 构建: 构建<12>.
* Windows: Windows<13>.
* macOS: macOS<12>.
* IDLE: IDLE<13>.
* C API: C API<9>.

Python 3.9.0 beta 1

* 安全性: 安全性<9>.
* 核心与内置函数: 核心与内置函数<17>.
* 库: 库<19>.
* 文档: 文档<14>.
* 测试: 测试<14>.
* 构建: 构建<13>.
* Windows: Windows<14>.
* macOS: macOS<13>.
* 工具/示例: 工具/示例<4>.
* C API: C API<10>.

Python 3.9.0 alpha 6

* 安全性: 安全性<10>.
* 核心与内置函数: 核心与内置函数<18>.
* 库: 库<20>.
* 文档: 文档<15>.
* 测试: 测试<15>.
* 构建: 构建<14>.
* Windows: Windows<15>.
* macOS: macOS<14>.
* IDLE: IDLE<14>.
* 工具/示例: 工具/示例<5>.
* C API: C API<11>.

Python 3.9.0 alpha 5

* 安全性: 安全性<11>.
* 核心与内置函数: 核心与内置函数<19>.
* 库: 库<21>.
* 文档: 文档<16>.
* 测试: 测试<16>.
* 构建: 构建<15>.
* Windows: Windows<16>.
* macOS: macOS<15>.
* IDLE: IDLE<15>.
* 工具/示例: 工具/示例<6>.
* C API: C API<12>.

Python 3.9.0 alpha 4

* 安全性: 安全性<12>.
* 核心与内置函数: 核心与内置函数<20>.
* 库: 库<22>.
* 文档: 文档<17>.
* 测试: 测试<17>.
* 构建: 构建<16>.
* Windows: Windows<17>.
* IDLE: IDLE<16>.
* C API: C API<13>.

Python 3.9.0 alpha 3

* 核心与内置函数: 核心与内置函数<21>.
* 库: 库<23>.
* 文档: 文档<18>.
* 构建: 构建<17>.
* IDLE: IDLE<17>.
* C API: C API<14>.

Python 3.9.0 alpha 2

* 安全性: 安全性<13>.
* 核心与内置函数: 核心与内置函数<22>.
* 库: 库<24>.
* 文档: 文档<19>.
* 测试: 测试<18>.
* 构建: 构建<18>.
* Windows: Windows<18>.
* macOS: macOS<16>.
* IDLE: IDLE<18>.
* C API: C API<15>.

Python 3.9.0 alpha 1

* 安全性: 安全性<14>.
* 核心与内置函数: 核心与内置函数<23>.
* 库: 库<25>.
* 文档: 文档<20>.
* 测试: 测试<19>.
* 构建: 构建<19>.
* Windows: Windows<19>.
* macOS: macOS<17>.
* IDLE: IDLE<19>.
* 工具/示例: 工具/示例<7>.
* C API: C API<16>.

Python 3.8.0 beta 1

* 安全性: 安全性<15>.
* 核心与内置函数: 核心与内置函数<24>.
* 库: 库<26>.
* 文档: 文档<21>.
* 测试: 测试<20>.
* 构建: 构建<20>.
* Windows: Windows<20>.
* macOS: macOS<18>.
* IDLE: IDLE<20>.
* 工具/示例: 工具/示例<8>.
* C API: C API<17>.

Python 3.8.0 alpha 4

* 安全性: 安全性<16>.
* 核心与内置函数: 核心与内置函数<25>.
* 库: 库<27>.
* 文档: 文档<22>.
* 测试: 测试<21>.
* 构建: 构建<21>.
* Windows: Windows<21>.
* macOS: macOS<19>.
* IDLE: IDLE<21>.
* 工具/示例: 工具/示例<9>.
* C API: C API<18>.

Python 3.8.0 alpha 3

* 安全性: 安全性<17>.
* 核心与内置函数: 核心与内置函数<26>.
* 库: 库<28>.
* 文档: 文档<23>.
* 测试: 测试<22>.
* 构建: 构建<22>.
* Windows: Windows<22>.
* IDLE: IDLE<22>.
* 工具/示例: 工具/示例<10>.
* C API: C API<19>.

Python 3.8.0 alpha 2

* 核心与内置函数: 核心与内置函数<27>.
* 库: 库<29>.
* 文档: 文档<24>.
* 测试: 测试<23>.
* Windows: Windows<23>.
* IDLE: IDLE<23>.

Python 3.8.0 alpha 1

* 安全性: 安全性<18>.
* 核心与内置函数: 核心与内置函数<28>.
* 库: 库<30>.
* 文档: 文档<25>.
* 测试: 测试<24>.
* 构建: 构建<23>.
* Windows: Windows<24>.
* macOS: macOS<20>.
* IDLE: IDLE<24>.
* 工具/示例: 工具/示例<11>.
* C API: C API<20>.

Python 3.7.0 正式版

* 库: 库<31>.
* C API: C API<21>.

Python 3.7.0 rc1

* 核心与内置函数: 核心与内置函数<29>.
* 库: 库<32>.
* 文档: 文档<26>.
* 构建: 构建<24>.
* Windows: Windows<25>.
* IDLE: IDLE<25>.

Python 3.7.0 beta 5

* 核心与内置函数: 核心与内置函数<30>.
* 库: 库<33>.
* 文档: 文档<27>.
* 测试: 测试<25>.
* 构建: 构建<25>.
* macOS: macOS<21>.
* IDLE: IDLE<26>.

Python 3.7.0 beta 4

* 核心与内置函数: 核心与内置函数<31>.
* 库: 库<34>.
* 文档: 文档<28>.
* 测试: 测试<26>.
* 构建: 构建<26>.
* Windows: Windows<26>.
* macOS: macOS<22>.
* IDLE: IDLE<27>.
* 工具/示例: 工具/示例<12>.

Python 3.7.0 beta 3

* 安全性: 安全性<19>.
* 核心与内置函数: 核心与内置函数<32>.
* 库: 库<35>.
* 文档: 文档<29>.
* 测试: 测试<27>.
* 构建: 构建<27>.
* Windows: Windows<27>.
* macOS: macOS<23>.
* IDLE: IDLE<28>.
* 工具/示例: 工具/示例<13>.
* C API: C API<22>.

Python 3.7.0 beta 2

* 安全性: 安全性<20>.
* 核心与内置函数: 核心与内置函数<33>.
* 库: 库<36>.
* 文档: 文档<30>.
* 测试: 测试<28>.
* 构建: 构建<28>.
* Windows: Windows<28>.
* macOS: macOS<24>.
* IDLE: IDLE<29>.
* 工具/示例: 工具/示例<14>.

Python 3.7.0 beta 1

* 核心与内置函数: 核心与内置函数<34>.
* 库: 库<37>.
* 文档: 文档<31>.
* 测试: 测试<29>.
* 构建: 构建<29>.
* Windows: Windows<29>.
* macOS: macOS<25>.
* C API: C API<23>.

Python 3.7.0 alpha 4

* 核心与内置函数: 核心与内置函数<35>.
* 库: 库<38>.
* 文档: 文档<32>.
* 测试: 测试<30>.
* Windows: Windows<30>.
* 工具/示例: 工具/示例<15>.
* C API: C API<24>.

Python 3.7.0 alpha 3

* 核心与内置函数: 核心与内置函数<36>.
* 库: 库<39>.
* 文档: 文档<33>.
* 测试: 测试<31>.
* 构建: 构建<30>.
* Windows: Windows<31>.
* macOS: macOS<26>.
* IDLE: IDLE<30>.
* 工具/示例: 工具/示例<16>.
* C API: C API<25>.

Python 3.7.0 alpha 2

* 核心与内置函数: 核心与内置函数<37>.
* 库: 库<40>.
* 文档: 文档<34>.
* 构建: 构建<31>.
* IDLE: IDLE<31>.
* C API: C API<26>.

Python 3.7.0 alpha 1

* 安全性: 安全性<21>.
* 核心与内置函数: 核心与内置函数<38>.
* 库: 库<41>.
* 文档: 文档<35>.
* 测试: 测试<32>.
* 构建: 构建<32>.
* Windows: Windows<32>.
* IDLE: IDLE<32>.
* 工具/示例: 工具/示例<17>.
* C API: C API<27>.

Python 3.6.6 rc1

* 核心与内置函数: 核心与内置函数<39>.
* 库: 库<42>.
* 文档: 文档<36>.
* 测试: 测试<33>.
* 构建: 构建<33>.
* Windows: Windows<33>.
* macOS: macOS<27>.
* IDLE: IDLE<33>.
* 工具/示例: 工具/示例<18>.
* C API: C API<28>.

Python 3.6.5 正式版

* 测试: 测试<34>.
* 构建: 构建<34>.

Python 3.6.5 rc1

* 安全性: 安全性<22>.
* 核心与内置函数: 核心与内置函数<40>.
* 库: 库<43>.
* 文档: 文档<37>.
* 测试: 测试<35>.
* 构建: 构建<35>.
* Windows: Windows<34>.
* macOS: macOS<28>.
* IDLE: IDLE<34>.
* 工具/示例: 工具/示例<19>.
* C API: C API<29>.

Python 3.6.4 rc1

* 核心与内置函数: 核心与内置函数<41>.
* 库: 库<44>.
* 文档: 文档<38>.
* 测试: 测试<36>.
* 构建: 构建<36>.
* Windows: Windows<35>.
* macOS: macOS<29>.
* IDLE: IDLE<35>.
* 工具/示例: 工具/示例<20>.
* C API: C API<30>.

Python 3.6.3 正式版

* 库: 库<45>.
* 构建: 构建<37>.

Python 3.6.3 rc1

* 安全性: 安全性<23>.
* 核心与内置函数: 核心与内置函数<42>.
* 库: 库<46>.
* 文档: 文档<39>.
* 测试: 测试<37>.
* 构建: 构建<38>.
* Windows: Windows<36>.
* IDLE: IDLE<36>.
* 工具/示例: 工具/示例<21>.

Python 3.6.2 rc2

* 安全性: 安全性<24>.

Python 3.6.2 rc1

* 核心与内置函数: 核心与内置函数<43>.
* 库: 库<47>.
* 安全性: 安全性<25>.
* 库: 库<48>.
* IDLE: IDLE<37>.
* C API: C API<31>.
* 构建: 构建<39>.
* 文档: 文档<40>.
* 工具/示例: 工具/示例<22>.
* 测试: 测试<38>.
* Windows: Windows<37>.

Python 3.6.1 正式版

* 核心与内置函数: 核心与内置函数<44>.
* 构建: 构建<40>.

Python 3.6.1 rc1

* 核心与内置函数: 核心与内置函数<45>.
* 库: 库<49>.
* IDLE: IDLE<38>.
* Windows: Windows<38>.
* C API: C API<32>.
* 文档: 文档<41>.
* 测试: 测试<39>.
* 构建: 构建<41>.

Python 3.6.0 rc2

* 核心与内置函数: 核心与内置函数<46>.
* 工具/示例: 工具/示例<23>.
* Windows: Windows<39>.
* 构建: 构建<42>.

Python 3.6.0 rc1

* 核心与内置函数: 核心与内置函数<47>.
* 库: 库<50>.
* C API: C API<33>.
* 文档: 文档<42>.
* 工具/示例: 工具/示例<24>.

Python 3.6.0 beta 4

* 核心与内置函数: 核心与内置函数<48>.
* 库: 库<51>.
* 文档: 文档<43>.
* 测试: 测试<40>.
* 构建: 构建<43>.

Python 3.6.0 beta 3

* 核心与内置函数: 核心与内置函数<49>.
* 库: 库<52>.
* Windows: Windows<40>.
* 构建: 构建<44>.
* 测试: 测试<41>.

Python 3.6.0 beta 2

* 核心与内置函数: 核心与内置函数<50>.
* 库: 库<53>.
* Windows: Windows<41>.
* C API: C API<34>.
* 构建: 构建<45>.
* 测试: 测试<42>.

Python 3.6.0 beta 1

* 核心与内置函数: 核心与内置函数<51>.
* 库: 库<54>.
* IDLE: IDLE<39>.
* C API: C API<35>.
* 测试: 测试<43>.
* 构建: 构建<46>.
* 工具/示例: 工具/示例<25>.
* Windows: Windows<42>.

Python 3.6.0 alpha 4

* 核心与内置函数: 核心与内置函数<52>.
* 库: 库<55>.
* IDLE: IDLE<40>.
* 测试: 测试<44>.
* Windows: Windows<43>.
* 构建: 构建<47>.

Python 3.6.0 alpha 3

* 核心与内置函数: 核心与内置函数<53>.
* 库: 库<56>.
* 安全性: 安全性<26>.
* 库: 库<57>.
* 安全性: 安全性<27>.
* 库: 库<58>.
* IDLE: IDLE<41>.
* C API: C API<36>.
* 构建: 构建<48>.
* 工具/示例: 工具/示例<26>.
* 文档: 文档<44>.
* 测试: 测试<45>.

Python 3.6.0 alpha 2

* 核心与内置函数: 核心与内置函数<54>.
* 库: 库<59>.
* 安全性: 安全性<28>.
* 库: 库<60>.
* 安全性: 安全性<29>.
* 库: 库<61>.
* IDLE: IDLE<42>.
* 文档: 文档<45>.
* 测试: 测试<46>.
* Windows: Windows<44>.
* 构建: 构建<49>.
* Windows: Windows<45>.
* C API: C API<37>.
* 工具/示例: 工具/示例<27>.

Python 3.6.0 alpha 1

* 核心与内置函数: 核心与内置函数<55>.
* 库: 库<62>.
* 安全性: 安全性<30>.
* 库: 库<63>.
* 安全性: 安全性<31>.
* 库: 库<64>.
* 安全性: 安全性<32>.
* 库: 库<65>.
* IDLE: IDLE<43>.
* 文档: 文档<46>.
* 测试: 测试<47>.
* 构建: 构建<50>.
* Windows: Windows<46>.
* 工具/示例: 工具/示例<28>.
* C API: C API<38>.

Python 3.5.5 rc1

* 安全性: 安全性<33>.
* 核心与内置函数: 核心与内置函数<56>.
* 库: 库<66>.

Python 3.5.4 正式版

* 库: 库<67>.

Python 3.5.4 rc1

* 安全性: 安全性<34>.
* 核心与内置函数: 核心与内置函数<57>.
* 库: 库<68>.
* 文档: 文档<47>.
* 测试: 测试<48>.
* 构建: 构建<51>.
* Windows: Windows<47>.
* C API: C API<39>.

Python 3.5.3 rc1

* 核心与内置函数: 核心与内置函数<58>.
* 库: 库<69>.
* 安全性: 安全性<35>.
* 库: 库<70>.
* 安全性: 安全性<36>.
* 库: 库<71>.
* IDLE: IDLE<44>.
* C API: C API<40>.
* 文档: 文档<48>.
* 测试: 测试<49>.
* 工具/示例: 工具/示例<29>.
* Windows: Windows<48>.
* 构建: 构建<52>.

Python 3.5.2 正式版

* 核心与内置函数: 核心与内置函数<59>.
* 测试: 测试<50>.
* IDLE: IDLE<45>.

Python 3.5.2 rc1

* 核心与内置函数: 核心与内置函数<60>.
* 安全性: 安全性<37>.
* 库: 库<72>.
* 安全性: 安全性<38>.
* 库: 库<73>.
* 安全性: 安全性<39>.
* 库: 库<74>.
* 安全性: 安全性<40>.
* 库: 库<75>.
* 安全性: 安全性<41>.
* 库: 库<76>.
* IDLE: IDLE<46>.
* 文档: 文档<49>.
* 测试: 测试<51>.
* 构建: 构建<53>.
* Windows: Windows<49>.
* 工具/示例: 工具/示例<30>.
* Windows: Windows<50>.

Python 3.5.1 正式版

* 核心与内置函数: 核心与内置函数<61>.
* Windows: Windows<51>.

Python 3.5.1 rc1

* 核心与内置函数: 核心与内置函数<62>.
* 库: 库<77>.
* IDLE: IDLE<47>.
* 文档: 文档<50>.
* 测试: 测试<52>.
* 构建: 构建<54>.
* Windows: Windows<52>.
* 工具/示例: 工具/示例<31>.

Python 3.5.0 正式版

* 构建: 构建<55>.

Python 3.5.0 rc4

* 库: 库<78>.
* 构建: 构建<56>.

Python 3.5.0 rc3

* 核心与内置函数: 核心与内置函数<63>.
* 库: 库<79>.

Python 3.5.0 rc2

* 核心与内置函数: 核心与内置函数<64>.
* 库: 库<80>.

Python 3.5.0 rc1

* 核心与内置函数: 核心与内置函数<65>.
* 库: 库<81>.
* IDLE: IDLE<48>.
* 文档: 文档<51>.
* 测试: 测试<53>.

Python 3.5.0 beta 4

* 核心与内置函数: 核心与内置函数<66>.
* 库: 库<82>.
* 构建: 构建<57>.

Python 3.5.0 beta 3

* 核心与内置函数: 核心与内置函数<67>.
* 库: 库<83>.
* 测试: 测试<54>.
* 文档: 文档<52>.
* 构建: 构建<58>.

Python 3.5.0 beta 2

* 核心与内置函数: 核心与内置函数<68>.
* 库: 库<84>.

Python 3.5.0 beta 1

* 核心与内置函数: 核心与内置函数<69>.
* 库: 库<85>.
* IDLE: IDLE<49>.
* 测试: 测试<55>.
* 文档: 文档<53>.
* 工具/示例: 工具/示例<32>.

Python 3.5.0 alpha 4

* 核心与内置函数: 核心与内置函数<70>.
* 库: 库<86>.
* 构建: 构建<59>.
* 测试: 测试<56>.
* 工具/示例: 工具/示例<33>.
* C API: C API<41>.

Python 3.5.0 alpha 3

* 核心与内置函数: 核心与内置函数<71>.
* 库: 库<87>.
* 构建: 构建<60>.
* 测试: 测试<57>.
* 工具/示例: 工具/示例<34>.

Python 3.5.0 alpha 2

* 核心与内置函数: 核心与内置函数<72>.
* 库: 库<88>.
* 构建: 构建<61>.
* C API: C API<42>.
* Windows: Windows<53>.

Python 3.5.0 alpha 1

* 核心与内置函数: 核心与内置函数<73>.
* 库: 库<89>.
* IDLE: IDLE<50>.
* 构建: 构建<62>.
* C API: C API<43>.
* 文档: 文档<54>.
* 测试: 测试<58>.
* 工具/示例: 工具/示例<35>.
* Windows: Windows<54>.

Python 教學

* 淺嘗滋味::
* 使用 Python 直譯器::
* 一個非正式的 Python 簡介::
* 深入了解流程控制::
* 資料結構::
* 模組 (Module): 模組 Module.
* 輸入和輸出::
* 錯誤和例外::
* Class（類別）::
* Python 標準函式庫概覽::
* Python 標準函式庫概覽——第二部份::
* 虛擬環境與套件::
* 現在可以來學習些什麼？::
* 互動式輸入編輯和歷史記錄替換::
* 浮點數運算：問題與限制::
* 附錄::

使用 Python 直譯器

* 啟動直譯器::
* 直譯器與它的環境::

啟動直譯器

* 傳遞引數::
* 互動模式::

直譯器與它的環境

* 原始碼的字元編碼 (encoding): 原始碼的字元編碼 encoding.

一個非正式的 Python 簡介

* 把 Python 當作計算機使用::
* 初探程式設計的前幾步::

把 Python 當作計算機使用

* 數字 (Number): 數字 Number.
* 字串 (String): 字串 String.
* List（串列）::

深入了解流程控制

* if 陳述式::
* for 陳述式::
* range() 函式: range 函式.
* 迴圈內的 break 和 continue 陳述式及 else 子句::
* pass 陳述式::
* 定義函式 (function): 定義函式 function.
* 深入了解函式定義::
* 間奏曲：程式碼風格 (Coding Style): 間奏曲：程式碼風格 Coding Style.

深入了解函式定義

* 預設引數值::
* 關鍵字引數::
* 特殊參數::
* 任意引數列表 (Arbitrary Argument Lists): 任意引數列表 Arbitrary Argument Lists.
* 拆解引數列表（Unpacking Argument Lists）::
* Lambda 運算式::
* 說明文件字串 (Documentation Strings): 說明文件字串 Documentation Strings.
* 函式註釋 (Function Annotations): 函式註釋 Function Annotations.

特殊參數

* 位置或關鍵字引數 (Positional-or-Keyword Arguments): 位置或關鍵字引數 Positional-or-Keyword Arguments.
* 僅限位置參數 (Positional-Only Parameters): 僅限位置參數 Positional-Only Parameters.
* 僅限關鍵字引數 (Keyword-Only Arguments): 僅限關鍵字引數 Keyword-Only Arguments.
* 函式範例::
* 回顧::

資料結構

* 進一步了解 List（串列）::
* del 陳述式::
* Tuples 和序列 (Sequences): Tuples 和序列 Sequences.
* 集合 (Sets): 集合 Sets.
* 字典（Dictionary）::
* 迴圈技巧::
* 深入了解條件 (Condition): 深入了解條件 Condition.
* 序列和其他資料類型之比較::

進一步了解 List（串列）

* 將 List 作為 Stack（堆疊）使用::
* 將 List 作為 Queue（佇列）使用::
* List Comprehensions（串列綜合運算）::
* 巢狀的 List Comprehensions::

模組 (Module)

* 深入了解模組::
* 標準模組::
* dir() 函式: dir 函式.
* 套件 (Package): 套件 Package.

深入了解模組

* 把模組當作腳本執行::
* 模組的搜尋路徑::
* 「編譯」Python 檔案::

套件 (Package)

* 從套件中 import *::
* 套件內引用::
* 多目錄中的套件::

輸入和輸出

* 更華麗的輸出格式::
* 讀寫檔案::

更華麗的輸出格式

* 格式化的字串文本 (Formatted String Literals): 格式化的字串文本 Formatted String Literals.
* 字串的 format() method: 字串的 format method.
* 手動格式化字串::
* 格式化字串的舊方法::

讀寫檔案

* 檔案物件的 method::
* 使用 json 儲存結構化資料::

錯誤和例外

* 語法錯誤 (Syntax Error): 語法錯誤 Syntax Error.
* 例外 (Exception): 例外 Exception.
* 處理例外::
* 引發例外::
* 例外鏈接 (Exception Chaining): 例外鏈接 Exception Chaining.
* 使用者自定的例外::
* 定義清理動作::
* 預定義的清理動作::

Class（類別）

* 關於名稱與物件的一段話::
* Python 作用域 (Scope) 及命名空間 (Namespace): Python 作用域 Scope 及命名空間 Namespace.
* 初見 class::
* 隨意的備註::
* 繼承 (Inheritance): 繼承 Inheritance.
* 私有變數::
* 補充說明::
* 疊代器 (Iterator): 疊代器 Iterator.
* 產生器 (Generator): 產生器 Generator.
* 產生器運算式::

Python 作用域 (Scope) 及命名空間 (Namespace)

* 作用域和命名空間的範例::

初見 class

* Class definition（類別定義）語法::
* Class 物件::
* 實例物件::
* Method 物件::
* Class 及實例變數::

繼承 (Inheritance)

* 多重繼承::

Python 標準函式庫概覽

* 作業系統介面::
* 檔案之萬用字元 (File Wildcards): 檔案之萬用字元 File Wildcards.
* 命令列引數::
* 錯誤輸出重新導向與程式終止::
* 字串樣式比對::
* 數學相關::
* 網路存取::
* 日期與時間::
* 資料壓縮::
* 效能量測::
* 品質控管::
* 標準模組庫::

Python 標準函式庫概覽——第二部份

* 輸出格式化 (Output Formatting): 輸出格式化 Output Formatting.
* 模板化 (Templating): 模板化 Templating.
* 二進制資料記錄編排 (Binary Data Record Layouts): 二進制資料記錄編排 Binary Data Record Layouts.
* 多執行緒 (Multi-threading): 多執行緒 Multi-threading.
* 日誌記錄 (Logging): 日誌記錄 Logging.
* 弱引用 (Weak References): 弱引用 Weak References.
* 使用於 List 的工具::
* 十進制 (Decimal) 浮點數運算: 十進制 Decimal 浮點數運算.

虛擬環境與套件

* 簡介: 簡介<4>.
* 建立虛擬環境::
* 用 pip 管理套件::

互動式輸入編輯和歷史記錄替換

* Tab 鍵自動完成 (Tab Completion) 和歷史記錄編輯 (History Editing): Tab 鍵自動完成 Tab Completion 和歷史記錄編輯 History Editing.
* 互動式直譯器的替代方案::

浮點數運算：問題與限制

* 表示法誤差 (Representation Error): 表示法誤差 Representation Error.

附錄

* 互動模式: 互動模式<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启动器::
* 查找模块::
* 附加模块::
* 編譯 Python 在 Windows::
* 其他平台::

完整安装程序

* 安装步骤::
* 删除 MAX_PATH 限制::
* 安裝排除使用者介面::
* 當安裝時不下載::
* 修改安装::

Microsoft Store包

* 已知的问题::

可嵌入的包

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

設定 Python

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

适用于Windows的Python启动器

* 開始::
* Shebang Lines::
* shebang lines 的参数::
* 自定义::
* 诊断::

開始

* 从命令行::
* 虛擬環境（Virtual environment）::
* 从脚本::
* 從檔案關聯::

自定义

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

附加模块

* PyWin32::
* cx_Freeze::
* WConio::

在 Mac 系統使用Python

* 取得和安裝 MacPython::
* 整合化開發工具::
* 安装额外的 Python 包::
* 圖形化使用者介面(GUI) 程式開發於Mac: 圖形化使用者介面 GUI 程式開發於Mac.
* 貢獻Python應用程式於 Mac::
* 其他資源::

取得和安裝 MacPython

* 如何執行Python腳本::
* 透過使用者圖形介面執行腳本::
* 設定::

Python 語言參考手冊

* 簡介: 簡介<5>.
* 词法分析::
* 数据模型::
* 执行模型::
* 导入系统::
* 表达式::
* 简单语句::
* 复合语句::
* 顶级组件::
* 完整的語法規格書::

簡介

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

词法分析

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

行结构

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

标识符和关键字

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

字面值

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

数据模型

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

特殊方法名称

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

自定义属性访问

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

__slots__

* 使用 __slots__ 的注意事项::

自定义类创建

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

模拟泛型类型

* The purpose of __class_getitem__::
* __class_getitem__ versus __getitem__::

协程

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

执行模型

* 程序的结构::
* 命名与绑定::
* 异常::

命名与绑定

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

导入系统

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

包

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

搜索

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

加载

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

基于路径的查找器

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

有关 __main__ 的特殊事项

* __main__.__spec__: __main__ __spec__.

表达式

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

原子

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

yield 表达式

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

原型

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

比较运算

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

简单语句

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

赋值语句

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

import 语句

* future 语句::

复合语句

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

协程

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

顶级组件

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

Python 標準函式庫 (Standard Library)

* 簡介: 簡介<6>.
* 內建函式::
* 內建常數::
* 內建型態::
* 內建的例外::
* 文本處理 (Text Processing) 服務: 文本處理 Text Processing 服務.
* 二进制数据服务::
* 数据类型::
* 數值與數學模組::
* 函式編程模組::
* 檔案與目錄存取::
* 数据持久化::
* 資料壓縮與保存::
* 檔案格式::
* 加密服务::
* 通用操作系统服务::
* 并发执行::
* 网络和进程间通信::
* 互联网数据处理::
* 结构化标记处理工具::
* 互联网协议和支持::
* 多媒体服务::
* 國際化::
* 程式框架::
* 以 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 类型::
* 其他内置类型::
* 特殊属性::

数字类型 — int, float, complex

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

迭代器类型

* 生成器类型::

序列类型 — list, tuple, range

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

文本序列类型 — str

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

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

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

映射类型 — dict

* 字典视图对象::

GenericAlias 类型

* 标准的泛型集合类::
* 泛型的特殊属性::

其他内置类型

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

內建的例外

* Exception context::
* 繼承自內建的例外::
* 基类::
* 具体异常::
* 警告::
* 异常层次结构::

具体异常

* OS 异常::

文本處理 (Text Processing) 服務

* 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 — 将字节串解读为打包的二进制数据

* 函数和异常::
* 格式字符串::
* 类::

格式字符串

* 字节顺序，大小和对齐方式::
* 格式字符::
* 示例: 示例<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 --- 堆積佇列 heap queue 演算法. 堆積佇列 (heap queue) 演算法
* bisect: bisect --- 陣列二分演算法 Array bisection algorithm. 陣列二分演算法 (Array bisection algorithm)
* 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 objects::
* Counter 物件::
* deque 对象::
* defaultdict 对象::
* namedtuple() 命名元组的工厂函数: namedtuple 命名元组的工厂函数.
* OrderedDict 对象::
* UserDict 对象::
* UserList 对象::
* UserString 对象::

ChainMap objects

* ChainMap 例子和方法::

deque 对象

* deque 用法::

defaultdict 对象

* defaultdict 例子::

OrderedDict 对象

* OrderedDict 例子和用法::

collections.abc — 容器的抽象基类

* 容器抽象基类::

heapq — 堆積佇列 (heap queue) 演算法

* 基礎範例::
* 優先佇列 (Priority Queue) 實作細節: 優先佇列 Priority Queue 實作細節.
* 原理::

bisect — 陣列二分演算法 (Array bisection algorithm)

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

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 — 操作类似图的结构的功能

* 异常: 异常<2>.

數值與數學模組

* 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 — 數學統計函式

* 平均值與中央位置量數::
* 離度 (spread) 的測量: 離度 spread 的測量.
* 函式細節::
* 异常: 异常<3>.
* 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 对象::
* 行对象::
* 异常: 异常<4>.
* 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 对象::
* 命令行界面: 命令行界面<3>.
* 示例: 示例<12>.
* 受支持的 tar 格式::
* Unicode 问题::

命令行界面

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

檔案格式

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

csv — CSV 文件读写

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

configparser — 配置文件解析器

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

netrc — netrc 文件处理

* netrc 对象::

xdrlib — 编码与解码 XDR 数据

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

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

* 示例: 示例<14>.

加密服务

* hashlib: hashlib --- 安全哈希与消息摘要. 安全哈希与消息摘要
* hmac: hmac --- 基于密钥的消息验证. 基于密钥的消息验证
* secrets: secrets --- 產生用於管理機密的安全亂數. 產生用於管理機密的安全亂數

hashlib — 安全哈希与消息摘要

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

BLAKE2

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

示例

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

secrets — 產生用於管理機密的安全亂數

* 亂數::
* 產生權杖（token）::
* 其他函式::
* 應用技巧和典範實務（best practices）::

產生權杖（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 — 多种操作系统接口

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

文件描述符操作

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

文件和目录

* Linux 扩展属性::

io — 处理流的核心工具

* 總覽::
* 高阶模块接口::
* 类的层次结构::
* 性能: 性能<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>.
* 多线程: 多线程<2>.
* 可重入性::

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 — 日志记录配置

* 配置函数::
* Security considerations::
* 配置字典架构::
* 配置文件格式::

配置字典架构

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

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 Platform::
* 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 — 基于进程的并行

* 簡介: 簡介<8>.
* 参考::
* 编程指导::
* 示例: 示例<17>.

簡介

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

参考

* Process 和异常::
* 管道和队列::
* 杂项: 杂项<3>.
* 连接（Connection）对象::
* 同步原语::
* 共享 ctypes 对象::
* 管理器::
* 代理对象::
* 进程池::
* 监听器及客户端::
* 认证密码::
* 日志::
* 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 模块::
* 安全考量::
* Popen 对象::
* Windows Popen 助手::
* 较旧的高阶 API::
* 使用 subprocess 模块替换旧函数::
* 旧式的 Shell 发起函数::
* 註解::

使用 subprocess 模块

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

Windows Popen 助手

* Windows 常数::

使用 subprocess 模块替换旧函数

* 替代 /bin/sh shell 命令替换::
* 替代 shell 管道::
* 替代 os.system(): 替代 os system.
* 替代 os.spawn 函数族: 替代 os spawn 函数族.
* 替代 os.popen(), os.popen2(), 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 复用库
* asyncore: asyncore --- 异步套接字处理器. 异步套接字处理器
* asynchat: asynchat --- 异步套接字指令/响应处理程序. 异步套接字指令/响应处理程序
* 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<55>.
* macOS: macOS<30>.

Windows

* Windows的子进程支持::

高层级 API 索引

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

低层级 API 索引

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

用 asyncio 开发

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

socket — 底层网络接口

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

模块内容

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

函数

* 创建套接字::
* 其他功能::

关于套接字超时的说明

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

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

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

方法、常量和异常处理

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

证书

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

示例

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

安全考量

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

手动设置

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

select — 等待 I/O 完成

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

selectors — 高级 I/O 复用库

* 簡介: 簡介<9>.
* 类: 类<2>.
* 示例: 示例<25>.

asyncore — 异步套接字处理器

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

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

* asynchat 示例::

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

* 一般规则::
* 模块内容: 模块内容<5>.
* 示例: 示例<26>.
* 对于 SIGPIPE 的说明::

一般规则

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

mmap — 内存映射文件支持

* MADV_* 常量::

互联网数据处理

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

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 编码和解码器

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

标准符合性和互操作性

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

命令行界面

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

mailbox — 操作多种格式的邮箱

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

Mailbox 对象

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

Message 对象

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

mimetypes — 映射文件名到 MIME 类型

* MimeTypes 对象::

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

* 註解: 註解<2>.

结构化标记处理工具

* 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对象::
* 异常: 异常<14>.

xml.dom — 文档对象模型 API

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

DOM 中的对象

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

一致性

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

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浏览器控制器
* cgi: cgi --- 通用网关接口支持. 通用网关接口支持
* cgitb: cgitb --- 用于 CGI 脚本的回溯管理器. 用于 CGI 脚本的回溯管理器
* 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 协议客户端
* nntplib: nntplib --- NNTP 协议客户端. NNTP 协议客户端
* smtplib ---SMTP协议客户端::
* smtpd: smtpd --- SMTP 服务器. SMTP 服务器
* telnetlib: telnetlib -- Telnet 客户端. Telnet 客户端
* 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浏览器控制器

* 浏览器控制器对象::

cgi — 通用网关接口支持

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

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 解析::
* 解析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 示例::

nntplib — NNTP 协议客户端

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

NNTP 对象

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

smtplib —SMTP协议客户端

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

smtpd — SMTP 服务器

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

telnetlib – Telnet 客户端

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

uuid — RFC 4122 定义的UUID对象

* 示例: 示例<35>.

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

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

示例

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

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 对象::
* 日期時間物件::
* 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>.

多媒体服务

* audioop: audioop --- 处理原始音频数据. 处理原始音频数据
* aifc: aifc --- 读写 AIFF 和 AIFC 文件. 读写 AIFF 和 AIFC 文件
* sunau: sunau --- 读写 Sun AU 文件. 读写 Sun AU 文件
* wave: wave --- 读写WAV格式文件. 读写WAV格式文件
* chunk: chunk --- 读取 IFF 分块数据. 读取 IFF 分块数据
* colorsys: colorsys --- 颜色系统间的转换. 颜色系统间的转换
* imghdr: imghdr --- 推测图像类型. 推测图像类型
* sndhdr: sndhdr --- 推测声音文件的类型. 推测声音文件的类型
* ossaudiodev: ossaudiodev --- 访问兼容OSS的音频设备. 访问兼容OSS的音频设备

sunau — 读写 Sun AU 文件

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

wave — 读写WAV格式文件

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

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

* 音频设备对象::
* Mixer Device Objects::

國際化

* 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 — 龜圖學

* 介紹::
* 可用的 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 专有方法, 而非继承自 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<51>.

tkinter — Tcl/Tk的Python接口

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

Tkinter 拾遗

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

快速参考

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

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 风格

* Layouts::

tkinter.tix — TK扩展包

* Using Tix::
* Tix Widgets::
* Tix Commands::

Tix Widgets

* Basic Widgets::
* File Selectors::
* Hierarchical ListBox::
* Tabular ListBox::
* Manager Widgets::
* Image Types::
* Miscellaneous Widgets::
* Form Geometry Manager::

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 --- Utilities for the Python test suite. Utilities for the Python test suite
* test.support.socket_helper: test support socket_helper --- Utilities for socket tests. Utilities for socket tests
* test.support.script_helper: test support script_helper --- Utilities for the Python execution tests. Utilities for the Python execution tests
* test.support.bytecode_helper: test support bytecode_helper --- Support tools for testing correct bytecode generation. Support tools for testing correct bytecode
                                generation

typing — 类型提示支持

* Relevant PEPs::
* 类型别名::
* 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 — 單元測試框架

* 簡單範例::
* 命令執行列介面 (Command-Line Interface): 命令執行列介面 Command-Line Interface.
* Test Discovery（測試探索）::
* 组织你的测试代码::
* 复用已有的测试代码::
* 跳过测试与预计的失败::
* Distinguishing test iterations using subtests::
* 类与函数::
* Class and Module Fixtures::
* 信号处理::

命令執行列介面 (Command-Line Interface)

* 命令列模式選項::

类与函数

* 测试用例::
* Grouping tests::
* Loading and running tests::

测试用例

* Deprecated aliases::

Loading and running tests

* load_tests Protocol::

Class and Module Fixtures

* setUpClass and tearDownClass::
* setUpModule and tearDownModule::

unittest.mock — mock对象库

* 快速上手::
* Mock 类::
* The patchers::
* MagicMock and magic method support::
* Helpers::

Mock 类

* Calling::
* Deleting Attributes::
* Mock names and the name attribute::
* Attaching Mocks as Attributes::

The patchers

* patch::
* patch.object: patch object.
* patch.dict: patch dict.
* patch.multiple: patch multiple.
* patch methods; start and stop: patch methods start and stop.
* patch builtins::
* TEST_PREFIX::
* Nesting Patch Decorators::
* Where to patch::
* Patching Descriptors and Proxy Objects::

MagicMock and magic method support

* Mocking Magic Methods::
* Magic Mock::

Helpers

* sentinel::
* DEFAULT::
* call::
* create_autospec::
* ANY::
* FILTER_DIR::
* mock_open::
* Autospeccing::
* Sealing mocks::

unittest.mock 上手指南

* 使用 mock::
* Patch Decorators::
* Further Examples::

使用 mock

* 模拟方法调用::
* 对象上的方法调用的 mock::
* Mocking Classes::
* Naming your mocks::
* Tracking all Calls::
* Setting Return Values and Attributes::
* Raising exceptions with mocks::
* Side effect functions and iterables::
* Mocking asynchronous iterators::
* Mocking asynchronous context manager::
* Creating a Mock from an Existing Object::

Further Examples

* Mocking chained calls::
* Partial mocking::
* Mocking a Generator Method::
* Applying the same patch to every test method::
* Mocking Unbound Methods::
* Checking multiple calls with mock::
* Coping with mutable arguments::
* Nesting Patches::
* Mocking a dictionary with MagicMock::
* Mock subclasses and their attributes::
* Mocking imports with patch.dict: Mocking imports with patch dict.
* Tracking order of calls and less verbose call assertions::
* More complex argument matching::

2to3 - 自動將 Python 2的程式碼轉成 Python 3

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

test —  Python回归测试包

* Writing Unit Tests for the test package::
* Running tests using the command-line interface::

调试和分析

* 审计事件表::
* bdb: bdb --- Debugger framework. Debugger framework
* 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 接口::
* 命令執行列介面::
* 示例: 示例<40>.

trace — 跟踪Python语句执行

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

命令行用法

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

tracemalloc — 跟踪内存分配

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

示例

* 显示前10项::
* 计算差异::
* Get the traceback of a memory block::
* Pretty top::

Pretty top

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

API

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

軟體封裝與發布

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

ensurepip — Bootstrapping the pip installer

* Command line interface::
* Module API::

venv — 创建虚拟环境

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

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

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

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

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

Python运行时服务

* sys: sys --- 系统相关的参数和函数. 系统相关的参数和函数
* sysconfig: sysconfig --- Provide access to Python's configuration information. Provide access to Python’s configuration information
* 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 — Provide access to Python’s configuration information

* 配置变量::
* 安装路径::
* 其他功能: 其他功能<2>.
* Using sysconfig as a script::

warnings —— 警告信息的控制

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

警告过滤器

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

dataclasses — 数据类

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

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

* 工具::
* 例子和配方::
* Single use, reusable and reentrant context managers: Single use reusable and reentrant context managers.

例子和配方

* Supporting a variable number of context managers::
* Catching exceptions from __enter__ methods::
* Cleaning up in an __enter__ implementation::
* Replacing any use of try-finally and flag variables::
* Using a context manager as a function decorator::

Single use, reusable and reentrant context managers

* Reentrant context managers::
* Reusable context managers::

atexit — 退出处理器

* atexit 示例::

traceback — 打印或检索堆栈回溯

* TracebackException Objects::
* StackSummary Objects::
* FrameSummary Objects::
* Traceback Examples::

inspect — 检查对象

* 类型和成员::
* Retrieving source code::
* Introspecting callables with the Signature object::
* 类与函数: 类与函数<2>.
* The interpreter stack::
* Fetching attributes statically::
* Current State of Generators and Coroutines::
* Code Objects Bit Flags::
* 命令行界面: 命令行界面<5>.

site —— 指定域的配置钩子

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

自定义 Python 解释器

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

code — 解释器基类

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

匯入模組

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

zipimport — 从 Zip 存档中导入模块

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

modulefinder — 查找脚本使用的模块

* ModuleFinder 的示例用法::

importlib — import 的实现

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

示例

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

Using importlib.metadata

* 概述::
* 可用 API::
* Distributions::
* Extending the search algorithm::

可用 API

* Entry points::
* Distribution metadata::
* Distribution versions::
* Distribution files::
* Distribution requirements::

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 --- Byte-compile Python libraries. Byte-compile Python libraries
* dis: dis --- Python bytecode的反組譯器. Python bytecode的反組譯器
* pickletools: pickletools --- pickle 开发者工具集. pickle 开发者工具集

parser — 访问 Python 解析树

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

ast — 抽象语法树

* 抽象文法::
* 节点类::
* ast 中的辅助函数::
* Compiler Flags::
* 命令行用法: 命令行用法<2>.

节点类

* 字面值: 字面值<3>.
* Variables::
* 表达式: 表达式<2>.
* Statements::
* Control flow::
* Function and class definitions::
* Async and await::

表达式

* Subscripting::
* Comprehensions::

Statements

* Imports::

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

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

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

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

pyclbr — Python 模块浏览器支持

* 函式物件::
* Class 对象::

compileall — Byte-compile Python libraries

* Command-line use::
* Public functions::

dis — Python bytecode的反組譯器

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

pickletools — pickle 开发者工具集

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

命令行语法

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

杂项服务

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

formatter — 通用格式化输出

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

Windows系统相关模块

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

msilib — Read and write Microsoft Installer files

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

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

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

winreg — Windows 注册表访问

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

常数

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

访问权限

* 64 位系统特有::

Unix 专有服务

* posix: posix --- 最常见的 POSIX 系统调用. 最常见的 POSIX 系统调用
* pwd: pwd --- 用户密码数据库. 用户密码数据库
* spwd —— shadow 密码库::
* grp: grp --- 组数据库. 组数据库
* crypt —— 检查 Unix 口令的函数::
* termios: termios --- POSIX 风格的 tty 控制. POSIX 风格的 tty 控制
* tty: tty --- 终端控制功能. 终端控制功能
* pty: pty --- 伪终端工具. 伪终端工具
* fcntl —— 系统调用 fcntl 和 ioctl::
* pipes: pipes --- 终端管道接口. 终端管道接口
* resource: resource --- 资源使用信息. 资源使用信息
* nis: nis --- Sun 的 NIS 黄页 接口. Sun 的 NIS (黄页) 接口
* Unix syslog 库例程::

posix — 最常见的 POSIX 系统调用

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

crypt —— 检查 Unix 口令的函数

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

termios — POSIX 风格的 tty 控制

* 示例: 示例<47>.

pty — 伪终端工具

* 示例: 示例<48>.

pipes — 终端管道接口

* 模板对象::

resource — 资源使用信息

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

Unix syslog 库例程

* 示例: 示例<49>.

示例

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

被取代的模块

* optparse: optparse --- 解析器的命令行选项. 解析器的命令行选项
* imp —— 由代码内部访问 import 。::

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::

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

* 示例: 示例<50>.

未创建文档的模块

* 平台特定模块::

擴充和嵌入 Python 直譯器

* 推薦的第三方工具::
* 不使用第三方工具建立擴充::
* 在更大的應用程式中嵌入 CPython 運行環境 (runtime): 在更大的應用程式中嵌入 CPython 運行環境 runtime.

不使用第三方工具建立擴充

* 以 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::

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

* 终结和内存释放::
* 对象展示::
* 属性管理::
* Object Comparison::
* Abstract Protocol Support::
* Weak Reference Support::
* 更多建议::

属性管理

* 泛型属性管理::
* Type-specific Attribute Management::

构建C/C++扩展

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

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

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

在更大的應用程式中嵌入 CPython 運行環境 (runtime)

* 在其它 App 內嵌入 Python::

在其它 App 內嵌入 Python

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

Python/C API 參考手冊

* 簡介: 簡介<12>.
* 稳定的应用程序二进制接口::
* The Very High Level Layer::
* 參照計數::
* 例外處理::
* 工具: 工具<2>.
* 抽象物件層::
* 具体的对象层::
* 初始化，终结和线程::
* Python初始化配置::
* 記憶體管理::
* 对象实现支持::
* API 和 ABI 版本管理::

簡介

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

对象、类型和引用计数

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

引用计数

* 引用计数细节::

例外處理

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

工具

* 作業系統工具::
* 系統函式::
* 行程（Process）控制::
* 匯入模組: 匯入模組<2>.
* 数据 marshal 操作支持::
* 语句解释及变量编译::
* 字串轉換與格式化::
* 反射::
* 编解码器注册与支持功能::

语句解释及变量编译

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

解析参数

* 字符串和缓存区::
* 數字::
* 其他对象::
* API 函数::

编解码器注册与支持功能

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

抽象物件層

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

调用协议

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

Vectorcall 协议

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

缓冲协议

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

缓冲区请求的类型

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

复杂数组

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

具体的对象层

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

基本对象

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

Type 对象

* Creating Heap-Allocated Types::

数值对象

* 整數物件::
* 布林物件::
* 浮點數（Floating Point）物件::
* 复数对象::

复数对象

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

序列对象

* 字节对象::
* 字节数组对象::
* Unicode物件與編碼::
* 元組（Tuple）物件::
* 结构序列对象::
* List（串列）物件::

字节数组对象

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

Unicode物件與編碼

* Unicode对象::
* Built-in Codecs::
* Methods and Slot Functions::

Unicode对象

* Unicode类型::
* Unicode字符属性::
* Creating and accessing Unicode strings::
* Deprecated Py_UNICODE APIs::
* Locale Encoding::
* File System Encoding::
* wchar_t Support::

Built-in Codecs

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

容器对象

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

函式物件

* 函式（Function）物件::
* 實體方法物件::
* 方法对象::
* Cell 物件::
* 代码对象: 代码对象<2>.

其他对象

* 檔案（File）物件::
* 模組物件模組::
* 迭代器（Iterator）物件::
* 修飾器物件::
* 切片物件::
* Ellipsis 对象::
* MemoryView 对象::
* 弱參照物件::
* Capsule 对象::
* 產生器物件::
* 协程对象: 协程对象<2>.
* 上下文变量对象::
* DateTime 物件::
* 类型注解对象::

模組物件模組

* Initializing C modules::
* Module lookup::

Initializing C modules

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

初始化，终结和线程

* 在Python初始化之前::
* 全局配置变量::
* Initializing and finalizing the interpreter::
* Process-wide parameters::
* Thread State and the Global Interpreter Lock::
* Sub-interpreter support::
* 异步通知::
* 分析和跟踪::
* 高级调试器支持::
* Thread Local Storage Support::

Thread State and the Global Interpreter Lock

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

Sub-interpreter support

* 错误和警告::

Thread Local Storage Support

* 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::

記憶體管理

* 總覽: 總覽<2>.
* 原始内存接口::
* 内存接口::
* 对象分配器::
* 默认内存分配器::
* 自定义内存分配器::
* 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 Definition::
* PyObject Slots::
* PyVarObject Slots::
* PyTypeObject Slots::
* Heap Types::

快速参考

* "tp 槽"::
* 子方法槽（方法域）::
* slot typedefs::

發布 Python 模組

* 關鍵術語::
* 開源授權與協同合作::
* 安裝工具::
* 閱讀 Python 封裝使用者指南::
* 我該如何...？: 我該如何 ？.

我該如何...？

* ...為我的專案選擇一個名稱？: 為我的專案選擇一個名稱？.
* ...建立和發布二進制擴充？: 建立和發布二進制擴充？.

安裝 Python 模組

* 關鍵術語: 關鍵術語<2>.
* 基本用法::
* 我該如何...？: 我該如何 ？<2>.
* 常見的安裝問題::

我該如何...？

* ...在 Python 3.4 之前的 Python 版本中安裝 pip？: 在 Python 3 4 之前的 Python 版本中安裝 pip？.
* ...只為目前的使用者安裝套件？: 只為目前的使用者安裝套件？.
* ...安裝科學的 Python 套件？: 安裝科學的 Python 套件？.
* ...平行安裝多個 Python 版本並使用它們？: 平行安裝多個 Python 版本並使用它們？.

常見的安裝問題

* 在 Linux 上安裝套件至系統 Python::
* 未安裝 pip::
* 安裝二進制擴充 (binary extension): 安裝二進制擴充 binary extension.

Python 如何達成任務

* Python 2 的程式碼移植到Python 3::
* 遷移延伸模組到 Python 3::
* 用 Python 进行 Curses 编程::
* 修飾器 HowTo 指南::
* 函式編程 HOWTO::
* 如何使用 Logging 模組::
* 日志操作手册::
* 如何使用正規表達式::
* 套接字编程指南::
* 如何排序::
* Unicode 指南::
* 如何使用urllib套件取得網路資源::
* Argparse 教學::
* ipaddress模組介紹::
* Argument Clinic How-To::
* 使用 DTrace 和 SystemTap 检测CPython::

Python 2 的程式碼移植到Python 3

* 簡短的說明::
* 詳細的::

詳細的

* 向下支援Python 2.6和更舊的版本: 向下支援Python 2 6和更舊的版本.
* 确保你在你的‘‘setup.py‘‘文件中指定适当的版本支持: 确保你在你的``setup py``文件中指定适当的版本支持.
* 有好的測試覆蓋率::
* 瞭解Python 2 & 3的差異::
* 更新你的程式碼::
* 防止兼容性退步::
* 检查哪些依赖性会阻碍你的过渡::
* 更新你的‘‘setup.py‘‘文件以表示对Python 3的兼容: 更新你的``setup py``文件以表示对Python 3的兼容.
* 使用持续集成以保持兼容::
* 考虑使用可选的静态类型检查::

更新你的程式碼

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

用 Python 进行 Curses 编程

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

curses 是什么？

* Python 的 curses 模块::

显示文字

* 属性和颜色::

修飾器 HowTo 指南

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

入门

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

完整的实际例子

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

技术教程

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

纯 Python 等价实现

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

函式編程 HOWTO

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

簡介

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

迭代器

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

生成器

* 向生成器传递值::

itertools 模块

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

functools 模块

* operator 模块::

引用文献

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

如何使用 Logging 模組

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

基礎 Logging 指南

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

进阶日志教程

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

日志级别

* 自定义级别::

日志操作手册

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

通过网络收发日志事件

* Running a logging socket listener in production::

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

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

利用 LoggerAdapter 传递上下文信息

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

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

* concurrent.futures.ProcessPoolExecutor 的用法: concurrent futures ProcessPoolExecutor 的用法.
* Deploying Web applications using Gunicorn and uWSGI::

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

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

理应避免的用法

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

如何使用正規表達式

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

简单模式

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

使用正则表达式

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

更多模式能力

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

修改字符串

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

常见问题

* 使用字符串方法::
* 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套件取得網路資源

* 簡介: 簡介<15>.
* 從URL取得資源::
* 异常的处理::
* info 和 geturl 方法::
* Opener 和 Handler::
* 基本认证::
* 代理::
* 套接字与分层::
* 註解: 註解<3>.

從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 How-To

* The Goals Of Argument Clinic::
* Basic Concepts And Usage::
* Converting Your First Function::
* Advanced Topics::

Advanced Topics

* Symbolic default values::
* Renaming the C functions and variables generated by Argument Clinic::
* Converting functions using PyArg_UnpackTuple::
* Optional Groups::
* Using real Argument Clinic converters, instead of "legacy converters": Using real Argument Clinic converters instead of "legacy converters".
* Py_buffer::
* Advanced converters::
* Parameter default values::
* The NULL default value::
* Expressions specified as default values::
* Using a return converter::
* Cloning existing functions::
* Calling Python code::
* Using a "self converter"::
* Writing a custom converter::
* Writing a custom return converter::
* METH_O and METH_NOARGS::
* tp_new and tp_init functions::
* Changing and redirecting Clinic's output::
* The #ifdef trick::
* Using Argument Clinic in Python files::

使用 DTrace 和 SystemTap 检测CPython

* 启用静态标记::
* 静态DTrace探针::
* 静态SystemTap标记::
* 可用的静态标记::
* SystemTap Tapsets::
* 示例: 示例<52>.

Python 常見問題

* 常見Python問答集::
* 程式開發常見問答集::
* 设计和历史常见问题::
* 函式庫和擴充功能的常見問題::
* 扩展/嵌入常见问题::
* FAQ：在 Windows 使用 Python::
* 圖形化使用者界面常見問答集::
* 為什麼Python被安裝在我的機器上?常見問答集::

常見Python問答集

* 常見資訊::
* Python在真實世界::

常見資訊

* 什麼是Python?::
* 什麼是Python軟體基金會?::
* 當使用Python時有任何版權限制嗎?::
* 為什麼Python被創造出來::
* 什麼是Python擅長的事情::
* Python 版本的编号形式是怎样的？::
* 我如何拿到Python的原始碼::
* 如何取得Python的相關文件::
* 我從來沒寫過程式，有沒有Python的教學::
* 有沒有新手的群組或是郵件群組討論Python::
* 我应如何获取 Python 的公开测试版本？::
* 我应如何为 Python 提交错误报告和补丁？::
* 是否有任何公开发表的 Python 相关文章可以供我参考引用？::
* 有沒有關於Python的書::
* www.python.org 這個非營利組織位於哪裡: www python org 這個非營利組織位於哪裡.
* 為什麼要取名為Python::
* 我需要喜歡蒙提·派森的飛行馬戲團這個節目嗎::

Python在真實世界

* Python穩定性如何::
* 有多少人使用Python::
* 有沒有任何重要的案子使用Python完成開發::
* 對於程式開發者Python對於未來有什麼期待::
* 提议对 Python 加入不兼容的更改是否合理？::
* Python對於入門的程式設計者而言是否為好的程式語言::

程式開發常見問答集

* 常見問題::
* 语言核心内容::
* 数字和字符串::
* 性能: 性能<4>.
* 序列（元组/列表）::
* 对象::
* 模块: 模块<2>.

常見問題

* 是否有可以使用在程式碼階段,具有中斷點,步驟執行等功能的除錯器？: 是否有可以使用在程式碼階段 具有中斷點 步驟執行等功能的除錯器？.
* 有沒有工具能夠幫忙找 bug 或執行靜態分析？::
* 如何由 Python 脚本创建能独立运行的二进制程序？::
* 是否有 Python 编码标准或风格指南？::

语言核心内容

* 為什麼當變數有值時我得到錯誤訊息 UnboundLocalError::
* Python 的區域變數和全域變數有什麼規則？::
* 为什么在循环中定义的参数各异的 lambda 都返回相同的结果？::
* 如何跨模块共享全局变量？::
* 导入模块的“最佳实践”是什么？::
* 为什么对象之间会共享默认值？::
* 如何将可选参数或关键字参数从一个函数传递到另一个函数？::
* 形参和实参之间有什么区别？::
* 为什么修改列表 'y' 也会更改列表 'x'？::
* 如何编写带有输出参数的函数（按照引用调用）？::
* 如何在 Python 中创建高阶函数？::
* 如何复制 Python 对象？::
* 如何找到对象的方法或属性？::
* 如何用代码获取对象的名称？::
* 逗号运算符的优先级是什么？::
* 是否提供等价于 C 语言 "?;" 三目运算符的东西？: 是否提供等价于 C 语言 "? " 三目运算符的东西？.
* 是否可以用 Python 编写让人眼晕的单行程序?::
* 函数形参列表中的斜杠（/）是什么意思？::

数字和字符串

* 如何给出十六进制和八进制整数？::
* 为什么 -22 // 10 会返回 -3 ？::
* How do I get int literal attribute instead of 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 运算符进行对象的身份相等性测试？::
* How can a subclass control what data is stored in an immutable instance?::

模块

* 如何创建 .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在列表和元组的末尾允许使用逗号？::

函式庫和擴充功能的常見問題

* 常見函式問題::
* 一般性的工作::
* 线程相关::
* 输入输出::
* 网络 / Internet 编程::
* 数据库::
* 数学和数字::

常見函式問題

* 如何找到可以用来做 XXX 的模块或应用？::
* 哪裡可以找到math.py (socket.py, regex.py, 等...) 原始檔案: 哪裡可以找到math py socket py regex py 等 原始檔案.
* 我如何使Python script 執行在Unix ?::
* 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中实现（例如通过继承）？::

FAQ：在 Windows 使用 Python

* 在 Windows 作業系統裡我想執行 Python 程式，要怎麼做？::
* 我怎么让 Python 脚本可执行？::
* 为什么有时候 Python 程序会启动缓慢？::
* 我怎样使用 Python 脚本制作可执行文件？::
* *.pyd 文件和 DLL 文件相同吗？: * pyd 文件和 DLL 文件相同吗？.
* 我怎样将 Python 嵌入一个 Windows 程序？::
* 如何让编辑器不要在我的 Python 源代码中插入 tab ？::
* 如何在不阻塞的情况下检查按键？::

圖形化使用者界面常見問答集

* 常見圖形化使用者界面(GUI) 問題: 常見圖形化使用者界面 GUI 問題.
* Python 有哪些 GUI 工具包？::
* 有关Tkinter的问题::

有关Tkinter的问题

* 我怎样“冻结”Tkinter程序？::
* 在等待 I/O 操作时能够处理 Tk 事件吗？::
* 在Tkinter中键绑定不工作：为什么？::

為什麼Python被安裝在我的機器上?常見問答集

* 什麼是Python?: 什麼是Python?<2>.
* 為什麼Python被安裝在我的機器上?::
* 我能夠自行刪除Python嗎?::

關於這些說明文件

* Python 文件的貢獻者們::

處理錯誤 (Bug)

* 說明文件的錯誤::
* 使用 Python 問題追蹤系統::
* 開始讓自己貢獻 Python::

沿革與授權

* 軟體沿革::
* 關於存取或以其他方式使用 Python 的合約條款::
* 被收錄軟體的授權與致謝::

關於存取或以其他方式使用 Python 的合約條款

* 用於 PYTHON 3.9.9 的 PSF 授權合約: 用於 PYTHON 3 9 9 的 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 授權合約.
* 用於 PYTHON 3.9.9 說明文件內程式碼的 ZERO-CLAUSE BSD 授權: 用於 PYTHON 3 9 9 說明文件內程式碼的 ZERO-CLAUSE BSD 授權.

被收錄軟體的授權與致謝

* Mersenne Twister::
* Sockets::
* 非同步 socket 服務::
* Cookie 管理::
* 執行追蹤::
* UUencode 與 UUdecode 函式::
* XML 遠端程序呼叫::
* test_epoll::
* Select kqueue::
* SipHash24::
* strtod 與 dtoa::
* OpenSSL::
* expat::
* libffi::
* zlib: zlib<3>.
* cfuhash::
* libmpdec::
* W3C C14N 測試套件::

發布 Python 模組（舊版）

* Distutils 模块介绍::
* 编写安装脚本::
* 编写设置脚本的配置文件::
* Creating a Source Distribution::
* 创建构建分布::
* Distutils 示例::
* 扩展 Distutils::
* 指令參照::
* API參照::

Distutils 模块介绍

* 概念和术语::
* 一个简单的例子: 一个简单的例子<3>.
* 通用的 Python 术语::
* Distutils 特定的术语::

编写安装脚本

* Listing whole packages::
* Listing individual modules::
* Describing extension modules::
* Relationships between Distributions and Packages::
* Installing Scripts::
* Installing Package Data::
* Installing Additional Files::
* Additional meta-data::
* Debugging the setup script::

Describing extension modules

* 扩展名和软件包::
* Extension source files::
* Preprocessor options::
* Library options::
* 其他选项: 其他选项<2>.

Creating a Source Distribution

* Specifying the files to distribute::
* Manifest-related options::

创建构建分布

* 创建RPM软件包::
* Creating Windows Installers::
* Cross-compiling on Windows::
* Vista User Access Control (UAC): Vista User Access Control UAC.

Cross-compiling on Windows

* The Postinstallation script::

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 模組（舊版）

* 簡介: 簡介<16>.
* Standard Build and Install::
* Alternate Installation::
* 自定义安装::
* Distutils Configuration Files::
* Building Extensions; Tips and Tricks: Building Extensions Tips and Tricks.

簡介

* 基于分布式系统的源代码分发::

Standard Build and Install

* Platform variations::
* Splitting the job up::
* 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.

自定义安装

* Modifying Python's Search Path::

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::



File: python.info,  Node: Python 有什麼新功能？,  Next: Python 教學,  Prev: Top,  Up: Top

1 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 有什么新变化.
* Changelog（更動日誌）::


File: python.info,  Node: Python 3 9 有什么新变化,  Next: Python 3 8 有什么新变化,  Up: Python 有什麼新功能？

1.1 Python 3.9 有什么新变化
===========================


发布版本: 3.9.9


日期: 1月 14, 2022


编者: Łukasz Langa

本文介绍了 Python 3.9 相比 3.8 的新特性。 Python 3.9 发布于 2020 年 10 月
5 日。

详情请参阅 *note 更新日志: 156.。

也參考
......

PEP 596(1) - 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 中的重要变化.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0596


File: python.info,  Node: 摘要 - 发布重点,  Next: 请检查代码中的 DeprecationWarning。,  Up: Python 3 9 有什么新变化

1.1.1 摘要 - 发布重点
---------------------

新的语法特性：

   * PEP 584(1)，为 ‘dict’ 增加合并运算符；

   * PEP 585(2)，标准多项集中的类型标注泛型。

   * PEP 614(3)，放宽对装饰器的语法限制。

新的内置特性：

   * PEP 616(4)，移除前缀和后缀的字符串方法。

标准库中的新特性:

   * PEP 593(5)，灵活函数和变量注解；

   * 添加了 *note os.pidfd_open(): 158. 以允许不带竞争和信号的进程管理。

解释器的改进:

   * PEP 573(6)，从 C 扩展类型的方法快速访问模块状态；

   * PEP 617(7)，CPython 现在使用基于 PEG 的新解析器；

   * 一些 Python 内置类型（range、tuple、set、frozenset、list、dict）现
     已使用 PEP 590(8) vectorcall 加速；

   * 垃圾回收不会因恢复的对象而阻塞；

   * 一些 Python 模块（‘_abc’、*note audioop: c.、‘_bz2’、‘_codecs’、
     ‘_contextvars’、‘_crypt’、‘_functools’、‘_json’、‘_locale’、*note
     math: b1.、*note operator: c2.、*note resource: e0.、*note time:
     10c.、‘_weakref’）现已使用 PEP 489 中定义的多段初始化；

   * 一些标准库模块 (*note audioop: c.、*note ast: 7.、*note grp: 8a.、
     ‘_hashlib’、*note pwd: d6.、‘_posixsubprocess’、*note random: dc.、
     *note select: e5.、*note struct: f8.、*note termios: 104.、*note
     zlib: 14d.) 现已使用 PEP 384 中定义的稳定 ABI。

新的库模块：

   * PEP 615(9)，标准库的 *note zoneinfo: 14e. 模块现已支持 IANA 时区数
     据库；

   * 图的拓扑排序实现现在已由新的 *note graphlib: 89. 模块提供。

发布进程的变化:

   * PEP 602(10)，CPython 采用年度发布周期。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0584

   (2) https://www.python.org/dev/peps/pep-0585

   (3) https://www.python.org/dev/peps/pep-0614

   (4) https://www.python.org/dev/peps/pep-0616

   (5) https://www.python.org/dev/peps/pep-0593

   (6) https://www.python.org/dev/peps/pep-0573

   (7) https://www.python.org/dev/peps/pep-0617

   (8) https://www.python.org/dev/peps/pep-0590

   (9) https://www.python.org/dev/peps/pep-0615

   (10) https://www.python.org/dev/peps/pep-0602


File: python.info,  Node: 请检查代码中的 DeprecationWarning。,  Next: 新的特性,  Prev: 摘要 - 发布重点,  Up: Python 3 9 有什么新变化

1.1.2 请检查代码中的 DeprecationWarning。
-----------------------------------------

Python 2.7 支持未终止时，为了实现向下兼容 Python 2.7，Python 3 保留了许
多旧版功能。Python 2 的支持终止后，已经移除了一部分向下兼容层，剩余部分
很快也会被移除。这几年，大部分兼容层都会触发 *note DeprecationWarning:
15a. 警告。例如，2012 年发布 Python 3.3 后，用 ‘collections.Mapping’ 替
代 ‘collections.abc.Mapping’ 就会触发 *note DeprecationWarning: 15a.。

请用 *note -W: 15b. ‘default’ 命令行选项测试应用程序来查看 *note
DeprecationWarning: 15a. 和 *note PendingDeprecationWarning: 15c.，甚至
可以用 *note -W: 15b. ‘error’ 将它们视为错误。 可以用 *note 警告过滤器:
15d. 忽略来自第三方代码的警告。

Python 3.9 是最后一个提供 Python 2 向下兼容层的版本，以给予 Python 项目
维护者更多时间移除 Python 2 支持，添加 Python 3.9 支持。

*note collections: 1d. 模块中 *note 抽象基类: 15e. 的别名，例如 *note
collections.abc.Mapping: 15f. 的别名 ‘collections.Mapping’ 会为向下兼容
最后保留一个发行版。 这些内容将在 Python 3.10 中移除。

更通俗的说法是，请在 *note Python 开发模式: 160. 下运行测试，这样做有助
于让代码兼容 Python 的后续版本。

注：一些前期已弃用的内容也将在此 Python 版本中移除。 详见 *note 移除:
161. 一节。


File: python.info,  Node: 新的特性,  Next: 其他语言特性修改,  Prev: 请检查代码中的 DeprecationWarning。,  Up: Python 3 9 有什么新变化

1.1.3 新的特性
--------------

* Menu:

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


File: python.info,  Node: 字典合并与更新运算符,  Next: 新增用于移除前缀和后缀的字符串方法,  Up: 新的特性

1.1.3.1 字典合并与更新运算符
............................

合并 (‘|’) 与更新 (‘|=’) 运算符已被加入内置的 *note dict: 164. 类。 它们
为现有的 ‘dict.update’ 和 ‘{**d1, **d2}’ 字典合并方法提供了补充。

示例:

     >>> 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'}

详见 PEP 584(1)。（Brandt Bucher 在 bpo-36144(2) 中的贡献。）

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0584

   (2) https://bugs.python.org/issue36144


File: python.info,  Node: 新增用于移除前缀和后缀的字符串方法,  Next: 标准多项集中的类型标注泛型,  Prev: 字典合并与更新运算符,  Up: 新的特性

1.1.3.2 新增用于移除前缀和后缀的字符串方法
..........................................

增加了 *note str.removeprefix(prefix): 166. 和 *note
str.removesuffix(suffix): 167. 用于方便地从字符串移除不需要的前缀或后缀
。 也增加了 ‘bytes’, ‘bytearray’ 以及 ‘collections.UserString’ 的对应方
法。 请参阅 PEP 616(1) 了解详情。 （由 Dennis Sweeney 在 bpo-39939(2) 中
贡献。）

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0616

   (2) https://bugs.python.org/issue39939


File: python.info,  Node: 标准多项集中的类型标注泛型,  Next: 新的解析器,  Prev: 新增用于移除前缀和后缀的字符串方法,  Up: 新的特性

1.1.3.3 标准多项集中的类型标注泛型
..................................

在类型标注中现在你可以使用内置多项集类型例如 ‘list’ 和 ‘dict’ 作为通用类
型而不必从 ‘typing’ 导入对应的大写形式类型名 (例如 ‘List’ 和 ‘Dict’)。 标
准库中的其他一些类型现在同样也是通用的，例如 ‘queue.Queue’。

示例:

     def greet_all(names: list[str]) -> None:
         for name in names:
             print("Hello", name)

详见 PEP 585(1)。（由 Guido van Rossum、Ethan Smith 和 Batuhan Taşkaya 在
bpo-39481(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0585

   (2) https://bugs.python.org/issue39481


File: python.info,  Node: 新的解析器,  Prev: 标准多项集中的类型标注泛型,  Up: 新的特性

1.1.3.4 新的解析器
..................

Python 3.9 使用于基于 PEG(1) 的新解析器替代 LL(1)(2)。 新解析器的性能与
旧解析器大致相当，但 PEG 在设计新语言特性时的形式化比 LL(1) 更灵活。 我
们将在 Python 3.10 及之后版本中开始使用这种灵活性。

*note ast: 7. 模块会使用新解析器并会生成与旧解析器一致的 AST。

在 Python 3.10 中，旧解析器将被移除，依赖于它的所有功能也将被移除（主要
是 *note parser: c7. 模块，它早已被弃用）。 `只有' 在 Python 3.9 中，你
可以使用命令行开关 (‘-X oldparser’) 或环境变量 (‘PYTHONOLDPARSER=1’) 切
换回 LL(1) 解析器。

请参阅 PEP 617(3) 了解详情。 （由 Guido van Rossum, Pablo Galindo 和
Lysandros Nikolaou 在 bpo-40334(4) 中贡献。）

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Parsing_expression_grammar

   (2) https://en.wikipedia.org/wiki/LL_parser

   (3) https://www.python.org/dev/peps/pep-0617

   (4) https://bugs.python.org/issue40334


File: python.info,  Node: 其他语言特性修改,  Next: 新增模块,  Prev: 新的特性,  Up: Python 3 9 有什么新变化

1.1.4 其他语言特性修改
----------------------

   * *note __import__(): 16b. 现在会引发 *note ImportError: 16c. 而不是
     *note ValueError: 16d.，后者曾经会在相对导入超出其最高层级包时发生
     。 （由 Ngalim Siregar 在 bpo-37444(1) 中贡献。）

   * Python 现在会获取命令行中指定的脚本文件名 (例如: ‘python3
     script.py’) 的绝对路径: *note __main__: 1. 模块的 ‘__file__’ 属性将
     是一个绝对路径，而不是相对路径。 现在此路径在当前目录通过 *note
     os.chdir(): 16e. 被改变后仍将保持有效。 作为附带效果，回溯信息也将
     在此情况下为 *note __main__: 1. 模块帧显示绝对路径。 （由 Victor
     Stinner 在 bpo-20443(2) 中贡献。）

   * 在 *note Python 开发模式: 160. 以及调试编译版本中，现在会针对字符串
     编码和解码操作检查 `encoding' 和 `errors' 参数。 例如: *note
     open(): 16f, *note str.encode(): 170. 和 *note bytes.decode():
     171.。

     默认设置下，为保证性能，`errors' 参数只会在第一次发生编码/解码错误
     时被检查，并且对于空字符串 `encoding' 参数有时会被忽略。 （由
     Victor Stinner 在 bpo-37388(3) 中贡献。）

   * ‘"".replace("", s, n)’ 对于所有非零的 ‘n’ 都将返回 ‘s’ 而不是空字符
     串。 现在此方法会与 ‘"".replace("", s)’ 保持一致。 对于 *note
     bytes: 172. 和 *note bytearray: 173. 对象也有类似的修改。 （由
     Serhiy Storchaka 在 bpo-28029(4) 中贡献。）

   * 任何有效的表达式现在都可被用作 *note decorator: 174.。 在之前版本中
     ，相关语法则更为严格。 请参阅 PEP 614(5) 了解详情。 （由 Brandt
     Bucher 在 bpo-39702(6) 中贡献。）

   * 改进了 *note typing: 122. 模块的帮助信息。 现在将为所有特殊形式和特
     殊通用别名 (例如 ‘Union’ 和 ‘List’) 显示文档字符串。 使用 *note
     help(): 175. 时传入通用别名例如 ‘List[int]’ 将显示对应实体类型 (这
     里对应的是 ‘list’) 的帮助信息。 （由 Serhiy Storchaka 在
     bpo-40257(7) 中贡献。）

   * *note aclose(): 176. / *note asend(): 177. / *note athrow(): 178. 的
     并行运行现在已被禁止，且 ‘ag_running’ 现在会反映异步生成器的实际运
     行状态。 （由 Yury Selivanov 在 bpo-30773(8) 中贡献。）

   * 调用 ‘__iter__’ 方法时发生的非预期错误不会再被 *note in: 179. 运算
     符以及 *note operator: c2. 的 *note contains(): 17a, *note
     indexOf(): 17b. 和 *note countOf(): 17c. 中的 ‘TypeError’ 所掩盖。
     （由 Serhiy Storchaka 在 bpo-40824(9) 中贡献。）

   * 未加圆括号的 lambda 表达式不能再作为推导式和生成器表达式的 ‘if’ 子
     句的表达式部分。 请参阅 bpo-41848(10) 和 bpo-43755(11) 了解详情。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37444

   (2) https://bugs.python.org/issue20443

   (3) https://bugs.python.org/issue37388

   (4) https://bugs.python.org/issue28029

   (5) https://www.python.org/dev/peps/pep-0614

   (6) https://bugs.python.org/issue39702

   (7) https://bugs.python.org/issue40257

   (8) https://bugs.python.org/issue30773

   (9) https://bugs.python.org/issue40824

   (10) https://bugs.python.org/issue41848

   (11) https://bugs.python.org/issue43755


File: python.info,  Node: 新增模块,  Next: 改进的模块,  Prev: 其他语言特性修改,  Up: Python 3 9 有什么新变化

1.1.5 新增模块
--------------

* Menu:

* zoneinfo::
* graphlib::


File: python.info,  Node: zoneinfo,  Next: graphlib,  Up: 新增模块

1.1.5.1 zoneinfo
................

*note zoneinfo: 14e. 模块为标准库引入了 IANA 时区数据库。 它添加了 *note
zoneinfo.ZoneInfo: 17f.，这是一个基于系统时区数据的实体 *note
datetime.tzinfo: 180. 实现。

示例:

     >>> 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

作为不包含 IANA 数据库的平台的一个回退数据源，还以第一方软件包的形式发布
了 tzdata(1) 模块 – 通过 PyPI 发行并由 CPython 核心团队维护。

也參考
......

PEP 615(2) – 在标准库中支持 IANA 时区数据库

     PEP 由 Paul Ganssle 撰写并实现

   ---------- Footnotes ----------

   (1) https://pypi.org/project/tzdata/

   (2) https://www.python.org/dev/peps/pep-0615


File: python.info,  Node: graphlib,  Prev: zoneinfo,  Up: 新增模块

1.1.5.2 graphlib
................

添加了新的 *note graphlib: 89. 模块，其中包含 *note
graphlib.TopologicalSorter: 182. 类来提供图的拓扑排序功能。 （由 Pablo
Galindo, Tim Peters 和 Larry Hastings 在 bpo-17005(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17005


File: python.info,  Node: 改进的模块,  Next: 性能优化,  Prev: 新增模块,  Up: Python 3 9 有什么新变化

1.1.6 改进的模块
----------------

* 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::


File: python.info,  Node: ast,  Next: asyncio,  Up: 改进的模块

1.1.6.1 ast
...........

将 `indent' 选项添加到 *note dump(): 185.，这允许它产生多行缩进的输出。
（由 Serhiy Storchaka 在 bpo-37995(1) 中贡献。）

添加了 *note ast.unparse(): 186. 作为 *note ast: 7. 模块中的一个函数，它
可被用来反解析 *note ast.AST: 187. 对象并产生相应的代码字符串，当它被解
析时将会产生一个等价的 *note ast.AST: 187. 对象。 （由 Pablo Galindo 和
Batuhan Taskaya 在 bpo-38870(2) 中贡献。）

为 AST 节点添加了文档字符串，其中包含 ASDL 签名，可被用来构造对应的节点
。 （由 Batuhan Taskaya 在 bpo-39638(3) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37995

   (2) https://bugs.python.org/issue38870

   (3) https://bugs.python.org/issue39638


File: python.info,  Node: asyncio,  Next: compileall,  Prev: ast,  Up: 改进的模块

1.1.6.2 asyncio
...............

出于重要的安全性考量，*note asyncio.loop.create_datagram_endpoint():
189. 的 `reuse_address' 形参不再被支持。 这是由 UDP 中的套接字选项
‘SO_REUSEADDR’ 的行为导致的。 更多细节请参阅
‘loop.create_datagram_endpoint()’ 的文档。 （由 Kyle Stanley, Antoine
Pitrou 和 Yury Selivanov 在 bpo-37228(1) 中贡献。。）

添加了新的 *note coroutine: 18a. *note shutdown_default_executor():
18b.，它可为等待 *note ThreadPoolExecutor: 18c. 结束关闭的默认执行器安排
关闭日程操作。 此外，*note asyncio.run(): 18d. 已被更新以使用新的 *note
coroutine: 18a.。 （由 Kyle Stanley 在 bpo-34037(2) 中贡献。）

添加了 *note asyncio.PidfdChildWatcher: 18e.，这是一个 Linux 专属的子监
视器实现，它负责轮询进程的文件描述符。 (bpo-38692(3))

添加了新的 *note coroutine: 18a. *note asyncio.to_thread(): 18f.。 它主
要被用于在单独线程中运行 IO 密集型函数以避免阻塞事件循环，实质上就相当于
是 *note run_in_executor(): 190. 的高层级版本，可直接接受关键字参数。 （
由 Kyle Stanley 和 Yury Selivanov 在 bpo-32309(4) 中贡献。）

当由于超时而取消任务时，*note asyncio.wait_for(): 191. 现在将会等待直到
也在 `timeout' 值 <= 0 的情况下完成取消。 就像 timeout 值为正数时一样。
（由 Elvis Pranskevichus 在 bpo-32751(5) 中贡献。）

当附带 *note ssl.SSLSocket: 192. 套接字调用不兼容的方法时 *note asyncio:
9. 现在会引发 ‘TyperError’。 （由 Ido Michael 在 bpo-37404(6) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37228

   (2) https://bugs.python.org/issue34037

   (3) https://bugs.python.org/issue38692

   (4) https://bugs.python.org/issue32309

   (5) https://bugs.python.org/issue32751

   (6) https://bugs.python.org/issue37404


File: python.info,  Node: compileall,  Next: concurrent futures,  Prev: asyncio,  Up: 改进的模块

1.1.6.3 compileall
..................

为重复的 ‘.pyc’ 文件添加了使用硬软件的可能性: `hardlink_dupes' 形参以及
–hardlink-dupes 命令行选项。 （由 Lumír ’Frenzy’ Balhar 在 bpo-40495(1)
中贡献。）

新增了一些用于在结果 ‘.pyc’ 文件中操纵路径的选项: `stripdir',
`prependdir', `limit_sl_dest' 形参以及 -s, -p, -e 命令行选项。 并使得为
优化等级多次指定选项成为可能。 （由 Lumír ’Frenzy’ Balhar 在
bpo-38112(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40495

   (2) https://bugs.python.org/issue38112


File: python.info,  Node: concurrent futures,  Next: curses,  Prev: compileall,  Up: 改进的模块

1.1.6.4 concurrent.futures
..........................

将新的 `cancel_futures' 形参添加到 *note
concurrent.futures.Executor.shutdown(): 195.，可以取消尚未开始运行的所有
挂起的 Future，而不必等待它们完成运行再关闭执行器。 （由 Kyle Stanley 在
bpo-39349(1) 中贡献。）

从 *note ThreadPoolExecutor: 18c. 和 *note ProcessPoolExecutor: 196. 中
移除了守护线程。 这改善与与子解释器的兼容性及它们在关闭进程时的可预测性
。 （由 Kyle Stanley 在 bpo-39812(2) 中贡献。）

现在 *note ProcessPoolExecutor: 196. 中的工作进程仅会在没有可重用的空闲
工作进程时按需产生。 这优化了启动开销并减少了由空闲工作进程导致的 CPU 时
间损失。 （由 Kyle Stanley 在 bpo-39207(3) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39349

   (2) https://bugs.python.org/issue39812

   (3) https://bugs.python.org/issue39207


File: python.info,  Node: curses,  Next: datetime,  Prev: concurrent futures,  Up: 改进的模块

1.1.6.5 curses
..............

增加了 *note curses.get_escdelay(): 198, *note curses.set_escdelay():
199, *note curses.get_tabsize(): 19a. 以及 *note curses.set_tabsize():
19b. 函数。（由 Anthony Sottile 在 bpo-38312(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38312


File: python.info,  Node: datetime,  Next: distutils,  Prev: curses,  Up: 改进的模块

1.1.6.6 datetime
................

*note datetime.date: 19d. 的 *note isocalendar(): 19e. 以及 *note
datetime.datetime: 19f. 的 *note isocalendar(): 1a0. 等方法现在将返回
*note namedtuple(): 1a1. 而不是 *note tuple: 1a2.。 （由 Dong-hee Na 在
bpo-24416(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24416


File: python.info,  Node: distutils,  Next: fcntl,  Prev: datetime,  Up: 改进的模块

1.1.6.7 distutils
.................

‘upload’ 命令现在会创建 SHA2-256 和 Blake2b-256 哈希摘要。 它会在禁用
MD5 摘要的平台上跳过 MD5。 （由 Christian Heimes 在 bpo-40698(1) 中贡献
。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40698


File: python.info,  Node: fcntl,  Next: ftplib,  Prev: distutils,  Up: 改进的模块

1.1.6.8 fcntl
.............

增加了 ‘F_OFD_GETLK’, ‘F_OFD_SETLK’ 和 ‘F_OFD_SETLKW’ 等常量。 （由
Dong-hee Na 在 bpo-38602(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38602


File: python.info,  Node: ftplib,  Next: gc,  Prev: fcntl,  Up: 改进的模块

1.1.6.9 ftplib
..............

现在 *note FTP: 1a6. 和 *note FTP_TLS: 1a7. 当它们的构造器所给定的超时参
数为零以防止创建非阻塞套接字时会引发 *note ValueError: 16d.。 （由
Dong-hee Na 在 bpo-39259(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39259


File: python.info,  Node: gc,  Next: hashlib,  Prev: ftplib,  Up: 改进的模块

1.1.6.10 gc
...........

当垃圾回收器进行某些复活对象的收集时（在终结器被执行之后这些对象可以在隔
离周期之外被访问），不会阻止对所有仍然无法访问的对象的收集。 （由 Pablo
Galindo 和 Tim Peters 在 bpo-38379(1) 中贡献。）

增加了一个新的函数 *note gc.is_finalized(): 1a9. 用来检测一个对象是否已
被垃圾回收器所终结。 （由 Pablo Galindo 在 bpo-39322(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38379

   (2) https://bugs.python.org/issue39322


File: python.info,  Node: hashlib,  Next: http,  Prev: gc,  Up: 改进的模块

1.1.6.11 hashlib
................

*note hashlib: 8c. 模块现在会在可能的情况下使用 OpenSSL 中的 SHA3 哈希和
SHAKE XOF。 （由 Christian Heimes 在 bpo-37630(1) 中贡献。）

内置的哈希模块现在可通过 ‘./configure --without-builtin-hashlib-hashes’
禁用或通过 ‘./configure --with-builtin-hashlib-hashes=sha3,blake2’ 这样
的形式有选择地启用以强制使用基于 OpenSSL 的实现。 （由 Christian Heimes
在 bpo-40479(2) 中贡献）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37630

   (2) https://bugs.python.org/issue40479


File: python.info,  Node: http,  Next: IDLE 与 idlelib,  Prev: hashlib,  Up: 改进的模块

1.1.6.12 http
.............

添加 HTTP 状态码 ‘103 EARLY_HINTS’, ‘418 IM_A_TEAPOT’ 和 ‘425 TOO_EARLY’
到 *note http.HTTPStatus: 1ac.。 （由 Dong-hee Na 在 bpo-39509(1) 以及
Ross Rhodes 在 bpo-39507(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39509

   (2) https://bugs.python.org/issue39507


File: python.info,  Node: IDLE 与 idlelib,  Next: imaplib,  Prev: http,  Up: 改进的模块

1.1.6.13 IDLE 与 idlelib
........................

添加了切换光标闪烁停止的选项。 （由 Zackery Spytz 在 bpo-4603(1) 中贡献
。）

Esc 键现在会关闭 IDLE 补全提示窗口。 （由 Johnny Najera 在 bpo-38944(2)
中贡献。）

添加关键字到模块名称补全列表。 （由 Terry J. Reedy 在 bpo-37765(3) 中贡
献。）

上述修改已被反向移植到 3.8 维护发行版中。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue4603

   (2) https://bugs.python.org/issue38944

   (3) https://bugs.python.org/issue37765


File: python.info,  Node: imaplib,  Next: importlib,  Prev: IDLE 与 idlelib,  Up: 改进的模块

1.1.6.14 imaplib
................

现在 *note IMAP4: 1af. 和 *note IMAP4_SSL: 1b0. 的构造器具有可选的
`timeout' 形参。 并且，现在 *note open(): 1b1. 方法也具有可选的
`timeout' 形参提供同样的修改。 *note IMAP4_SSL: 1b0. 和 *note
IMAP4_stream: 1b2. 中被重载的方法也应用了这个修改。 （由 Dong-hee Na 在
bpo-38615(1) 中贡献。）

增加了 *note imaplib.IMAP4.unselect(): 1b3.。 *note
imaplib.IMAP4.unselect(): 1b3. 会释放关联到选定邮箱的服务器资源并将服务
器返回到已认证状态。 此命令会执行与 *note imaplib.IMAP4.close(): 1b4. 相
同的动作，区别在于它不会从当前选定邮箱中永久性地移除消息。 （由 Dong-hee
Na 在 bpo-40375(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38615

   (2) https://bugs.python.org/issue40375


File: python.info,  Node: importlib,  Next: inspect,  Prev: imaplib,  Up: 改进的模块

1.1.6.15 importlib
..................

为提升与 import 语句的一致性，现在 *note importlib.util.resolve_name():
1b6. 对于无效的相对导入尝试会引发 *note ImportError: 16c. 而不是 *note
ValueError: 16d.。 （由 Ngalim Siregar 在 bpo-37444(1) 中贡献。）

发布不可变模块对象的导入加载器除了发布单独模块以外现在也可以发布不可变包
。 （由 Dino Viehland 在 bpo-39336(2) 中贡献。）

添加了带有对包数据中子目录支持的 *note importlib.resources.files(): 1b7.
函数，与 ‘importlib_resources’ 1.5 版的反向端口相匹配。（由 Jason R.
Coombs 在 bpo-39791(3) 中贡献。）

来自 ‘importlib_metadata’ 1.6.1 版的已更新 ‘importlib.metadata’。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37444

   (2) https://bugs.python.org/issue39336

   (3) https://bugs.python.org/issue39791


File: python.info,  Node: inspect,  Next: ipaddress,  Prev: importlib,  Up: 改进的模块

1.1.6.16 inspect
................

*note inspect.BoundArguments.arguments: 1b9. 已从 ‘OrderedDict’ 改为常规
字典。 （由 Inada Naoki 在 bpo-36350(1) 和 bpo-39775(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36350

   (2) https://bugs.python.org/issue39775


File: python.info,  Node: ipaddress,  Next: math,  Prev: inspect,  Up: 改进的模块

1.1.6.17 ipaddress
..................

*note ipaddress: a2. 现在支持 IPv6 作用域地址（即带有 ‘%<scope_id>’ 前缀
的 IPv6 地址）。

IPv6 作用域地址可使用 *note ipaddress.IPv6Address: 1bb. 来解析。 作用域
的区 ID 如果存在，可通过 *note scope_id: 1bc. 属性来获取。 （由
Oleksandr Pavliuk 在 bpo-34788(1) 中贡献。）

从 Python 3.9.5 开始 *note ipaddress: a2. 模块不再接受 IPv4 地址字符串中
有任何前缀的零。 （由 Christian Heimes 在 bpo-36384(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue34788

   (2) https://bugs.python.org/issue36384


File: python.info,  Node: math,  Next: multiprocessing,  Prev: ipaddress,  Up: 改进的模块

1.1.6.18 math
.............

对 *note math.gcd(): 1be. 函数进行了扩展以处理多个参数。 在之前版本中，
它只支持两个参数。 （由 Serhiy Storchaka 在 bpo-39648(1) 中贡献。）

增加了 *note math.lcm(): 1bf.: 返回指定参数的最小公倍数。 （由 Mark
Dickinson, Ananthakrishnan 和 Serhiy Storchaka 在 bpo-39479(2) 和
bpo-39648(3) 中贡献。）

增加了 *note math.nextafter(): 1c0.: 返回从 `x' 往 `y' 方向的下一个浮点
数值。 （由 Victor Stinner 在 bpo-39288(4) 中贡献。）

增加了 *note math.ulp(): 1c1.: 返回一个浮点数的最小有效比特位。 （由
Victor Stinner 在 bpo-39310(5) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39648

   (2) https://bugs.python.org/issue39479

   (3) https://bugs.python.org/issue39648

   (4) https://bugs.python.org/issue39288

   (5) https://bugs.python.org/issue39310


File: python.info,  Node: multiprocessing,  Next: nntplib,  Prev: math,  Up: 改进的模块

1.1.6.19 multiprocessing
........................

*note multiprocessing.SimpleQueue: 1c3. 类新增了 *note close(): 1c4. 方
法用来显式地关闭队列。 （由 Victor Stinner 在 bpo-30966(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30966


File: python.info,  Node: nntplib,  Next: os,  Prev: multiprocessing,  Up: 改进的模块

1.1.6.20 nntplib
................

现在 *note NNTP: 1c6. 和 *note NNTP_SSL: 1c7. 当它们的构造器所给定的超时
参数为零以防止创建非阻塞套接字时会引发 *note ValueError: 16d.。 （由
Dong-hee Na 在 bpo-39259(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39259


File: python.info,  Node: os,  Next: pathlib,  Prev: nntplib,  Up: 改进的模块

1.1.6.21 os
...........

增加了 *note CLD_KILLED: 1c9. 和 *note CLD_STOPPED: 1ca. 作为 ‘si_code’。
（由 Dong-hee Na 在 bpo-38493(1) 中贡献。）

对外公开了 Linux 专属的 *note os.pidfd_open(): 158. (bpo-38692(2)) 和
*note os.P_PIDFD: 1cb. (bpo-38713(3)) 用于文件描述符的进程管理。

现在 *note os.unsetenv(): 1cc. 函数在 Windows 上也已可用。 （由 Victor
Stinner 在 bpo-39413(4) 中贡献。）

现在 *note os.putenv(): 1cd. 和 *note os.unsetenv(): 1cc. 函数将总是可用
。 （由 Victor Stinner 在 bpo-39395(5) 中贡献。）

增加了 *note os.waitstatus_to_exitcode(): 1ce. 函数：将等待状态转换为退
出码。 （由 Victor Stinner 在 bpo-40094(6) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38493

   (2) https://bugs.python.org/issue38692

   (3) https://bugs.python.org/issue38713

   (4) https://bugs.python.org/issue39413

   (5) https://bugs.python.org/issue39395

   (6) https://bugs.python.org/issue40094


File: python.info,  Node: pathlib,  Next: pdb,  Prev: os,  Up: 改进的模块

1.1.6.22 pathlib
................

增加了 *note pathlib.Path.readlink(): 1d0.，其行为类似于 *note
os.readlink(): 1d1.。 （由 Girts Folkmanis 在 bpo-30618(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30618


File: python.info,  Node: pdb,  Next: poplib,  Prev: pathlib,  Up: 改进的模块

1.1.6.23 pdb
............

在 Windows 上 *note Pdb: 1d3. 现在支持 ‘~/.pdbrc’。 （由 Tim Hopper 和
Dan Lidral-Porter 在 bpo-20523(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20523


File: python.info,  Node: poplib,  Next: pprint,  Prev: pdb,  Up: 改进的模块

1.1.6.24 poplib
...............

现在 *note POP3: 1d5. 和 *note POP3_SSL: 1d6. 当它们的构造器所给定的超时
参数为零以防止创建非阻塞套接字时会引发 *note ValueError: 16d.。 （由
Dong-hee Na 在 bpo-39259(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39259


File: python.info,  Node: pprint,  Next: pydoc,  Prev: poplib,  Up: 改进的模块

1.1.6.25 pprint
...............

现在 *note pprint: d2. 能美化打印 *note types.SimpleNamespace: 1d8.。 （
由 Carl Bordum Hansen 在 bpo-37376(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37376


File: python.info,  Node: pydoc,  Next: random,  Prev: pprint,  Up: 改进的模块

1.1.6.26 pydoc
..............

文档字符串的显示现在不仅针对类、函数、方法等，也针对任何具有自己的
‘__doc__’ 属性的对象。 （由 Serhiy Storchaka 在 bpo-40257(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40257


File: python.info,  Node: random,  Next: signal,  Prev: pydoc,  Up: 改进的模块

1.1.6.27 random
...............

增加了新的 ‘random.Random.randbytes’ 方法：生成随机字节串。 （由 Victor
Stinner 在 bpo-40286(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40286


File: python.info,  Node: signal,  Next: smtplib,  Prev: random,  Up: 改进的模块

1.1.6.28 signal
...............

对外公开了 Linux 专属的 *note signal.pidfd_send_signal(): 1dc. 用于向使
用文件描述符而非 pid 的进程发送信号。 (bpo-38712(1))

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38712


File: python.info,  Node: smtplib,  Next: socket,  Prev: signal,  Up: 改进的模块

1.1.6.29 smtplib
................

现在 *note SMTP: 1de. 和 *note SMTP_SSL: 1df. 当它们的构造器所给定的超时
参数为零以防止创建非阻塞套接字时会引发 *note ValueError: 16d.。 （由
Dong-hee Na 在 bpo-39259(1) 中贡献。）

现在 *note LMTP: 1e0. 构造器具有可选的 `timeout' 形参。 （由 Dong-hee Na
在 bpo-39329(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39259

   (2) https://bugs.python.org/issue39329


File: python.info,  Node: socket,  Next: time,  Prev: smtplib,  Up: 改进的模块

1.1.6.30 socket
...............

*note socket: ef. 模块现在会在 Linux 4.1 或更高版本上导出 *note
CAN_RAW_JOIN_FILTERS: 1e2. 常量。 （由 Stefan Tatschner 和 Zackery Spytz
在 bpo-25780(1) 中贡献。）

现在 socket 模块会在支持的平台上支持 *note CAN_J1939: 1e3. 协议。 （由
Karl Ding 在 bpo-40291(2) 上贡献。）

现在 socket 模块具有 *note socket.send_fds(): 1e4. 和 *note
socket.recv_fds(): 1e5. 函数。 （由 Joannah Nanjekye, Shinya Okano 和
Victor Stinner 在 bpo-28724(3) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25780

   (2) https://bugs.python.org/issue40291

   (3) https://bugs.python.org/issue28724


File: python.info,  Node: time,  Next: sys,  Prev: socket,  Up: 改进的模块

1.1.6.31 time
.............

在 AIX 上，现在 *note thread_time(): 1e7. 是使用具有纳秒级精度的
‘thread_cputime()’ 实现，而不再是只有 10 毫秒精度的
‘clock_gettime(CLOCK_THREAD_CPUTIME_ID)’。 （由 Batuhan Taskaya 在
bpo-40192(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40192


File: python.info,  Node: sys,  Next: tracemalloc,  Prev: time,  Up: 改进的模块

1.1.6.32 sys
............

增加了新的 *note sys.platlibdir: 1e9. 属性：平台专属库目录的名称。 它被
用于构建标准库的路径以及已安装扩展模块的路径。 它在大多数平台上等于
‘"lib"’。 在 Fedora 和 SuSE 上，它等于 64 位平台上的 ‘"lib64"’。 （由
Jan Matějek, Matěj Cepl, Charalampos Stratakis 和 Victor Stinner 在
bpo-1294959(1) 中贡献。）

之前的版本中，*note sys.stderr: 1ea. 在非交互模式时是带块缓冲的。 现在
‘stderr’ 默认总是为行缓冲的。 （由 Jendrik Seipp 在 bpo-13601(2) 中贡献
。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1294959

   (2) https://bugs.python.org/issue13601


File: python.info,  Node: tracemalloc,  Next: typing,  Prev: sys,  Up: 改进的模块

1.1.6.33 tracemalloc
....................

增加了 *note tracemalloc.reset_peak(): 1ec. 用于将跟踪的内存块峰值大小设
为当前大小，以测量特定代码段的峰值。 （由 Huon Wilson 在 bpo-40630(1) 中
贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40630


File: python.info,  Node: typing,  Next: unicodedata,  Prev: tracemalloc,  Up: 改进的模块

1.1.6.34 typing
...............

PEP 593(1) 引入了一种 *note typing.Annotated: 1ee. 类型以使用上下文专属
的元数据来装饰现有类型，并将新的 ‘include_extras’ 形参添加到 *note
typing.get_type_hints(): 1ef. 以在运行时访问元数据。 （由 Till Varoquaux
和 Konstantin Kashin 贡献。）

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0593


File: python.info,  Node: unicodedata,  Next: venv,  Prev: typing,  Up: 改进的模块

1.1.6.35 unicodedata
....................

Unicode 数据库已更新到 13.0.0 版。 (bpo-39926(1))。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39926


File: python.info,  Node: venv,  Next: xml,  Prev: unicodedata,  Up: 改进的模块

1.1.6.36 venv
.............

由 *note venv: 12e. 所提供的激活脚本现在总是会使用 ‘__VENV_PROMPT__’ 设
置的值来一致地指明它们的自定义提示符。 在之前版本中某些脚本会无条件地使
用 ‘__VENV_PROMPT__’，而另一些脚本只在其恰好被设置时（这是默认情况）才会
使用，还有的脚本会改用 ‘__VENV_NAME__’。 （由 Brett Cannon 在
bpo-37663(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37663


File: python.info,  Node: xml,  Prev: venv,  Up: 改进的模块

1.1.6.37 xml
............

当把 *note xml.etree.ElementTree: 140. 序列化为 XML 文件时属性内部的空白
字符现在将被保留。 不同的行结束符不会再被正规化为 "n"。 这是对于如何解读
XML 规范 2.11 节的相关讨论的最终结果。 （由 Mefistotelis 在 bpo-39011(1)
中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39011


File: python.info,  Node: 性能优化,  Next: 弃用,  Prev: 改进的模块,  Up: Python 3 9 有什么新变化

1.1.7 性能优化
--------------

   * 优化了在推导式中为临时变量赋值的惯用方式。 现在推导式中的 ‘for y in
     [expr]’ 会与简单赋值语句 ‘y = expr’ 一样快速。 例如:

          sums = [s for s in [0] for x in data for s in [s + x]]

     不同于 ‘:=’ 运算符，这个惯用方式不会使变量泄露到外部作用域中。

     （由 Serhiy Storchaka 在 bpo-32856(1) 中贡献。）

   * 优化了多线程应用中的信号处理。 如果一个线程不是获得信号的主线程，字
     节码求值循环不会在每条字节码指令上被打断以检查无法被处理的挂起信号
     。 只有主解释器的主线程能够处理信号。

     在之前版本中，字节码求值循环会在每条指令上被打断直到主线程处理了信
     号。 （由 Victor Stinner 在 bpo-40010(2) 上贡献。）

   * 在 FreeBSD 上使用 ‘closefrom()’ 优化了 *note subprocess: f9. 模块。
     （由 Ed Maste, Conrad Meyer, Kyle Evans, Kubilay Kocak 和 Victor
     Stinner 在 bpo-38061(3) 中贡献。）

   * *note PyLong_FromDouble(): 1f4. 对于匹配 ‘long’ 的值执行速度现在加
     快了 1.87 倍。 （由 Sergey Fedoseev d bpo-37986(4) 中贡献。）

   * 多个 Python 内置类型 (*note range: 1f5, *note tuple: 1a2, *note
     set: 1f6, *note frozenset: 1f7, *note list: 1f8, *note dict: 164.)
     现在通过使用 PEP 590(5) 向量调用协议得到加速。 （由 Dong-hee Na,
     Mark Shannon, Jeroen Demeyer 和 Petr Viktorin 在 bpo-37207(6) 中贡
     献。）

   * 当另一集合远大于基础集合的情况下优化了 ‘difference_update()’ 的性能
     。 （由 Evgeny Kapun 提议，由 Michele Orrù 在 bpo-8425(7) 中贡献代
     码。）

   * Python 的小对象分配器 (‘obmalloc.c’) 现在允许（至多）一个空位可用于
     立即重用，而不必将其返回给 OS。 这可以防止简单循环中的多余消耗，在
     每次迭代中可以创建和销毁全新的空位。 （由 Tim Peters 在
     bpo-37257(8) 中贡献。）

   * 浮点数运算中的 *note floor division: 1f9. 现在会有更好的性能。 并且
     此运算的 *note ZeroDivisionError: 1fa. 的消息也已更新。 （由
     Dong-hee Na 在 bpo-39434(9) 中贡献。）

   * 使用 UTF-8 和 ascii 编解码器解码短 ASCII 字符串现在会加快大约 15%。
     （由 Inada Naoki 在 bpo-37348(10) 中贡献。）

以下是对从 Python 3.4 到 Python 3.9 的提升提升情况的总结:

     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

以上结果是由以下变量访问基准测试脚本所生成的:
‘Tools/scripts/var_access_benchmark.py’。 该基准测试脚本以纳秒为单位显示
时间。 基准测试数据是在一块 Intel® Core™ i7-4960HQ 处理器(11) 运行从
python.org(12) 获取的 macOS 64 位编译版本所得到的。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32856

   (2) https://bugs.python.org/issue40010

   (3) https://bugs.python.org/issue38061

   (4) https://bugs.python.org/issue37986

   (5) https://www.python.org/dev/peps/pep-0590

   (6) https://bugs.python.org/issue37207

   (7) https://bugs.python.org/issue8425

   (8) https://bugs.python.org/issue37257

   (9) https://bugs.python.org/issue39434

   (10) https://bugs.python.org/issue37348

   (11) 
https://ark.intel.com/content/www/us/en/ark/products/76088/intel-core-i7-4960hq-processor-6m-cache-up-to-3-80-ghz.html

   (12) https://www.python.org/downloads/mac-osx/


File: python.info,  Node: 弃用,  Next: 移除,  Prev: 性能优化,  Up: Python 3 9 有什么新变化

1.1.8 弃用
----------

   * distutils 的 ‘bdist_msi’ 命令现在已被弃用，请改用 ‘bdist_wheel’
     (wheel 包)。 （由 Hugo van Kemenade 在 bpo-39586(1) 中贡献。）

   * 目前 *note math.factorial(): 1fc. 接受具有非负整数值的 *note float:
     1fd. 实例 (如 ‘5.0’)。 对于非整数和负浮点数它会引发 *note
     ValueError: 16d.。 此行为现在已被弃用。 在未来的 Python 版本中对所
     有浮点数都将引发 *note TypeError: 1fe.。 （由 Serhiy Storchaka 在
     bpo-37315(2) 中贡献。）

   * *note parser: c7. 和 *note symbol: fb. 模块已被弃用并将在未来的
     Python 版本中移除。 对于大多数用例，用户都可以使用 *note ast: 7. 模
     块来控制抽象语法树 (AST) 的生成和编译阶段。

   * 公有 C API 函数 *note PyParser_SimpleParseStringFlags(): 1ff, *note
     PyParser_SimpleParseStringFlagsFilename(): 200, *note
     PyParser_SimpleParseFileFlags(): 201. 和 ‘PyNode_Compile()’ 已被弃
     用并将在 Python 3.10 版与旧解析器一起被移除。

   * 在布尔运算中使用 *note NotImplemented: 202. 已被弃用，因为它几乎必
     定是不正确的富比较运算符实现的结果。 它将在未来的 Python 版本中引发
     *note TypeError: 1fe.。 （由 Josh Rosenberg 在 bpo-35712(3) 中贡献
     。）

   * *note random: dc. 模块目前接受任何可哈希类型作为可能的种子值。 不幸
     的是，某些这样的类型并不保证具有确定性的哈希值。 在 Python 3.9 之后
     ，该模块将限定其种子值为 *note None: 203, *note int: 204, *note
     float: 1fd, *note str: 205, *note bytes: 172. 以及 *note bytearray:
     173.。

   * 打开 *note GzipFile: 206. 文件用于写入而不指定 `mode' 参数的特性已
     被弃用。 在未来的 Python 版本中将总是默认打开用于读取。 在打开文件
     用于写入时请指定 `mode' 参数以静默相关警告信息。 （由 Serhiy
     Storchaka 在 bpo-28286(4) 中贡献。）

   * 弃用了 ‘_tkinter.TkappType’ 的 ‘split()’ 方法而改用 ‘splitlist()’ 方
     法，此方法具有更稳定且可预测的行为。 （由 Serhiy Storchaka 在
     bpo-38371(5) 中贡献。）

   * 将协程对象显式传递给 *note asyncio.wait(): 207. 的做法已被弃用并且
     将在 3.11 版中被移除。 （由 Yury Selivanov 和 Kyle Stanley 在
     bpo-34790(6) 中贡献。）

   * binhex4 和 hexbin4 标准现已被弃用。 *note binhex: 10. 模块和下列
     *note binascii: f. 函数现已被弃用:

        * *note b2a_hqx(): 208, *note a2b_hqx(): 209.

        * *note rlecode_hqx(): 20a, *note rledecode_hqx(): 20b.

     （由 Victor Stinner 在 bpo-39353(7) 中贡献。）

   * *note ast: 7. 类 ‘slice’, ‘Index’ 和 ‘ExtSlice’ 被视为已弃用并将在
     未来的 Python 版本中被移除。 应当使用 ‘value’ 本身而不再是
     ‘Index(value)’。 应当使用 ‘Tuple(slices, Load())’ 而不再是
     ‘ExtSlice(slices)’。 （由 Serhiy Storchaka 在 bpo-34822(8) 中贡献。
     ）

   * *note ast: 7. 类 ‘Suite’, ‘Param’, ‘AugLoad’ 和 ‘AugStore’ 被视为已
     弃用并将在未来的 Python 版本中被移除。 它们不会被解析器所生成且不会
     被 Python 3 中的代码生成器所接受。 （由 Batuhan Taskaya 在
     bpo-39639(9) 和 bpo-39969(10) 中以及 Serhiy Storchaka 在
     bpo-39988(11) 中贡献。）

   * *note PyEval_InitThreads(): 20c. 和 *note
     PyEval_ThreadsInitialized(): 20d. 函数现已被弃用并将在 Python 3.11
     中被移除。 调用 *note PyEval_InitThreads(): 20c. 现在没有任何效果。
     自 Python 3.7 起 *note GIL: 20e. 会由 *note Py_Initialize(): 20f. 初
     始化。 （由 Victor Stinner 在 bpo-39877(12) 中贡献。）

   * 传入 ‘None’ 作为 *note shlex.split(): 210. 函数的第一个参数的做法已
     被弃用。 （由 Zackery Spytz 在 bpo-33262(13) 中贡献。）

   * *note smtpd.MailmanProxy(): 211. 现在已被弃用，因为它在没有外部模块
     ‘mailman’ 的情况下无法使用。 （由 Samuel Colvin 在 bpo-35800(14) 中
     贡献。）

   * 现在 *note lib2to3: a7. 模块将发出 *note PendingDeprecationWarning:
     15c.。 Python 3.9 已切换到 PEG 解析器 (参见 PEP 617(15))，Python
     3.10 可以会包含 lib2to3 的 LL(1) 解析器所不能解析的新语法。
     ‘lib2to3’ 模块可能会在未来的 Python 版本中被移出标准库。 请考虑使用
     第三方替换例如 LibCST(16) 或 parso(17)。 （由 Carl Meyer 在
     bpo-40360(18) 中贡献。）

   * *note random.shuffle(): 212. 的 `random' 形参已被弃用。 （由
     Raymond Hettinger 在 bpo-40465(19) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39586

   (2) https://bugs.python.org/issue37315

   (3) https://bugs.python.org/issue35712

   (4) https://bugs.python.org/issue28286

   (5) https://bugs.python.org/issue38371

   (6) https://bugs.python.org/issue34790

   (7) https://bugs.python.org/issue39353

   (8) https://bugs.python.org/issue34822

   (9) https://bugs.python.org/issue39639

   (10) https://bugs.python.org/issue39969

   (11) https://bugs.python.org/issue39988

   (12) https://bugs.python.org/issue39877

   (13) https://bugs.python.org/issue33262

   (14) https://bugs.python.org/issue35800

   (15) https://www.python.org/dev/peps/pep-0617

   (16) https://libcst.readthedocs.io/

   (17) https://parso.readthedocs.io/

   (18) https://bugs.python.org/issue40360

   (19) https://bugs.python.org/issue40465


File: python.info,  Node: 移除,  Next: 移植到 Python 3 9,  Prev: 弃用,  Up: Python 3 9 有什么新变化

1.1.9 移除
----------

   * ‘unittest.mock.__version__’ 上的错误版本已经被移除。

   * *note nntplib.NNTP: 1c6.: ‘xpath()’ 和 ‘xgtitle()’ 方法已被移除。 这
     些方法自 Python 3.3 起已被弃用。 一般来说，这些扩展都不再为 NNTP 服
     务管理员所支持或启用。 对于 ‘xgtitle()’，请改用 *note
     nntplib.NNTP.descriptions(): 214. 或 *note
     nntplib.NNTP.description(): 215.。 （由 Dong-hee Na 在 bpo-39366(1)
     中贡献。）

   * *note array.array: 216.: ‘tostring()’ 和 ‘fromstring()’ 方法已被移
     除。 它们分别是 ‘tobytes()’ 和 ‘frombytes()’ 的别名，自 Python 3.2
     起已被弃用。 （由 Victor Stinner 在 bpo-38916(2) 中贡献。）

   * 未写入文档的 ‘sys.callstats()’ 函数已被移除。 自 Python 3.7 起它就
     已被弃用并且总是会返回 *note None: 203.。 它需要一个特殊的构建选项
     ‘CALL_PROFILE’ 而该选项在 Python 3.7 中已被移除。 （由 Victor
     Stinner 在 bpo-37414(3) 中贡献。）

   * ‘sys.getcheckinterval()’ 和 ‘sys.setcheckinterval()’ 函数已被移除。
     它们自 Python 3.2 起已被弃用。 请改用 *note
     sys.getswitchinterval(): 217. 和 *note sys.setswitchinterval():
     218.。 （由 Victor Stinner 在 bpo-37392(4) 中贡献。）

   * C 函数 ‘PyImport_Cleanup()’ 已被移除。 它原本的文档为: "清空模块表
     。 仅限内部使用。" （由 Victor Stinner 在 bpo-36710(5) 中贡献。）

   * ‘_dummy_thread’ 和 ‘dummy_threading’ 模块已被移除。 这些模块自
     Python 3.7 起已被弃用，它们需要线程支持。 （由 Victor Stinner 在
     bpo-37312(6) 中贡献。）

   * ‘aifc.open()’ 的别名 ‘aifc.openfp()’，‘sunau.open()’ 的别名
     ‘sunau.openfp()’，以及 *note wave.open(): 219. 的别名
     ‘wave.openfp()’ 已被移除。 它们自 Python 3.7 起已被弃用。 （由
     Victor Stinner 在 bpo-37320(7) 中贡献。）

   * *note threading.Thread: 21a. 的 ‘isAlive()’ 方法已被移除。 它自
     Python 3.8 起已被弃用。 请改用 *note is_alive(): 21b.。 （由
     Dong-hee Na 在 bpo-37804(8) 中贡献。）

   * *note ElementTree: 140. 模块中 *note ElementTree: 21c. 和 *note
     Element: 21d. 等类的 ‘getchildren()’ 和 ‘getiterator()’ 方法已被移
     除。 它们在 Python 3.2 中已被弃用。 请使用 ‘iter(x)’ 或 ‘list(x)’ 替
     代 ‘x.getchildren()’ 并用 ‘x.iter()’ 或 ‘list(x.iter())’ 替代
     ‘x.getiterator()’。 （由 Serhiy Storchaka 在 bpo-36543(9) 中贡献。
     ）

   * 旧的 *note plistlib: cf. API 已被移除，它自 Python 3.4 起已被弃用。
     请使用 *note load(): 21e, *note loads(): 21f, *note dump(): 220. 和
     *note dumps(): 221. 等函数。 此外，`use_builtin_types' 形参已被移除
     而总是会使用 *note bytes: 172. 对象。 （由 Jon Janzen 在
     bpo-36409(10) 中贡献。）

   * C 函数 ‘PyGen_NeedsFinalizing’ 已被移除。 它未被写入文档、未经测试
     ，且自 PEP 442(11) 实现之后未在 CPython 的任何地方被使用。 由
     Joannah Nanjekye 提供补丁。 （由 Joannah Nanjekye 在 bpo-15088(12)
     中贡献。）

   * 自 Python 3.1 起被弃用的别名 ‘base64.encodestring()’ 和
     ‘base64.decodestring()’ 已被移除：请改用 *note
     base64.encodebytes(): 222. 和 *note base64.decodebytes(): 223.。 （
     由 Victor Stinner 在 bpo-39351(13) 中贡献。）

   * ‘fractions.gcd()’ 函数已被移除，它自 Python 3.5 起被弃用
     (bpo-22486(14))：请改用 *note math.gcd(): 1be.。 （由 Victor
     Stinner 在 bpo-39350(15) 中贡献。）

   * *note bz2.BZ2File: 224. 的 `buffering' 形参已被移除。 它自 Python
     3.0 起即被忽略，使用它将会引发 *note DeprecationWarning: 15a.。 请
     传入一个打开文件对象来控制文件的打开方式。 （由 Victor Stinner 在
     bpo-39357(16) 中贡献。）

   * *note json.loads(): 225. 的 `encoding' 形参已被移除。 它在 Python
     3.1 中已被弃用和忽略；自 Python 3.8 起使用它将会引发 *note
     DeprecationWarning: 15a.。 （由 Inada Naoki 在 bpo-39377(17) 中贡献
     。）

   * ‘with (await asyncio.lock):’ 和 ‘with (yield from asyncio.lock):’ 语
     句已不再受支持，请改用 ‘async with lock’。 ‘asyncio.Condition’ 和
     ‘asyncio.Semaphore’ 也同样如此。 （由 Andrew Svetlov 在
     bpo-34793(18) 中贡献。）

   * ‘sys.getcounts()’ 函数，‘-X showalloccount’ 命令行选项以及 C 结构体
     *note PyConfig: 226. 的 ‘show_alloc_count’ 字段已被移除。 它们需要
     使用定义了 ‘COUNT_ALLOCS’ 宏的特殊 Python 编译版本。 （由 Victor
     Stinner 在 bpo-39489(19) 中贡献。）

   * *note typing.NamedTuple: 227. 类的 ‘_field_types’ 属性已被移除。 它
     自 Python 3.8 起已被弃用。 请改用 ‘__annotations__’ 属性。 （由
     Serhiy Storchaka 在 bpo-40182(20) 中贡献。）

   * ‘symtable.SymbolTable.has_exec()’ 方法已被移除。 它自 2006 年起已被
     弃用，当被调用时仅会返回 ‘False’。 （由 Batuhan Taskaya 在
     bpo-40208(21) 中贡献。）

   * ‘asyncio.Task.current_task()’ 和 ‘asyncio.Task.all_tasks()’ 已被移
     除。 它们自 Python 3.7 起已被弃用，你可以改用 *note
     asyncio.current_task(): 228. 和 *note asyncio.all_tasks(): 229.。 （
     由 Rémi Lapeyre 在 bpo-40967(22) 中贡献。）

   * *note html.parser.HTMLParser: 22a. 类的 ‘unescape()’ 方法已被移除（
     它自 Python 3.4 起已被弃用）。 应当使用 *note html.unescape(): 22b.
     来将字符引用转换为对应的 unicode 字符。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39366

   (2) https://bugs.python.org/issue38916

   (3) https://bugs.python.org/issue37414

   (4) https://bugs.python.org/issue37392

   (5) https://bugs.python.org/issue36710

   (6) https://bugs.python.org/issue37312

   (7) https://bugs.python.org/issue37320

   (8) https://bugs.python.org/issue37804

   (9) https://bugs.python.org/issue36543

   (10) https://bugs.python.org/issue36409

   (11) https://www.python.org/dev/peps/pep-0442

   (12) https://bugs.python.org/issue15088

   (13) https://bugs.python.org/issue39351

   (14) https://bugs.python.org/issue22486

   (15) https://bugs.python.org/issue39350

   (16) https://bugs.python.org/issue39357

   (17) https://bugs.python.org/issue39377

   (18) https://bugs.python.org/issue34793

   (19) https://bugs.python.org/issue39489

   (20) https://bugs.python.org/issue40182

   (21) https://bugs.python.org/issue40208

   (22) https://bugs.python.org/issue40967


File: python.info,  Node: 移植到 Python 3 9,  Next: 构建的改变,  Prev: 移除,  Up: Python 3 9 有什么新变化

1.1.10 移植到 Python 3.9
------------------------

本节列出了先前描述的更改以及可能需要更改代码的其他错误修正.

* Menu:

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


File: python.info,  Node: Python API 的变化,  Next: C API 的变化,  Up: 移植到 Python 3 9

1.1.10.1 Python API 的变化
..........................

   * *note __import__(): 16b. 和 *note importlib.util.resolve_name():
     1b6. 现在会引发 *note ImportError: 16c. 取代之前所引发的 *note
     ValueError: 16d.。 捕获特定异常类型并同时支持 Python 3.9 和更早版本
     的调用者将需要使用 ‘except (ImportError, ValueError):’ 来同时捕获两
     者。

   * *note venv: 12e. 激活脚本不再将 ‘__VENV_PROMPT__’ 被设为 ‘""’ 的情
     况作为特例处理。

   * *note select.epoll.unregister(): 22e. 方法不会再忽略 *note EBADF:
     22f. 错误。 （由 Victor Stinner 在 bpo-39239(1) 中贡献。）

   * *note bz2.BZ2File: 224. 的 `compresslevel' 形参已成为仅限关键字形参
     ，因为 `buffering' 形参已被移除。 （由 Victor Stinner 在
     bpo-39357(2) 中贡献。）

   * 简化了 AST 的抽取操作。 简单索引将以它们的值来代表，扩展切片将以元
     组形式来代表。 ‘Index(value)’ 将返回 ‘value’ 本身，
     ‘ExtSlice(slices)’ 将返回 ‘Tuple(slices, Load())’。 （由 Serhiy
     Storchaka 在 bpo-34822(3) 中贡献。）

   * 当使用了 *note -E: 230. 或 *note -I: 231. 命令行参数时 *note
     importlib: 9a. 模块现在会忽略 *note PYTHONCASEOK: 232. 环境变量。

   * `encoding' 形参已作为仅限关键字形参被添加到 *note ftplib.FTP: 1a6.
     和 *note ftplib.FTP_TLS: 1a7. 类，并且默认编码格式由 Latin-1 改为
     UTF-8 以遵循 RFC 2640(4)。

   * *note asyncio.loop.shutdown_default_executor(): 18b. 已被添加到
     *note AbstractEventLoop: 233.，这意味着继承自它的替代事件循环应当定
     义此方法。 （由 Kyle Stanley 在 bpo-34037(5) 中贡献。）

   * 更新了 *note __future__: 0. 模块中未来特性旗标的常量值以防止与编译
     器旗标相冲突。 在之前版本中 ‘PyCF_ALLOW_TOP_LEVEL_AWAIT’ 会与
     ‘CO_FUTURE_DIVISION’ 发生冲突。 （由 Batuhan Taskaya 在
     bpo-39562(6) 中贡献。）

   * ‘array('u')’ 现在使用 ‘wchar_t’ 作为 C 类型而不是 ‘Py_UNICODE’。 这
     个改变不会影响其行为，因为自 Python 3.3 起 ‘Py_UNICODE’ 是
     ‘wchar_t’ 的别名。 （由 Inada Naoki 在 bpo-34538(7) 中贡献。）

   * 现在 *note logging.getLogger(): 234. API 当传入名称 ‘'root'’ 时将返
     回根日志记录器，而在之前它则返回一个名为 ‘'root'’ 的非根日志记录器
     。 这可能会影响到用户代码明确希望使用一个名为 ‘'root'’ 的非根日志记
     录器，或在某个名为 ‘'root.py'’ 的最高层级模块中使用
     ‘logging.getLogger(__name__)’ 来实例化日志记录器的情况。 （由 Vinay
     Sajip 在 bpo-37742(8) 中贡献。）

   * 现在 *note PurePath: 235. 的拆分处理当传入 ‘str’ 或 *note PurePath:
     235. 的实例以外的对象时会返回 ‘NotImplemented’ 而不是引发 *note
     TypeError: 1fe.。 这将允许创建不继承自上述类型的兼容类。 （由 Roger
     Aiudi 在 bpo-34775(9) 中贡献。）

   * 从 Python 3.9.5 开始 *note ipaddress: a2. 模块不再接受 IPv4 地址字
     符串中有任何前缀的零。 前缀的零有歧义且会被某些库解读为八进制数字。
     例如旧版函数 *note socket.inet_aton(): 236. 就瘵前缀的零视为八进制
     数字。 最新 *note inet_pton(): 237. 的 glibc 实现则不接受任何前缀的
     零。 （由 Christian Heimes 在 bpo-36384(10) 中贡献）。

   * *note codecs.lookup(): 238. 现在会以与
     ‘encodings.normalize_encoding()’ 相同的方式正规化编码格式名称，不同
     之处在于 *note codecs.lookup(): 238. 还会将名称转换为小写形式。 例
     如‘‘"latex+latin1"‘‘ 编写格式名称现在会被正规化为 ‘"latex_latin1"’。
     （由 Jordon Xu 在 bpo-37751(11) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39239

   (2) https://bugs.python.org/issue39357

   (3) https://bugs.python.org/issue34822

   (4) https://tools.ietf.org/html/rfc2640.html

   (5) https://bugs.python.org/issue34037

   (6) https://bugs.python.org/issue39562

   (7) https://bugs.python.org/issue34538

   (8) https://bugs.python.org/issue37742

   (9) https://bugs.python.org/issue34775

   (10) https://bugs.python.org/issue36384

   (11) https://bugs.python.org/issue37751


File: python.info,  Node: C API 的变化,  Next: CPython 字节码的改变,  Prev: Python API 的变化,  Up: 移植到 Python 3 9

1.1.10.2 C API 的变化
.....................

   * 堆分配类型的实例（例如使用 *note PyType_FromSpec(): 23a. 和类似 API
     创建的实例）自 Python 3.8 起会带有一个对其类型对象的引用。 正如
     Python 3.8 的 "C API 中的改变" 部分所述，对于大部分情况来说，这应当
     不会有任何副作用，但对于具有自定义 *note tp_traverse: 23b. 函数的类
     型来说，则要确保所有堆分配类型的自定义 ‘tp_traverse’ 函数可访问对象
     的类型。

          示例:

               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
               }

     如果你的遍历函数委托给了基类（或其他类）的 ‘tp_traverse’，则要确保
     ‘Py_TYPE(self)’ 只被访问一次。 请注意应当只有堆类型可访问
     ‘tp_traverse’ 中的类型。

          举例来说，如果你的 ‘tp_traverse’ 函数包括以下内容:

               base->tp_traverse(self, visit, arg)

          则要添加:

               #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

     （参阅 bpo-35810(1) 和 bpo-40217(2) 了解更多信息。）

   * ‘PyEval_CallObject’, ‘PyEval_CallFunction’, ‘PyEval_CallMethod’ 和
     ‘PyEval_CallObjectWithKeywords’ 函数已被弃用。 请改用 *note
     PyObject_Call(): 23c. 及其变化形式。 （详情参见 bpo-29548(3)。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35810

   (2) https://bugs.python.org/issue40217

   (3) https://bugs.python.org/issue29548


File: python.info,  Node: CPython 字节码的改变,  Prev: C API 的变化,  Up: 移植到 Python 3 9

1.1.10.3 CPython 字节码的改变
.............................

   * 添加了 *note LOAD_ASSERTION_ERROR: 23e. 操作码用于处理 *note
     assert: 23f. 语句。 在之前的版本中，如果 *note AssertionError: 240.
     异常被屏蔽则 assert 语句将不能正常运作。 （由 Zackery Spytz 在
     bpo-34880(1) 中贡献。）

   * *note COMPARE_OP: 241. 操作码已被拆分为四个单独指令:

        * ‘COMPARE_OP’ 用于富比较

        * ‘IS_OP’ 用于 ’is’ 和 ’is not’ 检测

        * ‘CONTAINS_OP’ 用于 ’in’ 和 ’not in’ 检测

        * ‘JUMP_IF_NOT_EXC_MATCH’ 用于检查 ’try-except’ 语句中的异常。

     （由 Mark Shannon 在 bpo-39156(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue34880

   (2) https://bugs.python.org/issue39156


File: python.info,  Node: 构建的改变,  Next: C API 的改变,  Prev: 移植到 Python 3 9,  Up: Python 3 9 有什么新变化

1.1.11 构建的改变
-----------------

   * 将 ‘--with-platlibdir’ 选项添加到 ‘configure’ 脚本：平台专属库目录
     的名称，保存在新的 *note sys.platlibdir: 1e9. 属性中。 请参阅 *note
     sys.platlibdir: 1e9. 属性了解详情。 （由 Jan Matějek, Matěj Cepl,
     Charalampos Stratakis 和 Victor Stinner 在 bpo-1294959(1) 中贡献。
     ）

   * ‘COUNT_ALLOCS’ 特殊构建宏已被移除。 （由 Victor Stinner 在
     bpo-39489(2) 中贡献。）

   * 在非 Windows 平台上，现在需要用 ‘setenv()’ 和 ‘unsetenv()’ 函数来构
     建 Python。 （由 Victor Stinner 在 bpo-39395(3) 中贡献。）

   * 在非 Windows 平台上，创建 ‘bdist_wininst’ 安装器现在已不受官方支持
     。 （详情参见 bpo-10945(4)。）

   * 当在 macOS 上用源代码编译 Python 时，‘_tkinter’ 现在会链接到非系统
     的 Tcl 和 Tk 框架，如果它们被安装到 ‘/Library/Frameworks’ 的话，就
     如在较旧的 macOS 发行版上的情况一样。 如果通过使用
     ‘--enable-universalsdk=’ 或 ‘-isysroot’ 明确地配置了 macOS SDK，则
     只会搜索 SDK 本身。 默认行为仍然可以通过 ‘--with-tcltk-includes’ 和
     ‘--with-tcltk-libs’ 来覆盖。 （由 Ned Deily 在 bpo-34956(5) 中贡献
     。）

   * Python 现在可以针对 Windows 10 ARM64 进行编译。 （由 Steve Dower 在
     bpo-33125(6) 中贡献。）

   * 现在当使用 ‘--pgo’ 时一些单独的测试会被跳过。 这些测试显著增加了
     PGO 任务的时间并且可能无助于提升最终可执行文件的优化程度。 这样能使
     任务加速大约 15 倍。 运行完整的单元测试是很慢的。 这个改变可能导致
     优化程序稍差的构建，因为将被执行的代码分支不够多。 如果你愿意等待更
     缓慢的构建，则可以使用 ‘./configure [..] PROFILE_TASK="-m test
     --pgo-extended"’ 来恢复旧版本的行为。 我们不保证哪个 PGO 任务集能产
     生更快的构建。 关心此问题的用户应当自行运行相关基准测试，因为结果可
     能取决于具体环境、工作负载以及编译工具链。 （请参阅 bpo-36044(7) 和
     bpo-37707(8) 了解详情。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1294959

   (2) https://bugs.python.org/issue39489

   (3) https://bugs.python.org/issue39395

   (4) https://bugs.python.org/issue10945

   (5) https://bugs.python.org/issue34956

   (6) https://bugs.python.org/issue33125

   (7) https://bugs.python.org/issue36044

   (8) https://bugs.python.org/issue37707


File: python.info,  Node: C API 的改变,  Next: Python 3 9 1 中的重要变化,  Prev: 构建的改变,  Up: Python 3 9 有什么新变化

1.1.12 C API 的改变
-------------------

* Menu:

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


File: python.info,  Node: 新的特性<2>,  Next: 移植到 Python 3 9<2>,  Up: C API 的改变

1.1.12.1 新的特性
.................

   * PEP 573(1): 添加了 *note PyType_FromModuleAndSpec(): 245. 用于通过
     类来关联一个模块；*note PyType_GetModule(): 246. 和 *note
     PyType_GetModuleState(): 247. 用于获取模块及其状态；以及 *note
     PyCMethod: 248. 和 ‘METH_METHOD’ 用于允许一个方法访问其定义所在的类
     。 （由 Marcel Plch 和 Petr Viktorin 在 bpo-38787(2) 中贡献。）

   * 增加了 *note PyFrame_GetCode(): 249. 函数：获取帧代码。 增加了
     *note PyFrame_GetBack(): 24a. 函数：获取帧的下一个外部帧。 （由
     Victor Stinner 在 bpo-40421(3) 中贡献。）

   * 将 *note PyFrame_GetLineNumber(): 24b. 添加到受限的 C API。 （由
     Victor Stinner 在 bpo-40421(4) 中贡献。）

   * 增加了 *note PyThreadState_GetInterpreter(): 24c. 和 *note
     PyInterpreterState_Get(): 24d. 函数用于获取解释器。 增加了 *note
     PyThreadState_GetFrame(): 24e. 函数用于获取 Python 线程状态的当前帧
     。 增加了 *note PyThreadState_GetID(): 24f. 函数：获取 Python 线程
     状态的唯一标识符。 （由 Victor Stinner 在 bpo-39947(5) 中贡献。）

   * 将新的公有 *note PyObject_CallNoArgs(): 250. 函数添加到 C API，该函
     数可不带任何参数调用一个 Python 可调用对象。 它是不带参数调用
     Python 可调用对象最有效率的方式。 （由 Victor Stinner 在
     bpo-37194(6) 中贡献。）

   * 受限 C API 中的改变（如果定义了 ‘Py_LIMITED_API’ 宏）:

        * 提供 *note Py_EnterRecursiveCall(): 251. 和 *note
          Py_LeaveRecursiveCall(): 252. 作为常规函数用于受限 API。 在之
          前版本中是使用宏定义，但这些宏不能与无法访问
          ‘PyThreadState.recursion_depth’ 字段的受限 C API 一同编译（该
          结构体在受限 C API 中是不透明的）。

        * ‘PyObject_INIT()’ 和 ‘PyObject_INIT_VAR()’ 已成为常规“不透明
          ”函数以隐藏实现细节。

     （由 Victor Stinner 在 bpo-38644(7) 和 bpo-39542(8) 中贡献。）

   * 增加了 *note PyModule_AddType(): 253. 函数以协助将类型加入到模块中
     。 （由 Dong-hee Na 在 bpo-40024(9) 中贡献。）

   * 将 *note PyObject_GC_IsTracked(): 254. 和 *note
     PyObject_GC_IsFinalized(): 255. 函数添加到公有 API 以允许分别查询
     Python 对象当前是正在被追踪还是已经被垃圾回收器所终结。 （由 Pablo
     Galindo Salgado 在 bpo-40241(10) 中贡献。）

   * 增加了 ‘_PyObject_FunctionStr()’ 以获取函数类对象的用户友好的表示形
     式。 （由 Jeroen Demeyer 在 bpo-37645(11) 中修正。）

   * 增加了 *note PyObject_CallOneArg(): 256. 用于调用具有一个位置参数的
     对象（由 Jeroen Demeyer 在 bpo-37483(12) 中修正。）

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0573

   (2) https://bugs.python.org/issue38787

   (3) https://bugs.python.org/issue40421

   (4) https://bugs.python.org/issue40421

   (5) https://bugs.python.org/issue39947

   (6) https://bugs.python.org/issue37194

   (7) https://bugs.python.org/issue38644

   (8) https://bugs.python.org/issue39542

   (9) https://bugs.python.org/issue40024

   (10) https://bugs.python.org/issue40241

   (11) https://bugs.python.org/issue37645

   (12) https://bugs.python.org/issue37483


File: python.info,  Node: 移植到 Python 3 9<2>,  Next: 移除<2>,  Prev: 新的特性<2>,  Up: C API 的改变

1.1.12.2 移植到 Python 3.9
..........................

   * ‘PyInterpreterState.eval_frame’ ( PEP 523(1)) 现在需要有新的强制性
     形参 `tstate' (‘PyThreadState*’)。 （由 Victor Stinner 在
     bpo-38500(2) 中贡献。）

   * 扩展模块: *note PyModuleDef: 258. 的 *note m_traverse: 259, *note
     m_clear: 25a. 和 *note m_free: 25b. 等函数在模块状态被请求但尚未被
     分配时将不会再被调用。 这种情况出现在模块被创建之后且模块被执行
     (*note Py_mod_exec: 25c. 函数) 之前的时刻。 更准确地说，这些函数在
     *note m_size: 25d. 大于 0 并且模块状态（即 *note
     PyModule_GetState(): 25e. 的返回值）为 ‘NULL’ 时将不会被调用。

     没有模块状态的扩展模块 (‘m_size <= 0’) 不会受到影响。

   * 现在如果 *note Py_AddPendingCall(): 25f. 是在子解释器内部被调用，该
     函数会被排入子解释器的调用日程，而不是由主解释器调用。 每个子解释器
     现在都拥有它们自己的调用日程列表。 （由 Victor Stinner 在
     bpo-39984(3) 中贡献。）

   * 当 ‘-E’ 选项被使用 (如果 *note PyConfig.use_environment: 260. 设为
     ‘0’) 时将不再使用 Windows 注册表来初始化 *note sys.path: 261.。 这
     会影响在 Windows 上嵌入 Python 的操作。 （由 Zackery Spytz 在
     bpo-8901(4) 中贡献。）

   * 全局变量 *note PyStructSequence_UnnamedField: 262. 现在为常量并且指
     向一个字符串常量。 （由 Serhiy Storchaka 在 bpo-38650(5) 中贡献。）

   * 现在 ‘PyGC_Head’ 结构是不透明的。 它只在内部 C API (‘pycore_gc.h’)
     中定义。 （由 Victor Stinner 在 bpo-40241(6) 中贡献。）

   * ‘Py_UNICODE_COPY’, ‘Py_UNICODE_FILL’, ‘PyUnicode_WSTR_LENGTH’,
     *note PyUnicode_FromUnicode(): 263, *note PyUnicode_AsUnicode():
     264, ‘_PyUnicode_AsUnicode’ 以及 *note
     PyUnicode_AsUnicodeAndSize(): 265. 在 C 中被标记为已弃用。 它们自
     Python 3.3 起就已被 PEP 393(7) 弃用。 （由 Inada Naoki 在
     bpo-36346(8) 中贡献。）

   * *note Py_FatalError(): 266. 函数会被一个自动记录当前函数名称的宏所
     替代，除非已定义了 ‘Py_LIMITED_API’ 宏。 （由 Victor Stinner 在
     bpo-39882(9) 中贡献。）

   * vectorcall 协议现在要求调用者只传入字符串作为键名。 （请参阅
     bpo-37540(10) 了解详情。）

   * 多个宏和函数的实现细节现在已被隐藏:

        * *note PyObject_IS_GC(): 267. 宏已被转换为函数。

        * ‘PyObject_NEW()’ 宏已成为 *note PyObject_New(): 268. 宏的别名
          ，而 ‘PyObject_NEW_VAR()’ 宏已成为 *note PyObject_NewVar():
          269. 宏的别名。 它们将不再直接访问 *note
          PyTypeObject.tp_basicsize: 26a. 成员。

        * ‘PyObject_GET_WEAKREFS_LISTPTR()’ 宏已被转换为函数：该宏会直接
          访问 *note PyTypeObject.tp_weaklistoffset: 26b. 成员。

        * *note PyObject_CheckBuffer(): 26c. 宏已被转换为函数：该宏会直
          接访问 *note PyTypeObject.tp_as_buffer: 26d. 成员。

        * 现在 *note PyIndex_Check(): 26e. 总是被声明为不透明函数以隐藏
          实现细节；‘PyIndex_Check()’ 宏已被移除。 该宏会直接访问 *note
          PyTypeObject.tp_as_number: 26f. 成员。

     （详情请参阅 bpo-40170(11)。）

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0523

   (2) https://bugs.python.org/issue38500

   (3) https://bugs.python.org/issue39984

   (4) https://bugs.python.org/issue8901

   (5) https://bugs.python.org/issue38650

   (6) https://bugs.python.org/issue40241

   (7) https://www.python.org/dev/peps/pep-0393

   (8) https://bugs.python.org/issue36346

   (9) https://bugs.python.org/issue39882

   (10) https://bugs.python.org/issue37540

   (11) https://bugs.python.org/issue40170


File: python.info,  Node: 移除<2>,  Prev: 移植到 Python 3 9<2>,  Up: C API 的改变

1.1.12.3 移除
.............

   * ‘pyfpe.h’ 的 ‘PyFPE_START_PROTECT()’ 和 ‘PyFPE_END_PROTECT()’ 宏已
     从受限的 C API 中被排除。 （由 Victor Stinner 在 bpo-38835(1) 中贡
     献。）

   * *note PyTypeObject: 271. 的 ‘tp_print’ 空位已被移除。 它在 Python
     2.7 及之前的版本中被用来将对象打印到文件。 自 Python 3.0 起，它已被
     忽略并且不再使用。 （由 Jeroen Demeyer 在 bpo-36974(2) 中贡献。）

   * 受限 C API 中的改变（如果定义了 ‘Py_LIMITED_API’ 宏）:

        * 以下函数已从受限 C API 中排除:

             * ‘PyThreadState_DeleteCurrent()’ （由 Joannah Nanjekye 在
               bpo-37878(3) 中贡献。）

             * ‘_Py_CheckRecursionLimit’

             * ‘_Py_NewReference()’

             * ‘_Py_ForgetReference()’

             * ‘_PyTraceMalloc_NewReference()’

             * ‘_Py_GetRefTotal()’

             * 在受限 C API 中从未使用的垃圾箱机制。

             * ‘PyTrash_UNWIND_LEVEL’

             * ‘Py_TRASHCAN_BEGIN_CONDITION’

             * ‘Py_TRASHCAN_BEGIN’

             * ‘Py_TRASHCAN_END’

             * ‘Py_TRASHCAN_SAFE_BEGIN’

             * ‘Py_TRASHCAN_SAFE_END’

        * 已将下列函数和定义移至内部 C API:

             * ‘_PyDebug_PrintTotalRefs()’

             * ‘_Py_PrintReferences()’

             * ‘_Py_PrintReferenceAddresses()’

             * ‘_Py_tracemalloc_config’

             * ‘_Py_AddToAllObjects()’ (‘Py_TRACE_REFS’ 构建专属)

     （由 Victor Stinner 在 bpo-38644(4) 和 bpo-39542(5) 中贡献。）

   * 移除了 ‘_PyRuntime.getframe’ 钩子并移除了 ‘_PyThreadState_GetFrame’
     宏，该宏是 ‘_PyRuntime.getframe’ 的一个别名。 它们仅由内部 C API 对
     外公开。 同样地移除了 ‘PyThreadFrameGetter’ 类型。 （由 Victor
     Stinner 在 bpo-39946(6) 中贡献。）

   * 从 C API 移除了下列函数。 请显式地调用 ‘PyGC_Collect()’ 来清空所有
     自由列表。 （由 Inada Naoki 和 Victor Stinner 在 bpo-37340(7),
     bpo-38896(8) 和 bpo-40428(9) 中贡献。）

        * ‘PyAsyncGen_ClearFreeLists()’

        * ‘PyContext_ClearFreeList()’

        * ‘PyDict_ClearFreeList()’

        * ‘PyFloat_ClearFreeList()’

        * ‘PyFrame_ClearFreeList()’

        * ‘PyList_ClearFreeList()’

        * ‘PyMethod_ClearFreeList()’ 和 ‘PyCFunction_ClearFreeList()’: 绑
          定方法对象的自由列表已被移除。

        * ‘PySet_ClearFreeList()’: 集合自由列表已在 Python 3.4 中被移除
          。

        * ‘PyTuple_ClearFreeList()’

        * ‘PyUnicode_ClearFreeList()’: Unicode 自由列表已在 Python 3.3 中
          被移除。

   * 移除了 ‘_PyUnicode_ClearStaticStrings()’ 函数。 （由 Victor Stinner
     在 bpo-39465(10) 中贡献。）

   * 移除了 ‘Py_UNICODE_MATCH’。 它已被 PEP 393(11) 所弃用，并自 Python
     3.3 起不再可用。 可以改用 *note PyUnicode_Tailmatch(): 272. 函数。
     （由 Inada Naoki 在 bpo-36346(12) 中贡献。）

   * 清除了已定义但未实现的接口的头文件。 被移除了公共 API 符号有:
     ‘_PyBytes_InsertThousandsGroupingLocale’,
     ‘_PyBytes_InsertThousandsGrouping’, ‘_Py_InitializeFromArgs’,
     ‘_Py_InitializeFromWideArgs’, ‘_PyFloat_Repr’, ‘_PyFloat_Digits’,
     ‘_PyFloat_DigitsInit’, ‘PyFrame_ExtendStack’,
     ‘_PyAIterWrapper_Type’, ‘PyNullImporter_Type’, ‘PyCmpWrapper_Type’,
     ‘PySortWrapper_Type’, ‘PyNoArgsFunction’。 （由 Pablo Galindo
     Salgado 在 bpo-39372(13) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38835

   (2) https://bugs.python.org/issue36974

   (3) https://bugs.python.org/issue37878

   (4) https://bugs.python.org/issue38644

   (5) https://bugs.python.org/issue39542

   (6) https://bugs.python.org/issue39946

   (7) https://bugs.python.org/issue37340

   (8) https://bugs.python.org/issue38896

   (9) https://bugs.python.org/issue40428

   (10) https://bugs.python.org/issue39465

   (11) https://www.python.org/dev/peps/pep-0393

   (12) https://bugs.python.org/issue36346

   (13) https://bugs.python.org/issue39372


File: python.info,  Node: Python 3 9 1 中的重要变化,  Next: Python 3 9 2 中的重要变化,  Prev: C API 的改变,  Up: Python 3 9 有什么新变化

1.1.13 Python 3.9.1 中的重要变化
--------------------------------

* Menu:

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


File: python.info,  Node: typing<2>,  Next: macOS 11 0 Big Sur 与 Apple Silicon Mac 支持,  Up: Python 3 9 1 中的重要变化

1.1.13.1 typing
...............

*note typing.Literal: 275. 的行为被改为遵循 PEP 586(1) 并匹配该 PEP 所描
述的静态类型检查器的行为。

  1. ‘Literal’ 现在将是去重复的形参。

  2. ‘Literal’ 对象间的相等性比较现在将是顺序无关的。

  3. ‘Literal’ 比较现在会考虑类型。 例如 ‘Literal[0] == Literal[False]’
     之前的结果值为 ‘True’。 现在则为 ‘False’。 为支持此改变，内部使用的
     类型缓存现在也支持区分类型。

  4. 现在如果有任何一个参数不为 *note hashable: 276.，‘Literal’ 对象将在
     相等性比较期间引发 *note TypeError: 1fe.。 请注意使用可变参数声明
     ‘Literal’ 将不会抛出异常:

          >>> 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'

（由 Yurii Karabas 在 bpo-42345(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0586

   (2) https://bugs.python.org/issue42345


File: python.info,  Node: macOS 11 0 Big Sur 与 Apple Silicon Mac 支持,  Prev: typing<2>,  Up: Python 3 9 1 中的重要变化

1.1.13.2 macOS 11.0 (Big Sur) 与 Apple Silicon Mac 支持
.......................................................

对于 3.9.1 版来说，Python 现在完全支持在 macOS 11.0 (Big Sur) 和 Apple
Silicon Macs (基于 ‘ARM64’ 架构) 上构建和运行。 现在提供了一个新的通用构
建类型 ‘universal2’，用于在一组可执行文件上原生支持 ‘ARM64’ 和 ‘Intel
64’。 二进制文件现在也可以在当前版本的 macOS 上编译以部署到多种较旧的
macOS 版本上 (已测试 10.9)，同时会基于运行时所使用的操作系统版本让某些较
新的 OS 功能和选项有条件地可用 ("弱链接") 。

（由 Ronald Oussoren 和 Lawrence D’Anna 在 bpo-41100(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41100


File: python.info,  Node: Python 3 9 2 中的重要变化,  Next: Python 3 9 3 中的重要变化,  Prev: Python 3 9 1 中的重要变化,  Up: Python 3 9 有什么新变化

1.1.14 Python 3.9.2 中的重要变化
--------------------------------

* Menu:

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


File: python.info,  Node: collections abc,  Next: urllib parse,  Up: Python 3 9 2 中的重要变化

1.1.14.1 collections.abc
........................

现在 *note collections.abc.Callable: 27a. 泛型会将类型形参展平，类似于
*note typing.Callable: 27b. 当前所做的那样。 这意味着
‘collections.abc.Callable[[int, str], str]’ 的 ‘__args__’ 将为 ‘(int,
str, str)’；之前则为 ‘([int, str], str)’。 为了允许这个改变，*note
types.GenericAlias: 27c. 现在可以被子类化，并且在抽取 *note
collections.abc.Callable: 27a. 类型时将返回一个子类。 通过 *note
typing.get_args(): 27d. 或 ‘__args__’ 访问参数的代码需要考虑到这个改变。
对于无效的 *note collections.abc.Callable: 27a. 参数化形式可能会发出
*note DeprecationWarning: 15a.，这在 Python 3.9.1 中可能会静默地传递。 这
个 *note DeprecationWarning: 15a. 将在 Python 3.10 中变为 *note
TypeError: 1fe.。 （由 Ken Jin 在 bpo-42195(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42195


File: python.info,  Node: urllib parse,  Prev: collections abc,  Up: Python 3 9 2 中的重要变化

1.1.14.2 urllib.parse
.....................

早先的 Python 版本允许使用 ‘;’ 和 ‘&’ 作为 *note
urllib.parse.parse_qs(): 27f. 和 *note urllib.parse.parse_qsl(): 280. 中
query 形参的分隔键。 出于安全考虑，也为了遵循更新的 W3C 推荐设置，这已被
改为只允许单个分隔键，默认为 ‘&’。 这一改变还会影响 *note cgi.parse():
281. 和 *note cgi.parse_multipart(): 282. 因为它们在内部使用了受影响的函
数。 要了解更多细节，请查看它们各自的文档。 （由 Adam Goldschmidt,
Senthil Kumaran 和 Ken Jin 在 bpo-42967(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42967


File: python.info,  Node: Python 3 9 3 中的重要变化,  Next: Python 3 9 5 中的重要变化,  Prev: Python 3 9 2 中的重要变化,  Up: Python 3 9 有什么新变化

1.1.15 Python 3.9.3 中的重要变化
--------------------------------

新的安全修正将A security fix alters the *note ftplib.FTP: 1a6. 的行为改
成当设置被动数据通道时不信任远程服务器所发送的 IPv4 地址。 我们会改为重
用 FTP 服务器的 IP 地址。 对于需要原先行为的不常见代码，请在你的 FTP 实
例上设置 ‘trust_server_pasv_ipv4_address’ 属性为 ‘True’。 (参见
bpo-43285(1))

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue43285


File: python.info,  Node: Python 3 9 5 中的重要变化,  Prev: Python 3 9 3 中的重要变化,  Up: Python 3 9 有什么新变化

1.1.16 Python 3.9.5 中的重要变化
--------------------------------

* Menu:

* urllib.parse: urllib parse<2>.


File: python.info,  Node: urllib parse<2>,  Up: Python 3 9 5 中的重要变化

1.1.16.1 urllib.parse
.....................

在 URL 部分中存在换行符或制表符可导致某些形式的攻击。 跟随更新了 RFC
3986(1) 的 WHATWG 规格描述，ASCII 换行 ‘\n’, ‘\r’ 和制表 ‘\t’ 等字符会被
*note urllib.parse: 128. 的解析器从 URL 中移除以防止此类攻击。 移除字符
操作是由新的模块级变量 ‘urllib.parse._UNSAFE_URL_BYTES_TO_REMOVE’ 来控制
的。 (参见 bpo-43882(2))

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc3986.html

   (2) https://bugs.python.org/issue43882


File: python.info,  Node: Python 3 8 有什么新变化,  Next: Python 3 7 有什么新变化,  Prev: Python 3 9 有什么新变化,  Up: Python 有什麼新功能？

1.2 Python 3.8 有什么新变化
===========================


编者: Raymond Hettinger

本文解释了 Python 3.8 相比 3.7 的新增特性。 完整的详情可参阅 *note
更新日志: 156.。

* 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 中的重要变化.
* Notable changes in Python 3.8.12: Notable changes in Python 3 8 12.


File: python.info,  Node: 摘要 - 发布重点<2>,  Next: 新的特性<3>,  Up: Python 3 8 有什么新变化

1.2.1 摘要 - 发布重点
---------------------


File: python.info,  Node: 新的特性<3>,  Next: 其他语言特性修改<2>,  Prev: 摘要 - 发布重点<2>,  Up: Python 3 8 有什么新变化

1.2.2 新的特性
--------------

* 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::


File: python.info,  Node: 赋值表达式,  Next: 仅限位置形参,  Up: 新的特性<3>

1.2.2.1 赋值表达式
..................

新增的语法 ‘:=’ 可在表达式内部为变量赋值。 它被昵称为“海象运算符”因为它
很像是 海象的眼睛和长牙(1)。

在这个示例中，赋值表达式可以避免调用 *note len(): 28b. 两次:

     if (n := len(a)) > 10:
         print(f"List is too long ({n} elements, expected <= 10)")

类似的益处还可出现在正则表达式匹配中需要使用两次匹配对象的情况中，一次检
测用于匹配是否发生，另一次用于提取子分组:

     discount = 0.0
     if (mo := re.search(r'(\d+)% discount', advertisement)):
         discount = float(mo.group(1)) / 100.0

此运算符也适用于配合 while 循环计算一个值来检测循环是否终止，而同一个值
又在循环体中再次被使用的情况:

     # Loop over fixed length blocks
     while (block := f.read(256)) != '':
         process(block)

另一个值得介绍的用例出现于列表推导式中，在筛选条件中计算一个值，而同一个
值又在表达式中需要被使用:

     [clean_name.title() for name in names
      if (clean_name := normalize('NFC', name)) in allowed_names]

请尽量将海象运算符的使用限制在清晰的场合中，以降低复杂性并提升可读性。

请参阅 PEP 572(2) 了解详情。

（由 Morehouse 在 bpo-35224(3) 中贡献。）

   ---------- Footnotes ----------

   (1) 
https://en.wikipedia.org/wiki/Walrus#/media/File:Pacific_Walrus_-_Bull_(8247646168).jpg

   (2) https://www.python.org/dev/peps/pep-0572

   (3) https://bugs.python.org/issue35224


File: python.info,  Node: 仅限位置形参,  Next: 用于已编译字节码文件的并行文件系统缓存,  Prev: 赋值表达式,  Up: 新的特性<3>

1.2.2.2 仅限位置形参
....................

新增了一个函数形参语法 ‘/’ 用来指明某些函数形参必须使用仅限位置而非关键
字参数的形式。 这种标记语法与通过 ‘help()’ 所显示的使用 Larry Hastings 的
Argument Clinic(1) 工具标记的 C 函数相同。

在下面的例子中，形参 `a' 和 `b' 为仅限位置形参，`c' 或 `d' 可以是位置形
参或关键字形参，而 `e' 或 `f' 要求为关键字形参:

     def f(a, b, /, c, d, *, e, f):
         print(a, b, c, d, e, f)

以下均为合法的调用:

     f(10, 20, 30, d=40, e=50, f=60)

但是，以下均为不合法的调用:

     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

这种标记形式的一个用例是它允许纯 Python 函数完整模拟现有的用 C 代码编写
的函数的行为。 例如，内置的 *note divmod(): 28d. 函数不接受关键字参数:

     def divmod(a, b, /):
         "Emulate the built in divmod() function"
         return (a // b, a % b)

另一个用例是在不需要形参名称时排除关键字参数。 例如，内置的 *note len():
28b. 函数的签名为 ‘len(obj, /)’。 这可以排除如下这种笨拙的调用形式:

     len(obj='hello')  # The "obj" keyword argument impairs readability

另一个益处是将形参标记为仅限位置形参将允许在未来修改形参名而不会破坏客户
的代码。 例如，在 *note statistics: f5. 模块中，形参名 `dist' 在未来可能
被修改。 这使得以下函数描述成为可能:

     def quantiles(dist, /, *, n=4, method='exclusive')
         ...

由于在 ‘/’ 左侧的形参不会被公开为可用关键字，其他形参名仍可在 ‘**kwargs’
中使用:

     >>> 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}

这极大地简化了需要接受任意关键字参数的函数和方法的实现。 例如，以下是一
段摘自 *note collections: 1d. 模块的代码:

     class Counter(dict):

         def __init__(self, iterable=None, /, **kwds):
             # Note "iterable" is a possible keyword argument

请参阅 PEP 570(2) 了解详情。

（由 Pablo Galindo 在 bpo-36540(3) 中贡献。）

   ---------- Footnotes ----------

   (1) https://docs.python.org/3/howto/clinic.html

   (2) https://www.python.org/dev/peps/pep-0570

   (3) https://bugs.python.org/issue36540


File: python.info,  Node: 用于已编译字节码文件的并行文件系统缓存,  Next: 调试构建使用与发布构建相同的 ABI,  Prev: 仅限位置形参,  Up: 新的特性<3>

1.2.2.3 用于已编译字节码文件的并行文件系统缓存
..............................................

新增的 *note PYTHONPYCACHEPREFIX: 28f. 设置 (也可使用 *note -X: 290.
‘pycache_prefix’) 可将隐式的字节码缓存配置为使用单独的并行文件系统树，而
不是默认的每个源代码目录下的 ‘__pycache__’ 子目录。

缓存的位置会在 *note sys.pycache_prefix: 291. 中报告 (*note None: 203. 表
示默认位置即 ‘__pycache__’ 子目录)。

（由 Carl Meyer 在 bpo-33499(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33499


File: python.info,  Node: 调试构建使用与发布构建相同的 ABI,  Next: f-字符串支持 = 用于自动记录表达式和调试文档,  Prev: 用于已编译字节码文件的并行文件系统缓存,  Up: 新的特性<3>

1.2.2.4 调试构建使用与发布构建相同的 ABI
........................................

Python 现在不论是以发布模式还是调试模式进行构建都将使用相同的 ABI。 在
Unix 上，当 Python 以调试模式构建时，现在将可以加载以发布模式构建的 C 扩
展和使用稳定版 ABI 构建的 C 扩展。

发布构建和调试构建现在都是 ABI 兼容的：定义 ‘Py_DEBUG’ 宏不会再启用
‘Py_TRACE_REFS’ 宏，它引入了唯一的 ABI 不兼容性。 ‘Py_TRACE_REFS’ 宏添加
了 ‘sys.getobjects()’ 函数和 *note PYTHONDUMPREFS: 293. 环境变量，它可以
使用新的 ‘./configure --with-trace-refs’ 构建选项来设置。 （由 Victor
Stinner 在 bpo-36465(1) 中贡献。）

在 Unix 上，C 扩展不会再被链接到 libpython，但 Android 和 Cygwin 例外。
现在静态链接的 Python 将可以加载使用共享库 Python 构建的 C 扩展。 （由
Victor Stinner 在 bpo-21536(2) 中贡献。）

在 Unix 上，当 Python 以调试模式构建时，导入操作现在也会查找在发布模式下
编译的 C 扩展以及使用稳定版 ABI 编译的 C 扩展。 （由 Victor Stinner 在
bpo-36722(3) 中贡献。）

要将 Python 嵌入到一个应用中，必须将新增的 ‘--embed’ 选项传给
‘python3-config --libs --embed’ 以获得 ‘-lpython3.8’ (将应用链接到
libpython)。 要同时支持 3.8 和旧版本，请先尝试 ‘python3-config --libs
--embed’ 并在此命令失败时回退到 ‘python3-config --libs’ (即不带
‘--embed’)。

增加一个 pkg-config ‘python-3.8-embed’ 模块用来将 Python 嵌入到一个应用
中: ‘pkg-config python-3.8-embed --libs’ 包含 ‘-lpython3.8’。 要同时支持
3.8 和旧版本，请先尝试 ‘pkg-config python-X.Y-embed --libs’ 并在此命令失
败时回退到 ‘pkg-config python-X.Y --libs’ (即不带 ‘--embed’) （请将
‘X.Y’ 替换为 Python 版本号）。

另一方面，‘pkg-config python3.8 --libs’ 不再包含 ‘-lpython3.8’。 C 扩展
不可被链接到 libpython (但 Android 和 Cygwin 例外，这两者的情况由脚本处
理)；此改变是故意被设为向下不兼容的。 （由 Victor Stinner 在
bpo-36721(4) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36465

   (2) https://bugs.python.org/issue21536

   (3) https://bugs.python.org/issue36722

   (4) https://bugs.python.org/issue36721


File: python.info,  Node: f-字符串支持 = 用于自动记录表达式和调试文档,  Next: PEP 578 Python 运行时审核钩子,  Prev: 调试构建使用与发布构建相同的 ABI,  Up: 新的特性<3>

1.2.2.5 f-字符串支持 ‘=’ 用于自动记录表达式和调试文档
.....................................................

增加 ‘=’ 说明符用于 *note f-string: 295.。 形式为 ‘f'{expr=}'’ 的 f-字符
串将扩展表示为表达式文本，加一个等于号，再加表达式的求值结果。 例如：

     >>> user = 'eric_idle'
     >>> member_since = date(1975, 7, 31)
     >>> f'{user=} {member_since=}'
     "user='eric_idle' member_since=datetime.date(1975, 7, 31)"

通常的 *note f-字符串格式说明符: 296. 允许更细致地控制所要显示的表达式结
果:

     >>> delta = date.today() - member_since
     >>> f'{user=!s}  {delta.days=:,d}'
     'user=eric_idle  delta.days=16,075'

‘=’ 说明符将输出整个表达式，以便详细演示计算过程:

     >>> print(f'{theta=}  {cos(radians(theta))=:.3f}')
     theta=30  cos(radians(theta))=0.866

（由 Eric V. Smith 和 Larry Hastings 在 bpo-36817(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36817


File: python.info,  Node: PEP 578 Python 运行时审核钩子,  Next: PEP 587 Python 初始化配置,  Prev: f-字符串支持 = 用于自动记录表达式和调试文档,  Up: 新的特性<3>

1.2.2.6 PEP 578: Python 运行时审核钩子
......................................

此 PEP 添加了审核钩子和已验证开放钩子。 两者在 Python 与本机代码中均可用
。允许以纯 Python 代码编写的应用和框架利用额外的通知，同时允许嵌入开发人
员或系统管理员部署始终启用审核的 Python 版本。

请参阅 PEP 578(1) 了解详情。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0578


File: python.info,  Node: PEP 587 Python 初始化配置,  Next: PEP 590 Vectorcall 用于 CPython 的快速调用协议,  Prev: PEP 578 Python 运行时审核钩子,  Up: 新的特性<3>

1.2.2.7 PEP 587: Python 初始化配置
..................................

PEP 587(1) 增加了一个新的 C API 用来配置 Python 初始化，提供对整个配置过
程的更细致控制以及更好的错误报告。

新的结构：

   * *note PyConfig: 226.

   * *note PyPreConfig: 299.

   * *note PyStatus: 29a.

   * *note PyWideStringList: 29b.

新的函数：

   * *note PyConfig_Clear(): 29c.

   * *note PyConfig_InitIsolatedConfig(): 29d.

   * *note PyConfig_InitPythonConfig(): 29e.

   * *note PyConfig_Read(): 29f.

   * *note PyConfig_SetArgv(): 2a0.

   * *note PyConfig_SetBytesArgv(): 2a1.

   * *note PyConfig_SetBytesString(): 2a2.

   * *note PyConfig_SetString(): 2a3.

   * *note PyPreConfig_InitIsolatedConfig(): 2a4.

   * *note PyPreConfig_InitPythonConfig(): 2a5.

   * *note PyStatus_Error(): 2a6.

   * *note PyStatus_Exception(): 2a7.

   * *note PyStatus_Exit(): 2a8.

   * *note PyStatus_IsError(): 2a9.

   * *note PyStatus_IsExit(): 2aa.

   * *note PyStatus_NoMemory(): 2ab.

   * *note PyStatus_Ok(): 2ac.

   * *note PyWideStringList_Append(): 2ad.

   * *note PyWideStringList_Insert(): 2ae.

   * *note Py_BytesMain(): 2af.

   * *note Py_ExitStatusException(): 2b0.

   * *note Py_InitializeFromConfig(): 2b1.

   * *note Py_PreInitialize(): 2b2.

   * *note Py_PreInitializeFromArgs(): 2b3.

   * *note Py_PreInitializeFromBytesArgs(): 2b4.

   * *note Py_RunMain(): 2b5.

此 PEP 还为这些内部结构添加了 ‘_PyRuntimeState.preconfig’ (*note
PyPreConfig: 299. 类型) 和 ‘PyInterpreterState.config’ (*note PyConfig:
226. 类型) 字段。 ‘PyInterpreterState.config’ 成为新的引用配置，替代全局
配置变量和其他私有变量。

请参阅 *note Python 初始化配置: 2b6. 获取详细文档。

请参阅 PEP 587(2) 了解详情。

（由 Victor Stinner 在 bpo-36763(3) 中贡献。）

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0587

   (2) https://www.python.org/dev/peps/pep-0587

   (3) https://bugs.python.org/issue36763


File: python.info,  Node: PEP 590 Vectorcall 用于 CPython 的快速调用协议,  Next: 具有外部数据缓冲区的 pickle 协议 5,  Prev: PEP 587 Python 初始化配置,  Up: 新的特性<3>

1.2.2.8 PEP 590: Vectorcall: 用于 CPython 的快速调用协议
........................................................

将 *note Vectorcall 协议: 2b8. 添加到 Python/C API。 它的目标是对已被应
用于许多类的现有优化进行正式化。 任何实现可调用对象的静态类型均可使用此
协议。

此特性目前为暂定状态，计划在 Python 3.9 将其完全公开。

请参阅 PEP 590(1) 了解详情。

（由 Jeroen Demeyer, Mark Shannon 和 Petr Viktorin 在 bpo-36974(2) 中贡
献。）

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0590

   (2) https://bugs.python.org/issue36974


File: python.info,  Node: 具有外部数据缓冲区的 pickle 协议 5,  Prev: PEP 590 Vectorcall 用于 CPython 的快速调用协议,  Up: 新的特性<3>

1.2.2.9 具有外部数据缓冲区的 pickle 协议 5
..........................................

当使用 *note pickle: ca. 在 Python 进程间传输大量数据以充分发挥多核或多
机处理的优势时，非常重要一点是通过减少内存拷贝来优化传输效率，并可能应用
一些定制技巧例如针对特定数据的压缩。

*note pickle: ca. 协议 5 引入了对于外部缓冲区的支持，这样 PEP 3118(1) 兼
容的数据可以与主 pickle 流分开进行传输，这是由通信层来确定的。

请参阅 PEP 574(2) 了解详情。

（由 Antoine Pitrou 在 bpo-36785(3) 中贡献。）

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3118

   (2) https://www.python.org/dev/peps/pep-0574

   (3) https://bugs.python.org/issue36785


File: python.info,  Node: 其他语言特性修改<2>,  Next: 新增模块<2>,  Prev: 新的特性<3>,  Up: Python 3 8 有什么新变化

1.2.3 其他语言特性修改
----------------------

   * 在之前版本中 *note continue: 2bb. 语句不允许在 *note finally: 2bc.
     子句中使用，这是因为具体实现存在一个问题。 在 Python 3.8 中此限制已
     被取消。 （由 Serhiy Storchaka 在 bpo-32489(1) 中贡献。）

   * *note bool: 2bd, *note int: 204. 和 *note fractions.Fraction: 2be.
     类型现在都有一个 *note as_integer_ratio(): 2bf. 方法，与 *note
     float: 1fd. 和 *note decimal.Decimal: 2c0. 中的已有方法类似。 这个
     微小的 API 扩展使得 ‘numerator, denominator = x.as_integer_ratio()’
     这样的写法在多种数字类型上通用成为可能。 （由 Lisa Roach 在
     bpo-33073(2) 和 Raymond Hettinger 在 bpo-37819(3) 中贡献。）

   * *note int: 204, *note float: 1fd. 和 *note complex: 2c1. 的构造器现
     在会使用 *note __index__(): 2c2. 特殊方法，如果该方法可用而对应的方
     法 method *note __int__(): 2c3, *note __float__(): 2c4. 或 *note
     __complex__(): 2c5. 方法不可用的话。 （由 Serhiy Storchaka 在
     bpo-20092(4) 中贡献。）

   * 添加 ‘\N{name}’ 转义符在 *note 正则表达式: dd. 中的支持:

          >>> notice = 'Copyright © 2019'
          >>> copyright_year_pattern = re.compile(r'\N{copyright sign}\s*(\d{4})')
          >>> int(copyright_year_pattern.search(notice).group(1))
          2019

     （由 Jonathan Eunice 和 Serhiy Storchaka 在 bpo-30688(5) 中贡献。）

   * 现在 dict 和 dictview 可以使用 *note reversed(): 2c6. 按插入顺序反
     向迭代。 （由 Rémi Lapeyre 在 bpo-33462(6) 中贡献。）

   * 在函数调用中允许使用的关键字名称语法受到进一步的限制。 特别地，
     ‘f((keyword)=arg)’ 不再被允许。 关键字参数赋值形式的左侧绝不允许一
     般标识符以外的其他内容。 （由 Benjamin Peterson 在 bpo-34641(7) 中
     贡献。）

   * 在 *note yield: 2c7. 和 *note return: 2c8. 语句中的一般可迭代对象解
     包不再要求加圆括号。 这使得 `yield' 和 `return' 的语法与正常的赋值
     语法更为一致:

          >>> def parse(family):
                  lastname, *members = family.split()
                  return lastname.upper(), *members

          >>> parse('simpsons homer marge bart lisa maggie')
          ('SIMPSONS', 'homer', 'marge', 'bart', 'lisa', 'maggie')

     （由 David Cuthbert 和 Jordan Chapman 在 bpo-32117(8) 中贡献。）

   * 当类似 ‘[(10, 20) (30, 40)]’ 这样在代码中少了一个逗号时，编译器将显
     示 *note SyntaxWarning: 2c9. 并附带更有帮助的提示。 这相比原来用
     *note TypeError: 1fe. 来提示第一个元组是不可调用的更容易被理解。 （
     由 Serhiy Storchaka 在 bpo-15248(9) 中贡献。）

   * *note datetime.date: 19d. 或 *note datetime.datetime: 19f. 和 *note
     datetime.timedelta: 2ca. 对象之间的算术运算现在将返回相应子类的实例
     而不是基类的实例。 这也会影响到在具体实现中（直接或间接地）使用了
     *note datetime.timedelta: 2ca. 算术运算的返回类型，例如 *note
     astimezone(): 2cb.。 （由 Paul Ganssle 在 bpo-32417(10) 中贡献。）

   * 当 Python 解释器通过 Ctrl-C (SIGINT) 被中断并且所产生的 *note
     KeyboardInterrupt: 2cc. 异常未被捕获，Python 进程现在会通过一个
     SIGINT 信号或是使得发起调用的进程能检测到它是由 Ctrl-C 操作杀死的正
     确退出代码来退出。 POSIX 和 Windows 上的终端会相应地使用此代码在交
     互式会话中终止脚本。 （由 Google 的 Gregory P. Smith 在
     bpo-1054041(11) 中贡献。）

   * 某些高级编程风格要求为现有的函数更新 *note types.CodeType: 2cd. 对
     象。 由于代码对象是不可变的，需要基于现有代码对象模型创建一个新的代
     码对象。 使用 19 个形参将会相当繁琐。 现在，新的 ‘replace()’ 方法使
     得通过少量修改的形参创建克隆对象成为可能。

     下面是一个修改 *note statistics.mean(): 2ce. 函数来防止 `data' 形参
     被用作关键字参数的例子:

          >>> 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'

     （由 Victor Stinner 在 bpo-37032(12) 中贡献。）

   * 对于整数，现在 *note pow(): 2cf. 函数的三参数形式在底数与模数不可约
     的情况下允许指数为负值。 随后它会在指数为 ‘-1’ 时计算底数的模乘逆元
     ，并对其他负指数计算反模的适当幂次。 例如，要计算 38 模 137 的 模乘
     逆元(13) 则可写为:

          >>> pow(38, -1, 137)
          119
          >>> 119 * 38 % 137
          1

     模乘逆元在求解 线性丢番图方程(14) 会被用到。 例如，想要求出 ‘4258𝑥
     + 147𝑦 = 369’ 的整数解，首先应重写为 ‘4258𝑥 ≡ 369 (mod 147)’ 然后求
     解：

          >>> x = 369 * pow(4258, -1, 147) % 147
          >>> y = (4258 * x - 369) // -147
          >>> 4258 * x + 147 * y
          369

     （由 Mark Dickinson 在 bpo-36027(15) 中贡献。）

   * 字典推导式已与字典字面值实现同步，会先计算键再计算值:

          >>> # 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

     对执行顺序的保证对赋值表达式来说很有用，因为在键表达式中赋值的变量
     将可在值表达式中被使用:

          >>> 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'}

     （由 Jörn Heissler 在 bpo-35224(16) 中贡献。）

   * *note object.__reduce__(): 2d0. 方法现在可返回长度为二至六个元素的
     元组。 之前的上限为五个。 新增的第六个可选元素是签名为 ‘(obj,
     state)’ 的可调用对象。 这样就允许直接控制特定对象的状态更新。 如果
     元素值不为 `None'，该可调用对象将优先于对象的 *note __setstate__():
     2d1. 方法。 （由 Pierre Glaser 和 Olivier Grisel 在 bpo-35900(17) 中
     贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32489

   (2) https://bugs.python.org/issue33073

   (3) https://bugs.python.org/issue37819

   (4) https://bugs.python.org/issue20092

   (5) https://bugs.python.org/issue30688

   (6) https://bugs.python.org/issue33462

   (7) https://bugs.python.org/issue34641

   (8) https://bugs.python.org/issue32117

   (9) https://bugs.python.org/issue15248

   (10) https://bugs.python.org/issue32417

   (11) https://bugs.python.org/issue1054041

   (12) https://bugs.python.org/issue37032

   (13) https://en.wikipedia.org/wiki/Modular_multiplicative_inverse

   (14) https://en.wikipedia.org/wiki/Diophantine_equation

   (15) https://bugs.python.org/issue36027

   (16) https://bugs.python.org/issue35224

   (17) https://bugs.python.org/issue35900


File: python.info,  Node: 新增模块<2>,  Next: 改进的模块<2>,  Prev: 其他语言特性修改<2>,  Up: Python 3 8 有什么新变化

1.2.4 新增模块
--------------

   * 新增的 *note importlib.metadata: 9d. 模块提供了从第三方包读取元数据
     的（临时）支持。 例如，它可以提取一个已安装软件包的版本号、入口点列
     表等等:

          >>> # 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')]

     （由 Barry Warsaw 和 Jason R. Coombs 在 bpo-34632(1) 中贡献）。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue34632


File: python.info,  Node: 改进的模块<2>,  Next: 性能优化<2>,  Prev: 新增模块<2>,  Up: Python 3 8 有什么新变化

1.2.5 改进的模块
----------------

* 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::
* threading::
* tokenize::
* tkinter::
* time: time<2>.
* typing: typing<3>.
* unicodedata: unicodedata<2>.
* unittest::
* venv: venv<2>.
* weakref::
* xml: xml<2>.
* xmlrpc::


File: python.info,  Node: ast<2>,  Next: asyncio<2>,  Up: 改进的模块<2>

1.2.5.1 ast
...........

AST 节点现在具有 ‘end_lineno’ 和 ‘end_col_offset’ 属性，它们给出节点结束
的精确位置。 （这只适用于具有 ‘lineno’ 和 ‘col_offset’ 属性的节点。）

新增函数 *note ast.get_source_segment(): 2d5. 返回指定 AST 节点的源代码
。

（由 Ivan Levkivskyi 在 bpo-33416(1) 中贡献。）

*note ast.parse(): 2d6. 函数具有一些新的旗标：

   * ‘type_comments=True’ 导致其返回与特定 AST 节点相关联的 PEP 484(2) 和
     PEP 526(3) 类型注释文本；

   * ‘mode='func_type'’ 可被用于解析 PEP 484(4) "签名类型注释" (为函数定
     义 AST 节点而返回)；

   * ‘feature_version=(3, N)’ 允许指定一个更早的 Python 3 版本。 例如，
     ‘feature_version=(3, 4)’ 将把 *note async: 2d7. 和 *note await:
     2d8. 视为非保留字。

（由 Guido van Rossum 在 bpo-35766(5) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33416

   (2) https://www.python.org/dev/peps/pep-0484

   (3) https://www.python.org/dev/peps/pep-0526

   (4) https://www.python.org/dev/peps/pep-0484

   (5) https://bugs.python.org/issue35766


File: python.info,  Node: asyncio<2>,  Next: builtins,  Prev: ast<2>,  Up: 改进的模块<2>

1.2.5.2 asyncio
...............

*note asyncio.run(): 18d. 已经从暂定状态晋级为稳定 API。 此函数可被用于
执行一个 *note coroutine: 18a. 并返回结果，同时自动管理事件循环。 例如:

     import asyncio

     async def main():
         await asyncio.sleep(0)
         return 42

     asyncio.run(main())

这 `大致' 等价于:

     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()

实际的实现要更复杂许多。 因此 *note asyncio.run(): 18d. 应该作为运行
asyncio 程序的首选方式。

（由 Yury Selivanov 在 bpo-32314(1) 中贡献。）

运行 ‘python -m asyncio’ 将启动一个原生异步 REPL。 这允许快速体验具有最
高层级 *note await: 2d8. 的代码。 这时不再需要直接调用 ‘asyncio.run()’，
因为此操作会在每次发起调用时产生一个新事件循环：

     $ 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

（由 Yury Selivanov 在 bpo-37028(2) 中贡献。）

异常 *note asyncio.CancelledError: 2da. 现在继承自 *note BaseException:
2db. 而不是 *note Exception: 2dc. 并且不再继承自 *note
concurrent.futures.CancelledError: 2dd.。 （由 Yury Selivanov 在
bpo-32528(3) 中贡献。）

在 Windows 上，现在默认的事件循环为 *note ProactorEventLoop: 2de.。 （由
Victor Stinner 在 bpo-34687(4) 中贡献。）

*note ProactorEventLoop: 2de. 现在也支持 UDP。 （由 Adam Meily 和 Andrew
Svetlov 在 bpo-29883(5) 中贡献。）

*note ProactorEventLoop: 2de. 现在可通过 *note KeyboardInterrupt: 2cc.
("CTRL+C") 来中断。 （由 Vladimir Matveev 在 bpo-23057(6) 中贡献。）

添加了 *note asyncio.Task.get_coro(): 2df. 用来获取 *note asyncio.Task:
2e0. 中的已包装协程。 （由 Alex Grönholm 在 bpo-36999(7) 中贡献。）

asyncio 任务现在可以被命名，或者是通过将 ‘name’ 关键字参数传给 *note
asyncio.create_task(): 2e1. 或 *note create_task(): 2e2. 事件循环方法，
或者是通过在任务对象上调用 *note set_name(): 2e3. 方法。 任务名称在
*note asyncio.Task: 2e0. 的 ‘repr()’ 输出中可见，并且还可以使用 *note
get_name(): 2e4. 方法来获取。 （由 Alex Grönholm 在 bpo-34270(8) 中贡献
。）

将对 Happy Eyeballs(9) 的支持添加到 *note
asyncio.loop.create_connection(): 2e5.。 要指定此行为，已增加了两个新的
形参: `happy_eyeballs_delay' 和 `interleave'。 Happy Eyeballs 算法可提升
支持 IPv4 和 IPv6 的应用的响应速度，具体做法是尝试同时使用两者进行连接。
（由 twisteroid ambassador 在 bpo-33530(10) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32314

   (2) https://bugs.python.org/issue37028

   (3) https://bugs.python.org/issue32528

   (4) https://bugs.python.org/issue34687

   (5) https://bugs.python.org/issue29883

   (6) https://bugs.python.org/issue23057

   (7) https://bugs.python.org/issue36999

   (8) https://bugs.python.org/issue34270

   (9) https://en.wikipedia.org/wiki/Happy_Eyeballs

   (10) https://bugs.python.org/issue33530


File: python.info,  Node: builtins,  Next: collections,  Prev: asyncio<2>,  Up: 改进的模块<2>

1.2.5.3 builtins
................

内置的 *note compile(): 2e7. 已改进为可接受
‘ast.PyCF_ALLOW_TOP_LEVEL_AWAIT’ 旗标。 当传入此新旗标时，*note
compile(): 2e7. 将允许通常被视为无效语法的最高层级 ‘await’, ‘async for’
和 ‘async with’ 构造。 此后将可返回带有 ‘CO_COROUTINE’ 旗标的异步代码对
象。 （由 Matthias Bussonnier 在 bpo-34616(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue34616


File: python.info,  Node: collections,  Next: cProfile,  Prev: builtins,  Up: 改进的模块<2>

1.2.5.4 collections
...................

*note collections.namedtuple(): 1a1. 的 *note _asdict(): 2e9. 方法现在将
返回 *note dict: 164. 而不是 *note collections.OrderedDict: 2ea.。 此项
更改是由于普通字典自 Python 3.7 起已保证具有确定的元素顺序。 如果还需要
‘OrderedDict’ 的额外特性，建议的解决方案是将结果转换为需要的类型:
‘OrderedDict(nt._asdict())’。 （由 Raymond Hettinger 在 bpo-35864(1) 中
贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35864


File: python.info,  Node: cProfile,  Next: csv,  Prev: collections,  Up: 改进的模块<2>

1.2.5.5 cProfile
................

*note cProfile.Profile: 2ec. 类现在可被用作上下文管理器。 在运行时对一个
代码块实现性能分析:

     import cProfile

     with cProfile.Profile() as profiler:
           # code to be profiled
           ...

（由 Scott Sanderson 在 bpo-29235(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29235


File: python.info,  Node: csv,  Next: curses<2>,  Prev: cProfile,  Up: 改进的模块<2>

1.2.5.6 csv
...........

*note csv.DictReader: 2ee. 现在将返回 *note dict: 164. 而不是 *note
collections.OrderedDict: 2ea.。 此工具现在会更快速且消耗更少内存同时仍然
保留字段顺序。 （由 Michael Selik 在 bpo-34003(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue34003


File: python.info,  Node: curses<2>,  Next: ctypes,  Prev: csv,  Up: 改进的模块<2>

1.2.5.7 curses
..............

添加了一个新变量用于保存下层 ncurses 库的结构版信息: *note
ncurses_version: 2f0.。 （由 Serhiy Storchaka 在 bpo-31680(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31680


File: python.info,  Node: ctypes,  Next: datetime<2>,  Prev: curses<2>,  Up: 改进的模块<2>

1.2.5.8 ctypes
..............

在 Windows 上，*note CDLL: 2f2. 及其子类现在接受 `winmode' 形参来指定用
于底层 ‘LoadLibraryEx’ 调用的旗标。 默认旗标被设为仅加载来自可信任位置的
DLL 依赖项，包括 DLL 的存放路径（如果加载初始 DLL 时使用了完整或部分路径
）以及通过 *note add_dll_directory(): 2f3. 添加的路径。 （由 Steve Dower
在 bpo-36085(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36085


File: python.info,  Node: datetime<2>,  Next: functools,  Prev: ctypes,  Up: 改进的模块<2>

1.2.5.9 datetime
................

添加了新的替代构造器 *note datetime.date.fromisocalendar(): 2f5. 和
*note datetime.datetime.fromisocalendar(): 2f6.，它们分别基于 ISO 年份、
周序号和周内日序号来构造 ‘date’ 和 *note datetime: 30. 对象；这两者分别
是其所对应类中 ‘isocalendar’ 方法的逆操作。 （由 Paul Ganssle 在
bpo-36004(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36004


File: python.info,  Node: functools,  Next: gc<2>,  Prev: datetime<2>,  Up: 改进的模块<2>

1.2.5.10 functools
..................

*note functools.lru_cache(): 2f8. 现在可直接作为装饰器而不是作为返回装饰
器的函数。 因此这两种写法现在都被支持:

     @lru_cache
     def f(x):
         ...

     @lru_cache(maxsize=256)
     def f(x):
         ...

（由 Raymond Hettinger 在 bpo-36772(1) 中贡献。）

添加了新的 *note functools.cached_property(): 2f9. 装饰器，用于在实例生
命周期内缓存的已计算特征属性。

     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)

（由 Carl Meyer 在 bpo-21145(2) 中贡献）

添加了新的 *note functools.singledispatchmethod(): 2fa. 装饰器可使用
*note single dispatch: 2fb. 将方法转换为 *note 泛型函数: 2fc.:

     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]

（由 Ethan Smith 在 bpo-32380(3) 中贡献）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36772

   (2) https://bugs.python.org/issue21145

   (3) https://bugs.python.org/issue32380


File: python.info,  Node: gc<2>,  Next: gettext,  Prev: functools,  Up: 改进的模块<2>

1.2.5.11 gc
...........

*note get_objects(): 2fe. 现在能接受一个可选的 `generation' 形参来指定一
个用于获取对象的生成器。 （由 Pablo Galindo 在 bpo-36016(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36016


File: python.info,  Node: gettext,  Next: gzip,  Prev: gc<2>,  Up: 改进的模块<2>

1.2.5.12 gettext
................

添加了 *note pgettext(): 300. 及其变化形式。 （由 Franz Glasner, Éric
Araujo 和 Cheryl Sabella 在 bpo-2504(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue2504


File: python.info,  Node: gzip,  Next: IDLE 与 idlelib<2>,  Prev: gettext,  Up: 改进的模块<2>

1.2.5.13 gzip
.............

添加 `mtime' 形参到 *note gzip.compress(): 302. 用于可重现的输出。 （由
Guo Ci Teo 在 bpo-34898(1) 中贡献。）

对于特定类型的无效或已损坏 gzip 文件现在将引发 *note BadGzipFile: 303. 而
不是 *note OSError: 304.。 （由 Filip Gruszczyński, Michele Orrù 和
Zackery Spytz 在 bpo-6584(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue34898

   (2) https://bugs.python.org/issue6584


File: python.info,  Node: IDLE 与 idlelib<2>,  Next: inspect<2>,  Prev: gzip,  Up: 改进的模块<2>

1.2.5.14 IDLE 与 idlelib
........................

超过 N 行（默认值为 50）的输出将被折叠为一个按钮。 N 可以在 Settings 对
话框的 General 页的 PyShell 部分中进行修改。 数量较少但是超长的行可以通
过在输出上右击来折叠。 被折叠的输出可通过双击按钮来展开，或是通过右击按
钮来放入剪贴板或是单独的窗口。 （由 Tal Einat 在 bpo-1529353(1) 中贡献。
）

在 Run 菜单中增加了 "Run Customized" 以使用自定义设置来运行模块。 输入的
任何命令行参数都会被加入 sys.argv。 它们在下次自定义运行时会再次显示在窗
体中。 用户也可以禁用通常的 Shell 主模块重启。 （由 Cheryl Sabella,
Terry Jan Reedy 等人在 bpo-5680(2) 和 bpo-37627(3) 中贡献。）

在 IDLE 编辑器窗口中增加了可选的行号。 窗口打开时默认不显示行号，除非在
配置对话框的 General 选项卡中特别设置。 已打开窗口中的行号可以在 Options
菜单中显示和隐藏。 （由 Tal Einat 和 Saimadhav Heblikar 在 bpo-17535(4)
中贡献。）

现在会使用 OS 本机编码格式在 Python 字符串和 Tcl 对象间进行转换。 这允许
在 IDLE 中处理 emoji 和其他非 BMP 字符。 这些字符将可被显示或是从剪贴板
复制和粘贴。 字符串从 Tcl 到 Python 的来回转换现在不会再发生失败。 （过
去八年有许多人都为此付出过努力，问题最终由 Serhiy Storchaka 在
bpo-13153(5) 中解决。）

在 3.8.1 中新增:

添加切换光标闪烁停止的选项。 （由 Zackery Spytz 在 bpo-4603(6) 中贡献。
）

Esc 键现在会关闭 IDLE 补全提示窗口。 （由 Johnny Najera 在 bpo-38944(7)
中贡献。）

上述修改已被反向移植到 3.7 维护发行版中。

添加关键字到模块名称补全列表。 （由 Terry J. Reedy 在 bpo-37765(8) 中贡
献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1529353

   (2) https://bugs.python.org/issue5680

   (3) https://bugs.python.org/issue37627

   (4) https://bugs.python.org/issue17535

   (5) https://bugs.python.org/issue13153

   (6) https://bugs.python.org/issue4603

   (7) https://bugs.python.org/issue38944

   (8) https://bugs.python.org/issue37765


File: python.info,  Node: inspect<2>,  Next: io,  Prev: IDLE 与 idlelib<2>,  Up: 改进的模块<2>

1.2.5.15 inspect
................

*note inspect.getdoc(): 307. 函数现在可以找到 ‘__slots__’ 的文档字符串，
如果该属性是一个元素值为文档字符串的 *note dict: 164. 的话。 这提供了类
似于目前已有的 *note property(): 308, *note classmethod(): 309. 和 *note
staticmethod(): 30a. 等函数的文档选项:

     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)

（由 Raymond Hettinger 在 bpo-36326(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36326


File: python.info,  Node: io,  Next: itertools,  Prev: inspect<2>,  Up: 改进的模块<2>

1.2.5.16 io
...........

在开发模式 (*note -X: 290. ‘env’) 和调试构建中，*note io.IOBase: 30c. 终
结器现在会在 ‘close()’ 方法失败时将异常写入日志。 发生的异常在发布构建中
默认会被静默忽略。 （由 Victor Stinner 在 bpo-18748(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18748


File: python.info,  Node: itertools,  Next: json tool,  Prev: io,  Up: 改进的模块<2>

1.2.5.17 itertools
..................

*note itertools.accumulate(): 30e. 函数增加了可选的 `initial' 关键字参数
用来指定一个初始值:

     >>> from itertools import accumulate
     >>> list(accumulate([10, 5, 30, 15], initial=1000))
     [1000, 1010, 1015, 1045, 1060]

（由 Lisa Roach 在 bpo-34659(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue34659


File: python.info,  Node: json tool,  Next: logging,  Prev: itertools,  Up: 改进的模块<2>

1.2.5.18 json.tool
..................

添加选项 ‘--json-lines’ 用于将每个输入行解析为单独的 JSON 对象。 （由
Weipeng Hong 在 bpo-31553(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31553


File: python.info,  Node: logging,  Next: math<2>,  Prev: json tool,  Up: 改进的模块<2>

1.2.5.19 logging
................

为 *note logging.basicConfig(): 311. 添加了 `force' 关键字参数，当设为真
值时，关联到根日志记录器的任何现有处理程序都将在执行由其他参数所指定的配
置之前被移除并关闭。

这解决了一个长期存在的问题。 当一个日志处理器或 `basicConfig()' 被调用时
，对 `basicConfig()' 的后续调用会被静默地忽略。 这导致使用交互提示符或
Jupyter 笔记本更新、试验或讲解各种日志配置选项变得相当困难。

（由 Raymond Hettinger 提议，由 Dong-hee Na 实现，并由 Vinay Sajip 在
bpo-33897(1) 中完成审核。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33897


File: python.info,  Node: math<2>,  Next: mmap,  Prev: logging,  Up: 改进的模块<2>

1.2.5.20 math
.............

添加了新的函数 *note math.dist(): 313. 用于计算两点之间的欧几里得距离。
（由 Raymond Hettinger 在 bpo-33089(1) 中贡献。）

扩展了 *note math.hypot(): 314. 函数以便处理更多的维度。 之前它仅支持
2-D 的情况。 （由 Raymond Hettinger 在 bpo-33089(2) 中贡献。）

添加了新的函数 *note math.prod(): 315. 作为的 *note sum(): 316. 同类，该
函数返回 ’start’ 值 (默认值: 1) 乘以一个数字可迭代对象的积:

     >>> prior = 0.8
     >>> likelihoods = [0.625, 0.84, 0.30]
     >>> math.prod(likelihoods, start=prior)
     0.126

（由 Pablo Galindo 在 bpo-35606(3) 中贡献。）

添加了两个新的组合函数 *note math.perm(): 317. 和 *note math.comb():
318.:

     >>> 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

（由 Yash Aggarwal, Keller Fuchs, Serhiy Storchaka 和 Raymond Hettinger
在 bpo-37128(4), bpo-37178(5) 和 bpo-35431(6) 中贡献。）

添加了一个新函数 *note math.isqrt(): 319. 用于计算精确整数平方根而无需转
换为浮点数。 该新函数支持任意大整数。 它的执行速度比 ‘floor(sqrt(n))’ 快
但是比 *note math.sqrt(): 31a. 慢:

     >>> r = 650320427
     >>> s = r ** 2
     >>> isqrt(s - 1)         # correct
     650320426
     >>> floor(sqrt(s - 1))   # incorrect
     650320427

（由 Mark Dickinson 在 bpo-36887(7) 中贡献。）

函数 *note math.factorial(): 1fc. 不再接受非整数类参数。 （由 Pablo
Galindo 在 bpo-33083(8) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33089

   (2) https://bugs.python.org/issue33089

   (3) https://bugs.python.org/issue35606

   (4) https://bugs.python.org/issue37128

   (5) https://bugs.python.org/issue37178

   (6) https://bugs.python.org/issue35431

   (7) https://bugs.python.org/issue36887

   (8) https://bugs.python.org/issue33083


File: python.info,  Node: mmap,  Next: multiprocessing<2>,  Prev: math<2>,  Up: 改进的模块<2>

1.2.5.21 mmap
.............

*note mmap.mmap: 31c. 类现在具有一个 *note madvise(): 31d. 方法用于访问
‘madvise()’ 系统调用。 （由 Zackery Spytz 在 bpo-32941(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32941


File: python.info,  Node: multiprocessing<2>,  Next: os<2>,  Prev: mmap,  Up: 改进的模块<2>

1.2.5.22 multiprocessing
........................

添加了新的 *note multiprocessing.shared_memory: bc. 模块。 （由 Davin
Potts 在 bpo-35813(1) 中贡献。）

在macOS上，现在默认使用的启动方式是*spawn*启动方式。 （由 Victor Stinner
在 bpo-33725(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35813

   (2) https://bugs.python.org/issue33725


File: python.info,  Node: os<2>,  Next: os path,  Prev: multiprocessing<2>,  Up: 改进的模块<2>

1.2.5.23 os
...........

在 Windows 上添加了新函数 *note add_dll_directory(): 2f3. 用于在导入扩展
模块或使用 *note ctypes: 2a. 加载 DLL 时为本机依赖提供额外搜索路径 。 （
由 Steve Dower 在 bpo-36085(1) 中贡献。）

添加了新的 *note os.memfd_create(): 320. 函数用于包装 ‘memfd_create()’ 系
统调用。 （由 Zackery Spytz 和 Christian Heimes 在 bpo-26836(2) 中贡献。
）

在 Windows 上，大部分用于处理重解析点,（包括符号链接和目录连接）的手动逻
辑已被委托给操作系统。 特别地，*note os.stat(): 321. 现在将会遍历操作系
统所支持的任何内容，而 *note os.lstat(): 322. 将只打开被标识为“名称代理
”的重解析点，而其要由 *note os.stat(): 321. 打开其他的重解析点。 在所有
情况下，‘stat_result.st_mode’ 将只为符号链接而非其他种类的重解析点设置
‘S_IFLNK’。 要标识其他种类的重解析点，请检查新的
‘stat_result.st_reparse_tag’ 属性。

在 Windows 上，*note os.readlink(): 1d1. 现在能够读取目录连接。 请注意
*note islink(): 323. 会对目录连接返回 ‘False’，因此首先检查 ‘islink’ 的
代码将连续把连接视为目录，而会处理 *note os.readlink(): 1d1. 所引发错误
的代码现在会把连接视为链接。

（由 Steve Dower 在 bpo-37834(3) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36085

   (2) https://bugs.python.org/issue26836

   (3) https://bugs.python.org/issue37834


File: python.info,  Node: os path,  Next: pathlib<2>,  Prev: os<2>,  Up: 改进的模块<2>

1.2.5.24 os.path
................

返回布尔值结果的 *note os.path: c5. 函数例如 *note exists(): 325, *note
lexists(): 326, *note isdir(): 327, *note isfile(): 328, *note islink():
323, 以及 *note ismount(): 329. 现在对于包含在 OS 层级无法表示的字符或字
节的路径将会返回 ‘False’ 而不是引发 *note ValueError: 16d. 或其子类
*note UnicodeEncodeError: 32a. 和 *note UnicodeDecodeError: 32b.。 （由
Serhiy Storchaka 在 bpo-33721(1) 中贡献。）

*note expanduser(): 32c. 在 Windows 上现在改用 ‘USERPROFILE’ 环境变量而
不再使用 ‘HOME’，后者通常不会为一般用户账户设置。 （由 Anthony Sottile 在
bpo-36264(2) 中贡献。）

*note isdir(): 327. 在 Windows 上将不再为不存在的目录的链接返回 ‘True’。

*note realpath(): 32d. 在 Windows 上现在会识别重解析点，包括符号链接和目
录连接。

（由 Steve Dower 在 bpo-37834(3) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33721

   (2) https://bugs.python.org/issue36264

   (3) https://bugs.python.org/issue37834


File: python.info,  Node: pathlib<2>,  Next: pickle,  Prev: os path,  Up: 改进的模块<2>

1.2.5.25 pathlib
................

返回布尔值结果的 *note pathlib.Path: 32f. 方法例如 *note exists(): 330,
*note is_dir(): 331, *note is_file(): 332, *note is_mount(): 333, *note
is_symlink(): 334, *note is_block_device(): 335, *note is_char_device():
336, *note is_fifo(): 337, *note is_socket(): 338. 现在对于包含在 OS 层
级无法表示的字符或字节的路径将会返回 ‘False’ 而不是引发 *note
ValueError: 16d. 或其子类 *note UnicodeEncodeError: 32a.。 （由 Serhiy
Storchaka 在 bpo-33721(1) 中贡献。）

添加了 *note pathlib.Path.link_to(): 339. 用于创建指向某个路径的硬链接。
（由 Joannah Nanjekye 在 bpo-26978(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33721

   (2) https://bugs.python.org/issue26978


File: python.info,  Node: pickle,  Next: plistlib,  Prev: pathlib<2>,  Up: 改进的模块<2>

1.2.5.26 pickle
...............

*note pickle: ca. 扩展子类化针对 C 优化的 *note Pickler: 33b. 现在可通过
定义特殊的 *note reducer_override(): 33c. 方法来重载函数和类的封存逻辑。
（由 Pierre Glaser 和 Olivier Grisel 在 bpo-35900(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35900


File: python.info,  Node: plistlib,  Next: pprint<2>,  Prev: pickle,  Up: 改进的模块<2>

1.2.5.27 plistlib
.................

添加了新的 *note plistlib.UID: 33e. 并启动了对读取和写入经过
NSKeyedArchiver 编码的二进制 plists 的支持。 （由 Jon Janzen 在
bpo-26707(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26707


File: python.info,  Node: pprint<2>,  Next: py_compile,  Prev: plistlib,  Up: 改进的模块<2>

1.2.5.28 pprint
...............

*note pprint: d2. 模块为一些函数添加了 `sort_dicts' 形参。 默认情况下，
这些函数会继续在渲染或打印之前对字典进行排序。 但是，如果 `sort_dicts' 设
为假值，则字典将保持键插入时的顺序。 这在调试期间与 JSON 输入进行比较时
会很有用。

除此之外，还增加了一个方便的新函数 *note pprint.pp(): 340.，它类似于
*note pprint.pprint(): 341. 但它的 `sort_dicts' 默认为 ‘False’:

     >>> 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'}

（由 Rémi Lapeyre 在 bpo-30670(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30670


File: python.info,  Node: py_compile,  Next: shlex,  Prev: pprint<2>,  Up: 改进的模块<2>

1.2.5.29 py_compile
...................

*note py_compile.compile(): 343. 现在支持静默模式。 （由 Joannah
Nanjekye 在 bpo-22640(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22640


File: python.info,  Node: shlex,  Next: shutil,  Prev: py_compile,  Up: 改进的模块<2>

1.2.5.30 shlex
..............

新增了 *note shlex.join(): 345. 函数作为 *note shlex.split(): 210. 的逆
操作。 （由 Bo Bayles 在 bpo-32102(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32102


File: python.info,  Node: shutil,  Next: socket<2>,  Prev: shlex,  Up: 改进的模块<2>

1.2.5.31 shutil
...............

*note shutil.copytree(): 347. 现在接受新的 ‘dirs_exist_ok’ 关键字参数。
（由 Josh Bronson 在 bpo-20849(1) 中贡献。）

*note shutil.make_archive(): 348. 现在对新的归档默认使用 modern pax
(POSIX.1-2001) 格式以提升可移植性和标准一致性，此特性继承自对 *note
tarfile: 101. 模块的相应更改。 （由 C.A.M. Gerlach 在 bpo-30661(2) 中贡
献。）

*note shutil.rmtree(): 349. 在 Windows 上现在会移除目录连接而不会递归地
先移除其中的内容。 （由 Steve Dower 在 bpo-37834(3) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20849

   (2) https://bugs.python.org/issue30661

   (3) https://bugs.python.org/issue37834


File: python.info,  Node: socket<2>,  Next: ssl,  Prev: shutil,  Up: 改进的模块<2>

1.2.5.32 socket
...............

添加了便捷的 *note create_server(): 34b. 和 *note has_dualstack_ipv6():
34c. 函数以自动化在创建服务器套接字时通常情况下所必须的任务，包括在同一
套接字中同时接受 IPv4 和 IPv6 连接。 （由 Giampaolo Rodolà 在
bpo-17561(1) 中贡献。）

*note socket.if_nameindex(): 34d, *note socket.if_nametoindex(): 34e. 和
*note socket.if_indextoname(): 34f. 函数已经在 Windows 上实现。 （由
Zackery Spytz 在 bpo-37007(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17561

   (2) https://bugs.python.org/issue37007


File: python.info,  Node: ssl,  Next: statistics,  Prev: socket<2>,  Up: 改进的模块<2>

1.2.5.33 ssl
............

增加了 *note post_handshake_auth: 351. 和 *note
verify_client_post_handshake(): 352. 分别启用和初始化 TLS 1.3 握手后验证
。 （由 Christian Heimes 在 bpo-34670(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue34670


File: python.info,  Node: statistics,  Next: sys<2>,  Prev: ssl,  Up: 改进的模块<2>

1.2.5.34 statistics
...................

添加了 *note statistics.fmean(): 354. 作为 *note statistics.mean(): 2ce.
的更快速的浮点数版版本。 （由 Raymond Hettinger 和 Steven D’Aprano 在
bpo-35904(1) 中贡献。）

添加了 *note statistics.geometric_mean(): 355. （由 Raymond Hettinger 在
bpo-27181(2) 中贡献。）

添加了 *note statistics.multimode(): 356. 用于返回最常见值的列表。 （由
Raymond Hettinger 在 bpo-35892(3) 中贡献。）

添加了 *note statistics.quantiles(): 357. 用于将数据或分布划分为多个等概
率区间（例如四分位、十分位或百分位）。 （由 Raymond Hettinger 在
bpo-36546(4) 中贡献。）

添加了 *note statistics.NormalDist: 358. 用于创建和操纵随机变量的正态分
布。 （由 Raymond Hettinger 在 bpo-36018(5) 中贡献。）

     >>> 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]

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35904

   (2) https://bugs.python.org/issue27181

   (3) https://bugs.python.org/issue35892

   (4) https://bugs.python.org/issue36546

   (5) https://bugs.python.org/issue36018


File: python.info,  Node: sys<2>,  Next: tarfile,  Prev: statistics,  Up: 改进的模块<2>

1.2.5.35 sys
............

添加了新的 *note sys.unraisablehook(): 35a. 函数，可被重载以便控制如何处
理“不可引发的异常”。 它会在发生了一个异常但 Python 没有办法处理时被调用
。 例如，当一个析构器在垃圾回收时 (*note gc.collect(): 35b.) 所引发的异
常。 （由 Victor Stinner 在 bpo-36829(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36829


File: python.info,  Node: tarfile,  Next: threading,  Prev: sys<2>,  Up: 改进的模块<2>

1.2.5.36 tarfile
................

*note tarfile: 101. 模块现在对新的归档默认使用 modern pax (POSIX.1-2001)
格式而不再是之前的 GNU 专属格式。 这通过标准化和可扩展格式的统一编码
(UTF-8) 提升了跨平台可移植性，还提供了其他一些益处。 （由 C.A.M. Gerlach
在 bpo-36268(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36268


File: python.info,  Node: threading,  Next: tokenize,  Prev: tarfile,  Up: 改进的模块<2>

1.2.5.37 threading
..................

添加了新的 *note threading.excepthook(): 35e. 函数用来处理未捕获的 *note
threading.Thread.run(): 35f. 异常。 它可被重载以便控制如何处理未捕获的
*note threading.Thread.run(): 35f. 异常。 （由 Victor Stinner 在
bpo-1230540(1) 中贡献。）

添加了新的 *note threading.get_native_id(): 360. 函数以及 *note
threading.Thread: 21a. 类的 *note native_id: 361. 属性。 它们会返回内核
所分配给当前线程的原生整数线程 ID。 此特性仅在特定平台上可用，参见 *note
get_native_id: 360. 了解详情。 （由 Jake Tesler 在 bpo-36084(2) 中贡献。
）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1230540

   (2) https://bugs.python.org/issue36084


File: python.info,  Node: tokenize,  Next: tkinter,  Prev: threading,  Up: 改进的模块<2>

1.2.5.38 tokenize
.................

当提供不带末尾新行的输入时，*note tokenize: 11a. 模块现在会隐式地添加
‘NEWLINE’ 形符。 此行为现在已与 C 词法分析器的内部行为相匹配。 （由
Ammar Askar 在 bpo-33899(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33899


File: python.info,  Node: tkinter,  Next: time<2>,  Prev: tokenize,  Up: 改进的模块<2>

1.2.5.39 tkinter
................

在 ‘tkinter.Spinbox’ 中添加了方法 ‘selection_from()’,
‘selection_present()’, ‘selection_range()’ 和 ‘selection_to()’。 （由
Juliette Monsel 在 bpo-34829(1) 中贡献。）

在 ‘tkinter.Canvas’ 类中添加了方法 ‘moveto()’。 （由 Juliette Monsel 在
bpo-23831(2) 中贡献。）

‘tkinter.PhotoImage’ 类现在具有 ‘transparency_get()’ 和
‘transparency_set()’ 方法。 （由 Zackery Spytz 在 bpo-25451(3) 中贡献。
）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue34829

   (2) https://bugs.python.org/issue23831

   (3) https://bugs.python.org/issue25451


File: python.info,  Node: time<2>,  Next: typing<3>,  Prev: tkinter,  Up: 改进的模块<2>

1.2.5.40 time
.............

为 macOS 10.12 添加了新的时钟 *note CLOCK_UPTIME_RAW: 365.。 （由
Joannah Nanjekye 在 bpo-35702(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35702


File: python.info,  Node: typing<3>,  Next: unicodedata<2>,  Prev: time<2>,  Up: 改进的模块<2>

1.2.5.41 typing
...............

*note typing: 122. 模块加入了一些新特性：

   * 一个带有键专属类型的字典类型。 参见 PEP 589(1) 和 *note
     typing.TypedDict: 367.。 TypedDict 只使用字符串作为键。 默认情况下
     每个键都要求提供。 指定 "total=False" 以允许键作为可选项:

          class Location(TypedDict, total=False):
              lat_long: tuple
              grid_square: str
              xy_coordinate: tuple

   * Literal 类型。 参见 PEP 586(2) 和 *note typing.Literal: 275.。
     Literal 类型指明一个形参或返回值被限定为一个或多个特定的字面值:

          def get_status(port: int) -> Literal['connected', 'disconnected']:
              ...

   * "Final" 变量、函数、方法和类。 参见 PEP 591(3), *note typing.Final:
     368. 和 *note typing.final(): 369.。 final 限定符会指示静态类型检查
     器限制进行子类化、重载或重新赋值:

          pi: Final[float] = 3.1415926536

   * 协议定义。 参见 PEP 544(4), *note typing.Protocol: 36a. 和 *note
     typing.runtime_checkable(): 36b.。 简单的 ABC 例如 *note
     typing.SupportsInt: 36c. 现在是 ‘Protocol’ 的子类。

   * 新的协议类 *note typing.SupportsIndex: 36d.。

   * 新的函数 *note typing.get_origin(): 36e. 和 *note
     typing.get_args(): 27d.。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0589

   (2) https://www.python.org/dev/peps/pep-0586

   (3) https://www.python.org/dev/peps/pep-0591

   (4) https://www.python.org/dev/peps/pep-0544


File: python.info,  Node: unicodedata<2>,  Next: unittest,  Prev: typing<3>,  Up: 改进的模块<2>

1.2.5.42 unicodedata
....................

*note unicodedata: 123. 模块现在已升级为使用 Unicode 12.1.0(1) 发布版。

新的函数 *note is_normalized(): 370. 可被用来验证字符串是否为特定正规形
式，通常会比实际进行字符串正规化要快得多。 （由 Max Belanger, David
Euresti 和 Greg Price 在 bpo-32285(2) 和 bpo-37966(3) 中贡献。）

   ---------- Footnotes ----------

   (1) http://blog.unicode.org/2019/05/unicode-12-1-en.html

   (2) https://bugs.python.org/issue32285

   (3) https://bugs.python.org/issue37966


File: python.info,  Node: unittest,  Next: venv<2>,  Prev: unicodedata<2>,  Up: 改进的模块<2>

1.2.5.43 unittest
.................

添加了 *note AsyncMock: 372. 以支持异步版本的 *note Mock: 373.。 同时也
添加了相应的断言函数用于测试。 （由 Lisa Roach 在 bpo-26467(1) 中贡献。
）

unittest 添加了 *note addModuleCleanup(): 374. 和 *note
addClassCleanup(): 375. 以支持对 ‘setUpModule()’ 和 *note setUpClass():
376. 进行清理。 （由 Lisa Roach 在 bpo-24412(2) 中贡献。）

一些模拟断言函数现在也会在失败时打印一个实际调用列表。 （由 Petter
Strandmark 在 bpo-35047(3) 中贡献。）

*note unittest: 124. 模块已支持通过 *note
unittest.IsolatedAsyncioTestCase: 377. 来使用协程作为测试用例。 （由
Andrew Svetlov 在 bpo-32972(4) 中贡献。）

示例:

     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()

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26467

   (2) https://bugs.python.org/issue24412

   (3) https://bugs.python.org/issue35047

   (4) https://bugs.python.org/issue32972


File: python.info,  Node: venv<2>,  Next: weakref,  Prev: unittest,  Up: 改进的模块<2>

1.2.5.44 venv
.............

现在 *note venv: 12e. 在所有平台上都会包含 ‘Activate.ps1’ 脚本用于在
PowerShell Core 6.1 下激活虚拟环境。 （由 Brett Cannon 在 bpo-32718(1) 中
贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32718


File: python.info,  Node: weakref,  Next: xml<2>,  Prev: venv<2>,  Up: 改进的模块<2>

1.2.5.45 weakref
................

由 *note weakref.proxy(): 37a. 返回的代理对象现在除其他算术运算符外也支
持矩阵乘法运算符 ‘@’ 和 ‘@=’。 （由 Mark Dickinson 在 bpo-36669(1) 中贡
献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36669


File: python.info,  Node: xml<2>,  Next: xmlrpc,  Prev: weakref,  Up: 改进的模块<2>

1.2.5.46 xml
............

作为对 DTD 和外部实体检索的缓解，在默认情况下 *note xml.dom.minidom:
13e. 和 *note xml.sax: 144. 模块不再处理外部实体。 （由 Christian Heimes
在 bpo-17239(1) 中贡献。）

*note xml.etree.ElementTree: 140. 模块中的 ‘.find*()’ 方法支持通配符搜索
例如 ‘{*}tag’，此搜索会忽略命名空间以及返回给定命名空间中所有标签的
‘{namespace}*’。 （由 Stefan Behnel 在 bpo-28238(2) 中贡献。）

*note xml.etree.ElementTree: 140. 模块提供了实现 C14N 2.0 的新函数
‘–xml.etree.ElementTree.canonicalize()’。 （由 Stefan Behnel 在
bpo-13611(3) 中贡献。）

*note xml.etree.ElementTree.XMLParser: 37c. 的目标对象可通过新的回调方法
‘start_ns()’ 和 ‘end_ns()’ 来接受命名空间声明事件。 此外，*note
xml.etree.ElementTree.TreeBuilder: 37d. 目标可被配置为处理有关注释和处理
指令事件以将它们包含在所生成的树当中。 （由 Stefan Behnel 在
bpo-36676(4) 和 bpo-36673(5) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17239

   (2) https://bugs.python.org/issue28238

   (3) https://bugs.python.org/issue13611

   (4) https://bugs.python.org/issue36676

   (5) https://bugs.python.org/issue36673


File: python.info,  Node: xmlrpc,  Prev: xml<2>,  Up: 改进的模块<2>

1.2.5.47 xmlrpc
...............

*note xmlrpc.client.ServerProxy: 37f. 现在支持可选的 `headers' 关键字参
数作为随同每次请求发送的 HTTP 标头序列。 此特征的作用之一是使得从默认的
基础认证升级到更快速的会话认证成为可能。 （由 Cédric Krier 在
bpo-35153(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35153


File: python.info,  Node: 性能优化<2>,  Next: 构建和 C API 的改变,  Prev: 改进的模块<2>,  Up: Python 3 8 有什么新变化

1.2.6 性能优化
--------------

   * *note subprocess: f9. 模块现在能在某些情况下使用 *note
     os.posix_spawn(): 381. 函数以获得更好的性能。 目前，它的使用仅限
     macOS 和 Linux（使用 glibc 2.24 或更新版本），并要求满足以下条件：

        * `close_fds' 为假值；

        * `preexec_fn', `pass_fds', `cwd' 和 `start_new_session' 形参未
          设置；

        * `executable' 路径包含一个目录。

     （由 Joannah Nanjekye 和 Victor Stinner 在 bpo-35537(1) 中贡献。）

   * *note shutil.copyfile(): 382, *note shutil.copy(): 383, *note
     shutil.copy2(): 384, *note shutil.copytree(): 347. 和 *note
     shutil.move(): 385. 在 Linux 和 macOS 上会使用平台专属的
     "fast-copy" 系统调用以提高效率。 "fast-copy" 意味着拷贝操作发生于内
     核中，从而避免在进行 "‘outfd.write(infd.read())’" 等操作时使用
     Python 中的用户空间缓冲区。 在 Windows 上 *note shutil.copyfile():
     382. 会使用更大的默认缓冲区（1 MiB 而不是 16 KiB）并且使用基于
     *note memoryview(): 386. 的 *note shutil.copyfileobj(): 387. 版本。
     在同一分区内拷贝一个 512 MiB 文件的速度提升在 Linux 上约为 +26%，在
     macOS 上为 +50%，在 Windows 上为 +40%。 此外还将消耗更少的 CPU 周期
     。 参见 *note 依赖于具体平台的高效拷贝操作: 388. 一节。 （由
     Giampaolo Rodolà 在 bpo-33671(2) 中贡献。）

   * *note shutil.copytree(): 347. 会根据其所用缓存的 *note os.stat():
     321. 值使用 *note os.scandir(): 389. 函数及所有拷贝函数。 拷贝一个
     包含 8000 文件的目录的速度提升在 Linux 上约为 +9%，在 Windows 上为
     +20%，对于 Windows SMB 共享目录则为 +30%。 此外 *note os.stat():
     321. 系统调用的次数也减少了 38%，使得 *note shutil.copytree(): 347.
     在网络文件系统上会特别快速。 （由Giampaolo Rodolà 在 bpo-33695(3) 中
     贡献。）

   * *note pickle: ca. 模块使用的默认协议现在为 Protocol 4，最早在
     Python 3.4 中被引入。 它提供了比自 Python 3.0 起可用的 Protocol 3 更
     好的性能和更小的数据尺寸。

   * 从 ‘PyGC_Head’ 移除了一个 ‘Py_ssize_t’ 成员。 所有跟踪 GC 的对象（
     例如 tuple, list, dict）大小减少了 4 或 8 字节。 （由 Inada Naoki 在
     bpo-33597(4) 中贡献。）

   * *note uuid.UUID: 38a. 现在会使用 ‘__slots__’ 以减少内存足迹。 （由
     Wouter Bolsterlee 和 Tal Einat 在 bpo-30977(5) 中贡献。）

   * *note operator.itemgetter(): 38b. 的性能提升了 33%。 优化了参数处理
     ，并为常见的在元组中单个非负整数索引的情况新增了一条快速路径（这是
     标准库中的典型用例）。 （由 Raymond Hettinger 在 bpo-35664(6) 中贡
     献。

   * 加快了在 *note collections.namedtuple(): 1a1. 中的字段查找。 它们现
     在的速度快了两倍以上，成为 Python 中最快的实例变量查找形式。 （由
     Raymond Hettinger, Pablo Galindo 和 Joe Jevnik, Serhiy Storchaka 在
     bpo-32492(7) 中贡献。）

   * 如果输入的可迭代对象的长度已知 (即输入对象实现了 ‘__len__’)，*note
     list: 1f8. 构造器不会过度分配内部项缓冲区。 这使得所创建的列表资源
     占用平均减少了 12%。 （由 Raymond Hettinger 和 Pablo Galindo 在
     bpo-33234(8) 中贡献。）

   * 类变量写入速度加倍。 当一个非冗余属性被更新时，之前存在一个更新
     slots 的非必要调用。 （由 Stefan Behnel, Pablo Galindo Salgado,
     Raymond Hettinger, Neil Schemenauer, 和 Serhiy Storchaka 在
     bpo-36012(9) 中贡献。）

   * 减少了传递给许多内置函数和方法的参数转换的开销。 这使得某些简单内置
     函数和方法的速度提升了 20–50%。 （由 Serhiy Storchaka 在
     bpo-23867(10), bpo-35582(11) 和 bpo-36127(12) 中贡献。）

   * ‘LOAD_GLOBAL’ 指令现在会使用新的 "per opcode cache" 机制。 它的速度
     现在提升了大约 40%。 （由 Yury Selivanov 和 Inada Naoki 在
     bpo-26219(13) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35537

   (2) https://bugs.python.org/issue33671

   (3) https://bugs.python.org/issue33695

   (4) https://bugs.python.org/issue33597

   (5) https://bugs.python.org/issue30977

   (6) https://bugs.python.org/issue35664

   (7) https://bugs.python.org/issue32492

   (8) https://bugs.python.org/issue33234

   (9) https://bugs.python.org/issue36012

   (10) https://bugs.python.org/issue23867

   (11) https://bugs.python.org/issue35582

   (12) https://bugs.python.org/issue36127

   (13) https://bugs.python.org/issue26219


File: python.info,  Node: 构建和 C API 的改变,  Next: 弃用<2>,  Prev: 性能优化<2>,  Up: Python 3 8 有什么新变化

1.2.7 构建和 C API 的改变
-------------------------

   * 默认的 *note sys.abiflags: 38d. 成为一个空字符串：pymalloc 的 ‘m’ 旗
     标不再有意义（无论是否启用 pymalloc 构建都是兼容 ABI 的）因此已被移
     除。 （由 Victor Stinner 在 bpo-36707(1) 中贡献。）

     改变的例子：

        * 只会安装 ‘python3.8’ 程序，不再有 ‘python3.8m’ 程序。

        * 只会安装 ‘python3.8-config’ 脚本，不再有 ‘python3.8m-config’ 脚
          本。

        * ‘m’ 旗标已经从动态库文件名后缀中移除：包括标准库中的扩展模块以
          及第三方包所产生和安装的模块例如从 PyPI 下载的模块。 以 Linux
          为例，Python 3.7 的后缀 ‘.cpython-37m-x86_64-linux-gnu.so’ 在
          Python 3.8 中改为 ‘.cpython-38-x86_64-linux-gnu.so’。

   * 重新组织了所有头文件以更好地区分不同种类的 API：

        * ‘Include/*.h’ 应为可移植的公有稳定版 C API。

        * ‘Include/cpython/*.h’ 应为 CPython 专属的不稳定版 C API；公有
          API，部分私有 API 附加 ‘_Py’ or ‘_PY’ 前缀。

        * ‘Include/internal/*.h’ 应为 CPython 特别专属的私有内部 C API。
          此 API 不具备向下兼容保证并且不应在 CPython 以外被使用。 它们
          的公开仅适用于特别限定的需求例如调试器和性能分析等必须直接访问
          CPython 内部数据而不通过调用函数的应用。 此 API 现在是通过
          ‘make install’ 安装的。

     （由 Victor Stinner 在 bpo-35134(2) 和 bpo-35081(3) 中贡献，相关工
     作由 Eric Snow 在 Python 3.7 中发起。）

   * 某些宏已被转换为静态内联函数：形参类型和返回类型定义良好，它们不再
     会有与宏相关的问题，变量具有局部作用域。 例如：

        * *note Py_INCREF(): 38e, *note Py_DECREF(): 38f.

        * *note Py_XINCREF(): 390, *note Py_XDECREF(): 391.

        * ‘PyObject_INIT()’, ‘PyObject_INIT_VAR()’

        * 私有函数: ‘_PyObject_GC_TRACK()’, ‘_PyObject_GC_UNTRACK()’,
          ‘_Py_Dealloc()’

     （由 Victor Stinner 在 bpo-35059(4) 中贡献。）

   * ‘PyByteArray_Init()’ 和 ‘PyByteArray_Fini()’ 函数已被移除。 它们自
     Python 2.7.4 和 Python 3.2.0 起就没有任何用处，被排除在受限 API (稳
     定版 ABI) 之外，并且未被写入文档。 （由 Victor Stinner 在
     bpo-35713(5) 中贡献。）

   * ‘PyExceptionClass_Name()’ 的结果类型现在是 ‘const char *’ 而非
     ‘char *’。 （由 Serhiy Storchaka 在 bpo-33818(6) 中贡献。）

   * ‘Modules/Setup.dist’ 与 ‘Modules/Setup’ 两者的共存已被移除。 之前在
     更新 CPython 源码树时，开发者必须手动拷贝 ‘Modules/Setup.dist’ (在
     源码树内) 到 ‘Modules/Setup’ (在构建树内) 以反映上游的任何改变。 旧
     特性对打包者来说有一点益处，但代价是对追踪 CPython 开发进程的开发者
     造成经常性的麻烦，因为忘记拷贝该文件可能导致构建失败。

     现在构建系统总是会从源码树内的 ‘Modules/Setup’ 读取数据。 建议希望
     定制该文件的开发者在 CPython 的一个 git 分叉或补丁文件中维护他们的
     更改，就如他们对源码树做任何其他改变时一样。

     （由 Antoine Pitrou 在 bpo-32430(7) 中贡献。）

   * 将 Python 数字转换为 C 整型的函数例如 *note PyLong_AsLong(): 392. 以
     及带有 ‘'i'’ 之类整型转换格式单元的参数解析函数例如 *note
     PyArg_ParseTuple(): 393. 现在如果可能将会使用 *note __index__():
     2c2. 特殊方法而不是 *note __int__(): 2c3.。 对于带有 ‘__int__()’ 方
     法但没有 ‘__index__()’ 方法的对象 (例如 *note Decimal: 2c0. 和
     *note Fraction: 2be.) 将会发出弃用警告。 对于实现了 ‘__index__()’ 的
     对象 *note PyNumber_Check(): 394. 现在将返回 ‘1’。 *note
     PyNumber_Long(): 395, *note PyNumber_Float(): 396. 和 *note
     PyFloat_AsDouble(): 397. 现在如果可能也将会使用 ‘__index__()’ 方法
     。 （由 Serhiy Storchaka 在 bpo-36048(8) 和 bpo-20092(9) 中贡献。）

   * 堆分配类型对象现在将增加它们在 *note PyObject_Init(): 398. (及其对
     应的宏 ‘PyObject_INIT’) 中的引用计数而不是在 *note
     PyType_GenericAlloc(): 399. 中。 修改实例分配或中止分配的类型可能需
     要进行调整。 （由 Elizondo 在 bpo-35810(10) 中贡献。）

   * 新增函数 *note PyCode_NewWithPosOnlyArgs(): 39a. 允许创建代码对象例
     如 *note PyCode_New(): 39b.，但带有一个额外的 `posonlyargcount' 形
     参以指明仅限位置参数的数量。 （由 Pablo Galindo 在 bpo-37221(11) 中
     贡献。）

   * *note Py_SetPath(): 39c. 现在会将 *note sys.executable: 39d. 设为程
     序完整路径 (*note Py_GetProgramFullPath(): 39e.) 而不是程序名称
     (*note Py_GetProgramName(): 39f.)。 （由 Victor Stinner 在
     bpo-38234(12) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36707

   (2) https://bugs.python.org/issue35134

   (3) https://bugs.python.org/issue35081

   (4) https://bugs.python.org/issue35059

   (5) https://bugs.python.org/issue35713

   (6) https://bugs.python.org/issue33818

   (7) https://bugs.python.org/issue32430

   (8) https://bugs.python.org/issue36048

   (9) https://bugs.python.org/issue20092

   (10) https://bugs.python.org/issue35810

   (11) https://bugs.python.org/issue37221

   (12) https://bugs.python.org/issue38234


File: python.info,  Node: 弃用<2>,  Next: API 与特性的移除,  Prev: 构建和 C API 的改变,  Up: Python 3 8 有什么新变化

1.2.8 弃用
----------

   * distutils 的 ‘bdist_wininst’ 命令现在已弃用，请改用 ‘bdist_wheel’
     (wheel 包)。 （由 Victor Stinner 在 bpo-37481(1) 中贡献。）

   * *note ElementTree: 140. 模块中的已弃用方法 ‘getchildren()’ 和
     ‘getiterator()’ 现在会引发 *note DeprecationWarning: 15a. 而不是
     *note PendingDeprecationWarning: 15c.。 它们将在 Python 3.9 中被移
     除。 （由 Serhiy Storchaka 在 bpo-29209(2) 中贡献。）

   * 将不是 *note concurrent.futures.ThreadPoolExecutor: 18c. 的实例的对
     象传给 *note loop.set_default_executor(): 3a1. 已被弃用，并将在
     Python 3.9 中被禁止。 （由 Elvis Pranskevichus 在 bpo-34075(3) 中贡
     献。）

   * *note xml.dom.pulldom.DOMEventStream: 3a2, *note
     wsgiref.util.FileWrapper: 3a3. 和 *note fileinput.FileInput: 3a4. 的
     *note __getitem__(): 3a5. 方法已被弃用。

     这些方法的实现会忽略它们的 `index' 形参，并改为返回下一条目。 （由
     Berker Peksag 在 bpo-9372(4) 中贡献。）

   * *note typing.NamedTuple: 227. 类已弃用了 ‘_field_types’ 属性而改用
     具有同样信息的 ‘__annotations__’ 属性。 （由 Raymond Hettinger 在
     bpo-36320(5) 中贡献。）

   * *note ast: 7. 类 ‘Num’, ‘Str’, ‘Bytes’, ‘NameConstant’ 和
     ‘Ellipsis’ 被视为已弃用并将在未来的 Python 版本中被移除。 应当改用
     *note Constant: 3a6.。 （由 Serhiy Storchaka 在 bpo-32892(6) 中贡献
     。）

   * *note ast.NodeVisitor: 3a7. 的方法 ‘visit_Num()’, ‘visit_Str()’,
     ‘visit_Bytes()’, ‘visit_NameConstant()’ 和 ‘visit_Ellipsis()’ 现在
     已被弃用，并且在未来的 Python 版本中将不再被调用。 添加
     ‘visit_Constant()’ 方法来处理所有常量节点。 （由 Serhiy Storchaka 在
     bpo-36917(7) 中贡献。）

   * *note asyncio.coroutine(): 3a8. *note decorator: 174. 已弃用并将在
     3.10 版中被移除。 原有的 ‘@asyncio.coroutine’ 请改用 *note async
     def: 3a9. 来替代。 （由 Andrew Svetlov 在 bpo-36921(8) 中贡献。）

   * 在 *note asyncio: 9. 中，`loop' 参数的显式传递已被弃用并且到 3.10 版
     时将会在以下函数中被移除: *note asyncio.sleep(): 3aa, *note
     asyncio.gather(): 3ab, *note asyncio.shield(): 3ac, *note
     asyncio.wait_for(): 191, *note asyncio.wait(): 207, *note
     asyncio.as_completed(): 3ad, *note asyncio.Task: 2e0, *note
     asyncio.Lock: 3ae, *note asyncio.Event: 3af, *note
     asyncio.Condition: 3b0, *note asyncio.Semaphore: 3b1, *note
     asyncio.BoundedSemaphore: 3b2, *note asyncio.Queue: 3b3, *note
     asyncio.create_subprocess_exec(): 3b4. 以及 *note
     asyncio.create_subprocess_shell(): 3b5.。

   * 将协程对象显式传递给 *note asyncio.wait(): 207. 的做法已被弃用并且
     将在 3.11 版中被移除。 （由 Yury Selivanov 在 bpo-34790(9) 中贡献。
     ）

   * *note gettext: 87. 模块中的下列函数和方法已被弃用: *note
     lgettext(): 3b6, *note ldgettext(): 3b7, *note lngettext(): 3b8. 和
     *note ldngettext(): 3b9.。 它们返回已编码的字节串，如果转换后的字符
     串存在编码问题你将可能遭遇预期之外的异常。 更好的做法是使用 Python
     3 中返回 Unicode 字符串的操作作为替代。 前面的函数都早已不宜使用。

     函数 *note bind_textdomain_codeset(): 3ba.，方法 *note
     output_charset(): 3bb. 和 *note set_output_charset(): 3bc.，以及函
     数 *note translation(): 3bd. 和 *note install(): 3be. 的 `codeset'
     形参也已被弃用，因为它们仅适用于 ‘l*gettext()’ 函数。 （由 Serhiy
     Storchaka 在 bpo-33710(10) 中贡献。）

   * *note threading.Thread: 21a. 的 ‘isAlive()’ 方法已弃用。 （由
     Dong-hee Na 在 bpo-35283(11) 中贡献。）

   * 许多接受整数参数的内置和扩展模块的函数现在将对传入 *note Decimal:
     2c0, *note Fraction: 2be. 以及任何其他可被转换为整数但会丢失精度（
     即具有 *note __int__(): 2c3. 方法但没有 *note __index__(): 2c2. 方
     法）的对象发出弃用警告。 在未来的版本中则将报错。 （由 Serhiy
     Storchaka 在 bpo-36048(12) 中贡献。）

   * 以下参数作为关键字参数传递的方式已被弃用：

        - *note functools.partialmethod(): 3bf, *note
          weakref.finalize(): 3c0, *note profile.Profile.runcall(): 3c1,
          ‘cProfile.Profile.runcall()’, *note bdb.Bdb.runcall(): 3c2,
          *note trace.Trace.runfunc(): 3c3. 与 *note curses.wrapper():
          3c4. 中的 `func'。

        - *note unittest.TestCase.addCleanup(): 3c5. 中的 `function'。

        - *note concurrent.futures.ThreadPoolExecutor: 18c. 和 *note
          concurrent.futures.ProcessPoolExecutor: 196. 的 *note
          submit(): 3c6. 方法中的 `fn'。

        - *note contextlib.ExitStack.callback(): 3c7,
          ‘contextlib.AsyncExitStack.callback()’ 和 *note
          contextlib.AsyncExitStack.push_async_callback(): 3c8. 中的
          `callback'。

        - ‘multiprocessing.managers.Server’ 和
          ‘multiprocessing.managers.SharedMemoryServer’ 的 ‘create()’ 方
          法中的 `c' 和 `typeid'。

        - *note weakref.finalize(): 3c0. 中的 `obj'。

     在未来版本的 Python 中，它们将成为 *note 仅限位置参数: 3c9.。 （由
     Serhiy Storchaka 在 bpo-36492(13) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37481

   (2) https://bugs.python.org/issue29209

   (3) https://bugs.python.org/issue34075

   (4) https://bugs.python.org/issue9372

   (5) https://bugs.python.org/issue36320

   (6) https://bugs.python.org/issue32892

   (7) https://bugs.python.org/issue36917

   (8) https://bugs.python.org/issue36921

   (9) https://bugs.python.org/issue34790

   (10) https://bugs.python.org/issue33710

   (11) https://bugs.python.org/issue35283

   (12) https://bugs.python.org/issue36048

   (13) https://bugs.python.org/issue36492


File: python.info,  Node: API 与特性的移除,  Next: 移植到 Python 3 8,  Prev: 弃用<2>,  Up: Python 3 8 有什么新变化

1.2.9 API 与特性的移除
----------------------

下列特性与 API 已从 Python 3.8 中移除：

   * 自 Python 3.3 起，从 *note collections: 1d. 导入 ABC 的做法已弃用，
     而应当从 *note collections.abc: 1e. 执行导入。 从 collections 导入
     的操作在 3.8 中已标记为被移除，但将推迟到 3.9 中实施。 （参见
     bpo-36952(1)。）

   * ‘macpath’ 模块，在 Python 3.7 中弃用，现已被移除。 （由 Victor
     Stinner 在 bpo-35471(2) 中贡献。）

   * 函数 ‘platform.popen()’ 已被移除，它自 Python 3.3 起就已被弃用：请
     改用 *note os.popen(): 3cb.。 （由 Victor Stinner 在 bpo-35345(3) 中
     贡献。）

   * 函数 ‘time.clock()’ 已被移除，它自 Python 3.3 起就已被弃用：请根据
     具体需求改用 *note time.perf_counter(): 3cc. 或 *note
     time.process_time(): 3cd. 以获得具有良好定义的行为。 （由 Matthias
     Bussonnier 在 bpo-36895(4) 中贡献。）

   * ‘pyvenv’ 脚本已被移除，推荐改用 ‘python3.8 -m venv’ 来帮助消除容易
     混淆 ‘pyvenv’ 脚本所关联的 Python 解释器这一问题。 （由 Brett
     Cannon 在 bpo-25427(5) 中贡献。）

   * ‘parse_qs’, ‘parse_qsl’ 和 ‘escape’ 已从 *note cgi: 15. 模块中被移
     除。 这些函数自 Python 3.2 或更早就已被弃用。 它们应改为从
     ‘urllib.parse’ 和 ‘html’ 模块导入。

   * ‘filemode’ 函数已从 *note tarfile: 101. 模块中被移除。 该函数未被写
     入文档，自 Python 3.3 起就已弃用。

   * *note XMLParser: 37c. 构造器不再接受 `html' 参数。 它从来没有任何作
     用并在 Python 3.4 中已被弃用。 所有其他形参现在都是 *note
     仅限关键字参数: 3ce.。 （由 Serhiy Storchaka 在 bpo-29209(6) 中贡献
     。）

   * *note XMLParser: 37c. 的 ‘doctype()’ 方法已被移除。 （由 Serhiy
     Storchaka 在 bpo-29209(7) 中贡献。）

   * "unicode_internal" 编解码器已被移除。 （由 Inada Naoki 在
     bpo-36297(8) 中贡献。）

   * *note sqlite3: f2. 模块的 ‘Cache’ 和 ‘Statement’ 对象已不再公开给用
     户。 （由 Aviv Palivoda 在 bpo-30262(9) 中贡献。）

   * *note fileinput.input(): 3cf. 和 *note fileinput.FileInput(): 3a4.
     中自 Python 3.6 起就已被忽略并弃用的 ‘bufsize’ 关键字参数已被移除。
     由 Matthias Bussonnier 在 bpo-36952(10) 中贡献。）

   * 在 Python 3.7 中弃用的函数 ‘sys.set_coroutine_wrapper()’ 和
     ‘sys.get_coroutine_wrapper()’ 已被移除。 （由 Matthias Bussonnier 在
     bpo-36933(11) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36952

   (2) https://bugs.python.org/issue35471

   (3) https://bugs.python.org/issue35345

   (4) https://bugs.python.org/issue36895

   (5) https://bugs.python.org/issue25427

   (6) https://bugs.python.org/issue29209

   (7) https://bugs.python.org/issue29209

   (8) https://bugs.python.org/issue36297

   (9) https://bugs.python.org/issue30262

   (10) https://bugs.python.org/issue36952

   (11) https://bugs.python.org/issue36933


File: python.info,  Node: 移植到 Python 3 8,  Next: Python 3 8 1 中的重要变化,  Prev: API 与特性的移除,  Up: Python 3 8 有什么新变化

1.2.10 移植到 Python 3.8
------------------------

本节列出了先前描述的更改以及可能需要更改代码的其他错误修正.

* Menu:

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


File: python.info,  Node: Python 行为的改变,  Next: 更改的Python API,  Up: 移植到 Python 3 8

1.2.10.1 Python 行为的改变
..........................

   * yield 表达式（包括 ‘yield’ 和 ‘yield from’ 子句）现在不允许在推导式
     和生成器表达式中使用（但 ‘for’ 子句最左边的可迭代对象表达式除外）。
     （由 Serhiy Storchaka 在 bpo-10544(1) 中贡献。）

   * 当标识号检测 (‘is’ 和 ‘is not’) 与特定类型的字面值 (例如字符串和数
     字) 一同使用时编译器现在会产生 *note SyntaxWarning: 2c9.。 这在
     CPython 中通常是可行的，但并不被语言定义所保证。 该警告会建议用户改
     用相等性检测 (‘==’ and ‘!=’)。 （由 Serhiy Storchaka 在
     bpo-34850(2) 中贡献。）

   * CPython 解释器在某些情况下可以忽略异常。 在 Python 3.8 中这种情况会
     更少发生。 特别地，从类型字典获取属性时引发的异常不会再被忽略。 （
     由 Serhiy Storchaka 在 bpo-35459(3) 中贡献。）

   * 从内置类型 *note bool: 2bd, *note int: 204, *note float: 1fd, *note
     complex: 2c1. 和标准库的一些类中移除了 ‘__str__’ 实现。 它们现在会
     从 *note object: 3d2. 继承 ‘__str__()’。 作为结果，在这些类的子类中
     定义 ‘__repr__()’ 方法将会影响它们的字符串表示。 （由 Serhiy
     Storchaka 在 bpo-36793(4) 中贡献。）

   * 在 AIX 上，*note sys.platform: 3d3. 将不再包含主要版本号。 它将总是
     ‘'aix'’ 而不再是 ‘'aix3'’ ..  ‘'aix7'’。 由于较旧的 Python 版本会包
     含该版本号，因此推荐总是使用 ‘sys.platform.startswith('aix')’。 （
     由 M. Felt 在 bpo-36588(5) 中贡献。）

   * 现在 *note PyEval_AcquireLock(): 3d4. 和 *note
     PyEval_AcquireThread(): 3d5. 如果当解释器终结化时被调用将会终结当前
     线程，以使它们与 *note PyEval_RestoreThread(): 3d6, *note
     Py_END_ALLOW_THREADS(): 3d7. 以及 *note PyGILState_Ensure(): 3d8. 保
     持一致。 如果不想要这样的行为，请通过检测 ‘_Py_IsFinalizing()’ 或
     ‘sys.is_finalizing()’ 来保护该调用。 （由 Joannah Nanjekye 在
     bpo-36475(6) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10544

   (2) https://bugs.python.org/issue34850

   (3) https://bugs.python.org/issue35459

   (4) https://bugs.python.org/issue36793

   (5) https://bugs.python.org/issue36588

   (6) https://bugs.python.org/issue36475


File: python.info,  Node: 更改的Python API,  Next: C API 中的改变,  Prev: Python 行为的改变,  Up: 移植到 Python 3 8

1.2.10.2 更改的Python API
.........................

   * 在 Windows 上 *note os.getcwdb(): 3da. 函数现在会使用 UTF-8 编码格
     式而不是 ANSI 代码页：请参看 PEP 529(1) 了解具体原因。 该函数在
     Windows 上不再被弃用。 （由 Victor Stinner 在 bpo-37412(2) 中贡献。
     ）

   * 现在 *note subprocess.Popen: 3db. 在某些情况下会使用 *note
     os.posix_spawn(): 381. 以获得更好的性能。 在适用于 Linux 的 Windows
     子系统和 QEMU 用户模拟器上，使用 *note os.posix_spawn(): 381. 的
     ‘Popen’ 构造器不会再因为“找不到程序”这样的错误引发异常。 而是让子进
     程失败并返回一个非零的 ‘returncode’。 （由 Joannah Nanjekye 和
     Victor Stinner 在 bpo-35537(3) 中贡献。）

   * The `preexec_fn' argument of * *note subprocess.Popen: 3db. is no
     longer compatible with subinterpreters.  The use of the parameter
     in a subinterpreter now raises *note RuntimeError: 3dc.
     (Contributed by Eric Snow in bpo-34651(4), modified by Christian
     Heimes in bpo-37951(5).)

   * ‘imap.IMAP4.logout()’ 方法不会再静默地忽略任意异常。 （由 Victor
     Stinner 在 bpo-36348(6) 中贡献。）

   * 函数 ‘platform.popen()’ 已被移除，它自 Python 3.3 起就已被弃用：请
     改用 *note os.popen(): 3cb.。 （由 Victor Stinner 在 bpo-35345(7) 中
     贡献。）

   * 当传入多模数据时 *note statistics.mode(): 3dd. 函数不会再引发异常。
     它将改为返回在输入数据中遇到的第一个模式。 （由 Raymond Hettinger 在
     bpo-35892(8) 中贡献。）

   * *note tkinter.ttk.Treeview: 3de. 类的 *note selection(): 3df. 方法
     不再接受参数。 带参数调用该方法来改变选择在 Python 3.6 中已弃用。 请
     使用专门方法例如 *note selection_set(): 3e0. 来改变选择。 （由
     Serhiy Storchaka 在 bpo-31508(9) 中贡献。）

   * *note xml.dom.minidom: 13e. 的 ‘writexml()’, ‘toxml()’ 和
     ‘toprettyxml()’ 方法以及 ‘xml.etree’ 的 ‘write()’ 方法现在会保留用
     户指定的属性顺序。 （由 Diego Rojas 和 Raymond Hettinger 在
     bpo-34160(10) 中贡献。）

   * 附带 ‘'r'’ 旗标打开的 *note dbm.dumb: 32. 数据库现在将是只读的。 如
     果数据库不存在，附带 ‘'r'’ 和 ‘'w'’ 旗标的 *note dbm.dumb.open():
     3e1. 不会再创建数据库。 （由 Serhiy Storchaka 在 bpo-32749(11) 中贡
     献。）

   * 在 *note XMLParser: 37c. 的子类中定义的 ‘doctype()’ 方法将不会再被
     调用，并将导致发出 *note RuntimeWarning: 3e2. 而不是 *note
     DeprecationWarning: 15a.。 请在目标上定义 *note doctype(): 3e3. 方
     法来处理 XML doctype 声明。 （由 Serhiy Storchaka 在 bpo-29209(12)
     中贡献。）

   * 现在当自定义元类未在传给 ‘type.__new__’ 的命名空间中提供
     ‘__classcell__’ 入口时将引发 *note RuntimeError: 3dc.。 在 Python
     3.6–3.7 中是则是引发 *note DeprecationWarning: 15a.。 （由 Serhiy
     Storchaka 在 bpo-23722(13) 中贡献。）

   * ‘cProfile.Profile’ 类现在可被用作上下文管理器。 （由 Scott
     Sanderson 在 bpo-29235(14) 中贡献。）

   * *note shutil.copyfile(): 382, *note shutil.copy(): 383, *note
     shutil.copy2(): 384, *note shutil.copytree(): 347. 和 *note
     shutil.move(): 385. 会使用平台专属的 "fast-copy" 系统调用（参见
     *note 依赖于具体平台的高效拷贝操作: 388. 一节）。

   * *note shutil.copyfile(): 382. 在 Windows 上的默认缓冲区大小从 16
     KiB 改为 1 MiB。

   * ‘PyGC_Head’ 结构已被完全改变。 所有接触到该结构的代码都应当被重写。
     （参见 bpo-33597(15)。）

   * *note PyInterpreterState: 3e4. 结构已被移入 "internal" 头文件（特别
     是 Include/internal/pycore_pystate.h）。 不透明的
     ‘PyInterpreterState’ 作为仅有 API（以及稳定版 ABI）的一部分仍然可用
     。 文档指明该结构的任何字段都不是公有的，因此我们希望没人在使用它们
     。 但是，如果你确实依赖其中某一个或更多个私有字段并且没有其他替代选
     项，则请开一个 BPO 问题。 我们将尽力帮助你进行调整（可能包括向公有
     API 添加访问器函数）。 （参见 bpo-35886(16)。）

   * 现在所有平台下的 *note mmap.flush(): 3e5. 方法都会在成功时返回
     ‘None’ 并在错误时引发异常。 之前它的行为取决于具体平台： Windows 下
     会在成功时返回非零值；在失败时返回零。 Unix 下会在成功时返回零；在
     失败时引发错误。 （由 Berker Peksag 在 bpo-2122(17) 中贡献。）

   * *note xml.dom.minidom: 13e. 和 *note xml.sax: 144. 模块默认将不再处
     理外部实体。 （由 Christian Heimes 在 bpo-17239(18) 中贡献。）

   * 从只读的 *note dbm: 31. 数据库 (*note dbm.dumb: 32, *note dbm.gnu:
     33. 或 *note dbm.ndbm: 34.) 删除键将会引发 ‘error’ (*note
     dbm.dumb.error: 3e6, *note dbm.gnu.error: 3e7. 或 *note
     dbm.ndbm.error: 3e8.) 而不是 *note KeyError: 3e9.。 （由 Xiang
     Zhang 在 bpo-33106(19) 中贡献。）

   * 简化了字面值的 AST。 所有常量将被表示为 *note ast.Constant: 3a6. 的
     实例。 实例化旧类 ‘Num’, ‘Str’, ‘Bytes’, ‘NameConstant’ 和
     ‘Ellipsis’ 都将返回 ‘Constant’ 的实例。 （由 Serhiy Storchaka 在
     bpo-32892(20) 中贡献。）

   * *note expanduser(): 32c. 在 Windows 上现在改用 ‘USERPROFILE’ 环境变
     量而不再使用 ‘HOME’，后者通常不会为一般用户账户设置。 （由 Anthony
     Sottile 在 bpo-36264(21) 中贡献。）

   * 异常 *note asyncio.CancelledError: 2da. 现在继承自 *note
     BaseException: 2db. 而不是 *note Exception: 2dc. 并且不再继承自
     *note concurrent.futures.CancelledError: 2dd.。 （由 Yury Selivanov
     在 bpo-32528(22) 中贡献。）

   * 当使用 *note asyncio.Task: 2e0. 的实例时，函数 *note
     asyncio.wait_for(): 191. 现在会正确地等待撤销。 在此之前当达到
     `timeout' 时，它会被撤销并立即返回。 （由 Elvis Pranskevichus 在
     bpo-32751(23) 中贡献。）

   * 当将 ’socket’ 作为 `name' 形参传入时，函数 *note
     asyncio.BaseTransport.get_extra_info(): 3ea. 现在会返回一个可安全使
     用的套接字对象。 （由 Yury Selivanov 在 bpo-37027(24) 中贡献。）

   * *note asyncio.BufferedProtocol: 3eb. 已经晋级为稳定 API。

   * 在 Windows 上对扩展模块的 DLL 依赖以及通过 *note ctypes: 2a. 加载的
     DLL 的解析现在将更为安全。 只有系统路径、包含相信 DLL 或 PYD 文件的
     路径以及通过 *note add_dll_directory(): 2f3. 添加的目录才会被作为加
     载时依赖的搜索位置。 特别地， ‘PATH’ 和当前工作目录将不再被使用，对
     它们的修改将不再对正常的 DLL 解析产生影响。 如果你的应用依赖于这些
     机制，你应当先检查 *note add_dll_directory(): 2f3.，如果它存在就用
     它在加载你的库时添加你的 DLL 目录。 请注意 Windows 7 用户还需要确保
     Windows 更新包 KB2533623 已安装（这一点也会由安装器进行验证）。 （
     由 Steve Dower 在 bpo-36085(25) 中贡献。）

   * 关联到 pgen 的头文件和函数在其被纯 Python 实现取代后已被移除。 （由
     Pablo Galindo 在 bpo-36623(26) 中贡献。）

   * *note types.CodeType: 2cd. 在构造器的第二个位置新增了一个形参
     (`posonlyargcount') 以支持在 PEP 570(27) 中定义的仅限位置参数。 第
     一个参数 (`argcount') 现在表示位置参数的总数量 (包括仅限位置参数)。
     *note types.CodeType: 2cd. 中新增的 ‘replace()’ 方法可用于让代码支
     持 future 特性。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0529

   (2) https://bugs.python.org/issue37412

   (3) https://bugs.python.org/issue35537

   (4) https://bugs.python.org/issue34651

   (5) https://bugs.python.org/issue37951

   (6) https://bugs.python.org/issue36348

   (7) https://bugs.python.org/issue35345

   (8) https://bugs.python.org/issue35892

   (9) https://bugs.python.org/issue31508

   (10) https://bugs.python.org/issue34160

   (11) https://bugs.python.org/issue32749

   (12) https://bugs.python.org/issue29209

   (13) https://bugs.python.org/issue23722

   (14) https://bugs.python.org/issue29235

   (15) https://bugs.python.org/issue33597

   (16) https://bugs.python.org/issue35886

   (17) https://bugs.python.org/issue2122

   (18) https://bugs.python.org/issue17239

   (19) https://bugs.python.org/issue33106

   (20) https://bugs.python.org/issue32892

   (21) https://bugs.python.org/issue36264

   (22) https://bugs.python.org/issue32528

   (23) https://bugs.python.org/issue32751

   (24) https://bugs.python.org/issue37027

   (25) https://bugs.python.org/issue36085

   (26) https://bugs.python.org/issue36623

   (27) https://www.python.org/dev/peps/pep-0570


File: python.info,  Node: C API 中的改变,  Next: CPython 字节码的改变<2>,  Prev: 更改的Python API,  Up: 移植到 Python 3 8

1.2.10.3 C API 中的改变
.......................

   * *note PyCompilerFlags: 3ee. 结构体添加了一个新的
     `cf_feature_version' 字段。 它应当被初始化为 ‘PY_MINOR_VERSION’。 该
     字段默认会被忽略，当且仅当 ‘PyCF_ONLY_AST’ 在 `cf_flags' 中设置旗标
     时才会被使用。 （由 Guido van Rossum 在 bpo-35766(1) 中贡献。）

   * ‘PyEval_ReInitThreads()’ 函数已从 C API 中移除。 它不应当被显式地调
     用；请改用 *note PyOS_AfterFork_Child(): 3ef.。 （由 Victor Stinner
     在 bpo-36728(2) 中贡献。）

   * 在 Unix 上，C 扩展不会再被链接到 libpython，但 Android 和 Cygwin 例
     外。 当 Python 被嵌入时，‘libpython’ 不可使用 ‘RTLD_LOCAL’ 加载，而
     要改用 ‘RTLD_GLOBAL’。 之前使用 ‘RTLD_LOCAL’ 已经不可能加载未链接到
     ‘libpython’ 的 C 扩展了，例如通过 ‘Modules/Setup’ 的 ‘*shared*’ 部
     分构建的标准库 C 扩展。 （由 Victor Stinner 在 bpo-21536(3) 中贡献
     。）

   * 在解析或构建值时（例如 *note PyArg_ParseTuple(): 393, *note
     Py_BuildValue(): 3f0, *note PyObject_CallFunction(): 3f1. 等等）使
     用形如 ‘#’ 的格式而不定义 ‘PY_SSIZE_T_CLEAN’ 现在将会引发
     ‘DeprecationWarning’。 它将在 3.10 或 4.0 中被移除。 请参阅 *note
     语句解释及变量编译: 3f2. 了解详情。 （由 Inada Naoki 在
     bpo-36381(4) 中贡献。）

   * 堆分配类型的实例（例如使用 *note PyType_FromSpec(): 23a. 创建的实例
     ）会保存一个对其类型对象的引用。 提升这些类型对象引用计数的操作已从
     *note PyType_GenericAlloc(): 399. 移至更低层级的函数 *note
     PyObject_Init(): 398. 和 ‘PyObject_INIT()’。 这使用通过This makes
     types created through *note PyType_FromSpec(): 23a. 所创建类型的行
     为与管理代码中的其他类保持一致。

     静态分配类型将不受影响。

     在大部分情况下，这应该都不会有附带影响。 但是，在分配实例后手动提升
     引用计数的类型（也许是为了绕过漏洞）现在可能永远不会被销毁。 要避免
     这种情况，这些类需要在实例撤销分配期间在类型对象上调用 Py_DECREF。

     要正确地将这些类型移植到 3.8，请应用以下修改：

        * 在分配实例之后在类型对象上移除 *note Py_INCREF: 38e. —— 如果有
          的话。 这可以发生在调用 *note PyObject_New(): 268, *note
          PyObject_NewVar(): 269, *note PyObject_GC_New(): 3f3, *note
          PyObject_GC_NewVar(): 3f4. 或任何其他使用 *note
          PyObject_Init(): 398. 或 ‘PyObject_INIT()’ 的自定义分配器之后
          。

          示例:

               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;
               }

        * 确保所有堆分配类型的自定义 ‘tp_dealloc’ 函数会减少类型的引用计
          数。

          示例:

               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
               }

     （由 Eddie Elizondo 在 bpo-35810(5) 中贡献。）

   * ‘Py_DEPRECATED()’ 宏已经针对 MSVC 实现。 这个宏现在必须放在符号名称
     之前。

     示例:

          Py_DEPRECATED(3.8) PyAPI_FUNC(int) Py_OldFunction(void);

     （由 Zackery Spytz 在 bpo-33407(6) 中贡献。）

   * 解释器将不再假装支持跨发布版本的扩展类型二进制兼容性。 由第三方扩展
     模块所导出的 *note PyTypeObject: 3f5. 应该具有当前 Python 版本所要
     求的所有空位，包括 *note tp_finalize: 3f6. (*note
     Py_TPFLAGS_HAVE_FINALIZE: 3f7. 不会再在读取 *note tp_finalize: 3f6.
     之前被检查)。

     （由 Antoine Pitrou 在 bpo-32388(7) 中贡献。）

   * 函数 ‘PyNode_AddChild()’ 和 ‘PyParser_AddToken()’ 现在接受两个额外
     的 ‘int’ 参数 `end_lineno' 和 `end_col_offset'。

   * 允许 MinGW 工具直接链接到 ‘python38.dll’ 的 ‘libpython38.a’ 文件已
     不再包含于标准的 Windows 分发包中。 如果你需要此文件，可使用
     ‘gendef’ 和 ‘dlltool’ 工具来生成它，这些工具是 MinGW binutils 包的
     一部分：

          gendef - python38.dll > tmp.def
          dlltool --dllname python38.dll --def tmp.def --output-lib libpython38.a

     已安装的 ‘pythonXY.dll’ 所在位置将取决于安装选项以及 Windows 的版本
     和语言。 请参阅 *note 在 Windows 上使用 Python: 3f8. 了解更多信息。
     该结果库应当放在与 ‘pythonXY.lib’ 相同的目录下，这通常是你的 Python
     安装路径下的 ‘libs’ 目录。

     （由 Steve Dower 在 bpo-37351(8) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35766

   (2) https://bugs.python.org/issue36728

   (3) https://bugs.python.org/issue21536

   (4) https://bugs.python.org/issue36381

   (5) https://bugs.python.org/issue35810

   (6) https://bugs.python.org/issue33407

   (7) https://bugs.python.org/issue32388

   (8) https://bugs.python.org/issue37351


File: python.info,  Node: CPython 字节码的改变<2>,  Next: 演示和工具,  Prev: C API 中的改变,  Up: 移植到 Python 3 8

1.2.10.4 CPython 字节码的改变
.............................

   * 解释器循环已通过将块堆栈展开逻辑移入编译器获得了简化。 编译器现在会
     发出显式指令来调整值堆栈并为 *note break: 3fa, *note continue: 2bb.
     和 *note return: 2c8. 调用清除代码。

     移除了操作码 ‘BREAK_LOOP’, ‘CONTINUE_LOOP’, ‘SETUP_LOOP’ 和
     ‘SETUP_EXCEPT’。 添加了新的操作码 *note ROT_FOUR: 3fb,
     ‘BEGIN_FINALLY’, ‘CALL_FINALLY’ 和 ‘POP_FINALLY’。 修改了
     ‘END_FINALLY’ 和 ‘WITH_CLEANUP_START’ 的行为。

     （由 Mark Shannon, Antoine Pitrou 和 Serhiy Storchaka 在
     bpo-17611(1) 中贡献。）

   * 添加了新的操作码 *note END_ASYNC_FOR: 3fc. 用于处理当等待 *note
     async for: 3fd. 循环的下一项时引发的异常。 （由 Serhiy Storchaka 在
     bpo-33041(2) 中贡献。）

   * *note MAP_ADD: 3fe. 现在会预期值为栈的第一个元素而键为第二个元素。
     作出此改变以使得字典推导式能如 PEP 572(3) 所提议的那样，键总是会在
     值之前被求值。 （由 Jörn Heissler 在 bpo-35224(4) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17611

   (2) https://bugs.python.org/issue33041

   (3) https://www.python.org/dev/peps/pep-0572

   (4) https://bugs.python.org/issue35224


File: python.info,  Node: 演示和工具,  Prev: CPython 字节码的改变<2>,  Up: 移植到 Python 3 8

1.2.10.5 演示和工具
...................

添加了一个检测脚本用于对访问变量的不同方式进行计时:
‘Tools/scripts/var_access_benchmark.py’。 （由 Raymond Hettinger 在
bpo-35884(1) 中贡献。）

以下是自 Python 3.3 以来性能提升情况的总结:

     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

基准测试是在 Intel® Core™ i7-4960HQ 处理器(2) 上运行从 python.org(3) 获
取的 macOS 64 位版得到的数据。 基准测试脚本显示时间以纳秒为单位。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35884

   (2) 
https://ark.intel.com/content/www/us/en/ark/products/76088/intel-core-i7-4960hq-processor-6m-cache-up-to-3-80-ghz.html

   (3) https://www.python.org/downloads/mac-osx/


File: python.info,  Node: Python 3 8 1 中的重要变化,  Next: Python 3 8 8 中的重要变化,  Prev: 移植到 Python 3 8,  Up: Python 3 8 有什么新变化

1.2.11 Python 3.8.1 中的重要变化
--------------------------------

出于重要的安全性考量，*note asyncio.loop.create_datagram_endpoint():
189. 的 `reuse_address' 形参不再被支持。 这是由 UDP 中的套接字选项
‘SO_REUSEADDR’ 的行为导致的。 更多细节请参阅
‘loop.create_datagram_endpoint()’ 的文档。 （由 Kyle Stanley, Antoine
Pitrou 和 Yury Selivanov 在 bpo-37228(1) 中贡献。。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37228


File: python.info,  Node: Python 3 8 8 中的重要变化,  Next: Notable changes in Python 3 8 12,  Prev: Python 3 8 1 中的重要变化,  Up: Python 3 8 有什么新变化

1.2.12 Python 3.8.8 中的重要变化
--------------------------------

早先的 Python 版本允许使用 ‘;’ 和 ‘&’ 作为 *note
urllib.parse.parse_qs(): 27f. 和 *note urllib.parse.parse_qsl(): 280. 中
query 形参的分隔键。 出于安全考虑，也为了遵循更新的 W3C 推荐设置，这已被
改为只允许单个分隔键，默认为 ‘&’。 这一改变还会影响 *note cgi.parse():
281. 和 *note cgi.parse_multipart(): 282. 因为它们在内部使用了受影响的函
数。 要了解更多细节，请查看它们各自的文档。 （由 Adam Goldschmidt,
Senthil Kumaran 和 Ken Jin 在 bpo-42967(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42967


File: python.info,  Node: Notable changes in Python 3 8 12,  Prev: Python 3 8 8 中的重要变化,  Up: Python 3 8 有什么新变化

1.2.13 Notable changes in Python 3.8.12
---------------------------------------

Starting with Python 3.8.12 the *note ipaddress: a2. 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 *note socket.inet_aton(): 236. treats
leading zeros as octal notation.  glibc implementation of modern *note
inet_pton(): 237. does not accept any leading zeros.

(Originally contributed by Christian Heimes in bpo-36384(1), and
backported to 3.8 by Achraf Merzouki.)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36384


File: python.info,  Node: Python 3 7 有什么新变化,  Next: Python 3 6 有什么新变化,  Prev: Python 3 8 有什么新变化,  Up: Python 有什麼新功能？

1.3 Python 3.7 有什么新变化
===========================


编者: Elvis Pranskevichus <<elvis@magic.io>>

本文解释了 Python 3.7 相比 3.6 的新增特性。Python 3.7 于 2018 年 6 月 27
日发布。完整的详情可参阅 *note 更新日志: 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 中的重要变化.


File: python.info,  Node: 摘要 - 发布重点<3>,  Next: 新的特性<4>,  Up: Python 3 7 有什么新变化

1.3.1 摘要 - 发布重点
---------------------

新的语法特性：

   * *note PEP 563: 406.，类型标注延迟求值。

向后不兼容的语法更改：

   * *note async: 2d7. 和 *note await: 2d8. 现在是保留的关键字。

新的库模块：

   * *note contextvars: 24.: *note PEP 567 – 上下文变量: 407.

   * *note dataclasses: 2f.: *note PEP 557 – 数据类: 408.

   * *note importlib.resources: 409.

新的内置特性：

   * *note PEP 553: 40a, 新的 *note breakpoint(): 40b. 函数。

对 Python 数据模型的改进：

   * *note PEP 562: 40c, 自定义可访问的模块属性。

   * *note PEP 560: 40d, typing模块和泛型类型的核心支持。

   * *note dict: 40e. 对象会保持插入时的顺序这个特性 正式宣布(1) 成为
     Python 语言官方规范的一部分。

标准库中的重大改进：

   * *note asyncio: 9. 模块添加了新的功能，重大改进请参阅 *note
     可用性与性能提升: 40f.。

   * *note time: 10c. 模块现在提供 *note 纳秒级精度函数: 410. 的支持。

CPython 实现的改进：

   * 避免使用 ASCII 作为默认的文本编码：

        * *note PEP 538: 411.，传统 C 区域强制转换

        * *note PEP 540: 412.，强制 UTF-8 运行时模式

   * *note PEP 552: 413.，确定性的 .pyc 文件

   * *note 新的 Python 开发模式: 414.

   * *note PEP 565: 415.，改进的 *note DeprecationWarning: 15a. 处理

C API 的改进：

   * *note PEP 539: 416.，用于线程本地存储的新 C API

文档的改进：

   * *note PEP 545: 417, Python 文档翻译

   * 新的文档翻译：Japanese(2)，French(3) 和 Korean(4)。

此版本在诸多方面有显著的性能改进。*note 性能优化: 418. 章节详细列出了它
们。

和之前的 Python 版本存在兼容性的更改列表，请参阅 *note 移植到 Python
3.7: 419. 章节。

   ---------- Footnotes ----------

   (1) 
https://mail.python.org/pipermail/python-dev/2017-December/151283.html

   (2) https://docs.python.org/ja/

   (3) https://docs.python.org/fr/

   (4) https://docs.python.org/ko/


File: python.info,  Node: 新的特性<4>,  Next: 其他语言特性修改<3>,  Prev: 摘要 - 发布重点<3>,  Up: Python 3 7 有什么新变化

1.3.2 新的特性
--------------

* 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.


File: python.info,  Node: PEP 563：延迟的标注求值,  Next: PEP 538 传统 C 区域强制转换,  Up: 新的特性<4>

1.3.2.1 PEP 563：延迟的标注求值
...............................

随着 PEP 3107(1) 加入标注功能并在 PEP 526(2) 进一步细化，Python 中类型提
示的出现揭示了两个明显的可用性问题：

   * 标注只能使用在当前作用域中已经存在的名称，也就是说，它们不支持任何
     形式的前向引用；而且——

   * 标注源码对 Python 程序的启动时间有不利的影响。

这两个问题都可以通过延迟标注求值来解决。在定义标注的时候，编译器并不会编
译执行相应表达式的代码，而是保存与相应表达式的 AST 等价的字符串形式。如
果有需要，标注可以在运行时使用 *note typing.get_type_hints(): 1ef. 进行
解析。在不需要这种解析的通常情况下，标注的存储成本更低（因为解析器只需处
理较短的字符串）且启动时间更短。

在可用性方面，标注现在支持向前引用，以使以下句法有效:

     class C:
         @classmethod
         def from_string(cls, source: str) -> C:
             ...

         def validate_b(self, obj: B) -> bool:
             ...

     class B:
         ...

由于此修改会破坏兼容性，在 Python 3.7 中此种新的行为需要在每个模块层级上
使用 *note __future__: 0. 导入来启用:

     from __future__ import annotations

它将在 Python 3.10 中成为默认行为。

也參考
......

PEP 563(3) – 延迟的标注求值

     PEP 由 Łukasz Langa 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3107

   (2) https://www.python.org/dev/peps/pep-0526

   (3) https://www.python.org/dev/peps/pep-0563


File: python.info,  Node: PEP 538 传统 C 区域强制转换,  Next: PEP 540 强制 UTF-8 运行时模式,  Prev: PEP 563：延迟的标注求值,  Up: 新的特性<4>

1.3.2.2 PEP 538: 传统 C 区域强制转换
....................................

Python 3 系列有一个持续的挑战就是为处理 7 比特位 ASCII 文本的假定编码确
定合理的默认策略，目前的设定是在非 Windows 平台上使用默认的 C 或 POSIX 区
域设置。

PEP 538(1) 更新了默认的解释器命令行接口，以自动将上述区域强制转换为可用
的基于 UTF-8 的区域，具体描述可参见有关新增环境变量 *note
PYTHONCOERCECLOCALE: 41d. 的文档。 以这种方式自动设置 ‘LC_CTYPE’ 意味着
核心解释器和能感知区域的 C 扩展 (例如 *note readline: de.) 都将会假定
UTF-8 已被用作默认的文本编码，而不再是 ASCII。

PEP 11(2) 中的平台支持定义也已被更新以限制完整文本处理支持适当配置的基于
非 ASCII 的语言区域。

作为此更改的一部分，当使用任何已定义的强制转换目标区域时 (目前为
‘C.UTF-8’, ‘C.utf8’ 和 ‘UTF-8’) *note stdin: 41e. 和 *note stdout: 41f.
默认的处理器现在将为 ‘surrogateescape’ (而不是 ‘strict’)。 而无论是什么
区域，*note stderr: 1ea. 默认的处理器仍为 ‘backslashreplace’。

默认情况下区域强制转换会静默进行，但为了辅助调试潜在的区域相关集成问题，
可以通过设置 ‘PYTHONCOERCECLOCALE=warn’ 来请求显式地启用警告信息（直接在
*note stderr: 1ea. 上发出）。 此设置还会使得 Python 运行时在核心解释器初
始化时如果传统 C 区域仍然处于激活状态时发出警告。

虽然 PEP 538(3) 的区域强制转换的好处在于它还会同时影响扩展模块 (例如 GNU
‘readline’) 以及子进程 (包括运行非 Python 应用和旧版本 Python 的子进程
)，但它也存在需要所运行系统必须存在适合的目标区域的缺点。 为了更好地处理
没有可用适合的目标区域的情况 (例如在 RHEL/CentOS 7 上就会出现此情况)，
Python 3.7 还实现了 *note PEP 540; 强制 UTF-8 运行时模式: 412.。

也參考
......

PEP 538(4) – 强制转换传统 C 区域到基于 UTF-8 的区域

     PEP 由 Nick Coghlan 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0538

   (2) https://www.python.org/dev/peps/pep-0011

   (3) https://www.python.org/dev/peps/pep-0538

   (4) https://www.python.org/dev/peps/pep-0538


File: python.info,  Node: PEP 540 强制 UTF-8 运行时模式,  Next: PEP 553 内置的 breakpoint,  Prev: PEP 538 传统 C 区域强制转换,  Up: 新的特性<4>

1.3.2.3 PEP 540: 强制 UTF-8 运行时模式
......................................

新的 *note -X: 290. ‘utf8’ 命令行选项和 *note PYTHONUTF8: 421. 环境变量
可被用来启用 CPython 的 `UTF-8 模式'。

当处于 UTF-8 模式时，CPython 会忽略区域设置，并默认使用 UTF-8 编码。 用
于 *note sys.stdin: 41e. 和 *note sys.stdout: 41f. 流的错误处理器将设置
为 ‘surrogateescape’。

强制 UTF-8 模式可被用来在嵌入的 Python 解释器中改变文本处理行为，而不会
改变嵌入方应用的区域设置。

PEP 540(1) 的 UTF-8 模式的好处是不必关心运行所在系统中有哪些可用区域即可
工作，但它也存在对扩展模块 (例如 GNU ‘readline’)、运行非 Python 应用的子
进程以及运行旧版本 Python 的子进程不起作用的缺点。 为了减小与这些组件通
信时破坏文本数据的风险，Python 3.7 还实现了 *note PEP 540; 强制 UTF-8
运行时模式: 412.)。

UTF-8 模式在语言区域为 ‘C’ 或 ‘POSIX’ 并且 PEP 538(2) 区域强制转换特性无
法将其修改为某种基于 UTF-8 的替代项时会被默认启用（无论修改失败是由于设
置了 ‘PYTHONCOERCECLOCALE=0’, ‘LC_ALL’ 还是由于缺少适合的目标区域）。

也參考
......

PEP 540(3) – 增加了新的 UTF-8 模式

     PEP 由 Victor Stinner 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0540

   (2) https://www.python.org/dev/peps/pep-0538

   (3) https://www.python.org/dev/peps/pep-0540


File: python.info,  Node: PEP 553 内置的 breakpoint,  Next: PEP 539 用于线程局部存储的新 C API,  Prev: PEP 540 强制 UTF-8 运行时模式,  Up: 新的特性<4>

1.3.2.4 PEP 553: 内置的 ‘breakpoint()’
......................................

Python 3.7 包含了新的内置 *note breakpoint(): 40b. 函数，作为一种简单方
便地进入 Python 调试器的方式。

内置 ‘breakpoint()’ 会调用 *note sys.breakpointhook(): 423.。 在默认情况
下后者会导入 *note pdb: c9. 然后再调用 ‘pdb.set_trace()’，但是通过将
‘sys.breakpointhook()’ 绑定到你选定的函数，‘breakpoint()’ 可以进入任何调
试器。 此外，环境变量 *note PYTHONBREAKPOINT: 424. 可被设置为你选定的调
试器的可调用对象。 设置 ‘PYTHONBREAKPOINT=0’ 会完全禁用内置
‘breakpoint()’。

也參考
......

PEP 553(1) – 内置的 breakpoint()

     PEP 由 Barry Warsaw 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0553


File: python.info,  Node: PEP 539 用于线程局部存储的新 C API,  Next: PEP 562 定制对模块属性的访问,  Prev: PEP 553 内置的 breakpoint,  Up: 新的特性<4>

1.3.2.5 PEP 539: 用于线程局部存储的新 C API
...........................................

虽然 Python 已提供了用于线程局部存储支持的 C API；但原有的 *note
线程局部存储 (TLS) API: 426. 使用 ‘int’ 来表示所有平台上的 TLS 密钥。 对
于官方支持的平台而言这通常不是问题，但这既不符合 POSIX 标准，也不具备任
何实际意义上的可移植性。

PEP 539(1) 通过向 CPython 提供了一个新的 *note 线程特定存储 (TSS) API:
427. 来改变这一点，它取代了原有的 CPython 内部 TLS API 的使用，并且原有
API 已弃用。 TSS API 使用一种新类型 *note Py_tss_t: 428. 而非 ‘int’ 来表
示 TSS 密钥 – 这是一种不透明类型，其定义可能依赖于下层的 TLS 实现。 因此
，这将允许在以无法安全地转换为 ‘int’ 的方式定义原生 TLS 密钥的平台上构建
CPython。

请注意在原生 TLS 密钥定义方式无法被安全地转换为 ‘int’ 的平台上，原有 TLS
API 中的全部函数将无法执行并会立即返回失败信息。 这样能清楚地表明原有
API 在无法可靠使用的平台上不受支持，并且不会再尝试添加此类支持。

也參考
......

PEP 539(2) – 在 CPython 中用于线程局部存储的新 C-API

     PEP 由 Erik M. Bray 撰写；由 Masayuki Yamamoto 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0539

   (2) https://www.python.org/dev/peps/pep-0539


File: python.info,  Node: PEP 562 定制对模块属性的访问,  Next: PEP 564 具有纳秒级精度的新时间函数,  Prev: PEP 539 用于线程局部存储的新 C API,  Up: 新的特性<4>

1.3.2.6 PEP 562: 定制对模块属性的访问
.....................................

Python 3.7 允许在模块上定义 *note __getattr__(): 42a. 并且当以其他方式找
不到某个模块属性时将会调用它。 在模块上定义 *note __dir__(): 42b. 现在也
是允许的。

一个典型的可能有用的例子是已弃用模块属性和惰性加载。

也參考
......

PEP 562(1) – 模块的 ‘__getattr__’ 和 ‘__dir__’

     PEP 由 Ivan Levkivskyi 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0562


File: python.info,  Node: PEP 564 具有纳秒级精度的新时间函数,  Next: PEP 565 在 __main__ 中显示 DeprecationWarning,  Prev: PEP 562 定制对模块属性的访问,  Up: 新的特性<4>

1.3.2.7 PEP 564: 具有纳秒级精度的新时间函数
...........................................

现代系统的时钟精度可以超过由 *note time.time(): 42d. 函数及其变化形式所
返回的浮点数的有限精度。 为了避免精度损失， PEP 564(1) 在 *note time:
10c. 模块中增加了原有计时器函数的六个新“纳秒版”变化形式:

   * *note time.clock_gettime_ns(): 42e.

   * *note time.clock_settime_ns(): 42f.

   * *note time.monotonic_ns(): 430.

   * *note time.perf_counter_ns(): 431.

   * *note time.process_time_ns(): 432.

   * *note time.time_ns(): 433.

这些新函数会以整数值的形式返回纳秒数。

测量(2) 表明在 Linux 和 Windows 上 *note time.time_ns(): 433. 的精度大约
比 *note time.time(): 42d. 要高 3 倍。

也參考
......

PEP 564(3) – 增加具有纳秒级精度的新时间函数

     PEP 由 Victor Stinner 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0564

   (2) 
https://www.python.org/dev/peps/pep-0564/#annex-clocks-resolution-in-python

   (3) https://www.python.org/dev/peps/pep-0564


File: python.info,  Node: PEP 565 在 __main__ 中显示 DeprecationWarning,  Next: PEP 560 对 typing 模块和泛型类型的核心支持,  Prev: PEP 564 具有纳秒级精度的新时间函数,  Up: 新的特性<4>

1.3.2.8 PEP 565: 在 ‘__main__’ 中显示 DeprecationWarning
........................................................

*note DeprecationWarning: 15a. 的默认处理方式已经被更改，这此警告默认只
显示一次，仅有当直接在 *note __main__: 1. 模块中运行的代码触发它们时才会
再次显示。 因此，单文件脚本开发者以及 Python 交互模式使用者应该会再次开
始看到针对他们所使用 API 的已弃用警告，但被导入应用、库和框架模块所触发
的已弃用警告默认将继续隐藏。

作为此项更改的结果，标准库现在允许开发者在三种不同的已弃用警告行为之间进
行选择:

   * *note FutureWarning: 435.: 默认情况下总是会显示，建议用于应用程序最
     终用户应该看到的警告信息（例如对于已弃用的应用程序配置的设置选项）
     。

   * *note DeprecationWarning: 15a.: 默认情况下仅在 *note __main__: 1. 中
     以及当运行测试时会显示，建议用于其他 Python 开发者应该看到的警告信
     息，提示版本升级可能导致行为改变或者错误。

   * *note PendingDeprecationWarning: 15c.: 默认情况下仅在运行测试时会显
     示，可用于提示未来版本升级将会改变警告类别为 *note
     DeprecationWarning: 15a. 或 *note FutureWarning: 435. 的情况。

在此之前 *note DeprecationWarning: 15a. 和 *note
PendingDeprecationWarning: 15c. 都仅在运行测试时可见，这意味着主要编写单
文件脚本或使用 Python 交互模式的开发者可能会因他们所用 API 突然出现的改
变而感到惊讶。

也參考
......

PEP 565(1) – 在 ‘__main__’ 中显示 DeprecationWarning

     PEP 由 Nick Coghlan 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0565


File: python.info,  Node: PEP 560 对 typing 模块和泛型类型的核心支持,  Next: PEP 552 基于哈希值的 pyc 文件,  Prev: PEP 565 在 __main__ 中显示 DeprecationWarning,  Up: 新的特性<4>

1.3.2.9 PEP 560: 对 ‘typing’ 模块和泛型类型的核心支持
.....................................................

PEP 484(1) 最初的设计方式使其不会向核心 CPython 解释器引入 `任何' 更改。
现在类型提示和 *note typing: 122. 模块已被社区广泛使用，因此这个限制已被
取消。 这个 PEP 引入了两个特殊方法 *note __class_getitem__(): 437. 和
‘__mro_entries__’，这些方法现在被 *note typing: 122. 中的大多数类和特殊
构造所使用。 结果就是与类型相关的各类操作的速度提升了 7 倍，泛型类型可以
在没有元类冲突的情况下被使用，而 *note typing: 122. 模块中几个长期存在的
错误也已被修正。

也參考
......

PEP 560(2) – 对 typing 模块和泛型类型的核心支持

     PEP 由 Ivan Levkivskyi 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0484

   (2) https://www.python.org/dev/peps/pep-0560


File: python.info,  Node: PEP 552 基于哈希值的 pyc 文件,  Next: PEP 545 Python 文档翻译,  Prev: PEP 560 对 typing 模块和泛型类型的核心支持,  Up: 新的特性<4>

1.3.2.10 PEP 552: 基于哈希值的 .pyc 文件
........................................

传统上 Python 检查字节码缓存文件 (即 ‘.pyc’ 文件) 是否最新的方式是通过对
源码元数据 (最后更改的时间戳和大小）和生成缓存时保存在其文件头中的源码元
数据进行比较。 这种检查方法虽然有效，但也存在缺点。 当文件系统的时间戳太
粗糙时，Python 有可能错过源码更新，导致用户感到困惑。 此外，在缓存文件中
存在时间戳对于 构建可再现(1) 并且基于内容的构建系统来说是有问题的。

PEP 552(2) 扩展了 pyc 格式以允许使用源文件的哈希值而非源文件的时间戳来检
查有效性。 这种 ‘.pyc’ 文件就称为“基于哈希值的”。 默认情况下，Python 仍
然使用基于时间戳的有效性检查，不会在运行时生成基于哈希值的 ‘.pyc’ 文件。
基于哈希值的 ‘.pyc’ 文件可以使用 *note py_compile: d7. 或 *note
compileall: 20. 来生成。

基于哈希值的 ‘.pyc’ 文件包含两种变体：已选定和未选定。 Python 会在运行时
针对相应源码文件验证已选定基于哈希值的 ‘.pyc’ 文件，但对未选定基于哈希值
的 pyc 文件则不会这样做。 未选定基于哈希值的 ‘.pyc’ 文件对于需要由
Python 外部的系统（例如构建系统）负责使 ‘.pyc’ 文件保持最新的环境来说是
一种有用的性能优化。

请参阅 *note 已缓存字节码的失效: 439. 了解更多信息。

也參考
......

PEP 552(3) – 确定性的 pyc 文件

     PEP 由 Benjamin Peterson 撰写并实现

   ---------- Footnotes ----------

   (1) https://reproducible-builds.org/

   (2) https://www.python.org/dev/peps/pep-0552

   (3) https://www.python.org/dev/peps/pep-0552


File: python.info,  Node: PEP 545 Python 文档翻译,  Next: Python 开发模式 -X dev,  Prev: PEP 552 基于哈希值的 pyc 文件,  Up: 新的特性<4>

1.3.2.11 PEP 545: Python 文档翻译
.................................

PEP 545(1) 描述了创建和维护 Python 文档翻译的整个过程。

新增了三个新的翻译版本:

   - 日语: ‘https://docs.python.org/ja/’

   - 法语: ‘https://docs.python.org/fr/’

   - 韩语: ‘https://docs.python.org/ko/’

也參考
......

PEP 545(2) – Python 文档翻译

     PEP 由 Julien Palard, Inada Naoki 和 Victor Stinner 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0545

   (2) https://www.python.org/dev/peps/pep-0545


File: python.info,  Node: Python 开发模式 -X dev,  Prev: PEP 545 Python 文档翻译,  Up: 新的特性<4>

1.3.2.12 Python 开发模式 (-X dev)
.................................

新的 *note -X: 290. ‘dev’ 命令行选项或新的 *note PYTHONDEVMODE: 43c. 环
境变量可被用来启用 *note Python 开发模式: 160.。 在开发模式下，Python 将
执行额外的如果默认启用会导致开销过大的运行时检查。 请参阅 *note Python
开发模式: 160. 文档查看完整说明。


File: python.info,  Node: 其他语言特性修改<3>,  Next: 新增模块<3>,  Prev: 新的特性<4>,  Up: Python 3 7 有什么新变化

1.3.3 其他语言特性修改
----------------------

   * *note await: 2d8. 表达式和包含 *note async for: 3fd. 子句的推导式不
     允许在 *note 格式化字符串字面值: 296. 的表达式中使用。 在 Python
     3.7 中此限制已被取消。

   * 现在可以将超过 255 个参数传递给一个函数，而现在一个函数也可以拥有超
     过 255 个形参。 （由 Serhiy Storchaka 在 bpo-12844(1) 和
     bpo-18896(2) 中贡献。）

   * 现在 *note bytes.fromhex(): 43e. 和 *note bytearray.fromhex(): 43f.
     会忽略所有 ASCII 空白符，而非仅是空格符. （由 Robert Xiao 在
     bpo-28927(3) 中贡献。）

   * *note str: 205, *note bytes: 172. 和 *note bytearray: 173. 获得了对
     新 *note isascii(): 440. 方法的支持，该方法可被用来测试是个字符串或
     字节串是否仅包含 ASCII 字符。 （由 INADA Naoki 在 bpo-32677(4) 中贡
     献。）

   * 现在当 ‘from ... import ...’ 失败时 *note ImportError: 16c. 会显示
     模块名称和模块 ‘__file__’ 路径。 （由 Matthias Bussonnier 在
     bpo-29546(5) 中贡献。）

   * 现在已支持涉及将子模块绑定到一个名称的绝对导入的循环导入。 （由
     Serhiy Storchaka 在 bpo-30024(6) 中贡献。）

   * 现在 ‘object.__format__(x, '')’ 等价于 ‘str(x)’ 而非
     ‘format(str(self), '')’。 （由 Serhiy Storchaka d bpo-28974(7) 中贡
     献。）

   * 为更好地支持栈跟踪的动态创建，现在 *note types.TracebackType: 441.
     可以从 Python 代码中被实例化，并且 *note 回溯对象: 442. 的
     ‘tb_next’ 属性现在是可写的。 （由 Nathaniel J. Smith 在
     bpo-30579(8) 中贡献。）

   * 当使用 *note -m: 443. 开关时，现在 ‘sys.path[0]’ 会主动扩展为完整的
     起始目录路径，而不是保持为空目录（这将允许在发生导入时从 `当前' 工
     作目录导入） （由 Nick Coghlan 在 bpo-33053(9) 中贡献。）

   * 新的 *note -X: 290. ‘importtime’ 选项或 *note
     PYTHONPROFILEIMPORTTIME: 444. 环境变量可被用来显示每次模块导入的时
     间。 （由 Victor Stinner 在 bpo-31415(10) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue12844

   (2) https://bugs.python.org/issue18896

   (3) https://bugs.python.org/issue28927

   (4) https://bugs.python.org/issue32677

   (5) https://bugs.python.org/issue29546

   (6) https://bugs.python.org/issue30024

   (7) https://bugs.python.org/issue28974

   (8) https://bugs.python.org/issue30579

   (9) https://bugs.python.org/issue33053

   (10) https://bugs.python.org/issue31415


File: python.info,  Node: 新增模块<3>,  Next: 改进的模块<3>,  Prev: 其他语言特性修改<3>,  Up: Python 3 7 有什么新变化

1.3.4 新增模块
--------------

* Menu:

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


File: python.info,  Node: contextvars,  Next: dataclasses,  Up: 新增模块<3>

1.3.4.1 contextvars
...................

新的 *note contextvars: 24. 模块和一组 *note 新的 C API: 447. 引入了对
`上下文变量' 的支持。 上下文变量在概念上类似于线程局部变量。 与 TLS 不同
，上下文变量能正确地支持异步代码。

*note asyncio: 9. 和 *note decimal: 35. 已得到更新以使用和支持开箱即用的
上下文变量。 特别是激活的 decimal 上下文现在将存储在上下文变量中，它允许
十进制运算在异步代码中使用正确的上下文。

也參考
......

PEP 567(1) – 上下文变量

     PEP 由 Yury Selivanov 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0567


File: python.info,  Node: dataclasses,  Next: importlib resources,  Prev: contextvars,  Up: 新增模块<3>

1.3.4.2 dataclasses
...................

新的 *note dataclass(): 449. 装饰器提供了一种声明 `数据类' 的方式。 数据
类使用变量标注来描述其属性。 它的构造器和其他魔术方法例如 *note
__repr__(): 44a, *note __eq__(): 44b. 以及 *note __hash__(): 44c. 会自动
地生成。

示例:

     @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)"

也參考
......

PEP 557(1) – 数据类

     PEP 由 Eric V. Smith 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0557


File: python.info,  Node: importlib resources,  Prev: dataclasses,  Up: 新增模块<3>

1.3.4.3 importlib.resources
...........................

新的 *note importlib.resources: 9e. 模块提供了一些新的 API 和一个新的
ABC 用于访问、打开和读取包内的 `资源'。 资源基本上类似于包内的文件，但它
们不一定是物理文件系统中实际的文件。 模块加载器可以提供
‘get_resource_reader()’ 函数，它会返回一个 *note
importlib.abc.ResourceReader: 44e. 实例来支持这个新 API。 内置的文件路径
加载器和 zip 文件加载器都支持此特性。

由 Barry Warsaw 和 Brett Cannon 在 bpo-32248(1) 中贡献。

也參考
......

importlib_resources(2) – 用于先前 Python 版本的 PyPI 下层接口。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32248

   (2) http://importlib-resources.readthedocs.io/en/latest/


File: python.info,  Node: 改进的模块<3>,  Next: C API 的改变<2>,  Prev: 新增模块<3>,  Up: Python 3 7 有什么新变化

1.3.5 改进的模块
----------------

* 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::


File: python.info,  Node: argparse,  Next: asyncio<3>,  Up: 改进的模块<3>

1.3.5.1 argparse
................

新的 *note ArgumentParser.parse_intermixed_args(): 451. 方法允许混合选项
与位置参数。 （由 paul.j3 在 bpo-14191(1) 中提供。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue14191


File: python.info,  Node: asyncio<3>,  Next: binascii,  Prev: argparse,  Up: 改进的模块<3>

1.3.5.2 asyncio
...............

*note asyncio: 9. 模块获得了许多新的特性、可用性和 *note 性能提升: 453.。
重要的改变包括:

   * 新的 *note 暂定: 454. *note asyncio.run(): 18d. 函数可被用于通过自
     动创建和销毁事件循环来基于同步代码运行协程。 （由 Yury Selivanov 在
     bpo-32314(1) 中贡献。）

   * asyncio 增加支持 *note contextvars: 24.  *note loop.call_soon():
     455, *note loop.call_soon_threadsafe(): 456, *note
     loop.call_later(): 457, *note loop.call_at(): 458. 并且 *note
     Future.add_done_callback(): 459. 具有新的可选仅关键字参数
     `context'。 现在 *note Tasks: 2e0. 会自动跟踪其上下文。 详情参见
     PEP 567(2)。 （由 Yury Selivanov 在 bpo-32436(3) 中贡献。）

   * 增加了新的 *note asyncio.create_task(): 2e1. 函数作为
     ‘asyncio.get_event_loop().create_task()’ 的快捷方式。 （由 Andrew
     Svetlov 在 bpo-32311(4) 中贡献。）

   * 新的 *note loop.start_tls(): 45a. 方法可用于升级现有的 TLS 连接。 （
     由 Yury Selivanov 在 bpo-23749(5) 中贡献。）

   * 新的 *note loop.sock_recv_into(): 45b. 方法允许直接从套接字读取数据
     放入所提供的缓冲区，从而可以减少数据复制。 （由 Antoine Pitrou 在
     bpo-31819(6) 中贡献。）

   * 新的 *note asyncio.current_task(): 228. 函数可返回当前运行的 *note
     Task: 2e0. 实例，以及新的 *note asyncio.all_tasks(): 229. 函数可返
     回给定循环中所有现存 ‘Task’ 实例的集合。 ‘Task.current_task()’ 和
     ‘Task.all_tasks()’ 方法已弃用。 （由 Andrew Svetlov 在 bpo-32250(7)
     中贡献。）

   * 新的 `暂定' *note BufferedProtocol: 3eb. 类允许通过手动控制接收缓冲
     区来实现流式协议。 （由 Yury Selivanov 在 bpo-32251(8) 中贡献。）

   * 新的 *note asyncio.get_running_loop(): 45c. 函数可返回当前运行的循
     环，如果没有循环在运行则引发 *note RuntimeError: 3dc.。 这与 *note
     asyncio.get_event_loop(): 45d. 不同，后者在没有循环在运行时将 `创建
     ' 一个新的事件循环。 （由 Yury Selivanov 在 bpo-32269(9) 中提供。）

   * 新的 *note StreamWriter.wait_closed(): 45e. 协程方法允许执行等待直
     到流写入器被关闭。 新的 *note StreamWriter.is_closing(): 45f. 方法
     可用于确定写入器是否被关闭。 （由 Andrew Svetlov 在 bpo-32391(10) 中
     贡献。）

   * 新的 *note loop.sock_sendfile(): 460. 协程方法允许在可能的情况下使
     用 *note os.sendfile: 461. 发送文件。 （由 Andrew Svetlov 在
     bpo-32410(11) 中贡献。）

   * 新的 *note Future.get_loop(): 462. 和 ‘Task.get_loop()’ 方法会返回
     创建 task 或 future 对象的事件循环的实例。 *note Server.get_loop():
     463. 允许为 *note asyncio.Server: 464. 对象执行同样操作。 （由 Yury
     Selivanov 在 bpo-32415(12) 中，以及由 Srinivas Reddy Thatiparthy 在
     bpo-32418(13) 中贡献。）

   * 现在可以控制 *note asyncio.Server: 464. 的实例如何开启服务。 之前，
     服务在创建后将立即开启服务。 新的 `start_serving' 关键字参数已添加
     到 *note loop.create_server(): 465. 和 *note
     loop.create_unix_server(): 466.，并且 *note Server.start_serving():
     467, 和 *note Server.serve_forever(): 468. 可被用来分离服务的实例化
     和服务的开启。 新的 *note Server.is_serving(): 469. 方法会在服务开
     启时返回 ‘True’。 现在 *note Server: 464. 对象已是异步上下文管理器:

          srv = await loop.create_server(...)

          async with srv:
              # some code

          # At this point, srv is closed and no longer accepts new connections.

     （由 Yury Selivanov 在 bpo-32662(14) 中贡献。）

   * 由 *note loop.call_later(): 457. 所返回的回调对象已获得新的 *note
     when(): 46a. 方法，该方法会返回一个排入计划日程的绝对时间戳。 （由
     Andrew Svetlov 在 bpo-32741(15) 中贡献。）

   * *note loop.create_datagram_endpoint(): 189. 方法已获得对 Unix 套接
     字的支持。 （由 Quentin Dawans 在 bpo-31245(16) 中贡献。）

   * *note asyncio.open_connection(): 46b, *note asyncio.start_server():
     46c. functions, *note loop.create_connection(): 2e5, *note
     loop.create_server(): 465, *note loop.create_accepted_socket():
     46d. 方法及其对应的 UNIX 套接字变体现在接受 `ssl_handshake_timeout'
     关键字参数。 （由 Neil Aspinall 在 bpo-29970(17) 中贡献。）

   * 新的 *note Handle.cancelled(): 46e. 方法会在回调被取消时返回
     ‘True’。 （由 Marat Sharafutdinov 在 bpo-31943(18) 中贡献。）

   * asyncio 源已被转换为使用 *note async: 2d7./*note await: 2d8. 语法。
     （由 Andrew Svetlov 在 bpo-32193(19) 中贡献。）

   * 新的 *note ReadTransport.is_reading(): 46f. 方法可用于确定传输的读
     取状态。 此外，对 *note ReadTransport.resume_reading(): 470. 和
     *note ReadTransport.pause_reading(): 471. 的调用现在是幂等的。 （由
     Yury Selivanov 在 bpo-32356(20) 中贡献。）

   * 接受套接字路径的循环方法现在支持传入 *note 路径类对象: 472.。 （由
     Yury Selivanov 在 bpo-32066(21) 中贡献。）

   * 在 *note asyncio: 9. 中，Linux 上的 TCP 套接字现在创建时默认带有
     ‘TCP_NODELAY’ 旗标设置。 （由 Yury Selivanov 和 Victor Stinner 在
     bpo-27456(22) 中贡献。）

   * 在被取消任务中发生的异常不会再被记录。 （由 Yury Selivanov 在
     bpo-30508(23) 中贡献。）

   * 新的 ‘WindowsSelectorEventLoopPolicy’ 和
     ‘WindowsProactorEventLoopPolicy’ 类。 （由 Yury Selivanov 在
     bpo-33792(24) 中贡献。）

部分 ‘asyncio’ API 改为 *note 已弃用: 473.。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32314

   (2) https://www.python.org/dev/peps/pep-0567

   (3) https://bugs.python.org/issue32436

   (4) https://bugs.python.org/issue32311

   (5) https://bugs.python.org/issue23749

   (6) https://bugs.python.org/issue31819

   (7) https://bugs.python.org/issue32250

   (8) https://bugs.python.org/issue32251

   (9) https://bugs.python.org/issue32269

   (10) https://bugs.python.org/issue32391

   (11) https://bugs.python.org/issue32410

   (12) https://bugs.python.org/issue32415

   (13) https://bugs.python.org/issue32418

   (14) https://bugs.python.org/issue32662

   (15) https://bugs.python.org/issue32741

   (16) https://bugs.python.org/issue31245

   (17) https://bugs.python.org/issue29970

   (18) https://bugs.python.org/issue31943

   (19) https://bugs.python.org/issue32193

   (20) https://bugs.python.org/issue32356

   (21) https://bugs.python.org/issue32066

   (22) https://bugs.python.org/issue27456

   (23) https://bugs.python.org/issue30508

   (24) https://bugs.python.org/issue33792


File: python.info,  Node: binascii,  Next: calendar,  Prev: asyncio<3>,  Up: 改进的模块<3>

1.3.5.3 binascii
................

*note b2a_uu(): 475. 函数现在接受可选的 `backtick' 关键字参数。 当其为真
值时，零会以 ‘'`'’ 而非空格来表示。 （由 Xiang Zhang 在 bpo-30103(1) 中
贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30103


File: python.info,  Node: calendar,  Next: collections<2>,  Prev: binascii,  Up: 改进的模块<3>

1.3.5.4 calendar
................

*note HTMLCalendar: 477. 类具有新的类属性，可以简化所生成 HTML 日历中
CSS 类的自定义。 （由 Oz Tiram 在 bpo-30095(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30095


File: python.info,  Node: collections<2>,  Next: compileall<2>,  Prev: calendar,  Up: 改进的模块<3>

1.3.5.5 collections
...................

‘collections.namedtuple()’ 现在支持默认值。 （由 Raymond Hettinger 在
bpo-32320(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32320


File: python.info,  Node: compileall<2>,  Next: concurrent futures<2>,  Prev: collections<2>,  Up: 改进的模块<3>

1.3.5.6 compileall
..................

*note compileall.compile_dir(): 47a. 增加了新的 `invalidation_mode' 形参
，可用于启用 *note 基于哈希值的 .pyc 有效性检测: 413.。 失效模式也可以在
命令行中使用新的 ‘--invalidation-mode’ 参数来指定。 （由 Benjamin
Peterson 在 bpo-31650(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31650


File: python.info,  Node: concurrent futures<2>,  Next: contextlib,  Prev: compileall<2>,  Up: 改进的模块<3>

1.3.5.7 concurrent.futures
..........................

*note ProcessPoolExecutor: 196. 和 *note ThreadPoolExecutor: 18c. 现在支
持新的 `初始化器' 以及 `initargs' 构造器参数。 （由 Antoine Pitrou 在
bpo-21423(1) 中贡献。）

*note ProcessPoolExecutor: 196. 现在能通过新的 `mp_context' 参数来接受多
进程上下文。 （由 Thomas Moreau 在 bpo-31540(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21423

   (2) https://bugs.python.org/issue31540


File: python.info,  Node: contextlib,  Next: cProfile<2>,  Prev: concurrent futures<2>,  Up: 改进的模块<3>

1.3.5.8 contextlib
..................

新的 *note nullcontext(): 47d. 是一个比 *note ExitStack: 47e. 更简单和快
速的无操作上下文管理器。 （由 Jesse-Bakker 在 bpo-10049(1) 中贡献。）

增加了新的 *note asynccontextmanager(): 47f, *note
AbstractAsyncContextManager: 480. 和 *note AsyncExitStack: 481. 以补充它
们所对应的同步项。 （由 Jelle Zijlstra 在 bpo-29679(2) 和 bpo-30241(3) 中
，以及由 Alexander Mohr 和 Ilya Kulakov 在 bpo-29302(4) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10049

   (2) https://bugs.python.org/issue29679

   (3) https://bugs.python.org/issue30241

   (4) https://bugs.python.org/issue29302


File: python.info,  Node: cProfile<2>,  Next: crypt,  Prev: contextlib,  Up: 改进的模块<3>

1.3.5.9 cProfile
................

*note cProfile: 27. 命令行现在接受 ‘-m module_name’ 作为脚本路径的替代。
（由 Sanyam Khurana 在 bpo-21862(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21862


File: python.info,  Node: crypt,  Next: datetime<3>,  Prev: cProfile<2>,  Up: 改进的模块<3>

1.3.5.10 crypt
..............

*note crypt: 28. 模块现在支持 Blowfish 哈希方法。 （由 Serhiy Storchaka
在 bpo-31664(1) 中贡献。）

*note mksalt(): 484. 函数现在允许指定哈希操作的轮数。 （由 Serhiy
Storchaka 在 bpo-31702(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31664

   (2) https://bugs.python.org/issue31702


File: python.info,  Node: datetime<3>,  Next: dbm,  Prev: crypt,  Up: 改进的模块<3>

1.3.5.11 datetime
.................

新的 *note datetime.fromisoformat(): 486. 方法会基于由
‘datetime.isoformat()’ 所输出的某一特定格式字符串构建 *note datetime:
19f. 对象。 （由 Paul Ganssle 在 bpo-15873(1) 中贡献。）

*note tzinfo: 180. 类现在支持小于一分钟的偏移量。 （由 Alexander
Belopolsky 在 bpo-5288(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15873

   (2) https://bugs.python.org/issue5288


File: python.info,  Node: dbm,  Next: decimal,  Prev: datetime<3>,  Up: 改进的模块<3>

1.3.5.12 dbm
............

*note dbm.dumb: 32. 现在支持读取只读文件，并且在其未改变时不再写入索引文
件。


File: python.info,  Node: decimal,  Next: dis,  Prev: dbm,  Up: 改进的模块<3>

1.3.5.13 decimal
................

*note decimal: 35. 模块现在使用 *note 上下文变量: 407. 来储存十进制值上
下文。 （由 Yury Selivanov 在 bpo-32630(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32630


File: python.info,  Node: dis,  Next: distutils<2>,  Prev: decimal,  Up: 改进的模块<3>

1.3.5.14 dis
............

*note dis(): 48a. 函数现在能够反汇编嵌套的代码对象（推导式、生成器表达式
和嵌套函数的代码，以及用于构建嵌套类的代码）。 反汇编递归的最大深度由新
的 `depth' 形参来控制。 （由 Serhiy Storchaka 在 bpo-11822(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue11822


File: python.info,  Node: distutils<2>,  Next: enum,  Prev: dis,  Up: 改进的模块<3>

1.3.5.15 distutils
..................

‘README.rst’ 现在包含在 distutils 的标准 README 列表之中，因而也包含在源
码发布之中。 （由 Ryan Gonzalez 在 bpo-11913(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue11913


File: python.info,  Node: enum,  Next: functools<2>,  Prev: distutils<2>,  Up: 改进的模块<3>

1.3.5.16 enum
.............

*note Enum: 48d. 增加了新的 ‘_ignore_’ 类特征属性，该属性允许列出不应当
成为枚举成员的特征属性名称。 （由 Ethan Furman 在 bpo-31801(1) 中贡献。
）

在 Python 3.8 中，尝试在 ‘Enum’ 类中检查非 Enum 对象将引发 *note
TypeError: 1fe. (例如 ‘1 in Color’)；类似地，尝试在 ‘Flag’ 成员中检查非
Flag 对象也将引发 *note TypeError: 1fe. (例如 ‘1 in Perm.RW’)；目前，两
种操作均会返回 *note False: 48e. 并且已弃用。 （由 Ethan Furman 在
bpo-33217(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31801

   (2) https://bugs.python.org/issue33217


File: python.info,  Node: functools<2>,  Next: gc<3>,  Prev: enum,  Up: 改进的模块<3>

1.3.5.17 functools
..................

*note functools.singledispatch(): 490. 现在支持使用类型标注来注册实现。
（由 Łukasz Langa 在 bpo-32227(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32227


File: python.info,  Node: gc<3>,  Next: hmac,  Prev: functools<2>,  Up: 改进的模块<3>

1.3.5.18 gc
...........

新的 *note gc.freeze(): 492. 函数允许冻结由垃圾回收器所跟踪的所有对象，
并将它们从未来的集合中排除。 这可以在 POSIX ‘fork()’ 调用之前使用以令 GC
友好地进行写入时复制或加速收集。 新的 *note gc.unfreeze(): 493. 函数会反
转此操作。 此外，*note gc.get_freeze_count(): 494. 可被用于获取冻结对象
的数量。 （由 Li Zekun 在 bpo-31558(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31558


File: python.info,  Node: hmac,  Next: http client,  Prev: gc<3>,  Up: 改进的模块<3>

1.3.5.19 hmac
.............

*note hmac: 8e. 现在具有经优化的一次性 *note digest(): 496. 函数，其速度
比 ‘HMAC()’ 要快三倍。 （由 Christian Heimes 在 bpo-32433(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32433


File: python.info,  Node: http client,  Next: http server,  Prev: hmac,  Up: 改进的模块<3>

1.3.5.20 http.client
....................

*note HTTPConnection: 498. 和 *note HTTPSConnection: 499. 现在支持新的
`blocksize' 参数以提升上传吞吐量。 （由 Nir Soffer 在 bpo-31945(1) 中贡
献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31945


File: python.info,  Node: http server,  Next: idlelib 与 IDLE,  Prev: http client,  Up: 改进的模块<3>

1.3.5.21 http.server
....................

*note SimpleHTTPRequestHandler: 49b. 现在支持 HTTP ‘If-Modified-Since’ 标
头。 如果目标文件在该标点指定的时间之后未被修改则服务器会返回 304 响应状
态。 （由 Pierre Quentel 在 bpo-29654(1) 中贡献。）

*note SimpleHTTPRequestHandler: 49b. 接受新的 `directory' 参数并增加了新
的 ‘--directory’ 命令行参数。 通过此形参，服务器可以对服务指定目录，默认
情况下它使用当前工作目录。 （由 Stéphane Wirtel 和 Julien Palard 在
bpo-28707(2) 中贡献。）

新的 *note ThreadingHTTPServer: 49c. 类使用线程来处理使用
‘ThreadingMixin’ 的请求。 它会在 ‘http.server’ 附带 ‘-m’ 运行时被使用。
（由 Julien Palard 在 bpo-31639(3) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29654

   (2) https://bugs.python.org/issue28707

   (3) https://bugs.python.org/issue31639


File: python.info,  Node: idlelib 与 IDLE,  Next: importlib<2>,  Prev: http server,  Up: 改进的模块<3>

1.3.5.22 idlelib 与 IDLE
........................

多个对自动补全的修正。 （由 Louie Lu 在 bpo-15786(1) 中贡献。）

Module Browser (在 File 菜单中，之前称为 Class Browser) 现在会在最高层级
函数和类之外显示嵌套的函数和类。 （由 Guilherme Polo, Cheryl Sabella 和
Terry Jan Reedy 在 bpo-1612262(2) 中贡献。）

Settings 对话框 (Options 中的 Configure IDLE) 已经被部分重写以改进外观和
功能。 （由 Cheryl Sabella 和 Terry Jan Reedy 在多个问题项中贡献。）

字体样本现在包括一组非拉丁字符以便用户能更好地查看所选特定字体的效果。 （
由 Terry Jan Reedy 在 bpo-13802(3) 中贡献。） 样本可以被修改以包括其他字
符。 （由 Serhiy Storchaka 在 bpo-31860(4) 中贡献。）

之前以扩展形式实现的 IDLE 特性已作为正常特性重新实现。 它们的设置已从
Extensions 选项卡移至其他对话框选项卡。 （由 Charles Wohlganger 和 Terry
Jan Reedy 在 bpo-27099(5) 中实现。）

编辑器代码上下文选项已经过修改。 Box 会显示所有上下文行直到最大行数。 点
击一个上下文行会使编辑器跳转到该行。 自定义主题的上下文颜色已添加到
Settings 对话框的 Highlights 选项卡。 （由 Cheryl Sabella 和 Terry Jan
Reedy 在 bpo-33642(6), bpo-33768(7) 和 bpo-33679(8) 中贡献。）

在 Windows 上，会有新的 API 调用将 tk 对 DPI 的调整告知 Windows。 在
Windows 8.1+ 或 10 上，如果 Python 二进制码的 DPI 兼容属性未改变，并且监
视器分辨率大于 96 DPI，这应该会令文本和线条更清晰。 否则的话它应该不造成
影响。 （由 Terry Jan Reedy 在 bpo-33656(9) 中贡献。）

在 3.7.1 中新增:

超过 N 行（默认值为 50）的输出将被折叠为一个按钮。 N 可以在 Settings 对
话框的 General 页的 PyShell 部分中进行修改。 数量较少但是超长的行可以通
过在输出上右击来折叠。 被折叠的输出可通过双击按钮来展开，或是通过右击按
钮来放入剪贴板或是单独的窗口。 （由 Tal Einat 在 bpo-1529353(10) 中贡献
。）

上述修改已被反向移植到 3.6 维护发行版中。

在 3.7.4 中新增:

在 Run 菜单中增加了 "Run Customized" 以使用自定义设置来运行模块。 输入的
任何命令行参数都会被加入 sys.argv。 它们在下次自定义运行时会再次显示在窗
体中。 用户也可以禁用通常的 Shell 主模块重启。 （由 Cheryl Sabella,
Terry Jan Reedy 等人在 bpo-5680(11) 和 bpo-37627(12) 中贡献。）

在 3.7.5 中新增:

在 IDLE 编辑器窗口中增加了可选的行序号。 窗口打开时默认不带行序号，除非
在配置对话框的 General 选项卡中进行设置。 已打开窗口中的行序号可以在
Options 菜单中显示和隐藏。 （由 Tal Einat 和 Saimadhav Heblikar 在
bpo-17535(13) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15786

   (2) https://bugs.python.org/issue1612262

   (3) https://bugs.python.org/issue13802

   (4) https://bugs.python.org/issue31860

   (5) https://bugs.python.org/issue27099

   (6) https://bugs.python.org/issue33642

   (7) https://bugs.python.org/issue33768

   (8) https://bugs.python.org/issue33679

   (9) https://bugs.python.org/issue33656

   (10) https://bugs.python.org/issue1529353

   (11) https://bugs.python.org/issue5680

   (12) https://bugs.python.org/issue37627

   (13) https://bugs.python.org/issue17535


File: python.info,  Node: importlib<2>,  Next: io<2>,  Prev: idlelib 与 IDLE,  Up: 改进的模块<3>

1.3.5.23 importlib
..................

引入了 *note importlib.abc.ResourceReader: 44e. ABC 以支持从包中加载资源
。 另请参阅 *note importlib.resources: 409.。 （由 Barry Warsaw, Brett
Cannon 在 bpo-32248(1) 中贡献。）

如果模块缺少规格描述 *note importlib.reload(): 49f. 现在会引发 *note
ModuleNotFoundError: 4a0.。 （由 Garvit Khatri 在 bpo-29851(2) 中贡献。
）

如果指定的父模块不是一个包 (即缺少 ‘__path__’ 属性)
‘importlib.find_spec()’ 现在会引发 *note ModuleNotFoundError: 4a0. 而非
*note AttributeError: 4a1.。 （由 Milan Oberkirch 在 bpo-30436(3) 中贡献
。）

新的 ‘importlib.source_hash()’ 可被用来计算传入源的哈希值。 *note
基于哈希值的 .pyc 文件: 413. 会嵌入此函数所返回的值。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32248

   (2) https://bugs.python.org/issue29851

   (3) https://bugs.python.org/issue30436


File: python.info,  Node: io<2>,  Next: ipaddress<2>,  Prev: importlib<2>,  Up: 改进的模块<3>

1.3.5.24 io
...........

新的 *note TextIOWrapper.reconfigure(): 4a3. 方法可用于根据新的设置重新
配置文本流。 （由 Antoine Pitrou 在 bpo-30526(1) 以及 INADA Naoki 在
bpo-15216(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30526

   (2) https://bugs.python.org/issue15216


File: python.info,  Node: ipaddress<2>,  Next: itertools<2>,  Prev: io<2>,  Up: 改进的模块<3>

1.3.5.25 ipaddress
..................

methods of *note ipaddress.IPv6Network: 4a5. 和 *note
ipaddress.IPv4Network: 4a6. 中新的 ‘subnet_of()’ 以及 ‘supernet_of()’ 方
法可用于网络包含测试。 （由 Michel Albert 和 Cheryl Sabella 在
bpo-20825(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20825


File: python.info,  Node: itertools<2>,  Next: locale,  Prev: ipaddress<2>,  Up: 改进的模块<3>

1.3.5.26 itertools
..................

*note itertools.islice(): 4a8. 现在接受 *note 类整数对象: 2c2. 作为
start, stop 和 slice 参数。 （由 Will Roberts 在 bpo-30537(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30537


File: python.info,  Node: locale,  Next: logging<2>,  Prev: itertools<2>,  Up: 改进的模块<3>

1.3.5.27 locale
...............

*note locale.format_string(): 4aa. 中新的 `monetary' 参数可用于转换所使
用的千位分隔符和分组字符串。 （由 Garvit 在 bpo-10379(1) 中贡献。）

现在 *note locale.getpreferredencoding(): 4ab. 函数在 Android 上或是在
*note 强制 UTF-8 模式: 412. 下总是返回 ‘'UTF-8'’ 。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10379


File: python.info,  Node: logging<2>,  Next: math<3>,  Prev: locale,  Up: 改进的模块<3>

1.3.5.28 logging
................

*note Logger: 4ad. 实例现在可以被 pickle。 （由 Vinay Sajip 在
bpo-30520(1) 中贡献。）

新的 *note StreamHandler.setStream(): 4ae. 方法可用于在句柄创建之后替换
日志流。 （由 Vinay Sajip 在 bpo-30522(2) 中创建。）

现在可以在传递给 *note logging.config.fileConfig(): 4af. 的配置信息中对
句柄构造器指定关键字参数。 （由 Preston Landers 在 bpo-31080(3) 中贡献。
)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30520

   (2) https://bugs.python.org/issue30522

   (3) https://bugs.python.org/issue31080


File: python.info,  Node: math<3>,  Next: mimetypes,  Prev: logging<2>,  Up: 改进的模块<3>

1.3.5.29 math
.............

新的 *note math.remainder(): 4b1. 函数实现了 IEEE 754 风格的余数运算。 （
由 Mark Dickinson 在 bpo-29962(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29962


File: python.info,  Node: mimetypes,  Next: msilib,  Prev: math<3>,  Up: 改进的模块<3>

1.3.5.30 mimetypes
..................

.bmp 的 MIME type 从 ‘'image/x-ms-bmp'’ 改为 ‘'image/bmp'’。 （由 Nitish
Chandra 在 bpo-22589(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22589


File: python.info,  Node: msilib,  Next: multiprocessing<3>,  Prev: mimetypes,  Up: 改进的模块<3>

1.3.5.31 msilib
...............

新的 *note Database.Close(): 4b4. 方法可用于关闭 MSI (last-in,
first-out) 数据库。 （由 Berker Peksag 在 bpo-20486(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20486


File: python.info,  Node: multiprocessing<3>,  Next: os<3>,  Prev: msilib,  Up: 改进的模块<3>

1.3.5.32 multiprocessing
........................

新的 *note Process.close(): 4b6. 方法会显式地关闭进程对象并释放与其关联
的所有资源。 如果底层进程仍在运行则将引发 *note ValueError: 16d.。 （由
Antoine Pitrou 在 bpo-30596(1) 中贡献。）

新的 *note Process.kill(): 4b7. 方法可用于在 Unix 上使用 ‘SIGKILL’ 信号
来终止进程。 （由 Vitor Pereira 在 bpo-30794(2) 中贡献。）

由 *note Process: 4b8. 所创建的非守护线程现在会在进程退出时被合并。 （由
Antoine Pitrou 在 bpo-18966(3) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30596

   (2) https://bugs.python.org/issue30794

   (3) https://bugs.python.org/issue18966


File: python.info,  Node: os<3>,  Next: pathlib<3>,  Prev: multiprocessing<3>,  Up: 改进的模块<3>

1.3.5.33 os
...........

*note os.fwalk(): 4ba. 现在接受 *note bytes: 172. 类型的 `path' 参数。 （
由 Serhiy Storchaka 在 bpo-28682(1) 中贡献。）

*note os.scandir(): 389. 已获得对 *note 文件描述器: 4bb. 的支持。 （由
Serhiy Storchaka 在 bpo-25996(2) 中贡献。）

新的 *note register_at_fork(): 4bc. 函数允许注册 Python 回调以便在进程分
叉中执行。 （由 Antoine Pitrou 在 bpo-16500(3) 中贡献。）

增加了 *note os.preadv(): 4bd. (结合了 *note os.readv(): 4be. 与 *note
os.pread(): 4bf. 的功能) 以及 *note os.pwritev(): 4c0. 函数 (结合了
*note os.writev(): 4c1. 和 *note os.pwrite(): 4c2. 的功能)。 （由 Pablo
Galindo 在 bpo-31368(4) 中贡献。）

*note os.makedirs(): 4c3. 的 mode 参数不再影响新创建的中间层级目录的文件
权限。 （由 Serhiy Storchaka 在 bpo-19930(5) 中贡献。）

*note os.dup2(): 4c4. 现在会返回新的文件描述器。 之前，返回的总是
‘None’。 （由 Benjamin Peterson 在 bpo-32441(6) 中贡献。）

在 Solaris 及其派生系统上 *note os.stat(): 321. 所返回的结构现在会包含
*note st_fstype: 4c5. 属性。 （由 Jesús Cea Avión 在 bpo-32659(7) 中贡献
。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28682

   (2) https://bugs.python.org/issue25996

   (3) https://bugs.python.org/issue16500

   (4) https://bugs.python.org/issue31368

   (5) https://bugs.python.org/issue19930

   (6) https://bugs.python.org/issue32441

   (7) https://bugs.python.org/issue32659


File: python.info,  Node: pathlib<3>,  Next: pdb<2>,  Prev: os<3>,  Up: 改进的模块<3>

1.3.5.34 pathlib
................

在 POSIX 类系统上新的 *note Path.is_mount(): 333. 方法现在可用于确定一个
路径是否为挂载点。 （由 Cooper Ry Lees 在 bpo-30897(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30897


File: python.info,  Node: pdb<2>,  Next: py_compile<2>,  Prev: pathlib<3>,  Up: 改进的模块<3>

1.3.5.35 pdb
............

*note pdb.set_trace(): 4c8. 现在接受一个可选的限关键字参数 `header'。 如
果给出，它会在调试开始之前被打印到控制台。 （由 Barry Warsaw 在
bpo-31389(1) 中贡献。）

*note pdb: c9. 命令行现在接受 ‘-m module_name’ 作为对脚本文件的替代。 （
由 Mario Corchero 在 bpo-32206(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31389

   (2) https://bugs.python.org/issue32206


File: python.info,  Node: py_compile<2>,  Next: pydoc<2>,  Prev: pdb<2>,  Up: 改进的模块<3>

1.3.5.36 py_compile
...................

*note py_compile.compile(): 343. – 及其扩展形式 *note compileall: 20. –
现在会通过无条件地为基于哈希值的有效性验证创建 ‘.pyc’ 文件来支持
‘SOURCE_DATE_EPOCH’ 环境变量。 这样可以确保当 ‘.pyc’ 文件被主动创建时 可
重现的生成(1)。 （由 Bernhard M. Wiedemann 在 bpo-29708(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://reproducible-builds.org/

   (2) https://bugs.python.org/issue29708


File: python.info,  Node: pydoc<2>,  Next: queue,  Prev: py_compile<2>,  Up: 改进的模块<3>

1.3.5.37 pydoc
..............

pydoc 服务器现在可以绑定到由新的 ‘-n’ 命令行参数所指定的任意主机名。 （
由 Feanil Patel 在 bpo-31128(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31128


File: python.info,  Node: queue,  Next: re,  Prev: pydoc<2>,  Up: 改进的模块<3>

1.3.5.38 queue
..............

新的 *note SimpleQueue: 4cc. 类是一个无界的 FIFO (last-in, first-out) 队
列。 （由 Antoine Pitrou 在 bpo-14976(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue14976


File: python.info,  Node: re,  Next: signal<2>,  Prev: queue,  Up: 改进的模块<3>

1.3.5.39 re
...........

旗标 *note re.ASCII: 4ce, *note re.LOCALE: 4cf. 和 ‘re.UNICODE’ 可以在组
的范围内设置。 （由 Serhiy Storchaka 在 bpo-31690(1) 中贡献。）

*note re.split(): 4d0. 现在支持基于匹配一个空字符串的模式例如 ‘r'\b'’,
‘'^$'’ 或 ‘(?=-)’ 进行拆分。 （由 Serhiy Storchaka 在 bpo-25054(2) 中贡
献。）

使用 *note re.LOCALE: 4cf. 旗标编译的正则表达式不再依赖于编译时的区域设
置。 区域设置仅在已编译正则表达式被使用时才被应用。 （由 Serhiy
Storchaka 在 bpo-30215(3) 中贡献。）

现在如果一个正则表达式包含语义将在未来发生改变的字符集构造，则会引发
*note FutureWarning: 435.，例如嵌套集与集合操作等。 （由 Serhiy
Storchaka 在 bpo-30349(4) 中贡献。）

已编译正则表达式和匹配对象现在可以使用 *note copy.copy(): 4d1. 和 *note
copy.deepcopy(): 4d2. 进行拷贝。 （由 Serhiy Storchaka 在 bpo-10076(5) 中
贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31690

   (2) https://bugs.python.org/issue25054

   (3) https://bugs.python.org/issue30215

   (4) https://bugs.python.org/issue30349

   (5) https://bugs.python.org/issue10076


File: python.info,  Node: signal<2>,  Next: socket<3>,  Prev: re,  Up: 改进的模块<3>

1.3.5.40 signal
...............

*note signal.set_wakeup_fd(): 4d4. 函数新增的 `warn_on_full_buffer' 参数
可以指定当唤醒缓冲区溢出时 Python 是否要在 stderr 上打印警告信息。 （由
Nathaniel J. Smith 在 bpo-30050(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30050


File: python.info,  Node: socket<3>,  Next: socketserver,  Prev: signal<2>,  Up: 改进的模块<3>

1.3.5.41 socket
...............

新增的 *note socket.getblocking(): 4d6. 方法会在套接字处于阻塞模式时返回
‘True’，否则返回 ‘False’。 （由 Yury Selivanov 在 bpo-32373(1) 中贡献。
）

新的 *note socket.close(): 4d7. 函数可关闭所传入的套接字文件描述符。 应
该用此函数来代替 *note os.close(): 4d8. 以获得更好的跨平台兼容性。 （由
Christian Heimes 在 bpo-32454(2) 中贡献。）

*note socket: ef. 模块现在会公开 ‘socket.TCP_CONGESTION’ (Linux 2.6.13),
‘socket.TCP_USER_TIMEOUT’ (Linux 2.6.37) 以及 ‘socket.TCP_NOTSENT_LOWAT’
(Linux 3.12) 常量。 （由 Omar Sandoval 在 bpo-26273(3) 以及 Nathaniel J.
Smith 在 bpo-29728(4) 中贡献。）

已加入对 *note socket.AF_VSOCK: 4d9. 套接字的支持以允许在虚拟机及其宿主
机之间进行通讯。 （由 Cathy Avery 在 bpo-27584(5) 中贡献。）

套接字现在默认会根据文件描述符自动检测所属族、类型和协议。 （由
Christian Heimes 在 bpo-28134(6) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32373

   (2) https://bugs.python.org/issue32454

   (3) https://bugs.python.org/issue26273

   (4) https://bugs.python.org/issue29728

   (5) https://bugs.python.org/issue27584

   (6) https://bugs.python.org/issue28134


File: python.info,  Node: socketserver,  Next: sqlite3,  Prev: socket<3>,  Up: 改进的模块<3>

1.3.5.42 socketserver
.....................

‘socketserver.ThreadingMixIn.server_close()’ 现在会等待所有非守护线程完
成。 ‘socketserver.ForkingMixIn.server_close()’ 现在会等待所有子进程完成
。

为 *note socketserver.ForkingMixIn: 4db. 和 *note
socketserver.ThreadingMixIn: 4dc. 类增加了新的
‘socketserver.ForkingMixIn.block_on_close’ 类属性。 该类属性值设为
‘False’ 以保持 3.7 之前的行为。


File: python.info,  Node: sqlite3,  Next: ssl<2>,  Prev: socketserver,  Up: 改进的模块<3>

1.3.5.43 sqlite3
................

现在当下层的 SQLite 库版本为 3.6.11 及以上时 *note sqlite3.Connection:
4de. 会开放 *note backup(): 4df. 方法。 （由 Lele Gaifax 在 bpo-27645(1)
中贡献。）

*note sqlite3.connect(): 4e0. 的 `database' 参数现在接受任何 *note
path-like object: 472.，而不是只接受字符串。 （由 Anders Lorentsen 在
bpo-31843(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27645

   (2) https://bugs.python.org/issue31843


File: python.info,  Node: ssl<2>,  Next: string,  Prev: sqlite3,  Up: 改进的模块<3>

1.3.5.44 ssl
............

*note ssl: f3. 模块现在使用 OpenSSL 的内置 API 代替 *note
match_hostname(): 4e2. 来检查主机名或 IP 地址。 值的验证会在 TLS 握手期
间进行。 任何证书验证错误包括主机名检查失败现在将引发 *note
SSLCertVerificationError: 4e3. 并使用正确的 TLS Alert 消息中止握手过程。
这个新异常包含有额外的信息。 主机名验证可通过 *note
SSLContext.hostname_checks_common_name: 4e4. 进行自定义。 （由 Christian
Heimes 在 bpo-31399(1) 中贡献。）

     備註: 改进的主机名检测需要有兼容 OpenSSL 1.0.2 或 1.1 的 `libssl' 实
     现。 因此，OpenSSL 0.9.8 和 1.0.1 不再被支持（请参阅 *note
     平台支持的移除: 4e5. 了解详情）。 目前 ssl 模块主要兼容 LibreSSL
     2.7.2 及更高版本。

‘ssl’ 模块不再以 SNI TLS 扩展发送 IP 地址。 （由 Christian Heimes 在
bpo-32185(2) 中贡献。）

*note match_hostname(): 4e2. 不再支持部分通配符例如 ‘www*.example.org’。
（由 Mandeep Singh 在 bpo-23033(3) 以及 Christian Heimes 在 bpo-31399(4)
中贡献。）

‘ssl’ 模块默认的加密套件选择现在是使用黑名单方式而非硬编码的白名单。
Python 不会再重新启用已经被 OpenSSL 安全更新所阻止的加密。 默认的加密套
件选择可以在编译时进行配置。 （由 Christian Heimes 在 bpo-31429(5) 中贡
献。）

现在已支持包含国际化域名 (IDN) 的服务器证书验证。 作为此更改的一部分，
*note SSLSocket.server_hostname: 4e6. 属性现在会以预期的 A 标签形式
(‘"xn--pythn-mua.org"’) 而不是以 U 标签形式 (‘"pythön.org"’) 存储。 （由
Nathaniel J. Smith 与 Christian Heimes 在 bpo-28414(6) 中贡献。）

‘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 及更早的版本略有差异，请参阅 *note TLS
1.3: 4e7.。 （由 Christian Heimes 在 bpo-32947(7), bpo-20995(8),
bpo-29136(9), bpo-30622(10) 以及 bpo-33618(11) 中贡献。）

*note SSLSocket: 192. 和 *note SSLObject: 4e8. 不再具有公共构造器。 直接
实例化从未成为有文档和受支持的特性。 实际必须通过 *note SSLContext: 4e9.
的方法 *note wrap_socket(): 4ea. 和 *note wrap_bio(): 4eb. 来创建。 （由
Christian Heimes 在 bpo-32951(12) 中贡献。）

用于设置最小和最大 TLS 协议版本的 OpenSSL 1.1 API 现已可用，名称分别为
*note SSLContext.minimum_version: 4ec. 和 *note
SSLContext.maximum_version: 4ed.。 受支持的协议由几个新增旗标指定，例如
*note HAS_TLSv1_1: 4ee.。 （由 Christian Heimes 在 bpo-32609(13) 中贡献
。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31399

   (2) https://bugs.python.org/issue32185

   (3) https://bugs.python.org/issue23033

   (4) https://bugs.python.org/issue31399

   (5) https://bugs.python.org/issue31429

   (6) https://bugs.python.org/issue28414

   (7) https://bugs.python.org/issue32947

   (8) https://bugs.python.org/issue20995

   (9) https://bugs.python.org/issue29136

   (10) https://bugs.python.org/issue30622

   (11) https://bugs.python.org/issue33618

   (12) https://bugs.python.org/issue32951

   (13) https://bugs.python.org/issue32609


File: python.info,  Node: string,  Next: subprocess,  Prev: ssl<2>,  Up: 改进的模块<3>

1.3.5.45 string
...............

*note string.Template: 4f0. 现在允许你有选择地分别修改带大括号的占位符和
不带大括号的占位符所对应的正则表达式模式。 （由 Barry Warsaw 在
bpo-1198569(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1198569


File: python.info,  Node: subprocess,  Next: sys<3>,  Prev: string,  Up: 改进的模块<3>

1.3.5.46 subprocess
...................

*note subprocess.run(): 4f2. 函数接受新的 `capture_output' 关键字参数。
当其为真值时，将会捕获 stdout 和 stderr。 这相当于将 *note
subprocess.PIPE: 4f3. 作为 `stdout' 和 `stderr' 参数传入。 （由 Bo
Bayles 在 bpo-32102(1) 中贡献。）

‘subprocess.run’ 函数和 *note subprocess.Popen: 3db. 构造器现在接受
`text' 关键字参数作为 `universal_newlines' 的别名。 （由 Andrew Clegg 在
bpo-31756(2) 中贡献。）

在 Windows 中当重定向标准句柄时 `close_fds' 的默认值由 ‘False’ 改为
‘True’。 现在可以在重定向标准句柄时将 `close_fds' 设为真值。 参阅 *note
subprocess.Popen: 3db.。 这意味着现在 `close_fds' 在所有受支持的平台上默
认值均为 ‘True’。 （由 Segev Finer 在 bpo-19764(3) 中贡献。）

在 *note subprocess.call(): 4f4, *note subprocess.run(): 4f2. 期间或在
*note Popen: 3db. 上下文管理器中，subprocess 模块现在能更优雅地处理
*note KeyboardInterrupt: 2cc.。 它现在会等待一小段时间以便子进程退出，然
后再继续处理 ‘KeyboardInterrupt’ 异常。 （由 Gregory P. Smith 在
bpo-25942(4) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32102

   (2) https://bugs.python.org/issue31756

   (3) https://bugs.python.org/issue19764

   (4) https://bugs.python.org/issue25942


File: python.info,  Node: sys<3>,  Next: time<3>,  Prev: subprocess,  Up: 改进的模块<3>

1.3.5.47 sys
............

新增 *note sys.breakpointhook(): 423. 钩子函数，供内置的 *note
breakpoint(): 40b. 进行调用。 （由 Barry Warsaw 在 bpo-31353(1) 中贡献。
）

在 Android 中新增的 *note sys.getandroidapilevel(): 4f6. 会返回构建时的
Android API 版本。 （由 Victor Stinner 在 bpo-28740(2) 中贡献。）

新的 *note sys.get_coroutine_origin_tracking_depth(): 4f7. 函数会返回当
前协程的由新的 *note sys.set_coroutine_origin_tracking_depth(): 4f8. 所
设定的原始跟踪深度。 *note asyncio: 9. 已转换为使用这个新 API 代替已弃用
的 ‘sys.set_coroutine_wrapper()’。 （由 Nathaniel J. Smith 在
bpo-32591(3) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31353

   (2) https://bugs.python.org/issue28740

   (3) https://bugs.python.org/issue32591


File: python.info,  Node: time<3>,  Next: tkinter<2>,  Prev: sys<3>,  Up: 改进的模块<3>

1.3.5.48 time
.............

PEP 564(1) 向 *note time: 10c. 模块增加六个具有纳秒级精度的新函数:

   * *note time.clock_gettime_ns(): 42e.

   * *note time.clock_settime_ns(): 42f.

   * *note time.monotonic_ns(): 430.

   * *note time.perf_counter_ns(): 431.

   * *note time.process_time_ns(): 432.

   * *note time.time_ns(): 433.

增加了新的时钟标识符:

   * *note time.CLOCK_BOOTTIME: 4fa. (Linux): 与 *note
     time.CLOCK_MONOTONIC: 4fb. 相似，不同点在于它还包括任何系统挂起的时
     间。

   * *note time.CLOCK_PROF: 4fc. (FreeBSD, NetBSD 和 OpenBSD): 高精度的
     分进程 CPU 计时器。

   * *note time.CLOCK_UPTIME: 4fd. (FreeBSD, OpenBSD): 该时间的绝对值是
     系统运行且未挂起的时间，提供准确的正常运行时间度量。

新的 *note time.thread_time(): 1e7. 和 *note time.thread_time_ns(): 4fe.
函数可用于获取每线程的 CPU 时间度量。 （由 Antoine Pitrou 在
bpo-32025(2) 中贡献。）

新的 *note time.pthread_getcpuclockid(): 4ff. 函数会返回特定线程中 CPU 时
钟的时钟 ID。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0564

   (2) https://bugs.python.org/issue32025


File: python.info,  Node: tkinter<2>,  Next: tracemalloc<2>,  Prev: time<3>,  Up: 改进的模块<3>

1.3.5.49 tkinter
................

新的 *note tkinter.ttk.Spinbox: 501. 类现已可用。 （由 Alan Moore 在
bpo-32585(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32585


File: python.info,  Node: tracemalloc<2>,  Next: types,  Prev: tkinter<2>,  Up: 改进的模块<3>

1.3.5.50 tracemalloc
....................

*note tracemalloc.Traceback: 503. 的行为更接近正规的回溯，会对所有帧按从
最旧到最新来排序。 *note Traceback.format(): 504. 现在接受负的 `limit'，
并会将结果截短至排在第 ‘abs(limit)’ 位的旧帧。 如果要获得旧的行为，请在
‘Traceback.format()’ 中使用新的 `most_recent_first' 参数。 （由 Jesse
Bakker 在 bpo-32121(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32121


File: python.info,  Node: types,  Next: unicodedata<3>,  Prev: tracemalloc<2>,  Up: 改进的模块<3>

1.3.5.51 types
..............

新的 *note WrapperDescriptorType: 506, *note MethodWrapperType: 507,
*note MethodDescriptorType: 508. 和 *note ClassMethodDescriptorType:
509. 类现已可用。 （由 Manuel Krebber 和 Guido van Rossum 在
bpo-29377(1) 以及 Serhiy Storchaka 在 bpo-32265(2) 中贡献。）

新的 *note types.resolve_bases(): 50a. 函数会以 PEP 560(3) 所规定的方式
动态解析 MRO 条目。 （由 Ivan Levkivskyi 在 bpo-32717(4) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29377

   (2) https://bugs.python.org/issue32265

   (3) https://www.python.org/dev/peps/pep-0560

   (4) https://bugs.python.org/issue32717


File: python.info,  Node: unicodedata<3>,  Next: unittest<2>,  Prev: types,  Up: 改进的模块<3>

1.3.5.52 unicodedata
....................

内部的 *note unicodedata: 123. 数据库已升级为使用 Unicode 11(1)。 （由
Benjamin Peterson 贡献。）

   ---------- Footnotes ----------

   (1) http://www.unicode.org/versions/Unicode11.0.0/


File: python.info,  Node: unittest<2>,  Next: unittest mock,  Prev: unicodedata<3>,  Up: 改进的模块<3>

1.3.5.53 unittest
.................

新的 ‘-k’ 命令行选项允许通过名称子字符串或类似于 Unix shell 的模式来筛选
测试项。 例如，‘python -m unittest -k foo’ 将运行
‘foo_tests.SomeTest.test_something’, ‘bar_tests.SomeTest.test_foo’，但不
会运行 ‘bar_tests.FooTest.test_something’。 （由 Jonas Haag 在
bpo-32071(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32071


File: python.info,  Node: unittest mock,  Next: urllib parse<3>,  Prev: unittest<2>,  Up: 改进的模块<3>

1.3.5.54 unittest.mock
......................

现在 *note sentinel: 50e. 属性会在它们被 *note 复制: 25. 或 *note 封存:
ca. 时保存其标识。 （由 Serhiy Storchaka 在 bpo-20804(1) 中贡献。）

新的 *note seal(): 50f. 函数允许 *note Mock: 373. 对实例进行密封，这将禁
止进一步创建属性模拟。 密封会以递归方式应用于自身模拟的所有属性。 （由
Mario Corchero 在 bpo-30541(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20804

   (2) https://bugs.python.org/issue30541


File: python.info,  Node: urllib parse<3>,  Next: uu,  Prev: unittest mock,  Up: 改进的模块<3>

1.3.5.55 urllib.parse
.....................

*note urllib.parse.quote(): 511. 已经从 RFC 2396(1) 更新为 RFC 3986(2)，
将 ‘~’ 添加到默认情况下从未引用的字符集。 （由 Christian Theune 和
Ratnadeep Debnath 在 bpo-16285(3) 中贡献。）

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2396.html

   (2) https://tools.ietf.org/html/rfc3986.html

   (3) https://bugs.python.org/issue16285


File: python.info,  Node: uu,  Next: uuid,  Prev: urllib parse<3>,  Up: 改进的模块<3>

1.3.5.56 uu
...........

*note uu.encode(): 513. 函数现在接受可选的 `backtick' 关键字参数。 当其
为真时，零会以 ‘'`'’ 而非空格来表示。 （由 Xiang Zhang 在 bpo-30103(1) 中
贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30103


File: python.info,  Node: uuid,  Next: warnings,  Prev: uu,  Up: 改进的模块<3>

1.3.5.57 uuid
.............

新的 *note UUID.is_safe: 515. 属性会从平台中继有关是否使用多进程安全模式
来生成所需 UUID 的信息。 （由 Barry Warsaw 在 bpo-22807(1) 中贡献。）

*note uuid.getnode(): 516. 现在更倾向于统一管理的 MAC 地址而不是本地管理
的 MAC 地址。 这样可以更好地保证从 *note uuid.uuid1(): 517. 返回的 UUID
的全局唯一性。 如果只有本地管理的 MAC 地址可用，则返回首个找到的此类地址
。 （由 Barry Warsaw 在 bpo-32107(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22807

   (2) https://bugs.python.org/issue32107


File: python.info,  Node: warnings,  Next: xml etree,  Prev: uuid,  Up: 改进的模块<3>

1.3.5.58 warnings
.................

默认警告过滤器的初始化已进行以下更改:

   * 通过命令行选项（包括 *note -b: 519. 以及新的 CPython 专属的 *note
     -X: 290. ‘dev’ 选项）启用的警告总是会通过 *note sys.warnoptions:
     51a. 属性被传递给警告机制。

   * 通过命令行或环境变量启用的警告过滤器现在具有以下优先顺序:

             * 用于 *note -b: 519. (或 ‘-bb’) 的 ‘BytesWarning’ 过滤器

             * 通过 *note -W: 15b. 选项指定的任何过滤器

             * 通过 *note PYTHONWARNINGS: 51b. 环境变量指定的任何过滤器

             * 任何其他 CPython 专属过滤器（例如 ‘-X dev’ 模式中新增的
               ‘default’ 过滤器）

             * 由警告机制所定义的任何隐式过滤器

   * 在 CPython 调试版本中，现在默认情况下会显示所有警告（隐式过滤器列表
     为空）

（由 Nick Coghlan 和 Victor Stinner 在 bpo-20361(1), bpo-32043(2) 以及
bpo-32230(3) 中贡献。）

在单文件脚本和交互式提示符中，默认情况下会再次显示已弃用警告。 详情参见
*note PEP 565; 在 __main__ 中显示 DeprecationWarning: 415.。 （由 Nick
Coghlan 在 bpo-31975(4) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20361

   (2) https://bugs.python.org/issue32043

   (3) https://bugs.python.org/issue32230

   (4) https://bugs.python.org/issue31975


File: python.info,  Node: xml etree,  Next: xmlrpc server,  Prev: warnings,  Up: 改进的模块<3>

1.3.5.59 xml.etree
..................

‘find()’ 方法中的 *note ElementPath: 51d. 描述词现在可以将当前节点文本与
‘[. = "text"]’ 进行比较，而不仅是子节点中的文本。 描述词还允许添加空格以
提高可读性。 （由 Stefan Behnel 在 bpo-31648(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31648


File: python.info,  Node: xmlrpc server,  Next: zipapp,  Prev: xml etree,  Up: 改进的模块<3>

1.3.5.60 xmlrpc.server
......................

‘SimpleXMLRPCDispatcher.register_function’ 现在可以被用作装饰器。 （由
Xiang Zhang 在 bpo-7769(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue7769


File: python.info,  Node: zipapp,  Next: zipfile,  Prev: xmlrpc server,  Up: 改进的模块<3>

1.3.5.61 zipapp
...............

函数 *note create_archive(): 520. 现在接受可选的 `filter' 参数，以允许用
户选择哪些文件应被加入归档包。 （由 Irmen de Jong 在 bpo-31072(1) 中贡献
。）

函数 *note create_archive(): 520. 现在接受可选的 `compressed' 参数，以生
成压缩归档包。 另外也加入了命令行选项 ‘--compress’ 以支持压缩。 （由
Zhiming Wang 在 bpo-31638(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31072

   (2) https://bugs.python.org/issue31638


File: python.info,  Node: zipfile,  Prev: zipapp,  Up: 改进的模块<3>

1.3.5.62 zipfile
................

*note ZipFile: 522. 现在接受新的 `compresslevel' 形参，以控制压缩级别。
（由 Bo Bayles 在 bpo-21417(1) 中贡献。）

‘ZipFile’ 所创建的归档包中的子目录现在会按字母表顺序保存。 （由 Bernhard
M. Wiedemann 在 bpo-30693(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21417

   (2) https://bugs.python.org/issue30693


File: python.info,  Node: C API 的改变<2>,  Next: 构建的改变<2>,  Prev: 改进的模块<3>,  Up: Python 3 7 有什么新变化

1.3.6 C API 的改变
------------------

已实现了用于线程本地存储的新 API。 相关概述请参阅 *note PEP 539;
用于线程局部存储的新 C API: 416.，完整参考文档请查看 *note Thread
Specific Storage (TSS) API: 427.。 （由 Masayuki Yamamoto 在
bpo-25658(1) 中贡献。)

新的 *note 上下文变量: 407. 功能开放了许多 *note 新的 C API: 447.。

新的 *note PyImport_GetModule(): 524. 函数会返回之前所导入的具有给定名称
的模块。 （由 Eric Snow 在 bpo-28411(2) 中贡献。）

新的 *note Py_RETURN_RICHCOMPARE: 525. 宏可以简化丰富比较函数的编写。 （
由 Petr Victorin 在 bpo-23699(3) 中贡献。）

新的 *note Py_UNREACHABLE: 526. 宏可用于标记不可到达的代码路径。 （由
Barry Warsaw 在 bpo-31338(4) 中贡献。）

*note tracemalloc: 11d. 现在通过新的 *note PyTraceMalloc_Track(): 527. 和
*note PyTraceMalloc_Untrack(): 528. 函数公开了一个 C API。 （由 Victor
Stinner 在 bpo-30054(5) 中贡献。）

新的 ‘import__find__load__start()’ 和 ‘import__find__load__done()’ 静态
标记可用于跟踪模块导入。 （由 Christian Heimes 在 bpo-31574(6) 中贡献。
）

结构体 *note PyMemberDef: 529, *note PyGetSetDef: 52a, *note
PyStructSequence_Field: 52b, *note PyStructSequence_Desc: 52c. 和
‘wrapperbase’ 的字段 ‘name’ 和 ‘doc’ 现在的类型为 ‘const char *’ 而不是
‘char *’。 （由 Serhiy Storchaka 在 bpo-28761(7) 中贡献。）

*note PyUnicode_AsUTF8AndSize(): 52d. 和 *note PyUnicode_AsUTF8(): 52e.
的结果类型现在是 ‘const char *’ 而非 ‘char *’。 （由 Serhiy Storchaka 在
bpo-28769(8) 中贡献。）

*note PyMapping_Keys(): 52f, *note PyMapping_Values(): 530. 和 *note
PyMapping_Items(): 531. 的结果现在肯定是列表，而非可能是列表也可能是元组
。 （由 Oren Milman 在 bpo-28280(9) 中贡献。）

添加了函数 *note PySlice_Unpack(): 532. 和 *note
PySlice_AdjustIndices(): 533.。 （由 Serhiy Storchaka 在 bpo-27867(10) 中
贡献。）

*note PyOS_AfterFork(): 534. 已弃用，建议改用新的 functions *note
PyOS_BeforeFork(): 535, *note PyOS_AfterFork_Parent(): 536. 和 *note
PyOS_AfterFork_Child(): 3ef.。 （由 Antoine Pitrou 在 bpo-16500(11) 中贡
献。）

曾经作为公共 API 一部分的 ‘PyExc_RecursionErrorInst’ 单例已被移除，因为
它的成员永远不会被清理，可能在解释器的最终化过程中导致段错误。 由 Xavier
de Gaye 在 bpo-22898(12) 和 bpo-30697(13) 中贡献。

添加 C API 对使用 timezone 的构造器 *note PyTimeZone_FromOffset(): 537.
和 *note PyTimeZone_FromOffsetAndName(): 538. 的时区的支持，以及通常
*note PyDateTime_TimeZone_UTC: 539. 使用 UTC 单例。 由 Paul Ganssle 在
bpo-10381(14) 中贡献。

‘PyThread_start_new_thread()’ 和 ‘PyThread_get_thread_ident()’ 的结果类
型以及 *note PyThreadState_SetAsyncExc(): 53a. 的 `id' 参数类型由 ‘long’
改为 ‘unsigned long’。 （由 Serhiy Storchaka 在 bpo-6532(15) 中贡献。）

现在 *note PyUnicode_AsWideCharString(): 53b. 如果第二个参数为 ‘NULL’ 并
且 ‘wchar_t*’ 字符串包含空字符则会引发 *note ValueError: 16d.。 （由
Serhiy Storchaka 在 bpo-30708(16) 中贡献。）

对启动顺序以及动态内存分配器管理的更改意味着早已记录在案的，对在调用大多
数 C API 函数之前调用 *note Py_Initialize(): 20f. 的要求的依赖现在变得更
加强烈，未遵循此要求可能导致嵌入式应用程序中的段错误。 请参阅此文档的
*note 移植到 Python 3.7: 419. 一节以及 C API 文档的 *note
在Python初始化之前: 53c. 一节了解更多细节。

新的 *note PyInterpreterState_GetID(): 53d. 会返回给定解释器的唯一 ID。
（由 Eric Snow 在 bpo-29102(17) 中贡献。）

现在当启用 *note UTF-8 模式: 412. 时 *note Py_DecodeLocale(): 53e, *note
Py_EncodeLocale(): 53f. 会使用 UTF-8 编码。 （由 Victor Stinner 在
bpo-29240(18) 中贡献。）

*note PyUnicode_DecodeLocaleAndSize(): 540. 和 *note
PyUnicode_EncodeLocale(): 541. 现在会为 ‘surrogateescape’ 错误句柄使用当
前区域编码。 （由 Victor Stinner 在 bpo-29240(19) 中贡献。）

*note PyUnicode_FindChar(): 542. 的 `start' 和 `end' 形参的行为现在调整
为与字符串切片类似。 （由 Xiang Zhang 在 bpo-28822(20) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25658

   (2) https://bugs.python.org/issue28411

   (3) https://bugs.python.org/issue23699

   (4) https://bugs.python.org/issue31338

   (5) https://bugs.python.org/issue30054

   (6) https://bugs.python.org/issue31574

   (7) https://bugs.python.org/issue28761

   (8) https://bugs.python.org/issue28769

   (9) https://bugs.python.org/issue28280

   (10) https://bugs.python.org/issue27867

   (11) https://bugs.python.org/issue16500

   (12) https://bugs.python.org/issue22898

   (13) https://bugs.python.org/issue30697

   (14) https://bugs.python.org/issue10381

   (15) https://bugs.python.org/issue6532

   (16) https://bugs.python.org/issue30708

   (17) https://bugs.python.org/issue29102

   (18) https://bugs.python.org/issue29240

   (19) https://bugs.python.org/issue29240

   (20) https://bugs.python.org/issue28822


File: python.info,  Node: 构建的改变<2>,  Next: 性能优化<3>,  Prev: C API 的改变<2>,  Up: Python 3 7 有什么新变化

1.3.7 构建的改变
----------------

对于 ‘--without-threads’ 构建的支持已被移除。 *note threading: 10b. 模块
现在将总是可用。 （由 Antoine Pitrou 在 bpo-31370(1) 中贡献。）

在非 OSX UNIX 平台上已不再包含用于构建 *note _ctypes: 2a. 模块的完整
libffi 副本。 现在当在此类平台上构建 ‘_ctypes’ 时需要事先装有 libffi 的
副本。 （由 Zachary Ware 在 bpo-27979(2) 中贡献。）

Windows 构建过程不再依赖 Subversion 来拉取外部源码，而是改用一段 Python
脚本从 GitHub 下载 zip 文件。 如果未在系统中找到 Python 3.6 (通过 ‘py
-3.6’)，则会使用 NuGet 下载一份 32 位的 Python 副本用于此目的。 （由
Zachary Ware 在 bpo-30450(3) 中贡献。）

*note ssl: f3. 模块需要兼容 OpenSSL 1.0.2 或 1.1 的 libssl。 OpenSSL
1.0.1 的生命期已于 2016-12-31 终止且不再受支持。 LibreSSL 暂时也不受支持
。 LibreSSL 发布版直到 2.6.4 版还缺少所需的 OpenSSL 1.0.2 API。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31370

   (2) https://bugs.python.org/issue27979

   (3) https://bugs.python.org/issue30450


File: python.info,  Node: 性能优化<3>,  Next: 其他 CPython 实现的改变,  Prev: 构建的改变<2>,  Up: Python 3 7 有什么新变化

1.3.8 性能优化
--------------

通过移植更多代码来使用 ‘METH_FASTCALL’ 的约定，可以显著地减少调用 C 代码
中实现的各类标准库的很多方法的开销。 （由 Victor Stinner 在
bpo-29300(1)、bpo-29507(2)、bpo-29452(3) 以及 bpo-29286(4) 中贡献。）

通过各种优化方式，使 Python 在 Linux 上的启动时间缩短了 10%，在 macOS 上
缩短了 30%。 （由 Victor Stinner, INADA Naoki 在 bpo-29585(5) 中，以及
Ivan Levkivskyi 在 bpo-31333(6) 中贡献。）

由于避免创建绑定方法案例的字节码更改，方法调用速度现在加快了 20%。 （由
Yury Selivanov 和 INADA Naoki 在 bpo-26110(7) 中贡献。） 对 *note
asyncio: 9. 模块里面的一些常用函数做了显著的性能优化。

   * *note asyncio.get_event_loop(): 45d. 函数已经改用 C 重新实现，使其
     执行速度加快了 15 倍。 （由 Yury Selivanov 在 bpo-32296(8) 中贡献。
     ）

   * *note asyncio.Future: 545. 回调管理已经过优化。 （由 Yury Selivanov
     在 bpo-32348(9) 中贡献。）

   * *note asyncio.gather(): 3ab. 的执行速度现在加快了 15%。 （由 Yury
     Selivanov 在 bpo-32355(10) 中贡献。）

   * 当 `delay' 参数为零或负值时 *note asyncio.sleep(): 3aa. 的执行速度
     现在加快了 2 倍。 （由 Andrew Svetlov 在 bpo-32351(11) 中贡献。）

   * asyncio 调试模式的执行开销已获减轻。 （由 Antoine Pitrou 在
     bpo-31970(12) 中贡献。）

作为 *note PEP 560 工作: 40d. 的结果，*note typing: 122. 的导入时间已减
少了 7 倍，许多与类型相关的操作现在会执行得更快。 （由 Ivan Levkivskyi 在
bpo-32226(13) 中贡献。）

*note sorted(): 546. 和 *note list.sort(): 547. 已经过优化，在通常情况下
执行速度可提升 40-75%。 （由 Elliot Gorokhovsky 在 bpo-28685(14) 中贡献
。）

*note dict.copy(): 548. 的执行速度现在加快了 5.5 倍。 （由 Yury
Selivanov 在 bpo-31179(15) 中贡献。）

当 `name' 未找到并且 `obj' 未重载 *note object.__getattr__(): 42a. 或
*note object.__getattribute__(): 549. 时 *note hasattr(): 54a. 和 *note
getattr(): 54b. 现在会比原来快大约 4 倍。 （由 INADA Naoki 在
bpo-32544(16) 中贡献。）

在字符串中搜索特定的 Unicode 字符（例如乌克兰语字母“Є”）会比搜索其他字符
慢上 25 倍。 而现在最坏情况下也只会慢上 3 倍。 （由 Serhiy Storchaka 在
bpo-24821(17) 中贡献。）

*note collections.namedtuple(): 1a1. 工厂对象已经重写实现，使得创建具名
元组的速度加快了 4 到 6 倍。 （由 Jelle Zijlstra 在 bpo-28638(18) 中贡献
，进一步的改进由 INADA Naoki, Serhiy Storchaka 和 Raymond Hettinger 贡献
。）

现在 ‘date.fromordinal()’ 和 ‘date.fromtimestamp()’ 在通常情况下执行速度
可提升 30%。 （由 Paul Ganssle 在 bpo-32403(19) 中贡献。）

由于使用了 *note os.scandir(): 389.，现在 *note os.fwalk(): 4ba. 函数执
行速度提升了 2 倍。 （由 Serhiy Storchaka 在 bpo-25996(20) 中贡献。）

由于使用了 *note os.scandir(): 389. 函数，*note shutil.rmtree(): 349. 函
数的执行速度已经提升了 20–40%。 （由 Serhiy Storchaka 在 bpo-28564(21) 中
贡献。）

*note 正则表达式: dd. 忽略大小写的匹配和搜索已获得优化。 现在搜索某些模
式的速度提升了 20 倍。 （由 Serhiy Storchaka 在 bpo-30285(22) 中贡献。）

*note re.compile(): 54c. 现在会将 ‘flags’ 形参转换为 int 对象，如果它是
‘RegexFlag’ 的话。 它现在会和 Python 3.5 一样快，而比 Python 3.6 快大约
10%，实际速度取决于具体的模式。 （由 INADA Naoki 在 bpo-31671(23) 中贡献
。）

*note selectors.EpollSelector: 54d, *note selectors.PollSelector: 54e. 和
*note selectors.DevpollSelector: 54f. 这几个类的 *note modify(): 550. 方
法在重负载下可以加快 10% 左右。 （由 Giampaolo Rodola’ 在 bpo-30014(24)
中贡献。）

常量折叠已经从窥孔优化器迁移至新的 AST 优化器，后者可以以更高的一致性来
执行优化。 （由 Eugene Toder 和 INADA Naoki 在 bpo-29469(25) 和
bpo-11549(26) 中贡献。）

*note abc: 3. 中的大部分函数和方法已经用 C 重写。 这使得创建抽像基类以及
调用其 *note isinstance(): 551. 和 *note issubclass(): 552. 的速度加快了
1.5 倍。 这也使得 Python 启动耗时减少了 10%。 （由 Ivan Levkivskyi 和
INADA Naoki 在 bpo-31333(27) 中贡献。）

在不构造子类时，通过使用快速路径构造器使得 *note datetime.date: 19d. 和
*note datetime.datetime: 19f. 的替代构造器获得了显著的速度提升。 （由
Paul Ganssle 在 bpo-32403(28) 中贡献。）

在特定情况下 *note array.array: 216. 实例的比较速度已获得很大提升。 现在
当比较存放相同的整数类型的值的数组时会比原来快 10 到 70 倍。 （由 Adrian
Wielgosik 在 bpo-24700(29) 中贡献。）

在大多数平台上 *note math.erf(): 553. 和 *note math.erfc(): 554. 函数现
在使用（更快的）C 库实现。 （由 Serhiy Storchaka 在 bpo-26121(30) 中贡献
。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29300

   (2) https://bugs.python.org/issue29507

   (3) https://bugs.python.org/issue29452

   (4) https://bugs.python.org/issue29286

   (5) https://bugs.python.org/issue29585

   (6) https://bugs.python.org/issue31333

   (7) https://bugs.python.org/issue26110

   (8) https://bugs.python.org/issue32296

   (9) https://bugs.python.org/issue32348

   (10) https://bugs.python.org/issue32355

   (11) https://bugs.python.org/issue32351

   (12) https://bugs.python.org/issue31970

   (13) https://bugs.python.org/issue32226

   (14) https://bugs.python.org/issue28685

   (15) https://bugs.python.org/issue31179

   (16) https://bugs.python.org/issue32544

   (17) https://bugs.python.org/issue24821

   (18) https://bugs.python.org/issue28638

   (19) https://bugs.python.org/issue32403

   (20) https://bugs.python.org/issue25996

   (21) https://bugs.python.org/issue28564

   (22) https://bugs.python.org/issue30285

   (23) https://bugs.python.org/issue31671

   (24) https://bugs.python.org/issue30014

   (25) https://bugs.python.org/issue29469

   (26) https://bugs.python.org/issue11549

   (27) https://bugs.python.org/issue31333

   (28) https://bugs.python.org/issue32403

   (29) https://bugs.python.org/issue24700

   (30) https://bugs.python.org/issue26121


File: python.info,  Node: 其他 CPython 实现的改变,  Next: 已弃用的 Python 行为,  Prev: 性能优化<3>,  Up: Python 3 7 有什么新变化

1.3.9 其他 CPython 实现的改变
-----------------------------

   * 跟踪钩子现在可以选择不接收 ‘line’ 而是选择从解释器接收 ‘opcode’ 事
     件，具体做法是在被跟踪的帧上相应地设置新的 ‘f_trace_lines’ 和
     ‘f_trace_opcodes’ 属性。 （由 Nick Coghlan 在 bpo-31344(1) 中贡献。
     ）

   * 修复了一些命名空间包模块属性的一致性问题。 命名空间模块对象的
     ‘__file__’ 被设置为 ‘None’ (原先未设置)，对象的 ‘__spec__.origin’ 也
     被设置为 ‘None’ (之前为字符串 ‘"namespace"’)。 参见 bpo-32305(2)。
     而且，命名空间模块对象的 ‘__spec__.loader’ 被设置的值与
     ‘__loader__’ 相同 (原先前者被设置为 ‘None’)。 参见 bpo-32303(3)。

   * *note locals(): 556. 字典现在以变量定义的词法顺序显示。 原先未定义
     顺序。 （由 Raymond Hettinger 在 bpo-32690(4) 中贡献。）

   * *note distutils: 38. ‘upload’ 命令不会再试图将行结束字符 CR 改为
     CRLF。 这修复了 sdists 的一个以与 CR 等价的字节结束的数据损坏问题。
     （由 Bo Bayles 在 bpo-32304(5) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31344

   (2) https://bugs.python.org/issue32305

   (3) https://bugs.python.org/issue32303

   (4) https://bugs.python.org/issue32690

   (5) https://bugs.python.org/issue32304


File: python.info,  Node: 已弃用的 Python 行为,  Next: 已弃用的 Python 模块、函数和方法,  Prev: 其他 CPython 实现的改变,  Up: Python 3 7 有什么新变化

1.3.10 已弃用的 Python 行为
---------------------------

在推导式和生成器表达式中的 yield 语句（包括 ‘yield’ 和 ‘yield from’ 子句
）现在已弃用（最左端的 ‘for’ 子句中的可迭代对象表达式除外）。 这确保了推
导式总是立即返回适当类型的容器（而不是有可能返回 *note generator
iterator: 558. 对象），这样生成器表达式不会试图将它们的隐式输出与任何来
自显式 yield 表达式的输出交错起来。 在 Python 3.7 中，这样的表达式会在编
译时引发 *note DeprecationWarning: 15a.，在 Python 3.8 中则将引发 *note
SyntaxError: 559.。 （由 Serhiy Storchaka 在 bpo-10544(1) 中贡献。）

从 *note object.__complex__(): 2c5. 返回一个 *note complex: 2c1. 的子类
的行为已弃用并将在未来的 Python 版本中引发错误。 这使得 ‘__complex__()’
的行为与 *note object.__int__(): 2c3. 和 *note object.__float__(): 2c4.
保持一致。 （由 Serhiy Storchaka 在 bpo-28894(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10544

   (2) https://bugs.python.org/issue28894


File: python.info,  Node: 已弃用的 Python 模块、函数和方法,  Next: 已弃用的 C API 函数和类型,  Prev: 已弃用的 Python 行为,  Up: Python 3 7 有什么新变化

1.3.11 已弃用的 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::


File: python.info,  Node: aifc,  Next: asyncio<4>,  Up: 已弃用的 Python 模块、函数和方法

1.3.11.1 aifc
.............

‘aifc.openfp()’ 已弃用并将在 Python 3.9 中被移除。 请改用 *note
aifc.open(): 55c.。 （由 Brian Curtin 在 bpo-31985(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31985


File: python.info,  Node: asyncio<4>,  Next: collections<3>,  Prev: aifc,  Up: 已弃用的 Python 模块、函数和方法

1.3.11.2 asyncio
................

对 *note asyncio.Lock: 3ae. 和其他 asyncio 同步原语的 ‘await’ 实例的直接
支持已弃用。 想要获取并释放同步资源必须使用异步上下文管理器。 （由
Andrew Svetlov 在 bpo-32253(1) 中贡献。）

‘asyncio.Task.current_task()’ 和 ‘asyncio.Task.all_tasks()’ 方法已弃用。
（由 Andrew Svetlov 在 bpo-32250(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32253

   (2) https://bugs.python.org/issue32250


File: python.info,  Node: collections<3>,  Next: dbm<2>,  Prev: asyncio<4>,  Up: 已弃用的 Python 模块、函数和方法

1.3.11.3 collections
....................

在 Python 3.8 中，*note collections.abc: 1e. 内的抽象基类将不会再通过常
规的 *note collections: 1d. 模块公开。 这有助于更清晰地区别具体类与抽象
基类。 （由 Serhiy Storchaka 在 bpo-25988(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25988


File: python.info,  Node: dbm<2>,  Next: enum<2>,  Prev: collections<3>,  Up: 已弃用的 Python 模块、函数和方法

1.3.11.4 dbm
............

*note dbm.dumb: 32. 现在支持读取只读文件，且当其未被更改时不会再写入索引
文件。 现在如果索引文件丢失并在 ‘'r'’ 与 ‘'w'’ 模式下被重新创建，则会发
出已弃用警告（在未来的 Python 发布版中将改为错误）。 （由 Serhiy
Storchaka 在 bpo-28847(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28847


File: python.info,  Node: enum<2>,  Next: gettext<2>,  Prev: dbm<2>,  Up: 已弃用的 Python 模块、函数和方法

1.3.11.5 enum
.............

在 Python 3.8 中，尝试在 ‘Enum’ 类中检查非 Enum 对象将引发 *note
TypeError: 1fe. (例如 ‘1 in Color’)；类似地，尝试在 ‘Flag’ 成员中检查非
Flag 对象也将引发 *note TypeError: 1fe. (例如 ‘1 in Perm.RW’)；目前，两
种操作均会返回 *note False: 48e.。 （由 Ethan Furman 在 bpo-33217(1) 中
贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33217


File: python.info,  Node: gettext<2>,  Next: importlib<3>,  Prev: enum<2>,  Up: 已弃用的 Python 模块、函数和方法

1.3.11.6 gettext
................

使用非整数值在 *note gettext: 87. 中选择复数形式现在已弃用。 它从未正确
地发挥作用。 （由 Serhiy Storchaka 在 bpo-28692(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28692


File: python.info,  Node: importlib<3>,  Next: locale<2>,  Prev: gettext<2>,  Up: 已弃用的 Python 模块、函数和方法

1.3.11.7 importlib
..................

下列方法 *note MetaPathFinder.find_module(): 563. (被 *note
MetaPathFinder.find_spec() 替代: 564.) 和 *note
PathEntryFinder.find_loader(): 565. (被 *note
PathEntryFinder.find_spec() 替代: 566.) 都在 Python 3.4 中已弃用，现在会
引发 *note DeprecationWarning: 15a.。 （由 Matthias Bussonnier 在
bpo-29576(1) 中贡献）

*note importlib.abc.ResourceLoader: 567. ABC 已弃用，推荐改用 *note
importlib.abc.ResourceReader: 44e.。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29576


File: python.info,  Node: locale<2>,  Next: macpath,  Prev: importlib<3>,  Up: 已弃用的 Python 模块、函数和方法

1.3.11.8 locale
...............

*note locale.format(): 569. 已弃用，请改用 *note locale.format_string():
4aa.。 （由 Garvit 在 bpo-10379(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10379


File: python.info,  Node: macpath,  Next: threading<2>,  Prev: locale<2>,  Up: 已弃用的 Python 模块、函数和方法

1.3.11.9 macpath
................

‘macpath’ 现在已弃用，将在 Python 3.8 中被移除。 （由 Chi Hsuan Yen 在
bpo-9850(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue9850


File: python.info,  Node: threading<2>,  Next: socket<4>,  Prev: macpath,  Up: 已弃用的 Python 模块、函数和方法

1.3.11.10 threading
...................

‘dummy_threading’ 和 ‘_dummy_thread’ 已弃用。 构建禁用线程的 Python 已不
再可能。 请改用 *note threading: 10b.。 （由 Antoine Pitrou 在
bpo-31370(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31370


File: python.info,  Node: socket<4>,  Next: ssl<3>,  Prev: threading<2>,  Up: 已弃用的 Python 模块、函数和方法

1.3.11.11 socket
................

*note socket.htons(): 56d. 和 *note socket.ntohs(): 56e. 中的静默参数截
断已弃用。 在未来的 Python 版本中，如果传入的参数长度大于 16 比特位，将
会引发异常。 （由 Oren Milman 在 bpo-28332(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28332


File: python.info,  Node: ssl<3>,  Next: sunau,  Prev: socket<4>,  Up: 已弃用的 Python 模块、函数和方法

1.3.11.12 ssl
.............

*note ssl.wrap_socket(): 570. 已弃用。 请改用 *note
ssl.SSLContext.wrap_socket(): 4ea.。 （由 Christian Heimes 在
bpo-28124(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28124


File: python.info,  Node: sunau,  Next: sys<4>,  Prev: ssl<3>,  Up: 已弃用的 Python 模块、函数和方法

1.3.11.13 sunau
...............

‘sunau.openfp()’ 已弃用并将在 Python 3.9 中被移除。 请改用 *note
sunau.open(): 572.。 （由 Brian Curtin 在 bpo-31985(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31985


File: python.info,  Node: sys<4>,  Next: wave,  Prev: sunau,  Up: 已弃用的 Python 模块、函数和方法

1.3.11.14 sys
.............

已弃用 ‘sys.set_coroutine_wrapper()’ 和 ‘sys.get_coroutine_wrapper()’。

未写入文档的 ‘sys.callstats()’ 函数已弃用并将在未来的 Python 版本中被移
除。 （由 Victor Stinner 在 bpo-28799(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28799


File: python.info,  Node: wave,  Prev: sys<4>,  Up: 已弃用的 Python 模块、函数和方法

1.3.11.15 wave
..............

‘wave.openfp()’ 已弃用并将在 Python 3.9 中被移除。 请改用 *note
wave.open(): 219.。 （由 Brian Curtin 在 bpo-31985(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31985


File: python.info,  Node: 已弃用的 C API 函数和类型,  Next: 平台支持的移除,  Prev: 已弃用的 Python 模块、函数和方法,  Up: Python 3 7 有什么新变化

1.3.12 已弃用的 C API 函数和类型
--------------------------------

如果 ‘Py_LIMITED_API’ 未设定或设定为范围在 ‘0x03050400’ 和 ‘0x03060000’
(不含) 之间，或为 ‘0x03060100’ 或更高的值，函数 *note
PySlice_GetIndicesEx(): 576. 已弃用并被一个宏所替代。 （由 Serhiy
Storchaka 在 bpo-27867(1) 中贡献。）

*note PyOS_AfterFork(): 534. 已弃用。 请改用 *note PyOS_BeforeFork():
535, *note PyOS_AfterFork_Parent(): 536. 或 *note
PyOS_AfterFork_Child(): 3ef.。 （由 Antoine Pitrou 在 bpo-16500(2) 中贡
献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27867

   (2) https://bugs.python.org/issue16500


File: python.info,  Node: 平台支持的移除,  Next: API 与特性的移除<2>,  Prev: 已弃用的 C API 函数和类型,  Up: Python 3 7 有什么新变化

1.3.13 平台支持的移除
---------------------

   * 官方已不再支持 FreeBSD 9 及更旧的版本。

   * 为了完整的 Unicode 支持，包括在扩展模块之内，*nix 平台现在至少应当
     提供 ‘C.UTF-8’ (完整区域), ‘C.utf8’ (完整区域) 或 ‘UTF-8’
     (‘LC_CTYPE’ 专属区域) 中的一个作为基于 ‘ASCII’ 的传统 ‘C’ 区域的替
     代。

   * 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 配置文件(1) 提供了一个使用 CPython 测试套件中的
     SSL 兼容性测试架构(2) 基于 OpenSSL 1.1.0 进行构建和链接的例子，而不
     是使用过时的系统所提供的 OpenSSL。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/.travis.yml

   (2) 
https://github.com/python/cpython/tree/3.9/Tools/ssl/multissltests.py


File: python.info,  Node: API 与特性的移除<2>,  Next: 移除的模块,  Prev: 平台支持的移除,  Up: Python 3 7 有什么新变化

1.3.14 API 与特性的移除
-----------------------

下列特性与 API 已从 Python 3.7 中移除:

   * ‘os.stat_float_times()’ 函数已被移除。 它在 Python 2.3 中被引入用于
     向下兼容 Python 2.2，并自 Python 3.1 起就已弃用。

   * 在 *note re.sub(): 579. 的替换模块中由 ‘'\'’ 与一个 ASCII 字母构成
     的未知转义在 Python 3.5 中已弃用，现在将会引发错误。

   * 在 *note tarfile.TarFile.add(): 57a. 中移除了对 `exclude' 参数的支
     持。 它在 Python 2.7 和 3.2 中已弃用。 请改用 `filter' 参数。

   * ‘ntpath’ 模块中的 ‘splitunc()’ 函数在 Python 3.1 中已弃用，现在已被
     移除。 请改用 *note splitdrive(): 57b. 函数。

   * *note collections.namedtuple(): 1a1. 不再支持 `verbose' 形参或
     ‘_source’ 属性，该属性会显示为具名元组类所生成的源代码。 这是加速类
     创建的设计优化的一部分。 （由 Jelle Zijlstra 在 bpo-28638(1) 中贡献
     ，进一步的改进由 INADA Naoki, Serhiy Storchaka 和 Raymond Hettinger
     贡献。）

   * 函数 *note bool(): 2bd, *note float(): 1fd, *note list(): 1f8. 和
     *note tuple(): 1a2. 不再接受关键字参数。 *note int(): 204. 的第一个
     参数现在只能作为位置参数传入。

   * 移除了之前在 Python 2.4 中已弃用的 *note plistlib: cf. 模块的类
     ‘Plist’, ‘Dict’ 和 ‘_InternalDict’。 作为函数 ‘readPlist()’ 和
     ‘readPlistFromBytes()’ 返回结果的 Dict 值现在为普通 dict。 你不能再
     使用属性访问来获取这些字典的项。

   * ‘asyncio.windows_utils.socketpair()’ 函数已被移除。 请改用 *note
     socket.socketpair(): 57c. 函数，它自 Python 3.5 起就在所有平台上可
     用。 ‘asyncio.windows_utils.socketpair’ 在 Python 3.5 及更新版本上
     只是 ‘socket.socketpair’ 的别名。

   * *note asyncio: 9. 不再将 *note selectors: e6. 和 ‘_overlapped’ 模块
     导出为 ‘asyncio.selectors’ 和 ‘asyncio._overlapped’。 请将 ‘from
     asyncio import selectors’ 替换为 ‘import selectors’。

   * 现在已禁止直接实例化 *note ssl.SSLSocket: 192. 和 *note
     ssl.SSLObject: 4e8. 对象。 相应构造器从未写入文档、也从未作为公有构
     造器进行测试或设计。 用户应当使用 *note ssl.wrap_socket(): 570. 或
     *note ssl.SSLContext: 4e9.。 （由 Christian Heimes 在 bpo-32951(2)
     中贡献。）

   * 未被使用的 *note distutils: 38. ‘install_misc’ 命令已被移除。 （由
     Eric N. Vander Weele 在 bpo-29218(3) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28638

   (2) https://bugs.python.org/issue32951

   (3) https://bugs.python.org/issue29218


File: python.info,  Node: 移除的模块,  Next: Windows 专属的改变,  Prev: API 与特性的移除<2>,  Up: Python 3 7 有什么新变化

1.3.15 移除的模块
-----------------

‘fpectl’ 模块已被移除。 它从未被默认启用，从未在 x86-64 上正确发挥效果，
并且它对 Python ABI 的改变会导致 C 扩展的意外损坏。 （由 Nathaniel J.
Smith 在 bpo-29137(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29137


File: python.info,  Node: Windows 专属的改变,  Next: 移植到 Python 3 7,  Prev: 移除的模块,  Up: Python 3 7 有什么新变化

1.3.16 Windows 专属的改变
-------------------------

Python 启动器（py.exe）可以接受 32 位或 64 位标记而 `不必' 同时指定一个
小版本。 因此 ‘py -3-32’ 和 ‘py -3-64’ 与 ‘py -3.7-32’ 均为有效，并且现
在还接受 -`m'-64 和 -`m.n'-64 来强制使用 64 位 python 命令，即使是本应使
用 32 位的时候。 如果指定版本不可用则 py.exe 将报错退出。 （由 Steve
Barnes 在 bpo-30291(1) 中贡献。）

启动器可以运行 ‘py -0’ 来列出已安装的所有 python，`默认版本会以星号标出
'。 运行 ‘py -0p’ 将同时列出相应的路径。 如果运行 py 时指定了无法匹配的
版本，它将显示 `简短形式' 的可用版本列表。 （由 Steve Barnes 在
bpo-30362(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30291

   (2) https://bugs.python.org/issue30362


File: python.info,  Node: 移植到 Python 3 7,  Next: Python 3 7 1 中的重要变化,  Prev: Windows 专属的改变,  Up: Python 3 7 有什么新变化

1.3.17 移植到 Python 3.7
------------------------

本节列出了先前描述的更改以及可能需要更改代码的其他错误修正.

* Menu:

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


File: python.info,  Node: Python 行为的更改,  Next: 更改的Python API<2>,  Up: 移植到 Python 3 7

1.3.17.1 Python 行为的更改
..........................

   * *note async: 2d7. 和 *note await: 2d8. 现在是保留关键字。 使用了这
     些名称作为标识符的代码现在将引发 *note SyntaxError: 559.。 （由
     Jelle Zijlstra 在 bpo-30406(1) 中贡献。）

   * PEP 479(2) 在 Python 3.7 中对所有代码启用，在协程和生成器中直接或间
     接引发的 *note StopIteration: 581. 异常会被转换为 *note
     RuntimeError: 3dc. 异常。 （由 Yury Selivanov 在 bpo-32670(3) 中贡
     献。）

   * *note object.__aiter__(): 582. 方法不再能被声明为异步的。 （由 Yury
     Selivanov 在 bpo-31709(4) 中贡献。）

   * 由于一个疏忽，之前的 Python 版本会错误地接受以下语法:

          f(1 for x in [1],)

          class C(1 for x in [1]):
              pass

     现在 Python 3.7 会正确地引发 *note SyntaxError: 559.，因为生成器表
     达式总是必须直接包含于一对括号之内， 且前后都不能有逗号，仅在调用时
     可以忽略重复的括号。 （由 Serhiy Storchaka 在 bpo-32012(5) 和
     bpo-32023(6) 中贡献。）

   * 现在当使用 *note -m: 443. 开关时，会将初始工作目录添加到 *note
     sys.path: 261.，而不再是一个空字符串（即在每次导入时动态地指明当前
     工作目录）。 任何会检测该空字符串，或是以其他方式依赖之前行为的的程
     序将需要进行相应的更新（例如改为还要检测 ‘os.getcwd()’ 或
     ‘os.path.dirname(__main__.__file__)’，具体做法首先要取决于为何要对
     代码执行空字符串检测）。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30406

   (2) https://www.python.org/dev/peps/pep-0479

   (3) https://bugs.python.org/issue32670

   (4) https://bugs.python.org/issue31709

   (5) https://bugs.python.org/issue32012

   (6) https://bugs.python.org/issue32023


File: python.info,  Node: 更改的Python API<2>,  Next: C API 中的改变<2>,  Prev: Python 行为的更改,  Up: 移植到 Python 3 7

1.3.17.2 更改的Python API
.........................

   * ‘socketserver.ThreadingMixIn.server_close()’ 现在会等待所有非守护线
     程完成。 将新增的 ‘socketserver.ThreadingMixIn.block_on_close’ 类属
     性设为 ‘False’ 可获得 3.7 之前版本的行为。 （由 Victor Stinner 在
     bpo-31233(1) 和 bpo-33540(2) 中贡献。）

   * ‘socketserver.ForkingMixIn.server_close()’ 现在会等等所有子进程完成
     。 将新增的 ‘socketserver.ForkingMixIn.block_on_close’ 类属性设为
     ‘False’ 可获得 3.7 之前版本的行为。 （由 Victor Stinner 在
     bpo-31151(3) 和 bpo-33540(4) 中贡献。）

   * 某些情况下 *note locale.localeconv(): 584. 函数现在会临时将
     ‘LC_CTYPE’ 区域设置为 ‘LC_NUMERIC’ 的值。 （由 Victor Stinner 在
     bpo-31900(5) 中贡献。）

   * 如果 `path' 为字符串 *note pkgutil.walk_packages(): 585. 现在会引发
     *note ValueError: 16d.。 之前则是返回一个空列表。 （由 Sanyam
     Khurana 在 bpo-24744(6) 中贡献。）

   * *note string.Formatter.format(): 586. 的格式字符串参数现在为 *note
     仅限位置: 3c9. 参数。 将其作为关键字参数传入的方式自 Python 3.5 起
     已弃用。 （由 Serhiy Storchaka 在 bpo-29193(7) 中贡献。）

   * 类 *note http.cookies.Morsel: 587. 的属性 *note key: 588, *note
     value: 589. 和 *note coded_value: 58a. 现在均为只读。 对其赋值的操
     作自 Python 3.5 起已弃用。 要设置它们的值请使用 *note set(): 58b. 方
     法。 （由 Serhiy Storchaka 在 bpo-29192(8) 中贡献。）

   * *note os.makedirs(): 4c3. 的 `mode' 参数不会再影响新建中间层级目录
     的文件权限位。 要设置它们的文件权限位你可以在发起调用 ‘makedirs()’
     之前设置 umask。 （由 Serhiy Storchaka 在 bpo-19930(9) 中贡献。）

   * *note struct.Struct.format: 58c. 的类型现在是 *note str: 205. 而非
     *note bytes: 172.。 （由 Victor Stinner 在 bpo-21071(10) 中贡献。）

   * *note parse_multipart(): 282. 现在接受 `encoding' 和 `errors' 参数
     并返回与 ‘FieldStorage’ 同样的结果：对于非文件字段，与键相关联的值
     是一个字符串列表，而非字节串。 （由 Pierre Quentel 在 bpo-29979(11)
     中贡献。）

   * 由于 *note socket: ef. 中的内部更改，在由旧版 Python 中的 *note
     socket.share: 58d. 所创建的套接字上调用 *note socket.fromshare():
     58e. 已不受支持。

   * *note BaseException: 2db. 的 ‘repr’ 已更改为不包含末尾的逗号。 大多
     数异常都会受此更改影响。 （由 Serhiy Storchaka 在 bpo-30399(12) 中
     贡献。）

   * *note datetime.timedelta: 2ca. 的 ‘repr’ 已更改为在输出中包含关键字
     参数。 （由 Utkarsh Upadhyay 在 bpo-30302(13) 中贡献。）

   * 因为 *note shutil.rmtree(): 349. 现在是使用 *note os.scandir():
     389. 函数实现的，用户指定的句柄 `onerror' 现在被调用时如果列目录失
     败会附带第一个参数 ‘os.scandir’ 而不是 ‘os.listdir’。

   * 未来可能加入在正则表达式中对 Unicode 技术标准 #18(14) 中嵌套集合与
     集合操作的支持。 这会改变现有语法。 为了推动这项未来的改变，目前在
     有歧义的情况下会引发 *note FutureWarning: 435.。 这包括以字面值
     ‘'['’ 开头或包含字面值字符序列 ‘'--'’, ‘'&&'’, ‘'~~'’ 以及 ‘'||'’ 的
     集合。 要避免警告，请用反斜杠对其进行转义。 （由 Serhiy Storchaka 在
     bpo-30349(15) 中贡献。）

   * 基于可以匹配空字符串的 *note 正则表达式: dd. 对字符串进行拆分的结果
     已被更改。 例如基于 ‘r'\s*'’ 的拆分现在不仅会像原先那样拆分空格符，
     而且会拆分所有非空格字符之前和字符串结尾处的空字符串。 通过将模式修
     改为 ‘r'\s+'’ 可以恢复原先的行为。 自 Python 3.5 开始此类模式将会引
     发 *note FutureWarning: 435.。

     对于同时匹配空字符串和非空字符串的模式，在其他情况下搜索所有匹配的
     结果也可能会被更改。 例如在字符串 ‘'a\n\n'’ 中，模式
     ‘r'(?m)^\s*?$'’ 将不仅会匹配位置 2 和 3 上的空字符串，还会匹配位置
     2–3 上的字符串 ‘'\n'’。 想要只匹配空行，模式应当改写为
     ‘r'(?m)^[^\S\n]*$'’。

     *note re.sub(): 579. 现在会替换与前一个的非空匹配相邻的空匹配。 例
     如 ‘re.sub('x*', '-', 'abxd')’ 现在会返回 ‘'-a-b--d-'’ 而不是
     ‘'-a-b-d-'’ (’b’ 和 ’d’ 之间的第一个减号是替换 ’x’，而第二个减号则
     是替换 ’x’ 和 ’d’ 之间的空字符串)。

     （由 Serhiy Storchaka 在 bpo-25054(16) 和 bpo-32308(17) 中贡献。）

   * *note re.escape(): 58f. 更改为只转义正则表达式特殊字符，而不转义
     ASCII 字母、数字和 ‘'_'’ 以外的所有字符。 （由 Serhiy Storchaka 在
     bpo-29995(18) 中贡献。）

   * *note tracemalloc.Traceback: 503. 帧现在是按从最旧到最新排序，以便
     与 *note traceback: 11c. 更为一致。 （由 Jesse Bakker 在
     bpo-32121(19) 中贡献。）

   * 在支持 *note socket.SOCK_NONBLOCK: 590. 或 *note
     socket.SOCK_CLOEXEC: 591. 标志位的操作系统上，*note socket.type:
     592. 不再应用它们。 因此，像 ‘if sock.type == socket.SOCK_STREAM’ 之
     类的检测会在所有平台上按预期的方式工作。 （由 Yury Selivanov 在
     bpo-32331(20) 中贡献。）

   * 在 Windows 上当重定向标准句柄时，*note subprocess.Popen: 3db. 的
     `close_fds' 参数的默认值从 *note False: 48e. 更改为 *note True:
     593.。 如果你以前依赖于在使用带有标准 io 重定向的 *note
     subprocess.Popen: 3db. 时所继承的句柄，则必须传入 ‘close_fds=False’
     以保留原先的行为，或是使用 *note STARTUPINFO.lpAttributeList: 594.。

   * *note importlib.machinery.PathFinder.invalidate_caches(): 595. – 此
     方法隐式地影响 *note importlib.invalidate_caches(): 596. – 现在会删
     除 *note sys.path_importer_cache: 597. 中被设为 ‘None’ 的条目。 （
     由 Brett Cannon 在 bpo-33169(21) 中贡献。）

   * 在 *note asyncio: 9. 中，*note loop.sock_recv(): 598, *note
     loop.sock_sendall(): 599, *note loop.sock_accept(): 59a, *note
     loop.getaddrinfo(): 59b, *note loop.getnameinfo(): 59c. 已被更改为
     正确的协程方法以与培训五日文档相匹配。 之前，这些方法会返回 *note
     asyncio.Future: 545. 实例。 （由 Yury Selivanov 在 bpo-32327(22) 中
     贡献。）

   * *note asyncio.Server.sockets: 59d. 现在会返回服务器套接字列表的副本
     ，而不是直接地返回它。 （由 Yury Selivanov 在 bpo-32662(23) 中贡献
     。）

   * *note Struct.format: 58c. 现在是一个 *note str: 205. 实例而非 *note
     bytes: 172. 实例。 （由 Victor Stinner 在 bpo-21071(24) 中贡献。）

   * 现在可以通过将 ‘required=True’ 传给 *note
     ArgumentParser.add_subparsers(): 59e. 使得 *note argparse: 5. 子解
     析器成为必需的。 （由 Anthony Sottile 在 bpo-26510(25) 中贡献。）

   * *note ast.literal_eval(): 59f. 现在更为严格。 任意地加减数字已不再
     被允许。 （由 Serhiy Storchaka 在 bpo-31778(26) 中贡献。）

   * 当一个日期超出 ‘0001-01-01’ 到 ‘9999-12-31’ 范围时 *note
     Calendar.itermonthdates: 5a0. 现在将始终如一地引发异常，以便支持不
     能容忍此类异常的应用程序，可以使用新增的 *note
     Calendar.itermonthdays3: 5a1. 和 *note Calendar.itermonthdays4:
     5a2.。 这些新方法返回元组，并且其不受 *note datetime.date: 19d. 所
     支持的范围限制。 （由 Alexander Belopolsky 在 bpo-28292(27) 中贡献
     。）

   * *note collections.ChainMap: 5a3. 现在会保留底层映射的顺序。 （由
     Raymond Hettinger 在 bpo-32792(28) 中贡献。）

   * 如果在解释器关闭期间被调用，*note
     concurrent.futures.ThreadPoolExecutor: 18c. 和 *note
     concurrent.futures.ProcessPoolExecutor: 196. 的 ‘submit()’ 方法现在
     会引发 *note RuntimeError: 3dc.。 （由 Mark Nemec 在 bpo-33097(29)
     中贡献。）

   * *note configparser.ConfigParser: 5a4. 构造器现在使用 ‘read_dict()’
     来处理默认值，以使其行为与解析器的其余部分保持致。 在默认字典中的非
     字符串键和值现在会被隐式地转换为字符串。 （由 James Tocknell 在
     bpo-23835(30) 中贡献。）

   * 一些未写入文档的内部导入已被移除。 一个例子是 ‘os.errno’ 已不再可用
     ；应改为直接使用 ‘import errno’。 请注意此类未写入文档的内部导入可
     能未经通知地随时被移除，甚至是在微版本号发行版中移除。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31233

   (2) https://bugs.python.org/issue33540

   (3) https://bugs.python.org/issue31151

   (4) https://bugs.python.org/issue33540

   (5) https://bugs.python.org/issue31900

   (6) https://bugs.python.org/issue24744

   (7) https://bugs.python.org/issue29193

   (8) https://bugs.python.org/issue29192

   (9) https://bugs.python.org/issue19930

   (10) https://bugs.python.org/issue21071

   (11) https://bugs.python.org/issue29979

   (12) https://bugs.python.org/issue30399

   (13) https://bugs.python.org/issue30302

   (14) https://unicode.org/reports/tr18/

   (15) https://bugs.python.org/issue30349

   (16) https://bugs.python.org/issue25054

   (17) https://bugs.python.org/issue32308

   (18) https://bugs.python.org/issue29995

   (19) https://bugs.python.org/issue32121

   (20) https://bugs.python.org/issue32331

   (21) https://bugs.python.org/issue33169

   (22) https://bugs.python.org/issue32327

   (23) https://bugs.python.org/issue32662

   (24) https://bugs.python.org/issue21071

   (25) https://bugs.python.org/issue26510

   (26) https://bugs.python.org/issue31778

   (27) https://bugs.python.org/issue28292

   (28) https://bugs.python.org/issue32792

   (29) https://bugs.python.org/issue33097

   (30) https://bugs.python.org/issue23835


File: python.info,  Node: C API 中的改变<2>,  Next: CPython 字节码的改变<3>,  Prev: 更改的Python API<2>,  Up: 移植到 Python 3 7

1.3.17.3 C API 中的改变
.......................

函数 *note PySlice_GetIndicesEx(): 576. 被认为对于大小可变的序列来说并不
安全。 如果切片索引不是 *note int: 204. 的实例，而是实现了 ‘__index__()’
方法的对象，则序列可以在其长度被传给 ‘PySlice_GetIndicesEx()’ 之后调整大
小。 这可能导致返回超出序列长度的索引号。 为了避免可能的问题，请使用新增
的函数 *note PySlice_Unpack(): 532. 和 *note PySlice_AdjustIndices():
533.。 （由 Serhiy Storchaka 在 bpo-27867(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27867


File: python.info,  Node: CPython 字节码的改变<3>,  Next: Windows 专属的改变<2>,  Prev: C API 中的改变<2>,  Up: 移植到 Python 3 7

1.3.17.4 CPython 字节码的改变
.............................

新增了两个操作码: *note LOAD_METHOD: 5a7. 和 *note CALL_METHOD: 5a8.。 （
由 Yury Selivanov 和 INADA Naoki 在 bpo-26110(1) 中贡献。）

‘STORE_ANNOTATION’ 操作码已被移除。 （由 Mark Shannon 在 bpo-32550(2) 中
贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26110

   (2) https://bugs.python.org/issue32550


File: python.info,  Node: Windows 专属的改变<2>,  Next: 其他 CPython 实现的改变<2>,  Prev: CPython 字节码的改变<3>,  Up: 移植到 Python 3 7

1.3.17.5 Windows 专属的改变
...........................

用于重载 *note sys.path: 261. 的文件现在命名为
‘<python-executable>._pth’ 而不是 ‘'sys.path'’。 请参阅 *note 查找模块:
5aa. 了解更多信息。 （由 Steve Dower 在 bpo-28137(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28137


File: python.info,  Node: 其他 CPython 实现的改变<2>,  Prev: Windows 专属的改变<2>,  Up: 移植到 Python 3 7

1.3.17.6 其他 CPython 实现的改变
................................

为了准备在未来对公开的 CPython 运行时初始化 API 进行潜在更改（请参阅 PEP
432(1) 获取最初但略为过时的文稿），CPython 内部的启动和配置管理逻辑已经
过大幅重构。 虽然这些更新旨在对嵌入式应用程序和常规的 CPython CLI 用户都
完全透明，但它们在这里被提及是因为重构会改变解释器启动期间许多操作的内部
顺序，因此可能提示出原先隐藏的缺陷，这可能存在于嵌入式应用程序中，或是在
CPython 自身内部。 （最初由 Nick Coghlan 和 Eric Snow 作为 bpo-22257(2)
的一部分贡献，并由 Nick, Eric 和 Victor Stinner 在一系列其他问题报告中进
一步更新）。 已知会受到影响的一些细节：

   * *note PySys_AddWarnOptionUnicode(): 5ac. 目前对嵌入式应用程序不可用
     ，因为在调用 ‘Py_Initialize’ 之前需要创建 Unicode 对象。 请改用
     *note PySys_AddWarnOption(): 5ad.。

   * 嵌入式应用程序通过 *note PySys_AddWarnOption(): 5ad. 所添加的警告过
     滤器现在应该以更高的一致性优先于由解释器所设置的默认过滤器

由于默认警告过滤器的配置方式发生了变化，将 *note Py_BytesWarningFlag:
5ae. 设置为大于一的值不再足以在发出 *note BytesWarning: 5af. 消息的同时
将其转换为异常。 而是改为必须设置旗标（以便首先发出警告），以及添加显式
的 ‘error::BytesWarning’ 警告过滤器来将其转换为异常。

由于编译器处理文档字符串的方式发生了变化，一个仅由文档字符串构成的函数体
中隐式的 ‘return None’ 现在被标记为在与文档字符串相同的行，而不是在函数
的标题行。

当前异常状态已从帧对象移到协程对象。 这会简化解释器并修正由于在进入或退
出生成器时具有交换异常状态而导致的一些模糊错误。 （由 Mark Shannon 在
bpo-25612(3) 中贡献。）

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0432

   (2) https://bugs.python.org/issue22257

   (3) https://bugs.python.org/issue25612


File: python.info,  Node: Python 3 7 1 中的重要变化,  Next: Python 3 7 2 中的重要变化,  Prev: 移植到 Python 3 7,  Up: Python 3 7 有什么新变化

1.3.18 Python 3.7.1 中的重要变化
--------------------------------

从 3.7.1 开始，*note Py_Initialize(): 20f. 现在始终会读取并遵循与 *note
Py_Main(): 5b1. 相同的环境设置（在更早的 Python 版本中，它会遵循一个错误
定义的环境变量子集，而在 Python 3.7.0 中则会由于 bpo-34247(1) 而完全不读
取它们）。 如果不想要此行为，请在调用 *note Py_Initialize(): 20f. 之前将
*note Py_IgnoreEnvironmentFlag: 5b2. 设为 1。

在 3.7.1 中，上下文变量的 C API 已 *note 获得更新: 5b3. 以使用 *note
PyObject: 5b4. 指针。 另请参阅 bpo-34762(2)。

在 3.7.1 中，当提供不带末尾新行的输入时 *note tokenize: 11a. 模块现在会
隐式地添加 ‘NEWLINE’ 形符。 此行为现在已与 C 词法分析器的内部行为相匹配
。 （由 Ammar Askar 在 bpo-33899(3) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue34247

   (2) https://bugs.python.org/issue34762

   (3) https://bugs.python.org/issue33899


File: python.info,  Node: Python 3 7 2 中的重要变化,  Next: Python 3 7 6 中的重要变化,  Prev: Python 3 7 1 中的重要变化,  Up: Python 3 7 有什么新变化

1.3.19 Python 3.7.2 中的重要变化
--------------------------------

在 3.7.2 中，Windows 下的 *note venv: 12e. 不再复制原来的二进制文件，而
是改为创建名为 ‘python.exe’ 和 ‘pythonw.exe’ 的重定向脚本。 这解决了一个
长期存在的问题，即所有虚拟环境在每次 Python 升级后都必须进行升级或是重新
创建。 然而，要注意此发布版仍然要求重新创建虚拟环境以获得新的脚本。


File: python.info,  Node: Python 3 7 6 中的重要变化,  Next: Python 3 7 10 中的重要变化,  Prev: Python 3 7 2 中的重要变化,  Up: Python 3 7 有什么新变化

1.3.20 Python 3.7.6 中的重要变化
--------------------------------

出于重要的安全性考量，*note asyncio.loop.create_datagram_endpoint():
189. 的 `reuse_address' 形参不再被支持。 这是由 UDP 中的套接字选项
‘SO_REUSEADDR’ 的行为导致的。 更多细节请参阅
‘loop.create_datagram_endpoint()’ 的文档。 （由 Kyle Stanley, Antoine
Pitrou 和 Yury Selivanov 在 bpo-37228(1) 中贡献。。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37228


File: python.info,  Node: Python 3 7 10 中的重要变化,  Prev: Python 3 7 6 中的重要变化,  Up: Python 3 7 有什么新变化

1.3.21 Python 3.7.10 中的重要变化
---------------------------------

早先的 Python 版本允许使用 ‘;’ 和 ‘&’ 作为 *note
urllib.parse.parse_qs(): 27f. 和 *note urllib.parse.parse_qsl(): 280. 中
query 形参的分隔键。 出于安全考虑，也为了遵循更新的 W3C 推荐设置，这已被
改为只允许单个分隔键，默认为 ‘&’。 这一改变还会影响 *note cgi.parse():
281. 和 *note cgi.parse_multipart(): 282. 因为它们在内部使用了受影响的函
数。 要了解更多细节，请查看它们各自的文档。 （由 Adam Goldschmidt,
Senthil Kumaran 和 Ken Jin 在 bpo-42967(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42967


File: python.info,  Node: Python 3 6 有什么新变化,  Next: Python 3 5 有什麼新功能,  Prev: Python 3 7 有什么新变化,  Up: Python 有什麼新功能？

1.4 Python 3.6 有什么新变化
===========================


编者: Elvis Pranskevichus <<elvis@magic.io>>, Yury Selivanov
<<yury@magic.io>>

本文解释了与3.5相比，Python 3.6中的新功能。 Python 3.6于2016年12月23日发
布。请参阅 changelog(1) 以获取完整的更改列表。

也參考
......

PEP 494(2) - 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.

   ---------- Footnotes ----------

   (1) https://docs.python.org/3.6/whatsnew/changelog.html

   (2) https://www.python.org/dev/peps/pep-0494


File: python.info,  Node: 摘要 - 发布重点<4>,  Next: 新的特性<5>,  Up: Python 3 6 有什么新变化

1.4.1 摘要 - 发布重点
---------------------

新的语法特性：

   * *note PEP 498: 5bb, 格式化字符串字面值

   * *note PEP 515: 5bc, 数字字面值中的下划线。

   * *note PEP 526: 5bd. , 变量标注语法。

   * *note PEP 525: 5be, 异步生成器。

   * *note PEP 530: 5bf.: 异步推导式。

新的库模块：

   * *note secrets: e4.: *note PEP 506 – Secret模块被加入Python标准库:
     5c0.。

CPython 实现的改进：

   * 根据 Raymond Hettinger 的提议(1) 已将 *note dict: 40e. 类型重新实现
     为使用 *note 更紧凑的表示形式: 5c1. 并类似于 PyPy dict
     implementation(2)。 这使得字典所使用的内存相对于 Python 3.5 版减少
     了 20% 到 25%。

   * 类创建的定制过程通过 *note 新协议: 5c2. 得到了简化。

   * 类属性的定义顺序 *note 现在会被保留: 5c3.。

   * 现在 ‘**kwargs’ 中的元素会与传给函数的关键字参数 *note
     保持对应顺序: 5c4.。

   * 添加了 DTrace 和 SystemTap *note 探测支持: 5c5.

   * 新的 *note PYTHONMALLOC: 5c6. 环境变量可被用来调试解释器的内存分配
     和访问错误。

标准库中的重大改进：

   * *note asyncio: 9. 模块获得了许多新特性，显著的可用性和性能提升，以
     及大量的问题修正。 从 Python 3.6 开始 ‘asyncio’ 模块不再处于待定状
     态，它已被视为稳定 API。

   * 实现了新的 *note 文件系统路径协议: 5c7. 以支持 *note 路径类对象:
     472.。 所有操作路径的标准库函数已被更新为使用新的协议。

   * *note datetime: 30. 模块已获得对 *note 本地时间消歧义: 5c8. 的支持
     。

   * *note typing: 122. 模块获得了大量的 *note 改进: 5c9.。

   * *note tracemalloc: 11d. 模块已被大幅重写，现在将被用于为 *note
     ResourceWarning: 5ca. 提供更好的输出，并为内存分配错误提供更好的诊
     断。 请参阅 *note PYTHONMALLOC 一节: 5c6. 来了解详情。

安全改进：

   * 添加了 *note secrets: e4. 模块以简化适用于密码管理的高加密强度伪随
     机数的生成，例如账户验证、安全凭据等场景。

   * 在 Linux 上，现在 *note os.urandom(): 5cb. 会阻塞直到系统的 urandom
     熵池被初始化以提升安全性。 其理由参见 PEP 524(3)。

   * *note hashlib: 8c. 和 *note ssl: f3. 模块现在支持 OpenSSL 1.1.0。

   * *note ssl: f3. 模块的默认设置和特性集已得到改进。

   * *note hashlib: 8c. 模块获得了对 BLAKE2, SHA-3 和 SHAKE 哈希算法以及
     *note scrypt(): 5cc. 密钥派生函数的支持。

Windows改进：

   * *note PEP 528: 5cd. 和 *note PEP 529: 5ce, 将Windows文件系统和控制
     台的编码更改为UTF-8

   * 在交互式地使用 ‘py.exe’ 启动器时，当用户未（通过命令行参数或配置文
     件）指定版本时不再优先选择 Python 2 而是选择 Python 3。 对声明行的
     处理则保持不变 —— 在这种情况下 "python" 还是指 Python 2。

   * ‘python.exe’ 和 ‘pythonw.exe’ 已被标记为支持长路径，这意味着不再有
     260 个字符的路径长度限制。 详情参见 *note 移除 MAX_PATH 限制: 5cf.。

   * 可以添加一个 ‘._pth’ 文件来强制使用隔离模式和完整指定所有搜索路径来
     避免注册表和环境查找。 更多信息请参阅 *note 相关文档: 5aa.。

   * 现在 ‘python36.zip’ 文件可以作为推断 *note PYTHONHOME: 5d0. 的标志
     。 更多信息请参阅 *note 相关文档: 5aa.。

   ---------- Footnotes ----------

   (1) 
https://mail.python.org/pipermail/python-dev/2012-December/123028.html

   (2) 
https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html

   (3) https://www.python.org/dev/peps/pep-0524


File: python.info,  Node: 新的特性<5>,  Next: 其他语言特性修改<4>,  Prev: 摘要 - 发布重点<4>,  Up: Python 3 6 有什么新变化

1.4.2 新的特性
--------------

* 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 探测支持::


File: python.info,  Node: PEP 498 格式化字符串字面值,  Next: PEP 526 变量标注的语法,  Up: 新的特性<5>

1.4.2.1 PEP 498: 格式化字符串字面值
...................................

PEP 498(1) 引入了一种新型的字符串字面值: `f-字符串'，或称 *note
格式化字符串字面值: 296.。

格式化字符串字面值带有 ‘'f'’ 前缀并且类似于 *note str.format(): 5d4. 所
接受的格式字符串。 其中包含由花括号包围的替换字段。 替换字段属于表达式，
它们会在运行时被求值，然后使用 *note format(): 5d5. 协议进行格式化:

     >>> 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'

也參考
......

PEP 498(2) – 字符串字面值插值。

     PEP 由 Eric V. Smith 撰写并实现

*note 特性文档: 296.。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0498

   (2) https://www.python.org/dev/peps/pep-0498


File: python.info,  Node: PEP 526 变量标注的语法,  Next: PEP 515 数字字面值中的下划线。,  Prev: PEP 498 格式化字符串字面值,  Up: 新的特性<5>

1.4.2.2 PEP 526: 变量标注的语法
...............................

PEP 484(1) 引入了函数形参类型标注即类型提示的标准。 这个 PEP 为 Python 添
加了标注变量类型的语法，包括类变量和实例变量:

     primes: List[int] = []

     captain: str  # Note: no initial value!

     class Starship:
         stats: Dict[str, int] = {}

与函数标注一样，Python 解释器不会为变量标注附加任何特殊含义，仅会将其保
存在类或模块的 ‘__annotations__’ 属性中。

与静态类型语法的变量声明不同，标注语法的目的是通过抽象语法树和
‘__annotations__’ 属性提供一个简单方式来为第三方工具和库指定结构化类型元
数据。

也參考
......

PEP 526(2) – 变量标注的语法。

     PEP 由 Ryan Gonzalez, Philip House, Ivan Levkivskyi, Lisa Roach, 和
     Guido van Rossum 撰写，由 Ivan Levkivskyi 实现。

使用或将要使用此新语法的工具有: mypy(3), pytype(4), PyCharm 等等。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0484

   (2) https://www.python.org/dev/peps/pep-0526

   (3) http://www.mypy-lang.org/

   (4) https://github.com/google/pytype


File: python.info,  Node: PEP 515 数字字面值中的下划线。,  Next: PEP 525 异步生成器,  Prev: PEP 526 变量标注的语法,  Up: 新的特性<5>

1.4.2.3 PEP 515: 数字字面值中的下划线。
.......................................

PEP 515(1) 增加了在数字字面值中使用下划线的能力以改善可读性。 例如:

     >>> 1_000_000_000_000_000
     1000000000000000
     >>> 0x_FF_FF_FF_FF
     4294967295

单个下划线允许用在数码之间和任何数制指示符之后。 一行内不允许有开头、末
尾或多个下划线。

*note 字符串格式化: 5d8. 微语言现在也支持以 ‘'_'’ 选项来表示用下划线作为
浮点表示类型和整数表示类型 ‘'d'’ 的千位分隔符。 对于整数表示类型 ‘'b'’,
‘'o'’, ‘'x'’ 和 ‘'X'’，将每隔 4 个数码插入一个下划线:

     >>> '{:_}'.format(1000000)
     '1_000_000'
     >>> '{:_x}'.format(0xFFFFFFFF)
     'ffff_ffff'

也參考
......

PEP 515(2) – 数字字面值中的下划线。

     PEP 由 Georg Brandl 和 Serhiy Storchaka 撰写

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0515

   (2) https://www.python.org/dev/peps/pep-0515


File: python.info,  Node: PEP 525 异步生成器,  Next: PEP 530 异步推导式,  Prev: PEP 515 数字字面值中的下划线。,  Up: 新的特性<5>

1.4.2.4 PEP 525: 异步生成器
...........................

PEP 492(1) 将对原生协程和 ‘async’ / ‘await’ 语法的支持引入到 Python 3.5
中。 但 Python 3.5 实现的一个明显限制是不可能在同一函数体中同时使用
‘await’ 和 ‘yield’。 在 Python 3.6 中此限制已被解除，这样就就能够定义 `异
步生成器':

     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)

这个新语法允许更快速且更精简的代码。

也參考
......

PEP 525(2) – 异步生成器

     PEP 由 Yury Selivanov 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0492

   (2) https://www.python.org/dev/peps/pep-0525


File: python.info,  Node: PEP 530 异步推导式,  Next: PEP 487 更简单的自定义类创建,  Prev: PEP 525 异步生成器,  Up: 新的特性<5>

1.4.2.5 PEP 530: 异步推导式
...........................

PEP 530(1) 添加了对在列表、集合与字典推导式和生成器表达式中使用 ‘async
for’ 的支持:

     result = [i async for i in aiter() if i % 2]

此外，‘await’ 表达式也在所有种类的推导式中得到支持:

     result = [await fun() for fun in funcs if await condition()]

也參考
......

PEP 530(2) – 异步推导式

     PEP 由 Yury Selivanov 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0530

   (2) https://www.python.org/dev/peps/pep-0530


File: python.info,  Node: PEP 487 更简单的自定义类创建,  Next: PEP 487 描述器协议的增强,  Prev: PEP 530 异步推导式,  Up: 新的特性<5>

1.4.2.6 PEP 487: 更简单的自定义类创建
.....................................

现在可以在不使用元类的情况下自定义子类的创建。 当一个新的子类被创建时将
在基类上调用新的 ‘__init_subclass__’ 类方法:

     class PluginBase:
         subclasses = []

         def __init_subclass__(cls, **kwargs):
             super().__init_subclass__(**kwargs)
             cls.subclasses.append(cls)

     class Plugin1(PluginBase):
         pass

     class Plugin2(PluginBase):
         pass

为了让来自 *note __init_subclass__(): 5dc. 实现的零参数 *note super():
5dd. 调用能正确工作，自定义元类必须保证新的 ‘__classcell__’ 命名空间入口
被传播到 ‘type.__new__’ (如 *note 创建类对象: 5de. 中所描述)。

也參考
......

PEP 487(1) – 更简单的自定义类创建

     PEP 由 Martin Teichmann 撰写并实现。

*note 特性文档: 5df.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0487


File: python.info,  Node: PEP 487 描述器协议的增强,  Next: PEP 519 添加文件系统路径协议,  Prev: PEP 487 更简单的自定义类创建,  Up: 新的特性<5>

1.4.2.7 PEP 487: 描述器协议的增强
.................................

PEP 487(1) 扩展了描述器协议以包括新的可选方法 *note __set_name__():
5e2.。 当创建一个新类时，这个新方法将在定义中包括的所有描述器上被调用，
为它们提供对所定义类的引用以及在类命名中间中给予描述器的名称。 换句话说
，描述器的实例现在能知道描述器在所有者类中的属性名称:

     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()

也參考
......

PEP 487(2) – 更简单的自定义类创建

     PEP 由 Martin Teichmann 撰写并实现。

*note 特性文档: 5e3.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0487

   (2) https://www.python.org/dev/peps/pep-0487


File: python.info,  Node: PEP 519 添加文件系统路径协议,  Next: PEP 495 消除本地时间的歧义,  Prev: PEP 487 描述器协议的增强,  Up: 新的特性<5>

1.4.2.8 PEP 519: 添加文件系统路径协议
.....................................

File system paths have historically been represented as *note str: 205.
or *note bytes: 172. 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 *note int: 204. 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 *note pathlib: c8. from working with pre-existing
code, including Python’s standard library.

To fix this situation, a new interface represented by *note os.PathLike:
5e5. has been defined.  By implementing the *note __fspath__(): 5e6.
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 *note str:
205. or *note bytes: 172. object.  This means an object is considered
*note path-like: 472. if it implements *note os.PathLike: 5e5. or is a
*note str: 205. or *note bytes: 172. object which represents a file
system path.  Code can use *note os.fspath(): 5e7, *note os.fsdecode():
5e8, or *note os.fsencode(): 5e9. to explicitly get a *note str: 205.
and/or *note bytes: 172. representation of a path-like object.

The built-in *note open(): 16f. function has been updated to accept
*note os.PathLike: 5e5. objects, as have all relevant functions in the
*note os: c4. and *note os.path: c5. modules, and most other functions
and classes in the standard library.  The *note os.DirEntry: 5ea. class
and relevant classes in *note pathlib: c8. have also been updated to
implement *note os.PathLike: 5e5.

The hope is that updating the fundamental functions for operating on
file system paths will lead to third-party code to implicitly support
all *note path-like objects: 472. without any code changes, or at least
very minimal ones (e.g.  calling *note os.fspath(): 5e7. at the
beginning of code before operating on a path-like object).

Here are some examples of how the new interface allows for *note
pathlib.Path: 32f. to be used more easily and transparently with
pre-existing code:

     >>> 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'

（由 Brett Cannon, Ethan Furman, Dusty Phillips 和 Jelle Zijlstra 实现。
）

也參考
......

PEP 519(1) – 添加文件系统路径协议

     PEP 由 Brett Cannon 和 Koos Zevenhoven 撰写。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0519


File: python.info,  Node: PEP 495 消除本地时间的歧义,  Next: PEP 529 将Windows文件系统编码更改为UTF-8,  Prev: PEP 519 添加文件系统路径协议,  Up: 新的特性<5>

1.4.2.9 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.

PEP 495(1) adds the new `fold' attribute to instances of *note
datetime.datetime: 19f. and *note datetime.time: 5ec. classes to
differentiate between two moments in time for which local times are the
same:

     >>> 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

The values of the *note fold: 5ed. attribute have the value ‘0’ for all
instances except those that represent the second (chronologically)
moment in time in an ambiguous case.

也參考
......

PEP 495(2) – 消除本地时间的歧义

     PEP 由 Alexander Belopolsky 和 Tim Peters 撰写，由 Alexander
     Belopolsky 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0495

   (2) https://www.python.org/dev/peps/pep-0495


File: python.info,  Node: PEP 529 将Windows文件系统编码更改为UTF-8,  Next: PEP 528 将Windows控制台编码更改为UTF-8,  Prev: PEP 495 消除本地时间的歧义,  Up: 新的特性<5>

1.4.2.10 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 *note sys.getfilesystemencoding(): 5ef, which now defaults
to ‘'utf-8'’.

Applications that do not use str to represent paths should use *note
os.fsencode(): 5e9. and *note os.fsdecode(): 5e8. to ensure their bytes
are correctly encoded.  To revert to the previous behaviour, set *note
PYTHONLEGACYWINDOWSFSENCODING: 5f0. or call *note
sys._enablelegacywindowsfsencoding(): 5f1.

有关详细信息和可能需要的代码修改的讨论，请参见 PEP 529(1) 。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0529


File: python.info,  Node: PEP 528 将Windows控制台编码更改为UTF-8,  Next: PEP 520 保留类属性定义顺序,  Prev: PEP 529 将Windows文件系统编码更改为UTF-8,  Up: 新的特性<5>

1.4.2.11 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.  ‘sys.stdin’,
‘sys.stdout’ and ‘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 *note PYTHONLEGACYWINDOWSSTDIO: 5f3.

也參考
......

PEP 528(1) – 将Windows控制台编码更改为UTF-8

     PEP 由 Steve Dower 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0528


File: python.info,  Node: PEP 520 保留类属性定义顺序,  Next: PEP 468 保留关键字参数顺序,  Prev: PEP 528 将Windows控制台编码更改为UTF-8,  Up: 新的特性<5>

1.4.2.12 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 *note __dict__: 5f5. attribute.

Also, the effective default class `execution' namespace (returned from
*note type.__prepare__(): 5f6.) is now an insertion-order-preserving
mapping.

也參考
......

PEP 520(1) – 保留类属性定义顺序

     PEP 由 Eric Snow 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0520


File: python.info,  Node: PEP 468 保留关键字参数顺序,  Next: 新的 dict 实现,  Prev: PEP 520 保留类属性定义顺序,  Up: 新的特性<5>

1.4.2.13 PEP 468: 保留关键字参数顺序
....................................

‘**kwargs’ in a function signature is now guaranteed to be an
insertion-order-preserving mapping.

也參考
......

PEP 468(1) – 保留关键字参数顺序

     PEP 由 Eric Snow 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0468


File: python.info,  Node: 新的 dict 实现,  Next: PEP 523 向CPython 添加框架评估API,  Prev: PEP 468 保留关键字参数顺序,  Up: 新的特性<5>

1.4.2.14 新的 dict 实现
.......................

The *note dict: 40e. type now uses a "compact" representation based on a
proposal by Raymond Hettinger(1) which was first implemented by PyPy(2).
The memory usage of the new *note dict(): 164. 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(3).  Idea originally suggested
by Raymond Hettinger(4).)

   ---------- Footnotes ----------

   (1) 
https://mail.python.org/pipermail/python-dev/2012-December/123028.html

   (2) 
https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html

   (3) https://bugs.python.org/issue27350

   (4) 
https://mail.python.org/pipermail/python-dev/2012-December/123028.html


File: python.info,  Node: PEP 523 向CPython 添加框架评估API,  Next: PYTHONMALLOC 环境变量,  Prev: 新的 dict 实现,  Up: 新的特性<5>

1.4.2.15 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.

PEP 523(1) 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.

也參考
......

PEP 523(2) – 向CPython 添加框架评估API

     PEP 由 Brett Cannon 和 Dino Viehland 撰写。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0523

   (2) https://www.python.org/dev/peps/pep-0523


File: python.info,  Node: PYTHONMALLOC 环境变量,  Next: DTrace 和 SystemTap 探测支持,  Prev: PEP 523 向CPython 添加框架评估API,  Up: 新的特性<5>

1.4.2.16 PYTHONMALLOC 环境变量
..............................

The new *note PYTHONMALLOC: 5fc. environment variable allows setting the
Python memory allocators and installing debug hooks.

It is now possible to install debug hooks on Python memory allocators on
Python compiled in release mode using ‘PYTHONMALLOC=debug’.  Effects of
debug hooks:

   * 新分配的内存中填充字节 ‘0xCB’

   * 释放的内存中填充了字节 ‘0xDB’

   * Detect violations of the Python memory allocator API. For example,
     *note PyObject_Free(): 5fd. called on a memory block allocated by
     *note PyMem_Malloc(): 5fe.

   * 在缓冲区开始之前检测写操作（缓冲区下溢）

   * 在缓冲区结束后检测写操作（缓冲区溢出）

   * Check that the *note GIL: 5ff. is held when allocator functions of
     *note PYMEM_DOMAIN_OBJ: 600. (ex: *note PyObject_Malloc(): 601.)
     and *note PYMEM_DOMAIN_MEM: 602. (ex: *note PyMem_Malloc(): 5fe.)
     domains are called.

检查是否保留了 GIL 也是Python 3.6 的新特性。

See the *note PyMem_SetupDebugHooks(): 603. function for debug hooks on
Python memory allocators.

It is now also possible to force the usage of the ‘malloc()’ allocator
of the C library for all Python memory allocations using
‘PYTHONMALLOC=malloc’.  This is helpful when using external memory
debuggers like Valgrind on a Python compiled in release mode.

On error, the debug hooks on Python memory allocators now use the *note
tracemalloc: 11d. module to get the traceback where a memory block was
allocated.

Example of fatal error on buffer overflow using ‘python3.6 -X
tracemalloc=5’ (store 5 frames in traces):

     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__
       ...

（由 Victor Stinner 在 bpo-26516(1) 和 bpo-26564(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26516

   (2) https://bugs.python.org/issue26564


File: python.info,  Node: DTrace 和 SystemTap 探测支持,  Prev: PYTHONMALLOC 环境变量,  Up: 新的特性<5>

1.4.2.17 DTrace 和 SystemTap 探测支持
.....................................

Python can now be built ‘--with-dtrace’ which enables static markers for
the following events in the interpreter:

   * 函数调用/返回

   * 垃圾收集开始/完成

   * 执行的代码行。

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.

更多信息，请参见 *note 使用 DTrace 和 SystemTap 检测CPython: 605. 。

当前的实现已在 Linux 和 macOS 上进行了测试。将来可能会添加其他标记。

(Contributed by Łukasz Langa in bpo-21590(1), based on patches by Jesús
Cea Avión, David Malcolm, and Nikhil Benesch.)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21590


File: python.info,  Node: 其他语言特性修改<4>,  Next: 新增模块<4>,  Prev: 新的特性<5>,  Up: Python 3 6 有什么新变化

1.4.3 其他语言特性修改
----------------------

对Python 语言核心进行的小改动：

   * A ‘global’ or ‘nonlocal’ statement must now textually appear before
     the first use of the affected name in the same scope.  Previously
     this was a *note SyntaxWarning: 2c9.

   * It is now possible to set a *note special method: 607. to ‘None’ to
     indicate that the corresponding operation is not available.  For
     example, if a class sets *note __iter__(): 608. to ‘None’, the
     class is not iterable.  (Contributed by Andrew Barnert and Ivan
     Levkivskyi in bpo-25958(1).)

   * Long sequences of repeated traceback lines are now abbreviated as
     ‘"[Previous line repeated {count} more times]"’ (see *note
     traceback: 609. for an example).  (Contributed by Emanuel Barry in
     bpo-26823(2).)

   * Import now raises the new exception *note ModuleNotFoundError: 4a0.
     (subclass of *note ImportError: 16c.) 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(3).)

   * Class methods relying on zero-argument ‘super()’ will now work
     correctly when called from metaclass methods during class creation.
     (Contributed by Martin Teichmann in bpo-23722(4).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25958

   (2) https://bugs.python.org/issue26823

   (3) https://bugs.python.org/issue15767

   (4) https://bugs.python.org/issue23722


File: python.info,  Node: 新增模块<4>,  Next: 改进的模块<4>,  Prev: 其他语言特性修改<4>,  Up: Python 3 6 有什么新变化

1.4.4 新增模块
--------------

* Menu:

* secrets::


File: python.info,  Node: secrets,  Up: 新增模块<4>

1.4.4.1 secrets
...............

The main purpose of the new *note secrets: e4. 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.

     警告: Note that the pseudo-random generators in the *note random:
     dc. module should `NOT' be used for security purposes.  Use *note
     secrets: e4. on Python 3.6+ and *note os.urandom(): 5cb. on Python
     3.5 and earlier.

也參考
......

PEP 506(1) – Secrets模块被加入Python标准库

     PEP 由 Steven D’Aprano 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0506


File: python.info,  Node: 改进的模块<4>,  Next: 性能优化<4>,  Prev: 新增模块<4>,  Up: Python 3 6 有什么新变化

1.4.5 改进的模块
----------------

* 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::


File: python.info,  Node: array,  Next: ast<3>,  Up: 改进的模块<4>

1.4.5.1 array
.............

Exhausted iterators of *note array.array: 216. 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(1) 中贡献。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26492


File: python.info,  Node: ast<3>,  Next: asyncio<5>,  Prev: array,  Up: 改进的模块<4>

1.4.5.2 ast
...........

The new *note ast.Constant: 3a6. AST node has been added.  It can be
used by external AST optimizers for the purposes of constant folding.

由 Victor Stinner 在 bpo-26146(1) 中贡献。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26146


File: python.info,  Node: asyncio<5>,  Next: binascii<2>,  Prev: ast<3>,  Up: 改进的模块<4>

1.4.5.3 asyncio
...............

Starting with Python 3.6 the ‘asyncio’ module is no longer provisional
and its API is considered stable.

Notable changes in the *note asyncio: 9. module since Python 3.5.0 (all
backported to 3.5.x due to the provisional status):

   * The *note get_event_loop(): 45d. function has been changed to
     always return the currently running loop when called from
     coroutines and callbacks.  (Contributed by Yury Selivanov in
     bpo-28613(1).)

   * The *note ensure_future(): 610. function and all functions that use
     it, such as *note loop.run_until_complete(): 611, now accept all
     kinds of *note awaitable objects: 612.  (Contributed by Yury
     Selivanov.)

   * New *note run_coroutine_threadsafe(): 613. function to submit
     coroutines to event loops from other threads.  (Contributed by
     Vincent Michel.)

   * New *note Transport.is_closing(): 614. method to check if the
     transport is closing or closed.  (Contributed by Yury Selivanov.)

   * The *note loop.create_server(): 465. method can now accept a list
     of hosts.  (Contributed by Yann Sionneau.)

   * New *note loop.create_future(): 615. method to create Future
     objects.  This allows alternative event loop implementations, such
     as uvloop(2), to provide a faster *note asyncio.Future: 545.
     implementation.  (Contributed by Yury Selivanov in bpo-27041(3).)

   * New *note loop.get_exception_handler(): 616. method to get the
     current exception handler.  (Contributed by Yury Selivanov in
     bpo-27040(4).)

   * New *note StreamReader.readuntil(): 617. method to read data from
     the stream until a separator bytes sequence appears.  (Contributed
     by Mark Korenberg.)

   * The performance of *note StreamReader.readexactly(): 618. has been
     improved.  (Contributed by Mark Korenberg in bpo-28370(5).)

   * The *note loop.getaddrinfo(): 59b. method is optimized to avoid
     calling the system ‘getaddrinfo’ function if the address is already
     resolved.  (Contributed by A. Jesse Jiryu Davis.)

   * The *note loop.stop(): 619. 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(6).)

   * ‘Future.set_exception’ will now raise *note TypeError: 1fe. when
     passed an instance of the *note StopIteration: 581. exception.
     (Contributed by Chris Angelico in bpo-26221(7).)

   * New *note loop.connect_accepted_socket(): 46d. 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(8).)

   * ‘TCP_NODELAY’ flag is now set for all TCP transports by default.
     (Contributed by Yury Selivanov in bpo-27456(9).)

   * New *note loop.shutdown_asyncgens(): 61a. to properly close pending
     asynchronous generators before closing the loop.  (Contributed by
     Yury Selivanov in bpo-28003(10).)

   * *note Future: 545. and *note Task: 2e0. 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(11) and bpo-28544(12).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28613

   (2) https://github.com/MagicStack/uvloop

   (3) https://bugs.python.org/issue27041

   (4) https://bugs.python.org/issue27040

   (5) https://bugs.python.org/issue28370

   (6) https://bugs.python.org/issue25593

   (7) https://bugs.python.org/issue26221

   (8) https://bugs.python.org/issue27392

   (9) https://bugs.python.org/issue27456

   (10) https://bugs.python.org/issue28003

   (11) https://bugs.python.org/issue26081

   (12) https://bugs.python.org/issue28544


File: python.info,  Node: binascii<2>,  Next: cmath,  Prev: asyncio<5>,  Up: 改进的模块<4>

1.4.5.4 binascii
................

The *note b2a_base64(): 61c. function now accepts an optional `newline'
keyword argument to control whether the newline character is appended to
the return value.  (Contributed by Victor Stinner in bpo-25357(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25357


File: python.info,  Node: cmath,  Next: collections<4>,  Prev: binascii<2>,  Up: 改进的模块<4>

1.4.5.5 cmath
.............

The new *note cmath.tau: 61e. (`τ') constant has been added.
(Contributed by Lisa Roach in bpo-12345(1), see PEP 628(2) for details.)

New constants: *note cmath.inf: 61f. and *note cmath.nan: 620. to match
*note math.inf: 621. and *note math.nan: 622, and also *note cmath.infj:
623. and *note cmath.nanj: 624. to match the format used by complex
repr.  (Contributed by Mark Dickinson in bpo-23229(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue12345

   (2) https://www.python.org/dev/peps/pep-0628

   (3) https://bugs.python.org/issue23229


File: python.info,  Node: collections<4>,  Next: concurrent futures<3>,  Prev: cmath,  Up: 改进的模块<4>

1.4.5.6 collections
...................

The new *note Collection: 626. abstract base class has been added to
represent sized iterable container classes.  (Contributed by Ivan
Levkivskyi, docs by Neil Girdhar in bpo-27598(1).)

The new *note Reversible: 627. abstract base class represents iterable
classes that also provide the *note __reversed__(): 628. method.
(Contributed by Ivan Levkivskyi in bpo-25987(2).)

The new *note AsyncGenerator: 629. abstract base class represents
asynchronous generators.  (Contributed by Yury Selivanov in
bpo-28720(3).)

The *note namedtuple(): 1a1. function now accepts an optional keyword
argument `module', which, when specified, is used for the ‘__module__’
attribute of the returned named tuple class.  (Contributed by Raymond
Hettinger in bpo-17941(4).)

The `verbose' and `rename' arguments for *note namedtuple(): 1a1. are
now keyword-only.  (Contributed by Raymond Hettinger in bpo-25628(5).)

Recursive *note collections.deque: 62a. instances can now be pickled.
(Contributed by Serhiy Storchaka in bpo-26482(6).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27598

   (2) https://bugs.python.org/issue25987

   (3) https://bugs.python.org/issue28720

   (4) https://bugs.python.org/issue17941

   (5) https://bugs.python.org/issue25628

   (6) https://bugs.python.org/issue26482


File: python.info,  Node: concurrent futures<3>,  Next: contextlib<2>,  Prev: collections<4>,  Up: 改进的模块<4>

1.4.5.7 concurrent.futures
..........................

The *note ThreadPoolExecutor: 18c. class constructor now accepts an
optional `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(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27664


File: python.info,  Node: contextlib<2>,  Next: datetime<4>,  Prev: concurrent futures<3>,  Up: 改进的模块<4>

1.4.5.8 contextlib
..................

The *note contextlib.AbstractContextManager: 62d. class has been added
to provide an abstract base class for context managers.  It provides a
sensible default implementation for ‘__enter__()’ which returns ‘self’
and leaves ‘__exit__()’ an abstract method.  A matching class has been
added to the *note typing: 122. module as *note typing.ContextManager:
62e.  (Contributed by Brett Cannon in bpo-25609(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25609


File: python.info,  Node: datetime<4>,  Next: decimal<2>,  Prev: contextlib<2>,  Up: 改进的模块<4>

1.4.5.9 datetime
................

The *note datetime: 19f. and *note time: 5ec. classes have the new
‘fold’ attribute used to disambiguate local time when necessary.  Many
functions in the *note datetime: 30. have been updated to support local
time disambiguation.  See *note Local Time Disambiguation: 5c8. section
for more information.  (Contributed by Alexander Belopolsky in
bpo-24773(1).)

The *note datetime.strftime(): 630. and *note date.strftime(): 631.
methods now support ISO 8601 date directives ‘%G’, ‘%u’ and ‘%V’.
(Contributed by Ashley Anderson in bpo-12006(2).)

The *note datetime.isoformat(): 632. function now accepts an optional
`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(3).)

The *note datetime.combine(): 633. now accepts an optional `tzinfo'
argument.  (Contributed by Alexander Belopolsky in bpo-27661(4).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24773

   (2) https://bugs.python.org/issue12006

   (3) https://bugs.python.org/issue19475

   (4) https://bugs.python.org/issue27661


File: python.info,  Node: decimal<2>,  Next: distutils<3>,  Prev: datetime<4>,  Up: 改进的模块<4>

1.4.5.10 decimal
................

New *note Decimal.as_integer_ratio(): 635. method that returns a pair
‘(n, d)’ of integers that represent the given *note Decimal: 2c0.
instance as a fraction, in lowest terms and with a positive denominator:

     >>> Decimal('-3.14').as_integer_ratio()
     (-157, 50)

（由 Stefan Krah 和 Mark Dickinson 在 bpo-25928(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25928


File: python.info,  Node: distutils<3>,  Next: email,  Prev: decimal<2>,  Up: 改进的模块<4>

1.4.5.11 distutils
..................

The ‘default_format’ attribute has been removed from
‘distutils.command.sdist.sdist’ and the ‘formats’ attribute defaults to
‘['gztar']’.  Although not anticipated, any code relying on the presence
of ‘default_format’ may need to be adapted.  See bpo-27819(1) for more
details.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27819


File: python.info,  Node: email,  Next: encodings,  Prev: distutils<3>,  Up: 改进的模块<4>

1.4.5.12 email
..............

The new email API, enabled via the `policy' keyword to various
constructors, is no longer provisional.  The *note email: 67.
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(1).)

The *note email.mime: 71. classes now all accept an optional `policy'
keyword.  (Contributed by Berker Peksag in bpo-27331(2).)

The *note DecodedGenerator: 638. now supports the `policy' keyword.

There is a new *note policy: 73. attribute, *note message_factory: 639,
that controls what class is used by default when the parser creates new
message objects.  For the *note email.policy.compat32: 63a. policy this
is *note Message: 63b, for the new policies it is *note EmailMessage:
63c.  (Contributed by R. David Murray in bpo-20476(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24277

   (2) https://bugs.python.org/issue27331

   (3) https://bugs.python.org/issue20476


File: python.info,  Node: encodings,  Next: enum<3>,  Prev: email,  Up: 改进的模块<4>

1.4.5.13 encodings
..................

On Windows, added the ‘'oem'’ encoding to use ‘CP_OEMCP’, and the
‘'ansi'’ alias for the existing ‘'mbcs'’ encoding, which uses the
‘CP_ACP’ code page.  (Contributed by Steve Dower in bpo-27959(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27959


File: python.info,  Node: enum<3>,  Next: faulthandler,  Prev: encodings,  Up: 改进的模块<4>

1.4.5.14 enum
.............

Two new enumeration base classes have been added to the *note enum: 79.
module: *note Flag: 63f. and ‘IntFlags’.  Both are used to define
constants that can be combined using the bitwise operators.
(Contributed by Ethan Furman in bpo-23591(1).)

Many standard library modules have been updated to use the ‘IntFlags’
class for their constants.

The new *note enum.auto: 640. value can be used to assign values to enum
members automatically:

     >>> 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>]

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23591


File: python.info,  Node: faulthandler,  Next: fileinput,  Prev: enum<3>,  Up: 改进的模块<4>

1.4.5.15 faulthandler
.....................

On Windows, the *note faulthandler: 7b. module now installs a handler
for Windows exceptions: see *note faulthandler.enable(): 642.
(Contributed by Victor Stinner in bpo-23848(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23848


File: python.info,  Node: fileinput,  Next: hashlib<2>,  Prev: faulthandler,  Up: 改进的模块<4>

1.4.5.16 fileinput
..................

*note hook_encoded(): 644. now supports the `errors' argument.
(Contributed by Joseph Hackman in bpo-25788(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25788


File: python.info,  Node: hashlib<2>,  Next: http client<2>,  Prev: fileinput,  Up: 改进的模块<4>

1.4.5.17 hashlib
................

*note hashlib: 8c. supports OpenSSL 1.1.0.  The minimum recommend
version is 1.0.2.  (Contributed by Christian Heimes in bpo-26470(1).)

BLAKE2 hash functions were added to the module.  *note blake2b(): 646.
and *note blake2s(): 647. are always available and support the full
feature set of BLAKE2.  (Contributed by Christian Heimes in bpo-26798(2)
based on code by Dmitry Chestnykh and Samuel Neves.  Documentation
written by Dmitry Chestnykh.)

The SHA-3 hash functions ‘sha3_224()’, ‘sha3_256()’, ‘sha3_384()’,
‘sha3_512()’, and SHAKE hash functions ‘shake_128()’ and ‘shake_256()’
were added.  (Contributed by Christian Heimes in bpo-16113(3).  Keccak
Code Package by Guido Bertoni, Joan Daemen, Michaël Peeters, Gilles Van
Assche, and Ronny Van Keer.)

The password-based key derivation function *note scrypt(): 5cc. is now
available with OpenSSL 1.1.0 and newer.  (Contributed by Christian
Heimes in bpo-27928(4).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26470

   (2) https://bugs.python.org/issue26798

   (3) https://bugs.python.org/issue16113

   (4) https://bugs.python.org/issue27928


File: python.info,  Node: http client<2>,  Next: idlelib 与 IDLE<2>,  Prev: hashlib<2>,  Up: 改进的模块<4>

1.4.5.18 http.client
....................

*note HTTPConnection.request(): 649. and *note endheaders(): 64a. both
now support chunked encoding request bodies.  (Contributed by Demian
Brecht and Rolf Krahl in bpo-12319(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue12319


File: python.info,  Node: idlelib 与 IDLE<2>,  Next: importlib<4>,  Prev: http client<2>,  Up: 改进的模块<4>

1.4.5.19 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(1).  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(2) 中贡献。）

在 3.6.3 中新增:

Module Browser (在 File 菜单中，之前称为 Class Browser) 现在会在最高层级
函数和类之外显示嵌套的函数和类。 （由 Guilherme Polo, Cheryl Sabella 和
Terry Jan Reedy 在 bpo-1612262(3) 中贡献。）

之前以扩展形式实现的 IDLE 特性已作为正常特性重新实现。 它们的设置已从
Extensions 选项卡移至其他对话框选项卡。 （由 Charles Wohlganger 和 Terry
Jan Reedy 在 bpo-27099(4) 中实现。）

Settings 对话框 (Options 中的 Configure IDLE) 已经被部分重写以改进外观和
功能。 （由 Cheryl Sabella 和 Terry Jan Reedy 在多个问题项中贡献。）

在 3.6.4 中新增:

字体样本现在包括一组非拉丁字符以便用户能更好地查看所选特定字体的效果。 （
由 Terry Jan Reedy 在 bpo-13802(5) 中贡献。） 样本可以被修改以包括其他字
符。 （由 Serhiy Storchaka 在 bpo-31860(6) 中贡献。）

在 3.6.6 中新增:

编辑器代码上下文选项已经过修改。 Box 会显示所有上下文行直到最大行数。 点
击一个上下文行会使编辑器跳转到该行。 自定义主题的上下文颜色已添加到
Settings 对话框的 Highlights 选项卡。 （由 Cheryl Sabella 和 Terry Jan
Reedy 在 bpo-33642(7), bpo-33768(8) 和 bpo-33679(9) 中贡献。）

在 Windows 上，会有新的 API 调用将 tk 对 DPI 的调整告知 Windows。 在
Windows 8.1+ 或 10 上，如果 Python 二进制码的 DPI 兼容属性未改变，并且监
视器分辨率大于 96 DPI，这应该会令文本和线条更清晰。 否则的话它应该不造成
影响。 （由 Terry Jan Reedy 在 bpo-33656(10) 中贡献。）

在 3.6.7 中新增:

超过 N 行（默认值为 50）的输出将被折叠为一个按钮。 N 可以在 Settings 对
话框的 General 页的 PyShell 部分中进行修改。 数量较少但是超长的行可以通
过在输出上右击来折叠。 被折叠的输出可通过双击按钮来展开，或是通过右击按
钮来放入剪贴板或是单独的窗口。 （由 Tal Einat 在 bpo-1529353(11) 中贡献
。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24225

   (2) https://bugs.python.org/issue15786

   (3) https://bugs.python.org/issue1612262

   (4) https://bugs.python.org/issue27099

   (5) https://bugs.python.org/issue13802

   (6) https://bugs.python.org/issue31860

   (7) https://bugs.python.org/issue33642

   (8) https://bugs.python.org/issue33768

   (9) https://bugs.python.org/issue33679

   (10) https://bugs.python.org/issue33656

   (11) https://bugs.python.org/issue1529353


File: python.info,  Node: importlib<4>,  Next: inspect<3>,  Prev: idlelib 与 IDLE<2>,  Up: 改进的模块<4>

1.4.5.20 importlib
..................

Import now raises the new exception *note ModuleNotFoundError: 4a0.
(subclass of *note ImportError: 16c.) when it cannot find a module.
Code that current checks for ‘ImportError’ (in try-except) will still
work.  (Contributed by Eric Snow in bpo-15767(1).)

*note importlib.util.LazyLoader: 64d. now calls *note create_module():
64e. on the wrapped loader, removing the restriction that *note
importlib.machinery.BuiltinImporter: 64f. and *note
importlib.machinery.ExtensionFileLoader: 650. couldn’t be used with
*note importlib.util.LazyLoader: 64d.

*note importlib.util.cache_from_source(): 651, *note
importlib.util.source_from_cache(): 652, and *note
importlib.util.spec_from_file_location(): 653. now accept a *note
path-like object: 472.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15767


File: python.info,  Node: inspect<3>,  Next: json,  Prev: importlib<4>,  Up: 改进的模块<4>

1.4.5.21 inspect
................

The *note inspect.signature(): 655. function now reports the implicit
‘.0’ parameters generated by the compiler for comprehension and
generator expression scopes as if they were positional-only parameters
called ‘implicit0’.  (Contributed by Jelle Zijlstra in bpo-19611(1).)

To reduce code churn when upgrading from Python 2.7 and the legacy *note
inspect.getargspec(): 656. API, the previously documented deprecation of
*note inspect.getfullargspec(): 657. has been reversed.  While this
function is convenient for single/source Python 2/3 code bases, the
richer *note inspect.signature(): 655. interface remains the recommended
approach for new code.  (Contributed by Nick Coghlan in bpo-27172(2))

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue19611

   (2) https://bugs.python.org/issue27172


File: python.info,  Node: json,  Next: logging<3>,  Prev: inspect<3>,  Up: 改进的模块<4>

1.4.5.22 json
.............

*note json.load(): 659. and *note json.loads(): 225. 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(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17909


File: python.info,  Node: logging<3>,  Next: math<4>,  Prev: json,  Up: 改进的模块<4>

1.4.5.23 logging
................

The new *note WatchedFileHandler.reopenIfNeeded(): 65b. 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(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24884


File: python.info,  Node: math<4>,  Next: multiprocessing<4>,  Prev: logging<3>,  Up: 改进的模块<4>

1.4.5.24 math
.............

The tau (`τ') constant has been added to the *note math: b1. and *note
cmath: 18. modules.  (Contributed by Lisa Roach in bpo-12345(1), see PEP
628(2) for details.)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue12345

   (2) https://www.python.org/dev/peps/pep-0628


File: python.info,  Node: multiprocessing<4>,  Next: os<4>,  Prev: math<4>,  Up: 改进的模块<4>

1.4.5.25 multiprocessing
........................

*note Proxy Objects: 65e. returned by ‘multiprocessing.Manager()’ can
now be nested.  (Contributed by Davin Potts in bpo-6766(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue6766


File: python.info,  Node: os<4>,  Next: pathlib<4>,  Prev: multiprocessing<4>,  Up: 改进的模块<4>

1.4.5.26 os
...........

See the summary of *note PEP 519: 5c7. for details on how the *note os:
c4. and *note os.path: c5. modules now support *note path-like objects:
472.

*note scandir(): 389. now supports *note bytes: 172. paths on Windows.

A new *note close(): 660. method allows explicitly closing a *note
scandir(): 389. iterator.  The *note scandir(): 389. iterator now
supports the *note context manager: 661. protocol.  If a ‘scandir()’
iterator is neither exhausted nor explicitly closed a *note
ResourceWarning: 5ca. will be emitted in its destructor.  (Contributed
by Serhiy Storchaka in bpo-25994(1).)

在 Linux 上，现在 *note os.urandom(): 5cb. 会阻塞直到系统的 urandom 熵池
被初始化以提升安全性。 其理由参见 PEP 524(2)。

The Linux ‘getrandom()’ syscall (get random bytes) is now exposed as the
new *note os.getrandom(): 662. function.  (Contributed by Victor
Stinner, part of the PEP 524(3))

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25994

   (2) https://www.python.org/dev/peps/pep-0524

   (3) https://www.python.org/dev/peps/pep-0524


File: python.info,  Node: pathlib<4>,  Next: pdb<3>,  Prev: os<4>,  Up: 改进的模块<4>

1.4.5.27 pathlib
................

*note pathlib: c8. now supports *note path-like objects: 472.
(Contributed by Brett Cannon in bpo-27186(1).)

See the summary of *note PEP 519: 5c7. for details.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27186


File: python.info,  Node: pdb<3>,  Next: pickle<2>,  Prev: pathlib<4>,  Up: 改进的模块<4>

1.4.5.28 pdb
............

The *note Pdb: 1d3. class constructor has a new optional `readrc'
argument to control whether ‘.pdbrc’ files should be read.


File: python.info,  Node: pickle<2>,  Next: pickletools,  Prev: pdb<3>,  Up: 改进的模块<4>

1.4.5.29 pickle
...............

Objects that need ‘__new__’ called with keyword arguments can now be
pickled using *note pickle protocols: 666. older than protocol version
4.  Protocol version 4 already supports this case.  (Contributed by
Serhiy Storchaka in bpo-24164(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24164


File: python.info,  Node: pickletools,  Next: pydoc<3>,  Prev: pickle<2>,  Up: 改进的模块<4>

1.4.5.30 pickletools
....................

*note pickletools.dis(): 668. now outputs the implicit memo index for
the ‘MEMOIZE’ opcode.  (Contributed by Serhiy Storchaka in
bpo-25382(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25382


File: python.info,  Node: pydoc<3>,  Next: random<2>,  Prev: pickletools,  Up: 改进的模块<4>

1.4.5.31 pydoc
..............

The *note pydoc: d9. module has learned to respect the ‘MANPAGER’
environment variable.  (Contributed by Matthias Klose in bpo-8637(1).)

*note help(): 175. and *note pydoc: d9. can now list named tuple fields
in the order they were defined rather than alphabetically.  (Contributed
by Raymond Hettinger in bpo-24879(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue8637

   (2) https://bugs.python.org/issue24879


File: python.info,  Node: random<2>,  Next: re<2>,  Prev: pydoc<3>,  Up: 改进的模块<4>

1.4.5.32 random
...............

The new *note choices(): 66b. function returns a list of elements of
specified size from the given population with optional weights.
(Contributed by Raymond Hettinger in bpo-18844(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18844


File: python.info,  Node: re<2>,  Next: readline,  Prev: random<2>,  Up: 改进的模块<4>

1.4.5.33 re
...........

Added support of modifier spans in regular expressions.  Examples:
‘'(?i:p)ython'’ matches ‘'python'’ and ‘'Python'’, but not ‘'PYTHON'’;
‘'(?i)g(?-i:v)r'’ matches ‘'GvR'’ and ‘'gvr'’, but not ‘'GVR'’.
(Contributed by Serhiy Storchaka in bpo-433028(1).)

Match object groups can be accessed by ‘__getitem__’, which is
equivalent to ‘group()’.  So ‘mo['name']’ is now equivalent to
‘mo.group('name')’.  (Contributed by Eric Smith in bpo-24454(2).)

‘Match’ objects now support *note index-like objects: 2c2. as group
indices.  (Contributed by Jeroen Demeyer and Xiang Zhang in
bpo-27177(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue433028

   (2) https://bugs.python.org/issue24454

   (3) https://bugs.python.org/issue27177


File: python.info,  Node: readline,  Next: rlcompleter,  Prev: re<2>,  Up: 改进的模块<4>

1.4.5.34 readline
.................

Added *note set_auto_history(): 66e. to enable or disable automatic
addition of input to the history list.  (Contributed by Tyler Crompton
in bpo-26870(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26870


File: python.info,  Node: rlcompleter,  Next: shlex<2>,  Prev: readline,  Up: 改进的模块<4>

1.4.5.35 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(1)
and bpo-25209(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25011

   (2) https://bugs.python.org/issue25209


File: python.info,  Node: shlex<2>,  Next: site,  Prev: rlcompleter,  Up: 改进的模块<4>

1.4.5.36 shlex
..............

The *note shlex: 671. has much *note improved shell compatibility: 672.
through the new `punctuation_chars' argument to control which characters
are treated as punctuation.  (Contributed by Vinay Sajip in
bpo-1521950(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1521950


File: python.info,  Node: site,  Next: sqlite3<2>,  Prev: shlex<2>,  Up: 改进的模块<4>

1.4.5.37 site
.............

When specifying paths to add to *note sys.path: 261. in a ‘.pth’ file,
you may now specify file paths on top of directories (e.g.  zip files).
(Contributed by Wolfgang Langner in bpo-26587(1)).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26587


File: python.info,  Node: sqlite3<2>,  Next: socket<5>,  Prev: site,  Up: 改进的模块<4>

1.4.5.38 sqlite3
................

*note sqlite3.Cursor.lastrowid: 675. now supports the ‘REPLACE’
statement.  (Contributed by Alex LordThorsen in bpo-16864(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16864


File: python.info,  Node: socket<5>,  Next: socketserver<2>,  Prev: sqlite3<2>,  Up: 改进的模块<4>

1.4.5.39 socket
...............

The *note ioctl(): 677. function now supports the *note
SIO_LOOPBACK_FAST_PATH: 678. control code.  (Contributed by Daniel
Stokes in bpo-26536(1).)

The *note getsockopt(): 679. constants ‘SO_DOMAIN’, ‘SO_PROTOCOL’,
‘SO_PEERSEC’, and ‘SO_PASSSEC’ are now supported.  (Contributed by
Christian Heimes in bpo-26907(2).)

The *note setsockopt(): 67a. now supports the ‘setsockopt(level,
optname, None, optlen: int)’ form.  (Contributed by Christian Heimes in
bpo-27744(3).)

The socket module now supports the address family *note AF_ALG: 67b. to
interface with Linux Kernel crypto API. ‘ALG_*’, ‘SOL_ALG’ and *note
sendmsg_afalg(): 67c. were added.  (Contributed by Christian Heimes in
bpo-27744(4) with support from Victor Stinner.)

New Linux constants ‘TCP_USER_TIMEOUT’ and ‘TCP_CONGESTION’ were added.
(Contributed by Omar Sandoval, issue:‘26273’).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26536

   (2) https://bugs.python.org/issue26907

   (3) https://bugs.python.org/issue27744

   (4) https://bugs.python.org/issue27744


File: python.info,  Node: socketserver<2>,  Next: ssl<4>,  Prev: socket<5>,  Up: 改进的模块<4>

1.4.5.40 socketserver
.....................

Servers based on the *note socketserver: f0. module, including those
defined in *note http.server: 96, *note xmlrpc.server: 149. and *note
wsgiref.simple_server: 138, now support the *note context manager: 661.
protocol.  (Contributed by Aviv Palivoda in bpo-26404(1).)

The ‘wfile’ attribute of *note StreamRequestHandler: 67e. classes now
implements the *note io.BufferedIOBase: 67f. writable interface.  In
particular, calling *note write(): 680. is now guaranteed to send the
data in full.  (Contributed by Martin Panter in bpo-26721(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26404

   (2) https://bugs.python.org/issue26721


File: python.info,  Node: ssl<4>,  Next: statistics<2>,  Prev: socketserver<2>,  Up: 改进的模块<4>

1.4.5.41 ssl
............

*note ssl: f3. supports OpenSSL 1.1.0.  The minimum recommend version is
1.0.2.  (Contributed by Christian Heimes in bpo-26470(1).)

3DES has been removed from the default cipher suites and ChaCha20
Poly1305 cipher suites have been added.  (Contributed by Christian
Heimes in bpo-27850(2) and bpo-27766(3).)

*note SSLContext: 4e9. has better default configuration for options and
ciphers.  (Contributed by Christian Heimes in bpo-28043(4).)

SSL session can be copied from one client-side connection to another
with the new *note SSLSession: 682. class.  TLS session resumption can
speed up the initial handshake, reduce latency and improve performance
(Contributed by Christian Heimes in bpo-19500(5) based on a draft by
Alex Warhawk.)

The new *note get_ciphers(): 683. method can be used to get a list of
enabled ciphers in order of cipher priority.

All constants and flags have been converted to *note IntEnum: 684. and
‘IntFlags’.  (Contributed by Christian Heimes in bpo-28025(6).)

Server and client-side specific TLS protocols for *note SSLContext: 4e9.
were added.  (Contributed by Christian Heimes in bpo-28085(7).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26470

   (2) https://bugs.python.org/issue27850

   (3) https://bugs.python.org/issue27766

   (4) https://bugs.python.org/issue28043

   (5) https://bugs.python.org/issue19500

   (6) https://bugs.python.org/issue28025

   (7) https://bugs.python.org/issue28085


File: python.info,  Node: statistics<2>,  Next: struct,  Prev: ssl<4>,  Up: 改进的模块<4>

1.4.5.42 statistics
...................

A new *note harmonic_mean(): 686. function has been added.  (Contributed
by Steven D’Aprano in bpo-27181(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27181


File: python.info,  Node: struct,  Next: subprocess<2>,  Prev: statistics<2>,  Up: 改进的模块<4>

1.4.5.43 struct
...............

*note struct: f8. now supports IEEE 754 half-precision floats via the
‘'e'’ format specifier.  (Contributed by Eli Stevens, Mark Dickinson in
bpo-11734(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue11734


File: python.info,  Node: subprocess<2>,  Next: sys<5>,  Prev: struct,  Up: 改进的模块<4>

1.4.5.44 subprocess
...................

*note subprocess.Popen: 3db. destructor now emits a *note
ResourceWarning: 5ca. warning if the child process is still running.
Use the context manager protocol (‘with proc: ...’) or explicitly call
the *note wait(): 689. method to read the exit status of the child
process.  (Contributed by Victor Stinner in bpo-26741(1).)

The *note subprocess.Popen: 3db. constructor and all functions that pass
arguments through to it now accept `encoding' and `errors' arguments.
Specifying either of these will enable text mode for the `stdin',
`stdout' and `stderr' streams.  (Contributed by Steve Dower in
bpo-6135(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26741

   (2) https://bugs.python.org/issue6135


File: python.info,  Node: sys<5>,  Next: telnetlib,  Prev: subprocess<2>,  Up: 改进的模块<4>

1.4.5.45 sys
............

The new *note getfilesystemencodeerrors(): 68b. function returns the
name of the error mode used to convert between Unicode filenames and
bytes filenames.  (Contributed by Steve Dower in bpo-27781(1).)

On Windows the return value of the *note getwindowsversion(): 68c.
function now includes the `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(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27781

   (2) https://bugs.python.org/issue27932


File: python.info,  Node: telnetlib,  Next: time<4>,  Prev: sys<5>,  Up: 改进的模块<4>

1.4.5.46 telnetlib
..................

*note Telnet: 68e. is now a context manager (contributed by Stéphane
Wirtel in bpo-25485(1)).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25485


File: python.info,  Node: time<4>,  Next: timeit,  Prev: telnetlib,  Up: 改进的模块<4>

1.4.5.47 time
.............

The *note struct_time: 690. attributes ‘tm_gmtoff’ and ‘tm_zone’ are now
available on all platforms.


File: python.info,  Node: timeit,  Next: tkinter<3>,  Prev: time<4>,  Up: 改进的模块<4>

1.4.5.48 timeit
...............

The new *note Timer.autorange(): 692. convenience method has been added
to call *note Timer.timeit(): 693. repeatedly so that the total run time
is greater or equal to 200 milliseconds.  (Contributed by Steven
D’Aprano in bpo-6422(1).)

*note timeit: 10d. now warns when there is substantial (4x) variance
between best and worst times.  (Contributed by Serhiy Storchaka in
bpo-23552(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue6422

   (2) https://bugs.python.org/issue23552


File: python.info,  Node: tkinter<3>,  Next: traceback,  Prev: timeit,  Up: 改进的模块<4>

1.4.5.49 tkinter
................

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.  (Contributed by
Serhiy Storchaka in bpo-22115(1)).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22115


File: python.info,  Node: traceback,  Next: tracemalloc<3>,  Prev: tkinter<3>,  Up: 改进的模块<4>

1.4.5.50 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:

     >>> 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

（由 Emanuel Barry在 bpo-26823(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26823


File: python.info,  Node: tracemalloc<3>,  Next: typing<4>,  Prev: traceback,  Up: 改进的模块<4>

1.4.5.51 tracemalloc
....................

The *note tracemalloc: 11d. module now supports tracing memory
allocations in multiple different address spaces.

The new *note DomainFilter: 697. filter class has been added to filter
block traces by their address space (domain).

（由 Victor Stinner 在 bpo-26588(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26588


File: python.info,  Node: typing<4>,  Next: unicodedata<4>,  Prev: tracemalloc<3>,  Up: 改进的模块<4>

1.4.5.52 typing
...............

Since the *note typing: 122. module is *note provisional: 454, all
changes introduced in Python 3.6 have also been backported to Python
3.5.x.

The *note typing: 122. module has a much improved support for generic
type aliases.  For example ‘Dict[str, Tuple[S, T]]’ is now a valid type
annotation.  (Contributed by Guido van Rossum in Github #195(1).)

The *note typing.ContextManager: 62e. class has been added for
representing *note contextlib.AbstractContextManager: 62d.  (Contributed
by Brett Cannon in bpo-25609(2).)

The *note typing.Collection: 699. class has been added for representing
*note collections.abc.Collection: 626.  (Contributed by Ivan Levkivskyi
in bpo-27598(3).)

The *note typing.ClassVar: 69a. type construct has been added to mark
class variables.  As introduced in PEP 526(4), 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(5).)

A new *note TYPE_CHECKING: 69b. constant that is assumed to be ‘True’ by
the static type checkers, but is ‘False’ at runtime.  (Contributed by
Guido van Rossum in Github #230(6).)

A new *note NewType(): 69c. helper function has been added to create
lightweight distinct types for annotations:

     from typing import NewType

     UserId = NewType('UserId', int)
     some_id = UserId(524313)

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(7).)

   ---------- Footnotes ----------

   (1) https://github.com/python/typing/pull/195

   (2) https://bugs.python.org/issue25609

   (3) https://bugs.python.org/issue27598

   (4) https://www.python.org/dev/peps/pep-0526

   (5) https://github.com/python/typing/pull/280

   (6) https://github.com/python/typing/issues/230

   (7) https://github.com/python/typing/issues/189


File: python.info,  Node: unicodedata<4>,  Next: unittest mock<2>,  Prev: typing<4>,  Up: 改进的模块<4>

1.4.5.53 unicodedata
....................

The *note unicodedata: 123. module now uses data from Unicode 9.0.0(1).
(Contributed by Benjamin Peterson.)

   ---------- Footnotes ----------

   (1) http://unicode.org/versions/Unicode9.0.0/


File: python.info,  Node: unittest mock<2>,  Next: urllib request,  Prev: unicodedata<4>,  Up: 改进的模块<4>

1.4.5.54 unittest.mock
......................

The *note Mock: 373. class has the following improvements:

   * Two new methods, *note Mock.assert_called(): 69f. and *note
     Mock.assert_called_once(): 6a0. to check if the mock object was
     called.  (Contributed by Amit Saha in bpo-26323(1).)

   * The *note Mock.reset_mock(): 6a1. method now has two optional
     keyword only arguments: `return_value' and `side_effect'.
     (Contributed by Kushal Das in bpo-21271(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26323

   (2) https://bugs.python.org/issue21271


File: python.info,  Node: urllib request,  Next: urllib robotparser,  Prev: unittest mock<2>,  Up: 改进的模块<4>

1.4.5.55 urllib.request
.......................

If a HTTP request has a file or iterable body (other than a bytes
object) but no ‘Content-Length’ header, rather than throwing an error,
‘AbstractHTTPHandler’ now falls back to use chunked transfer encoding.
(Contributed by Demian Brecht and Rolf Krahl in bpo-12319(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue12319


File: python.info,  Node: urllib robotparser,  Next: venv<3>,  Prev: urllib request,  Up: 改进的模块<4>

1.4.5.56 urllib.robotparser
...........................

*note RobotFileParser: 6a4. now supports the ‘Crawl-delay’ and
‘Request-rate’ extensions.  (Contributed by Nikolay Bogoychev in
bpo-16099(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16099


File: python.info,  Node: venv<3>,  Next: warnings<2>,  Prev: urllib robotparser,  Up: 改进的模块<4>

1.4.5.57 venv
.............

*note venv: 12e. accepts a new parameter ‘--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(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22829


File: python.info,  Node: warnings<2>,  Next: winreg,  Prev: venv<3>,  Up: 改进的模块<4>

1.4.5.58 warnings
.................

A new optional `source' parameter has been added to the *note
warnings.warn_explicit(): 6a7. function: the destroyed object which
emitted a *note ResourceWarning: 5ca.  A `source' attribute has also
been added to ‘warnings.WarningMessage’ (contributed by Victor Stinner
in bpo-26568(1) and bpo-26567(2)).

When a *note ResourceWarning: 5ca. warning is logged, the *note
tracemalloc: 11d. module is now used to try to retrieve the traceback
where the destroyed object was allocated.

Example with the script ‘example.py’:

     import warnings

     def func():
         return open(__file__)

     f = func()
     f = None

Output of the command ‘python3.6 -Wd -X tracemalloc=5 example.py’:

     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()

The "Object allocated at" traceback is new and is only displayed if
*note tracemalloc: 11d. is tracing Python memory allocations and if the
*note warnings: 12f. module was already imported.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26568

   (2) https://bugs.python.org/issue26567


File: python.info,  Node: winreg,  Next: winsound,  Prev: warnings<2>,  Up: 改进的模块<4>

1.4.5.59 winreg
...............

Added the 64-bit integer type *note REG_QWORD: 6a9.  (Contributed by
Clement Rouault in bpo-23026(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23026


File: python.info,  Node: winsound,  Next: xmlrpc client,  Prev: winreg,  Up: 改进的模块<4>

1.4.5.60 winsound
.................

Allowed keyword arguments to be passed to *note Beep: 6ab, *note
MessageBeep: 6ac, and *note PlaySound: 6ad. (bpo-27982(1)).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27982


File: python.info,  Node: xmlrpc client,  Next: zipfile<2>,  Prev: winsound,  Up: 改进的模块<4>

1.4.5.61 xmlrpc.client
......................

The *note xmlrpc.client: 148. module now supports unmarshalling
additional data types used by the Apache XML-RPC implementation for
numerics and ‘None’.  (Contributed by Serhiy Storchaka in bpo-26885(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26885


File: python.info,  Node: zipfile<2>,  Next: zlib,  Prev: xmlrpc client,  Up: 改进的模块<4>

1.4.5.62 zipfile
................

A new *note ZipInfo.from_file(): 6b0. class method allows making a *note
ZipInfo: 6b1. instance from a filesystem file.  A new *note
ZipInfo.is_dir(): 6b2. method can be used to check if the *note ZipInfo:
6b1. instance represents a directory.  (Contributed by Thomas Kluyver in
bpo-26039(1).)

The *note ZipFile.open(): 6b3. 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(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26039

   (2) https://bugs.python.org/issue26039


File: python.info,  Node: zlib,  Prev: zipfile<2>,  Up: 改进的模块<4>

1.4.5.63 zlib
.............

The *note compress(): 6b5. and *note decompress(): 6b6. functions now
accept keyword arguments.  (Contributed by Aviv Palivoda in bpo-26243(1)
and Xiang Zhang in bpo-16764(2) respectively.)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26243

   (2) https://bugs.python.org/issue16764


File: python.info,  Node: 性能优化<4>,  Next: 构建和 C API 的改变<2>,  Prev: 改进的模块<4>,  Up: Python 3 6 有什么新变化

1.4.6 性能优化
--------------

   * 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(1) and bpo-28050(2).)

   * The *note asyncio.Future: 545. class now has an optimized C
     implementation.  (Contributed by Yury Selivanov and INADA Naoki in
     bpo-26081(3).)

   * The *note asyncio.Task: 2e0. class now has an optimized C
     implementation.  (Contributed by Yury Selivanov in bpo-28544(4).)

   * Various implementation improvements in the *note typing: 122.
     module (such as caching of generic types) allow up to 30 times
     performance improvements and reduced memory footprint.

   * The ASCII decoder is now up to 60 times as fast for error handlers
     ‘surrogateescape’, ‘ignore’ and ‘replace’ (Contributed by Victor
     Stinner in bpo-24870(5)).

   * The ASCII and the Latin1 encoders are now up to 3 times as fast for
     the error handler ‘surrogateescape’ (Contributed by Victor Stinner
     in bpo-25227(6)).

   * The UTF-8 encoder is now up to 75 times as fast for error handlers
     ‘ignore’, ‘replace’, ‘surrogateescape’, ‘surrogatepass’
     (Contributed by Victor Stinner in bpo-25267(7)).

   * The UTF-8 decoder is now up to 15 times as fast for error handlers
     ‘ignore’, ‘replace’ and ‘surrogateescape’ (Contributed by Victor
     Stinner in bpo-25301(8)).

   * ‘bytes % args’ is now up to 2 times faster.  (Contributed by Victor
     Stinner in bpo-25349(9)).

   * ‘bytearray % args’ is now between 2.5 and 5 times faster.
     (Contributed by Victor Stinner in bpo-25399(10)).

   * Optimize *note bytes.fromhex(): 43e. and *note bytearray.fromhex():
     43f.: they are now between 2x and 3.5x faster.  (Contributed by
     Victor Stinner in bpo-25401(11)).

   * Optimize ‘bytes.replace(b'', b'.')’ and ‘bytearray.replace(b'',
     b'.')’: up to 80% faster.  (Contributed by Josh Snider in
     bpo-26574(12)).

   * Allocator functions of the *note PyMem_Malloc(): 5fe. domain (*note
     PYMEM_DOMAIN_MEM: 602.) now use the *note pymalloc memory
     allocator: 6b8. instead of ‘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 ‘malloc()’ for larger
     memory blocks.  (Contributed by Victor Stinner in bpo-26249(13)).

   * *note pickle.load(): 6b9. and *note pickle.loads(): 6ba. are now up
     to 10% faster when deserializing many small objects (Contributed by
     Victor Stinner in bpo-27056(14)).

   * Passing *note keyword arguments: 6bb. to a function has an overhead
     in comparison with passing *note positional arguments: 6bc.  Now in
     extension functions implemented with using Argument Clinic this
     overhead is significantly decreased.  (Contributed by Serhiy
     Storchaka in bpo-27574(15)).

   * Optimized *note glob(): 6bd. and *note iglob(): 6be. functions in
     the *note glob: 88. module; they are now about 3–6 times faster.
     (Contributed by Serhiy Storchaka in bpo-25596(16)).

   * Optimized globbing in *note pathlib: c8. by using *note
     os.scandir(): 389.; it is now about 1.5–4 times faster.
     (Contributed by Serhiy Storchaka in bpo-26032(17)).

   * *note xml.etree.ElementTree: 140. parsing, iteration and deepcopy
     performance has been significantly improved.  (Contributed by
     Serhiy Storchaka in bpo-25638(18), bpo-25873(19), and
     bpo-25869(20).)

   * Creation of *note fractions.Fraction: 2be. instances from floats
     and decimals is now 2 to 3 times faster.  (Contributed by Serhiy
     Storchaka in bpo-25971(21).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26647

   (2) https://bugs.python.org/issue28050

   (3) https://bugs.python.org/issue26081

   (4) https://bugs.python.org/issue28544

   (5) https://bugs.python.org/issue24870

   (6) https://bugs.python.org/issue25227

   (7) https://bugs.python.org/issue25267

   (8) https://bugs.python.org/issue25301

   (9) https://bugs.python.org/issue25349

   (10) https://bugs.python.org/issue25399

   (11) https://bugs.python.org/issue25401

   (12) https://bugs.python.org/issue26574

   (13) https://bugs.python.org/issue26249

   (14) https://bugs.python.org/issue27056

   (15) https://bugs.python.org/issue27574

   (16) https://bugs.python.org/issue25596

   (17) https://bugs.python.org/issue26032

   (18) https://bugs.python.org/issue25638

   (19) https://bugs.python.org/issue25873

   (20) https://bugs.python.org/issue25869

   (21) https://bugs.python.org/issue25971


File: python.info,  Node: 构建和 C API 的改变<2>,  Next: 其他改进,  Prev: 性能优化<4>,  Up: Python 3 6 有什么新变化

1.4.7 构建和 C API 的改变
-------------------------

   * 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 ‘PY_LONG_LONG’.  For more information,
     see PEP 7(1) and bpo-17884(2).

   * 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(3).

   * The ‘--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(4).)

   * The *note GIL: 5ff. must now be held when allocator functions of
     *note PYMEM_DOMAIN_OBJ: 600. (ex: *note PyObject_Malloc(): 601.)
     and *note PYMEM_DOMAIN_MEM: 602. (ex: *note PyMem_Malloc(): 5fe.)
     domains are called.

   * New *note Py_FinalizeEx(): 6c0. API which indicates if flushing
     buffered data failed.  (Contributed by Martin Panter in
     bpo-5319(5).)

   * *note PyArg_ParseTupleAndKeywords(): 6c1. now supports *note
     positional-only parameters: 3c9.  Positional-only parameters are
     defined by empty names.  (Contributed by Serhiy Storchaka in
     bpo-26282(6)).

   * ‘PyTraceback_Print’ method now abbreviates long sequences of
     repeated lines as ‘"[Previous line repeated {count} more times]"’.
     (Contributed by Emanuel Barry in bpo-26823(7).)

   * The new *note PyErr_SetImportErrorSubclass(): 6c2. function allows
     for specifying a subclass of *note ImportError: 16c. to raise.
     (Contributed by Eric Snow in bpo-15767(8).)

   * The new *note PyErr_ResourceWarning(): 6c3. function can be used to
     generate a *note ResourceWarning: 5ca. providing the source of the
     resource allocation.  (Contributed by Victor Stinner in
     bpo-26567(9).)

   * The new *note PyOS_FSPath(): 6c4. function returns the file system
     representation of a *note path-like object: 472.  (Contributed by
     Brett Cannon in bpo-27186(10).)

   * The *note PyUnicode_FSConverter(): 6c5. and *note
     PyUnicode_FSDecoder(): 6c6. functions will now accept *note
     path-like objects: 472.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0007

   (2) https://bugs.python.org/issue17884

   (3) https://bugs.python.org/issue26865

   (4) https://bugs.python.org/issue26359

   (5) https://bugs.python.org/issue5319

   (6) https://bugs.python.org/issue26282

   (7) https://bugs.python.org/issue26823

   (8) https://bugs.python.org/issue15767

   (9) https://bugs.python.org/issue26567

   (10) https://bugs.python.org/issue27186


File: python.info,  Node: 其他改进,  Next: 弃用<3>,  Prev: 构建和 C API 的改变<2>,  Up: Python 3 6 有什么新变化

1.4.8 其他改进
--------------

   * When *note –version: 6c8. (short form: *note -V: 6c9.) is supplied
     twice, Python prints *note sys.version: 6ca. for detailed
     information.

          $ ./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)]


File: python.info,  Node: 弃用<3>,  Next: 移除<3>,  Prev: 其他改进,  Up: Python 3 6 有什么新变化

1.4.9 弃用
----------

* Menu:

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


File: python.info,  Node: 新关键字,  Next: 已弃用的 Python 行为<2>,  Up: 弃用<3>

1.4.9.1 新关键字
................

‘async’ and ‘await’ are not recommended to be used as variable, class,
function or module names.  Introduced by PEP 492(1) in Python 3.5, they
will become proper keywords in Python 3.7.  Starting in Python 3.6, the
use of ‘async’ or ‘await’ as names will generate a *note
DeprecationWarning: 15a.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0492


File: python.info,  Node: 已弃用的 Python 行为<2>,  Next: 已弃用的 Python 模块、函数和方法<2>,  Prev: 新关键字,  Up: 弃用<3>

1.4.9.2 已弃用的 Python 行为
............................

Raising the *note StopIteration: 581. exception inside a generator will
now generate a *note DeprecationWarning: 15a, and will trigger a *note
RuntimeError: 3dc. in Python 3.7.  See *note PEP 479; Change
StopIteration handling inside generators: 6ce. for details.

The *note __aiter__(): 582. method is now expected to return an
asynchronous iterator directly instead of returning an awaitable as
previously.  Doing the former will trigger a *note DeprecationWarning:
15a.  Backward compatibility will be removed in Python 3.7.
(Contributed by Yury Selivanov in bpo-27243(1).)

A backslash-character pair that is not a valid escape sequence now
generates a *note DeprecationWarning: 15a.  Although this will
eventually become a *note SyntaxError: 559, that will not be for several
Python releases.  (Contributed by Emanuel Barry in bpo-27364(2).)

When performing a relative import, falling back on ‘__name__’ and
‘__path__’ from the calling module when ‘__spec__’ or ‘__package__’ are
not defined now raises an *note ImportWarning: 6cf.  (Contributed by
Rose Ames in bpo-25791(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27243

   (2) https://bugs.python.org/issue27364

   (3) https://bugs.python.org/issue25791


File: python.info,  Node: 已弃用的 Python 模块、函数和方法<2>,  Next: 已弃用的 C API 函数和类型<2>,  Prev: 已弃用的 Python 行为<2>,  Up: 弃用<3>

1.4.9.3 已弃用的 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>.


File: python.info,  Node: asynchat,  Next: asyncore,  Up: 已弃用的 Python 模块、函数和方法<2>

1.4.9.4 asynchat
................

The *note asynchat: 8. has been deprecated in favor of *note asyncio: 9.
(Contributed by Mariatta in bpo-25002(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25002


File: python.info,  Node: asyncore,  Next: dbm<3>,  Prev: asynchat,  Up: 已弃用的 Python 模块、函数和方法<2>

1.4.9.5 asyncore
................

The *note asyncore: a. has been deprecated in favor of *note asyncio: 9.
(Contributed by Mariatta in bpo-25002(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25002


File: python.info,  Node: dbm<3>,  Next: distutils<4>,  Prev: asyncore,  Up: 已弃用的 Python 模块、函数和方法<2>

1.4.9.6 dbm
...........

Unlike other *note dbm: 31. implementations, the *note dbm.dumb: 32.
module creates databases with the ‘'rw'’ mode and allows modifying the
database opened with the ‘'r'’ mode.  This behavior is now deprecated
and will be removed in 3.8.  (Contributed by Serhiy Storchaka in
bpo-21708(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21708


File: python.info,  Node: distutils<4>,  Next: grp,  Prev: dbm<3>,  Up: 已弃用的 Python 模块、函数和方法<2>

1.4.9.7 distutils
.................

The undocumented ‘extra_path’ argument to the ‘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(1) for details.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27919


File: python.info,  Node: grp,  Next: importlib<5>,  Prev: distutils<4>,  Up: 已弃用的 Python 模块、函数和方法<2>

1.4.9.8 grp
...........

The support of non-integer arguments in *note getgrgid(): 6d6. has been
deprecated.  (Contributed by Serhiy Storchaka in bpo-26129(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26129


File: python.info,  Node: importlib<5>,  Next: os<5>,  Prev: grp,  Up: 已弃用的 Python 模块、函数和方法<2>

1.4.9.9 importlib
.................

The *note importlib.machinery.SourceFileLoader.load_module(): 6d8. and
*note importlib.machinery.SourcelessFileLoader.load_module(): 6d9.
methods are now deprecated.  They were the only remaining
implementations of *note importlib.abc.Loader.load_module(): 6da. in
*note importlib: 9a. that had not been deprecated in previous versions
of Python in favour of *note importlib.abc.Loader.exec_module(): 6db.

The *note importlib.machinery.WindowsRegistryFinder: 6dc. class is now
deprecated.  As of 3.6.0, it is still added to *note sys.meta_path: 6dd.
by default (on Windows), but this may change in future releases.


File: python.info,  Node: os<5>,  Next: re<3>,  Prev: importlib<5>,  Up: 已弃用的 Python 模块、函数和方法<2>

1.4.9.10 os
...........

Undocumented support of general *note bytes-like objects: 6df. as paths
in *note os: c4. functions, *note compile(): 2e7. and similar functions
is now deprecated.  (Contributed by Serhiy Storchaka in bpo-25791(1) and
bpo-26754(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25791

   (2) https://bugs.python.org/issue26754


File: python.info,  Node: re<3>,  Next: ssl<5>,  Prev: os<5>,  Up: 已弃用的 Python 模块、函数和方法<2>

1.4.9.11 re
...........

Support for inline flags ‘(?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(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22493


File: python.info,  Node: ssl<5>,  Next: tkinter<4>,  Prev: re<3>,  Up: 已弃用的 Python 模块、函数和方法<2>

1.4.9.12 ssl
............

OpenSSL 0.9.8, 1.0.0 and 1.0.1 are deprecated and no longer supported.
In the future the *note ssl: f3. module will require at least OpenSSL
1.0.2 or 1.1.0.

SSL-related arguments like ‘certfile’, ‘keyfile’ and ‘check_hostname’ in
*note ftplib: 82, *note http.client: 93, *note imaplib: 97, *note
poplib: d0, and *note smtplib: ed. have been deprecated in favor of
‘context’.  (Contributed by Christian Heimes in bpo-28022(1).)

A couple of protocols and functions of the *note ssl: f3. 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(2) and
bpo-26470(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28022

   (2) https://bugs.python.org/issue28022

   (3) https://bugs.python.org/issue26470


File: python.info,  Node: tkinter<4>,  Next: venv<4>,  Prev: ssl<5>,  Up: 已弃用的 Python 模块、函数和方法<2>

1.4.9.13 tkinter
................

The *note tkinter.tix: 117. module is now deprecated.  *note tkinter:
10e. users should use *note tkinter.ttk: 118. instead.


File: python.info,  Node: venv<4>,  Prev: tkinter<4>,  Up: 已弃用的 Python 模块、函数和方法<2>

1.4.9.14 venv
.............

The ‘pyvenv’ script has been deprecated in favour of ‘python3 -m venv’.
This prevents confusion as to what Python interpreter ‘pyvenv’ is
connected to and thus what Python interpreter will be used by the
virtual environment.  (Contributed by Brett Cannon in bpo-25154(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25154


File: python.info,  Node: 已弃用的 C API 函数和类型<2>,  Next: 弃用的构建选项,  Prev: 已弃用的 Python 模块、函数和方法<2>,  Up: 弃用<3>

1.4.9.15 已弃用的 C API 函数和类型
..................................

Undocumented functions ‘PyUnicode_AsEncodedObject()’,
‘PyUnicode_AsDecodedObject()’, ‘PyUnicode_AsEncodedUnicode()’ and
‘PyUnicode_AsDecodedUnicode()’ are deprecated now.  Use the *note
generic codec based API: 6e5. instead.


File: python.info,  Node: 弃用的构建选项,  Prev: 已弃用的 C API 函数和类型<2>,  Up: 弃用<3>

1.4.9.16 弃用的构建选项
.......................

The ‘--with-system-ffi’ configure flag is now on by default on non-macOS
UNIX platforms.  It may be disabled by using ‘--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 ‘--with-system-ffi’ flag when building their system
Python.


File: python.info,  Node: 移除<3>,  Next: 移植到Python 3 6,  Prev: 弃用<3>,  Up: Python 3 6 有什么新变化

1.4.10 移除
-----------

* Menu:

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


File: python.info,  Node: API 与特性的移除<3>,  Up: 移除<3>

1.4.10.1 API 与特性的移除
.........................

   * Unknown escapes consisting of ‘'\'’ and an ASCII letter in regular
     expressions will now cause an error.  In replacement templates for
     *note re.sub(): 579. they are still allowed, but deprecated.  The
     *note re.LOCALE: 4cf. flag can now only be used with binary
     patterns.

   * ‘inspect.getmoduleinfo()’ was removed (was deprecated since CPython
     3.3).  *note inspect.getmodulename(): 6e9. should be used for
     obtaining the module name for a given path.  (Contributed by Yury
     Selivanov in bpo-13248(1).)

   * ‘traceback.Ignore’ class and ‘traceback.usage’,
     ‘traceback.modname’, ‘traceback.fullmodname’,
     ‘traceback.find_lines_from_code’, ‘traceback.find_lines’,
     ‘traceback.find_strings’, ‘traceback.find_executable_lines’ methods
     were removed from the *note traceback: 11c. module.  They were
     undocumented methods deprecated since Python 3.2 and equivalent
     functionality is available from private methods.

   * The ‘tk_menuBar()’ and ‘tk_bindForTraversal()’ dummy methods in
     *note tkinter: 10e. widget classes were removed (corresponding Tk
     commands were obsolete since Tk 4.0).

   * The *note open(): 6b3. method of the *note zipfile.ZipFile: 522.
     class no longer supports the ‘'U'’ mode (was deprecated since
     Python 3.4).  Use *note io.TextIOWrapper: 6ea. for reading
     compressed text files in *note universal newlines: 6eb. mode.

   * The undocumented ‘IN’, ‘CDROM’, ‘DLFCN’, ‘TYPES’, ‘CDIO’, and
     ‘STROPTS’ modules have been removed.  They had been available in
     the platform specific ‘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(2).

   * The deprecated ‘asynchat.fifo’ class has been removed.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13248

   (2) https://github.com/python/cpython/tree/3.9/Tools/scripts/h2py.py


File: python.info,  Node: 移植到Python 3 6,  Next: Python 3 6 2 中的重要变化,  Prev: 移除<3>,  Up: Python 3 6 有什么新变化

1.4.11 移植到Python 3.6
-----------------------

本节列出了先前描述的更改以及可能需要更改代码的其他错误修正.

* Menu:

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


File: python.info,  Node: 'python' 命令行为的变化,  Next: Python API 的更改,  Up: 移植到Python 3 6

1.4.11.1 ’python’ 命令行为的变化
................................

   * 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’.
     (Contributed by Serhiy Storchaka in bpo-23034(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23034


File: python.info,  Node: Python API 的更改,  Next: C API 中的改变<3>,  Prev: 'python' 命令行为的变化,  Up: 移植到Python 3 6

1.4.11.2 Python API 的更改
..........................

   * *note open(): 16f. will no longer allow combining the ‘'U'’ mode
     flag with ‘'+'’.  (Contributed by Jeff Balogh and John O’Connor in
     bpo-2091(1).)

   * *note sqlite3: f2. no longer implicitly commits an open transaction
     before DDL statements.

   * On Linux, *note os.urandom(): 5cb. now blocks until the system
     urandom entropy pool is initialized to increase the security.

   * When *note importlib.abc.Loader.exec_module(): 6db. is defined,
     *note importlib.abc.Loader.create_module(): 64e. must also be
     defined.

   * *note PyErr_SetImportError(): 6ef. now sets *note TypeError: 1fe.
     when its `msg' argument is not set.  Previously only ‘NULL’ was
     returned.

   * The format of the ‘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
     ‘frame.f_lineno’, ‘PyFrame_GetLineNumber()’ or ‘PyCode_Addr2Line()’
     are not affected.  Functions directly decoding ‘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 ‘Objects/lnotab_notes.txt’ for the
     ‘co_lnotab’ format and how to decode it, and see the PEP 511(2) for
     the rationale.

   * The functions in the *note compileall: 20. module now return
     booleans instead of ‘1’ or ‘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
     ‘1’ or ‘0’.  See bpo-25768(3).

   * Reading the ‘port’ attribute of *note urllib.parse.urlsplit(): 6f0.
     and *note urlparse(): 6f1. results now raises *note ValueError:
     16d. for out-of-range values, rather than returning *note None:
     203.  See bpo-20059(4).

   * The *note imp: 99. module now raises a *note DeprecationWarning:
     15a. instead of *note PendingDeprecationWarning: 15c.

   * The following modules have had missing APIs added to their
     ‘__all__’ attributes to match the documented APIs: *note calendar:
     14, *note cgi: 15, *note csv: 29, *note ElementTree: 140, *note
     enum: 79, *note fileinput: 7e, *note ftplib: 82, *note logging: aa,
     *note mailbox: ae, *note mimetypes: b2, *note optparse: c3, *note
     plistlib: cf, *note smtpd: ec, *note subprocess: f9, *note tarfile:
     101, *note threading: 10b. and *note wave: 130.  This means they
     will export new symbols when ‘import *’ is used.  (Contributed by
     Joel Taddei and Jacek Kołodziej in bpo-23883(5).)

   * When performing a relative import, if ‘__package__’ does not
     compare equal to ‘__spec__.parent’ then *note ImportWarning: 6cf.
     is raised.  (Contributed by Brett Cannon in bpo-25791(6).)

   * When a relative import is performed and no parent package is known,
     then *note ImportError: 16c. will be raised.  Previously, *note
     SystemError: 6f2. could be raised.  (Contributed by Brett Cannon in
     bpo-18018(7).)

   * Servers based on the *note socketserver: f0. module, including
     those defined in *note http.server: 96, *note xmlrpc.server: 149.
     and *note wsgiref.simple_server: 138, now only catch exceptions
     derived from *note Exception: 2dc.  Therefore if a request handler
     raises an exception like *note SystemExit: 6f3. or *note
     KeyboardInterrupt: 2cc, *note handle_error(): 6f4. is no longer
     called, and the exception will stop a single-threaded server.
     (Contributed by Martin Panter in bpo-23430(8).)

   * *note spwd.getspnam(): 6f5. now raises a *note PermissionError:
     6f6. instead of *note KeyError: 3e9. if the user doesn’t have
     privileges.

   * The *note socket.socket.close(): 6f7. method now raises an
     exception if an error (e.g.  ‘EBADF’) was reported by the
     underlying system call.  (Contributed by Martin Panter in
     bpo-26685(9).)

   * The `decode_data' argument for the *note smtpd.SMTPChannel: 6f8.
     and *note smtpd.SMTPServer: 6f9. constructors is now ‘False’ by
     default.  This means that the argument passed to *note
     process_message(): 6fa. is now a bytes object by default, and
     ‘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.

   * All optional arguments of the *note dump(): 6fb, *note dumps():
     6fc, *note load(): 659. and *note loads(): 225. functions and *note
     JSONEncoder: 6fd. and *note JSONDecoder: 6fe. class constructors in
     the *note json: a4. module are now *note keyword-only: 3ce.
     (Contributed by Serhiy Storchaka in bpo-18726(10).)

   * *note type: 6ff. 的子类如果未重载 ‘type.__new__’，将不再能使用一个
     参数的形式来获取对象的类型。

   * As part of PEP 487(11), the handling of keyword arguments passed to
     *note type: 6ff. (other than the metaclass hint, ‘metaclass’) is
     now consistently delegated to *note object.__init_subclass__():
     5dc.  This means that ‘type.__new__()’ and ‘type.__init__()’ both
     now accept arbitrary keyword arguments, but *note
     object.__init_subclass__(): 5dc. (which is called from
     ‘type.__new__()’) will reject them by default.  Custom metaclasses
     accepting additional keyword arguments will need to adjust their
     calls to ‘type.__new__()’ (whether direct or via *note super: 5dd.)
     accordingly.

   * In ‘distutils.command.sdist.sdist’, the ‘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 ‘setup.cfg’ file containing
     the following:

          [sdist]
          formats=zip

     This behavior has also been backported to earlier Python versions
     by Setuptools 26.0.0.

   * In the *note urllib.request: 129. module and the *note
     http.client.HTTPConnection.request(): 649. 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(12).)

   * The *note DictReader: 2ee. now returns rows of type *note
     OrderedDict: 2ea.  (Contributed by Steve Holden in bpo-27842(13).)

   * The *note crypt.METHOD_CRYPT: 700. will no longer be added to
     ‘crypt.methods’ if unsupported by the platform.  (Contributed by
     Victor Stinner in bpo-25287(14).)

   * The `verbose' and `rename' arguments for *note namedtuple(): 1a1.
     are now keyword-only.  (Contributed by Raymond Hettinger in
     bpo-25628(15).)

   * On Linux, *note ctypes.util.find_library(): 701. now looks in
     ‘LD_LIBRARY_PATH’ for shared libraries.  (Contributed by Vinay
     Sajip in bpo-9998(16).)

   * The *note imaplib.IMAP4: 1af. class now handles flags containing
     the ‘']'’ character in messages sent from the server to improve
     real-world compatibility.  (Contributed by Lita Cho in
     bpo-21815(17).)

   * The ‘mmap.write()’ function now returns the number of bytes written
     like other write methods.  (Contributed by Jakub Stasiak in
     bpo-26335(18).)

   * The *note pkgutil.iter_modules(): 702. and *note
     pkgutil.walk_packages(): 585. functions now return *note
     ModuleInfo: 703. named tuples.  (Contributed by Ramchandra Apte in
     bpo-17211(19).)

   * *note re.sub(): 579. 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(20).)

   * *note zipfile.ZipFile: 522. will now raise *note
     NotImplementedError: 704. for unrecognized compression values.
     Previously a plain *note RuntimeError: 3dc. was raised.
     Additionally, calling *note ZipFile: 522. methods on a closed
     ZipFile or calling the *note write(): 705. method on a ZipFile
     created with mode ‘'r'’ will raise a *note ValueError: 16d.
     Previously, a *note RuntimeError: 3dc. was raised in those
     scenarios.

   * when custom metaclasses are combined with zero-argument *note
     super(): 5dd. or direct references from methods to the implicit
     ‘__class__’ closure variable, the implicit ‘__classcell__’
     namespace entry must now be passed up to ‘type.__new__’ for
     initialisation.  Failing to do so will result in a *note
     DeprecationWarning: 15a. in Python 3.6 and a *note RuntimeError:
     3dc. in Python 3.8.

   * With the introduction of *note ModuleNotFoundError: 4a0, import
     system consumers may start expecting import system replacements to
     raise that more specific exception when appropriate, rather than
     the less-specific *note ImportError: 16c.  To provide future
     compatibility with such consumers, implementors of alternative
     import systems that completely replace *note __import__(): 16b.
     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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue2091

   (2) https://www.python.org/dev/peps/pep-0511

   (3) https://bugs.python.org/issue25768

   (4) https://bugs.python.org/issue20059

   (5) https://bugs.python.org/issue23883

   (6) https://bugs.python.org/issue25791

   (7) https://bugs.python.org/issue18018

   (8) https://bugs.python.org/issue23430

   (9) https://bugs.python.org/issue26685

   (10) https://bugs.python.org/issue18726

   (11) https://www.python.org/dev/peps/pep-0487

   (12) https://bugs.python.org/issue12319

   (13) https://bugs.python.org/issue27842

   (14) https://bugs.python.org/issue25287

   (15) https://bugs.python.org/issue25628

   (16) https://bugs.python.org/issue9998

   (17) https://bugs.python.org/issue21815

   (18) https://bugs.python.org/issue26335

   (19) https://bugs.python.org/issue17211

   (20) https://bugs.python.org/issue25953


File: python.info,  Node: C API 中的改变<3>,  Next: CPython 字节码的改变<4>,  Prev: Python API 的更改,  Up: 移植到Python 3 6

1.4.11.3 C API 中的改变
.......................

   * The *note PyMem_Malloc(): 5fe. allocator family now uses the *note
     pymalloc allocator: 6b8. rather than the system ‘malloc()’.
     Applications calling *note PyMem_Malloc(): 5fe. without holding the
     GIL can now crash.  Set the *note PYTHONMALLOC: 5fc. environment
     variable to ‘debug’ to validate the usage of memory allocators in
     your application.  See bpo-26249(1).

   * *note Py_Exit(): 707. (and the main interpreter) now override the
     exit status with 120 if flushing buffered data failed.  See
     bpo-5319(2).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26249

   (2) https://bugs.python.org/issue5319


File: python.info,  Node: CPython 字节码的改变<4>,  Prev: C API 中的改变<3>,  Up: 移植到Python 3 6

1.4.11.4 CPython 字节码的改变
.............................

There have been several major changes to the *note bytecode: 709. in
Python 3.6.

   * 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(1) and
     bpo-28050(2).)

   * The new *note FORMAT_VALUE: 70a. and *note BUILD_STRING: 70b.
     opcodes as part of the *note formatted string literal: 5bb.
     implementation.  (Contributed by Eric Smith in bpo-25483(3) and
     Serhiy Storchaka in bpo-27078(4).)

   * The new *note BUILD_CONST_KEY_MAP: 70c. opcode to optimize the
     creation of dictionaries with constant keys.  (Contributed by
     Serhiy Storchaka in bpo-27140(5).)

   * The function call opcodes have been heavily reworked for better
     performance and simpler implementation.  The *note MAKE_FUNCTION:
     70d, *note CALL_FUNCTION: 70e, *note CALL_FUNCTION_KW: 70f. and
     ‘BUILD_MAP_UNPACK_WITH_CALL’ opcodes have been modified, the new
     *note CALL_FUNCTION_EX: 710. and ‘BUILD_TUPLE_UNPACK_WITH_CALL’
     have been added, and ‘CALL_FUNCTION_VAR’, ‘CALL_FUNCTION_VAR_KW’
     and ‘MAKE_CLOSURE’ opcodes have been removed.  (Contributed by
     Demur Rumed in bpo-27095(6), and Serhiy Storchaka in bpo-27213(7),
     bpo-28257(8).)

   * The new *note SETUP_ANNOTATIONS: 711. and ‘STORE_ANNOTATION’
     opcodes have been added to support the new *note variable
     annotation: 712. syntax.  (Contributed by Ivan Levkivskyi in
     bpo-27985(9).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26647

   (2) https://bugs.python.org/issue28050

   (3) https://bugs.python.org/issue25483

   (4) https://bugs.python.org/issue27078

   (5) https://bugs.python.org/issue27140

   (6) https://bugs.python.org/issue27095

   (7) https://bugs.python.org/issue27213

   (8) https://bugs.python.org/issue28257

   (9) https://bugs.python.org/issue27985


File: python.info,  Node: Python 3 6 2 中的重要变化,  Next: Python 3 6 4 中的重要变化,  Prev: 移植到Python 3 6,  Up: Python 3 6 有什么新变化

1.4.12 Python 3.6.2 中的重要变化
--------------------------------

* Menu:

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


File: python.info,  Node: New make regen-all build target,  Next: Removal of make touch build target,  Up: Python 3 6 2 中的重要变化

1.4.12.1 New ‘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 ‘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(1) for details.

（由 Victor Stinner 在 bpo-23404(2) 中贡献。）

3.6.2 版新加入.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Makefile.pre.in

   (2) https://bugs.python.org/issue23404


File: python.info,  Node: Removal of make touch build target,  Prev: New make regen-all build target,  Up: Python 3 6 2 中的重要变化

1.4.12.2 Removal of ‘make touch’ build target
.............................................

The ‘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 ‘make regen-all’ target.

（由 Victor Stinner 在 bpo-23404(1) 中贡献。）

3.6.2 版更變.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23404


File: python.info,  Node: Python 3 6 4 中的重要变化,  Next: Python 3 6 5 中的重要变化,  Prev: Python 3 6 2 中的重要变化,  Up: Python 3 6 有什么新变化

1.4.13 Python 3.6.4 中的重要变化
--------------------------------

The ‘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(1) and bpo-30697(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22898

   (2) https://bugs.python.org/issue30697


File: python.info,  Node: Python 3 6 5 中的重要变化,  Next: Python 3 6 7 中的重要变化,  Prev: Python 3 6 4 中的重要变化,  Up: Python 3 6 有什么新变化

1.4.14 Python 3.6.5 中的重要变化
--------------------------------

The *note locale.localeconv(): 584. function now sets temporarily the
‘LC_CTYPE’ locale to the ‘LC_NUMERIC’ locale in some cases.
(Contributed by Victor Stinner in bpo-31900(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31900


File: python.info,  Node: Python 3 6 7 中的重要变化,  Next: Python 3 6 10 中的重要变化,  Prev: Python 3 6 5 中的重要变化,  Up: Python 3 6 有什么新变化

1.4.15 Python 3.6.7 中的重要变化
--------------------------------

In 3.6.7 the *note tokenize: 11a. module now implicitly emits a
‘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(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33899


File: python.info,  Node: Python 3 6 10 中的重要变化,  Next: Notable changes in Python 3 6 13,  Prev: Python 3 6 7 中的重要变化,  Up: Python 3 6 有什么新变化

1.4.16 Python 3.6.10 中的重要变化
---------------------------------

出于重要的安全性考量，*note asyncio.loop.create_datagram_endpoint():
189. 的 `reuse_address' 形参不再被支持。 这是由 UDP 中的套接字选项
‘SO_REUSEADDR’ 的行为导致的。 更多细节请参阅
‘loop.create_datagram_endpoint()’ 的文档。 （由 Kyle Stanley, Antoine
Pitrou 和 Yury Selivanov 在 bpo-37228(1) 中贡献。。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37228


File: python.info,  Node: Notable changes in Python 3 6 13,  Prev: Python 3 6 10 中的重要变化,  Up: Python 3 6 有什么新变化

1.4.17 Notable changes in Python 3.6.13
---------------------------------------

早先的 Python 版本允许使用 ‘;’ 和 ‘&’ 作为 *note
urllib.parse.parse_qs(): 27f. 和 *note urllib.parse.parse_qsl(): 280. 中
query 形参的分隔键。 出于安全考虑，也为了遵循更新的 W3C 推荐设置，这已被
改为只允许单个分隔键，默认为 ‘&’。 这一改变还会影响 *note cgi.parse():
281. 和 *note cgi.parse_multipart(): 282. 因为它们在内部使用了受影响的函
数。 要了解更多细节，请查看它们各自的文档。 （由 Adam Goldschmidt,
Senthil Kumaran 和 Ken Jin 在 bpo-42967(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42967


File: python.info,  Node: Python 3 5 有什麼新功能,  Next: Python 3 4 有什么新变化,  Prev: Python 3 6 有什么新变化,  Up: Python 有什麼新功能？

1.5 Python 3.5 有什麼新功能
===========================


编者: Elvis Pranskevichus <<elvis@magic.io>>, Yury Selivanov
<<yury@magic.io>>

This article explains the new features in Python 3.5, compared to 3.4.
Python 3.5 was released on September 13, 2015.   See the changelog(1)
for a full list of changes.

也參考
......

PEP 478(2) - 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 的显著变化.

   ---------- Footnotes ----------

   (1) https://docs.python.org/3.5/whatsnew/changelog.html

   (2) https://www.python.org/dev/peps/pep-0478


File: python.info,  Node: 摘要 - 发布重点<5>,  Next: 新的特性<6>,  Up: Python 3 5 有什麼新功能

1.5.1 摘要 - 发布重点
---------------------

新的语法特性：

   * *note PEP 492: 71e, 使用 async 和 await 语法实现协程。

   * *note PEP 465: 71f, 新的矩阵乘法运算符: ‘a @ b’.

   * *note PEP 448: 720, additional unpacking generalizations.

新的库模块：

   * *note typing: 122.: *note PEP 484 – 类型提示: 721.

   * *note zipapp: 14a.: *note PEP 441 改进Python ZIP应用程序支持: 722.

新的内置特性：

   * ‘bytes % args’, ‘bytearray % args’: *note PEP 461: 723. – Adding
     ‘%’ formatting to bytes and bytearray.

   * New *note bytes.hex(): 724, *note bytearray.hex(): 725. and *note
     memoryview.hex(): 726. methods.  (Contributed by Arnon Yaari in
     bpo-9951(1).)

   * *note memoryview: 386. now supports tuple indexing (including
     multi-dimensional).  (Contributed by Antoine Pitrou in
     bpo-23632(2).)

   * Generators have a new ‘gi_yieldfrom’ attribute, which returns the
     object being iterated by ‘yield from’ expressions.  (Contributed by
     Benno Leslie and Yury Selivanov in bpo-24450(3).)

   * A new *note RecursionError: 727. exception is now raised when
     maximum recursion depth is reached.  (Contributed by Georg Brandl
     in bpo-19235(4).)

CPython 实现的改进：

   * When the ‘LC_TYPE’ locale is the POSIX locale (‘C’ locale), *note
     sys.stdin: 41e. and *note sys.stdout: 41f. now use the
     ‘surrogateescape’ error handler, instead of the ‘strict’ error
     handler.  (Contributed by Victor Stinner in bpo-19977(5).)

   * ‘.pyo’ files are no longer used and have been replaced by a more
     flexible scheme that includes the optimization level explicitly in
     ‘.pyc’ name.  (See *note PEP 488 overview: 728.)

   * Builtin and extension modules are now initialized in a multi-phase
     process, which is similar to how Python modules are loaded.  (See
     *note PEP 489 overview: 729.)

标准库中的重大改进：

   * *note collections.OrderedDict: 2ea. is now *note implemented in C:
     72a, which makes it 4 to 100 times faster.

   * The *note ssl: f3. module gained *note support for Memory BIO: 72b,
     which decouples SSL protocol handling from network IO.

   * The new *note os.scandir(): 389. function provides a *note better
     and significantly faster way: 72c. of directory traversal.

   * *note functools.lru_cache(): 2f8. has been mostly *note
     reimplemented in C: 72d, yielding much better performance.

   * The new *note subprocess.run(): 4f2. function provides a *note
     streamlined way to run subprocesses: 72e.

   * The *note traceback: 11c. module has been significantly *note
     enhanced: 72f. for improved performance and developer convenience.

安全改进：

   * SSLv3 is now disabled throughout the standard library.  It can
     still be enabled by instantiating a *note ssl.SSLContext: 4e9.
     manually.  (See bpo-22638(6) for more details; this change was
     backported to CPython 3.4 and 2.7.)

   * HTTP cookie parsing is now stricter, in order to protect against
     potential injection attacks.  (Contributed by Antoine Pitrou in
     bpo-22796(7).)

Windows改进：

   * A new installer for Windows has replaced the old MSI. See *note 在
     Windows 上使用 Python: 3f8. for more information.

   * Windows builds now use Microsoft Visual C++ 14.0, and extension
     modules should use the same.

Please read on for a comprehensive list of user-facing changes,
including many other smaller improvements, CPython optimizations,
deprecations, and potential porting issues.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue9951

   (2) https://bugs.python.org/issue23632

   (3) https://bugs.python.org/issue24450

   (4) https://bugs.python.org/issue19235

   (5) https://bugs.python.org/issue19977

   (6) https://bugs.python.org/issue22638

   (7) https://bugs.python.org/issue22796


File: python.info,  Node: 新的特性<6>,  Next: 其他语言特性修改<5>,  Prev: 摘要 - 发布重点<5>,  Up: Python 3 5 有什麼新功能

1.5.2 新的特性
--------------

* 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.


File: python.info,  Node: PEP 492 - 使用 async 和 await 语法实现协程,  Next: PEP 465 - 用于矩阵乘法的专用中缀运算符,  Up: 新的特性<6>

1.5.2.1 PEP 492 - 使用 async 和 await 语法实现协程
..................................................

PEP 492(1) greatly improves support for asynchronous programming in
Python by adding *note awaitable objects: 612, *note coroutine
functions: 732, *note asynchronous iteration: 733, and *note
asynchronous context managers: 734.

Coroutine functions are declared using the new *note async def: 3a9.
syntax:

     >>> async def coro():
     ...     return 'spam'

Inside a coroutine function, the new *note await: 2d8. expression can be
used to suspend coroutine execution until the result is available.  Any
object can be `awaited', as long as it implements the *note awaitable:
612. protocol by defining the *note __await__(): 735. method.

PEP 492 also adds *note async for: 3fd. statement for convenient
iteration over asynchronous iterables.

An example of a rudimentary HTTP client written using the new syntax:

     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'', b''
         ]))

         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()

Similarly to asynchronous iteration, there is a new syntax for
asynchronous context managers.  The following script:

     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()

将输出：

     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

Note that both *note async for: 3fd. and *note async with: 736. can only
be used inside a coroutine function declared with *note async def: 3a9.

Coroutine functions are intended to be run inside a compatible event
loop, such as the *note asyncio loop: 737.

     備註: 
     3.5.2 版更變: Starting with CPython 3.5.2, ‘__aiter__’ can directly
     return *note asynchronous iterators: 738.  Returning an *note
     awaitable: 612. object will result in a *note
     PendingDeprecationWarning: 15c.

     See more details in the *note 异步迭代器: 739. documentation
     section.

也參考
......

PEP 492(2) – 使用 async 和 await 语法实现协程

     PEP 由 Yury Selivanov 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0492

   (2) https://www.python.org/dev/peps/pep-0492


File: python.info,  Node: PEP 465 - 用于矩阵乘法的专用中缀运算符,  Next: PEP 448 - Additional Unpacking Generalizations,  Prev: PEP 492 - 使用 async 和 await 语法实现协程,  Up: 新的特性<6>

1.5.2.2 PEP 465 - 用于矩阵乘法的专用中缀运算符
..............................................

PEP 465(1) adds the ‘@’ infix operator for matrix multiplication.
Currently, no builtin Python types implement the new operator, however,
it can be implemented by defining *note __matmul__(): 73b, *note
__rmatmul__(): 73c, and *note __imatmul__(): 73d. for regular,
reflected, and in-place matrix multiplication.  The semantics of these
methods is similar to that of methods defining other infix arithmetic
operators.

矩阵乘法在数学，科学，工程学的许多领域中是一种常见的操作，使用 ‘@’ 运算
符可以编写更简洁的代码：

     S = (H @ beta - r).T @ inv(H @ V @ H.T) @ (H @ beta - r)

代替：

     S = dot((dot(H, beta) - r).T,
             dot(inv(dot(dot(H, V), H.T)), dot(H, beta) - r))

NumPy 1.10 支持新的运算符：

     >>> 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.])

也參考
......

PEP 465(2) – 用于矩阵乘法的专用中缀运算符

     PEP 由 Nathaniel J. Smith 撰写，由 Benjamin Peterson 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0465

   (2) https://www.python.org/dev/peps/pep-0465


File: python.info,  Node: PEP 448 - Additional Unpacking Generalizations,  Next: PEP 461 - percent formatting support for bytes and bytearray,  Prev: PEP 465 - 用于矩阵乘法的专用中缀运算符,  Up: 新的特性<6>

1.5.2.3 PEP 448 - Additional Unpacking Generalizations
......................................................

PEP 448(1) extends the allowed uses of the ‘*’ iterable unpacking
operator and ‘**’ dictionary unpacking operator.  It is now possible to
use an arbitrary number of unpackings in *note function calls: 73f.:

     >>> 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

Similarly, tuple, list, set, and dictionary displays allow multiple
unpackings (see *note 表达式列表: 740. and *note 字典显示: 741.):

     >>> *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}

也參考
......

PEP 448(2) – Additional Unpacking Generalizations

     PEP 由 Joshua Landau 撰写 ，由 Neil Girdhar，Thomas Wouters 和
     Joshua Landau 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0448

   (2) https://www.python.org/dev/peps/pep-0448


File: python.info,  Node: PEP 461 - percent formatting support for bytes and bytearray,  Next: PEP 484 - 类型提示,  Prev: PEP 448 - Additional Unpacking Generalizations,  Up: 新的特性<6>

1.5.2.4 PEP 461 - percent formatting support for bytes and bytearray
....................................................................

PEP 461(1) adds support for the ‘%’ *note interpolation operator: 743.
to *note bytes: 172. and *note bytearray: 173.

While interpolation is usually thought of as a string operation, there
are cases where interpolation on ‘bytes’ or ‘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.

例如:

     >>> b'Hello %b!' % b'World'
     b'Hello World!'

     >>> b'x=%i y=%f' % (1, 2.5)
     b'x=1 y=2.500000'

Unicode is not allowed for ‘%b’, but it is accepted by ‘%a’ (equivalent
of ‘repr(obj).encode('ascii', 'backslashreplace')’):

     >>> 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'"

Note that ‘%s’ and ‘%r’ conversion types, although supported, should
only be used in codebases that need compatibility with Python 2.

也參考
......

PEP 461(2) – Adding % formatting to bytes and bytearray

     PEP 由 Ethan Furman 撰写 ，由 Neil Schemenauer 和 Ethan Furman 实现
     。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0461

   (2) https://www.python.org/dev/peps/pep-0461


File: python.info,  Node: PEP 484 - 类型提示,  Next: PEP 471 - os scandir function -- a better and faster directory iterator,  Prev: PEP 461 - percent formatting support for bytes and bytearray,  Up: 新的特性<6>

1.5.2.5 PEP 484 - 类型提示
..........................

Function annotation syntax has been a Python feature since version 3.0 (
PEP 3107(1)), 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.

PEP 484(2) introduces a *note provisional module: 454. 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:

     def greeting(name: str) -> str:
         return 'Hello ' + name

While these annotations are available at runtime through the usual
‘__annotations__’ attribute, `no automatic type checking happens at
runtime'.  Instead, it is assumed that a separate off-line type checker
(e.g.  mypy(3)) will be used for on-demand source code analysis.

The type system supports unions, generic types, and a special type named
*note Any: 745. which is consistent with (i.e.  assignable to and from)
all types.

也參考
......

   * *note typing: 122. 模块文档

   * 
     PEP 484(4) – 类型提示

          PEP 由 Guido van Rossum，Jukka Lehtosalo 和 Łukasz Langa 撰写
          ，由 Guido van Rossum 实现。

   * 
     PEP 483(5) – 类型提示理论

          PEP 由 Yury Selivanov 撰写

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3107

   (2) https://www.python.org/dev/peps/pep-0484

   (3) http://mypy-lang.org

   (4) https://www.python.org/dev/peps/pep-0484

   (5) https://www.python.org/dev/peps/pep-0483


File: python.info,  Node: PEP 471 - os scandir function -- a better and faster directory iterator,  Next: PEP 475 Retry system calls failing with EINTR,  Prev: PEP 484 - 类型提示,  Up: 新的特性<6>

1.5.2.6 PEP 471 - os.scandir() function – a better and faster directory iterator
................................................................................

PEP 471(1) adds a new directory iteration function, *note os.scandir():
389, to the standard library.  Additionally, *note os.walk(): 747. is
now implemented using ‘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 *note
os.stat(): 321. required to walk a directory tree.

Additionally, ‘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 *note os.scandir(): 389. to
display all the files (excluding directories) in the given `path' that
don’t start with ‘'.'’.  The *note entry.is_file(): 748. call will
generally not make an additional system call:

     for entry in os.scandir(path):
         if not entry.name.startswith('.') and entry.is_file():
             print(entry.name)

也參考
......

PEP 471(2) – os.scandir() function – a better and faster directory iterator

     PEP 由 Ben Hoyt 在 Victor Stinner 的帮助下撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0471

   (2) https://www.python.org/dev/peps/pep-0471


File: python.info,  Node: PEP 475 Retry system calls failing with EINTR,  Next: PEP 479 Change StopIteration handling inside generators,  Prev: PEP 471 - os scandir function -- a better and faster directory iterator,  Up: 新的特性<6>

1.5.2.7 PEP 475: Retry system calls failing with EINTR
......................................................

An *note errno.EINTR: 74b. error code is returned whenever a system
call, that is waiting for I/O, is interrupted by a signal.  Previously,
Python would raise *note InterruptedError: 74c. in such cases.  This
meant that, when writing a Python application, the developer had two
choices:

  1. Ignore the ‘InterruptedError’.

  2. Handle the ‘InterruptedError’ and attempt to restart the
     interrupted system call at every call site.

The first option makes an application fail intermittently.  The second
option adds a large amount of boilerplate that makes the code nearly
unreadable.  Compare:

     print("Hello World")

和:

     while True:
         try:
             print("Hello World")
             break
         except InterruptedError:
             continue

PEP 475(1) implements automatic retry of system calls on ‘EINTR’.  This
removes the burden of dealing with ‘EINTR’ or *note InterruptedError:
74c. 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:

   * *note open(): 16f. 和 *note io.open(): 74d.;

   * *note faulthandler: 7b. 模块的功能

   * *note os: c4. 函数: *note fchdir(): 74e, *note fchmod(): 74f, *note
     fchown(): 750, *note fdatasync(): 751, *note fstat(): 752, *note
     fstatvfs(): 753, *note fsync(): 754, *note ftruncate(): 755, *note
     mkfifo(): 756, *note mknod(): 757, *note open(): 758, *note
     posix_fadvise(): 759, *note posix_fallocate(): 75a, *note pread():
     4bf, *note pwrite(): 4c2, *note read(): 75b, *note readv(): 4be,
     *note sendfile(): 461, *note wait3(): 75c, *note wait4(): 75d,
     *note wait(): 75e, *note waitid(): 75f, *note waitpid(): 760, *note
     write(): 761, *note writev(): 4c1.;

   * 特例: *note os.close(): 4d8. 和 *note os.dup2(): 4c4. 现在会忽略
     *note EINTR: 74b. 错误; 不重试系统调用（请参阅PEP了解基本原理）

   * *note select: e5. 函数: *note devpoll.poll(): 762, *note
     epoll.poll(): 763, *note kqueue.control(): 764, *note poll.poll():
     765, *note select(): 766.;

   * *note socket: 767. 类的方法: *note accept(): 768, *note connect():
     769. （除了非阻塞套接字）, *note recv(): 76a, *note recvfrom():
     76b, *note recvmsg(): 76c, *note send(): 76d, *note sendall(): 76e,
     *note sendmsg(): 76f, *note sendto(): 770.;

   * *note signal.sigtimedwait(): 771. 和 *note signal.sigwaitinfo():
     772.;

   * *note time.sleep(): 773.

也參考
......

PEP 475(2) – 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).

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0475

   (2) https://www.python.org/dev/peps/pep-0475


File: python.info,  Node: PEP 479 Change StopIteration handling inside generators,  Next: PEP 485 A function for testing approximate equality,  Prev: PEP 475 Retry system calls failing with EINTR,  Up: 新的特性<6>

1.5.2.8 PEP 479: Change StopIteration handling inside generators
................................................................

The interaction of generators and *note StopIteration: 581. in Python
3.4 and earlier was sometimes surprising, and could conceal obscure
bugs.  Previously, ‘StopIteration’ raised accidentally inside a
generator function was interpreted as the end of the iteration by the
loop construct driving the generator.

PEP 479(1) changes the behavior of generators: when a ‘StopIteration’
exception is raised inside a generator, it is replaced with a *note
RuntimeError: 3dc. before it exits the generator frame.  The main goal
of this change is to ease debugging in the situation where an unguarded
*note next(): 775. call raises ‘StopIteration’ and causes the iteration
controlled by the generator to terminate silently.  This is particularly
pernicious in combination with the ‘yield from’ construct.

This is a backwards incompatible change, so to enable the new behavior,
a *note __future__: 776. import is necessary:

     >>> 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

Without a ‘__future__’ import, a *note PendingDeprecationWarning: 15c.
will be raised whenever a *note StopIteration: 581. exception is raised
inside a generator.

也參考
......

PEP 479(2) – Change StopIteration handling inside generators

     PEP 由 Chris Angelico 和 Guido van Rossum 撰写，由 Chris Angelico，
     Yury Selivanov 和 Nick Coghlan 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0479

   (2) https://www.python.org/dev/peps/pep-0479


File: python.info,  Node: PEP 485 A function for testing approximate equality,  Next: PEP 486 Make the Python Launcher aware of virtual environments,  Prev: PEP 479 Change StopIteration handling inside generators,  Up: 新的特性<6>

1.5.2.9 PEP 485: A function for testing approximate equality
............................................................

PEP 485(1) adds the *note math.isclose(): 779. and *note
cmath.isclose(): 77a. 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 ‘isclose’ arguments, relative to the larger absolute
value:

     >>> 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

It is also possible to compare two values using absolute tolerance,
which must be a non-negative value:

     >>> 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

也參考
......

PEP 485(2) —— 用于测试近似相等的函数

     PEP 由 Christopher Barker 撰写，由 Chris Barker 和 Tal Einat 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0485

   (2) https://www.python.org/dev/peps/pep-0485


File: python.info,  Node: PEP 486 Make the Python Launcher aware of virtual environments,  Next: PEP 488 Elimination of PYO files,  Prev: PEP 485 A function for testing approximate equality,  Up: 新的特性<6>

1.5.2.10 PEP 486: Make the Python Launcher aware of virtual environments
........................................................................

PEP 486(1) makes the Windows launcher (see PEP 397(2)) aware of an
active virtual environment.  When the default interpreter would be used
and the ‘VIRTUAL_ENV’ environment variable is set, the interpreter in
the virtual environment will be used.

也參考
......

PEP 486(3) – Make the Python Launcher aware of virtual environments

     PEP 由 Paul Moore 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0486

   (2) https://www.python.org/dev/peps/pep-0397

   (3) https://www.python.org/dev/peps/pep-0486


File: python.info,  Node: PEP 488 Elimination of PYO files,  Next: PEP 489 Multi-phase extension module initialization,  Prev: PEP 486 Make the Python Launcher aware of virtual environments,  Up: 新的特性<6>

1.5.2.11 PEP 488: Elimination of PYO files
..........................................

PEP 488(1) does away with the concept of ‘.pyo’ files.  This means that
‘.pyc’ files represent both unoptimized and optimized bytecode.  To
prevent the need to constantly regenerate bytecode files, ‘.pyc’ files
now have an optional ‘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 *note -O: 77e. or *note -OO: 77f.
Consequently, bytecode files generated from *note -O: 77e, and *note
-OO: 77f. may now exist simultaneously.  *note
importlib.util.cache_from_source(): 651. has an updated API to help with
this change.

也參考
......

PEP 488(2) – Elimination of PYO files

     PEP 由 Brett Cannon 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0488

   (2) https://www.python.org/dev/peps/pep-0488


File: python.info,  Node: PEP 489 Multi-phase extension module initialization,  Prev: PEP 488 Elimination of PYO files,  Up: 新的特性<6>

1.5.2.12 PEP 489: Multi-phase extension module initialization
.............................................................

PEP 489(1) updates extension module initialization to take advantage of
the two step module loading mechanism introduced by PEP 451(2) 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.

也參考
......

PEP 489(3) – Multi-phase extension module initialization

     PEP 由 Petr Viktorin , Stefan Behnel 和 Nick Coghlan 撰写，由 Petr
     Viktorin 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0489

   (2) https://www.python.org/dev/peps/pep-0451

   (3) https://www.python.org/dev/peps/pep-0489


File: python.info,  Node: 其他语言特性修改<5>,  Next: 新增模块<5>,  Prev: 新的特性<6>,  Up: Python 3 5 有什麼新功能

1.5.3 其他语言特性修改
----------------------

对Python 语言核心进行的小改动：

   * Added the ‘"namereplace"’ error handlers.  The ‘"backslashreplace"’
     error handlers now work with decoding and translating.
     (Contributed by Serhiy Storchaka in bpo-19676(1) and bpo-22286(2).)

   * The *note -b: 519. option now affects comparisons of *note bytes:
     172. with *note int: 204.  (Contributed by Serhiy Storchaka in
     bpo-23681(3).)

   * New Kazakh ‘kz1048’ and Tajik ‘koi8_t’ *note codecs: 782.
     (Contributed by Serhiy Storchaka in bpo-22682(4) and bpo-22681(5).)

   * Property docstrings are now writable.  This is especially useful
     for *note collections.namedtuple(): 1a1. docstrings.  (Contributed
     by Berker Peksag in bpo-24064(6).)

   * Circular imports involving relative imports are now supported.
     (Contributed by Brett Cannon and Antoine Pitrou in bpo-17636(7).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue19676

   (2) https://bugs.python.org/issue22286

   (3) https://bugs.python.org/issue23681

   (4) https://bugs.python.org/issue22682

   (5) https://bugs.python.org/issue22681

   (6) https://bugs.python.org/issue24064

   (7) https://bugs.python.org/issue17636


File: python.info,  Node: 新增模块<5>,  Next: 改进的模块<5>,  Prev: 其他语言特性修改<5>,  Up: Python 3 5 有什麼新功能

1.5.4 新增模块
--------------

* Menu:

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


File: python.info,  Node: typing<5>,  Next: zipapp<2>,  Up: 新增模块<5>

1.5.4.1 typing
..............

The new *note typing: 122. *note provisional: 454. module provides
standard definitions and tools for function type annotations.  See *note
Type Hints: 721. for more information.


File: python.info,  Node: zipapp<2>,  Prev: typing<5>,  Up: 新增模块<5>

1.5.4.2 zipapp
..............

The new *note zipapp: 14a. module (specified in PEP 441(1)) provides an
API and command line tool for creating executable Python Zip
Applications, which were introduced in Python 2.6 in bpo-1739468(2), 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 ‘__main__.py’ file, into a directory ‘myapp’
and running:

     $ python -m zipapp myapp
     $ python myapp.pyz

The module implementation has been contributed by Paul Moore in
bpo-23491(3).

也參考
......

PEP 441(4) – Improving Python ZIP Application Support

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0441

   (2) https://bugs.python.org/issue1739468

   (3) https://bugs.python.org/issue23491

   (4) https://www.python.org/dev/peps/pep-0441


File: python.info,  Node: 改进的模块<5>,  Next: 其他模块级更改,  Prev: 新增模块<5>,  Up: Python 3 5 有什麼新功能

1.5.5 改进的模块
----------------

* 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<2>.
* 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>.


File: python.info,  Node: argparse<2>,  Next: asyncio<6>,  Up: 改进的模块<5>

1.5.5.1 argparse
................

The *note ArgumentParser: 788. class now allows disabling *note
abbreviated usage: 789. of long options by setting *note allow_abbrev:
78a. to ‘False’.  (Contributed by Jonathan Paugh, Steven Bethard, paul
j3 and Daniel Eriksson in bpo-14910(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue14910


File: python.info,  Node: asyncio<6>,  Next: bz2,  Prev: argparse<2>,  Up: 改进的模块<5>

1.5.5.2 asyncio
...............

Since the *note asyncio: 9. module is *note provisional: 454, all
changes introduced in Python 3.5 have also been backported to Python
3.4.x.

Notable changes in the *note asyncio: 9. module since Python 3.4.0:

   * New debugging APIs: *note loop.set_debug(): 78c. and *note
     loop.get_debug(): 78d. methods.  (Contributed by Victor Stinner.)

   * The proactor event loop now supports SSL. (Contributed by Antoine
     Pitrou and Victor Stinner in bpo-22560(1).)

   * A new *note loop.is_closed(): 78e. method to check if the event
     loop is closed.  (Contributed by Victor Stinner in bpo-21326(2).)

   * A new *note loop.create_task(): 2e2. to conveniently create and
     schedule a new *note Task: 2e0. for a coroutine.  The ‘create_task’
     method is also used by all asyncio functions that wrap coroutines
     into tasks, such as *note asyncio.wait(): 207, *note
     asyncio.gather(): 3ab, etc.  (Contributed by Victor Stinner.)

   * A new *note transport.get_write_buffer_limits(): 78f. method to
     inquire for `high-' and `low-' water limits of the flow control.
     (Contributed by Victor Stinner.)

   * The ‘async()’ function is deprecated in favor of *note
     ensure_future(): 610.  (Contributed by Yury Selivanov.)

   * New *note loop.set_task_factory(): 790. and *note
     loop.get_task_factory(): 791. methods to customize the task factory
     that *note loop.create_task(): 2e2. method uses.  (Contributed by
     Yury Selivanov.)

   * New *note Queue.join(): 792. and *note Queue.task_done(): 793.
     queue methods.  (Contributed by Victor Stinner.)

   * The ‘JoinableQueue’ class was removed, in favor of the *note
     asyncio.Queue: 3b3. class.  (Contributed by Victor Stinner.)

3.5.1 中的更新：

   * The *note ensure_future(): 610. function and all functions that use
     it, such as *note loop.run_until_complete(): 611, now accept all
     kinds of *note awaitable objects: 612.  (Contributed by Yury
     Selivanov.)

   * New *note run_coroutine_threadsafe(): 613. function to submit
     coroutines to event loops from other threads.  (Contributed by
     Vincent Michel.)

   * New *note Transport.is_closing(): 614. method to check if the
     transport is closing or closed.  (Contributed by Yury Selivanov.)

   * The *note loop.create_server(): 465. method can now accept a list
     of hosts.  (Contributed by Yann Sionneau.)

3.5.2 中的更新：

   * New *note loop.create_future(): 615. method to create Future
     objects.  This allows alternative event loop implementations, such
     as uvloop(3), to provide a faster *note asyncio.Future: 545.
     implementation.  (Contributed by Yury Selivanov.)

   * New *note loop.get_exception_handler(): 616. method to get the
     current exception handler.  (Contributed by Yury Selivanov.)

   * New *note StreamReader.readuntil(): 617. method to read data from
     the stream until a separator bytes sequence appears.  (Contributed
     by Mark Korenberg.)

   * The *note loop.create_connection(): 2e5. and *note
     loop.create_server(): 465. methods are optimized to avoid calling
     the system ‘getaddrinfo’ function if the address is already
     resolved.  (Contributed by A. Jesse Jiryu Davis.)

   * The *note loop.sock_connect(sock, address): 794. no longer requires
     the `address' to be resolved prior to the call.  (Contributed by A.
     Jesse Jiryu Davis.)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22560

   (2) https://bugs.python.org/issue21326

   (3) https://github.com/MagicStack/uvloop


File: python.info,  Node: bz2,  Next: cgi,  Prev: asyncio<6>,  Up: 改进的模块<5>

1.5.5.3 bz2
...........

The *note BZ2Decompressor.decompress: 796. method now accepts an
optional `max_length' argument to limit the maximum size of decompressed
data.  (Contributed by Nikolaus Rath in bpo-15955(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15955


File: python.info,  Node: cgi,  Next: cmath<2>,  Prev: bz2,  Up: 改进的模块<5>

1.5.5.4 cgi
...........

The ‘FieldStorage’ class now supports the *note context manager: 661.
protocol.  (Contributed by Berker Peksag in bpo-20289(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20289


File: python.info,  Node: cmath<2>,  Next: code,  Prev: cgi,  Up: 改进的模块<5>

1.5.5.5 cmath
.............

A new function *note isclose(): 77a. provides a way to test for
approximate equality.  (Contributed by Chris Barker and Tal Einat in
bpo-24270(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24270


File: python.info,  Node: code,  Next: collections<5>,  Prev: cmath<2>,  Up: 改进的模块<5>

1.5.5.6 code
............

The *note InteractiveInterpreter.showtraceback(): 79a. method now prints
the full chained traceback, just like the interactive interpreter.
(Contributed by Claudiu Popa in bpo-17442(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17442


File: python.info,  Node: collections<5>,  Next: collections abc<2>,  Prev: code,  Up: 改进的模块<5>

1.5.5.7 collections
...................

The *note OrderedDict: 2ea. class is now implemented in C, which makes
it 4 to 100 times faster.  (Contributed by Eric Snow in bpo-16991(1).)

‘OrderedDict.items()’, ‘OrderedDict.keys()’, ‘OrderedDict.values()’
views now support *note reversed(): 2c6. iteration.  (Contributed by
Serhiy Storchaka in bpo-19505(2).)

The *note deque: 62a. class now defines *note index(): 79c, *note
insert(): 79d, and *note copy(): 79e, and supports the ‘+’ and ‘*’
operators.  This allows deques to be recognized as a *note
MutableSequence: 79f. and improves their substitutability for lists.
(Contributed by Raymond Hettinger in bpo-23704(3).)

Docstrings produced by *note namedtuple(): 1a1. can now be updated:

     Point = namedtuple('Point', ['x', 'y'])
     Point.__doc__ += ': Cartesian coodinate'
     Point.x.__doc__ = 'abscissa'
     Point.y.__doc__ = 'ordinate'

（由 Berker Peksag 在 bpo-24064(4) 中贡献。）

The *note UserString: 7a0. class now implements the *note
__getnewargs__(): 7a1, *note __rmod__(): 7a2, *note casefold(): 7a3,
*note format_map(): 7a4, *note isprintable(): 7a5, and *note
maketrans(): 7a6. methods to match the corresponding methods of *note
str: 205.  (Contributed by Joe Jevnik in bpo-22189(5).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16991

   (2) https://bugs.python.org/issue19505

   (3) https://bugs.python.org/issue23704

   (4) https://bugs.python.org/issue24064

   (5) https://bugs.python.org/issue22189


File: python.info,  Node: collections abc<2>,  Next: compileall<3>,  Prev: collections<5>,  Up: 改进的模块<5>

1.5.5.8 collections.abc
.......................

The ‘Sequence.index()’ method now accepts `start' and `stop' arguments
to match the corresponding methods of *note tuple: 1a2, *note list: 1f8,
etc.  (Contributed by Devin Jeanpierre in bpo-23086(1).)

A new *note Generator: 7a8. abstract base class.  (Contributed by Stefan
Behnel in bpo-24018(2).)

New *note Awaitable: 7a9, *note Coroutine: 7aa, *note AsyncIterator:
7ab, and *note AsyncIterable: 7ac. abstract base classes.  (Contributed
by Yury Selivanov in bpo-24184(3).)

For earlier Python versions, a backport of the new ABCs is available in
an external PyPI package(4).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23086

   (2) https://bugs.python.org/issue24018

   (3) https://bugs.python.org/issue24184

   (4) https://pypi.org/project/backports_abc


File: python.info,  Node: compileall<3>,  Next: concurrent futures<4>,  Prev: collections abc<2>,  Up: 改进的模块<5>

1.5.5.9 compileall
..................

A new *note compileall: 20. option, ‘-j `N'’, allows running `N' workers
simultaneously to perform parallel bytecode compilation.  The *note
compile_dir(): 47a. function has a corresponding ‘workers’ parameter.
(Contributed by Claudiu Popa in bpo-16104(1).)

Another new option, ‘-r’, allows controlling the maximum recursion level
for subdirectories.  (Contributed by Claudiu Popa in bpo-19628(2).)

The ‘-q’ command line option can now be specified more than once, in
which case all output, including errors, will be suppressed.  The
corresponding ‘quiet’ parameter in *note compile_dir(): 47a, *note
compile_file(): 7ae, and *note compile_path(): 7af. can now accept an
integer value indicating the level of output suppression.  (Contributed
by Thomas Kluyver in bpo-21338(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16104

   (2) https://bugs.python.org/issue19628

   (3) https://bugs.python.org/issue21338


File: python.info,  Node: concurrent futures<4>,  Next: configparser,  Prev: compileall<3>,  Up: 改进的模块<5>

1.5.5.10 concurrent.futures
...........................

The *note Executor.map(): 7b1. method now accepts a `chunksize' argument
to allow batching of tasks to improve performance when *note
ProcessPoolExecutor(): 196. is used.  (Contributed by Dan O’Reilly in
bpo-11271(1).)

The number of workers in the *note ThreadPoolExecutor: 18c. constructor
is optional now.  The default value is 5 times the number of CPUs.
(Contributed by Claudiu Popa in bpo-21527(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue11271

   (2) https://bugs.python.org/issue21527


File: python.info,  Node: configparser,  Next: contextlib<3>,  Prev: concurrent futures<4>,  Up: 改进的模块<5>

1.5.5.11 configparser
.....................

*note configparser: 22. now provides a way to customize the conversion
of values by specifying a dictionary of converters in the *note
ConfigParser: 5a4. constructor, or by defining them as methods in
‘ConfigParser’ subclasses.  Converters defined in a parser instance are
inherited by its section proxies.

示例:

     >>> 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']

（由 Łukasz Langa 在 bpo-18159(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18159


File: python.info,  Node: contextlib<3>,  Next: csv<2>,  Prev: configparser,  Up: 改进的模块<5>

1.5.5.12 contextlib
...................

The new *note redirect_stderr(): 7b4. *note context manager: 661.
(similar to *note redirect_stdout(): 7b5.) makes it easier for utility
scripts to handle inflexible APIs that write their output to *note
sys.stderr: 1ea. and don’t provide any options to redirect it:

     >>> import contextlib, io, logging
     >>> f = io.StringIO()
     >>> with contextlib.redirect_stderr(f):
     ...     logging.warning('warning')
     ...
     >>> f.getvalue()
     'WARNING:root:warning\n'

（由 Berker Peksag 在 bpo-22389(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22389


File: python.info,  Node: csv<2>,  Next: curses<3>,  Prev: contextlib<3>,  Up: 改进的模块<5>

1.5.5.13 csv
............

The *note writerow(): 7b7. method now supports arbitrary iterables, not
just sequences.  (Contributed by Serhiy Storchaka in bpo-23171(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23171


File: python.info,  Node: curses<3>,  Next: dbm<4>,  Prev: csv<2>,  Up: 改进的模块<5>

1.5.5.14 curses
...............

The new *note update_lines_cols(): 7b9. function updates the ‘LINES’ and
‘COLS’ environment variables.  This is useful for detecting manual
screen resizing.  (Contributed by Arnon Yaari in bpo-4254(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue4254


File: python.info,  Node: dbm<4>,  Next: difflib,  Prev: curses<3>,  Up: 改进的模块<5>

1.5.5.15 dbm
............

*note dumb.open: 3e1. always creates a new database when the flag has
the value ‘"n"’.  (Contributed by Claudiu Popa in bpo-18039(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18039


File: python.info,  Node: difflib,  Next: distutils<5>,  Prev: dbm<4>,  Up: 改进的模块<5>

1.5.5.16 difflib
................

The charset of HTML documents generated by *note HtmlDiff.make_file():
7bc. can now be customized by using a new `charset' keyword-only
argument.  The default charset of HTML document changed from
‘"ISO-8859-1"’ to ‘"utf-8"’.  (Contributed by Berker Peksag in
bpo-2052(1).)

The *note diff_bytes(): 7bd. 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(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue2052

   (2) https://bugs.python.org/issue17445


File: python.info,  Node: distutils<5>,  Next: doctest,  Prev: difflib,  Up: 改进的模块<5>

1.5.5.17 distutils
..................

Both the ‘build’ and ‘build_ext’ commands now accept a ‘-j’ option to
enable parallel building of extension modules.  (Contributed by Antoine
Pitrou in bpo-5309(1).)

The *note distutils: 38. module now supports ‘xz’ compression, and can
be enabled by passing ‘xztar’ as an argument to ‘bdist --format’.
(Contributed by Serhiy Storchaka in bpo-16314(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5309

   (2) https://bugs.python.org/issue16314


File: python.info,  Node: doctest,  Next: email<2>,  Prev: distutils<5>,  Up: 改进的模块<5>

1.5.5.18 doctest
................

The *note DocTestSuite(): 7c0. function returns an empty *note
unittest.TestSuite: 7c1. if `module' contains no docstrings, instead of
raising *note ValueError: 16d.  (Contributed by Glenn Jones in
bpo-15916(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15916


File: python.info,  Node: email<2>,  Next: enum<4>,  Prev: doctest,  Up: 改进的模块<5>

1.5.5.19 email
..............

A new policy option *note Policy.mangle_from_: 7c3. controls whether or
not lines that start with ‘"From "’ in email bodies are prefixed with a
‘">"’ character by generators.  The default is ‘True’ for *note
compat32: 63a. and ‘False’ for all other policies.  (Contributed by
Milan Oberkirch in bpo-20098(1).)

A new *note Message.get_content_disposition(): 7c4. method provides easy
access to a canonical value for the ‘Content-Disposition’ header.
(Contributed by Abhilash Raj in bpo-21083(2).)

A new policy option *note EmailPolicy.utf8: 7c5. can be set to ‘True’ to
encode email headers using the UTF-8 charset instead of using encoded
words.  This allows ‘Messages’ to be formatted according to RFC 6532(3)
and used with an SMTP server that supports the RFC 6531(4) ‘SMTPUTF8’
extension.  (Contributed by R. David Murray in bpo-24211(5).)

The *note mime.text.MIMEText: 7c6. constructor now accepts a *note
charset.Charset: 7c7. instance.  (Contributed by Claude Paroz and Berker
Peksag in bpo-16324(6).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20098

   (2) https://bugs.python.org/issue21083

   (3) https://tools.ietf.org/html/rfc6532.html

   (4) https://tools.ietf.org/html/rfc6531.html

   (5) https://bugs.python.org/issue24211

   (6) https://bugs.python.org/issue16324


File: python.info,  Node: enum<4>,  Next: faulthandler<2>,  Prev: email<2>,  Up: 改进的模块<5>

1.5.5.20 enum
.............

The *note Enum: 48d. callable has a new parameter `start' to specify the
initial number of enum values if only `names' are provided:

     >>> Animal = enum.Enum('Animal', 'cat dog', start=10)
     >>> Animal.cat
     <Animal.cat: 10>
     >>> Animal.dog
     <Animal.dog: 11>

（由 Ethan Furman 在 bpo-21706(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21706


File: python.info,  Node: faulthandler<2>,  Next: functools<3>,  Prev: enum<4>,  Up: 改进的模块<5>

1.5.5.21 faulthandler
.....................

The *note enable(): 642, *note register(): 7ca, *note dump_traceback():
7cb. and *note dump_traceback_later(): 7cc. functions now accept file
descriptors in addition to file-like objects.  (Contributed by Wei Wu in
bpo-23566(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23566


File: python.info,  Node: functools<3>,  Next: glob,  Prev: faulthandler<2>,  Up: 改进的模块<5>

1.5.5.22 functools
..................

Most of the *note lru_cache(): 2f8. machinery is now implemented in C,
making it significantly faster.  (Contributed by Matt Joiner, Alexey
Kachayev, and Serhiy Storchaka in bpo-14373(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue14373


File: python.info,  Node: glob,  Next: gzip<2>,  Prev: functools<3>,  Up: 改进的模块<5>

1.5.5.23 glob
.............

The *note iglob(): 6be. and *note glob(): 6bd. functions now support
recursive search in subdirectories, using the ‘"**"’ pattern.
(Contributed by Serhiy Storchaka in bpo-13968(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13968


File: python.info,  Node: gzip<2>,  Next: heapq,  Prev: glob,  Up: 改进的模块<5>

1.5.5.24 gzip
.............

The `mode' argument of the *note GzipFile: 206. constructor now accepts
‘"x"’ to request exclusive creation.  (Contributed by Tim Heaney in
bpo-19222(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue19222


File: python.info,  Node: heapq,  Next: http<2>,  Prev: gzip<2>,  Up: 改进的模块<5>

1.5.5.25 heapq
..............

Element comparison in *note merge(): 7d1. can now be customized by
passing a *note key function: 7d2. in a new optional `key' keyword
argument, and a new optional `reverse' keyword argument can be used to
reverse element comparison:

     >>> 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']

（由 Raymond Hettinger 在 bpo-13742(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13742


File: python.info,  Node: http<2>,  Next: http client<3>,  Prev: heapq,  Up: 改进的模块<5>

1.5.5.26 http
.............

A new *note HTTPStatus: 1ac. enum that defines a set of HTTP status
codes, reason phrases and long descriptions written in English.
(Contributed by Demian Brecht in bpo-21793(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21793


File: python.info,  Node: http client<3>,  Next: idlelib 与 IDLE<3>,  Prev: http<2>,  Up: 改进的模块<5>

1.5.5.27 http.client
....................

*note HTTPConnection.getresponse(): 7d5. now raises a *note
RemoteDisconnected: 7d6. exception when a remote server connection is
closed unexpectedly.  Additionally, if a *note ConnectionError: 7d7. (of
which ‘RemoteDisconnected’ is a subclass) is raised, the client socket
is now closed automatically, and will reconnect on the next request:

     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

（由 Martin Panter 在 bpo-3566(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue3566


File: python.info,  Node: idlelib 与 IDLE<3>,  Next: imaplib<2>,  Prev: http client<3>,  Up: 改进的模块<5>

1.5.5.28 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 ‘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.


File: python.info,  Node: imaplib<2>,  Next: imghdr,  Prev: idlelib 与 IDLE<3>,  Up: 改进的模块<5>

1.5.5.29 imaplib
................

The *note IMAP4: 1af. class now supports the *note context manager: 661.
protocol.  When used in a *note with: 7da. statement, the IMAP4 ‘LOGOUT’
command will be called automatically at the end of the block.
(Contributed by Tarek Ziadé and Serhiy Storchaka in bpo-4972(1).)

The *note imaplib: 97. module now supports RFC 5161(2) (ENABLE
Extension) and RFC 6855(3) (UTF-8 Support) via the *note IMAP4.enable():
7db. method.  A new *note IMAP4.utf8_enabled: 7dc. attribute tracks
whether or not RFC 6855(4) support is enabled.  (Contributed by Milan
Oberkirch, R. David Murray, and Maciej Szulik in bpo-21800(5).)

The *note imaplib: 97. 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(6).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue4972

   (2) https://tools.ietf.org/html/rfc5161.html

   (3) https://tools.ietf.org/html/rfc6855.html

   (4) https://tools.ietf.org/html/rfc6855.html

   (5) https://bugs.python.org/issue21800

   (6) https://bugs.python.org/issue21800


File: python.info,  Node: imghdr,  Next: importlib<6>,  Prev: imaplib<2>,  Up: 改进的模块<5>

1.5.5.30 imghdr
...............

The *note what(): 7de. function now recognizes the OpenEXR(1) format
(contributed by Martin Vignali and Claudiu Popa in bpo-20295(2)), and
the WebP(3) format (contributed by Fabrice Aneche and Claudiu Popa in
bpo-20197(4).)

   ---------- Footnotes ----------

   (1) http://www.openexr.com

   (2) https://bugs.python.org/issue20295

   (3) https://en.wikipedia.org/wiki/WebP

   (4) https://bugs.python.org/issue20197


File: python.info,  Node: importlib<6>,  Next: inspect<4>,  Prev: imghdr,  Up: 改进的模块<5>

1.5.5.31 importlib
..................

The *note util.LazyLoader: 64d. class allows for lazy loading of modules
in applications where startup time is important.  (Contributed by Brett
Cannon in bpo-17621(1).)

The *note abc.InspectLoader.source_to_code(): 7e0. method is now a
static method.  This makes it easier to initialize a module object with
code compiled from a string by running ‘exec(code, module.__dict__)’.
(Contributed by Brett Cannon in bpo-21156(2).)

The new *note util.module_from_spec(): 7e1. function is now the
preferred way to create a new module.  As opposed to creating a *note
types.ModuleType: 7e2. 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(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17621

   (2) https://bugs.python.org/issue21156

   (3) https://bugs.python.org/issue20383


File: python.info,  Node: inspect<4>,  Next: io<3>,  Prev: importlib<6>,  Up: 改进的模块<5>

1.5.5.32 inspect
................

Both the *note Signature: 7e4. and *note Parameter: 7e5. classes are now
picklable and hashable.  (Contributed by Yury Selivanov in bpo-20726(1)
and bpo-20334(2).)

A new *note BoundArguments.apply_defaults(): 7e6. method provides a way
to set default values for missing arguments:

     >>> def foo(a, b='ham', *args): pass
     >>> ba = inspect.signature(foo).bind('spam')
     >>> ba.apply_defaults()
     >>> ba.arguments
     OrderedDict([('a', 'spam'), ('b', 'ham'), ('args', ())])

（由 Yury Selivanov 在 bpo-24190(3) 中贡献。）

A new class method *note Signature.from_callable(): 7e7. makes
subclassing of *note Signature: 7e4. easier.  (Contributed by Yury
Selivanov and Eric Snow in bpo-17373(4).)

The *note signature(): 655. function now accepts a `follow_wrapped'
optional keyword argument, which, when set to ‘False’, disables
automatic following of ‘__wrapped__’ links.  (Contributed by Yury
Selivanov in bpo-20691(5).)

A set of new functions to inspect *note coroutine functions: 732. and
*note coroutine objects: 18a. has been added: *note iscoroutine(): 7e8,
*note iscoroutinefunction(): 7e9, *note isawaitable(): 7ea, *note
getcoroutinelocals(): 7eb, and *note getcoroutinestate(): 7ec.
(Contributed by Yury Selivanov in bpo-24017(6) and bpo-24400(7).)

The *note stack(): 7ed, *note trace(): 7ee, *note getouterframes(): 7ef,
and *note getinnerframes(): 7f0. functions now return a list of named
tuples.  (Contributed by Daniel Shahaf in bpo-16808(8).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20726

   (2) https://bugs.python.org/issue20334

   (3) https://bugs.python.org/issue24190

   (4) https://bugs.python.org/issue17373

   (5) https://bugs.python.org/issue20691

   (6) https://bugs.python.org/issue24017

   (7) https://bugs.python.org/issue24400

   (8) https://bugs.python.org/issue16808


File: python.info,  Node: io<3>,  Next: ipaddress<3>,  Prev: inspect<4>,  Up: 改进的模块<5>

1.5.5.33 io
...........

A new *note BufferedIOBase.readinto1(): 7f2. method, that uses at most
one call to the underlying raw stream’s *note RawIOBase.read(): 7f3. or
*note RawIOBase.readinto(): 7f4. methods.  (Contributed by Nikolaus Rath
in bpo-20578(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20578


File: python.info,  Node: ipaddress<3>,  Next: json<2>,  Prev: io<3>,  Up: 改进的模块<5>

1.5.5.34 ipaddress
..................

Both the *note IPv4Network: 4a6. and *note IPv6Network: 4a5. classes now
accept an ‘(address, netmask)’ tuple argument, so as to easily construct
network objects from existing addresses:

     >>> 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')

（由 Peter Moody 和 Antoine Pitrou 在 bpo-16531(1) 中贡献。）

A new ‘reverse_pointer’ attribute for the *note IPv4Network: 4a6. and
*note IPv6Network: 4a5. classes returns the name of the reverse DNS PTR
record:

     >>> 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'

（由 Leon Weber 在 bpo-20480(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16531

   (2) https://bugs.python.org/issue20480


File: python.info,  Node: json<2>,  Next: linecache,  Prev: ipaddress<3>,  Up: 改进的模块<5>

1.5.5.35 json
.............

The *note json.tool: a5. command line interface now preserves the order
of keys in JSON objects passed in input.  The new ‘--sort-keys’ option
can be used to sort the keys alphabetically.  (Contributed by Berker
Peksag in bpo-21650(1).)

JSON decoder now raises *note JSONDecodeError: 7f7. instead of *note
ValueError: 16d. to provide better context information about the error.
(Contributed by Serhiy Storchaka in bpo-19361(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21650

   (2) https://bugs.python.org/issue19361


File: python.info,  Node: linecache,  Next: locale<3>,  Prev: json<2>,  Up: 改进的模块<5>

1.5.5.36 linecache
..................

A new *note lazycache(): 7f9. function can be used to capture
information about a non-file-based module to permit getting its lines
later via *note getline(): 7fa.  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(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17911


File: python.info,  Node: locale<3>,  Next: logging<4>,  Prev: linecache,  Up: 改进的模块<5>

1.5.5.37 locale
...............

A new *note delocalize(): 7fc. function can be used to convert a string
into a normalized number string, taking the ‘LC_NUMERIC’ settings into
account:

     >>> 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'

（由 Cédric Krier 在 bpo-13918(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13918


File: python.info,  Node: logging<4>,  Next: lzma,  Prev: locale<3>,  Up: 改进的模块<5>

1.5.5.38 logging
................

All logging methods (*note Logger: 4ad. *note log(): 7fe, *note
exception(): 7ff, *note critical(): 800, *note debug(): 801, etc.), now
accept exception instances as an `exc_info' argument, in addition to
boolean values and exception tuples:

     >>> import logging
     >>> try:
     ...     1/0
     ... except ZeroDivisionError as ex:
     ...     logging.error('exception', exc_info=ex)
     ERROR:root:exception

（由 Yury Selivanov 在 bpo-20537(1) 中贡献。）

The *note handlers.HTTPHandler: 802. class now accepts an optional *note
ssl.SSLContext: 4e9. instance to configure SSL settings used in an HTTP
connection.  (Contributed by Alex Gaynor in bpo-22788(2).)

The *note handlers.QueueListener: 803. class now takes a
`respect_handler_level' keyword argument which, if set to ‘True’, will
pass messages to handlers taking handler levels into account.
(Contributed by Vinay Sajip.)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20537

   (2) https://bugs.python.org/issue22788


File: python.info,  Node: lzma,  Next: math<5>,  Prev: logging<4>,  Up: 改进的模块<5>

1.5.5.39 lzma
.............

The *note LZMADecompressor.decompress(): 805. method now accepts an
optional `max_length' argument to limit the maximum size of decompressed
data.  (Contributed by Martin Panter in bpo-15955(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15955


File: python.info,  Node: math<5>,  Next: multiprocessing<5>,  Prev: lzma,  Up: 改进的模块<5>

1.5.5.40 math
.............

Two new constants have been added to the *note math: b1. module: *note
inf: 621. and *note nan: 622.  (Contributed by Mark Dickinson in
bpo-23185(1).)

A new function *note isclose(): 779. provides a way to test for
approximate equality.  (Contributed by Chris Barker and Tal Einat in
bpo-24270(2).)

A new *note gcd(): 1be. function has been added.  The ‘fractions.gcd()’
function is now deprecated.  (Contributed by Mark Dickinson and Serhiy
Storchaka in bpo-22486(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23185

   (2) https://bugs.python.org/issue24270

   (3) https://bugs.python.org/issue22486


File: python.info,  Node: multiprocessing<5>,  Next: operator,  Prev: math<5>,  Up: 改进的模块<5>

1.5.5.41 multiprocessing
........................

*note sharedctypes.synchronized(): 808. objects now support the *note
context manager: 661. protocol.  (Contributed by Charles-François Natali
in bpo-21565(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21565


File: python.info,  Node: operator,  Next: os<6>,  Prev: multiprocessing<5>,  Up: 改进的模块<5>

1.5.5.42 operator
.................

*note attrgetter(): 80a, *note itemgetter(): 38b, and *note
methodcaller(): 80b. objects now support pickling.  (Contributed by Josh
Rosenberg and Serhiy Storchaka in bpo-22955(1).)

New *note matmul(): 80c. and *note imatmul(): 80d. functions to perform
matrix multiplication.  (Contributed by Benjamin Peterson in
bpo-21176(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22955

   (2) https://bugs.python.org/issue21176


File: python.info,  Node: os<6>,  Next: pathlib<5>,  Prev: operator,  Up: 改进的模块<5>

1.5.5.43 os
...........

The new *note scandir(): 389. function returning an iterator of *note
DirEntry: 5ea. objects has been added.  If possible, *note scandir():
389. 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(1).)

On Windows, a new *note stat_result.st_file_attributes: 80f. attribute
is now available.  It corresponds to the ‘dwFileAttributes’ member of
the ‘BY_HANDLE_FILE_INFORMATION’ structure returned by
‘GetFileInformationByHandle()’.  (Contributed by Ben Hoyt in
bpo-21719(2).)

The *note urandom(): 5cb. function now uses the ‘getrandom()’ syscall on
Linux 3.17 or newer, and ‘getentropy()’ on OpenBSD 5.6 and newer,
removing the need to use ‘/dev/urandom’ and avoiding failures due to
potential file descriptor exhaustion.  (Contributed by Victor Stinner in
bpo-22181(3).)

New *note get_blocking(): 810. and *note set_blocking(): 811. functions
allow getting and setting a file descriptor’s blocking mode (*note
O_NONBLOCK: 812.)  (Contributed by Victor Stinner in bpo-22054(4).)

The *note truncate(): 813. and *note ftruncate(): 755. functions are now
supported on Windows.  (Contributed by Steve Dower in bpo-23668(5).)

There is a new *note os.path.commonpath(): 814. function returning the
longest common sub-path of each passed pathname.  Unlike the *note
os.path.commonprefix(): 815. function, it always returns a valid path:

     >>> os.path.commonprefix(['/usr/lib', '/usr/local/lib'])
     '/usr/l'

     >>> os.path.commonpath(['/usr/lib', '/usr/local/lib'])
     '/usr'

（由 Rafik Draoui 和 Serhiy Storchaka 在 bpo-10395(6) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22524

   (2) https://bugs.python.org/issue21719

   (3) https://bugs.python.org/issue22181

   (4) https://bugs.python.org/issue22054

   (5) https://bugs.python.org/issue23668

   (6) https://bugs.python.org/issue10395


File: python.info,  Node: pathlib<5>,  Next: pickle<3>,  Prev: os<6>,  Up: 改进的模块<5>

1.5.5.44 pathlib
................

The new *note Path.samefile(): 817. method can be used to check whether
the path points to the same file as another path, which can be either
another *note Path: 32f. object, or a string:

     >>> import pathlib
     >>> p1 = pathlib.Path('/etc/hosts')
     >>> p2 = pathlib.Path('/etc/../etc/hosts')
     >>> p1.samefile(p2)
     True

（由 Vajrasky Kok 和 Antoine Pitrou 在 bpo-19775(1) 中贡献。）

The *note Path.mkdir(): 818. method now accepts a new optional
`exist_ok' argument to match ‘mkdir -p’ and *note os.makedirs(): 4c3.
functionality.  (Contributed by Berker Peksag in bpo-21539(2).)

There is a new *note Path.expanduser(): 819. method to expand ‘~’ and
‘~user’ prefixes.  (Contributed by Serhiy Storchaka and Claudiu Popa in
bpo-19776(3).)

A new *note Path.home(): 81a. class method can be used to get a *note
Path: 32f. instance representing the user’s home directory.
(Contributed by Victor Salgado and Mayank Tripathi in bpo-19777(4).)

New *note Path.write_text(): 81b, *note Path.read_text(): 81c, *note
Path.write_bytes(): 81d, *note Path.read_bytes(): 81e. methods to
simplify read/write operations on files.

The following code snippet will create or rewrite existing file
‘~/spam42’:

     >>> import pathlib
     >>> p = pathlib.Path('~/spam42')
     >>> p.expanduser().write_text('ham')
     3

（由 Christopher Welborn 在 bpo-20218(5) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue19775

   (2) https://bugs.python.org/issue21539

   (3) https://bugs.python.org/issue19776

   (4) https://bugs.python.org/issue19777

   (5) https://bugs.python.org/issue20218


File: python.info,  Node: pickle<3>,  Next: poplib<2>,  Prev: pathlib<5>,  Up: 改进的模块<5>

1.5.5.45 pickle
...............

Nested objects, such as unbound methods or nested classes, can now be
pickled using *note pickle protocols: 666. older than protocol version
4.  Protocol version 4 already supports these cases.  (Contributed by
Serhiy Storchaka in bpo-23611(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23611


File: python.info,  Node: poplib<2>,  Next: re<4>,  Prev: pickle<3>,  Up: 改进的模块<5>

1.5.5.46 poplib
...............

A new *note POP3.utf8(): 821. command enables RFC 6856(1)
(Internationalized Email) support, if a POP server supports it.
(Contributed by Milan OberKirch in bpo-21804(2).)

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc6856.html

   (2) https://bugs.python.org/issue21804


File: python.info,  Node: re<4>,  Next: readline<2>,  Prev: poplib<2>,  Up: 改进的模块<5>

1.5.5.47 re
...........

References and conditional references to groups with fixed length are
now allowed in lookbehind assertions:

     >>> 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'>

（由 Serhiy Storchaka 在 bpo-9179(1) 中贡献。）

The number of capturing groups in regular expressions is no longer
limited to 100.  (Contributed by Serhiy Storchaka in bpo-22437(2).)

The *note sub(): 579. and *note subn(): 823. functions now replace
unmatched groups with empty strings instead of raising an exception.
(Contributed by Serhiy Storchaka in bpo-1519638(3).)

The *note re.error: 824. exceptions have new attributes, *note msg: 825,
*note pattern: 826, *note pos: 827, *note lineno: 828, and *note colno:
829, that provide better context information about the error:

     >>> re.compile("""
     ...     (?x)
     ...     .++
     ... """)
     Traceback (most recent call last):
        ...
     sre_constants.error: multiple repeat at position 16 (line 3, column 7)

（由 Serhiy Storchaka 在 bpo-22578(4) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue9179

   (2) https://bugs.python.org/issue22437

   (3) https://bugs.python.org/issue1519638

   (4) https://bugs.python.org/issue22578


File: python.info,  Node: readline<2>,  Next: selectors,  Prev: re<4>,  Up: 改进的模块<5>

1.5.5.48 readline
.................

A new *note append_history_file(): 82b. 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(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22940


File: python.info,  Node: selectors,  Next: shutil<2>,  Prev: readline<2>,  Up: 改进的模块<5>

1.5.5.49 selectors
..................

The new *note DevpollSelector: 54f. supports efficient ‘/dev/poll’
polling on Solaris.  (Contributed by Giampaolo Rodola’ in bpo-18931(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18931


File: python.info,  Node: shutil<2>,  Next: signal<3>,  Prev: selectors,  Up: 改进的模块<5>

1.5.5.50 shutil
...............

The *note move(): 385. function now accepts a `copy_function' argument,
allowing, for example, the *note copy(): 383. function to be used
instead of the default *note copy2(): 384. if there is a need to ignore
file metadata when moving.  (Contributed by Claudiu Popa in
bpo-19840(1).)

The *note make_archive(): 348. function now supports the `xztar' format.
(Contributed by Serhiy Storchaka in bpo-5411(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue19840

   (2) https://bugs.python.org/issue5411


File: python.info,  Node: signal<3>,  Next: smtpd,  Prev: shutil<2>,  Up: 改进的模块<5>

1.5.5.51 signal
...............

On Windows, the *note set_wakeup_fd(): 4d4. function now also supports
socket handles.  (Contributed by Victor Stinner in bpo-22018(1).)

Various ‘SIG*’ constants in the *note signal: ea. module have been
converted into *note Enums: 79.  This allows meaningful names to be
printed during debugging, instead of integer "magic numbers".
(Contributed by Giampaolo Rodola’ in bpo-21076(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22018

   (2) https://bugs.python.org/issue21076


File: python.info,  Node: smtpd,  Next: smtplib<2>,  Prev: signal<3>,  Up: 改进的模块<5>

1.5.5.52 smtpd
..............

Both the *note SMTPServer: 6f9. and *note SMTPChannel: 6f8. classes now
accept a `decode_data' keyword argument to determine if the ‘DATA’
portion of the SMTP transaction is decoded using the ‘"utf-8"’ codec or
is instead provided to the *note SMTPServer.process_message(): 6fa.
method as a byte string.  The default is ‘True’ for backward
compatibility reasons, but will change to ‘False’ in Python 3.6.  If
`decode_data' is set to ‘False’, the ‘process_message’ method must be
prepared to accept keyword arguments.  (Contributed by Maciej Szulik in
bpo-19662(1).)

The *note SMTPServer: 6f9. class now advertises the ‘8BITMIME’ extension
( RFC 6152(2)) if `decode_data' has been set ‘True’.  If the client
specifies ‘BODY=8BITMIME’ on the ‘MAIL’ command, it is passed to *note
SMTPServer.process_message(): 6fa. via the `mail_options' keyword.
(Contributed by Milan Oberkirch and R. David Murray in bpo-21795(3).)

The *note SMTPServer: 6f9. class now also supports the ‘SMTPUTF8’
extension ( RFC 6531(4): Internationalized Email).  If the client
specified ‘SMTPUTF8 BODY=8BITMIME’ on the ‘MAIL’ command, they are
passed to *note SMTPServer.process_message(): 6fa. via the
`mail_options' keyword.  It is the responsibility of the
‘process_message’ method to correctly handle the ‘SMTPUTF8’ data.
(Contributed by Milan Oberkirch in bpo-21725(5).)

It is now possible to provide, directly or via name resolution, IPv6
addresses in the *note SMTPServer: 6f9. constructor, and have it
successfully connect.  (Contributed by Milan Oberkirch in bpo-14758(6).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue19662

   (2) https://tools.ietf.org/html/rfc6152.html

   (3) https://bugs.python.org/issue21795

   (4) https://tools.ietf.org/html/rfc6531.html

   (5) https://bugs.python.org/issue21725

   (6) https://bugs.python.org/issue14758


File: python.info,  Node: smtplib<2>,  Next: sndhdr,  Prev: smtpd,  Up: 改进的模块<5>

1.5.5.53 smtplib
................

A new *note SMTP.auth(): 831. method provides a convenient way to
implement custom authentication mechanisms.  (Contributed by Milan
Oberkirch in bpo-15014(1).)

The *note SMTP.set_debuglevel(): 832. method now accepts an additional
debuglevel (2), which enables timestamps in debug messages.
(Contributed by Gavin Chappell and Maciej Szulik in bpo-16914(2).)

Both the *note SMTP.sendmail(): 833. and *note SMTP.send_message(): 834.
methods now support RFC 6531(3) (SMTPUTF8).  (Contributed by Milan
Oberkirch and R. David Murray in bpo-22027(4).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15014

   (2) https://bugs.python.org/issue16914

   (3) https://tools.ietf.org/html/rfc6531.html

   (4) https://bugs.python.org/issue22027


File: python.info,  Node: sndhdr,  Next: socket<6>,  Prev: smtplib<2>,  Up: 改进的模块<5>

1.5.5.54 sndhdr
...............

The *note what(): 836. and *note whathdr(): 837. functions now return a
*note namedtuple(): 1a1.  (Contributed by Claudiu Popa in bpo-18615(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18615


File: python.info,  Node: socket<6>,  Next: ssl<6>,  Prev: sndhdr,  Up: 改进的模块<5>

1.5.5.55 socket
...............

Functions with timeouts now use a monotonic clock, instead of a system
clock.  (Contributed by Victor Stinner in bpo-22043(1).)

A new *note socket.sendfile(): 839. method allows sending a file over a
socket by using the high-performance *note os.sendfile(): 461. function
on UNIX, resulting in uploads being from 2 to 3 times faster than when
using plain *note socket.send(): 76d.  (Contributed by Giampaolo Rodola’
in bpo-17552(2).)

The *note socket.sendall(): 76e. 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(3).)

The `backlog' argument of the *note socket.listen(): 83a. method is now
optional.  By default it is set to *note SOMAXCONN: 83b. or to ‘128’,
whichever is less.  (Contributed by Charles-François Natali in
bpo-21455(4).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22043

   (2) https://bugs.python.org/issue17552

   (3) https://bugs.python.org/issue23853

   (4) https://bugs.python.org/issue21455


File: python.info,  Node: ssl<6>,  Next: sqlite3<3>,  Prev: socket<6>,  Up: 改进的模块<5>

1.5.5.56 ssl
............

* Menu:

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


File: python.info,  Node: 内存 BIO 支持,  Next: Application-Layer Protocol Negotiation Support,  Up: ssl<6>

1.5.5.57 内存 BIO 支持
......................

（由 Geert Jansen 在 bpo-21965(1) 中贡献。）

The new *note SSLObject: 4e8. class has been added to provide SSL
protocol support for cases when the network I/O capabilities of *note
SSLSocket: 192. are not necessary or are suboptimal.  ‘SSLObject’
represents an SSL protocol instance, but does not implement any network
I/O methods, and instead provides a memory buffer interface.  The new
*note MemoryBIO: 83e. 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 *note SSLSocket:
192.’s readiness model ("select/poll") is inefficient.

A new *note SSLContext.wrap_bio(): 4eb. method can be used to create a
new ‘SSLObject’ instance.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21965


File: python.info,  Node: Application-Layer Protocol Negotiation Support,  Next: Other Changes,  Prev: 内存 BIO 支持,  Up: ssl<6>

1.5.5.58 Application-Layer Protocol Negotiation Support
.......................................................

（由 Benjamin Peterson 在 bpo-20188(1) 中贡献。）

Where OpenSSL support is present, the *note ssl: f3. module now
implements the `Application-Layer Protocol Negotiation' TLS extension as
described in RFC 7301(2).

The new *note SSLContext.set_alpn_protocols(): 840. can be used to
specify which protocols a socket should advertise during the TLS
handshake.

The new *note SSLSocket.selected_alpn_protocol(): 841. returns the
protocol that was selected during the TLS handshake.  The *note
HAS_ALPN: 842. flag indicates whether ALPN support is present.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20188

   (2) https://tools.ietf.org/html/rfc7301.html


File: python.info,  Node: Other Changes,  Prev: Application-Layer Protocol Negotiation Support,  Up: ssl<6>

1.5.5.59 Other Changes
......................

There is a new *note SSLSocket.version(): 844. method to query the
actual protocol version in use.  (Contributed by Antoine Pitrou in
bpo-20421(1).)

The *note SSLSocket: 192. class now implements a ‘SSLSocket.sendfile()’
method.  (Contributed by Giampaolo Rodola’ in bpo-17552(2).)

The ‘SSLSocket.send()’ method now raises either the *note
ssl.SSLWantReadError: 845. or *note ssl.SSLWantWriteError: 846.
exception on a non-blocking socket if the operation would block.
Previously, it would return ‘0’.  (Contributed by Nikolaus Rath in
bpo-20951(3).)

The *note cert_time_to_seconds(): 847. function now interprets the input
time as UTC and not as local time, per RFC 5280(4).  Additionally, the
return value is always an *note int: 204.  (Contributed by Akira Li in
bpo-19940(5).)

New ‘SSLObject.shared_ciphers()’ and *note SSLSocket.shared_ciphers():
848. methods return the list of ciphers sent by the client during the
handshake.  (Contributed by Benjamin Peterson in bpo-23186(6).)

The *note SSLSocket.do_handshake(): 849, *note SSLSocket.read(): 84a,
‘SSLSocket.shutdown()’, and *note SSLSocket.write(): 84b. methods of the
*note SSLSocket: 192. 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(7).)

The *note match_hostname(): 4e2. function now supports matching of IP
addresses.  (Contributed by Antoine Pitrou in bpo-23239(8).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20421

   (2) https://bugs.python.org/issue17552

   (3) https://bugs.python.org/issue20951

   (4) https://tools.ietf.org/html/rfc5280.html

   (5) https://bugs.python.org/issue19940

   (6) https://bugs.python.org/issue23186

   (7) https://bugs.python.org/issue23853

   (8) https://bugs.python.org/issue23239


File: python.info,  Node: sqlite3<3>,  Next: subprocess<3>,  Prev: ssl<6>,  Up: 改进的模块<5>

1.5.5.60 sqlite3
................

The *note Row: 84d. class now fully supports the sequence protocol, in
particular *note reversed(): 2c6. iteration and slice indexing.
(Contributed by Claudiu Popa in bpo-10203(1); by Lucas Sinclair, Jessica
McKellar, and Serhiy Storchaka in bpo-13583(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10203

   (2) https://bugs.python.org/issue13583


File: python.info,  Node: subprocess<3>,  Next: sys<6>,  Prev: sqlite3<3>,  Up: 改进的模块<5>

1.5.5.61 subprocess
...................

The new *note run(): 4f2. function has been added.  It runs the
specified command and returns a *note CompletedProcess: 84f. 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(1).)

例如:

     >>> 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')

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23342


File: python.info,  Node: sys<6>,  Next: sysconfig,  Prev: subprocess<3>,  Up: 改进的模块<5>

1.5.5.62 sys
............

A new ‘set_coroutine_wrapper()’ function allows setting a global hook
that will be called whenever a *note coroutine object: 18a. is created
by an *note async def: 3a9. function.  A corresponding
‘get_coroutine_wrapper()’ can be used to obtain a currently set wrapper.
Both functions are *note provisional: 454, and are intended for
debugging purposes only.  (Contributed by Yury Selivanov in
bpo-24017(1).)

A new *note is_finalizing(): 851. function can be used to check if the
Python interpreter is *note shutting down: 852.  (Contributed by Antoine
Pitrou in bpo-22696(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24017

   (2) https://bugs.python.org/issue22696


File: python.info,  Node: sysconfig,  Next: tarfile<2>,  Prev: sys<6>,  Up: 改进的模块<5>

1.5.5.63 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(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23437


File: python.info,  Node: tarfile<2>,  Next: threading<3>,  Prev: sysconfig,  Up: 改进的模块<5>

1.5.5.64 tarfile
................

The `mode' argument of the *note open(): 855. function now accepts ‘"x"’
to request exclusive creation.  (Contributed by Berker Peksag in
bpo-21717(1).)

The *note TarFile.extractall(): 856. and *note TarFile.extract(): 857.
methods now take a keyword argument `numeric_owner'.  If set to ‘True’,
the extracted files and directories will be owned by the numeric ‘uid’
and ‘gid’ from the tarfile.  If set to ‘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(2).)

The *note TarFile.list(): 858. now accepts an optional `members' keyword
argument that can be set to a subset of the list returned by *note
TarFile.getmembers(): 859.  (Contributed by Serhiy Storchaka in
bpo-21549(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21717

   (2) https://bugs.python.org/issue23193

   (3) https://bugs.python.org/issue21549


File: python.info,  Node: threading<3>,  Next: time<5>,  Prev: tarfile<2>,  Up: 改进的模块<5>

1.5.5.65 threading
..................

Both the *note Lock.acquire(): 85b. and *note RLock.acquire(): 85c.
methods now use a monotonic clock for timeout management.  (Contributed
by Victor Stinner in bpo-22043(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22043


File: python.info,  Node: time<5>,  Next: timeit<2>,  Prev: threading<3>,  Up: 改进的模块<5>

1.5.5.66 time
.............

The *note monotonic(): 85e. function is now always available.
(Contributed by Victor Stinner in bpo-22043(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22043


File: python.info,  Node: timeit<2>,  Next: tkinter<5>,  Prev: time<5>,  Up: 改进的模块<5>

1.5.5.67 timeit
...............

A new command line option ‘-u’ or ‘--unit=`U'’ can be used to specify
the time unit for the timer output.  Supported options are ‘usec’,
‘msec’, or ‘sec’.  (Contributed by Julian Gindi in bpo-18983(1).)

The *note timeit(): 860. function has a new `globals' parameter for
specifying the namespace in which the code will be running.
(Contributed by Ben Roberts in bpo-2527(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18983

   (2) https://bugs.python.org/issue2527


File: python.info,  Node: tkinter<5>,  Next: traceback<2>,  Prev: timeit<2>,  Up: 改进的模块<5>

1.5.5.68 tkinter
................

The ‘tkinter._fix’ module used for setting up the Tcl/Tk environment on
Windows has been replaced by a private function in the ‘_tkinter’ module
which makes no permanent changes to environment variables.  (Contributed
by Zachary Ware in bpo-20035(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20035


File: python.info,  Node: traceback<2>,  Next: types<2>,  Prev: tkinter<5>,  Up: 改进的模块<5>

1.5.5.69 traceback
..................

New *note walk_stack(): 863. and *note walk_tb(): 864. functions to
conveniently traverse frame and traceback objects.  (Contributed by
Robert Collins in bpo-17911(1).)

New lightweight classes: *note TracebackException: 865, *note
StackSummary: 866, and *note FrameSummary: 867.  (Contributed by Robert
Collins in bpo-17911(2).)

Both the *note print_tb(): 868. and *note print_stack(): 869. functions
now support negative values for the `limit' argument.  (Contributed by
Dmitry Kazakov in bpo-22619(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17911

   (2) https://bugs.python.org/issue17911

   (3) https://bugs.python.org/issue22619


File: python.info,  Node: types<2>,  Next: unicodedata<5>,  Prev: traceback<2>,  Up: 改进的模块<5>

1.5.5.70 types
..............

A new *note coroutine(): 86b. function to transform *note generator:
558. and *note generator-like: 7a8. objects into *note awaitables: 612.
(Contributed by Yury Selivanov in bpo-24017(1).)

A new type called *note CoroutineType: 86c, which is used for *note
coroutine: 18a. objects created by *note async def: 3a9. functions.
(Contributed by Yury Selivanov in bpo-24400(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24017

   (2) https://bugs.python.org/issue24400


File: python.info,  Node: unicodedata<5>,  Next: unittest<3>,  Prev: types<2>,  Up: 改进的模块<5>

1.5.5.71 unicodedata
....................

The *note unicodedata: 123. module now uses data from Unicode 8.0.0(1).

   ---------- Footnotes ----------

   (1) http://unicode.org/versions/Unicode8.0.0/


File: python.info,  Node: unittest<3>,  Next: unittest mock<3>,  Prev: unicodedata<5>,  Up: 改进的模块<5>

1.5.5.72 unittest
.................

The *note TestLoader.loadTestsFromModule(): 86f. method now accepts a
keyword-only argument `pattern' which is passed to ‘load_tests’ as the
third argument.  Found packages are now checked for ‘load_tests’
regardless of whether their path matches `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(1).)

Unittest discovery errors now are exposed in the *note
TestLoader.errors: 870. attribute of the *note TestLoader: 871.
instance.  (Contributed by Robert Collins in bpo-19746(2).)

A new command line option ‘--locals’ to show local variables in
tracebacks.  (Contributed by Robert Collins in bpo-22936(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16662

   (2) https://bugs.python.org/issue19746

   (3) https://bugs.python.org/issue22936


File: python.info,  Node: unittest mock<3>,  Next: urllib,  Prev: unittest<3>,  Up: 改进的模块<5>

1.5.5.73 unittest.mock
......................

The *note Mock: 373. class has the following improvements:

   * The class constructor has a new `unsafe' parameter, which causes
     mock objects to raise *note AttributeError: 4a1. on attribute names
     starting with ‘"assert"’.  (Contributed by Kushal Das in
     bpo-21238(1).)

   * A new *note Mock.assert_not_called(): 873. method to check if the
     mock object was called.  (Contributed by Kushal Das in
     bpo-21262(2).)

The *note MagicMock: 874. class now supports *note __truediv__(): 875,
*note __divmod__(): 876. and *note __matmul__(): 73b. operators.
(Contributed by Johannes Baiter in bpo-20968(3), and Håkan Lövdahl in
bpo-23581(4) and bpo-23568(5).)

It is no longer necessary to explicitly pass ‘create=True’ to the *note
patch(): 877. function when patching builtin names.  (Contributed by
Kushal Das in bpo-17660(6).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21238

   (2) https://bugs.python.org/issue21262

   (3) https://bugs.python.org/issue20968

   (4) https://bugs.python.org/issue23581

   (5) https://bugs.python.org/issue23568

   (6) https://bugs.python.org/issue17660


File: python.info,  Node: urllib,  Next: wsgiref,  Prev: unittest mock<3>,  Up: 改进的模块<5>

1.5.5.74 urllib
...............

A new *note request.HTTPPasswordMgrWithPriorAuth: 879. class allows HTTP
Basic Authentication credentials to be managed so as to eliminate
unnecessary ‘401’ response handling, or to unconditionally send
credentials on the first request in order to communicate with servers
that return a ‘404’ response instead of a ‘401’ if the ‘Authorization’
header is not sent.  (Contributed by Matej Cepl in bpo-19494(1) and
Akshit Khurana in bpo-7159(2).)

A new `quote_via' argument for the *note parse.urlencode(): 87a.
function provides a way to control the encoding of query parts if
needed.  (Contributed by Samwyse and Arnon Yaari in bpo-13866(3).)

The *note request.urlopen(): 87b. function accepts an *note
ssl.SSLContext: 4e9. object as a `context' argument, which will be used
for the HTTPS connection.  (Contributed by Alex Gaynor in bpo-22366(4).)

The *note parse.urljoin(): 87c. was updated to use the RFC 3986(5)
semantics for the resolution of relative URLs, rather than RFC 1808(6)
and RFC 2396(7).  (Contributed by Demian Brecht and Senthil Kumaran in
bpo-22118(8).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue19494

   (2) https://bugs.python.org/issue7159

   (3) https://bugs.python.org/issue13866

   (4) https://bugs.python.org/issue22366

   (5) https://tools.ietf.org/html/rfc3986.html

   (6) https://tools.ietf.org/html/rfc1808.html

   (7) https://tools.ietf.org/html/rfc2396.html

   (8) https://bugs.python.org/issue22118


File: python.info,  Node: wsgiref,  Next: xmlrpc<2>,  Prev: urllib,  Up: 改进的模块<5>

1.5.5.75 wsgiref
................

The `headers' argument of the *note headers.Headers: 87e. class
constructor is now optional.  (Contributed by Pablo Torres Navarrete and
SilentGhost in bpo-5800(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5800


File: python.info,  Node: xmlrpc<2>,  Next: xml sax,  Prev: wsgiref,  Up: 改进的模块<5>

1.5.5.76 xmlrpc
...............

The *note client.ServerProxy: 37f. class now supports the *note context
manager: 661. protocol.  (Contributed by Claudiu Popa in bpo-20627(1).)

The *note client.ServerProxy: 37f. constructor now accepts an optional
*note ssl.SSLContext: 4e9. instance.  (Contributed by Alex Gaynor in
bpo-22960(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20627

   (2) https://bugs.python.org/issue22960


File: python.info,  Node: xml sax,  Next: zipfile<3>,  Prev: xmlrpc<2>,  Up: 改进的模块<5>

1.5.5.77 xml.sax
................

SAX parsers now support a character stream of the *note
xmlreader.InputSource: 881. object.  (Contributed by Serhiy Storchaka in
bpo-2175(1).)

*note parseString(): 882. now accepts a *note str: 205. instance.
(Contributed by Serhiy Storchaka in bpo-10590(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue2175

   (2) https://bugs.python.org/issue10590


File: python.info,  Node: zipfile<3>,  Prev: xml sax,  Up: 改进的模块<5>

1.5.5.78 zipfile
................

ZIP output can now be written to unseekable streams.  (Contributed by
Serhiy Storchaka in bpo-23252(1).)

The `mode' argument of *note ZipFile.open(): 6b3. method now accepts
‘"x"’ to request exclusive creation.  (Contributed by Serhiy Storchaka
in bpo-21717(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23252

   (2) https://bugs.python.org/issue21717


File: python.info,  Node: 其他模块级更改,  Next: 性能优化<5>,  Prev: 改进的模块<5>,  Up: Python 3 5 有什麼新功能

1.5.6 其他模块级更改
--------------------

Many functions in the *note mmap: b3, *note ossaudiodev: c6, *note
socket: ef, *note ssl: f3, and *note codecs: 1b. modules now accept
writable *note bytes-like objects: 6df.  (Contributed by Serhiy
Storchaka in bpo-23001(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23001


File: python.info,  Node: 性能优化<5>,  Next: 构建和 C API 的改变<3>,  Prev: 其他模块级更改,  Up: Python 3 5 有什麼新功能

1.5.7 性能优化
--------------

The *note os.walk(): 747. 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 *note os.scandir(): 389. function, which exposes file information
from the underlying ‘readdir’ or ‘FindFirstFile’/‘FindNextFile’ system
calls.  (Contributed by Ben Hoyt with help from Victor Stinner in
bpo-23605(1).)

Construction of ‘bytes(int)’ (filled by zero bytes) is faster and uses
less memory for large objects.  ‘calloc()’ is used instead of ‘malloc()’
to allocate memory for these objects.  (Contributed by Victor Stinner in
bpo-21233(2).)

Some operations on *note ipaddress: a2. *note IPv4Network: 4a6. and
*note IPv6Network: 4a5. have been massively sped up, such as *note
subnets(): 886, *note supernet(): 887, *note summarize_address_range():
888, *note collapse_addresses(): 889.  The speed up can range from 3 to
15 times.  (Contributed by Antoine Pitrou, Michel Albert, and Markus in
bpo-21486(3), bpo-21487(4), bpo-20826(5), bpo-23266(6).)

Pickling of *note ipaddress: a2. objects was optimized to produce
significantly smaller output.  (Contributed by Serhiy Storchaka in
bpo-23133(7).)

Many operations on *note io.BytesIO: 88a. are now 50% to 100% faster.
(Contributed by Serhiy Storchaka in bpo-15381(8) and David Wilson in
bpo-22003(9).)

The *note marshal.dumps(): 88b. 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(10) and bpo-23344(11).)

The UTF-32 encoder is now 3 to 7 times faster.  (Contributed by Serhiy
Storchaka in bpo-15027(12).)

Regular expressions are now parsed up to 10% faster.  (Contributed by
Serhiy Storchaka in bpo-19380(13).)

The *note json.dumps(): 6fc. function was optimized to run with
‘ensure_ascii=False’ as fast as with ‘ensure_ascii=True’.  (Contributed
by Naoki Inada in bpo-23206(14).)

The *note PyObject_IsInstance(): 88c. and *note PyObject_IsSubclass():
88d. functions have been sped up in the common case that the second
argument has *note type: 6ff. as its metaclass.  (Contributed Georg
Brandl by in bpo-22540(15).)

Method caching was slightly improved, yielding up to 5% performance
improvement in some benchmarks.  (Contributed by Antoine Pitrou in
bpo-22847(16).)

Objects from the *note random: dc. module now use 50% less memory on
64-bit builds.  (Contributed by Serhiy Storchaka in bpo-23488(17).)

The *note property(): 308. getter calls are up to 25% faster.
(Contributed by Joe Jevnik in bpo-23910(18).)

Instantiation of *note fractions.Fraction: 2be. is now up to 30% faster.
(Contributed by Stefan Behnel in bpo-22464(19).)

String methods *note find(): 88e, *note rfind(): 88f, *note split():
890, *note partition(): 891. and the *note in: 179. string operator are
now significantly faster for searching 1-character substrings.
(Contributed by Serhiy Storchaka in bpo-23573(20).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23605

   (2) https://bugs.python.org/issue21233

   (3) https://bugs.python.org/issue21486

   (4) https://bugs.python.org/issue21487

   (5) https://bugs.python.org/issue20826

   (6) https://bugs.python.org/issue23266

   (7) https://bugs.python.org/issue23133

   (8) https://bugs.python.org/issue15381

   (9) https://bugs.python.org/issue22003

   (10) https://bugs.python.org/issue20416

   (11) https://bugs.python.org/issue23344

   (12) https://bugs.python.org/issue15027

   (13) https://bugs.python.org/issue19380

   (14) https://bugs.python.org/issue23206

   (15) https://bugs.python.org/issue22540

   (16) https://bugs.python.org/issue22847

   (17) https://bugs.python.org/issue23488

   (18) https://bugs.python.org/issue23910

   (19) https://bugs.python.org/issue22464

   (20) https://bugs.python.org/issue23573


File: python.info,  Node: 构建和 C API 的改变<3>,  Next: 弃用<4>,  Prev: 性能优化<5>,  Up: Python 3 5 有什麼新功能

1.5.8 构建和 C API 的改变
-------------------------

增加了 ‘calloc’ 函数

   * *note PyMem_RawCalloc(): 893,

   * *note PyMem_Calloc(): 894,

   * *note PyObject_Calloc(): 895.

(Victor Stinner 贡献于 bpo-21233(1).)

新的 encoding/decoding 帮助函数:

   * *note Py_DecodeLocale(): 53e. (替代 ‘_Py_char2wchar()’),

   * *note Py_EncodeLocale(): 53f. (替代 ‘_Py_wchar2char()’).

（由 Victor Stinner 在 bpo-18395(2) 中贡献。）

A new *note PyCodec_NameReplaceErrors(): 896. function to replace the
unicode encode error with ‘\N{...}’ escapes.  (Contributed by Serhiy
Storchaka in bpo-19676(3).)

A new *note PyErr_FormatV(): 897. function similar to *note
PyErr_Format(): 898, but accepts a ‘va_list’ argument.  (Contributed by
Antoine Pitrou in bpo-18711(4).)

A new ‘PyExc_RecursionError’ exception.  (Contributed by Georg Brandl in
bpo-19235(5).)

New *note PyModule_FromDefAndSpec(): 899, *note
PyModule_FromDefAndSpec2(): 89a, and *note PyModule_ExecDef(): 89b.
functions introduced by PEP 489(6) – multi-phase extension module
initialization.  (Contributed by Petr Viktorin in bpo-24268(7).)

New *note PyNumber_MatrixMultiply(): 89c. and *note
PyNumber_InPlaceMatrixMultiply(): 89d. functions to perform matrix
multiplication.  (Contributed by Benjamin Peterson in bpo-21176(8).  See
also PEP 465(9) for details.)

The *note PyTypeObject.tp_finalize: 3f6. 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(10).

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):

   * On Linux, extension module filenames end with
     ‘.cpython-<major><minor>m-<architecture>-<os>.pyd’:

        * ‘<major>’ is the major number of the Python version; for
          Python 3.5 this is ‘3’.

        * ‘<minor>’ is the minor number of the Python version; for
          Python 3.5 this is ‘5’.

        * ‘<architecture>’ is the hardware architecture the extension
          module was built to run on.  It’s most commonly either ‘i386’
          for 32-bit Intel platforms or ‘x86_64’ for 64-bit Intel (and
          AMD) platforms.

        * ‘<os>’ is always ‘linux-gnu’, except for extensions built to
          talk to the 32-bit ABI on 64-bit platforms, in which case it
          is ‘linux-gnu32’ (and ‘<architecture>’ will be ‘x86_64’).

   * On Windows, extension module filenames end with
     ‘<debug>.cp<major><minor>-<platform>.pyd’:

        * ‘<major>’ is the major number of the Python version; for
          Python 3.5 this is ‘3’.

        * ‘<minor>’ is the minor number of the Python version; for
          Python 3.5 this is ‘5’.

        * ‘<platform>’ is the platform the extension module was built
          for, either ‘win32’ for Win32, ‘win_amd64’ for Win64,
          ‘win_ia64’ for Windows Itanium 64, and ‘win_arm’ for Windows
          on ARM.

        * If built in debug mode, ‘<debug>’ will be ‘_d’, otherwise it
          will be blank.

   * On OS X platforms, extension module filenames now end with
     ‘-darwin.so’.

   * On all other platforms, extension module filenames are the same as
     they were with Python 3.4.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21233

   (2) https://bugs.python.org/issue18395

   (3) https://bugs.python.org/issue19676

   (4) https://bugs.python.org/issue18711

   (5) https://bugs.python.org/issue19235

   (6) https://www.python.org/dev/peps/pep-0489

   (7) https://bugs.python.org/issue24268

   (8) https://bugs.python.org/issue21176

   (9) https://www.python.org/dev/peps/pep-0465

   (10) https://www.visualstudio.com/


File: python.info,  Node: 弃用<4>,  Next: 移除<4>,  Prev: 构建和 C API 的改变<3>,  Up: Python 3 5 有什麼新功能

1.5.9 弃用
----------

* Menu:

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


File: python.info,  Node: 新关键字<2>,  Next: 已弃用的 Python 行为<3>,  Up: 弃用<4>

1.5.9.1 新关键字
................

‘async’ and ‘await’ are not recommended to be used as variable, class,
function or module names.  Introduced by PEP 492(1) in Python 3.5, they
will become proper keywords in Python 3.7.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0492


File: python.info,  Node: 已弃用的 Python 行为<3>,  Next: 不支持的操作系统,  Prev: 新关键字<2>,  Up: 弃用<4>

1.5.9.2 已弃用的 Python 行为
............................

Raising the *note StopIteration: 581. exception inside a generator will
now generate a silent *note PendingDeprecationWarning: 15c, which will
become a non-silent deprecation warning in Python 3.6 and will trigger a
*note RuntimeError: 3dc. in Python 3.7.  See *note PEP 479; Change
StopIteration handling inside generators: 6ce. for details.


File: python.info,  Node: 不支持的操作系统,  Next: 已弃用的 Python 模块、函数和方法<3>,  Prev: 已弃用的 Python 行为<3>,  Up: 弃用<4>

1.5.9.3 不支持的操作系统
........................

Windows XP is no longer supported by Microsoft, thus, per PEP 11(1),
CPython 3.5 is no longer officially supported on this OS.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0011


File: python.info,  Node: 已弃用的 Python 模块、函数和方法<3>,  Prev: 不支持的操作系统,  Up: 弃用<4>

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

The *note formatter: 80. module has now graduated to full deprecation
and is still slated for removal in Python 3.6.

The ‘asyncio.async()’ function is deprecated in favor of *note
ensure_future(): 610.

The *note smtpd: ec. module has in the past always decoded the DATA
portion of email messages using the ‘utf-8’ codec.  This can now be
controlled by the new `decode_data' keyword to *note SMTPServer: 6f9.
The default value is ‘True’, but this default is deprecated.  Specify
the `decode_data' keyword with an appropriate value to avoid the
deprecation warning.

Directly assigning values to the *note key: 588, *note value: 589. and
*note coded_value: 58a. of *note http.cookies.Morsel: 587. objects is
deprecated.  Use the *note set(): 58b. method instead.  In addition, the
undocumented `LegalChars' parameter of *note set(): 58b. is deprecated,
and is now ignored.

Passing a format string as keyword argument `format_string' to the *note
format(): 586. method of the *note string.Formatter: 8a3. class has been
deprecated.  (Contributed by Serhiy Storchaka in bpo-23671(1).)

The ‘platform.dist()’ and ‘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(2).)

The previously undocumented ‘from_function’ and ‘from_builtin’ methods
of *note inspect.Signature: 7e4. are deprecated.  Use the new *note
Signature.from_callable(): 7e7. method instead.  (Contributed by Yury
Selivanov in bpo-24248(3).)

The *note inspect.getargspec(): 656. function is deprecated and
scheduled to be removed in Python 3.6.  (See bpo-20438(4) for details.)

The *note inspect: a0. *note getfullargspec(): 657, *note getcallargs():
8a4, and *note formatargspec(): 8a5. functions are deprecated in favor
of the *note inspect.signature(): 655. API. (Contributed by Yury
Selivanov in bpo-20438(5).)

*note getargvalues(): 8a6. and *note formatargvalues(): 8a7. functions
were inadvertently marked as deprecated with the release of Python
3.5.0.

Use of *note re.LOCALE: 4cf. flag with str patterns or *note re.ASCII:
4ce. is now deprecated.  (Contributed by Serhiy Storchaka in
bpo-22407(6).)

Use of unrecognized special sequences consisting of ‘'\'’ 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(7).)

The undocumented and unofficial `use_load_tests' default argument of the
*note unittest.TestLoader.loadTestsFromModule(): 86f. method now is
deprecated and ignored.  (Contributed by Robert Collins and Barry A.
Warsaw in bpo-16662(8).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23671

   (2) https://bugs.python.org/issue1322

   (3) https://bugs.python.org/issue24248

   (4) https://bugs.python.org/issue20438

   (5) https://bugs.python.org/issue20438

   (6) https://bugs.python.org/issue22407

   (7) https://bugs.python.org/issue23622

   (8) https://bugs.python.org/issue16662


File: python.info,  Node: 移除<4>,  Next: 移植到Python 3 5,  Prev: 弃用<4>,  Up: Python 3 5 有什麼新功能

1.5.10 移除
-----------

* Menu:

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


File: python.info,  Node: API 与特性的移除<4>,  Up: 移除<4>

1.5.10.1 API 与特性的移除
.........................

The following obsolete and previously deprecated APIs and features have
been removed:

   * The ‘__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 ‘__version__’ string was not
     updated in the last few releases.

   * The internal ‘Netrc’ class in the *note ftplib: 82. module was
     deprecated in 3.4, and has now been removed.  (Contributed by Matt
     Chaput in bpo-6623(1).)

   * The concept of ‘.pyo’ files has been removed.

   * The JoinableQueue class in the provisional *note asyncio: 9. module
     was deprecated in 3.4.4 and is now removed.  (Contributed by A.
     Jesse Jiryu Davis in bpo-23464(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue6623

   (2) https://bugs.python.org/issue23464


File: python.info,  Node: 移植到Python 3 5,  Next: Python 3 5 4 的显著变化,  Prev: 移除<4>,  Up: Python 3 5 有什麼新功能

1.5.11 移植到Python 3.5
-----------------------

本节列出了先前描述的更改以及可能需要更改代码的其他错误修正.

* Menu:

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


File: python.info,  Node: Python 行为的改变<2>,  Next: 改变了的Python API,  Up: 移植到Python 3 5

1.5.11.1 Python 行为的改变
..........................

   * 由于一个疏忽，之前的 Python 版本会错误地接受以下语法:

          f(1 for x in [1], *args)
          f(1 for x in [1], **kwargs)

     Python 3.5 now correctly raises a *note SyntaxError: 559, as
     generator expressions must be put in parentheses if not a sole
     argument to a function.


File: python.info,  Node: 改变了的Python API,  Next: C API 中的改变<4>,  Prev: Python 行为的改变<2>,  Up: 移植到Python 3 5

1.5.11.2 改变了的Python API
...........................

   * PEP 475(1): System calls are now retried when interrupted by a
     signal instead of raising *note InterruptedError: 74c. if the
     Python signal handler does not raise an exception.

   * Before Python 3.5, a *note datetime.time: 5ec. 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(2) for full details.

   * The ‘ssl.SSLSocket.send()’ method now raises either *note
     ssl.SSLWantReadError: 845. or *note ssl.SSLWantWriteError: 846. on
     a non-blocking socket if the operation would block.  Previously, it
     would return ‘0’.  (Contributed by Nikolaus Rath in bpo-20951(3).)

   * The ‘__name__’ attribute of generators is now set from the function
     name, instead of being set from the code name.  Use
     ‘gen.gi_code.co_name’ to retrieve the code name.  Generators also
     have a new ‘__qualname__’ attribute, the qualified name, which is
     now used for the representation of a generator (‘repr(gen)’).
     (Contributed by Victor Stinner in bpo-21205(4).)

   * The deprecated "strict" mode and argument of *note HTMLParser: 22a,
     ‘HTMLParser.error()’, and the ‘HTMLParserError’ exception have been
     removed.  (Contributed by Ezio Melotti in bpo-15114(5).)  The
     `convert_charrefs' argument of *note HTMLParser: 22a. is now ‘True’
     by default.  (Contributed by Berker Peksag in bpo-21047(6).)

   * 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 *note bytes-like object: 6df. is
     required, not ’sometype’".  (Contributed by Ezio Melotti in
     bpo-16518(7).)

   * If the current directory is set to a directory that no longer
     exists then *note FileNotFoundError: 8ad. will no longer be raised
     and instead *note find_spec(): 8ae. will return ‘None’ `without'
     caching ‘None’ in *note sys.path_importer_cache: 597, which is
     different than the typical case (bpo-22834(8)).

   * HTTP status code and messages from *note http.client: 93. and *note
     http.server: 96. were refactored into a common *note HTTPStatus:
     1ac. enum.  The values in *note http.client: 93. and *note
     http.server: 96. remain available for backwards compatibility.
     (Contributed by Demian Brecht in bpo-21793(9).)

   * When an import loader defines
     ‘importlib.machinery.Loader.exec_module()’ it is now expected to
     also define ‘create_module()’ (raises a *note DeprecationWarning:
     15a. now, will be an error in Python 3.6).  If the loader inherits
     from *note importlib.abc.Loader: 8af. then there is nothing to do,
     else simply define ‘create_module()’ to return ‘None’.
     (Contributed by Brett Cannon in bpo-23014(10).)

   * The *note re.split(): 4d0. function always ignored empty pattern
     matches, so the ‘"x*"’ pattern worked the same as ‘"x+"’, and the
     ‘"\b"’ pattern never worked.  Now *note re.split(): 4d0. raises a
     warning if the pattern could match an empty string.  For
     compatibility, use patterns that never match an empty string (e.g.
     ‘"x+"’ instead of ‘"x*"’).  Patterns that could only match an empty
     string (such as ‘"\b"’) now raise an error.  (Contributed by Serhiy
     Storchaka in bpo-22818(11).)

   * The *note http.cookies.Morsel: 587. dict-like interface has been
     made self consistent: morsel comparison now takes the *note key:
     588. and *note value: 589. into account, *note copy(): 8b0. now
     results in a *note Morsel: 587. instance rather than a *note dict:
     164, and *note update(): 8b1. will now raise an exception if any of
     the keys in the update dictionary are invalid.  In addition, the
     undocumented `LegalChars' parameter of *note set(): 58b. is
     deprecated and is now ignored.  (Contributed by Demian Brecht in
     bpo-2211(12).)

   * PEP 488(13) has removed ‘.pyo’ files from Python and introduced the
     optional ‘opt-’ tag in ‘.pyc’ file names.  The *note
     importlib.util.cache_from_source(): 651. has gained an
     `optimization' parameter to help control the ‘opt-’ tag.  Because
     of this, the `debug_override' parameter of the function is now
     deprecated.  ‘.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 ‘.pyo’ files from previous versions of Python
     are invalid regardless of this PEP.

   * The *note socket: ef. module now exports the *note
     CAN_RAW_FD_FRAMES: 8b2. constant on linux 3.6 and greater.

   * The *note ssl.cert_time_to_seconds(): 847. function now interprets
     the input time as UTC and not as local time, per RFC 5280(14).
     Additionally, the return value is always an *note int: 204.
     (Contributed by Akira Li in bpo-19940(15).)

   * The ‘pygettext.py’ Tool now uses the standard +NNNN format for
     timezones in the POT-Creation-Date header.

   * The *note smtplib: ed. module now uses *note sys.stderr: 1ea.
     instead of the previous module-level ‘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.

   * The *note str.startswith(): 8b3. and *note str.endswith(): 8b4.
     methods no longer return ‘True’ when finding the empty string and
     the indexes are completely out of range.  (Contributed by Serhiy
     Storchaka in bpo-24284(16).)

   * The *note inspect.getdoc(): 307. 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 *note pydoc: d9. module and the *note
     help(): 175. function.  (Contributed by Serhiy Storchaka in
     bpo-15582(17).)

   * Nested *note functools.partial(): 8b5. calls are now flattened.  If
     you were relying on the previous behavior, you can now either add
     an attribute to a *note functools.partial(): 8b5. object or you can
     create a subclass of *note functools.partial(): 8b5.  (Contributed
     by Alexander Belopolsky in bpo-7830(18).)

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0475

   (2) https://bugs.python.org/issue13936

   (3) https://bugs.python.org/issue20951

   (4) https://bugs.python.org/issue21205

   (5) https://bugs.python.org/issue15114

   (6) https://bugs.python.org/issue21047

   (7) https://bugs.python.org/issue16518

   (8) https://bugs.python.org/issue22834

   (9) https://bugs.python.org/issue21793

   (10) https://bugs.python.org/issue23014

   (11) https://bugs.python.org/issue22818

   (12) https://bugs.python.org/issue2211

   (13) https://www.python.org/dev/peps/pep-0488

   (14) https://tools.ietf.org/html/rfc5280.html

   (15) https://bugs.python.org/issue19940

   (16) https://bugs.python.org/issue24284

   (17) https://bugs.python.org/issue15582

   (18) https://bugs.python.org/issue7830


File: python.info,  Node: C API 中的改变<4>,  Prev: 改变了的Python API,  Up: 移植到Python 3 5

1.5.11.3 C API 中的改变
.......................

   * The undocumented ‘format’ member of the (non-public)
     ‘PyMemoryViewObject’ structure has been removed.  All extensions
     relying on the relevant parts in ‘memoryobject.h’ must be rebuilt.

   * The ‘PyMemAllocator’ structure was renamed to *note
     PyMemAllocatorEx: 8b7. and a new ‘calloc’ field was added.

   * Removed non-documented macro ‘PyObject_REPR’ which leaked
     references.  Use format character ‘%R’ in *note
     PyUnicode_FromFormat(): 8b8.-like functions to format the *note
     repr(): 8b9. of the object.  (Contributed by Serhiy Storchaka in
     bpo-22453(1).)

   * Because the lack of the ‘__module__’ attribute breaks pickling and
     introspection, a deprecation warning is now raised for builtin
     types without the ‘__module__’ attribute.  This would be an
     AttributeError in the future.  (Contributed by Serhiy Storchaka in
     bpo-20204(2).)

   * As part of the PEP 492(3) implementation, the ‘tp_reserved’ slot of
     *note PyTypeObject: 3f5. was replaced with a ‘tp_as_async’ slot.
     Refer to *note 协程对象: 8ba. for new types, structures and
     functions.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22453

   (2) https://bugs.python.org/issue20204

   (3) https://www.python.org/dev/peps/pep-0492


File: python.info,  Node: Python 3 5 4 的显著变化,  Prev: 移植到Python 3 5,  Up: Python 3 5 有什麼新功能

1.5.12 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>.


File: python.info,  Node: New make regen-all build target<2>,  Next: Removal of make touch build target<2>,  Up: Python 3 5 4 的显著变化

1.5.12.1 New ‘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 ‘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(1) for details.

（由 Victor Stinner 在 bpo-23404(2) 中贡献。）

3.5.4 版新加入.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Makefile.pre.in

   (2) https://bugs.python.org/issue23404


File: python.info,  Node: Removal of make touch build target<2>,  Prev: New make regen-all build target<2>,  Up: Python 3 5 4 的显著变化

1.5.12.2 Removal of ‘make touch’ build target
.............................................

The ‘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 ‘make regen-all’ target.

（由 Victor Stinner 在 bpo-23404(1) 中贡献。）

3.5.4 版更變.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23404


File: python.info,  Node: Python 3 4 有什么新变化,  Next: Python 3 3 有什么新变化,  Prev: Python 3 5 有什麼新功能,  Up: Python 有什麼新功能？

1.6 Python 3.4 有什么新变化
===========================


作者: R. David Murray <<rdmurray@bitdance.com>> (Editor)

This article explains the new features in Python 3.4, compared to 3.3.
Python 3.4 was released on March 16, 2014.  For full details, see the
changelog(1).

也參考
......

PEP 429(2) – 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 的变化.

   ---------- Footnotes ----------

   (1) https://docs.python.org/3.4/whatsnew/changelog.html

   (2) https://www.python.org/dev/peps/pep-0429


File: python.info,  Node: 摘要 - 发布重点<6>,  Next: 新的特性<7>,  Up: Python 3 4 有什么新变化

1.6.1 摘要 - 发布重点
---------------------

新的语法特性：

   * No new syntax features were added in Python 3.4.

其他的新特性

   * *note pip 能够随时可用: 8c1. ( PEP 453(1)).

   * *note Newly created file descriptors are non-inheritable: 8c2. (
     PEP 446(2)).

   * command line option for *note isolated mode: 8c3. (bpo-16499(3)).

   * *note improvements in the handling of codecs: 8c4. that are not
     text encodings (multiple issues).

   * *note A ModuleSpec Type: 8c5. for the Import System ( PEP 451(4)).
     (Affects importer authors.)

   * The *note marshal: b0. format has been made *note more compact and
     efficient: 8c6. (bpo-16475(5)).

新的库模块：

   * *note asyncio: 9.: *note New provisional API for asynchronous IO:
     8c7. ( PEP 3156(6)).

   * *note ensurepip: 78.: *note Bootstrapping the pip installer: 8c8. (
     PEP 453(7)).

   * *note enum: 79.: *note Support for enumeration types: 8c9. ( PEP
     435(8)).

   * *note pathlib: c8.: *note Object-oriented filesystem paths: 8ca. (
     PEP 428(9)).

   * *note selectors: e6.: *note High-level and efficient I/O
     multiplexing: 8cb, built upon the *note select: e5. module
     primitives (part of PEP 3156(10)).

   * *note statistics: f5.: A basic *note numerically stable statistics
     library: 8cc. ( PEP 450(11)).

   * *note tracemalloc: 11d.: *note Trace Python memory allocations:
     8cd. ( PEP 454(12)).

Significantly improved library modules:

   * *note Single-dispatch generic functions: 8ce. in *note functools:
     83. ( PEP 443(13)).

   * New *note pickle: ca. *note protocol 4: 8cf. ( PEP 3154(14)).

   * *note multiprocessing: b7. now has *note an option to avoid using
     os.fork on Unix: 8d0. (bpo-8713(15)).

   * *note email: 67. has a new submodule, *note contentmanager: 69, and
     a new *note Message: 63b. subclass (‘EmailMessage’) that *note
     simplify MIME handling: 8d1. (bpo-18891(16)).

   * The *note inspect: a0. and *note pydoc: d9. modules are now capable
     of correct introspection of a much wider variety of callable
     objects, which improves the output of the Python *note help(): 175.
     system.

   * The *note ipaddress: a2. module API has been declared stable

安全改进：

   * *note Secure and interchangeable hash algorithm: 8d2. ( PEP
     456(17)).

   * *note Make newly created file descriptors non-inheritable: 8c2. (
     PEP 446(18)) to avoid leaking file descriptors to child processes.

   * New command line option for *note isolated mode: 8c3,
     (bpo-16499(19)).

   * *note multiprocessing: b7. now has *note an option to avoid using
     os.fork on Unix: 8d0.  `spawn' and `forkserver' are more secure
     because they avoid sharing data with child processes.

   * *note multiprocessing: b7. child processes on Windows no longer
     inherit all of the parent’s inheritable handles, only the necessary
     ones.

   * A new *note hashlib.pbkdf2_hmac(): 8d3. function provides the
     PKCS#5 password-based key derivation function 2(20).

   * *note TLSv1.1 and TLSv1.2 support: 8d4. for *note ssl: f3.

   * *note Retrieving certificates from the Windows system cert store
     support: 8d5. for *note ssl: f3.

   * *note Server-side SNI (Server Name Indication) support: 8d6. for
     *note ssl: f3.

   * The *note ssl.SSLContext: 4e9. class has a *note lot of
     improvements: 8d7.

   * All modules in the standard library that support SSL now support
     server certificate verification, including hostname matching (*note
     ssl.match_hostname(): 4e2.) and CRLs (Certificate Revocation lists,
     see *note ssl.SSLContext.load_verify_locations(): 8d8.).

CPython 实现的改进：

   * *note Safe object finalization: 8d9. ( PEP 442(21)).

   * Leveraging PEP 442(22), in most cases *note module globals are no
     longer set to None during finalization: 8d9. (bpo-18214(23)).

   * *note Configurable memory allocators: 8da. ( PEP 445(24)).

   * *note Argument Clinic: 8db. ( PEP 436(25)).

Please read on for a comprehensive list of user-facing changes,
including many other smaller improvements, CPython optimizations,
deprecations, and potential porting issues.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0453

   (2) https://www.python.org/dev/peps/pep-0446

   (3) https://bugs.python.org/issue16499

   (4) https://www.python.org/dev/peps/pep-0451

   (5) https://bugs.python.org/issue16475

   (6) https://www.python.org/dev/peps/pep-3156

   (7) https://www.python.org/dev/peps/pep-0453

   (8) https://www.python.org/dev/peps/pep-0435

   (9) https://www.python.org/dev/peps/pep-0428

   (10) https://www.python.org/dev/peps/pep-3156

   (11) https://www.python.org/dev/peps/pep-0450

   (12) https://www.python.org/dev/peps/pep-0454

   (13) https://www.python.org/dev/peps/pep-0443

   (14) https://www.python.org/dev/peps/pep-3154

   (15) https://bugs.python.org/issue8713

   (16) https://bugs.python.org/issue18891

   (17) https://www.python.org/dev/peps/pep-0456

   (18) https://www.python.org/dev/peps/pep-0446

   (19) https://bugs.python.org/issue16499

   (20) https://en.wikipedia.org/wiki/PBKDF2

   (21) https://www.python.org/dev/peps/pep-0442

   (22) https://www.python.org/dev/peps/pep-0442

   (23) https://bugs.python.org/issue18214

   (24) https://www.python.org/dev/peps/pep-0445

   (25) https://www.python.org/dev/peps/pep-0436


File: python.info,  Node: 新的特性<7>,  Next: 新增模块<6>,  Prev: 摘要 - 发布重点<6>,  Up: Python 3 4 有什么新变化

1.6.2 新的特性
--------------

* 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>.


File: python.info,  Node: PEP 453 Explicit Bootstrapping of PIP in Python Installations,  Next: PEP 446 Newly Created File Descriptors Are Non-Inheritable,  Up: 新的特性<7>

1.6.2.1 PEP 453: Explicit Bootstrapping of PIP in Python Installations
......................................................................

* Menu:

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


File: python.info,  Node: Bootstrapping pip By Default,  Next: 文档更改,  Up: PEP 453 Explicit Bootstrapping of PIP in Python Installations

1.6.2.2 Bootstrapping pip By Default
....................................

The new *note ensurepip: 78. module (defined in PEP 453(1)) provides a
standard cross-platform mechanism to bootstrap the pip installer into
Python installations and virtual environments.  The version of ‘pip’
included with Python 3.4.0 is ‘pip’ 1.5.4, and future 3.4.x maintenance
releases will update the bundled version to the latest version of ‘pip’
that is available at the time of creating the release candidate.

By default, the commands ‘pipX’ and ‘pipX.Y’ will be installed on all
platforms (where X.Y stands for the version of the Python installation),
along with the ‘pip’ Python package and its dependencies.  On Windows
and in virtual environments on all platforms, the unversioned ‘pip’
command will also be installed.  On other platforms, the system wide
unversioned ‘pip’ command typically refers to the separately installed
Python 2 version.

The ‘pyvenv’ command line utility and the *note venv: 12e. module make
use of the *note ensurepip: 78. module to make ‘pip’ readily available
in virtual environments.  When using the command line utility, ‘pip’ is
installed by default, while when using the *note venv: 12e. module *note
API: 8df. installation of ‘pip’ must be requested explicitly.

For CPython *note source builds on POSIX systems: 8e0, the ‘make
install’ and ‘make altinstall’ commands bootstrap ‘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 ‘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 ‘PATH’ modifications to have ‘pip’ available
from the command line by default, otherwise it can still be accessed
through the Python launcher for Windows as ‘py -m pip’.

As discussed in the PEP(2), 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).

     備註: To avoid conflicts between parallel Python 2 and Python 3
     installations, only the versioned ‘pip3’ and ‘pip3.4’ commands are
     bootstrapped by default when ‘ensurepip’ is invoked directly - the
     ‘--default-pip’ option is needed to also request the unversioned
     ‘pip’ command.  ‘pyvenv’ and the Windows installer ensure that the
     unqualified ‘pip’ command is made available in those environments,
     and ‘pip’ can always be invoked via the ‘-m’ switch rather than
     directly to avoid ambiguity on systems with multiple Python
     installations.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0453

   (2) 
https://www.python.org/dev/peps/pep-0453/#recommendations-for-downstream-distributors


File: python.info,  Node: 文档更改,  Prev: Bootstrapping pip By Default,  Up: PEP 453 Explicit Bootstrapping of PIP in Python Installations

1.6.2.3 文档更改
................

As part of this change, the *note 安裝 Python 模組: 8e2. and *note 發布
Python 模組: 8e3. 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(1) and the documentation of the
individual projects.

However, as this migration is currently still incomplete, the legacy
versions of those guides remaining available as *note 安裝 Python
模組（舊版）: 8e4. and *note 發布 Python 模組（舊版）: 8e5.

也參考
......

PEP 453(2) – Python安装中pip的显式引导

     PEP 由Donald Stufft 和 Nick Coghlan 撰写，由 Donald Stufft，Nick
     Coghlan，Martin von Löwis 和 Ned Deily 实现。

   ---------- Footnotes ----------

   (1) https://packaging.python.org

   (2) https://www.python.org/dev/peps/pep-0453


File: python.info,  Node: PEP 446 Newly Created File Descriptors Are Non-Inheritable,  Next: Improvements to Codec Handling,  Prev: PEP 453 Explicit Bootstrapping of PIP in Python Installations,  Up: 新的特性<7>

1.6.2.4 PEP 446: Newly Created File Descriptors Are Non-Inheritable
...................................................................

PEP 446(1) makes newly created file descriptors *note non-inheritable:
8e7.  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:

   * *note os.get_inheritable(): 8e8, *note os.set_inheritable(): 8e9.

   * *note os.get_handle_inheritable(): 8ea, *note
     os.set_handle_inheritable(): 8eb.

   * *note socket.socket.get_inheritable(): 8ec, *note
     socket.socket.set_inheritable(): 8ed.

也參考
......

PEP 446(2) – Make newly created file descriptors non-inheritable

     PEP 由 Victor Stinner 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0446

   (2) https://www.python.org/dev/peps/pep-0446


File: python.info,  Node: Improvements to Codec Handling,  Next: PEP 451 A ModuleSpec Type for the Import System,  Prev: PEP 446 Newly Created File Descriptors Are Non-Inheritable,  Up: 新的特性<7>

1.6.2.5 Improvements to Codec Handling
......................................

Since it was first introduced, the *note codecs: 1b. 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 *note
str: 205, *note bytes: 172. and *note bytearray: 173. types, has
historically obscured that fact.

As a key step in clarifying the situation, the *note codecs.encode():
8ef. and *note codecs.decode(): 8f0. convenience functions are now
properly documented in Python 2.7, 3.3 and 3.4.  These functions have
existed in the *note codecs: 1b. 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 *note str: 205, *note bytes: 172. and
*note bytearray: 173, the *note codecs: 1b. convenience functions
support arbitrary codecs in both Python 2 and Python 3, rather than
being limited to Unicode text encodings (in Python 3) or ‘basestring’
<-> ‘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:

     >>> 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

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:

     >>> 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)

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:

     >>> from codecs import encode, decode
     >>> encode(b"hello", "hex")
     b'68656c6c6f'
     >>> decode(b"68656c6c6f", "hex")
     b'hello'

The binary and text transforms provided in the standard library are
detailed in *note 二进制转换: 8f1. and *note 文字转换: 8f2.

(Contributed by Nick Coghlan in bpo-7475(1), bpo-17827(2), bpo-17828(3)
and bpo-19619(4).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue7475

   (2) https://bugs.python.org/issue17827

   (3) https://bugs.python.org/issue17828

   (4) https://bugs.python.org/issue19619


File: python.info,  Node: PEP 451 A ModuleSpec Type for the Import System,  Next: 其他语言特性修改<6>,  Prev: Improvements to Codec Handling,  Up: 新的特性<7>

1.6.2.6 PEP 451: A ModuleSpec Type for the Import System
........................................................

PEP 451(1) 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(2).

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 *note 弃用: 8f4. section for a list of methods
that should be replaced and their replacements.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0451

   (2) 
https://mail.python.org/pipermail/python-dev/2013-November/130111.html


File: python.info,  Node: 其他语言特性修改<6>,  Prev: PEP 451 A ModuleSpec Type for the Import System,  Up: 新的特性<7>

1.6.2.7 其他语言特性修改
........................

对Python 语言核心进行的小改动：

   * Unicode database updated to UCD version 6.3.

   * *note min(): 8f6. and *note max(): 8f7. now accept a `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(1).)

   * Module objects are now *note weakref: 131.’able.

   * Module ‘__file__’ attributes (and related values) should now always
     contain absolute paths by default, with the sole exception of
     ‘__main__.__file__’ when a script has been executed directly using
     a relative path.  (Contributed by Brett Cannon in bpo-18416(2).)

   * All the UTF-* codecs (except UTF-7) now reject surrogates during
     both encoding and decoding unless the ‘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(3).)

   * New German EBCDIC *note codec: 782. ‘cp273’.  (Contributed by
     Michael Bierenfeld and Andrew Kuchling in bpo-1097797(4).)

   * New Ukrainian *note codec: 782. ‘cp1125’.  (Contributed by Serhiy
     Storchaka in bpo-19668(5).)

   * *note bytes: 172.join() and *note bytearray: 173.join() now accept
     arbitrary buffer objects as arguments.  (Contributed by Antoine
     Pitrou in bpo-15958(6).)

   * The *note int: 204. constructor now accepts any object that has an
     ‘__index__’ method for its `base' argument.  (Contributed by Mark
     Dickinson in bpo-16772(7).)

   * Frame objects now have a *note clear(): 8f8. method that clears all
     references to local variables from the frame.  (Contributed by
     Antoine Pitrou in bpo-17934(8).)

   * *note memoryview: 386. is now registered as a *note Sequence: 1e,
     and supports the *note reversed(): 2c6. builtin.  (Contributed by
     Nick Coghlan and Claudiu Popa in bpo-18690(9) and bpo-19078(10).)

   * Signatures reported by *note help(): 175. have been modified and
     improved in several cases as a result of the introduction of
     Argument Clinic and other changes to the *note inspect: a0. and
     *note pydoc: d9. modules.

   * *note __length_hint__(): 8f9. is now part of the formal language
     specification (see PEP 424(11)).  (Contributed by Armin Ronacher in
     bpo-16148(12).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18111

   (2) https://bugs.python.org/issue18416

   (3) https://bugs.python.org/issue12892

   (4) https://bugs.python.org/issue1097797

   (5) https://bugs.python.org/issue19668

   (6) https://bugs.python.org/issue15958

   (7) https://bugs.python.org/issue16772

   (8) https://bugs.python.org/issue17934

   (9) https://bugs.python.org/issue18690

   (10) https://bugs.python.org/issue19078

   (11) https://www.python.org/dev/peps/pep-0424

   (12) https://bugs.python.org/issue16148


File: python.info,  Node: 新增模块<6>,  Next: 改进的模块<6>,  Prev: 新的特性<7>,  Up: Python 3 4 有什么新变化

1.6.3 新增模块
--------------

* Menu:

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


File: python.info,  Node: asyncio<7>,  Next: ensurepip,  Up: 新增模块<6>

1.6.3.1 asyncio
...............

The new *note asyncio: 9. module (defined in PEP 3156(1)) 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 *note provisional API: 454.

也參考
......

PEP 3156(2) – Asynchronous IO Support Rebooted: the "asyncio" Module

     PEP 由 Guido van Rossum 领导编写和实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3156

   (2) https://www.python.org/dev/peps/pep-3156


File: python.info,  Node: ensurepip,  Next: enum<5>,  Prev: asyncio<7>,  Up: 新增模块<6>

1.6.3.2 ensurepip
.................

The new *note ensurepip: 78. module is the primary infrastructure for
the PEP 453(1) 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 ‘pip’ if the automated bootstrapping into an
installation or virtual environment was declined.

*note ensurepip: 78. includes a bundled copy of ‘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).
‘ensurepip’ does not access the internet.  If the installation has
Internet access, after ‘ensurepip’ is run the bundled ‘pip’ can be used
to upgrade ‘pip’ to a more recent release than the bundled one.  (Note
that such an upgraded version of ‘pip’ is considered to be a separately
installed package and will not be removed if Python is uninstalled.)

The module is named `ensure'pip because if called when ‘pip’ is already
installed, it does nothing.  It also has an ‘--upgrade’ option that will
cause it to install the bundled copy of ‘pip’ if the existing installed
version of ‘pip’ is older than the bundled copy.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0453


File: python.info,  Node: enum<5>,  Next: pathlib<6>,  Prev: ensurepip,  Up: 新增模块<6>

1.6.3.3 enum
............

The new *note enum: 79. module (defined in PEP 435(1)) provides a
standard implementation of enumeration types, allowing other modules
(such as *note socket: ef.) to provide more informative error messages
and better debugging support by replacing opaque integer constants with
backwards compatible enumeration values.

也參考
......

PEP 435(2) – Adding an Enum type to the Python standard library

     PEP 由 Barry Warsaw，Eli Bendersky 和 Ethan Furman 撰写 ，由 Ethan
     Furman 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0435

   (2) https://www.python.org/dev/peps/pep-0435


File: python.info,  Node: pathlib<6>,  Next: selectors<2>,  Prev: enum<5>,  Up: 新增模块<6>

1.6.3.4 pathlib
...............

The new *note pathlib: c8. module offers classes representing filesystem
paths with semantics appropriate for different operating systems.  Path
classes are divided between `pure paths', which provide purely
computational operations without I/O, and `concrete paths', which
inherit from pure paths but also provide I/O operations.

For Python 3.4, this module is considered a *note provisional API: 454.

也參考
......

PEP 428(1) – The pathlib module – object-oriented filesystem paths

     PEP 由 Antoine Pitrou 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0428


File: python.info,  Node: selectors<2>,  Next: statistics<3>,  Prev: pathlib<6>,  Up: 新增模块<6>

1.6.3.5 selectors
.................

The new *note selectors: e6. module (created as part of implementing PEP
3156(1)) allows high-level and efficient I/O multiplexing, built upon
the *note select: e5. module primitives.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3156


File: python.info,  Node: statistics<3>,  Next: tracemalloc<4>,  Prev: selectors<2>,  Up: 新增模块<6>

1.6.3.6 statistics
..................

The new *note statistics: f5. module (defined in PEP 450(1)) 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.

也參考
......

PEP 450(2) – Adding A Statistics Module To The Standard Library

     PEP 由 Steven D’Aprano 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0450

   (2) https://www.python.org/dev/peps/pep-0450


File: python.info,  Node: tracemalloc<4>,  Prev: statistics<3>,  Up: 新增模块<6>

1.6.3.7 tracemalloc
...................

The new *note tracemalloc: 11d. module (defined in PEP 454(1)) is a
debug tool to trace memory blocks allocated by Python.  It provides the
following information:

   * Trace where an object was allocated

   * Statistics on allocated memory blocks per filename and per line
     number: total size, number and average size of allocated memory
     blocks

   * Compute the differences between two snapshots to detect memory
     leaks

也參考
......

PEP 454(2) – Add a new tracemalloc module to trace Python memory allocations

     PEP 由 Victor Stinner 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0454

   (2) https://www.python.org/dev/peps/pep-0454


File: python.info,  Node: 改进的模块<6>,  Next: CPython Implementation Changes,  Prev: 新增模块<6>,  Up: Python 3 4 有什么新变化

1.6.4 改进的模块
----------------

* 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<3>.
* 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>.


File: python.info,  Node: abc,  Next: aifc<2>,  Up: 改进的模块<6>

1.6.4.1 abc
...........

New function *note abc.get_cache_token(): 904. 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(1).)

New class *note ABC: 905. has *note ABCMeta: 906. as its meta class.
Using ‘ABC’ as a base class has essentially the same effect as
specifying ‘metaclass=abc.ABCMeta’, but is simpler to type and easier to
read.  (Contributed by Bruno Dupuis in bpo-16049(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16832

   (2) https://bugs.python.org/issue16049


File: python.info,  Node: aifc<2>,  Next: argparse<3>,  Prev: abc,  Up: 改进的模块<6>

1.6.4.2 aifc
............

The *note getparams(): 908. method now returns a namedtuple rather than
a plain tuple.  (Contributed by Claudiu Popa in bpo-17818(1).)

*note aifc.open(): 55c. now supports the context management protocol:
when used in a *note with: 7da. block, the *note close(): 909. method of
the returned object will be called automatically at the end of the
block.  (Contributed by Serhiy Storchacha in bpo-16486(2).)

The *note writeframesraw(): 90a. and *note writeframes(): 90b. methods
now accept any *note bytes-like object: 6df.  (Contributed by Serhiy
Storchaka in bpo-8311(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17818

   (2) https://bugs.python.org/issue16486

   (3) https://bugs.python.org/issue8311


File: python.info,  Node: argparse<3>,  Next: audioop,  Prev: aifc<2>,  Up: 改进的模块<6>

1.6.4.3 argparse
................

The *note FileType: 90d. class now accepts `encoding' and `errors'
arguments, which are passed through to *note open(): 16f.  (Contributed
by Lucas Maystre in bpo-11175(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue11175


File: python.info,  Node: audioop,  Next: base64,  Prev: argparse<3>,  Up: 改进的模块<6>

1.6.4.4 audioop
...............

*note audioop: c. now supports 24-bit samples.  (Contributed by Serhiy
Storchaka in bpo-12866(1).)

New *note byteswap(): 90f. function converts big-endian samples to
little-endian and vice versa.  (Contributed by Serhiy Storchaka in
bpo-19641(2).)

All *note audioop: c. functions now accept any *note bytes-like object:
6df.  Strings are not accepted: they didn’t work before, now they raise
an error right away.  (Contributed by Serhiy Storchaka in bpo-16685(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue12866

   (2) https://bugs.python.org/issue19641

   (3) https://bugs.python.org/issue16685


File: python.info,  Node: base64,  Next: collections<6>,  Prev: audioop,  Up: 改进的模块<6>

1.6.4.5 base64
..............

The encoding and decoding functions in *note base64: d. now accept any
*note bytes-like object: 6df. in cases where it previously required a
*note bytes: 172. or *note bytearray: 173. instance.  (Contributed by
Nick Coghlan in bpo-17839(1).)

New functions *note a85encode(): 911, *note a85decode(): 912, *note
b85encode(): 913, and *note b85decode(): 914. provide the ability to
encode and decode binary data from and to ‘Ascii85’ and the
git/mercurial ‘Base85’ formats, respectively.  The ‘a85’ functions have
options that can be used to make them compatible with the variants of
the ‘Ascii85’ encoding, including the Adobe variant.  (Contributed by
Martin Morrison, the Mercurial project, Serhiy Storchaka, and Antoine
Pitrou in bpo-17618(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17839

   (2) https://bugs.python.org/issue17618


File: python.info,  Node: collections<6>,  Next: colorsys,  Prev: base64,  Up: 改进的模块<6>

1.6.4.6 collections
...................

The *note ChainMap.new_child(): 916. method now accepts an `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(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16613


File: python.info,  Node: colorsys,  Next: contextlib<4>,  Prev: collections<6>,  Up: 改进的模块<6>

1.6.4.7 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(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue14323


File: python.info,  Node: contextlib<4>,  Next: dbm<5>,  Prev: colorsys,  Up: 改进的模块<6>

1.6.4.8 contextlib
..................

The new *note contextlib.suppress: 919. context manager helps to clarify
the intent of code that deliberately suppresses exceptions from a single
statement.  (Contributed by Raymond Hettinger in bpo-15806(1) and Zero
Piraeus in bpo-19266(2).)

The new *note contextlib.redirect_stdout(): 7b5. context manager makes
it easier for utility scripts to handle inflexible APIs that write their
output to *note sys.stdout: 41f. and don’t provide any options to
redirect it.  Using the context manager, the *note sys.stdout: 41f.
output can be redirected to any other stream or, in conjunction with
*note io.StringIO: 91a, 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 *note sys.stdout:
41f.  (Contributed by Raymond Hettinger in bpo-15805(3).)

The *note contextlib: 23. documentation has also been updated to include
a *note discussion: 91b. of the differences between single use, reusable
and reentrant context managers.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15806

   (2) https://bugs.python.org/issue19266

   (3) https://bugs.python.org/issue15805


File: python.info,  Node: dbm<5>,  Next: dis<2>,  Prev: contextlib<4>,  Up: 改进的模块<6>

1.6.4.9 dbm
...........

*note dbm.open(): 91d. objects now support the context management
protocol.  When used in a *note with: 7da. statement, the ‘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(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue19282


File: python.info,  Node: dis<2>,  Next: doctest<2>,  Prev: dbm<5>,  Up: 改进的模块<6>

1.6.4.10 dis
............

Functions *note show_code(): 91f, *note dis(): 48a, *note distb(): 920,
and *note disassemble(): 921. now accept a keyword-only `file' argument
that controls where they write their output.

The *note dis: 37. module is now built around an *note Instruction: 922.
class that provides object oriented access to the details of each
individual bytecode operation.

A new method, *note get_instructions(): 923, 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 *note dis:
37. module itself.  For example:

     >>> import dis
     >>> for instr in dis.get_instructions(lambda x: x + 1):
     ...     print(instr.opname)
     LOAD_FAST
     LOAD_CONST
     BINARY_ADD
     RETURN_VALUE

The various display tools in the *note dis: 37. module have been
rewritten to use these new components.

In addition, a new application-friendly class *note Bytecode: 924.
provides an object-oriented API for inspecting bytecode in both in
human-readable form and for iterating over instructions.  The *note
Bytecode: 924. constructor takes the same arguments that
‘get_instruction()’ does (plus an optional `current_offset'), and the
resulting object can be iterated to produce *note Instruction: 922.
objects.  But it also has a *note dis: 925. method, equivalent to
calling *note dis: 48a. on the constructor argument, but returned as a
multi-line string:

     >>> 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']

*note Bytecode: 924. also has a class method, *note from_traceback():
926, that provides the ability to manipulate a traceback (that is,
‘print(Bytecode.from_traceback(tb).dis())’ is equivalent to
‘distb(tb)’).

(Contributed by Nick Coghlan, Ryan Kelly and Thomas Kluyver in
bpo-11816(1) and Claudiu Popa in bpo-17916(2).)

New function *note stack_effect(): 927. 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(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue11816

   (2) https://bugs.python.org/issue17916

   (3) https://bugs.python.org/issue19722


File: python.info,  Node: doctest<2>,  Next: email<3>,  Prev: dis<2>,  Up: 改进的模块<6>

1.6.4.11 doctest
................

A new *note option flag: 929, *note FAIL_FAST: 92a, halts test running
as soon as the first failure is detected.  (Contributed by R. David
Murray and Daniel Urban in bpo-16522(1).)

The *note doctest: 66. command line interface now uses *note argparse:
5, and has two new options, ‘-o’ and ‘-f’.  ‘-o’ allows *note doctest
options: 929. to be specified on the command line, and ‘-f’ is a
shorthand for ‘-o FAIL_FAST’ (to parallel the similar option supported
by the *note unittest: 124. CLI). (Contributed by R. David Murray in
bpo-11390(2).)

*note doctest: 66. will now find doctests in extension module ‘__doc__’
strings.  (Contributed by Zachary Ware in bpo-3158(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16522

   (2) https://bugs.python.org/issue11390

   (3) https://bugs.python.org/issue3158


File: python.info,  Node: email<3>,  Next: filecmp,  Prev: doctest<2>,  Up: 改进的模块<6>

1.6.4.12 email
..............

*note as_string(): 92c. now accepts a `policy' argument to override the
default policy of the message when generating a string representation of
it.  This means that ‘as_string’ can now be used in more circumstances,
instead of having to create and use a *note generator: 6c. in order to
pass formatting parameters to its ‘flatten’ method.  (Contributed by R.
David Murray in bpo-18600(1).)

New method *note as_bytes(): 92d. added to produce a bytes
representation of the message in a fashion similar to how ‘as_string’
produces a string representation.  It does not accept the `maxheaderlen'
argument, but does accept the `unixfrom' and `policy' arguments.  The
*note Message: 63b. *note __bytes__(): 92e. method calls it, meaning
that ‘bytes(mymsg)’ will now produce the intuitive result: a bytes
object containing the fully formatted message.  (Contributed by R. David
Murray in bpo-18600(2).)

The *note Message.set_param(): 92f. message now accepts a `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 ‘False’.  (Contributed by R. David Murray
in bpo-18891(3).)  A pair of new subclasses of *note Message: 63b. have
been added (*note EmailMessage: 63c. and *note MIMEPart: 930.), along
with a new sub-module, *note contentmanager: 69. and a new *note policy:
73. attribute *note content_manager: 931.  All documentation is
currently in the new module, which is being added as part of email’s new
*note provisional API: 454.  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 *note contentmanager:
69. documentation and the *note email; 示例: 932.  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(4).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18600

   (2) https://bugs.python.org/issue18600

   (3) https://bugs.python.org/issue18891

   (4) https://bugs.python.org/issue18891


File: python.info,  Node: filecmp,  Next: functools<4>,  Prev: email<3>,  Up: 改进的模块<6>

1.6.4.13 filecmp
................

A new *note clear_cache(): 934. function provides the ability to clear
the *note filecmp: 7d. comparison cache, which uses *note os.stat():
321. 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(1).)

New module attribute *note DEFAULT_IGNORES: 935. provides the list of
directories that are used as the default value for the `ignore'
parameter of the *note dircmp(): 936. function.  (Contributed by Eli
Bendersky in bpo-15442(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18149

   (2) https://bugs.python.org/issue15442


File: python.info,  Node: functools<4>,  Next: gc<4>,  Prev: filecmp,  Up: 改进的模块<6>

1.6.4.14 functools
..................

The new *note partialmethod(): 3bf. descriptor brings partial argument
application to descriptors, just as *note partial(): 8b5. provides for
normal callables.  The new descriptor also makes it easier to get
arbitrary callables (including *note partial(): 8b5. instances) to
behave like normal instance methods when included in a class definition.
(Contributed by Alon Horev and Nick Coghlan in bpo-4331(1).)  The new
*note singledispatch(): 490. 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
`different' kinds of data.

也參考
......

PEP 443(2) – Single-dispatch generic functions

     PEP 由 Łukasz Langa 撰写并实现。

*note total_ordering(): 938. now supports a return value of *note
NotImplemented: 202. from the underlying comparison function.
(Contributed by Katie Miller in bpo-10042(3).)

A pure-python version of the *note partial(): 8b5. 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(4).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue4331

   (2) https://www.python.org/dev/peps/pep-0443

   (3) https://bugs.python.org/issue10042

   (4) https://bugs.python.org/issue12428


File: python.info,  Node: gc<4>,  Next: glob<2>,  Prev: functools<4>,  Up: 改进的模块<6>

1.6.4.15 gc
...........

New function *note get_stats(): 93a. returns a list of three
per-generation dictionaries containing the collections statistics since
interpreter startup.  (Contributed by Antoine Pitrou in bpo-16351(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16351


File: python.info,  Node: glob<2>,  Next: hashlib<3>,  Prev: gc<4>,  Up: 改进的模块<6>

1.6.4.16 glob
.............

A new function *note escape(): 93c. 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(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue8402


File: python.info,  Node: hashlib<3>,  Next: hmac<2>,  Prev: glob<2>,  Up: 改进的模块<6>

1.6.4.17 hashlib
................

A new *note hashlib.pbkdf2_hmac(): 8d3. function provides the PKCS#5
password-based key derivation function 2(1).  (Contributed by Christian
Heimes in bpo-18582(2).)

The *note name: 93e. attribute of *note hashlib: 8c. hash objects is now
a formally supported interface.  It has always existed in CPython’s
*note hashlib: 8c. (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(3).)

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/PBKDF2

   (2) https://bugs.python.org/issue18582

   (3) https://bugs.python.org/issue18532


File: python.info,  Node: hmac<2>,  Next: html,  Prev: hashlib<3>,  Up: 改进的模块<6>

1.6.4.18 hmac
.............

*note hmac: 8e. now accepts ‘bytearray’ as well as ‘bytes’ for the `key'
argument to the *note new(): 940. function, and the `msg' parameter to
both the *note new(): 940. function and the *note update(): 941. method
now accepts any type supported by the *note hashlib: 8c. module.
(Contributed by Jonas Borgström in bpo-18240(1).)

The `digestmod' argument to the *note hmac.new(): 940. function may now
be any hash digest name recognized by *note hashlib: 8c.  In addition,
the current behavior in which the value of `digestmod' defaults to ‘MD5’
is deprecated: in a future version of Python there will be no default
value.  (Contributed by Christian Heimes in bpo-17276(2).)

With the addition of *note block_size: 942. and *note name: 943.
attributes (and the formal documentation of the *note digest_size: 944.
attribute), the *note hmac: 8e. module now conforms fully to the PEP
247(3) API. (Contributed by Christian Heimes in bpo-18775(4).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18240

   (2) https://bugs.python.org/issue17276

   (3) https://www.python.org/dev/peps/pep-0247

   (4) https://bugs.python.org/issue18775


File: python.info,  Node: html,  Next: http<3>,  Prev: hmac<2>,  Up: 改进的模块<6>

1.6.4.19 html
.............

New function *note unescape(): 22b. function converts HTML5 character
references to the corresponding Unicode characters.  (Contributed by
Ezio Melotti in bpo-2927(1).)

*note HTMLParser: 22a. accepts a new keyword argument `convert_charrefs'
that, when ‘True’, automatically converts all character references.  For
backward-compatibility, its value defaults to ‘False’, but it will
change to ‘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(2).)

The `strict' argument of *note HTMLParser: 22a. is now deprecated.
(Contributed by Ezio Melotti in bpo-15114(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue2927

   (2) https://bugs.python.org/issue13633

   (3) https://bugs.python.org/issue15114


File: python.info,  Node: http<3>,  Next: idlelib 与 IDLE<4>,  Prev: html,  Up: 改进的模块<6>

1.6.4.20 http
.............

*note send_error(): 947. now accepts an optional additional `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 ‘error_message_format’ attribute
and sent as the body of the error response.  (Contributed by Karl Cow in
bpo-12921(1).)

The *note http.server: 96. *note command line interface: 948. now has a
‘-b/--bind’ option that causes the server to listen on a specific
address.  (Contributed by Malte Swart in bpo-17764(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue12921

   (2) https://bugs.python.org/issue17764


File: python.info,  Node: idlelib 与 IDLE<4>,  Next: importlib<7>,  Prev: http<3>,  Up: 改进的模块<6>

1.6.4.21 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 ‘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.


File: python.info,  Node: importlib<7>,  Next: inspect<5>,  Prev: idlelib 与 IDLE<4>,  Up: 改进的模块<6>

1.6.4.22 importlib
..................

The *note InspectLoader: 94b. ABC defines a new method, *note
source_to_code(): 7e0. that accepts source data and a path and returns a
code object.  The default implementation is equivalent to ‘compile(data,
path, 'exec', dont_inherit=True)’.  (Contributed by Eric Snow and Brett
Cannon in bpo-15627(1).)

*note InspectLoader: 94b. also now has a default implementation for the
*note get_code(): 94c. method.  However, it will normally be desirable
to override the default implementation for performance reasons.
(Contributed by Brett Cannon in bpo-18072(2).)

The *note reload(): 49f. function has been moved from *note imp: 99. to
*note importlib: 9a. as part of the *note imp: 99. module deprecation.
(Contributed by Berker Peksag in bpo-18193(3).)

*note importlib.util: 9f. now has a *note MAGIC_NUMBER: 94d. attribute
providing access to the bytecode version number.  This replaces the
*note get_magic(): 94e. function in the deprecated *note imp: 99.
module.  (Contributed by Brett Cannon in bpo-18192(4).)

New *note importlib.util: 9f. functions *note cache_from_source(): 651.
and *note source_from_cache(): 652. replace the same-named functions in
the deprecated *note imp: 99. module.  (Contributed by Brett Cannon in
bpo-18194(5).)

The *note importlib: 9a. bootstrap ‘NamespaceLoader’ now conforms to the
*note InspectLoader: 94b. ABC, which means that ‘runpy’ and ‘python -m’
can now be used with namespace packages.  (Contributed by Brett Cannon
in bpo-18058(6).)

*note importlib.util: 9f. has a new function *note decode_source(): 94f.
that decodes source from bytes using universal newline processing.  This
is useful for implementing *note InspectLoader.get_source(): 950.
methods.

*note importlib.machinery.ExtensionFileLoader: 650. now has a *note
get_filename(): 951. method.  This was inadvertently omitted in the
original implementation.  (Contributed by Eric Snow in bpo-19152(7).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15627

   (2) https://bugs.python.org/issue18072

   (3) https://bugs.python.org/issue18193

   (4) https://bugs.python.org/issue18192

   (5) https://bugs.python.org/issue18194

   (6) https://bugs.python.org/issue18058

   (7) https://bugs.python.org/issue19152


File: python.info,  Node: inspect<5>,  Next: ipaddress<4>,  Prev: importlib<7>,  Up: 改进的模块<6>

1.6.4.23 inspect
................

The *note inspect: a0. module now offers a basic *note command line
interface: 953. to quickly display source code and other information for
modules, classes and functions.  (Contributed by Claudiu Popa and Nick
Coghlan in bpo-18626(1).)

*note unwrap(): 954. makes it easy to unravel wrapper function chains
created by *note functools.wraps(): 955. (and any other API that sets
the ‘__wrapped__’ attribute on a wrapper function).  (Contributed by
Daniel Urban, Aaron Iles and Nick Coghlan in bpo-13266(2).)

As part of the implementation of the new *note enum: 79. module, the
*note inspect: a0. module now has substantially better support for
custom ‘__dir__’ methods and dynamic class attributes provided through
metaclasses.  (Contributed by Ethan Furman in bpo-18929(3) and
bpo-19030(4).)

*note getfullargspec(): 657. and *note getargspec(): 656. now use the
*note signature(): 655. API. This allows them to support a much broader
range of callables, including those with ‘__signature__’ attributes,
those with metadata provided by argument clinic, *note
functools.partial(): 8b5. objects and more.  Note that, unlike *note
signature(): 655, these functions still ignore ‘__wrapped__’ attributes,
and report the already bound first argument for bound methods, so it is
still necessary to update your code to use *note signature(): 655.
directly if those features are desired.  (Contributed by Yury Selivanov
in bpo-17481(5).)

*note signature(): 655. 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(6).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18626

   (2) https://bugs.python.org/issue13266

   (3) https://bugs.python.org/issue18929

   (4) https://bugs.python.org/issue19030

   (5) https://bugs.python.org/issue17481

   (6) https://bugs.python.org/issue17159


File: python.info,  Node: ipaddress<4>,  Next: logging<5>,  Prev: inspect<5>,  Up: 改进的模块<6>

1.6.4.24 ipaddress
..................

*note ipaddress: a2. was added to the standard library in Python 3.3 as
a *note provisional API: 454.  With the release of Python 3.4, this
qualification has been removed: *note ipaddress: a2. is now considered a
stable API, covered by the normal standard library requirements to
maintain backwards compatibility.

A new *note is_global: 957. property is ‘True’ if an address is globally
routeable.  (Contributed by Peter Moody in bpo-17400(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17400


File: python.info,  Node: logging<5>,  Next: marshal,  Prev: ipaddress<4>,  Up: 改进的模块<6>

1.6.4.25 logging
................

The *note TimedRotatingFileHandler: 959. has a new `atTime' parameter
that can be used to specify the time of day when rollover should happen.
(Contributed by Ronald Oussoren in bpo-9556(1).)

*note SocketHandler: 95a. and *note DatagramHandler: 95b. now support
Unix domain sockets (by setting `port' to ‘None’).  (Contributed by
Vinay Sajip in commit ce46195b56a9.)

*note fileConfig(): 4af. now accepts a *note
configparser.RawConfigParser: 95c. subclass instance for the `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
*note fileConfig(): 4af.  (Contributed by Vinay Sajip in bpo-16110(2).)

Logging configuration data received from a socket via the *note
logging.config.listen(): 95d. function can now be validated before being
processed by supplying a verification function as the argument to the
new `verify' keyword argument.  (Contributed by Vinay Sajip in
bpo-15452(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue9556

   (2) https://bugs.python.org/issue16110

   (3) https://bugs.python.org/issue15452


File: python.info,  Node: marshal,  Next: mmap<2>,  Prev: logging<5>,  Up: 改进的模块<6>

1.6.4.26 marshal
................

The default *note marshal: b0. 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 ‘.pyc’ files and the amount of memory a module occupies in memory
when it is loaded from a ‘.pyc’ (or ‘.pyo’) file.  (Contributed by
Kristján Valur Jónsson in bpo-16475(1), with additional speedups by
Antoine Pitrou in bpo-19219(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16475

   (2) https://bugs.python.org/issue19219


File: python.info,  Node: mmap<2>,  Next: multiprocessing<6>,  Prev: marshal,  Up: 改进的模块<6>

1.6.4.27 mmap
.............

mmap objects can now be *note weakref: 131.ed.  (Contributed by Valerie
Lambert in bpo-4885(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue4885


File: python.info,  Node: multiprocessing<6>,  Next: operator<2>,  Prev: mmap<2>,  Up: 改进的模块<6>

1.6.4.28 multiprocessing
........................

On Unix two new *note start methods: 961, ‘spawn’ and ‘forkserver’, have
been added for starting processes using *note multiprocessing: b7.
These make the mixing of processes with threads more robust, and the
‘spawn’ method matches the semantics that multiprocessing has always
used on Windows.  New function *note get_all_start_methods(): 962.
reports all start methods available on the platform, *note
get_start_method(): 963. reports the current start method, and *note
set_start_method(): 964. sets the start method.  (Contributed by Richard
Oudkerk in bpo-8713(1).)

*note multiprocessing: b7. also now has the concept of a ‘context’,
which determines how child processes are created.  New function *note
get_context(): 965. returns a context that uses a specified start
method.  It has the same API as the *note multiprocessing: b7. module
itself, so you can use it to create *note Pool: 966.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(2).)

Except when using the old `fork' start method, child processes no longer
inherit unneeded handles/file descriptors from their parents (part of
bpo-8713(3)).

*note multiprocessing: b7. now relies on *note runpy: e2. (which
implements the ‘-m’ switch) to initialise ‘__main__’ appropriately in
child processes when using the ‘spawn’ or ‘forkserver’ start methods.
This resolves some edge cases where combining multiprocessing, the ‘-m’
command line switch, and explicit relative imports could cause obscure
failures in child processes.  (Contributed by Nick Coghlan in
bpo-19946(4).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue8713

   (2) https://bugs.python.org/issue18999

   (3) https://bugs.python.org/issue8713

   (4) https://bugs.python.org/issue19946


File: python.info,  Node: operator<2>,  Next: os<7>,  Prev: multiprocessing<6>,  Up: 改进的模块<6>

1.6.4.29 operator
.................

New function *note length_hint(): 968. provides an implementation of the
specification for how the *note __length_hint__(): 8f9. special method
should be used, as part of the PEP 424(1) formal specification of this
language feature.  (Contributed by Armin Ronacher in bpo-16148(2).)

There is now a pure-python version of the *note operator: c2. module
available for reference and for use by alternate implementations of
Python.  (Contributed by Zachary Ware in bpo-16694(3).)

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0424

   (2) https://bugs.python.org/issue16148

   (3) https://bugs.python.org/issue16694


File: python.info,  Node: os<7>,  Next: pdb<4>,  Prev: operator<2>,  Up: 改进的模块<6>

1.6.4.30 os
...........

There are new functions to get and set the *note inheritable flag: 8e7.
of a file descriptor (*note os.get_inheritable(): 8e8, *note
os.set_inheritable(): 8e9.) or a Windows handle (*note
os.get_handle_inheritable(): 8ea, *note os.set_handle_inheritable():
8eb.).

New function *note cpu_count(): 96a. reports the number of CPUs
available on the platform on which Python is running (or ‘None’ if the
count can’t be determined).  The *note multiprocessing.cpu_count(): 96b.
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(1).)

*note os.path.samestat(): 96c. is now available on the Windows platform
(and the *note os.path.samefile(): 96d. implementation is now shared
between Unix and Windows).  (Contributed by Brian Curtin in
bpo-11939(2).)

*note os.path.ismount(): 329. now recognizes volumes mounted below a
drive root on Windows.  (Contributed by Tim Golden in bpo-9035(3).)

*note os.open(): 758. supports two new flags on platforms that provide
them, *note O_PATH: 96e. (un-opened file descriptor), and *note
O_TMPFILE: 96f. (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(4) and
Benjamin Peterson, respectively.)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17914

   (2) https://bugs.python.org/issue11939

   (3) https://bugs.python.org/issue9035

   (4) https://bugs.python.org/issue18673


File: python.info,  Node: pdb<4>,  Next: pickle<4>,  Prev: os<7>,  Up: 改进的模块<6>

1.6.4.31 pdb
............

*note pdb: c9. has been enhanced to handle generators, *note yield: 2c7,
and ‘yield from’ in a more useful fashion.  This is especially helpful
when debugging *note asyncio: 9. based programs.  (Contributed by Andrew
Svetlov and Xavier de Gaye in bpo-16596(1).)

The ‘print’ command has been removed from *note pdb: c9, restoring
access to the Python *note print(): 971. function from the pdb command
line.  Python2’s ‘pdb’ did not have a ‘print’ command; instead, entering
‘print’ executed the ‘print’ statement.  In Python3 ‘print’ was
mistakenly made an alias for the pdb *note p: 972. command.  ‘p’,
however, prints the ‘repr’ of its argument, not the ‘str’ like the
Python2 ‘print’ command did.  Worse, the Python3 ‘pdb print’ command
shadowed the Python3 ‘print’ function, making it inaccessible at the
‘pdb’ prompt.  (Contributed by Connor Osborn in bpo-18764(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16596

   (2) https://bugs.python.org/issue18764


File: python.info,  Node: pickle<4>,  Next: plistlib<2>,  Prev: pdb<4>,  Up: 改进的模块<6>

1.6.4.32 pickle
...............

*note pickle: ca. 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 *note __new__(): 974. method takes keyword-only arguments.
It also provides some efficiency improvements.

也參考
......

PEP 3154(1) – Pickle protocol 4

     PEP 由 Antoine Pitrou 撰写，并由 Alexandre Vassalotti 实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3154


File: python.info,  Node: plistlib<2>,  Next: poplib<3>,  Prev: pickle<4>,  Up: 改进的模块<6>

1.6.4.33 plistlib
.................

*note plistlib: cf. now has an API that is similar to the standard
pattern for stdlib serialization protocols, with new *note load(): 21e,
*note dump(): 220, *note loads(): 21f, and *note dumps(): 221.
functions.  (The older API is now deprecated.)  In addition to the
already supported XML plist format (*note FMT_XML: 976.), it also now
supports the binary plist format (*note FMT_BINARY: 977.).  (Contributed
by Ronald Oussoren and others in bpo-14455(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue14455


File: python.info,  Node: poplib<3>,  Next: pprint<3>,  Prev: plistlib<2>,  Up: 改进的模块<6>

1.6.4.34 poplib
...............

Two new methods have been added to *note poplib: d0.: *note capa(): 979,
which returns the list of capabilities advertised by the POP server, and
*note stls(): 97a, 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(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue4473


File: python.info,  Node: pprint<3>,  Next: pty,  Prev: poplib<3>,  Up: 改进的模块<6>

1.6.4.35 pprint
...............

The *note pprint: d2. module’s *note PrettyPrinter: 97c. class and its
*note pformat(): 97d, and *note pprint(): 341. functions have a new
option, `compact', that controls how the output is formatted.  Currently
setting `compact' to ‘True’ means that sequences will be printed with as
many sequence elements as will fit within `width' on each (indented)
line.  (Contributed by Serhiy Storchaka in bpo-19132(1).)

Long strings are now wrapped using Python’s normal line continuation
syntax.  (Contributed by Antoine Pitrou in bpo-17150(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue19132

   (2) https://bugs.python.org/issue17150


File: python.info,  Node: pty,  Next: pydoc<4>,  Prev: pprint<3>,  Up: 改进的模块<6>

1.6.4.36 pty
............

*note pty.spawn(): 97f. now returns the status value from *note
os.waitpid(): 760. on the child process, instead of ‘None’.
(Contributed by Gregory P. Smith.)


File: python.info,  Node: pydoc<4>,  Next: re<5>,  Prev: pty,  Up: 改进的模块<6>

1.6.4.37 pydoc
..............

The *note pydoc: d9. module is now based directly on the *note
inspect.signature(): 655. introspection API, allowing it to provide
signature information for a wider variety of callable objects.  This
change also means that ‘__wrapped__’ attributes are now taken into
account when displaying help information.  (Contributed by Larry
Hastings in bpo-19674(1).)

The *note pydoc: d9. module no longer displays the ‘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(2).)

In addition to the changes that have been made to *note pydoc: d9.
directly, its handling of custom ‘__dir__’ methods and various
descriptor behaviours has also been improved substantially by the
underlying changes in the *note inspect: a0. module.

As the *note help(): 175. builtin is based on *note pydoc: d9, the above
changes also affect the behaviour of *note help(): 175.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue19674

   (2) https://bugs.python.org/issue20710


File: python.info,  Node: re<5>,  Next: resource,  Prev: pydoc<4>,  Up: 改进的模块<6>

1.6.4.38 re
...........

New *note fullmatch(): 982. function and ‘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 ‘$’ characters get lost during code changes or the
addition of alternatives to an existing regular expression.
(Contributed by Matthew Barnett in bpo-16203(1).)

The repr of *note regex objects: 983. now includes the pattern and the
flags; the repr of *note match objects: 984. now includes the start,
end, and the part of the string that matched.  (Contributed by Hugo
Lopes Tavares and Serhiy Storchaka in bpo-13592(2) and bpo-17087(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16203

   (2) https://bugs.python.org/issue13592

   (3) https://bugs.python.org/issue17087


File: python.info,  Node: resource,  Next: select,  Prev: re<5>,  Up: 改进的模块<6>

1.6.4.39 resource
.................

New *note prlimit(): 986. 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(1).)

On Linux kernel version 2.6.36 or later, there are also some new Linux
specific constants: *note RLIMIT_MSGQUEUE: 987, *note RLIMIT_NICE: 988,
*note RLIMIT_RTPRIO: 989, *note RLIMIT_RTTIME: 98a, and *note
RLIMIT_SIGPENDING: 98b.  (Contributed by Christian Heimes in
bpo-19324(2).)

On FreeBSD version 9 and later, there some new FreeBSD specific
constants: *note RLIMIT_SBSIZE: 98c, *note RLIMIT_SWAP: 98d, and *note
RLIMIT_NPTS: 98e.  (Contributed by Claudiu Popa in bpo-19343(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16595

   (2) https://bugs.python.org/issue19324

   (3) https://bugs.python.org/issue19343


File: python.info,  Node: select,  Next: shelve,  Prev: resource,  Up: 改进的模块<6>

1.6.4.40 select
...............

*note epoll: 990. objects now support the context management protocol.
When used in a *note with: 7da. statement, the *note close(): 991.
method will be called automatically at the end of the block.
(Contributed by Serhiy Storchaka in bpo-16488(1).)

*note devpoll: 992. objects now have *note fileno(): 993. and *note
close(): 994. methods, as well as a new attribute *note closed: 995.
(Contributed by Victor Stinner in bpo-18794(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16488

   (2) https://bugs.python.org/issue18794


File: python.info,  Node: shelve,  Next: shutil<3>,  Prev: select,  Up: 改进的模块<6>

1.6.4.41 shelve
...............

*note Shelf: 997. instances may now be used in *note with: 7da.
statements, and will be automatically closed at the end of the ‘with’
block.  (Contributed by Filip Gruszczyński in bpo-13896(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13896


File: python.info,  Node: shutil<3>,  Next: smtpd<2>,  Prev: shelve,  Up: 改进的模块<6>

1.6.4.42 shutil
...............

*note copyfile(): 382. now raises a specific *note Error: 999. subclass,
*note SameFileError: 99a, 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(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1492704


File: python.info,  Node: smtpd<2>,  Next: smtplib<3>,  Prev: shutil<3>,  Up: 改进的模块<6>

1.6.4.43 smtpd
..............

The *note SMTPServer: 6f9. and *note SMTPChannel: 6f8. classes now
accept a `map' keyword argument which, if specified, is passed in to
*note asynchat.async_chat: 99c. as its `map' argument.  This allows an
application to avoid affecting the global socket map.  (Contributed by
Vinay Sajip in bpo-11959(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue11959


File: python.info,  Node: smtplib<3>,  Next: socket<7>,  Prev: smtpd<2>,  Up: 改进的模块<6>

1.6.4.44 smtplib
................

*note SMTPException: 99e. is now a subclass of *note OSError: 304, 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(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue2118


File: python.info,  Node: socket<7>,  Next: sqlite3<4>,  Prev: smtplib<3>,  Up: 改进的模块<6>

1.6.4.45 socket
...............

The socket module now supports the *note CAN_BCM: 9a0. protocol on
platforms that support it.  (Contributed by Brian Thorne in
bpo-15359(1).)

Socket objects have new methods to get or set their *note inheritable
flag: 8e7, *note get_inheritable(): 8ec. and *note set_inheritable():
8ed.

The ‘socket.AF_*’ and ‘socket.SOCK_*’ constants are now enumeration
values using the new *note enum: 79. module.  This allows meaningful
names to be printed during debugging, instead of integer "magic
numbers".

The *note AF_LINK: 9a1. constant is now available on BSD and OSX.

*note inet_pton(): 237. and *note inet_ntop(): 9a2. are now supported on
Windows.  (Contributed by Atsuo Ishimoto in bpo-7171(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15359

   (2) https://bugs.python.org/issue7171


File: python.info,  Node: sqlite3<4>,  Next: ssl<7>,  Prev: socket<7>,  Up: 改进的模块<6>

1.6.4.46 sqlite3
................

A new boolean parameter to the *note connect(): 4e0. function, `uri',
can be used to indicate that the `database' parameter is a ‘uri’ (see
the SQLite URI documentation(1)).  (Contributed by poq in bpo-13773(2).)

   ---------- Footnotes ----------

   (1) https://www.sqlite.org/uri.html

   (2) https://bugs.python.org/issue13773


File: python.info,  Node: ssl<7>,  Next: stat,  Prev: sqlite3<4>,  Up: 改进的模块<6>

1.6.4.47 ssl
............

*note PROTOCOL_TLSv1_1: 9a5. and *note PROTOCOL_TLSv1_2: 9a6. (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(1).)  New
function *note create_default_context(): 9a7. provides a standard way to
obtain an *note SSLContext: 4e9. whose settings are intended to be a
reasonable balance between compatibility and security.  These settings
are more stringent than the defaults provided by the *note SSLContext:
4e9. 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 *note create_default_context(): 9a7. to obtain an *note
SSLContext: 4e9. object, modify it if needed, and then pass it as the
`context' argument of the appropriate stdlib API. (Contributed by
Christian Heimes in bpo-19689(2).)

*note SSLContext: 4e9. method *note load_verify_locations(): 8d8.
accepts a new optional argument `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(3).)

New function *note get_default_verify_paths(): 9a8. returns a named
tuple of the paths and environment variables that the *note
set_default_verify_paths(): 9a9. method uses to set OpenSSL’s default
‘cafile’ and ‘capath’.  This can be an aid in debugging default
verification issues.  (Contributed by Christian Heimes in bpo-18143(4).)

*note SSLContext: 4e9. has a new method, *note cert_store_stats(): 9aa,
that reports the number of loaded ‘X.509’ certs, ‘X.509 CA’ certs, and
certificate revocation lists (‘crl’s), as well as a *note
get_ca_certs(): 9ab. method that returns a list of the loaded ‘CA’
certificates.  (Contributed by Christian Heimes in bpo-18147(5).)

If OpenSSL 0.9.8 or later is available, *note SSLContext: 4e9. has a new
attribute *note verify_flags: 9ac. that can be used to control the
certificate verification process by setting it to some combination of
the new constants *note VERIFY_DEFAULT: 9ad, *note
VERIFY_CRL_CHECK_LEAF: 9ae, *note VERIFY_CRL_CHECK_CHAIN: 9af, or *note
VERIFY_X509_STRICT: 9b0.  OpenSSL does not do any CRL verification by
default.  (Contributed by Christien Heimes in bpo-8813(6).)

New *note SSLContext: 4e9. method *note load_default_certs(): 9b1. 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 (‘purpose=’*note
SERVER_AUTH: 9b2.) for a client to use to verify a server, and
certificates for a server to use in verifying client certificates
(‘purpose=’*note CLIENT_AUTH: 9b3.).  (Contributed by Christian Heimes
in bpo-19292(7).)  Two new windows-only functions, *note
enum_certificates(): 9b4. and *note enum_crls(): 9b5. provide the
ability to retrieve certificates, certificate information, and CRLs from
the Windows cert store.  (Contributed by Christian Heimes in
bpo-17134(8).)  Support for server-side SNI (Server Name Indication)
using the new *note ssl.SSLContext.set_servername_callback(): 9b6.
method.  (Contributed by Daniel Black in bpo-8109(9).)

The dictionary returned by *note SSLSocket.getpeercert(): 9b7. contains
additional ‘X509v3’ extension items: ‘crlDistributionPoints’,
‘calIssuers’, and ‘OCSP’ URIs.  (Contributed by Christian Heimes in
bpo-18379(10).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16692

   (2) https://bugs.python.org/issue19689

   (3) https://bugs.python.org/issue18138

   (4) https://bugs.python.org/issue18143

   (5) https://bugs.python.org/issue18147

   (6) https://bugs.python.org/issue8813

   (7) https://bugs.python.org/issue19292

   (8) https://bugs.python.org/issue17134

   (9) https://bugs.python.org/issue8109

   (10) https://bugs.python.org/issue18379


File: python.info,  Node: stat,  Next: struct<2>,  Prev: ssl<7>,  Up: 改进的模块<6>

1.6.4.48 stat
.............

The *note stat: f4. module is now backed by a C implementation in
‘_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(1).)

The module supports new *note ST_MODE: 9b9. flags, *note S_IFDOOR: 9ba,
*note S_IFPORT: 9bb, and *note S_IFWHT: 9bc.  (Contributed by Christian
Hiemes in bpo-11016(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue11016

   (2) https://bugs.python.org/issue11016


File: python.info,  Node: struct<2>,  Next: subprocess<4>,  Prev: stat,  Up: 改进的模块<6>

1.6.4.49 struct
...............

New function *note iter_unpack: 9be. and a new *note
struct.Struct.iter_unpack(): 9bf. 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(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17804


File: python.info,  Node: subprocess<4>,  Next: sunau<2>,  Prev: struct<2>,  Up: 改进的模块<6>

1.6.4.50 subprocess
...................

*note check_output(): 9c1. now accepts an `input' argument that can be
used to provide the contents of ‘stdin’ for the command that is run.
(Contributed by Zack Weinberg in bpo-16624(1).)

‘getstatus()’ and *note getstatusoutput(): 9c2. now work on Windows.
This change was actually inadvertently made in 3.3.4.  (Contributed by
Tim Golden in bpo-10197(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16624

   (2) https://bugs.python.org/issue10197


File: python.info,  Node: sunau<2>,  Next: sys<7>,  Prev: subprocess<4>,  Up: 改进的模块<6>

1.6.4.51 sunau
..............

The ‘getparams()’ method now returns a namedtuple rather than a plain
tuple.  (Contributed by Claudiu Popa in bpo-18901(1).)

*note sunau.open(): 572. now supports the context management protocol:
when used in a *note with: 7da. block, the ‘close’ method of the
returned object will be called automatically at the end of the block.
(Contributed by Serhiy Storchaka in bpo-18878(2).)

*note AU_write.setsampwidth(): 9c4. now supports 24 bit samples, thus
adding support for writing 24 sample using the module.  (Contributed by
Serhiy Storchaka in bpo-19261(3).)

The *note writeframesraw(): 9c5. and *note writeframes(): 9c6. methods
now accept any *note bytes-like object: 6df.  (Contributed by Serhiy
Storchaka in bpo-8311(4).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18901

   (2) https://bugs.python.org/issue18878

   (3) https://bugs.python.org/issue19261

   (4) https://bugs.python.org/issue8311


File: python.info,  Node: sys<7>,  Next: tarfile<3>,  Prev: sunau<2>,  Up: 改进的模块<6>

1.6.4.52 sys
............

New function *note sys.getallocatedblocks(): 9c8. returns the current
number of blocks allocated by the interpreter.  (In CPython with the
default ‘--with-pymalloc’ setting, this is allocations made through the
*note PyObject_Malloc(): 601. API.) This can be useful for tracking
memory leaks, especially if automated via a test suite.  (Contributed by
Antoine Pitrou in bpo-13390(1).)

When the Python interpreter starts in *note interactive mode: 9c9, it
checks for an *note __interactivehook__: 9ca. attribute on the *note
sys: fd. module.  If the attribute exists, its value is called with no
arguments just before interactive mode is started.  The check is made
after the *note PYTHONSTARTUP: 9cb. file is read, so it can be set
there.  The *note site: eb. module *note sets it: 9cc. to a function
that enables tab completion and history saving (in ‘~/.python-history’)
if the platform supports *note readline: de.  If you do not want this
(new) behavior, you can override it in *note PYTHONSTARTUP: 9cb,
‘sitecustomize’, or ‘usercustomize’ by deleting this attribute from
*note sys: fd. (or setting it to some other callable).  (Contributed by
Éric Araujo and Antoine Pitrou in bpo-5845(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13390

   (2) https://bugs.python.org/issue5845


File: python.info,  Node: tarfile<3>,  Next: textwrap,  Prev: sys<7>,  Up: 改进的模块<6>

1.6.4.53 tarfile
................

The *note tarfile: 101. module now supports a simple *note 命令行界面:
9ce. when called as a script directly or via ‘-m’.  This can be used to
create and extract tarfile archives.  (Contributed by Berker Peksag in
bpo-13477(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13477


File: python.info,  Node: textwrap,  Next: threading<4>,  Prev: tarfile<3>,  Up: 改进的模块<6>

1.6.4.54 textwrap
.................

The *note TextWrapper: 9d0. class has two new attributes/constructor
arguments: *note max_lines: 9d1, which limits the number of lines in the
output, and *note placeholder: 9d2, which is a string that will appear
at the end of the output if it has been truncated because of
`max_lines'.  Building on these capabilities, a new convenience function
*note shorten(): 9d3. collapses all of the whitespace in the input to
single spaces and produces a single line of a given `width' that ends
with the `placeholder' (by default, ‘[...]’).  (Contributed by Antoine
Pitrou and Serhiy Storchaka in bpo-18585(1) and bpo-18725(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18585

   (2) https://bugs.python.org/issue18725


File: python.info,  Node: threading<4>,  Next: traceback<3>,  Prev: textwrap,  Up: 改进的模块<6>

1.6.4.55 threading
..................

The *note Thread: 21a. object representing the main thread can be
obtained from the new *note main_thread(): 9d5. function.  In normal
conditions this will be the thread from which the Python interpreter was
started.  (Contributed by Andrew Svetlov in bpo-18882(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18882


File: python.info,  Node: traceback<3>,  Next: types<3>,  Prev: threading<4>,  Up: 改进的模块<6>

1.6.4.56 traceback
..................

A new *note traceback.clear_frames(): 9d7. 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(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1565525


File: python.info,  Node: types<3>,  Next: urllib<2>,  Prev: traceback<3>,  Up: 改进的模块<6>

1.6.4.57 types
..............

A new *note DynamicClassAttribute(): 9d9. descriptor provides a way to
define an attribute that acts normally when looked up through an
instance object, but which is routed to the `class' ‘__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 ‘Enum’ for an example).  (Contributed by Ethan Furman in
bpo-19030(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue19030


File: python.info,  Node: urllib<2>,  Next: unittest<4>,  Prev: types<3>,  Up: 改进的模块<6>

1.6.4.58 urllib
...............

*note urllib.request: 129. now supports ‘data:’ URLs via the *note
DataHandler: 9db. class.  (Contributed by Mathias Panzenböck in
bpo-16423(1).)

The http method that will be used by a *note Request: 9dc. class can now
be specified by setting a *note method: 9dd. class attribute on the
subclass.  (Contributed by Jason R Coombs in bpo-18978(2).)

*note Request: 9dc. objects are now reusable: if the *note full_url:
9de. or *note data: 9df. attributes are modified, all relevant internal
properties are updated.  This means, for example, that it is now
possible to use the same *note Request: 9dc. object in more than one
*note OpenerDirector.open(): 9e0. call with different `data' arguments,
or to modify a *note Request: 9dc.’s ‘url’ rather than recomputing it
from scratch.  There is also a new *note remove_header(): 9e1. method
that can be used to remove headers from a *note Request: 9dc.
(Contributed by Alexey Kachayev in bpo-16464(3), Daniel Wozniak in
bpo-17485(4), and Damien Brecht and Senthil Kumaran in bpo-17272(5).)

*note HTTPError: 9e2. objects now have a *note headers: 9e3. attribute
that provides access to the HTTP response headers associated with the
error.  (Contributed by Berker Peksag in bpo-15701(6).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16423

   (2) https://bugs.python.org/issue18978

   (3) https://bugs.python.org/issue16464

   (4) https://bugs.python.org/issue17485

   (5) https://bugs.python.org/issue17272

   (6) https://bugs.python.org/issue15701


File: python.info,  Node: unittest<4>,  Next: venv<5>,  Prev: urllib<2>,  Up: 改进的模块<6>

1.6.4.59 unittest
.................

The *note TestCase: 9e5. class has a new method, *note subTest(): 9e6,
that produces a context manager whose *note with: 7da. block becomes a
"sub-test".  This context manager allows a test method to dynamically
generate subtests by, say, calling the ‘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:

     class NumbersTest(unittest.TestCase):
         def test_even(self):
             for i in range(6):
                 with self.subTest(i=i):
                     self.assertEqual(i % 2, 0)

will result in six subtests, each identified in the unittest verbose
output with a label consisting of the variable name ‘i’ and a particular
value for that variable (‘i=0’, ‘i=1’, etc).  See *note Distinguishing
test iterations using subtests: 9e7. for the full version of this
example.  (Contributed by Antoine Pitrou in bpo-16997(1).)

*note unittest.main(): 9e8. now accepts an iterable of test names for
`defaultTest', where previously it only accepted a single test name as a
string.  (Contributed by Jyrki Pulliainen in bpo-15132(2).)

If *note SkipTest: 9e9. 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(3).)

*note discover(): 9ea. now sorts the discovered files to provide
consistent test ordering.  (Contributed by Martin Melin and Jeff Ramnani
in bpo-16709(4).)

*note TestSuite: 7c1. 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 *note TestSuite: 7c1. subclass that
defines a custom ‘_removeTestAtIndex’ method.  (Contributed by Tom
Wardill, Matt McClure, and Andrew Svetlov in bpo-11798(5).)

A new test assertion context-manager, *note assertLogs(): 9eb, will
ensure that a given block of code emits a log message using the *note
logging: aa. module.  By default the message can come from any logger
and have a priority of ‘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 *note LogRecord: 9ec.s
and/or formatted messages that were logged.  (Contributed by Antoine
Pitrou in bpo-18937(6).)

Test discovery now works with namespace packages (Contributed by Claudiu
Popa in bpo-17457(7).)

*note unittest.mock: 125. 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(8).)

‘mock_open()’ objects now have ‘readline’ and ‘readlines’ methods.
(Contributed by Toshio Kuratomi in bpo-17467(9).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16997

   (2) https://bugs.python.org/issue15132

   (3) https://bugs.python.org/issue16935

   (4) https://bugs.python.org/issue16709

   (5) https://bugs.python.org/issue11798

   (6) https://bugs.python.org/issue18937

   (7) https://bugs.python.org/issue17457

   (8) https://bugs.python.org/issue17015

   (9) https://bugs.python.org/issue17467


File: python.info,  Node: venv<5>,  Next: wave<2>,  Prev: unittest<4>,  Up: 改进的模块<6>

1.6.4.60 venv
.............

*note venv: 12e. now includes activation scripts for the ‘csh’ and
‘fish’ shells.  (Contributed by Andrew Svetlov in bpo-15417(1).)

*note EnvBuilder: 9ee. and the *note create(): 9ef. convenience function
take a new keyword argument `with_pip', which defaults to ‘False’, that
controls whether or not *note EnvBuilder: 9ee. ensures that ‘pip’ is
installed in the virtual environment.  (Contributed by Nick Coghlan in
bpo-19552(2) as part of the PEP 453(3) implementation.)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15417

   (2) https://bugs.python.org/issue19552

   (3) https://www.python.org/dev/peps/pep-0453


File: python.info,  Node: wave<2>,  Next: weakref<2>,  Prev: venv<5>,  Up: 改进的模块<6>

1.6.4.61 wave
.............

The ‘getparams()’ method now returns a namedtuple rather than a plain
tuple.  (Contributed by Claudiu Popa in bpo-17487(1).)

*note wave.open(): 219. now supports the context management protocol.
(Contributed by Claudiu Popa in bpo-17616(2).)

*note wave: 130. can now *note write output to unseekable files: 9f1.
(Contributed by David Jones, Guilherme Polo, and Serhiy Storchaka in
bpo-5202(3).)

The *note writeframesraw(): 9f2. and *note writeframes(): 9f3. methods
now accept any *note bytes-like object: 6df.  (Contributed by Serhiy
Storchaka in bpo-8311(4).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17487

   (2) https://bugs.python.org/issue17616

   (3) https://bugs.python.org/issue5202

   (4) https://bugs.python.org/issue8311


File: python.info,  Node: weakref<2>,  Next: xml etree<2>,  Prev: wave<2>,  Up: 改进的模块<6>

1.6.4.62 weakref
................

New *note WeakMethod: 9f5. class simulates weak references to bound
methods.  (Contributed by Antoine Pitrou in bpo-14631(1).)

New *note finalize: 3c0. 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(2).)

The callback, if any, associated with a *note ref: 9f6. is now exposed
via the *note __callback__: 9f7. attribute.  (Contributed by Mark
Dickinson in bpo-17643(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue14631

   (2) https://bugs.python.org/issue15528

   (3) https://bugs.python.org/issue17643


File: python.info,  Node: xml etree<2>,  Next: zipfile<4>,  Prev: weakref<2>,  Up: 改进的模块<6>

1.6.4.63 xml.etree
..................

A new parser, *note XMLPullParser: 9f9, allows a non-blocking
applications to parse XML documents.  An example can be seen at *note
用于非阻塞解析的拉取 API: 9fa.  (Contributed by Antoine Pitrou in
bpo-17741(1).)

The *note xml.etree.ElementTree: 140. *note tostring(): 9fb. and *note
tostringlist(): 9fc. functions, and the *note ElementTree: 21c. *note
write(): 9fd. method, now have a `short_empty_elements' *note
keyword-only parameter: 3ce. providing control over whether elements
with no content are written in abbreviated (‘<tag />’) or expanded
(‘<tag></tag>’) form.  (Contributed by Ariel Poliak and Serhiy Storchaka
in bpo-14377(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17741

   (2) https://bugs.python.org/issue14377


File: python.info,  Node: zipfile<4>,  Prev: xml etree<2>,  Up: 改进的模块<6>

1.6.4.64 zipfile
................

The *note writepy(): 9ff. method of the *note PyZipFile: a00. class has
a new `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(1).)

The `allowZip64' parameter to *note ZipFile: 522. and ‘PyZipfile’ is now
‘True’ by default.  (Contributed by William Mallard in bpo-17201(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue19274

   (2) https://bugs.python.org/issue17201


File: python.info,  Node: CPython Implementation Changes,  Next: 弃用<5>,  Prev: 改进的模块<6>,  Up: Python 3 4 有什么新变化

1.6.5 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::


File: python.info,  Node: PEP 445 Customization of CPython Memory Allocators,  Next: PEP 442 Safe Object Finalization,  Up: CPython Implementation Changes

1.6.5.1 PEP 445: Customization of CPython Memory Allocators
...........................................................

PEP 445(1) adds new C level interfaces to customize memory allocation in
the CPython interpreter.

也參考
......

PEP 445(2) – Add new APIs to customize Python memory allocators

     PEP 由 Victor Stinner 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0445

   (2) https://www.python.org/dev/peps/pep-0445


File: python.info,  Node: PEP 442 Safe Object Finalization,  Next: PEP 456 Secure and Interchangeable Hash Algorithm,  Prev: PEP 445 Customization of CPython Memory Allocators,  Up: CPython Implementation Changes

1.6.5.2 PEP 442: Safe Object Finalization
.........................................

PEP 442(1) removes the current limitations and quirks of object
finalization in CPython.  With it, objects with *note __del__(): a04.
methods, as well as generators with *note finally: 2bc. 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
*note None: 203. 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 ‘__del__’ methods, that have plagued Python since the cyclic
GC was first introduced.

也參考
......

PEP 442(2) – Safe object finalization

     PEP 由 Antoine Pitrou 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0442

   (2) https://www.python.org/dev/peps/pep-0442


File: python.info,  Node: PEP 456 Secure and Interchangeable Hash Algorithm,  Next: PEP 436 Argument Clinic,  Prev: PEP 442 Safe Object Finalization,  Up: CPython Implementation Changes

1.6.5.3 PEP 456: Secure and Interchangeable Hash Algorithm
..........................................................

PEP 456(1) 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(2) 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 *note sys.hash_info: a06. named
tuple to describe the hash algorithm in use by the currently executing
binary.  Otherwise, the PEP does not alter any existing CPython APIs.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0456

   (2) https://bugs.python.org/issue14621


File: python.info,  Node: PEP 436 Argument Clinic,  Next: Other Build and C API Changes,  Prev: PEP 456 Secure and Interchangeable Hash Algorithm,  Up: CPython Implementation Changes

1.6.5.4 PEP 436: Argument Clinic
................................

"Argument Clinic" ( PEP 436(1)) 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 *note pydoc: d9. and *note inspect:
a0. 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.

     備註: 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.

也參考
......

PEP 436(2) – The Argument Clinic DSL

     PEP 由 Larry Hastings 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0436

   (2) https://www.python.org/dev/peps/pep-0436


File: python.info,  Node: Other Build and C API Changes,  Next: 其他改进<2>,  Prev: PEP 436 Argument Clinic,  Up: CPython Implementation Changes

1.6.5.5 Other Build and C API Changes
.....................................

   * The new *note PyType_GetSlot(): a09. 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(1).)

   * The new *note Py_SetStandardStreamEncoding(): a0a.
     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(2).)

   * Most Python C APIs that don’t mutate string arguments are now
     correctly marked as accepting ‘const char *’ rather than ‘char *’.
     (Contributed by Serhiy Storchaka in bpo-1772673(3).)

   * A new shell version of ‘python-config’ can be used even when a
     python interpreter is not available (for example, in cross
     compilation scenarios).

   * *note PyUnicode_FromFormat(): 8b8. now supports width and precision
     specifications for ‘%s’, ‘%A’, ‘%U’, ‘%V’, ‘%S’, and ‘%R’.
     (Contributed by Ysj Ray and Victor Stinner in bpo-7330(4).)

   * New function *note PyStructSequence_InitType2(): a0b. supplements
     the existing *note PyStructSequence_InitType(): a0c. function.  The
     difference is that it returns ‘0’ on success and ‘-1’ on failure.

   * 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(5).)

   * The Windows build now uses Address Space Layout Randomization(6)
     and Data Execution Prevention(7).  (Contributed by Christian Heimes
     in bpo-16632(8).)

   * New function *note PyObject_LengthHint(): a0d. is the C API
     equivalent of *note operator.length_hint(): 968.  (Contributed by
     Armin Ronacher in bpo-16148(9).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17162

   (2) https://bugs.python.org/issue16129

   (3) https://bugs.python.org/issue1772673

   (4) https://bugs.python.org/issue7330

   (5) https://bugs.python.org/issue18596

   (6) https://en.wikipedia.org/wiki/Address_space_layout_randomization

   (7) https://en.wikipedia.org/wiki/Data_Execution_Prevention

   (8) https://bugs.python.org/issue16632

   (9) https://bugs.python.org/issue16148


File: python.info,  Node: 其他改进<2>,  Next: Significant Optimizations,  Prev: Other Build and C API Changes,  Up: CPython Implementation Changes

1.6.5.6 其他改进
................

   * The *note python: a10. command has a new *note option: a11, ‘-I’,
     which causes it to run in "isolated mode", which means that *note
     sys.path: 261. contains neither the script’s directory nor the
     user’s ‘site-packages’ directory, and all ‘PYTHON*’ environment
     variables are ignored (it implies both ‘-s’ and ‘-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 ‘#!’ line of system scripts.  (Contributed by Christian Heimes
     in bpo-16499(1).)

   * Tab-completion is now enabled by default in the interactive
     interpreter on systems that support *note readline: de.  History is
     also enabled by default, and is written to (and read from) the file
     ‘~/.python-history’.  (Contributed by Antoine Pitrou and Éric
     Araujo in bpo-5845(2).)

   * Invoking the Python interpreter with ‘--version’ now outputs the
     version to standard output instead of standard error
     (bpo-18338(3)).  Similar changes were made to *note argparse: 5.
     (bpo-18920(4)) and other modules that have script-like invocation
     capabilities (bpo-18922(5)).

   * The CPython Windows installer now adds ‘.py’ to the ‘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 ‘.py’ extension.  (Contributed by Paul Moore in
     bpo-18569(6).)

   * A new ‘make’ target coverage-report(7) will build python, run the
     test suite, and generate an HTML coverage report for the C codebase
     using ‘gcov’ and lcov(8).

   * The ‘-R’ option to the *note python regression test suite: a12. now
     also checks for memory allocation leaks, using *note
     sys.getallocatedblocks(): 9c8.  (Contributed by Antoine Pitrou in
     bpo-13390(9).)

   * ‘python -m’ now works with namespace packages.

   * The *note stat: f4. 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.

   * Loading multiple python modules from a single OS module (‘.so’,
     ‘.dll’) now works correctly (previously it silently returned the
     first python module in the file).  (Contributed by Václav Šmilauer
     in bpo-16421(10).)

   * A new opcode, *note LOAD_CLASSDEREF: a13, has been added to fix a
     bug in the loading of free variables in class bodies that could be
     triggered by certain uses of *note __prepare__: 5f6.  (Contributed
     by Benjamin Peterson in bpo-17853(11).)

   * A number of MemoryError-related crashes were identified and fixed
     by Victor Stinner using his PEP 445(12)-based ‘pyfailmalloc’ tool
     (bpo-18408(13), bpo-18520(14)).

   * The ‘pyvenv’ command now accepts a ‘--copies’ option to use copies
     rather than symlinks even on systems where symlinks are the
     default.  (Contributed by Vinay Sajip in bpo-18807(15).)

   * The ‘pyvenv’ command also accepts a ‘--without-pip’ option to
     suppress the otherwise-automatic bootstrapping of pip into the
     virtual environment.  (Contributed by Nick Coghlan in bpo-19552(16)
     as part of the PEP 453(17) implementation.)

   * The encoding name is now optional in the value set for the *note
     PYTHONIOENCODING: a14. environment variable.  This makes it
     possible to set just the error handler, without changing the
     default encoding.  (Contributed by Serhiy Storchaka in
     bpo-18818(18).)

   * The *note bz2: 13, *note lzma: ad, and *note gzip: 8b. module
     ‘open’ functions now support ‘x’ (exclusive creation) mode.
     (Contributed by Tim Heaney and Vajrasky Kok in bpo-19201(19),
     bpo-19222(20), and bpo-19223(21).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16499

   (2) https://bugs.python.org/issue5845

   (3) https://bugs.python.org/issue18338

   (4) https://bugs.python.org/issue18920

   (5) https://bugs.python.org/issue18922

   (6) https://bugs.python.org/issue18569

   (7) 
https://devguide.python.org/coverage/#measuring-coverage-of-c-code-with-gcov-and-lcov

   (8) http://ltp.sourceforge.net/coverage/lcov.php

   (9) https://bugs.python.org/issue13390

   (10) https://bugs.python.org/issue16421

   (11) https://bugs.python.org/issue17853

   (12) https://www.python.org/dev/peps/pep-0445

   (13) https://bugs.python.org/issue18408

   (14) https://bugs.python.org/issue18520

   (15) https://bugs.python.org/issue18807

   (16) https://bugs.python.org/issue19552

   (17) https://www.python.org/dev/peps/pep-0453

   (18) https://bugs.python.org/issue18818

   (19) https://bugs.python.org/issue19201

   (20) https://bugs.python.org/issue19222

   (21) https://bugs.python.org/issue19223


File: python.info,  Node: Significant Optimizations,  Prev: 其他改进<2>,  Up: CPython Implementation Changes

1.6.5.7 Significant Optimizations
.................................

   * The UTF-32 decoder is now 3x to 4x faster.  (Contributed by Serhiy
     Storchaka in bpo-14625(1).)

   * 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(2).)

   * The interpreter starts about 30% faster.  A couple of measures lead
     to the speedup.  The interpreter loads fewer modules on startup,
     e.g.  the *note re: dd, *note collections: 1d. and *note locale:
     a9. 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(3), bpo-19218(4),
     bpo-19209(5), bpo-19205(6) and bpo-9548(7).)

   * *note bz2.BZ2File: 224. is now as fast or faster than the Python2
     version for most cases.  *note lzma.LZMAFile: a16. has also been
     optimized.  (Contributed by Serhiy Storchaka and Nadeem Vawda in
     bpo-16034(8).)

   * *note random.getrandbits(): a17. is 20%-40% faster for small
     integers (the most common use case).  (Contributed by Serhiy
     Storchaka in bpo-16674(9).)

   * 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(10).)

   * A performance issue in ‘io.FileIO.readall()’ has been solved.  This
     particularly affects Windows, and significantly speeds up the case
     of piping significant amounts of data through *note subprocess: f9.
     (Contributed by Richard Oudkerk in bpo-15758(11).)

   * *note html.escape(): a18. is now 10x faster.  (Contributed by Matt
     Bryant in bpo-18020(12).)

   * On Windows, the native ‘VirtualAlloc’ is now used instead of the
     CRT ‘malloc’ in ‘obmalloc’.  Artificial benchmarks show about a 3%
     memory savings.

   * *note os.urandom(): 5cb. 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(13).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue14625

   (2) https://bugs.python.org/issue18771

   (3) https://bugs.python.org/issue19219

   (4) https://bugs.python.org/issue19218

   (5) https://bugs.python.org/issue19209

   (6) https://bugs.python.org/issue19205

   (7) https://bugs.python.org/issue9548

   (8) https://bugs.python.org/issue16034

   (9) https://bugs.python.org/issue16674

   (10) https://bugs.python.org/issue15596

   (11) https://bugs.python.org/issue15758

   (12) https://bugs.python.org/issue18020

   (13) https://bugs.python.org/issue18756


File: python.info,  Node: 弃用<5>,  Next: 移除<5>,  Prev: CPython Implementation Changes,  Up: Python 3 4 有什么新变化

1.6.6 弃用
----------

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
*note DeprecationWarning: 15a. when the interpreter is run with
deprecation warnings enabled (for example, by using ‘-Wd’).

* Menu:

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


File: python.info,  Node: Deprecations in the Python API,  Next: Deprecated Features,  Up: 弃用<5>

1.6.6.1 Deprecations in the Python API
......................................

   * As mentioned in *note PEP 451; A ModuleSpec Type for the Import
     System: 8c5, a number of *note importlib: 9a. methods and functions
     are deprecated: *note importlib.find_loader(): a1b. is replaced by
     *note importlib.util.find_spec(): a1c.; *note
     importlib.machinery.PathFinder.find_module(): a1d. is replaced by
     *note importlib.machinery.PathFinder.find_spec(): a1e.; *note
     importlib.abc.MetaPathFinder.find_module(): 563. is replaced by
     *note importlib.abc.MetaPathFinder.find_spec(): 564.; *note
     importlib.abc.PathEntryFinder.find_loader(): 565. and *note
     find_module(): a1f. are replaced by *note
     importlib.abc.PathEntryFinder.find_spec(): 566.; all of the
     ‘xxxLoader’ ABC ‘load_module’ methods (*note
     importlib.abc.Loader.load_module(): 6da, *note
     importlib.abc.InspectLoader.load_module(): a20, *note
     importlib.abc.FileLoader.load_module(): a21, *note
     importlib.abc.SourceLoader.load_module(): a22.) should no longer be
     implemented, instead loaders should implement an ‘exec_module’
     method (*note importlib.abc.Loader.exec_module(): 6db, *note
     importlib.abc.InspectLoader.exec_module(): a23. *note
     importlib.abc.SourceLoader.exec_module(): a24.) and let the import
     system take care of the rest; and *note
     importlib.abc.Loader.module_repr(): a25, *note
     importlib.util.module_for_loader(): a26, *note
     importlib.util.set_loader(): a27, and *note
     importlib.util.set_package(): a28. are no longer needed because
     their functions are now handled automatically by the import system.

   * The *note imp: 99. module is pending deprecation.  To keep
     compatibility with Python 2/3 code bases, the module’s removal is
     currently not scheduled.

   * The *note formatter: 80. module is pending deprecation and is
     slated for removal in Python 3.6.

   * ‘MD5’ as the default `digestmod' for the *note hmac.new(): 940.
     function is deprecated.  Python 3.6 will require an explicit digest
     name or constructor as `digestmod' argument.

   * The internal ‘Netrc’ class in the *note ftplib: 82. module has been
     documented as deprecated in its docstring for quite some time.  It
     now emits a *note DeprecationWarning: 15a. and will be removed
     completely in Python 3.5.

   * The undocumented `endtime' argument to *note
     subprocess.Popen.wait(): 689. should not have been exposed and is
     hopefully not in use; it is deprecated and will mostly likely be
     removed in Python 3.5.

   * The `strict' argument of *note HTMLParser: 22a. is deprecated.

   * The *note plistlib: cf. ‘readPlist()’, ‘writePlist()’,
     ‘readPlistFromBytes()’, and ‘writePlistToBytes()’ functions are
     deprecated in favor of the corresponding new functions *note
     load(): 21e, *note dump(): 220, *note loads(): 21f, and *note
     dumps(): 221.  ‘Data()’ is deprecated in favor of just using the
     *note bytes: 172. constructor.

   * The *note sysconfig: fe. key ‘SO’ is deprecated, it has been
     replaced by ‘EXT_SUFFIX’.

   * The ‘U’ mode accepted by various ‘open’ functions is deprecated.
     In Python3 it does not do anything useful, and should be replaced
     by appropriate uses of *note io.TextIOWrapper: 6ea. (if needed) and
     its `newline' argument.

   * The `parser' argument of *note xml.etree.ElementTree.iterparse():
     a29. has been deprecated, as has the `html' argument of *note
     XMLParser(): 37c.  To prepare for the removal of the latter, all
     arguments to ‘XMLParser’ should be passed by keyword.


File: python.info,  Node: Deprecated Features,  Prev: Deprecations in the Python API,  Up: 弃用<5>

1.6.6.2 Deprecated Features
...........................

   * Running *note IDLE: a2b. with the ‘-n’ flag (no subprocess) is
     deprecated.  However, the feature will not be removed until
     bpo-18823(1) is resolved.

   * The site module adding a "site-python" directory to sys.path, if it
     exists, is deprecated (bpo-19375(2)).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18823

   (2) https://bugs.python.org/issue19375


File: python.info,  Node: 移除<5>,  Next: 移植到 Python 3 4,  Prev: 弃用<5>,  Up: Python 3 4 有什么新变化

1.6.7 移除
----------

* Menu:

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


File: python.info,  Node: 不再支持的操作系统,  Next: API 与特性的移除<5>,  Up: 移除<5>

1.6.7.1 不再支持的操作系统
..........................

从源代码和构建工具中删除了对以下操作系统的支持：

   * OS/2 (bpo-16135(1)).

   * Windows 2000（变更集e52df05b496a）。

   * Windows系统中 ‘COMSPEC’ 指向 ‘command.com’ 的版本（ bpo-14470(2) ）
     。

   * VMS (bpo-16136(3)).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16135

   (2) https://bugs.python.org/issue14470

   (3) https://bugs.python.org/issue16136


File: python.info,  Node: API 与特性的移除<5>,  Next: Code Cleanups,  Prev: 不再支持的操作系统,  Up: 移除<5>

1.6.7.2 API 与特性的移除
........................

The following obsolete and previously deprecated APIs and features have
been removed:

   * The unmaintained ‘Misc/TextMate’ and ‘Misc/vim’ directories have
     been removed (see the devguide(1) for suggestions on what to use
     instead).

   * The ‘SO’ makefile macro is removed (it was replaced by the
     ‘SHLIB_SUFFIX’ and ‘EXT_SUFFIX’ macros) (bpo-16754(2)).

   * The ‘PyThreadState.tick_counter’ field has been removed; its value
     has been meaningless since Python 3.2, when the "new GIL" was
     introduced (bpo-19199(3)).

   * ‘PyLoader’ and ‘PyPycLoader’ have been removed from *note
     importlib: 9a.  (Contributed by Taras Lyapun in bpo-15641(4).)

   * The `strict' argument to *note HTTPConnection: 498. and *note
     HTTPSConnection: 499. has been removed.  HTTP 0.9-style "Simple
     Responses" are no longer supported.

   * The deprecated *note urllib.request.Request: 9dc. getter and setter
     methods ‘add_data’, ‘has_data’, ‘get_data’, ‘get_type’, ‘get_host’,
     ‘get_selector’, ‘set_proxy’, ‘get_origin_req_host’, and
     ‘is_unverifiable’ have been removed (use direct attribute access
     instead).

   * Support for loading the deprecated ‘TYPE_INT64’ has been removed
     from *note marshal: b0.  (Contributed by Dan Riti in bpo-15480(5).)

   * *note inspect.Signature: 7e4.: positional-only parameters are now
     required to have a valid name.

   * *note object.__format__(): a2f. no longer accepts non-empty format
     strings, it now raises a *note TypeError: 1fe. 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 *note
     TypeError: 1fe. if you are using an ‘'s'’ format code with objects
     that do not have a __format__ method that handles it.  See
     bpo-7994(6) for background.

   * ‘difflib.SequenceMatcher.isbjunk()’ and
     ‘difflib.SequenceMatcher.isbpopular()’ were deprecated in 3.2, and
     have now been removed: use ‘x in sm.bjunk’ and ‘x in sm.bpopular’,
     where `sm' is a *note SequenceMatcher: a30. object (bpo-13248(7)).

   ---------- Footnotes ----------

   (1) https://devguide.python.org

   (2) https://bugs.python.org/issue16754

   (3) https://bugs.python.org/issue19199

   (4) https://bugs.python.org/issue15641

   (5) https://bugs.python.org/issue15480

   (6) https://bugs.python.org/issue7994

   (7) https://bugs.python.org/issue13248


File: python.info,  Node: Code Cleanups,  Prev: API 与特性的移除<5>,  Up: 移除<5>

1.6.7.3 Code Cleanups
.....................

   * The unused and undocumented internal ‘Scanner’ class has been
     removed from the *note pydoc: d9. module.

   * The private and effectively unused ‘_gestalt’ module has been
     removed, along with the private *note platform: ce. functions
     ‘_mac_ver_lookup’, ‘_mac_ver_gstalt’, and ‘_bcd2str’, which would
     only have ever been called on badly broken OSX systems (see
     bpo-18393(1)).

   * The hardcoded copies of certain *note stat: f4. constants that were
     included in the *note tarfile: 101. module namespace have been
     removed.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18393


File: python.info,  Node: 移植到 Python 3 4,  Next: 3 4 3 的变化,  Prev: 移除<5>,  Up: Python 3 4 有什么新变化

1.6.8 移植到 Python 3.4
-----------------------

本节列出了先前描述的更改以及可能需要更改代码的其他错误修正.

* Menu:

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


File: python.info,  Node: 'python' 命令行为的变化<2>,  Next: Python API 的变化<2>,  Up: 移植到 Python 3 4

1.6.8.1 ’python’ 命令行为的变化
...............................

   * In a posix shell, setting the ‘PATH’ environment variable to an
     empty value is equivalent to not setting it at all.  However,
     setting *note PYTHONPATH: a34. to an empty value was `not'
     equivalent to not setting it at all: setting *note PYTHONPATH: a34.
     to an empty value was equivalent to setting it to ‘.’, which leads
     to confusion when reasoning by analogy to how ‘PATH’ works.  The
     behavior now conforms to the posix convention for ‘PATH’.

   * The [X refs, Y blocks] output of a debug (‘--with-pydebug’) build
     of the CPython interpreter is now off by default.  It can be
     re-enabled using the ‘-X showrefcount’ option.  (Contributed by
     Ezio Melotti in bpo-17323(1).)

   * The python command and most stdlib scripts (as well as *note
     argparse: 5.) now output ‘--version’ information to ‘stdout’
     instead of ‘stderr’ (for issue list see *note 其他改进: a0f.
     above).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17323


File: python.info,  Node: Python API 的变化<2>,  Next: C API 的变化<2>,  Prev: 'python' 命令行为的变化<2>,  Up: 移植到 Python 3 4

1.6.8.2 Python API 的变化
.........................

   * The ABCs defined in *note importlib.abc: 9b. now either raise the
     appropriate exception or return a default value instead of raising
     *note NotImplementedError: 704. blindly.  This will only affect
     code calling *note super(): 5dd. and falling through all the way to
     the ABCs.  For compatibility, catch both *note NotImplementedError:
     704. or the appropriate exception as needed.

   * The module type now initializes the *note __package__: a36. and
     *note __loader__: a37. attributes to ‘None’ by default.  To
     determine if these attributes were set in a backwards-compatible
     fashion, use e.g.  ‘getattr(module, '__loader__', None) is not
     None’.  (bpo-17115(1).)

   * *note importlib.util.module_for_loader(): a26. now sets
     ‘__loader__’ and ‘__package__’ unconditionally to properly support
     reloading.  If this is not desired then you will need to set these
     attributes manually.  You can use ‘importlib.util.module_to_load()’
     for module management.

   * Import now resets relevant attributes (e.g.  ‘__name__’,
     ‘__loader__’, ‘__package__’, ‘__file__’, ‘__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(2)).

   * Frozen packages no longer set ‘__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 ‘hasattr(module, '__path__')’
     (bpo-18065(3)).

   * Frozen modules no longer define a ‘__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 ‘__spec__.location’ is set to ‘'frozen'’, check if the
     loader is a subclass of *note importlib.machinery.FrozenImporter:
     a38, or if Python 2 compatibility is necessary you can use
     ‘imp.is_frozen()’.

   * *note py_compile.compile(): 343. now raises *note FileExistsError:
     a39. 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.

   * *note importlib.abc.SourceLoader.get_source(): a3a. no longer
     raises *note ImportError: 16c. when the source code being loaded
     triggers a *note SyntaxError: 559. or *note UnicodeDecodeError:
     32b.  As *note ImportError: 16c. 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.

   * *note functools.update_wrapper(): a3b. and *note functools.wraps():
     955. now correctly set the ‘__wrapped__’ attribute to the function
     being wrapped, even if that function also had its ‘__wrapped__’
     attribute set.  This means ‘__wrapped__’ attributes now correctly
     link a stack of decorated functions rather than every ‘__wrapped__’
     attribute in the chain referring to the innermost function.
     Introspection libraries that assumed the previous behaviour was
     intentional can use *note inspect.unwrap(): 954. to access the
     first function in the chain that has no ‘__wrapped__’ attribute.

   * *note inspect.getfullargspec(): 657. has been reimplemented on top
     of *note inspect.signature(): 655. 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 *note inspect.getfullargspec():
     657. will fail on non-Python callables may need to be adjusted
     accordingly.

   * *note importlib.machinery.PathFinder: a3c. now passes on the
     current working directory to objects in *note sys.path_hooks: a3d.
     for the empty string.  This results in *note
     sys.path_importer_cache: 597. never containing ‘''’, thus iterating
     through *note sys.path_importer_cache: 597. based on *note
     sys.path: 261. will not find all keys.  A module’s ‘__file__’ when
     imported in the current working directory will also now have an
     absolute path, including when using ‘-m’ with the interpreter
     (except for ‘__main__.__file__’ when a script has been executed
     directly using a relative path) (Contributed by Brett Cannon in
     bpo-18416(4)).  is specified on the command-line) (bpo-18416(5)).

   * The removal of the `strict' argument to *note HTTPConnection: 498.
     and *note HTTPSConnection: 499. 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.

   * Strings between ‘from __future__ import ...’ statements now
     `always' raise a *note SyntaxError: 559.  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(6)).

   * *note ssl.SSLSocket.getpeercert(): 9b7. and *note
     ssl.SSLSocket.do_handshake(): 849. now raise an *note OSError: 304.
     with ‘ENOTCONN’ when the ‘SSLSocket’ is not connected, instead of
     the previous behavior of raising an *note AttributeError: 4a1.  In
     addition, *note getpeercert(): 9b7. will raise a *note ValueError:
     16d. if the handshake has not yet been done.

   * *note base64.b32decode(): a3e. now raises a *note binascii.Error:
     a3f. when the input string contains non-b32-alphabet characters,
     instead of a *note TypeError: 1fe.  This particular *note
     TypeError: 1fe. was missed when the other *note TypeError: 1fe.s
     were converted.  (Contributed by Serhiy Storchaka in bpo-18011(7).)
     Note: this change was also inadvertently applied in Python 3.3.3.

   * The ‘file’ attribute is now automatically closed when the creating
     ‘cgi.FieldStorage’ instance is garbage collected.  If you were
     pulling the file object out separately from the ‘cgi.FieldStorage’
     instance and not keeping the instance alive, then you should either
     store the entire ‘cgi.FieldStorage’ instance or read the contents
     of the file before the ‘cgi.FieldStorage’ instance is garbage
     collected.

   * Calling ‘read’ or ‘write’ on a closed SSL socket now raises an
     informative *note ValueError: 16d. rather than the previous more
     mysterious *note AttributeError: 4a1. (bpo-9177(8)).

   * *note slice.indices(): a40. no longer produces an *note
     OverflowError: a41. for huge values.  As a consequence of this fix,
     *note slice.indices(): a40. now raises a *note ValueError: 16d. if
     given a negative length; previously it returned nonsense values
     (bpo-14794(9)).

   * The *note complex: 2c1. constructor, unlike the *note cmath: 18.
     functions, was incorrectly accepting *note float: 1fd. values if an
     object’s ‘__complex__’ special method returned one.  This now
     raises a *note TypeError: 1fe.  (bpo-16290(10).)

   * The *note int: 204. constructor in 3.2 and 3.3 erroneously accepts
     *note float: 1fd. values for the `base' parameter.  It is unlikely
     anyone was doing this, but if so, it will now raise a *note
     TypeError: 1fe. (bpo-16772(11)).

   * Defaults for keyword-only arguments are now evaluated `after'
     defaults for regular keyword arguments, instead of before.
     Hopefully no one wrote any code that depends on the previous buggy
     behavior (bpo-16967(12)).

   * Stale thread states are now cleared after *note fork(): a42.  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(13).)

   * Parameter names in ‘__annotations__’ dicts are now mangled
     properly, similarly to ‘__kwdefaults__’.  (Contributed by Yury
     Selivanov in bpo-20625(14).)

   * *note hashlib.hash.name: 93e. 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(15)).

   * Because *note unittest.TestSuite: 7c1. now drops references to
     tests after they are run, test harnesses that re-use a *note
     TestSuite: 7c1. 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 *note
     unittest: 124. is designed to provide.  However, if the lack of
     isolation is considered acceptable, the old behavior can be
     restored by creating a *note TestSuite: 7c1. subclass that defines
     a ‘_removeTestAtIndex’ method that does nothing (see *note
     TestSuite.__iter__(): a43.) (bpo-11798(16)).

   * *note unittest: 124. now uses *note argparse: 5. 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.

   * The *note re.split(): 4d0, *note re.findall(): a44, and *note
     re.sub(): 579. functions, and the ‘group()’ and ‘groups()’ methods
     of ‘match’ objects now always return a `bytes' object when the
     string to be matched is a *note bytes-like object: 6df.  Previously
     the return type matched the input type, so if your code was
     depending on the return value being, say, a ‘bytearray’, you will
     need to change your code.

   * *note audioop: c. functions now raise an error immediately if
     passed string input, instead of failing randomly later on
     (bpo-16685(17)).

   * The new `convert_charrefs' argument to *note HTMLParser: 22a.
     currently defaults to ‘False’ for backward compatibility, but will
     eventually be changed to default to ‘True’.  It is recommended that
     you add this keyword, with the appropriate value, to any *note
     HTMLParser: 22a. calls in your code (bpo-13633(18)).

   * Since the `digestmod' argument to the *note hmac.new(): 940.
     function will in the future have no default, all calls to *note
     hmac.new(): 940. should be changed to explicitly specify a
     `digestmod' (bpo-17276(19)).

   * Calling *note sysconfig.get_config_var(): a45. with the ‘SO’ key,
     or looking ‘SO’ up in the results of a call to *note
     sysconfig.get_config_vars(): a46. is deprecated.  This key should
     be replaced by ‘EXT_SUFFIX’ or ‘SHLIB_SUFFIX’, depending on the
     context (bpo-19555(20)).

   * Any calls to ‘open’ functions that specify ‘U’ should be modified.
     ‘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 `newline' argument, or if
     necessary by wrapping the stream in *note TextIOWrapper: 6ea. to
     use its `newline' argument (bpo-15204(21)).

   * If you use ‘pyvenv’ in a script and desire that pip `not' be
     installed, you must add ‘--without-pip’ to your command invocation.

   * The default behavior of *note json.dump(): 6fb. and *note
     json.dumps(): 6fc. 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(22)).

   * *note doctest: 66. now looks for doctests in extension module
     ‘__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(23)).

   * The *note collections.abc: 1e. 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 *note collections:
     1d. automatically imports *note collections.abc: 1e.  If your
     program depended on the (undocumented) implicit import, you will
     need to add an explicit ‘import collections.abc’ (bpo-20784(24)).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17115

   (2) https://bugs.python.org/issue19413

   (3) https://bugs.python.org/issue18065

   (4) https://bugs.python.org/issue18416

   (5) https://bugs.python.org/issue18416

   (6) https://bugs.python.org/issue17434

   (7) https://bugs.python.org/issue18011

   (8) https://bugs.python.org/issue9177

   (9) https://bugs.python.org/issue14794

   (10) https://bugs.python.org/issue16290

   (11) https://bugs.python.org/issue16772

   (12) https://bugs.python.org/issue16967

   (13) https://bugs.python.org/issue17094

   (14) https://bugs.python.org/issue20625

   (15) https://bugs.python.org/issue18532

   (16) https://bugs.python.org/issue11798

   (17) https://bugs.python.org/issue16685

   (18) https://bugs.python.org/issue13633

   (19) https://bugs.python.org/issue17276

   (20) https://bugs.python.org/issue19555

   (21) https://bugs.python.org/issue15204

   (22) https://bugs.python.org/issue16333

   (23) https://bugs.python.org/issue3158

   (24) https://bugs.python.org/issue20784


File: python.info,  Node: C API 的变化<2>,  Prev: Python API 的变化<2>,  Up: 移植到 Python 3 4

1.6.8.3 C API 的变化
....................

   * *note PyEval_EvalFrameEx(): a48, *note PyObject_Repr(): a49, and
     *note PyObject_Str(): a4a, 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 *note PyErr_Fetch(): a4b. or is being
     deliberately replaced with a different exception), an explicit
     *note PyErr_Clear(): a4c. 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.

   * *note PyErr_SetImportError(): 6ef. now sets *note TypeError: 1fe.
     when its `msg' argument is not set.  Previously only ‘NULL’ was
     returned with no exception set.

   * The result of the *note PyOS_ReadlineFunctionPointer: a4d. callback
     must now be a string allocated by *note PyMem_RawMalloc(): a4e. or
     *note PyMem_RawRealloc(): a4f, or ‘NULL’ if an error occurred,
     instead of a string allocated by *note PyMem_Malloc(): 5fe. or
     *note PyMem_Realloc(): a50. (bpo-16742(1))

   * *note PyThread_set_key_value(): a51. 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-‘NULL’ pointer).

   * The ‘f_tstate’ (thread state) field of the *note PyFrameObject:
     a52. structure has been removed to fix a bug: see bpo-14432(2) for
     the rationale.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16742

   (2) https://bugs.python.org/issue14432


File: python.info,  Node: 3 4 3 的变化,  Prev: 移植到 Python 3 4,  Up: Python 3 4 有什么新变化

1.6.9 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.


File: python.info,  Node: PEP 476 Enabling certificate verification by default for stdlib http clients,  Up: 3 4 3 的变化

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

*note http.client: 93. and modules which use it, such as *note
urllib.request: 129. and *note xmlrpc.client: 148, 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:

     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)


File: python.info,  Node: Python 3 3 有什么新变化,  Next: Python 3 2 有什么新变化,  Prev: Python 3 4 有什么新变化,  Up: Python 有什麼新功能？

1.7 Python 3.3 有什么新变化
===========================

本文介绍了Python 3.3相比 3.2 的新增特性。Python 3.3于2012年9月29日发布。
有关完整详细信息，请参见 changelog(1)。

也參考
......

PEP 398(2) - 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.

   ---------- Footnotes ----------

   (1) https://docs.python.org/3.3/whatsnew/changelog.html

   (2) https://www.python.org/dev/peps/pep-0398


File: python.info,  Node: 摘要 - 发布重点<7>,  Next: PEP 405 虚拟环境,  Up: Python 3 3 有什么新变化

1.7.1 摘要 - 发布重点
---------------------

新的语法特性：

   * New ‘yield from’ expression for *note generator delegation: a59.

   * The ‘u'unicode'’ syntax is accepted again for *note str: 205.
     objects.

新的库模块：

   * *note faulthandler: 7b. （帮助调试低级崩溃）

   * *note ipaddress: a2. (high-level objects representing IP addresses
     and masks)

   * *note lzma: ad. (compress data using the XZ / LZMA algorithm)

   * *note unittest.mock: 125. (replace parts of your system under test
     with mock objects)

   * *note venv: 12e. (Python *note virtual environments: a5a, as in the
     popular ‘virtualenv’ package)

新的内置特性：

   * 重写 *note I/O 异常的层次结构: a5b.

实现的改进：

   * 基于 *note importlib: 9a. 重写 *note import machinery: a5c.

   * More compact *note unicode strings: a5d.

   * More compact *note attribute dictionaries: a5e.

显着改进的库模块：

   * C Accelerator for the *note decimal: a5f. module.

   * Better unicode handling in the *note email: a60. module (*note
     provisional: a61.).

安全改进：

   * Hash randomization is switched on by default.

Please read on for a comprehensive list of user-facing changes.


File: python.info,  Node: PEP 405 虚拟环境,  Next: PEP 420 隐式命名空间包,  Prev: 摘要 - 发布重点<7>,  Up: Python 3 3 有什么新变化

1.7.2 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
‘virtualenv’ third-party package, but benefit from tighter integration
with the interpreter core.

This PEP adds the *note venv: 12e. module for programmatic access, and
the ‘pyvenv’ script for command-line access and administration.  The
Python interpreter checks for a ‘pyvenv.cfg’, file whose existence
signals the base of a virtual environment’s directory tree.

也參考
......

PEP 405(1) - Python虚拟环境

     PEP 由 Carl Meyer 撰写 ; 由 Carl Meyer 和 Vinay Sajip 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0405


File: python.info,  Node: PEP 420 隐式命名空间包,  Next: PEP 3118 新的内存视图实现和缓冲协议文档,  Prev: PEP 405 虚拟环境,  Up: Python 3 3 有什么新变化

1.7.3 PEP 420: 隐式命名空间包
-----------------------------

Native support for package directories that don’t require ‘__init__.py’
marker files and can automatically span multiple path segments (inspired
by various third party approaches to namespace packages, as described in
PEP 420(1))

也參考
......

PEP 420(2) - 隐式命名空间包

     PEP 由 Eric V. Smith 撰写，由 Eric V. Smith 和 Barry Warsaw 实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0420

   (2) https://www.python.org/dev/peps/pep-0420


File: python.info,  Node: PEP 3118 新的内存视图实现和缓冲协议文档,  Next: PEP 393 灵活的字符串表示,  Prev: PEP 420 隐式命名空间包,  Up: Python 3 3 有什么新变化

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

The implementation of PEP 3118(1) has been significantly improved.

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 changes::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3118


File: python.info,  Node: 相关特性,  Next: API changes,  Up: PEP 3118 新的内存视图实现和缓冲协议文档

1.7.4.1 相关特性
................

   * All native single character format specifiers in struct module
     syntax (optionally prefixed with ’@’) are now supported.

   * With some restrictions, the cast() method allows changing of format
     and shape of C-contiguous arrays.

   * Multi-dimensional list representations are supported for any array
     type.

   * Multi-dimensional comparisons are supported for any array type.

   * One-dimensional memoryviews of hashable (read-only) types with
     formats B, b or c are now hashable.  (Contributed by Antoine Pitrou
     in bpo-13411(1).)

   * 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13411


File: python.info,  Node: API changes,  Prev: 相关特性,  Up: PEP 3118 新的内存视图实现和缓冲协议文档

1.7.4.2 API changes
...................

   * The maximum number of dimensions is officially limited to 64.

   * The representation of empty shape, strides and suboffsets is now an
     empty tuple instead of ‘None’.

   * 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.

   * 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.

   * For further changes see *note Build and C API Changes: a68. and
     *note Porting C code: a69.

（由 Stefan Krah 在 bpo-10181(1) 中贡献。）

也參考
......

PEP 3118(2) - 修改缓冲区协议

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10181

   (2) https://www.python.org/dev/peps/pep-3118


File: python.info,  Node: PEP 393 灵活的字符串表示,  Next: PEP 397 适用于Windows的Python启动器,  Prev: PEP 3118 新的内存视图实现和缓冲协议文档,  Up: Python 3 3 有什么新变化

1.7.5 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, PEP 393(1) 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:

* Functionality::
* Performance and resource usage::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0393


File: python.info,  Node: Functionality,  Next: Performance and resource usage,  Up: PEP 393 灵活的字符串表示

1.7.5.1 Functionality
.....................

Changes introduced by PEP 393(1) are the following:

   * Python now always supports the full range of Unicode code points,
     including non-BMP ones (i.e.  from ‘U+0000’ to ‘U+10FFFF’).  The
     distinction between narrow and wide builds no longer exists and
     Python now behaves like a wide build, even under Windows.

   * With the death of narrow builds, the problems specific to narrow
     builds have also been fixed, for example:

        * *note len(): 28b. now always returns 1 for non-BMP characters,
          so ‘len('\U0010FFFF') == 1’;

        * surrogate pairs are not recombined in string literals, so
          ‘'\uDBFF\uDFFF' != '\U0010FFFF'’;

        * indexing or slicing non-BMP characters returns the expected
          value, so ‘'\U0010FFFF'[0]’ now returns ‘'\U0010FFFF'’ and not
          ‘'\uDBFF'’;

        * all other functions in the standard library now correctly
          handle non-BMP code points.

   * The value of *note sys.maxunicode: a6c. is now always ‘1114111’
     (‘0x10FFFF’ in hexadecimal).  The ‘PyUnicode_GetMax()’ function
     still returns either ‘0xFFFF’ or ‘0x10FFFF’ for backward
     compatibility, and it should not be used with the new Unicode API
     (see bpo-13054(2)).

   * The ‘./configure’ flag ‘--with-wide-unicode’ has been removed.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0393

   (2) https://bugs.python.org/issue13054


File: python.info,  Node: Performance and resource usage,  Prev: Functionality,  Up: PEP 393 灵活的字符串表示

1.7.5.2 Performance and resource usage
......................................

The storage of Unicode strings now depends on the highest code point in
the string:

   * pure ASCII and Latin1 strings (‘U+0000-U+00FF’) use 1 byte per code
     point;

   * BMP strings (‘U+0000-U+FFFF’) use 2 bytes per code point;

   * non-BMP strings (‘U+10000-U+10FFFF’) use 4 bytes per code point.

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).

也參考
......

PEP 393(1) - 灵活的字符串表示

     PEP 由 Martin von Löwis 撰写 ; 由 Torsten Becker 和 Martin von
     Löwis 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0393


File: python.info,  Node: PEP 397 适用于Windows的Python启动器,  Next: PEP 3151 重写 OS 和 IO 异常的层次结构,  Prev: PEP 393 灵活的字符串表示,  Up: Python 3 3 有什么新变化

1.7.6 PEP 397: 适用于Windows的Python启动器
------------------------------------------

The Python 3.3 Windows installer now includes a ‘py’ launcher
application that can be used to launch Python applications in a version
independent fashion.

This launcher is invoked implicitly when double-clicking ‘*.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
‘py’ application.  Running ‘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 ‘-3’ to request
Python 3 when Python 2 is also installed, or ‘-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(1).)

也參考
......

PEP 397(2) - 适用于Windows的Python启动器

     PEP 由 Mark Hammond 和 Martin v.  Löwis 撰写 ; 由 Vinay Sajip实现。

Launcher documentation: *note 适用于Windows的Python启动器: a70.

Installer PATH modification: *note 查找Python可执行文件: a71.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue3561

   (2) https://www.python.org/dev/peps/pep-0397


File: python.info,  Node: PEP 3151 重写 OS 和 IO 异常的层次结构,  Next: PEP 380 委托给子生成器的语法,  Prev: PEP 397 适用于Windows的Python启动器,  Up: Python 3 3 有什么新变化

1.7.7 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 *note OSError: 304, *note IOError: a73, *note
EnvironmentError: a74, *note WindowsError: a75, ‘mmap.error’, *note
socket.error: a76. or *note select.error: a77.  All these exception
types are now only one: *note OSError: 304.  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 ‘errno’ attribute (or ‘args[0]’) for a particular
constant from the *note errno: 7a. module, you can catch the adequate
*note OSError: 304. subclass.  The available subclasses are the
following:

   * *note BlockingIOError: a78.

   * *note ChildProcessError: a79.

   * *note ConnectionError: 7d7.

   * *note FileExistsError: a39.

   * *note FileNotFoundError: 8ad.

   * *note InterruptedError: 74c.

   * *note IsADirectoryError: a7a.

   * *note NotADirectoryError: a7b.

   * *note PermissionError: 6f6.

   * *note ProcessLookupError: a7c.

   * *note TimeoutError: a7d.

And the *note ConnectionError: 7d7. itself has finer-grained subclasses:

   * *note BrokenPipeError: a7e.

   * *note ConnectionAbortedError: a7f.

   * *note ConnectionRefusedError: a80.

   * *note ConnectionResetError: a81.

Thanks to the new exceptions, common usages of the *note errno: 7a. can
now be avoided.  For example, the following code written for Python 3.2:

     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

can now be written without the *note errno: 7a. import and without
manual inspection of exception attributes:

     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")

也參考
......

PEP 3151(1) - 重写 OS 和 IO 异常的层次结构

     PEP 由 Antoine Pitrou 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3151


File: python.info,  Node: PEP 380 委托给子生成器的语法,  Next: PEP 409 清除异常上下文,  Prev: PEP 3151 重写 OS 和 IO 异常的层次结构,  Up: Python 3 3 有什么新变化

1.7.8 PEP 380: 委托给子生成器的语法
-----------------------------------

PEP 380 adds the ‘yield from’ expression, allowing a *note generator:
a83. to delegate part of its operations to another generator.  This
allows a section of code containing *note yield: 2c7. 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
‘yield from’ expression actually allows delegation to arbitrary
subiterators.

For simple iterators, ‘yield from iterable’ is essentially just a
shortened form of ‘for item in iterable: yield item’:

     >>> 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]

However, unlike an ordinary loop, ‘yield from’ allows subgenerators to
receive sent and thrown values directly from the calling scope, and
return a final value to the outer generator:

     >>> 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]

The main principle driving this change is to allow even generators that
are designed to be used with the ‘send’ and ‘throw’ methods to be split
into multiple subgenerators as easily as a single large function can be
split into multiple subfunctions.

也參考
......

PEP 380(1) - 委托给子生成器的语法

     PEP 由 Greg Ewing 撰写，由 Greg Ewing 实现。由 Renaud Blanch，Ryan
     Kelly 和 Nick Coghlan 集成到3.3，由 Zbigniew Jędrzejewski-Szmek 和
     Nick Coghlan 编写文档

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0380


File: python.info,  Node: PEP 409 清除异常上下文,  Next: PEP 414 显式的Unicode文本,  Prev: PEP 380 委托给子生成器的语法,  Up: Python 3 3 有什么新变化

1.7.9 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:

     >>> 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

Without the ‘from None’ suffix to suppress the cause, the original
exception would be displayed by default:

     >>> 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

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):

     >>> try:
     ...     D({}).x
     ... except AttributeError as exc:
     ...     print(repr(exc.__context__))
     ...
     KeyError('x',)

也參考
......

PEP 409(1) - 清除异常上下文

     PEP 由 Ethan Furman 撰写 ，由 Ethan Furman 和 Nick Coghlan 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0409


File: python.info,  Node: PEP 414 显式的Unicode文本,  Next: PEP 3155 类和函数的限定名称,  Prev: PEP 409 清除异常上下文,  Up: Python 3 3 有什么新变化

1.7.10 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 "‘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).

也參考
......

PEP 414(1) - 显式的Unicode文本

     PEP 由 Armin Ronacher 撰写

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0414


File: python.info,  Node: PEP 3155 类和函数的限定名称,  Next: PEP 412 Key-Sharing Dictionary,  Prev: PEP 414 显式的Unicode文本,  Up: Python 3 3 有什么新变化

1.7.11 PEP 3155: 类和函数的限定名称
-----------------------------------

Functions and class objects have a new ‘__qualname__’ attribute
representing the "path" from the module top-level to their definition.
For global functions and classes, this is the same as ‘__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:

     >>> class C:
     ...     def meth(self):
     ...         pass
     >>> C.meth.__name__
     'meth'
     >>> C.meth.__qualname__
     'C.meth'

Example with nested classes:

     >>> 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'

Example with nested functions:

     >>> def outer():
     ...     def inner():
     ...         pass
     ...     return inner
     ...
     >>> outer().__name__
     'inner'
     >>> outer().__qualname__
     'outer.<locals>.inner'

The string representation of those objects is also changed to include
the new, more precise information:

     >>> str(C.D)
     "<class '__main__.C.D'>"
     >>> str(C.D.meth)
     '<function C.D.meth at 0x7f46b9fe31e0>'

也參考
......

PEP 3155(1) - 类和函数的限定名称

     PEP 由 Antoine Pitrou 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3155


File: python.info,  Node: PEP 412 Key-Sharing Dictionary,  Next: PEP 362 函数签名对象,  Prev: PEP 3155 类和函数的限定名称,  Up: Python 3 3 有什么新变化

1.7.12 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.

也參考
......

PEP 412(1) - Key-Sharing Dictionary

     PEP 由 Mark Shannon 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0412


File: python.info,  Node: PEP 362 函数签名对象,  Next: PEP 421 添加 sys implementation,  Prev: PEP 412 Key-Sharing Dictionary,  Up: Python 3 3 有什么新变化

1.7.13 PEP 362: 函数签名对象
----------------------------

A new function *note inspect.signature(): 655. makes introspection of
python callables easy and straightforward.  A broad range of callables
is supported: python functions, decorated or not, classes, and *note
functools.partial(): 8b5. objects.  New classes *note inspect.Signature:
7e4, *note inspect.Parameter: 7e5. and *note inspect.BoundArguments:
a89. 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.

也參考
......

PEP 362(1): - 函数签名对象

     PEP 由 Brett Cannon，Yury Selivanov，Larry Hastings，Jiwon Seo 撰写
     ，由 Yury Selivanov 实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0362


File: python.info,  Node: PEP 421 添加 sys implementation,  Next: Using importlib as the Implementation of Import,  Prev: PEP 362 函数签名对象,  Up: Python 3 3 有什么新变化

1.7.14 PEP 421: 添加 sys.implementation
---------------------------------------

A new attribute on the *note sys: fd. module exposes details specific to
the implementation of the currently running interpreter.  The initial
set of attributes on *note sys.implementation: a8b. are ‘name’,
‘version’, ‘hexversion’, and ‘cache_tag’.

The intention of ‘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,
‘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 ‘cache_tag’.  As
of Python 3.3, ‘sys.implementation.cache_tag’ is used by *note
importlib: 9a. to support PEP 3147(1) compliance.  Any Python
implementation that uses ‘importlib’ for its built-in import system may
use ‘cache_tag’ to control the caching behavior for modules.

* Menu:

* SimpleNamespace::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3147


File: python.info,  Node: SimpleNamespace,  Up: PEP 421 添加 sys implementation

1.7.14.1 SimpleNamespace
........................

The implementation of ‘sys.implementation’ also introduces a new type to
Python: *note types.SimpleNamespace: 1d8.  In contrast to a
mapping-based namespace, like *note dict: 164, ‘SimpleNamespace’ is
attribute-based, like *note object: 3d2.  However, unlike ‘object’,
‘SimpleNamespace’ instances are writable.  This means that you can add,
remove, and modify the namespace through normal attribute access.

也參考
......

PEP 421(1) - 添加 sys.implementation

     PEP 由 Eric Snow 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0421


File: python.info,  Node: Using importlib as the Implementation of Import,  Next: 其他语言特性修改<7>,  Prev: PEP 421 添加 sys implementation,  Up: Python 3 3 有什么新变化

1.7.15 Using importlib as the Implementation of Import
------------------------------------------------------

bpo-2377(1) - Replace __import__ w/ importlib.__import__ bpo-13959(2) -
Re-implement parts of *note imp: 99. in pure Python bpo-14605(3) - Make
import machinery explicit bpo-14646(4) - Require loaders set __loader__
and __package__

The *note __import__(): 16b. function is now powered by *note
importlib.__import__(): a8e.  This work leads to the completion of
"phase 2" of PEP 302(5).  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 *note Porting Python code: a8f. section of this document.

* Menu:

* New APIs::
* Visible Changes::

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue2377

   (2) https://bugs.python.org/issue13959

   (3) https://bugs.python.org/issue14605

   (4) https://bugs.python.org/issue14646

   (5) https://www.python.org/dev/peps/pep-0302


File: python.info,  Node: New APIs,  Next: Visible Changes,  Up: Using importlib as the Implementation of Import

1.7.15.1 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 *note importlib:
9a. package.

The abstract base classes defined in *note importlib.abc: 9b. have been
expanded to properly delineate between *note meta path finders: a91. and
*note path entry finders: a92. by introducing *note
importlib.abc.MetaPathFinder: a93. and *note
importlib.abc.PathEntryFinder: a94, respectively.  The old ABC of *note
importlib.abc.Finder: a95. is now only provided for
backwards-compatibility and does not enforce any method requirements.

In terms of finders, *note importlib.machinery.FileFinder: a96. exposes
the mechanism used to search for source and bytecode files of a module.
Previously this class was an implicit member of *note sys.path_hooks:
a3d.

For loaders, the new abstract base class *note importlib.abc.FileLoader:
a97. helps write a loader that uses the file system as the storage
mechanism for a module’s code.  The loader for source files (*note
importlib.machinery.SourceFileLoader: a98.), sourceless bytecode files
(*note importlib.machinery.SourcelessFileLoader: a99.), and extension
modules (*note importlib.machinery.ExtensionFileLoader: 650.) are now
available for direct use.

*note ImportError: 16c. now has ‘name’ and ‘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 *note importlib.invalidate_caches(): 596. function will now call the
method with the same name on all finders cached in *note
sys.path_importer_cache: 597. to help clean up any stored state as
necessary.


File: python.info,  Node: Visible Changes,  Prev: New APIs,  Up: Using importlib as the Implementation of Import

1.7.15.2 Visible Changes
........................

For potential required changes to code, see the *note Porting Python
code: a8f. section.

Beyond the expanse of what *note importlib: 9a. now exposes, there are
other visible changes to import.  The biggest is that *note
sys.meta_path: 6dd. and *note sys.path_hooks: a3d. 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 ‘__loader__’ attribute,
storing the loader used to create the module.  PEP 302(1) 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 ‘__package__’ attribute from
PEP 366(2).  Once again, import itself is already setting this on all
loaders from *note importlib: 9a. and import itself is setting the
attribute post-load.

‘None’ is now inserted into *note sys.path_importer_cache: 597. when no
finder can be found on *note sys.path_hooks: a3d.  Since *note
imp.NullImporter: a9b. is not directly exposed on *note sys.path_hooks:
a3d. 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 *note Porting Python code: a8f. section of this document.

(Implementation by Brett Cannon)

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0302

   (2) https://www.python.org/dev/peps/pep-0366


File: python.info,  Node: 其他语言特性修改<7>,  Next: A Finer-Grained Import Lock,  Prev: Using importlib as the Implementation of Import,  Up: Python 3 3 有什么新变化

1.7.16 其他语言特性修改
-----------------------

对Python 语言核心进行的小改动：

   * Added support for Unicode name aliases and named sequences.  Both
     *note unicodedata.lookup(): a9d. and ‘'\N{...}'’ now resolve name
     aliases, and *note unicodedata.lookup(): a9d. resolves named
     sequences too.

     （由 Ezio Melotti 在 bpo-12753(1) 中贡献。）

   * Unicode database updated to UCD version 6.1.0

   * Equality comparisons on *note range(): 1f5. objects now return a
     result reflecting the equality of the underlying sequences
     generated by those range objects.  (bpo-13201(2))

   * The ‘count()’, ‘find()’, ‘rfind()’, ‘index()’ and ‘rindex()’
     methods of *note bytes: 172. and *note bytearray: 173. objects now
     accept an integer between 0 and 255 as their first argument.

     （由 Petri Lehtinen 在 bpo-12170(3) 中贡献。）

   * The ‘rjust()’, ‘ljust()’, and ‘center()’ methods of *note bytes:
     172. and *note bytearray: 173. now accept a *note bytearray: 173.
     for the ‘fill’ argument.  (Contributed by Petri Lehtinen in
     bpo-12380(4).)

   * New methods have been added to *note list: 1f8. and *note
     bytearray: 173.: ‘copy()’ and ‘clear()’ (bpo-10516(5)).
     Consequently, *note MutableSequence: 79f. now also defines a
     ‘clear()’ method (bpo-11388(6)).

   * Raw bytes literals can now be written ‘rb"..."’ as well as
     ‘br"..."’.

     （由 Antoine Pitrou 在 bpo-13748(7) 中贡献。）

   * *note dict.setdefault(): a9e. now does only one lookup for the
     given key, making it atomic when used with built-in types.

     （由 Filip Gruszczyński 在 bpo-13521(8) 中贡献。）

   * The error messages produced when a function call does not match the
     function signature have been significantly improved.

     （由 Benjamin Peterson 贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue12753

   (2) https://bugs.python.org/issue13201

   (3) https://bugs.python.org/issue12170

   (4) https://bugs.python.org/issue12380

   (5) https://bugs.python.org/issue10516

   (6) https://bugs.python.org/issue11388

   (7) https://bugs.python.org/issue13748

   (8) https://bugs.python.org/issue13521


File: python.info,  Node: A Finer-Grained Import Lock,  Next: Builtin functions and types,  Prev: 其他语言特性修改<7>,  Up: Python 3 3 有什么新变化

1.7.17 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
*note PyImport_ImportModuleNoBlock(): aa0. 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(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue9260


File: python.info,  Node: Builtin functions and types,  Next: 新增模块<7>,  Prev: A Finer-Grained Import Lock,  Up: Python 3 3 有什么新变化

1.7.18 Builtin functions and types
----------------------------------

   * *note open(): 16f. gets a new `opener' parameter: the underlying
     file descriptor for the file object is then obtained by calling
     `opener' with (`file', `flags').  It can be used to use custom
     flags like *note os.O_CLOEXEC: aa2. for example.  The ‘'x'’ mode
     was added: open for exclusive creation, failing if the file already
     exists.

   * *note print(): 971.: added the `flush' keyword argument.  If the
     `flush' keyword argument is true, the stream is forcibly flushed.

   * *note hash(): aa3.: hash randomization is enabled by default, see
     *note object.__hash__(): 44c. and *note PYTHONHASHSEED: aa4.

   * The *note str: 205. type gets a new *note casefold(): 7a3. method:
     return a casefolded copy of the string, casefolded strings may be
     used for caseless matching.  For example, ‘'ß'.casefold()’ returns
     ‘'ss'’.

   * 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(1)).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue4966


File: python.info,  Node: 新增模块<7>,  Next: 改进的模块<7>,  Prev: Builtin functions and types,  Up: Python 3 3 有什么新变化

1.7.19 新增模块
---------------

* Menu:

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


File: python.info,  Node: faulthandler<3>,  Next: ipaddress<5>,  Up: 新增模块<7>

1.7.19.1 faulthandler
.....................

This new debug module *note faulthandler: 7b. 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 *note
faulthandler.enable(): 642. to install fault handlers for the ‘SIGSEGV’,
‘SIGFPE’, ‘SIGABRT’, ‘SIGBUS’, and ‘SIGILL’ signals.  You can also
enable them at startup by setting the *note PYTHONFAULTHANDLER: aa7.
environment variable or by using *note -X: 290. ‘faulthandler’ command
line option.

Example of a segmentation fault on Linux:

     $ 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


File: python.info,  Node: ipaddress<5>,  Next: lzma<2>,  Prev: faulthandler<3>,  Up: 新增模块<7>

1.7.19.2 ipaddress
..................

The new *note ipaddress: a2. 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(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue3144


File: python.info,  Node: lzma<2>,  Prev: ipaddress<5>,  Up: 新增模块<7>

1.7.19.3 lzma
.............

The newly-added *note lzma: ad. module provides data compression and
decompression using the LZMA algorithm, including support for the ‘.xz’
and ‘.lzma’ file formats.

（由 Nadeem Vawda 和 Per Øyvind Karlsen 在 bpo-6715(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue6715


File: python.info,  Node: 改进的模块<7>,  Next: 性能优化<6>,  Prev: 新增模块<7>,  Up: Python 3 3 有什么新变化

1.7.20 改进的模块
-----------------

* 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<4>.
* 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>.


File: python.info,  Node: abc<2>,  Next: array<2>,  Up: 改进的模块<7>

1.7.20.1 abc
............

Improved support for abstract base classes containing descriptors
composed with abstract methods.  The recommended approach to declaring
abstract descriptors is now to provide ‘__isabstractmethod__’ as a
dynamically updated property.  The built-in descriptors have been
updated accordingly.

        * *note abc.abstractproperty: aac. has been deprecated, use
          *note property: 308. with *note abc.abstractmethod(): aad.
          instead.

        * *note abc.abstractclassmethod: aae. has been deprecated, use
          *note classmethod: 309. with *note abc.abstractmethod(): aad.
          instead.

        * *note abc.abstractstaticmethod: aaf. has been deprecated, use
          *note staticmethod: 30a. with *note abc.abstractmethod(): aad.
          instead.

（由 Pablo Galindo 在 bpo-11610(1) 中贡献。）

*note abc.ABCMeta.register(): ab0. now returns the registered subclass,
which means it can now be used as a class decorator (bpo-10868(2)).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue11610

   (2) https://bugs.python.org/issue10868


File: python.info,  Node: array<2>,  Next: base64<2>,  Prev: abc<2>,  Up: 改进的模块<7>

1.7.20.2 array
..............

The *note array: 6. module supports the ‘long long’ type using ‘q’ and
‘Q’ type codes.

（由 Oren Tirosh 和 Hirokazu Yamamoto 在 bpo-1172711(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1172711


File: python.info,  Node: base64<2>,  Next: binascii<3>,  Prev: array<2>,  Up: 改进的模块<7>

1.7.20.3 base64
...............

ASCII-only Unicode strings are now accepted by the decoding functions of
the *note base64: d. modern interface.  For example,
‘base64.b64decode('YWJj')’ returns ‘b'abc'’.  (Contributed by Catalin
Iacob in bpo-13641(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13641


File: python.info,  Node: binascii<3>,  Next: bz2<2>,  Prev: base64<2>,  Up: 改进的模块<7>

1.7.20.4 binascii
.................

In addition to the binary objects they normally accept, the ‘a2b_’
functions now all also accept ASCII-only strings as input.  (Contributed
by Antoine Pitrou in bpo-13637(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13637


File: python.info,  Node: bz2<2>,  Next: 编码器,  Prev: binascii<3>,  Up: 改进的模块<7>

1.7.20.5 bz2
............

The *note bz2: 13. module has been rewritten from scratch.  In the
process, several new features have been added:

   * New *note bz2.open(): ab5. function: open a bzip2-compressed file
     in binary or text mode.

   * *note bz2.BZ2File: 224. can now read from and write to arbitrary
     file-like objects, by means of its constructor’s `fileobj'
     argument.

     （由 Nadeem Vawda 在 bpo-5863(1) 中贡献。）

   * *note bz2.BZ2File: 224. and *note bz2.decompress(): ab6. can now
     decompress multi-stream inputs (such as those produced by the
     ‘pbzip2’ tool).  *note bz2.BZ2File: 224. can now also be used to
     create this type of file, using the ‘'a'’ (append) mode.

     （由 Nir Aides 在 bpo-1625(2) 中贡献。）

   * *note bz2.BZ2File: 224. now implements all of the *note
     io.BufferedIOBase: 67f. API, except for the ‘detach()’ and
     ‘truncate()’ methods.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5863

   (2) https://bugs.python.org/issue1625


File: python.info,  Node: 编码器,  Next: collections<7>,  Prev: bz2<2>,  Up: 改进的模块<7>

1.7.20.6 编码器
...............

The *note mbcs: 76. codec has been rewritten to handle correctly
‘replace’ and ‘ignore’ error handlers on all Windows versions.  The
*note mbcs: 76. codec now supports all error handlers, instead of only
‘replace’ to encode and ‘ignore’ to decode.

A new Windows-only codec has been added: ‘cp65001’ (bpo-13216(1)).  It
is the Windows code page 65001 (Windows UTF-8, ‘CP_UTF8’).  For example,
it is used by ‘sys.stdout’ if the console output code page is set to
cp65001 (e.g., using ‘chcp 65001’ command).

Multibyte CJK decoders now resynchronize faster.  They only ignore the
first byte of an invalid byte sequence.  For example,
‘b'\xff\n'.decode('gb2312', 'replace')’ now returns a ‘\n’ after the
replacement character.

(bpo-12016(2))

Incremental CJK codec encoders are no longer reset at each call to their
encode() methods.  For example:

     >>> import codecs
     >>> encoder = codecs.getincrementalencoder('hz')('strict')
     >>> b''.join(encoder.encode(x) for x in '\u52ff\u65bd\u65bc\u4eba\u3002 Bye.')
     b'~{NpJ)l6HK!#~} Bye.'

This example gives ‘b'~{Np~}~{J)~}~{l6~}~{HK~}~{!#~} Bye.'’ with older
Python versions.

(bpo-12100(3))

The ‘unicode_internal’ codec has been deprecated.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13216

   (2) https://bugs.python.org/issue12016

   (3) https://bugs.python.org/issue12100


File: python.info,  Node: collections<7>,  Next: contextlib<5>,  Prev: 编码器,  Up: 改进的模块<7>

1.7.20.7 collections
....................

Addition of a new *note ChainMap: 5a3. class to allow treating a number
of mappings as a single unit.  (Written by Raymond Hettinger for
bpo-11089(1), made public in bpo-11297(2).)

The abstract base classes have been moved in a new *note
collections.abc: 1e. module, to better differentiate between the
abstract and the concrete collections classes.  Aliases for ABCs are
still present in the *note collections: 1d. module to preserve existing
imports.  (bpo-11085(3))

The *note Counter: ab9. class now supports the unary ‘+’ and ‘-’
operators, as well as the in-place operators ‘+=’, ‘-=’, ‘|=’, and ‘&=’.
(Contributed by Raymond Hettinger in bpo-13121(4).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue11089

   (2) https://bugs.python.org/issue11297

   (3) https://bugs.python.org/issue11085

   (4) https://bugs.python.org/issue13121


File: python.info,  Node: contextlib<5>,  Next: crypt<2>,  Prev: collections<7>,  Up: 改进的模块<7>

1.7.20.8 contextlib
...................

*note ExitStack: 47e. now provides a solid foundation for programmatic
manipulation of context managers and similar cleanup functionality.
Unlike the previous ‘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 ‘__init__’
method (for example, file objects) or in their ‘__enter__’ method (for
example, synchronisation objects from the *note threading: 10b. module).

(bpo-13585(1))

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13585


File: python.info,  Node: crypt<2>,  Next: curses<4>,  Prev: contextlib<5>,  Up: 改进的模块<7>

1.7.20.9 crypt
..............

Addition of salt and modular crypt format (hashing method) and the *note
mksalt(): 484. function to the *note crypt: 28. module.

(bpo-10924(1))

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10924


File: python.info,  Node: curses<4>,  Next: datetime<5>,  Prev: crypt<2>,  Up: 改进的模块<7>

1.7.20.10 curses
................

        * If the *note curses: 2b. module is linked to the ncursesw
          library, use Unicode functions when Unicode strings or
          characters are passed (e.g.  ‘waddwstr()’), and bytes
          functions otherwise (e.g.  ‘waddstr()’).

        * Use the locale encoding instead of ‘utf-8’ to encode Unicode
          strings.

        * ‘curses.window’ has a new *note curses.window.encoding: abd.
          attribute.

        * The ‘curses.window’ class has a new *note get_wch(): abe.
          method to get a wide character

        * The *note curses: 2b. module has a new *note unget_wch(): abf.
          function to push a wide character so the next *note get_wch():
          abe. will return it

（由 Iñigo Serna 在 bpo-6755(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue6755


File: python.info,  Node: datetime<5>,  Next: decimal<3>,  Prev: curses<4>,  Up: 改进的模块<7>

1.7.20.11 datetime
..................

        * Equality comparisons between naive and aware *note datetime:
          19f. instances now return *note False: 48e. instead of raising
          *note TypeError: 1fe. (bpo-15006(1)).

        * New *note datetime.datetime.timestamp(): ac1. method: Return
          POSIX timestamp corresponding to the *note datetime: 19f.
          instance.

        * The *note datetime.datetime.strftime(): 630. method supports
          formatting years older than 1000.

        * The *note datetime.datetime.astimezone(): 2cb. method can now
          be called without arguments to convert datetime instance to
          the system timezone.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15006


File: python.info,  Node: decimal<3>,  Next: email<4>,  Prev: datetime<5>,  Up: 改进的模块<7>

1.7.20.12 decimal
.................

bpo-7652(1) - integrate fast native decimal arithmetic.

     C-module and libmpdec written by Stefan Krah.

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 ‘http://www.bytereef.org/mpdecimal/quickstart.html’.

                   decimal.py        _decimal           加速
                                                        
     ---------------------------------------------------------------------
                                                        
     pi            42.02秒           0.345秒            120倍
                                                        
                                                        
     telco         172.19秒          5.68秒             30倍
                                                        
                                                        
     psycopg       3.57秒            0.29秒             12倍
                                                        

* Menu:

* 相关特性: 相关特性<2>.
* API changes: API changes<2>.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue7652


File: python.info,  Node: 相关特性<2>,  Next: API changes<2>,  Up: decimal<3>

1.7.20.13 相关特性
..................

   * The *note FloatOperation: ac4. signal optionally enables stricter
     semantics for mixing floats and Decimals.

   * If Python is compiled without threads, the C version automatically
     disables the expensive thread local context machinery.  In this
     case, the variable *note HAVE_THREADS: ac5. is set to ‘False’.


File: python.info,  Node: API changes<2>,  Prev: 相关特性<2>,  Up: decimal<3>

1.7.20.14 API changes
.....................

   * C模块上下文限制（如下表），具体取决于计算机体系结构：

                                  32位                      64位
                                                            
          -------------------------------------------------------------------------------------
                                                            
          ‘MAX_PREC’              ‘425000000’               ‘999999999999999999’
                                                            
                                                            
          ‘MAX_EMAX’              ‘425000000’               ‘999999999999999999’
                                                            
                                                            
          ‘MIN_EMIN’              ‘-425000000’              ‘-999999999999999999’
                                                            

   * In the context templates (*note DefaultContext: ac7, *note
     BasicContext: ac8. and *note ExtendedContext: ac9.) the magnitude
     of ‘Emax’ and ‘Emin’ has changed to ‘999999’.

   * The *note Decimal: 2c0. 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 *note InvalidOperation: aca. is raised and the
     result is NaN. In the latter case it is always possible to use
     *note create_decimal(): acb. in order to obtain a rounded or
     inexact value.

   * The power function in decimal.py is always correctly-rounded.  In
     the C version, it is defined in terms of the correctly-rounded
     *note exp(): acc. and *note ln(): acd. functions, but the final
     result is only "almost always correctly rounded".

   * In the C version, the context dictionary containing the signals is
     a *note MutableMapping: ace.  For speed reasons, ‘flags’ and
     ‘traps’ always refer to the same *note MutableMapping: ace. that
     the context was initialized with.  If a new signal dictionary is
     assigned, ‘flags’ and ‘traps’ are updated with the new values, but
     they do not reference the RHS dictionary.

   * Pickling a *note Context: acf. produces a different output in order
     to have a common interchange format for the Python and C versions.

   * The order of arguments in the *note Context: acf. constructor has
     been changed to match the order displayed by *note repr(): 8b9.

   * The ‘watchexp’ parameter in the *note quantize(): ad0. method is
     deprecated.


File: python.info,  Node: email<4>,  Next: ftplib<2>,  Prev: decimal<3>,  Up: 改进的模块<7>

1.7.20.15 email
...............

* Menu:

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


File: python.info,  Node: Policy Framework,  Next: Provisional Policy with New Header API,  Up: email<4>

1.7.20.16 Policy Framework
..........................

The email package now has a *note policy: 73. framework.  A *note
Policy: ad3. is an object with several methods and properties that
control how the email package behaves.  The primary policy for Python
3.3 is the *note Compat32: ad4. policy, which provides backward
compatibility with the email package in Python 3.2.  A ‘policy’ can be
specified when an email message is parsed by a *note parser: 72, or when
a *note Message: 63b. object is created, or when an email is serialized
using a *note generator: 6c.  Unless overridden, a policy passed to a
‘parser’ is inherited by all the ‘Message’ object and sub-objects
created by the ‘parser’.  By default a ‘generator’ will use the policy
of the ‘Message’ object it is serializing.  The default policy is *note
compat32: 63a.

The minimum set of controls implemented by all ‘policy’ objects are:

     max_line_length     The maximum length, excluding the linesep character(s),
                         individual lines may have when a ‘Message’ is serialized.
                         Defaults to 78.
                         
                         
     linesep             The character used to separate individual lines when a
                         ‘Message’ is serialized.  Defaults to ‘\n’.
                         
                         
     cte_type            ‘7bit’ or ‘8bit’.  ‘8bit’ applies only to a ‘Bytes’
                         ‘generator’, and means that non-ASCII may be used where
                         allowed by the protocol (or where it exists in the
                         original input).
                         
                         
     raise_on_defect     Causes a ‘parser’ to raise error when defects are
                         encountered instead of adding them to the ‘Message’
                         object’s ‘defects’ list.
                         

A new policy instance, with new settings, is created using the *note
clone(): ad5. method of policy objects.  ‘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
‘\r\n’ linesep characters like this:

     mypolicy = compat32.clone(linesep='\r\n')

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 ‘linesep='\r\n'’ in all the places you call a ‘generator’, you
can specify it once, when you set the policy used by the ‘parser’ or the
‘Message’, whichever your program uses to create ‘Message’ objects.  On
the other hand, if you need to generate messages in multiple forms, you
can still specify the parameters in the appropriate ‘generator’ call.
Or you can have custom policy instances for your different cases, and
pass those in when you create the ‘generator’.


File: python.info,  Node: Provisional Policy with New Header API,  Next: Other API Changes,  Prev: Policy Framework,  Up: email<4>

1.7.20.17 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 *note provisional policy: a61.
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 *note EmailPolicy: ad7, and add the
following additional controls:

     refold_source       Controls whether or not headers parsed by a
                         *note parser: 72. are refolded by the
                         *note generator: 6c.  It can be ‘none’, ‘long’, or ‘all’.
                         The default is ‘long’, which means that source headers
                         with a line longer than ‘max_line_length’ get refolded.
                         ‘none’ means no line get refolded, and ‘all’ means that
                         all lines get refolded.
                         
                         
     header_factory      A callable that take a ‘name’ and ‘value’ and produces a
                         custom header object.
                         

The ‘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 ‘Message’ object is an object produced by the ‘header_factory’,
and any time you set a header on a ‘Message’ it becomes an object
produced by ‘header_factory’.  All such header objects have a ‘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:

     >>> 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

You will note that the unicode display name is automatically encoded as
‘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 *note email.header: 6d. *note decode_header():
ad8. or *note make_header(): ad9. functions.

You can also create addresses from parts:

     >>> 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>

Decoding to unicode is done automatically:

     >>> m2 = message_from_string(str(m))
     >>> m2['to']
     'Éric <foo@example.com>'

When you parse a message, you can use the ‘addresses’ and ‘groups’
attributes of the header objects to access the groups and individual
addresses:

     >>> 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'),))

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.


File: python.info,  Node: Other API Changes,  Prev: Provisional Policy with New Header API,  Up: email<4>

1.7.20.18 Other API Changes
...........................

New *note BytesHeaderParser: adb, added to the *note parser: 72. module
to complement *note HeaderParser: adc. and complete the Bytes API.

New utility functions:

        * *note format_datetime(): add.: given a *note datetime: 19f,
          produce a string formatted for use in an email header.

        * *note parsedate_to_datetime(): ade.: given a date string from
          an email header, convert it into an aware *note datetime: 19f,
          or a naive *note datetime: 19f. if the offset is ‘-0000’.

        * *note localtime(): adf.: With no argument, returns the current
          local time as an aware *note datetime: 19f. using the local
          *note timezone: ae0.  Given an aware *note datetime: 19f,
          converts it into an aware *note datetime: 19f. using the local
          *note timezone: ae0.


File: python.info,  Node: ftplib<2>,  Next: functools<5>,  Prev: email<4>,  Up: 改进的模块<7>

1.7.20.19 ftplib
................

   * *note ftplib.FTP: 1a6. now accepts a ‘source_address’ keyword
     argument to specify the ‘(host, port)’ to use as the source address
     in the bind call when creating the outgoing socket.  (Contributed
     by Giampaolo Rodolà in bpo-8594(1).)

   * The *note FTP_TLS: 1a7. class now provides a new *note ccc(): ae2.
     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(2).)

   * Added *note ftplib.FTP.mlsd(): ae3. method which provides a
     parsable directory listing format and deprecates *note
     ftplib.FTP.nlst(): ae4. and *note ftplib.FTP.dir(): ae5.
     (Contributed by Giampaolo Rodolà in bpo-11072(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue8594

   (2) https://bugs.python.org/issue12139

   (3) https://bugs.python.org/issue11072


File: python.info,  Node: functools<5>,  Next: gc<5>,  Prev: ftplib<2>,  Up: 改进的模块<7>

1.7.20.20 functools
...................

The *note functools.lru_cache(): 2f8. decorator now accepts a ‘typed’
keyword argument (that defaults to ‘False’ to ensure that it caches
values of different types that compare equal in separate cache slots.
(Contributed by Raymond Hettinger in bpo-13227(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13227


File: python.info,  Node: gc<5>,  Next: hmac<3>,  Prev: functools<5>,  Up: 改进的模块<7>

1.7.20.21 gc
............

It is now possible to register callbacks invoked by the garbage
collector before and after collection using the new *note callbacks:
ae8. list.


File: python.info,  Node: hmac<3>,  Next: http<4>,  Prev: gc<5>,  Up: 改进的模块<7>

1.7.20.22 hmac
..............

A new *note compare_digest(): aea. function has been added to prevent
side channel attacks on digests through timing analysis.  (Contributed
by Nick Coghlan and Christian Heimes in bpo-15061(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15061


File: python.info,  Node: http<4>,  Next: html<2>,  Prev: hmac<3>,  Up: 改进的模块<7>

1.7.20.23 http
..............

*note http.server.BaseHTTPRequestHandler: aec. now buffers the headers
and writes them all at once when *note end_headers(): aed. is called.  A
new method *note flush_headers(): aee. can be used to directly manage
when the accumulated headers are sent.  (Contributed by Andrew Schaaf in
bpo-3709(1).)

*note http.server: 96. now produces valid ‘HTML 4.01 strict’ output.
(Contributed by Ezio Melotti in bpo-13295(2).)

*note http.client.HTTPResponse: aef. now has a *note readinto(): af0.
method, which means it can be used as an *note io.RawIOBase: af1. class.
(Contributed by John Kuhn in bpo-13464(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue3709

   (2) https://bugs.python.org/issue13295

   (3) https://bugs.python.org/issue13464


File: python.info,  Node: html<2>,  Next: imaplib<3>,  Prev: http<4>,  Up: 改进的模块<7>

1.7.20.24 html
..............

*note html.parser.HTMLParser: 22a. is now able to parse broken markup
without raising errors, therefore the `strict' argument of the
constructor and the ‘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(1), and
bpo-14538(2), bpo-13993(3), bpo-13960(4), bpo-13358(5), bpo-1745761(6),
bpo-755670(7), bpo-13357(8), bpo-12629(9), bpo-1200313(10),
bpo-670664(11), bpo-13273(12), bpo-12888(13), bpo-7311(14).)

A new *note html5: af3. dictionary that maps HTML5 named character
references to the equivalent Unicode character(s) (e.g.  ‘html5['gt;']
== '>'’) has been added to the *note html.entities: 90. module.  The
dictionary is now also used by *note HTMLParser: 22a.  (Contributed by
Ezio Melotti in bpo-11113(15) and bpo-15156(16).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15114

   (2) https://bugs.python.org/issue14538

   (3) https://bugs.python.org/issue13993

   (4) https://bugs.python.org/issue13960

   (5) https://bugs.python.org/issue13358

   (6) https://bugs.python.org/issue1745761

   (7) https://bugs.python.org/issue755670

   (8) https://bugs.python.org/issue13357

   (9) https://bugs.python.org/issue12629

   (10) https://bugs.python.org/issue1200313

   (11) https://bugs.python.org/issue670664

   (12) https://bugs.python.org/issue13273

   (13) https://bugs.python.org/issue12888

   (14) https://bugs.python.org/issue7311

   (15) https://bugs.python.org/issue11113

   (16) https://bugs.python.org/issue15156


File: python.info,  Node: imaplib<3>,  Next: inspect<6>,  Prev: html<2>,  Up: 改进的模块<7>

1.7.20.25 imaplib
.................

The *note IMAP4_SSL: 1b0. constructor now accepts an SSLContext
parameter to control parameters of the secure channel.

（由 Sijin Joseph 在 bpo-8808(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue8808


File: python.info,  Node: inspect<6>,  Next: io<4>,  Prev: imaplib<3>,  Up: 改进的模块<7>

1.7.20.26 inspect
.................

A new *note getclosurevars(): af6. 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(1) 中贡献。）

A new *note getgeneratorlocals(): af7. 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(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13062

   (2) https://bugs.python.org/issue15153


File: python.info,  Node: io<4>,  Next: itertools<3>,  Prev: inspect<6>,  Up: 改进的模块<7>

1.7.20.27 io
............

The *note open(): 74d. function has a new ‘'x'’ mode that can be used to
exclusively create a new file, and raise a *note FileExistsError: a39.
if the file already exists.  It is based on the C11 ’x’ mode to fopen().

（由 David Townshend 在 bpo-12760(1) 中贡献。）

The constructor of the *note TextIOWrapper: 6ea. class has a new
`write_through' optional argument.  If `write_through' is ‘True’, calls
to ‘write()’ are guaranteed not to be buffered: any data written on the
*note TextIOWrapper: 6ea. object is immediately handled to its
underlying binary buffer.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue12760


File: python.info,  Node: itertools<3>,  Next: logging<6>,  Prev: io<4>,  Up: 改进的模块<7>

1.7.20.28 itertools
...................

*note accumulate(): 30e. now takes an optional ‘func’ argument for
providing a user-supplied binary function.


File: python.info,  Node: logging<6>,  Next: math<6>,  Prev: itertools<3>,  Up: 改进的模块<7>

1.7.20.29 logging
.................

The *note basicConfig(): 311. function now supports an optional
‘handlers’ argument taking an iterable of handlers to be added to the
root logger.

A class level attribute ‘append_nul’ has been added to *note
SysLogHandler: afb. to allow control of the appending of the ‘NUL’
(‘\000’) byte to syslog records, since for some daemons it is required
while for others it is passed through to the log.


File: python.info,  Node: math<6>,  Next: mmap<3>,  Prev: logging<6>,  Up: 改进的模块<7>

1.7.20.30 math
..............

The *note math: b1. module has a new function, *note log2(): afd, which
returns the base-2 logarithm of `x'.

(Written by Mark Dickinson in bpo-11888(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue11888


File: python.info,  Node: mmap<3>,  Next: multiprocessing<7>,  Prev: math<6>,  Up: 改进的模块<7>

1.7.20.31 mmap
..............

The *note read(): aff. method is now more compatible with other
file-like objects: if the argument is omitted or specified as ‘None’, it
returns the bytes from the current file position to the end of the
mapping.  (Contributed by Petri Lehtinen in bpo-12021(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue12021


File: python.info,  Node: multiprocessing<7>,  Next: nntplib<2>,  Prev: mmap<3>,  Up: 改进的模块<7>

1.7.20.32 multiprocessing
.........................

The new *note multiprocessing.connection.wait(): b01. function allows
polling multiple objects (such as connections, sockets and pipes) with a
timeout.  (Contributed by Richard Oudkerk in bpo-12328(1).)

‘multiprocessing.Connection’ objects can now be transferred over
multiprocessing connections.  (Contributed by Richard Oudkerk in
bpo-4892(2).)

*note multiprocessing.Process: 4b8. now accepts a ‘daemon’ keyword
argument to override the default behavior of inheriting the ‘daemon’
flag from the parent process (bpo-6064(3)).

New attribute *note multiprocessing.Process.sentinel: b02. allows a
program to wait on multiple *note Process: 4b8. objects at one time
using the appropriate OS primitives (for example, *note select: e5. on
posix systems).

New methods *note multiprocessing.pool.Pool.starmap(): b03. and *note
starmap_async(): b04. provide *note itertools.starmap(): b05.
equivalents to the existing *note multiprocessing.pool.Pool.map(): b06.
and *note map_async(): b07. functions.  (Contributed by Hynek Schlawack
in bpo-12708(4).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue12328

   (2) https://bugs.python.org/issue4892

   (3) https://bugs.python.org/issue6064

   (4) https://bugs.python.org/issue12708


File: python.info,  Node: nntplib<2>,  Next: os<8>,  Prev: multiprocessing<7>,  Up: 改进的模块<7>

1.7.20.33 nntplib
.................

The *note nntplib.NNTP: 1c6. class now supports the context management
protocol to unconditionally consume *note socket.error: a76. exceptions
and to close the NNTP connection when done:

     >>> 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')
     >>>

（由 Giampaolo Rodolà 在 bpo-9795(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue9795


File: python.info,  Node: os<8>,  Next: pdb<5>,  Prev: nntplib<2>,  Up: 改进的模块<7>

1.7.20.34 os
............

   * The *note os: c4. module has a new *note pipe2(): b0a. function
     that makes it possible to create a pipe with *note O_CLOEXEC: aa2.
     or *note O_NONBLOCK: 812. flags set atomically.  This is especially
     useful to avoid race conditions in multi-threaded programs.

   * The *note os: c4. module has a new *note sendfile(): 461. 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.  *note sendfile(): 461. 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(1).)

   * 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(2), bpo-10755(3) and
     bpo-14626(4)).

        - The *note os: c4. module has a new *note fwalk(): 4ba.
          function similar to *note walk(): 747. except that it also
          yields file descriptors referring to the directories visited.
          This is especially useful to avoid symlink races.

        - The following functions get new optional `dir_fd' (*note paths
          relative to directory descriptors: b0b.) and/or
          `follow_symlinks' (*note not following symlinks: b0c.): *note
          access(): b0d, *note chflags(): b0e, *note chmod(): b0f, *note
          chown(): b10, *note link(): b11, *note lstat(): 322, *note
          mkdir(): b12, *note mkfifo(): 756, *note mknod(): 757, *note
          open(): 758, *note readlink(): 1d1, *note remove(): b13, *note
          rename(): b14, *note replace(): b15, *note rmdir(): b16, *note
          stat(): 321, *note symlink(): b17, *note unlink(): b18, *note
          utime(): b19.  Platform support for using these parameters can
          be checked via the sets *note os.supports_dir_fd: b1a. and
          ‘os.supports_follows_symlinks’.

        - The following functions now support a file descriptor for
          their path argument: *note chdir(): 16e, *note chmod(): b0f,
          *note chown(): b10, *note execve(): b1b, *note listdir(): b1c,
          *note pathconf(): b1d, *note exists(): 325, *note stat(): 321,
          *note statvfs(): b1e, *note utime(): b19.  Platform support
          for this can be checked via the *note os.supports_fd: b1f.
          set.

   * *note access(): b0d. accepts an ‘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
     *note supports_effective_ids: b20. set.

   * The *note os: c4. module has two new functions: *note
     getpriority(): b21. and *note setpriority(): b22.  They can be used
     to get or set process niceness/priority in a fashion similar to
     *note os.nice(): b23. but extended to all processes instead of just
     the current one.

     (Patch submitted by Giampaolo Rodolà in bpo-10784(5).)

   * The new *note os.replace(): b15. function allows cross-platform
     renaming of a file with overwriting the destination.  With *note
     os.rename(): b14, an existing destination file is overwritten under
     POSIX, but raises an error under Windows.  (Contributed by Antoine
     Pitrou in bpo-8828(6).)

   * The stat family of functions (*note stat(): 321, *note fstat():
     752, and *note lstat(): 322.) now support reading a file’s
     timestamps with nanosecond precision.  Symmetrically, *note
     utime(): b19. can now write file timestamps with nanosecond
     precision.  (Contributed by Larry Hastings in bpo-14127(7).)

   * The new *note os.get_terminal_size(): b24. function queries the
     size of the terminal attached to a file descriptor.  See also *note
     shutil.get_terminal_size(): b25.  (Contributed by Zbigniew
     Jędrzejewski-Szmek in bpo-13609(8).)

   * New functions to support Linux extended attributes (bpo-12720(9)):
     *note getxattr(): b26, *note listxattr(): b27, *note removexattr():
     b28, *note setxattr(): b29.

   * New interface to the scheduler.  These functions control how a
     process is allocated CPU time by the operating system.  New
     functions: *note sched_get_priority_max(): b2a, *note
     sched_get_priority_min(): b2b, *note sched_getaffinity(): b2c,
     *note sched_getparam(): b2d, *note sched_getscheduler(): b2e, *note
     sched_rr_get_interval(): b2f, *note sched_setaffinity(): b30, *note
     sched_setparam(): b31, *note sched_setscheduler(): b32, *note
     sched_yield(): b33,

   * New functions to control the file system:

        * *note posix_fadvise(): 759.: Announces an intention to access
          data in a specific pattern thus allowing the kernel to make
          optimizations.

        * *note posix_fallocate(): 75a.: Ensures that enough disk space
          is allocated for a file.

        * *note sync(): b34.: Force write of everything to disk.

   * Additional new posix functions:

        * *note lockf(): b35.: Apply, test or remove a POSIX lock on an
          open file descriptor.

        * *note pread(): 4bf.: Read from a file descriptor at an offset,
          the file offset remains unchanged.

        * *note pwrite(): 4c2.: Write to a file descriptor from an
          offset, leaving the file offset unchanged.

        * *note readv(): 4be.: Read from a file descriptor into a number
          of writable buffers.

        * *note truncate(): 813.: Truncate the file corresponding to
          `path', so that it is at most `length' bytes in size.

        * *note waitid(): 75f.: Wait for the completion of one or more
          child processes.

        * *note writev(): 4c1.: Write the contents of `buffers' to a
          file descriptor, where `buffers' is an arbitrary sequence of
          buffers.

        * *note getgrouplist(): b36. (bpo-9344(10)): Return list of
          group ids that specified user belongs to.

   * *note times(): b37. and *note uname(): b38.: Return type changed
     from a tuple to a tuple-like object with named attributes.

   * Some platforms now support additional constants for the *note
     lseek(): b39. function, such as ‘os.SEEK_HOLE’ and ‘os.SEEK_DATA’.

   * New constants *note RTLD_LAZY: b3a, *note RTLD_NOW: b3b, *note
     RTLD_GLOBAL: b3c, *note RTLD_LOCAL: b3d, *note RTLD_NODELETE: b3e,
     *note RTLD_NOLOAD: b3f, and *note RTLD_DEEPBIND: b40. are available
     on platforms that support them.  These are for use with the *note
     sys.setdlopenflags(): b41. function, and supersede the similar
     constants defined in *note ctypes: 2a. and ‘DLFCN’.  (Contributed
     by Victor Stinner in bpo-13226(11).)

   * *note os.symlink(): b17. now accepts (and ignores) the
     ‘target_is_directory’ keyword argument on non-Windows platforms, to
     ease cross-platform support.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10882

   (2) https://bugs.python.org/issue4761

   (3) https://bugs.python.org/issue10755

   (4) https://bugs.python.org/issue14626

   (5) https://bugs.python.org/issue10784

   (6) https://bugs.python.org/issue8828

   (7) https://bugs.python.org/issue14127

   (8) https://bugs.python.org/issue13609

   (9) https://bugs.python.org/issue12720

   (10) https://bugs.python.org/issue9344

   (11) https://bugs.python.org/issue13226


File: python.info,  Node: pdb<5>,  Next: pickle<5>,  Prev: os<8>,  Up: 改进的模块<7>

1.7.20.35 pdb
.............

Tab-completion is now available not only for command names, but also
their arguments.  For example, for the ‘break’ command, function and
file names are completed.

（由 Georg Brandl 在 bpo-14210(1) 中贡献）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue14210


File: python.info,  Node: pickle<5>,  Next: pydoc<5>,  Prev: pdb<5>,  Up: 改进的模块<7>

1.7.20.36 pickle
................

*note pickle.Pickler: 33b. objects now have an optional *note
dispatch_table: b44. attribute allowing per-pickler reduction functions
to be set.

（由 Richard Oudkerk 在 bpo-14166(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue14166


File: python.info,  Node: pydoc<5>,  Next: re<6>,  Prev: pickle<5>,  Up: 改进的模块<7>

1.7.20.37 pydoc
...............

The Tk GUI and the ‘serve()’ function have been removed from the *note
pydoc: d9. module: ‘pydoc -g’ and ‘serve()’ have been deprecated in
Python 3.2.


File: python.info,  Node: re<6>,  Next: sched,  Prev: pydoc<5>,  Up: 改进的模块<7>

1.7.20.38 re
............

*note str: 205. regular expressions now support ‘\u’ and ‘\U’ escapes.

（由 Serhiy Storchaka 在 bpo-3665(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue3665


File: python.info,  Node: sched,  Next: select<2>,  Prev: re<6>,  Up: 改进的模块<7>

1.7.20.39 sched
...............

   * *note run(): b48. now accepts a `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 *note scheduler: b49. in
     non-blocking applications.  (Contributed by Giampaolo Rodolà in
     bpo-13449(1).)

   * *note scheduler: b49. class can now be safely used in
     multi-threaded environments.  (Contributed by Josiah Carlson and
     Giampaolo Rodolà in bpo-8684(2).)

   * `timefunc' and `delayfunct' parameters of *note scheduler: b49.
     class constructor are now optional and defaults to *note
     time.time(): 42d. and *note time.sleep(): 773. respectively.
     (Contributed by Chris Clark in bpo-13245(3).)

   * *note enter(): b4a. and *note enterabs(): b4b. `argument' parameter
     is now optional.  (Contributed by Chris Clark in bpo-13245(4).)

   * *note enter(): b4a. and *note enterabs(): b4b. now accept a
     `kwargs' parameter.  (Contributed by Chris Clark in bpo-13245(5).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13449

   (2) https://bugs.python.org/issue8684

   (3) https://bugs.python.org/issue13245

   (4) https://bugs.python.org/issue13245

   (5) https://bugs.python.org/issue13245


File: python.info,  Node: select<2>,  Next: shlex<3>,  Prev: sched,  Up: 改进的模块<7>

1.7.20.40 select
................

Solaris and derivative platforms have a new class *note select.devpoll:
992. for high performance asynchronous sockets via ‘/dev/poll’.
(Contributed by Jesús Cea Avión in bpo-6397(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue6397


File: python.info,  Node: shlex<3>,  Next: shutil<4>,  Prev: select<2>,  Up: 改进的模块<7>

1.7.20.41 shlex
...............

The previously undocumented helper function ‘quote’ from the *note
pipes: cc. modules has been moved to the *note shlex: e8. module and
documented.  *note quote(): b4e. properly escapes all characters in a
string that might be otherwise given special meaning by the shell.


File: python.info,  Node: shutil<4>,  Next: signal<4>,  Prev: shlex<3>,  Up: 改进的模块<7>

1.7.20.42 shutil
................

   * 新的函数：

        * *note disk_usage(): b50.: provides total, used and free disk
          space statistics.  (Contributed by Giampaolo Rodolà in
          bpo-12442(1).)

        * *note chown(): b51.: 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(2).)

        * *note shutil.get_terminal_size(): b25.: returns the size of
          the terminal window to which the interpreter is attached.
          (Contributed by Zbigniew Jędrzejewski-Szmek in bpo-13609(3).)

   * *note copy2(): 384. and *note copystat(): b52. 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(4) and bpo-15238(5).)

   * Several functions now take an optional ‘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(6).)

   * When copying files to a different file system, *note move(): 385.
     now handles symlinks the way the posix ‘mv’ command does,
     recreating the symlink rather than copying the target file
     contents.  (Contributed by Jonathan Niehof in bpo-9993(7).)  *note
     move(): 385. now also returns the ‘dst’ argument as its result.

   * *note rmtree(): 349. is now resistant to symlink attacks on
     platforms which support the new ‘dir_fd’ parameter in *note
     os.open(): 758. and *note os.unlink(): b18.  (Contributed by Martin
     von Löwis and Hynek Schlawack in bpo-4489(8).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue12442

   (2) https://bugs.python.org/issue12191

   (3) https://bugs.python.org/issue13609

   (4) https://bugs.python.org/issue14127

   (5) https://bugs.python.org/issue15238

   (6) https://bugs.python.org/issue12715

   (7) https://bugs.python.org/issue9993

   (8) https://bugs.python.org/issue4489


File: python.info,  Node: signal<4>,  Next: smtpd<3>,  Prev: shutil<4>,  Up: 改进的模块<7>

1.7.20.43 signal
................

   * The *note signal: ea. module has new functions:

        * *note pthread_sigmask(): b54.: fetch and/or change the signal
          mask of the calling thread (Contributed by Jean-Paul Calderone
          in bpo-8407(1));

        * *note pthread_kill(): b55.: send a signal to a thread;

        * *note sigpending(): b56.: examine pending functions;

        * *note sigwait(): b57.: wait a signal;

        * *note sigwaitinfo(): 772.: wait for a signal, returning
          detailed information about it;

        * *note sigtimedwait(): 771.: like *note sigwaitinfo(): 772. but
          with a timeout.

   * 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.

   * *note signal.signal(): b58. and *note signal.siginterrupt(): b59.
     raise an OSError, instead of a RuntimeError: OSError has an errno
     attribute.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue8407


File: python.info,  Node: smtpd<3>,  Next: smtplib<4>,  Prev: signal<4>,  Up: 改进的模块<7>

1.7.20.44 smtpd
...............

The *note smtpd: ec. module now supports RFC 5321(1) (extended SMTP) and
RFC 1870(2) (size extension).  Per the standard, these extensions are
enabled if and only if the client initiates the session with an ‘EHLO’
command.

(Initial ‘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(3))

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc5321.html

   (2) https://tools.ietf.org/html/rfc1870.html

   (3) https://bugs.python.org/issue8739


File: python.info,  Node: smtplib<4>,  Next: socket<8>,  Prev: smtpd<3>,  Up: 改进的模块<7>

1.7.20.45 smtplib
.................

The *note SMTP: 1de, *note SMTP_SSL: 1df, and *note LMTP: 1e0. classes
now accept a ‘source_address’ keyword argument to specify the ‘(host,
port)’ to use as the source address in the bind call when creating the
outgoing socket.  (Contributed by Paulo Scardine in bpo-11281(1).)

*note SMTP: 1de. now supports the context management protocol, allowing
an ‘SMTP’ instance to be used in a ‘with’ statement.  (Contributed by
Giampaolo Rodolà in bpo-11289(2).)

The *note SMTP_SSL: 1df. constructor and the *note starttls(): b5c.
method now accept an SSLContext parameter to control parameters of the
secure channel.  (Contributed by Kasun Herath in bpo-8809(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue11281

   (2) https://bugs.python.org/issue11289

   (3) https://bugs.python.org/issue8809


File: python.info,  Node: socket<8>,  Next: socketserver<3>,  Prev: smtplib<4>,  Up: 改进的模块<7>

1.7.20.46 socket
................

   * The *note socket: 767. class now exposes additional methods to
     process ancillary data when supported by the underlying platform:

        * *note sendmsg(): 76f.

        * *note recvmsg(): 76c.

        * *note recvmsg_into(): b5e.

     (Contributed by David Watson in bpo-6560(1), based on an earlier
     patch by Heiko Wundram)

   * The *note socket: 767. class now supports the PF_CAN protocol
     family (‘https://en.wikipedia.org/wiki/Socketcan’), on Linux
     (‘https://lwn.net/Articles/253425’).

     (Contributed by Matthias Fuchs, updated by Tiago Gonçalves in
     bpo-10141(2).)

   * The *note socket: 767. class now supports the PF_RDS protocol
     family (‘https://en.wikipedia.org/wiki/Reliable_Datagram_Sockets’
     and ‘https://oss.oracle.com/projects/rds/’).

   * The *note socket: 767. class now supports the ‘PF_SYSTEM’ protocol
     family on OS X. (Contributed by Michael Goderbauer in
     bpo-13777(3).)

   * New function *note sethostname(): b5f. allows the hostname to be
     set on unix systems if the calling process has sufficient
     privileges.  (Contributed by Ross Lagerwall in bpo-10866(4).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue6560

   (2) https://bugs.python.org/issue10141

   (3) https://bugs.python.org/issue13777

   (4) https://bugs.python.org/issue10866


File: python.info,  Node: socketserver<3>,  Next: sqlite3<5>,  Prev: socket<8>,  Up: 改进的模块<7>

1.7.20.47 socketserver
......................

*note BaseServer: b61. now has an overridable method *note
service_actions(): b62. that is called by the *note serve_forever():
b63. method in the service loop.  *note ForkingMixIn: 4db. now uses this
to clean up zombie child processes.  (Contributed by Justin Warkentin in
bpo-11109(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue11109


File: python.info,  Node: sqlite3<5>,  Next: ssl<8>,  Prev: socketserver<3>,  Up: 改进的模块<7>

1.7.20.48 sqlite3
.................

New *note sqlite3.Connection: 4de. method *note set_trace_callback():
b65. can be used to capture a trace of all sql commands processed by
sqlite.  (Contributed by Torsten Landschoff in bpo-11688(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue11688


File: python.info,  Node: ssl<8>,  Next: stat<2>,  Prev: sqlite3<5>,  Up: 改进的模块<7>

1.7.20.49 ssl
.............

   * The *note ssl: f3. module has two new random generation functions:

        * *note RAND_bytes(): b67.: generate cryptographically strong
          pseudo-random bytes.

        * *note RAND_pseudo_bytes(): b68.: generate pseudo-random bytes.

     （由 Victor Stinner 在 bpo-12049(1) 中贡献。）

   * The *note ssl: f3. 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(2).)

   * *note load_cert_chain(): b69. now accepts a `password' argument to
     be used if the private key is encrypted.  (Contributed by Adam
     Simpkins in bpo-12803(3).)

   * Diffie-Hellman key exchange, both regular and Elliptic Curve-based,
     is now supported through the *note load_dh_params(): b6a. and *note
     set_ecdh_curve(): b6b. methods.  (Contributed by Antoine Pitrou in
     bpo-13626(4) and bpo-13627(5).)

   * SSL sockets have a new *note get_channel_binding(): b6c. method
     allowing the implementation of certain authentication mechanisms
     such as SCRAM-SHA-1-PLUS. (Contributed by Jacek Konieczny in
     bpo-12551(6).)

   * You can query the SSL compression algorithm used by an SSL socket,
     thanks to its new *note compression(): b6d. method.  The new
     attribute *note OP_NO_COMPRESSION: b6e. can be used to disable
     compression.  (Contributed by Antoine Pitrou in bpo-13634(7).)

   * Support has been added for the Next Protocol Negotiation extension
     using the *note ssl.SSLContext.set_npn_protocols(): b6f. method.
     (Contributed by Colin Marc in bpo-14204(8).)

   * SSL errors can now be introspected more easily thanks to *note
     library: b70. and *note reason: b71. attributes.  (Contributed by
     Antoine Pitrou in bpo-14837(9).)

   * The *note get_server_certificate(): b72. function now supports
     IPv6.  (Contributed by Charles-François Natali in bpo-11811(10).)

   * New attribute *note OP_CIPHER_SERVER_PREFERENCE: b73. allows
     setting SSLv3 server sockets to use the server’s cipher ordering
     preference rather than the client’s (bpo-13635(11)).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue12049

   (2) https://bugs.python.org/issue11183

   (3) https://bugs.python.org/issue12803

   (4) https://bugs.python.org/issue13626

   (5) https://bugs.python.org/issue13627

   (6) https://bugs.python.org/issue12551

   (7) https://bugs.python.org/issue13634

   (8) https://bugs.python.org/issue14204

   (9) https://bugs.python.org/issue14837

   (10) https://bugs.python.org/issue11811

   (11) https://bugs.python.org/issue13635


File: python.info,  Node: stat<2>,  Next: struct<3>,  Prev: ssl<8>,  Up: 改进的模块<7>

1.7.20.50 stat
..............

The undocumented tarfile.filemode function has been moved to *note
stat.filemode(): b75.  It can be used to convert a file’s mode to a
string of the form ’-rwxrwxrwx’.

（由 Giampaolo Rodolà 在 bpo-14807(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue14807


File: python.info,  Node: struct<3>,  Next: subprocess<5>,  Prev: stat<2>,  Up: 改进的模块<7>

1.7.20.51 struct
................

The *note struct: f8. module now supports ‘ssize_t’ and ‘size_t’ via the
new codes ‘n’ and ‘N’, respectively.  (Contributed by Antoine Pitrou in
bpo-3163(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue3163


File: python.info,  Node: subprocess<5>,  Next: sys<8>,  Prev: struct<3>,  Up: 改进的模块<7>

1.7.20.52 subprocess
....................

Command strings can now be bytes objects on posix platforms.
(Contributed by Victor Stinner in bpo-8513(1).)

A new constant *note DEVNULL: b78. allows suppressing output in a
platform-independent fashion.  (Contributed by Ross Lagerwall in
bpo-5870(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue8513

   (2) https://bugs.python.org/issue5870


File: python.info,  Node: sys<8>,  Next: tarfile<4>,  Prev: subprocess<5>,  Up: 改进的模块<7>

1.7.20.53 sys
.............

The *note sys: fd. module has a new *note thread_info: b7a. *note named
tuple: b7b. holding information about the thread implementation
(bpo-11223(1)).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue11223


File: python.info,  Node: tarfile<4>,  Next: tempfile,  Prev: sys<8>,  Up: 改进的模块<7>

1.7.20.54 tarfile
.................

*note tarfile: 101. now supports ‘lzma’ encoding via the *note lzma: ad.
module.  (Contributed by Lars Gustäbel in bpo-5689(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5689


File: python.info,  Node: tempfile,  Next: textwrap<2>,  Prev: tarfile<4>,  Up: 改进的模块<7>

1.7.20.55 tempfile
..................

*note tempfile.SpooledTemporaryFile: b7e.’s ‘truncate()’ method now
accepts a ‘size’ parameter.  (Contributed by Ryan Kelly in bpo-9957(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue9957


File: python.info,  Node: textwrap<2>,  Next: threading<5>,  Prev: tempfile,  Up: 改进的模块<7>

1.7.20.56 textwrap
..................

The *note textwrap: 10a. module has a new *note indent(): b80. that
makes it straightforward to add a common prefix to selected lines in a
block of text (bpo-13857(1)).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13857


File: python.info,  Node: threading<5>,  Next: time<6>,  Prev: textwrap<2>,  Up: 改进的模块<7>

1.7.20.57 threading
...................

*note threading.Condition: b82, *note threading.Semaphore: b83, *note
threading.BoundedSemaphore: b84, *note threading.Event: b85, and *note
threading.Timer: b86, 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(1).)

The *note threading.Thread: 21a. constructor now accepts a ‘daemon’
keyword argument to override the default behavior of inheriting the
‘daemon’ flag value from the parent thread (bpo-6064(2)).

The formerly private function ‘_thread.get_ident’ is now available as
the public function *note threading.get_ident(): b87.  This eliminates
several cases of direct access to the ‘_thread’ module in the stdlib.
Third party code that used ‘_thread.get_ident’ should likewise be
changed to use the new public interface.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10968

   (2) https://bugs.python.org/issue6064


File: python.info,  Node: time<6>,  Next: types<4>,  Prev: threading<5>,  Up: 改进的模块<7>

1.7.20.58 time
..............

The PEP 418(1) added new functions to the *note time: 10c. module:

   * *note get_clock_info(): b89.: Get information on a clock.

   * *note monotonic(): 85e.: Monotonic clock (cannot go backward), not
     affected by system clock updates.

   * *note perf_counter(): 3cc.: Performance counter with the highest
     available resolution to measure a short duration.

   * *note process_time(): 3cd.: Sum of the system and user CPU time of
     the current process.

Other new functions:

   * *note clock_getres(): b8a, *note clock_gettime(): b8b. and *note
     clock_settime(): b8c. functions with ‘CLOCK_xxx’ constants.
     (Contributed by Victor Stinner in bpo-10278(2).)

To improve cross platform consistency, *note sleep(): 773. now raises a
*note ValueError: 16d. when passed a negative sleep value.  Previously
this was an error on posix, but produced an infinite sleep on Windows.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0418

   (2) https://bugs.python.org/issue10278


File: python.info,  Node: types<4>,  Next: unittest<5>,  Prev: time<6>,  Up: 改进的模块<7>

1.7.20.59 types
...............

Add a new *note types.MappingProxyType: b8e. class: Read-only proxy of a
mapping.  (bpo-14386(1))

The new functions *note types.new_class(): b8f. and *note
types.prepare_class(): b90. provide support for PEP 3115(2) compliant
dynamic type creation.  (bpo-14588(3))

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue14386

   (2) https://www.python.org/dev/peps/pep-3115

   (3) https://bugs.python.org/issue14588


File: python.info,  Node: unittest<5>,  Next: urllib<3>,  Prev: types<4>,  Up: 改进的模块<7>

1.7.20.60 unittest
..................

*note assertRaises(): b92, *note assertRaisesRegex(): b93, *note
assertWarns(): b94, and *note assertWarnsRegex(): b95. now accept a
keyword argument `msg' when used as context managers.  (Contributed by
Ezio Melotti and Winston Ewert in bpo-10775(1).)

*note unittest.TestCase.run(): b96. now returns the *note TestResult:
b97. object.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10775


File: python.info,  Node: urllib<3>,  Next: webbrowser,  Prev: unittest<5>,  Up: 改进的模块<7>

1.7.20.61 urllib
................

The *note Request: 9dc. class, now accepts a `method' argument used by
*note get_method(): b99. to determine what HTTP method should be used.
For example, this will send a ‘'HEAD'’ request:

     >>> urlopen(Request('https://www.python.org', method='HEAD'))

(bpo-1673007(1))

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1673007


File: python.info,  Node: webbrowser,  Next: xml etree ElementTree,  Prev: urllib<3>,  Up: 改进的模块<7>

1.7.20.62 webbrowser
....................

The *note webbrowser: 132. module supports more "browsers": Google
Chrome (named ‘chrome’, ‘chromium’, ‘chrome-browser’ or
‘chromium-browser’ depending on the version and operating system), and
the generic launchers ‘xdg-open’, from the FreeDesktop.org project, and
‘gvfs-open’, which is the default URI handler for GNOME 3.  (The former
contributed by Arnaud Calmettes in bpo-13620(1), the latter by Matthias
Klose in bpo-14493(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13620

   (2) https://bugs.python.org/issue14493


File: python.info,  Node: xml etree ElementTree,  Next: zlib<2>,  Prev: webbrowser,  Up: 改进的模块<7>

1.7.20.63 xml.etree.ElementTree
...............................

The *note xml.etree.ElementTree: 140. module now imports its C
accelerator by default; there is no longer a need to explicitly import
‘xml.etree.cElementTree’ (this module stays for backwards compatibility,
but is now deprecated).  In addition, the ‘iter’ family of methods of
*note Element: 21d. has been optimized (rewritten in C). The module’s
documentation has also been greatly improved with added examples and a
more detailed reference.


File: python.info,  Node: zlib<2>,  Prev: xml etree ElementTree,  Up: 改进的模块<7>

1.7.20.64 zlib
..............

New attribute *note zlib.Decompress.eof: b9d. makes it possible to
distinguish between a properly-formed compressed stream and an
incomplete or truncated one.  (Contributed by Nadeem Vawda in
bpo-12646(1).)

New attribute *note zlib.ZLIB_RUNTIME_VERSION: b9e. reports the version
string of the underlying ‘zlib’ library that is loaded at runtime.
(Contributed by Torsten Landschoff in bpo-12306(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue12646

   (2) https://bugs.python.org/issue12306


File: python.info,  Node: 性能优化<6>,  Next: 构建和 C API 的改变<4>,  Prev: 改进的模块<7>,  Up: Python 3 3 有什么新变化

1.7.21 性能优化
---------------

Major performance enhancements have been added:

   * Thanks to PEP 393(1), some operations on Unicode strings have been
     optimized:

        * the memory footprint is divided by 2 to 4 depending on the
          text

        * encode an ASCII string to UTF-8 doesn’t need to encode
          characters anymore, the UTF-8 representation is shared with
          the ASCII representation

        * the UTF-8 encoder has been optimized

        * repeating a single ASCII letter and getting a substring of an
          ASCII string is 4 times faster

   * UTF-8 is now 2x to 4x faster.  UTF-16 encoding is now up to 10x
     faster.

     (Contributed by Serhiy Storchaka, bpo-14624(2), bpo-14738(3) and
     bpo-15026(4).)

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0393

   (2) https://bugs.python.org/issue14624

   (3) https://bugs.python.org/issue14738

   (4) https://bugs.python.org/issue15026


File: python.info,  Node: 构建和 C API 的改变<4>,  Next: 弃用<6>,  Prev: 性能优化<6>,  Up: Python 3 3 有什么新变化

1.7.22 构建和 C API 的改变
--------------------------

Changes to Python’s build process and to the C API include:

   * 新的 PEP 3118(1) 相关功能：

        * *note PyMemoryView_FromMemory(): ba0.

   * PEP 393(2) 添加了新的 Unicode 类型，宏和函数

        * 高阶 API

             * *note PyUnicode_CopyCharacters(): ba1.

             * *note PyUnicode_FindChar(): 542.

             * *note PyUnicode_GetLength(): ba2, *note
               PyUnicode_GET_LENGTH: ba3.

             * *note PyUnicode_New(): ba4.

             * *note PyUnicode_Substring(): ba5.

             * *note PyUnicode_ReadChar(): ba6, *note
               PyUnicode_WriteChar(): ba7.

        * 低阶 API:

             * *note Py_UCS1: ba8, *note Py_UCS2: ba9, *note Py_UCS4:
               baa. 类型

             * *note PyASCIIObject: bab. 和 *note
               PyCompactUnicodeObject: bac. 结构

             * *note PyUnicode_READY: bad.

             * *note PyUnicode_FromKindAndData(): bae.

             * *note PyUnicode_AsUCS4(): baf, *note
               PyUnicode_AsUCS4Copy(): bb0.

             * *note PyUnicode_DATA: bb1, *note PyUnicode_1BYTE_DATA:
               bb2, *note PyUnicode_2BYTE_DATA: bb3, *note
               PyUnicode_4BYTE_DATA: bb4.

             * *note PyUnicode_KIND: bb5. 使用 ‘PyUnicode_Kind’ 枚举:
               *note PyUnicode_WCHAR_KIND: bb6, *note
               PyUnicode_1BYTE_KIND: bb7, *note PyUnicode_2BYTE_KIND:
               bb8, *note PyUnicode_4BYTE_KIND: bb9.

             * *note PyUnicode_READ: bba, *note PyUnicode_READ_CHAR:
               bbb, *note PyUnicode_WRITE: bbc.

             * *note PyUnicode_MAX_CHAR_VALUE: bbd.

   * *note PyArg_ParseTuple: 393. 现在接受 ‘c’ 格式的 *note bytearray:
     173. (bpo-12380(3))。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3118

   (2) https://www.python.org/dev/peps/pep-0393

   (3) https://bugs.python.org/issue12380


File: python.info,  Node: 弃用<6>,  Next: 移植到 Python 3 3,  Prev: 构建和 C API 的改变<4>,  Up: Python 3 3 有什么新变化

1.7.23 弃用
-----------

* Menu:

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


File: python.info,  Node: 不支持的操作系统<2>,  Next: 已弃用的 Python 模块、函数和方法<4>,  Up: 弃用<6>

1.7.23.1 不支持的操作系统
.........................

由于缺少维护人员，不再支持 OS/2 和 VMS 系统 。

由于维护负担，将 ‘COMSPEC’ 设置为 ‘command.com’ 的 Windows平台（含
Windows 2000）不再受支持。

OSF支持在3.2中被弃用，现在已经被完全删除。


File: python.info,  Node: 已弃用的 Python 模块、函数和方法<4>,  Next: 已弃用的 C API 函数和类型<3>,  Prev: 不支持的操作系统<2>,  Up: 弃用<6>

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

   * Passing a non-empty string to ‘object.__format__()’ is deprecated,
     and will produce a *note TypeError: 1fe. in Python 3.4
     (bpo-9856(1)).

   * The ‘unicode_internal’ codec has been deprecated because of the PEP
     393(2), use UTF-8, UTF-16 (‘utf-16-le’ or ‘utf-16-be’), or UTF-32
     (‘utf-32-le’ or ‘utf-32-be’)

   * *note ftplib.FTP.nlst(): ae4. and *note ftplib.FTP.dir(): ae5.: use
     *note ftplib.FTP.mlsd(): ae3.

   * ‘platform.popen()’: use the *note subprocess: f9. module.  Check
     especially the *note 使用 subprocess 模块替换旧函数: bc1. section
     (bpo-11377(3)).

   * bpo-13374(4): The Windows bytes API has been deprecated in the
     *note os: c4. module.  Use Unicode filenames, instead of bytes
     filenames, to not depend on the ANSI code page anymore and to
     support any filename.

   * bpo-13988(5): The ‘xml.etree.cElementTree’ module is deprecated.
     The accelerator is used automatically whenever available.

   * The behaviour of ‘time.clock()’ depends on the platform: use the
     new *note time.perf_counter(): 3cc. or *note time.process_time():
     3cd. function instead, depending on your requirements, to have a
     well defined behaviour.

   * The ‘os.stat_float_times()’ function is deprecated.

   * *note abc: 3. module:

        * *note abc.abstractproperty: aac. has been deprecated, use
          *note property: 308. with *note abc.abstractmethod(): aad.
          instead.

        * *note abc.abstractclassmethod: aae. has been deprecated, use
          *note classmethod: 309. with *note abc.abstractmethod(): aad.
          instead.

        * *note abc.abstractstaticmethod: aaf. has been deprecated, use
          *note staticmethod: 30a. with *note abc.abstractmethod(): aad.
          instead.

   * *note importlib: 9a. package:

        * *note importlib.abc.SourceLoader.path_mtime(): bc2. is now
          deprecated in favour of *note
          importlib.abc.SourceLoader.path_stats(): bc3. as bytecode
          files now store both the modification time and size of the
          source file the bytecode file was compiled from.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue9856

   (2) https://www.python.org/dev/peps/pep-0393

   (3) https://bugs.python.org/issue11377

   (4) https://bugs.python.org/issue13374

   (5) https://bugs.python.org/issue13988


File: python.info,  Node: 已弃用的 C API 函数和类型<3>,  Next: 弃用的功能,  Prev: 已弃用的 Python 模块、函数和方法<4>,  Up: 弃用<6>

1.7.23.3 已弃用的 C API 函数和类型
..................................

*note Py_UNICODE: bc5. 已经在 PEP 393(1) 弃用，并将于 Python 4 中移除。
所有使用此类型的函数都已弃用：

Unicode functions and methods using *note Py_UNICODE: bc5. and *note
Py_UNICODE*: bc5. types:

   * *note PyUnicode_FromUnicode: 263.: 使用 *note
     PyUnicode_FromWideChar(): bc6. 或 *note
     PyUnicode_FromKindAndData(): bae.

   * *note PyUnicode_AS_UNICODE: bc7, *note PyUnicode_AsUnicode(): 264,
     *note PyUnicode_AsUnicodeAndSize(): 265.: 使用 *note
     PyUnicode_AsWideCharString(): 53b.

   * *note PyUnicode_AS_DATA: bc8.: 使用 *note PyUnicode_DATA: bb1. 以及
     *note PyUnicode_READ: bba. 和 *note PyUnicode_WRITE: bbc.

   * *note PyUnicode_GET_SIZE: bc9, *note PyUnicode_GetSize(): bca.: 使
     用 *note PyUnicode_GET_LENGTH: ba3. 或 *note PyUnicode_GetLength():
     ba2.

   * *note PyUnicode_GET_DATA_SIZE: bcb.: 使用
     ‘PyUnicode_GET_LENGTH(str) * PyUnicode_KIND(str)’ (仅适用于现成的字
     符串)

   * *note PyUnicode_AsUnicodeCopy(): bcc.: 使用 *note
     PyUnicode_AsUCS4Copy(): bb0. 或 *note PyUnicode_AsWideCharString():
     53b.

   * ‘PyUnicode_GetMax()’

Functions and macros manipulating Py_UNICODE* strings:

   * ‘Py_UNICODE_strlen’: 使用 *note PyUnicode_GetLength(): ba2. 或
     *note PyUnicode_GET_LENGTH: ba3.

   * ‘Py_UNICODE_strcat’: 使用 *note PyUnicode_CopyCharacters(): ba1. 或
     *note PyUnicode_FromFormat(): 8b8.

   * ‘Py_UNICODE_strcpy’, ‘Py_UNICODE_strncpy’, ‘Py_UNICODE_COPY’: 使用
     *note PyUnicode_CopyCharacters(): ba1. 或 *note
     PyUnicode_Substring(): ba5.

   * ‘Py_UNICODE_strcmp’: 使用 *note PyUnicode_Compare(): bcd.

   * ‘Py_UNICODE_strncmp’: 使用 *note PyUnicode_Tailmatch(): 272.

   * ‘Py_UNICODE_strchr’, ‘Py_UNICODE_strrchr’: 使用 *note
     PyUnicode_FindChar(): 542.

   * ‘Py_UNICODE_FILL’: 使用 *note PyUnicode_Fill(): bce.

   * ‘Py_UNICODE_MATCH’

编码器:

   * *note PyUnicode_Encode(): bcf.: 使用 ‘PyUnicode_AsEncodedObject()’

   * *note PyUnicode_EncodeUTF7(): bd0.

   * *note PyUnicode_EncodeUTF8(): bd1.: 使用 *note PyUnicode_AsUTF8():
     52e. 或 *note PyUnicode_AsUTF8String(): bd2.

   * *note PyUnicode_EncodeUTF32(): bd3.

   * *note PyUnicode_EncodeUTF16(): bd4.

   * *note PyUnicode_EncodeUnicodeEscape(): bd5. use *note
     PyUnicode_AsUnicodeEscapeString(): bd6.

   * *note PyUnicode_EncodeRawUnicodeEscape(): bd7. use *note
     PyUnicode_AsRawUnicodeEscapeString(): bd8.

   * *note PyUnicode_EncodeLatin1(): bd9.: 使用 *note
     PyUnicode_AsLatin1String(): bda.

   * *note PyUnicode_EncodeASCII(): bdb.: 使用 *note
     PyUnicode_AsASCIIString(): bdc.

   * *note PyUnicode_EncodeCharmap(): bdd.

   * *note PyUnicode_TranslateCharmap(): bde.

   * *note PyUnicode_EncodeMBCS(): bdf.: 使用 *note
     PyUnicode_AsMBCSString(): be0. 或 *note PyUnicode_EncodeCodePage():
     be1. (和 ‘CP_ACP’ code_page)

   * ‘PyUnicode_EncodeDecimal()’, *note
     PyUnicode_TransformDecimalToASCII(): be2.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0393


File: python.info,  Node: 弃用的功能,  Prev: 已弃用的 C API 函数和类型<3>,  Up: 弃用<6>

1.7.23.4 弃用的功能
...................

The *note array: 6. module’s ‘'u'’ format code is now deprecated and
will be removed in Python 4 together with the rest of the (*note
Py_UNICODE: bc5.) API.


File: python.info,  Node: 移植到 Python 3 3,  Prev: 弃用<6>,  Up: Python 3 3 有什么新变化

1.7.24 移植到 Python 3.3
------------------------

本节列出了先前描述的更改以及可能需要更改代码的其他错误修正.

* Menu:

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


File: python.info,  Node: Porting Python code,  Next: Porting C code,  Up: 移植到 Python 3 3

1.7.24.1 Porting Python code
............................

   * Hash randomization is enabled by default.  Set the *note
     PYTHONHASHSEED: aa4. environment variable to ‘0’ to disable hash
     randomization.  See also the *note object.__hash__(): 44c. method.

   * bpo-12326(1): 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.

   * bpo-13847(2), bpo-14180(3): *note time: 10c. and *note datetime:
     30.: *note OverflowError: a41. is now raised instead of *note
     ValueError: 16d. if a timestamp is out of range.  *note OSError:
     304. is now raised if C functions ‘gmtime()’ or ‘localtime()’
     failed.

   * 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 *note
     importlib.invalidate_caches(): 596. to clear out the cache for the
     finders to notice the new file.

   * *note ImportError: 16c. 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.

   * The `index' argument to *note __import__(): 16b. now defaults to 0
     instead of -1 and no longer support negative values.  It was an
     oversight when PEP 328(4) 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 *note
     importlib.import_module(): be6. rather than call *note
     __import__(): 16b. directly.

   * *note __import__(): 16b. no longer allows one to use an index value
     other than 0 for top-level modules.  E.g.  ‘__import__('sys',
     level=1)’ is now an error.

   * Because *note sys.meta_path: 6dd. and *note sys.path_hooks: a3d.
     now have finders on them by default, you will most likely want to
     use ‘list.insert()’ instead of ‘list.append()’ to add to those
     lists.

   * Because ‘None’ is now inserted into *note sys.path_importer_cache:
     597, 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 ‘None’ `and' *note imp.NullImporter: a9b. to be
     backwards-compatible.  This will lead to extra overhead on older
     versions of Python that re-insert ‘None’ into *note
     sys.path_importer_cache: 597. where it represents the use of
     implicit finders, but semantically it should not change anything.

   * *note importlib.abc.Finder: a95. no longer specifies a
     ‘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 ‘find_loader()’ first, though, in the case of working
     with *note path entry finders: a92.

   * *note pkgutil: cd. has been converted to use *note importlib: 9a.
     internally.  This eliminates many edge cases where the old
     behaviour of the PEP 302(5) import emulation failed to match the
     behaviour of the real import system.  The import emulation itself
     is still present, but is now deprecated.  The *note
     pkgutil.iter_importers(): be7. and *note pkgutil.walk_packages():
     585. functions special case the standard import hooks so they are
     still supported even though they do not provide the non-standard
     ‘iter_modules()’ method.

   * A longstanding RFC-compliance bug (bpo-1079(6)) in the parsing done
     by *note email.header.decode_header(): ad8. has been fixed.  Code
     that uses the standard idiom to convert encoded headers into
     unicode (‘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
     ‘ASCII’ sections is now included in the ‘ASCII’ section.  Code that
     builds headers using ‘make_header’ should also continue to work
     without change, since ‘make_header’ continues to add whitespace
     between ‘ASCII’ and non-‘ASCII’ sections if it is not already
     present in the input strings.

   * *note email.utils.formataddr(): be8. now does the correct content
     transfer encoding when passed non-‘ASCII’ display names.  Any code
     that depended on the previous buggy behavior that preserved the
     non-‘ASCII’ unicode in the formatted output string will need to be
     changed (bpo-1690608(7)).

   * *note poplib.POP3.quit(): be9. may now raise protocol errors like
     all other ‘poplib’ methods.  Code that assumes ‘quit’ does not
     raise *note poplib.error_proto: bea. errors may need to be changed
     if errors on ‘quit’ are encountered by a particular application
     (bpo-11291(8)).

   * The ‘strict’ argument to *note email.parser.Parser: beb, deprecated
     since Python 2.4, has finally been removed.

   * The deprecated method ‘unittest.TestCase.assertSameElements’ has
     been removed.

   * The deprecated variable ‘time.accept2dyear’ has been removed.

   * The deprecated ‘Context._clamp’ attribute has been removed from the
     *note decimal: 35. module.  It was previously replaced by the
     public attribute ‘clamp’.  (See bpo-8540(9).)

   * The undocumented internal helper class ‘SSLFakeFile’ has been
     removed from *note smtplib: ed, since its functionality has long
     been provided directly by *note socket.socket.makefile(): bec.

   * Passing a negative value to *note time.sleep(): 773. on Windows now
     raises an error instead of sleeping forever.  It has always raised
     an error on posix.

   * The ‘ast.__version__’ constant has been removed.  If you need to
     make decisions affected by the AST version, use *note
     sys.version_info: bed. to make the decision.

   * Code that used to work around the fact that the *note threading:
     10b. module used factory functions by subclassing the private
     classes will need to change to subclass the now-public classes.

   * 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(10)).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue12326

   (2) https://bugs.python.org/issue13847

   (3) https://bugs.python.org/issue14180

   (4) https://www.python.org/dev/peps/pep-0328

   (5) https://www.python.org/dev/peps/pep-0302

   (6) https://bugs.python.org/issue1079

   (7) https://bugs.python.org/issue1690608

   (8) https://bugs.python.org/issue11291

   (9) https://bugs.python.org/issue8540

   (10) https://bugs.python.org/issue13550


File: python.info,  Node: Porting C code,  Next: Building C extensions,  Prev: Porting Python code,  Up: 移植到 Python 3 3

1.7.24.2 Porting C code
.......................

   * In the course of changes to the buffer API the undocumented
     ‘smalltable’ member of the *note Py_buffer: bee. structure has been
     removed and the layout of the ‘PyMemoryViewObject’ has changed.

     All extensions relying on the relevant parts in ‘memoryobject.h’ or
     ‘object.h’ must be rebuilt.

   * Due to *note PEP 393: a5d, the *note Py_UNICODE: bc5. 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 PEP 393(1), you have to
     convert your code to the new *note Unicode API: bef.

     However, if you only have been using high-level functions such as
     *note PyUnicode_Concat(): bf0, *note PyUnicode_Join(): bf1. or
     *note PyUnicode_FromFormat(): 8b8, your code will automatically
     take advantage of the new unicode representations.

   * *note PyImport_GetMagicNumber(): bf2. now returns ‘-1’ upon
     failure.

   * As a negative value for the `level' argument to *note __import__():
     16b. is no longer valid, the same now holds for *note
     PyImport_ImportModuleLevel(): bf3.  This also means that the value
     of `level' used by *note PyImport_ImportModuleEx(): bf4. is now ‘0’
     instead of ‘-1’.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0393


File: python.info,  Node: Building C extensions,  Next: Command Line Switch Changes,  Prev: Porting C code,  Up: 移植到 Python 3 3

1.7.24.3 Building C extensions
..............................

   * The range of possible file names for C extensions has been
     narrowed.  Very rarely used spellings have been suppressed: under
     POSIX, files named ‘xxxmodule.so’, ‘xxxmodule.abi3.so’ and
     ‘xxxmodule.cpython-*.so’ are no longer recognized as implementing
     the ‘xxx’ module.  If you had been generating such files, you have
     to switch to the other spellings (i.e., remove the ‘module’ string
     from the file names).

     (implemented in bpo-14040(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue14040


File: python.info,  Node: Command Line Switch Changes,  Prev: Building C extensions,  Up: 移植到 Python 3 3

1.7.24.4 Command Line Switch Changes
....................................

   * The -Q command-line flag and related artifacts have been removed.
     Code checking sys.flags.division_warning will need updating.

     （bpo-10998(1)，由 Éric Araujo 贡献。）

   * When ‘python’ is started with *note -S: bf7, ‘import site’ will no
     longer add site-specific paths to the module search paths.  In
     previous versions, it did.

     (bpo-11591(2), contributed by Carl Meyer with editions by Éric
     Araujo.)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10998

   (2) https://bugs.python.org/issue11591


File: python.info,  Node: Python 3 2 有什么新变化,  Next: Python 3 1 有什么新变化,  Prev: Python 3 3 有什么新变化,  Up: Python 有什麼新功能？

1.8 Python 3.2 有什么新变化
===========================


作者: Raymond Hettinger

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(1) file.

也參考
......

PEP 392(2) - 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.

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/blob/076ca6c3c8df3030307e548d9be792ce3c1c6eea/Misc/NEWS

   (2) https://www.python.org/dev/peps/pep-0392


File: python.info,  Node: PEP 384 定义稳定的ABI,  Next: PEP 389 Argparse 命令行解析模块,  Up: Python 3 2 有什么新变化

1.8.1 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.

也參考
......

PEP 384(1) - 定义稳定的ABI

     PEP 由 Martin von Löwis 撰写

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0384


File: python.info,  Node: PEP 389 Argparse 命令行解析模块,  Next: PEP 391 基于字典的日志配置,  Prev: PEP 384 定义稳定的ABI,  Up: Python 3 2 有什么新变化

1.8.2 PEP 389: Argparse 命令行解析模块
--------------------------------------

A new module for command line parsing, *note argparse: 5, was introduced
to overcome the limitations of *note optparse: c3. 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
*note argparse: 5. 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 `metavar' in the help screen,
validating that one or more positional arguments is present, and making
a required option:

     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')

Example of calling the parser on a command string:

     >>> 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'

Example of the parser’s automatically generated help:

     >>> 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

An especially nice *note argparse: 5. feature is the ability to define
subparsers, each with their own argument patterns and help displays:

     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)

     $ ./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

也參考
......

PEP 389(1) - 新的命令行解析模块

     PEP 由 Steven Bethard 撰写

*note 升级 optparse 代码: bfc. for details on the differences from *note
optparse: c3.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0389


File: python.info,  Node: PEP 391 基于字典的日志配置,  Next: PEP 3148 concurrent futures 模块,  Prev: PEP 389 Argparse 命令行解析模块,  Up: Python 3 2 有什么新变化

1.8.3 PEP 391: 基于字典的日志配置
---------------------------------

The *note logging: aa. 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 ‘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 *note
logging.config.dictConfig(): bfe. 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:

     {"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"]}}

If that dictionary is stored in a file called ‘conf.json’, it can be
loaded and called with code like this:

     >>> 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

也參考
......

PEP 391(1) - 基于字典的日志配置

     PEP 由 Vinay Sajip 撰写

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0391


File: python.info,  Node: PEP 3148 concurrent futures 模块,  Next: PEP 3147 PYC 仓库目录,  Prev: PEP 391 基于字典的日志配置,  Up: Python 3 2 有什么新变化

1.8.4 PEP 3148: ‘concurrent.futures’ 模块
-----------------------------------------

Code for creating and managing concurrency is being collected in a new
top-level namespace, `concurrent'.  Its first member is a `futures'
package which provides a uniform high-level interface for managing
threads and processes.

The design for *note concurrent.futures: 21. was inspired by the
`java.util.concurrent' package.  In that model, a running call and its
result are represented by a *note Future: c00. 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: *note
submit(): 3c6. for scheduling a callable and returning a *note Future:
c00. object; *note map(): 7b1. for scheduling many asynchronous calls at
a time, and *note shutdown(): 195. for freeing resources.  The class is
a *note context manager: 661. and can be used in a *note with: 7da.
statement to assure that resources are automatically released when
currently pending futures are done executing.

A simple of example of *note ThreadPoolExecutor: 18c. is a launch of
four parallel threads for copying files:

     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')

也參考
......

PEP 3148(1) – futures - 异步执行指令

     PEP 由 Brian Quinlan 撰写

*note Code for Threaded Parallel URL reads: c01, an example using
threads to fetch multiple web pages in parallel.

*note Code for computing prime numbers in parallel: c02, an example
demonstrating *note ProcessPoolExecutor: 196.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3148


File: python.info,  Node: PEP 3147 PYC 仓库目录,  Next: PEP 3149 ABI Version Tagged so Files,  Prev: PEP 3148 concurrent futures 模块,  Up: Python 3 2 有什么新变化

1.8.5 PEP 3147: PYC 仓库目录
----------------------------

Python’s scheme for caching bytecode in `.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 `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:

   * Imported modules now have a *note __cached__: c04. attribute which
     stores the name of the actual file that was imported:

          >>> import collections
          >>> collections.__cached__
          'c:/py32/lib/__pycache__/collections.cpython-32.pyc'

   * The tag that is unique to each interpreter is accessible from the
     *note imp: 99. module:

          >>> import imp
          >>> imp.get_tag()
          'cpython-32'

   * 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 *note imp: 99. module:

          >>> 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'

   * The *note py_compile: d7. and *note compileall: 20. modules have
     been updated to reflect the new naming convention and target
     directory.  The command-line invocation of `compileall' has new
     options: ‘-i’ for specifying a list of files and directories to
     compile and ‘-b’ which causes bytecode files to be written to their
     legacy location rather than `__pycache__'.

   * The *note importlib.abc: 9b. module has been updated with new *note
     abstract base classes: c05. for loading bytecode files.  The
     obsolete ABCs, ‘PyLoader’ and ‘PyPycLoader’, have been deprecated
     (instructions on how to stay Python 3.1 compatible are included
     with the documentation).

也參考
......

PEP 3147(1) - PYC 仓库目录

     PEP 由 Barry Warsaw 撰写

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3147


File: python.info,  Node: PEP 3149 ABI Version Tagged so Files,  Next: PEP 3333 Python Web服务器网关接口v1 0 1,  Prev: PEP 3147 PYC 仓库目录,  Up: Python 3 2 有什么新变化

1.8.6 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:

     /usr/share/pyshared/foo.cpython-32m.so
     /usr/share/pyshared/foo.cpython-33md.so

In Python itself, the tags are accessible from functions in the *note
sysconfig: fe. module:

     >>> 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'

也參考
......

PEP 3149(1) - ABI Version Tagged .so Files

     PEP 由 Barry Warsaw 撰写

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3149


File: python.info,  Node: PEP 3333 Python Web服务器网关接口v1 0 1,  Next: 其他语言特性修改<8>,  Prev: PEP 3149 ABI Version Tagged so Files,  Up: Python 3 2 有什么新变化

1.8.7 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 *note str: 205. type even though
the HTTP protocol is itself bytes oriented.

The PEP differentiates so-called `native strings' that are used for
request/response headers and metadata versus `byte strings' which are
used for the bodies of requests and responses.

The `native strings' are always of type *note str: 205. but are
restricted to code points between `U+0000' through `U+00FF' which are
translatable to bytes using `Latin-1' encoding.  These strings are used
for the keys and values in the environment dictionary and for response
headers and statuses in the ‘start_response()’ function.  They must
follow RFC 2616(1) with respect to encoding.  That is, they must either
be `ISO-8859-1' characters or use RFC 2047(2) MIME encoding.

For developers porting WSGI applications from Python 2, here are the
salient points:

   * If the app already used strings for headers in Python 2, no change
     is needed.

   * 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
     ‘h.encode('utf-8')’ now needs to convert from bytes to native
     strings using ‘h.encode('utf-8').decode('latin-1')’.

   * Values yielded by an application or sent using the ‘write()’ method
     must be byte strings.  The ‘start_response()’ function and environ
     must use native strings.  The two cannot be mixed.

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 *note wsgiref: 135. module has a
new function, *note wsgiref.handlers.read_environ(): c08. for
transcoding CGI variables from *note os.environ: c09. into native
strings and returning a new dictionary.

也參考
......

PEP 3333(3) - Python Web服务器网关接口v1.0.1

     PEP 由 Phillip Eby 撰写

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2616.html

   (2) https://tools.ietf.org/html/rfc2047.html

   (3) https://www.python.org/dev/peps/pep-3333


File: python.info,  Node: 其他语言特性修改<8>,  Next: 新增，改进和弃用的模块,  Prev: PEP 3333 Python Web服务器网关接口v1 0 1,  Up: Python 3 2 有什么新变化

1.8.8 其他语言特性修改
----------------------

对Python 语言核心进行的小改动：

   * String formatting for *note format(): 5d5. and *note str.format():
     5d4. gained new capabilities for the format character `#'.
     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.

          >>> format(20, '#o')
          '0o24'
          >>> format(12.34, '#5.0f')
          '  12.'

     (Suggested by Mark Dickinson and implemented by Eric Smith in
     bpo-7094(1).)

   * There is also a new *note str.format_map(): 7a4. method that
     extends the capabilities of the existing *note str.format(): 5d4.
     method by accepting arbitrary *note mapping: c0b. objects.  This
     new method makes it possible to use string formatting with any of
     Python’s many dictionary-like objects such as *note defaultdict:
     c0c, *note Shelf: 997, *note ConfigParser: 5a4, or *note dbm: 31.
     It is also useful with custom *note dict: 164. subclasses that
     normalize keys before look-up or that supply a *note __missing__():
     c0d. method for unknown keys:

          >>> 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>'

     (Suggested by Raymond Hettinger and implemented by Eric Smith in
     bpo-6081(2).)

   * The interpreter can now be started with a quiet option, ‘-q’, to
     prevent the copyright and version information from being displayed
     in the interactive mode.  The option can be introspected using the
     *note sys.flags: c0e. attribute:

          $ 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)

     （由 Marcin Wojdyr 在 bpo-1772833(3) 中贡献。）

   * The *note hasattr(): 54a. function works by calling *note
     getattr(): 54b. and detecting whether an exception is raised.  This
     technique allows it to detect methods created dynamically by *note
     __getattr__(): 42a. or *note __getattribute__(): 549. which would
     otherwise be absent from the class dictionary.  Formerly, `hasattr'
     would catch any exception, possibly masking genuine errors.  Now,
     `hasattr' has been tightened to only catch *note AttributeError:
     4a1. and let other exceptions pass through:

          >>> 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

     (Discovered by Yury Selivanov and fixed by Benjamin Peterson;
     bpo-9666(4).)

   * The *note str(): 205. of a float or complex number is now the same
     as its *note repr(): 8b9.  Previously, the *note str(): 205. form
     was shorter but that just caused confusion and is no longer needed
     now that the shortest possible *note repr(): 8b9. is displayed by
     default:

          >>> import math
          >>> repr(math.pi)
          '3.141592653589793'
          >>> str(math.pi)
          '3.141592653589793'

     (Proposed and implemented by Mark Dickinson; bpo-9337(5).)

   * *note memoryview: 386. objects now have a *note release(): c0f.
     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.

          >>> with memoryview(b'abcdefgh') as v:
          ...     print(v.tolist())
          [97, 98, 99, 100, 101, 102, 103, 104]

     (Added by Antoine Pitrou; bpo-9757(6).)

   * Previously it was illegal to delete a name from the local namespace
     if it occurs as a free variable in a nested block:

          def outer(x):
              def inner():
                  return x
              inner()
              del x

     This is now allowed.  Remember that the target of an *note except:
     c10. clause is cleared, so this code which used to work with Python
     2.6, raised a *note SyntaxError: 559. with Python 3.1 and now works
     again:

          def f():
              def print_error():
                  print(e)
              try:
                  something
              except Exception as e:
                  print_error()
                  # implicit "del e" here

     (See bpo-4617(7).)

   * The internal ‘structsequence’ tool now creates subclasses of tuple.
     This means that C structures like those returned by *note
     os.stat(): 321, *note time.gmtime(): c11, and *note
     sys.version_info: bed. now work like a *note named tuple: b7b. 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:

          >>> import sys
          >>> isinstance(sys.version_info, tuple)
          True
          >>> 'Version %d.%d.%d %s(%d)' % sys.version_info
          'Version 3.2.0 final(0)'

     (Suggested by Arfrever Frehtes Taifersar Arahesis and implemented
     by Benjamin Peterson in bpo-8413(8).)

   * Warnings are now easier to control using the *note PYTHONWARNINGS:
     51b. environment variable as an alternative to using ‘-W’ at the
     command line:

          $ export PYTHONWARNINGS='ignore::RuntimeWarning::,once::UnicodeWarning::'

     (Suggested by Barry Warsaw and implemented by Philip Jenvey in
     bpo-7301(9).)

   * A new warning category, *note ResourceWarning: 5ca, 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 *note
     warnings: 12f. module, or on the command line.

     A *note ResourceWarning: 5ca. is issued at interpreter shutdown if
     the *note gc.garbage: c12. list isn’t empty, and if *note
     gc.DEBUG_UNCOLLECTABLE: c13. is set, all uncollectable objects are
     printed.  This is meant to make the programmer aware that their
     code contains object finalization issues.

     A *note ResourceWarning: 5ca. is also issued when a *note file
     object: c14. 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:

          $ python -q -Wdefault
          >>> f = open("foo", "wb")
          >>> del f
          __main__:1: ResourceWarning: unclosed file <_io.BufferedWriter name='foo'>

     (Added by Antoine Pitrou and Georg Brandl in bpo-10093(10) and
     bpo-477863(11).)

   * *note range: 1f5. objects now support `index' and `count' methods.
     This is part of an effort to make more objects fully implement the
     ‘collections.Sequence’ *note abstract base class: c05.  As a
     result, the language will have a more uniform API. In addition,
     *note range: 1f5. objects now support slicing and negative indices,
     even with values larger than *note sys.maxsize: c15.  This makes
     `range' more interoperable with lists:

          >>> 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)

     （由 Daniel Stutzbach 在 bpo-9213(12) 中贡献，由 Alexander
     Belopolsky 在 bpo-2690(13) 中贡献，由 Nick Coghlan 在 bpo-10889(14)
     中贡献。）

   * The *note callable(): c16. builtin function from Py2.x was
     resurrected.  It provides a concise, readable alternative to using
     an *note abstract base class: c05. in an expression like
     ‘isinstance(x, collections.Callable)’:

          >>> callable(max)
          True
          >>> callable(20)
          False

     （见 bpo-10518(15) ）

   * 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.

     (Required extensive work by Victor Stinner in bpo-9425(16).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue7094

   (2) https://bugs.python.org/issue6081

   (3) https://bugs.python.org/issue1772833

   (4) https://bugs.python.org/issue9666

   (5) https://bugs.python.org/issue9337

   (6) https://bugs.python.org/issue9757

   (7) https://bugs.python.org/issue4617

   (8) https://bugs.python.org/issue8413

   (9) https://bugs.python.org/issue7301

   (10) https://bugs.python.org/issue10093

   (11) https://bugs.python.org/issue477863

   (12) https://bugs.python.org/issue9213

   (13) https://bugs.python.org/issue2690

   (14) https://bugs.python.org/issue10889

   (15) https://bugs.python.org/issue10518

   (16) https://bugs.python.org/issue9425


File: python.info,  Node: 新增，改进和弃用的模块,  Next: 多线程,  Prev: 其他语言特性修改<8>,  Up: Python 3 2 有什么新变化

1.8.9 新增，改进和弃用的模块
----------------------------

Python’s standard library has undergone significant maintenance efforts
and quality improvements.

The biggest news for Python 3.2 is that the *note email: 67. package,
*note mailbox: ae. module, and *note nntplib: c0. 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 `SSL' connections and security certificates.

In addition, more classes now implement a *note context manager: 661. to
support convenient and reliable resource clean-up using a *note with:
7da. 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<5>.
* 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::


File: python.info,  Node: email<5>,  Next: elementtree,  Up: 新增，改进和弃用的模块

1.8.9.1 email
.............

The usability of the *note email: 67. 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 *note
bytes: 172. rather than *note str: 205. 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.

   * New functions *note message_from_bytes(): c19. and *note
     message_from_binary_file(): c1a, and new classes *note
     BytesFeedParser: c1b. and *note BytesParser: c1c. allow binary
     message data to be parsed into model objects.

   * Given bytes input to the model, *note get_payload(): c1d. will by
     default decode a message body that has a
     ‘Content-Transfer-Encoding’ of `8bit' using the charset specified
     in the MIME headers and return the resulting string.

   * Given bytes input to the model, *note Generator: c1e. will convert
     message bodies that have a ‘Content-Transfer-Encoding’ of `8bit' to
     instead have a `7bit' ‘Content-Transfer-Encoding’.

     Headers with unencoded non-ASCII bytes are deemed to be RFC
     2047(1)-encoded using the `unknown-8bit' character set.

   * A new class *note BytesGenerator: c1f. 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
     ‘Content-Transfer-Encoding’ of `8bit'.

   * The *note smtplib: ed. *note SMTP: 1de. class now accepts a byte
     string for the `msg' argument to the *note sendmail(): 833. method,
     and a new method, *note send_message(): 834. accepts a *note
     Message: 63b. object and can optionally obtain the `from_addr' and
     `to_addrs' addresses directly from the object.

(Proposed and implemented by R. David Murray, bpo-4661(2) and
bpo-10321(3).)

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2047.html

   (2) https://bugs.python.org/issue4661

   (3) https://bugs.python.org/issue10321


File: python.info,  Node: elementtree,  Next: functools<6>,  Prev: email<5>,  Up: 新增，改进和弃用的模块

1.8.9.2 elementtree
...................

The *note xml.etree.ElementTree: 140. package and its
‘xml.etree.cElementTree’ counterpart have been updated to version 1.3.

Several new and useful functions and methods have been added:

   * *note xml.etree.ElementTree.fromstringlist(): c21. which builds an
     XML document from a sequence of fragments

   * *note xml.etree.ElementTree.register_namespace(): c22. for
     registering a global namespace prefix

   * *note xml.etree.ElementTree.tostringlist(): 9fc. for string
     representation including all sublists

   * *note xml.etree.ElementTree.Element.extend(): c23. for appending a
     sequence of zero or more elements

   * *note xml.etree.ElementTree.Element.iterfind(): c24. searches an
     element and subelements

   * *note xml.etree.ElementTree.Element.itertext(): c25. creates a text
     iterator over an element and its subelements

   * *note xml.etree.ElementTree.TreeBuilder.end(): c26. closes the
     current element

   * *note xml.etree.ElementTree.TreeBuilder.doctype(): 3e3. handles a
     doctype declaration

两个方法被弃用：

   * ‘xml.etree.ElementTree.getchildren()’ 被 ‘list(elem)’ 替代。

   * ‘xml.etree.ElementTree.getiterator()’ 被 ‘Element.iter’ 替代。

For details of the update, see Introducing ElementTree(1) on Fredrik
Lundh’s website.

（由 Florent Xicluna 和 Fredrik Lundh 在 bpo-6472(2) 中贡献。）

   ---------- Footnotes ----------

   (1) http://effbot.org/zone/elementtree-13-intro.htm

   (2) https://bugs.python.org/issue6472


File: python.info,  Node: functools<6>,  Next: itertools<4>,  Prev: elementtree,  Up: 新增，改进和弃用的模块

1.8.9.3 functools
.................

   * The *note functools: 83. module includes a new decorator for
     caching function calls.  *note functools.lru_cache(): 2f8. 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:

          >>> 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]

          >>> for name in user_requests:
          ...     get_phone_number(name)        # cached lookup

     To help with choosing an effective cache size, the wrapped function
     is instrumented for tracking cache statistics:

          >>> get_phone_number.cache_info()
          CacheInfo(hits=4805, misses=980, maxsize=300, currsize=300)

     If the phonelist table gets updated, the outdated contents of the
     cache can be cleared with:

          >>> get_phone_number.cache_clear()

     (Contributed by Raymond Hettinger and incorporating design ideas
     from Jim Baker, Miki Tebeka, and Nick Coghlan; see recipe
     498245(1), recipe 577479(2), bpo-10586(3), and bpo-10593(4).)

   * The *note functools.wraps(): 955. decorator now adds a
     ‘__wrapped__’ attribute pointing to the original callable function.
     This allows wrapped functions to be introspected.  It also copies
     ‘__annotations__’ if defined.  And now it also gracefully skips
     over missing attributes such as ‘__doc__’ which might not be
     defined for the wrapped callable.

     In the above example, the cache can be removed by recovering the
     original function:

          >>> get_phone_number = get_phone_number.__wrapped__    # uncached function

     (By Nick Coghlan and Terrence Cole; bpo-9567(5), bpo-3445(6), and
     bpo-8814(7).)

   * To help write classes with rich comparison methods, a new decorator
     *note functools.total_ordering(): 938. will use existing equality
     and inequality methods to fill in the remaining methods.

     For example, supplying `__eq__' and `__lt__' will enable *note
     total_ordering(): 938. to fill-in `__le__', `__gt__' and `__ge__':

          @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()))

     With the `total_ordering' decorator, the remaining comparison
     methods are filled in automatically.

     （由 Raymond Hettinger 贡献。）

   * To aid in porting programs from Python 2, the *note
     functools.cmp_to_key(): c28. function converts an old-style
     comparison function to modern *note key function: 7d2.:

          >>> # locale-aware sort order
          >>> sorted(iterable, key=cmp_to_key(locale.strcoll))

     For sorting examples and a brief sorting tutorial, see the Sorting
     HowTo(8) tutorial.

     （由 Raymond Hettinger 贡献。）

   ---------- Footnotes ----------

   (1) https://code.activestate.com/recipes/498245

   (2) https://code.activestate.com/recipes/577479

   (3) https://bugs.python.org/issue10586

   (4) https://bugs.python.org/issue10593

   (5) https://bugs.python.org/issue9567

   (6) https://bugs.python.org/issue3445

   (7) https://bugs.python.org/issue8814

   (8) https://wiki.python.org/moin/HowTo/Sorting/


File: python.info,  Node: itertools<4>,  Next: collections<8>,  Prev: functools<6>,  Up: 新增，改进和弃用的模块

1.8.9.4 itertools
.................

   * The *note itertools: a3. module has a new *note accumulate(): 30e.
     function modeled on APL’s `scan' operator and Numpy’s `accumulate'
     function:

          >>> from itertools import accumulate
          >>> list(accumulate([8, 2, 50]))
          [8, 10, 60]

          >>> 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]

     For an example using *note accumulate(): 30e, see the *note
     examples for the random module: c2a.

     (Contributed by Raymond Hettinger and incorporating design
     suggestions from Mark Dickinson.)


File: python.info,  Node: collections<8>,  Next: threading<6>,  Prev: itertools<4>,  Up: 新增，改进和弃用的模块

1.8.9.5 collections
...................

   * The *note collections.Counter: ab9. class now has two forms of
     in-place subtraction, the existing `-=' operator for saturating
     subtraction(1) and the new *note subtract(): c2c. method for
     regular subtraction.  The former is suitable for multisets(2) which
     only have positive counts, and the latter is more suitable for use
     cases that allow negative counts:

          >>> from collections import Counter
          >>> tally = Counter(dogs=5, cats=3)
          >>> tally -= Counter(dogs=2, cats=8)    # saturating subtraction
          >>> tally
          Counter({'dogs': 3})

          >>> tally = Counter(dogs=5, cats=3)
          >>> tally.subtract(dogs=2, cats=8)      # regular subtraction
          >>> tally
          Counter({'dogs': 3, 'cats': -5})

     （由 Raymond Hettinger 贡献。）

   * The *note collections.OrderedDict: 2ea. class has a new method
     *note move_to_end(): c2d. 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 ‘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.

          >>> 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']

     （由 Raymond Hettinger 贡献。）

   * The *note collections.deque: 62a. class grew two new methods *note
     count(): c2e. and *note reverse(): c2f. that make them more
     substitutable for *note list: 1f8. objects:

          >>> 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'])

     （由 Raymond Hettinger 贡献。）

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Saturation_arithmetic

   (2) https://en.wikipedia.org/wiki/Multiset


File: python.info,  Node: threading<6>,  Next: datetime 和 time,  Prev: collections<8>,  Up: 新增，改进和弃用的模块

1.8.9.6 threading
.................

The *note threading: 10b. module has a new *note Barrier: c31.
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(1) which is defined for only two threads.

Implemented as a two-phase cyclic barrier, *note Barrier: c31. objects
are suitable for use in loops.  The separate `filling' and `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:

     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()

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 *note
threading.Thread.join(): c32, 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 `timeout' parameter.  Then if the timeout
period elapses before all the predecessor tasks reach the barrier point,
all waiting threads are released and a *note BrokenBarrierError: c33.
exception is raised:

     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)

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(2) 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(3),
`section 3.6'.

(Contributed by Kristján Valur Jónsson with an API review by Jeffrey
Yasskin in bpo-8777(4).)

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Synchronous_rendezvous

   (2) 
http://osl.cs.illinois.edu/media/papers/karmani-2009-barrier_synchronization_pattern.pdf

   (3) https://greenteapress.com/semaphores/LittleBookOfSemaphores.pdf

   (4) https://bugs.python.org/issue8777


File: python.info,  Node: datetime 和 time,  Next: math<7>,  Prev: threading<6>,  Up: 新增，改进和弃用的模块

1.8.9.7 datetime 和 time
........................

   * The *note datetime: 30. module has a new type *note timezone: ae0.
     that implements the *note tzinfo: 180. interface by returning a
     fixed UTC offset and timezone name.  This makes it easier to create
     timezone-aware datetime objects:

          >>> 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)

   * Also, *note timedelta: 2ca. objects can now be multiplied by *note
     float: 1fd. and divided by *note float: 1fd. and *note int: 204.
     objects.  And *note timedelta: 2ca. objects can now divide one
     another.

   * The *note datetime.date.strftime(): 631. method is no longer
     restricted to years after 1900.  The new supported year range is
     from 1000 to 9999 inclusive.

   * Whenever a two-digit year is used in a time tuple, the
     interpretation has been governed by ‘time.accept2dyear’.  The
     default is ‘True’ which means that for a two-digit year, the
     century is guessed according to the POSIX rules governing the ‘%y’
     strptime format.

     Starting with Py3.2, use of the century guessing heuristic will
     emit a *note DeprecationWarning: 15a.  Instead, it is recommended
     that ‘time.accept2dyear’ be set to ‘False’ so that large date
     ranges can be used without guesswork:

          >>> 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'

     Several functions now have significantly expanded date ranges.
     When ‘time.accept2dyear’ is false, the *note time.asctime(): c35.
     function will accept any year that fits in a C int, while the *note
     time.mktime(): c36. and *note time.strftime(): c37. functions will
     accept the full range supported by the corresponding operating
     system functions.

(Contributed by Alexander Belopolsky and Victor Stinner in
bpo-1289118(1), bpo-5094(2), bpo-6641(3), bpo-2706(4), bpo-1777412(5),
bpo-8013(6), and bpo-10827(7).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1289118

   (2) https://bugs.python.org/issue5094

   (3) https://bugs.python.org/issue6641

   (4) https://bugs.python.org/issue2706

   (5) https://bugs.python.org/issue1777412

   (6) https://bugs.python.org/issue8013

   (7) https://bugs.python.org/issue10827


File: python.info,  Node: math<7>,  Next: abc<3>,  Prev: datetime 和 time,  Up: 新增，改进和弃用的模块

1.8.9.8 math
............

The *note math: b1. module has been updated with six new functions
inspired by the C99 standard.

The *note isfinite(): c39. function provides a reliable and fast way to
detect special values.  It returns ‘True’ for regular numbers and
‘False’ for `Nan' or `Infinity':

     >>> from math import isfinite
     >>> [isfinite(x) for x in (123, 4.56, float('Nan'), float('Inf'))]
     [True, True, False, False]

The *note expm1(): c3a. function computes ‘e**x-1’ for small values of
`x' without incurring the loss of precision that usually accompanies the
subtraction of nearly equal quantities:

     >>> from math import expm1
     >>> expm1(0.013671875)   # more accurate way to compute e**x-1 for a small x
     0.013765762467652909

The *note erf(): 553. function computes a probability integral or
Gaussian error function(1).  The complementary error function, *note
erfc(): 554, is ‘1 - erf(x)’:

     >>> 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

The *note gamma(): c3b. function is a continuous extension of the
factorial function.  See ‘https://en.wikipedia.org/wiki/Gamma_function’
for details.  Because the function is related to factorials, it grows
large even for small values of `x', so there is also a *note lgamma():
c3c. function for computing the natural logarithm of the gamma function:

     >>> from math import gamma, lgamma
     >>> gamma(7.0)           # six factorial
     720.0
     >>> lgamma(801.0)        # log(800 factorial)
     4551.950730698041

（由 Mark Dickinson 贡献）

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Error_function


File: python.info,  Node: abc<3>,  Next: io<5>,  Prev: math<7>,  Up: 新增，改进和弃用的模块

1.8.9.9 abc
...........

The *note abc: 3. module now supports *note abstractclassmethod(): aae.
and *note abstractstaticmethod(): aaf.

These tools make it possible to define an *note abstract base class:
c05. that requires a particular *note classmethod(): 309. or *note
staticmethod(): 30a. to be implemented:

     class Temperature(metaclass=abc.ABCMeta):
         @abc.abstractclassmethod
         def from_fahrenheit(cls, t):
             ...
         @abc.abstractclassmethod
         def from_celsius(cls, t):
             ...

(Patch submitted by Daniel Urban; bpo-5867(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5867


File: python.info,  Node: io<5>,  Next: reprlib,  Prev: abc<3>,  Up: 新增，改进和弃用的模块

1.8.9.10 io
...........

The *note io.BytesIO: 88a. has a new method, *note getbuffer(): c3f,
which provides functionality similar to *note memoryview(): 386.  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:

     >>> 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'

（由 Antoine Pitrou 在 bpo-5506(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5506


File: python.info,  Node: reprlib,  Next: logging<7>,  Prev: io<5>,  Up: 新增，改进和弃用的模块

1.8.9.11 reprlib
................

When writing a *note __repr__(): 44a. 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 *note list: 1f8. and
*note set: 1f6. handle self-reference by displaying "..."  in the
recursive part of the representation string.

To help write such *note __repr__(): 44a. methods, the *note reprlib:
df. module has a new decorator, *note recursive_repr(): c41, for
detecting recursive calls to *note __repr__(): 44a. and substituting a
placeholder string instead:

     >>> 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'>

（由 Raymond Hettinger 在 bpo-9826(1) 和 bpo-9840(2) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue9826

   (2) https://bugs.python.org/issue9840


File: python.info,  Node: logging<7>,  Next: csv<3>,  Prev: reprlib,  Up: 新增，改进和弃用的模块

1.8.9.12 logging
................

In addition to dictionary-based configuration described above, the *note
logging: aa. package has many other improvements.

The logging documentation has been augmented by a *note basic tutorial:
c43, an *note advanced tutorial: c44, and a *note cookbook: c45. of
logging recipes.  These documents are the fastest way to learn about
logging.

The *note logging.basicConfig(): 311. set-up function gained a `style'
argument to support three different types of string formatting.  It
defaults to "%" for traditional %-formatting, can be set to "{" for the
new *note str.format(): 5d4. style, or can be set to "$" for the
shell-style formatting provided by *note string.Template: 4f0.  The
following three configurations are equivalent:

     >>> 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")

If no configuration is set-up before a logging event occurs, there is
now a default configuration using a *note StreamHandler: c46. directed
to *note sys.stderr: 1ea. for events of ‘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 ‘logging.raiseExceptions’.  The new default handler is stored
in *note logging.lastResort: c47.

The use of filters has been simplified.  Instead of creating a *note
Filter: c48. object, the predicate can be any Python callable that
returns ‘True’ or ‘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.


File: python.info,  Node: csv<3>,  Next: contextlib<6>,  Prev: logging<7>,  Up: 新增，改进和弃用的模块

1.8.9.13 csv
............

The *note csv: 29. module now supports a new dialect, *note
unix_dialect: c4a, which applies quoting for all fields and a
traditional Unix style with ‘'\n'’ as the line terminator.  The
registered dialect name is ‘unix’.

The *note csv.DictWriter: c4b. has a new method, *note writeheader():
c4c. for writing-out an initial row to document the field names:

     >>> 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"

(New dialect suggested by Jay Talbot in bpo-5975(1), and the new method
suggested by Ed Abraham in bpo-1537721(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5975

   (2) https://bugs.python.org/issue1537721


File: python.info,  Node: contextlib<6>,  Next: decimal and fractions,  Prev: csv<3>,  Up: 新增，改进和弃用的模块

1.8.9.14 contextlib
...................

There is a new and slightly mind-blowing tool *note ContextDecorator:
c4e. that is helpful for creating a *note context manager: 661. that
does double duty as a function decorator.

As a convenience, this new functionality is used by *note
contextmanager(): c4f. 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 *note with: 7da. 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 *note contextmanager(): c4f. provides both
capabilities in a single definition:

     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)

Formerly, this would have only been usable as a context manager:

     with track_entry_and_exit('widget loader'):
         print('Some time consuming activity goes here')
         load_widget()

Now, it can be used as a decorator as well:

     @track_entry_and_exit('widget loader')
     def activity():
         print('Some time consuming activity goes here')
         load_widget()

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 *note with: 7da. statement, but there is no
parallel for function decorators.

In the above example, there is not a clean way for the
`track_entry_and_exit' context manager to return a logging instance for
use in the body of enclosed statements.

（由 Michael Foord 在 bpo-9110(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue9110


File: python.info,  Node: decimal and fractions,  Next: ftp,  Prev: contextlib<6>,  Up: 新增，改进和弃用的模块

1.8.9.15 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(1)):

     assert hash(Fraction(3, 2)) == hash(1.5) == \
            hash(Decimal("1.5")) == hash(complex(1.5, 0))

Some of the hashing details are exposed through a new attribute, *note
sys.hash_info: a06, which describes the bit width of the hash value, the
prime modulus, the hash values for `infinity' and `nan', and the
multiplier used for the imaginary part of a number:

     >>> sys.hash_info
     sys.hash_info(width=64, modulus=2305843009213693951, inf=314159, nan=0, imag=1000003)

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 ‘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.

   * The *note decimal.Decimal: 2c0. constructor now accepts *note
     float: 1fd. objects directly so there in no longer a need to use
     the *note from_float(): c51. method (bpo-8257(2)).

   * Mixed type comparisons are now fully supported so that *note
     Decimal: 2c0. objects can be directly compared with *note float:
     1fd. and *note fractions.Fraction: 2be. (bpo-2531(3) and
     bpo-8188(4)).

Similar changes were made to *note fractions.Fraction: 2be. so that the
*note from_float(): c52. and *note from_decimal(): c53. methods are no
longer needed (bpo-8294(5)):

     >>> from decimal import Decimal
     >>> from fractions import Fraction
     >>> Decimal(1.1)
     Decimal('1.100000000000000088817841970012523233890533447265625')
     >>> Fraction(1.1)
     Fraction(2476979795053773, 2251799813685248)

Another useful change for the *note decimal: 35. module is that the
‘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(6)).

（由 Mark Dickinson 和 Raymond Hettinger贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue8188

   (2) https://bugs.python.org/issue8257

   (3) https://bugs.python.org/issue2531

   (4) https://bugs.python.org/issue8188

   (5) https://bugs.python.org/issue8294

   (6) https://bugs.python.org/issue8540


File: python.info,  Node: ftp,  Next: popen,  Prev: decimal and fractions,  Up: 新增，改进和弃用的模块

1.8.9.16 ftp
............

The *note ftplib.FTP: 1a6. class now supports the context management
protocol to unconditionally consume *note socket.error: a76. exceptions
and to close the FTP connection when done:

     >>> 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

Other file-like objects such as *note mmap.mmap: 31c. and *note
fileinput.input(): 3cf. also grew auto-closing context managers:

     with fileinput.input(files=('log1.txt', 'log2.txt')) as f:
         for line in f:
             process(line)

（由 Tarek Ziadé 和 Giampaolo Rodolà 在 bpo-4972‘贡献，由 Georg Brandl 在
:issue:‘8046(1) 和 bpo-1286(2) 贡献。）

The *note FTP_TLS: 1a7. class now accepts a `context' parameter, which
is a *note ssl.SSLContext: 4e9. object allowing bundling SSL
configuration options, certificates and private keys into a single
(potentially long-lived) structure.

（由 Giampaolo Rodolà 在 bpo-8806(3) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue4972‘贡献，由 Georg Brandl 在
:issue:‘8046

   (2) https://bugs.python.org/issue1286

   (3) https://bugs.python.org/issue8806


File: python.info,  Node: popen,  Next: select<3>,  Prev: ftp,  Up: 新增，改进和弃用的模块

1.8.9.17 popen
..............

The *note os.popen(): 3cb. and *note subprocess.Popen(): 3db. functions
now support *note with: 7da. statements for auto-closing of the file
descriptors.

（由 Antoine Pitrou 和 Brian Curtin 在 bpo-7461(1) 和 bpo-10554(2) 中贡
献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue7461

   (2) https://bugs.python.org/issue10554


File: python.info,  Node: select<3>,  Next: gzip 和 zipfile,  Prev: popen,  Up: 新增，改进和弃用的模块

1.8.9.18 select
...............

The *note select: e5. module now exposes a new, constant attribute,
*note PIPE_BUF: c57, which gives the minimum number of bytes which are
guaranteed not to block when *note select.select(): 766. says a pipe is
ready for writing.

     >>> import select
     >>> select.PIPE_BUF
     512

(Available on Unix systems.  Patch by Sébastien Sablé in bpo-9862(1))

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue9862


File: python.info,  Node: gzip 和 zipfile,  Next: tarfile<5>,  Prev: select<3>,  Up: 新增，改进和弃用的模块

1.8.9.19 gzip 和 zipfile
........................

*note gzip.GzipFile: 206. now implements the *note io.BufferedIOBase:
67f. *note abstract base class: c05. (except for ‘truncate()’).  It also
has a *note peek(): c59. method and supports unseekable as well as
zero-padded file objects.

The *note gzip: 8b. module also gains the *note compress(): 302. and
*note decompress(): c5a. functions for easier in-memory compression and
decompression.  Keep in mind that text needs to be encoded as *note
bytes: 172. before compressing and decompressing:

     >>> 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'

（由 Anand B. Pillai 在 bpo-3488(1) 中贡献，由Antoine Pitrou, Nir Aides
和 Brian Curtin 在 bpo-9962(2)，bpo-1675951(3) ，bpo-7471(4) 和
bpo-2846(5) 中贡献。）

Also, the ‘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 *note io.BufferedReader:
c5b. object for more speedups.  It also solves an issue where
interleaved calls to `read' and `readline' gave the wrong results.

(Patch submitted by Nir Aides in bpo-7610(6).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue3488

   (2) https://bugs.python.org/issue9962

   (3) https://bugs.python.org/issue1675951

   (4) https://bugs.python.org/issue7471

   (5) https://bugs.python.org/issue2846

   (6) https://bugs.python.org/issue7610


File: python.info,  Node: tarfile<5>,  Next: hashlib<4>,  Prev: gzip 和 zipfile,  Up: 新增，改进和弃用的模块

1.8.9.20 tarfile
................

The *note TarFile: c5d. class can now be used as a context manager.  In
addition, its *note add(): 57a. method has a new option, `filter', that
controls which files are added to the archive and allows the file
metadata to be edited.

The new `filter' option replaces the older, less flexible `exclude'
parameter which is now deprecated.  If specified, the optional `filter'
parameter needs to be a *note keyword argument: 6bb.  The user-supplied
filter function accepts a *note TarInfo: c5e. object and returns an
updated *note TarInfo: c5e. object, or if it wants the file to be
excluded, the function can return ‘None’:

     >>> 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

(Proposed by Tarek Ziadé and implemented by Lars Gustäbel in
bpo-6856(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue6856


File: python.info,  Node: hashlib<4>,  Next: ast<4>,  Prev: tarfile<5>,  Up: 新增，改进和弃用的模块

1.8.9.21 hashlib
................

The *note hashlib: 8c. module has two new constant attributes listing
the hashing algorithms guaranteed to be present in all implementations
and those available on the current implementation:

     >>> 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'}

（由 Carl Chenet 在 bpo-7418(1) 中建议。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue7418


File: python.info,  Node: ast<4>,  Next: os<9>,  Prev: hashlib<4>,  Up: 新增，改进和弃用的模块

1.8.9.22 ast
............

The *note ast: 7. module has a wonderful a general-purpose tool for
safely evaluating expression strings using the Python literal syntax.
The *note ast.literal_eval(): 59f. function serves as a secure
alternative to the builtin *note eval(): c61. function which is easily
abused.  Python 3.2 adds *note bytes: 172. and *note set: 1f6. literals
to the list of supported types: strings, bytes, numbers, tuples, lists,
dicts, sets, booleans, and ‘None’.

     >>> 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>

（由Benjamin Peterson 和 Georg Brandl 实现。）


File: python.info,  Node: os<9>,  Next: shutil<5>,  Prev: ast<4>,  Up: 新增，改进和弃用的模块

1.8.9.23 os
...........

Different operating systems use various encodings for filenames and
environment variables.  The *note os: c4. module provides two new
functions, *note fsencode(): 5e9. and *note fsdecode(): 5e8, for
encoding and decoding filenames:

     >>> import os
     >>> filename = 'Sehenswürdigkeiten'
     >>> os.fsencode(filename)
     b'Sehensw\xc3\xbcrdigkeiten'

Some operating systems allow direct access to encoded bytes in the
environment.  If so, the *note os.supports_bytes_environ: c63. constant
will be true.

For direct access to encoded environment variables (if available), use
the new *note os.getenvb(): c64. function or use *note os.environb: c65.
which is a bytes version of *note os.environ: c09.

（由 Victor Stinner 贡献。）


File: python.info,  Node: shutil<5>,  Next: sqlite3<6>,  Prev: os<9>,  Up: 新增，改进和弃用的模块

1.8.9.24 shutil
...............

The *note shutil.copytree(): 347. function has two new options:

   * `ignore_dangling_symlinks': when ‘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.

   * `copy_function': is a callable that will be used to copy files.
     *note shutil.copy2(): 384. is used by default.

（由 Tarek Ziadé 贡献。）

In addition, the *note shutil: e9. module now supports *note archiving
operations: c67. 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 *note make_archive(): 348. and *note
unpack_archive(): c68.  By default, both operate on the current
directory (which can be set by *note os.chdir(): 16e.) 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).

     >>> 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'
     ... )

（由 Tarek Ziadé 贡献。）


File: python.info,  Node: sqlite3<6>,  Next: html<3>,  Prev: shutil<5>,  Up: 新增，改进和弃用的模块

1.8.9.25 sqlite3
................

The *note sqlite3: f2. module was updated to pysqlite version 2.6.0.  It
has two new capabilities.

   * The ‘sqlite3.Connection.in_transit’ attribute is true if there is
     an active transaction for uncommitted changes.

   * The *note sqlite3.Connection.enable_load_extension(): c6a. and
     *note sqlite3.Connection.load_extension(): c6b. methods allows you
     to load SQLite extensions from ".so" files.  One well-known
     extension is the fulltext-search extension distributed with SQLite.

（由 R. David Murray 和 Shashwat Anand 在 bpo-8845(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue8845


File: python.info,  Node: html<3>,  Next: socket<9>,  Prev: sqlite3<6>,  Up: 新增，改进和弃用的模块

1.8.9.26 html
.............

A new *note html: 8f. module was introduced with only a single function,
*note escape(): a18, which is used for escaping reserved characters from
HTML markup:

     >>> import html
     >>> html.escape('x > 2 && x < 7')
     'x &gt; 2 &amp;&amp; x &lt; 7'


File: python.info,  Node: socket<9>,  Next: ssl<9>,  Prev: html<3>,  Up: 新增，改进和弃用的模块

1.8.9.27 socket
...............

The *note socket: ef. module has two new improvements.

   * Socket objects now have a *note detach(): c6e. 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(1).)

   * *note socket.create_connection(): c6f. now supports the context
     management protocol to unconditionally consume *note socket.error:
     a76. exceptions and to close the socket when done.  (Contributed by
     Giampaolo Rodolà; bpo-9794(2).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue8524

   (2) https://bugs.python.org/issue9794


File: python.info,  Node: ssl<9>,  Next: nntp,  Prev: socket<9>,  Up: 新增，改进和弃用的模块

1.8.9.28 ssl
............

The *note ssl: f3. module added a number of features to satisfy common
requirements for secure (encrypted, authenticated) internet connections:

   * A new class, *note SSLContext: 4e9, serves as a container for
     persistent SSL data, such as protocol settings, certificates,
     private keys, and various other options.  It includes a *note
     wrap_socket(): 4ea. for creating an SSL socket from an SSL context.

   * A new function, *note ssl.match_hostname(): 4e2, supports server
     identity verification for higher-level protocols by implementing
     the rules of HTTPS (from RFC 2818(1)) which are also suitable for
     other protocols.

   * The *note ssl.wrap_socket(): 570. constructor function now takes a
     `ciphers' argument.  The `ciphers' string lists the allowed
     encryption algorithms using the format described in the OpenSSL
     documentation(2).

   * When linked against recent versions of OpenSSL, the *note ssl: f3.
     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 `server_hostname'
     argument to *note ssl.SSLContext.wrap_socket(): 4ea.

   * Various options have been added to the *note ssl: f3. module, such
     as *note OP_NO_SSLv2: c71. which disables the insecure and obsolete
     SSLv2 protocol.

   * 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.

   * The version of OpenSSL being used is now accessible using the
     module attributes *note ssl.OPENSSL_VERSION: c72. (a string), *note
     ssl.OPENSSL_VERSION_INFO: c73. (a 5-tuple), and *note
     ssl.OPENSSL_VERSION_NUMBER: c74. (an integer).

（由 Antoine Pitrou 在 bpo-8850(3), bpo-1589(4), bpo-8322(5),
bpo-5639(6), bpo-4870(7), bpo-8484(8) 和 bpo-8321(9) 中贡献。）

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2818.html

   (2) 
https://www.openssl.org/docs/manmaster/man1/ciphers.html#CIPHER-LIST-FORMAT

   (3) https://bugs.python.org/issue8850

   (4) https://bugs.python.org/issue1589

   (5) https://bugs.python.org/issue8322

   (6) https://bugs.python.org/issue5639

   (7) https://bugs.python.org/issue4870

   (8) https://bugs.python.org/issue8484

   (9) https://bugs.python.org/issue8321


File: python.info,  Node: nntp,  Next: certificates,  Prev: ssl<9>,  Up: 新增，改进和弃用的模块

1.8.9.29 nntp
.............

The *note nntplib: c0. 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 *note
nntplib.NNTP_SSL: 1c7.) and explicit (using *note
nntplib.NNTP.starttls(): c76.) TLS has also been added.

（由 Antoine Pitrou 在 bpo-9360(1) 中贡献，由 Andrew Vant 在 bpo-1926(2)
中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue9360

   (2) https://bugs.python.org/issue1926


File: python.info,  Node: certificates,  Next: imaplib<4>,  Prev: nntp,  Up: 新增，改进和弃用的模块

1.8.9.30 certificates
.....................

*note http.client.HTTPSConnection: 499, *note
urllib.request.HTTPSHandler: c78. and *note urllib.request.urlopen():
87b. now take optional arguments to allow for server certificate
checking against a set of Certificate Authorities, as recommended in
public uses of HTTPS.

(Added by Antoine Pitrou, bpo-9003(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue9003


File: python.info,  Node: imaplib<4>,  Next: http client<4>,  Prev: certificates,  Up: 新增，改进和弃用的模块

1.8.9.31 imaplib
................

Support for explicit TLS on standard IMAP4 connections has been added
through the new *note imaplib.IMAP4.starttls: c7a. method.

（由 Lorenzo M. Catucci 和 Antoine Pitrou 在 bpo-4471(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue4471


File: python.info,  Node: http client<4>,  Next: unittest<6>,  Prev: imaplib<4>,  Up: 新增，改进和弃用的模块

1.8.9.32 http.client
....................

There were a number of small API improvements in the *note http.client:
93. module.  The old-style HTTP 0.9 simple responses are no longer
supported and the `strict' parameter is deprecated in all classes.

The *note HTTPConnection: 498. and *note HTTPSConnection: 499. classes
now have a `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
*note HTTPSConnection: 499.

The *note request(): 649. method on connection objects allowed an
optional `body' argument so that a *note file object: c14. could be used
to supply the content of the request.  Conveniently, the `body' argument
now also accepts an *note iterable: c7c. object so long as it includes
an explicit ‘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
*note set_tunnel(): c7d. method that sets the host and port for HTTP
Connect tunneling.

To match the behavior of *note http.server: 96, 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(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10980


File: python.info,  Node: unittest<6>,  Next: random<3>,  Prev: http client<4>,  Up: 新增，改进和弃用的模块

1.8.9.33 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.

   * The command-line call ‘python -m unittest’ can now accept file
     paths instead of module names for running specific tests
     (bpo-10620(1)).  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 ‘-t’
     option, a pattern for matching files with ‘-p’, and a directory to
     start discovery with ‘-s’:

          $ python -m unittest discover -s my_proj_dir -p _test.py

     （由 Michael Foord 贡献）

   * Experimentation at the interactive prompt is now easier because the
     ‘unittest.case.TestCase’ class can now be instantiated without
     arguments:

          >>> from unittest import TestCase
          >>> TestCase().assertEqual(pow(2, 3), 8)

     （由 Michael Foord 贡献）

   * The *note unittest: 124. module has two new methods, *note
     assertWarns(): b94. and *note assertWarnsRegex(): b95. to verify
     that a given warning type is triggered by the code under test:

          with self.assertWarns(DeprecationWarning):
              legacy_function('XYZ')

     （由 Antoine Pitrou 在 bpo-9754(2) 中贡献。）

     Another new method, *note assertCountEqual(): c7f. 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):

          def test_anagram(self):
              self.assertCountEqual('algorithm', 'logarithm')

     （由 Raymond Hettinger 贡献。）

   * 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
     *note maxDiff: c80. attribute that sets maximum length of diffs
     displayed.

   * In addition, the method names in the module have undergone a number
     of clean-ups.

     For example, *note assertRegex(): c81. is the new name for
     ‘assertRegexpMatches()’ which was misnamed because the test uses
     *note re.search(): c82, not *note re.match(): c83.  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 *note
     re: dd. module, and it has unambiguous camel-casing.

     （由 Raymond Hettinger 贡献并由 Ezio Melotti 实现。）

   * To improve consistency, some long-standing method aliases are being
     deprecated in favor of the preferred names:

          旧名称                              首选名称
                                              
          -----------------------------------------------------------------------
                                              
          ‘assert_()’                         *note assertTrue(): c84.
                                              
                                              
          ‘assertEquals()’                    *note assertEqual(): c85.
                                              
                                              
          ‘assertNotEquals()’                 *note assertNotEqual(): c86.
                                              
                                              
          ‘assertAlmostEquals()’              *note assertAlmostEqual(): c87.
                                              
                                              
          ‘assertNotAlmostEquals()’           *note assertNotAlmostEqual(): c88.
                                              

     Likewise, the ‘TestCase.fail*’ methods deprecated in Python 3.1 are
     expected to be removed in Python 3.3.  Also see the *note
     Deprecated aliases: c89. section in the *note unittest: 124.
     documentation.

     （由 Ezio Melotti 在 bpo-9424(3) 中贡献。）

   * The ‘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
     ‘TestCase().assertDictContainsSubset({'a':1, 'b':2}, {'a':1})’
     would fail.

     （由 Raymond Hettinger 贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10620

   (2) https://bugs.python.org/issue9754

   (3) https://bugs.python.org/issue9424


File: python.info,  Node: random<3>,  Next: poplib<4>,  Prev: unittest<6>,  Up: 新增，改进和弃用的模块

1.8.9.34 random
...............

The integer methods in the *note random: dc. module now do a better job
of producing uniform distributions.  Previously, they computed
selections with ‘int(n*random())’ which had a slight bias whenever `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 ‘0 <= x < n’.  The functions and methods affected are
*note randrange(): c8b, *note randint(): c8c, *note choice(): c8d, *note
shuffle(): 212. and *note sample(): c8e.

（由 Raymond Hettinger 在 bpo-9025(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue9025


File: python.info,  Node: poplib<4>,  Next: asyncore<2>,  Prev: random<3>,  Up: 新增，改进和弃用的模块

1.8.9.35 poplib
...............

*note POP3_SSL: 1d6. class now accepts a `context' parameter, which is a
*note ssl.SSLContext: 4e9. object allowing bundling SSL configuration
options, certificates and private keys into a single (potentially
long-lived) structure.

（由 Giampaolo Rodolà 在 bpo-8807(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue8807


File: python.info,  Node: asyncore<2>,  Next: tempfile<2>,  Prev: poplib<4>,  Up: 新增，改进和弃用的模块

1.8.9.36 asyncore
.................

*note asyncore.dispatcher: c91. now provides a *note handle_accepted():
c92. method returning a ‘(sock, 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 *note
handle_accept(): c93. and avoids the user to call *note accept(): c94.
directly.

（由 Giampaolo Rodolà 在 bpo-6706(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue6706


File: python.info,  Node: tempfile<2>,  Next: inspect<7>,  Prev: asyncore<2>,  Up: 新增，改进和弃用的模块

1.8.9.37 tempfile
.................

The *note tempfile: 103. module has a new context manager, *note
TemporaryDirectory: c96. which provides easy deterministic cleanup of
temporary directories:

     with tempfile.TemporaryDirectory() as tmpdirname:
         print('created temporary dir:', tmpdirname)

（由 Neil Schemenauer 和 Nick Coghlan 在 bpo-5178(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5178


File: python.info,  Node: inspect<7>,  Next: pydoc<6>,  Prev: tempfile<2>,  Up: 新增，改进和弃用的模块

1.8.9.38 inspect
................

   * The *note inspect: a0. module has a new function *note
     getgeneratorstate(): c98. to easily identify the current state of a
     generator-iterator:

          >>> 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'

     （由 Rodolpho Eckhardt 和 Nick Coghlan 在 bpo-10220(1) 中贡献。）

   * To support lookups without the possibility of activating a dynamic
     attribute, the *note inspect: a0. module has a new function, *note
     getattr_static(): c99.  Unlike *note hasattr(): 54a, this is a true
     read-only search, guaranteed not to change state while it is
     searching:

          >>> 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>

     （由 Michael Foord 贡献）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10220


File: python.info,  Node: pydoc<6>,  Next: dis<3>,  Prev: inspect<7>,  Up: 新增，改进和弃用的模块

1.8.9.39 pydoc
..............

The *note pydoc: d9. module now provides a much-improved Web server
interface, as well as a new command-line option ‘-b’ to automatically
open a browser window to display that server:

     $ pydoc3.2 -b

（由 Ron Adam 在 bpo-2001(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue2001


File: python.info,  Node: dis<3>,  Next: dbm<6>,  Prev: pydoc<6>,  Up: 新增，改进和弃用的模块

1.8.9.40 dis
............

The *note dis: 37. module gained two new functions for inspecting code,
*note code_info(): c9c. and *note show_code(): 91f.  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:

     >>> 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

In addition, the *note dis(): 48a. function now accepts string arguments
so that the common idiom ‘dis(compile(s, '', 'eval'))’ can be shortened
to ‘dis(s)’:

     >>> 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

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(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue9147


File: python.info,  Node: dbm<6>,  Next: ctypes<2>,  Prev: dis<3>,  Up: 新增，改进和弃用的模块

1.8.9.41 dbm
............

All database modules now support the ‘get()’ and ‘setdefault()’ methods.

（由 Ray Allen 在 bpo-9523(1) 中建议。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue9523


File: python.info,  Node: ctypes<2>,  Next: site<2>,  Prev: dbm<6>,  Up: 新增，改进和弃用的模块

1.8.9.42 ctypes
...............

A new type, *note ctypes.c_ssize_t: c9f. represents the C ‘ssize_t’
datatype.


File: python.info,  Node: site<2>,  Next: sysconfig<2>,  Prev: ctypes<2>,  Up: 新增，改进和弃用的模块

1.8.9.43 site
.............

The *note site: eb. module has three new functions useful for reporting
on the details of a given Python installation.

   * *note getsitepackages(): ca1. lists all global site-packages
     directories.

   * *note getuserbase(): ca2. reports on the user’s base directory
     where data can be stored.

   * *note getusersitepackages(): ca3. reveals the user-specific
     site-packages directory path.

     >>> 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'

Conveniently, some of site’s functionality is accessible directly from
the command-line:

     $ python -m site --user-base
     /Users/raymondhettinger/.local
     $ python -m site --user-site
     /Users/raymondhettinger/.local/lib/python3.2/site-packages

（由 Tarek Ziadé 在 bpo-6693(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue6693


File: python.info,  Node: sysconfig<2>,  Next: pdb<6>,  Prev: site<2>,  Up: 新增，改进和弃用的模块

1.8.9.44 sysconfig
..................

The new *note sysconfig: fe. 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:

   * *note get_platform(): ca5. returning values like `linux-i586' or
     `macosx-10.6-ppc'.

   * *note get_python_version(): ca6. returns a Python version string
     such as "3.2".

It also provides access to the paths and variables corresponding to one
of seven named schemes used by *note distutils: 38.  Those include
`posix_prefix', `posix_home', `posix_user', `nt', `nt_user', `os2',
`os2_home':

   * *note get_paths(): ca7. makes a dictionary containing installation
     paths for the current installation scheme.

   * *note get_config_vars(): a46. returns a dictionary of platform
     specific variables.

还有一个方便的命令行界面：

     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"

（由TarekZiadé 移出Distutils。）


File: python.info,  Node: pdb<6>,  Next: configparser<2>,  Prev: sysconfig<2>,  Up: 新增，改进和弃用的模块

1.8.9.45 pdb
............

The *note pdb: c9. debugger module gained a number of usability
improvements:

   * ‘pdb.py’ now has a ‘-c’ option that executes commands as given in a
     ‘.pdbrc’ script file.

   * A ‘.pdbrc’ script file can contain ‘continue’ and ‘next’ commands
     that continue debugging.

   * The ‘Pdb’ class constructor now accepts a `nosigint' argument.

   * New commands: ‘l(list)’, ‘ll(long list)’ and ‘source’ for listing
     source code.

   * New commands: ‘display’ and ‘undisplay’ for showing or hiding the
     value of an expression if it has changed.

   * New command: ‘interact’ for starting an interactive interpreter
     containing the global and local names found in the current scope.

   * Breakpoints can be cleared by breakpoint number.

（由Georg Brandl, Antonio Cuni 和 Ilya Sandler 贡献。）


File: python.info,  Node: configparser<2>,  Next: urllib parse<4>,  Prev: pdb<6>,  Up: 新增，改进和弃用的模块

1.8.9.46 configparser
.....................

The *note configparser: 22. module was modified to improve usability and
predictability of the default parser and its supported INI syntax.  The
old ‘ConfigParser’ class was removed in favor of ‘SafeConfigParser’
which has in turn been renamed to *note ConfigParser: 5a4.  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:

     >>> 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)'

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 `DEFAULT' section or switch the
interpolation syntax.

There is support for pluggable interpolation including an additional
interpolation handler *note ExtendedInterpolation: caa.:

     >>> 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'

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.

(All changes contributed by Łukasz Langa.)


File: python.info,  Node: urllib parse<4>,  Next: mailbox,  Prev: configparser<2>,  Up: 新增，改进和弃用的模块

1.8.9.47 urllib.parse
.....................

A number of usability improvements were made for the *note urllib.parse:
128. module.

The *note urlparse(): 6f1. function now supports IPv6(1) addresses as
described in RFC 2732(2):

     >>> 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='',
                 query='',
                 fragment='')

The *note urldefrag(): cac. function now returns a *note named tuple:
b7b.:

     >>> 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'

And, the *note urlencode(): 87a. function is now much more flexible,
accepting either a string or bytes type for the `query' argument.  If it
is a string, then the `safe', `encoding', and `error' parameters are
sent to *note quote_plus(): cad. for encoding:

     >>> urllib.parse.urlencode([
     ...      ('type', 'telenovela'),
     ...      ('name', '¿Dónde Está Elisa?')],
     ...      encoding='latin-1')
     'type=telenovela&name=%BFD%F3nde+Est%E1+Elisa%3F'

As detailed in *note 解析ASCII编码字节: cae, all the *note urllib.parse:
128. 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:

     >>> 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'', query=b'', fragment=b'')

(Work by Nick Coghlan, Dan Mahn, and Senthil Kumaran in bpo-2987(3),
bpo-5468(4), and bpo-9873(5).)

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/IPv6

   (2) https://tools.ietf.org/html/rfc2732.html

   (3) https://bugs.python.org/issue2987

   (4) https://bugs.python.org/issue5468

   (5) https://bugs.python.org/issue9873


File: python.info,  Node: mailbox,  Next: turtledemo,  Prev: urllib parse<4>,  Up: 新增，改进和弃用的模块

1.8.9.48 mailbox
................

Thanks to a concerted effort by R. David Murray, the *note mailbox: ae.
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 *note bytes: 172. because various parts of a
message may have different encodings.

The solution harnessed the *note email: 67. package’s binary support for
parsing arbitrary email messages.  In addition, the solution required a
number of API changes.

As expected, the *note add(): cb0. method for *note mailbox.Mailbox:
cb1. objects now accepts binary input.

*note StringIO: 91a. 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 *note get_file(): cb2.
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 *note
get_bytes(): cb3. method that returns a *note bytes: 172. representation
of a message corresponding to a given `key'.

It is still possible to get non-binary output using the old API’s *note
get_string(): cb4. method, but that approach is not very useful.
Instead, it is best to extract messages from a *note Message: cb5.
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(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue9124


File: python.info,  Node: turtledemo,  Prev: mailbox,  Up: 新增，改进和弃用的模块

1.8.9.49 turtledemo
...................

The demonstration code for the *note turtle: 11f. module was moved from
the `Demo' directory to main library.  It includes over a dozen sample
scripts with lively displays.  Being on *note sys.path: 261, it can now
be run directly from the command-line:

     $ python -m turtledemo

(Moved from the Demo directory by Alexander Belopolsky in bpo-10199(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10199


File: python.info,  Node: 多线程,  Next: 性能优化<7>,  Prev: 新增，改进和弃用的模块,  Up: Python 3 2 有什么新变化

1.8.10 多线程
-------------

   * The mechanism for serializing execution of concurrently running
     Python threads (generally known as the *note GIL: 20e. 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 *note sys.setswitchinterval(): 218.
     It currently defaults to 5 milliseconds.

     Additional details about the implementation can be read from a
     python-dev mailing-list message(1) (however, "priority requests" as
     exposed in this message have not been kept for inclusion).

     （由 Antoine Pitrou 贡献。）

   * Regular and recursive locks now accept an optional `timeout'
     argument to their *note acquire(): 85b. method.  (Contributed by
     Antoine Pitrou; bpo-7316(2).)

   * Similarly, *note threading.Semaphore.acquire(): cb8. also gained a
     `timeout' argument.  (Contributed by Torsten Landschoff;
     bpo-850728(3).)

   * 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
     ‘Ctrl+C’ in most shells).  (Contributed by Reid Kleckner;
     bpo-8844(4).)

   ---------- Footnotes ----------

   (1) 
https://mail.python.org/pipermail/python-dev/2009-October/093321.html

   (2) https://bugs.python.org/issue7316

   (3) https://bugs.python.org/issue850728

   (4) https://bugs.python.org/issue8844


File: python.info,  Node: 性能优化<7>,  Next: Unicode,  Prev: 多线程,  Up: Python 3 2 有什么新变化

1.8.11 性能优化
---------------

A number of small performance enhancements have been added:

   * Python’s peephole optimizer now recognizes patterns such ‘x in {1,
     2, 3}’ as being a test for membership in a set of constants.  The
     optimizer recasts the *note set: 1f6. as a *note frozenset: 1f7.
     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:

          extension = name.rpartition('.')[2]
          if extension in {'xml', 'html', 'xhtml', 'css'}:
              handle(name)

     (Patch and additional tests contributed by Dave Malcolm;
     bpo-6690(1)).

   * Serializing and unserializing data using the *note pickle: ca.
     module is now several times faster.

     （由 Alexandre Vassalotti, Antoine Pitrou 和 Unladen Swallow 团队在
     bpo-9410(2) 和 bpo-3873(3) 中贡献。）

   * The Timsort algorithm(4) used in *note list.sort(): 547. and *note
     sorted(): 546. now runs faster and uses less memory when called
     with a *note key function: 7d2.  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(5).)

   * 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 ‘sort_keys’
     argument is true.

     （由Antoine Pitrou 在 bpo-7451(6) 中贡献，由 Raymond Hettinger 和
     Antoine Pitrou 在 bpo-10314(7) 中贡献。）

   * Recursive locks (created with the *note threading.RLock(): cba.
     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(8) 中贡献。）

   * The fast-search algorithm in stringlib is now used by the
     ‘split()’, ‘rsplit()’, ‘splitlines()’ and ‘replace()’ methods on
     *note bytes: 172, *note bytearray: 173. and *note str: 205.
     objects.  Likewise, the algorithm is also used by ‘rfind()’,
     ‘rindex()’, ‘rsplit()’ and ‘rpartition()’.

     (Patch by Florent Xicluna in bpo-7622(9) and bpo-7462(10).)

   * Integer to string conversions now work two "digits" at a time,
     reducing the number of division and modulo operations.

     (bpo-6713(11) by Gawain Bolton, Mark Dickinson, and Victor
     Stinner.)

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(12)).  The ‘array.repeat()’ method has a faster
implementation (bpo-1569291(13) by Alexander Belopolsky).  The
‘BaseHTTPRequestHandler’ has more efficient buffering (bpo-3709(14) by
Andrew Schaaf).  The *note operator.attrgetter(): 80a. function has been
sped-up (bpo-10160(15) by Christos Georgiou).  And ‘ConfigParser’ loads
multi-line arguments a bit faster (bpo-7113(16) by Łukasz Langa).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue6690

   (2) https://bugs.python.org/issue9410

   (3) https://bugs.python.org/issue3873

   (4) https://en.wikipedia.org/wiki/Timsort

   (5) https://bugs.python.org/issue9915

   (6) https://bugs.python.org/issue7451

   (7) https://bugs.python.org/issue10314

   (8) https://bugs.python.org/issue3001

   (9) https://bugs.python.org/issue7622

   (10) https://bugs.python.org/issue7462

   (11) https://bugs.python.org/issue6713

   (12) https://bugs.python.org/issue8685

   (13) https://bugs.python.org/issue1569291

   (14) https://bugs.python.org/issue3709

   (15) https://bugs.python.org/issue10160

   (16) https://bugs.python.org/issue7113


File: python.info,  Node: Unicode,  Next: 编解码器,  Prev: 性能优化<7>,  Up: Python 3 2 有什么新变化

1.8.12 Unicode
--------------

Python has been updated to Unicode 6.0.0(1).  The update to the standard
adds over 2,000 new characters including emoji(2) 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(3).

   ---------- Footnotes ----------

   (1) http://unicode.org/versions/Unicode6.0.0/

   (2) https://en.wikipedia.org/wiki/Emoji

   (3) http://www.unicode.org/versions/Unicode6.0.0/#Database_Changes


File: python.info,  Node: 编解码器,  Next: 文档,  Prev: Unicode,  Up: Python 3 2 有什么新变化

1.8.13 编解码器
---------------

Support was added for `cp720' Arabic DOS encoding (bpo-1616979(1)).

MBCS encoding no longer ignores the error handler argument.  In the
default strict mode, it raises an *note UnicodeDecodeError: 32b. when it
encounters an undecodable byte sequence and an *note UnicodeEncodeError:
32a. for an unencodable character.

The MBCS codec supports ‘'strict'’ and ‘'ignore'’ error handlers for
decoding, and ‘'strict'’ and ‘'replace'’ for encoding.

To emulate Python3.1 MBCS encoding, select the ‘'ignore'’ handler for
decoding and the ‘'replace'’ handler for encoding.

On Mac OS X, Python decodes command line arguments with ‘'utf-8'’ rather
than the locale encoding.

By default, *note tarfile: 101. uses ‘'utf-8'’ encoding on Windows
(instead of ‘'mbcs'’) and the ‘'surrogateescape'’ error handler on all
operating systems.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1616979


File: python.info,  Node: 文档,  Next: IDLE,  Prev: 编解码器,  Up: Python 3 2 有什么新变化

1.8.14 文档
-----------

The documentation continues to be improved.

   * A table of quick links has been added to the top of lengthy
     sections such as *note 內建函式: cbe.  In the case of *note
     itertools: a3, 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.

   * 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 *note
     functools: 83. module documentation has a quick link at the top
     labeled:

          `源代码' Lib/functools.py(1).

     （由 Raymond Hettinger 贡献，参见 rationale(2)。）

   * The docs now contain more examples and recipes.  In particular,
     *note re: dd. module has an extensive section, *note
     正则表达式例子: cbf.  Likewise, the *note itertools: a3. module
     continues to be updated with new *note itertools 配方: cc0.

   * The *note datetime: 30. 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(3) 中贡献。）

   * The unmaintained ‘Demo’ directory has been removed.  Some demos
     were integrated into the documentation, some were moved to the
     ‘Tools/demo’ directory, and others were removed altogether.

     （由 Georg Brandl 在 bpo-7962(4) 中贡献）

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/functools.py

   (2) 
https://rhettinger.wordpress.com/2011/01/28/open-your-source-more/

   (3) https://bugs.python.org/issue9528

   (4) https://bugs.python.org/issue7962


File: python.info,  Node: IDLE,  Next: 代码库,  Prev: 文档,  Up: Python 3 2 有什么新变化

1.8.15 IDLE
-----------

   * The format menu now has an option to clean source files by
     stripping trailing whitespace.

     （由 Raymond Hettinger 在 bpo-5150(1) 中贡献。）

   * IDLE on Mac OS X now works with both Carbon AquaTk and Cocoa
     AquaTk.

     （由 Kevin Walzer, Ned Deily 和 Ronald Oussoren 在 bpo-6075(2) 中贡
     献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5150

   (2) https://bugs.python.org/issue6075


File: python.info,  Node: 代码库,  Next: 构建和 C API 的改变<5>,  Prev: IDLE,  Up: Python 3 2 有什么新变化

1.8.16 代码库
-------------

In addition to the existing Subversion code repository at
‘http://svn.python.org’ there is now a Mercurial(1) repository at
‘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 PEP 385(2) for details.

To learn to use the new version control system, see the Quick Start(3)
or the Guide to Mercurial Workflows(4).

   ---------- Footnotes ----------

   (1) https://www.mercurial-scm.org/

   (2) https://www.python.org/dev/peps/pep-0385

   (3) https://www.mercurial-scm.org/wiki/QuickStart

   (4) https://www.mercurial-scm.org/guide


File: python.info,  Node: 构建和 C API 的改变<5>,  Next: 移植到 Python 3 2,  Prev: 代码库,  Up: Python 3 2 有什么新变化

1.8.17 构建和 C API 的改变
--------------------------

Changes to Python’s build process and to the C API include:

   * The `idle', `pydoc' and `2to3' scripts are now installed with a
     version-specific suffix on ‘make altinstall’ (bpo-10679(1)).

   * 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 *note
     unicodedata.numeric(): cc4. now returns the correct value for large
     code points, and *note repr(): 8b9. may consider more characters as
     printable.

     (Reported by Bupjoe Lee and fixed by Amaury Forgeot D’Arc;
     bpo-5127(2).)

   * 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 ‘--without-computed-gotos’.

     （由 Antoine Pitrou 在 bpo-9203(3) 中贡献。）

   * The option ‘--with-wctype-functions’ was removed.  The built-in
     unicode database is now used for all functions.

     （由 Amaury Forgeot d’Arc 在 bpo-9210(4) 中贡献。）

   * Hash values are now values of a new type, ‘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, *note set: 1f6. and *note
     dict: 164. can now hold more than ‘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(5).)

   * A new macro ‘Py_VA_COPY’ copies the state of the variable argument
     list.  It is equivalent to C99 `va_copy' but available on all
     Python platforms (bpo-2443(6)).

   * A new C API function *note PySys_SetArgvEx(): cc5. allows an
     embedded interpreter to set *note sys.argv: cc6. without also
     modifying *note sys.path: 261. (bpo-5753(7)).

   * ‘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(8)).

   * There is a new function *note PyLong_AsLongLongAndOverflow(): cc7.
     which is analogous to *note PyLong_AsLongAndOverflow(): cc8.  They
     both serve to convert Python *note int: 204. into a native
     fixed-width type while providing detection of cases where the
     conversion won’t fit (bpo-7767(9)).

   * The *note PyUnicode_CompareWithASCIIString(): cc9. function now
     returns `not equal' if the Python string is `NUL' terminated.

   * There is a new function *note PyErr_NewExceptionWithDoc(): cca.
     that is like *note PyErr_NewException(): ccb. but allows a
     docstring to be specified.  This lets C exceptions have the same
     self-documenting capabilities as their pure Python counterparts
     (bpo-7033(10)).

   * When compiled with the ‘--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(11)).

   * Removed the ‘O?’ format from the `PyArg_Parse' functions.  The
     format is no longer used and it had never been documented
     (bpo-8837(12)).

There were a number of other small changes to the C-API. See the
Misc/NEWS(13) file for a complete list.

Also, there were a number of updates to the Mac OS X build, see
Mac/BuildScript/README.txt(14) 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(15).  See
‘https://www.python.org/download/mac/tcltk/’ for additional details.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10679

   (2) https://bugs.python.org/issue5127

   (3) https://bugs.python.org/issue9203

   (4) https://bugs.python.org/issue9210

   (5) https://bugs.python.org/issue9778

   (6) https://bugs.python.org/issue2443

   (7) https://bugs.python.org/issue5753

   (8) https://bugs.python.org/issue8276

   (9) https://bugs.python.org/issue7767

   (10) https://bugs.python.org/issue7033

   (11) https://bugs.python.org/issue2422

   (12) https://bugs.python.org/issue8837

   (13) https://github.com/python/cpython/tree/3.9/Misc/NEWS

   (14) 
https://github.com/python/cpython/tree/3.9/Mac/BuildScript/README.txt

   (15) https://www.activestate.com/activetcl/downloads


File: python.info,  Node: 移植到 Python 3 2,  Prev: 构建和 C API 的改变<5>,  Up: Python 3 2 有什么新变化

1.8.18 移植到 Python 3.2
------------------------

This section lists previously described changes and other bugfixes that
may require changes to your code:

   * The *note configparser: 22. module has a number of clean-ups.  The
     major change is to replace the old ‘ConfigParser’ class with
     long-standing preferred alternative ‘SafeConfigParser’.  In
     addition there are a number of smaller incompatibilities:

        * The interpolation syntax is now validated on *note get(): ccd.
          and *note set(): cce. operations.  In the default
          interpolation scheme, only two tokens with percent signs are
          valid: ‘%(name)s’ and ‘%%’, the latter being an escaped
          percent sign.

        * The *note set(): cce. and *note add_section(): ccf. methods
          now verify that values are actual strings.  Formerly,
          unsupported types could be introduced unintentionally.

        * Duplicate sections or options from a single source now raise
          either *note DuplicateSectionError: cd0. or *note
          DuplicateOptionError: cd1.  Formerly, duplicates would
          silently overwrite a previous entry.

        * Inline comments are now disabled by default so now the `;'
          character can be safely used in values.

        * Comments now can be indented.  Consequently, for `;' or `#' 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.

        * ‘""’ is now a valid value and is no longer automatically
          converted to an empty string.  For empty strings, use ‘"option
          ="’ in a line.

   * The *note nntplib: c0. module was reworked extensively, meaning
     that its APIs are often incompatible with the 3.1 APIs.

   * *note bytearray: 173. objects can no longer be used as filenames;
     instead, they should be converted to *note bytes: 172.

   * The ‘array.tostring()’ and ‘array.fromstring()’ have been renamed
     to ‘array.tobytes()’ and ‘array.frombytes()’ for clarity.  The old
     names have been deprecated.  (See bpo-8990(1).)

   * ‘PyArg_Parse*()’ 函数:

        * "t#" format has been removed: use "s#" or "s*" instead

        * "w" and "w#" formats has been removed: use "w*" instead

   * The ‘PyCObject’ type, deprecated in 3.1, has been removed.  To wrap
     opaque C pointers in Python objects, the *note PyCapsule: cd2. 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.

   * The ‘sys.setfilesystemencoding()’ function was removed because it
     had a flawed design.

   * The *note random.seed(): cd3. function and method now salt string
     seeds with an sha512 hash function.  To access the previous version
     of `seed' in order to reproduce Python 3.1 sequences, set the
     `version' argument to `1', ‘random.seed(s, version=1)’.

   * The previously deprecated ‘string.maketrans()’ function has been
     removed in favor of the static methods *note bytes.maketrans():
     cd4. and *note bytearray.maketrans(): cd5.  This change solves the
     confusion around which types were supported by the *note string:
     f6. module.  Now, *note str: 205, *note bytes: 172, and *note
     bytearray: 173. each have their own `maketrans' and `translate'
     methods with intermediate translation tables of the appropriate
     type.

     （由Georg Brandl在 bpo-5675(2) 中贡献）

   * The previously deprecated ‘contextlib.nested()’ function has been
     removed in favor of a plain *note with: 7da. 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:

          with open('mylog.txt') as infile, open('a.out', 'w') as outfile:
              for line in infile:
                  if '<critical>' in line:
                      outfile.write(line)

     (Contributed by Georg Brandl and Mattias Brändström; appspot issue
     53094(3).)

   * *note struct.pack(): cd6. now only allows bytes for the ‘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 ‘struct.pack('<6sHHBBB', 'GIF87a', x, y)’ should be
     rewritten with to use bytes instead of text,
     ‘struct.pack('<6sHHBBB', b'GIF87a', x, y)’.

     (Discovered by David Beazley and fixed by Victor Stinner;
     bpo-10783(4).)

   * The *note xml.etree.ElementTree: 140. class now raises an *note
     xml.etree.ElementTree.ParseError: cd7. when a parse fails.
     Previously it raised an *note xml.parsers.expat.ExpatError: cd8.

   * The new, longer *note str(): 205. value on floats may break
     doctests which rely on the old output format.

   * In *note subprocess.Popen: 3db, the default value for `close_fds'
     is now ‘True’ under Unix; under Windows, it is ‘True’ if the three
     standard streams are set to ‘None’, ‘False’ otherwise.  Previously,
     `close_fds' was always ‘False’ by default, which produced difficult
     to solve bugs or race conditions when open file descriptors would
     leak into the child process.

   * Support for legacy HTTP 0.9 has been removed from *note
     urllib.request: 129. and *note http.client: 93.  Such support is
     still present on the server side (in *note http.server: 96.).

     （由 Antoine Pitrou 在 bpo-10711(5) 中贡献。）

   * SSL sockets in timeout mode now raise *note socket.timeout: cd9.
     when a timeout occurs, rather than a generic *note SSLError: cda.

     （由 Antoine Pitrou 在 bpo-10272(6) 中贡献。）

   * The misleading functions *note PyEval_AcquireLock(): 3d4. and *note
     PyEval_ReleaseLock(): cdb. have been officially deprecated.  The
     thread-state aware APIs (such as *note PyEval_SaveThread(): cdc.
     and *note PyEval_RestoreThread(): 3d6.) should be used instead.

   * Due to security risks, ‘asyncore.handle_accept()’ has been
     deprecated, and a new function, ‘asyncore.handle_accepted()’, was
     added to replace it.

     （由 Giampaolo Rodola 在 bpo-6706(7) 中贡献。）

   * Due to the new *note GIL: 20e. implementation, *note
     PyEval_InitThreads(): 20c. cannot be called before *note
     Py_Initialize(): 20f. anymore.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue8990

   (2) https://bugs.python.org/issue5675

   (3) https://codereview.appspot.com/53094

   (4) https://bugs.python.org/issue10783

   (5) https://bugs.python.org/issue10711

   (6) https://bugs.python.org/issue10272

   (7) https://bugs.python.org/issue6706


File: python.info,  Node: Python 3 1 有什么新变化,  Next: Python 3 0 有什么新变化,  Prev: Python 3 2 有什么新变化,  Up: Python 有什麼新功能？

1.9 Python 3.1 有什么新变化
===========================


作者: Raymond Hettinger

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.


File: python.info,  Node: PEP 372 有序字典,  Next: PEP 378 千位分隔符的格式说明符,  Up: Python 3 1 有什么新变化

1.9.1 PEP 372: 有序字典
-----------------------

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, a new
*note collections.OrderedDict: 2ea. class has been introduced.

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 *note configparser: 22. module uses them by default.  This
lets configuration files be read, modified, and then written back in
their original order.  The `_asdict()' method for *note
collections.namedtuple(): 1a1. now returns an ordered dictionary with
the values appearing in the same order as the underlying tuple indices.
The *note json: a4. module is being built-out with an
`object_pairs_hook' to allow OrderedDicts to be built by the decoder.
Support was also added for third-party tools like PyYAML(1).

也參考
......

PEP 372(2) - 有序字典

     PEP 由 Armin Ronacher 和 Raymond Hettinger 撰写，由 Raymond
     Hettinger 实现。

   ---------- Footnotes ----------

   (1) http://pyyaml.org/

   (2) https://www.python.org/dev/peps/pep-0372


File: python.info,  Node: PEP 378 千位分隔符的格式说明符,  Next: 其他语言特性修改<9>,  Prev: PEP 372 有序字典,  Up: Python 3 1 有什么新变化

1.9.2 PEP 378: 千位分隔符的格式说明符
-------------------------------------

The built-in *note format(): 5d5. function and the *note str.format():
5d4. 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:

     >>> 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'

The supported types are *note int: 204, *note float: 1fd, *note complex:
2c1. and *note decimal.Decimal: 2c0.

Discussions are underway about how to specify alternative separators
like dots, spaces, apostrophes, or underscores.  Locale-aware
applications should use the existing `n' format specifier which already
has some support for thousands separators.

也參考
......

PEP 378(1) - 千位分隔符的格式说明符

     PEP 由 Raymond Hettinger 撰写，并由 Eric Smith 和 Mark Dickinson 实
     现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0378


File: python.info,  Node: 其他语言特性修改<9>,  Next: 新增，改进和弃用的模块<2>,  Prev: PEP 378 千位分隔符的格式说明符,  Up: Python 3 1 有什么新变化

1.9.3 其他语言特性修改
----------------------

对Python 语言核心进行的小改动：

   * Directories and zip archives containing a ‘__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(1).)

   * The *note int(): 204. type gained a ‘bit_length’ method that
     returns the number of bits necessary to represent its argument in
     binary:

          >>> n = 37
          >>> bin(37)
          '0b100101'
          >>> n.bit_length()
          6
          >>> n = 2**123-1
          >>> n.bit_length()
          123
          >>> (n+1).bit_length()
          124

     （由 Fredrik Johansson, Victor Stinner, Raymond Hettinger 和 Mark
     Dickinson 在 bpo-3439(2) 中贡献。）

   * The fields in *note format(): 5d5. strings can now be automatically
     numbered:

          >>> 'Sir {} of {}'.format('Gallahad', 'Camelot')
          'Sir Gallahad of Camelot'

     Formerly, the string would have required numbered fields such as:
     ‘'Sir {0} of {1}'’.

     （由 Eric Smith在 bpo-5237(3) 中贡献）

   * The ‘string.maketrans()’ function is deprecated and is replaced by
     new static methods, *note bytes.maketrans(): cd4. and *note
     bytearray.maketrans(): cd5.  This change solves the confusion
     around which types were supported by the *note string: f6. module.
     Now, *note str: 205, *note bytes: 172, and *note bytearray: 173.
     each have their own `maketrans' and `translate' methods with
     intermediate translation tables of the appropriate type.

     （由Georg Brandl在 bpo-5675(4) 中贡献）

   * The syntax of the *note with: 7da. statement now allows multiple
     context managers in a single statement:

          >>> with open('mylog.txt') as infile, open('a.out', 'w') as outfile:
          ...     for line in infile:
          ...         if '<critical>' in line:
          ...             outfile.write(line)

     With the new syntax, the ‘contextlib.nested()’ function is no
     longer needed and is now deprecated.

     (Contributed by Georg Brandl and Mattias Brändström; appspot issue
     53094(5).)

   * ‘round(x, n)’ now returns an integer if `x' is an integer.
     Previously it returned a float:

          >>> round(1123, -2)
          1100

     （由 Mark Dickinson在 bpo-4707(6) 贡献）

   * 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 ‘1.1’ which does
     not have an exact equivalent in binary floating point.  Since there
     is no exact equivalent, an expression like ‘float('1.1')’ evaluates
     to the nearest representable value which is ‘0x1.199999999999ap+0’
     in hex or ‘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 ‘repr(1.1)’ was computed as
     ‘format(1.1, '.17g')’ which evaluated to ‘'1.1000000000000001'’.
     The advantage of using 17 digits was that it relied on IEEE-754
     guarantees to assure that ‘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 ‘repr(1.1)’ is smarter and returns ‘'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 ‘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(7) 贡献）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1739468

   (2) https://bugs.python.org/issue3439

   (3) https://bugs.python.org/issue5237

   (4) https://bugs.python.org/issue5675

   (5) https://codereview.appspot.com/53094

   (6) https://bugs.python.org/issue4707

   (7) https://bugs.python.org/issue1580


File: python.info,  Node: 新增，改进和弃用的模块<2>,  Next: 性能优化<8>,  Prev: 其他语言特性修改<9>,  Up: Python 3 1 有什么新变化

1.9.4 新增，改进和弃用的模块
----------------------------

   * Added a *note collections.Counter: ab9. class to support convenient
     counting of unique items in a sequence or iterable:

          >>> Counter(['red', 'blue', 'red', 'green', 'blue', 'blue'])
          Counter({'blue': 3, 'red': 2, 'green': 1})

     （由 Raymond Hettinger 在 bpo-1696199(1) 中贡献。）

   * Added a new module, *note tkinter.ttk: 118. 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(2) 中贡献。）

   * The *note gzip.GzipFile: 206. and *note bz2.BZ2File: 224. classes
     now support the context management protocol:

          >>> # Automatically close file after writing
          >>> with gzip.GzipFile(filename, "wb") as f:
          ...     f.write(b"xxx")

     （由 Antoine Pitrou 贡献。）

   * The *note decimal: 35. module now supports methods for creating a
     decimal object from a binary *note float: 1fd.  The conversion is
     exact but can sometimes be surprising:

          >>> Decimal.from_float(1.1)
          Decimal('1.100000000000000088817841970012523233890533447265625')

     The long decimal result shows the actual binary fraction being
     stored for `1.1'.  The fraction has many digits because `1.1'
     cannot be exactly represented in binary.

     （由Raymond Hettinger 和 Mark Dickinson贡献。）

   * The *note itertools: a3. module grew two new functions.  The *note
     itertools.combinations_with_replacement(): ce3. function is one of
     four for generating combinatorics including permutations and
     Cartesian products.  The *note itertools.compress(): ce4. function
     mimics its namesake from APL. Also, the existing *note
     itertools.count(): ce5. function now has an optional `step'
     argument and can accept any type of counting sequence including
     *note fractions.Fraction: 2be. and *note decimal.Decimal: 2c0.:

          >>> [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)]

     （由 Raymond Hettinger 贡献。）

   * *note collections.namedtuple(): 1a1. now supports a keyword
     argument `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:

          >>> 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)]

     （由 Raymond Hettinger 在 bpo-1818(3) 中贡献。）

   * The *note re.sub(): 579, *note re.subn(): 823. and *note
     re.split(): 4d0. functions now accept a flags parameter.

     （由 Gregory Smith 贡献）

   * The *note logging: aa. module now implements a simple *note
     logging.NullHandler: ce6. 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":

          >>> h = logging.NullHandler()
          >>> logging.getLogger("foo").addHandler(h)

     （由 Vinay Sajip 在 bpo-4384(4) 中贡献。）

   * The *note runpy: e2. module which supports the ‘-m’ command line
     switch now supports the execution of packages by looking for and
     executing a ‘__main__’ submodule when a package name is supplied.

     （由 Andi Vajda 在 bpo-4195(5) 中贡献。）

   * The *note pdb: c9. module can now access and display source code
     loaded via *note zipimport: 14c. (or any other conformant PEP
     302(6) loader).

     （由 Alexander Belopolsky 在 bpo-4201(7) 中贡献。）

   * *note functools.partial: 8b5. objects can now be pickled.

     (Suggested by Antoine Pitrou and Jesse Noller.  Implemented by Jack
     Diederich; bpo-5228(8).)

   * Add *note pydoc: d9. help topics for symbols so that ‘help('@')’
     works as expected in the interactive environment.

     （由 David Laban 在 bpo-4739(9) 中贡献。）

   * The *note unittest: 124. 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:

          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):
                  ...

     Also, tests for exceptions have been builtout to work with context
     managers using the *note with: 7da. statement:

          def test_division_by_zero(self):
              with self.assertRaises(ZeroDivisionError):
                  x / 0

     In addition, several new assertion methods were added including
     ‘assertSetEqual()’, ‘assertDictEqual()’,
     ‘assertDictContainsSubset()’, ‘assertListEqual()’,
     ‘assertTupleEqual()’, ‘assertSequenceEqual()’,
     ‘assertRaisesRegexp()’, ‘assertIsNone()’, and ‘assertIsNotNone()’.

     （由Benjamin Peterson 和 Antoine Pitrou 贡献。）

   * The *note io: a1. module has three new constants for the ‘seek()’
     method ‘SEEK_SET’, ‘SEEK_CUR’, and ‘SEEK_END’.

   * The *note sys.version_info: bed. tuple is now a named tuple:

          >>> sys.version_info
          sys.version_info(major=3, minor=1, micro=0, releaselevel='alpha', serial=2)

     （由 Ross Light 在 bpo-4285(10) 中贡献。）

   * The *note nntplib: c0. and *note imaplib: 97. modules now support
     IPv6.

     （由 Derek Morr 在 bpo-1655(11) 和 bpo-1664(12) 中贡献。）

   * The *note pickle: ca. 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, ‘__builtin__.set’
     in Python 2 is called ‘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 `fix_imports' option:

          >>> 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.'

     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(13) 中贡献
     。）

   * A new module, *note importlib: 9a. was added.  It provides a
     complete, portable, pure Python reference implementation of the
     *note import: ce7. statement and its counterpart, the *note
     __import__(): 16b. function.  It represents a substantial step
     forward in documenting and defining the actions that take place
     during imports.

     （由 Brett Cannon 贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1696199

   (2) https://bugs.python.org/issue2983

   (3) https://bugs.python.org/issue1818

   (4) https://bugs.python.org/issue4384

   (5) https://bugs.python.org/issue4195

   (6) https://www.python.org/dev/peps/pep-0302

   (7) https://bugs.python.org/issue4201

   (8) https://bugs.python.org/issue5228

   (9) https://bugs.python.org/issue4739

   (10) https://bugs.python.org/issue4285

   (11) https://bugs.python.org/issue1655

   (12) https://bugs.python.org/issue1664

   (13) https://bugs.python.org/issue6137


File: python.info,  Node: 性能优化<8>,  Next: IDLE<2>,  Prev: 新增，改进和弃用的模块<2>,  Up: Python 3 1 有什么新变化

1.9.5 性能优化
--------------

Major performance enhancements have been added:

   * The new I/O library (as defined in PEP 3116(1)) 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 ‘_pyio’ module.

     （由 Amaury Forgeot d’Arc 和 Antoine Pitrou 贡献。）

   * 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(2) 中贡献。）

   * Enabling a configure option named ‘--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(3) 中贡献。）

   * 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(4) 中贡献。
     ）

   * The *note json: a4. module now has a C extension to substantially
     improve its performance.  In addition, the API was modified so that
     json works only with *note str: 205, not with *note bytes: 172.
     That change makes the module closely match the JSON
     specification(5) which is defined in terms of Unicode.

     （由 Bob Ippolito 在 bpo-4136(6) 中贡献。并由 Antoine Pitrou 和
     Benjamin Peterson 转换为Py3.1）

   * Unpickling now interns the attribute names of pickled objects.
     This saves memory and allows pickles to be smaller.

     （由 Jake McGuire 和 Antoine Pitrou 在 bpo-5084(7) 中贡献。）

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3116

   (2) https://bugs.python.org/issue4688

   (3) https://bugs.python.org/issue4753

   (4) https://bugs.python.org/issue4868

   (5) http://json.org/

   (6) https://bugs.python.org/issue4136

   (7) https://bugs.python.org/issue5084


File: python.info,  Node: IDLE<2>,  Next: 构建和 C API 的改变<6>,  Prev: 性能优化<8>,  Up: Python 3 1 有什么新变化

1.9.6 IDLE
----------

   * IDLE’s format menu now provides an option to strip trailing
     whitespace from a source file.

     （由 Roger D. Serwy 在 bpo-5150(1) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5150


File: python.info,  Node: 构建和 C API 的改变<6>,  Next: 移植到 Python 3 1,  Prev: IDLE<2>,  Up: Python 3 1 有什么新变化

1.9.7 构建和 C API 的改变
-------------------------

Changes to Python’s build process and to the C API include:

   * Integers are now stored internally either in base ‘2**15’ or in
     base ‘2**30’, the base being determined at build time.  Previously,
     they were always stored in base ‘2**15’.  Using base ‘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 ‘2**30’ on 64-bit machines and base
     ‘2**15’ on 32-bit machines; on Unix, there’s a new configure option
     ‘--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 *note sys.int_info: ceb. 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:

          >>> import sys
          >>> sys.int_info
          sys.int_info(bits_per_digit=30, sizeof_digit=4)

     （由 Mark Dickinson在 bpo-4258(1) 贡献）

   * The *note PyLong_AsUnsignedLongLong(): cec. function now handles a
     negative `pylong' by raising *note OverflowError: a41. instead of
     *note TypeError: 1fe.

     （由 Mark Dickinson 和 Lisandro Dalcrin 在 bpo-5175(2) 中贡献。）

   * Deprecated ‘PyNumber_Int()’.  Use *note PyNumber_Long(): 395.
     instead.

     （由 Mark Dickinson在 bpo-4910(3) 贡献）

   * Added a new *note PyOS_string_to_double(): ced. function to replace
     the deprecated functions ‘PyOS_ascii_strtod()’ and
     ‘PyOS_ascii_atof()’.

     （由 Mark Dickinson 在 bpo-5914(4) 贡献）

   * Added *note PyCapsule: cd2. as a replacement for the ‘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(5) 中贡献。）

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue4258

   (2) https://bugs.python.org/issue5175

   (3) https://bugs.python.org/issue4910

   (4) https://bugs.python.org/issue5914

   (5) https://bugs.python.org/issue5630


File: python.info,  Node: 移植到 Python 3 1,  Prev: 构建和 C API 的改变<6>,  Up: Python 3 1 有什么新变化

1.9.8 移植到 Python 3.1
-----------------------

This section lists previously described changes and other bugfixes that
may require changes to your code:

   * The new floating point string representations can break existing
     doctests.  For example:

          def e():
              '''Compute the base of natural logarithms.

              >>> e()
              2.7182818284590451

              '''
              return sum(1/math.factorial(x) for x in reversed(range(30)))

          doctest.testmod()

          **********************************************************************
          Failed example:
              e()
          Expected:
              2.7182818284590451
          Got:
              2.718281828459045
          **********************************************************************

   * 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
     `fix_imports' option to ‘False’.  See the discussion above for more
     details.


File: python.info,  Node: Python 3 0 有什么新变化,  Next: Python 2 7 有什么新变化,  Prev: Python 3 1 有什么新变化,  Up: Python 有什麼新功能？

1.10 Python 3.0 有什么新变化
============================


作者: Guido van Rossum

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
`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 ‘Misc/NEWS’ file in the
source distribution contains a wealth of detailed information about
every small thing that was changed.

* Menu:

* 常见的绊脚石::
* Overview Of Syntax Changes::
* Changes Already Present In Python 2.6: Changes Already Present In Python 2 6.
* Library Changes::
* 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.


File: python.info,  Node: 常见的绊脚石,  Next: Overview Of Syntax Changes,  Up: Python 3 0 有什么新变化

1.10.1 常见的绊脚石
-------------------

This section lists those few changes that are most likely to trip you up
if you’re used to Python 2.5.

* Menu:

* Print Is A Function::
* Views And Iterators Instead Of Lists::
* Ordering Comparisons::
* 整数::
* Text Vs. Data Instead Of Unicode Vs. 8-bit: Text Vs Data Instead Of Unicode Vs 8-bit.


File: python.info,  Node: Print Is A Function,  Next: Views And Iterators Instead Of Lists,  Up: 常见的绊脚石

1.10.1.1 Print Is A Function
............................

The ‘print’ statement has been replaced with a *note print(): 971.
function, with keyword arguments to replace most of the special syntax
of the old ‘print’ statement ( PEP 3105(1)).  Examples:

     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)!

You can also customize the separator between items, e.g.:

     print("There are <", 2**32, "> possibilities!", sep="")

which produces:

     There are <4294967296> possibilities!

注意

   * The *note print(): 971. function doesn’t support the "softspace"
     feature of the old ‘print’ statement.  For example, in Python 2.x,
     ‘print "A\n", "B"’ would write ‘"A\nB\n"’; but in Python 3.0,
     ‘print("A\n", "B")’ writes ‘"A\n B\n"’.

   * Initially, you’ll be finding yourself typing the old ‘print x’ a
     lot in interactive mode.  Time to retrain your fingers to type
     ‘print(x)’ instead!

   * When using the ‘2to3’ source-to-source conversion tool, all ‘print’
     statements are automatically converted to *note print(): 971.
     function calls, so this is mostly a non-issue for larger projects.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3105


File: python.info,  Node: Views And Iterators Instead Of Lists,  Next: Ordering Comparisons,  Prev: Print Is A Function,  Up: 常见的绊脚石

1.10.1.2 Views And Iterators Instead Of Lists
.............................................

Some well-known APIs no longer return lists:

   * *note dict: 164. methods *note dict.keys(): cf4, *note
     dict.items(): cf5. and *note dict.values(): cf6. return "views"
     instead of lists.  For example, this no longer works: ‘k =
     d.keys(); k.sort()’.  Use ‘k = sorted(d)’ instead (this works in
     Python 2.5 too and is just as efficient).

   * Also, the ‘dict.iterkeys()’, ‘dict.iteritems()’ and
     ‘dict.itervalues()’ methods are no longer supported.

   * *note map(): cf7. and *note filter(): cf8. return iterators.  If
     you really need a list and the input sequences are all of equal
     length, a quick fix is to wrap *note map(): cf7. in *note list():
     1f8, e.g.  ‘list(map(...))’, but a better fix is often to use a
     list comprehension (especially when the original code uses *note
     lambda: cf9.), or rewriting the code so it doesn’t need a list at
     all.  Particularly tricky is *note map(): cf7. invoked for the side
     effects of the function; the correct transformation is to use a
     regular *note for: cfa. loop (since creating a list would just be
     wasteful).

     If the input sequences are not of equal length, *note map(): cf7.
     will stop at the termination of the shortest of the sequences.  For
     full compatibility with *note map(): cf7. from Python 2.x, also
     wrap the sequences in *note itertools.zip_longest(): cfb, e.g.
     ‘map(func, *sequences)’ becomes ‘list(map(func,
     itertools.zip_longest(*sequences)))’.

   * *note range(): 1f5. now behaves like ‘xrange()’ used to behave,
     except it works with values of arbitrary size.  The latter no
     longer exists.

   * *note zip(): cfc. now returns an iterator.


File: python.info,  Node: Ordering Comparisons,  Next: 整数,  Prev: Views And Iterators Instead Of Lists,  Up: 常见的绊脚石

1.10.1.3 Ordering Comparisons
.............................

Python 3.0 has simplified the rules for ordering comparisons:

   * The ordering comparison operators (‘<’, ‘<=’, ‘>=’, ‘>’) raise a
     TypeError exception when the operands don’t have a meaningful
     natural ordering.  Thus, expressions like ‘1 < ''’, ‘0 > None’ or
     ‘len <= len’ are no longer valid, and e.g.  ‘None < None’ raises
     *note TypeError: 1fe. instead of returning ‘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 ‘==’ and ‘!=’ operators: objects of different
     incomparable types always compare unequal to each other.

   * ‘builtin.sorted()’ and *note list.sort(): 547. no longer accept the
     `cmp' argument providing a comparison function.  Use the `key'
     argument instead.  N.B. the `key' and `reverse' arguments are now
     "keyword-only".

   * The ‘cmp()’ function should be treated as gone, and the ‘__cmp__()’
     special method is no longer supported.  Use *note __lt__(): cfe.
     for sorting, *note __eq__(): 44b. with *note __hash__(): 44c, and
     other rich comparisons as needed.  (If you really need the ‘cmp()’
     functionality, you could use the expression ‘(a > b) - (a < b)’ as
     the equivalent for ‘cmp(a, b)’.)


File: python.info,  Node: 整数,  Next: Text Vs Data Instead Of Unicode Vs 8-bit,  Prev: Ordering Comparisons,  Up: 常见的绊脚石

1.10.1.4 整数
.............

   * PEP 237(1): Essentially, ‘long’ renamed to *note int: 204.  That
     is, there is only one built-in integral type, named *note int:
     204.; but it behaves mostly like the old ‘long’ type.

   * PEP 238(2): An expression like ‘1/2’ returns a float.  Use ‘1//2’
     to get the truncating behavior.  (The latter syntax has existed for
     years, at least since Python 2.2.)

   * The ‘sys.maxint’ constant was removed, since there is no longer a
     limit to the value of integers.  However, *note sys.maxsize: c15.
     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 ‘sys.maxint’ in previous releases on
     the same platform (assuming the same build options).

   * The *note repr(): 8b9. of a long integer doesn’t include the
     trailing ‘L’ anymore, so code that unconditionally strips that
     character will chop off the last digit instead.  (Use *note str():
     205. instead.)

   * Octal literals are no longer of the form ‘0720’; use ‘0o720’
     instead.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0237

   (2) https://www.python.org/dev/peps/pep-0238


File: python.info,  Node: Text Vs Data Instead Of Unicode Vs 8-bit,  Prev: 整数,  Up: 常见的绊脚石

1.10.1.5 Text Vs. Data Instead Of Unicode Vs. 8-bit
...................................................

Everything you thought you knew about binary data and Unicode has
changed.

   * Python 3.0 uses the concepts of `text' and (binary) `data' instead
     of Unicode strings and 8-bit strings.  All text is Unicode; however
     `encoded' Unicode is represented as binary data.  The type used to
     hold text is *note str: 205, the type used to hold data is *note
     bytes: 172.  The biggest difference with the 2.x situation is that
     any attempt to mix text and data in Python 3.0 raises *note
     TypeError: 1fe, 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 *note
     UnicodeDecodeError: 32b. if it contained non-ASCII values.  This
     value-specific behavior has caused numerous sad faces over the
     years.

   * 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 ‘unicode’ for all
     unencoded text, and *note str: 205. for binary or encoded data
     only.  Then the ‘2to3’ tool will do most of the work for you.

   * You can no longer use ‘u"..."’ literals for Unicode text.  However,
     you must use ‘b"..."’ literals for binary data.

   * As the *note str: 205. and *note bytes: 172. types cannot be mixed,
     you must always explicitly convert between them.  Use *note
     str.encode(): 170. to go from *note str: 205. to *note bytes: 172,
     and *note bytes.decode(): 171. to go from *note bytes: 172. to
     *note str: 205.  You can also use ‘bytes(s, encoding=...)’ and
     ‘str(b, encoding=...)’, respectively.

   * Like *note str: 205, the *note bytes: 172. type is immutable.
     There is a separate `mutable' type to hold buffered binary data,
     *note bytearray: 173.  Nearly all APIs that accept *note bytes:
     172. also accept *note bytearray: 173.  The mutable API is based on
     ‘collections.MutableSequence’.

   * All backslashes in raw string literals are interpreted literally.
     This means that ‘'\U'’ and ‘'\u'’ escapes in raw strings are not
     treated specially.  For example, ‘r'\u20ac'’ is a string of 6
     characters in Python 3.0, whereas in 2.6, ‘ur'\u20ac'’ was the
     single "euro" character.  (Of course, this change only affects raw
     string literals; the euro character is ‘'\u20ac'’ in Python 3.0.)

   * The built-in ‘basestring’ abstract type was removed.  Use *note
     str: 205. instead.  The *note str: 205. and *note bytes: 172. types
     don’t have functionality enough in common to warrant a shared base
     class.  The ‘2to3’ tool (see below) replaces every occurrence of
     ‘basestring’ with *note str: 205.

   * Files opened as text files (still the default mode for *note
     open(): 16f.) always use an encoding to map between strings (in
     memory) and bytes (on disk).  Binary files (opened with a ‘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 ‘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 *note codecs: 1b. module.

   * The initial values of *note sys.stdin: 41e, *note sys.stdout: 41f.
     and *note sys.stderr: 1ea. are now unicode-only text files (i.e.,
     they are instances of *note io.TextIOBase: d01.).  To read and
     write bytes data with these streams, you need to use their *note
     io.TextIOBase.buffer: d02. attribute.

   * 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.  *note open(): 16f. and many functions
     in the *note os: c4. module) that take filenames accept *note
     bytes: 172. objects as well as strings, and a few APIs have a way
     to ask for a *note bytes: 172. return value.  Thus, *note
     os.listdir(): b1c. returns a list of *note bytes: 172. instances if
     the argument is a *note bytes: 172. instance, and *note
     os.getcwdb(): 3da. returns the current working directory as a *note
     bytes: 172. instance.  Note that when *note os.listdir(): b1c.
     returns a list of strings, filenames that cannot be decoded
     properly are omitted rather than raising *note UnicodeError: d03.

   * Some system APIs like *note os.environ: c09. and *note sys.argv:
     cc6. can also present problems when the bytes made available by the
     system is not interpretable using the default encoding.  Setting
     the ‘LANG’ variable and rerunning the program is probably the best
     approach.

   * PEP 3138(1): The *note repr(): 8b9. 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.

   * PEP 3120(2): The default source encoding is now UTF-8.

   * PEP 3131(3): Non-ASCII letters are now allowed in identifiers.
     (However, the standard library remains ASCII-only with the
     exception of contributor names in comments.)

   * The ‘StringIO’ and ‘cStringIO’ modules are gone.  Instead, import
     the *note io: a1. module and use *note io.StringIO: 91a. or *note
     io.BytesIO: 88a. for text and data respectively.

   * See also the *note Unicode 指南: d04, which was updated for Python
     3.0.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3138

   (2) https://www.python.org/dev/peps/pep-3120

   (3) https://www.python.org/dev/peps/pep-3131


File: python.info,  Node: Overview Of Syntax Changes,  Next: Changes Already Present In Python 2 6,  Prev: 常见的绊脚石,  Up: Python 3 0 有什么新变化

1.10.2 Overview Of Syntax Changes
---------------------------------

This section gives a brief overview of every `syntactic' change in
Python 3.0.

* Menu:

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


File: python.info,  Node: 新语法,  Next: 修改的语法,  Up: Overview Of Syntax Changes

1.10.2.1 新语法
...............

   * PEP 3107(1): 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 ‘__annotations__’ attribute.  The intent is to encourage
     experimentation through metaclasses, decorators or frameworks.

   * PEP 3102(2): Keyword-only arguments.  Named parameters occurring
     after ‘*args’ in the parameter list `must' be specified using
     keyword syntax in the call.  You can also use a bare ‘*’ in the
     parameter list to indicate that you don’t accept a variable-length
     argument list, but you do have keyword-only arguments.

   * 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.

   * PEP 3104(3): *note nonlocal: d07. statement.  Using ‘nonlocal x’
     you can now assign directly to a variable in an outer (but
     non-global) scope.  ‘nonlocal’ is a new reserved word.

   * PEP 3132(4): Extended Iterable Unpacking.  You can now write things
     like ‘a, b, *rest = some_sequence’.  And even ‘*rest, a = stuff’.
     The ‘rest’ object is always a (possibly empty) list; the right-hand
     side may be any iterable.  Example:

          (a, *rest, b) = range(5)

     This sets `a' to ‘0’, `b' to ‘4’, and `rest' to ‘[1, 2, 3]’.

   * Dictionary comprehensions: ‘{k: v for k, v in stuff}’ means the
     same thing as ‘dict(stuff)’ but is more flexible.  (This is PEP
     274(5) vindicated.  :-)

   * Set literals, e.g.  ‘{1, 2}’.  Note that ‘{}’ is an empty
     dictionary; use ‘set()’ for an empty set.  Set comprehensions are
     also supported; e.g., ‘{x for x in stuff}’ means the same thing as
     ‘set(stuff)’ but is more flexible.

   * New octal literals, e.g.  ‘0o720’ (already in 2.6).  The old octal
     literals (‘0720’) are gone.

   * New binary literals, e.g.  ‘0b1010’ (already in 2.6), and there is
     a new corresponding built-in function, *note bin(): d08.

   * Bytes literals are introduced with a leading ‘b’ or ‘B’, and there
     is a new corresponding built-in function, *note bytes(): 172.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3107

   (2) https://www.python.org/dev/peps/pep-3102

   (3) https://www.python.org/dev/peps/pep-3104

   (4) https://www.python.org/dev/peps/pep-3132

   (5) https://www.python.org/dev/peps/pep-0274


File: python.info,  Node: 修改的语法,  Next: 移除的语法,  Prev: 新语法,  Up: Overview Of Syntax Changes

1.10.2.2 修改的语法
...................

   * PEP 3109(1) and PEP 3134(2): new *note raise: d0a. statement
     syntax: ‘raise [`expr' [from `expr']]’.  See below.

   * ‘as’ and *note with: 7da. are now reserved words.  (Since 2.6,
     actually.)

   * ‘True’, ‘False’, and ‘None’ are reserved words.  (2.6 partially
     enforced the restrictions on ‘None’ already.)

   * Change from *note except: c10. `exc', `var' to ‘except’ `exc' ‘as’
     `var'.  See PEP 3110(3).

   * PEP 3115(4): New Metaclass Syntax.  Instead of:

          class C:
              __metaclass__ = M
              ...

     you must now use:

          class C(metaclass=M):
              ...

     The module-global ‘__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 *note object: 3d2.)

   * List comprehensions no longer support the syntactic form ‘[... for
     `var' in `item1', `item2', ...]’.  Use ‘[... for `var' in (`item1',
     `item2', ...)]’ instead.  Also note that list comprehensions have
     different semantics: they are closer to syntactic sugar for a
     generator expression inside a *note list(): 1f8. constructor, and
     in particular the loop control variables are no longer leaked into
     the surrounding scope.

   * The `ellipsis' (‘...’) can be used as an atomic expression
     anywhere.  (Previously it was only allowed in slices.)  Also, it
     `must' now be spelled as ‘...’.  (Previously it could also be
     spelled as ‘. . .’, by a mere accident of the grammar.)

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3109

   (2) https://www.python.org/dev/peps/pep-3134

   (3) https://www.python.org/dev/peps/pep-3110

   (4) https://www.python.org/dev/peps/pep-3115


File: python.info,  Node: 移除的语法,  Prev: 修改的语法,  Up: Overview Of Syntax Changes

1.10.2.3 移除的语法
...................

   * PEP 3113(1): Tuple parameter unpacking removed.  You can no longer
     write ‘def foo(a, (b, c)): ...’.  Use ‘def foo(a, b_c): b, c = b_c’
     instead.

   * Removed backticks (use *note repr(): 8b9. instead).

   * Removed ‘<>’ (use ‘!=’ instead).

   * Removed keyword: *note exec(): d0c. is no longer a keyword; it
     remains as a function.  (Fortunately the function syntax was also
     accepted in 2.x.)  Also note that *note exec(): d0c. no longer
     takes a stream argument; instead of ‘exec(f)’ you can use
     ‘exec(f.read())’.

   * Integer literals no longer support a trailing ‘l’ or ‘L’.

   * String literals no longer support a leading ‘u’ or ‘U’.

   * The *note from: d0d. `module' *note import: ce7. ‘*’ syntax is only
     allowed at the module level, no longer inside functions.

   * The only acceptable syntax for relative imports is ‘from
     .[`module'] import `name'’.  All *note import: ce7. forms not
     starting with ‘.’ are interpreted as absolute imports.  ( PEP
     328(2))

   * Classic classes are gone.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3113

   (2) https://www.python.org/dev/peps/pep-0328


File: python.info,  Node: Changes Already Present In Python 2 6,  Next: Library Changes,  Prev: Overview Of Syntax Changes,  Up: Python 3 0 有什么新变化

1.10.3 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 *note Python 2.6 有什么新变化: d0f.
should be consulted for longer descriptions.

   * *note PEP 343; "with" 语句: d10.  The *note with: 7da. statement is
     now a standard feature and no longer needs to be imported from the
     *note __future__: 0.  Also check out *note Writing Context
     Managers: d11. and *note contextlib 模块: d12.

   * *note PEP 366; 从主模块显式相对导入: d13.  This enhances the
     usefulness of the *note -m: 443. option when the referenced module
     lives in a package.

   * *note PEP 370; 分用户的 site-packages 目录: d14.

   * *note PEP 371; 多任务处理包: d15.

   * *note PEP 3101; 高级字符串格式: d16.  Note: the 2.6 description
     mentions the *note format(): 5d5. method for both 8-bit and Unicode
     strings.  In 3.0, only the *note str: 205. type (text strings with
     Unicode support) supports this method; the *note bytes: 172. type
     does not.  The plan is to eventually make this the only API for
     string formatting, and to start deprecating the ‘%’ operator in
     Python 3.1.

   * *note PEP 3105; print 改为函数: d17.  This is now a standard
     feature and no longer needs to be imported from *note __future__:
     0.  More details were given above.

   * *note PEP 3110; 异常处理的变更: d18.  The *note except: c10. `exc'
     ‘as’ `var' syntax is now standard and ‘except’ `exc', `var' is no
     longer supported.  (Of course, the ‘as’ `var' part is still
     optional.)

   * *note PEP 3112; 字节字面值: d19.  The ‘b"..."’ string literal
     notation (and its variants like ‘b'...'’, ‘b"""..."""’, and
     ‘br"..."’) now produces a literal of type *note bytes: 172.

   * *note PEP 3116; 新 I/O 库: d1a.  The *note io: a1. module is now
     the standard way of doing file I/O. The built-in *note open(): 16f.
     function is now an alias for *note io.open(): 74d. and has
     additional keyword arguments `encoding', `errors', `newline' and
     `closefd'.  Also note that an invalid `mode' argument now raises
     *note ValueError: 16d, not *note IOError: a73.  The binary file
     object underlying a text file object can be accessed as ‘f.buffer’
     (but beware that the text object maintains a buffer of itself in
     order to speed up the encoding and decoding operations).

   * *note PEP 3118; 修改缓冲区协议: d1b.  The old builtin ‘buffer()’ is
     now really gone; the new builtin *note memoryview(): 386. provides
     (mostly) similar functionality.

   * *note PEP 3119; 抽象基类: d1c.  The *note abc: 3. module and the
     ABCs defined in the *note collections: 1d. module plays a somewhat
     more prominent role in the language now, and built-in collection
     types like *note dict: 164. and *note list: 1f8. conform to the
     ‘collections.MutableMapping’ and ‘collections.MutableSequence’
     ABCs, respectively.

   * *note PEP 3127; 整型文字支持和语法: d1d.  As mentioned above, the
     new octal literal notation is the only one supported, and binary
     literals have been added.

   * *note PEP 3129; 类装饰器: d1e.

   * *note PEP 3141; A Type Hierarchy for Numbers: d1f.  The *note
     numbers: c1. module is another new use of ABCs, defining Python’s
     "numeric tower".  Also note the new *note fractions: 81. module
     which implements *note numbers.Rational: d20.


File: python.info,  Node: Library Changes,  Next: PEP 3101 A New Approach To String Formatting,  Prev: Changes Already Present In Python 2 6,  Up: Python 3 0 有什么新变化

1.10.4 Library Changes
----------------------

Due to time constraints, this document does not exhaustively cover the
very extensive changes to the standard library.  PEP 3108(1) is the
reference for the major changes to the library.  Here’s a capsule
review:

   * Many old modules were removed.  Some, like ‘gopherlib’ (no longer
     used) and ‘md5’ (replaced by *note hashlib: 8c.), were already
     deprecated by PEP 4(2).  Others were removed as a result of the
     removal of support for various platforms such as Irix, BeOS and Mac
     OS 9 (see PEP 11(3)).  Some modules were also selected for removal
     in Python 3.0 due to lack of use or because a better replacement
     exists.  See PEP 3108(4) for an exhaustive list.

   * The ‘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
     ‘https://www.jcea.es/programacion/pybsddb.htm’.

   * Some modules were renamed because their old name disobeyed PEP
     8(5), or for various other reasons.  Here’s the list:

     旧名称                      新名称
                                 
     --------------------------------------------------------
                                 
     _winreg                     winreg
                                 
                                 
     ConfigParser                configparser
                                 
                                 
     copy_reg                    copyreg
                                 
                                 
     Queue                       queue
                                 
                                 
     SocketServer                socketserver
                                 
                                 
     markupbase                  _markupbase
                                 
                                 
     repr                        reprlib
                                 
                                 
     test.test_support           test.support
                                 

   * 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, *note pickle: ca. and
     ‘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 *note pickle: ca. / ‘cPickle’ pair received this
     treatment.  The *note profile: d3. module is on the list for 3.1.
     The ‘StringIO’ module has been turned into a class in the *note io:
     a1. module.

   * Some related modules have been grouped into packages, and usually
     the submodule names have been simplified.  The resulting new
     packages are:

        * *note dbm: 31. (‘anydbm’, ‘dbhash’, *note dbm: 31, ‘dumbdbm’,
          ‘gdbm’, ‘whichdb’).

        * *note html: 8f. (‘HTMLParser’, ‘htmlentitydefs’).

        * *note http: 92. (‘httplib’, ‘BaseHTTPServer’, ‘CGIHTTPServer’,
          ‘SimpleHTTPServer’, ‘Cookie’, ‘cookielib’).

        * *note tkinter: 10e. (all ‘Tkinter’-related modules except
          *note turtle: 11f.).  The target audience of *note turtle:
          11f. doesn’t really care about *note tkinter: 10e.  Also note
          that as of Python 2.6, the functionality of *note turtle: 11f.
          has been greatly enhanced.

        * *note urllib: 126. (*note urllib: 126, ‘urllib2’, ‘urlparse’,
          ‘robotparse’).

        * ‘xmlrpc’ (‘xmlrpclib’, ‘DocXMLRPCServer’,
          ‘SimpleXMLRPCServer’).

Some other changes to standard library modules, not covered by PEP
3108(6):

   * Killed ‘sets’.  Use the built-in *note set(): 1f6. class.

   * Cleanup of the *note sys: fd. module: removed ‘sys.exitfunc()’,
     ‘sys.exc_clear()’, ‘sys.exc_type’, ‘sys.exc_value’,
     ‘sys.exc_traceback’.  (Note that *note sys.last_type: d22. etc.
     remain.)

   * Cleanup of the *note array.array: 216. type: the ‘read()’ and
     ‘write()’ methods are gone; use ‘fromfile()’ and ‘tofile()’
     instead.  Also, the ‘'c'’ typecode for array is gone – use either
     ‘'b'’ for bytes or ‘'u'’ for Unicode characters.

   * Cleanup of the *note operator: c2. module: removed
     ‘sequenceIncludes()’ and ‘isCallable()’.

   * Cleanup of the ‘thread’ module: ‘acquire_lock()’ and
     ‘release_lock()’ are gone; use ‘acquire()’ and ‘release()’ instead.

   * Cleanup of the *note random: dc. module: removed the ‘jumpahead()’
     API.

   * The ‘new’ module is gone.

   * The functions ‘os.tmpnam()’, ‘os.tempnam()’ and ‘os.tmpfile()’ have
     been removed in favor of the *note tempfile: 103. module.

   * The *note tokenize: 11a. module has been changed to work with
     bytes.  The main entry point is now *note tokenize.tokenize(): d23,
     instead of generate_tokens.

   * ‘string.letters’ and its friends (‘string.lowercase’ and
     ‘string.uppercase’) are gone.  Use *note string.ascii_letters: d24.
     etc.  instead.  (The reason for the removal is that
     ‘string.letters’ and friends had locale-specific behavior, which is
     a bad idea for such attractively-named global "constants".)

   * Renamed module ‘__builtin__’ to *note builtins: 12. (removing the
     underscores, adding an ’s’).  The ‘__builtins__’ variable found in
     most global namespaces is unchanged.  To modify a builtin, you
     should use *note builtins: 12, not ‘__builtins__’!

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3108

   (2) https://www.python.org/dev/peps/pep-0004

   (3) https://www.python.org/dev/peps/pep-0011

   (4) https://www.python.org/dev/peps/pep-3108

   (5) https://www.python.org/dev/peps/pep-0008

   (6) https://www.python.org/dev/peps/pep-3108


File: python.info,  Node: PEP 3101 A New Approach To String Formatting,  Next: Changes To Exceptions,  Prev: Library Changes,  Up: Python 3 0 有什么新变化

1.10.5 `PEP 3101': A New Approach To String Formatting
------------------------------------------------------

   * A new system for built-in string formatting operations replaces the
     ‘%’ string formatting operator.  (However, the ‘%’ operator is
     still supported; it will be deprecated in Python 3.1 and removed
     from the language at some later time.)  Read PEP 3101(1) for the
     full scoop.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3101


File: python.info,  Node: Changes To Exceptions,  Next: Miscellaneous Other Changes,  Prev: PEP 3101 A New Approach To String Formatting,  Up: Python 3 0 有什么新变化

1.10.6 Changes To Exceptions
----------------------------

The APIs for raising and catching exception have been cleaned up and new
powerful features added:

   * PEP 352(1): All exceptions must be derived (directly or indirectly)
     from *note BaseException: 2db.  This is the root of the exception
     hierarchy.  This is not new as a recommendation, but the
     `requirement' to inherit from *note BaseException: 2db. 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.

   * Almost all exceptions should actually derive from *note Exception:
     2dc.; *note BaseException: 2db. should only be used as a base class
     for exceptions that should only be handled at the top level, such
     as *note SystemExit: 6f3. or *note KeyboardInterrupt: 2cc.  The
     recommended idiom for handling all exceptions except for this
     latter category is to use *note except: c10. *note Exception: 2dc.

   * ‘StandardError’ was removed.

   * Exceptions no longer behave as sequences.  Use the ‘args’ attribute
     instead.

   * PEP 3109(2): Raising exceptions.  You must now use ‘raise
     `Exception'(`args')’ instead of ‘raise `Exception', `args'’.
     Additionally, you can no longer explicitly specify a traceback;
     instead, if you `have' to do this, you can assign directly to the
     ‘__traceback__’ attribute (see below).

   * PEP 3110(3): Catching exceptions.  You must now use ‘except
     `SomeException' as `variable'’ instead of ‘except `SomeException',
     `variable'’.  Moreover, the `variable' is explicitly deleted when
     the *note except: c10. block is left.

   * PEP 3134(4): Exception chaining.  There are two cases: implicit
     chaining and explicit chaining.  Implicit chaining happens when an
     exception is raised in an *note except: c10. or *note finally: 2bc.
     handler block.  This usually happens due to a bug in the handler
     block; we call this a `secondary' exception.  In this case, the
     original exception (that was being handled) is saved as the
     ‘__context__’ attribute of the secondary exception.  Explicit
     chaining is invoked with this syntax:

          raise SecondaryException() from primary_exception

     (where `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
     ‘__cause__’ attribute of the secondary exception.  The traceback
     printed when an unhandled exception occurs walks the chain of
     ‘__cause__’ and ‘__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.)

   * PEP 3134(5): Exception objects now store their traceback as the
     ‘__traceback__’ attribute.  This means that an exception object now
     contains all the information pertaining to an exception, and there
     are fewer reasons to use *note sys.exc_info(): d27. (though the
     latter is not removed).

   * A few exception messages are improved when Windows fails to load an
     extension module.  For example, ‘error code 193’ is now ‘%1 is not
     a valid Win32 application’.  Strings now deal with non-English
     locales.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0352

   (2) https://www.python.org/dev/peps/pep-3109

   (3) https://www.python.org/dev/peps/pep-3110

   (4) https://www.python.org/dev/peps/pep-3134

   (5) https://www.python.org/dev/peps/pep-3134


File: python.info,  Node: Miscellaneous Other Changes,  Next: 构建和 C API 的改变<7>,  Prev: Changes To Exceptions,  Up: Python 3 0 有什么新变化

1.10.7 Miscellaneous Other Changes
----------------------------------

* Menu:

* Operators And Special Methods::
* Builtins::


File: python.info,  Node: Operators And Special Methods,  Next: Builtins,  Up: Miscellaneous Other Changes

1.10.7.1 Operators And Special Methods
......................................

   * ‘!=’ now returns the opposite of ‘==’, unless ‘==’ returns *note
     NotImplemented: 202.

   * 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.

   * ‘__getslice__()’, ‘__setslice__()’ and ‘__delslice__()’ were
     killed.  The syntax ‘a[i:j]’ now translates to
     ‘a.__getitem__(slice(i, j))’ (or *note __setitem__(): d2a. or *note
     __delitem__(): d2b, when used as an assignment or deletion target,
     respectively).

   * PEP 3114(1): the standard *note next(): 775. method has been
     renamed to *note __next__(): d2c.

   * The ‘__oct__()’ and ‘__hex__()’ special methods are removed – *note
     oct(): d2d. and *note hex(): d2e. use *note __index__(): 2c2. now
     to convert the argument to an integer.

   * Removed support for ‘__members__’ and ‘__methods__’.

   * The function attributes named ‘func_X’ have been renamed to use the
     ‘__X__’ form, freeing up these names in the function attribute
     namespace for user-defined attributes.  To wit, ‘func_closure’,
     ‘func_code’, ‘func_defaults’, ‘func_dict’, ‘func_doc’,
     ‘func_globals’, ‘func_name’ were renamed to ‘__closure__’,
     ‘__code__’, ‘__defaults__’, *note __dict__: 5f5, ‘__doc__’,
     ‘__globals__’, *note __name__: d2f, respectively.

   * ‘__nonzero__()’ is now *note __bool__(): d30.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3114


File: python.info,  Node: Builtins,  Prev: Operators And Special Methods,  Up: Miscellaneous Other Changes

1.10.7.2 Builtins
.................

   * PEP 3135(1): New *note super(): 5dd.  You can now invoke *note
     super(): 5dd. without arguments and (assuming this is in a regular
     instance method defined inside a *note class: d32. statement) the
     right class and instance will automatically be chosen.  With
     arguments, the behavior of *note super(): 5dd. is unchanged.

   * PEP 3111(2): ‘raw_input()’ was renamed to *note input(): d33.  That
     is, the new *note input(): d33. function reads a line from *note
     sys.stdin: 41e. and returns it with the trailing newline stripped.
     It raises *note EOFError: d34. if the input is terminated
     prematurely.  To get the old behavior of *note input(): d33, use
     ‘eval(input())’.

   * A new built-in function *note next(): 775. was added to call the
     *note __next__(): d2c. method on an object.

   * The *note round(): d35. 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, ‘round(2.5)’
     now returns ‘2’ rather than ‘3’.)  ‘round(x[, n])’ now delegates to
     ‘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 ‘x’ when called with two arguments.

   * Moved ‘intern()’ to *note sys.intern(): d36.

   * Removed: ‘apply()’.  Instead of ‘apply(f, args)’ use ‘f(*args)’.

   * Removed *note callable(): c16.  Instead of ‘callable(f)’ you can
     use ‘isinstance(f, collections.Callable)’.  The
     ‘operator.isCallable()’ function is also gone.

   * Removed ‘coerce()’.  This function no longer serves a purpose now
     that classic classes are gone.

   * Removed ‘execfile()’.  Instead of ‘execfile(fn)’ use
     ‘exec(open(fn).read())’.

   * Removed the ‘file’ type.  Use *note open(): 16f.  There are now
     several different kinds of streams that open can return in the
     *note io: a1. module.

   * Removed ‘reduce()’.  Use *note functools.reduce(): d37. if you
     really need it; however, 99 percent of the time an explicit *note
     for: cfa. loop is more readable.

   * Removed ‘reload()’.  Use *note imp.reload(): d38.

   * Removed.  ‘dict.has_key()’ – use the *note in: 179. operator
     instead.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3135

   (2) https://www.python.org/dev/peps/pep-3111


File: python.info,  Node: 构建和 C API 的改变<7>,  Next: 性能,  Prev: Miscellaneous Other Changes,  Up: Python 3 0 有什么新变化

1.10.8 构建和 C API 的改变
--------------------------

Due to time constraints, here is a `very' incomplete list of changes to
the C API.

   * Support for several platforms was dropped, including but not
     limited to Mac OS 9, BeOS, RISCOS, Irix, and Tru64.

   * PEP 3118(1): New Buffer API.

   * PEP 3121(2): Extension Module Initialization & Finalization.

   * PEP 3123(3): Making *note PyObject_HEAD: d3a. conform to standard
     C.

   * No more C API support for restricted execution.

   * ‘PyNumber_Coerce()’, ‘PyNumber_CoerceEx()’, ‘PyMember_Get()’, and
     ‘PyMember_Set()’ C APIs are removed.

   * New C API *note PyImport_ImportModuleNoBlock(): aa0, works like
     *note PyImport_ImportModule(): d3b. but won’t block on the import
     lock (returning an error instead).

   * Renamed the boolean conversion C-level slot and method:
     ‘nb_nonzero’ is now ‘nb_bool’.

   * Removed ‘METH_OLDARGS’ and ‘WITH_CYCLE_GC’ from the C API.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3118

   (2) https://www.python.org/dev/peps/pep-3121

   (3) https://www.python.org/dev/peps/pep-3123


File: python.info,  Node: 性能,  Next: 移植到 Python 3 0,  Prev: 构建和 C API 的改变<7>,  Up: Python 3 0 有什么新变化

1.10.9 性能
-----------

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!


File: python.info,  Node: 移植到 Python 3 0,  Prev: 性能,  Up: Python 3 0 有什么新变化

1.10.10 移植到 Python 3.0
-------------------------

For porting existing Python 2.5 or 2.6 source code to Python 3.0, the
best strategy is the following:

  0. (Prerequisite:) Start with excellent test coverage.

  1. 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.

  2. (Still using 2.6:) Turn on the ‘-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.

  3. Run the ‘2to3’ source-to-source translator over your source code
     tree.  (See *note 2to3 - 自動將 Python 2的程式碼轉成 Python 3: d3e.
     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.

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 ‘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 ‘2to3’ translator
again, rather than editing the 3.0 version of the source code.

For porting C extensions to Python 3.0, please see *note 遷移延伸模組到
Python 3: d3f.


File: python.info,  Node: Python 2 7 有什么新变化,  Next: Python 2 6 有什么新变化,  Prev: Python 3 0 有什么新变化,  Up: Python 有什麼新功能？

1.11 Python 2.7 有什么新变化
============================


作者: A.M. Kuchling (amk at amk.ca)

本文介绍了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 *note Decimal: 2c0. class.  There are some useful
additions to the standard library, such as a greatly enhanced *note
unittest: 124. module, the *note argparse: 5. module for parsing
command-line options, convenient *note OrderedDict: 2ea. and *note
Counter: ab9. classes in the *note collections: 1d. 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
‘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 ‘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的未来.
* Changes to the Handling of Deprecation Warnings::
* Python 3.1 Features: Python 3 1 Features.
* 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; Dictionary Views: PEP 3106 Dictionary Views.
* PEP 3137; The memoryview Object: PEP 3137 The memoryview Object.
* 其他语言特性修改: 其他语言特性修改<10>.
* 新增和改进的模块::
* 构建和 C API 的改变: 构建和 C API 的改变<8>.
* Other Changes and Fixes::
* 移植到 Python 2.7: 移植到 Python 2 7.
* New Features Added to Python 2.7 Maintenance Releases: New Features Added to Python 2 7 Maintenance Releases.
* 致谢::


File: python.info,  Node: Python 2 x的未来,  Next: Changes to the Handling of Deprecation Warnings,  Up: Python 2 7 有什么新变化

1.11.1 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系列的预期完整生命周期在 PEP 373(1) 中
有详细介绍。

长期保留 2.7 版的的一些关键后果：

   * 如上所述，与早期的2.x版本相比，2.7版本的维护时间更长。目前，预计核
     心开发团队将继续支持Python 2.7（接收安全更新和其他错误修复），直到
     至少2020年（首次发布后10年，相比之下，通常的支持期为18–24个月）。

   * 随着 Python 2.7 标准库的老化，有效地利用 Python 包索引（直接或通过
     重新分发者）对 Python 2 用户来说变得更加重要。除了各种任务的第三方
     包之外，可用的包还包括与 Python 2 兼容的 Python 3 标准库中的新模块
     和功能的后端移植，以及各种工具和库，这些工具和库可以让用户更容易迁
     移到 Python 3。 Python 包用户指南(2) 提供了从 Python 包索引的下载和
     安装软件的指导。

   * 虽然现在增强 Python 2 的首选方法是在Python包索引上发布新包，但这种
     方法不一定适用于所有情况，尤其是与网络安全相关的情况。在一些特殊情
     况下，如果在PyPI上发布新的或更新的包无法得到充分的处理，则可以使用
     Python增强建议过程来提出直接在Python 2标准库中添加新功能。任何此类
     添加及其添加的维护版本将在下面的 *note New Features Added to Python
     2.7 Maintenance Releases: d44. 部分中注明。

对于希望从 Python2 迁移到 Python3 的项目，或者对于希望同时支持 Python2 和
Python3 用户的库和框架开发人员，可以使用各种工具和指南来帮助决定合适的方
法并管理所涉及的一些技术细节。建议从 *note Python 2 的程式碼移植到Python
3: d45. 操作指南开始。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0373

   (2) https://packaging.python.org


File: python.info,  Node: Changes to the Handling of Deprecation Warnings,  Next: Python 3 1 Features,  Prev: Python 2 x的未来,  Up: Python 2 7 有什么新变化

1.11.2 Changes to the Handling of Deprecation Warnings
------------------------------------------------------

For Python 2.7, a policy decision was made to silence warnings only of
interest to developers by default.  *note DeprecationWarning: 15a. 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(1).)

In previous releases, *note DeprecationWarning: 15a. 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.
*note DeprecationWarning: 15a. 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 *note DeprecationWarning: 15a. messages by
running Python with the *note -Wdefault: 15b. (short form: *note -Wd:
15b.) switch, or by setting the *note PYTHONWARNINGS: 51b. environment
variable to ‘"default"’ (or ‘"d"’) before running Python.  Python code
can also re-enable them by calling ‘warnings.simplefilter('default')’.

The ‘unittest’ module also automatically reenables deprecation warnings
when running tests.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue7319


File: python.info,  Node: Python 3 1 Features,  Next: PEP 372 Adding an Ordered Dictionary to collections,  Prev: Changes to the Handling of Deprecation Warnings,  Up: Python 2 7 有什么新变化

1.11.3 Python 3.1 Features
--------------------------

就像 Python2.6 集成了 Python3.0 的特性一样，2.7版也集成了 Python3.1 中的
一些新特性。2.x 系列继续提供迁移到3.x系列的工具。

3.1 功能的部分列表，这些功能已反向移植到 2.7：

   * The syntax for set literals (‘{1,2,3}’ is a mutable set).

   * Dictionary and set comprehensions (‘{i: i*2 for i in range(3)}’).

   * Multiple context managers in a single *note with: 7da. statement.

   * A new version of the *note io: a1. library, rewritten in C for
     performance.

   * The ordered-dictionary type described in *note PEP 372; Adding an
     Ordered Dictionary to collections: d48.

   * The new ‘","’ format specifier described in *note PEP 378;
     千位分隔符的格式说明符: d49.

   * The *note memoryview: 386. object.

   * A small subset of the *note importlib: 9a. module, *note described
     below: d4a.

   * The *note repr(): 8b9. of a float ‘x’ is shorter in many cases:
     it’s now based on the shortest decimal string that’s guaranteed to
     round back to ‘x’.  As in previous versions of Python, it’s
     guaranteed that ‘float(repr(x))’ recovers ‘x’.

   * Float-to-string and string-to-float conversions are correctly
     rounded.  The *note round(): d35. function is also now correctly
     rounded.

   * The *note PyCapsule: cd2. type, used to provide a C API for
     extension modules.

   * The *note PyLong_AsLongAndOverflow(): cc8. C API function.

Other new Python3-mode warnings include:

   * ‘operator.isCallable()’ and ‘operator.sequenceIncludes()’, which
     are not supported in 3.x, now trigger warnings.

   * The ‘-3’ switch now automatically enables the ‘-Qwarn’ switch that
     causes warnings about using classic division with integers and long
     integers.


File: python.info,  Node: PEP 372 Adding an Ordered Dictionary to collections,  Next: PEP 378 千位分隔符的格式说明符<2>,  Prev: Python 3 1 Features,  Up: Python 2 7 有什么新变化

1.11.4 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 *note OrderedDict: 2ea. class in the *note collections:
1d. module.

The *note OrderedDict: 2ea. 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:

     >>> from collections import OrderedDict
     >>> d = OrderedDict([('first', 1),
     ...                  ('second', 2),
     ...                  ('third', 3)])
     >>> d.items()
     [('first', 1), ('second', 2), ('third', 3)]

If a new entry overwrites an existing entry, the original insertion
position is left unchanged:

     >>> d['second'] = 4
     >>> d.items()
     [('first', 1), ('second', 4), ('third', 3)]

Deleting an entry and reinserting it will move it to the end:

     >>> del d['second']
     >>> d['second'] = 5
     >>> d.items()
     [('first', 1), ('third', 3), ('second', 5)]

The *note popitem(): d4c. method has an optional `last' argument that
defaults to ‘True’.  If `last' is true, the most recently added key is
returned and removed; if it’s false, the oldest key is selected:

     >>> 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)

Comparing two ordered dictionaries checks both the keys and values, and
requires that the insertion order was the same:

     >>> 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

Comparing an *note OrderedDict: 2ea. with a regular dictionary ignores
the insertion order and just compares the keys and values.

How does the *note OrderedDict: 2ea. 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.

   * The ‘ConfigParser’ module uses them by default, meaning that
     configuration files can now be read, modified, and then written
     back in their original order.

   * The *note _asdict(): 2e9. method for *note
     collections.namedtuple(): 1a1. now returns an ordered dictionary
     with the values appearing in the same order as the underlying tuple
     indices.

   * The *note json: a4. module’s *note JSONDecoder: 6fe. class
     constructor was extended with an `object_pairs_hook' parameter to
     allow ‘OrderedDict’ instances to be built by the decoder.  Support
     was also added for third-party tools like PyYAML(1).

也參考
......

PEP 372(2) - 将有序词典添加到集合中

     PEP 由 Armin Ronacher 和 Raymond Hettinger 撰写，由 Raymond
     Hettinger 实现。

   ---------- Footnotes ----------

   (1) http://pyyaml.org/

   (2) https://www.python.org/dev/peps/pep-0372


File: python.info,  Node: PEP 378 千位分隔符的格式说明符<2>,  Next: PEP 389 The argparse Module for Parsing Command Lines,  Prev: PEP 372 Adding an Ordered Dictionary to collections,  Up: Python 2 7 有什么新变化

1.11.5 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 *note locale: a9.
module, which can use different separators ("," in North America, "."
in Europe) and different grouping sizes, but *note locale: a9. 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 *note str.format(): 5d4. method.  When
formatting a floating-point number, simply include a comma between the
width and the precision:

     >>> '{:20,.2f}'.format(18446744073709551616.0)
     '18,446,744,073,709,551,616.00'

When formatting an integer, include the comma after the width:

     >>> '{:20,d}'.format(18446744073709551616)
     '18,446,744,073,709,551,616'

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 *note locale: a9.
module, but it’s easier to use.

也參考
......

PEP 378(1) - 千位分隔符的格式说明符

     PEP 由 Raymond Hettinger 撰写，由 Eric Smith 实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0378


File: python.info,  Node: PEP 389 The argparse Module for Parsing Command Lines,  Next: PEP 391 Dictionary-Based Configuration For Logging,  Prev: PEP 378 千位分隔符的格式说明符<2>,  Up: Python 2 7 有什么新变化

1.11.6 PEP 389: The argparse Module for Parsing Command Lines
-------------------------------------------------------------

The *note argparse: 5. module for parsing command-line arguments was
added as a more powerful replacement for the *note optparse: c3. module.

This means Python now supports three different modules for parsing
command-line arguments: *note getopt: 85, *note optparse: c3, and *note
argparse: 5.  The *note getopt: 85. module closely resembles the C
library’s ‘getopt()’ function, so it remains useful if you’re writing a
Python prototype that will eventually be rewritten in C. *note optparse:
c3. 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 *note argparse: 5. API consistent with *note
optparse: c3.’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 *note argparse: 5.
instead of *note optparse: c3.

以下是为示例代码:

     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__

Unless you override it, ‘-h’ and ‘--help’ switches are automatically
added, and produce neatly formatted output:

     -> ./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

As with *note optparse: c3, the command-line switches and arguments are
returned as an object with attributes named by the `dest' parameters:

     -> ./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']}

*note argparse: 5. has much fancier validation than *note optparse: c3.;
you can specify an exact number of arguments as an integer, 0 or more
arguments by passing ‘'*'’, 1 or more by passing ‘'+'’, or an optional
argument with ‘'?'’.  A top-level parser can contain sub-parsers to
define subcommands that have different sets of switches, as in ‘svn
commit’, ‘svn checkout’, etc.  You can specify an argument’s type as
*note FileType: 90d, which will automatically open files for you and
understands that ‘'-'’ means standard input or output.

也參考
......

*note argparse: 5. documentation

     argparse 模块的文档页面。

*note 升级 optparse 代码: bfc.

     Part of the Python documentation, describing how to convert code
     that uses *note optparse: c3.

PEP 389(1) - argparse - 新的命令行解析模块

     PEP 由 Steven Bethard 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0389


File: python.info,  Node: PEP 391 Dictionary-Based Configuration For Logging,  Next: PEP 3106 Dictionary Views,  Prev: PEP 389 The argparse Module for Parsing Command Lines,  Up: Python 2 7 有什么新变化

1.11.7 PEP 391: Dictionary-Based Configuration For Logging
----------------------------------------------------------

The *note logging: aa. 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.  *note logging: aa.
also supports a ‘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 ‘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 *note 配置函数: d50.

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 ‘network.log’ file that will be
rotated once the log reaches 1MB.

     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')

Three smaller enhancements to the *note logging: aa. module, all
implemented by Vinay Sajip, are:

   * The *note SysLogHandler: afb. class now supports syslogging over
     TCP. The constructor has a `socktype' parameter giving the type of
     socket to use, either *note socket.SOCK_DGRAM: d51. for UDP or
     *note socket.SOCK_STREAM: d52. for TCP. The default protocol
     remains UDP.

   * *note Logger: 4ad. instances gained a *note getChild(): d53. method
     that retrieves a descendant logger using a relative path.  For
     example, once you retrieve a logger by doing ‘log =
     getLogger('app')’, calling ‘log.getChild('network.listen')’ is
     equivalent to ‘getLogger('app.network.listen')’.

   * The *note LoggerAdapter: d54. class gained an ‘isEnabledFor()’
     method that takes a `level' and returns whether the underlying
     logger would process a message of that level of importance.

也參考
......

PEP 391(1) - 基于字典的日志配置

     PEP 由 Vinay Sajip 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0391


File: python.info,  Node: PEP 3106 Dictionary Views,  Next: PEP 3137 The memoryview Object,  Prev: PEP 391 Dictionary-Based Configuration For Logging,  Up: Python 2 7 有什么新变化

1.11.8 PEP 3106: Dictionary Views
---------------------------------

The dictionary methods *note keys(): cf4, *note values(): cf6, and *note
items(): cf5. are different in Python 3.x.  They return an object called
a `view' instead of a fully materialized list.

It’s not possible to change the return values of *note keys(): cf4,
*note values(): cf6, and *note items(): cf5. in Python 2.7 because too
much code would break.  Instead the 3.x versions were added under the
new names ‘viewkeys()’, ‘viewvalues()’, and ‘viewitems()’.

     >>> 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])

Views can be iterated over, but the key and item views also behave like
sets.  The ‘&’ operator performs intersection, and ‘|’ performs a union:

     >>> 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])

The view keeps track of the dictionary and its contents change as the
dictionary is modified:

     >>> vk = d.viewkeys()
     >>> vk
     dict_keys([0, 130, 10, ..., 250])
     >>> d[260] = '&'
     >>> vk
     dict_keys([0, 130, 260, 10, ..., 250])

However, note that you can’t add or remove keys while you’re iterating
over the view:

     >>> 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

You can use the view methods in Python 2.x code, and the 2to3 converter
will change them to the standard *note keys(): cf4, *note values(): cf6,
and *note items(): cf5. methods.

也參考
......

PEP 3106(1) - 改造 dict.keys(), .values() 和 .items()

     PEP written by Guido van Rossum.  Backported to 2.7 by Alexandre
     Vassalotti; bpo-1967(2).

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3106

   (2) https://bugs.python.org/issue1967


File: python.info,  Node: PEP 3137 The memoryview Object,  Next: 其他语言特性修改<10>,  Prev: PEP 3106 Dictionary Views,  Up: Python 2 7 有什么新变化

1.11.9 PEP 3137: The memoryview Object
--------------------------------------

The *note memoryview: 386. object provides a view of another object’s
memory content that matches the *note bytes: 172. type’s interface.

     >>> 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>

The content of the view can be converted to a string of bytes or a list
of integers:

     >>> m2.tobytes()
     'abcdefghijklmnopqrstuvwxyz'
     >>> m2.tolist()
     [97, 98, 99, 100, 101, 102, 103, ... 121, 122]
     >>>

*note memoryview: 386. objects allow modifying the underlying object if
it’s a mutable object.

     >>> 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')
     >>>

也參考
......

PEP 3137(1) - 不变字节和可变缓冲区

     PEP written by Guido van Rossum.  Implemented by Travis Oliphant,
     Antoine Pitrou and others.  Backported to 2.7 by Antoine Pitrou;
     bpo-2396(2).

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3137

   (2) https://bugs.python.org/issue2396


File: python.info,  Node: 其他语言特性修改<10>,  Next: 新增和改进的模块,  Prev: PEP 3137 The memoryview Object,  Up: Python 2 7 有什么新变化

1.11.10 其他语言特性修改
------------------------

对Python 语言核心进行的小改动：

   * 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.  ‘{}’ continues to represent an
     empty dictionary; use ‘set()’ for an empty set.

          >>> {1, 2, 3, 4, 5}
          set([1, 2, 3, 4, 5])
          >>> set() # empty set
          set([])
          >>> {}    # empty dict
          {}

     Backported by Alexandre Vassalotti; bpo-2335(1).

   * Dictionary and set comprehensions are another feature backported
     from 3.x, generalizing list/generator comprehensions to use the
     literal syntax for sets and dictionaries.

          >>> {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(['', 'a', 'aa', 'aaa', 'aaaa', 'aaaaa'])

     Backported by Alexandre Vassalotti; bpo-2333(2).

   * The *note with: 7da. 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 ‘with’
     statement.  This means that:

          with A() as a, B() as b:
              ... suite of statements ...

     相当于:

          with A() as a:
              with B() as b:
                  ... suite of statements ...

     The ‘contextlib.nested()’ function provides a very similar
     function, so it’s no longer necessary and has been deprecated.

     (Proposed in ‘https://codereview.appspot.com/53094’; implemented by
     Georg Brandl.)

   * Conversions between floating-point numbers and strings are now
     correctly rounded on most platforms.  These conversions occur in
     many different places: *note str(): 205. on floats and complex
     numbers; the *note float: 1fd. and *note complex: 2c1.
     constructors; numeric formatting; serializing and deserializing
     floats and complex numbers using the *note marshal: b0, *note
     pickle: ca. and *note json: a4. modules; parsing of float and
     imaginary literals in Python code; and *note Decimal: 2c0.-to-float
     conversion.

     Related to this, the *note repr(): 8b9. of a floating-point number
     `x' now returns a result based on the shortest decimal string
     that’s guaranteed to round back to `x' under correct rounding (with
     round-half-to-even rounding mode).  Previously it gave a string
     based on rounding x to 17 decimal digits.

     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 *note sys.float_repr_style: d58, which will be ‘short’ if
     the new code is in use and ‘legacy’ if it isn’t.

     Implemented by Eric Smith and Mark Dickinson, using David Gay’s
     ‘dtoa.c’ library; bpo-7117(3).

   * 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:

          >>> n = 295147905179352891391
          >>> float(n)
          2.9514790517935283e+20
          >>> n - long(float(n))
          65535L

     Python 2.7’s floating-point result is larger, but much closer to
     the true value:

          >>> n = 295147905179352891391
          >>> float(n)
          2.9514790517935289e+20
          >>> n - long(float(n))
          -1L

     (Implemented by Mark Dickinson; bpo-3166(4).)

     Integer division is also more accurate in its rounding behaviours.
     (Also implemented by Mark Dickinson; bpo-1811(5).)

   * Implicit coercion for complex numbers has been removed; the
     interpreter will no longer ever attempt to call a ‘__coerce__()’
     method on complex objects.  (Removed by Meador Inge and Mark
     Dickinson; bpo-5211(6).)

   * The *note str.format(): 5d4. method now supports automatic
     numbering of the replacement fields.  This makes using *note
     str.format(): 5d4. more closely resemble using ‘%s’ formatting:

          >>> '{}:{}:{}'.format(2009, 04, 'Sunday')
          '2009:4:Sunday'
          >>> '{}:{}:{day}'.format(2009, 4, day='Sunday')
          '2009:4:Sunday'

     The auto-numbering takes the fields from left to right, so the
     first ‘{...}’ specifier will use the first argument to *note
     str.format(): 5d4, 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(7).)

     Complex numbers now correctly support usage with *note format():
     5d5, 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 ‘1.5+3j’ output.  (Contributed by Eric
     Smith; bpo-1588(8) and bpo-7988(9).)

     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(10).)

     A low-level change: the *note object.__format__(): a2f. method now
     triggers a *note PendingDeprecationWarning: 15c. if it’s passed a
     format string, because the *note __format__(): a2f. method for
     *note object: 3d2. 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(11).)

   * The *note int(): 204. and ‘long()’ types gained a ‘bit_length’
     method that returns the number of bits necessary to represent its
     argument in binary:

          >>> n = 37
          >>> bin(n)
          '0b100101'
          >>> n.bit_length()
          6
          >>> n = 2**123-1
          >>> n.bit_length()
          123
          >>> (n+1).bit_length()
          124

     (Contributed by Fredrik Johansson and Victor Stinner;
     bpo-3439(12).)

   * The *note import: ce7. statement will no longer try an absolute
     import if a relative import (e.g.  ‘from .os import sep’) fails.
     This fixes a bug, but could possibly break certain ‘import’
     statements that were only working by accident.  (Fixed by Meador
     Inge; bpo-7902(13).)

   * It’s now possible for a subclass of the built-in ‘unicode’ type to
     override the ‘__unicode__()’ method.  (Implemented by Victor
     Stinner; bpo-1583863(14).)

   * The *note bytearray: 173. type’s *note translate(): d59. method now
     accepts ‘None’ as its first argument.  (Fixed by Georg Brandl;
     bpo-4759(15).)

   * When using ‘@classmethod’ and ‘@staticmethod’ to wrap methods as
     class or static methods, the wrapper object now exposes the wrapped
     function as their ‘__func__’ attribute.  (Contributed by Amaury
     Forgeot d’Arc, after a suggestion by George Sakkis; bpo-5982(16).)

   * When a restricted set of attributes were set using ‘__slots__’,
     deleting an unset attribute would not raise *note AttributeError:
     4a1. as you would expect.  Fixed by Benjamin Peterson;
     bpo-7604(17).)

   * 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(18); CP858 contributed by Tim Hatch in
     bpo-8016(19).)

   * The ‘file’ object will now set the ‘filename’ attribute on the
     *note IOError: a73. exception when trying to open a directory on
     POSIX platforms (noted by Jan Kaliszewski; bpo-4764(20)), 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(21)).

   * The Python tokenizer now translates line endings itself, so the
     *note compile(): 2e7. built-in function now accepts code using any
     line-ending convention.  Additionally, it no longer requires that
     the code end in a newline.

   * Extra parentheses in function definitions are illegal in Python
     3.x, meaning that you get a syntax error from ‘def f((x)): pass’.
     In Python3-warning mode, Python 2.7 will now warn about this odd
     usage.  (Noted by James Lingard; bpo-7362(22).)

   * 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(23).)

   * 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(24)).

* Menu:

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

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue2335

   (2) https://bugs.python.org/issue2333

   (3) https://bugs.python.org/issue7117

   (4) https://bugs.python.org/issue3166

   (5) https://bugs.python.org/issue1811

   (6) https://bugs.python.org/issue5211

   (7) https://bugs.python.org/issue5237

   (8) https://bugs.python.org/issue1588

   (9) https://bugs.python.org/issue7988

   (10) https://bugs.python.org/issue3382

   (11) https://bugs.python.org/issue7994

   (12) https://bugs.python.org/issue3439

   (13) https://bugs.python.org/issue7902

   (14) https://bugs.python.org/issue1583863

   (15) https://bugs.python.org/issue4759

   (16) https://bugs.python.org/issue5982

   (17) https://bugs.python.org/issue7604

   (18) https://bugs.python.org/issue1616979

   (19) https://bugs.python.org/issue8016

   (20) https://bugs.python.org/issue4764

   (21) https://bugs.python.org/issue5677

   (22) https://bugs.python.org/issue7362

   (23) https://bugs.python.org/issue8268

   (24) https://bugs.python.org/issue7140


File: python.info,  Node: Interpreter Changes,  Next: 性能优化<9>,  Up: 其他语言特性修改<10>

1.11.10.1 Interpreter Changes
.............................

A new environment variable, *note PYTHONWARNINGS: 51b, allows
controlling warnings.  It should be set to a string containing warning
settings, equivalent to those used with the *note -W: 15b. switch,
separated by commas.  (Contributed by Brian Curtin; bpo-7301(1).)

For example, the following setting will print warnings every time they
occur, but turn warnings from the ‘Cookie’ module into an error.  (The
exact syntax for setting an environment variable varies across operating
systems and shells.)

     export PYTHONWARNINGS=all,error:::Cookie:0

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue7301


File: python.info,  Node: 性能优化<9>,  Prev: Interpreter Changes,  Up: 其他语言特性修改<10>

1.11.10.2 性能优化
..................

Several performance enhancements have been added:

   * A new opcode was added to perform the initial setup for *note with:
     7da. statements, looking up the *note __enter__(): d5d. and *note
     __exit__(): d5e. methods.  (Contributed by Benjamin Peterson.)

   * 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(1).)

   * 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(2).)

   * Long integers are now stored internally either in base ‘2**15’ or
     in base ‘2**30’, the base being determined at build time.
     Previously, they were always stored in base ‘2**15’.  Using base
     ‘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 ‘2**30’ on 64-bit machines
     and base ‘2**15’ on 32-bit machines; on Unix, there’s a new
     configure option ‘--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 ‘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:

          >>> import sys
          >>> sys.long_info
          sys.long_info(bits_per_digit=30, sizeof_digit=4)

     （由 Mark Dickinson在 bpo-4258(3) 贡献）

     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(4).)

   * 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(5).)
     Bitwise operations are also significantly faster (initial patch by
     Gregory Smith; bpo-1087418(6)).

   * The implementation of ‘%’ 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 ‘%’ with
     strings, such as templating libraries.  (Implemented by Collin
     Winter; bpo-5176(7).)

   * List comprehensions with an ‘if’ condition are compiled into faster
     bytecode.  (Patch by Antoine Pitrou, back-ported to 2.7 by Jeffrey
     Yasskin; bpo-4715(8).)

   * 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(9).)

   * The ‘split()’, ‘replace()’, ‘rindex()’, ‘rpartition()’, and
     ‘rsplit()’ methods of string-like types (strings, Unicode strings,
     and *note bytearray: 173. 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(10) and bpo-7622(11).)

   * The *note pickle: ca. and ‘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(12).)

   * The ‘cPickle’ module now special-cases dictionaries, nearly halving
     the time required to pickle them.  (Contributed by Collin Winter;
     bpo-5670(13).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue4074

   (2) https://bugs.python.org/issue4688

   (3) https://bugs.python.org/issue4258

   (4) https://bugs.python.org/issue5260

   (5) https://bugs.python.org/issue5512

   (6) https://bugs.python.org/issue1087418

   (7) https://bugs.python.org/issue5176

   (8) https://bugs.python.org/issue4715

   (9) https://bugs.python.org/issue6713

   (10) https://bugs.python.org/issue7462

   (11) https://bugs.python.org/issue7622

   (12) https://bugs.python.org/issue5084

   (13) https://bugs.python.org/issue5670


File: python.info,  Node: 新增和改进的模块,  Next: 构建和 C API 的改变<8>,  Prev: 其他语言特性修改<10>,  Up: Python 2 7 有什么新变化

1.11.11 新增和改进的模块
------------------------

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 ‘Misc/NEWS’
file in the source tree for a more complete list of changes, or look
through the Subversion logs for all the details.

   * The *note bdb: e. module’s base debugging class *note Bdb: d60.
     gained a feature for skipping modules.  The constructor now takes
     an iterable containing glob-style patterns such as ‘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(1).)

   * The *note binascii: f. module now supports the buffer API, so it
     can be used with *note memoryview: 386. instances and other similar
     buffer objects.  (Backported from 3.x by Florent Xicluna;
     bpo-7703(2).)

   * Updated module: the ‘bsddb’ module has been updated from
     4.7.2devel9 to version 4.8.4 of the pybsddb package(3).  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(4).  The pybsddb changelog can be read
     at ‘http://hg.jcea.es/pybsddb/file/tip/ChangeLog’.)

   * The *note bz2: 13. module’s *note BZ2File: 224. now supports the
     context management protocol, so you can write ‘with
     bz2.BZ2File(...) as f:’.  (Contributed by Hagen Fürstenau;
     bpo-3860(5).)

   * New class: the *note Counter: ab9. class in the *note collections:
     1d. module is useful for tallying data.  *note Counter: ab9.
     instances behave mostly like dictionaries but return zero for
     missing keys instead of raising a *note KeyError: 3e9.:

          >>> 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

     There are three additional *note Counter: ab9. methods.  *note
     most_common(): d61. returns the N most common elements and their
     counts.  *note elements(): d62. returns an iterator over the
     contained elements, repeating each element as many times as its
     count.  *note subtract(): c2c. takes an iterable and subtracts one
     for each element instead of adding; if the argument is a dictionary
     or another ‘Counter’, the counts are subtracted.

          >>> 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

     Contributed by Raymond Hettinger; bpo-1696199(6).

     New class: *note OrderedDict: 2ea. is described in the earlier
     section *note PEP 372; Adding an Ordered Dictionary to collections:
     d48.

     New method: The *note deque: 62a. data type now has a *note
     count(): c2e. method that returns the number of contained elements
     equal to the supplied argument `x', and a *note reverse(): c2f.
     method that reverses the elements of the deque in-place.  *note
     deque: 62a. also exposes its maximum length as the read-only *note
     maxlen: d63. attribute.  (Both features added by Raymond
     Hettinger.)

     The *note namedtuple: 1a1. class now has an optional `rename'
     parameter.  If `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:

          >>> from collections import namedtuple
          >>> T = namedtuple('T', ['field1', '$illegal', 'for', 'field2'], rename=True)
          >>> T._fields
          ('field1', '_1', '_2', 'field2')

     (Added by Raymond Hettinger; bpo-1818(7).)

     Finally, the ‘Mapping’ abstract base class now returns *note
     NotImplemented: 202. if a mapping is compared to another type that
     isn’t a ‘Mapping’.  (Fixed by Daniel Stutzbach; bpo-8729(8).)

   * Constructors for the parsing classes in the ‘ConfigParser’ module
     now take an `allow_no_value' parameter, defaulting to false; if
     true, options without values will be allowed.  For 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'

     (Contributed by Mats Kindahl; bpo-7005(9).)

   * Deprecated function: ‘contextlib.nested()’, which allows handling
     more than one context manager with a single *note with: 7da.
     statement, has been deprecated, because the ‘with’ statement now
     supports multiple context managers.

   * The ‘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(10).)

   * The *note copy: 25. module’s *note deepcopy(): 4d2. function will
     now correctly copy bound instance methods.  (Implemented by Robert
     Collins; bpo-1515(11).)

   * The *note ctypes: 2a. module now always converts ‘None’ to a C
     ‘NULL’ pointer for arguments declared as pointers.  (Changed by
     Thomas Heller; bpo-4606(12).)  The underlying libffi library(13)
     has been updated to version 3.0.9, containing various fixes for
     different platforms.  (Updated by Matthias Klose; bpo-8142(14).)

   * New method: the *note datetime: 30. module’s *note timedelta: 2ca.
     class gained a *note total_seconds(): d64. method that returns the
     number of seconds in the duration.  (Contributed by Brian Quinlan;
     bpo-5788(15).)

   * New method: the *note Decimal: 2c0. class gained a *note
     from_float(): c51. class method that performs an exact conversion
     of a floating-point number to a *note Decimal: 2c0.  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,
     ‘Decimal.from_float(0.1)’ returns
     ‘Decimal('0.1000000000000000055511151231257827021181583404541015625')’.
     (Implemented by Raymond Hettinger; bpo-4796(16).)

     Comparing instances of *note Decimal: 2c0. 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 ‘Decimal’ and floating-point in other operations such as
     addition, since you should be explicitly choosing how to convert
     between float and *note Decimal: 2c0.  (Fixed by Mark Dickinson;
     bpo-2531(17).)

     The constructor for *note Decimal: 2c0. now accepts floating-point
     numbers (added by Raymond Hettinger; bpo-8257(18)) and non-European
     Unicode characters such as Arabic-Indic digits (contributed by Mark
     Dickinson; bpo-6595(19)).

     Most of the methods of the *note Context: acf. class now accept
     integers as well as *note Decimal: 2c0. instances; the only
     exceptions are the *note canonical(): d65. and *note
     is_canonical(): d66. methods.  (Patch by Juan José Conti;
     bpo-7633(20).)

     When using *note Decimal: 2c0. instances with a string’s *note
     format(): 5d4. 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(21).)

     Comparisons involving a signaling NaN value (or ‘sNAN’) now signal
     ‘InvalidOperation’ instead of silently returning a true or false
     value depending on the comparison operator.  Quiet NaN values (or
     ‘NaN’) are now hashable.  (Fixed by Mark Dickinson; bpo-7279(22).)

   * The *note difflib: 36. module now produces output that is more
     compatible with modern ‘diff’/‘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(23).)

   * The Distutils ‘sdist’ command now always regenerates the ‘MANIFEST’
     file, since even if the ‘MANIFEST.in’ or ‘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(24).)

   * The *note doctest: 66. module’s ‘IGNORE_EXCEPTION_DETAIL’ flag will
     now ignore the name of the module containing the exception being
     tested.  (Patch by Lennart Regebro; bpo-7490(25).)

   * The *note email: 67. module’s *note Message: 63b. class will now
     accept a Unicode-valued payload, automatically converting the
     payload to the encoding specified by ‘output_charset’.  (Added by
     R. David Murray; bpo-1368247(26).)

   * The *note Fraction: 2be. class now accepts a single float or *note
     Decimal: 2c0. instance, or two rational numbers, as arguments to
     its constructor.  (Implemented by Mark Dickinson; rationals added
     in bpo-5812(27), and float/decimal in bpo-8294(28).)

     Ordering comparisons (‘<’, ‘<=’, ‘>’, ‘>=’) between fractions and
     complex numbers now raise a *note TypeError: 1fe.  This fixes an
     oversight, making the *note Fraction: 2be. match the other numeric
     types.

   * New class: *note FTP_TLS: 1a7. in the *note ftplib: 82. module
     provides secure FTP connections using TLS encapsulation of
     authentication as well as subsequent control and data transfers.
     (Contributed by Giampaolo Rodola; bpo-2054(29).)

     The *note storbinary(): d67. method for binary uploads can now
     restart uploads thanks to an added `rest' parameter (patch by Pablo
     Mouzo; bpo-6845(30).)

   * New class decorator: *note total_ordering(): 938. in the *note
     functools: 83. module takes a class that defines an *note __eq__():
     44b. method and one of *note __lt__(): cfe, *note __le__(): d68,
     *note __gt__(): d69, or *note __ge__(): d6a, and generates the
     missing comparison methods.  Since the ‘__cmp__()’ method is being
     deprecated in Python 3.x, this decorator makes it easier to define
     ordered classes.  (Added by Raymond Hettinger; bpo-5479(31).)

     New function: *note cmp_to_key(): c28. will take an old-style
     comparison function that expects two arguments and return a new
     callable that can be used as the `key' parameter to functions such
     as *note sorted(): 546, *note min(): 8f6. and *note max(): 8f7,
     etc.  The primary intended use is to help with making code
     compatible with Python 3.x.  (Added by Raymond Hettinger.)

   * New function: the *note gc: 84. module’s *note is_tracked(): d6b.
     returns true if a given instance is tracked by the garbage
     collector, false otherwise.  (Contributed by Antoine Pitrou;
     bpo-4688(32).)

   * The *note gzip: 8b. module’s *note GzipFile: 206. now supports the
     context management protocol, so you can write ‘with
     gzip.GzipFile(...) as f:’ (contributed by Hagen Fürstenau;
     bpo-3860(33)), and it now implements the *note io.BufferedIOBase:
     67f. ABC, so you can wrap it with *note io.BufferedReader: c5b. for
     faster processing (contributed by Nir Aides; bpo-7471(34)).  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(35).)

     Files in gzip format can be padded with trailing zero bytes; the
     *note gzip: 8b. module will now consume these trailing bytes.
     (Fixed by Tadek Pietraszek and Brian Curtin; bpo-2846(36).)

   * New attribute: the *note hashlib: 8c. module now has an
     ‘algorithms’ attribute containing a tuple naming the supported
     algorithms.  In Python 2.7, ‘hashlib.algorithms’ contains ‘('md5',
     'sha1', 'sha224', 'sha256', 'sha384', 'sha512')’.  (Contributed by
     Carl Chenet; bpo-7418(37).)

   * The default ‘HTTPResponse’ class used by the ‘httplib’ module now
     supports buffering, resulting in much faster reading of HTTP
     responses.  (Contributed by Kristján Valur Jónsson; bpo-4879(38).)

     The ‘HTTPConnection’ and ‘HTTPSConnection’ classes now support a
     `source_address' parameter, a ‘(host, port)’ 2-tuple giving the
     source address that will be used for the connection.  (Contributed
     by Eldon Ziegler; bpo-3972(39).)

   * The ‘ihooks’ module now supports relative imports.  Note that
     ‘ihooks’ is an older module for customizing imports, superseded by
     the ‘imputil’ module added in Python 2.0.  (Relative import support
     added by Neil Schemenauer.)

   * The *note imaplib: 97. module now supports IPv6 addresses.
     (Contributed by Derek Morr; bpo-1655(40).)

   * New function: the *note inspect: a0. module’s *note getcallargs():
     8a4. 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:

          >>> 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)

     由 Georg Sakkis 在 bpo-3135(41) 中贡献。

   * Updated module: The *note io: a1. 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 ‘_pyio’ module.

     One minor resulting change: the *note io.TextIOBase: d01. class now
     has an ‘errors’ attribute giving the error setting used for
     encoding and decoding errors (one of ‘'strict'’, ‘'replace'’,
     ‘'ignore'’).

     The *note io.FileIO: d6c. class now raises an *note OSError: 304.
     when passed an invalid file descriptor.  (Implemented by Benjamin
     Peterson; bpo-4991(42).)  The *note truncate(): d6d. 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(43).)

   * New function: ‘itertools.compress(data, selectors)’ takes two
     iterators.  Elements of `data' are returned if the corresponding
     value in `selectors' is true:

          itertools.compress('ABCDEF', [1,0,1,0,1,1]) =>
            A, C, E, F

     New function: ‘itertools.combinations_with_replacement(iter, r)’
     returns all the possible `r'-length combinations of elements from
     the iterable `iter'.  Unlike *note combinations(): d6e, individual
     elements can be repeated in the generated combinations:

          itertools.combinations_with_replacement('abc', 2) =>
            ('a', 'a'), ('a', 'b'), ('a', 'c'),
            ('b', 'b'), ('b', 'c'), ('c', 'c')

     Note that elements are treated as unique depending on their
     position in the input, not their actual values.

     The *note itertools.count(): ce5. function now has a `step'
     argument that allows incrementing by values other than 1.  *note
     count(): ce5. also now allows keyword arguments, and using
     non-integer values such as floats or *note Decimal: 2c0. instances.
     (Implemented by Raymond Hettinger; bpo-5032(44).)

     *note itertools.combinations(): d6e. and *note itertools.product():
     d6f. previously raised *note ValueError: 16d. for values of `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(45).)

   * Updated module: The *note json: a4. 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(46).)

     To support the new *note collections.OrderedDict: 2ea. type, *note
     json.load(): 659. now has an optional `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(47).)

   * The *note mailbox: ae. module’s *note Maildir: d70. 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(48),
     bpo-6896(49).)

   * New functions: the *note math: b1. module gained *note erf(): 553.
     and *note erfc(): 554. for the error function and the complementary
     error function, *note expm1(): c3a. which computes ‘e**x - 1’ with
     more precision than using *note exp(): d71. and subtracting 1,
     *note gamma(): c3b. for the Gamma function, and *note lgamma():
     c3c. for the natural log of the Gamma function.  (Contributed by
     Mark Dickinson and nirinA raseliarison; bpo-3366(50).)

   * The *note multiprocessing: b7. module’s ‘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(51).)

     The ‘Pool’ class, which controls a pool of worker processes, now
     has an optional `maxtasksperchild' parameter.  Worker processes
     will perform the specified number of tasks and then exit, causing
     the ‘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(52).)

   * The *note nntplib: c0. module now supports IPv6 addresses.
     (Contributed by Derek Morr; bpo-1664(53).)

   * New functions: the *note os: c4. module wraps the following POSIX
     system calls: *note getresgid(): d72. and *note getresuid(): d73,
     which return the real, effective, and saved GIDs and UIDs; *note
     setresgid(): d74. and *note setresuid(): d75, which set real,
     effective, and saved GIDs and UIDs to new values; *note
     initgroups(): d76, which initialize the group access list for the
     current process.  (GID/UID functions contributed by Travis H.;
     bpo-6508(54).  Support for initgroups added by Jean-Paul Calderone;
     bpo-7333(55).)

     The *note os.fork(): a42. function now re-initializes the import
     lock in the child process; this fixes problems on Solaris when
     *note fork(): a42. is called from a thread.  (Fixed by Zsolt
     Cserna; bpo-7242(56).)

   * In the *note os.path: c5. module, the *note normpath(): d77. and
     *note abspath(): d78. functions now preserve Unicode; if their
     input path is a Unicode string, the return value is also a Unicode
     string.  (*note normpath(): d77. fixed by Matt Giuca in
     bpo-5827(57); *note abspath(): d78. fixed by Ezio Melotti in
     bpo-3426(58).)

   * The *note pydoc: d9. module now has help for the various symbols
     that Python uses.  You can now do ‘help('<<')’ or ‘help('@')’, for
     example.  (Contributed by David Laban; bpo-4739(59).)

   * The *note re: dd. module’s *note split(): 4d0, *note sub(): 579,
     and *note subn(): 823. now accept an optional `flags' argument, for
     consistency with the other functions in the module.  (Added by
     Gregory P. Smith.)

   * New function: *note run_path(): d79. in the *note runpy: e2. module
     will execute the code at a provided `path' argument.  `path' can be
     the path of a Python source file (‘example.py’), a compiled
     bytecode file (‘example.pyc’), a directory (‘./package/’), or a zip
     archive (‘example.zip’).  If a directory or zip path is provided,
     it will be added to the front of ‘sys.path’ and the module *note
     __main__: 1. will be imported.  It’s expected that the directory or
     zip contains a ‘__main__.py’; if it doesn’t, some other
     ‘__main__.py’ might be imported from a location later in
     ‘sys.path’.  This makes more of the machinery of *note runpy: e2.
     available to scripts that want to mimic the way Python’s command
     line processes an explicit path name.  (Added by Nick Coghlan;
     bpo-6816(60).)

   * New function: in the *note shutil: e9. module, *note
     make_archive(): 348. 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é.)

     *note shutil: e9.’s *note copyfile(): 382. and *note copytree():
     347. functions now raise a ‘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(61).)

   * The *note signal: ea. 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(62).)

   * New functions: in the *note site: eb. module, three new functions
     return various site- and user-specific paths.  *note
     getsitepackages(): ca1. returns a list containing all global
     site-packages directories, *note getusersitepackages(): ca3.
     returns the path of the user’s site-packages directory, and *note
     getuserbase(): ca2. returns the value of the ‘USER_BASE’
     environment variable, giving the path to a directory that can be
     used to store data.  (Contributed by Tarek Ziadé; bpo-6693(63).)

     The *note site: eb. module now reports exceptions occurring when
     the ‘sitecustomize’ module is imported, and will no longer catch
     and swallow the *note KeyboardInterrupt: 2cc. exception.  (Fixed by
     Victor Stinner; bpo-3137(64).)

   * The *note create_connection(): c6f. function gained a
     `source_address' parameter, a ‘(host, port)’ 2-tuple giving the
     source address that will be used for the connection.  (Contributed
     by Eldon Ziegler; bpo-3972(65).)

     The *note recv_into(): d7a. and *note recvfrom_into(): d7b. methods
     will now write into objects that support the buffer API, most
     usefully the *note bytearray: 173. and *note memoryview: 386.
     objects.  (Implemented by Antoine Pitrou; bpo-8104(66).)

   * The ‘SocketServer’ module’s ‘TCPServer’ class now supports socket
     timeouts and disabling the Nagle algorithm.  The
     ‘disable_nagle_algorithm’ class attribute defaults to ‘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 ‘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, ‘handle_timeout()’ will be
     called and ‘handle_request()’ will return.  (Contributed by
     Kristján Valur Jónsson; bpo-6192(67) and bpo-6267(68).)

   * Updated module: the *note sqlite3: f2. module has been updated to
     version 2.6.0 of the pysqlite package(69).  Version 2.6.0 includes
     a number of bugfixes, and adds the ability to load SQLite
     extensions from shared libraries.  Call the
     ‘enable_load_extension(True)’ method to enable extensions, and then
     call *note load_extension(): c6b. to load a particular shared
     library.  (Updated by Gerhard Häring.)

   * The *note ssl: f3. module’s *note SSLSocket: 192. objects now
     support the buffer API, which fixed a test suite failure (fix by
     Antoine Pitrou; bpo-7133(70)) and automatically set OpenSSL’s
     ‘SSL_MODE_AUTO_RETRY’, which will prevent an error code being
     returned from ‘recv()’ operations that trigger an SSL renegotiation
     (fix by Antoine Pitrou; bpo-8222(71)).

     The *note ssl.wrap_socket(): 570. constructor function now takes a
     `ciphers' argument that’s a string listing the encryption
     algorithms to be allowed; the format of the string is described in
     the OpenSSL documentation(72).  (Added by Antoine Pitrou;
     bpo-8322(73).)

     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(74).)

     The version of OpenSSL being used is now available as the module
     attributes *note ssl.OPENSSL_VERSION: c72. (a string), *note
     ssl.OPENSSL_VERSION_INFO: c73. (a 5-tuple), and *note
     ssl.OPENSSL_VERSION_NUMBER: c74. (an integer).  (Added by Antoine
     Pitrou; bpo-8321(75).)

   * The *note struct: f8. module will no longer silently ignore
     overflow errors when a value is too large for a particular integer
     format code (one of ‘bBhHiIlLqQ’); it now always raises a *note
     struct.error: d7c. exception.  (Changed by Mark Dickinson;
     bpo-1523(76).)  The *note pack(): cd6. function will also attempt
     to use *note __index__(): 2c2. to convert and pack non-integers
     before trying the *note __int__(): 2c3. method or reporting an
     error.  (Changed by Mark Dickinson; bpo-8300(77).)

   * New function: the *note subprocess: f9. module’s *note
     check_output(): 9c1. 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 *note CalledProcessError:
     d7d. exception otherwise.

          >>> 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

     （由 Gregory P. Smith 贡献）

     The *note subprocess: f9. module will now retry its internal system
     calls on receiving an ‘EINTR’ signal.  (Reported by several people;
     final patch by Gregory P. Smith in bpo-1068268(78).)

   * New function: *note is_declared_global(): d7e. in the *note
     symtable: fc. module returns true for variables that are explicitly
     declared to be global, false for ones that are implicitly global.
     (Contributed by Jeremy Hylton.)

   * The *note syslog: ff. module will now use the value of
     ‘sys.argv[0]’ as the identifier instead of the previous default
     value of ‘'python'’.  (Changed by Sean Reifschneider;
     bpo-8451(79).)

   * The ‘sys.version_info’ value is now a named tuple, with attributes
     named ‘major’, ‘minor’, ‘micro’, ‘releaselevel’, and ‘serial’.
     (Contributed by Ross Light; bpo-4285(80).)

     *note sys.getwindowsversion(): 68c. also returns a named tuple,
     with attributes named ‘major’, ‘minor’, ‘build’, *note platform:
     ce, ‘service_pack’, ‘service_pack_major’, ‘service_pack_minor’,
     ‘suite_mask’, and ‘product_type’.  (Contributed by Brian Curtin;
     bpo-7766(81).)

   * The *note tarfile: 101. 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(82).)

     *note tarfile: 101. now supports filtering the *note TarInfo: c5e.
     objects being added to a tar file.  When you call *note add(): 57a,
     you may supply an optional `filter' argument that’s a callable.
     The `filter' callable will be passed the *note TarInfo: c5e. for
     every file being added, and can modify and return it.  If the
     callable returns ‘None’, the file will be excluded from the
     resulting archive.  This is more powerful than the existing
     `exclude' argument, which has therefore been deprecated.  (Added by
     Lars Gustäbel; bpo-6856(83).)  The *note TarFile: c5d. class also
     now supports the context management protocol.  (Added by Lars
     Gustäbel; bpo-7232(84).)

   * The *note wait(): d7f. method of the *note threading.Event: b85.
     class now returns the internal flag on exit.  This means the method
     will usually return true because *note wait(): d7f. 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(85).)

   * The Unicode database provided by the *note unicodedata: 123. module
     is now used internally to determine which characters are numeric,
     whitespace, or represent line breaks.  The database also includes
     information from the ‘Unihan.txt’ data file (patch by Anders
     Chrigström and Amaury Forgeot d’Arc; bpo-1571184(86)) and has been
     updated to version 5.2.0 (updated by Florent Xicluna;
     bpo-8024(87)).

   * The ‘urlparse’ module’s ‘urlsplit()’ now handles unknown URL
     schemes in a fashion compliant with RFC 3986(88): if the URL is of
     the form ‘"<something>://..."’, the text before the ‘://’ 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:

          >>> import urlparse
          >>> urlparse.urlsplit('invented://host/filename?query')
          ('invented', '', '//host/filename?query', '', '')

     Python 2.7 (and Python 2.6.5) will return:

          >>> import urlparse
          >>> urlparse.urlsplit('invented://host/filename?query')
          ('invented', 'host', '/filename?query', '', '')

     (Python 2.7 actually produces slightly different output, since it
     returns a named tuple instead of a standard tuple.)

     The ‘urlparse’ module also supports IPv6 literal addresses as
     defined by RFC 2732(89) (contributed by Senthil Kumaran;
     bpo-2987(90)).

          >>> urlparse.urlparse('http://[1080::8:800:200C:417A]/foo')
          ParseResult(scheme='http', netloc='[1080::8:800:200C:417A]',
                      path='/foo', params='', query='', fragment='')

   * New class: the *note WeakSet: d80. class in the *note weakref: 131.
     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.)

   * The ElementTree library, ‘xml.etree’, no longer escapes ampersands
     and angle brackets when outputting an XML processing instruction
     (which looks like ‘<?xml-stylesheet href="#style1"?>’) or comment
     (which looks like ‘<!-- comment -->’).  (Patch by Neil Muller;
     bpo-2746(91).)

   * The XML-RPC client and server, provided by the ‘xmlrpclib’ and
     ‘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 ‘encode_threshold’ attribute of
     ‘SimpleXMLRPCRequestHandler’, which contains a size in bytes;
     responses larger than this will be compressed.  (Contributed by
     Kristján Valur Jónsson; bpo-6267(92).)

   * The *note zipfile: 14b. module’s *note ZipFile: 522. now supports
     the context management protocol, so you can write ‘with
     zipfile.ZipFile(...) as f:’.  (Contributed by Brian Curtin;
     bpo-5511(93).)

     *note zipfile: 14b. now also supports archiving empty directories
     and extracts them correctly.  (Fixed by Kuba Wieczorek;
     bpo-4710(94).)  Reading files out of an archive is faster, and
     interleaving *note read(): d81. and ‘readline()’ now works
     correctly.  (Contributed by Nir Aides; bpo-7610(95).)

     The *note is_zipfile(): d82. function now accepts a file object, in
     addition to the path names accepted in earlier versions.
     (Contributed by Gabriel Genellina; bpo-4756(96).)

     The *note writestr(): d83. method now has an optional
     `compress_type' parameter that lets you override the default
     compression method specified in the *note ZipFile: 522.
     constructor.  (Contributed by Ronald Oussoren; bpo-6003(97).)

* Menu:

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

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5142

   (2) https://bugs.python.org/issue7703

   (3) https://www.jcea.es/programacion/pybsddb.htm

   (4) https://bugs.python.org/issue8156

   (5) https://bugs.python.org/issue3860

   (6) https://bugs.python.org/issue1696199

   (7) https://bugs.python.org/issue1818

   (8) https://bugs.python.org/issue8729

   (9) https://bugs.python.org/issue7005

   (10) https://bugs.python.org/issue3924

   (11) https://bugs.python.org/issue1515

   (12) https://bugs.python.org/issue4606

   (13) https://sourceware.org/libffi/

   (14) https://bugs.python.org/issue8142

   (15) https://bugs.python.org/issue5788

   (16) https://bugs.python.org/issue4796

   (17) https://bugs.python.org/issue2531

   (18) https://bugs.python.org/issue8257

   (19) https://bugs.python.org/issue6595

   (20) https://bugs.python.org/issue7633

   (21) https://bugs.python.org/issue6857

   (22) https://bugs.python.org/issue7279

   (23) https://bugs.python.org/issue7585

   (24) https://bugs.python.org/issue8688

   (25) https://bugs.python.org/issue7490

   (26) https://bugs.python.org/issue1368247

   (27) https://bugs.python.org/issue5812

   (28) https://bugs.python.org/issue8294

   (29) https://bugs.python.org/issue2054

   (30) https://bugs.python.org/issue6845

   (31) https://bugs.python.org/issue5479

   (32) https://bugs.python.org/issue4688

   (33) https://bugs.python.org/issue3860

   (34) https://bugs.python.org/issue7471

   (35) https://bugs.python.org/issue4272

   (36) https://bugs.python.org/issue2846

   (37) https://bugs.python.org/issue7418

   (38) https://bugs.python.org/issue4879

   (39) https://bugs.python.org/issue3972

   (40) https://bugs.python.org/issue1655

   (41) https://bugs.python.org/issue3135

   (42) https://bugs.python.org/issue4991

   (43) https://bugs.python.org/issue6939

   (44) https://bugs.python.org/issue5032

   (45) https://bugs.python.org/issue4816

   (46) https://bugs.python.org/issue4136

   (47) https://bugs.python.org/issue5381

   (48) https://bugs.python.org/issue1607951

   (49) https://bugs.python.org/issue6896

   (50) https://bugs.python.org/issue3366

   (51) https://bugs.python.org/issue5585

   (52) https://bugs.python.org/issue6963

   (53) https://bugs.python.org/issue1664

   (54) https://bugs.python.org/issue6508

   (55) https://bugs.python.org/issue7333

   (56) https://bugs.python.org/issue7242

   (57) https://bugs.python.org/issue5827

   (58) https://bugs.python.org/issue3426

   (59) https://bugs.python.org/issue4739

   (60) https://bugs.python.org/issue6816

   (61) https://bugs.python.org/issue3002

   (62) https://bugs.python.org/issue8354

   (63) https://bugs.python.org/issue6693

   (64) https://bugs.python.org/issue3137

   (65) https://bugs.python.org/issue3972

   (66) https://bugs.python.org/issue8104

   (67) https://bugs.python.org/issue6192

   (68) https://bugs.python.org/issue6267

   (69) https://github.com/ghaering/pysqlite

   (70) https://bugs.python.org/issue7133

   (71) https://bugs.python.org/issue8222

   (72) 
https://www.openssl.org/docs/manmaster/man1/ciphers.html#CIPHER-LIST-FORMAT

   (73) https://bugs.python.org/issue8322

   (74) https://bugs.python.org/issue8484

   (75) https://bugs.python.org/issue8321

   (76) https://bugs.python.org/issue1523

   (77) https://bugs.python.org/issue8300

   (78) https://bugs.python.org/issue1068268

   (79) https://bugs.python.org/issue8451

   (80) https://bugs.python.org/issue4285

   (81) https://bugs.python.org/issue7766

   (82) https://bugs.python.org/issue7357

   (83) https://bugs.python.org/issue6856

   (84) https://bugs.python.org/issue7232

   (85) https://bugs.python.org/issue1674032

   (86) https://bugs.python.org/issue1571184

   (87) https://bugs.python.org/issue8024

   (88) https://tools.ietf.org/html/rfc3986.html

   (89) https://tools.ietf.org/html/rfc2732.html

   (90) https://bugs.python.org/issue2987

   (91) https://bugs.python.org/issue2746

   (92) https://bugs.python.org/issue6267

   (93) https://bugs.python.org/issue5511

   (94) https://bugs.python.org/issue4710

   (95) https://bugs.python.org/issue7610

   (96) https://bugs.python.org/issue4756

   (97) https://bugs.python.org/issue6003


File: python.info,  Node: 新模块：importlib,  Next: 新模块：sysconfig,  Up: 新增和改进的模块

1.11.11.1 新模块：importlib
...........................

Python 3.1 includes the *note importlib: 9a. package, a
re-implementation of the logic underlying Python’s *note import: ce7.
statement.  *note importlib: 9a. 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 *note importlib: 9a. package, but instead has a tiny subset
that contains a single function, *note import_module(): be6.

‘import_module(name, package=None)’ imports a module.  `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 ‘.’ character,
such as ‘..utils.errors’.  For relative imports, the `package' argument
must be provided and is the name of the package that will be used as the
anchor for the relative import.  *note import_module(): be6. both
inserts the imported module into ‘sys.modules’ and returns the module
object.

这是一些例子:

     >>> 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'>

*note importlib: 9a. was implemented by Brett Cannon and introduced in
Python 3.1.


File: python.info,  Node: 新模块：sysconfig,  Next: ttk Themed Widgets for Tk,  Prev: 新模块：importlib,  Up: 新增和改进的模块

1.11.11.2 新模块：sysconfig
...........................

The *note sysconfig: fe. module has been pulled out of the Distutils
package, becoming a new top-level module in its own right.  *note
sysconfig: fe. 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:

   * *note get_config_var(): a45. returns variables from Python’s
     Makefile and the ‘pyconfig.h’ file.

   * *note get_config_vars(): a46. returns a dictionary containing all
     of the configuration variables.

   * *note get_path(): d86. returns the configured path for a particular
     type of module: the standard library, site-specific modules,
     platform-specific modules, etc.

   * *note is_python_build(): d87. returns true if you’re running a
     binary from a Python source tree, and false otherwise.

Consult the *note sysconfig: fe. documentation for more details and for
a complete list of functions.

The Distutils package and *note sysconfig: fe. are now maintained by
Tarek Ziadé, who has also started a Distutils2 package (source
repository at ‘https://hg.python.org/distutils2/’) for developing a
next-generation version of Distutils.


File: python.info,  Node: ttk Themed Widgets for Tk,  Next: 更新的模块：unittest,  Prev: 新模块：sysconfig,  Up: 新增和改进的模块

1.11.11.3 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 ‘ttk’ module documentation.  You may also wish
to read the Tcl/Tk manual page describing the Ttk theme engine,
available at ‘https://www.tcl.tk/man/tcl8.5/TkCmd/ttk_intro.htm’.  Some
screenshots of the Python/Ttk code in use are at
‘https://code.google.com/archive/p/python-ttk/wikis/Screenshots.wiki’.

The ‘ttk’ module was written by Guilherme Polo and added in bpo-2983(1).
An alternate version called ‘Tile.py’, written by Martin Franklin and
maintained by Kevin Walzer, was proposed for inclusion in bpo-2618(2),
but the authors argued that Guilherme Polo’s work was more
comprehensive.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue2983

   (2) https://bugs.python.org/issue2618


File: python.info,  Node: 更新的模块：unittest,  Next: 更新的模块：ElementTree 1 3,  Prev: ttk Themed Widgets for Tk,  Up: 新增和改进的模块

1.11.11.4 更新的模块：unittest
..............................

The *note unittest: 124. 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 ‘unittest2’ package, from
‘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(1) or nose(2), but provides a
simple way to run tests kept within a set of package directories.  For
example, the following command will search the ‘test/’ subdirectory for
any importable test files named ‘test*.py’:

     python -m unittest discover -s test

Consult the *note unittest: 124. module documentation for more details.
(Developed in bpo-6001(3).)

The *note main(): 9e8. function supports some other new options:

   * *note -b: d8b. or ‘--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.

   * *note -c: d8c. or ‘--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 *note
     removeHandler(): d8d. decorator that can be used to mark tests that
     should have the control-C handling disabled.

   * *note -f: d8e. or ‘--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(4).)

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 *note SkipTest: 9e9. exception to skip a test
(bpo-1034053(5)).

The error messages for *note assertEqual(): c85, *note assertTrue():
c84, and *note assertFalse(): d8f. failures now provide more
information.  If you set the *note longMessage: d90. attribute of your
*note TestCase: 9e5. 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(6).)

The *note assertRaises(): b92. method now returns a context handler when
called without providing a callable object to run.  For example, you can
write this:

     with self.assertRaises(KeyError):
         {}['foo']

(Implemented by Antoine Pitrou; bpo-4444(7).)

Module- and class-level setup and teardown fixtures are now supported.
Modules can contain ‘setUpModule()’ and ‘tearDownModule()’ functions.
Classes can have *note setUpClass(): 376. and *note tearDownClass():
d91. methods that must be defined as class methods (using ‘@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 *note addCleanup(): 3c5. and *note doCleanups(): d92. were
added.  *note addCleanup(): 3c5. lets you add cleanup functions that
will be called unconditionally (after *note setUp(): d93. if *note
setUp(): d93. fails, otherwise after *note tearDown(): d94.).  This
allows for much simpler resource allocation and deallocation during
tests (bpo-5679(8)).

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 *note unittest: 124.

   * *note assertIsNone(): d95. and *note assertIsNotNone(): d96. take
     one expression and verify that the result is or is not ‘None’.

   * *note assertIs(): d97. and *note assertIsNot(): d98. take two
     values and check whether the two values evaluate to the same object
     or not.  (Added by Michael Foord; bpo-2578(9).)

   * *note assertIsInstance(): d99. and *note assertNotIsInstance():
     d9a. 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(10).)

   * *note assertGreater(): d9b, *note assertGreaterEqual(): d9c, *note
     assertLess(): d9d, and *note assertLessEqual(): d9e. compare two
     quantities.

   * *note assertMultiLineEqual(): d9f. 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 *note assertEqual():
     c85.

   * ‘assertRegexpMatches()’ and ‘assertNotRegexpMatches()’ checks
     whether the first argument is a string matching or not matching the
     regular expression provided as the second argument (bpo-8038(11)).

   * ‘assertRaisesRegexp()’ checks whether a particular exception is
     raised, and then also checks that the string representation of the
     exception matches the provided regular expression.

   * *note assertIn(): da0. and *note assertNotIn(): da1. tests whether
     `first' is or is not in `second'.

   * ‘assertItemsEqual()’ tests whether two provided sequences contain
     the same elements.

   * *note assertSetEqual(): da2. compares whether two sets are equal,
     and only reports the differences between the sets in case of error.

   * Similarly, *note assertListEqual(): da3. and *note
     assertTupleEqual(): da4. 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 *note assertEqual(): c85.  More generally, *note
     assertSequenceEqual(): da5. compares two sequences and can
     optionally check whether both sequences are of a particular type.

   * *note assertDictEqual(): da6. compares two dictionaries and reports
     the differences; it’s now used by default when you compare two
     dictionaries using *note assertEqual(): c85.
     ‘assertDictContainsSubset()’ checks whether all of the key/value
     pairs in `first' are found in `second'.

   * *note assertAlmostEqual(): c87. and *note assertNotAlmostEqual():
     c88. test whether `first' and `second' are approximately equal.
     This method can either round their difference to an
     optionally-specified number of `places' (the default is 7) and
     compare it to zero, or require the difference to be smaller than a
     supplied `delta' value.

   * *note loadTestsFromName(): da7. properly honors the *note
     suiteClass: da8. attribute of the *note TestLoader: 871.  (Fixed by
     Mark Roddy; bpo-6866(12).)

   * A new hook lets you extend the *note assertEqual(): c85. method to
     handle new data types.  The *note addTypeEqualityFunc(): da9.
     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.

*note unittest.main(): 9e8. now takes an optional ‘exit’ argument.  If
false, *note main(): 9e8. doesn’t call *note sys.exit(): daa, allowing
*note main(): 9e8. to be used from the interactive interpreter.
(Contributed by J. Pablo Fernández; bpo-3379(13).)

*note TestResult: b97. has new *note startTestRun(): dab. and *note
stopTestRun(): dac. methods that are called immediately before and after
a test run.  (Contributed by Robert Collins; bpo-5728(14).)

With all these changes, the ‘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.

也參考
......

‘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.)

   ---------- Footnotes ----------

   (1) http://pytest.org

   (2) https://nose.readthedocs.io/

   (3) https://bugs.python.org/issue6001

   (4) https://bugs.python.org/issue8074

   (5) https://bugs.python.org/issue1034053

   (6) https://bugs.python.org/issue5663

   (7) https://bugs.python.org/issue4444

   (8) https://bugs.python.org/issue5679

   (9) https://bugs.python.org/issue2578

   (10) https://bugs.python.org/issue7031

   (11) https://bugs.python.org/issue8038

   (12) https://bugs.python.org/issue6866

   (13) https://bugs.python.org/issue3379

   (14) https://bugs.python.org/issue5728


File: python.info,  Node: 更新的模块：ElementTree 1 3,  Prev: 更新的模块：unittest,  Up: 新增和改进的模块

1.11.11.5 更新的模块：ElementTree 1.3
.....................................

The version of the ElementTree library included with Python was updated
to version 1.3.  Some of the new features are:

   * The various parsing functions now take a `parser' keyword argument
     giving an *note XMLParser: 37c. instance that will be used.  This
     makes it possible to override the file’s internal encoding:

          p = ET.XMLParser(encoding='utf-8')
          t = ET.XML("""<root/>""", parser=p)

     Errors in parsing XML now raise a ‘ParseError’ exception, whose
     instances have a ‘position’ attribute containing a (`line',
     `column') tuple giving the location of the problem.

   * ElementTree’s code for converting trees to a string has been
     significantly reworked, making it roughly twice as fast in many
     cases.  The *note ElementTree.write(): 9fd. and ‘Element.write()’
     methods now have a `method' parameter that can be "xml" (the
     default), "html", or "text".  HTML mode will output empty elements
     as ‘<empty></empty>’ instead of ‘<empty/>’, and text mode will skip
     over elements and only output the text chunks.  If you set the
     ‘tag’ attribute of an element to ‘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 ‘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 ‘default_namespace’ attribute and can
     register new prefixes with *note register_namespace(): c22.  In XML
     mode, you can use the true/false `xml_declaration' parameter to
     suppress the XML declaration.

   * New *note Element: 21d. method: *note extend(): c23. 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:

          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)

   * New ‘Element’ method: *note iter(): daf. yields the children of the
     element as a generator.  It’s also possible to write ‘for child in
     elem:’ to loop over an element’s children.  The existing method
     ‘getiterator()’ is now deprecated, as is ‘getchildren()’ which
     constructs and returns a list of children.

   * New ‘Element’ method: *note itertext(): c25. yields all chunks of
     text that are descendants of the element.  For 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())

   * Deprecated: using an element as a Boolean (i.e., ‘if elem:’) would
     return true if the element had any children, or false if there were
     no children.  This behaviour is confusing – ‘None’ is false, but so
     is a childless element?  – so it will now trigger a *note
     FutureWarning: 435.  In your code, you should be explicit: write
     ‘len(elem) != 0’ if you’re interested in the number of children, or
     ‘elem is not None’.

Fredrik Lundh develops ElementTree and produced the 1.3 version; you can
read his article describing 1.3 at
‘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(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue6472


File: python.info,  Node: 构建和 C API 的改变<8>,  Next: Other Changes and Fixes,  Prev: 新增和改进的模块,  Up: Python 2 7 有什么新变化

1.11.12 构建和 C API 的改变
---------------------------

Changes to Python’s build process and to the C API include:

   * The latest release of the GNU Debugger, GDB 7, can be scripted
     using Python(1).  When you begin debugging an executable program P,
     GDB will look for a file named ‘P-gdb.py’ and automatically read
     it.  Dave Malcolm contributed a ‘python-gdb.py’ that adds a number
     of commands useful when debugging Python itself.  For example,
     ‘py-up’ and ‘py-down’ go up or down one Python stack frame, which
     usually corresponds to several C stack frames.  ‘py-print’ prints
     the value of a Python variable, and ‘py-bt’ prints the Python stack
     trace.  (Added as a result of bpo-8032(2).)

   * If you use the ‘.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(3).)

   * *note Py_AddPendingCall(): 25f. 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(4).)

   * New function: *note PyCode_NewEmpty(): db1. 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 *note PyCode_New(): 39b, which had many
     more arguments.  (Added by Jeffrey Yasskin.)

   * New function: *note PyErr_NewExceptionWithDoc(): cca. creates a new
     exception class, just as the existing *note PyErr_NewException():
     ccb. does, but takes an extra ‘char *’ argument containing the
     docstring for the new exception class.  (Added by ’lekma’ on the
     Python bug tracker; bpo-7033(5).)

   * New function: *note PyFrame_GetLineNumber(): 24b. 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.)

   * New functions: *note PyLong_AsLongAndOverflow(): cc8. and *note
     PyLong_AsLongLongAndOverflow(): cc7. approximates a Python long
     integer as a C ‘long’ or ‘long long’.  If the number is too large
     to fit into the output type, an `overflow' flag is set and returned
     to the caller.  (Contributed by Case Van Horsen; bpo-7528(6) and
     bpo-7767(7).)

   * New function: stemming from the rewrite of string-to-float
     conversion, a new *note PyOS_string_to_double(): ced. function was
     added.  The old ‘PyOS_ascii_strtod()’ and ‘PyOS_ascii_atof()’
     functions are now deprecated.

   * New function: *note PySys_SetArgvEx(): cc5. sets the value of
     ‘sys.argv’ and can optionally update ‘sys.path’ to include the
     directory containing the script named by ‘sys.argv[0]’ depending on
     the value of an `updatepath' parameter.

     This function was added to close a security hole for applications
     that embed Python.  The old function, *note PySys_SetArgv(): db2,
     would always update ‘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 ‘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 *note PySys_SetArgv(): db2. and carefully
     consider whether the application should be using *note
     PySys_SetArgvEx(): cc5. with `updatepath' set to false.

     Security issue reported as CVE-2008-5983(8); discussed in
     bpo-5753(9), and fixed by Antoine Pitrou.

   * New macros: the Python header files now define the following
     macros: ‘Py_ISALNUM’, ‘Py_ISALPHA’, ‘Py_ISDIGIT’, ‘Py_ISLOWER’,
     ‘Py_ISSPACE’, ‘Py_ISUPPER’, ‘Py_ISXDIGIT’, ‘Py_TOLOWER’, and
     ‘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(10).)

   * Removed function: ‘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(11).)

   * New format codes: the ‘PyFormat_FromString()’,
     ‘PyFormat_FromStringV()’, and *note PyErr_Format(): 898. functions
     now accept ‘%lld’ and ‘%llu’ format codes for displaying C’s ‘long
     long’ types.  (Contributed by Mark Dickinson; bpo-7228(12).)

   * The complicated interaction between threads and process forking has
     been changed.  Previously, the child process created by *note
     os.fork(): a42. might fail because the child is created with only a
     single thread running, the thread performing the *note os.fork():
     a42.  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 *note
     os.fork(): a42, and will also clean up any locks created using the
     *note threading: 10b. module.  C extension modules that have
     internal locks, or that call ‘fork()’ themselves, will not benefit
     from this clean-up.

     (Fixed by Thomas Wouters; bpo-1590864(13).)

   * The *note Py_Finalize(): db3. function now calls the internal
     ‘threading._shutdown()’ function; this prevents some exceptions
     from being raised when an interpreter shuts down.  (Patch by Adam
     Olsen; bpo-1722344(14).)

   * When using the *note PyMemberDef: 529. structure to define
     attributes of a type, Python will no longer let you try to delete
     or set a ‘T_STRING_INPLACE’ attribute.

   * Global symbols defined by the *note ctypes: 2a. module are now
     prefixed with ‘Py’, or with ‘_ctypes’.  (Implemented by Thomas
     Heller; bpo-3102(15).)

   * New configure option: the ‘--with-system-expat’ switch allows
     building the ‘pyexpat’ module to use the system Expat library.
     (Contributed by Arfrever Frehtes Taifersar Arahesis; bpo-7609(16).)

   * New configure option: the ‘--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(17).)

   * New configure option: you can now supply an empty string to
     ‘--with-dbmliborder=’ in order to disable all of the various DBM
     modules.  (Added by Arfrever Frehtes Taifersar Arahesis;
     bpo-6491(18).)

   * The ‘configure’ script now checks for floating-point rounding bugs
     on certain 32-bit Intel chips and defines a ‘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(19).)

     ‘configure’ also now sets a ‘LDCXXSHARED’ Makefile variable for
     supporting C++ linking.  (Contributed by Arfrever Frehtes Taifersar
     Arahesis; bpo-1222585(20).)

   * The build process now creates the necessary files for pkg-config
     support.  (Contributed by Clinton Roy; bpo-3585(21).)

   * The build process now supports Subversion 1.7.  (Contributed by
     Arfrever Frehtes Taifersar Arahesis; bpo-6094(22).)

* Menu:

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

   ---------- Footnotes ----------

   (1) https://sourceware.org/gdb/current/onlinedocs/gdb/Python.html

   (2) https://bugs.python.org/issue8032

   (3) https://bugs.python.org/issue3632

   (4) https://bugs.python.org/issue4293

   (5) https://bugs.python.org/issue7033

   (6) https://bugs.python.org/issue7528

   (7) https://bugs.python.org/issue7767

   (8) https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-5983

   (9) https://bugs.python.org/issue5753

   (10) https://bugs.python.org/issue5793

   (11) https://bugs.python.org/issue8276

   (12) https://bugs.python.org/issue7228

   (13) https://bugs.python.org/issue1590864

   (14) https://bugs.python.org/issue1722344

   (15) https://bugs.python.org/issue3102

   (16) https://bugs.python.org/issue7609

   (17) https://bugs.python.org/issue2422

   (18) https://bugs.python.org/issue6491

   (19) https://bugs.python.org/issue2937

   (20) https://bugs.python.org/issue1222585

   (21) https://bugs.python.org/issue3585

   (22) https://bugs.python.org/issue6094


File: python.info,  Node: 胶囊,  Next: 特定于 Windows 的更改：,  Up: 构建和 C API 的改变<8>

1.11.12.1 胶囊
..............

Python 3.1 adds a new C datatype, *note PyCapsule: cd2, for providing a
C API to an extension module.  A capsule is essentially the holder of a
C ‘void *’ pointer, and is made available as a module attribute; for
example, the *note socket: ef. module’s API is exposed as ‘socket.CAPI’,
and *note unicodedata: 123. exposes ‘ucnhash_CAPI’.  Other extensions
can import the module, access its dictionary to get the capsule object,
and then get the ‘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, ‘PyCObject’, but
it doesn’t provide type safety.  Evil code written in pure Python could
cause a segmentation fault by taking a ‘PyCObject’ from module A and
somehow substituting it for the ‘PyCObject’ in module B. Capsules know
their own name, and getting the pointer requires providing the name:

     void *vtable;

     if (!PyCapsule_IsValid(capsule, "mymodule.CAPI") {
             PyErr_SetString(PyExc_ValueError, "argument type invalid");
             return NULL;
     }

     vtable = PyCapsule_GetPointer(capsule, "mymodule.CAPI");

You are assured that ‘vtable’ points to whatever you’re expecting.  If a
different capsule was passed in, *note PyCapsule_IsValid(): db6. would
detect the mismatched name and return false.  Refer to *note
给扩展模块提供C API: db7. for more information on using these objects.

Python 2.7 now uses capsules internally to provide various
extension-module APIs, but the ‘PyCObject_AsVoidPtr()’ was modified to
handle capsules, preserving compile-time compatibility with the
‘CObject’ interface.  Use of ‘PyCObject_AsVoidPtr()’ will signal a *note
PendingDeprecationWarning: 15c, which is silent by default.

Implemented in Python 3.1 and backported to 2.7 by Larry Hastings;
discussed in bpo-5630(1).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5630


File: python.info,  Node: 特定于 Windows 的更改：,  Next: 特定于 Mac OS X 的更改：,  Prev: 胶囊,  Up: 构建和 C API 的改变<8>

1.11.12.2 特定于 Windows 的更改：
.................................

   * The *note msvcrt: b6. module now contains some constants from the
     ‘crtassem.h’ header file: ‘CRT_ASSEMBLY_VERSION’,
     ‘VC_ASSEMBLY_PUBLICKEYTOKEN’, and ‘LIBRARIES_ASSEMBLY_NAME_PREFIX’.
     (Contributed by David Cournapeau; bpo-4365(1).)

   * The ‘_winreg’ module for accessing the registry now implements the
     ‘CreateKeyEx()’ and ‘DeleteKeyEx()’ functions, extended versions of
     previously-supported functions that take several extra arguments.
     The ‘DisableReflectionKey()’, ‘EnableReflectionKey()’, and
     ‘QueryReflectionKey()’ were also tested and documented.
     (Implemented by Brian Curtin: bpo-7347(2).)

   * The new ‘_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(3).)

   * The *note os.kill(): db9. function now works on Windows.  The
     signal value can be the constants ‘CTRL_C_EVENT’,
     ‘CTRL_BREAK_EVENT’, or any integer.  The first two constants will
     send ‘Control-C’ and ‘Control-Break’ keystroke events to
     subprocesses; any other value will use the ‘TerminateProcess()’
     API. (Contributed by Miki Tebeka; bpo-1220212(4).)

   * The *note os.listdir(): b1c. function now correctly fails for an
     empty path.  (Fixed by Hirokazu Yamamoto; bpo-5913(5).)

   * The ‘mimelib’ module will now read the MIME database from the
     Windows registry when initializing.  (Patch by Gabriel Genellina;
     bpo-4969(6).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue4365

   (2) https://bugs.python.org/issue7347

   (3) https://bugs.python.org/issue3582

   (4) https://bugs.python.org/issue1220212

   (5) https://bugs.python.org/issue5913

   (6) https://bugs.python.org/issue4969


File: python.info,  Node: 特定于 Mac OS X 的更改：,  Next: 特定于 FreeBSD 的更改：,  Prev: 特定于 Windows 的更改：,  Up: 构建和 C API 的改变<8>

1.11.12.3 特定于 Mac OS X 的更改：
..................................

   * The path ‘/Library/Python/2.7/site-packages’ is now appended to
     ‘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(1).)

          2.7.13 版更變: As of 2.7.13, this change was removed.
          ‘/Library/Python/2.7/site-packages’, the site-packages
          directory used by the Apple-supplied system Python 2.7 is no
          longer appended to ‘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(2))

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue4865

   (2) https://bugs.python.org/issue28440


File: python.info,  Node: 特定于 FreeBSD 的更改：,  Prev: 特定于 Mac OS X 的更改：,  Up: 构建和 C API 的改变<8>

1.11.12.4 特定于 FreeBSD 的更改：
.................................

   * FreeBSD 7.1’s ‘SO_SETFIB’ constant, used with
     ‘getsockopt()’/‘setsockopt()’ to select an alternate routing table,
     is now available in the *note socket: ef. module.  (Added by Kyle
     VanderBeek; bpo-8235(1).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue8235


File: python.info,  Node: Other Changes and Fixes,  Next: 移植到 Python 2 7,  Prev: 构建和 C API 的改变<8>,  Up: Python 2 7 有什么新变化

1.11.13 Other Changes and Fixes
-------------------------------

   * Two benchmark scripts, ‘iobench’ and ‘ccbench’, were added to the
     ‘Tools’ directory.  ‘iobench’ measures the speed of the built-in
     file I/O objects returned by *note open(): 16f. while performing
     various operations, and ‘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.

   * The ‘Tools/i18n/msgfmt.py’ script now understands plural forms in
     ‘.po’ files.  (Fixed by Martin von Löwis; bpo-5464(1).)

   * When importing a module from a ‘.pyc’ or ‘.pyo’ file with an
     existing ‘.py’ counterpart, the ‘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(2).)

   * The ‘regrtest.py’ script now takes a ‘--randseed=’ switch that
     takes an integer that will be used as the random seed for the ‘-r’
     option that executes tests in random order.  The ‘-r’ option also
     reports the seed that was used (Added by Collin Winter.)

   * Another ‘regrtest.py’ switch is ‘-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 ‘-R’ switch
     which is known to produce long runtimes.  (Added by Antoine Pitrou,
     bpo-6152(3).)  This can also be used with a new ‘-F’ switch that
     runs selected tests in a loop until they fail.  (Added by Antoine
     Pitrou; bpo-7312(4).)

   * When executed as a script, the ‘py_compile.py’ module now accepts
     ‘'-'’ as an argument, which will read standard input for the list
     of filenames to be compiled.  (Contributed by Piotr Ożarowski;
     bpo-8233(5).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5464

   (2) https://bugs.python.org/issue1180193

   (3) https://bugs.python.org/issue6152

   (4) https://bugs.python.org/issue7312

   (5) https://bugs.python.org/issue8233


File: python.info,  Node: 移植到 Python 2 7,  Next: New Features Added to Python 2 7 Maintenance Releases,  Prev: Other Changes and Fixes,  Up: Python 2 7 有什么新变化

1.11.14 移植到 Python 2.7
-------------------------

This section lists previously described changes and other bugfixes that
may require changes to your code:

   * The *note range(): 1f5. function processes its arguments more
     consistently; it will now call *note __int__(): 2c3. on non-float,
     non-integer arguments that are supplied to it.  (Fixed by Alexander
     Belopolsky; bpo-1533(1).)

   * The string *note format(): 5d5. method changed the default
     precision used for floating-point and complex numbers from 6
     decimal places to 12, which matches the precision used by *note
     str(): 205.  (Changed by Eric Smith; bpo-5920(2).)

   * Because of an optimization for the *note with: 7da. statement, the
     special methods *note __enter__(): d5d. and *note __exit__(): d5e.
     must belong to the object’s type, and cannot be directly attached
     to the object’s instance.  This affects new-style classes (derived
     from *note object: 3d2.) and C extension types.  (bpo-6101(3).)

   * Due to a bug in Python 2.6, the `exc_value' parameter to *note
     __exit__(): d5e. methods was often the string representation of the
     exception, not an instance.  This was fixed in 2.7, so `exc_value'
     will be an instance as expected.  (Fixed by Florent Xicluna;
     bpo-7853(4).)

   * When a restricted set of attributes were set using ‘__slots__’,
     deleting an unset attribute would not raise *note AttributeError:
     4a1. as you would expect.  Fixed by Benjamin Peterson;
     bpo-7604(5).)

In the standard library:

   * Operations with *note datetime: 19f. instances that resulted in a
     year falling outside the supported range didn’t always raise *note
     OverflowError: a41.  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(6).)

   * When using *note Decimal: 2c0. instances with a string’s *note
     format(): 5d5. 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(7).)

     Comparisons involving a signaling NaN value (or ‘sNAN’) now signal
     *note InvalidOperation: aca. instead of silently returning a true
     or false value depending on the comparison operator.  Quiet NaN
     values (or ‘NaN’) are now hashable.  (Fixed by Mark Dickinson;
     bpo-7279(8).)

   * The ElementTree library, ‘xml.etree’, no longer escapes ampersands
     and angle brackets when outputting an XML processing instruction
     (which looks like ‘<?xml-stylesheet href="#style1"?>’) or comment
     (which looks like ‘<!– comment –>’).  (Patch by Neil Muller;
     bpo-2746(9).)

   * The ‘readline()’ method of ‘StringIO’ objects now does nothing when
     a negative length is requested, as other file-like objects do.
     (bpo-7348(10)).

   * The *note syslog: ff. module will now use the value of
     ‘sys.argv[0]’ as the identifier instead of the previous default
     value of ‘'python'’.  (Changed by Sean Reifschneider;
     bpo-8451(11).)

   * The *note tarfile: 101. 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(12).)

   * The ‘urlparse’ module’s ‘urlsplit()’ now handles unknown URL
     schemes in a fashion compliant with RFC 3986(13): if the URL is of
     the form ‘"<something>://..."’, the text before the ‘://’ 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:

          >>> import urlparse
          >>> urlparse.urlsplit('invented://host/filename?query')
          ('invented', '', '//host/filename?query', '', '')

     Python 2.7 (and Python 2.6.5) will return:

          >>> import urlparse
          >>> urlparse.urlsplit('invented://host/filename?query')
          ('invented', 'host', '/filename?query', '', '')

     (Python 2.7 actually produces slightly different output, since it
     returns a named tuple instead of a standard tuple.)

对于C 扩展模块：

   * C extensions that use integer format codes with the ‘PyArg_Parse*’
     family of functions will now raise a *note TypeError: 1fe.
     exception instead of triggering a *note DeprecationWarning: 15a.
     (bpo-5080(14)).

   * Use the new *note PyOS_string_to_double(): ced. function instead of
     the old ‘PyOS_ascii_strtod()’ and ‘PyOS_ascii_atof()’ functions,
     which are now deprecated.

对于嵌入Python的应用程序：

   * The *note PySys_SetArgvEx(): cc5. function was added, letting
     applications close a security hole when the existing *note
     PySys_SetArgv(): db2. function was used.  Check whether you’re
     calling *note PySys_SetArgv(): db2. and carefully consider whether
     the application should be using *note PySys_SetArgvEx(): cc5. with
     `updatepath' set to false.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1533

   (2) https://bugs.python.org/issue5920

   (3) https://bugs.python.org/issue6101

   (4) https://bugs.python.org/issue7853

   (5) https://bugs.python.org/issue7604

   (6) https://bugs.python.org/issue7150

   (7) https://bugs.python.org/issue6857

   (8) https://bugs.python.org/issue7279

   (9) https://bugs.python.org/issue2746

   (10) https://bugs.python.org/issue7348

   (11) https://bugs.python.org/issue8451

   (12) https://bugs.python.org/issue7357

   (13) https://tools.ietf.org/html/rfc3986.html

   (14) https://bugs.python.org/issue5080


File: python.info,  Node: New Features Added to Python 2 7 Maintenance Releases,  Next: 致谢,  Prev: 移植到 Python 2 7,  Up: Python 2 7 有什么新变化

1.11.15 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 ‘-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>.


File: python.info,  Node: Two new environment variables for debug mode,  Next: PEP 434 IDLE Enhancement Exception for All Branches,  Up: New Features Added to Python 2 7 Maintenance Releases

1.11.15.1 Two new environment variables for debug mode
......................................................

In debug mode, the ‘[xxx refs]’ statistic is not written by default, the
‘PYTHONSHOWREFCOUNT’ environment variable now must also be set.
(Contributed by Victor Stinner; bpo-31733(1).)

When Python is compiled with ‘COUNT_ALLOC’ defined, allocation counts
are no longer dumped by default anymore: the ‘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(2).)

2.7.15 版新加入.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31733

   (2) https://bugs.python.org/issue31692


File: python.info,  Node: PEP 434 IDLE Enhancement Exception for All Branches,  Next: PEP 466 Network Security Enhancements for Python 2 7,  Prev: Two new environment variables for debug mode,  Up: New Features Added to Python 2 7 Maintenance Releases

1.11.15.2 PEP 434: IDLE Enhancement Exception for All Branches
..............................................................

PEP 434(1) 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.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0434


File: python.info,  Node: PEP 466 Network Security Enhancements for Python 2 7,  Next: PEP 477 Backport ensurepip PEP 453 to Python 2 7,  Prev: PEP 434 IDLE Enhancement Exception for All Branches,  Up: New Features Added to Python 2 7 Maintenance Releases

1.11.15.3 PEP 466: Network Security Enhancements for Python 2.7
...............................................................

PEP 466(1) 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.

PEP 466(2) Python 2.7.7 中添加的相关功能：

   * *note hmac.compare_digest(): aea. was backported from Python 3 to
     make a timing attack resistant comparison operation available to
     Python 2 applications.  (Contributed by Alex Gaynor; bpo-21306(3).)

   * OpenSSL 1.0.1g was upgraded in the official Windows installers
     published on python.org.  (Contributed by Zachary Ware;
     bpo-21462(4).)

PEP 466(5) Python 2.7.8 中添加的相关功能：

   * *note hashlib.pbkdf2_hmac(): 8d3. 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(6).)

   * OpenSSL 1.0.1h was upgraded for the official Windows installers
     published on python.org.  (contributed by Zachary Ware in
     bpo-21671(7) for CVE-2014-0224)

PEP 466(8) Python 2.7.9 中添加的相关功能：

   * Most of Python 3.4’s *note ssl: f3. module was backported.  This
     means *note ssl: f3. now supports Server Name Indication, TLS1.x
     settings, access to the platform certificate store, the *note
     SSLContext: 4e9. class, and other features.  (Contributed by Alex
     Gaynor and David Reid; bpo-21308(9).)

     Refer to the "Version added: 2.7.9" notes in the module
     documentation for specific details.

   * *note os.urandom(): 5cb. was changed to cache a file descriptor to
     ‘/dev/urandom’ instead of reopening ‘/dev/urandom’ on every call.
     (Contributed by Alex Gaynor; bpo-21305(10).)

   * *note hashlib.algorithms_guaranteed: dc2. and *note
     hashlib.algorithms_available: dc3. 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(11))

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0466

   (2) https://www.python.org/dev/peps/pep-0466

   (3) https://bugs.python.org/issue21306

   (4) https://bugs.python.org/issue21462

   (5) https://www.python.org/dev/peps/pep-0466

   (6) https://bugs.python.org/issue21304

   (7) https://bugs.python.org/issue21671

   (8) https://www.python.org/dev/peps/pep-0466

   (9) https://bugs.python.org/issue21308

   (10) https://bugs.python.org/issue21305

   (11) https://bugs.python.org/issue21307


File: python.info,  Node: PEP 477 Backport ensurepip PEP 453 to Python 2 7,  Next: PEP 476 Enabling certificate verification by default for stdlib http clients<2>,  Prev: PEP 466 Network Security Enhancements for Python 2 7,  Up: New Features Added to Python 2 7 Maintenance Releases

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

PEP 477(1) approves the inclusion of the PEP 453(2) 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>.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0477

   (2) https://www.python.org/dev/peps/pep-0453


File: python.info,  Node: Bootstrapping pip By Default<2>,  Next: 文档更改<2>,  Up: PEP 477 Backport ensurepip PEP 453 to Python 2 7

1.11.15.5 Bootstrapping pip By Default
......................................

The new *note ensurepip: 78. module (defined in PEP 453(1)) provides a
standard cross-platform mechanism to bootstrap the pip installer into
Python installations.  The version of ‘pip’ included with Python 2.7.9
is ‘pip’ 1.5.6, and future 2.7.x maintenance releases will update the
bundled version to the latest version of ‘pip’ that is available at the
time of creating the release candidate.

By default, the commands ‘pip’, ‘pipX’ and ‘pipX.Y’ will be installed on
all platforms (where X.Y stands for the version of the Python
installation), along with the ‘pip’ Python package and its dependencies.

For CPython *note source builds on POSIX systems: 8e0, the ‘make
install’ and ‘make altinstall’ commands do not bootstrap ‘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 ‘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 ‘PATH’ modifications to have ‘pip’ available
from the command line by default, otherwise it can still be accessed
through the Python launcher for Windows as ‘py -m pip’.

As discussed in the PEP(2), 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).

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0453

   (2) 
https://www.python.org/dev/peps/pep-0477/#disabling-ensurepip-by-downstream-distributors


File: python.info,  Node: 文档更改<2>,  Prev: Bootstrapping pip By Default<2>,  Up: PEP 477 Backport ensurepip PEP 453 to Python 2 7

1.11.15.6 文档更改
..................

As part of this change, the *note 安裝 Python 模組: 8e2. and *note 發布
Python 模組: 8e3. 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(1) and the documentation of the
individual projects.

However, as this migration is currently still incomplete, the legacy
versions of those guides remaining available as *note 安裝 Python
模組（舊版）: 8e4. and *note 發布 Python 模組（舊版）: 8e5.

也參考
......

PEP 453(2) – Python安装中pip的显式引导

     PEP 由Donald Stufft 和 Nick Coghlan 撰写，由 Donald Stufft，Nick
     Coghlan，Martin von Löwis 和 Ned Deily 实现。

   ---------- Footnotes ----------

   (1) http://packaging.python.org

   (2) https://www.python.org/dev/peps/pep-0453


File: python.info,  Node: PEP 476 Enabling certificate verification by default for stdlib http clients<2>,  Next: PEP 493：适用于Python 2 7 的 HTTPS 验证迁移工具,  Prev: PEP 477 Backport ensurepip PEP 453 to Python 2 7,  Up: New Features Added to Python 2 7 Maintenance Releases

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

PEP 476(1) updated ‘httplib’ and modules which use it, such as ‘urllib2’
and ‘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:

     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)

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0476


File: python.info,  Node: PEP 493：适用于Python 2 7 的 HTTPS 验证迁移工具,  Next: New make regen-all build target<3>,  Prev: PEP 476 Enabling certificate verification by default for stdlib http clients<2>,  Up: New Features Added to Python 2 7 Maintenance Releases

1.11.15.8 PEP 493：适用于Python 2.7 的 HTTPS 验证迁移工具
.........................................................

PEP 493(1) 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
‘PYTHONHTTPSVERIFY’ environment variable may be set to ‘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
‘ssl._https_verify_certificates()’ function can be used to adjust the
default behaviour at runtime.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0493


File: python.info,  Node: New make regen-all build target<3>,  Next: Removal of make touch build target<3>,  Prev: PEP 493：适用于Python 2 7 的 HTTPS 验证迁移工具,  Up: New Features Added to Python 2 7 Maintenance Releases

1.11.15.9 New ‘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 ‘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(1) for details.

（由 Victor Stinner 在 bpo-23404(2) 中贡献。）

2.7.14 版新加入.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Makefile.pre.in

   (2) https://bugs.python.org/issue23404


File: python.info,  Node: Removal of make touch build target<3>,  Prev: New make regen-all build target<3>,  Up: New Features Added to Python 2 7 Maintenance Releases

1.11.15.10 Removal of ‘make touch’ build target
...............................................

The ‘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 ‘make regen-all’ target.

（由 Victor Stinner 在 bpo-23404(1) 中贡献。）

2.7.14 版更變.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23404


File: python.info,  Node: 致谢,  Prev: New Features Added to Python 2 7 Maintenance Releases,  Up: Python 2 7 有什么新变化

1.11.16 致谢
------------

作者要感谢以下人员为本文的各种草案提供建议，更正和帮助： Nick Coghlan,
Philip Jenvey, Ryan Lovett, R. David Murray, Hugh Secker-Walker.


File: python.info,  Node: Python 2 6 有什么新变化,  Next: Python 2 5 有什么新变化,  Prev: Python 2 7 有什么新变化,  Up: Python 有什麼新功能？

1.12 Python 2.6 有什么新变化
============================


作者: A.M. Kuchling (amk at amk.ca)

本文介绍了 Python 2.6 的新特性，它发布于 2008 年 10 月 1 日。 发布日程说
明见 PEP 361(1)。

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 ‘future_builtins’ module and a ‘-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 *note multiprocessing: b7. and *note json: a4. 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.

* 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>.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0361


File: python.info,  Node: Python 3 0,  Next: 开发过程的变化,  Up: Python 2 6 有什么新变化

1.12.1 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:

   * A *note __complex__(): 2c5. method for converting objects to a
     complex number.

   * Alternate syntax for catching exceptions: ‘except TypeError as
     exc’.

   * The addition of *note functools.reduce(): d37. as a synonym for the
     built-in ‘reduce()’ function.

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 *note
bin(): d08. have simply been added to Python 2.6, but existing builtins
haven’t been changed; instead, the ‘future_builtins’ module has versions
with the new 3.0 semantics.  Code written to be compatible with 3.0 can
do ‘from future_builtins import hex, map’ as necessary.

A new command-line switch, ‘-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
‘sys.py3kwarning’, and to C extension code as ‘Py_Py3kWarningFlag’.

也參考
......

The 3xxx series of PEPs, which contains proposals for Python 3.0.  PEP
3000(1) describes the development process for Python 3.0.  Start with
PEP 3100(2) that describes the general goals for Python 3.0, and then
explore the higher-numbered PEPS that propose specific features.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3000

   (2) https://www.python.org/dev/peps/pep-3100


File: python.info,  Node: 开发过程的变化,  Next: PEP 343 "with" 语句,  Prev: Python 3 0,  Up: Python 2 6 有什么新变化

1.12.2 开发过程的变化
---------------------

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:

* New Issue Tracker; Roundup: New Issue Tracker Roundup.
* 新的文档格式：使用 Sphinx 的 reStructuredText::


File: python.info,  Node: New Issue Tracker Roundup,  Next: 新的文档格式：使用 Sphinx 的 reStructuredText,  Up: 开发过程的变化

1.12.2.1 New Issue Tracker: Roundup
...................................

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(1), Launchpad(2), Roundup(3), and
Trac(4).  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 ‘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(5) 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
‘http://svn.python.org/view/tracker/importer/’ and may be useful to
other projects wishing to move from SourceForge to Roundup.

也參考
......

‘https://bugs.python.org’

     Python 的错误追踪器

‘http://bugs.jython.org’:

     Jython 的错误追踪器

‘http://roundup.sourceforge.net/’

     Roundup 下载和文档。

‘http://svn.python.org/view/tracker/importer/’

     Martin von Löwis 的转换脚本。

   ---------- Footnotes ----------

   (1) https://www.atlassian.com/software/jira/

   (2) https://launchpad.net/

   (3) http://roundup.sourceforge.net/

   (4) https://trac.edgewall.org/

   (5) http://www.upfrontsoftware.co.za


File: python.info,  Node: 新的文档格式：使用 Sphinx 的 reStructuredText,  Prev: New Issue Tracker Roundup,  Up: 开发过程的变化

1.12.2.2 新的文档格式：使用 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
‘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(1)) have adopted
Sphinx as their documentation tool.

也參考
......

Documenting Python(2)

     描述如何编写Python文档。

Sphinx(3)

     Sphinx工具链的文档和代码。

Docutils(4)

     reStructuredText 的基础解析器和工具集。

   ---------- Footnotes ----------

   (1) https://www.sphinx-doc.org/en/master/examples.html

   (2) https://devguide.python.org/documenting/

   (3) http://sphinx-doc.org/

   (4) http://docutils.sourceforge.net


File: python.info,  Node: PEP 343 "with" 语句,  Next: PEP 366 从主模块显式相对导入,  Prev: 开发过程的变化,  Up: Python 2 6 有什么新变化

1.12.3 PEP 343: "with" 语句
---------------------------

The previous version, Python 2.5, added the ’*note with: 7da.’ statement
as an optional feature, to be enabled by a ‘from __future__ import
with_statement’ directive.  In 2.6 the statement no longer needs to be
specially enabled; this means that ‘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
’‘with’’ statement from Python 2.5, you can skip this section.

The ’*note with: 7da.’ statement clarifies code that previously would
use ‘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 ’*note with: 7da.’ statement is a control-flow structure whose basic
structure is:

     with expression [as variable]:
         with-block

The expression is evaluated, and it should result in an object that
supports the context management protocol (that is, has *note
__enter__(): d5d. and *note __exit__(): d5e. methods).

The object’s *note __enter__(): d5d. is called before `with-block' is
executed and therefore can run set-up code.  It also may return a value
that is bound to the name `variable', if given.  (Note carefully that
`variable' is `not' assigned the result of `expression'.)

After execution of the `with-block' is finished, the object’s *note
__exit__(): d5e. 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 ’*note with: 7da.’ statement.  File objects are
one example:

     with open('/etc/passwd', 'r') as f:
         for line in f:
             print line
             ... more processing code ...

After this statement has executed, the file object in `f' will have been
automatically closed, even if the *note for: cfa. loop raised an
exception part-way through the block.

     備註: In this case, `f' is the same object created by *note open():
     16f, because ‘file.__enter__()’ returns `self'.

The *note threading: 10b. module’s locks and condition variables also
support the ’*note with: 7da.’ statement:

     lock = threading.Lock()
     with lock:
         # Critical section of code
         ...

The lock is acquired before the block is executed and always released
once the block is complete.

The ‘localcontext()’ function in the *note decimal: 35. module makes it
easy to save and restore the current decimal context, which encapsulates
the desired precision and rounding characteristics for computations:

     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()

* Menu:

* Writing Context Managers::
* contextlib 模块::


File: python.info,  Node: Writing Context Managers,  Next: contextlib 模块,  Up: PEP 343 "with" 语句

1.12.3.1 Writing Context Managers
.................................

Under the hood, the ’*note with: 7da.’ statement is fairly complicated.
Most people will only use ’‘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.

A high-level explanation of the context management protocol is:

   * The expression is evaluated and should result in an object called a
     "context manager".  The context manager must have *note
     __enter__(): d5d. and *note __exit__(): d5e. methods.

   * The context manager’s *note __enter__(): d5d. method is called.
     The value returned is assigned to `VAR'. If no ‘as VAR’ clause is
     present, the value is simply discarded.

   * The code in `BLOCK' is executed.

   * If `BLOCK' raises an exception, the context manager’s *note
     __exit__(): d5e. method is called with three arguments, the
     exception details (‘type, value, traceback’, the same values
     returned by *note sys.exc_info(): d27, which can also be ‘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 ‘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 ’*note with: 7da.’ statement will never realize
     anything went wrong.

   * If `BLOCK' didn’t raise an exception, the *note __exit__(): d5e.
     method is still called, but `type', `value', and `traceback' are
     all ‘None’.

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:

     db_connection = DatabaseConnection()
     with db_connection as cursor:
         cursor.execute('insert into ...')
         cursor.execute('delete from ...')
         # ... more operations ...

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 ‘DatabaseConnection’ that I’ll assume:

     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"

The *note __enter__(): d5d. 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 ‘as cursor’ to their ’*note with: 7da.’ statement to bind the
cursor to a variable name.

     class DatabaseConnection:
         ...
         def __enter__(self):
             # Code to start a new transaction
             cursor = self.cursor()
             return cursor

The *note __exit__(): d5e. 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 ‘None’.  ‘None’ is false, so the
exception will be re-raised automatically.  If you wished, you could be
more explicit and add a *note return: 2c8. statement at the marked
location.

     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


File: python.info,  Node: contextlib 模块,  Prev: Writing Context Managers,  Up: PEP 343 "with" 语句

1.12.3.2 contextlib 模块
........................

The *note contextlib: 23. module provides some functions and a decorator
that are useful when writing objects for use with the ’*note with: 7da.’
statement.

The decorator is called ‘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 *note yield: 2c7.
will be executed as the *note __enter__(): d5d. method, and the value
yielded will be the method’s return value that will get bound to the
variable in the ’*note with: 7da.’ statement’s ‘as’ clause, if any.  The
code after the ‘yield’ will be executed in the *note __exit__(): d5e.
method.  Any exception raised in the block will be raised by the ‘yield’
statement.

Using this decorator, our database example from the previous section
could be written as:

     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:
         ...

The *note contextlib: 23. module also has a ‘nested(mgr1, mgr2, ...)’
function that combines a number of context managers so you don’t need to
write nested ’*note with: 7da.’ statements.  In this example, the single
’‘with’’ statement both starts a database transaction and acquires a
thread lock:

     lock = threading.Lock()
     with nested (db_transaction(db), lock) as (cursor, locked):
         ...

Finally, the ‘closing()’ function returns its argument so that it can be
bound to a variable, and calls the argument’s ‘.close()’ method at the
end of the block.

     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)

也參考
......

PEP 343(1) - "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 ’*note with: 7da.’ statement, which can be
     helpful in learning how the statement works.

*note contextlib: 23. 模块的文档。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0343


File: python.info,  Node: PEP 366 从主模块显式相对导入,  Next: PEP 370 分用户的 site-packages 目录,  Prev: PEP 343 "with" 语句,  Up: Python 2 6 有什么新变化

1.12.4 PEP 366: 从主模块显式相对导入
------------------------------------

Python’s *note -m: 443. 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 *note __package__: a36. attribute to
modules.  When this attribute is present, relative imports will be
relative to the value of this attribute instead of the *note __name__:
dd8. attribute.

PEP 302-style importers can then set *note __package__: a36. as
necessary.  The *note runpy: e2. module that implements the *note -m:
443. switch now does this, so relative imports will now work correctly
in scripts running from inside a package.


File: python.info,  Node: PEP 370 分用户的 site-packages 目录,  Next: PEP 371 多任务处理包,  Prev: PEP 366 从主模块显式相对导入,  Up: Python 2 6 有什么新变化

1.12.5 PEP 370: 分用户的 site-packages 目录
-------------------------------------------

When you run Python, the module search path ‘sys.path’ usually includes
a directory whose path ends in ‘"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 introduces a convention for user-specific site directories.
The directory varies depending on the platform:

   * Unix and Mac OS X: ‘~/.local/’

   * Windows: ‘%APPDATA%/Python’

Within this directory, there will be version-specific subdirectories,
such as ‘lib/python2.6/site-packages’ on Unix/Mac OS and
‘Python26/site-packages’ on Windows.

If you don’t like the default directory, it can be overridden by an
environment variable.  *note PYTHONUSERBASE: dda. 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 ‘APPDATA’ environment variable.  You can also modify the
‘site.py’ file for your Python installation.

The feature can be disabled entirely by running Python with the *note
-s: ddb. option or setting the *note PYTHONNOUSERSITE: ddc. environment
variable.

也參考
......

PEP 370(1) - 分用户的 site-packages 目录

     PEP 由 Christian Heimes 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0370


File: python.info,  Node: PEP 371 多任务处理包,  Next: PEP 3101 高级字符串格式,  Prev: PEP 370 分用户的 site-packages 目录,  Up: Python 2 6 有什么新变化

1.12.6 PEP 371: 多任务处理包
----------------------------

The new *note multiprocessing: b7. 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 *note multiprocessing: b7. module started out as an exact emulation
of the *note threading: 10b. 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
‘Process’, which is passed a callable object and a collection of
arguments.  The ‘start()’ method sets the callable running in a
subprocess, after which you can call the ‘is_alive()’ method to check
whether the subprocess is still running and the ‘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.

     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

A *note Queue: dde. is used to communicate the result of the factorial.
The *note Queue: dde. 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 *note Queue: dde, 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, ‘Pool’ and ‘Manager’, provide higher-level
interfaces.  ‘Pool’ will create a fixed number of worker processes, and
requests can then be distributed to the workers by calling ‘apply()’ or
‘apply_async()’ to add a single request, and *note map(): cf7. or
‘map_async()’ to add a number of requests.  The following code uses a
‘Pool’ to spread requests across 5 worker processes and retrieve a list
of results:

     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

This produces the following output:

     1
     39916800
     51090942171709440000
     8222838654177922817725562880000000
     33452526613163807108170062053440751665152000000000
     ...

The other high-level interface, the ‘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 *note dict(): 164. method; the worker processes then insert
values into the dictionary.  (Locking is not done for you automatically,
which doesn’t matter in this example.  ‘Manager’’s methods also include
‘Lock()’, ‘RLock()’, and ‘Semaphore()’ to create shared locks.)

     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

This will produce the output:

     1 1
     11 39916800
     21 51090942171709440000
     31 8222838654177922817725562880000000
     41 33452526613163807108170062053440751665152000000000
     51 15511187532873822802242430164693032110632597200169861120000...

也參考
......

*note multiprocessing: b7. 模块的文档。

PEP 371(1) - 添加多任务处理包

     PEP 由 Jesse Noller 和 Richard Oudkerk 撰写，由 Richard Oudkerk 和
     Jesse Noller 实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0371


File: python.info,  Node: PEP 3101 高级字符串格式,  Next: PEP 3105 print 改为函数,  Prev: PEP 371 多任务处理包,  Up: Python 2 6 有什么新变化

1.12.7 PEP 3101: 高级字符串格式
-------------------------------

In Python 3.0, the ‘%’ operator is supplemented by a more powerful
string formatting method, *note format(): 5d5.  Support for the *note
str.format(): 5d4. method has been backported to Python 2.6.

In 2.6, both 8-bit and Unicode strings have a ‘.format()’ method that
treats the string as a template and takes the arguments to be formatted.
The formatting template uses curly brackets (‘{’, ‘}’) as special
characters:

     >>> # 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'

Curly brackets can be escaped by doubling them:

     >>> "Empty dict: {{}}".format()
     "Empty dict: {}"

Field names can be integers indicating positional arguments, such as
‘{0}’, ‘{1}’, etc.  or names of keyword arguments.  You can also supply
compound field names that read attributes or access dictionary keys:

     >>> 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'

Note that when using dictionary-style notation such as ‘[.mp4]’, you
don’t need to put any quotation marks around the string; it will look up
the value using ‘.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:

     >>> # 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'

Format specifiers can reference other fields through nesting:

     >>> fmt = '{0:{1}}'
     >>> width = 15
     >>> fmt.format('Invoice #1234', width)
     'Invoice #1234  '
     >>> width = 35
     >>> fmt.format('Invoice #1234', width)
     'Invoice #1234                      '

可以指定所需宽度内的字段对齐方式：

字符                 效果
                     
----------------------------------------------------------------------
                     
< (默认)             左对齐
                     
                     
>                    右对齐
                     
                     
^                    居中对齐
                     
                     
=                    （仅适用于数字类型）在符号后加空格。
                     

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:

     >>> '{0:g}'.format(3.75)
     '3.75'
     >>> '{0:e}'.format(3.75)
     '3.750000e+00'

A variety of presentation types are available.  Consult the 2.6
documentation for a *note complete list: de0.; here’s a sample:

‘b’       二进制。输出以2为底的数字。
          
          
‘c’       字符。在打印之前将整数转换为相应的Unicode字符。
          
          
‘d’       十进制整数。输出基数为10的数字。
          
          
‘o’       八进制格式。输出基数为8的数字。
          
          
‘x’       十六进制格式输出基数为16的数字，使用小写字母表示9以上的数字。
          
          
‘e’       指数表示法。用字母 ’e’ 以科学计数法打印数字以表示指数。
          
          
‘g’       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.
          
          
‘n’       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.
          
          
‘%’       Percentage.  Multiplies the number by 100 and displays in fixed (’f’)
          format, followed by a percent sign.
          

Classes and types can define a *note __format__(): a2f. method to
control how they’re formatted.  It receives a single argument, the
format specifier:

     def __format__(self, format_spec):
         if isinstance(format_spec, unicode):
             return unicode(str(self))
         else:
             return str(self)

There’s also a *note format(): 5d5. builtin that will format a single
value.  It calls the type’s *note __format__(): a2f. method with the
provided specifier:

     >>> format(75.6564, '.2f')
     '75.66'

也參考
......

*note 格式字符串语法: de0.

     格式字段的参考文档。

PEP 3101(1) - 高级字符串格式

     PEP 由 Eric V. Smith 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3101


File: python.info,  Node: PEP 3105 print 改为函数,  Next: PEP 3110 异常处理的变更,  Prev: PEP 3101 高级字符串格式,  Up: Python 2 6 有什么新变化

1.12.8 PEP 3105: ‘print’ 改为函数
---------------------------------

The ‘print’ statement becomes the *note print(): 971. function in Python
3.0.  Making *note print(): 971. a function makes it possible to replace
the function by doing ‘def print(...)’ or importing a new function from
somewhere else.

Python 2.6 has a ‘__future__’ import that removes ‘print’ as language
syntax, letting you use the functional form instead.  For example:

     >>> from __future__ import print_function
     >>> print('# of entries', len(dictionary), file=sys.stderr)

The signature of the new function is:

     def print(*args, sep=' ', end='\n', file=None)

The parameters are:

        * `args': positional arguments whose values will be printed out.

        * `sep': the separator, which will be printed between arguments.

        * `end': the ending text, which will be printed after all of the
          arguments have been output.

        * `file': the file object to which the output will be sent.

也參考
......

PEP 3105(1) - print 改为函数

     PEP 由 Georg Brandl 撰写

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3105


File: python.info,  Node: PEP 3110 异常处理的变更,  Next: PEP 3112 字节字面值,  Prev: PEP 3105 print 改为函数,  Up: Python 2 6 有什么新变化

1.12.9 PEP 3110: 异常处理的变更
-------------------------------

One error that Python programmers occasionally make is writing the
following code:

     try:
         ...
     except TypeError, ValueError:  # Wrong!
         ...

The author is probably trying to catch both *note TypeError: 1fe. and
*note ValueError: 16d. exceptions, but this code actually does something
different: it will catch *note TypeError: 1fe. and bind the resulting
exception object to the local name ‘"ValueError"’.  The *note
ValueError: 16d. exception will not be caught at all.  The correct code
specifies a tuple of exceptions:

     try:
         ...
     except (TypeError, ValueError):
         ...

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 ‘exc’, you must write:

     try:
         ...
     except TypeError as exc:
         ...

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.

也參考
......

PEP 3110(1) - 在 Python 3000 中捕获异常

     PEP 由 Collin Winter 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3110


File: python.info,  Node: PEP 3112 字节字面值,  Next: PEP 3116 新 I/O 库,  Prev: PEP 3110 异常处理的变更,  Up: Python 2 6 有什么新变化

1.12.10 PEP 3112: 字节字面值
----------------------------

Python 3.0 adopts Unicode as the language’s fundamental string type and
denotes 8-bit literals differently, either as ‘b'string'’ or using a
*note bytes: 172. constructor.  For future compatibility, Python 2.6
adds *note bytes: 172. as a synonym for the *note str: 205. type, and it
also supports the ‘b''’ notation.

The 2.6 *note str: 205. differs from 3.0’s *note bytes: 172. type in
various ways; most notably, the constructor is completely different.  In
3.0, ‘bytes([65, 66, 67])’ is 3 elements long, containing the bytes
representing ‘ABC’; in 2.6, ‘bytes([65, 66, 67])’ returns the 12-byte
string representing the *note str(): 205. of the list.

The primary use of *note bytes: 172. in 2.6 will be to write tests of
object type such as ‘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 *note bytes:
172. or *note str: 205. to represent your intention exactly, and the
resulting code will also be correct in Python 3.0.

There’s also a ‘__future__’ import that causes all string literals to
become Unicode strings.  This means that ‘\u’ escape sequences can be
used to include Unicode characters:

     from __future__ import unicode_literals

     s = ('\u751f\u3080\u304e\u3000\u751f\u3054'
          '\u3081\u3000\u751f\u305f\u307e\u3054')

     print len(s)               # 12 Unicode characters

At the C level, Python 3.0 will rename the existing 8-bit string type,
called ‘PyStringObject’ in Python 2.x, to *note PyBytesObject: de4.
Python 2.6 uses ‘#define’ to support using the names *note
PyBytesObject(): de4, *note PyBytes_Check(): de5, *note
PyBytes_FromStringAndSize(): de6, and all the other functions and macros
used with strings.

Instances of the *note bytes: 172. type are immutable just as strings
are.  A new *note bytearray: 173. type stores a mutable sequence of
bytes:

     >>> 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'

Byte arrays support most of the methods of string types, such as
‘startswith()’/‘endswith()’, ‘find()’/‘rfind()’, and some of the methods
of lists, such as ‘append()’, ‘pop()’, and ‘reverse()’.

     >>> b = bytearray('ABC')
     >>> b.append('d')
     >>> b.append(ord('e'))
     >>> b
     bytearray(b'ABCde')

There’s also a corresponding C API, with *note PyByteArray_FromObject():
de7, *note PyByteArray_FromStringAndSize(): de8, and various other
functions.

也參考
......

PEP 3112(1) - Python 3000 中的字节字面值

     PEP 由 Jason Orendorff 撰写， 补丁2.6 由 Christian Heimes 撰写。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3112


File: python.info,  Node: PEP 3116 新 I/O 库,  Next: PEP 3118 修改缓冲区协议,  Prev: PEP 3112 字节字面值,  Up: Python 2 6 有什么新变化

1.12.11 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 ‘read()’ and ‘write()’, but they may not
support *note readline(): de, for example.  Python 3.0 introduces a
layered I/O library in the *note io: a1. 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 *note
io: a1. module:

   * ‘RawIOBase’ defines raw I/O operations: ‘read()’, ‘readinto()’,
     ‘write()’, ‘seek()’, ‘tell()’, ‘truncate()’, and ‘close()’.  Most
     of the methods of this class will often map to a single system
     call.  There are also ‘readable()’, ‘writable()’, and ‘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.

   * ‘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
     ‘RawIOBase’, and adds a ‘raw’ attribute holding the underlying raw
     object.

     There are five concrete classes implementing this ABC.
     ‘BufferedWriter’ and ‘BufferedReader’ are for objects that support
     write-only or read-only usage that have a ‘seek()’ method for
     random access.  ‘BufferedRandom’ objects support read and write
     access upon the same underlying stream, and ‘BufferedRWPair’ is for
     objects such as TTYs that have both read and write operations
     acting upon unconnected streams of data.  The ‘BytesIO’ class
     supports reading, writing, and seeking over an in-memory buffer.

   * ‘TextIOBase’: Provides functions for reading and writing strings
     (remember, strings will be Unicode in Python 3.0), and supporting
     *note universal newlines: 6eb.  ‘TextIOBase’ defines the *note
     readline(): de. method and supports iteration upon objects.

     There are two concrete implementations.  ‘TextIOWrapper’ wraps a
     buffered I/O object, supporting all of the methods for text I/O and
     adding a ‘buffer’ attribute for access to the underlying object.
     ‘StringIO’ simply buffers everything in memory without ever writing
     anything to disk.

     (In Python 2.6, *note io.StringIO: 91a. is implemented in pure
     Python, so it’s pretty slow.  You should therefore stick with the
     existing ‘StringIO’ module or ‘cStringIO’ for now.  At some point
     Python 3.0’s *note io: a1. module will be rewritten into C for
     speed, and perhaps the C implementation will be backported to the
     2.x releases.)

In Python 2.6, the underlying implementations haven’t been restructured
to build on top of the *note io: a1. 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.

也參考
......

PEP 3116(1) - 新 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.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3116


File: python.info,  Node: PEP 3118 修改缓冲区协议,  Next: PEP 3119 抽象基类,  Prev: PEP 3116 新 I/O 库,  Up: Python 2 6 有什么新变化

1.12.12 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 *note re: dd. 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 ‘PyObject_GetBuffer(PyObject
*obj, Py_buffer *view, int flags)’, which takes an object and a set of
flags, and fills in the ‘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 ‘PyBuffer_Release(Py_buffer *view)’
to indicate that the external caller is done.

The `flags' argument to *note PyObject_GetBuffer(): deb. specifies
constraints upon the memory returned.  Some examples are:

        * ‘PyBUF_WRITABLE’ indicates that the memory must be writable.

        * ‘PyBUF_LOCK’ requests a read-only or exclusive lock on the
          memory.

        * ‘PyBUF_C_CONTIGUOUS’ and ‘PyBUF_F_CONTIGUOUS’ requests a
          C-contiguous (last dimension varies the fastest) or
          Fortran-contiguous (first dimension varies the fastest) array
          layout.

Two new argument codes for *note PyArg_ParseTuple(): 393, ‘s*’ and ‘z*’,
return locked buffer objects for a parameter.

也參考
......

PEP 3118(1) - 修改缓冲区协议

     PEP 由 Travis Oliphant 和 Carl Banks 撰写，由 Travis Oliphant 实现
     。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3118


File: python.info,  Node: PEP 3119 抽象基类,  Next: PEP 3127 整型文字支持和语法,  Prev: PEP 3118 修改缓冲区协议,  Up: Python 2 6 有什么新变化

1.12.13 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 *note abc: 3. module
containing a metaclass called ‘ABCMeta’, special handling of this
metaclass by the *note isinstance(): 551. and *note issubclass(): 552.
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 ‘obj[1]’
works.  Does it imply that setting items with ‘obj[2] = value’ works?
Or that the object will have ‘keys()’, ‘values()’, and ‘items()’
methods?  What about the iterative variants such as ‘iterkeys()’?  *note
copy(): 25. and ‘update()’?  Iterating over the object with *note
iter(): ded.?

The Python 2.6 *note collections: 1d. module includes a number of
different ABCs that represent these distinctions.  ‘Iterable’ indicates
that a class defines *note __iter__(): 608, and ‘Container’ means the
class defines a *note __contains__(): dee. method and therefore supports
‘x in y’ expressions.  The basic dictionary interface of getting items,
setting items, and ‘keys()’, ‘values()’, and ‘items()’, is defined by
the ‘MutableMapping’ ABC.

You can derive your own classes from a particular ABC to indicate they
support that ABC’s interface:

     import collections

     class Storage(collections.MutableMapping):
         ...

Alternatively, you could write the class without deriving from the
desired ABC and instead register the class by calling the ABC’s
‘register()’ method:

     import collections

     class Storage:
         ...

     collections.MutableMapping.register(Storage)

For classes that you write, deriving from the ABC is probably clearer.
The ‘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
‘PrintableType’ ABC, it’s legal to do:

     # Register Python's types
     PrintableType.register(int)
     PrintableType.register(float)
     PrintableType.register(str)

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:

     def func(d):
         if not isinstance(d, collections.MutableMapping):
             raise ValueError("Mapping object expected, not %r" % d)

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 ‘abc.ABCMeta’ as the metaclass in a
class definition:

     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):
             ...

In the ‘Drawable’ ABC above, the ‘draw_doubled()’ method renders the
object at twice its size and can be implemented in terms of other
methods described in ‘Drawable’.  Classes implementing this ABC
therefore don’t need to provide their own implementation of
‘draw_doubled()’, though they can do so.  An implementation of ‘draw()’
is necessary, though; the ABC can’t provide a useful generic
implementation.

You can apply the ‘@abstractmethod’ decorator to methods such as
‘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:

     >>> 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
     >>>

Abstract data attributes can be declared using the ‘@abstractproperty’
decorator:

     from abc import abstractproperty
     ...

     @abstractproperty
     def readonly(self):
        return self._x

Subclasses must then define a ‘readonly()’ property.

也參考
......

PEP 3119(1) - 引入抽象基类

     PEP written by Guido van Rossum and Talin.  Implemented by Guido
     van Rossum.  Backported to 2.6 by Benjamin Aranguren, with Alex
     Martelli.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3119


File: python.info,  Node: PEP 3127 整型文字支持和语法,  Next: PEP 3129 类装饰器,  Prev: PEP 3119 抽象基类,  Up: Python 2 6 有什么新变化

1.12.14 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":

     >>> 0o21, 2*8 + 1
     (17, 17)
     >>> 0b101111
     47

The *note oct(): d2d. builtin still returns numbers prefixed with a
leading zero, and a new *note bin(): d08. builtin returns the binary
representation for a number:

     >>> oct(42)
     '052'
     >>> future_builtins.oct(42)
     '0o52'
     >>> bin(173)
     '0b10101101'

The *note int(): 204. and ‘long()’ builtins will now accept the "0o" and
"0b" prefixes when base-8 or base-2 are requested, or when the `base'
argument is zero (signalling that the base used should be determined
from the string):

     >>> int ('0o52', 0)
     42
     >>> int('1101', 2)
     13
     >>> int('0b1101', 2)
     13
     >>> int('0b1101', 0)
     13

也參考
......

PEP 3127(1) - 整型文字支持和语法

     PEP written by Patrick Maupin; backported to 2.6 by Eric Smith.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3127


File: python.info,  Node: PEP 3129 类装饰器,  Next: PEP 3141 A Type Hierarchy for Numbers,  Prev: PEP 3127 整型文字支持和语法,  Up: Python 2 6 有什么新变化

1.12.15 PEP 3129: 类装饰器
--------------------------

Decorators have been extended from functions to classes.  It’s now legal
to write:

     @foo
     @bar
     class A:
       pass

这相当于:

     class A:
       pass

     A = foo(bar(A))

也參考
......

PEP 3129(1) - 类装饰器

     PEP 由 Collin Winter 撰写

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3129


File: python.info,  Node: PEP 3141 A Type Hierarchy for Numbers,  Next: 其他语言特性修改<11>,  Prev: PEP 3129 类装饰器,  Up: Python 2 6 有什么新变化

1.12.16 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
*note numbers: c1. module.

The most general ABC is ‘Number’.  It defines no operations at all, and
only exists to allow checking if an object is a number by doing
‘isinstance(obj, Number)’.

‘Complex’ is a subclass of ‘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 ‘Complex’.

‘Real’ further derives from ‘Complex’, and adds operations that only
work on real numbers: ‘floor()’, ‘trunc()’, rounding, taking the
remainder mod N, floor division, and comparisons.

‘Rational’ numbers derive from ‘Real’, have ‘numerator’ and
‘denominator’ properties, and can be converted to floats.  Python 2.6
adds a simple rational-number class, ‘Fraction’, in the *note fractions:
81. module.  (It’s called ‘Fraction’ instead of ‘Rational’ to avoid a
name clash with *note numbers.Rational: d20.)

‘Integral’ numbers derive from ‘Rational’, and can be shifted left and
right with ‘<<’ and ‘>>’, combined using bitwise operations such as ‘&’
and ‘|’, and can be used as array indexes and slice boundaries.

In Python 3.0, the PEP slightly redefines the existing builtins *note
round(): d35, *note math.floor(): df2, *note math.ceil(): df3, and adds
a new one, *note math.trunc(): df4, that’s been backported to Python
2.6.  *note math.trunc(): df4. rounds toward zero, returning the closest
‘Integral’ that’s between the function’s argument and zero.

也參考
......

PEP 3141(1) - A Type Hierarchy for Numbers

     PEP 由 Jeffrey Yasskin 撰写

Scheme’s numerical tower(2), from the Guile manual.

Scheme’s number datatypes(3) from the R5RS Scheme specification.

* Menu:

* fractions 模块::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3141

   (2) 
https://www.gnu.org/software/guile/manual/html_node/Numerical-Tower.html#Numerical-Tower

   (3) 
http://schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-9.html#%_sec_6.2


File: python.info,  Node: fractions 模块,  Up: PEP 3141 A Type Hierarchy for Numbers

1.12.16.1 ‘fractions’ 模块
..........................

To fill out the hierarchy of numeric types, the *note fractions: 81.
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 ‘2/3’ that floating-point numbers can
only approximate.

The ‘Fraction’ constructor takes two ‘Integral’ values that will be the
numerator and denominator of the resulting fraction.

     >>> 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)

For converting floating-point numbers to rationals, the float type now
has an ‘as_integer_ratio()’ method that returns the numerator and
denominator for a fraction that evaluates to the same floating-point
value:

     >>> (2.5) .as_integer_ratio()
     (5, 2)
     >>> (3.1415) .as_integer_ratio()
     (7074029114692207L, 2251799813685248L)
     >>> (1./3) .as_integer_ratio()
     (6004799503160661L, 18014398509481984L)

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
`exactly'.

The *note fractions: 81. module is based upon an implementation by
Sjoerd Mullender that was in Python’s ‘Demo/classes/’ directory for a
long time.  This implementation was significantly updated by Jeffrey
Yasskin.


File: python.info,  Node: 其他语言特性修改<11>,  Next: 新增和改进的模块<2>,  Prev: PEP 3141 A Type Hierarchy for Numbers,  Up: Python 2 6 有什么新变化

1.12.17 其他语言特性修改
------------------------

对Python 语言核心进行的小改动：

   * Directories and zip archives containing a ‘__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(1).)

   * The *note hasattr(): 54a. function was catching and ignoring all
     errors, under the assumption that they meant a *note __getattr__():
     42a. method was failing somehow and the return value of *note
     hasattr(): 54a. would therefore be ‘False’.  This logic shouldn’t
     be applied to *note KeyboardInterrupt: 2cc. and *note SystemExit:
     6f3, however; Python 2.6 will no longer discard such exceptions
     when *note hasattr(): 54a. encounters them.  (Fixed by Benjamin
     Peterson; bpo-2196(2).)

   * When calling a function using the ‘**’ syntax to provide keyword
     arguments, you are no longer required to use a Python dictionary;
     any mapping will now work:

          >>> def f(**kw):
          ...    print sorted(kw)
          ...
          >>> ud=UserDict.UserDict()
          >>> ud['a'] = 1
          >>> ud['b'] = 'string'
          >>> f(**ud)
          ['a', 'b']

     （由 Alexander Belopolsky 在 bpo-1686487(3) 中贡献。）

     It’s also become legal to provide keyword arguments after a ‘*args’
     argument to a function call.

          >>> def f(*args, **kw):
          ...     print args, kw
          ...
          >>> f(1,2,3, *(4,5,6), keyword=13)
          (1, 2, 3, 4, 5, 6) {'keyword': 13}

     Previously this would have been a syntax error.  (Contributed by
     Amaury Forgeot d’Arc; bpo-3473(4).)

   * A new builtin, ‘next(iterator, [default])’ returns the next item
     from the specified iterator.  If the `default' argument is
     supplied, it will be returned if `iterator' has been exhausted;
     otherwise, the *note StopIteration: 581. exception will be raised.
     (Backported in bpo-2719(5).)

   * Tuples now have ‘index()’ and ‘count()’ methods matching the list
     type’s ‘index()’ and ‘count()’ methods:

          >>> t = (0,1,2,3,4,0,1,2)
          >>> t.index(3)
          3
          >>> t.count(0)
          2

     （由 Raymond Hettinger 贡献）

   * The built-in types now have improved support for extended slicing
     syntax, accepting various combinations of ‘(start, stop, step)’.
     Previously, the support was partial and certain corner cases
     wouldn’t work.  (Implemented by Thomas Wouters.)

   * Properties now have three attributes, ‘getter’, ‘setter’ and
     ‘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:

          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

   * Several methods of the built-in set types now accept multiple
     iterables: ‘intersection()’, ‘intersection_update()’, ‘union()’,
     ‘update()’, ‘difference()’ and ‘difference_update()’.

          >>> s=set('1234567890')
          >>> s.intersection('abc123', 'cdf246')  # Intersection between all inputs
          set(['2'])
          >>> s.difference('246', '789')
          set(['1', '0', '3', '5'])

     （由 Raymond Hettinger 贡献。）

   * Many floating-point features were added.  The *note float(): 1fd.
     function will now turn the string ‘nan’ into an IEEE 754 Not A
     Number value, and ‘+inf’ and ‘-inf’ into positive or negative
     infinity.  This works on any platform with IEEE 754 semantics.
     (Contributed by Christian Heimes; bpo-1635(6).)

     Other functions in the *note math: b1. module, ‘isinf()’ and
     ‘isnan()’, return true if their floating-point argument is infinite
     or Not A Number.  (bpo-1640(7))

     Conversion functions were added to convert floating-point numbers
     into hexadecimal strings (bpo-3008(8)).  These functions convert
     floats to and from a string representation without introducing
     rounding errors from the conversion between decimal and binary.
     Floats have a *note hex(): d2e. method that returns a string
     representation, and the ‘float.fromhex()’ method converts a string
     back into a number:

          >>> a = 3.75
          >>> a.hex()
          '0x1.e000000000000p+1'
          >>> float.fromhex('0x1.e000000000000p+1')
          3.75
          >>> b=1./3
          >>> b.hex()
          '0x1.5555555555555p-2'

   * A numerical nicety: when creating a complex number from two floats
     on systems that support signed zeros (-0 and +0), the *note
     complex(): 2c1. constructor will now preserve the sign of the zero.
     (Fixed by Mark T. Dickinson; bpo-1507(9).)

   * Classes that inherit a *note __hash__(): 44c. method from a parent
     class can set ‘__hash__ = None’ to indicate that the class isn’t
     hashable.  This will make ‘hash(obj)’ raise a *note TypeError: 1fe.
     and the class will not be indicated as implementing the ‘Hashable’
     ABC.

     You should do this when you’ve defined a ‘__cmp__()’ or *note
     __eq__(): 44b. method that compares objects by their value rather
     than by identity.  All objects have a default hash method that uses
     ‘id(obj)’ as the hash value.  There’s no tidy way to remove the
     *note __hash__(): 44c. method inherited from a parent class, so
     assigning ‘None’ was implemented as an override.  At the C level,
     extensions can set ‘tp_hash’ to *note
     PyObject_HashNotImplemented(): df7.  (Fixed by Nick Coghlan and
     Amaury Forgeot d’Arc; bpo-2235(10).)

   * The *note GeneratorExit: df8. exception now subclasses *note
     BaseException: 2db. instead of *note Exception: 2dc.  This means
     that an exception handler that does ‘except Exception:’ will not
     inadvertently catch *note GeneratorExit: df8.  (Contributed by Chad
     Austin; bpo-1537(11).)

   * Generator objects now have a ‘gi_code’ attribute that refers to the
     original code object backing the generator.  (Contributed by Collin
     Winter; bpo-1473257(12).)

   * The *note compile(): 2e7. built-in function now accepts keyword
     arguments as well as positional parameters.  (Contributed by Thomas
     Wouters; bpo-1444529(13).)

   * The *note complex(): 2c1. constructor now accepts strings
     containing parenthesized complex numbers, meaning that
     ‘complex(repr(cplx))’ will now round-trip values.  For example,
     ‘complex('(3+4j)')’ now returns the value (3+4j).
     (bpo-1491866(14))

   * The string ‘translate()’ method now accepts ‘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(15).)

   * The built-in *note dir(): df9. function now checks for a *note
     __dir__(): 42b. 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 *note dir(): df9. produces.  Objects that have *note
     __getattr__(): 42a. or *note __getattribute__(): 549. methods can
     use this to advertise pseudo-attributes they will honor.
     (bpo-1591665(16))

   * Instance method objects have new attributes for the object and
     function comprising the method; the new synonym for ‘im_self’ is
     ‘__self__’, and ‘im_func’ is also available as ‘__func__’.  The old
     names are still supported in Python 2.6, but are gone in 3.0.

   * An obscure change: when you use the *note locals(): 556. function
     inside a *note class: d32. statement, the resulting dictionary no
     longer returns free variables.  (Free variables, in this case, are
     variables referenced in the ‘class’ statement that aren’t
     attributes of the class.)

* Menu:

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

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1739468

   (2) https://bugs.python.org/issue2196

   (3) https://bugs.python.org/issue1686487

   (4) https://bugs.python.org/issue3473

   (5) https://bugs.python.org/issue2719

   (6) https://bugs.python.org/issue1635

   (7) https://bugs.python.org/issue1640

   (8) https://bugs.python.org/issue3008

   (9) https://bugs.python.org/issue1507

   (10) https://bugs.python.org/issue2235

   (11) https://bugs.python.org/issue1537

   (12) https://bugs.python.org/issue1473257

   (13) https://bugs.python.org/issue1444529

   (14) https://bugs.python.org/issue1491866

   (15) https://bugs.python.org/issue1193128

   (16) https://bugs.python.org/issue1591665


File: python.info,  Node: 性能优化<10>,  Next: Interpreter Changes<2>,  Up: 其他语言特性修改<11>

1.12.17.1 性能优化
..................

   * The *note warnings: 12f. 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(1).)

   * 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(2).)

     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
     ‘Py_TPFLAGS_HAVE_VERSION_TAG’ to the module’s ‘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
     ‘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(3) for some discussion.)

   * 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(4).)

   * All of the functions in the *note struct: f8. module have been
     rewritten in C, thanks to work at the Need For Speed sprint.
     (Contributed by Raymond Hettinger.)

   * 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.)

   * Unicode strings now use faster code for detecting whitespace and
     line breaks; this speeds up the ‘split()’ method by about 25% and
     ‘splitlines()’ by 35%.  (Contributed by Antoine Pitrou.)  Memory
     usage is reduced by using pymalloc for the Unicode string’s data.

   * The ‘with’ statement now stores the *note __exit__(): d5e. method
     on the stack, producing a small speedup.  (Implemented by Jeffrey
     Yasskin.)

   * 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1631171

   (2) https://bugs.python.org/issue1700288

   (3) https://bugs.python.org/issue1878

   (4) https://bugs.python.org/issue1819


File: python.info,  Node: Interpreter Changes<2>,  Prev: 性能优化<10>,  Up: 其他语言特性修改<11>

1.12.17.2 Interpreter Changes
.............................

Two command-line options have been reserved for use by other Python
implementations.  The *note -J: dfd. switch has been reserved for use by
Jython for Jython-specific options, such as switches that are passed to
the underlying JVM. *note -X: 290. 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 ‘.pyc’ or ‘.pyo’ files by
supplying the *note -B: dfe. switch to the Python interpreter, or by
setting the *note PYTHONDONTWRITEBYTECODE: dff. environment variable
before running the interpreter.  This setting is available to Python
programs as the ‘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 *note PYTHONIOENCODING: a14. environment
variable before running the interpreter.  The value should be a string
in the form ‘<encoding>’ or ‘<encoding>:<errorhandler>’.  The `encoding'
part specifies the encoding’s name, e.g.  ‘utf-8’ or ‘latin-1’; the
optional `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.)


File: python.info,  Node: 新增和改进的模块<2>,  Next: Deprecations and Removals,  Prev: 其他语言特性修改<11>,  Up: Python 2 6 有什么新变化

1.12.18 新增和改进的模块
------------------------

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 ‘Misc/NEWS’
file in the source tree for a more complete list of changes, or look
through the Subversion logs for all the details.

   * The *note asyncore: a. and *note asynchat: 8. modules are being
     actively maintained again, and a number of patches and bugfixes
     were applied.  (Maintained by Josiah Carlson; see bpo-1736190(1)
     for one patch.)

   * The ‘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(2).  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 ‘bsddb.dbshelve’ module now uses the highest pickling protocol
     available, instead of restricting itself to protocol 1.
     (Contributed by W. Barnes.)

   * The *note cgi: 15. 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(3).)

     The ‘parse_qs()’ and ‘parse_qsl()’ functions have been relocated
     from the *note cgi: 15. module to the ‘urlparse’ module.  The
     versions still available in the *note cgi: 15. module will trigger
     *note PendingDeprecationWarning: 15c. messages in 2.6
     (bpo-600362(4)).

   * The *note cmath: 18. module underwent extensive revision,
     contributed by Mark Dickinson and Christian Heimes.  Five new
     functions were added:

        * ‘polar()’ converts a complex number to polar form, returning
          the modulus and argument of the complex number.

        * ‘rect()’ does the opposite, turning a modulus, argument pair
          back into the corresponding complex number.

        * ‘phase()’ returns the argument (also called the angle) of a
          complex number.

        * ‘isnan()’ returns True if either the real or imaginary part of
          its argument is a NaN.

        * ‘isinf()’ returns True if either the real or imaginary part of
          its argument is infinite.

     The revisions also improved the numerical soundness of the *note
     cmath: 18. 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(5) for the
     details.  The branch cuts for ‘asinh()’, ‘atanh()’: and ‘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 *note cmath: 18. module now handles IEEE
     754 special values and floating-point exceptions in a manner
     consistent with Annex ’G’ of the C99 standard.

   * A new data type in the *note collections: 1d. module:
     ‘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:

          >>> 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)

     Several places in the standard library that returned tuples have
     been modified to return ‘namedtuple’ instances.  For example, the
     ‘Decimal.as_tuple()’ method now returns a named tuple with ‘sign’,
     ‘digits’, and ‘exponent’ fields.

     （由 Raymond Hettinger 贡献。）

   * Another change to the *note collections: 1d. module is that the
     ‘deque’ type now supports an optional `maxlen' parameter; if
     supplied, the deque’s size will be restricted to no more than
     `maxlen' items.  Adding more items to a full deque causes old items
     to be discarded.

          >>> 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)

     （由 Raymond Hettinger 贡献。）

   * The ‘Cookie’ module’s ‘Morsel’ objects now support an ‘httponly’
     attribute.  In some browsers.  cookies with this attribute set
     cannot be accessed or manipulated by JavaScript code.  (Contributed
     by Arvin Schnell; bpo-1638033(6).)

   * A new window method in the *note curses: 2b. module, ‘chgat()’,
     changes the display attributes for a certain number of characters
     on a single line.  (Contributed by Fabian Kreutz.)

          # Boldface text starting at y=0,x=21
          # and affecting the rest of the line.
          stdscr.chgat(0, 21, curses.A_BOLD)

     The ‘Textbox’ class in the *note curses.textpad: 2e. module now
     supports editing in insert mode as well as overwrite mode.  Insert
     mode is enabled by supplying a true value for the `insert_mode'
     parameter when creating the ‘Textbox’ instance.

   * The *note datetime: 30. module’s ‘strftime()’ methods now support a
     ‘%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(7).)

   * The *note decimal: 35. module was updated to version 1.66 of the
     General Decimal Specification(8).  New features include some
     methods for some basic mathematical functions such as ‘exp()’ and
     ‘log10()’:

          >>> Decimal(1).exp()
          Decimal("2.718281828459045235360287471")
          >>> Decimal("2.7182818").ln()
          Decimal("0.9999999895305022877376682436")
          >>> Decimal(1000).log10()
          Decimal("3")

     The ‘as_tuple()’ method of ‘Decimal’ objects now returns a named
     tuple with ‘sign’, ‘digits’, and ‘exponent’ fields.

     (Implemented by Facundo Batista and Mark Dickinson.  Named tuple
     support added by Raymond Hettinger.)

   * The *note difflib: 36. module’s ‘SequenceMatcher’ class now returns
     named tuples representing matches, with ‘a’, ‘b’, and ‘size’
     attributes.  (Contributed by Raymond Hettinger.)

   * An optional ‘timeout’ parameter, specifying a timeout measured in
     seconds, was added to the *note ftplib.FTP: 1a6. class constructor
     as well as the ‘connect()’ method.  (Added by Facundo Batista.)
     Also, the ‘FTP’ class’s ‘storbinary()’ and ‘storlines()’ now take
     an optional `callback' parameter that will be called with each
     block of data after the data has been sent.  (Contributed by Phil
     Schwartz; bpo-1221598(9).)

   * The ‘reduce()’ built-in function is also available in the *note
     functools: 83. module.  In Python 3.0, the builtin has been dropped
     and ‘reduce()’ is only available from *note functools: 83.;
     currently there are no plans to drop the builtin in the 2.x series.
     (Patched by Christian Heimes; bpo-1739906(10).)

   * When possible, the *note getpass: 86. module will now use
     ‘/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.)

   * The *note glob.glob(): 6bd. function can now return Unicode
     filenames if a Unicode path was used and Unicode filenames are
     matched within the directory.  (bpo-1001604(11))

   * A new function in the *note heapq: 8d. module, ‘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:

          >>> list(heapq.merge([1, 3, 5, 9], [2, 8, 16]))
          [1, 2, 3, 5, 8, 9, 16]

     Another new function, ‘heappushpop(heap, item)’, pushes `item' onto
     `heap', then pops off and returns the smallest item.  This is more
     efficient than making a call to ‘heappush()’ and then ‘heappop()’.

     *note heapq: 8d. is now implemented to only use less-than
     comparison, instead of the less-than-or-equal comparison it
     previously used.  This makes *note heapq: 8d.’s usage of a type
     match the *note list.sort(): 547. method.  (Contributed by Raymond
     Hettinger.)

   * An optional ‘timeout’ parameter, specifying a timeout measured in
     seconds, was added to the ‘httplib.HTTPConnection’ and
     ‘HTTPSConnection’ class constructors.  (Added by Facundo Batista.)

   * Most of the *note inspect: a0. module’s functions, such as
     ‘getmoduleinfo()’ and ‘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.)

     Some new functions in the module include ‘isgenerator()’,
     ‘isgeneratorfunction()’, and ‘isabstract()’.

   * The *note itertools: a3. module gained several new functions.

     ‘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 `fillvalue'.  For example:

          >>> tuple(itertools.izip_longest([1,2,3], [1,2,3,4,5]))
          ((1, 1), (2, 2), (3, 3), (None, 4), (None, 5))

     ‘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.

          >>> 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)]

     The optional `repeat' keyword argument is used for taking the
     product of an iterable or a set of iterables with themselves,
     repeated `N' times.  With a single iterable argument, `N'-tuples
     are returned:

          >>> 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)]

     With two iterables, `2N'-tuples are returned.

          >>> 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)]

     ‘combinations(iterable, r)’ returns sub-sequences of length `r'
     from the elements of `iterable'.

          >>> 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')]

     ‘permutations(iter[, r])’ returns all the permutations of length
     `r' of the iterable’s elements.  If `r' is not specified, it will
     default to the number of elements produced by the iterable.

          >>> 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)]

     ‘itertools.chain(*iterables)’ is an existing function in *note
     itertools: a3. that gained a new constructor in Python 2.6.
     ‘itertools.chain.from_iterable(iterable)’ takes a single iterable
     that should return other iterables.  ‘chain()’ will then return all
     the elements of the first iterable, then all the elements of the
     second, and so on.

          >>> list(itertools.chain.from_iterable([[1,2,3], [4,5,6]]))
          [1, 2, 3, 4, 5, 6]

     (All contributed by Raymond Hettinger.)

   * The *note logging: aa. module’s ‘FileHandler’ class and its
     subclasses ‘WatchedFileHandler’, ‘RotatingFileHandler’, and
     ‘TimedRotatingFileHandler’ now have an optional `delay' parameter
     to their constructors.  If `delay' is true, opening of the log file
     is deferred until the first ‘emit()’ call is made.  (Contributed by
     Vinay Sajip.)

     ‘TimedRotatingFileHandler’ also has a `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.

   * Several new functions were added to the *note math: b1. module:

        * *note isinf(): e01. and *note isnan(): e02. determine whether
          a given float is a (positive or negative) infinity or a NaN
          (Not a Number), respectively.

        * *note copysign(): e03. copies the sign bit of an IEEE 754
          number, returning the absolute value of `x' combined with the
          sign bit of `y'.  For example, ‘math.copysign(1, -0.0)’
          returns -1.0.  (Contributed by Christian Heimes.)

        * *note factorial(): 1fc. computes the factorial of a number.
          (Contributed by Raymond Hettinger; bpo-2138(12).)

        * *note fsum(): e04. 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(13).)

        * *note acosh(): e05, *note asinh(): e06. and *note atanh():
          e07. compute the inverse hyperbolic functions.

        * *note log1p(): e08. returns the natural logarithm of `1+x'
          (base `e').

        * ‘trunc()’ rounds a number toward zero, returning the closest
          ‘Integral’ that’s between the function’s argument and zero.
          Added as part of the backport of *note PEP 3141’s type
          hierarchy for numbers: d1f.

   * The *note math: b1. 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, ‘sqrt(-1.)’
     should now give a *note ValueError: 16d. across almost all
     platforms, while ‘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 *note
     ValueError: 16d.  Where Annex ’F’ of the C99 standard recommends
     signaling ’overflow’, Python will raise *note OverflowError: a41.
     (See bpo-711019(14) and bpo-1640(15).)

     （由 Christian Heimes 和 Mark Dickinson 贡献。）

   * *note mmap: 31c. objects now have a ‘rfind()’ method that searches
     for a substring beginning at the end of the string and searching
     backwards.  The ‘find()’ method also gained an `end' parameter
     giving an index at which to stop searching.  (Contributed by John
     Lenton.)

   * The *note operator: c2. module gained a ‘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:

          >>> # 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'

     （由 Gregory Petrosyan 提供建议，之后由 Georg Brandl 贡献。）

     The ‘attrgetter()’ function now accepts dotted names and performs
     the corresponding attribute lookups:

          >>> inst_name = operator.attrgetter(
          ...        '__class__.__name__')
          >>> inst_name('')
          'str'
          >>> inst_name(help)
          '_Helper'

     （由 Barry Warsaw 提供建议，之后由 Georg Brandl 贡献。）

   * The *note os: c4. module now wraps several new system calls.
     ‘fchmod(fd, mode)’ and ‘fchown(fd, uid, gid)’ change the mode and
     ownership of an opened file, and ‘lchmod(path, mode)’ changes the
     mode of a symlink.  (Contributed by Georg Brandl and Christian
     Heimes.)

     ‘chflags()’ and ‘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 *note stat:
     f4. module; some possible values include ‘UF_IMMUTABLE’ to signal
     the file may not be changed and ‘UF_APPEND’ to indicate that data
     can only be appended to the file.  (Contributed by M. Levinson.)

     ‘os.closerange(low, high)’ efficiently closes all file descriptors
     from `low' to `high', ignoring any errors and not including `high'
     itself.  This function is now used by the *note subprocess: f9.
     module to make starting processes faster.  (Contributed by Georg
     Brandl; bpo-1663329(16).)

   * The ‘os.environ’ object’s ‘clear()’ method will now unset the
     environment variables using *note os.unsetenv(): 1cc. in addition
     to clearing the object’s keys.  (Contributed by Martin Horcicka;
     bpo-1181(17).)

   * The *note os.walk(): 747. function now has a ‘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(18))

   * In the *note os.path: c5. module, the ‘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, ‘os.path.splitext('.ipython')’ now returns ‘('.ipython',
     '')’ instead of ‘('', '.ipython')’.  (bpo-1115886(19))

     A new function, ‘os.path.relpath(path, start='.')’, returns a
     relative path from the ‘start’ path, if it’s supplied, or from the
     current working directory to the destination ‘path’.  (Contributed
     by Richard Barran; bpo-1339796(20).)

     On Windows, *note os.path.expandvars(): e09. 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(21).)

   * The Python debugger provided by the *note pdb: c9. 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(22).)

   * The *note pdb.post_mortem(): e0a. function, used to begin debugging
     a traceback, will now use the traceback returned by *note
     sys.exc_info(): d27. if no traceback is supplied.  (Contributed by
     Facundo Batista; bpo-1106316(23).)

   * The *note pickletools: cb. module now has an ‘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.)

   * A ‘get_data()’ function was added to the *note pkgutil: cd. module
     that returns the contents of resource files included with an
     installed Python package.  For example:

          >>> import pkgutil
          >>> print pkgutil.get_data('test', 'exception_hierarchy.txt')
          BaseException
           +-- SystemExit
           +-- KeyboardInterrupt
           +-- GeneratorExit
           +-- Exception
                +-- StopIteration
                +-- StandardError
           ...

     （由 Paul Moore 在 bpo-2439(24) 中贡献。）

   * The ‘pyexpat’ module’s ‘Parser’ objects now allow setting their
     ‘buffer_size’ attribute to change the size of the buffer used to
     hold character data.  (Contributed by Achim Gaedke; bpo-1137(25).)

   * The ‘Queue’ module now provides queue variants that retrieve
     entries in different orders.  The ‘PriorityQueue’ class stores
     queued items in a heap and retrieves them in priority order, and
     ‘LifoQueue’ retrieves the most recently added entries first,
     meaning that it behaves like a stack.  (Contributed by Raymond
     Hettinger.)

   * The *note random: dc. module’s ‘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
     ‘Random’ objects can’t be unpickled correctly on earlier versions
     of Python.  (Contributed by Shawn Ligocki; bpo-1727780(26).)

     The new ‘triangular(low, high, mode)’ function returns random
     numbers following a triangular distribution.  The returned values
     are between `low' and `high', not including `high' itself, and with
     `mode' as the most frequently occurring value in the distribution.
     (Contributed by Wladmir van der Laan and Raymond Hettinger;
     bpo-1681432(27).)

   * Long regular expression searches carried out by the *note re: dd.
     module will check for signals being delivered, so time-consuming
     searches can now be interrupted.  (Contributed by Josh Hoyt and
     Ralf Schmitt; bpo-846388(28).)

     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(29).)

   * The *note rlcompleter: e1. module’s ‘Completer.complete()’ method
     will now ignore exceptions triggered while evaluating a name.
     (Fixed by Lorenz Quack; bpo-2250(30).)

   * The *note sched: e3. module’s ‘scheduler’ instances now have a
     read-only *note queue: da. attribute that returns the contents of
     the scheduler’s queue, represented as a list of named tuples with
     the fields ‘(time, priority, action, argument)’.  (Contributed by
     Raymond Hettinger; bpo-1861(31).)

   * The *note select: e5. module now has wrapper functions for the
     Linux ‘epoll()’ and BSD ‘kqueue()’ system calls.  ‘modify()’ method
     was added to the existing ‘poll’ objects; ‘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(32).)

   * The *note shutil.copytree(): 347. function now has an optional
     `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 *note shutil: e9. module also provides an ‘ignore_patterns()’
     function for use with this new parameter.  ‘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 ‘.svn’ directories and Emacs backup files, which
     have names ending with ’~’:

          shutil.copytree('Doc/library', '/tmp/library',
                          ignore=shutil.ignore_patterns('*~', '.svn'))

     （由 Tarek Ziadé 在 bpo-2663(33) 中贡献。）

   * 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 *note signal: ea.
     module can now make this more efficient.  Calling
     ‘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, *note PySignal_SetWakeupFd(): e0b,
     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 ‘set_wakeup_fd()’, and the readable
     descriptor will be added to the list of descriptors monitored by
     the event loop via ‘select()’ or ‘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(34) 中贡献。）

     The ‘siginterrupt()’ function is now available from Python code,
     and allows changing whether signals can interrupt system calls or
     not.  (Contributed by Ralf Schmitt.)

     The ‘setitimer()’ and ‘getitimer()’ functions have also been added
     (where they’re available).  ‘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(35).)

   * The *note smtplib: ed. module now supports SMTP over SSL thanks to
     the addition of the ‘SMTP_SSL’ class.  This class supports an
     interface identical to the existing ‘SMTP’ class.  (Contributed by
     Monty Taylor.)  Both class constructors also have an optional
     ‘timeout’ parameter that specifies a timeout for the initial
     connection attempt, measured in seconds.  (Contributed by Facundo
     Batista.)

     An implementation of the LMTP protocol ( RFC 2033(36)) 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(37).)

     ‘SMTP.starttls()’ now complies with RFC 3207(38) and forgets any
     knowledge obtained from the server not obtained from the TLS
     negotiation itself.  (Patch contributed by Bill Fenner;
     bpo-829951(39).)

   * The *note socket: ef. module now supports TIPC
     (‘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(40).)

     A new function, ‘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 ‘create_connection()’ instead of
     ‘socket(socket.AF_INET, ...)’ may be all that’s required to make
     your code work with IPv6.

   * The base classes in the ‘SocketServer’ module now support calling a
     ‘handle_timeout()’ method after a span of inactivity specified by
     the server’s ‘timeout’ attribute.  (Contributed by Michael
     Pomraning.)  The ‘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(41), bpo-1193577(42).)

   * The *note sqlite3: f2. module, maintained by Gerhard Häring, has
     been updated from version 2.3.2 in Python 2.5 to version 2.4.1.

   * The *note struct: f8. module now supports the C99 ‘_Bool’ type,
     using the format character ‘'?'’.  (Contributed by David Remahl.)

   * The ‘Popen’ objects provided by the *note subprocess: f9. module
     now have ‘terminate()’, ‘kill()’, and ‘send_signal()’ methods.  On
     Windows, ‘send_signal()’ only supports the ‘SIGTERM’ signal, and
     all these methods are aliases for the Win32 API function
     ‘TerminateProcess()’.  (Contributed by Christian Heimes.)

   * A new variable in the *note sys: fd. module, ‘float_info’, is an
     object containing information derived from the ‘float.h’ file about
     the platform’s floating-point support.  Attributes of this object
     include ‘mant_dig’ (number of digits in the mantissa), ‘epsilon’
     (smallest difference between 1.0 and the next largest value
     representable), and several others.  (Contributed by Christian
     Heimes; bpo-1534(43).)

     Another new variable, ‘dont_write_bytecode’, controls whether
     Python writes any ‘.pyc’ or ‘.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 *note -B:
     dfe. switch to the Python interpreter, or by setting the *note
     PYTHONDONTWRITEBYTECODE: dff. 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 ‘sys.flags’.  For example, the ‘verbose’ attribute is
     true if Python was executed in verbose mode, ‘debug’ is true in
     debugging mode, etc.  These attributes are all read-only.
     (Contributed by Christian Heimes.)

     A new function, ‘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 ‘__sizeof__()’ method to return the object’s
     size.  (Contributed by Robert Schuppenies; bpo-2898(44).)

     It’s now possible to determine the current profiler and tracer
     functions by calling *note sys.getprofile(): e0c. and *note
     sys.gettrace(): e0d.  (Contributed by Georg Brandl; bpo-1648(45).)

   * The *note tarfile: 101. 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 ‘format’ parameter to open a file using a
     different format:

          tar = tarfile.open("output.tar", "w",
                             format=tarfile.PAX_FORMAT)

     The new ‘encoding’ and ‘errors’ parameters specify an encoding and
     an error handling scheme for character conversions.  ‘'strict'’,
     ‘'ignore'’, and ‘'replace'’ are the three standard ways Python can
     handle errors,; ‘'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 ‘TarFile.add()’ method now accepts an ‘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 ‘add()’
     and to the names of files in recursively-added directories.

     (All changes contributed by Lars Gustäbel).

   * An optional ‘timeout’ parameter was added to the *note
     telnetlib.Telnet: 68e. class constructor, specifying a timeout
     measured in seconds.  (Added by Facundo Batista.)

   * The *note tempfile.NamedTemporaryFile: e0e. class usually deletes
     the temporary file it created when the file is closed.  This
     behaviour can now be changed by passing ‘delete=False’ to the
     constructor.  (Contributed by Damien Miller; bpo-1537850(46).)

     A new class, ‘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 ‘NamedTemporaryFile’ and ‘SpooledTemporaryFile’ classes both
     work as context managers, so you can write ‘with
     tempfile.NamedTemporaryFile() as tmp: ...’.  (Contributed by
     Alexander Belopolsky; bpo-2021(47).)

   * The ‘test.test_support’ module gained a number of context managers
     useful for writing tests.  ‘EnvironmentVarGuard()’ is a context
     manager that temporarily changes environment variables and
     automatically restores them to their old values.

     Another context manager, ‘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:

          with test_support.TransientResource(IOError,
                                          errno=errno.ETIMEDOUT):
              f = urllib.urlopen('https://sf.net')
              ...

     Finally, ‘check_warnings()’ resets the ‘warning’ module’s warning
     filters and returns an object that will record all warning messages
     triggered (bpo-3781(48)):

          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"

     （由 Brett Cannon 贡献。）

   * The *note textwrap: 10a. module can now preserve existing
     whitespace at the beginnings and ends of the newly-created lines by
     specifying ‘drop_whitespace=False’ as an argument:

          >>> 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.
          >>>

     （由 Dwayne Bailey 在 bpo-1581073(49) 中贡献。）

   * The *note threading: 10b. module API is being changed to use
     properties such as ‘daemon’ instead of ‘setDaemon()’ and
     ‘isDaemon()’ methods, and some methods have been renamed to use
     underscores instead of camel-case; for example, the ‘activeCount()’
     method is renamed to ‘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 *note threading: 10b. module’s ‘Thread’ objects gained an
     ‘ident’ property that returns the thread’s identifier, a nonzero
     integer.  (Contributed by Gregory P. Smith; bpo-2871(50).)

   * The *note timeit: 10d. 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 ‘Timer’ instances:
     ‘repeat(stmt, setup, time, repeat, number)’ and ‘timeit(stmt,
     setup, time, number)’ create an instance and call the corresponding
     method.  (Contributed by Erik Demaine; bpo-1533909(51).)

   * The ‘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(52).)

   * The *note turtle: 11f. module for turtle graphics was greatly
     enhanced by Gregor Lingl.  New features in the module include:

        * Better animation of turtle movement and rotation.

        * Control over turtle movement using the new ‘delay()’,
          ‘tracer()’, and ‘speed()’ methods.

        * The ability to set new shapes for the turtle, and to define a
          new coordinate system.

        * Turtles now have an ‘undo()’ method that can roll back
          actions.

        * Simple support for reacting to input events such as mouse and
          keyboard activity, making it possible to write simple games.

        * A ‘turtle.cfg’ file can be used to customize the starting
          appearance of the turtle’s screen.

        * The module’s docstrings can be replaced by new docstrings that
          have been translated into another language.

     (bpo-1513695(53))

   * An optional ‘timeout’ parameter was added to the ‘urllib.urlopen()’
     function and the ‘urllib.ftpwrapper’ class constructor, as well as
     the ‘urllib2.urlopen()’ function.  The parameter specifies a
     timeout measured in seconds.  For example:

          >>> u = urllib2.urlopen("http://slow.example.com",
                                  timeout=3)
          Traceback (most recent call last):
            ...
          urllib2.URLError: <urlopen error timed out>
          >>>

     (Added by Facundo Batista.)

   * The Unicode database provided by the *note unicodedata: 123. module
     has been updated to version 5.1.0.  (Updated by Martin von Löwis;
     bpo-3811(54).)

   * The *note warnings: 12f. module’s ‘formatwarning()’ and
     ‘showwarning()’ gained an optional `line' argument that can be used
     to supply the line of source code.  (Added as part of
     bpo-1631171(55), which re-implemented part of the *note warnings:
     12f. module in C code.)

     A new function, ‘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(56)).

   * The XML-RPC ‘SimpleXMLRPCServer’ and ‘DocXMLRPCServer’ classes can
     now be prevented from immediately opening and binding to their
     socket by passing ‘False’ as the `bind_and_activate' constructor
     parameter.  This can be used to modify the instance’s
     ‘allow_reuse_address’ attribute before calling the ‘server_bind()’
     and ‘server_activate()’ methods to open the socket and begin
     listening for connections.  (Contributed by Peter Parente;
     bpo-1599845(57).)

     ‘SimpleXMLRPCServer’ also has a ‘_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.)

   * The ‘xmlrpclib’ module no longer automatically converts *note
     datetime.date: 19d. and *note datetime.time: 5ec. to the
     ‘xmlrpclib.DateTime’ type; the conversion semantics were not
     necessarily correct for all applications.  Code using ‘xmlrpclib’
     should convert ‘date’ and *note time: 5ec. instances.
     (bpo-1330538(58)) The code can also handle dates before 1900
     (contributed by Ralf Schmitt; bpo-2014(59)) and 64-bit integers
     represented by using ‘<i8>’ in XML-RPC responses (contributed by
     Riku Lindblad; bpo-2985(60)).

   * The *note zipfile: 14b. module’s ‘ZipFile’ class now has
     ‘extract()’ and ‘extractall()’ methods that will unpack a single
     file or all the files in the archive to the current directory, or
     to a specified directory:

          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()

     （由 Alan McIntyre 在 bpo-467924(61) 中贡献。）

     The *note open(): 16f, ‘read()’ and ‘extract()’ methods can now
     take either a filename or a ‘ZipInfo’ object.  This is useful when
     an archive accidentally contains a duplicated filename.
     (Contributed by Graham Horler; bpo-1775025(62).)

     Finally, *note zipfile: 14b. now supports using Unicode filenames
     for archived files.  (Contributed by Alexey Borzenkov;
     bpo-1734346(63).)

* Menu:

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

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1736190

   (2) https://www.jcea.es/programacion/pybsddb.htm

   (3) https://bugs.python.org/issue1817

   (4) https://bugs.python.org/issue600362

   (5) https://bugs.python.org/issue1381

   (6) https://bugs.python.org/issue1638033

   (7) https://bugs.python.org/issue1158

   (8) http://speleotrove.com/decimal/decarith.html

   (9) https://bugs.python.org/issue1221598

   (10) https://bugs.python.org/issue1739906

   (11) https://bugs.python.org/issue1001604

   (12) https://bugs.python.org/issue2138

   (13) https://bugs.python.org/issue2819

   (14) https://bugs.python.org/issue711019

   (15) https://bugs.python.org/issue1640

   (16) https://bugs.python.org/issue1663329

   (17) https://bugs.python.org/issue1181

   (18) https://bugs.python.org/issue1273829

   (19) https://bugs.python.org/issue1115886

   (20) https://bugs.python.org/issue1339796

   (21) https://bugs.python.org/issue957650

   (22) https://bugs.python.org/issue1393667

   (23) https://bugs.python.org/issue1106316

   (24) https://bugs.python.org/issue2439

   (25) https://bugs.python.org/issue1137

   (26) https://bugs.python.org/issue1727780

   (27) https://bugs.python.org/issue1681432

   (28) https://bugs.python.org/issue846388

   (29) https://bugs.python.org/issue3487

   (30) https://bugs.python.org/issue2250

   (31) https://bugs.python.org/issue1861

   (32) https://bugs.python.org/issue1657

   (33) https://bugs.python.org/issue2663

   (34) https://bugs.python.org/issue1583

   (35) https://bugs.python.org/issue2240

   (36) https://tools.ietf.org/html/rfc2033.html

   (37) https://bugs.python.org/issue957003

   (38) https://tools.ietf.org/html/rfc3207.html

   (39) https://bugs.python.org/issue829951

   (40) https://bugs.python.org/issue1646

   (41) https://bugs.python.org/issue742598

   (42) https://bugs.python.org/issue1193577

   (43) https://bugs.python.org/issue1534

   (44) https://bugs.python.org/issue2898

   (45) https://bugs.python.org/issue1648

   (46) https://bugs.python.org/issue1537850

   (47) https://bugs.python.org/issue2021

   (48) https://bugs.python.org/issue3781

   (49) https://bugs.python.org/issue1581073

   (50) https://bugs.python.org/issue2871

   (51) https://bugs.python.org/issue1533909

   (52) https://bugs.python.org/issue2906

   (53) https://bugs.python.org/issue1513695

   (54) https://bugs.python.org/issue3811

   (55) https://bugs.python.org/issue1631171

   (56) https://bugs.python.org/issue3781

   (57) https://bugs.python.org/issue1599845

   (58) https://bugs.python.org/issue1330538

   (59) https://bugs.python.org/issue2014

   (60) https://bugs.python.org/issue2985

   (61) https://bugs.python.org/issue467924

   (62) https://bugs.python.org/issue1775025

   (63) https://bugs.python.org/issue1734346


File: python.info,  Node: ast 模块,  Next: future_builtins 模块,  Up: 新增和改进的模块<2>

1.12.18.1 ‘ast’ 模块
....................

The *note ast: 7. 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 ‘parse()’ function takes an expression and returns an AST. The
‘dump()’ function outputs a representation of a tree, suitable for
debugging:

     import ast

     t = ast.parse("""
     d = {}
     for i in 'abcdefghijklm':
         d[i + i] = ord(i) - ord('a') + 1
     print d
     """)
     print ast.dump(t)

This outputs a deeply nested tree:

     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)
      ])

The ‘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 *note eval(): c61. call, ‘literal_eval()’ will
handle it safely:

     >>> 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

The module also includes ‘NodeVisitor’ and ‘NodeTransformer’ classes for
traversing and modifying an AST, and functions for common
transformations such as changing line numbers.


File: python.info,  Node: future_builtins 模块,  Next: The json module JavaScript Object Notation,  Prev: ast 模块,  Up: 新增和改进的模块<2>

1.12.18.2 ‘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 ‘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:

   * ‘ascii(obj)’: equivalent to *note repr(): 8b9.  In Python 3.0,
     *note repr(): 8b9. will return a Unicode string, while *note
     ascii(): e11. will return a pure ASCII bytestring.

   * ‘filter(predicate, iterable)’, ‘map(func, iterable1, ...)’: the 3.0
     versions return iterators, unlike the 2.x builtins which return
     lists.

   * ‘hex(value)’, ‘oct(value)’: instead of calling the ‘__hex__()’ or
     ‘__oct__()’ methods, these versions will call the *note
     __index__(): 2c2. method and convert the result to hexadecimal or
     octal.  *note oct(): d2d. will use the new ‘0o’ notation for its
     result.


File: python.info,  Node: The json module JavaScript Object Notation,  Next: plistlib 模块：属性列表解析器,  Prev: future_builtins 模块,  Up: 新增和改进的模块<2>

1.12.18.3 The ‘json’ module: JavaScript Object Notation
.......................................................

The new *note json: a4. 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 ‘http://www.json.org’.

*note json: a4. comes with support for decoding and encoding most
built-in Python types.  The following example encodes and decodes a
dictionary:

     >>> 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}

It’s also possible to write your own decoders and encoders to support
more types.  Pretty-printing of the JSON strings is also supported.

*note json: a4. (originally called simplejson) was written by Bob
Ippolito.


File: python.info,  Node: plistlib 模块：属性列表解析器,  Next: ctypes Enhancements,  Prev: The json module JavaScript Object Notation,  Up: 新增和改进的模块<2>

1.12.18.4 ‘plistlib’ 模块：属性列表解析器
.........................................

The ‘.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 *note plistlib: cf. module has
been promoted to the standard library.

Using the module is simple:

     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)


File: python.info,  Node: ctypes Enhancements,  Next: Improved SSL Support,  Prev: plistlib 模块：属性列表解析器,  Up: 新增和改进的模块<2>

1.12.18.5 ctypes Enhancements
.............................

Thomas Heller continued to maintain and enhance the *note ctypes: 2a.
module.

*note ctypes: 2a. now supports a ‘c_bool’ datatype that represents the
C99 ‘bool’ type.  (Contributed by David Remahl; bpo-1649190(1).)

The *note ctypes: 2a. string, buffer and array types have improved
support for extended slicing syntax, where various combinations of
‘(start, stop, step)’ are supplied.  (Implemented by Thomas Wouters.)

All *note ctypes: 2a. data types now support ‘from_buffer()’ and
‘from_buffer_copy()’ methods that create a ctypes instance based on a
provided buffer object.  ‘from_buffer_copy()’ copies the contents of the
object, while ‘from_buffer()’ will share the same memory area.

A new calling convention tells *note ctypes: 2a. to clear the ‘errno’ or
Win32 LastError variables at the outset of each wrapped call.
(Implemented by Thomas Heller; bpo-1798(2).)

You can now retrieve the Unix ‘errno’ variable after a function call.
When creating a wrapped function, you can supply ‘use_errno=True’ as a
keyword parameter to the ‘DLL()’ function and then call the module-level
methods ‘set_errno()’ and ‘get_errno()’ to set and retrieve the error
value.

The Win32 LastError variable is similarly supported by the ‘DLL()’,
‘OleDLL()’, and ‘WinDLL()’ functions.  You supply ‘use_last_error=True’
as a keyword parameter and then call the module-level methods
‘set_last_error()’ and ‘get_last_error()’.

The ‘byref()’ function, used to retrieve a pointer to a ctypes instance,
now has an optional `offset' parameter that is a byte count that will be
added to the returned pointer.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1649190

   (2) https://bugs.python.org/issue1798


File: python.info,  Node: Improved SSL Support,  Prev: ctypes Enhancements,  Up: 新增和改进的模块<2>

1.12.18.6 Improved SSL Support
..............................

Bill Janssen made extensive improvements to Python 2.6’s support for the
Secure Sockets Layer by adding a new module, *note ssl: f3, that’s built
atop the OpenSSL(1) 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 *note socket: ef. 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 *note ssl.wrap_socket(): 570.
function.  It’s possible to specify whether a certificate is required,
and to obtain certificate info by calling the ‘getpeercert()’ method.

也參考
......

*note ssl: f3. 模块的文档。

   ---------- Footnotes ----------

   (1) https://www.openssl.org/


File: python.info,  Node: Deprecations and Removals,  Next: 构建和 C API 的改变<9>,  Prev: 新增和改进的模块<2>,  Up: Python 2 6 有什么新变化

1.12.19 Deprecations and Removals
---------------------------------

   * String exceptions have been removed.  Attempting to use them raises
     a *note TypeError: 1fe.

   * Changes to the *note Exception: 2dc. interface as dictated by PEP
     352(1) continue to be made.  For 2.6, the ‘message’ attribute is
     being deprecated in favor of the ‘args’ attribute.

   * (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: ‘audiodev’, ‘bgenlocations’,
     ‘buildtools’, ‘bundlebuilder’, ‘Canvas’, ‘compiler’, ‘dircache’,
     ‘dl’, ‘fpformat’, ‘gensuitemodule’, ‘ihooks’, ‘imageop’, ‘imgfile’,
     ‘linuxaudiodev’, ‘mhlib’, ‘mimetools’, ‘multifile’, ‘new’, ‘pure’,
     ‘statvfs’, ‘sunaudiodev’, ‘test.testall’, and ‘toaiff’.

   * ‘gopherlib’ 模块已被移除。

   * The ‘MimeWriter’ module and ‘mimify’ module have been deprecated;
     use the *note email: 67. package instead.

   * The ‘md5’ module has been deprecated; use the *note hashlib: 8c.
     module instead.

   * The ‘posixfile’ module has been deprecated; *note fcntl.lockf():
     e17. provides better locking.

   * The ‘popen2’ module has been deprecated; use the *note subprocess:
     f9. module.

   * ‘rgbimg’ 模块已被移除。

   * The ‘sets’ module has been deprecated; it’s better to use the
     built-in *note set: 1f6. and *note frozenset: 1f7. types.

   * The ‘sha’ module has been deprecated; use the *note hashlib: 8c.
     module instead.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0352


File: python.info,  Node: 构建和 C API 的改变<9>,  Next: 移植到Python 2 6,  Prev: Deprecations and Removals,  Up: Python 2 6 有什么新变化

1.12.20 构建和 C API 的改变
---------------------------

Changes to Python’s build process and to the C API include:

   * Python now must be compiled with C89 compilers (after 19 years!).
     This means that the Python source tree has dropped its own
     implementations of ‘memmove()’ and ‘strerror()’, which are in the
     C89 standard library.

   * Python 2.6 can be built with Microsoft Visual Studio 2008 (version
     9.0), and this is the new default compiler.  See the ‘PCbuild’
     directory for the build files.  (Implemented by Christian Heimes.)

   * On Mac OS X, Python 2.6 can be compiled as a 4-way universal build.
     The ‘configure’ script can take a
     ‘--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.)

   * The BerkeleyDB module now has a C API object, available as
     ‘bsddb.db.api’.  This object can be used by other C extensions that
     wish to use the ‘bsddb’ module for their own purposes.
     (Contributed by Duncan Grisby.)

   * The new buffer interface, previously described in *note the PEP
     3118 section: dea, adds *note PyObject_GetBuffer(): deb. and *note
     PyBuffer_Release(): e19, as well as a few other functions.

   * 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
     ‘PyFile_IncUseCount()’ and ‘PyFile_DecUseCount()’ functions.  File
     objects can’t be closed unless the reference count is zero.
     ‘PyFile_IncUseCount()’ should be called while the GIL is still
     held, before carrying out an I/O operation using the ‘FILE *’
     pointer, and ‘PyFile_DecUseCount()’ should be called immediately
     after the GIL is re-acquired.  (Contributed by Antoine Pitrou and
     Gregory P. Smith.)

   * Importing modules simultaneously in two different threads no longer
     deadlocks; it will now raise an *note ImportError: 16c.  A new API
     function, *note PyImport_ImportModuleNoBlock(): aa0, will look for
     a module in ‘sys.modules’ first, then try to import it after
     acquiring an import lock.  If the import lock is held by another
     thread, an *note ImportError: 16c. is raised.  (Contributed by
     Christian Heimes.)

   * Several functions return information about the platform’s
     floating-point support.  *note PyFloat_GetMax(): e1a. returns the
     maximum representable floating point value, and *note
     PyFloat_GetMin(): e1b. returns the minimum positive value.  *note
     PyFloat_GetInfo(): e1c. returns an object containing more
     information from the ‘float.h’ file, such as ‘"mant_dig"’ (number
     of digits in the mantissa), ‘"epsilon"’ (smallest difference
     between 1.0 and the next largest value representable), and several
     others.  (Contributed by Christian Heimes; bpo-1534(1).)

   * C functions and methods that use *note PyComplex_AsCComplex(): e1d.
     will now accept arguments that have a *note __complex__(): 2c5.
     method.  In particular, the functions in the *note cmath: 18.
     module will now accept objects with this method.  This is a
     backport of a Python 3.0 change.  (Contributed by Mark Dickinson;
     bpo-1675423(2).)

   * Python’s C API now includes two functions for case-insensitive
     string comparisons, ‘PyOS_stricmp(char*, char*)’ and
     ‘PyOS_strnicmp(char*, char*, Py_ssize_t)’.  (Contributed by
     Christian Heimes; bpo-1635(3).)

   * Many C extensions define their own little macro for adding integers
     and strings to the module’s dictionary in the ‘init*’ function.
     Python 2.6 finally defines standard macros for adding values to a
     module, *note PyModule_AddStringMacro: e1e. and
     ‘PyModule_AddIntMacro()’.  (Contributed by Christian Heimes.)

   * Some macros were renamed in both 3.0 and 2.6 to make it clearer
     that they are macros, not functions.  ‘Py_Size()’ became
     ‘Py_SIZE()’, ‘Py_Type()’ became ‘Py_TYPE()’, and ‘Py_Refcnt()’
     became ‘Py_REFCNT()’.  The mixed-case macros are still available in
     Python 2.6 for backward compatibility.  (bpo-1629(4))

   * 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(5).)

   * 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 ‘free_list’, the counter is always named
     ‘numfree’, and a macro ‘Py<typename>_MAXFREELIST’ is always
     defined.

   * A new Makefile target, "make patchcheck", prepares the Python
     source tree for making a patch: it fixes trailing whitespace in all
     modified ‘.py’ files, checks whether the documentation has been
     changed, and reports whether the ‘Misc/ACKS’ and ‘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.)

* Menu:

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

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1534

   (2) https://bugs.python.org/issue1675423

   (3) https://bugs.python.org/issue1635

   (4) https://bugs.python.org/issue1629

   (5) https://bugs.python.org/issue1530959


File: python.info,  Node: 特定于 Windows 的更改：<2>,  Next: 特定于 Mac OS X 的更改：Mac OS X,  Up: 构建和 C API 的改变<9>

1.12.20.1 特定于 Windows 的更改：
.................................

   * The support for Windows 95, 98, ME and NT4 has been dropped.
     Python 2.6 requires at least Windows 2000 SP4.

   * 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
     ‘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.)

   * The *note msvcrt: b6. module now supports both the normal and wide
     char variants of the console I/O API. The ‘getwch()’ function reads
     a keypress and returns a Unicode value, as does the ‘getwche()’
     function.  The ‘putwch()’ function takes a Unicode character and
     writes it to the console.  (Contributed by Christian Heimes.)

   * *note os.path.expandvars(): e09. 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(1).)

   * The *note socket: ef. module’s socket objects now have an ‘ioctl()’
     method that provides a limited interface to the ‘WSAIoctl()’ system
     interface.

   * The ‘_winreg’ module now has a function,
     ‘ExpandEnvironmentStrings()’, that expands environment variable
     references such as ‘%NAME%’ in an input string.  The handle objects
     provided by this module now support the context protocol, so they
     can be used in *note with: 7da. statements.  (Contributed by
     Christian Heimes.)

     ‘_winreg’ also has better support for x64 systems, exposing the
     ‘DisableReflectionKey()’, ‘EnableReflectionKey()’, and
     ‘QueryReflectionKey()’ functions, which enable and disable registry
     reflection for 32-bit processes running on 64-bit systems.
     (bpo-1753245(2))

   * The *note msilib: b5. module’s ‘Record’ object gained
     ‘GetInteger()’ and ‘GetString()’ methods that return field values
     as an integer or a string.  (Contributed by Floris Bruynooghe;
     bpo-2125(3).)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue957650

   (2) https://bugs.python.org/issue1753245

   (3) https://bugs.python.org/issue2125


File: python.info,  Node: 特定于 Mac OS X 的更改：Mac OS X,  Next: 特定于 IRIX 的更改：,  Prev: 特定于 Windows 的更改：<2>,  Up: 构建和 C API 的改变<9>

1.12.20.2 特定于 Mac OS X 的更改：Mac OS X
..........................................

   * 现在，在编译Python的框架版本时，可以为 ‘configure’ 脚本添加
     ‘--with-framework-name=’ 选项来指定要使用的框架名称。

   * ‘macfs’ 模块已被删除。这反过来要求删除 ‘macostools.touched()’ 函数
     ，因为它依赖于 ‘macfs’ 模块。 (bpo-1490190(1))

   * 许多其他 Mac OS 模块已弃用并将在 Python 3.0 中被删除:
     ‘_builtinSuites’, ‘aepack’, ‘aetools’, ‘aetypes’, ‘applesingle’,
     ‘appletrawmain’, ‘appletrunner’, ‘argvemulator’, ‘Audio_mac’,
     ‘autoGIL’, ‘Carbon’, ‘cfmfile’, ‘CodeWarrior’, ‘ColorPicker’,
     ‘EasyDialogs’, ‘Explorer’, ‘Finder’, ‘FrameWork’, ‘findertools’,
     ‘ic’, ‘icglue’, ‘icopen’, ‘macerrors’, ‘MacOS’, ‘macfs’,
     ‘macostools’, ‘macresource’, ‘MiniAEFrame’, ‘Nav’, ‘Netscape’,
     ‘OSATerminology’, ‘pimp’, ‘PixMapWrapper’, ‘StdSuites’,
     ‘SystemEvents’, ‘Terminal’ 和 ‘terminalcommand’。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1490190


File: python.info,  Node: 特定于 IRIX 的更改：,  Prev: 特定于 Mac OS X 的更改：Mac OS X,  Up: 构建和 C API 的改变<9>

1.12.20.3 特定于 IRIX 的更改：
..............................

许多旧的 IRIX 专用模块已被弃用，并将在Python 3.0中删除： ‘al’ 和 ‘AL’,
‘cd’, ‘cddb’, ‘cdplayer’, ‘CL’ 和 ‘cl’, ‘DEVICE’, ‘ERRNO’, ‘FILE’, ‘FL’
和 ‘fl’, ‘flp’, ‘fm’, ‘GET’, ‘GLWS’, ‘GL’ 和 ‘gl’, ‘IN’, ‘IOCTL’,
‘jpeg’, ‘panelparser’, ‘readcd’, ‘SV’ 和 ‘sv’, ‘torgb’, ‘videoreader’, 和
‘WAIT’.


File: python.info,  Node: 移植到Python 2 6,  Next: 致谢<2>,  Prev: 构建和 C API 的改变<9>,  Up: Python 2 6 有什么新变化

1.12.21 移植到Python 2.6
------------------------

This section lists previously described changes and other bugfixes that
may require changes to your code:

   * Classes that aren’t supposed to be hashable should set ‘__hash__ =
     None’ in their definitions to indicate the fact.

   * String exceptions have been removed.  Attempting to use them raises
     a *note TypeError: 1fe.

   * The *note __init__(): e23. method of *note collections.deque: 62a.
     now clears any existing contents of the deque before adding
     elements from the iterable.  This change makes the behavior match
     ‘list.__init__()’.

   * *note object.__init__(): e23. previously accepted arbitrary
     arguments and keyword arguments, ignoring them.  In Python 2.6,
     this is no longer allowed and will result in a *note TypeError:
     1fe.  This will affect *note __init__(): e23. methods that end up
     calling the corresponding method on *note object: 3d2. (perhaps
     through using *note super(): 5dd.).  See bpo-1683368(1) for
     discussion.

   * The ‘Decimal’ constructor now accepts leading and trailing
     whitespace when passed a string.  Previously it would raise an
     ‘InvalidOperation’ exception.  On the other hand, the
     ‘create_decimal()’ method of ‘Context’ objects now explicitly
     disallows extra whitespace, raising a ‘ConversionSyntax’ exception.

   * Due to an implementation accident, if you passed a file path to the
     built-in *note __import__(): 16b. 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 *note ImportError: 16c.

   * C API: the *note PyImport_Import(): e24. and *note
     PyImport_ImportModule(): d3b. functions now default to absolute
     imports, not relative imports.  This will affect C extensions that
     import other modules.

   * C API: extension data types that shouldn’t be hashable should
     define their ‘tp_hash’ slot to *note PyObject_HashNotImplemented():
     df7.

   * The *note socket: ef. module exception *note socket.error: a76. now
     inherits from *note IOError: a73.  Previously it wasn’t a subclass
     of ‘StandardError’ but now it is, through *note IOError: a73.
     (Implemented by Gregory P. Smith; bpo-1706815(2).)

   * The ‘xmlrpclib’ module no longer automatically converts *note
     datetime.date: 19d. and *note datetime.time: 5ec. to the
     ‘xmlrpclib.DateTime’ type; the conversion semantics were not
     necessarily correct for all applications.  Code using ‘xmlrpclib’
     should convert ‘date’ and *note time: 5ec. instances.
     (bpo-1330538(3))

   * (3.0-warning mode) The *note Exception: 2dc. class now warns when
     accessed using slicing or index access; having *note Exception:
     2dc. behave like a tuple is being phased out.

   * (3.0-warning mode) inequality comparisons between two dictionaries
     or two objects that don’t implement comparison methods are reported
     as warnings.  ‘dict1 == dict2’ still works, but ‘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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1683368

   (2) https://bugs.python.org/issue1706815

   (3) https://bugs.python.org/issue1330538


File: python.info,  Node: 致谢<2>,  Prev: 移植到Python 2 6,  Up: Python 2 6 有什么新变化

1.12.22 致谢
------------

作者感谢以下人员对本文各种草稿给予的建议，更正和协助： Georg Brandl,
Steve Brown, Nick Coghlan, Ralph Corderoy, Jim Jewett, Kent Johnson,
Chris Lambacher, Martin Michlmayr, Antoine Pitrou, Brian Warner.


File: python.info,  Node: Python 2 5 有什么新变化,  Next: Python 2 4 有什么新变化,  Prev: Python 2 6 有什么新变化,  Up: Python 有什麼新功能？

1.13 Python 2.5 有什么新变化
============================


作者: A.M. Kuchling

This article explains the new features in Python 2.5.  The final release
of Python 2.5 is scheduled for August 2006; PEP 356(1) 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
(‘xml.etree’), the SQLite database module (‘sqlite’), and the *note
ctypes: 2a. 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 *note PEP 308; 条件表达式: e29.  The
new ’*note with: 7da.’ statement will make writing cleanup code easier
(section *note PEP 343; "with" 语句: e2a.).  Values can now be passed
into generators (section *note PEP 342; 生成器的新特性: e2b.).  Imports
are now visible as either absolute or relative (section *note PEP 328;
绝对导入和相对导入: e2c.).  Some corner cases of exception handling are
handled better (section *note PEP 341; 统一 try/except/finally: e2d.).
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 ‘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.

* 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>.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0356


File: python.info,  Node: PEP 308 条件表达式,  Next: PEP 309 部分功能应用,  Up: Python 2 5 有什么新变化

1.13.1 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:

     if condition:
         x = true_value
     else:
         x = false_value

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
‘cond ? true_v : false_v’, ‘if cond then true_v else false_v’, and 16
other variations.

Guido van Rossum 最终选择了一种令人惊讶的语法：

     x = true_value if condition else false_value

Evaluation is still lazy as in existing Boolean expressions, so the
order of evaluation jumps around a bit.  The `condition' expression in
the middle is evaluated first, and the `true_value' expression is
evaluated only if the condition was true.  Similarly, the `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 `middle' of the expression, and not in the front as in C’s ‘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:

     contents = ((doc + '\n') if doc else '')

I read the above statement as meaning "here `contents' is usually
assigned a value of ‘doc+'\n'’; sometimes `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 `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:

     # First version -- no parens
     level = 1 if logging else 0

     # Second version -- with parens
     level = (1 if logging else 0)

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 `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 PEP 308(1) for some examples.  If you put parentheses
around your conditional expressions, you won’t run into this case.

也參考
......

PEP 308(2) - 条件表达式

     PEP 由 Guido van Rossum 和 Raymond D 撰写，由 Thomas Wouters 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0308

   (2) https://www.python.org/dev/peps/pep-0308


File: python.info,  Node: PEP 309 部分功能应用,  Next: PEP 314 Python软件包的元数据 v1 1,  Prev: PEP 308 条件表达式,  Up: Python 2 5 有什么新变化

1.13.2 PEP 309: 部分功能应用
----------------------------

The *note functools: 83. module is intended to contain tools for
functional-style programming.

One useful tool in this module is the ‘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 ‘f(a, b, c)’; you
could create a new function ‘g(b, c)’ that was equivalent to ‘f(1, b,
c)’.  This is called "partial function application".

‘partial()’ takes the arguments ‘(function, arg1, arg2, ...
kwarg1=value1, kwarg2=value2)’.  The resulting object is callable, so
you can just call it to invoke `function' with the filled-in arguments.

这里有一个很小但很现实的例子:

     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')

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 ‘open_item()’ method, where the first argument has been provided.

     ...
     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) )

Another function in the *note functools: 83. module is the
‘update_wrapper(wrapper, wrapped)’ function that helps you write
well-behaved decorators.  ‘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:

     def my_decorator(f):
         def wrapper(*args, **kwds):
             print 'Calling decorated function'
             return f(*args, **kwds)
         functools.update_wrapper(wrapper, f)
         return wrapper

‘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:

     def my_decorator(f):
         @functools.wraps(f)
         def wrapper(*args, **kwds):
             print 'Calling decorated function'
             return f(*args, **kwds)
         return wrapper

也參考
......

PEP 309(1) - Partial Function Application

     PEP由 Peter Harris 提出并撰写；由 Hye-Shik Chang 和 Nick Coghlan 实
     现，并由 Raymond Hettinger 适配。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0309


File: python.info,  Node: PEP 314 Python软件包的元数据 v1 1,  Next: PEP 328 绝对导入和相对导入,  Prev: PEP 309 部分功能应用,  Up: Python 2 5 有什么新变化

1.13.3 PEP 314: Python软件包的元数据 v1.1
-----------------------------------------

Some simple dependency support was added to Distutils.  The ‘setup()’
function now has ‘requires’, ‘provides’, and ‘obsoletes’ keyword
parameters.  When you build a source distribution using the ‘sdist’
command, the dependency information will be recorded in the ‘PKG-INFO’
file.

Another new keyword parameter is ‘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.

     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),
          )

Another new enhancement to the Python package index at
‘https://pypi.org’ is storing source and binary archives for a package.
The new ‘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 ‘sdist’ Distutils command.  Once that works, you
can run ‘python setup.py upload’ to add your package to the PyPI
archive.  Optionally you can GPG-sign the package by supplying the
‘--sign’ and ‘--identity’ options.

Package uploading was implemented by Martin von Löwis and Richard Jones.

也參考
......

PEP 314(1) - Python软件包的元数据 v1.1

     PEP 由 A.M. Kuchling, Richard Jones 和 Fred Drake 提出并撰写，由
     Richard Jones 和 Fred Drake 实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0314


File: python.info,  Node: PEP 328 绝对导入和相对导入,  Next: PEP 338 将模块作为脚本执行,  Prev: PEP 314 Python软件包的元数据 v1 1,  Up: Python 2 5 有什么新变化

1.13.4 PEP 328: 绝对导入和相对导入
----------------------------------

The simpler part of PEP 328(1) was implemented in Python 2.4:
parentheses could now be used to enclose the names imported from a
module using the ‘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:

     pkg/
     pkg/__init__.py
     pkg/main.py
     pkg/string.py

This defines a package named ‘pkg’ containing the ‘pkg.main’ and
‘pkg.string’ submodules.

Consider the code in the ‘main.py’ module.  What happens if it executes
the statement ‘import string’?  In Python 2.4 and earlier, it will first
look in the package’s directory to perform a relative import, finds
‘pkg/string.py’, imports the contents of that file as the ‘pkg.string’
module, and that module is bound to the name ‘string’ in the ‘pkg.main’
module’s namespace.

That’s fine if ‘pkg.string’ was what you wanted.  But what if you wanted
Python’s standard *note string: f6. module?  There’s no clean way to
ignore ‘pkg.string’ and look for the standard module; generally you had
to look at the contents of ‘sys.modules’, which is slightly unclean.
Holger Krekel’s ‘py.std’ package provides a tidier way to perform
imports from the standard library, ‘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, *note string: f6.
or ‘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 *note import: ce7.’s behaviour to absolute
imports using a ‘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,
‘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 ‘from pkg import string’
in your code.

Relative imports are still possible by adding a leading period to the
module name when using the ‘from ... import’ form:

     # Import names from pkg.string
     from .string import name1, name2
     # Import pkg.string
     from . import string

This imports the *note string: f6. module relative to the current
package, so in ‘pkg.main’ this will import `name1' and `name2' from
‘pkg.string’.  Additional leading periods perform the relative import
starting from the parent of the current package.  For example, code in
the ‘A.B.C’ module can do:

     from . import D                 # Imports A.B.D
     from .. import E                # Imports A.E
     from ..F import G               # Imports A.F.G

Leading periods cannot be used with the ‘import modname’ form of the
import statement, only the ‘from ... import’ form.

也參考
......

PEP 328(2) - 导入：多行和绝对/相对导入

     PEP 由 Aahz 撰写，由 Thomas Wouters 实现。

‘https://pylib.readthedocs.io/’

     The py library by Holger Krekel, which contains the ‘py.std’
     package.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0328

   (2) https://www.python.org/dev/peps/pep-0328


File: python.info,  Node: PEP 338 将模块作为脚本执行,  Next: PEP 341 统一 try/except/finally,  Prev: PEP 328 绝对导入和相对导入,  Up: Python 2 5 有什么新变化

1.13.5 PEP 338: 将模块作为脚本执行
----------------------------------

The *note -m: 443. 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, *note runpy: e2.

The *note runpy: e2. module implements a more sophisticated import
mechanism so that it’s now possible to run modules in a package such as
‘pychecker.checker’.  The module also supports alternative import
mechanisms such as the *note zipimport: 14c. module.  This means you can
add a .zip archive’s path to ‘sys.path’ and then use the *note -m: 443.
switch to execute code from the archive.

也參考
......

PEP 338(1) - 将模块作为脚本执行

     PEP 由 Nick Coghlan 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0338


File: python.info,  Node: PEP 341 统一 try/except/finally,  Next: PEP 342 生成器的新特性,  Prev: PEP 338 将模块作为脚本执行,  Up: Python 2 5 有什么新变化

1.13.6 PEP 341: 统一 try/except/finally
---------------------------------------

Until Python 2.5, the *note try: e37. statement came in two flavours.
You could use a *note finally: 2bc. block to ensure that code is always
executed, or one or more *note except: c10. blocks to catch specific
exceptions.  You couldn’t combine both ‘except’ blocks and a ‘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 *note except: c10. blocks and a *note
finally: 2bc. block, and this clarified what the statement should mean.
In Python 2.5, you can now write:

     try:
         block-1 ...
     except Exception1:
         handler-1 ...
     except Exception2:
         handler-2 ...
     else:
         else-block
     finally:
         final-block

The code in `block-1' is executed.  If the code raises an exception, the
various *note except: c10. blocks are tested: if the exception is of
class ‘Exception1’, `handler-1' is executed; otherwise if it’s of class
‘Exception2’, `handler-2' is executed, and so forth.  If no exception is
raised, the `else-block' is executed.

No matter what happened previously, the `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 `else-block' and a new
exception is raised, the code in the `final-block' is still run.

也參考
......

PEP 341(1) - 统一 try-except 和 try-finally

     PEP 由 Georg Brandl 撰写，由 Thomas Lee 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0341


File: python.info,  Node: PEP 342 生成器的新特性,  Next: PEP 343 "with" 语句<2>,  Prev: PEP 341 统一 try/except/finally,  Up: Python 2 5 有什么新变化

1.13.7 PEP 342: 生成器的新特性
------------------------------

Python 2.5 adds a simple way to pass values `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:

     def counter (maximum):
         i = 0
         while i < maximum:
             yield i
             i += 1

When you call ‘counter(10)’, the result is an iterator that returns the
values from 0 up to 9.  On encountering the *note yield: 2c7. 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 *note next(): 775. method, picking up
after the ‘yield’ statement.

In Python 2.3, *note yield: 2c7. was a statement; it didn’t return any
value.  In 2.5, ‘yield’ is now an expression, returning a value that can
be assigned to a variable or otherwise operated on:

     val = (yield i)

I recommend that you always put parentheses around a *note yield: 2c7.
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.

( PEP 342(1) explains the exact rules, which are that a *note yield:
2c7.-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 ‘val = yield i’ but have to use parentheses when
there’s an operation, as in ‘val = (yield i) + 12’.)

Values are sent into a generator by calling its ‘send(value)’ method.
The generator’s code is then resumed and the *note yield: 2c7.
expression returns the specified `value'.  If the regular *note next():
775. method is called, the ‘yield’ returns *note None: 203.

Here’s the previous example, modified to allow changing the value of the
internal counter.

     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

And here’s an example of changing the counter:

     >>> 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

*note yield: 2c7. will usually return *note None: 203, so you should
always check for this case.  Don’t just use its value in expressions
unless you’re sure that the ‘send()’ method will be the only method used
to resume your generator function.

In addition to ‘send()’, there are two other new methods on generators:

   * ‘throw(type, value=None, traceback=None)’ is used to raise an
     exception inside the generator; the exception is raised by the
     *note yield: 2c7. expression where the generator’s execution is
     paused.

   * ‘close()’ raises a new *note GeneratorExit: df8. exception inside
     the generator to terminate the iteration.  On receiving this
     exception, the generator’s code must either raise *note
     GeneratorExit: df8. or *note StopIteration: 581.  Catching the
     *note GeneratorExit: df8. exception and returning a value is
     illegal and will trigger a *note RuntimeError: 3dc.; if the
     function raises some other exception, that exception is propagated
     to the caller.  ‘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 *note GeneratorExit: df8.
     occurs, I suggest using a ‘try: ... finally:’ suite instead of
     catching *note GeneratorExit: df8.

这些改变的累积效应是，让生成器从单向的信息生产者变成了既是生产者，又是消
费者。

Generators also become `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 *note return: 2c8. statement), but
coroutines can be entered, exited, and resumed at many different points
(the *note yield: 2c7. statements).  We’ll have to figure out patterns
for using coroutines effectively in Python.

The addition of the ‘close()’ method has one side effect that isn’t
obvious.  ‘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 ‘try...finally’
statements in generators can now be guaranteed to work; the *note
finally: 2bc. clause will now always get a chance to run.  The syntactic
restriction that you couldn’t mix *note yield: 2c7. statements with a
‘try...finally’ suite has therefore been removed.  This seems like a
minor bit of language trivia, but using generators and ‘try...finally’
is actually necessary in order to implement the *note with: 7da.
statement described by PEP 343(2).  I’ll look at this new statement in
the following section.

Another even more esoteric effect of this change: previously, the
‘gi_frame’ attribute of a generator was always a frame object.  It’s now
possible for ‘gi_frame’ to be ‘None’ once the generator has been
exhausted.

也參考
......

PEP 342(3) - 通过增强型生成器实现协程

     PEP 由 Guido van Rossum 和 Phillip J. Eby 撰写，由 Phillip J. Eby 实
     现。包括一些更高级的使用生成器作为协程的示例。

     这些功能的早期版本在 PEP 288(4) （由 Raymond Hettinger 撰写） 和
     PEP 325(5) （由 Samuele Pedroni 撰写）中提出。

‘https://en.wikipedia.org/wiki/Coroutine’

     协程的Wikipedia条目。

‘http://www.sidhe.org/~dan/blog/archives/000178.html’

     An explanation of coroutines from a Perl point of view, written by
     Dan Sugalski.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0342

   (2) https://www.python.org/dev/peps/pep-0343

   (3) https://www.python.org/dev/peps/pep-0342

   (4) https://www.python.org/dev/peps/pep-0288

   (5) https://www.python.org/dev/peps/pep-0325


File: python.info,  Node: PEP 343 "with" 语句<2>,  Next: PEP 352 异常作为新型的类,  Prev: PEP 342 生成器的新特性,  Up: Python 2 5 有什么新变化

1.13.8 PEP 343: "with" 语句
---------------------------

The ’*note with: 7da.’ statement clarifies code that previously would
use ‘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 ’*note with: 7da.’ statement is a new control-flow structure whose
basic structure is:

     with expression [as variable]:
         with-block

The expression is evaluated, and it should result in an object that
supports the context management protocol (that is, has *note
__enter__(): d5d. and *note __exit__(): d5e. methods.

The object’s *note __enter__(): d5d. is called before `with-block' is
executed and therefore can run set-up code.  It also may return a value
that is bound to the name `variable', if given.  (Note carefully that
`variable' is `not' assigned the result of `expression'.)

After execution of the `with-block' is finished, the object’s *note
__exit__(): d5e. 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:

     from __future__ import with_statement

该语句在Python 2.6 中始终启用。

Some standard Python objects now support the context management protocol
and can be used with the ’*note with: 7da.’ statement.  File objects are
one example:

     with open('/etc/passwd', 'r') as f:
         for line in f:
             print line
             ... more processing code ...

After this statement has executed, the file object in `f' will have been
automatically closed, even if the *note for: cfa. loop raised an
exception part-way through the block.

     備註: In this case, `f' is the same object created by *note open():
     16f, because ‘file.__enter__()’ returns `self'.

The *note threading: 10b. module’s locks and condition variables also
support the ’*note with: 7da.’ statement:

     lock = threading.Lock()
     with lock:
         # Critical section of code
         ...

The lock is acquired before the block is executed and always released
once the block is complete.

The new ‘localcontext()’ function in the *note decimal: 35. module makes
it easy to save and restore the current decimal context, which
encapsulates the desired precision and rounding characteristics for
computations:

     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()

* Menu:

* Writing Context Managers: Writing Context Managers<2>.
* contextlib 模块: contextlib 模块<2>.


File: python.info,  Node: Writing Context Managers<2>,  Next: contextlib 模块<2>,  Up: PEP 343 "with" 语句<2>

1.13.8.1 Writing Context Managers
.................................

Under the hood, the ’*note with: 7da.’ statement is fairly complicated.
Most people will only use ’‘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.

A high-level explanation of the context management protocol is:

   * The expression is evaluated and should result in an object called a
     "context manager".  The context manager must have *note
     __enter__(): d5d. and *note __exit__(): d5e. methods.

   * The context manager’s *note __enter__(): d5d. method is called.
     The value returned is assigned to `VAR'. If no ‘'as VAR'’ clause is
     present, the value is simply discarded.

   * The code in `BLOCK' is executed.

   * If `BLOCK' raises an exception, the ‘__exit__(type, value,
     traceback)’ is called with the exception details, the same values
     returned by *note sys.exc_info(): d27.  The method’s return value
     controls whether the exception is re-raised: any false value
     re-raises the exception, and ‘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 ’*note with: 7da.’
     statement will never realize anything went wrong.

   * If `BLOCK' didn’t raise an exception, the *note __exit__(): d5e.
     method is still called, but `type', `value', and `traceback' are
     all ‘None’.

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:

     db_connection = DatabaseConnection()
     with db_connection as cursor:
         cursor.execute('insert into ...')
         cursor.execute('delete from ...')
         # ... more operations ...

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 ‘DatabaseConnection’ that I’ll assume:

     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"

The *note __enter__(): d5d. 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 ‘as cursor’ to their ’*note with: 7da.’ statement to bind the
cursor to a variable name.

     class DatabaseConnection:
         ...
         def __enter__ (self):
             # Code to start a new transaction
             cursor = self.cursor()
             return cursor

The *note __exit__(): d5e. 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 ‘None’.  ‘None’ is false, so the
exception will be re-raised automatically.  If you wished, you could be
more explicit and add a *note return: 2c8. statement at the marked
location.

     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


File: python.info,  Node: contextlib 模块<2>,  Prev: Writing Context Managers<2>,  Up: PEP 343 "with" 语句<2>

1.13.8.2 contextlib 模块
........................

The new *note contextlib: 23. module provides some functions and a
decorator that are useful for writing objects for use with the ’*note
with: 7da.’ statement.

The decorator is called ‘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 *note yield: 2c7.
will be executed as the *note __enter__(): d5d. method, and the value
yielded will be the method’s return value that will get bound to the
variable in the ’*note with: 7da.’ statement’s ‘as’ clause, if any.  The
code after the *note yield: 2c7. will be executed in the *note
__exit__(): d5e. method.  Any exception raised in the block will be
raised by the ‘yield’ statement.

Our database example from the previous section could be written using
this decorator as:

     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:
         ...

The *note contextlib: 23. module also has a ‘nested(mgr1, mgr2, ...)’
function that combines a number of context managers so you don’t need to
write nested ’*note with: 7da.’ statements.  In this example, the single
’‘with’’ statement both starts a database transaction and acquires a
thread lock:

     lock = threading.Lock()
     with nested (db_transaction(db), lock) as (cursor, locked):
         ...

Finally, the ‘closing(object)’ function returns `object' so that it can
be bound to a variable, and calls ‘object.close’ at the end of the
block.

     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)

也參考
......

PEP 343(1) - "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 ’*note with: 7da.’ statement, which can be
     helpful in learning how the statement works.

*note contextlib: 23. 模块的文档。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0343


File: python.info,  Node: PEP 352 异常作为新型的类,  Next: PEP 353 使用ssize_t作为索引类型,  Prev: PEP 343 "with" 语句<2>,  Up: Python 2 5 有什么新变化

1.13.9 PEP 352: 异常作为新型的类
--------------------------------

Exception classes can now be new-style classes, not just classic
classes, and the built-in *note Exception: 2dc. class and all the
standard built-in exceptions (*note NameError: e40, *note ValueError:
16d, etc.)  are now new-style classes.

The inheritance hierarchy for exceptions has been rearranged a bit.  In
2.5, the inheritance relationships are:

     BaseException       # New in Python 2.5
     |- KeyboardInterrupt
     |- SystemExit
     |- Exception
        |- (all other current built-in exceptions)

This rearrangement was done because people often want to catch all
exceptions that indicate program errors.  *note KeyboardInterrupt: 2cc.
and *note SystemExit: 6f3. aren’t errors, though, and usually represent
an explicit action such as the user hitting ‘Control-C’ or code calling
*note sys.exit(): daa.  A bare ‘except:’ will catch all exceptions, so
you commonly need to list *note KeyboardInterrupt: 2cc. and *note
SystemExit: 6f3. in order to re-raise them.  The usual pattern is:

     try:
         ...
     except (KeyboardInterrupt, SystemExit):
         raise
     except:
         # Log error...
         # Continue running program...

In Python 2.5, you can now write ‘except Exception’ to achieve the same
result, catching all the exceptions that usually indicate errors but
leaving *note KeyboardInterrupt: 2cc. and *note SystemExit: 6f3. alone.
As in previous versions, a bare ‘except:’ still catches all exceptions.

The goal for Python 3.0 is to require any class raised as an exception
to derive from *note BaseException: 2db. or some descendant of *note
BaseException: 2db, 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 *note Exception: 2dc. now.  It’s
been suggested that the bare ‘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 ‘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.

也參考
......

PEP 352(1) - 异常所需的超类

     PEP 由 Brett Cannon 和 Guido van Rossum 撰写，由 Brett Cannon 实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0352


File: python.info,  Node: PEP 353 使用ssize_t作为索引类型,  Next: PEP 357 '__index__' 方法,  Prev: PEP 352 异常作为新型的类,  Up: Python 2 5 有什么新变化

1.13.10 PEP 353: 使用ssize_t作为索引类型
----------------------------------------

A wide-ranging change to Python’s C API, using a new ‘Py_ssize_t’ type
definition instead of ‘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 ‘int’ type to store
sizes or counts; for example, the number of items in a list or tuple
were stored in an ‘int’.  The C compilers for most 64-bit platforms
still define ‘int’ as a 32-bit type, so that meant that lists could only
hold up to ‘2**31 - 1’ = 2147483647 items.  (There are actually a few
different programming models that 64-bit C compilers can use – see
‘http://www.unix.org/version2/whatsnew/lp64_wp.html’ for a discussion –
but the most commonly available model leaves ‘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 *note PyObject: 5b4. 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 ‘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 `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
‘Py_ssize_t’ to store their size.  Functions such as *note
PyList_Size(): e43. now return ‘Py_ssize_t’.  Code in extension modules
may therefore need to have some variables changed to ‘Py_ssize_t’.

The *note PyArg_ParseTuple(): 393. and *note Py_BuildValue(): 3f0.
functions have a new conversion code, ‘n’, for ‘Py_ssize_t’.  *note
PyArg_ParseTuple(): 393.’s ‘s#’ and ‘t#’ still output ‘int’ by default,
but you can define the macro ‘PY_SSIZE_T_CLEAN’ before including
‘Python.h’ to make them return ‘Py_ssize_t’.

PEP 353(1) has a section on conversion guidelines that extension authors
should read to learn about supporting 64-bit platforms.

也參考
......

PEP 353(2) - 使用ssize_t作为索引类型

     PEP 由 Martin von Löwis 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0353

   (2) https://www.python.org/dev/peps/pep-0353


File: python.info,  Node: PEP 357 '__index__' 方法,  Next: 其他语言特性修改<12>,  Prev: PEP 353 使用ssize_t作为索引类型,  Up: Python 2 5 有什么新变化

1.13.11 PEP 357: ’__index__’ 方法
---------------------------------

The NumPy developers had a problem that could only be solved by adding a
new special method, *note __index__(): 2c2.  When using slice notation,
as in ‘[start:stop:step]’, the values of the `start', `stop', and `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 *note __int__(): 2c3. method because
that method is also used to implement coercion to integers.  If slicing
used *note __int__(): 2c3, floating-point numbers would also become
legal slice indexes and that’s clearly an undesirable behaviour.

Instead, a new special method called *note __index__(): 2c2. was added.
It takes no arguments and returns an integer giving the slice index to
use.  For example:

     class C:
         def __index__ (self):
             return self.value

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
*note TypeError: 1fe. if this requirement isn’t met.

A corresponding ‘nb_index’ slot was added to the C-level *note
PyNumberMethods: e46. structure to let C extensions implement this
protocol.  ‘PyNumber_Index(obj)’ can be used in extension code to call
the *note __index__(): 2c2. function and retrieve its result.

也參考
......

PEP 357(1) - 允许将任何对象用于切片

     PEP 由 Travis Oliphant 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0357


File: python.info,  Node: 其他语言特性修改<12>,  Next: 新增，改进和删除的模块,  Prev: PEP 357 '__index__' 方法,  Up: Python 2 5 有什么新变化

1.13.12 其他语言特性修改
------------------------

Here are all of the changes that Python 2.5 makes to the core Python
language.

   * The *note dict: 164. 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
     ‘__missing__(key)’ method will be called.  This hook is used to
     implement the new ‘defaultdict’ class in the *note collections: 1d.
     module.  The following example defines a dictionary that returns
     zero for any missing key:

          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

   * Both 8-bit and Unicode strings have new ‘partition(sep)’ and
     ‘rpartition(sep)’ methods that simplify a common use case.

     The ‘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.  ‘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.  ‘rpartition(sep)’ also returns a 3-tuple but
     starts searching from the end of the string; the ‘r’ stands for
     ’reverse’.

     一些範例：

          >>> ('http://www.python.org').partition('://')
          ('http', '://', 'www.python.org')
          >>> ('file:/usr/share/doc/index.html').partition('://')
          ('file:/usr/share/doc/index.html', '', '')
          >>> (u'Subject: a quick question').partition(':')
          (u'Subject', u':', u' a quick question')
          >>> 'www.python.org'.rpartition('.')
          ('www.python', '.', 'org')
          >>> 'www.python.org'.rpartition(':')
          ('', '', 'www.python.org')

     (Implemented by Fredrik Lundh following a suggestion by Raymond
     Hettinger.)

   * The ‘startswith()’ and ‘endswith()’ methods of string types now
     accept tuples of strings to check for.

          def is_image_file (filename):
              return filename.endswith(('.gif', '.jpg', '.tiff'))

     (Implemented by Georg Brandl following a suggestion by Tom Lynn.)

   * The *note min(): 8f6. and *note max(): 8f7. built-in functions
     gained a ‘key’ keyword parameter analogous to the ‘key’ argument
     for ‘sort()’.  This parameter supplies a function that takes a
     single argument and is called for every value in the list; *note
     min(): 8f6./*note max(): 8f7. 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:

          L = ['medium', 'longest', 'short']
          # Prints 'longest'
          print max(L, key=len)
          # Prints 'short', because lexicographically 'short' has the largest value
          print max(L)

     （由 Steven Bethard 和 Raymond Hettinger 贡献。）

   * Two new built-in functions, *note any(): e49. and *note all(): e4a,
     evaluate whether an iterator contains any true or false values.
     *note any(): e49. returns *note True: 593. if any value returned by
     the iterator is true; otherwise it will return *note False: 48e.
     *note all(): e4a. returns *note True: 593. only if all of the
     values returned by the iterator evaluate as true.  (Suggested by
     Guido van Rossum, and implemented by Raymond Hettinger.)

   * The result of a class’s *note __hash__(): 44c. 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
     *note id(): e4b. built-in was changed to always return non-negative
     numbers, and users often seem to use ‘id(self)’ in *note
     __hash__(): 44c. methods (though this is discouraged).

   * 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 PEP 263(1) for how to
     declare a module’s encoding; for example, you might add a line like
     this near the top of the source file:

          # -*- coding: latin1 -*-

   * A new warning, *note UnicodeWarning: e4c, 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:

          >>> 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

     Previously this would raise a *note UnicodeDecodeError: 32b.
     exception, but in 2.5 this could result in puzzling problems when
     accessing a dictionary.  If you looked up ‘unichr(128)’ and
     ‘chr(128)’ was being used as a key, you’d get a *note
     UnicodeDecodeError: 32b. exception.  Other changes in 2.5 resulted
     in this exception being raised instead of suppressed by the code in
     ‘dictobject.c’ that implements dictionaries.

     Raising an exception for such a comparison is strictly correct, but
     the change might have broken code, so instead *note UnicodeWarning:
     e4c. was introduced.

     （由 Marc-André Lemburg 实现。）

   * One error that Python programmers sometimes make is forgetting to
     include an ‘__init__.py’ module in a package directory.  Debugging
     this mistake can be confusing, and usually requires running Python
     with the *note -v: e4d. switch to log all the paths searched.  In
     Python 2.5, a new *note ImportWarning: 6cf. warning is triggered
     when an import would have picked up a directory as a package but no
     ‘__init__.py’ was found.  This warning is silently ignored by
     default; provide the *note -Wd: 15b. option when running the Python
     executable to display the warning message.  (Implemented by Thomas
     Wouters.)

   * The list of base classes in a class definition can now be empty.
     As an example, this is now legal:

          class C():
              pass

     （由 Brett Cannon 实现。）

* Menu:

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

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0263


File: python.info,  Node: 交互解释器变更,  Next: 性能优化<11>,  Up: 其他语言特性修改<12>

1.13.12.1 交互解释器变更
........................

In the interactive interpreter, ‘quit’ and ‘exit’ have long been strings
so that new users get a somewhat helpful message when they try to quit:

     >>> quit
     'Use Ctrl-D (i.e. EOF) to exit.'

In Python 2.5, ‘quit’ and ‘exit’ are now objects that still produce
string representations of themselves, but are also callable.  Newbies
who try ‘quit()’ or ‘exit()’ will now exit the interpreter as they
expect.  (Implemented by Georg Brandl.)

The Python executable now accepts the standard long options *note –help:
e50. and *note –version: 6c8.; on Windows, it also accepts the *note /?:
e51. option for displaying a help message.  (Implemented by Georg
Brandl.)


File: python.info,  Node: 性能优化<11>,  Prev: 交互解释器变更,  Up: 其他语言特性修改<12>

1.13.12.2 性能优化
..................

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.

   * When they were introduced in Python 2.4, the built-in *note set:
     1f6. and *note frozenset: 1f7. 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.)

   * 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.)

   * The ‘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.)

   * It’s now illegal to mix iterating over a file with ‘for line in
     file’ and calling the file object’s ‘read()’/*note readline():
     de./‘readlines()’ methods.  Iteration uses an internal buffer and
     the ‘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 *note ValueError: 16d. from the ‘read*()’ method.  (Implemented
     by Thomas Wouters.)

   * The *note struct: f8. 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.)

   * The *note re: dd. module got a 1 or 2% speedup by switching to
     Python’s allocator functions instead of the system’s ‘malloc()’ and
     ‘free()’.  (Contributed by Jack Diederich at the NeedForSpeed
     sprint.)

   * The code generator’s peephole optimizer now performs simple
     constant folding in expressions.  If you write something like ‘a =
     2+3’, the code generator will do the arithmetic and produce code
     corresponding to ‘a = 5’.  (Proposed and implemented by Raymond
     Hettinger.)

   * 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.)

   * 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.)

   * Importing now caches the paths tried, recording whether they exist
     or not so that the interpreter makes fewer ‘open()’ and ‘stat()’
     calls on startup.  (Contributed by Martin von Löwis and Georg
     Brandl.)


File: python.info,  Node: 新增，改进和删除的模块,  Next: 构建和 C API 的改变<10>,  Prev: 其他语言特性修改<12>,  Up: Python 2 5 有什么新变化

1.13.13 新增，改进和删除的模块
------------------------------

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 ‘Misc/NEWS’ file in the
source tree for a more complete list of changes, or look through the SVN
logs for all the details.

   * The *note audioop: c. module now supports the a-LAW encoding, and
     the code for u-LAW encoding has been improved.  (Contributed by
     Lars Immisch.)

   * The *note codecs: 1b. module gained support for incremental codecs.
     The ‘codec.lookup()’ function now returns a ‘CodecInfo’ instance
     instead of a tuple.  ‘CodecInfo’ instances behave like a 4-tuple to
     preserve backward compatibility but also have the attributes
     ‘encode’, ‘decode’, ‘incrementalencoder’, ‘incrementaldecoder’,
     ‘streamwriter’, and ‘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 *note codecs: 1b. module documentation for details.  (Designed
     and implemented by Walter Dörwald.)

   * The *note collections: 1d. module gained a new type, ‘defaultdict’,
     that subclasses the standard *note dict: 164. 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 ‘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 *note list(): 1f8. or *note
     int(): 204.  For example, you can make an index of words based on
     their initial letter like this:

          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)

     打印 ‘index’ 导致以下输出:

          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']}

     （由 Guido van Rossum 贡献。）

   * The ‘deque’ double-ended queue type supplied by the *note
     collections: 1d. module now has a ‘remove(value)’ method that
     removes the first occurrence of `value' in the queue, raising *note
     ValueError: 16d. if the value isn’t found.  (Contributed by Raymond
     Hettinger.)

   * New module: The *note contextlib: 23. module contains helper
     functions for use with the new ’*note with: 7da.’ statement.  See
     section *note contextlib 模块: e3c. for more about this module.

   * New module: The *note cProfile: 27. module is a C implementation of
     the existing *note profile: d3. module that has much lower
     overhead.  The module’s interface is the same as *note profile:
     d3.: you run ‘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
     *note profile: d3. module’s interface, will continue to be
     maintained in future versions of Python.  (Contributed by Armin
     Rigo.)

     Also, the *note pstats: d4. module for analyzing the data measured
     by the profiler now supports directing the output to any file
     object by supplying a `stream' argument to the ‘Stats’ constructor.
     (Contributed by Skip Montanaro.)

   * The *note csv: 29. 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 ‘csv.field_size_limit(new_limit)’ function; omitting
     the `new_limit' argument will return the currently-set limit.  The
     ‘reader’ class now has a ‘line_num’ attribute that counts the
     number of physical lines read from the source; records can span
     multiple physical lines, so ‘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 贡献。）

   * The *note datetime: 19f. class in the *note datetime: 30. module
     now has a ‘strptime(string, format)’ method for parsing date
     strings, contributed by Josh Spoerri.  It uses the same format
     characters as *note time.strptime(): e56. and *note
     time.strftime(): c37.:

          from datetime import datetime

          ts = datetime.strptime('10:13:15 2006-03-07',
                                 '%H:%M:%S %Y-%m-%d')

   * The ‘SequenceMatcher.get_matching_blocks()’ method in the *note
     difflib: 36. 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.)

   * The *note doctest: 66. module gained a ‘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 `encoding' parameter was added to the ‘testfile()’ function and
     the ‘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.)

   * *note email: 67. 包已经升级到 4.0版 （由 Barry Warsaw 贡献）

   * The *note fileinput: 7e. module was made more flexible.  Unicode
     filenames are now supported, and a `mode' parameter that defaults
     to ‘"r"’ was added to the *note input(): d33. function to allow
     opening files in binary or *note universal newlines: 6eb. mode.
     Another new parameter, `openhook', lets you use a function other
     than *note open(): 16f. to open the input files.  Once you’re
     iterating over the set of files, the ‘FileInput’ object’s new
     ‘fileno()’ returns the file descriptor for the currently opened
     file.  (Contributed by Georg Brandl.)

   * In the *note gc: 84. module, the new ‘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 *note gc.collect():
     35b. function now takes an optional `generation' argument of 0, 1,
     or 2 to specify which generation to collect.  (Contributed by Barry
     Warsaw.)

   * The ‘nsmallest()’ and ‘nlargest()’ functions in the *note heapq:
     8d. module now support a ‘key’ keyword parameter similar to the one
     provided by the *note min(): 8f6./*note max(): 8f7. functions and
     the ‘sort()’ methods.  For 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']

     （由 Raymond Hettinger 贡献。）

   * The *note itertools.islice(): 4a8. function now accepts ‘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:

          s = slice(5)     # Create slice object
          itertools.islice(iterable, s.start, s.stop, s.step)

     （由 Raymond Hettinger 贡献。）

   * The *note format(): 5d5. function in the *note locale: a9. module
     has been modified and two new functions were added,
     ‘format_string()’ and ‘currency()’.

     The *note format(): 5d5. function’s `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 `monetary' parameter was
     also added which, if ‘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
     ‘format_string()’ function that works like *note format(): 5d5. but
     also supports mixing %char specifiers with arbitrary text.

     A new ‘currency()’ function was also added that formats a number
     according to the current locale’s settings.

     （由Georg Brandl 贡献。）

   * The *note mailbox: ae. module underwent a massive rewrite to add
     the capability to modify mailboxes in addition to reading them.  A
     new set of classes that include ‘mbox’, ‘MH’, and ‘Maildir’ are
     used to read mailboxes, and have an ‘add(message)’ method to add
     messages, ‘remove(key)’ to remove messages, and ‘lock()’/‘unlock()’
     to lock/unlock the mailbox.  The following example converts a
     maildir-format mailbox into an mbox-format one:

          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)

     (Contributed by Gregory K. Johnson.  Funding was provided by
     Google’s 2005 Summer of Code.)

   * New module: the *note msilib: b5. module allows creating Microsoft
     Installer ‘.msi’ files and CAB files.  Some support for reading the
     ‘.msi’ database is also included.  (Contributed by Martin von
     Löwis.)

   * The *note nis: bf. module now supports accessing domains other than
     the system default domain by supplying a `domain' argument to the
     *note nis.match(): e57. and *note nis.maps(): e58. functions.
     (Contributed by Ben Bell.)

   * The *note operator: c2. module’s ‘itemgetter()’ and ‘attrgetter()’
     functions now support multiple fields.  A call such as
     ‘operator.attrgetter('a', 'b')’ will return a function that
     retrieves the ‘a’ and ‘b’ attributes.  Combining this new feature
     with the ‘sort()’ method’s ‘key’ parameter lets you easily sort
     lists using multiple fields.  (Contributed by Raymond Hettinger.)

   * The *note optparse: c3. module was updated to version 1.5.1 of the
     Optik library.  The ‘OptionParser’ class gained an ‘epilog’
     attribute, a string that will be printed after the help message,
     and a ‘destroy()’ method to break reference cycles created by the
     object.  (Contributed by Greg Ward.)

   * The *note os: c4. module underwent several changes.  The
     ‘stat_float_times’ variable now defaults to true, meaning that
     *note os.stat(): 321. will now return time values as floats.  (This
     doesn’t necessarily mean that *note os.stat(): 321. will return
     times that are precise to fractions of a second; not all systems
     support such precision.)

     Constants named *note os.SEEK_SET: e59, *note os.SEEK_CUR: e5a, and
     *note os.SEEK_END: e5b. have been added; these are the parameters
     to the *note os.lseek(): b39. function.  Two new constants for
     locking are *note os.O_SHLOCK: e5c. and *note os.O_EXLOCK: e5d.

     Two new functions, ‘wait3()’ and ‘wait4()’, were added.  They’re
     similar the ‘waitpid()’ function which waits for a child process to
     exit and returns a tuple of the process ID and its exit status, but
     ‘wait3()’ and ‘wait4()’ return additional information.  ‘wait3()’
     doesn’t take a process ID as input, so it waits for any child
     process to exit and returns a 3-tuple of `process-id',
     `exit-status', `resource-usage' as returned from the *note
     resource.getrusage(): e5e. function.  ‘wait4(pid)’ does take a
     process ID. (Contributed by Chad J. Schroeder.)

     On FreeBSD, the *note os.stat(): 321. function now returns times
     with nanosecond resolution, and the returned object now has
     ‘st_gen’ and ‘st_birthtime’.  The ‘st_flags’ attribute is also
     available, if the platform supports it.  (Contributed by Antti
     Louko and Diego Pettenò.)

   * The Python debugger provided by the *note pdb: c9. module can now
     store lists of commands to execute when a breakpoint is reached and
     execution stops.  Once breakpoint #1 has been created, enter
     ‘commands 1’ and enter a series of commands to be executed,
     finishing the list with ‘end’.  The command list can include
     commands that resume execution, such as ‘continue’ or ‘next’.
     (Contributed by Grégoire Dooms.)

   * The *note pickle: ca. and ‘cPickle’ modules no longer accept a
     return value of ‘None’ from the *note __reduce__(): 2d0. method;
     the method must return a tuple of arguments instead.  The ability
     to return ‘None’ was deprecated in Python 2.4, so this completes
     the removal of the feature.

   * The *note pkgutil: cd. module, containing various utility functions
     for finding packages, was enhanced to support PEP 302(1)’s import
     hooks and now also works for packages stored in ZIP-format
     archives.  (Contributed by Phillip J. Eby.)

   * The pybench benchmark suite by Marc-André Lemburg is now included
     in the ‘Tools/pybench’ directory.  The pybench suite is an
     improvement on the commonly used ‘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 ‘pystone.py’ does.

   * The ‘pyexpat’ module now uses version 2.0 of the Expat parser.
     (Contributed by Trent Mick.)

   * The *note Queue: dde. class provided by the ‘Queue’ module gained
     two new methods.  ‘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,
     ‘task_done()’, to signal that processing for an item has been
     completed.  (Contributed by Raymond Hettinger.)

   * The old ‘regex’ and ‘regsub’ modules, which have been deprecated
     ever since Python 2.0, have finally been deleted.  Other deleted
     modules: ‘statcache’, ‘tzparse’, ‘whrandom’.

   * Also deleted: the ‘lib-old’ directory, which includes ancient
     modules such as ‘dircmp’ and ‘ni’, was removed.  ‘lib-old’ wasn’t
     on the default ‘sys.path’, so unless your programs explicitly added
     the directory to ‘sys.path’, this removal shouldn’t affect your
     code.

   * The *note rlcompleter: e1. module is no longer dependent on
     importing the *note readline: de. module and therefore now works on
     non-Unix platforms.  (Patch from Robert Kiendl.)

   * The ‘SimpleXMLRPCServer’ and ‘DocXMLRPCServer’ classes now have a
     ‘rpc_paths’ attribute that constrains XML-RPC operations to a
     limited set of URL paths; the default is to allow only ‘'/'’ and
     ‘'/RPC2'’.  Setting ‘rpc_paths’ to ‘None’ or an empty tuple
     disables this path checking.

   * The *note socket: ef. module now supports ‘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
     ‘https://www.linuxjournal.com/article/7356’.  In Python code,
     netlink addresses are represented as a tuple of 2 integers, ‘(pid,
     group_mask)’.

     Two new methods on socket objects, ‘recv_into(buffer)’ and
     ‘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 ‘getfamily()’, ‘gettype()’, and
     ‘getproto()’ accessor methods to retrieve the family, type, and
     protocol values for the socket.

   * New module: the *note spwd: f1. module provides functions for
     accessing the shadow password database on systems that support
     shadow passwords.

   * The *note struct: f8. is now faster because it compiles format
     strings into ‘Struct’ objects with ‘pack()’ and ‘unpack()’ methods.
     This is similar to how the *note re: dd. module lets you create
     compiled regular expression objects.  You can still use the
     module-level ‘pack()’ and ‘unpack()’ functions; they’ll create
     ‘Struct’ objects and cache them.  Or you can use ‘Struct’ instances
     directly:

          s = struct.Struct('ih3s')

          data = s.pack(1972, 187, 'abc')
          year, number, name = s.unpack(data)

     You can also pack and unpack data to and from buffer objects
     directly using the ‘pack_into(buffer, offset, v1, v2, ...)’ and
     ‘unpack_from(buffer, offset)’ methods.  This lets you store data
     directly into an array or a memory-mapped file.

     (‘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.)

   * The Python developers switched from CVS to Subversion during the
     2.5 development process.  Information about the exact build version
     is available as the ‘sys.subversion’ variable, a 3-tuple of
     ‘(interpreter-name, branch-name, revision-range)’.  For example, at
     the time of writing my copy of 2.5 was reporting ‘('CPython',
     'trunk', '45313:45315')’.

     This information is also available to C extensions via the *note
     Py_GetBuildInfo(): e5f. function that returns a string of build
     information like this: ‘"trunk:45355:45356M, Apr 13 2006,
     07:42:19"’.  (Contributed by Barry Warsaw.)

   * Another new function, *note sys._current_frames(): e60, 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.)

   * The ‘TarFile’ class in the *note tarfile: 101. module now has an
     ‘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 ‘'r|*'’.  (Contributed by Lars
     Gustäbel.)

   * The *note threading: 10b. module now lets you set the stack size
     used when new threads are created.  The ‘stack_size([*size*])’
     function returns the currently configured stack size, and supplying
     the optional `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.)

   * The *note unicodedata: 123. 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 *note
     unicodedata.ucd_3_2_0: e61.

   * New module: the *note uuid: 12d. module generates universally
     unique identifiers (UUIDs) according to RFC 4122(2).  The RFC
     defines several different UUID versions that are generated from a
     starting string, from system properties, or purely randomly.  This
     module contains a ‘UUID’ class and functions named ‘uuid1()’,
     ‘uuid3()’, ‘uuid4()’, and ‘uuid5()’ to generate different versions
     of UUID. (Version 2 UUIDs are not specified in RFC 4122(3) and are
     not supported by this module.)

          >>> 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')

     （由 Ka-Ping Yee 贡献。）

   * The *note weakref: 131. module’s ‘WeakKeyDictionary’ and
     ‘WeakValueDictionary’ types gained new methods for iterating over
     the weak references contained in the dictionary.  ‘iterkeyrefs()’
     and ‘keyrefs()’ methods were added to ‘WeakKeyDictionary’, and
     ‘itervaluerefs()’ and ‘valuerefs()’ were added to
     ‘WeakValueDictionary’.  (Contributed by Fred L. Drake, Jr.)

   * The *note webbrowser: 132. module received a number of
     enhancements.  It’s now usable as a script with ‘python -m
     webbrowser’, taking a URL as the argument; there are a number of
     switches to control the behaviour (‘-n’ for a new browser window,
     ‘-t’ for a new tab).  New module-level functions, ‘open_new()’ and
     ‘open_new_tab()’, were added to support this.  The module’s *note
     open(): 16f. function supports an additional feature, an
     `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.)

   * The ‘xmlrpclib’ module now supports returning *note datetime: 19f.
     objects for the XML-RPC date type.  Supply ‘use_datetime=True’ to
     the ‘loads()’ function or the ‘Unmarshaller’ class to enable this
     feature.  (Contributed by Skip Montanaro.)

   * The *note zipfile: 14b. 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.)

   * The *note zlib: 14d. module’s ‘Compress’ and ‘Decompress’ objects
     now support a *note copy(): 25. method that makes a copy of the
     object’s internal state and returns a new ‘Compress’ or
     ‘Decompress’ object.  (Contributed by Chris AtLee.)

* Menu:

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

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0302

   (2) https://tools.ietf.org/html/rfc4122.html

   (3) https://tools.ietf.org/html/rfc4122.html


File: python.info,  Node: ctypes 包,  Next: ElementTree 包,  Up: 新增，改进和删除的模块

1.13.13.1 ctypes 包
...................

The *note ctypes: 2a. package, written by Thomas Heller, has been added
to the standard library.  *note ctypes: 2a. lets you call arbitrary
functions in shared libraries or DLLs.  Long-time users may remember the
‘dl’ module, which provides functions for loading shared libraries and
calling functions in them.  The *note ctypes: 2a. package is much
fancier.

To load a shared library or DLL, you must create an instance of the
‘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 ‘CDLL’ object.

     import ctypes

     libc = ctypes.CDLL('libc.so.6')
     result = libc.printf("Line of output\n")

Type constructors for the various C types are provided: ‘c_int()’,
‘c_float()’, ‘c_double()’, ‘c_char_p()’ (equivalent to ‘char *’), and so
forth.  Unlike Python’s types, the C versions are all mutable; you can
assign to their ‘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 `must'; getting it wrong will often
result in the interpreter crashing with a segmentation fault.)

You shouldn’t use ‘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 ‘create_string_buffer()’:

     s = "this is a string"
     buf = ctypes.create_string_buffer(s)
     libc.strfry(buf)

C functions are assumed to return integers, but you can set the
‘restype’ attribute of the function object to change this:

     >>> libc.atof('2.71828')
     -1783957616
     >>> libc.atof.restype = ctypes.c_double
     >>> libc.atof('2.71828')
     2.71828

*note ctypes: 2a. also provides a wrapper for Python’s C API as the
‘ctypes.pythonapi’ object.  This object does `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 ‘py_object()’
type constructor that will create a *note PyObject *: 5b4. pointer.  A
simple usage:

     import ctypes

     d = {}
     ctypes.pythonapi.PyObject_SetItem(ctypes.py_object(d),
               ctypes.py_object("abc"),  ctypes.py_object(1))
     # d is now {'abc', 1}.

Don’t forget to use ‘py_object()’; if it’s omitted you end up with a
segmentation fault.

*note ctypes: 2a. has been around for a while, but people still write
and distribution hand-coded extension modules because you can’t rely on
*note ctypes: 2a. being present.  Perhaps developers will begin to write
Python wrappers atop a library accessed through *note ctypes: 2a.
instead of extension modules, now that *note ctypes: 2a. is included
with core Python.

也參考
......

‘http://starship.python.net/crew/theller/ctypes/’

     ctypes的主页，含教程， 参考和常见问题解答。

*note ctypes: 2a. 模块的文档。


File: python.info,  Node: ElementTree 包,  Next: hashlib 包,  Prev: ctypes 包,  Up: 新增，改进和删除的模块

1.13.13.2 ElementTree 包
........................

A subset of Fredrik Lundh’s ElementTree library for processing XML has
been added to the standard library as ‘xml.etree’.  The available
modules are ‘ElementTree’, ‘ElementPath’, and ‘ElementInclude’ from
ElementTree 1.2.6.  The ‘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
‘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 ‘text’ and ‘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 ‘TextNode’.)

The most commonly used parsing function is ‘parse()’, that takes either
a string (assumed to contain a filename) or a file-like object and
returns an ‘ElementTree’ instance:

     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)

Once you have an ‘ElementTree’ instance, you can call its ‘getroot()’
method to get the root ‘Element’ node.

There’s also an ‘XML()’ function that takes a string literal and returns
an ‘Element’ node (not an ‘ElementTree’).  This function provides a tidy
way to incorporate XML fragments, approaching the convenience of an XML
literal:

     svg = ET.XML("""<svg width="10px" version="1.0">
                  </svg>""")
     svg.set('height', '320px')
     svg.append(elem1)

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.

运算                                结果
                                    
-------------------------------------------------------------------------------------
                                    
‘elem[n]’                           返回第n个子元素
                                    
                                    
‘elem[m:n]’                         返回第m至第n个子元素的列表。
                                    
                                    
‘len(elem)’                         返回子元素的个数
                                    
                                    
‘list(elem)’                        返回子元素的列表
                                    
                                    
‘elem.append(elem2)’                将 `elem2' 添加为子级。
                                    
                                    
‘elem.insert(index, elem2)’         在指定位置插入 `elem2' 。
                                    
                                    
‘del elem[n]’                       删除第n个子元素
                                    
                                    
‘elem.keys()’                       返回属性名称的列表。
                                    
                                    
‘elem.get(name)’                    返回 `name' 属性的值。
                                    
                                    
‘elem.set(name, value)’             为 `name' 属性设置新值
                                    
                                    
‘elem.attrib’                       检索包含属性的字典。
                                    
                                    
‘del elem.attrib[name]’             删除 元素 `name' 的属性
                                    

Comments and processing instructions are also represented as ‘Element’
nodes.  To check if a node is a comment or processing instructions:

     if elem.tag is ET.Comment:
         ...
     elif elem.tag is ET.ProcessingInstruction:
         ...

To generate XML output, you should call the ‘ElementTree.write()’
method.  Like ‘parse()’, it can take either a string or a file-like
object:

     # Encoding is US-ASCII
     tree.write('output.xml')

     # Encoding is UTF-8
     f = open('output.xml', 'w')
     tree.write(f, encoding='utf-8')

(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.

也參考
......

‘http://effbot.org/zone/element-index.htm’

     ElementTree 的官方文档


File: python.info,  Node: hashlib 包,  Next: sqlite3 包,  Prev: ElementTree 包,  Up: 新增，改进和删除的模块

1.13.13.3 hashlib 包
....................

A new *note hashlib: 8c. module, written by Gregory P. Smith, has been
added to replace the ‘md5’ and ‘sha’ modules.  *note hashlib: 8c. 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 ‘md5’ and ‘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.

     # 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

Once a hash object has been created, its methods are the same as before:
‘update(string)’ hashes the specified string into the current digest
state, ‘digest()’ and ‘hexdigest()’ return the digest value as a binary
string or a string of hex digits, and *note copy(): 25. returns a new
hashing object with the same digest state.

也參考
......

*note hashlib: 8c. 模块的文档。


File: python.info,  Node: sqlite3 包,  Next: wsgiref 包,  Prev: hashlib 包,  Up: 新增，改进和删除的模块

1.13.13.4 sqlite3 包
....................

The pysqlite module (‘http://www.pysqlite.org’), a wrapper for the
SQLite embedded database, has been added to the standard library under
the package name *note sqlite3: f2.

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 PEP 249(1).

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 ‘Connection’ object that
represents the database.  Here the data will be stored in the
‘/tmp/example’ file:

     conn = sqlite3.connect('/tmp/example')

你也可以使用 ‘:memory:’ 来创建一个内存中的数据库

Once you have a ‘Connection’, you can create a ‘Cursor’ object and call
its ‘execute()’ method to perform SQL commands:

     c = conn.cursor()

     # Create table
     c.execute('''create table stocks
     (date text, trans text, symbol text,
      qty real, price real)''')

     # Insert a row of data
     c.execute("""insert into stocks
               values ('2006-01-05','BUY','RHAT',100,35.14)""")

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 ‘?’ 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 ‘execute()’ method.
(Other database modules may use a different placeholder, such as ‘%s’ or
‘:1’.)  For 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)

To retrieve data after executing a SELECT statement, you can either
treat the cursor as an iterator, call the cursor’s ‘fetchone()’ method
to retrieve a single matching row, or call ‘fetchall()’ to get a list of
the matching rows.

下面是一个使用迭代器形式的例子：

     >>> 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)
     >>>

For more information about the SQL dialect supported by SQLite, see
‘https://www.sqlite.org’.

也參考
......

‘http://www.pysqlite.org’

     pysqlite 的主页

‘https://www.sqlite.org’

     SQLite的主页；它的文档详细描述了它所支持的 SQL 方言的语法和可用的数
     据类型。

*note sqlite3: f2. 模块的文档。

PEP 249(2) - DB-API 2.0 规范

     PEP 由 Marc-André Lemburg 撰写。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0249

   (2) https://www.python.org/dev/peps/pep-0249


File: python.info,  Node: wsgiref 包,  Prev: sqlite3 包,  Up: 新增，改进和删除的模块

1.13.13.5 wsgiref 包
....................

The Web Server Gateway Interface (WSGI) v1.0 defines a standard
interface between web servers and Python web applications and is
described in PEP 333(1).  The *note wsgiref: 135. package is a reference
implementation of the WSGI specification.

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:

     from wsgiref import simple_server

     wsgi_app = ...

     host = ''
     port = 8000
     httpd = simple_server.make_server(host, port, wsgi_app)
     httpd.serve_forever()

也參考
......

‘http://www.wsgi.org’

     WSGI相关资源的核心网站。

PEP 333(2) - Python Web服务器网关接口 v1.0

     PEP 由 Phillip J. Eby 撰写

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0333

   (2) https://www.python.org/dev/peps/pep-0333


File: python.info,  Node: 构建和 C API 的改变<10>,  Next: 移植到Python 2 5,  Prev: 新增，改进和删除的模块,  Up: Python 2 5 有什么新变化

1.13.14 构建和 C API 的改变
---------------------------

Changes to Python’s build process and to the C API include:

   * 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
     PEP 347(1).

   * 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 ‘https://scan.coverity.com’ for the
     statistics.

   * The largest change to the C API came from PEP 353(2), which
     modifies the interpreter to use a ‘Py_ssize_t’ type definition
     instead of ‘int’.  See the earlier section *note PEP 353;
     使用ssize_t作为索引类型: e41. for a discussion of this change.

   * 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
     *note compile(): 2e7. built-in and specifying ‘_ast.PyCF_ONLY_AST’
     as the value of the `flags' parameter:

          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]

     No official documentation has been written for the AST code yet,
     but PEP 339(3) discusses the design.  To start learning about the
     code, read the definition of the various AST nodes in
     ‘Parser/Python.asdl’.  A Python script reads this file and
     generates a set of C structure definitions in
     ‘Include/Python-ast.h’.  The ‘PyParser_ASTFromString()’ and
     ‘PyParser_ASTFromFile()’, defined in ‘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
     ‘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.

   * 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,
     *note PyMem_Malloc(): 5fe, *note PyMem_Realloc(): a50, and *note
     PyMem_Free(): e6e. are one family that allocates raw memory, while
     *note PyObject_Malloc(): 601, *note PyObject_Realloc(): e6f, and
     *note PyObject_Free(): 5fd. are another family that’s supposed to
     be used for creating Python objects.

     Previously these different families all reduced to the platform’s
     ‘malloc()’ and ‘free()’ functions.  This meant it didn’t matter if
     you got things wrong and allocated memory with the ‘PyMem()’
     function but freed it with the *note PyObject(): 5b4. 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.

   * The built-in set types now have an official C API. Call *note
     PySet_New(): e70. and *note PyFrozenSet_New(): e71. to create a new
     set, *note PySet_Add(): e72. and *note PySet_Discard(): e73. to add
     and remove elements, and *note PySet_Contains(): e74. and *note
     PySet_Size(): e75. to examine the set’s state.  (Contributed by
     Raymond Hettinger.)

   * C code can now obtain information about the exact revision of the
     Python interpreter by calling the *note Py_GetBuildInfo(): e5f.
     function that returns a string of build information like this:
     ‘"trunk:45355:45356M, Apr 13 2006, 07:42:19"’.  (Contributed by
     Barry Warsaw.)

   * 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.  ‘Py_LOCAL(type)’ declares the function as returning a value
     of the specified `type' and uses a fast-calling qualifier.
     ‘Py_LOCAL_INLINE(type)’ does the same thing and also requests the
     function be inlined.  If ‘PY_LOCAL_AGGRESSIVE()’ is defined before
     ‘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.)

   * ‘PyErr_NewException(name, base, dict)’ can now accept a tuple of
     base classes as its `base' argument.  (Contributed by Georg
     Brandl.)

   * The ‘PyErr_Warn()’ function for issuing warnings is now deprecated
     in favour of ‘PyErr_WarnEx(category, message, stacklevel)’ which
     lets you specify the number of stack frames separating this
     function and the caller.  A `stacklevel' of 1 is the function
     calling *note PyErr_WarnEx(): e76, 2 is the function above that,
     and so forth.  (Added by Neal Norwitz.)

   * 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.)

   * The ‘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:

          range = PyObject_CallFunction((PyObject*) &PyRange_Type, "lll",
                                        start, stop, step);

* Menu:

* Port-Specific Changes::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0347

   (2) https://www.python.org/dev/peps/pep-0353

   (3) https://www.python.org/dev/peps/pep-0339


File: python.info,  Node: Port-Specific Changes,  Up: 构建和 C API 的改变<10>

1.13.14.1 Port-Specific Changes
...............................

   * MacOS X (10.3 and higher): dynamic loading of modules now uses the
     ‘dlopen()’ function instead of MacOS-specific functions.

   * MacOS X: an ‘--enable-universalsdk’ switch was added to the
     ‘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(1).)

   * Windows: ‘.dll’ is no longer supported as a filename extension for
     extension modules.  ‘.pyd’ is now the only filename extension that
     will be searched for.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue2573


File: python.info,  Node: 移植到Python 2 5,  Next: 致谢<3>,  Prev: 构建和 C API 的改变<10>,  Up: Python 2 5 有什么新变化

1.13.15 移植到Python 2.5
------------------------

This section lists previously described changes that may require changes
to your code:

   * 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.

   * Previously, the ‘gi_frame’ attribute of a generator was always a
     frame object.  Because of the PEP 342(1) changes described in
     section *note PEP 342; 生成器的新特性: e2b, it’s now possible for
     ‘gi_frame’ to be ‘None’.

   * A new warning, *note UnicodeWarning: e4c, 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 *note UnicodeDecodeError:
     32b. exception.

   * Library: the *note csv: 29. 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.

   * Library: the *note locale: a9. module’s *note format(): 5d5.
     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.

   * Library: The *note pickle: ca. and ‘cPickle’ modules no longer
     accept a return value of ‘None’ from the *note __reduce__(): 2d0.
     method; the method must return a tuple of arguments instead.  The
     modules also no longer accept the deprecated `bin' keyword
     parameter.

   * Library: The ‘SimpleXMLRPCServer’ and ‘DocXMLRPCServer’ classes now
     have a ‘rpc_paths’ attribute that constrains XML-RPC operations to
     a limited set of URL paths; the default is to allow only ‘'/'’ and
     ‘'/RPC2'’.  Setting ‘rpc_paths’ to ‘None’ or an empty tuple
     disables this path checking.

   * C API: Many functions now use ‘Py_ssize_t’ instead of ‘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 *note PEP 353;
     使用ssize_t作为索引类型: e41. for a discussion of this change.

   * C API: The obmalloc changes mean that you must be careful to not
     mix usage of the ‘PyMem_*()’ and ‘PyObject_*()’ families of
     functions.  Memory allocated with one family’s ‘*_Malloc()’ must be
     freed with the corresponding family’s ‘*_Free()’ function.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0342


File: python.info,  Node: 致谢<3>,  Prev: 移植到Python 2 5,  Up: Python 2 5 有什么新变化

1.13.16 致谢
------------

作者感谢以下人员对本文各种草稿给予的建议，更正和协助： 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.


File: python.info,  Node: Python 2 4 有什么新变化,  Next: Python 2 3 有什么新变化,  Prev: Python 2 5 有什么新变化,  Up: Python 有什麼新功能？

1.14 Python 2.4 有什么新变化
============================


作者: A.M. Kuchling

本文介绍了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.

* Menu:

* PEP 218; 内置集合对象: PEP 218 内置集合对象.
* PEP 237; 统一长整数和整数: PEP 237 统一长整数和整数.
* PEP 289; 生成器表达式: PEP 289 生成器表达式.
* PEP 292; Simpler String Substitutions: PEP 292 Simpler String Substitutions.
* PEP 318; Decorators for Functions and Methods: PEP 318 Decorators for Functions and Methods.
* 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>.


File: python.info,  Node: PEP 218 内置集合对象,  Next: PEP 237 统一长整数和整数,  Up: Python 2 4 有什么新变化

1.14.1 PEP 218: 内置集合对象
----------------------------

Python 2.3 introduced the ‘sets’ module.  C implementations of set data
types have now been added to the Python core as two new built-in types,
‘set(iterable)’ and ‘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.

     >>> 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'])
     >>> ''.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'])

The *note frozenset(): 1f7. type is an immutable version of *note set():
1f6.  Since it is immutable and hashable, it may be used as a dictionary
key or as a member of another set.

The ‘sets’ module remains in the standard library, and may be useful if
you wish to subclass the ‘Set’ or ‘ImmutableSet’ classes.  There are
currently no plans to deprecate the module.

也參考
......

PEP 218(1) - 添加内置Set对象类型

     最初由 Greg Wilson 提出，由 Raymond Hettinger 最终实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0218


File: python.info,  Node: PEP 237 统一长整数和整数,  Next: PEP 289 生成器表达式,  Prev: PEP 218 内置集合对象,  Up: Python 2 4 有什么新变化

1.14.2 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 *note
FutureWarning: 435. 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, ‘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.

也參考
......

PEP 237(1) - 统一长整数和整数

     原始PEP由 Moshe Zadka 和 GvR 撰写，2.4 的变更由 Kalle Svensson 实现
     。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0237


File: python.info,  Node: PEP 289 生成器表达式,  Next: PEP 292 Simpler String Substitutions,  Prev: PEP 237 统一长整数和整数,  Up: Python 2 4 有什么新变化

1.14.3 PEP 289: 生成器表达式
----------------------------

The iterator feature introduced in Python 2.2 and the *note itertools:
a3. 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:

     links = [link for link in get_all_links() if not link.followed]
     for link in links:
         ...

代替：

     for link in get_all_links():
         if link.followed:
             continue
         ...

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:

     links = (link for link in get_all_links() if not link.followed)
     for link in links:
         ...

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:

     print sum(obj.count for obj in list_all_objects())

Generator expressions differ from list comprehensions in various small
ways.  Most notably, the loop variable (`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.

也參考
......

PEP 289(1) - 生成器表达式

     Proposed by Raymond Hettinger and implemented by Jiwon Seo with
     early efforts steered by Hye-Shik Chang.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0289


File: python.info,  Node: PEP 292 Simpler String Substitutions,  Next: PEP 318 Decorators for Functions and Methods,  Prev: PEP 289 生成器表达式,  Up: Python 2 4 有什么新变化

1.14.4 PEP 292: Simpler String Substitutions
--------------------------------------------

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.

The usual way of substituting variables by name is the ‘%’ operator:

     >>> '%(page)i: %(title)s' % {'page':2, 'title': 'The Best of Times'}
     '2: The Best of Times'

When writing the template string, it can be easy to forget the ‘i’ or
‘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" *note ValueError: 16d, 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 ‘Template’ class to the *note string: f6. module that
uses ‘$’ to indicate a substitution:

     >>> import string
     >>> t = string.Template('$page: $title')
     >>> t.substitute({'page':2, 'title': 'The Best of Times'})
     '2: The Best of Times'

If a key is missing from the dictionary, the ‘substitute()’ method will
raise a *note KeyError: 3e9.  There’s also a ‘safe_substitute()’ method
that ignores missing keys:

     >>> t = string.Template('$page: $title')
     >>> t.safe_substitute({'page':3})
     '3: $title'

也參考
......

PEP 292(1) - Simpler String Substitutions

     由 Barry Warsaw 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0292


File: python.info,  Node: PEP 318 Decorators for Functions and Methods,  Next: PEP 322 反向迭代,  Prev: PEP 292 Simpler String Substitutions,  Up: Python 2 4 有什么新变化

1.14.5 PEP 318: Decorators for Functions and Methods
----------------------------------------------------

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
*note def: e83. statement in the usual way, and pass the resulting
method to a *note staticmethod(): 30a. or *note classmethod(): 309.
function that would wrap up the function as a method of the new type.
Your code would look like this:

     class C:
        def meth (cls):
            ...

        meth = classmethod(meth)   # Rebind name to wrapped-up class method

If the method was very long, it would be easy to miss or forget the
*note classmethod(): 309. 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 `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 *note classmethod(): 309, *note staticmethod(): 30a, and
friends are storing additional information on a function object; they’re
`decorating' functions with more details.

The notation borrows from Java and uses the ‘'@'’ character as an
indicator.  Using the new syntax, the example above would be written:

     class C:

        @classmethod
        def meth (cls):
            ...

The ‘@classmethod’ is shorthand for the ‘meth=classmethod(meth)’
assignment.  More generally, if you have the following:

     @A
     @B
     @C
     def f ():
         ...

It’s equivalent to the following pre-decorator code:

     def f(): ...
     f = A(B(C(f)))

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 ‘@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:

     >>> def deco(func):
     ...    func.attr = 'decorated'
     ...    return func
     ...
     >>> @deco
     ... def f(): pass
     ...
     >>> f
     <function f at 0x402ef0d4>
     >>> f.attr
     'decorated'
     >>>

As a slightly more realistic example, the following decorator checks
that the supplied argument is an integer:

     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

An example in PEP 318(1) 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, ‘@A @B
@C(args)’ becomes:

     def f(): ...
     _deco = C(args)
     f = A(B(_deco(f)))

Getting this right can be slightly brain-bending, but it’s not too
difficult.

A small related change makes the ‘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.

也參考
......

PEP 318(2) - Decorators for Functions, Methods and Classes

     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.

‘https://wiki.python.org/moin/PythonDecoratorLibrary’

     该Wiki页面包含几个装饰器示例。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0318

   (2) https://www.python.org/dev/peps/pep-0318


File: python.info,  Node: PEP 322 反向迭代,  Next: PEP 324 新的子进程模块,  Prev: PEP 318 Decorators for Functions and Methods,  Up: Python 2 4 有什么新变化

1.14.6 PEP 322: 反向迭代
------------------------

A new built-in function, ‘reversed(seq)’, takes a sequence and returns
an iterator that loops over the elements of the sequence in reverse
order.

     >>> for i in reversed(xrange(1,4)):
     ...    print i
     ...
     3
     2
     1

Compared to extended slicing, such as ‘range(1,4)[::-1]’, *note
reversed(): 2c6. is easier to read, runs faster, and uses substantially
less memory.

Note that *note reversed(): 2c6. only accepts sequences, not arbitrary
iterators.  If you want to reverse an iterator, first convert it to a
list with *note list(): 1f8.

     >>> input = open('/etc/passwd', 'r')
     >>> for line in reversed(list(input)):
     ...   print line
     ...
     root:*:0:0:System Administrator:/var/root:/bin/tcsh
       ...

也參考
......

PEP 322(1) - 反向迭代

     由 Raymond Hettinger 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0322


File: python.info,  Node: PEP 324 新的子进程模块,  Next: PEP 327 十进制数据类型,  Prev: PEP 322 反向迭代,  Up: Python 2 4 有什么新变化

1.14.7 PEP 324: 新的子进程模块
------------------------------

The standard library provides a number of ways to execute a subprocess,
offering different features and different levels of complexity.
‘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 ‘popen2’ module offers
classes that can capture standard output and standard error from the
subprocess, but the naming is confusing.  The *note subprocess: f9.
module cleans this up, providing a unified interface that offers all the
features you might need.

Instead of ‘popen2’’s collection of classes, *note subprocess: f9.
contains a single class called ‘Popen’ whose constructor supports a
number of different keyword arguments.

     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):

`args' is commonly a sequence of strings that will be the arguments to
the program executed as the subprocess.  (If the `shell' argument is
true, `args' can be a string which will then be passed on to the shell
for interpretation, just as *note os.system(): e86. does.)

`stdin', `stdout', and `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 ‘subprocess.PIPE’ to create
a pipe between the subprocess and the parent.

The constructor has a number of handy options:

   * `close_fds' requests that all file descriptors be closed before
     running the subprocess.

   * `cwd' specifies the working directory in which the subprocess will
     be executed (defaulting to whatever the parent’s working directory
     is).

   * `env' is a dictionary specifying environment variables.

   * `preexec_fn' is a function that gets called before the child is
     started.

   * `universal_newlines' opens the child’s input and output using
     Python’s *note universal newlines: 6eb. feature.

Once you’ve created the ‘Popen’ instance, you can call its ‘wait()’
method to pause until the subprocess has exited, ‘poll()’ to check if
it’s exited without pausing, or ‘communicate(data)’ to send the string
`data' to the subprocess’s standard input.  ‘communicate(data)’ then
reads any data that the subprocess has sent to its standard output or
standard error, returning a tuple ‘(stdout_data, stderr_data)’.

‘call()’ is a shortcut that passes its arguments along to the ‘Popen’
constructor, waits for the command to complete, and returns the status
code of the subprocess.  It can serve as a safer analog to *note
os.system(): e86.:

     sts = subprocess.call(['dpkg', '-i', '/tmp/new-package.deb'])
     if sts == 0:
         # Success
         ...
     else:
         # dpkg returned an error
         ...

The command is invoked without use of the shell.  If you really do want
to use the shell, you can add ‘shell=True’ as a keyword argument and
provide a string instead of a sequence:

     sts = subprocess.call('dpkg -i /tmp/new-package.deb', shell=True)

The PEP takes various examples of shell and Python code and shows how
they’d be translated into Python code that uses *note subprocess: f9.
Reading this section of the PEP is highly recommended.

也參考
......

PEP 324(1) - 子进程 - 新的进程模块

     由 Peter Åstrand 在 Fredrik Lundh 等人的协助下撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0324


File: python.info,  Node: PEP 327 十进制数据类型,  Next: PEP 328 多行导入,  Prev: PEP 324 新的子进程模块,  Up: Python 2 4 有什么新变化

1.14.8 PEP 327: 十进制数据类型
------------------------------

Python has always supported floating-point (FP) numbers, based on the
underlying C ‘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 ‘Decimal’ type can
represent these fractions accurately, up to a user-specified precision
limit.

* Menu:

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


File: python.info,  Node: 为什么需要十进制？,  Next: Decimal 类型,  Up: PEP 327 十进制数据类型

1.14.8.1 为什么需要十进制？
...........................

The limitations arise from the representation used for floating-point
numbers.  FP numbers are made up of three components:

   * The sign, which is positive or negative.

   * The mantissa, which is a single-digit binary number followed by a
     fractional part.  For example, ‘1.01’ in base-2 notation is ‘1 +
     0/2 + 1/4’, or 1.25 in decimal notation.

   * The exponent, which tells where the decimal point is located in the
     number represented.

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 ‘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
‘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:

     >>> 1.1
     1.1000000000000001

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.

因此，创建了 ‘Decimal’ 类型。


File: python.info,  Node: Decimal 类型,  Next: Context 类型,  Prev: 为什么需要十进制？,  Up: PEP 327 十进制数据类型

1.14.8.2 ‘Decimal’ 类型
.......................

A new module, *note decimal: 35, was added to Python’s standard library.
It contains two classes, ‘Decimal’ and ‘Context’.  ‘Decimal’ instances
represent numbers, and ‘Context’ instances are used to wrap up various
settings such as the precision and default rounding mode.

‘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.  ‘Decimal’ instances can be created from integers or
strings:

     >>> import decimal
     >>> decimal.Decimal(1972)
     Decimal("1972")
     >>> decimal.Decimal("1.1")
     Decimal("1.1")

You can also provide tuples containing the sign, the mantissa
represented as a tuple of decimal digits, and the exponent:

     >>> decimal.Decimal((1, (1, 4, 7, 5), -2))
     Decimal("-14.75")

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 ‘Decimal’
constructor:

     >>> f = 1.1
     >>> decimal.Decimal(str(f))
     Decimal("1.1")
     >>> decimal.Decimal('%.12f' % f)
     Decimal("1.100000000000")

Once you have ‘Decimal’ instances, you can perform the usual
mathematical operations on them.  One limitation: exponentiation
requires an integer exponent:

     >>> 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)

You can combine ‘Decimal’ instances with integers, but not with
floating-point numbers:

     >>> 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.
     >>>

‘Decimal’ numbers can be used with the *note math: b1. and *note cmath:
18. 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 ‘Decimal’.

     >>> import math, cmath
     >>> d = decimal.Decimal('123456789012.345')
     >>> math.sqrt(d)
     351364.18288201344
     >>> cmath.sqrt(-d)
     351364.18288201344j

‘Decimal’ instances have a ‘sqrt()’ method that returns a ‘Decimal’, but
if you need other things such as trigonometric functions you’ll have to
implement them.

     >>> d.sqrt()
     Decimal("351364.1828820134592177245001")


File: python.info,  Node: Context 类型,  Prev: Decimal 类型,  Up: PEP 327 十进制数据类型

1.14.8.3 ‘Context’ 类型
.......................

Instances of the ‘Context’ class encapsulate several settings for
decimal operations:

   * ‘prec’ is the precision, the number of decimal places.

   * ‘rounding’ specifies the rounding mode.  The *note decimal: 35.
     module has constants for the various possibilities: ‘ROUND_DOWN’,
     ‘ROUND_CEILING’, ‘ROUND_HALF_EVEN’, and various others.

   * ‘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.

There’s a thread-local default context available by calling
‘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:

     >>> 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")

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:

     >>> 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")
     >>>

The ‘Context’ instance also has various methods for formatting numbers
such as ‘to_eng_string()’ and ‘to_sci_string()’.

For more information, see the documentation for the *note decimal: 35.
module, which includes a quick-start tutorial and a reference.

也參考
......

PEP 327(1) - 十进数据类型

     由 Facundo Batista 撰写，由Facundo Batista, Eric Price, Raymond
     Hettinger, Aahz 和 Tim Peters 实现。

‘http://www.lahey.com/float.htm’

     The article uses Fortran code to illustrate many of the problems
     that floating-point inaccuracy can cause.

‘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.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0327


File: python.info,  Node: PEP 328 多行导入,  Next: PEP 331 Locale-Independent Float/String Conversions,  Prev: PEP 327 十进制数据类型,  Up: Python 2 4 有什么新变化

1.14.9 PEP 328: 多行导入
------------------------

One language change is a small syntactic tweak aimed at making it easier
to import many names from a module.  In a ‘from module import names’
statement, `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:

     from SimpleXMLRPCServer import SimpleXMLRPCServer,\
                 SimpleXMLRPCRequestHandler,\
                 CGIXMLRPCRequestHandler,\
                 resolve_dotted_attribute

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:

     from SimpleXMLRPCServer import (SimpleXMLRPCServer,
                                     SimpleXMLRPCRequestHandler,
                                     CGIXMLRPCRequestHandler,
                                     resolve_dotted_attribute)

The PEP also proposes that all *note import: ce7. statements be absolute
imports, with a leading ‘.’ 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.

也參考
......

PEP 328(1) - 导入：多行和绝对/相对导入

     由 Aahz 撰写，多行导入由 Dima Dorfman 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0328


File: python.info,  Node: PEP 331 Locale-Independent Float/String Conversions,  Next: 其他语言特性修改<13>,  Prev: PEP 328 多行导入,  Up: Python 2 4 有什么新变化

1.14.10 PEP 331: Locale-Independent Float/String Conversions
------------------------------------------------------------

The *note locale: a9. 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 ‘'C'’ locale.  Often
this was because the code was using the C library’s ‘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:

   * ‘PyOS_ascii_strtod(str, ptr)’ and ‘PyOS_ascii_atof(str, ptr)’ both
     convert a string to a C ‘double’.

   * ‘PyOS_ascii_formatd(buffer, buf_len, format, d)’ converts a
     ‘double’ to an ASCII string.

The code for these functions came from the GLib library
(‘https://developer.gnome.org/glib/stable/’), whose developers kindly
relicensed the relevant functions and donated them to the Python
Software Foundation.  The *note locale: a9. module can now change the
numeric locale, letting extensions such as GTK+ produce the correct
results.

也參考
......

PEP 331(1) - Locale-Independent Float/String Conversions

     由Christian R. Reis撰写，由 Gustavo Carneiro 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0331


File: python.info,  Node: 其他语言特性修改<13>,  Next: 新增，改进和弃用的模块<3>,  Prev: PEP 331 Locale-Independent Float/String Conversions,  Up: Python 2 4 有什么新变化

1.14.11 其他语言特性修改
------------------------

Here are all of the changes that Python 2.4 makes to the core Python
language.

   * Decorators for functions and methods were added ( PEP 318(1)).

   * Built-in *note set(): 1f6. and *note frozenset(): 1f7. types were
     added ( PEP 218(2)).  Other new built-ins include the
     ‘reversed(seq)’ function ( PEP 322(3)).

   * Generator expressions were added ( PEP 289(4)).

   * Certain numeric expressions no longer return values restricted to
     32 or 64 bits ( PEP 237(5)).

   * You can now put parentheses around the list of names in a ‘from
     module import names’ statement ( PEP 328(6)).

   * The *note dict.update(): e8e. method now accepts the same argument
     forms as the *note dict: 164. constructor.  This includes any
     mapping, any iterable of key/value pairs, and keyword arguments.
     (Contributed by Raymond Hettinger.)

   * The string methods ‘ljust()’, ‘rjust()’, and ‘center()’ now take an
     optional argument for specifying a fill character other than a
     space.  (Contributed by Raymond Hettinger.)

   * Strings also gained an ‘rsplit()’ method that works like the
     ‘split()’ method but splits from the end of the string.
     (Contributed by Sean Reifschneider.)

          >>> 'www.python.org'.split('.', 1)
          ['www', 'python.org']
          'www.python.org'.rsplit('.', 1)
          ['www.python', 'org']

   * Three keyword parameters, `cmp', `key', and `reverse', were added
     to the ‘sort()’ method of lists.  These parameters make some common
     usages of ‘sort()’ simpler.  All of these parameters are optional.

     For the `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 ‘sort()’.

     `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:

          >>> 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']

     The last example, which uses the `cmp' parameter, is the old way to
     perform a case-insensitive sort.  It works but is slower than using
     a `key' parameter.  Using `key' calls ‘lower()’ method once for
     each element in the list while using `cmp' will call it twice for
     each comparison, so using `key' saves on invocations of the
     ‘lower()’ method.

     For simple key functions and comparison functions, it is often
     possible to avoid a *note lambda: cf9. expression by using an
     unbound method instead.  For example, the above case-insensitive
     sort is best written as:

          >>> L.sort(key=str.lower)
          >>> L
          ['A', 'b', 'c', 'D']

     Finally, the `reverse' parameter takes a Boolean value.  If the
     value is true, the list will be sorted into reverse order.  Instead
     of ‘L.sort(); L.reverse()’, you can now write
     ‘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 ‘sort()’ contributed by Raymond Hettinger.)

   * There is a new built-in function ‘sorted(iterable)’ that works like
     the in-place *note list.sort(): 547. method but can be used in
     expressions.  The differences are:

   * the input may be any iterable;

   * a newly formed copy is sorted, leaving the original intact; and

   * the expression returns the new sorted copy

          >>> 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

     （由 Raymond Hettinger 贡献。）

   * Integer operations will no longer trigger an ‘OverflowWarning’.
     The ‘OverflowWarning’ warning will disappear in Python 2.5.

   * The interpreter gained a new switch, *note -m: 443, that takes a
     name, searches for the corresponding module on ‘sys.path’, and runs
     the module as a script.  For example, you can now run the Python
     profiler with ‘python -m profile’.  (Contributed by Nick Coghlan.)

   * The ‘eval(expr, globals, locals)’ and ‘execfile(filename, globals,
     locals)’ functions and the ‘exec’ statement now accept any mapping
     type for the `locals' parameter.  Previously this had to be a
     regular Python dictionary.  (Contributed by Raymond Hettinger.)

   * The *note zip(): cfc. built-in function and ‘itertools.izip()’ now
     return an empty list if called with no arguments.  Previously they
     raised a *note TypeError: 1fe. exception.  This makes them more
     suitable for use with variable length argument lists:

          >>> def transpose(array):
          ...    return zip(*array)
          ...
          >>> transpose([(1,2,3), (4,5,6)])
          [(1, 4), (2, 5), (3, 6)]
          >>> transpose([])
          []

     （由 Raymond Hettinger 贡献。）

   * Encountering a failure while importing a module no longer leaves a
     partially-initialized module object in ‘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.)

   * *note None: 203. is now a constant; code that binds a new value to
     the name ‘None’ is now a syntax error.  (Contributed by Raymond
     Hettinger.)

* Menu:

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

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0318

   (2) https://www.python.org/dev/peps/pep-0218

   (3) https://www.python.org/dev/peps/pep-0322

   (4) https://www.python.org/dev/peps/pep-0289

   (5) https://www.python.org/dev/peps/pep-0237

   (6) https://www.python.org/dev/peps/pep-0328


File: python.info,  Node: 性能优化<12>,  Up: 其他语言特性修改<13>

1.14.11.1 性能优化
..................

   * 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 ‘keys()’,
     ‘values()’, ‘items()’, ‘iterkeys()’, ‘itervalues()’, and
     ‘iteritems()’.  (Contributed by Raymond Hettinger.)

   * 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 ‘realloc()’.  List comprehensions also
     benefit.  ‘list.extend()’ was also optimized and no longer converts
     its argument into a temporary list before extending the base list.
     (Contributed by Raymond Hettinger.)

   * *note list(): 1f8, *note tuple(): 1a2, *note map(): cf7, *note
     filter(): cf8, and *note zip(): cfc. now run several times faster
     with non-sequence arguments that supply a *note __len__(): e90.
     method.  (Contributed by Raymond Hettinger.)

   * The methods ‘list.__getitem__()’, ‘dict.__getitem__()’, and
     ‘dict.__contains__()’ are now implemented as ‘method_descriptor’
     objects rather than ‘wrapper_descriptor’ objects.  This form of
     access doubles their performance and makes them more suitable for
     use as arguments to functionals: ‘map(mydict.__getitem__,
     keylist)’.  (Contributed by Raymond Hettinger.)

   * Added a new opcode, ‘LIST_APPEND’, that simplifies the generated
     bytecode for list comprehensions and speeds them up by about a
     third.  (Contributed by Raymond Hettinger.)

   * The peephole bytecode optimizer has been improved to produce
     shorter, faster bytecode; remarkably, the resulting bytecode is
     more readable.  (Enhanced by Raymond Hettinger.)

   * String concatenations in statements of the form ‘s = s + "abc"’ and
     ‘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 ‘join()’ method of strings is still recommended when you want
     to efficiently glue a large number of strings together.
     (Contributed by Armin Rigo.)

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.)


File: python.info,  Node: 新增，改进和弃用的模块<3>,  Next: 构建和 C API 的改变<11>,  Prev: 其他语言特性修改<13>,  Up: Python 2 4 有什么新变化

1.14.12 新增，改进和弃用的模块
------------------------------

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 ‘Misc/NEWS’ file in
the source tree for a more complete list of changes, or look through the
CVS logs for all the details.

   * The *note asyncore: a. module’s ‘loop()’ function now has a `count'
     parameter that lets you perform a limited number of passes through
     the polling loop.  The default is still to loop forever.

   * The *note base64: d. module now has more complete RFC 3548(1)
     support for Base64, Base32, and Base16 encoding and decoding,
     including optional case folding and optional alternative alphabets.
     (Contributed by Barry Warsaw.)

   * The *note bisect: 11. module now has an underlying C implementation
     for improved performance.  (Contributed by Dmitry Vasiliev.)

   * 由 Hye-Shik Chang 维护的东亚编解码器的 CJKCodecs 集合已集成到 2.4 中
     。新的编码为：

   * 汉语（大陆）: gb2312, gbk, gb18030, big5hkscs, hz

   * 汉语（台湾）: big5, cp950

   * 
     日语: 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

   * 韩语: cp949, euc-kr, johab, iso-2022-kr

   * 添加了其他一些新的编码：HP Roman8, ISO_8859-11, ISO_8859-16,
     PCTP-154 和 TIS-620

   * The UTF-8 and UTF-16 codecs now cope better with receiving partial
     input.  Previously the ‘StreamReader’ class would try to read more
     data, making it impossible to resume decoding from the stream.  The
     ‘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.)

   * There is a new *note collections: 1d. module for various
     specialized collection datatypes.  Currently it contains just one
     type, ‘deque’, a double-ended queue that supports efficiently
     adding and removing elements from either end:

          >>> 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

     Several modules, such as the ‘Queue’ and *note threading: 10b.
     modules, now take advantage of *note collections.deque: 62a. for
     improved performance.  (Contributed by Raymond Hettinger.)

   * The ‘ConfigParser’ classes have been enhanced slightly.  The
     ‘read()’ method now returns a list of the files that were
     successfully parsed, and the *note set(): 1f6. method raises *note
     TypeError: 1fe. if passed a `value' argument that isn’t a string.
     (Contributed by John Belmonte and David Goodger.)

   * The *note curses: 2b. module now supports the ncurses extension
     ‘use_default_colors()’.  On platforms where the terminal supports
     transparency, this makes it possible to use a transparent
     background.  (Contributed by Jörg Lehmann.)

   * The *note difflib: 36. module now includes an ‘HtmlDiff’ class that
     creates an HTML table showing a side by side comparison of two
     versions of a text.  (Contributed by Dan Gass.)

   * The *note email: 67. 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
     ‘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
     ‘defect’ attribute of the message.  (Developed by Anthony Baxter,
     Barry Warsaw, Thomas Wouters, and others.)

   * The *note heapq: 8d. 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 ‘nlargest()’ and ‘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.)

   * The ‘httplib’ module now contains constants for HTTP status codes
     defined in various HTTP-related RFC documents.  Constants have
     names such as ‘OK’, ‘CREATED’, ‘CONTINUE’, and ‘MOVED_PERMANENTLY’;
     use pydoc to get a full list.  (Contributed by Andrew Eland.)

   * The *note imaplib: 97. module now supports IMAP’s THREAD command
     (contributed by Yves Dionne) and new ‘deleteacl()’ and ‘myrights()’
     methods (contributed by Arnaud Mazin).

   * The *note itertools: a3. module gained a ‘groupby(iterable[,
     *func*])’ function.  `iterable' is something that can be iterated
     over to return a stream of elements, and the optional `func'
     parameter is a function that takes an element and returns a key
     value; if omitted, the key is simply the element itself.
     ‘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 `key' function simply
     returns whether a number is even or odd, so the result of
     ‘groupby()’ is to return consecutive runs of odd or even numbers.

          >>> 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]
          >>>

     ‘groupby()’ is typically used with sorted input.  The logic for
     ‘groupby()’ is similar to the Unix ‘uniq’ filter which makes it
     handy for eliminating, counting, or identifying duplicate elements:

          >>> 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)]

     （由 Hye-Shik Chang 贡献。）

   * *note itertools: a3. also gained a function named ‘tee(iterator,
     N)’ that returns `N' independent iterators that replicate
     `iterator'.  If `N' is omitted, the default is 2.

          >>> 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]

     Note that ‘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 *note list():
     1f8. instead.  When the iterators track closely with one another,
     ‘tee()’ is ideal.  Possible applications include bookmarking,
     windowing, or lookahead iterators.  (Contributed by Raymond
     Hettinger.)

   * A number of functions were added to the *note locale: a9. module,
     such as ‘bind_textdomain_codeset()’ to specify a particular
     encoding and a family of ‘l*gettext()’ functions that return
     messages in the chosen encoding.  (Contributed by Gustavo
     Niemeyer.)

   * Some keyword arguments were added to the *note logging: aa.
     package’s ‘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:

          import logging
          logging.basicConfig(filename='/var/log/application.log',
              level=0,  # Log all messages
              format='%(levelname):%(process):%(thread):%(message)')

     Other additions to the *note logging: aa. package include a
     ‘log(level, msg)’ convenience method, as well as a
     ‘TimedRotatingFileHandler’ class that rotates its log files at a
     timed interval.  The module already had ‘RotatingFileHandler’,
     which rotated logs once the file exceeded a certain size.  Both
     classes derive from a new ‘BaseRotatingHandler’ class that can be
     used to implement other rotating handlers.

     （更改由 Vinay Sajip 实现。）

   * The *note marshal: b0. 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 ‘.pyc’ files
     significantly smaller.  (Contributed by Martin von Löwis.)

   * The *note nntplib: c0. module’s ‘NNTP’ class gained ‘description()’
     and ‘descriptions()’ methods to retrieve newsgroup descriptions for
     a single group or for a range of groups.  (Contributed by Jürgen A.
     Erhard.)

   * Two new functions were added to the *note operator: c2. module,
     ‘attrgetter(attr)’ and ‘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 *note map(): cf7. or *note sorted(): 546.  For
     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)]

     （由 Raymond Hettinger 贡献。）

   * The *note optparse: c3. module was updated in various ways.  The
     module now passes its messages through *note gettext.gettext():
     e92, making it possible to internationalize Optik’s help and error
     messages.  Help messages for options can now include the string
     ‘'%default'’, which will be replaced by the option’s default value.
     (Contributed by Greg Ward.)

   * The long-term plan is to deprecate the ‘rfc822’ module in some
     future Python release in favor of the *note email: 67. package.  To
     this end, the ‘email.Utils.formatdate()’ function has been changed
     to make it usable as a replacement for ‘rfc822.formatdate()’.  You
     may want to write new e-mail processing code with this in mind.
     (Change implemented by Anthony Baxter.)

   * A new ‘urandom(n)’ function was added to the *note os: c4. module,
     returning a string containing `n' bytes of random data.  This
     function provides access to platform-specific sources of randomness
     such as ‘/dev/urandom’ on Linux or the Windows CryptoAPI.
     (Contributed by Trevor Perrin.)

   * Another new function: ‘os.path.lexists(path)’ returns true if the
     file specified by `path' exists, whether or not it’s a symbolic
     link.  This differs from the existing ‘os.path.exists(path)’
     function, which returns false if `path' is a symlink that points to
     a destination that doesn’t exist.  (Contributed by Beni
     Cherniavsky.)

   * A new ‘getsid()’ function was added to the *note posix: d1. module
     that underlies the *note os: c4. module.  (Contributed by J.
     Raynor.)

   * The *note poplib: d0. module now supports POP over SSL.
     (Contributed by Hector Urtubia.)

   * The *note profile: d3. module can now profile C extension
     functions.  (Contributed by Nick Bastin.)

   * The *note random: dc. module has a new method called
     ‘getrandbits(N)’ that returns a long integer `N' bits in length.
     The existing ‘randrange()’ method now uses ‘getrandbits()’ where
     appropriate, making generation of arbitrarily large random numbers
     more efficient.  (Contributed by Raymond Hettinger.)

   * The regular expression language accepted by the *note re: dd.
     module was extended with simple conditional expressions, written as
     ‘(?(group)A|B)’.  `group' is either a numeric group ID or a group
     name defined with ‘(?P<group>...)’ earlier in the expression.  If
     the specified group matched, the regular expression pattern `A'
     will be tested against the string; if the group didn’t match, the
     pattern `B' will be used instead.  (Contributed by Gustavo
     Niemeyer.)

   * The *note re: dd. 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 ‘a’
     characters against the expression ‘(a|b)+’, one stack frame was
     consumed per character.  Python 2.3 tried to check for stack
     overflow and raise a *note RuntimeError: 3dc. 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.

   * The *note signal: ea. module now performs tighter error-checking on
     the parameters to the *note signal.signal(): b58. function.  For
     example, you can’t set a handler on the ‘SIGKILL’ signal; previous
     versions of Python would quietly accept this, but 2.4 will raise a
     *note RuntimeError: 3dc. exception.

   * Two new functions were added to the *note socket: ef. module.
     ‘socketpair()’ returns a pair of connected sockets and
     ‘getservbyport(port)’ looks up the service name for a given port
     number.  (Contributed by Dave Cole and Barry Warsaw.)

   * The ‘sys.exitfunc()’ function has been deprecated.  Code should be
     using the existing *note atexit: b. module, which correctly handles
     calling multiple exit functions.  Eventually ‘sys.exitfunc()’ will
     become a purely internal interface, accessed only by *note atexit:
     b.

   * The *note tarfile: 101. module now generates GNU-format tar files
     by default.  (Contributed by Lars Gustäbel.)

   * The *note threading: 10b. module now has an elegantly simple way to
     support thread-local data.  The module contains a ‘local’ class
     whose attribute values are local to different threads.

          import threading

          data = threading.local()
          data.number = 42
          data.url = ('www.python.org', 80)

     Other threads can assign and retrieve their own values for the
     ‘number’ and ‘url’ attributes.  You can subclass ‘local’ to
     initialize attributes or to add methods.  (Contributed by Jim
     Fulton.)

   * The *note timeit: 10d. module now automatically disables periodic
     garbage collection during the timing loop.  This change makes
     consecutive timings more comparable.  (Contributed by Raymond
     Hettinger.)

   * The *note weakref: 131. 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.)

   * The ‘xmlrpclib’ module now supports a multi-call extension for
     transmitting multiple XML-RPC calls in a single HTTP operation.
     (Contributed by Brian Quinlan.)

   * ‘mpz’, ‘rotor’ 和 ‘xreadlines’ 模块已被移除。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc3548.html


File: python.info,  Node: cookielib,  Next: doctest<3>,  Up: 新增，改进和弃用的模块<3>

1.14.12.1 cookielib
...................

The ‘cookielib’ library supports client-side handling for HTTP cookies,
mirroring the ‘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.

‘urllib2’ has been changed to interact with ‘cookielib’:
‘HTTPCookieProcessor’ manages a cookie jar that is used when accessing
URLs.

该模块由 John J. Lee 贡献。


File: python.info,  Node: doctest<3>,  Prev: cookielib,  Up: 新增，改进和弃用的模块<3>

1.14.12.2 doctest
.................

The *note doctest: 66. module underwent considerable refactoring thanks
to Edward Loper and Tim Peters.  Testing can still be as simple as
running *note doctest.testmod(): e95, but the refactorings allow
customizing the module’s operation in various ways

The new ‘DocTestFinder’ class extracts the tests from a given object’s
docstrings:

     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)

The new ‘DocTestRunner’ class then runs individual tests and can produce
a summary of the results:

     runner = doctest.DocTestRunner()
     for t in tests:
         tried, failed = runner.run(t)

     runner.summarize(verbose=1)

The above example produces the following output:

     1 items passed all tests:
        2 tests in f
     2 tests in 1 items.
     2 passed and 0 failed.
     Test passed.

‘DocTestRunner’ uses an instance of the ‘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 ‘OutputChecker’.

The default output checker provides a number of handy features.  For
example, with the *note doctest.ELLIPSIS: e96. option flag, an ellipsis
(‘...’) in the expected output matches any substring, making it easier
to accommodate outputs that vary in minor ways:

     def o (n):
         """>>> o(1)
     <__main__.C instance at 0x...>
     >>>
     """

Another special string, ‘<BLANKLINE>’, matches a blank line:

     def p (n):
         """>>> p(1)
     <BLANKLINE>
     >>>
     """

Another new capability is producing a diff-style display of the output
by specifying the *note doctest.REPORT_UDIFF: e97. (unified diffs),
*note doctest.REPORT_CDIFF: e98. (context diffs), or *note
doctest.REPORT_NDIFF: e99. (delta-style) option flags.  For 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

Running the above function’s tests with *note doctest.REPORT_UDIFF: e97.
specified, you get the following output:

     **********************************************************************
     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
     **********************************************************************


File: python.info,  Node: 构建和 C API 的改变<11>,  Next: 移植到 Python 2 4,  Prev: 新增，改进和弃用的模块<3>,  Up: Python 2 4 有什么新变化

1.14.13 构建和 C API 的改变
---------------------------

Some of the changes to Python’s build process and to the C API are:

   * Three new convenience macros were added for common return values
     from extension functions: *note Py_RETURN_NONE: e9b, *note
     Py_RETURN_TRUE: e9c, and *note Py_RETURN_FALSE: e9d.  (Contributed
     by Brett Cannon.)

   * Another new macro, ‘Py_CLEAR(obj)’, decreases the reference count
     of `obj' and sets `obj' to the null pointer.  (Contributed by Jim
     Fulton.)

   * A new function, ‘PyTuple_Pack(N, obj1, obj2, ..., objN)’,
     constructs tuples from a variable length argument list of Python
     objects.  (Contributed by Raymond Hettinger.)

   * A new function, ‘PyDict_Contains(d, k)’, implements fast dictionary
     lookups without masking exceptions raised during the look-up
     process.  (Contributed by Raymond Hettinger.)

   * The ‘Py_IS_NAN(X)’ macro returns 1 if its float or double argument
     `X' is a NaN. (Contributed by Tim Peters.)

   * C code can avoid unnecessary locking by using the new *note
     PyEval_ThreadsInitialized(): 20d. function to tell if any thread
     operations have been performed.  If this function returns false, no
     lock operations are needed.  (Contributed by Nick Coghlan.)

   * A new function, *note PyArg_VaParseTupleAndKeywords(): e9e, is the
     same as *note PyArg_ParseTupleAndKeywords(): 6c1. but takes a
     ‘va_list’ instead of a number of arguments.  (Contributed by Greg
     Chapman.)

   * A new method flag, ‘METH_COEXISTS’, allows a function defined in
     slots to co-exist with a *note PyCFunction: e9f. having the same
     name.  This can halve the access time for a method such as
     ‘set.__contains__()’.  (Contributed by Raymond Hettinger.)

   * Python can now be built with additional profiling for the
     interpreter itself, intended as an aid to people developing the
     Python core.  Providing ‘--enable-profiling’ to the ‘configure’
     script will let you profile the interpreter with ‘gprof’, and
     providing the ‘--with-tsc’ switch enables profiling using the
     Pentium’s Time-Stamp-Counter register.  Note that the ‘--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.)

   * The ‘tracebackobject’ type has been renamed to ‘PyTracebackObject’.

* Menu:

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


File: python.info,  Node: Port-Specific Changes<2>,  Up: 构建和 C API 的改变<11>

1.14.13.1 Port-Specific Changes
...............................

   * The Windows port now builds under MSVC++ 7.1 as well as version 6.
     (Contributed by Martin von Löwis.)


File: python.info,  Node: 移植到 Python 2 4,  Next: 致谢<4>,  Prev: 构建和 C API 的改变<11>,  Up: Python 2 4 有什么新变化

1.14.14 移植到 Python 2.4
-------------------------

This section lists previously described changes that may require changes
to your code:

   * Left shifts and hexadecimal/octal constants that are too large no
     longer trigger a *note FutureWarning: 435. and return a value
     limited to 32 or 64 bits; instead they return a long integer.

   * Integer operations will no longer trigger an ‘OverflowWarning’.
     The ‘OverflowWarning’ warning will disappear in Python 2.5.

   * The *note zip(): cfc. built-in function and ‘itertools.izip()’ now
     return an empty list instead of raising a *note TypeError: 1fe.
     exception if called with no arguments.

   * You can no longer compare the ‘date’ and *note datetime: 19f.
     instances provided by the *note datetime: 30. module.  Two
     instances of different classes will now always be unequal, and
     relative comparisons (‘<’, ‘>’) will raise a *note TypeError: 1fe.

   * ‘dircache.listdir()’ now passes exceptions to the caller instead of
     returning empty lists.

   * ‘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.

   * *note fcntl.ioctl(): ea2. now warns if the `mutate' argument is
     omitted and relevant.

   * The *note tarfile: 101. module now generates GNU-format tar files
     by default.

   * Encountering a failure while importing a module no longer leaves a
     partially-initialized module object in ‘sys.modules’.

   * *note None: 203. is now a constant; code that binds a new value to
     the name ‘None’ is now a syntax error.

   * The ‘signals.signal()’ function now raises a *note RuntimeError:
     3dc. exception for certain illegal values; previously these errors
     would pass silently.  For example, you can no longer set a handler
     on the ‘SIGKILL’ signal.


File: python.info,  Node: 致谢<4>,  Prev: 移植到 Python 2 4,  Up: Python 2 4 有什么新变化

1.14.15 致谢
------------

作者感谢以下人员对本文各种草稿给予的建议，更正和协助：Koray Can,
Hye-Shik Chang, Michael Dyck, Raymond Hettinger, Brian Hurt, Hamish
Lawson, Fredrik Lundh, Sean Reifschneider, Sadruddin Rejeb.


File: python.info,  Node: Python 2 3 有什么新变化,  Next: Python 2 2 有什么新变化,  Prev: Python 2 4 有什么新变化,  Up: Python 有什麼新功能？

1.15 Python 2.3 有什么新变化
============================


作者: A.M. Kuchling

本文介绍了 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 *note sum(): 316. and *note enumerate(): ea7.  The
*note in: 179. operator can now be used for substring searches (e.g.
‘"ab" in "abc"’ returns *note True: 593.).

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.

* Menu:

* PEP 218; A Standard Set Datatype: PEP 218 A Standard Set Datatype.
* PEP 255; Simple Generators: PEP 255 Simple Generators.
* PEP 263; Source Code Encodings: PEP 263 Source Code Encodings.
* PEP 273; 从ZIP压缩包导入模块: PEP 273 从ZIP压缩包导入模块.
* PEP 277; Unicode file name support for Windows NT: PEP 277 Unicode file name support for Windows NT.
* 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; New Import Hooks: PEP 302 New Import Hooks.
* 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>.
* Other Changes and Fixes: Other Changes and Fixes<2>.
* 移植到 Python 2.3: 移植到 Python 2 3.
* 致谢: 致谢<5>.


File: python.info,  Node: PEP 218 A Standard Set Datatype,  Next: PEP 255 Simple Generators,  Up: Python 2 3 有什么新变化

1.15.1 PEP 218: A Standard Set Datatype
---------------------------------------

The new ‘sets’ module contains an implementation of a set datatype.  The
‘Set’ class is for mutable sets, sets that can have members added and
removed.  The ‘ImmutableSet’ class is for sets that can’t be modified,
and instances of ‘ImmutableSet’ can therefore be used as dictionary
keys.  Sets are built on top of dictionaries, so the elements within a
set must be hashable.

这是一个简单的示例：

     >>> 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])
     >>>

The union and intersection of sets can be computed with the ‘union()’
and ‘intersection()’ methods; an alternative notation uses the bitwise
operators ‘&’ and ‘|’.  Mutable sets also have in-place versions of
these methods, ‘union_update()’ and ‘intersection_update()’.

     >>> 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])
     >>>

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 (‘^’), and an in-place version with the ungainly name
‘symmetric_difference_update()’.

     >>> 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])
     >>>

There are also ‘issubset()’ and ‘issuperset()’ methods for checking
whether one set is a subset or superset of another:

     >>> S1 = sets.Set([1,2,3])
     >>> S2 = sets.Set([2,3])
     >>> S2.issubset(S1)
     True
     >>> S1.issubset(S2)
     False
     >>> S1.issuperset(S2)
     True
     >>>

也參考
......

PEP 218(1) - 添加内置Set对象类型

     PEP 由 Greg V. Wilson 撰写 ; 由 Greg V. Wilson, Alex Martelli 和
     GvR 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0218


File: python.info,  Node: PEP 255 Simple Generators,  Next: PEP 263 Source Code Encodings,  Prev: PEP 218 A Standard Set Datatype,  Up: Python 2 3 有什么新变化

1.15.2 PEP 255: Simple Generators
---------------------------------

In Python 2.2, generators were added as an optional feature, to be
enabled by a ‘from __future__ import generators’ directive.  In 2.3
generators no longer need to be specially enabled, and are now always
present; this means that *note yield: 2c7. 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 *note return: 2c8.
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.

Here’s the simplest example of a generator function:

     def generate_ints(N):
         for i in range(N):
             yield i

A new keyword, *note yield: 2c7, was introduced for generators.  Any
function containing a ‘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 *note yield: 2c7. statement, the generator
outputs the value of ‘i’, similar to a *note return: 2c8. statement.
The big difference between ‘yield’ and a ‘return’ statement is that on
reaching a ‘yield’ the generator’s state of execution is suspended and
local variables are preserved.  On the next call to the generator’s
‘.next()’ method, the function will resume executing immediately after
the ‘yield’ statement.  (For complicated reasons, the ‘yield’ statement
isn’t allowed inside the *note try: e37. block of a ‘try’...‘finally’
statement; read PEP 255(1) for a full explanation of the interaction
between ‘yield’ and exceptions.)

Here’s a sample usage of the ‘generate_ints()’ generator:

     >>> 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

You could equally write ‘for i in generate_ints(5)’, or ‘a,b,c =
generate_ints(3)’.

Inside a generator function, the *note return: 2c8. 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.
‘return’ with a value, such as ‘return 5’, is a syntax error inside a
generator function.  The end of the generator’s results can also be
indicated by raising *note StopIteration: 581. 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 ‘self.count’ to 0, and having the *note next(): 775. method
increment ‘self.count’ and return it.  However, for a moderately
complicated generator, writing a corresponding class would be much
messier.  ‘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.

     # 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

Two other examples in ‘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 (‘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
‘https://www.cs.arizona.edu/icon/docs/ipd266.htm’ gives an idea of what
this looks like:

     sentence := "Store it in the neighboring harbor"
     if (i := find("or", sentence)) > 5 then write(i)

In Icon the ‘find()’ function returns the indexes at which the substring
"or" is found: 3, 23, 33.  In the *note if: eab. statement, ‘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.

也參考
......

PEP 255(2) - 简单生成器

     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.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0255

   (2) https://www.python.org/dev/peps/pep-0255


File: python.info,  Node: PEP 263 Source Code Encodings,  Next: PEP 273 从ZIP压缩包导入模块,  Prev: PEP 255 Simple Generators,  Up: Python 2 3 有什么新变化

1.15.3 PEP 263: Source Code Encodings
-------------------------------------

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:

     #!/usr/bin/env python
     # -*- coding: UTF-8 -*-

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 *note
DeprecationWarning: 15a. 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.

也參考
......

PEP 263(1) - Defining Python Source Code Encodings

     由 Marc-André Lemburg 和 Martin von Löwis 撰写 ; 由 Suzuki Hisao 和
     Martin von Löwis 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0263


File: python.info,  Node: PEP 273 从ZIP压缩包导入模块,  Next: PEP 277 Unicode file name support for Windows NT,  Prev: PEP 263 Source Code Encodings,  Up: Python 2 3 有什么新变化

1.15.4 PEP 273: 从ZIP压缩包导入模块
-----------------------------------

The new *note zipimport: 14c. 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 ‘sys.path’.  For 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'
     >>>

An entry in ‘sys.path’ can now be the filename of a ZIP archive.  The
ZIP archive can contain any kind of files, but only files named ‘*.py’,
‘*.pyc’, or ‘*.pyo’ can be imported.  If an archive only contains ‘*.py’
files, Python will not attempt to modify the archive by adding the
corresponding ‘*.pyc’ file, meaning that if a ZIP archive doesn’t
contain ‘*.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 ‘/tmp/example.zip/lib/’ would only
import from the ‘lib/’ subdirectory within the archive.

也參考
......

PEP 273(1) -  从ZIP压缩包导入模块

     Written by James C. Ahlstrom, who also provided an implementation.
     Python 2.3 follows the specification in PEP 273(2), but uses an
     implementation written by Just van Rossum that uses the import
     hooks described in PEP 302(3).  See section *note PEP 302; New
     Import Hooks: eaf. for a description of the new import hooks.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0273

   (2) https://www.python.org/dev/peps/pep-0273

   (3) https://www.python.org/dev/peps/pep-0302


File: python.info,  Node: PEP 277 Unicode file name support for Windows NT,  Next: PEP 278 通用换行支持,  Prev: PEP 273 从ZIP压缩包导入模块,  Up: Python 2 3 有什么新变化

1.15.5 PEP 277: Unicode file name support for Windows NT
--------------------------------------------------------

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 *note open(): 16f. built-in function.  If a
Unicode string is passed to *note os.listdir(): b1c, Python now returns
a list of Unicode strings.  A new function, ‘os.getcwdu()’, returns the
current directory as a Unicode string.

Byte strings still work as file names, and on Windows Python will
transparently convert them to Unicode using the ‘mbcs’ encoding.

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
*note UnicodeError: d03. to be raised.  Applications can test whether
arbitrary Unicode strings are supported as file names by checking *note
os.path.supports_unicode_filenames: eb1, a Boolean value.

Under MacOS, *note os.listdir(): b1c. may now return Unicode filenames.

也參考
......

PEP 277(1) - Unicode file name support for Windows NT

     由 Neil Hodgson 撰写 ; 由 Neil Hodgson, Martin von Löwis 和 Mark
     Hammond 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0277


File: python.info,  Node: PEP 278 通用换行支持,  Next: PEP 279 enumerate,  Prev: PEP 277 Unicode file name support for Windows NT,  Up: Python 2 3 有什么新变化

1.15.6 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 ‘'U'’ or ‘'rU'’ will open a file for reading in *note
universal newlines: 6eb. mode.  All three line ending conventions will
be translated to a ‘'\n'’ in the strings returned by the various file
methods such as ‘read()’ and *note readline(): de.

Universal newline support is also used when importing modules and when
executing a file with the ‘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
‘--without-universal-newlines’ switch when running Python’s ‘configure’
script.

也參考
......

PEP 278(1) - 通用换行支持

     由 Jack Jansen 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0278


File: python.info,  Node: PEP 279 enumerate,  Next: PEP 282 logging 包,  Prev: PEP 278 通用换行支持,  Up: Python 2 3 有什么新变化

1.15.7 PEP 279: enumerate()
---------------------------

A new built-in function, *note enumerate(): ea7, will make certain loops
a bit clearer.  ‘enumerate(thing)’, where `thing' is either an iterator
or a sequence, returns an iterator that will return ‘(0, thing[0])’,
‘(1, thing[1])’, ‘(2, thing[2])’, and so forth.

A common idiom to change every element of a list looks like this:

     for i in range(len(L)):
         item = L[i]
         # ... compute some result based on item ...
         L[i] = result

可以使用 *note enumerate(): ea7. 重写为：

     for i, item in enumerate(L):
         # ... compute some result based on item ...
         L[i] = result

也參考
......

PEP 279(1) - 内置函数 enumerate()

     由 Raymond D. Hettinger 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0279


File: python.info,  Node: PEP 282 logging 包,  Next: PEP 285 布尔类型,  Prev: PEP 279 enumerate,  Up: Python 2 3 有什么新变化

1.15.8 PEP 282: logging 包
--------------------------

A standard package for writing logs, *note logging: aa, 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 ‘Logger’ class is the primary class.  Most application code will
deal with one or more ‘Logger’ objects, each one used by a particular
subsystem of the application.  Each ‘Logger’ is identified by a name,
and names are organized into a hierarchy using ‘.’ as the component
separator.  For example, you might have ‘Logger’ instances named
‘server’, ‘server.auth’ and ‘server.network’.  The latter two instances
are below ‘server’ in the hierarchy.  This means that if you turn up the
verbosity for ‘server’ or direct ‘server’ messages to a different
handler, the changes will also apply to records logged to ‘server.auth’
and ‘server.network’.  There’s also a root ‘Logger’ that’s the parent of
all other loggers.

For simple uses, the *note logging: aa. package contains some
convenience functions that always use the root log:

     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')

This produces the following output:

     WARNING:root:Warning:config file server.conf not found
     ERROR:root:Error occurred
     CRITICAL:root:Critical error -- shutting down

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
‘setLevel()’ method on the root logger.

Notice the ‘warning()’ call’s use of string formatting operators; all of
the functions for logging messages take the arguments ‘(msg, arg1, arg2,
...)’ and log the string resulting from ‘msg % (arg1, arg2, ...)’.

There’s also an ‘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 `exc_info'.

     def f():
         try:    1/0
         except: logging.exception('Problem recorded')

     f()

This produces the following output:

     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

Slightly more advanced programs will use a logger other than the root
logger.  The ‘getLogger(name)’ function is used to get a particular log,
creating it if it doesn’t exist yet.  ‘getLogger(None)’ returns the root
logger.

     log = logging.getLogger('server')
      ...
     log.info('Listening on port %i', port)
      ...
     log.critical('Disk full')
      ...

Log records are usually propagated up the hierarchy, so a message logged
to ‘server.auth’ is also seen by ‘server’ and ‘root’, but a ‘Logger’ can
prevent this by setting its ‘propagate’ attribute to *note False: 48e.

There are more classes provided by the *note logging: aa. package that
can be customized.  When a ‘Logger’ instance is told to log a message,
it creates a ‘LogRecord’ instance that is sent to any number of
different ‘Handler’ instances.  Loggers and handlers can also have an
attached list of filters, and each filter can cause the ‘LogRecord’ to
be ignored or can modify the record before passing it along.  When
they’re finally output, ‘LogRecord’ instances are converted to text by a
‘Formatter’ class.  All of these classes can be replaced by your own
specially-written classes.

With all of these features the *note logging: aa. 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 PEP 282(1) will
also be helpful.

也參考
......

PEP 282(2) - Logging 系统

     由 Vinay Sajip 和 Trent Mick 撰写 ; 由 Vinay Sajip 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0282

   (2) https://www.python.org/dev/peps/pep-0282


File: python.info,  Node: PEP 285 布尔类型,  Next: PEP 293 Codec Error Handling Callbacks,  Prev: PEP 282 logging 包,  Up: Python 2 3 有什么新变化

1.15.9 PEP 285: 布尔类型
------------------------

A Boolean type was added to Python 2.3.  Two new constants were added to
the ‘__builtin__’ module, *note True: 593. and *note False: 48e.  (*note
True: 593. and *note False: 48e. 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 *note bool: 2bd.; the
constructor for it takes any Python value and converts it to *note True:
593. or *note False: 48e.

     >>> bool(1)
     True
     >>> bool(0)
     False
     >>> bool([])
     False
     >>> bool( (1,) )
     True

Most of the standard library modules and built-in functions have been
changed to return Booleans.

     >>> obj = []
     >>> hasattr(obj, 'append')
     True
     >>> isinstance(obj, list)
     True
     >>> isinstance(obj, tuple)
     False

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 ‘return 1’, you might wonder whether the ‘1’ represents a
Boolean truth value, an index, or a coefficient that multiplies some
other quantity.  If the statement is ‘return True’, however, the meaning
of the return value is quite clear.

Python’s Booleans were `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
*note if: eab. statement always evaluate to a Boolean result.  Python is
not this strict and never will be, as PEP 285(1) explicitly says.  This
means you can still use any expression in an ‘if’ statement, even ones
that evaluate to a list or tuple or some random object.  The Boolean
type is a subclass of the *note int: 204. class so that arithmetic using
a Boolean still works.

     >>> True + 1
     2
     >>> False + 1
     1
     >>> False * 75
     0
     >>> True * 75
     75

To sum up *note True: 593. and *note False: 48e. in a sentence: they’re
alternative ways to spell the integer values 1 and 0, with the single
difference that *note str(): 205. and *note repr(): 8b9. return the
strings ‘'True'’ and ‘'False'’ instead of ‘'1'’ and ‘'0'’.

也參考
......

PEP 285(2) - 添加布尔类型

     由 GvR 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0285

   (2) https://www.python.org/dev/peps/pep-0285


File: python.info,  Node: PEP 293 Codec Error Handling Callbacks,  Next: PEP 301 Distutils的软件包索引和元数据,  Prev: PEP 285 布尔类型,  Up: Python 2 3 有什么新变化

1.15.10 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 *note UnicodeError:
d03.), "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 *note
codecs.register_error(): eb9, and codecs then can access the error
handler with *note codecs.lookup_error(): eba.  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.

也參考
......

PEP 293(1) - Codec Error Handling Callbacks

     由 Walter Dörwald 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0293


File: python.info,  Node: PEP 301 Distutils的软件包索引和元数据,  Next: PEP 302 New Import Hooks,  Prev: PEP 293 Codec Error Handling Callbacks,  Up: Python 2 3 有什么新变化

1.15.11 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 ‘register’ command.
Running ‘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 ‘https://pypi.org’.

To make the catalog a bit more useful, a new optional `classifiers'
keyword argument has been added to the Distutils ‘setup()’ function.  A
list of Trove(1)-style strings can be supplied to help classify the
software.

Here’s an example ‘setup.py’ with classifiers, written to be compatible
with older versions of the Distutils:

     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)

The full list of classifiers can be obtained by running ‘python setup.py
register --list-classifiers’.

也參考
......

PEP 301(2) - Distutils 的软件包索引和元数据

     由 Richard Jones 撰写并实现。

   ---------- Footnotes ----------

   (1) http://catb.org/~esr/trove/

   (2) https://www.python.org/dev/peps/pep-0301


File: python.info,  Node: PEP 302 New Import Hooks,  Next: PEP 305 逗号分隔文件,  Prev: PEP 301 Distutils的软件包索引和元数据,  Up: Python 2 3 有什么新变化

1.15.12 PEP 302: New Import Hooks
---------------------------------

While it’s been possible to write custom import hooks ever since the
‘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
‘imputil’ and ‘iu’ modules, but none of them has ever gained much
acceptance, and none of them were easily usable from C code.

PEP 302(1) borrows ideas from its predecessors, especially from Gordon
McMillan’s ‘iu’ module.  Three new items are added to the *note sys: fd.
module:

   * ‘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 *note ImportError: 16c. exception if it
     can’t handle this path.

   * ‘sys.path_importer_cache’ caches importer objects for each path, so
     ‘sys.path_hooks’ will only need to be traversed once for each path.

   * ‘sys.meta_path’ is a list of importer objects that will be
     traversed before ‘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.

Importer objects must have a single method, ‘find_module(fullname,
path=None)’.  `fullname' will be a module or package name, e.g.
‘string’ or ‘distutils.core’.  ‘find_module()’ must return a loader
object that has a single method, ‘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 PEP 302(2) for the full details):

     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

也參考
......

PEP 302(3) - 新导入钩

     由 Just van Rossum 和 Paul Moore 撰写 ; 由 Just van Rossum 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0302

   (2) https://www.python.org/dev/peps/pep-0302

   (3) https://www.python.org/dev/peps/pep-0302


File: python.info,  Node: PEP 305 逗号分隔文件,  Next: PEP 307 Pickle Enhancements,  Prev: PEP 302 New Import Hooks,  Up: Python 2 3 有什么新变化

1.15.13 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:

     Costs,150,200,3.95

Read a line and call ‘line.split(',')’: what could be simpler?  But toss
in string data that can contain commas, and things get more complicated:

     "Costs",150,200,3.95,"Includes taxes, shipping, and sundry items"

A big ugly regular expression can parse this, but using the new *note
csv: 29. package is much simpler:

     import csv

     input = open('datafile', 'rb')
     reader = csv.reader(input)
     for line in reader:
         print line

The ‘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 *note csv.writer: ec0. class will generate
comma-separated files from a succession of tuples or lists, quoting
strings that contain the delimiter.

也參考
......

PEP 305(1) - CSV 文件 API

     由 Kevin Altis, Dave Cole, Andrew McNamara, Skip Montanaro, Cliff
     Wells 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0305


File: python.info,  Node: PEP 307 Pickle Enhancements,  Next: 扩展切片,  Prev: PEP 305 逗号分隔文件,  Up: Python 2 3 有什么新变化

1.15.14 PEP 307: Pickle Enhancements
------------------------------------

The *note pickle: ca. and ‘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; PEP
307(1) 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 *note
pickle.dumps(): ec3. 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, *note
pickle.HIGHEST_PROTOCOL: ec4, can be used to select the fanciest
protocol available.

Unpickling is no longer considered a safe operation.  2.2’s *note
pickle: ca. provided hooks for trying to prevent unsafe classes from
being unpickled (specifically, a ‘__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: *note
__getstate__(): ec5, *note __setstate__(): 2d1, and *note
__getnewargs__(): 7a1.  Consult PEP 307(2) 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.

也參考
......

PEP 307(3) - Extensions to the pickle protocol

     PEP 由 Guido van Rossum 和 Tim Peters 撰写和实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0307

   (2) https://www.python.org/dev/peps/pep-0307

   (3) https://www.python.org/dev/peps/pep-0307


File: python.info,  Node: 扩展切片,  Next: 其他语言特性修改<14>,  Prev: PEP 307 Pickle Enhancements,  Up: Python 2 3 有什么新变化

1.15.15 扩展切片
----------------

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: ‘L[1:10:2]’, ‘L[:-1:1]’, ‘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
*note TypeError: 1fe. 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:

     >>> L = range(10)
     >>> L[::2]
     [0, 2, 4, 6, 8]

Negative values also work to make a copy of the same list in reverse
order:

     >>> L[::-1]
     [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

This also works for tuples, arrays, and strings:

     >>> s='abcd'
     >>> s[::2]
     'ac'
     >>> s[::-1]
     'dcba'

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:

     >>> a = range(3)
     >>> a
     [0, 1, 2]
     >>> a[1:3] = [4, 5, 6]
     >>> a
     [0, 4, 5, 6]

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:

     >>> 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

Deletion is more straightforward:

     >>> a = range(4)
     >>> a
     [0, 1, 2, 3]
     >>> a[::2]
     [0, 2]
     >>> del a[::2]
     >>> a
     [1, 3]

One can also now pass slice objects to the *note __getitem__(): 3a5.
methods of the built-in sequences:

     >>> range(10).__getitem__(slice(0, 5, 2))
     [0, 2, 4]

Or use slice objects directly in subscripts:

     >>> range(10)[slice(0, 5, 2)]
     [0, 2, 4]

To simplify implementing sequences that support extended slicing, slice
objects now have a method ‘indices(length)’ which, given the length of a
sequence, returns a ‘(start, stop, step)’ tuple that can be passed
directly to *note range(): 1f5.  ‘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:

     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)

From this example you can also see that the built-in *note slice: ec8.
object is now the type object for the slice type, and is no longer a
function.  This is consistent with Python 2.2, where *note int: 204,
*note str: 205, etc., underwent the same change.


File: python.info,  Node: 其他语言特性修改<14>,  Next: 新增，改进和弃用的模块<4>,  Prev: 扩展切片,  Up: Python 2 3 有什么新变化

1.15.16 其他语言特性修改
------------------------

Here are all of the changes that Python 2.3 makes to the core Python
language.

   * The *note yield: 2c7. statement is now always a keyword, as
     described in section *note PEP 255; Simple Generators: eaa. of this
     document.

   * A new built-in function *note enumerate(): ea7. was added, as
     described in section *note PEP 279; enumerate(): eb4. of this
     document.

   * Two new constants, *note True: 593. and *note False: 48e. were
     added along with the built-in *note bool: 2bd. type, as described
     in section *note PEP 285; 布尔类型: eb7. of this document.

   * The *note int(): 204. type constructor will now return a long
     integer instead of raising an *note OverflowError: a41. when a
     string or floating-point number is too large to fit into an
     integer.  This can lead to the paradoxical result that
     ‘isinstance(int(expression), int)’ is false, but that seems
     unlikely to cause problems in practice.

   * Built-in types now support the extended slicing syntax, as
     described in section *note 扩展切片: ec7. of this document.

   * A new built-in function, ‘sum(iterable, start=0)’, adds up the
     numeric items in the iterable object and returns their sum.  *note
     sum(): 316. only accepts numbers, meaning that you can’t use it to
     concatenate a bunch of strings.  (Contributed by Alex Martelli.)

   * ‘list.insert(pos, value)’ used to insert `value' at the front of
     the list when `pos' was negative.  The behaviour has now been
     changed to be consistent with slice indexing, so when `pos' is -1
     the value will be inserted before the last element, and so forth.

   * ‘list.index(value)’, which searches for `value' within the list and
     returns its index, now takes optional `start' and `stop' arguments
     to limit the search to only part of the list.

   * Dictionaries have a new method, ‘pop(key[, *default*])’, that
     returns the value corresponding to `key' and removes that key/value
     pair from the dictionary.  If the requested key isn’t present in
     the dictionary, `default' is returned if it’s specified and *note
     KeyError: 3e9. raised if it isn’t.

          >>> 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
          {}
          >>>

     There’s also a new class method, ‘dict.fromkeys(iterable, value)’,
     that creates a dictionary with keys taken from the supplied
     iterator `iterable' and all values set to `value', defaulting to
     ‘None’.

     (Patches contributed by Raymond Hettinger.)

     Also, the *note dict(): 164. constructor now accepts keyword
     arguments to simplify creating small dictionaries:

          >>> dict(red=1, blue=2, green=3, black=4)
          {'blue': 2, 'black': 4, 'green': 3, 'red': 1}

     （由 Just van Rossum 贡献。）

   * The *note assert: 23f. statement no longer checks the ‘__debug__’
     flag, so you can no longer disable assertions by assigning to
     ‘__debug__’.  Running Python with the *note -O: 77e. switch will
     still generate code that doesn’t execute any assertions.

   * 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 ‘new’ module can be deprecated in a future Python version,
     because you can now use the type objects available in the *note
     types: 121. module.)  For example, you can create a new module
     object with the following code:

          >>> import types
          >>> m = types.ModuleType('abc','docstring')
          >>> m
          <module 'abc' (built-in)>
          >>> m.__doc__
          'docstring'

   * A new warning, *note PendingDeprecationWarning: 15c. was added to
     indicate features which are in the process of being deprecated.
     The warning will `not' be printed by default.  To check for use of
     features that will be deprecated in the future, supply *note
     -Walways;;PendingDeprecationWarning;;: 15b. on the command line or
     use *note warnings.filterwarnings(): eca.

   * The process of deprecating string-based exceptions, as in ‘raise
     "Error occurred"’, has begun.  Raising a string will now trigger
     *note PendingDeprecationWarning: 15c.

   * Using ‘None’ as a variable name will now result in a *note
     SyntaxWarning: 2c9. warning.  In a future version of Python, ‘None’
     may finally become a keyword.

   * The ‘xreadlines()’ method of file objects, introduced in Python
     2.1, is no longer necessary because files now behave as their own
     iterator.  ‘xreadlines()’ was originally introduced as a faster way
     to loop over all the lines in a file, but now you can simply write
     ‘for line in file_obj’.  File objects also have a new read-only
     ‘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.

   * 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"(1).
     To understand the motivation for this change, read Michele
     Simionato’s article "Python 2.3 Method Resolution Order"(2), or
     read the thread on python-dev starting with the message at
     ‘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.

   * 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 ‘sys.setcheckinterval(N)’.  The limit can be retrieved with
     the new ‘sys.getcheckinterval()’ function.

   * 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 ‘'.'’ in front of the type name.  For example, in
     Python 2.2, if you created a socket and printed its ‘__class__’,
     you’d get this output:

          >>> s = socket.socket()
          >>> s.__class__
          <type 'socket'>

     In 2.3, you get this:

          >>> s.__class__
          <type '_socket.socket'>

   * One of the noted incompatibilities between old- and new-style
     classes has been removed: you can now assign to the *note __name__:
     d2f. and *note __bases__: ecb. attributes of new-style classes.
     There are some restrictions on what can be assigned to *note
     __bases__: ecb. along the lines of those relating to assigning to
     an instance’s *note __class__: ecc. attribute.

* Menu:

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

   ---------- Footnotes ----------

   (1) http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.19.3910

   (2) http://www.phyast.pitt.edu/~micheles/mro.html


File: python.info,  Node: String Changes,  Next: 性能优化<13>,  Up: 其他语言特性修改<14>

1.15.16.1 String Changes
........................

   * The *note in: 179. operator now works differently for strings.
     Previously, when evaluating ‘X in Y’ where `X' and `Y' are strings,
     `X' could only be a single character.  That’s now changed; `X' can
     be a string of any length, and ‘X in Y’ will return *note True:
     593. if `X' is a substring of `Y'. If `X' is the empty string, the
     result is always *note True: 593.

          >>> 'ab' in 'abcd'
          True
          >>> 'ad' in 'abcd'
          False
          >>> '' in 'abcd'
          True

     Note that this doesn’t tell you where the substring starts; if you
     need that information, use the ‘find()’ string method.

   * The ‘strip()’, ‘lstrip()’, and ‘rstrip()’ string methods now have
     an optional argument for specifying the characters to strip.  The
     default is still to remove all whitespace characters:

          >>> '   abc '.strip()
          'abc'
          >>> '><><abc<><><>'.strip('<>')
          'abc'
          >>> '><><abc<><><>\n'.strip('<>')
          'abc<><><>\n'
          >>> u'\u4000\u4001abc\u4000'.strip(u'\u4000')
          u'\u4001abc'
          >>>

     (Suggested by Simon Brunning and implemented by Walter Dörwald.)

   * The ‘startswith()’ and ‘endswith()’ string methods now accept
     negative numbers for the `start' and `end' parameters.

   * Another new string method is ‘zfill()’, originally a function in
     the *note string: f6. module.  ‘zfill()’ pads a numeric string with
     zeros on the left until it’s the specified width.  Note that the
     ‘%’ operator is still more flexible and powerful than ‘zfill()’.

          >>> '45'.zfill(4)
          '0045'
          >>> '12345'.zfill(4)
          '12345'
          >>> 'goofy'.zfill(6)
          '0goofy'

     （由 Walter Dörwald 贡献。）

   * A new type object, ‘basestring’, has been added.  Both 8-bit
     strings and Unicode strings inherit from this type, so
     ‘isinstance(obj, basestring)’ will return *note True: 593. for
     either kind of string.  It’s a completely abstract type, so you
     can’t create ‘basestring’ instances.

   * 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.)


File: python.info,  Node: 性能优化<13>,  Prev: String Changes,  Up: 其他语言特性修改<14>

1.15.16.2 性能优化
..................

   * The creation of new-style class instances has been made much
     faster; they’re now faster than classic classes!

   * The ‘sort()’ method of list objects has been extensively rewritten
     by Tim Peters, and the implementation is significantly faster.

   * 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.)

   * The ‘SET_LINENO’ opcode is now gone.  This may provide a small
     speed increase, depending on your compiler’s idiosyncrasies.  See
     section *note Other Changes and Fixes: ecf. for a longer
     explanation.  (Removed by Michael Hudson.)

   * ‘xrange()’ objects now have their own iterator, making ‘for i in
     xrange(n)’ slightly faster than ‘for i in range(n)’.  (Patch by
     Raymond Hettinger.)

   * 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.)

The net result of the 2.3 optimizations is that Python 2.3 runs the
pystone benchmark around 25% faster than Python 2.2.


File: python.info,  Node: 新增，改进和弃用的模块<4>,  Next: Pymalloc A Specialized Object Allocator,  Prev: 其他语言特性修改<14>,  Up: Python 2 3 有什么新变化

1.15.17 新增，改进和弃用的模块
------------------------------

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 ‘Misc/NEWS’ file in
the source tree for a more complete list of changes, or look through the
CVS logs for all the details.

   * The *note array: 6. module now supports arrays of Unicode
     characters using the ‘'u'’ format character.  Arrays also now
     support using the ‘+=’ assignment operator to add another array’s
     contents, and the ‘*=’ assignment operator to repeat an array.
     (Contributed by Jason Orendorff.)

   * The ‘bsddb’ module has been replaced by version 4.1.6 of the
     PyBSDDB(1) package, providing a more complete interface to the
     transactional features of the BerkeleyDB library.

     The old version of the module has been renamed to ‘bsddb185’ and is
     no longer built automatically; you’ll have to edit ‘Modules/Setup’
     to enable it.  Note that the new ‘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 ‘db2pickle.py’ and
     ‘pickle2db.py’ which you will find in the distribution’s
     ‘Tools/scripts’ directory.  If you’ve already been using the
     PyBSDDB package and importing it as ‘bsddb3’, you will have to
     change your ‘import’ statements to import it as ‘bsddb’.

   * The new *note bz2: 13. module is an interface to the bz2 data
     compression library.  bz2-compressed data is usually smaller than
     corresponding *note zlib: 14d.-compressed data.  (Contributed by
     Gustavo Niemeyer.)

   * A set of standard date/time types has been added in the new *note
     datetime: 30. module.  See the following section for more details.

   * The Distutils ‘Extension’ class now supports an extra constructor
     argument named `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
     ‘sampmodule.c’ includes the header file ‘sample.h’, you would
     create the ‘Extension’ object like this:

          ext = Extension("samp",
                          sources=["sampmodule.c"],
                          depends=["sample.h"])

     Modifying ‘sample.h’ would then cause the module to be recompiled.
     (Contributed by Jeremy Hylton.)

   * Other minor changes to Distutils: it now checks for the ‘CC’,
     ‘CFLAGS’, ‘CPP’, ‘LDFLAGS’, and ‘CPPFLAGS’ environment variables,
     using them to override the settings in Python’s configuration
     (contributed by Robert Weber).

   * Previously the *note doctest: 66. module would only search the
     docstrings of public methods and functions for test cases, but it
     now also examines private ones as well.  The ‘DocTestSuite()’
     function creates a *note unittest.TestSuite: 7c1. object from a set
     of *note doctest: 66. tests.

   * The new ‘gc.get_referents(object)’ function returns a list of all
     the objects referenced by `object'.

   * The *note getopt: 85. module gained a new function, ‘gnu_getopt()’,
     that supports the same arguments as the existing *note getopt():
     85. function but uses GNU-style scanning mode.  The existing *note
     getopt(): 85. 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:

          >>> getopt.getopt(['-f', 'filename', 'output', '-v'], 'f:v')
          ([('-f', 'filename')], ['output', '-v'])
          >>> getopt.gnu_getopt(['-f', 'filename', 'output', '-v'], 'f:v')
          ([('-f', 'filename'), ('-v', '')], ['output'])

     （由 Peter Åstrand 贡献。）

   * The *note grp: 8a, *note pwd: d6, and *note resource: e0. modules
     now return enhanced tuples:

          >>> import grp
          >>> g = grp.getgrnam('amk')
          >>> g.gr_name, g.gr_gid
          ('amk', 500)

   * The *note gzip: 8b. module can now handle files exceeding 2 GiB.

   * The new *note heapq: 8d. 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
     `k', ‘heap[k] <= heap[2*k+1]’ and ‘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
     ‘https://xlinux.nist.gov/dads//HTML/priorityque.html’ for more
     information about the priority queue data structure.)

     The *note heapq: 8d. module provides ‘heappush()’ and ‘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:

          >>> 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]

     （由 Kevin O’Connor 贡献。）

   * The IDLE integrated development environment has been updated using
     the code from the IDLEfork project
     (‘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 ‘reload()’
     operations.  IDLE’s core code has been incorporated into the
     standard library as the ‘idlelib’ package.

   * The *note imaplib: 97. module now supports IMAP over SSL.
     (Contributed by Piers Lauder and Tino Lange.)

   * The *note itertools: a3. contains a number of useful functions for
     use with iterators, inspired by various functions provided by the
     ML and Haskell languages.  For example,
     ‘itertools.ifilter(predicate, iterator)’ returns all elements in
     the iterator for which the function ‘predicate()’ returns *note
     True: 593, and ‘itertools.repeat(obj, N)’ returns ‘obj’ `N' times.
     There are a number of other functions in the module; see the
     package’s reference documentation for details.  (Contributed by
     Raymond Hettinger.)

   * Two new functions in the *note math: b1. module, ‘degrees(rads)’
     and ‘radians(degs)’, convert between radians and degrees.  Other
     functions in the *note math: b1. module such as *note math.sin():
     ed1. and *note math.cos(): ed2. have always required input values
     measured in radians.  Also, an optional `base' argument was added
     to *note math.log(): ed3. to make it easier to compute logarithms
     for bases other than ‘e’ and ‘10’.  (Contributed by Raymond
     Hettinger.)

   * Several new POSIX functions (‘getpgid()’, ‘killpg()’, ‘lchown()’,
     ‘loadavg()’, ‘major()’, ‘makedev()’, ‘minor()’, and ‘mknod()’) were
     added to the *note posix: d1. module that underlies the *note os:
     c4. module.  (Contributed by Gustavo Niemeyer, Geert Jansen, and
     Denis S. Otkidach.)

   * In the *note os: c4. module, the ‘*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 *note
     time.time(): 42d.

     During testing, it was found that some applications will break if
     time stamps are floats.  For compatibility, when using the tuple
     interface of the ‘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
     ‘os.stat_float_times()’ is invoked to enable float return values:

          >>> os.stat("/tmp").st_mtime
          1034791200
          >>> os.stat_float_times(True)
          >>> os.stat("/tmp").st_mtime
          1034791200.6335014

     In Python 2.4, the default will change to always returning floats.

     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.

   * The *note optparse: c3. 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.

   * The old and never-documented ‘linuxaudiodev’ module has been
     deprecated, and a new version named *note ossaudiodev: c6. 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.)

   * The new *note platform: ce. 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.)

   * The parser objects provided by the ‘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 ‘buffer_text’ attribute to *note True: 593.
     will enable buffering.

   * The ‘sample(population, k)’ function was added to the *note random:
     dc. module.  `population' is a sequence or ‘xrange’ object
     containing the elements of a population, and ‘sample()’ chooses `k'
     elements from the population without replacing chosen elements.
     `k' can be any value up to ‘len(population)’.  For 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]

     The *note random: dc. module now uses a new algorithm, the Mersenne
     Twister, implemented in C. It’s faster and more extensively studied
     than the previous algorithm.

     (All changes contributed by Raymond Hettinger.)

   * The *note readline: de. module also gained a number of new
     functions: ‘get_history_item()’, ‘get_current_history_length()’,
     and ‘redisplay()’.

   * The ‘rexec’ and ‘Bastion’ modules have been declared dead, and
     attempts to import them will fail with a *note RuntimeError: 3dc.
     New-style classes provide new ways to break out of the restricted
     execution environment provided by ‘rexec’, and no one has interest
     in fixing them or time to do so.  If you have applications using
     ‘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 ‘rexec’ module in
     those versions.  To repeat: if you’re using ‘rexec’, stop using it
     immediately.)

   * The ‘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.

   * The *note shutil: e9. module gained a ‘move(src, dest)’ function
     that recursively moves a file or directory to a new location.

   * Support for more advanced POSIX signal handling was added to the
     *note signal: ea. but then removed again as it proved impossible to
     make it work reliably across platforms.

   * The *note socket: ef. module now supports timeouts.  You can call
     the ‘settimeout(t)’ method on a socket object to set a timeout of
     `t' seconds.  Subsequent socket operations that take longer than
     `t' seconds to complete will abort and raise a *note
     socket.timeout: cd9. exception.

     The original timeout implementation was by Tim O’Malley.  Michael
     Gilfix integrated it into the Python *note socket: ef. 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.)

   * On Windows, the *note socket: ef. module now ships with Secure
     Sockets Layer (SSL) support.

   * The value of the C ‘PYTHON_API_VERSION’ macro is now exposed at the
     Python level as ‘sys.api_version’.  The current exception can be
     cleared by calling the new ‘sys.exc_clear()’ function.

   * The new *note tarfile: 101. module allows reading from and writing
     to ‘tar’-format archive files.  (Contributed by Lars Gustäbel.)

   * The new *note textwrap: 10a. module contains functions for wrapping
     strings containing paragraphs of text.  The ‘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 ‘fill(text,
     width)’ function returns a single string, reformatted to fit into
     lines no longer than the chosen width.  (As you can guess, ‘fill()’
     is built on top of ‘wrap()’.  For 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.
          >>>

     The module also contains a ‘TextWrapper’ class that actually
     implements the text wrapping strategy.  Both the ‘TextWrapper’
     class and the ‘wrap()’ and ‘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.)

   * The ‘thread’ and *note threading: 10b. modules now have companion
     modules, ‘dummy_thread’ and ‘dummy_threading’, that provide a
     do-nothing implementation of the ‘thread’ module’s interface for
     platforms where threads are not supported.  The intention is to
     simplify thread-aware modules (ones that `don’t' rely on threads to
     run) by putting the following code at the top:

          try:
              import threading as _threading
          except ImportError:
              import dummy_threading as _threading

     In this example, ‘_threading’ is used as the module name to make it
     clear that the module being used is not necessarily the actual
     *note threading: 10b. module.  Code can call functions and use
     classes in ‘_threading’ whether or not threads are supported,
     avoiding an *note if: eab. 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.

   * The *note time: 10c. module’s ‘strptime()’ function has long been
     an annoyance because it uses the platform C library’s ‘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.

   * The new *note timeit: 10d. module helps measure how long snippets
     of Python code take to execute.  The ‘timeit.py’ file can be run
     directly from the command line, or the module’s ‘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 ‘unicode()’
     function:

          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]

   * The ‘Tix’ module has received various bug fixes and updates for the
     current version of the Tix package.

   * The ‘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,
     ‘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 ‘Tkinter’ will now
     raise an exception on such an access so that you can at least find
     out about the problem.  See
     ‘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.)

   * Calling Tcl methods through ‘_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 ‘_tkinter.Tcl_Obj’ object if no Python equivalent exists.
     This behavior can be controlled through the ‘wantobjects()’ method
     of ‘tkapp’ objects.

     When using ‘_tkinter’ through the ‘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 ‘wantobjects’ variable in the ‘Tkinter’
     module to false before creating the first ‘tkapp’ object.

          import Tkinter
          Tkinter.wantobjects = 0

     Any breakage caused by this change should be reported as a bug.

   * The ‘UserDict’ module has a new ‘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 *note
     shelve: e7. module.

     Adding the mix-in as a superclass provides the full dictionary
     interface whenever the class defines *note __getitem__(): 3a5,
     *note __setitem__(): d2a, *note __delitem__(): d2b, and ‘keys()’.
     For 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']

     （由 Raymond Hettinger 贡献。）

   * The DOM implementation in *note xml.dom.minidom: 13e. can now
     generate XML output in a particular encoding by providing an
     optional encoding argument to the ‘toxml()’ and ‘toprettyxml()’
     methods of DOM nodes.

   * The ‘xmlrpclib’ module now supports an XML-RPC extension for
     handling nil data values such as Python’s ‘None’.  Nil values are
     always supported on unmarshalling an XML-RPC response.  To generate
     requests containing ‘None’, you must supply a true value for the
     `allow_none' parameter when creating a ‘Marshaller’ instance.

   * The new ‘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.)

   * 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.

          >{}>{}> u"www.Alliancefrançaise.nu".encode("idna")
          'www.xn--alliancefranaise-npb.nu'

     The *note socket: ef. 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 ‘httplib’ and *note ftplib: 82.) also support Unicode host
     names; ‘httplib’ also sends HTTP ‘Host’ headers using the ACE
     version of the domain name.  *note urllib: 126. supports Unicode
     URLs with non-ASCII host names as long as the ‘path’ part of the
     URL is ASCII only.

     To implement this change, the *note stringprep: f7. module, the
     ‘mkstringprep’ tool and the ‘punycode’ encoding have been added.

* Menu:

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

   ---------- Footnotes ----------

   (1) http://pybsddb.sourceforge.net


File: python.info,  Node: Date/Time 类型,  Next: optparse 模块,  Up: 新增，改进和弃用的模块<4>

1.15.17.1 Date/Time 类型
........................

Date and time types suitable for expressing timestamps were added as the
*note datetime: 30. 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: ‘date’, representing a day, month, and
year; *note time: 5ec, consisting of hour, minute, and second; and *note
datetime: 19f, which contains all the attributes of both ‘date’ and
*note time: 5ec.  There’s also a ‘timedelta’ class representing
differences between two points in time, and time zone logic is
implemented by classes inheriting from the abstract ‘tzinfo’ class.

You can create instances of ‘date’ and *note time: 5ec. by either
supplying keyword arguments to the appropriate constructor, e.g.
‘datetime.date(year=1972, month=10, day=15)’, or by using one of a
number of class methods.  For example, the ‘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:

     >>> 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'

The ‘replace()’ method allows modifying one or more fields of a ‘date’
or *note datetime: 19f. instance, returning a new instance:

     >>> 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)
     >>>

Instances can be compared, hashed, and converted to strings (the result
is the same as that of ‘isoformat()’).  ‘date’ and *note datetime: 19f.
instances can be subtracted from each other, and added to ‘timedelta’
instances.  The largest missing feature is that there’s no standard
library support for parsing strings and getting back a ‘date’ or *note
datetime: 19f.

For more information, refer to the module’s reference documentation.
(Contributed by Tim Peters.)


File: python.info,  Node: optparse 模块,  Prev: Date/Time 类型,  Up: 新增，改进和弃用的模块<4>

1.15.17.2 optparse 模块
.......................

The *note getopt: 85. module provides simple parsing of command-line
arguments.  The new *note optparse: c3. module (originally named Optik)
provides more elaborate command-line parsing that follows the Unix
conventions, automatically creates the output for ‘--help’, and can
perform different actions for different options.

You start by creating an instance of ‘OptionParser’ and telling it what
your program’s options are.

     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')

Parsing a command line is then done by calling the ‘parse_args()’
method.

     options, args = op.parse_args(sys.argv[1:])
     print options
     print args

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.

     $ ./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}>
     []
     $

The help message is automatically generated for you:

     $ ./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
     $

有关更多详细信息，请参见模块的文档。

Optik was written by Greg Ward, with suggestions from the readers of the
Getopt SIG.


File: python.info,  Node: Pymalloc A Specialized Object Allocator,  Next: 构建和 C API 的改变<12>,  Prev: 新增，改进和弃用的模块<4>,  Up: Python 2 3 有什么新变化

1.15.18 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 ‘malloc()’ and to have less memory overhead for
allocation patterns typical of Python programs.  The allocator uses C’s
‘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 ‘--with-pymalloc’ option to the ‘configure’ script.  In
2.3, pymalloc has had further enhancements and is now enabled by
default; you’ll have to supply ‘--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 ‘malloc()’ and
‘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 ‘malloc()’ and ‘free()’ any more, and
calling the wrong function to free memory may get you a core dump.  For
example, if memory was allocated using *note PyObject_Malloc(): 601, it
has to be freed using *note PyObject_Free(): 5fd, not ‘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.

   * To allocate and free an undistinguished chunk of memory use the
     "raw memory" family: *note PyMem_Malloc(): 5fe, *note
     PyMem_Realloc(): a50, and *note PyMem_Free(): e6e.

   * The "object memory" family is the interface to the pymalloc
     facility described above and is biased towards a large number of
     "small" allocations: *note PyObject_Malloc(): 601, *note
     PyObject_Realloc(): e6f, and *note PyObject_Free(): 5fd.

   * To allocate and free Python objects, use the "object" family *note
     PyObject_New(): 268, *note PyObject_NewVar(): 269, and *note
     PyObject_Del(): ed8.

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 ‘configure’ with ‘--with-pydebug’.

To aid extension writers, a header file ‘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.

也參考
......

‘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 ‘Objects/obmalloc.c’ in the Python
     source code.  The above link points to the file within the
     python.org SVN browser.


File: python.info,  Node: 构建和 C API 的改变<12>,  Next: Other Changes and Fixes<2>,  Prev: Pymalloc A Specialized Object Allocator,  Up: Python 2 3 有什么新变化

1.15.19 构建和 C API 的改变
---------------------------

Changes to Python’s build process and to the C API include:

   * 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 ‘--with-cycle-gc’
     switch to ‘configure’ has been removed.

   * Python can now optionally be built as a shared library
     (‘libpython2.3.so’) by supplying ‘--enable-shared’ when running
     Python’s ‘configure’ script.  (Contributed by Ondrej Palkovsky.)

   * The ‘DL_EXPORT’ and ‘DL_IMPORT’ macros are now deprecated.
     Initialization functions for Python extension modules should now be
     declared using the new macro ‘PyMODINIT_FUNC’, while the Python
     core will generally use the ‘PyAPI_FUNC’ and ‘PyAPI_DATA’ macros.

   * The interpreter can be compiled without any docstrings for the
     built-in functions and modules by supplying ‘--without-doc-strings’
     to the ‘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.)

   * The ‘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 *note METH_NOARGS: eda. 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 ‘PyArg_ParseTuple(args, "")’ instead,
     but this will be slower than using *note METH_NOARGS: eda.

   * *note PyArg_ParseTuple(): 393. accepts new format characters for
     various sizes of unsigned integers: ‘B’ for ‘unsigned char’, ‘H’
     for ‘unsigned short int’, ‘I’ for ‘unsigned int’, and ‘K’ for
     ‘unsigned long long’.

   * A new function, ‘PyObject_DelItemString(mapping, char *key)’ was
     added as shorthand for ‘PyObject_DelItem(mapping,
     PyString_New(key))’.

   * File objects now manage their internal string buffer differently,
     increasing it exponentially when needed.  This results in the
     benchmark tests in ‘Lib/test/test_bufio.py’ speeding up
     considerably (from 57 seconds to 1.7 seconds, according to one
     measurement).

   * It’s now possible to define class and static methods for a C
     extension type by setting either the *note METH_CLASS: edb. or
     *note METH_STATIC: edc. flags in a method’s *note PyMethodDef: edd.
     structure.

   * 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.

   * If you dynamically allocate type objects in your extension, you
     should be aware of a change in the rules relating to the
     ‘__module__’ and *note __name__: d2f. attributes.  In summary, you
     will want to ensure the type’s dictionary contains a ‘'__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.

* Menu:

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


File: python.info,  Node: Port-Specific Changes<3>,  Up: 构建和 C API 的改变<12>

1.15.19.1 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; ‘fork()’ and *note fcntl(): 7c. 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 ‘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
(‘http://www.atheos.cx/’), GNU/Hurd, and OpenVMS.


File: python.info,  Node: Other Changes and Fixes<2>,  Next: 移植到 Python 2 3,  Prev: 构建和 C API 的改变<12>,  Up: Python 2 3 有什么新变化

1.15.20 Other Changes and Fixes
-------------------------------

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.

Some of the more notable changes are:

   * If the *note PYTHONINSPECT: ee0. 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 *note -i:
     ee1. 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.

   * The ‘regrtest.py’ script now provides a way to allow "all resources
     except `foo'."  A resource name passed to the ‘-u’ option can now
     be prefixed with a hyphen (‘'-'’) to mean "remove this resource."
     For example, the option ’‘-uall,-bsddb’’ could be used to enable
     the use of all resources except ‘bsddb’.

   * The tools used to build the documentation now work under Cygwin as
     well as Unix.

   * The ‘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., *note pdb: c9.).  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 ‘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 *note -O: 77e.

     C extensions that access the ‘f_lineno’ field of frame objects
     should instead call ‘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
     ‘f_lineno’ attribute of frame objects, changing the line that will
     be executed next.  A ‘jump’ command has been added to the *note
     pdb: c9. debugger taking advantage of this new feature.
     (Implemented by Richie Hindle.)


File: python.info,  Node: 移植到 Python 2 3,  Next: 致谢<5>,  Prev: Other Changes and Fixes<2>,  Up: Python 2 3 有什么新变化

1.15.21 移植到 Python 2.3
-------------------------

This section lists previously described changes that may require changes
to your code:

   * *note yield: 2c7. is now always a keyword; if it’s used as a
     variable name in your code, a different name must be chosen.

   * For strings `X' and `Y', ‘X in Y’ now works if `X' is more than one
     character long.

   * The *note int(): 204. type constructor will now return a long
     integer instead of raising an *note OverflowError: a41. when a
     string or floating-point number is too large to fit into an
     integer.

   * 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 *note PEP 263;
     Source Code Encodings: ead. for more information.

   * Calling Tcl methods through ‘_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 ‘_tkinter.Tcl_Obj’ object if no Python equivalent exists.

   * Large octal and hex literals such as ‘0xffffffff’ now trigger a
     *note FutureWarning: 435.  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 ‘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 ‘~(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 ‘0xffffffffL &~(1L<<31)’.

   * You can no longer disable assertions by assigning to ‘__debug__’.

   * The Distutils ‘setup()’ function has gained various new keyword
     arguments such as `depends'.  Old versions of the Distutils will
     abort if passed unknown keywords.  A solution is to check for the
     presence of the new ‘get_distutil_options()’ function in your
     ‘setup.py’ and only uses the new keywords with a version of the
     Distutils that supports them:

          from distutils import core

          kw = {'sources': 'foo.c', ...}
          if hasattr(core, 'get_distutil_options'):
              kw['depends'] = ['foo.h']
          ext = Extension(**kw)

   * Using ‘None’ as a variable name will now result in a *note
     SyntaxWarning: 2c9. warning.

   * Names of extension types defined by the modules included with
     Python now contain the module and a ‘'.'’ in front of the type
     name.


File: python.info,  Node: 致谢<5>,  Prev: 移植到 Python 2 3,  Up: Python 2 3 有什么新变化

1.15.22 致谢
------------

作者感谢以下人员为本文的各种草案提供建议，更正和帮助： 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.


File: python.info,  Node: Python 2 2 有什么新变化,  Next: Python 2 1 有什么新变化,  Prev: Python 2 3 有什么新变化,  Up: Python 有什麼新功能？

1.16 Python 2.2 有什么新变化
============================


作者: A.M. Kuchling

* Menu:

* 簡介::
* PEPs 252 and 253; Type and Class Changes: PEPs 252 and 253 Type and Class Changes.
* PEP 234; Iterators: PEP 234 Iterators.
* PEP 255; Simple Generators: PEP 255 Simple Generators<2>.
* PEP 237; 统一长整数和整数: PEP 237 统一长整数和整数<2>.
* PEP 238; Changing the Division Operator: PEP 238 Changing the Division Operator.
* Unicode Changes::
* PEP 227; Nested Scopes: PEP 227 Nested Scopes.
* 新增和改进的模块: 新增和改进的模块<3>.
* Interpreter Changes and Fixes::
* Other Changes and Fixes: Other Changes and Fixes<3>.
* 致谢: 致谢<6>.


File: python.info,  Node: 簡介,  Next: PEPs 252 and 253 Type and Class Changes,  Up: Python 2 2 有什么新变化

1.16.1 簡介
-----------

This article explains the new features in Python 2.2.2, released on
October 14, 2002.  Python 2.2.2 is a bugfix release of Python 2.2,
originally released on December 21, 2001.

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(1) and the Python Reference Manual(2).  If
you want to understand the complete implementation and design rationale
for a change, refer to the PEP for a particular new feature.

   ---------- Footnotes ----------

   (1) https://docs.python.org/2.2/lib/lib.html

   (2) https://docs.python.org/2.2/ref/ref.html


File: python.info,  Node: PEPs 252 and 253 Type and Class Changes,  Next: PEP 234 Iterators,  Prev: 簡介,  Up: Python 2 2 有什么新变化

1.16.2 PEPs 252 and 253: Type and Class Changes
-----------------------------------------------

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 ‘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 ‘UserList’ instance.

Python 2.2 fixes this, and in the process adds some exciting new
capabilities.  A brief summary:

   * 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.

   * It’s now possible to define static and class methods, in addition
     to the instance methods available in previous versions of Python.

   * It’s also possible to automatically call methods on accessing or
     setting an instance attribute by using a new mechanism called
     `properties'.  Many uses of *note __getattr__(): 42a. 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.

   * The list of legal attributes for an instance can be limited to a
     particular set using `slots', making it possible to safeguard
     against typos and perhaps make more optimizations possible in
     future versions of Python.

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 *note Related
Links: ee9, "Related Links", for further sources of information about
Python 2.2’s new object model.

* Menu:

* Old and New Classes::
* Descriptors::
* Multiple Inheritance; The Diamond Rule: Multiple Inheritance The Diamond Rule.
* Attribute Access::
* Related Links::


File: python.info,  Node: Old and New Classes,  Next: Descriptors,  Up: PEPs 252 and 253 Type and Class Changes

1.16.2.1 Old and New Classes
............................

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 *note object: 3d2, the base class for all
built-in types, has also been added so if no built-in type is suitable,
you can just subclass *note object: 3d2.:

     class C(object):
         def __init__ (self):
             ...
         ...

This means that *note class: d32. 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
‘__metaclass__’ — see PEP 253(1) for the details — but it’s easier to
just subclass *note object: 3d2.)

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 *note int(): 204, *note float(): 1fd, and *note str(): 205.  In
2.2, they aren’t functions any more, but type objects that behave as
factories when called.

     >>> int
     <type 'int'>
     >>> int('123')
     123

To make the set of types complete, new type objects such as *note
dict(): 164. and ‘file()’ have been added.  Here’s a more interesting
example, adding a ‘lock()’ method to file objects:

     class LockableFile(file):
         def lock (self, operation, length=0, start=0, whence=0):
             import fcntl
             return fcntl.lockf(self.fileno(), operation,
                                length, start, whence)

The now-obsolete ‘posixfile’ module contained a class that emulated all
of a file object’s methods and also added a ‘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 ‘LockableFile’.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0253


File: python.info,  Node: Descriptors,  Next: Multiple Inheritance The Diamond Rule,  Prev: Old and New Classes,  Up: PEPs 252 and 253 Type and Class Changes

1.16.2.2 Descriptors
....................

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 ‘__members__’ and
‘__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 *note __dict__: 5f5. of an object, but
when class inheritance or an arbitrary *note __getattr__(): 42a. 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 `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:

   * *note __name__: d2f. is the attribute’s name.

   * ‘__doc__’ is the attribute’s docstring.

   * ‘__get__(object)’ is a method that retrieves the attribute value
     from `object'.

   * ‘__set__(object, value)’ sets the attribute on `object' to `value'.

   * ‘__delete__(object, value)’ deletes the `value' attribute of
     `object'.

For example, when you write ‘obj.x’, the steps that Python actually
performs are:

     descriptor = obj.__class__.x
     descriptor.__get__(obj)

For methods, ‘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:

     class C(object):
         def f(arg1, arg2):
             ...
         f = staticmethod(f)

         def g(cls, arg1, arg2):
             ...
         g = classmethod(g)

The *note staticmethod(): 30a. function takes the function ‘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 (‘def static f’, ‘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:

     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)

Note that a person using the new ‘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
‘eiffelmethod()’ or the ZODB or whatever, but most users will just write
code on top of the resulting libraries and ignore the implementation
details.


File: python.info,  Node: Multiple Inheritance The Diamond Rule,  Next: Attribute Access,  Prev: Descriptors,  Up: PEPs 252 and 253 Type and Class Changes

1.16.2.3 Multiple Inheritance: The Diamond Rule
...............................................

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 PEP 253(1) by Guido van Rossum):

           class A:
             ^ ^  def save(self): ...
            /   \
           /     \
          /       \
         /         \
     class B     class C:
         ^         ^  def save(self): ...
          \       /
           \     /
            \   /
             \ /
           class D

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 ‘D.save()’ will search the classes ‘D’, ‘B’, and then ‘A’,
where ‘save()’ would be found and returned.  ‘C.save()’ would never be
found at all.  This is bad, because if ‘C’’s ‘save()’ method is saving
some internal state specific to ‘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.)

  1. 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 [‘D’, ‘B’, ‘A’, ‘C’,
     ‘A’].

  2. Scan the list for duplicated classes.  If any are found, remove all
     but one occurrence, leaving the `last' one in the list.  In the
     above example, the list becomes [‘D’, ‘B’, ‘C’, ‘A’] after dropping
     duplicates.

Following this rule, referring to ‘D.save()’ will return ‘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, *note super():
5dd, provides a way to get at a class’s superclasses without having to
reimplement Python’s algorithm.  The most commonly used form will be
‘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, ‘D’’s ‘save()’ method would look
like this:

     class D (B,C):
         def save (self):
             # Call superclass .save()
             super(D, self).save()
             # Save D's private information here
             ...

*note super(): 5dd. can also return unbound superclass objects when
called as ‘super(class)’ or ‘super(class1, class2)’, but this probably
won’t often be useful.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0253


File: python.info,  Node: Attribute Access,  Next: Related Links,  Prev: Multiple Inheritance The Diamond Rule,  Up: PEPs 252 and 253 Type and Class Changes

1.16.2.4 Attribute Access
.........................

A fair number of sophisticated Python classes define hooks for attribute
access using *note __getattr__(): 42a.; most commonly this is done for
convenience, to make code more readable by automatically mapping an
attribute access such as ‘obj.parent’ into a method call such as
‘obj.get_parent’.  Python 2.2 adds some new ways of controlling
attribute access.

First, ‘__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 ‘obj.foo’ and no attribute named ‘foo’ is
found in the instance’s dictionary.

New-style classes also support a new method,
‘__getattribute__(attr_name)’.  The difference between the two methods
is that *note __getattribute__(): 549. is `always' called whenever any
attribute is accessed, while the old *note __getattr__(): 42a. is only
called if ‘foo’ isn’t found in the instance’s dictionary.

However, Python 2.2’s support for `properties' will often be a simpler
way to trap attribute references.  Writing a *note __getattr__(): 42a.
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 *note __dict__: 5f5.  *note __getattr__(): 42a. methods also
end up being called by Python when it checks for other methods such as
*note __repr__(): 44a. or ‘__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.

*note property: 308. 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 ‘size’ attribute that’s computed, but
also settable, you could write:

     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")

That is certainly clearer and easier to write than a pair of *note
__getattr__(): 42a./*note __setattr__(): eee. methods that check for the
‘size’ attribute and handle it specially while retrieving all other
attributes from the instance’s *note __dict__: 5f5.  Accesses to ‘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 *note __slots__: eef. 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
‘obj.new_attr=1’.  A new-style class can define a class attribute named
*note __slots__: eef. to limit the legal attributes to a particular set
of names.  An example will make this clear:

     >>> 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'

Note how you get an *note AttributeError: 4a1. on the attempt to assign
to an attribute not listed in *note __slots__: eef.


File: python.info,  Node: Related Links,  Prev: Attribute Access,  Up: PEPs 252 and 253 Type and Class Changes

1.16.2.5 Related Links
......................

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?

‘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, PEP 252(1) and PEP 253(2).  PEP
252(3) is titled "Making Types Look More Like Classes", and covers the
descriptor API. PEP 253(4) is titled "Subtyping Built-in Types", and
describes the changes to type objects that make it possible to subtype
built-in objects.  PEP 253(5) 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 ‘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.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0252

   (2) https://www.python.org/dev/peps/pep-0253

   (3) https://www.python.org/dev/peps/pep-0252

   (4) https://www.python.org/dev/peps/pep-0253

   (5) https://www.python.org/dev/peps/pep-0253


File: python.info,  Node: PEP 234 Iterators,  Next: PEP 255 Simple Generators<2>,  Prev: PEPs 252 and 253 Type and Class Changes,  Up: Python 2 2 有什么新变化

1.16.3 PEP 234: Iterators
-------------------------

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 ‘for item in obj’
work is to define a *note __getitem__(): 3a5. method that looks
something like this:

     def __getitem__(self, index):
         return <next item>

*note __getitem__(): 3a5. is more properly used to define an indexing
operation on an object so that you can write ‘obj[5]’ to retrieve the
sixth element.  It’s a bit misleading when you’re using this only to
support *note for: cfa. loops.  Consider some file-like object that
wants to be looped over; the `index' parameter is essentially
meaningless, as the class probably assumes that a series of *note
__getitem__(): 3a5. calls will be made with `index' incrementing by one
each time.  In other words, the presence of the *note __getitem__():
3a5. method doesn’t mean that using ‘file[5]’ to randomly access the
sixth element will work, though it really should.

In Python 2.2, iteration can be implemented separately, and *note
__getitem__(): 3a5. methods can be limited to classes that really do
support random access.  The basic idea of iterators is simple.  A new
built-in function, ‘iter(obj)’ or ‘iter(C, sentinel)’, is used to get an
iterator.  ‘iter(obj)’ returns an iterator for the object `obj', while
‘iter(C, sentinel)’ returns an iterator that will invoke the callable
object `C' until it returns `sentinel' to signal that the iterator is
done.

Python classes can define an *note __iter__(): 608. method, which should
create and return a new iterator for the object; if the object is its
own iterator, this method can just return ‘self’.  In particular,
iterators will usually be their own iterators.  Extension types
implemented in C can implement a *note tp_iter: ef2. function in order
to return an iterator, and extension types that want to behave as
iterators can define a *note tp_iternext: ef3. function.

So, after all this, what do iterators actually do?  They have one
required method, *note next(): 775, which takes no arguments and returns
the next value.  When there are no more values to be returned, calling
*note next(): 775. should raise the *note StopIteration: 581. exception.

     >>> 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
     >>>

In 2.2, Python’s *note for: cfa. statement no longer expects a sequence;
it expects something for which *note iter(): ded. will return an
iterator.  For backward compatibility and convenience, an iterator is
automatically constructed for sequences that don’t implement *note
__iter__(): 608. or a *note tp_iter: ef2. slot, so ‘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:

     >>> L = [1,2,3]
     >>> i = iter(L)
     >>> a,b,c = i
     >>> a,b,c
     (1, 2, 3)

Iterator support has been added to some of Python’s basic types.
Calling *note iter(): ded. on a dictionary will return an iterator which
loops over its keys:

     >>> 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

That’s just the default behaviour.  If you want to iterate over keys,
values, or key/value pairs, you can explicitly call the ‘iterkeys()’,
‘itervalues()’, or ‘iteritems()’ methods to get an appropriate iterator.
In a minor related change, the *note in: 179. operator now works on
dictionaries, so ‘key in dict’ is now equivalent to ‘dict.has_key(key)’.

Files also provide an iterator, which calls the *note readline(): de.
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:

     for line in file:
         # do something for each line
         ...

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 *note next(): 775. method.

也參考
......

PEP 234(1) - Iterators

     由 Ka-Ping Yee 和 GvR 撰写；由 Python Labs 小组（主要由 GvR 和 Tim
     Peters）实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0234


File: python.info,  Node: PEP 255 Simple Generators<2>,  Next: PEP 237 统一长整数和整数<2>,  Prev: PEP 234 Iterators,  Up: Python 2 2 有什么新变化

1.16.4 PEP 255: Simple Generators
---------------------------------

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 *note return: 2c8.
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.

Here’s the simplest example of a generator function:

     def generate_ints(N):
         for i in range(N):
             yield i

A new keyword, *note yield: 2c7, was introduced for generators.  Any
function containing a ‘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 ‘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 *note yield: 2c7. statement, the generator
outputs the value of ‘i’, similar to a *note return: 2c8. statement.
The big difference between ‘yield’ and a ‘return’ statement is that on
reaching a ‘yield’ the generator’s state of execution is suspended and
local variables are preserved.  On the next call to the generator’s
‘next()’ method, the function will resume executing immediately after
the ‘yield’ statement.  (For complicated reasons, the ‘yield’ statement
isn’t allowed inside the ‘try’ block of a *note try: e37...*note
finally: 2bc. statement; read PEP 255(1) for a full explanation of the
interaction between ‘yield’ and exceptions.)

Here’s a sample usage of the ‘generate_ints()’ generator:

     >>> 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

You could equally write ‘for i in generate_ints(5)’, or ‘a,b,c =
generate_ints(3)’.

Inside a generator function, the *note return: 2c8. 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.
‘return’ with a value, such as ‘return 5’, is a syntax error inside a
generator function.  The end of the generator’s results can also be
indicated by raising *note StopIteration: 581. 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 ‘self.count’ to 0, and having the *note next(): 775. method
increment ‘self.count’ and return it.  However, for a moderately
complicated generator, writing a corresponding class would be much
messier.  ‘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.

     # 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

Two other examples in ‘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 (‘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
‘https://www.cs.arizona.edu/icon/docs/ipd266.htm’ gives an idea of what
this looks like:

     sentence := "Store it in the neighboring harbor"
     if (i := find("or", sentence)) > 5 then write(i)

In Icon the ‘find()’ function returns the indexes at which the substring
"or" is found: 3, 23, 33.  In the *note if: eab. statement, ‘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.

也參考
......

PEP 255(2) - 简单生成器

     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.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0255

   (2) https://www.python.org/dev/peps/pep-0255


File: python.info,  Node: PEP 237 统一长整数和整数<2>,  Next: PEP 238 Changing the Division Operator,  Prev: PEP 255 Simple Generators<2>,  Up: Python 2 2 有什么新变化

1.16.5 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 ‘2**32’ bytes, the ‘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 ‘'abc'[1L:]’ would
raise a *note TypeError: 1fe. 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 *note OverflowError: a41. will now
return a long integer as their result.  For example:

     >>> 1234567890123
     1234567890123L
     >>> 2 ** 64
     18446744073709551616L

In most cases, integers and long integers will now be treated
identically.  You can still distinguish them with the *note type(): 6ff.
built-in function, but that’s rarely needed.

也參考
......

PEP 237(1) - 统一长整数和整数

     由 Moshe Zadka 和 Guido van Rossum 撰写 ; 大部分由 Guido van Rossum
     实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0237


File: python.info,  Node: PEP 238 Changing the Division Operator,  Next: Unicode Changes,  Prev: PEP 237 统一长整数和整数<2>,  Up: Python 2 2 有什么新变化

1.16.6 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, ‘/’, 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, ‘3/2’ is 1, not 1.5, and ‘(-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 `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 ‘comp.lang.python’.  I won’t argue for
either side here and will stick to describing what’s implemented in 2.2.
Read PEP 238(1) 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 PEP 238(2).  "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 ‘/’
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 ‘/’; 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:

   * A new operator, ‘//’, is the floor division operator.  (Yes, we
     know it looks like C++’s comment symbol.)  ‘//’ `always' performs
     floor division no matter what the types of its operands are, so ‘1
     // 2’ is 0 and ‘1.0 // 2.0’ is also 0.0.

     ‘//’ is always available in Python 2.2; you don’t need to enable it
     using a ‘__future__’ statement.

   * By including a ‘from __future__ import division’ in a module, the
     ‘/’ operator will be changed to return the result of true division,
     so ‘1/2’ is 0.5.  Without the ‘__future__’ statement, ‘/’ still
     means classic division.  The default meaning of ‘/’ will not change
     until Python 3.0.

   * Classes can define methods called *note __truediv__(): 875. and
     *note __floordiv__(): ef7. to overload the two division operators.
     At the C level, there are also slots in the *note PyNumberMethods:
     e46. structure so extension types can define the two operators.

   * Python 2.2 supports some command-line arguments for testing whether
     code will work with the changed division semantics.  Running python
     with ‘-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.

也參考
......

PEP 238(3) - Changing the Division Operator

     由 Moshe Zadka 和 Guido van Rossum 撰写 ; 由 Guido van Rossum 实现
     。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0238

   (2) https://www.python.org/dev/peps/pep-0238

   (3) https://www.python.org/dev/peps/pep-0238


File: python.info,  Node: Unicode Changes,  Next: PEP 227 Nested Scopes,  Prev: PEP 238 Changing the Division Operator,  Up: Python 2 2 有什么新变化

1.16.7 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 ‘--enable-unicode=ucs4’ to the
configure script.  (It’s also possible to specify ‘--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 ‘unichr()’ function is expanded accordingly.  Using
an interpreter compiled to use UCS-2 (a "narrow Python"), values greater
than 65535 will still cause ‘unichr()’ to raise a *note ValueError: 16d.
exception.  This is all described in PEP 261(1), "Support for ’wide’
Unicode characters"; consult it for further details.

Another change is simpler to explain.  Since their introduction, Unicode
strings have supported an ‘encode()’ method to convert the string to a
selected encoding such as UTF-8 or Latin-1.  A symmetric
‘decode([*encoding*])’ method has been added to 8-bit strings (though
not to Unicode strings) in 2.2.  ‘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 *note
zlib: 14d. module:

     >>> 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'

To convert a class instance to Unicode, a ‘__unicode__()’ method can be
defined by a class, analogous to *note __str__(): ef9.

‘encode()’, ‘decode()’, and ‘__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.

也參考
......

PEP 261(2) - Support for ’wide’ Unicode characters

     Written by Paul Prescod.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0261

   (2) https://www.python.org/dev/peps/pep-0261


File: python.info,  Node: PEP 227 Nested Scopes,  Next: 新增和改进的模块<3>,  Prev: Unicode Changes,  Up: Python 2 2 有什么新变化

1.16.8 PEP 227: Nested Scopes
-----------------------------

In Python 2.1, statically nested scopes were added as an optional
feature, to be enabled by a ‘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:

     def f():
         ...
         def g(value):
             ...
             return g(value-1) + 1
         ...

The function ‘g()’ will always raise a *note NameError: e40. exception,
because the binding of the name ‘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 *note lambda: cf9. expression
clumsier, and this was a problem in practice.  In code which uses
‘lambda’ you can often find local variables being copied by passing them
as the default values of arguments.

     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

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
‘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 *note def: e83, *note class: d32, or
*note import: ce7. 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 ‘from module import *’ and
‘exec’ statements have been made illegal inside a function scope under
certain conditions.  The Python reference manual has said all along that
‘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.  ‘from module import *’ and ‘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 *note lambda: cf9. expressions with
free variables, the compiler will flag this by raising a *note
SyntaxError: 559. exception.

To make the preceding explanation a bit clearer, here’s an example:

     x = 1
     def f():
         # The next line is a syntax error
         exec 'x=2'
         def g():
             return x

Line 4 containing the ‘exec’ statement is a syntax error, since ‘exec’
would define a new local variable named ‘x’ whose value should be
accessed by ‘g()’.

This shouldn’t be much of a limitation, since ‘exec’ is rarely used in
most Python code (and when it is used, it’s often a sign of a poor
design anyway).

也參考
......

PEP 227(1) - Statically Nested Scopes

     由 Jeremy Hylton 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0227


File: python.info,  Node: 新增和改进的模块<3>,  Next: Interpreter Changes and Fixes,  Prev: PEP 227 Nested Scopes,  Up: Python 2 2 有什么新变化

1.16.9 新增和改进的模块
-----------------------

   * The ‘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:

          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)'}, ... ]

     The ‘SimpleXMLRPCServer’ module makes it easy to create
     straightforward XML-RPC servers.  See
     ‘http://xmlrpc.scripting.com/’ for more information about XML-RPC.

   * The new *note hmac: 8e. module implements the HMAC algorithm
     described by RFC 2104(1).  (Contributed by Gerhard Häring.)

   * 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 ‘tm_year’.  The
     enhanced functions include *note stat(): f4, ‘fstat()’,
     ‘statvfs()’, and ‘fstatvfs()’ in the *note os: c4. module, and
     ‘localtime()’, ‘gmtime()’, and ‘strptime()’ in the *note time: 10c.
     module.

     For example, to obtain a file’s size using the old tuples, you’d
     end up writing something like ‘file_size =
     os.stat(filename)[stat.ST_SIZE]’, but now this can be written more
     clearly as ‘file_size = os.stat(filename).st_size’.

     The original patch for this feature was contributed by Nick
     Mathewson.

   * 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.)

   * The *note socket: ef. module can be compiled to support IPv6;
     specify the ‘--enable-ipv6’ option to Python’s configure script.
     (Contributed by Jun-ichiro "itojun" Hagino.)

   * Two new format characters were added to the *note struct: f8.
     module for 64-bit integers on platforms that support the C ‘long
     long’ type.  ‘q’ is for a signed 64-bit integer, and ‘Q’ is for an
     unsigned one.  The value is returned in Python’s long integer type.
     (Contributed by Tim Peters.)

   * In the interpreter’s interactive mode, there’s a new built-in
     function *note help(): 175. that uses the *note pydoc: d9. module
     introduced in Python 2.1 to provide interactive help.
     ‘help(object)’ displays any available help text about `object'.
     *note help(): 175. 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 *note pydoc: d9. module.)

   * Various bugfixes and performance improvements have been made to the
     SRE engine underlying the *note re: dd. module.  For example, the
     *note re.sub(): 579. and *note re.split(): 4d0. functions have been
     rewritten in C. Another contributed patch speeds up certain Unicode
     character ranges by a factor of two, and a new ‘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.)

   * The *note smtplib: ed. module now supports RFC 2487(2), "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.  *note smtplib: ed. also supports SMTP authentication.
     (Contributed by Gerhard Häring.)

   * The *note imaplib: 97. module, maintained by Piers Lauder, has
     support for several new extensions: the NAMESPACE extension defined
     in RFC 2342(3), SORT, GETACL and SETACL. (Contributed by Anthony
     Baxter and Michel Pelletier.)

   * The ‘rfc822’ module’s parsing of email addresses is now compliant
     with RFC 2822(4), an update to RFC 822(5).  (The module’s name is
     `not' going to be changed to ‘rfc2822’.)  A new package, *note
     email: 67, has also been added for parsing and generating e-mail
     messages.  (Contributed by Barry Warsaw, and arising out of his
     work on Mailman.)

   * The *note difflib: 36. module now contains a new ‘Differ’ class for
     producing human-readable lists of changes (a "delta") between two
     sequences of lines of text.  There are also two generator
     functions, ‘ndiff()’ and ‘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.)

   * New constants ‘ascii_letters’, ‘ascii_lowercase’, and
     ‘ascii_uppercase’ were added to the *note string: f6. module.
     There were several modules in the standard library that used
     ‘string.letters’ to mean the ranges A-Za-z, but that assumption is
     incorrect when locales are in use, because ‘string.letters’ varies
     depending on the set of legal characters defined by the current
     locale.  The buggy modules have all been fixed to use
     ‘ascii_letters’ instead.  (Reported by an unknown person; fixed by
     Fred L. Drake, Jr.)

   * The *note mimetypes: b2. module now makes it easier to use
     alternative MIME-type databases by the addition of a ‘MimeTypes’
     class, which takes a list of filenames to be parsed.  (Contributed
     by Fred L. Drake, Jr.)

   * A ‘Timer’ class was added to the *note threading: 10b. module that
     allows scheduling an activity to happen at some future time.
     (Contributed by Itamar Shtull-Trauring.)

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2104.html

   (2) https://tools.ietf.org/html/rfc2487.html

   (3) https://tools.ietf.org/html/rfc2342.html

   (4) https://tools.ietf.org/html/rfc2822.html

   (5) https://tools.ietf.org/html/rfc822.html


File: python.info,  Node: Interpreter Changes and Fixes,  Next: Other Changes and Fixes<3>,  Prev: 新增和改进的模块<3>,  Up: Python 2 2 有什么新变化

1.16.10 Interpreter Changes and Fixes
-------------------------------------

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.

   * 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, *note
     PyEval_SetProfile(): efd. and *note PyEval_SetTrace(): efe.  The
     existing *note sys.setprofile(): eff. and *note sys.settrace():
     f00. functions still exist, and have simply been changed to use the
     new C-level interface.  (Contributed by Fred L. Drake, Jr.)

   * Another low-level API, primarily of interest to implementors of
     Python debuggers and development tools, was added.  *note
     PyInterpreterState_Head(): f01. and *note
     PyInterpreterState_Next(): f02. let a caller walk through all the
     existing interpreter objects; *note
     PyInterpreterState_ThreadHead(): f03. and *note
     PyThreadState_Next(): f04. allow looping over all the thread states
     for a given interpreter.  (Contributed by David Beazley.)

   * 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 `not' participate in garbage collection, so
     updating them for 2.2 should be considered fairly high priority.

     To upgrade an extension module to the new API, perform the
     following steps:

   * Rename ‘Py_TPFLAGS_GC()’ to ‘PyTPFLAGS_HAVE_GC()’.

   * 
     Use *note PyObject_GC_New(): 3f3. or *note PyObject_GC_NewVar(): 3f4. to allocate

          objects, and *note PyObject_GC_Del(): f05. to deallocate them.

   * 
     Rename ‘PyObject_GC_Init()’ to *note PyObject_GC_Track(): f06. and

          ‘PyObject_GC_Fini()’ to *note PyObject_GC_UnTrack(): f07.

   * Remove ‘PyGC_HEAD_SIZE()’ from object size calculations.

   * Remove calls to ‘PyObject_AS_GC()’ and ‘PyObject_FROM_GC()’.

   * A new ‘et’ format sequence was added to *note PyArg_ParseTuple():
     393.; ‘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 ‘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.)

   * A different argument parsing function, *note PyArg_UnpackTuple():
     f08, 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
     *note PyObject*: 5b4. variables that will be filled in with
     argument values.

   * Two new flags *note METH_NOARGS: eda. and *note METH_O: f09. 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 *note METH_VARARGS: f0a.  Also, the old ‘METH_OLDARGS’
     style of writing C methods is now officially deprecated.

   * Two new wrapper functions, *note PyOS_snprintf(): f0b. and *note
     PyOS_vsnprintf(): f0c. were added to provide cross-platform
     implementations for the relatively new ‘snprintf()’ and
     ‘vsnprintf()’ C lib APIs.  In contrast to the standard ‘sprintf()’
     and ‘vsprintf()’ functions, the Python versions check the bounds of
     the buffer used to protect against buffer overruns.  (Contributed
     by M.-A. Lemburg.)

   * The *note _PyTuple_Resize(): f0d. 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.


File: python.info,  Node: Other Changes and Fixes<3>,  Next: 致谢<6>,  Prev: Interpreter Changes and Fixes,  Up: Python 2 2 有什么新变化

1.16.11 Other Changes and Fixes
-------------------------------

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.

Some of the more notable changes are:

   * 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 ‘--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
     ‘/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 ‘setup.py’.
     People who want to experiment with these modules can uncomment them
     manually.

   * Keyword arguments passed to built-in functions that don’t take them
     now cause a *note TypeError: 1fe. exception to be raised, with the
     message "`function' takes no keyword arguments".

   * 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 *note ReferenceError: f0f. exception has
     therefore moved from the *note weakref: 131. module to become a
     built-in exception.

   * A new script, ‘Tools/scripts/cleanfuture.py’ by Tim Peters,
     automatically removes obsolete ‘__future__’ statements from Python
     source code.

   * An additional `flags' argument has been added to the built-in
     function *note compile(): 2e7, so the behaviour of ‘__future__’
     statements can now be correctly observed in simulated shells, such
     as those presented by IDLE and other development environments.
     This is described in PEP 264(1).  (Contributed by Michael Hudson.)

   * 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.

   * 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
     ‘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.)

   * Large file support is now enabled on Windows.  (Contributed by Tim
     Peters.)

   * The ‘Tools/scripts/ftpmirror.py’ script now parses a ‘.netrc’ file,
     if you have one.  (Contributed by Mike Romberg.)

   * Some features of the object returned by the ‘xrange()’ function are
     now deprecated, and trigger warnings when they’re accessed; they’ll
     disappear in Python 2.3.  ‘xrange’ objects tried to pretend they
     were full sequence types by supporting slicing, sequence
     multiplication, and the *note in: 179. operator, but these features
     were rarely used and therefore buggy.  The ‘tolist()’ method and
     the ‘start’, ‘stop’, and ‘step’ attributes are also being
     deprecated.  At the C level, the fourth argument to the
     ‘PyRange_New()’ function, ‘repeat’, has also been deprecated.

   * 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.

   * 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 `is' progress...)

   * 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.)

   * Files ending in ‘.pyw’ can now be imported on Windows.  ‘.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.)

   * On platforms where Python uses the C ‘dlopen()’ function to load
     extension modules, it’s now possible to set the flags used by
     ‘dlopen()’ using the *note sys.getdlopenflags(): f10. and *note
     sys.setdlopenflags(): b41. functions.  (Contributed by Bram Stolk.)

   * The *note pow(): 2cf. built-in function no longer supports 3
     arguments when floating-point numbers are supplied.  ‘pow(x, y, z)’
     returns ‘(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 ‘pow(2.0, 8.0, 7.0)’ will now raise a
     *note TypeError: 1fe. exception.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0264


File: python.info,  Node: 致谢<6>,  Prev: Other Changes and Fixes<3>,  Up: Python 2 2 有什么新变化

1.16.12 致谢
------------

作者感谢以下人员为本文的各种草案提供建议，更正和帮助： 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.


File: python.info,  Node: Python 2 1 有什么新变化,  Next: Python 2 0 有什么新变化,  Prev: Python 2 2 有什么新变化,  Up: Python 有什麼新功能？

1.17 Python 2.1 有什么新变化
============================


作者: A.M. Kuchling

* Menu:

* 簡介: 簡介<2>.
* PEP 227; Nested Scopes: PEP 227 Nested Scopes<2>.
* PEP 236; __future__ Directives: PEP 236 __future__ Directives.
* PEP 207; Rich Comparisons: PEP 207 Rich Comparisons.
* PEP 230; Warning Framework: PEP 230 Warning Framework.
* PEP 229; New Build System: PEP 229 New Build System.
* PEP 205; Weak References: PEP 205 Weak References.
* PEP 232; Function Attributes: PEP 232 Function Attributes.
* PEP 235; Importing Modules on Case-Insensitive Platforms: PEP 235 Importing Modules on Case-Insensitive Platforms.
* 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>.
* Other Changes and Fixes: Other Changes and Fixes<4>.
* 致谢: 致谢<7>.


File: python.info,  Node: 簡介<2>,  Next: PEP 227 Nested Scopes<2>,  Up: Python 2 1 有什么新变化

1.17.1 簡介
-----------

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日发布。


File: python.info,  Node: PEP 227 Nested Scopes<2>,  Next: PEP 236 __future__ Directives,  Prev: 簡介<2>,  Up: Python 2 1 有什么新变化

1.17.2 PEP 227: Nested Scopes
-----------------------------

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:

     def f():
         ...
         def g(value):
             ...
             return g(value-1) + 1
         ...

The function ‘g()’ will always raise a *note NameError: e40. exception,
because the binding of the name ‘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 *note lambda: cf9. expression
clumsier, and this was a problem in practice.  In code which uses *note
lambda: cf9. you can often find local variables being copied by passing
them as the default values of arguments.

     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

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
‘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 *note def: e83, *note class: d32, or
*note import: ce7. 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 ‘from module import *’ and
‘exec’ statements have been made illegal inside a function scope under
certain conditions.  The Python reference manual has said all along that
‘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.  ‘from module import *’ and ‘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 *note lambda: cf9. expressions with
free variables, the compiler will flag this by raising a *note
SyntaxError: 559. exception.

To make the preceding explanation a bit clearer, here’s an example:

     x = 1
     def f():
         # The next line is a syntax error
         exec 'x=2'
         def g():
             return x

Line 4 containing the ‘exec’ statement is a syntax error, since ‘exec’
would define a new local variable named ‘x’ whose value should be
accessed by ‘g()’.

This shouldn’t be much of a limitation, since ‘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
PEP 236(1).  (See the following section for further discussion of PEP
236(2).)  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.

也參考
......

PEP 227(3) - Statically Nested Scopes

     由 Jeremy Hylton 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0236

   (2) https://www.python.org/dev/peps/pep-0236

   (3) https://www.python.org/dev/peps/pep-0227


File: python.info,  Node: PEP 236 __future__ Directives,  Next: PEP 207 Rich Comparisons,  Prev: PEP 227 Nested Scopes<2>,  Up: Python 2 1 有什么新变化

1.17.3 PEP 236: __future__ Directives
-------------------------------------

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 ‘from...import’ statement using the reserved module
name *note __future__: 0.  Nested scopes can be enabled by the following
statement:

     from __future__ import nested_scopes

While it looks like a normal *note import: ce7. 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 ‘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.

也參考
......

PEP 236(1) - Back to the *note __future__: 0.

     由 Tim Peters 撰写，主要由 Jeremy Hylton 实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0236


File: python.info,  Node: PEP 207 Rich Comparisons,  Next: PEP 230 Warning Framework,  Prev: PEP 236 __future__ Directives,  Up: Python 2 1 有什么新变化

1.17.4 PEP 207: Rich Comparisons
--------------------------------

In earlier versions, Python’s support for implementing comparisons on
user-defined classes and extension types was quite simple.  Classes
could implement a ‘__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 ‘<’,
‘<=’, ‘>’, ‘>=’, ‘==’, and ‘!=’ operations.  The new magic method names
are:

运算            方法名称
                
-------------------------------------
                
‘<’             *note __lt__(): cfe.
                
                
‘<=’            *note __le__(): d68.
                
                
‘>’             *note __gt__(): d69.
                
                
‘>=’            *note __ge__(): d6a.
                
                
‘==’            *note __eq__(): 44b.
                
                
‘!=’            *note __ne__(): f18.
                

(The magic methods are named after the corresponding Fortran operators
‘.LT.’.  ‘.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 ‘method(self, other)’, where
‘self’ will be the object on the left-hand side of the operator, while
‘other’ will be the object on the right-hand side.  For example, the
expression ‘A < B’ will cause ‘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 ‘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 ‘"<"’, ‘"<="’,
‘">"’, ‘">="’, ‘"=="’, or ‘"!="’.  If called without the optional third
argument, ‘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 ‘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 PEP 207(1), or to 2.1’s C API documentation, for the
full list of related functions.

也參考
......

PEP 207(2) - Rich Comparisons

     Written by Guido van Rossum, heavily based on earlier work by David
     Ascher, and implemented by Guido van Rossum.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0207

   (2) https://www.python.org/dev/peps/pep-0207


File: python.info,  Node: PEP 230 Warning Framework,  Next: PEP 229 New Build System,  Prev: PEP 207 Rich Comparisons,  Up: Python 2 1 有什么新变化

1.17.5 PEP 230: Warning Framework
---------------------------------

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 *note warnings: 12f. 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 ‘regex’ module is deprecated, so
importing it causes a warning to be printed:

     >>> import regex
     __main__:1: DeprecationWarning: the regex module
              is deprecated; please use the re module
     >>>

Warnings can be issued by calling the *note warnings.warn(): f1a.
function:

     warnings.warn("feature X no longer supported")

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
‘regex’ module and not want to spare the time to convert it to use the
*note re: dd. module right now.  The warning can be suppressed by
calling

     import warnings
     warnings.filterwarnings(action = 'ignore',
                             message='.*regex module is deprecated',
                             category=DeprecationWarning,
                             module = '__main__')

This adds a filter that will apply only to warnings of the class *note
DeprecationWarning: 15a. triggered in the *note __main__: 1. module, and
applies a regular expression to only match the message about the ‘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.

也參考
......

PEP 5(1) - Guidelines for Language Evolution

     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.

PEP 230(2) - Warning Framework

     由 Guido van Rossum 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0005

   (2) https://www.python.org/dev/peps/pep-0230


File: python.info,  Node: PEP 229 New Build System,  Next: PEP 205 Weak References,  Prev: PEP 230 Warning Framework,  Up: Python 2 1 有什么新变化

1.17.6 PEP 229: New Build System
--------------------------------

When compiling Python, the user had to go in and edit the
‘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 ‘Modules/Setup’ file in order to enable
modules, a ‘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 ‘Modules/Setup’, the ‘setup.py’
script won’t attempt to compile that module and will defer to the
‘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
‘Python/’, ‘Parser/’, ‘Objects/’, and ‘Modules/’ subdirectories.  This
makes building Python faster and also makes hacking the Makefiles
clearer and simpler.

也參考
......

PEP 229(1) - Using Distutils to Build Python

     由 A.M. Kuchling 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0229


File: python.info,  Node: PEP 205 Weak References,  Next: PEP 232 Function Attributes,  Prev: PEP 229 New Build System,  Up: Python 2 1 有什么新变化

1.17.7 PEP 205: Weak References
-------------------------------

Weak references, available through the *note weakref: 131. 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 ‘f(x)’ by storing the function’s argument and its
result in a dictionary:

     _cache = {}
     def memoize(x):
         if _cache.has_key(x):
             return _cache[x]

         retval = f(x)

         # Cache the returned object
         _cache[x] = retval

         return retval

This version works for simple things such as integers, but it has a side
effect; the ‘_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 ‘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 `obj' is created by calling ‘wr =
weakref.ref(obj)’.  The object being referred to is returned by calling
the weak reference as if it were a function: ‘wr()’.  It will return the
referenced object, or ‘None’ if the object no longer exists.

This makes it possible to write a ‘memoize()’ function whose cache
doesn’t keep objects alive, by storing weak references in the cache.

     _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

The *note weakref: 131. 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
‘weakref.ReferenceError’ exception to be raised.

     proxy = weakref.proxy(obj)
     proxy.attr   # Equivalent to obj.attr
     proxy.meth() # Equivalent to obj.meth()
     del obj
     proxy.attr   # raises weakref.ReferenceError

也參考
......

PEP 205(1) - 弱引用

     由 Fred L. Drake, Jr 撰写并实现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0205


File: python.info,  Node: PEP 232 Function Attributes,  Next: PEP 235 Importing Modules on Case-Insensitive Platforms,  Prev: PEP 205 Weak References,  Up: Python 2 1 有什么新变化

1.17.8 PEP 232: Function Attributes
-----------------------------------

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 ‘__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:

     def f(): pass

     f.publish = 1
     f.secure = 1
     f.grammar = "A ::= B (C D)*"

The dictionary containing attributes can be accessed as the function’s
*note __dict__: 5f5.  Unlike the *note __dict__: 5f5. attribute of class
instances, in functions you can actually assign a new dictionary to
*note __dict__: 5f5, though the new value is restricted to a regular
Python dictionary; you `can’t' be tricky and set it to a ‘UserDict’
instance, or any other random object that behaves like a mapping.

也參考
......

PEP 232(1) - Function Attributes

     由 Barry Warsaw 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0232


File: python.info,  Node: PEP 235 Importing Modules on Case-Insensitive Platforms,  Next: PEP 217 Interactive Display Hook,  Prev: PEP 232 Function Attributes,  Up: Python 2 1 有什么新变化

1.17.9 PEP 235: Importing Modules on Case-Insensitive Platforms
---------------------------------------------------------------

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 ‘FILE.PY’ and ‘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 *note import: ce7. 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 *note
ImportError: 16c. if no such file is found, so ‘import file’ will not
import a module named ‘FILE.PY’.  Case-insensitive matching can be
requested by setting the *note PYTHONCASEOK: 232. environment variable
before starting the Python interpreter.


File: python.info,  Node: PEP 217 Interactive Display Hook,  Next: PEP 208 New Coercion Model,  Prev: PEP 235 Importing Modules on Case-Insensitive Platforms,  Up: Python 2 1 有什么新变化

1.17.10 PEP 217: Interactive Display Hook
-----------------------------------------

When using the Python interpreter interactively, the output of commands
is displayed using the built-in *note repr(): 8b9. function.  In Python
2.1, the variable *note sys.displayhook(): f20. can be set to a callable
object which will be called instead of *note repr(): 8b9.  For example,
you can set it to a special pretty-printing function:

     >>> # 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>]
     >>>

也參考
......

PEP 217(1) - Display Hook for Interactive Use

     由 Moshe Zadka 撰写并实现

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0217


File: python.info,  Node: PEP 208 New Coercion Model,  Next: PEP 241 Metadata in Python Packages,  Prev: PEP 217 Interactive Display Hook,  Up: Python 2 1 有什么新变化

1.17.11 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 ‘Py_TPFLAGS_CHECKTYPES’ in
their ‘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 ‘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
‘Py_NotImplemented’, then a *note TypeError: 1fe. will be raised.
Numeric methods written in Python can also return ‘Py_NotImplemented’,
causing the interpreter to act as if the method did not exist (perhaps
raising a *note TypeError: 1fe, perhaps trying another object’s numeric
methods).

也參考
......

PEP 208(1) - 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.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0208


File: python.info,  Node: PEP 241 Metadata in Python Packages,  Next: 新增和改进的模块<4>,  Prev: PEP 208 New Coercion Model,  Up: Python 2 1 有什么新变化

1.17.12 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 ‘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 ‘sdist’ command will include a file named
‘PKG-INFO’ containing information about the package such as its name,
version, and author (metadata, in cataloguing terminology).  PEP 241(1)
contains the full list of fields that can be present in the ‘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 ‘sdist’ and ‘bdist_*’ commands could support an ‘upload’
option that would automatically upload your package to a catalog server.

You can start creating packages containing ‘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 PEP 241(2), as well as various
bugfixes and enhancements.  It will be available from the Distutils SIG
at ‘https://www.python.org/community/sigs/current/distutils-sig/’.

也參考
......

PEP 241(3) - Metadata for Python Software Packages

     由 A.M. Kuchling 撰写并实现。

PEP 243(4) - Module Repository Upload Mechanism

     Written by Sean Reifschneider, this draft PEP describes a proposed
     mechanism for uploading Python packages to a central server.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0241

   (2) https://www.python.org/dev/peps/pep-0241

   (3) https://www.python.org/dev/peps/pep-0241

   (4) https://www.python.org/dev/peps/pep-0243


File: python.info,  Node: 新增和改进的模块<4>,  Next: Other Changes and Fixes<4>,  Prev: PEP 241 Metadata in Python Packages,  Up: Python 2 1 有什么新变化

1.17.13 新增和改进的模块
------------------------

   * Ka-Ping Yee contributed two new modules: ‘inspect.py’, a module for
     getting information about live Python code, and ‘pydoc.py’, a
     module for interactively converting docstrings to HTML or text.  As
     a bonus, ‘Tools/scripts/pydoc’, which is now automatically
     installed, uses ‘pydoc.py’ to display documentation given a Python
     module, package, or class name.  For example, ‘pydoc xml.dom’
     displays the following:

          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:
                ...

     ‘pydoc’ also includes a Tk-based interactive help browser.  ‘pydoc’
     quickly becomes addictive; try it out!

   * Two different modules for unit testing were added to the standard
     library.  The *note doctest: 66. 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 ‘http://pyunit.sourceforge.net/’
     for more information about PyUnit.

   * The *note difflib: 36. module contains a class, ‘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 ‘diff’ program, and
     in fact the sample program ‘Tools/scripts/ndiff.py’ demonstrates
     how to write such a script.

   * *note curses.panel: 2d, 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.

   * The PyXML package has gone through a few releases since Python 2.0,
     and Python 2.1 includes an updated version of the *note xml: 13c.
     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 ‘minidom’ module.

   * Ping also contributed another hook for handling uncaught
     exceptions.  *note sys.excepthook(): f24. can be set to a callable
     object.  When an exception isn’t caught by any *note try:
     e37...*note except: c10. blocks, the exception will be passed to
     *note sys.excepthook(): f24, 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.

   * Various functions in the *note time: 10c. module, such as
     ‘asctime()’ and ‘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, ‘time.asctime()’ can be used, instead of the lengthier
     ‘time.asctime(time.localtime(time.time()))’ that was previously
     required.

     This change was proposed and implemented by Thomas Wouters.

   * The *note ftplib: 82. 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 *note ftplib: 82. 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 ‘set_pasv(0)’ on FTP objects to disable passive mode.

   * Support for raw socket access has been added to the *note socket:
     ef. module, contributed by Grant Edwards.

   * The *note pstats: d4. 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.

   * A new implementation-dependent function, ‘sys._getframe([depth])’,
     has been added to return a given frame object from the current call
     stack.  *note sys._getframe(): f25. returns the frame at the top of
     the call stack; if the optional integer argument `depth' is
     supplied, the function returns the frame that is `depth' calls
     below the top of the stack.  For example, ‘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.


File: python.info,  Node: Other Changes and Fixes<4>,  Next: 致谢<7>,  Prev: 新增和改进的模块<4>,  Up: Python 2 1 有什么新变化

1.17.14 Other Changes and Fixes
-------------------------------

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:

   * A specialized object allocator is now optionally available, that
     should be faster than the system ‘malloc()’ and have less memory
     overhead.  The allocator uses C’s ‘malloc()’ function to get large
     pools of memory, and then fulfills smaller memory requests from
     these pools.  It can be enabled by providing the ‘--with-pymalloc’
     option to the ‘configure’ script; see ‘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 ‘malloc()’ and ‘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 ‘malloc()’ and ‘free()’ any more,
     and calling the wrong function to free memory will get you a core
     dump.  For example, if memory was allocated using ‘PyMem_New()’, it
     has to be freed using ‘PyMem_Del()’, not ‘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.

   * 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 *note readline(): de.
     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 ‘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, ‘xreadlines()’, is
     similar to the existing ‘xrange()’ built-in.  ‘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 ‘readlines()’ method does.  You’d
     use it like this:

          for line in sys.stdin.xreadlines():
              # ... do something for each line ...
              ...

     For a fuller discussion of the line I/O changes, see the python-dev
     summary for January 1–15, 2001 at
     ‘https://mail.python.org/pipermail/python-dev/2001-January/’.

   * A new method, ‘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.  ‘D.popitem()’
     removes a random ‘(key, value)’ pair from the dictionary ‘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.

   * Modules can now control which names are imported when ‘from module
     import *’ is used, by defining an ‘__all__’ attribute containing a
     list of names that will be imported.  One common complaint is that
     if the module imports other modules such as *note sys: fd. or *note
     string: f6, ‘from module import *’ will add them to the importing
     module’s namespace.  To fix this, simply list the public names in
     ‘__all__’:

          # List public names
          __all__ = ['Database', 'open']

     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.

   * Applying *note repr(): 8b9. to strings previously used octal
     escapes for non-printable characters; for example, a newline was
     ‘'\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 ‘\n’, ‘\t’,
     ‘\r’ escapes for the appropriate characters, and implemented this
     new formatting.

   * 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.

   * C extensions which import other modules have been changed to use
     ‘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.

   * The size of the Unicode character database was shrunk by another
     340K thanks to Fredrik Lundh.

   * Some new ports were contributed: MacOS X (by Steven Majewski),
     Cygwin (by Jason Tishler); RISCOS (by Dietmar Schwertberger);
     Unixware 7 (by Billy G. Allie).

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.


File: python.info,  Node: 致谢<7>,  Prev: Other Changes and Fixes<4>,  Up: Python 2 1 有什么新变化

1.17.15 致谢
------------

作者感谢以下人员对本文的各种草案提出建议： Graeme Cross, David Goodger,
Jay Graves, Michael Hudson, Marc-André Lemburg, Fredrik Lundh, Neil
Schemenauer, Thomas Wouters.


File: python.info,  Node: Python 2 0 有什么新变化,  Next: Changelog（更動日誌）,  Prev: Python 2 1 有什么新变化,  Up: Python 有什麼新功能？

1.18 Python 2.0 有什么新变化
============================


作者: A.M. Kuchling 和 Moshe Zadka

* Menu:

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


File: python.info,  Node: 簡介<3>,  Next: What About Python 1 6?,  Up: Python 2 0 有什么新变化

1.18.1 簡介
-----------

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.


File: python.info,  Node: What About Python 1 6?,  Next: 新开发流程,  Prev: 簡介<3>,  Up: Python 2 0 有什么新变化

1.18.2 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.


File: python.info,  Node: 新开发流程,  Next: Unicode<2>,  Prev: What About Python 1 6?,  Up: Python 2 0 有什么新变化

1.18.3 新开发流程
-----------------

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
‘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 PEP 1(1), "PEP Purpose and
Guidelines":

     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.

Read the rest of PEP 1(2) 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 ‘https://www.python.org/dev/peps/’.  As of
September 2000, there are 25 PEPS, ranging from PEP 201(3), "Lockstep
Iteration", to PEP 225, "Elementwise/Objectwise Operators".

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0001

   (2) https://www.python.org/dev/peps/pep-0001

   (3) https://www.python.org/dev/peps/pep-0201


File: python.info,  Node: Unicode<2>,  Next: 串列綜合運算（List Comprehension）,  Prev: 新开发流程,  Up: Python 2 0 有什么新变化

1.18.4 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 PEP 100(1), "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 ‘u"string"’.
Arbitrary Unicode characters can be written using a new escape sequence,
‘\uHHHH’, where `HHHH' is a 4-digit hexadecimal number from 0000 to
FFFF. The existing ‘\xHHHH’ escape sequence can also be used, and octal
escapes can be used for characters up to U+01FF, which is represented by
‘\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 ‘encode( [encoding] )’ method that returns an
8-bit string in the desired encoding.  Encodings are named by strings,
such as ‘'ascii'’, ‘'utf-8'’, ‘'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
‘sys.setdefaultencoding(encoding)’ function in a customized version of
‘site.py’.

Combining 8-bit and Unicode strings always coerces to Unicode, using the
default ASCII encoding; the result of ‘'a' + u'bc'’ is ‘u'abc'’.

New built-in functions have been added, and existing built-ins modified
to support Unicode:

   * ‘unichr(ch)’ returns a Unicode string 1 character long, containing
     the character `ch'.

   * ‘ord(u)’, where `u' is a 1-character regular or Unicode string,
     returns the number of the character as an integer.

   * ‘unicode(string [, encoding] [, errors] )’ creates a Unicode string
     from an 8-bit string.  ‘encoding’ is a string naming the encoding
     to use.  The ‘errors’ parameter specifies the treatment of
     characters that are invalid for the current encoding; passing
     ‘'strict'’ as the value causes an exception to be raised on any
     encoding error, while ‘'ignore'’ causes errors to be silently
     ignored and ‘'replace'’ uses U+FFFD, the official replacement
     character, in case of any problems.

   * The ‘exec’ statement, and various built-ins such as ‘eval()’,
     ‘getattr()’, and ‘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.)

A new module, *note unicodedata: 123, provides an interface to Unicode
character properties.  For example, ‘unicodedata.category(u'A')’ returns
the 2-character string ’Lu’, the ’L’ denoting it’s a letter, and ’u’
meaning that it’s uppercase.  ‘unicodedata.bidirectional(u'\u0660')’
returns ’AN’, meaning that U+0660 is an Arabic number.

The *note codecs: 1b. 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 ‘codecs.lookup(encoding)’ function,
which returns a 4-element tuple: ‘(encode_func, decode_func,
stream_reader, stream_writer)’.

   * `encode_func' is a function that takes a Unicode string, and
     returns a 2-tuple ‘(string, length)’.  `string' is an 8-bit string
     containing a portion (perhaps all) of the Unicode string converted
     into the given encoding, and `length' tells you how much of the
     Unicode string was converted.

   * `decode_func' is the opposite of `encode_func', taking an 8-bit
     string and returning a 2-tuple ‘(ustring, length)’, consisting of
     the resulting Unicode string `ustring' and the integer `length'
     telling how much of the 8-bit string was consumed.

   * `stream_reader' is a class that supports decoding input from a
     stream.  `stream_reader(file_obj)' returns an object that supports
     the ‘read()’, *note readline(): de, and ‘readlines()’ methods.
     These methods will all translate from the given encoding and return
     Unicode strings.

   * `stream_writer', similarly, is a class that supports encoding
     output to a stream.  `stream_writer(file_obj)' returns an object
     that supports the ‘write()’ and ‘writelines()’ methods.  These
     methods expect Unicode strings, translating them to the given
     encoding on output.

For example, the following code writes a Unicode string into a file,
encoding it as UTF-8:

     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()

The following code would then read UTF-8 input from the file:

     input = UTF8_streamreader( open( '/tmp/output', 'rb') )
     print repr(input.read())
     input.close()

Unicode-aware regular expressions are available through the *note re:
dd. module, which has a new underlying implementation called SRE written
by Fredrik Lundh of Secret Labs AB.

A ‘-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.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0100


File: python.info,  Node: 串列綜合運算（List Comprehension）,  Next: Augmented Assignment,  Prev: Unicode<2>,  Up: Python 2 0 有什么新变化

1.18.5 串列綜合運算（List Comprehension）
-----------------------------------------

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 *note map(): cf7. and *note filter(): cf8. 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:

     # 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)

Because of Python’s scoping rules, a default argument is used so that
the anonymous function created by the *note lambda: cf9. expression
knows what substring is being searched for.  List comprehensions make
this cleaner:

     sublist = [ s for s in L if string.find(s, S) != -1 ]

List comprehensions have the form:

     [ expression for expr in sequence1
                  for expr2 in sequence2 ...
                  for exprN in sequenceN
                  if condition ]

The ‘for’...‘in’ clauses contain the sequences to be iterated over.  The
sequences do not have to be the same length, because they are `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 `expression'.  The final ‘if’
clause is optional; if present, `expression' is only evaluated and added
to the result if `condition' is true.

To make the semantics very clear, a list comprehension is equivalent to
the following Python code:

     for expr1 in sequence1:
         for expr2 in sequence2:
         ...
             for exprN in sequenceN:
                  if (condition):
                       # Append the value of
                       # the expression to the
                       # resulting list.

This means that when there are multiple ‘for’...‘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:

     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)]

To avoid introducing an ambiguity into Python’s grammar, if `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:

     # Syntax error
     [ x,y for x in seq1 for y in seq2]
     # Correct
     [ (x,y) for x in seq1 for y in seq2]

The idea of list comprehensions originally comes from the functional
programming language Haskell (‘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.


File: python.info,  Node: Augmented Assignment,  Next: 字符串的方法,  Prev: 串列綜合運算（List Comprehension）,  Up: Python 2 0 有什么新变化

1.18.6 Augmented Assignment
---------------------------

Augmented assignment operators, another long-requested feature, have
been added to Python 2.0.  Augmented assignment operators include ‘+=’,
‘-=’, ‘*=’, and so forth.  For example, the statement ‘a += 2’
increments the value of the variable ‘a’ by 2, equivalent to the
slightly lengthier ‘a = a + 2’.

The full list of supported assignment operators is ‘+=’, ‘-=’, ‘*=’,
‘/=’, ‘%=’, ‘**=’, ‘&=’, ‘|=’, ‘^=’, ‘>>=’, and ‘<<=’.  Python classes
can override the augmented assignment operators by defining methods
named *note __iadd__(): f30, *note __isub__(): f31, etc.  For example,
the following ‘Number’ class stores a number and supports using += to
create a new instance with an incremented value.

     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

The *note __iadd__(): f30. 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 ‘awk’, C++,
Java, Perl, and PHP also support them.  The augmented assignment patch
was implemented by Thomas Wouters.


File: python.info,  Node: 字符串的方法,  Next: Garbage Collection of Cycles,  Prev: Augmented Assignment,  Up: Python 2 0 有什么新变化

1.18.7 字符串的方法
-------------------

Until now string-manipulation functionality was in the *note string: f6.
module, which was usually a front-end for the ‘strop’ module written in
C. The addition of Unicode posed a difficulty for the ‘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
‘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.

     >>> 'andrew'.capitalize()
     'Andrew'
     >>> 'hostname'.replace('os', 'linux')
     'hlinuxtname'
     >>> 'moshe'.find('sh')
     2

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 *note string: f6. 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 ‘startswith()’ and
‘endswith()’.  ‘s.startswith(t)’ is equivalent to ‘s[:len(t)] == t’,
while ‘s.endswith(t)’ is equivalent to ‘s[-len(t):] == t’.

One other method which deserves special mention is ‘join()’.  The
‘join()’ method of a string receives one parameter, a sequence of
strings, and is equivalent to the ‘string.join()’ function from the old
*note string: f6. module, with the arguments reversed.  In other words,
‘s.join(seq)’ is equivalent to the old ‘string.join(seq, s)’.


File: python.info,  Node: Garbage Collection of Cycles,  Next: 其他核心变化,  Prev: 字符串的方法,  Up: Python 2 0 有什么新变化

1.18.8 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:

     instance = SomeClass()
     instance.myself = instance

After the above two lines of code have been executed, the reference
count of ‘instance’ is 2; one reference is from the variable named
‘'instance'’, and the other is from the ‘myself’ attribute of the
instance.

If the next line of code is ‘del instance’, what happens?  The reference
count of ‘instance’ is decreased by 1, so it has a reference count of 1;
the reference in the ‘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 *note gc: 84. 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
‘--without-cycle-gc’ switch when running the ‘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".


File: python.info,  Node: 其他核心变化,  Next: 移植 Python 2 0,  Prev: Garbage Collection of Cycles,  Up: Python 2 0 有什么新变化

1.18.9 其他核心变化
-------------------

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:

* Minor Language Changes::
* Changes to Built-in Functions::


File: python.info,  Node: Minor Language Changes,  Next: Changes to Built-in Functions,  Up: 其他核心变化

1.18.9.1 Minor Language Changes
...............................

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 ‘apply()’ built-in function: ‘apply(f,
args, kw)’ calls the function ‘f()’ with the argument tuple `args' and
the keyword arguments in the dictionary `kw'.  ‘apply()’ is the same in
2.0, but thanks to a patch from Greg Ewing, ‘f(*args, **kw)’ is a
shorter and clearer way to achieve the same effect.  This syntax is
symmetrical with the syntax for defining functions:

     def f(*args, **kw):
         # args is a tuple of positional args,
         # kw is a dictionary of keyword args
         ...

The ‘print’ statement can now have its output directed to a file-like
object by following the ‘print’ with ‘>> file’, similar to the
redirection operator in Unix shells.  Previously you’d either have to
use the ‘write()’ method of the file-like object, which lacks the
convenience and simplicity of ‘print’, or you could assign a new value
to ‘sys.stdout’ and then restore the old value.  For sending output to
standard error, it’s much easier to write this:

     print >> sys.stderr, "Warning: action field not supplied"

Modules can now be renamed on importing them, using the syntax ‘import
module as name’ or ‘from module import name as othername’.  The patch
was submitted by Thomas Wouters.

A new format style is available when using the ‘%’ operator; ’%r’ will
insert the *note repr(): 8b9. of its argument.  This was also added from
symmetry considerations, this time for symmetry with the existing ’%s’
format style, which inserts the *note str(): 205. of its argument.  For
example, ‘'%r %s' % ('abc', 'abc')’ returns a string containing ‘'abc'
abc’.

Previously there was no way to implement a class that overrode Python’s
built-in *note in: 179. operator and implemented a custom version.  ‘obj
in seq’ returns true if `obj' is present in the sequence `seq'; Python
computes this by simply trying every index of the sequence until either
`obj' is found or an *note IndexError: f36. is encountered.  Moshe Zadka
contributed a patch which adds a *note __contains__(): dee. magic method
for providing a custom implementation for ‘in’.  Additionally, new
built-in objects written in C can define what ‘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:

     a = []
     b = []
     a.append(a)
     b.append(b)

The comparison ‘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 ‘cmp(a,b)’ would always produce
an answer, even if a user-defined ‘__cmp__()’ method encountered an
error, since the resulting exception would simply be silently swallowed.

Work has been done on porting Python to 64-bit Windows on the Itanium
processor, mostly by Trent Mick of ActiveState.  (Confusingly,
‘sys.platform’ is still ‘'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
‘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 *note NameError: e40. 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 ‘print’ statement
in both 1.5.2 and 2.0; in 1.5.2 a *note NameError: e40. exception is
raised, while 2.0 raises a new *note UnboundLocalError: f37. exception.
*note UnboundLocalError: f37. is a subclass of *note NameError: e40, so
any existing code that expects *note NameError: e40. to be raised should
still work.

     def f():
         print "i=",i
         i = i + 1
     f()

Two new exceptions, *note TabError: f38. and *note IndentationError:
f39, have been introduced.  They’re both subclasses of *note
SyntaxError: 559, and are raised when Python code is found to be
improperly indented.


File: python.info,  Node: Changes to Built-in Functions,  Prev: Minor Language Changes,  Up: 其他核心变化

1.18.9.2 Changes to Built-in Functions
......................................

A new built-in, ‘zip(seq1, seq2, ...)’, has been added.  *note zip():
cfc. returns a list of tuples where each tuple contains the i-th element
from each of the argument sequences.  The difference between *note
zip(): cfc. and ‘map(None, seq1, seq2)’ is that *note map(): cf7. pads
the sequences with ‘None’ if the sequences aren’t all of the same
length, while *note zip(): cfc. truncates the returned list to the
length of the shortest argument sequence.

The *note int(): 204. and ‘long()’ functions now accept an optional
"base" parameter when the first argument is a string.  ‘int('123', 10)’
returns 123, while ‘int('123', 16)’ returns 291.  ‘int(123, 16)’ raises
a *note TypeError: 1fe. 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 *note sys: fd. module.  ‘sys.version_info’ is a tuple ‘(major,
minor, micro, level, serial)’ For example, in a hypothetical 2.0.1beta1,
‘sys.version_info’ would be ‘(2, 0, 1, 'beta', 1)’.  `level' is a string
such as ‘"alpha"’, ‘"beta"’, or ‘"final"’ for a final release.

Dictionaries have an odd new method, ‘setdefault(key, default)’, which
behaves similarly to the existing ‘get()’ method.  However, if the key
is missing, ‘setdefault()’ both returns the value of `default' as
‘get()’ would do, and also inserts it into the dictionary as the value
for `key'.  Thus, the following lines of code:

     if dict.has_key( key ): return dict[key]
     else:
         dict[key] = []
         return dict[key]

can be reduced to a single ‘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 *note
sys.getrecursionlimit(): f3b. and *note sys.setrecursionlimit(): f3c.
The default value is 1000, and a rough maximum value for a given
platform can be found by running a new script,
‘Misc/find_recursionlimit.py’.


File: python.info,  Node: 移植 Python 2 0,  Next: 扩展/嵌入更改,  Prev: 其他核心变化,  Up: Python 2 0 有什么新变化

1.18.10 移植 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 ‘append()’ and ‘insert()’.  In earlier versions of Python, if
‘L’ is a list, ‘L.append( 1,2 )’ appends the tuple ‘(1,2)’ to the list.
In Python 2.0 this causes a *note TypeError: 1fe. 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: ‘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 ‘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 ‘Objects/listobject.c’ and define the
preprocessor symbol ‘NO_STRICT_LIST_APPEND’ to preserve the old
behaviour; this isn’t recommended.

Some of the functions in the *note socket: ef. module are still
forgiving in this way.  For example, ‘socket.connect( ('hostname', 25)
)()’ is the correct form, passing a tuple representing an IP address,
but ‘socket.connect( 'hostname', 25 )()’ also works.
‘socket.connect_ex()’ and ‘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 *note socket: ef.
module, the documentation was fixed and the multiple argument form is
simply marked as deprecated; it `will' be tightened up again in a future
Python version.

The ‘\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 ‘\x123456’ was equivalent to
‘\x56’.

The *note AttributeError: 4a1. and *note NameError: e40. exceptions have
a more friendly error message, whose text will be something like ‘'Spam'
instance has no attribute 'eggs'’ or ‘name 'eggs' is not defined’.
Previously the error message was just the missing attribute name ‘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 ‘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 *note
TypeError: 1fe.  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; ‘3L *
'abc'’ produces ’abcabcabc’, and ‘(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 ‘seek()’ method of file objects,
and in the formats supported by the ‘%’ operator (‘%d’, ‘%i’, ‘%x’,
etc.).  For example, ‘"%d" % 2L**64’ will produce the string
‘18446744073709551616’.

The subtlest long integer change of all is that the *note str(): 205. of
a long integer no longer has a trailing ’L’ character, though *note
repr(): 8b9. 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 ‘str(longval)[:-1]’ and
assumes the ’L’ is there, will now lose the final digit.

Taking the *note repr(): 8b9. of a float now uses a different formatting
precision than *note str(): 205.  *note repr(): 8b9. uses ‘%.17g’ format
string for C’s ‘sprintf()’, while *note str(): 205. uses ‘%.12g’ as
before.  The effect is that *note repr(): 8b9. may occasionally show
more decimal places than *note str(): 205, for certain numbers.  For
example, the number 8.1 can’t be represented exactly in binary, so
‘repr(8.1)’ is ‘'8.0999999999999996'’, while str(8.1) is ‘'8.1'’.

The ‘-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 ‘exceptions’ module containing the
standard exceptions was translated from Python to a built-in C module,
written by Barry Warsaw and Fredrik Lundh.


File: python.info,  Node: 扩展/嵌入更改,  Next: Distutils：使模块易于安装,  Prev: 移植 Python 2 0,  Up: Python 2 0 有什么新变化

1.18.11 扩展/嵌入更改
---------------------

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
*note isinstance(): 551. and *note issubclass(): 552.  This means you no
longer have to remember to write code such as ‘if type(obj) ==
myExtensionClass’, but can use the more natural ‘if isinstance(obj,
myExtensionClass)’.

The ‘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.  ‘importdl.c’ is now quite small, and
platform-specific code has been moved into a bunch of
‘Python/dynload_*.c’ files.  Another cleanup: there were also a number
of ‘my*.h’ files in the Include/ directory that held various portability
hacks; they’ve been merged into a single file, ‘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 ‘malloc()’.  For documentation, read the
comments in ‘Include/pymem.h’ and ‘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 ‘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
‘2**16’ to ‘2**32’.

Three new convenience functions intended for adding constants to a
module’s dictionary at module initialization time were added:
‘PyModule_AddObject()’, ‘PyModule_AddIntConstant()’, and
‘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.  ‘PyOS_getsig()’
gets a signal handler and ‘PyOS_setsig()’ will set a new handler.


File: python.info,  Node: Distutils：使模块易于安装,  Next: XML 模块,  Prev: 扩展/嵌入更改,  Up: Python 2 0 有什么新变化

1.18.12 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 *note distutils: 38. 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 "‘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 ‘setup.py’ script.
For the simple case, when the software contains only .py files, a
minimal ‘setup.py’ can be just a few lines long:

     from distutils.core import setup
     setup (name = "foo", version = "1.0",
            py_modules = ["module1", "module2"])

The ‘setup.py’ file isn’t much more complicated if the software consists
of a few packages:

     from distutils.core import setup
     setup (name = "foo", version = "1.0",
            packages = ["package", "package.subpackage"])

A C extension can be the most complicated case; here’s an example taken
from the PyXML package:

     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 ] )

The Distutils can also take care of creating source and binary
distributions.  The "sdist" command, run by "‘python setup.py sdist’’,
builds a source distribution such as ‘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 ‘.pkg’ files
are in various stages of development.

All this is documented in a new manual, `Distributing Python Modules',
that joins the basic set of Python documentation.


File: python.info,  Node: XML 模块,  Next: 模块更改,  Prev: Distutils：使模块易于安装,  Up: Python 2 0 有什么新变化

1.18.13 XML 模块
----------------

Python 1.5.2 included a simple XML parser in the form of the ‘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 ‘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 *note
xml: 13c. 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::


File: python.info,  Node: SAX2 Support,  Next: DOM Support,  Up: XML 模块

1.18.13.1 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 ‘startElement()’ and
‘endElement()’ methods are called for every starting and end tag
encountered by the parser, the ‘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
‘hamlet.xml’ using it:

     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' )

For more information, consult the Python documentation, or the XML HOWTO
at ‘http://pyxml.sourceforge.net/topics/howto/xml-howto.html’.


File: python.info,  Node: DOM Support,  Next: Relationship to PyXML,  Prev: SAX2 Support,  Up: XML 模块

1.18.13.2 DOM Support
.....................

The Document Object Model is a tree-based representation for an XML
document.  A top-level ‘Document’ instance is the root of the tree, and
has a single child which is the top-level ‘Element’ instance.  This
‘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 ‘<tag1>’...‘</tag1>’ to a file.

The DOM implementation included with Python lives in the *note
xml.dom.minidom: 13e. module.  It’s a lightweight implementation of the
Level 1 DOM with support for XML namespaces.  The ‘parse()’ and
‘parseString()’ convenience functions are provided for generating a DOM
tree:

     from xml.dom import minidom
     doc = minidom.parse('hamlet.xml')

‘doc’ is a ‘Document’ instance.  ‘Document’, like all the other DOM
classes such as ‘Element’ and ‘Text’, is a subclass of the ‘Node’ base
class.  All the nodes in a DOM tree therefore support certain common
methods, such as ‘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, ‘Element’ and ‘Document’
instances have a method to find all child elements with a given tag
name.  Continuing from the previous 2-line example:

     perslist = doc.getElementsByTagName( 'PERSONA' )
     print perslist[0].toxml()
     print perslist[1].toxml()

For the `Hamlet' XML file, the above few lines output:

     <PERSONA>CLAUDIUS, king of Denmark. </PERSONA>
     <PERSONA>HAMLET, son to the late, and nephew to the present king.</PERSONA>

The root element of the document is available as ‘doc.documentElement’,
and its children can be easily modified by deleting, adding, or removing
nodes:

     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] )

Again, I will refer you to the Python documentation for a complete
listing of the different ‘Node’ classes and their various methods.


File: python.info,  Node: Relationship to PyXML,  Prev: DOM Support,  Up: XML 模块

1.18.13.3 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
‘https://www.python.org/community/sigs/current/xml-sig’.  The PyXML
distribution also used the package name ‘xml’.  If you’ve written
programs that used PyXML, you’re probably wondering about its
compatibility with the 2.0 *note xml: 13c. package.

The answer is that Python 2.0’s *note xml: 13c. 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 *note xml: 13c. 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:

   * 4DOM, a full DOM implementation from FourThought, Inc.

   * The xmlproc validating parser, written by Lars Marius Garshol.

   * The ‘sgmlop’ parser accelerator module, written by Fredrik Lundh.


File: python.info,  Node: 模块更改,  Next: 新增模块<8>,  Prev: XML 模块,  Up: Python 2 0 有什么新变化

1.18.14 模块更改
----------------

Lots of improvements and bugfixes were made to Python’s extensive
standard library; some of the affected modules include *note readline:
de, ‘ConfigParser’, *note cgi: 15, *note calendar: 14, *note posix: d1,
*note readline: de, ‘xmllib’, *note aifc: 4, ‘chunk, wave’, *note
random: dc, *note shelve: e7, and *note nntplib: c0.  Consult the CVS
logs for the exact patch-by-patch details.

Brian Gallew contributed OpenSSL support for the *note socket: ef.
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 ‘Modules/Setup’ to include SSL support, which adds an
additional function to the *note socket: ef. module: ‘socket.ssl(socket,
keyfile, certfile)’, which takes a socket object and returns an SSL
socket.  The ‘httplib’ and *note urllib: 126. modules were also changed
to support ‘https://’ URLs, though no one has implemented FTP or SMTP
over SSL.

The ‘httplib’ module has been rewritten by Greg Stein to support
HTTP/1.1.  Backward compatibility with the 1.5 version of ‘httplib’ is
provided, though using HTTP/1.1 features such as pipelining will require
rewriting code to use a different set of interfaces.

The ‘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
‘create_line’ and ‘create_polygon’ much faster, especially when using
lots of coordinates.

The *note curses: 2b. 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
*note re: dd. 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.


File: python.info,  Node: 新增模块<8>,  Next: IDLE 改进,  Prev: 模块更改,  Up: Python 2 0 有什么新变化

1.18.15 新增模块
----------------

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.

   * *note atexit: b.: For registering functions to be called before the
     Python interpreter exits.  Code that currently sets ‘sys.exitfunc’
     directly should be changed to use the *note atexit: b. module
     instead, importing *note atexit: b. and calling *note
     atexit.register(): f46. with the function to be called on exit.
     (Contributed by Skip Montanaro.)

   * *note codecs: 1b, ‘encodings’, *note unicodedata: 123.: Added as
     part of the new Unicode support.

   * *note filecmp: 7d.: Supersedes the old ‘cmp’, ‘cmpcache’ and
     ‘dircmp’ modules, which have now become deprecated.  (Contributed
     by Gordon MacMillan and Moshe Zadka.)

   * *note gettext: 87.: 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.)

   * ‘linuxaudiodev’: Support for the ‘/dev/audio’ device on Linux, a
     twin to the existing ‘sunaudiodev’ module.  (Contributed by Peter
     Bosch, with fixes by Jeremy Hylton.)

   * *note mmap: b3.: 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 *note re: dd.
     module.  (Contributed by Sam Rushing, with some extensions by A.M.
     Kuchling.)

   * ‘pyexpat’: An interface to the Expat XML parser.  (Contributed by
     Paul Prescod.)

   * ‘robotparser’: Parse a ‘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 ‘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.)

   * *note tabnanny: 100.: A module/script to check Python source code
     for ambiguous indentation.  (Contributed by Tim Peters.)

   * ‘UserString’: A base class useful for deriving objects that behave
     like strings.

   * *note webbrowser: 132.: 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 `BROWSER'
     environment variable.  (Originally inspired by Eric S. Raymond’s
     patch to *note urllib: 126. which added similar functionality, but
     the final module comes from code originally implemented by Fred
     Drake as ‘Tools/idle/BrowserControl.py’, and adapted for the
     standard library by Fred.)

   * ‘_winreg’: An interface to the Windows registry.  ‘_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.  ‘_winreg’ was written by Bill Tutt and Mark
     Hammond.

   * *note zipfile: 14b.: A module for reading and writing ZIP-format
     archives.  These are archives produced by ‘PKZIP’ on DOS/Windows or
     ‘zip’ on Unix, not to be confused with ‘gzip’-format files (which
     are supported by the *note gzip: 8b. module) (Contributed by James
     C. Ahlstrom.)

   * ‘imputil’: A module that provides a simpler way for writing
     customized import hooks, in comparison to the existing ‘ihooks’
     module.  (Implemented by Greg Stein, with much discussion on
     python-dev along the way.)


File: python.info,  Node: IDLE 改进,  Next: 删除和弃用的模块,  Prev: 新增模块<8>,  Up: Python 2 0 有什么新变化

1.18.16 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:

   * UI improvements and optimizations, especially in the area of syntax
     highlighting and auto-indentation.

   * The class browser now shows more information, such as the top level
     functions in a module.

   * Tab width is now a user settable option.  When opening an existing
     Python file, IDLE automatically detects the indentation
     conventions, and adapts.

   * There is now support for calling browsers on various platforms,
     used to open the Python documentation in a browser.

   * IDLE now has a command line, which is largely similar to the
     vanilla Python interpreter.

   * Call tips were added in many places.

   * IDLE can now be installed as a package.

   * In the editor window, there is now a line/column bar at the bottom.

   * Three new keystroke commands: Check module (‘Alt-F5’), Import
     module (‘F5’) and Run script (‘Ctrl-F5’).


File: python.info,  Node: 删除和弃用的模块,  Next: 致谢<8>,  Prev: IDLE 改进,  Up: Python 2 0 有什么新变化

1.18.17 删除和弃用的模块
------------------------

A few modules have been dropped because they’re obsolete, or because
there are now better ways to do the same thing.  The ‘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 ‘lib-old’ subdirectory:
‘cmp’, ‘cmpcache’, ‘dircmp’, ‘dump’, ‘find’, ‘grep’, ‘packmail’, ‘poly’,
‘util’, ‘whatsound’, ‘zmod’.  If you have code which relies on a module
that’s been moved to ‘lib-old’, you can simply add that directory to
‘sys.path’ to get them back, but you’re encouraged to update any code
that uses these modules.


File: python.info,  Node: 致谢<8>,  Prev: 删除和弃用的模块,  Up: Python 2 0 有什么新变化

1.18.18 致谢
------------

作者感谢以下人士对本文的各种草稿提出建议： 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(1) 目录下文件 构建(2) 的 HTML 版本，它包含
了对当前 Python 版本进行的 `所有' 重要的更改。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Misc/NEWS.d

   (2) https://pypi.org/project/blurb


File: python.info,  Node: Changelog（更動日誌）,  Prev: Python 2 0 有什么新变化,  Up: Python 有什麼新功能？

1.19 Changelog（更動日誌）
==========================

* Menu:

* Python 下一版::
* 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 最终版: Python 3 9 6 最终版.
* Python 3.9.5 最终版: Python 3 9 5 最终版.
* 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 发布候选版 1: Python 3 9 2 发布候选版 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 发布候选版 1: Python 3 9 0 发布候选版 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 正式版: Python 3 7 0 正式版.
* Python 3.7.0 rc1: Python 3 7 0 rc1.
* 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 正式版: Python 3 6 6 正式版.
* Python 3.6.6 rc1: Python 3 6 6 rc1.
* Python 3.6.5 正式版: Python 3 6 5 正式版.
* Python 3.6.5 rc1: Python 3 6 5 rc1.
* Python 3.6.4 正式版: Python 3 6 4 正式版.
* Python 3.6.4 rc1: Python 3 6 4 rc1.
* Python 3.6.3 正式版: Python 3 6 3 正式版.
* Python 3.6.3 rc1: Python 3 6 3 rc1.
* Python 3.6.2 正式版: Python 3 6 2 正式版.
* Python 3.6.2 rc2: Python 3 6 2 rc2.
* Python 3.6.2 rc1: Python 3 6 2 rc1.
* Python 3.6.1 正式版: Python 3 6 1 正式版.
* Python 3.6.1 rc1: Python 3 6 1 rc1.
* Python 3.6.0 正式版: Python 3 6 0 正式版.
* Python 3.6.0 rc2: Python 3 6 0 rc2.
* Python 3.6.0 rc1: Python 3 6 0 rc1.
* 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 正式版: Python 3 5 5 正式版.
* Python 3.5.5 rc1: Python 3 5 5 rc1.
* Python 3.5.4 正式版: Python 3 5 4 正式版.
* Python 3.5.4 rc1: Python 3 5 4 rc1.
* Python 3.5.3 正式版: Python 3 5 3 正式版.
* Python 3.5.3 rc1: Python 3 5 3 rc1.
* Python 3.5.2 正式版: Python 3 5 2 正式版.
* Python 3.5.2 rc1: Python 3 5 2 rc1.
* Python 3.5.1 正式版: Python 3 5 1 正式版.
* Python 3.5.1 rc1: Python 3 5 1 rc1.
* Python 3.5.0 正式版: Python 3 5 0 正式版.
* Python 3.5.0 rc4: Python 3 5 0 rc4.
* Python 3.5.0 rc3: Python 3 5 0 rc3.
* Python 3.5.0 rc2: Python 3 5 0 rc2.
* Python 3.5.0 rc1: Python 3 5 0 rc1.
* 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.


File: python.info,  Node: Python 下一版,  Next: Python 3 9 9 final,  Up: Changelog（更動日誌）

1.19.1 Python 下一版
--------------------

`发布日期: XXXX-XX-XX'

* Menu:

* 核心与内置函数::
* 库::
* 文档: 文档<2>.
* 测试::
* 构建::
* Windows::
* macOS::
* 工具/示例::
* C API::


File: python.info,  Node: 核心与内置函数,  Next: 库,  Up: Python 下一版

1.19.1.1 核心与内置函数
.......................

   - bpo-46070(1): *note Py_EndInterpreter(): f4e. now explicitly
     untracks all objects currently tracked by the GC. Previously, if an
     object was used later by another interpreter, calling *note
     PyObject_GC_UnTrack(): f07. on the object crashed if the previous
     or the next object of the ‘PyGC_Head’ structure became a dangling
     pointer.  Patch by Victor Stinner.

   - bpo-46085(2): Fix iterator cache mechanism of ‘OrderedDict’.

   - bpo-46110(3): Add a maximum recursion check to the PEG parser to
     avoid stack overflow.  Patch by Pablo Galindo

   - bpo-46000(4): Improve compatibility of the *note curses: 2b. module
     with NetBSD curses.

   - bpo-45614(5): Fix *note traceback: 11c. display for exceptions with
     invalid module name.

   - bpo-45806(6): Re-introduced fix that allows recovery from stack
     overflow without crashing the interpreter.  The original fix as
     part of bpo-42500(7) 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.

   - bpo-45822(8): Fixed a bug in the parser that was causing it to not
     respect PEP 263(9) coding cookies when no flags are provided.
     Patch by Pablo Galindo

   - bpo-45820(10): Fix a segfault when the parser fails without reading
     any input.  Patch by Pablo Galindo

   - bpo-42540(11): Fix crash when *note os.fork(): a42. is called with
     an active non-default memory allocator.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue46070

   (2) https://bugs.python.org/issue46085

   (3) https://bugs.python.org/issue46110

   (4) https://bugs.python.org/issue46000

   (5) https://bugs.python.org/issue45614

   (6) https://bugs.python.org/issue45806

   (7) https://bugs.python.org/issue42500

   (8) https://bugs.python.org/issue45822

   (9) https://www.python.org/dev/peps/pep-0263

   (10) https://bugs.python.org/issue45820

   (11) https://bugs.python.org/issue42540


File: python.info,  Node: 库,  Next: 文档<2>,  Prev: 核心与内置函数,  Up: Python 下一版

1.19.1.2 库
...........

   - bpo-40479(1): Fix *note hashlib: 8c. `usedforsecurity' option to
     work correctly with OpenSSL 3.0.0 in FIPS mode.

   - bpo-46070(2): Fix possible segfault when importing the *note
     asyncio: 9. module from different sub-interpreters in parallel.
     Patch by Erlend E. Aasland.

   - bpo-46278(3): Reflect ‘context’ argument in
     ‘AbstractEventLoop.call_*()’ methods.  Loop implementations already
     support it.

   - bpo-46239(4): Improve error message when importing
     ‘asyncio.windows_events’ on non-Windows.

   - bpo-20369(5): *note concurrent.futures.wait(): f50. no longer
     blocks forever when given duplicate Futures.  Patch by Kumar
     Aditya.

   - bpo-46105(6): Honor spec when generating requirement specs with
     urls and extras (importlib_metadata 4.8.3).

   - bpo-26952(7): *note argparse: 5. raises *note ValueError: 16d. with
     clear message when trying to render usage for an empty
     mutually-exclusive group.  Previously it raised a cryptic *note
     IndexError: f36.

   - bpo-27718(8): Fix help for the *note signal: ea. module.  Some
     functions (e.g.  ‘signal()’ and ‘getsignal()’) were omitted.

   - bpo-46032(9): The ‘registry()’ method of *note
     functools.singledispatch(): 490. 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.  ‘typing.List[int]’) or caused an error at calling
     time (e.g.  ‘list[int]’).

   - bpo-46018(10): Ensure that *note math.expm1(): c3a. does not raise
     on underflow.

   - bpo-27946(11): Fix possible crash when getting an attribute of
     class:*note xml.etree.ElementTree.Element: 21d. simultaneously with
     replacing the ‘attrib’ dict.

   - bpo-13236(12): *note unittest.TextTestResult: f51. and *note
     unittest.TextTestRunner: f52. flush now the output stream more
     often.

   - bpo-37658(13): Fix issue when on certain conditions
     ‘asyncio.wait_for()’ may allow a coroutine to complete
     successfully, but fail to return the result, potentially causing
     memory leaks or other issues.

   - bpo-45831(14): *note faulthandler: 7b. 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.

   - bpo-41735(15): Fix thread lock in ‘zlib.Decompress.flush()’ method
     before ‘PyObject_GetBuffer’.

   - bpo-45664(16): Fix *note types.resolve_bases(): 50a. and *note
     types.new_class(): b8f. for *note types.GenericAlias: 27c. instance
     as a base.

   - bpo-45663(17): Fix *note dataclasses.is_dataclass(): f53. for
     dataclasses which are subclasses of *note types.GenericAlias: 27c.

   - bpo-45662(18): Fix the repr of ‘dataclasses.InitVar’ with a type
     alias to the built-in class, e.g.  ‘InitVar[list[int]]’.

   - bpo-43498(19): Avoid a possible `"RuntimeError: dictionary changed
     size during iteration"' when adjusting the process count of
     ‘ProcessPoolExecutor’.

   - bpo-29620(20): *note assertWarns(): b94. no longer raises a
     ‘RuntimeException’ when accessing a module’s ‘__warningregistry__’
     causes importation of a new module, or when a new module is
     imported in another thread.  Patch by Kernc.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40479

   (2) https://bugs.python.org/issue46070

   (3) https://bugs.python.org/issue46278

   (4) https://bugs.python.org/issue46239

   (5) https://bugs.python.org/issue20369

   (6) https://bugs.python.org/issue46105

   (7) https://bugs.python.org/issue26952

   (8) https://bugs.python.org/issue27718

   (9) https://bugs.python.org/issue46032

   (10) https://bugs.python.org/issue46018

   (11) https://bugs.python.org/issue27946

   (12) https://bugs.python.org/issue13236

   (13) https://bugs.python.org/issue37658

   (14) https://bugs.python.org/issue45831

   (15) https://bugs.python.org/issue41735

   (16) https://bugs.python.org/issue45664

   (17) https://bugs.python.org/issue45663

   (18) https://bugs.python.org/issue45662

   (19) https://bugs.python.org/issue43498

   (20) https://bugs.python.org/issue29620


File: python.info,  Node: 文档<2>,  Next: 测试,  Prev: 库,  Up: Python 下一版

1.19.1.3 文档
.............

   - bpo-19737(1): Update the documentation for the *note globals():
     f55. function.

   - bpo-45840(2): Improve cross-references in the documentation for the
     data model.

   - bpo-45788(3): Link doc for sys.prefix to sysconfig doc on
     installation paths.

   - bpo-25381(4): In the extending chapter of the extending doc, update
     a paragraph about the global variables containing exception
     information.

   - bpo-43905(5): Expanded *note astuple(): f56. and *note asdict():
     f57. docs, warning about deepcopy being applied and providing a
     workaround.

   - bpo-41028(6): Language and version switchers, previously maintained
     in every cpython branches, are now handled by docsbuild-script.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue19737

   (2) https://bugs.python.org/issue45840

   (3) https://bugs.python.org/issue45788

   (4) https://bugs.python.org/issue25381

   (5) https://bugs.python.org/issue43905

   (6) https://bugs.python.org/issue41028


File: python.info,  Node: 测试,  Next: 构建,  Prev: 文档<2>,  Up: Python 下一版

1.19.1.4 测试
.............

   - bpo-46205(1): Fix hang in runtest_mp due to race condition

   - bpo-46263(2): Fix test_capi on FreeBSD 14-dev: instruct jemalloc to
     not fill freed memory with junk byte.

   - bpo-46150(3): Now ‘fakename’ in
     ‘test_pathlib.PosixPathTest.test_expanduser’ is checked to be
     non-existent.

   - bpo-46129(4): Rewrite ‘asyncio.locks’ tests with *note
     unittest.IsolatedAsyncioTestCase: 377. usage.

   - bpo-23819(5): Fixed *note asyncio: 9. tests in python optimized
     mode.  Patch by Kumar Aditya.

   - bpo-46114(6): Fix test case for OpenSSL 3.0.1 version.  OpenSSL 3.0
     uses ‘0xMNN00PP0L’.

   - bpo-19460(7): Add new Test for *note
     email.mime.nonmultipart.MIMENonMultipart: f59.

   - bpo-45835(8): Fix race condition in test_queue tests with multiple
     "feeder" threads.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue46205

   (2) https://bugs.python.org/issue46263

   (3) https://bugs.python.org/issue46150

   (4) https://bugs.python.org/issue46129

   (5) https://bugs.python.org/issue23819

   (6) https://bugs.python.org/issue46114

   (7) https://bugs.python.org/issue19460

   (8) https://bugs.python.org/issue45835


File: python.info,  Node: 构建,  Next: Windows,  Prev: 测试,  Up: Python 下一版

1.19.1.5 构建
.............

   - bpo-46263(1): ‘configure’ no longer sets ‘MULTIARCH’ on FreeBSD
     platforms.

   - bpo-46106(2): Updated OpenSSL to 1.1.1m in Windows builds, macOS
     installer builds, and CI. Patch by Kumar Aditya.

   - bpo-44035(3): CI now verifies that autoconf files have been
     regenerated with a current and unpatched autoconf package.

   - bpo-33393(4): Update ‘config.guess’ to 2021-06-03 and ‘config.sub’
     to 2021-08-14.  ‘Makefile’ now has an ‘update-config’ target to
     make updating more convenient.

   - bpo-45866(5): ‘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.

   - bpo-41498(6): Python now compiles on platforms without ‘sigset_t’.
     Several functions in *note signal: ea. are not available when
     ‘sigset_t’ is missing.

     Based on patch by Roman Yurchak for pyodide.

   - bpo-45881(7): ‘setup.py’ now uses ‘CC’ from environment first to
     discover multiarch and cross compile paths.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue46263

   (2) https://bugs.python.org/issue46106

   (3) https://bugs.python.org/issue44035

   (4) https://bugs.python.org/issue33393

   (5) https://bugs.python.org/issue45866

   (6) https://bugs.python.org/issue41498

   (7) https://bugs.python.org/issue45881


File: python.info,  Node: Windows,  Next: macOS,  Prev: 构建,  Up: Python 下一版

1.19.1.6 Windows
................

   - bpo-45901(1): When installed through the Microsoft Store and set as
     the default app for ‘*.py’ files, command line arguments will now
     be passed to Python when invoking a script without explicitly
     launching Python (that is, ‘script.py args’ rather than ‘python
     script.py args’).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue45901


File: python.info,  Node: macOS,  Next: 工具/示例,  Prev: Windows,  Up: Python 下一版

1.19.1.7 macOS
..............

   - bpo-40477(1): The Python Launcher app for macOS now properly
     launches scripts and, if necessary, the Terminal app when running
     on recent macOS releases.

   - bpo-45732(2): Update python.org macOS installer to use Tcl/Tk
     8.6.12.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40477

   (2) https://bugs.python.org/issue45732


File: python.info,  Node: 工具/示例,  Next: C API,  Prev: macOS,  Up: Python 下一版

1.19.1.8 工具/示例
..................

   - bpo-45838(1): Fix line number calculation when debugging Python
     with GDB.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue45838


File: python.info,  Node: C API,  Prev: 工具/示例,  Up: Python 下一版

1.19.1.9 C API
..............

   - bpo-39026(1): Fix Python.h to build C extensions with Xcode: remove
     a relative include from ‘Include/cpython/pystate.h’.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39026


File: python.info,  Node: Python 3 9 9 final,  Next: Python 3 9 8 final,  Prev: Python 下一版,  Up: Changelog（更動日誌）

1.19.2 Python 3.9.9 final
-------------------------

`Release date: 2021-11-15'

* Menu:

* 核心与内置函数: 核心与内置函数<2>.
* 库: 库<2>.
* 文档: 文档<3>.
* Windows: Windows<2>.


File: python.info,  Node: 核心与内置函数<2>,  Next: 库<2>,  Up: Python 3 9 9 final

1.19.2.1 核心与内置函数
.......................

   - bpo-45738(1): Fix computation of error location for invalid
     continuation characters in the parser.  Patch by Pablo Galindo.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue45738


File: python.info,  Node: 库<2>,  Next: 文档<3>,  Prev: 核心与内置函数<2>,  Up: Python 3 9 9 final

1.19.2.2 库
...........

   - bpo-45235(1): 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.

   - bpo-45765(2): In importlib.metadata, fix distribution discovery for
     an empty path.

   - bpo-45644(3): In-place JSON file formatting using ‘python3 -m
     json.tool infile infile’ now works correctly, previously it left
     the file empty.  Patch by Chris Wesseling.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue45235

   (2) https://bugs.python.org/issue45765

   (3) https://bugs.python.org/issue45644


File: python.info,  Node: 文档<3>,  Next: Windows<2>,  Prev: 库<2>,  Up: Python 3 9 9 final

1.19.2.3 文档
.............

   - bpo-45772(1): ‘socket.socket’ documentation is corrected to a class
     from a function.

   - bpo-45392(2): Update the docstring of the *note type: 6ff. built-in
     to remove a redundant line and to mention keyword arguments for the
     constructor.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue45772

   (2) https://bugs.python.org/issue45392


File: python.info,  Node: Windows<2>,  Prev: 文档<3>,  Up: Python 3 9 9 final

1.19.2.4 Windows
................

   - bpo-45732(1): Updates bundled Tcl/Tk to 8.6.12.

   - bpo-45720(2): Internal reference to ‘shlwapi.dll’ was dropped to
     help improve startup time.  This DLL will no longer be loaded at
     the start of every Python process.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue45732

   (2) https://bugs.python.org/issue45720


File: python.info,  Node: Python 3 9 8 final,  Next: Python 3 9 7 final,  Prev: Python 3 9 9 final,  Up: Changelog（更動日誌）

1.19.3 Python 3.9.8 final
-------------------------

`Release date: 2021-11-05'

* Menu:

* 核心与内置函数: 核心与内置函数<3>.
* 库: 库<3>.
* 文档: 文档<4>.
* 测试: 测试<2>.
* 构建: 构建<2>.
* Windows: Windows<3>.
* macOS: macOS<2>.
* IDLE: IDLE<3>.
* C API: C API<2>.


File: python.info,  Node: 核心与内置函数<3>,  Next: 库<3>,  Up: Python 3 9 8 final

1.19.3.1 核心与内置函数
.......................

   - bpo-30570(1): Fixed a crash in ‘issubclass()’ from infinite
     recursion when searching pathological ‘__bases__’ tuples.

   - bpo-45494(2): Fix parser crash when reporting errors involving
     invalid continuation characters.  Patch by Pablo Galindo.

   - bpo-45385(3): Fix reference leak from descr_check.  Patch by
     Dong-hee Na.

   - bpo-45167(4): Fix deepcopying of *note types.GenericAlias: 27c.
     objects.

   - bpo-44219(5): Release the GIL while performing ‘isatty’ system
     calls on arbitrary file descriptors.  In particular, this affects
     *note os.isatty(): f66, *note os.device_encoding(): f67. and *note
     io.TextIOWrapper: 6ea.  By extension, *note io.open(): 74d. in text
     mode is also affected.  This change solves a deadlock in *note
     os.isatty(): f66.  Patch by Vincent Michel in bpo-44219(6).

   - bpo-44959(7): Added fallback to extension modules with ’.sl’ suffix
     on HP-UX

   - bpo-44050(8): Extensions that indicate they use global state (by
     setting ‘m_size’ to -1) can again be used in multiple interpreters.
     This reverts to behavior of Python 3.8.

   - bpo-45121(9): Fix issue where ‘Protocol.__init__’ raises
     ‘RecursionError’ when it’s called directly or via ‘super()’.  Patch
     provided by Yurii Karabas.

   - bpo-45083(10): 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 *note
     traceback: 11c. module was using qualname already).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30570

   (2) https://bugs.python.org/issue45494

   (3) https://bugs.python.org/issue45385

   (4) https://bugs.python.org/issue45167

   (5) https://bugs.python.org/issue44219

   (6) https://bugs.python.org/issue44219

   (7) https://bugs.python.org/issue44959

   (8) https://bugs.python.org/issue44050

   (9) https://bugs.python.org/issue45121

   (10) https://bugs.python.org/issue45083


File: python.info,  Node: 库<3>,  Next: 文档<4>,  Prev: 核心与内置函数<3>,  Up: Python 3 9 8 final

1.19.3.2 库
...........

   - bpo-45678(1): Fix bug in Python 3.9 that meant
     ‘functools.singledispatchmethod’ failed to properly wrap the
     attributes of the target method.  Patch by Alex Waygood.

   - bpo-45679(2): Fix caching of multi-value *note typing.Literal: 275.
     ‘Literal[True, 2]’ is no longer equal to ‘Literal[1, 2]’.

   - bpo-45438(3): Fix typing.Signature string representation for
     generic builtin types.

   - bpo-45581(4): *note sqlite3.connect(): 4e0. now correctly raises
     *note MemoryError: f69. if the underlying SQLite API signals memory
     error.  Patch by Erlend E. Aasland.

   - bpo-39679(5): Fix bug in *note functools.singledispatchmethod: 2fa.
     that caused it to fail when attempting to register a *note
     classmethod(): 309. or *note staticmethod(): 30a. using type
     annotations.  Patch contributed by Alex Waygood.

   - bpo-45515(6): Add references to *note zoneinfo: 14e. in the *note
     datetime: 30. documentation, mostly replacing outdated references
     to ‘dateutil.tz’.  Change by Paul Ganssle.

   - bpo-45467(7): Fix incremental decoder and stream reader in the
     "raw-unicode-escape" codec.  Previously they failed if the escape
     sequence was split.

   - bpo-45461(8): Fix incremental decoder and stream reader in the
     "unicode-escape" codec.  Previously they failed if the escape
     sequence was split.

   - bpo-45239(9): Fixed *note email.utils.parsedate_tz(): f6a. crashing
     with *note UnboundLocalError: f37. on certain invalid input instead
     of returning ‘None’.  Patch by Ben Hoyt.

   - bpo-44904(10): Fix bug in the *note doctest: 66. module that caused
     it to fail if a docstring included an example with a ‘classmethod’
     ‘property’.  Patch by Alex Waygood.

   - bpo-45406(11): Make *note inspect.getmodule(): f6b. catch
     ‘FileNotFoundError’ raised by :’func:‘inspect.getabsfile’, and
     return ‘None’ to indicate that the module could not be determined.

   - bpo-45262(12): 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

   - bpo-45386(13): Make *note xmlrpc.client: 148. more robust to C
     runtimes where the underlying C ‘strftime’ function results in a
     ‘ValueError’ when testing for year formatting options.

   - bpo-45371(14): Fix clang rpath issue in *note distutils: 38.  The
     UnixCCompiler now uses correct clang option to add a runtime
     library directory (rpath) to a shared library.

   - bpo-20028(15): Improve error message of *note csv.Dialect: f6c.
     when initializing.  Patch by Vajrasky Kok and Dong-hee Na.

   - bpo-45343(16): Update bundled pip to 21.2.4 and setuptools to
     58.1.0

   - bpo-41710(17): On Unix, if the ‘sem_clockwait()’ function is
     available in the C library (glibc 2.30 and newer), the *note
     threading.Lock.acquire(): 85b. method now uses the monotonic clock
     (*note time.CLOCK_MONOTONIC: 4fb.) for the timeout, rather than
     using the system clock (*note time.CLOCK_REALTIME: f6d.), to not be
     affected by system clock changes.  Patch by Victor Stinner.

   - bpo-45328(18): Fixed *note http.client.HTTPConnection: 498. to work
     properly in OSs that don’t support the ‘TCP_NODELAY’ socket option.

   - bpo-1596321(19): Fix the ‘threading._shutdown()’ function when the
     *note threading: 10b. module was imported first from a thread
     different than the main thread: no longer log an error at Python
     exit.

   - bpo-45274(20): Fix a race condition in the *note Thread.join():
     c32. method of the *note threading: 10b. 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.

   - bpo-45238(21): Fix ‘unittest.IsolatedAsyncioTestCase.debug()’: it
     runs now asynchronous methods and callbacks.

   - bpo-36674(22): *note unittest.TestCase.debug(): f6e. raises now a
     *note unittest.SkipTest: 9e9. if the class or the test method are
     decorated with the skipping decorator.

   - bpo-45235(23): Fix an issue where argparse would not preserve
     values in a provided namespace when using a subparser with
     defaults.

   - bpo-45234(24): Fixed a regression in *note copyfile(): 382, *note
     copy(): 383, *note copy2(): 384. raising *note FileNotFoundError:
     8ad. when source is a directory, which should raise *note
     IsADirectoryError: a7a.

   - bpo-45228(25): Fix stack buffer overflow in parsing J1939 network
     address.

   - bpo-45192(26): Fix the ‘tempfile._infer_return_type’ function so
     that the ‘dir’ argument of the *note tempfile: 103. functions
     accepts an object implementing the ‘os.PathLike’ protocol.

     Patch by Kyungmin Lee.

   - bpo-45160(27): When tracing a tkinter variable used by a ttk
     OptionMenu, callbacks are no longer made twice.

   - bpo-35474(28): Calling *note mimetypes.guess_all_extensions(): f6f.
     with ‘strict=False’ no longer affects the result of the following
     call with ‘strict=True’.  Also, mutating the returned list no
     longer affects the global state.

   - bpo-45166(29): *note typing.get_type_hints(): 1ef. now works with
     *note Final: 368. wrapped in *note ForwardRef: f70.

   - bpo-45097(30): Remove deprecation warnings about the loop argument
     in *note asyncio: 9. incorrectly emitted in cases when the user
     does not pass the loop argument.

   - bpo-45081(31): Fix issue when dataclasses that inherit from
     ‘typing.Protocol’ subclasses have wrong ‘__init__’.  Patch provided
     by Yurii Karabas.

   - bpo-24444(32): Fixed an error raised in *note argparse: 5. help
     display when help for an option is set to 1+ blank spaces or when
     `choices' arg is an empty container.

   - bpo-45021(33): Fix a potential deadlock at shutdown of forked
     children when using *note concurrent.futures: 21. module

   - bpo-45030(34): Fix integer overflow in pickling and copying the
     range iterator.

   - bpo-39039(35): tarfile.open raises *note ReadError: f71. when a
     zlib error occurs during file extraction.

   - bpo-44594(36): Fix an edge case of ‘ExitStack’ and ‘AsyncExitStack’
     exception chaining.  They will now match ‘with’ block behavior when
     ‘__context__’ is explicitly set to ‘None’ when the exception is in
     flight.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue45678

   (2) https://bugs.python.org/issue45679

   (3) https://bugs.python.org/issue45438

   (4) https://bugs.python.org/issue45581

   (5) https://bugs.python.org/issue39679

   (6) https://bugs.python.org/issue45515

   (7) https://bugs.python.org/issue45467

   (8) https://bugs.python.org/issue45461

   (9) https://bugs.python.org/issue45239

   (10) https://bugs.python.org/issue44904

   (11) https://bugs.python.org/issue45406

   (12) https://bugs.python.org/issue45262

   (13) https://bugs.python.org/issue45386

   (14) https://bugs.python.org/issue45371

   (15) https://bugs.python.org/issue20028

   (16) https://bugs.python.org/issue45343

   (17) https://bugs.python.org/issue41710

   (18) https://bugs.python.org/issue45328

   (19) https://bugs.python.org/issue1596321

   (20) https://bugs.python.org/issue45274

   (21) https://bugs.python.org/issue45238

   (22) https://bugs.python.org/issue36674

   (23) https://bugs.python.org/issue45235

   (24) https://bugs.python.org/issue45234

   (25) https://bugs.python.org/issue45228

   (26) https://bugs.python.org/issue45192

   (27) https://bugs.python.org/issue45160

   (28) https://bugs.python.org/issue35474

   (29) https://bugs.python.org/issue45166

   (30) https://bugs.python.org/issue45097

   (31) https://bugs.python.org/issue45081

   (32) https://bugs.python.org/issue24444

   (33) https://bugs.python.org/issue45021

   (34) https://bugs.python.org/issue45030

   (35) https://bugs.python.org/issue39039

   (36) https://bugs.python.org/issue44594


File: python.info,  Node: 文档<4>,  Next: 测试<2>,  Prev: 库<3>,  Up: Python 3 9 8 final

1.19.3.3 文档
.............

   - bpo-45726(1): Improve documentation for *note
     functools.singledispatch(): 490. and *note
     functools.singledispatchmethod: 2fa.

   - bpo-45680(2): Amend the docs on ‘GenericAlias’ objects to clarify
     that non-container classes can also implement ‘__class_getitem__’.
     Patch contributed by Alex Waygood.

   - bpo-45655(3): Add a new "relevant PEPs" section to the top of the
     documentation for the ‘typing’ module.  Patch by Alex Waygood.

   - bpo-45604(4): Add ‘level’ argument to
     ‘multiprocessing.log_to_stderr’ function docs.

   - bpo-45464(5): Mention in the documentation of *note Built-in
     Exceptions: f73. that inheriting from multiple exception types in a
     single subclass is not recommended due to possible memory layout
     incompatibility.

   - bpo-45449(6): Add note about PEP 585(7) in *note collections.abc:
     1e.

   - bpo-45516(8): Add protocol description to the *note
     importlib.abc.Traversable: f74. documentation.

   - bpo-20692(9): Add Programming FAQ entry explaining that int literal
     attribute access requires either a space after or parentheses
     around the literal.

   - bpo-45216(10): Remove extra documentation listing methods in
     ‘difflib’.  It was rendering twice in pydoc and was outdated in
     some places.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue45726

   (2) https://bugs.python.org/issue45680

   (3) https://bugs.python.org/issue45655

   (4) https://bugs.python.org/issue45604

   (5) https://bugs.python.org/issue45464

   (6) https://bugs.python.org/issue45449

   (7) https://www.python.org/dev/peps/pep-0585

   (8) https://bugs.python.org/issue45516

   (9) https://bugs.python.org/issue20692

   (10) https://bugs.python.org/issue45216


File: python.info,  Node: 测试<2>,  Next: 构建<2>,  Prev: 文档<4>,  Up: Python 3 9 8 final

1.19.3.4 测试
.............

   - bpo-45578(1): Add tests for *note dis.distb(): 920.

   - bpo-45577(2): Add subtests for all ‘pickle’ protocols in
     ‘test_zoneinfo’.

   - bpo-43592(3): ‘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.

   - bpo-40173(4): Fix
     ‘test.support.import_helper.import_fresh_module()’.

   - bpo-45280(5): Add a test case for empty *note typing.NamedTuple:
     227.

   - bpo-45269(6): Cover case when invalid ‘markers’ type is supplied to
     ‘c_make_encoder’.

   - bpo-45209(7): Fix ‘UserWarning: resource_tracker’ warning in
     ‘_test_multiprocessing._TestSharedMemory.test_shared_memory_cleaned_after_process_termination’

   - bpo-45195(8): 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.

   - bpo-45156(9): Fixes infinite loop on *note unittest.mock.seal():
     50f. of mocks created by ‘create_autospec()’.

   - bpo-45042(10): Fixes that test classes decorated with
     ‘@hashlib_helper.requires_hashdigest’ were skipped all the time.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue45578

   (2) https://bugs.python.org/issue45577

   (3) https://bugs.python.org/issue43592

   (4) https://bugs.python.org/issue40173

   (5) https://bugs.python.org/issue45280

   (6) https://bugs.python.org/issue45269

   (7) https://bugs.python.org/issue45209

   (8) https://bugs.python.org/issue45195

   (9) https://bugs.python.org/issue45156

   (10) https://bugs.python.org/issue45042


File: python.info,  Node: 构建<2>,  Next: Windows<3>,  Prev: 测试<2>,  Up: Python 3 9 8 final

1.19.3.5 构建
.............

   - bpo-43158(1): ‘setup.py’ now uses values from configure script to
     build the ‘_uuid’ extension module.  Configure now detects
     util-linux’s ‘libuuid’, too.

   - bpo-45571(2): ‘Modules/Setup’ now use ‘PY_CFLAGS_NODIST’ instead of
     ‘PY_CFLAGS’ to compile shared modules.

   - bpo-45532(3): Update *note sys.version: 6ca. to use ‘main’ as
     fallback information.  Patch by Jeong YunWon.

   - bpo-45405(4): Prevent ‘internal configure error’ when running
     ‘configure’ with recent versions of non-Apple clang.  Patch by
     David Bohman.

   - bpo-45220(5): Avoid building with the Windows 11 SDK previews
     automatically.  This may be overridden by setting the
     ‘DefaultWindowsSDKVersion’ environment variable before building.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue43158

   (2) https://bugs.python.org/issue45571

   (3) https://bugs.python.org/issue45532

   (4) https://bugs.python.org/issue45405

   (5) https://bugs.python.org/issue45220


File: python.info,  Node: Windows<3>,  Next: macOS<2>,  Prev: 构建<2>,  Up: Python 3 9 8 final

1.19.3.6 Windows
................

   - bpo-45337(1): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue45337


File: python.info,  Node: macOS<2>,  Next: IDLE<3>,  Prev: Windows<3>,  Up: Python 3 9 8 final

1.19.3.7 macOS
..............

   - bpo-44828(1): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue44828


File: python.info,  Node: IDLE<3>,  Next: C API<2>,  Prev: macOS<2>,  Up: Python 3 9 8 final

1.19.3.8 IDLE
.............

   - bpo-45296(1): On Windows, change exit/quit message to suggest
     Ctrl-D, which works, instead of <Ctrl-Z Return>, which does not
     work in IDLE.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue45296


File: python.info,  Node: C API<2>,  Prev: IDLE<3>,  Up: Python 3 9 8 final

1.19.3.9 C API
..............

   - bpo-44687(1): ‘BufferedReader.peek()’ no longer raises *note
     ValueError: 16d. when the entire file has already been buffered.

   - bpo-44751(2): Remove ‘crypt.h’ include from the public ‘Python.h’
     header.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue44687

   (2) https://bugs.python.org/issue44751


File: python.info,  Node: Python 3 9 7 final,  Next: Python 3 9 6 最终版,  Prev: Python 3 9 8 final,  Up: Changelog（更動日誌）

1.19.4 Python 3.9.7 final
-------------------------

`Release date: 2021-08-30'

* Menu:

* 安全性::
* 核心与内置函数: 核心与内置函数<4>.
* 库: 库<4>.
* 文档: 文档<5>.
* 测试: 测试<3>.
* 构建: 构建<3>.
* Windows: Windows<4>.
* macOS: macOS<3>.


File: python.info,  Node: 安全性,  Next: 核心与内置函数<4>,  Up: Python 3 9 7 final

1.19.4.1 安全性
...............

   - bpo-42278(1): Replaced usage of *note tempfile.mktemp(): f7d. with
     *note TemporaryDirectory: c96. to avoid a potential race condition.

   - bpo-41180(2): 将审计事件添加到 *note marshal: b0. 模块，并停止为每
     个未 marshall 的代码对象引发 ‘code.__init__’ 事件。 直接实例化的代
     码对象将继续引发事件，并且审计事件处理句柄应当检查或收集原始
     marshal 数据。 当从 ‘.pyc’ 文件加载时这显著降低了性能开销。

   - bpo-44394(3): 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.

   - bpo-43124(4): Made the internal ‘putcmd’ function in *note smtplib:
     ed. sanitize input for presence of ‘\r’ and ‘\n’ characters to
     avoid (unlikely) command injection.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42278

   (2) https://bugs.python.org/issue41180

   (3) https://bugs.python.org/issue44394

   (4) https://bugs.python.org/issue43124


File: python.info,  Node: 核心与内置函数<4>,  Next: 库<4>,  Prev: 安全性,  Up: Python 3 9 7 final

1.19.4.2 核心与内置函数
.......................

   - bpo-45018(1): Fixed pickling of range iterators that iterated for
     over 2**32 times.

   - bpo-44962(2): 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

   - bpo-44954(3): Fixed a corner case bug where the result of
     ‘float.fromhex('0x.8p-1074')’ was rounded the wrong way.

   - bpo-44947(4) ：改善导入语句尾部逗号的语法错误。由 Pablo Galindo 提
     供补丁。

   - bpo-44698(5): Restore behaviour of complex exponentiation with
     integer-valued exponent of type *note float: 1fd. or *note complex:
     2c1.

   - bpo-44885(6): Correct the ast locations of f-strings with format
     specs and repeated expressions.  Patch by Pablo Galindo

   - bpo-44872(7): Use new trashcan macros (Py_TRASHCAN_BEGIN/END) in
     frameobject.c instead of the old ones (Py_TRASHCAN_SAFE_BEGIN/END).

   - bpo-33930(8): Fix segmentation fault with deep recursion when
     cleaning method objects.  Patch by Augusto Goulart and Pablo
     Galindo.

   - bpo-25782(9): Fix bug where ‘PyErr_SetObject’ hangs when the
     current exception has a cycle in its context chain.

   - bpo-44856(10): Fix reference leaks in the error paths of
     ‘update_bases()’ and ‘__build_class__’.  Patch by Pablo Galindo.

   - bpo-44698(11): Fix undefined behaviour in complex object
     exponentiation.

   - bpo-44562(12): Remove uses of *note PyObject_GC_Del(): f05. in
     error path when initializing *note types.GenericAlias: 27c.

   - bpo-44523(13): 移除针对 *note weakref.proxy: 37a. 对象的 *note
     hash(): aa3. 的传递以防止当原始被引用对象死亡而代理是可哈希对象的一
     部分时出现意外的结果。 由 Pablo Galindo 提供补丁。

   - bpo-44472(14): Fix ltrace functionality when exceptions are raised.
     Patch by Pablo Galindo

   - bpo-44184(15): Fix a crash at Python exit when a deallocator
     function removes the last strong reference to a heap type.  Patch
     by Victor Stinner.

   - bpo-39091(16): Fix crash when using passing a non-exception to a
     generator’s ‘throw()’ method.  Patch by Noah Oxer

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue45018

   (2) https://bugs.python.org/issue44962

   (3) https://bugs.python.org/issue44954

   (4) https://bugs.python.org/issue44947

   (5) https://bugs.python.org/issue44698

   (6) https://bugs.python.org/issue44885

   (7) https://bugs.python.org/issue44872

   (8) https://bugs.python.org/issue33930

   (9) https://bugs.python.org/issue25782

   (10) https://bugs.python.org/issue44856

   (11) https://bugs.python.org/issue44698

   (12) https://bugs.python.org/issue44562

   (13) https://bugs.python.org/issue44523

   (14) https://bugs.python.org/issue44472

   (15) https://bugs.python.org/issue44184

   (16) https://bugs.python.org/issue39091


File: python.info,  Node: 库<4>,  Next: 文档<5>,  Prev: 核心与内置函数<4>,  Up: Python 3 9 7 final

1.19.4.3 库
...........

   - bpo-41620(1): *note run(): b96. now always return a *note
     TestResult: b97. instance.  Previously it returned ‘None’ if the
     test class or method was decorated with a skipping decorator.

   - bpo-43913(2): Fix bugs in cleaning up classes and modules in *note
     unittest: 124.:

        * Functions registered with *note addModuleCleanup(): 374. were
          not called unless the user defines ‘tearDownModule()’ in their
          test module.

        * Functions registered with *note addClassCleanup(): 375. were
          not called if ‘tearDownClass’ is set to ‘None’.

        * Buffering in *note TestResult: b97. did not work with
          functions registered with ‘addClassCleanup()’ and
          ‘addModuleCleanup()’.

        * Errors in functions registered with ‘addClassCleanup()’ and
          ‘addModuleCleanup()’ were not handled correctly in buffered
          and debug modes.

        * Errors in ‘setUpModule()’ and functions registered with
          ‘addModuleCleanup()’ were reported in wrong order.

        * And several lesser bugs.

   - bpo-45001(3): Made email date parsing more robust against malformed
     input, namely a whitespace-only ‘Date:’ header.  Patch by Wouter
     Bolsterlee.

   - bpo-44449(4): Fix a crash in the signal handler of the *note
     faulthandler: 7b. module: no longer modify the reference count of
     frame objects.  Patch by Victor Stinner.

   - bpo-44955(5): Method *note stopTestRun(): dac. is now always called
     in pair with method *note startTestRun(): dab. for *note
     TestResult: b97. objects implicitly created in *note run(): b96.
     Previously it was not called for test methods and classes decorated
     with a skipping decorator.

   - bpo-38956(6): ‘argparse.BooleanOptionalAction’’s default value is
     no longer printed twice when used with *note
     argparse.ArgumentDefaultsHelpFormatter: f80.

   - bpo-44581(7): Upgrade bundled pip to 21.2.3 and setuptools to
     57.4.0

   - bpo-44849(8): Fix the *note os.set_inheritable(): 8e9. function on
     FreeBSD 14 for file descriptor opened with the *note O_PATH: 96e.
     flag: ignore the *note EBADF: 22f. error on ‘ioctl()’, fallback on
     the ‘fcntl()’ implementation.  Patch by Victor Stinner.

   - bpo-44605(9): The @functools.total_ordering() decorator now works
     with metaclasses.

   - bpo-44822(10): *note sqlite3: f2. user-defined functions and
     aggregators returning *note strings: 205. with embedded NUL
     characters are no longer truncated.  Patch by Erlend E. Aasland.

   - bpo-44815(11): Always show ‘loop=’ arg deprecations in *note
     asyncio.gather(): 3ab. and *note asyncio.sleep(): 3aa.

   - bpo-44806(12): Non-protocol subclasses of *note typing.Protocol:
     36a. ignore now the ‘__init__’ method inherited from protocol base
     classes.

   - bpo-44667(13): The *note tokenize.tokenize(): d23. doesn’t
     incorrectly generate a ‘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 ‘NL’ token.  Patch by Pablo
     Galindo

   - bpo-42853(14): Fix ‘http.client.HTTPSConnection’ fails to download
     >2GiB data.

   - bpo-44752(15): ‘rcompleter’ does not call *note getattr(): 54b. on
     *note property: 308. objects to avoid the side-effect of evaluating
     the corresponding method.

   - bpo-44720(16): ‘weakref.proxy’ objects referencing non-iterators
     now raise ‘TypeError’ rather than dereferencing the null
     ‘tp_iternext’ slot and crashing.

   - bpo-44704(17): The implementation of ‘collections.abc.Set._hash()’
     now matches that of ‘frozenset.__hash__()’.

   - bpo-44666(18): Fixed issue in *note compileall.compile_file(): 7ae.
     when ‘sys.stdout’ is redirected.  Patch by Stefan Hölzl.

   - bpo-40897(19): Give priority to using the current class constructor
     in *note inspect.signature(): 655.  Patch by Weipeng Hong.

   - bpo-44608(20): Fix memory leak in ‘_tkinter._flatten()’ if it is
     called with a sequence or set, but not list or tuple.

   - bpo-41928(21): Update *note shutil.copyfile(): 382. to raise *note
     FileNotFoundError: 8ad. instead of confusing *note
     IsADirectoryError: a7a. when a path ending with a ‘os.path.sep’
     does not exist; *note shutil.copy(): 383. and *note shutil.copy2():
     384. are also affected.

   - bpo-44566(22): handle StopIteration subclass raised from
     @contextlib.contextmanager generator

   - bpo-44558(23): Make the implementation consistency of *note
     indexOf(): 17b. between C and Python versions.  Patch by Dong-hee
     Na.

   - bpo-41249(24): Fixes ‘TypedDict’ to work with
     ‘typing.get_type_hints()’ and postponed evaluation of annotations
     across modules.

   - bpo-44461(25): Fix bug with *note pdb: c9.’s handling of import
     error due to a package which does not have a ‘__main__’ module

   - bpo-42892(26): Fixed an exception thrown while parsing a malformed
     multipart email by *note email.message.EmailMessage: 63c.

   - bpo-27827(27): ‘pathlib.PureWindowsPath.is_reserved()’ now
     identifies a greater range of reserved filenames, including those
     with trailing spaces or colons.

   - bpo-34266(28): 处理来自解析 *note pdb: c9. 的 run/restart 命令的参
     数的异常。

   - bpo-27334(29): The *note sqlite3: f2. context manager now performs
     a rollback (thus releasing the database lock) if commit failed.
     Patch by Luca Citi and Erlend E. Aasland.

   - bpo-43853(30): Improved string handling for *note sqlite3: f2.
     user-defined functions and aggregates:

        * It is now possible to pass strings with embedded null
          characters to UDFs

        * Conversion failures now correctly raise *note MemoryError:
          f69.

     Patch by Erlend E. Aasland.

   - bpo-43048(31): Handle *note RecursionError: 727. in *note
     TracebackException: 865.’s constructor, so that long exceptions
     chains are truncated instead of causing traceback formatting to
     fail.

   - bpo-41402(32): Fix *note email.message.EmailMessage.set_content():
     f81. when called with binary data and ‘7bit’ content transfer
     encoding.

   - bpo-32695(33): The `compresslevel' and `preset' keyword arguments
     of *note tarfile.open(): 855. are now both documented and tested.

   - bpo-34990(34): Fixed a Y2k38 bug in the compileall module where it
     would fail to compile files with a modification time after the year
     2038.

   - bpo-38840(35): Fix ‘test___all__’ on platforms lacking a shared
     memory implementation.

   - bpo-30256(36): Pass multiprocessing BaseProxy argument
     ‘manager_owned’ through AutoProxy.

   - bpo-27513(37): *note email.utils.getaddresses(): f82. now accepts
     *note email.header.Header: f83. objects along with string values.
     Patch by Zackery Spytz.

   - bpo-33349(38): lib2to3 now recognizes async generators everywhere.

   - bpo-29298(39): Fix ‘TypeError’ when required subparsers without
     ‘dest’ do not receive arguments.  Patch by Anthony Sottile.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41620

   (2) https://bugs.python.org/issue43913

   (3) https://bugs.python.org/issue45001

   (4) https://bugs.python.org/issue44449

   (5) https://bugs.python.org/issue44955

   (6) https://bugs.python.org/issue38956

   (7) https://bugs.python.org/issue44581

   (8) https://bugs.python.org/issue44849

   (9) https://bugs.python.org/issue44605

   (10) https://bugs.python.org/issue44822

   (11) https://bugs.python.org/issue44815

   (12) https://bugs.python.org/issue44806

   (13) https://bugs.python.org/issue44667

   (14) https://bugs.python.org/issue42853

   (15) https://bugs.python.org/issue44752

   (16) https://bugs.python.org/issue44720

   (17) https://bugs.python.org/issue44704

   (18) https://bugs.python.org/issue44666

   (19) https://bugs.python.org/issue40897

   (20) https://bugs.python.org/issue44608

   (21) https://bugs.python.org/issue41928

   (22) https://bugs.python.org/issue44566

   (23) https://bugs.python.org/issue44558

   (24) https://bugs.python.org/issue41249

   (25) https://bugs.python.org/issue44461

   (26) https://bugs.python.org/issue42892

   (27) https://bugs.python.org/issue27827

   (28) https://bugs.python.org/issue34266

   (29) https://bugs.python.org/issue27334

   (30) https://bugs.python.org/issue43853

   (31) https://bugs.python.org/issue43048

   (32) https://bugs.python.org/issue41402

   (33) https://bugs.python.org/issue32695

   (34) https://bugs.python.org/issue34990

   (35) https://bugs.python.org/issue38840

   (36) https://bugs.python.org/issue30256

   (37) https://bugs.python.org/issue27513

   (38) https://bugs.python.org/issue33349

   (39) https://bugs.python.org/issue29298


File: python.info,  Node: 文档<5>,  Next: 测试<3>,  Prev: 库<4>,  Up: Python 3 9 7 final

1.19.4.4 文档
.............

   - bpo-44903(1): 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 ‘page on GUI frameworks’.

   - bpo-44693(2): Update the definition of __future__ in the glossary
     by replacing the confusing word "pseudo-module" with a more
     accurate description.

   - bpo-35183(3): Add typical examples to os.path.splitext docs

   - bpo-30511(4): Clarify that *note shutil.make_archive(): 348. is not
     thread-safe due to reliance on changing the current working
     directory.

   - bpo-44561(5): 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".

   - bpo-42958(6): Updated the docstring and docs of *note
     filecmp.cmp(): f85. to be more accurate and less confusing
     especially in respect to `shallow' arg.

   - bpo-44558(7): Match the docstring and python implementation of
     *note countOf(): 17c. to the behavior of its c implementation.

   - bpo-44544(8): List all kwargs for *note textwrap.wrap(): f86, *note
     textwrap.fill(): f87, and *note textwrap.shorten(): 9d3.  Now,
     there are nav links to attributes of ‘TextWrap’, which makes
     navigation much easier while minimizing duplication in the
     documentation.

   - bpo-38062(9): Clarify that atexit uses equality comparisons
     internally.

   - bpo-43066(10): Added a warning to *note zipfile: 14b. docs:
     filename arg with a leading slash may cause archive to be
     un-openable on Windows systems.

   - bpo-27752(11): Documentation of csv.Dialect is more descriptive.

   - bpo-44453(12): Fix documentation for the return type of *note
     sysconfig.get_path(): d86.

   - bpo-39498(13): Add a "Security Considerations" index which links to
     standard library modules that have explicitly documented security
     considerations.

   - bpo-33479(14): 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,

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue44903

   (2) https://bugs.python.org/issue44693

   (3) https://bugs.python.org/issue35183

   (4) https://bugs.python.org/issue30511

   (5) https://bugs.python.org/issue44561

   (6) https://bugs.python.org/issue42958

   (7) https://bugs.python.org/issue44558

   (8) https://bugs.python.org/issue44544

   (9) https://bugs.python.org/issue38062

   (10) https://bugs.python.org/issue43066

   (11) https://bugs.python.org/issue27752

   (12) https://bugs.python.org/issue44453

   (13) https://bugs.python.org/issue39498

   (14) https://bugs.python.org/issue33479


File: python.info,  Node: 测试<3>,  Next: 构建<3>,  Prev: 文档<5>,  Up: Python 3 9 7 final

1.19.4.5 测试
.............

   - bpo-25130(1): Add calls of *note gc.collect(): 35b. in tests to
     support PyPy.

   - bpo-45011(2): Made tests relying on the ‘_asyncio’ C extension
     module optional to allow running on alternative Python
     implementations.  Patch by Serhiy Storchaka.

   - bpo-44949(3): 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.

   - bpo-44852(4): Add ability to wholesale silence DeprecationWarnings
     while running the regression test suite.

   - bpo-40928(5): Notify users running test_decimal regression tests on
     macOS of potential harmless "malloc can’t allocate region" messages
     spewed by test_decimal.

   - bpo-44734(6): Fixed floating point precision issue in turtle tests.

   - bpo-44708(7): Regression tests, when run with -w, are now
     re-running only the affected test methods instead of re-running the
     entire test file.

   - bpo-30256(8): Add test for nested queues when using
     ‘multiprocessing’ shared objects ‘AutoProxy[Queue]’ inside
     ‘ListProxy’ and ‘DictProxy’

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25130

   (2) https://bugs.python.org/issue45011

   (3) https://bugs.python.org/issue44949

   (4) https://bugs.python.org/issue44852

   (5) https://bugs.python.org/issue40928

   (6) https://bugs.python.org/issue44734

   (7) https://bugs.python.org/issue44708

   (8) https://bugs.python.org/issue30256


File: python.info,  Node: 构建<3>,  Next: Windows<4>,  Prev: 测试<3>,  Up: Python 3 9 7 final

1.19.4.6 构建
.............

   - bpo-44535(1): Enable building using a Visual Studio 2022 install on
     Windows.

   - bpo-43298(2): Improved error message when building without a
     Windows SDK installed.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue44535

   (2) https://bugs.python.org/issue43298


File: python.info,  Node: Windows<4>,  Next: macOS<3>,  Prev: 构建<3>,  Up: Python 3 9 7 final

1.19.4.7 Windows
................

   - bpo-45007(1): Update to OpenSSL 1.1.1l in Windows build

   - bpo-44572(2): Avoid consuming standard input in the *note platform:
     ce. module

   - bpo-40263(3): This is a follow-on bug from
     ‘https://bugs.python.org/issue26903’.  Once that is applied we run
     into an off-by-one assertion problem.  The assert was not correct.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue45007

   (2) https://bugs.python.org/issue44572

   (3) https://bugs.python.org/issue40263


File: python.info,  Node: macOS<3>,  Prev: Windows<4>,  Up: Python 3 9 7 final

1.19.4.8 macOS
..............

   - bpo-45007(1): Update macOS installer builds to use OpenSSL 1.1.1l.

   - bpo-44689(2): *note ctypes.util.find_library(): 701. 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,
     ‘find_library’ was not able to find macOS system libraries when
     running on Big Sur due to changes in how system libraries are
     stored.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue45007

   (2) https://bugs.python.org/issue44689


File: python.info,  Node: Python 3 9 6 最终版,  Next: Python 3 9 5 最终版,  Prev: Python 3 9 7 final,  Up: Changelog（更動日誌）

1.19.5 Python 3.9.6 最终版
--------------------------

`发布日期: 2021-06-28'

* Menu:

* 安全性: 安全性<2>.
* 核心与内置函数: 核心与内置函数<5>.
* 库: 库<5>.
* 文档: 文档<6>.
* 测试: 测试<4>.
* 构建: 构建<4>.
* Windows: Windows<5>.
* macOS: macOS<4>.
* IDLE: IDLE<4>.
* 工具/示例: 工具/示例<2>.
* C API: C API<3>.


File: python.info,  Node: 安全性<2>,  Next: 核心与内置函数<5>,  Up: Python 3 9 6 最终版

1.19.5.1 安全性
...............

   - bpo-44022(1): 现在如果服务器返回了 ‘100 Continue’ 应答状态，
     mod:*note http.client: 93. 就不会再持续不停地尝试读取 HTTP 头部信息
     了。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue44022


File: python.info,  Node: 核心与内置函数<5>,  Next: 库<5>,  Prev: 安全性<2>,  Up: Python 3 9 6 最终版

1.19.5.2 核心与内置函数
.......................

   - bpo-44409(1): 修复了在标识 记初始化时引发的标记器错误所对应的错误位
     置信息。 由 Pablo Galindo 提供补丁。

   - bpo-43667(2) ：改进了 Oracle Solaris 平台中非 UTF 语言环境下的
     Unicode 支持。本提案不会影响其他 Solaris 系统。

   - bpo-44168(3): 修正了解析器中涉及关键字参数带有无效表达式的错误消息
     。 由 Pablo Galindo 修复。

   - bpo-44114(4): 修正了 C 代码中 dictkeys_reversed 和
     dictitems_reversed 函数的错误签名，这一错误会破坏 webassembly 的构
     建。

   - bpo-44070(5) ：自版本 3.9.5 开始，除了扩展模块外，不再急于将导入文
     件名转为绝对路径。

   - bpo-28146(6) ：修正了 *note str.format(): 5d4. 中不甚明了的错误代码
     。

   - bpo-11105(7)：当用 *note compile(): 2e7. 编译带有递归引用的 *note
     ast.AST: 187. 对象时，解释器不会再崩溃，而是会触发 *note
     RecursionError: 727.。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue44409

   (2) https://bugs.python.org/issue43667

   (3) https://bugs.python.org/issue44168

   (4) https://bugs.python.org/issue44114

   (5) https://bugs.python.org/issue44070

   (6) https://bugs.python.org/issue28146

   (7) https://bugs.python.org/issue11105


File: python.info,  Node: 库<5>,  Next: 文档<6>,  Prev: 核心与内置函数<5>,  Up: Python 3 9 6 最终版

1.19.5.3 库
...........

   - bpo-44516(1): 将所提供的 pip 更新至 21.1.3

   - bpo-44482(2): Fix very unlikely resource leak in *note glob: 88. in
     alternate Python implementations.

   - bpo-44439(3): Fix in ‘bz2.BZ2File.write()’ /
     ‘lzma.LZMAFile.write()’ methods, when the input data is an object
     that supports the buffer protocol, the file length may be wrong.

   - bpo-44434(4): _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.

   - bpo-44422(5): The *note threading.enumerate(): f90. function now
     uses a reentrant lock to prevent a hang on reentrant call.  Patch
     by Victor Stinner.

   - bpo-44395(6): Fix ‘as_string()’ to pass unixfrom properly.  Patch
     by Dong-hee Na.

   - bpo-44342(7): [Enum] Be more robust in searching for pickle support
     before making an enum class unpicklable.

   - bpo-44356(8): [Enum] Allow multiple data-type mixins if they are
     all the same.

   - bpo-44254(9) ：在 Mac 上，为 turtledemo 按钮文本设置在浅色或深色背
     景下都能使用的颜色。程序员无法控制背景颜色。

   - bpo-44145(10) ：在调用 OpenSSL 的 C API ‘HMAC_Update’ （3.9 中的新
     功能）时， *note hmac: 8e. 代码没有释放 GIL。这无意间阻止了并行计算
     ，而其他 *note hashlib: 8c. 算法是支持并行的。

   - bpo-37788(11)： 修正了未曾 join 的 Thread 对象的引用泄漏问题。

   - bpo-44061(12) ：在用 *note pathlib.Path: 32f. 对象列表为参数调用
     *note pkgutil.iter_modules(): 702. 时，修复了先前版本的回归（
     regression）问题。

   - bpo-36515(13) ：在 ARM 平台下编译时， *note hashlib: 8c. 模块不会再
     进行未对齐的内存访问。

   - bpo-44018(14) ：random.seed() 不再对输入的字节数组进行修改。

   - bpo-38352(15) ：在 ‘typing.__all__’ 中添加了 ‘IO’ 、 ‘BinaryIO’ 、
     ‘TextIO’ 、 ‘Match’ 和 ‘Pattern’ 。修正人员为 Jelle Zijlstra。

   - bpo-43972(16) ：当 *note http.server.SimpleHTTPRequestHandler: 49b.
     为不以 ‘/’ 结尾的目录路径发送 ‘301 (Moved Permanently)’ 时，会添加
     一个 ‘Content-Length: 0’ 头部信息。某些客户端能因此受益。

   - bpo-28528(17) ：修正了 *note pdb: c9. 模块中的 bug：如果在
     ‘reset()’ 之后调用 ‘checkline()’ ，将会引发 *note AttributeError:
     4a1. 。

   - bpo-43776(18): When *note subprocess.Popen: 3db. args are provided
     as a string or as *note pathlib.Path: 32f, the Popen instance repr
     now shows the right thing.

   - bpo-43666(19) ：AIX：‘Lib/_aix_support.get_platform()’ 在 AIX WPAR
     中可能会失败。文件集 bos.rte 似乎在 LPAR 和 WPAR 中都带了
     builddate，因此查询的是该文件集而不是 bos.mp64。为了防止类似情况的
     发生（ODM 中不带 builddate），给了一个足以完成构建的值（9988）。修
     正人为 M Felt。

   - bpo-43650(20) ：修正 *note shutil.unpack_archive(): c68. 对大文件执
     行 ‘shutil._unpack_zipfile()’ 会失败的错误，报错为 *note
     MemoryError: f69. 。修正人为 Igor Bolshakov。

   - bpo-43318(21): Fix a bug where *note pdb: c9. does not always echo
     cleared breakpoints.

   - bpo-43295(22) ：现在 *note datetime.datetime.strptime(): f91. 以
     ‘%z’ 格式符匹配 ‘'z'’ 时，将引发 ‘ValueError’ 而不是 ‘IndexError’ 。

   - bpo-37022(23)： *note pdb: c9. 现在可以用 ‘p’ 和 ‘pp’ 命令显示
     ‘repr()’ 触发的异常。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue44516

   (2) https://bugs.python.org/issue44482

   (3) https://bugs.python.org/issue44439

   (4) https://bugs.python.org/issue44434

   (5) https://bugs.python.org/issue44422

   (6) https://bugs.python.org/issue44395

   (7) https://bugs.python.org/issue44342

   (8) https://bugs.python.org/issue44356

   (9) https://bugs.python.org/issue44254

   (10) https://bugs.python.org/issue44145

   (11) https://bugs.python.org/issue37788

   (12) https://bugs.python.org/issue44061

   (13) https://bugs.python.org/issue36515

   (14) https://bugs.python.org/issue44018

   (15) https://bugs.python.org/issue38352

   (16) https://bugs.python.org/issue43972

   (17) https://bugs.python.org/issue28528

   (18) https://bugs.python.org/issue43776

   (19) https://bugs.python.org/issue43666

   (20) https://bugs.python.org/issue43650

   (21) https://bugs.python.org/issue43318

   (22) https://bugs.python.org/issue43295

   (23) https://bugs.python.org/issue37022


File: python.info,  Node: 文档<6>,  Next: 测试<4>,  Prev: 库<5>,  Up: Python 3 9 6 最终版

1.19.5.4 文档
.............

   - bpo-40620(1): Convert examples in tutorial controlflow.rst section
     4.3 to be interpreter-demo style.

   - bpo-13814(2): In the Design FAQ, answer "Why don’t generators
     support the with statement?"

   - bpo-44392(3): Added a new section in the C API documentation for
     types used in type hinting.  Documented ‘Py_GenericAlias’ and
     ‘Py_GenericAliasType’.

   - bpo-38291(4): Mark ‘typing.io’ and ‘typing.re’ as deprecated since
     Python 3.8 in the documentation.  They were never properly
     supported by type checkers.

   - bpo-44322(5): Document that SyntaxError args have a details tuple
     and that details are adjusted for errors in f-string field
     replacement expressions.

   - bpo-44195(6) ：修正文档中 ‘TraversableResources’ 的引用。没有
     ‘TraversableReader’ 。

   - bpo-41963(7) ：将“ ‘ConfigParser’ 在读取配置文件时会去除注释”写入文
     档。

   - bpo-44072(8): Correct where in the numeric ABC hierarchy ‘**’
     support is added, i.e., in numbers.Complex, not numbers.Integral.

   - bpo-43558(9): Add the remark to *note dataclasses: 2f.
     documentation that the *note __init__(): e23. of any base class has
     to be called in ‘__post_init__()’, along with a code example.

   - bpo-41621(10): Document that *note collections.defaultdict: c0c.
     parameter ‘default_factory’ defaults to None and is
     positional-only.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40620

   (2) https://bugs.python.org/issue13814

   (3) https://bugs.python.org/issue44392

   (4) https://bugs.python.org/issue38291

   (5) https://bugs.python.org/issue44322

   (6) https://bugs.python.org/issue44195

   (7) https://bugs.python.org/issue41963

   (8) https://bugs.python.org/issue44072

   (9) https://bugs.python.org/issue43558

   (10) https://bugs.python.org/issue41621


File: python.info,  Node: 测试<4>,  Next: 构建<4>,  Prev: 文档<6>,  Up: Python 3 9 6 最终版

1.19.5.5 测试
.............

   - bpo-44287(1): Fix asyncio test_popen() of test_windows_utils by
     using a longer timeout.  Use military grade battle-tested *note
     test.support.SHORT_TIMEOUT: f94. 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.

   - bpo-44363(2): Account for address sanitizer in test_capi.
     test_capi now passes when run GCC address sanitizer.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue44287

   (2) https://bugs.python.org/issue44363


File: python.info,  Node: 构建<4>,  Next: Windows<5>,  Prev: 测试<4>,  Up: Python 3 9 6 最终版

1.19.5.6 构建
.............

   - bpo-44381(1): The Windows build now accepts
     ‘EnableControlFlowGuard’ set to ‘guard’ to enable CFG.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue44381


File: python.info,  Node: Windows<5>,  Next: macOS<4>,  Prev: 构建<4>,  Up: Python 3 9 6 最终版

1.19.5.7 Windows
................

   - bpo-41299(1): Fix 16ms jitter when using timeouts in *note
     threading: 10b, such as with *note threading.Lock.acquire(): 85b.
     or *note threading.Condition.wait(): f97.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41299


File: python.info,  Node: macOS<4>,  Next: IDLE<4>,  Prev: Windows<5>,  Up: Python 3 9 6 最终版

1.19.5.8 macOS
..............

   - bpo-43568(1): Relax unnecessarily restrictive
     MACOSX_DEPLOYMENT_TARGET check when building extension modules for
     macOS. Patch by Joshua Root.

   - bpo-43109(2): Allow –with-lto configure option to work with
     Apple-supplied Xcode or Command Line Tools.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue43568

   (2) https://bugs.python.org/issue43109


File: python.info,  Node: IDLE<4>,  Next: 工具/示例<2>,  Prev: macOS<4>,  Up: Python 3 9 6 最终版

1.19.5.9 IDLE
.............

   - bpo-40128(1): 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.

   - bpo-33962(2): Move the indent space setting from the Font tab to
     the new Windows tab.  Patch by Mark Roseman and Terry Jan Reedy.

   - bpo-40468(3): 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.

   - bpo-41611(4): Avoid uncaught exceptions in
     ‘AutoCompleteWindow.winconfig_event()’.

   - bpo-41611(5): Fix IDLE sometimes freezing upon tab-completion on
     macOS.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40128

   (2) https://bugs.python.org/issue33962

   (3) https://bugs.python.org/issue40468

   (4) https://bugs.python.org/issue41611

   (5) https://bugs.python.org/issue41611


File: python.info,  Node: 工具/示例<2>,  Next: C API<3>,  Prev: IDLE<4>,  Up: Python 3 9 6 最终版

1.19.5.10 工具/示例
...................

   - bpo-44074(1): Make patchcheck automatically detect the correct base
     branch name (previously it was hardcoded to ’master’)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue44074


File: python.info,  Node: C API<3>,  Prev: 工具/示例<2>,  Up: Python 3 9 6 最终版

1.19.5.11 C API
...............

   - bpo-44441(1): *note Py_RunMain(): 2b5. now resets
     ‘PyImport_Inittab’ to its initial value at exit.  It must be
     possible to call *note PyImport_AppendInittab(): f9c. or *note
     PyImport_ExtendInittab(): f9d. at each Python initialization.
     Patch by Victor Stinner.

   - bpo-42083(2): Fix crash in *note PyStructSequence_NewType(): f9e.
     when passed ‘NULL’ in the documentation string slot.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue44441

   (2) https://bugs.python.org/issue42083


File: python.info,  Node: Python 3 9 5 最终版,  Next: Python 3 9 4 final,  Prev: Python 3 9 6 最终版,  Up: Changelog（更動日誌）

1.19.6 Python 3.9.5 最终版
--------------------------

`发布日期: 2021-05-03'

* Menu:

* 安全性: 安全性<3>.
* 核心与内置函数: 核心与内置函数<6>.
* 库: 库<6>.
* 文档: 文档<7>.
* 测试: 测试<5>.
* Windows: Windows<6>.
* macOS: macOS<5>.
* IDLE: IDLE<5>.


File: python.info,  Node: 安全性<3>,  Next: 核心与内置函数<6>,  Up: Python 3 9 5 最终版

1.19.6.1 安全性
...............

   - bpo-43434(1): Creating a *note sqlite3.Connection: 4de. object now
     also produces a ‘sqlite3.connect’ *note auditing event: fa1.
     Previously this event was only produced by *note sqlite3.connect():
     4e0. calls.  Patch by Erlend E. Aasland.

   - bpo-43882(2): URL部分出现的换行或制表符可能会应许某些形式的攻击。

     Following the controlling specification for URLs defined by WHATWG
     *note urllib.parse(): 128. now removes ASCII newlines and tabs from
     URLs, preventing such attacks.

   - bpo-43472(3): Ensures interpreter-level audit hooks receive the
     ‘cpython.PyInterpreterState_New’ event when called through the
     ‘_xxsubinterpreters’ module.

   - bpo-36384(4): *note ipaddress: a2. 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 *note socket.inet_aton(): 236. treats leading
     zeros as octal notatation.  glibc implementation of modern *note
     inet_pton(): 237. does not accept any leading zeros.  For a while
     the *note ipaddress: a2. module used to accept ambiguous leading
     zeros.

   - bpo-43075(5)： 修复了 *note
     urllib.request.AbstractBasicAuthHandler: fa2. 中的正则表达式拒绝服
     务（ReDoS）漏洞。易受 ReDoS 攻击的正则表达式在最坏情况下具有二次复
     杂度，并且在验证一个精心制作的无效 RFCs 时它会导致拒绝服务。这个
     ReDoS 问题发生在客户端，需要远程攻击者控制 HTTP 服务器。

   - bpo-42800(6): Audit hooks are now fired for frame.f_code,
     traceback.tb_frame, and generator code/frame attribute access.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue43434

   (2) https://bugs.python.org/issue43882

   (3) https://bugs.python.org/issue43472

   (4) https://bugs.python.org/issue36384

   (5) https://bugs.python.org/issue43075

   (6) https://bugs.python.org/issue42800


File: python.info,  Node: 核心与内置函数<6>,  Next: 库<6>,  Prev: 安全性<3>,  Up: Python 3 9 5 最终版

1.19.6.2 核心与内置函数
.......................

   - bpo-43105(1): Importlib now resolves relative paths when creating
     module spec objects from file locations.

   - bpo-42924(2): Fix ‘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
     ‘bytearray’ to a shorter byte string).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue43105

   (2) https://bugs.python.org/issue42924


File: python.info,  Node: 库<6>,  Next: 文档<7>,  Prev: 核心与内置函数<6>,  Up: Python 3 9 5 最终版

1.19.6.3 库
...........

   - bpo-43993(1): Update bundled pip to 21.1.1.

   - bpo-43937(2): Fixed the *note turtle: 11f. module working with
     non-default root window.

   - bpo-43930(3): Update bundled pip to 21.1 and setuptools to 56.0.0

   - bpo-43920(4): OpenSSL 3.0.0: *note load_verify_locations(): 8d8.
     now returns a consistent error message when cadata contains no
     valid certificate.

   - bpo-43607(5): *note urllib: 126. can now convert Windows paths with
     ‘\\?\’ prefixes into URL paths.

   - bpo-43284(6): 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.

   - bpo-42248(7): [Enum] ensure exceptions raised in ‘_missing_’ are
     released.

   - bpo-43799(8): OpenSSL 3.0.0: define ‘OPENSSL_API_COMPAT’ 1.1.1 to
     suppress deprecation warnings.  Python requires OpenSSL 1.1.1 APIs.

   - bpo-43794(9): Add *note ssl.OP_IGNORE_UNEXPECTED_EOF: fa5.
     constants (OpenSSL 3.0.0)

   - bpo-43789(10): OpenSSL 3.0.0: Don’t call the password callback
     function a second time when first call has signaled an error
     condition.

   - bpo-43788(11): The header files for *note ssl: f3. error codes are
     now OpenSSL version-specific.  Exceptions will now show correct
     reason and library codes.  The ‘make_ssl_data.py’ script has been
     rewritten to use OpenSSL’s text file with error codes.

   - bpo-43655(12): *note tkinter: 10e. dialog windows are now
     recognized as dialogs by window managers on macOS and X Window.

   - bpo-43534(13): *note turtle.textinput(): fa6. and *note
     turtle.numinput(): fa7. create now a transient window working on
     behalf of the canvas window.

   - bpo-43522(14): Fix problem with *note hostname_checks_common_name:
     4e4.  OpenSSL does not copy hostflags from `struct SSL_CTX' to
     `struct SSL'.

   - bpo-42967(15): Allow *note bytes: 172. ‘separator’ argument in
     ‘urllib.parse.parse_qs’ and ‘urllib.parse.parse_qsl’ when parsing
     *note str: 205. query strings.  Previously, this raised a
     ‘TypeError’.

   - bpo-43176(16): Fixed processing of a dataclass that inherits from a
     frozen dataclass with no fields.  It is now correctly detected as
     an error.

   - bpo-41735(17): Fix thread locks in zlib module may go wrong in rare
     case.  Patch by Ma Lin.

   - bpo-36470(18): Fix dataclasses with ‘InitVar’s and *note replace():
     fa8.  Patch by Claudiu Popa.

   - bpo-32745(19): Fix a regression in the handling of ctypes’ *note
     ctypes.c_wchar_p: fa9. type: embedded null characters would cause a
     *note ValueError: 16d. to be raised.  Patch by Zackery Spytz.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue43993

   (2) https://bugs.python.org/issue43937

   (3) https://bugs.python.org/issue43930

   (4) https://bugs.python.org/issue43920

   (5) https://bugs.python.org/issue43607

   (6) https://bugs.python.org/issue43284

   (7) https://bugs.python.org/issue42248

   (8) https://bugs.python.org/issue43799

   (9) https://bugs.python.org/issue43794

   (10) https://bugs.python.org/issue43789

   (11) https://bugs.python.org/issue43788

   (12) https://bugs.python.org/issue43655

   (13) https://bugs.python.org/issue43534

   (14) https://bugs.python.org/issue43522

   (15) https://bugs.python.org/issue42967

   (16) https://bugs.python.org/issue43176

   (17) https://bugs.python.org/issue41735

   (18) https://bugs.python.org/issue36470

   (19) https://bugs.python.org/issue32745


File: python.info,  Node: 文档<7>,  Next: 测试<5>,  Prev: 库<6>,  Up: Python 3 9 5 最终版

1.19.6.4 文档
.............

   - bpo-43959(1): The documentation on the PyContextVar C-API was
     clarified.

   - bpo-43938(2): Update dataclasses documentation to express that
     FrozenInstanceError is derived from AttributeError.

   - bpo-43755(3): Update documentation to reflect that unparenthesized
     lambda expressions can no longer be the expression part in an ‘if’
     clause in comprehensions and generator expressions since Python
     3.9.

   - bpo-43739(4): Fixing the example code in
     Doc/extending/extending.rst to declare and initialize the pmodule
     variable to be of the right type.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue43959

   (2) https://bugs.python.org/issue43938

   (3) https://bugs.python.org/issue43755

   (4) https://bugs.python.org/issue43739


File: python.info,  Node: 测试<5>,  Next: Windows<6>,  Prev: 文档<7>,  Up: Python 3 9 5 最终版

1.19.6.5 测试
.............

   - bpo-43961(1): Fix test_logging.test_namer_rotator_inheritance() on
     Windows: use *note os.replace(): b15. rather than *note
     os.rename(): b14.  Patch by Victor Stinner.

   - bpo-43842(2): 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.

   - bpo-43811(3): Tests multiple OpenSSL versions on GitHub Actions.
     Use ccache to speed up testing.

   - bpo-43791(4): OpenSSL 3.0.0: Disable testing of legacy protocols
     TLS 1.0 and 1.1.  Tests are failing with
     TLSV1_ALERT_INTERNAL_ERROR.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue43961

   (2) https://bugs.python.org/issue43842

   (3) https://bugs.python.org/issue43811

   (4) https://bugs.python.org/issue43791


File: python.info,  Node: Windows<6>,  Next: macOS<5>,  Prev: 测试<5>,  Up: Python 3 9 5 最终版

1.19.6.6 Windows
................

   - bpo-35306(1): Avoid raising errors from *note
     pathlib.Path.exists(): 330. when passed an invalid filename.

   - bpo-38822(2): Fixed *note os.stat(): 321. failing on inaccessible
     directories with a trailing slash, rather than falling back to the
     parent directory’s metadata.  This implicitly affected *note
     os.path.exists(): 325. and *note os.path.isdir(): 327.

   - bpo-26227(3): Fixed decoding of host names in *note
     socket.gethostbyaddr(): fad. and *note socket.gethostbyname_ex():
     fae.

   - bpo-40432(4): 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.

   - bpo-43745(5): Actually updates Windows release to OpenSSL 1.1.1k.
     Earlier releases were mislabelled and actually included 1.1.1i
     again.

   - bpo-43492(6): Upgrade Windows installer to use SQLite 3.35.5.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35306

   (2) https://bugs.python.org/issue38822

   (3) https://bugs.python.org/issue26227

   (4) https://bugs.python.org/issue40432

   (5) https://bugs.python.org/issue43745

   (6) https://bugs.python.org/issue43492


File: python.info,  Node: macOS<5>,  Next: IDLE<5>,  Prev: Windows<6>,  Up: Python 3 9 5 最终版

1.19.6.7 macOS
..............

   - bpo-42119(1): Fix check for macOS SDK paths when building Python.
     Narrow search to match contents of SDKs, namely only files in
     ‘/System/Library’, ‘/System/IOSSupport’, and ‘/usr’ other than
     ‘/usr/local’.  Previously, anything under ‘/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
     ‘/System’.  Paths in ‘/Library’ were also incorrectly treated as
     SDK locations.

   - bpo-44009(2): 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.

   - bpo-43492(3): Update macOS installer to use SQLite 3.35.4.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42119

   (2) https://bugs.python.org/issue44009

   (3) https://bugs.python.org/issue43492


File: python.info,  Node: IDLE<5>,  Prev: macOS<5>,  Up: Python 3 9 5 最终版

1.19.6.8 IDLE
.............

   - bpo-43655(1): IDLE dialog windows are now recognized as dialogs by
     window managers on macOS and X Window.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue43655


File: python.info,  Node: Python 3 9 4 final,  Next: Python 3 9 3 final,  Prev: Python 3 9 5 最终版,  Up: Changelog（更動日誌）

1.19.7 Python 3.9.4 final
-------------------------

`Release date: 2021-04-04'

* Menu:

* 核心与内置函数: 核心与内置函数<7>.
* 库: 库<7>.


File: python.info,  Node: 核心与内置函数<7>,  Next: 库<7>,  Up: Python 3 9 4 final

1.19.7.1 核心与内置函数
.......................

   - bpo-43710(1): Reverted the fix for
     ‘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).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue43710


File: python.info,  Node: 库<7>,  Prev: 核心与内置函数<7>,  Up: Python 3 9 4 final

1.19.7.2 库
...........

   - bpo-26053(1): Fixed bug where the *note pdb: c9. interactive run
     command echoed the args from the shell command line, even if those
     have been overridden at the pdb prompt.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26053


File: python.info,  Node: Python 3 9 3 final,  Next: Python 3 9 2 final,  Prev: Python 3 9 4 final,  Up: Changelog（更動日誌）

1.19.8 Python 3.9.3 final
-------------------------

`Release date: 2021-04-02'

* Menu:

* 安全性: 安全性<4>.
* 核心与内置函数: 核心与内置函数<8>.
* 库: 库<8>.
* 文档: 文档<8>.
* 测试: 测试<6>.
* 构建: 构建<5>.
* macOS: macOS<6>.
* IDLE: IDLE<6>.


File: python.info,  Node: 安全性<4>,  Next: 核心与内置函数<8>,  Up: Python 3 9 3 final

1.19.8.1 安全性
...............

   - bpo-42988(1): CVE-2021-3426: Remove the ‘getfile’ feature of the
     *note pydoc: d9. 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.

   - bpo-43285(2): *note ftplib: 82. 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
     ‘trust_server_pasv_ipv4_address’ attribute on their *note
     ftplib.FTP: 1a6. instances to ‘True’ to re-enable it.

   - bpo-43439(3): Add audit hooks for *note gc.get_objects(): 2fe,
     *note gc.get_referrers(): fb6. and *note gc.get_referents(): fb7.
     Patch by Pablo Galindo.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42988

   (2) https://bugs.python.org/issue43285

   (3) https://bugs.python.org/issue43439


File: python.info,  Node: 核心与内置函数<8>,  Next: 库<8>,  Prev: 安全性<4>,  Up: Python 3 9 3 final

1.19.8.2 核心与内置函数
.......................

   - bpo-43660(1): Fix crash that happens when replacing ‘sys.stderr’
     with a callable that can remove the object while an exception is
     being printed.  Patch by Pablo Galindo.

   - bpo-43555(2): Report the column offset for *note SyntaxError: 559.
     for invalid line continuation characters.  Patch by Pablo Galindo.

   - bpo-43517(3): Fix misdetection of circular imports when using ‘from
     pkg.mod import attr’, which caused false positives in non-trivial
     multi-threaded code.

   - bpo-35883(4): Python no longer fails at startup with a fatal error
     if a command line argument contains an invalid Unicode character.
     The *note Py_DecodeLocale(): 53e. function now escapes byte
     sequences which would be decoded as Unicode characters outside the
     [U+0000; U+10ffff] range.

   - bpo-43406(5): Fix a possible race condition where
     ‘PyErr_CheckSignals’ tries to execute a non-Python signal handler.

   - bpo-42500(6): Improve handling of exceptions near recursion limit.
     Converts a number of Fatal Errors in RecursionErrors.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue43660

   (2) https://bugs.python.org/issue43555

   (3) https://bugs.python.org/issue43517

   (4) https://bugs.python.org/issue35883

   (5) https://bugs.python.org/issue43406

   (6) https://bugs.python.org/issue42500


File: python.info,  Node: 库<8>,  Next: 文档<8>,  Prev: 核心与内置函数<8>,  Up: Python 3 9 3 final

1.19.8.3 库
...........

   - bpo-43433(1): *note xmlrpc.client.ServerProxy: 37f. no longer
     ignores query and fragment in the URL of the server.

   - bpo-35930(2): Raising an exception raised in a "future" instance
     will create reference cycles.

   - bpo-43577(3): Fix deadlock when using *note ssl.SSLContext: 4e9.
     debug callback with *note ssl.SSLContext.sni_callback(): fba.

   - bpo-43521(4): ‘ast.unparse’ can now render NaNs and empty sets.

   - bpo-43423(5): ‘subprocess.communicate()’ no longer raises an
     IndexError when there is an empty stdout or stderr IO buffer during
     a timeout on Windows.

   - bpo-27820(6): 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.

   - bpo-43332(7): Improves the networking efficiency of *note
     http.client: 93. when using a proxy via ‘set_tunnel()’.  Fewer
     small send calls are made during connection setup.

   - bpo-43399(8): Fix ‘ElementTree.extend’ not working on iterators
     when using the Python implementation

   - bpo-43316(9): The ‘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.

   - bpo-43260(10): Fix TextIOWrapper can not flush internal buffer
     forever after very large text is written.

   - bpo-42782(11): Fail fast in *note shutil.move(): 385. to avoid
     creating destination directories on failure.

   - bpo-37193(12): Fixed memory leak in ‘socketserver.ThreadingMixIn’
     introduced in Python 3.7.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue43433

   (2) https://bugs.python.org/issue35930

   (3) https://bugs.python.org/issue43577

   (4) https://bugs.python.org/issue43521

   (5) https://bugs.python.org/issue43423

   (6) https://bugs.python.org/issue27820

   (7) https://bugs.python.org/issue43332

   (8) https://bugs.python.org/issue43399

   (9) https://bugs.python.org/issue43316

   (10) https://bugs.python.org/issue43260

   (11) https://bugs.python.org/issue42782

   (12) https://bugs.python.org/issue37193


File: python.info,  Node: 文档<8>,  Next: 测试<6>,  Prev: 库<8>,  Up: Python 3 9 3 final

1.19.8.4 文档
.............

   - bpo-43199(1): Answer "Why is there no goto?"  in the Design and
     History FAQ.

   - bpo-43407(2): Clarified that a result from *note time.monotonic():
     85e, *note time.perf_counter(): 3cc, *note time.process_time():
     3cd, or *note time.thread_time(): 1e7. can be compared with the
     result from any following call to the same function - not just the
     next immediate call.

   - bpo-27646(3): Clarify that ’yield from <expr>’ works with any
     iterable, not just iterators.

   - bpo-36346(4): Update some deprecated unicode APIs which are
     documented as "will be removed in 4.0" to "3.12".  See PEP 623(5)
     for detail.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue43199

   (2) https://bugs.python.org/issue43407

   (3) https://bugs.python.org/issue27646

   (4) https://bugs.python.org/issue36346

   (5) https://www.python.org/dev/peps/pep-0623


File: python.info,  Node: 测试<6>,  Next: 构建<5>,  Prev: 文档<8>,  Up: Python 3 9 3 final

1.19.8.5 测试
.............

   - bpo-37945(1): Fix test_getsetlocale_issue1813() of test_locale:
     skip the test if ‘setlocale()’ fails.  Patch by Victor Stinner.

   - bpo-41561(2): Add workaround for Ubuntu’s custom OpenSSL security
     level policy.

   - bpo-43288(3): Fix test_importlib to correctly skip Unicode file
     tests if the fileystem does not support them.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37945

   (2) https://bugs.python.org/issue41561

   (3) https://bugs.python.org/issue43288


File: python.info,  Node: 构建<5>,  Next: macOS<6>,  Prev: 测试<6>,  Up: Python 3 9 3 final

1.19.8.6 构建
.............

   - bpo-43631(1): Update macOS, Windows, and CI to OpenSSL 1.1.1k.

   - bpo-43617(2): Improve configure.ac: Check for presence of
     autoconf-archive package and remove our copies of M4 macros.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue43631

   (2) https://bugs.python.org/issue43617


File: python.info,  Node: macOS<6>,  Next: IDLE<6>,  Prev: 构建<5>,  Up: Python 3 9 3 final

1.19.8.7 macOS
..............

   - bpo-41837(1): Update macOS installer build to use OpenSSL 1.1.1j.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41837


File: python.info,  Node: IDLE<6>,  Prev: macOS<6>,  Up: Python 3 9 3 final

1.19.8.8 IDLE
.............

   - bpo-42225(1): Document that IDLE can fail on Unix either from
     misconfigured IP masquerage rules or failure displaying complex
     colored (non-ascii) characters.

   - bpo-43283(2): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42225

   (2) https://bugs.python.org/issue43283


File: python.info,  Node: Python 3 9 2 final,  Next: Python 3 9 2 发布候选版 1,  Prev: Python 3 9 3 final,  Up: Changelog（更動日誌）

1.19.9 Python 3.9.2 final
-------------------------

`发布日期: 2021-02-19'

* Menu:

* Windows: Windows<7>.


File: python.info,  Node: Windows<7>,  Up: Python 3 9 2 final

1.19.9.1 Windows
................

   - bpo-43155(1): ‘PyCMethod_New()’ 现在已加入 ‘python3.lib’。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue43155


File: python.info,  Node: Python 3 9 2 发布候选版 1,  Next: Python 3 9 1 final,  Prev: Python 3 9 2 final,  Up: Changelog（更動日誌）

1.19.10 Python 3.9.2 发布候选版 1
---------------------------------

`发布日期: 2021-02-16'

* Menu:

* 安全性: 安全性<5>.
* 核心与内置函数: 核心与内置函数<9>.
* 库: 库<9>.
* 文档: 文档<9>.
* 测试: 测试<7>.
* 构建: 构建<6>.
* Windows: Windows<8>.
* macOS: macOS<7>.
* IDLE: IDLE<7>.
* 工具/示例: 工具/示例<3>.
* C API: C API<4>.


File: python.info,  Node: 安全性<5>,  Next: 核心与内置函数<9>,  Up: Python 3 9 2 发布候选版 1

1.19.10.1 安全性
................

   - bpo-42967(1): Fix web cache poisoning vulnerability by defaulting
     the query args separator to ‘&’, and allowing the user to choose a
     custom separator.

   - bpo-42938(2): 在计算 *note ctypes.c_double: fc4. 和 *note
     ctypes.c_longdouble: fc5. 值的表示形式时避免静态缓冲区。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42967

   (2) https://bugs.python.org/issue42938


File: python.info,  Node: 核心与内置函数<9>,  Next: 库<9>,  Prev: 安全性<5>,  Up: Python 3 9 2 发布候选版 1

1.19.10.2 核心与内置函数
........................

   - bpo-42819(1): *note readline: de.: 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 ‘readline.read_init_file()’.  The Python REPL has not
     implemented bracketed paste support.  Also, bracketed mode writes
     the ‘"\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 ‘readline.parse_and_bind("set
     enable-bracketed-paste on")’.  Patch by Dustin Rodrigues.

   - bpo-42806(2): 修复包括在圆括号中的 *note ast: 7. 节点以及会产生多行
     的节点的f-字符串列偏移量问题。 由 Pablo Galindo 提供补丁。

   - bpo-40631(3): 修复了单个带圆括号的星号表达式是有效的赋值目标时的回
     归。

   - bpo-32381(4): 修复了在 Windows 上运行 ‘.pyc’ 文件时的编码格式名称，
     现在 *note PyRun_SimpleFileExFlags(): fc7. 会使用正确的编码格式来编
     码文件名。

   - bpo-42536(5): g一些内置和标准库类型现在会确保其内部结果元组总是会被
     *note 垃圾回收器: fc8. 所追踪:

        - *note collections.OrderedDict.items(): 2ea.

        - *note dict.items(): cf5.

        - *note enumerate(): ea7.

        - *note functools.reduce(): d37.

        - *note itertools.combinations(): d6e.

        - *note itertools.combinations_with_replacement(): ce3.

        - *note itertools.permutations(): fc9.

        - *note itertools.product(): d6f.

        - *note itertools.zip_longest(): cfb.

        - *note zip(): cfc.

     之前，它们可能会被前一次垃圾回收取消追踪。 由 Brandt Bucher 提供补
     丁。

   - bpo-42195(6): The ‘__args__’ of the parameterized generics for
     *note typing.Callable: 27b. and *note collections.abc.Callable:
     27a. are now consistent.  The ‘__args__’ for *note
     collections.abc.Callable: 27a. are now flattened while *note
     typing.Callable: 27b.’s have not changed.  To allow this change,
     *note types.GenericAlias: 27c. can now be subclassed and
     ‘collections.abc.Callable’’s ‘__class_getitem__’ will now return a
     subclass of ‘types.GenericAlias’.  Tests for typing were also
     updated to not subclass things like ‘Callable[..., T]’ as that is
     not a valid base class.  Finally, both types no longer validate
     their ‘argtypes’, in ‘Callable[[argtypes], resulttype]’ to prepare
     for PEP 612(7).  Patch by Ken Jin.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42819

   (2) https://bugs.python.org/issue42806

   (3) https://bugs.python.org/issue40631

   (4) https://bugs.python.org/issue32381

   (5) https://bugs.python.org/issue42536

   (6) https://bugs.python.org/issue42195

   (7) https://www.python.org/dev/peps/pep-0612


File: python.info,  Node: 库<9>,  Next: 文档<9>,  Prev: 核心与内置函数<9>,  Up: Python 3 9 2 发布候选版 1

1.19.10.3 库
............

   - bpo-43102(1): The namedtuple __new__ method had its __builtins__
     set to None instead of an actual dictionary.  This created problems
     for introspection tools.

   - bpo-43108(2): 修复 *note curses: 2b. 模块中的引用泄漏。由Pablo
     Galindo修正。

   - bpo-42944(3): Fix ‘random.Random.sample’ when ‘counts’ argument is
     not ‘None’.

   - bpo-42931(4): Add ‘randbytes()’ to ‘random.__all__’.

   - bpo-42780(5): Fix os.set_inheritable() for O_PATH file descriptors
     on Linux.

   - bpo-42851(6): remove __init_subclass__ support for Enum members

   - bpo-41748(7): Fix HTMLParser parsing rules for element attributes
     containing commas with spaces.  Patch by Karl Dubost.

   - bpo-42759(8): Fixed equality comparison of ‘tkinter.Variable’ and
     *note tkinter.font.Font: fcb.  Objects which belong to different
     Tcl interpreters are now always different, even if they have the
     same name.

   - bpo-42756(9): Configure LMTP Unix-domain socket to use socket
     global default timeout when a timeout is not explicitly provided.

   - bpo-23328(10): Allow / character in username, password fields on
     _PROXY envars.

   - bpo-42655(11): *note subprocess: f9. `extra_groups' is now
     correctly passed into setgroups() system call.

   - bpo-42727(12): ‘EnumMeta.__prepare__’ now accepts ‘**kwds’ to
     properly support ‘__init_subclass__’

   - bpo-42681(13): Fixed range checks for color and pair numbers in
     *note curses: 2b.

   - bpo-37961(14): Fix crash in ‘tracemalloc.Traceback.__repr__()’
     (regressed in Python 3.9).

   - bpo-42630(15): *note tkinter: 10e. functions and constructors which
     need a default root window raise now *note RuntimeError: 3dc. with
     descriptive message instead of obscure *note AttributeError: 4a1.
     or *note NameError: e40. if it is not created yet or cannot be
     created automatically.

   - bpo-42644(16): *note logging.disable: fcc. will now validate the
     types and value of its parameter.  It also now accepts strings
     representing the levels (as does ‘loging.setLevel’) instead of only
     the numerical values.

   - bpo-36541(17): Fixed lib2to3.pgen2 to be able to parse PEP-570
     positional only argument syntax.

   - bpo-42517(18): Enum: private names will raise a DeprecationWarning;
     in 3.10 they will become normal attributes

   - bpo-42678(19): ‘Enum’: call ‘__init_subclass__’ after members have
     been added

   - bpo-42532(20): Remove unexpected call of ‘__bool__’ when passing a
     ‘spec_arg’ argument to a Mock.

   - bpo-42388(21): Fix subprocess.check_output(..., input=None)
     behavior when text=True to be consistent with that of the
     documentation and universal_newlines=True.

   - bpo-34463(22): Fixed discrepancy between *note traceback: 11c. and
     the interpreter in formatting of SyntaxError with lineno not set
     (*note traceback: 11c. was changed to match interpreter).

   - bpo-42375(23): subprocess module update for DragonFlyBSD support.

   - bpo-42384(24): Make pdb populate sys.path[0] exactly the same as
     regular python execution.

   - bpo-42383(25): pdb修复: 之前的 pdb 在指定路径时如果使用了相对路径，
     并且当前路径发生改变后重启调试目标会失败的问题。

   - bpo-42318(26): Fixed support of non-BMP characters in *note
     tkinter: 10e. on macOS.

   - bpo-42163(27): Restore compatibility for ‘uname_result’ around
     deepcopy and _replace.

   - bpo-39825(28): Windows: Change
     ‘sysconfig.get_config_var('EXT_SUFFIX')’ to the expected full
     ‘platform_tag.extension’ format.  Previously it was hard-coded to
     ‘.pyd’, now it is compatible with ‘distutils.sysconfig’ and will
     result in something like ‘.cp38-win_amd64.pyd’.  This brings
     windows into conformance with the other platforms.

   - bpo-42059(29): *note typing.TypedDict: 367. types created using the
     alternative call-style syntax now correctly respect the ‘total’
     keyword argument when setting their ‘__required_keys__’ and
     ‘__optional_keys__’ class attributes.

   - bpo-39101(30): Fixed tests using IsolatedAsyncioTestCase from
     hanging on BaseExceptions.

   - bpo-42005(31): Fix CLI of *note cProfile: 27. and *note profile:
     d3. to catch *note BrokenPipeError: a7e.

   - bpo-41907(32): fix *note format(): 5d5. behavior for ‘IntFlag’

   - bpo-41889(33): Enum: fix regression involving inheriting a
     multiply-inherited enum

   - bpo-41891(34): Ensure asyncio.wait_for waits for task completion

   - bpo-41604(35): Don’t decrement the reference count of the previous
     user_ptr when set_panel_userptr fails.

   - bpo-40219(36): Lowered ‘tkinter.ttk.LabeledScale’ dummy widget to
     prevent hiding part of the content label.

   - bpo-40084(37): Fix ‘Enum.__dir__’: dir(Enum.member) now includes
     attributes as well as methods.

   - bpo-39068(38): Fix initialization race condition in ‘a85encode()’
     and ‘b85encode()’ in *note base64: d.  Patch by Brandon Stansbury.

   - bpo-33289(39): Correct call to *note tkinter.colorchooser: 10f. to
     return RGB triplet of ints instead of floats.  Patch by Cheryl
     Sabella.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue43102

   (2) https://bugs.python.org/issue43108

   (3) https://bugs.python.org/issue42944

   (4) https://bugs.python.org/issue42931

   (5) https://bugs.python.org/issue42780

   (6) https://bugs.python.org/issue42851

   (7) https://bugs.python.org/issue41748

   (8) https://bugs.python.org/issue42759

   (9) https://bugs.python.org/issue42756

   (10) https://bugs.python.org/issue23328

   (11) https://bugs.python.org/issue42655

   (12) https://bugs.python.org/issue42727

   (13) https://bugs.python.org/issue42681

   (14) https://bugs.python.org/issue37961

   (15) https://bugs.python.org/issue42630

   (16) https://bugs.python.org/issue42644

   (17) https://bugs.python.org/issue36541

   (18) https://bugs.python.org/issue42517

   (19) https://bugs.python.org/issue42678

   (20) https://bugs.python.org/issue42532

   (21) https://bugs.python.org/issue42388

   (22) https://bugs.python.org/issue34463

   (23) https://bugs.python.org/issue42375

   (24) https://bugs.python.org/issue42384

   (25) https://bugs.python.org/issue42383

   (26) https://bugs.python.org/issue42318

   (27) https://bugs.python.org/issue42163

   (28) https://bugs.python.org/issue39825

   (29) https://bugs.python.org/issue42059

   (30) https://bugs.python.org/issue39101

   (31) https://bugs.python.org/issue42005

   (32) https://bugs.python.org/issue41907

   (33) https://bugs.python.org/issue41889

   (34) https://bugs.python.org/issue41891

   (35) https://bugs.python.org/issue41604

   (36) https://bugs.python.org/issue40219

   (37) https://bugs.python.org/issue40084

   (38) https://bugs.python.org/issue39068

   (39) https://bugs.python.org/issue33289


File: python.info,  Node: 文档<9>,  Next: 测试<7>,  Prev: 库<9>,  Up: Python 3 9 2 发布候选版 1

1.19.10.4 文档
..............

   - bpo-40304(1): Fix doc for type(name, bases, dict).  Patch by Boris
     Verkhovskiy and Éric Araujo.

   - bpo-42811(2): Updated importlib.utils.resolve_name() doc to use
     __spec__.parent instead of __package__.  (Thanks Yair Frid.)

   - bpo-17140(3): Add documentation for the *note
     multiprocessing.pool.ThreadPool: fce. class.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40304

   (2) https://bugs.python.org/issue42811

   (3) https://bugs.python.org/issue17140


File: python.info,  Node: 测试<7>,  Next: 构建<6>,  Prev: 文档<9>,  Up: Python 3 9 2 发布候选版 1

1.19.10.5 测试
..............

   - bpo-42794(1): Update test_nntplib to use offical group name of
     news.aioe.org for testing.  Patch by Dong-hee Na.

   - bpo-40810(2): In *note sqlite3: f2, fix ‘CheckTraceCallbackContent’
     for SQLite pre 3.7.15.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42794

   (2) https://bugs.python.org/issue40810


File: python.info,  Node: 构建<6>,  Next: Windows<8>,  Prev: 测试<7>,  Up: Python 3 9 2 发布候选版 1

1.19.10.6 构建
..............

   - bpo-43174(1): Windows build now uses ‘/utf-8’ compiler option.

   - bpo-42692(2): Fix __builtin_available check on older compilers.
     Patch by Joshua Root.

   - bpo-42604(3): 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".

   - bpo-42598(4): Fix implicit function declarations in configure which
     could have resulted in incorrect configuration checks.  Patch
     contributed by Joshua Root.

   - bpo-29076(5): Add fish shell support to macOS installer.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue43174

   (2) https://bugs.python.org/issue42692

   (3) https://bugs.python.org/issue42604

   (4) https://bugs.python.org/issue42598

   (5) https://bugs.python.org/issue29076


File: python.info,  Node: Windows<8>,  Next: macOS<7>,  Prev: 构建<6>,  Up: Python 3 9 2 发布候选版 1

1.19.10.7 Windows
.................

   - bpo-41837(1): Updated Windows installer to include OpenSSL 1.1.1i

   - bpo-42584(2): Upgrade Windows installer to use SQLite 3.34.0.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41837

   (2) https://bugs.python.org/issue42584


File: python.info,  Node: macOS<7>,  Next: IDLE<7>,  Prev: Windows<8>,  Up: Python 3 9 2 发布候选版 1

1.19.10.8 macOS
...............

   - bpo-42504(1): 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.

   - bpo-42361(2): Update macOS installer build to use Tcl/Tk 8.6.11
     (rc2, expected to be final release).

   - bpo-41837(3): Update macOS installer build to use OpenSSL 1.1.1i.

   - bpo-42584(4): Update macOS installer to use SQLite 3.34.0.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42504

   (2) https://bugs.python.org/issue42361

   (3) https://bugs.python.org/issue41837

   (4) https://bugs.python.org/issue42584


File: python.info,  Node: IDLE<7>,  Next: 工具/示例<3>,  Prev: macOS<7>,  Up: Python 3 9 2 发布候选版 1

1.19.10.9 IDLE
..............

   - bpo-43008(1): Make IDLE invoke *note sys.excepthook(): f24. in
     normal, 2-process mode.  Patch by Ken Hilton.

   - bpo-33065(2): Fix problem debugging user classes with __repr__
     method.

   - bpo-23544(3): Disable Debug=>Stack Viewer when user code is running
     or Debugger is active, to prevent hang or crash.  Patch by Zackery
     Spytz.

   - bpo-32631(4): Finish zzdummy example extension module: make menu
     entries work; add docstrings and tests with 100% coverage.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue43008

   (2) https://bugs.python.org/issue33065

   (3) https://bugs.python.org/issue23544

   (4) https://bugs.python.org/issue32631


File: python.info,  Node: 工具/示例<3>,  Next: C API<4>,  Prev: IDLE<7>,  Up: Python 3 9 2 发布候选版 1

1.19.10.10 工具/示例
....................

   - bpo-42726(1): Fixed Python 3 compatibility issue with
     gdb/libpython.py handling of attribute dictionaries.

   - bpo-42613(2): Fix ‘freeze.py’ tool to use the prope config and
     library directories.  Patch by Victor Stinner.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42726

   (2) https://bugs.python.org/issue42613


File: python.info,  Node: C API<4>,  Prev: 工具/示例<3>,  Up: Python 3 9 2 发布候选版 1

1.19.10.11 C API
................

   - bpo-43030(1): Fixed a compiler warning in *note
     Py_UNICODE_ISSPACE(): fd6. on platforms with signed ‘wchar_t’.

   - bpo-42591(2): Export the ‘Py_FrozenMain()’ function: fix a Python
     3.9.0 regression.  Python 3.9 uses ‘-fvisibility=hidden’ and the
     function was not exported explicitly and so not exported.

   - bpo-40052(3): Fix an alignment build warning/error in function
     ‘PyVectorcall_Function()’.  Patch by Andreas Schneider, Antoine
     Pitrou and Petr Viktorin.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue43030

   (2) https://bugs.python.org/issue42591

   (3) https://bugs.python.org/issue40052


File: python.info,  Node: Python 3 9 1 final,  Next: Python 3 9 1 release candidate 1,  Prev: Python 3 9 2 发布候选版 1,  Up: Changelog（更動日誌）

1.19.11 Python 3.9.1 final
--------------------------

`发布日期: 2020-12-07'

* Menu:

* 核心与内置函数: 核心与内置函数<10>.
* 库: 库<10>.
* 测试: 测试<8>.
* macOS: macOS<8>.
* IDLE: IDLE<8>.


File: python.info,  Node: 核心与内置函数<10>,  Next: 库<10>,  Up: Python 3 9 1 final

1.19.11.1 核心与内置函数
........................

   - bpo-42576(1): ‘types.GenericAlias’ will now raise a ‘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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42576


File: python.info,  Node: 库<10>,  Next: 测试<8>,  Prev: 核心与内置函数<10>,  Up: Python 3 9 1 final

1.19.11.2 库
............

   - bpo-5054(1): 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.

   - bpo-17735(2): ‘inspect.findsource()’ now raises *note OSError: 304.
     instead of *note IndexError: f36. when ‘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.

   - bpo-42116(3): Fix handling of trailing comments by *note
     inspect.getsource(): fda.

   - bpo-42487(4): ChainMap.__iter__ no longer calls __getitem__ on
     underlying maps

   - bpo-42482(5): *note TracebackException: 865. 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.

   - bpo-42406(6): We fixed an issue in ‘pickle.whichmodule’ in which
     importing *note multiprocessing: b7. could change the how pickle
     identifies which module an object belongs to, potentially breaking
     the unpickling of those objects.

   - bpo-34215(7): Clarify the error message for *note
     asyncio.IncompleteReadError: fdb. when ‘expected’ is ‘None’.

   - bpo-12800(8): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5054

   (2) https://bugs.python.org/issue17735

   (3) https://bugs.python.org/issue42116

   (4) https://bugs.python.org/issue42487

   (5) https://bugs.python.org/issue42482

   (6) https://bugs.python.org/issue42406

   (7) https://bugs.python.org/issue34215

   (8) https://bugs.python.org/issue12800


File: python.info,  Node: 测试<8>,  Next: macOS<8>,  Prev: 库<10>,  Up: Python 3 9 1 final

1.19.11.3 测试
..............

   - bpo-41473(1): Reenable test_gdb on gdb 9.2 and newer:
     ‘https://bugzilla.redhat.com/show_bug.cgi?id=1866884’ bug is fixed
     in gdb 10.1.

   - bpo-42553(2): Fix ‘test_asyncio.test_call_later()’ race condition:
     don’t measure asyncio performance in the ‘call_later()’ unit test.
     The test failed randomly on the CI.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41473

   (2) https://bugs.python.org/issue42553


File: python.info,  Node: macOS<8>,  Next: IDLE<8>,  Prev: 测试<8>,  Up: Python 3 9 1 final

1.19.11.4 macOS
...............

   - bpo-41116(1): 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.

   - bpo-42504(2): Fix build on macOS Big Sur when
     MACOSX_DEPLOYMENT_TARGET=11

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41116

   (2) https://bugs.python.org/issue42504


File: python.info,  Node: IDLE<8>,  Prev: macOS<8>,  Up: Python 3 9 1 final

1.19.11.5 IDLE
..............

   - bpo-42508(1): Keep IDLE running on macOS. Remove obsolete
     workaround that prevented running files with shortcuts when using
     new universal2 installers built on macOS 11.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42508


File: python.info,  Node: Python 3 9 1 release candidate 1,  Next: Python 3 9 0 final,  Prev: Python 3 9 1 final,  Up: Changelog（更動日誌）

1.19.12 Python 3.9.1 release candidate 1
----------------------------------------

`Release date: 2020-11-24'

* Menu:

* 安全性: 安全性<6>.
* 核心与内置函数: 核心与内置函数<11>.
* 库: 库<11>.
* 文档: 文档<10>.
* 测试: 测试<9>.
* 构建: 构建<7>.
* Windows: Windows<9>.
* macOS: macOS<9>.
* IDLE: IDLE<9>.
* C API: C API<5>.


File: python.info,  Node: 安全性<6>,  Next: 核心与内置函数<11>,  Up: Python 3 9 1 release candidate 1

1.19.12.1 安全性
................

   - bpo-42103(1): Prevented potential DoS attack via CPU and RAM
     exhaustion when processing malformed Apple Property List files in
     binary format.

   - bpo-42051(2)：模块 *note plistlib: cf. 不再接受 XML 属性列表文件中
     的实体声明（避免引发 XML 脆弱性）。此更改不应该影响用户使用，因为实
     体声明在常规属性列表文件中不被使用。

   - bpo-40791(3): Add ‘volatile’ to the accumulator variable in
     ‘hmac.compare_digest’, making constant-time-defeating optimizations
     less likely.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42103

   (2) https://bugs.python.org/issue42051

   (3) https://bugs.python.org/issue40791


File: python.info,  Node: 核心与内置函数<11>,  Next: 库<11>,  Prev: 安全性<6>,  Up: Python 3 9 1 release candidate 1

1.19.12.2 核心与内置函数
........................

   - bpo-41686(1): On Windows, the ‘SIGINT’ event,
     ‘_PyOS_SigintEvent()’, is now created even if Python is configured
     to not install signal handlers (if *note
     PyConfig.install_signal_handlers: fe2. equals to 0, or
     ‘Py_InitializeEx(0)’).

   - bpo-42381(2): Allow assignment expressions in set literals and set
     comprehensions as per PEP 572.  Patch by Pablo Galindo.

   - bpo-42374(3): Fix a regression introduced by the new parser, where
     an unparenthesized walrus operator was not allowed within generator
     expressions.

   - bpo-42296(4): 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.

   - bpo-42332(5): *note types.GenericAlias: 27c. objects can now be the
     targets of weakrefs.

   - bpo-42218(6)：修正了PEG解析器中导致调试模式崩溃的错误。现在，在左递
     归规则中检查错误，以避免此类错误没有得到及时处理，并在其他地方出现
     长距离崩溃的情况。

   - bpo-42214(7)：修正了PEG解析器在检查 ‘barry_as_flufl’ 规则中的 “!=”
     标记时可能的崩溃。由Pablo Galindo修正。

   - bpo-42143(8): Fix handling of errors during creation of
     ‘PyFunctionObject’, which resulted in operations on uninitialized
     memory.  Patch by Yonatan Goldschmidt.

   - bpo-41659(9): Fix a bug in the parser, where a curly brace
     following a ‘primary’ didn’t fail immediately.  This led to invalid
     expressions like ‘a {b}’ to throw a *note SyntaxError: 559. with a
     wrong offset, or invalid expressions ending with a curly brace like
     ‘a {’ to not fail immediately in the REPL.

   - bpo-42150(10): Fix possible buffer overflow in the new parser when
     checking for continuation lines.  Patch by Pablo Galindo.

   - bpo-42123(11): 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.

   - bpo-42057(12): 修复窥孔优化程序对条件跳转 + JUMP_IF_NOT_EXC_MATCH 对
     的错误优化。

   - bpo-41984(13): 垃圾回收器现在会跟踪所有用户定义类。 由 Brandt
     Bucher 修复。

   - bpo-41993(14): Fixed potential issues with removing not completely
     initialized module from ‘sys.modules’ when import fails.

   - bpo-41979(15): Star-unpacking is now allowed for with item’s
     targets in the PEG parser.

   - bpo-41909(16): Fixed stack overflow in *note issubclass(): 552. and
     *note isinstance(): 551. when getting the ‘__bases__’ attribute
     leads to infinite recursion.

   - bpo-41894(17): 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.

   - bpo-39934(18): Correctly count control blocks in ’except’ in
     compiler.  Ensures that a syntax error, rather a fatal error,
     occurs for deeply nested, named exception handlers.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41686

   (2) https://bugs.python.org/issue42381

   (3) https://bugs.python.org/issue42374

   (4) https://bugs.python.org/issue42296

   (5) https://bugs.python.org/issue42332

   (6) https://bugs.python.org/issue42218

   (7) https://bugs.python.org/issue42214

   (8) https://bugs.python.org/issue42143

   (9) https://bugs.python.org/issue41659

   (10) https://bugs.python.org/issue42150

   (11) https://bugs.python.org/issue42123

   (12) https://bugs.python.org/issue42057

   (13) https://bugs.python.org/issue41984

   (14) https://bugs.python.org/issue41993

   (15) https://bugs.python.org/issue41979

   (16) https://bugs.python.org/issue41909

   (17) https://bugs.python.org/issue41894

   (18) https://bugs.python.org/issue39934


File: python.info,  Node: 库<11>,  Next: 文档<10>,  Prev: 核心与内置函数<11>,  Up: Python 3 9 1 release candidate 1

1.19.12.3 库
............

   - bpo-42328(1): Fixed *note tkinter.ttk.Style.map(): fe4.  The
     function accepts now the representation of the default state as
     empty sequence (as returned by ‘Style.map()’).  The structure of
     the result is now the same on all platform and does not depend on
     the value of ‘wantobjects’.

   - bpo-42345(2): Fix various issues with ‘typing.Literal’ parameter
     handling (flatten, deduplicate, use type to cache key).  Patch
     provided by Yurii Karabas.

   - bpo-42350(3): Fix the *note threading.Thread: 21a. 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.

   - bpo-42014(4): The ‘onerror’ callback from ‘shutil.rmtree’ now
     receives correct function when ‘os.open’ fails.

   - bpo-42237(5): Fix *note os.sendfile(): 461. on illumos.

   - bpo-42249(6): Fixed writing binary Plist files larger than 4 GiB.

   - bpo-35455(7): On Solaris, *note thread_time(): 1e7. is now
     implemented with ‘gethrvtime()’ because
     ‘clock_gettime(CLOCK_THREAD_CPUTIME_ID)’ is not always available.
     Patch by Jakub Kulik.

   - bpo-42233(8): The *note repr(): 8b9. of *note typing: 122. types
     containing *note Generic Alias Types: fe5. previously did not show
     the parameterized types in the ‘GenericAlias’.  They have now been
     changed to do so.

   - bpo-41754(9): webbrowser: Ignore `NotADirectoryError' when calling
     ‘xdg-settings’.

   - bpo-29566(10): ‘binhex.binhex()’ consistently writes macOS 9 line
     endings.

   - bpo-42183(11): Fix a stack overflow error for asyncio Task or
     Future repr().

     在 Task 或 Future 递归返回自身的情形下会导致栈溢出。

   - bpo-42146(12): Fix memory leak in *note subprocess.Popen(): 3db. in
     case an uid (gid) specified in ‘user’ (‘group’, ‘extra_groups’)
     overflows ‘uid_t’ (‘gid_t’).

   - bpo-42140(13): Improve asyncio.wait function to create the futures
     set just one time.

   - bpo-42103(14): ‘InvalidFileException’ and *note RecursionError:
     727. are now the only errors caused by loading malformed binary
     Plist file (previously ValueError and TypeError could be raised in
     some specific cases).

   - bpo-41052(15): Pickling heap types implemented in C with protocols
     0 and 1 raises now an error instead of producing incorrect data.

   - bpo-41491(16): plistlib: fix parsing XML plists with hexadecimal
     integer values

   - bpo-42065(17): Fix an incorrectly formatted error from
     ‘_codecs.charmap_decode()’ when called with a mapped value outside
     the range of valid Unicode code points.  PR by Max Bernstein.

   - bpo-41966(18): Fix pickling pure Python *note datetime.time: 5ec.
     subclasses.  Patch by Dean Inwood.

   - bpo-41976(19): Fixed a bug that was causing *note
     ctypes.util.find_library(): 701. to return ‘None’ when triying to
     locate a library in an environment when gcc>=9 is available and
     ‘ldconfig’ is not.  Patch by Pablo Galindo

   - bpo-41900(20): C14N 2.0 serialisation in xml.etree.ElementTree
     failed for unprefixed attributes when a default namespace was
     defined.

   - bpo-41840(21): Fix a bug in the *note symtable: fc. module that was
     causing module-scope global variables to not be reported as both
     local and global.  Patch by Pablo Galindo.

   - bpo-41831(22): ‘str()’ for the ‘type’ attribute of the
     ‘tkinter.Event’ object always returns now the numeric code returned
     by Tk instead of the name of the event type.

   - bpo-41817(23): fix ‘tkinter.EventType’ Enum so all members are
     strings, and none are tuples

   - bpo-41815(24): Fix SQLite3 segfault when backing up closed
     database.  Patch contributed by Peter David McCormick.

   - bpo-41316(25): Fix the *note tarfile: 101. module to write only
     basename of TAR file to GZIP compression header.

   - bpo-16396(26): Allow ‘ctypes.wintypes’ to be imported on
     non-Windows systems.

   - bpo-40592(27): *note shutil.which(): fe6. now ignores empty entries
     in ‘PATHEXT’ instead of treating them as a match.

   - bpo-40550(28): Fix time-of-check/time-of-action issue in
     subprocess.Popen.send_signal.

   - bpo-40492(29): Fix ‘--outfile’ for *note cProfile: 27. / *note
     profile: d3. not writing the output file in the original directory
     when the program being profiled changes the working directory.  PR
     by Anthony Sottile.

   - bpo-40105(30): ZipFile truncates files to avoid corruption when a
     shorter comment is provided in append ("a") mode.  Patch by Jan
     Mazur.

   - bpo-27321(31): Fixed KeyError exception when flattening an email to
     a string attempts to replace a non-existent
     Content-Transfer-Encoding header.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42328

   (2) https://bugs.python.org/issue42345

   (3) https://bugs.python.org/issue42350

   (4) https://bugs.python.org/issue42014

   (5) https://bugs.python.org/issue42237

   (6) https://bugs.python.org/issue42249

   (7) https://bugs.python.org/issue35455

   (8) https://bugs.python.org/issue42233

   (9) https://bugs.python.org/issue41754

   (10) https://bugs.python.org/issue29566

   (11) https://bugs.python.org/issue42183

   (12) https://bugs.python.org/issue42146

   (13) https://bugs.python.org/issue42140

   (14) https://bugs.python.org/issue42103

   (15) https://bugs.python.org/issue41052

   (16) https://bugs.python.org/issue41491

   (17) https://bugs.python.org/issue42065

   (18) https://bugs.python.org/issue41966

   (19) https://bugs.python.org/issue41976

   (20) https://bugs.python.org/issue41900

   (21) https://bugs.python.org/issue41840

   (22) https://bugs.python.org/issue41831

   (23) https://bugs.python.org/issue41817

   (24) https://bugs.python.org/issue41815

   (25) https://bugs.python.org/issue41316

   (26) https://bugs.python.org/issue16396

   (27) https://bugs.python.org/issue40592

   (28) https://bugs.python.org/issue40550

   (29) https://bugs.python.org/issue40492

   (30) https://bugs.python.org/issue40105

   (31) https://bugs.python.org/issue27321


File: python.info,  Node: 文档<10>,  Next: 测试<9>,  Prev: 库<11>,  Up: Python 3 9 1 release candidate 1

1.19.12.4 文档
..............

   - bpo-42153(1): Fix the URL for the IMAP protocol documents.

   - bpo-42061(2): Document __format__ functionality for IP addresses.

   - bpo-41910(3): 记录 *note object.__eq__: 44b. 的默认实现。

   - bpo-42010(4): Clarify that subscription expressions are also valid
     for certain *note classes: fe8. and *note types: fe9. in the
     standard library, and for user-defined classes and types if the
     classmethod *note __class_getitem__(): 437. is provided.

   - bpo-41805(5): Documented *note generic alias type: fe5. and *note
     types.GenericAlias: 27c.  Also added an entry in glossary for *note
     generic types: fea.

   - bpo-41774(6): In Programming FAQ "Sequences (Tuples/Lists)"
     section, add "How do you remove multiple items from a list".

   - bpo-35293(7): Fix RemovedInSphinx40Warning when building the
     documentation.  Patch by Dong-hee Na.

   - bpo-41726(8): Update the refcounts info of
     ‘PyType_FromModuleAndSpec’.

   - bpo-39693(9): Fix tarfile’s extractfile documentation

   - bpo-39416(10): Document some restrictions on the default string
     representations of numeric classes.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42153

   (2) https://bugs.python.org/issue42061

   (3) https://bugs.python.org/issue41910

   (4) https://bugs.python.org/issue42010

   (5) https://bugs.python.org/issue41805

   (6) https://bugs.python.org/issue41774

   (7) https://bugs.python.org/issue35293

   (8) https://bugs.python.org/issue41726

   (9) https://bugs.python.org/issue39693

   (10) https://bugs.python.org/issue39416


File: python.info,  Node: 测试<9>,  Next: 构建<7>,  Prev: 文档<10>,  Up: Python 3 9 1 release candidate 1

1.19.12.5 测试
..............

   - bpo-40754(1): Include ‘_testinternalcapi’ module in Windows
     installer for test suite

   - bpo-41739(2): Fix
     test_logging.test_race_between_set_target_and_flush(): the test now
     waits until all threads complete to avoid leaking running threads.

   - bpo-41970(3): Avoid a test failure in ‘test_lib2to3’ if the module
     has already imported at the time the test executes.  Patch by Pablo
     Galindo.

   - bpo-41944(4): Tests for CJK codecs no longer call ‘eval()’ on
     content received via HTTP.

   - bpo-41939(5): Fix test_site.test_license_exists_at_url(): call
     ‘urllib.request.urlcleanup()’ to reset the global
     ‘urllib.request._opener’.  Patch by Victor Stinner.

   - bpo-41561(6): test_ssl: skip test_min_max_version_mismatch when TLS
     1.0 is not available

   - bpo-41602(7): Add tests for SIGINT handling in the runpy module.

   - bpo-41306(8): Fixed a failure in ‘test_tk.test_widgets.ScaleTest’
     happening when executing the test with Tk 8.6.10.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40754

   (2) https://bugs.python.org/issue41739

   (3) https://bugs.python.org/issue41970

   (4) https://bugs.python.org/issue41944

   (5) https://bugs.python.org/issue41939

   (6) https://bugs.python.org/issue41561

   (7) https://bugs.python.org/issue41602

   (8) https://bugs.python.org/issue41306


File: python.info,  Node: 构建<7>,  Next: Windows<9>,  Prev: 测试<9>,  Up: Python 3 9 1 release candidate 1

1.19.12.6 构建
..............

   - bpo-42398(1): 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.

   - bpo-41617(2): Fix building ‘pycore_bitutils.h’ internal header on
     old clang version without ‘__builtin_bswap16()’ (ex: Xcode 4.6.3 on
     Mac OS X 10.7).  Patch by Joshua Root and Victor Stinner.

   - bpo-38249(3): Update *note Py_UNREACHABLE: 526. to use
     __builtin_unreachable() if only the compiler is able to use it.
     Patch by Dong-hee Na.

   - bpo-40998(4): Addressed three compiler warnings found by undefined
     behavior sanitizer (ubsan).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42398

   (2) https://bugs.python.org/issue41617

   (3) https://bugs.python.org/issue38249

   (4) https://bugs.python.org/issue40998


File: python.info,  Node: Windows<9>,  Next: macOS<9>,  Prev: 构建<7>,  Up: Python 3 9 1 release candidate 1

1.19.12.7 Windows
.................

   - bpo-42120(1): Remove macro definition of ‘copysign’ (to
     ‘_copysign’) in headers.

   - bpo-38439(2): Updates the icons for IDLE in the Windows Store
     package.

   - bpo-41744(3): Fixes automatic import of props file when using the
     Nuget package.

   - bpo-41557(4): Update Windows installer to use SQLite 3.33.0.

   - bpo-38324(5): Avoid Unicode errors when accessing certain locale
     data on Windows.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42120

   (2) https://bugs.python.org/issue38439

   (3) https://bugs.python.org/issue41744

   (4) https://bugs.python.org/issue41557

   (5) https://bugs.python.org/issue38324


File: python.info,  Node: macOS<9>,  Next: IDLE<9>,  Prev: Windows<9>,  Up: Python 3 9 1 release candidate 1

1.19.12.8 macOS
...............

   - bpo-41116(1): Ensure distutils.unixxcompiler.find_library_file can
     find system provided libraries on macOS 11.

   - bpo-41100(2): 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.

   - bpo-38443(3): The ‘--enable-universalsdk’ and
     ‘--with-universal-archs’ options for the configure script now check
     that the specified architectures can be used.

   - bpo-41471(4): Ignore invalid prefix lengths in system proxy
     excludes.

   - bpo-41557(5): Update macOS installer to use SQLite 3.33.0.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41116

   (2) https://bugs.python.org/issue41100

   (3) https://bugs.python.org/issue38443

   (4) https://bugs.python.org/issue41471

   (5) https://bugs.python.org/issue41557


File: python.info,  Node: IDLE<9>,  Next: C API<5>,  Prev: macOS<9>,  Up: Python 3 9 1 release candidate 1

1.19.12.9 IDLE
..............

   - bpo-42426(1): Fix reporting offset of the RE error in searchengine.

   - bpo-42415(2): Get docstrings for IDLE calltips more often by using
     inspect.getdoc.

   - bpo-33987(3): Mostly finish using ttk widgets, mainly for editor,
     settings, and searches.  Some patches by Mark Roseman.

   - bpo-41775(4): Use ’IDLE Shell’ as shell title

   - bpo-35764(5): Rewrite the Calltips doc section.

   - bpo-40181(6): In calltips, stop reminding that ’/’ marks the end of
     positional-only arguments.

   - bpo-40511(7): 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.

   - bpo-38439(8): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42426

   (2) https://bugs.python.org/issue42415

   (3) https://bugs.python.org/issue33987

   (4) https://bugs.python.org/issue41775

   (5) https://bugs.python.org/issue35764

   (6) https://bugs.python.org/issue40181

   (7) https://bugs.python.org/issue40511

   (8) https://bugs.python.org/issue38439


File: python.info,  Node: C API<5>,  Prev: IDLE<9>,  Up: Python 3 9 1 release candidate 1

1.19.12.10 C API
................

   - bpo-42015(1): Fix potential crash in deallocating method objects
     when dynamically allocated ‘PyMethodDef’’s lifetime is managed
     through the ‘self’ argument of a ‘PyCFunction’.

   - bpo-41986(2): ‘Py_FileSystemDefaultEncodeErrors’ and ‘Py_UTF8Mode’
     are available again in limited API.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue42015

   (2) https://bugs.python.org/issue41986


File: python.info,  Node: Python 3 9 0 final,  Next: Python 3 9 0 release candidate 2,  Prev: Python 3 9 1 release candidate 1,  Up: Changelog（更動日誌）

1.19.13 Python 3.9.0 final
--------------------------

`Release date: 2020-10-04'

* Menu:

* 库: 库<12>.
* 测试: 测试<10>.
* 构建: 构建<8>.


File: python.info,  Node: 库<12>,  Next: 测试<10>,  Up: Python 3 9 0 final

1.19.13.1 库
............

   - bpo-41815(1): Fix SQLite3 segfault when backing up closed database.
     Patch contributed by Peter David McCormick.

   - bpo-41662(2): No longer override exceptions raised in ‘__len__()’
     of a sequence of parameters in *note sqlite3: f2. with *note
     ProgrammingError: ff3.

   - bpo-41662(3): Fixed crash when mutate list of parameters during
     iteration in *note sqlite3: f2.

   - bpo-39728(4): fix default ‘_missing_’ so a duplicate *note
     ValueError: 16d. is not set as the ‘__context__’ of the original
     *note ValueError: 16d.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41815

   (2) https://bugs.python.org/issue41662

   (3) https://bugs.python.org/issue41662

   (4) https://bugs.python.org/issue39728


File: python.info,  Node: 测试<10>,  Next: 构建<8>,  Prev: 库<12>,  Up: Python 3 9 0 final

1.19.13.2 测试
..............

   - bpo-41602(1): Add tests for SIGINT handling in the runpy module.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41602


File: python.info,  Node: 构建<8>,  Prev: 测试<10>,  Up: Python 3 9 0 final

1.19.13.3 构建
..............

   - bpo-38249(1): Update *note Py_UNREACHABLE: 526. to use
     __builtin_unreachable() if only the compiler is able to use it.
     Patch by Dong-hee Na.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38249


File: python.info,  Node: Python 3 9 0 release candidate 2,  Next: Python 3 9 0 发布候选版 1,  Prev: Python 3 9 0 final,  Up: Changelog（更動日誌）

1.19.14 Python 3.9.0 release candidate 2
----------------------------------------

`Release date: 2020-09-16'

* Menu:

* 核心与内置函数: 核心与内置函数<12>.
* 库: 库<13>.
* 文档: 文档<11>.
* 测试: 测试<11>.
* 构建: 构建<9>.
* Windows: Windows<10>.
* C API: C API<6>.


File: python.info,  Node: 核心与内置函数<12>,  Next: 库<13>,  Up: Python 3 9 0 release candidate 2

1.19.14.1 核心与内置函数
........................

   - bpo-41780(1): Fix *note __dir__(): 42b. of *note
     types.GenericAlias: 27c.  Patch by Batuhan Taskaya.

   - bpo-41690(2): Fix a possible stack overflow in the parser when
     parsing functions and classes with a huge ammount of arguments.
     Patch by Pablo Galindo.

   - bpo-41681(3): Fixes the wrong error description in the error raised
     by using 2 ‘,’ in format string in f-string and *note str.format():
     5d4.

   - bpo-41654(4): Fix a crash that occurred when destroying subclasses
     of *note MemoryError: f69.  Patch by Pablo Galindo.

   - bpo-41631(5): The ‘_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
     ‘__import__()’ function to implement lazy import, whereas Python
     expected that ‘import _ast’ always return a fully initialized
     ‘_ast’ module.

   - bpo-41533(6): Free the stack allocated in ‘va_build_stack’ if
     ‘do_mkstack’ fails and the stack is not a ‘small_stack’.

   - bpo-41531(7): Fix a bug that was dropping keys when compiling dict
     literals with more than 0xFFFF elements.  Patch by Pablo Galindo.

   - bpo-41525(8): The output of ‘python --help’ contains now only ASCII
     characters.

   - bpo-29590(9): Make the stack trace correct after calling *note
     generator.throw(): ff8. on a generator that has yielded from a
     ‘yield from’.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41780

   (2) https://bugs.python.org/issue41690

   (3) https://bugs.python.org/issue41681

   (4) https://bugs.python.org/issue41654

   (5) https://bugs.python.org/issue41631

   (6) https://bugs.python.org/issue41533

   (7) https://bugs.python.org/issue41531

   (8) https://bugs.python.org/issue41525

   (9) https://bugs.python.org/issue29590


File: python.info,  Node: 库<13>,  Next: 文档<11>,  Prev: 核心与内置函数<12>,  Up: Python 3 9 0 release candidate 2

1.19.14.2 库
............

   - bpo-41517(1): fix bug allowing Enums to be extended via multiple
     inheritance

   - bpo-39587(2): use the correct mix-in data type when constructing
     Enums

   - bpo-41789(3): Honor *note object: 3d2. overrides in ‘Enum’ class
     creation (specifically, ‘__str__’, ‘__repr__’, ‘__format__’, and
     ‘__reduce_ex__’).

   - bpo-39651(4): Fix a race condition in the ‘call_soon_threadsafe()’
     method of ‘asyncio.ProactorEventLoop’: do nothing if the self-pipe
     socket has been closed.

   - bpo-41720(5): Fixed ‘turtle.Vec2D.__rmul__()’ for arguments which
     are not int or float.

   - bpo-41696(6): Fix handling of debug mode in *note asyncio.run():
     18d.  This allows setting ‘PYTHONASYNCIODEBUG’ or ‘-X dev’ to
     enable asyncio debug mode when using *note asyncio.run(): 18d.

   - bpo-41687(7): Fix implementation of sendfile to be compatible with
     Solaris.

   - bpo-39010(8): Restarting a ‘ProactorEventLoop’ on Windows no longer
     logs spurious ‘ConnectionResetErrors’.

   - bpo-41609(9): The pdb whatis command correctly reports instance
     methods as ’Method’ rather than ’Function’.

   - bpo-32751(10): When cancelling the task due to a timeout, *note
     asyncio.wait_for(): 191. will now wait until the cancellation is
     complete also in the case when `timeout' is <= 0, like it does with
     positive timeouts.

   - bpo-37658(11): *note asyncio.wait_for(): 191. now properly handles
     races between cancellation of itself and the completion of the
     wrapped awaitable.

   - bpo-40782(12): Change the method
     asyncio.AbstractEventLoop.run_in_executor to not be a coroutine.

   - bpo-41520(13): Fix *note codeop: 1c. regression that prevented
     turning compile warnings into errors.

   - bpo-41503(14): Fixed a race between setTarget and flush in
     logging.handlers.MemoryHandler.

   - bpo-41344(15): Prevent creating ‘shared_memory.SharedMemory’
     objects with ‘size=0’.

   - bpo-41025(16): Fixed an issue preventing the C implementation of
     *note zoneinfo.ZoneInfo: 17f. from being subclassed.

   - bpo-31122(17): ssl.wrap_socket() now raises ssl.SSLEOFError rather
     than OSError when peer closes connection during TLS negotiation

   - bpo-33660(18): Fix pathlib.PosixPath to resolve a relative path
     located on the root directory properly.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41517

   (2) https://bugs.python.org/issue39587

   (3) https://bugs.python.org/issue41789

   (4) https://bugs.python.org/issue39651

   (5) https://bugs.python.org/issue41720

   (6) https://bugs.python.org/issue41696

   (7) https://bugs.python.org/issue41687

   (8) https://bugs.python.org/issue39010

   (9) https://bugs.python.org/issue41609

   (10) https://bugs.python.org/issue32751

   (11) https://bugs.python.org/issue37658

   (12) https://bugs.python.org/issue40782

   (13) https://bugs.python.org/issue41520

   (14) https://bugs.python.org/issue41503

   (15) https://bugs.python.org/issue41344

   (16) https://bugs.python.org/issue41025

   (17) https://bugs.python.org/issue31122

   (18) https://bugs.python.org/issue33660


File: python.info,  Node: 文档<11>,  Next: 测试<11>,  Prev: 库<13>,  Up: Python 3 9 0 release candidate 2

1.19.14.3 文档
..............

   - bpo-37149(1): 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.

   - bpo-41624(2): Fix the signature of *note typing.Coroutine: ffb.

   - bpo-40204(3): Enable Sphinx 3.2 ‘c_allow_pre_v3’ option and disable
     ‘c_warn_on_allowed_pre_v3’ option to make the documentation
     compatible with Sphinx 2 and Sphinx 3.

   - bpo-40979(4): 重构 typing.rst，将超过 70 个类、函数和装饰器组织至新
     的子小节。

   - bpo-39883(5): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37149

   (2) https://bugs.python.org/issue41624

   (3) https://bugs.python.org/issue40204

   (4) https://bugs.python.org/issue40979

   (5) https://bugs.python.org/issue39883


File: python.info,  Node: 测试<11>,  Next: 构建<9>,  Prev: 文档<11>,  Up: Python 3 9 0 release candidate 2

1.19.14.4 测试
..............

   - bpo-41731(1): Make test_cmd_line_script pass with option ’-vv’.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41731


File: python.info,  Node: 构建<9>,  Next: Windows<10>,  Prev: 测试<11>,  Up: Python 3 9 0 release candidate 2

1.19.14.5 构建
..............

   - bpo-41617(1): Fix ‘pycore_byteswap.h’ header file to support old
     clang versions: ‘__builtin_bswap16()’ is not available in LLVM
     clang 3.0.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41617


File: python.info,  Node: Windows<10>,  Next: C API<6>,  Prev: 构建<9>,  Up: Python 3 9 0 release candidate 2

1.19.14.6 Windows
.................

   - bpo-41526(1): Fixed layout of final page of the installer by
     removing the special thanks to Mark Hammond (with his permission).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41526


File: python.info,  Node: C API<6>,  Prev: Windows<10>,  Up: Python 3 9 0 release candidate 2

1.19.14.7 C API
...............

   - bpo-41524(1): Fix bug in PyOS_mystrnicmp and PyOS_mystricmp that
     incremented pointers beyond the end of a string.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41524


File: python.info,  Node: Python 3 9 0 发布候选版 1,  Next: Python 3 9 0 beta 5,  Prev: Python 3 9 0 release candidate 2,  Up: Changelog（更動日誌）

1.19.15 Python 3.9.0 发布候选版 1
---------------------------------

`发布日期: 2020-08-11'

* Menu:

* 核心与内置函数: 核心与内置函数<13>.
* 库: 库<14>.
* 文档: 文档<12>.
* Windows: Windows<11>.
* IDLE: IDLE<10>.


File: python.info,  Node: 核心与内置函数<13>,  Next: 库<14>,  Up: Python 3 9 0 发布候选版 1

1.19.15.1 核心与内置函数
........................

   - bpo-38156(1): 正确地处理 ‘PyOS_StdioReadline’ 中 EOF 之后的中断。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38156


File: python.info,  Node: 库<14>,  Next: 文档<12>,  Prev: 核心与内置函数<13>,  Up: Python 3 9 0 发布候选版 1

1.19.15.2 库
............

   - bpo-41497(1): 在 dis 模块中修复潜在的 UnicodeDecodeError。

   - bpo-41490(2): 更新 *note ensurepip: 78. 以安装 pip 20.2.1 和
     setuptools 49.2.1。

   - bpo-41467(3): 在 Windows 上，修复 asyncio ‘recv_into()’ 当套接字/管
     道被关闭时的返回值 (*note BrokenPipeError: a7e.)：返回 ‘0’ 而不是空
     字节串 (‘b''’)。

   - bpo-41425(4): 让 tkinter 文档示例可运行。

   - bpo-41384(5): 当传给 tkinter.OptionMenu 的选项未知时引发 TclError 而
     不是 TypeError。

   - bpo-38731(6): 修复了 *note py_compile: d7. 模块命令行界面下的 *note
     NameError: e40.。

   - bpo-41317(7): 在 asyncio.loop.sock_accept() 中使用
     add_done_callback() 以在撤销时及早退订读取器。

   - bpo-41364(8): 减少 *note uuid: 12d. 的导入开销。

   - bpo-41341(9): 在 ‘get_type_hints’ 中对 *note typing.ForwardRef:
     f70. 递归求值。

   - bpo-41182(10): 选择器：使用基于 DefaultSelector 的实现

   - bpo-40726(11): 处理在 *note ast.increment_lineno(): 1003. 上
     ‘end_lineno’ 为 ‘None’ 的情况。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41497

   (2) https://bugs.python.org/issue41490

   (3) https://bugs.python.org/issue41467

   (4) https://bugs.python.org/issue41425

   (5) https://bugs.python.org/issue41384

   (6) https://bugs.python.org/issue38731

   (7) https://bugs.python.org/issue41317

   (8) https://bugs.python.org/issue41364

   (9) https://bugs.python.org/issue41341

   (10) https://bugs.python.org/issue41182

   (11) https://bugs.python.org/issue40726


File: python.info,  Node: 文档<12>,  Next: Windows<11>,  Prev: 库<14>,  Up: Python 3 9 0 发布候选版 1

1.19.15.3 文档
..............

   - bpo-41045(1): 添加了 关于f-strings调试功能的文档.

   - bpo-41314(2): 将‘‘from __future__ import annotations‘‘ 的默认值由
     ‘4.0’ 变更到‘‘3.10‘‘ (参考 PEP 563的变更).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41045

   (2) https://bugs.python.org/issue41314


File: python.info,  Node: Windows<11>,  Next: IDLE<10>,  Prev: 文档<12>,  Up: Python 3 9 0 发布候选版 1

1.19.15.4 Windows
.................

   - bpo-41492(1): 修复了UAC提示的描述.

   - bpo-40948(2): Improve post-install message to direct people to the
     "py" command.

   - bpo-41412(3): The installer will now fail to install on Windows 7
     and Windows 8.  Further, the UCRT dependency is now always
     downloaded on demand.

   - bpo-28791(4): 更新 Windows 版本以支持 SQLite 3.21.0.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41492

   (2) https://bugs.python.org/issue40948

   (3) https://bugs.python.org/issue41412

   (4) https://bugs.python.org/issue28791


File: python.info,  Node: IDLE<10>,  Prev: Windows<11>,  Up: Python 3 9 0 发布候选版 1

1.19.15.5 IDLE
..............

   - bpo-41468(1): 改进IDIE运行错误信息 (也许用户永远都看不到).

   - bpo-41373(2): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41468

   (2) https://bugs.python.org/issue41373


File: python.info,  Node: Python 3 9 0 beta 5,  Next: Python 3 9 0 beta 4,  Prev: Python 3 9 0 发布候选版 1,  Up: Changelog（更動日誌）

1.19.16 Python 3.9.0 beta 5
---------------------------

`Release date: 2020-07-20'

* Menu:

* 安全性: 安全性<7>.
* 核心与内置函数: 核心与内置函数<14>.
* 库: 库<15>.
* 文档: 文档<13>.
* macOS: macOS<10>.
* IDLE: IDLE<11>.
* C API: C API<7>.


File: python.info,  Node: 安全性<7>,  Next: 核心与内置函数<14>,  Up: Python 3 9 0 beta 5

1.19.16.1 安全性
................

   - bpo-41304(1): Fixes ‘python3x._pth’ being ignored on Windows,
     caused by the fix for bpo-29778(2) (CVE-2020-15801).

   - bpo-41162(3): Audit hooks are now cleared later during finalization
     to avoid missing events.

   - bpo-29778(4): Ensure ‘python3.dll’ is loaded from correct locations
     when Python is embedded (CVE-2020-15523).

   - bpo-39603(5): Prevent http header injection by rejecting control
     characters in http.client.putrequest(...).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41304

   (2) https://bugs.python.org/issue29778

   (3) https://bugs.python.org/issue41162

   (4) https://bugs.python.org/issue29778

   (5) https://bugs.python.org/issue39603


File: python.info,  Node: 核心与内置函数<14>,  Next: 库<15>,  Prev: 安全性<7>,  Up: Python 3 9 0 beta 5

1.19.16.2 核心与内置函数
........................

   - bpo-41295(1): 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.

   - bpo-41247(2): Always cache the running loop holder when running
     ‘asyncio.set_running_loop’.

   - bpo-41252(3): Fix incorrect refcounting in _ssl.c’s
     ‘_servername_callback()’.

   - bpo-41215(4): 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.

   - bpo-41218(5): 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.

   - bpo-41175(6): Guard against a NULL pointer dereference within
     bytearrayobject triggered by the ‘bytearray() + bytearray()’
     operation.

   - bpo-39960(7): The "hackcheck" that prevents sneaking around a
     type’s __setattr__() by calling the superclass method was rewritten
     to allow C implemented heap types.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41295

   (2) https://bugs.python.org/issue41247

   (3) https://bugs.python.org/issue41252

   (4) https://bugs.python.org/issue41215

   (5) https://bugs.python.org/issue41218

   (6) https://bugs.python.org/issue41175

   (7) https://bugs.python.org/issue39960


File: python.info,  Node: 库<15>,  Next: 文档<13>,  Prev: 核心与内置函数<14>,  Up: Python 3 9 0 beta 5

1.19.16.3 库
............

   - bpo-41288(1): Unpickling invalid NEWOBJ_EX opcode with the C
     implementation raises now UnpicklingError instead of crashing.

   - bpo-39017(2): Avoid infinite loop when reading specially crafted
     TAR files using the tarfile module (CVE-2019-20907).

   - bpo-41235(3): Fix the error handling in *note
     ssl.SSLContext.load_dh_params(): b6a.

   - bpo-41207(4): In distutils.spawn, restore expectation that
     DistutilsExecError is raised when the command is not found.

   - bpo-39168(5): Remove the ‘__new__’ method of *note typing.Generic:
     100b.

   - bpo-41194(6): Fix a crash in the ‘_ast’ module: it can no longer be
     loaded more than once.  It now uses a global state rather than a
     module state.

   - bpo-39384(7): Fixed email.contentmanager to allow set_content() to
     set a null string.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41288

   (2) https://bugs.python.org/issue39017

   (3) https://bugs.python.org/issue41235

   (4) https://bugs.python.org/issue41207

   (5) https://bugs.python.org/issue39168

   (6) https://bugs.python.org/issue41194

   (7) https://bugs.python.org/issue39384


File: python.info,  Node: 文档<13>,  Next: macOS<10>,  Prev: 库<15>,  Up: Python 3 9 0 beta 5

1.19.16.4 文档
..............

   - bpo-37703(1): Updated Documentation to comprehensively elaborate on
     the behaviour of gather.cancel()

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37703


File: python.info,  Node: macOS<10>,  Next: IDLE<11>,  Prev: 文档<13>,  Up: Python 3 9 0 beta 5

1.19.16.5 macOS
...............

   - bpo-40741(1): Update macOS installer to use SQLite 3.32.3.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40741


File: python.info,  Node: IDLE<11>,  Next: C API<7>,  Prev: macOS<10>,  Up: Python 3 9 0 beta 5

1.19.16.6 IDLE
..............

   - bpo-41300(1): Save files with non-ascii chars.  Fix regression
     released in 3.9.0b4 and 3.8.4.

   - bpo-37765(2): Add keywords to module name completion list.  Rewrite
     Completions section of IDLE doc.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41300

   (2) https://bugs.python.org/issue37765


File: python.info,  Node: C API<7>,  Prev: IDLE<11>,  Up: Python 3 9 0 beta 5

1.19.16.7 C API
...............

   - bpo-40170(1): Revert *note PyType_HasFeature(): 1010. change: it
     reads again directly the *note PyTypeObject.tp_flags: 1011. member
     when the limited C API is not used, rather than always calling
     *note PyType_GetFlags(): 1012. which hides implementation details.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40170


File: python.info,  Node: Python 3 9 0 beta 4,  Next: Python 3 9 0 beta 3,  Prev: Python 3 9 0 beta 5,  Up: Changelog（更動日誌）

1.19.17 Python 3.9.0 beta 4
---------------------------

`Release date: 2020-07-02'

* Menu:

* 安全性: 安全性<8>.
* 核心与内置函数: 核心与内置函数<15>.
* 库: 库<16>.
* 测试: 测试<12>.
* 构建: 构建<10>.
* Windows: Windows<12>.
* macOS: macOS<11>.
* IDLE: IDLE<12>.
* C API: C API<8>.


File: python.info,  Node: 安全性<8>,  Next: 核心与内置函数<15>,  Up: Python 3 9 0 beta 4

1.19.17.1 安全性
................

   - bpo-41004(1): 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).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41004


File: python.info,  Node: 核心与内置函数<15>,  Next: 库<16>,  Prev: 安全性<8>,  Up: Python 3 9 0 beta 4

1.19.17.2 核心与内置函数
........................

   - bpo-41094(1): Fix decoding errors with audit when open files with
     non-ASCII names on non-UTF-8 locale.

   - bpo-41084(2): Prefix the error message with ’f-string: ’, when
     parsing an f-string expression which throws a *note SyntaxError:
     559.

   - bpo-41076(3): 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.

   - bpo-40939(4): Deprecate ‘PyNode_Compile()’.

   - bpo-41056(5): 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)

   - bpo-41061(6): Fix incorrect expressions and asserts in hashtable
     code and tests.

   - bpo-41052(7): Opt out serialization/deserialization for
     _random.Random

   - bpo-40939(8): Deprecate *note PyParser_SimpleParseStringFlags():
     1ff, *note PyParser_SimpleParseStringFlagsFilename(): 200. and
     *note PyParser_SimpleParseFileFlags(): 201.

   - bpo-35975(9): 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.

   - bpo-40985(10): Fix a bug that caused the *note SyntaxError: 559.
     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.

   - bpo-40958(11): Fix a possible buffer overflow in the PEG parser
     when gathering information for emitting syntax errors.  Patch by
     Pablo Galindo.

   - bpo-40957(12): Fix refleak in _Py_fopen_obj() when PySys_Audit()
     fails

   - bpo-40947(13): The Python *note Path Configuration: 1016. now takes
     *note PyConfig.platlibdir: 1017. in account.

   - bpo-40847(14): 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 ‘NEWLINE’ token was emitted.  The
     old parser was working around the issue, but the new parser threw a
     *note SyntaxError: 559. for valid input due to this.  For example,
     an empty line following a line continuation character was
     interpreted as a *note SyntaxError: 559.

   - bpo-40824(15): Unexpected errors in calling the ‘__iter__’ method
     are no longer masked by ‘TypeError’ in the *note in: 179. operator
     and functions *note contains(): 17a, *note indexOf(): 17b. and
     *note countOf(): 17c. of the *note operator: c2. module.

   - bpo-19569(16): Add the private macros ‘_Py_COMP_DIAG_PUSH’,
     ‘_Py_COMP_DIAG_IGNORE_DEPR_DECLS’, and ‘_Py_COMP_DIAG_POP’.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41094

   (2) https://bugs.python.org/issue41084

   (3) https://bugs.python.org/issue41076

   (4) https://bugs.python.org/issue40939

   (5) https://bugs.python.org/issue41056

   (6) https://bugs.python.org/issue41061

   (7) https://bugs.python.org/issue41052

   (8) https://bugs.python.org/issue40939

   (9) https://bugs.python.org/issue35975

   (10) https://bugs.python.org/issue40985

   (11) https://bugs.python.org/issue40958

   (12) https://bugs.python.org/issue40957

   (13) https://bugs.python.org/issue40947

   (14) https://bugs.python.org/issue40847

   (15) https://bugs.python.org/issue40824

   (16) https://bugs.python.org/issue19569


File: python.info,  Node: 库<16>,  Next: 测试<12>,  Prev: 核心与内置函数<15>,  Up: Python 3 9 0 beta 4

1.19.17.3 库
............

   - bpo-41193(1): The ‘write_history()’ atexit function of the readline
     completer now ignores any *note OSError: 304. to ignore error if
     the filesystem is read-only, instead of only ignoring *note
     FileNotFoundError: 8ad. and *note PermissionError: 6f6.

   - bpo-41161(2): The decimal module now requires libmpdec-2.5.0.
     Users of –with-system-libmpdec should update their system library.

   - bpo-40874(3): The decimal module now requires libmpdec-2.5.0.

   - bpo-41138(4): Fixed the *note trace: 11b. module CLI for Python
     source files with non-UTF-8 encoding.

   - bpo-31938(5): Fix default-value signatures of several functions in
     the *note select: e5. module - by Anthony Sottile.

   - bpo-41068(6): Fixed reading files with non-ASCII names from ZIP
     archive directly after writing them.

   - bpo-41058(7): ‘pdb.find_function()’ now correctly determines the
     source file encoding.

   - bpo-41056(8): Fix a NULL pointer dereference within the ssl module
     during a MemoryError in the keylog callback.  (discovered by
     Coverity)

   - bpo-41056(9): Fixed an instance where a MemoryError within the
     zoneinfo module might not be reported or not reported at its
     source.  (found by Coverity)

   - bpo-41048(10): *note mimetypes.read_mime_types(): 1019. function
     reads the rule file using UTF-8 encoding, not the locale encoding.
     Patch by Srinivas Reddy Thatiparthy.

   - bpo-41043(11): Fixed the use of *note glob(): 6bd. in the stdlib:
     literal part of the path is now always correctly escaped.

   - bpo-40448(12): *note ensurepip: 78. now disables the use of ‘pip’
     cache when installing the bundled versions of ‘pip’ and
     ‘setuptools’.  Patch by Krzysztof Konopko.

   - bpo-40967(13): Removed ‘asyncio.Task.current_task()’ and
     ‘asyncio.Task.all_tasks()’.  Patch contributed by Rémi Lapeyre.

   - bpo-40955(14): Fix a minor memory leak in *note subprocess: f9.
     module when extra_groups was specified.

   - bpo-40855(15): The standard deviation and variance functions in the
     statistics module were ignoring their mu and xbar arguments.

   - bpo-40924(16): Removed support for loaders implementing .files and
     supplying TraversableResources.

   - bpo-40939(17): Use the new PEG parser when generating the stdlib
     *note keyword: a6. module.

   - bpo-40834(18): Fix truncate when sending str object
     with_xxsubinterpreters.channel_send.

   - bpo-26407(19): Unexpected errors in calling the ‘__iter__’ method
     are no longer masked by ‘TypeError’ in *note csv.reader(): 101a,
     ‘csv.writer.writerow()’ and ‘csv.writer.writerows()’.

   - bpo-38488(20): Update ensurepip to install pip 20.1.1 and
     setuptools 47.1.0.

   - bpo-36543(21): Restored the deprecated ‘xml.etree.cElementTree’
     module.

   - bpo-34226(22): Fix *note cgi.parse_multipart: 282. without
     content_length.  Patch by Roger Duran

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41193

   (2) https://bugs.python.org/issue41161

   (3) https://bugs.python.org/issue40874

   (4) https://bugs.python.org/issue41138

   (5) https://bugs.python.org/issue31938

   (6) https://bugs.python.org/issue41068

   (7) https://bugs.python.org/issue41058

   (8) https://bugs.python.org/issue41056

   (9) https://bugs.python.org/issue41056

   (10) https://bugs.python.org/issue41048

   (11) https://bugs.python.org/issue41043

   (12) https://bugs.python.org/issue40448

   (13) https://bugs.python.org/issue40967

   (14) https://bugs.python.org/issue40955

   (15) https://bugs.python.org/issue40855

   (16) https://bugs.python.org/issue40924

   (17) https://bugs.python.org/issue40939

   (18) https://bugs.python.org/issue40834

   (19) https://bugs.python.org/issue26407

   (20) https://bugs.python.org/issue38488

   (21) https://bugs.python.org/issue36543

   (22) https://bugs.python.org/issue34226


File: python.info,  Node: 测试<12>,  Next: 构建<10>,  Prev: 库<16>,  Up: Python 3 9 0 beta 4

1.19.17.4 测试
..............

   - bpo-41085(1): Fix integer overflow in the *note
     array.array.index(): 101c. method on 64-bit Windows for index
     larger than ‘2**31’.

   - bpo-41069(2): *note test.support.TESTFN: 101d. and the current
     directory for tests when run via ‘test.regrtest’ contain now
     non-ascii characters if possible.

   - bpo-38377(3): On Linux, skip tests using multiprocessing if the
     current user cannot create a file in ‘/dev/shm/’ directory.  Add
     the ‘skip_if_broken_multiprocessing_synchronize()’ function to the
     *note test.support: 106. module.

   - bpo-41009(4): Fix use of
     ‘support.require_{linux|mac|freebsd}_version()’ decorators as class
     decorator.

   - bpo-41003(5): Fix ‘test_copyreg’ when ‘numpy’ is installed:
     ‘test.pickletester’ now saves/restores warnings filters when
     importing ‘numpy’, to ignore filters installed by ‘numpy’.

   - bpo-40964(6): Disable remote *note imaplib: 97. tests, host
     cyrus.andrew.cmu.edu is blocking incoming connections.

   - bpo-40927(7): Fix test_binhex when run twice: it now uses
     import_fresh_module() to ensure that it raises DeprecationWarning
     each time.

   - bpo-34401(8): Make test_gdb properly run on HP-UX. Patch by Michael
     Osipov.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41085

   (2) https://bugs.python.org/issue41069

   (3) https://bugs.python.org/issue38377

   (4) https://bugs.python.org/issue41009

   (5) https://bugs.python.org/issue41003

   (6) https://bugs.python.org/issue40964

   (7) https://bugs.python.org/issue40927

   (8) https://bugs.python.org/issue34401


File: python.info,  Node: 构建<10>,  Next: Windows<12>,  Prev: 测试<12>,  Up: Python 3 9 0 beta 4

1.19.17.5 构建
..............

   - bpo-40204(1): Pin Sphinx version to 2.3.1 in ‘Doc/Makefile’.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40204


File: python.info,  Node: Windows<12>,  Next: macOS<11>,  Prev: 构建<10>,  Up: Python 3 9 0 beta 4

1.19.17.6 Windows
.................

   - bpo-41074(1): Fixed support of non-ASCII names in functions *note
     msilib.OpenDatabase(): 1020. and *note msilib.init_database():
     1021. and non-ASCII SQL in method *note msilib.Database.OpenView():
     1022.

   - bpo-40164(2): Updates Windows OpenSSL to 1.1.1g

   - bpo-37556(3): Extend py.exe help to mention overrides via venv,
     shebang, environmental variables & ini files.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41074

   (2) https://bugs.python.org/issue40164

   (3) https://bugs.python.org/issue37556


File: python.info,  Node: macOS<11>,  Next: IDLE<12>,  Prev: Windows<12>,  Up: Python 3 9 0 beta 4

1.19.17.7 macOS
...............

   - bpo-39580(1): Avoid opening Finder window if running installer from
     the command line.  Patch contributed by Rick Heil.

   - bpo-41100(2): 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.

   - bpo-41005(3): fixed an XDG settings issue not allowing macos to
     open browser in webbrowser.py

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39580

   (2) https://bugs.python.org/issue41100

   (3) https://bugs.python.org/issue41005


File: python.info,  Node: IDLE<12>,  Next: C API<8>,  Prev: macOS<11>,  Up: Python 3 9 0 beta 4

1.19.17.8 IDLE
..............

   - bpo-41152(1): The encoding of ‘stdin’, ‘stdout’ and ‘stderr’ in
     IDLE is now always UTF-8.

   - bpo-41144(2): Make Open Module open a special module such as
     os.path.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue41152

   (2) https://bugs.python.org/issue41144


File: python.info,  Node: C API<8>,  Prev: IDLE<12>,  Up: Python 3 9 0 beta 4

1.19.17.9 C API
...............

   - bpo-36346(1): Mark ‘Py_UNICODE_COPY’, ‘Py_UNICODE_FILL’,
     ‘PyUnicode_WSTR_LENGTH’, ‘PyUnicode_FromUnicode’,
     ‘PyUnicode_AsUnicode’, ‘_PyUnicode_AsUnicode’, and
     ‘PyUnicode_AsUnicodeAndSize’ as deprecated in C. Remove
     ‘Py_UNICODE_MATCH’ which was deprecated and broken since Python
     3.3.

   - bpo-36020(2): On Windows, ‘#include "pyerrors.h"’ no longer defines
     ‘snprintf’ and ‘vsnprintf’ macros.

   - bpo-40703(3): The PyType_FromSpec*() functions no longer overwrite
     the type’s "__module__" attribute if it is set via "Py_tp_members"
     or "Py_tp_getset".

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36346

   (2) https://bugs.python.org/issue36020

   (3) https://bugs.python.org/issue40703


File: python.info,  Node: Python 3 9 0 beta 3,  Next: Python 3 9 0 beta 2,  Prev: Python 3 9 0 beta 4,  Up: Changelog（更動日誌）

1.19.18 Python 3.9.0 beta 3
---------------------------

`Release date: 2020-06-09'

* Menu:

* 库: 库<17>.
* 构建: 构建<11>.


File: python.info,  Node: 库<17>,  Next: 构建<11>,  Up: Python 3 9 0 beta 3

1.19.18.1 库
............

   - bpo-40924(1): *note importlib.resources: 9e.: Reverted
     ‘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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40924


File: python.info,  Node: 构建<11>,  Prev: 库<17>,  Up: Python 3 9 0 beta 3

1.19.18.2 构建
..............

   - bpo-40684(1): ‘make install’ now uses the ‘PLATLIBDIR’ variable for
     the destination ‘lib-dynload/’ directory when ‘./configure
     --with-platlibdir’ is used.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40684


File: python.info,  Node: Python 3 9 0 beta 2,  Next: Python 3 9 0 beta 1,  Prev: Python 3 9 0 beta 3,  Up: Changelog（更動日誌）

1.19.19 Python 3.9.0 beta 2
---------------------------

`Release date: 2020-06-08'

* Menu:

* 核心与内置函数: 核心与内置函数<16>.
* 库: 库<18>.
* 测试: 测试<13>.
* 构建: 构建<12>.
* Windows: Windows<13>.
* macOS: macOS<12>.
* IDLE: IDLE<13>.
* C API: C API<9>.


File: python.info,  Node: 核心与内置函数<16>,  Next: 库<18>,  Up: Python 3 9 0 beta 2

1.19.19.1 核心与内置函数
........................

   - bpo-40904(1): Fix possible segfault in the new PEG parser when
     parsing f-string containing yield statements with no value
     (‘f"{yield}"’).  Patch by Pablo Galindo

   - bpo-40903(2): Fixed a possible segfault in the new PEG parser when
     producing error messages for invalid assignments of the form
     ‘p=p=’.  Patch by Pablo Galindo

   - bpo-40880(3): Fix invalid memory read in the new parser when
     checking newlines in string literals.  Patch by Pablo Galindo.

   - bpo-40883(4): Fix memory leak in when parsing f-strings in the new
     parser.  Patch by Pablo Galindo

   - bpo-40870(5): Raise *note ValueError: 16d. when validating custom
     AST’s where the constants ‘True’, ‘False’ and ‘None’ are used
     within a *note ast.Name: 102b. node.

   - bpo-40854(6): Allow overriding *note sys.platlibdir: 1e9. via a new
     *note PYTHONPLATLIBDIR: 102c. environment variable.

   - bpo-40826(7): Fix GIL usage in ‘PyOS_Readline()’: lock the GIL to
     set an exception and pass the Python thread state when checking if
     there is a pending signal.

   - bpo-40780(8): Fix a corner case where g-style string formatting of
     a float failed to remove trailing zeros.

   - bpo-38964(9): When there’s a *note SyntaxError: 559. in the
     expression part of an fstring, the filename attribute of the *note
     SyntaxError: 559. gets correctly set to the name of the file the
     fstring resides in.

   - bpo-40750(10): Support the "-d" debug flag in the new PEG parser.
     Patch by Pablo Galindo

   - bpo-40217(11): Instances of types created with *note
     PyType_FromSpecWithBases(): 102d. 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.

   - bpo-40696(12): Fix a hang that can arise after *note
     generator.throw(): ff8. due to a cycle in the exception context
     chain.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40904

   (2) https://bugs.python.org/issue40903

   (3) https://bugs.python.org/issue40880

   (4) https://bugs.python.org/issue40883

   (5) https://bugs.python.org/issue40870

   (6) https://bugs.python.org/issue40854

   (7) https://bugs.python.org/issue40826

   (8) https://bugs.python.org/issue40780

   (9) https://bugs.python.org/issue38964

   (10) https://bugs.python.org/issue40750

   (11) https://bugs.python.org/issue40217

   (12) https://bugs.python.org/issue40696


File: python.info,  Node: 库<18>,  Next: 测试<13>,  Prev: 核心与内置函数<16>,  Up: Python 3 9 0 beta 2

1.19.19.2 库
............

   - bpo-39791(1): Refresh importlib.metadata from importlib_metadata
     1.6.1.

   - bpo-40807(2): Stop codeop._maybe_compile, used by
     code.InteractiveInterpreter (and IDLE). from from emitting each
     warning three times.

   - bpo-39791(3): Built-in loaders (SourceFileLoader and ZipImporter)
     now supply ‘TraversableResources’ implementations for
     ‘ResourceReader’, and the fallback function has been removed.

   - bpo-17005(4): The topological sort functionality that was
     introduced initially in the *note functools: 83. module has been
     moved to a new *note graphlib: 89. module to better accommodate the
     new tools and keep the original scope of the *note functools: 83.
     module.  Patch by Pablo Galindo

   - bpo-40777(5): Initialize PyDateTime_IsoCalendarDateType.tp_base at
     run-time to avoid errors on some compilers.

   - bpo-40767(6): *note webbrowser: 132. now properly finds the default
     browser in pure Wayland systems by checking the WAYLAND_DISPLAY
     environment variable.  Patch contributed by Jérémy Attali.

   - bpo-40791(7): ‘hashlib.compare_digest()’ uses OpenSSL’s
     ‘CRYPTO_memcmp()’ function when OpenSSL is available.

   - bpo-40795(8): *note ctypes: 2a. 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 *note
     PyErr_Print(): 102f.

   - bpo-30008(9): Fix *note ssl: f3. code to be compatible with OpenSSL
     1.1.x builds that use ‘no-deprecated’ and ‘--api=1.1.0’.

   - bpo-30064(10): Fix asyncio ‘loop.sock_*’ race condition issue

   - bpo-40759(11): Deprecate the *note symbol: fb. module.

   - bpo-40737(12): Fix possible reference leak for *note sqlite3: f2.
     initialization.

   - bpo-40698(13): *note distutils: 38. upload creates SHA2-256 and
     Blake2b-256 digests.  MD5 digests is skipped if platform blocks
     MD5.

   - bpo-40695(14): *note hashlib: 8c. no longer falls back to builtin
     hash implementations when OpenSSL provides a hash digest and the
     algorithm is blocked by security policy.

   - bpo-9216(15): func:*note hashlib.new: 1030. passed
     ‘usedforsecurity’ to OpenSSL EVP constructor ‘_hashlib.new()’.
     test_hashlib and test_smtplib handle strict security policy better.

   - bpo-40614(16): *note ast.parse(): 2d6. will not parse self
     documenting expressions in f-strings when passed ‘feature_version’
     is less than ‘(3, 8)’.

   - bpo-40671(17): Prepare ‘_hashlib’ for PEP 489(18) and use *note
     PyModule_AddType(): 253.

   - bpo-32309(19): Added a new *note coroutine: 18a. *note
     asyncio.to_thread(): 18f.  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 *note
     run_in_executor(): 190. that can directly take keyword arguments.

   - bpo-40630(20): Added *note tracemalloc.reset_peak(): 1ec. to set
     the peak size of traced memory blocks to the current size, to
     measure the peak of specific pieces of code.

   - bpo-13097(21): ‘ctypes’ now raises an ‘ArgumentError’ when a
     callback is invoked with more than 1024 arguments.

   - bpo-23082(22): Updated the error message and docs of
     PurePath.relative_to() to better reflect the function behaviour.

   - bpo-39244(23): Fixed
     ‘multiprocessing.context.get_all_start_methods’ to properly return
     the default method first on macOS.

   - bpo-39040(24): Fix parsing of invalid mime headers parameters by
     collapsing whitespace between encoded words in a bare-quote-string.

   - bpo-35714(25): *note struct.error: d7c. is now raised if there is a
     null character in a *note struct: f8. format string.

   - bpo-36290(26): AST nodes are now raising *note TypeError: 1fe. on
     conflicting keyword arguments.  Patch contributed by Rémi Lapeyre.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39791

   (2) https://bugs.python.org/issue40807

   (3) https://bugs.python.org/issue39791

   (4) https://bugs.python.org/issue17005

   (5) https://bugs.python.org/issue40777

   (6) https://bugs.python.org/issue40767

   (7) https://bugs.python.org/issue40791

   (8) https://bugs.python.org/issue40795

   (9) https://bugs.python.org/issue30008

   (10) https://bugs.python.org/issue30064

   (11) https://bugs.python.org/issue40759

   (12) https://bugs.python.org/issue40737

   (13) https://bugs.python.org/issue40698

   (14) https://bugs.python.org/issue40695

   (15) https://bugs.python.org/issue9216

   (16) https://bugs.python.org/issue40614

   (17) https://bugs.python.org/issue40671

   (18) https://www.python.org/dev/peps/pep-0489

   (19) https://bugs.python.org/issue32309

   (20) https://bugs.python.org/issue40630

   (21) https://bugs.python.org/issue13097

   (22) https://bugs.python.org/issue23082

   (23) https://bugs.python.org/issue39244

   (24) https://bugs.python.org/issue39040

   (25) https://bugs.python.org/issue35714

   (26) https://bugs.python.org/issue36290


File: python.info,  Node: 测试<13>,  Next: 构建<12>,  Prev: 库<18>,  Up: Python 3 9 0 beta 2

1.19.19.3 测试
..............

   - bpo-17258(1): Skip some *note multiprocessing: b7. tests when MD5
     hash digest is blocked.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17258


File: python.info,  Node: 构建<12>,  Next: Windows<13>,  Prev: 测试<13>,  Up: Python 3 9 0 beta 2

1.19.19.4 构建
..............

   - bpo-40514(1): Remove ‘--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.

   - bpo-40683(2): Fixed an issue where the *note zoneinfo: 14e. module
     and its tests were not included when Python is installed with
     ‘make’.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40514

   (2) https://bugs.python.org/issue40683


File: python.info,  Node: Windows<13>,  Next: macOS<12>,  Prev: 构建<12>,  Up: Python 3 9 0 beta 2

1.19.19.5 Windows
.................

   - bpo-39631(1): Changes the registered MIME type for ‘.py’ files on
     Windows to ‘text/x-python’ instead of ‘text/plain’.

   - bpo-40677(2): Manually define IO_REPARSE_TAG_APPEXECLINK in case
     some old Windows SDK doesn’t have it.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39631

   (2) https://bugs.python.org/issue40677


File: python.info,  Node: macOS<12>,  Next: IDLE<13>,  Prev: Windows<13>,  Up: Python 3 9 0 beta 2

1.19.19.6 macOS
...............

   - bpo-40741(1): Update macOS installer to use SQLite 3.32.2.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40741


File: python.info,  Node: IDLE<13>,  Next: C API<9>,  Prev: macOS<12>,  Up: Python 3 9 0 beta 2

1.19.19.7 IDLE
..............

   - bpo-39885(1): Make context menu Cut and Copy work again when
     right-clicking within a selection.

   - bpo-40723(2): Make test_idle pass when run after import.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39885

   (2) https://bugs.python.org/issue40723


File: python.info,  Node: C API<9>,  Prev: IDLE<13>,  Up: Python 3 9 0 beta 2

1.19.19.8 C API
...............

   - bpo-40910(1): Export explicitly the *note Py_GetArgcArgv(): 1037.
     function to the C API and document the function.  Previously, it
     was exported implicitly which no longer works since Python is built
     with ‘-fvisibility=hidden’.

   - bpo-40724(2): Allow defining buffer slots in type specs.

   - bpo-40826(3): ‘PyOS_InterruptOccurred()’ now fails with a fatal
     error if it is called with the GIL released.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40910

   (2) https://bugs.python.org/issue40724

   (3) https://bugs.python.org/issue40826


File: python.info,  Node: Python 3 9 0 beta 1,  Next: Python 3 9 0 alpha 6,  Prev: Python 3 9 0 beta 2,  Up: Changelog（更動日誌）

1.19.20 Python 3.9.0 beta 1
---------------------------

`发布日期: 2020-05-19'

* Menu:

* 安全性: 安全性<9>.
* 核心与内置函数: 核心与内置函数<17>.
* 库: 库<19>.
* 文档: 文档<14>.
* 测试: 测试<14>.
* 构建: 构建<13>.
* Windows: Windows<14>.
* macOS: macOS<13>.
* 工具/示例: 工具/示例<4>.
* C API: C API<10>.


File: python.info,  Node: 安全性<9>,  Next: 核心与内置函数<17>,  Up: Python 3 9 0 beta 1

1.19.20.1 安全性
................

   - bpo-40501(1): *note uuid: 12d. no longer uses *note ctypes: 2a. to
     load ‘libuuid’ or ‘rpcrt4.dll’ at runtime.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40501


File: python.info,  Node: 核心与内置函数<17>,  Next: 库<19>,  Prev: 安全性<9>,  Up: Python 3 9 0 beta 1

1.19.20.2 核心与内置函数
........................

   - bpo-40663(1): Correctly generate annotations where parentheses are
     omitted but required (e.g: ‘Type[(str, int, *other))]’.

   - bpo-40596(2): Fixed *note str.isidentifier(): 103b. for
     non-canonicalized strings containing non-BMP characters on Windows.

   - bpo-40593(3): Improved syntax errors for invalid characters in
     source code.

   - bpo-40585(4): Fixed a bug when using *note
     codeop.compile_command(): 103c. that was causing exceptions to be
     swallowed with the new parser.  Patch by Pablo Galindo

   - bpo-40566(5): Apply PEP 573(6) to *note abc: 3.

   - bpo-40502(7): Initialize ‘n->n_col_offset’.  (Patch by Joannah
     Nanjekye)

   - bpo-40527(8): Fix command line argument parsing: no longer write
     errors multiple times into stderr.

   - bpo-1635741(9): Port *note errno: 7a. to multiphase initialization
     ( PEP 489(10)).

   - bpo-40523(11): Add pass-throughs for *note hash(): aa3. and *note
     reversed(): 2c6. to *note weakref.proxy: 37a. objects.  Patch by
     Pablo Galindo.

   - bpo-1635741(12): Port *note syslog: ff. to multiphase
     initialization ( PEP 489(13)).

   - bpo-40246(14): Reporting a specialised error message for invalid
     string prefixes, which was introduced in bpo-40246(15), is being
     reverted due to backwards compatibility concerns for strings that
     immediately follow a reserved keyword without whitespace between
     them.  Constructs like ‘bg="#d00" if clear else"#fca"’ were failing
     to parse, which is not an acceptable breakage on such short notice.

   - bpo-40417(16): Fix imp module deprecation warning when
     PyImport_ReloadModule is called.  Patch by Robert Rouhani.

   - bpo-40408(17): Fixed support of nested type variables in
     GenericAlias (e.g.  ‘list[list[T]]’).

   - bpo-1635741(18): Port _stat module to multiphase initialization (
     PEP 489(19)).

   - bpo-29587(20): Enable implicit exception chaining when calling
     *note generator.throw(): ff8.

   - bpo-40328(21): Add tools for generating mappings headers for
     CJKCodecs.

   - bpo-40228(22): Setting frame.f_lineno is now robust w.r.t.  changes
     in the source-to-bytecode compiler

   - bpo-38880(23): Added the ability to list interpreters associated
     with channel ends in the internal subinterpreters module.

   - bpo-37986(24): Improve performance of *note PyLong_FromDouble():
     1f4. for values that fit into ‘long’.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40663

   (2) https://bugs.python.org/issue40596

   (3) https://bugs.python.org/issue40593

   (4) https://bugs.python.org/issue40585

   (5) https://bugs.python.org/issue40566

   (6) https://www.python.org/dev/peps/pep-0573

   (7) https://bugs.python.org/issue40502

   (8) https://bugs.python.org/issue40527

   (9) https://bugs.python.org/issue1635741

   (10) https://www.python.org/dev/peps/pep-0489

   (11) https://bugs.python.org/issue40523

   (12) https://bugs.python.org/issue1635741

   (13) https://www.python.org/dev/peps/pep-0489

   (14) https://bugs.python.org/issue40246

   (15) https://bugs.python.org/issue40246

   (16) https://bugs.python.org/issue40417

   (17) https://bugs.python.org/issue40408

   (18) https://bugs.python.org/issue1635741

   (19) https://www.python.org/dev/peps/pep-0489

   (20) https://bugs.python.org/issue29587

   (21) https://bugs.python.org/issue40328

   (22) https://bugs.python.org/issue40228

   (23) https://bugs.python.org/issue38880

   (24) https://bugs.python.org/issue37986


File: python.info,  Node: 库<19>,  Next: 文档<14>,  Prev: 核心与内置函数<17>,  Up: Python 3 9 0 beta 1

1.19.20.3 库
............

   - bpo-40662(1): Fixed *note ast.get_source_segment(): 2d5. for ast
     nodes that have incomplete location information.  Patch by Irit
     Katriel.

   - bpo-40665(2): Convert *note bisect: 11. to use Argument Clinic.

   - bpo-40536(3): Added the *note available_timezones(): 103e. function
     to the *note zoneinfo: 14e. module.  Patch by Paul Ganssle.

   - bpo-40645(4): The ‘hmac.HMAC’ exposes internal implementation
     details.  The attributes ‘digest_cons’, ‘inner’, and ‘outer’ are
     deprecated and will be removed in the future.

   - bpo-40645(5): The internal module ‘_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.

   - bpo-40637(6): Builtin hash modules can now be disabled or
     selectively enabled with ‘configure
     --with-builtin-hashlib-hashes=sha3,blake1’ or
     ‘--without-builtin-hashlib-hashes’.

   - bpo-37630(7): The *note hashlib: 8c. module can now use SHA3 hashes
     and SHAKE XOF from OpenSSL when available.

   - bpo-40479(8): The *note hashlib: 8c. now compiles with OpenSSL
     3.0.0-alpha2.

   - bpo-40257(9): Revert changes to *note inspect.getdoc(): 307.

   - bpo-40607(10): When cancelling a task due to timeout, *note
     asyncio.wait_for(): 191. will now propagate the exception if an
     error happens during cancellation.  Patch by Roman Skurikhin.

   - bpo-40612(11): 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.

   - bpo-40597(12): If text content lines are longer than
     policy.max_line_length, always use a content-encoding to make sure
     they are wrapped.

   - bpo-40571(13): Added functools.cache() as a simpler, more
     discoverable way to access the unbounded cache variant of
     lru_cache(maxsize=None).

   - bpo-40503(14): PEP 615(15), the *note zoneinfo: 14e. module.  Adds
     support for the IANA time zone database.

   - bpo-40397(16): Removed attributes ‘__args__’ and ‘__parameters__’
     from special generic aliases like ‘typing.List’ (not subscripted).

   - bpo-40549(17): Convert posixmodule.c ("posix" or "nt" module) to
     the multiphase initialization (PEP 489).

   - bpo-31033(18): Add a ‘msg’ argument to ‘Future.cancel()’ and
     ‘Task.cancel()’.

   - bpo-40541(19): Added an optional `counts' parameter to
     random.sample().

   - bpo-40515(20): The *note ssl: f3. and *note hashlib: 8c. 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.

   - bpo-31033(21): When a *note asyncio.Task: 2e0. is cancelled, the
     exception traceback now chains all the way back to where the task
     was first interrupted.

   - bpo-40504(22): *note functools.lru_cache(): 2f8. objects can now be
     the targets of weakrefs.

   - bpo-40559(23): Fix possible memory leak in the C implementation of
     *note asyncio.Task: 2e0.

   - bpo-40480(24): ‘fnmatch.fnmatch()’ could take exponential time in
     the presence of multiple ‘*’ pattern characters.  This was repaired
     by generating more elaborate regular expressions to avoid futile
     backtracking.

   - bpo-40495(25): *note compileall: 20. is now able to use hardlinks
     to prevent duplicates in a case when ‘.pyc’ files for different
     optimization levels have the same content.

   - bpo-40457(26): The ssl module now support OpenSSL builds without
     TLS 1.0 and 1.1 methods.

   - bpo-40355(27): Improve error reporting in *note ast.literal_eval():
     59f. in the presence of malformed *note ast.Dict: 103f. nodes
     instead of silently ignoring any non-conforming elements.  Patch by
     Curtis Bucher.

   - bpo-40465(28): Deprecated the optional `random' argument to
     `random.shuffle()'.

   - bpo-40459(29): *note platform.win32_ver(): 1040. now produces
     correct `ptype' strings instead of empty strings.

   - bpo-39435(30): The first argument of *note pickle.loads(): 6ba. is
     now positional-only.

   - bpo-39305(31): Update *note nntplib: c0. to merge *note
     nntplib.NNTP: 1c6. and ‘nntplib._NNTPBase’.  Patch by Dong-hee Na.

   - bpo-32494(32): Update *note dbm.gnu: 33. to use gdbm_count if
     possible when calling *note len(): 28b.  Patch by Dong-hee Na.

   - bpo-40453(33): Add ‘isolated=True’ keyword-only parameter to
     ‘_xxsubinterpreters.create()’.  An isolated subinterpreter cannot
     spawn threads, spawn a child process or call ‘os.fork()’.

   - bpo-40286(34): Remove ‘_random.Random.randbytes()’: the C
     implementation of ‘randbytes()’.  Implement the method in Python to
     ease subclassing: ‘randbytes()’ now directly reuses
     ‘getrandbits()’.

   - bpo-40394(35): Added default arguments to *note
     difflib.SequenceMatcher.find_longest_match(): 1041.

   - bpo-39995(36): Fix a race condition in
     concurrent.futures._ThreadWakeup: access to _ThreadWakeup is now
     protected with the shutdown lock.

   - bpo-30966(37): ‘Process.shutdown(wait=True)’ of *note
     concurrent.futures: 21. now closes explicitly the result queue.

   - bpo-30966(38): Add a new *note close(): 1c4. method to the *note
     SimpleQueue: 1c3. class to explicitly close the queue.

   - bpo-39966(39): Revert bpo-25597(40).  *note
     unittest.mock.MagicMock: 874. with wraps’ set uses default return
     values for magic methods.

   - bpo-39791(41): Added ‘files()’ function to importlib.resources with
     support for subdirectories in package data, matching backport in
     importlib_resources 1.5.

   - bpo-40375(42): *note imaplib.IMAP4.unselect(): 1b3. is added.
     Patch by Dong-hee Na.

   - bpo-40389(43): ‘repr()’ now returns ‘typing.Optional[T]’ when
     called for ‘typing.Union’ of two types, one of which is ‘NoneType’.

   - bpo-40291(44): Add support for CAN_J1939 sockets (available on
     Linux 5.4+)

   - bpo-40273(45): *note types.MappingProxyType: b8e. is now
     reversible.

   - bpo-39075(46): The repr for *note types.SimpleNamespace: 1d8. is
     now insertion ordered rather than alphabetical.

   - bpo-40192(47): On AIX, *note thread_time(): 1e7. is now implemented
     with ‘thread_cputime()’ which has nanosecond resolution, rather
     than ‘clock_gettime(CLOCK_THREAD_CPUTIME_ID)’ which has a
     resolution of 10 ms.  Patch by Batuhan Taskaya.

   - bpo-40025(48): Raise TypeError when _generate_next_value_ is
     defined after members.  Patch by Ethan Onstott.

   - bpo-39058(49): 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.

   - bpo-24416(50): The ‘isocalendar()’ methods of *note datetime.date:
     19d. and *note datetime.datetime: 19f. now return a *note named
     tuple: b7b. instead of a *note tuple: 1a2.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40662

   (2) https://bugs.python.org/issue40665

   (3) https://bugs.python.org/issue40536

   (4) https://bugs.python.org/issue40645

   (5) https://bugs.python.org/issue40645

   (6) https://bugs.python.org/issue40637

   (7) https://bugs.python.org/issue37630

   (8) https://bugs.python.org/issue40479

   (9) https://bugs.python.org/issue40257

   (10) https://bugs.python.org/issue40607

   (11) https://bugs.python.org/issue40612

   (12) https://bugs.python.org/issue40597

   (13) https://bugs.python.org/issue40571

   (14) https://bugs.python.org/issue40503

   (15) https://www.python.org/dev/peps/pep-0615

   (16) https://bugs.python.org/issue40397

   (17) https://bugs.python.org/issue40549

   (18) https://bugs.python.org/issue31033

   (19) https://bugs.python.org/issue40541

   (20) https://bugs.python.org/issue40515

   (21) https://bugs.python.org/issue31033

   (22) https://bugs.python.org/issue40504

   (23) https://bugs.python.org/issue40559

   (24) https://bugs.python.org/issue40480

   (25) https://bugs.python.org/issue40495

   (26) https://bugs.python.org/issue40457

   (27) https://bugs.python.org/issue40355

   (28) https://bugs.python.org/issue40465

   (29) https://bugs.python.org/issue40459

   (30) https://bugs.python.org/issue39435

   (31) https://bugs.python.org/issue39305

   (32) https://bugs.python.org/issue32494

   (33) https://bugs.python.org/issue40453

   (34) https://bugs.python.org/issue40286

   (35) https://bugs.python.org/issue40394

   (36) https://bugs.python.org/issue39995

   (37) https://bugs.python.org/issue30966

   (38) https://bugs.python.org/issue30966

   (39) https://bugs.python.org/issue39966

   (40) https://bugs.python.org/issue25597

   (41) https://bugs.python.org/issue39791

   (42) https://bugs.python.org/issue40375

   (43) https://bugs.python.org/issue40389

   (44) https://bugs.python.org/issue40291

   (45) https://bugs.python.org/issue40273

   (46) https://bugs.python.org/issue39075

   (47) https://bugs.python.org/issue40192

   (48) https://bugs.python.org/issue40025

   (49) https://bugs.python.org/issue39058

   (50) https://bugs.python.org/issue24416


File: python.info,  Node: 文档<14>,  Next: 测试<14>,  Prev: 库<19>,  Up: Python 3 9 0 beta 1

1.19.20.4 文档
..............

   - bpo-34790(1): Add version of removal for explicit passing of coros
     to *note asyncio.wait(): 207.’s documentation

   - bpo-40561(2): Provide docstrings for webbrowser open functions.

   - bpo-40499(3): Mention that *note asyncio.wait(): 207. requires a
     non-empty set of awaitables.

   - bpo-39705(4): 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.

   - bpo-39435(5): Fix an incorrect signature for *note pickle.loads():
     6ba. in the docs

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue34790

   (2) https://bugs.python.org/issue40561

   (3) https://bugs.python.org/issue40499

   (4) https://bugs.python.org/issue39705

   (5) https://bugs.python.org/issue39435


File: python.info,  Node: 测试<14>,  Next: 构建<13>,  Prev: 文档<14>,  Up: Python 3 9 0 beta 1

1.19.20.5 测试
..............

   - bpo-40055(1): distutils.tests now saves/restores warnings filters
     to leave them unchanged.  Importing tests imports docutils which
     imports pkg_resources which adds a warnings filter.

   - bpo-40436(2): test_gdb and test.pythoninfo now check gdb command
     exit code.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40055

   (2) https://bugs.python.org/issue40436


File: python.info,  Node: 构建<13>,  Next: Windows<14>,  Prev: 测试<14>,  Up: Python 3 9 0 beta 1

1.19.20.6 构建
..............

   - bpo-40653(1): Move _dirnameW out of HAVE_SYMLINK to fix a potential
     compiling issue.

   - bpo-40514(2): Add ‘--with-experimental-isolated-subinterpreters’
     build option to ‘configure’: better isolate subinterpreters,
     experimental build mode.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40653

   (2) https://bugs.python.org/issue40514


File: python.info,  Node: Windows<14>,  Next: macOS<13>,  Prev: 构建<13>,  Up: Python 3 9 0 beta 1

1.19.20.7 Windows
.................

   - bpo-40650(1): Include winsock2.h in pytime.c for timeval.

   - bpo-40458(2): Increase reserved stack space to prevent overflow
     crash on Windows.

   - bpo-39148(3): Add IPv6 support to *note asyncio: 9. datagram
     endpoints in ProactorEventLoop.  Change the raised exception for
     unknown address families to ValueError as it’s not coming from
     Windows API.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40650

   (2) https://bugs.python.org/issue40458

   (3) https://bugs.python.org/issue39148


File: python.info,  Node: macOS<13>,  Next: 工具/示例<4>,  Prev: Windows<14>,  Up: Python 3 9 0 beta 1

1.19.20.8 macOS
...............

   - bpo-34956(1): When building Python on macOS from source, ‘_tkinter’
     now links with non-system Tcl and Tk frameworks if they are
     installed in ‘/Library/Frameworks’, as had been the case on older
     releases of macOS. If a macOS SDK is explicitly configured, by
     using ‘--enable-universalsdk=’ or ‘-isysroot’, only the SDK itself
     is searched.  The default behavior can still be overridden with
     ‘--with-tcltk-includes’ and ‘--with-tcltk-libs’.

   - bpo-35569(2): Expose RFC 3542 IPv6 socket options.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue34956

   (2) https://bugs.python.org/issue35569


File: python.info,  Node: 工具/示例<4>,  Next: C API<10>,  Prev: macOS<13>,  Up: Python 3 9 0 beta 1

1.19.20.9 工具/示例
...................

   - bpo-40479(1): Update multissltest helper to test with latest
     OpenSSL 1.0.2, 1.1.0, 1.1.1, and 3.0.0-alpha.

   - bpo-40431(2): Fix a syntax typo in ‘turtledemo’ that now raises a
     ‘SyntaxError’.

   - bpo-40163(3): Fix multissltest tool.  OpenSSL has changed download
     URL for old releases.  The multissltest tool now tries to download
     from current and old download URLs.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40479

   (2) https://bugs.python.org/issue40431

   (3) https://bugs.python.org/issue40163


File: python.info,  Node: C API<10>,  Prev: 工具/示例<4>,  Up: Python 3 9 0 beta 1

1.19.20.10 C API
................

   - bpo-39465(1): Remove the ‘_PyUnicode_ClearStaticStrings()’ function
     from the C API.

   - bpo-38787(2): 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.

   - bpo-40545(3): Declare ‘_PyErr_GetTopmostException()’ with
     ‘PyAPI_FUNC()’ to properly export the function in the C API. The
     function remains private (‘_Py’) prefix.

   - bpo-40412(4): Nullify inittab_copy during finalization, preventing
     future interpreter initializations in an embedded situation from
     crashing.  Patch by Gregory Szorc.

   - bpo-40429(5): The *note PyThreadState_GetFrame(): 24e. function now
     returns a strong reference to the frame.

   - bpo-40428(6): Remove the following functions from the C API. Call
     ‘PyGC_Collect()’ explicitly to free all free lists.

        * ‘PyAsyncGen_ClearFreeLists()’

        * ‘PyContext_ClearFreeList()’

        * ‘PyDict_ClearFreeList()’

        * ‘PyFloat_ClearFreeList()’

        * ‘PyFrame_ClearFreeList()’

        * ‘PyList_ClearFreeList()’

        * ‘PySet_ClearFreeList()’

        * ‘PyTuple_ClearFreeList()’

   - bpo-40421(7): New *note PyFrame_GetBack(): 24a. function: get the
     frame next outer frame.

   - bpo-40421(8): New *note PyFrame_GetCode(): 249. function: return a
     borrowed reference to the frame code.

   - bpo-40217(9): Ensure that instances of types created with *note
     PyType_FromSpecWithBases(): 102d. will visit its class object when
     traversing references in the garbage collector (implemented as an
     extension of the provided *note tp_traverse: 23b.).  Patch by Pablo
     Galindo.

   - bpo-38787(10): Module C state is now accessible from C-defined heap
     type methods ( PEP 573(11)).  Patch by Marcel Plch and Petr
     Viktorin.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39465

   (2) https://bugs.python.org/issue38787

   (3) https://bugs.python.org/issue40545

   (4) https://bugs.python.org/issue40412

   (5) https://bugs.python.org/issue40429

   (6) https://bugs.python.org/issue40428

   (7) https://bugs.python.org/issue40421

   (8) https://bugs.python.org/issue40421

   (9) https://bugs.python.org/issue40217

   (10) https://bugs.python.org/issue38787

   (11) https://www.python.org/dev/peps/pep-0573


File: python.info,  Node: Python 3 9 0 alpha 6,  Next: Python 3 9 0 alpha 5,  Prev: Python 3 9 0 beta 1,  Up: Changelog（更動日誌）

1.19.21 Python 3.9.0 alpha 6
----------------------------

`发布日期: 2020-04-27'

* Menu:

* 安全性: 安全性<10>.
* 核心与内置函数: 核心与内置函数<18>.
* 库: 库<20>.
* 文档: 文档<15>.
* 测试: 测试<15>.
* 构建: 构建<14>.
* Windows: Windows<15>.
* macOS: macOS<14>.
* IDLE: IDLE<14>.
* 工具/示例: 工具/示例<5>.
* C API: C API<11>.


File: python.info,  Node: 安全性<10>,  Next: 核心与内置函数<18>,  Up: Python 3 9 0 alpha 6

1.19.21.1 安全性
................

   - bpo-40121(1): Fixes audit events raised on creating a new socket.

   - bpo-39073(2): Disallow CR or LF in email.headerregistry.Address
     arguments to guard against header injection attacks.

   - bpo-39503(3): CVE-2020-8492: The *note AbstractBasicAuthHandler:
     fa2. class of the *note urllib.request: 129. 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40121

   (2) https://bugs.python.org/issue39073

   (3) https://bugs.python.org/issue39503


File: python.info,  Node: 核心与内置函数<18>,  Next: 库<20>,  Prev: 安全性<10>,  Up: Python 3 9 0 alpha 6

1.19.21.2 核心与内置函数
........................

   - bpo-40313(1): Improve the performance of bytes.hex().

   - bpo-40334(2): Switch to a new parser, based on PEG. For more
     details see PEP 617.  To temporarily switch back to the old parser,
     use ‘-X oldparser’ or ‘PYTHONOLDPARSER=1’.  In Python 3.10 we will
     remove the old parser completely, including the ‘parser’ module
     (already deprecated) and anything that depends on it.

   - bpo-40267(3): 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 ‘unexpected EOF while
     parsing’, while it should be ‘invalid syntax’.

   - bpo-39522(4): Correctly unparse explicit ‘u’ prefix for strings
     when postponed evaluation for annotations activated.  Patch by
     Batuhan Taskaya.

   - bpo-40246(5): Report a specialized error message, ‘invalid string
     prefix’, when the tokenizer encounters a string with an invalid
     prefix.

   - bpo-40082(6): Fix the signal handler: it now always uses the main
     interpreter, rather than trying to get the current Python thread
     state.

   - bpo-37388(7): 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().

   - bpo-40077(8): Fix possible refleaks in ‘_json’, memo of
     PyScannerObject should be traversed.

   - bpo-37207(9): Speed up calls to ‘dict()’ by using the PEP 590(10)
     ‘vectorcall’ calling convention.

   - bpo-40141(11): Add column and line information to ‘ast.keyword’
     nodes.  Patch by Pablo Galindo.

   - bpo-1635741(12): Port *note resource: e0. to multiphase
     initialization ( PEP 489(13)).

   - bpo-1635741(14): Port *note math: b1. to multiphase initialization
     ( PEP 489(15)).

   - bpo-1635741(16): Port _uuid module to multiphase initialization (
     PEP 489(17)).

   - bpo-40077(18): Convert json module to use *note PyType_FromSpec():
     23a.

   - bpo-40067(19): Improve the error message for multiple star
     expressions in an assignment.  Patch by Furkan Onder

   - bpo-1635741(20): Port _functools module to multiphase
     initialization (PEP 489).  Patch by Paulo Henrique Silva.

   - bpo-1635741(21): Port operator module to multiphase initialization
     (PEP 489).  Patch by Paulo Henrique Silva.

   - bpo-20526(22): Fix *note PyThreadState_Clear(): 104c.
     ‘PyThreadState.frame’ is a borrowed reference, not a strong
     reference: ‘PyThreadState_Clear()’ must not call
     ‘Py_CLEAR(tstate->frame)’.

   - bpo-1635741(23): Port time module to multiphase initialization (
     PEP 489(24)).  Patch by Paulo Henrique Silva.

   - bpo-1635741(25): Port _weakref extension module to multiphase
     initialization ( PEP 489(26)).

   - bpo-40020(27): Fix a leak and subsequent crash in parsetok.c caused
     by realloc misuse on a rare codepath.

   - bpo-39939(28): Added str.removeprefix and str.removesuffix methods
     and corresponding bytes, bytearray, and collections.UserString
     methods to remove affixes from a string if present.  See PEP
     616(29) for a full description.  Patch by Dennis Sweeney.

   - bpo-39481(30): Implement PEP 585.  This supports list[int],
     tuple[str, ...]  etc.

   - bpo-32894(31): Support unparsing of infinity numbers in postponed
     annotations.  Patch by Batuhan Taşkaya.

   - bpo-37207(32): Speed up calls to ‘list()’ by using the PEP 590(33)
     ‘vectorcall’ calling convention.  Patch by Mark Shannon.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40313

   (2) https://bugs.python.org/issue40334

   (3) https://bugs.python.org/issue40267

   (4) https://bugs.python.org/issue39522

   (5) https://bugs.python.org/issue40246

   (6) https://bugs.python.org/issue40082

   (7) https://bugs.python.org/issue37388

   (8) https://bugs.python.org/issue40077

   (9) https://bugs.python.org/issue37207

   (10) https://www.python.org/dev/peps/pep-0590

   (11) https://bugs.python.org/issue40141

   (12) https://bugs.python.org/issue1635741

   (13) https://www.python.org/dev/peps/pep-0489

   (14) https://bugs.python.org/issue1635741

   (15) https://www.python.org/dev/peps/pep-0489

   (16) https://bugs.python.org/issue1635741

   (17) https://www.python.org/dev/peps/pep-0489

   (18) https://bugs.python.org/issue40077

   (19) https://bugs.python.org/issue40067

   (20) https://bugs.python.org/issue1635741

   (21) https://bugs.python.org/issue1635741

   (22) https://bugs.python.org/issue20526

   (23) https://bugs.python.org/issue1635741

   (24) https://www.python.org/dev/peps/pep-0489

   (25) https://bugs.python.org/issue1635741

   (26) https://www.python.org/dev/peps/pep-0489

   (27) https://bugs.python.org/issue40020

   (28) https://bugs.python.org/issue39939

   (29) https://www.python.org/dev/peps/pep-0616

   (30) https://bugs.python.org/issue39481

   (31) https://bugs.python.org/issue32894

   (32) https://bugs.python.org/issue37207

   (33) https://www.python.org/dev/peps/pep-0590


File: python.info,  Node: 库<20>,  Next: 文档<15>,  Prev: 核心与内置函数<18>,  Up: Python 3 9 0 alpha 6

1.19.21.3 库
............

   - bpo-40398(1): *note typing.get_args(): 27d. now always returns an
     empty tuple for special generic aliases.

   - bpo-40396(2): Functions *note typing.get_origin(): 36e, *note
     typing.get_args(): 27d. and *note typing.get_type_hints(): 1ef.
     support now generic aliases like ‘list[int]’.

   - bpo-38061(3): Optimize the *note subprocess: f9. module on FreeBSD
     using ‘closefrom()’.  A single ‘close(fd)’ syscall is cheap, but
     when ‘sysconf(_SC_OPEN_MAX)’ is high, the loop calling ‘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):
     ‘https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=242274’

   - bpo-38061(4): On FreeBSD, ‘os.closerange(fd_low, fd_high)’ now
     calls ‘closefrom(fd_low)’ if `fd_high' is greater than or equal to
     ‘sysconf(_SC_OPEN_MAX)’.

     Initial patch by Ed Maste (emaste), Conrad Meyer (cem), Kyle Evans
     (kevans) and Kubilay Kocak (koobs):
     ‘https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=242274’

   - bpo-40360(5): The *note lib2to3: a7. module is pending deprecation
     due to PEP 617(6).

   - bpo-40138(7): Fix the Windows implementation of *note os.waitpid():
     760. for exit code larger than ‘INT_MAX >> 8’.  The exit status is
     now interpreted as an unsigned number.

   - bpo-39942(8): Set "__main__" as the default module name when
     "__name__" is missing in *note typing.TypeVar: 104e.  Patch by
     Weipeng Hong.

   - bpo-40275(9): The *note logging: aa. package is now imported lazily
     in *note unittest: 124. only when the *note assertLogs(): 9eb.
     assertion is used.

   - bpo-40275(10): The *note asyncio: 9. package is now imported lazily
     in *note unittest: 124. only when the *note
     IsolatedAsyncioTestCase: 377. class is used.

   - bpo-40330(11): In ‘ShareableList.__setitem__()’, check the size of
     a new string item after encoding it to utf-8, not before.

   - bpo-40148(12): Added ‘pathlib.Path.with_stem()’ to create a new
     Path with the stem replaced.

   - bpo-40325(13): Deprecated support for set objects in
     random.sample().

   - bpo-40257(14): Improved help for the *note typing: 122. module.
     Docstrings are now shown for all special forms and special generic
     aliases (like ‘Union’ and ‘List’).  Using ‘help()’ with generic
     alias like ‘List[int]’ will show the help for the correspondent
     concrete type (‘list’ in this case).

   - bpo-40257(15): func:*note inspect.getdoc: 307. 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 *note pydoc: d9. the documentation string is now shown not only
     for class, function, method etc, but for any object that has its
     own ‘__doc__’ attribute.

   - bpo-40287(16): Fixed ‘SpooledTemporaryFile.seek()’ to return the
     position.

   - bpo-40290(17): Added zscore() to statistics.NormalDist().

   - bpo-40282(18): Allow ‘random.getrandbits(0)’ to succeed and to
     return 0.

   - bpo-40286(19): Add *note random.randbytes(): 104f. function and
     ‘random.Random.randbytes()’ method to generate random bytes.

   - bpo-40277(20): *note collections.namedtuple(): 1a1. now provides a
     human-readable repr for its field accessors.

   - bpo-40270(21): The included copy of sqlite3 on Windows is now
     compiled with the json extension.  This allows the use of functions
     such as ‘json_object’.

   - bpo-29255(22): Wait in ‘KqueueSelector.select’ when no fds are
     registered

   - bpo-40260(23): Ensure *note modulefinder: b4. uses *note
     io.open_code(): 1050. and respects coding comments.

   - bpo-40234(24): Allow again to spawn daemon threads in
     subinterpreters (revert change which denied them).

   - bpo-39207(25): Workers in *note ProcessPoolExecutor: 196. 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.

   - bpo-40091(26): 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.

   - bpo-40149(27): Implement traverse and clear slots in _abc._abc_data
     type.

   - bpo-40208(28): Remove deprecated ‘symtable.SymbolTable.has_exec()’.

   - bpo-40196(29): Fix a bug in the *note symtable: fc. module that was
     causing incorrectly report global variables as local.  Patch by
     Pablo Galindo.

   - bpo-40190(30): Add support for ‘_SC_AIX_REALMEM’ to
     ‘posix.sysconf()’.

   - bpo-40182(31): Removed the ‘_field_types’ attribute of the *note
     typing.NamedTuple: 227. class.

   - bpo-36517(32): Multiple inheritance with *note typing.NamedTuple:
     227. now raises an error instead of silently ignoring other types.

   - bpo-40126(33): Fixed reverting multiple patches in unittest.mock.
     Patcher’s ‘__exit__()’ is now never called if its ‘__enter__()’ is
     failed.  Returning true from ‘__exit__()’ silences now the
     exception.

   - bpo-40094(34): 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."

   - bpo-40108(35): Improve the error message when triying to import a
     module using *note runpy: e2. and incorrently use the ".py"
     extension at the end of the module name.  Patch by Pablo Galindo.

   - bpo-40094(36): Add *note os.waitstatus_to_exitcode(): 1ce.
     function: convert a wait status to an exit code.

   - bpo-40089(37): 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.

   - bpo-40089(38): Add a private ‘_at_fork_reinit()’ method to
     ‘_thread.Lock’, ‘_thread.RLock’, *note threading.RLock: cba. and
     *note threading.Condition: b82. classes: reinitialize the lock at
     fork in the child process, reset the lock to the unlocked state.
     Rename also the private ‘_reset_internal_locks()’ method of *note
     threading.Event: b85. to ‘_at_fork_reinit()’.

   - bpo-25780(39): Expose *note CAN_RAW_JOIN_FILTERS: 1e2. in the *note
     socket: ef. module.

   - bpo-39503(40): *note AbstractBasicAuthHandler: fa2. of *note
     urllib.request: 129. now parses all WWW-Authenticate HTTP headers
     and accepts multiple challenges per header: use the realm of the
     first Basic challenge.

   - bpo-39812(41): Removed daemon threads from *note
     concurrent.futures: 21. by adding an internal
     ‘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.

   - bpo-40050(42): Fix ‘importlib._bootstrap_external’: avoid creating
     a new ‘winreg’ builtin module if it’s already available in *note
     sys.modules: 1051, and remove redundant imports.

   - bpo-40014(43): Fix ‘os.getgrouplist()’: if ‘getgrouplist()’
     function fails because the group list is too small, retry with a
     larger group list.  On failure, the glibc implementation of
     ‘getgrouplist()’ sets ‘ngroups’ to the total number of groups.  For
     other implementations, double the group list size.

   - bpo-40017(44): Add *note time.CLOCK_TAI: 1052. constant if the
     operating system support it.

   - bpo-40016(45): In re docstring, clarify the relationship between
     inline and argument compile flags.

   - bpo-39953(46): Update internal table of OpenSSL error codes in the
     ‘ssl’ module.

   - bpo-36144(47): Added PEP 584(48) operators to *note
     weakref.WeakValueDictionary: 1053.

   - bpo-36144(49): Added PEP 584(50) operators to *note
     weakref.WeakKeyDictionary: 1054.

   - bpo-38891(51): Fix linear runtime behaviour of the ‘__getitem__’
     and ‘__setitem__’ methods in *note
     multiprocessing.shared_memory.ShareableList: 1055.  This avoids
     quadratic performance when iterating a ‘ShareableList’.  Patch by
     Thomas Krennwallner.

   - bpo-39682(52): Remove undocumented support for `closing' a *note
     pathlib.Path: 32f. object via its context manager.  The context
     manager magic methods remain, but they are now a no-op, making
     ‘Path’ objects immutable.

   - bpo-36144(53): Added PEP 584(54) operators (‘|’ and ‘|=’) to *note
     collections.ChainMap: 5a3.

   - bpo-39011(55): Normalization of line endings in ElementTree
     attributes was removed, as line endings which were replaced by
     entity numbers should be preserved in original form.

   - bpo-38410(56): Properly handle *note sys.audit(): 1056. failures in
     *note sys.set_asyncgen_hooks(): 1057.

   - bpo-36541(57): lib2to3 now recognizes named assignment expressions
     (the walrus operator, ‘:=’)

   - bpo-35967(58): In platform, delay the invocation of ’uname -p’
     until the processor attribute is requested.

   - bpo-35113(59): *note inspect.getsource(): fda. 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.

   - bpo-33262(60): Deprecate passing None as an argument for *note
     shlex.split(): 210.’s ‘s’ parameter.  Patch by Zackery Spytz.

   - bpo-31758(61): Prevent crashes when using an uninitialized
     ‘_elementtree.XMLParser’ object.  Patch by Oren Milman.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40398

   (2) https://bugs.python.org/issue40396

   (3) https://bugs.python.org/issue38061

   (4) https://bugs.python.org/issue38061

   (5) https://bugs.python.org/issue40360

   (6) https://www.python.org/dev/peps/pep-0617

   (7) https://bugs.python.org/issue40138

   (8) https://bugs.python.org/issue39942

   (9) https://bugs.python.org/issue40275

   (10) https://bugs.python.org/issue40275

   (11) https://bugs.python.org/issue40330

   (12) https://bugs.python.org/issue40148

   (13) https://bugs.python.org/issue40325

   (14) https://bugs.python.org/issue40257

   (15) https://bugs.python.org/issue40257

   (16) https://bugs.python.org/issue40287

   (17) https://bugs.python.org/issue40290

   (18) https://bugs.python.org/issue40282

   (19) https://bugs.python.org/issue40286

   (20) https://bugs.python.org/issue40277

   (21) https://bugs.python.org/issue40270

   (22) https://bugs.python.org/issue29255

   (23) https://bugs.python.org/issue40260

   (24) https://bugs.python.org/issue40234

   (25) https://bugs.python.org/issue39207

   (26) https://bugs.python.org/issue40091

   (27) https://bugs.python.org/issue40149

   (28) https://bugs.python.org/issue40208

   (29) https://bugs.python.org/issue40196

   (30) https://bugs.python.org/issue40190

   (31) https://bugs.python.org/issue40182

   (32) https://bugs.python.org/issue36517

   (33) https://bugs.python.org/issue40126

   (34) https://bugs.python.org/issue40094

   (35) https://bugs.python.org/issue40108

   (36) https://bugs.python.org/issue40094

   (37) https://bugs.python.org/issue40089

   (38) https://bugs.python.org/issue40089

   (39) https://bugs.python.org/issue25780

   (40) https://bugs.python.org/issue39503

   (41) https://bugs.python.org/issue39812

   (42) https://bugs.python.org/issue40050

   (43) https://bugs.python.org/issue40014

   (44) https://bugs.python.org/issue40017

   (45) https://bugs.python.org/issue40016

   (46) https://bugs.python.org/issue39953

   (47) https://bugs.python.org/issue36144

   (48) https://www.python.org/dev/peps/pep-0584

   (49) https://bugs.python.org/issue36144

   (50) https://www.python.org/dev/peps/pep-0584

   (51) https://bugs.python.org/issue38891

   (52) https://bugs.python.org/issue39682

   (53) https://bugs.python.org/issue36144

   (54) https://www.python.org/dev/peps/pep-0584

   (55) https://bugs.python.org/issue39011

   (56) https://bugs.python.org/issue38410

   (57) https://bugs.python.org/issue36541

   (58) https://bugs.python.org/issue35967

   (59) https://bugs.python.org/issue35113

   (60) https://bugs.python.org/issue33262

   (61) https://bugs.python.org/issue31758


File: python.info,  Node: 文档<15>,  Next: 测试<15>,  Prev: 库<20>,  Up: Python 3 9 0 alpha 6

1.19.21.4 文档
..............

   - bpo-27635(1): The pickle documentation incorrectly claimed that
     ‘__new__’ isn’t called by default when unpickling.

   - bpo-39879(2): Updated *note 数据模型: 1059. docs to include *note
     dict(): 164. insertion order preservation.  Patch by Furkan Onder
     and Samy Lahfa.

   - bpo-38387(3): Document *note PyDoc_STRVAR: 105a. macro in the C-API
     reference.

   - bpo-13743(4): Some methods within xml.dom.minidom.Element class are
     now better documented.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27635

   (2) https://bugs.python.org/issue39879

   (3) https://bugs.python.org/issue38387

   (4) https://bugs.python.org/issue13743


File: python.info,  Node: 测试<15>,  Next: 构建<14>,  Prev: 文档<15>,  Up: Python 3 9 0 alpha 6

1.19.21.5 测试
..............

   - bpo-31904(1): Set expected default encoding in
     test_c_locale_coercion.py for VxWorks RTOS.

   - bpo-40162(2): Update Travis CI configuration to OpenSSL 1.1.1f.

   - bpo-40146(3): Update OpenSSL to 1.1.1f in Azure Pipelines.

   - bpo-40094(4): Add *note test.support.wait_process(): 105c.
     function.

   - bpo-40003(5): ‘test.bisect_cmd’ now copies Python command line
     options like ‘-O’ or ‘-W’.  Moreover, emit a warning if
     ‘test.bisect_cmd’ is used with ‘-w’/‘--verbose2’ option.

   - bpo-39380(6): Add the encoding in *note ftplib.FTP: 1a6. and *note
     ftplib.FTP_TLS: 1a7. to the constructor as keyword-only and change
     the default from ‘latin-1’ to ‘utf-8’ to follow RFC 2640(7).

   - bpo-39793(8): Use the same domain when testing ‘make_msgid’.  Patch
     by Batuhan Taskaya.

   - bpo-1812(9): Fix newline handling in doctest.testfile when loading
     from a package whose loader has a get_data method.  Patch by Peter
     Donis.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31904

   (2) https://bugs.python.org/issue40162

   (3) https://bugs.python.org/issue40146

   (4) https://bugs.python.org/issue40094

   (5) https://bugs.python.org/issue40003

   (6) https://bugs.python.org/issue39380

   (7) https://tools.ietf.org/html/rfc2640.html

   (8) https://bugs.python.org/issue39793

   (9) https://bugs.python.org/issue1812


File: python.info,  Node: 构建<14>,  Next: Windows<15>,  Prev: 测试<15>,  Up: Python 3 9 0 alpha 6

1.19.21.6 构建
..............

   - bpo-38360(1): Support single-argument form of macOS -isysroot flag.

   - bpo-40158(2): Fix CPython MSBuild Properties in NuGet Package
     (build/native/python.props)

   - bpo-38527(3): Fix configure check on Solaris for "float word
     ordering": sometimes, the correct "grep" command was not being
     used.  Patch by Arnon Yaari.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38360

   (2) https://bugs.python.org/issue40158

   (3) https://bugs.python.org/issue38527


File: python.info,  Node: Windows<15>,  Next: macOS<14>,  Prev: 构建<14>,  Up: Python 3 9 0 alpha 6

1.19.21.7 Windows
.................

   - bpo-40164(1): Updates Windows to OpenSSL 1.1.1f

   - bpo-8901(2): Ignore the Windows registry when the ‘-E’ option is
     used.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40164

   (2) https://bugs.python.org/issue8901


File: python.info,  Node: macOS<14>,  Next: IDLE<14>,  Prev: Windows<15>,  Up: Python 3 9 0 alpha 6

1.19.21.8 macOS
...............

   - bpo-38329(1): 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.

   - bpo-40164(2): Update macOS installer builds to use OpenSSL 1.1.1g.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38329

   (2) https://bugs.python.org/issue40164


File: python.info,  Node: IDLE<14>,  Next: 工具/示例<5>,  Prev: macOS<14>,  Up: Python 3 9 0 alpha 6

1.19.21.9 IDLE
..............

   - bpo-38439(1): Add a 256×256 pixel IDLE icon to support more modern
     environments.  Created by Andrew Clover.  Delete the unused macOS
     idle.icns icon file.

   - bpo-38689(2): IDLE will no longer freeze when inspect.signature
     fails when fetching a calltip.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38439

   (2) https://bugs.python.org/issue38689


File: python.info,  Node: 工具/示例<5>,  Next: C API<11>,  Prev: IDLE<14>,  Up: Python 3 9 0 alpha 6

1.19.21.10 工具/示例
....................

   - bpo-40385(1): Removed the checkpyc.py tool.  Please see compileall
     without force mode as a potential alternative.

   - bpo-40179(2): Fixed translation of ‘#elif’ in Argument Clinic.

   - bpo-40094(3): Fix ‘which.py’ script exit code: it now uses *note
     os.waitstatus_to_exitcode(): 1ce. to convert *note os.system():
     e86. exit status into an exit code.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40385

   (2) https://bugs.python.org/issue40179

   (3) https://bugs.python.org/issue40094


File: python.info,  Node: C API<11>,  Prev: 工具/示例<5>,  Up: Python 3 9 0 alpha 6

1.19.21.11 C API
................

   - bpo-40241(1): Move the ‘PyGC_Head’ structure to the internal C API.

   - bpo-40170(2): Convert *note PyObject_IS_GC(): 267. macro to a
     function to hide implementation details.

   - bpo-40241(3): Add the functions *note PyObject_GC_IsTracked(): 254.
     and *note PyObject_GC_IsFinalized(): 255. 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.

   - bpo-40170(4): The ‘PyObject_NEW()’ macro becomes an alias to the
     *note PyObject_New(): 268. macro, and the ‘PyObject_NEW_VAR()’
     macro becomes an alias to the *note PyObject_NewVar(): 269. macro,
     to hide implementation details.  They no longer access directly the
     *note PyTypeObject.tp_basicsize: 26a. member.

   - bpo-40170(5): *note PyType_HasFeature(): 1010. now always calls
     *note PyType_GetFlags(): 1012. to hide implementation details.
     Previously, it accessed directly the *note PyTypeObject.tp_flags:
     1011. member when the limited C API was not used.

   - bpo-40170(6): Convert the ‘PyObject_GET_WEAKREFS_LISTPTR()’ macro
     to a function to hide implementation details: the macro accessed
     directly to the *note PyTypeObject.tp_weaklistoffset: 26b. member.

   - bpo-40170(7): Convert *note PyObject_CheckBuffer(): 26c. macro to a
     function to hide implementation details: the macro accessed
     directly the *note PyTypeObject.tp_as_buffer: 26d. member.

   - bpo-40170(8): Always declare *note PyIndex_Check(): 26e. as an
     opaque function to hide implementation details: remove
     ‘PyIndex_Check()’ macro.  The macro accessed directly the *note
     PyTypeObject.tp_as_number: 26f. member.

   - bpo-39947(9): Add *note PyThreadState_GetID(): 24f. function: get
     the unique identifier of a Python thread state.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40241

   (2) https://bugs.python.org/issue40170

   (3) https://bugs.python.org/issue40241

   (4) https://bugs.python.org/issue40170

   (5) https://bugs.python.org/issue40170

   (6) https://bugs.python.org/issue40170

   (7) https://bugs.python.org/issue40170

   (8) https://bugs.python.org/issue40170

   (9) https://bugs.python.org/issue39947


File: python.info,  Node: Python 3 9 0 alpha 5,  Next: Python 3 9 0 alpha 4,  Prev: Python 3 9 0 alpha 6,  Up: Changelog（更動日誌）

1.19.22 Python 3.9.0 alpha 5
----------------------------

`发布日期: 2020-03-23'

* Menu:

* 安全性: 安全性<11>.
* 核心与内置函数: 核心与内置函数<19>.
* 库: 库<21>.
* 文档: 文档<16>.
* 测试: 测试<16>.
* 构建: 构建<15>.
* Windows: Windows<16>.
* macOS: macOS<15>.
* IDLE: IDLE<15>.
* 工具/示例: 工具/示例<6>.
* C API: C API<12>.


File: python.info,  Node: 安全性<11>,  Next: 核心与内置函数<19>,  Up: Python 3 9 0 alpha 5

1.19.22.1 安全性
................

   - bpo-38576(1): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38576


File: python.info,  Node: 核心与内置函数<19>,  Next: 库<21>,  Prev: 安全性<11>,  Up: Python 3 9 0 alpha 5

1.19.22.2 核心与内置函数
........................

   - bpo-40010(1): Optimize pending calls in multithreaded applications.
     If a thread different than the main thread schedules a pending call
     (*note Py_AddPendingCall(): 25f.), 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.

   - bpo-1635741(2): Port _weakref extension module to multiphase
     initialization ( PEP 489(3)).

   - bpo-1635741(4): Port _collections module to multiphase
     initialization ( PEP 489(5)).

   - bpo-40010(6): 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.

   - bpo-39984(7): If *note Py_AddPendingCall(): 25f. 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.

   - bpo-1635741(8): Port _heapq module to multiphase initialization.

   - bpo-1635741(9): Port itertools module to multiphase initialization
     ( PEP 489(10)).

   - bpo-37207(11): Speed up calls to ‘frozenset()’ by using the PEP
     590(12) ‘vectorcall’ calling convention.  Patch by Dong-hee Na.

   - bpo-39984(13): subinterpreters: Move
     ‘_PyRuntimeState.ceval.tracing_possible’ to
     ‘PyInterpreterState.ceval.tracing_possible’: each interpreter now
     has its own variable.

   - bpo-37207(14): Speed up calls to ‘set()’ by using the PEP 590(15)
     ‘vectorcall’ calling convention.  Patch by Dong-hee Na.

   - bpo-1635741(16): Port _statistics module to multiphase
     initialization ( PEP 489(17)).

   - bpo-39968(18): Use inline function to replace extension modules’
     get_module_state macros.

   - bpo-39965(19): Correctly raise ‘SyntaxError’ if `await' is used
     inside non-async functions and ‘PyCF_ALLOW_TOP_LEVEL_AWAIT’ is set
     (like in the asyncio REPL). Patch by Pablo Galindo.

   - bpo-39562(20): Allow executing asynchronous comprehensions on the
     top level when the ‘PyCF_ALLOW_TOP_LEVEL_AWAIT’ flag is given.
     Patch by Batuhan Taskaya.

   - bpo-37207(21): Speed up calls to ‘tuple()’ by using the PEP 590(22)
     ‘vectorcall’ calling convention.  Patch by Dong-hee Na.

   - bpo-38373(23): 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.

   - bpo-39926(24): Update Unicode database to Unicode version 13.0.0.

   - bpo-19466(25): 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.

   - bpo-38894(26): Fix a bug that was causing incomplete results when
     calling ‘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.

   - bpo-39877(27): Fix *note PyEval_RestoreThread(): 3d6. random crash
     at exit with daemon threads.  It now accesses the ‘_PyRuntime’
     variable directly instead of using ‘tstate->interp->runtime’, since
     ‘tstate’ can be a dangling pointer after *note Py_Finalize(): db3.
     has been called.  Moreover, the daemon thread now exits before
     trying to take the GIL.

   - bpo-39871(28): Fix a possible *note SystemError: 6f2. in
     ‘math.{atan2,copysign,remainder}()’ when the first argument cannot
     be converted to a *note float: 1fd.  Patch by Zackery Spytz.

   - bpo-39776(29): 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).

   - bpo-39778(30): Fixed a crash due to incorrect handling of weak
     references in ‘collections.OrderedDict’ classes.  Patch by Pablo
     Galindo.

   - bpo-1635741(31): Port audioop extension module to multiphase
     initialization ( PEP 489(32)).

   - bpo-39702(33): Relax *note decorator: 174. grammar restrictions to
     allow any valid expression ( PEP 614(34)).

   - bpo-38091(35): Tweak import deadlock detection code to not deadlock
     itself.

   - bpo-1635741(36): Port _locale extension module to multiphase
     initialization ( PEP 489(37)).

   - bpo-39087(38): Optimize *note PyUnicode_AsUTF8(): 52e. and *note
     PyUnicode_AsUTF8AndSize(): 52d. slightly when they need to create
     internal UTF-8 cache.

   - bpo-39520(39): Fix unparsing of ext slices with no items
     (‘foo[:,]’).  Patch by Batuhan Taskaya.

   - bpo-39220(40): Do not optimize annotations if ’from __future__
     import annotations’ is used.  Patch by Pablo Galindo.

   - bpo-35712(41): Using *note NotImplemented: 202. in a boolean
     context has been deprecated.  Patch contributed by Josh Rosenberg.

   - bpo-22490(42): Don’t leak environment variable
     ‘__PYVENV_LAUNCHER__’ into the interpreter session on macOS.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40010

   (2) https://bugs.python.org/issue1635741

   (3) https://www.python.org/dev/peps/pep-0489

   (4) https://bugs.python.org/issue1635741

   (5) https://www.python.org/dev/peps/pep-0489

   (6) https://bugs.python.org/issue40010

   (7) https://bugs.python.org/issue39984

   (8) https://bugs.python.org/issue1635741

   (9) https://bugs.python.org/issue1635741

   (10) https://www.python.org/dev/peps/pep-0489

   (11) https://bugs.python.org/issue37207

   (12) https://www.python.org/dev/peps/pep-0590

   (13) https://bugs.python.org/issue39984

   (14) https://bugs.python.org/issue37207

   (15) https://www.python.org/dev/peps/pep-0590

   (16) https://bugs.python.org/issue1635741

   (17) https://www.python.org/dev/peps/pep-0489

   (18) https://bugs.python.org/issue39968

   (19) https://bugs.python.org/issue39965

   (20) https://bugs.python.org/issue39562

   (21) https://bugs.python.org/issue37207

   (22) https://www.python.org/dev/peps/pep-0590

   (23) https://bugs.python.org/issue38373

   (24) https://bugs.python.org/issue39926

   (25) https://bugs.python.org/issue19466

   (26) https://bugs.python.org/issue38894

   (27) https://bugs.python.org/issue39877

   (28) https://bugs.python.org/issue39871

   (29) https://bugs.python.org/issue39776

   (30) https://bugs.python.org/issue39778

   (31) https://bugs.python.org/issue1635741

   (32) https://www.python.org/dev/peps/pep-0489

   (33) https://bugs.python.org/issue39702

   (34) https://www.python.org/dev/peps/pep-0614

   (35) https://bugs.python.org/issue38091

   (36) https://bugs.python.org/issue1635741

   (37) https://www.python.org/dev/peps/pep-0489

   (38) https://bugs.python.org/issue39087

   (39) https://bugs.python.org/issue39520

   (40) https://bugs.python.org/issue39220

   (41) https://bugs.python.org/issue35712

   (42) https://bugs.python.org/issue22490


File: python.info,  Node: 库<21>,  Next: 文档<16>,  Prev: 核心与内置函数<19>,  Up: Python 3 9 0 alpha 5

1.19.22.3 库
............

   - bpo-39830(1): Add *note zipfile.Path: 1067. to ‘__all__’ in the
     *note zipfile: 14b. module.

   - bpo-40000(2): Improved error messages for validation of
     ‘ast.Constant’ nodes.  Patch by Batuhan Taskaya.

   - bpo-39999(3): ‘__module__’ of the AST node classes is now set to
     "ast" instead of "_ast".  Added docstrings for dummy AST node
     classes and deprecated attributes.

   - bpo-39991(4): *note uuid.getnode(): 516. now skips IPv6 addresses
     with the same string length than a MAC address (17 characters):
     only use MAC addresses.

   - bpo-39988(5): Deprecated ‘ast.AugLoad’ and ‘ast.AugStore’ node
     classes because they are no longer used.

   - bpo-39656(6): Ensure ‘bin/python3.#’ is always present in virtual
     environments on POSIX platforms - by Anthony Sottile.

   - bpo-39969(7): Deprecated ‘ast.Param’ node class because it’s no
     longer used.  Patch by Batuhan Taskaya.

   - bpo-39360(8): Ensure all workers exit when finalizing a
     ‘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 ‘multiprocessing.Pool.terminate’.
     Patch by Batuhan Taskaya and Pablo Galindo.

   - bpo-35370(9): sys.settrace(), sys.setprofile() and
     _lsprof.Profiler.enable() now properly report *note PySys_Audit():
     1068. error if "sys.setprofile" or "sys.settrace" audit event is
     denied.

   - bpo-39936(10): 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.

   - bpo-36144(11): *note collections.OrderedDict: 2ea. now implements
     ‘|’ and ‘|=’ ( PEP 584(12)).

   - bpo-39652(13): The column name found in
     ‘sqlite3.Cursor.description’ is now truncated on the first ’[’ only
     if the PARSE_COLNAMES option is set.

   - bpo-39915(14): Ensure *note
     unittest.mock.AsyncMock.await_args_list: 1069. has call objects in
     the order of awaited arguments instead of using *note
     unittest.mock.Mock.call_args: 106a. which has the last value of the
     call.  Patch by Karthikeyan Singaravelan.

   - bpo-36144(15): Updated *note os.environ: c09. and *note
     os.environb: c65. to support PEP 584(16)’s merge (‘|’) and update
     (‘|=’) operators.

   - bpo-38662(17): The ‘ensurepip’ module now invokes ‘pip’ via the
     ‘runpy’ module.  Hence it is no longer tightly coupled with the
     internal API of the bundled ‘pip’ version, allowing easier updates
     to a newer ‘pip’ version both internally and for distributors.

   - bpo-38075(18): Fix the ‘random.Random.seed()’ method when a *note
     bool: 2bd. is passed as the seed.

   - bpo-39916(19): More reliable use of ‘os.scandir()’ in
     ‘Path.glob()’.  It no longer emits a ResourceWarning when
     interrupted.

   - bpo-39850(20): *note multiprocessing: b7. now supports abstract
     socket addresses (if abstract sockets are supported in the running
     platform).  When creating arbitrary addresses (like when
     default-constructing *note multiprocessing.connection.Listener:
     106b. 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.

   - bpo-36287(21): *note ast.dump(): 185. 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.  ‘Constant.kind’ is set to ‘None’).

   - bpo-39889(22): Fixed *note ast.unparse(): 186. for extended slices
     containing a single element (e.g.  ‘a[i:j,]’).  Remove redundant
     tuples when index with a tuple (e.g.  ‘a[i, j]’).

   - bpo-39828(23): Fix *note json.tool: a5. to catch *note
     BrokenPipeError: a7e.  Patch by Dong-hee Na.

   - bpo-13487(24): Avoid a possible `"RuntimeError: dictionary changed
     size during iteration"' from *note inspect.getmodule(): f6b. when
     it tried to loop through *note sys.modules: 1051.

   - bpo-39674(25): Revert "bpo-37330(26): 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.

   - bpo-28577(27): 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.

   - bpo-39826(28): Add getConnection method to logging HTTPHandler to
     enable custom connections.

   - bpo-39763(29): Reimplement ‘distutils.spawn.spawn()’ function with
     the *note subprocess: f9. module.

   - bpo-39794(30): Add –without-decimal-contextvar build option.  This
     enables a thread-local rather than a coroutine local context.

   - bpo-36144(31): *note collections.defaultdict: c0c. now implements
     ‘|’ ( PEP 584(32)).

   - bpo-39517(33): Fix runpy.run_path() when using pathlike objects

   - bpo-39775(34): Change ‘inspect.Signature.parameters’ back to
     ‘collections.OrderedDict’.  This was changed to ‘dict’ in Python
     3.9.0a4.

   - bpo-39678(35): Refactor queue_manager in *note
     concurrent.futures.ProcessPoolExecutor: 196. to make it easier to
     maintain.

   - bpo-39764(36): Fix AttributeError when calling get_stack on a
     PyAsyncGenObject Task

   - bpo-39769(37): The *note compileall.compile_dir(): 47a. function’s
     `ddir' parameter and the compileall command line flag ‘-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.

   - bpo-36144(38): *note types.MappingProxyType: b8e. objects now
     support the merge (‘|’) operator from PEP 584(39).

   - bpo-38691(40): The *note importlib: 9a. module now ignores the
     *note PYTHONCASEOK: 232. environment variable when the *note -E:
     230. or *note -I: 231. command line options are being used.

   - bpo-39719(41): Remove ‘tempfile.SpooledTemporaryFile.softspace()’
     as files no longer have the ‘softspace’ attribute in Python 3.
     Patch by Shantanu.

   - bpo-39667(42): Improve pathlib.Path compatibility on zipfile.Path
     and correct performance degradation as found in zipp 3.0.

   - bpo-39638(43): Keep ASDL signatures in the docstrings for ‘AST’
     nodes.  Patch by Batuhan Taskaya

   - bpo-39639(44): Deprecated ‘ast.Suite’ node class because it’s no
     longer used.  Patch by Batuhan Taskaya.

   - bpo-39609(45): Add thread_name_prefix to default asyncio executor

   - bpo-39548(46): Fix handling of header in *note
     urllib.request.AbstractDigestAuthHandler: 106c. when the optional
     ‘qop’ parameter is not present.

   - bpo-39509(47): HTTP status codes ‘103 EARLY_HINTS’ and ‘425
     TOO_EARLY’ are added to *note http.HTTPStatus: 1ac.  Patch by
     Dong-hee Na.

   - bpo-39507(48): Adding HTTP status 418 "I’m a Teapot" to HTTPStatus
     in http library.  Patch by Ross Rhodes.

   - bpo-39495(49): Remove default value from `attrs' parameter of *note
     xml.etree.ElementTree.TreeBuilder.start(): 106d. for consistency
     between Python and C implementations.

   - bpo-38971(50): 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.

   - bpo-38641(51): Added starred expressions support to ‘return’ and
     ‘yield’ statements for ‘lib2to3’.  Patch by Vlad Emelianov.

   - bpo-37534(52): 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:
     ‘https://www.w3.org/TR/xml/#sec-prolog-dtd’).

   - bpo-34788(53): Add support for scoped IPv6 addresses to *note
     ipaddress: a2.  Patch by Oleksandr Pavliuk.

   - bpo-34822(54): Simplified AST for subscription.  Simple indices are
     now represented by their value, extended slices are represented as
     tuples.  *note ast: 7. classes ‘Index’ and ‘ExtSlice’ are
     considered deprecated and will be removed in future Python
     versions.  In the meantime, ‘Index(value)’ now returns a ‘value’
     itself, ‘ExtSlice(slices)’ returns ‘Tuple(slices, Load())’.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39830

   (2) https://bugs.python.org/issue40000

   (3) https://bugs.python.org/issue39999

   (4) https://bugs.python.org/issue39991

   (5) https://bugs.python.org/issue39988

   (6) https://bugs.python.org/issue39656

   (7) https://bugs.python.org/issue39969

   (8) https://bugs.python.org/issue39360

   (9) https://bugs.python.org/issue35370

   (10) https://bugs.python.org/issue39936

   (11) https://bugs.python.org/issue36144

   (12) https://www.python.org/dev/peps/pep-0584

   (13) https://bugs.python.org/issue39652

   (14) https://bugs.python.org/issue39915

   (15) https://bugs.python.org/issue36144

   (16) https://www.python.org/dev/peps/pep-0584

   (17) https://bugs.python.org/issue38662

   (18) https://bugs.python.org/issue38075

   (19) https://bugs.python.org/issue39916

   (20) https://bugs.python.org/issue39850

   (21) https://bugs.python.org/issue36287

   (22) https://bugs.python.org/issue39889

   (23) https://bugs.python.org/issue39828

   (24) https://bugs.python.org/issue13487

   (25) https://bugs.python.org/issue39674

   (26) https://bugs.python.org/issue37330

   (27) https://bugs.python.org/issue28577

   (28) https://bugs.python.org/issue39826

   (29) https://bugs.python.org/issue39763

   (30) https://bugs.python.org/issue39794

   (31) https://bugs.python.org/issue36144

   (32) https://www.python.org/dev/peps/pep-0584

   (33) https://bugs.python.org/issue39517

   (34) https://bugs.python.org/issue39775

   (35) https://bugs.python.org/issue39678

   (36) https://bugs.python.org/issue39764

   (37) https://bugs.python.org/issue39769

   (38) https://bugs.python.org/issue36144

   (39) https://www.python.org/dev/peps/pep-0584

   (40) https://bugs.python.org/issue38691

   (41) https://bugs.python.org/issue39719

   (42) https://bugs.python.org/issue39667

   (43) https://bugs.python.org/issue39638

   (44) https://bugs.python.org/issue39639

   (45) https://bugs.python.org/issue39609

   (46) https://bugs.python.org/issue39548

   (47) https://bugs.python.org/issue39509

   (48) https://bugs.python.org/issue39507

   (49) https://bugs.python.org/issue39495

   (50) https://bugs.python.org/issue38971

   (51) https://bugs.python.org/issue38641

   (52) https://bugs.python.org/issue37534

   (53) https://bugs.python.org/issue34788

   (54) https://bugs.python.org/issue34822


File: python.info,  Node: 文档<16>,  Next: 测试<16>,  Prev: 库<21>,  Up: Python 3 9 0 alpha 5

1.19.22.4 文档
..............

   - bpo-39868(1): Updated the Language Reference for PEP 572(2).

   - bpo-13790(3): Change ’string’ to ’specification’ in format doc.

   - bpo-17422(4): The language reference no longer restricts default
     class namespaces to dicts only.

   - bpo-39530(5): Fix misleading documentation about mixed-type numeric
     comparisons.

   - bpo-39718(6): Update *note token: 119. documentation to reflect
     additions in Python 3.8

   - bpo-39677(7): Changed operand name of `MAKE_FUNCTION' from `argc'
     to `flags' for module *note dis: 37.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39868

   (2) https://www.python.org/dev/peps/pep-0572

   (3) https://bugs.python.org/issue13790

   (4) https://bugs.python.org/issue17422

   (5) https://bugs.python.org/issue39530

   (6) https://bugs.python.org/issue39718

   (7) https://bugs.python.org/issue39677


File: python.info,  Node: 测试<16>,  Next: 构建<15>,  Prev: 文档<16>,  Up: Python 3 9 0 alpha 5

1.19.22.5 测试
..............

   - bpo-40019(1): test_gdb now skips tests if it detects that gdb
     failed to read debug information because the Python binary is
     optimized.

   - bpo-27807(2): ‘test_site.test_startup_imports()’ is now skipped if
     a path of *note sys.path: 261. contains a ‘.pth’ file.

   - bpo-26067(3): Do not fail test_shutil test_chown test when uid or
     gid of user cannot be resolved to a name.

   - bpo-39855(4): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40019

   (2) https://bugs.python.org/issue27807

   (3) https://bugs.python.org/issue26067

   (4) https://bugs.python.org/issue39855


File: python.info,  Node: 构建<15>,  Next: Windows<16>,  Prev: 测试<16>,  Up: Python 3 9 0 alpha 5

1.19.22.6 构建
..............

   - bpo-39761(1): Fix build with DTrace but without additional DFLAGS.

   - bpo-39763(2): setup.py now uses a basic implementation of the *note
     subprocess: f9. module if the *note subprocess: f9. module is not
     available: before required C extension modules are built.

   - bpo-1294959(3): Add ‘--with-platlibdir’ option to the configure
     script: name of the platform-specific library directory, stored in
     the new *note sys.platlibdir: 1e9. attribute.  It is used to build
     the path of platform-specific extension modules and the path of the
     standard library.  It is equal to ‘"lib"’ on most platforms.  On
     Fedora and SuSE, it is equal to ‘"lib64"’ on 64-bit platforms.
     Patch by Jan Matějek, Matěj Cepl, Charalampos Stratakis and Victor
     Stinner.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39761

   (2) https://bugs.python.org/issue39763

   (3) https://bugs.python.org/issue1294959


File: python.info,  Node: Windows<16>,  Next: macOS<15>,  Prev: 构建<15>,  Up: Python 3 9 0 alpha 5

1.19.22.7 Windows
.................

   - bpo-39930(1): Ensures the required ‘vcruntime140.dll’ is included
     in install packages.

   - bpo-39847(2): Avoid hang when computer is hibernated whilst waiting
     for a mutex (for lock-related objects from *note threading: 10b.)
     around 49-day uptime.

   - bpo-38597(3): *note distutils: 38. will no longer statically link
     ‘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.

   - bpo-38380(4): Update Windows builds to use SQLite 3.31.1

   - bpo-39789(5): Update Windows release build machines to Visual
     Studio 2019 (MSVC 14.2).

   - bpo-34803(6): Package for nuget.org now includes repository
     reference and bundled icon image.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39930

   (2) https://bugs.python.org/issue39847

   (3) https://bugs.python.org/issue38597

   (4) https://bugs.python.org/issue38380

   (5) https://bugs.python.org/issue39789

   (6) https://bugs.python.org/issue34803


File: python.info,  Node: macOS<15>,  Next: IDLE<15>,  Prev: Windows<16>,  Up: Python 3 9 0 alpha 5

1.19.22.8 macOS
...............

   - bpo-38380(1): Update macOS builds to use SQLite 3.31.1

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38380


File: python.info,  Node: IDLE<15>,  Next: 工具/示例<6>,  Prev: macOS<15>,  Up: Python 3 9 0 alpha 5

1.19.22.9 IDLE
..............

   - bpo-27115(1): For ’Go to Line’, use a Query box subclass with IDLE
     standard behavior and improved error checking.

   - bpo-39885(2): Since clicking to get an IDLE context menu moves the
     cursor, any text selection should be and now is cleared.

   - bpo-39852(3): Edit "Go to line" now clears any selection,
     preventing accidental deletion.  It also updates Ln and Col on the
     status bar.

   - bpo-39781(4): Selecting code context lines no longer causes a jump.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27115

   (2) https://bugs.python.org/issue39885

   (3) https://bugs.python.org/issue39852

   (4) https://bugs.python.org/issue39781


File: python.info,  Node: 工具/示例<6>,  Next: C API<12>,  Prev: IDLE<15>,  Up: Python 3 9 0 alpha 5

1.19.22.10 工具/示例
....................

   - bpo-36184(1): 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.

   - bpo-38080(2): Added support to fix ‘getproxies’ in the
     ‘lib2to3.fixes.fix_urllib’ module.  Patch by José Roberto Meza
     Cabrera.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36184

   (2) https://bugs.python.org/issue38080


File: python.info,  Node: C API<12>,  Prev: 工具/示例<6>,  Up: Python 3 9 0 alpha 5

1.19.22.11 C API
................

   - bpo-40024(1): Add *note PyModule_AddType(): 253. helper function:
     add a type to a module.  Patch by Dong-hee Na.

   - bpo-39946(2): Remove ‘_PyRuntime.getframe’ hook and remove
     ‘_PyThreadState_GetFrame’ macro which was an alias to
     ‘_PyRuntime.getframe’.  They were only exposed by the internal C
     API. Remove also ‘PyThreadFrameGetter’ type.

   - bpo-39947(3): Add *note PyThreadState_GetFrame(): 24e. function:
     get the current frame of a Python thread state.

   - bpo-37207(4): Add _PyArg_NoKwnames helper function.  Patch by
     Dong-hee Na.

   - bpo-39947(5): Add *note PyThreadState_GetInterpreter(): 24c.: get
     the interpreter of a Python thread state.

   - bpo-39947(6): Add *note PyInterpreterState_Get(): 24d. function to
     the limited C API.

   - bpo-35370(7): If *note PySys_Audit(): 1068. fails in *note
     PyEval_SetProfile(): efd. or *note PyEval_SetTrace(): efe, log the
     error as an unraisable exception.

   - bpo-39947(8): 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.

   - bpo-39947(9): 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.

   - bpo-39884(10): *note PyDescr_NewMethod(): 1076. and
     ‘PyCFunction_NewEx()’ now include the method name in the
     SystemError "bad call flags" error message to ease debug.

   - bpo-39877(11): Deprecated *note PyEval_InitThreads(): 20c. and
     *note PyEval_ThreadsInitialized(): 20d.  Calling *note
     PyEval_InitThreads(): 20c. now does nothing.

   - bpo-38249(12): *note Py_UNREACHABLE: 526. is now implemented with
     ‘__builtin_unreachable()’ and analogs in release mode.

   - bpo-38643(13): *note PyNumber_ToBase(): 1077. now raises a *note
     SystemError: 6f2. instead of crashing when called with invalid
     base.

   - bpo-39882(14): The *note Py_FatalError(): 266. function is replaced
     with a macro which logs automatically the name of the current
     function, unless the ‘Py_LIMITED_API’ macro is defined.

   - bpo-39824(15): Extension modules: *note m_traverse: 259, *note
     m_clear: 25a. and *note m_free: 25b. functions of *note
     PyModuleDef: 258. 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
     (*note Py_mod_exec: 25c. function).  More precisely, these
     functions are not called if *note m_size: 25d. is greater than 0
     and the module state (as returned by *note PyModule_GetState():
     25e.) is ‘NULL’.

     没有模块状态的扩展模块 (‘m_size <= 0’) 不会受到影响。

   - bpo-38913(16): Fixed segfault in ‘Py_BuildValue()’ called with a
     format containing "#" and undefined PY_SSIZE_T_CLEAN whwn an
     exception is set.

   - bpo-38500(17): Add a private API to get and set the frame
     evaluation function: add *note
     _PyInterpreterState_GetEvalFrameFunc(): 1078. and *note
     _PyInterpreterState_SetEvalFrameFunc(): 1079. C functions.  The
     *note _PyFrameEvalFunction: 107a. function type now takes a
     `tstate' parameter.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40024

   (2) https://bugs.python.org/issue39946

   (3) https://bugs.python.org/issue39947

   (4) https://bugs.python.org/issue37207

   (5) https://bugs.python.org/issue39947

   (6) https://bugs.python.org/issue39947

   (7) https://bugs.python.org/issue35370

   (8) https://bugs.python.org/issue39947

   (9) https://bugs.python.org/issue39947

   (10) https://bugs.python.org/issue39884

   (11) https://bugs.python.org/issue39877

   (12) https://bugs.python.org/issue38249

   (13) https://bugs.python.org/issue38643

   (14) https://bugs.python.org/issue39882

   (15) https://bugs.python.org/issue39824

   (16) https://bugs.python.org/issue38913

   (17) https://bugs.python.org/issue38500


File: python.info,  Node: Python 3 9 0 alpha 4,  Next: Python 3 9 0 alpha 3,  Prev: Python 3 9 0 alpha 5,  Up: Changelog（更動日誌）

1.19.23 Python 3.9.0 alpha 4
----------------------------

`发布日期: 2020-02-25'

* Menu:

* 安全性: 安全性<12>.
* 核心与内置函数: 核心与内置函数<20>.
* 库: 库<22>.
* 文档: 文档<17>.
* 测试: 测试<17>.
* 构建: 构建<16>.
* Windows: Windows<17>.
* IDLE: IDLE<16>.
* C API: C API<13>.


File: python.info,  Node: 安全性<12>,  Next: 核心与内置函数<20>,  Up: Python 3 9 0 alpha 4

1.19.23.1 安全性
................

   - bpo-39184(1): Add audit events to functions in *note fcntl: 7c,
     *note msvcrt: b6, *note os: c4, *note resource: e0, *note shutil:
     e9, *note signal: ea. and *note syslog: ff.

   - bpo-39401(2): Avoid unsafe DLL load at startup on Windows 7 and
     earlier.

   - bpo-39184(3): Add audit events to command execution functions in os
     and pty modules.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39184

   (2) https://bugs.python.org/issue39401

   (3) https://bugs.python.org/issue39184


File: python.info,  Node: 核心与内置函数<20>,  Next: 库<22>,  Prev: 安全性<12>,  Up: Python 3 9 0 alpha 4

1.19.23.2 核心与内置函数
........................

   - bpo-39382(1): Fix a use-after-free in the single inheritance path
     of ‘issubclass()’, when the ‘__bases__’ of an object has a single
     reference, and so does its first item.  Patch by Yonatan
     Goldschmidt.

   - bpo-39573(2): Update clinic tool to use *note Py_IS_TYPE(): 107e.
     Patch by Dong-hee Na.

   - bpo-39619(3): Enable use of *note os.chroot(): 107f. on HP-UX
     systems.

   - bpo-39573(4): Add *note Py_IS_TYPE(): 107e. static inline function
     to check whether the object `o' type is `type'.

   - bpo-39606(5): Fix regression caused by fix for bpo-39386(6), that
     prevented calling ‘aclose’ on an async generator that had already
     been closed or exhausted.

   - bpo-39579(7): Change the ending column offset of ‘Attribute’ nodes
     constructed in ‘ast_for_dotted_name’ to point at the end of the
     current node and not at the end of the last ‘NAME’ node.

   - bpo-1635741(8): Port _crypt extension module to multiphase
     initialization ( PEP 489(9)).

   - bpo-1635741(10): Port _contextvars extension module to multiphase
     initialization ( PEP 489(11)).

   - bpo-39510(12): Fix segfault in ‘readinto()’ method on closed
     BufferedReader.

   - bpo-39502(13): Fix *note time.localtime(): 1080. on 64-bit AIX to
     support years before 1902 and after 2038.  Patch by M Felt.

   - bpo-39492(14): Fix a reference cycle in the C Pickler that was
     preventing the garbage collection of deleted, pickled objects.

   - bpo-39453(15): Fixed a possible crash in ‘list.__contains__()’ when
     a list is changed during comparing items.  Patch by Dong-hee Na.

   - bpo-39434(16): *note floor division: 1f9. of float operation now
     has a better performance.  Also the message of *note
     ZeroDivisionError: 1fa. for this operation is updated.  Patch by
     Dong-hee Na.

   - bpo-1635741(17): Port _codecs extension module to multiphase
     initialization ( PEP 489(18)).

   - bpo-1635741(19): Port _bz2 extension module to multiphase
     initialization ( PEP 489(20)).

   - bpo-1635741(21): Port _abc extension module to multiphase
     initialization ( PEP 489(22)).

   - bpo-39320(23): Replace two complex bytecodes for building dicts
     with two simpler ones.  The new bytecodes ‘DICT_MERGE’ and
     ‘DICT_UPDATE’ have been added The old bytecodes ‘BUILD_MAP_UNPACK’
     and ‘BUILD_MAP_UNPACK_WITH_CALL’ have been removed.

   - bpo-39219(24): Syntax errors raised in the tokenizer now always set
     correct "text" and "offset" attributes.

   - bpo-36051(25): Drop the GIL during large ‘bytes.join’ operations.
     Patch by Bruce Merry.

   - bpo-38960(26): Fix DTrace build issues on FreeBSD. Patch by David
     Carlier.

   - bpo-37207(27): Speed up calls to ‘range()’ by about 30%, by using
     the PEP 590 ‘vectorcall’ calling convention.  Patch by Mark
     Shannon.

   - bpo-36144(28): *note dict: 164. (and *note collections.UserDict:
     1081.) objects now support PEP 584’s merge (‘|’) and update (‘|=’)
     operators.  Patch by Brandt Bucher.

   - bpo-32856(29): Optimized the idiom for assignment a temporary
     variable in comprehensions.  Now ‘for y in [expr]’ in
     comprehensions is as fast as a simple assignment ‘y = expr’.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39382

   (2) https://bugs.python.org/issue39573

   (3) https://bugs.python.org/issue39619

   (4) https://bugs.python.org/issue39573

   (5) https://bugs.python.org/issue39606

   (6) https://bugs.python.org/issue39386

   (7) https://bugs.python.org/issue39579

   (8) https://bugs.python.org/issue1635741

   (9) https://www.python.org/dev/peps/pep-0489

   (10) https://bugs.python.org/issue1635741

   (11) https://www.python.org/dev/peps/pep-0489

   (12) https://bugs.python.org/issue39510

   (13) https://bugs.python.org/issue39502

   (14) https://bugs.python.org/issue39492

   (15) https://bugs.python.org/issue39453

   (16) https://bugs.python.org/issue39434

   (17) https://bugs.python.org/issue1635741

   (18) https://www.python.org/dev/peps/pep-0489

   (19) https://bugs.python.org/issue1635741

   (20) https://www.python.org/dev/peps/pep-0489

   (21) https://bugs.python.org/issue1635741

   (22) https://www.python.org/dev/peps/pep-0489

   (23) https://bugs.python.org/issue39320

   (24) https://bugs.python.org/issue39219

   (25) https://bugs.python.org/issue36051

   (26) https://bugs.python.org/issue38960

   (27) https://bugs.python.org/issue37207

   (28) https://bugs.python.org/issue36144

   (29) https://bugs.python.org/issue32856


File: python.info,  Node: 库<22>,  Next: 文档<17>,  Prev: 核心与内置函数<20>,  Up: Python 3 9 0 alpha 4

1.19.23.3 库
............

   - bpo-30566(1): Fix *note IndexError: f36. when trying to decode an
     invalid string with punycode codec.

   - bpo-39649(2): Remove obsolete check for ‘__args__’ in
     bdb.Bdb.format_stack_entry.

   - bpo-39648(3): Expanded *note math.gcd(): 1be. and *note math.lcm():
     1bf. to handle multiple arguments.

   - bpo-39681(4): Fix a regression where the C pickle module wouldn’t
     allow unpickling from a file-like object that doesn’t expose a
     readinto() method.

   - bpo-35950(5): Raise *note io.UnsupportedOperation: 1083. in
     ‘io.BufferedReader.truncate()’ when it is called on a read-only
     *note io.BufferedReader: c5b. instance.

   - bpo-39479(6): Add *note math.lcm(): 1bf. function: least common
     multiple.

   - bpo-39674(7): Revert "Do not expose abstract collection classes in
     the collections module" change (bpo-25988(8)).  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.

   - bpo-39104(9): Fix hanging ProcessPoolExcutor on
     ‘shutdown(wait=False)’ when a task has failed pickling.

   - bpo-39627(10): Fixed TypedDict totality check for inherited keys.

   - bpo-39474(11): Fixed starting position of AST for expressions like
     ‘(a)(b)’, ‘(a)[b]’ and ‘(a).b’.

   - bpo-21016(12): The *note pydoc: d9. and *note trace: 11b. modules
     now use the *note sysconfig: fe. module to get the path to the
     Python standard library, to support uncommon installation path like
     ‘/usr/lib64/python3.9/’ on Fedora.  Patch by Jan Matějek.

   - bpo-39590(13): Collections.deque now holds strong references during
     deque.__contains__ and deque.count, fixing crashes.

   - bpo-39586(14): The distutils ‘bdist_msi’ command is deprecated in
     Python 3.9, use ‘bdist_wheel’ (wheel packages) instead.

   - bpo-39595(15): 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(16).

   - bpo-39350(17): Fix regression in *note fractions.Fraction: 2be. if
     the numerator and/or the denominator is an *note int: 204.
     subclass.  The *note math.gcd(): 1be. function is now used to
     normalize the `numerator' and `denominator'.  *note math.gcd():
     1be. always return a *note int: 204. type.  Previously, the GCD
     type depended on `numerator' and `denominator'.

   - bpo-39567(18): Added audit for *note os.walk(): 747, *note
     os.fwalk(): 4ba, *note pathlib.Path.glob(): 1084. and *note
     pathlib.Path.rglob(): 1085.

   - bpo-39559(19): Remove unused, undocumented argument ‘getters’ from
     *note uuid.getnode(): 516.

   - bpo-38149(20): *note sys.audit(): 1056. is now called only once per
     call of *note glob.glob(): 6bd. and *note glob.iglob(): 6be.

   - bpo-39546(21): Fix a regression in *note ArgumentParser: 788. where
     ‘allow_abbrev=False’ was ignored for long options that used a
     prefix character other than "-".

   - bpo-39450(22): Striped whitespace from docstring before returning
     it from ‘unittest.case.shortDescription()’.

   - bpo-12915(23): A new function ‘resolve_name’ has been added to the
     ‘pkgutil’ module.  This resolves a string of the form ‘'a.b.c.d'’
     or ‘'a.b:c.d'’ to an object.  In the example, ‘a.b’ is a
     package/module and ‘c.d’ is an object within that package/module
     reached via recursive attribute access.

   - bpo-39353(24): The *note binascii.crc_hqx(): 1086. function is no
     longer deprecated.

   - bpo-39493(25): Mark ‘typing.IO.closed’ as a property

   - bpo-39491(26): Add *note typing.Annotated: 1ee. and
     ‘include_extras’ parameter to *note typing.get_type_hints(): 1ef.
     as part of PEP 593(27).  Patch by Till Varoquaux, documentation by
     Till Varoquaux and Konstantin Kashin.

   - bpo-39485(28): Fix a bug in *note unittest.mock.create_autospec():
     1087. that would complain about the wrong number of arguments for
     custom descriptors defined in an extension module returning
     functions.

   - bpo-38932(29): Mock fully resets child objects on reset_mock().
     Patch by Vegard Stikbakke

   - bpo-39082(30): Allow AsyncMock to correctly patch static/class
     methods

   - bpo-39432(31): Implement PEP-489 algorithm for non-ascii
     "PyInit_..."  symbol names in distutils to make it export the
     correct init symbol also on Windows.

   - bpo-18819(32): Omit ‘devmajor’ and ‘devminor’ fields for non-device
     files in *note tarfile: 101. archives, enabling bit-for-bit
     compatibility with GNU ‘tar(1)’.

   - bpo-39349(33): Added a new `cancel_futures' parameter to *note
     concurrent.futures.Executor.shutdown(): 195. that cancels all
     pending futures which have not started running, instead of waiting
     for them to complete before shutting down the executor.

   - bpo-39274(34): ‘bool(fraction.Fraction)’ now returns a boolean even
     if (numerator != 0) does not return a boolean (ex: numpy number).

   - bpo-34793(35): Remove support for ‘with (await asyncio.lock):’ and
     ‘with (yield from asyncio.lock):’.  The same is correct for
     ‘asyncio.Condition’ and ‘asyncio.Semaphore’.

   - bpo-25597(36): Ensure, if ‘wraps’ is supplied to *note
     unittest.mock.MagicMock: 874, it is used to calculate return values
     for the magic methods instead of using the default return values.
     Patch by Karthikeyan Singaravelan.

   - bpo-36350(37): *note inspect.Signature.parameters: 1088. and *note
     inspect.BoundArguments.arguments: 1b9. are now dicts instead of
     OrderedDicts.  Patch contributed by Rémi Lapeyre.

   - bpo-35727(38): Fix sys.exit() and sys.exit(None) exit code
     propagation when used in multiprocessing.Process.

   - bpo-32173(39): * Add ‘lazycache’ function to ‘__all__’.  * Use
     *note dict.clear: 1089. to clear the cache.  * Refactoring
     ‘getline’ function and ‘checkcache’ function.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30566

   (2) https://bugs.python.org/issue39649

   (3) https://bugs.python.org/issue39648

   (4) https://bugs.python.org/issue39681

   (5) https://bugs.python.org/issue35950

   (6) https://bugs.python.org/issue39479

   (7) https://bugs.python.org/issue39674

   (8) https://bugs.python.org/issue25988

   (9) https://bugs.python.org/issue39104

   (10) https://bugs.python.org/issue39627

   (11) https://bugs.python.org/issue39474

   (12) https://bugs.python.org/issue21016

   (13) https://bugs.python.org/issue39590

   (14) https://bugs.python.org/issue39586

   (15) https://bugs.python.org/issue39595

   (16) 
https://importlib-metadata.readthedocs.io/en/latest/changelog%20(links).html#v1-5-0

   (17) https://bugs.python.org/issue39350

   (18) https://bugs.python.org/issue39567

   (19) https://bugs.python.org/issue39559

   (20) https://bugs.python.org/issue38149

   (21) https://bugs.python.org/issue39546

   (22) https://bugs.python.org/issue39450

   (23) https://bugs.python.org/issue12915

   (24) https://bugs.python.org/issue39353

   (25) https://bugs.python.org/issue39493

   (26) https://bugs.python.org/issue39491

   (27) https://www.python.org/dev/peps/pep-0593

   (28) https://bugs.python.org/issue39485

   (29) https://bugs.python.org/issue38932

   (30) https://bugs.python.org/issue39082

   (31) https://bugs.python.org/issue39432

   (32) https://bugs.python.org/issue18819

   (33) https://bugs.python.org/issue39349

   (34) https://bugs.python.org/issue39274

   (35) https://bugs.python.org/issue34793

   (36) https://bugs.python.org/issue25597

   (37) https://bugs.python.org/issue36350

   (38) https://bugs.python.org/issue35727

   (39) https://bugs.python.org/issue32173


File: python.info,  Node: 文档<17>,  Next: 测试<17>,  Prev: 库<22>,  Up: Python 3 9 0 alpha 4

1.19.23.4 文档
..............

   - bpo-17422(1): The language reference now specifies restrictions on
     class namespaces.  Adapted from a patch by Ethan Furman.

   - bpo-39572(2): Updated documentation of ‘total’ flag of ‘TypedDict’.

   - bpo-39654(3): In pyclbr doc, update ’class’ to ’module’ where
     appropriate and add readmodule comment.  Patch by Hakan Çelik.

   - bpo-39153(4): Clarify refcounting semantics for the following
     functions: - PyObject_SetItem - PyMapping_SetItemString -
     PyDict_SetItem - PyDict_SetItemString

   - bpo-39392(5): Explain that when filling with turtle, overlap
     regions may be left unfilled.

   - bpo-39369(6): 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.

   - bpo-9056(7): Include subsection in TOC for PDF version of docs.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17422

   (2) https://bugs.python.org/issue39572

   (3) https://bugs.python.org/issue39654

   (4) https://bugs.python.org/issue39153

   (5) https://bugs.python.org/issue39392

   (6) https://bugs.python.org/issue39369

   (7) https://bugs.python.org/issue9056


File: python.info,  Node: 测试<17>,  Next: 构建<16>,  Prev: 文档<17>,  Up: Python 3 9 0 alpha 4

1.19.23.5 测试
..............

   - bpo-38325(1): Skip tests on non-BMP characters of
     test_winconsoleio.

   - bpo-39502(2): Skip test_zipfile.test_add_file_after_2107() if *note
     time.localtime(): 1080. fails with *note OverflowError: a41.  It is
     the case on AIX 6.1 for example.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38325

   (2) https://bugs.python.org/issue39502


File: python.info,  Node: 构建<16>,  Next: Windows<17>,  Prev: 测试<17>,  Up: Python 3 9 0 alpha 4

1.19.23.6 构建
..............

   - bpo-39489(1): Remove ‘COUNT_ALLOCS’ special build.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39489


File: python.info,  Node: Windows<17>,  Next: IDLE<16>,  Prev: 构建<16>,  Up: Python 3 9 0 alpha 4

1.19.23.7 Windows
.................

   - bpo-39553(1): Delete unused code related to SxS manifests.

   - bpo-39439(2): Honor the Python path when a virtualenv is active on
     Windows.

   - bpo-39393(3): Improve the error message when attempting to load a
     DLL with unresolved dependencies.

   - bpo-38883(4): *note home(): 81a. and *note expanduser(): 819. on
     Windows now prefer ‘USERPROFILE’ and no longer use ‘HOME’, which is
     not normally set for regular user accounts.  This makes them again
     behave like *note os.path.expanduser(): 32c, which was changed to
     ignore ‘HOME’ in 3.8, see bpo-36264(5).

   - bpo-39185(6): The build.bat script has additional options for
     very-quiet output (-q) and very-verbose output (-vv)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39553

   (2) https://bugs.python.org/issue39439

   (3) https://bugs.python.org/issue39393

   (4) https://bugs.python.org/issue38883

   (5) https://bugs.python.org/issue36264

   (6) https://bugs.python.org/issue39185


File: python.info,  Node: IDLE<16>,  Next: C API<13>,  Prev: Windows<17>,  Up: Python 3 9 0 alpha 4

1.19.23.8 IDLE
..............

   - bpo-39663(1): Add tests for pyparse find_good_parse_start().

   - bpo-39600(2): In the font configuration window, remove duplicated
     font names.

   - bpo-30780(3): Add remaining configdialog tests for buttons and
     highlights and keys tabs.

   - bpo-39388(4): IDLE Settings Cancel button now cancels pending
     changes

   - bpo-38792(5): Close an IDLE shell calltip if a *note
     KeyboardInterrupt: 2cc. or shell restart occurs.  Patch by Zackery
     Spytz.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39663

   (2) https://bugs.python.org/issue39600

   (3) https://bugs.python.org/issue30780

   (4) https://bugs.python.org/issue39388

   (5) https://bugs.python.org/issue38792


File: python.info,  Node: C API<13>,  Prev: IDLE<16>,  Up: Python 3 9 0 alpha 4

1.19.23.9 C API
...............

   - bpo-35081(1): Move the ‘bytes_methods.h’ header file to the
     internal C API as ‘pycore_bytes_methods.h’: it only contains
     private symbols (prefixed by ‘_Py’), except of the
     ‘PyDoc_STRVAR_shared()’ macro.

   - bpo-35081(2): Move the ‘dtoa.h’ header file to the internal C API
     as ‘pycore_dtoa.h’: it only contains private functions (prefixed by
     ‘_Py’).  The *note math: b1. and *note cmath: 18. modules must now
     be compiled with the ‘Py_BUILD_CORE’ macro defined.

   - bpo-39573(3): Add *note Py_SET_SIZE(): 1090. function to set the
     size of an object.

   - bpo-39500(4): *note PyUnicode_IsIdentifier(): 1091. does not call
     *note Py_FatalError(): 266. anymore if the string is not ready.

   - bpo-39573(5): Add *note Py_SET_TYPE(): 1092. function to set the
     type of an object.

   - bpo-39573(6): Add a *note Py_SET_REFCNT(): 1093. function to set
     the reference counter of an object.

   - bpo-39542(7): Convert *note PyType_HasFeature(): 1010, *note
     PyType_Check(): 1094. and *note PyType_CheckExact(): 1095. macros
     to static inline functions.

   - bpo-39542(8): In the limited C API, ‘PyObject_INIT()’ and
     ‘PyObject_INIT_VAR()’ are now defined as aliases to *note
     PyObject_Init(): 398. and *note PyObject_InitVar(): 1096. 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: ‘_Py_NewReference()’, ‘_Py_ForgetReference()’,
     ‘_PyTraceMalloc_NewReference()’ and ‘_Py_GetRefTotal()’.

   - bpo-39542(9): 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.

   - bpo-39511(10): The *note PyThreadState_Clear(): 104c. function now
     calls the ‘PyThreadState.on_delete’ callback.  Previously, that
     happened in *note PyThreadState_Delete(): 1097.

   - bpo-38076(11): Fix to clear the interpreter state only after
     clearing module globals to guarantee module state access from C
     Extensions during runtime destruction

   - bpo-39245(12): The Vectorcall API (PEP 590) was made public, adding
     the functions ‘PyObject_Vectorcall’, ‘PyObject_VectorcallMethod’,
     ‘PyVectorcall_Function’, ‘PyObject_CallOneArg’,
     ‘PyObject_CallMethodNoArgs’, ‘PyObject_CallMethodOneArg’,
     ‘PyObject_FastCallDict’, and the flag ‘Py_TPFLAGS_HAVE_VECTORCALL’.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35081

   (2) https://bugs.python.org/issue35081

   (3) https://bugs.python.org/issue39573

   (4) https://bugs.python.org/issue39500

   (5) https://bugs.python.org/issue39573

   (6) https://bugs.python.org/issue39573

   (7) https://bugs.python.org/issue39542

   (8) https://bugs.python.org/issue39542

   (9) https://bugs.python.org/issue39542

   (10) https://bugs.python.org/issue39511

   (11) https://bugs.python.org/issue38076

   (12) https://bugs.python.org/issue39245


File: python.info,  Node: Python 3 9 0 alpha 3,  Next: Python 3 9 0 alpha 2,  Prev: Python 3 9 0 alpha 4,  Up: Changelog（更動日誌）

1.19.24 Python 3.9.0 alpha 3
----------------------------

`发布日期: 2020-01-24'

* Menu:

* 核心与内置函数: 核心与内置函数<21>.
* 库: 库<23>.
* 文档: 文档<18>.
* 构建: 构建<17>.
* IDLE: IDLE<17>.
* C API: C API<14>.


File: python.info,  Node: 核心与内置函数<21>,  Next: 库<23>,  Up: Python 3 9 0 alpha 3

1.19.24.1 核心与内置函数
........................

   - bpo-39427(1): Document all possibilities for the ‘-X’ options in
     the command line help section.  Patch by Pablo Galindo.

   - bpo-39421(2): Fix possible crashes when operating with the
     functions in the *note heapq: 8d. module and custom comparison
     operators.

   - bpo-39386(3): Prevent double awaiting of async iterator.

   - bpo-17005(4): Add ‘functools.TopologicalSorter’ to the *note
     functools: 83. module to offers functionality to perform
     topological sorting of graphs.  Patch by Pablo Galindo, Tim Peters
     and Larry Hastings.

   - bpo-39320(5): Replace four complex bytecodes for building sequences
     with three simpler ones.

     The following four bytecodes have been removed:

        * BUILD_LIST_UNPACK

        * BUILD_TUPLE_UNPACK

        * BUILD_SET_UNPACK

        * BUILD_TUPLE_UNPACK_WITH_CALL

     The following three bytecodes have been added:

        * LIST_TO_TUPLE

        * LIST_EXTEND

        * SET_UPDATE

   - bpo-39336(6): Import loaders which publish immutable module objects
     can now publish immutable packages in addition to individual
     modules.

   - bpo-39322(7): Added a new function *note gc.is_finalized(): 1a9. to
     check if an object has been finalized by the garbage collector.
     Patch by Pablo Galindo.

   - bpo-39048(8): Improve the displayed error message when incorrect
     types are passed to ‘async with’ statements by looking up the *note
     __aenter__(): 109a. special method before the *note __aexit__():
     109b. special method when entering an asynchronous context manager.
     Patch by Géry Ogam.

   - bpo-39235(9): Fix AST end location for lone generator expression in
     function call, e.g.  f(i for i in a).

   - bpo-39209(10): Correctly handle multi-line tokens in interactive
     mode.  Patch by Pablo Galindo.

   - bpo-1635741(11): Port _json extension module to multiphase
     initialization ( PEP 489(12)).

   - bpo-39216(13): Fix constant folding optimization for positional
     only arguments - by Anthony Sottile.

   - bpo-39215(14): Fix ‘SystemError’ when nested function has
     annotation on positional-only argument - by Anthony Sottile.

   - bpo-39200(15): Correct the error message when calling the *note
     min(): 8f6. or *note max(): 8f7. with no arguments.  Patch by
     Dong-hee Na.

   - bpo-39200(16): Correct the error message when trying to construct
     *note range: 1f5. objects with no arguments.  Patch by Pablo
     Galindo.

   - bpo-39166(17): Fix incorrect line execution reporting in trace
     functions when tracing the last iteration of asynchronous for
     loops.  Patch by Pablo Galindo.

   - bpo-39114(18): Fix incorrect line execution reporting in trace
     functions when tracing exception handlers with name binding.  Patch
     by Pablo Galindo.

   - bpo-39156(19): Split the COMPARE_OP bytecode instruction into four
     distinct instructions.

        * COMPARE_OP for rich comparisons

        * IS_OP for ’is’ and ’is not’ tests

        * CONTAINS_OP for ’in’ and ’is not’ tests

        * JUMP_IF_NOT_EXC_MATCH for checking exceptions in ’try-except’
          statements.

     This improves the clarity of the interpreter and should provide a
     modest speedup.

   - bpo-38588(20): Fix possible crashes in dict and list when calling
     *note PyObject_RichCompareBool(): 109c.

   - bpo-13601(21): By default, ‘sys.stderr’ is line-buffered now, even
     if ‘stderr’ is redirected to a file.  You can still make
     ‘sys.stderr’ unbuffered by passing the *note -u: 109d. command-line
     option or setting the *note PYTHONUNBUFFERED: 109e. environment
     variable.

     (Contributed by Jendrik Seipp in bpo-13601(22).)

   - bpo-38610(23): Fix possible crashes in several list methods by
     holding strong references to list elements when calling *note
     PyObject_RichCompareBool(): 109c.

   - bpo-32021(24): Include brotli .br encoding in mimetypes
     encodings_map

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39427

   (2) https://bugs.python.org/issue39421

   (3) https://bugs.python.org/issue39386

   (4) https://bugs.python.org/issue17005

   (5) https://bugs.python.org/issue39320

   (6) https://bugs.python.org/issue39336

   (7) https://bugs.python.org/issue39322

   (8) https://bugs.python.org/issue39048

   (9) https://bugs.python.org/issue39235

   (10) https://bugs.python.org/issue39209

   (11) https://bugs.python.org/issue1635741

   (12) https://www.python.org/dev/peps/pep-0489

   (13) https://bugs.python.org/issue39216

   (14) https://bugs.python.org/issue39215

   (15) https://bugs.python.org/issue39200

   (16) https://bugs.python.org/issue39200

   (17) https://bugs.python.org/issue39166

   (18) https://bugs.python.org/issue39114

   (19) https://bugs.python.org/issue39156

   (20) https://bugs.python.org/issue38588

   (21) https://bugs.python.org/issue13601

   (22) https://bugs.python.org/issue13601

   (23) https://bugs.python.org/issue38610

   (24) https://bugs.python.org/issue32021


File: python.info,  Node: 库<23>,  Next: 文档<18>,  Prev: 核心与内置函数<21>,  Up: Python 3 9 0 alpha 3

1.19.24.2 库
............

   - bpo-39430(1): Fixed race condition in lazy imports in *note
     tarfile: 101.

   - bpo-39413(2): The *note os.unsetenv(): 1cc. function is now also
     available on Windows.

   - bpo-39390(3): Fixed a regression with the ‘ignore’ callback of
     *note shutil.copytree(): 347.  The argument types are now str and
     List[str] again.

   - bpo-39395(4): The *note os.putenv(): 1cd. and *note os.unsetenv():
     1cc. functions are now always available.

   - bpo-39406(5): If ‘setenv()’ C function is available, *note
     os.putenv(): 1cd. is now implemented with ‘setenv()’ instead of
     ‘putenv()’, so Python doesn’t have to handle the environment
     variable memory.

   - bpo-39396(6): Fix ‘math.nextafter(-0.0, +0.0)’ on AIX 7.1.

   - bpo-29435(7): Allow *note tarfile.is_tarfile(): 10a0. to be used
     with file and file-like objects, like *note zipfile.is_zipfile():
     d82.  Patch by William Woodruff.

   - bpo-39377(8): Removed ‘encoding’ option from *note json.loads():
     225.  It has been deprecated since Python 3.1.

   - bpo-39389(9): Write accurate compression level metadata in *note
     gzip: 8b. archives, rather than always signaling maximum
     compression.

   - bpo-39366(10): The previously deprecated ‘xpath()’ and ‘xgtitle()’
     methods of *note nntplib.NNTP: 1c6. have been removed.

   - bpo-39357(11): Remove the `buffering' parameter of *note
     bz2.BZ2File: 224.  Since Python 3.0, it was ignored and using it
     was emitting *note DeprecationWarning: 15a.  Pass an open file
     object, to control how the file is opened.  The `compresslevel'
     parameter becomes keyword-only.

   - bpo-39353(12): Deprecate binhex4 and hexbin4 standards.  Deprecate
     the *note binhex: 10. module and the following *note binascii: f.
     functions: *note b2a_hqx(): 208, *note a2b_hqx(): 209, *note
     rlecode_hqx(): 20a, *note rledecode_hqx(): 20b, *note crc_hqx():
     1086.

   - bpo-39351(13): Remove ‘base64.encodestring()’ and
     ‘base64.decodestring()’, aliases deprecated since Python 3.1: use
     *note base64.encodebytes(): 222. and *note base64.decodebytes():
     223. instead.

   - bpo-39350(14): Remove ‘fractions.gcd()’ function, deprecated since
     Python 3.5 (bpo-22486(15)): use *note math.gcd(): 1be. instead.

   - bpo-39329(16): *note LMTP: 1e0. constructor now has an optional
     `timeout' parameter.  Patch by Dong-hee Na.

   - bpo-39313(17): Add a new ‘exec_function’ option (`–exec-function'
     in the CLI) to ‘RefactoringTool’ for making ‘exec’ a function.
     Patch by Batuhan Taskaya.

   - bpo-39259(18): *note FTP_TLS: 1a7. and *note FTP_TLS: 1a7. now
     raise a *note ValueError: 16d. if the given timeout for their
     constructor is zero to prevent the creation of a non-blocking
     socket.  Patch by Dong-hee Na.

   - bpo-39259(19): *note SMTP: 1de. and *note SMTP_SSL: 1df. now raise
     a *note ValueError: 16d. if the given timeout for their constructor
     is zero to prevent the creation of a non-blocking socket.  Patch by
     Dong-hee Na.

   - bpo-39310(20): Add *note math.ulp(): 1c1.: return the value of the
     least significant bit of a float.

   - bpo-39297(21): Improved performance of importlib.metadata
     distribution discovery and resilients to inaccessible sys.path
     entries (importlib_metadata v1.4.0).

   - bpo-39259(22): *note NNTP: 1c6. and *note NNTP_SSL: 1c7. now raise
     a *note ValueError: 16d. if the given timeout for their constructor
     is zero to prevent the creation of a non-blocking socket.  Patch by
     Dong-hee Na.

   - bpo-38901(23): 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.

   - bpo-39288(24): Add *note math.nextafter(): 1c0.: return the next
     floating-point value after `x' towards `y'.

   - bpo-39259(25): *note POP3: 1d5. and *note POP3_SSL: 1d6. now raise
     a *note ValueError: 16d. if the given timeout for their constructor
     is zero to prevent the creation of a non-blocking socket.  Patch by
     Dong-hee Na.

   - bpo-39242(26): Updated the Gmane domain from news.gmane.org to
     news.gmane.io which is used for examples of *note NNTP: 1c6. news
     reader server and nntplib tests.

   - bpo-35292(27): Proxy the ‘SimpleHTTPRequestHandler.guess_type’ to
     *note mimetypes.guess_type: 10a1. so the *note mimetypes.init:
     10a2. is called lazily to avoid unnecessary costs when *note
     http.server: 96. module is imported.

   - bpo-39239(28): The *note select.epoll.unregister(): 22e. method no
     longer ignores the *note EBADF: 22f. error.

   - bpo-38907(29): In http.server script, restore binding to IPv4 on
     Windows.

   - bpo-39152(30): Fix ttk.Scale.configure([name]) to return
     configuration tuple for name or all options.  Giovanni Lombardo
     contributed part of the patch.

   - bpo-39198(31): If an exception were to be thrown in
     ‘Logger.isEnabledFor’ (say, by asyncio timeouts or stopit) , the
     *note logging: aa. global lock may not be released appropriately,
     resulting in deadlock.  This change wraps that block of code with
     ‘try...finally’ to ensure the lock is released.

   - bpo-39191(32): Perform a check for running loop before starting a
     new task in ‘loop.run_until_complete()’ to fail fast; it prevents
     the side effect of new task spawning before exception raising.

   - bpo-38871(33): Correctly parenthesize filter-based statements that
     contain lambda expressions in mod:*note lib2to3: a7.  Patch by
     Dong-hee Na.

   - bpo-39142(34): 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.

   - bpo-39158(35): ast.literal_eval() now supports empty sets.

   - bpo-39129(36): Fix import path for ‘asyncio.TimeoutError’

   - bpo-39057(37): ‘urllib.request.proxy_bypass_environment()’ now
     ignores leading dots and no longer ignores a trailing newline.

   - bpo-39056(38): Fixed handling invalid warning category in the -W
     option.  No longer import the re module if it is not needed.

   - bpo-39055(39): *note base64.b64decode(): 10a3. with ‘validate=True’
     raises now a binascii.Error if the input ends with a single ‘\n’.

   - bpo-21600(40): Fix ‘mock.patch.stopall()’ to stop active patches
     that were created with ‘mock.patch.dict()’.

   - bpo-39019(41): Implement dummy ‘__class_getitem__’ for *note
     tempfile.SpooledTemporaryFile: b7e.

   - bpo-39019(42): Implement dummy ‘__class_getitem__’ for
     ‘subprocess.Popen’, ‘subprocess.CompletedProcess’

   - bpo-38914(43): Adjusted the wording of the warning issued by
     distutils’ ‘check’ command when the ‘author’ and ‘maintainer’
     fields are supplied but no corresponding e-mail field
     (‘author_email’ or ‘maintainer_email’) is found.  The wording now
     reflects the fact that these fields are suggested, but not
     required.  Patch by Juergen Gmach.

   - bpo-38878(44): Fixed __subclasshook__ of *note os.PathLike: 5e5. to
     return a correct result upon inheritance.  Patch by Bar Harel.

   - bpo-38615(45): *note IMAP4: 1af. and *note IMAP4_SSL: 1b0. now have
     an optional `timeout' parameter for their constructors.  Also, the
     *note open(): 1b1. method now has an optional `timeout' parameter
     with this change.  The overridden methods of *note IMAP4_SSL: 1b0.
     and *note IMAP4_stream: 1b2. were applied to this change.  Patch by
     Dong-hee Na.

   - bpo-35182(46): Fixed ‘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.

   - bpo-38630(47): On Unix, *note subprocess.Popen.send_signal(): 10a4.
     now polls the process status.  Polling reduces the risk of sending
     a signal to the wrong process if the process completed, the *note
     subprocess.Popen.returncode: 10a5. attribute is still ‘None’, and
     the pid has been reassigned (recycled) to a new different process.

   - bpo-38536(48): Removes trailing space in formatted currency with
     ‘international=True’ and a locale with symbol following value.
     E.g.  ‘locale.currency(12.34, international=True)’ returned ‘'12,34
     EUR '’ instead of ‘'12,34 EUR'’.

   - bpo-38473(49): Use signature from inner mock for autospecced
     methods attached with ‘unittest.mock.attach_mock()’.  Patch by
     Karthikeyan Singaravelan.

   - bpo-38361(50): Fixed an issue where ‘ident’ could include a leading
     path separator when *note syslog.openlog(): 10a6. was called
     without arguments.

   - bpo-38293(51): Add *note copy.copy(): 4d1. and *note
     copy.deepcopy(): 4d2. support to *note property(): 308. objects.

   - bpo-37958(52): Added the pstats.Stats.get_profile_dict() method to
     return the profile data as a StatsProfile instance.

   - bpo-28367(53): Termios magic constants for the following baud
     rates: - B500000 - B576000 - B921600 - B1000000 - B1152000 -
     B1500000 - B2000000 - B2500000 - B3000000 - B3500000 - B4000000
     Patch by Andrey Smirnov

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39430

   (2) https://bugs.python.org/issue39413

   (3) https://bugs.python.org/issue39390

   (4) https://bugs.python.org/issue39395

   (5) https://bugs.python.org/issue39406

   (6) https://bugs.python.org/issue39396

   (7) https://bugs.python.org/issue29435

   (8) https://bugs.python.org/issue39377

   (9) https://bugs.python.org/issue39389

   (10) https://bugs.python.org/issue39366

   (11) https://bugs.python.org/issue39357

   (12) https://bugs.python.org/issue39353

   (13) https://bugs.python.org/issue39351

   (14) https://bugs.python.org/issue39350

   (15) https://bugs.python.org/issue22486

   (16) https://bugs.python.org/issue39329

   (17) https://bugs.python.org/issue39313

   (18) https://bugs.python.org/issue39259

   (19) https://bugs.python.org/issue39259

   (20) https://bugs.python.org/issue39310

   (21) https://bugs.python.org/issue39297

   (22) https://bugs.python.org/issue39259

   (23) https://bugs.python.org/issue38901

   (24) https://bugs.python.org/issue39288

   (25) https://bugs.python.org/issue39259

   (26) https://bugs.python.org/issue39242

   (27) https://bugs.python.org/issue35292

   (28) https://bugs.python.org/issue39239

   (29) https://bugs.python.org/issue38907

   (30) https://bugs.python.org/issue39152

   (31) https://bugs.python.org/issue39198

   (32) https://bugs.python.org/issue39191

   (33) https://bugs.python.org/issue38871

   (34) https://bugs.python.org/issue39142

   (35) https://bugs.python.org/issue39158

   (36) https://bugs.python.org/issue39129

   (37) https://bugs.python.org/issue39057

   (38) https://bugs.python.org/issue39056

   (39) https://bugs.python.org/issue39055

   (40) https://bugs.python.org/issue21600

   (41) https://bugs.python.org/issue39019

   (42) https://bugs.python.org/issue39019

   (43) https://bugs.python.org/issue38914

   (44) https://bugs.python.org/issue38878

   (45) https://bugs.python.org/issue38615

   (46) https://bugs.python.org/issue35182

   (47) https://bugs.python.org/issue38630

   (48) https://bugs.python.org/issue38536

   (49) https://bugs.python.org/issue38473

   (50) https://bugs.python.org/issue38361

   (51) https://bugs.python.org/issue38293

   (52) https://bugs.python.org/issue37958

   (53) https://bugs.python.org/issue28367


File: python.info,  Node: 文档<18>,  Next: 构建<17>,  Prev: 库<23>,  Up: Python 3 9 0 alpha 3

1.19.24.3 文档
..............

   - bpo-39381(1): Mention in docs that *note asyncio.get_event_loop():
     45d. implicitly creates new event loop only if called from the main
     thread.

   - bpo-38918(2): Add an entry for ‘__module__’ in the "function" &
     "method" sections of the inspect docs types and members table(3)

   - bpo-3530(4): In the *note ast: 7. module documentation, fix a
     misleading ‘NodeTransformer’ example and add advice on when to use
     the ‘fix_missing_locations’ function.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39381

   (2) https://bugs.python.org/issue38918

   (3) https://docs.python.org/3/library/inspect.html#types-and-members

   (4) https://bugs.python.org/issue3530


File: python.info,  Node: 构建<17>,  Next: IDLE<17>,  Prev: 文档<18>,  Up: Python 3 9 0 alpha 3

1.19.24.4 构建
..............

   - bpo-39395(1): On non-Windows platforms, the ‘setenv()’ and
     ‘unsetenv()’ functions are now required to build Python.

   - bpo-39160(2): Updated the documentation in ‘/configure --help’ to
     show default values, reference documentation where required and add
     additional explanation where needed.

   - bpo-39144(3): The ctags and etags build targets both include
     Modules/_ctypes and Python standard library source files.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39395

   (2) https://bugs.python.org/issue39160

   (3) https://bugs.python.org/issue39144


File: python.info,  Node: IDLE<17>,  Next: C API<14>,  Prev: 构建<17>,  Up: Python 3 9 0 alpha 3

1.19.24.5 IDLE
..............

   - bpo-39050(1): Make IDLE Settings dialog Help button work again.

   - bpo-34118(2): Tag memoryview, range, and tuple as classes, the same
     as list, etcetera, in the library manual built-in functions list.

   - bpo-32989(3): Add tests for editor newline_and_indent_event method.
     Remove dead code from pyparse find_good_parse_start method.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39050

   (2) https://bugs.python.org/issue34118

   (3) https://bugs.python.org/issue32989


File: python.info,  Node: C API<14>,  Prev: IDLE<17>,  Up: Python 3 9 0 alpha 3

1.19.24.6 C API
...............

   - bpo-39372(1): Clean header files of interfaces defined but with no
     implementation.  The public API symbols being removed are:
     ‘_PyBytes_InsertThousandsGroupingLocale’,
     ‘_PyBytes_InsertThousandsGrouping’, ‘_Py_InitializeFromArgs’,
     ‘_Py_InitializeFromWideArgs’, ‘_PyFloat_Repr’, ‘_PyFloat_Digits’,
     ‘_PyFloat_DigitsInit’, ‘PyFrame_ExtendStack’,
     ‘_PyAIterWrapper_Type’, ‘PyNullImporter_Type’, ‘PyCmpWrapper_Type’,
     ‘PySortWrapper_Type’, ‘PyNoArgsFunction’.

   - bpo-39164(2): Add a private ‘_PyErr_GetExcInfo()’ function to
     retrieve exception information of the specified Python thread
     state.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39372

   (2) https://bugs.python.org/issue39164


File: python.info,  Node: Python 3 9 0 alpha 2,  Next: Python 3 9 0 alpha 1,  Prev: Python 3 9 0 alpha 3,  Up: Changelog（更動日誌）

1.19.25 Python 3.9.0 alpha 2
----------------------------

`发布日期: 2019-12-18'

* Menu:

* 安全性: 安全性<13>.
* 核心与内置函数: 核心与内置函数<22>.
* 库: 库<24>.
* 文档: 文档<19>.
* 测试: 测试<18>.
* 构建: 构建<18>.
* Windows: Windows<18>.
* macOS: macOS<16>.
* IDLE: IDLE<18>.
* C API: C API<15>.


File: python.info,  Node: 安全性<13>,  Next: 核心与内置函数<22>,  Up: Python 3 9 0 alpha 2

1.19.25.1 安全性
................

   - bpo-38945(1): 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.

   - bpo-37228(2): Due to significant security concerns, the
     `reuse_address' parameter of *note
     asyncio.loop.create_datagram_endpoint(): 189. is no longer
     supported.  This is because of the behavior of ‘SO_REUSEADDR’ in
     UDP. For more details, see the documentation for
     ‘loop.create_datagram_endpoint()’.  (Contributed by Kyle Stanley,
     Antoine Pitrou, and Yury Selivanov in bpo-37228(3).)

   - bpo-38804(4): Fixes a ReDoS vulnerability in *note http.cookiejar:
     94.  Patch by Ben Caller.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38945

   (2) https://bugs.python.org/issue37228

   (3) https://bugs.python.org/issue37228

   (4) https://bugs.python.org/issue38804


File: python.info,  Node: 核心与内置函数<22>,  Next: 库<24>,  Prev: 安全性<13>,  Up: Python 3 9 0 alpha 2

1.19.25.2 核心与内置函数
........................

   - bpo-39028(1): Slightly improve the speed of keyword argument
     parsing with many kwargs by strengthening the assumption that
     kwargs are interned strings.

   - bpo-39080(2): Fix the value of `end_col_offset' for Starred
     Expression AST nodes when they are among the elements in the `args'
     attribute of Call AST nodes.

   - bpo-39031(3): 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.

   - bpo-20443(4): 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.

   - bpo-39008(5): *note PySys_Audit(): 1068. now requires ‘Py_ssize_t’
     to be used for size arguments in the format string, regardless of
     whether ‘PY_SSIZE_T_CLEAN’ was defined at include time.

   - bpo-38673(6): In REPL mode, don’t switch to PS2 if the line starts
     with comment or whitespace.  Based on work by Batuhan Taşkaya.

   - bpo-38922(7): Calling ‘replace’ on a code object now raises the
     ‘code.__new__’ audit event.

   - bpo-38920(8): Add audit hooks for when *note sys.excepthook(): f24.
     and *note sys.unraisablehook(): 35a. are invoked.

   - bpo-38892(9): Improve documentation for audit events table and
     functions.

   - bpo-38852(10): Set the thread stack size to 8 Mb for debug builds
     on android platforms.

   - bpo-38858(11): 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 ‘NSMALLNEGINTS’ and ‘NSMALLPOSINTS’ macros: macros
     should now be modified manually in ‘pycore_pystate.h’ header file.

   - bpo-36854(12): The garbage collector state becomes per interpreter
     (‘PyInterpreterState.gc’), rather than being global
     (‘_PyRuntimeState.gc’).

   - bpo-38835(13): The ‘PyFPE_START_PROTECT()’ and
     ‘PyFPE_END_PROTECT()’ macros are empty: they have been doing
     nothing for the last year, so stop using them.

   - bpo-38328(14): Sped up the creation time of constant *note list:
     1f8. and *note set: 1f6. displays.  Patch by Brandt Bucher.

   - bpo-38707(15): ‘MainThread.native_id’ is now correctly reset in
     child processes spawned using *note multiprocessing.Process: 4b8,
     instead of retaining the parent’s value.

   - bpo-38629(16): Added ‘__floor__’ and ‘__ceil__’ methods to float
     object.  Patch by Batuhan Taşkaya.

   - bpo-27145(17): int + int and int - int operators can now return
     small integer singletons.  Patch by hongweipeng.

   - bpo-38021(18): Provide a platform tag for AIX that is sufficient
     for PEP425 binary distribution identification.  Patch by Michael
     Felt.

   - bpo-35409(19): Ignore GeneratorExit exceptions when throwing an
     exception into the aclose coroutine of an asynchronous generator.

   - bpo-33387(20): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39028

   (2) https://bugs.python.org/issue39080

   (3) https://bugs.python.org/issue39031

   (4) https://bugs.python.org/issue20443

   (5) https://bugs.python.org/issue39008

   (6) https://bugs.python.org/issue38673

   (7) https://bugs.python.org/issue38922

   (8) https://bugs.python.org/issue38920

   (9) https://bugs.python.org/issue38892

   (10) https://bugs.python.org/issue38852

   (11) https://bugs.python.org/issue38858

   (12) https://bugs.python.org/issue36854

   (13) https://bugs.python.org/issue38835

   (14) https://bugs.python.org/issue38328

   (15) https://bugs.python.org/issue38707

   (16) https://bugs.python.org/issue38629

   (17) https://bugs.python.org/issue27145

   (18) https://bugs.python.org/issue38021

   (19) https://bugs.python.org/issue35409

   (20) https://bugs.python.org/issue33387


File: python.info,  Node: 库<24>,  Next: 文档<19>,  Prev: 核心与内置函数<22>,  Up: Python 3 9 0 alpha 2

1.19.25.3 库
............

   - bpo-39033(1): Fix *note NameError: e40. in *note zipimport: 14c.
     Patch by Karthikeyan Singaravelan.

   - bpo-39022(2): Update importlib.metadata to include improvements
     from importlib_metadata 1.3 including better serialization of
     EntryPoints and improved documentation for custom finders.

   - bpo-39006(3): Fix asyncio when the ssl module is missing: only
     check for ssl.SSLSocket instance if the ssl module is available.

   - bpo-38708(4): Fix a potential IndexError in email parser when
     parsing an empty msg-id.

   - bpo-38698(5): Add a new ‘InvalidMessageID’ token to email parser to
     represent invalid Message-ID headers.  Also, add defects when there
     is remaining value after parsing the header.

   - bpo-38994(6): Implement ‘__class_getitem__’ for ‘os.PathLike’,
     ‘pathlib.Path’.

   - bpo-38979(7): Return class from ‘ContextVar.__class_getitem__’ to
     simplify subclassing.

   - bpo-38978(8): Implement ‘__class_getitem__’ on asyncio objects
     (Future, Task, Queue).  Patch by Batuhan Taskaya.

   - bpo-38916(9): *note array.array: 216.: Remove ‘tostring()’ and
     ‘fromstring()’ methods.  They were aliases to ‘tobytes()’ and
     ‘frombytes()’, deprecated since Python 3.2.

   - bpo-38986(10): Make repr of C accelerated TaskWakeupMethWrapper the
     same as of pure Python version.

   - bpo-38982(11): Fix asyncio ‘PidfdChildWatcher’: handle ‘waitpid()’
     error.  If ‘waitpid()’ is called elsewhere, ‘waitpid()’ call fails
     with *note ChildProcessError: a79.: use return code 255 in this
     case, and log a warning.  It ensures that the pidfd file descriptor
     is closed if this error occurs.

   - bpo-38529(12): Drop too noisy asyncio warning about deletion of a
     stream without explicit ‘.close()’ call.

   - bpo-27413(13): Added ability to pass through ‘ensure_ascii’ options
     to json.dumps in the ‘json.tool’ command-line interface.

   - bpo-38634(14): The *note readline: de. module now detects if Python
     is linked to libedit at runtime on all platforms.  Previously, the
     check was only done on macOS.

   - bpo-33684(15): Fix ‘json.tool’ failed to read a JSON file with
     non-ASCII characters when locale encoding is not UTF-8.

   - bpo-38698(16): 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 *note UnboundLocalError: f37.
     on parsing an invalid value.  Patch by Claudiu Popa.

   - bpo-38927(17): Use ‘python -m pip’ instead of ‘pip’ to upgrade
     dependencies in venv.

   - bpo-26730(18): Fix ‘SpooledTemporaryFile.rollover()’ might corrupt
     the file when it is in text mode.  Patch by Serhiy Storchaka.

   - bpo-38881(19): random.choices() now raises a ValueError when all
     the weights are zero.

   - bpo-38876(20): Raise pickle.UnpicklingError when loading an item
     from memo for invalid input.

     The previous code was raising a *note KeyError: 3e9. 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 ‘BINGET’ or
     ‘LONG_BINGET’ load from the memo, leading to a *note KeyError: 3e9.
     as the determined index was bogus.  Patch by Claudiu Popa

   - bpo-38688(21): Calling func:*note shutil.copytree: 347. 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.

   - bpo-38863(22): Improve ‘is_cgi()’ function in *note http.server:
     96, which enables processing the case that cgi directory is a child
     of another directory other than root.

   - bpo-37838(23): *note typing.get_type_hints(): 1ef. properly handles
     functions decorated with *note functools.wraps(): 955.

   - bpo-38870(24): Expose *note ast.unparse(): 186. as a function of
     the *note ast: 7. module that can be used to unparse an *note
     ast.AST: 187. object and produce a string with code that would
     produce an equivalent *note ast.AST: 187. object when parsed.
     Patch by Pablo Galindo and Batuhan Taskaya.

   - bpo-38859(25): 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.

   - bpo-38857(26): 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.

   - bpo-38834(27): *note typing.TypedDict: 367. subclasses now track
     which keys are optional using the ‘__required_keys__’ and
     ‘__optional_keys__’ attributes, to enable runtime validation by
     downstream projects.  Patch by Zac Hatfield-Dodds.

   - bpo-38821(28): Fix unhandled exceptions in *note argparse: 5. when
     internationalizing error messages for arguments with ‘nargs’ set to
     special (non-integer) values.  Patch by Federico Bond.

   - bpo-38820(29): Make Python compatible with OpenSSL 3.0.0.  *note
     ssl.SSLSocket.getpeercert(): 9b7. no longer returns IPv6 addresses
     with a trailing new line.

   - bpo-38811(30): Fix an unhandled exception in *note pathlib: c8.
     when *note os.link(): b11. is missing.  Patch by Toke
     Høiland-Jørgensen.

   - bpo-38686(31): Added support for multiple ‘qop’ values in *note
     urllib.request.AbstractDigestAuthHandler: 106c.

   - bpo-38712(32): Add the Linux-specific *note
     signal.pidfd_send_signal(): 1dc. function, which allows sending a
     signal to a process identified by a file descriptor rather than a
     pid.

   - bpo-38348(33): Add ‘-i’ and ‘--indent’ (indentation level), and
     ‘--no-type-comments’ (type comments) command line options to ast
     parsing tool.

   - bpo-37523(34): Change ‘zipfile.ZipExtFile’ to raise ‘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.

   - bpo-38045(35): Improve the performance of ‘enum._decompose()’ in
     *note enum: 79.  Patch by hongweipeng.

   - bpo-36820(36): 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 ‘__traceback__’ attribute.
     Patch by Mario Corchero.

   - bpo-36406(37): Handle namespace packages in *note doctest: 66.
     Patch by Karthikeyan Singaravelan.

   - bpo-34776(38): Fix dataclasses to support forward references in
     type annotations

   - bpo-20928(39): ElementTree supports recursive XInclude processing.
     Patch by Stefan Behnel.

   - bpo-29636(40): Add whitespace options for formatting JSON with the
     ‘json.tool’ CLI. The following mutually exclusive options are now
     supported: ‘--indent’ for setting the indent level in spaces;
     ‘--tab’ for indenting with tabs; ‘--no-indent’ for suppressing
     newlines; and ‘--compact’ for suppressing all whitespace.  The
     default behavior remains the same as ‘--indent=4’.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39033

   (2) https://bugs.python.org/issue39022

   (3) https://bugs.python.org/issue39006

   (4) https://bugs.python.org/issue38708

   (5) https://bugs.python.org/issue38698

   (6) https://bugs.python.org/issue38994

   (7) https://bugs.python.org/issue38979

   (8) https://bugs.python.org/issue38978

   (9) https://bugs.python.org/issue38916

   (10) https://bugs.python.org/issue38986

   (11) https://bugs.python.org/issue38982

   (12) https://bugs.python.org/issue38529

   (13) https://bugs.python.org/issue27413

   (14) https://bugs.python.org/issue38634

   (15) https://bugs.python.org/issue33684

   (16) https://bugs.python.org/issue38698

   (17) https://bugs.python.org/issue38927

   (18) https://bugs.python.org/issue26730

   (19) https://bugs.python.org/issue38881

   (20) https://bugs.python.org/issue38876

   (21) https://bugs.python.org/issue38688

   (22) https://bugs.python.org/issue38863

   (23) https://bugs.python.org/issue37838

   (24) https://bugs.python.org/issue38870

   (25) https://bugs.python.org/issue38859

   (26) https://bugs.python.org/issue38857

   (27) https://bugs.python.org/issue38834

   (28) https://bugs.python.org/issue38821

   (29) https://bugs.python.org/issue38820

   (30) https://bugs.python.org/issue38811

   (31) https://bugs.python.org/issue38686

   (32) https://bugs.python.org/issue38712

   (33) https://bugs.python.org/issue38348

   (34) https://bugs.python.org/issue37523

   (35) https://bugs.python.org/issue38045

   (36) https://bugs.python.org/issue36820

   (37) https://bugs.python.org/issue36406

   (38) https://bugs.python.org/issue34776

   (39) https://bugs.python.org/issue20928

   (40) https://bugs.python.org/issue29636


File: python.info,  Node: 文档<19>,  Next: 测试<18>,  Prev: 库<24>,  Up: Python 3 9 0 alpha 2

1.19.25.4 文档
..............

   - bpo-38928(1): Correct when venv’s ‘upgrade_dependencies()’ and
     ‘--upgrade-deps’ are added.

   - bpo-38899(2): Update documentation to state that to activate
     virtual environments under fish one should use ‘source’, not ‘’ as
     documented at
     ‘https://fishshell.com/docs/current/commands.html#source’.

   - bpo-22377(3): Improves documentation of the values that *note
     datetime.datetime.strptime(): f91. accepts for ‘%Z’.  Patch by Karl
     Dubost.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38928

   (2) https://bugs.python.org/issue38899

   (3) https://bugs.python.org/issue22377


File: python.info,  Node: 测试<18>,  Next: 构建<18>,  Prev: 文档<19>,  Up: Python 3 9 0 alpha 2

1.19.25.5 测试
..............

   - bpo-38546(1): 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.

   - bpo-38546(2): Multiprocessing and concurrent.futures tests now stop
     the resource tracker process when tests complete.

   - bpo-38614(3): Replace hardcoded timeout constants in tests with new
     *note test.support: 106. constants: *note LOOPBACK_TIMEOUT: 10b1,
     *note INTERNET_TIMEOUT: 10b2, *note SHORT_TIMEOUT: f94. and *note
     LONG_TIMEOUT: 10b3.  It becomes easier to adjust these four timeout
     constants for all tests at once, rather than having to adjust every
     single test file.

   - bpo-38547(4): 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.

   - bpo-38992(5): Fix a test for *note math.fsum(): e04. that was
     failing due to constant folding.

   - bpo-38991(6): *note test.support: 106.: ‘run_python_until_end()’,
     ‘assert_python_ok()’ and ‘assert_python_failure()’ functions no
     longer strip whitespaces from stderr.  Remove
     ‘test.support.strip_python_stderr()’ function.

   - bpo-38965(7): Fix test_faulthandler on GCC 10.  Use the "volatile"
     keyword in ‘faulthandler._stack_overflow()’ to prevent tail call
     optimization on any compiler, rather than relying on compiler
     specific pragma.

   - bpo-38875(8): test_capi: trashcan tests now require the test "cpu"
     resource.

   - bpo-38841(9): Skip asyncio
     test_create_datagram_endpoint_existing_sock_unix on platforms
     lacking a functional bind() for named unix domain sockets.

   - bpo-38692(10): Skip the test_posix.test_pidfd_open() test if
     ‘os.pidfd_open()’ fails with a *note PermissionError: 6f6.  This
     situation can happen in a Linux sandbox using a syscall whitelist
     which doesn’t allow the ‘pidfd_open()’ syscall yet.

   - bpo-38839(11): Fix some unused functions in tests.  Patch by Adam
     Johnson.

   - bpo-38669(12): Raise *note TypeError: 1fe. when passing target as a
     string with *note unittest.mock.patch.object(): 10b4.

   - bpo-37957(13): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38546

   (2) https://bugs.python.org/issue38546

   (3) https://bugs.python.org/issue38614

   (4) https://bugs.python.org/issue38547

   (5) https://bugs.python.org/issue38992

   (6) https://bugs.python.org/issue38991

   (7) https://bugs.python.org/issue38965

   (8) https://bugs.python.org/issue38875

   (9) https://bugs.python.org/issue38841

   (10) https://bugs.python.org/issue38692

   (11) https://bugs.python.org/issue38839

   (12) https://bugs.python.org/issue38669

   (13) https://bugs.python.org/issue37957


File: python.info,  Node: 构建<18>,  Next: Windows<18>,  Prev: 测试<18>,  Up: Python 3 9 0 alpha 2

1.19.25.6 构建
..............

   - bpo-37404(1): *note asyncio: 9. now raises ‘TyperError’ when
     calling incompatible methods with an *note ssl.SSLSocket: 192.
     socket.  Patch by Ido Michael.

   - bpo-36500(2): Added an optional "regen" project to the Visual
     Studio solution that will regenerate all grammar, tokens, and
     opcodes.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37404

   (2) https://bugs.python.org/issue36500


File: python.info,  Node: Windows<18>,  Next: macOS<16>,  Prev: 构建<18>,  Up: Python 3 9 0 alpha 2

1.19.25.7 Windows
.................

   - bpo-39007(1): Add auditing events to functions in *note winreg:
     133.

   - bpo-33125(2): Add support for building and releasing Windows ARM64
     packages.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue39007

   (2) https://bugs.python.org/issue33125


File: python.info,  Node: macOS<16>,  Next: IDLE<18>,  Prev: Windows<18>,  Up: Python 3 9 0 alpha 2

1.19.25.8 macOS
...............

   - bpo-37931(1): 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 ‘import posix’.  Patch
     by Benoît Hudson.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37931


File: python.info,  Node: IDLE<18>,  Next: C API<15>,  Prev: macOS<16>,  Up: Python 3 9 0 alpha 2

1.19.25.9 IDLE
..............

   - bpo-38944(1): Escape key now closes IDLE completion windows.  Patch
     by Johnny Najera.

   - bpo-38943(2): Fix IDLE autocomplete windows not always appearing on
     some systems.  Patch by Johnny Najera.

   - bpo-38862(3): ’Strip Trailing Whitespace’ on the Format menu
     removes extra newlines at the end of non-shell files.

   - bpo-38636(4): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38944

   (2) https://bugs.python.org/issue38943

   (3) https://bugs.python.org/issue38862

   (4) https://bugs.python.org/issue38636


File: python.info,  Node: C API<15>,  Prev: IDLE<18>,  Up: Python 3 9 0 alpha 2

1.19.25.10 C API
................

   - bpo-38896(1): Remove ‘PyUnicode_ClearFreeList()’ function: the
     Unicode free list has been removed in Python 3.3.

   - bpo-37340(2): Remove ‘PyMethod_ClearFreeList()’ and
     ‘PyCFunction_ClearFreeList()’ functions: the free lists of bound
     method objects have been removed.

   - bpo-38835(3): Exclude ‘PyFPE_START_PROTECT()’ and
     ‘PyFPE_END_PROTECT()’ macros of ‘pyfpe.h’ from ‘Py_LIMITED_API’
     (stable API).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38896

   (2) https://bugs.python.org/issue37340

   (3) https://bugs.python.org/issue38835


File: python.info,  Node: Python 3 9 0 alpha 1,  Next: Python 3 8 0 beta 1,  Prev: Python 3 9 0 alpha 2,  Up: Changelog（更動日誌）

1.19.26 Python 3.9.0 alpha 1
----------------------------

`发布日期: 2019-11-19'

* Menu:

* 安全性: 安全性<14>.
* 核心与内置函数: 核心与内置函数<23>.
* 库: 库<25>.
* 文档: 文档<20>.
* 测试: 测试<19>.
* 构建: 构建<19>.
* Windows: Windows<19>.
* macOS: macOS<17>.
* IDLE: IDLE<19>.
* 工具/示例: 工具/示例<7>.
* C API: C API<16>.


File: python.info,  Node: 安全性<14>,  Next: 核心与内置函数<23>,  Up: Python 3 9 0 alpha 1

1.19.26.1 安全性
................

   - bpo-38722(1): *note runpy: e2. now uses *note io.open_code(): 1050.
     to open code files.  Patch by Jason Killen.

   - bpo-38622(2): Add additional audit events for the *note ctypes: 2a.
     module.

   - bpo-38418(3): 修复 *note os.system(): e86. 的审计事件被命名为
     ‘os.system’ 。

   - bpo-38243(4): 在将文档页渲染为 HTML 时会对 *note
     xmlrpc.server.DocXMLRPCServer: 10bc. 的服务器标题进行转义。 （由
     Dong-hee Na 在 bpo-38243(5) 中贡献。）

   - bpo-38174(6): 将厂商化的 expat 库版本更新至 2.2.8，这解决了
     CVE-2019-15903。

   - bpo-37764(7): 修复了 email._header_value_parser.get_unstructured 在
     邮件头不包含末尾空格，以及在其包含无效的已编码字等特定情况下进入无
     限循环的问题。 由 Ashwin Ramaswami 贡献补丁。

   - bpo-37461(8): Fix an infinite loop when parsing specially crafted
     email headers.  Patch by Abhilash Raj.

   - bpo-37363(9): Adds audit events for the range of supported run
     commands (see *note 命令行与环境: 10bd.).

   - bpo-37463(10): 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’.

   - bpo-37363(11): Adds audit events for *note ensurepip: 78, *note
     ftplib: 82, *note glob: 88, *note imaplib: 97, *note nntplib: c0,
     *note pdb: c9, *note poplib: d0, *note shutil: e9, *note smtplib:
     ed, *note sqlite3: f2, *note subprocess: f9, *note telnetlib: 102,
     *note tempfile: 103. and *note webbrowser: 132, as well as *note
     os.listdir(): b1c, *note os.scandir(): 389. and *note breakpoint():
     40b.

   - bpo-37364(12): *note io.open_code(): 1050. is now used when reading
     ‘.pth’ files.

   - bpo-34631(13): 在Windows安装程序中将OpenSSL更新为1.1.1c

   - bpo-34155(14): Fix parsing of invalid email addresses with more
     than one ‘@’ (e.g.  a@b@c.com.)  to not return the part before 2nd
     ‘@’ as valid email address.  Patch by maxking & jpic.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38722

   (2) https://bugs.python.org/issue38622

   (3) https://bugs.python.org/issue38418

   (4) https://bugs.python.org/issue38243

   (5) https://bugs.python.org/issue38243

   (6) https://bugs.python.org/issue38174

   (7) https://bugs.python.org/issue37764

   (8) https://bugs.python.org/issue37461

   (9) https://bugs.python.org/issue37363

   (10) https://bugs.python.org/issue37463

   (11) https://bugs.python.org/issue37363

   (12) https://bugs.python.org/issue37364

   (13) https://bugs.python.org/issue34631

   (14) https://bugs.python.org/issue34155


File: python.info,  Node: 核心与内置函数<23>,  Next: 库<25>,  Prev: 安全性<14>,  Up: Python 3 9 0 alpha 1

1.19.26.2 核心与内置函数
........................

   - bpo-38631(1): Replace ‘Py_FatalError()’ call with a regular *note
     RuntimeError: 3dc. exception in ‘float.__getformat__()’.

   - bpo-38639(2): Optimized *note math.floor(): df2, *note math.ceil():
     df3. and *note math.trunc(): df4. for floats.

   - bpo-38640(3): 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.

   - bpo-38613(4): Optimized some set operations (e.g.  ‘|’, ‘^’, and
     ‘-’) of ‘dict_keys’.  ‘d.keys() | other’ was slower than ‘set(d) |
     other’ but they are almost same performance for now.

   - bpo-28029(5): ‘"".replace("", s, n)’ now returns ‘s’ instead of an
     empty string for all non-zero ‘n’.  There are similar changes for
     *note bytes: 172. and *note bytearray: 173. objects.

   - bpo-38535(6): 修复了装饰器中不带参数调用的AST节点的行号和列偏移量。

   - bpo-38525(7): 修复了使用空 ‘dict’ 对象的反向迭代器时的分段错误。由
     Dong-hee Na 和 Inada Naoki 补丁修复

   - bpo-38465(8): *note bytearray: 173, *note array: 216. and *note
     mmap: 31c. objects allow now to export more than ‘2**31’ buffers at
     a time.

   - bpo-38469(9): Fixed a bug where the scope of named expressions was
     not being resolved correctly in the presence of the `global'
     keyword.  Patch by Pablo Galindo.

   - bpo-38437(10): Activate the ‘GC_DEBUG’ macro for debug builds of
     the interpreter (when ‘Py_DEBUG’ is set).  Patch by Pablo Galindo.

   - bpo-38379(11): 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.

   - bpo-38379(12): 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 ‘collect()’ and ‘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.

   - bpo-38392(13): In debug mode, *note PyObject_GC_Track(): f06. now
     calls ‘tp_traverse()’ of the object type to ensure that the object
     is valid: test that objects visited by ‘tp_traverse()’ are valid.

   - bpo-38210(14): Remove unnecessary intersection and update set
     operation in dictview with empty set.  (Contributed by Dong-hee Na
     in bpo-38210(15).)

   - bpo-38402(16): Check the error from the system’s underlying ‘crypt’
     or ‘crypt_r’.

   - bpo-37474(17): On FreeBSD, Python no longer calls
     ‘fedisableexcept()’ at startup to control the floating point
     control mode.  The call became useless since FreeBSD 6: it became
     the default mode.

   - bpo-38006(18): 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.

   - bpo-38317(19): Fix warnings options priority:
     ‘PyConfig.warnoptions’ has the highest priority, as stated in the
     PEP 587(20).

   - bpo-38310(21): Predict ‘BUILD_MAP_UNPACK_WITH_CALL’ ->
     ‘CALL_FUNCTION_EX’ opcode pairs in the main interpreter loop.
     Patch by Brandt Bucher.

   - bpo-36871(22): 改进了 mock 的 assert_has_calls 和 assert_has_awaits
     方法的错误处理。 修复了一个漏洞，它会在将预期的调用绑定到 mock 的规
     格时静默接收所遇到的任何错误，从而产生误导性的错误输出。

   - bpo-11410(23): 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.

   - bpo-38219(24): Optimized the *note dict: 164. constructor and the
     *note update(): e8e. method for the case when the argument is a
     dict.

   - bpo-38236(25): Python now dumps path configuration if it fails to
     import the Python codecs of the filesystem and stdio encodings.

   - bpo-38013(26): Allow to call ‘async_generator_athrow().throw(...)’
     even for non-started async generator helper.  It fixes annoying
     warning at the end of *note asyncio.run(): 18d. call.

   - bpo-38124(27): Fix an off-by-one error in PyState_AddModule that
     could cause out-of-bounds memory access.

   - bpo-38116(28): The select module is now PEP-384 compliant and no
     longer has static state

   - bpo-38113(29): ast module updated to PEP-384 and all statics
     removed

   - bpo-38076(30): The struct module is now PEP-384 compatible

   - bpo-38075(31): The random module is now PEP-384 compatible

   - bpo-38074(32): zlib module made PEP-384 compatible

   - bpo-38073(33): Make pwd extension module PEP-384 compatible

   - bpo-38072(34): grp module made PEP-384 compatible

   - bpo-38069(35): Make _posixsubprocess PEP-384 compatible

   - bpo-38071(36): Make termios extension module PEP-384 compatible

   - bpo-38005(37): 修复InterpreterID 和 ChannelID的创建和对比.

   - bpo-36946(38): Fix possible signed integer overflow when handling
     slices.  Patch by hongweipeng.

   - bpo-37994(39): Fixed silencing arbitrary errors if an attribute
     lookup fails in several sites.  Only AttributeError should be
     silenced.

   - bpo-8425(40): 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ù).

   - bpo-37966(41): The implementation of *note is_normalized(): 370.
     has been greatly sped up on strings that aren’t normalized, by
     implementing the full normalization-quick-check algorithm from the
     Unicode standard.

   - bpo-37947(42): Adjust correctly the recursion level in the symtable
     generation for named expressions.  Patch by Pablo Galindo.

   - bpo-37812(43): The ‘CHECK_SMALL_INT’ macro used inside
     ‘Object/longobject.c’ has been replaced with an explicit ‘return’
     at each call site.

   - bpo-37751(44): Fix *note codecs.lookup(): 238. to normalize the
     encoding name the same way than ‘encodings.normalize_encoding()’,
     except that *note codecs.lookup(): 238. also converts the name to
     lower case.

   - bpo-37830(45): Fixed compilation of *note break: 3fa. and *note
     continue: 2bb. in the *note finally: 2bc. block when the
     corresponding *note try: e37. block contains *note return: 2c8.
     with a non-constant value.

   - bpo-20490(46): Improve import error message for partially
     initialized module on circular ‘from’ imports - by Anthony Sottile.

   - bpo-37840(47): Fix handling of negative indices in *note sq_item:
     10bf. of *note bytearray: 173.  Patch by Sergey Fedoseev.

   - bpo-37802(48): Slightly improve performance of *note
     PyLong_FromUnsignedLong(): 10c0, *note
     PyLong_FromUnsignedLongLong(): 10c1. and *note PyLong_FromSize_t():
     10c2.  Patch by Sergey Fedoseev.

   - bpo-37409(49): 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.

   - bpo-32912(50): Reverted bpo-32912(51): emitting *note
     SyntaxWarning: 2c9. instead of *note DeprecationWarning: 15a. for
     invalid escape sequences in string and bytes literals.

   - bpo-37757(52): PEP 572(53): As described in the PEP, assignment
     expressions now raise *note SyntaxError: 559. when their
     interaction with comprehension scoping results in an ambiguous
     target scope.

     The ‘TargetScopeError’ subclass originally proposed by the PEP has
     been removed in favour of just raising regular syntax errors for
     the disallowed cases.

   - bpo-36279(54): Fix potential use of uninitialized memory in *note
     os.wait3(): 75c.

   - bpo-36311(55): Decoding bytes objects larger than 2GiB is faster
     and no longer fails when a multibyte characters spans a chunk
     boundary.

   - bpo-34880(56): The *note assert: 23f. statement now works properly
     if the *note AssertionError: 240. exception is being shadowed.
     Patch by Zackery Spytz.

   - bpo-37340(57): Removed object cache (‘free_list’) for bound method
     objects.  Temporary bound method objects are less used than before
     thanks to the ‘LOAD_METHOD’ opcode and the
     ‘_PyObject_VectorcallMethod’ C API.

   - bpo-37648(58): Fixed minor inconsistency in ‘list.__contains__()’,
     ‘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
     ‘==’.

   - bpo-37444(59): Update differing exception between
     ‘builtins.__import__()’ and *note importlib.__import__(): a8e.

   - bpo-37619(60): When adding a wrapper descriptor from one class to a
     different class (for example, setting ‘__add__ = str.__add__’ on an
     ‘int’ subclass), an exception is correctly raised when the operator
     is called.

   - bpo-37593(61): Swap the positions of the `posonlyargs' and `args'
     parameters in the constructor of ‘ast.parameters’ nodes.

   - bpo-37543(62): Optimized pymalloc for non PGO build.

   - bpo-37537(63): Compute allocated pymalloc blocks inside
     _Py_GetAllocatedBlocks().  This slows down _Py_GetAllocatedBlocks()
     but gives a small speedup to _PyObject_Malloc() and
     _PyObject_Free().

   - bpo-37467(64): Fix *note sys.excepthook(): f24. and
     ‘PyErr_Display()’ if a filename is a bytes string.  For example,
     for a SyntaxError exception where the filename attribute is a bytes
     string.

   - bpo-37433(65): Fix ‘SyntaxError’ indicator printing too many spaces
     for multi-line strings - by Anthony Sottile.

   - bpo-37417(66): ‘bytearray.extend()’ now correctly handles errors
     that arise during iteration.  Patch by Brandt Bucher.

   - bpo-37414(67): The undocumented ‘sys.callstats()’ function has been
     removed.  Since Python 3.7, it was deprecated and always returned
     ‘None’.  It required a special build option ‘CALL_PROFILE’ which
     was already removed in Python 3.7.

   - bpo-37392(68): Remove ‘sys.getcheckinterval()’ and
     ‘sys.setcheckinterval()’ functions.  They were deprecated since
     Python 3.2.  Use *note sys.getswitchinterval(): 217. and *note
     sys.setswitchinterval(): 218. instead.  Remove also
     ‘check_interval’ field of the ‘PyInterpreterState’ structure.

   - bpo-37388(69): In development mode and in debug build, `encoding'
     and `errors' arguments are now checked on string encoding and
     decoding operations.  Examples: *note open(): 16f, *note
     str.encode(): 170. and *note bytes.decode(): 171.

     By default, for best performances, the `errors' argument is only
     checked at the first encoding/decoding error, and the `encoding'
     argument is sometimes ignored for empty strings.

   - bpo-37348(70): Optimized decoding short ASCII string with UTF-8 and
     ascii codecs.  ‘b"foo".decode()’ is about 15% faster.  Patch by
     Inada Naoki.

   - bpo-24214(71): Improved support of the surrogatepass error handler
     in the UTF-8 and UTF-16 incremental decoders.

   - bpo-37330(72): *note open(): 16f, *note io.open(): 74d, *note
     codecs.open(): 10c3. and *note fileinput.FileInput: 3a4. no longer
     accept ‘'U'’ ("universal newline") in the file mode.  This flag was
     deprecated since Python 3.3.

   - bpo-35224(73): Reverse evaluation order of key: value in dict
     comprehensions as proposed in PEP 572.  I.e.  in ‘{k: v for ...}’,
     ‘k’ will be evaluated before ‘v’.

   - bpo-37316(74): Fix the *note PySys_Audit(): 1068. call in *note
     mmap.mmap: 31c.

   - bpo-37300(75): Remove an unnecessary Py_XINCREF in classobject.c.

   - bpo-37269(76): Fix a bug in the peephole optimizer that was not
     treating correctly constant conditions with binary operators.
     Patch by Pablo Galindo.

   - bpo-20443(77): 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.

   - bpo-37257(78): Python’s small object allocator (‘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.

   - bpo-37231(79): The dispatching of type slots to special methods
     (for example calling ‘__mul__’ when doing ‘x * y’) has been made
     faster.

   - bpo-36974(80): Implemented separate vectorcall functions for every
     calling convention of builtin functions and methods.  This improves
     performance for calls.

   - bpo-37213(81): Handle correctly negative line offsets in the
     peephole optimizer.  Patch by Pablo Galindo.

   - bpo-37219(82): Remove erroneous optimization for empty set
     differences.

   - bpo-15913(83): Implement *note PyBuffer_SizeFromFormat(): 10c4.
     function (previously documented but not implemented): call *note
     struct.calcsize(): 10c5.  Patch by Joannah Nanjekye.

   - bpo-36922(84): Slot functions optimize any callable with
     ‘Py_TPFLAGS_METHOD_DESCRIPTOR’ instead of only instances of
     ‘function’.

   - bpo-36974(85): The slot ‘tp_vectorcall_offset’ is inherited
     unconditionally to support ‘super().__call__()’ when the base class
     uses vectorcall.

   - bpo-37160(86): *note threading.get_native_id(): 360. now also
     supports NetBSD.

   - bpo-37077(87): Add *note threading.get_native_id(): 360. support
     for AIX. Patch by M. Felt

   - bpo-36781(88): *note sum(): 316. has been optimized for boolean
     values.

   - bpo-34556(89): Add ‘--upgrade-deps’ to venv module.  Patch by
     Cooper Ry Lees

   - bpo-20523(90): ‘pdb.Pdb’ supports ~/.pdbrc in Windows 7.  Patch by
     Tim Hopper and Dan Lidral-Porter.

   - bpo-35551(91): 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.

   - bpo-19072(92): The *note classmethod: 309. decorator can now wrap
     other descriptors such as property objects.  Adapted from a patch
     written by Graham Dumpleton.

   - bpo-27575(93): Improve speed of dictview intersection by directly
     using set intersection logic.  Patch by David Su.

   - bpo-30773(94): Prohibit parallel running of aclose() / asend() /
     athrow().  Fix ag_running to reflect the actual running status of
     the AG.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38631

   (2) https://bugs.python.org/issue38639

   (3) https://bugs.python.org/issue38640

   (4) https://bugs.python.org/issue38613

   (5) https://bugs.python.org/issue28029

   (6) https://bugs.python.org/issue38535

   (7) https://bugs.python.org/issue38525

   (8) https://bugs.python.org/issue38465

   (9) https://bugs.python.org/issue38469

   (10) https://bugs.python.org/issue38437

   (11) https://bugs.python.org/issue38379

   (12) https://bugs.python.org/issue38379

   (13) https://bugs.python.org/issue38392

   (14) https://bugs.python.org/issue38210

   (15) https://bugs.python.org/issue38210

   (16) https://bugs.python.org/issue38402

   (17) https://bugs.python.org/issue37474

   (18) https://bugs.python.org/issue38006

   (19) https://bugs.python.org/issue38317

   (20) https://www.python.org/dev/peps/pep-0587

   (21) https://bugs.python.org/issue38310

   (22) https://bugs.python.org/issue36871

   (23) https://bugs.python.org/issue11410

   (24) https://bugs.python.org/issue38219

   (25) https://bugs.python.org/issue38236

   (26) https://bugs.python.org/issue38013

   (27) https://bugs.python.org/issue38124

   (28) https://bugs.python.org/issue38116

   (29) https://bugs.python.org/issue38113

   (30) https://bugs.python.org/issue38076

   (31) https://bugs.python.org/issue38075

   (32) https://bugs.python.org/issue38074

   (33) https://bugs.python.org/issue38073

   (34) https://bugs.python.org/issue38072

   (35) https://bugs.python.org/issue38069

   (36) https://bugs.python.org/issue38071

   (37) https://bugs.python.org/issue38005

   (38) https://bugs.python.org/issue36946

   (39) https://bugs.python.org/issue37994

   (40) https://bugs.python.org/issue8425

   (41) https://bugs.python.org/issue37966

   (42) https://bugs.python.org/issue37947

   (43) https://bugs.python.org/issue37812

   (44) https://bugs.python.org/issue37751

   (45) https://bugs.python.org/issue37830

   (46) https://bugs.python.org/issue20490

   (47) https://bugs.python.org/issue37840

   (48) https://bugs.python.org/issue37802

   (49) https://bugs.python.org/issue37409

   (50) https://bugs.python.org/issue32912

   (51) https://bugs.python.org/issue32912

   (52) https://bugs.python.org/issue37757

   (53) https://www.python.org/dev/peps/pep-0572

   (54) https://bugs.python.org/issue36279

   (55) https://bugs.python.org/issue36311

   (56) https://bugs.python.org/issue34880

   (57) https://bugs.python.org/issue37340

   (58) https://bugs.python.org/issue37648

   (59) https://bugs.python.org/issue37444

   (60) https://bugs.python.org/issue37619

   (61) https://bugs.python.org/issue37593

   (62) https://bugs.python.org/issue37543

   (63) https://bugs.python.org/issue37537

   (64) https://bugs.python.org/issue37467

   (65) https://bugs.python.org/issue37433

   (66) https://bugs.python.org/issue37417

   (67) https://bugs.python.org/issue37414

   (68) https://bugs.python.org/issue37392

   (69) https://bugs.python.org/issue37388

   (70) https://bugs.python.org/issue37348

   (71) https://bugs.python.org/issue24214

   (72) https://bugs.python.org/issue37330

   (73) https://bugs.python.org/issue35224

   (74) https://bugs.python.org/issue37316

   (75) https://bugs.python.org/issue37300

   (76) https://bugs.python.org/issue37269

   (77) https://bugs.python.org/issue20443

   (78) https://bugs.python.org/issue37257

   (79) https://bugs.python.org/issue37231

   (80) https://bugs.python.org/issue36974

   (81) https://bugs.python.org/issue37213

   (82) https://bugs.python.org/issue37219

   (83) https://bugs.python.org/issue15913

   (84) https://bugs.python.org/issue36922

   (85) https://bugs.python.org/issue36974

   (86) https://bugs.python.org/issue37160

   (87) https://bugs.python.org/issue37077

   (88) https://bugs.python.org/issue36781

   (89) https://bugs.python.org/issue34556

   (90) https://bugs.python.org/issue20523

   (91) https://bugs.python.org/issue35551

   (92) https://bugs.python.org/issue19072

   (93) https://bugs.python.org/issue27575

   (94) https://bugs.python.org/issue30773


File: python.info,  Node: 库<25>,  Next: 文档<20>,  Prev: 核心与内置函数<23>,  Up: Python 3 9 0 alpha 1

1.19.26.3 库
............

   - bpo-36589(1): The *note curses.update_lines_cols(): 7b9. function
     now returns ‘None’ instead of ‘1’ on success.

   - bpo-38807(2): Update *note TypeError: 1fe. messages for *note
     os.path.join(): 10c7. to include *note os.PathLike: 5e5. objects as
     acceptable input types.

   - bpo-38724(3): Add a repr for ‘subprocess.Popen’ objects.  Patch by
     Andrey Doroschenko.

   - bpo-38786(4): pydoc now recognizes and parses HTTPS URLs.  Patch by
     python273.

   - bpo-38785(5): Prevent asyncio from crashing if parent ‘__init__’ is
     not called from a constructor of object derived from
     ‘asyncio.Future’.

   - bpo-38723(6): *note pdb: c9. now uses *note io.open_code(): 1050.
     to trigger auditing events.

   - bpo-27805(7): Allow opening pipes and other non-seekable files in
     append mode with *note open(): 16f.

   - bpo-38438(8): Simplify the *note argparse: 5. usage message for
     ‘nargs="*"’.

   - bpo-38761(9): WeakSet is now registered as a
     collections.abc.MutableSet.

   - bpo-38716(10): 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.

   - bpo-38713(11): Add *note os.P_PIDFD: 1cb. constant, which may be
     passed to *note os.waitid(): 75f. to wait on a Linux process file
     descriptor.

   - bpo-38692(12): Add *note asyncio.PidfdChildWatcher: 18e, a
     Linux-specific child watcher implementation that polls process file
     descriptors.

   - bpo-38692(13): Expose the Linux ‘pidfd_open’ syscall as *note
     os.pidfd_open(): 158.

   - bpo-38602(14): Added constants ‘F_OFD_GETLK’, ‘F_OFD_SETLK’ and
     ‘F_OFD_SETLKW’ to the *note fcntl: 7c. module.  Patch by Dong-hee
     Na.

   - bpo-38334(15): 修复了在加密的 ‘zipfile.ZipExtFile’ 上向后搜索的问题
     。

   - bpo-38312(16): Add *note curses.get_escdelay(): 198, *note
     curses.set_escdelay(): 199, *note curses.get_tabsize(): 19a, and
     *note curses.set_tabsize(): 19b. functions - by Anthony Sottile.

   - bpo-38586(17): Now *note fileConfig(): 4af. correctly sets the
     .name of handlers loaded.

   - bpo-38565(18): Add new cache_parameters() method for
     functools.lru_cache() to better support pickling.

   - bpo-34679(19): asynci.ProactorEventLoop.close() 现在仅调用主线程中
     的 signal.set_wakeup_fd()

   - bpo-31202(20): ‘pathlib.WindowsPath.glob()’ 的结果现在与文本部分的
     式样匹配。

   - bpo-36321(21): Remove misspelled attribute.  The 3.8 changelog
     noted that this would be removed in 3.9.

   - bpo-38521(22): Fixed erroneous equality comparison in
     statistics.NormalDist().

   - bpo-38493(23): Added *note CLD_KILLED: 1c9. and *note CLD_STOPPED:
     1ca. for ‘si_code’.  Patch by Dong-hee Na.

   - bpo-38478(24): Fixed a bug in ‘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.

   - bpo-33604(25): Fixed *note hmac.new: 940. and ‘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.

   - bpo-38378(26): Parameters `out' and `in' of *note os.sendfile():
     461. was renamed to `out_fd' and `in_fd'.

   - bpo-38417(27): Added support for setting the umask in the child
     process to the subprocess module on POSIX systems.

   - bpo-38449(28): Revert GH-15522, which introduces a regression in
     *note mimetypes.guess_type(): 10a1. due to improper handling of
     filenames as urls.

   - bpo-38431(29): Fix ‘__repr__’ method for ‘dataclasses.InitVar’ to
     support typing objects, patch by Samuel Colvin.

   - bpo-38109(30): Add missing *note stat.S_IFDOOR: 9ba, *note
     stat.S_IFPORT: 9bb, *note stat.S_IFWHT: 9bc, *note stat.S_ISDOOR():
     10c8, *note stat.S_ISPORT(): 10c9, and *note stat.S_ISWHT(): 10ca.
     values to the Python implementation of *note stat: f4.

   - bpo-38422(31): Clarify docstrings of pathlib suffix(es)

   - bpo-38405(32): Nested subclasses of *note typing.NamedTuple: 227.
     are now pickleable.

   - bpo-38332(33): Prevent *note KeyError: 3e9. thrown by
     ‘_encoded_words.decode()’ when given an encoded-word with invalid
     content-type encoding from propagating all the way to
     ‘email.message.get()’.

   - bpo-38371(34): Deprecated the ‘split()’ method in
     ‘_tkinter.TkappType’ in favour of the ‘splitlist()’ method which
     has more consistent and predicable behavior.

   - bpo-38341(35): Add *note smtplib.SMTPNotSupportedError: 10cb. to
     the *note smtplib: ed. exported names.

   - bpo-38319(36): 修复 套接字 和 shutil 模块中使用的sendfile() 在
     32-bit 架构上会产生 OverflowError for files >= 2GiB .  (补丁由
     Giampaolo Rodola提供)

   - bpo-38242(37): 回滚新的 asyncio Streams API

   - bpo-13153(38): 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).

   - bpo-38019(39): Correctly handle pause/resume reading of closed
     asyncio unix pipe.

   - bpo-38163(40): 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).

   - bpo-38161(41): Removes _AwaitEvent from AsyncMock.

   - bpo-38216(42): Allow the rare code that wants to send invalid http
     requests from the *note http.client: 93. library a way to do so.
     The fixes for bpo-30458(43) led to breakage for some projects that
     were relying on this ability to test their own behavior in the face
     of bad requests.

   - bpo-28286(44): Deprecate opening *note GzipFile: 206. for writing
     implicitly.  Always specify the `mode' argument for writing.

   - bpo-38108(45): Any synchronous magic methods on an AsyncMock now
     return a MagicMock.  Any asynchronous magic methods on a MagicMock
     now return an AsyncMock.

   - bpo-38265(46): Update the `length' parameter of *note os.pread():
     4bf. to accept ‘Py_ssize_t’ instead of ‘int’.

   - bpo-38112(47): *note compileall: 20. has a higher default recursion
     limit and new command-line arguments for path manipulation,
     symlinks handling, and multiple optimization levels.

   - bpo-38248(48): asyncio: Fix inconsistent immediate Task
     cancellation

   - bpo-38237(49): The arguments for the builtin pow function are more
     descriptive.  They can now also be passed in as keywords.

   - bpo-34002(50): Improve efficiency in parts of email package by
     changing while-pop to a for loop, using isdisjoint instead of set
     intersections.

   - bpo-38191(51): Constructors of *note NamedTuple: 227. and *note
     TypedDict: 367. types now accept arbitrary keyword argument names,
     including "cls", "self", "typename", "_typename", "fields" and
     "_fields".

   - bpo-38155(52): Add ‘__all__’ to *note datetime: 30.  Patch by Tahia
     Khan.

   - bpo-38185(53): Fixed case-insensitive string comparison in *note
     sqlite3.Row: 84d. indexing.

   - bpo-38136(54): 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.

   - bpo-37828(55): Fix default mock name in *note
     unittest.mock.Mock.assert_called(): 69f. exceptions.  Patch by
     Abraham Toriz Cruz.

   - bpo-38175(56): Fix a memory leak in comparison of *note
     sqlite3.Row: 84d. objects.

   - bpo-33936(57): _hashlib no longer calls obsolete OpenSSL
     initialization function with OpenSSL 1.1.0+.

   - bpo-34706(58): Preserve subclassing in
     inspect.Signature.from_callable.

   - bpo-38153(59): 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.

   - bpo-38115(60): 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.

   - bpo-38148(61): Add slots to *note asyncio: 9. transport classes,
     which can reduce memory usage.

   - bpo-38142(62): The _hashlib OpenSSL wrapper extension module is now
     PEP-384 compliant.

   - bpo-9216(63): hashlib constructors now support usedforsecurity flag
     to signal that a hashing algorithm is not used in a security
     context.

   - bpo-36991(64): Fixes a potential incorrect AttributeError exception
     escaping ZipFile.extract() in some unsupported input error
     situations.

   - bpo-38134(65): Remove obsolete copy of PBKDF2_HMAC_fast.  All
     supported OpenSSL versions contain a fast implementation.

   - bpo-38132(66): 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.

   - bpo-38008(67): Fix parent class check in protocols to correctly
     identify the module that provides a builtin protocol, instead of
     assuming they all come from the *note collections.abc: 1e. module

   - bpo-34037(68): For *note asyncio: 9, add a new coroutine
     ‘loop.shutdown_default_executor()’.  The new coroutine provides an
     API to schedule an executor shutdown that waits on the threadpool
     to finish closing.  Also, *note asyncio.run(): 18d. has been
     updated to utilize the new coroutine.  Patch by Kyle Stanley.

   - bpo-37405(69): Fixed regression bug for socket.getsockname() for
     non-CAN_ISOTP AF_CAN address family sockets by returning a 1-tuple
     instead of string.

   - bpo-38121(70): Update parameter names on functions in
     importlib.metadata matching the changes in the 0.22 release of
     importlib_metadata.

   - bpo-38110(71): The os.closewalk() implementation now uses the libc
     fdwalk() API on platforms where it is available.

   - bpo-38093(72): Fixes AsyncMock so it doesn’t crash when used with
     AsyncContextManagers or AsyncIterators.

   - bpo-37488(73): Add warning to ‘datetime.utctimetuple()’,
     ‘datetime.utcnow()’ and ‘datetime.utcfromtimestamp()’ .

   - bpo-35640(74): Allow passing a *note path-like object: 472. as
     ‘directory’ argument to the *note
     http.server.SimpleHTTPRequestHandler: 49b. class.  Patch by Géry
     Ogam.

   - bpo-38086(75): Update importlib.metadata with changes from
     importlib_metadata 0.21(76).

   - bpo-37251(77): Remove ‘__code__’ check in AsyncMock that
     incorrectly evaluated function specs as async objects but failed to
     evaluate classes with ‘__await__’ but no ‘__code__’ attribute
     defined as async objects.

   - bpo-38037(78): Fix reference counters in the *note signal: ea.
     module.

   - bpo-38066(79): Hide internal asyncio.Stream methods: feed_eof(),
     feed_data(), set_exception() and set_transport().

   - bpo-38059(80): inspect.py now uses sys.exit() instead of exit()

   - bpo-38049(81): Added command-line interface for the *note ast: 7.
     module.

   - bpo-37953(82): In *note typing: 122, improved the ‘__hash__’ and
     ‘__eq__’ methods for ‘ForwardReferences’.

   - bpo-38026(83): Fixed *note inspect.getattr_static(): c99. used
     ‘isinstance’ while it should avoid dynamic lookup.

   - bpo-35923(84): Update *note importlib.machinery.BuiltinImporter:
     64f. to use ‘loader._ORIGIN’ instead of a hardcoded value.  Patch
     by Dong-hee Na.

   - bpo-38010(85): In ‘importlib.metadata’ sync with
     ‘importlib_metadata’ 0.20, clarifying behavior of ‘files()’ and
     fixing issue where only one requirement was returned for
     ‘requires()’ on ‘dist-info’ packages.

   - bpo-38006(86): 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.

   - bpo-37995(87): Added the `indent' option to *note ast.dump(): 185.
     which allows it to produce a multiline indented output.

   - bpo-34410(88): Fixed a crash in the ‘tee()’ iterator when re-enter
     it.  RuntimeError is now raised in this case.

   - bpo-37140(89): 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.

   - bpo-37587(90): ‘_json.scanstring’ is now up to 3x faster when there
     are many backslash escaped characters in the JSON string.

   - bpo-37834(91): Prevent shutil.rmtree exception when built on
     non-Windows system without fd system call support, like older
     versions of macOS.

   - bpo-10978(92): Semaphores and BoundedSemaphores can now release
     more than one waiting thread at a time.

   - bpo-37972(93): Subscripts to the *note unittest.mock.call: 10cc.
     objects now receive the same chaining mechanism as any other custom
     attributes, so that the following usage no longer raises a *note
     TypeError: 1fe.:

     call().foo().__getitem__(’bar’)

     Patch by blhsing

   - bpo-37965(94): Fix C compiler warning caused by
     distutils.ccompiler.CCompiler.has_function.

   - bpo-37964(95): Add ‘F_GETPATH’ command to *note fcntl: 7c.

   - bpo-37960(96): ‘repr()’ of buffered and text streams now silences
     only expected exceptions when get the value of "name" and "mode"
     attributes.

   - bpo-37961(97): Add a ‘total_nframe’ field to the traces collected
     by the tracemalloc module.  This field indicates the original
     number of frames before it was truncated.

   - bpo-37951(98): Most features of the subprocess module now work
     again in subinterpreters.  Only `preexec_fn' is restricted in
     subinterpreters.

   - bpo-36205(99): Fix the rusage implementation of time.process_time()
     to correctly report the sum of the system and user CPU time.

   - bpo-37950(100): Fix *note ast.dump(): 185. when call with
     incompletely initialized node.

   - bpo-34679(101): Restores instantiation of Windows IOCP event loops
     from the non-main thread.

   - bpo-36917(102): Add default implementation of the
     ‘ast.NodeVisitor.visit_Constant()’ method which emits a deprecation
     warning and calls corresponding methody ‘visit_Num()’,
     ‘visit_Str()’, etc.

   - bpo-37798(103): Update test_statistics.py to verify that the
     statistics module works well for both C and Python implementations.
     Patch by Dong-hee Na

   - bpo-26589(104): Added a new status code to the http module: 451
     UNAVAILABLE_FOR_LEGAL_REASONS

   - bpo-37915(105): Fix a segmentation fault that appeared when
     comparing instances of ‘datetime.timezone’ and ‘datetime.tzinfo’
     objects.  Patch by Pablo Galindo.

   - bpo-32554(106): Deprecate having random.seed() call hash on
     arbitrary types.

   - bpo-9938(107): Add optional keyword argument ‘exit_on_error’ for
     ‘ArgumentParser’.

   - bpo-37851(108): The *note faulthandler: 7b. module no longer
     allocates its alternative stack at Python startup.  Now the stack
     is only allocated at the first faulthandler usage.

   - bpo-32793(109): Fix a duplicated debug message when *note
     smtplib.SMTP.connect(): 10cd. is called.

   - bpo-37885(110): venv: Don’t generate unset variable warning on
     deactivate.

   - bpo-37868(111): 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.

   - bpo-37811(112): Fix ‘socket’ module’s ‘socket.connect(address)’
     function being unable to establish connection in case of
     interrupted system call.  The problem was observed on all OSes
     which ‘poll(2)’ system call can take only non-negative integers and
     -1 as a timeout value.

   - bpo-37863(113): Optimizations for Fraction.__hash__ suggested by
     Tim Peters.

   - bpo-21131(114): Fix ‘faulthandler.register(chain=True)’ stack.
     faulthandler now allocates a dedicated stack of ‘SIGSTKSZ*2’ bytes,
     instead of just ‘SIGSTKSZ’ bytes.  Calling the previous signal
     handler in faulthandler signal handler uses more than ‘SIGSTKSZ’
     bytes of stack memory on some platforms.

   - bpo-37798(115): Add C fastpath for statistics.NormalDist.inv_cdf()
     Patch by Dong-hee Na

   - bpo-37804(116): Remove the deprecated method
     ‘threading.Thread.isAlive()’.  Patch by Dong-hee Na.

   - bpo-37819(117): Add Fraction.as_integer_ratio() to match the
     corresponding methods in bool, int, float, and decimal.

   - bpo-14465(118): Add an xml.etree.ElementTree.indent() function for
     pretty-printing XML trees.  Contributed by Stefan Behnel.

   - bpo-37810(119): Fix *note difflib: 36. ‘?’ hint in diff output when
     dealing with tabs.  Patch by Anthony Sottile.

   - bpo-37772(120): In ‘zipfile.Path’, when adding implicit dirs,
     ensure that ancestral directories are added and that duplicates are
     excluded.

   - bpo-18578(121): Renamed and documented ‘test.bytecode_helper’ as
     *note test.support.bytecode_helper: 107.  Patch by Joannah
     Nanjekye.

   - bpo-37785(122): Fix xgettext warnings in *note argparse: 5.

   - bpo-34488(123): ‘writelines()’ method of *note io.BytesIO: 88a. is
     now slightly faster when many small lines are passed.  Patch by
     Sergey Fedoseev.

   - bpo-37449(124): *note ensurepip: 78. now uses *note
     importlib.resources.read_binary(): 10ce. to read data instead of
     *note pkgutil.get_data(): 10cf.  Patch by Joannah Nanjekye.

   - bpo-28292(125): 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.

   - bpo-18049(126): 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

   - bpo-37742(127): 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’.

   - bpo-37738(128): Fix the implementation of curses ‘addch(str,
     color_pair)’: pass the color pair to ‘setcchar()’, instead of
     always passing 0 as the color pair.

   - bpo-37723(129): Fix performance regression on regular expression
     parsing with huge character sets.  Patch by Yann Vaginay.

   - bpo-35943(130): The function *note PyImport_GetModule(): 524. now
     ensures any module it returns is fully initialized.  Patch by
     Joannah Nanjekye.

   - bpo-32178(131): Fix IndexError in *note email: 67. package when
     trying to parse invalid address fields starting with ‘:’.

   - bpo-37268(132): The *note parser: c7. module is deprecated and will
     be removed in future versions of Python.

   - bpo-11953(133): Completing WSA* error codes in *note socket: ef.

   - bpo-37685(134): Fixed comparisons of *note datetime.timedelta: 2ca.
     and *note datetime.timezone: ae0.

   - bpo-37697(135): Synchronize ‘importlib.metadata’ with
     importlib_metadata 0.19(136), improving handling of EGG-INFO files
     and fixing a crash when entry point names contained colons.

   - bpo-37695(137): Correct *note curses.unget_wch(): abf. error
     message.  Patch by Anthony Sottile.

   - bpo-37689(138): Add ‘is_relative_to()’ in ‘PurePath’ to determine
     whether or not one path is relative to another.

   - bpo-29553(139): Fixed *note argparse.ArgumentParser.format_usage():
     10d0. for mutually exclusive groups.  Patch by Andrew Nester.

   - bpo-37691(140): Let math.dist() accept coordinates as sequences (or
     iterables) rather than just tuples.

   - bpo-37685(141): Fixed ‘__eq__’, ‘__lt__’ etc implementations in
     some classes.  They now return *note NotImplemented: 202. for
     unsupported type of the other operand.  This allows the other
     operand to play role (for example the equality comparison with
     *note ANY: 10d1. will return ‘True’).

   - bpo-37354(142): Make Activate.ps1 Powershell script static to allow
     for signing it.

   - bpo-37664(143): Update wheels bundled with ensurepip (pip 19.2.3
     and setuptools 41.2.0)

   - bpo-37663(144): Bring consistency to venv shell activation scripts
     by always using __VENV_PROMPT__.

   - bpo-37642(145): Allowed the pure Python implementation of *note
     datetime.timezone: ae0. 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

   - bpo-36161(146): In *note posix: d1, use ‘ttyname_r’ instead of
     ‘ttyname’ for thread safety.

   - bpo-36324(147): Make internal attributes for
     statistics.NormalDist() private.

   - bpo-37555(148): Fix ‘NonCallableMock._call_matcher’ returning tuple
     instead of ‘_Call’ object when ‘self._spec_signature’ exists.
     Patch by Elizabeth Uselton

   - bpo-29446(149): Make ‘from tkinter import *’ import only the
     expected objects.

   - bpo-16970(150): Adding a value error when an invalid value in
     passed to nargs Patch by Robert Leenders

   - bpo-34443(151): Exceptions from *note enum: 79. now use the
     ‘__qualname’ of the enum class in the exception message instead of
     the ‘__name__’.

   - bpo-37491(152): Fix ‘IndexError’ when parsing email headers with
     unexpectedly ending bare-quoted string value.  Patch by Abhilash
     Raj.

   - bpo-37587(153): Make json.loads faster for long strings.  (Patch by
     Marco Paolini)

   - bpo-18378(154): Recognize "UTF-8" as a valid value for LC_CTYPE in
     locale._parse_localename.

   - bpo-37579(155): Return *note NotImplemented: 202. in Python
     implementation of ‘__eq__’ for *note timedelta: 2ca. and *note
     time: 5ec. when the other object being compared is not of the same
     type to match C implementation.  Patch by Karthikeyan Singaravelan.

   - bpo-21478(156): Record calls to parent when autospecced object is
     attached to a mock using ‘unittest.mock.attach_mock()’.  Patch by
     Karthikeyan Singaravelan.

   - bpo-37531(157): "python3 -m test -jN –timeout=TIMEOUT" now kills a
     worker process if it runs longer than `TIMEOUT' seconds.

   - bpo-37482(158): Fix serialization of display name in originator or
     destination address fields with both encoded words and special
     chars.

   - bpo-36993(159): Improve error reporting for corrupt zip files with
     bad zip64 extra data.  Patch by Daniel Hillier.

   - bpo-37502(160): pickle.loads() no longer raises TypeError when the
     buffers argument is set to None

   - bpo-37520(161): Correct behavior for zipfile.Path.parent when the
     path object identifies a subdirectory.

   - bpo-18374(162): Fix the ‘.col_offset’ attribute of nested *note
     ast.BinOp: 10d2. instances which had a too large value in some
     situations.

   - bpo-37424(163): Fixes a possible hang when using a timeout on *note
     subprocess.run(): 4f2. 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.

   - bpo-37421(164): Fix ‘multiprocessing.util.get_temp_dir()’
     finalizer: clear also the ’tempdir’ configuration of the current
     process, so next call to ‘get_temp_dir()’ will create a new
     temporary directory, rather than reusing the removed temporary
     directory.

   - bpo-37481(165): The distutils ‘bdist_wininst’ command is deprecated
     in Python 3.8, use ‘bdist_wheel’ (wheel packages) instead.

   - bpo-37479(166): When ‘Enum.__str__’ is overridden in a derived
     class, the override will be used by ‘Enum.__format__’ regardless of
     whether mixin classes are present.

   - bpo-37440(167): http.client now enables TLS 1.3 post-handshake
     authentication for default context or if a cert_file is passed to
     HTTPSConnection.

   - bpo-37437(168): Update vendorized expat version to 2.2.7.

   - bpo-37428(169): 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.

   - bpo-37420(170): *note os.sched_setaffinity(): b30. now correctly
     handles errors that arise during iteration over its ‘mask’
     argument.  Patch by Brandt Bucher.

   - bpo-37412(171): The *note os.getcwdb(): 3da. function now uses the
     UTF-8 encoding on Windows, rather than the ANSI code page: see PEP
     529(172) for the rationale.  The function is no longer deprecated
     on Windows.

   - bpo-37406(173): The sqlite3 module now raises TypeError, rather
     than ValueError, if operation argument type is not str: execute(),
     executemany() and calling a connection.

   - bpo-29412(174): Fix IndexError in parsing a header value ending
     unexpectedly.  Patch by Abhilash Raj.

   - bpo-36546(175): The `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.

   - bpo-37394(176): Fix a bug that was causing the *note queue: da.
     module to fail if the accelerator module was not available.  Patch
     by Pablo Galindo.

   - bpo-37376(177): *note pprint: d2. now has support for *note
     types.SimpleNamespace: 1d8.  Patch by Carl Bordum Hansen.

   - bpo-26967(178): An *note ArgumentParser: 788. with
     ‘allow_abbrev=False’ no longer disables grouping of short flags,
     such as ‘-vv’, but only disables abbreviation of long flags as
     documented.  Patch by Zac Hatfield-Dodds.

   - bpo-37212(179): *note unittest.mock.call(): 10cc. now preserves the
     order of keyword arguments in repr output.  Patch by Karthikeyan
     Singaravelan.

   - bpo-37372(180): Fix error unpickling datetime.time objects from
     Python 2 with seconds>=24.  Patch by Justin Blanchard.

   - bpo-37345(181): Add formal support for UDPLITE sockets.  Support
     was present before, but it is now easier to detect support with
     ‘hasattr(socket, 'IPPROTO_UDPLITE')’ and there are constants
     defined for each of the values needed: ‘socket.IPPROTO_UDPLITE’,
     ‘UDPLITE_SEND_CSCOV’, and ‘UDPLITE_RECV_CSCOV’.  Patch by Gabe
     Appleton.

   - bpo-37358(182): Optimized ‘functools.partial’ by using vectorcall.

   - bpo-37347(183): *note sqlite3.Connection.create_aggregate(): 10d3,
     *note sqlite3.Connection.create_function(): 10d4, *note
     sqlite3.Connection.set_authorizer(): 10d5, *note
     sqlite3.Connection.set_progress_handler(): 10d6. *note
     sqlite3.Connection.set_trace_callback(): b65. 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.

   - bpo-37163(184): The `obj' argument of *note dataclasses.replace():
     fa8. is positional-only now.

   - bpo-37085(185): Add the optional Linux SocketCAN Broadcast Manager
     constants, used as flags to configure the BCM behaviour, in the
     socket module.  Patch by Karl Ding.

   - bpo-37328(186): ‘HTMLParser.unescape’ is removed.  It was
     undocumented and deprecated since Python 3.4.

   - bpo-37305(187): Add .webmanifest -> application/manifest+json to
     list of recognized file types and content type headers

   - bpo-37320(188): ‘aifc.openfp()’ alias to ‘aifc.open()’,
     ‘sunau.openfp()’ alias to ‘sunau.open()’, and ‘wave.openfp()’ alias
     to ‘wave.open()’ have been removed.  They were deprecated since
     Python 3.7.

   - bpo-37315(189): Deprecated accepting floats with integral value
     (like ‘5.0’) in *note math.factorial(): 1fc.

   - bpo-37312(190): ‘_dummy_thread’ and ‘dummy_threading’ modules have
     been removed.  These modules were deprecated since Python 3.7 which
     requires threading support.

   - bpo-33972(191): Email with single part but content-type set to
     ‘multipart/*’ doesn’t raise AttributeError anymore.

   - bpo-37280(192): Use threadpool for reading from file for sendfile
     fallback mode.

   - bpo-37279(193): Fix asyncio sendfile support when sendfile sends
     extra data in fallback mode.

   - bpo-19865(194): *note ctypes.create_unicode_buffer(): 10d7. now
     also supports non-BMP characters on platforms with 16-bit ‘wchar_t’
     (for example, Windows and AIX).

   - bpo-37266(195): 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.

   - bpo-37210(196): Allow pure Python implementation of *note pickle:
     ca. to work even when the C ‘_pickle’ module is unavailable.

   - bpo-21872(197): Fix *note lzma: ad.: 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.

   - bpo-35922(198): Fix ‘RobotFileParser.crawl_delay()’ and
     ‘RobotFileParser.request_rate()’ to return ‘None’ rather than raise
     *note AttributeError: 4a1. when no relevant rule is defined in the
     robots.txt file.  Patch by Rémi Lapeyre.

   - bpo-35766(199): Change the format of feature_version to be a
     (major, minor) tuple.

   - bpo-36607(200): Eliminate *note RuntimeError: 3dc. raised by *note
     asyncio.all_tasks(): 229. if internal tasks weak set is changed by
     another thread during iteration.

   - bpo-18748(201): ‘_pyio.IOBase’ destructor now does nothing if
     getting the ‘closed’ attribute fails to better mimic ‘_io.IOBase’
     finalizer.

   - bpo-36402(202): 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.

   - bpo-37206(203): Default values which cannot be represented as
     Python objects no longer improperly represented as ‘None’ in
     function signatures.

   - bpo-37111(204): Added ‘encoding’ and ‘errors’ keyword parameters to
     ‘logging.basicConfig’.

   - bpo-12144(205): Ensure cookies with ‘expires’ attribute are handled
     in ‘CookieJar.make_cookies()’.

   - bpo-34886(206): Fix an unintended ValueError from *note
     subprocess.run(): 4f2. when checking for conflicting *note input:
     d33. and ‘stdin’ or ‘capture_output’ and ‘stdout’ or ‘stderr’ args
     when they were explicitly provided but with *note None: 203. values
     within a passed in ‘**kwargs’ dict rather than as passed directly
     by name.  Patch contributed by Rémi Lapeyre.

   - bpo-37173(207): The exception message for ‘inspect.getfile()’ now
     correctly reports the passed class rather than the builtins module.

   - bpo-37178(208): Give math.perm() a one argument form that means the
     same as math.factorial().

   - bpo-37178(209): For math.perm(n, k), let k default to n, giving the
     same result as factorial.

   - bpo-37165(210): Converted _collections._count_elements to use the
     Argument Clinic.

   - bpo-34767(211): Do not always create a *note collections.deque:
     62a. in *note asyncio.Lock: 3ae.

   - bpo-37158(212): Speed-up statistics.fmean() by switching from a
     function to a generator.

   - bpo-34282(213): Remove ‘Enum._convert’ method, deprecated in 3.8.

   - bpo-37150(214): ‘argparse._ActionsContainer.add_argument’ now
     throws error, if someone accidentally pass FileType class object
     instead of instance of FileType as *note type: 6ff. argument

   - bpo-28724(215): The socket module now has the *note
     socket.send_fds(): 1e4. and ‘socket.recv.fds()’ methods.
     Contributed by Joannah Nanjekye, Shinya Okano and Victor Stinner.

   - bpo-35621(216): Support running asyncio subprocesses when execution
     event loop in a thread on UNIX.

   - bpo-36520(217): Lengthy email headers with UTF-8 characters are now
     properly encoded when they are folded.  Patch by Jeffrey Kintscher.

   - bpo-30835(218): 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.

   - bpo-31163(219): pathlib.Path instance’s rename and replace methods
     now return the new Path instance.

   - bpo-25068(220): *note urllib.request.ProxyHandler: 10d8. now
     lowercases the keys of the passed dictionary.

   - bpo-26185(221): Fix *note repr(): 8b9. on empty ‘ZipInfo’ object.
     Patch by Mickaël Schoentgen.

   - bpo-21315(222): 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.

   - bpo-31904(223): Port test_datetime to VxWorks: skip zoneinfo tests
     on VxWorks

   - bpo-35805(224): Add parser for Message-ID header and add it to
     default HeaderRegistry.  This should prevent folding of Message-ID
     using RFC 2048 encoded words.

   - bpo-36871(225): Ensure method signature is used instead of
     constructor signature of a class while asserting mock object
     against method calls.  Patch by Karthikeyan Singaravelan.

   - bpo-35070(226): posix.getgrouplist() now works correctly when the
     user belongs to NGROUPS_MAX supplemental groups.  Patch by Jeffrey
     Kintscher.

   - bpo-31783(227): Fix race condition in ThreadPoolExecutor when
     worker threads are created during interpreter shutdown.

   - bpo-36582(228): Fix ‘UserString.encode()’ to correctly return
     ‘bytes’ rather than a ‘UserString’ instance.

   - bpo-32424(229): Deprecate xml.etree.ElementTree.Element.copy() in
     favor of copy.copy().

     Patch by Gordon P. Hemsley

   - bpo-36564(230): 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

   - bpo-36543(231): Removed methods Element.getchildren(),
     Element.getiterator() and ElementTree.getiterator() and the
     xml.etree.cElementTree module.

   - bpo-36409(232): Remove the old plistlib API deprecated in Python
     3.4

   - bpo-36302(233): distutils sorts source file lists so that Extension
     .so files build more reproducibly by default

   - bpo-36250(234): Ignore ‘ValueError’ from ‘signal’ with
     ‘interaction’ in non-main thread.

   - bpo-36046(235): Added ‘user’, ‘group’ and ‘extra_groups’ parameters
     to the subprocess.Popen constructor.  Patch by Patrick McLean.

   - bpo-32627(236): Fix compile error when ‘_uuid’ headers conflicting
     included.

   - bpo-35800(237): Deprecate ‘smtpd.MailmanProxy’ ready for future
     removal.

   - bpo-35168(238): *note shlex.shlex.punctuation_chars: 10d9. is now a
     read-only property.

   - bpo-8538(239): Add support for boolean actions like ‘--foo’ and
     ‘--no-foo’ to argparse.  Patch contributed by Rémi Lapeyre.

   - bpo-20504(240): Fixes a bug in *note cgi: 15. module when a
     multipart/form-data request has no ‘Content-Length’ header.

   - bpo-25988(241): The abstract base classes in *note collections.abc:
     1e. no longer are exposed in the regular *note collections: 1d.
     module.

   - bpo-11122(242): Distutils won’t check for rpmbuild in specified
     paths only.

   - bpo-34775(243): 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.

   - bpo-34749(244): *note binascii.a2b_base64(): 10da. is now up to 2
     times faster.  Patch by Sergey Fedoseev.

   - bpo-34519(245): Add additional aliases for HP Roman 8.  Patch by
     Michael Osipov.

   - bpo-28009(246): 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.

   - bpo-30618(247): Add *note readlink(): 1d0.  Patch by Girts
     Folkmanis.

   - bpo-32498(248): Made *note urllib.parse.unquote(): 10db. accept
     bytes in addition to strings.  Patch by Stein Karlsen.

   - bpo-33348(249): lib2to3 now recognizes expressions after ‘*’ and
     ‘**’ like in ‘f(*[] or [])’.

   - bpo-32689(250): Update *note shutil.move(): 385. function to allow
     for Path objects to be used as source argument.  Patch by Emily
     Morehouse and Maxwell "5.13b" McKinnon.

   - bpo-32820(251): 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.

   - bpo-27657(252): 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").

   - bpo-4963(253): Fixed non-deterministic behavior related to
     mimetypes extension mapping and module reinitialization.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36589

   (2) https://bugs.python.org/issue38807

   (3) https://bugs.python.org/issue38724

   (4) https://bugs.python.org/issue38786

   (5) https://bugs.python.org/issue38785

   (6) https://bugs.python.org/issue38723

   (7) https://bugs.python.org/issue27805

   (8) https://bugs.python.org/issue38438

   (9) https://bugs.python.org/issue38761

   (10) https://bugs.python.org/issue38716

   (11) https://bugs.python.org/issue38713

   (12) https://bugs.python.org/issue38692

   (13) https://bugs.python.org/issue38692

   (14) https://bugs.python.org/issue38602

   (15) https://bugs.python.org/issue38334

   (16) https://bugs.python.org/issue38312

   (17) https://bugs.python.org/issue38586

   (18) https://bugs.python.org/issue38565

   (19) https://bugs.python.org/issue34679

   (20) https://bugs.python.org/issue31202

   (21) https://bugs.python.org/issue36321

   (22) https://bugs.python.org/issue38521

   (23) https://bugs.python.org/issue38493

   (24) https://bugs.python.org/issue38478

   (25) https://bugs.python.org/issue33604

   (26) https://bugs.python.org/issue38378

   (27) https://bugs.python.org/issue38417

   (28) https://bugs.python.org/issue38449

   (29) https://bugs.python.org/issue38431

   (30) https://bugs.python.org/issue38109

   (31) https://bugs.python.org/issue38422

   (32) https://bugs.python.org/issue38405

   (33) https://bugs.python.org/issue38332

   (34) https://bugs.python.org/issue38371

   (35) https://bugs.python.org/issue38341

   (36) https://bugs.python.org/issue38319

   (37) https://bugs.python.org/issue38242

   (38) https://bugs.python.org/issue13153

   (39) https://bugs.python.org/issue38019

   (40) https://bugs.python.org/issue38163

   (41) https://bugs.python.org/issue38161

   (42) https://bugs.python.org/issue38216

   (43) https://bugs.python.org/issue30458

   (44) https://bugs.python.org/issue28286

   (45) https://bugs.python.org/issue38108

   (46) https://bugs.python.org/issue38265

   (47) https://bugs.python.org/issue38112

   (48) https://bugs.python.org/issue38248

   (49) https://bugs.python.org/issue38237

   (50) https://bugs.python.org/issue34002

   (51) https://bugs.python.org/issue38191

   (52) https://bugs.python.org/issue38155

   (53) https://bugs.python.org/issue38185

   (54) https://bugs.python.org/issue38136

   (55) https://bugs.python.org/issue37828

   (56) https://bugs.python.org/issue38175

   (57) https://bugs.python.org/issue33936

   (58) https://bugs.python.org/issue34706

   (59) https://bugs.python.org/issue38153

   (60) https://bugs.python.org/issue38115

   (61) https://bugs.python.org/issue38148

   (62) https://bugs.python.org/issue38142

   (63) https://bugs.python.org/issue9216

   (64) https://bugs.python.org/issue36991

   (65) https://bugs.python.org/issue38134

   (66) https://bugs.python.org/issue38132

   (67) https://bugs.python.org/issue38008

   (68) https://bugs.python.org/issue34037

   (69) https://bugs.python.org/issue37405

   (70) https://bugs.python.org/issue38121

   (71) https://bugs.python.org/issue38110

   (72) https://bugs.python.org/issue38093

   (73) https://bugs.python.org/issue37488

   (74) https://bugs.python.org/issue35640

   (75) https://bugs.python.org/issue38086

   (76) 
https://gitlab.com/python-devs/importlib_metadata/blob/0.21/importlib_metadata/docs/changelog.rst

   (77) https://bugs.python.org/issue37251

   (78) https://bugs.python.org/issue38037

   (79) https://bugs.python.org/issue38066

   (80) https://bugs.python.org/issue38059

   (81) https://bugs.python.org/issue38049

   (82) https://bugs.python.org/issue37953

   (83) https://bugs.python.org/issue38026

   (84) https://bugs.python.org/issue35923

   (85) https://bugs.python.org/issue38010

   (86) https://bugs.python.org/issue38006

   (87) https://bugs.python.org/issue37995

   (88) https://bugs.python.org/issue34410

   (89) https://bugs.python.org/issue37140

   (90) https://bugs.python.org/issue37587

   (91) https://bugs.python.org/issue37834

   (92) https://bugs.python.org/issue10978

   (93) https://bugs.python.org/issue37972

   (94) https://bugs.python.org/issue37965

   (95) https://bugs.python.org/issue37964

   (96) https://bugs.python.org/issue37960

   (97) https://bugs.python.org/issue37961

   (98) https://bugs.python.org/issue37951

   (99) https://bugs.python.org/issue36205

   (100) https://bugs.python.org/issue37950

   (101) https://bugs.python.org/issue34679

   (102) https://bugs.python.org/issue36917

   (103) https://bugs.python.org/issue37798

   (104) https://bugs.python.org/issue26589

   (105) https://bugs.python.org/issue37915

   (106) https://bugs.python.org/issue32554

   (107) https://bugs.python.org/issue9938

   (108) https://bugs.python.org/issue37851

   (109) https://bugs.python.org/issue32793

   (110) https://bugs.python.org/issue37885

   (111) https://bugs.python.org/issue37868

   (112) https://bugs.python.org/issue37811

   (113) https://bugs.python.org/issue37863

   (114) https://bugs.python.org/issue21131

   (115) https://bugs.python.org/issue37798

   (116) https://bugs.python.org/issue37804

   (117) https://bugs.python.org/issue37819

   (118) https://bugs.python.org/issue14465

   (119) https://bugs.python.org/issue37810

   (120) https://bugs.python.org/issue37772

   (121) https://bugs.python.org/issue18578

   (122) https://bugs.python.org/issue37785

   (123) https://bugs.python.org/issue34488

   (124) https://bugs.python.org/issue37449

   (125) https://bugs.python.org/issue28292

   (126) https://bugs.python.org/issue18049

   (127) https://bugs.python.org/issue37742

   (128) https://bugs.python.org/issue37738

   (129) https://bugs.python.org/issue37723

   (130) https://bugs.python.org/issue35943

   (131) https://bugs.python.org/issue32178

   (132) https://bugs.python.org/issue37268

   (133) https://bugs.python.org/issue11953

   (134) https://bugs.python.org/issue37685

   (135) https://bugs.python.org/issue37697

   (136) 
https://gitlab.com/python-devs/importlib_metadata/-/milestones/20

   (137) https://bugs.python.org/issue37695

   (138) https://bugs.python.org/issue37689

   (139) https://bugs.python.org/issue29553

   (140) https://bugs.python.org/issue37691

   (141) https://bugs.python.org/issue37685

   (142) https://bugs.python.org/issue37354

   (143) https://bugs.python.org/issue37664

   (144) https://bugs.python.org/issue37663

   (145) https://bugs.python.org/issue37642

   (146) https://bugs.python.org/issue36161

   (147) https://bugs.python.org/issue36324

   (148) https://bugs.python.org/issue37555

   (149) https://bugs.python.org/issue29446

   (150) https://bugs.python.org/issue16970

   (151) https://bugs.python.org/issue34443

   (152) https://bugs.python.org/issue37491

   (153) https://bugs.python.org/issue37587

   (154) https://bugs.python.org/issue18378

   (155) https://bugs.python.org/issue37579

   (156) https://bugs.python.org/issue21478

   (157) https://bugs.python.org/issue37531

   (158) https://bugs.python.org/issue37482

   (159) https://bugs.python.org/issue36993

   (160) https://bugs.python.org/issue37502

   (161) https://bugs.python.org/issue37520

   (162) https://bugs.python.org/issue18374

   (163) https://bugs.python.org/issue37424

   (164) https://bugs.python.org/issue37421

   (165) https://bugs.python.org/issue37481

   (166) https://bugs.python.org/issue37479

   (167) https://bugs.python.org/issue37440

   (168) https://bugs.python.org/issue37437

   (169) https://bugs.python.org/issue37428

   (170) https://bugs.python.org/issue37420

   (171) https://bugs.python.org/issue37412

   (172) https://www.python.org/dev/peps/pep-0529

   (173) https://bugs.python.org/issue37406

   (174) https://bugs.python.org/issue29412

   (175) https://bugs.python.org/issue36546

   (176) https://bugs.python.org/issue37394

   (177) https://bugs.python.org/issue37376

   (178) https://bugs.python.org/issue26967

   (179) https://bugs.python.org/issue37212

   (180) https://bugs.python.org/issue37372

   (181) https://bugs.python.org/issue37345

   (182) https://bugs.python.org/issue37358

   (183) https://bugs.python.org/issue37347

   (184) https://bugs.python.org/issue37163

   (185) https://bugs.python.org/issue37085

   (186) https://bugs.python.org/issue37328

   (187) https://bugs.python.org/issue37305

   (188) https://bugs.python.org/issue37320

   (189) https://bugs.python.org/issue37315

   (190) https://bugs.python.org/issue37312

   (191) https://bugs.python.org/issue33972

   (192) https://bugs.python.org/issue37280

   (193) https://bugs.python.org/issue37279

   (194) https://bugs.python.org/issue19865

   (195) https://bugs.python.org/issue37266

   (196) https://bugs.python.org/issue37210

   (197) https://bugs.python.org/issue21872

   (198) https://bugs.python.org/issue35922

   (199) https://bugs.python.org/issue35766

   (200) https://bugs.python.org/issue36607

   (201) https://bugs.python.org/issue18748

   (202) https://bugs.python.org/issue36402

   (203) https://bugs.python.org/issue37206

   (204) https://bugs.python.org/issue37111

   (205) https://bugs.python.org/issue12144

   (206) https://bugs.python.org/issue34886

   (207) https://bugs.python.org/issue37173

   (208) https://bugs.python.org/issue37178

   (209) https://bugs.python.org/issue37178

   (210) https://bugs.python.org/issue37165

   (211) https://bugs.python.org/issue34767

   (212) https://bugs.python.org/issue37158

   (213) https://bugs.python.org/issue34282

   (214) https://bugs.python.org/issue37150

   (215) https://bugs.python.org/issue28724

   (216) https://bugs.python.org/issue35621

   (217) https://bugs.python.org/issue36520

   (218) https://bugs.python.org/issue30835

   (219) https://bugs.python.org/issue31163

   (220) https://bugs.python.org/issue25068

   (221) https://bugs.python.org/issue26185

   (222) https://bugs.python.org/issue21315

   (223) https://bugs.python.org/issue31904

   (224) https://bugs.python.org/issue35805

   (225) https://bugs.python.org/issue36871

   (226) https://bugs.python.org/issue35070

   (227) https://bugs.python.org/issue31783

   (228) https://bugs.python.org/issue36582

   (229) https://bugs.python.org/issue32424

   (230) https://bugs.python.org/issue36564

   (231) https://bugs.python.org/issue36543

   (232) https://bugs.python.org/issue36409

   (233) https://bugs.python.org/issue36302

   (234) https://bugs.python.org/issue36250

   (235) https://bugs.python.org/issue36046

   (236) https://bugs.python.org/issue32627

   (237) https://bugs.python.org/issue35800

   (238) https://bugs.python.org/issue35168

   (239) https://bugs.python.org/issue8538

   (240) https://bugs.python.org/issue20504

   (241) https://bugs.python.org/issue25988

   (242) https://bugs.python.org/issue11122

   (243) https://bugs.python.org/issue34775

   (244) https://bugs.python.org/issue34749

   (245) https://bugs.python.org/issue34519

   (246) https://bugs.python.org/issue28009

   (247) https://bugs.python.org/issue30618

   (248) https://bugs.python.org/issue32498

   (249) https://bugs.python.org/issue33348

   (250) https://bugs.python.org/issue32689

   (251) https://bugs.python.org/issue32820

   (252) https://bugs.python.org/issue27657

   (253) https://bugs.python.org/issue4963


File: python.info,  Node: 文档<20>,  Next: 测试<19>,  Prev: 库<25>,  Up: Python 3 9 0 alpha 1

1.19.26.4 文档
..............

   - bpo-21767(1): Explicitly mention abc support in
     functools.singledispatch

   - bpo-38816(2): Provides more details about the interaction between
     ‘fork()’ and CPython’s runtime, focusing just on the C-API. This
     includes cautions about where ‘fork()’ should and shouldn’t be
     called.

   - bpo-38351(3): Modernize *note email: 67. examples from %-formatting
     to f-strings.

   - bpo-38778(4): Document the fact that *note RuntimeError: 3dc. is
     raised if *note os.fork(): a42. is called in a subinterpreter.

   - bpo-38592(5): Add Brazilian Portuguese to the language switcher at
     Python Documentation website.

   - bpo-38294(6): Add list of no-longer-escaped chars to re.escape
     documentation

   - bpo-38053(7): Modernized the plistlib documentation

   - bpo-26868(8): Fix example usage of *note PyModule_AddObject():
     10dd. to properly handle errors.

   - bpo-36797(9): Fix a dead link in the distutils API Reference.

   - bpo-37977(10): Warn more strongly and clearly about pickle
     insecurity

   - bpo-37979(11): Added a link to dateutil.parser.isoparse in the
     datetime.fromisoformat documentation.  Patch by Paul Ganssle

   - bpo-12707(12): 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

   - bpo-37937(13): Mention ‘frame.f_trace’ in *note sys.settrace():
     f00. docs.

   - bpo-37878(14): Make *note PyThreadState_DeleteCurrent(): 10de.
     Internal.

   - bpo-37759(15): Beginning edits to Whatsnew 3.8

   - bpo-37726(16): Stop recommending getopt in the tutorial for command
     line argument parsing and promote argparse.

   - bpo-32910(17): Remove implementation-specific behaviour of how
     venv’s Deactivate works.

   - bpo-37256(18): Fix wording of arguments for ‘Request’ in *note
     urllib.request: 129.

   - bpo-37284(19): Add a brief note to indicate that any new
     ‘sys.implementation’ required attributes must go through the PEP
     process.

   - bpo-30088(20): Documented that *note mailbox.Maildir: d70.
     constructor doesn’t attempt to verify the maildir folder layout
     correctness.  Patch by Sviatoslav Sydorenko.

   - bpo-37521(21): Fix *note importlib: 9a. 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.

   - bpo-37456(22): Slash (’/’) is now part of syntax.

   - bpo-37487(23): Fix PyList_GetItem index description to include 0.

   - bpo-37149(24): Replace the dead link to the Tkinter 8.5 reference
     by John Shipman, New Mexico Tech, with a link to the archive.org
     copy.

   - bpo-37478(25): Added possible exceptions to the description of
     os.chdir().

   - bpo-34903(26): Documented that in *note
     datetime.datetime.strptime(): f91, the leading zero in some
     two-digit formats is optional.  Patch by Mike Gleen.

   - bpo-36260(27): Add decompression pitfalls to zipfile module
     documentation.

   - bpo-37004(28): 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.

   - bpo-36960(29): Restructured the *note datetime: 30. docs in the
     interest of making them more user-friendly and improving
     readability.  Patch by Brad Solomon.

   - bpo-36487(30): Make C-API docs clear about what the "main"
     interpreter is.

   - bpo-23460(31): The documentation for decimal string formatting
     using the ‘:g’ specifier has been updated to reflect the correct
     exponential notation cutoff point.  Original patch contributed by
     Tuomas Suutari.

   - bpo-35803(32): Document and test that ‘tempfile’ functions may
     accept a *note path-like object: 472. for the ‘dir’ argument.
     Patch by Anthony Sottile.

   - bpo-33944(33): Added a note about the intended use of code in .pth
     files.

   - bpo-34293(34): Fix the Doc/Makefile regarding PAPER environment
     variable and PDF builds

   - bpo-25237(35): Add documentation for tkinter modules

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21767

   (2) https://bugs.python.org/issue38816

   (3) https://bugs.python.org/issue38351

   (4) https://bugs.python.org/issue38778

   (5) https://bugs.python.org/issue38592

   (6) https://bugs.python.org/issue38294

   (7) https://bugs.python.org/issue38053

   (8) https://bugs.python.org/issue26868

   (9) https://bugs.python.org/issue36797

   (10) https://bugs.python.org/issue37977

   (11) https://bugs.python.org/issue37979

   (12) https://bugs.python.org/issue12707

   (13) https://bugs.python.org/issue37937

   (14) https://bugs.python.org/issue37878

   (15) https://bugs.python.org/issue37759

   (16) https://bugs.python.org/issue37726

   (17) https://bugs.python.org/issue32910

   (18) https://bugs.python.org/issue37256

   (19) https://bugs.python.org/issue37284

   (20) https://bugs.python.org/issue30088

   (21) https://bugs.python.org/issue37521

   (22) https://bugs.python.org/issue37456

   (23) https://bugs.python.org/issue37487

   (24) https://bugs.python.org/issue37149

   (25) https://bugs.python.org/issue37478

   (26) https://bugs.python.org/issue34903

   (27) https://bugs.python.org/issue36260

   (28) https://bugs.python.org/issue37004

   (29) https://bugs.python.org/issue36960

   (30) https://bugs.python.org/issue36487

   (31) https://bugs.python.org/issue23460

   (32) https://bugs.python.org/issue35803

   (33) https://bugs.python.org/issue33944

   (34) https://bugs.python.org/issue34293

   (35) https://bugs.python.org/issue25237


File: python.info,  Node: 测试<19>,  Next: 构建<19>,  Prev: 文档<20>,  Up: Python 3 9 0 alpha 1

1.19.26.5 测试
..............

   - bpo-38614(1): Fix test_communicate() of
     test_asyncio.test_subprocess: use ‘support.LONG_TIMEOUT’ (5
     minutes), instead of just 1 minute.

   - bpo-38614(2): Add timeout constants to *note test.support: 106.:
     *note LOOPBACK_TIMEOUT: 10b1, *note INTERNET_TIMEOUT: 10b2, *note
     SHORT_TIMEOUT: f94. and *note LONG_TIMEOUT: 10b3.

   - bpo-38502(3): test.regrtest now uses process groups in the
     multiprocessing mode (-jN command line option) if process groups
     are available: if *note os.setsid(): 10e0. and *note os.killpg():
     10e1. functions are available.

   - bpo-35998(4): 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.

   - bpo-38470(5): Fix ‘test_compileall.test_compile_dir_maxlevels()’ on
     Windows without long path support: only create 3 subdirectories
     instead of between 20 and 100 subdirectories.

   - bpo-37531(6): On timeout, regrtest no longer attempts to call
     ‘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.

   - bpo-38239(7): Fix test_gdb for Link Time Optimization (LTO) builds.

   - bpo-38275(8): 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.

   - bpo-38271(9): 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.

   - bpo-38270(10): 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.

   - bpo-37123(11): 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.

   - bpo-38212(12): Multiprocessing tests: increase
     test_queue_feeder_donot_stop_onexc() timeout from 1 to 60 seconds.

   - bpo-38117(13): 使用OpenSSL 1.1.1d进行测试

   - bpo-38018(14): Increase code coverage for
     multiprocessing.shared_memory.

   - bpo-37805(15): Add tests for json.dump(..., skipkeys=True).  Patch
     by Dong-hee Na.

   - bpo-37531(16): 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().

   - bpo-37876(17): Add tests for ROT-13 codec.

   - bpo-36833(18): Added tests for PyDateTime_xxx_GET_xxx() macros of
     the C API of the *note datetime: 30. module.  Patch by Joannah
     Nanjekye.

   - bpo-37558(19): Fix
     test_shared_memory_cleaned_after_process_termination name handling

   - bpo-37526(20): Add *note test.support.catch_threading_exception():
     10e2.: context manager catching *note threading.Thread: 21a.
     exception using *note threading.excepthook(): 35e.

   - bpo-37421(21): test_concurrent_futures now explicitly stops the
     ForkServer instance if it’s running.

   - bpo-37421(22): 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.

   - bpo-37421(23): 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.

   - bpo-37421(24): test_concurrent_futures now cleans up
     multiprocessing to remove immediately temporary directories created
     by multiprocessing.util.get_temp_dir().

   - bpo-37421(25): test_winconsoleio doesn’t leak a temporary file
     anymore: use tempfile.TemporaryFile() to remove it when the test
     completes.

   - bpo-37421(26): multiprocessing tests now explicitly call
     ‘_run_finalizers()’ to immediately remove temporary directories
     created by tests.

   - bpo-37421(27): urllib.request tests now call *note urlcleanup():
     10e3. to remove temporary files created by ‘urlretrieve()’ tests
     and to clear the ‘_opener’ global variable set by ‘urlopen()’ and
     functions calling indirectly ‘urlopen()’.

   - bpo-37472(28): Remove ‘Lib/test/outstanding_bugs.py’.

   - bpo-37199(29): Fix test failures when IPv6 is unavailable or
     disabled.

   - bpo-19696(30): Replace deprecated method "random.choose" with
     "random.choice" in "test_pkg_import.py".

   - bpo-37335(31): Remove no longer necessary code from c locale
     coercion tests

   - bpo-37421(32): Fix test_shutil to no longer leak temporary files.

   - bpo-37411(33): Fix test_wsgiref.testEnviron() to no longer depend
     on the environment variables (don’t fail if "X" variable is set).

   - bpo-37400(34): Fix test_os.test_chown(): use os.getgroups() rather
     than grp.getgrall() to get groups.  Rename also the test to
     test_chown_gid().

   - bpo-37359(35): Add –cleanup option to python3 -m test to remove
     ‘test_python_*’ directories of previous failed jobs.  Add "make
     cleantest" to run ‘python3 -m test --cleanup’.

   - bpo-37362(36): 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.

   - bpo-35998(37): Avoid TimeoutError in test_asyncio:
     test_start_tls_server_1()

   - bpo-37278(38): Fix test_asyncio ProactorLoopCtrlC: join the thread
     to prevent leaking a running thread and leaking a reference.

   - bpo-37261(39): Fix *note test.support.catch_unraisable_exception():
     10e4.: its __exit__() method now ignores unraisable exception
     raised when clearing its ‘unraisable’ attribute.

   - bpo-37069(40): regrtest now uses *note sys.unraisablehook(): 35a.
     to mark a test as "environment altered" (ENV_CHANGED) if it emits
     an "unraisable exception".  Moreover, regrtest logs a warning in
     this case.

     Use ‘python3 -m test --fail-env-changed’ to catch unraisable
     exceptions in tests.

   - bpo-37252(41): Fix assertions in ‘test_close’ and
     ‘test_events_mask_overflow’ devpoll tests.

   - bpo-37169(42): Rewrite ‘_PyObject_IsFreed()’ unit tests.

   - bpo-37153(43): ‘test_venv.test_multiprocessing()’ now explicitly
     calls ‘pool.terminate()’ to wait until the pool completes.

   - bpo-34001(44): Make test_ssl pass with LibreSSL. LibreSSL handles
     minimum and maximum TLS version differently than OpenSSL.

   - bpo-36919(45): Make ‘test_source_encoding.test_issue2301’
     implementation independent.  The test will work now for both
     CPython and IronPython.

   - bpo-30202(46): Update ‘test.test_importlib.test_abc’ to test
     ‘find_spec()’.

   - bpo-28009(47): 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

   - bpo-34596(48): Fallback to a default reason when *note
     unittest.skip(): 10e5. is uncalled.  Patch by Naitree Zhu.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38614

   (2) https://bugs.python.org/issue38614

   (3) https://bugs.python.org/issue38502

   (4) https://bugs.python.org/issue35998

   (5) https://bugs.python.org/issue38470

   (6) https://bugs.python.org/issue37531

   (7) https://bugs.python.org/issue38239

   (8) https://bugs.python.org/issue38275

   (9) https://bugs.python.org/issue38271

   (10) https://bugs.python.org/issue38270

   (11) https://bugs.python.org/issue37123

   (12) https://bugs.python.org/issue38212

   (13) https://bugs.python.org/issue38117

   (14) https://bugs.python.org/issue38018

   (15) https://bugs.python.org/issue37805

   (16) https://bugs.python.org/issue37531

   (17) https://bugs.python.org/issue37876

   (18) https://bugs.python.org/issue36833

   (19) https://bugs.python.org/issue37558

   (20) https://bugs.python.org/issue37526

   (21) https://bugs.python.org/issue37421

   (22) https://bugs.python.org/issue37421

   (23) https://bugs.python.org/issue37421

   (24) https://bugs.python.org/issue37421

   (25) https://bugs.python.org/issue37421

   (26) https://bugs.python.org/issue37421

   (27) https://bugs.python.org/issue37421

   (28) https://bugs.python.org/issue37472

   (29) https://bugs.python.org/issue37199

   (30) https://bugs.python.org/issue19696

   (31) https://bugs.python.org/issue37335

   (32) https://bugs.python.org/issue37421

   (33) https://bugs.python.org/issue37411

   (34) https://bugs.python.org/issue37400

   (35) https://bugs.python.org/issue37359

   (36) https://bugs.python.org/issue37362

   (37) https://bugs.python.org/issue35998

   (38) https://bugs.python.org/issue37278

   (39) https://bugs.python.org/issue37261

   (40) https://bugs.python.org/issue37069

   (41) https://bugs.python.org/issue37252

   (42) https://bugs.python.org/issue37169

   (43) https://bugs.python.org/issue37153

   (44) https://bugs.python.org/issue34001

   (45) https://bugs.python.org/issue36919

   (46) https://bugs.python.org/issue30202

   (47) https://bugs.python.org/issue28009

   (48) https://bugs.python.org/issue34596


File: python.info,  Node: 构建<19>,  Next: Windows<19>,  Prev: 测试<19>,  Up: Python 3 9 0 alpha 1

1.19.26.6 构建
..............

   - bpo-38809(1): On Windows, build scripts will now recognize and use
     python.exe from an active virtual env.

   - bpo-38684(2): Fix _hashlib build when Blake2 is disabled, but
     OpenSSL supports it.

   - bpo-38468(3): Misc/python-config.in now uses ‘getvar()’ for all
     still existing *note sysconfig.get_config_var(): a45. calls.  Patch
     by Joannah Nanjekye.

   - bpo-37415(4): Fix stdatomic.h header check for ICC compiler: the
     ICC implementation lacks atomic_uintptr_t type which is needed by
     Python.

   - bpo-38301(5): In Solaris family, we must be sure to use
     ‘-D_REENTRANT’.  Patch by Jesús Cea Avión.

   - bpo-36002(6): Locate ‘llvm-profdata’ and ‘llvm-ar’ binaries using
     ‘AC_PATH_TOOL’ rather than ‘AC_PATH_TARGET_TOOL’.

   - bpo-37936(7): The ‘.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.

   - bpo-37760(8): The ‘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 *note
     str: 205. and by the *note unicodedata: 123. module, now handles
     each character’s data as a ‘dataclass’ with named attributes,
     rather than a length-18 list of different fields.

   - bpo-37936(9): The ‘.gitignore’ file no longer applies to any files
     that are in fact tracked in the Git repository.  Patch by Greg
     Price.

   - bpo-37725(10): 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".

   - bpo-37707(11): 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.

   - bpo-36044(12): 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.

   - bpo-37468(13): ‘make install’ no longer installs ‘wininst-*.exe’
     files used by distutils bdist_wininst: bdist_wininst only works on
     Windows.

   - bpo-37189(14): Many ‘PyRun_XXX()’ functions like *note
     PyRun_String(): 10e7. were no longer exported in ‘libpython38.dll’
     by mistake.  Export them again to fix the ABI compatibility.

   - bpo-25361(15): Enables use of SSE2 instructions in Windows 32-bit
     build.

   - bpo-36210(16): 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

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38809

   (2) https://bugs.python.org/issue38684

   (3) https://bugs.python.org/issue38468

   (4) https://bugs.python.org/issue37415

   (5) https://bugs.python.org/issue38301

   (6) https://bugs.python.org/issue36002

   (7) https://bugs.python.org/issue37936

   (8) https://bugs.python.org/issue37760

   (9) https://bugs.python.org/issue37936

   (10) https://bugs.python.org/issue37725

   (11) https://bugs.python.org/issue37707

   (12) https://bugs.python.org/issue36044

   (13) https://bugs.python.org/issue37468

   (14) https://bugs.python.org/issue37189

   (15) https://bugs.python.org/issue25361

   (16) https://bugs.python.org/issue36210


File: python.info,  Node: Windows<19>,  Next: macOS<17>,  Prev: 构建<19>,  Up: Python 3 9 0 alpha 1

1.19.26.7 Windows
.................

   - bpo-38589(1): Fixes HTML Help shortcut when Windows is not
     installed to C drive

   - bpo-38453(2): Ensure ntpath.realpath() correctly resolves relative
     paths.

   - bpo-38519(3): Restores the internal C headers that were missing
     from the nuget.org and Microsoft Store packages.

   - bpo-38492(4): 删除 pythonw.exe 依赖的 Microsoft C++ 执行库。

   - bpo-38344(5): Fix error message in activate.bat

   - bpo-38359(6): Ensures ‘pyw.exe’ launcher reads correct registry
     key.

   - bpo-38355(7): Fixes ‘ntpath.realpath’ failing on ‘sys.executable’.

   - bpo-38117(8): 将绑定的OpenSSL更新到1.1.1d

   - bpo-38092(9): Reduce overhead when using multiprocessing in a
     Windows virtual environment.

   - bpo-38133(10): Allow py.exe launcher to locate installations from
     the Microsoft Store and improve display of active virtual
     environments.

   - bpo-38114(11): The ‘pip.ini’ is no longer included in the Nuget
     package.

   - bpo-32592(12): Set Windows 8 as the minimum required version for
     API support

   - bpo-36634(13): *note os.cpu_count(): 96a. now returns active
     processors rather than maximum processors.

   - bpo-36634(14): venv activate.bat now works when the existing
     variables contain double quote characters.

   - bpo-38081(15): Prevent error calling *note os.path.realpath(): 32d.
     on ‘'NUL'’.

   - bpo-38087(16): Fix case sensitivity in test_pathlib and
     test_ntpath.

   - bpo-38088(17): Fixes distutils not finding vcruntime140.dll with
     only the v142 toolset installed.

   - bpo-37283(18): Ensure command-line and unattend.xml setting
     override previously detected states in Windows installer.

   - bpo-38030(19): Fixes *note os.stat(): 321. failing for block
     devices on Windows

   - bpo-38020(20): Fixes potential crash when calling *note
     os.readlink(): 1d1. (or indirectly through *note realpath(): 32d.)
     on a file that is not a supported link.

   - bpo-37705(21): Improve the implementation of ‘winerror_to_errno()’.

   - bpo-37549(22): *note os.dup(): 10e9. no longer fails for standard
     streams on Windows 7.

   - bpo-1311(23): The ‘nul’ file on Windows now returns True from *note
     exists(): 325. and a valid result from *note os.stat(): 321. with
     ‘S_IFCHR’ set.

   - bpo-9949(24): Enable support for following symlinks in
     ‘os.realpath()’.

   - bpo-37834(25): Treat all name surrogate reparse points on Windows
     in *note os.lstat(): 322. and other reparse points as regular files
     in *note os.stat(): 321.

   - bpo-36266(26): Add the module name in the formatted error message
     when DLL load fail happens during module import in
     ‘_PyImport_FindSharedFuncptrWindows()’.  Patch by Srinivas
     Nyayapati.

   - bpo-25172(27): Trying to import the *note crypt: 28. module on
     Windows will result in an *note ImportError: 16c. with a message
     explaining that the module isn’t supported on Windows.  On other
     platforms, if the underlying ‘_crypt’ module is not available, the
     ImportError will include a message explaining the problem.

   - bpo-37778(28): Fixes the icons used for file associations to the
     Microsoft Store package.

   - bpo-37734(29): Fix use of registry values to launch Python from
     Microsoft Store app.

   - bpo-37702(30): Fix memory leak on Windows in creating an SSLContext
     object or running urllib.request.urlopen(’‘https://’...’).

   - bpo-37672(31): Switch Windows Store package’s pip to use bundled
     ‘pip.ini’ instead of ‘PIP_USER’ variable.

   - bpo-10945(32): 正式取消对在非Windows系统上创建 bdist_wininst 安装程
     序的支持。

   - bpo-37445(33): Include the ‘FORMAT_MESSAGE_IGNORE_INSERTS’ flag in
     ‘FormatMessageW()’ calls.

   - bpo-37369(34): Fixes path for *note sys.executable: 39d. when
     running from the Microsoft Store.

   - bpo-37380(35): Don’t collect unfinished processes with
     ‘subprocess._active’ on Windows to cleanup later.  Patch by Ruslan
     Kuprieiev.

   - bpo-37351(36): Removes libpython38.a from standard Windows
     distribution.

   - bpo-35360(37): 更新 Windows 构建以使用 SQLite 3.28.0.

   - bpo-37267(38): On Windows, *note os.dup(): 10e9. no longer creates
     an inheritable fd when handling a character file.

   - bpo-36779(39): Ensure ‘time.tzname’ is correct on Windows when the
     active code page is set to CP_UTF7 or CP_UTF8.

   - bpo-32587(40): Make *note winreg.REG_MULTI_SZ: 10ea. support
     zero-length strings.

   - bpo-28269(41): Replace use of ‘strcasecmp()’ for the system
     function ‘_stricmp()’.  Patch by Minmin Gong.

   - bpo-36590(42): Add native Bluetooth RFCOMM support to socket
     module.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38589

   (2) https://bugs.python.org/issue38453

   (3) https://bugs.python.org/issue38519

   (4) https://bugs.python.org/issue38492

   (5) https://bugs.python.org/issue38344

   (6) https://bugs.python.org/issue38359

   (7) https://bugs.python.org/issue38355

   (8) https://bugs.python.org/issue38117

   (9) https://bugs.python.org/issue38092

   (10) https://bugs.python.org/issue38133

   (11) https://bugs.python.org/issue38114

   (12) https://bugs.python.org/issue32592

   (13) https://bugs.python.org/issue36634

   (14) https://bugs.python.org/issue36634

   (15) https://bugs.python.org/issue38081

   (16) https://bugs.python.org/issue38087

   (17) https://bugs.python.org/issue38088

   (18) https://bugs.python.org/issue37283

   (19) https://bugs.python.org/issue38030

   (20) https://bugs.python.org/issue38020

   (21) https://bugs.python.org/issue37705

   (22) https://bugs.python.org/issue37549

   (23) https://bugs.python.org/issue1311

   (24) https://bugs.python.org/issue9949

   (25) https://bugs.python.org/issue37834

   (26) https://bugs.python.org/issue36266

   (27) https://bugs.python.org/issue25172

   (28) https://bugs.python.org/issue37778

   (29) https://bugs.python.org/issue37734

   (30) https://bugs.python.org/issue37702

   (31) https://bugs.python.org/issue37672

   (32) https://bugs.python.org/issue10945

   (33) https://bugs.python.org/issue37445

   (34) https://bugs.python.org/issue37369

   (35) https://bugs.python.org/issue37380

   (36) https://bugs.python.org/issue37351

   (37) https://bugs.python.org/issue35360

   (38) https://bugs.python.org/issue37267

   (39) https://bugs.python.org/issue36779

   (40) https://bugs.python.org/issue32587

   (41) https://bugs.python.org/issue28269

   (42) https://bugs.python.org/issue36590


File: python.info,  Node: macOS<17>,  Next: IDLE<19>,  Prev: Windows<19>,  Up: Python 3 9 0 alpha 1

1.19.26.8 macOS
...............

   - bpo-38117(1): 在MacOS安装程序中将OpenSSL更新为1.1.1d。

   - bpo-38089(2): Move Azure Pipelines to latest VM versions and make
     macOS tests optional

   - bpo-18049(3): 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.

   - bpo-34602(4): 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.

   - bpo-35360(5): 更新macOS安装程序以使用SQLite 3.28.0.

   - bpo-34631(6): 在MacOS安装程序中将OpenSSL更新为1.1.1c。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38117

   (2) https://bugs.python.org/issue38089

   (3) https://bugs.python.org/issue18049

   (4) https://bugs.python.org/issue34602

   (5) https://bugs.python.org/issue35360

   (6) https://bugs.python.org/issue34631


File: python.info,  Node: IDLE<19>,  Next: 工具/示例<7>,  Prev: macOS<17>,  Up: Python 3 9 0 alpha 1

1.19.26.9 IDLE
..............

   - bpo-26353(1): Stop adding newline when saving an IDLE shell window.

   - bpo-4630(2): 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.

   - bpo-38598(3): Do not try to compile IDLE shell or output windows

   - bpo-36698(4): 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 ‘errors’ field to the
     standard streams.

   - bpo-35379(5): 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.

   - bpo-38183(6): 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.

   - bpo-38077(7): 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.

   - bpo-38041(8): 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.

   - bpo-35771(9): To avoid occasional spurious test_idle failures on
     slower machines, increase the ‘hover_delay’ in test_tooltip.

   - bpo-37824(10): Properly handle user input warnings in IDLE shell.
     Cease turning SyntaxWarnings into SyntaxErrors.

   - bpo-37929(11): IDLE Settings dialog now closes properly when there
     is no shell window.

   - bpo-37902(12): Add mousewheel scrolling for IDLE module, path, and
     stack browsers.  Patch by George Zhang.

   - bpo-37849(13): Fixed completions list appearing too high or low
     when shown above the current line.

   - bpo-36419(14): Refactor IDLE autocomplete and improve testing.

   - bpo-37748(15): Reorder the Run menu.  Put the most common choice,
     Run Module, at the top.

   - bpo-37692(16): Improve highlight config sample with example shell
     interaction and better labels for shell elements.

   - bpo-37628(17): Settings dialog no longer expands with font size.

   - bpo-37627(18): Initialize the Customize Run dialog with the command
     line arguments most recently entered before.  The user can
     optionally edit before submitting them.

   - bpo-33610(19): Fix code context not showing the correct context
     when first toggled on.

   - bpo-37530(20): Optimize code context to reduce unneeded background
     activity.  Font and highlight changes now occur along with text
     changes instead of after a random delay.

   - bpo-27452(21): Cleanup ‘config.py’ by inlining ‘RemoveFile’ and
     simplifying the handling of ‘file’ in ‘CreateConfigHandlers’.

   - bpo-37325(22): Fix tab focus traversal order for help source and
     custom run dialogs.

   - bpo-37321(23): Both subprocess connection error messages now refer
     to the ’Startup failure’ section of the IDLE doc.

   - bpo-17535(24): Add optional line numbers for IDLE editor windows.
     Windows open without line numbers unless set otherwise in the
     General tab of the configuration dialog.

   - bpo-26806(25): 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.

   - bpo-37177(26): Properly ’attach’ search dialogs to their main
     window so that they behave like other dialogs and do not get hidden
     behind their main window.

   - bpo-37039(27): 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.

   - bpo-35763(28): Make calltip reminder about ’/’ meaning
     positional-only less obtrusive by only adding it when there is room
     on the first line.

   - bpo-5680(29): 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.

   - bpo-36390(30): Gather Format menu functions into format.py.
     Combine paragraph.py, rstrip.py, and format methods from editor.py.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26353

   (2) https://bugs.python.org/issue4630

   (3) https://bugs.python.org/issue38598

   (4) https://bugs.python.org/issue36698

   (5) https://bugs.python.org/issue35379

   (6) https://bugs.python.org/issue38183

   (7) https://bugs.python.org/issue38077

   (8) https://bugs.python.org/issue38041

   (9) https://bugs.python.org/issue35771

   (10) https://bugs.python.org/issue37824

   (11) https://bugs.python.org/issue37929

   (12) https://bugs.python.org/issue37902

   (13) https://bugs.python.org/issue37849

   (14) https://bugs.python.org/issue36419

   (15) https://bugs.python.org/issue37748

   (16) https://bugs.python.org/issue37692

   (17) https://bugs.python.org/issue37628

   (18) https://bugs.python.org/issue37627

   (19) https://bugs.python.org/issue33610

   (20) https://bugs.python.org/issue37530

   (21) https://bugs.python.org/issue27452

   (22) https://bugs.python.org/issue37325

   (23) https://bugs.python.org/issue37321

   (24) https://bugs.python.org/issue17535

   (25) https://bugs.python.org/issue26806

   (26) https://bugs.python.org/issue37177

   (27) https://bugs.python.org/issue37039

   (28) https://bugs.python.org/issue35763

   (29) https://bugs.python.org/issue5680

   (30) https://bugs.python.org/issue36390


File: python.info,  Node: 工具/示例<7>,  Next: C API<16>,  Prev: IDLE<19>,  Up: Python 3 9 0 alpha 1

1.19.26.10 工具/示例
....................

   - bpo-38118(1): Update Valgrind suppression file to ignore a false
     alarm in *note PyUnicode_Decode(): 10ee. when using GCC builtin
     strcmp().

   - bpo-38347(2): pathfix.py: Assume all files that end on ’.py’ are
     Python scripts when working recursively.

   - bpo-37803(3): pdb’s ‘--help’ and ‘--version’ long options now work.

   - bpo-37942(4): Improve ArgumentClinic converter for floats.

   - bpo-37704(5): Remove ‘Tools/scripts/h2py.py’: use cffi to access a
     C API in Python.

   - bpo-37675(6): 2to3 now works when run from a zipped standard
     library.

   - bpo-37034(7): Argument Clinic now uses the argument name on errors
     with keyword-only argument instead of their position.  Patch
     contributed by Rémi Lapeyre.

   - bpo-37064(8): Add option -k to pathscript.py script: preserve
     shebang flags.  Add option -a to pathscript.py script: add flags.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue38118

   (2) https://bugs.python.org/issue38347

   (3) https://bugs.python.org/issue37803

   (4) https://bugs.python.org/issue37942

   (5) https://bugs.python.org/issue37704

   (6) https://bugs.python.org/issue37675

   (7) https://bugs.python.org/issue37034

   (8) https://bugs.python.org/issue37064


File: python.info,  Node: C API<16>,  Prev: 工具/示例<7>,  Up: Python 3 9 0 alpha 1

1.19.26.11 C API
................

   - bpo-37633(1): Re-export some function compatibility wrappers for
     macros in ‘pythonrun.h’.

   - bpo-38644(2): Provide *note Py_EnterRecursiveCall(): 251. and *note
     Py_LeaveRecursiveCall(): 252. 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
     ‘PyThreadState.recursion_depth’ field.  Remove
     ‘_Py_CheckRecursionLimit’ from the stable ABI.

   - bpo-38650(3): The global variable *note
     PyStructSequence_UnnamedField: 262. is now a constant and refers to
     a constant string.

   - bpo-38540(4): Fixed possible leak in *note PyArg_Parse(): 10f0. and
     similar functions for format units ‘"es#"’ and ‘"et#"’ when the
     macro ‘PY_SSIZE_T_CLEAN’ is not defined.

   - bpo-38395(5): Fix a crash in *note weakref.proxy: 37a. 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.

   - bpo-36389(6): The ‘_PyObject_CheckConsistency()’ function is now
     also available in release mode.  For example, it can be used to
     debug a crash in the ‘visit_decref()’ function of the GC.

   - bpo-38266(7): Revert the removal of PyThreadState_DeleteCurrent()
     with documentation.

   - bpo-38303(8): Update audioop extension module to use the stable ABI
     (PEP-384).  Patch by Tyler Kieft.

   - bpo-38234(9): *note Py_SetPath(): 39c. now sets *note
     sys.executable: 39d. to the program full path (*note
     Py_GetProgramFullPath(): 39e.) rather than to the program name
     (*note Py_GetProgramName(): 39f.).

   - bpo-38234(10): Python ignored arguments passed to *note
     Py_SetPath(): 39c, *note Py_SetPythonHome(): 10f1. and *note
     Py_SetProgramName(): 10f2.: fix Python initialization to use
     specified arguments.

   - bpo-38205(11): The *note Py_UNREACHABLE(): 526. macro now calls
     *note Py_FatalError(): 266.

   - bpo-38140(12): Make dict and weakref offsets opaque for C heap
     types by passing the offsets through PyMemberDef

   - bpo-15088(13): The C function ‘PyGen_NeedsFinalizing’ has been
     removed.  It was not documented, tested or used anywhere within
     CPython after the implementation of PEP 442(14).  Patch by Joannah
     Nanjekye.  (Patch by Joannah Nanjekye)

   - bpo-36763(15): Options added by ‘PySys_AddXOption()’ are now
     handled the same way than ‘PyConfig.xoptions’ and command line ‘-X’
     options.

   - bpo-37926(16): Fix a crash in ‘PySys_SetArgvEx(0, NULL, 0)’.

   - bpo-37879(17): Fix subtype_dealloc to suppress the type decref when
     the base type is a C heap type

   - bpo-37645(18): Add ‘_PyObject_FunctionStr()’ to get a user-friendly
     string representation of a function-like object.  Patch by Jeroen
     Demeyer.

   - bpo-29548(19): The functions ‘PyEval_CallObject’,
     ‘PyEval_CallFunction’, ‘PyEval_CallMethod’ and
     ‘PyEval_CallObjectWithKeywords’ are deprecated.  Use *note
     PyObject_Call(): 23c. and its variants instead.

   - bpo-37151(20): ‘PyCFunction_Call’ is now a deprecated alias of
     *note PyObject_Call(): 23c.

   - bpo-37540(21): The vectorcall protocol now requires that the caller
     passes only strings as keyword names.

   - bpo-37207(22): The vectorcall protocol is now enabled for ‘type’
     objects: set ‘tp_vectorcall’ to a vectorcall function to be used
     instead of ‘tp_new’ and ‘tp_init’ when calling the class itself.

   - bpo-21120(23): Exclude Python-ast.h, ast.h and asdl.h from the
     limited API.

   - bpo-37483(24): Add new function ‘_PyObject_CallOneArg’ for calling
     an object with one positional argument.

   - bpo-36763(25): Add ‘PyConfig_SetWideStringList()’ function.

   - bpo-37337(26): Add fast functions for calling methods:
     ‘_PyObject_VectorcallMethod()’, ‘_PyObject_CallMethodNoArgs()’ and
     ‘_PyObject_CallMethodOneArg()’.

   - bpo-28805(27): The *note METH_FASTCALL: 10f3. calling convention
     has been documented.

   - bpo-37221(28): The new function *note PyCode_NewWithPosOnlyArgs():
     39a. allows to create code objects like *note PyCode_New(): 39b,
     but with an extra `posonlyargcount' parameter for indicating the
     number of positonal-only arguments.

   - bpo-37215(29): Fix dtrace issue introduce by bpo-36842(30)

   - bpo-37194(31): Add a new public *note PyObject_CallNoArgs(): 250.
     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,
     ‘PyObject_CallFunctionObjArgs(func, NULL)’ allocates 960 bytes on
     the stack per call, whereas ‘PyObject_CallNoArgs(func)’ only
     allocates 624 bytes per call.

   - bpo-37170(32): Fix the cast on error in *note
     PyLong_AsUnsignedLongLongMask(): 10f4.

   - bpo-35381(33): Convert posixmodule.c statically allocated types
     ‘DirEntryType’ and ‘ScandirIteratorType’ to heap-allocated types.

   - bpo-34331(34): Use singular/plural noun in error message when
     instantiating an abstract class with non-overriden abstract
     method(s).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37633

   (2) https://bugs.python.org/issue38644

   (3) https://bugs.python.org/issue38650

   (4) https://bugs.python.org/issue38540

   (5) https://bugs.python.org/issue38395

   (6) https://bugs.python.org/issue36389

   (7) https://bugs.python.org/issue38266

   (8) https://bugs.python.org/issue38303

   (9) https://bugs.python.org/issue38234

   (10) https://bugs.python.org/issue38234

   (11) https://bugs.python.org/issue38205

   (12) https://bugs.python.org/issue38140

   (13) https://bugs.python.org/issue15088

   (14) https://www.python.org/dev/peps/pep-0442

   (15) https://bugs.python.org/issue36763

   (16) https://bugs.python.org/issue37926

   (17) https://bugs.python.org/issue37879

   (18) https://bugs.python.org/issue37645

   (19) https://bugs.python.org/issue29548

   (20) https://bugs.python.org/issue37151

   (21) https://bugs.python.org/issue37540

   (22) https://bugs.python.org/issue37207

   (23) https://bugs.python.org/issue21120

   (24) https://bugs.python.org/issue37483

   (25) https://bugs.python.org/issue36763

   (26) https://bugs.python.org/issue37337

   (27) https://bugs.python.org/issue28805

   (28) https://bugs.python.org/issue37221

   (29) https://bugs.python.org/issue37215

   (30) https://bugs.python.org/issue36842

   (31) https://bugs.python.org/issue37194

   (32) https://bugs.python.org/issue37170

   (33) https://bugs.python.org/issue35381

   (34) https://bugs.python.org/issue34331


File: python.info,  Node: Python 3 8 0 beta 1,  Next: Python 3 8 0 alpha 4,  Prev: Python 3 9 0 alpha 1,  Up: Changelog（更動日誌）

1.19.27 Python 3.8.0 beta 1
---------------------------

`发布日期: 2019-06-04'

* Menu:

* 安全性: 安全性<15>.
* 核心与内置函数: 核心与内置函数<24>.
* 库: 库<26>.
* 文档: 文档<21>.
* 测试: 测试<20>.
* 构建: 构建<20>.
* Windows: Windows<20>.
* macOS: macOS<18>.
* IDLE: IDLE<20>.
* 工具/示例: 工具/示例<8>.
* C API: C API<17>.


File: python.info,  Node: 安全性<15>,  Next: 核心与内置函数<24>,  Up: Python 3 8 0 beta 1

1.19.27.1 安全性
................

   - bpo-35907(1): CVE-2019-9948: Avoid file reading by disallowing
     ‘local-file://’ and ‘local_file://’ URL schemes in
     ‘URLopener().open()’ and ‘URLopener().retrieve()’ of *note
     urllib.request: 129.

   - bpo-33529(2): Prevent fold function used in email header encoding
     from entering infinite loop when there are too many non-ASCII
     characters in a header.

   - bpo-33164(3): Updated blake2 implementation which uses secure
     memset implementation provided by platform.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35907

   (2) https://bugs.python.org/issue33529

   (3) https://bugs.python.org/issue33164


File: python.info,  Node: 核心与内置函数<24>,  Next: 库<26>,  Prev: 安全性<15>,  Up: Python 3 8 0 beta 1

1.19.27.2 核心与内置函数
........................

   - bpo-35814(1): Allow unpacking in the right hand side of annotated
     assignments.  In particular, ‘t: Tuple[int, ...] = x, y, *z’ is now
     allowed.

   - bpo-37126(2): All structseq objects are now tracked by the garbage
     collector.  Patch by Pablo Galindo.

   - bpo-37122(3): Make the `co_argcount' attribute of code objects
     represent the total number of positional arguments (including
     positional-only arguments).  The value of `co_posonlyargcount' can
     be used to distinguish which arguments are positional only, and the
     difference (`co_argcount' - `co_posonlyargcount') is the number of
     positional-or-keyword arguments.  Patch by Pablo Galindo.

   - bpo-20092(4): Constructors of *note int: 204, *note float: 1fd. and
     *note complex: 2c1. will now use the *note __index__(): 2c2.
     special method, if available and the corresponding method *note
     __int__(): 2c3, *note __float__(): 2c4. or *note __complex__():
     2c5. is not available.

   - bpo-37087(5): Add native thread ID (TID) support to OpenBSD.

   - bpo-26219(6): Implemented per opcode cache mechanism and
     ‘LOAD_GLOBAL’ instruction use it.  ‘LOAD_GLOBAL’ is now about 40%
     faster.  Contributed by Yury Selivanov, and Inada Naoki.

   - bpo-37072(7): Fix crash in PyAST_FromNodeObject() when flags is
     NULL.

   - bpo-37029(8): Freeing a great many small objects could take time
     quadratic in the number of arenas, due to using linear search to
     keep ‘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.

   - bpo-26423(9): Fix possible overflow in ‘wrap_lenfunc()’ when
     ‘sizeof(long) < sizeof(Py_ssize_t)’ (e.g., 64-bit Windows).

   - bpo-37050(10): 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).

   - bpo-22385(11): The *note bytes.hex: 724, *note bytearray.hex: 725,
     and *note memoryview.hex: 726. methods as well as the *note
     binascii.hexlify: 10f8. and ‘b2a_hex’ functions now have the
     ability to include an optional separator between hex bytes.  This
     functionality was inspired by MicroPython’s hexlify implementation.

   - bpo-26836(12): Add *note os.memfd_create(): 320.

   - bpo-37032(13): Added new ‘replace()’ method to the code type (*note
     types.CodeType: 2cd.).

   - bpo-37007(14): Implement *note socket.if_nameindex(): 34d, *note
     socket.if_nametoindex(): 34e, and *note socket.if_indextoname():
     34f. on Windows.

   - bpo-36829(15): *note PyErr_WriteUnraisable(): 10f9. now creates a
     traceback object if there is no current traceback.  Moreover, call
     *note PyErr_NormalizeException(): 10fa. and *note
     PyException_SetTraceback(): 10fb. to normalize the exception value.
     Ignore any error.

   - bpo-36878(16): Only accept text after ‘# type: ignore’ if the first
     character is ASCII. This is to disallow things like ‘# type:
     ignoreé’.

   - bpo-36878(17): Store text appearing after a ‘# type: ignore’
     comment in the AST. For example a type ignore like ‘# type:
     ignore[E1000]’ will have the string ‘"[E1000]"’ stored in its AST
     node.

   - bpo-2180(18): Treat line continuation at EOF as a ‘SyntaxError’ by
     Anthony Sottile.

   - bpo-36907(19): Fix a crash when calling a C function with a keyword
     dict (‘f(**kwargs)’) and changing the dict ‘kwargs’ while that
     function is running.

   - bpo-36946(20): Fix possible signed integer overflow when handling
     slices.

   - bpo-36826(21): Add NamedExpression kind support to ast_unparse.c

   - bpo-1875(22): A *note SyntaxError: 559. 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.

   - bpo-36027(23): Allow computation of modular inverses via
     three-argument ‘pow’: the second argument is now permitted to be
     negative in the case where the first and third arguments are
     relatively prime.

   - bpo-36861(24): Update the Unicode database to version 12.1.0.

   - bpo-28866(25): Avoid caching attributes of classes which type
     defines mro() to avoid a hard cache invalidation problem.

   - bpo-36851(26): The ‘FrameType’ stack is now correctly cleaned up if
     the execution ends with a return and the stack is not empty.

   - bpo-34616(27): The ‘compile()’ builtin functions now support the
     ‘ast.PyCF_ALLOW_TOP_LEVEL_AWAIT’ flag, which allow to compile
     sources that contains top-level ‘await’, ‘async with’ or ‘async
     for’.  This is useful to evaluate async-code from with an already
     async functions; for example in a custom REPL.

   - bpo-36842(28): Implement PEP 578, adding sys.audit, io.open_code
     and related APIs.

   - bpo-27639(29): Correct return type for UserList slicing operations.
     Patch by Michael Blahay, Erick Cervantes, and vaultah

   - bpo-36737(30): Move PyRuntimeState.warnings into per-interpreter
     state (via "module state").

   - bpo-36793(31): Removed ‘__str__’ implementations from builtin types
     *note bool: 2bd, *note int: 204, *note float: 1fd, *note complex:
     2c1. and few classes from the standard library.  They now inherit
     ‘__str__()’ from *note object: 3d2.

   - bpo-36817(32): Add a ‘=’ feature f-strings for debugging.  This can
     precede ‘!s’, ‘!r’, or ‘!a’.  It produces the text of the
     expression, followed by an equal sign, followed by the repr of the
     value of the expression.  So ‘f'{3*9+15=}'’ would be equal to the
     string ‘'3*9+15=42'’.  If ‘=’ is specified, the default conversion
     is set to ‘!r’, unless a format spec is given, in which case the
     formatting behavior is unchanged, and __format__ will be used.

   - bpo-24048(33): Save the live exception during import.c’s
     ‘remove_module()’.

   - bpo-27987(34): 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.

   - bpo-36601(35): A long-since-meaningless check for ‘getpid() ==
     main_pid’ was removed from Python’s internal C signal handler.

   - bpo-36594(36): Fix incorrect use of ‘%p’ in format strings.  Patch
     by Zackery Spytz.

   - bpo-36045(37): builtins.help() now prefixes ‘async’ for async
     functions

   - bpo-36084(38): Add native thread ID (TID) to threading.Thread
     objects (supported platforms: Windows, FreeBSD, Linux, macOS)

   - bpo-36035(39): Added fix for broken symlinks in combination with
     pathlib

   - bpo-35983(40): Added new trashcan macros to deal with a double
     deallocation that could occur when the ‘tp_dealloc’ of a subclass
     calls the ‘tp_dealloc’ of a base class and that base class uses the
     trashcan mechanism.  Patch by Jeroen Demeyer.

   - bpo-20602(41): Do not clear *note sys.flags: c0e. and *note
     sys.float_info: 10fc. during shutdown.  Patch by Zackery Spytz.

   - bpo-26826(42): Expose ‘copy_file_range()’ as a low level API in the
     *note os: c4. module.

   - bpo-32388(43): Remove cross-version binary compatibility
     requirement in tp_flags.

   - bpo-31862(44): Port binascii to PEP 489 multiphase initialization.
     Patch by Marcel Plch.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35814

   (2) https://bugs.python.org/issue37126

   (3) https://bugs.python.org/issue37122

   (4) https://bugs.python.org/issue20092

   (5) https://bugs.python.org/issue37087

   (6) https://bugs.python.org/issue26219

   (7) https://bugs.python.org/issue37072

   (8) https://bugs.python.org/issue37029

   (9) https://bugs.python.org/issue26423

   (10) https://bugs.python.org/issue37050

   (11) https://bugs.python.org/issue22385

   (12) https://bugs.python.org/issue26836

   (13) https://bugs.python.org/issue37032

   (14) https://bugs.python.org/issue37007

   (15) https://bugs.python.org/issue36829

   (16) https://bugs.python.org/issue36878

   (17) https://bugs.python.org/issue36878

   (18) https://bugs.python.org/issue2180

   (19) https://bugs.python.org/issue36907

   (20) https://bugs.python.org/issue36946

   (21) https://bugs.python.org/issue36826

   (22) https://bugs.python.org/issue1875

   (23) https://bugs.python.org/issue36027

   (24) https://bugs.python.org/issue36861

   (25) https://bugs.python.org/issue28866

   (26) https://bugs.python.org/issue36851

   (27) https://bugs.python.org/issue34616

   (28) https://bugs.python.org/issue36842

   (29) https://bugs.python.org/issue27639

   (30) https://bugs.python.org/issue36737

   (31) https://bugs.python.org/issue36793

   (32) https://bugs.python.org/issue36817

   (33) https://bugs.python.org/issue24048

   (34) https://bugs.python.org/issue27987

   (35) https://bugs.python.org/issue36601

   (36) https://bugs.python.org/issue36594

   (37) https://bugs.python.org/issue36045

   (38) https://bugs.python.org/issue36084

   (39) https://bugs.python.org/issue36035

   (40) https://bugs.python.org/issue35983

   (41) https://bugs.python.org/issue20602

   (42) https://bugs.python.org/issue26826

   (43) https://bugs.python.org/issue32388

   (44) https://bugs.python.org/issue31862


File: python.info,  Node: 库<26>,  Next: 文档<21>,  Prev: 核心与内置函数<24>,  Up: Python 3 8 0 beta 1

1.19.27.3 库
............

   - bpo-37128(1): Added *note math.perm(): 317.

   - bpo-37120(2): Add SSLContext.num_tickets to control the number of
     TLSv1.3 session tickets.

   - bpo-12202(3): Fix the error handling in *note
     msilib.SummaryInformation.GetProperty(): 10fe.  Patch by Zackery
     Spytz.

   - bpo-26835(4): The fcntl module now contains file sealing constants
     for sealing of memfds.

   - bpo-29262(5): Add ‘get_origin()’ and ‘get_args()’ introspection
     helpers to ‘typing’ module.

   - bpo-12639(6): *note msilib.Directory.start_component(): 10ff. no
     longer fails if `keyfile' is not ‘None’.

   - bpo-36999(7): Add the ‘asyncio.Task.get_coro()’ method to publicly
     expose the tasks’s coroutine object.

   - bpo-35246(8): Make *note asyncio.create_subprocess_exec(): 3b4.
     accept path-like arguments.

   - bpo-35279(9): Change default `max_workers' of ‘ThreadPoolExecutor’
     from ‘cpu_count() * 5’ to ‘min(32, cpu_count() + 4)’.  Previous
     value was unreasonably large on many cores machines.

   - bpo-37076(10): *note _thread.start_new_thread(): 1100. now logs
     uncaught exception raised by the function using *note
     sys.unraisablehook(): 35a, rather than *note sys.excepthook(): f24,
     so the hook gets access to the function which raised the exception.

   - bpo-33725(11): On macOS, the *note multiprocessing: b7. module now
     uses `spawn' start method by default.

   - bpo-37054(12): Fix destructor ‘_pyio.BytesIO’ and
     ‘_pyio.TextIOWrapper’: initialize their ‘_buffer’ attribute as soon
     as possible (in the class body), because it’s used by ‘__del__()’
     which calls ‘close()’.

   - bpo-37058(13): PEP 544: Add ‘Protocol’ and ‘@runtime_checkable’ to
     the ‘typing’ module.

   - bpo-36933(14): The functions ‘sys.set_coroutine_wrapper’ and
     ‘sys.get_coroutine_wrapper’ that were deprecated and marked for
     removal in 3.8 have been removed.

   - bpo-37047(15): Handle late binding and attribute access in *note
     unittest.mock.AsyncMock: 372. setup for autospeccing.  Document
     newly implemented async methods in *note unittest.mock.MagicMock:
     874.

   - bpo-37049(16): PEP 589: Add ‘TypedDict’ to the ‘typing’ module.

   - bpo-37046(17): PEP 586: Add ‘Literal’ to the ‘typing’ module.

   - bpo-37045(18): PEP 591: Add ‘Final’ qualifier and ‘@final’
     decorator to the ‘typing’ module.

   - bpo-37035(19): 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.

   - bpo-37001(20): *note symtable.symtable(): 1101. now accepts the
     same input types for source code as the built-in *note compile():
     2e7. function.  Patch by Dino Viehland.

   - bpo-37028(21): Implement asyncio REPL

   - bpo-37027(22): Return safe to use proxy socket object from
     transport.get_extra_info(’socket’)

   - bpo-32528(23): 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.

   - bpo-1230540(24): Add a new *note threading.excepthook(): 35e.
     function which handles uncaught *note threading.Thread.run(): 35f.
     exception.  It can be overridden to control how uncaught *note
     threading.Thread.run(): 35f. exceptions are handled.

   - bpo-36996(25): Handle *note unittest.mock.patch(): 877. used as a
     decorator on async functions.

   - bpo-37008(26): Add support for calling *note next(): 775. with the
     mock resulting from *note unittest.mock.mock_open(): 1102.

   - bpo-27737(27): Allow whitespace only header encoding in
     ‘email.header’ - by Batuhan Taskaya

   - bpo-36969(28): PDB command ‘args’ now display positional only
     arguments.  Patch contributed by Rémi Lapeyre.

   - bpo-36969(29): PDB command ‘args’ now display keyword only
     arguments.  Patch contributed by Rémi Lapeyre.

   - bpo-36983(30): Add missing names to ‘typing.__all__’: ‘ChainMap’,
     ‘ForwardRef’, ‘OrderedDict’ - by Anthony Sottile.

   - bpo-36972(31): Add SupportsIndex protocol to the typing module to
     allow type checking to detect classes that can be passed to *note
     hex(): d2e, *note oct(): d2d. and *note bin(): d08.

   - bpo-32972(32): Implement ‘unittest.IsolatedAsyncioTestCase’ to help
     testing asyncio-based code.

   - bpo-36952(33): *note fileinput.input(): 3cf. and *note
     fileinput.FileInput: 3a4. `bufsize' argument has been removed (was
     deprecated and ignored since Python 3.6), and as a result the
     `mode' and `openhook' arguments have been made keyword-only.

   - bpo-36952(34): Starting with Python 3.3, importing ABCs from *note
     collections: 1d. is deprecated, and import should be done from
     *note collections.abc: 1e.  Still being able to import from *note
     collections: 1d. was marked for removal in 3.8, but has been
     delayed to 3.9; documentation and ‘DeprecationWarning’ clarified.

   - bpo-36949(35): Implement __repr__ for WeakSet objects.

   - bpo-36948(36): Fix *note NameError: e40. in *note
     urllib.request.URLopener.retrieve(): 1103.  Patch by Karthikeyan
     Singaravelan.

   - bpo-33524(37): 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).

   - bpo-24564(38): *note shutil.copystat(): b52. now ignores *note
     errno.EINVAL: 1104. on *note os.setxattr(): b29. which may occur
     when copying files on filesystems without extended attributes
     support.

     Original patch by Giampaolo Rodola, updated by Ying Wang.

   - bpo-36888(39): Python child processes can now access the status of
     their parent process using multiprocessing.process.parent_process

   - bpo-36921(40): Deprecate ‘@coroutine’ for sake of ‘async def’.

   - bpo-25652(41): Fix bug in ‘__rmod__’ of ‘UserString’ - by Batuhan
     Taskaya.

   - bpo-36916(42): Remove a message about an unhandled exception in a
     task when writer.write() is used without await and writer.drain()
     fails with an exception.

   - bpo-36889(43): Introduce ‘asyncio.Stream’ class that merges *note
     asyncio.StreamReader: 1105. and *note asyncio.StreamWriter: 1106.
     functionality.  ‘asyncio.Stream’ can work in readonly, writeonly
     and readwrite modes.  Provide ‘asyncio.connect()’,
     ‘asyncio.connect_unix()’, ‘asyncio.connect_read_pipe()’ and
     ‘asyncio.connect_write_pipe()’ factories to open ‘asyncio.Stream’
     connections.  Provide ‘asyncio.StreamServer’ and ‘UnixStreamServer’
     to serve servers with asyncio.Stream API. Modify *note
     asyncio.create_subprocess_shell(): 3b5. and *note
     asyncio.create_subprocess_exec(): 3b4. to use ‘asyncio.Stream’
     instead of deprecated ‘StreamReader’ and ‘StreamWriter’.  Deprecate
     *note asyncio.StreamReader: 1105. and *note asyncio.StreamWriter:
     1106.  Deprecate usage of private classes, e.g.
     ‘asyncio.FlowControlMixing’ and ‘asyncio.StreamReaderProtocol’
     outside of asyncio package.

   - bpo-36845(44): Added validation of integer prefixes to the
     construction of IP networks and interfaces in the ipaddress module.

   - bpo-23378(45): Add an extend action to argparser.

   - bpo-36867(46): Fix a bug making a SharedMemoryManager instance and
     its parent process use two separate resource_tracker processes.

   - bpo-23896(47): Adds a grammar to lib2to3.pygram that contains exec
     as a function not as statement.

   - bpo-36895(48): The function ‘time.clock()’ was deprecated in 3.3 in
     favor of ‘time.perf_counter()’ and marked for removal in 3.8, it
     has removed.

   - bpo-35545(49): Fix asyncio discarding IPv6 scopes when ensuring
     hostname resolutions internally

   - bpo-36887(50): Add new function *note math.isqrt(): 319. to compute
     integer square roots.

   - bpo-34632(51): Introduce the ‘importlib.metadata’ module with
     (provisional) support for reading metadata from third-party
     packages.

   - bpo-36878(52): When using ‘type_comments=True’ in *note ast.parse:
     2d6, treat ‘# 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 ‘# type: ignore[E1000]’.

   - bpo-36778(53): ‘cp65001’ encoding (Windows code page 65001) becomes
     an alias to ‘utf_8’ encoding.

   - bpo-36867(54): The multiprocessing.resource_tracker replaces the
     multiprocessing.semaphore_tracker module.  Other than semaphores,
     resource_tracker also tracks shared_memory segments.

   - bpo-30262(55): The ‘Cache’ and ‘Statement’ objects of the *note
     sqlite3: f2. module are not exposed to the user.  Patch by Aviv
     Palivoda.

   - bpo-24538(56): In *note shutil.copystat(): b52, first copy extended
     file attributes and then file permissions, since extended
     attributes can only be set on the destination while it is still
     writeable.

   - bpo-36829(57): Add new *note sys.unraisablehook(): 35a. 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 (*note
     gc.collect(): 35b.).

   - bpo-36832(58): Introducing ‘zipfile.Path’, a pathlib-compatible
     wrapper for traversing zip files.

   - bpo-36814(59): Fix an issue where os.posix_spawnp() would
     incorrectly raise a TypeError when file_actions is None.

   - bpo-33110(60): Handle exceptions raised by functions added by
     concurrent.futures add_done_callback correctly when the Future has
     already completed.

   - bpo-26903(61): Limit ‘max_workers’ in ‘ProcessPoolExecutor’ to 61
     to work around a WaitForMultipleObjects limitation.

   - bpo-36813(62): Fix *note QueueListener: 803. to call
     ‘queue.task_done()’ upon stopping.  Patch by Bar Harel.

   - bpo-36806(63): Forbid creation of asyncio stream objects like
     StreamReader, StreamWriter, Process, and their protocols outside of
     asyncio package.

   - bpo-36802(64): Provide both sync and async calls for
     StreamWriter.write() and StreamWriter.close()

   - bpo-36801(65): Properly handle SSL connection closing in asyncio
     StreamWriter.drain() call.

   - bpo-36785(66): Implement PEP 574 (pickle protocol 5 with
     out-of-band buffers).

   - bpo-36772(67): functools.lru_cache() can now be used as a straight
     decorator in addition to its existing usage as a function that
     returns a decorator.

   - bpo-6584(68): Add a *note BadGzipFile: 303. exception to the *note
     gzip: 8b. module.

   - bpo-36748(69): Optimized write buffering in C implementation of
     ‘TextIOWrapper’.  Writing ASCII string to ‘TextIOWrapper’ with
     ascii, latin1, or utf-8 encoding is about 20% faster.  Patch by
     Inada Naoki.

   - bpo-8138(70): Don’t mark ‘wsgiref.simple_server.SimpleServer’ as
     multi-threaded since ‘wsgiref.simple_server.WSGIServer’ is
     single-threaded.

   - bpo-22640(71): *note py_compile.compile(): 343. now supports silent
     mode.  Patch by Joannah Nanjekye

   - bpo-29183(72): Fix double exceptions in *note
     wsgiref.handlers.BaseHandler: 1107. by calling its ‘close()’ method
     only when no exception is raised.

   - bpo-36548(73): Improved the repr of regular expression flags.

   - bpo-36542(74): The signature of Python functions can now be
     overridden by specifying the ‘__text_signature__’ attribute.

   - bpo-36533(75): 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.

   - bpo-35252(76): Throw a TypeError instead of an AssertionError when
     using an invalid type annotation with singledispatch.

   - bpo-35900(77): 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 ‘__setstate__’ method.

   - bpo-35900(78): enable custom reduction callback registration for
     functions and classes in _pickle.c, using the new Pickler’s
     attribute ‘reducer_override’

   - bpo-36368(79): Fix a bug crashing SharedMemoryManager instances in
     interactive sessions after a ctrl-c (KeyboardInterrupt) was sent

   - bpo-31904(80): Fix mmap fail for VxWorks

   - bpo-27497(81): *note csv.DictWriter.writeheader(): c4c. now returns
     the return value of the underlying ‘csv.Writer.writerow()’ method.
     Patch contributed by Ashish Nitin Patil.

   - bpo-36239(82): Parsing .mo files now ignores comments starting and
     ending with #-#-#-#-#.

   - bpo-26707(83): 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.

   - bpo-31904(84): Add posix module support for VxWorks.

   - bpo-35125(85): Asyncio: Remove inner callback on outer cancellation
     in shield

   - bpo-35721(86): Fix ‘asyncio.SelectorEventLoop.subprocess_exec()’
     leaks file descriptors if ‘Popen’ fails and called with
     ‘stdin=subprocess.PIPE’.  Patch by Niklas Fiekas.

   - bpo-31855(87): *note unittest.mock.mock_open(): 1102. results now
     respects the argument of read([size]).  Patch contributed by Rémi
     Lapeyre.

   - bpo-35431(88): Implement *note math.comb(): 318. 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.

   - bpo-26660(89): Fixed permission errors in *note TemporaryDirectory:
     c96. clean up.  Previously ‘TemporaryDirectory.cleanup()’ failed
     when non-writeable or non-searchable files or directories were
     created inside a temporary directory.

   - bpo-34271(90): 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.

   - bpo-26467(91): Added AsyncMock to support using unittest to mock
     asyncio coroutines.  Patch by Lisa Roach.

   - bpo-33569(92): dataclasses.InitVar: Exposes the type used to create
     the init var.

   - bpo-34424(93): Fix serialization of messages containing encoded
     strings when the policy.linesep is set to a multi-character string.
     Patch by Jens Troeger.

   - bpo-34303(94): Performance of *note functools.reduce(): d37. is
     slightly improved.  Patch by Sergey Fedoseev.

   - bpo-33361(95): Fix a bug in *note codecs.StreamRecoder: 1108. where
     seeking might leave old data in a buffer and break subsequent read
     calls.  Patch by Ammar Askar.

   - bpo-22454(96): The *note shlex: e8. module now exposes *note
     shlex.join(): 345, the inverse of *note shlex.split(): 210.  Patch
     by Bo Bayles.

   - bpo-31922(97):
     ‘asyncio.AbstractEventLoop.create_datagram_endpoint()’: Do not
     connect UDP socket when broadcast is allowed.  This allows to
     receive replies after a UDP broadcast.

   - bpo-24882(98): Change ThreadPoolExecutor to use existing idle
     threads before spinning up new ones.

   - bpo-31961(99): Added support for bytes and path-like objects in
     *note subprocess.Popen(): 3db. on Windows.  The `args' parameter
     now accepts a *note path-like object: 472. if `shell' is ‘False’
     and a sequence containing bytes and path-like objects.  The
     `executable' parameter now accepts a bytes and *note path-like
     object: 472.  The `cwd' parameter now accepts a bytes object.
     Based on patch by Anders Lorentsen.

   - bpo-33123(100): *note pathlib.Path.unlink: 1109. now accepts a
     `missing_ok' parameter to avoid a *note FileNotFoundError: 8ad.
     from being raised.  Patch by Robert Buchholz.

   - bpo-32941(101): Allow *note mmap.mmap: 31c. objects to access the
     madvise() system call (through *note mmap.mmap.madvise(): 31d.).

   - bpo-22102(102): 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.

   - bpo-32515(103): trace.py can now run modules via python3 -m trace
     -t –module module_name

   - bpo-32299(104): Changed *note unittest.mock.patch.dict(): 110a. to
     return the patched dictionary when used as context manager.  Patch
     by Vadim Tsander.

   - bpo-27141(105): Added a ‘__copy__()’ to ‘collections.UserList’ and
     ‘collections.UserDict’ in order to correctly implement shallow
     copying of the objects.  Patch by Bar Harel.

   - bpo-31829(106): ‘\r’, ‘\0’ and ‘\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.

   - bpo-23395(107): ‘_thread.interrupt_main()’ now avoids setting the
     Python error status if the ‘SIGINT’ signal is ignored or not
     handled by Python.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37128

   (2) https://bugs.python.org/issue37120

   (3) https://bugs.python.org/issue12202

   (4) https://bugs.python.org/issue26835

   (5) https://bugs.python.org/issue29262

   (6) https://bugs.python.org/issue12639

   (7) https://bugs.python.org/issue36999

   (8) https://bugs.python.org/issue35246

   (9) https://bugs.python.org/issue35279

   (10) https://bugs.python.org/issue37076

   (11) https://bugs.python.org/issue33725

   (12) https://bugs.python.org/issue37054

   (13) https://bugs.python.org/issue37058

   (14) https://bugs.python.org/issue36933

   (15) https://bugs.python.org/issue37047

   (16) https://bugs.python.org/issue37049

   (17) https://bugs.python.org/issue37046

   (18) https://bugs.python.org/issue37045

   (19) https://bugs.python.org/issue37035

   (20) https://bugs.python.org/issue37001

   (21) https://bugs.python.org/issue37028

   (22) https://bugs.python.org/issue37027

   (23) https://bugs.python.org/issue32528

   (24) https://bugs.python.org/issue1230540

   (25) https://bugs.python.org/issue36996

   (26) https://bugs.python.org/issue37008

   (27) https://bugs.python.org/issue27737

   (28) https://bugs.python.org/issue36969

   (29) https://bugs.python.org/issue36969

   (30) https://bugs.python.org/issue36983

   (31) https://bugs.python.org/issue36972

   (32) https://bugs.python.org/issue32972

   (33) https://bugs.python.org/issue36952

   (34) https://bugs.python.org/issue36952

   (35) https://bugs.python.org/issue36949

   (36) https://bugs.python.org/issue36948

   (37) https://bugs.python.org/issue33524

   (38) https://bugs.python.org/issue24564

   (39) https://bugs.python.org/issue36888

   (40) https://bugs.python.org/issue36921

   (41) https://bugs.python.org/issue25652

   (42) https://bugs.python.org/issue36916

   (43) https://bugs.python.org/issue36889

   (44) https://bugs.python.org/issue36845

   (45) https://bugs.python.org/issue23378

   (46) https://bugs.python.org/issue36867

   (47) https://bugs.python.org/issue23896

   (48) https://bugs.python.org/issue36895

   (49) https://bugs.python.org/issue35545

   (50) https://bugs.python.org/issue36887

   (51) https://bugs.python.org/issue34632

   (52) https://bugs.python.org/issue36878

   (53) https://bugs.python.org/issue36778

   (54) https://bugs.python.org/issue36867

   (55) https://bugs.python.org/issue30262

   (56) https://bugs.python.org/issue24538

   (57) https://bugs.python.org/issue36829

   (58) https://bugs.python.org/issue36832

   (59) https://bugs.python.org/issue36814

   (60) https://bugs.python.org/issue33110

   (61) https://bugs.python.org/issue26903

   (62) https://bugs.python.org/issue36813

   (63) https://bugs.python.org/issue36806

   (64) https://bugs.python.org/issue36802

   (65) https://bugs.python.org/issue36801

   (66) https://bugs.python.org/issue36785

   (67) https://bugs.python.org/issue36772

   (68) https://bugs.python.org/issue6584

   (69) https://bugs.python.org/issue36748

   (70) https://bugs.python.org/issue8138

   (71) https://bugs.python.org/issue22640

   (72) https://bugs.python.org/issue29183

   (73) https://bugs.python.org/issue36548

   (74) https://bugs.python.org/issue36542

   (75) https://bugs.python.org/issue36533

   (76) https://bugs.python.org/issue35252

   (77) https://bugs.python.org/issue35900

   (78) https://bugs.python.org/issue35900

   (79) https://bugs.python.org/issue36368

   (80) https://bugs.python.org/issue31904

   (81) https://bugs.python.org/issue27497

   (82) https://bugs.python.org/issue36239

   (83) https://bugs.python.org/issue26707

   (84) https://bugs.python.org/issue31904

   (85) https://bugs.python.org/issue35125

   (86) https://bugs.python.org/issue35721

   (87) https://bugs.python.org/issue31855

   (88) https://bugs.python.org/issue35431

   (89) https://bugs.python.org/issue26660

   (90) https://bugs.python.org/issue34271

   (91) https://bugs.python.org/issue26467

   (92) https://bugs.python.org/issue33569

   (93) https://bugs.python.org/issue34424

   (94) https://bugs.python.org/issue34303

   (95) https://bugs.python.org/issue33361

   (96) https://bugs.python.org/issue22454

   (97) https://bugs.python.org/issue31922

   (98) https://bugs.python.org/issue24882

   (99) https://bugs.python.org/issue31961

   (100) https://bugs.python.org/issue33123

   (101) https://bugs.python.org/issue32941

   (102) https://bugs.python.org/issue22102

   (103) https://bugs.python.org/issue32515

   (104) https://bugs.python.org/issue32299

   (105) https://bugs.python.org/issue27141

   (106) https://bugs.python.org/issue31829

   (107) https://bugs.python.org/issue23395


File: python.info,  Node: 文档<21>,  Next: 测试<20>,  Prev: 库<26>,  Up: Python 3 8 0 beta 1

1.19.27.4 文档
..............

   - bpo-36896(1): Clarify that some types have unstable constructor
     signature between Python versions.

   - bpo-36686(2): Improve documentation of the stdin, stdout, and
     stderr arguments of the ‘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.

   - bpo-36984(3): Improve version added references in ‘typing’ module -
     by Anthony Sottile.

   - bpo-36868(4): What’s new now mentions
     SSLContext.hostname_checks_common_name instead of
     SSLContext.host_flags.

   - bpo-35924(5): Add a note to the ‘curses.addstr()’ documentation to
     warn that multiline strings can cause segfaults because of an
     ncurses bug.

   - bpo-36783(6): Added C API Documentation for Time_FromTimeAndFold
     and PyDateTime_FromDateAndTimeAndFold as per PEP 495.  Patch by
     Edison Abahurire.

   - bpo-36797(7): 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.

   - bpo-22865(8): Add detail to the documentation on the *note
     pty.spawn: 97f. function.

   - bpo-35397(9): Remove deprecation and document
     urllib.parse.unwrap().  Patch contributed by Rémi Lapeyre.

   - bpo-32995(10): Added the context variable in glossary.

   - bpo-33519(11): Clarify that *note copy(): 25. is not part of the
     ‘MutableSequence’ ABC.

   - bpo-33482(12): Make ‘codecs.StreamRecoder.writelines’ take a list
     of bytes.

   - bpo-25735(13): Added documentation for func factorial to indicate
     that returns integer values

   - bpo-20285(14): 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.)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36896

   (2) https://bugs.python.org/issue36686

   (3) https://bugs.python.org/issue36984

   (4) https://bugs.python.org/issue36868

   (5) https://bugs.python.org/issue35924

   (6) https://bugs.python.org/issue36783

   (7) https://bugs.python.org/issue36797

   (8) https://bugs.python.org/issue22865

   (9) https://bugs.python.org/issue35397

   (10) https://bugs.python.org/issue32995

   (11) https://bugs.python.org/issue33519

   (12) https://bugs.python.org/issue33482

   (13) https://bugs.python.org/issue25735

   (14) https://bugs.python.org/issue20285


File: python.info,  Node: 测试<20>,  Next: 构建<20>,  Prev: 文档<21>,  Up: Python 3 8 0 beta 1

1.19.27.5 测试
..............

   - bpo-37069(1): Modify test_coroutines, test_cprofile,
     test_generators, test_raise, test_ssl and test_yield_from to use
     *note test.support.catch_unraisable_exception(): 10e4. rather than
     *note test.support.captured_stderr(): 110d.

   - bpo-37098(2): Fix test_memfd_create on older Linux Kernels.

   - bpo-37081(3): 使用OpenSSL 1.1.1c进行测试

   - bpo-36829(4): Add *note test.support.catch_unraisable_exception():
     10e4.: context manager catching unraisable exception using *note
     sys.unraisablehook(): 35a.

   - bpo-36915(5): 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).

   - bpo-36719(6): "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.

   - bpo-36816(7): Update Lib/test/selfsigned_pythontestdotnet.pem to
     match self-signed.pythontest.net’s new TLS certificate.

   - bpo-35925(8): 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.

   - bpo-36782(9): Add tests for several C API functions in the *note
     datetime: 30. module.  Patch by Edison Abahurire.

   - bpo-36342(10): Fix test_multiprocessing in test_venv if platform
     lacks functioning sem_open.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37069

   (2) https://bugs.python.org/issue37098

   (3) https://bugs.python.org/issue37081

   (4) https://bugs.python.org/issue36829

   (5) https://bugs.python.org/issue36915

   (6) https://bugs.python.org/issue36719

   (7) https://bugs.python.org/issue36816

   (8) https://bugs.python.org/issue35925

   (9) https://bugs.python.org/issue36782

   (10) https://bugs.python.org/issue36342


File: python.info,  Node: 构建<20>,  Next: Windows<20>,  Prev: 测试<20>,  Up: Python 3 8 0 beta 1

1.19.27.6 构建
..............

   - bpo-36721(1): To embed Python into an application, a new ‘--embed’
     option must be passed to ‘python3-config --libs --embed’ to get
     ‘-lpython3.8’ (link the application to libpython).  To support both
     3.8 and older, try ‘python3-config --libs --embed’ first and
     fallback to ‘python3-config --libs’ (without ‘--embed’) if the
     previous command fails.

     增加一个 pkg-config ‘python-3.8-embed’ 模块用来将 Python 嵌入到一个
     应用中: ‘pkg-config python-3.8-embed --libs’ 包含 ‘-lpython3.8’。 要
     同时支持 3.8 和旧版本，请先尝试 ‘pkg-config python-X.Y-embed
     --libs’ 并在此命令失败时回退到 ‘pkg-config python-X.Y --libs’ (即不
     带 ‘--embed’) （请将 ‘X.Y’ 替换为 Python 版本号）。

     On the other hand, ‘pkg-config python3.8 --libs’ no longer contains
     ‘-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.

   - bpo-36786(2): "make install" now runs compileall in parallel.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36721

   (2) https://bugs.python.org/issue36786


File: python.info,  Node: Windows<20>,  Next: macOS<18>,  Prev: 构建<20>,  Up: Python 3 8 0 beta 1

1.19.27.7 Windows
.................

   - bpo-36965(1): include of STATUS_CONTROL_C_EXIT without depending on
     MSC compiler

   - bpo-35926(2): 在Windows安装程序中将OpenSSL更新为1.1.1b

   - bpo-29883(3): Add Windows support for UDP transports for the
     Proactor Event Loop.  Patch by Adam Meily.

   - bpo-33407(4): The ‘Py_DEPRECATED()’ macro has been implemented for
     MSVC.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36965

   (2) https://bugs.python.org/issue35926

   (3) https://bugs.python.org/issue29883

   (4) https://bugs.python.org/issue33407


File: python.info,  Node: macOS<18>,  Next: IDLE<20>,  Prev: Windows<20>,  Up: Python 3 8 0 beta 1

1.19.27.8 macOS
...............

   - bpo-36231(1): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36231


File: python.info,  Node: IDLE<20>,  Next: 工具/示例<8>,  Prev: macOS<18>,  Up: Python 3 8 0 beta 1

1.19.27.9 IDLE
..............

   - bpo-35610(1): Replace now redundant .context_use_ps1 with
     .prompt_last_line.  This finishes change started in bpo-31858(2).

   - bpo-37038(3): Make idlelib.run runnable; add test clause.

   - bpo-36958(4): Print any argument other than None or int passed to
     SystemExit or sys.exit().

   - bpo-36807(5): When saving a file, call os.fsync() so bits are
     flushed to e.g.  USB drive.

   - bpo-32411(6): In browser.py, remove extraneous sorting by line
     number since dictionary was created in line number order.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35610

   (2) https://bugs.python.org/issue31858

   (3) https://bugs.python.org/issue37038

   (4) https://bugs.python.org/issue36958

   (5) https://bugs.python.org/issue36807

   (6) https://bugs.python.org/issue32411


File: python.info,  Node: 工具/示例<8>,  Next: C API<17>,  Prev: IDLE<20>,  Up: Python 3 8 0 beta 1

1.19.27.10 工具/示例
....................

   - bpo-37053(1): Handle strings like u"bar" correctly in
     Tools/parser/unparse.py.  Patch by Chih-Hsuan Yen.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue37053


File: python.info,  Node: C API<17>,  Prev: 工具/示例<8>,  Up: Python 3 8 0 beta 1

1.19.27.11 C API
................

   - bpo-36763(1): Implement the PEP 587(2) "Python Initialization
     Configuration".

   - bpo-36379(3): Fix crashes when attempting to use the `modulo'
     parameter when ‘__ipow__’ is implemented in C.

   - bpo-37107(4): Update *note PyObject_CallMethodObjArgs(): 1114. and
     ‘_PyObject_CallMethodIdObjArgs’ to use ‘_PyObject_GetMethod’ to
     avoid creating a bound method object in many cases.  Patch by
     Michael J. Sullivan.

   - bpo-36974(5): Implement PEP 590(6): Vectorcall: a fast calling
     protocol for CPython.  This is a new protocol to optimize calls of
     custom callable objects.

   - bpo-36763(7): ‘Py_Main()’ now returns the exitcode rather than
     calling ‘Py_Exit(exitcode)’ when calling ‘PyErr_Print()’ if the
     current exception type is ‘SystemExit’.

   - bpo-36922(8): Add new type flag ‘Py_TPFLAGS_METHOD_DESCRIPTOR’ for
     objects behaving like unbound methods.  These are objects
     supporting the optimization given by the
     ‘LOAD_METHOD’/‘CALL_METHOD’ opcodes.  See PEP 590.

   - bpo-36728(9): The ‘PyEval_ReInitThreads()’ function has been
     removed from the C API. It should not be called explicitly: use
     *note PyOS_AfterFork_Child(): 3ef. instead.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36763

   (2) https://www.python.org/dev/peps/pep-0587

   (3) https://bugs.python.org/issue36379

   (4) https://bugs.python.org/issue37107

   (5) https://bugs.python.org/issue36974

   (6) https://www.python.org/dev/peps/pep-0590

   (7) https://bugs.python.org/issue36763

   (8) https://bugs.python.org/issue36922

   (9) https://bugs.python.org/issue36728


File: python.info,  Node: Python 3 8 0 alpha 4,  Next: Python 3 8 0 alpha 3,  Prev: Python 3 8 0 beta 1,  Up: Changelog（更動日誌）

1.19.28 Python 3.8.0 alpha 4
----------------------------

`发布日期: 2019-05-06'

* Menu:

* 安全性: 安全性<16>.
* 核心与内置函数: 核心与内置函数<25>.
* 库: 库<27>.
* 文档: 文档<22>.
* 测试: 测试<21>.
* 构建: 构建<21>.
* Windows: Windows<21>.
* macOS: macOS<19>.
* IDLE: IDLE<21>.
* 工具/示例: 工具/示例<9>.
* C API: C API<18>.


File: python.info,  Node: 安全性<16>,  Next: 核心与内置函数<25>,  Up: Python 3 8 0 alpha 4

1.19.28.1 安全性
................

   - bpo-36742(1): 于函数 urlsplit() 中修复了对于预规格化字符的不当处理
     过程。

   - bpo-30458(2): 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.

   - bpo-35755(3): *note shutil.which(): fe6. now uses
     ‘os.confstr("CS_PATH")’ if available and if the ‘PATH’ environment
     variable is not set.  Remove also the current directory from
     ‘posixpath.defpath’.  On Unix, *note shutil.which(): fe6. and the
     *note subprocess: f9. module no longer search the executable in the
     current directory if the ‘PATH’ environment variable is not set.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36742

   (2) https://bugs.python.org/issue30458

   (3) https://bugs.python.org/issue35755


File: python.info,  Node: 核心与内置函数<25>,  Next: 库<27>,  Prev: 安全性<16>,  Up: Python 3 8 0 alpha 4

1.19.28.2 核心与内置函数
........................

   - bpo-36722(1): In debug build, import now also looks for C
     extensions compiled in release mode and for C extensions compiled
     in the stable ABI.

   - bpo-32849(2): Fix Python Initialization code on FreeBSD to detect
     properly when stdin file descriptor (fd 0) is invalid.

   - bpo-36623(3): Remove parser headers and related function
     declarations that lack implementations after the removal of pgen.

   - bpo-20180(4): ‘dict.pop()’ is now up to 33% faster thanks to
     Argument Clinic.  Patch by Inada Naoki.

   - bpo-36611(5): Debug memory allocators: disable serialno field by
     default from debug hooks on Python memory allocators to reduce the
     memory footprint by 5%.  Enable *note tracemalloc: 11d. 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 ‘PYMEM_DEBUG_SERIALNO’ defined to get back the
     field.

   - bpo-36588(6): On AIX, *note sys.platform: 3d3. doesn’t contain the
     major version anymore.  Always return ‘'aix'’, instead of ‘'aix3'’
     ..  ‘'aix7'’.  Since older Python versions include the version
     number, it is recommended to always use
     ‘sys.platform.startswith('aix')’.  Contributed by M. Felt.

   - bpo-36549(7): Change str.capitalize to use titlecase for the first
     character instead of uppercase.

   - bpo-36540(8): Implement PEP 570(9) (Python positional-only
     parameters).  Patch by Pablo Galindo.

   - bpo-36475(10): *note PyEval_AcquireLock(): 3d4. and *note
     PyEval_AcquireThread(): 3d5. now terminate the current thread if
     called while the interpreter is finalizing, making them consistent
     with *note PyEval_RestoreThread(): 3d6, *note
     Py_END_ALLOW_THREADS(): 3d7, and *note PyGILState_Ensure(): 3d8.

   - bpo-36504(11): 在 _ctypes.c’s ‘PyCArrayType_new()’ 中修复了“有符号
     整数”类型的溢出。

   - bpo-20844(12): 修复了含有经编码的 cookie 和换行符的脚本位于 Windows
     平台可能运行失败的问题。

   - bpo-24214(13): 修复了UTF-8增量解码器对surrogatepass的错误回调方法的
     支持

   - bpo-36452(14): Changing ‘dict’ keys during iteration of the dict
     itself, ‘keys()’, ‘values()’, or ‘items()’ will now be detected in
     certain corner cases where keys are deleted/added so that the
     number of keys isn’t changed.  A *note RuntimeError: 3dc. will be
     raised after ‘len(dict)’ iterations.  Contributed by Thomas Perl.

   - bpo-36459(15): 修复了由于tokenizer.c中的 ‘tok_nextc()’ 方法可能导致
     的两次 ‘PyMem_FREE()’ 调用。

   - bpo-36433(16): 修复了位于 classmethoddescr_call 的类型错误信息

   - bpo-36430(17): 修复了函数 *note itertools.count(): ce5. 中的潜在引
     用对象泄漏。

   - bpo-36440(18): Include node names in ‘ParserError’ messages,
     instead of numeric IDs.  Patch by A. Skrobov.

   - bpo-36143(19): Regenerate *note keyword: a6. from the Grammar and
     Tokens file using pgen.  Patch by Pablo Galindo.

   - bpo-18372(20): Add missing *note PyObject_GC_Track(): f06. calls in
     the *note pickle: ca. module.  Patch by Zackery Spytz.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36722

   (2) https://bugs.python.org/issue32849

   (3) https://bugs.python.org/issue36623

   (4) https://bugs.python.org/issue20180

   (5) https://bugs.python.org/issue36611

   (6) https://bugs.python.org/issue36588

   (7) https://bugs.python.org/issue36549

   (8) https://bugs.python.org/issue36540

   (9) https://www.python.org/dev/peps/pep-0570

   (10) https://bugs.python.org/issue36475

   (11) https://bugs.python.org/issue36504

   (12) https://bugs.python.org/issue20844

   (13) https://bugs.python.org/issue24214

   (14) https://bugs.python.org/issue36452

   (15) https://bugs.python.org/issue36459

   (16) https://bugs.python.org/issue36433

   (17) https://bugs.python.org/issue36430

   (18) https://bugs.python.org/issue36440

   (19) https://bugs.python.org/issue36143

   (20) https://bugs.python.org/issue18372


File: python.info,  Node: 库<27>,  Next: 文档<22>,  Prev: 核心与内置函数<25>,  Up: Python 3 8 0 alpha 4

1.19.28.3 库
............

   - bpo-35952(1): Fix pythoninfo when the compiler is missing.

   - bpo-28238(2): The ‘.find*()’ methods of xml.etree.ElementTree can
     now search for wildcards like ‘{*}tag’ and ‘{ns}*’ that match a tag
     in any namespace or all tags in a namespace.  Patch by Stefan
     Behnel.

   - bpo-26978(3): ‘pathlib.path.link_to()’ is now implemented.  It
     creates a hard link pointing to a path.

   - bpo-1613500(4): *note fileinput.FileInput: 3a4. now uses the input
     file mode to correctly set the output file mode (previously it was
     hardcoded to ‘'w'’) when ‘inplace=True’ is passed to its
     constructor.

   - bpo-36734(5): Fix compilation of ‘faulthandler.c’ on HP-UX.
     Initialize ‘stack_t current_stack’ to zero using ‘memset()’.

   - bpo-13611(6): The xml.etree.ElementTree packages gained support for
     C14N 2.0 serialisation.  Patch by Stefan Behnel.

   - bpo-36669(7): Add missing matrix multiplication operator support to
     weakref.proxy.

   - bpo-36676(8): 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.

   - bpo-36673(9): The TreeBuilder and XMLPullParser in
     xml.etree.ElementTree gained support for parsing comments and
     processing instructions.  Patch by Stefan Behnel.

   - bpo-36650(10): The C version of functools.lru_cache() was treating
     calls with an empty ‘**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.

   - bpo-28552(11): Fix *note distutils.sysconfig: 61. if *note
     sys.executable: 39d. is ‘None’ or an empty string: use *note
     os.getcwd(): 1119. to initialize ‘project_base’.  Fix also the
     distutils build command: don’t use *note sys.executable: 39d. if it
     is ‘None’ or an empty string.

   - bpo-35755(12): *note shutil.which(): fe6. and
     ‘distutils.spawn.find_executable()’ now use ‘os.confstr("CS_PATH")’
     if available instead of *note os.defpath: 111a, if the ‘PATH’
     environment variable is not set.  Moreover, don’t use
     ‘os.confstr("CS_PATH")’ nor *note os.defpath: 111a. if the ‘PATH’
     environment variable is set to an empty string.

   - bpo-25430(13): improve performance of ‘IPNetwork.__contains__()’

   - bpo-30485(14): 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.

   - bpo-36613(15): Fix *note asyncio: 9. wait() not removing callback
     if exception

   - bpo-36598(16): Fix ‘isinstance’ check for Mock objects with spec
     when the code is executed under tracing.  Patch by Karthikeyan
     Singaravelan.

   - bpo-18748(17): In development mode (*note -X: 290. ‘dev’) and in
     debug build, the *note io.IOBase: 30c. destructor now logs
     ‘close()’ exceptions.  These exceptions are silent by default in
     release mode.

   - bpo-36575(18): The ‘_lsprof’ module now uses internal timer same to
     ‘time.perf_counter()’ by default.  ‘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
     ‘perf_counter()’ is monotonic.  Patch by Inada Naoki.

   - bpo-33461(19): ‘json.loads’ now emits ‘DeprecationWarning’ when
     ‘encoding’ option is specified.  Patch by Matthias Bussonnier.

   - bpo-36559(20): The random module now prefers the lean internal
     _sha512 module over hashlib for seed(version=2) to optimize import
     time.

   - bpo-17561(21): Set backlog=None as the default for
     socket.create_server.

   - bpo-34373(22): Fix *note time.mktime(): c36. error handling on AIX
     for year before 1970.

   - bpo-36232(23): Improve error message when trying to open existing
     DBM database that actually doesn’t exist.  Patch by Marco Rougeth.

   - bpo-36546(24): Add statistics.quantiles()

   - bpo-36050(25): Optimized ‘http.client.HTTPResponse.read()’ for
     large response.  Patch by Inada Naoki.

   - bpo-36522(26): If `debuglevel' is set to >0 in *note http.client:
     93, print all values for headers with multiple values for the same
     header name.  Patch by Matt Houglum.

   - bpo-36492(27): Deprecated passing required arguments like `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.

   - bpo-27181(28): Add statistics.geometric_mean().

   - bpo-30427(29): ‘os.path.normcase()’ relies on ‘os.fspath()’ to
     check the type of its argument.  Redundant checks have been removed
     from its ‘posixpath.normcase()’ and ‘ntpath.normcase()’
     implementations.  Patch by Wolfgang Maier.

   - bpo-36385(30): 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.

   - bpo-36434(31): Errors during writing to a ZIP file no longer
     prevent to properly close it.

   - bpo-36407(32): Fixed wrong indentation writing for CDATA section in
     xml.dom.minidom.  Patch by Vladimir Surjaninov.

   - bpo-36326(33): inspect.getdoc() can now find docstrings for member
     objects when __slots__ is a dictionary.

   - bpo-36366(34): Calling ‘stop()’ on an unstarted or stopped *note
     unittest.mock.patch(): 877. object will now return *note None: 203.
     instead of raising *note RuntimeError: 3dc, making the method
     idempotent.  Patch by Karthikeyan Singaravelan.

   - bpo-36348(35): The ‘imap.IMAP4.logout()’ method no longer ignores
     silently arbitrary exceptions.

   - bpo-31904(36): Add time module support and fix test_time faiures
     for VxWorks.

   - bpo-36227(37): Added support for keyword arguments
     ‘default_namespace’ and ‘xml_declaration’ in functions
     ElementTree.tostring() and ElementTree.tostringlist().

   - bpo-36004(38): Added new alternate constructors *note
     datetime.date.fromisocalendar(): 2f5. and *note
     datetime.datetime.fromisocalendar(): 2f6, which construct date
     objects from ISO year, week number and weekday; these are the
     inverse of each class’s ‘isocalendar’ method.  Patch by Paul
     Ganssle.

   - bpo-35936(39): *note modulefinder: b4. no longer depends on the
     deprecated *note imp: 99. module, and the initializer for *note
     modulefinder.ModuleFinder: 111b. now has immutable default
     arguments.  Patch by Brandt Bucher.

   - bpo-35376(40): *note modulefinder: b4. correctly handles modules
     that have the same name as a bad package.  Patch by Brandt Bucher.

   - bpo-17396(41): *note modulefinder: b4. no longer crashes when
     encountering syntax errors in followed imports.  Patch by Brandt
     Bucher.

   - bpo-35934(42): Added *note create_server(): 34b. and *note
     has_dualstack_ipv6(): 34c. 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(43).)

   - bpo-23078(44): Add support for *note classmethod(): 309. and *note
     staticmethod(): 30a. to *note unittest.mock.create_autospec():
     1087.  Initial patch by Felipe Ochoa.

   - bpo-35416(45): Fix potential resource warnings in distutils.  Patch
     by Mickaël Schoentgen.

   - bpo-25451(46): Add transparency methods to ‘tkinter.PhotoImage’.
     Patch by Zackery Spytz.

   - bpo-35082(47): Don’t return deleted attributes when calling dir on
     a *note unittest.mock.Mock: 373.

   - bpo-34547(48): *note wsgiref.handlers.BaseHandler: 1107. now
     handles abrupt client connection terminations gracefully.  Patch by
     Petter Strandmark.

   - bpo-31658(49): *note xml.sax.parse(): 111c. now supports *note
     path-like: 472.  Patch by Mickaël Schoentgen.

   - bpo-34139(50): Remove stale unix datagram socket before binding

   - bpo-33530(51): Implemented Happy Eyeballs in
     ‘asyncio.create_connection()’.  Added two new arguments,
     `happy_eyeballs_delay' and `interleave', to specify Happy Eyeballs
     behavior.

   - bpo-33291(52): Do not raise AttributeError when calling the inspect
     functions isgeneratorfunction, iscoroutinefunction,
     isasyncgenfunction on a method created from an arbitrary callable.
     Instead, return False.

   - bpo-31310(53): Fix the multiprocessing.semaphore_tracker so it is
     reused by child processes

   - bpo-31292(54): 为包含 ‘include’ 指令的文件修复 ‘setup.py check
     --restructuredtext’。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35952

   (2) https://bugs.python.org/issue28238

   (3) https://bugs.python.org/issue26978

   (4) https://bugs.python.org/issue1613500

   (5) https://bugs.python.org/issue36734

   (6) https://bugs.python.org/issue13611

   (7) https://bugs.python.org/issue36669

   (8) https://bugs.python.org/issue36676

   (9) https://bugs.python.org/issue36673

   (10) https://bugs.python.org/issue36650

   (11) https://bugs.python.org/issue28552

   (12) https://bugs.python.org/issue35755

   (13) https://bugs.python.org/issue25430

   (14) https://bugs.python.org/issue30485

   (15) https://bugs.python.org/issue36613

   (16) https://bugs.python.org/issue36598

   (17) https://bugs.python.org/issue18748

   (18) https://bugs.python.org/issue36575

   (19) https://bugs.python.org/issue33461

   (20) https://bugs.python.org/issue36559

   (21) https://bugs.python.org/issue17561

   (22) https://bugs.python.org/issue34373

   (23) https://bugs.python.org/issue36232

   (24) https://bugs.python.org/issue36546

   (25) https://bugs.python.org/issue36050

   (26) https://bugs.python.org/issue36522

   (27) https://bugs.python.org/issue36492

   (28) https://bugs.python.org/issue27181

   (29) https://bugs.python.org/issue30427

   (30) https://bugs.python.org/issue36385

   (31) https://bugs.python.org/issue36434

   (32) https://bugs.python.org/issue36407

   (33) https://bugs.python.org/issue36326

   (34) https://bugs.python.org/issue36366

   (35) https://bugs.python.org/issue36348

   (36) https://bugs.python.org/issue31904

   (37) https://bugs.python.org/issue36227

   (38) https://bugs.python.org/issue36004

   (39) https://bugs.python.org/issue35936

   (40) https://bugs.python.org/issue35376

   (41) https://bugs.python.org/issue17396

   (42) https://bugs.python.org/issue35934

   (43) https://bugs.python.org/issue17561

   (44) https://bugs.python.org/issue23078

   (45) https://bugs.python.org/issue35416

   (46) https://bugs.python.org/issue25451

   (47) https://bugs.python.org/issue35082

   (48) https://bugs.python.org/issue34547

   (49) https://bugs.python.org/issue31658

   (50) https://bugs.python.org/issue34139

   (51) https://bugs.python.org/issue33530

   (52) https://bugs.python.org/issue33291

   (53) https://bugs.python.org/issue31310

   (54) https://bugs.python.org/issue31292


File: python.info,  Node: 文档<22>,  Next: 测试<21>,  Prev: 库<27>,  Up: Python 3 8 0 alpha 4

1.19.28.4 文档
..............

   - bpo-36625(1): Remove obsolete comments from docstrings in
     fractions.Fraction

   - bpo-30840(2): Document relative imports

   - bpo-36523(3): Add docstring for io.IOBase.writelines().

   - bpo-36425(4): 新增的文档翻译: 简体中文(5).

   - bpo-36345(6): Avoid the duplication of code from
     ‘Tools/scripts/serve.py’ in using the ‘literalinclude’ directive
     for the basic wsgiref-based web server in the documentation of
     *note wsgiref: 135.  Contributed by Stéphane Wirtel.

   - bpo-36345(7): Using the code of the ‘Tools/scripts/serve.py’ script
     as an example in the *note wsgiref: 135. documentation.
     Contributed by Stéphane Wirtel.

   - bpo-36157(8): Added Documention for PyInterpreterState_Main().

   - bpo-33043(9): 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.

   - bpo-35581(10): @typing.type_check_only now allows type stubs to
     mark functions and classes not available during runtime.

   - bpo-33832(11): Add glossary entry for ’magic method’.

   - bpo-32913(12): Added re.Match.groupdict example to regex HOWTO.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36625

   (2) https://bugs.python.org/issue30840

   (3) https://bugs.python.org/issue36523

   (4) https://bugs.python.org/issue36425

   (5) https://docs.python.org/zh-cn/

   (6) https://bugs.python.org/issue36345

   (7) https://bugs.python.org/issue36345

   (8) https://bugs.python.org/issue36157

   (9) https://bugs.python.org/issue33043

   (10) https://bugs.python.org/issue35581

   (11) https://bugs.python.org/issue33832

   (12) https://bugs.python.org/issue32913


File: python.info,  Node: 测试<21>,  Next: 构建<21>,  Prev: 文档<22>,  Up: Python 3 8 0 alpha 4

1.19.28.5 测试
..............

   - bpo-36719(1): regrtest now always detects uncollectable objects.
     Previously, the check was only enabled by ‘--findleaks’.  The check
     now also works with ‘-jN/--multiprocess N’.  ‘--findleaks’ becomes
     a deprecated alias to ‘--fail-env-changed’.

   - bpo-36725(2): 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.

   - bpo-36454(3): 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.

   - bpo-32424(4): Improve test coverage for xml.etree.ElementTree.
     Patch by Gordon P. Hemsley.

   - bpo-32424(5): Fix typo in test_cyclic_gc() test for
     xml.etree.ElementTree.  Patch by Gordon P. Hemsley.

   - bpo-36635(6): Add a new ‘_testinternalcapi’ module to test the
     internal C API.

   - bpo-36629(7): Fix ‘test_imap4_host_default_value()’ of
     ‘test_imaplib’: catch also *note errno.ENETUNREACH: 111f. error.

   - bpo-36611(8): Fix ‘test_sys.test_getallocatedblocks()’ when *note
     tracemalloc: 11d. is enabled.

   - bpo-36560(9): 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.

   - bpo-36565(10): Fix reference hunting (‘python3 -m test -R 3:3’)
     when Python has no built-in abc module.

   - bpo-31904(11): Port test_resource to VxWorks: skip tests cases
     setting RLIMIT_FSIZE and RLIMIT_CPU.

   - bpo-31904(12): Fix test_tabnanny on VxWorks: adjust ENOENT error
     message.

   - bpo-36436(13): Fix ‘_testcapi.pymem_buffer_overflow()’: handle
     memory allocation failure.

   - bpo-31904(14): Fix test_utf8_mode on VxWorks: Python always use
     UTF-8 on VxWorks.

   - bpo-36341(15): Fix tests that may fail with PermissionError upon
     calling bind() on AF_UNIX sockets.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36719

   (2) https://bugs.python.org/issue36725

   (3) https://bugs.python.org/issue36454

   (4) https://bugs.python.org/issue32424

   (5) https://bugs.python.org/issue32424

   (6) https://bugs.python.org/issue36635

   (7) https://bugs.python.org/issue36629

   (8) https://bugs.python.org/issue36611

   (9) https://bugs.python.org/issue36560

   (10) https://bugs.python.org/issue36565

   (11) https://bugs.python.org/issue31904

   (12) https://bugs.python.org/issue31904

   (13) https://bugs.python.org/issue36436

   (14) https://bugs.python.org/issue31904

   (15) https://bugs.python.org/issue36341


File: python.info,  Node: 构建<21>,  Next: Windows<21>,  Prev: 测试<21>,  Up: Python 3 8 0 alpha 4

1.19.28.6 构建
..............

   - bpo-36747(1): Remove the stale scriptsinstall Makefile target.

   - bpo-21536(2): On Unix, C extensions are no longer linked to
     libpython except on Android and Cygwin.

     通过共享库的 Python 构建的 C 扩展现在可以被静态链接的 Python 加载了
     。

     When Python is embedded, ‘libpython’ must not be loaded with
     ‘RTLD_LOCAL’, but ‘RTLD_GLOBAL’ instead.  Previously, using
     ‘RTLD_LOCAL’, it was already not possible to load C extensions
     which were not linked to ‘libpython’, such as C extensions of the
     standard library built by the ‘*shared*’ section of
     ‘Modules/Setup’.

     distutils，python-config 和 python-config.py 已被修改。

   - bpo-36707(3): ‘./configure --with-pymalloc’ no longer adds the ‘m’
     flag to SOABI (sys.implementation.cache_tag).  Enabling or
     disabling pymalloc has no impact on the ABI.

   - bpo-36635(4): Change ‘PyAPI_FUNC(type)’, ‘PyAPI_DATA(type)’ and
     ‘PyMODINIT_FUNC’ macros of ‘pyport.h’ when ‘Py_BUILD_CORE_MODULE’
     is defined.  The ‘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.

   - bpo-31904(5): Don’t build the ‘_crypt’ extension on VxWorks.

   - bpo-36618(6): Add ‘-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 ‘CFLAGS’ and not just
     ‘CFLAGS_NODIST’, since third party C extensions can have the same
     issue.

   - bpo-36605(7): ‘make tags’ and ‘make TAGS’ now also parse
     ‘Modules/_io/*.c’ and ‘Modules/_io/*.h’.

   - bpo-36465(8): Release builds and debug builds are now ABI
     compatible: defining the ‘Py_DEBUG’ macro no longer implies the
     ‘Py_TRACE_REFS’ macro, which introduces the only ABI
     incompatibility.  The ‘Py_TRACE_REFS’ macro, which adds the
     ‘sys.getobjects()’ function and the *note PYTHONDUMPREFS: 293.
     environment variable, can be set using the new ‘./configure
     --with-trace-refs’ build option.

   - bpo-36577(9): setup.py now correctly reports missing OpenSSL
     headers and libraries again.

   - bpo-36544(10): Fix regression introduced in bpo-36146(11)
     refactoring setup.py

   - bpo-36508(12): ‘python-config --ldflags’ no longer includes flags
     of the ‘LINKFORSHARED’ variable.  The ‘LINKFORSHARED’ variable must
     only be used to build executables.

   - bpo-36503(13): Remove references to "aix3" and "aix4".  Patch by M.
     Felt.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36747

   (2) https://bugs.python.org/issue21536

   (3) https://bugs.python.org/issue36707

   (4) https://bugs.python.org/issue36635

   (5) https://bugs.python.org/issue31904

   (6) https://bugs.python.org/issue36618

   (7) https://bugs.python.org/issue36605

   (8) https://bugs.python.org/issue36465

   (9) https://bugs.python.org/issue36577

   (10) https://bugs.python.org/issue36544

   (11) https://bugs.python.org/issue36146

   (12) https://bugs.python.org/issue36508

   (13) https://bugs.python.org/issue36503


File: python.info,  Node: Windows<21>,  Next: macOS<19>,  Prev: 构建<21>,  Up: Python 3 8 0 alpha 4

1.19.28.7 Windows
.................

   - bpo-35920(1): 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.

   - bpo-36649(2): Remove trailing spaces for registry keys when
     installed via the Store.

   - bpo-34144(3): Fixed activate.bat to correctly update codepage when
     chcp.com returns dots in output.  Patch by Lorenz Mende.

   - bpo-36509(4): 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.

   - bpo-35941(5): 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.

   - bpo-36441(6): Fixes creating a venv when debug binaries are
     installed.

   - bpo-36085(7): Enable better DLL resolution on Windows by using safe
     DLL search paths and adding *note os.add_dll_directory(): 2f3.

   - bpo-36010(8): Add the venv standard library module to the nuget
     distribution for Windows.

   - bpo-29515(9): 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

   - bpo-35947(10): Added current version of libffi to
     cpython-source-deps.  Change _ctypes to use current version of
     libffi on Windows.

   - bpo-34060(11): Report system load when running test suite on
     Windows.  Patch by Ammar Askar.  Based on prior work by Jeremy
     Kloth.

   - bpo-31512(12): With the Windows 10 Creators Update, non-elevated
     users can now create symlinks as long as the computer has Developer
     Mode enabled.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35920

   (2) https://bugs.python.org/issue36649

   (3) https://bugs.python.org/issue34144

   (4) https://bugs.python.org/issue36509

   (5) https://bugs.python.org/issue35941

   (6) https://bugs.python.org/issue36441

   (7) https://bugs.python.org/issue36085

   (8) https://bugs.python.org/issue36010

   (9) https://bugs.python.org/issue29515

   (10) https://bugs.python.org/issue35947

   (11) https://bugs.python.org/issue34060

   (12) https://bugs.python.org/issue31512


File: python.info,  Node: macOS<19>,  Next: IDLE<21>,  Prev: Windows<21>,  Up: Python 3 8 0 alpha 4

1.19.28.8 macOS
...............

   - bpo-34602(1): Avoid failures setting macOS stack resource limit
     with resource.setrlimit.  This reverts an earlier fix for
     bpo-18075(2) which forced a non-default stack size when building
     the interpreter executable on macOS.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue34602

   (2) https://bugs.python.org/issue18075


File: python.info,  Node: IDLE<21>,  Next: 工具/示例<9>,  Prev: macOS<19>,  Up: Python 3 8 0 alpha 4

1.19.28.9 IDLE
..............

   - bpo-36429(1): Fix starting IDLE with pyshell.  Add idlelib.pyshell
     alias at top; remove pyshell alias at bottom.  Remove obsolete
     __name__==’__main__’ command.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36429


File: python.info,  Node: 工具/示例<9>,  Next: C API<18>,  Prev: IDLE<21>,  Up: Python 3 8 0 alpha 4

1.19.28.10 工具/示例
....................

   - bpo-14546(1): Fix the argument handling in Tools/scripts/lll.py.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue14546


File: python.info,  Node: C API<18>,  Prev: 工具/示例<9>,  Up: Python 3 8 0 alpha 4

1.19.28.11 C API
................

   - bpo-36763(1): Fix memory leak in *note
     Py_SetStandardStreamEncoding(): a0a.: release memory if the
     function is called twice.

   - bpo-36641(2): ‘PyDoc_VAR(name)’ and ‘PyDoc_STRVAR(name,str)’ now
     create ‘static const char name[]’ instead of ‘static char name[]’.
     Patch by Inada Naoki.

   - bpo-36389(3): Change the value of ‘CLEANBYTE’, ‘DEADDYTE’ and
     ‘FORBIDDENBYTE’ internal constants used by debug hooks on Python
     memory allocators (*note PyMem_SetupDebugHooks(): 603. function).
     Byte patterns ‘0xCB’, ‘0xDB’ and ‘0xFB’ have been replaced with
     ‘0xCD’, ‘0xDD’ and ‘0xFD’ to use the same values than Windows CRT
     debug ‘malloc()’ and ‘free()’.

   - bpo-36443(4): Since Python 3.7.0, calling *note Py_DecodeLocale():
     53e. before *note Py_Initialize(): 20f. produces mojibake if the
     ‘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 ‘_Py_PreInitialize()’
     API with ‘_PyPreConfig’.

   - bpo-36025(5): Fixed an accidental change to the datetime C API
     where the arguments to the *note PyDate_FromTimestamp(): 1126.
     function were incorrectly interpreted as a single timestamp rather
     than an arguments tuple, which causes existing code to start
     raising *note TypeError: 1fe.  The backwards-incompatible change
     was only present in alpha releases of Python 3.8.  Patch by Paul
     Ganssle.

   - bpo-35810(6): Modify ‘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

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36763

   (2) https://bugs.python.org/issue36641

   (3) https://bugs.python.org/issue36389

   (4) https://bugs.python.org/issue36443

   (5) https://bugs.python.org/issue36025

   (6) https://bugs.python.org/issue35810


File: python.info,  Node: Python 3 8 0 alpha 3,  Next: Python 3 8 0 alpha 2,  Prev: Python 3 8 0 alpha 4,  Up: Changelog（更動日誌）

1.19.29 Python 3.8.0 alpha 3
----------------------------

`发布日期： 2019-03-25'

* Menu:

* 安全性: 安全性<17>.
* 核心与内置函数: 核心与内置函数<26>.
* 库: 库<28>.
* 文档: 文档<23>.
* 测试: 测试<22>.
* 构建: 构建<22>.
* Windows: Windows<22>.
* IDLE: IDLE<22>.
* 工具/示例: 工具/示例<10>.
* C API: C API<19>.


File: python.info,  Node: 安全性<17>,  Next: 核心与内置函数<26>,  Up: Python 3 8 0 alpha 3

1.19.29.1 安全性
................

   - bpo-36216(1): 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.

   - bpo-35121(2): 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 *note
     http.cookiejar.DefaultCookiePolicy: 1129. policy.  Patch by
     Karthikeyan Singaravelan.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36216

   (2) https://bugs.python.org/issue35121


File: python.info,  Node: 核心与内置函数<26>,  Next: 库<28>,  Prev: 安全性<17>,  Up: Python 3 8 0 alpha 3

1.19.29.2 核心与内置函数
........................

   - bpo-36421(1): Fix a possible double decref in _ctypes.c’s
     ‘PyCArrayType_new()’.

   - bpo-36412(2): Fix a possible crash when creating a new dictionary.

   - bpo-36398(3): Fix a possible crash in ‘structseq_repr()’.

   - bpo-36256(4): 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.

   - bpo-36365(5): repr(structseq) is no longer limited to 512 bytes.

   - bpo-36374(6): Fix a possible null pointer dereference in
     ‘merge_consts_recursive()’.  Patch by Zackery Spytz.

   - bpo-36236(7): 在 Python 初始化时，如果当前目录被移除，则它将不再会
     被添加到 *note sys.path: 261. 中。

   - bpo-36352(8): Python initialization now fails with an error, rather
     than silently truncating paths, if a path is too long.

   - bpo-36301(9): Python initialization now fails if decoding
     ‘pybuilddir.txt’ configuration file fails at startup.

   - bpo-36333(10): Fix leak in _PyRuntimeState_Fini.  Contributed by
     Stéphane Wirtel.

   - bpo-36332(11): The builtin *note compile(): 2e7. can now handle AST
     objects that contain assignment expressions.  Patch by Pablo
     Galindo.

   - bpo-36282(12): Improved error message for too much positional
     arguments in some builtin functions.

   - bpo-30040(13): New empty dict uses fewer memory for now.  It used
     more memory than empty dict created by ‘dict.clear()’.  And empty
     dict creation and deletion is about 2x faster.  Patch by Inada
     Naoki.

   - bpo-36262(14): 修复了在 ‘float(str)’, ‘complex(str)’, *note
     pickle.load(): 6b9, *note marshal.load(): 112b. 等所用的函数
     ‘_Py_dg_strtod()’ 中进行从字符串到浮点数的转换时偶有发生的一个内存
     泄漏问题。

   - bpo-36252(15): Update Unicode databases to version 12.0.0.

   - bpo-36218(16): Fix a segfault occurring when sorting a list of
     heterogeneous values.  Patch contributed by Rémi Lapeyre and Elliot
     Gorokhovsky.

   - bpo-36188(17): Cleaned up left-over vestiges of Python 2 unbound
     method handling in method objects and documentation.  Patch by
     Martijn Pieters

   - bpo-36124(18): 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.

   - bpo-35975(19): Add a ‘feature_version’ flag to ‘ast.parse()’
     (documented) and ‘compile()’ (hidden) that allows tweaking the
     parser to support older versions of the grammar.  In particular, if
     ‘feature_version’ is 5 or 6, the hacks for the ‘async’ and ‘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 ‘NAME’ tokens that the parser driver
     recognizes.)

   - bpo-31904(20): Use UTF-8 as the system encoding on VxWorks.

   - bpo-36048(21): The *note __index__(): 2c2. special method will be
     used instead of *note __int__(): 2c3. for implicit conversion of
     Python numbers to C integers.  Using the ‘__int__()’ method in
     implicit conversions has been deprecated.

   - bpo-35808(22): Retire pgen and use a modified version of pgen2 to
     generate the parser.  Patch by Pablo Galindo.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36421

   (2) https://bugs.python.org/issue36412

   (3) https://bugs.python.org/issue36398

   (4) https://bugs.python.org/issue36256

   (5) https://bugs.python.org/issue36365

   (6) https://bugs.python.org/issue36374

   (7) https://bugs.python.org/issue36236

   (8) https://bugs.python.org/issue36352

   (9) https://bugs.python.org/issue36301

   (10) https://bugs.python.org/issue36333

   (11) https://bugs.python.org/issue36332

   (12) https://bugs.python.org/issue36282

   (13) https://bugs.python.org/issue30040

   (14) https://bugs.python.org/issue36262

   (15) https://bugs.python.org/issue36252

   (16) https://bugs.python.org/issue36218

   (17) https://bugs.python.org/issue36188

   (18) https://bugs.python.org/issue36124

   (19) https://bugs.python.org/issue35975

   (20) https://bugs.python.org/issue31904

   (21) https://bugs.python.org/issue36048

   (22) https://bugs.python.org/issue35808


File: python.info,  Node: 库<28>,  Next: 文档<23>,  Prev: 核心与内置函数<26>,  Up: Python 3 8 0 alpha 3

1.19.29.3 库
............

   - bpo-36401(1): The class documentation created by pydoc now has a
     separate section for readonly properties.

   - bpo-36320(2): 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.

   - bpo-34745(3): Fix *note asyncio: 9. ssl memory issues caused by
     circular references

   - bpo-36324(4): Add method to statistics.NormalDist for computing the
     inverse cumulative normal distribution.

   - bpo-36321(5): 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.

   - bpo-36297(6): "unicode_internal" codec is removed.  It was
     deprecated since Python 3.3.  Patch by Inada Naoki.

   - bpo-36298(7): Raise ModuleNotFoundError in pyclbr when a module
     can’t be found.  Thanks to ’mental’ for the bug report.

   - bpo-36268(8): Switch the default format used for writing tars with
     mod:*note tarfile: 101. to the modern POSIX.1-2001 pax standard,
     from the vendor-specific GNU. Contributed by C.A.M. Gerlach.

   - bpo-36285(9): Fix integer overflows in the array module.  Patch by
     Stephan Hohe.

   - bpo-31904(10): Add _signal module support for VxWorks.

   - bpo-36272(11): *note logging: aa. does not silently ignore
     RecursionError anymore.  Patch contributed by Rémi Lapeyre.

   - bpo-36280(12): 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.

   - bpo-35931(13): The *note pdb: c9. ‘debug’ command now gracefully
     handles all exceptions.

   - bpo-36251(14): Fix format strings used for stderrprinter and
     re.Match reprs.  Patch by Stephan Hohe.

   - bpo-36235(15): Fix ‘CFLAGS’ in ‘customize_compiler()’ of
     ‘distutils.sysconfig’: when the ‘CFLAGS’ environment variable is
     defined, don’t override ‘CFLAGS’ variable with the ‘OPT’ variable
     anymore.  Initial patch written by David Malcolm.

   - bpo-35807(16): Update ensurepip to install pip 19.0.3 and
     setuptools 40.8.0.

   - bpo-36139(17): Release GIL when closing *note mmap: 31c. objects.

   - bpo-36179(18): Fix two unlikely reference leaks in _hashopenssl.
     The leaks only occur in out-of-memory cases.

   - bpo-36169(19): Add overlap() method to statistics.NormalDist.
     Computes the overlapping coefficient for two normal distributions.

   - bpo-36103(20): Default buffer size used by ‘shutil.copyfileobj()’
     is changed from 16 KiB to 64 KiB on non-Windows platform to reduce
     system call overhead.  Contributed by Inada Naoki.

   - bpo-36130(21): Fix ‘pdb’ with ‘skip=...’ when stepping into a frame
     without a ‘__name__’ global.  Patch by Anthony Sottile.

   - bpo-35652(22): shutil.copytree(copy_function=...)  erroneously pass
     DirEntry instead of a path string.

   - bpo-35178(23): Ensure custom *note warnings.formatwarning(): 112d.
     function can receive ‘line’ as positional argument.  Based on patch
     by Tashrif Billah.

   - bpo-36106(24): Resolve potential name clash with libm’s sinpi().
     Patch by Dmitrii Pasechnik.

   - bpo-36091(25): Clean up reference to async generator in Lib/types.
     Patch by Henry Chen.

   - bpo-36043(26): ‘FileCookieJar’ supports *note path-like object:
     472.  Contributed by Stéphane Wirtel

   - bpo-35899(27): 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.

   - bpo-21269(28): Add ‘args’ and ‘kwargs’ properties to mock call
     objects.  Contributed by Kumar Akshay.

   - bpo-30670(29): *note pprint.pp: 340. has been added to pretty-print
     objects with dictionary keys being sorted with their insertion
     order by default.  Parameter `sort_dicts' has been added to *note
     pprint.pprint: 341, *note pprint.pformat: 97d. and *note
     pprint.PrettyPrinter: 97c.  Contributed by Rémi Lapeyre.

   - bpo-35843(30): Implement ‘__getitem__’ for ‘_NamespacePath’.  Patch
     by Anthony Sottile.

   - bpo-35802(31): Clean up code which checked presence of ‘os.stat’ /
     ‘os.lstat’ / ‘os.chmod’ which are always present.  Patch by Anthony
     Sottile.

   - bpo-35715(32): Librates the return value of a ProcessPoolExecutor
     _process_worker after it’s no longer needed to free memory

   - bpo-35493(33): Use *note multiprocessing.connection.wait(): b01.
     instead of polling each 0.2 seconds for worker updates in
     ‘multiprocessing.Pool’.  Patch by Pablo Galindo.

   - bpo-35661(34): Store the venv prompt in pyvenv.cfg.

   - bpo-35121(35): 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.

   - bpo-21478(36): Calls to a child function created with *note
     unittest.mock.create_autospec(): 1087. should propagate to the
     parent.  Patch by Karthikeyan Singaravelan.

   - bpo-35198(37): Fix C++ extension compilation on AIX

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36401

   (2) https://bugs.python.org/issue36320

   (3) https://bugs.python.org/issue34745

   (4) https://bugs.python.org/issue36324

   (5) https://bugs.python.org/issue36321

   (6) https://bugs.python.org/issue36297

   (7) https://bugs.python.org/issue36298

   (8) https://bugs.python.org/issue36268

   (9) https://bugs.python.org/issue36285

   (10) https://bugs.python.org/issue31904

   (11) https://bugs.python.org/issue36272

   (12) https://bugs.python.org/issue36280

   (13) https://bugs.python.org/issue35931

   (14) https://bugs.python.org/issue36251

   (15) https://bugs.python.org/issue36235

   (16) https://bugs.python.org/issue35807

   (17) https://bugs.python.org/issue36139

   (18) https://bugs.python.org/issue36179

   (19) https://bugs.python.org/issue36169

   (20) https://bugs.python.org/issue36103

   (21) https://bugs.python.org/issue36130

   (22) https://bugs.python.org/issue35652

   (23) https://bugs.python.org/issue35178

   (24) https://bugs.python.org/issue36106

   (25) https://bugs.python.org/issue36091

   (26) https://bugs.python.org/issue36043

   (27) https://bugs.python.org/issue35899

   (28) https://bugs.python.org/issue21269

   (29) https://bugs.python.org/issue30670

   (30) https://bugs.python.org/issue35843

   (31) https://bugs.python.org/issue35802

   (32) https://bugs.python.org/issue35715

   (33) https://bugs.python.org/issue35493

   (34) https://bugs.python.org/issue35661

   (35) https://bugs.python.org/issue35121

   (36) https://bugs.python.org/issue21478

   (37) https://bugs.python.org/issue35198


File: python.info,  Node: 文档<23>,  Next: 测试<22>,  Prev: 库<28>,  Up: Python 3 8 0 alpha 3

1.19.29.4 文档
..............

   - bpo-36329(1): Declare the path of the Python binary for the usage
     of ‘Tools/scripts/serve.py’ when executing ‘make -C Doc/ serve’.
     Contributed by Stéphane Wirtel

   - bpo-36138(2): Improve documentation about converting
     datetime.timedelta to scalars.

   - bpo-21314(3): 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

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36329

   (2) https://bugs.python.org/issue36138

   (3) https://bugs.python.org/issue21314


File: python.info,  Node: 测试<22>,  Next: 构建<22>,  Prev: 文档<23>,  Up: Python 3 8 0 alpha 3

1.19.29.5 测试
..............

   - bpo-36234(1): test_posix.PosixUidGidTests: add tests for invalid
     uid/gid type (str).  Initial patch written by David Malcolm.

   - bpo-29571(2): Fix ‘test_re.test_locale_flag()’: use
     ‘locale.getpreferredencoding()’ rather than ‘locale.getlocale()’ to
     get the locale encoding.  With some locales, ‘locale.getlocale()’
     returns the wrong encoding.

   - bpo-36123(3): Fix race condition in test_socket.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36234

   (2) https://bugs.python.org/issue29571

   (3) https://bugs.python.org/issue36123


File: python.info,  Node: 构建<22>,  Next: Windows<22>,  Prev: 测试<22>,  Up: Python 3 8 0 alpha 3

1.19.29.6 构建
..............

   - bpo-36356(1): Fix leaks that led to build failure when configured
     with address sanitizer.

   - bpo-36146(2): Add ‘TEST_EXTENSIONS’ constant to ‘setup.py’ to allow
     to not build test extensions like ‘_testcapi’.

   - bpo-36146(3): Fix setup.py on macOS: only add ‘/usr/include/ffi’ to
     include directories of _ctypes, not for all extensions.

   - bpo-31904(4): Enable build system to cross-build for VxWorks RTOS.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36356

   (2) https://bugs.python.org/issue36146

   (3) https://bugs.python.org/issue36146

   (4) https://bugs.python.org/issue31904


File: python.info,  Node: Windows<22>,  Next: IDLE<22>,  Prev: 构建<22>,  Up: Python 3 8 0 alpha 3

1.19.29.7 Windows
.................

   - bpo-36312(1): Fixed decoders for the following code pages: 50220,
     50221, 50222, 50225, 50227, 50229, 57002 through 57011, 65000 and
     42.

   - bpo-36264(2): Don’t honor POSIX ‘HOME’ in ‘os.path.expanduser’ on
     windows.  Patch by Anthony Sottile.

   - bpo-24643(3): Fix name collisions due to ‘#define timezone
     _timezone’ in PC/pyconfig.h.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36312

   (2) https://bugs.python.org/issue36264

   (3) https://bugs.python.org/issue24643


File: python.info,  Node: IDLE<22>,  Next: 工具/示例<10>,  Prev: Windows<22>,  Up: Python 3 8 0 alpha 3

1.19.29.8 IDLE
..............

   - bpo-36405(1): Use dict unpacking in idlelib.

   - bpo-36396(2): Remove fgBg param of idlelib.config.GetHighlight().
     This param was only used twice and changed the return type.

   - bpo-36176(3): 修复 IDLE 自动补全和 calltip 悬浮窗的颜色. 避免与
     Linux 暗色主题冲突 (略微加深了calltip 的背景颜色).

   - bpo-23205(4): For the grep module, add tests for findfiles,
     refactor findfiles to be a module-level function, and refactor
     findfiles to use os.walk.

   - bpo-23216(5): 将文档字符串添加到IDLE 的搜索模块。

   - bpo-36152(6): Remove colorizer.ColorDelegator.close_when_done and
     the corresponding argument of .close().  In IDLE, both have always
     been None or False since 2007.

   - bpo-32129(7): Avoid blurry IDLE application icon on macOS with Tk
     8.6.  Patch by Kevin Walzer.

   - bpo-36096(8): Refactor class variables to instance variables in
     colorizer.

   - bpo-30348(9): Increase test coverage of idlelib.autocomplete by
     30%.  Patch by Louie Lu

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36405

   (2) https://bugs.python.org/issue36396

   (3) https://bugs.python.org/issue36176

   (4) https://bugs.python.org/issue23205

   (5) https://bugs.python.org/issue23216

   (6) https://bugs.python.org/issue36152

   (7) https://bugs.python.org/issue32129

   (8) https://bugs.python.org/issue36096

   (9) https://bugs.python.org/issue30348


File: python.info,  Node: 工具/示例<10>,  Next: C API<19>,  Prev: IDLE<22>,  Up: Python 3 8 0 alpha 3

1.19.29.9 工具/示例
...................

   - bpo-35132(1): Fix py-list and py-bt commands of python-gdb.py on
     gdb7.

   - bpo-32217(2): Fix freeze script on Windows.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35132

   (2) https://bugs.python.org/issue32217


File: python.info,  Node: C API<19>,  Prev: 工具/示例<10>,  Up: Python 3 8 0 alpha 3

1.19.29.10 C API
................

   - bpo-36381(1): Raise ‘DeprecationWarning’ when ’#’ formats are used
     for building or parsing values without ‘PY_SSIZE_T_CLEAN’.

   - bpo-36142(2): The whole coreconfig.h header is now excluded from
     Py_LIMITED_API. Move functions definitions into a new internal
     pycore_coreconfig.h header.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36381

   (2) https://bugs.python.org/issue36142


File: python.info,  Node: Python 3 8 0 alpha 2,  Next: Python 3 8 0 alpha 1,  Prev: Python 3 8 0 alpha 3,  Up: Changelog（更動日誌）

1.19.30 Python 3.8.0 alpha 2
----------------------------

`发布日期: 2019-02-25'

* Menu:

* 核心与内置函数: 核心与内置函数<27>.
* 库: 库<29>.
* 文档: 文档<24>.
* 测试: 测试<23>.
* Windows: Windows<23>.
* IDLE: IDLE<23>.


File: python.info,  Node: 核心与内置函数<27>,  Next: 库<29>,  Up: Python 3 8 0 alpha 2

1.19.30.1 核心与内置函数
........................

   - bpo-36052(1): Raise a *note SyntaxError: 559. when assigning a
     value to *note __debug__: 1137. with the Assignment Operator.
     Contributed by Stéphane Wirtel and Pablo Galindo.

   - bpo-36012(2): Doubled the speed of class variable writes.  When a
     non-dunder attribute was updated, there was an unnecessary call to
     update slots.

   - bpo-35942(3): The error message emitted when returning invalid
     types from ‘__fspath__’ in interfaces that allow passing *note
     PathLike: 5e5. objects has been improved and now it does explain
     the origin of the error.

   - bpo-36016(4): ‘gc.get_objects’ can now receive an optional
     parameter indicating a generation to get objects from.  Patch by
     Pablo Galindo.

   - bpo-1054041(5): 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.

   - bpo-35992(6): Fix ‘__class_getitem__()’ not being called on a class
     with a custom non-subscriptable metaclass.

   - bpo-35993(7): Fix a crash on fork when using subinterpreters.
     Contributed by Stéphane Wirtel

   - bpo-35991(8): Fix a potential double free in
     Modules/_randommodule.c.

   - bpo-35961(9): Fix a crash in slice_richcompare(): use strong
     references rather than stolen references for the two temporary
     internal tuples.

   - bpo-35911(10): Enable the creation of cell objects by adding a
     ‘cell.__new__’ method, and expose the type ‘cell’ in ‘Lib/types.py’
     under the name CellType.  Patch by Pierre Glaser.

   - bpo-12822(11): Use monotonic clock for ‘pthread_cond_timedwait’
     when ‘pthread_condattr_setclock’ and ‘CLOCK_MONOTONIC’ are
     available.

   - bpo-15248(12): The compiler emits now syntax warnings in the case
     when a comma is likely missed before tuple or list.

   - bpo-35886(13): The implementation of PyInterpreterState has been
     moved into the internal header files (guarded by Py_BUILD_CORE).

   - bpo-31506(14): Clarify the errors reported when ‘object.__new__’
     and ‘object.__init__’ receive more than one argument.  Contributed
     by Sanyam Khurana.

   - bpo-35724(15): Signal-handling is now guaranteed to happen relative
     to the main interpreter.

   - bpo-33608(16): 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.

   - bpo-33989(17): Fix a possible crash in *note list.sort(): 547. when
     sorting objects with ‘ob_type->tp_richcompare == NULL’.  Patch by
     Zackery Spytz.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36052

   (2) https://bugs.python.org/issue36012

   (3) https://bugs.python.org/issue35942

   (4) https://bugs.python.org/issue36016

   (5) https://bugs.python.org/issue1054041

   (6) https://bugs.python.org/issue35992

   (7) https://bugs.python.org/issue35993

   (8) https://bugs.python.org/issue35991

   (9) https://bugs.python.org/issue35961

   (10) https://bugs.python.org/issue35911

   (11) https://bugs.python.org/issue12822

   (12) https://bugs.python.org/issue15248

   (13) https://bugs.python.org/issue35886

   (14) https://bugs.python.org/issue31506

   (15) https://bugs.python.org/issue35724

   (16) https://bugs.python.org/issue33608

   (17) https://bugs.python.org/issue33989


File: python.info,  Node: 库<29>,  Next: 文档<24>,  Prev: 核心与内置函数<27>,  Up: Python 3 8 0 alpha 2

1.19.30.2 库
............

   - bpo-35512(1): *note unittest.mock.patch.dict(): 110a. used as a
     decorator with string target resolves the target during function
     call instead of during decorator construction.  Patch by
     Karthikeyan Singaravelan.

   - bpo-36018(2): 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.

   - bpo-35904(3): Added statistics.fmean() as a faster, floating point
     variant of the existing mean() function.

   - bpo-35918(4): Removed broken ‘has_key’ method from
     multiprocessing.managers.SyncManager.dict.  Contributed by Rémi
     Lapeyre.

   - bpo-18283(5): Add support for bytes to *note shutil.which(): fe6.

   - bpo-35960(6): Fix *note dataclasses.field(): 1139. throwing away
     empty mapping objects passed as metadata.

   - bpo-35500(7): Write expected and actual call parameters on separate
     lines in *note unittest.mock.Mock.assert_called_with(): 113a.
     assertion errors.  Contributed by Susan Su.

   - bpo-35931(8): The *note pdb: c9. ‘debug’ command now gracefully
     handles syntax errors.

   - bpo-24209(9): 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.

   - bpo-35321(10): Set ‘__spec__.origin’ of ‘_frozen_importlib’ to
     frozen so that it matches the behavior of
     ‘_frozen_importlib_external’.  Patch by Nina Zakharenko.

   - bpo-35378(11): Fix a reference issue inside ‘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.

   - bpo-34294(12): re module, fix wrong capturing groups in rare cases.
     *note re.search(): c82, *note re.findall(): a44, *note re.sub():
     579. and other functions that scan through string looking for a
     match, should reset capturing groups between two match attempts.
     Patch by Ma Lin.

   - bpo-35615(13): *note weakref: 131.: Fix a RuntimeError when copying
     a WeakKeyDictionary or a WeakValueDictionary, due to some keys or
     values disappearing while iterating.

   - bpo-35606(14): Implement *note math.prod(): 315. as analogous
     function to *note sum(): 316. that returns the product of a ’start’
     value (default: 1) times an iterable of numbers.  Patch by Pablo
     Galindo.

   - bpo-32417(15): Performing arithmetic between *note
     datetime.datetime: 19f. subclasses and *note datetime.timedelta:
     2ca. now returns an object of the same type as the *note
     datetime.datetime: 19f. subclass.  As a result, *note
     datetime.datetime.astimezone(): 2cb. and alternate constructors
     like *note datetime.datetime.now(): 113b. and
     ‘datetime.fromtimestamp()’ called with a ‘tz’ argument now `also'
     retain their subclass.

   - bpo-35153(16): Add `headers' optional keyword-only parameter to
     *note xmlrpc.client.ServerProxy: 37f, ‘xmlrpc.client.Transport’ and
     ‘xmlrpc.client.SafeTransport’.  Patch by Cédric Krier.

   - bpo-34572(17): Fix C implementation of pickle.loads to use
     importlib’s locking mechanisms, and thereby avoid using
     partially-loaded modules.  Patch by Tim Burgess.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35512

   (2) https://bugs.python.org/issue36018

   (3) https://bugs.python.org/issue35904

   (4) https://bugs.python.org/issue35918

   (5) https://bugs.python.org/issue18283

   (6) https://bugs.python.org/issue35960

   (7) https://bugs.python.org/issue35500

   (8) https://bugs.python.org/issue35931

   (9) https://bugs.python.org/issue24209

   (10) https://bugs.python.org/issue35321

   (11) https://bugs.python.org/issue35378

   (12) https://bugs.python.org/issue34294

   (13) https://bugs.python.org/issue35615

   (14) https://bugs.python.org/issue35606

   (15) https://bugs.python.org/issue32417

   (16) https://bugs.python.org/issue35153

   (17) https://bugs.python.org/issue34572


File: python.info,  Node: 文档<24>,  Next: 测试<23>,  Prev: 库<29>,  Up: Python 3 8 0 alpha 2

1.19.30.3 文档
..............

   - bpo-36083(1): Fix formatting of –check-hash-based-pycs options in
     the manpage Synopsis.

   - bpo-36007(2): Bump minimum sphinx version to 1.8.  Patch by Anthony
     Sottile.

   - bpo-22062(3): Update documentation and docstrings for pathlib.
     Original patch by Mike Short.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue36083

   (2) https://bugs.python.org/issue36007

   (3) https://bugs.python.org/issue22062


File: python.info,  Node: 测试<23>,  Next: Windows<23>,  Prev: 文档<24>,  Up: Python 3 8 0 alpha 2

1.19.30.4 测试
..............

   - bpo-27313(1): Avoid test_ttk_guionly ComboboxTest failure with
     macOS Cocoa Tk.

   - bpo-36019(2): Add test.support.TEST_HTTP_URL and replace references
     of ‘http://www.example.com’ by this new constant.  Contributed by
     Stéphane Wirtel.

   - bpo-36037(3): 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.

   - bpo-35798(4): Added *note test.support.check_syntax_warning():
     113e.

   - bpo-35505(5): Make test_imap4_host_default_value independent on
     whether the local IMAP server is running.

   - bpo-35917(6): 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)

   - bpo-35704(7): Skip ‘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)

   - bpo-34720(8): Assert m_state != NULL to mimic GC traversal
     functions that do not correctly handle module creation when the
     module state has not been created.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27313

   (2) https://bugs.python.org/issue36019

   (3) https://bugs.python.org/issue36037

   (4) https://bugs.python.org/issue35798

   (5) https://bugs.python.org/issue35505

   (6) https://bugs.python.org/issue35917

   (7) https://bugs.python.org/issue35704

   (8) https://bugs.python.org/issue34720


File: python.info,  Node: Windows<23>,  Next: IDLE<23>,  Prev: 测试<23>,  Up: Python 3 8 0 alpha 2

1.19.30.5 Windows
.................

   - bpo-35976(1): Added ARM build support to Windows build files in
     PCBuild.

   - bpo-35692(2): ‘pathlib’ no longer raises when checking file and
     directory existence on drives that are not ready

   - bpo-35872(3): Uses the base Python executable when invoking venv in
     a virtual environment

   - bpo-35873(4): Prevents venv paths being inherited by child
     processes

   - bpo-35299(5): Fix sysconfig detection of the source directory and
     distutils handling of pyconfig.h during PGO profiling

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35976

   (2) https://bugs.python.org/issue35692

   (3) https://bugs.python.org/issue35872

   (4) https://bugs.python.org/issue35873

   (5) https://bugs.python.org/issue35299


File: python.info,  Node: IDLE<23>,  Prev: Windows<23>,  Up: Python 3 8 0 alpha 2

1.19.30.6 IDLE
..............

   - bpo-24310(1): IDLE – 文档设置对话框字体选项卡示例。

   - bpo-35833(2): Revise IDLE doc for control codes sent to Shell.  Add
     a code example block.

   - bpo-35689(3): Add docstrings and unittests for colorizer.py.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24310

   (2) https://bugs.python.org/issue35833

   (3) https://bugs.python.org/issue35689


File: python.info,  Node: Python 3 8 0 alpha 1,  Next: Python 3 7 0 正式版,  Prev: Python 3 8 0 alpha 2,  Up: Changelog（更動日誌）

1.19.31 Python 3.8.0 alpha 1
----------------------------

`发布日期: 2019-02-03'

* Menu:

* 安全性: 安全性<18>.
* 核心与内置函数: 核心与内置函数<28>.
* 库: 库<30>.
* 文档: 文档<25>.
* 测试: 测试<24>.
* 构建: 构建<23>.
* Windows: Windows<24>.
* macOS: macOS<20>.
* IDLE: IDLE<24>.
* 工具/示例: 工具/示例<11>.
* C API: C API<20>.


File: python.info,  Node: 安全性<18>,  Next: 核心与内置函数<28>,  Up: Python 3 8 0 alpha 1

1.19.31.1 安全性
................

   - bpo-35746(1): [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.

   - bpo-34812(2): The *note -I: 231. command line option (run Python in
     isolated mode) is now also copied by the *note multiprocessing: b7.
     and *note distutils: 38. modules when spawning child processes.
     Previously, only *note -E: 230. and *note -s: ddb. options (enabled
     by *note -I: 231.) were copied.

   - bpo-34791(3): 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.

   - bpo-17239(4): 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.

   - bpo-34623(5): CVE-2018-14647: The C accelerated _elementtree module
     now initializes hash randomization salt from _Py_HashSecret instead
     of libexpat’s default CSPRNG.

   - bpo-34405(6): 将Windows内部版本更新到OpenSSL 1.1.0i

   - bpo-33871(7): 修复了使用 *note os.sendfile(): 461. 在macOS上发送部
     分文件的错误。使用 `trailers' 参数可能导致从输入文件发送的字节数多
     于指定的数量。

   - bpo-32533(8): Fixed thread-safety of error handling in _ssl.

   - bpo-33136(9): 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.

   - bpo-33001(10): Minimal fix to prevent buffer overrun in os.symlink
     on Windows

   - bpo-32981(11): 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.

   - bpo-28414(12): The ssl module now allows users to perform their own
     IDN en/decoding when using SNI.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35746

   (2) https://bugs.python.org/issue34812

   (3) https://bugs.python.org/issue34791

   (4) https://bugs.python.org/issue17239

   (5) https://bugs.python.org/issue34623

   (6) https://bugs.python.org/issue34405

   (7) https://bugs.python.org/issue33871

   (8) https://bugs.python.org/issue32533

   (9) https://bugs.python.org/issue33136

   (10) https://bugs.python.org/issue33001

   (11) https://bugs.python.org/issue32981

   (12) https://bugs.python.org/issue28414


File: python.info,  Node: 核心与内置函数<28>,  Next: 库<30>,  Prev: 安全性<18>,  Up: Python 3 8 0 alpha 1

1.19.31.2 核心与内置函数
........................

   - bpo-35877(1): Make parenthesis optional for named expressions in
     while statement.  Patch by Karthikeyan Singaravelan.

   - bpo-35814(2): Allow same right hand side expressions in annotated
     assignments as in normal ones.  In particular, ‘x: Tuple[int, int]
     = 1, 2’ (without parentheses on the right) is now allowed.

   - bpo-35766(3): 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](‘https://github.com/python/typed_ast’).

   - bpo-35713(4): Reorganize Python initialization to get working
     exceptions and sys.stderr earlier.

   - bpo-33416(5): Add end line and end column position information to
     the Python AST nodes.  This is a C-level backwards incompatible
     change.

   - bpo-35720(6): Fixed a minor memory leak in
     pymain_parse_cmdline_impl function in Modules/main.c

   - bpo-35634(7): ‘func(**kwargs)’ will now raise an error when
     ‘kwargs’ is a mapping containing multiple entries with the same
     key.  An error was already raised when other keyword arguments are
     passed before ‘**kwargs’ since Python 3.6.

   - bpo-35623(8): 修复了在排序超长列表时崩溃的问题。 补丁作者 Stephan
     Hohe。

   - bpo-35214(9): 添加了 clang Memory Sanitizer 构建工具以绕过来自
     posix, socket, time, test_io 和 test_faulthandler 的误报问题。

   - bpo-35560(10): 修复了在调试版中使用 "n" 格式进行零留空和小宽度的浮
     点格式化时 *note format(): 5d5. 内的一个断言错误。 发布版未受影响。
     补丁作者 Karthikeyan Singaravelan。

   - bpo-35552(11): Format characters ‘%s’ and ‘%V’ in *note
     PyUnicode_FromFormat(): 8b8. and ‘%s’ in *note
     PyBytes_FromFormat(): 1144. no longer read memory past the limit if
     `precision' is specified.

   - bpo-35504(12): 修复了在删除特定属性时的段错误和 *note SystemError:
     6f2. 问题。 补丁作者 Zackery Spytz。

   - bpo-35504(13): Fixed a SystemError when delete the
     characters_written attribute of an OSError.

   - bpo-35494(14): Improved syntax error messages for unbalanced
     parentheses in f-string.

   - bpo-35444(15): Fixed error handling in pickling methods when fail
     to look up builtin "getattr".  Sped up pickling iterators.

   - bpo-35436(16): Fix various issues with memory allocation error
     handling.  Patch by Zackery Spytz.

   - bpo-35423(17): 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.

   - bpo-35357(18): 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.

   - bpo-35372(19): Fixed the code page decoder for input longer than 2
     GiB containing undecodable bytes.

   - bpo-35336(20): Fix PYTHONCOERCECLOCALE=1 environment variable: only
     coerce the C locale if the LC_CTYPE locale is "C".

   - bpo-31241(21): The `lineno' and `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.

   - bpo-33954(22): For *note str.format(): 5d4, ‘float.__format__()’
     and ‘complex.__format__()’ methods for non-ASCII decimal point when
     using the "n" formatter.

   - bpo-35269(23): Fix a possible segfault involving a newly-created
     coroutine.  Patch by Zackery Spytz.

   - bpo-35224(24): Implement PEP 572(25) (assignment expressions).
     Patch by Emily Morehouse.

   - bpo-32492(26): Speed up ‘namedtuple’ attribute access by 1.6x using
     a C fast-path for the name descriptors.  Patch by Pablo Galindo.

   - bpo-35214(27): Fixed an out of bounds memory access when parsing a
     truncated unicode escape sequence at the end of a string such as
     ‘'\N'’.  It would read one byte beyond the end of the memory
     allocation.

   - bpo-35214(28): 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.

   - bpo-35193(29): 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.

   - bpo-35169(30): Improved error messages for forbidden assignments.

   - bpo-34022(31): Fix handling of hash-based bytecode files in *note
     zipimport: 14c.  Patch by Elvis Pranskevichus.

   - bpo-28401(32): 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.

   - bpo-29341(33): Clarify in the docstrings of *note os: c4. methods
     that path-like objects are also accepted as input parameters.

   - bpo-35050(34): *note socket: ef.: Fix off-by-one bug in length
     check for ‘AF_ALG’ name and type.

   - bpo-29743(35): Raise *note ValueError: 16d. instead of *note
     OverflowError: a41. in case of a negative ‘_length_’ in a *note
     ctypes.Array: 1145. subclass.  Also raise *note TypeError: 1fe.
     instead of *note AttributeError: 4a1. for non-integer ‘_length_’.
     Original patch by Oren Milman.

   - bpo-16806(36): Fix ‘lineno’ and ‘col_offset’ for multi-line string
     tokens.

   - bpo-35029(37): *note SyntaxWarning: 2c9. raised as an exception at
     code generation time will be now replaced with a *note SyntaxError:
     559. for better error reporting.

   - bpo-34983(38): Expose *note symtable.Symbol.is_nonlocal(): 1146. in
     the symtable module.  Patch by Pablo Galindo.

   - bpo-34974(39): *note bytes: 172. and *note bytearray: 173.
     constructors no longer convert unexpected exceptions (e.g.  *note
     MemoryError: f69. and *note KeyboardInterrupt: 2cc.) to *note
     TypeError: 1fe.

   - bpo-34939(40): Allow annotated names in module namespace that are
     declared global before the annotation happens.  Patch by Pablo
     Galindo.

   - bpo-34973(41): Fixed crash in *note bytes(): 172. when the *note
     list: 1f8. argument is mutated while it is iterated.

   - bpo-34876(42): The `lineno' and `col_offset' attributes of the AST
     for decorated function and class refer now to the position of the
     corresponding ‘def’, ‘async def’ and ‘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.

   - bpo-34879(43): Fix a possible null pointer dereference in
     bytesobject.c.  Patch by Zackery Spytz.

   - bpo-34784(44): Fix the implementation of PyStructSequence_NewType
     in order to create heap allocated StructSequences.

   - bpo-32912(45): A *note SyntaxWarning: 2c9. is now emitted instead
     of a *note DeprecationWarning: 15a. for invalid escape sequences in
     string and bytes literals.

   - bpo-34854(46): 修复问题——当编译包含一个没有默认值的关键字参数的
     lambda 的字符串注解时可导致崩溃。

   - bpo-34850(47): The compiler now produces a *note SyntaxWarning:
     2c9. when identity checks (‘is’ and ‘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 (‘==’ and ‘!=’)
     instead.

   - bpo-34824(48): Fix a possible null pointer dereference in
     Modules/_ssl.c.  Patch by Zackery Spytz.

   - bpo-30156(49): The C function ‘property_descr_get()’ uses a
     "cached" tuple to optimize function calls.  But this tuple can be
     discovered in debug mode with ‘sys.getobjects()’.  Remove the
     optimization, it’s not really worth it and it causes 3 different
     crashes last years.

   - bpo-34762(50): Fix contextvars C API to use PyObject* pointer
     types.

   - bpo-34751(51): 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.

   - bpo-34735(52): Fix a memory leak in Modules/timemodule.c.  Patch by
     Zackery Spytz.

   - bpo-34683(53): Fixed a bug where some SyntaxError error pointed to
     locations that were off-by-one.

   - bpo-34651(54): Only allow the main interpreter to fork.  The avoids
     the possibility of affecting the main interpreter, which is
     critical to operation of the runtime.

   - bpo-34653(55): Remove unused function
     PyParser_SimpleParseStringFilename.

   - bpo-32236(56): Warn that line buffering is not supported if *note
     open(): 16f. is called with binary mode and ‘buffering=1’.

   - bpo-34641(57): Further restrict the syntax of the left-hand side of
     keyword arguments in function calls.  In particular,
     ‘f((keyword)=arg)’ is now disallowed.

   - bpo-34637(58): Make the `start' argument to `sum()' visible as a
     keyword argument.

   - bpo-1621(59): Do not assume signed integer overflow behavior (C
     undefined behavior) when performing set hash table resizing.

   - bpo-34588(60): Fix an off-by-one in the recursive call pruning
     feature of traceback formatting.

   - bpo-34485(61): 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, "").

   - bpo-34485(62): 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).

   - bpo-34485(63): Fix the error handler of standard streams like
     sys.stdout: PYTHONIOENCODING=":" is now ignored instead of setting
     the error handler to "strict".

   - bpo-34485(64): 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.

   - bpo-34527(65): 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".

   - bpo-34527(66): The UTF-8 Mode is now also enabled by the "POSIX"
     locale, not only by the "C" locale.

   - bpo-34403(67): 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).

   - bpo-34523(68): The Python filesystem encoding is now read earlier
     during the Python initialization.

   - bpo-12458(69): 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.

   - bpo-34408(70): Prevent a null pointer dereference and resource
     leakage in ‘PyInterpreterState_New()’.

   - bpo-34400(71): Fix undefined behavior in parsetok.c.  Patch by
     Zackery Spytz.

   - bpo-33073(72): Added as_integer_ratio to ints to make them more
     interoperable with floats.

   - bpo-34377(73): 更新valgrind的抑制列表，使用
     ‘_PyObject_Free’/‘_PyObject_Realloc’ 代替
     ‘PyObject_Free’/‘PyObject_Realloc’ 。

   - bpo-34353(74): Added the "socket" option in the *note
     stat.filemode(): b75. Python implementation to match the C
     implementation.

   - bpo-34320(75): 修复问题——‘dict(od)’ 不会复制 OrderedDict 的迭代顺序
     。

   - bpo-34113(76): Fixed crash on debug builds when opcode stack was
     adjusted with negative numbers.  Patch by Constantin Petrisor.

   - bpo-34100(77): Compiler now merges constants in tuples and
     frozensets recursively.  Code attributes like ‘co_names’ are merged
     too.

   - bpo-34151(78): Performance of list concatenation, repetition and
     slicing operations is slightly improved.  Patch by Sergey Fedoseev.

   - bpo-34170(79): -X dev: 即使启用了开发模式，现在也可以使用
     PYTHONMALLOC重载内存分配器。

   - bpo-33237(80): Improved *note AttributeError: 4a1. message for
     partially initialized module.

   - bpo-34149(81): Fix min and max functions to get default behavior
     when key is None.

   - bpo-34125(82): Profiling of unbound built-in methods now works when
     ‘**kwargs’ is given.

   - bpo-34141(83): Optimized pickling atomic types (None, bool, int,
     float, bytes, str).

   - bpo-34126(84): 修复在分析某些未绑定的方法的无效调用时崩溃的问题。由
     Jeroen Demeyer修复。

   - bpo-24618(85): 修复了当创建代码对象时使用的变量名元组太小或参数太多
     导致读取无效内存的问题。

   - bpo-34068(86): 在调用 *note io.IOBase.close(): 1147. 时确保 *note
     closed: 1148. 属性未设置有效的异常。 由Zackery Spytz和Serhiy
     Storchaka修复。

   - bpo-34087(87): 修复由unicode转换为数值类型时缓冲区溢出的问题。

   - bpo-34080(88): 修复了编译器在标记化过程中引发一些不常见错误时内存泄
     漏的问题。

   - bpo-34066(89): 调用 ‘open()’ 和进入 ‘with open()’ 的 `with' 语句块
     内时禁止使用 Ctrl-C 中断。

   - bpo-34042(90): 修复 dict.copy() 以维护正确的总引用计数（由
     sys.gettotalrefcount()报告）。

   - bpo-33418(91): Fix potential memory leak in function object when it
     creates reference cycle.

   - bpo-33985(92): 实现contextvars.ContextVar.name 属性。

   - bpo-33956(93): Update vendored Expat library copy to version 2.2.5.

   - bpo-24596(94): 执行 *note PyErr_Print(): 102f. 之前，在 *note
     PyRun_SimpleFileExFlags(): fc7. 内减少模块对象的引用。 由Zackery
     Spytz修复。

   - bpo-33451(95): 执行 ‘PyEval_EvalCode()’ 前先关闭直接执行的pyc文件。

   - bpo-1617161(96): The hash of ‘BuiltinMethodType’ instances (methods
     of built-in classes) now depends on the hash of the identity of
     `__self__' instead of its value.  The hash and equality of
     ‘ModuleType’ and ‘MethodWrapperType’ instances (methods of
     user-defined classes and some methods of built-in classes like
     ‘str.__add__’) now depend on the hash and equality of the identity
     of `__self__' instead of its value.  ‘MethodWrapperType’ instances
     no longer support ordering.

   - bpo-33824(97): 修复"LC_ALL=C python3.7 -V"：在读取Python配置后编码
     发生更改时，正确重置命令行解析器。

   - bpo-33803(98): Fix a crash in hamt.c caused by enabling GC tracking
     for an object that hadn’t all of its fields set to NULL.

   - bpo-33738(99): Seven macro incompatibilities with the Limited API
     were fixed, and the macros *note PyIter_Check(): 1149, *note
     PyIndex_Check(): 26e. and ‘PyExceptionClass_Name()’ were added as
     functions.  A script for automatic macro checks was added.

   - bpo-33786(100): Fix asynchronous generators to handle GeneratorExit
     in athrow() correctly

   - bpo-30167(101): ‘PyRun_SimpleFileExFlags’ removes ‘__cached__’ from
     module in addition to ‘__file__’.

   - bpo-33706(102): Fix a crash in Python initialization when parsing
     the command line options.  Thanks Christoph Gohlke for the bug
     report and the fix!

   - bpo-33597(103): Reduce ‘PyGC_Head’ size from 3 words to 2 words.

   - bpo-30654(104): 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.

   - bpo-33622(105): Fixed a leak when the garbage collector fails to
     add an object with the ‘__del__’ method or referenced by it into
     the *note gc.garbage: c12. list.  ‘PyGC_Collect()’ can now be
     called when an exception is set and preserves it.

   - bpo-33462(106): Make dict and dict views reversible.  Patch by Rémi
     Lapeyre.

   - bpo-23722(107): A *note RuntimeError: 3dc. is now raised when the
     custom metaclass doesn’t provide the ‘__classcell__’ entry in the
     namespace passed to ‘type.__new__’.  A *note DeprecationWarning:
     15a. was emitted in Python 3.6–3.7.

   - bpo-33499(108): Add *note PYTHONPYCACHEPREFIX: 28f. environment
     variable and *note -X: 290. ‘pycache_prefix’ command-line option to
     set an alternate root directory for writing module bytecode cache
     files.

   - bpo-25711(109): The *note zipimport: 14c. module has been rewritten
     in pure Python.

   - bpo-33509(110): Fix module_globals parameter of
     warnings.warn_explicit(): don’t crash if module_globals is not a
     dict.

   - bpo-31849(111): Fix signed/unsigned comparison warning in pyhash.c.

   - bpo-33475(112): Fixed miscellaneous bugs in converting annotations
     to strings and optimized parentheses in the string representation.

   - bpo-20104(113): Added support for the ‘setpgroup’, ‘resetids’,
     ‘setsigmask’, ‘setsigdef’ and ‘scheduler’ parameters of
     ‘posix_spawn’.  Patch by Pablo Galindo.

   - bpo-33391(114): Fix a leak in set_symmetric_difference().

   - bpo-33363(115): 在异步函数外使用‘‘async with‘‘ 和 ‘async for’ 时抛
     出SyntaxError异常。

   - bpo-28055(116): Fix unaligned accesses in siphash24().  Patch by
     Rolf Eike Beer.

   - bpo-33128(117): 修复导致PathFinder在sys.meta_path上出现两次的错误。
     由Pablo Galindo Salgado提供补丁。

   - bpo-33331(118): Modules imported last are now cleared first at
     interpreter shutdown.

   - bpo-33312(119): Fixed clang ubsan (undefined behavior sanitizer)
     warnings in dictobject.c by adjusting how the internal struct
     _dictkeysobject shared keys structure is declared.

   - bpo-33305(120): Improved syntax error messages for invalid
     numerical literals.

   - bpo-33306(121): Improved syntax error messages for unbalanced
     parentheses.

   - bpo-33234(122): The list constructor will pre-size and not
     over-allocate when the input length is known.

   - bpo-33270(123): Intern the names for all anonymous code objects.
     Patch by Zackery Spytz.

   - bpo-30455(124): The C and Python code and the documentation related
     to tokens are now generated from a single source file
     ‘Grammar/Tokens’.

   - bpo-33176(125): Add a ‘toreadonly()’ method to memoryviews.

   - bpo-33231(126): 修复 ‘normalizestring()’ 中潜在的内存泄漏。

   - bpo-33205(127): Change dict growth function from
     ‘round_up_to_power_2(used*2+hashtable_size/2)’ to
     ‘round_up_to_power_2(used*3)’.  Previously, dict is shrinked only
     when ‘used == 0’.  Now dict has more chance to be shrinked.

   - bpo-29922(128): Improved error messages in ’async with’ when
     ‘__aenter__()’ or ‘__aexit__()’ return non-awaitable object.

   - bpo-33199(129): Fix ‘ma_version_tag’ in dict implementation is
     uninitialized when copying from key-sharing dict.

   - bpo-33053(130): When using the -m switch, sys.path[0] is now
     explicitly expanded as the `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)

   - bpo-33138(131): Changed standard error message for non-pickleable
     and non-copyable types.  It now says "cannot pickle" instead of
     "can’t pickle" or "cannot serialize".

   - bpo-33018(132): Improve consistency of errors raised by
     ‘issubclass()’ when called with a non-class and an abstract base
     class as the first and second arguments, respectively.  Patch by
     Josh Bronson.

   - bpo-33083(133): ‘math.factorial’ no longer accepts arguments that
     are not int-like.  Patch by Pablo Galindo.

   - bpo-33041(134): Added new opcode *note END_ASYNC_FOR: 3fc. and
     fixes the following issues:

        * Setting global *note StopAsyncIteration: 114a. no longer
          breaks ‘async for’ loops.

        * 跳入一个 ‘async for’ 循环现在被禁止了。

        * 跳出一个 ‘async for’ 循环不再会破坏堆栈了。

   - bpo-25750(135): Fix rare Python crash due to bad refcounting in
     ‘type_getattro()’ if a descriptor deletes itself from the class.
     Patch by Jeroen Demeyer.

   - bpo-33041(136): 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.

   - bpo-33026(137): Fixed jumping out of "with" block by setting
     f_lineno.

   - bpo-33005(138): 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.

   - bpo-32911(139): Due to unexpected compatibility issues discovered
     during downstream beta testing, reverted bpo-29463(140).
     ‘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.

   - bpo-17288(141): Prevent jumps from ’return’ and ’exception’ trace
     events.

   - bpo-32946(142): Importing names from already imported module with
     "from ...  import ..."  is now 30% faster if the module is not a
     package.

   - bpo-32932(143): Make error message more revealing when there are
     non-str objects in ‘__all__’.

   - bpo-32925(144): Optimized iterating and containing test for literal
     lists consisting of non-constants: ‘x in [a, b]’ and ‘for x in [a,
     b]’.  The case of all constant elements already was optimized.

   - bpo-32889(145): Update Valgrind suppression list to account for the
     rename of ‘Py_ADDRESS_IN_RANG’ to ‘address_in_range’.

   - bpo-32836(146): Don’t use temporary variables in cases of
     list/dict/set comprehensions

   - bpo-31356(147): Remove the new API added in bpo-31356(148)
     (gc.ensure_disabled() context manager).

   - bpo-32305(149): For namespace packages, ensure that both ‘__file__’
     and ‘__spec__.origin’ are set to None.

   - bpo-32303(150): Make sure ‘__spec__.loader’ matches ‘__loader__’
     for namespace packages.

   - bpo-32711(151): Fix the warning messages for Python/ast_unparse.c.
     Patch by Stéphane Wirtel

   - bpo-32583(152): Fix possible crashing in builtin Unicode decoders
     caused by write out-of-bound errors when using customized decode
     error handlers.

   - bpo-32489(153): A *note continue: 2bb. statement is now allowed in
     the *note finally: 2bc. clause.

   - bpo-17611(154): 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 *note break: 3fa, *note
     continue: 2bb. and *note return: 2c8.

     Removed opcodes ‘BREAK_LOOP’, ‘CONTINUE_LOOP’, ‘SETUP_LOOP’ and
     ‘SETUP_EXCEPT’.  Added new opcodes *note ROT_FOUR: 3fb,
     ‘BEGIN_FINALLY’ and ‘CALL_FINALLY’ and ‘POP_FINALLY’.  Changed the
     behavior of ‘END_FINALLY’ and ‘WITH_CLEANUP_START’.

   - bpo-32285(155): New function unicodedata.is_normalized, which can
     check whether a string is in a specific normal form.

   - bpo-10544(156): Yield expressions are now disallowed in
     comprehensions and generator expressions except the expression for
     the outermost iterable.

   - bpo-32117(157): Iterable unpacking is now allowed without
     parentheses in yield and return statements, e.g.  ‘yield 1, 2, 3,
     *rest’.  Thanks to David Cuthbert for the change and Jordan Chapman
     for added tests.

   - bpo-31902(158): Fix the ‘col_offset’ attribute for ast nodes
     ‘ast.AsyncFor’, ‘ast.AsyncFunctionDef’, and ‘ast.AsyncWith’.
     Previously, ‘col_offset’ pointed to the keyword after ‘async’.

   - bpo-25862(159): 修复 ‘io.TextIOWrapper’ 的 ‘tell()’ 方法内的错误断
     言。

   - bpo-21983(160): Fix a crash in *note ctypes.cast(): 114b. in case
     the type argument is a ctypes structured data type.  Patch by Eryk
     Sun and Oren Milman.

   - bpo-31577(161): Fix a crash in *note os.utime(): b19. in case of a
     bad ns argument.  Patch by Oren Milman.

   - bpo-29832(162): Remove references to ’getsockaddrarg’ from various
     socket error messages.  Patch by Oren Milman.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35877

   (2) https://bugs.python.org/issue35814

   (3) https://bugs.python.org/issue35766

   (4) https://bugs.python.org/issue35713

   (5) https://bugs.python.org/issue33416

   (6) https://bugs.python.org/issue35720

   (7) https://bugs.python.org/issue35634

   (8) https://bugs.python.org/issue35623

   (9) https://bugs.python.org/issue35214

   (10) https://bugs.python.org/issue35560

   (11) https://bugs.python.org/issue35552

   (12) https://bugs.python.org/issue35504

   (13) https://bugs.python.org/issue35504

   (14) https://bugs.python.org/issue35494

   (15) https://bugs.python.org/issue35444

   (16) https://bugs.python.org/issue35436

   (17) https://bugs.python.org/issue35423

   (18) https://bugs.python.org/issue35357

   (19) https://bugs.python.org/issue35372

   (20) https://bugs.python.org/issue35336

   (21) https://bugs.python.org/issue31241

   (22) https://bugs.python.org/issue33954

   (23) https://bugs.python.org/issue35269

   (24) https://bugs.python.org/issue35224

   (25) https://www.python.org/dev/peps/pep-0572

   (26) https://bugs.python.org/issue32492

   (27) https://bugs.python.org/issue35214

   (28) https://bugs.python.org/issue35214

   (29) https://bugs.python.org/issue35193

   (30) https://bugs.python.org/issue35169

   (31) https://bugs.python.org/issue34022

   (32) https://bugs.python.org/issue28401

   (33) https://bugs.python.org/issue29341

   (34) https://bugs.python.org/issue35050

   (35) https://bugs.python.org/issue29743

   (36) https://bugs.python.org/issue16806

   (37) https://bugs.python.org/issue35029

   (38) https://bugs.python.org/issue34983

   (39) https://bugs.python.org/issue34974

   (40) https://bugs.python.org/issue34939

   (41) https://bugs.python.org/issue34973

   (42) https://bugs.python.org/issue34876

   (43) https://bugs.python.org/issue34879

   (44) https://bugs.python.org/issue34784

   (45) https://bugs.python.org/issue32912

   (46) https://bugs.python.org/issue34854

   (47) https://bugs.python.org/issue34850

   (48) https://bugs.python.org/issue34824

   (49) https://bugs.python.org/issue30156

   (50) https://bugs.python.org/issue34762

   (51) https://bugs.python.org/issue34751

   (52) https://bugs.python.org/issue34735

   (53) https://bugs.python.org/issue34683

   (54) https://bugs.python.org/issue34651

   (55) https://bugs.python.org/issue34653

   (56) https://bugs.python.org/issue32236

   (57) https://bugs.python.org/issue34641

   (58) https://bugs.python.org/issue34637

   (59) https://bugs.python.org/issue1621

   (60) https://bugs.python.org/issue34588

   (61) https://bugs.python.org/issue34485

   (62) https://bugs.python.org/issue34485

   (63) https://bugs.python.org/issue34485

   (64) https://bugs.python.org/issue34485

   (65) https://bugs.python.org/issue34527

   (66) https://bugs.python.org/issue34527

   (67) https://bugs.python.org/issue34403

   (68) https://bugs.python.org/issue34523

   (69) https://bugs.python.org/issue12458

   (70) https://bugs.python.org/issue34408

   (71) https://bugs.python.org/issue34400

   (72) https://bugs.python.org/issue33073

   (73) https://bugs.python.org/issue34377

   (74) https://bugs.python.org/issue34353

   (75) https://bugs.python.org/issue34320

   (76) https://bugs.python.org/issue34113

   (77) https://bugs.python.org/issue34100

   (78) https://bugs.python.org/issue34151

   (79) https://bugs.python.org/issue34170

   (80) https://bugs.python.org/issue33237

   (81) https://bugs.python.org/issue34149

   (82) https://bugs.python.org/issue34125

   (83) https://bugs.python.org/issue34141

   (84) https://bugs.python.org/issue34126

   (85) https://bugs.python.org/issue24618

   (86) https://bugs.python.org/issue34068

   (87) https://bugs.python.org/issue34087

   (88) https://bugs.python.org/issue34080

   (89) https://bugs.python.org/issue34066

   (90) https://bugs.python.org/issue34042

   (91) https://bugs.python.org/issue33418

   (92) https://bugs.python.org/issue33985

   (93) https://bugs.python.org/issue33956

   (94) https://bugs.python.org/issue24596

   (95) https://bugs.python.org/issue33451

   (96) https://bugs.python.org/issue1617161

   (97) https://bugs.python.org/issue33824

   (98) https://bugs.python.org/issue33803

   (99) https://bugs.python.org/issue33738

   (100) https://bugs.python.org/issue33786

   (101) https://bugs.python.org/issue30167

   (102) https://bugs.python.org/issue33706

   (103) https://bugs.python.org/issue33597

   (104) https://bugs.python.org/issue30654

   (105) https://bugs.python.org/issue33622

   (106) https://bugs.python.org/issue33462

   (107) https://bugs.python.org/issue23722

   (108) https://bugs.python.org/issue33499

   (109) https://bugs.python.org/issue25711

   (110) https://bugs.python.org/issue33509

   (111) https://bugs.python.org/issue31849

   (112) https://bugs.python.org/issue33475

   (113) https://bugs.python.org/issue20104

   (114) https://bugs.python.org/issue33391

   (115) https://bugs.python.org/issue33363

   (116) https://bugs.python.org/issue28055

   (117) https://bugs.python.org/issue33128

   (118) https://bugs.python.org/issue33331

   (119) https://bugs.python.org/issue33312

   (120) https://bugs.python.org/issue33305

   (121) https://bugs.python.org/issue33306

   (122) https://bugs.python.org/issue33234

   (123) https://bugs.python.org/issue33270

   (124) https://bugs.python.org/issue30455

   (125) https://bugs.python.org/issue33176

   (126) https://bugs.python.org/issue33231

   (127) https://bugs.python.org/issue33205

   (128) https://bugs.python.org/issue29922

   (129) https://bugs.python.org/issue33199

   (130) https://bugs.python.org/issue33053

   (131) https://bugs.python.org/issue33138

   (132) https://bugs.python.org/issue33018

   (133) https://bugs.python.org/issue33083

   (134) https://bugs.python.org/issue33041

   (135) https://bugs.python.org/issue25750

   (136) https://bugs.python.org/issue33041

   (137) https://bugs.python.org/issue33026

   (138) https://bugs.python.org/issue33005

   (139) https://bugs.python.org/issue32911

   (140) https://bugs.python.org/issue29463

   (141) https://bugs.python.org/issue17288

   (142) https://bugs.python.org/issue32946

   (143) https://bugs.python.org/issue32932

   (144) https://bugs.python.org/issue32925

   (145) https://bugs.python.org/issue32889

   (146) https://bugs.python.org/issue32836

   (147) https://bugs.python.org/issue31356

   (148) https://bugs.python.org/issue31356

   (149) https://bugs.python.org/issue32305

   (150) https://bugs.python.org/issue32303

   (151) https://bugs.python.org/issue32711

   (152) https://bugs.python.org/issue32583

   (153) https://bugs.python.org/issue32489

   (154) https://bugs.python.org/issue17611

   (155) https://bugs.python.org/issue32285

   (156) https://bugs.python.org/issue10544

   (157) https://bugs.python.org/issue32117

   (158) https://bugs.python.org/issue31902

   (159) https://bugs.python.org/issue25862

   (160) https://bugs.python.org/issue21983

   (161) https://bugs.python.org/issue31577

   (162) https://bugs.python.org/issue29832


File: python.info,  Node: 库<30>,  Next: 文档<25>,  Prev: 核心与内置函数<28>,  Up: Python 3 8 0 alpha 1

1.19.31.3 库
............

   - bpo-35845(1): Add ’order’ parameter to memoryview.tobytes().

   - bpo-35864(2): The _asdict() method for collections.namedtuple now
     returns a regular dict instead of an OrderedDict.

   - bpo-35537(3): 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)

   - bpo-35847(4): RISC-V needed the CTYPES_PASS_BY_REF_HACK. Fixes
     ctypes Structure test_pass_by_value.

   - bpo-35813(5): Shared memory submodule added to multiprocessing to
     avoid need for serialization between processes

   - bpo-35780(6): 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.

   - bpo-35537(7): *note os.posix_spawn(): 381. and *note
     os.posix_spawnp(): 114d. now have a `setsid' parameter.

   - bpo-23846(8): *note asyncio.ProactorEventLoop: 2de. now catches and
     logs send errors when the self-pipe is full.

   - bpo-34323(9): *note asyncio: 9.: Enhance ‘IocpProactor.close()’
     log: wait 1 second before the first log, then log every second.
     Log also the number of seconds since ‘close()’ was called.

   - bpo-35674(10): Add a new *note os.posix_spawnp(): 114d. function.
     Patch by Joannah Nanjekye.

   - bpo-35733(11): ‘ast.Constant(boolean)’ no longer an instance of
     ‘ast.Num’.  Patch by Anthony Sottile.

   - bpo-35726(12): QueueHandler.prepare() now makes a copy of the
     record before modifying and enqueueing it, to avoid affecting other
     handlers in the chain.

   - bpo-35719(13): Sped up multi-argument *note math: b1. functions
     atan2(), copysign(), remainder() and hypot() by 1.3–2.5 times.

   - bpo-35717(14): Fix KeyError exception raised when using enums and
     compile.  Patch contributed by Rémi Lapeyre.

   - bpo-35699(15): Fixed detection of Visual Studio Build Tools 2017 in
     distutils

   - bpo-32710(16): Fix memory leaks in asyncio ProactorEventLoop on
     overlapped operation failure.

   - bpo-35702(17): The *note time.CLOCK_UPTIME_RAW: 365. constant is
     now available for macOS 10.12.

   - bpo-32710(18): Fix a memory leak in asyncio in the
     ProactorEventLoop when ‘ReadFile()’ or ‘WSASend()’ overlapped
     operation fail immediately: release the internal buffer.

   - bpo-35682(19): Fix ‘asyncio.ProactorEventLoop.sendfile()’: don’t
     attempt to set the result of an internal future if it’s already
     done.

   - bpo-35283(20): Add a deprecated warning for the
     ‘threading.Thread.isAlive()’ method.  Patch by Dong-hee Na.

   - bpo-35664(21): 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).

   - bpo-35643(22): 修复了 Modules/_sha3/cleanup.py 中的一个
     SyntaxWarning: invalid escape sequence。 补丁作者 Mickaël
     Schoentgen。

   - bpo-35619(23): Improved support of custom data descriptors in *note
     help(): 175. and *note pydoc: d9.

   - bpo-28503(24): 当库函数可用时 *note crypt: 28. 模块现在将在内部使用
     ‘crypt_r()’ 而非 *note crypt(): 28.。

   - bpo-35614(25): Fixed help() on metaclasses.  Patch by Sanyam
     Khurana.

   - bpo-35568(26): Expose ‘raise(signum)’ as ‘raise_signal’

   - bpo-35588(27): The floor division and modulo operations and the
     *note divmod(): 28d. function on *note fractions.Fraction: 2be.
     types are 2–4x faster.  Patch by Stefan Behnel.

   - bpo-35585(28): 加快构建按值枚举的速度，例如 http.HTTPStatus(200)。

   - bpo-30561(29): 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.

   - bpo-35537(30): The *note subprocess: f9. module can now use the
     *note os.posix_spawn(): 381. function in some cases for better
     performance.

   - bpo-35526(31): Delaying the ’joke’ of barry_as_FLUFL.mandatory to
     Python version 4.0

   - bpo-35523(32): Remove *note ctypes: 2a. callback workaround: no
     longer create a callback at startup.  Avoid SELinux alert on
     ‘import ctypes’ and ‘import uuid’.

   - bpo-31784(33): *note uuid.uuid1(): 517. now calls *note
     time.time_ns(): 433. rather than ‘int(time.time() * 1e9)’.

   - bpo-35513(34): ‘unittest.runner’ 的 ‘TextTestRunner’ 现在将使用
     *note time.perf_counter(): 3cc. 而非 *note time.time(): 42d. 来计量
     一个测试的执行时间: *note time.time(): 42d. 可以回退，而 *note
     time.perf_counter(): 3cc. 为单调递增。

   - bpo-35502(35): 修复了构建树未完成的情况下 *note
     xml.etree.ElementTree.TreeBuilder: 37d. 中的引用泄漏（特别是在解析
     XML 期间引发错误的时候）。

   - bpo-35348(36): Make *note platform.architecture(): 114e. parsing of
     ‘file’ command output more reliable: add the ‘-b’ option to the
     ‘file’ command to omit the filename, force the usage of the C
     locale, and search also the "shared object" pattern.

   - bpo-35491(37): *note multiprocessing: b7.: Add ‘Pool.__repr__()’
     and enhance ‘BaseProcess.__repr__()’ (add pid and parent pid) to
     ease debugging.  Pool state constant values are now strings instead
     of integers, for example ‘RUN’ value becomes ‘'RUN'’ instead of
     ‘0’.

   - bpo-35477(38): ‘multiprocessing.Pool.__enter__()’ now fails if the
     pool is not running: ‘with pool:’ fails if used more than once.

   - bpo-31446(39): 复制被传递给 CreateProcessW 的命令行，因为此函数能改
     变输入缓存的内容。

   - bpo-35471(40): Python2.4 取消了对MacOS 9 的支持。Python3.7 中已弃用
     macpath 模块。该模块现在已移除。

   - bpo-23057(41): Unblock Proactor event loop when keyboard interrupt
     is received on Windows

   - bpo-35052(42): Fix xml.dom.minidom cloneNode() on a document with
     an entity: pass the correct arguments to the user data handler of
     an entity.

   - bpo-20239(43): Allow repeated assignment deletion of *note
     unittest.mock.Mock: 373. attributes.  Patch by Pablo Galindo.

   - bpo-17185(44): 在 mock 上设置 ‘__signature__’ 以便 *note inspect:
     a0. 能获得签名。 补丁作者为 Karthikeyan Singaravelan。

   - bpo-35445(45): Memory errors during creating posix.environ no
     longer ignored.

   - bpo-35415(46): Validate fileno= argument to socket.socket().

   - bpo-35424(47): ‘multiprocessing.Pool’ destructor now emits *note
     ResourceWarning: 5ca. if the pool is still running.

   - bpo-35330(48): When a ‘Mock’ instance was used to wrap an object,
     if ‘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.

   - bpo-35346(49): 从 *note platform: ce. 模块中删除 MacOS 9 和
     Rhapsody 支持。Rhapsody 上一次发布是在2000年。MacOS 9 上一次发布是
     在2001年。

   - bpo-10496(50): ‘check_environ()’ of ‘distutils.utils’ now catches
     *note KeyError: 3e9. on calling *note pwd.getpwuid(): 114f.: don’t
     create the ‘HOME’ environment variable in this case.

   - bpo-10496(51): ‘posixpath.expanduser()’ now returns the input
     `path' unchanged if the ‘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 *note site: eb. module if the current user doesn’t exist in
     the password database (if the user has no home directory).

   - bpo-35389(52): *note platform.libc_ver(): 1150. now uses
     ‘os.confstr('CS_GNU_LIBC_VERSION')’ if available and the
     `executable' parameter is not set.

   - bpo-35394(53): Add empty slots to asyncio abstract protocols.

   - bpo-35310(54): Fix a bug in *note select.select(): 766. 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.  *note select.select(): 766. will now always
     return empty lists if a timeout has occurred.  Patch by Oran
     Avraham.

   - bpo-35380(55): Enable TCP_NODELAY on Windows for proactor asyncio
     event loop.

   - bpo-35341(56): Add generic version of ‘collections.OrderedDict’ to
     the ‘typing’ module.  Patch by Ismo Toijala.

   - bpo-35371(57): Fixed possible crash in ‘os.utime()’ on Windows when
     pass incorrect arguments.

   - bpo-35346(58): *note platform.uname(): 1151. now redirects ‘stderr’
     to *note os.devnull: 1152. when running external programs like ‘cmd
     /c ver’.

   - bpo-35066(59): 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 ’%’.

   - bpo-35345(60): The function ‘platform.popen’ has been removed, it
     was deprecated since Python 3.3: use *note os.popen(): 3cb.
     instead.

   - bpo-35344(61): On macOS, *note platform.platform(): 1153. now uses
     *note platform.mac_ver(): 1154, if it returns a non-empty release
     string, to get the macOS version rather than the darwin version.

   - bpo-35312(62): Make ‘lib2to3.pgen2.parse.ParseError’ round-trip
     pickle-able.  Patch by Anthony Sottile.

   - bpo-35308(63): Fix regression in ‘webbrowser’ where default
     browsers may be preferred over browsers in the ‘BROWSER’
     environment variable.

   - bpo-24746(64): Avoid stripping trailing whitespace in doctest fancy
     diff.  Original patch by R. David Murray & Jairo Trad.  Enhanced by
     Sanyam Khurana.

   - bpo-28604(65): *note locale.localeconv(): 584. now sets temporarily
     the ‘LC_CTYPE’ locale to the ‘LC_MONETARY’ locale if the two
     locales are different and monetary strings are non-ASCII. This
     temporary change affects other threads.

   - bpo-35277(66): Update ensurepip to install pip 18.1 and setuptools
     40.6.2.

   - bpo-24209(67): Adds IPv6 support when invoking http.server
     directly.

   - bpo-35226(68): Recursively check arguments when testing for
     equality of *note unittest.mock.call: 10cc. objects and add note
     that tracking of parameters used to create ancestors of mocks in
     ‘mock_calls’ is not possible.

   - bpo-29564(69): 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.

   - bpo-35189(70): Modify the following fnctl function to retry if
     interrupted by a signal (EINTR): flock, lockf, fnctl

   - bpo-30064(71): Use add_done_callback() in sock_* asyncio API to
     unsubscribe reader/writer early on calcellation.

   - bpo-35186(72): Removed the "built with" comment added when
     ‘setup.py upload’ is used with either ‘bdist_rpm’ or ‘bdist_dumb’.

   - bpo-35152(73): Allow sending more than 2 GB at once on a
     multiprocessing connection on non-Windows systems.

   - bpo-35062(74): Fix incorrect parsing of
     ‘_io.IncrementalNewlineDecoder’’s `translate' argument.

   - bpo-35065(75): Remove ‘StreamReaderProtocol._untrack_reader’.  The
     call to ‘_untrack_reader’ is currently performed too soon, causing
     the protocol to forget about the reader before ‘connection_lost’
     can run and feed the EOF to the reader.

   - bpo-34160(76): ElementTree and minidom now preserve the attribute
     order specified by the user.

   - bpo-35079(77): Improve difflib.SequenceManager.get_matching_blocks
     doc by adding ’non-overlapping’ and changing ’!=’ to ’<’.

   - bpo-33710(78): Deprecated ‘l*gettext()’ functions and methods in
     the *note gettext: 87. 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
     ‘l*gettext()’ functions and methods.

   - bpo-35017(79): *note socketserver.BaseServer.serve_forever(): b63.
     now exits immediately if it’s *note shutdown(): 1155. method is
     called while it is polling for new events.

   - bpo-35024(80): *note importlib: 9a. no longer logs ‘wrote’
     redundantly after ‘(created|could not create)’ is already logged.
     Patch by Quentin Agren.

   - bpo-35047(81): ‘unittest.mock’ now includes mock calls in exception
     messages if ‘assert_not_called’, ‘assert_called_once’, or
     ‘assert_called_once_with’ fails.  Patch by Petter Strandmark.

   - bpo-31047(82): Fix ‘ntpath.abspath’ regression where it didn’t
     remove a trailing separator on Windows.  Patch by Tim Graham.

   - bpo-35053(83): 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).

   - bpo-31553(84): Add the –json-lines option to json.tool.  Patch by
     hongweipeng.

   - bpo-34794(85): Fixed a leak in Tkinter when pass the Python wrapper
     around Tcl_Obj back to Tcl/Tk.

   - bpo-34909(86): Enum: fix grandchildren subclassing when parent
     mixed with concrete data types.

   - bpo-35022(87): *note unittest.mock.MagicMock: 874. now supports the
     ‘__fspath__’ method (from *note os.PathLike: 5e5.).

   - bpo-35008(88): Fixed references leaks when call the
     ‘__setstate__()’ method of *note xml.etree.ElementTree.Element:
     21d. in the C implementation for already initialized element.

   - bpo-23420(89): Verify the value for the parameter ’-s’ of the
     cProfile CLI. Patch by Robert Kuska

   - bpo-33947(90): dataclasses now handle recursive reprs without
     raising RecursionError.

   - bpo-34890(91): Make *note inspect.iscoroutinefunction(): 7e9, *note
     inspect.isgeneratorfunction(): 1156. and *note
     inspect.isasyncgenfunction(): 1157. work with *note
     functools.partial(): 8b5.  Patch by Pablo Galindo.

   - bpo-34521(92): Use *note socket.CMSG_SPACE(): 1158. to calculate
     ancillary data size instead of *note socket.CMSG_LEN(): 1159. in
     ‘multiprocessing.reduction.recvfds()’ as RFC 3542(93) requires the
     use of the former for portable applications.

   - bpo-31522(94): The ‘mailbox.mbox.get_string’ function `from_'
     parameter can now successfully be set to a non-default value.

   - bpo-34970(95): Protect tasks weak set manipulation in
     ‘asyncio.all_tasks()’

   - bpo-34969(96): 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).

   - bpo-16965(97): The *note 2to3: 115a. *note execfile: 115b. fixer
     now opens the file with mode ‘'rb'’.  Patch by Zackery Spytz.

   - bpo-34966(98): *note pydoc: d9. now supports aliases not only to
     methods defined in the end class, but also to inherited methods.
     The docstring is not duplicated for aliases.

   - bpo-34926(99): *note mimetypes.MimeTypes.guess_type(): 115c. now
     accepts *note path-like object: 472. in addition to url strings.
     Patch by Mayank Asthana.

   - bpo-23831(100): Add ‘moveto()’ method to the ‘tkinter.Canvas’
     widget.  Patch by Juliette Monsel.

   - bpo-34941(101): Methods ‘find()’, ‘findtext()’ and ‘findall()’ of
     the ‘Element’ class in the *note xml.etree.ElementTree: 140. module
     are now able to find children which are instances of ‘Element’
     subclasses.

   - bpo-32680(102): *note smtplib.SMTP: 1de. objects now always have a
     ‘sock’ attribute present

   - bpo-34769(103): Fix for async generators not finalizing when event
     loop is in debug mode and garbage collector runs in another thread.

   - bpo-34936(104): Fix ‘TclError’ in
     ‘tkinter.Spinbox.selection_element()’.  Patch by Juliette Monsel.

   - bpo-34829(105): Add methods ‘selection_from’, ‘selection_range’,
     ‘selection_present’ and ‘selection_to’ to the ‘tkinter.Spinbox’ for
     consistency with the ‘tkinter.Entry’ widget.  Patch by Juliette
     Monsel.

   - bpo-34911(106): Added `secure_protocols' argument to
     `http.cookiejar.DefaultCookiePolicy' to allow for tweaking of
     protocols and also to add support by default for `wss', the secure
     websocket protocol.

   - bpo-34922(107): Fixed integer overflow in the *note digest(): 115d.
     and *note hexdigest(): 115e. methods for the SHAKE algorithm in the
     *note hashlib: 8c. module.

   - bpo-34925(108): 25% speedup in argument parsing for the functions
     in the bisect module.

   - bpo-34900(109): Fixed *note unittest.TestCase.debug(): f6e. when
     used to call test methods with subtests.  Patch by Bruno Oliveira.

   - bpo-34844(110): 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.

   - bpo-34897(111): Adjust test.support.missing_compiler_executable
     check so that a nominal command name of "" is ignored.  Patch by
     Michael Felt.

   - bpo-34871(112): Fix inspect module polluted ‘sys.modules’ when
     parsing ‘__text_signature__’ of callable.

   - bpo-34898(113): Add ‘mtime’ argument to *note gzip.compress: 302.
     for reproducible output.  Patch by Guo Ci Teo.

   - bpo-28441(114): On Cygwin and MinGW, ensure that ‘sys.executable’
     always includes the full filename in the path, including the ‘.exe’
     suffix (unless it is a symbolic link).

   - bpo-34866(115): Adding ‘max_num_fields’ to ‘cgi.FieldStorage’ to
     make DOS attacks harder by limiting the number of
     ‘MiniFieldStorage’ objects created by ‘FieldStorage’.

   - bpo-34711(116): 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.

   - bpo-34872(117): Fix self-cancellation in C implementation of
     asyncio.Task

   - bpo-34849(118): Don’t log waiting for ‘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.

   - bpo-34022(119): The ‘SOURCE_DATE_EPOCH’ environment variable no
     longer overrides the value of the `invalidation_mode' argument to
     *note py_compile.compile(): 343, and determines its default value
     instead.

   - bpo-34819(120): 使用一个单一时钟计算 ‘Executor.map()’ 和
     ‘as_completed()’ 中的超时，以防止当系统时钟被修改时因偏离导致的超时
     。

   - bpo-34758(121): Add .wasm -> application/wasm to list of recognized
     file types and content type headers

   - bpo-34789(122): *note xml.sax.make_parser(): 115f. now accepts any
     iterable as its `parser_list' argument.  Patch by Andrés Delfino.

   - bpo-34334(123): In ‘QueueHandler’, clear ‘exc_text’ from
     ‘LogRecord’ to prevent traceback from being written twice.

   - bpo-34687(124): On Windows, asyncio now uses ProactorEventLoop,
     instead of SelectorEventLoop, by default.

   - bpo-5950(125): Support reading zip files with archive comments in
     *note zipimport: 14c.

   - bpo-32892(126): The parser now represents all constants as *note
     ast.Constant: 3a6. instead of using specific constant AST types
     (‘Num’, ‘Str’, ‘Bytes’, ‘NameConstant’ and ‘Ellipsis’).  These
     classes are considered deprecated and will be removed in future
     Python versions.

   - bpo-34728(127): Add deprecation warning when ‘loop’ is used in
     methods: *note asyncio.sleep: 3aa, *note asyncio.wait: 207. and
     *note asyncio.wait_for: 191.

   - bpo-34738(128): ZIP files created by *note distutils: 38. will now
     include entries for directories.

   - bpo-34659(129): Add an optional `initial' argument to
     itertools.accumulate().

   - bpo-29577(130): Support multiple mixin classes when creating Enums.

   - bpo-34670(131): Add SSLContext.post_handshake_auth and
     SSLSocket.verify_client_post_handshake for TLS 1.3’s post handshake
     authentication feature.

   - bpo-32718(132): The Activate.ps1 script from venv works with
     PowerShell Core 6.1 and is now available under all operating
     systems.

   - bpo-31177(133): Fix bug that prevented using *note reset_mock: 6a1.
     on mock instances with deleted attributes

   - bpo-34672(134): Add a workaround, so the ‘'Z'’ *note
     time.strftime(): c37. specifier on the musl C library can work in
     some cases.

   - bpo-34666(135): Implement ‘asyncio.StreamWriter.awrite’ and
     ‘asyncio.StreamWriter.aclose()’ coroutines.  Methods are needed for
     providing a consistent stream API with control flow switched on by
     default.

   - bpo-6721(136): Acquire the logging module’s commonly used internal
     locks while fork()ing to avoid deadlocks in the child process.

   - bpo-34658(137): 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.

   - bpo-34652(138): Ensure *note os.lchmod(): 1160. is never defined on
     Linux.

   - bpo-34638(139): 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 ‘close()’ call.

   - bpo-34536(140): ‘Enum._missing_’: raise *note ValueError: 16d. if
     None returned and *note TypeError: 1fe. if non-member is returned.

   - bpo-34636(141): Speed up re scanning of many non-matching
     characters for s w and d within bytes objects.  (microoptimization)

   - bpo-24412(142): Add *note addModuleCleanup(): 374. and *note
     addClassCleanup(): 375. to unittest to support cleanups for
     ‘setUpModule()’ and *note setUpClass(): 376.  Patch by Lisa Roach.

   - bpo-34630(143): Don’t log SSL certificate errors in asyncio code
     (connection error logging is skipped already).

   - bpo-32490(144): Prevent filename duplication in *note subprocess:
     f9. exception messages.  Patch by Zackery Spytz.

   - bpo-34363(145): dataclasses.asdict() and .astuple() now handle
     namedtuples correctly.

   - bpo-34625(146): Update vendorized expat library version to 2.2.6.

   - bpo-32270(147): 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.

   - bpo-34622(148): Create a dedicated ‘asyncio.CancelledError’,
     ‘asyncio.InvalidStateError’ and ‘asyncio.TimeoutError’ exception
     classes.  Inherit them from corresponding exceptions from
     ‘concurrent.futures’ package.  Extract ‘asyncio’ exceptions into a
     separate file.

   - bpo-34610(149): Fixed iterator of
     ‘multiprocessing.managers.DictProxy’.

   - bpo-34421(150): Fix distutils logging for non-ASCII strings.  This
     caused installation issues on Windows.

   - bpo-34604(151): Fix possible mojibake in the error message of *note
     pwd.getpwnam: 1161. and *note grp.getgrnam: 1162. using string
     representation because of invisible characters or trailing
     whitespaces.  Patch by William Grzybowski.

   - bpo-30977(152): Make uuid.UUID use ‘__slots__’ to reduce its memory
     footprint.  Based on original patch by Wouter Bolsterlee.

   - bpo-34574(153): OrderedDict iterators are not exhausted during
     pickling anymore.  Patch by Sergey Fedoseev.

   - bpo-8110(154): Refactored *note subprocess: f9. to check for
     Windows-specific modules rather than ‘sys.platform == 'win32'’.

   - bpo-34530(155): ‘distutils.spawn.find_executable()’ now falls back
     on *note os.defpath: 111a. if the ‘PATH’ environment variable is
     not set.

   - bpo-34563(156): On Windows, fix multiprocessing.Connection for very
     large read: fix _winapi.PeekNamedPipe() and _winapi.ReadFile() for
     read larger than INT_MAX (usually ‘2**31-1’).

   - bpo-34558(157): Correct typo in Lib/ctypes/_aix.py

   - bpo-34282(158): Move ‘Enum._convert’ to ‘EnumMeta._convert_’ and
     fix enum members getting shadowed by parent attributes.

   - bpo-22872(159): When the queue is closed, *note ValueError: 16d. is
     now raised by *note multiprocessing.Queue.put(): 1163. and *note
     multiprocessing.Queue.get(): 1164. instead of *note AssertionError:
     240. and *note OSError: 304, respectively.  Patch by Zackery Spytz.

   - bpo-34515(160): Fix parsing non-ASCII identifiers in
     ‘lib2to3.pgen2.tokenize’ (PEP 3131).

   - bpo-13312(161): Avoids a possible integer underflow (undefined
     behavior) in the time module’s year handling code when passed a
     very low negative year value.

   - bpo-34472(162): Improved compatibility for streamed files in *note
     zipfile: 14b.  Previously an optional signature was not being
     written and certain ZIP applications were not supported.  Patch by
     Silas Sewell.

   - bpo-34454(163): 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.

   - bpo-6700(164): Fix inspect.getsourcelines for module level
     frames/tracebacks.  Patch by Vladimir Matveev.

   - bpo-34171(165): Running the *note trace: 11b. module no longer
     creates the ‘trace.cover’ file.

   - bpo-34441(166): Fix crash when an ‘ABC’-derived class with invalid
     ‘__subclasses__’ is passed as the second argument to *note
     issubclass(): 552.  Patch by Alexey Izbyshev.

   - bpo-34427(167): Fix infinite loop in ‘a.extend(a)’ for
     ‘MutableSequence’ subclasses.

   - bpo-34412(168): Make *note signal.strsignal(): 1165. work on HP-UX.
     Patch by Michael Osipov.

   - bpo-20849(169): shutil.copytree now accepts a new ‘dirs_exist_ok’
     keyword argument.  Patch by Josh Bronson.

   - bpo-31715(170): Associate ‘.mjs’ file extension with
     ‘application/javascript’ MIME Type.

   - bpo-34384(171): *note os.readlink(): 1d1. now accepts *note
     path-like: 472. and *note bytes: 172. objects on Windows.

   - bpo-22602(172): The UTF-7 decoder now raises *note
     UnicodeDecodeError: 32b. for ill-formed sequences starting with "+"
     (as specified in RFC 2152).  Patch by Zackery Spytz.

   - bpo-2122(173): The *note mmap.flush(): 3e5. method now returns
     ‘None’ on success, raises an exception on error under all
     platforms.

   - bpo-34341(174): Appending to the ZIP archive with the ZIP64
     extension no longer grows the size of extra fields of existing
     entries.

   - bpo-34333(175): 修复在 *note pathlib.PurePath.with_suffix(): 1166.
     内使用%-formatting 格式化错误信息的错误。

   - bpo-18540(176): The *note imaplib.IMAP4: 1af. and *note
     imaplib.IMAP4_SSL: 1b0. classes now resolve to the local host IP
     correctly when the default value of `host' parameter (‘''’) is
     used.

   - bpo-26502(177): Implement ‘traceback.FrameSummary.__len__()’ method
     to preserve compatibility with the old tuple API.

   - bpo-34318(178): *note assertRaises(): b92, *note
     assertRaisesRegex(): b93, *note assertWarns(): b94. and *note
     assertWarnsRegex(): b95. 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.

   - bpo-9372(179): Deprecate *note __getitem__(): 3a5. methods of *note
     xml.dom.pulldom.DOMEventStream: 3a2, *note
     wsgiref.util.FileWrapper: 3a3. and *note fileinput.FileInput: 3a4.

   - bpo-33613(180): Fix a race condition in
     ‘multiprocessing.semaphore_tracker’ when the tracker receives
     SIGINT before it can register signal handlers for ignoring it.

   - bpo-34248(181): Report filename in the exception raised when the
     database file cannot be opened by *note dbm.gnu.open(): 1167. and
     *note dbm.ndbm.open(): 1168. due to OS-related error.  Patch by
     Zsolt Cserna.

   - bpo-33089(182): Add math.dist() to compute the Euclidean distance
     between two points.

   - bpo-34246(183): *note smtplib.SMTP.send_message(): 834. no longer
     modifies the content of the `mail_options' argument.  Patch by
     Pablo S. Blum de Aguiar.

   - bpo-31047(184): Fix ‘ntpath.abspath’ for invalid paths on windows.
     Patch by Franz Woellert.

   - bpo-32321(185): Add pure Python fallback for functools.reduce.
     Patch by Robert Wright.

   - bpo-34270(186): The default asyncio task class now always has a
     name which can be get or set using two new methods (*note
     get_name(): 2e4. and *note set_name(): 2e3.) and is visible in the
     *note repr(): 8b9. output.  An initial name can also be set using
     the new ‘name’ keyword argument to *note asyncio.create_task():
     2e1. or the ‘create_task()’ method of the event loop.  If no
     initial name is set, the default Task implementation generates a
     name like ‘Task-1’ using a monotonic counter.

   - bpo-34263(187): asyncio’s event loop will not pass timeouts longer
     than one day to epoll/select etc.

   - bpo-34035(188): Fix several AttributeError in zipfile seek()
     methods.  Patch by Mickaël Schoentgen.

   - bpo-32215(189): Fix performance regression in *note sqlite3: f2.
     when a DML statement appeared in a different line than the rest of
     the SQL query.

   - bpo-34075(190): Deprecate passing non-ThreadPoolExecutor instances
     to ‘AbstractEventLoop.set_default_executor()’.

   - bpo-34251(191): Restore ‘msilib.Win64’ to preserve backwards
     compatibility since it’s already used by *note distutils: 38.’
     ‘bdist_msi’ command.

   - bpo-19891(192): Ignore errors caused by missing / non-writable
     homedir while writing history during exit of an interactive
     session.  Patch by Anthony Sottile.

   - bpo-33089(193): Enhanced math.hypot() to support more than two
     dimensions.

   - bpo-34228(194): tracemalloc: PYTHONTRACEMALLOC=0 environment
     variable and -X tracemalloc=0 command line option are now allowed
     to disable explicitly tracemalloc at startup.

   - bpo-13041(195): Use *note shutil.get_terminal_size(): b25. to
     calculate the terminal width correctly in the
     ‘argparse.HelpFormatter’ class.  Initial patch by Zbyszek
     Jędrzejewski-Szmek.

   - bpo-34213(196): Allow frozen dataclasses to have a field named
     "object".  Previously this conflicted with an internal use of
     "object".

   - bpo-34052(197): *note sqlite3.Connection.create_aggregate(): 10d3,
     *note sqlite3.Connection.create_function(): 10d4, *note
     sqlite3.Connection.set_authorizer(): 10d5, *note
     sqlite3.Connection.set_progress_handler(): 10d6. 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.

   - bpo-34197(198): Attributes `skipinitialspace', `doublequote' and
     `strict' of the `dialect' attribute of the *note csv: 29. reader
     are now *note bool: 2bd. instances instead of integers 0 or 1.

   - bpo-32788(199): Errors other than *note TypeError: 1fe. raised in
     methods ‘__adapt__()’ and ‘__conform__()’ in the *note sqlite3: f2.
     module are now propagated to the user.

   - bpo-21446(200): The *note reload: 1169. fixer now uses *note
     importlib.reload(): 49f. instead of deprecated *note imp.reload():
     d38.

   - bpo-940286(201): pydoc’s ‘Helper.showtopic()’ method now prints the
     cross references of a topic correctly.

   - bpo-34164(202): *note base64.b32decode(): a3e. could raise
     UnboundLocalError or OverflowError for incorrect padding.  Now it
     always raises ‘base64.Error’ in these cases.

   - bpo-33729(203): Fixed issues with arguments parsing in *note
     hashlib: 8c.

   - bpo-34097(204): ZipFile can zip files older than 1980-01-01 and
     newer than 2107-12-31 using a new ‘strict_timestamps’ parameter at
     the cost of setting the timestamp to the limit.

   - bpo-34108(205): Remove extraneous CR in 2to3 refactor.

   - bpo-34070(206): Make sure to only check if the handle is a tty,
     when opening a file with ‘buffering=-1’.

   - bpo-27494(207): Reverted bpo-27494(208).  2to3 rejects now a
     trailing comma in generator expressions.

   - bpo-33967(209): functools.singledispatch now raises TypeError
     instead of IndexError when no positional arguments are passed.

   - bpo-34041(210): Add the parameter `deterministic' to the *note
     sqlite3.Connection.create_function(): 10d4. method.  Patch by
     Sergey Fedoseev.

   - bpo-34056(211): Ensure the loader shim created by ‘imp.load_module’
     always returns bytes from its ‘get_data()’ function.  This fixes
     using ‘imp.load_module’ with PEP 552(212) hash-based pycs.

   - bpo-34054(213): The multiprocessing module now uses the monotonic
     clock *note time.monotonic(): 85e. instead of the system clock
     *note time.time(): 42d. to implement timeout.

   - bpo-34043(214): Optimize tarfile uncompress performance about 15%
     when gzip is used.

   - bpo-34044(215): ‘subprocess.Popen’ now copies the `startupinfo'
     argument to leave it unchanged: it will modify the copy, so that
     the same ‘STARTUPINFO’ object can be used multiple times.

   - bpo-34010(216): Fixed a performance regression for reading streams
     with tarfile.  The buffered read should use a list, instead of
     appending to a bytes object.

   - bpo-34019(217): webbrowser: Correct the arguments passed to Opera
     Browser when opening a new URL using the ‘webbrowser’ module.
     Patch by Bumsik Kim.

   - bpo-34003(218): csv.DictReader now creates dicts instead of
     OrderedDicts.  Patch by Michael Selik.

   - bpo-33978(219): Closed existing logging handlers before
     reconfiguration via fileConfig and dictConfig.  Patch by
     Karthikeyan Singaravelan.

   - bpo-14117(220): 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.

   - bpo-33974(221): Fixed passing lists and tuples of strings
     containing special characters ‘"’, ‘\’, ‘{’, ‘}’ and ‘\n’ as
     options to *note ttk: 118. widgets.

   - bpo-27500(222): Fix getaddrinfo to resolve IPv6 addresses
     correctly.

   - bpo-24567(223): Improve random.choices() to handle subnormal input
     weights that could occasionally trigger an IndexError.

   - bpo-33871(224): Fixed integer overflow in *note os.readv(): 4be,
     *note os.writev(): 4c1, *note os.preadv(): 4bd. and *note
     os.pwritev(): 4c0. and in *note os.sendfile(): 461. with `headers'
     or `trailers' arguments (on BSD-based OSes and macOS).

   - bpo-25007(225): Add *note copy.copy(): 4d1. and *note
     copy.deepcopy(): 4d2. support to zlib compressors and
     decompressors.  Patch by Zackery Spytz.

   - bpo-33929(226): 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.

   - bpo-33899(227): 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.

   - bpo-33897(228): Added a ’force’ keyword argument to
     logging.basicConfig().

   - bpo-33695(229): *note shutil.copytree(): 347. uses *note
     os.scandir(): 389. function and all copy functions depending from
     it use cached *note os.stat(): 321. 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 *note
     os.stat(): 321. syscalls is reduced by 38% making *note
     shutil.copytree(): 347. especially faster on network filesystems.
     (Contributed by Giampaolo Rodola’ in bpo-33695(230).)

   - bpo-33916(231): bz2 and lzma: When Decompressor.__init__() is
     called twice, free the old lock to not leak memory.

   - bpo-32568(232): Make select.epoll() and its documentation
     consistent regarding `sizehint' and `flags'.

   - bpo-33833(233): Fixed bug in asyncio where ProactorSocketTransport
     logs AssertionError if force closed during write.

   - bpo-33663(234): Convert content length to string before putting to
     header.

   - bpo-33721(235): *note os.path: c5. functions that return a boolean
     result like *note exists(): 325, *note lexists(): 326, *note
     isdir(): 327, *note isfile(): 328, *note islink(): 323, and *note
     ismount(): 329, and *note pathlib.Path: 32f. methods that return a
     boolean result like *note exists(): 330, *note is_dir(): 331, *note
     is_file(): 332, *note is_mount(): 333, *note is_symlink(): 334,
     *note is_block_device(): 335, *note is_char_device(): 336, *note
     is_fifo(): 337, *note is_socket(): 338. now return ‘False’ instead
     of raising *note ValueError: 16d. or its subclasses *note
     UnicodeEncodeError: 32a. and *note UnicodeDecodeError: 32b. for
     paths that contain characters or bytes unrepresentable at the OS
     level.

   - bpo-26544(236): Fixed implementation of *note platform.libc_ver():
     1150.  It almost always returned version ’2.9’ for glibc.

   - bpo-33843(237): Remove deprecated ‘cgi.escape’, ‘cgi.parse_qs’ and
     ‘cgi.parse_qsl’.

   - bpo-33842(238): Remove ‘tarfile.filemode’ which is deprecated since
     Python 3.3.

   - bpo-30167(239): Prevent site.main() exception if PYTHONSTARTUP is
     set.  Patch by Steve Weber.

   - bpo-33805(240): Improve error message of dataclasses.replace() when
     an InitVar is not specified

   - bpo-33687(241): Fix the call to ‘os.chmod()’ for ‘uu.decode()’ if a
     mode is given or decoded.  Patch by Timo Furrer.

   - bpo-33812(242): Datetime instance d with non-None tzinfo, but with
     d.tzinfo.utcoffset(d) returning None is now treated as naive by the
     astimezone() method.

   - bpo-32108(243): In configparser, don’t clear section when it is
     assigned to itself.

   - bpo-27397(244): Make email module properly handle invalid-length
     base64 strings.

   - bpo-33578(245): Implement multibyte encoder/decoder state methods

   - bpo-30805(246): Avoid race condition with debug logging

   - bpo-33476(247): Fix _header_value_parser.py when address group is
     missing final ’;’.  Contributed by Enrique Perez-Terron

   - bpo-33694(248): asyncio: Fix a race condition causing data loss on
     pause_reading()/resume_reading() when using the ProactorEventLoop.

   - bpo-32493(249): Correct test for ‘uuid_enc_be’ availability in
     ‘configure.ac’.  Patch by Michael Felt.

   - bpo-33792(250): Add asyncio.WindowsSelectorEventLoopPolicy and
     asyncio.WindowsProactorEventLoopPolicy.

   - bpo-33274(251): 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.

   - bpo-33778(252): Update ‘unicodedata’’s database to Unicode version
     11.0.0.

   - bpo-33165(253): Added a stacklevel parameter to logging calls to
     allow use of wrapper/helper functions for logging APIs.

   - bpo-33770(254): improve base64 exception message for encoded inputs
     of invalid length

   - bpo-33769(255): asyncio/start_tls: Fix error message; cancel
     callbacks in case of an unhandled error; mark SSLTransport as
     closed if it is aborted.

   - bpo-33767(256): The concatenation (‘+’) and repetition (‘*’)
     sequence operations now raise *note TypeError: 1fe. instead of
     *note SystemError: 6f2. when performed on *note mmap.mmap: 31c.
     objects.  Patch by Zackery Spytz.

   - bpo-33734(257): asyncio/ssl: Fix AttributeError, increase default
     handshake timeout

   - bpo-31014(258): Fixed creating a controller for *note webbrowser:
     132. when a user specifies a path to an entry in the BROWSER
     environment variable.  Based on patch by John Still.

   - bpo-2504(259): Add gettext.pgettext() and variants.

   - bpo-33197(260): Add description property for _ParameterKind

   - bpo-32751(261): When cancelling the task due to a timeout, *note
     asyncio.wait_for(): 191. will now wait until the cancellation is
     complete.

   - bpo-32684(262): Fix gather to propagate cancellation of itself even
     with return_exceptions.

   - bpo-33654(263): Support protocol type switching in
     SSLTransport.set_protocol().

   - bpo-33674(264): Pause the transport as early as possible to further
     reduce the risk of data_received() being called before
     connection_made().

   - bpo-33671(265): *note shutil.copyfile(): 382, *note shutil.copy():
     383, *note shutil.copy2(): 384, *note shutil.copytree(): 347. and
     *note shutil.move(): 385. use platform-specific fast-copy syscalls
     on Linux and macOS in order to copy the file more efficiently.  On
     Windows *note shutil.copyfile(): 382. uses a bigger default buffer
     size (1 MiB instead of 16 KiB) and a *note memoryview(): 386.-based
     variant of *note shutil.copyfileobj(): 387. 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(266).)

   - bpo-33674(267): 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.

   - bpo-31647(268): Fixed bug where calling write_eof() on a
     _SelectorSocketTransport after it’s already closed raises
     AttributeError.

   - bpo-32610(269): Make asyncio.all_tasks() return only pending tasks.

   - bpo-32410(270): Avoid blocking on file IO in sendfile fallback code

   - bpo-33469(271): Fix RuntimeError after closing loop that used
     run_in_executor

   - bpo-33672(272): Fix Task.__repr__ crash with Cython’s bogus
     coroutines

   - bpo-33654(273): Fix transport.set_protocol() to support switching
     between asyncio.Protocol and asyncio.BufferedProtocol.  Fix
     loop.start_tls() to work with asyncio.BufferedProtocols.

   - bpo-33652(274): Pickles of type variables and subscripted generics
     are now future-proof and compatible with older Python versions.

   - bpo-32493(275): Fixed *note uuid.uuid1(): 517. on FreeBSD.

   - bpo-33238(276): Add ‘InvalidStateError’ to *note
     concurrent.futures: 21.  ‘Future.set_result’ and
     ‘Future.set_exception’ now raise ‘InvalidStateError’ if the futures
     are not pending or running.  Patch by Jason Haydaman.

   - bpo-33618(277): Finalize and document preliminary and experimental
     TLS 1.3 support with OpenSSL 1.1.1

   - bpo-33625(278): Release GIL on *note grp.getgrnam: 1162, *note
     grp.getgrgid: 6d6, *note pwd.getpwnam: 1161. and *note
     pwd.getpwuid: 114f. if reentrant variants of these functions are
     available.  Patch by William Grzybowski.

   - bpo-33623(279): Fix possible SIGSGV when asyncio.Future is created
     in __del__

   - bpo-11874(280): Use a better regex when breaking usage into
     wrappable parts.  Avoids bogus assertion errors from custom metavar
     strings.

   - bpo-30877(281): 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.

   - bpo-33604(282): Remove HMAC default to md5 marked for removal in
     3.8 (removal originally planned in 3.6, bump to 3.8 in gh-7062).

   - bpo-33582(283): Emit a deprecation warning for
     inspect.formatargspec

   - bpo-21145(284): Add ‘functools.cached_property’ decorator, for
     computed properties cached for the life of the instance.

   - bpo-33570(285): 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.

   - bpo-28556(286): Do not simplify arguments to *note typing.Union:
     116a.  Now ‘Union[Manager, Employee]’ is not simplified to
     ‘Employee’ at runtime.  Such simplification previously caused
     several bugs and limited possibilities for introspection.

   - bpo-12486(287): *note tokenize.generate_tokens(): 116b. is now
     documented as a public API to tokenize unicode strings.  It was
     previously present but undocumented.

   - bpo-33540(288): Add a new ‘block_on_close’ class attribute to
     ‘ForkingMixIn’ and ‘ThreadingMixIn’ classes of *note socketserver:
     f0.

   - bpo-33548(289): tempfile._candidate_tempdir_list should consider
     common TEMP locations

   - bpo-33109(290): argparse subparsers are once again not required by
     default, reverting the change in behavior introduced by
     bpo-26510(291) in 3.7.0a2.

   - bpo-33541(292): Remove unused private method
     ‘_strptime.LocaleTime.__pad’ (a.k.a.  ‘_LocaleTime__pad’).

   - bpo-33536(293): dataclasses.make_dataclass now checks for invalid
     field names and duplicate fields.  Also, added a check for invalid
     field specifications.

   - bpo-33542(294): Prevent ‘uuid.get_node’ from using a DUID instead
     of a MAC on Windows.  Patch by Zvi Effron

   - bpo-26819(295): Fix race condition with
     ‘ReadTransport.resume_reading’ in Windows proactor event loop.

   - Fix failure in *note typing.get_type_hints(): 1ef. when ClassVar
     was provided as a string forward reference.

   - bpo-33516(296): *note unittest.mock.MagicMock: 874. now supports
     the ‘__round__’ magic method.

   - bpo-28612(297): Added support for Site Maps to urllib’s
     ‘RobotFileParser’ as *note RobotFileParser.site_maps(): 116c.
     Patch by Lady Red, based on patch by Peter Wirtz.

   - bpo-28167(298): Remove platform.linux_distribution, which was
     deprecated since 3.5.

   - bpo-33504(299): Switch the default dictionary implementation for
     *note configparser: 22. from *note collections.OrderedDict: 2ea. to
     the standard *note dict: 164. type.

   - bpo-33505(300): Optimize asyncio.ensure_future() by reordering if
     checks: 1.17x faster.

   - bpo-33497(301): Add errors param to cgi.parse_multipart and make an
     encoding in FieldStorage use the given errors (needed for Twisted).
     Patch by Amber Brown.

   - bpo-29235(302): The ‘cProfile.Profile’ class can now be used as a
     context manager.  Patch by Scott Sanderson.

   - bpo-33495(303): 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.

   - bpo-26103(304): Correct ‘inspect.isdatadescriptor’ to look for
     ‘__set__’ or ‘__delete__’.  Patch by Aaron Hall.

   - bpo-29209(305): Removed the ‘doctype()’ method and the `html'
     parameter of the constructor of *note XMLParser: 37c.  The
     ‘doctype()’ method defined in a subclass will no longer be called.
     Deprecated methods ‘getchildren()’ and ‘getiterator()’ in the *note
     ElementTree: 140. module emit now a *note DeprecationWarning: 15a.
     instead of *note PendingDeprecationWarning: 15c.

   - bpo-33453(306): 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").

   - bpo-28556(307): Minor fixes in typing module: add annotations to
     ‘NamedTuple.__new__’, pass ‘*args’ and ‘**kwds’ in
     ‘Generic.__new__’.  Original PRs by Paulius Šarka and Chad
     Dombrova.

   - bpo-33365(308): Print the header values besides the header keys
     instead just the header keys if `debuglevel' is set to >0 in *note
     http.client: 93.  Patch by Marco Strigl.

   - bpo-20087(309): Updated alias mapping with glibc 2.27 supported
     locales.

   - bpo-33422(310): Fix trailing quotation marks getting deleted when
     looking up byte/string literals on pydoc.  Patch by Andrés Delfino.

   - bpo-28167(311): The function ‘platform.linux_distribution’ and
     ‘platform.dist’ now trigger a ‘DeprecationWarning’ and have been
     marked for removal in Python 3.8

   - bpo-33281(312): Fix ctypes.util.find_library regression on macOS.

   - bpo-33311(313): 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.

   - bpo-27300(314): The file classes in `tempfile' now accept an
     `errors' parameter that complements the already existing
     `encoding'.  Patch by Stephan Hohe.

   - bpo-32933(315): *note unittest.mock.mock_open(): 1102. now supports
     iteration over the file contents.  Patch by Tony Flury.

   - bpo-33217(316): Raise *note TypeError: 1fe. when looking up
     non-Enum objects in Enum classes and Enum members.

   - bpo-33197(317): Update error message when constructing invalid
     inspect.Parameters Patch by Dong-hee Na.

   - bpo-33383(318): Fixed crash in the get() method of the *note
     dbm.ndbm: 34. database object when it is called with a single
     argument.

   - bpo-33375(319): 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.

   - bpo-33336(320): ‘imaplib’ now allows ‘MOVE’ command in
     ‘IMAP4.uid()’ (RFC 6851: IMAP MOVE Extension) and potentially as a
     name of supported method of ‘IMAP4’ object.

   - bpo-32455(321): Added `jump' parameter to *note dis.stack_effect():
     927.

   - bpo-27485(322): Rename and deprecate undocumented functions in
     *note urllib.parse(): 128.

   - bpo-33332(323): Add ‘signal.valid_signals()’ to expose the POSIX
     sigfillset() functionality.

   - bpo-33251(324): ‘ConfigParser.items()’ was fixed so that key-value
     pairs passed in via *note vars: 116d. are not included in the
     resulting output.

   - bpo-33329(325): Fix multiprocessing regression on newer glibcs

   - bpo-33334(326): *note dis.stack_effect(): 927. now supports all
     defined opcodes including NOP and EXTENDED_ARG.

   - bpo-991266(327): Fix quoting of the ‘Comment’ attribute of *note
     http.cookies.SimpleCookie: 116e.

   - bpo-33131(328): Upgrade bundled version of pip to 10.0.1.

   - bpo-33308(329): Fixed a crash in the *note parser: c7. module when
     converting an ST object to a tree of tuples or lists with
     ‘line_info=False’ and ‘col_info=True’.

   - bpo-23403(330): lib2to3 now uses pickle protocol 4 for pre-computed
     grammars.

   - bpo-33266(331): lib2to3 now recognizes ‘rf'...'’ strings.

   - bpo-11594(332): Ensure line-endings are respected when using
     lib2to3.

   - bpo-33254(333): Have *note importlib.resources.contents(): 116f.
     and *note importlib.abc.ResourceReader.contents(): 1170. return an
     *note iterable: c7c. instead of an *note iterator: 1171.

   - bpo-33265(334): ‘contextlib.ExitStack’ and
     ‘contextlib.AsyncExitStack’ now use a method instead of a wrapper
     function for exit callbacks.

   - bpo-33263(335): Fix FD leak in ‘_SelectorSocketTransport’ Patch by
     Vlad Starostin.

   - bpo-33256(336): Fix display of ‘<module>’ call in the html produced
     by ‘cgitb.html()’.  Patch by Stéphane Blondon.

   - bpo-33144(337): ‘random.Random()’ and its subclassing mechanism got
     optimized to check only once at class/subclass instantiation time
     whether its ‘getrandbits()’ method can be relied on by other
     methods, including ‘randrange()’, for the generation of arbitrarily
     large random integers.  Patch by Wolfgang Maier.

   - bpo-33185(338): Fixed regression when running pydoc with the *note
     -m: 443. switch.  (The regression was introduced in 3.7.0b3 by the
     resolution of bpo-33053(339))

     This fix also changed pydoc to add ‘os.getcwd()’ to *note sys.path:
     261. when necessary, rather than adding ‘"."’.

   - bpo-29613(340): Added support for the ‘SameSite’ cookie flag to the
     ‘http.cookies’ module.

   - bpo-33169(341): Delete entries of ‘None’ in *note
     sys.path_importer_cache: 597. when
     ‘importlib.machinery.invalidate_caches()’ is called.

   - bpo-33203(342): ‘random.Random.choice()’ now raises ‘IndexError’
     for empty sequences consistently even when called from subclasses
     without a ‘getrandbits()’ implementation.

   - bpo-33224(343): Update difflib.mdiff() for PEP 479(344).  Convert
     an uncaught StopIteration in a generator into a return-statement.

   - bpo-33209(345): End framing at the end of C implementation of *note
     pickle.Pickler.dump(): 1172.

   - bpo-32861(346): The urllib.robotparser’s ‘__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.

   - bpo-23403(347): ‘DEFAULT_PROTOCOL’ in *note pickle: ca. was bumped
     to 4.  Protocol 4 is described in PEP 3154(348) and available since
     Python 3.4.  It offers better performance and smaller size compared
     to protocol 3 introduced in Python 3.0.

   - bpo-20104(349): Improved error handling and fixed a reference leak
     in *note os.posix_spawn(): 381.

   - bpo-33106(350): Deleting a key from a read-only dbm database raises
     module specific error instead of KeyError.

   - bpo-33175(351): In dataclasses, Field.__set_name__ now looks up the
     __set_name__ special method on the class, not the instance, of the
     default value.

   - bpo-32380(352): Create functools.singledispatchmethod to support
     generic single dispatch on descriptors and methods.

   - bpo-33141(353): Have Field objects pass through __set_name__ to
     their default values, if they have their own __set_name__.

   - bpo-33096(354): 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.

   - bpo-32873(355): 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.

   - bpo-33134(356): 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.

   - bpo-33127(357): ssl模块现在使用LibreSSL 2.7.1编译。

   - bpo-32505(358): 如果数据类的成员变量的类型为Field，但没有类型注解，
     则引发TypeError。

   - bpo-33078(359): 修复在OSX平台因为依赖sem_getvalue而导致的失败。

   - bpo-33116(360): 将’Field’添加到dataclasses.__all__。

   - bpo-32896(361): Fix an error where subclassing a dataclass with a
     field that uses a default_factory would generate an incorrect
     class.

   - bpo-33100(362): 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.

   - bpo-32953(363): 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.

   - bpo-33097(364): Raise RuntimeError when ‘executor.submit’ is called
     during interpreter shutdown.

   - bpo-32968(365): Modulo and floor division involving Fraction and
     float should return float.

   - bpo-33061(366): 添加丢失的 ‘NoReturn’ 到typing.py的 ‘__all__’

   - bpo-33078(367): Fix the size handling in multiprocessing.Queue when
     a pickling error occurs.

   - bpo-33064(368): lib2to3 now properly supports trailing commas after
     ‘*args’ and ‘**kwargs’ in function signatures.

   - bpo-33056(369): FIX properly close leaking fds in
     concurrent.futures.ProcessPoolExecutor.

   - bpo-33021(370): Release the GIL during fstat() calls, avoiding hang
     of all threads when calling mmap.mmap(), os.urandom(), and
     random.seed().  Patch by Nir Soffer.

   - bpo-31804(371): Avoid failing in multiprocessing.Process if the
     standard streams are closed or None at exit.

   - bpo-33034(372): Providing an explicit error message when casting
     the port property to anything that is not an integer value using
     ‘urlparse()’ and ‘urlsplit()’.  Patch by Matt Eaton.

   - bpo-30249(373): Improve struct.unpack_from() exception messages for
     problems with the buffer size and offset.

   - bpo-33037(374): Skip sending/receiving data after SSL transport
     closing.

   - bpo-27683(375): Fix a regression in *note ipaddress: a2. that
     result of ‘hosts()’ is empty when the network is constructed by a
     tuple containing an integer mask and only 1 bit left for addresses.

   - bpo-22674(376): Add the strsignal() function in the signal module
     that returns the system description of the given signal, as
     returned by strsignal(3).

   - bpo-32999(377): Fix C implementation of ‘ABC.__subclasscheck__(cls,
     subclass)’ crashed when ‘subclass’ is not a type object.

   - bpo-33009(378): Fix inspect.signature() for single-parameter
     partialmethods.

   - bpo-32969(379): Expose several missing constants in zlib and fix
     corresponding documentation.

   - bpo-32056(380): Improved exceptions raised for invalid number of
     channels and sample width when read an audio file in modules *note
     aifc: 4, *note wave: 130. and *note sunau: fa.

   - bpo-32970(381): Improved disassembly of the MAKE_FUNCTION
     instruction.

   - bpo-32844(382): Fix wrong redirection of a low descriptor (0 or 1)
     to stderr in subprocess if another low descriptor is closed.

   - bpo-32960(383): 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.

   - bpo-32713(384): Fixed tarfile.itn handling of out-of-bounds float
     values.  Patch by Joffrey Fuhrer.

   - bpo-32257(385): The ssl module now contains OP_NO_RENEGOTIATION
     constant, available with OpenSSL 1.1.0h or 1.1.1.

   - bpo-32951(386): 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.

   - bpo-32929(387): 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.

   - bpo-32947(388): Add OP_ENABLE_MIDDLEBOX_COMPAT and test workaround
     for TLSv1.3 for future compatibility with OpenSSL 1.1.1.

   - bpo-32146(389): Document the interaction between frozen executables
     and the spawn and forkserver start methods in multiprocessing.

   - bpo-30622(390): The ssl module now detects missing NPN support in
     LibreSSL.

   - bpo-32922(391): dbm.open() now encodes filename with the filesystem
     encoding rather than default encoding.

   - bpo-32759(392): Free unused arenas in multiprocessing.heap.

   - bpo-32859(393): In ‘os.dup2’, don’t check every call whether the
     ‘dup3’ syscall exists or not.

   - bpo-32556(394): nt._getfinalpathname, nt._getvolumepathname and
     nt._getdiskusage now correctly convert from bytes.

   - bpo-21060(395): 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".

   - bpo-32857(396): In *note tkinter: 10e, ‘after_cancel(None)’ now
     raises a *note ValueError: 16d. instead of canceling the first
     scheduled function.  Patch by Cheryl Sabella.

   - bpo-32852(397): Make sure sys.argv remains as a list when running
     trace.

   - bpo-31333(398): ‘_abc’ module is added.  It is a speedup module
     with C implementations for various functions and methods in ‘abc’.
     Creating an ABC subclass and calling ‘isinstance’ or ‘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
     ‘_abc_registry’, ‘_abc_cache’, and ‘_abc_negative_cache’.  There
     are three debugging helper methods that can be used instead
     ‘_dump_registry’, ‘_abc_registry_clear’, and ‘_abc_caches_clear’.

   - bpo-32841(399): Fixed *note asyncio.Condition: 3b0. issue which
     silently ignored cancellation after notifying and cancelling a
     conditional lock.  Patch by Bar Harel.

   - bpo-32819(400): 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.

   - bpo-19675(401): ‘multiprocessing.Pool’ no longer leaks processes if
     its initialization fails.

   - bpo-32394(402): socket: Remove
     TCP_FASTOPEN,TCP_KEEPCNT,TCP_KEEPIDLE,TCP_KEEPINTVL flags on older
     version Windows during run-time.

   - bpo-31787(403): Fixed refleaks of ‘__init__()’ methods in various
     modules.  (Contributed by Oren Milman)

   - bpo-30157(404): Fixed guessing quote and delimiter in
     csv.Sniffer.sniff() when only the last field is quoted.  Patch by
     Jake Davis.

   - bpo-30688(405): Added support of ‘\N{name}’ escapes in regular
     expressions.  Based on patch by Jonathan Eunice.

   - bpo-32792(406): collections.ChainMap() preserves the order of the
     underlying mappings.

   - bpo-32775(407): *note fnmatch.translate(): 1173. 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.

   - bpo-32622(408): Implement native fast sendfile for Windows proactor
     event loop.

   - bpo-32777(409): 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.

   - bpo-32647(410): The ctypes module used to depend on indirect
     linking for dlopen.  The shared extension is now explicitly linked
     against libdl on platforms with dl.

   - bpo-32749(411): A *note dbm.dumb: 32. database opened with flags
     ’r’ is now read-only.  *note dbm.dumb.open(): 3e1. with flags ’r’
     and ’w’ no longer creates a database if it does not exist.

   - bpo-32741(412): Implement ‘asyncio.TimerHandle.when()’ method.

   - bpo-32691(413): Use mod_spec.parent when running modules with pdb

   - bpo-32734(414): Fixed ‘asyncio.Lock()’ safety issue which allowed
     acquiring and locking the same lock multiple times, without it
     being free.  Patch by Bar Harel.

   - bpo-32727(415): Do not include name field in SMTP envelope from
     address.  Patch by Stéphane Wirtel

   - bpo-31453(416): Add TLSVersion constants and
     SSLContext.maximum_version / minimum_version attributes.  The new
     API wraps OpenSSL 1.1
     ‘https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_set_min_proto_version.html’
     feature.

   - bpo-24334(417): 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.

   - bpo-31848(418): Fix the error handling in Aifc_read.initfp() when
     the SSND chunk is not found.  Patch by Zackery Spytz.

   - bpo-32585(419): Add Ttk spinbox widget to *note tkinter.ttk: 118.
     Patch by Alan D Moore.

   - bpo-32512(420): *note profile: d3. CLI accepts ‘-m module_name’ as
     an alternative to script path.

   - bpo-8525(421): 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.

   - bpo-31639(422): http.server now exposes a ThreadingHTTPServer class
     and uses it when the module is run with ‘-m’ to cope with web
     browsers pre-opening sockets.

   - bpo-29877(423): compileall: import ProcessPoolExecutor only when
     needed, preventing hangs on low resource platforms

   - bpo-32221(424): Various functions returning tuple containing IPv6
     addresses now omit ‘%scope’ part since the same information is
     already encoded in `scopeid' tuple item.  Especially this speeds up
     ‘socket.recvfrom()’ when it receives multicast packet since useless
     resolving of network interface name is omitted.

   - bpo-32147(425): *note binascii.unhexlify(): 1174. is now up to 2
     times faster.  Patch by Sergey Fedoseev.

   - bpo-30693(426): The TarFile class now recurses directories in a
     reproducible way.

   - bpo-30693(427): The ZipFile class now recurses directories in a
     reproducible way.

   - bpo-31680(428): Added *note curses.ncurses_version: 2f0.

   - bpo-31908(429): Fix output of cover files for ‘trace’ module
     command-line tool.  Previously emitted cover files only when
     ‘--missing’ option was used.  Patch by Michael Selik.

   - bpo-31608(430): Raise a ‘TypeError’ instead of crashing if a
     ‘collections.deque’ subclass returns a non-deque from ‘__new__’.
     Patch by Oren Milman.

   - bpo-31425(431): 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.

   - bpo-22005(432): Implemented unpickling instances of *note datetime:
     19f, *note date: 19d. and *note time: 5ec. pickled by Python 2.
     ‘encoding='latin1'’ should be used for successful decoding.

   - bpo-27645(433): *note sqlite3.Connection: 4de. now exposes a *note
     backup: 4df. method, if the underlying SQLite library is at version
     3.6.11 or higher.  Patch by Lele Gaifax.

   - bpo-16865(434): Support arrays >=2GiB in *note ctypes: 2a.  Patch
     by Segev Finer.

   - bpo-31508(435): Removed support of arguments in *note
     tkinter.ttk.Treeview.selection: 3df.  It was deprecated in 3.6.
     Use specialized methods like ‘selection_set’ for changing the
     selection.

   - bpo-29456(436): Fix bugs in hangul normalization: u1176, u11a7 and
     u11c3

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35845

   (2) https://bugs.python.org/issue35864

   (3) https://bugs.python.org/issue35537

   (4) https://bugs.python.org/issue35847

   (5) https://bugs.python.org/issue35813

   (6) https://bugs.python.org/issue35780

   (7) https://bugs.python.org/issue35537

   (8) https://bugs.python.org/issue23846

   (9) https://bugs.python.org/issue34323

   (10) https://bugs.python.org/issue35674

   (11) https://bugs.python.org/issue35733

   (12) https://bugs.python.org/issue35726

   (13) https://bugs.python.org/issue35719

   (14) https://bugs.python.org/issue35717

   (15) https://bugs.python.org/issue35699

   (16) https://bugs.python.org/issue32710

   (17) https://bugs.python.org/issue35702

   (18) https://bugs.python.org/issue32710

   (19) https://bugs.python.org/issue35682

   (20) https://bugs.python.org/issue35283

   (21) https://bugs.python.org/issue35664

   (22) https://bugs.python.org/issue35643

   (23) https://bugs.python.org/issue35619

   (24) https://bugs.python.org/issue28503

   (25) https://bugs.python.org/issue35614

   (26) https://bugs.python.org/issue35568

   (27) https://bugs.python.org/issue35588

   (28) https://bugs.python.org/issue35585

   (29) https://bugs.python.org/issue30561

   (30) https://bugs.python.org/issue35537

   (31) https://bugs.python.org/issue35526

   (32) https://bugs.python.org/issue35523

   (33) https://bugs.python.org/issue31784

   (34) https://bugs.python.org/issue35513

   (35) https://bugs.python.org/issue35502

   (36) https://bugs.python.org/issue35348

   (37) https://bugs.python.org/issue35491

   (38) https://bugs.python.org/issue35477

   (39) https://bugs.python.org/issue31446

   (40) https://bugs.python.org/issue35471

   (41) https://bugs.python.org/issue23057

   (42) https://bugs.python.org/issue35052

   (43) https://bugs.python.org/issue20239

   (44) https://bugs.python.org/issue17185

   (45) https://bugs.python.org/issue35445

   (46) https://bugs.python.org/issue35415

   (47) https://bugs.python.org/issue35424

   (48) https://bugs.python.org/issue35330

   (49) https://bugs.python.org/issue35346

   (50) https://bugs.python.org/issue10496

   (51) https://bugs.python.org/issue10496

   (52) https://bugs.python.org/issue35389

   (53) https://bugs.python.org/issue35394

   (54) https://bugs.python.org/issue35310

   (55) https://bugs.python.org/issue35380

   (56) https://bugs.python.org/issue35341

   (57) https://bugs.python.org/issue35371

   (58) https://bugs.python.org/issue35346

   (59) https://bugs.python.org/issue35066

   (60) https://bugs.python.org/issue35345

   (61) https://bugs.python.org/issue35344

   (62) https://bugs.python.org/issue35312

   (63) https://bugs.python.org/issue35308

   (64) https://bugs.python.org/issue24746

   (65) https://bugs.python.org/issue28604

   (66) https://bugs.python.org/issue35277

   (67) https://bugs.python.org/issue24209

   (68) https://bugs.python.org/issue35226

   (69) https://bugs.python.org/issue29564

   (70) https://bugs.python.org/issue35189

   (71) https://bugs.python.org/issue30064

   (72) https://bugs.python.org/issue35186

   (73) https://bugs.python.org/issue35152

   (74) https://bugs.python.org/issue35062

   (75) https://bugs.python.org/issue35065

   (76) https://bugs.python.org/issue34160

   (77) https://bugs.python.org/issue35079

   (78) https://bugs.python.org/issue33710

   (79) https://bugs.python.org/issue35017

   (80) https://bugs.python.org/issue35024

   (81) https://bugs.python.org/issue35047

   (82) https://bugs.python.org/issue31047

   (83) https://bugs.python.org/issue35053

   (84) https://bugs.python.org/issue31553

   (85) https://bugs.python.org/issue34794

   (86) https://bugs.python.org/issue34909

   (87) https://bugs.python.org/issue35022

   (88) https://bugs.python.org/issue35008

   (89) https://bugs.python.org/issue23420

   (90) https://bugs.python.org/issue33947

   (91) https://bugs.python.org/issue34890

   (92) https://bugs.python.org/issue34521

   (93) https://tools.ietf.org/html/rfc3542.html

   (94) https://bugs.python.org/issue31522

   (95) https://bugs.python.org/issue34970

   (96) https://bugs.python.org/issue34969

   (97) https://bugs.python.org/issue16965

   (98) https://bugs.python.org/issue34966

   (99) https://bugs.python.org/issue34926

   (100) https://bugs.python.org/issue23831

   (101) https://bugs.python.org/issue34941

   (102) https://bugs.python.org/issue32680

   (103) https://bugs.python.org/issue34769

   (104) https://bugs.python.org/issue34936

   (105) https://bugs.python.org/issue34829

   (106) https://bugs.python.org/issue34911

   (107) https://bugs.python.org/issue34922

   (108) https://bugs.python.org/issue34925

   (109) https://bugs.python.org/issue34900

   (110) https://bugs.python.org/issue34844

   (111) https://bugs.python.org/issue34897

   (112) https://bugs.python.org/issue34871

   (113) https://bugs.python.org/issue34898

   (114) https://bugs.python.org/issue28441

   (115) https://bugs.python.org/issue34866

   (116) https://bugs.python.org/issue34711

   (117) https://bugs.python.org/issue34872

   (118) https://bugs.python.org/issue34849

   (119) https://bugs.python.org/issue34022

   (120) https://bugs.python.org/issue34819

   (121) https://bugs.python.org/issue34758

   (122) https://bugs.python.org/issue34789

   (123) https://bugs.python.org/issue34334

   (124) https://bugs.python.org/issue34687

   (125) https://bugs.python.org/issue5950

   (126) https://bugs.python.org/issue32892

   (127) https://bugs.python.org/issue34728

   (128) https://bugs.python.org/issue34738

   (129) https://bugs.python.org/issue34659

   (130) https://bugs.python.org/issue29577

   (131) https://bugs.python.org/issue34670

   (132) https://bugs.python.org/issue32718

   (133) https://bugs.python.org/issue31177

   (134) https://bugs.python.org/issue34672

   (135) https://bugs.python.org/issue34666

   (136) https://bugs.python.org/issue6721

   (137) https://bugs.python.org/issue34658

   (138) https://bugs.python.org/issue34652

   (139) https://bugs.python.org/issue34638

   (140) https://bugs.python.org/issue34536

   (141) https://bugs.python.org/issue34636

   (142) https://bugs.python.org/issue24412

   (143) https://bugs.python.org/issue34630

   (144) https://bugs.python.org/issue32490

   (145) https://bugs.python.org/issue34363

   (146) https://bugs.python.org/issue34625

   (147) https://bugs.python.org/issue32270

   (148) https://bugs.python.org/issue34622

   (149) https://bugs.python.org/issue34610

   (150) https://bugs.python.org/issue34421

   (151) https://bugs.python.org/issue34604

   (152) https://bugs.python.org/issue30977

   (153) https://bugs.python.org/issue34574

   (154) https://bugs.python.org/issue8110

   (155) https://bugs.python.org/issue34530

   (156) https://bugs.python.org/issue34563

   (157) https://bugs.python.org/issue34558

   (158) https://bugs.python.org/issue34282

   (159) https://bugs.python.org/issue22872

   (160) https://bugs.python.org/issue34515

   (161) https://bugs.python.org/issue13312

   (162) https://bugs.python.org/issue34472

   (163) https://bugs.python.org/issue34454

   (164) https://bugs.python.org/issue6700

   (165) https://bugs.python.org/issue34171

   (166) https://bugs.python.org/issue34441

   (167) https://bugs.python.org/issue34427

   (168) https://bugs.python.org/issue34412

   (169) https://bugs.python.org/issue20849

   (170) https://bugs.python.org/issue31715

   (171) https://bugs.python.org/issue34384

   (172) https://bugs.python.org/issue22602

   (173) https://bugs.python.org/issue2122

   (174) https://bugs.python.org/issue34341

   (175) https://bugs.python.org/issue34333

   (176) https://bugs.python.org/issue18540

   (177) https://bugs.python.org/issue26502

   (178) https://bugs.python.org/issue34318

   (179) https://bugs.python.org/issue9372

   (180) https://bugs.python.org/issue33613

   (181) https://bugs.python.org/issue34248

   (182) https://bugs.python.org/issue33089

   (183) https://bugs.python.org/issue34246

   (184) https://bugs.python.org/issue31047

   (185) https://bugs.python.org/issue32321

   (186) https://bugs.python.org/issue34270

   (187) https://bugs.python.org/issue34263

   (188) https://bugs.python.org/issue34035

   (189) https://bugs.python.org/issue32215

   (190) https://bugs.python.org/issue34075

   (191) https://bugs.python.org/issue34251

   (192) https://bugs.python.org/issue19891

   (193) https://bugs.python.org/issue33089

   (194) https://bugs.python.org/issue34228

   (195) https://bugs.python.org/issue13041

   (196) https://bugs.python.org/issue34213

   (197) https://bugs.python.org/issue34052

   (198) https://bugs.python.org/issue34197

   (199) https://bugs.python.org/issue32788

   (200) https://bugs.python.org/issue21446

   (201) https://bugs.python.org/issue940286

   (202) https://bugs.python.org/issue34164

   (203) https://bugs.python.org/issue33729

   (204) https://bugs.python.org/issue34097

   (205) https://bugs.python.org/issue34108

   (206) https://bugs.python.org/issue34070

   (207) https://bugs.python.org/issue27494

   (208) https://bugs.python.org/issue27494

   (209) https://bugs.python.org/issue33967

   (210) https://bugs.python.org/issue34041

   (211) https://bugs.python.org/issue34056

   (212) https://www.python.org/dev/peps/pep-0552

   (213) https://bugs.python.org/issue34054

   (214) https://bugs.python.org/issue34043

   (215) https://bugs.python.org/issue34044

   (216) https://bugs.python.org/issue34010

   (217) https://bugs.python.org/issue34019

   (218) https://bugs.python.org/issue34003

   (219) https://bugs.python.org/issue33978

   (220) https://bugs.python.org/issue14117

   (221) https://bugs.python.org/issue33974

   (222) https://bugs.python.org/issue27500

   (223) https://bugs.python.org/issue24567

   (224) https://bugs.python.org/issue33871

   (225) https://bugs.python.org/issue25007

   (226) https://bugs.python.org/issue33929

   (227) https://bugs.python.org/issue33899

   (228) https://bugs.python.org/issue33897

   (229) https://bugs.python.org/issue33695

   (230) https://bugs.python.org/issue33695

   (231) https://bugs.python.org/issue33916

   (232) https://bugs.python.org/issue32568

   (233) https://bugs.python.org/issue33833

   (234) https://bugs.python.org/issue33663

   (235) https://bugs.python.org/issue33721

   (236) https://bugs.python.org/issue26544

   (237) https://bugs.python.org/issue33843

   (238) https://bugs.python.org/issue33842

   (239) https://bugs.python.org/issue30167

   (240) https://bugs.python.org/issue33805

   (241) https://bugs.python.org/issue33687

   (242) https://bugs.python.org/issue33812

   (243) https://bugs.python.org/issue32108

   (244) https://bugs.python.org/issue27397

   (245) https://bugs.python.org/issue33578

   (246) https://bugs.python.org/issue30805

   (247) https://bugs.python.org/issue33476

   (248) https://bugs.python.org/issue33694

   (249) https://bugs.python.org/issue32493

   (250) https://bugs.python.org/issue33792

   (251) https://bugs.python.org/issue33274

   (252) https://bugs.python.org/issue33778

   (253) https://bugs.python.org/issue33165

   (254) https://bugs.python.org/issue33770

   (255) https://bugs.python.org/issue33769

   (256) https://bugs.python.org/issue33767

   (257) https://bugs.python.org/issue33734

   (258) https://bugs.python.org/issue31014

   (259) https://bugs.python.org/issue2504

   (260) https://bugs.python.org/issue33197

   (261) https://bugs.python.org/issue32751

   (262) https://bugs.python.org/issue32684

   (263) https://bugs.python.org/issue33654

   (264) https://bugs.python.org/issue33674

   (265) https://bugs.python.org/issue33671

   (266) https://bugs.python.org/issue25427

   (267) https://bugs.python.org/issue33674

   (268) https://bugs.python.org/issue31647

   (269) https://bugs.python.org/issue32610

   (270) https://bugs.python.org/issue32410

   (271) https://bugs.python.org/issue33469

   (272) https://bugs.python.org/issue33672

   (273) https://bugs.python.org/issue33654

   (274) https://bugs.python.org/issue33652

   (275) https://bugs.python.org/issue32493

   (276) https://bugs.python.org/issue33238

   (277) https://bugs.python.org/issue33618

   (278) https://bugs.python.org/issue33625

   (279) https://bugs.python.org/issue33623

   (280) https://bugs.python.org/issue11874

   (281) https://bugs.python.org/issue30877

   (282) https://bugs.python.org/issue33604

   (283) https://bugs.python.org/issue33582

   (284) https://bugs.python.org/issue21145

   (285) https://bugs.python.org/issue33570

   (286) https://bugs.python.org/issue28556

   (287) https://bugs.python.org/issue12486

   (288) https://bugs.python.org/issue33540

   (289) https://bugs.python.org/issue33548

   (290) https://bugs.python.org/issue33109

   (291) https://bugs.python.org/issue26510

   (292) https://bugs.python.org/issue33541

   (293) https://bugs.python.org/issue33536

   (294) https://bugs.python.org/issue33542

   (295) https://bugs.python.org/issue26819

   (296) https://bugs.python.org/issue33516

   (297) https://bugs.python.org/issue28612

   (298) https://bugs.python.org/issue28167

   (299) https://bugs.python.org/issue33504

   (300) https://bugs.python.org/issue33505

   (301) https://bugs.python.org/issue33497

   (302) https://bugs.python.org/issue29235

   (303) https://bugs.python.org/issue33495

   (304) https://bugs.python.org/issue26103

   (305) https://bugs.python.org/issue29209

   (306) https://bugs.python.org/issue33453

   (307) https://bugs.python.org/issue28556

   (308) https://bugs.python.org/issue33365

   (309) https://bugs.python.org/issue20087

   (310) https://bugs.python.org/issue33422

   (311) https://bugs.python.org/issue28167

   (312) https://bugs.python.org/issue33281

   (313) https://bugs.python.org/issue33311

   (314) https://bugs.python.org/issue27300

   (315) https://bugs.python.org/issue32933

   (316) https://bugs.python.org/issue33217

   (317) https://bugs.python.org/issue33197

   (318) https://bugs.python.org/issue33383

   (319) https://bugs.python.org/issue33375

   (320) https://bugs.python.org/issue33336

   (321) https://bugs.python.org/issue32455

   (322) https://bugs.python.org/issue27485

   (323) https://bugs.python.org/issue33332

   (324) https://bugs.python.org/issue33251

   (325) https://bugs.python.org/issue33329

   (326) https://bugs.python.org/issue33334

   (327) https://bugs.python.org/issue991266

   (328) https://bugs.python.org/issue33131

   (329) https://bugs.python.org/issue33308

   (330) https://bugs.python.org/issue23403

   (331) https://bugs.python.org/issue33266

   (332) https://bugs.python.org/issue11594

   (333) https://bugs.python.org/issue33254

   (334) https://bugs.python.org/issue33265

   (335) https://bugs.python.org/issue33263

   (336) https://bugs.python.org/issue33256

   (337) https://bugs.python.org/issue33144

   (338) https://bugs.python.org/issue33185

   (339) https://bugs.python.org/issue33053

   (340) https://bugs.python.org/issue29613

   (341) https://bugs.python.org/issue33169

   (342) https://bugs.python.org/issue33203

   (343) https://bugs.python.org/issue33224

   (344) https://www.python.org/dev/peps/pep-0479

   (345) https://bugs.python.org/issue33209

   (346) https://bugs.python.org/issue32861

   (347) https://bugs.python.org/issue23403

   (348) https://www.python.org/dev/peps/pep-3154

   (349) https://bugs.python.org/issue20104

   (350) https://bugs.python.org/issue33106

   (351) https://bugs.python.org/issue33175

   (352) https://bugs.python.org/issue32380

   (353) https://bugs.python.org/issue33141

   (354) https://bugs.python.org/issue33096

   (355) https://bugs.python.org/issue32873

   (356) https://bugs.python.org/issue33134

   (357) https://bugs.python.org/issue33127

   (358) https://bugs.python.org/issue32505

   (359) https://bugs.python.org/issue33078

   (360) https://bugs.python.org/issue33116

   (361) https://bugs.python.org/issue32896

   (362) https://bugs.python.org/issue33100

   (363) https://bugs.python.org/issue32953

   (364) https://bugs.python.org/issue33097

   (365) https://bugs.python.org/issue32968

   (366) https://bugs.python.org/issue33061

   (367) https://bugs.python.org/issue33078

   (368) https://bugs.python.org/issue33064

   (369) https://bugs.python.org/issue33056

   (370) https://bugs.python.org/issue33021

   (371) https://bugs.python.org/issue31804

   (372) https://bugs.python.org/issue33034

   (373) https://bugs.python.org/issue30249

   (374) https://bugs.python.org/issue33037

   (375) https://bugs.python.org/issue27683

   (376) https://bugs.python.org/issue22674

   (377) https://bugs.python.org/issue32999

   (378) https://bugs.python.org/issue33009

   (379) https://bugs.python.org/issue32969

   (380) https://bugs.python.org/issue32056

   (381) https://bugs.python.org/issue32970

   (382) https://bugs.python.org/issue32844

   (383) https://bugs.python.org/issue32960

   (384) https://bugs.python.org/issue32713

   (385) https://bugs.python.org/issue32257

   (386) https://bugs.python.org/issue32951

   (387) https://bugs.python.org/issue32929

   (388) https://bugs.python.org/issue32947

   (389) https://bugs.python.org/issue32146

   (390) https://bugs.python.org/issue30622

   (391) https://bugs.python.org/issue32922

   (392) https://bugs.python.org/issue32759

   (393) https://bugs.python.org/issue32859

   (394) https://bugs.python.org/issue32556

   (395) https://bugs.python.org/issue21060

   (396) https://bugs.python.org/issue32857

   (397) https://bugs.python.org/issue32852

   (398) https://bugs.python.org/issue31333

   (399) https://bugs.python.org/issue32841

   (400) https://bugs.python.org/issue32819

   (401) https://bugs.python.org/issue19675

   (402) https://bugs.python.org/issue32394

   (403) https://bugs.python.org/issue31787

   (404) https://bugs.python.org/issue30157

   (405) https://bugs.python.org/issue30688

   (406) https://bugs.python.org/issue32792

   (407) https://bugs.python.org/issue32775

   (408) https://bugs.python.org/issue32622

   (409) https://bugs.python.org/issue32777

   (410) https://bugs.python.org/issue32647

   (411) https://bugs.python.org/issue32749

   (412) https://bugs.python.org/issue32741

   (413) https://bugs.python.org/issue32691

   (414) https://bugs.python.org/issue32734

   (415) https://bugs.python.org/issue32727

   (416) https://bugs.python.org/issue31453

   (417) https://bugs.python.org/issue24334

   (418) https://bugs.python.org/issue31848

   (419) https://bugs.python.org/issue32585

   (420) https://bugs.python.org/issue32512

   (421) https://bugs.python.org/issue8525

   (422) https://bugs.python.org/issue31639

   (423) https://bugs.python.org/issue29877

   (424) https://bugs.python.org/issue32221

   (425) https://bugs.python.org/issue32147

   (426) https://bugs.python.org/issue30693

   (427) https://bugs.python.org/issue30693

   (428) https://bugs.python.org/issue31680

   (429) https://bugs.python.org/issue31908

   (430) https://bugs.python.org/issue31608

   (431) https://bugs.python.org/issue31425

   (432) https://bugs.python.org/issue22005

   (433) https://bugs.python.org/issue27645

   (434) https://bugs.python.org/issue16865

   (435) https://bugs.python.org/issue31508

   (436) https://bugs.python.org/issue29456


File: python.info,  Node: 文档<25>,  Next: 测试<24>,  Prev: 库<30>,  Up: Python 3 8 0 alpha 1

1.19.31.4 文档
..............

   - bpo-21257(1): Document *note http.client.parse_headers(): 1176.

   - bpo-34764(2): Improve example of iter() with 2nd sentinel argument.

   - bpo-35564(3): Explicitly set master_doc variable in conf.py for
     compliance with Sphinx 2.0

   - bpo-35511(4): 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.

   - bpo-10536(5): Enhance the gettext docs.  Patch by Éric Araujo

   - bpo-35089(6): Remove mention of ‘typing.io’ and ‘typing.re’.  Their
     types should be imported from ‘typing’ directly.

   - bpo-35038(7): Fix the documentation about an unexisting
     ‘f_restricted’ attribute in the frame object.  Patch by Stéphane
     Wirtel

   - bpo-35042(8): Replace PEP XYZ by the pep role and allow to use the
     direct links to the PEPs.

   - bpo-35044(9): Fix the documentation with the role ‘exc’ for the
     appropriated exception.  Patch by Stéphane Wirtel

   - bpo-35035(10): Rename documentation for *note email.utils: 74. to
     ‘email.utils.rst’.

   - bpo-34967(11): Use app.add_object_type() instead of the deprecated
     Sphinx function app.description_unit()

   - bpo-34913(12): Add documentation about the new command line
     interface of the gzip module.

   - bpo-32174(13): chm document displays non-ASCII charaters properly
     on some MBCS Windows systems.

   - bpo-11233(14): Create availability directive for documentation.
     Original patch by Georg Brandl.

   - bpo-34790(15): Document how passing coroutines to asyncio.wait()
     can be confusing.

   - bpo-34552(16): Make clear that ‘==’ operator sometimes is
     equivalent to ‘is’.  The ‘<’, ‘<=’, ‘>’ and ‘>=’ operators are only
     defined where they make sense.

   - bpo-28617(17): Fixed info in the stdtypes docs concerning the types
     that support membership tests.

   - bpo-20177(18): Migrate datetime.date.fromtimestamp to Argument
     Clinic.  Patch by Tim Hoffmann.

   - bpo-34065(19): Fix wrongly written basicConfig documentation markup
     syntax

   - bpo-33460(20): replaced ellipsis with correct error codes in
     tutorial chapter 3.

   - bpo-33847(21): Add ’@’ operator entry to index.

   - bpo-33409(22): Clarified the relationship between PEP 538(23)’s
     PYTHONCOERCECLOCALE and PEP 540’s PYTHONUTF8 mode.

   - bpo-33197(24): Add versionadded tag to the documentation of
     ParameterKind.description

   - bpo-17045(25): 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.

   - bpo-33736(26): Improve the documentation of *note
     asyncio.open_connection(): 46b, *note asyncio.start_server(): 46c.
     and their UNIX socket counterparts.

   - bpo-23859(27): Document that *note asyncio.wait(): 207. does not
     cancel its futures on timeout.

   - bpo-32436(28): Document PEP 567(29) changes to asyncio.

   - bpo-33604(30): 更新HMAC md5默认报告DeprecationWarning，并将在3.8移
     除。

   - bpo-33594(31): Document ‘getargspec’, ‘from_function’ and
     ‘from_builtin’ as deprecated in their respective docstring, and
     include version since deprecation in DeprecationWarning message.

   - bpo-33503(32): 修复错误的pypi链接

   - bpo-33421(33): 为‘‘typing.AsyncContextManager‘‘添加缺失的文档。

   - bpo-33487(34): 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.

   - bpo-33378(35): Add Korean language switcher for
     ‘https://docs.python.org/3/’

   - bpo-33276(36): Clarify that the ‘__path__’ attribute on modules
     cannot be just any value.

   - bpo-33201(37): Modernize documentation for writing C extension
     types.

   - bpo-33195(38): Deprecate ‘Py_UNICODE’ usage in ‘c-api/arg’
     document.  ‘Py_UNICODE’ related APIs are deprecated since Python
     3.3, but it is missed in the document.

   - bpo-33126(39): Document PyBuffer_ToContiguous().

   - bpo-27212(40): Modify documentation for the ‘islice()’ recipe to
     consume initial values up to the start index.

   - bpo-28247(41): Update *note zipapp: 14a. documentation to describe
     how to make standalone applications.

   - bpo-18802(42): Documentation changes for ipaddress.  Patch by Jon
     Foster and Berker Peksag.

   - bpo-27428(43): Update documentation to clarify that
     ‘WindowsRegistryFinder’ implements ‘MetaPathFinder’.  (Patch by
     Himanshu Lakhara)

   - bpo-28124(44): 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.

   - bpo-17232(45): Clarify docs for -O and -OO. Patch by Terry Reedy.

   - bpo-32436(46): Add documentation for the contextvars module (PEP
     567).

   - bpo-32800(47): Update link to w3c doc for xml default namespaces.

   - bpo-11015(48): Update *note test.support: 106. documentation.

   - bpo-32613(49): Update the faq/windows.html to use the py command
     from PEP 397 instead of python.

   - bpo-8722(50): Document *note __getattr__(): 42a. behavior when
     property ‘get()’ method raises *note AttributeError: 4a1.

   - bpo-32614(51): Modify RE examples in documentation to use raw
     strings to prevent *note DeprecationWarning: 15a. and add text to
     REGEX HOWTO to highlight the deprecation.

   - bpo-20709(52): Remove the paragraph where we explain that
     os.utime() does not support a directory as path under Windows.
     Patch by Jan-Philip Gehrcke

   - bpo-32722(53): Remove the bad example in the tutorial of the
     Generator Expression.  Patch by Stéphane Wirtel

   - bpo-31972(54): Improve docstrings for *note pathlib.PurePath: 235.
     subclasses.

   - bpo-30607(55): Use the externalized ‘python-docs-theme’ package
     when building the documentation.

   - bpo-8243(56): Add a note about curses.addch and curses.addstr
     exception behavior when writing outside a window, or pad.

   - bpo-32337(57): Update documentation related with ‘dict’ order.

   - bpo-25041(58): Document ‘AF_PACKET’ in the *note socket: ef.
     module.

   - bpo-31432(59): Clarify meaning of CERT_NONE, CERT_OPTIONAL, and
     CERT_REQUIRED flags for ssl.SSLContext.verify_mode.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21257

   (2) https://bugs.python.org/issue34764

   (3) https://bugs.python.org/issue35564

   (4) https://bugs.python.org/issue35511

   (5) https://bugs.python.org/issue10536

   (6) https://bugs.python.org/issue35089

   (7) https://bugs.python.org/issue35038

   (8) https://bugs.python.org/issue35042

   (9) https://bugs.python.org/issue35044

   (10) https://bugs.python.org/issue35035

   (11) https://bugs.python.org/issue34967

   (12) https://bugs.python.org/issue34913

   (13) https://bugs.python.org/issue32174

   (14) https://bugs.python.org/issue11233

   (15) https://bugs.python.org/issue34790

   (16) https://bugs.python.org/issue34552

   (17) https://bugs.python.org/issue28617

   (18) https://bugs.python.org/issue20177

   (19) https://bugs.python.org/issue34065

   (20) https://bugs.python.org/issue33460

   (21) https://bugs.python.org/issue33847

   (22) https://bugs.python.org/issue33409

   (23) https://www.python.org/dev/peps/pep-0538

   (24) https://bugs.python.org/issue33197

   (25) https://bugs.python.org/issue17045

   (26) https://bugs.python.org/issue33736

   (27) https://bugs.python.org/issue23859

   (28) https://bugs.python.org/issue32436

   (29) https://www.python.org/dev/peps/pep-0567

   (30) https://bugs.python.org/issue33604

   (31) https://bugs.python.org/issue33594

   (32) https://bugs.python.org/issue33503

   (33) https://bugs.python.org/issue33421

   (34) https://bugs.python.org/issue33487

   (35) https://bugs.python.org/issue33378

   (36) https://bugs.python.org/issue33276

   (37) https://bugs.python.org/issue33201

   (38) https://bugs.python.org/issue33195

   (39) https://bugs.python.org/issue33126

   (40) https://bugs.python.org/issue27212

   (41) https://bugs.python.org/issue28247

   (42) https://bugs.python.org/issue18802

   (43) https://bugs.python.org/issue27428

   (44) https://bugs.python.org/issue28124

   (45) https://bugs.python.org/issue17232

   (46) https://bugs.python.org/issue32436

   (47) https://bugs.python.org/issue32800

   (48) https://bugs.python.org/issue11015

   (49) https://bugs.python.org/issue32613

   (50) https://bugs.python.org/issue8722

   (51) https://bugs.python.org/issue32614

   (52) https://bugs.python.org/issue20709

   (53) https://bugs.python.org/issue32722

   (54) https://bugs.python.org/issue31972

   (55) https://bugs.python.org/issue30607

   (56) https://bugs.python.org/issue8243

   (57) https://bugs.python.org/issue32337

   (58) https://bugs.python.org/issue25041

   (59) https://bugs.python.org/issue31432


File: python.info,  Node: 测试<24>,  Next: 构建<23>,  Prev: 文档<25>,  Up: Python 3 8 0 alpha 1

1.19.31.5 测试
..............

   - bpo-35772(1): 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.

   - bpo-35045(2): Make ssl tests less strict and also accept TLSv1 as
     system default.  The changes unbreaks test_min_max_version on
     Fedora 29.

   - bpo-32710(3): ‘test_asyncio/test_sendfile.py’ now resets the event
     loop policy using ‘tearDownModule()’ as done in other tests, to
     prevent a warning when running tests on Windows.

   - bpo-33717(4): test.pythoninfo now logs information of all clocks,
     not only time.time() and time.perf_counter().

   - bpo-35488(5): Add a test to pathlib’s Path.match() to verify it
     does not support glob-style ** recursive pattern matching.

   - bpo-31731(6): Fix a race condition in ‘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.

   - bpo-35424(7): Fix test_multiprocessing_main_handling: use
     ‘multiprocessing.Pool’ with a context manager and then explicitly
     join the pool.

   - bpo-35519(8): Rename ‘test.bisect’ module to ‘test.bisect_cmd’ to
     avoid conflict with *note bisect: 11. module when running directly
     a test like ‘./python Lib/test/test_xmlrpc.py’.

   - bpo-35513(9): Replace *note time.time(): 42d. with *note
     time.monotonic(): 85e. in tests to measure time delta.

   - bpo-34279(10): *note test.support.run_unittest(): 1178. no longer
     raise ‘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.

   - bpo-35412(11): Add testcase to ‘test_future4’: check unicode
     literal.

   - bpo-26704(12): 添加了对一个实例方法进行双重修补的测试演示。 补丁作
     者为 Anthony Sottile。

   - bpo-33725(13): test_multiprocessing_fork may crash on recent
     versions of macOS. Until the issue is resolved, skip the test on
     macOS.

   - bpo-35352(14): Modify test_asyncio to use the certificate set from
     the test directory.

   - bpo-35317(15): Fix ‘mktime()’ overflow error in ‘test_email’: run
     ‘test_localtime_daylight_true_dst_true()’ and
     ‘test_localtime_daylight_false_dst_true()’ with a specific
     timezone.

   - bpo-21263(16): 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

   - bpo-34279(17): 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.

   - bpo-34962(18): make docstest in Doc now passes., and is enforced in
     CI

   - bpo-23596(19): Use argparse for the command line of the gzip
     module.  Patch by Antony Lee

   - bpo-34537(20): Fix ‘test_gdb.test_strings()’ when ‘LC_ALL=C’ and
     GDB was compiled with Python 3.6 or earlier.

   - bpo-34587(21): 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.

   - bpo-34661(22): Fix test_shutil if unzip doesn’t support -t.

   - bpo-34200(23): 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.

   - bpo-34569(24): The experimental PEP 554 data channels now correctly
     pass negative PyLong objects between subinterpreters on 32-bit
     systems.  Patch by Michael Felt.

   - bpo-34594(25): Fix usage of hardcoded ‘errno’ values in the tests.

   - bpo-34579(26): Fix test_embed for AIX Patch by Michael Felt

   - bpo-34542(27): Use 3072 RSA keys and SHA-256 signature for test
     certs and keys.

   - bpo-11193(28): Remove special condition for AIX in
     ‘test_subprocess.test_undecodable_env’

   - bpo-34347(29): Fix ‘test_utf8_mode.test_cmd_line’ for AIX

   - bpo-34490(30): On AIX with AF_UNIX family sockets getsockname()
     does not provide ’sockname’, so skip calls to
     transport.get_extra_info(’sockname’)

   - bpo-34391(31): Fix ftplib test for TLS 1.3 by reading from data
     socket.

   - bpo-11192(32): Fix ‘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()

   - bpo-34399(33): Update all RSA keys and DH params to use at least
     2048 bits.

   - bpo-34373(34): Fix ‘test_mktime’ and ‘test_pthread_getcpuclickid’
     tests for AIX Add range checking for ‘_PyTime_localtime’ for AIX
     Patch by Michael Felt

   - bpo-11191(35): Skip the distutils test ’test_search_cpp’ when using
     XLC as compiler patch by aixtools (Michael Felt)

   - Improved an error message when mock assert_has_calls fails.

   - bpo-33746(36): Fix test_unittest when run in verbose mode.

   - bpo-33901(37): Fix test_dbm_gnu on macOS with gdbm 1.15: add a
     larger value to make sure that the file size changes.

   - bpo-33873(38): Fix a bug in ‘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).

   - bpo-33562(39): Check that a global asyncio event loop policy is not
     left behind by any tests.

   - bpo-33655(40): 忽略运行在BSD平台的ZFS上时test_posix_fallocate的失败
     。

   - bpo-32962(41): Fixed test_gdb when Python is compiled with flags
     -mcet -fcf-protection -O0.

   - bpo-33358(42): Fix
     ‘test_embed.test_pre_initialization_sys_options()’ when the
     interpreter is built with ‘--enable-shared’.

   - bpo-32872(43): Avoid regrtest compatibility issue with namespace
     packages.

   - bpo-32517(44): Fix failing ‘test_asyncio’ on macOS 10.12.2+ due to
     transport of ‘KqueueSelector’ loop was not being closed.

   - bpo-32663(45): Making sure the ‘SMTPUTF8SimTests’ class of tests
     gets run in test_smtplib.py.

   - bpo-27643(46): 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

   - bpo-19417(47): Add test_bdb.py.

   - bpo-31809(48): Add tests to verify connection with secp ECDH
     curves.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35772

   (2) https://bugs.python.org/issue35045

   (3) https://bugs.python.org/issue32710

   (4) https://bugs.python.org/issue33717

   (5) https://bugs.python.org/issue35488

   (6) https://bugs.python.org/issue31731

   (7) https://bugs.python.org/issue35424

   (8) https://bugs.python.org/issue35519

   (9) https://bugs.python.org/issue35513

   (10) https://bugs.python.org/issue34279

   (11) https://bugs.python.org/issue35412

   (12) https://bugs.python.org/issue26704

   (13) https://bugs.python.org/issue33725

   (14) https://bugs.python.org/issue35352

   (15) https://bugs.python.org/issue35317

   (16) https://bugs.python.org/issue21263

   (17) https://bugs.python.org/issue34279

   (18) https://bugs.python.org/issue34962

   (19) https://bugs.python.org/issue23596

   (20) https://bugs.python.org/issue34537

   (21) https://bugs.python.org/issue34587

   (22) https://bugs.python.org/issue34661

   (23) https://bugs.python.org/issue34200

   (24) https://bugs.python.org/issue34569

   (25) https://bugs.python.org/issue34594

   (26) https://bugs.python.org/issue34579

   (27) https://bugs.python.org/issue34542

   (28) https://bugs.python.org/issue11193

   (29) https://bugs.python.org/issue34347

   (30) https://bugs.python.org/issue34490

   (31) https://bugs.python.org/issue34391

   (32) https://bugs.python.org/issue11192

   (33) https://bugs.python.org/issue34399

   (34) https://bugs.python.org/issue34373

   (35) https://bugs.python.org/issue11191

   (36) https://bugs.python.org/issue33746

   (37) https://bugs.python.org/issue33901

   (38) https://bugs.python.org/issue33873

   (39) https://bugs.python.org/issue33562

   (40) https://bugs.python.org/issue33655

   (41) https://bugs.python.org/issue32962

   (42) https://bugs.python.org/issue33358

   (43) https://bugs.python.org/issue32872

   (44) https://bugs.python.org/issue32517

   (45) https://bugs.python.org/issue32663

   (46) https://bugs.python.org/issue27643

   (47) https://bugs.python.org/issue19417

   (48) https://bugs.python.org/issue31809


File: python.info,  Node: 构建<23>,  Next: Windows<24>,  Prev: 测试<24>,  Up: Python 3 8 0 alpha 1

1.19.31.6 构建
..............

   - bpo-34691(1): The _contextvars module is now built into the core
     Python library on Windows.

   - bpo-35683(2): Improved Azure Pipelines build steps and now
     verifying layouts correctly

   - bpo-35642(3): Remove asynciomodule.c from pythoncore.vcxproj

   - bpo-35550(4): Fix incorrect Solaris #ifdef checks to look for __sun
     && __SVR4 instead of sun when compiling.

   - bpo-35499(5): ‘make profile-opt’ no longer replaces ‘CFLAGS_NODIST’
     with ‘CFLAGS’.  It now adds profile-guided optimization (PGO) flags
     to ‘CFLAGS_NODIST’: existing ‘CFLAGS_NODIST’ flags are kept.

   - bpo-35257(6): Avoid leaking the linker flags from Link Time
     Optimizations (LTO) into distutils when compiling C extensions.

   - bpo-35351(7): When building Python with clang and LTO, LTO flags
     are no longer passed into CFLAGS to build third-party C extensions
     through distutils.

   - bpo-35139(8): Fix a compiler error when statically linking
     ‘pyexpat’ in ‘Modules/Setup’.

   - bpo-35059(9): 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.

   - bpo-35011(10): 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.

   - bpo-28015(11): Have –with-lto works correctly with clang.

   - bpo-34765(12): Update the outdated install-sh file to the latest
     revision from automake v1.16.1

   - bpo-34585(13): 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.

   - bpo-34710(14): Fixed SSL module build with OpenSSL & pedantic
     CFLAGS.

   - bpo-34582(15): Add JUnit XML output for regression tests and update
     Azure DevOps builds.

   - bpo-34081(16): Make Sphinx warnings as errors in the Docs Makefile.

   - bpo-34555(17): Fix for case where it was not possible to have both
     ‘HAVE_LINUX_VM_SOCKETS_H’ and ‘HAVE_SOCKADDR_ALG’ be undefined.

   - bpo-33015(18): Fix an undefined behaviour in the pthread
     implementation of ‘PyThread_start_new_thread()’: add a function
     wrapper to always return ‘NULL’.

   - bpo-34245(19): The Python shared library is now installed with
     write permission (mode 0755), which is the standard way of
     installing such libraries.

   - bpo-34121(20): Fix detection of C11 atomic support on clang.

   - bpo-32430(21): 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.

   - bpo-30345(22): Add -g to LDFLAGS when compiling with LTO to get
     debug symbols.

   - bpo-5755(23): Move ‘-Wstrict-prototypes’ option to ‘CFLAGS_NODIST’
     from ‘OPT’.  This option emitted annoying warnings when building
     extension modules written in C++.

   - bpo-33614(24): Ensures module definition files for the stable ABI
     on Windows are correctly regenerated.

   - bpo-33648(25): The –with-c-locale-warning configuration flag has
     been removed.  It has had no effect for about a year.

   - bpo-33522(26): Enable CI builds on Visual Studio Team Services at
     ‘https://python.visualstudio.com/cpython’

   - bpo-33512(27): configure’s check for "long double" has been
     simplified

   - bpo-33483(28): C compiler is now correctly detected from the
     standard environment variables.  –without-gcc and –with-icc options
     have been removed.

   - bpo-33394(29): Enable the verbose build for extension modules, when
     GNU make is passed macros on the command line.

   - bpo-33393(30): Update config.guess and config.sub files.

   - bpo-33377(31): Add new triplets for mips r6 and riscv variants
     (used in extension suffixes).

   - bpo-32232(32): By default, modules configured in ‘Modules/Setup’
     are no longer built with ‘-DPy_BUILD_CORE’.  Instead, modules that
     specifically need that preprocessor definition include it in their
     individual entries.

   - bpo-33182(33): The embedding tests can once again be built with
     clang 6.0

   - bpo-33163(34): Upgrade pip to 9.0.3 and setuptools to v39.0.1.

   - bpo-33012(35): 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.

   - bpo-32898(36): Fix the python debug build when using COUNT_ALLOCS.

   - bpo-29442(37): Replace optparse with argparse in setup.py

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue34691

   (2) https://bugs.python.org/issue35683

   (3) https://bugs.python.org/issue35642

   (4) https://bugs.python.org/issue35550

   (5) https://bugs.python.org/issue35499

   (6) https://bugs.python.org/issue35257

   (7) https://bugs.python.org/issue35351

   (8) https://bugs.python.org/issue35139

   (9) https://bugs.python.org/issue35059

   (10) https://bugs.python.org/issue35011

   (11) https://bugs.python.org/issue28015

   (12) https://bugs.python.org/issue34765

   (13) https://bugs.python.org/issue34585

   (14) https://bugs.python.org/issue34710

   (15) https://bugs.python.org/issue34582

   (16) https://bugs.python.org/issue34081

   (17) https://bugs.python.org/issue34555

   (18) https://bugs.python.org/issue33015

   (19) https://bugs.python.org/issue34245

   (20) https://bugs.python.org/issue34121

   (21) https://bugs.python.org/issue32430

   (22) https://bugs.python.org/issue30345

   (23) https://bugs.python.org/issue5755

   (24) https://bugs.python.org/issue33614

   (25) https://bugs.python.org/issue33648

   (26) https://bugs.python.org/issue33522

   (27) https://bugs.python.org/issue33512

   (28) https://bugs.python.org/issue33483

   (29) https://bugs.python.org/issue33394

   (30) https://bugs.python.org/issue33393

   (31) https://bugs.python.org/issue33377

   (32) https://bugs.python.org/issue32232

   (33) https://bugs.python.org/issue33182

   (34) https://bugs.python.org/issue33163

   (35) https://bugs.python.org/issue33012

   (36) https://bugs.python.org/issue32898

   (37) https://bugs.python.org/issue29442


File: python.info,  Node: Windows<24>,  Next: macOS<20>,  Prev: 构建<23>,  Up: Python 3 8 0 alpha 1

1.19.31.7 Windows
.................

   - bpo-35890(1): Fix API calling consistency of GetVersionEx and
     wcstok.

   - bpo-32560(2): The ‘py’ launcher now forwards its ‘STARTUPINFO’
     structure to child processes.

   - bpo-35854(3): Fix EnvBuilder and –symlinks in venv on Windows

   - bpo-35811(4): Avoid propagating venv settings when launching via
     py.exe

   - bpo-35797(5): Fix default executable used by the multiprocessing
     module

   - bpo-35758(6): Allow building on ARM with MSVC.

   - bpo-29734(7): Fix handle leaks in os.stat on Windows.

   - bpo-35596(8): Use unchecked PYCs for the embeddable distro to avoid
     zipimport restrictions.

   - bpo-35596(9): Fix vcruntime140.dll being added to embeddable distro
     multiple times.

   - bpo-35402(10): 更新 Windows 构建以使用 Tcl 和 Tk 8.6.9

   - bpo-35401(11): 将Windows内部版本更新到OpenSSL 1.1.0j

   - bpo-34977(12): venv on Windows will now use a python.exe redirector
     rather than copying the actual binaries from the base environment.

   - bpo-34977(13): Adds support for building a Windows App Store
     package

   - bpo-35067(14): Remove _distutils_findvs module and use vswhere.exe
     instead.

   - bpo-32557(15): Allow shutil.disk_usage to take a file path on
     Windows

   - bpo-34770(16): Fix a possible null pointer dereference in
     pyshellext.cpp.

   - bpo-34603(17): Fix returning structs from functions produced by
     MSVC

   - bpo-34581(18): Guard MSVC-specific code in socketmodule.c with
     ‘#ifdef _MSC_VER’.

   - bpo-34532(19): Fixes exit code of list version arguments for
     py.exe.

   - bpo-34062(20): Fixed the ’–list’ and ’–list-paths’ arguments for
     the py.exe launcher

   - bpo-34225(21): Ensure INCLUDE and LIB directories do not end with a
     backslash.

   - bpo-34011(22): 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.

   - bpo-34006(23): 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.

   - bpo-31546(24): 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.

   - bpo-30237(25): Output error when ReadConsole is canceled by
     CancelSynchronousIo instead of crashing.

   - bpo-33895(26): GIL is released while calling functions that acquire
     Windows loader lock.

   - bpo-33720(27): Reduces maximum marshal recursion depth on release
     builds.

   - bpo-29097(28): Fix bug where ‘datetime.fromtimestamp()’ erroneously
     throws an *note OSError: 304. on Windows for values between 0 and
     86400.  Patch by Ammar Askar.

   - bpo-33316(29): PyThread_release_lock always fails

   - bpo-33184(30): 在Windows安装程序中将OpenSSL更新为1.1.0h.

   - bpo-32890(31): Fix usage of GetLastError() instead of errno in
     os.execve() and os.truncate().

   - bpo-33016(32): Fix potential use of uninitialized memory in
     nt._getfinalpathname

   - bpo-32903(33): Fix a memory leak in os.chdir() on Windows if the
     current directory is set to a UNC path.

   - bpo-32901(34): Update Tcl and Tk versions to 8.6.8

   - bpo-31966(35): Fixed WindowsConsoleIO.write() for writing empty
     data.

   - bpo-32409(36): Ensures activate.bat can handle Unicode contents.

   - bpo-32457(37): Improves handling of denormalized executable path
     when launching Python.

   - bpo-32370(38): Use the correct encoding for ipconfig output in the
     uuid module.  Patch by Segev Finer.

   - bpo-29248(39): Fix *note os.readlink(): 1d1. on Windows, which was
     mistakenly treating the ‘PrintNameOffset’ field of the reparse data
     buffer as a number of characters instead of bytes.  Patch by Craig
     Holmquist and SSE4.

   - bpo-1104(40): Correctly handle string length in
     ‘msilib.SummaryInfo.GetProperty()’ to prevent it from truncating
     the last character.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35890

   (2) https://bugs.python.org/issue32560

   (3) https://bugs.python.org/issue35854

   (4) https://bugs.python.org/issue35811

   (5) https://bugs.python.org/issue35797

   (6) https://bugs.python.org/issue35758

   (7) https://bugs.python.org/issue29734

   (8) https://bugs.python.org/issue35596

   (9) https://bugs.python.org/issue35596

   (10) https://bugs.python.org/issue35402

   (11) https://bugs.python.org/issue35401

   (12) https://bugs.python.org/issue34977

   (13) https://bugs.python.org/issue34977

   (14) https://bugs.python.org/issue35067

   (15) https://bugs.python.org/issue32557

   (16) https://bugs.python.org/issue34770

   (17) https://bugs.python.org/issue34603

   (18) https://bugs.python.org/issue34581

   (19) https://bugs.python.org/issue34532

   (20) https://bugs.python.org/issue34062

   (21) https://bugs.python.org/issue34225

   (22) https://bugs.python.org/issue34011

   (23) https://bugs.python.org/issue34006

   (24) https://bugs.python.org/issue31546

   (25) https://bugs.python.org/issue30237

   (26) https://bugs.python.org/issue33895

   (27) https://bugs.python.org/issue33720

   (28) https://bugs.python.org/issue29097

   (29) https://bugs.python.org/issue33316

   (30) https://bugs.python.org/issue33184

   (31) https://bugs.python.org/issue32890

   (32) https://bugs.python.org/issue33016

   (33) https://bugs.python.org/issue32903

   (34) https://bugs.python.org/issue32901

   (35) https://bugs.python.org/issue31966

   (36) https://bugs.python.org/issue32409

   (37) https://bugs.python.org/issue32457

   (38) https://bugs.python.org/issue32370

   (39) https://bugs.python.org/issue29248

   (40) https://bugs.python.org/issue1104


File: python.info,  Node: macOS<20>,  Next: IDLE<24>,  Prev: Windows<24>,  Up: Python 3 8 0 alpha 1

1.19.31.8 macOS
...............

   - bpo-35401(1): 在MacOS安装程序中将OpenSSL更新为1.1.0j。

   - bpo-35025(2): Properly guard the use of the ‘CLOCK_GETTIME’ et al.
     macros in ‘timemodule’ on macOS.

   - bpo-24658(3): On macOS, fix reading from and writing into a file
     with a size larger than 2 GiB.

   - bpo-34405(4): 在MacOS安装程序中将OpenSSL更新为1.1.0i 。

   - bpo-33635(5): 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.

   - bpo-13631(6): The .editrc file in user’s home directory is now
     processed correctly during the readline initialization through
     editline emulation on macOS.

   - bpo-33184(7): 在MacOS安装程序中将OpenSSL更新为1.1.0h。

   - bpo-32726(8): 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.

   - bpo-32901(9): Update macOS 10.9+ installer to Tcl/Tk 8.6.8.

   - bpo-31903(10): In ‘_scproxy’, drop the GIL when calling into
     ‘SystemConfiguration’ to avoid deadlocks.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35401

   (2) https://bugs.python.org/issue35025

   (3) https://bugs.python.org/issue24658

   (4) https://bugs.python.org/issue34405

   (5) https://bugs.python.org/issue33635

   (6) https://bugs.python.org/issue13631

   (7) https://bugs.python.org/issue33184

   (8) https://bugs.python.org/issue32726

   (9) https://bugs.python.org/issue32901

   (10) https://bugs.python.org/issue31903


File: python.info,  Node: IDLE<24>,  Next: 工具/示例<11>,  Prev: macOS<20>,  Up: Python 3 8 0 alpha 1

1.19.31.9 IDLE
..............

   - bpo-35770(1): 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.

   - bpo-35769(2): 将 IDLE 的新文件名从 ’Untitled’ 更改为 ’untitled’

   - bpo-35660(3): Fix imports in idlelib.window.

   - bpo-35641(4): 当函数没有文档字符串时正确地格式化 ‘calltip’。

   - bpo-33987(5): Use ttk Frame for ttk widgets.

   - bpo-34055(6): Fix erroneous ’smart’ indents and newlines in IDLE
     Shell.

   - bpo-35591(7): Find Selection now works when selection not found.

   - bpo-35196(8): Speed up squeezer line counting.

   - bpo-35598(9): Update config_key: use PEP 8 names and ttk widgets,
     make some objects global, and add tests.

   - bpo-28097(10): Add Previous/Next History entries to Shell menu.

   - bpo-35208(11): Squeezer now properly counts wrapped lines before
     newlines.

   - bpo-35555(12): Gray out Code Context menu entry when it’s not
     applicable.

   - bpo-35521(13): Document the IDLE editor code context feature.  Add
     some internal references within the IDLE doc.

   - bpo-22703(14): 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.

   - bpo-35213(15): Where appropriate, use ’macOS’ in idlelib.

   - bpo-34864(16): On macOS, warn if the system preference "Prefer tabs
     when opening documents" is set to "Always".

   - bpo-34864(17): 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.

   - bpo-35202(18): Remove unused imports from lib/idlelib

   - bpo-33000(19): Document that IDLE’s shell has no line limit.  A
     program that runs indefinitely can overfill memory.

   - bpo-23220(20): Explain how IDLE’s Shell displays output.

   - bpo-35099(21): 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.

   - bpo-35097(22): Add IDLE doc subsection explaining editor windows.
     Topics include opening, title and status bar, .py* extension, and
     running.

   - bpo-35093(23): Document the IDLE document viewer in the IDLE doc.
     Add a paragraph in "Help and preferences", "Help sources"
     subsection.

   - bpo-35088(24): Update idlelib.help.copy_string docstring.  We now
     use git and backporting instead of hg and forward merging.

   - bpo-35087(25): Update idlelib help files for the current doc build.
     The main change is the elimination of chapter-section numbers.

   - bpo-34548(26): Use configured color theme for read-only text views.

   - bpo-1529353(27): 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".

   - bpo-34047(28): Fixed mousewheel scrolling direction on macOS.

   - bpo-34275(29): Make IDLE calltips always visible on Mac.  Some
     MacOS-tk combinations need .update_idletasks().  Patch by Kevin
     Walzer.

   - bpo-34120(30): Fix unresponsiveness after closing certain windows
     and dialogs.

   - bpo-33975(31): 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.

   - bpo-33905(32): Add test for idlelib.stackview.StackBrowser.

   - bpo-33924(33): Change mainmenu.menudefs key ’windows’ to ’window’.
     Every other menudef key is lowercase version of main menu entry.

   - bpo-33906(34): Rename idlelib.windows as window Match Window on the
     main menu and remove last plural module name.

   - bpo-33917(35): 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.

   - bpo-33904(36): IDLE: In rstrip, rename class RstripExtension as
     Rstrip

   - bpo-33907(37): 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.

   - bpo-33856(38): Add "help" in the welcome message of IDLE

   - bpo-33839(39): IDLE: refactor ToolTip and CallTip and add
     documentation and tests

   - bpo-33855(40): Minimally test all IDLE modules.  Add missing files,
     import module, instantiate classes, and check coverage.  Check
     existing files.

   - bpo-33656(41): 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.

   - bpo-33768(42): Clicking on a context line moves that line to the
     top of the editor window.

   - bpo-33763(43): IDLE: Use read-only text widget for code context
     instead of label widget.

   - bpo-33664(44): 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.

   - bpo-33679(45): 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.

   - bpo-33642(46): Display up to maxlines non-blank lines for Code
     Context.  If there is no current context, show a single blank line.

   - bpo-33628(47): IDLE: Cleanup codecontext.py and its test.

   - bpo-33564(48): IDLE’s code context now recognizes async as a block
     opener.

   - bpo-21474(49): 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.

   - bpo-33204(50): 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.

   - bpo-32984(51): Set ‘__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,
     ‘-s’ runs a file named in environmental variable ‘IDLESTARTUP’ or
     *note PYTHONSTARTUP: 9cb.; ‘-r file’ runs ‘file’.  Python sets
     ‘__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 ‘-n’ option.

   - bpo-32940(52): Simplify and rename StringTranslatePseudoMapping in
     pyparse.

   - bpo-32916(53): Change ‘str’ to ‘code’ in pyparse.

   - bpo-32905(54): Remove unused code in pyparse module.

   - bpo-32874(55): Add tests for pyparse.

   - bpo-32837(56): Using the system and place-dependent default
     encoding for open() is a bad idea for IDLE’s system and
     location-independent files.

   - bpo-32826(57): 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.

   - bpo-32831(58): Add docstrings and tests for codecontext.

   - bpo-32765(59): Update configdialog General tab docstring to add new
     widgets to the widget list.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35770

   (2) https://bugs.python.org/issue35769

   (3) https://bugs.python.org/issue35660

   (4) https://bugs.python.org/issue35641

   (5) https://bugs.python.org/issue33987

   (6) https://bugs.python.org/issue34055

   (7) https://bugs.python.org/issue35591

   (8) https://bugs.python.org/issue35196

   (9) https://bugs.python.org/issue35598

   (10) https://bugs.python.org/issue28097

   (11) https://bugs.python.org/issue35208

   (12) https://bugs.python.org/issue35555

   (13) https://bugs.python.org/issue35521

   (14) https://bugs.python.org/issue22703

   (15) https://bugs.python.org/issue35213

   (16) https://bugs.python.org/issue34864

   (17) https://bugs.python.org/issue34864

   (18) https://bugs.python.org/issue35202

   (19) https://bugs.python.org/issue33000

   (20) https://bugs.python.org/issue23220

   (21) https://bugs.python.org/issue35099

   (22) https://bugs.python.org/issue35097

   (23) https://bugs.python.org/issue35093

   (24) https://bugs.python.org/issue35088

   (25) https://bugs.python.org/issue35087

   (26) https://bugs.python.org/issue34548

   (27) https://bugs.python.org/issue1529353

   (28) https://bugs.python.org/issue34047

   (29) https://bugs.python.org/issue34275

   (30) https://bugs.python.org/issue34120

   (31) https://bugs.python.org/issue33975

   (32) https://bugs.python.org/issue33905

   (33) https://bugs.python.org/issue33924

   (34) https://bugs.python.org/issue33906

   (35) https://bugs.python.org/issue33917

   (36) https://bugs.python.org/issue33904

   (37) https://bugs.python.org/issue33907

   (38) https://bugs.python.org/issue33856

   (39) https://bugs.python.org/issue33839

   (40) https://bugs.python.org/issue33855

   (41) https://bugs.python.org/issue33656

   (42) https://bugs.python.org/issue33768

   (43) https://bugs.python.org/issue33763

   (44) https://bugs.python.org/issue33664

   (45) https://bugs.python.org/issue33679

   (46) https://bugs.python.org/issue33642

   (47) https://bugs.python.org/issue33628

   (48) https://bugs.python.org/issue33564

   (49) https://bugs.python.org/issue21474

   (50) https://bugs.python.org/issue33204

   (51) https://bugs.python.org/issue32984

   (52) https://bugs.python.org/issue32940

   (53) https://bugs.python.org/issue32916

   (54) https://bugs.python.org/issue32905

   (55) https://bugs.python.org/issue32874

   (56) https://bugs.python.org/issue32837

   (57) https://bugs.python.org/issue32826

   (58) https://bugs.python.org/issue32831

   (59) https://bugs.python.org/issue32765


File: python.info,  Node: 工具/示例<11>,  Next: C API<20>,  Prev: IDLE<24>,  Up: Python 3 8 0 alpha 1

1.19.31.10 工具/示例
....................

   - bpo-35884(1): Add a benchmark script for timing various ways to
     access variables: ‘Tools/scripts/var_access_benchmark.py’.

   - bpo-34989(2): python-gdb.py now handles errors on computing the
     line number of a Python frame.

   - bpo-20260(3): Argument Clinic now has non-bitwise unsigned int
     converters.

   - bpo-32962(4): python-gdb now catches ‘UnicodeDecodeError’
     exceptions when calling ‘string()’.

   - bpo-32962(5): python-gdb now catches ValueError on read_var(): when
     Python has no debug symbols for example.

   - bpo-33189(6): ‘pygettext.py’ now recognizes only literal strings as
     docstrings and translatable strings, and rejects bytes literals and
     f-string expressions.

   - bpo-31920(7): Fixed handling directories as arguments in the
     ‘pygettext’ script.  Based on patch by Oleg Krasnikov.

   - bpo-29673(8): Fix pystackv and pystack gdbinit macros.

   - bpo-25427(9): Remove the pyvenv script in favor of ‘python3 -m
     venv’ in order to lower confusion as to what Python interpreter a
     virtual environment will be created for.

   - bpo-32885(10): Add an ‘-n’ flag for ‘Tools/scripts/pathfix.py’ to
     disable automatic backup creation (files with ‘~’ suffix).

   - bpo-32222(11): Fix pygettext not extracting docstrings for
     functions with type annotated arguments.  Patch by Toby Harradine.

   - bpo-31583(12): Fix 2to3 for using with –add-suffix option but
     without –output-dir option for relative path to files in current
     directory.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35884

   (2) https://bugs.python.org/issue34989

   (3) https://bugs.python.org/issue20260

   (4) https://bugs.python.org/issue32962

   (5) https://bugs.python.org/issue32962

   (6) https://bugs.python.org/issue33189

   (7) https://bugs.python.org/issue31920

   (8) https://bugs.python.org/issue29673

   (9) https://bugs.python.org/issue25427

   (10) https://bugs.python.org/issue32885

   (11) https://bugs.python.org/issue32222

   (12) https://bugs.python.org/issue31583


File: python.info,  Node: C API<20>,  Prev: 工具/示例<11>,  Up: Python 3 8 0 alpha 1

1.19.31.11 C API
................

   - bpo-35713(1): The ‘PyByteArray_Init()’ and ‘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.

   - bpo-33817(2): Fixed *note _PyBytes_Resize(): 117f. for empty bytes
     objects.

   - bpo-35322(3): Fix memory leak in *note PyUnicode_EncodeLocale():
     541. and *note PyUnicode_EncodeFSDefault(): 1180. on error
     handling.

   - bpo-35059(4): The following C macros have been converted to static
     inline functions: *note Py_INCREF(): 38e, *note Py_DECREF(): 38f,
     *note Py_XINCREF(): 390, *note Py_XDECREF(): 391,
     ‘PyObject_INIT()’, ‘PyObject_INIT_VAR()’.

   - bpo-35296(5): ‘make install’ now also installs the internal API:
     ‘Include/internal/*.h’ header files.

   - bpo-35081(6): Internal APIs surrounded by ‘#ifdef Py_BUILD_CORE’
     have been moved from ‘Include/*.h’ headers to new header files
     ‘Include/internal/pycore_*.h’.

   - bpo-35259(7): 基于 Py_LIMITED_API 有条件地声明 *note
     Py_FinalizeEx(): 6c0. (3.6 中新增)。 补丁作者 Arthur Neufeld。

   - bpo-35081(8): The ‘_PyObject_GC_TRACK()’ and
     ‘_PyObject_GC_UNTRACK()’ macros have been removed from the public C
     API.

   - bpo-35134(9): Creation of a new ‘Include/cpython/’ subdirectory.

   - bpo-34725(10): Adds _Py_SetProgramFullPath so embedders may
     override sys.executable

   - bpo-34910(11): Ensure that *note PyObject_Print(): 1181. always
     returns ‘-1’ on error.  Patch by Zackery Spytz.

   - bpo-34523(12): Py_DecodeLocale() and Py_EncodeLocale() now use the
     UTF-8 encoding on Windows if Py_LegacyWindowsFSEncodingFlag is
     zero.

   - bpo-34193(13): Fix pluralization in TypeError messages in getargs.c
     and typeobject.c: ’1 argument’ instead of ’1 arguments’ and ’1
     element’ instead of ’1 elements’.

   - bpo-34127(14): Return grammatically correct error message based on
     argument count.  Patch by Karthikeyan Singaravelan.

   - bpo-23927(15): Fixed *note SystemError: 6f2. in *note
     PyArg_ParseTupleAndKeywords(): 6c1. when the ‘w*’ format unit is
     used for optional parameter.

   - bpo-32455(16): Added ‘PyCompile_OpcodeStackEffectWithJump()’.

   - bpo-34008(17): Py_Main() can again be called after Py_Initialize(),
     as in Python 3.6.

   - bpo-32500(18): Fixed error messages for *note PySequence_Size():
     1182, *note PySequence_GetItem(): 1183, *note PySequence_SetItem():
     1184. and *note PySequence_DelItem(): 1185. called with a mapping
     and *note PyMapping_Size(): 1186. called with a sequence.

   - bpo-33818(19): ‘PyExceptionClass_Name()’ will now return ‘const
     char *’ instead of ‘char *’.

   - bpo-33042(20): Embedding applications may once again call
     PySys_ResetWarnOptions, PySys_AddWarnOption, and PySys_AddXOption
     prior to calling Py_Initialize.

   - bpo-32374(21): Document that m_traverse for multi-phase initialized
     modules can be called with m_state=NULL, and add a sanity check

   - bpo-30863(22): *note PyUnicode_AsWideChar(): 1187. and *note
     PyUnicode_AsWideCharString(): 53b. no longer cache the ‘wchar_t*’
     representation of string objects.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35713

   (2) https://bugs.python.org/issue33817

   (3) https://bugs.python.org/issue35322

   (4) https://bugs.python.org/issue35059

   (5) https://bugs.python.org/issue35296

   (6) https://bugs.python.org/issue35081

   (7) https://bugs.python.org/issue35259

   (8) https://bugs.python.org/issue35081

   (9) https://bugs.python.org/issue35134

   (10) https://bugs.python.org/issue34725

   (11) https://bugs.python.org/issue34910

   (12) https://bugs.python.org/issue34523

   (13) https://bugs.python.org/issue34193

   (14) https://bugs.python.org/issue34127

   (15) https://bugs.python.org/issue23927

   (16) https://bugs.python.org/issue32455

   (17) https://bugs.python.org/issue34008

   (18) https://bugs.python.org/issue32500

   (19) https://bugs.python.org/issue33818

   (20) https://bugs.python.org/issue33042

   (21) https://bugs.python.org/issue32374

   (22) https://bugs.python.org/issue30863


File: python.info,  Node: Python 3 7 0 正式版,  Next: Python 3 7 0 rc1,  Prev: Python 3 8 0 alpha 1,  Up: Changelog（更動日誌）

1.19.32 Python 3.7.0 正式版
---------------------------

`发布日期: 2018-06-27'

* Menu:

* 库: 库<31>.
* C API: C API<21>.


File: python.info,  Node: 库<31>,  Next: C API<21>,  Up: Python 3 7 0 正式版

1.19.32.1 库
............

   - bpo-33851(1): Fix *note ast.get_docstring(): 118a. for a node that
     lacks a docstring.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33851


File: python.info,  Node: C API<21>,  Prev: 库<31>,  Up: Python 3 7 0 正式版

1.19.32.2 C API
...............

   - bpo-33932(1): Calling Py_Initialize() twice does nothing, instead
     of failing with a fatal error: restore the Python 3.6 behaviour.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33932


File: python.info,  Node: Python 3 7 0 rc1,  Next: Python 3 7 0 beta 5,  Prev: Python 3 7 0 正式版,  Up: Changelog（更動日誌）

1.19.33 Python 3.7.0 rc1
------------------------

`发布日期: 2018-06-12'

* Menu:

* 核心与内置函数: 核心与内置函数<29>.
* 库: 库<32>.
* 文档: 文档<26>.
* 构建: 构建<24>.
* Windows: Windows<25>.
* IDLE: IDLE<25>.


File: python.info,  Node: 核心与内置函数<29>,  Next: 库<32>,  Up: Python 3 7 0 rc1

1.19.33.1 核心与内置函数
........................

   - bpo-33803(1): Fix a crash in hamt.c caused by enabling GC tracking
     for an object that hadn’t all of its fields set to NULL.

   - bpo-33706(2): Fix a crash in Python initialization when parsing the
     command line options.  Thanks Christoph Gohlke for the bug report
     and the fix!

   - bpo-30654(3): 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.

   - bpo-31849(4): Fix signed/unsigned comparison warning in pyhash.c.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33803

   (2) https://bugs.python.org/issue33706

   (3) https://bugs.python.org/issue30654

   (4) https://bugs.python.org/issue31849


File: python.info,  Node: 库<32>,  Next: 文档<26>,  Prev: 核心与内置函数<29>,  Up: Python 3 7 0 rc1

1.19.33.2 库
............

   - bpo-30167(1): Prevent site.main() exception if PYTHONSTARTUP is
     set.  Patch by Steve Weber.

   - bpo-33812(2): Datetime instance d with non-None tzinfo, but with
     d.tzinfo.utcoffset(d) returning None is now treated as naive by the
     astimezone() method.

   - bpo-30805(3): Avoid race condition with debug logging

   - bpo-33694(4): asyncio: Fix a race condition causing data loss on
     pause_reading()/resume_reading() when using the ProactorEventLoop.

   - bpo-32493(5): Correct test for ‘uuid_enc_be’ availability in
     ‘configure.ac’.  Patch by Michael Felt.

   - bpo-33792(6): Add asyncio.WindowsSelectorEventLoopPolicy and
     asyncio.WindowsProactorEventLoopPolicy.

   - bpo-33778(7): Update ‘unicodedata’’s database to Unicode version
     11.0.0.

   - bpo-33770(8): improve base64 exception message for encoded inputs
     of invalid length

   - bpo-33769(9): asyncio/start_tls: Fix error message; cancel
     callbacks in case of an unhandled error; mark SSLTransport as
     closed if it is aborted.

   - bpo-33767(10): The concatenation (‘+’) and repetition (‘*’)
     sequence operations now raise *note TypeError: 1fe. instead of
     *note SystemError: 6f2. when performed on *note mmap.mmap: 31c.
     objects.  Patch by Zackery Spytz.

   - bpo-33734(11): asyncio/ssl: Fix AttributeError, increase default
     handshake timeout

   - bpo-11874(12): Use a better regex when breaking usage into
     wrappable parts.  Avoids bogus assertion errors from custom metavar
     strings.

   - bpo-33582(13): Emit a deprecation warning for inspect.formatargspec

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30167

   (2) https://bugs.python.org/issue33812

   (3) https://bugs.python.org/issue30805

   (4) https://bugs.python.org/issue33694

   (5) https://bugs.python.org/issue32493

   (6) https://bugs.python.org/issue33792

   (7) https://bugs.python.org/issue33778

   (8) https://bugs.python.org/issue33770

   (9) https://bugs.python.org/issue33769

   (10) https://bugs.python.org/issue33767

   (11) https://bugs.python.org/issue33734

   (12) https://bugs.python.org/issue11874

   (13) https://bugs.python.org/issue33582


File: python.info,  Node: 文档<26>,  Next: 构建<24>,  Prev: 库<32>,  Up: Python 3 7 0 rc1

1.19.33.3 文档
..............

   - bpo-33409(1): Clarified the relationship between PEP 538(2)’s
     PYTHONCOERCECLOCALE and PEP 540’s PYTHONUTF8 mode.

   - bpo-33736(3): Improve the documentation of *note
     asyncio.open_connection(): 46b, *note asyncio.start_server(): 46c.
     and their UNIX socket counterparts.

   - bpo-31432(4): Clarify meaning of CERT_NONE, CERT_OPTIONAL, and
     CERT_REQUIRED flags for ssl.SSLContext.verify_mode.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33409

   (2) https://www.python.org/dev/peps/pep-0538

   (3) https://bugs.python.org/issue33736

   (4) https://bugs.python.org/issue31432


File: python.info,  Node: 构建<24>,  Next: Windows<25>,  Prev: 文档<26>,  Up: Python 3 7 0 rc1

1.19.33.4 构建
..............

   - bpo-5755(1): Move ‘-Wstrict-prototypes’ option to ‘CFLAGS_NODIST’
     from ‘OPT’.  This option emitted annoying warnings when building
     extension modules written in C++.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5755


File: python.info,  Node: Windows<25>,  Next: IDLE<25>,  Prev: 构建<24>,  Up: Python 3 7 0 rc1

1.19.33.5 Windows
.................

   - bpo-33720(1): Reduces maximum marshal recursion depth on release
     builds.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33720


File: python.info,  Node: IDLE<25>,  Prev: Windows<25>,  Up: Python 3 7 0 rc1

1.19.33.6 IDLE
..............

   - bpo-33656(1): 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.

   - bpo-33768(2): Clicking on a context line moves that line to the top
     of the editor window.

   - bpo-33763(3): IDLE: Use read-only text widget for code context
     instead of label widget.

   - bpo-33664(4): 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.

   - bpo-33679(5): 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.

   - bpo-33642(6): Display up to maxlines non-blank lines for Code
     Context.  If there is no current context, show a single blank line.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33656

   (2) https://bugs.python.org/issue33768

   (3) https://bugs.python.org/issue33763

   (4) https://bugs.python.org/issue33664

   (5) https://bugs.python.org/issue33679

   (6) https://bugs.python.org/issue33642


File: python.info,  Node: Python 3 7 0 beta 5,  Next: Python 3 7 0 beta 4,  Prev: Python 3 7 0 rc1,  Up: Changelog（更動日誌）

1.19.34 Python 3.7.0 beta 5
---------------------------

`发布日期: 2018-05-30'

* Menu:

* 核心与内置函数: 核心与内置函数<30>.
* 库: 库<33>.
* 文档: 文档<27>.
* 测试: 测试<25>.
* 构建: 构建<25>.
* macOS: macOS<21>.
* IDLE: IDLE<26>.


File: python.info,  Node: 核心与内置函数<30>,  Next: 库<33>,  Up: Python 3 7 0 beta 5

1.19.34.1 核心与内置函数
........................

   - bpo-33622(1): Fixed a leak when the garbage collector fails to add
     an object with the ‘__del__’ method or referenced by it into the
     *note gc.garbage: c12. list.  ‘PyGC_Collect()’ can now be called
     when an exception is set and preserves it.

   - bpo-33509(2): Fix module_globals parameter of
     warnings.warn_explicit(): don’t crash if module_globals is not a
     dict.

   - bpo-20104(3): The new *note os.posix_spawn: 381. 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.

   - bpo-33475(4): Fixed miscellaneous bugs in converting annotations to
     strings and optimized parentheses in the string representation.

   - bpo-33391(5): Fix a leak in set_symmetric_difference().

   - bpo-28055(6): Fix unaligned accesses in siphash24().  Patch by Rolf
     Eike Beer.

   - bpo-32911(7): Due to unexpected compatibility issues discovered
     during downstream beta testing, reverted bpo-29463(8).  ‘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.

   - bpo-21983(9): Fix a crash in *note ctypes.cast(): 114b. in case the
     type argument is a ctypes structured data type.  Patch by Eryk Sun
     and Oren Milman.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33622

   (2) https://bugs.python.org/issue33509

   (3) https://bugs.python.org/issue20104

   (4) https://bugs.python.org/issue33475

   (5) https://bugs.python.org/issue33391

   (6) https://bugs.python.org/issue28055

   (7) https://bugs.python.org/issue32911

   (8) https://bugs.python.org/issue29463

   (9) https://bugs.python.org/issue21983


File: python.info,  Node: 库<33>,  Next: 文档<27>,  Prev: 核心与内置函数<30>,  Up: Python 3 7 0 beta 5

1.19.34.2 库
............

   - bpo-32751(1): When cancelling the task due to a timeout, *note
     asyncio.wait_for(): 191. will now wait until the cancellation is
     complete.

   - bpo-32684(2): Fix gather to propagate cancellation of itself even
     with return_exceptions.

   - bpo-33654(3): Support protocol type switching in
     SSLTransport.set_protocol().

   - bpo-33674(4): Pause the transport as early as possible to further
     reduce the risk of data_received() being called before
     connection_made().

   - bpo-33674(5): 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.

   - bpo-31647(6): Fixed bug where calling write_eof() on a
     _SelectorSocketTransport after it’s already closed raises
     AttributeError.

   - bpo-32610(7): Make asyncio.all_tasks() return only pending tasks.

   - bpo-32410(8): Avoid blocking on file IO in sendfile fallback code

   - bpo-33469(9): Fix RuntimeError after closing loop that used
     run_in_executor

   - bpo-33672(10): Fix Task.__repr__ crash with Cython’s bogus
     coroutines

   - bpo-33654(11): Fix transport.set_protocol() to support switching
     between asyncio.Protocol and asyncio.BufferedProtocol.  Fix
     loop.start_tls() to work with asyncio.BufferedProtocols.

   - bpo-33652(12): Pickles of type variables and subscripted generics
     are now future-proof and compatible with older Python versions.

   - bpo-32493(13): Fixed *note uuid.uuid1(): 517. on FreeBSD.

   - bpo-33618(14): Finalize and document preliminary and experimental
     TLS 1.3 support with OpenSSL 1.1.1

   - bpo-33623(15): Fix possible SIGSGV when asyncio.Future is created
     in __del__

   - bpo-30877(16): 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.

   - bpo-33570(17): 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.

   - bpo-28556(18): Do not simplify arguments to *note typing.Union:
     116a.  Now ‘Union[Manager, Employee]’ is not simplified to
     ‘Employee’ at runtime.  Such simplification previously caused
     several bugs and limited possibilities for introspection.

   - bpo-33540(19): Add a new ‘block_on_close’ class attribute to
     ‘ForkingMixIn’ and ‘ThreadingMixIn’ classes of *note socketserver:
     f0.

   - bpo-33548(20): tempfile._candidate_tempdir_list should consider
     common TEMP locations

   - bpo-33109(21): argparse subparsers are once again not required by
     default, reverting the change in behavior introduced by
     bpo-26510(22) in 3.7.0a2.

   - bpo-33536(23): dataclasses.make_dataclass now checks for invalid
     field names and duplicate fields.  Also, added a check for invalid
     field specifications.

   - bpo-33542(24): Prevent ‘uuid.get_node’ from using a DUID instead of
     a MAC on Windows.  Patch by Zvi Effron

   - bpo-26819(25): Fix race condition with
     ‘ReadTransport.resume_reading’ in Windows proactor event loop.

   - Fix failure in *note typing.get_type_hints(): 1ef. when ClassVar
     was provided as a string forward reference.

   - bpo-33505(26): Optimize asyncio.ensure_future() by reordering if
     checks: 1.17x faster.

   - bpo-33497(27): Add errors param to cgi.parse_multipart and make an
     encoding in FieldStorage use the given errors (needed for Twisted).
     Patch by Amber Brown.

   - bpo-33495(28): 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.

   - bpo-33453(29): 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").

   - bpo-28556(30): Minor fixes in typing module: add annotations to
     ‘NamedTuple.__new__’, pass ‘*args’ and ‘**kwds’ in
     ‘Generic.__new__’.  Original PRs by Paulius Šarka and Chad
     Dombrova.

   - bpo-20087(31): Updated alias mapping with glibc 2.27 supported
     locales.

   - bpo-33422(32): Fix trailing quotation marks getting deleted when
     looking up byte/string literals on pydoc.  Patch by Andrés Delfino.

   - bpo-28167(33): The function ‘platform.linux_distribution’ and
     ‘platform.dist’ now trigger a ‘DeprecationWarning’ and have been
     marked for removal in Python 3.8

   - bpo-33197(34): Update error message when constructing invalid
     inspect.Parameters Patch by Dong-hee Na.

   - bpo-33263(35): Fix FD leak in ‘_SelectorSocketTransport’ Patch by
     Vlad Starostin.

   - bpo-32861(36): The urllib.robotparser’s ‘__str__’ representation
     now includes wildcard entries and the "Crawl-delay" and
     "Request-rate" fields.  Patch by Michael Lazar.

   - bpo-32257(37): The ssl module now contains OP_NO_RENEGOTIATION
     constant, available with OpenSSL 1.1.0h or 1.1.1.

   - bpo-16865(38): Support arrays >=2GiB in *note ctypes: 2a.  Patch by
     Segev Finer.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32751

   (2) https://bugs.python.org/issue32684

   (3) https://bugs.python.org/issue33654

   (4) https://bugs.python.org/issue33674

   (5) https://bugs.python.org/issue33674

   (6) https://bugs.python.org/issue31647

   (7) https://bugs.python.org/issue32610

   (8) https://bugs.python.org/issue32410

   (9) https://bugs.python.org/issue33469

   (10) https://bugs.python.org/issue33672

   (11) https://bugs.python.org/issue33654

   (12) https://bugs.python.org/issue33652

   (13) https://bugs.python.org/issue32493

   (14) https://bugs.python.org/issue33618

   (15) https://bugs.python.org/issue33623

   (16) https://bugs.python.org/issue30877

   (17) https://bugs.python.org/issue33570

   (18) https://bugs.python.org/issue28556

   (19) https://bugs.python.org/issue33540

   (20) https://bugs.python.org/issue33548

   (21) https://bugs.python.org/issue33109

   (22) https://bugs.python.org/issue26510

   (23) https://bugs.python.org/issue33536

   (24) https://bugs.python.org/issue33542

   (25) https://bugs.python.org/issue26819

   (26) https://bugs.python.org/issue33505

   (27) https://bugs.python.org/issue33497

   (28) https://bugs.python.org/issue33495

   (29) https://bugs.python.org/issue33453

   (30) https://bugs.python.org/issue28556

   (31) https://bugs.python.org/issue20087

   (32) https://bugs.python.org/issue33422

   (33) https://bugs.python.org/issue28167

   (34) https://bugs.python.org/issue33197

   (35) https://bugs.python.org/issue33263

   (36) https://bugs.python.org/issue32861

   (37) https://bugs.python.org/issue32257

   (38) https://bugs.python.org/issue16865


File: python.info,  Node: 文档<27>,  Next: 测试<25>,  Prev: 库<33>,  Up: Python 3 7 0 beta 5

1.19.34.3 文档
..............

   - bpo-23859(1): Document that *note asyncio.wait(): 207. does not
     cancel its futures on timeout.

   - bpo-32436(2): Document PEP 567(3) changes to asyncio.

   - bpo-33604(4): 更新HMAC md5默认报告DeprecationWarning，并将在3.8移除
     。

   - bpo-33503(5): 修复错误的pypi链接

   - bpo-33421(6): 为‘‘typing.AsyncContextManager‘‘添加缺失的文档。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23859

   (2) https://bugs.python.org/issue32436

   (3) https://www.python.org/dev/peps/pep-0567

   (4) https://bugs.python.org/issue33604

   (5) https://bugs.python.org/issue33503

   (6) https://bugs.python.org/issue33421


File: python.info,  Node: 测试<25>,  Next: 构建<25>,  Prev: 文档<27>,  Up: Python 3 7 0 beta 5

1.19.34.4 测试
..............

   - bpo-33655(1): 忽略运行在BSD平台的ZFS上时test_posix_fallocate的失败
     。

   - bpo-32604(2): 删除_xxsubinterpreters模块（用于测试）和相关的帮助程
     序。该模块最初最初是在3.7b1中添加的。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33655

   (2) https://bugs.python.org/issue32604


File: python.info,  Node: 构建<25>,  Next: macOS<21>,  Prev: 测试<25>,  Up: Python 3 7 0 beta 5

1.19.34.5 构建
..............

   - bpo-33614(1): Ensures module definition files for the stable ABI on
     Windows are correctly regenerated.

   - bpo-33522(2): Enable CI builds on Visual Studio Team Services at
     ‘https://python.visualstudio.com/cpython’

   - bpo-33012(3): Add ‘-Wno-cast-function-type’ for gcc 8 for silencing
     warnings about function casts like casting to PyCFunction in method
     definition lists.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33614

   (2) https://bugs.python.org/issue33522

   (3) https://bugs.python.org/issue33012


File: python.info,  Node: macOS<21>,  Next: IDLE<26>,  Prev: 构建<25>,  Up: Python 3 7 0 beta 5

1.19.34.6 macOS
...............

   - bpo-13631(1): The .editrc file in user’s home directory is now
     processed correctly during the readline initialization through
     editline emulation on macOS.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13631


File: python.info,  Node: IDLE<26>,  Prev: macOS<21>,  Up: Python 3 7 0 beta 5

1.19.34.7 IDLE
..............

   - bpo-33628(1): IDLE: Cleanup codecontext.py and its test.

   - bpo-33564(2): IDLE’s code context now recognizes async as a block
     opener.

   - bpo-32831(3): Add docstrings and tests for codecontext.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33628

   (2) https://bugs.python.org/issue33564

   (3) https://bugs.python.org/issue32831


File: python.info,  Node: Python 3 7 0 beta 4,  Next: Python 3 7 0 beta 3,  Prev: Python 3 7 0 beta 5,  Up: Changelog（更動日誌）

1.19.35 Python 3.7.0 beta 4
---------------------------

`发布日期: 2018-05-02'

* Menu:

* 核心与内置函数: 核心与内置函数<31>.
* 库: 库<34>.
* 文档: 文档<28>.
* 测试: 测试<26>.
* 构建: 构建<26>.
* Windows: Windows<26>.
* macOS: macOS<22>.
* IDLE: IDLE<27>.
* 工具/示例: 工具/示例<12>.


File: python.info,  Node: 核心与内置函数<31>,  Next: 库<34>,  Up: Python 3 7 0 beta 4

1.19.35.1 核心与内置函数
........................

   - bpo-33363(1): 在异步函数外使用‘‘async with‘‘ 和 ‘async for’ 时抛出
     SyntaxError异常。

   - bpo-33128(2): 修复导致PathFinder在sys.meta_path上出现两次的错误。由
     Pablo Galindo Salgado提供补丁。

   - bpo-33312(3): Fixed clang ubsan (undefined behavior sanitizer)
     warnings in dictobject.c by adjusting how the internal struct
     _dictkeysobject shared keys structure is declared.

   - bpo-33231(4): 修复 ‘normalizestring()’ 中潜在的内存泄漏。

   - bpo-33205(5): Change dict growth function from
     ‘round_up_to_power_2(used*2+hashtable_size/2)’ to
     ‘round_up_to_power_2(used*3)’.  Previously, dict is shrinked only
     when ‘used == 0’.  Now dict has more chance to be shrinked.

   - bpo-29922(6): Improved error messages in ’async with’ when
     ‘__aenter__()’ or ‘__aexit__()’ return non-awaitable object.

   - bpo-33199(7): Fix ‘ma_version_tag’ in dict implementation is
     uninitialized when copying from key-sharing dict.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33363

   (2) https://bugs.python.org/issue33128

   (3) https://bugs.python.org/issue33312

   (4) https://bugs.python.org/issue33231

   (5) https://bugs.python.org/issue33205

   (6) https://bugs.python.org/issue29922

   (7) https://bugs.python.org/issue33199


File: python.info,  Node: 库<34>,  Next: 文档<28>,  Prev: 核心与内置函数<31>,  Up: Python 3 7 0 beta 4

1.19.35.2 库
............

   - bpo-33281(1): Fix ctypes.util.find_library regression on macOS.

   - bpo-33383(2): Fixed crash in the get() method of the *note
     dbm.ndbm: 34. database object when it is called with a single
     argument.

   - bpo-33329(3): Fix multiprocessing regression on newer glibcs

   - bpo-991266(4): Fix quoting of the ‘Comment’ attribute of *note
     http.cookies.SimpleCookie: 116e.

   - bpo-33131(5): Upgrade bundled version of pip to 10.0.1.

   - bpo-33308(6): Fixed a crash in the *note parser: c7. module when
     converting an ST object to a tree of tuples or lists with
     ‘line_info=False’ and ‘col_info=True’.

   - bpo-33266(7): lib2to3 now recognizes ‘rf'...'’ strings.

   - bpo-11594(8): Ensure line-endings are respected when using lib2to3.

   - bpo-33254(9): Have *note importlib.resources.contents(): 116f. and
     *note importlib.abc.ResourceReader.contents(): 1170. return an
     *note iterable: c7c. instead of an *note iterator: 1171.

   - bpo-33256(10): Fix display of ‘<module>’ call in the html produced
     by ‘cgitb.html()’.  Patch by Stéphane Blondon.

   - bpo-33185(11): Fixed regression when running pydoc with the *note
     -m: 443. switch.  (The regression was introduced in 3.7.0b3 by the
     resolution of bpo-33053(12)) This fix also changed pydoc to add
     ‘os.getcwd()’ to *note sys.path: 261. when necessary, rather than
     adding ‘"."’.

   - bpo-33169(13): Delete entries of ‘None’ in *note
     sys.path_importer_cache: 597. when
     ‘importlib.machinery.invalidate_caches()’ is called.

   - bpo-33217(14): Deprecate looking up non-Enum objects in Enum
     classes and Enum members (will raise *note TypeError: 1fe. in
     3.8+).

   - bpo-33203(15): ‘random.Random.choice()’ now raises ‘IndexError’ for
     empty sequences consistently even when called from subclasses
     without a ‘getrandbits()’ implementation.

   - bpo-33224(16): Update difflib.mdiff() for PEP 479(17).  Convert an
     uncaught StopIteration in a generator into a return-statement.

   - bpo-33209(18): End framing at the end of C implementation of *note
     pickle.Pickler.dump(): 1172.

   - bpo-20104(19): Improved error handling and fixed a reference leak
     in *note os.posix_spawn(): 381.

   - bpo-33175(20): In dataclasses, Field.__set_name__ now looks up the
     __set_name__ special method on the class, not the instance, of the
     default value.

   - bpo-33097(21): Raise RuntimeError when ‘executor.submit’ is called
     during interpreter shutdown.

   - bpo-31908(22): Fix output of cover files for ‘trace’ module
     command-line tool.  Previously emitted cover files only when
     ‘--missing’ option was used.  Patch by Michael Selik.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33281

   (2) https://bugs.python.org/issue33383

   (3) https://bugs.python.org/issue33329

   (4) https://bugs.python.org/issue991266

   (5) https://bugs.python.org/issue33131

   (6) https://bugs.python.org/issue33308

   (7) https://bugs.python.org/issue33266

   (8) https://bugs.python.org/issue11594

   (9) https://bugs.python.org/issue33254

   (10) https://bugs.python.org/issue33256

   (11) https://bugs.python.org/issue33185

   (12) https://bugs.python.org/issue33053

   (13) https://bugs.python.org/issue33169

   (14) https://bugs.python.org/issue33217

   (15) https://bugs.python.org/issue33203

   (16) https://bugs.python.org/issue33224

   (17) https://www.python.org/dev/peps/pep-0479

   (18) https://bugs.python.org/issue33209

   (19) https://bugs.python.org/issue20104

   (20) https://bugs.python.org/issue33175

   (21) https://bugs.python.org/issue33097

   (22) https://bugs.python.org/issue31908


File: python.info,  Node: 文档<28>,  Next: 测试<26>,  Prev: 库<34>,  Up: Python 3 7 0 beta 4

1.19.35.3 文档
..............

   - bpo-33378(1): Add Korean language switcher for
     ‘https://docs.python.org/3/’

   - bpo-33276(2): Clarify that the ‘__path__’ attribute on modules
     cannot be just any value.

   - bpo-33201(3): Modernize documentation for writing C extension
     types.

   - bpo-33195(4): Deprecate ‘Py_UNICODE’ usage in ‘c-api/arg’ document.
     ‘Py_UNICODE’ related APIs are deprecated since Python 3.3, but it
     is missed in the document.

   - bpo-8243(5): Add a note about curses.addch and curses.addstr
     exception behavior when writing outside a window, or pad.

   - bpo-32337(6): Update documentation related with ‘dict’ order.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33378

   (2) https://bugs.python.org/issue33276

   (3) https://bugs.python.org/issue33201

   (4) https://bugs.python.org/issue33195

   (5) https://bugs.python.org/issue8243

   (6) https://bugs.python.org/issue32337


File: python.info,  Node: 测试<26>,  Next: 构建<26>,  Prev: 文档<28>,  Up: Python 3 7 0 beta 4

1.19.35.4 测试
..............

   - bpo-33358(1): Fix
     ‘test_embed.test_pre_initialization_sys_options()’ when the
     interpreter is built with ‘--enable-shared’.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33358


File: python.info,  Node: 构建<26>,  Next: Windows<26>,  Prev: 测试<26>,  Up: Python 3 7 0 beta 4

1.19.35.5 构建
..............

   - bpo-33394(1): Enable the verbose build for extension modules, when
     GNU make is passed macros on the command line.

   - bpo-33393(2): Update config.guess and config.sub files.

   - bpo-33377(3): Add new triplets for mips r6 and riscv variants (used
     in extension suffixes).

   - bpo-32232(4): By default, modules configured in ‘Modules/Setup’ are
     no longer built with ‘-DPy_BUILD_CORE’.  Instead, modules that
     specifically need that preprocessor definition include it in their
     individual entries.

   - bpo-33182(5): The embedding tests can once again be built with
     clang 6.0

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33394

   (2) https://bugs.python.org/issue33393

   (3) https://bugs.python.org/issue33377

   (4) https://bugs.python.org/issue32232

   (5) https://bugs.python.org/issue33182


File: python.info,  Node: Windows<26>,  Next: macOS<22>,  Prev: 构建<26>,  Up: Python 3 7 0 beta 4

1.19.35.6 Windows
.................

   - bpo-33184(1): 在Windows安装程序中将OpenSSL更新为1.1.0h.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33184


File: python.info,  Node: macOS<22>,  Next: IDLE<27>,  Prev: Windows<26>,  Up: Python 3 7 0 beta 4

1.19.35.7 macOS
...............

   - bpo-33184(1): 在MacOS安装程序中将OpenSSL更新为1.1.0h。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33184


File: python.info,  Node: IDLE<27>,  Next: 工具/示例<12>,  Prev: macOS<22>,  Up: Python 3 7 0 beta 4

1.19.35.8 IDLE
..............

   - bpo-21474(1): 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.

   - bpo-33204(2): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21474

   (2) https://bugs.python.org/issue33204


File: python.info,  Node: 工具/示例<12>,  Prev: IDLE<27>,  Up: Python 3 7 0 beta 4

1.19.35.9 工具/示例
...................

   - bpo-33189(1): ‘pygettext.py’ now recognizes only literal strings as
     docstrings and translatable strings, and rejects bytes literals and
     f-string expressions.

   - bpo-31920(2): Fixed handling directories as arguments in the
     ‘pygettext’ script.  Based on patch by Oleg Krasnikov.

   - bpo-29673(3): Fix pystackv and pystack gdbinit macros.

   - bpo-31583(4): Fix 2to3 for using with –add-suffix option but
     without –output-dir option for relative path to files in current
     directory.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33189

   (2) https://bugs.python.org/issue31920

   (3) https://bugs.python.org/issue29673

   (4) https://bugs.python.org/issue31583


File: python.info,  Node: Python 3 7 0 beta 3,  Next: Python 3 7 0 beta 2,  Prev: Python 3 7 0 beta 4,  Up: Changelog（更動日誌）

1.19.36 Python 3.7.0 beta 3
---------------------------

`发布日期: 2018-03-29'

* Menu:

* 安全性: 安全性<19>.
* 核心与内置函数: 核心与内置函数<32>.
* 库: 库<35>.
* 文档: 文档<29>.
* 测试: 测试<27>.
* 构建: 构建<27>.
* Windows: Windows<27>.
* macOS: macOS<23>.
* IDLE: IDLE<28>.
* 工具/示例: 工具/示例<13>.
* C API: C API<22>.


File: python.info,  Node: 安全性<19>,  Next: 核心与内置函数<32>,  Up: Python 3 7 0 beta 3

1.19.36.1 安全性
................

   - bpo-33136(1): 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.

   - bpo-33001(2): Minimal fix to prevent buffer overrun in os.symlink
     on Windows

   - bpo-32981(3): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33136

   (2) https://bugs.python.org/issue33001

   (3) https://bugs.python.org/issue32981


File: python.info,  Node: 核心与内置函数<32>,  Next: 库<35>,  Prev: 安全性<19>,  Up: Python 3 7 0 beta 3

1.19.36.2 核心与内置函数
........................

   - bpo-33053(1): When using the -m switch, sys.path[0] is now
     explicitly expanded as the `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)

   - bpo-33018(2): Improve consistency of errors raised by
     ‘issubclass()’ when called with a non-class and an abstract base
     class as the first and second arguments, respectively.  Patch by
     Josh Bronson.

   - bpo-33041(3): Fixed jumping when the function contains an ‘async
     for’ loop.

   - bpo-33026(4): Fixed jumping out of "with" block by setting
     f_lineno.

   - bpo-33005(5): 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.

   - bpo-17288(6): Prevent jumps from ’return’ and ’exception’ trace
     events.

   - bpo-32836(7): Don’t use temporary variables in cases of
     list/dict/set comprehensions

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33053

   (2) https://bugs.python.org/issue33018

   (3) https://bugs.python.org/issue33041

   (4) https://bugs.python.org/issue33026

   (5) https://bugs.python.org/issue33005

   (6) https://bugs.python.org/issue17288

   (7) https://bugs.python.org/issue32836


File: python.info,  Node: 库<35>,  Next: 文档<29>,  Prev: 核心与内置函数<32>,  Up: Python 3 7 0 beta 3

1.19.36.3 库
............

   - bpo-33141(1): Have Field objects pass through __set_name__ to their
     default values, if they have their own __set_name__.

   - bpo-33096(2): 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.

   - bpo-32873(3): 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.

   - bpo-33134(4): 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.

   - bpo-33127(5): ssl模块现在使用LibreSSL 2.7.1编译。

   - bpo-32505(6): 如果数据类的成员变量的类型为Field，但没有类型注解，则
     引发TypeError。

   - bpo-33078(7): 修复在OSX平台因为依赖sem_getvalue而导致的失败。

   - bpo-33116(8): 将’Field’添加到dataclasses.__all__。

   - bpo-32896(9): Fix an error where subclassing a dataclass with a
     field that uses a default_factory would generate an incorrect
     class.

   - bpo-33100(10): 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.

   - bpo-32953(11): 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.

   - bpo-33061(12): 添加丢失的 ‘NoReturn’ 到typing.py的 ‘__all__’

   - bpo-33078(13): Fix the size handling in multiprocessing.Queue when
     a pickling error occurs.

   - bpo-33064(14): lib2to3 now properly supports trailing commas after
     ‘*args’ and ‘**kwargs’ in function signatures.

   - bpo-33056(15): FIX properly close leaking fds in
     concurrent.futures.ProcessPoolExecutor.

   - bpo-33021(16): Release the GIL during fstat() calls, avoiding hang
     of all threads when calling mmap.mmap(), os.urandom(), and
     random.seed().  Patch by Nir Soffer.

   - bpo-31804(17): Avoid failing in multiprocessing.Process if the
     standard streams are closed or None at exit.

   - bpo-33037(18): Skip sending/receiving data after SSL transport
     closing.

   - bpo-27683(19): Fix a regression in *note ipaddress: a2. that result
     of ‘hosts()’ is empty when the network is constructed by a tuple
     containing an integer mask and only 1 bit left for addresses.

   - bpo-32999(20): Fix C implementation of ‘ABC.__subclasscheck__(cls,
     subclass)’ crashed when ‘subclass’ is not a type object.

   - bpo-33009(21): Fix inspect.signature() for single-parameter
     partialmethods.

   - bpo-32969(22): Expose several missing constants in zlib and fix
     corresponding documentation.

   - bpo-32056(23): Improved exceptions raised for invalid number of
     channels and sample width when read an audio file in modules *note
     aifc: 4, *note wave: 130. and *note sunau: fa.

   - bpo-32844(24): Fix wrong redirection of a low descriptor (0 or 1)
     to stderr in subprocess if another low descriptor is closed.

   - bpo-32857(25): In *note tkinter: 10e, ‘after_cancel(None)’ now
     raises a *note ValueError: 16d. instead of canceling the first
     scheduled function.  Patch by Cheryl Sabella.

   - bpo-31639(26): http.server now exposes a ThreadedHTTPServer class
     and uses it when the module is run with ‘-m’ to cope with web
     browsers pre-opening sockets.

   - bpo-27645(27): *note sqlite3.Connection: 4de. now exposes a *note
     backup: 4df. method, if the underlying SQLite library is at version
     3.6.11 or higher.  Patch by Lele Gaifax.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33141

   (2) https://bugs.python.org/issue33096

   (3) https://bugs.python.org/issue32873

   (4) https://bugs.python.org/issue33134

   (5) https://bugs.python.org/issue33127

   (6) https://bugs.python.org/issue32505

   (7) https://bugs.python.org/issue33078

   (8) https://bugs.python.org/issue33116

   (9) https://bugs.python.org/issue32896

   (10) https://bugs.python.org/issue33100

   (11) https://bugs.python.org/issue32953

   (12) https://bugs.python.org/issue33061

   (13) https://bugs.python.org/issue33078

   (14) https://bugs.python.org/issue33064

   (15) https://bugs.python.org/issue33056

   (16) https://bugs.python.org/issue33021

   (17) https://bugs.python.org/issue31804

   (18) https://bugs.python.org/issue33037

   (19) https://bugs.python.org/issue27683

   (20) https://bugs.python.org/issue32999

   (21) https://bugs.python.org/issue33009

   (22) https://bugs.python.org/issue32969

   (23) https://bugs.python.org/issue32056

   (24) https://bugs.python.org/issue32844

   (25) https://bugs.python.org/issue32857

   (26) https://bugs.python.org/issue31639

   (27) https://bugs.python.org/issue27645


File: python.info,  Node: 文档<29>,  Next: 测试<27>,  Prev: 库<35>,  Up: Python 3 7 0 beta 3

1.19.36.4 文档
..............

   - bpo-33126(1): Document PyBuffer_ToContiguous().

   - bpo-27212(2): Modify documentation for the ‘islice()’ recipe to
     consume initial values up to the start index.

   - bpo-28247(3): Update *note zipapp: 14a. documentation to describe
     how to make standalone applications.

   - bpo-18802(4): Documentation changes for ipaddress.  Patch by Jon
     Foster and Berker Peksag.

   - bpo-27428(5): Update documentation to clarify that
     ‘WindowsRegistryFinder’ implements ‘MetaPathFinder’.  (Patch by
     Himanshu Lakhara)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33126

   (2) https://bugs.python.org/issue27212

   (3) https://bugs.python.org/issue28247

   (4) https://bugs.python.org/issue18802

   (5) https://bugs.python.org/issue27428


File: python.info,  Node: 测试<27>,  Next: 构建<27>,  Prev: 文档<29>,  Up: Python 3 7 0 beta 3

1.19.36.5 测试
..............

   - bpo-32872(1): Avoid regrtest compatibility issue with namespace
     packages.

   - bpo-32517(2): Fix failing ‘test_asyncio’ on macOS 10.12.2+ due to
     transport of ‘KqueueSelector’ loop was not being closed.

   - bpo-19417(3): Add test_bdb.py.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32872

   (2) https://bugs.python.org/issue32517

   (3) https://bugs.python.org/issue19417


File: python.info,  Node: 构建<27>,  Next: Windows<27>,  Prev: 测试<27>,  Up: Python 3 7 0 beta 3

1.19.36.6 构建
..............

   - bpo-33163(1): Upgrade pip to 9.0.3 and setuptools to v39.0.1.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33163


File: python.info,  Node: Windows<27>,  Next: macOS<23>,  Prev: 构建<27>,  Up: Python 3 7 0 beta 3

1.19.36.7 Windows
.................

   - bpo-33016(1): Fix potential use of uninitialized memory in
     nt._getfinalpathname

   - bpo-32903(2): Fix a memory leak in os.chdir() on Windows if the
     current directory is set to a UNC path.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33016

   (2) https://bugs.python.org/issue32903


File: python.info,  Node: macOS<23>,  Next: IDLE<28>,  Prev: Windows<27>,  Up: Python 3 7 0 beta 3

1.19.36.8 macOS
...............

   - bpo-32726(1): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32726


File: python.info,  Node: IDLE<28>,  Next: 工具/示例<13>,  Prev: macOS<23>,  Up: Python 3 7 0 beta 3

1.19.36.9 IDLE
..............

   - bpo-32984(1): Set ‘__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,
     ‘-s’ runs a file named in environmental variable ‘IDLESTARTUP’ or
     *note PYTHONSTARTUP: 9cb.; ‘-r file’ runs ‘file’.  Python sets
     ‘__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 ‘-n’ option.

   - bpo-32940(2): Simplify and rename StringTranslatePseudoMapping in
     pyparse.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32984

   (2) https://bugs.python.org/issue32940


File: python.info,  Node: 工具/示例<13>,  Next: C API<22>,  Prev: IDLE<28>,  Up: Python 3 7 0 beta 3

1.19.36.10 工具/示例
....................

   - bpo-32885(1): Add an ‘-n’ flag for ‘Tools/scripts/pathfix.py’ to
     disable automatic backup creation (files with ‘~’ suffix).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32885


File: python.info,  Node: C API<22>,  Prev: 工具/示例<13>,  Up: Python 3 7 0 beta 3

1.19.36.11 C API
................

   - bpo-33042(1): Embedding applications may once again call
     PySys_ResetWarnOptions, PySys_AddWarnOption, and PySys_AddXOption
     prior to calling Py_Initialize.

   - bpo-32374(2): Document that m_traverse for multi-phase initialized
     modules can be called with m_state=NULL, and add a sanity check

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33042

   (2) https://bugs.python.org/issue32374


File: python.info,  Node: Python 3 7 0 beta 2,  Next: Python 3 7 0 beta 1,  Prev: Python 3 7 0 beta 3,  Up: Changelog（更動日誌）

1.19.37 Python 3.7.0 beta 2
---------------------------

`发布日期: 2018-02-27'

* Menu:

* 安全性: 安全性<20>.
* 核心与内置函数: 核心与内置函数<33>.
* 库: 库<36>.
* 文档: 文档<30>.
* 测试: 测试<28>.
* 构建: 构建<28>.
* Windows: Windows<28>.
* macOS: macOS<24>.
* IDLE: IDLE<29>.
* 工具/示例: 工具/示例<14>.


File: python.info,  Node: 安全性<20>,  Next: 核心与内置函数<33>,  Up: Python 3 7 0 beta 2

1.19.37.1 安全性
................

   - bpo-28414(1): The ssl module now allows users to perform their own
     IDN en/decoding when using SNI.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28414


File: python.info,  Node: 核心与内置函数<33>,  Next: 库<36>,  Prev: 安全性<20>,  Up: Python 3 7 0 beta 2

1.19.37.2 核心与内置函数
........................

   - bpo-32889(1): Update Valgrind suppression list to account for the
     rename of ‘Py_ADDRESS_IN_RANG’ to ‘address_in_range’.

   - bpo-31356(2): Remove the new API added in bpo-31356(3)
     (gc.ensure_disabled() context manager).

   - bpo-32305(4): For namespace packages, ensure that both ‘__file__’
     and ‘__spec__.origin’ are set to None.

   - bpo-32303(5): Make sure ‘__spec__.loader’ matches ‘__loader__’ for
     namespace packages.

   - bpo-32711(6): Fix the warning messages for Python/ast_unparse.c.
     Patch by Stéphane Wirtel

   - bpo-32583(7): Fix possible crashing in builtin Unicode decoders
     caused by write out-of-bound errors when using customized decode
     error handlers.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32889

   (2) https://bugs.python.org/issue31356

   (3) https://bugs.python.org/issue31356

   (4) https://bugs.python.org/issue32305

   (5) https://bugs.python.org/issue32303

   (6) https://bugs.python.org/issue32711

   (7) https://bugs.python.org/issue32583


File: python.info,  Node: 库<36>,  Next: 文档<30>,  Prev: 核心与内置函数<33>,  Up: Python 3 7 0 beta 2

1.19.37.3 库
............

   - bpo-32960(1): 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.

   - bpo-32713(2): Fixed tarfile.itn handling of out-of-bounds float
     values.  Patch by Joffrey Fuhrer.

   - bpo-32951(3): 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.

   - bpo-32929(4): 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.

   - bpo-32947(5): Add OP_ENABLE_MIDDLEBOX_COMPAT and test workaround
     for TLSv1.3 for future compatibility with OpenSSL 1.1.1.

   - bpo-30622(6): The ssl module now detects missing NPN support in
     LibreSSL.

   - bpo-32922(7): dbm.open() now encodes filename with the filesystem
     encoding rather than default encoding.

   - bpo-32859(8): In ‘os.dup2’, don’t check every call whether the
     ‘dup3’ syscall exists or not.

   - bpo-32556(9): nt._getfinalpathname, nt._getvolumepathname and
     nt._getdiskusage now correctly convert from bytes.

   - bpo-25988(10): Emit a *note DeprecationWarning: 15a. when using or
     importing an ABC directly from *note collections: 1d. rather than
     from *note collections.abc: 1e.

   - bpo-21060(11): 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".

   - bpo-32852(12): Make sure sys.argv remains as a list when running
     trace.

   - bpo-31333(13): ‘_abc’ module is added.  It is a speedup module with
     C implementations for various functions and methods in ‘abc’.
     Creating an ABC subclass and calling ‘isinstance’ or ‘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 ‘_abc_registry’, ‘_abc_cache’,
     and ‘_abc_negative_cache’.  There are three debugging helper
     methods that can be used instead ‘_dump_registry’,
     ‘_abc_registry_clear’, and ‘_abc_caches_clear’.

   - bpo-32841(14): Fixed *note asyncio.Condition: 3b0. issue which
     silently ignored cancellation after notifying and cancelling a
     conditional lock.  Patch by Bar Harel.

   - bpo-32819(15): 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.

   - bpo-32394(16): socket: Remove
     TCP_FASTOPEN,TCP_KEEPCNT,TCP_KEEPIDLE,TCP_KEEPINTVL flags on older
     version Windows during run-time.

   - bpo-31787(17): Fixed refleaks of ‘__init__()’ methods in various
     modules.  (Contributed by Oren Milman)

   - bpo-30157(18): Fixed guessing quote and delimiter in
     csv.Sniffer.sniff() when only the last field is quoted.  Patch by
     Jake Davis.

   - bpo-32792(19): collections.ChainMap() preserves the order of the
     underlying mappings.

   - bpo-32775(20): *note fnmatch.translate(): 1173. 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.

   - bpo-32622(21): Implement native fast sendfile for Windows proactor
     event loop.

   - bpo-32777(22): 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.

   - bpo-32647(23): The ctypes module used to depend on indirect linking
     for dlopen.  The shared extension is now explicitly linked against
     libdl on platforms with dl.

   - bpo-32741(24): Implement ‘asyncio.TimerHandle.when()’ method.

   - bpo-32691(25): Use mod_spec.parent when running modules with pdb

   - bpo-32734(26): Fixed ‘asyncio.Lock()’ safety issue which allowed
     acquiring and locking the same lock multiple times, without it
     being free.  Patch by Bar Harel.

   - bpo-32727(27): Do not include name field in SMTP envelope from
     address.  Patch by Stéphane Wirtel

   - bpo-31453(28): Add TLSVersion constants and
     SSLContext.maximum_version / minimum_version attributes.  The new
     API wraps OpenSSL 1.1
     ‘https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_set_min_proto_version.html’
     feature.

   - bpo-24334(29): 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.

   - bpo-31848(30): Fix the error handling in Aifc_read.initfp() when
     the SSND chunk is not found.  Patch by Zackery Spytz.

   - bpo-32585(31): Add Ttk spinbox widget to *note tkinter.ttk: 118.
     Patch by Alan D Moore.

   - bpo-32221(32): Various functions returning tuple containing IPv6
     addresses now omit ‘%scope’ part since the same information is
     already encoded in `scopeid' tuple item.  Especially this speeds up
     ‘socket.recvfrom()’ when it receives multicast packet since useless
     resolving of network interface name is omitted.

   - bpo-30693(33): The TarFile class now recurses directories in a
     reproducible way.

   - bpo-30693(34): The ZipFile class now recurses directories in a
     reproducible way.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32960

   (2) https://bugs.python.org/issue32713

   (3) https://bugs.python.org/issue32951

   (4) https://bugs.python.org/issue32929

   (5) https://bugs.python.org/issue32947

   (6) https://bugs.python.org/issue30622

   (7) https://bugs.python.org/issue32922

   (8) https://bugs.python.org/issue32859

   (9) https://bugs.python.org/issue32556

   (10) https://bugs.python.org/issue25988

   (11) https://bugs.python.org/issue21060

   (12) https://bugs.python.org/issue32852

   (13) https://bugs.python.org/issue31333

   (14) https://bugs.python.org/issue32841

   (15) https://bugs.python.org/issue32819

   (16) https://bugs.python.org/issue32394

   (17) https://bugs.python.org/issue31787

   (18) https://bugs.python.org/issue30157

   (19) https://bugs.python.org/issue32792

   (20) https://bugs.python.org/issue32775

   (21) https://bugs.python.org/issue32622

   (22) https://bugs.python.org/issue32777

   (23) https://bugs.python.org/issue32647

   (24) https://bugs.python.org/issue32741

   (25) https://bugs.python.org/issue32691

   (26) https://bugs.python.org/issue32734

   (27) https://bugs.python.org/issue32727

   (28) https://bugs.python.org/issue31453

   (29) https://bugs.python.org/issue24334

   (30) https://bugs.python.org/issue31848

   (31) https://bugs.python.org/issue32585

   (32) https://bugs.python.org/issue32221

   (33) https://bugs.python.org/issue30693

   (34) https://bugs.python.org/issue30693


File: python.info,  Node: 文档<30>,  Next: 测试<28>,  Prev: 库<36>,  Up: Python 3 7 0 beta 2

1.19.37.4 文档
..............

   - bpo-28124(1): 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.

   - bpo-17232(2): Clarify docs for -O and -OO. Patch by Terry Reedy.

   - bpo-32436(3): Add documentation for the contextvars module (PEP
     567).

   - bpo-32800(4): Update link to w3c doc for xml default namespaces.

   - bpo-11015(5): Update *note test.support: 106. documentation.

   - bpo-8722(6): Document *note __getattr__(): 42a. behavior when
     property ‘get()’ method raises *note AttributeError: 4a1.

   - bpo-32614(7): Modify RE examples in documentation to use raw
     strings to prevent *note DeprecationWarning: 15a. and add text to
     REGEX HOWTO to highlight the deprecation.

   - bpo-31972(8): Improve docstrings for *note pathlib.PurePath: 235.
     subclasses.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28124

   (2) https://bugs.python.org/issue17232

   (3) https://bugs.python.org/issue32436

   (4) https://bugs.python.org/issue32800

   (5) https://bugs.python.org/issue11015

   (6) https://bugs.python.org/issue8722

   (7) https://bugs.python.org/issue32614

   (8) https://bugs.python.org/issue31972


File: python.info,  Node: 测试<28>,  Next: 构建<28>,  Prev: 文档<30>,  Up: Python 3 7 0 beta 2

1.19.37.5 测试
..............

   - bpo-31809(1): Add tests to verify connection with secp ECDH curves.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31809


File: python.info,  Node: 构建<28>,  Next: Windows<28>,  Prev: 测试<28>,  Up: Python 3 7 0 beta 2

1.19.37.6 构建
..............

   - bpo-32898(1): Fix the python debug build when using COUNT_ALLOCS.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32898


File: python.info,  Node: Windows<28>,  Next: macOS<24>,  Prev: 构建<28>,  Up: Python 3 7 0 beta 2

1.19.37.7 Windows
.................

   - bpo-32901(1): Update Tcl and Tk versions to 8.6.8

   - bpo-31966(2): Fixed WindowsConsoleIO.write() for writing empty
     data.

   - bpo-32409(3): Ensures activate.bat can handle Unicode contents.

   - bpo-32457(4): Improves handling of denormalized executable path
     when launching Python.

   - bpo-32370(5): Use the correct encoding for ipconfig output in the
     uuid module.  Patch by Segev Finer.

   - bpo-29248(6): Fix *note os.readlink(): 1d1. on Windows, which was
     mistakenly treating the ‘PrintNameOffset’ field of the reparse data
     buffer as a number of characters instead of bytes.  Patch by Craig
     Holmquist and SSE4.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32901

   (2) https://bugs.python.org/issue31966

   (3) https://bugs.python.org/issue32409

   (4) https://bugs.python.org/issue32457

   (5) https://bugs.python.org/issue32370

   (6) https://bugs.python.org/issue29248


File: python.info,  Node: macOS<24>,  Next: IDLE<29>,  Prev: Windows<28>,  Up: Python 3 7 0 beta 2

1.19.37.8 macOS
...............

   - bpo-32901(1): Update macOS 10.9+ installer to Tcl/Tk 8.6.8.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32901


File: python.info,  Node: IDLE<29>,  Next: 工具/示例<14>,  Prev: macOS<24>,  Up: Python 3 7 0 beta 2

1.19.37.9 IDLE
..............

   - bpo-32916(1): Change ‘str’ to ‘code’ in pyparse.

   - bpo-32905(2): Remove unused code in pyparse module.

   - bpo-32874(3): Add tests for pyparse.

   - bpo-32837(4): Using the system and place-dependent default encoding
     for open() is a bad idea for IDLE’s system and location-independent
     files.

   - bpo-32826(5): 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.

   - bpo-32765(6): Update configdialog General tab docstring to add new
     widgets to the widget list.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32916

   (2) https://bugs.python.org/issue32905

   (3) https://bugs.python.org/issue32874

   (4) https://bugs.python.org/issue32837

   (5) https://bugs.python.org/issue32826

   (6) https://bugs.python.org/issue32765


File: python.info,  Node: 工具/示例<14>,  Prev: IDLE<29>,  Up: Python 3 7 0 beta 2

1.19.37.10 工具/示例
....................

   - bpo-32222(1): Fix pygettext not extracting docstrings for functions
     with type annotated arguments.  Patch by Toby Harradine.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32222


File: python.info,  Node: Python 3 7 0 beta 1,  Next: Python 3 7 0 alpha 4,  Prev: Python 3 7 0 beta 2,  Up: Changelog（更動日誌）

1.19.38 Python 3.7.0 beta 1
---------------------------

`发布日期: 2018-01-30'

* Menu:

* 核心与内置函数: 核心与内置函数<34>.
* 库: 库<37>.
* 文档: 文档<31>.
* 测试: 测试<29>.
* 构建: 构建<29>.
* Windows: Windows<29>.
* macOS: macOS<25>.
* C API: C API<23>.


File: python.info,  Node: 核心与内置函数<34>,  Next: 库<37>,  Up: Python 3 7 0 beta 1

1.19.38.1 核心与内置函数
........................

   - bpo-32703(1): Fix coroutine’s ResourceWarning when there’s an
     active error set when it’s being finalized.

   - bpo-32650(2): Pdb and other debuggers dependent on bdb.py will
     correctly step over (next command) native coroutines.  Patch by
     Pablo Galindo.

   - bpo-28685(3): Optimize list.sort() and sorted() by using type
     specialized comparisons when possible.

   - bpo-32685(4): 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.

   - bpo-32697(5): 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.

   - bpo-32690(6): The locals() dictionary now displays in the lexical
     order that variables were defined.  Previously, the order was
     reversed.

   - bpo-32677(7): Add ‘.isascii()’ method to ‘str’, ‘bytes’ and
     ‘bytearray’.  It can be used to test that string contains only
     ASCII characters.

   - bpo-32670(8): Enforce PEP 479(9) 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.

   - bpo-32591(10): 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.

   - bpo-31368(11): Expose preadv and pwritev system calls in the os
     module.  Patch by Pablo Galindo

   - bpo-32544(12): ‘hasattr(obj, name)’ and ‘getattr(obj, name,
     default)’ are about 4 times faster than before when ‘name’ is not
     found and ‘obj’ doesn’t override ‘__getattr__’ or
     ‘__getattribute__’.

   - bpo-26163(13): Improved frozenset() hash to create more distinct
     hash values when faced with datasets containing many similar
     values.

   - bpo-32550(14): Remove the STORE_ANNOTATION bytecode.

   - bpo-20104(15): Expose posix_spawn as a low level API in the os
     module.  (removed before 3.7.0rc1)

   - bpo-24340(16): Fixed estimation of the code stack size.

   - bpo-32436(17): Implement PEP 567(18) Context Variables.

   - bpo-18533(19): ‘repr()’ on a dict containing its own ‘values()’ or
     ‘items()’ no longer raises ‘RecursionError’; OrderedDict similarly.
     Instead, use ‘...’, as for other recursive structures.  Patch by
     Ben North.

   - bpo-20891(20): 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.

   - bpo-32028(21): Leading whitespace is now correctly ignored when
     generating suggestions for converting Py2 print statements to Py3
     builtin print function calls.  Patch by Sanyam Khurana.

   - bpo-31179(22): Make dict.copy() up to 5.5 times faster.

   - bpo-31113(23): Get rid of recursion in the compiler for normal
     control flow.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32703

   (2) https://bugs.python.org/issue32650

   (3) https://bugs.python.org/issue28685

   (4) https://bugs.python.org/issue32685

   (5) https://bugs.python.org/issue32697

   (6) https://bugs.python.org/issue32690

   (7) https://bugs.python.org/issue32677

   (8) https://bugs.python.org/issue32670

   (9) https://www.python.org/dev/peps/pep-0479

   (10) https://bugs.python.org/issue32591

   (11) https://bugs.python.org/issue31368

   (12) https://bugs.python.org/issue32544

   (13) https://bugs.python.org/issue26163

   (14) https://bugs.python.org/issue32550

   (15) https://bugs.python.org/issue20104

   (16) https://bugs.python.org/issue24340

   (17) https://bugs.python.org/issue32436

   (18) https://www.python.org/dev/peps/pep-0567

   (19) https://bugs.python.org/issue18533

   (20) https://bugs.python.org/issue20891

   (21) https://bugs.python.org/issue32028

   (22) https://bugs.python.org/issue31179

   (23) https://bugs.python.org/issue31113


File: python.info,  Node: 库<37>,  Next: 文档<31>,  Prev: 核心与内置函数<34>,  Up: Python 3 7 0 beta 1

1.19.38.2 库
............

   - bpo-25988(1): Deprecate exposing the contents of collections.abc in
     the regular collections module.

   - bpo-31429(2): 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.

   - bpo-30306(3): 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.

   - bpo-21417(4): Added support for setting the compression level for
     zipfile.ZipFile.

   - bpo-32251(5): Implement asyncio.BufferedProtocol (provisional API).

   - bpo-32513(6): In dataclasses, allow easier overriding of dunder
     methods without specifying decorator parameters.

   - bpo-32660(7): *note termios: 104. makes available ‘FIONREAD’,
     ‘FIONCLEX’, ‘FIOCLEX’, ‘FIOASYNC’ and ‘FIONBIO’ also under
     Solaris/derivatives.

   - bpo-27931(8): Fix email address header parsing error when the
     username is an empty quoted string.  Patch by Xiang Zhang.

   - bpo-32659(9): Under Solaris and derivatives, *note os.stat_result:
     11bf. provides a st_fstype attribute.

   - bpo-32662(10): 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().

   - bpo-32391(11): Implement *note asyncio.StreamWriter.wait_closed():
     45e. and *note asyncio.StreamWriter.is_closing(): 45f. methods

   - bpo-32643(12): Make Task._step, Task._wakeup and
     Future._schedule_callbacks methods private.

   - bpo-32630(13): Refactor decimal module to use contextvars to store
     decimal context.

   - bpo-32622(14): Add ‘asyncio.AbstractEventLoop.sendfile()’ method.

   - bpo-32304(15): 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.

   - bpo-32502(16): uuid.uuid1 no longer raises an exception if a 64-bit
     hardware address is encountered.

   - bpo-32596(17): ‘concurrent.futures’ imports ‘ThreadPoolExecutor’
     and ‘ProcessPoolExecutor’ lazily (using PEP 562(18)).  It makes
     ‘import asyncio’ about 15% faster because asyncio uses only
     ‘ThreadPoolExecutor’ by default.

   - bpo-31801(19): Add ‘_ignore_’ to ‘Enum’ so temporary variables can
     be used during class construction without being turned into
     members.

   - bpo-32576(20): Use queue.SimpleQueue() in places where it can be
     invoked from a weakref callback.

   - bpo-32574(21): 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.

   - bpo-32521(22): The nis module is now compatible with new libnsl and
     headers location.

   - bpo-32467(23): collections.abc.ValuesView now inherits from
     collections.abc.Collection.

   - bpo-32473(24): Improve ABCMeta._dump_registry() output readability

   - bpo-32102(25): New argument ‘capture_output’ for subprocess.run

   - bpo-32521(26): glibc has removed Sun RPC. Use replacement libtirpc
     headers and library in nis module.

   - bpo-32493(27): UUID module fixes build for FreeBSD/OpenBSD

   - bpo-32503(28): Pickling with protocol 4 no longer creates too small
     frames.

   - bpo-29237(29): Create enum for pstats sorting options

   - bpo-32454(30): Add close(fd) function to the socket module.

   - bpo-25942(31): 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.

   - bpo-32433(32): The hmac module now has hmac.digest(), which
     provides an optimized HMAC digest.

   - bpo-28134(33): Sockets now auto-detect family, type and protocol
     from file descriptor by default.

   - bpo-32404(34): Fix bug where *note
     datetime.datetime.fromtimestamp(): 11c0. did not call __new__ in
     *note datetime.datetime: 19f. subclasses.

   - bpo-32403(35): Improved speed of *note datetime.date: 19d. and
     *note datetime.datetime: 19f. alternate constructors.

   - bpo-32228(36): Ensure that ‘truncate()’ preserves the file position
     (as reported by ‘tell()’) after writes longer than the buffer size.

   - bpo-32410(37): Implement ‘loop.sock_sendfile’ for asyncio event
     loop.

   - bpo-22908(38): Added seek and tell to the ZipExtFile class.  This
     only works if the file object used to open the zipfile is seekable.

   - bpo-32373(39): Add socket.getblocking() method.

   - bpo-32248(40): Add *note importlib.resources: 9e. and *note
     importlib.abc.ResourceReader: 44e. as the unified API for reading
     resources contained within packages.  Loaders wishing to support
     resource reading must implement the ‘get_resource_reader()’ method.
     File-based and zipimport-based loaders both implement these APIs.
     *note importlib.abc.ResourceLoader: 567. is deprecated in favor of
     these new APIs.

   - bpo-32320(41): collections.namedtuple() now supports default
     values.

   - bpo-29302(42): Add contextlib.AsyncExitStack.  Patch by Alexander
     Mohr and Ilya Kulakov.

   - bpo-31961(43): `Removed in Python 3.7.0b2.'  The `args' argument of
     subprocess.Popen can now be a *note path-like object: 472.  If
     `args' is given as a sequence, it’s first element can now be a
     *note path-like object: 472. as well.

   - bpo-31900(44): The *note locale.localeconv(): 584. function now
     sets temporarily the ‘LC_CTYPE’ locale to the ‘LC_NUMERIC’ locale
     to decode ‘decimal_point’ and ‘thousands_sep’ byte strings if they
     are non-ASCII or longer than 1 byte, and the ‘LC_NUMERIC’ locale is
     different than the ‘LC_CTYPE’ locale.  This temporary change
     affects other threads.  Same change for the *note str.format():
     5d4. method when formatting a number (*note int: 204, *note float:
     1fd, *note float: 1fd. and subclasses) with the ‘n’ type (ex:
     ‘'{:n}'.format(1234)’).

   - bpo-31853(45): Use super().method instead of socket.method in
     SSLSocket.  They were there most likely for legacy reasons.

   - bpo-31399(46): 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.

   - bpo-14976(47): Add a queue.SimpleQueue class, an unbounded FIFO
     queue with a reentrant C implementation of put().

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25988

   (2) https://bugs.python.org/issue31429

   (3) https://bugs.python.org/issue30306

   (4) https://bugs.python.org/issue21417

   (5) https://bugs.python.org/issue32251

   (6) https://bugs.python.org/issue32513

   (7) https://bugs.python.org/issue32660

   (8) https://bugs.python.org/issue27931

   (9) https://bugs.python.org/issue32659

   (10) https://bugs.python.org/issue32662

   (11) https://bugs.python.org/issue32391

   (12) https://bugs.python.org/issue32643

   (13) https://bugs.python.org/issue32630

   (14) https://bugs.python.org/issue32622

   (15) https://bugs.python.org/issue32304

   (16) https://bugs.python.org/issue32502

   (17) https://bugs.python.org/issue32596

   (18) https://www.python.org/dev/peps/pep-0562

   (19) https://bugs.python.org/issue31801

   (20) https://bugs.python.org/issue32576

   (21) https://bugs.python.org/issue32574

   (22) https://bugs.python.org/issue32521

   (23) https://bugs.python.org/issue32467

   (24) https://bugs.python.org/issue32473

   (25) https://bugs.python.org/issue32102

   (26) https://bugs.python.org/issue32521

   (27) https://bugs.python.org/issue32493

   (28) https://bugs.python.org/issue32503

   (29) https://bugs.python.org/issue29237

   (30) https://bugs.python.org/issue32454

   (31) https://bugs.python.org/issue25942

   (32) https://bugs.python.org/issue32433

   (33) https://bugs.python.org/issue28134

   (34) https://bugs.python.org/issue32404

   (35) https://bugs.python.org/issue32403

   (36) https://bugs.python.org/issue32228

   (37) https://bugs.python.org/issue32410

   (38) https://bugs.python.org/issue22908

   (39) https://bugs.python.org/issue32373

   (40) https://bugs.python.org/issue32248

   (41) https://bugs.python.org/issue32320

   (42) https://bugs.python.org/issue29302

   (43) https://bugs.python.org/issue31961

   (44) https://bugs.python.org/issue31900

   (45) https://bugs.python.org/issue31853

   (46) https://bugs.python.org/issue31399

   (47) https://bugs.python.org/issue14976


File: python.info,  Node: 文档<31>,  Next: 测试<29>,  Prev: 库<37>,  Up: Python 3 7 0 beta 1

1.19.38.3 文档
..............

   - bpo-32724(1): Add references to some commands in the documentation
     of Pdb.  Patch by Stéphane Wirtel

   - bpo-32649(2): Complete the C API documentation, profiling and
     tracing part with the newly added per-opcode events.

   - bpo-17799(3): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32724

   (2) https://bugs.python.org/issue32649

   (3) https://bugs.python.org/issue17799


File: python.info,  Node: 测试<29>,  Next: 构建<29>,  Prev: 文档<31>,  Up: Python 3 7 0 beta 1

1.19.38.4 测试
..............

   - bpo-32721(1): Fix test_hashlib to not fail if the _md5 module is
     not built.

   - bpo-28414(2): Add test cases for IDNA 2003 and 2008 host names.
     IDNA 2003 internationalized host names are working since
     bpo-31399(3) has landed.  IDNA 2008 are still broken.

   - bpo-32604(4): 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.

   - bpo-32602(5): Add test certs and test for ECDSA cert and EC/RSA
     dual mode.

   - bpo-32549(6): On Travis CI, Python now Compiles and uses a local
     copy of OpenSSL 1.1.0g for testing.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32721

   (2) https://bugs.python.org/issue28414

   (3) https://bugs.python.org/issue31399

   (4) https://bugs.python.org/issue32604

   (5) https://bugs.python.org/issue32602

   (6) https://bugs.python.org/issue32549


File: python.info,  Node: 构建<29>,  Next: Windows<29>,  Prev: 测试<29>,  Up: Python 3 7 0 beta 1

1.19.38.5 构建
..............

   - bpo-32635(1): Fix segfault of the crypt module when libxcrypt is
     provided instead of libcrypt at the system.

   - bpo-32598(2): 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.

   - bpo-32593(3): 放弃对 FreeBSD 9 及更早版本的支持。

   - bpo-29708(4): If the ‘SOURCE_DATE_EPOCH’ environment variable is
     set, *note py_compile: d7. will always create hash-based ‘.pyc’
     files.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32635

   (2) https://bugs.python.org/issue32598

   (3) https://bugs.python.org/issue32593

   (4) https://bugs.python.org/issue29708


File: python.info,  Node: Windows<29>,  Next: macOS<25>,  Prev: 构建<29>,  Up: Python 3 7 0 beta 1

1.19.38.6 Windows
.................

   - bpo-32588(1): Create standalone _distutils_findvs module and add
     missing _queue module to installer.

   - bpo-29911(2): Ensure separate Modify and Uninstall buttons are
     displayed.

   - bpo-32507(3): Use app-local UCRT install rather than the proper
     update for old versions of Windows.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32588

   (2) https://bugs.python.org/issue29911

   (3) https://bugs.python.org/issue32507


File: python.info,  Node: macOS<25>,  Next: C API<23>,  Prev: Windows<29>,  Up: Python 3 7 0 beta 1

1.19.38.7 macOS
...............

   - bpo-32726(1): 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.

   - bpo-28440(2): No longer add /Library/Python/3.x/site-packages to
     sys.path for macOS framework builds to avoid future conflicts.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32726

   (2) https://bugs.python.org/issue28440


File: python.info,  Node: C API<23>,  Prev: macOS<25>,  Up: Python 3 7 0 beta 1

1.19.38.8 C API
...............

   - bpo-32681(1): Fix uninitialized variable ’res’ in the C
     implementation of os.dup2.  Patch by Stéphane Wirtel

   - bpo-10381(2): Add C API access to the ‘datetime.timezone’
     constructor and ‘datetime.timzone.UTC’ singleton.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32681

   (2) https://bugs.python.org/issue10381


File: python.info,  Node: Python 3 7 0 alpha 4,  Next: Python 3 7 0 alpha 3,  Prev: Python 3 7 0 beta 1,  Up: Changelog（更動日誌）

1.19.39 Python 3.7.0 alpha 4
----------------------------

`发布日期: 2018-01-08'

* Menu:

* 核心与内置函数: 核心与内置函数<35>.
* 库: 库<38>.
* 文档: 文档<32>.
* 测试: 测试<30>.
* Windows: Windows<30>.
* 工具/示例: 工具/示例<15>.
* C API: C API<24>.


File: python.info,  Node: 核心与内置函数<35>,  Next: 库<38>,  Up: Python 3 7 0 alpha 4

1.19.39.1 核心与内置函数
........................

   - bpo-31975(1): 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.

   - bpo-32226(2): ‘__class_getitem__’ is now an automatic class method.

   - bpo-32399(3): Add AIX uuid library support for RFC4122 using
     uuid_create() in libc.a

   - bpo-32390(4): Fix the compilation failure on AIX after the f_fsid
     field has been added to the object returned by os.statvfs()
     (bpo-32143(5)).  Original patch by Michael Felt.

   - bpo-32379(6): Make MRO computation faster when a class inherits
     from a single base.

   - bpo-32259(7): The error message of a TypeError raised when unpack
     non-iterable is now more specific.

   - bpo-27169(8): The ‘__debug__’ constant is now optimized out at
     compile time.  This fixes also bpo-22091(9).

   - bpo-32329(10): The *note -R: 11c9. option now turns on hash
     randomization when the *note PYTHONHASHSEED: aa4. environment
     variable is set to ‘0’.  Previously, the option was ignored.
     Moreover, ‘sys.flags.hash_randomization’ is now properly set to 0
     when hash randomization is turned off by ‘PYTHONHASHSEED=0’.

   - bpo-30416(11): 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.

   - bpo-32282(12): Fix an unnecessary ifdef in the include of
     VersionHelpers.h in socketmodule on Windows.

   - bpo-30579(13): Implement TracebackType.__new__ to allow
     Python-level creation of traceback objects, and make
     TracebackType.tb_next mutable.

   - bpo-32260(14): Don’t byte swap the input keys to the SipHash
     algorithm on big-endian platforms.  This should ensure siphash
     gives consistent results across platforms.

   - bpo-31506(15): Improve the error message logic for object.__new__
     and object.__init__.  Patch by Sanyam Khurana.

   - bpo-20361(16): ‘-b’ and ‘-bb’ now inject ‘'default::BytesWarning'’
     and ‘error::BytesWarning’ entries into ‘sys.warnoptions’, ensuring
     that they take precedence over any other warning filters configured
     via the ‘-W’ option or the ‘PYTHONWARNINGS’ environment variable.

   - bpo-32230(17): ‘-X dev’ now injects a ‘'default'’ entry into
     sys.warnoptions, ensuring that it behaves identically to actually
     passing ‘-Wdefault’ at the command line.

   - bpo-29240(18): Add a new UTF-8 mode: implementation of the PEP
     540(19).

   - bpo-32226(20): PEP 560(21): Add support for ‘__mro_entries__’ and
     ‘__class_getitem__’.  Implemented by Ivan Levkivskyi.

   - bpo-32225(22): PEP 562(23): Add support for module ‘__getattr__’
     and ‘__dir__’.  Implemented by Ivan Levkivskyi.

   - bpo-31901(24): The *note atexit: b. module now has its callback
     stored per interpreter.

   - bpo-31650(25): Implement PEP 552(26) (Deterministic pycs).  Python
     now supports invalidating bytecode cache files bashed on a source
     content hash rather than source last-modified time.

   - bpo-29469(27): Move constant folding from bytecode layer to AST
     layer.  Original patch by Eugene Toder.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31975

   (2) https://bugs.python.org/issue32226

   (3) https://bugs.python.org/issue32399

   (4) https://bugs.python.org/issue32390

   (5) https://bugs.python.org/issue32143

   (6) https://bugs.python.org/issue32379

   (7) https://bugs.python.org/issue32259

   (8) https://bugs.python.org/issue27169

   (9) https://bugs.python.org/issue22091

   (10) https://bugs.python.org/issue32329

   (11) https://bugs.python.org/issue30416

   (12) https://bugs.python.org/issue32282

   (13) https://bugs.python.org/issue30579

   (14) https://bugs.python.org/issue32260

   (15) https://bugs.python.org/issue31506

   (16) https://bugs.python.org/issue20361

   (17) https://bugs.python.org/issue32230

   (18) https://bugs.python.org/issue29240

   (19) https://www.python.org/dev/peps/pep-0540

   (20) https://bugs.python.org/issue32226

   (21) https://www.python.org/dev/peps/pep-0560

   (22) https://bugs.python.org/issue32225

   (23) https://www.python.org/dev/peps/pep-0562

   (24) https://bugs.python.org/issue31901

   (25) https://bugs.python.org/issue31650

   (26) https://www.python.org/dev/peps/pep-0552

   (27) https://bugs.python.org/issue29469


File: python.info,  Node: 库<38>,  Next: 文档<32>,  Prev: 核心与内置函数<35>,  Up: Python 3 7 0 alpha 4

1.19.39.2 库
............

   - bpo-32506(1): Now that dict is defined as keeping insertion order,
     drop OrderedDict and just use plain dict.

   - bpo-32279(2): Add params to dataclasses.make_dataclasses(): init,
     repr, eq, order, hash, and frozen.  Pass them through to
     dataclass().

   - bpo-32278(3): Make type information optional on
     dataclasses.make_dataclass().  If omitted, the string ’typing.Any’
     is used.

   - bpo-32499(4): Add dataclasses.is_dataclass(obj), which returns True
     if obj is a dataclass or an instance of one.

   - bpo-32468(5): Improve frame repr() to mention filename, code name
     and current line number.

   - bpo-23749(6): asyncio: Implement loop.start_tls()

   - bpo-32441(7): Return the new file descriptor (i.e., the second
     argument) from ‘os.dup2’.  Previously, ‘None’ was always returned.

   - bpo-32422(8): ‘functools.lru_cache’ uses less memory (3 words for
     each cached key) and takes about 1/3 time for cyclic GC.

   - bpo-31721(9): 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.

   - bpo-32415(10): asyncio: Add Task.get_loop() and Future.get_loop()

   - bpo-26133(11): Don’t unsubscribe signals in asyncio UNIX event loop
     on interpreter shutdown.

   - bpo-32363(12): 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.

   - bpo-32357(13): 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.

   - bpo-32356(14): asyncio.transport.resume_reading() and
     pause_reading() are now idempotent.  New transport.is_reading()
     method is added.

   - bpo-32355(15): Optimize asyncio.gather(); now up to 15% faster.

   - bpo-32351(16): Use fastpath in asyncio.sleep if delay<0 (2x boost)

   - bpo-32348(17): Optimize asyncio.Future schedule/add/remove
     callback.  The optimization shows 3-6% performance improvements of
     async/await code.

   - bpo-32331(18): 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.

   - bpo-32248(19): Add *note importlib.abc.ResourceReader: 44e. as an
     ABC for loaders to provide a unified API for reading resources
     contained within packages.  Also add *note importlib.resources: 9e.
     as the port of ‘importlib_resources’.

   - bpo-32311(20): Implement asyncio.create_task(coro) shortcut

   - bpo-32327(21): 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.

   - bpo-32323(22): *note urllib.parse.urlsplit(): 6f0. does not convert
     zone-id (scope) to lower case for scoped IPv6 addresses in
     hostnames now.

   - bpo-32302(23): Fix bdist_wininst of distutils for CRT v142: it
     binary compatible with CRT v140.

   - bpo-29711(24): Fix ‘stop_serving’ in asyncio proactor loop kill all
     listening servers

   - bpo-32308(25): *note re.sub(): 579. now replaces empty matches
     adjacent to a previous non-empty match.

   - bpo-29970(26): Abort asyncio SSLProtocol connection if handshake
     not complete within 10s

   - bpo-32314(27): Implement asyncio.run().

   - bpo-17852(28): Revert incorrect fix based on misunderstanding of
     _Py_PyAtExit() semantics.

   - bpo-32296(29): Implement asyncio._get_running_loop() and
     get_event_loop() in C. This makes them 4x faster.

   - bpo-32250(30): Implement ‘asyncio.current_task()’ and
     ‘asyncio.all_tasks()’.  Add helpers intended to be used by
     alternative task implementations: ‘asyncio._register_task’,
     ‘asyncio._enter_task’, ‘asyncio._leave_task’ and
     ‘asyncio._unregister_task’.  Deprecate
     ‘asyncio.Task.current_task()’ and ‘asyncio.Task.all_tasks()’.

   - bpo-32255(31): 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.

   - bpo-32277(32): Raise ‘NotImplementedError’ instead of ‘SystemError’
     on platforms where ‘chmod(..., follow_symlinks=False)’ is not
     supported.  Patch by Anthony Sottile.

   - bpo-30050(33): 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.

   - bpo-29137(34): The ‘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.

   - bpo-32273(35): Move asyncio.test_utils to test.test_asyncio.

   - bpo-32272(36): Remove asyncio.async() function.

   - bpo-32269(37): Add asyncio.get_running_loop() function.

   - bpo-32265(38): 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.

   - bpo-32253(39): Deprecate ‘yield from lock’, ‘await lock’, ‘with
     (yield from lock)’ and ‘with await lock’ for asyncio
     synchronization primitives.

   - bpo-22589(40): Changed MIME type of .bmp from ’image/x-ms-bmp’ to
     ’image/bmp’

   - bpo-32193(41): Convert asyncio to use `async/await' syntax.  Old
     styled ‘yield from’ is still supported too.

   - bpo-32206(42): Add support to run modules with pdb

   - bpo-32227(43): ‘functools.singledispatch’ now supports registering
     implementations using type annotations.

   - bpo-15873(44): Added new alternate constructors *note
     datetime.datetime.fromisoformat(): 486, *note
     datetime.time.fromisoformat(): 11cb. and *note
     datetime.date.fromisoformat(): 11cc. as the inverse operation of
     each classes’s respective ‘isoformat’ methods.

   - bpo-32199(45): The getnode() ip getter now uses ’ip link’ instead
     of ’ip link list’.

   - bpo-32143(46): os.statvfs() includes the f_fsid field from
     statvfs(2)

   - bpo-26439(47): Fix ctypes.util.find_library() for AIX by
     implementing ctypes._aix.find_library() Patch by: Michael Felt

   - bpo-31993(48): 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.

   - bpo-27456(49): Ensure TCP_NODELAY is set on Linux.  Tests by Victor
     Stinner.

   - bpo-31778(50): ast.literal_eval() is now more strict.  Addition and
     subtraction of arbitrary numbers no longer allowed.

   - bpo-31802(51): Importing native path module (‘posixpath’, ‘ntpath’)
     now works even if the ‘os’ module still is not imported.

   - bpo-30241(52): Add contextlib.AbstractAsyncContextManager.  Patch
     by Jelle Zijlstra.

   - bpo-31699(53): Fix deadlocks in *note
     concurrent.futures.ProcessPoolExecutor: 196. when task arguments or
     results cause pickling or unpickling errors.  This should make sure
     that calls to the ‘ProcessPoolExecutor’ API always eventually
     return.

   - bpo-15216(54): ‘TextIOWrapper.reconfigure()’ supports changing
     `encoding', `errors', and `newline'.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32506

   (2) https://bugs.python.org/issue32279

   (3) https://bugs.python.org/issue32278

   (4) https://bugs.python.org/issue32499

   (5) https://bugs.python.org/issue32468

   (6) https://bugs.python.org/issue23749

   (7) https://bugs.python.org/issue32441

   (8) https://bugs.python.org/issue32422

   (9) https://bugs.python.org/issue31721

   (10) https://bugs.python.org/issue32415

   (11) https://bugs.python.org/issue26133

   (12) https://bugs.python.org/issue32363

   (13) https://bugs.python.org/issue32357

   (14) https://bugs.python.org/issue32356

   (15) https://bugs.python.org/issue32355

   (16) https://bugs.python.org/issue32351

   (17) https://bugs.python.org/issue32348

   (18) https://bugs.python.org/issue32331

   (19) https://bugs.python.org/issue32248

   (20) https://bugs.python.org/issue32311

   (21) https://bugs.python.org/issue32327

   (22) https://bugs.python.org/issue32323

   (23) https://bugs.python.org/issue32302

   (24) https://bugs.python.org/issue29711

   (25) https://bugs.python.org/issue32308

   (26) https://bugs.python.org/issue29970

   (27) https://bugs.python.org/issue32314

   (28) https://bugs.python.org/issue17852

   (29) https://bugs.python.org/issue32296

   (30) https://bugs.python.org/issue32250

   (31) https://bugs.python.org/issue32255

   (32) https://bugs.python.org/issue32277

   (33) https://bugs.python.org/issue30050

   (34) https://bugs.python.org/issue29137

   (35) https://bugs.python.org/issue32273

   (36) https://bugs.python.org/issue32272

   (37) https://bugs.python.org/issue32269

   (38) https://bugs.python.org/issue32265

   (39) https://bugs.python.org/issue32253

   (40) https://bugs.python.org/issue22589

   (41) https://bugs.python.org/issue32193

   (42) https://bugs.python.org/issue32206

   (43) https://bugs.python.org/issue32227

   (44) https://bugs.python.org/issue15873

   (45) https://bugs.python.org/issue32199

   (46) https://bugs.python.org/issue32143

   (47) https://bugs.python.org/issue26439

   (48) https://bugs.python.org/issue31993

   (49) https://bugs.python.org/issue27456

   (50) https://bugs.python.org/issue31778

   (51) https://bugs.python.org/issue31802

   (52) https://bugs.python.org/issue30241

   (53) https://bugs.python.org/issue31699

   (54) https://bugs.python.org/issue15216


File: python.info,  Node: 文档<32>,  Next: 测试<30>,  Prev: 库<38>,  Up: Python 3 7 0 alpha 4

1.19.39.3 文档
..............

   - bpo-32418(1): Add get_loop() method to Server and AbstractServer
     classes.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32418


File: python.info,  Node: 测试<30>,  Next: Windows<30>,  Prev: 文档<32>,  Up: Python 3 7 0 alpha 4

1.19.39.4 测试
..............

   - bpo-32252(1): Fix faulthandler_suppress_crash_report() used to
     prevent core dump files when testing crashes.  getrlimit() returns
     zero on success.

   - bpo-32002(2): Adjust C locale coercion testing for the empty locale
     and POSIX locale cases to more readily adjust to platform dependent
     behaviour.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32252

   (2) https://bugs.python.org/issue32002


File: python.info,  Node: Windows<30>,  Next: 工具/示例<15>,  Prev: 测试<30>,  Up: Python 3 7 0 alpha 4

1.19.39.5 Windows
.................

   - bpo-19764(1): Implement support for
     ‘subprocess.Popen(close_fds=True)’ on Windows.  Patch by Segev
     Finer.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue19764


File: python.info,  Node: 工具/示例<15>,  Next: C API<24>,  Prev: Windows<30>,  Up: Python 3 7 0 alpha 4

1.19.39.6 工具/示例
...................

   - bpo-24960(1): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24960


File: python.info,  Node: C API<24>,  Prev: 工具/示例<15>,  Up: Python 3 7 0 alpha 4

1.19.39.7 C API
...............

   - bpo-32030(1): Py_Initialize() doesn’t reset the memory allocators
     to default if the ‘PYTHONMALLOC’ environment variable is not set.

   - bpo-29084(2): 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.

   - bpo-32264(3): Moved the pygetopt.h header into internal/, since it
     has no public APIs.

   - bpo-32241(4): *note Py_SetProgramName(): 10f2. and *note
     Py_SetPythonHome(): 10f1. now take the ‘const wchar *’ arguments
     instead of ‘wchar *’.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32030

   (2) https://bugs.python.org/issue29084

   (3) https://bugs.python.org/issue32264

   (4) https://bugs.python.org/issue32241


File: python.info,  Node: Python 3 7 0 alpha 3,  Next: Python 3 7 0 alpha 2,  Prev: Python 3 7 0 alpha 4,  Up: Changelog（更動日誌）

1.19.40 Python 3.7.0 alpha 3
----------------------------

`发布日期: 2017-12-05'

* Menu:

* 核心与内置函数: 核心与内置函数<36>.
* 库: 库<39>.
* 文档: 文档<33>.
* 测试: 测试<31>.
* 构建: 构建<30>.
* Windows: Windows<31>.
* macOS: macOS<26>.
* IDLE: IDLE<30>.
* 工具/示例: 工具/示例<16>.
* C API: C API<25>.


File: python.info,  Node: 核心与内置函数<36>,  Next: 库<39>,  Up: Python 3 7 0 alpha 3

1.19.40.1 核心与内置函数
........................

   - bpo-32176(1): 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.

   - bpo-10544(2): 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.

   - bpo-32137(3): The repr of deeply nested dict now raises a
     RecursionError instead of crashing due to a stack overflow.

   - bpo-32096(4): 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().

   - bpo-32043(5): Add a new "developer mode": new "-X dev" command line
     option to enable debug checks at runtime.

   - bpo-32023(6): 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.

   - bpo-32012(7): 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.

   - bpo-28180(8): A new internal ‘_Py_SetLocaleFromEnv(category)’
     helper function has been added in order to improve the consistency
     of behaviour across different ‘libc’ implementations (e.g.  Android
     doesn’t support setting the locale from the environment by
     default).

   - bpo-31949(9): 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 ‘2**31’ traceback items on Windows.  Fixed output
     errors handling.

   - bpo-30696(10): Fix the interactive interpreter looping endlessly
     when no memory.

   - bpo-20047(11): 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.

   - bpo-21720(12): BytesWarning no longer emitted when the `fromlist'
     argument of ‘__import__()’ or the ‘__all__’ attribute of the module
     contain bytes instances.

   - bpo-31845(13): Environment variables are once more read correctly
     at interpreter startup.

   - bpo-28936(14): Ensure that lexically first syntax error involving a
     parameter and ‘global’ or ‘nonlocal’ is detected first at a given
     scope.  Patch by Ivan Levkivskyi.

   - bpo-31825(15): Fixed OverflowError in the ’unicode-escape’ codec
     and in codecs.escape_decode() when decode an escaped non-ascii
     byte.

   - bpo-31618(16): The per-frame tracing logic added in 3.7a1 has been
     altered so that ‘frame->f_lineno’ is updated before either ‘"line"’
     or ‘"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 ‘f_trace_lines’ and
     ‘f_trace_opcodes’ are enabled, line events now occur first.

   - bpo-28603(17): 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.

   - bpo-31786(18): 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.

   - bpo-31781(19): Prevent crashes when calling methods of an
     uninitialized ‘zipimport.zipimporter’ object.  Patch by Oren
     Milman.

   - bpo-30399(20): Standard repr() of BaseException with a single
     argument no longer contains redundant trailing comma.

   - bpo-31626(21): Fixed a bug in debug memory allocator.  There was a
     write to freed memory after shrinking a memory block.

   - bpo-30817(22): ‘PyErr_PrintEx()’ clears now the ignored exception
     that may be raised by ‘_PySys_SetObjectId()’, for example when no
     memory.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32176

   (2) https://bugs.python.org/issue10544

   (3) https://bugs.python.org/issue32137

   (4) https://bugs.python.org/issue32096

   (5) https://bugs.python.org/issue32043

   (6) https://bugs.python.org/issue32023

   (7) https://bugs.python.org/issue32012

   (8) https://bugs.python.org/issue28180

   (9) https://bugs.python.org/issue31949

   (10) https://bugs.python.org/issue30696

   (11) https://bugs.python.org/issue20047

   (12) https://bugs.python.org/issue21720

   (13) https://bugs.python.org/issue31845

   (14) https://bugs.python.org/issue28936

   (15) https://bugs.python.org/issue31825

   (16) https://bugs.python.org/issue31618

   (17) https://bugs.python.org/issue28603

   (18) https://bugs.python.org/issue31786

   (19) https://bugs.python.org/issue31781

   (20) https://bugs.python.org/issue30399

   (21) https://bugs.python.org/issue31626

   (22) https://bugs.python.org/issue30817


File: python.info,  Node: 库<39>,  Next: 文档<33>,  Prev: 核心与内置函数<36>,  Up: Python 3 7 0 alpha 3

1.19.40.2 库
............

   - bpo-28556(1): Two minor fixes for ‘typing’ module: allow shallow
     copying instances of generic classes, improve interaction of
     ‘__init_subclass__’ with generics.  Original PRs by Ivan
     Levkivskyi.

   - bpo-32214(2): PEP 557, Data Classes.  Provides a decorator which
     adds boilerplate methods to classes which use type annotations so
     specify fields.

   - bpo-27240(3): The header folding algorithm for the new email
     policies has been rewritten, which also fixes bpo-30788(4),
     bpo-31831(5), and bpo-32182(6).  In particular, RFC2231 folding is
     now done correctly.

   - bpo-32186(7): 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.

   - bpo-321010(8): Add ‘sys.flags.dev_mode’ flag

   - bpo-32154(9): The ‘asyncio.windows_utils.socketpair()’ function has
     been removed: use directly *note socket.socketpair(): 57c. which is
     available on all platforms since Python 3.5 (before, it wasn’t
     available on Windows).  ‘asyncio.windows_utils.socketpair()’ was
     just an alias to ‘socket.socketpair’ on Python 3.5 and newer.

   - bpo-32089(10): 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.

   - bpo-32107(11): ‘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 ‘uuid.uuid1()’.  If only
     locally administered MAC addresses are available, the first such
     one found is returned.

   - bpo-23033(12): Wildcard is now supported in hostname when it is one
     and only character in the left most segment of hostname in second
     argument of *note ssl.match_hostname(): 4e2.  Patch by Mandeep
     Singh.

   - bpo-12239(13): Make *note msilib.SummaryInformation.GetProperty():
     10fe. return ‘None’ when the value of property is ‘VT_EMPTY’.
     Initial patch by Mark Mc Mahon.

   - bpo-28334(14): Use *note os.path.expanduser(): 32c. to find the
     ‘~/.netrc’ file in *note netrc.netrc: 11d5.  If it does not exist,
     *note FileNotFoundError: 8ad. is raised.  Patch by Dimitri
     Merejkowsky.

   - bpo-32121(15): Made ‘tracemalloc.Traceback’ behave more like the
     traceback module, sorting the frames from oldest to most recent.
     ‘Traceback.format()’ now accepts negative `limit', truncating the
     result to the ‘abs(limit)’ oldest frames.  To get the old
     behaviour, one can use the new `most_recent_first' argument to
     ‘Traceback.format()’.  (Patch by Jesse Bakker.)

   - bpo-31325(16): Fix wrong usage of *note collections.namedtuple():
     1a1. in the *note RobotFileParser.parse(): 11d6. method.  Initial
     patch by Robin Wellner.

   - bpo-12382(17): *note msilib.OpenDatabase(): 1020. now raises a
     better exception message when it couldn’t open or create an MSI
     file.  Initial patch by William Tisäter.

   - bpo-19610(18): ‘setup()’ now warns about invalid types for some
     fields.  The ‘distutils.dist.Distribution’ class now warns when
     ‘classifiers’, ‘keywords’ and ‘platforms’ fields are not specified
     as a list or a string.

   - bpo-32071(19): Added the ‘-k’ command-line option to ‘python -m
     unittest’ to run only tests that match the given pattern(s).

   - bpo-10049(20): Added `nullcontext' no-op context manager to
     contextlib.  This provides a simpler and faster alternative to
     ExitStack() when handling optional context managers.

   - bpo-28684(21): 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).

   - bpo-32110(22): ‘codecs.StreamReader.read(n)’ now returns not more
     than `n' characters/bytes for non-negative `n'.  This makes it
     compatible with ‘read()’ methods of other file-like objects.

   - bpo-27535(23): 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.

   - bpo-32088(24): warnings: When Python is build is debug mode
     (‘Py_DEBUG’), *note DeprecationWarning: 15a, *note
     PendingDeprecationWarning: 15c. and *note ImportWarning: 6cf.
     warnings are now displayed by default.

   - bpo-1647489(25): Fixed searching regular expression patterns that
     could match an empty string.  Non-empty string can now be correctly
     found after matching an empty string.

   - bpo-25054(26): Added support of splitting on a pattern that could
     match an empty string.

   - bpo-32072(27): 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.

   - bpo-32069(28): Drop legacy SSL transport from asyncio,
     ssl.MemoryBIO is always used anyway.

   - bpo-32066(29): asyncio: Support pathlib.Path in
     create_unix_connection; sock arg should be optional

   - bpo-32046(30): Updates 2to3 to convert from
     operator.isCallable(obj) to callable(obj).  Patch by Dong-hee Na.

   - bpo-32018(31): inspect.signature should follow PEP 8(32), if the
     parameter has an annotation and a default value.  Patch by Dong-hee
     Na.

   - bpo-32025(33): Add time.thread_time() and time.thread_time_ns()

   - bpo-32037(34): 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.

   - bpo-32034(35): Make asyncio.IncompleteReadError and
     LimitOverrunError pickleable.

   - bpo-32015(36): Fixed the looping of asyncio in the case of
     reconnection the socket during waiting async read/write from/to the
     socket.

   - bpo-32011(37): Restored support of loading marshal files with the
     TYPE_INT64 code.  These files can be produced in Python 2.7.

   - bpo-28369(38): 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.

   - bpo-31976(39): Fix race condition when flushing a file is slow,
     which can cause a segfault if closing the file from another thread.

   - bpo-31985(40): 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.

   - bpo-21862(41): cProfile command line now accepts ‘-m module_name’
     as an alternative to script path.  Patch by Sanyam Khurana.

   - bpo-31970(42): Reduce performance overhead of asyncio debug mode.

   - bpo-31843(43): `database' argument of sqlite3.connect() now accepts
     a *note path-like object: 472, instead of just a string.

   - bpo-31945(44): Add Configurable `blocksize' to ‘HTTPConnection’ and
     ‘HTTPSConnection’ for improved upload throughput.  Patch by Nir
     Soffer.

   - bpo-31943(45): Add a ‘cancelled()’ method to *note asyncio.Handle:
     11d7.  Patch by Marat Sharafutdinov.

   - bpo-9678(46): 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.

   - bpo-30057(47): Fix potential missed signal in signal.signal().

   - bpo-31933(48): Fix Blake2 params leaf_size and node_offset on big
     endian platforms.  Patch by Jack O’Connor.

   - bpo-21423(49): Add an initializer argument to
     {Process,Thread}PoolExecutor

   - bpo-31927(50): 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.

   - bpo-27666(51): 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.

   - bpo-31917(52): Add 3 new clock identifiers: *note
     time.CLOCK_BOOTTIME: 4fa, *note time.CLOCK_PROF: 4fc. and *note
     time.CLOCK_UPTIME: 4fd.

   - bpo-31897(53): plistlib now catches more errors when read binary
     plists and raises InvalidFileException instead of unexpected
     exceptions.

   - bpo-25720(54): Fix the method for checking pad state of curses
     WINDOW. Patch by Masayuki Yamamoto.

   - bpo-31893(55): Fixed the layout of the kqueue_event structure on
     OpenBSD and NetBSD. Fixed the comparison of the kqueue_event
     objects.

   - bpo-31891(56): Fixed building the curses module on NetBSD.

   - bpo-31884(57): added required constants to subprocess module for
     setting priority on windows

   - bpo-28281(58): Remove year (1-9999) limits on the
     Calendar.weekday() function.  Patch by Mark Gollahon.

   - bpo-31702(59): crypt.mksalt() now allows to specify the number of
     rounds for SHA-256 and SHA-512 hashing.

   - bpo-30639(60): *note inspect.getfile(): 11d8. no longer computes
     the repr of unknown objects to display in an error message, to
     protect against badly behaved custom reprs.

   - bpo-30768(61): 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 PEP 475(62).

   - bpo-31854(63): Add ‘mmap.ACCESS_DEFAULT’ constant.

   - bpo-31834(64): Use optimized code for BLAKE2 only with SSSE3+.  The
     pure SSE2 implementation is slower than the pure C reference
     implementation.

   - bpo-28292(65): 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.

   - bpo-28564(66): The shutil.rmtree() function has been sped up to
     20–40%.  This was done using the os.scandir() function.

   - bpo-28416(67): Instances of pickle.Pickler subclass with the
     persistent_id() method and pickle.Unpickler subclass with the
     persistent_load() method no longer create reference cycles.

   - bpo-31653(68): Don’t release the GIL if we can acquire a
     multiprocessing semaphore immediately.

   - bpo-28326(69): Fix multiprocessing.Process when stdout and/or
     stderr is closed or None.

   - bpo-20825(70): Add ‘subnet_of’ and ‘superset_of’ containment tests
     to *note ipaddress.IPv6Network: 4a5. and *note
     ipaddress.IPv4Network: 4a6.  Patch by Michel Albert and Cheryl
     Sabella.

   - bpo-31827(71): 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.

   - bpo-31756(72): Add a ‘subprocess.Popen(text=False)’ keyword
     argument to *note subprocess: f9. functions to be more explicit
     about when the library should attempt to decode outputs into text.
     Patch by Andrew Clegg.

   - bpo-31819(73): Add AbstractEventLoop.sock_recv_into().

   - bpo-31457(74): If nested log adapters are used, the inner
     ‘process()’ methods are no longer omitted.

   - bpo-31457(75): The ‘manager’ property on LoggerAdapter objects is
     now properly settable.

   - bpo-31806(76): 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.

   - bpo-31803(77): time.clock() and time.get_clock_info(’clock’) now
     emit a DeprecationWarning warning.

   - bpo-31800(78): Extended support for parsing UTC offsets.  strptime
     ’%z’ can now parse the output generated by datetime.isoformat,
     including seconds and microseconds.

   - bpo-28603(79): 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.

   - bpo-30541(80): Add new function to seal a mock and prevent the
     automatically creation of child mocks.  Patch by Mario Corchero.

   - bpo-31784(81): Implement the PEP 564(82), add new 6 new functions
     with nanosecond resolution to the *note time: 10c. module: *note
     clock_gettime_ns(): 42e, *note clock_settime_ns(): 42f, *note
     monotonic_ns(): 430, *note perf_counter_ns(): 431, *note
     process_time_ns(): 432, *note time_ns(): 433.

   - bpo-30143(83): 2to3 now generates a code that uses abstract
     collection classes from collections.abc rather than collections.

   - bpo-31770(84): Prevent a crash when calling the ‘__init__()’ method
     of a ‘sqlite3.Cursor’ object more than once.  Patch by Oren Milman.

   - bpo-31764(85): Prevent a crash in ‘sqlite3.Cursor.close()’ in case
     the ‘Cursor’ object is uninitialized.  Patch by Oren Milman.

   - bpo-31752(86): Fix possible crash in timedelta constructor called
     with custom integers.

   - bpo-31620(87): an empty asyncio.Queue now doesn’t leak memory when
     queue.get pollers timeout

   - bpo-31690(88): Allow the flags re.ASCII, re.LOCALE, and re.UNICODE
     to be used as group flags for regular expressions.

   - bpo-30349(89): FutureWarning is now emitted if a regular expression
     contains character set constructs that will change semantically in
     the future (nested sets and set operations).

   - bpo-31664(90): Added support for the Blowfish hashing in the crypt
     module.

   - bpo-31632(91): Fix method set_protocol() of class
     _SSLProtocolTransport in asyncio module.  This method was
     previously modifying a wrong reference to the protocol.

   - bpo-15037(92): Added a workaround for getkey() in curses for
     ncurses 5.7 and earlier.

   - bpo-31307(93): Allow use of bytes objects for arguments to *note
     configparser.ConfigParser.read(): 11d9.  Patch by Vincent Michel.

   - bpo-31334(94): Fix ‘poll.poll([timeout])’ in the ‘select’ module
     for arbitrary negative timeouts on all OSes where it can only be a
     non-negative integer or -1.  Patch by Riccardo Coccioli.

   - bpo-31310(95): multiprocessing’s semaphore tracker should be
     launched again if crashed.

   - bpo-31308(96): Make multiprocessing’s forkserver process immune to
     Ctrl-C and other user interruptions.  If it crashes, restart it
     when necessary.

   - bpo-31245(97): Added support for AF_UNIX socket in asyncio
     ‘create_datagram_endpoint’.

   - bpo-30553(98): Add HTTP/2 status code 421 (Misdirected Request) to
     *note http.HTTPStatus: 1ac.  Patch by Vitor Pereira.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28556

   (2) https://bugs.python.org/issue32214

   (3) https://bugs.python.org/issue27240

   (4) https://bugs.python.org/issue30788

   (5) https://bugs.python.org/issue31831

   (6) https://bugs.python.org/issue32182

   (7) https://bugs.python.org/issue32186

   (8) https://bugs.python.org/issue321010

   (9) https://bugs.python.org/issue32154

   (10) https://bugs.python.org/issue32089

   (11) https://bugs.python.org/issue32107

   (12) https://bugs.python.org/issue23033

   (13) https://bugs.python.org/issue12239

   (14) https://bugs.python.org/issue28334

   (15) https://bugs.python.org/issue32121

   (16) https://bugs.python.org/issue31325

   (17) https://bugs.python.org/issue12382

   (18) https://bugs.python.org/issue19610

   (19) https://bugs.python.org/issue32071

   (20) https://bugs.python.org/issue10049

   (21) https://bugs.python.org/issue28684

   (22) https://bugs.python.org/issue32110

   (23) https://bugs.python.org/issue27535

   (24) https://bugs.python.org/issue32088

   (25) https://bugs.python.org/issue1647489

   (26) https://bugs.python.org/issue25054

   (27) https://bugs.python.org/issue32072

   (28) https://bugs.python.org/issue32069

   (29) https://bugs.python.org/issue32066

   (30) https://bugs.python.org/issue32046

   (31) https://bugs.python.org/issue32018

   (32) https://www.python.org/dev/peps/pep-0008

   (33) https://bugs.python.org/issue32025

   (34) https://bugs.python.org/issue32037

   (35) https://bugs.python.org/issue32034

   (36) https://bugs.python.org/issue32015

   (37) https://bugs.python.org/issue32011

   (38) https://bugs.python.org/issue28369

   (39) https://bugs.python.org/issue31976

   (40) https://bugs.python.org/issue31985

   (41) https://bugs.python.org/issue21862

   (42) https://bugs.python.org/issue31970

   (43) https://bugs.python.org/issue31843

   (44) https://bugs.python.org/issue31945

   (45) https://bugs.python.org/issue31943

   (46) https://bugs.python.org/issue9678

   (47) https://bugs.python.org/issue30057

   (48) https://bugs.python.org/issue31933

   (49) https://bugs.python.org/issue21423

   (50) https://bugs.python.org/issue31927

   (51) https://bugs.python.org/issue27666

   (52) https://bugs.python.org/issue31917

   (53) https://bugs.python.org/issue31897

   (54) https://bugs.python.org/issue25720

   (55) https://bugs.python.org/issue31893

   (56) https://bugs.python.org/issue31891

   (57) https://bugs.python.org/issue31884

   (58) https://bugs.python.org/issue28281

   (59) https://bugs.python.org/issue31702

   (60) https://bugs.python.org/issue30639

   (61) https://bugs.python.org/issue30768

   (62) https://www.python.org/dev/peps/pep-0475

   (63) https://bugs.python.org/issue31854

   (64) https://bugs.python.org/issue31834

   (65) https://bugs.python.org/issue28292

   (66) https://bugs.python.org/issue28564

   (67) https://bugs.python.org/issue28416

   (68) https://bugs.python.org/issue31653

   (69) https://bugs.python.org/issue28326

   (70) https://bugs.python.org/issue20825

   (71) https://bugs.python.org/issue31827

   (72) https://bugs.python.org/issue31756

   (73) https://bugs.python.org/issue31819

   (74) https://bugs.python.org/issue31457

   (75) https://bugs.python.org/issue31457

   (76) https://bugs.python.org/issue31806

   (77) https://bugs.python.org/issue31803

   (78) https://bugs.python.org/issue31800

   (79) https://bugs.python.org/issue28603

   (80) https://bugs.python.org/issue30541

   (81) https://bugs.python.org/issue31784

   (82) https://www.python.org/dev/peps/pep-0564

   (83) https://bugs.python.org/issue30143

   (84) https://bugs.python.org/issue31770

   (85) https://bugs.python.org/issue31764

   (86) https://bugs.python.org/issue31752

   (87) https://bugs.python.org/issue31620

   (88) https://bugs.python.org/issue31690

   (89) https://bugs.python.org/issue30349

   (90) https://bugs.python.org/issue31664

   (91) https://bugs.python.org/issue31632

   (92) https://bugs.python.org/issue15037

   (93) https://bugs.python.org/issue31307

   (94) https://bugs.python.org/issue31334

   (95) https://bugs.python.org/issue31310

   (96) https://bugs.python.org/issue31308

   (97) https://bugs.python.org/issue31245

   (98) https://bugs.python.org/issue30553


File: python.info,  Node: 文档<33>,  Next: 测试<31>,  Prev: 库<39>,  Up: Python 3 7 0 alpha 3

1.19.40.3 文档
..............

   - bpo-32105(1): Added asyncio.BaseEventLoop.connect_accepted_socket
     versionadded marker.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32105


File: python.info,  Node: 测试<31>,  Next: 构建<30>,  Prev: 文档<33>,  Up: Python 3 7 0 alpha 3

1.19.40.4 测试
..............

   - bpo-31380(1): Skip test_httpservers test_undecodable_file on macOS:
     fails on APFS.

   - bpo-31705(2): 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.

   - bpo-32138(3): Skip on Android test_faulthandler tests that raise
     SIGSEGV and remove the test.support.requires_android_level
     decorator.

   - bpo-32136(4): The runtime embedding tests have been split out from
     ‘Lib/test/test_capi.py’ into a new ‘Lib/test/test_embed.py’ file.

   - bpo-28668(5): 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.

   - bpo-32126(6): Skip test_get_event_loop_new_process in
     test.test_asyncio.test_events when sem_open() is not functional.

   - bpo-31174(7): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31380

   (2) https://bugs.python.org/issue31705

   (3) https://bugs.python.org/issue32138

   (4) https://bugs.python.org/issue32136

   (5) https://bugs.python.org/issue28668

   (6) https://bugs.python.org/issue32126

   (7) https://bugs.python.org/issue31174


File: python.info,  Node: 构建<30>,  Next: Windows<31>,  Prev: 测试<31>,  Up: Python 3 7 0 alpha 3

1.19.40.5 构建
..............

   - bpo-28538(1): Revert the previous changes, the if_nameindex
     structure is defined by Unified Headers.

   - bpo-28762(2): Revert the last commit, the F_LOCK macro is defined
     by Android Unified Headers.

   - bpo-29040(3): Support building Android with Unified Headers.  The
     first NDK release to support Unified Headers is android-ndk-r14.

   - bpo-32059(4): ‘detect_modules()’ in ‘setup.py’ now also searches
     the sysroot paths when cross-compiling.

   - bpo-31957(5): Fixes Windows SDK version detection when building for
     Windows.

   - bpo-31609(6): Fixes quotes in PCbuild/clean.bat

   - bpo-31934(7): Abort the build when building out of a not clean
     source tree.

   - bpo-31926(8): 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.

   - bpo-28791(9): 更新 Windows 构建以使用 SQLite 3.21.0.

   - bpo-28791(10): 更新 OS X 安装程序以使用 SQLite 3.21.0.

   - bpo-28643(11): Record profile-opt build progress with stamp files.

   - bpo-31866(12): Finish removing support for AtheOS.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28538

   (2) https://bugs.python.org/issue28762

   (3) https://bugs.python.org/issue29040

   (4) https://bugs.python.org/issue32059

   (5) https://bugs.python.org/issue31957

   (6) https://bugs.python.org/issue31609

   (7) https://bugs.python.org/issue31934

   (8) https://bugs.python.org/issue31926

   (9) https://bugs.python.org/issue28791

   (10) https://bugs.python.org/issue28791

   (11) https://bugs.python.org/issue28643

   (12) https://bugs.python.org/issue31866


File: python.info,  Node: Windows<31>,  Next: macOS<26>,  Prev: 构建<30>,  Up: Python 3 7 0 alpha 3

1.19.40.6 Windows
.................

   - bpo-1102(1): Return ‘None’ when ‘View.Fetch()’ returns
     ‘ERROR_NO_MORE_ITEMS’ instead of raising ‘MSIError’.  Initial patch
     by Anthony Tuininga.

   - bpo-31944(2): Fixes Modify button in Apps and Features dialog.

   - bpo-20486(3): Implement the ‘Database.Close()’ method to help
     closing MSI database objects.

   - bpo-31857(4): Make the behavior of USE_STACKCHECK deterministic in
     a multi-threaded environment.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1102

   (2) https://bugs.python.org/issue31944

   (3) https://bugs.python.org/issue20486

   (4) https://bugs.python.org/issue31857


File: python.info,  Node: macOS<26>,  Next: IDLE<30>,  Prev: Windows<31>,  Up: Python 3 7 0 alpha 3

1.19.40.7 macOS
...............

   - bpo-31392(1): 更新 macOS 安装程序以使用OpenSSL 1.0.2m

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31392


File: python.info,  Node: IDLE<30>,  Next: 工具/示例<16>,  Prev: macOS<26>,  Up: Python 3 7 0 alpha 3

1.19.40.8 IDLE
..............

   - bpo-32207(1): 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.

   - bpo-32164(2): Delete unused file idlelib/tabbedpages.py.  Use of
     TabbedPageSet in configdialog was replaced by ttk.Notebook.

   - bpo-32100(3): IDLE: Fix old and new bugs in pathbrowser; improve
     tests.  Patch mostly by Cheryl Sabella.

   - bpo-31858(4): 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.

   - bpo-31860(5): The font sample in the IDLE configuration dialog is
     now editable.  Changes persist while IDLE remains open

   - bpo-31836(6): 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.

   - bpo-28603(7): Fix a TypeError that caused a shell restart when
     printing a traceback that includes an exception that is unhashable.
     Patch by Zane Bitter.

   - bpo-13802(8): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32207

   (2) https://bugs.python.org/issue32164

   (3) https://bugs.python.org/issue32100

   (4) https://bugs.python.org/issue31858

   (5) https://bugs.python.org/issue31860

   (6) https://bugs.python.org/issue31836

   (7) https://bugs.python.org/issue28603

   (8) https://bugs.python.org/issue13802


File: python.info,  Node: 工具/示例<16>,  Next: C API<25>,  Prev: IDLE<30>,  Up: Python 3 7 0 alpha 3

1.19.40.9 工具/示例
...................

   - bpo-32159(1): 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.

   - bpo-30722(2): Make redemo work with Python 3.6 and newer versions.
     Also, remove the ‘LOCALE’ option since it doesn’t work with string
     patterns in Python 3.  Patch by Christoph Sarnowski.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32159

   (2) https://bugs.python.org/issue30722


File: python.info,  Node: C API<25>,  Prev: 工具/示例<16>,  Up: Python 3 7 0 alpha 3

1.19.40.10 C API
................

   - bpo-20891(1): 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.

   - bpo-32125(2): The ‘Py_UseClassExceptionsFlag’ flag has been
     removed.  It was deprecated and wasn’t used anymore since Python
     2.0.

   - bpo-25612(3): 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.

   - bpo-23699(4): Add Py_RETURN_RICHCOMPARE macro to reduce boilerplate
     code in rich comparison functions.

   - bpo-30697(5): The ‘PyExc_RecursionErrorInst’ singleton is removed
     and ‘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(6).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20891

   (2) https://bugs.python.org/issue32125

   (3) https://bugs.python.org/issue25612

   (4) https://bugs.python.org/issue23699

   (5) https://bugs.python.org/issue30697

   (6) https://bugs.python.org/issue22898


File: python.info,  Node: Python 3 7 0 alpha 2,  Next: Python 3 7 0 alpha 1,  Prev: Python 3 7 0 alpha 3,  Up: Changelog（更動日誌）

1.19.41 Python 3.7.0 alpha 2
----------------------------

`发布日期: 2017-10-16'

* Menu:

* 核心与内置函数: 核心与内置函数<37>.
* 库: 库<40>.
* 文档: 文档<34>.
* 构建: 构建<31>.
* IDLE: IDLE<31>.
* C API: C API<26>.


File: python.info,  Node: 核心与内置函数<37>,  Next: 库<40>,  Up: Python 3 7 0 alpha 2

1.19.41.1 核心与内置函数
........................

   - bpo-31558(1): ‘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().

   - bpo-31642(2): Restored blocking "from package import module" by
     setting sys.modules["package.module"] to None.

   - bpo-31708(3): Allow use of asynchronous generator expressions in
     synchronous functions.

   - bpo-31709(4): 取消对异步__Aiter__的支持。

   - bpo-30404(5): The -u option now makes the stdout and stderr streams
     unbuffered rather than line-buffered.

   - bpo-31619(6): Fixed a ValueError when convert a string with large
     number of underscores to integer with binary base.

   - bpo-31602(7): Fix an assertion failure in
     ‘zipimporter.get_source()’ in case of a bad *note
     zlib.decompress(): 6b6.  Patch by Oren Milman.

   - bpo-31592(8): Fixed an assertion failure in Python parser in case
     of a bad *note unicodedata.normalize(): 11e4.  Patch by Oren
     Milman.

   - bpo-31588(9): Raise a *note TypeError: 1fe. with a helpful error
     message when class creation fails due to a metaclass with a bad
     ‘__prepare__()’ method.  Patch by Oren Milman.

   - bpo-31574(10): Importlib was instrumented with two dtrace probes to
     profile import timing.

   - bpo-31566(11): Fix an assertion failure in ‘_warnings.warn()’ in
     case of a bad ‘__name__’ global.  Patch by Oren Milman.

   - bpo-31506(12): Improved the error message logic for object.__new__
     and object.__init__.

   - bpo-31505(13): Fix an assertion failure in *note json: a4, in case
     ‘_json.make_encoder()’ received a bad ‘encoder()’ argument.  Patch
     by Oren Milman.

   - bpo-31492(14): Fix assertion failures in case of failing to import
     from a module with a bad ‘__name__’ attribute, and in case of
     failing to access an attribute of such a module.  Patch by Oren
     Milman.

   - bpo-31478(15): Fix an assertion failure in ‘_random.Random.seed()’
     in case the argument has a bad ‘__abs__()’ method.  Patch by Oren
     Milman.

   - bpo-31336(16): Speed up class creation by 10-20% by reducing the
     overhead in the necessary special method lookups.  Patch by Stefan
     Behnel.

   - bpo-31415(17): Add ‘-X importtime’ option to show how long each
     import takes.  It can be used to optimize application’s startup
     time.  Support the *note PYTHONPROFILEIMPORTTIME: 444. as an
     equivalent way to enable this.

   - bpo-31410(18): Optimized calling wrapper and classmethod
     descriptors.

   - bpo-31353(19): PEP 553(20) - Add a new built-in called
     ‘breakpoint()’ which calls ‘sys.breakpointhook()’.  By default this
     imports ‘pdb’ and calls ‘pdb.set_trace()’, but users may override
     ‘sys.breakpointhook()’ to call whatever debugger they want.  The
     original value of the hook is saved in ‘sys.__breakpointhook__’.

   - bpo-17852(21): Maintain a list of open buffered files, flush them
     before exiting the interpreter.  Based on a patch from Armin Rigo.

   - bpo-31315(22): Fix an assertion failure in imp.create_dynamic(),
     when spec.name is not a string.  Patch by Oren Milman.

   - bpo-31311(23): Fix a crash in the ‘__setstate__()’ method of *note
     ctypes._CData: 11e5, in case of a bad ‘__dict__’.  Patch by Oren
     Milman.

   - bpo-31293(24): 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.

   - bpo-31285(25): Fix an assertion failure in *note
     warnings.warn_explicit: 6a7, when the return value of the received
     loader’s get_source() has a bad splitlines() method.  Patch by Oren
     Milman.

   - bpo-30406(26): Make ‘async’ and ‘await’ proper keywords, as
     specified in PEP 492(27).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31558

   (2) https://bugs.python.org/issue31642

   (3) https://bugs.python.org/issue31708

   (4) https://bugs.python.org/issue31709

   (5) https://bugs.python.org/issue30404

   (6) https://bugs.python.org/issue31619

   (7) https://bugs.python.org/issue31602

   (8) https://bugs.python.org/issue31592

   (9) https://bugs.python.org/issue31588

   (10) https://bugs.python.org/issue31574

   (11) https://bugs.python.org/issue31566

   (12) https://bugs.python.org/issue31506

   (13) https://bugs.python.org/issue31505

   (14) https://bugs.python.org/issue31492

   (15) https://bugs.python.org/issue31478

   (16) https://bugs.python.org/issue31336

   (17) https://bugs.python.org/issue31415

   (18) https://bugs.python.org/issue31410

   (19) https://bugs.python.org/issue31353

   (20) https://www.python.org/dev/peps/pep-0553

   (21) https://bugs.python.org/issue17852

   (22) https://bugs.python.org/issue31315

   (23) https://bugs.python.org/issue31311

   (24) https://bugs.python.org/issue31293

   (25) https://bugs.python.org/issue31285

   (26) https://bugs.python.org/issue30406

   (27) https://www.python.org/dev/peps/pep-0492


File: python.info,  Node: 库<40>,  Next: 文档<34>,  Prev: 核心与内置函数<37>,  Up: Python 3 7 0 alpha 2

1.19.41.2 库
............

   - bpo-30058(1): Fixed buffer overflow in select.kqueue.control().

   - bpo-31672(2): ‘idpattern’ in ‘string.Template’ matched some
     non-ASCII characters.  Now it uses ‘-i’ regular expression local
     flag to avoid non-ASCII characters.

   - bpo-31701(3): On Windows, faulthandler.enable() now ignores MSC and
     COM exceptions.

   - bpo-31728(4): Prevent crashes in ‘_elementtree’ due to unsafe
     cleanup of ‘Element.text’ and ‘Element.tail’.  Patch by Oren
     Milman.

   - bpo-31671(5): Now ‘re.compile()’ converts passed RegexFlag to
     normal int object before compiling.  bm_regex_compile benchmark
     shows 14% performance improvements.

   - bpo-30397(6): The types of compiled regular objects and match
     objects are now exposed as ‘re.Pattern’ and ‘re.Match’.  This adds
     information in pydoc output for the re module.

   - bpo-31675(7): Fixed memory leaks in Tkinter’s methods splitlist()
     and split() when pass a string larger than 2 GiB.

   - bpo-31673(8): Fixed typo in the name of Tkinter’s method
     adderrorinfo().

   - bpo-31648(9): 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.

   - bpo-30806(10): Fix the string representation of a netrc object.

   - bpo-31638(11): Add optional argument ‘compressed’ to
     ‘zipapp.create_archive’, and add option ‘--compress’ to the command
     line interface of ‘zipapp’.

   - bpo-25351(12): Avoid venv activate failures with undefined
     variables

   - bpo-20519(13): Avoid ctypes use (if possible) and improve import
     time for uuid.

   - bpo-28293(14): The regular expression cache is no longer completely
     dumped when it is full.

   - bpo-31596(15): Added pthread_getcpuclockid() to the time module

   - bpo-27494(16): Make 2to3 accept a trailing comma in generator
     expressions.  For example, ‘set(x for x in [],)’ is now allowed.

   - bpo-30347(17): Stop crashes when concurrently iterate over
     itertools.groupby() iterators.

   - bpo-30346(18): An iterator produced by itertools.groupby() iterator
     now becomes exhausted after advancing the groupby iterator.

   - bpo-31556(19): Cancel asyncio.wait_for future faster if timeout <=
     0

   - bpo-31540(20): Allow passing a context object in *note
     concurrent.futures.ProcessPoolExecutor: 196. constructor.  Also,
     free job resources in *note concurrent.futures.ProcessPoolExecutor:
     196. earlier to improve memory usage when a worker waits for new
     jobs.

   - bpo-31516(21): ‘threading.current_thread()’ should not return a
     dummy thread at shutdown.

   - bpo-31525(22): In the sqlite module, require the sqlite3_prepare_v2
     API. Thus, the sqlite module now requires sqlite version at least
     3.3.9.

   - bpo-26510(23): argparse subparsers are now required by default.
     This matches behaviour in Python 2.  For optional subparsers, use
     the new parameter ‘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.)

   - bpo-27541(24): Reprs of subclasses of some collection and iterator
     classes (*note bytearray: 173, *note array.array: 216, *note
     collections.deque: 62a, *note collections.defaultdict: c0c, *note
     itertools.count: ce5, *note itertools.repeat: 11e7.) now contain
     actual type name insteads of hardcoded name of the base class.

   - bpo-31351(25): python -m ensurepip now exits with non-zero exit
     code if pip bootstrapping has failed.

   - bpo-31389(26): ‘pdb.set_trace()’ now takes an optional keyword-only
     argument ‘header’.  If given, this is printed to the console just
     before debugging begins.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30058

   (2) https://bugs.python.org/issue31672

   (3) https://bugs.python.org/issue31701

   (4) https://bugs.python.org/issue31728

   (5) https://bugs.python.org/issue31671

   (6) https://bugs.python.org/issue30397

   (7) https://bugs.python.org/issue31675

   (8) https://bugs.python.org/issue31673

   (9) https://bugs.python.org/issue31648

   (10) https://bugs.python.org/issue30806

   (11) https://bugs.python.org/issue31638

   (12) https://bugs.python.org/issue25351

   (13) https://bugs.python.org/issue20519

   (14) https://bugs.python.org/issue28293

   (15) https://bugs.python.org/issue31596

   (16) https://bugs.python.org/issue27494

   (17) https://bugs.python.org/issue30347

   (18) https://bugs.python.org/issue30346

   (19) https://bugs.python.org/issue31556

   (20) https://bugs.python.org/issue31540

   (21) https://bugs.python.org/issue31516

   (22) https://bugs.python.org/issue31525

   (23) https://bugs.python.org/issue26510

   (24) https://bugs.python.org/issue27541

   (25) https://bugs.python.org/issue31351

   (26) https://bugs.python.org/issue31389


File: python.info,  Node: 文档<34>,  Next: 构建<31>,  Prev: 库<40>,  Up: Python 3 7 0 alpha 2

1.19.41.3 文档
..............

   - bpo-31537(1): Fix incorrect usage of ‘get_history_length’ in
     readline documentation example code.  Patch by Brad Smith.

   - bpo-30085(2): The operator functions without double underscores are
     preferred for clarity.  The one with underscores are only kept for
     back-compatibility.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31537

   (2) https://bugs.python.org/issue30085


File: python.info,  Node: 构建<31>,  Next: IDLE<31>,  Prev: 文档<34>,  Up: Python 3 7 0 alpha 2

1.19.41.4 构建
..............

   - bpo-31696(1): Improve compiler version information in *note
     sys.version: 6ca. when Python is built with Clang.

   - bpo-31625(2): Stop using ranlib on static libraries.  Instead, we
     assume ar supports the ’s’ flag.

   - bpo-31624(3): 删除对 BSD/OS 的支持。

   - bpo-22140(4): Prevent double substitution of prefix in
     python-config.sh.

   - bpo-31569(5): Correct PCBuild/ case to PCbuild/ in build scripts
     and documentation.

   - bpo-31536(6): Avoid wholesale rebuild after ‘make regen-all’ if
     nothing changed.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31696

   (2) https://bugs.python.org/issue31625

   (3) https://bugs.python.org/issue31624

   (4) https://bugs.python.org/issue22140

   (5) https://bugs.python.org/issue31569

   (6) https://bugs.python.org/issue31536


File: python.info,  Node: IDLE<31>,  Next: C API<26>,  Prev: 构建<31>,  Up: Python 3 7 0 alpha 2

1.19.41.5 IDLE
..............

   - bpo-31460(1): 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.

   - bpo-31649(2): IDLE - Make _htest, _utest parameters keyword only.

   - bpo-31559(3): Remove test order dependence in
     idle_test.test_browser.

   - bpo-31459(4): 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.

   - bpo-31500(5): Default fonts now are scaled on HiDPI displays.

   - bpo-1612262(6): IDLE module browser now shows nested classes and
     functions.  Original patches for code and tests by Guilherme Polo
     and Cheryl Sabella, respectively.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31460

   (2) https://bugs.python.org/issue31649

   (3) https://bugs.python.org/issue31559

   (4) https://bugs.python.org/issue31459

   (5) https://bugs.python.org/issue31500

   (6) https://bugs.python.org/issue1612262


File: python.info,  Node: C API<26>,  Prev: IDLE<31>,  Up: Python 3 7 0 alpha 2

1.19.41.6 C API
...............

   - bpo-28280(1): Make ‘PyMapping_Keys()’, ‘PyMapping_Values()’ and
     ‘PyMapping_Items()’ always return a *note list: 1f8. (rather than a
     *note list: 1f8. or a *note tuple: 1a2.).  Patch by Oren Milman.

   - bpo-31532(2): Fix memory corruption due to allocator mix in
     getpath.c between Py_GetPath() and Py_SetPath()

   - bpo-25658(3): Implement PEP 539(4) 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28280

   (2) https://bugs.python.org/issue31532

   (3) https://bugs.python.org/issue25658

   (4) https://www.python.org/dev/peps/pep-0539


File: python.info,  Node: Python 3 7 0 alpha 1,  Next: Python 3 6 6 正式版,  Prev: Python 3 7 0 alpha 2,  Up: Changelog（更動日誌）

1.19.42 Python 3.7.0 alpha 1
----------------------------

`发布日期: 2017-09-19'

* Menu:

* 安全性: 安全性<21>.
* 核心与内置函数: 核心与内置函数<38>.
* 库: 库<41>.
* 文档: 文档<35>.
* 测试: 测试<32>.
* 构建: 构建<32>.
* Windows: Windows<32>.
* IDLE: IDLE<32>.
* 工具/示例: 工具/示例<17>.
* C API: C API<27>.


File: python.info,  Node: 安全性<21>,  Next: 核心与内置函数<38>,  Up: Python 3 7 0 alpha 1

1.19.42.1 安全性
................

   - bpo-29781(1): SSLObject.version() now correctly returns None when
     handshake over BIO has not been performed yet.

   - bpo-29505(2): Add fuzz tests for float(str), int(str),
     unicode(str); for oss-fuzz.

   - bpo-30947(3): Upgrade libexpat embedded copy from version 2.2.1 to
     2.2.3 to get security fixes.

   - bpo-30730(4): Prevent environment variables injection in subprocess
     on Windows.  Prevent passing other environment variables and
     command arguments.

   - bpo-30694(5): 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
     ‘XML_SetHashSalt()’.

   - bpo-30500(6): Fix urllib.parse.splithost() to correctly parse
     fragments.  For example, ‘splithost('//127.0.0.1#@evil.com/')’ now
     correctly returns the ‘127.0.0.1’ host, instead of treating
     ‘@evil.com’ as the host in an authentication (‘login@host’).

   - bpo-29591(7): Update expat copy from 2.1.1 to 2.2.0 to get fixes of
     CVE-2016-0718 and CVE-2016-4472.  See
     ‘https://sourceforge.net/p/expat/bugs/537/’ for more information.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29781

   (2) https://bugs.python.org/issue29505

   (3) https://bugs.python.org/issue30947

   (4) https://bugs.python.org/issue30730

   (5) https://bugs.python.org/issue30694

   (6) https://bugs.python.org/issue30500

   (7) https://bugs.python.org/issue29591


File: python.info,  Node: 核心与内置函数<38>,  Next: 库<41>,  Prev: 安全性<21>,  Up: Python 3 7 0 alpha 1

1.19.42.2 核心与内置函数
........................

   - bpo-31490(1): Fix an assertion failure in *note ctypes: 2a. class
     definition, in case the class has an attribute whose name is
     specified in ‘_anonymous_’ but not in ‘_fields_’.  Patch by Oren
     Milman.

   - bpo-31471(2): Fix an assertion failure in *note subprocess.Popen():
     3db. on Windows, in case the env argument has a bad keys() method.
     Patch by Oren Milman.

   - bpo-31418(3): Fix an assertion failure in ‘PyErr_WriteUnraisable()’
     in case of an exception with a bad ‘__module__’ attribute.  Patch
     by Oren Milman.

   - bpo-31416(4): Fix assertion failures in case of a bad
     warnings.filters or warnings.defaultaction.  Patch by Oren Milman.

   - bpo-28411(5): 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.

   - bpo-28411(6): Switch to the abstract API when dealing with
     ‘PyInterpreterState.modules’.  This allows later support for all
     dict subclasses and other Mapping implementations.  Also add a
     ‘PyImport_GetModule()’ function to reduce a bunch of duplicated
     code.

   - bpo-31411(7): Raise a TypeError instead of SystemError in case
     warnings.onceregistry is not a dictionary.  Patch by Oren Milman.

   - bpo-31344(8): 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: ‘f_trace_lines’
     (‘True’ by default) to turn off per-line trace events; and
     ‘f_trace_opcodes’ (‘False’ by default) to turn on per-opcode trace
     events.

   - bpo-31373(9): Fix several possible instances of undefined behavior
     due to floating-point demotions.

   - bpo-30465(10): Location information (‘lineno’ and ‘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).

   - bpo-30860(11): Consolidate CPython’s global runtime state under a
     single struct.  This improves discoverability of the runtime state.

   - bpo-31347(12): Fix possible undefined behavior in
     _PyObject_FastCall_Prepend.

   - bpo-31343(13): Include sys/sysmacros.h for major(), minor(), and
     makedev().  GNU C libray plans to remove the functions from
     sys/types.h.

   - bpo-31291(14): Fix an assertion failure in *note
     zipimport.zipimporter.get_data: 11ef. on Windows, when the return
     value of ‘pathname.replace('/','\\')’ isn’t a string.  Patch by
     Oren Milman.

   - bpo-31271(15): Fix an assertion failure in the write() method of
     *note io.TextIOWrapper: 6ea, when the encoder doesn’t return a
     bytes object.  Patch by Oren Milman.

   - bpo-31243(16): Fix a crash in some methods of *note
     io.TextIOWrapper: 6ea, when the decoder’s state is invalid.  Patch
     by Oren Milman.

   - bpo-30721(17): ‘print’ now shows correct usage hint for using
     Python 2 redirection syntax.  Patch by Sanyam Khurana.

   - bpo-31070(18): Fix a race condition in importlib
     _get_module_lock().

   - bpo-30747(19): Add a non-dummy implementation of _Py_atomic_store
     and _Py_atomic_load on MSVC.

   - bpo-31095(20): Fix potential crash during GC caused by ‘tp_dealloc’
     which doesn’t call ‘PyObject_GC_UnTrack()’.

   - bpo-31071(21): Avoid masking original TypeError in call with *
     unpacking when other arguments are passed.

   - bpo-30978(22): str.format_map() now passes key lookup exceptions
     through.  Previously any exception was replaced with a KeyError
     exception.

   - bpo-30808(23): Use _Py_atomic API for concurrency-sensitive signal
     state.

   - bpo-30876(24): 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.

   - bpo-30703(25): 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).

   - bpo-30765(26): Avoid blocking in pthread_mutex_lock() when
     PyThread_acquire_lock() is asked not to block.

   - bpo-31161(27): Make sure the ’Missing parentheses’ syntax error
     message is only applied to SyntaxError, not to subclasses.  Patch
     by Martijn Pieters.

   - bpo-30814(28): Fixed a race condition when import a submodule from
     a package.

   - bpo-30736(29): The internal unicodedata database has been upgraded
     to Unicode 10.0.

   - bpo-30604(30): Move co_extra_freefuncs from per-thread to
     per-interpreter to avoid crashes.

   - bpo-30597(31): ‘print’ now shows expected input in custom error
     message when used as a Python 2 statement.  Patch by Sanyam
     Khurana.

   - bpo-30682(32): Removed a too-strict assertion that failed for
     certain f-strings, such as eval("f’\n’") and eval("f’\r’").

   - bpo-30501(33): 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.

   - bpo-28180(34): Implement PEP 538(35) (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.

   - bpo-30486(36): Allows setting cell values for __closure__.  Patch
     by Lisa Roach.

   - bpo-30537(37): itertools.islice now accepts integer-like objects
     (having an __index__ method) as start, stop, and slice arguments

   - bpo-25324(38): Tokens needed for parsing in Python moved to C.
     ‘COMMENT’, ‘NL’ and ‘ENCODING’.  This way the tokens and tok_names
     in the token module don’t get changed when you import the tokenize
     module.

   - bpo-29104(39): Fixed parsing backslashes in f-strings.

   - bpo-27945(40): Fixed various segfaults with dict when input
     collections are mutated during searching, inserting or comparing.
     Based on patches by Duane Griffin and Tim Mitchell.

   - bpo-25794(41): Fixed type.__setattr__() and type.__delattr__() for
     non-interned attribute names.  Based on patch by Eryk Sun.

   - bpo-30039(42): 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.

   - bpo-28974(43): ‘object.__format__(x, '')’ is now equivalent to
     ‘str(x)’ rather than ‘format(str(self), '')’.

   - bpo-30024(44): Circular imports involving absolute imports with
     binding a submodule to a name are now supported.

   - bpo-12414(45): 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.

   - bpo-29839(46): len() now raises ValueError rather than
     OverflowError if __len__() returned a large negative integer.

   - bpo-11913(47): README.rst is now included in the list of distutils
     standard READMEs and therefore included in source distributions.

   - bpo-29914(48): Fixed default implementations of __reduce__ and
     __reduce_ex__().  object.__reduce__() no longer takes arguments,
     object.__reduce_ex__() now requires one argument.

   - bpo-29949(49): Fix memory usage regression of set and frozenset
     object.

   - bpo-29935(50): Fixed error messages in the index() method of tuple,
     list and deque when pass indices of wrong type.

   - bpo-29816(51): 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.

   - bpo-24821(52): Fixed the slowing down to 25 times in the searching
     of some unlucky Unicode characters.

   - bpo-29102(53): Add a unique ID to PyInterpreterState.  This makes
     it easier to identify each subinterpreter.

   - bpo-29894(54): 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.

   - bpo-29859(55): Show correct error messages when any of the
     pthread_* calls in thread_pthread.h fails.

   - bpo-29849(56): Fix a memory leak when an ImportError is raised
     during from import.

   - bpo-28856(57): Fix an oversight that %b format for bytes should
     support objects follow the buffer protocol.

   - bpo-29723(58): The ‘sys.path[0]’ initialization change for
     bpo-29139(59) caused a regression by revealing an inconsistency in
     how sys.path is initialized when executing ‘__main__’ from a
     zipfile, directory, or other import location.  The interpreter now
     consistently avoids ever adding the import location’s parent
     directory to ‘sys.path’, and ensures no other ‘sys.path’ entries
     are inadvertently modified when inserting the import location named
     on the command line.

   - bpo-29568(60): Escaped percent "%%" in the format string for
     classic string formatting no longer allows any characters between
     two percents.

   - bpo-29714(61): Fix a regression that bytes format may fail when
     containing zero bytes inside.

   - bpo-29695(62): bool(), float(), list() and tuple() no longer take
     keyword arguments.  The first argument of int() can now be passes
     only as positional argument.

   - bpo-28893(63): Set correct __cause__ for errors about invalid
     awaitables returned from __aiter__ and __anext__.

   - bpo-28876(64): ‘bool(range)’ works even if ‘len(range)’ raises
     *note OverflowError: a41.

   - bpo-29683(65): Fixes to memory allocation in _PyCode_SetExtra.
     Patch by Brian Coleman.

   - bpo-29684(66): 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.

   - bpo-28598(67): Support __rmod__ for subclasses of str being called
     before str.__mod__.  Patch by Martijn Pieters.

   - bpo-29607(68): Fix stack_effect computation for CALL_FUNCTION_EX.
     Patch by Matthieu Dartiailh.

   - bpo-29602(69): Fix incorrect handling of signed zeros in complex
     constructor for complex subclasses and for inputs having a
     __complex__ method.  Patch by Serhiy Storchaka.

   - bpo-29347(70): Fixed possibly dereferencing undefined pointers when
     creating weakref objects.

   - bpo-29463(71): Add ‘docstring’ field to Module, ClassDef,
     FunctionDef, and AsyncFunctionDef ast nodes.  docstring is not
     first stmt in their body anymore.  It affects ‘co_firstlineno’ and
     ‘co_lnotab’ of code object for module and class.  (Reverted in
     bpo-32911(72).)

   - bpo-29438(73): Fixed use-after-free problem in key sharing dict.

   - bpo-29546(74): Set the ’path’ and ’name’ attribute on ImportError
     for ‘from ... import ...’.

   - bpo-29546(75): Improve from-import error message with location

   - bpo-29478(76): If max_line_length=None is specified while using the
     Compat32 policy, it is no longer ignored.  Patch by Mircea Cosbuc.

   - bpo-29319(77): Prevent RunMainFromImporter overwriting sys.path[0].

   - bpo-29337(78): Fixed possible BytesWarning when compare the code
     objects.  Warnings could be emitted at compile time.

   - bpo-29327(79): Fixed a crash when pass the iterable keyword
     argument to sorted().

   - bpo-29034(80): Fix memory leak and use-after-free in os module
     (path_converter).

   - bpo-29159(81): Fix regression in bytes(x) when x.__index__() raises
     Exception.

   - bpo-29049(82): Call _PyObject_GC_TRACK() lazily when calling Python
     function.  Calling function is up to 5% faster.

   - bpo-28927(83): bytes.fromhex() and bytearray.fromhex() now ignore
     all ASCII whitespace, not only spaces.  Patch by Robert Xiao.

   - bpo-28932(84): Do not include <sys/random.h> if it does not exist.

   - bpo-25677(85): Correct the positioning of the syntax error caret
     for indented blocks.  Based on patch by Michael Layzell.

   - bpo-29000(86): Fixed bytes formatting of octals with zero padding
     in alternate form.

   - bpo-18896(87): Python function can now have more than 255
     parameters.  collections.namedtuple() now supports tuples with more
     than 255 elements.

   - bpo-28596(88): The preferred encoding is UTF-8 on Android.  Patch
     written by Chi Hsuan Yen.

   - bpo-22257(89): Clean up interpreter startup (see PEP 432(90)).

   - bpo-26919(91): 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.

   - bpo-28991(92): functools.lru_cache() was susceptible to an obscure
     reentrancy bug triggerable by a monkey-patched len() function.

   - bpo-28147(93): Fix a memory leak in split-table dictionaries:
     setattr() must not convert combined table into split table.  Patch
     written by INADA Naoki.

   - bpo-28739(94): f-string expressions are no longer accepted as
     docstrings and by ast.literal_eval() even if they do not include
     expressions.

   - bpo-28512(95): Fixed setting the offset attribute of SyntaxError by
     PyErr_SyntaxLocationEx() and PyErr_SyntaxLocationObject().

   - bpo-28918(96): Fix the cross compilation of xxlimited when Python
     has been built with Py_DEBUG defined.

   - bpo-23722(97): Rather than silently producing a class that doesn’t
     support zero-argument ‘super()’ in methods, failing to pass the new
     ‘__classcell__’ namespace entry up to ‘type.__new__’ now results in
     a ‘DeprecationWarning’ and a class that supports zero-argument
     ‘super()’.

   - bpo-28797(98): 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.

   - bpo-28799(99): Remove the ‘PyEval_GetCallStats()’ function and
     deprecate the untested and undocumented ‘sys.callstats()’ function.
     Remove the ‘CALL_PROFILE’ special build: use the *note
     sys.setprofile(): eff. function, *note cProfile: 27. or *note
     profile: d3. to profile function calls.

   - bpo-12844(100): More than 255 arguments can now be passed to a
     function.

   - bpo-28782(101): Fix a bug in the implementation ‘yield from’ when
     checking if the next instruction is YIELD_FROM. Regression
     introduced by WORDCODE (bpo-26647(102)).

   - bpo-28774(103): 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).

   - bpo-28731(104): Optimize _PyDict_NewPresized() to create correct
     size dict.  Improve speed of dict literal with constant keys up to
     30%.

   - bpo-28532(105): Show sys.version when -V option is supplied twice.

   - bpo-27100(106): 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.

   - bpo-28746(107): Fix the set_inheritable() file descriptor method on
     platforms that do not have the ioctl FIOCLEX and FIONCLEX commands.

   - bpo-26920(108): Fix not getting the locale’s charset upon
     initializing the interpreter, on platforms that do not have
     langinfo.

   - bpo-28648(109): Fixed crash in Py_DecodeLocale() in debug build on
     Mac OS X when decode astral characters.  Patch by Xiang Zhang.

   - bpo-28665(110): Improve speed of the STORE_DEREF opcode by 40%.

   - bpo-19398(111): Extra slash no longer added to sys.path components
     in case of empty compile-time PYTHONPATH components.

   - bpo-28621(112): Sped up converting int to float by reusing faster
     bits counting implementation.  Patch by Adrian Wielgosik.

   - bpo-28580(113): Optimize iterating split table values.  Patch by
     Xiang Zhang.

   - bpo-28583(114): PyDict_SetDefault didn’t combine split table when
     needed.  Patch by Xiang Zhang.

   - bpo-28128(115): 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.

   - bpo-28509(116): dict.update() no longer allocate unnecessary large
     memory.

   - bpo-28426(117): Fixed potential crash in
     PyUnicode_AsDecodedObject() in debug build.

   - bpo-28517(118): Fixed of-by-one error in the peephole optimizer
     that caused keeping unreachable code.

   - bpo-28214(119): Improved exception reporting for problematic
     __set_name__ attributes.

   - bpo-23782(120): Fixed possible memory leak in _PyTraceback_Add()
     and exception loss in PyTraceBack_Here().

   - bpo-28183(121): Optimize and cleanup dict iteration.

   - bpo-26081(122): Added C implementation of asyncio.Future.  Original
     patch by Yury Selivanov.

   - bpo-28379(123): Added sanity checks and tests for
     PyUnicode_CopyCharacters().  Patch by Xiang Zhang.

   - bpo-28376(124): The type of long range iterator is now registered
     as Iterator.  Patch by Oren Milman.

   - bpo-28376(125): 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.

   - bpo-26906(126): Resolving special methods of uninitialized type now
     causes implicit initialization of the type instead of a fail.

   - bpo-18287(127): PyType_Ready() now checks that tp_name is not NULL.
     Original patch by Niklas Koep.

   - bpo-24098(128): Fixed possible crash when AST is changed in process
     of compiling it.

   - bpo-28201(129): Dict reduces possibility of 2nd conflict in hash
     table when hashes have same lower bits.

   - bpo-28350(130): String constants with null character no longer
     interned.

   - bpo-26617(131): Fix crash when GC runs during weakref callbacks.

   - bpo-27942(132): String constants now interned recursively in tuples
     and frozensets.

   - bpo-28289(133): ImportError.__init__ now resets not specified
     attributes.

   - bpo-21578(134): Fixed misleading error message when ImportError
     called with invalid keyword args.

   - bpo-28203(135): Fix incorrect type in complex(1.0, {2:3}) error
     message.  Patch by Soumya Sharma.

   - bpo-28086(136): Single var-positional argument of tuple subtype was
     passed unscathed to the C-defined function.  Now it is converted to
     exact tuple.

   - bpo-28214(137): Now __set_name__ is looked up on the class instead
     of the instance.

   - bpo-27955(138): Fallback on reading /dev/urandom device when the
     getrandom() syscall fails with EPERM, for example when blocked by
     SECCOMP.

   - bpo-28192(139): Don’t import readline in isolated mode.

   - bpo-27441(140): Remove some redundant assignments to ob_size in
     longobject.c.  Thanks Oren Milman.

   - bpo-27222(141): Clean up redundant code in long_rshift function.
     Thanks Oren Milman.

   - Upgrade internal unicode databases to Unicode version 9.0.0.

   - bpo-28131(142): Fix a regression in zipimport’s compile_source().
     zipimport should use the same optimization level as the
     interpreter.

   - bpo-28126(143): Replace Py_MEMCPY with memcpy().  Visual Studio can
     properly optimize memcpy().

   - bpo-28120(144): Fix dict.pop() for splitted dictionary when trying
     to remove a "pending key" (Not yet inserted in split-table).  Patch
     by Xiang Zhang.

   - bpo-26182(145): Raise DeprecationWarning when async and await
     keywords are used as variable/attribute/class/function name.

   - bpo-26182(146): Fix a refleak in code that raises
     DeprecationWarning.

   - bpo-28721(147): Fix asynchronous generators aclose() and athrow()
     to handle StopAsyncIteration propagation properly.

   - bpo-26110(148): Speed-up method calls: add LOAD_METHOD and
     CALL_METHOD opcodes.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31490

   (2) https://bugs.python.org/issue31471

   (3) https://bugs.python.org/issue31418

   (4) https://bugs.python.org/issue31416

   (5) https://bugs.python.org/issue28411

   (6) https://bugs.python.org/issue28411

   (7) https://bugs.python.org/issue31411

   (8) https://bugs.python.org/issue31344

   (9) https://bugs.python.org/issue31373

   (10) https://bugs.python.org/issue30465

   (11) https://bugs.python.org/issue30860

   (12) https://bugs.python.org/issue31347

   (13) https://bugs.python.org/issue31343

   (14) https://bugs.python.org/issue31291

   (15) https://bugs.python.org/issue31271

   (16) https://bugs.python.org/issue31243

   (17) https://bugs.python.org/issue30721

   (18) https://bugs.python.org/issue31070

   (19) https://bugs.python.org/issue30747

   (20) https://bugs.python.org/issue31095

   (21) https://bugs.python.org/issue31071

   (22) https://bugs.python.org/issue30978

   (23) https://bugs.python.org/issue30808

   (24) https://bugs.python.org/issue30876

   (25) https://bugs.python.org/issue30703

   (26) https://bugs.python.org/issue30765

   (27) https://bugs.python.org/issue31161

   (28) https://bugs.python.org/issue30814

   (29) https://bugs.python.org/issue30736

   (30) https://bugs.python.org/issue30604

   (31) https://bugs.python.org/issue30597

   (32) https://bugs.python.org/issue30682

   (33) https://bugs.python.org/issue30501

   (34) https://bugs.python.org/issue28180

   (35) https://www.python.org/dev/peps/pep-0538

   (36) https://bugs.python.org/issue30486

   (37) https://bugs.python.org/issue30537

   (38) https://bugs.python.org/issue25324

   (39) https://bugs.python.org/issue29104

   (40) https://bugs.python.org/issue27945

   (41) https://bugs.python.org/issue25794

   (42) https://bugs.python.org/issue30039

   (43) https://bugs.python.org/issue28974

   (44) https://bugs.python.org/issue30024

   (45) https://bugs.python.org/issue12414

   (46) https://bugs.python.org/issue29839

   (47) https://bugs.python.org/issue11913

   (48) https://bugs.python.org/issue29914

   (49) https://bugs.python.org/issue29949

   (50) https://bugs.python.org/issue29935

   (51) https://bugs.python.org/issue29816

   (52) https://bugs.python.org/issue24821

   (53) https://bugs.python.org/issue29102

   (54) https://bugs.python.org/issue29894

   (55) https://bugs.python.org/issue29859

   (56) https://bugs.python.org/issue29849

   (57) https://bugs.python.org/issue28856

   (58) https://bugs.python.org/issue29723

   (59) https://bugs.python.org/issue29139

   (60) https://bugs.python.org/issue29568

   (61) https://bugs.python.org/issue29714

   (62) https://bugs.python.org/issue29695

   (63) https://bugs.python.org/issue28893

   (64) https://bugs.python.org/issue28876

   (65) https://bugs.python.org/issue29683

   (66) https://bugs.python.org/issue29684

   (67) https://bugs.python.org/issue28598

   (68) https://bugs.python.org/issue29607

   (69) https://bugs.python.org/issue29602

   (70) https://bugs.python.org/issue29347

   (71) https://bugs.python.org/issue29463

   (72) https://bugs.python.org/issue32911

   (73) https://bugs.python.org/issue29438

   (74) https://bugs.python.org/issue29546

   (75) https://bugs.python.org/issue29546

   (76) https://bugs.python.org/issue29478

   (77) https://bugs.python.org/issue29319

   (78) https://bugs.python.org/issue29337

   (79) https://bugs.python.org/issue29327

   (80) https://bugs.python.org/issue29034

   (81) https://bugs.python.org/issue29159

   (82) https://bugs.python.org/issue29049

   (83) https://bugs.python.org/issue28927

   (84) https://bugs.python.org/issue28932

   (85) https://bugs.python.org/issue25677

   (86) https://bugs.python.org/issue29000

   (87) https://bugs.python.org/issue18896

   (88) https://bugs.python.org/issue28596

   (89) https://bugs.python.org/issue22257

   (90) https://www.python.org/dev/peps/pep-0432

   (91) https://bugs.python.org/issue26919

   (92) https://bugs.python.org/issue28991

   (93) https://bugs.python.org/issue28147

   (94) https://bugs.python.org/issue28739

   (95) https://bugs.python.org/issue28512

   (96) https://bugs.python.org/issue28918

   (97) https://bugs.python.org/issue23722

   (98) https://bugs.python.org/issue28797

   (99) https://bugs.python.org/issue28799

   (100) https://bugs.python.org/issue12844

   (101) https://bugs.python.org/issue28782

   (102) https://bugs.python.org/issue26647

   (103) https://bugs.python.org/issue28774

   (104) https://bugs.python.org/issue28731

   (105) https://bugs.python.org/issue28532

   (106) https://bugs.python.org/issue27100

   (107) https://bugs.python.org/issue28746

   (108) https://bugs.python.org/issue26920

   (109) https://bugs.python.org/issue28648

   (110) https://bugs.python.org/issue28665

   (111) https://bugs.python.org/issue19398

   (112) https://bugs.python.org/issue28621

   (113) https://bugs.python.org/issue28580

   (114) https://bugs.python.org/issue28583

   (115) https://bugs.python.org/issue28128

   (116) https://bugs.python.org/issue28509

   (117) https://bugs.python.org/issue28426

   (118) https://bugs.python.org/issue28517

   (119) https://bugs.python.org/issue28214

   (120) https://bugs.python.org/issue23782

   (121) https://bugs.python.org/issue28183

   (122) https://bugs.python.org/issue26081

   (123) https://bugs.python.org/issue28379

   (124) https://bugs.python.org/issue28376

   (125) https://bugs.python.org/issue28376

   (126) https://bugs.python.org/issue26906

   (127) https://bugs.python.org/issue18287

   (128) https://bugs.python.org/issue24098

   (129) https://bugs.python.org/issue28201

   (130) https://bugs.python.org/issue28350

   (131) https://bugs.python.org/issue26617

   (132) https://bugs.python.org/issue27942

   (133) https://bugs.python.org/issue28289

   (134) https://bugs.python.org/issue21578

   (135) https://bugs.python.org/issue28203

   (136) https://bugs.python.org/issue28086

   (137) https://bugs.python.org/issue28214

   (138) https://bugs.python.org/issue27955

   (139) https://bugs.python.org/issue28192

   (140) https://bugs.python.org/issue27441

   (141) https://bugs.python.org/issue27222

   (142) https://bugs.python.org/issue28131

   (143) https://bugs.python.org/issue28126

   (144) https://bugs.python.org/issue28120

   (145) https://bugs.python.org/issue26182

   (146) https://bugs.python.org/issue26182

   (147) https://bugs.python.org/issue28721

   (148) https://bugs.python.org/issue26110


File: python.info,  Node: 库<41>,  Next: 文档<35>,  Prev: 核心与内置函数<38>,  Up: Python 3 7 0 alpha 1

1.19.42.3 库
............

   - bpo-31499(1): xml.etree: Fix a crash when a parser is part of a
     reference cycle.

   - bpo-31482(2): ‘random.seed()’ now works with bytes in version=1

   - bpo-28556(3): typing.get_type_hints now finds the right globalns
     for classes and modules by default (when no ‘globalns’ was
     specified by the caller).

   - bpo-28556(4): Speed improvements to the ‘typing’ module.  Original
     PRs by Ivan Levkivskyi and Mitar.

   - bpo-31544(5): The C accelerator module of ElementTree ignored
     exceptions raised when looking up TreeBuilder target methods in
     XMLParser().

   - bpo-31234(6): socket.create_connection() now fixes manually a
     reference cycle: clear the variable storing the last exception on
     success.

   - bpo-31457(7): LoggerAdapter objects can now be nested.

   - bpo-31431(8): SSLContext.check_hostname now automatically sets
     SSLContext.verify_mode to ssl.CERT_REQUIRED instead of failing with
     a ValueError.

   - bpo-31233(9): socketserver.ThreadingMixIn now keeps a list of
     non-daemonic threads to wait until all these threads complete in
     server_close().

   - bpo-28638(10): Changed the implementation strategy for
     collections.namedtuple() to substantially reduce the use of exec()
     in favor of precomputed methods.  As a result, the `verbose'
     parameter and `_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.)

   - bpo-31400(11): Improves SSL error handling to avoid losing error
     numbers.

   - bpo-27629(12): Make return types of SSLContext.wrap_bio() and
     SSLContext.wrap_socket() customizable.

   - bpo-28958(13): ssl.SSLContext() now uses OpenSSL error information
     when a context cannot be instantiated.

   - bpo-28182(14): The SSL module now raises SSLCertVerificationError
     when OpenSSL fails to verify the peer’s certificate.  The exception
     contains more information about the error.

   - bpo-27340(15): 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.

   - bpo-14191(16): A new function
     ‘argparse.ArgumentParser.parse_intermixed_args’ provides the
     ability to parse command lines where there user intermixes options
     and positional arguments.

   - bpo-31178(17): Fix string concatenation bug in rare error path in
     the subprocess module

   - bpo-31350(18): Micro-optimize ‘asyncio._get_running_loop()’ to
     become up to 10% faster.

   - bpo-31170(19): expat: Update libexpat from 2.2.3 to 2.2.4.  Fix
     copying of partial characters for UTF-8 input (libexpat bug 115):
     ‘https://github.com/libexpat/libexpat/issues/115’

   - bpo-29136(20): Add TLS 1.3 cipher suites and OP_NO_TLSv1_3.

   - bpo-1198569(21): ‘string.Template’ subclasses can optionally define
     ‘braceidpattern’ if they want to specify different placeholder
     patterns inside and outside the braces.  If None (the default) it
     falls back to ‘idpattern’.

   - bpo-31326(22): 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.

   - bpo-27144(23): The ‘map()’ and ‘as_completed()’ iterators in
     ‘concurrent.futures’ now avoid keeping a reference to yielded
     objects.

   - bpo-31281(24): Fix ‘fileinput.FileInput(files, inplace=True)’ when
     ‘files’ contain ‘pathlib.Path’ objects.

   - bpo-10746(25): Fix ctypes producing wrong PEP 3118(26) type codes
     for integer types.

   - bpo-27584(27): ‘AF_VSOCK’ has been added to the socket interface
     which allows communication between virtual machines and their host.

   - bpo-22536(28): The subprocess module now sets the filename when
     FileNotFoundError is raised on POSIX systems due to the executable
     or cwd not being found.

   - bpo-29741(29): Update some methods in the _pyio module to also
     accept integer types.  Patch by Oren Milman.

   - bpo-31249(30): concurrent.futures: WorkItem.run() used by
     ThreadPoolExecutor now breaks a reference cycle between an
     exception object and the WorkItem object.

   - bpo-31247(31): xmlrpc.server now explicitly breaks reference cycles
     when using sys.exc_info() in code handling exceptions.

   - bpo-23835(32): configparser: reading defaults in the
     ‘ConfigParser()’ constructor is now using ‘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.

   - bpo-31238(33): 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.

   - bpo-5001(34): Many asserts in *note multiprocessing: b7. are now
     more informative, and some error types have been changed to more
     specific ones.

   - bpo-31109(35): Convert zipimport to use Argument Clinic.

   - bpo-30102(36): 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.

   - bpo-18966(37): Non-daemonic threads created by a
     multiprocessing.Process are now joined on child exit.

   - bpo-31183(38): *note dis: 37. now works with asynchronous generator
     and coroutine objects.  Patch by George Collins based on diagnosis
     by Luciano Ramalho.

   - bpo-5001(39): There are a number of uninformative asserts in the
     *note multiprocessing: b7. 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
     ‘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 `reported' by the function/its caller (such as
     in issue 31169).  - Patch by Allen W. Smith (drallensmith on
     github).

   - bpo-31185(40): Fixed miscellaneous errors in asyncio speedup
     module.

   - bpo-31151(41): socketserver.ForkingMixIn.server_close() now waits
     until all child processes completed to prevent leaking zombie
     processes.

   - bpo-31072(42): Add an ‘include_file’ parameter to
     ‘zipapp.create_archive()’

   - bpo-24700(43): Optimize array.array comparison.  It is now from 10x
     up to 70x faster when comparing arrays holding values of the same
     integer type.

   - bpo-31135(44): 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.

   - bpo-31107(45): Fix ‘copyreg._slotnames()’ mangled attribute
     calculation for classes whose name begins with an underscore.
     Patch by Shane Harvey.

   - bpo-31080(46): Allow *note logging.config.fileConfig: 4af. to
     accept kwargs and/or args.

   - bpo-30897(47): ‘pathlib.Path’ objects now include an ‘is_mount()’
     method (only implemented on POSIX). This is similar to
     ‘os.path.ismount(p)’.  Patch by Cooper Ry Lees.

   - bpo-31061(48): Fixed a crash when using asyncio and threads.

   - bpo-30987(49): Added support for CAN ISO-TP protocol in the socket
     module.

   - bpo-30522(50): Added a ‘setStream’ method to
     ‘logging.StreamHandler’ to allow the stream to be set after
     creation.

   - bpo-30502(51): Fix handling of long oids in ssl.  Based on patch by
     Christian Heimes.

   - bpo-5288(52): Support tzinfo objects with sub-minute offsets.

   - bpo-30919(53): 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.

   - bpo-26732(54): 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.

   - bpo-29403(55): Fix ‘unittest.mock’’s autospec to not fail on
     method-bound builtin functions.  Patch by Aaron Gallagher.

   - bpo-30961(56): Fix decrementing a borrowed reference in
     tracemalloc.

   - bpo-19896(57): Fix multiprocessing.sharedctypes to recognize
     typecodes ‘'q'’ and ‘'Q'’.

   - bpo-30946(58): Remove obsolete code in readline module for
     platforms where GNU readline is older than 2.1 or where select() is
     not available.

   - bpo-25684(59): Change ‘ttk.OptionMenu’ radiobuttons to be unique
     across instances of ‘OptionMenu’.

   - bpo-30886(60): 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.

   - bpo-29854(61): Fix segfault in readline when using readline’s
     history-size option.  Patch by Nir Soffer.

   - bpo-30794(62): Added multiprocessing.Process.kill method to
     terminate using the SIGKILL signal on Unix.

   - bpo-30319(63): socket.close() now ignores ECONNRESET error.

   - bpo-30828(64): Fix out of bounds write in
     ‘asyncio.CFuture.remove_done_callback()’.

   - bpo-30302(65): Use keywords in the ‘repr’ of ‘datetime.timedelta’.

   - bpo-30807(66): 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.

   - bpo-30441(67): Fix bug when modifying os.environ while iterating
     over it

   - bpo-29585(68): Avoid importing ‘sysconfig’ from ‘site’ to improve
     startup speed.  Python startup is about 5% faster on Linux and 30%
     faster on macOS.

   - bpo-29293(69): 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.

   - bpo-30532(70): Fix email header value parser dropping folding white
     space in certain cases.

   - bpo-30596(71): Add a ‘close()’ method to ‘multiprocessing.Process’.

   - bpo-9146(72): 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.

   - bpo-29169(73): Update zlib to 1.2.11.

   - bpo-30119(74): ftplib.FTP.putline() now throws ValueError on
     commands that contains CR or LF. Patch by Dong-hee Na.

   - bpo-30879(75): os.listdir() and os.scandir() now emit bytes names
     when called with bytes-like argument.

   - bpo-30746(76): Prohibited the ’=’ character in environment variable
     names in ‘os.putenv()’ and ‘os.spawn*()’.

   - bpo-30664(77): The description of a unittest subtest now preserves
     the order of keyword arguments of TestCase.subTest().

   - bpo-21071(78): struct.Struct.format type is now *note str: 205.
     instead of *note bytes: 172.

   - bpo-29212(79): 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".

   - bpo-29755(80): Fixed the lgettext() family of functions in the
     gettext module.  They now always return bytes.

   - bpo-30616(81): Functional API of enum allows to create empty enums.
     Patched by Dong-hee Na

   - bpo-30038(82): Fix race condition between signal delivery and
     wakeup file descriptor.  Patch by Nathaniel Smith.

   - bpo-23894(83): lib2to3 now recognizes ‘rb'...'’ and ‘f'...'’
     strings.

   - bpo-24744(84): pkgutil.walk_packages function now raises ValueError
     if `path' is a string.  Patch by Sanyam Khurana.

   - bpo-24484(85): Avoid race condition in multiprocessing cleanup.

   - bpo-30589(86): 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.

   - bpo-28994(87): The traceback no longer displayed for SystemExit
     raised in a callback registered by atexit.

   - bpo-30508(88): Don’t log exceptions if Task/Future "cancel()"
     method was called.

   - bpo-30645(89): Fix path calculation in ‘imp.load_package()’, fixing
     it for cases when a package is only shipped with bytecodes.  Patch
     by Alexandru Ardelean.

   - bpo-11822(90): The dis.dis() function now is able to disassemble
     nested code objects.

   - bpo-30624(91): selectors does not take KeyboardInterrupt and
     SystemExit into account, leaving a fd in a bad state in case of
     error.  Patch by Giampaolo Rodola’.

   - bpo-30595(92): 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.

   - bpo-28556(93): Updates to typing module: Add generic
     AsyncContextManager, add support for ContextManager on all
     versions.  Original PRs by Jelle Zijlstra and Ivan Levkivskyi

   - bpo-30605(94): re.compile() no longer raises a BytesWarning when
     compiling a bytes instance with misplaced inline modifier.  Patch
     by Roy Williams.

   - bpo-29870(95): Fix ssl sockets leaks when connection is aborted in
     asyncio/ssl implementation.  Patch by Michaël Sghaïer.

   - bpo-29743(96): Closing transport during handshake process leaks
     open socket.  Patch by Nikolay Kim

   - bpo-27585(97): Fix waiter cancellation in asyncio.Lock.  Patch by
     Mathieu Sornay.

   - bpo-30014(98): modify() method of poll(), epoll() and devpoll()
     based classes of selectors module is around 10% faster.  Patch by
     Giampaolo Rodola’.

   - bpo-30418(99): On Windows, subprocess.Popen.communicate() now also
     ignore EINVAL on stdin.write() if the child process is still
     running but closed the pipe.

   - bpo-30463(100): Addded empty __slots__ to abc.ABC. This allows
     subclassers to deny __dict__ and __weakref__ creation.  Patch by
     Aaron Hall.

   - bpo-30520(101): Loggers are now pickleable.

   - bpo-30557(102): faulthandler now correctly filters and displays
     exception codes on Windows

   - bpo-30526(103): Add TextIOWrapper.reconfigure() and a
     TextIOWrapper.write_through attribute.

   - bpo-30245(104): Fix possible overflow when organize
     struct.pack_into error message.  Patch by Yuan Liu.

   - bpo-30378(105): Fix the problem that logging.handlers.SysLogHandler
     cannot handle IPv6 addresses.

   - bpo-16500(106): Allow registering at-fork handlers.

   - bpo-30470(107): Deprecate invalid ctypes call protection on
     Windows.  Patch by Mariatta Wijaya.

   - bpo-30414(108): multiprocessing.Queue._feed background running
     thread do not break from main loop on exception.

   - bpo-30003(109): Fix handling escape characters in HZ codec.  Based
     on patch by Ma Lin.

   - bpo-30149(110): inspect.signature() now supports callables with
     variable-argument parameters wrapped with partialmethod.  Patch by
     Dong-hee Na.

   - bpo-30436(111): importlib.find_spec() raises ModuleNotFoundError
     instead of AttributeError if the specified parent module is not a
     package (i.e.  lacks a __path__ attribute).

   - bpo-30301(112): Fix AttributeError when using SimpleQueue.empty()
     under `spawn' and `forkserver' start methods.

   - bpo-30375(113): 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.

   - bpo-30329(114): 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.

   - bpo-29196(115): 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.

   - bpo-9850(116): The ‘macpath’ is now deprecated and will be removed
     in Python 3.8.

   - bpo-30299(117): Compiling regular expression in debug mode on
     CPython now displays the compiled bytecode in human readable form.

   - bpo-30048(118): Fixed ‘Task.cancel()’ can be ignored when the task
     is running coroutine and the coroutine returned without any more
     ‘await’.

   - bpo-30266(119): contextlib.AbstractContextManager now supports
     anti-registration by setting __enter__ = None or __exit__ = None,
     following the pattern introduced in bpo-25958(120).  Patch by Jelle
     Zijlstra.

   - bpo-30340(121): Enhanced regular expressions optimization.  This
     increased the performance of matching some patterns up to 25 times.

   - bpo-30298(122): Weaken the condition of deprecation warnings for
     inline modifiers.  Now allowed several subsequential inline
     modifiers at the start of the pattern (e.g.  ‘'(?i)(?s)...'’).  In
     verbose mode whitespaces and comments now are allowed before and
     between inline modifiers (e.g.  ‘'(?x) (?i) (?s)...'’).

   - bpo-30285(123): Optimized case-insensitive matching and searching
     of regular expressions.

   - bpo-29990(124): Fix range checking in GB18030 decoder.  Original
     patch by Ma Lin.

   - bpo-29979(125): 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.

   - bpo-30243(126): 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.

   - bpo-30215(127): 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.

   - bpo-30185(128): Avoid KeyboardInterrupt tracebacks in forkserver
     helper process when Ctrl-C is received.

   - bpo-30103(129): binascii.b2a_uu() and uu.encode() now support using
     ‘'`'’ as zero instead of space.

   - bpo-28556(130): Various updates to typing module: add
     typing.NoReturn type, use WrapperDescriptorType, minor bug-fixes.
     Original PRs by Jim Fasarakis-Hilliard and Ivan Levkivskyi.

   - bpo-30205(131): Fix getsockname() for unbound AF_UNIX sockets on
     Linux.

   - bpo-30228(132): 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).

   - bpo-30190(133): 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’)

   - bpo-30101(134): Add support for curses.A_ITALIC.

   - bpo-29822(135): inspect.isabstract() now works during
     __init_subclass__.  Patch by Nate Soares.

   - bpo-29960(136): Preserve generator state when
     _random.Random.setstate() raises an exception.  Patch by Bryan
     Olson.

   - bpo-30070(137): Fixed leaks and crashes in errors handling in the
     parser module.

   - bpo-22352(138): Column widths in the output of dis.dis() are now
     adjusted for large line numbers and instruction offsets.

   - bpo-30061(139): 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().

   - bpo-30218(140): Fix PathLike support for shutil.unpack_archive.
     Patch by Jelle Zijlstra.

   - bpo-10076(141): Compiled regular expression and match objects in
     the re module now support copy.copy() and copy.deepcopy() (they are
     considered atomic).

   - bpo-30068(142): _io._IOBase.readlines will check if it’s closed
     first when hint is present.

   - bpo-29694(143): Fixed race condition in pathlib mkdir with flags
     parents=True.  Patch by Armin Rigo.

   - bpo-29692(144): Fixed arbitrary unchaining of RuntimeError
     exceptions in contextlib.contextmanager.  Patch by Siddharth
     Velankar.

   - bpo-26187(145): 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(146).  Patch by
     Aviv Palivoda.

   - bpo-30017(147): Allowed calling the close() method of the zip entry
     writer object multiple times.  Writing to a closed writer now
     always produces a ValueError.

   - bpo-29998(148): Pickling and copying ImportError now preserves name
     and path attributes.

   - bpo-29995(149): re.escape() now escapes only regex special
     characters.

   - bpo-29962(150): Add math.remainder operation, implementing
     remainder as specified in IEEE 754.

   - bpo-29649(151): Improve struct.pack_into() exception messages for
     problems with the buffer size and offset.  Patch by Andrew Nester.

   - bpo-29654(152): Support If-Modified-Since HTTP header (browser
     cache).  Patch by Pierre Quentel.

   - bpo-29931(153): Fixed comparison check for ipaddress.ip_interface
     objects.  Patch by Sanjay Sundaresan.

   - bpo-29953(154): Fixed memory leaks in the replace() method of
     datetime and time objects when pass out of bound fold argument.

   - bpo-29942(155): Fix a crash in itertools.chain.from_iterable when
     encountering long runs of empty iterables.

   - bpo-10030(156): Sped up reading encrypted ZIP files by 2 times.

   - bpo-29204(157): 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.

   - bpo-27863(158): Fixed multiple crashes in ElementTree caused by
     race conditions and wrong types.

   - bpo-25996(159): Added support of file descriptors in os.scandir()
     on Unix.  os.fwalk() is sped up by 2 times by using os.scandir().

   - bpo-28699(160): 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.

   - bpo-23890(161): unittest.TestCase.assertRaises() now manually
     breaks a reference cycle to not keep objects alive longer than
     expected.

   - bpo-29901(162): The zipapp module now supports general path-like
     objects, not just pathlib.Path.

   - bpo-25803(163): Avoid incorrect errors raised by
     Path.mkdir(exist_ok=True) when the OS gives priority to errors such
     as EACCES over EEXIST.

   - bpo-29861(164): Release references to tasks, their arguments and
     their results as soon as they are finished in multiprocessing.Pool.

   - bpo-19930(165): The mode argument of os.makedirs() no longer
     affects the file permission bits of newly-created
     intermediate-level directories.

   - bpo-29884(166): faulthandler: Restore the old sigaltstack during
     teardown.  Patch by Christophe Zeitouny.

   - bpo-25455(167): Fixed crashes in repr of recursive buffered
     file-like objects.

   - bpo-29800(168): Fix crashes in partial.__repr__ if the keys of
     partial.keywords are not strings.  Patch by Michael Seifert.

   - bpo-8256(169): Fixed possible failing or crashing input() if
     attributes "encoding" or "errors" of sys.stdin or sys.stdout are
     not set or are not strings.

   - bpo-28692(170): Using non-integer value for selecting a plural form
     in gettext is now deprecated.

   - bpo-26121(171): Use C library implementation for math functions
     erf() and erfc().

   - bpo-29619(172): os.stat() and os.DirEntry.inode() now convert inode
     (st_ino) using unsigned integers.

   - bpo-28298(173): Fix a bug that prevented array ’Q’, ’L’ and ’I’
     from accepting big intables (objects that have __int__) as
     elements.

   - bpo-29645(174): Speed up importing the webbrowser module.
     webbrowser.register() is now thread-safe.

   - bpo-28231(175): The zipfile module now accepts path-like objects
     for external paths.

   - bpo-26915(176): index() and count() methods of
     collections.abc.Sequence now check identity before checking
     equality when do comparisons.

   - bpo-28682(177): Added support for bytes paths in os.fwalk().

   - bpo-29728(178): Add new ‘socket.TCP_NOTSENT_LOWAT’ (Linux 3.12)
     constant.  Patch by Nathaniel J. Smith.

   - bpo-29623(179): Allow use of path-like object as a single argument
     in ConfigParser.read().  Patch by David Ellis.

   - bpo-9303(180): Migrate sqlite3 module to _v2 API. Patch by Aviv
     Palivoda.

   - bpo-28963(181): Fix out of bound iteration in
     asyncio.Future.remove_done_callback implemented in C.

   - bpo-29704(182): asyncio.subprocess.SubprocessStreamProtocol no
     longer closes before all pipes are closed.

   - bpo-29271(183): Fix Task.current_task and Task.all_tasks
     implemented in C to accept None argument as their pure Python
     implementation.

   - bpo-29703(184): Fix asyncio to support instantiation of new event
     loops in child processes.

   - bpo-29615(185): SimpleXMLRPCDispatcher no longer chains KeyError
     (or any other exception) to exception(s) raised in the dispatched
     methods.  Patch by Petr Motejlek.

   - bpo-7769(186): Method register_function() of
     xmlrpc.server.SimpleXMLRPCDispatcher and its subclasses can now be
     used as a decorator.

   - bpo-29376(187): Fix assertion error in
     threading._DummyThread.is_alive().

   - bpo-28624(188): Add a test that checks that cwd parameter of
     Popen() accepts PathLike objects.  Patch by Sayan Chowdhury.

   - bpo-28518(189): Start a transaction implicitly before a DML
     statement.  Patch by Aviv Palivoda.

   - bpo-29742(190): get_extra_info() raises exception if get called on
     closed ssl transport.  Patch by Nikolay Kim.

   - bpo-16285(191): 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.

   - bpo-29532(192): Altering a kwarg dictionary passed to
     functools.partial() no longer affects a partial object after
     creation.

   - bpo-29110(193): 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.

   - bpo-22807(194): 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.

   - bpo-29576(195): Improve some deprecations in importlib.  Some
     deprecated methods now emit DeprecationWarnings and have better
     descriptive messages.

   - bpo-29534(196): Fixed different behaviour of Decimal.from_float()
     for _decimal and _pydecimal.  Thanks Andrew Nester.

   - bpo-10379(197): locale.format_string now supports the ’monetary’
     keyword argument, and locale.format is deprecated.

   - bpo-29851(198): importlib.reload() now raises ModuleNotFoundError
     if the module lacks a spec.

   - bpo-28556(199): 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.

   - bpo-29100(200): Fix datetime.fromtimestamp() regression introduced
     in Python 3.6.0: check minimum and maximum years.

   - bpo-29416(201): Prevent infinite loop in pathlib.Path.mkdir

   - bpo-29444(202): Fixed out-of-bounds buffer access in the group()
     method of the match object.  Based on patch by WGH.

   - bpo-29377(203): Add WrapperDescriptorType, MethodWrapperType, and
     MethodDescriptorType built-in types to types module.  Original
     patch by Manuel Krebber.

   - bpo-29218(204): Unused install_misc command is now removed.  It has
     been documented as unused since 2000.  Patch by Eric N. Vander
     Weele.

   - bpo-29368(205): 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.

   - bpo-29338(206): The help of a builtin or extension class now
     includes the constructor signature if __text_signature__ is
     provided for the class.

   - bpo-29335(207): Fix subprocess.Popen.wait() when the child process
     has exited to a stopped instead of terminated state (ex: when under
     ptrace).

   - bpo-29290(208): Fix a regression in argparse that help messages
     would wrap at non-breaking spaces.

   - bpo-28735(209): Fixed the comparison of mock.MagickMock with
     mock.ANY.

   - bpo-29197(210): Removed deprecated function ntpath.splitunc().

   - bpo-29210(211): Removed support of deprecated argument "exclude" in
     tarfile.TarFile.add().

   - bpo-29219(212): Fixed infinite recursion in the repr of
     uninitialized ctypes.CDLL instances.

   - bpo-29192(213): Removed deprecated features in the http.cookies
     module.

   - bpo-29193(214): A format string argument for
     string.Formatter.format() is now positional-only.

   - bpo-29195(215): Removed support of deprecated undocumented keyword
     arguments in methods of regular expression objects.

   - bpo-28969(216): 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.

   - bpo-20804(217): The unittest.mock.sentinel attributes now preserve
     their identity when they are copied or pickled.

   - bpo-29142(218): 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.

   - bpo-28961(219): Fix unittest.mock._Call helper: don’t ignore the
     name parameter anymore.  Patch written by Jiajun Huang.

   - bpo-15812(220): inspect.getframeinfo() now correctly shows the
     first line of a context.  Patch by Sam Breese.

   - bpo-28985(221): Update authorizer constants in sqlite3 module.
     Patch by Dingyuan Wang.

   - bpo-29079(222): Prevent infinite loop in pathlib.resolve() on
     Windows

   - bpo-13051(223): Fixed recursion errors in large or resized
     curses.textpad.Textbox.  Based on patch by Tycho Andersen.

   - bpo-9770(224): curses.ascii predicates now work correctly with
     negative integers.

   - bpo-28427(225): old keys should not remove new values from
     WeakValueDictionary when collecting from another thread.

   - bpo-28923(226): Remove editor artifacts from Tix.py.

   - bpo-28871(227): Fixed a crash when deallocate deep ElementTree.

   - bpo-19542(228): Fix bugs in WeakValueDictionary.setdefault() and
     WeakValueDictionary.pop() when a GC collection happens in another
     thread.

   - bpo-20191(229): Fixed a crash in resource.prlimit() when passing a
     sequence that doesn’t own its elements as limits.

   - bpo-16255(230): subprocess.Popen uses /system/bin/sh on Android as
     the shell, instead of /bin/sh.

   - bpo-28779(231): multiprocessing.set_forkserver_preload() would
     crash the forkserver process if a preloaded module instantiated
     some multiprocessing objects such as locks.

   - bpo-26937(232): 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.

   - bpo-28847(233): 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).

   - bpo-27030(234): Unknown escapes consisting of ‘'\'’ and an ASCII
     letter in re.sub() replacement templates regular expressions now
     are errors.

   - bpo-28835(235): Fix a regression introduced in
     warnings.catch_warnings(): call warnings.showwarning() if it was
     overridden inside the context manager.

   - bpo-27172(236): To assist with upgrades from 2.7, the previously
     documented deprecation of ‘inspect.getfullargspec()’ has been
     reversed.  This decision may be revisited again after the Python
     2.7 branch is no longer officially supported.

   - bpo-28740(237): Add sys.getandroidapilevel(): return the build time
     API version of Android as an integer.  Function only available on
     Android.

   - bpo-26273(238): Add new ‘socket.TCP_CONGESTION’ (Linux 2.6.13) and
     ‘socket.TCP_USER_TIMEOUT’ (Linux 2.6.37) constants.  Patch written
     by Omar Sandoval.

   - bpo-28752(239): Restored the __reduce__() methods of datetime
     objects.

   - bpo-28727(240): 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(241): don’t
     duplicate warning filters when the warnings module is reloaded
     (thing usually only done in unit tests).

   - bpo-20572(242): Remove the subprocess.Popen.wait endtime parameter.
     It was deprecated in 3.4 and undocumented prior to that.

   - bpo-25659(243): In ctypes, prevent a crash calling the
     from_buffer() and from_buffer_copy() methods on abstract classes
     like Array.

   - bpo-28548(244): In the "http.server" module, parse the protocol
     version if possible, to avoid using HTTP 0.9 in some error
     responses.

   - bpo-19717(245): Makes Path.resolve() succeed on paths that do not
     exist.  Patch by Vajrasky Kok

   - bpo-28563(246): 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.

   - bpo-28387(247): Fixed possible crash in _io.TextIOWrapper
     deallocator when the garbage collector is invoked in other thread.
     Based on patch by Sebastian Cufre.

   - bpo-27517(248): LZMA compressor and decompressor no longer raise
     exceptions if given empty data twice.  Patch by Benjamin Fogle.

   - bpo-28549(249): Fixed segfault in curses’s addch() with ncurses6.

   - bpo-28449(250): 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.

   - bpo-23262(251): The webbrowser module now supports Firefox 36+ and
     derived browsers.  Based on patch by Oleg Broytman.

   - bpo-24241(252): 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

   - bpo-27939(253): 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.

   - bpo-28255(254): 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.

   - bpo-28255(255): calendar.TextCalendar.prmonth() no longer prints a
     space at the start of new line after printing a month’s calendar.
     Patch by Xiang Zhang.

   - bpo-20491(256): The textwrap.TextWrapper class now honors
     non-breaking spaces.  Based on patch by Kaarle Ritvanen.

   - bpo-28353(257): os.fwalk() no longer fails on broken links.

   - bpo-28430(258): Fix iterator of C implemented asyncio.Future
     doesn’t accept non-None value is passed to it.send(val).

   - bpo-27025(259): Generated names for Tkinter widgets now start by
     the "!"  prefix for readability.

   - bpo-25464(260): Fixed HList.header_exists() in tkinter.tix module
     by addin a workaround to Tix library bug.

   - bpo-28488(261): shutil.make_archive() no longer adds entry "./" to
     ZIP archive.

   - bpo-25953(262): 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.

   - bpo-28469(263): timeit now uses the sequence 1, 2, 5, 10, 20,
     50,...  instead of 1, 10, 100,...  for autoranging.

   - bpo-28115(264): Command-line interface of the zipfile module now
     uses argparse.  Added support of long options.

   - bpo-18219(265): Optimize csv.DictWriter for large number of
     columns.  Patch by Mariatta Wijaya.

   - bpo-28448(266): Fix C implemented asyncio.Future didn’t work on
     Windows.

   - bpo-23214(267): In the "io" module, the argument to BufferedReader
     and BytesIO’s read1() methods is now optional and can be -1,
     matching the BufferedIOBase specification.

   - bpo-28480(268): Fix error building socket module when
     multithreading is disabled.

   - bpo-28240(269): timeit: remove ‘-c/--clock’ and ‘-t/--time’ command
     line options which were deprecated since Python 3.3.

   - bpo-28240(270): timeit now repeats the benchmarks 5 times instead
     of only 3 to make benchmarks more reliable.

   - bpo-28240(271): 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.

   - 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(272) for rationale.

   - bpo-24452(273): Make webbrowser support Chrome on Mac OS X. Patch
     by Ned Batchelder.

   - bpo-20766(274): Fix references leaked by pdb in the handling of
     SIGINT handlers.

   - bpo-27998(275): Fixed bytes path support in os.scandir() on
     Windows.  Patch by Eryk Sun.

   - bpo-28317(276): The disassembler now decodes FORMAT_VALUE argument.

   - bpo-28380(277): unittest.mock Mock autospec functions now properly
     support assert_called, assert_not_called, and assert_called_once.

   - bpo-28229(278): lzma module now supports pathlib.

   - bpo-28321(279): Fixed writing non-BMP characters with binary format
     in plistlib.

   - bpo-28225(280): bz2 module now supports pathlib.  Initial patch by
     Ethan Furman.

   - bpo-28227(281): gzip now supports pathlib.  Patch by Ethan Furman.

   - bpo-28332(282): Deprecated silent truncations in socket.htons and
     socket.ntohs.  Original patch by Oren Milman.

   - bpo-27358(283): Optimized merging var-keyword arguments and
     improved error message when passing a non-mapping as a var-keyword
     argument.

   - bpo-28257(284): Improved error message when passing a non-iterable
     as a var-positional argument.  Added opcode
     BUILD_TUPLE_UNPACK_WITH_CALL.

   - bpo-28322(285): Fixed possible crashes when unpickle itertools
     objects from incorrect pickle data.  Based on patch by John Leitch.

   - bpo-28228(286): imghdr now supports pathlib.

   - bpo-28226(287): compileall now supports pathlib.

   - bpo-28314(288): Fix function declaration (C flags) for the
     getiterator() method of xml.etree.ElementTree.Element.

   - bpo-28148(289): 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.

   - bpo-28253(290): 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.

   - bpo-28275(291): Fixed possible use after free in the decompress()
     methods of the LZMADecompressor and BZ2Decompressor classes.
     Original patch by John Leitch.

   - bpo-27897(292): Fixed possible crash in
     sqlite3.Connection.create_collation() if pass invalid string-like
     object as a name.  Patch by Xiang Zhang.

   - bpo-18844(293): 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.

   - bpo-18893(294): Fix invalid exception handling in
     Lib/ctypes/macholib/dyld.py.  Patch by Madison May.

   - bpo-27611(295): Fixed support of default root window in the
     tkinter.tix module.  Added the master parameter in the DisplayStyle
     constructor.

   - bpo-27348(296): In the traceback module, restore the formatting of
     exception messages like "Exception: None".  This fixes a regression
     introduced in 3.5a2.

   - bpo-25651(297): Allow falsy values to be used for msg parameter of
     subTest().

   - bpo-27778(298): Fix a memory leak in os.getrandom() when the
     getrandom() is interrupted by a signal and a signal handler raises
     a Python exception.

   - bpo-28200(299): Fix memory leak on Windows in the os module (fix
     path_converter() function).

   - bpo-25400(300): RobotFileParser now correctly returns default
     values for crawl_delay and request_rate.  Initial patch by Peter
     Wirtz.

   - bpo-27932(301): Prevent memory leak in win32_ver().

   - Fix UnboundLocalError in socket._sendfile_use_sendfile.

   - bpo-28075(302): Check for ERROR_ACCESS_DENIED in Windows
     implementation of os.stat().  Patch by Eryk Sun.

   - bpo-22493(303): Warning message emitted by using inline flags in
     the middle of regular expression now contains a (truncated) regex
     pattern.  Patch by Tim Graham.

   - bpo-25270(304): Prevent codecs.escape_encode() from raising
     SystemError when an empty bytestring is passed.

   - bpo-28181(305): Get antigravity over HTTPS. Patch by Kaartic
     Sivaraam.

   - bpo-25895(306): Enable WebSocket URL schemes in
     urllib.parse.urljoin.  Patch by Gergely Imreh and Markus
     Holtermann.

   - bpo-28114(307): Fix a crash in parse_envlist() when env contains
     byte strings.  Patch by Eryk Sun.

   - bpo-27599(308): Fixed buffer overrun in binascii.b2a_qp() and
     binascii.a2b_qp().

   - bpo-27906(309): Fix socket accept exhaustion during high TCP
     traffic.  Patch by Kevin Conway.

   - bpo-28174(310): Handle when SO_REUSEPORT isn’t properly supported.
     Patch by Seth Michael Larson.

   - bpo-26654(311): Inspect functools.partial in
     asyncio.Handle.__repr__.  Patch by iceboy.

   - bpo-26909(312): Fix slow pipes IO in asyncio.  Patch by INADA
     Naoki.

   - bpo-28176(313): Fix callbacks race in
     asyncio.SelectorLoop.sock_connect.

   - bpo-27759(314): Fix selectors incorrectly retain invalid file
     descriptors.  Patch by Mark Williams.

   - bpo-28325(315): Remove vestigial MacOS 9 macurl2path module and its
     tests.

   - bpo-28368(316): Refuse monitoring processes if the child watcher
     has no loop attached.  Patch by Vincent Michel.

   - bpo-28369(317): Raise RuntimeError when transport’s FD is used with
     add_reader, add_writer, etc.

   - bpo-28370(318): Speedup asyncio.StreamReader.readexactly.  Patch by
     Коренберг Марк.

   - bpo-28371(319): Deprecate passing asyncio.Handles to
     run_in_executor.

   - bpo-28372(320): Fix asyncio to support formatting of non-python
     coroutines.

   - bpo-28399(321): Remove UNIX socket from FS before binding.  Patch
     by Коренберг Марк.

   - bpo-27972(322): Prohibit Tasks to await on themselves.

   - bpo-24142(323): Reading a corrupt config file left configparser in
     an invalid state.  Original patch by Florian Höch.

   - bpo-29581(324): ABCMeta.__new__ now accepts ‘**kwargs’, allowing
     abstract base classes to use keyword parameters in
     __init_subclass__.  Patch by Nate Soares.

   - bpo-25532(325): 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.

   - bpo-30177(326): path.resolve(strict=False) no longer cuts the path
     after the first element not present in the filesystem.  Patch by
     Antoine Pietri.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31499

   (2) https://bugs.python.org/issue31482

   (3) https://bugs.python.org/issue28556

   (4) https://bugs.python.org/issue28556

   (5) https://bugs.python.org/issue31544

   (6) https://bugs.python.org/issue31234

   (7) https://bugs.python.org/issue31457

   (8) https://bugs.python.org/issue31431

   (9) https://bugs.python.org/issue31233

   (10) https://bugs.python.org/issue28638

   (11) https://bugs.python.org/issue31400

   (12) https://bugs.python.org/issue27629

   (13) https://bugs.python.org/issue28958

   (14) https://bugs.python.org/issue28182

   (15) https://bugs.python.org/issue27340

   (16) https://bugs.python.org/issue14191

   (17) https://bugs.python.org/issue31178

   (18) https://bugs.python.org/issue31350

   (19) https://bugs.python.org/issue31170

   (20) https://bugs.python.org/issue29136

   (21) https://bugs.python.org/issue1198569

   (22) https://bugs.python.org/issue31326

   (23) https://bugs.python.org/issue27144

   (24) https://bugs.python.org/issue31281

   (25) https://bugs.python.org/issue10746

   (26) https://www.python.org/dev/peps/pep-3118

   (27) https://bugs.python.org/issue27584

   (28) https://bugs.python.org/issue22536

   (29) https://bugs.python.org/issue29741

   (30) https://bugs.python.org/issue31249

   (31) https://bugs.python.org/issue31247

   (32) https://bugs.python.org/issue23835

   (33) https://bugs.python.org/issue31238

   (34) https://bugs.python.org/issue5001

   (35) https://bugs.python.org/issue31109

   (36) https://bugs.python.org/issue30102

   (37) https://bugs.python.org/issue18966

   (38) https://bugs.python.org/issue31183

   (39) https://bugs.python.org/issue5001

   (40) https://bugs.python.org/issue31185

   (41) https://bugs.python.org/issue31151

   (42) https://bugs.python.org/issue31072

   (43) https://bugs.python.org/issue24700

   (44) https://bugs.python.org/issue31135

   (45) https://bugs.python.org/issue31107

   (46) https://bugs.python.org/issue31080

   (47) https://bugs.python.org/issue30897

   (48) https://bugs.python.org/issue31061

   (49) https://bugs.python.org/issue30987

   (50) https://bugs.python.org/issue30522

   (51) https://bugs.python.org/issue30502

   (52) https://bugs.python.org/issue5288

   (53) https://bugs.python.org/issue30919

   (54) https://bugs.python.org/issue26732

   (55) https://bugs.python.org/issue29403

   (56) https://bugs.python.org/issue30961

   (57) https://bugs.python.org/issue19896

   (58) https://bugs.python.org/issue30946

   (59) https://bugs.python.org/issue25684

   (60) https://bugs.python.org/issue30886

   (61) https://bugs.python.org/issue29854

   (62) https://bugs.python.org/issue30794

   (63) https://bugs.python.org/issue30319

   (64) https://bugs.python.org/issue30828

   (65) https://bugs.python.org/issue30302

   (66) https://bugs.python.org/issue30807

   (67) https://bugs.python.org/issue30441

   (68) https://bugs.python.org/issue29585

   (69) https://bugs.python.org/issue29293

   (70) https://bugs.python.org/issue30532

   (71) https://bugs.python.org/issue30596

   (72) https://bugs.python.org/issue9146

   (73) https://bugs.python.org/issue29169

   (74) https://bugs.python.org/issue30119

   (75) https://bugs.python.org/issue30879

   (76) https://bugs.python.org/issue30746

   (77) https://bugs.python.org/issue30664

   (78) https://bugs.python.org/issue21071

   (79) https://bugs.python.org/issue29212

   (80) https://bugs.python.org/issue29755

   (81) https://bugs.python.org/issue30616

   (82) https://bugs.python.org/issue30038

   (83) https://bugs.python.org/issue23894

   (84) https://bugs.python.org/issue24744

   (85) https://bugs.python.org/issue24484

   (86) https://bugs.python.org/issue30589

   (87) https://bugs.python.org/issue28994

   (88) https://bugs.python.org/issue30508

   (89) https://bugs.python.org/issue30645

   (90) https://bugs.python.org/issue11822

   (91) https://bugs.python.org/issue30624

   (92) https://bugs.python.org/issue30595

   (93) https://bugs.python.org/issue28556

   (94) https://bugs.python.org/issue30605

   (95) https://bugs.python.org/issue29870

   (96) https://bugs.python.org/issue29743

   (97) https://bugs.python.org/issue27585

   (98) https://bugs.python.org/issue30014

   (99) https://bugs.python.org/issue30418

   (100) https://bugs.python.org/issue30463

   (101) https://bugs.python.org/issue30520

   (102) https://bugs.python.org/issue30557

   (103) https://bugs.python.org/issue30526

   (104) https://bugs.python.org/issue30245

   (105) https://bugs.python.org/issue30378

   (106) https://bugs.python.org/issue16500

   (107) https://bugs.python.org/issue30470

   (108) https://bugs.python.org/issue30414

   (109) https://bugs.python.org/issue30003

   (110) https://bugs.python.org/issue30149

   (111) https://bugs.python.org/issue30436

   (112) https://bugs.python.org/issue30301

   (113) https://bugs.python.org/issue30375

   (114) https://bugs.python.org/issue30329

   (115) https://bugs.python.org/issue29196

   (116) https://bugs.python.org/issue9850

   (117) https://bugs.python.org/issue30299

   (118) https://bugs.python.org/issue30048

   (119) https://bugs.python.org/issue30266

   (120) https://bugs.python.org/issue25958

   (121) https://bugs.python.org/issue30340

   (122) https://bugs.python.org/issue30298

   (123) https://bugs.python.org/issue30285

   (124) https://bugs.python.org/issue29990

   (125) https://bugs.python.org/issue29979

   (126) https://bugs.python.org/issue30243

   (127) https://bugs.python.org/issue30215

   (128) https://bugs.python.org/issue30185

   (129) https://bugs.python.org/issue30103

   (130) https://bugs.python.org/issue28556

   (131) https://bugs.python.org/issue30205

   (132) https://bugs.python.org/issue30228

   (133) https://bugs.python.org/issue30190

   (134) https://bugs.python.org/issue30101

   (135) https://bugs.python.org/issue29822

   (136) https://bugs.python.org/issue29960

   (137) https://bugs.python.org/issue30070

   (138) https://bugs.python.org/issue22352

   (139) https://bugs.python.org/issue30061

   (140) https://bugs.python.org/issue30218

   (141) https://bugs.python.org/issue10076

   (142) https://bugs.python.org/issue30068

   (143) https://bugs.python.org/issue29694

   (144) https://bugs.python.org/issue29692

   (145) https://bugs.python.org/issue26187

   (146) https://bugs.python.org/issue9303

   (147) https://bugs.python.org/issue30017

   (148) https://bugs.python.org/issue29998

   (149) https://bugs.python.org/issue29995

   (150) https://bugs.python.org/issue29962

   (151) https://bugs.python.org/issue29649

   (152) https://bugs.python.org/issue29654

   (153) https://bugs.python.org/issue29931

   (154) https://bugs.python.org/issue29953

   (155) https://bugs.python.org/issue29942

   (156) https://bugs.python.org/issue10030

   (157) https://bugs.python.org/issue29204

   (158) https://bugs.python.org/issue27863

   (159) https://bugs.python.org/issue25996

   (160) https://bugs.python.org/issue28699

   (161) https://bugs.python.org/issue23890

   (162) https://bugs.python.org/issue29901

   (163) https://bugs.python.org/issue25803

   (164) https://bugs.python.org/issue29861

   (165) https://bugs.python.org/issue19930

   (166) https://bugs.python.org/issue29884

   (167) https://bugs.python.org/issue25455

   (168) https://bugs.python.org/issue29800

   (169) https://bugs.python.org/issue8256

   (170) https://bugs.python.org/issue28692

   (171) https://bugs.python.org/issue26121

   (172) https://bugs.python.org/issue29619

   (173) https://bugs.python.org/issue28298

   (174) https://bugs.python.org/issue29645

   (175) https://bugs.python.org/issue28231

   (176) https://bugs.python.org/issue26915

   (177) https://bugs.python.org/issue28682

   (178) https://bugs.python.org/issue29728

   (179) https://bugs.python.org/issue29623

   (180) https://bugs.python.org/issue9303

   (181) https://bugs.python.org/issue28963

   (182) https://bugs.python.org/issue29704

   (183) https://bugs.python.org/issue29271

   (184) https://bugs.python.org/issue29703

   (185) https://bugs.python.org/issue29615

   (186) https://bugs.python.org/issue7769

   (187) https://bugs.python.org/issue29376

   (188) https://bugs.python.org/issue28624

   (189) https://bugs.python.org/issue28518

   (190) https://bugs.python.org/issue29742

   (191) https://bugs.python.org/issue16285

   (192) https://bugs.python.org/issue29532

   (193) https://bugs.python.org/issue29110

   (194) https://bugs.python.org/issue22807

   (195) https://bugs.python.org/issue29576

   (196) https://bugs.python.org/issue29534

   (197) https://bugs.python.org/issue10379

   (198) https://bugs.python.org/issue29851

   (199) https://bugs.python.org/issue28556

   (200) https://bugs.python.org/issue29100

   (201) https://bugs.python.org/issue29416

   (202) https://bugs.python.org/issue29444

   (203) https://bugs.python.org/issue29377

   (204) https://bugs.python.org/issue29218

   (205) https://bugs.python.org/issue29368

   (206) https://bugs.python.org/issue29338

   (207) https://bugs.python.org/issue29335

   (208) https://bugs.python.org/issue29290

   (209) https://bugs.python.org/issue28735

   (210) https://bugs.python.org/issue29197

   (211) https://bugs.python.org/issue29210

   (212) https://bugs.python.org/issue29219

   (213) https://bugs.python.org/issue29192

   (214) https://bugs.python.org/issue29193

   (215) https://bugs.python.org/issue29195

   (216) https://bugs.python.org/issue28969

   (217) https://bugs.python.org/issue20804

   (218) https://bugs.python.org/issue29142

   (219) https://bugs.python.org/issue28961

   (220) https://bugs.python.org/issue15812

   (221) https://bugs.python.org/issue28985

   (222) https://bugs.python.org/issue29079

   (223) https://bugs.python.org/issue13051

   (224) https://bugs.python.org/issue9770

   (225) https://bugs.python.org/issue28427

   (226) https://bugs.python.org/issue28923

   (227) https://bugs.python.org/issue28871

   (228) https://bugs.python.org/issue19542

   (229) https://bugs.python.org/issue20191

   (230) https://bugs.python.org/issue16255

   (231) https://bugs.python.org/issue28779

   (232) https://bugs.python.org/issue26937

   (233) https://bugs.python.org/issue28847

   (234) https://bugs.python.org/issue27030

   (235) https://bugs.python.org/issue28835

   (236) https://bugs.python.org/issue27172

   (237) https://bugs.python.org/issue28740

   (238) https://bugs.python.org/issue26273

   (239) https://bugs.python.org/issue28752

   (240) https://bugs.python.org/issue28727

   (241) https://bugs.python.org/issue18383

   (242) https://bugs.python.org/issue20572

   (243) https://bugs.python.org/issue25659

   (244) https://bugs.python.org/issue28548

   (245) https://bugs.python.org/issue19717

   (246) https://bugs.python.org/issue28563

   (247) https://bugs.python.org/issue28387

   (248) https://bugs.python.org/issue27517

   (249) https://bugs.python.org/issue28549

   (250) https://bugs.python.org/issue28449

   (251) https://bugs.python.org/issue23262

   (252) https://bugs.python.org/issue24241

   (253) https://bugs.python.org/issue27939

   (254) https://bugs.python.org/issue28255

   (255) https://bugs.python.org/issue28255

   (256) https://bugs.python.org/issue20491

   (257) https://bugs.python.org/issue28353

   (258) https://bugs.python.org/issue28430

   (259) https://bugs.python.org/issue27025

   (260) https://bugs.python.org/issue25464

   (261) https://bugs.python.org/issue28488

   (262) https://bugs.python.org/issue25953

   (263) https://bugs.python.org/issue28469

   (264) https://bugs.python.org/issue28115

   (265) https://bugs.python.org/issue18219

   (266) https://bugs.python.org/issue28448

   (267) https://bugs.python.org/issue23214

   (268) https://bugs.python.org/issue28480

   (269) https://bugs.python.org/issue28240

   (270) https://bugs.python.org/issue28240

   (271) https://bugs.python.org/issue28240

   (272) https://github.com/pypa/setuptools/issues/100

   (273) https://bugs.python.org/issue24452

   (274) https://bugs.python.org/issue20766

   (275) https://bugs.python.org/issue27998

   (276) https://bugs.python.org/issue28317

   (277) https://bugs.python.org/issue28380

   (278) https://bugs.python.org/issue28229

   (279) https://bugs.python.org/issue28321

   (280) https://bugs.python.org/issue28225

   (281) https://bugs.python.org/issue28227

   (282) https://bugs.python.org/issue28332

   (283) https://bugs.python.org/issue27358

   (284) https://bugs.python.org/issue28257

   (285) https://bugs.python.org/issue28322

   (286) https://bugs.python.org/issue28228

   (287) https://bugs.python.org/issue28226

   (288) https://bugs.python.org/issue28314

   (289) https://bugs.python.org/issue28148

   (290) https://bugs.python.org/issue28253

   (291) https://bugs.python.org/issue28275

   (292) https://bugs.python.org/issue27897

   (293) https://bugs.python.org/issue18844

   (294) https://bugs.python.org/issue18893

   (295) https://bugs.python.org/issue27611

   (296) https://bugs.python.org/issue27348

   (297) https://bugs.python.org/issue25651

   (298) https://bugs.python.org/issue27778

   (299) https://bugs.python.org/issue28200

   (300) https://bugs.python.org/issue25400

   (301) https://bugs.python.org/issue27932

   (302) https://bugs.python.org/issue28075

   (303) https://bugs.python.org/issue22493

   (304) https://bugs.python.org/issue25270

   (305) https://bugs.python.org/issue28181

   (306) https://bugs.python.org/issue25895

   (307) https://bugs.python.org/issue28114

   (308) https://bugs.python.org/issue27599

   (309) https://bugs.python.org/issue27906

   (310) https://bugs.python.org/issue28174

   (311) https://bugs.python.org/issue26654

   (312) https://bugs.python.org/issue26909

   (313) https://bugs.python.org/issue28176

   (314) https://bugs.python.org/issue27759

   (315) https://bugs.python.org/issue28325

   (316) https://bugs.python.org/issue28368

   (317) https://bugs.python.org/issue28369

   (318) https://bugs.python.org/issue28370

   (319) https://bugs.python.org/issue28371

   (320) https://bugs.python.org/issue28372

   (321) https://bugs.python.org/issue28399

   (322) https://bugs.python.org/issue27972

   (323) https://bugs.python.org/issue24142

   (324) https://bugs.python.org/issue29581

   (325) https://bugs.python.org/issue25532

   (326) https://bugs.python.org/issue30177


File: python.info,  Node: 文档<35>,  Next: 测试<32>,  Prev: 库<41>,  Up: Python 3 7 0 alpha 1

1.19.42.4 文档
..............

   - bpo-31294(1): Fix incomplete code snippet in the
     ZeroMQSocketListener and ZeroMQSocketHandler examples and adapt
     them to Python 3.

   - bpo-21649(2): Add RFC 7525 and Mozilla server side TLS links to SSL
     documentation.

   - bpo-31128(3): Allow the pydoc server to bind to arbitrary
     hostnames.

   - bpo-30803(4): Clarify doc on truth value testing.  Original patch
     by Peter Thomassen.

   - bpo-30176(5): Add missing attribute related constants in curses
     documentation.

   - bpo-30052(6): the link targets for *note bytes(): 172. and *note
     bytearray(): 173. are now their respective type definitions, rather
     than the corresponding builtin function entries.  Use *note bytes:
     11f2. and *note bytearray: 11f3. 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.

   - bpo-26985(7): Add missing info of code object in inspect
     documentation.

   - bpo-19824(8): 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(9),
     bpo-12518(10))

   - bpo-28929(11): Link the documentation to its source file on GitHub.

   - bpo-25008(12): Document smtpd.py as effectively deprecated and add
     a pointer to aiosmtpd, a third-party asyncio-based replacement.

   - bpo-26355(13): Add canonical header link on each page to
     corresponding major version of the documentation.  Patch by
     Matthias Bussonnier.

   - bpo-29349(14): Fix Python 2 syntax in code for building the
     documentation.

   - bpo-23722(15): The data model reference and the porting section in
     the 3.6 What’s New guide now cover the additional ‘__classcell__’
     handling needed for custom metaclasses to fully support PEP 487(16)
     and zero-argument ‘super()’.

   - bpo-28513(17): Documented command-line interface of zipfile.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31294

   (2) https://bugs.python.org/issue21649

   (3) https://bugs.python.org/issue31128

   (4) https://bugs.python.org/issue30803

   (5) https://bugs.python.org/issue30176

   (6) https://bugs.python.org/issue30052

   (7) https://bugs.python.org/issue26985

   (8) https://bugs.python.org/issue19824

   (9) https://bugs.python.org/issue20314

   (10) https://bugs.python.org/issue12518

   (11) https://bugs.python.org/issue28929

   (12) https://bugs.python.org/issue25008

   (13) https://bugs.python.org/issue26355

   (14) https://bugs.python.org/issue29349

   (15) https://bugs.python.org/issue23722

   (16) https://www.python.org/dev/peps/pep-0487

   (17) https://bugs.python.org/issue28513


File: python.info,  Node: 测试<32>,  Next: 构建<32>,  Prev: 文档<35>,  Up: Python 3 7 0 alpha 1

1.19.42.5 测试
..............

   - bpo-29639(1): test.support.HOST is now "localhost", a new HOSTv4
     constant has been added for your ‘127.0.0.1’ needs, similar to the
     existing HOSTv6 constant.

   - bpo-31320(2): Silence traceback in test_ssl

   - bpo-31346(3): Prefer PROTOCOL_TLS_CLIENT and PROTOCOL_TLS_SERVER
     protocols for SSLContext.

   - bpo-25674(4): Remove sha256.tbs-internet.com ssl test

   - bpo-30715(5): Address ALPN callback changes for OpenSSL 1.1.0f.
     The latest version behaves like OpenSSL 1.0.2 and no longer aborts
     handshake.

   - bpo-30822(6): 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.

   - bpo-30695(7): Add the ‘set_nomemory(start, stop)’ and
     ‘remove_mem_hooks()’ functions to the _testcapi module.

   - bpo-30357(8): 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.

   - bpo-30197(9): 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.

   - bpo-24932(10): Use proper command line parsing in _testembed

   - bpo-28950(11): Disallow -j0 to be combined with -T/-l in regrtest
     command line arguments.

   - bpo-28683(12): Fix the tests that bind() a unix socket and raise
     PermissionError on Android for a non-root user.

   - bpo-26936(13): Fix the test_socket failures on Android -
     getservbyname(), getservbyport() and getaddrinfo() are broken on
     some Android API levels.

   - bpo-28666(14): Now test.support.rmtree is able to remove unwritable
     or unreadable directories.

   - bpo-23839(15): Various caches now are cleared before running every
     test file.

   - bpo-26944(16): Fix test_posix for Android where ’id -G’ is entirely
     wrong or missing the effective gid.

   - bpo-28409(17): regrtest: fix the parser of command line arguments.

   - bpo-28217(18): Adds _testconsole module to test console input.

   - bpo-26939(19): Add the support.setswitchinterval() function to fix
     test_functools hanging on the Android armv7 qemu emulator.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29639

   (2) https://bugs.python.org/issue31320

   (3) https://bugs.python.org/issue31346

   (4) https://bugs.python.org/issue25674

   (5) https://bugs.python.org/issue30715

   (6) https://bugs.python.org/issue30822

   (7) https://bugs.python.org/issue30695

   (8) https://bugs.python.org/issue30357

   (9) https://bugs.python.org/issue30197

   (10) https://bugs.python.org/issue24932

   (11) https://bugs.python.org/issue28950

   (12) https://bugs.python.org/issue28683

   (13) https://bugs.python.org/issue26936

   (14) https://bugs.python.org/issue28666

   (15) https://bugs.python.org/issue23839

   (16) https://bugs.python.org/issue26944

   (17) https://bugs.python.org/issue28409

   (18) https://bugs.python.org/issue28217

   (19) https://bugs.python.org/issue26939


File: python.info,  Node: 构建<32>,  Next: Windows<32>,  Prev: 测试<32>,  Up: Python 3 7 0 alpha 1

1.19.42.6 构建
..............

   - bpo-31354(1): Allow –with-lto to be used on all builds, not just
     ‘make profile-opt’.

   - bpo-31370(2): 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.

   - bpo-31341(3): Per PEP 11(4), support for the IRIX operating system
     was removed.

   - bpo-30854(5): Fix compile error when compiling –without-threads.
     Patch by Masayuki Yamamoto.

   - bpo-30687(6): Locate msbuild.exe on Windows when building rather
     than vcvarsall.bat

   - bpo-20210(7): Support the `disabled' marker in Setup files.
     Extension modules listed after this marker are not built at all,
     neither by the Makefile nor by setup.py.

   - bpo-29941(8): Add ‘--with-assertions’ configure flag to explicitly
     enable C ‘assert()’ checks.  Defaults to off.  ‘--with-pydebug’
     implies ‘--with-assertions’.

   - bpo-28787(9): Fix out-of-tree builds of Python when configured with
     ‘--with--dtrace’.

   - bpo-29243(10): Prevent unnecessary rebuilding of Python during
     ‘make test’, ‘make install’ and some other make targets when
     configured with ‘--enable-optimizations’.

   - bpo-23404(11): Don’t regenerate generated files based on file
     modification time anymore: the action is now explicit.  Replace
     ‘make touch’ with ‘make regen-all’.

   - bpo-29643(12): Fix ‘--enable-optimization’ didn’t work.

   - bpo-27593(13): 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.

   - bpo-29572(14): 更新Windows 构建和OS X安装程序以使用OpenSSL 1.0.2k。

   - bpo-27659(15): Prohibit implicit C function declarations: use
     ‘-Werror=implicit-function-declaration’ when possible (GCC and
     Clang, but it depends on the compiler version).  Patch written by
     Chi Hsuan Yen.

   - bpo-29384(16): Remove old Be OS helper scripts.

   - bpo-26851(17): Set Android compilation and link flags.

   - bpo-28768(18): Fix implicit declaration of function _setmode.
     Patch by Masayuki Yamamoto

   - bpo-29080(19): Removes hard dependency on hg.exe from
     PCBuild/build.bat

   - bpo-23903(20): Added missed names to PC/python3.def.

   - bpo-28762(21): lockf() is available on Android API level 24, but
     the F_LOCK macro is not defined in android-ndk-r13.

   - bpo-28538(22): Fix the compilation error that occurs because
     if_nameindex() is available on Android API level 24, but the
     if_nameindex structure is not defined.

   - bpo-20211(23): 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.

   - bpo-28849(24): Do not define sys.implementation._multiarch on
     Android.

   - bpo-10656(25): Fix out-of-tree building on AIX. Patch by Tristan
     Carel and Michael Haubenwallner.

   - bpo-26359(26): Rename –with-optimiations to –enable-optimizations.

   - bpo-28444(27): Fix missing extensions modules when cross compiling.

   - bpo-28208(28): 更新Windows 构建和OS X 安装程序以使用SQLite 3.14.2.

   - bpo-28248(29): 更新Windows 构建和OS X安装程序以使用OpenSSL 1.0.2j.

   - bpo-21124(30): Fix building the _struct module on Cygwin by passing
     ‘NULL’ instead of ‘&PyType_Type’ to PyVarObject_HEAD_INIT. Patch by
     Masayuki Yamamoto.

   - bpo-13756(31): Fix building extensions modules on Cygwin.  Patch by
     Roumen Petrov, based on original patch by Jason Tishler.

   - bpo-21085(32): Add configure check for siginfo_t.si_band, which
     Cygwin does not provide.  Patch by Masayuki Yamamoto with review
     and rebase by Erik Bray.

   - bpo-28258(33): Fixed build with Estonian locale (python-config and
     distclean targets in Makefile).  Patch by Arfrever Frehtes
     Taifersar Arahesis.

   - bpo-26661(34): setup.py now detects system libffi with multiarch
     wrapper.

   - bpo-27979(35): 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.

   - bpo-15819(36): Remove redundant include search directory option for
     building outside the source tree.

   - bpo-28676(37): Prevent missing ’getentropy’ declaration warning on
     macOS. Patch by Gareth Rees.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31354

   (2) https://bugs.python.org/issue31370

   (3) https://bugs.python.org/issue31341

   (4) https://www.python.org/dev/peps/pep-0011

   (5) https://bugs.python.org/issue30854

   (6) https://bugs.python.org/issue30687

   (7) https://bugs.python.org/issue20210

   (8) https://bugs.python.org/issue29941

   (9) https://bugs.python.org/issue28787

   (10) https://bugs.python.org/issue29243

   (11) https://bugs.python.org/issue23404

   (12) https://bugs.python.org/issue29643

   (13) https://bugs.python.org/issue27593

   (14) https://bugs.python.org/issue29572

   (15) https://bugs.python.org/issue27659

   (16) https://bugs.python.org/issue29384

   (17) https://bugs.python.org/issue26851

   (18) https://bugs.python.org/issue28768

   (19) https://bugs.python.org/issue29080

   (20) https://bugs.python.org/issue23903

   (21) https://bugs.python.org/issue28762

   (22) https://bugs.python.org/issue28538

   (23) https://bugs.python.org/issue20211

   (24) https://bugs.python.org/issue28849

   (25) https://bugs.python.org/issue10656

   (26) https://bugs.python.org/issue26359

   (27) https://bugs.python.org/issue28444

   (28) https://bugs.python.org/issue28208

   (29) https://bugs.python.org/issue28248

   (30) https://bugs.python.org/issue21124

   (31) https://bugs.python.org/issue13756

   (32) https://bugs.python.org/issue21085

   (33) https://bugs.python.org/issue28258

   (34) https://bugs.python.org/issue26661

   (35) https://bugs.python.org/issue27979

   (36) https://bugs.python.org/issue15819

   (37) https://bugs.python.org/issue28676


File: python.info,  Node: Windows<32>,  Next: IDLE<32>,  Prev: 构建<32>,  Up: Python 3 7 0 alpha 1

1.19.42.7 Windows
.................

   - bpo-31392(1): 更新Windows 构建以使用OpenSSL 1.1.0f

   - bpo-30389(2): Adds detection of Visual Studio 2017 to distutils on
     Windows.

   - bpo-31358(3): zlib is no longer bundled in the CPython source,
     instead it is downloaded on demand just like bz2, lzma, OpenSSL,
     Tcl/Tk, and SQLite.

   - bpo-31340(4): Change to building with MSVC v141 (included with
     Visual Studio 2017)

   - bpo-30581(5): os.cpu_count() now returns the correct number of
     processors on Windows when the number of logical processors is
     greater than 64.

   - bpo-30916(6): Pre-build OpenSSL, Tcl and Tk and include the
     binaries in the build.

   - bpo-30731(7): Add a missing xmlns to python.manifest so that it
     matches the schema.

   - bpo-30291(8): Allow requiring 64-bit interpreters from py.exe using
     -64 suffix.  Contributed by Steve (Gadget) Barnes.

   - bpo-30362(9): Adds list options (-0, -0p) to py.exe launcher.
     Contributed by Steve Barnes.

   - bpo-23451(10): Fix socket deprecation warnings in socketmodule.c.
     Patch by Segev Finer.

   - bpo-30450(11): 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 ‘py -3.6’),
     NuGet is used to download a copy of 32-bit Python.

   - bpo-29579(12): Removes readme.txt from the installer.

   - bpo-25778(13): winreg does not truncate string correctly (Patch by
     Eryk Sun)

   - bpo-28896(14): Deprecate WindowsRegistryFinder and disable it by
     default

   - bpo-28522(15): Fixes mishandled buffer reallocation in getpathp.c

   - bpo-28402(16): Adds signed catalog files for stdlib on Windows.

   - bpo-28333(17): Enables Unicode for ps1/ps2 and input() prompts.
     (Patch by Eryk Sun)

   - bpo-28251(18): Improvements to help manuals on Windows.

   - bpo-28110(19): launcher.msi has different product codes between
     32-bit and 64-bit

   - bpo-28161(20): Opening CON for write access fails

   - bpo-28162(21): WindowsConsoleIO readall() fails if first line
     starts with Ctrl+Z

   - bpo-28163(22): WindowsConsoleIO fileno() passes wrong flags to
     _open_osfhandle

   - bpo-28164(23): _PyIO_get_console_type fails for various paths

   - bpo-28137(24): Renames Windows path file to ._pth

   - bpo-28138(25): Windows ._pth file should allow import site

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31392

   (2) https://bugs.python.org/issue30389

   (3) https://bugs.python.org/issue31358

   (4) https://bugs.python.org/issue31340

   (5) https://bugs.python.org/issue30581

   (6) https://bugs.python.org/issue30916

   (7) https://bugs.python.org/issue30731

   (8) https://bugs.python.org/issue30291

   (9) https://bugs.python.org/issue30362

   (10) https://bugs.python.org/issue23451

   (11) https://bugs.python.org/issue30450

   (12) https://bugs.python.org/issue29579

   (13) https://bugs.python.org/issue25778

   (14) https://bugs.python.org/issue28896

   (15) https://bugs.python.org/issue28522

   (16) https://bugs.python.org/issue28402

   (17) https://bugs.python.org/issue28333

   (18) https://bugs.python.org/issue28251

   (19) https://bugs.python.org/issue28110

   (20) https://bugs.python.org/issue28161

   (21) https://bugs.python.org/issue28162

   (22) https://bugs.python.org/issue28163

   (23) https://bugs.python.org/issue28164

   (24) https://bugs.python.org/issue28137

   (25) https://bugs.python.org/issue28138


File: python.info,  Node: IDLE<32>,  Next: 工具/示例<17>,  Prev: Windows<32>,  Up: Python 3 7 0 alpha 1

1.19.42.8 IDLE
..............

   - bpo-31493(1): IDLE code context – fix code update and font update
     timers.  Canceling timers prevents a warning message when test_idle
     completes.

   - bpo-31488(2): 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.

   - bpo-31477(3): IDLE - Improve rstrip entry in doc.  Strip trailing
     whitespace strips more than blank spaces.  Multiline string
     literals are not skipped.

   - bpo-31480(4): IDLE - make tests pass with zzdummy extension
     disabled by default.

   - bpo-31421(5): 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.

   - bpo-31414(6): IDLE – fix tk entry box tests by deleting first.
     Adding to an int entry is not the same as deleting and inserting
     because int(’’) will fail.

   - bpo-31051(7): Rearrange IDLE configdialog GenPage into Window,
     Editor, and Help sections.

   - bpo-30617(8): 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.

   - bpo-31287(9): IDLE - Do not modify tkinter.message in
     test_configdialog.

   - bpo-27099(10): 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.

   - bpo-31206(11): IDLE: Factor HighPage(Frame) class from
     ConfigDialog.  Patch by Cheryl Sabella.

   - bpo-31001(12): Add tests for configdialog highlight tab.  Patch by
     Cheryl Sabella.

   - bpo-31205(13): IDLE: Factor KeysPage(Frame) class from
     ConfigDialog.  The slightly modified tests continue to pass.  Patch
     by Cheryl Sabella.

   - bpo-31130(14): IDLE – stop leaks in test_configdialog.  Initial
     patch by Victor Stinner.

   - bpo-31002(15): Add tests for configdialog keys tab.  Patch by
     Cheryl Sabella.

   - bpo-19903(16): IDLE: Calltips use *note inspect.signature: 655.
     instead of *note inspect.getfullargspec: 657.  This improves
     calltips for builtins converted to use Argument Clinic.  Patch by
     Louie Lu.

   - bpo-31083(17): IDLE - Add an outline of a TabPage class in
     configdialog.  Update existing classes to match outline.  Initial
     patch by Cheryl Sabella.

   - bpo-31050(18): Factor GenPage(Frame) class from ConfigDialog.  The
     slightly modified tests continue to pass.  Patch by Cheryl Sabella.

   - bpo-31004(19): IDLE - Factor FontPage(Frame) class from
     ConfigDialog.  Slightly modified tests continue to pass.  Fix
     General tests.  Patch mostly by Cheryl Sabella.

   - bpo-30781(20): IDLE - Use ttk widgets in ConfigDialog.  Patches by
     Terry Jan Reedy and Cheryl Sabella.

   - bpo-31060(21): 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.

   - bpo-30853(22): 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%.

   - bpo-31003(23): IDLE: Add more tests for General tab.

   - bpo-30993(24): 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.

   - bpo-30981(25): IDLE – Add more configdialog font page tests.

   - bpo-28523(26): IDLE: replace ’colour’ with ’color’ in configdialog.

   - bpo-30917(27): Add tests for idlelib.config.IdleConf.  Increase
     coverage from 46% to 96%.  Patch by Louie Lu.

   - bpo-30934(28): 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.

   - bpo-30913(29): 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.

   - bpo-30899(30): IDLE: Add tests for ConfigParser subclasses in
     config.  Patch by Louie Lu.

   - bpo-30881(31): IDLE: Add docstrings to browser.py.  Patch by Cheryl
     Sabella.

   - bpo-30851(32): IDLE: Remove unused variables in configdialog.  One
     is a duplicate, one is set but cannot be altered by users.  Patch
     by Cheryl Sabella.

   - bpo-30870(33): IDLE: In Settings dialog, select font with Up, Down
     keys as well as mouse.  Initial patch by Louie Lu.

   - bpo-8231(34): IDLE: call config.IdleConf.GetUserCfgDir only once.

   - bpo-30779(35): 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.

   - bpo-30777(36): IDLE: configdialog - Add docstrings and fix
     comments.  Patch by Cheryl Sabella.

   - bpo-30495(37): IDLE: Improve textview with docstrings, PEP8 names,
     and more tests.  Patch by Cheryl Sabella.

   - bpo-30723(38): 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.

   - bpo-30674(39): IDLE: add docstrings to grep module.  Patch by
     Cheryl Sabella

   - bpo-21519(40): IDLE’s basic custom key entry dialog now detects
     duplicates properly.  Original patch by Saimadhav Heblikar.

   - bpo-29910(41): IDLE no longer deletes a character after commenting
     out a region by a key shortcut.  Add ‘return 'break'’ for this and
     other potential conflicts between IDLE and default key bindings.

   - bpo-30728(42): Review and change idlelib.configdialog names.
     Lowercase method and attribute names.  Replace ’colour’ with
     ’color’, expand overly cryptic names, delete unneeded underscores.
     Replace ‘import *’ with specific imports.  Patches by Cheryl
     Sabella.

   - bpo-6739(43): 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.

   - bpo-15786(44): 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.

   - bpo-25514(45): Add doc subsubsection about IDLE failure to start.
     Popup no-connection message directs users to this section.

   - bpo-30642(46): Fix reference leaks in IDLE tests.  Patches by Louie
     Lu and Terry Jan Reedy.

   - bpo-30495(47): Add docstrings for textview.py and use PEP8 names.
     Patches by Cheryl Sabella and Terry Jan Reedy.

   - bpo-30290(48): Help-about: use pep8 names and add tests.  Increase
     coverage to 100%.  Patches by Louie Lu, Cheryl Sabella, and Terry
     Jan Reedy.

   - bpo-30303(49): Add _utest option to textview; add new tests.
     Increase coverage to 100%.  Patches by Louie Lu and Terry Jan
     Reedy.

   - bpo-29071(50): IDLE colors f-string prefixes (but not invalid ur
     prefixes).

   - bpo-28572(51): Add 10% to coverage of IDLE’s test_configdialog.
     Update and augment description of the configuration system.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31493

   (2) https://bugs.python.org/issue31488

   (3) https://bugs.python.org/issue31477

   (4) https://bugs.python.org/issue31480

   (5) https://bugs.python.org/issue31421

   (6) https://bugs.python.org/issue31414

   (7) https://bugs.python.org/issue31051

   (8) https://bugs.python.org/issue30617

   (9) https://bugs.python.org/issue31287

   (10) https://bugs.python.org/issue27099

   (11) https://bugs.python.org/issue31206

   (12) https://bugs.python.org/issue31001

   (13) https://bugs.python.org/issue31205

   (14) https://bugs.python.org/issue31130

   (15) https://bugs.python.org/issue31002

   (16) https://bugs.python.org/issue19903

   (17) https://bugs.python.org/issue31083

   (18) https://bugs.python.org/issue31050

   (19) https://bugs.python.org/issue31004

   (20) https://bugs.python.org/issue30781

   (21) https://bugs.python.org/issue31060

   (22) https://bugs.python.org/issue30853

   (23) https://bugs.python.org/issue31003

   (24) https://bugs.python.org/issue30993

   (25) https://bugs.python.org/issue30981

   (26) https://bugs.python.org/issue28523

   (27) https://bugs.python.org/issue30917

   (28) https://bugs.python.org/issue30934

   (29) https://bugs.python.org/issue30913

   (30) https://bugs.python.org/issue30899

   (31) https://bugs.python.org/issue30881

   (32) https://bugs.python.org/issue30851

   (33) https://bugs.python.org/issue30870

   (34) https://bugs.python.org/issue8231

   (35) https://bugs.python.org/issue30779

   (36) https://bugs.python.org/issue30777

   (37) https://bugs.python.org/issue30495

   (38) https://bugs.python.org/issue30723

   (39) https://bugs.python.org/issue30674

   (40) https://bugs.python.org/issue21519

   (41) https://bugs.python.org/issue29910

   (42) https://bugs.python.org/issue30728

   (43) https://bugs.python.org/issue6739

   (44) https://bugs.python.org/issue15786

   (45) https://bugs.python.org/issue25514

   (46) https://bugs.python.org/issue30642

   (47) https://bugs.python.org/issue30495

   (48) https://bugs.python.org/issue30290

   (49) https://bugs.python.org/issue30303

   (50) https://bugs.python.org/issue29071

   (51) https://bugs.python.org/issue28572


File: python.info,  Node: 工具/示例<17>,  Next: C API<27>,  Prev: IDLE<32>,  Up: Python 3 7 0 alpha 1

1.19.42.9 工具/示例
...................

   - bpo-30983(1): gdb integration commands (py-bt, etc.)  work on
     optimized shared builds now, too.  PEP 523(2) 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.

   - bpo-29748(3): Added the slice index converter in Argument Clinic.

   - bpo-24037(4): Argument Clinic now uses the converter
     ‘bool(accept={int})’ rather than *note int: 204. for semantical
     booleans.  This avoids repeating the default value for Python and C
     and will help in converting to *note bool: 2bd. in future.

   - bpo-29367(5): python-gdb.py now supports also ‘method-wrapper’
     (‘wrapperobject’) objects.

   - bpo-28023(6): Fix python-gdb.py didn’t support new dict
     implementation.

   - bpo-15369(7): The pybench and pystone microbenchmark have been
     removed from Tools.  Please use the new Python benchmark suite
     ‘https://github.com/python/performance’ which is more reliable and
     includes a portable version of pybench working on Python 2 and
     Python 3.

   - bpo-28102(8): The zipfile module CLI now prints usage to stderr.
     Patch by Stephen J. Turnbull.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30983

   (2) https://www.python.org/dev/peps/pep-0523

   (3) https://bugs.python.org/issue29748

   (4) https://bugs.python.org/issue24037

   (5) https://bugs.python.org/issue29367

   (6) https://bugs.python.org/issue28023

   (7) https://bugs.python.org/issue15369

   (8) https://bugs.python.org/issue28102


File: python.info,  Node: C API<27>,  Prev: 工具/示例<17>,  Up: Python 3 7 0 alpha 1

1.19.42.10 C API
................

   - bpo-31338(1): Added the ‘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.

   - bpo-30832(2): 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.

   - bpo-30708(3): PyUnicode_AsWideCharString() now raises a ValueError
     if the second argument is NULL and the wchar_t* string contains
     null characters.

   - bpo-16500(4): Deprecate PyOS_AfterFork() and add PyOS_BeforeFork(),
     PyOS_AfterFork_Parent() and PyOS_AfterFork_Child().

   - bpo-6532(5): 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".

   - bpo-27867(6): 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().

   - bpo-29083(7): 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.

   - bpo-28769(8): The result of PyUnicode_AsUTF8AndSize() and
     PyUnicode_AsUTF8() is now of type ‘const char *’ rather of ‘char
     *’.

   - bpo-29058(9): 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.

   - bpo-28822(10): The index parameters `start' and `end' of
     PyUnicode_FindChar() are now adjusted to behave like
     ‘str[start:end]’.

   - bpo-28808(11): PyUnicode_CompareWithASCIIString() now never raises
     exceptions.

   - bpo-28761(12): The fields name and doc of structures PyMemberDef,
     PyGetSetDef, PyStructSequence_Field, PyStructSequence_Desc, and
     wrapperbase are now of type ‘const char *’ rather of ‘char *’.

   - bpo-28748(13): Private variable _Py_PackageContext is now of type
     ‘const char *’ rather of ‘char *’.

   - bpo-19569(14): Compiler warnings are now emitted if use most of
     deprecated functions.

   - bpo-28426(15): Deprecated undocumented functions
     PyUnicode_AsEncodedObject(), PyUnicode_AsDecodedObject(),
     PyUnicode_AsDecodedUnicode() and PyUnicode_AsEncodedUnicode().

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31338

   (2) https://bugs.python.org/issue30832

   (3) https://bugs.python.org/issue30708

   (4) https://bugs.python.org/issue16500

   (5) https://bugs.python.org/issue6532

   (6) https://bugs.python.org/issue27867

   (7) https://bugs.python.org/issue29083

   (8) https://bugs.python.org/issue28769

   (9) https://bugs.python.org/issue29058

   (10) https://bugs.python.org/issue28822

   (11) https://bugs.python.org/issue28808

   (12) https://bugs.python.org/issue28761

   (13) https://bugs.python.org/issue28748

   (14) https://bugs.python.org/issue19569

   (15) https://bugs.python.org/issue28426


File: python.info,  Node: Python 3 6 6 正式版,  Next: Python 3 6 6 rc1,  Prev: Python 3 7 0 alpha 1,  Up: Changelog（更動日誌）

1.19.43 Python 3.6.6 正式版
---------------------------

`发布日期: 2018-06-27'

在 3.6.6 版本中没有新的更改。


File: python.info,  Node: Python 3 6 6 rc1,  Next: Python 3 6 5 正式版,  Prev: Python 3 6 6 正式版,  Up: Changelog（更動日誌）

1.19.44 Python 3.6.6 rc1
------------------------

`发布日期: 2018-06-11'

* Menu:

* 核心与内置函数: 核心与内置函数<39>.
* 库: 库<42>.
* 文档: 文档<36>.
* 测试: 测试<33>.
* 构建: 构建<33>.
* Windows: Windows<33>.
* macOS: macOS<27>.
* IDLE: IDLE<33>.
* 工具/示例: 工具/示例<18>.
* C API: C API<28>.


File: python.info,  Node: 核心与内置函数<39>,  Next: 库<42>,  Up: Python 3 6 6 rc1

1.19.44.1 核心与内置函数
........................

   - bpo-33786(1): Fix asynchronous generators to handle GeneratorExit
     in athrow() correctly

   - bpo-30654(2): 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.

   - bpo-33622(3): Fixed a leak when the garbage collector fails to add
     an object with the ‘__del__’ method or referenced by it into the
     *note gc.garbage: c12. list.  ‘PyGC_Collect()’ can now be called
     when an exception is set and preserves it.

   - bpo-31849(4): Fix signed/unsigned comparison warning in pyhash.c.

   - bpo-33391(5): Fix a leak in set_symmetric_difference().

   - bpo-28055(6): Fix unaligned accesses in siphash24().  Patch by Rolf
     Eike Beer.

   - bpo-33231(7): 修复 ‘normalizestring()’ 中潜在的内存泄漏。

   - bpo-29922(8): Improved error messages in ’async with’ when
     ‘__aenter__()’ or ‘__aexit__()’ return non-awaitable object.

   - bpo-33199(9): Fix ‘ma_version_tag’ in dict implementation is
     uninitialized when copying from key-sharing dict.

   - bpo-33041(10): Fixed jumping when the function contains an ‘async
     for’ loop.

   - bpo-32282(11): Fix an unnecessary ifdef in the include of
     VersionHelpers.h in socketmodule on Windows.

   - bpo-21983(12): Fix a crash in *note ctypes.cast(): 114b. in case
     the type argument is a ctypes structured data type.  Patch by Eryk
     Sun and Oren Milman.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33786

   (2) https://bugs.python.org/issue30654

   (3) https://bugs.python.org/issue33622

   (4) https://bugs.python.org/issue31849

   (5) https://bugs.python.org/issue33391

   (6) https://bugs.python.org/issue28055

   (7) https://bugs.python.org/issue33231

   (8) https://bugs.python.org/issue29922

   (9) https://bugs.python.org/issue33199

   (10) https://bugs.python.org/issue33041

   (11) https://bugs.python.org/issue32282

   (12) https://bugs.python.org/issue21983


File: python.info,  Node: 库<42>,  Next: 文档<36>,  Prev: 核心与内置函数<39>,  Up: Python 3 6 6 rc1

1.19.44.2 库
............

   - bpo-30167(1): Prevent site.main() exception if PYTHONSTARTUP is
     set.  Patch by Steve Weber.

   - bpo-33812(2): Datetime instance d with non-None tzinfo, but with
     d.tzinfo.utcoffset(d) returning None is now treated as naive by the
     astimezone() method.

   - bpo-30805(3): Avoid race condition with debug logging

   - bpo-33767(4): The concatenation (‘+’) and repetition (‘*’) sequence
     operations now raise *note TypeError: 1fe. instead of *note
     SystemError: 6f2. when performed on *note mmap.mmap: 31c. objects.
     Patch by Zackery Spytz.

   - bpo-32684(5): Fix gather to propagate cancellation of itself even
     with return_exceptions.

   - bpo-33674(6): 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.

   - bpo-31647(7): Fixed bug where calling write_eof() on a
     _SelectorSocketTransport after it’s already closed raises
     AttributeError.

   - bpo-33672(8): Fix Task.__repr__ crash with Cython’s bogus
     coroutines

   - bpo-33469(9): Fix RuntimeError after closing loop that used
     run_in_executor

   - bpo-11874(10): Use a better regex when breaking usage into
     wrappable parts.  Avoids bogus assertion errors from custom metavar
     strings.

   - bpo-30877(11): 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.

   - bpo-33548(12): tempfile._candidate_tempdir_list should consider
     common TEMP locations

   - bpo-33542(13): Prevent ‘uuid.get_node’ from using a DUID instead of
     a MAC on Windows.  Patch by Zvi Effron

   - bpo-26819(14): Fix race condition with
     ‘ReadTransport.resume_reading’ in Windows proactor event loop.

   - bpo-28556(15): Minor fixes in typing module: add annotations to
     ‘NamedTuple.__new__’, pass ‘*args’ and ‘**kwds’ in
     ‘Generic.__new__’.  Original PRs by Paulius Šarka and Chad
     Dombrova.

   - bpo-20087(16): Updated alias mapping with glibc 2.27 supported
     locales.

   - bpo-33422(17): Fix trailing quotation marks getting deleted when
     looking up byte/string literals on pydoc.  Patch by Andrés Delfino.

   - bpo-33197(18): Update error message when constructing invalid
     inspect.Parameters Patch by Dong-hee Na.

   - bpo-33383(19): Fixed crash in the get() method of the *note
     dbm.ndbm: 34. database object when it is called with a single
     argument.

   - bpo-33329(20): Fix multiprocessing regression on newer glibcs

   - bpo-991266(21): Fix quoting of the ‘Comment’ attribute of *note
     http.cookies.SimpleCookie: 116e.

   - bpo-33131(22): Upgrade bundled version of pip to 10.0.1.

   - bpo-33308(23): Fixed a crash in the *note parser: c7. module when
     converting an ST object to a tree of tuples or lists with
     ‘line_info=False’ and ‘col_info=True’.

   - bpo-33263(24): Fix FD leak in ‘_SelectorSocketTransport’ Patch by
     Vlad Starostin.

   - bpo-33256(25): Fix display of ‘<module>’ call in the html produced
     by ‘cgitb.html()’.  Patch by Stéphane Blondon.

   - bpo-33203(26): ‘random.Random.choice()’ now raises ‘IndexError’ for
     empty sequences consistently even when called from subclasses
     without a ‘getrandbits()’ implementation.

   - bpo-33224(27): Update difflib.mdiff() for PEP 479(28).  Convert an
     uncaught StopIteration in a generator into a return-statement.

   - bpo-33209(29): End framing at the end of C implementation of *note
     pickle.Pickler.dump(): 1172.

   - bpo-32861(30): The urllib.robotparser’s ‘__str__’ representation
     now includes wildcard entries and the "Crawl-delay" and
     "Request-rate" fields.  Patch by Michael Lazar.

   - bpo-33096(31): 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.

   - bpo-33127(32): ssl模块现在使用LibreSSL 2.7.1编译。

   - bpo-33021(33): Release the GIL during fstat() calls, avoiding hang
     of all threads when calling mmap.mmap(), os.urandom(), and
     random.seed().  Patch by Nir Soffer.

   - bpo-27683(34): Fix a regression in *note ipaddress: a2. that result
     of ‘hosts()’ is empty when the network is constructed by a tuple
     containing an integer mask and only 1 bit left for addresses.

   - bpo-32844(35): Fix wrong redirection of a low descriptor (0 or 1)
     to stderr in subprocess if another low descriptor is closed.

   - bpo-31908(36): Fix output of cover files for ‘trace’ module
     command-line tool.  Previously emitted cover files only when
     ‘--missing’ option was used.  Patch by Michael Selik.

   - bpo-31457(37): If nested log adapters are used, the inner
     ‘process()’ methods are no longer omitted.

   - bpo-16865(38): Support arrays >=2GiB in *note ctypes: 2a.  Patch by
     Segev Finer.

   - bpo-31238(39): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30167

   (2) https://bugs.python.org/issue33812

   (3) https://bugs.python.org/issue30805

   (4) https://bugs.python.org/issue33767

   (5) https://bugs.python.org/issue32684

   (6) https://bugs.python.org/issue33674

   (7) https://bugs.python.org/issue31647

   (8) https://bugs.python.org/issue33672

   (9) https://bugs.python.org/issue33469

   (10) https://bugs.python.org/issue11874

   (11) https://bugs.python.org/issue30877

   (12) https://bugs.python.org/issue33548

   (13) https://bugs.python.org/issue33542

   (14) https://bugs.python.org/issue26819

   (15) https://bugs.python.org/issue28556

   (16) https://bugs.python.org/issue20087

   (17) https://bugs.python.org/issue33422

   (18) https://bugs.python.org/issue33197

   (19) https://bugs.python.org/issue33383

   (20) https://bugs.python.org/issue33329

   (21) https://bugs.python.org/issue991266

   (22) https://bugs.python.org/issue33131

   (23) https://bugs.python.org/issue33308

   (24) https://bugs.python.org/issue33263

   (25) https://bugs.python.org/issue33256

   (26) https://bugs.python.org/issue33203

   (27) https://bugs.python.org/issue33224

   (28) https://www.python.org/dev/peps/pep-0479

   (29) https://bugs.python.org/issue33209

   (30) https://bugs.python.org/issue32861

   (31) https://bugs.python.org/issue33096

   (32) https://bugs.python.org/issue33127

   (33) https://bugs.python.org/issue33021

   (34) https://bugs.python.org/issue27683

   (35) https://bugs.python.org/issue32844

   (36) https://bugs.python.org/issue31908

   (37) https://bugs.python.org/issue31457

   (38) https://bugs.python.org/issue16865

   (39) https://bugs.python.org/issue31238


File: python.info,  Node: 文档<36>,  Next: 测试<33>,  Prev: 库<42>,  Up: Python 3 6 6 rc1

1.19.44.3 文档
..............

   - bpo-33503(1): 修复错误的pypi链接

   - bpo-33421(2): 为‘‘typing.AsyncContextManager‘‘添加缺失的文档。

   - bpo-33378(3): Add Korean language switcher for
     ‘https://docs.python.org/3/’

   - bpo-33276(4): Clarify that the ‘__path__’ attribute on modules
     cannot be just any value.

   - bpo-33201(5): Modernize documentation for writing C extension
     types.

   - bpo-33195(6): Deprecate ‘Py_UNICODE’ usage in ‘c-api/arg’ document.
     ‘Py_UNICODE’ related APIs are deprecated since Python 3.3, but it
     is missed in the document.

   - bpo-33126(7): Document PyBuffer_ToContiguous().

   - bpo-27212(8): Modify documentation for the ‘islice()’ recipe to
     consume initial values up to the start index.

   - bpo-28247(9): Update *note zipapp: 14a. documentation to describe
     how to make standalone applications.

   - bpo-18802(10): Documentation changes for ipaddress.  Patch by Jon
     Foster and Berker Peksag.

   - bpo-27428(11): Update documentation to clarify that
     ‘WindowsRegistryFinder’ implements ‘MetaPathFinder’.  (Patch by
     Himanshu Lakhara)

   - bpo-8243(12): Add a note about curses.addch and curses.addstr
     exception behavior when writing outside a window, or pad.

   - bpo-31432(13): Clarify meaning of CERT_NONE, CERT_OPTIONAL, and
     CERT_REQUIRED flags for ssl.SSLContext.verify_mode.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33503

   (2) https://bugs.python.org/issue33421

   (3) https://bugs.python.org/issue33378

   (4) https://bugs.python.org/issue33276

   (5) https://bugs.python.org/issue33201

   (6) https://bugs.python.org/issue33195

   (7) https://bugs.python.org/issue33126

   (8) https://bugs.python.org/issue27212

   (9) https://bugs.python.org/issue28247

   (10) https://bugs.python.org/issue18802

   (11) https://bugs.python.org/issue27428

   (12) https://bugs.python.org/issue8243

   (13) https://bugs.python.org/issue31432


File: python.info,  Node: 测试<33>,  Next: 构建<33>,  Prev: 文档<36>,  Up: Python 3 6 6 rc1

1.19.44.4 测试
..............

   - bpo-33655(1): 忽略运行在BSD平台的ZFS上时test_posix_fallocate的失败
     。

   - bpo-19417(2): Add test_bdb.py.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33655

   (2) https://bugs.python.org/issue19417


File: python.info,  Node: 构建<33>,  Next: Windows<33>,  Prev: 测试<33>,  Up: Python 3 6 6 rc1

1.19.44.5 构建
..............

   - bpo-5755(1): Move ‘-Wstrict-prototypes’ option to ‘CFLAGS_NODIST’
     from ‘OPT’.  This option emitted annoying warnings when building
     extension modules written in C++.

   - bpo-33614(2): Ensures module definition files for the stable ABI on
     Windows are correctly regenerated.

   - bpo-33522(3): Enable CI builds on Visual Studio Team Services at
     ‘https://python.visualstudio.com/cpython’

   - bpo-33012(4): Add ‘-Wno-cast-function-type’ for gcc 8 for silencing
     warnings about function casts like casting to PyCFunction in method
     definition lists.

   - bpo-33394(5): Enable the verbose build for extension modules, when
     GNU make is passed macros on the command line.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5755

   (2) https://bugs.python.org/issue33614

   (3) https://bugs.python.org/issue33522

   (4) https://bugs.python.org/issue33012

   (5) https://bugs.python.org/issue33394


File: python.info,  Node: Windows<33>,  Next: macOS<27>,  Prev: 构建<33>,  Up: Python 3 6 6 rc1

1.19.44.6 Windows
.................

   - bpo-33184(1): 更新Windows 构建以使用OpenSSL 1.0.2o.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33184


File: python.info,  Node: macOS<27>,  Next: IDLE<33>,  Prev: Windows<33>,  Up: Python 3 6 6 rc1

1.19.44.7 macOS
...............

   - bpo-33184(1): 更新macOS 安装程序以使用OpenSSL 1.0.2o.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33184


File: python.info,  Node: IDLE<33>,  Next: 工具/示例<18>,  Prev: macOS<27>,  Up: Python 3 6 6 rc1

1.19.44.8 IDLE
..............

   - bpo-33656(1): 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.

   - bpo-33768(2): Clicking on a context line moves that line to the top
     of the editor window.

   - bpo-33763(3): IDLE: Use read-only text widget for code context
     instead of label widget.

   - bpo-33664(4): 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.

   - bpo-33679(5): 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.

   - bpo-33642(6): Display up to maxlines non-blank lines for Code
     Context.  If there is no current context, show a single blank line.

   - bpo-33628(7): IDLE: Cleanup codecontext.py and its test.

   - bpo-33564(8): IDLE’s code context now recognizes async as a block
     opener.

   - bpo-29706(9): IDLE now colors async and await as keywords in 3.6.
     They become full keywords in 3.7.

   - bpo-21474(10): 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.

   - bpo-33204(11): 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.

   - bpo-32831(12): Add docstrings and tests for codecontext.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33656

   (2) https://bugs.python.org/issue33768

   (3) https://bugs.python.org/issue33763

   (4) https://bugs.python.org/issue33664

   (5) https://bugs.python.org/issue33679

   (6) https://bugs.python.org/issue33642

   (7) https://bugs.python.org/issue33628

   (8) https://bugs.python.org/issue33564

   (9) https://bugs.python.org/issue29706

   (10) https://bugs.python.org/issue21474

   (11) https://bugs.python.org/issue33204

   (12) https://bugs.python.org/issue32831


File: python.info,  Node: 工具/示例<18>,  Next: C API<28>,  Prev: IDLE<33>,  Up: Python 3 6 6 rc1

1.19.44.9 工具/示例
...................

   - bpo-33189(1): ‘pygettext.py’ now recognizes only literal strings as
     docstrings and translatable strings, and rejects bytes literals and
     f-string expressions.

   - bpo-31920(2): Fixed handling directories as arguments in the
     ‘pygettext’ script.  Based on patch by Oleg Krasnikov.

   - bpo-29673(3): Fix pystackv and pystack gdbinit macros.

   - bpo-32885(4): Add an ‘-n’ flag for ‘Tools/scripts/pathfix.py’ to
     disable automatic backup creation (files with ‘~’ suffix).

   - bpo-31583(5): Fix 2to3 for using with –add-suffix option but
     without –output-dir option for relative path to files in current
     directory.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33189

   (2) https://bugs.python.org/issue31920

   (3) https://bugs.python.org/issue29673

   (4) https://bugs.python.org/issue32885

   (5) https://bugs.python.org/issue31583


File: python.info,  Node: C API<28>,  Prev: 工具/示例<18>,  Up: Python 3 6 6 rc1

1.19.44.10 C API
................

   - bpo-32374(1): Document that m_traverse for multi-phase initialized
     modules can be called with m_state=NULL, and add a sanity check

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32374


File: python.info,  Node: Python 3 6 5 正式版,  Next: Python 3 6 5 rc1,  Prev: Python 3 6 6 rc1,  Up: Changelog（更動日誌）

1.19.45 Python 3.6.5 正式版
---------------------------

`发布日期: 2018-03-28'

* Menu:

* 测试: 测试<34>.
* 构建: 构建<34>.


File: python.info,  Node: 测试<34>,  Next: 构建<34>,  Up: Python 3 6 5 正式版

1.19.45.1 测试
..............

   - bpo-32872(1): Avoid regrtest compatibility issue with namespace
     packages.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32872


File: python.info,  Node: 构建<34>,  Prev: 测试<34>,  Up: Python 3 6 5 正式版

1.19.45.2 构建
..............

   - bpo-33163(1): Upgrade pip to 9.0.3 and setuptools to v39.0.1.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33163


File: python.info,  Node: Python 3 6 5 rc1,  Next: Python 3 6 4 正式版,  Prev: Python 3 6 5 正式版,  Up: Changelog（更動日誌）

1.19.46 Python 3.6.5 rc1
------------------------

`发布日期: 2018-03-13'

* Menu:

* 安全性: 安全性<22>.
* 核心与内置函数: 核心与内置函数<40>.
* 库: 库<43>.
* 文档: 文档<37>.
* 测试: 测试<35>.
* 构建: 构建<35>.
* Windows: Windows<34>.
* macOS: macOS<28>.
* IDLE: IDLE<34>.
* 工具/示例: 工具/示例<19>.
* C API: C API<29>.


File: python.info,  Node: 安全性<22>,  Next: 核心与内置函数<40>,  Up: Python 3 6 5 rc1

1.19.46.1 安全性
................

   - bpo-33001(1): Minimal fix to prevent buffer overrun in os.symlink
     on Windows

   - bpo-32981(2): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33001

   (2) https://bugs.python.org/issue32981


File: python.info,  Node: 核心与内置函数<40>,  Next: 库<43>,  Prev: 安全性<22>,  Up: Python 3 6 5 rc1

1.19.46.2 核心与内置函数
........................

   - bpo-33026(1): Fixed jumping out of "with" block by setting
     f_lineno.

   - bpo-17288(2): Prevent jumps from ’return’ and ’exception’ trace
     events.

   - bpo-32889(3): Update Valgrind suppression list to account for the
     rename of ‘Py_ADDRESS_IN_RANG’ to ‘address_in_range’.

   - bpo-32650(4): Pdb and other debuggers dependent on bdb.py will
     correctly step over (next command) native coroutines.  Patch by
     Pablo Galindo.

   - bpo-32685(5): 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.

   - bpo-32583(6): Fix possible crashing in builtin Unicode decoders
     caused by write out-of-bound errors when using customized decode
     error handlers.

   - bpo-26163(7): Improved frozenset() hash to create more distinct
     hash values when faced with datasets containing many similar
     values.

   - bpo-27169(8): The ‘__debug__’ constant is now optimized out at
     compile time.  This fixes also bpo-22091(9).

   - bpo-32329(10): ‘sys.flags.hash_randomization’ is now properly set
     to 0 when hash randomization is turned off by ‘PYTHONHASHSEED=0’.

   - bpo-30416(11): The optimizer is now protected from spending much
     time doing complex calculations and consuming much memory for
     creating large constants in constant folding.

   - bpo-18533(12): ‘repr()’ on a dict containing its own ‘values()’ or
     ‘items()’ no longer raises ‘RecursionError’; OrderedDict similarly.
     Instead, use ‘...’, as for other recursive structures.  Patch by
     Ben North.

   - bpo-32028(13): Leading whitespace is now correctly ignored when
     generating suggestions for converting Py2 print statements to Py3
     builtin print function calls.  Patch by Sanyam Khurana.

   - bpo-32137(14): The repr of deeply nested dict now raises a
     RecursionError instead of crashing due to a stack overflow.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33026

   (2) https://bugs.python.org/issue17288

   (3) https://bugs.python.org/issue32889

   (4) https://bugs.python.org/issue32650

   (5) https://bugs.python.org/issue32685

   (6) https://bugs.python.org/issue32583

   (7) https://bugs.python.org/issue26163

   (8) https://bugs.python.org/issue27169

   (9) https://bugs.python.org/issue22091

   (10) https://bugs.python.org/issue32329

   (11) https://bugs.python.org/issue30416

   (12) https://bugs.python.org/issue18533

   (13) https://bugs.python.org/issue32028

   (14) https://bugs.python.org/issue32137


File: python.info,  Node: 库<43>,  Next: 文档<37>,  Prev: 核心与内置函数<40>,  Up: Python 3 6 5 rc1

1.19.46.3 库
............

   - bpo-33064(1): lib2to3 now properly supports trailing commas after
     ‘*args’ and ‘**kwargs’ in function signatures.

   - bpo-31804(2): Avoid failing in multiprocessing.Process if the
     standard streams are closed or None at exit.

   - bpo-33037(3): Skip sending/receiving data after SSL transport
     closing.

   - bpo-30353(4): Fix ctypes pass-by-value for structs on 64-bit
     Cygwin/MinGW.

   - bpo-33009(5): Fix inspect.signature() for single-parameter
     partialmethods.

   - bpo-32969(6): Expose several missing constants in zlib and fix
     corresponding documentation.

   - bpo-32713(7): Fixed tarfile.itn handling of out-of-bounds float
     values.  Patch by Joffrey Fuhrer.

   - bpo-30622(8): The ssl module now detects missing NPN support in
     LibreSSL.

   - bpo-32922(9): dbm.open() now encodes filename with the filesystem
     encoding rather than default encoding.

   - bpo-32859(10): In ‘os.dup2’, don’t check every call whether the
     ‘dup3’ syscall exists or not.

   - bpo-21060(11): 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".

   - bpo-32857(12): In *note tkinter: 10e, ‘after_cancel(None)’ now
     raises a *note ValueError: 16d. instead of canceling the first
     scheduled function.  Patch by Cheryl Sabella.

   - bpo-32852(13): Make sure sys.argv remains as a list when running
     trace.

   - bpo-32841(14): Fixed *note asyncio.Condition: 3b0. issue which
     silently ignored cancellation after notifying and cancelling a
     conditional lock.  Patch by Bar Harel.

   - bpo-31787(15): Fixed refleaks of ‘__init__()’ methods in various
     modules.  (Contributed by Oren Milman)

   - bpo-30157(16): Fixed guessing quote and delimiter in
     csv.Sniffer.sniff() when only the last field is quoted.  Patch by
     Jake Davis.

   - bpo-32394(17): socket: Remove TCP_FASTOPEN, TCP_KEEPCNT flags on
     older version Windows during run-time.

   - bpo-32777(18): 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.

   - bpo-32647(19): The ctypes module used to depend on indirect linking
     for dlopen.  The shared extension is now explicitly linked against
     libdl on platforms with dl.

   - bpo-32734(20): Fixed ‘asyncio.Lock()’ safety issue which allowed
     acquiring and locking the same lock multiple times, without it
     being free.  Patch by Bar Harel.

   - bpo-32727(21): Do not include name field in SMTP envelope from
     address.  Patch by Stéphane Wirtel

   - bpo-27931(22): Fix email address header parsing error when the
     username is an empty quoted string.  Patch by Xiang Zhang.

   - bpo-32304(23): 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.

   - bpo-32502(24): uuid.uuid1 no longer raises an exception if a 64-bit
     hardware address is encountered.

   - bpo-31848(25): Fix the error handling in Aifc_read.initfp() when
     the SSND chunk is not found.  Patch by Zackery Spytz.

   - bpo-32555(26): 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.

   - bpo-32521(27): The nis module is now compatible with new libnsl and
     headers location.

   - bpo-32473(28): Improve ABCMeta._dump_registry() output readability

   - bpo-32521(29): glibc has removed Sun RPC. Use replacement libtirpc
     headers and library in nis module.

   - bpo-32228(30): Ensure that ‘truncate()’ preserves the file position
     (as reported by ‘tell()’) after writes longer than the buffer size.

   - bpo-26133(31): Don’t unsubscribe signals in asyncio UNIX event loop
     on interpreter shutdown.

   - bpo-32185(32): The SSL module no longer sends IP addresses in SNI
     TLS extension on platforms with OpenSSL 1.0.2+ or inet_pton.

   - bpo-32323(33): *note urllib.parse.urlsplit(): 6f0. does not convert
     zone-id (scope) to lower case for scoped IPv6 addresses in
     hostnames now.

   - bpo-32302(34): Fix bdist_wininst of distutils for CRT v142: it
     binary compatible with CRT v140.

   - bpo-32255(35): 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.

   - bpo-32277(36): Raise ‘NotImplementedError’ instead of ‘SystemError’
     on platforms where ‘chmod(..., follow_symlinks=False)’ is not
     supported.  Patch by Anthony Sottile.

   - bpo-32199(37): The getnode() ip getter now uses ’ip link’ instead
     of ’ip link list’.

   - bpo-27456(38): Ensure TCP_NODELAY is set on Linux.  Tests by Victor
     Stinner.

   - bpo-31900(39): The *note locale.localeconv(): 584. function now
     sets temporarily the ‘LC_CTYPE’ locale to the ‘LC_NUMERIC’ locale
     to decode ‘decimal_point’ and ‘thousands_sep’ byte strings if they
     are non-ASCII or longer than 1 byte, and the ‘LC_NUMERIC’ locale is
     different than the ‘LC_CTYPE’ locale.  This temporary change
     affects other threads.  Same change for the *note str.format():
     5d4. method when formatting a number (*note int: 204, *note float:
     1fd, *note float: 1fd. and subclasses) with the ‘n’ type (ex:
     ‘'{:n}'.format(1234)’).

   - bpo-31802(40): Importing native path module (‘posixpath’, ‘ntpath’)
     now works even if the ‘os’ module still is not imported.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33064

   (2) https://bugs.python.org/issue31804

   (3) https://bugs.python.org/issue33037

   (4) https://bugs.python.org/issue30353

   (5) https://bugs.python.org/issue33009

   (6) https://bugs.python.org/issue32969

   (7) https://bugs.python.org/issue32713

   (8) https://bugs.python.org/issue30622

   (9) https://bugs.python.org/issue32922

   (10) https://bugs.python.org/issue32859

   (11) https://bugs.python.org/issue21060

   (12) https://bugs.python.org/issue32857

   (13) https://bugs.python.org/issue32852

   (14) https://bugs.python.org/issue32841

   (15) https://bugs.python.org/issue31787

   (16) https://bugs.python.org/issue30157

   (17) https://bugs.python.org/issue32394

   (18) https://bugs.python.org/issue32777

   (19) https://bugs.python.org/issue32647

   (20) https://bugs.python.org/issue32734

   (21) https://bugs.python.org/issue32727

   (22) https://bugs.python.org/issue27931

   (23) https://bugs.python.org/issue32304

   (24) https://bugs.python.org/issue32502

   (25) https://bugs.python.org/issue31848

   (26) https://bugs.python.org/issue32555

   (27) https://bugs.python.org/issue32521

   (28) https://bugs.python.org/issue32473

   (29) https://bugs.python.org/issue32521

   (30) https://bugs.python.org/issue32228

   (31) https://bugs.python.org/issue26133

   (32) https://bugs.python.org/issue32185

   (33) https://bugs.python.org/issue32323

   (34) https://bugs.python.org/issue32302

   (35) https://bugs.python.org/issue32255

   (36) https://bugs.python.org/issue32277

   (37) https://bugs.python.org/issue32199

   (38) https://bugs.python.org/issue27456

   (39) https://bugs.python.org/issue31900

   (40) https://bugs.python.org/issue31802


File: python.info,  Node: 文档<37>,  Next: 测试<35>,  Prev: 库<43>,  Up: Python 3 6 5 rc1

1.19.46.4 文档
..............

   - bpo-17232(1): Clarify docs for -O and -OO. Patch by Terry Reedy.

   - bpo-32800(2): Update link to w3c doc for xml default namespaces.

   - bpo-8722(3): Document *note __getattr__(): 42a. behavior when
     property ‘get()’ method raises *note AttributeError: 4a1.

   - bpo-32614(4): Modify RE examples in documentation to use raw
     strings to prevent *note DeprecationWarning: 15a. and add text to
     REGEX HOWTO to highlight the deprecation.

   - bpo-31972(5): Improve docstrings for *note pathlib.PurePath: 235.
     subclasses.

   - bpo-17799(6): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17232

   (2) https://bugs.python.org/issue32800

   (3) https://bugs.python.org/issue8722

   (4) https://bugs.python.org/issue32614

   (5) https://bugs.python.org/issue31972

   (6) https://bugs.python.org/issue17799


File: python.info,  Node: 测试<35>,  Next: 构建<35>,  Prev: 文档<37>,  Up: Python 3 6 5 rc1

1.19.46.5 测试
..............

   - bpo-32517(1): Fix failing ‘test_asyncio’ on macOS 10.12.2+ due to
     transport of ‘KqueueSelector’ loop was not being closed.

   - bpo-32721(2): Fix test_hashlib to not fail if the _md5 module is
     not built.

   - bpo-32252(3): Fix faulthandler_suppress_crash_report() used to
     prevent core dump files when testing crashes.  getrlimit() returns
     zero on success.

   - bpo-31518(4): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32517

   (2) https://bugs.python.org/issue32721

   (3) https://bugs.python.org/issue32252

   (4) https://bugs.python.org/issue31518


File: python.info,  Node: 构建<35>,  Next: Windows<34>,  Prev: 测试<35>,  Up: Python 3 6 5 rc1

1.19.46.6 构建
..............

   - bpo-32635(1): Fix segfault of the crypt module when libxcrypt is
     provided instead of libcrypt at the system.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32635


File: python.info,  Node: Windows<34>,  Next: macOS<28>,  Prev: 构建<35>,  Up: Python 3 6 5 rc1

1.19.46.7 Windows
.................

   - bpo-33016(1): Fix potential use of uninitialized memory in
     nt._getfinalpathname

   - bpo-32903(2): Fix a memory leak in os.chdir() on Windows if the
     current directory is set to a UNC path.

   - bpo-31966(3): Fixed WindowsConsoleIO.write() for writing empty
     data.

   - bpo-32409(4): Ensures activate.bat can handle Unicode contents.

   - bpo-32457(5): Improves handling of denormalized executable path
     when launching Python.

   - bpo-32370(6): Use the correct encoding for ipconfig output in the
     uuid module.  Patch by Segev Finer.

   - bpo-29248(7): Fix *note os.readlink(): 1d1. on Windows, which was
     mistakenly treating the ‘PrintNameOffset’ field of the reparse data
     buffer as a number of characters instead of bytes.  Patch by Craig
     Holmquist and SSE4.

   - bpo-32588(8): Create standalone _distutils_findvs module.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33016

   (2) https://bugs.python.org/issue32903

   (3) https://bugs.python.org/issue31966

   (4) https://bugs.python.org/issue32409

   (5) https://bugs.python.org/issue32457

   (6) https://bugs.python.org/issue32370

   (7) https://bugs.python.org/issue29248

   (8) https://bugs.python.org/issue32588


File: python.info,  Node: macOS<28>,  Next: IDLE<34>,  Prev: Windows<34>,  Up: Python 3 6 5 rc1

1.19.46.8 macOS
...............

   - bpo-32726(1): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32726


File: python.info,  Node: IDLE<34>,  Next: 工具/示例<19>,  Prev: macOS<28>,  Up: Python 3 6 5 rc1

1.19.46.9 IDLE
..............

   - bpo-32984(1): Set ‘__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,
     ‘-s’ runs a file named in environmental variable ‘IDLESTARTUP’ or
     *note PYTHONSTARTUP: 9cb.; ‘-r file’ runs ‘file’.  Python sets
     ‘__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 ‘-n’ option.

   - bpo-32940(2): Simplify and rename StringTranslatePseudoMapping in
     pyparse.

   - bpo-32916(3): Change ‘str’ to ‘code’ in pyparse.

   - bpo-32905(4): Remove unused code in pyparse module.

   - bpo-32874(5): Add tests for pyparse.

   - bpo-32837(6): Using the system and place-dependent default encoding
     for open() is a bad idea for IDLE’s system and location-independent
     files.

   - bpo-32826(7): 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.

   - bpo-32765(8): Update configdialog General tab docstring to add new
     widgets to the widget list.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32984

   (2) https://bugs.python.org/issue32940

   (3) https://bugs.python.org/issue32916

   (4) https://bugs.python.org/issue32905

   (5) https://bugs.python.org/issue32874

   (6) https://bugs.python.org/issue32837

   (7) https://bugs.python.org/issue32826

   (8) https://bugs.python.org/issue32765


File: python.info,  Node: 工具/示例<19>,  Next: C API<29>,  Prev: IDLE<34>,  Up: Python 3 6 5 rc1

1.19.46.10 工具/示例
....................

   - bpo-24960(1): 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.

   - bpo-32222(2): Fix pygettext not extracting docstrings for functions
     with type annotated arguments.  Patch by Toby Harradine.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24960

   (2) https://bugs.python.org/issue32222


File: python.info,  Node: C API<29>,  Prev: 工具/示例<19>,  Up: Python 3 6 5 rc1

1.19.46.11 C API
................

   - bpo-29084(1): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29084


File: python.info,  Node: Python 3 6 4 正式版,  Next: Python 3 6 4 rc1,  Prev: Python 3 6 5 rc1,  Up: Changelog（更動日誌）

1.19.47 Python 3.6.4 正式版
---------------------------

`发布日期: 2017-12-18'

从 3.6.4 rc1 到 3.6.4 正式版中没有新的代码更改。


File: python.info,  Node: Python 3 6 4 rc1,  Next: Python 3 6 3 正式版,  Prev: Python 3 6 4 正式版,  Up: Changelog（更動日誌）

1.19.48 Python 3.6.4 rc1
------------------------

`发布日期: 2017-12-05'

* Menu:

* 核心与内置函数: 核心与内置函数<41>.
* 库: 库<44>.
* 文档: 文档<38>.
* 测试: 测试<36>.
* 构建: 构建<36>.
* Windows: Windows<35>.
* macOS: macOS<29>.
* IDLE: IDLE<35>.
* 工具/示例: 工具/示例<20>.
* C API: C API<30>.


File: python.info,  Node: 核心与内置函数<41>,  Next: 库<44>,  Up: Python 3 6 4 rc1

1.19.48.1 核心与内置函数
........................

   - bpo-32176(1): 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.

   - bpo-31949(2): 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 ‘2**31’ traceback items on Windows.  Fixed output
     errors handling.

   - bpo-30696(3): Fix the interactive interpreter looping endlessly
     when no memory.

   - bpo-20047(4): 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.

   - bpo-31852(5): Fix a segmentation fault caused by a combination of
     the async soft keyword and continuation lines.

   - bpo-21720(6): BytesWarning no longer emitted when the `fromlist'
     argument of ‘__import__()’ or the ‘__all__’ attribute of the module
     contain bytes instances.

   - bpo-31825(7): Fixed OverflowError in the ’unicode-escape’ codec and
     in codecs.escape_decode() when decode an escaped non-ascii byte.

   - bpo-28603(8): 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.

   - bpo-31786(9): 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.

   - bpo-31642(10): Restored blocking "from package import module" by
     setting sys.modules["package.module"] to None.

   - bpo-31626(11): Fixed a bug in debug memory allocator.  There was a
     write to freed memory after shrinking a memory block.

   - bpo-31619(12): Fixed a ValueError when convert a string with large
     number of underscores to integer with binary base.

   - bpo-31592(13): Fixed an assertion failure in Python parser in case
     of a bad *note unicodedata.normalize(): 11e4.  Patch by Oren
     Milman.

   - bpo-31588(14): Raise a *note TypeError: 1fe. with a helpful error
     message when class creation fails due to a metaclass with a bad
     ‘__prepare__()’ method.  Patch by Oren Milman.

   - bpo-31566(15): Fix an assertion failure in ‘_warnings.warn()’ in
     case of a bad ‘__name__’ global.  Patch by Oren Milman.

   - bpo-31505(16): Fix an assertion failure in *note json: a4, in case
     ‘_json.make_encoder()’ received a bad ‘encoder()’ argument.  Patch
     by Oren Milman.

   - bpo-31492(17): Fix assertion failures in case of failing to import
     from a module with a bad ‘__name__’ attribute, and in case of
     failing to access an attribute of such a module.  Patch by Oren
     Milman.

   - bpo-31490(18): Fix an assertion failure in *note ctypes: 2a. class
     definition, in case the class has an attribute whose name is
     specified in ‘_anonymous_’ but not in ‘_fields_’.  Patch by Oren
     Milman.

   - bpo-31478(19): Fix an assertion failure in ‘_random.Random.seed()’
     in case the argument has a bad ‘__abs__()’ method.  Patch by Oren
     Milman.

   - bpo-31315(20): Fix an assertion failure in imp.create_dynamic(),
     when spec.name is not a string.  Patch by Oren Milman.

   - bpo-31311(21): Fix a crash in the ‘__setstate__()’ method of *note
     ctypes._CData: 11e5, in case of a bad ‘__dict__’.  Patch by Oren
     Milman.

   - bpo-31293(22): 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.

   - bpo-31285(23): Fix an assertion failure in *note
     warnings.warn_explicit: 6a7, when the return value of the received
     loader’s get_source() has a bad splitlines() method.  Patch by Oren
     Milman.

   - bpo-30817(24): ‘PyErr_PrintEx()’ clears now the ignored exception
     that may be raised by ‘_PySys_SetObjectId()’, for example when no
     memory.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32176

   (2) https://bugs.python.org/issue31949

   (3) https://bugs.python.org/issue30696

   (4) https://bugs.python.org/issue20047

   (5) https://bugs.python.org/issue31852

   (6) https://bugs.python.org/issue21720

   (7) https://bugs.python.org/issue31825

   (8) https://bugs.python.org/issue28603

   (9) https://bugs.python.org/issue31786

   (10) https://bugs.python.org/issue31642

   (11) https://bugs.python.org/issue31626

   (12) https://bugs.python.org/issue31619

   (13) https://bugs.python.org/issue31592

   (14) https://bugs.python.org/issue31588

   (15) https://bugs.python.org/issue31566

   (16) https://bugs.python.org/issue31505

   (17) https://bugs.python.org/issue31492

   (18) https://bugs.python.org/issue31490

   (19) https://bugs.python.org/issue31478

   (20) https://bugs.python.org/issue31315

   (21) https://bugs.python.org/issue31311

   (22) https://bugs.python.org/issue31293

   (23) https://bugs.python.org/issue31285

   (24) https://bugs.python.org/issue30817


File: python.info,  Node: 库<44>,  Next: 文档<38>,  Prev: 核心与内置函数<41>,  Up: Python 3 6 4 rc1

1.19.48.2 库
............

   - bpo-28556(1): Two minor fixes for ‘typing’ module: allow shallow
     copying instances of generic classes, improve interaction of
     ‘__init_subclass__’ with generics.  Original PRs by Ivan
     Levkivskyi.

   - bpo-27240(2): The header folding algorithm for the new email
     policies has been rewritten, which also fixes bpo-30788(3),
     bpo-31831(4), and bpo-32182(5).  In particular, RFC2231 folding is
     now done correctly.

   - bpo-32186(6): 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.

   - bpo-12239(7): Make *note msilib.SummaryInformation.GetProperty():
     10fe. return ‘None’ when the value of property is ‘VT_EMPTY’.
     Initial patch by Mark Mc Mahon.

   - bpo-31325(8): Fix wrong usage of *note collections.namedtuple():
     1a1. in the *note RobotFileParser.parse(): 11d6. method.  Initial
     patch by Robin Wellner.

   - bpo-12382(9): *note msilib.OpenDatabase(): 1020. now raises a
     better exception message when it couldn’t open or create an MSI
     file.  Initial patch by William Tisäter.

   - bpo-32110(10): ‘codecs.StreamReader.read(n)’ now returns not more
     than `n' characters/bytes for non-negative `n'.  This makes it
     compatible with ‘read()’ methods of other file-like objects.

   - bpo-32072(11): 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.

   - bpo-32034(12): Make asyncio.IncompleteReadError and
     LimitOverrunError pickleable.

   - bpo-32015(13): Fixed the looping of asyncio in the case of
     reconnection the socket during waiting async read/write from/to the
     socket.

   - bpo-32011(14): Restored support of loading marshal files with the
     TYPE_INT64 code.  These files can be produced in Python 2.7.

   - bpo-31970(15): Reduce performance overhead of asyncio debug mode.

   - bpo-9678(16): 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.

   - bpo-30057(17): Fix potential missed signal in signal.signal().

   - bpo-31933(18): Fix Blake2 params leaf_size and node_offset on big
     endian platforms.  Patch by Jack O’Connor.

   - bpo-31927(19): 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.

   - bpo-27666(20): 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.

   - bpo-31897(21): plistlib now catches more errors when read binary
     plists and raises InvalidFileException instead of unexpected
     exceptions.

   - bpo-25720(22): Fix the method for checking pad state of curses
     WINDOW. Patch by Masayuki Yamamoto.

   - bpo-31893(23): Fixed the layout of the kqueue_event structure on
     OpenBSD and NetBSD. Fixed the comparison of the kqueue_event
     objects.

   - bpo-31891(24): Fixed building the curses module on NetBSD.

   - bpo-28416(25): Instances of pickle.Pickler subclass with the
     persistent_id() method and pickle.Unpickler subclass with the
     persistent_load() method no longer create reference cycles.

   - bpo-28326(26): Fix multiprocessing.Process when stdout and/or
     stderr is closed or None.

   - bpo-31457(27): If nested log adapters are used, the inner
     ‘process()’ methods are no longer omitted.

   - bpo-31457(28): The ‘manager’ property on LoggerAdapter objects is
     now properly settable.

   - bpo-31806(29): 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.

   - bpo-28603(30): 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.

   - bpo-30058(31): Fixed buffer overflow in select.kqueue.control().

   - bpo-31770(32): Prevent a crash when calling the ‘__init__()’ method
     of a ‘sqlite3.Cursor’ object more than once.  Patch by Oren Milman.

   - bpo-31672(33): ‘idpattern’ in ‘string.Template’ matched some
     non-ASCII characters.  Now it uses ‘-i’ regular expression local
     flag to avoid non-ASCII characters.

   - bpo-31764(34): Prevent a crash in ‘sqlite3.Cursor.close()’ in case
     the ‘Cursor’ object is uninitialized.  Patch by Oren Milman.

   - bpo-31752(35): Fix possible crash in timedelta constructor called
     with custom integers.

   - bpo-31701(36): On Windows, faulthandler.enable() now ignores MSC
     and COM exceptions.

   - bpo-31728(37): Prevent crashes in ‘_elementtree’ due to unsafe
     cleanup of ‘Element.text’ and ‘Element.tail’.  Patch by Oren
     Milman.

   - bpo-31620(38): an empty asyncio.Queue now doesn’t leak memory when
     queue.get pollers timeout

   - bpo-31632(39): Fix method set_protocol() of class
     _SSLProtocolTransport in asyncio module.  This method was
     previously modifying a wrong reference to the protocol.

   - bpo-31675(40): Fixed memory leaks in Tkinter’s methods splitlist()
     and split() when pass a string larger than 2 GiB.

   - bpo-31673(41): Fixed typo in the name of Tkinter’s method
     adderrorinfo().

   - bpo-30806(42): Fix the string representation of a netrc object.

   - bpo-15037(43): Added a workaround for getkey() in curses for
     ncurses 5.7 and earlier.

   - bpo-25351(44): Avoid venv activate failures with undefined
     variables

   - bpo-25532(45): 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.

   - bpo-30347(46): Stop crashes when concurrently iterate over
     itertools.groupby() iterators.

   - bpo-31516(47): ‘threading.current_thread()’ should not return a
     dummy thread at shutdown.

   - bpo-31351(48): python -m ensurepip now exits with non-zero exit
     code if pip bootstrapping has failed.

   - bpo-31482(49): ‘random.seed()’ now works with bytes in version=1

   - bpo-31334(50): Fix ‘poll.poll([timeout])’ in the ‘select’ module
     for arbitrary negative timeouts on all OSes where it can only be a
     non-negative integer or -1.  Patch by Riccardo Coccioli.

   - bpo-31310(51): multiprocessing’s semaphore tracker should be
     launched again if crashed.

   - bpo-31308(52): Make multiprocessing’s forkserver process immune to
     Ctrl-C and other user interruptions.  If it crashes, restart it
     when necessary.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28556

   (2) https://bugs.python.org/issue27240

   (3) https://bugs.python.org/issue30788

   (4) https://bugs.python.org/issue31831

   (5) https://bugs.python.org/issue32182

   (6) https://bugs.python.org/issue32186

   (7) https://bugs.python.org/issue12239

   (8) https://bugs.python.org/issue31325

   (9) https://bugs.python.org/issue12382

   (10) https://bugs.python.org/issue32110

   (11) https://bugs.python.org/issue32072

   (12) https://bugs.python.org/issue32034

   (13) https://bugs.python.org/issue32015

   (14) https://bugs.python.org/issue32011

   (15) https://bugs.python.org/issue31970

   (16) https://bugs.python.org/issue9678

   (17) https://bugs.python.org/issue30057

   (18) https://bugs.python.org/issue31933

   (19) https://bugs.python.org/issue31927

   (20) https://bugs.python.org/issue27666

   (21) https://bugs.python.org/issue31897

   (22) https://bugs.python.org/issue25720

   (23) https://bugs.python.org/issue31893

   (24) https://bugs.python.org/issue31891

   (25) https://bugs.python.org/issue28416

   (26) https://bugs.python.org/issue28326

   (27) https://bugs.python.org/issue31457

   (28) https://bugs.python.org/issue31457

   (29) https://bugs.python.org/issue31806

   (30) https://bugs.python.org/issue28603

   (31) https://bugs.python.org/issue30058

   (32) https://bugs.python.org/issue31770

   (33) https://bugs.python.org/issue31672

   (34) https://bugs.python.org/issue31764

   (35) https://bugs.python.org/issue31752

   (36) https://bugs.python.org/issue31701

   (37) https://bugs.python.org/issue31728

   (38) https://bugs.python.org/issue31620

   (39) https://bugs.python.org/issue31632

   (40) https://bugs.python.org/issue31675

   (41) https://bugs.python.org/issue31673

   (42) https://bugs.python.org/issue30806

   (43) https://bugs.python.org/issue15037

   (44) https://bugs.python.org/issue25351

   (45) https://bugs.python.org/issue25532

   (46) https://bugs.python.org/issue30347

   (47) https://bugs.python.org/issue31516

   (48) https://bugs.python.org/issue31351

   (49) https://bugs.python.org/issue31482

   (50) https://bugs.python.org/issue31334

   (51) https://bugs.python.org/issue31310

   (52) https://bugs.python.org/issue31308


File: python.info,  Node: 文档<38>,  Next: 测试<36>,  Prev: 库<44>,  Up: Python 3 6 4 rc1

1.19.48.3 文档
..............

   - bpo-32105(1): Added asyncio.BaseEventLoop.connect_accepted_socket
     versionadded marker.

   - bpo-31537(2): Fix incorrect usage of ‘get_history_length’ in
     readline documentation example code.  Patch by Brad Smith.

   - bpo-30085(3): The operator functions without double underscores are
     preferred for clarity.  The one with underscores are only kept for
     back-compatibility.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32105

   (2) https://bugs.python.org/issue31537

   (3) https://bugs.python.org/issue30085


File: python.info,  Node: 测试<36>,  Next: 构建<36>,  Prev: 文档<38>,  Up: Python 3 6 4 rc1

1.19.48.4 测试
..............

   - bpo-31380(1): Skip test_httpservers test_undecodable_file on macOS:
     fails on APFS.

   - bpo-31705(2): 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.

   - bpo-31174(3): 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.

   - bpo-30695(4): Add the ‘set_nomemory(start, stop)’ and
     ‘remove_mem_hooks()’ functions to the _testcapi module.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31380

   (2) https://bugs.python.org/issue31705

   (3) https://bugs.python.org/issue31174

   (4) https://bugs.python.org/issue30695


File: python.info,  Node: 构建<36>,  Next: Windows<35>,  Prev: 测试<36>,  Up: Python 3 6 4 rc1

1.19.48.5 构建
..............

   - bpo-32059(1): ‘detect_modules()’ in ‘setup.py’ now also searches
     the sysroot paths when cross-compiling.

   - bpo-31957(2): Fixes Windows SDK version detection when building for
     Windows.

   - bpo-31609(3): Fixes quotes in PCbuild/clean.bat

   - bpo-31934(4): Abort the build when building out of a not clean
     source tree.

   - bpo-31926(5): 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.

   - bpo-28791(6): 更新 Windows 构建以使用 SQLite 3.21.0.

   - bpo-28791(7): 更新 OS X 安装程序以使用 SQLite 3.21.0.

   - bpo-22140(8): Prevent double substitution of prefix in
     python-config.sh.

   - bpo-31536(9): Avoid wholesale rebuild after ‘make regen-all’ if
     nothing changed.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32059

   (2) https://bugs.python.org/issue31957

   (3) https://bugs.python.org/issue31609

   (4) https://bugs.python.org/issue31934

   (5) https://bugs.python.org/issue31926

   (6) https://bugs.python.org/issue28791

   (7) https://bugs.python.org/issue28791

   (8) https://bugs.python.org/issue22140

   (9) https://bugs.python.org/issue31536


File: python.info,  Node: Windows<35>,  Next: macOS<29>,  Prev: 构建<36>,  Up: Python 3 6 4 rc1

1.19.48.6 Windows
.................

   - bpo-1102(1): Return ‘None’ when ‘View.Fetch()’ returns
     ‘ERROR_NO_MORE_ITEMS’ instead of raising ‘MSIError’.  Initial patch
     by Anthony Tuininga.

   - bpo-31944(2): Fixes Modify button in Apps and Features dialog.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue1102

   (2) https://bugs.python.org/issue31944


File: python.info,  Node: macOS<29>,  Next: IDLE<35>,  Prev: Windows<35>,  Up: Python 3 6 4 rc1

1.19.48.7 macOS
...............

   - bpo-31392(1): 更新 macOS 安装程序以使用OpenSSL 1.0.2m

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31392


File: python.info,  Node: IDLE<35>,  Next: 工具/示例<20>,  Prev: macOS<29>,  Up: Python 3 6 4 rc1

1.19.48.8 IDLE
..............

   - bpo-32207(1): 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.

   - bpo-32164(2): Delete unused file idlelib/tabbedpages.py.  Use of
     TabbedPageSet in configdialog was replaced by ttk.Notebook.

   - bpo-32100(3): IDLE: Fix old and new bugs in pathbrowser; improve
     tests.  Patch mostly by Cheryl Sabella.

   - bpo-31858(4): 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.

   - bpo-31860(5): The font sample in the IDLE configuration dialog is
     now editable.  Changes persist while IDLE remains open

   - bpo-31836(6): 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.

   - bpo-28603(7): Fix a TypeError that caused a shell restart when
     printing a traceback that includes an exception that is unhashable.
     Patch by Zane Bitter.

   - bpo-13802(8): 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.

   - bpo-31460(9): 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.

   - bpo-31649(10): IDLE - Make _htest, _utest parameters keyword only.

   - bpo-31559(11): Remove test order dependence in
     idle_test.test_browser.

   - bpo-31459(12): 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.

   - bpo-31500(13): Default fonts now are scaled on HiDPI displays.

   - bpo-1612262(14): IDLE module browser now shows nested classes and
     functions.  Original patches for code and tests by Guilherme Polo
     and Cheryl Sabella, respectively.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32207

   (2) https://bugs.python.org/issue32164

   (3) https://bugs.python.org/issue32100

   (4) https://bugs.python.org/issue31858

   (5) https://bugs.python.org/issue31860

   (6) https://bugs.python.org/issue31836

   (7) https://bugs.python.org/issue28603

   (8) https://bugs.python.org/issue13802

   (9) https://bugs.python.org/issue31460

   (10) https://bugs.python.org/issue31649

   (11) https://bugs.python.org/issue31559

   (12) https://bugs.python.org/issue31459

   (13) https://bugs.python.org/issue31500

   (14) https://bugs.python.org/issue1612262


File: python.info,  Node: 工具/示例<20>,  Next: C API<30>,  Prev: IDLE<35>,  Up: Python 3 6 4 rc1

1.19.48.9 工具/示例
...................

   - bpo-30722(1): Make redemo work with Python 3.6 and newer versions.
     Also, remove the ‘LOCALE’ option since it doesn’t work with string
     patterns in Python 3.  Patch by Christoph Sarnowski.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30722


File: python.info,  Node: C API<30>,  Prev: 工具/示例<20>,  Up: Python 3 6 4 rc1

1.19.48.10 C API
................

   - bpo-20891(1): 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.

   - bpo-31532(2): Fix memory corruption due to allocator mix in
     getpath.c between Py_GetPath() and Py_SetPath()

   - bpo-30697(3): The ‘PyExc_RecursionErrorInst’ singleton is removed
     and ‘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(4).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20891

   (2) https://bugs.python.org/issue31532

   (3) https://bugs.python.org/issue30697

   (4) https://bugs.python.org/issue22898


File: python.info,  Node: Python 3 6 3 正式版,  Next: Python 3 6 3 rc1,  Prev: Python 3 6 4 rc1,  Up: Changelog（更動日誌）

1.19.49 Python 3.6.3 正式版
---------------------------

`发布日期: 2017-10-03'

* Menu:

* 库: 库<45>.
* 构建: 构建<37>.


File: python.info,  Node: 库<45>,  Next: 构建<37>,  Up: Python 3 6 3 正式版

1.19.49.1 库
............

   - bpo-31641(1): Re-allow arbitrary iterables in *note
     concurrent.futures.as_completed(): 1223.  Fixes regression in
     3.6.3rc1.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31641


File: python.info,  Node: 构建<37>,  Prev: 库<45>,  Up: Python 3 6 3 正式版

1.19.49.2 构建
..............

   - bpo-31662(1): Fix typos in Windows ‘uploadrelease.bat’ script.  Fix
     Windows Doc build issues in ‘Doc/make.bat’.

   - bpo-31423(2): Fix building the PDF documentation with newer
     versions of Sphinx.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31662

   (2) https://bugs.python.org/issue31423


File: python.info,  Node: Python 3 6 3 rc1,  Next: Python 3 6 2 正式版,  Prev: Python 3 6 3 正式版,  Up: Changelog（更動日誌）

1.19.50 Python 3.6.3 rc1
------------------------

`发布日期: 2017-09-18'

* Menu:

* 安全性: 安全性<23>.
* 核心与内置函数: 核心与内置函数<42>.
* 库: 库<46>.
* 文档: 文档<39>.
* 测试: 测试<37>.
* 构建: 构建<38>.
* Windows: Windows<36>.
* IDLE: IDLE<36>.
* 工具/示例: 工具/示例<21>.


File: python.info,  Node: 安全性<23>,  Next: 核心与内置函数<42>,  Up: Python 3 6 3 rc1

1.19.50.1 安全性
................

   - bpo-29781(1): SSLObject.version() now correctly returns None when
     handshake over BIO has not been performed yet.

   - bpo-30947(2): Upgrade libexpat embedded copy from version 2.2.1 to
     2.2.3 to get security fixes.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29781

   (2) https://bugs.python.org/issue30947


File: python.info,  Node: 核心与内置函数<42>,  Next: 库<46>,  Prev: 安全性<23>,  Up: Python 3 6 3 rc1

1.19.50.2 核心与内置函数
........................

   - bpo-31471(1): Fix an assertion failure in *note subprocess.Popen():
     3db. on Windows, in case the env argument has a bad keys() method.
     Patch by Oren Milman.

   - bpo-31418(2): Fix an assertion failure in ‘PyErr_WriteUnraisable()’
     in case of an exception with a bad ‘__module__’ attribute.  Patch
     by Oren Milman.

   - bpo-31416(3): Fix assertion failures in case of a bad
     warnings.filters or warnings.defaultaction.  Patch by Oren Milman.

   - bpo-31411(4): Raise a TypeError instead of SystemError in case
     warnings.onceregistry is not a dictionary.  Patch by Oren Milman.

   - bpo-31373(5): Fix several possible instances of undefined behavior
     due to floating-point demotions.

   - bpo-30465(6): Location information (‘lineno’ and ‘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).

   - bpo-31343(7): Include sys/sysmacros.h for major(), minor(), and
     makedev().  GNU C libray plans to remove the functions from
     sys/types.h.

   - bpo-31291(8): Fix an assertion failure in *note
     zipimport.zipimporter.get_data: 11ef. on Windows, when the return
     value of ‘pathname.replace('/','\\')’ isn’t a string.  Patch by
     Oren Milman.

   - bpo-31271(9): Fix an assertion failure in the write() method of
     *note io.TextIOWrapper: 6ea, when the encoder doesn’t return a
     bytes object.  Patch by Oren Milman.

   - bpo-31243(10): Fix a crash in some methods of *note
     io.TextIOWrapper: 6ea, when the decoder’s state is invalid.  Patch
     by Oren Milman.

   - bpo-30721(11): ‘print’ now shows correct usage hint for using
     Python 2 redirection syntax.  Patch by Sanyam Khurana.

   - bpo-31070(12): Fix a race condition in importlib
     _get_module_lock().

   - bpo-31095(13): Fix potential crash during GC caused by ‘tp_dealloc’
     which doesn’t call ‘PyObject_GC_UnTrack()’.

   - bpo-31071(14): Avoid masking original TypeError in call with *
     unpacking when other arguments are passed.

   - bpo-30978(15): str.format_map() now passes key lookup exceptions
     through.  Previously any exception was replaced with a KeyError
     exception.

   - bpo-30808(16): Use _Py_atomic API for concurrency-sensitive signal
     state.

   - bpo-30876(17): 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.

   - bpo-30703(18): 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).

   - bpo-30765(19): Avoid blocking in pthread_mutex_lock() when
     PyThread_acquire_lock() is asked not to block.

   - bpo-31161(20): Make sure the ’Missing parentheses’ syntax error
     message is only applied to SyntaxError, not to subclasses.  Patch
     by Martijn Pieters.

   - bpo-30814(21): Fixed a race condition when import a submodule from
     a package.

   - bpo-30597(22): ‘print’ now shows expected input in custom error
     message when used as a Python 2 statement.  Patch by Sanyam
     Khurana.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31471

   (2) https://bugs.python.org/issue31418

   (3) https://bugs.python.org/issue31416

   (4) https://bugs.python.org/issue31411

   (5) https://bugs.python.org/issue31373

   (6) https://bugs.python.org/issue30465

   (7) https://bugs.python.org/issue31343

   (8) https://bugs.python.org/issue31291

   (9) https://bugs.python.org/issue31271

   (10) https://bugs.python.org/issue31243

   (11) https://bugs.python.org/issue30721

   (12) https://bugs.python.org/issue31070

   (13) https://bugs.python.org/issue31095

   (14) https://bugs.python.org/issue31071

   (15) https://bugs.python.org/issue30978

   (16) https://bugs.python.org/issue30808

   (17) https://bugs.python.org/issue30876

   (18) https://bugs.python.org/issue30703

   (19) https://bugs.python.org/issue30765

   (20) https://bugs.python.org/issue31161

   (21) https://bugs.python.org/issue30814

   (22) https://bugs.python.org/issue30597


File: python.info,  Node: 库<46>,  Next: 文档<39>,  Prev: 核心与内置函数<42>,  Up: Python 3 6 3 rc1

1.19.50.3 库
............

   - bpo-31499(1): xml.etree: Fix a crash when a parser is part of a
     reference cycle.

   - bpo-28556(2): typing.get_type_hints now finds the right globalns
     for classes and modules by default (when no ‘globalns’ was
     specified by the caller).

   - bpo-28556(3): Speed improvements to the ‘typing’ module.  Original
     PRs by Ivan Levkivskyi and Mitar.

   - bpo-31544(4): The C accelerator module of ElementTree ignored
     exceptions raised when looking up TreeBuilder target methods in
     XMLParser().

   - bpo-31234(5): socket.create_connection() now fixes manually a
     reference cycle: clear the variable storing the last exception on
     success.

   - bpo-31457(6): LoggerAdapter objects can now be nested.

   - bpo-31400(7): Improves SSL error handling to avoid losing error
     numbers.

   - bpo-28958(8): ssl.SSLContext() now uses OpenSSL error information
     when a context cannot be instantiated.

   - bpo-27340(9): 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.

   - bpo-31178(10): Fix string concatenation bug in rare error path in
     the subprocess module

   - bpo-31350(11): Micro-optimize ‘asyncio._get_running_loop()’ to
     become up to 10% faster.

   - bpo-31170(12): expat: Update libexpat from 2.2.3 to 2.2.4.  Fix
     copying of partial characters for UTF-8 input (libexpat bug 115):
     ‘https://github.com/libexpat/libexpat/issues/115’

   - bpo-29136(13): Add TLS 1.3 cipher suites and OP_NO_TLSv1_3.

   - bpo-29212(14): 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".

   - bpo-9146(15): 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.

   - bpo-27144(16): The ‘map()’ and ‘as_completed()’ iterators in
     ‘concurrent.futures’ now avoid keeping a reference to yielded
     objects.

   - bpo-10746(17): Fix ctypes producing wrong PEP 3118(18) type codes
     for integer types.

   - bpo-22536(19): The subprocess module now sets the filename when
     FileNotFoundError is raised on POSIX systems due to the executable
     or cwd not being found.

   - bpo-31249(20): concurrent.futures: WorkItem.run() used by
     ThreadPoolExecutor now breaks a reference cycle between an
     exception object and the WorkItem object.

   - bpo-31247(21): xmlrpc.server now explicitly breaks reference cycles
     when using sys.exc_info() in code handling exceptions.

   - bpo-30102(22): 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.

   - bpo-31185(23): Fixed miscellaneous errors in asyncio speedup
     module.

   - bpo-31135(24): 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.

   - bpo-31107(25): Fix ‘copyreg._slotnames()’ mangled attribute
     calculation for classes whose name begins with an underscore.
     Patch by Shane Harvey.

   - bpo-31061(26): Fixed a crash when using asyncio and threads.

   - bpo-30502(27): Fix handling of long oids in ssl.  Based on patch by
     Christian Heimes.

   - bpo-30119(28): ftplib.FTP.putline() now throws ValueError on
     commands that contains CR or LF. Patch by Dong-hee Na.

   - bpo-30595(29): 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.

   - bpo-29403(30): Fix ‘unittest.mock’’s autospec to not fail on
     method-bound builtin functions.  Patch by Aaron Gallagher.

   - bpo-30961(31): Fix decrementing a borrowed reference in
     tracemalloc.

   - bpo-25684(32): Change ‘ttk.OptionMenu’ radiobuttons to be unique
     across instances of ‘OptionMenu’.

   - bpo-30886(33): 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.

   - bpo-29854(34): Fix segfault in readline when using readline’s
     history-size option.  Patch by Nir Soffer.

   - bpo-30319(35): socket.close() now ignores ECONNRESET error.

   - bpo-30828(36): Fix out of bounds write in
     ‘asyncio.CFuture.remove_done_callback()’.

   - bpo-30807(37): 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.

   - bpo-30441(38): Fix bug when modifying os.environ while iterating
     over it

   - bpo-30532(39): Fix email header value parser dropping folding white
     space in certain cases.

   - bpo-30879(40): os.listdir() and os.scandir() now emit bytes names
     when called with bytes-like argument.

   - bpo-30746(41): Prohibited the ’=’ character in environment variable
     names in ‘os.putenv()’ and ‘os.spawn*()’.

   - bpo-29755(42): Fixed the lgettext() family of functions in the
     gettext module.  They now always return bytes.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31499

   (2) https://bugs.python.org/issue28556

   (3) https://bugs.python.org/issue28556

   (4) https://bugs.python.org/issue31544

   (5) https://bugs.python.org/issue31234

   (6) https://bugs.python.org/issue31457

   (7) https://bugs.python.org/issue31400

   (8) https://bugs.python.org/issue28958

   (9) https://bugs.python.org/issue27340

   (10) https://bugs.python.org/issue31178

   (11) https://bugs.python.org/issue31350

   (12) https://bugs.python.org/issue31170

   (13) https://bugs.python.org/issue29136

   (14) https://bugs.python.org/issue29212

   (15) https://bugs.python.org/issue9146

   (16) https://bugs.python.org/issue27144

   (17) https://bugs.python.org/issue10746

   (18) https://www.python.org/dev/peps/pep-3118

   (19) https://bugs.python.org/issue22536

   (20) https://bugs.python.org/issue31249

   (21) https://bugs.python.org/issue31247

   (22) https://bugs.python.org/issue30102

   (23) https://bugs.python.org/issue31185

   (24) https://bugs.python.org/issue31135

   (25) https://bugs.python.org/issue31107

   (26) https://bugs.python.org/issue31061

   (27) https://bugs.python.org/issue30502

   (28) https://bugs.python.org/issue30119

   (29) https://bugs.python.org/issue30595

   (30) https://bugs.python.org/issue29403

   (31) https://bugs.python.org/issue30961

   (32) https://bugs.python.org/issue25684

   (33) https://bugs.python.org/issue30886

   (34) https://bugs.python.org/issue29854

   (35) https://bugs.python.org/issue30319

   (36) https://bugs.python.org/issue30828

   (37) https://bugs.python.org/issue30807

   (38) https://bugs.python.org/issue30441

   (39) https://bugs.python.org/issue30532

   (40) https://bugs.python.org/issue30879

   (41) https://bugs.python.org/issue30746

   (42) https://bugs.python.org/issue29755


File: python.info,  Node: 文档<39>,  Next: 测试<37>,  Prev: 库<46>,  Up: Python 3 6 3 rc1

1.19.50.4 文档
..............

   - bpo-31294(1): Fix incomplete code snippet in the
     ZeroMQSocketListener and ZeroMQSocketHandler examples and adapt
     them to Python 3.

   - bpo-21649(2): Add RFC 7525 and Mozilla server side TLS links to SSL
     documentation.

   - bpo-30803(3): Clarify doc on truth value testing.  Original patch
     by Peter Thomassen.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31294

   (2) https://bugs.python.org/issue21649

   (3) https://bugs.python.org/issue30803


File: python.info,  Node: 测试<37>,  Next: 构建<38>,  Prev: 文档<39>,  Up: Python 3 6 3 rc1

1.19.50.5 测试
..............

   - bpo-31320(1): Silence traceback in test_ssl

   - bpo-25674(2): Remove sha256.tbs-internet.com ssl test

   - bpo-30715(3): Address ALPN callback changes for OpenSSL 1.1.0f.
     The latest version behaves like OpenSSL 1.0.2 and no longer aborts
     handshake.

   - bpo-30822(4): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31320

   (2) https://bugs.python.org/issue25674

   (3) https://bugs.python.org/issue30715

   (4) https://bugs.python.org/issue30822


File: python.info,  Node: 构建<38>,  Next: Windows<36>,  Prev: 测试<37>,  Up: Python 3 6 3 rc1

1.19.50.6 构建
..............

   - bpo-30854(1): Fix compile error when compiling –without-threads.
     Patch by Masayuki Yamamoto.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30854


File: python.info,  Node: Windows<36>,  Next: IDLE<36>,  Prev: 构建<38>,  Up: Python 3 6 3 rc1

1.19.50.7 Windows
.................

   - bpo-30389(1): Adds detection of Visual Studio 2017 to distutils on
     Windows.

   - bpo-31340(2): Change to building with MSVC v141 (included with
     Visual Studio 2017)

   - bpo-30581(3): os.cpu_count() now returns the correct number of
     processors on Windows when the number of logical processors is
     greater than 64.

   - bpo-30731(4): Add a missing xmlns to python.manifest so that it
     matches the schema.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30389

   (2) https://bugs.python.org/issue31340

   (3) https://bugs.python.org/issue30581

   (4) https://bugs.python.org/issue30731


File: python.info,  Node: IDLE<36>,  Next: 工具/示例<21>,  Prev: Windows<36>,  Up: Python 3 6 3 rc1

1.19.50.8 IDLE
..............

   - bpo-31493(1): IDLE code context – fix code update and font update
     timers.  Canceling timers prevents a warning message when test_idle
     completes.

   - bpo-31488(2): 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.

   - bpo-31477(3): IDLE - Improve rstrip entry in doc.  Strip trailing
     whitespace strips more than blank spaces.  Multiline string
     literals are not skipped.

   - bpo-31480(4): IDLE - make tests pass with zzdummy extension
     disabled by default.

   - bpo-31421(5): 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.

   - bpo-31414(6): IDLE – fix tk entry box tests by deleting first.
     Adding to an int entry is not the same as deleting and inserting
     because int(’’) will fail.

   - bpo-31051(7): Rearrange IDLE configdialog GenPage into Window,
     Editor, and Help sections.

   - bpo-30617(8): 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.

   - bpo-31287(9): IDLE - Do not modify tkinter.message in
     test_configdialog.

   - bpo-27099(10): 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.

   - bpo-31206(11): IDLE: Factor HighPage(Frame) class from
     ConfigDialog.  Patch by Cheryl Sabella.

   - bpo-31001(12): Add tests for configdialog highlight tab.  Patch by
     Cheryl Sabella.

   - bpo-31205(13): IDLE: Factor KeysPage(Frame) class from
     ConfigDialog.  The slightly modified tests continue to pass.  Patch
     by Cheryl Sabella.

   - bpo-31130(14): IDLE – stop leaks in test_configdialog.  Initial
     patch by Victor Stinner.

   - bpo-31002(15): Add tests for configdialog keys tab.  Patch by
     Cheryl Sabella.

   - bpo-19903(16): IDLE: Calltips use *note inspect.signature: 655.
     instead of *note inspect.getfullargspec: 657.  This improves
     calltips for builtins converted to use Argument Clinic.  Patch by
     Louie Lu.

   - bpo-31083(17): IDLE - Add an outline of a TabPage class in
     configdialog.  Update existing classes to match outline.  Initial
     patch by Cheryl Sabella.

   - bpo-31050(18): Factor GenPage(Frame) class from ConfigDialog.  The
     slightly modified tests continue to pass.  Patch by Cheryl Sabella.

   - bpo-31004(19): IDLE - Factor FontPage(Frame) class from
     ConfigDialog.  Slightly modified tests continue to pass.  Fix
     General tests.  Patch mostly by Cheryl Sabella.

   - bpo-30781(20): IDLE - Use ttk widgets in ConfigDialog.  Patches by
     Terry Jan Reedy and Cheryl Sabella.

   - bpo-31060(21): 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.

   - bpo-30853(22): 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%.

   - bpo-31003(23): IDLE: Add more tests for General tab.

   - bpo-30993(24): 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.

   - bpo-30981(25): IDLE – Add more configdialog font page tests.

   - bpo-28523(26): IDLE: replace ’colour’ with ’color’ in configdialog.

   - bpo-30917(27): Add tests for idlelib.config.IdleConf.  Increase
     coverage from 46% to 96%.  Patch by Louie Lu.

   - bpo-30934(28): 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.

   - bpo-30913(29): 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.

   - bpo-30899(30): IDLE: Add tests for ConfigParser subclasses in
     config.  Patch by Louie Lu.

   - bpo-30881(31): IDLE: Add docstrings to browser.py.  Patch by Cheryl
     Sabella.

   - bpo-30851(32): IDLE: Remove unused variables in configdialog.  One
     is a duplicate, one is set but cannot be altered by users.  Patch
     by Cheryl Sabella.

   - bpo-30870(33): IDLE: In Settings dialog, select font with Up, Down
     keys as well as mouse.  Initial patch by Louie Lu.

   - bpo-8231(34): IDLE: call config.IdleConf.GetUserCfgDir only once.

   - bpo-30779(35): 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.

   - bpo-30777(36): IDLE: configdialog - Add docstrings and fix
     comments.  Patch by Cheryl Sabella.

   - bpo-30495(37): IDLE: Improve textview with docstrings, PEP8 names,
     and more tests.  Patch by Cheryl Sabella.

   - bpo-30723(38): 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.

   - bpo-30674(39): IDLE: add docstrings to grep module.  Patch by
     Cheryl Sabella

   - bpo-21519(40): IDLE’s basic custom key entry dialog now detects
     duplicates properly.  Original patch by Saimadhav Heblikar.

   - bpo-29910(41): IDLE no longer deletes a character after commenting
     out a region by a key shortcut.  Add ‘return 'break'’ for this and
     other potential conflicts between IDLE and default key bindings.

   - bpo-30728(42): Review and change idlelib.configdialog names.
     Lowercase method and attribute names.  Replace ’colour’ with
     ’color’, expand overly cryptic names, delete unneeded underscores.
     Replace ‘import *’ with specific imports.  Patches by Cheryl
     Sabella.

   - bpo-6739(43): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31493

   (2) https://bugs.python.org/issue31488

   (3) https://bugs.python.org/issue31477

   (4) https://bugs.python.org/issue31480

   (5) https://bugs.python.org/issue31421

   (6) https://bugs.python.org/issue31414

   (7) https://bugs.python.org/issue31051

   (8) https://bugs.python.org/issue30617

   (9) https://bugs.python.org/issue31287

   (10) https://bugs.python.org/issue27099

   (11) https://bugs.python.org/issue31206

   (12) https://bugs.python.org/issue31001

   (13) https://bugs.python.org/issue31205

   (14) https://bugs.python.org/issue31130

   (15) https://bugs.python.org/issue31002

   (16) https://bugs.python.org/issue19903

   (17) https://bugs.python.org/issue31083

   (18) https://bugs.python.org/issue31050

   (19) https://bugs.python.org/issue31004

   (20) https://bugs.python.org/issue30781

   (21) https://bugs.python.org/issue31060

   (22) https://bugs.python.org/issue30853

   (23) https://bugs.python.org/issue31003

   (24) https://bugs.python.org/issue30993

   (25) https://bugs.python.org/issue30981

   (26) https://bugs.python.org/issue28523

   (27) https://bugs.python.org/issue30917

   (28) https://bugs.python.org/issue30934

   (29) https://bugs.python.org/issue30913

   (30) https://bugs.python.org/issue30899

   (31) https://bugs.python.org/issue30881

   (32) https://bugs.python.org/issue30851

   (33) https://bugs.python.org/issue30870

   (34) https://bugs.python.org/issue8231

   (35) https://bugs.python.org/issue30779

   (36) https://bugs.python.org/issue30777

   (37) https://bugs.python.org/issue30495

   (38) https://bugs.python.org/issue30723

   (39) https://bugs.python.org/issue30674

   (40) https://bugs.python.org/issue21519

   (41) https://bugs.python.org/issue29910

   (42) https://bugs.python.org/issue30728

   (43) https://bugs.python.org/issue6739


File: python.info,  Node: 工具/示例<21>,  Prev: IDLE<36>,  Up: Python 3 6 3 rc1

1.19.50.9 工具/示例
...................

   - bpo-30983(1): gdb integration commands (py-bt, etc.)  work on
     optimized shared builds now, too.  PEP 523(2) 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30983

   (2) https://www.python.org/dev/peps/pep-0523


File: python.info,  Node: Python 3 6 2 正式版,  Next: Python 3 6 2 rc2,  Prev: Python 3 6 3 rc1,  Up: Changelog（更動日誌）

1.19.51 Python 3.6.2 正式版
---------------------------

`发布日期: 2017-07-17'

自rc2起没有更改


File: python.info,  Node: Python 3 6 2 rc2,  Next: Python 3 6 2 rc1,  Prev: Python 3 6 2 正式版,  Up: Changelog（更動日誌）

1.19.52 Python 3.6.2 rc2
------------------------

`发布日期: 2017-07-07'

* Menu:

* 安全性: 安全性<24>.


File: python.info,  Node: 安全性<24>,  Up: Python 3 6 2 rc2

1.19.52.1 安全性
................

   - bpo-30730(1): Prevent environment variables injection in subprocess
     on Windows.  Prevent passing other environment variables and
     command arguments.

   - bpo-30694(2): 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
     ‘XML_SetHashSalt()’.

   - bpo-30500(3): Fix urllib.parse.splithost() to correctly parse
     fragments.  For example, ‘splithost('//127.0.0.1#@evil.com/')’ now
     correctly returns the ‘127.0.0.1’ host, instead of treating
     ‘@evil.com’ as the host in an authentication (‘login@host’).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30730

   (2) https://bugs.python.org/issue30694

   (3) https://bugs.python.org/issue30500


File: python.info,  Node: Python 3 6 2 rc1,  Next: Python 3 6 1 正式版,  Prev: Python 3 6 2 rc2,  Up: Changelog（更動日誌）

1.19.53 Python 3.6.2 rc1
------------------------

`发布日期: 2017-06-17'

* Menu:

* 核心与内置函数: 核心与内置函数<43>.
* 库: 库<47>.
* 安全性: 安全性<25>.
* 库: 库<48>.
* IDLE: IDLE<37>.
* C API: C API<31>.
* 构建: 构建<39>.
* 文档: 文档<40>.
* 工具/示例: 工具/示例<22>.
* 测试: 测试<38>.
* Windows: Windows<37>.


File: python.info,  Node: 核心与内置函数<43>,  Next: 库<47>,  Up: Python 3 6 2 rc1

1.19.53.1 核心与内置函数
........................

   - bpo-30682(1): Removed a too-strict assertion that failed for
     certain f-strings, such as eval("f’\n’") and eval("f’\r’").

   - bpo-30604(2): Move co_extra_freefuncs to not be per-thread to avoid
     crashes

   - bpo-29104(3): Fixed parsing backslashes in f-strings.

   - bpo-27945(4): Fixed various segfaults with dict when input
     collections are mutated during searching, inserting or comparing.
     Based on patches by Duane Griffin and Tim Mitchell.

   - bpo-25794(5): Fixed type.__setattr__() and type.__delattr__() for
     non-interned attribute names.  Based on patch by Eryk Sun.

   - bpo-30039(6): 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.

   - bpo-12414(7): 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.

   - bpo-29949(8): Fix memory usage regression of set and frozenset
     object.

   - bpo-29935(9): Fixed error messages in the index() method of tuple,
     list and deque when pass indices of wrong type.

   - bpo-29859(10): Show correct error messages when any of the
     pthread_* calls in thread_pthread.h fails.

   - bpo-28876(11): ‘bool(range)’ works even if ‘len(range)’ raises
     *note OverflowError: a41.

   - bpo-29600(12): Fix wrapping coroutine return values in
     StopIteration.

   - bpo-28856(13): Fix an oversight that %b format for bytes should
     support objects follow the buffer protocol.

   - bpo-29714(14): Fix a regression that bytes format may fail when
     containing zero bytes inside.

   - bpo-29478(15): If max_line_length=None is specified while using the
     Compat32 policy, it is no longer ignored.  Patch by Mircea Cosbuc.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30682

   (2) https://bugs.python.org/issue30604

   (3) https://bugs.python.org/issue29104

   (4) https://bugs.python.org/issue27945

   (5) https://bugs.python.org/issue25794

   (6) https://bugs.python.org/issue30039

   (7) https://bugs.python.org/issue12414

   (8) https://bugs.python.org/issue29949

   (9) https://bugs.python.org/issue29935

   (10) https://bugs.python.org/issue29859

   (11) https://bugs.python.org/issue28876

   (12) https://bugs.python.org/issue29600

   (13) https://bugs.python.org/issue28856

   (14) https://bugs.python.org/issue29714

   (15) https://bugs.python.org/issue29478


File: python.info,  Node: 库<47>,  Next: 安全性<25>,  Prev: 核心与内置函数<43>,  Up: Python 3 6 2 rc1

1.19.53.2 库
............

   - bpo-30616(1): Functional API of enum allows to create empty enums.
     Patched by Dong-hee Na

   - bpo-30038(2): Fix race condition between signal delivery and wakeup
     file descriptor.  Patch by Nathaniel Smith.

   - bpo-23894(3): lib2to3 now recognizes ‘rb'...'’ and ‘f'...'’
     strings.

   - bpo-23890(4): unittest.TestCase.assertRaises() now manually breaks
     a reference cycle to not keep objects alive longer than expected.

   - bpo-30149(5): inspect.signature() now supports callables with
     variable-argument parameters wrapped with partialmethod.  Patch by
     Dong-hee Na.

   - bpo-30645(6): Fix path calculation in imp.load_package(), fixing it
     for cases when a package is only shipped with bytecodes.  Patch by
     Alexandru Ardelean.

   - bpo-29931(7): Fixed comparison check for ipaddress.ip_interface
     objects.  Patch by Sanjay Sundaresan.

   - bpo-30605(8): re.compile() no longer raises a BytesWarning when
     compiling a bytes instance with misplaced inline modifier.  Patch
     by Roy Williams.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30616

   (2) https://bugs.python.org/issue30038

   (3) https://bugs.python.org/issue23894

   (4) https://bugs.python.org/issue23890

   (5) https://bugs.python.org/issue30149

   (6) https://bugs.python.org/issue30645

   (7) https://bugs.python.org/issue29931

   (8) https://bugs.python.org/issue30605


File: python.info,  Node: 安全性<25>,  Next: 库<48>,  Prev: 库<47>,  Up: Python 3 6 2 rc1

1.19.53.3 安全性
................

   - bpo-29591(1): Update expat copy from 2.1.1 to 2.2.0 to get fixes of
     CVE-2016-0718 and CVE-2016-4472.  See
     ‘https://sourceforge.net/p/expat/bugs/537/’ for more information.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29591


File: python.info,  Node: 库<48>,  Next: IDLE<37>,  Prev: 安全性<25>,  Up: Python 3 6 2 rc1

1.19.53.4 库
............

   - bpo-24484(1): Avoid race condition in multiprocessing cleanup
     (#2159)

   - bpo-28994(2): The traceback no longer displayed for SystemExit
     raised in a callback registered by atexit.

   - bpo-30508(3): Don’t log exceptions if Task/Future "cancel()" method
     was called.

   - bpo-28556(4): Updates to typing module: Add generic
     AsyncContextManager, add support for ContextManager on all
     versions.  Original PRs by Jelle Zijlstra and Ivan Levkivskyi

   - bpo-29870(5): Fix ssl sockets leaks when connection is aborted in
     asyncio/ssl implementation.  Patch by Michaël Sghaïer.

   - bpo-29743(6): Closing transport during handshake process leaks open
     socket.  Patch by Nikolay Kim

   - bpo-27585(7): Fix waiter cancellation in asyncio.Lock.  Patch by
     Mathieu Sornay.

   - bpo-30418(8): On Windows, subprocess.Popen.communicate() now also
     ignore EINVAL on stdin.write() if the child process is still
     running but closed the pipe.

   - bpo-29822(9): inspect.isabstract() now works during
     __init_subclass__.  Patch by Nate Soares.

   - bpo-29581(10): ABCMeta.__new__ now accepts ‘**kwargs’, allowing
     abstract base classes to use keyword parameters in
     __init_subclass__.  Patch by Nate Soares.

   - bpo-30557(11): faulthandler now correctly filters and displays
     exception codes on Windows

   - bpo-30378(12): Fix the problem that logging.handlers.SysLogHandler
     cannot handle IPv6 addresses.

   - bpo-29960(13): Preserve generator state when
     _random.Random.setstate() raises an exception.  Patch by Bryan
     Olson.

   - bpo-30414(14): multiprocessing.Queue._feed background running
     thread do not break from main loop on exception.

   - bpo-30003(15): Fix handling escape characters in HZ codec.  Based
     on patch by Ma Lin.

   - bpo-30301(16): Fix AttributeError when using SimpleQueue.empty()
     under `spawn' and `forkserver' start methods.

   - bpo-30329(17): 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.

   - bpo-30375(18): 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.

   - bpo-30048(19): Fixed ‘Task.cancel()’ can be ignored when the task
     is running coroutine and the coroutine returned without any more
     ‘await’.

   - bpo-30266(20): contextlib.AbstractContextManager now supports
     anti-registration by setting __enter__ = None or __exit__ = None,
     following the pattern introduced in bpo-25958(21).  Patch by Jelle
     Zijlstra.

   - bpo-30298(22): Weaken the condition of deprecation warnings for
     inline modifiers.  Now allowed several subsequential inline
     modifiers at the start of the pattern (e.g.  ‘'(?i)(?s)...'’).  In
     verbose mode whitespaces and comments now are allowed before and
     between inline modifiers (e.g.  ‘'(?x) (?i) (?s)...'’).

   - bpo-29990(23): Fix range checking in GB18030 decoder.  Original
     patch by Ma Lin.

   - bpo-26293(24): Change resulted because of zipfile breakage.  (See
     also: bpo-29094(25))

   - bpo-30243(26): 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.

   - bpo-30185(27): Avoid KeyboardInterrupt tracebacks in forkserver
     helper process when Ctrl-C is received.

   - bpo-28556(28): Various updates to typing module: add
     typing.NoReturn type, use WrapperDescriptorType, minor bug-fixes.
     Original PRs by Jim Fasarakis-Hilliard and Ivan Levkivskyi.

   - bpo-30205(29): Fix getsockname() for unbound AF_UNIX sockets on
     Linux.

   - bpo-30070(30): Fixed leaks and crashes in errors handling in the
     parser module.

   - bpo-30061(31): 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().

   - bpo-30017(32): Allowed calling the close() method of the zip entry
     writer object multiple times.  Writing to a closed writer now
     always produces a ValueError.

   - bpo-30068(33): _io._IOBase.readlines will check if it’s closed
     first when hint is present.

   - bpo-29694(34): Fixed race condition in pathlib mkdir with flags
     parents=True.  Patch by Armin Rigo.

   - bpo-29692(35): Fixed arbitrary unchaining of RuntimeError
     exceptions in contextlib.contextmanager.  Patch by Siddharth
     Velankar.

   - bpo-29998(36): Pickling and copying ImportError now preserves name
     and path attributes.

   - bpo-29953(37): Fixed memory leaks in the replace() method of
     datetime and time objects when pass out of bound fold argument.

   - bpo-29942(38): Fix a crash in itertools.chain.from_iterable when
     encountering long runs of empty iterables.

   - bpo-27863(39): Fixed multiple crashes in ElementTree caused by race
     conditions and wrong types.

   - bpo-28699(40): 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.

   - bpo-25803(41): Avoid incorrect errors raised by
     Path.mkdir(exist_ok=True) when the OS gives priority to errors such
     as EACCES over EEXIST.

   - bpo-29861(42): Release references to tasks, their arguments and
     their results as soon as they are finished in multiprocessing.Pool.

   - bpo-29884(43): faulthandler: Restore the old sigaltstack during
     teardown.  Patch by Christophe Zeitouny.

   - bpo-25455(44): Fixed crashes in repr of recursive buffered
     file-like objects.

   - bpo-29800(45): Fix crashes in partial.__repr__ if the keys of
     partial.keywords are not strings.  Patch by Michael Seifert.

   - bpo-29742(46): get_extra_info() raises exception if get called on
     closed ssl transport.  Patch by Nikolay Kim.

   - bpo-8256(47): Fixed possible failing or crashing input() if
     attributes "encoding" or "errors" of sys.stdin or sys.stdout are
     not set or are not strings.

   - bpo-28298(48): Fix a bug that prevented array ’Q’, ’L’ and ’I’ from
     accepting big intables (objects that have __int__) as elements.
     Patch by Oren Milman.

   - bpo-28231(49): The zipfile module now accepts path-like objects for
     external paths.

   - bpo-26915(50): index() and count() methods of
     collections.abc.Sequence now check identity before checking
     equality when do comparisons.

   - bpo-29615(51): SimpleXMLRPCDispatcher no longer chains KeyError (or
     any other exception) to exception(s) raised in the dispatched
     methods.  Patch by Petr Motejlek.

   - bpo-30177(52): path.resolve(strict=False) no longer cuts the path
     after the first element not present in the filesystem.  Patch by
     Antoine Pietri.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24484

   (2) https://bugs.python.org/issue28994

   (3) https://bugs.python.org/issue30508

   (4) https://bugs.python.org/issue28556

   (5) https://bugs.python.org/issue29870

   (6) https://bugs.python.org/issue29743

   (7) https://bugs.python.org/issue27585

   (8) https://bugs.python.org/issue30418

   (9) https://bugs.python.org/issue29822

   (10) https://bugs.python.org/issue29581

   (11) https://bugs.python.org/issue30557

   (12) https://bugs.python.org/issue30378

   (13) https://bugs.python.org/issue29960

   (14) https://bugs.python.org/issue30414

   (15) https://bugs.python.org/issue30003

   (16) https://bugs.python.org/issue30301

   (17) https://bugs.python.org/issue30329

   (18) https://bugs.python.org/issue30375

   (19) https://bugs.python.org/issue30048

   (20) https://bugs.python.org/issue30266

   (21) https://bugs.python.org/issue25958

   (22) https://bugs.python.org/issue30298

   (23) https://bugs.python.org/issue29990

   (24) https://bugs.python.org/issue26293

   (25) https://bugs.python.org/issue29094

   (26) https://bugs.python.org/issue30243

   (27) https://bugs.python.org/issue30185

   (28) https://bugs.python.org/issue28556

   (29) https://bugs.python.org/issue30205

   (30) https://bugs.python.org/issue30070

   (31) https://bugs.python.org/issue30061

   (32) https://bugs.python.org/issue30017

   (33) https://bugs.python.org/issue30068

   (34) https://bugs.python.org/issue29694

   (35) https://bugs.python.org/issue29692

   (36) https://bugs.python.org/issue29998

   (37) https://bugs.python.org/issue29953

   (38) https://bugs.python.org/issue29942

   (39) https://bugs.python.org/issue27863

   (40) https://bugs.python.org/issue28699

   (41) https://bugs.python.org/issue25803

   (42) https://bugs.python.org/issue29861

   (43) https://bugs.python.org/issue29884

   (44) https://bugs.python.org/issue25455

   (45) https://bugs.python.org/issue29800

   (46) https://bugs.python.org/issue29742

   (47) https://bugs.python.org/issue8256

   (48) https://bugs.python.org/issue28298

   (49) https://bugs.python.org/issue28231

   (50) https://bugs.python.org/issue26915

   (51) https://bugs.python.org/issue29615

   (52) https://bugs.python.org/issue30177


File: python.info,  Node: IDLE<37>,  Next: C API<31>,  Prev: 库<48>,  Up: Python 3 6 2 rc1

1.19.53.5 IDLE
..............

   - bpo-15786(1): 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.

   - bpo-25514(2): Add doc subsubsection about IDLE failure to start.
     Popup no-connection message directs users to this section.

   - bpo-30642(3): Fix reference leaks in IDLE tests.  Patches by Louie
     Lu and Terry Jan Reedy.

   - bpo-30495(4): Add docstrings for textview.py and use PEP8 names.
     Patches by Cheryl Sabella and Terry Jan Reedy.

   - bpo-30290(5): Help-about: use pep8 names and add tests.  Increase
     coverage to 100%.  Patches by Louie Lu, Cheryl Sabella, and Terry
     Jan Reedy.

   - bpo-30303(6): Add _utest option to textview; add new tests.
     Increase coverage to 100%.  Patches by Louie Lu and Terry Jan
     Reedy.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15786

   (2) https://bugs.python.org/issue25514

   (3) https://bugs.python.org/issue30642

   (4) https://bugs.python.org/issue30495

   (5) https://bugs.python.org/issue30290

   (6) https://bugs.python.org/issue30303


File: python.info,  Node: C API<31>,  Next: 构建<39>,  Prev: IDLE<37>,  Up: Python 3 6 2 rc1

1.19.53.6 C API
...............

   - bpo-27867(1): Function PySlice_GetIndicesEx() no longer replaced
     with a macro if Py_LIMITED_API is not set.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27867


File: python.info,  Node: 构建<39>,  Next: 文档<40>,  Prev: C API<31>,  Up: Python 3 6 2 rc1

1.19.53.7 构建
..............

   - bpo-29941(1): Add ‘--with-assertions’ configure flag to explicitly
     enable C ‘assert()’ checks.  Defaults to off.  ‘--with-pydebug’
     implies ‘--with-assertions’.

   - bpo-28787(2): Fix out-of-tree builds of Python when configured with
     ‘--with--dtrace’.

   - bpo-29243(3): Prevent unnecessary rebuilding of Python during ‘make
     test’, ‘make install’ and some other make targets when configured
     with ‘--enable-optimizations’.

   - bpo-23404(4): Don’t regenerate generated files based on file
     modification time anymore: the action is now explicit.  Replace
     ‘make touch’ with ‘make regen-all’.

   - bpo-29643(5): Fix ‘--enable-optimization’ didn’t work.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29941

   (2) https://bugs.python.org/issue28787

   (3) https://bugs.python.org/issue29243

   (4) https://bugs.python.org/issue23404

   (5) https://bugs.python.org/issue29643


File: python.info,  Node: 文档<40>,  Next: 工具/示例<22>,  Prev: 构建<39>,  Up: Python 3 6 2 rc1

1.19.53.8 文档
..............

   - bpo-30176(1): Add missing attribute related constants in curses
     documentation.

   - bpo-30052(2): the link targets for *note bytes(): 172. and *note
     bytearray(): 173. are now their respective type definitions, rather
     than the corresponding builtin function entries.  Use *note bytes:
     11f2. and *note bytearray: 11f3. 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.

   - bpo-26985(3): Add missing info of code object in inspect
     documentation.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30176

   (2) https://bugs.python.org/issue30052

   (3) https://bugs.python.org/issue26985


File: python.info,  Node: 工具/示例<22>,  Next: 测试<38>,  Prev: 文档<40>,  Up: Python 3 6 2 rc1

1.19.53.9 工具/示例
...................

   - bpo-29367(1): python-gdb.py now supports also ‘method-wrapper’
     (‘wrapperobject’) objects.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29367


File: python.info,  Node: 测试<38>,  Next: Windows<37>,  Prev: 工具/示例<22>,  Up: Python 3 6 2 rc1

1.19.53.10 测试
...............

   - bpo-30357(1): 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.

   - bpo-30197(2): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30357

   (2) https://bugs.python.org/issue30197


File: python.info,  Node: Windows<37>,  Prev: 测试<38>,  Up: Python 3 6 2 rc1

1.19.53.11 Windows
..................

   - bpo-30687(1): Locate msbuild.exe on Windows when building rather
     than vcvarsall.bat

   - bpo-30450(2): 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 ‘py -3.6’),
     NuGet is used to download a copy of 32-bit Python.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30687

   (2) https://bugs.python.org/issue30450


File: python.info,  Node: Python 3 6 1 正式版,  Next: Python 3 6 1 rc1,  Prev: Python 3 6 2 rc1,  Up: Changelog（更動日誌）

1.19.54 Python 3.6.1 正式版
---------------------------

`发布日期: 2017-03-21'

* Menu:

* 核心与内置函数: 核心与内置函数<44>.
* 构建: 构建<40>.


File: python.info,  Node: 核心与内置函数<44>,  Next: 构建<40>,  Up: Python 3 6 1 正式版

1.19.54.1 核心与内置函数
........................

   - bpo-29723(1): The ‘sys.path[0]’ initialization change for
     bpo-29139(2) caused a regression by revealing an inconsistency in
     how sys.path is initialized when executing ‘__main__’ from a
     zipfile, directory, or other import location.  The interpreter now
     consistently avoids ever adding the import location’s parent
     directory to ‘sys.path’, and ensures no other ‘sys.path’ entries
     are inadvertently modified when inserting the import location named
     on the command line.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29723

   (2) https://bugs.python.org/issue29139


File: python.info,  Node: 构建<40>,  Prev: 核心与内置函数<44>,  Up: Python 3 6 1 正式版

1.19.54.2 构建
..............

   - bpo-27593(1): fix format of git information used in sys.version

   - Fix incompatible comment in python.h

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27593


File: python.info,  Node: Python 3 6 1 rc1,  Next: Python 3 6 0 正式版,  Prev: Python 3 6 1 正式版,  Up: Changelog（更動日誌）

1.19.55 Python 3.6.1 rc1
------------------------

`发布日期: 2017-03-04'

* Menu:

* 核心与内置函数: 核心与内置函数<45>.
* 库: 库<49>.
* IDLE: IDLE<38>.
* Windows: Windows<38>.
* C API: C API<32>.
* 文档: 文档<41>.
* 测试: 测试<39>.
* 构建: 构建<41>.


File: python.info,  Node: 核心与内置函数<45>,  Next: 库<49>,  Up: Python 3 6 1 rc1

1.19.55.1 核心与内置函数
........................

   - bpo-28893(1): Set correct __cause__ for errors about invalid
     awaitables returned from __aiter__ and __anext__.

   - bpo-29683(2): Fixes to memory allocation in _PyCode_SetExtra.
     Patch by Brian Coleman.

   - bpo-29684(3): 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.

   - bpo-28598(4): Support __rmod__ for subclasses of str being called
     before str.__mod__.  Patch by Martijn Pieters.

   - bpo-29607(5): Fix stack_effect computation for CALL_FUNCTION_EX.
     Patch by Matthieu Dartiailh.

   - bpo-29602(6): Fix incorrect handling of signed zeros in complex
     constructor for complex subclasses and for inputs having a
     __complex__ method.  Patch by Serhiy Storchaka.

   - bpo-29347(7): Fixed possibly dereferencing undefined pointers when
     creating weakref objects.

   - bpo-29438(8): Fixed use-after-free problem in key sharing dict.

   - bpo-29319(9): Prevent RunMainFromImporter overwriting sys.path[0].

   - bpo-29337(10): Fixed possible BytesWarning when compare the code
     objects.  Warnings could be emitted at compile time.

   - bpo-29327(11): Fixed a crash when pass the iterable keyword
     argument to sorted().

   - bpo-29034(12): Fix memory leak and use-after-free in os module
     (path_converter).

   - bpo-29159(13): Fix regression in bytes(x) when x.__index__() raises
     Exception.

   - bpo-28932(14): Do not include <sys/random.h> if it does not exist.

   - bpo-25677(15): Correct the positioning of the syntax error caret
     for indented blocks.  Based on patch by Michael Layzell.

   - bpo-29000(16): Fixed bytes formatting of octals with zero padding
     in alternate form.

   - bpo-26919(17): 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.

   - bpo-28991(18): functools.lru_cache() was susceptible to an obscure
     reentrancy bug triggerable by a monkey-patched len() function.

   - bpo-28739(19): f-string expressions are no longer accepted as
     docstrings and by ast.literal_eval() even if they do not include
     expressions.

   - bpo-28512(20): Fixed setting the offset attribute of SyntaxError by
     PyErr_SyntaxLocationEx() and PyErr_SyntaxLocationObject().

   - bpo-28918(21): Fix the cross compilation of xxlimited when Python
     has been built with Py_DEBUG defined.

   - bpo-28731(22): Optimize _PyDict_NewPresized() to create correct
     size dict.  Improve speed of dict literal with constant keys up to
     30%.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28893

   (2) https://bugs.python.org/issue29683

   (3) https://bugs.python.org/issue29684

   (4) https://bugs.python.org/issue28598

   (5) https://bugs.python.org/issue29607

   (6) https://bugs.python.org/issue29602

   (7) https://bugs.python.org/issue29347

   (8) https://bugs.python.org/issue29438

   (9) https://bugs.python.org/issue29319

   (10) https://bugs.python.org/issue29337

   (11) https://bugs.python.org/issue29327

   (12) https://bugs.python.org/issue29034

   (13) https://bugs.python.org/issue29159

   (14) https://bugs.python.org/issue28932

   (15) https://bugs.python.org/issue25677

   (16) https://bugs.python.org/issue29000

   (17) https://bugs.python.org/issue26919

   (18) https://bugs.python.org/issue28991

   (19) https://bugs.python.org/issue28739

   (20) https://bugs.python.org/issue28512

   (21) https://bugs.python.org/issue28918

   (22) https://bugs.python.org/issue28731


File: python.info,  Node: 库<49>,  Next: IDLE<38>,  Prev: 核心与内置函数<45>,  Up: Python 3 6 1 rc1

1.19.55.2 库
............

   - bpo-29169(1): Update zlib to 1.2.11.

   - bpo-29623(2): Allow use of path-like object as a single argument in
     ConfigParser.read().  Patch by David Ellis.

   - bpo-28963(3): Fix out of bound iteration in
     asyncio.Future.remove_done_callback implemented in C.

   - bpo-29704(4): asyncio.subprocess.SubprocessStreamProtocol no longer
     closes before all pipes are closed.

   - bpo-29271(5): Fix Task.current_task and Task.all_tasks implemented
     in C to accept None argument as their pure Python implementation.

   - bpo-29703(6): Fix asyncio to support instantiation of new event
     loops in child processes.

   - bpo-29376(7): Fix assertion error in
     threading._DummyThread.is_alive().

   - bpo-28624(8): Add a test that checks that cwd parameter of Popen()
     accepts PathLike objects.  Patch by Sayan Chowdhury.

   - bpo-28518(9): Start a transaction implicitly before a DML
     statement.  Patch by Aviv Palivoda.

   - bpo-29532(10): Altering a kwarg dictionary passed to
     functools.partial() no longer affects a partial object after
     creation.

   - bpo-29110(11): 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.

   - bpo-28556(12): 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.

   - bpo-29100(13): Fix datetime.fromtimestamp() regression introduced
     in Python 3.6.0: check minimum and maximum years.

   - bpo-29519(14): Fix weakref spewing exceptions during interpreter
     shutdown when used with a rare combination of multiprocessing and
     custom codecs.

   - bpo-29416(15): Prevent infinite loop in pathlib.Path.mkdir

   - bpo-29444(16): Fixed out-of-bounds buffer access in the group()
     method of the match object.  Based on patch by WGH.

   - bpo-29335(17): Fix subprocess.Popen.wait() when the child process
     has exited to a stopped instead of terminated state (ex: when under
     ptrace).

   - bpo-29290(18): Fix a regression in argparse that help messages
     would wrap at non-breaking spaces.

   - bpo-28735(19): Fixed the comparison of mock.MagickMock with
     mock.ANY.

   - bpo-29316(20): Restore the provisional status of typing module, add
     corresponding note to documentation.  Patch by Ivan L.

   - bpo-29219(21): Fixed infinite recursion in the repr of
     uninitialized ctypes.CDLL instances.

   - bpo-29011(22): Fix an important omission by adding Deque to the
     typing module.

   - bpo-28969(23): 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.

   - bpo-29142(24): 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.

   - bpo-28961(25): Fix unittest.mock._Call helper: don’t ignore the
     name parameter anymore.  Patch written by Jiajun Huang.

   - bpo-29203(26): functools.lru_cache() now respects PEP 468(27) 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.

   - bpo-15812(28): inspect.getframeinfo() now correctly shows the first
     line of a context.  Patch by Sam Breese.

   - bpo-29094(29): Offsets in a ZIP file created with extern file
     object and modes "w" and "x" now are relative to the start of the
     file.

   - bpo-29085(30): Allow random.Random.seed() to use high quality OS
     randomness rather than the pid and time.

   - bpo-29061(31): Fixed bug in secrets.randbelow() which would hang
     when given a negative input.  Patch by Brendan Donegan.

   - bpo-29079(32): Prevent infinite loop in pathlib.resolve() on
     Windows

   - bpo-13051(33): Fixed recursion errors in large or resized
     curses.textpad.Textbox.  Based on patch by Tycho Andersen.

   - bpo-29119(34): Fix weakrefs in the pure python version of
     collections.OrderedDict move_to_end() method.  Contributed by Andra
     Bogildea.

   - bpo-9770(35): curses.ascii predicates now work correctly with
     negative integers.

   - bpo-28427(36): old keys should not remove new values from
     WeakValueDictionary when collecting from another thread.

   - bpo-28923(37): Remove editor artifacts from Tix.py.

   - bpo-29055(38): Neaten-up empty population error on random.choice()
     by suppressing the upstream exception.

   - bpo-28871(39): Fixed a crash when deallocate deep ElementTree.

   - bpo-19542(40): Fix bugs in WeakValueDictionary.setdefault() and
     WeakValueDictionary.pop() when a GC collection happens in another
     thread.

   - bpo-20191(41): Fixed a crash in resource.prlimit() when passing a
     sequence that doesn’t own its elements as limits.

   - bpo-28779(42): multiprocessing.set_forkserver_preload() would crash
     the forkserver process if a preloaded module instantiated some
     multiprocessing objects such as locks.

   - bpo-28847(43): dbm.dumb now supports reading read-only files and no
     longer writes the index file when it is not changed.

   - bpo-26937(44): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29169

   (2) https://bugs.python.org/issue29623

   (3) https://bugs.python.org/issue28963

   (4) https://bugs.python.org/issue29704

   (5) https://bugs.python.org/issue29271

   (6) https://bugs.python.org/issue29703

   (7) https://bugs.python.org/issue29376

   (8) https://bugs.python.org/issue28624

   (9) https://bugs.python.org/issue28518

   (10) https://bugs.python.org/issue29532

   (11) https://bugs.python.org/issue29110

   (12) https://bugs.python.org/issue28556

   (13) https://bugs.python.org/issue29100

   (14) https://bugs.python.org/issue29519

   (15) https://bugs.python.org/issue29416

   (16) https://bugs.python.org/issue29444

   (17) https://bugs.python.org/issue29335

   (18) https://bugs.python.org/issue29290

   (19) https://bugs.python.org/issue28735

   (20) https://bugs.python.org/issue29316

   (21) https://bugs.python.org/issue29219

   (22) https://bugs.python.org/issue29011

   (23) https://bugs.python.org/issue28969

   (24) https://bugs.python.org/issue29142

   (25) https://bugs.python.org/issue28961

   (26) https://bugs.python.org/issue29203

   (27) https://www.python.org/dev/peps/pep-0468

   (28) https://bugs.python.org/issue15812

   (29) https://bugs.python.org/issue29094

   (30) https://bugs.python.org/issue29085

   (31) https://bugs.python.org/issue29061

   (32) https://bugs.python.org/issue29079

   (33) https://bugs.python.org/issue13051

   (34) https://bugs.python.org/issue29119

   (35) https://bugs.python.org/issue9770

   (36) https://bugs.python.org/issue28427

   (37) https://bugs.python.org/issue28923

   (38) https://bugs.python.org/issue29055

   (39) https://bugs.python.org/issue28871

   (40) https://bugs.python.org/issue19542

   (41) https://bugs.python.org/issue20191

   (42) https://bugs.python.org/issue28779

   (43) https://bugs.python.org/issue28847

   (44) https://bugs.python.org/issue26937


File: python.info,  Node: IDLE<38>,  Next: Windows<38>,  Prev: 库<49>,  Up: Python 3 6 1 rc1

1.19.55.3 IDLE
..............

   - bpo-29071(1): IDLE colors f-string prefixes (but not invalid ur
     prefixes).

   - bpo-28572(2): Add 10% to coverage of IDLE’s test_configdialog.
     Update and augment description of the configuration system.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29071

   (2) https://bugs.python.org/issue28572


File: python.info,  Node: Windows<38>,  Next: C API<32>,  Prev: IDLE<38>,  Up: Python 3 6 1 rc1

1.19.55.4 Windows
.................

   - bpo-29579(1): Removes readme.txt from the installer

   - bpo-29326(2): Ignores blank lines in ._pth files (Patch by Alexey
     Izbyshev)

   - bpo-28164(3): Correctly handle special console filenames (patch by
     Eryk Sun)

   - bpo-29409(4): Implement PEP 529(5) for io.FileIO (Patch by Eryk
     Sun)

   - bpo-29392(6): Prevent crash when passing invalid arguments into
     msvcrt module.

   - bpo-25778(7): winreg does not truncate string correctly (Patch by
     Eryk Sun)

   - bpo-28896(8): Deprecate WindowsRegistryFinder and disable it by
     default.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29579

   (2) https://bugs.python.org/issue29326

   (3) https://bugs.python.org/issue28164

   (4) https://bugs.python.org/issue29409

   (5) https://www.python.org/dev/peps/pep-0529

   (6) https://bugs.python.org/issue29392

   (7) https://bugs.python.org/issue25778

   (8) https://bugs.python.org/issue28896


File: python.info,  Node: C API<32>,  Next: 文档<41>,  Prev: Windows<38>,  Up: Python 3 6 1 rc1

1.19.55.5 C API
...............

   - bpo-27867(1): 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.

   - bpo-29083(2): 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.

   - bpo-29058(3): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27867

   (2) https://bugs.python.org/issue29083

   (3) https://bugs.python.org/issue29058


File: python.info,  Node: 文档<41>,  Next: 测试<39>,  Prev: C API<32>,  Up: Python 3 6 1 rc1

1.19.55.6 文档
..............

   - bpo-28929(1): Link the documentation to its source file on GitHub.

   - bpo-25008(2): Document smtpd.py as effectively deprecated and add a
     pointer to aiosmtpd, a third-party asyncio-based replacement.

   - bpo-26355(3): Add canonical header link on each page to
     corresponding major version of the documentation.  Patch by
     Matthias Bussonnier.

   - bpo-29349(4): Fix Python 2 syntax in code for building the
     documentation.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28929

   (2) https://bugs.python.org/issue25008

   (3) https://bugs.python.org/issue26355

   (4) https://bugs.python.org/issue29349


File: python.info,  Node: 测试<39>,  Next: 构建<41>,  Prev: 文档<41>,  Up: Python 3 6 1 rc1

1.19.55.7 测试
..............

   - bpo-28087(1): 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.

   - bpo-29571(2): to match the behaviour of the ‘re.LOCALE’ flag,
     test_re.test_locale_flag now uses
     ‘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)

   - bpo-28950(3): Disallow -j0 to be combined with -T/-l in regrtest
     command line arguments.

   - bpo-28683(4): Fix the tests that bind() a unix socket and raise
     PermissionError on Android for a non-root user.

   - bpo-26939(5): Add the support.setswitchinterval() function to fix
     test_functools hanging on the Android armv7 qemu emulator.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28087

   (2) https://bugs.python.org/issue29571

   (3) https://bugs.python.org/issue28950

   (4) https://bugs.python.org/issue28683

   (5) https://bugs.python.org/issue26939


File: python.info,  Node: 构建<41>,  Prev: 测试<39>,  Up: Python 3 6 1 rc1

1.19.55.8 构建
..............

   - bpo-27593(1): 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.

   - bpo-29572(2): 更新Windows 构建和OS X安装程序以使用OpenSSL 1.0.2k。

   - bpo-26851(3): Set Android compilation and link flags.

   - bpo-28768(4): Fix implicit declaration of function _setmode.  Patch
     by Masayuki Yamamoto

   - bpo-29080(5): Removes hard dependency on hg.exe from
     PCBuild/build.bat

   - bpo-23903(6): Added missed names to PC/python3.def.

   - bpo-28762(7): lockf() is available on Android API level 24, but the
     F_LOCK macro is not defined in android-ndk-r13.

   - bpo-28538(8): Fix the compilation error that occurs because
     if_nameindex() is available on Android API level 24, but the
     if_nameindex structure is not defined.

   - bpo-20211(9): 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.

   - bpo-28849(10): Do not define sys.implementation._multiarch on
     Android.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27593

   (2) https://bugs.python.org/issue29572

   (3) https://bugs.python.org/issue26851

   (4) https://bugs.python.org/issue28768

   (5) https://bugs.python.org/issue29080

   (6) https://bugs.python.org/issue23903

   (7) https://bugs.python.org/issue28762

   (8) https://bugs.python.org/issue28538

   (9) https://bugs.python.org/issue20211

   (10) https://bugs.python.org/issue28849


File: python.info,  Node: Python 3 6 0 正式版,  Next: Python 3 6 0 rc2,  Prev: Python 3 6 1 rc1,  Up: Changelog（更動日誌）

1.19.56 Python 3.6.0 正式版
---------------------------

`发布日期: 2016-12-23'

自rc2起没有更改


File: python.info,  Node: Python 3 6 0 rc2,  Next: Python 3 6 0 rc1,  Prev: Python 3 6 0 正式版,  Up: Changelog（更動日誌）

1.19.57 Python 3.6.0 rc2
------------------------

`发布日期: 2016-12-16'

* Menu:

* 核心与内置函数: 核心与内置函数<46>.
* 工具/示例: 工具/示例<23>.
* Windows: Windows<39>.
* 构建: 构建<42>.


File: python.info,  Node: 核心与内置函数<46>,  Next: 工具/示例<23>,  Up: Python 3 6 0 rc2

1.19.57.1 核心与内置函数
........................

   - bpo-28147(1): Fix a memory leak in split-table dictionaries:
     setattr() must not convert combined table into split table.  Patch
     written by INADA Naoki.

   - bpo-28990(2): Fix asyncio SSL hanging if connection is closed
     before handshake is completed.  (Patch by HoHo-Ho)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28147

   (2) https://bugs.python.org/issue28990


File: python.info,  Node: 工具/示例<23>,  Next: Windows<39>,  Prev: 核心与内置函数<46>,  Up: Python 3 6 0 rc2

1.19.57.2 工具/示例
...................

   - bpo-28770(1): Fix python-gdb.py for fastcalls.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28770


File: python.info,  Node: Windows<39>,  Next: 构建<42>,  Prev: 工具/示例<23>,  Up: Python 3 6 0 rc2

1.19.57.3 Windows
.................

   - bpo-28896(1): Deprecate WindowsRegistryFinder.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28896


File: python.info,  Node: 构建<42>,  Prev: Windows<39>,  Up: Python 3 6 0 rc2

1.19.57.4 构建
..............

   - bpo-28898(1): Prevent gdb build errors due to HAVE_LONG_LONG
     redefinition.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28898


File: python.info,  Node: Python 3 6 0 rc1,  Next: Python 3 6 0 beta 4,  Prev: Python 3 6 0 rc2,  Up: Changelog（更動日誌）

1.19.58 Python 3.6.0 rc1
------------------------

`发布日期: 2016-12-06'

* Menu:

* 核心与内置函数: 核心与内置函数<47>.
* 库: 库<50>.
* C API: C API<33>.
* 文档: 文档<42>.
* 工具/示例: 工具/示例<24>.


File: python.info,  Node: 核心与内置函数<47>,  Next: 库<50>,  Up: Python 3 6 0 rc1

1.19.58.1 核心与内置函数
........................

   - bpo-23722(1): Rather than silently producing a class that doesn’t
     support zero-argument ‘super()’ in methods, failing to pass the new
     ‘__classcell__’ namespace entry up to ‘type.__new__’ now results in
     a ‘DeprecationWarning’ and a class that supports zero-argument
     ‘super()’.

   - bpo-28797(2): 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.

   - bpo-28782(3): Fix a bug in the implementation ‘yield from’ when
     checking if the next instruction is YIELD_FROM. Regression
     introduced by WORDCODE (bpo-26647(4)).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23722

   (2) https://bugs.python.org/issue28797

   (3) https://bugs.python.org/issue28782

   (4) https://bugs.python.org/issue26647


File: python.info,  Node: 库<50>,  Next: C API<33>,  Prev: 核心与内置函数<47>,  Up: Python 3 6 0 rc1

1.19.58.2 库
............

   - bpo-27030(1): Unknown escapes in re.sub() replacement template are
     allowed again.  But they still are deprecated and will be disabled
     in 3.7.

   - bpo-28835(2): Fix a regression introduced in
     warnings.catch_warnings(): call warnings.showwarning() if it was
     overridden inside the context manager.

   - bpo-27172(3): To assist with upgrades from 2.7, the previously
     documented deprecation of ‘inspect.getfullargspec()’ has been
     reversed.  This decision may be revisited again after the Python
     2.7 branch is no longer officially supported.

   - bpo-26273(4): Add new ‘socket.TCP_CONGESTION’ (Linux 2.6.13) and
     ‘socket.TCP_USER_TIMEOUT’ (Linux 2.6.37) constants.  Patch written
     by Omar Sandoval.

   - bpo-24142(5): Reading a corrupt config file left configparser in an
     invalid state.  Original patch by Florian Höch.

   - bpo-28843(6): Fix asyncio C Task to handle exceptions
     __traceback__.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27030

   (2) https://bugs.python.org/issue28835

   (3) https://bugs.python.org/issue27172

   (4) https://bugs.python.org/issue26273

   (5) https://bugs.python.org/issue24142

   (6) https://bugs.python.org/issue28843


File: python.info,  Node: C API<33>,  Next: 文档<42>,  Prev: 库<50>,  Up: Python 3 6 0 rc1

1.19.58.3 C API
...............

   - bpo-28808(1): PyUnicode_CompareWithASCIIString() now never raises
     exceptions.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28808


File: python.info,  Node: 文档<42>,  Next: 工具/示例<24>,  Prev: C API<33>,  Up: Python 3 6 0 rc1

1.19.58.4 文档
..............

   - bpo-23722(1): The data model reference and the porting section in
     the What’s New guide now cover the additional ‘__classcell__’
     handling needed for custom metaclasses to fully support PEP 487(2)
     and zero-argument ‘super()’.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23722

   (2) https://www.python.org/dev/peps/pep-0487


File: python.info,  Node: 工具/示例<24>,  Prev: 文档<42>,  Up: Python 3 6 0 rc1

1.19.58.5 工具/示例
...................

   - bpo-28023(1): Fix python-gdb.py didn’t support new dict
     implementation.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28023


File: python.info,  Node: Python 3 6 0 beta 4,  Next: Python 3 6 0 beta 3,  Prev: Python 3 6 0 rc1,  Up: Changelog（更動日誌）

1.19.59 Python 3.6.0 beta 4
---------------------------

`发布日期: 2016-11-21'

* Menu:

* 核心与内置函数: 核心与内置函数<48>.
* 库: 库<51>.
* 文档: 文档<43>.
* 测试: 测试<40>.
* 构建: 构建<43>.


File: python.info,  Node: 核心与内置函数<48>,  Next: 库<51>,  Up: Python 3 6 0 beta 4

1.19.59.1 核心与内置函数
........................

   - bpo-28532(1): Show sys.version when -V option is supplied twice.

   - bpo-27100(2): 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.

   - bpo-28746(3): Fix the set_inheritable() file descriptor method on
     platforms that do not have the ioctl FIOCLEX and FIONCLEX commands.

   - bpo-26920(4): Fix not getting the locale’s charset upon
     initializing the interpreter, on platforms that do not have
     langinfo.

   - bpo-28648(5): Fixed crash in Py_DecodeLocale() in debug build on
     Mac OS X when decode astral characters.  Patch by Xiang Zhang.

   - bpo-19398(6): Extra slash no longer added to sys.path components in
     case of empty compile-time PYTHONPATH components.

   - bpo-28665(7): Improve speed of the STORE_DEREF opcode by 40%.

   - bpo-28583(8): PyDict_SetDefault didn’t combine split table when
     needed.  Patch by Xiang Zhang.

   - bpo-27243(9): 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.

   - bpo-26182(10): Fix a refleak in code that raises
     DeprecationWarning.

   - bpo-28721(11): Fix asynchronous generators aclose() and athrow() to
     handle StopAsyncIteration propagation properly.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28532

   (2) https://bugs.python.org/issue27100

   (3) https://bugs.python.org/issue28746

   (4) https://bugs.python.org/issue26920

   (5) https://bugs.python.org/issue28648

   (6) https://bugs.python.org/issue19398

   (7) https://bugs.python.org/issue28665

   (8) https://bugs.python.org/issue28583

   (9) https://bugs.python.org/issue27243

   (10) https://bugs.python.org/issue26182

   (11) https://bugs.python.org/issue28721


File: python.info,  Node: 库<51>,  Next: 文档<43>,  Prev: 核心与内置函数<48>,  Up: Python 3 6 0 beta 4

1.19.59.2 库
............

   - bpo-28752(1): Restored the __reduce__() methods of datetime
     objects.

   - bpo-28727(2): 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(3): don’t
     duplicate warning filters when the warnings module is reloaded
     (thing usually only done in unit tests).

   - bpo-20572(4): The subprocess.Popen.wait method’s undocumented
     endtime parameter now raises a DeprecationWarning.

   - bpo-25659(5): In ctypes, prevent a crash calling the from_buffer()
     and from_buffer_copy() methods on abstract classes like Array.

   - bpo-19717(6): Makes Path.resolve() succeed on paths that do not
     exist.  Patch by Vajrasky Kok

   - bpo-28563(7): 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.

   - bpo-28387(8): Fixed possible crash in _io.TextIOWrapper deallocator
     when the garbage collector is invoked in other thread.  Based on
     patch by Sebastian Cufre.

   - bpo-28600(9): Optimize loop.call_soon.

   - bpo-28613(10): Fix get_event_loop() return the current loop if
     called from coroutines/callbacks.

   - bpo-28634(11): Fix asyncio.isfuture() to support unittest.Mock.

   - bpo-26081(12): Fix refleak in _asyncio.Future.__iter__().throw.

   - bpo-28639(13): Fix inspect.isawaitable to always return bool Patch
     by Justin Mayfield.

   - bpo-28652(14): Make loop methods reject socket kinds they do not
     support.

   - bpo-28653(15): Fix a refleak in functools.lru_cache.

   - bpo-28703(16): Fix asyncio.iscoroutinefunction to handle Mock
     objects.

   - bpo-28704(17): Fix create_unix_server to support Path-like objects
     (PEP 519).

   - bpo-28720(18): Add collections.abc.AsyncGenerator.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28752

   (2) https://bugs.python.org/issue28727

   (3) https://bugs.python.org/issue18383

   (4) https://bugs.python.org/issue20572

   (5) https://bugs.python.org/issue25659

   (6) https://bugs.python.org/issue19717

   (7) https://bugs.python.org/issue28563

   (8) https://bugs.python.org/issue28387

   (9) https://bugs.python.org/issue28600

   (10) https://bugs.python.org/issue28613

   (11) https://bugs.python.org/issue28634

   (12) https://bugs.python.org/issue26081

   (13) https://bugs.python.org/issue28639

   (14) https://bugs.python.org/issue28652

   (15) https://bugs.python.org/issue28653

   (16) https://bugs.python.org/issue28703

   (17) https://bugs.python.org/issue28704

   (18) https://bugs.python.org/issue28720


File: python.info,  Node: 文档<43>,  Next: 测试<40>,  Prev: 库<51>,  Up: Python 3 6 0 beta 4

1.19.59.3 文档
..............

   - bpo-28513(1): Documented command-line interface of zipfile.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28513


File: python.info,  Node: 测试<40>,  Next: 构建<43>,  Prev: 文档<43>,  Up: Python 3 6 0 beta 4

1.19.59.4 测试
..............

   - bpo-28666(1): Now test.support.rmtree is able to remove unwritable
     or unreadable directories.

   - bpo-23839(2): Various caches now are cleared before running every
     test file.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28666

   (2) https://bugs.python.org/issue23839


File: python.info,  Node: 构建<43>,  Prev: 测试<40>,  Up: Python 3 6 0 beta 4

1.19.59.5 构建
..............

   - bpo-10656(1): Fix out-of-tree building on AIX. Patch by Tristan
     Carel and Michael Haubenwallner.

   - bpo-26359(2): Rename –with-optimiations to –enable-optimizations.

   - bpo-28676(3): Prevent missing ’getentropy’ declaration warning on
     macOS. Patch by Gareth Rees.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue10656

   (2) https://bugs.python.org/issue26359

   (3) https://bugs.python.org/issue28676


File: python.info,  Node: Python 3 6 0 beta 3,  Next: Python 3 6 0 beta 2,  Prev: Python 3 6 0 beta 4,  Up: Changelog（更動日誌）

1.19.60 Python 3.6.0 beta 3
---------------------------

`发布日期: 2016-10-31'

* Menu:

* 核心与内置函数: 核心与内置函数<49>.
* 库: 库<52>.
* Windows: Windows<40>.
* 构建: 构建<44>.
* 测试: 测试<41>.


File: python.info,  Node: 核心与内置函数<49>,  Next: 库<52>,  Up: Python 3 6 0 beta 3

1.19.60.1 核心与内置函数
........................

   - bpo-28128(1): 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.

   - bpo-28509(2): dict.update() no longer allocate unnecessary large
     memory.

   - bpo-28426(3): Fixed potential crash in PyUnicode_AsDecodedObject()
     in debug build.

   - bpo-28517(4): Fixed of-by-one error in the peephole optimizer that
     caused keeping unreachable code.

   - bpo-28214(5): Improved exception reporting for problematic
     __set_name__ attributes.

   - bpo-23782(6): Fixed possible memory leak in _PyTraceback_Add() and
     exception loss in PyTraceBack_Here().

   - bpo-28471(7): Fix "Python memory allocator called without holding
     the GIL" crash in socket.setblocking.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28128

   (2) https://bugs.python.org/issue28509

   (3) https://bugs.python.org/issue28426

   (4) https://bugs.python.org/issue28517

   (5) https://bugs.python.org/issue28214

   (6) https://bugs.python.org/issue23782

   (7) https://bugs.python.org/issue28471


File: python.info,  Node: 库<52>,  Next: Windows<40>,  Prev: 核心与内置函数<49>,  Up: Python 3 6 0 beta 3

1.19.60.2 库
............

   - bpo-27517(1): LZMA compressor and decompressor no longer raise
     exceptions if given empty data twice.  Patch by Benjamin Fogle.

   - bpo-28549(2): Fixed segfault in curses’s addch() with ncurses6.

   - bpo-28449(3): 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.

   - bpo-23262(4): The webbrowser module now supports Firefox 36+ and
     derived browsers.  Based on patch by Oleg Broytman.

   - bpo-27939(5): 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.

   - bpo-18844(6): The various ways of specifying weights for
     random.choices() now produce the same result sequences.

   - bpo-28255(7): calendar.TextCalendar().prmonth() no longer prints a
     space at the start of new line after printing a month’s calendar.
     Patch by Xiang Zhang.

   - bpo-20491(8): The textwrap.TextWrapper class now honors
     non-breaking spaces.  Based on patch by Kaarle Ritvanen.

   - bpo-28353(9): os.fwalk() no longer fails on broken links.

   - bpo-28430(10): Fix iterator of C implemented asyncio.Future doesn’t
     accept non-None value is passed to it.send(val).

   - bpo-27025(11): Generated names for Tkinter widgets now start by the
     "!"  prefix for readability.

   - bpo-25464(12): Fixed HList.header_exists() in tkinter.tix module by
     addin a workaround to Tix library bug.

   - bpo-28488(13): shutil.make_archive() no longer adds entry "./" to
     ZIP archive.

   - bpo-25953(14): 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.

   - bpo-18219(15): Optimize csv.DictWriter for large number of columns.
     Patch by Mariatta Wijaya.

   - bpo-28448(16): Fix C implemented asyncio.Future didn’t work on
     Windows.

   - bpo-28480(17): Fix error building socket module when multithreading
     is disabled.

   - bpo-24452(18): Make webbrowser support Chrome on Mac OS X.

   - bpo-20766(19): Fix references leaked by pdb in the handling of
     SIGINT handlers.

   - bpo-28492(20): Fix how StopIteration exception is raised in
     _asyncio.Future.

   - bpo-28500(21): Fix asyncio to handle async gens GC from another
     thread.

   - bpo-26923(22): Fix asyncio.Gather to refuse being cancelled once
     all children are done.  Patch by Johannes Ebke.

   - bpo-26796(23): Don’t configure the number of workers for default
     threadpool executor.  Initial patch by Hans Lawrenz.

   - bpo-28544(24): Implement asyncio.Task in C.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27517

   (2) https://bugs.python.org/issue28549

   (3) https://bugs.python.org/issue28449

   (4) https://bugs.python.org/issue23262

   (5) https://bugs.python.org/issue27939

   (6) https://bugs.python.org/issue18844

   (7) https://bugs.python.org/issue28255

   (8) https://bugs.python.org/issue20491

   (9) https://bugs.python.org/issue28353

   (10) https://bugs.python.org/issue28430

   (11) https://bugs.python.org/issue27025

   (12) https://bugs.python.org/issue25464

   (13) https://bugs.python.org/issue28488

   (14) https://bugs.python.org/issue25953

   (15) https://bugs.python.org/issue18219

   (16) https://bugs.python.org/issue28448

   (17) https://bugs.python.org/issue28480

   (18) https://bugs.python.org/issue24452

   (19) https://bugs.python.org/issue20766

   (20) https://bugs.python.org/issue28492

   (21) https://bugs.python.org/issue28500

   (22) https://bugs.python.org/issue26923

   (23) https://bugs.python.org/issue26796

   (24) https://bugs.python.org/issue28544


File: python.info,  Node: Windows<40>,  Next: 构建<44>,  Prev: 库<52>,  Up: Python 3 6 0 beta 3

1.19.60.3 Windows
.................

   - bpo-28522(1): Fixes mishandled buffer reallocation in getpathp.c

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28522


File: python.info,  Node: 构建<44>,  Next: 测试<41>,  Prev: Windows<40>,  Up: Python 3 6 0 beta 3

1.19.60.4 构建
..............

   - bpo-28444(1): Fix missing extensions modules when cross compiling.

   - bpo-28208(2): 更新Windows 构建和OS X 安装程序以使用SQLite 3.14.2.

   - bpo-28248(3): 更新Windows 构建和OS X安装程序以使用OpenSSL 1.0.2j.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28444

   (2) https://bugs.python.org/issue28208

   (3) https://bugs.python.org/issue28248


File: python.info,  Node: 测试<41>,  Prev: 构建<44>,  Up: Python 3 6 0 beta 3

1.19.60.5 测试
..............

   - bpo-26944(1): Fix test_posix for Android where ’id -G’ is entirely
     wrong or missing the effective gid.

   - bpo-28409(2): regrtest: fix the parser of command line arguments.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26944

   (2) https://bugs.python.org/issue28409


File: python.info,  Node: Python 3 6 0 beta 2,  Next: Python 3 6 0 beta 1,  Prev: Python 3 6 0 beta 3,  Up: Changelog（更動日誌）

1.19.61 Python 3.6.0 beta 2
---------------------------

`发布日期: 2016-10-10'

* Menu:

* 核心与内置函数: 核心与内置函数<50>.
* 库: 库<53>.
* Windows: Windows<41>.
* C API: C API<34>.
* 构建: 构建<45>.
* 测试: 测试<42>.


File: python.info,  Node: 核心与内置函数<50>,  Next: 库<53>,  Up: Python 3 6 0 beta 2

1.19.61.1 核心与内置函数
........................

   - bpo-28183(1): Optimize and cleanup dict iteration.

   - bpo-26081(2): Added C implementation of asyncio.Future.  Original
     patch by Yury Selivanov.

   - bpo-28379(3): Added sanity checks and tests for
     PyUnicode_CopyCharacters().  Patch by Xiang Zhang.

   - bpo-28376(4): The type of long range iterator is now registered as
     Iterator.  Patch by Oren Milman.

   - bpo-28376(5): Creating instances of range_iterator by calling
     range_iterator type now is deprecated.  Patch by Oren Milman.

   - bpo-28376(6): The constructor of range_iterator now checks that
     step is not 0.  Patch by Oren Milman.

   - bpo-26906(7): Resolving special methods of uninitialized type now
     causes implicit initialization of the type instead of a fail.

   - bpo-18287(8): PyType_Ready() now checks that tp_name is not NULL.
     Original patch by Niklas Koep.

   - bpo-24098(9): Fixed possible crash when AST is changed in process
     of compiling it.

   - bpo-28201(10): Dict reduces possibility of 2nd conflict in hash
     table when hashes have same lower bits.

   - bpo-28350(11): String constants with null character no longer
     interned.

   - bpo-26617(12): Fix crash when GC runs during weakref callbacks.

   - bpo-27942(13): String constants now interned recursively in tuples
     and frozensets.

   - bpo-21578(14): Fixed misleading error message when ImportError
     called with invalid keyword args.

   - bpo-28203(15): Fix incorrect type in complex(1.0, {2:3}) error
     message.  Patch by Soumya Sharma.

   - bpo-28086(16): Single var-positional argument of tuple subtype was
     passed unscathed to the C-defined function.  Now it is converted to
     exact tuple.

   - bpo-28214(17): Now __set_name__ is looked up on the class instead
     of the instance.

   - bpo-27955(18): Fallback on reading /dev/urandom device when the
     getrandom() syscall fails with EPERM, for example when blocked by
     SECCOMP.

   - bpo-28192(19): Don’t import readline in isolated mode.

   - Upgrade internal unicode databases to Unicode version 9.0.0.

   - bpo-28131(20): Fix a regression in zipimport’s compile_source().
     zipimport should use the same optimization level as the
     interpreter.

   - bpo-28126(21): Replace Py_MEMCPY with memcpy().  Visual Studio can
     properly optimize memcpy().

   - bpo-28120(22): Fix dict.pop() for splitted dictionary when trying
     to remove a "pending key" (Not yet inserted in split-table).  Patch
     by Xiang Zhang.

   - bpo-26182(23): Raise DeprecationWarning when async and await
     keywords are used as variable/attribute/class/function name.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28183

   (2) https://bugs.python.org/issue26081

   (3) https://bugs.python.org/issue28379

   (4) https://bugs.python.org/issue28376

   (5) https://bugs.python.org/issue28376

   (6) https://bugs.python.org/issue28376

   (7) https://bugs.python.org/issue26906

   (8) https://bugs.python.org/issue18287

   (9) https://bugs.python.org/issue24098

   (10) https://bugs.python.org/issue28201

   (11) https://bugs.python.org/issue28350

   (12) https://bugs.python.org/issue26617

   (13) https://bugs.python.org/issue27942

   (14) https://bugs.python.org/issue21578

   (15) https://bugs.python.org/issue28203

   (16) https://bugs.python.org/issue28086

   (17) https://bugs.python.org/issue28214

   (18) https://bugs.python.org/issue27955

   (19) https://bugs.python.org/issue28192

   (20) https://bugs.python.org/issue28131

   (21) https://bugs.python.org/issue28126

   (22) https://bugs.python.org/issue28120

   (23) https://bugs.python.org/issue26182


File: python.info,  Node: 库<53>,  Next: Windows<41>,  Prev: 核心与内置函数<50>,  Up: Python 3 6 0 beta 2

1.19.61.2 库
............

   - bpo-27998(1): Fixed bytes path support in os.scandir() on Windows.
     Patch by Eryk Sun.

   - bpo-28317(2): The disassembler now decodes FORMAT_VALUE argument.

   - bpo-26293(3): 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.

   - bpo-28380(4): unittest.mock Mock autospec functions now properly
     support assert_called, assert_not_called, and assert_called_once.

   - bpo-27181(5): remove statistics.geometric_mean and defer until 3.7.

   - bpo-28229(6): lzma module now supports pathlib.

   - bpo-28321(7): Fixed writing non-BMP characters with binary format
     in plistlib.

   - bpo-28225(8): bz2 module now supports pathlib.  Initial patch by
     Ethan Furman.

   - bpo-28227(9): gzip now supports pathlib.  Patch by Ethan Furman.

   - bpo-27358(10): Optimized merging var-keyword arguments and improved
     error message when passing a non-mapping as a var-keyword argument.

   - bpo-28257(11): Improved error message when passing a non-iterable
     as a var-positional argument.  Added opcode
     BUILD_TUPLE_UNPACK_WITH_CALL.

   - bpo-28322(12): Fixed possible crashes when unpickle itertools
     objects from incorrect pickle data.  Based on patch by John Leitch.

   - bpo-28228(13): imghdr now supports pathlib.

   - bpo-28226(14): compileall now supports pathlib.

   - bpo-28314(15): Fix function declaration (C flags) for the
     getiterator() method of xml.etree.ElementTree.Element.

   - bpo-28148(16): 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.

   - bpo-28253(17): 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.

   - bpo-28275(18): Fixed possible use after free in the decompress()
     methods of the LZMADecompressor and BZ2Decompressor classes.
     Original patch by John Leitch.

   - bpo-27897(19): Fixed possible crash in
     sqlite3.Connection.create_collation() if pass invalid string-like
     object as a name.  Patch by Xiang Zhang.

   - bpo-18844(20): 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.

   - bpo-18893(21): Fix invalid exception handling in
     Lib/ctypes/macholib/dyld.py.  Patch by Madison May.

   - bpo-27611(22): Fixed support of default root window in the
     tkinter.tix module.  Added the master parameter in the DisplayStyle
     constructor.

   - bpo-27348(23): In the traceback module, restore the formatting of
     exception messages like "Exception: None".  This fixes a regression
     introduced in 3.5a2.

   - bpo-25651(24): Allow falsy values to be used for msg parameter of
     subTest().

   - bpo-27778(25): Fix a memory leak in os.getrandom() when the
     getrandom() is interrupted by a signal and a signal handler raises
     a Python exception.

   - bpo-28200(26): Fix memory leak on Windows in the os module (fix
     path_converter() function).

   - bpo-25400(27): RobotFileParser now correctly returns default values
     for crawl_delay and request_rate.  Initial patch by Peter Wirtz.

   - bpo-27932(28): Prevent memory leak in win32_ver().

   - Fix UnboundLocalError in socket._sendfile_use_sendfile.

   - bpo-28075(29): Check for ERROR_ACCESS_DENIED in Windows
     implementation of os.stat().  Patch by Eryk Sun.

   - bpo-22493(30): Warning message emitted by using inline flags in the
     middle of regular expression now contains a (truncated) regex
     pattern.  Patch by Tim Graham.

   - bpo-25270(31): Prevent codecs.escape_encode() from raising
     SystemError when an empty bytestring is passed.

   - bpo-28181(32): Get antigravity over HTTPS. Patch by Kaartic
     Sivaraam.

   - bpo-25895(33): Enable WebSocket URL schemes in
     urllib.parse.urljoin.  Patch by Gergely Imreh and Markus
     Holtermann.

   - bpo-28114(34): Fix a crash in parse_envlist() when env contains
     byte strings.  Patch by Eryk Sun.

   - bpo-27599(35): Fixed buffer overrun in binascii.b2a_qp() and
     binascii.a2b_qp().

   - bpo-27906(36): Fix socket accept exhaustion during high TCP
     traffic.  Patch by Kevin Conway.

   - bpo-28174(37): Handle when SO_REUSEPORT isn’t properly supported.
     Patch by Seth Michael Larson.

   - bpo-26654(38): Inspect functools.partial in
     asyncio.Handle.__repr__.  Patch by iceboy.

   - bpo-26909(39): Fix slow pipes IO in asyncio.  Patch by INADA Naoki.

   - bpo-28176(40): Fix callbacks race in
     asyncio.SelectorLoop.sock_connect.

   - bpo-27759(41): Fix selectors incorrectly retain invalid file
     descriptors.  Patch by Mark Williams.

   - bpo-28368(42): Refuse monitoring processes if the child watcher has
     no loop attached.  Patch by Vincent Michel.

   - bpo-28369(43): Raise RuntimeError when transport’s FD is used with
     add_reader, add_writer, etc.

   - bpo-28370(44): Speedup asyncio.StreamReader.readexactly.  Patch by
     Коренберг Марк.

   - bpo-28371(45): Deprecate passing asyncio.Handles to
     run_in_executor.

   - bpo-28372(46): Fix asyncio to support formatting of non-python
     coroutines.

   - bpo-28399(47): Remove UNIX socket from FS before binding.  Patch by
     Коренберг Марк.

   - bpo-27972(48): Prohibit Tasks to await on themselves.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27998

   (2) https://bugs.python.org/issue28317

   (3) https://bugs.python.org/issue26293

   (4) https://bugs.python.org/issue28380

   (5) https://bugs.python.org/issue27181

   (6) https://bugs.python.org/issue28229

   (7) https://bugs.python.org/issue28321

   (8) https://bugs.python.org/issue28225

   (9) https://bugs.python.org/issue28227

   (10) https://bugs.python.org/issue27358

   (11) https://bugs.python.org/issue28257

   (12) https://bugs.python.org/issue28322

   (13) https://bugs.python.org/issue28228

   (14) https://bugs.python.org/issue28226

   (15) https://bugs.python.org/issue28314

   (16) https://bugs.python.org/issue28148

   (17) https://bugs.python.org/issue28253

   (18) https://bugs.python.org/issue28275

   (19) https://bugs.python.org/issue27897

   (20) https://bugs.python.org/issue18844

   (21) https://bugs.python.org/issue18893

   (22) https://bugs.python.org/issue27611

   (23) https://bugs.python.org/issue27348

   (24) https://bugs.python.org/issue25651

   (25) https://bugs.python.org/issue27778

   (26) https://bugs.python.org/issue28200

   (27) https://bugs.python.org/issue25400

   (28) https://bugs.python.org/issue27932

   (29) https://bugs.python.org/issue28075

   (30) https://bugs.python.org/issue22493

   (31) https://bugs.python.org/issue25270

   (32) https://bugs.python.org/issue28181

   (33) https://bugs.python.org/issue25895

   (34) https://bugs.python.org/issue28114

   (35) https://bugs.python.org/issue27599

   (36) https://bugs.python.org/issue27906

   (37) https://bugs.python.org/issue28174

   (38) https://bugs.python.org/issue26654

   (39) https://bugs.python.org/issue26909

   (40) https://bugs.python.org/issue28176

   (41) https://bugs.python.org/issue27759

   (42) https://bugs.python.org/issue28368

   (43) https://bugs.python.org/issue28369

   (44) https://bugs.python.org/issue28370

   (45) https://bugs.python.org/issue28371

   (46) https://bugs.python.org/issue28372

   (47) https://bugs.python.org/issue28399

   (48) https://bugs.python.org/issue27972


File: python.info,  Node: Windows<41>,  Next: C API<34>,  Prev: 库<53>,  Up: Python 3 6 0 beta 2

1.19.61.3 Windows
.................

   - bpo-28402(1): Adds signed catalog files for stdlib on Windows.

   - bpo-28333(2): Enables Unicode for ps1/ps2 and input() prompts.
     (Patch by Eryk Sun)

   - bpo-28251(3): Improvements to help manuals on Windows.

   - bpo-28110(4): launcher.msi has different product codes between
     32-bit and 64-bit

   - bpo-28161(5): Opening CON for write access fails

   - bpo-28162(6): WindowsConsoleIO readall() fails if first line starts
     with Ctrl+Z

   - bpo-28163(7): WindowsConsoleIO fileno() passes wrong flags to
     _open_osfhandle

   - bpo-28164(8): _PyIO_get_console_type fails for various paths

   - bpo-28137(9): Renames Windows path file to ._pth

   - bpo-28138(10): Windows ._pth file should allow import site

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28402

   (2) https://bugs.python.org/issue28333

   (3) https://bugs.python.org/issue28251

   (4) https://bugs.python.org/issue28110

   (5) https://bugs.python.org/issue28161

   (6) https://bugs.python.org/issue28162

   (7) https://bugs.python.org/issue28163

   (8) https://bugs.python.org/issue28164

   (9) https://bugs.python.org/issue28137

   (10) https://bugs.python.org/issue28138


File: python.info,  Node: C API<34>,  Next: 构建<45>,  Prev: Windows<41>,  Up: Python 3 6 0 beta 2

1.19.61.4 C API
...............

   - bpo-28426(1): Deprecated undocumented functions
     PyUnicode_AsEncodedObject(), PyUnicode_AsDecodedObject(),
     PyUnicode_AsDecodedUnicode() and PyUnicode_AsEncodedUnicode().

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28426


File: python.info,  Node: 构建<45>,  Next: 测试<42>,  Prev: C API<34>,  Up: Python 3 6 0 beta 2

1.19.61.5 构建
..............

   - bpo-28258(1): Fixed build with Estonian locale (python-config and
     distclean targets in Makefile).  Patch by Arfrever Frehtes
     Taifersar Arahesis.

   - bpo-26661(2): setup.py now detects system libffi with multiarch
     wrapper.

   - bpo-15819(3): Remove redundant include search directory option for
     building outside the source tree.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28258

   (2) https://bugs.python.org/issue26661

   (3) https://bugs.python.org/issue15819


File: python.info,  Node: 测试<42>,  Prev: 构建<45>,  Up: Python 3 6 0 beta 2

1.19.61.6 测试
..............

   - bpo-28217(1): Adds _testconsole module to test console input.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28217


File: python.info,  Node: Python 3 6 0 beta 1,  Next: Python 3 6 0 alpha 4,  Prev: Python 3 6 0 beta 2,  Up: Changelog（更動日誌）

1.19.62 Python 3.6.0 beta 1
---------------------------

`发布日期： 2016-09-12'

* Menu:

* 核心与内置函数: 核心与内置函数<51>.
* 库: 库<54>.
* IDLE: IDLE<39>.
* C API: C API<35>.
* 测试: 测试<43>.
* 构建: 构建<46>.
* 工具/示例: 工具/示例<25>.
* Windows: Windows<42>.


File: python.info,  Node: 核心与内置函数<51>,  Next: 库<54>,  Up: Python 3 6 0 beta 1

1.19.62.1 核心与内置函数
........................

   - bpo-23722(1): 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.

   - bpo-25221(2): Fix corrupted result from PyLong_FromLong(0) when
     Python is compiled with NSMALLPOSINTS = 0.

   - bpo-27080(3): Implement formatting support for PEP 515(4).  Initial
     patch by Chris Angelico.

   - bpo-27199(5): In tarfile, expose copyfileobj bufsize to improve
     throughput.  Patch by Jason Fried.

   - bpo-27948(6): 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
     ‘f'\x7b"hi"\x7d'’.

   - bpo-28046(7): Remove platform-specific directories from sys.path.

   - bpo-28071(8): Add early-out for differencing from an empty set.

   - bpo-25758(9): Prevents zipimport from unnecessarily encoding a
     filename (patch by Eryk Sun)

   - bpo-25856(10): The __module__ attribute of extension classes and
     functions now is interned.  This leads to more compact pickle data
     with protocol 4.

   - bpo-27213(11): 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.

   - bpo-26331(12): Implement tokenizing support for PEP 515(13).  Patch
     by Georg Brandl.

   - bpo-27999(14): Make "global after use" a SyntaxError, and ditto for
     nonlocal.  Patch by Ivan Levkivskyi.

   - bpo-28003(15): Implement PEP 525(16) – Asynchronous Generators.

   - bpo-27985(17): Implement PEP 526(18) – Syntax for Variable
     Annotations.  Patch by Ivan Levkivskyi.

   - bpo-26058(19): 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.

   - bpo-27364(20): A backslash-character pair that is not a valid
     escape sequence now generates a DeprecationWarning.  Patch by
     Emanuel Barry.

   - bpo-27350(21): *note dict: 164. implementation is changed like
     PyPy.  It is more compact and preserves insertion order.  (Concept
     developed by Raymond Hettinger and patch by Inada Naoki.)

   - bpo-27911(22): Remove unnecessary error checks in
     ‘exec_builtin_or_dynamic()’.

   - bpo-27078(23): Added BUILD_STRING opcode.  Optimized f-strings
     evaluation.

   - bpo-17884(24): Python now requires systems with inttypes.h and
     stdint.h

   - bpo-27961(25): Require platforms to support ‘long long’.  Python
     hasn’t compiled without ‘long long’ for years, so this is basically
     a formality.

   - bpo-27355(26): Removed support for Windows CE. It was never
     finished, and Windows CE is no longer a relevant platform for
     Python.

   - Implement PEP 523(27).

   - bpo-27870(28): A left shift of zero by a large integer no longer
     attempts to allocate large amounts of memory.

   - bpo-25402(29): 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.

   - bpo-27214(30): 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.

   - bpo-27506(31): Support passing the bytes/bytearray.translate()
     "delete" argument by keyword.

   - bpo-27812(32): Properly clear out a generator’s frame’s
     backreference to the generator to prevent crashes in frame.clear().

   - bpo-27811(33): Fix a crash when a coroutine that has not been
     awaited is finalized with warnings-as-errors enabled.

   - bpo-27587(34): Fix another issue found by PVS-Studio: Null pointer
     check after use of ’def’ in _PyState_AddModule().  Initial patch by
     Christian Heimes.

   - bpo-27792(35): The modulo operation applied to ‘bool’ and other
     ‘int’ subclasses now always returns an ‘int’.  Previously the
     return type depended on the input values.  Patch by Xiang Zhang.

   - bpo-26984(36): int() now always returns an instance of exact int.

   - bpo-25604(37): 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.

   - bpo-24254(38): Make class definition namespace ordered by default.

   - bpo-27662(39): Fix an overflow check in ‘List_New’: the original
     code was checking against ‘Py_SIZE_MAX’ instead of the correct
     upper bound of ‘Py_SSIZE_T_MAX’.  Patch by Xiang Zhang.

   - bpo-27782(40): Multi-phase extension module import now correctly
     allows the ‘m_methods’ field to be used to add module level
     functions to instances of non-module types returned from
     ‘Py_create_mod’.  Patch by Xiang Zhang.

   - bpo-27936(41): 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.

   - bpo-27487(42): 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.

   - bpo-27157(43): Make only type() itself accept the one-argument
     form.  Patch by Eryk Sun and Emanuel Barry.

   - bpo-27558(44): 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.

   - bpo-28008(45): Implement PEP 530(46) – asynchronous comprehensions.

   - bpo-27942(47): Fix memory leak in codeobject.c

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23722

   (2) https://bugs.python.org/issue25221

   (3) https://bugs.python.org/issue27080

   (4) https://www.python.org/dev/peps/pep-0515

   (5) https://bugs.python.org/issue27199

   (6) https://bugs.python.org/issue27948

   (7) https://bugs.python.org/issue28046

   (8) https://bugs.python.org/issue28071

   (9) https://bugs.python.org/issue25758

   (10) https://bugs.python.org/issue25856

   (11) https://bugs.python.org/issue27213

   (12) https://bugs.python.org/issue26331

   (13) https://www.python.org/dev/peps/pep-0515

   (14) https://bugs.python.org/issue27999

   (15) https://bugs.python.org/issue28003

   (16) https://www.python.org/dev/peps/pep-0525

   (17) https://bugs.python.org/issue27985

   (18) https://www.python.org/dev/peps/pep-0526

   (19) https://bugs.python.org/issue26058

   (20) https://bugs.python.org/issue27364

   (21) https://bugs.python.org/issue27350

   (22) https://bugs.python.org/issue27911

   (23) https://bugs.python.org/issue27078

   (24) https://bugs.python.org/issue17884

   (25) https://bugs.python.org/issue27961

   (26) https://bugs.python.org/issue27355

   (27) https://www.python.org/dev/peps/pep-0523

   (28) https://bugs.python.org/issue27870

   (29) https://bugs.python.org/issue25402

   (30) https://bugs.python.org/issue27214

   (31) https://bugs.python.org/issue27506

   (32) https://bugs.python.org/issue27812

   (33) https://bugs.python.org/issue27811

   (34) https://bugs.python.org/issue27587

   (35) https://bugs.python.org/issue27792

   (36) https://bugs.python.org/issue26984

   (37) https://bugs.python.org/issue25604

   (38) https://bugs.python.org/issue24254

   (39) https://bugs.python.org/issue27662

   (40) https://bugs.python.org/issue27782

   (41) https://bugs.python.org/issue27936

   (42) https://bugs.python.org/issue27487

   (43) https://bugs.python.org/issue27157

   (44) https://bugs.python.org/issue27558

   (45) https://bugs.python.org/issue28008

   (46) https://www.python.org/dev/peps/pep-0530

   (47) https://bugs.python.org/issue27942


File: python.info,  Node: 库<54>,  Next: IDLE<39>,  Prev: 核心与内置函数<51>,  Up: Python 3 6 0 beta 1

1.19.62.2 库
............

   - bpo-28732(1): Fix crash in os.spawnv() with no elements in args

   - bpo-28485(2): Always raise ValueError for negative
     compileall.compile_dir(workers=...)  parameter, even when
     multithreading is unavailable.

   - bpo-28037(3): Use sqlite3_get_autocommit() instead of setting
     Connection->inTransaction manually.

   - bpo-25283(4): Attributes tm_gmtoff and tm_zone are now available on
     all platforms in the return values of time.localtime() and
     time.gmtime().

   - bpo-24454(5): Regular expression match object groups are now
     accessible using __getitem__.  "mo[x]" is equivalent to
     "mo.group(x)".

   - bpo-10740(6): sqlite3 no longer implicitly commit an open
     transaction before DDL statements.

   - bpo-17941(7): Add a `module' parameter to collections.namedtuple().

   - bpo-22493(8): 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.

   - bpo-26885(9): xmlrpc now supports unmarshalling additional data
     types used by Apache XML-RPC implementation for numerics and None.

   - bpo-28070(10): Fixed parsing inline verbose flag in regular
     expressions.

   - bpo-19500(11): Add client-side SSL session resumption to the ssl
     module.

   - bpo-28022(12): 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.

   - bpo-28043(13): 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.

   - bpo-24693(14): Changed some RuntimeError’s in the zipfile module to
     more appropriate types.  Improved some error messages and debugging
     output.

   - bpo-17909(15): ‘json.load’ and ‘json.loads’ now support binary
     input encoded as UTF-8, UTF-16 or UTF-32.  Patch by Serhiy
     Storchaka.

   - bpo-27137(16): the pure Python fallback implementation of
     ‘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.

   - Fix possible integer overflows and crashes in the mmap module with
     unusual usage patterns.

   - bpo-1703178(17): Fix the ability to pass the –link-objects option
     to the distutils build_ext command.

   - bpo-28019(18): itertools.count() no longer rounds non-integer step
     in range between 1.0 and 2.0 to 1.

   - bpo-18401(19): Pdb now supports the ’readrc’ keyword argument to
     control whether .pdbrc files should be read.  Patch by Martin
     Matusiak and Sam Kimbrel.

   - bpo-25969(20): Update the lib2to3 grammar to handle the unpacking
     generalizations added in 3.5.

   - bpo-14977(21): mailcap now respects the order of the lines in the
     mailcap files ("first match"), as required by RFC 1542.  Patch by
     Michael Lazar.

   - bpo-28082(22): Convert re flag constants to IntFlag.

   - bpo-28025(23): Convert all ssl module constants to IntEnum and
     IntFlags.  SSLContext properties now return flags and enums.

   - bpo-23591(24): Add Flag, IntFlag, and auto() to enum module.

   - bpo-433028(25): Added support of modifier spans in regular
     expressions.

   - bpo-24594(26): Validates persist parameter when opening MSI
     database

   - bpo-17582(27): xml.etree.ElementTree nows preserves whitespaces in
     attributes (Patch by Duane Griffin.  Reviewed and approved by
     Stefan Behnel.)

   - bpo-28047(28): Fixed calculation of line length used for the base64
     CTE in the new email policies.

   - bpo-27576(29): Fix call order in OrderedDict.__init__().

   - email.generator.DecodedGenerator now supports the policy keyword.

   - bpo-28027(30): Remove undocumented modules from ‘Lib/plat-*’: IN,
     CDROM, DLFCN, TYPES, CDIO, and STROPTS.

   - bpo-27445(31): Don’t pass str(_charset) to MIMEText.set_payload().
     Patch by Claude Paroz.

   - bpo-24277(32): The new email API is no longer provisional, and the
     docs have been reorganized and rewritten to emphasize the new API.

   - bpo-22450(33): urllib now includes an ‘Accept: */*’ header among
     the default headers.  This makes the results of REST API requests
     more consistent and predictable especially when proxy servers are
     involved.

   - 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.

   - bpo-28005(34): Allow ImportErrors in encoding implementation to
     propagate.

   - bpo-26667(35): Support path-like objects in importlib.util.

   - bpo-27570(36): Avoid zero-length memcpy() etc calls with null
     source pointers in the "ctypes" and "array" modules.

   - bpo-22233(37): Break email header lines `only' on the RFC specified
     CR and LF characters, not on arbitrary unicode line breaks.  This
     also fixes a bug in HTTP header parsing.

   - bpo-27331(38): The email.mime classes now all accept an optional
     policy keyword.

   - bpo-27988(39): Fix email iter_attachments incorrect mutation of
     payload list.

   - bpo-16113(40): Add SHA-3 and SHAKE support to hashlib module.

   - Eliminate a tautological-pointer-compare warning in _scproxy.c.

   - bpo-27776(41): The *note os.urandom(): 5cb. 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
     PEP 524(42).

   - bpo-27778(43): Expose the Linux ‘getrandom()’ syscall as a new
     *note os.getrandom(): 662. function.  This change is part of the
     PEP 524(44).

   - bpo-27691(45): Fix ssl module’s parsing of GEN_RID subject
     alternative name fields in X.509 certs.

   - bpo-18844(46): Add random.choices().

   - bpo-25761(47): Improved error reporting about truncated pickle data
     in C implementation of unpickler.  UnpicklingError is now raised
     instead of AttributeError and ValueError in some cases.

   - bpo-26798(48): Add BLAKE2 (blake2b and blake2s) to hashlib.

   - bpo-26032(49): Optimized globbing in pathlib by using os.scandir();
     it is now about 1.5–4 times faster.

   - bpo-25596(50): Optimized glob() and iglob() functions in the glob
     module; they are now about 3–6 times faster.

   - bpo-27928(51): Add scrypt (password-based key derivation function)
     to hashlib module (requires OpenSSL 1.1.0).

   - bpo-27850(52): Remove 3DES from ssl module’s default cipher list to
     counter measure sweet32 attack (CVE-2016-2183).

   - bpo-27766(53): Add ChaCha20 Poly1305 to ssl module’s default cipher
     list.  (Required OpenSSL 1.1.0 or LibreSSL).

   - bpo-25387(54): Check return value of winsound.MessageBeep.

   - bpo-27866(55): Add SSLContext.get_ciphers() method to get a list of
     all enabled ciphers.

   - bpo-27744(56): Add AF_ALG (Linux Kernel crypto) to socket module.

   - bpo-26470(57): Port ssl and hashlib module to OpenSSL 1.1.0.

   - bpo-11620(58): Fix support for SND_MEMORY in winsound.PlaySound.
     Based on a patch by Tim Lesher.

   - bpo-11734(59): Add support for IEEE 754 half-precision floats to
     the struct module.  Based on a patch by Eli Stevens.

   - bpo-27919(60): Deprecated ‘extra_path’ distribution option in
     distutils packaging.

   - bpo-23229(61): Add new ‘cmath’ constants: ‘cmath.inf’ and
     ‘cmath.nan’ to match ‘math.inf’ and ‘math.nan’, and also
     ‘cmath.infj’ and ‘cmath.nanj’ to match the format used by complex
     repr.

   - bpo-27842(62): The csv.DictReader now returns rows of type
     OrderedDict.  (Contributed by Steve Holden.)

   - Remove support for passing a file descriptor to os.access.  It
     never worked but previously didn’t raise.

   - bpo-12885(63): Fix error when distutils encounters symlink.

   - bpo-27881(64): Fixed possible bugs when setting
     sqlite3.Connection.isolation_level.  Based on patch by Xiang Zhang.

   - bpo-27861(65): Fixed a crash in sqlite3.Connection.cursor() when a
     factory creates not a cursor.  Patch by Xiang Zhang.

   - bpo-19884(66): Avoid spurious output on OS X with Gnu Readline.

   - bpo-27706(67): 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.

   - bpo-10513(68): Fix a regression in Connection.commit().  Statements
     should not be reset after a commit.

   - bpo-12319(69): 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.

   - A new version of typing.py from ‘https://github.com/python/typing’:
     - Collection (only for 3.6) (bpo-27598(70)) - Add FrozenSet to
     __all__ (upstream #261) - fix crash in _get_type_vars() (upstream
     #259) - Remove the dict constraint in ForwardRef._eval_type
     (upstream #252)

   - bpo-27832(71): Make ‘_normalize’ parameter to ‘Fraction’
     constructor keyword-only, so that ‘Fraction(2, 3, 4)’ now raises
     ‘TypeError’.

   - bpo-27539(72): Fix unnormalised ‘Fraction.__pow__’ result in the
     case of negative exponent and negative base.

   - bpo-21718(73): cursor.description is now available for queries
     using CTEs.

   - bpo-27819(74): In distutils sdists, simply produce the "gztar"
     (gzipped tar format) distributions on all platforms unless
     "formats" is supplied.

   - bpo-2466(75): posixpath.ismount now correctly recognizes mount
     points which the user does not have permission to access.

   - bpo-9998(76): On Linux, ctypes.util.find_library now looks in
     LD_LIBRARY_PATH for shared libraries.

   - bpo-27573(77): exit message for code.interact is now configurable.

   - bpo-27930(78): Improved behaviour of
     logging.handlers.QueueListener.  Thanks to Paulo Andrade and Petr
     Viktorin for the analysis and patch.

   - bpo-6766(79): Distributed reference counting added to
     multiprocessing to support nesting of shared values / proxy
     objects.

   - bpo-21201(80): Improves readability of multiprocessing error
     message.  Thanks to Wojciech Walczak for patch.

   - asyncio: 在各Transport类中添加了 set_protocol / get_protocol 方法

   - bpo-27456(81): asyncio: Set TCP_NODELAY by default.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28732

   (2) https://bugs.python.org/issue28485

   (3) https://bugs.python.org/issue28037

   (4) https://bugs.python.org/issue25283

   (5) https://bugs.python.org/issue24454

   (6) https://bugs.python.org/issue10740

   (7) https://bugs.python.org/issue17941

   (8) https://bugs.python.org/issue22493

   (9) https://bugs.python.org/issue26885

   (10) https://bugs.python.org/issue28070

   (11) https://bugs.python.org/issue19500

   (12) https://bugs.python.org/issue28022

   (13) https://bugs.python.org/issue28043

   (14) https://bugs.python.org/issue24693

   (15) https://bugs.python.org/issue17909

   (16) https://bugs.python.org/issue27137

   (17) https://bugs.python.org/issue1703178

   (18) https://bugs.python.org/issue28019

   (19) https://bugs.python.org/issue18401

   (20) https://bugs.python.org/issue25969

   (21) https://bugs.python.org/issue14977

   (22) https://bugs.python.org/issue28082

   (23) https://bugs.python.org/issue28025

   (24) https://bugs.python.org/issue23591

   (25) https://bugs.python.org/issue433028

   (26) https://bugs.python.org/issue24594

   (27) https://bugs.python.org/issue17582

   (28) https://bugs.python.org/issue28047

   (29) https://bugs.python.org/issue27576

   (30) https://bugs.python.org/issue28027

   (31) https://bugs.python.org/issue27445

   (32) https://bugs.python.org/issue24277

   (33) https://bugs.python.org/issue22450

   (34) https://bugs.python.org/issue28005

   (35) https://bugs.python.org/issue26667

   (36) https://bugs.python.org/issue27570

   (37) https://bugs.python.org/issue22233

   (38) https://bugs.python.org/issue27331

   (39) https://bugs.python.org/issue27988

   (40) https://bugs.python.org/issue16113

   (41) https://bugs.python.org/issue27776

   (42) https://www.python.org/dev/peps/pep-0524

   (43) https://bugs.python.org/issue27778

   (44) https://www.python.org/dev/peps/pep-0524

   (45) https://bugs.python.org/issue27691

   (46) https://bugs.python.org/issue18844

   (47) https://bugs.python.org/issue25761

   (48) https://bugs.python.org/issue26798

   (49) https://bugs.python.org/issue26032

   (50) https://bugs.python.org/issue25596

   (51) https://bugs.python.org/issue27928

   (52) https://bugs.python.org/issue27850

   (53) https://bugs.python.org/issue27766

   (54) https://bugs.python.org/issue25387

   (55) https://bugs.python.org/issue27866

   (56) https://bugs.python.org/issue27744

   (57) https://bugs.python.org/issue26470

   (58) https://bugs.python.org/issue11620

   (59) https://bugs.python.org/issue11734

   (60) https://bugs.python.org/issue27919

   (61) https://bugs.python.org/issue23229

   (62) https://bugs.python.org/issue27842

   (63) https://bugs.python.org/issue12885

   (64) https://bugs.python.org/issue27881

   (65) https://bugs.python.org/issue27861

   (66) https://bugs.python.org/issue19884

   (67) https://bugs.python.org/issue27706

   (68) https://bugs.python.org/issue10513

   (69) https://bugs.python.org/issue12319

   (70) https://bugs.python.org/issue27598

   (71) https://bugs.python.org/issue27832

   (72) https://bugs.python.org/issue27539

   (73) https://bugs.python.org/issue21718

   (74) https://bugs.python.org/issue27819

   (75) https://bugs.python.org/issue2466

   (76) https://bugs.python.org/issue9998

   (77) https://bugs.python.org/issue27573

   (78) https://bugs.python.org/issue27930

   (79) https://bugs.python.org/issue6766

   (80) https://bugs.python.org/issue21201

   (81) https://bugs.python.org/issue27456


File: python.info,  Node: IDLE<39>,  Next: C API<35>,  Prev: 库<54>,  Up: Python 3 6 0 beta 1

1.19.62.3 IDLE
..............

   - bpo-15308(1): Add ’interrupt execution’ (^C) to Shell menu.  Patch
     by Roger Serwy, updated by Bayard Randel.

   - bpo-27922(2): Stop IDLE tests from ’flashing’ gui widgets on the
     screen.

   - bpo-27891(3): Consistently group and sort imports within idlelib
     modules.

   - bpo-17642(4): add larger font sizes for classroom projection.

   - 在 IDLE 帮助窗口的标题中加入版本号

   - bpo-25564(5): In section on IDLE – console differences, mention
     that using exec means that __builtins__ is defined for each
     statement.

   - bpo-27821(6): Fix 3.6.0a3 regression that prevented custom key sets
     from being selected when no custom theme was defined.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15308

   (2) https://bugs.python.org/issue27922

   (3) https://bugs.python.org/issue27891

   (4) https://bugs.python.org/issue17642

   (5) https://bugs.python.org/issue25564

   (6) https://bugs.python.org/issue27821


File: python.info,  Node: C API<35>,  Next: 测试<43>,  Prev: IDLE<39>,  Up: Python 3 6 0 beta 1

1.19.62.4 C API
...............

   - bpo-26900(1): Excluded underscored names and other private API from
     limited API.

   - bpo-26027(2): Add support for path-like objects in
     PyUnicode_FSConverter() & PyUnicode_FSDecoder().

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26900

   (2) https://bugs.python.org/issue26027


File: python.info,  Node: 测试<43>,  Next: 构建<46>,  Prev: C API<35>,  Up: Python 3 6 0 beta 1

1.19.62.5 测试
..............

   - bpo-27427(1): Additional tests for the math module.  Patch by
     Francisco Couzo.

   - bpo-27953(2): Skip math and cmath tests that fail on OS X 10.4 due
     to a poor libm implementation of tan.

   - bpo-26040(3): Improve test_math and test_cmath coverage and rigour.
     Patch by Jeff Allen.

   - bpo-27787(4): Call gc.collect() before checking each test for
     "dangling threads", since the dangling threads are weak references.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27427

   (2) https://bugs.python.org/issue27953

   (3) https://bugs.python.org/issue26040

   (4) https://bugs.python.org/issue27787


File: python.info,  Node: 构建<46>,  Next: 工具/示例<25>,  Prev: 测试<43>,  Up: Python 3 6 0 beta 1

1.19.62.6 构建
..............

   - bpo-27566(1): Fix clean target in freeze makefile (patch by Lisa
     Roach)

   - bpo-27705(2): Update message in validate_ucrtbase.py

   - bpo-27976(3): Deprecate building _ctypes with the bundled copy of
     libffi on non-OSX UNIX platforms.

   - bpo-27983(4): 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.

   - bpo-21590(5): Support for DTrace and SystemTap probes.

   - bpo-26307(6): The profile-opt build now applies PGO to the built-in
     modules.

   - bpo-26359(7): Add the –with-optimizations flag to turn on LTO and
     PGO build support when available.

   - bpo-27917(8): Set platform triplets for Android builds.

   - bpo-25825(9): Update references to the $(LIBPL) installation path
     on AIX. This path was changed in 3.2a4.

   - 更新 OS X 安装包，使用SQLite 3.14.1 和 XZ 5.2.2版本。

   - bpo-21122(10): Fix LTO builds on OS X.

   - bpo-17128(11): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27566

   (2) https://bugs.python.org/issue27705

   (3) https://bugs.python.org/issue27976

   (4) https://bugs.python.org/issue27983

   (5) https://bugs.python.org/issue21590

   (6) https://bugs.python.org/issue26307

   (7) https://bugs.python.org/issue26359

   (8) https://bugs.python.org/issue27917

   (9) https://bugs.python.org/issue25825

   (10) https://bugs.python.org/issue21122

   (11) https://bugs.python.org/issue17128


File: python.info,  Node: 工具/示例<25>,  Next: Windows<42>,  Prev: 构建<46>,  Up: Python 3 6 0 beta 1

1.19.62.7 工具/示例
...................

   - bpo-27952(1): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27952


File: python.info,  Node: Windows<42>,  Prev: 工具/示例<25>,  Up: Python 3 6 0 beta 1

1.19.62.8 Windows
.................

   - bpo-28065(1): Update xz dependency to 5.2.2 and build it from
     source.

   - bpo-25144(2): Ensures TargetDir is set before continuing with
     custom install.

   - bpo-1602(3): Windows console doesn’t input or print Unicode (PEP
     528)

   - bpo-27781(4): Change file system encoding on Windows to UTF-8 (PEP
     529)

   - bpo-27731(5): Opt-out of MAX_PATH on Windows 10

   - bpo-6135(6): Adds encoding and errors parameters to subprocess.

   - bpo-27959(7): Adds oem encoding, alias ansi to mbcs, move aliasmbcs
     to codec lookup.

   - bpo-27982(8): The functions of the winsound module now accept
     keyword arguments.

   - bpo-20366(9): Build full text search support into SQLite on
     Windows.

   - bpo-27756(10): Adds new icons for Python files and processes on
     Windows.  Designs by Cherry Wang.

   - bpo-27883(11): 在Windows上将sqlite更新到3.14.1.0

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28065

   (2) https://bugs.python.org/issue25144

   (3) https://bugs.python.org/issue1602

   (4) https://bugs.python.org/issue27781

   (5) https://bugs.python.org/issue27731

   (6) https://bugs.python.org/issue6135

   (7) https://bugs.python.org/issue27959

   (8) https://bugs.python.org/issue27982

   (9) https://bugs.python.org/issue20366

   (10) https://bugs.python.org/issue27756

   (11) https://bugs.python.org/issue27883


File: python.info,  Node: Python 3 6 0 alpha 4,  Next: Python 3 6 0 alpha 3,  Prev: Python 3 6 0 beta 1,  Up: Changelog（更動日誌）

1.19.63 Python 3.6.0 alpha 4
----------------------------

`发布日期: 2016-08-15'

* Menu:

* 核心与内置函数: 核心与内置函数<52>.
* 库: 库<55>.
* IDLE: IDLE<40>.
* 测试: 测试<44>.
* Windows: Windows<43>.
* 构建: 构建<47>.


File: python.info,  Node: 核心与内置函数<52>,  Next: 库<55>,  Up: Python 3 6 0 alpha 4

1.19.63.1 核心与内置函数
........................

   - bpo-27704(1): Optimized creating bytes and bytearray from byte-like
     objects and iterables.  Speed up to 3 times for short objects.
     Original patch by Naoki Inada.

   - bpo-26823(2): 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.

   - bpo-27574(3): Decreased an overhead of parsing keyword arguments in
     functions implemented with using Argument Clinic.

   - bpo-22557(4): Now importing already imported modules is up to 2.5
     times faster.

   - bpo-17596(5): Include <wincrypt.h> to help with Min GW building.

   - bpo-17599(6): On Windows, rename the privately defined
     REPARSE_DATA_BUFFER structure to avoid conflicting with the
     definition from Min GW.

   - bpo-27507(7): Add integer overflow check in bytearray.extend().
     Patch by Xiang Zhang.

   - bpo-27581(8): Don’t rely on wrapping for overflow check in
     PySequence_Tuple().  Patch by Xiang Zhang.

   - bpo-1621(9): Avoid signed integer overflow in list and tuple
     operations.  Patch by Xiang Zhang.

   - bpo-27419(10): 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__.

   - bpo-27083(11): Respect the PYTHONCASEOK environment variable under
     Windows.

   - bpo-27514(12): Make having too many statically nested blocks a
     SyntaxError instead of SystemError.

   - bpo-27366(13): Implemented PEP 487(14) (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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27704

   (2) https://bugs.python.org/issue26823

   (3) https://bugs.python.org/issue27574

   (4) https://bugs.python.org/issue22557

   (5) https://bugs.python.org/issue17596

   (6) https://bugs.python.org/issue17599

   (7) https://bugs.python.org/issue27507

   (8) https://bugs.python.org/issue27581

   (9) https://bugs.python.org/issue1621

   (10) https://bugs.python.org/issue27419

   (11) https://bugs.python.org/issue27083

   (12) https://bugs.python.org/issue27514

   (13) https://bugs.python.org/issue27366

   (14) https://www.python.org/dev/peps/pep-0487


File: python.info,  Node: 库<55>,  Next: IDLE<40>,  Prev: 核心与内置函数<52>,  Up: Python 3 6 0 alpha 4

1.19.63.2 库
............

   - bpo-26027(1): Add PEP 519(2)/__fspath__() support to the os and
     os.path modules.  Includes code from Jelle Zijlstra.  (See also:
     bpo-27524(3))

   - bpo-27598(4): Add Collections to collections.abc.  Patch by Ivan
     Levkivskyi, docs by Neil Girdhar.

   - bpo-25958(5): 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.

   - bpo-16764(6): Support keyword arguments to zlib.decompress().
     Patch by Xiang Zhang.

   - bpo-27736(7): Prevent segfault after interpreter re-initialization
     due to ref count problem introduced in code for bpo-27038(8) in
     3.6.0a3.  Patch by Xiang Zhang.

   - bpo-25628(9): The `verbose' and `rename' parameters for
     collections.namedtuple are now keyword-only.

   - bpo-12345(10): Add mathematical constant tau to math and cmath.
     See also PEP 628(11).

   - bpo-26823(12): 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.

   - bpo-27664(13): Add to
     concurrent.futures.thread.ThreadPoolExecutor() the ability to
     specify a thread name prefix.

   - bpo-27181(14): Add geometric_mean and harmonic_mean to statistics
     module.

   - bpo-27573(15): code.interact now prints an message when exiting.

   - bpo-6422(16): Add autorange method to timeit.Timer objects.

   - bpo-27773(17): Correct some memory management errors
     server_hostname in _ssl.wrap_socket().

   - bpo-26750(18): 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.

   - bpo-26754(19): Undocumented support of general bytes-like objects
     as path in compile() and similar functions is now deprecated.

   - bpo-26800(20): Undocumented support of general bytes-like objects
     as paths in os functions is now deprecated.

   - bpo-26981(21): Add _order_ compatibility shim to enum.Enum for
     Python 2/3 code bases.

   - bpo-27661(22): Added tzinfo keyword argument to datetime.combine.

   - In the curses module, raise an error if window.getstr() or
     window.instr() is passed a negative value.

   - bpo-27783(23): Fix possible usage of uninitialized memory in
     operator.methodcaller.

   - bpo-27774(24): Fix possible Py_DECREF on unowned object in _sre.

   - bpo-27760(25): Fix possible integer overflow in binascii.b2a_qp.

   - bpo-27758(26): Fix possible integer overflow in the _csv module for
     large record lengths.

   - bpo-27568(27): 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.

   - bpo-7063(28): Remove dead code from the "array" module’s slice
     handling.  Patch by Chuck.

   - bpo-27656(29): Do not assume sched.h defines any SCHED_* constants.

   - bpo-27130(30): 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.

   - bpo-24773(31): Implemented PEP 495(32) (Local Time Disambiguation).

   - Expose the EPOLLEXCLUSIVE constant (when it is defined) in the
     select module.

   - bpo-27567(33): Expose the EPOLLRDHUP and POLLRDHUP constants in the
     select module.

   - bpo-1621(34): Avoid signed int negation overflow in the "audioop"
     module.

   - bpo-27533(35): Release GIL in nt._isdir

   - bpo-17711(36): Fixed unpickling by the persistent ID with protocol
     0.  Original patch by Alexandre Vassalotti.

   - bpo-27522(37): Avoid an unintentional reference cycle in
     email.feedparser.

   - bpo-27512(38): Fix a segfault when os.fspath() called an
     __fspath__() method that raised an exception.  Patch by Xiang
     Zhang.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26027

   (2) https://www.python.org/dev/peps/pep-0519

   (3) https://bugs.python.org/issue27524

   (4) https://bugs.python.org/issue27598

   (5) https://bugs.python.org/issue25958

   (6) https://bugs.python.org/issue16764

   (7) https://bugs.python.org/issue27736

   (8) https://bugs.python.org/issue27038

   (9) https://bugs.python.org/issue25628

   (10) https://bugs.python.org/issue12345

   (11) https://www.python.org/dev/peps/pep-0628

   (12) https://bugs.python.org/issue26823

   (13) https://bugs.python.org/issue27664

   (14) https://bugs.python.org/issue27181

   (15) https://bugs.python.org/issue27573

   (16) https://bugs.python.org/issue6422

   (17) https://bugs.python.org/issue27773

   (18) https://bugs.python.org/issue26750

   (19) https://bugs.python.org/issue26754

   (20) https://bugs.python.org/issue26800

   (21) https://bugs.python.org/issue26981

   (22) https://bugs.python.org/issue27661

   (23) https://bugs.python.org/issue27783

   (24) https://bugs.python.org/issue27774

   (25) https://bugs.python.org/issue27760

   (26) https://bugs.python.org/issue27758

   (27) https://bugs.python.org/issue27568

   (28) https://bugs.python.org/issue7063

   (29) https://bugs.python.org/issue27656

   (30) https://bugs.python.org/issue27130

   (31) https://bugs.python.org/issue24773

   (32) https://www.python.org/dev/peps/pep-0495

   (33) https://bugs.python.org/issue27567

   (34) https://bugs.python.org/issue1621

   (35) https://bugs.python.org/issue27533

   (36) https://bugs.python.org/issue17711

   (37) https://bugs.python.org/issue27522

   (38) https://bugs.python.org/issue27512


File: python.info,  Node: IDLE<40>,  Next: 测试<44>,  Prev: 库<55>,  Up: Python 3 6 0 alpha 4

1.19.63.3 IDLE
..............

   - bpo-27714(1): 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.

   - bpo-27621(2): 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.

   - bpo-27620(3): Escape key now closes Query box as cancelled.

   - bpo-27609(4): IDLE: tab after initial whitespace should tab, not
     autocomplete.  This fixes problem with writing docstrings at least
     twice indented.

   - bpo-27609(5): Explicitly return None when there are also non-None
     returns.  In a few cases, reverse a condition and eliminate a
     return.

   - bpo-25507(6): IDLE no longer runs buggy code because of its tkinter
     imports.  Users must include the same imports required to run
     directly in Python.

   - bpo-27173(7): 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.

   - bpo-27452(8): add line counter and crc to IDLE configHandler test
     dump.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27714

   (2) https://bugs.python.org/issue27621

   (3) https://bugs.python.org/issue27620

   (4) https://bugs.python.org/issue27609

   (5) https://bugs.python.org/issue27609

   (6) https://bugs.python.org/issue25507

   (7) https://bugs.python.org/issue27173

   (8) https://bugs.python.org/issue27452


File: python.info,  Node: 测试<44>,  Next: Windows<43>,  Prev: IDLE<40>,  Up: Python 3 6 0 alpha 4

1.19.63.4 测试
..............

   - bpo-25805(1): Skip a test in test_pkgutil as needed that doesn’t
     work when ‘__name__ == __main__’.  Patch by SilentGhost.

   - bpo-27472(2): Add test.support.unix_shell as the path to the
     default shell.

   - bpo-27369(3): In test_pyexpat, avoid testing an error message
     detail that changed in Expat 2.2.0.

   - bpo-27594(4): Prevent assertion error when running test_ast with
     coverage enabled: ensure code object has a valid first line number.
     Patch suggested by Ivan Levkivskyi.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25805

   (2) https://bugs.python.org/issue27472

   (3) https://bugs.python.org/issue27369

   (4) https://bugs.python.org/issue27594


File: python.info,  Node: Windows<43>,  Next: 构建<47>,  Prev: 测试<44>,  Up: Python 3 6 0 alpha 4

1.19.63.5 Windows
.................

   - bpo-27647(1): Update bundled Tcl/Tk to 8.6.6.

   - bpo-27610(2): Adds PEP 514(3) metadata to Windows installer

   - bpo-27469(4): Adds a shell extension to the launcher so that drag
     and drop works correctly.

   - bpo-27309(5): Enables proper Windows styles in python[w].exe
     manifest.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27647

   (2) https://bugs.python.org/issue27610

   (3) https://www.python.org/dev/peps/pep-0514

   (4) https://bugs.python.org/issue27469

   (5) https://bugs.python.org/issue27309


File: python.info,  Node: 构建<47>,  Prev: Windows<43>,  Up: Python 3 6 0 alpha 4

1.19.63.6 构建
..............

   - bpo-27713(1): Suppress spurious build warnings when updating
     importlib’s bootstrap files.  Patch by Xiang Zhang

   - bpo-25825(2): Correct the references to Modules/python.exp, which
     is required on AIX. The references were accidentally changed in
     3.5.0a1.

   - bpo-27453(3): CPP invocation in configure must use CPPFLAGS. Patch
     by Chi Hsuan Yen.

   - bpo-27641(4): The configure script now inserts comments into the
     makefile to prevent the pgen and _freeze_importlib executables from
     being cross-compiled.

   - bpo-26662(5): Set PYTHON_FOR_GEN in configure as the Python program
     to be used for file generation during the build.

   - bpo-10910(6): Avoid C++ compilation errors on FreeBSD and OS X.
     Also update FreedBSD version checks for the original ctype UTF-8
     workaround.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27713

   (2) https://bugs.python.org/issue25825

   (3) https://bugs.python.org/issue27453

   (4) https://bugs.python.org/issue27641

   (5) https://bugs.python.org/issue26662

   (6) https://bugs.python.org/issue10910


File: python.info,  Node: Python 3 6 0 alpha 3,  Next: Python 3 6 0 alpha 2,  Prev: Python 3 6 0 alpha 4,  Up: Changelog（更動日誌）

1.19.64 Python 3.6.0 alpha 3
----------------------------

`发布日期: 2016-07-11'

* Menu:

* 核心与内置函数: 核心与内置函数<53>.
* 库: 库<56>.
* 安全性: 安全性<26>.
* 库: 库<57>.
* 安全性: 安全性<27>.
* 库: 库<58>.
* IDLE: IDLE<41>.
* C API: C API<36>.
* 构建: 构建<48>.
* 工具/示例: 工具/示例<26>.
* 文档: 文档<44>.
* 测试: 测试<45>.


File: python.info,  Node: 核心与内置函数<53>,  Next: 库<56>,  Up: Python 3 6 0 alpha 3

1.19.64.1 核心与内置函数
........................

   - bpo-27473(1): Fixed possible integer overflow in bytes and
     bytearray concatenations.  Patch by Xiang Zhang.

   - bpo-23034(2): 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.

   - bpo-27443(3): __length_hint__() of bytearray iterators no longer
     return a negative integer for a resized bytearray.

   - bpo-27007(4): The fromhex() class methods of bytes and bytearray
     subclasses now return an instance of corresponding subclass.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27473

   (2) https://bugs.python.org/issue23034

   (3) https://bugs.python.org/issue27443

   (4) https://bugs.python.org/issue27007


File: python.info,  Node: 库<56>,  Next: 安全性<26>,  Prev: 核心与内置函数<53>,  Up: Python 3 6 0 alpha 3

1.19.64.2 库
............

   - bpo-26844(1): Fix error message for imp.find_module() to refer to
     ’path’ instead of ’name’.  Patch by Lev Maximov.

   - bpo-23804(2): Fix SSL zero-length recv() calls to not block and not
     raise an error about unclean EOF.

   - bpo-27466(3): Change time format returned by
     http.cookie.time2netscape, confirming the netscape cookie format
     and making it consistent with documentation.

   - bpo-21708(4): 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.

   - bpo-26721(5): Change the socketserver.StreamRequestHandler.wfile
     attribute to implement BufferedIOBase.  In particular, the write()
     method no longer does partial writes.

   - bpo-22115(6): 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.

   - bpo-26243(7): Only the level argument to zlib.compress() is keyword
     argument now.  The first argument is positional-only.

   - bpo-27038(8): Expose the DirEntry type as os.DirEntry.  Code patch
     by Jelle Zijlstra.

   - bpo-27186(9): Update os.fspath()/PyOS_FSPath() to check the return
     value of __fspath__() to be either str or bytes.

   - bpo-18726(10): 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.

   - bpo-27319(11): 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.

   - bpo-27079(12): Fixed curses.ascii functions isblank(), iscntrl()
     and ispunct().

   - bpo-27294(13): Numerical state in the repr for Tkinter event
     objects is now represented as a combination of known flags.

   - bpo-27177(14): Match objects in the re module now support
     index-like objects as group indices.  Based on patches by Jeroen
     Demeyer and Xiang Zhang.

   - bpo-26754(15): Some functions (compile() etc) accepted a filename
     argument encoded as an iterable of integers.  Now only strings and
     byte-like objects are accepted.

   - bpo-26536(16): socket.ioctl now supports SIO_LOOPBACK_FAST_PATH.
     Patch by Daniel Stokes.

   - bpo-27048(17): Prevents distutils failing on Windows when
     environment variables contain non-ASCII characters

   - bpo-27330(18): Fixed possible leaks in the ctypes module.

   - bpo-27238(19): Got rid of bare excepts in the turtle module.
     Original patch by Jelle Zijlstra.

   - bpo-27122(20): 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 PEP 479(21) bug described in issue25782.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26844

   (2) https://bugs.python.org/issue23804

   (3) https://bugs.python.org/issue27466

   (4) https://bugs.python.org/issue21708

   (5) https://bugs.python.org/issue26721

   (6) https://bugs.python.org/issue22115

   (7) https://bugs.python.org/issue26243

   (8) https://bugs.python.org/issue27038

   (9) https://bugs.python.org/issue27186

   (10) https://bugs.python.org/issue18726

   (11) https://bugs.python.org/issue27319

   (12) https://bugs.python.org/issue27079

   (13) https://bugs.python.org/issue27294

   (14) https://bugs.python.org/issue27177

   (15) https://bugs.python.org/issue26754

   (16) https://bugs.python.org/issue26536

   (17) https://bugs.python.org/issue27048

   (18) https://bugs.python.org/issue27330

   (19) https://bugs.python.org/issue27238

   (20) https://bugs.python.org/issue27122

   (21) https://www.python.org/dev/peps/pep-0479


File: python.info,  Node: 安全性<26>,  Next: 库<57>,  Prev: 库<56>,  Up: Python 3 6 0 alpha 3

1.19.64.3 安全性
................

   - bpo-27278(1): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27278


File: python.info,  Node: 库<57>,  Next: 安全性<27>,  Prev: 安全性<26>,  Up: Python 3 6 0 alpha 3

1.19.64.4 库
............

   - bpo-16864(1): sqlite3.Cursor.lastrowid now supports REPLACE
     statement.  Initial patch by Alex LordThorsen.

   - bpo-26386(2): Fixed ttk.TreeView selection operations with item
     id’s containing spaces.

   - bpo-8637(3): Honor a pager set by the env var MANPAGER (in
     preference to one set by the env var PAGER).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16864

   (2) https://bugs.python.org/issue26386

   (3) https://bugs.python.org/issue8637


File: python.info,  Node: 安全性<27>,  Next: 库<58>,  Prev: 库<57>,  Up: Python 3 6 0 alpha 3

1.19.64.5 安全性
................

   - bpo-22636(1): Avoid shell injection problems with
     ctypes.util.find_library().

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22636


File: python.info,  Node: 库<58>,  Next: IDLE<41>,  Prev: 安全性<27>,  Up: Python 3 6 0 alpha 3

1.19.64.6 库
............

   - bpo-16182(1): Fix various functions in the "readline" module to use
     the locale encoding, and fix get_begidx() and get_endidx() to
     return code point indexes.

   - bpo-27392(2): Add loop.connect_accepted_socket().  Patch by Jim
     Fulton.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16182

   (2) https://bugs.python.org/issue27392


File: python.info,  Node: IDLE<41>,  Next: C API<36>,  Prev: 库<58>,  Up: Python 3 6 0 alpha 3

1.19.64.7 IDLE
..............

   - bpo-27477(1): IDLE search dialogs now use ttk widgets.

   - bpo-27173(2): 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.

   - bpo-27452(3): make command line "idle-test> python test_help.py"
     work.  __file__ is relative when python is started in the file’s
     directory.

   - bpo-27452(4): add line counter and crc to IDLE configHandler test
     dump.

   - bpo-27380(5): 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.

   - bpo-27372(6): Test_idle no longer changes the locale.

   - bpo-27365(7): Allow non-ascii chars in IDLE NEWS.txt, for
     contributor names.

   - bpo-27245(8): 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.

   - bpo-24137(9): 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.

   - bpo-27310(10): Fix IDLE.app failure to launch on OS X due to
     vestigial import.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27477

   (2) https://bugs.python.org/issue27173

   (3) https://bugs.python.org/issue27452

   (4) https://bugs.python.org/issue27452

   (5) https://bugs.python.org/issue27380

   (6) https://bugs.python.org/issue27372

   (7) https://bugs.python.org/issue27365

   (8) https://bugs.python.org/issue27245

   (9) https://bugs.python.org/issue24137

   (10) https://bugs.python.org/issue27310


File: python.info,  Node: C API<36>,  Next: 构建<48>,  Prev: IDLE<41>,  Up: Python 3 6 0 alpha 3

1.19.64.8 C API
...............

   - bpo-26754(1): PyUnicode_FSDecoder() accepted a filename argument
     encoded as an iterable of integers.  Now only strings and byte-like
     objects are accepted.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26754


File: python.info,  Node: 构建<48>,  Next: 工具/示例<26>,  Prev: C API<36>,  Up: Python 3 6 0 alpha 3

1.19.64.9 构建
..............

   - bpo-28066(1): Fix the logic that searches build directories for
     generated include files when building outside the source tree.

   - bpo-27442(2): Expose the Android API level that python was built
     against, in sysconfig.get_config_vars() as ’ANDROID_API_LEVEL’.

   - bpo-27434(3): 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.

   - bpo-26930(4): 更新Windows 构建以使用OpenSSL OpenSSL 1.0.2h.

   - bpo-23968(5): 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.

   - 在 GNU/Hurd 系统中不使用大文件支持。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28066

   (2) https://bugs.python.org/issue27442

   (3) https://bugs.python.org/issue27434

   (4) https://bugs.python.org/issue26930

   (5) https://bugs.python.org/issue23968


File: python.info,  Node: 工具/示例<26>,  Next: 文档<44>,  Prev: 构建<48>,  Up: Python 3 6 0 alpha 3

1.19.64.10 工具/示例
....................

   - bpo-27332(1): Fixed the type of the first argument of module-level
     functions generated by Argument Clinic.  Patch by Petr Viktorin.

   - bpo-27418(2): Fixed Tools/importbench/importbench.py.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27332

   (2) https://bugs.python.org/issue27418


File: python.info,  Node: 文档<44>,  Next: 测试<45>,  Prev: 工具/示例<26>,  Up: Python 3 6 0 alpha 3

1.19.64.11 文档
...............

   - bpo-19489(1): Moved the search box from the sidebar to the header
     and footer of each page.  Patch by Ammar Askar.

   - bpo-27285(2): Update documentation to reflect the deprecation of
     ‘pyvenv’ and normalize on the term "virtual environment".  Patch by
     Steve Piercy.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue19489

   (2) https://bugs.python.org/issue27285


File: python.info,  Node: 测试<45>,  Prev: 文档<44>,  Up: Python 3 6 0 alpha 3

1.19.64.12 测试
...............

   - bpo-27027(1): Added test.support.is_android that is True when this
     is an Android build.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27027


File: python.info,  Node: Python 3 6 0 alpha 2,  Next: Python 3 6 0 alpha 1,  Prev: Python 3 6 0 alpha 3,  Up: Changelog（更動日誌）

1.19.65 Python 3.6.0 alpha 2
----------------------------

`发布日期: 2016-06-13'

* Menu:

* 核心与内置函数: 核心与内置函数<54>.
* 库: 库<59>.
* 安全性: 安全性<28>.
* 库: 库<60>.
* 安全性: 安全性<29>.
* 库: 库<61>.
* IDLE: IDLE<42>.
* 文档: 文档<45>.
* 测试: 测试<46>.
* Windows: Windows<44>.
* 构建: 构建<49>.
* Windows: Windows<45>.
* C API: C API<37>.
* 工具/示例: 工具/示例<27>.


File: python.info,  Node: 核心与内置函数<54>,  Next: 库<59>,  Up: Python 3 6 0 alpha 2

1.19.65.1 核心与内置函数
........................

   - bpo-27095(1): Simplified MAKE_FUNCTION and removed MAKE_CLOSURE
     opcodes.  Patch by Demur Rumed.

   - bpo-27190(2): Raise NotSupportedError if sqlite3 is older than
     3.3.1.  Patch by Dave Sawyer.

   - bpo-27286(3): Fixed compiling BUILD_MAP_UNPACK_WITH_CALL opcode.
     Calling function with generalized unpacking (PEP 448) and
     conflicting keyword names could cause undefined behavior.

   - bpo-27140(4): Added BUILD_CONST_KEY_MAP opcode.

   - bpo-27186(5): Add support for os.PathLike objects to open() (part
     of PEP 519(6)).

   - bpo-27066(7): Fixed SystemError if a custom opener (for open())
     returns a negative number without setting an exception.

   - bpo-26983(8): 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.

   - bpo-27097(9): Python interpreter is now about 7% faster due to
     optimized instruction decoding.  Based on patch by Demur Rumed.

   - bpo-26647(10): Python interpreter now uses 16-bit wordcode instead
     of bytecode.  Patch by Demur Rumed.

   - bpo-23275(11): Allow assigning to an empty target list in round
     brackets: () = iterable.

   - bpo-27243(12): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27095

   (2) https://bugs.python.org/issue27190

   (3) https://bugs.python.org/issue27286

   (4) https://bugs.python.org/issue27140

   (5) https://bugs.python.org/issue27186

   (6) https://www.python.org/dev/peps/pep-0519

   (7) https://bugs.python.org/issue27066

   (8) https://bugs.python.org/issue26983

   (9) https://bugs.python.org/issue27097

   (10) https://bugs.python.org/issue26647

   (11) https://bugs.python.org/issue23275

   (12) https://bugs.python.org/issue27243


File: python.info,  Node: 库<59>,  Next: 安全性<28>,  Prev: 核心与内置函数<54>,  Up: Python 3 6 0 alpha 2

1.19.65.2 库
............

   - 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.

   - bpo-27025(1): Generated names for Tkinter widgets are now more
     meaningful and recognizable.

   - bpo-25455(2): Fixed crashes in repr of recursive
     ElementTree.Element and functools.partial objects.

   - bpo-27294(3): Improved repr for Tkinter event objects.

   - bpo-20508(4): Improve exception message of
     IPv{4,6}Network.__getitem__.  Patch by Gareth Rees.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27025

   (2) https://bugs.python.org/issue25455

   (3) https://bugs.python.org/issue27294

   (4) https://bugs.python.org/issue20508


File: python.info,  Node: 安全性<28>,  Next: 库<60>,  Prev: 库<59>,  Up: Python 3 6 0 alpha 2

1.19.65.3 安全性
................

   - bpo-26556(1): Update expat to 2.1.1, fixes CVE-2015-1283.

   - Fix TLS stripping vulnerability in smtplib, CVE-2016-0772.
     Reported by Team Oststrom.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26556


File: python.info,  Node: 库<60>,  Next: 安全性<29>,  Prev: 安全性<28>,  Up: Python 3 6 0 alpha 2

1.19.65.4 库
............

   - bpo-21386(1): Implement missing IPv4Address.is_global property.  It
     was documented since 07a5610bae9d.  Initial patch by Roger Luethi.

   - bpo-27029(2): Removed deprecated support of universal newlines mode
     from ZipFile.open().

   - bpo-27030(3): Unknown escapes consisting of ‘'\'’ and an ASCII
     letter in regular expressions now are errors.  The re.LOCALE flag
     now can be used only with bytes patterns.

   - bpo-27186(4): Add os.PathLike support to DirEntry (part of PEP
     519(5)).  Initial patch by Jelle Zijlstra.

   - bpo-20900(6): distutils register command now decodes HTTP responses
     correctly.  Initial patch by ingrid.

   - bpo-27186(7): Add os.PathLike support to pathlib, removing its
     provisional status (part of PEP 519).  Initial patch by Dusty
     Phillips.

   - bpo-27186(8): Add support for os.PathLike objects to os.fsencode()
     and os.fsdecode() (part of PEP 519(9)).

   - bpo-27186(10): Introduce os.PathLike and os.fspath() (part of PEP
     519(11)).

   - 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 PEP 492(12)
     (Awaitable, AsyncIterable, AsyncIterator) have been added (in fact
     they made it into 3.5.1 but were never mentioned).

   - bpo-25738(13): 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.

   - bpo-21313(14): Fix the "platform" module to tolerate when
     sys.version contains truncated build information.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21386

   (2) https://bugs.python.org/issue27029

   (3) https://bugs.python.org/issue27030

   (4) https://bugs.python.org/issue27186

   (5) https://www.python.org/dev/peps/pep-0519

   (6) https://bugs.python.org/issue20900

   (7) https://bugs.python.org/issue27186

   (8) https://bugs.python.org/issue27186

   (9) https://www.python.org/dev/peps/pep-0519

   (10) https://bugs.python.org/issue27186

   (11) https://www.python.org/dev/peps/pep-0519

   (12) https://www.python.org/dev/peps/pep-0492

   (13) https://bugs.python.org/issue25738

   (14) https://bugs.python.org/issue21313


File: python.info,  Node: 安全性<29>,  Next: 库<61>,  Prev: 库<60>,  Up: Python 3 6 0 alpha 2

1.19.65.5 安全性
................

   - bpo-26839(1): On Linux, *note os.urandom(): 5cb. now calls
     ‘getrandom()’ with ‘GRND_NONBLOCK’ to fall back on reading
     ‘/dev/urandom’ if the urandom entropy pool is not initialized yet.
     Patch written by Colm Buckley.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26839


File: python.info,  Node: 库<61>,  Next: IDLE<42>,  Prev: 安全性<29>,  Up: Python 3 6 0 alpha 2

1.19.65.6 库
............

   - bpo-23883(1): 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.

   - bpo-27164(2): In the zlib module, allow decompressing raw Deflate
     streams with a predefined zdict.  Based on patch by Xiang Zhang.

   - bpo-24291(3): 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.

   - bpo-21272(4): Use _sysconfigdata.py to initialize
     distutils.sysconfig.

   - bpo-19611(5): *note inspect: a0. now reports the implicit ‘.0’
     parameters generated by the compiler for comprehension and
     generator expression scopes as if they were positional-only
     parameters called ‘implicit0’.  Patch by Jelle Zijlstra.

   - bpo-26809(6): Add ‘__all__’ to *note string: f6.  Patch by Emanuel
     Barry.

   - bpo-26373(7): subprocess.Popen.communicate now correctly ignores
     BrokenPipeError when the child process dies before .communicate()
     is called in more/all circumstances.

   - 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.

   - bpo-27167(8): Clarify the subprocess.CalledProcessError error
     message text when the child process died due to a signal.

   - bpo-25931(9): Don’t define socketserver.Forking* names on platforms
     such as Windows that do not support os.fork().

   - bpo-21776(10): distutils.upload now correctly handles HTTPError.
     Initial patch by Claudiu Popa.

   - bpo-26526(11): Replace custom parse tree validation in the parser
     module with a simple DFA validator.

   - bpo-27114(12): Fix SSLContext._load_windows_store_certs fails with
     PermissionError

   - bpo-18383(13): Avoid creating duplicate filters when using
     filterwarnings and simplefilter.  Based on patch by Alex Shkop.

   - bpo-23026(14): winreg.QueryValueEx() now return an integer for
     REG_QWORD type.

   - bpo-26741(15): subprocess.Popen destructor now emits a
     ResourceWarning warning if the child process is still running.

   - bpo-27056(16): Optimize pickle.load() and pickle.loads(), up to 10%
     faster to deserialize a lot of small objects.

   - bpo-21271(17): New keyword only parameters in reset_mock call.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23883

   (2) https://bugs.python.org/issue27164

   (3) https://bugs.python.org/issue24291

   (4) https://bugs.python.org/issue21272

   (5) https://bugs.python.org/issue19611

   (6) https://bugs.python.org/issue26809

   (7) https://bugs.python.org/issue26373

   (8) https://bugs.python.org/issue27167

   (9) https://bugs.python.org/issue25931

   (10) https://bugs.python.org/issue21776

   (11) https://bugs.python.org/issue26526

   (12) https://bugs.python.org/issue27114

   (13) https://bugs.python.org/issue18383

   (14) https://bugs.python.org/issue23026

   (15) https://bugs.python.org/issue26741

   (16) https://bugs.python.org/issue27056

   (17) https://bugs.python.org/issue21271


File: python.info,  Node: IDLE<42>,  Next: 文档<45>,  Prev: 库<61>,  Up: Python 3 6 0 alpha 2

1.19.65.7 IDLE
..............

   - bpo-5124(1): 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.

   - bpo-24750(2): Switch all scrollbars in IDLE to ttk versions.  Where
     needed, minimal tests are added to cover changes.

   - bpo-24759(3): 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.

   - bpo-27239(4): idlelib.macosx.isXyzTk functions initialize as
     needed.

   - bpo-27262(5): move Aqua unbinding code, which enable context menus,
     to macosx.

   - bpo-24759(6): Make clear in idlelib.idle_test.__init__ that the
     directory is a private implementation of test.test_idle and tool
     for maintainers.

   - bpo-27196(7): 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

   - bpo-20567(8): Revise idle_test/README.txt with advice about
     avoiding tk warning messages from tests.  Apply advice to several
     IDLE tests.

   - bpo-24225(9): Update idlelib/README.txt with new file names and
     event handlers.

   - bpo-27156(10): Remove obsolete code not used by IDLE.

   - bpo-27117(11): Make colorizer htest and turtledemo work with dark
     themes.  Move code for configuring text widget colors to a new
     function.

   - bpo-24225(12): Rename many ‘idlelib/*.py’ and ‘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.

   - bpo-26673(13): When tk reports font size as 0, change to size 10.
     Such fonts on Linux prevented the configuration dialog from
     opening.

   - bpo-21939(14): Add test for IDLE’s percolator.  Original patch by
     Saimadhav Heblikar.

   - bpo-21676(15): Add test for IDLE’s replace dialog.  Original patch
     by Saimadhav Heblikar.

   - bpo-18410(16): Add test for IDLE’s search dialog.  Original patch
     by Westley Martínez.

   - bpo-21703(17): Add test for undo delegator.  Patch mostly by
     Saimadhav Heblikar .

   - bpo-27044(18): Add ConfigDialog.remove_var_callbacks to stop memory
     leaks.

   - bpo-23977(19): Add more asserts to test_delegator.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5124

   (2) https://bugs.python.org/issue24750

   (3) https://bugs.python.org/issue24759

   (4) https://bugs.python.org/issue27239

   (5) https://bugs.python.org/issue27262

   (6) https://bugs.python.org/issue24759

   (7) https://bugs.python.org/issue27196

   (8) https://bugs.python.org/issue20567

   (9) https://bugs.python.org/issue24225

   (10) https://bugs.python.org/issue27156

   (11) https://bugs.python.org/issue27117

   (12) https://bugs.python.org/issue24225

   (13) https://bugs.python.org/issue26673

   (14) https://bugs.python.org/issue21939

   (15) https://bugs.python.org/issue21676

   (16) https://bugs.python.org/issue18410

   (17) https://bugs.python.org/issue21703

   (18) https://bugs.python.org/issue27044

   (19) https://bugs.python.org/issue23977


File: python.info,  Node: 文档<45>,  Next: 测试<46>,  Prev: IDLE<42>,  Up: Python 3 6 0 alpha 2

1.19.65.8 文档
..............

   - bpo-16484(1): Change the default PYTHONDOCS URL to "https:", and
     fix the resulting links to use lowercase.  Patch by Sean Rodman,
     test by Kaushik Nadikuditi.

   - bpo-24136(2): Document the new PEP 448(3) unpacking syntax of 3.5.

   - bpo-22558(4): Add remaining doc links to source code for
     Python-coded modules.  Patch by Yoni Lavi.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16484

   (2) https://bugs.python.org/issue24136

   (3) https://www.python.org/dev/peps/pep-0448

   (4) https://bugs.python.org/issue22558


File: python.info,  Node: 测试<46>,  Next: Windows<44>,  Prev: 文档<45>,  Up: Python 3 6 0 alpha 2

1.19.65.9 测试
..............

   - bpo-25285(1): 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.

   - bpo-25285(2): Tools/buildbot/test.bat script now uses -j1 by
     default to run each test file in fresh child process.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25285

   (2) https://bugs.python.org/issue25285


File: python.info,  Node: Windows<44>,  Next: 构建<49>,  Prev: 测试<46>,  Up: Python 3 6 0 alpha 2

1.19.65.10 Windows
..................

   - bpo-27064(1): The py.exe launcher now defaults to Python 3.  The
     Windows launcher ‘py.exe’ no longer prefers an installed Python 2
     version over Python 3 by default when used interactively.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27064


File: python.info,  Node: 构建<49>,  Next: Windows<45>,  Prev: Windows<44>,  Up: Python 3 6 0 alpha 2

1.19.65.11 构建
...............

   - bpo-27229(1): Fix the cross-compiling pgen rule for in-tree builds.
     Patch by Xavier de Gaye.

   - bpo-26930(2): 更新OS X 10.5+（仅32位）安装程序以构建并链接OpenSSL
     1.0.2h。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27229

   (2) https://bugs.python.org/issue26930


File: python.info,  Node: Windows<45>,  Next: C API<37>,  Prev: 构建<49>,  Up: Python 3 6 0 alpha 2

1.19.65.12 Windows
..................

   - bpo-17500(1): Remove unused and outdated icons.  (See also:
     ‘https://github.com/python/pythondotorg/issues/945’)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17500


File: python.info,  Node: C API<37>,  Next: 工具/示例<27>,  Prev: Windows<45>,  Up: Python 3 6 0 alpha 2

1.19.65.13 C API
................

   - bpo-27186(1): Add the PyOS_FSPath() function (part of PEP 519(2)).

   - bpo-26282(3): PyArg_ParseTupleAndKeywords() now supports
     positional-only parameters.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27186

   (2) https://www.python.org/dev/peps/pep-0519

   (3) https://bugs.python.org/issue26282


File: python.info,  Node: 工具/示例<27>,  Prev: C API<37>,  Up: Python 3 6 0 alpha 2

1.19.65.14 工具/示例
....................

   - bpo-26282(1): Argument Clinic now supports positional-only and
     keyword parameters in the same function.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26282


File: python.info,  Node: Python 3 6 0 alpha 1,  Next: Python 3 5 5 正式版,  Prev: Python 3 6 0 alpha 2,  Up: Changelog（更動日誌）

1.19.66 Python 3.6.0 alpha 1
----------------------------

`发布日期: 2016-05-16'

* Menu:

* 核心与内置函数: 核心与内置函数<55>.
* 库: 库<62>.
* 安全性: 安全性<30>.
* 库: 库<63>.
* 安全性: 安全性<31>.
* 库: 库<64>.
* 安全性: 安全性<32>.
* 库: 库<65>.
* IDLE: IDLE<43>.
* 文档: 文档<46>.
* 测试: 测试<47>.
* 构建: 构建<50>.
* Windows: Windows<46>.
* 工具/示例: 工具/示例<28>.
* C API: C API<38>.


File: python.info,  Node: 核心与内置函数<55>,  Next: 库<62>,  Up: Python 3 6 0 alpha 1

1.19.66.1 核心与内置函数
........................

   - bpo-20041(1): Fixed TypeError when frame.f_trace is set to None.
     Patch by Xavier de Gaye.

   - bpo-26168(2): Fixed possible refleaks in failing Py_BuildValue()
     with the "N" format unit.

   - bpo-26991(3): Fix possible refleak when creating a function with
     annotations.

   - bpo-27039(4): Fixed bytearray.remove() for values greater than 127.
     Based on patch by Joe Jevnik.

   - bpo-23640(5): int.from_bytes() no longer bypasses constructors for
     subclasses.

   - bpo-27005(6): Optimized the float.fromhex() class method for exact
     float.  It is now 2 times faster.

   - bpo-18531(7): Single var-keyword argument of dict subtype was
     passed unscathed to the C-defined function.  Now it is converted to
     exact dict.

   - bpo-26811(8): gc.get_objects() no longer contains a broken tuple
     with NULL pointer.

   - bpo-20120(9): 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.

   - bpo-26249(10): Memory functions of the *note PyMem_Malloc(): 5fe.
     domain (*note PYMEM_DOMAIN_MEM: 602.) now use the *note pymalloc
     allocator: 6b8. rather than system ‘malloc()’.  Applications
     calling *note PyMem_Malloc(): 5fe. without holding the GIL can now
     crash: use ‘PYTHONMALLOC=debug’ environment variable to validate
     the usage of memory allocators in your application.

   - bpo-26802(11): Optimize function calls only using unpacking like
     ‘func(*tuple)’ (no other positional argument, no keyword): avoid
     copying the tuple.  Patch written by Joe Jevnik.

   - bpo-26659(12): Make the builtin slice type support cycle
     collection.

   - bpo-26718(13): super.__init__ no longer leaks memory if called
     multiple times.  NOTE: A direct call of super.__init__ is not
     endorsed!

   - bpo-27138(14): Fix the doc comment for FileFinder.find_spec().

   - bpo-27147(15): Mention PEP 420(16) in the importlib docs.

   - bpo-25339(17): PYTHONIOENCODING now has priority over locale in
     setting the error handler for stdin and stdout.

   - bpo-26494(18): 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.

   - bpo-26574(19): Optimize ‘bytes.replace(b'', b'.')’ and
     ‘bytearray.replace(b'', b'.')’.  Patch written by Josh Snider.

   - bpo-26581(20): If coding cookie is specified multiple times on a
     line in Python source code file, only the first one is taken to
     account.

   - bpo-19711(21): Add tests for reloading namespace packages.

   - bpo-21099(22): Switch applicable importlib tests to use PEP 451(23)
     API.

   - bpo-26563(24): Debug hooks on Python memory allocators now raise a
     fatal error if functions of the *note PyMem_Malloc(): 5fe. family
     are called without holding the GIL.

   - bpo-26564(25): On error, the debug hooks on Python memory
     allocators now use the *note tracemalloc: 11d. module to get the
     traceback where a memory block was allocated.

   - bpo-26558(26): The debug hooks on Python memory allocator *note
     PyObject_Malloc(): 601. now detect when functions are called
     without holding the GIL.

   - bpo-26516(27): Add *note PYTHONMALLOC: 5fc. environment variable to
     set the Python memory allocators and/or install debug hooks.

   - bpo-26516(28): The *note PyMem_SetupDebugHooks(): 603. function can
     now also be used on Python compiled in release mode.

   - bpo-26516(29): The *note PYTHONMALLOCSTATS: 1297. environment
     variable can now also be used on Python compiled in release mode.
     It now has no effect if set to an empty string.

   - bpo-26516(30): In debug mode, debug hooks are now also installed on
     Python memory allocators when Python is configured without
     pymalloc.

   - bpo-26464(31): 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.

   - bpo-22836(32): 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.

   - bpo-26302(33): Correct behavior to reject comma as a legal
     character for cookie names.

   - bpo-26136(34): Upgrade the warning when a generator raises
     StopIteration from PendingDeprecationWarning to DeprecationWarning.
     Patch by Anish Shah.

   - bpo-26204(35): 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, ‘1.0’ is now ignored in ‘def f(): 1.0’.

   - bpo-4806(36): Avoid masking the original TypeError exception when
     using star (‘*’) unpacking in function calls.  Based on patch by
     Hagen Fürstenau and Daniel Urban.

   - bpo-26146(37): Add a new kind of AST node: ‘ast.Constant’.  It can
     be used by external AST optimizers, but the compiler does not emit
     directly such node.

   - bpo-23601(38): Sped-up allocation of dict key objects by using
     Python’s small object allocator.  (Contributed by Julian Taylor.)

   - bpo-18018(39): Import raises ImportError instead of SystemError if
     a relative import is attempted without a known parent package.

   - bpo-25843(40): When compiling code, don’t merge constants if they
     are equal but have a different types.  For example, ‘f1, f2 =
     lambda: 1, lambda: 1.0’ is now correctly compiled to two different
     functions: ‘f1()’ returns ‘1’ (‘int’) and ‘f2()’ returns ‘1.0’
     (‘float’), even if ‘1’ and ‘1.0’ are equal.

   - bpo-26107(41): The format of the ‘co_lnotab’ attribute of code
     objects changes to support negative line number delta.

   - bpo-26154(42): 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.

   - bpo-25791(43): If __package__ != __spec__.parent or if neither
     __package__ or __spec__ are defined then ImportWarning is raised.

   - bpo-22995(44): [UPDATE] Comment out the one of the pickleability
     tests in _PyObject_GetState() due to regressions observed in
     Cython-based projects.

   - bpo-25961(45): Disallowed null characters in the type name.

   - bpo-25973(46): Fix segfault when an invalid nonlocal statement
     binds a name starting with two underscores.

   - bpo-22995(47): 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.

   - bpo-20440(48): Massive replacing unsafe attribute setting code with
     special macro Py_SETREF.

   - bpo-25766(49): Special method __bytes__() now works in str
     subclasses.

   - bpo-25421(50): __sizeof__ methods of builtin types now use dynamic
     basic size.  This allows sys.getsize() to work correctly with their
     subclasses with __slots__ defined.

   - bpo-25709(51): Fixed problem with in-place string concatenation and
     utf-8 cache.

   - bpo-5319(52): New Py_FinalizeEx() API allowing Python to set an
     exit status of 120 on failure to flush buffered streams.

   - bpo-25485(53): telnetlib.Telnet is now a context manager.

   - bpo-24097(54): Fixed crash in object.__reduce__() if slot name is
     freed inside __getattr__.

   - bpo-24731(55): 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.

   - bpo-25630(56): Fix a possible segfault during argument parsing in
     functions that accept filesystem paths.

   - bpo-23564(57): 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.

   - bpo-25388(58): Fixed tokenizer crash when processing undecodable
     source code with a null byte.

   - bpo-25462(59): The hash of the key now is calculated only once in
     most operations in C implementation of OrderedDict.

   - bpo-22995(60): Default implementation of __reduce__ and
     __reduce_ex__ now rejects builtin types with not defined __new__.

   - bpo-24802(61): 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.

   - bpo-25555(62): Fix parser and AST: fill lineno and col_offset of
     "arg" node when compiling AST from Python objects.

   - bpo-24726(63): Fixed a crash and leaking NULL in repr() of
     OrderedDict that was mutated by direct calls of dict methods.

   - bpo-25449(64): Iterating OrderedDict with keys with unstable hash
     now raises KeyError in C implementations as well as in Python
     implementation.

   - bpo-25395(65): Fixed crash when highly nested OrderedDict
     structures were garbage collected.

   - bpo-25401(66): Optimize bytes.fromhex() and bytearray.fromhex():
     they are now between 2x and 3.5x faster.

   - bpo-25399(67): Optimize bytearray % args using the new private
     _PyBytesWriter API. Formatting is now between 2.5 and 5 times
     faster.

   - bpo-25274(68): 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.

   - bpo-24402(69): Fix input() to prompt to the redirected stdout when
     sys.stdout.fileno() fails.

   - bpo-25349(70): Optimize bytes % args using the new private
     _PyBytesWriter API. Formatting is now up to 2 times faster.

   - bpo-24806(71): Prevent builtin types that are not allowed to be
     subclassed from being subclassed through multiple inheritance.

   - bpo-25301(72): The UTF-8 decoder is now up to 15 times as fast for
     error handlers: ‘ignore’, ‘replace’ and ‘surrogateescape’.

   - bpo-24848(73): Fixed a number of bugs in UTF-7 decoding of
     misformed data.

   - bpo-25267(74): The UTF-8 encoder is now up to 75 times as fast for
     error handlers: ‘ignore’, ‘replace’, ‘surrogateescape’,
     ‘surrogatepass’.  Patch co-written with Serhiy Storchaka.

   - bpo-25280(75): Import trace messages emitted in verbose (-v) mode
     are no longer formatted twice.

   - bpo-25227(76): Optimize ASCII and latin1 encoders with the
     ‘surrogateescape’ error handler: the encoders are now up to 3 times
     as fast.  Initial patch written by Serhiy Storchaka.

   - bpo-25003(77): 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.

   - bpo-9232(78): 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.

   - bpo-24965(79): Implement PEP 498(80) "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.

   - bpo-26478(81): Fix semantic bugs when using binary operators with
     dictionary views and tuples.

   - bpo-26171(82): Fix possible integer overflow and heap corruption in
     zipimporter.get_data().

   - bpo-25660(83): Fix TAB key behaviour in REPL with readline.

   - bpo-26288(84): Optimize PyLong_AsDouble.

   - bpo-26289(85): 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(86))

   - bpo-25887(87): Raise a RuntimeError when a coroutine object is
     awaited more than once.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20041

   (2) https://bugs.python.org/issue26168

   (3) https://bugs.python.org/issue26991

   (4) https://bugs.python.org/issue27039

   (5) https://bugs.python.org/issue23640

   (6) https://bugs.python.org/issue27005

   (7) https://bugs.python.org/issue18531

   (8) https://bugs.python.org/issue26811

   (9) https://bugs.python.org/issue20120

   (10) https://bugs.python.org/issue26249

   (11) https://bugs.python.org/issue26802

   (12) https://bugs.python.org/issue26659

   (13) https://bugs.python.org/issue26718

   (14) https://bugs.python.org/issue27138

   (15) https://bugs.python.org/issue27147

   (16) https://www.python.org/dev/peps/pep-0420

   (17) https://bugs.python.org/issue25339

   (18) https://bugs.python.org/issue26494

   (19) https://bugs.python.org/issue26574

   (20) https://bugs.python.org/issue26581

   (21) https://bugs.python.org/issue19711

   (22) https://bugs.python.org/issue21099

   (23) https://www.python.org/dev/peps/pep-0451

   (24) https://bugs.python.org/issue26563

   (25) https://bugs.python.org/issue26564

   (26) https://bugs.python.org/issue26558

   (27) https://bugs.python.org/issue26516

   (28) https://bugs.python.org/issue26516

   (29) https://bugs.python.org/issue26516

   (30) https://bugs.python.org/issue26516

   (31) https://bugs.python.org/issue26464

   (32) https://bugs.python.org/issue22836

   (33) https://bugs.python.org/issue26302

   (34) https://bugs.python.org/issue26136

   (35) https://bugs.python.org/issue26204

   (36) https://bugs.python.org/issue4806

   (37) https://bugs.python.org/issue26146

   (38) https://bugs.python.org/issue23601

   (39) https://bugs.python.org/issue18018

   (40) https://bugs.python.org/issue25843

   (41) https://bugs.python.org/issue26107

   (42) https://bugs.python.org/issue26154

   (43) https://bugs.python.org/issue25791

   (44) https://bugs.python.org/issue22995

   (45) https://bugs.python.org/issue25961

   (46) https://bugs.python.org/issue25973

   (47) https://bugs.python.org/issue22995

   (48) https://bugs.python.org/issue20440

   (49) https://bugs.python.org/issue25766

   (50) https://bugs.python.org/issue25421

   (51) https://bugs.python.org/issue25709

   (52) https://bugs.python.org/issue5319

   (53) https://bugs.python.org/issue25485

   (54) https://bugs.python.org/issue24097

   (55) https://bugs.python.org/issue24731

   (56) https://bugs.python.org/issue25630

   (57) https://bugs.python.org/issue23564

   (58) https://bugs.python.org/issue25388

   (59) https://bugs.python.org/issue25462

   (60) https://bugs.python.org/issue22995

   (61) https://bugs.python.org/issue24802

   (62) https://bugs.python.org/issue25555

   (63) https://bugs.python.org/issue24726

   (64) https://bugs.python.org/issue25449

   (65) https://bugs.python.org/issue25395

   (66) https://bugs.python.org/issue25401

   (67) https://bugs.python.org/issue25399

   (68) https://bugs.python.org/issue25274

   (69) https://bugs.python.org/issue24402

   (70) https://bugs.python.org/issue25349

   (71) https://bugs.python.org/issue24806

   (72) https://bugs.python.org/issue25301

   (73) https://bugs.python.org/issue24848

   (74) https://bugs.python.org/issue25267

   (75) https://bugs.python.org/issue25280

   (76) https://bugs.python.org/issue25227

   (77) https://bugs.python.org/issue25003

   (78) https://bugs.python.org/issue9232

   (79) https://bugs.python.org/issue24965

   (80) https://www.python.org/dev/peps/pep-0498

   (81) https://bugs.python.org/issue26478

   (82) https://bugs.python.org/issue26171

   (83) https://bugs.python.org/issue25660

   (84) https://bugs.python.org/issue26288

   (85) https://bugs.python.org/issue26289

   (86) https://bugs.python.org/issue26315

   (87) https://bugs.python.org/issue25887


File: python.info,  Node: 库<62>,  Next: 安全性<30>,  Prev: 核心与内置函数<55>,  Up: Python 3 6 0 alpha 1

1.19.66.2 库
............

   - bpo-27057(1): 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.

   - bpo-27014(2): Fix infinite recursion using typing.py.  Thanks to
     Kalle Tuure!

   - bpo-27031(3): Removed dummy methods in Tkinter widget classes:
     tk_menuBar() and tk_bindForTraversal().

   - bpo-14132(4): Fix urllib.request redirect handling when the target
     only has a query string.  Original fix by Ján Janech.

   - bpo-17214(5): 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.

   - bpo-27033(6): The default value of the decode_data parameter for
     smtpd.SMTPChannel and smtpd.SMTPServer constructors is changed to
     False.

   - bpo-27034(7): Removed deprecated class asynchat.fifo.

   - bpo-26870(8): Added readline.set_auto_history(), which can stop
     entries being automatically added to the history list.  Based on
     patch by Tyler Crompton.

   - bpo-26039(9): zipfile.ZipFile.open() can now be used to write data
     into a ZIP file, as well as for extracting data.  Patch by Thomas
     Kluyver.

   - bpo-26892(10): Honor debuglevel flag in urllib.request.HTTPHandler.
     Patch contributed by Chi Hsuan Yen.

   - bpo-22274(11): In the subprocess module, allow stderr to be
     redirected to stdout even when stdout is not redirected.  Patch by
     Akira Li.

   - bpo-26807(12): mock_open ’files’ no longer error on readline at end
     of file.  Patch from Yolanda Robla.

   - bpo-25745(13): Fixed leaking a userptr in curses panel destructor.

   - bpo-26977(14): Removed unnecessary, and ignored, call to sum of
     squares helper in statistics.pvariance.

   - bpo-26002(15): Use bisect in statistics.median instead of a linear
     search.  Patch by Upendra Kuma.

   - bpo-25974(16): Make use of new Decimal.as_integer_ratio() method in
     statistics module.  Patch by Stefan Krah.

   - bpo-26996(17): Add secrets module as described in PEP 506(18).

   - bpo-26881(19): The modulefinder module now supports extended opcode
     arguments.

   - bpo-23815(20): Fixed crashes related to directly created instances
     of types in _tkinter and curses.panel modules.

   - bpo-17765(21): weakref.ref() no longer silently ignores keyword
     arguments.  Patch by Georg Brandl.

   - bpo-26873(22): xmlrpc now raises ResponseError on unsupported type
     tags instead of silently return incorrect result.

   - bpo-26915(23): 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.

   - bpo-26711(24): Fixed the comparison of plistlib.Data with other
     types.

   - bpo-24114(25): Fix an uninitialized variable in ‘ctypes.util’.  The
     bug only occurs on SunOS when the ctypes implementation searches
     for the ‘crle’ program.  Patch by Xiang Zhang.  Tested on SunOS by
     Kees Bos.

   - bpo-26864(26): 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.

   - bpo-24902(27): Print server URL on http.server startup.  Initial
     patch by Felix Kaiser.

   - bpo-25788(28): fileinput.hook_encoded() now supports an "errors"
     argument for passing to open.  Original patch by Joseph Hackman.

   - bpo-26634(29): recursive_repr() now sets __qualname__ of wrapper.
     Patch by Xiang Zhang.

   - bpo-26804(30): urllib.request will prefer lower_case proxy
     environment variables over UPPER_CASE or Mixed_Case ones.  Patch
     contributed by Hans-Peter Jansen.

   - bpo-26837(31): assertSequenceEqual() now correctly outputs
     non-stringified differing items (like bytes in the -b mode).  This
     affects assertListEqual() and assertTupleEqual().

   - bpo-26041(32): Remove "will be removed in Python 3.7" from
     deprecation messages of platform.dist() and
     platform.linux_distribution().  Patch by Kumaripaba Miyurusara
     Athukorala.

   - bpo-26822(33): itemgetter, attrgetter and methodcaller objects no
     longer silently ignore keyword arguments.

   - bpo-26733(34): Disassembling a class now disassembles class and
     static methods.  Patch by Xiang Zhang.

   - bpo-26801(35): Fix error handling in *note
     shutil.get_terminal_size(): b25, catch *note AttributeError: 4a1.
     instead of *note NameError: e40.  Patch written by Emanuel Barry.

   - bpo-24838(36): tarfile’s ustar and gnu formats now correctly
     calculate name and link field limits for multibyte character
     encodings like utf-8.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27057

   (2) https://bugs.python.org/issue27014

   (3) https://bugs.python.org/issue27031

   (4) https://bugs.python.org/issue14132

   (5) https://bugs.python.org/issue17214

   (6) https://bugs.python.org/issue27033

   (7) https://bugs.python.org/issue27034

   (8) https://bugs.python.org/issue26870

   (9) https://bugs.python.org/issue26039

   (10) https://bugs.python.org/issue26892

   (11) https://bugs.python.org/issue22274

   (12) https://bugs.python.org/issue26807

   (13) https://bugs.python.org/issue25745

   (14) https://bugs.python.org/issue26977

   (15) https://bugs.python.org/issue26002

   (16) https://bugs.python.org/issue25974

   (17) https://bugs.python.org/issue26996

   (18) https://www.python.org/dev/peps/pep-0506

   (19) https://bugs.python.org/issue26881

   (20) https://bugs.python.org/issue23815

   (21) https://bugs.python.org/issue17765

   (22) https://bugs.python.org/issue26873

   (23) https://bugs.python.org/issue26915

   (24) https://bugs.python.org/issue26711

   (25) https://bugs.python.org/issue24114

   (26) https://bugs.python.org/issue26864

   (27) https://bugs.python.org/issue24902

   (28) https://bugs.python.org/issue25788

   (29) https://bugs.python.org/issue26634

   (30) https://bugs.python.org/issue26804

   (31) https://bugs.python.org/issue26837

   (32) https://bugs.python.org/issue26041

   (33) https://bugs.python.org/issue26822

   (34) https://bugs.python.org/issue26733

   (35) https://bugs.python.org/issue26801

   (36) https://bugs.python.org/issue24838


File: python.info,  Node: 安全性<30>,  Next: 库<63>,  Prev: 库<62>,  Up: Python 3 6 0 alpha 1

1.19.66.3 安全性
................

   - bpo-26657(1): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26657


File: python.info,  Node: 库<63>,  Next: 安全性<31>,  Prev: 安全性<30>,  Up: Python 3 6 0 alpha 1

1.19.66.4 库
............

   - bpo-26717(1): Stop encoding Latin-1-ized WSGI paths with UTF-8.
     Patch by Anthony Sottile.

   - bpo-26782(2): Add STARTUPINFO to subprocess.__all__ on Windows.

   - bpo-26404(3): Add context manager to socketserver.  Patch by Aviv
     Palivoda.

   - bpo-26735(4): Fix *note os.urandom(): 5cb. on Solaris 11.3 and
     newer when reading more than 1,024 bytes: call ‘getrandom()’
     multiple times with a limit of 1024 bytes per call.

   - bpo-26585(5): Eliminate http.server._quote_html() and use
     html.escape(quote=False).  Patch by Xiang Zhang.

   - bpo-26685(6): Raise OSError if closing a socket fails.

   - bpo-16329(7): Add .webm to mimetypes.types_map.  Patch by Giampaolo
     Rodola’.

   - bpo-13952(8): Add .csv to mimetypes.types_map.  Patch by Geoff
     Wilson.

   - bpo-26587(9): the site module now allows .pth files to specify
     files to be added to sys.path (e.g.  zip files).

   - bpo-25609(10): Introduce contextlib.AbstractContextManager and
     typing.ContextManager.

   - bpo-26709(11): Fixed Y2038 problem in loading binary PLists.

   - bpo-23735(12): Handle terminal resizing with Readline 6.3+ by
     installing our own SIGWINCH handler.  Patch by Eric Price.

   - bpo-25951(13): Change SSLSocket.sendall() to return None, as
     explicitly documented for plain socket objects.  Patch by Aviv
     Palivoda.

   - bpo-26586(14): 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.

   - bpo-26676(15): Added missing XMLPullParser to ElementTree.__all__.

   - bpo-22854(16): Change BufferedReader.writable() and
     BufferedWriter.readable() to always return False.

   - bpo-26492(17): 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.

   - bpo-26641(18): doctest.DocFileTest and doctest.testfile() now
     support packages (module splitted into multiple directories) for
     the package parameter.

   - bpo-25195(19): 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.

   - bpo-26644(20): Raise ValueError rather than SystemError when a
     negative length is passed to SSLSocket.recv() or read().

   - bpo-23804(21): Fix SSL recv(0) and read(0) methods to return zero
     bytes instead of up to 1024.

   - bpo-26616(22): Fixed a bug in datetime.astimezone() method.

   - bpo-26637(23): The *note importlib: 9a. module now emits an *note
     ImportError: 16c. rather than a *note TypeError: 1fe. if *note
     __import__(): 16b. is tried during the Python shutdown process but
     *note sys.path: 261. is already cleared (set to ‘None’).

   - bpo-21925(24): *note warnings.formatwarning(): 112d. now catches
     exceptions when calling *note linecache.getline(): 7fa. and *note
     tracemalloc.get_object_traceback(): 129b. to be able to log *note
     ResourceWarning: 5ca. emitted late during the Python shutdown
     process.

   - bpo-23848(25): 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).

   - bpo-26530(26): Add C functions ‘_PyTraceMalloc_Track()’ and
     ‘_PyTraceMalloc_Untrack()’ to track memory blocks using the *note
     tracemalloc: 11d. module.  Add ‘_PyTraceMalloc_GetTraceback()’ to
     get the traceback of an object.

   - bpo-26588(27): The _tracemalloc now supports tracing memory
     allocations of multiple address spaces (domains).

   - bpo-24266(28): Ctrl+C during Readline history search now cancels
     the search mode when compiled with Readline 7.

   - bpo-26590(29): Implement a safe finalizer for the _socket.socket
     type.  It now releases the GIL to close the socket.

   - bpo-18787(30): spwd.getspnam() now raises a PermissionError if the
     user doesn’t have privileges.

   - bpo-26560(31): Avoid potential ValueError in
     BaseHandler.start_response.  Initial patch by Peter Inglesby.

   - bpo-26567(32): Add a new function *note PyErr_ResourceWarning():
     6c3. function to pass the destroyed object.  Add a `source'
     attribute to ‘warnings.WarningMessage’.  Add
     warnings._showwarnmsg() which uses tracemalloc to get the traceback
     where source object was allocated.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26717

   (2) https://bugs.python.org/issue26782

   (3) https://bugs.python.org/issue26404

   (4) https://bugs.python.org/issue26735

   (5) https://bugs.python.org/issue26585

   (6) https://bugs.python.org/issue26685

   (7) https://bugs.python.org/issue16329

   (8) https://bugs.python.org/issue13952

   (9) https://bugs.python.org/issue26587

   (10) https://bugs.python.org/issue25609

   (11) https://bugs.python.org/issue26709

   (12) https://bugs.python.org/issue23735

   (13) https://bugs.python.org/issue25951

   (14) https://bugs.python.org/issue26586

   (15) https://bugs.python.org/issue26676

   (16) https://bugs.python.org/issue22854

   (17) https://bugs.python.org/issue26492

   (18) https://bugs.python.org/issue26641

   (19) https://bugs.python.org/issue25195

   (20) https://bugs.python.org/issue26644

   (21) https://bugs.python.org/issue23804

   (22) https://bugs.python.org/issue26616

   (23) https://bugs.python.org/issue26637

   (24) https://bugs.python.org/issue21925

   (25) https://bugs.python.org/issue23848

   (26) https://bugs.python.org/issue26530

   (27) https://bugs.python.org/issue26588

   (28) https://bugs.python.org/issue24266

   (29) https://bugs.python.org/issue26590

   (30) https://bugs.python.org/issue18787

   (31) https://bugs.python.org/issue26560

   (32) https://bugs.python.org/issue26567


File: python.info,  Node: 安全性<31>,  Next: 库<64>,  Prev: 库<63>,  Up: Python 3 6 0 alpha 1

1.19.66.5 安全性
................

   - bpo-26313(1): ssl.py _load_windows_store_certs fails if windows
     cert store is empty.  Patch by Baji.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26313


File: python.info,  Node: 库<64>,  Next: 安全性<32>,  Prev: 安全性<31>,  Up: Python 3 6 0 alpha 1

1.19.66.6 库
............

   - bpo-26569(1): Fix *note pyclbr.readmodule(): 129e. and *note
     pyclbr.readmodule_ex(): 129f. to support importing packages.

   - bpo-26499(2): Account for remaining Content-Length in
     HTTPResponse.readline() and read1().  Based on patch by Silent
     Ghost.  Also document that HTTPResponse now supports these methods.

   - bpo-25320(3): Handle sockets in directories unittest discovery is
     scanning.  Patch from Victor van den Elzen.

   - bpo-16181(4): cookiejar.http2time() now returns None if year is
     higher than datetime.MAXYEAR.

   - bpo-26513(5): Fixes platform module detection of Windows Server

   - bpo-23718(6): Fixed parsing time in week 0 before Jan 1.  Original
     patch by Tamás Bence Gedai.

   - bpo-26323(7): Add Mock.assert_called() and
     Mock.assert_called_once() methods to unittest.mock.  Patch written
     by Amit Saha.

   - bpo-20589(8): Invoking Path.owner() and Path.group() on Windows now
     raise NotImplementedError instead of ImportError.

   - bpo-26177(9): Fixed the keys() method for Canvas and Scrollbar
     widgets.

   - bpo-15068(10): Got rid of excessive buffering in fileinput.  The
     bufsize parameter is now deprecated and ignored.

   - bpo-19475(11): Added an optional argument timespec to the datetime
     isoformat() method to choose the precision of the time component.

   - bpo-2202(12): Fix UnboundLocalError in
     AbstractDigestAuthHandler.get_algorithm_impls.  Initial patch by
     Mathieu Dupuy.

   - bpo-26167(13): Minimized overhead in copy.copy() and
     copy.deepcopy().  Optimized copying and deepcopying bytearrays,
     NotImplemented, slices, short lists, tuples, dicts, sets.

   - bpo-25718(14): Fixed pickling and copying the accumulate() iterator
     with total is None.

   - bpo-26475(15): Fixed debugging output for regular expressions with
     the (?x) flag.

   - bpo-26482(16): Allowed pickling recursive dequeues.

   - bpo-26335(17): Make mmap.write() return the number of bytes written
     like other write methods.  Patch by Jakub Stasiak.

   - bpo-26457(18): 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.

   - bpo-26385(19): Remove the file if the internal open() call in
     NamedTemporaryFile() fails.  Patch by Silent Ghost.

   - bpo-26402(20): 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.

   - bpo-25913(21): Leading ‘<~’ is optional now in base64.a85decode()
     with adobe=True.  Patch by Swati Jaiswal.

   - bpo-26186(22): Remove an invalid type check in
     importlib.util.LazyLoader.

   - bpo-26367(23): importlib.__import__() raises ImportError like
     builtins.__import__() when ‘level’ is specified but without an
     accompanying package specified.

   - bpo-26309(24): In the "socketserver" module, shut down the request
     (closing the connected socket) when verify_request() returns false.
     Patch by Aviv Palivoda.

   - bpo-23430(25): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26569

   (2) https://bugs.python.org/issue26499

   (3) https://bugs.python.org/issue25320

   (4) https://bugs.python.org/issue16181

   (5) https://bugs.python.org/issue26513

   (6) https://bugs.python.org/issue23718

   (7) https://bugs.python.org/issue26323

   (8) https://bugs.python.org/issue20589

   (9) https://bugs.python.org/issue26177

   (10) https://bugs.python.org/issue15068

   (11) https://bugs.python.org/issue19475

   (12) https://bugs.python.org/issue2202

   (13) https://bugs.python.org/issue26167

   (14) https://bugs.python.org/issue25718

   (15) https://bugs.python.org/issue26475

   (16) https://bugs.python.org/issue26482

   (17) https://bugs.python.org/issue26335

   (18) https://bugs.python.org/issue26457

   (19) https://bugs.python.org/issue26385

   (20) https://bugs.python.org/issue26402

   (21) https://bugs.python.org/issue25913

   (22) https://bugs.python.org/issue26186

   (23) https://bugs.python.org/issue26367

   (24) https://bugs.python.org/issue26309

   (25) https://bugs.python.org/issue23430


File: python.info,  Node: 安全性<32>,  Next: 库<65>,  Prev: 库<64>,  Up: Python 3 6 0 alpha 1

1.19.66.7 安全性
................

   - bpo-25939(1): On Windows open the cert store readonly in
     ssl.enum_certificates.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25939


File: python.info,  Node: 库<65>,  Next: IDLE<43>,  Prev: 安全性<32>,  Up: Python 3 6 0 alpha 1

1.19.66.8 库
............

   - bpo-25995(1): os.walk() no longer uses FDs proportional to the tree
     depth.

   - bpo-25994(2): Added the close() method and the support of the
     context manager protocol for the os.scandir() iterator.

   - bpo-23992(3): multiprocessing: make MapResult not fail-fast upon
     exception.

   - bpo-26243(4): Support keyword arguments to zlib.compress().  Patch
     by Aviv Palivoda.

   - bpo-26117(5): The os.scandir() iterator now closes file descriptor
     not only when the iteration is finished, but when it was failed
     with error.

   - bpo-25949(6): __dict__ for an OrderedDict instance is now created
     only when needed.

   - bpo-25911(7): Restored support of bytes paths in os.walk() on
     Windows.

   - bpo-26045(8): Add UTF-8 suggestion to error message when posting a
     non-Latin-1 string with http.client.

   - bpo-26039(9): Added zipfile.ZipInfo.from_file() and
     zipinfo.ZipInfo.is_dir().  Patch by Thomas Kluyver.

   - bpo-12923(10): Reset FancyURLopener’s redirect counter even if
     there is an exception.  Based on patches by Brian Brazil and Daniel
     Rocco.

   - bpo-25945(11): 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.

   - bpo-26202(12): copy.deepcopy() now correctly copies range() objects
     with non-atomic attributes.

   - bpo-23076(13): Path.glob() now raises a ValueError if it’s called
     with an invalid pattern.  Patch by Thomas Nyberg.

   - bpo-19883(14): Fixed possible integer overflows in zipimport.

   - bpo-26227(15): 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.

   - bpo-26099(16): 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.

   - bpo-26147(17): xmlrpc now works with strings not encodable with
     used non-UTF-8 encoding.

   - bpo-25935(18): Garbage collector now breaks reference loops with
     OrderedDict.

   - bpo-16620(19): Fixed AttributeError in msilib.Directory.glob().

   - bpo-26013(20): Added compatibility with broken protocol 2 pickles
     created in old Python 3 versions (3.4.3 and lower).

   - bpo-26129(21): Deprecated accepting non-integers in grp.getgrgid().

   - bpo-25850(22): Use cross-compilation by default for 64-bit Windows.

   - bpo-25822(23): Add docstrings to the fields of urllib.parse
     results.  Patch contributed by Swati Jaiswal.

   - bpo-22642(24): Convert trace module option parsing mechanism to
     argparse.  Patch contributed by SilentGhost.

   - bpo-24705(25): Fix sysconfig._parse_makefile not expanding ${} vars
     appearing before $() vars.

   - bpo-26069(26): Remove the deprecated apis in the trace module.

   - bpo-22138(27): Fix mock.patch behavior when patching descriptors.
     Restore original values after patching.  Patch contributed by Sean
     McCully.

   - bpo-25672(28): In the ssl module, enable the
     SSL_MODE_RELEASE_BUFFERS mode option if it is safe to do so.

   - bpo-26012(29): Don’t traverse into symlinks for ‘**’ pattern in
     pathlib.Path.[r]glob().

   - bpo-24120(30): Ignore PermissionError when traversing a tree with
     pathlib.Path.[r]glob().  Patch by Ulrich Petri.

   - bpo-21815(31): 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.

   - bpo-25447(32): fileinput now uses sys.stdin as-is if it does not
     have a buffer attribute (restores backward compatibility).

   - bpo-25971(33): Optimized creating Fractions from floats by 2 times
     and from Decimals by 3 times.

   - bpo-25802(34): Document as deprecated the remaining implementations
     of importlib.abc.Loader.load_module().

   - bpo-25928(35): Add Decimal.as_integer_ratio().

   - bpo-25447(36): Copying the lru_cache() wrapper object now always
     works, independently from the type of the wrapped object (by
     returning the original object unchanged).

   - bpo-25768(37): Have the functions in compileall return booleans
     instead of ints and add proper documentation and tests for the
     return values.

   - bpo-24103(38): Fixed possible use after free in
     ElementTree.XMLPullParser.

   - bpo-25860(39): os.fwalk() no longer skips remaining directories
     when error occurs.  Original patch by Samson Lee.

   - bpo-25914(40): Fixed and simplified OrderedDict.__sizeof__.

   - bpo-25869(41): Optimized deepcopying ElementTree; it is now 20
     times faster.

   - bpo-25873(42): Optimized iterating ElementTree.  Iterating elements
     Element.iter() is now 40% faster, iterating text Element.itertext()
     is now up to 2.5 times faster.

   - bpo-25902(43): Fixed various refcount issues in ElementTree
     iteration.

   - bpo-22227(44): The TarFile iterator is reimplemented using
     generator.  This implementation is simpler that using class.

   - bpo-25638(45): Optimized ElementTree.iterparse(); it is now 2x
     faster.  Optimized ElementTree parsing; it is now 10% faster.

   - bpo-25761(46): Improved detecting errors in broken pickle data.

   - bpo-25717(47): 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.

   - bpo-24903(48): 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.

   - bpo-25764(49): In the subprocess module, preserve any exception
     caused by fork() failure when preexec_fn is used.

   - bpo-25771(50): Tweak the exception message for
     importlib.util.resolve_name() when ’package’ isn’t specified but
     necessary.

   - bpo-6478(51): _strptime’s regexp cache now is reset after changing
     timezone with time.tzset().

   - bpo-14285(52): 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.

   - bpo-19771(53): 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 ‘*.pyc’ file).

   - bpo-25177(54): 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.

   - bpo-25718(55): Fixed copying object with state with boolean value
     is false.

   - bpo-10131(56): Fixed deep copying of minidom documents.  Based on
     patch by Marian Ganisin.

   - bpo-7990(57): dir() on ElementTree.Element now lists properties:
     "tag", "text", "tail" and "attrib".  Original patch by Santoso
     Wijaya.

   - bpo-25725(58): Fixed a reference leak in pickle.loads() when
     unpickling invalid data including tuple instructions.

   - bpo-25663(59): In the Readline completer, avoid listing duplicate
     global names, and search the global namespace before searching
     builtins.

   - bpo-25688(60): Fixed file leak in ElementTree.iterparse() raising
     an error.

   - bpo-23914(61): Fixed SystemError raised by unpickler on broken
     pickle data.

   - bpo-25691(62): Fixed crash on deleting ElementTree.Element
     attributes.

   - bpo-25624(63): ZipFile now always writes a ZIP_STORED header for
     directory entries.  Patch by Dingyuan Wang.

   - bpo-25626(64): 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.

   - bpo-25583(65): Avoid incorrect errors raised by
     os.makedirs(exist_ok=True) when the OS gives priority to errors
     such as EACCES over EEXIST.

   - bpo-25593(66): Change semantics of EventLoop.stop() in asyncio.

   - bpo-6973(67): 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.

   - bpo-23883(68): 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.

   - bpo-25590(69): 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.

   - bpo-25498(70): 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.

   - bpo-25584(71): Added "escape" to the __all__ list in the glob
     module.

   - bpo-25584(72): Fixed recursive glob() with patterns starting with
     ‘**’.

   - bpo-25446(73): Fix regression in smtplib’s AUTH LOGIN support.

   - bpo-18010(74): Fix the pydoc web server’s module search function to
     handle exceptions from importing packages.

   - bpo-25554(75): Got rid of circular references in regular expression
     parsing.

   - bpo-18973(76): Command-line interface of the calendar module now
     uses argparse instead of optparse.

   - bpo-25510(77): fileinput.FileInput.readline() now returns b’’
     instead of ’’ at the end if the FileInput was opened with binary
     mode.  Patch by Ryosuke Ito.

   - bpo-25503(78): Fixed inspect.getdoc() for inherited docstrings of
     properties.  Original patch by John Mark Vandenberg.

   - bpo-25515(79): Always use os.urandom as a source of randomness in
     uuid.uuid4.

   - bpo-21827(80): Fixed textwrap.dedent() for the case when largest
     common whitespace is a substring of smallest leading whitespace.
     Based on patch by Robert Li.

   - bpo-25447(81): The lru_cache() wrapper objects now can be copied
     and pickled (by returning the original object unchanged).

   - bpo-25390(82): typing: Don’t crash on Union[str, Pattern].

   - bpo-25441(83): asyncio: Raise error from drain() when socket is
     closed.

   - bpo-25410(84): Cleaned up and fixed minor bugs in C implementation
     of OrderedDict.

   - bpo-25411(85): Improved Unicode support in SMTPHandler through
     better use of the email package.  Thanks to user simon04 for the
     patch.

   - Move the imp module from a PendingDeprecationWarning to
     DeprecationWarning.

   - bpo-25407(86): Remove mentions of the formatter module being
     removed in Python 3.6.

   - bpo-25406(87): 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.

   - bpo-25382(88): pickletools.dis() now outputs implicit memo index
     for the MEMOIZE opcode.

   - bpo-25357(89): Add an optional newline parameter to
     binascii.b2a_base64().  base64.b64encode() uses it to avoid a
     memory copy.

   - bpo-24164(90): Objects that need calling ‘__new__’ with keyword
     arguments, can now be pickled using pickle protocols older than
     protocol version 4.

   - bpo-25364(91): zipfile now works in threads disabled builds.

   - bpo-25328(92): smtpd’s SMTPChannel now correctly raises a
     ValueError if both decode_data and enable_SMTPUTF8 are set to true.

   - bpo-16099(93): RobotFileParser now supports Crawl-delay and
     Request-rate extensions.  Patch by Nikolay Bogoychev.

   - bpo-25316(94): distutils raises OSError instead of
     DistutilsPlatformError when MSVC is not installed.

   - bpo-25380(95): Fixed protocol for the STACK_GLOBAL opcode in
     pickletools.opcodes.

   - bpo-23972(96): 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.

   - bpo-25304(97): 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.

   - bpo-25232(98): Fix CGIRequestHandler to split the query from the
     URL at the first question mark (?)  rather than the last.  Patch
     from Xiang Zhang.

   - bpo-24657(99): Prevent CGIRequestHandler from collapsing slashes in
     the query part of the URL as if it were a path.  Patch from Xiang
     Zhang.

   - bpo-25287(100): 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.

   - bpo-23600(101): Default implementation of tzinfo.fromutc() was
     returning wrong results in some cases.

   - bpo-25203(102): Failed readline.set_completer_delims() no longer
     left the module in inconsistent state.

   - bpo-25011(103): rlcompleter now omits private and special attribute
     names unless the prefix starts with underscores.

   - bpo-25209(104): rlcompleter now can add a space or a colon after
     completed keyword.

   - bpo-22241(105): timezone.utc name is now plain ’UTC’, not
     ’UTC-00:00’.

   - bpo-23517(106): 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).

   - bpo-23552(107): Timeit now warns when there is substantial (4x)
     variance between best and worst times.  Patch from Serhiy
     Storchaka.

   - bpo-24633(108): site-packages/README -> README.txt.

   - bpo-24879(109): 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.

   - bpo-24874(110): Improve speed of itertools.cycle() and make its
     pickle more compact.

   - Fix crash in itertools.cycle.__setstate__() when the first argument
     wasn’t a list.

   - bpo-20059(111): urllib.parse raises ValueError on all invalid
     ports.  Patch by Martin Panter.

   - bpo-24360(112): Improve __repr__ of argparse.Namespace() for
     invalid identifiers.  Patch by Matthias Bussonnier.

   - bpo-23426(113): run_setup was broken in distutils.  Patch from
     Alexander Belopolsky.

   - bpo-13938(114): 2to3 converts StringTypes to a tuple.  Patch from
     Mark Hammond.

   - bpo-2091(115): open() accepted a ’U’ mode string containing ’+’,
     but ’U’ can only be used with ’r’.  Patch from Jeff Balogh and John
     O’Connor.

   - bpo-8585(116): improved tests for zipimporter2.  Patch from Mark
     Lawrence.

   - bpo-18622(117): unittest.mock.mock_open().reset_mock would recurse
     infinitely.  Patch from Nicola Palumbo and Laurent De Buyst.

   - bpo-24426(118): 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.

   - bpo-23661(119): unittest.mock side_effects can now be exceptions
     again.  This was a regression vs Python 3.4.  Patch from Ignacio
     Rossi

   - bpo-13248(120): Remove deprecated inspect.getmoduleinfo function.

   - bpo-25578(121): Fix (another) memory leak in
     SSLSocket.getpeercer().

   - bpo-25530(122): Disable the vulnerable SSLv3 protocol by default
     when creating ssl.SSLContext.

   - bpo-25569(123): Fix memory leak in SSLSocket.getpeercert().

   - bpo-25471(124): Sockets returned from accept() shouldn’t appear to
     be nonblocking.

   - bpo-25319(125): When threading.Event is reinitialized, the
     underlying condition should use a regular lock rather than a
     recursive lock.

   - Skip getaddrinfo if host is already resolved.  Patch by A. Jesse
     Jiryu Davis.

   - bpo-26050(126): Add asyncio.StreamReader.readuntil() method.  Patch
     by Марк Коренберг.

   - bpo-25924(127): Avoid unnecessary serialization of getaddrinfo(3)
     calls on OS X versions 10.5 or higher.  Original patch by A. Jesse
     Jiryu Davis.

   - bpo-26406(128): Avoid unnecessary serialization of getaddrinfo(3)
     calls on current versions of OpenBSD and NetBSD. Patch by A. Jesse
     Jiryu Davis.

   - bpo-26848(129): Fix asyncio/subprocess.communicate() to handle
     empty input.  Patch by Jack O’Connor.

   - bpo-27040(130): Add loop.get_exception_handler method

   - bpo-27041(131): asyncio: Add loop.create_future method

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25995

   (2) https://bugs.python.org/issue25994

   (3) https://bugs.python.org/issue23992

   (4) https://bugs.python.org/issue26243

   (5) https://bugs.python.org/issue26117

   (6) https://bugs.python.org/issue25949

   (7) https://bugs.python.org/issue25911

   (8) https://bugs.python.org/issue26045

   (9) https://bugs.python.org/issue26039

   (10) https://bugs.python.org/issue12923

   (11) https://bugs.python.org/issue25945

   (12) https://bugs.python.org/issue26202

   (13) https://bugs.python.org/issue23076

   (14) https://bugs.python.org/issue19883

   (15) https://bugs.python.org/issue26227

   (16) https://bugs.python.org/issue26099

   (17) https://bugs.python.org/issue26147

   (18) https://bugs.python.org/issue25935

   (19) https://bugs.python.org/issue16620

   (20) https://bugs.python.org/issue26013

   (21) https://bugs.python.org/issue26129

   (22) https://bugs.python.org/issue25850

   (23) https://bugs.python.org/issue25822

   (24) https://bugs.python.org/issue22642

   (25) https://bugs.python.org/issue24705

   (26) https://bugs.python.org/issue26069

   (27) https://bugs.python.org/issue22138

   (28) https://bugs.python.org/issue25672

   (29) https://bugs.python.org/issue26012

   (30) https://bugs.python.org/issue24120

   (31) https://bugs.python.org/issue21815

   (32) https://bugs.python.org/issue25447

   (33) https://bugs.python.org/issue25971

   (34) https://bugs.python.org/issue25802

   (35) https://bugs.python.org/issue25928

   (36) https://bugs.python.org/issue25447

   (37) https://bugs.python.org/issue25768

   (38) https://bugs.python.org/issue24103

   (39) https://bugs.python.org/issue25860

   (40) https://bugs.python.org/issue25914

   (41) https://bugs.python.org/issue25869

   (42) https://bugs.python.org/issue25873

   (43) https://bugs.python.org/issue25902

   (44) https://bugs.python.org/issue22227

   (45) https://bugs.python.org/issue25638

   (46) https://bugs.python.org/issue25761

   (47) https://bugs.python.org/issue25717

   (48) https://bugs.python.org/issue24903

   (49) https://bugs.python.org/issue25764

   (50) https://bugs.python.org/issue25771

   (51) https://bugs.python.org/issue6478

   (52) https://bugs.python.org/issue14285

   (53) https://bugs.python.org/issue19771

   (54) https://bugs.python.org/issue25177

   (55) https://bugs.python.org/issue25718

   (56) https://bugs.python.org/issue10131

   (57) https://bugs.python.org/issue7990

   (58) https://bugs.python.org/issue25725

   (59) https://bugs.python.org/issue25663

   (60) https://bugs.python.org/issue25688

   (61) https://bugs.python.org/issue23914

   (62) https://bugs.python.org/issue25691

   (63) https://bugs.python.org/issue25624

   (64) https://bugs.python.org/issue25626

   (65) https://bugs.python.org/issue25583

   (66) https://bugs.python.org/issue25593

   (67) https://bugs.python.org/issue6973

   (68) https://bugs.python.org/issue23883

   (69) https://bugs.python.org/issue25590

   (70) https://bugs.python.org/issue25498

   (71) https://bugs.python.org/issue25584

   (72) https://bugs.python.org/issue25584

   (73) https://bugs.python.org/issue25446

   (74) https://bugs.python.org/issue18010

   (75) https://bugs.python.org/issue25554

   (76) https://bugs.python.org/issue18973

   (77) https://bugs.python.org/issue25510

   (78) https://bugs.python.org/issue25503

   (79) https://bugs.python.org/issue25515

   (80) https://bugs.python.org/issue21827

   (81) https://bugs.python.org/issue25447

   (82) https://bugs.python.org/issue25390

   (83) https://bugs.python.org/issue25441

   (84) https://bugs.python.org/issue25410

   (85) https://bugs.python.org/issue25411

   (86) https://bugs.python.org/issue25407

   (87) https://bugs.python.org/issue25406

   (88) https://bugs.python.org/issue25382

   (89) https://bugs.python.org/issue25357

   (90) https://bugs.python.org/issue24164

   (91) https://bugs.python.org/issue25364

   (92) https://bugs.python.org/issue25328

   (93) https://bugs.python.org/issue16099

   (94) https://bugs.python.org/issue25316

   (95) https://bugs.python.org/issue25380

   (96) https://bugs.python.org/issue23972

   (97) https://bugs.python.org/issue25304

   (98) https://bugs.python.org/issue25232

   (99) https://bugs.python.org/issue24657

   (100) https://bugs.python.org/issue25287

   (101) https://bugs.python.org/issue23600

   (102) https://bugs.python.org/issue25203

   (103) https://bugs.python.org/issue25011

   (104) https://bugs.python.org/issue25209

   (105) https://bugs.python.org/issue22241

   (106) https://bugs.python.org/issue23517

   (107) https://bugs.python.org/issue23552

   (108) https://bugs.python.org/issue24633

   (109) https://bugs.python.org/issue24879

   (110) https://bugs.python.org/issue24874

   (111) https://bugs.python.org/issue20059

   (112) https://bugs.python.org/issue24360

   (113) https://bugs.python.org/issue23426

   (114) https://bugs.python.org/issue13938

   (115) https://bugs.python.org/issue2091

   (116) https://bugs.python.org/issue8585

   (117) https://bugs.python.org/issue18622

   (118) https://bugs.python.org/issue24426

   (119) https://bugs.python.org/issue23661

   (120) https://bugs.python.org/issue13248

   (121) https://bugs.python.org/issue25578

   (122) https://bugs.python.org/issue25530

   (123) https://bugs.python.org/issue25569

   (124) https://bugs.python.org/issue25471

   (125) https://bugs.python.org/issue25319

   (126) https://bugs.python.org/issue26050

   (127) https://bugs.python.org/issue25924

   (128) https://bugs.python.org/issue26406

   (129) https://bugs.python.org/issue26848

   (130) https://bugs.python.org/issue27040

   (131) https://bugs.python.org/issue27041


File: python.info,  Node: IDLE<43>,  Next: 文档<46>,  Prev: 库<65>,  Up: Python 3 6 0 alpha 1

1.19.66.9 IDLE
..............

   - bpo-20640(1): Add tests for idlelib.configHelpSourceEdit.  Patch by
     Saimadhav Heblikar.

   - In the ’IDLE-console differences’ section of the IDLE doc, clarify
     how running with IDLE affects sys.modules and the standard streams.

   - bpo-25507(2): fix incorrect change in IOBinding that prevented
     printing.  Augment IOBinding htest to include all major IOBinding
     functions.

   - bpo-25905(3): 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’.

   - bpo-15348(4): 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.

   - bpo-24455(5): 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.

   - 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.

   - bpo-24750(6): Improve the appearance of the IDLE editor window
     status bar.  Patch by Mark Roseman.

   - bpo-25313(7): 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.

   - bpo-24782(8): 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.

   - bpo-22726(9): Re-activate the config dialog help button with some
     content about the other buttons and the new IDLE Dark theme.

   - bpo-24820(10): 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.

   - bpo-25224(11): 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’.

   - bpo-24820(12): Users can now set breakpoint colors in Settings ->
     Custom Highlighting.  Original patch by Mark Roseman.

   - bpo-24972(13): 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.

   - bpo-24570(14): Idle: make calltip and completion boxes appear on
     Macs affected by a tk regression.  Initial patch by Mark Roseman.

   - bpo-24988(15): Idle ScrolledList context menus (used in debugger)
     now work on Mac Aqua.  Patch by Mark Roseman.

   - bpo-24801(16): Make right-click for context menu work on Mac Aqua.
     Patch by Mark Roseman.

   - bpo-25173(17): Associate tkinter messageboxes with a specific
     widget.  For Mac OSX, make them a ’sheet’.  Patch by Mark Roseman.

   - bpo-25198(18): 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.

   - bpo-25225(19): Condense and rewrite Idle doc section on text
     colors.

   - bpo-21995(20): Explain some differences between IDLE and console
     Python.

   - bpo-22820(21): Explain need for `print' when running file from Idle
     editor.

   - bpo-25224(22): Doc: augment Idle feature list and no-subprocess
     section.

   - bpo-25219(23): Update doc for Idle command line options.  Some were
     missing and notes were not correct.

   - bpo-24861(24): Most of idlelib is private and subject to change.
     Use idleib.idle.* to start Idle.  See idlelib.__init__.__doc__.

   - bpo-25199(25): Idle: add synchronization comments for future
     maintainers.

   - bpo-16893(26): 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.

   - bpo-24199(27): Deprecate unused idlelib.idlever with possible
     removal in 3.6.

   - bpo-24790(28): Remove extraneous code (which also create 2 & 3
     conflicts).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20640

   (2) https://bugs.python.org/issue25507

   (3) https://bugs.python.org/issue25905

   (4) https://bugs.python.org/issue15348

   (5) https://bugs.python.org/issue24455

   (6) https://bugs.python.org/issue24750

   (7) https://bugs.python.org/issue25313

   (8) https://bugs.python.org/issue24782

   (9) https://bugs.python.org/issue22726

   (10) https://bugs.python.org/issue24820

   (11) https://bugs.python.org/issue25224

   (12) https://bugs.python.org/issue24820

   (13) https://bugs.python.org/issue24972

   (14) https://bugs.python.org/issue24570

   (15) https://bugs.python.org/issue24988

   (16) https://bugs.python.org/issue24801

   (17) https://bugs.python.org/issue25173

   (18) https://bugs.python.org/issue25198

   (19) https://bugs.python.org/issue25225

   (20) https://bugs.python.org/issue21995

   (21) https://bugs.python.org/issue22820

   (22) https://bugs.python.org/issue25224

   (23) https://bugs.python.org/issue25219

   (24) https://bugs.python.org/issue24861

   (25) https://bugs.python.org/issue25199

   (26) https://bugs.python.org/issue16893

   (27) https://bugs.python.org/issue24199

   (28) https://bugs.python.org/issue24790


File: python.info,  Node: 文档<46>,  Next: 测试<47>,  Prev: IDLE<43>,  Up: Python 3 6 0 alpha 1

1.19.66.10 文档
...............

   - bpo-26736(1): Used HTTPS for external links in the documentation if
     possible.

   - bpo-6953(2): Rework the Readline module documentation to group
     related functions together, and add more details such as what
     underlying Readline functions and variables are accessed.

   - bpo-23606(3): Adds note to ctypes documentation regarding
     cdll.msvcrt.

   - bpo-24952(4): Clarify the default size argument of stack_size() in
     the "threading" and "_thread" modules.  Patch from Mattip.

   - bpo-26014(5): 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

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26736

   (2) https://bugs.python.org/issue6953

   (3) https://bugs.python.org/issue23606

   (4) https://bugs.python.org/issue24952

   (5) https://bugs.python.org/issue26014


File: python.info,  Node: 测试<47>,  Next: 构建<50>,  Prev: 文档<46>,  Up: Python 3 6 0 alpha 1

1.19.66.11 测试
...............

   - bpo-21916(1): Added tests for the turtle module.  Patch by ingrid,
     Gregory Loyse and Jelle Zijlstra.

   - bpo-26295(2): When using "python3 -m test –testdir=TESTDIR",
     regrtest doesn’t add "test."  prefix to test module names.

   - bpo-26523(3): The multiprocessing thread pool
     (multiprocessing.dummy.Pool) was untested.

   - bpo-26015(4): Added new tests for pickling iterators of mutable
     sequences.

   - bpo-26325(5): Added test.support.check_no_resource_warning() to
     check that no ResourceWarning is emitted.

   - bpo-25940(6): Changed test_ssl to use its internal local server
     more.  This avoids relying on svn.python.org, which recently
     changed root certificate.

   - bpo-25616(7): Tests for OrderedDict are extracted from
     test_collections into separate file test_ordered_dict.

   - bpo-25449(8): Added tests for OrderedDict subclasses.

   - bpo-25188(9): 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.

   - bpo-22806(10): Add ‘python -m test --list-tests’ command to list
     tests.

   - bpo-18174(11): ‘python -m test --huntrleaks ...’ now also checks
     for leak of file descriptors.  Patch written by Richard Oudkerk.

   - bpo-25260(12): Fix ‘python -m test --coverage’ on Windows.  Remove
     the list of ignored directories.

   - ‘PCbuild\rt.bat’ now accepts an unlimited number of arguments to
     pass along to regrtest.py.  Previously there was a limit of 9.

   - bpo-26583(13): Skip test_timestamp_overflow in test_import if
     bytecode files cannot be written.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21916

   (2) https://bugs.python.org/issue26295

   (3) https://bugs.python.org/issue26523

   (4) https://bugs.python.org/issue26015

   (5) https://bugs.python.org/issue26325

   (6) https://bugs.python.org/issue25940

   (7) https://bugs.python.org/issue25616

   (8) https://bugs.python.org/issue25449

   (9) https://bugs.python.org/issue25188

   (10) https://bugs.python.org/issue22806

   (11) https://bugs.python.org/issue18174

   (12) https://bugs.python.org/issue25260

   (13) https://bugs.python.org/issue26583


File: python.info,  Node: 构建<50>,  Next: Windows<46>,  Prev: 测试<47>,  Up: Python 3 6 0 alpha 1

1.19.66.12 构建
...............

   - bpo-21277(1): Don’t try to link _ctypes with a ffi_convenience
     library.

   - bpo-26884(2): Fix linking extension modules for cross builds.
     Patch by Xavier de Gaye.

   - bpo-26932(3): Fixed support of RTLD_* constants defined as enum
     values, not via macros (in particular on Android).  Patch by Chi
     Hsuan Yen.

   - bpo-22359(4): 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.

   - bpo-21668(5): Link audioop, _datetime, _ctypes_test modules to
     libm, except on Mac OS X. Patch written by Chi Hsuan Yen.

   - bpo-25702(6): 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.

   - bpo-26624(7): Adds validation of ucrtbase[d].dll version with
     warning for old versions.

   - bpo-17603(8): Avoid error about nonexistent fileblocks.o file by
     using a lower-level check for st_blocks in struct stat.

   - bpo-26079(9): Fixing the build output folder for tix-8.4.3.6.
     Patch by Bjoern Thiel.

   - bpo-26465(10): 更新Windows 构建OpenSSL 1.0.2g.

   - bpo-25348(11): Added ‘--pgo’ and ‘--pgo-job’ arguments to
     ‘PCbuild\build.bat’ for building with Profile-Guided Optimization.
     The old ‘PCbuild\build_pgo.bat’ script is removed.

   - bpo-25827(12): Add support for building with ICC to ‘configure’,
     including a new ‘--with-icc’ flag.

   - bpo-25696(13): Fix installation of Python on UNIX with make -j9.

   - bpo-24986(14): It is now possible to build Python on Windows
     without errors when external libraries are not available.

   - bpo-24421(15): Compile Modules/_math.c once, before building
     extensions.  Previously it could fail to compile properly if the
     math and cmath builds were concurrent.

   - bpo-26465(16): 更新 OS X 10.5+（仅32位）安装程序以构建并链接
     OpenSSL 1.0.2g.

   - bpo-26268(17): 更新Windows 构建OpenSSL 1.0.2f.

   - bpo-25136(18): Support Apple Xcode 7’s new textual SDK stub
     libraries.

   - bpo-24324(19): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21277

   (2) https://bugs.python.org/issue26884

   (3) https://bugs.python.org/issue26932

   (4) https://bugs.python.org/issue22359

   (5) https://bugs.python.org/issue21668

   (6) https://bugs.python.org/issue25702

   (7) https://bugs.python.org/issue26624

   (8) https://bugs.python.org/issue17603

   (9) https://bugs.python.org/issue26079

   (10) https://bugs.python.org/issue26465

   (11) https://bugs.python.org/issue25348

   (12) https://bugs.python.org/issue25827

   (13) https://bugs.python.org/issue25696

   (14) https://bugs.python.org/issue24986

   (15) https://bugs.python.org/issue24421

   (16) https://bugs.python.org/issue26465

   (17) https://bugs.python.org/issue26268

   (18) https://bugs.python.org/issue25136

   (19) https://bugs.python.org/issue24324


File: python.info,  Node: Windows<46>,  Next: 工具/示例<28>,  Prev: 构建<50>,  Up: Python 3 6 0 alpha 1

1.19.66.13 Windows
..................

   - bpo-27053(1): Updates make_zip.py to correctly generate library ZIP
     file.

   - bpo-26268(2): 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).

   - bpo-26071(3): bdist_wininst created binaries fail to start and find
     32bit Python

   - bpo-26073(4): Update the list of magic numbers in launcher

   - bpo-26065(5): Excludes venv from library when generating embeddable
     distro.

   - bpo-25022(6): Removed very outdated PC/example_nt/ directory.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27053

   (2) https://bugs.python.org/issue26268

   (3) https://bugs.python.org/issue26071

   (4) https://bugs.python.org/issue26073

   (5) https://bugs.python.org/issue26065

   (6) https://bugs.python.org/issue25022


File: python.info,  Node: 工具/示例<28>,  Next: C API<38>,  Prev: Windows<46>,  Up: Python 3 6 0 alpha 1

1.19.66.14 工具/示例
....................

   - bpo-26799(1): 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.

   - bpo-26271(2): Fix the Freeze tool to properly use flags passed
     through configure.  Patch by Daniel Shaulov.

   - bpo-26489(3): Add dictionary unpacking support to
     Tools/parser/unparse.py.  Patch by Guo Ci Teo.

   - bpo-26316(4): Fix variable name typo in Argument Clinic.

   - bpo-25440(5): Fix output of python-config –extension-suffix.

   - bpo-25154(6): The pyvenv script has been deprecated in favour of
     ‘python3 -m venv’.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26799

   (2) https://bugs.python.org/issue26271

   (3) https://bugs.python.org/issue26489

   (4) https://bugs.python.org/issue26316

   (5) https://bugs.python.org/issue25440

   (6) https://bugs.python.org/issue25154


File: python.info,  Node: C API<38>,  Prev: 工具/示例<28>,  Up: Python 3 6 0 alpha 1

1.19.66.15 C API
................

   - bpo-26312(1): SystemError is now raised in all programming bugs
     with using PyArg_ParseTupleAndKeywords().  RuntimeError did raised
     before in some programming bugs.

   - bpo-26198(2): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26312

   (2) https://bugs.python.org/issue26198


File: python.info,  Node: Python 3 5 5 正式版,  Next: Python 3 5 5 rc1,  Prev: Python 3 6 0 alpha 1,  Up: Changelog（更動日誌）

1.19.67 Python 3.5.5 正式版
---------------------------

`发布日期e: 2018-02-04'

在 3.5.5 版本中没有新的更改。


File: python.info,  Node: Python 3 5 5 rc1,  Next: Python 3 5 4 正式版,  Prev: Python 3 5 5 正式版,  Up: Changelog（更動日誌）

1.19.68 Python 3.5.5 rc1
------------------------

`发布日期: 2018-01-23'

* Menu:

* 安全性: 安全性<33>.
* 核心与内置函数: 核心与内置函数<56>.
* 库: 库<66>.


File: python.info,  Node: 安全性<33>,  Next: 核心与内置函数<56>,  Up: Python 3 5 5 rc1

1.19.68.1 安全性
................

   - bpo-32551(1): The ‘sys.path[0]’ initialization change for
     bpo-29139(2) caused a regression by revealing an inconsistency in
     how sys.path is initialized when executing ‘__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 ‘sys.path’, and ensures no other ‘sys.path’ entries
     are inadvertently modified when inserting the import location named
     on the command line.  (Originally reported as bpo-29723(3) against
     Python 3.6rc1, but it was missed at the time that the then upcoming
     Python 3.5.4 release would also be affected)

   - bpo-30657(4): Fixed possible integer overflow in
     PyBytes_DecodeEscape, CVE-2017-1000158.  Original patch by Jay
     Bosamiya; rebased to Python 3 by Miro Hrončok.

   - bpo-30947(5): Upgrade libexpat embedded copy from version 2.2.1 to
     2.2.3 to get security fixes.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32551

   (2) https://bugs.python.org/issue29139

   (3) https://bugs.python.org/issue29723

   (4) https://bugs.python.org/issue30657

   (5) https://bugs.python.org/issue30947


File: python.info,  Node: 核心与内置函数<56>,  Next: 库<66>,  Prev: 安全性<33>,  Up: Python 3 5 5 rc1

1.19.68.2 核心与内置函数
........................

   - bpo-31095(1): Fix potential crash during GC caused by ‘tp_dealloc’
     which doesn’t call ‘PyObject_GC_UnTrack()’.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue31095


File: python.info,  Node: 库<66>,  Prev: 核心与内置函数<56>,  Up: Python 3 5 5 rc1

1.19.68.3 库
............

   - bpo-32072(1): 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.

   - bpo-31170(2): expat: Update libexpat from 2.2.3 to 2.2.4.  Fix
     copying of partial characters for UTF-8 input (libexpat bug 115):
     ‘https://github.com/libexpat/libexpat/issues/115’

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue32072

   (2) https://bugs.python.org/issue31170


File: python.info,  Node: Python 3 5 4 正式版,  Next: Python 3 5 4 rc1,  Prev: Python 3 5 5 rc1,  Up: Changelog（更動日誌）

1.19.69 Python 3.5.4 正式版
---------------------------

`发布日期: 2017-08-07'

* Menu:

* 库: 库<67>.


File: python.info,  Node: 库<67>,  Up: Python 3 5 4 正式版

1.19.69.1 库
............

   - bpo-30119(1): ftplib.FTP.putline() now throws ValueError on
     commands that contains CR or LF. Patch by Dong-hee Na.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30119


File: python.info,  Node: Python 3 5 4 rc1,  Next: Python 3 5 3 正式版,  Prev: Python 3 5 4 正式版,  Up: Changelog（更動日誌）

1.19.70 Python 3.5.4 rc1
------------------------

`发布日期: 2017-07-23'

* Menu:

* 安全性: 安全性<34>.
* 核心与内置函数: 核心与内置函数<57>.
* 库: 库<68>.
* 文档: 文档<47>.
* 测试: 测试<48>.
* 构建: 构建<51>.
* Windows: Windows<47>.
* C API: C API<39>.


File: python.info,  Node: 安全性<34>,  Next: 核心与内置函数<57>,  Up: Python 3 5 4 rc1

1.19.70.1 安全性
................

   - bpo-30730(1): Prevent environment variables injection in subprocess
     on Windows.  Prevent passing other environment variables and
     command arguments.

   - bpo-30694(2): 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
     ‘XML_SetHashSalt()’.

   - bpo-30500(3): Fix urllib.parse.splithost() to correctly parse
     fragments.  For example, ‘splithost('//127.0.0.1#@evil.com/')’ now
     correctly returns the ‘127.0.0.1’ host, instead of treating
     ‘@evil.com’ as the host in an authentication (‘login@host’).

   - bpo-29591(4): Update expat copy from 2.1.1 to 2.2.0 to get fixes of
     CVE-2016-0718 and CVE-2016-4472.  See
     ‘https://sourceforge.net/p/expat/bugs/537/’ for more information.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30730

   (2) https://bugs.python.org/issue30694

   (3) https://bugs.python.org/issue30500

   (4) https://bugs.python.org/issue29591


File: python.info,  Node: 核心与内置函数<57>,  Next: 库<68>,  Prev: 安全性<34>,  Up: Python 3 5 4 rc1

1.19.70.2 核心与内置函数
........................

   - bpo-30876(1): 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.

   - bpo-30765(2): Avoid blocking in pthread_mutex_lock() when
     PyThread_acquire_lock() is asked not to block.

   - bpo-27945(3): Fixed various segfaults with dict when input
     collections are mutated during searching, inserting or comparing.
     Based on patches by Duane Griffin and Tim Mitchell.

   - bpo-25794(4): Fixed type.__setattr__() and type.__delattr__() for
     non-interned attribute names.  Based on patch by Eryk Sun.

   - bpo-29935(5): Fixed error messages in the index() method of tuple,
     list and deque when pass indices of wrong type.

   - bpo-28876(6): ‘bool(range)’ works even if ‘len(range)’ raises *note
     OverflowError: a41.

   - bpo-29600(7): Fix wrapping coroutine return values in
     StopIteration.

   - bpo-29537(8): 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.

   - bpo-28598(9): Support __rmod__ for subclasses of str being called
     before str.__mod__.  Patch by Martijn Pieters.

   - bpo-29602(10): Fix incorrect handling of signed zeros in complex
     constructor for complex subclasses and for inputs having a
     __complex__ method.  Patch by Serhiy Storchaka.

   - bpo-29347(11): Fixed possibly dereferencing undefined pointers when
     creating weakref objects.

   - bpo-29438(12): Fixed use-after-free problem in key sharing dict.

   - bpo-29319(13): Prevent RunMainFromImporter overwriting sys.path[0].

   - bpo-29337(14): Fixed possible BytesWarning when compare the code
     objects.  Warnings could be emitted at compile time.

   - bpo-29478(15): If max_line_length=None is specified while using the
     Compat32 policy, it is no longer ignored.  Patch by Mircea Cosbuc.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30876

   (2) https://bugs.python.org/issue30765

   (3) https://bugs.python.org/issue27945

   (4) https://bugs.python.org/issue25794

   (5) https://bugs.python.org/issue29935

   (6) https://bugs.python.org/issue28876

   (7) https://bugs.python.org/issue29600

   (8) https://bugs.python.org/issue29537

   (9) https://bugs.python.org/issue28598

   (10) https://bugs.python.org/issue29602

   (11) https://bugs.python.org/issue29347

   (12) https://bugs.python.org/issue29438

   (13) https://bugs.python.org/issue29319

   (14) https://bugs.python.org/issue29337

   (15) https://bugs.python.org/issue29478


File: python.info,  Node: 库<68>,  Next: 文档<47>,  Prev: 核心与内置函数<57>,  Up: Python 3 5 4 rc1

1.19.70.3 库
............

   - bpo-29403(1): Fix ‘unittest.mock’’s autospec to not fail on
     method-bound builtin functions.  Patch by Aaron Gallagher.

   - bpo-30961(2): Fix decrementing a borrowed reference in tracemalloc.

   - bpo-30886(3): 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.

   - bpo-29854(4): Fix segfault in readline when using readline’s
     history-size option.  Patch by Nir Soffer.

   - bpo-30807(5): 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.

   - bpo-30441(6): Fix bug when modifying os.environ while iterating
     over it

   - bpo-30532(7): Fix email header value parser dropping folding white
     space in certain cases.

   - bpo-29169(8): Update zlib to 1.2.11.

   - bpo-30879(9): os.listdir() and os.scandir() now emit bytes names
     when called with bytes-like argument.

   - bpo-30746(10): Prohibited the ’=’ character in environment variable
     names in ‘os.putenv()’ and ‘os.spawn*()’.

   - bpo-29755(11): Fixed the lgettext() family of functions in the
     gettext module.  They now always return bytes.

   - bpo-30645(12): Fix path calculation in imp.load_package(), fixing
     it for cases when a package is only shipped with bytecodes.  Patch
     by Alexandru Ardelean.

   - bpo-23890(13): unittest.TestCase.assertRaises() now manually breaks
     a reference cycle to not keep objects alive longer than expected.

   - bpo-30149(14): inspect.signature() now supports callables with
     variable-argument parameters wrapped with partialmethod.  Patch by
     Dong-hee Na.

   - bpo-29931(15): Fixed comparison check for ipaddress.ip_interface
     objects.  Patch by Sanjay Sundaresan.

   - bpo-24484(16): Avoid race condition in multiprocessing cleanup.

   - bpo-28994(17): The traceback no longer displayed for SystemExit
     raised in a callback registered by atexit.

   - bpo-30508(18): Don’t log exceptions if Task/Future "cancel()"
     method was called.

   - bpo-28556(19): Updates to typing module: Add generic
     AsyncContextManager, add support for ContextManager on all
     versions.  Original PRs by Jelle Zijlstra and Ivan Levkivskyi

   - bpo-29870(20): Fix ssl sockets leaks when connection is aborted in
     asyncio/ssl implementation.  Patch by Michaël Sghaïer.

   - bpo-29743(21): Closing transport during handshake process leaks
     open socket.  Patch by Nikolay Kim

   - bpo-27585(22): Fix waiter cancellation in asyncio.Lock.  Patch by
     Mathieu Sornay.

   - bpo-30418(23): On Windows, subprocess.Popen.communicate() now also
     ignore EINVAL on stdin.write() if the child process is still
     running but closed the pipe.

   - bpo-30378(24): Fix the problem that logging.handlers.SysLogHandler
     cannot handle IPv6 addresses.

   - bpo-29960(25): Preserve generator state when
     _random.Random.setstate() raises an exception.  Patch by Bryan
     Olson.

   - bpo-30414(26): multiprocessing.Queue._feed background running
     thread do not break from main loop on exception.

   - bpo-30003(27): Fix handling escape characters in HZ codec.  Based
     on patch by Ma Lin.

   - bpo-30301(28): Fix AttributeError when using SimpleQueue.empty()
     under `spawn' and `forkserver' start methods.

   - bpo-30329(29): 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.

   - bpo-30375(30): 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.

   - bpo-30048(31): Fixed ‘Task.cancel()’ can be ignored when the task
     is running coroutine and the coroutine returned without any more
     ‘await’.

   - bpo-29990(32): Fix range checking in GB18030 decoder.  Original
     patch by Ma Lin.

   - bpo-26293(33): Change resulted because of zipfile breakage.  (See
     also: bpo-29094(34))

   - bpo-30243(35): 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.

   - bpo-30185(36): Avoid KeyboardInterrupt tracebacks in forkserver
     helper process when Ctrl-C is received.

   - bpo-28556(37): Various updates to typing module: add
     typing.NoReturn type, use WrapperDescriptorType, minor bug-fixes.
     Original PRs by Jim Fasarakis-Hilliard and Ivan Levkivskyi.

   - bpo-30205(38): Fix getsockname() for unbound AF_UNIX sockets on
     Linux.

   - bpo-30070(39): Fixed leaks and crashes in errors handling in the
     parser module.

   - bpo-30061(40): 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().

   - bpo-30068(41): _io._IOBase.readlines will check if it’s closed
     first when hint is present.

   - bpo-29694(42): Fixed race condition in pathlib mkdir with flags
     parents=True.  Patch by Armin Rigo.

   - bpo-29692(43): Fixed arbitrary unchaining of RuntimeError
     exceptions in contextlib.contextmanager.  Patch by Siddharth
     Velankar.

   - bpo-29998(44): Pickling and copying ImportError now preserves name
     and path attributes.

   - bpo-29942(45): Fix a crash in itertools.chain.from_iterable when
     encountering long runs of empty iterables.

   - bpo-27863(46): Fixed multiple crashes in ElementTree caused by race
     conditions and wrong types.

   - bpo-28699(47): 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.

   - bpo-25803(48): Avoid incorrect errors raised by
     Path.mkdir(exist_ok=True) when the OS gives priority to errors such
     as EACCES over EEXIST.

   - bpo-29861(49): Release references to tasks, their arguments and
     their results as soon as they are finished in multiprocessing.Pool.

   - bpo-29884(50): faulthandler: Restore the old sigaltstack during
     teardown.  Patch by Christophe Zeitouny.

   - bpo-25455(51): Fixed crashes in repr of recursive buffered
     file-like objects.

   - bpo-29800(52): Fix crashes in partial.__repr__ if the keys of
     partial.keywords are not strings.  Patch by Michael Seifert.

   - bpo-29742(53): get_extra_info() raises exception if get called on
     closed ssl transport.  Patch by Nikolay Kim.

   - bpo-8256(54): Fixed possible failing or crashing input() if
     attributes "encoding" or "errors" of sys.stdin or sys.stdout are
     not set or are not strings.

   - bpo-28298(55): Fix a bug that prevented array ’Q’, ’L’ and ’I’ from
     accepting big intables (objects that have __int__) as elements.
     Patch by Oren Milman.

   - bpo-29615(56): SimpleXMLRPCDispatcher no longer chains KeyError (or
     any other exception) to exception(s) raised in the dispatched
     methods.  Patch by Petr Motejlek.

   - bpo-29704(57): asyncio.subprocess.SubprocessStreamProtocol no
     longer closes before all pipes are closed.

   - bpo-29703(58): Fix asyncio to support instantiation of new event
     loops in child processes.

   - bpo-29376(59): Fix assertion error in
     threading._DummyThread.is_alive().

   - bpo-29110(60): 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.

   - bpo-28961(61): Fix unittest.mock._Call helper: don’t ignore the
     name parameter anymore.  Patch written by Jiajun Huang.

   - bpo-29532(62): Altering a kwarg dictionary passed to
     functools.partial() no longer affects a partial object after
     creation.

   - bpo-28556(63): 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.

   - bpo-29100(64): Fix datetime.fromtimestamp() regression introduced
     in Python 3.6.0: check minimum and maximum years.

   - bpo-29519(65): Fix weakref spewing exceptions during interpreter
     shutdown when used with a rare combination of multiprocessing and
     custom codecs.

   - bpo-29416(66): Prevent infinite loop in pathlib.Path.mkdir

   - bpo-29444(67): Fixed out-of-bounds buffer access in the group()
     method of the match object.  Based on patch by WGH.

   - bpo-29335(68): Fix subprocess.Popen.wait() when the child process
     has exited to a stopped instead of terminated state (ex: when under
     ptrace).

   - bpo-29290(69): Fix a regression in argparse that help messages
     would wrap at non-breaking spaces.

   - bpo-28735(70): Fixed the comparison of mock.MagickMock with
     mock.ANY.

   - bpo-29011(71): Fix an important omission by adding Deque to the
     typing module.

   - bpo-29219(72): Fixed infinite recursion in the repr of
     uninitialized ctypes.CDLL instances.

   - bpo-28969(73): 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.

   - bpo-29142(74): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29403

   (2) https://bugs.python.org/issue30961

   (3) https://bugs.python.org/issue30886

   (4) https://bugs.python.org/issue29854

   (5) https://bugs.python.org/issue30807

   (6) https://bugs.python.org/issue30441

   (7) https://bugs.python.org/issue30532

   (8) https://bugs.python.org/issue29169

   (9) https://bugs.python.org/issue30879

   (10) https://bugs.python.org/issue30746

   (11) https://bugs.python.org/issue29755

   (12) https://bugs.python.org/issue30645

   (13) https://bugs.python.org/issue23890

   (14) https://bugs.python.org/issue30149

   (15) https://bugs.python.org/issue29931

   (16) https://bugs.python.org/issue24484

   (17) https://bugs.python.org/issue28994

   (18) https://bugs.python.org/issue30508

   (19) https://bugs.python.org/issue28556

   (20) https://bugs.python.org/issue29870

   (21) https://bugs.python.org/issue29743

   (22) https://bugs.python.org/issue27585

   (23) https://bugs.python.org/issue30418

   (24) https://bugs.python.org/issue30378

   (25) https://bugs.python.org/issue29960

   (26) https://bugs.python.org/issue30414

   (27) https://bugs.python.org/issue30003

   (28) https://bugs.python.org/issue30301

   (29) https://bugs.python.org/issue30329

   (30) https://bugs.python.org/issue30375

   (31) https://bugs.python.org/issue30048

   (32) https://bugs.python.org/issue29990

   (33) https://bugs.python.org/issue26293

   (34) https://bugs.python.org/issue29094

   (35) https://bugs.python.org/issue30243

   (36) https://bugs.python.org/issue30185

   (37) https://bugs.python.org/issue28556

   (38) https://bugs.python.org/issue30205

   (39) https://bugs.python.org/issue30070

   (40) https://bugs.python.org/issue30061

   (41) https://bugs.python.org/issue30068

   (42) https://bugs.python.org/issue29694

   (43) https://bugs.python.org/issue29692

   (44) https://bugs.python.org/issue29998

   (45) https://bugs.python.org/issue29942

   (46) https://bugs.python.org/issue27863

   (47) https://bugs.python.org/issue28699

   (48) https://bugs.python.org/issue25803

   (49) https://bugs.python.org/issue29861

   (50) https://bugs.python.org/issue29884

   (51) https://bugs.python.org/issue25455

   (52) https://bugs.python.org/issue29800

   (53) https://bugs.python.org/issue29742

   (54) https://bugs.python.org/issue8256

   (55) https://bugs.python.org/issue28298

   (56) https://bugs.python.org/issue29615

   (57) https://bugs.python.org/issue29704

   (58) https://bugs.python.org/issue29703

   (59) https://bugs.python.org/issue29376

   (60) https://bugs.python.org/issue29110

   (61) https://bugs.python.org/issue28961

   (62) https://bugs.python.org/issue29532

   (63) https://bugs.python.org/issue28556

   (64) https://bugs.python.org/issue29100

   (65) https://bugs.python.org/issue29519

   (66) https://bugs.python.org/issue29416

   (67) https://bugs.python.org/issue29444

   (68) https://bugs.python.org/issue29335

   (69) https://bugs.python.org/issue29290

   (70) https://bugs.python.org/issue28735

   (71) https://bugs.python.org/issue29011

   (72) https://bugs.python.org/issue29219

   (73) https://bugs.python.org/issue28969

   (74) https://bugs.python.org/issue29142


File: python.info,  Node: 文档<47>,  Next: 测试<48>,  Prev: 库<68>,  Up: Python 3 5 4 rc1

1.19.70.4 文档
..............

   - bpo-30176(1): Add missing attribute related constants in curses
     documentation.

   - bpo-26985(2): Add missing info of code object in inspect
     documentation.

   - bpo-28929(3): Link the documentation to its source file on GitHub.

   - bpo-25008(4): Document smtpd.py as effectively deprecated and add a
     pointer to aiosmtpd, a third-party asyncio-based replacement.

   - bpo-26355(5): Add canonical header link on each page to
     corresponding major version of the documentation.  Patch by
     Matthias Bussonnier.

   - bpo-29349(6): Fix Python 2 syntax in code for building the
     documentation.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30176

   (2) https://bugs.python.org/issue26985

   (3) https://bugs.python.org/issue28929

   (4) https://bugs.python.org/issue25008

   (5) https://bugs.python.org/issue26355

   (6) https://bugs.python.org/issue29349


File: python.info,  Node: 测试<48>,  Next: 构建<51>,  Prev: 文档<47>,  Up: Python 3 5 4 rc1

1.19.70.5 测试
..............

   - bpo-30822(1): Fix regrtest command line parser to allow passing -u
     extralargefile to run test_zipfile64.

   - bpo-30383(2): 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(3)), –matchfile (load a list
     of test filters from a text file, bpo-30540(4)), –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(5)).

   - bpo-30357(6): 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.

   - bpo-28087(7): 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.

   - bpo-30197(8): 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.

   - bpo-29571(9): to match the behaviour of the ‘re.LOCALE’ flag,
     test_re.test_locale_flag now uses
     ‘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)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30822

   (2) https://bugs.python.org/issue30383

   (3) https://bugs.python.org/issue30523

   (4) https://bugs.python.org/issue30540

   (5) https://bugs.python.org/issue30675

   (6) https://bugs.python.org/issue30357

   (7) https://bugs.python.org/issue28087

   (8) https://bugs.python.org/issue30197

   (9) https://bugs.python.org/issue29571


File: python.info,  Node: 构建<51>,  Next: Windows<47>,  Prev: 测试<48>,  Up: Python 3 5 4 rc1

1.19.70.6 构建
..............

   - bpo-29243(1): Prevent unnecessary rebuilding of Python during ‘make
     test’, ‘make install’ and some other make targets when configured
     with ‘--enable-optimizations’.

   - bpo-23404(2): Don’t regenerate generated files based on file
     modification time anymore: the action is now explicit.  Replace
     ‘make touch’ with ‘make regen-all’.

   - bpo-29643(3): Fix ‘--enable-optimization’ didn’t work.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29243

   (2) https://bugs.python.org/issue23404

   (3) https://bugs.python.org/issue29643


File: python.info,  Node: Windows<47>,  Next: C API<39>,  Prev: 构建<51>,  Up: Python 3 5 4 rc1

1.19.70.7 Windows
.................

   - bpo-30687(1): Locate msbuild.exe on Windows when building rather
     than vcvarsall.bat

   - bpo-29392(2): Prevent crash when passing invalid arguments into
     msvcrt module.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue30687

   (2) https://bugs.python.org/issue29392


File: python.info,  Node: C API<39>,  Prev: Windows<47>,  Up: Python 3 5 4 rc1

1.19.70.8 C API
...............

   - bpo-27867(1): 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.

   - bpo-29083(2): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27867

   (2) https://bugs.python.org/issue29083


File: python.info,  Node: Python 3 5 3 正式版,  Next: Python 3 5 3 rc1,  Prev: Python 3 5 4 rc1,  Up: Changelog（更動日誌）

1.19.71 Python 3.5.3 正式版
---------------------------

`发布日期: 2017-01-17'

There were no code changes between 3.5.3rc1 and 3.5.3 final.


File: python.info,  Node: Python 3 5 3 rc1,  Next: Python 3 5 2 正式版,  Prev: Python 3 5 3 正式版,  Up: Changelog（更動日誌）

1.19.72 Python 3.5.3 rc1
------------------------

`发布日期: 2017-01-02'

* Menu:

* 核心与内置函数: 核心与内置函数<58>.
* 库: 库<69>.
* 安全性: 安全性<35>.
* 库: 库<70>.
* 安全性: 安全性<36>.
* 库: 库<71>.
* IDLE: IDLE<44>.
* C API: C API<40>.
* 文档: 文档<48>.
* 测试: 测试<49>.
* 工具/示例: 工具/示例<29>.
* Windows: Windows<48>.
* 构建: 构建<52>.


File: python.info,  Node: 核心与内置函数<58>,  Next: 库<69>,  Up: Python 3 5 3 rc1

1.19.72.1 核心与内置函数
........................

   - bpo-29073(1): bytearray formatting no longer truncates on first
     null byte.

   - bpo-28932(2): Do not include <sys/random.h> if it does not exist.

   - bpo-28147(3): Fix a memory leak in split-table dictionaries:
     setattr() must not convert combined table into split table.

   - bpo-25677(4): Correct the positioning of the syntax error caret for
     indented blocks.  Based on patch by Michael Layzell.

   - bpo-29000(5): Fixed bytes formatting of octals with zero padding in
     alternate form.

   - bpo-28512(6): Fixed setting the offset attribute of SyntaxError by
     PyErr_SyntaxLocationEx() and PyErr_SyntaxLocationObject().

   - bpo-28991(7): functools.lru_cache() was susceptible to an obscure
     reentrancy bug caused by a monkey-patched len() function.

   - bpo-28648(8): Fixed crash in Py_DecodeLocale() in debug build on
     Mac OS X when decode astral characters.  Patch by Xiang Zhang.

   - bpo-19398(9): Extra slash no longer added to sys.path components in
     case of empty compile-time PYTHONPATH components.

   - bpo-28426(10): Fixed potential crash in PyUnicode_AsDecodedObject()
     in debug build.

   - bpo-23782(11): Fixed possible memory leak in _PyTraceback_Add() and
     exception loss in PyTraceBack_Here().

   - bpo-28379(12): Added sanity checks and tests for
     PyUnicode_CopyCharacters().  Patch by Xiang Zhang.

   - bpo-28376(13): The type of long range iterator is now registered as
     Iterator.  Patch by Oren Milman.

   - bpo-28376(14): The constructor of range_iterator now checks that
     step is not 0.  Patch by Oren Milman.

   - bpo-26906(15): Resolving special methods of uninitialized type now
     causes implicit initialization of the type instead of a fail.

   - bpo-18287(16): PyType_Ready() now checks that tp_name is not NULL.
     Original patch by Niklas Koep.

   - bpo-24098(17): Fixed possible crash when AST is changed in process
     of compiling it.

   - bpo-28350(18): String constants with null character no longer
     interned.

   - bpo-26617(19): Fix crash when GC runs during weakref callbacks.

   - bpo-27942(20): String constants now interned recursively in tuples
     and frozensets.

   - bpo-21578(21): Fixed misleading error message when ImportError
     called with invalid keyword args.

   - bpo-28203(22): Fix incorrect type in error message from
     ‘complex(1.0, {2:3})’.  Patch by Soumya Sharma.

   - bpo-27955(23): Fallback on reading /dev/urandom device when the
     getrandom() syscall fails with EPERM, for example when blocked by
     SECCOMP.

   - bpo-28131(24): Fix a regression in zipimport’s compile_source().
     zipimport should use the same optimization level as the
     interpreter.

   - bpo-25221(25): Fix corrupted result from PyLong_FromLong(0) when
     Python is compiled with NSMALLPOSINTS = 0.

   - bpo-25758(26): Prevents zipimport from unnecessarily encoding a
     filename (patch by Eryk Sun)

   - bpo-28189(27): dictitems_contains no longer swallows compare
     errors.  (Patch by Xiang Zhang)

   - bpo-27812(28): Properly clear out a generator’s frame’s
     backreference to the generator to prevent crashes in frame.clear().

   - bpo-27811(29): Fix a crash when a coroutine that has not been
     awaited is finalized with warnings-as-errors enabled.

   - bpo-27587(30): Fix another issue found by PVS-Studio: Null pointer
     check after use of ’def’ in _PyState_AddModule().  Initial patch by
     Christian Heimes.

   - bpo-26020(31): set literal evaluation order did not match
     documented behaviour.

   - bpo-27782(32): Multi-phase extension module import now correctly
     allows the ‘m_methods’ field to be used to add module level
     functions to instances of non-module types returned from
     ‘Py_create_mod’.  Patch by Xiang Zhang.

   - bpo-27936(33): 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.

   - bpo-27487(34): 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.

   - bpo-27558(35): 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.

   - bpo-27419(36): 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.

   - bpo-27083(37): Respect the PYTHONCASEOK environment variable under
     Windows.

   - bpo-27514(38): Make having too many statically nested blocks a
     SyntaxError instead of SystemError.

   - bpo-27473(39): Fixed possible integer overflow in bytes and
     bytearray concatenations.  Patch by Xiang Zhang.

   - bpo-27507(40): Add integer overflow check in bytearray.extend().
     Patch by Xiang Zhang.

   - bpo-27581(41): Don’t rely on wrapping for overflow check in
     PySequence_Tuple().  Patch by Xiang Zhang.

   - bpo-27443(42): __length_hint__() of bytearray iterators no longer
     return a negative integer for a resized bytearray.

   - bpo-27942(43): Fix memory leak in codeobject.c

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29073

   (2) https://bugs.python.org/issue28932

   (3) https://bugs.python.org/issue28147

   (4) https://bugs.python.org/issue25677

   (5) https://bugs.python.org/issue29000

   (6) https://bugs.python.org/issue28512

   (7) https://bugs.python.org/issue28991

   (8) https://bugs.python.org/issue28648

   (9) https://bugs.python.org/issue19398

   (10) https://bugs.python.org/issue28426

   (11) https://bugs.python.org/issue23782

   (12) https://bugs.python.org/issue28379

   (13) https://bugs.python.org/issue28376

   (14) https://bugs.python.org/issue28376

   (15) https://bugs.python.org/issue26906

   (16) https://bugs.python.org/issue18287

   (17) https://bugs.python.org/issue24098

   (18) https://bugs.python.org/issue28350

   (19) https://bugs.python.org/issue26617

   (20) https://bugs.python.org/issue27942

   (21) https://bugs.python.org/issue21578

   (22) https://bugs.python.org/issue28203

   (23) https://bugs.python.org/issue27955

   (24) https://bugs.python.org/issue28131

   (25) https://bugs.python.org/issue25221

   (26) https://bugs.python.org/issue25758

   (27) https://bugs.python.org/issue28189

   (28) https://bugs.python.org/issue27812

   (29) https://bugs.python.org/issue27811

   (30) https://bugs.python.org/issue27587

   (31) https://bugs.python.org/issue26020

   (32) https://bugs.python.org/issue27782

   (33) https://bugs.python.org/issue27936

   (34) https://bugs.python.org/issue27487

   (35) https://bugs.python.org/issue27558

   (36) https://bugs.python.org/issue27419

   (37) https://bugs.python.org/issue27083

   (38) https://bugs.python.org/issue27514

   (39) https://bugs.python.org/issue27473

   (40) https://bugs.python.org/issue27507

   (41) https://bugs.python.org/issue27581

   (42) https://bugs.python.org/issue27443

   (43) https://bugs.python.org/issue27942


File: python.info,  Node: 库<69>,  Next: 安全性<35>,  Prev: 核心与内置函数<58>,  Up: Python 3 5 3 rc1

1.19.72.2 库
............

   - bpo-15812(1): inspect.getframeinfo() now correctly shows the first
     line of a context.  Patch by Sam Breese.

   - bpo-29094(2): Offsets in a ZIP file created with extern file object
     and modes "w" and "x" now are relative to the start of the file.

   - bpo-13051(3): Fixed recursion errors in large or resized
     curses.textpad.Textbox.  Based on patch by Tycho Andersen.

   - bpo-29119(4): Fix weakrefs in the pure python version of
     collections.OrderedDict move_to_end() method.  Contributed by Andra
     Bogildea.

   - bpo-9770(5): curses.ascii predicates now work correctly with
     negative integers.

   - bpo-28427(6): old keys should not remove new values from
     WeakValueDictionary when collecting from another thread.

   - bpo-28923(7): Remove editor artifacts from Tix.py.

   - bpo-28871(8): Fixed a crash when deallocate deep ElementTree.

   - bpo-19542(9): Fix bugs in WeakValueDictionary.setdefault() and
     WeakValueDictionary.pop() when a GC collection happens in another
     thread.

   - bpo-20191(10): Fixed a crash in resource.prlimit() when pass a
     sequence that doesn’t own its elements as limits.

   - bpo-28779(11): multiprocessing.set_forkserver_preload() would crash
     the forkserver process if a preloaded module instantiated some
     multiprocessing objects such as locks.

   - bpo-28847(12): dbm.dumb now supports reading read-only files and no
     longer writes the index file when it is not changed.

   - bpo-25659(13): In ctypes, prevent a crash calling the from_buffer()
     and from_buffer_copy() methods on abstract classes like Array.

   - bpo-28732(14): Fix crash in os.spawnv() with no elements in args

   - bpo-28485(15): Always raise ValueError for negative
     compileall.compile_dir(workers=...)  parameter, even when
     multithreading is unavailable.

   - bpo-28387(16): Fixed possible crash in _io.TextIOWrapper
     deallocator when the garbage collector is invoked in other thread.
     Based on patch by Sebastian Cufre.

   - bpo-27517(17): LZMA compressor and decompressor no longer raise
     exceptions if given empty data twice.  Patch by Benjamin Fogle.

   - bpo-28549(18): Fixed segfault in curses’s addch() with ncurses6.

   - bpo-28449(19): 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.

   - bpo-23262(20): The webbrowser module now supports Firefox 36+ and
     derived browsers.  Based on patch by Oleg Broytman.

   - bpo-27939(21): 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.

   - bpo-28255(22): calendar.TextCalendar().prmonth() no longer prints a
     space at the start of new line after printing a month’s calendar.
     Patch by Xiang Zhang.

   - bpo-20491(23): The textwrap.TextWrapper class now honors
     non-breaking spaces.  Based on patch by Kaarle Ritvanen.

   - bpo-28353(24): os.fwalk() no longer fails on broken links.

   - bpo-25464(25): Fixed HList.header_exists() in tkinter.tix module by
     addin a workaround to Tix library bug.

   - bpo-28488(26): shutil.make_archive() no longer add entry "./" to
     ZIP archive.

   - bpo-24452(27): Make webbrowser support Chrome on Mac OS X.

   - bpo-20766(28): Fix references leaked by pdb in the handling of
     SIGINT handlers.

   - bpo-26293(29): 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.

   - bpo-28321(30): Fixed writing non-BMP characters with binary format
     in plistlib.

   - bpo-28322(31): Fixed possible crashes when unpickle itertools
     objects from incorrect pickle data.  Based on patch by John Leitch.

   - Fix possible integer overflows and crashes in the mmap module with
     unusual usage patterns.

   - bpo-1703178(32): Fix the ability to pass the –link-objects option
     to the distutils build_ext command.

   - bpo-28253(33): 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.

   - bpo-28275(34): Fixed possible use after free in the decompress()
     methods of the LZMADecompressor and BZ2Decompressor classes.
     Original patch by John Leitch.

   - bpo-27897(35): Fixed possible crash in
     sqlite3.Connection.create_collation() if pass invalid string-like
     object as a name.  Patch by Xiang Zhang.

   - bpo-18893(36): Fix invalid exception handling in
     Lib/ctypes/macholib/dyld.py.  Patch by Madison May.

   - bpo-27611(37): Fixed support of default root window in the
     tkinter.tix module.

   - bpo-27348(38): In the traceback module, restore the formatting of
     exception messages like "Exception: None".  This fixes a regression
     introduced in 3.5a2.

   - bpo-25651(39): Allow falsy values to be used for msg parameter of
     subTest().

   - bpo-27932(40): Prevent memory leak in win32_ver().

   - Fix UnboundLocalError in socket._sendfile_use_sendfile.

   - bpo-28075(41): Check for ERROR_ACCESS_DENIED in Windows
     implementation of os.stat().  Patch by Eryk Sun.

   - bpo-25270(42): Prevent codecs.escape_encode() from raising
     SystemError when an empty bytestring is passed.

   - bpo-28181(43): Get antigravity over HTTPS. Patch by Kaartic
     Sivaraam.

   - bpo-25895(44): Enable WebSocket URL schemes in
     urllib.parse.urljoin.  Patch by Gergely Imreh and Markus
     Holtermann.

   - bpo-27599(45): Fixed buffer overrun in binascii.b2a_qp() and
     binascii.a2b_qp().

   - bpo-19003(46): m email.generator now replaces only ‘\r’ and/or ‘\n’
     line endings, per the RFC, instead of all unicode line endings.

   - bpo-28019(47): itertools.count() no longer rounds non-integer step
     in range between 1.0 and 2.0 to 1.

   - bpo-25969(48): Update the lib2to3 grammar to handle the unpacking
     generalizations added in 3.5.

   - bpo-14977(49): mailcap now respects the order of the lines in the
     mailcap files ("first match"), as required by RFC 1542.  Patch by
     Michael Lazar.

   - bpo-24594(50): Validates persist parameter when opening MSI
     database

   - bpo-17582(51): xml.etree.ElementTree nows preserves whitespaces in
     attributes (Patch by Duane Griffin.  Reviewed and approved by
     Stefan Behnel.)

   - bpo-28047(52): Fixed calculation of line length used for the base64
     CTE in the new email policies.

   - bpo-27445(53): Don’t pass str(_charset) to MIMEText.set_payload().
     Patch by Claude Paroz.

   - bpo-22450(54): urllib now includes an ‘Accept: */*’ header among
     the default headers.  This makes the results of REST API requests
     more consistent and predictable especially when proxy servers are
     involved.

   - 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.

   - bpo-27570(55): Avoid zero-length memcpy() etc calls with null
     source pointers in the "ctypes" and "array" modules.

   - bpo-22233(56): Break email header lines `only' on the RFC specified
     CR and LF characters, not on arbitrary unicode line breaks.  This
     also fixes a bug in HTTP header parsing.

   - bpo-27988(57): Fix email iter_attachments incorrect mutation of
     payload list.

   - bpo-27691(58): Fix ssl module’s parsing of GEN_RID subject
     alternative name fields in X.509 certs.

   - bpo-27850(59): Remove 3DES from ssl module’s default cipher list to
     counter measure sweet32 attack (CVE-2016-2183).

   - bpo-27766(60): Add ChaCha20 Poly1305 to ssl module’s default cipher
     list.  (Required OpenSSL 1.1.0 or LibreSSL).

   - bpo-26470(61): Port ssl and hashlib module to OpenSSL 1.1.0.

   - Remove support for passing a file descriptor to os.access.  It
     never worked but previously didn’t raise.

   - bpo-12885(62): Fix error when distutils encounters symlink.

   - bpo-27881(63): Fixed possible bugs when setting
     sqlite3.Connection.isolation_level.  Based on patch by Xiang Zhang.

   - bpo-27861(64): Fixed a crash in sqlite3.Connection.cursor() when a
     factory creates not a cursor.  Patch by Xiang Zhang.

   - bpo-19884(65): Avoid spurious output on OS X with Gnu Readline.

   - bpo-27706(66): 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.

   - bpo-10513(67): Fix a regression in Connection.commit().  Statements
     should not be reset after a commit.

   - A new version of typing.py from ‘https://github.com/python/typing’:
     Collection (only for 3.6) (bpo-27598(68)).  Add FrozenSet to
     __all__ (upstream #261).  Fix crash in _get_type_vars() (upstream
     #259).  Remove the dict constraint in ForwardRef._eval_type
     (upstream #252).

   - bpo-27539(69): Fix unnormalised ‘Fraction.__pow__’ result in the
     case of negative exponent and negative base.

   - bpo-21718(70): cursor.description is now available for queries
     using CTEs.

   - bpo-2466(71): posixpath.ismount now correctly recognizes mount
     points which the user does not have permission to access.

   - bpo-27773(72): Correct some memory management errors
     server_hostname in _ssl.wrap_socket().

   - bpo-26750(73): unittest.mock.create_autospec() now works properly
     for subclasses of property() and other data descriptors.

   - In the curses module, raise an error if window.getstr() or
     window.instr() is passed a negative value.

   - bpo-27783(74): Fix possible usage of uninitialized memory in
     operator.methodcaller.

   - bpo-27774(75): Fix possible Py_DECREF on unowned object in _sre.

   - bpo-27760(76): Fix possible integer overflow in binascii.b2a_qp.

   - bpo-27758(77): Fix possible integer overflow in the _csv module for
     large record lengths.

   - bpo-27568(78): 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.

   - bpo-27656(79): Do not assume sched.h defines any SCHED_* constants.

   - bpo-27130(80): 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.

   - bpo-27533(81): Release GIL in nt._isdir

   - bpo-17711(82): Fixed unpickling by the persistent ID with protocol
     0.  Original patch by Alexandre Vassalotti.

   - bpo-27522(83): Avoid an unintentional reference cycle in
     email.feedparser.

   - bpo-26844(84): Fix error message for imp.find_module() to refer to
     ’path’ instead of ’name’.  Patch by Lev Maximov.

   - bpo-23804(85): Fix SSL zero-length recv() calls to not block and
     not raise an error about unclean EOF.

   - bpo-27466(86): Change time format returned by
     http.cookie.time2netscape, confirming the netscape cookie format
     and making it consistent with documentation.

   - bpo-26664(87): Fix activate.fish by removing mis-use of ‘$’.

   - bpo-22115(88): 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.

   - Fix a scoping issue in importlib.util.LazyLoader which triggered an
     UnboundLocalError when lazy-loading a module that was already put
     into sys.modules.

   - bpo-27079(89): Fixed curses.ascii functions isblank(), iscntrl()
     and ispunct().

   - bpo-26754(90): Some functions (compile() etc) accepted a filename
     argument encoded as an iterable of integers.  Now only strings and
     byte-like objects are accepted.

   - bpo-27048(91): Prevents distutils failing on Windows when
     environment variables contain non-ASCII characters

   - bpo-27330(92): Fixed possible leaks in the ctypes module.

   - bpo-27238(93): Got rid of bare excepts in the turtle module.
     Original patch by Jelle Zijlstra.

   - bpo-27122(94): 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 PEP 479(95) bug described in issue25782.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15812

   (2) https://bugs.python.org/issue29094

   (3) https://bugs.python.org/issue13051

   (4) https://bugs.python.org/issue29119

   (5) https://bugs.python.org/issue9770

   (6) https://bugs.python.org/issue28427

   (7) https://bugs.python.org/issue28923

   (8) https://bugs.python.org/issue28871

   (9) https://bugs.python.org/issue19542

   (10) https://bugs.python.org/issue20191

   (11) https://bugs.python.org/issue28779

   (12) https://bugs.python.org/issue28847

   (13) https://bugs.python.org/issue25659

   (14) https://bugs.python.org/issue28732

   (15) https://bugs.python.org/issue28485

   (16) https://bugs.python.org/issue28387

   (17) https://bugs.python.org/issue27517

   (18) https://bugs.python.org/issue28549

   (19) https://bugs.python.org/issue28449

   (20) https://bugs.python.org/issue23262

   (21) https://bugs.python.org/issue27939

   (22) https://bugs.python.org/issue28255

   (23) https://bugs.python.org/issue20491

   (24) https://bugs.python.org/issue28353

   (25) https://bugs.python.org/issue25464

   (26) https://bugs.python.org/issue28488

   (27) https://bugs.python.org/issue24452

   (28) https://bugs.python.org/issue20766

   (29) https://bugs.python.org/issue26293

   (30) https://bugs.python.org/issue28321

   (31) https://bugs.python.org/issue28322

   (32) https://bugs.python.org/issue1703178

   (33) https://bugs.python.org/issue28253

   (34) https://bugs.python.org/issue28275

   (35) https://bugs.python.org/issue27897

   (36) https://bugs.python.org/issue18893

   (37) https://bugs.python.org/issue27611

   (38) https://bugs.python.org/issue27348

   (39) https://bugs.python.org/issue25651

   (40) https://bugs.python.org/issue27932

   (41) https://bugs.python.org/issue28075

   (42) https://bugs.python.org/issue25270

   (43) https://bugs.python.org/issue28181

   (44) https://bugs.python.org/issue25895

   (45) https://bugs.python.org/issue27599

   (46) https://bugs.python.org/issue19003

   (47) https://bugs.python.org/issue28019

   (48) https://bugs.python.org/issue25969

   (49) https://bugs.python.org/issue14977

   (50) https://bugs.python.org/issue24594

   (51) https://bugs.python.org/issue17582

   (52) https://bugs.python.org/issue28047

   (53) https://bugs.python.org/issue27445

   (54) https://bugs.python.org/issue22450

   (55) https://bugs.python.org/issue27570

   (56) https://bugs.python.org/issue22233

   (57) https://bugs.python.org/issue27988

   (58) https://bugs.python.org/issue27691

   (59) https://bugs.python.org/issue27850

   (60) https://bugs.python.org/issue27766

   (61) https://bugs.python.org/issue26470

   (62) https://bugs.python.org/issue12885

   (63) https://bugs.python.org/issue27881

   (64) https://bugs.python.org/issue27861

   (65) https://bugs.python.org/issue19884

   (66) https://bugs.python.org/issue27706

   (67) https://bugs.python.org/issue10513

   (68) https://bugs.python.org/issue27598

   (69) https://bugs.python.org/issue27539

   (70) https://bugs.python.org/issue21718

   (71) https://bugs.python.org/issue2466

   (72) https://bugs.python.org/issue27773

   (73) https://bugs.python.org/issue26750

   (74) https://bugs.python.org/issue27783

   (75) https://bugs.python.org/issue27774

   (76) https://bugs.python.org/issue27760

   (77) https://bugs.python.org/issue27758

   (78) https://bugs.python.org/issue27568

   (79) https://bugs.python.org/issue27656

   (80) https://bugs.python.org/issue27130

   (81) https://bugs.python.org/issue27533

   (82) https://bugs.python.org/issue17711

   (83) https://bugs.python.org/issue27522

   (84) https://bugs.python.org/issue26844

   (85) https://bugs.python.org/issue23804

   (86) https://bugs.python.org/issue27466

   (87) https://bugs.python.org/issue26664

   (88) https://bugs.python.org/issue22115

   (89) https://bugs.python.org/issue27079

   (90) https://bugs.python.org/issue26754

   (91) https://bugs.python.org/issue27048

   (92) https://bugs.python.org/issue27330

   (93) https://bugs.python.org/issue27238

   (94) https://bugs.python.org/issue27122

   (95) https://www.python.org/dev/peps/pep-0479


File: python.info,  Node: 安全性<35>,  Next: 库<70>,  Prev: 库<69>,  Up: Python 3 5 3 rc1

1.19.72.3 安全性
................

   - bpo-27278(1): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27278


File: python.info,  Node: 库<70>,  Next: 安全性<36>,  Prev: 安全性<35>,  Up: Python 3 5 3 rc1

1.19.72.4 库
............

   - bpo-26386(1): Fixed ttk.TreeView selection operations with item
     id’s containing spaces.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26386


File: python.info,  Node: 安全性<36>,  Next: 库<71>,  Prev: 库<70>,  Up: Python 3 5 3 rc1

1.19.72.5 安全性
................

   - bpo-22636(1): Avoid shell injection problems with
     ctypes.util.find_library().

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22636


File: python.info,  Node: 库<71>,  Next: IDLE<44>,  Prev: 安全性<36>,  Up: Python 3 5 3 rc1

1.19.72.6 库
............

   - bpo-16182(1): Fix various functions in the "readline" module to use
     the locale encoding, and fix get_begidx() and get_endidx() to
     return code point indexes.

   - bpo-27392(2): Add loop.connect_accepted_socket().  Patch by Jim
     Fulton.

   - bpo-27930(3): Improved behaviour of logging.handlers.QueueListener.
     Thanks to Paulo Andrade and Petr Viktorin for the analysis and
     patch.

   - bpo-21201(4): Improves readability of multiprocessing error
     message.  Thanks to Wojciech Walczak for patch.

   - bpo-27456(5): asyncio: Set TCP_NODELAY by default.

   - bpo-27906(6): Fix socket accept exhaustion during high TCP traffic.
     Patch by Kevin Conway.

   - bpo-28174(7): Handle when SO_REUSEPORT isn’t properly supported.
     Patch by Seth Michael Larson.

   - bpo-26654(8): Inspect functools.partial in asyncio.Handle.__repr__.
     Patch by iceboy.

   - bpo-26909(9): Fix slow pipes IO in asyncio.  Patch by INADA Naoki.

   - bpo-28176(10): Fix callbacks race in
     asyncio.SelectorLoop.sock_connect.

   - bpo-27759(11): Fix selectors incorrectly retain invalid file
     descriptors.  Patch by Mark Williams.

   - bpo-28368(12): Refuse monitoring processes if the child watcher has
     no loop attached.  Patch by Vincent Michel.

   - bpo-28369(13): Raise RuntimeError when transport’s FD is used with
     add_reader, add_writer, etc.

   - bpo-28370(14): Speedup asyncio.StreamReader.readexactly.  Patch by
     Коренберг Марк.

   - bpo-28371(15): Deprecate passing asyncio.Handles to
     run_in_executor.

   - bpo-28372(16): Fix asyncio to support formatting of non-python
     coroutines.

   - bpo-28399(17): Remove UNIX socket from FS before binding.  Patch by
     Коренберг Марк.

   - bpo-27972(18): Prohibit Tasks to await on themselves.

   - bpo-26923(19): Fix asyncio.Gather to refuse being cancelled once
     all children are done.  Patch by Johannes Ebke.

   - bpo-26796(20): Don’t configure the number of workers for default
     threadpool executor.  Initial patch by Hans Lawrenz.

   - bpo-28600(21): Optimize loop.call_soon().

   - bpo-28613(22): Fix get_event_loop() return the current loop if
     called from coroutines/callbacks.

   - bpo-28639(23): Fix inspect.isawaitable to always return bool Patch
     by Justin Mayfield.

   - bpo-28652(24): Make loop methods reject socket kinds they do not
     support.

   - bpo-28653(25): Fix a refleak in functools.lru_cache.

   - bpo-28703(26): Fix asyncio.iscoroutinefunction to handle Mock
     objects.

   - bpo-24142(27): Reading a corrupt config file left the parser in an
     invalid state.  Original patch by Florian Höch.

   - bpo-28990(28): Fix SSL hanging if connection is closed before
     handshake completed.  (Patch by HoHo-Ho)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue16182

   (2) https://bugs.python.org/issue27392

   (3) https://bugs.python.org/issue27930

   (4) https://bugs.python.org/issue21201

   (5) https://bugs.python.org/issue27456

   (6) https://bugs.python.org/issue27906

   (7) https://bugs.python.org/issue28174

   (8) https://bugs.python.org/issue26654

   (9) https://bugs.python.org/issue26909

   (10) https://bugs.python.org/issue28176

   (11) https://bugs.python.org/issue27759

   (12) https://bugs.python.org/issue28368

   (13) https://bugs.python.org/issue28369

   (14) https://bugs.python.org/issue28370

   (15) https://bugs.python.org/issue28371

   (16) https://bugs.python.org/issue28372

   (17) https://bugs.python.org/issue28399

   (18) https://bugs.python.org/issue27972

   (19) https://bugs.python.org/issue26923

   (20) https://bugs.python.org/issue26796

   (21) https://bugs.python.org/issue28600

   (22) https://bugs.python.org/issue28613

   (23) https://bugs.python.org/issue28639

   (24) https://bugs.python.org/issue28652

   (25) https://bugs.python.org/issue28653

   (26) https://bugs.python.org/issue28703

   (27) https://bugs.python.org/issue24142

   (28) https://bugs.python.org/issue28990


File: python.info,  Node: IDLE<44>,  Next: C API<40>,  Prev: 库<71>,  Up: Python 3 5 3 rc1

1.19.72.7 IDLE
..............

   - bpo-15308(1): Add ’interrupt execution’ (^C) to Shell menu.  Patch
     by Roger Serwy, updated by Bayard Randel.

   - bpo-27922(2): Stop IDLE tests from ’flashing’ gui widgets on the
     screen.

   - 在 IDLE 帮助窗口的标题中加入版本号

   - bpo-25564(3): In section on IDLE – console differences, mention
     that using exec means that __builtins__ is defined for each
     statement.

   - bpo-27714(4): 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.

   - bpo-25507(5): IDLE no longer runs buggy code because of its tkinter
     imports.  Users must include the same imports required to run
     directly in Python.

   - bpo-27452(6): add line counter and crc to IDLE configHandler test
     dump.

   - bpo-27365(7): Allow non-ascii chars in IDLE NEWS.txt, for
     contributor names.

   - bpo-27245(8): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15308

   (2) https://bugs.python.org/issue27922

   (3) https://bugs.python.org/issue25564

   (4) https://bugs.python.org/issue27714

   (5) https://bugs.python.org/issue25507

   (6) https://bugs.python.org/issue27452

   (7) https://bugs.python.org/issue27365

   (8) https://bugs.python.org/issue27245


File: python.info,  Node: C API<40>,  Next: 文档<48>,  Prev: IDLE<44>,  Up: Python 3 5 3 rc1

1.19.72.8 C API
...............

   - bpo-28808(1): PyUnicode_CompareWithASCIIString() now never raises
     exceptions.

   - bpo-26754(2): PyUnicode_FSDecoder() accepted a filename argument
     encoded as an iterable of integers.  Now only strings and
     bytes-like objects are accepted.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28808

   (2) https://bugs.python.org/issue26754


File: python.info,  Node: 文档<48>,  Next: 测试<49>,  Prev: C API<40>,  Up: Python 3 5 3 rc1

1.19.72.9 文档
..............

   - bpo-28513(1): Documented command-line interface of zipfile.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28513


File: python.info,  Node: 测试<49>,  Next: 工具/示例<29>,  Prev: 文档<48>,  Up: Python 3 5 3 rc1

1.19.72.10 测试
...............

   - bpo-28950(1): Disallow -j0 to be combined with -T/-l/-M in regrtest
     command line arguments.

   - bpo-28666(2): Now test.support.rmtree is able to remove unwritable
     or unreadable directories.

   - bpo-23839(3): Various caches now are cleared before running every
     test file.

   - bpo-28409(4): regrtest: fix the parser of command line arguments.

   - bpo-27787(5): Call gc.collect() before checking each test for
     "dangling threads", since the dangling threads are weak references.

   - bpo-27369(6): In test_pyexpat, avoid testing an error message
     detail that changed in Expat 2.2.0.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28950

   (2) https://bugs.python.org/issue28666

   (3) https://bugs.python.org/issue23839

   (4) https://bugs.python.org/issue28409

   (5) https://bugs.python.org/issue27787

   (6) https://bugs.python.org/issue27369


File: python.info,  Node: 工具/示例<29>,  Next: Windows<48>,  Prev: 测试<49>,  Up: Python 3 5 3 rc1

1.19.72.11 工具/示例
....................

   - bpo-27952(1): 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.

   - bpo-27332(2): Fixed the type of the first argument of module-level
     functions generated by Argument Clinic.  Patch by Petr Viktorin.

   - bpo-27418(3): Fixed Tools/importbench/importbench.py.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27952

   (2) https://bugs.python.org/issue27332

   (3) https://bugs.python.org/issue27418


File: python.info,  Node: Windows<48>,  Next: 构建<52>,  Prev: 工具/示例<29>,  Up: Python 3 5 3 rc1

1.19.72.12 Windows
..................

   - bpo-28251(1): Improvements to help manuals on Windows.

   - bpo-28110(2): launcher.msi has different product codes between
     32-bit and 64-bit

   - bpo-25144(3): Ensures TargetDir is set before continuing with
     custom install.

   - bpo-27469(4): Adds a shell extension to the launcher so that drag
     and drop works correctly.

   - bpo-27309(5): Enabled proper Windows styles in python[w].exe
     manifest.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28251

   (2) https://bugs.python.org/issue28110

   (3) https://bugs.python.org/issue25144

   (4) https://bugs.python.org/issue27469

   (5) https://bugs.python.org/issue27309


File: python.info,  Node: 构建<52>,  Prev: Windows<48>,  Up: Python 3 5 3 rc1

1.19.72.13 构建
...............

   - bpo-29080(1): Removes hard dependency on hg.exe from
     PCBuild/build.bat

   - bpo-23903(2): Added missed names to PC/python3.def.

   - bpo-10656(3): Fix out-of-tree building on AIX. Patch by Tristan
     Carel and Michael Haubenwallner.

   - bpo-26359(4): Rename –with-optimiations to –enable-optimizations.

   - bpo-28444(5): Fix missing extensions modules when cross compiling.

   - bpo-28248(6): 更新Windows 构建和OS X安装程序以使用OpenSSL 1.0.2j.

   - bpo-28258(7): Fixed build with Estonian locale (python-config and
     distclean targets in Makefile).  Patch by Arfrever Frehtes
     Taifersar Arahesis.

   - bpo-26661(8): setup.py now detects system libffi with multiarch
     wrapper.

   - bpo-28066(9): Fix the logic that searches build directories for
     generated include files when building outside the source tree.

   - bpo-15819(10): Remove redundant include search directory option for
     building outside the source tree.

   - bpo-27566(11): Fix clean target in freeze makefile (patch by Lisa
     Roach)

   - bpo-27705(12): Update message in validate_ucrtbase.py

   - bpo-27983(13): 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.

   - bpo-26307(14): The profile-opt build now applies PGO to the
     built-in modules.

   - bpo-26359(15): Add the –with-optimizations configure flag.

   - bpo-27713(16): Suppress spurious build warnings when updating
     importlib’s bootstrap files.  Patch by Xiang Zhang

   - bpo-25825(17): 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.

   - bpo-27453(18): CPP invocation in configure must use CPPFLAGS. Patch
     by Chi Hsuan Yen.

   - bpo-27641(19): The configure script now inserts comments into the
     makefile to prevent the pgen and _freeze_importlib executables from
     being cross-compiled.

   - bpo-26662(20): Set PYTHON_FOR_GEN in configure as the Python
     program to be used for file generation during the build.

   - bpo-10910(21): Avoid C++ compilation errors on FreeBSD and OS X.
     Also update FreedBSD version checks for the original ctype UTF-8
     workaround.

   - bpo-28676(22): Prevent missing ’getentropy’ declaration warning on
     macOS. Patch by Gareth Rees.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue29080

   (2) https://bugs.python.org/issue23903

   (3) https://bugs.python.org/issue10656

   (4) https://bugs.python.org/issue26359

   (5) https://bugs.python.org/issue28444

   (6) https://bugs.python.org/issue28248

   (7) https://bugs.python.org/issue28258

   (8) https://bugs.python.org/issue26661

   (9) https://bugs.python.org/issue28066

   (10) https://bugs.python.org/issue15819

   (11) https://bugs.python.org/issue27566

   (12) https://bugs.python.org/issue27705

   (13) https://bugs.python.org/issue27983

   (14) https://bugs.python.org/issue26307

   (15) https://bugs.python.org/issue26359

   (16) https://bugs.python.org/issue27713

   (17) https://bugs.python.org/issue25825

   (18) https://bugs.python.org/issue27453

   (19) https://bugs.python.org/issue27641

   (20) https://bugs.python.org/issue26662

   (21) https://bugs.python.org/issue10910

   (22) https://bugs.python.org/issue28676


File: python.info,  Node: Python 3 5 2 正式版,  Next: Python 3 5 2 rc1,  Prev: Python 3 5 3 rc1,  Up: Changelog（更動日誌）

1.19.73 Python 3.5.2 正式版
---------------------------

`发布日期: 2016-06-26'

* Menu:

* 核心与内置函数: 核心与内置函数<59>.
* 测试: 测试<50>.
* IDLE: IDLE<45>.


File: python.info,  Node: 核心与内置函数<59>,  Next: 测试<50>,  Up: Python 3 5 2 正式版

1.19.73.1 核心与内置函数
........................

   - bpo-26930(1): 更新Windows 构建以使用OpenSSL OpenSSL 1.0.2h.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26930


File: python.info,  Node: 测试<50>,  Next: IDLE<45>,  Prev: 核心与内置函数<59>,  Up: Python 3 5 2 正式版

1.19.73.2 测试
..............

   - bpo-26867(1): Ubuntu’s openssl OP_NO_SSLv3 is forced on by default;
     fix test.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26867


File: python.info,  Node: IDLE<45>,  Prev: 测试<50>,  Up: Python 3 5 2 正式版

1.19.73.3 IDLE
..............

   - bpo-27365(1): Allow non-ascii in idlelib/NEWS.txt - minimal part
     for 3.5.2.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27365


File: python.info,  Node: Python 3 5 2 rc1,  Next: Python 3 5 1 正式版,  Prev: Python 3 5 2 正式版,  Up: Changelog（更動日誌）

1.19.74 Python 3.5.2 rc1
------------------------

`发布日期: 2016-06-12'

* Menu:

* 核心与内置函数: 核心与内置函数<60>.
* 安全性: 安全性<37>.
* 库: 库<72>.
* 安全性: 安全性<38>.
* 库: 库<73>.
* 安全性: 安全性<39>.
* 库: 库<74>.
* 安全性: 安全性<40>.
* 库: 库<75>.
* 安全性: 安全性<41>.
* 库: 库<76>.
* IDLE: IDLE<46>.
* 文档: 文档<49>.
* 测试: 测试<51>.
* 构建: 构建<53>.
* Windows: Windows<49>.
* 工具/示例: 工具/示例<30>.
* Windows: Windows<50>.


File: python.info,  Node: 核心与内置函数<60>,  Next: 安全性<37>,  Up: Python 3 5 2 rc1

1.19.74.1 核心与内置函数
........................

   - bpo-27066(1): Fixed SystemError if a custom opener (for open())
     returns a negative number without setting an exception.

   - bpo-20041(2): Fixed TypeError when frame.f_trace is set to None.
     Patch by Xavier de Gaye.

   - bpo-26168(3): Fixed possible refleaks in failing Py_BuildValue()
     with the "N" format unit.

   - bpo-26991(4): Fix possible refleak when creating a function with
     annotations.

   - bpo-27039(5): Fixed bytearray.remove() for values greater than 127.
     Patch by Joe Jevnik.

   - bpo-23640(6): int.from_bytes() no longer bypasses constructors for
     subclasses.

   - bpo-26811(7): gc.get_objects() no longer contains a broken tuple
     with NULL pointer.

   - bpo-20120(8): 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.

   - bpo-26659(9): Make the builtin slice type support cycle collection.

   - bpo-26718(10): super.__init__ no longer leaks memory if called
     multiple times.  NOTE: A direct call of super.__init__ is not
     endorsed!

   - bpo-25339(11): PYTHONIOENCODING now has priority over locale in
     setting the error handler for stdin and stdout.

   - bpo-26494(12): 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.

   - bpo-26581(13): If coding cookie is specified multiple times on a
     line in Python source code file, only the first one is taken to
     account.

   - bpo-26464(14): 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.

   - bpo-22836(15): 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.

   - bpo-26302(16): Correct behavior to reject comma as a legal
     character for cookie names.

   - bpo-4806(17): Avoid masking the original TypeError exception when
     using star (‘*’) unpacking in function calls.  Based on patch by
     Hagen Fürstenau and Daniel Urban.

   - bpo-27138(18): Fix the doc comment for FileFinder.find_spec().

   - bpo-26154(19): 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.

   - bpo-26194(20): 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.

   - bpo-25843(21): When compiling code, don’t merge constants if they
     are equal but have a different types.  For example, ‘f1, f2 =
     lambda: 1, lambda: 1.0’ is now correctly compiled to two different
     functions: ‘f1()’ returns ‘1’ (‘int’) and ‘f2()’ returns ‘1.0’
     (‘int’), even if ‘1’ and ‘1.0’ are equal.

   - bpo-22995(22): [UPDATE] Comment out the one of the pickleability
     tests in _PyObject_GetState() due to regressions observed in
     Cython-based projects.

   - bpo-25961(23): Disallowed null characters in the type name.

   - bpo-25973(24): Fix segfault when an invalid nonlocal statement
     binds a name starting with two underscores.

   - bpo-22995(25): 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.

   - bpo-20440(26): Massive replacing unsafe attribute setting code with
     special macro Py_SETREF.

   - bpo-25766(27): Special method __bytes__() now works in str
     subclasses.

   - bpo-25421(28): __sizeof__ methods of builtin types now use dynamic
     basic size.  This allows sys.getsize() to work correctly with their
     subclasses with __slots__ defined.

   - bpo-25709(29): Fixed problem with in-place string concatenation and
     utf-8 cache.

   - bpo-27147(30): Mention PEP 420(31) in the importlib docs.

   - bpo-24097(32): Fixed crash in object.__reduce__() if slot name is
     freed inside __getattr__.

   - bpo-24731(33): 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.

   - bpo-26478(34): Fix semantic bugs when using binary operators with
     dictionary views and tuples.

   - bpo-26171(35): Fix possible integer overflow and heap corruption in
     zipimporter.get_data().

   - bpo-25660(36): Fix TAB key behaviour in REPL with readline.

   - bpo-25887(37): Raise a RuntimeError when a coroutine object is
     awaited more than once.

   - bpo-27243(38): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27066

   (2) https://bugs.python.org/issue20041

   (3) https://bugs.python.org/issue26168

   (4) https://bugs.python.org/issue26991

   (5) https://bugs.python.org/issue27039

   (6) https://bugs.python.org/issue23640

   (7) https://bugs.python.org/issue26811

   (8) https://bugs.python.org/issue20120

   (9) https://bugs.python.org/issue26659

   (10) https://bugs.python.org/issue26718

   (11) https://bugs.python.org/issue25339

   (12) https://bugs.python.org/issue26494

   (13) https://bugs.python.org/issue26581

   (14) https://bugs.python.org/issue26464

   (15) https://bugs.python.org/issue22836

   (16) https://bugs.python.org/issue26302

   (17) https://bugs.python.org/issue4806

   (18) https://bugs.python.org/issue27138

   (19) https://bugs.python.org/issue26154

   (20) https://bugs.python.org/issue26194

   (21) https://bugs.python.org/issue25843

   (22) https://bugs.python.org/issue22995

   (23) https://bugs.python.org/issue25961

   (24) https://bugs.python.org/issue25973

   (25) https://bugs.python.org/issue22995

   (26) https://bugs.python.org/issue20440

   (27) https://bugs.python.org/issue25766

   (28) https://bugs.python.org/issue25421

   (29) https://bugs.python.org/issue25709

   (30) https://bugs.python.org/issue27147

   (31) https://www.python.org/dev/peps/pep-0420

   (32) https://bugs.python.org/issue24097

   (33) https://bugs.python.org/issue24731

   (34) https://bugs.python.org/issue26478

   (35) https://bugs.python.org/issue26171

   (36) https://bugs.python.org/issue25660

   (37) https://bugs.python.org/issue25887

   (38) https://bugs.python.org/issue27243


File: python.info,  Node: 安全性<37>,  Next: 库<72>,  Prev: 核心与内置函数<60>,  Up: Python 3 5 2 rc1

1.19.74.2 安全性
................

   - bpo-26556(1): Update expat to 2.1.1, fixes CVE-2015-1283.

   - Fix TLS stripping vulnerability in smtplib, CVE-2016-0772.
     Reported by Team Oststrom

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26556


File: python.info,  Node: 库<72>,  Next: 安全性<38>,  Prev: 安全性<37>,  Up: Python 3 5 2 rc1

1.19.74.3 库
............

   - bpo-21386(1): Implement missing IPv4Address.is_global property.  It
     was documented since 07a5610bae9d.  Initial patch by Roger Luethi.

   - bpo-20900(2): distutils register command now decodes HTTP responses
     correctly.  Initial patch by ingrid.

   - 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 PEP 492(3)
     (Awaitable, AsyncIterable, AsyncIterator) have been added (in fact
     they made it into 3.5.1 but were never mentioned).

   - bpo-25738(4): 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.

   - bpo-21313(5): Fix the "platform" module to tolerate when
     sys.version contains truncated build information.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21386

   (2) https://bugs.python.org/issue20900

   (3) https://www.python.org/dev/peps/pep-0492

   (4) https://bugs.python.org/issue25738

   (5) https://bugs.python.org/issue21313


File: python.info,  Node: 安全性<38>,  Next: 库<73>,  Prev: 库<72>,  Up: Python 3 5 2 rc1

1.19.74.4 安全性
................

   - bpo-26839(1): On Linux, *note os.urandom(): 5cb. now calls
     ‘getrandom()’ with ‘GRND_NONBLOCK’ to fall back on reading
     ‘/dev/urandom’ if the urandom entropy pool is not initialized yet.
     Patch written by Colm Buckley.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26839


File: python.info,  Node: 库<73>,  Next: 安全性<39>,  Prev: 安全性<38>,  Up: Python 3 5 2 rc1

1.19.74.5 库
............

   - bpo-27164(1): In the zlib module, allow decompressing raw Deflate
     streams with a predefined zdict.  Based on patch by Xiang Zhang.

   - bpo-24291(2): 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.

   - bpo-26809(3): Add ‘__all__’ to *note string: f6.  Patch by Emanuel
     Barry.

   - bpo-26373(4): subprocess.Popen.communicate now correctly ignores
     BrokenPipeError when the child process dies before .communicate()
     is called in more/all circumstances.

   - bpo-21776(5): distutils.upload now correctly handles HTTPError.
     Initial patch by Claudiu Popa.

   - bpo-27114(6): Fix SSLContext._load_windows_store_certs fails with
     PermissionError

   - bpo-18383(7): Avoid creating duplicate filters when using
     filterwarnings and simplefilter.  Based on patch by Alex Shkop.

   - bpo-27057(8): 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.

   - bpo-27014(9): Fix infinite recursion using typing.py.  Thanks to
     Kalle Tuure!

   - bpo-14132(10): Fix urllib.request redirect handling when the target
     only has a query string.  Original fix by Ján Janech.

   - bpo-17214(11): 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.

   - bpo-26892(12): Honor debuglevel flag in urllib.request.HTTPHandler.
     Patch contributed by Chi Hsuan Yen.

   - bpo-22274(13): In the subprocess module, allow stderr to be
     redirected to stdout even when stdout is not redirected.  Patch by
     Akira Li.

   - bpo-26807(14): mock_open ’files’ no longer error on readline at end
     of file.  Patch from Yolanda Robla.

   - bpo-25745(15): Fixed leaking a userptr in curses panel destructor.

   - bpo-26977(16): Removed unnecessary, and ignored, call to sum of
     squares helper in statistics.pvariance.

   - bpo-26881(17): The modulefinder module now supports extended opcode
     arguments.

   - bpo-23815(18): Fixed crashes related to directly created instances
     of types in _tkinter and curses.panel modules.

   - bpo-17765(19): weakref.ref() no longer silently ignores keyword
     arguments.  Patch by Georg Brandl.

   - bpo-26873(20): xmlrpc now raises ResponseError on unsupported type
     tags instead of silently return incorrect result.

   - bpo-26711(21): Fixed the comparison of plistlib.Data with other
     types.

   - bpo-24114(22): Fix an uninitialized variable in ‘ctypes.util’.  The
     bug only occurs on SunOS when the ctypes implementation searches
     for the ‘crle’ program.  Patch by Xiang Zhang.  Tested on SunOS by
     Kees Bos.

   - bpo-26864(23): 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.

   - bpo-26634(24): recursive_repr() now sets __qualname__ of wrapper.
     Patch by Xiang Zhang.

   - bpo-26804(25): urllib.request will prefer lower_case proxy
     environment variables over UPPER_CASE or Mixed_Case ones.  Patch
     contributed by Hans-Peter Jansen.

   - bpo-26837(26): assertSequenceEqual() now correctly outputs
     non-stringified differing items (like bytes in the -b mode).  This
     affects assertListEqual() and assertTupleEqual().

   - bpo-26041(27): Remove "will be removed in Python 3.7" from
     deprecation messages of platform.dist() and
     platform.linux_distribution().  Patch by Kumaripaba Miyurusara
     Athukorala.

   - bpo-26822(28): itemgetter, attrgetter and methodcaller objects no
     longer silently ignore keyword arguments.

   - bpo-26733(29): Disassembling a class now disassembles class and
     static methods.  Patch by Xiang Zhang.

   - bpo-26801(30): Fix error handling in *note
     shutil.get_terminal_size(): b25, catch *note AttributeError: 4a1.
     instead of *note NameError: e40.  Patch written by Emanuel Barry.

   - bpo-24838(31): tarfile’s ustar and gnu formats now correctly
     calculate name and link field limits for multibyte character
     encodings like utf-8.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27164

   (2) https://bugs.python.org/issue24291

   (3) https://bugs.python.org/issue26809

   (4) https://bugs.python.org/issue26373

   (5) https://bugs.python.org/issue21776

   (6) https://bugs.python.org/issue27114

   (7) https://bugs.python.org/issue18383

   (8) https://bugs.python.org/issue27057

   (9) https://bugs.python.org/issue27014

   (10) https://bugs.python.org/issue14132

   (11) https://bugs.python.org/issue17214

   (12) https://bugs.python.org/issue26892

   (13) https://bugs.python.org/issue22274

   (14) https://bugs.python.org/issue26807

   (15) https://bugs.python.org/issue25745

   (16) https://bugs.python.org/issue26977

   (17) https://bugs.python.org/issue26881

   (18) https://bugs.python.org/issue23815

   (19) https://bugs.python.org/issue17765

   (20) https://bugs.python.org/issue26873

   (21) https://bugs.python.org/issue26711

   (22) https://bugs.python.org/issue24114

   (23) https://bugs.python.org/issue26864

   (24) https://bugs.python.org/issue26634

   (25) https://bugs.python.org/issue26804

   (26) https://bugs.python.org/issue26837

   (27) https://bugs.python.org/issue26041

   (28) https://bugs.python.org/issue26822

   (29) https://bugs.python.org/issue26733

   (30) https://bugs.python.org/issue26801

   (31) https://bugs.python.org/issue24838


File: python.info,  Node: 安全性<39>,  Next: 库<74>,  Prev: 库<73>,  Up: Python 3 5 2 rc1

1.19.74.6 安全性
................

   - bpo-26657(1): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26657


File: python.info,  Node: 库<74>,  Next: 安全性<40>,  Prev: 安全性<39>,  Up: Python 3 5 2 rc1

1.19.74.7 库
............

   - bpo-26717(1): Stop encoding Latin-1-ized WSGI paths with UTF-8.
     Patch by Anthony Sottile.

   - bpo-26735(2): Fix *note os.urandom(): 5cb. on Solaris 11.3 and
     newer when reading more than 1,024 bytes: call ‘getrandom()’
     multiple times with a limit of 1024 bytes per call.

   - bpo-16329(3): Add .webm to mimetypes.types_map.  Patch by Giampaolo
     Rodola’.

   - bpo-13952(4): Add .csv to mimetypes.types_map.  Patch by Geoff
     Wilson.

   - bpo-26709(5): Fixed Y2038 problem in loading binary PLists.

   - bpo-23735(6): Handle terminal resizing with Readline 6.3+ by
     installing our own SIGWINCH handler.  Patch by Eric Price.

   - bpo-26586(7): 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.

   - bpo-22854(8): Change BufferedReader.writable() and
     BufferedWriter.readable() to always return False.

   - bpo-25195(9): 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.

   - bpo-26644(10): Raise ValueError rather than SystemError when a
     negative length is passed to SSLSocket.recv() or read().

   - bpo-23804(11): Fix SSL recv(0) and read(0) methods to return zero
     bytes instead of up to 1024.

   - bpo-26616(12): Fixed a bug in datetime.astimezone() method.

   - bpo-21925(13): *note warnings.formatwarning(): 112d. now catches
     exceptions on ‘linecache.getline(...)’ to be able to log *note
     ResourceWarning: 5ca. emitted late during the Python shutdown
     process.

   - bpo-24266(14): Ctrl+C during Readline history search now cancels
     the search mode when compiled with Readline 7.

   - bpo-26560(15): Avoid potential ValueError in
     BaseHandler.start_response.  Initial patch by Peter Inglesby.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26717

   (2) https://bugs.python.org/issue26735

   (3) https://bugs.python.org/issue16329

   (4) https://bugs.python.org/issue13952

   (5) https://bugs.python.org/issue26709

   (6) https://bugs.python.org/issue23735

   (7) https://bugs.python.org/issue26586

   (8) https://bugs.python.org/issue22854

   (9) https://bugs.python.org/issue25195

   (10) https://bugs.python.org/issue26644

   (11) https://bugs.python.org/issue23804

   (12) https://bugs.python.org/issue26616

   (13) https://bugs.python.org/issue21925

   (14) https://bugs.python.org/issue24266

   (15) https://bugs.python.org/issue26560


File: python.info,  Node: 安全性<40>,  Next: 库<75>,  Prev: 库<74>,  Up: Python 3 5 2 rc1

1.19.74.8 安全性
................

   - bpo-26313(1): ssl.py _load_windows_store_certs fails if windows
     cert store is empty.  Patch by Baji.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26313


File: python.info,  Node: 库<75>,  Next: 安全性<41>,  Prev: 安全性<40>,  Up: Python 3 5 2 rc1

1.19.74.9 库
............

   - bpo-26569(1): Fix *note pyclbr.readmodule(): 129e. and *note
     pyclbr.readmodule_ex(): 129f. to support importing packages.

   - bpo-26499(2): Account for remaining Content-Length in
     HTTPResponse.readline() and read1().  Based on patch by Silent
     Ghost.  Also document that HTTPResponse now supports these methods.

   - bpo-25320(3): Handle sockets in directories unittest discovery is
     scanning.  Patch from Victor van den Elzen.

   - bpo-16181(4): cookiejar.http2time() now returns None if year is
     higher than datetime.MAXYEAR.

   - bpo-26513(5): Fixes platform module detection of Windows Server

   - bpo-23718(6): Fixed parsing time in week 0 before Jan 1.  Original
     patch by Tamás Bence Gedai.

   - bpo-20589(7): Invoking Path.owner() and Path.group() on Windows now
     raise NotImplementedError instead of ImportError.

   - bpo-26177(8): Fixed the keys() method for Canvas and Scrollbar
     widgets.

   - bpo-15068(9): Got rid of excessive buffering in the fileinput
     module.  The bufsize parameter is no longer used.

   - bpo-2202(10): Fix UnboundLocalError in
     AbstractDigestAuthHandler.get_algorithm_impls.  Initial patch by
     Mathieu Dupuy.

   - bpo-25718(11): Fixed pickling and copying the accumulate() iterator
     with total is None.

   - bpo-26475(12): Fixed debugging output for regular expressions with
     the (?x) flag.

   - bpo-26457(13): 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.

   - bpo-26385(14): Remove the file if the internal open() call in
     NamedTemporaryFile() fails.  Patch by Silent Ghost.

   - bpo-26402(15): 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.

   - bpo-25913(16): Leading ‘<~’ is optional now in base64.a85decode()
     with adobe=True.  Patch by Swati Jaiswal.

   - bpo-26186(17): Remove an invalid type check in
     importlib.util.LazyLoader.

   - bpo-26367(18): importlib.__import__() raises SystemError like
     builtins.__import__() when ‘level’ is specified but without an
     accompanying package specified.

   - bpo-26309(19): In the "socketserver" module, shut down the request
     (closing the connected socket) when verify_request() returns false.
     Patch by Aviv Palivoda.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26569

   (2) https://bugs.python.org/issue26499

   (3) https://bugs.python.org/issue25320

   (4) https://bugs.python.org/issue16181

   (5) https://bugs.python.org/issue26513

   (6) https://bugs.python.org/issue23718

   (7) https://bugs.python.org/issue20589

   (8) https://bugs.python.org/issue26177

   (9) https://bugs.python.org/issue15068

   (10) https://bugs.python.org/issue2202

   (11) https://bugs.python.org/issue25718

   (12) https://bugs.python.org/issue26475

   (13) https://bugs.python.org/issue26457

   (14) https://bugs.python.org/issue26385

   (15) https://bugs.python.org/issue26402

   (16) https://bugs.python.org/issue25913

   (17) https://bugs.python.org/issue26186

   (18) https://bugs.python.org/issue26367

   (19) https://bugs.python.org/issue26309


File: python.info,  Node: 安全性<41>,  Next: 库<76>,  Prev: 库<75>,  Up: Python 3 5 2 rc1

1.19.74.10 安全性
.................

   - bpo-25939(1): On Windows open the cert store readonly in
     ssl.enum_certificates.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25939


File: python.info,  Node: 库<76>,  Next: IDLE<46>,  Prev: 安全性<41>,  Up: Python 3 5 2 rc1

1.19.74.11 库
.............

   - bpo-25995(1): os.walk() no longer uses FDs proportional to the tree
     depth.

   - bpo-26117(2): The os.scandir() iterator now closes file descriptor
     not only when the iteration is finished, but when it was failed
     with error.

   - bpo-25911(3): Restored support of bytes paths in os.walk() on
     Windows.

   - bpo-26045(4): Add UTF-8 suggestion to error message when posting a
     non-Latin-1 string with http.client.

   - bpo-12923(5): Reset FancyURLopener’s redirect counter even if there
     is an exception.  Based on patches by Brian Brazil and Daniel
     Rocco.

   - bpo-25945(6): 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.

   - bpo-26202(7): copy.deepcopy() now correctly copies range() objects
     with non-atomic attributes.

   - bpo-23076(8): Path.glob() now raises a ValueError if it’s called
     with an invalid pattern.  Patch by Thomas Nyberg.

   - bpo-19883(9): Fixed possible integer overflows in zipimport.

   - bpo-26227(10): 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.

   - bpo-26147(11): xmlrpc now works with strings not encodable with
     used non-UTF-8 encoding.

   - bpo-25935(12): Garbage collector now breaks reference loops with
     OrderedDict.

   - bpo-16620(13): Fixed AttributeError in msilib.Directory.glob().

   - bpo-26013(14): Added compatibility with broken protocol 2 pickles
     created in old Python 3 versions (3.4.3 and lower).

   - bpo-25850(15): Use cross-compilation by default for 64-bit Windows.

   - bpo-17633(16): Improve zipimport’s support for namespace packages.

   - bpo-24705(17): Fix sysconfig._parse_makefile not expanding ${} vars
     appearing before $() vars.

   - bpo-22138(18): Fix mock.patch behavior when patching descriptors.
     Restore original values after patching.  Patch contributed by Sean
     McCully.

   - bpo-25672(19): In the ssl module, enable the
     SSL_MODE_RELEASE_BUFFERS mode option if it is safe to do so.

   - bpo-26012(20): Don’t traverse into symlinks for ‘**’ pattern in
     pathlib.Path.[r]glob().

   - bpo-24120(21): Ignore PermissionError when traversing a tree with
     pathlib.Path.[r]glob().  Patch by Ulrich Petri.

   - bpo-25447(22): fileinput now uses sys.stdin as-is if it does not
     have a buffer attribute (restores backward compatibility).

   - bpo-25447(23): Copying the lru_cache() wrapper object now always
     works, independently from the type of the wrapped object (by
     returning the original object unchanged).

   - bpo-24103(24): Fixed possible use after free in
     ElementTree.XMLPullParser.

   - bpo-25860(25): os.fwalk() no longer skips remaining directories
     when error occurs.  Original patch by Samson Lee.

   - bpo-25914(26): Fixed and simplified OrderedDict.__sizeof__.

   - bpo-25902(27): Fixed various refcount issues in ElementTree
     iteration.

   - bpo-25717(28): 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.

   - bpo-24903(29): 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.

   - bpo-25764(30): In the subprocess module, preserve any exception
     caused by fork() failure when preexec_fn is used.

   - bpo-6478(31): _strptime’s regexp cache now is reset after changing
     timezone with time.tzset().

   - bpo-14285(32): 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.

   - bpo-19771(33): 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 ‘*.pyc’ file).

   - bpo-25177(34): 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.

   - bpo-25718(35): Fixed copying object with state with boolean value
     is false.

   - bpo-10131(36): Fixed deep copying of minidom documents.  Based on
     patch by Marian Ganisin.

   - bpo-25725(37): Fixed a reference leak in pickle.loads() when
     unpickling invalid data including tuple instructions.

   - bpo-25663(38): In the Readline completer, avoid listing duplicate
     global names, and search the global namespace before searching
     builtins.

   - bpo-25688(39): Fixed file leak in ElementTree.iterparse() raising
     an error.

   - bpo-23914(40): Fixed SystemError raised by unpickler on broken
     pickle data.

   - bpo-25691(41): Fixed crash on deleting ElementTree.Element
     attributes.

   - bpo-25624(42): ZipFile now always writes a ZIP_STORED header for
     directory entries.  Patch by Dingyuan Wang.

   - Skip getaddrinfo if host is already resolved.  Patch by A. Jesse
     Jiryu Davis.

   - bpo-26050(43): Add asyncio.StreamReader.readuntil() method.  Patch
     by Марк Коренберг.

   - bpo-25924(44): Avoid unnecessary serialization of getaddrinfo(3)
     calls on OS X versions 10.5 or higher.  Original patch by A. Jesse
     Jiryu Davis.

   - bpo-26406(45): Avoid unnecessary serialization of getaddrinfo(3)
     calls on current versions of OpenBSD and NetBSD. Patch by A. Jesse
     Jiryu Davis.

   - bpo-26848(46): Fix asyncio/subprocess.communicate() to handle empty
     input.  Patch by Jack O’Connor.

   - bpo-27040(47): Add loop.get_exception_handler method

   - bpo-27041(48): asyncio: Add loop.create_future method

   - bpo-27223(49): asyncio: Fix _read_ready and _write_ready to respect
     _conn_lost.  Patch by Łukasz Langa.

   - bpo-22970(50): asyncio: Fix inconsistency cancelling
     Condition.wait.  Patch by David Coles.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25995

   (2) https://bugs.python.org/issue26117

   (3) https://bugs.python.org/issue25911

   (4) https://bugs.python.org/issue26045

   (5) https://bugs.python.org/issue12923

   (6) https://bugs.python.org/issue25945

   (7) https://bugs.python.org/issue26202

   (8) https://bugs.python.org/issue23076

   (9) https://bugs.python.org/issue19883

   (10) https://bugs.python.org/issue26227

   (11) https://bugs.python.org/issue26147

   (12) https://bugs.python.org/issue25935

   (13) https://bugs.python.org/issue16620

   (14) https://bugs.python.org/issue26013

   (15) https://bugs.python.org/issue25850

   (16) https://bugs.python.org/issue17633

   (17) https://bugs.python.org/issue24705

   (18) https://bugs.python.org/issue22138

   (19) https://bugs.python.org/issue25672

   (20) https://bugs.python.org/issue26012

   (21) https://bugs.python.org/issue24120

   (22) https://bugs.python.org/issue25447

   (23) https://bugs.python.org/issue25447

   (24) https://bugs.python.org/issue24103

   (25) https://bugs.python.org/issue25860

   (26) https://bugs.python.org/issue25914

   (27) https://bugs.python.org/issue25902

   (28) https://bugs.python.org/issue25717

   (29) https://bugs.python.org/issue24903

   (30) https://bugs.python.org/issue25764

   (31) https://bugs.python.org/issue6478

   (32) https://bugs.python.org/issue14285

   (33) https://bugs.python.org/issue19771

   (34) https://bugs.python.org/issue25177

   (35) https://bugs.python.org/issue25718

   (36) https://bugs.python.org/issue10131

   (37) https://bugs.python.org/issue25725

   (38) https://bugs.python.org/issue25663

   (39) https://bugs.python.org/issue25688

   (40) https://bugs.python.org/issue23914

   (41) https://bugs.python.org/issue25691

   (42) https://bugs.python.org/issue25624

   (43) https://bugs.python.org/issue26050

   (44) https://bugs.python.org/issue25924

   (45) https://bugs.python.org/issue26406

   (46) https://bugs.python.org/issue26848

   (47) https://bugs.python.org/issue27040

   (48) https://bugs.python.org/issue27041

   (49) https://bugs.python.org/issue27223

   (50) https://bugs.python.org/issue22970


File: python.info,  Node: IDLE<46>,  Next: 文档<49>,  Prev: 库<76>,  Up: Python 3 5 2 rc1

1.19.74.12 IDLE
...............

   - bpo-5124(1): 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.

   - bpo-24759(2): Make clear in idlelib.idle_test.__init__ that the
     directory is a private implementation of test.test_idle and tool
     for maintainers.

   - bpo-27196(3): 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

   - bpo-20567(4): Revise idle_test/README.txt with advice about
     avoiding tk warning messages from tests.  Apply advice to several
     IDLE tests.

   - bpo-27117(5): Make colorizer htest and turtledemo work with dark
     themes.  Move code for configuring text widget colors to a new
     function.

   - bpo-26673(6): When tk reports font size as 0, change to size 10.
     Such fonts on Linux prevented the configuration dialog from
     opening.

   - bpo-21939(7): Add test for IDLE’s percolator.  Original patch by
     Saimadhav Heblikar.

   - bpo-21676(8): Add test for IDLE’s replace dialog.  Original patch
     by Saimadhav Heblikar.

   - bpo-18410(9): Add test for IDLE’s search dialog.  Original patch by
     Westley Martínez.

   - bpo-21703(10): Add test for IDLE’s undo delegator.  Original patch
     by Saimadhav Heblikar .

   - bpo-27044(11): Add ConfigDialog.remove_var_callbacks to stop memory
     leaks.

   - bpo-23977(12): Add more asserts to test_delegator.

   - bpo-20640(13): Add tests for idlelib.configHelpSourceEdit.  Patch
     by Saimadhav Heblikar.

   - In the ’IDLE-console differences’ section of the IDLE doc, clarify
     how running with IDLE affects sys.modules and the standard streams.

   - bpo-25507(14): fix incorrect change in IOBinding that prevented
     printing.  Augment IOBinding htest to include all major IOBinding
     functions.

   - bpo-25905(15): 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’.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5124

   (2) https://bugs.python.org/issue24759

   (3) https://bugs.python.org/issue27196

   (4) https://bugs.python.org/issue20567

   (5) https://bugs.python.org/issue27117

   (6) https://bugs.python.org/issue26673

   (7) https://bugs.python.org/issue21939

   (8) https://bugs.python.org/issue21676

   (9) https://bugs.python.org/issue18410

   (10) https://bugs.python.org/issue21703

   (11) https://bugs.python.org/issue27044

   (12) https://bugs.python.org/issue23977

   (13) https://bugs.python.org/issue20640

   (14) https://bugs.python.org/issue25507

   (15) https://bugs.python.org/issue25905


File: python.info,  Node: 文档<49>,  Next: 测试<51>,  Prev: IDLE<46>,  Up: Python 3 5 2 rc1

1.19.74.13 文档
...............

   - bpo-19489(1): Moved the search box from the sidebar to the header
     and footer of each page.  Patch by Ammar Askar.

   - bpo-24136(2): Document the new PEP 448(3) unpacking syntax of 3.5.

   - bpo-26736(4): Used HTTPS for external links in the documentation if
     possible.

   - bpo-6953(5): Rework the Readline module documentation to group
     related functions together, and add more details such as what
     underlying Readline functions and variables are accessed.

   - bpo-23606(6): Adds note to ctypes documentation regarding
     cdll.msvcrt.

   - bpo-25500(7): Fix documentation to not claim that __import__ is
     searched for in the global scope.

   - bpo-26014(8): 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

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue19489

   (2) https://bugs.python.org/issue24136

   (3) https://www.python.org/dev/peps/pep-0448

   (4) https://bugs.python.org/issue26736

   (5) https://bugs.python.org/issue6953

   (6) https://bugs.python.org/issue23606

   (7) https://bugs.python.org/issue25500

   (8) https://bugs.python.org/issue26014


File: python.info,  Node: 测试<51>,  Next: 构建<53>,  Prev: 文档<49>,  Up: Python 3 5 2 rc1

1.19.74.14 测试
...............

   - bpo-21916(1): Added tests for the turtle module.  Patch by ingrid,
     Gregory Loyse and Jelle Zijlstra.

   - bpo-26523(2): The multiprocessing thread pool
     (multiprocessing.dummy.Pool) was untested.

   - bpo-26015(3): Added new tests for pickling iterators of mutable
     sequences.

   - bpo-26325(4): Added test.support.check_no_resource_warning() to
     check that no ResourceWarning is emitted.

   - bpo-25940(5): Changed test_ssl to use self-signed.pythontest.net.
     This avoids relying on svn.python.org, which recently changed root
     certificate.

   - bpo-25616(6): Tests for OrderedDict are extracted from
     test_collections into separate file test_ordered_dict.

   - bpo-26583(7): Skip test_timestamp_overflow in test_import if
     bytecode files cannot be written.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21916

   (2) https://bugs.python.org/issue26523

   (3) https://bugs.python.org/issue26015

   (4) https://bugs.python.org/issue26325

   (5) https://bugs.python.org/issue25940

   (6) https://bugs.python.org/issue25616

   (7) https://bugs.python.org/issue26583


File: python.info,  Node: 构建<53>,  Next: Windows<49>,  Prev: 测试<51>,  Up: Python 3 5 2 rc1

1.19.74.15 构建
...............

   - bpo-26884(1): Fix linking extension modules for cross builds.
     Patch by Xavier de Gaye.

   - bpo-22359(2): 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.

   - bpo-27229(3): Fix the cross-compiling pgen rule for in-tree builds.
     Patch by Xavier de Gaye.

   - bpo-21668(4): Link audioop, _datetime, _ctypes_test modules to
     libm, except on Mac OS X. Patch written by Xavier de Gaye.

   - bpo-25702(5): 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.

   - bpo-26624(6): Adds validation of ucrtbase[d].dll version with
     warning for old versions.

   - bpo-17603(7): Avoid error about nonexistent fileblocks.o file by
     using a lower-level check for st_blocks in struct stat.

   - bpo-26079(8): Fixing the build output folder for tix-8.4.3.6.
     Patch by Bjoern Thiel.

   - bpo-26465(9): 更新Windows 构建OpenSSL 1.0.2g.

   - bpo-24421(10): Compile Modules/_math.c once, before building
     extensions.  Previously it could fail to compile properly if the
     math and cmath builds were concurrent.

   - bpo-25348(11): Added ‘--pgo’ and ‘--pgo-job’ arguments to
     ‘PCbuild\build.bat’ for building with Profile-Guided Optimization.
     The old ‘PCbuild\build_pgo.bat’ script is now deprecated, and
     simply calls ‘PCbuild\build.bat --pgo %*’.

   - bpo-25827(12): Add support for building with ICC to ‘configure’,
     including a new ‘--with-icc’ flag.

   - bpo-25696(13): Fix installation of Python on UNIX with make -j9.

   - bpo-26930(14): 更新OS X 10.5+（仅32位）安装程序以构建并链接OpenSSL
     1.0.2h。

   - bpo-26268(15): 更新Windows 构建OpenSSL 1.0.2f.

   - bpo-25136(16): Support Apple Xcode 7’s new textual SDK stub
     libraries.

   - bpo-24324(17): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26884

   (2) https://bugs.python.org/issue22359

   (3) https://bugs.python.org/issue27229

   (4) https://bugs.python.org/issue21668

   (5) https://bugs.python.org/issue25702

   (6) https://bugs.python.org/issue26624

   (7) https://bugs.python.org/issue17603

   (8) https://bugs.python.org/issue26079

   (9) https://bugs.python.org/issue26465

   (10) https://bugs.python.org/issue24421

   (11) https://bugs.python.org/issue25348

   (12) https://bugs.python.org/issue25827

   (13) https://bugs.python.org/issue25696

   (14) https://bugs.python.org/issue26930

   (15) https://bugs.python.org/issue26268

   (16) https://bugs.python.org/issue25136

   (17) https://bugs.python.org/issue24324


File: python.info,  Node: Windows<49>,  Next: 工具/示例<30>,  Prev: 构建<53>,  Up: Python 3 5 2 rc1

1.19.74.16 Windows
..................

   - bpo-27053(1): Updates make_zip.py to correctly generate library ZIP
     file.

   - bpo-26268(2): 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).

   - bpo-26071(3): bdist_wininst created binaries fail to start and find
     32bit Python

   - bpo-26073(4): Update the list of magic numbers in launcher

   - bpo-26065(5): Excludes venv from library when generating embeddable
     distro.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue27053

   (2) https://bugs.python.org/issue26268

   (3) https://bugs.python.org/issue26071

   (4) https://bugs.python.org/issue26073

   (5) https://bugs.python.org/issue26065


File: python.info,  Node: 工具/示例<30>,  Next: Windows<50>,  Prev: Windows<49>,  Up: Python 3 5 2 rc1

1.19.74.17 工具/示例
....................

   - bpo-26799(1): 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.

   - bpo-26271(2): Fix the Freeze tool to properly use flags passed
     through configure.  Patch by Daniel Shaulov.

   - bpo-26489(3): Add dictionary unpacking support to
     Tools/parser/unparse.py.  Patch by Guo Ci Teo.

   - bpo-26316(4): Fix variable name typo in Argument Clinic.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue26799

   (2) https://bugs.python.org/issue26271

   (3) https://bugs.python.org/issue26489

   (4) https://bugs.python.org/issue26316


File: python.info,  Node: Windows<50>,  Prev: 工具/示例<30>,  Up: Python 3 5 2 rc1

1.19.74.18 Windows
..................

   - bpo-17500(1): Remove unused and outdated icons.  (See also:
     ‘https://github.com/python/pythondotorg/issues/945’)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue17500


File: python.info,  Node: Python 3 5 1 正式版,  Next: Python 3 5 1 rc1,  Prev: Python 3 5 2 rc1,  Up: Changelog（更動日誌）

1.19.75 Python 3.5.1 正式版
---------------------------

`发布日期: 2015-12-06'

* Menu:

* 核心与内置函数: 核心与内置函数<61>.
* Windows: Windows<51>.


File: python.info,  Node: 核心与内置函数<61>,  Next: Windows<51>,  Up: Python 3 5 1 正式版

1.19.75.1 核心与内置函数
........................

   - bpo-25709(1): Fixed problem with in-place string concatenation and
     utf-8 cache.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25709


File: python.info,  Node: Windows<51>,  Prev: 核心与内置函数<61>,  Up: Python 3 5 1 正式版

1.19.75.2 Windows
.................

   - bpo-25715(1): Python 3.5.1 installer shows wrong upgrade path and
     incorrect logic for launcher detection.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25715


File: python.info,  Node: Python 3 5 1 rc1,  Next: Python 3 5 0 正式版,  Prev: Python 3 5 1 正式版,  Up: Changelog（更動日誌）

1.19.76 Python 3.5.1 rc1
------------------------

`发布日期: 2015-11-22'

* Menu:

* 核心与内置函数: 核心与内置函数<62>.
* 库: 库<77>.
* IDLE: IDLE<47>.
* 文档: 文档<50>.
* 测试: 测试<52>.
* 构建: 构建<54>.
* Windows: Windows<52>.
* 工具/示例: 工具/示例<31>.


File: python.info,  Node: 核心与内置函数<62>,  Next: 库<77>,  Up: Python 3 5 1 rc1

1.19.76.1 核心与内置函数
........................

   - bpo-25630(1): Fix a possible segfault during argument parsing in
     functions that accept filesystem paths.

   - bpo-23564(2): 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.

   - bpo-25388(3): Fixed tokenizer crash when processing undecodable
     source code with a null byte.

   - bpo-25462(4): The hash of the key now is calculated only once in
     most operations in C implementation of OrderedDict.

   - bpo-22995(5): Default implementation of __reduce__ and
     __reduce_ex__ now rejects builtin types with not defined __new__.

   - bpo-25555(6): Fix parser and AST: fill lineno and col_offset of
     "arg" node when compiling AST from Python objects.

   - bpo-24802(7): 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.

   - bpo-24726(8): Fixed a crash and leaking NULL in repr() of
     OrderedDict that was mutated by direct calls of dict methods.

   - bpo-25449(9): Iterating OrderedDict with keys with unstable hash
     now raises KeyError in C implementations as well as in Python
     implementation.

   - bpo-25395(10): Fixed crash when highly nested OrderedDict
     structures were garbage collected.

   - bpo-25274(11): 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.

   - bpo-24402(12): Fix input() to prompt to the redirected stdout when
     sys.stdout.fileno() fails.

   - bpo-24806(13): Prevent builtin types that are not allowed to be
     subclassed from being subclassed through multiple inheritance.

   - bpo-24848(14): Fixed a number of bugs in UTF-7 decoding of
     misformed data.

   - bpo-25280(15): Import trace messages emitted in verbose (-v) mode
     are no longer formatted twice.

   - bpo-25003(16): 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.

   - bpo-25182(17): The stdprinter (used as sys.stderr before the io
     module is imported at startup) now uses the backslashreplace error
     handler.

   - bpo-25131(18): Make the line number and column offset of set/dict
     literals and comprehensions correspond to the opening brace.

   - bpo-25150(19): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25630

   (2) https://bugs.python.org/issue23564

   (3) https://bugs.python.org/issue25388

   (4) https://bugs.python.org/issue25462

   (5) https://bugs.python.org/issue22995

   (6) https://bugs.python.org/issue25555

   (7) https://bugs.python.org/issue24802

   (8) https://bugs.python.org/issue24726

   (9) https://bugs.python.org/issue25449

   (10) https://bugs.python.org/issue25395

   (11) https://bugs.python.org/issue25274

   (12) https://bugs.python.org/issue24402

   (13) https://bugs.python.org/issue24806

   (14) https://bugs.python.org/issue24848

   (15) https://bugs.python.org/issue25280

   (16) https://bugs.python.org/issue25003

   (17) https://bugs.python.org/issue25182

   (18) https://bugs.python.org/issue25131

   (19) https://bugs.python.org/issue25150


File: python.info,  Node: 库<77>,  Next: IDLE<47>,  Prev: 核心与内置函数<62>,  Up: Python 3 5 1 rc1

1.19.76.2 库
............

   - bpo-25626(1): 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.

   - bpo-25583(2): Avoid incorrect errors raised by
     os.makedirs(exist_ok=True) when the OS gives priority to errors
     such as EACCES over EEXIST.

   - bpo-25593(3): Change semantics of EventLoop.stop() in asyncio.

   - bpo-6973(4): 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.

   - bpo-25590(5): In the Readline completer, only call getattr() once
     per attribute.

   - bpo-25498(6): 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.

   - bpo-25584(7): Added "escape" to the __all__ list in the glob
     module.

   - bpo-25584(8): Fixed recursive glob() with patterns starting with
     ‘**’.

   - bpo-25446(9): Fix regression in smtplib’s AUTH LOGIN support.

   - bpo-18010(10): Fix the pydoc web server’s module search function to
     handle exceptions from importing packages.

   - bpo-25554(11): Got rid of circular references in regular expression
     parsing.

   - bpo-25510(12): fileinput.FileInput.readline() now returns b’’
     instead of ’’ at the end if the FileInput was opened with binary
     mode.  Patch by Ryosuke Ito.

   - bpo-25503(13): Fixed inspect.getdoc() for inherited docstrings of
     properties.  Original patch by John Mark Vandenberg.

   - bpo-25515(14): Always use os.urandom as a source of randomness in
     uuid.uuid4.

   - bpo-21827(15): Fixed textwrap.dedent() for the case when largest
     common whitespace is a substring of smallest leading whitespace.
     Based on patch by Robert Li.

   - bpo-25447(16): The lru_cache() wrapper objects now can be copied
     and pickled (by returning the original object unchanged).

   - bpo-25390(17): typing: Don’t crash on Union[str, Pattern].

   - bpo-25441(18): asyncio: Raise error from drain() when socket is
     closed.

   - bpo-25410(19): Cleaned up and fixed minor bugs in C implementation
     of OrderedDict.

   - bpo-25411(20): Improved Unicode support in SMTPHandler through
     better use of the email package.  Thanks to user simon04 for the
     patch.

   - bpo-25407(21): Remove mentions of the formatter module being
     removed in Python 3.6.

   - bpo-25406(22): 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.

   - bpo-25364(23): zipfile now works in threads disabled builds.

   - bpo-25328(24): smtpd’s SMTPChannel now correctly raises a
     ValueError if both decode_data and enable_SMTPUTF8 are set to true.

   - bpo-25316(25): distutils raises OSError instead of
     DistutilsPlatformError when MSVC is not installed.

   - bpo-25380(26): Fixed protocol for the STACK_GLOBAL opcode in
     pickletools.opcodes.

   - bpo-23972(27): 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.

   - bpo-25304(28): 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.

   - bpo-25232(29): Fix CGIRequestHandler to split the query from the
     URL at the first question mark (?)  rather than the last.  Patch
     from Xiang Zhang.

   - bpo-24657(30): Prevent CGIRequestHandler from collapsing slashes in
     the query part of the URL as if it were a path.  Patch from Xiang
     Zhang.

   - bpo-24483(31): C implementation of functools.lru_cache() now
     calculates key’s hash only once.

   - bpo-22958(32): Constructor and update method of
     weakref.WeakValueDictionary now accept the self and the dict
     keyword arguments.

   - bpo-22609(33): Constructor of collections.UserDict now accepts the
     self keyword argument.

   - bpo-25111(34): Fixed comparison of traceback.FrameSummary.

   - bpo-25262(35): 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.

   - bpo-25034(36): Fix string.Formatter problem with auto-numbering and
     nested format_specs.  Patch by Anthon van der Neut.

   - bpo-25233(37): Rewrite the guts of asyncio.Queue and
     asyncio.Semaphore to be more understandable and correct.

   - bpo-25203(38): Failed readline.set_completer_delims() no longer
     left the module in inconsistent state.

   - bpo-23600(39): Default implementation of tzinfo.fromutc() was
     returning wrong results in some cases.

   - bpo-23329(40): Allow the ssl module to be built with older versions
     of LibreSSL.

   - Prevent overflow in _Unpickler_Read.

   - bpo-25047(41): 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.

   - bpo-25135(42): Make deque_clear() safer by emptying the deque
     before clearing.  This helps avoid possible reentrancy issues.

   - bpo-19143(43): platform module now reads Windows version from
     kernel32.dll to avoid compatibility shims.

   - bpo-25092(44): Fix datetime.strftime() failure when errno was
     already set to EINVAL.

   - bpo-23517(45): 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.

   - bpo-25155(46): 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.

   - bpo-25108(47): Omitted internal frames in traceback functions
     print_stack(), format_stack(), and extract_stack() called without
     arguments.

   - bpo-25118(48): Fix a regression of Python 3.5.0 in os.waitpid() on
     Windows.

   - bpo-24684(49): 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.

   - bpo-25060(50): Correctly compute stack usage of the BUILD_MAP
     opcode.

   - bpo-24857(51): Comparing call_args to a long sequence now correctly
     returns a boolean result instead of raising an exception.  Patch by
     A Kaptur.

   - bpo-23144(52): Make sure that HTMLParser.feed() returns all the
     data, even when convert_charrefs is True.

   - bpo-24982(53): shutil.make_archive() with the "zip" format now adds
     entries for directories (including empty directories) in ZIP file.

   - bpo-25019(54): Fixed a crash caused by setting non-string key of
     expat parser.  Based on patch by John Leitch.

   - bpo-16180(55): Exit pdb if file has syntax error, instead of
     trapping user in an infinite loop.  Patch by Xavier de Gaye.

   - bpo-24891(56): 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.

   - bpo-24992(57): Fix error handling and a race condition (related to
     garbage collection) in collections.OrderedDict constructor.

   - bpo-24881(58): Fixed setting binary mode in Python implementation
     of FileIO on Windows and Cygwin.  Patch from Akira Li.

   - bpo-25578(59): Fix (another) memory leak in SSLSocket.getpeercer().

   - bpo-25530(60): Disable the vulnerable SSLv3 protocol by default
     when creating ssl.SSLContext.

   - bpo-25569(61): Fix memory leak in SSLSocket.getpeercert().

   - bpo-25471(62): Sockets returned from accept() shouldn’t appear to
     be nonblocking.

   - bpo-25319(63): When threading.Event is reinitialized, the
     underlying condition should use a regular lock rather than a
     recursive lock.

   - bpo-21112(64): Fix regression in unittest.expectedFailure on
     subclasses.  Patch from Berker Peksag.

   - bpo-24764(65): cgi.FieldStorage.read_multi() now ignores the
     Content-Length header in part headers.  Patch written by Peter
     Landry and reviewed by Pierre Quentel.

   - bpo-24913(66): Fix overrun error in deque.index().  Found by John
     Leitch and Bryce Darling.

   - bpo-24774(67): Fix docstring in http.server.test.  Patch from
     Chiu-Hsiang Hsu.

   - bpo-21159(68): Improve message in
     configparser.InterpolationMissingOptionError.  Patch from Łukasz
     Langa.

   - bpo-20362(69): Honour TestCase.longMessage correctly in
     assertRegex.  Patch from Ilia Kurenkov.

   - bpo-23572(70): Fixed functools.singledispatch on classes with falsy
     metaclasses.  Patch by Ethan Furman.

   - asyncio: ensure_future() now accepts awaitable objects.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25626

   (2) https://bugs.python.org/issue25583

   (3) https://bugs.python.org/issue25593

   (4) https://bugs.python.org/issue6973

   (5) https://bugs.python.org/issue25590

   (6) https://bugs.python.org/issue25498

   (7) https://bugs.python.org/issue25584

   (8) https://bugs.python.org/issue25584

   (9) https://bugs.python.org/issue25446

   (10) https://bugs.python.org/issue18010

   (11) https://bugs.python.org/issue25554

   (12) https://bugs.python.org/issue25510

   (13) https://bugs.python.org/issue25503

   (14) https://bugs.python.org/issue25515

   (15) https://bugs.python.org/issue21827

   (16) https://bugs.python.org/issue25447

   (17) https://bugs.python.org/issue25390

   (18) https://bugs.python.org/issue25441

   (19) https://bugs.python.org/issue25410

   (20) https://bugs.python.org/issue25411

   (21) https://bugs.python.org/issue25407

   (22) https://bugs.python.org/issue25406

   (23) https://bugs.python.org/issue25364

   (24) https://bugs.python.org/issue25328

   (25) https://bugs.python.org/issue25316

   (26) https://bugs.python.org/issue25380

   (27) https://bugs.python.org/issue23972

   (28) https://bugs.python.org/issue25304

   (29) https://bugs.python.org/issue25232

   (30) https://bugs.python.org/issue24657

   (31) https://bugs.python.org/issue24483

   (32) https://bugs.python.org/issue22958

   (33) https://bugs.python.org/issue22609

   (34) https://bugs.python.org/issue25111

   (35) https://bugs.python.org/issue25262

   (36) https://bugs.python.org/issue25034

   (37) https://bugs.python.org/issue25233

   (38) https://bugs.python.org/issue25203

   (39) https://bugs.python.org/issue23600

   (40) https://bugs.python.org/issue23329

   (41) https://bugs.python.org/issue25047

   (42) https://bugs.python.org/issue25135

   (43) https://bugs.python.org/issue19143

   (44) https://bugs.python.org/issue25092

   (45) https://bugs.python.org/issue23517

   (46) https://bugs.python.org/issue25155

   (47) https://bugs.python.org/issue25108

   (48) https://bugs.python.org/issue25118

   (49) https://bugs.python.org/issue24684

   (50) https://bugs.python.org/issue25060

   (51) https://bugs.python.org/issue24857

   (52) https://bugs.python.org/issue23144

   (53) https://bugs.python.org/issue24982

   (54) https://bugs.python.org/issue25019

   (55) https://bugs.python.org/issue16180

   (56) https://bugs.python.org/issue24891

   (57) https://bugs.python.org/issue24992

   (58) https://bugs.python.org/issue24881

   (59) https://bugs.python.org/issue25578

   (60) https://bugs.python.org/issue25530

   (61) https://bugs.python.org/issue25569

   (62) https://bugs.python.org/issue25471

   (63) https://bugs.python.org/issue25319

   (64) https://bugs.python.org/issue21112

   (65) https://bugs.python.org/issue24764

   (66) https://bugs.python.org/issue24913

   (67) https://bugs.python.org/issue24774

   (68) https://bugs.python.org/issue21159

   (69) https://bugs.python.org/issue20362

   (70) https://bugs.python.org/issue23572


File: python.info,  Node: IDLE<47>,  Next: 文档<50>,  Prev: 库<77>,  Up: Python 3 5 1 rc1

1.19.76.3 IDLE
..............

   - bpo-15348(1): 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.

   - bpo-24455(2): 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.

   - 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.

   - bpo-24750(3): Improve the appearance of the IDLE editor window
     status bar.  Patch by Mark Roseman.

   - bpo-25313(4): 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.

   - bpo-24782(5): 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.

   - bpo-22726(6): Re-activate the config dialog help button with some
     content about the other buttons and the new IDLE Dark theme.

   - bpo-24820(7): 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.

   - bpo-25224(8): 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’.

   - bpo-24820(9): Users can now set breakpoint colors in Settings ->
     Custom Highlighting.  Original patch by Mark Roseman.

   - bpo-24972(10): 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.

   - bpo-24570(11): Idle: make calltip and completion boxes appear on
     Macs affected by a tk regression.  Initial patch by Mark Roseman.

   - bpo-24988(12): Idle ScrolledList context menus (used in debugger)
     now work on Mac Aqua.  Patch by Mark Roseman.

   - bpo-24801(13): Make right-click for context menu work on Mac Aqua.
     Patch by Mark Roseman.

   - bpo-25173(14): Associate tkinter messageboxes with a specific
     widget.  For Mac OSX, make them a ’sheet’.  Patch by Mark Roseman.

   - bpo-25198(15): 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.

   - bpo-25225(16): Condense and rewrite Idle doc section on text
     colors.

   - bpo-21995(17): Explain some differences between IDLE and console
     Python.

   - bpo-22820(18): Explain need for `print' when running file from Idle
     editor.

   - bpo-25224(19): Doc: augment Idle feature list and no-subprocess
     section.

   - bpo-25219(20): Update doc for Idle command line options.  Some were
     missing and notes were not correct.

   - bpo-24861(21): Most of idlelib is private and subject to change.
     Use idleib.idle.* to start Idle.  See idlelib.__init__.__doc__.

   - bpo-25199(22): Idle: add synchronization comments for future
     maintainers.

   - bpo-16893(23): 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.

   - bpo-24199(24): Deprecate unused idlelib.idlever with possible
     removal in 3.6.

   - bpo-24790(25): Remove extraneous code (which also create 2 & 3
     conflicts).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15348

   (2) https://bugs.python.org/issue24455

   (3) https://bugs.python.org/issue24750

   (4) https://bugs.python.org/issue25313

   (5) https://bugs.python.org/issue24782

   (6) https://bugs.python.org/issue22726

   (7) https://bugs.python.org/issue24820

   (8) https://bugs.python.org/issue25224

   (9) https://bugs.python.org/issue24820

   (10) https://bugs.python.org/issue24972

   (11) https://bugs.python.org/issue24570

   (12) https://bugs.python.org/issue24988

   (13) https://bugs.python.org/issue24801

   (14) https://bugs.python.org/issue25173

   (15) https://bugs.python.org/issue25198

   (16) https://bugs.python.org/issue25225

   (17) https://bugs.python.org/issue21995

   (18) https://bugs.python.org/issue22820

   (19) https://bugs.python.org/issue25224

   (20) https://bugs.python.org/issue25219

   (21) https://bugs.python.org/issue24861

   (22) https://bugs.python.org/issue25199

   (23) https://bugs.python.org/issue16893

   (24) https://bugs.python.org/issue24199

   (25) https://bugs.python.org/issue24790


File: python.info,  Node: 文档<50>,  Next: 测试<52>,  Prev: IDLE<47>,  Up: Python 3 5 1 rc1

1.19.76.4 文档
..............

   - bpo-22558(1): Add remaining doc links to source code for
     Python-coded modules.  Patch by Yoni Lavi.

   - bpo-12067(2): 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.

   - bpo-24952(3): Clarify the default size argument of stack_size() in
     the "threading" and "_thread" modules.  Patch from Mattip.

   - bpo-23725(4): Overhaul tempfile docs.  Note deprecated status of
     mktemp.  Patch from Zbigniew Jędrzejewski-Szmek.

   - bpo-24808(5): Update the types of some PyTypeObject fields.  Patch
     by Joseph Weston.

   - bpo-22812(6): Fix unittest discovery examples.  Patch from Pam
     McA’Nulty.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22558

   (2) https://bugs.python.org/issue12067

   (3) https://bugs.python.org/issue24952

   (4) https://bugs.python.org/issue23725

   (5) https://bugs.python.org/issue24808

   (6) https://bugs.python.org/issue22812


File: python.info,  Node: 测试<52>,  Next: 构建<54>,  Prev: 文档<50>,  Up: Python 3 5 1 rc1

1.19.76.5 测试
..............

   - bpo-25449(1): Added tests for OrderedDict subclasses.

   - bpo-25099(2): Make test_compileall not fail when an entry on
     sys.path cannot be written to (commonly seen in administrative
     installs on Windows).

   - bpo-23919(3): Prevents assert dialogs appearing in the test suite.

   - ‘PCbuild\rt.bat’ now accepts an unlimited number of arguments to
     pass along to regrtest.py.  Previously there was a limit of 9.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25449

   (2) https://bugs.python.org/issue25099

   (3) https://bugs.python.org/issue23919


File: python.info,  Node: 构建<54>,  Next: Windows<52>,  Prev: 测试<52>,  Up: Python 3 5 1 rc1

1.19.76.6 构建
..............

   - bpo-24915(1): Add LLVM support for PGO builds and use the test
     suite to generate the profile data.  Initial patch by Alecsandru
     Patrascu of Intel.

   - bpo-24910(2): Windows MSIs now have unique display names.

   - bpo-24986(3): It is now possible to build Python on Windows without
     errors when external libraries are not available.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24915

   (2) https://bugs.python.org/issue24910

   (3) https://bugs.python.org/issue24986


File: python.info,  Node: Windows<52>,  Next: 工具/示例<31>,  Prev: 构建<54>,  Up: Python 3 5 1 rc1

1.19.76.7 Windows
.................

   - bpo-25450(1): Updates shortcuts to start Python in installation
     directory.

   - bpo-25164(2): Changes default all-users install directory to match
     per-user directory.

   - bpo-25143(3): Improves installer error messages for unsupported
     platforms.

   - bpo-25163(4): Display correct directory in installer when using
     non-default settings.

   - bpo-25361(5): Disables use of SSE2 instructions in Windows 32-bit
     build

   - bpo-25089(6): Adds logging to installer for case where launcher is
     not selected on upgrade.

   - bpo-25165(7): Windows uninstallation should not remove launcher if
     other versions remain

   - bpo-25112(8): py.exe launcher is missing icons

   - bpo-25102(9): Windows installer does not precompile for -O or -OO.

   - bpo-25081(10): Makes Back button in installer go back to upgrade
     page when upgrading.

   - bpo-25091(11): Increases font size of the installer.

   - bpo-25126(12): Clarifies that the non-web installer will download
     some components.

   - bpo-25213(13): Restores requestedExecutionLevel to manifest to
     disable UAC virtualization.

   - bpo-25022(14): Removed very outdated PC/example_nt/ directory.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25450

   (2) https://bugs.python.org/issue25164

   (3) https://bugs.python.org/issue25143

   (4) https://bugs.python.org/issue25163

   (5) https://bugs.python.org/issue25361

   (6) https://bugs.python.org/issue25089

   (7) https://bugs.python.org/issue25165

   (8) https://bugs.python.org/issue25112

   (9) https://bugs.python.org/issue25102

   (10) https://bugs.python.org/issue25081

   (11) https://bugs.python.org/issue25091

   (12) https://bugs.python.org/issue25126

   (13) https://bugs.python.org/issue25213

   (14) https://bugs.python.org/issue25022


File: python.info,  Node: 工具/示例<31>,  Prev: Windows<52>,  Up: Python 3 5 1 rc1

1.19.76.8 工具/示例
...................

   - bpo-25440(1): Fix output of python-config –extension-suffix.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25440


File: python.info,  Node: Python 3 5 0 正式版,  Next: Python 3 5 0 rc4,  Prev: Python 3 5 1 rc1,  Up: Changelog（更動日誌）

1.19.77 Python 3.5.0 正式版
---------------------------

`发布日期: 2015-09-13'

* Menu:

* 构建: 构建<55>.


File: python.info,  Node: 构建<55>,  Up: Python 3 5 0 正式版

1.19.77.1 构建
..............

   - bpo-25071(1): Windows installer should not require TargetDir
     parameter when installing quietly.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25071


File: python.info,  Node: Python 3 5 0 rc4,  Next: Python 3 5 0 rc3,  Prev: Python 3 5 0 正式版,  Up: Changelog（更動日誌）

1.19.78 Python 3.5.0 rc4
------------------------

`发布日期: 2015-09-09'

* Menu:

* 库: 库<78>.
* 构建: 构建<56>.


File: python.info,  Node: 库<78>,  Next: 构建<56>,  Up: Python 3 5 0 rc4

1.19.78.1 库
............

   - bpo-25029(1): Fixes MemoryError in test_strptime.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25029


File: python.info,  Node: 构建<56>,  Prev: 库<78>,  Up: Python 3 5 0 rc4

1.19.78.2 构建
..............

   - bpo-25027(1): Reverts partial-static build options and adds
     vcruntime140.dll to Windows installation.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue25027


File: python.info,  Node: Python 3 5 0 rc3,  Next: Python 3 5 0 rc2,  Prev: Python 3 5 0 rc4,  Up: Changelog（更動日誌）

1.19.79 Python 3.5.0 rc3
------------------------

`发布日期: 2015-09-07'

* Menu:

* 核心与内置函数: 核心与内置函数<63>.
* 库: 库<79>.


File: python.info,  Node: 核心与内置函数<63>,  Next: 库<79>,  Up: Python 3 5 0 rc3

1.19.79.1 核心与内置函数
........................

   - bpo-24305(1): Prevent import subsystem stack frames from being
     counted by the warnings.warn(stacklevel=) parameter.

   - bpo-24912(2): Prevent __class__ assignment to immutable built-in
     objects.

   - bpo-24975(3): Fix AST compilation for PEP 448(4) syntax.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24305

   (2) https://bugs.python.org/issue24912

   (3) https://bugs.python.org/issue24975

   (4) https://www.python.org/dev/peps/pep-0448


File: python.info,  Node: 库<79>,  Prev: 核心与内置函数<63>,  Up: Python 3 5 0 rc3

1.19.79.2 库
............

   - bpo-24917(1): time_strftime() buffer over-read.

   - bpo-24748(2): 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.

   - bpo-24635(3): Fixed a bug in typing.py where isinstance([],
     typing.Iterable) would return True once, then False on subsequent
     calls.

   - bpo-24989(4): Fixed buffer overread in BytesIO.readline() if a
     position is set beyond size.  Based on patch by John Leitch.

   - bpo-24913(5): Fix overrun error in deque.index().  Found by John
     Leitch and Bryce Darling.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24917

   (2) https://bugs.python.org/issue24748

   (3) https://bugs.python.org/issue24635

   (4) https://bugs.python.org/issue24989

   (5) https://bugs.python.org/issue24913


File: python.info,  Node: Python 3 5 0 rc2,  Next: Python 3 5 0 rc1,  Prev: Python 3 5 0 rc3,  Up: Changelog（更動日誌）

1.19.80 Python 3.5.0 rc2
------------------------

`发布日期: 2015-08-25'

* Menu:

* 核心与内置函数: 核心与内置函数<64>.
* 库: 库<80>.


File: python.info,  Node: 核心与内置函数<64>,  Next: 库<80>,  Up: Python 3 5 0 rc2

1.19.80.1 核心与内置函数
........................

   - bpo-24769(1): Interpreter now starts properly when dynamic loading
     is disabled.  Patch by Petr Viktorin.

   - bpo-21167(2): NAN operations are now handled correctly when python
     is compiled with ICC even if -fp-model strict is not specified.

   - bpo-24492(3): A "package" lacking a __name__ attribute when trying
     to perform a ‘from .. import ...’ statement will trigger an
     ImportError instead of an AttributeError.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24769

   (2) https://bugs.python.org/issue21167

   (3) https://bugs.python.org/issue24492


File: python.info,  Node: 库<80>,  Prev: 核心与内置函数<64>,  Up: Python 3 5 0 rc2

1.19.80.2 库
............

   - bpo-24847(1): Removes vcruntime140.dll dependency from Tcl/Tk.

   - bpo-24839(2): platform._syscmd_ver raises DeprecationWarning

   - bpo-24867(3): Fix Task.get_stack() for ’async def’ coroutines

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24847

   (2) https://bugs.python.org/issue24839

   (3) https://bugs.python.org/issue24867


File: python.info,  Node: Python 3 5 0 rc1,  Next: Python 3 5 0 beta 4,  Prev: Python 3 5 0 rc2,  Up: Changelog（更動日誌）

1.19.81 Python 3.5.0 rc1
------------------------

`发布日期: 2015-08-09'

* Menu:

* 核心与内置函数: 核心与内置函数<65>.
* 库: 库<81>.
* IDLE: IDLE<48>.
* 文档: 文档<51>.
* 测试: 测试<53>.


File: python.info,  Node: 核心与内置函数<65>,  Next: 库<81>,  Up: Python 3 5 0 rc1

1.19.81.1 核心与内置函数
........................

   - bpo-24667(1): Resize odict in all cases that the underlying dict
     resizes.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24667


File: python.info,  Node: 库<81>,  Next: IDLE<48>,  Prev: 核心与内置函数<65>,  Up: Python 3 5 0 rc1

1.19.81.2 库
............

   - bpo-24824(1): Signatures of codecs.encode() and codecs.decode() now
     are compatible with pydoc.

   - bpo-24634(2): Importing uuid should not try to load libc on Windows

   - bpo-24798(3): _msvccompiler.py doesn’t properly support manifests

   - bpo-4395(4): Better testing and documentation of binary operators.
     Patch by Martin Panter.

   - bpo-23973(5): Update typing.py from GitHub repo.

   - bpo-23004(6): mock_open() now reads binary data correctly when the
     type of read_data is bytes.  Initial patch by Aaron Hill.

   - bpo-23888(7): Handle fractional time in cookie expiry.  Patch by
     ssh.

   - bpo-23652(8): 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.

   - bpo-22932(9): Fix timezones in email.utils.formatdate.  Patch from
     Dmitry Shachnev.

   - bpo-23779(10): imaplib raises TypeError if authenticator tries to
     abort.  Patch from Craig Holmquist.

   - bpo-23319(11): Fix ctypes.BigEndianStructure, swap correctly bytes.
     Patch written by Matthieu Gautier.

   - bpo-23254(12): Document how to close the TCPServer listening
     socket.  Patch from Martin Panter.

   - bpo-19450(13): 更新Windows和OS X安装程序以使用SQLite 3.8.11

   - bpo-17527(14): Add PATCH to wsgiref.validator.  Patch from Luca
     Sbardella.

   - bpo-24791(15): Fix grammar regression for call syntax: ’g(*a or
     b)’.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24824

   (2) https://bugs.python.org/issue24634

   (3) https://bugs.python.org/issue24798

   (4) https://bugs.python.org/issue4395

   (5) https://bugs.python.org/issue23973

   (6) https://bugs.python.org/issue23004

   (7) https://bugs.python.org/issue23888

   (8) https://bugs.python.org/issue23652

   (9) https://bugs.python.org/issue22932

   (10) https://bugs.python.org/issue23779

   (11) https://bugs.python.org/issue23319

   (12) https://bugs.python.org/issue23254

   (13) https://bugs.python.org/issue19450

   (14) https://bugs.python.org/issue17527

   (15) https://bugs.python.org/issue24791


File: python.info,  Node: IDLE<48>,  Next: 文档<51>,  Prev: 库<81>,  Up: Python 3 5 0 rc1

1.19.81.3 IDLE
..............

   - bpo-23672(1): Allow Idle to edit and run files with astral chars in
     name.  Patch by Mohd Sanad Zaki Rizvi.

   - bpo-24745(2): 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.

   - bpo-21192(3): Idle editor.  When a file is run, put its name in the
     restart bar.  Do not print false prompts.  Original patch by Adnan
     Umer.

   - bpo-13884(4): Idle menus.  Remove tearoff lines.  Patch by Roger
     Serwy.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23672

   (2) https://bugs.python.org/issue24745

   (3) https://bugs.python.org/issue21192

   (4) https://bugs.python.org/issue13884


File: python.info,  Node: 文档<51>,  Next: 测试<53>,  Prev: IDLE<48>,  Up: Python 3 5 0 rc1

1.19.81.4 文档
..............

   - bpo-24129(1): 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.

   - bpo-20769(2): Improve reload() docs.  Patch by Dorian Pula.

   - bpo-23589(3): Remove duplicate sentence from the FAQ. Patch by
     Yongzhi Pan.

   - bpo-24729(4): Correct IO tutorial to match implementation regarding
     encoding parameter to open function.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24129

   (2) https://bugs.python.org/issue20769

   (3) https://bugs.python.org/issue23589

   (4) https://bugs.python.org/issue24729


File: python.info,  Node: 测试<53>,  Prev: 文档<51>,  Up: Python 3 5 0 rc1

1.19.81.5 测试
..............

   - bpo-24751(1): When running regrtest with the ‘-w’ command line
     option, a test run is no longer marked as a failure if all tests
     succeed when re-run.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24751


File: python.info,  Node: Python 3 5 0 beta 4,  Next: Python 3 5 0 beta 3,  Prev: Python 3 5 0 rc1,  Up: Changelog（更動日誌）

1.19.82 Python 3.5.0 beta 4
---------------------------

`发布日期: 2015-07-26'

* Menu:

* 核心与内置函数: 核心与内置函数<66>.
* 库: 库<82>.
* 构建: 构建<57>.


File: python.info,  Node: 核心与内置函数<66>,  Next: 库<82>,  Up: Python 3 5 0 beta 4

1.19.82.1 核心与内置函数
........................

   - bpo-23573(1): Restored optimization of bytes.rfind() and
     bytearray.rfind() for single-byte argument on Linux.

   - bpo-24569(2): Make PEP 448(3) dictionary evaluation more
     consistent.

   - bpo-24583(4): Fix crash when set is mutated while being updated.

   - bpo-24407(5): Fix crash when dict is mutated while being updated.

   - bpo-24619(6): New approach for tokenizing async/await.  As a
     consequence, it is now possible to have one-line ’async def foo():
     await ..’ functions.

   - bpo-24687(7): Plug refleak on SyntaxError in function parameters
     annotations.

   - bpo-15944(8): memoryview: Allow arbitrary formats when casting to
     bytes.  Patch by Martin Panter.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23573

   (2) https://bugs.python.org/issue24569

   (3) https://www.python.org/dev/peps/pep-0448

   (4) https://bugs.python.org/issue24583

   (5) https://bugs.python.org/issue24407

   (6) https://bugs.python.org/issue24619

   (7) https://bugs.python.org/issue24687

   (8) https://bugs.python.org/issue15944


File: python.info,  Node: 库<82>,  Next: 构建<57>,  Prev: 核心与内置函数<66>,  Up: Python 3 5 0 beta 4

1.19.82.2 库
............

   - bpo-23441(1): rcompleter now prints a tab character instead of
     displaying possible completions for an empty word.  Initial patch
     by Martin Sekera.

   - bpo-24683(2): Fixed crashes in _json functions called with
     arguments of inappropriate type.

   - bpo-21697(3): shutil.copytree() now correctly handles symbolic
     links that point to directories.  Patch by Eduardo Seabra and
     Thomas Kluyver.

   - bpo-14373(4): Fixed segmentation fault when gc.collect() is called
     during constructing lru_cache (C implementation).

   - bpo-24695(5): Fix a regression in traceback.print_exception().  If
     exc_traceback is None we shouldn’t print a traceback header like
     described in the documentation.

   - bpo-24620(6): Random.setstate() now validates the value of state
     last element.

   - bpo-22485(7): Fixed an issue that caused *note inspect.getsource:
     fda. to return incorrect results on nested functions.

   - bpo-22153(8): Improve unittest docs.  Patch from Martin Panter and
     evilzero.

   - bpo-24580(9): Symbolic group references to open group in re
     patterns now are explicitly forbidden as well as numeric group
     references.

   - bpo-24206(10): Fixed __eq__ and __ne__ methods of inspect classes.

   - bpo-24631(11): Fixed regression in the timeit module with multiline
     setup.

   - bpo-18622(12): unittest.mock.mock_open().reset_mock would recurse
     infinitely.  Patch from Nicola Palumbo and Laurent De Buyst.

   - bpo-23661(13): unittest.mock side_effects can now be exceptions
     again.  This was a regression vs Python 3.4.  Patch from Ignacio
     Rossi

   - bpo-24608(14): chunk.Chunk.read() now always returns bytes, not
     str.

   - bpo-18684(15): Fixed reading out of the buffer in the re module.

   - bpo-24259(16): tarfile now raises a ReadError if an archive is
     truncated inside a data segment.

   - bpo-15014(17): SMTP.auth() and SMTP.login() now support RFC 4954’s
     optional initial-response argument to the SMTP AUTH command.

   - bpo-24669(18): Fix inspect.getsource() for ’async def’ functions.
     Patch by Kai Groner.

   - bpo-24688(19): ast.get_docstring() for ’async def’ functions.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23441

   (2) https://bugs.python.org/issue24683

   (3) https://bugs.python.org/issue21697

   (4) https://bugs.python.org/issue14373

   (5) https://bugs.python.org/issue24695

   (6) https://bugs.python.org/issue24620

   (7) https://bugs.python.org/issue22485

   (8) https://bugs.python.org/issue22153

   (9) https://bugs.python.org/issue24580

   (10) https://bugs.python.org/issue24206

   (11) https://bugs.python.org/issue24631

   (12) https://bugs.python.org/issue18622

   (13) https://bugs.python.org/issue23661

   (14) https://bugs.python.org/issue24608

   (15) https://bugs.python.org/issue18684

   (16) https://bugs.python.org/issue24259

   (17) https://bugs.python.org/issue15014

   (18) https://bugs.python.org/issue24669

   (19) https://bugs.python.org/issue24688


File: python.info,  Node: 构建<57>,  Prev: 库<82>,  Up: Python 3 5 0 beta 4

1.19.82.3 构建
..............

   - bpo-24603(1): 更新Windows 构建和OS X 10.5 安装程序以使用OpenSSL
     1.0.2d.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24603


File: python.info,  Node: Python 3 5 0 beta 3,  Next: Python 3 5 0 beta 2,  Prev: Python 3 5 0 beta 4,  Up: Changelog（更動日誌）

1.19.83 Python 3.5.0 beta 3
---------------------------

`发布日期: 2015-07-05'

* Menu:

* 核心与内置函数: 核心与内置函数<67>.
* 库: 库<83>.
* 测试: 测试<54>.
* 文档: 文档<52>.
* 构建: 构建<58>.


File: python.info,  Node: 核心与内置函数<67>,  Next: 库<83>,  Up: Python 3 5 0 beta 3

1.19.83.1 核心与内置函数
........................

   - bpo-24467(1): 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.

   - Upgrade to Unicode 8.0.0.

   - bpo-24345(2): Add Py_tp_finalize slot for the stable ABI.

   - bpo-24400(3): Introduce a distinct type for PEP 492(4) 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.

   - bpo-24450(5): Add gi_yieldfrom to generators and cr_await to
     coroutines.  Contributed by Benno Leslie and Yury Selivanov.

   - bpo-19235(6): Add new RecursionError exception.  Patch by Georg
     Brandl.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24467

   (2) https://bugs.python.org/issue24345

   (3) https://bugs.python.org/issue24400

   (4) https://www.python.org/dev/peps/pep-0492

   (5) https://bugs.python.org/issue24450

   (6) https://bugs.python.org/issue19235


File: python.info,  Node: 库<83>,  Next: 测试<54>,  Prev: 核心与内置函数<67>,  Up: Python 3 5 0 beta 3

1.19.83.2 库
............

   - bpo-21750(1): mock_open.read_data can now be read from each
     instance, as it could in Python 3.3.

   - bpo-24552(2): Fix use after free in an error case of the _pickle
     module.

   - bpo-24514(3): tarfile now tolerates number fields consisting of
     only whitespace.

   - bpo-19176(4): 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.

   - bpo-20387(5): Restore semantic round-trip correctness in
     tokenize/untokenize for tab-indented blocks.

   - bpo-24456(6): Fixed possible buffer over-read in adpcm2lin() and
     lin2adpcm() functions of the audioop module.

   - bpo-24336(7): The contextmanager decorator now works with functions
     with keyword arguments called "func" and "self".  Patch by Martin
     Panter.

   - bpo-24522(8): Fix possible integer overflow in json accelerator
     module.

   - bpo-24489(9): ensure a previously set C errno doesn’t disturb
     cmath.polar().

   - bpo-24408(10): Fixed AttributeError in measure() and metrics()
     methods of tkinter.Font.

   - bpo-14373(11): C implementation of functools.lru_cache() now can be
     used with methods.

   - bpo-24347(12): Set KeyError if PyDict_GetItemWithError returns
     NULL.

   - bpo-24348(13): Drop superfluous incref/decref.

   - bpo-24359(14): Check for changed OrderedDict size during iteration.

   - bpo-24368(15): Support keyword arguments in OrderedDict methods.

   - bpo-24362(16): Simplify the C OrderedDict fast nodes resize logic.

   - bpo-24377(17): Fix a ref leak in OrderedDict.__repr__.

   - bpo-24369(18): Defend against key-changes during iteration.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21750

   (2) https://bugs.python.org/issue24552

   (3) https://bugs.python.org/issue24514

   (4) https://bugs.python.org/issue19176

   (5) https://bugs.python.org/issue20387

   (6) https://bugs.python.org/issue24456

   (7) https://bugs.python.org/issue24336

   (8) https://bugs.python.org/issue24522

   (9) https://bugs.python.org/issue24489

   (10) https://bugs.python.org/issue24408

   (11) https://bugs.python.org/issue14373

   (12) https://bugs.python.org/issue24347

   (13) https://bugs.python.org/issue24348

   (14) https://bugs.python.org/issue24359

   (15) https://bugs.python.org/issue24368

   (16) https://bugs.python.org/issue24362

   (17) https://bugs.python.org/issue24377

   (18) https://bugs.python.org/issue24369


File: python.info,  Node: 测试<54>,  Next: 文档<52>,  Prev: 库<83>,  Up: Python 3 5 0 beta 3

1.19.83.3 测试
..............

   - bpo-24373(1): _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(2) for details)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24373

   (2) https://bugs.python.org/issue16690


File: python.info,  Node: 文档<52>,  Next: 构建<58>,  Prev: 测试<54>,  Up: Python 3 5 0 beta 3

1.19.83.4 文档
..............

   - bpo-24458(1): Update documentation to cover multi-phase
     initialization for extension modules (PEP 489).  Patch by Petr
     Viktorin.

   - bpo-24351(2): Clarify what is meant by "identifier" in the context
     of string.Template instances.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24458

   (2) https://bugs.python.org/issue24351


File: python.info,  Node: 构建<58>,  Prev: 文档<52>,  Up: Python 3 5 0 beta 3

1.19.83.5 构建
..............

   - bpo-24432(1): 更新Windows 构建和OS X 10.5 安装程序以使用OpenSSL
     1.0.2c.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24432


File: python.info,  Node: Python 3 5 0 beta 2,  Next: Python 3 5 0 beta 1,  Prev: Python 3 5 0 beta 3,  Up: Changelog（更動日誌）

1.19.84 Python 3.5.0 beta 2
---------------------------

`发布日期: 2015-05-31'

* Menu:

* 核心与内置函数: 核心与内置函数<68>.
* 库: 库<84>.


File: python.info,  Node: 核心与内置函数<68>,  Next: 库<84>,  Up: Python 3 5 0 beta 2

1.19.84.1 核心与内置函数
........................

   - bpo-24284(1): 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.

   - bpo-24115(2): Update uses of PyObject_IsTrue(), PyObject_Not(),
     PyObject_IsInstance(), PyObject_RichCompareBool() and
     _PyDict_Contains() to check for and handle errors correctly.

   - bpo-24328(3): Fix importing one character extension modules.

   - bpo-11205(4): In dictionary displays, evaluate the key before the
     value.

   - bpo-24285(5): Fixed regression that prevented importing extension
     modules from inside packages.  Patch by Petr Viktorin.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24284

   (2) https://bugs.python.org/issue24115

   (3) https://bugs.python.org/issue24328

   (4) https://bugs.python.org/issue11205

   (5) https://bugs.python.org/issue24285


File: python.info,  Node: 库<84>,  Prev: 核心与内置函数<68>,  Up: Python 3 5 0 beta 2

1.19.84.2 库
............

   - bpo-23247(1): Fix a crash in the StreamWriter.reset() of CJK
     codecs.

   - bpo-24270(2): Add math.isclose() and cmath.isclose() functions as
     per PEP 485(3).  Contributed by Chris Barker and Tal Einat.

   - bpo-5633(4): Fixed timeit when the statement is a string and the
     setup is not.

   - bpo-24326(5): Fixed audioop.ratecv() with non-default weightB
     argument.  Original patch by David Moore.

   - bpo-16991(6): Add a C implementation of OrderedDict.

   - bpo-23934(7): Fix inspect.signature to fail correctly for builtin
     types lacking signature information.  Initial patch by James
     Powell.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23247

   (2) https://bugs.python.org/issue24270

   (3) https://www.python.org/dev/peps/pep-0485

   (4) https://bugs.python.org/issue5633

   (5) https://bugs.python.org/issue24326

   (6) https://bugs.python.org/issue16991

   (7) https://bugs.python.org/issue23934


File: python.info,  Node: Python 3 5 0 beta 1,  Next: Python 3 5 0 alpha 4,  Prev: Python 3 5 0 beta 2,  Up: Changelog（更動日誌）

1.19.85 Python 3.5.0 beta 1
---------------------------

`发布日期: 2015-05-24'

* Menu:

* 核心与内置函数: 核心与内置函数<69>.
* 库: 库<85>.
* IDLE: IDLE<49>.
* 测试: 测试<55>.
* 文档: 文档<53>.
* 工具/示例: 工具/示例<32>.


File: python.info,  Node: 核心与内置函数<69>,  Next: 库<85>,  Up: Python 3 5 0 beta 1

1.19.85.1 核心与内置函数
........................

   - bpo-24276(1): Fixed optimization of property descriptor getter.

   - bpo-24268(2): PEP 489: Multi-phase extension module initialization.
     Patch by Petr Viktorin.

   - bpo-23955(3): Add pyvenv.cfg option to suppress
     registry/environment lookup for generating sys.path on Windows.

   - bpo-24257(4): Fixed system error in the comparison of faked
     types.SimpleNamespace.

   - bpo-22939(5): Fixed integer overflow in iterator object.  Patch by
     Clement Rouault.

   - bpo-23985(6): Fix a possible buffer overrun when deleting a slice
     from the front of a bytearray and then appending some other bytes
     data.

   - bpo-24102(7): Fixed exception type checking in standard error
     handlers.

   - bpo-15027(8): The UTF-32 encoder is now 3x to 7x faster.

   - bpo-23290(9): Optimize set_merge() for cases where the target is
     empty.  (Contributed by Serhiy Storchaka.)

   - bpo-2292(10): PEP 448: Additional Unpacking Generalizations.

   - bpo-24096(11): Make warnings.warn_explicit more robust against
     mutation of the warnings.filters list.

   - bpo-23996(12): Avoid a crash when a delegated generator raises an
     unnormalized StopIteration exception.  Patch by Stefan Behnel.

   - bpo-23910(13): Optimize property() getter calls.  Patch by Joe
     Jevnik.

   - bpo-23911(14): Move path-based importlib bootstrap code to a
     separate frozen module.

   - bpo-24192(15): Fix namespace package imports.

   - bpo-24022(16): Fix tokenizer crash when processing undecodable
     source code.

   - bpo-9951(17): Added a hex() method to bytes, bytearray, and
     memoryview.

   - bpo-22906(18): PEP 479: Change StopIteration handling inside
     generators.

   - bpo-24017(19): PEP 492: Coroutines with async and await syntax.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24276

   (2) https://bugs.python.org/issue24268

   (3) https://bugs.python.org/issue23955

   (4) https://bugs.python.org/issue24257

   (5) https://bugs.python.org/issue22939

   (6) https://bugs.python.org/issue23985

   (7) https://bugs.python.org/issue24102

   (8) https://bugs.python.org/issue15027

   (9) https://bugs.python.org/issue23290

   (10) https://bugs.python.org/issue2292

   (11) https://bugs.python.org/issue24096

   (12) https://bugs.python.org/issue23996

   (13) https://bugs.python.org/issue23910

   (14) https://bugs.python.org/issue23911

   (15) https://bugs.python.org/issue24192

   (16) https://bugs.python.org/issue24022

   (17) https://bugs.python.org/issue9951

   (18) https://bugs.python.org/issue22906

   (19) https://bugs.python.org/issue24017


File: python.info,  Node: 库<85>,  Next: IDLE<49>,  Prev: 核心与内置函数<69>,  Up: Python 3 5 0 beta 1

1.19.85.2 库
............

   - bpo-14373(1): Added C implementation of functools.lru_cache().
     Based on patches by Matt Joiner and Alexey Kachayev.

   - bpo-24230(2): The tempfile module now accepts bytes for prefix,
     suffix and dir parameters and returns bytes in such situations
     (matching the os module APIs).

   - bpo-22189(3): collections.UserString now supports __getnewargs__(),
     __rmod__(), casefold(), format_map(), isprintable(), and
     maketrans().  Patch by Joe Jevnik.

   - bpo-24244(4): Prevents termination when an invalid format string is
     encountered on Windows in strftime.

   - bpo-23973(5): PEP 484: Add the typing module.

   - bpo-23086(6): The collections.abc.Sequence() abstract base class
     added `start' and `stop' parameters to the index() mixin.  Patch by
     Devin Jeanpierre.

   - bpo-20035(7): Replaced the ‘tkinter._fix’ module used for setting
     up the Tcl/Tk environment on Windows with a private function in the
     ‘_tkinter’ module that makes no permanent changes to the
     environment.

   - bpo-24257(8): Fixed segmentation fault in sqlite3.Row constructor
     with faked cursor type.

   - bpo-15836(9): 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.

   - bpo-9858(10): Add missing method stubs to _io.RawIOBase.  Patch by
     Laura Rupprecht.

   - bpo-22955(11): 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.

   - bpo-22107(12): 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.

   - bpo-23780(13): Improved error message in os.path.join() with single
     argument.

   - bpo-6598(14): Increased time precision and random number range in
     email.utils.make_msgid() to strengthen the uniqueness of the
     message ID.

   - bpo-24091(15): Fixed various crashes in corner cases in C
     implementation of ElementTree.

   - bpo-21931(16): 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.

   - bpo-13866(17): `quote_via' argument added to
     urllib.parse.urlencode.

   - bpo-20098(18): New mangle_from policy option for email, default
     True for compat32, but False for all other policies.

   - bpo-24211(19): The email library now supports RFC 6532: it can
     generate headers using utf-8 instead of encoded words.

   - bpo-16314(20): Added support for the LZMA compression in distutils.

   - bpo-21804(21): poplib now supports RFC 6856 (UTF8).

   - bpo-18682(22): Optimized pprint functions for builtin scalar types.

   - bpo-22027(23): smtplib now supports RFC 6531 (SMTPUTF8).

   - bpo-23488(24): Random generator objects now consume 2x less memory
     on 64-bit.

   - bpo-1322(25): platform.dist() and platform.linux_distribution()
     functions are now deprecated.  Initial patch by Vajrasky Kok.

   - bpo-22486(26): Added the math.gcd() function.  The fractions.gcd()
     function now is deprecated.  Based on patch by Mark Dickinson.

   - bpo-24064(27): Property() docstrings are now writeable.  (Patch by
     Berker Peksag.)

   - bpo-22681(28): Added support for the koi8_t encoding.

   - bpo-22682(29): Added support for the kz1048 encoding.

   - bpo-23796(30): peek and read1 methods of BufferedReader now raise
     ValueError if they called on a closed object.  Patch by John
     Hergenroeder.

   - bpo-21795(31): smtpd now supports the 8BITMIME extension whenever
     the new `decode_data' constructor argument is set to False.

   - bpo-24155(32): optimize heapq.heapify() for better cache
     performance when heapifying large lists.

   - bpo-21800(33): imaplib now supports RFC 5161 (enable), RFC 6855
     (utf8/internationalized email) and automatically encodes non-ASCII
     usernames and passwords to UTF8.

   - bpo-20274(34): When calling a _sqlite.Connection, it now complains
     if passed any keyword arguments.  Previously it silently ignored
     them.

   - bpo-20274(35): Remove ignored and erroneous "kwargs" parameters
     from three METH_VARARGS methods on _sqlite.Connection.

   - bpo-24134(36): 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.

   - bpo-24018(37): Add a collections.abc.Generator abstract base class.
     Contributed by Stefan Behnel.

   - bpo-23880(38): Tkinter’s getint() and getdouble() now support
     Tcl_Obj.  Tkinter’s getdouble() now supports any numbers (in
     particular int).

   - bpo-22619(39): Added negative limit support in the traceback
     module.  Based on patch by Dmitry Kazakov.

   - bpo-24094(40): Fix possible crash in json.encode with poorly
     behaved dict subclasses.

   - bpo-9246(41): On POSIX, os.getcwd() now supports paths longer than
     1025 bytes.  Patch written by William Orr.

   - bpo-17445(42): add difflib.diff_bytes() to support comparison of
     byte strings (fixes a regression from Python 2).

   - bpo-23917(43): Fall back to sequential compilation when
     ProcessPoolExecutor doesn’t exist.  Patch by Claudiu Popa.

   - bpo-23008(44): Fixed resolving attributes with boolean value is
     False in pydoc.

   - Fix asyncio issue 235: LifoQueue and PriorityQueue’s put didn’t
     increment unfinished tasks (this bug was introduced when
     JoinableQueue was merged with Queue).

   - bpo-23908(45): os functions now reject paths with embedded null
     character on Windows instead of silently truncating them.

   - bpo-23728(46): binascii.crc_hqx() could return an integer outside
     of the range 0-0xffff for empty data.

   - bpo-23887(47): urllib.error.HTTPError now has a proper repr()
     representation.  Patch by Berker Peksag.

   - asyncio: New event loop APIs: set_task_factory() and
     get_task_factory().

   - asyncio: async() function is deprecated in favour of
     ensure_future().

   - bpo-24178(48): asyncio.Lock, Condition, Semaphore, and
     BoundedSemaphore support new ’async with’ syntax.  Contributed by
     Yury Selivanov.

   - bpo-24179(49): Support ’async for’ for asyncio.StreamReader.
     Contributed by Yury Selivanov.

   - bpo-24184(50): Add AsyncIterator and AsyncIterable ABCs to
     collections.abc.  Contributed by Yury Selivanov.

   - bpo-22547(51): Implement informative __repr__ for
     inspect.BoundArguments.  Contributed by Yury Selivanov.

   - bpo-24190(52): Implement inspect.BoundArgument.apply_defaults()
     method.  Contributed by Yury Selivanov.

   - bpo-20691(53): Add ’follow_wrapped’ argument to
     inspect.Signature.from_callable() and inspect.signature().
     Contributed by Yury Selivanov.

   - bpo-24248(54): Deprecate inspect.Signature.from_function() and
     inspect.Signature.from_builtin().

   - bpo-23898(55): Fix inspect.classify_class_attrs() to support
     attributes with overloaded __eq__ and __bool__.  Patch by Mike
     Bayer.

   - bpo-24298(56): Fix inspect.signature() to correctly unwrap wrappers
     around bound methods.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue14373

   (2) https://bugs.python.org/issue24230

   (3) https://bugs.python.org/issue22189

   (4) https://bugs.python.org/issue24244

   (5) https://bugs.python.org/issue23973

   (6) https://bugs.python.org/issue23086

   (7) https://bugs.python.org/issue20035

   (8) https://bugs.python.org/issue24257

   (9) https://bugs.python.org/issue15836

   (10) https://bugs.python.org/issue9858

   (11) https://bugs.python.org/issue22955

   (12) https://bugs.python.org/issue22107

   (13) https://bugs.python.org/issue23780

   (14) https://bugs.python.org/issue6598

   (15) https://bugs.python.org/issue24091

   (16) https://bugs.python.org/issue21931

   (17) https://bugs.python.org/issue13866

   (18) https://bugs.python.org/issue20098

   (19) https://bugs.python.org/issue24211

   (20) https://bugs.python.org/issue16314

   (21) https://bugs.python.org/issue21804

   (22) https://bugs.python.org/issue18682

   (23) https://bugs.python.org/issue22027

   (24) https://bugs.python.org/issue23488

   (25) https://bugs.python.org/issue1322

   (26) https://bugs.python.org/issue22486

   (27) https://bugs.python.org/issue24064

   (28) https://bugs.python.org/issue22681

   (29) https://bugs.python.org/issue22682

   (30) https://bugs.python.org/issue23796

   (31) https://bugs.python.org/issue21795

   (32) https://bugs.python.org/issue24155

   (33) https://bugs.python.org/issue21800

   (34) https://bugs.python.org/issue20274

   (35) https://bugs.python.org/issue20274

   (36) https://bugs.python.org/issue24134

   (37) https://bugs.python.org/issue24018

   (38) https://bugs.python.org/issue23880

   (39) https://bugs.python.org/issue22619

   (40) https://bugs.python.org/issue24094

   (41) https://bugs.python.org/issue9246

   (42) https://bugs.python.org/issue17445

   (43) https://bugs.python.org/issue23917

   (44) https://bugs.python.org/issue23008

   (45) https://bugs.python.org/issue23908

   (46) https://bugs.python.org/issue23728

   (47) https://bugs.python.org/issue23887

   (48) https://bugs.python.org/issue24178

   (49) https://bugs.python.org/issue24179

   (50) https://bugs.python.org/issue24184

   (51) https://bugs.python.org/issue22547

   (52) https://bugs.python.org/issue24190

   (53) https://bugs.python.org/issue20691

   (54) https://bugs.python.org/issue24248

   (55) https://bugs.python.org/issue23898

   (56) https://bugs.python.org/issue24298


File: python.info,  Node: IDLE<49>,  Next: 测试<55>,  Prev: 库<85>,  Up: Python 3 5 0 beta 1

1.19.85.3 IDLE
..............

   - bpo-23184(1): remove unused names and imports in idlelib.  Initial
     patch by Al Sweigart.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23184


File: python.info,  Node: 测试<55>,  Next: 文档<53>,  Prev: IDLE<49>,  Up: Python 3 5 0 beta 1

1.19.85.4 测试
..............

   - bpo-21520(1): test_zipfile no longer fails if the word ’bad’
     appears anywhere in the name of the current directory.

   - bpo-9517(2): Move script_helper into the support package.  Patch by
     Christie Wilson.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue21520

   (2) https://bugs.python.org/issue9517


File: python.info,  Node: 文档<53>,  Next: 工具/示例<32>,  Prev: 测试<55>,  Up: Python 3 5 0 beta 1

1.19.85.5 文档
..............

   - bpo-22155(1): Add File Handlers subsection with createfilehandler
     to tkinter doc.  Remove obsolete example from FAQ. Patch by Martin
     Panter.

   - bpo-24029(2): Document the name binding behavior for submodule
     imports.

   - bpo-24077(3): Fix typo in man page for -I command option: -s, not
     -S

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22155

   (2) https://bugs.python.org/issue24029

   (3) https://bugs.python.org/issue24077


File: python.info,  Node: 工具/示例<32>,  Prev: 文档<53>,  Up: Python 3 5 0 beta 1

1.19.85.6 工具/示例
...................

   - bpo-24000(1): Improved Argument Clinic’s mapping of converters to
     legacy "format units".  Updated the documentation to match.

   - bpo-24001(2): Argument Clinic converters now use accept={type}
     instead of types={’type’} to specify the types the converter
     accepts.

   - bpo-23330(3): h2py now supports arbitrary filenames in #include.

   - bpo-24031(4): make patchcheck now supports git checkouts, too.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue24000

   (2) https://bugs.python.org/issue24001

   (3) https://bugs.python.org/issue23330

   (4) https://bugs.python.org/issue24031


File: python.info,  Node: Python 3 5 0 alpha 4,  Next: Python 3 5 0 alpha 3,  Prev: Python 3 5 0 beta 1,  Up: Changelog（更動日誌）

1.19.86 Python 3.5.0 alpha 4
----------------------------

`发布日期: 2015-04-19'

* Menu:

* 核心与内置函数: 核心与内置函数<70>.
* 库: 库<86>.
* 构建: 构建<59>.
* 测试: 测试<56>.
* 工具/示例: 工具/示例<33>.
* C API: C API<41>.


File: python.info,  Node: 核心与内置函数<70>,  Next: 库<86>,  Up: Python 3 5 0 alpha 4

1.19.86.1 核心与内置函数
........................

   - bpo-22980(1): 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 PEP 3149(2)-style
     information.

   - bpo-22631(3): Added Linux-specific socket constant
     CAN_RAW_FD_FRAMES. Patch courtesy of Joe Jevnik.

   - bpo-23731(4): Implement PEP 488(5): removal of .pyo files.

   - bpo-23726(6): Don’t enable GC for user subclasses of non-GC types
     that don’t add any new fields.  Patch by Eugene Toder.

   - bpo-23309(7): 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.

   - bpo-22977(8): Fixed formatting Windows error messages on Wine.
     Patch by Martin Panter.

   - bpo-23466(9): %c, %o, %x, and %X in bytes formatting now raise
     TypeError on non-integer input.

   - bpo-24044(10): Fix possible null pointer dereference in list.sort
     in out of memory conditions.

   - bpo-21354(11): PyCFunction_New function is exposed by python DLL
     again.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22980

   (2) https://www.python.org/dev/peps/pep-3149

   (3) https://bugs.python.org/issue22631

   (4) https://bugs.python.org/issue23731

   (5) https://www.python.org/dev/peps/pep-0488

   (6) https://bugs.python.org/issue23726

   (7) https://bugs.python.org/issue23309

   (8) https://bugs.python.org/issue22977

   (9) https://bugs.python.org/issue23466

   (10) https://bugs.python.org/issue24044

   (11) https://bugs.python.org/issue21354


File: python.info,  Node: 库<86>,  Next: 构建<59>,  Prev: 核心与内置函数<70>,  Up: Python 3 5 0 alpha 4

1.19.86.2 库
............

   - bpo-23840(1): tokenize.open() now closes the temporary binary file
     on error to fix a resource warning.

   - bpo-16914(2): new debuglevel 2 in smtplib adds timestamps to debug
     output.

   - bpo-7159(3): urllib.request now supports sending auth credentials
     automatically after the first 401.  This enhancement is a superset
     of the enhancement from bpo-19494(4) and supersedes that change.

   - bpo-23703(5): Fix a regression in urljoin() introduced in
     901e4e52b20a.  Patch by Demian Brecht.

   - bpo-4254(6): Adds _curses.update_lines_cols().  Patch by Arnon
     Yaari

   - bpo-19933(7): Provide default argument for ndigits in round.  Patch
     by Vajrasky Kok.

   - bpo-23193(8): Add a numeric_owner parameter to
     tarfile.TarFile.extract and tarfile.TarFile.extractall.  Patch by
     Michael Vogt and Eric Smith.

   - bpo-23342(9): Add a subprocess.run() function than returns a
     CalledProcess instance for a more consistent API than the existing
     call* functions.

   - bpo-21217(10): 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.

   - bpo-24521(11): Fix possible integer overflows in the pickle module.

   - bpo-22931(12): Allow ’[’ and ’]’ in cookie values.

   - The keywords attribute of functools.partial is now always a
     dictionary.

   - bpo-23811(13): Add missing newline to the PyCompileError error
     message.  Patch by Alex Shkop.

   - bpo-21116(14): Avoid blowing memory when allocating a
     multiprocessing shared array that’s larger than 50% of the
     available RAM. Patch by Médéric Boquien.

   - bpo-22982(15): Improve BOM handling when seeking to multiple
     positions of a writable text file.

   - bpo-23464(16): Removed deprecated asyncio JoinableQueue.

   - bpo-23529(17): 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.

   - bpo-21859(18): Added Python implementation of io.FileIO.

   - bpo-23865(19): 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.

   - bpo-23400(20): Raise same exception on both Python 2 and 3 if
     sem_open is not available.  Patch by Davin Potts.

   - bpo-10838(21): The subprocess now module includes SubprocessError
     and TimeoutError in its list of exported names for the users wild
     enough to use ‘from subprocess import *’.

   - bpo-23411(22): Added DefragResult, ParseResult, SplitResult,
     DefragResultBytes, ParseResultBytes, and SplitResultBytes to
     urllib.parse.__all__.  Patch by Martin Panter.

   - bpo-23881(23): urllib.request.ftpwrapper constructor now closes the
     socket if the FTP connection failed to fix a ResourceWarning.

   - bpo-23853(24): *note socket.socket.sendall(): 76e. 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.

   - bpo-22721(25): 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.

   - bpo-15133(26): _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.

   - bpo-10590(27): xml.sax.parseString() now supports string argument.

   - bpo-23338(28): Fixed formatting ctypes error messages on Cygwin.
     Patch by Makoto Kato.

   - bpo-15582(29): inspect.getdoc() now follows inheritance chains.

   - bpo-2175(30): SAX parsers now support a character stream of
     InputSource object.

   - bpo-16840(31): Tkinter now supports 64-bit integers added in Tcl
     8.4 and arbitrary precision integers added in Tcl 8.5.

   - bpo-23834(32): Fix socket.sendto(), use the C Py_ssize_t type to
     store the result of sendto() instead of the C int type.

   - bpo-23618(33): *note socket.socket.connect(): 769. now waits until
     the connection completes instead of raising *note InterruptedError:
     74c. if the connection is interrupted by signals, signal handlers
     don’t raise an exception and the socket is blocking or has a
     timeout.  *note socket.socket.connect(): 769. still raise *note
     InterruptedError: 74c. for non-blocking sockets.

   - bpo-21526(34): Tkinter now supports new boolean type in Tcl 8.5.

   - bpo-23836(35): Fix the faulthandler module to handle reentrant
     calls to its signal handlers.

   - bpo-23838(36): linecache now clears the cache and returns an empty
     result on MemoryError.

   - bpo-10395(37): Added os.path.commonpath().  Implemented in
     posixpath and ntpath.  Based on patch by Rafik Draoui.

   - bpo-23611(38): Serializing more "lookupable" objects (such as
     unbound methods or nested classes) now are supported with pickle
     protocols < 4.

   - bpo-13583(39): sqlite3.Row now supports slice indexing.

   - bpo-18473(40): 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.

   - bpo-23485(41): 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 PEP
     475(42).

   - bpo-23752(43): When built from an existing file descriptor,
     io.FileIO() now only calls fstat() once.  Before fstat() was called
     twice, which was not necessary.

   - bpo-23704(44): collections.deque() objects now support __add__,
     __mul__, and __imul__().

   - bpo-23171(45): csv.Writer.writerow() now supports arbitrary
     iterables.

   - bpo-23745(46): The new email header parser now handles duplicate
     MIME parameter names without error, similar to how get_param
     behaves.

   - bpo-22117(47): Fix os.utime(), it now rounds the timestamp towards
     minus infinity (-inf) instead of rounding towards zero.

   - bpo-23310(48): Fix MagicMock’s initializer to work with
     __methods__, just like configure_mock().  Patch by Kasia Jachim.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23840

   (2) https://bugs.python.org/issue16914

   (3) https://bugs.python.org/issue7159

   (4) https://bugs.python.org/issue19494

   (5) https://bugs.python.org/issue23703

   (6) https://bugs.python.org/issue4254

   (7) https://bugs.python.org/issue19933

   (8) https://bugs.python.org/issue23193

   (9) https://bugs.python.org/issue23342

   (10) https://bugs.python.org/issue21217

   (11) https://bugs.python.org/issue24521

   (12) https://bugs.python.org/issue22931

   (13) https://bugs.python.org/issue23811

   (14) https://bugs.python.org/issue21116

   (15) https://bugs.python.org/issue22982

   (16) https://bugs.python.org/issue23464

   (17) https://bugs.python.org/issue23529

   (18) https://bugs.python.org/issue21859

   (19) https://bugs.python.org/issue23865

   (20) https://bugs.python.org/issue23400

   (21) https://bugs.python.org/issue10838

   (22) https://bugs.python.org/issue23411

   (23) https://bugs.python.org/issue23881

   (24) https://bugs.python.org/issue23853

   (25) https://bugs.python.org/issue22721

   (26) https://bugs.python.org/issue15133

   (27) https://bugs.python.org/issue10590

   (28) https://bugs.python.org/issue23338

   (29) https://bugs.python.org/issue15582

   (30) https://bugs.python.org/issue2175

   (31) https://bugs.python.org/issue16840

   (32) https://bugs.python.org/issue23834

   (33) https://bugs.python.org/issue23618

   (34) https://bugs.python.org/issue21526

   (35) https://bugs.python.org/issue23836

   (36) https://bugs.python.org/issue23838

   (37) https://bugs.python.org/issue10395

   (38) https://bugs.python.org/issue23611

   (39) https://bugs.python.org/issue13583

   (40) https://bugs.python.org/issue18473

   (41) https://bugs.python.org/issue23485

   (42) https://www.python.org/dev/peps/pep-0475

   (43) https://bugs.python.org/issue23752

   (44) https://bugs.python.org/issue23704

   (45) https://bugs.python.org/issue23171

   (46) https://bugs.python.org/issue23745

   (47) https://bugs.python.org/issue22117

   (48) https://bugs.python.org/issue23310


File: python.info,  Node: 构建<59>,  Next: 测试<56>,  Prev: 库<86>,  Up: Python 3 5 0 alpha 4

1.19.86.3 构建
..............

   - bpo-23817(1): FreeBSD now uses "1.0" in the SOVERSION as other
     operating systems, instead of just "1".

   - bpo-23501(2): Argument Clinic now generates code into separate
     files by default.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23817

   (2) https://bugs.python.org/issue23501


File: python.info,  Node: 测试<56>,  Next: 工具/示例<33>,  Prev: 构建<59>,  Up: Python 3 5 0 alpha 4

1.19.86.4 测试
..............

   - bpo-23799(1): Added test.support.start_threads() for running and
     cleaning up multiple threads.

   - bpo-22390(2): test.regrtest now emits a warning if temporary files
     or directories are left after running a test.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23799

   (2) https://bugs.python.org/issue22390


File: python.info,  Node: 工具/示例<33>,  Next: C API<41>,  Prev: 测试<56>,  Up: Python 3 5 0 alpha 4

1.19.86.5 工具/示例
...................

   - bpo-18128(1): pygettext now uses standard +NNNN format in the
     POT-Creation-Date header.

   - bpo-23935(2): Argument Clinic’s understanding of format units
     accepting bytes, bytearrays, and buffers is now consistent with
     both the documentation and the implementation.

   - bpo-23944(3): Argument Clinic now wraps long impl prototypes at
     column 78.

   - bpo-20586(4): Argument Clinic now ensures that functions without
     docstrings have signatures.

   - bpo-23492(5): Argument Clinic now generates argument parsing code
     with PyArg_Parse instead of PyArg_ParseTuple if possible.

   - bpo-23500(6): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18128

   (2) https://bugs.python.org/issue23935

   (3) https://bugs.python.org/issue23944

   (4) https://bugs.python.org/issue20586

   (5) https://bugs.python.org/issue23492

   (6) https://bugs.python.org/issue23500


File: python.info,  Node: C API<41>,  Prev: 工具/示例<33>,  Up: Python 3 5 0 alpha 4

1.19.86.6 C API
...............

   - bpo-23998(1): PyImport_ReInitLock() now checks for lock allocation
     error

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23998


File: python.info,  Node: Python 3 5 0 alpha 3,  Next: Python 3 5 0 alpha 2,  Prev: Python 3 5 0 alpha 4,  Up: Changelog（更動日誌）

1.19.87 Python 3.5.0 alpha 3
----------------------------

`发布日期: 2015-03-28'

* Menu:

* 核心与内置函数: 核心与内置函数<71>.
* 库: 库<87>.
* 构建: 构建<60>.
* 测试: 测试<57>.
* 工具/示例: 工具/示例<34>.


File: python.info,  Node: 核心与内置函数<71>,  Next: 库<87>,  Up: Python 3 5 0 alpha 3

1.19.87.1 核心与内置函数
........................

   - bpo-23573(1): 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).

   - bpo-23753(2): Python doesn’t support anymore platforms without
     stat() or fstat(), these functions are always required.

   - bpo-23681(3): The -b option now affects comparisons of bytes with
     int.

   - bpo-23632(4): Memoryviews now allow tuple indexing (including for
     multi-dimensional memoryviews).

   - bpo-23192(5): Fixed generator lambdas.  Patch by Bruno Cauet.

   - bpo-23629(6): Fix the default __sizeof__ implementation for
     variable-sized objects.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23573

   (2) https://bugs.python.org/issue23753

   (3) https://bugs.python.org/issue23681

   (4) https://bugs.python.org/issue23632

   (5) https://bugs.python.org/issue23192

   (6) https://bugs.python.org/issue23629


File: python.info,  Node: 库<87>,  Next: 构建<60>,  Prev: 核心与内置函数<71>,  Up: Python 3 5 0 alpha 3

1.19.87.2 库
............

   - bpo-14260(1): The groupindex attribute of regular expression
     pattern object now is non-modifiable mapping.

   - bpo-23792(2): 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.

   - bpo-23775(3): pprint() of OrderedDict now outputs the same
     representation as repr().

   - bpo-23765(4): Removed IsBadStringPtr calls in ctypes

   - bpo-22364(5): Improved some re error messages using regex for
     hints.

   - bpo-23742(6): ntpath.expandvars() no longer loses unbalanced single
     quotes.

   - bpo-21717(7): The zipfile.ZipFile.open function now supports ’x’
     (exclusive creation) mode.

   - bpo-21802(8): The reader in BufferedRWPair now is closed even when
     closing writer failed in BufferedRWPair.close().

   - bpo-23622(9): Unknown escapes in regular expressions that consist
     of ‘'\'’ and ASCII letter now raise a deprecation warning and will
     be forbidden in Python 3.6.

   - bpo-23671(10): 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.

   - bpo-23502(11): The pprint module now supports mapping proxies.

   - bpo-17530(12): pprint now wraps long bytes objects and bytearrays.

   - bpo-22687(13): Fixed some corner cases in breaking words in
     tetxtwrap.  Got rid of quadratic complexity in breaking long words.

   - bpo-4727(14): The copy module now uses pickle protocol 4 (PEP 3154)
     and supports copying of instances of classes whose __new__ method
     takes keyword-only arguments.

   - bpo-23491(15): 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).

   - bpo-23657(16): Avoid explicit checks for str in zipapp, adding
     support for pathlib.Path objects as arguments.

   - bpo-23688(17): Added support of arbitrary bytes-like objects and
     avoided unnecessary copying of memoryview in gzip.GzipFile.write().
     Original patch by Wolfgang Maier.

   - bpo-23252(18): Added support for writing ZIP files to unseekable
     streams.

   - bpo-23647(19): Increase imaplib’s MAXLINE to accommodate modern
     mailbox sizes.

   - bpo-23539(20): 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.

   - bpo-22351(21): The nntplib.NNTP constructor no longer leaves the
     connection and socket open until the garbage collector cleans them
     up.  Patch by Martin Panter.

   - bpo-23704(22): 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.

   - bpo-23715(23): *note signal.sigwaitinfo(): 772. and *note
     signal.sigtimedwait(): 771. are now retried when interrupted by a
     signal not in the `sigset' parameter, if the signal handler does
     not raise an exception.  signal.sigtimedwait() recomputes the
     timeout with a monotonic clock when it is retried.

   - bpo-23001(24): 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.

   - bpo-23646(25): 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).

   - bpo-23136(26): _strptime now uniformly handles all days in week 0,
     including Dec 30 of previous year.  Based on patch by Jim Carroll.

   - bpo-23700(27): Iterator of NamedTemporaryFile now keeps a reference
     to NamedTemporaryFile instance.  Patch by Bohuslav Kabrda.

   - bpo-22903(28): The fake test case created by unittest.loader when
     it fails importing a test module is now picklable.

   - bpo-22181(29): 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.

   - bpo-2211(30): 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.

   - bpo-18983(31): Allow selection of output units in timeit.  Patch by
     Julian Gindi.

   - bpo-23631(32): Fix traceback.format_list when a traceback has been
     mutated.

   - bpo-23568(33): Add rdivmod support to MagicMock() objects.  Patch
     by Håkan Lövdahl.

   - bpo-2052(34): Add charset parameter to HtmlDiff.make_file().

   - bpo-23668(35): Support os.truncate and os.ftruncate on Windows.

   - bpo-23138(36): Fixed parsing cookies with absent keys or values in
     cookiejar.  Patch by Demian Brecht.

   - bpo-23051(37): multiprocessing.Pool methods imap() and
     imap_unordered() now handle exceptions raised by an iterator.
     Patch by Alon Diamant and Davin Potts.

   - bpo-23581(38): Add matmul support to MagicMock.  Patch by Håkan
     Lövdahl.

   - bpo-23566(39): enable(), register(), dump_traceback() and
     dump_traceback_later() functions of faulthandler now accept file
     descriptors.  Patch by Wei Wu.

   - bpo-22928(40): Disabled HTTP header injections in http.client.
     Original patch by Demian Brecht.

   - bpo-23615(41): Modules bz2, tarfile and tokenize now can be
     reloaded with imp.reload().  Patch by Thomas Kluyver.

   - bpo-23605(42): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue14260

   (2) https://bugs.python.org/issue23792

   (3) https://bugs.python.org/issue23775

   (4) https://bugs.python.org/issue23765

   (5) https://bugs.python.org/issue22364

   (6) https://bugs.python.org/issue23742

   (7) https://bugs.python.org/issue21717

   (8) https://bugs.python.org/issue21802

   (9) https://bugs.python.org/issue23622

   (10) https://bugs.python.org/issue23671

   (11) https://bugs.python.org/issue23502

   (12) https://bugs.python.org/issue17530

   (13) https://bugs.python.org/issue22687

   (14) https://bugs.python.org/issue4727

   (15) https://bugs.python.org/issue23491

   (16) https://bugs.python.org/issue23657

   (17) https://bugs.python.org/issue23688

   (18) https://bugs.python.org/issue23252

   (19) https://bugs.python.org/issue23647

   (20) https://bugs.python.org/issue23539

   (21) https://bugs.python.org/issue22351

   (22) https://bugs.python.org/issue23704

   (23) https://bugs.python.org/issue23715

   (24) https://bugs.python.org/issue23001

   (25) https://bugs.python.org/issue23646

   (26) https://bugs.python.org/issue23136

   (27) https://bugs.python.org/issue23700

   (28) https://bugs.python.org/issue22903

   (29) https://bugs.python.org/issue22181

   (30) https://bugs.python.org/issue2211

   (31) https://bugs.python.org/issue18983

   (32) https://bugs.python.org/issue23631

   (33) https://bugs.python.org/issue23568

   (34) https://bugs.python.org/issue2052

   (35) https://bugs.python.org/issue23668

   (36) https://bugs.python.org/issue23138

   (37) https://bugs.python.org/issue23051

   (38) https://bugs.python.org/issue23581

   (39) https://bugs.python.org/issue23566

   (40) https://bugs.python.org/issue22928

   (41) https://bugs.python.org/issue23615

   (42) https://bugs.python.org/issue23605


File: python.info,  Node: 构建<60>,  Next: 测试<57>,  Prev: 库<87>,  Up: Python 3 5 0 alpha 3

1.19.87.3 构建
..............

   - bpo-23585(1): make patchcheck will ensure the interpreter is built.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23585


File: python.info,  Node: 测试<57>,  Next: 工具/示例<34>,  Prev: 构建<60>,  Up: Python 3 5 0 alpha 3

1.19.87.4 测试
..............

   - bpo-23583(1): Added tests for standard IO streams in IDLE.

   - bpo-22289(2): Prevent test_urllib2net failures due to ftp
     connection timeout.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23583

   (2) https://bugs.python.org/issue22289


File: python.info,  Node: 工具/示例<34>,  Prev: 测试<57>,  Up: Python 3 5 0 alpha 3

1.19.87.5 工具/示例
...................

   - bpo-22826(1): 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).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22826


File: python.info,  Node: Python 3 5 0 alpha 2,  Next: Python 3 5 0 alpha 1,  Prev: Python 3 5 0 alpha 3,  Up: Changelog（更動日誌）

1.19.88 Python 3.5.0 alpha 2
----------------------------

`发布日期: 2015-03-09'

* Menu:

* 核心与内置函数: 核心与内置函数<72>.
* 库: 库<88>.
* 构建: 构建<61>.
* C API: C API<42>.
* Windows: Windows<53>.


File: python.info,  Node: 核心与内置函数<72>,  Next: 库<88>,  Up: Python 3 5 0 alpha 2

1.19.88.1 核心与内置函数
........................

   - bpo-23571(1): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23571


File: python.info,  Node: 库<88>,  Next: 构建<61>,  Prev: 核心与内置函数<72>,  Up: Python 3 5 0 alpha 2

1.19.88.2 库
............

   - bpo-22524(1): New os.scandir() function, part of the PEP 471(2):
     "os.scandir() function – a better and faster directory iterator".
     Patch written by Ben Hoyt.

   - bpo-23103(3): Reduced the memory consumption of IPv4Address and
     IPv6Address.

   - bpo-21793(4): BaseHTTPRequestHandler again logs response code as
     numeric, not as stringified enum.  Patch by Demian Brecht.

   - bpo-23476(5): In the ssl module, enable OpenSSL’s
     X509_V_FLAG_TRUSTED_FIRST flag on certificate stores when it is
     available.

   - bpo-23576(6): Avoid stalling in SSL reads when EOF has been reached
     in the SSL layer but the underlying connection hasn’t been closed.

   - bpo-23504(7): Added an __all__ to the types module.

   - bpo-23563(8): Optimized utility functions in urllib.parse.

   - bpo-7830(9): Flatten nested functools.partial.

   - bpo-20204(10): Added the __module__ attribute to _tkinter classes.

   - bpo-19980(11): Improved help() for non-recognized strings.
     help(’’) now shows the help on str.  help(’help’) now shows the
     help on help().  Original patch by Mark Lawrence.

   - bpo-23521(12): Corrected pure python implementation of timedelta
     division.  Eliminated OverflowError from ‘timedelta * float’ for
     some floats; Corrected rounding in timedelta true division.

   - bpo-21619(13): Popen objects no longer leave a zombie after exit in
     the with statement if the pipe was broken.  Patch by Martin Panter.

   - bpo-22936(14): Make it possible to show local variables in
     tracebacks for both the traceback module and unittest.

   - bpo-15955(15): Add an option to limit the output size in
     bz2.decompress().  Patch by Nikolaus Rath.

   - bpo-6639(16): Module-level turtle functions no longer raise
     TclError after closing the window.

   - bpo-814253(17): Group references and conditional group references
     now work in lookbehind assertions in regular expressions.  (See
     also: bpo-9179(18))

   - bpo-23215(19): Multibyte codecs with custom error handlers that
     ignores errors consumed too much memory and raised SystemError or
     MemoryError.  Original patch by Aleksi Torhamo.

   - bpo-5700(20): io.FileIO() called flush() after closing the file.
     flush() was not called in close() if closefd=False.

   - bpo-23374(21): Fixed pydoc failure with non-ASCII files when stdout
     encoding differs from file system encoding (e.g.  on Mac OS).

   - bpo-23481(22): Remove RC4 from the SSL module’s default cipher
     list.

   - bpo-21548(23): Fix pydoc.synopsis() and pydoc.apropos() on modules
     with empty docstrings.

   - bpo-22885(24): Fixed arbitrary code execution vulnerability in the
     dbm.dumb module.  Original patch by Claudiu Popa.

   - bpo-23239(25): ssl.match_hostname() now supports matching of IP
     addresses.

   - bpo-23146(26): Fix mishandling of absolute Windows paths with
     forward slashes in pathlib.

   - bpo-23096(27): Pickle representation of floats with protocol 0 now
     is the same for both Python and C implementations.

   - bpo-19105(28): pprint now more efficiently uses free space at the
     right.

   - bpo-14910(29): Add allow_abbrev parameter to
     argparse.ArgumentParser.  Patch by Jonathan Paugh, Steven Bethard,
     paul j3 and Daniel Eriksson.

   - bpo-21717(30): tarfile.open() now supports ’x’ (exclusive creation)
     mode.

   - bpo-23344(31): marshal.dumps() is now 20-25% faster on average.

   - bpo-20416(32): marshal.dumps() with protocols 3 and 4 is now 40-50%
     faster on average.

   - bpo-23421(33): Fixed compression in tarfile CLI. Patch by wdv4758h.

   - bpo-23367(34): Fix possible overflows in the unicodedata module.

   - bpo-23361(35): Fix possible overflow in Windows subprocess creation
     code.

   - 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.

   - bpo-19705(36): turtledemo now has a visual sorting algorithm demo.
     Original patch from Jason Yeo.

   - bpo-23801(37): Fix issue where cgi.FieldStorage did not always
     ignore the entire preamble to a multipart body.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22524

   (2) https://www.python.org/dev/peps/pep-0471

   (3) https://bugs.python.org/issue23103

   (4) https://bugs.python.org/issue21793

   (5) https://bugs.python.org/issue23476

   (6) https://bugs.python.org/issue23576

   (7) https://bugs.python.org/issue23504

   (8) https://bugs.python.org/issue23563

   (9) https://bugs.python.org/issue7830

   (10) https://bugs.python.org/issue20204

   (11) https://bugs.python.org/issue19980

   (12) https://bugs.python.org/issue23521

   (13) https://bugs.python.org/issue21619

   (14) https://bugs.python.org/issue22936

   (15) https://bugs.python.org/issue15955

   (16) https://bugs.python.org/issue6639

   (17) https://bugs.python.org/issue814253

   (18) https://bugs.python.org/issue9179

   (19) https://bugs.python.org/issue23215

   (20) https://bugs.python.org/issue5700

   (21) https://bugs.python.org/issue23374

   (22) https://bugs.python.org/issue23481

   (23) https://bugs.python.org/issue21548

   (24) https://bugs.python.org/issue22885

   (25) https://bugs.python.org/issue23239

   (26) https://bugs.python.org/issue23146

   (27) https://bugs.python.org/issue23096

   (28) https://bugs.python.org/issue19105

   (29) https://bugs.python.org/issue14910

   (30) https://bugs.python.org/issue21717

   (31) https://bugs.python.org/issue23344

   (32) https://bugs.python.org/issue20416

   (33) https://bugs.python.org/issue23421

   (34) https://bugs.python.org/issue23367

   (35) https://bugs.python.org/issue23361

   (36) https://bugs.python.org/issue19705

   (37) https://bugs.python.org/issue23801


File: python.info,  Node: 构建<61>,  Next: C API<42>,  Prev: 库<88>,  Up: Python 3 5 0 alpha 2

1.19.88.3 构建
..............

   - bpo-23445(1): pydebug builds now use "gcc -Og" where possible, to
     make the resulting executable faster.

   - bpo-23686(2): 更新OS X 10.5 安装程序以使用OpenSSL 1.0.2a.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23445

   (2) https://bugs.python.org/issue23686


File: python.info,  Node: C API<42>,  Next: Windows<53>,  Prev: 构建<61>,  Up: Python 3 5 0 alpha 2

1.19.88.4 C API
...............

   - bpo-20204(1): Deprecation warning is now raised for builtin types
     without the __module__ attribute.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20204


File: python.info,  Node: Windows<53>,  Prev: C API<42>,  Up: Python 3 5 0 alpha 2

1.19.88.5 Windows
.................

   - bpo-23465(1): Implement PEP 486(2) - Make the Python Launcher aware
     of virtual environments.  Patch by Paul Moore.

   - bpo-23437(3): Make user scripts directory versioned on Windows.
     Patch by Paul Moore.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23465

   (2) https://www.python.org/dev/peps/pep-0486

   (3) https://bugs.python.org/issue23437


File: python.info,  Node: Python 3 5 0 alpha 1,  Prev: Python 3 5 0 alpha 2,  Up: Changelog（更動日誌）

1.19.89 Python 3.5.0 alpha 1
----------------------------

`发布日期: 2015-02-08'

* Menu:

* 核心与内置函数: 核心与内置函数<73>.
* 库: 库<89>.
* IDLE: IDLE<50>.
* 构建: 构建<62>.
* C API: C API<43>.
* 文档: 文档<54>.
* 测试: 测试<58>.
* 工具/示例: 工具/示例<35>.
* Windows: Windows<54>.


File: python.info,  Node: 核心与内置函数<73>,  Next: 库<89>,  Up: Python 3 5 0 alpha 1

1.19.89.1 核心与内置函数
........................

   - bpo-23285(1): PEP 475 - EINTR handling.

   - bpo-22735(2): Fix many edge cases (including crashes) involving
     custom mro() implementations.

   - bpo-22896(3): Avoid using PyObject_AsCharBuffer(),
     PyObject_AsReadBuffer() and PyObject_AsWriteBuffer().

   - bpo-21295(4): Revert some changes (bpo-16795(5)) to AST line
     numbers and column offsets that constituted a regression.

   - bpo-22986(6): Allow changing an object’s __class__ between a
     dynamic type and static type in some cases.

   - bpo-15859(7): 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.

   - bpo-21408(8): The default __ne__() now returns NotImplemented if
     __eq__() returned NotImplemented.  Original patch by Martin Panter.

   - bpo-23321(9): Fixed a crash in str.decode() when error handler
     returned replacement string longer than malformed input data.

   - bpo-22286(10): The "backslashreplace" error handlers now works with
     decoding and translating.

   - bpo-23253(11): Delay-load ShellExecute[AW] in os.startfile for
     reduced startup overhead on Windows.

   - bpo-22038(12): 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.

   - bpo-20284(13): %-interpolation (aka printf) formatting added for
     bytes and bytearray.

   - bpo-23048(14): Fix jumping out of an infinite while loop in the
     pdb.

   - bpo-20335(15): bytes constructor now raises TypeError when encoding
     or errors is specified with non-string argument.  Based on patch by
     Renaud Blanch.

   - bpo-22834(16): If the current working directory ends up being set
     to a non-existent directory then import will no longer raise
     FileNotFoundError.

   - bpo-22869(17): Move the interpreter startup & shutdown code to a
     new dedicated pylifecycle.c module

   - bpo-22847(18): Improve method cache efficiency.

   - bpo-22335(19): Fix crash when trying to enlarge a bytearray to
     0x7fffffff bytes on a 32-bit platform.

   - bpo-22653(20): Fix an assertion failure in debug mode when doing a
     reentrant dict insertion in debug mode.

   - bpo-22643(21): Fix integer overflow in Unicode case operations
     (upper, lower, title, swapcase, casefold).

   - bpo-17636(22): Circular imports involving relative imports are now
     supported.

   - bpo-22604(23): Fix assertion error in debug mode when dividing a
     complex number by (nan+0j).

   - bpo-21052(24): Do not raise ImportWarning when sys.path_hooks or
     sys.meta_path are set to None.

   - bpo-16518(25): Use ’bytes-like object required’ in error messages
     that previously used the far more cryptic "’x’ does not support the
     buffer protocol.

   - bpo-22470(26): Fixed integer overflow issues in "backslashreplace",
     "xmlcharrefreplace", and "surrogatepass" error handlers.

   - bpo-22540(27): speed up ‘PyObject_IsInstance’ and
     ‘PyObject_IsSubclass’ in the common case that the second argument
     has metaclass *note type: 6ff.

   - bpo-18711(28): Add a new ‘PyErr_FormatV’ function, similar to
     ‘PyErr_Format’ but accepting a ‘va_list’ argument.

   - bpo-22520(29): Fix overflow checking when generating the repr of a
     unicode object.

   - bpo-22519(30): Fix overflow checking in PyBytes_Repr.

   - bpo-22518(31): Fix integer overflow issues in latin-1 encoding.

   - bpo-16324(32): _charset parameter of MIMEText now also accepts
     email.charset.Charset instances.  Initial patch by Claude Paroz.

   - bpo-1764286(33): Fix inspect.getsource() to support decorated
     functions.  Patch by Claudiu Popa.

   - bpo-18554(34): os.__all__ includes posix functions.

   - bpo-21391(35): Use os.path.abspath in the shutil module.

   - bpo-11471(36): avoid generating a JUMP_FORWARD instruction at the
     end of an if-block if there is no else-clause.  Original patch by
     Eugene Toder.

   - bpo-22215(37): Now ValueError is raised instead of TypeError when
     str or bytes argument contains not permitted null character or
     byte.

   - bpo-22258(38): Fix the internal function set_inheritable() on
     Illumos.  This platform exposes the function ‘ioctl(FIOCLEX)’, but
     calling it fails with errno is ENOTTY: "Inappropriate ioctl for
     device".  set_inheritable() now falls back to the slower ‘fcntl()’
     (‘F_GETFD’ and then ‘F_SETFD’).

   - bpo-21389(39): Displaying the __qualname__ of the underlying
     function in the repr of a bound method.

   - bpo-22206(40): Using pthread, PyThread_create_key() now sets errno
     to ENOMEM and returns -1 (error) on integer overflow.

   - bpo-20184(41): Argument Clinic based signature introspection added
     for 30 of the builtin functions.

   - bpo-22116(42): C functions and methods (of the
     ’builtin_function_or_method’ type) can now be weakref’ed.  Patch by
     Wei Wu.

   - bpo-22077(43): Improve index error messages for bytearrays, bytes,
     lists, and tuples by adding ’or slices’.  Added ’, not <typename>’
     for bytearrays.  Original patch by Claudiu Popa.

   - bpo-20179(44): Apply Argument Clinic to bytes and bytearray.  Patch
     by Tal Einat.

   - bpo-22082(45): Clear interned strings in slotdefs.

   - 升级 Unicode 数据库到 7.0.0 版本。

   - bpo-21897(46): Fix a crash with the f_locals attribute with closure
     variables when frame.clear() has been called.

   - bpo-21205(47): Add a new ‘__qualname__’ attribute to generator, the
     qualified name, and use it in the representation of a generator
     (‘repr(gen)’).  The default name of the generator (‘__name__’
     attribute) is now get from the function instead of the code.  Use
     ‘gen.gi_code.co_name’ to get the name of the code.

   - bpo-21669(48): 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.

   - bpo-21642(49): In the conditional if-else expression, allow an
     integer written with no space between itself and the ‘else’ keyword
     (e.g.  ‘True if 42else False’) to be valid syntax.

   - bpo-21523(50): 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.

   - bpo-21418(51): Fix a crash in the builtin function super() when
     called without argument and without current frame (ex: embedded
     Python).

   - bpo-21425(52): Fix flushing of standard streams in the interactive
     interpreter.

   - bpo-21435(53): 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.

   - bpo-21377(54): PyBytes_Concat() now tries to concatenate in-place
     when the first argument has a reference count of 1.  Patch by
     Nikolaus Rath.

   - bpo-20355(55): -W command line options now have higher priority
     than the PYTHONWARNINGS environment variable.  Patch by Arfrever.

   - bpo-21274(56): Define PATH_MAX for GNU/Hurd in Python/pythonrun.c.

   - bpo-20904(57): Support setting FPU precision on m68k.

   - bpo-21209(58): Fix sending tuples to custom generator objects with
     the yield from syntax.

   - bpo-21193(59): pow(a, b, c) now raises ValueError rather than
     TypeError when b is negative.  Patch by Josh Rosenberg.

   - bpo-21176(60): PEP 465: Add the ’@’ operator for matrix
     multiplication.

   - bpo-21134(61): Fix segfault when str is called on an uninitialized
     UnicodeEncodeError, UnicodeDecodeError, or UnicodeTranslateError
     object.

   - bpo-19537(62): Fix PyUnicode_DATA() alignment under m68k.  Patch by
     Andreas Schwab.

   - bpo-20929(63): Add a type cast to avoid shifting a negative number.

   - bpo-20731(64): Properly position in source code files even if they
     are opened in text mode.  Patch by Serhiy Storchaka.

   - bpo-20637(65): Key-sharing now also works for instance dictionaries
     of subclasses.  Patch by Peter Ingebretson.

   - bpo-8297(66): Attributes missing from modules now include the
     module name in the error text.  Original patch by ysj.ray.

   - bpo-19995(67): %c, %o, %x, and %X now raise TypeError on
     non-integer input.

   - bpo-19655(68): 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.

   - bpo-12546(69): Allow ‘\x00’ to be used as a fill character when
     using str, int, float, and complex __format__ methods.

   - bpo-20480(70): Add ipaddress.reverse_pointer.  Patch by Leon Weber.

   - bpo-13598(71): 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.

   - bpo-8931(72): 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.

   - bpo-23165(73): Perform overflow checks before allocating memory in
     the _Py_char2wchar function.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23285

   (2) https://bugs.python.org/issue22735

   (3) https://bugs.python.org/issue22896

   (4) https://bugs.python.org/issue21295

   (5) https://bugs.python.org/issue16795

   (6) https://bugs.python.org/issue22986

   (7) https://bugs.python.org/issue15859

   (8) https://bugs.python.org/issue21408

   (9) https://bugs.python.org/issue23321

   (10) https://bugs.python.org/issue22286

   (11) https://bugs.python.org/issue23253

   (12) https://bugs.python.org/issue22038

   (13) https://bugs.python.org/issue20284

   (14) https://bugs.python.org/issue23048

   (15) https://bugs.python.org/issue20335

   (16) https://bugs.python.org/issue22834

   (17) https://bugs.python.org/issue22869

   (18) https://bugs.python.org/issue22847

   (19) https://bugs.python.org/issue22335

   (20) https://bugs.python.org/issue22653

   (21) https://bugs.python.org/issue22643

   (22) https://bugs.python.org/issue17636

   (23) https://bugs.python.org/issue22604

   (24) https://bugs.python.org/issue21052

   (25) https://bugs.python.org/issue16518

   (26) https://bugs.python.org/issue22470

   (27) https://bugs.python.org/issue22540

   (28) https://bugs.python.org/issue18711

   (29) https://bugs.python.org/issue22520

   (30) https://bugs.python.org/issue22519

   (31) https://bugs.python.org/issue22518

   (32) https://bugs.python.org/issue16324

   (33) https://bugs.python.org/issue1764286

   (34) https://bugs.python.org/issue18554

   (35) https://bugs.python.org/issue21391

   (36) https://bugs.python.org/issue11471

   (37) https://bugs.python.org/issue22215

   (38) https://bugs.python.org/issue22258

   (39) https://bugs.python.org/issue21389

   (40) https://bugs.python.org/issue22206

   (41) https://bugs.python.org/issue20184

   (42) https://bugs.python.org/issue22116

   (43) https://bugs.python.org/issue22077

   (44) https://bugs.python.org/issue20179

   (45) https://bugs.python.org/issue22082

   (46) https://bugs.python.org/issue21897

   (47) https://bugs.python.org/issue21205

   (48) https://bugs.python.org/issue21669

   (49) https://bugs.python.org/issue21642

   (50) https://bugs.python.org/issue21523

   (51) https://bugs.python.org/issue21418

   (52) https://bugs.python.org/issue21425

   (53) https://bugs.python.org/issue21435

   (54) https://bugs.python.org/issue21377

   (55) https://bugs.python.org/issue20355

   (56) https://bugs.python.org/issue21274

   (57) https://bugs.python.org/issue20904

   (58) https://bugs.python.org/issue21209

   (59) https://bugs.python.org/issue21193

   (60) https://bugs.python.org/issue21176

   (61) https://bugs.python.org/issue21134

   (62) https://bugs.python.org/issue19537

   (63) https://bugs.python.org/issue20929

   (64) https://bugs.python.org/issue20731

   (65) https://bugs.python.org/issue20637

   (66) https://bugs.python.org/issue8297

   (67) https://bugs.python.org/issue19995

   (68) https://bugs.python.org/issue19655

   (69) https://bugs.python.org/issue12546

   (70) https://bugs.python.org/issue20480

   (71) https://bugs.python.org/issue13598

   (72) https://bugs.python.org/issue8931

   (73) https://bugs.python.org/issue23165


File: python.info,  Node: 库<89>,  Next: IDLE<50>,  Prev: 核心与内置函数<73>,  Up: Python 3 5 0 alpha 1

1.19.89.2 库
............

   - bpo-23399(1): pyvenv creates relative symlinks where possible.

   - bpo-20289(2): cgi.FieldStorage() now supports the context
     management protocol.

   - bpo-13128(3): Print response headers for CONNECT requests when
     debuglevel > 0.  Patch by Demian Brecht.

   - bpo-15381(4): Optimized io.BytesIO to make less allocations and
     copyings.

   - bpo-22818(5): Splitting on a pattern that could match an empty
     string now raises a warning.  Patterns that can only match empty
     strings are now rejected.

   - bpo-23099(6): Closing io.BytesIO with exported buffer is rejected
     now to prevent corrupting exported buffer.

   - bpo-23326(7): Removed __ne__ implementations.  Since fixing default
     __ne__ implementation in bpo-21408(8) they are redundant.

   - bpo-23363(9): Fix possible overflow in itertools.permutations.

   - bpo-23364(10): Fix possible overflow in itertools.product.

   - bpo-23366(11): Fixed possible integer overflow in
     itertools.combinations.

   - bpo-23369(12): Fixed possible integer overflow in
     _json.encode_basestring_ascii.

   - bpo-23353(13): 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.

   - bpo-14099(14): Restored support of writing ZIP files to tellable
     but non-seekable streams.

   - bpo-14099(15): Writing to ZipFile and reading multiple ZipExtFiles
     is threadsafe now.

   - bpo-19361(16): JSON decoder now raises JSONDecodeError instead of
     ValueError.

   - bpo-18518(17): timeit now rejects statements which can’t be
     compiled outside a function or a loop (e.g.  "return" or "break").

   - bpo-23094(18): Fixed readline with frames in Python implementation
     of pickle.

   - bpo-23268(19): Fixed bugs in the comparison of ipaddress classes.

   - bpo-21408(20): Removed incorrect implementations of __ne__() which
     didn’t returned NotImplemented if __eq__() returned NotImplemented.
     The default __ne__() now works correctly.

   - bpo-19996(21): ‘email.feedparser.FeedParser’ now handles
     (malformed) headers with no key rather than assuming the body has
     started.

   - bpo-20188(22): Support Application-Layer Protocol Negotiation
     (ALPN) in the ssl module.

   - bpo-23133(23): Pickling of ipaddress objects now produces more
     compact and portable representation.

   - bpo-23248(24): 从最新的OpenSSL git master更新SSL错误代码。

   - bpo-23266(25): Much faster implementation of
     ipaddress.collapse_addresses() when there are many non-consecutive
     addresses.

   - bpo-23098(26): 64-bit dev_t is now supported in the os module.

   - bpo-21817(27): 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.

   - bpo-15955(28): Add an option to limit output size when
     decompressing LZMA data.  Patch by Nikolaus Rath and Martin Panter.

   - bpo-23250(29): In the http.cookies module, capitalize "HttpOnly"
     and "Secure" as they are written in the standard.

   - bpo-23063(30): In the distutils’ check command, fix parsing of reST
     with code or code-block directives.

   - bpo-23209(31): 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(32))

   - bpo-17911(33): Provide a way to seed the linecache for a PEP-302
     module without actually loading the code.

   - bpo-17911(34): 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.

   - bpo-19777(35): Provide a home() classmethod on Path objects.
     Contributed by Victor Salgado and Mayank Tripathi.

   - bpo-23206(36): Make ‘json.dumps(..., ensure_ascii=False)’ as fast
     as the default case of ‘ensure_ascii=True’.  Patch by Naoki Inada.

   - bpo-23185(37): Add math.inf and math.nan constants.

   - bpo-23186(38): Add ssl.SSLObject.shared_ciphers() and
     ssl.SSLSocket.shared_ciphers() to fetch the client’s list ciphers
     sent at handshake.

   - bpo-23143(39): Remove compatibility with OpenSSLs older than 0.9.8.

   - bpo-23132(40): Improve performance and introspection support of
     comparison methods created by functool.total_ordering.

   - bpo-19776(41): Add an expanduser() method on Path objects.

   - bpo-23112(42): Fix SimpleHTTPServer to correctly carry the query
     string and fragment when it redirects to add a trailing slash.

   - bpo-21793(43): Added http.HTTPStatus enums (i.e.  HTTPStatus.OK,
     HTTPStatus.NOT_FOUND). Patch by Demian Brecht.

   - bpo-23093(44): In the io, module allow more operations to work on
     detached streams.

   - bpo-23111(45): In the ftplib, make ssl.PROTOCOL_SSLv23 the default
     protocol version.

   - bpo-22585(46): On OpenBSD 5.6 and newer, os.urandom() now calls
     getentropy(), instead of reading /dev/urandom, to get pseudo-random
     bytes.

   - bpo-19104(47): pprint now produces evaluable output for wrapped
     strings.

   - bpo-23071(48): Added missing names to codecs.__all__.  Patch by
     Martin Panter.

   - bpo-22783(49): Pickling now uses the NEWOBJ opcode instead of the
     NEWOBJ_EX opcode if possible.

   - bpo-15513(50): Added a __sizeof__ implementation for pickle
     classes.

   - bpo-19858(51): 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.

   - bpo-22095(52): Fixed HTTPConnection.set_tunnel with default port.
     The port value in the host header was set to "None".  Patch by
     Demian Brecht.

   - bpo-23016(53): A warning no longer produces an AttributeError when
     the program is run with pythonw.exe.

   - bpo-21775(54): 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.

   - bpo-1218234(55): Fix inspect.getsource() to load updated source of
     reloaded module.  Initial patch by Berker Peksag.

   - bpo-21740(56): Support wrapped callables in doctest.  Patch by
     Claudiu Popa.

   - bpo-23009(57): Make sure selectors.EpollSelector.select() works
     when no FD is registered.

   - bpo-22959(58): In the constructor of http.client.HTTPSConnection,
     prefer the context’s check_hostname attribute over the
     `check_hostname' parameter.

   - bpo-22696(59): Add function *note sys.is_finalizing(): 851. to know
     about interpreter shutdown.

   - bpo-16043(60): Add a default limit for the amount of data
     xmlrpclib.gzip_decode will return.  This resolves CVE-2013-1753.

   - bpo-14099(61): 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.

   - bpo-22966(62): Fix __pycache__ pyc file name clobber when
     pyc_compile is asked to compile a source file containing multiple
     dots in the source file name.

   - bpo-21971(63): Update turtledemo doc and add module to the index.

   - bpo-21032(64): Fixed socket leak if HTTPConnection.getresponse()
     fails.  Original patch by Martin Panter.

   - bpo-22407(65): Deprecated the use of re.LOCALE flag with str
     patterns or re.ASCII. It was newer worked.

   - bpo-22902(66): The "ip" command is now used on Linux to determine
     MAC address in uuid.getnode().  Pach by Bruno Cauet.

   - bpo-22960(67): Add a context argument to xmlrpclib.ServerProxy
     constructor.

   - bpo-22389(68): Add contextlib.redirect_stderr().

   - bpo-21356(69): Make ssl.RAND_egd() optional to support LibreSSL.
     The availability of the function is checked during the compilation.
     Patch written by Bernard Spil.

   - bpo-22915(70): SAX parser now supports files opened with file
     descriptor or bytes path.

   - bpo-22609(71): Constructors and update methods of mapping classes
     in the collections module now accept the self keyword argument.

   - bpo-22940(72): Add readline.append_history_file.

   - bpo-19676(73): Added the "namereplace" error handler.

   - bpo-22788(74): Add `context' parameter to
     logging.handlers.HTTPHandler.

   - bpo-22921(75): Allow SSLContext to take the `hostname' parameter
     even if OpenSSL doesn’t support SNI.

   - bpo-22894(76): TestCase.subTest() would cause the test suite to be
     stopped when in failfast mode, even in the absence of failures.

   - bpo-22796(77): HTTP cookie parsing is now stricter, in order to
     protect against potential injection attacks.

   - bpo-22370(78): Windows detection in pathlib is now more robust.

   - bpo-22841(79): Reject coroutines in asyncio add_signal_handler().
     Patch by Ludovic.Gasc.

   - bpo-19494(80): Added urllib.request.HTTPBasicPriorAuthHandler.
     Patch by Matej Cepl.

   - bpo-22578(81): Added attributes to the re.error class.

   - bpo-22849(82): Fix possible double free in the io.TextIOWrapper
     constructor.

   - bpo-12728(83): Different Unicode characters having the same
     uppercase but different lowercase are now matched in
     case-insensitive regular expressions.

   - bpo-22821(84): Fixed fcntl() with integer argument on 64-bit
     big-endian platforms.

   - bpo-21650(85): Add an ‘--sort-keys’ option to json.tool CLI.

   - bpo-22824(86): Updated reprlib output format for sets to use set
     literals.  Patch contributed by Berker Peksag.

   - bpo-22824(87): Updated reprlib output format for arrays to display
     empty arrays without an unnecessary empty list.  Suggested by
     Serhiy Storchaka.

   - bpo-22406(88): Fixed the uu_codec codec incorrectly ported to 3.x.
     Based on patch by Martin Panter.

   - bpo-17293(89): uuid.getnode() now determines MAC address on AIX
     using netstat.  Based on patch by Aivars Kalvāns.

   - bpo-22769(90): Fixed ttk.Treeview.tag_has() when called without
     arguments.

   - bpo-22417(91): Verify certificates by default in httplib (PEP 476).

   - bpo-22775(92): Fixed unpickling of http.cookies.SimpleCookie with
     protocol 2 and above.  Patch by Tim Graham.

   - bpo-22776(93): Brought excluded code into the scope of a try block
     in SysLogHandler.emit().

   - bpo-22665(94): Add missing get_terminal_size and SameFileError to
     shutil.__all__.

   - bpo-6623(95): Remove deprecated Netrc class in the ftplib module.
     Patch by Matt Chaput.

   - bpo-17381(96): Fixed handling of case-insensitive ranges in regular
     expressions.

   - bpo-22410(97): Module level functions in the re module now cache
     compiled locale-dependent regular expressions taking into account
     the locale.

   - bpo-22759(98): Query methods on pathlib.Path() (exists(), is_dir(),
     etc.)  now return False when the underlying stat call raises
     NotADirectoryError.

   - bpo-8876(99): distutils now falls back to copying files when hard
     linking doesn’t work.  This allows use with special filesystems
     such as VirtualBox shared folders.

   - bpo-22217(100): Implemented reprs of classes in the zipfile module.

   - bpo-22457(101): Honour load_tests in the start_dir of discovery.

   - bpo-18216(102): gettext now raises an error when a .mo file has an
     unsupported major version number.  Patch by Aaron Hill.

   - bpo-13918(103): 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.

   - bpo-22676(104): Make the pickling of global objects which don’t
     have a __module__ attribute less slow.

   - bpo-18853(105): Fixed ResourceWarning in shlex.__nain__.

   - bpo-9351(106): Defaults set with set_defaults on an argparse
     subparser are no longer ignored when also set on the parent parser.

   - bpo-7559(107): unittest test loading ImportErrors are reported as
     import errors with their import exception rather than as attribute
     errors after the import has already failed.

   - bpo-19746(108): Make it possible to examine the errors from
     unittest discovery without executing the test suite.  The new
     ‘errors’ attribute on TestLoader exposes these non-fatal errors
     encountered during discovery.

   - bpo-21991(109): 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.

   - bpo-22638(110): SSLv3 is now disabled throughout the standard
     library.  It can still be enabled by instantiating a SSLContext
     manually.

   - bpo-22641(111): In asyncio, the default SSL context for client
     connections is now created using ssl.create_default_context(), for
     stronger security.

   - bpo-17401(112): Include closefd in io.FileIO repr.

   - bpo-21338(113): 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.

   - bpo-20152(114): Convert the array and cmath modules to Argument
     Clinic.

   - bpo-18643(115): Add socket.socketpair() on Windows.

   - bpo-22435(116): Fix a file descriptor leak when socketserver bind
     fails.

   - bpo-13096(117): Fixed segfault in CTypes POINTER handling of large
     values.

   - bpo-11694(118): Raise ConversionError in xdrlib as documented.
     Patch by Filip Gruszczyński and Claudiu Popa.

   - bpo-19380(119): Optimized parsing of regular expressions.

   - bpo-1519638(120): Now unmatched groups are replaced with empty
     strings in re.sub() and re.subn().

   - bpo-18615(121): sndhdr.what/whathdr now return a namedtuple.

   - bpo-22462(122): Fix pyexpat’s creation of a dummy frame to make it
     appear in exception tracebacks.

   - bpo-21965(123): Add support for in-memory SSL to the ssl module.
     Patch by Geert Jansen.

   - bpo-21173(124): Fix len() on a WeakKeyDictionary when .clear() was
     called with an iterator alive.

   - bpo-11866(125): Eliminated race condition in the computation of
     names for new threads.

   - bpo-21905(126): Avoid RuntimeError in pickle.whichmodule() when
     sys.modules is mutated while iterating.  Patch by Olivier Grisel.

   - bpo-11271(127): concurrent.futures.Executor.map() now takes a
     `chunksize' argument to allow batching of tasks in child processes
     and improve performance of ProcessPoolExecutor.  Patch by Dan
     O’Reilly.

   - bpo-21883(128): os.path.join() and os.path.relpath() now raise a
     TypeError with more helpful error message for unsupported or
     mismatched types of arguments.

   - bpo-22219(129): The zipfile module CLI now adds entries for
     directories (including empty directories) in ZIP file.

   - bpo-22449(130): In the ssl.SSLContext.load_default_certs, consult
     the environmental variables SSL_CERT_DIR and SSL_CERT_FILE on
     Windows.

   - bpo-22508(131): 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.

   - bpo-20076(132): Added non derived UTF-8 aliases to locale aliases
     table.

   - bpo-20079(133): Added locales supported in glibc 2.18 to locale
     alias table.

   - bpo-20218(134): Added convenience methods read_text/write_text and
     read_bytes/ write_bytes to pathlib.Path objects.

   - bpo-22396(135): On 32-bit AIX platform, don’t expose
     os.posix_fadvise() nor os.posix_fallocate() because their
     prototypes in system headers are wrong.

   - bpo-22517(136): When an io.BufferedRWPair object is deallocated,
     clear its weakrefs.

   - bpo-22437(137): Number of capturing groups in regular expression is
     no longer limited by 100.

   - bpo-17442(138): InteractiveInterpreter now displays the full
     chained traceback in its showtraceback method, to match the built
     in interactive interpreter.

   - bpo-23392(139): Added tests for marshal C API that works with
     FILE*.

   - bpo-10510(140): distutils register and upload methods now use HTML
     standards compliant CRLF line endings.

   - bpo-9850(141): Fixed macpath.join() for empty first component.
     Patch by Oleg Oshmyan.

   - bpo-5309(142): distutils’ build and build_ext commands now accept a
     ‘-j’ option to enable parallel building of extension modules.

   - bpo-22448(143): Improve canceled timer handles cleanup to prevent
     unbound memory usage.  Patch by Joshua Moore-Oliva.

   - bpo-22427(144): TemporaryDirectory no longer attempts to clean up
     twice when used in the with statement in generator.

   - bpo-22362(145): Forbidden ambiguous octal escapes out of range
     0-0o377 in regular expressions.

   - bpo-20912(146): Now directories added to ZIP file have correct Unix
     and MS-DOS directory attributes.

   - bpo-21866(147): ZipFile.close() no longer writes ZIP64 central
     directory records if allowZip64 is false.

   - bpo-22278(148): Fix urljoin problem with relative urls, a
     regression observed after changes to issue22118 were submitted.

   - bpo-22415(149): Fixed debugging output of the GROUPREF_EXISTS
     opcode in the re module.  Removed trailing spaces in debugging
     output.

   - bpo-22423(150): Unhandled exception in thread no longer causes
     unhandled AttributeError when sys.stderr is None.

   - bpo-21332(151): Ensure that ‘bufsize=1’ in subprocess.Popen()
     selects line buffering, rather than block buffering.  Patch by
     Akira Li.

   - bpo-21091(152): Fix API bug:
     email.message.EmailMessage.is_attachment is now a method.

   - bpo-21079(153): Fix email.message.EmailMessage.is_attachment to
     return the correct result when the header has parameters as well as
     a value.

   - bpo-22247(154): Add NNTPError to nntplib.__all__.

   - bpo-22366(155): urllib.request.urlopen will accept a context object
     (SSLContext) as an argument which will then be used for HTTPS
     connection.  Patch by Alex Gaynor.

   - bpo-4180(156): The warnings registries are now reset when the
     filters are modified.

   - bpo-22419(157): 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.

   - 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.

   - bpo-20537(158): logging methods now accept an exception instance as
     well as a Boolean value or exception tuple.  Thanks to Yury
     Selivanov for the patch.

   - bpo-22384(159): An exception in Tkinter callback no longer crashes
     the program when it is run with pythonw.exe.

   - bpo-22168(160): Prevent turtle AttributeError with non-default
     Canvas on OS X.

   - bpo-21147(161): sqlite3 now raises an exception if the request
     contains a null character instead of truncating it.  Based on patch
     by Victor Stinner.

   - bpo-13968(162): The glob module now supports recursive search in
     subdirectories using the ‘**’ pattern.

   - bpo-21951(163): Fixed a crash in Tkinter on AIX when called Tcl
     command with empty string or tuple argument.

   - bpo-21951(164): Tkinter now most likely raises MemoryError instead
     of crash if the memory allocation fails.

   - bpo-22338(165): Fix a crash in the json module on memory allocation
     failure.

   - bpo-12410(166): imaplib.IMAP4 now supports the context management
     protocol.  Original patch by Tarek Ziadé.

   - bpo-21270(167): We now override tuple methods in mock.call objects
     so that they can be used as normal call attributes.

   - bpo-16662(168): 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
     ‘pattern’ is added and documented.  Patch given by Robert Collins,
     tweaked by Barry Warsaw.

   - bpo-22226(169): First letter no longer is stripped from the
     "status" key in the result of Treeview.heading().

   - bpo-19524(170): Fixed resource leak in the HTTP connection when an
     invalid response is received.  Patch by Martin Panter.

   - bpo-20421(171): Add a .version() method to SSL sockets exposing the
     actual protocol version in use.

   - bpo-19546(172): configparser exceptions no longer expose
     implementation details.  Chained KeyErrors are removed, which leads
     to cleaner tracebacks.  Patch by Claudiu Popa.

   - bpo-22051(173): 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.

   - bpo-21933(174): Turtledemo users can change the code font size with
     a menu selection or control(command) ’-’ or ’+’ or
     control-mousewheel.  Original patch by Lita Cho.

   - bpo-21597(175): 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.

   - bpo-18132(176): Turtledemo buttons no longer disappear when the
     window is shrunk.  Original patches by Jan Kanis and Lita Cho.

   - bpo-22043(177): time.monotonic() is now always available.
     ‘threading.Lock.acquire()’, ‘threading.RLock.acquire()’ and socket
     operations now use a monotonic clock, instead of the system clock,
     when a timeout is used.

   - bpo-21527(178): Add a default number of workers to
     ThreadPoolExecutor equal to 5 times the number of CPUs.  Patch by
     Claudiu Popa.

   - bpo-22216(179): 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.

   - bpo-22098(180): ctypes’ BigEndianStructure and
     LittleEndianStructure now define an empty __slots__ so that
     subclasses don’t always get an instance dict.  Patch by Claudiu
     Popa.

   - bpo-22185(181): Fix an occasional RuntimeError in
     threading.Condition.wait() caused by mutation of the waiters queue
     without holding the lock.  Patch by Doug Zongker.

   - bpo-22287(182): 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).

   - bpo-22182(183): Use e.args to unpack exceptions correctly in
     distutils.file_util.move_file.  Patch by Claudiu Popa.

   - The webbrowser module now uses subprocess’s start_new_session=True
     rather than a potentially risky preexec_fn=os.setsid call.

   - bpo-22042(184): signal.set_wakeup_fd(fd) now raises an exception if
     the file descriptor is in blocking mode.

   - bpo-16808(185): inspect.stack() now returns a named tuple instead
     of a tuple.  Patch by Daniel Shahaf.

   - bpo-22236(186): Fixed Tkinter images copying operations in
     NoDefaultRoot mode.

   - bpo-2527(187): Add a `globals' argument to timeit functions, in
     order to override the globals namespace in which the timed code is
     executed.  Patch by Ben Roberts.

   - bpo-22118(188): Switch urllib.parse to use RFC 3986 semantics for
     the resolution of relative URLs, rather than RFCs 1808 and 2396.
     Patch by Demian Brecht.

   - bpo-21549(189): Added the "members" parameter to TarFile.list().

   - bpo-19628(190): Allow compileall recursion depth to be specified
     with a -r option.

   - bpo-15696(191): Add a __sizeof__ implementation for mmap objects on
     Windows.

   - bpo-22068(192): Avoided reference loops with Variables and Fonts in
     Tkinter.

   - bpo-22165(193): SimpleHTTPRequestHandler now supports undecodable
     file names.

   - bpo-15381(194): Optimized line reading in io.BytesIO.

   - bpo-8797(195): Raise HTTPError on failed Basic Authentication
     immediately.  Initial patch by Sam Bull.

   - bpo-20729(196): Restored the use of lazy
     iterkeys()/itervalues()/iteritems() in the mailbox module.

   - bpo-21448(197): Changed FeedParser feed() to avoid O(N^2) behavior
     when parsing long line.  Original patch by Raymond Hettinger.

   - bpo-22184(198): The functools LRU Cache decorator factory now gives
     an earlier and clearer error message when the user forgets the
     required parameters.

   - bpo-17923(199): glob() patterns ending with a slash no longer match
     non-dirs on AIX. Based on patch by Delhallt.

   - bpo-21725(200): Added support for RFC 6531 (SMTPUTF8) in smtpd.

   - bpo-22176(201): Update the ctypes module’s libffi to v3.1.  This
     release adds support for the Linux AArch64 and POWERPC ELF ABIv2
     little endian architectures.

   - bpo-5411(202): Added support for the "xztar" format in the shutil
     module.

   - bpo-21121(203): Don’t force 3rd party C extensions to be built with
     -Werror=declaration-after-statement.

   - bpo-21975(204): Fixed crash when using uninitialized sqlite3.Row
     (in particular when unpickling pickled sqlite3.Row).  sqlite3.Row
     is now initialized in the __new__() method.

   - bpo-20170(205): Convert posixmodule to use Argument Clinic.

   - bpo-21539(206): Add an `exists_ok' argument to ‘Pathlib.mkdir()’ to
     mimic ‘mkdir -p’ and *note os.makedirs(): 4c3. functionality.  When
     true, ignore FileExistsErrors.  Patch by Berker Peksag.

   - bpo-22127(207): Bypass IDNA for pure-ASCII host names in the socket
     module (in particular for numeric IPs).

   - bpo-21047(208): set the default value for the `convert_charrefs'
     argument of HTMLParser to True.  Patch by Berker Peksag.

   - 在 html.entities 包中增加 __all__ 变量。

   - bpo-15114(209): the strict mode and argument of HTMLParser,
     HTMLParser.error, and the HTMLParserError exception have been
     removed.

   - bpo-22085(210): 在 Tkinter 中删除了对 TK 8.3 的支持。

   - bpo-21580(211): Now Tkinter correctly handles bytes arguments
     passed to Tk.  In particular this allows initializing images from
     binary data.

   - bpo-22003(212): 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.

   - bpo-22018(213): On Windows, signal.set_wakeup_fd() now also
     supports sockets.  A side effect is that Python depends to the
     WinSock library.

   - bpo-22054(214): 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.

   - bpo-17172(215): Make turtledemo start as active on OS X even when
     run with subprocess.  Patch by Lita Cho.

   - bpo-21704(216): Fix build error for _multiprocessing when
     semaphores are not available.  Patch by Arfrever Frehtes Taifersar
     Arahesis.

   - bpo-20173(217): Convert sha1, sha256, sha512 and md5 to
     ArgumentClinic.  Patch by Vajrasky Kok.

   - Fix repr(_socket.socket) on Windows 64-bit: don’t fail with
     OverflowError on closed socket.  repr(socket.socket) already works
     fine.

   - bpo-22033(218): Reprs of most Python implemented classes now
     contain actual class name instead of hardcoded one.

   - bpo-21947(219): The dis module can now disassemble
     generator-iterator objects based on their gi_code attribute.  Patch
     by Clement Rouault.

   - bpo-16133(220): The asynchat.async_chat.handle_read() method now
     ignores BlockingIOError exceptions.

   - bpo-22044(221): Fixed premature DECREF in call_tzinfo_method.
     Patch by Tom Flanagan.

   - bpo-19884(222): readline: Disable the meta modifier key if stdout
     is not a terminal to not write the ANSI sequence ‘"\033[1034h"’
     into stdout.  This sequence is used on some terminal (ex:
     TERM=xterm-256color") to enable support of 8 bit characters.

   - bpo-4350(223): Removed a number of out-of-dated and non-working for
     a long time Tkinter methods.

   - bpo-6167(224): Scrollbar.activate() now returns the name of active
     element if the argument is not specified.  Scrollbar.set() now
     always accepts only 2 arguments.

   - bpo-15275(225): Clean up and speed up the ntpath module.

   - bpo-21888(226): plistlib’s load() and loads() now work if the fmt
     parameter is specified.

   - bpo-22032(227): __qualname__ instead of __name__ is now always used
     to format fully qualified class names of Python implemented
     classes.

   - bpo-22031(228): Reprs now always use hexadecimal format with the
     "0x" prefix when contain an id in form " at 0x...".

   - bpo-22018(229): signal.set_wakeup_fd() now raises an OSError
     instead of a ValueError on ‘fstat()’ failure.

   - bpo-21044(230): tarfile.open() now handles fileobj with an integer
     ’name’ attribute.  Based on patch by Antoine Pietri.

   - bpo-21966(231): Respect -q command-line option when code module is
     ran.

   - bpo-19076(232): Don’t pass the redundant ’file’ argument to
     self.error().

   - bpo-16382(233): Improve exception message of warnings.warn() for
     bad category.  Initial patch by Phil Elson.

   - bpo-21932(234): os.read() now uses a ‘Py_ssize_t()’ type instead of
     ‘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.

   - bpo-21942(235): Fixed source file viewing in pydoc’s server mode on
     Windows.

   - bpo-11259(236): asynchat.async_chat().set_terminator() now raises a
     ValueError if the number of received bytes is negative.

   - bpo-12523(237): asynchat.async_chat.push() now raises a TypeError
     if it doesn’t get a bytes string

   - bpo-21707(238): Add missing kwonlyargcount argument to
     ModuleFinder.replace_paths_in_code().

   - bpo-20639(239): calling Path.with_suffix(’’) allows removing the
     suffix again.  Patch by July Tikhonov.

   - bpo-21714(240): Disallow the construction of invalid paths using
     Path.with_name().  Original patch by Antony Lee.

   - bpo-15014(241): Added ’auth’ method to smtplib to make implementing
     auth mechanisms simpler, and used it internally in the login
     method.

   - bpo-21151(242): Fixed a segfault in the winreg module when ‘None’
     is passed as a ‘REG_BINARY’ value to SetValueEx.  Patch by John
     Ehresman.

   - bpo-21090(243): 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.

   - bpo-5800(244): headers parameter of wsgiref.headers.Headers is now
     optional.  Initial patch by Pablo Torres Navarrete and SilentGhost.

   - bpo-21781(245): ssl.RAND_add() now supports strings longer than 2
     GB.

   - bpo-21679(246): Prevent extraneous fstat() calls during open().
     Patch by Bohuslav Kabrda.

   - bpo-21863(247): cProfile now displays the module name of C
     extension functions, in addition to their own name.

   - bpo-11453(248): 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.

   - bpo-21858(249): Better handling of Python exceptions in the sqlite3
     module.

   - bpo-21476(250): Make sure the email.parser.BytesParser
     TextIOWrapper is discarded after parsing, so the input file isn’t
     unexpectedly closed.

   - bpo-20295(251): imghdr now recognizes OpenEXR format images.

   - bpo-21729(252): Used the "with" statement in the dbm.dumb module to
     ensure files closing.  Patch by Claudiu Popa.

   - bpo-21491(253): socketserver: Fix a race condition in child
     processes reaping.

   - bpo-21719(254): Added the ‘st_file_attributes’ field to
     os.stat_result on Windows.

   - bpo-21832(255): Require named tuple inputs to be exact strings.

   - bpo-21722(256): The distutils "upload" command now exits with a
     non-zero return code when uploading fails.  Patch by Martin
     Dengler.

   - bpo-21723(257): asyncio.Queue: support any type of number (ex:
     float) for the maximum size.  Patch written by Vajrasky Kok.

   - bpo-21711(258): support for "site-python" directories has now been
     removed from the site module (it was deprecated in 3.4).

   - bpo-17552(259): 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’.

   - bpo-18039(260): dbm.dump.open() now always creates a new database
     when the flag has the value ’n’.  Patch by Claudiu Popa.

   - bpo-21326(261): 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.

   - bpo-21766(262): Prevent a security hole in CGIHTTPServer by URL
     unquoting paths before checking for a CGI script at that path.

   - bpo-21310(263): Fixed possible resource leak in failed open().

   - bpo-21256(264): Printout of keyword args should be in deterministic
     order in a mock function call.  This will help to write better
     doctests.

   - bpo-21677(265): Fixed chaining nonnormalized exceptions in io
     close() methods.

   - bpo-11709(266): Fix the pydoc.help function to not fail when
     sys.stdin is not a valid file.

   - bpo-21515(267): tempfile.TemporaryFile now uses os.O_TMPFILE flag
     is available.

   - bpo-13223(268): Fix pydoc.writedoc so that the HTML documentation
     for methods that use ’self’ in the example code is generated
     correctly.

   - bpo-21463(269): In urllib.request, fix pruning of the FTP cache.

   - bpo-21618(270): 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.

   - bpo-20383(271): Introduce importlib.util.module_from_spec() as the
     preferred way to create a new module.

   - bpo-21552(272): Fixed possible integer overflow of too long string
     lengths in the tkinter module on 64-bit platforms.

   - bpo-14315(273): 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.

   - bpo-13742(274): Added "key" and "reverse" parameters to
     heapq.merge().  (First draft of patch contributed by Simon Sapin.)

   - bpo-21402(275): tkinter.ttk now works when default root window is
     not set.

   - bpo-3015(276): _tkinter.create() now creates tkapp object with
     wantobject=1 by default.

   - bpo-10203(277): sqlite3.Row now truly supports sequence protocol.
     In particular it supports reverse() and negative indices.  Original
     patch by Claudiu Popa.

   - bpo-18807(278): If copying (no symlinks) specified for a venv, then
     the python interpreter aliases (python, python3) are now created by
     copying rather than symlinking.

   - bpo-20197(279): Added support for the WebP image type in the imghdr
     module.  Patch by Fabrice Aneche and Claudiu Popa.

   - bpo-21513(280): Speedup some properties of IP addresses
     (IPv4Address, IPv6Address) such as .is_private or .is_multicast.

   - bpo-21137(281): Improve the repr for threading.Lock() and its
     variants by showing the "locked" or "unlocked" status.  Patch by
     Berker Peksag.

   - bpo-21538(282): The plistlib module now supports loading of binary
     plist files when reference or offset size is not a power of two.

   - bpo-21455(283): Add a default backlog to socket.listen().

   - bpo-21525(284): Most Tkinter methods which accepted tuples now
     accept lists too.

   - bpo-22166(285): 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

   - bpo-22236(286): Tkinter tests now don’t reuse default root window.
     New root window is created for every test class.

   - bpo-10744(287): Fix PEP 3118(288) format strings on ctypes objects
     with a nontrivial shape.

   - bpo-20826(289): Optimize ipaddress.collapse_addresses().

   - bpo-21487(290): Optimize ipaddress.summarize_address_range() and
     ipaddress.{IPv4Network,IPv6Network}.subnets().

   - bpo-21486(291): Optimize parsing of netmasks in
     ipaddress.IPv4Network and ipaddress.IPv6Network.

   - bpo-13916(292): Disallowed the surrogatepass error handler for non
     UTF-* encodings.

   - bpo-20998(293): Fixed re.fullmatch() of repeated single character
     pattern with ignore case.  Original patch by Matthew Barnett.

   - bpo-21075(294): fileinput.FileInput now reads bytes from standard
     stream if binary mode is specified.  Patch by Sam Kimbrel.

   - bpo-19775(295): Add a samefile() method to pathlib Path objects.
     Initial patch by Vajrasky Kok.

   - bpo-21226(296): Set up modules properly in
     PyImport_ExecCodeModuleObject (and friends).

   - bpo-21398(297): Fix a unicode error in the pydoc pager when the
     documentation contains characters not encodable to the stdout
     encoding.

   - bpo-16531(298): ipaddress.IPv4Network and ipaddress.IPv6Network now
     accept an (address, netmask) tuple argument, so as to easily
     construct network objects from existing addresses.

   - bpo-21156(299): importlib.abc.InspectLoader.source_to_code() is now
     a staticmethod.

   - bpo-21424(300): Simplified and optimized heaqp.nlargest() and
     nmsmallest() to make fewer tuple comparisons.

   - bpo-21396(301): Fix TextIOWrapper(..., write_through=True) to not
     force a flush() on the underlying binary stream.  Patch by akira.

   - bpo-18314(302): Unlink now removes junctions on Windows.  Patch by
     Kim Gräsman

   - bpo-21088(303): Bugfix for curses.window.addch() regression in
     3.4.0.  In porting to Argument Clinic, the first two arguments were
     reversed.

   - bpo-21407(304): _decimal: The module now supports function
     signatures.

   - bpo-10650(305): Remove the non-standard ’watchexp’ parameter from
     the Decimal.quantize() method in the Python version.  It had never
     been present in the C version.

   - bpo-21469(306): 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().

   - bpo-19414(307): Have the OrderedDict mark deleted links as
     unusable.  This gives an early failure if the link is deleted
     during iteration.

   - bpo-21421(308): Add __slots__ to the MappingViews ABC. Patch by
     Josh Rosenberg.

   - bpo-21101(309): Eliminate double hashing in the C speed-up code for
     collections.Counter().

   - bpo-21321(310): itertools.islice() now releases the reference to
     the source iterator when the slice is exhausted.  Patch by Anton
     Afanasyev.

   - bpo-21057(311): 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.

   - bpo-20951(312): 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.

   - bpo-13248(313): removed previously deprecated asyncore.dispatcher
     __getattr__ cheap inheritance hack.

   - bpo-9815(314): assertRaises now tries to clear references to local
     variables in the exception’s traceback.

   - bpo-19940(315): ssl.cert_time_to_seconds() now interprets the given
     time string in the UTC timezone (as specified in RFC 5280), not the
     local timezone.

   - bpo-13204(316): Calling sys.flags.__new__ would crash the
     interpreter, now it raises a TypeError.

   - bpo-19385(317): Make operations on a closed dbm.dumb database
     always raise the same exception.

   - bpo-21207(318): Detect when the os.urandom cached fd has been
     closed or replaced, and open it anew.

   - bpo-21291(319): 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.

   - bpo-21127(320): Path objects can now be instantiated from str
     subclass instances (such as ‘numpy.str_’).

   - bpo-15002(321): urllib.response object to use _TemporaryFileWrapper
     (and _TemporaryFileCloser) facility.  Provides a better way to
     handle file descriptor close.  Patch contributed by Christian
     Theune.

   - bpo-12220(322): mindom now raises a custom ValueError indicating it
     doesn’t support spaces in URIs instead of letting a ’split’
     ValueError bubble up.

   - bpo-21068(323): The ssl.PROTOCOL* constants are now enum members.

   - bpo-21276(324): posixmodule: Don’t define USE_XATTRS on KFreeBSD
     and the Hurd.

   - bpo-21262(325): New method assert_not_called for Mock.  It raises
     AssertionError if the mock has been called.

   - bpo-21238(326): New keyword argument ‘unsafe’ to Mock.  It raises
     *note AttributeError: 4a1. incase of an attribute startswith assert
     or assret.

   - bpo-20896(327): ssl.get_server_certificate() now uses
     PROTOCOL_SSLv23, not PROTOCOL_SSLv3, for maximum compatibility.

   - bpo-21239(328): patch.stopall() didn’t work deterministically when
     the same name was patched more than once.

   - bpo-21203(329): Updated fileConfig and dictConfig to remove
     inconsistencies.  Thanks to Jure Koren for the patch.

   - bpo-21222(330): Passing name keyword argument to
     mock.create_autospec now works.

   - bpo-21197(331): Add lib64 -> lib symlink in venvs on 64-bit non-OS
     X POSIX.

   - bpo-17498(332): 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.

   - bpo-17826(333): setting an iterable side_effect on a mock function
     created by create_autospec now works.  Patch by Kushal Das.

   - bpo-7776(334): Fix ‘Host:’ header and reconnection when using
     http.client.HTTPConnection.set_tunnel().  Patch by Nikolaus Rath.

   - bpo-20968(335): unittest.mock.MagicMock now supports division.
     Patch by Johannes Baiter.

   - bpo-21529(336): Fix arbitrary memory access in
     JSONDecoder.raw_decode with a negative second parameter.  Bug
     reported by Guido Vranken.  (See also: CVE-2014-4616)

   - bpo-21169(337): getpass now handles non-ascii characters that the
     input stream encoding cannot encode by re-encoding using the
     replace error handler.

   - bpo-21171(338): Fixed undocumented filter API of the rot13 codec.
     Patch by Berker Peksag.

   - bpo-20539(339): Improved math.factorial error message for large
     positive inputs and changed exception type (OverflowError ->
     ValueError) for large negative inputs.

   - bpo-21172(340): isinstance check relaxed from dict to
     collections.Mapping.

   - bpo-21155(341): asyncio.EventLoop.create_unix_server() now raises a
     ValueError if path and sock are specified at the same time.

   - bpo-21136(342): Avoid unnecessary normalization of Fractions
     resulting from power and other operations.  Patch by Raymond
     Hettinger.

   - bpo-17621(343): Introduce importlib.util.LazyLoader.

   - bpo-21076(344): signal module constants were turned into enums.
     Patch by Giampaolo Rodola’.

   - bpo-20636(345): Improved the repr of Tkinter widgets.

   - bpo-19505(346): The items, keys, and values views of OrderedDict
     now support reverse iteration using reversed().

   - bpo-21149(347): Improved thread-safety in logging cleanup during
     interpreter shutdown.  Thanks to Devin Jeanpierre for the patch.

   - bpo-21058(348): Fix a leak of file descriptor in *note
     tempfile.NamedTemporaryFile(): e0e, close the file descriptor if
     *note io.open(): 74d. fails

   - bpo-21200(349): Return None from pkgutil.get_loader() when __spec__
     is missing.

   - bpo-21013(350): Enhance ssl.create_default_context() when used for
     server side sockets to provide better security by default.

   - bpo-20145(351): ‘assertRaisesRegex’ and ‘assertWarnsRegex’ now
     raise a TypeError if the second argument is not a string or
     compiled regex.

   - bpo-20633(352): Replace relative import by absolute import.

   - bpo-20980(353): Stop wrapping exception when using ThreadPool.

   - bpo-21082(354): In os.makedirs, do not set the process-wide umask.
     Note this changes behavior of makedirs when exist_ok=True.

   - bpo-20990(355): Fix issues found by pyflakes for multiprocessing.

   - bpo-21015(356): 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".

   - bpo-21000(357): Improve the command-line interface of json.tool.

   - bpo-20995(358): Enhance default ciphers used by the ssl module to
     enable better security and prioritize perfect forward secrecy.

   - bpo-20884(359): Don’t assume that __file__ is defined on
     importlib.__init__.

   - bpo-21499(360): Ignore __builtins__ in several
     test_importlib.test_api tests.

   - bpo-20627(361): xmlrpc.client.ServerProxy is now a context manager.

   - bpo-19165(362): The formatter module now raises DeprecationWarning
     instead of PendingDeprecationWarning.

   - bpo-13936(363): Remove the ability of datetime.time instances to be
     considered false in boolean contexts.

   - bpo-18931(364): selectors module now supports /dev/poll on Solaris.
     Patch by Giampaolo Rodola’.

   - bpo-19977(365): When the ‘LC_TYPE’ locale is the POSIX locale (‘C’
     locale), *note sys.stdin: 41e. and *note sys.stdout: 41f. are now
     using the ‘surrogateescape’ error handler, instead of the ‘strict’
     error handler.

   - bpo-20574(366): Implement incremental decoder for cp65001 code
     (Windows code page 65001, Microsoft UTF-8).

   - bpo-20879(367): 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.

   - bpo-19157(368): Include the broadcast address in the usuable hosts
     for IPv6 in ipaddress.

   - bpo-11599(369): 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.

   - bpo-4931(370): distutils should not produce unhelpful "error: None"
     messages anymore.  distutils.util.grok_environment_error is kept
     but doc-deprecated.

   - bpo-20875(371): Prevent possible gzip "’read’ is not defined"
     NameError.  Patch by Claudiu Popa.

   - bpo-11558(372): ‘email.message.Message.attach’ now returns a more
     useful error message if ‘attach’ is called on a message for which
     ‘is_multipart’ is False.

   - bpo-20283(373): RE pattern methods now accept the string keyword
     parameters as documented.  The pattern and source keyword
     parameters are left as deprecated aliases.

   - bpo-20778(374): Fix modulefinder to work with bytecode-only
     modules.

   - bpo-20791(375): copy.copy() now doesn’t make a copy when the input
     is a bytes object.  Initial patch by Peter Otten.

   - bpo-19748(376): On AIX, time.mktime() now raises an OverflowError
     for year outsize range [1902; 2037].

   - bpo-19573(377): inspect.signature: Use enum for parameter kind
     constants.

   - bpo-20726(378): inspect.signature: Make Signature and Parameter
     picklable.

   - bpo-17373(379): Add inspect.Signature.from_callable method.

   - bpo-20378(380): Improve repr of inspect.Signature and
     inspect.Parameter.

   - bpo-20816(381): Fix inspect.getcallargs() to raise correct
     TypeError for missing keyword-only arguments.  Patch by Jeremiah
     Lowin.

   - bpo-20817(382): Fix inspect.getcallargs() to fail correctly if more
     than 3 arguments are missing.  Patch by Jeremiah Lowin.

   - bpo-6676(383): 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)

   - bpo-21117(384): 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.

   - bpo-20334(385): inspect.Signature and inspect.Parameter are now
     hashable.  Thanks to Antony Lee for bug reports and suggestions.

   - bpo-15916(386): doctest.DocTestSuite returns an empty
     unittest.TestSuite instead of raising ValueError if it finds no
     tests

   - bpo-21209(387): Fix asyncio.tasks.CoroWrapper to workaround a bug
     in yield-from implementation in CPythons prior to 3.4.1.

   - asyncio: Add gi_{frame,running,code} properties to CoroWrapper
     (upstream bpo-163(388)).

   - bpo-21311(389): Avoid exception in _osx_support with non-standard
     compiler configurations.  Patch by John Szakmeister.

   - bpo-11571(390): Ensure that the turtle window becomes the topmost
     window when launched on OS X.

   - bpo-21801(391): Validate that __signature__ is None or an instance
     of Signature.

   - bpo-21923(392): Prevent AttributeError in
     distutils.sysconfig.customize_compiler due to possible
     uninitialized _config_vars.

   - bpo-21323(393): Fix http.server to again handle scripts in CGI
     subdirectories, broken by the fix for security bpo-19435(394).
     Patch by Zach Byrne.

   - bpo-22733(395): Fix ffi_prep_args not zero-extending argument
     values correctly on 64-bit Windows.

   - bpo-23302(396): 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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23399

   (2) https://bugs.python.org/issue20289

   (3) https://bugs.python.org/issue13128

   (4) https://bugs.python.org/issue15381

   (5) https://bugs.python.org/issue22818

   (6) https://bugs.python.org/issue23099

   (7) https://bugs.python.org/issue23326

   (8) https://bugs.python.org/issue21408

   (9) https://bugs.python.org/issue23363

   (10) https://bugs.python.org/issue23364

   (11) https://bugs.python.org/issue23366

   (12) https://bugs.python.org/issue23369

   (13) https://bugs.python.org/issue23353

   (14) https://bugs.python.org/issue14099

   (15) https://bugs.python.org/issue14099

   (16) https://bugs.python.org/issue19361

   (17) https://bugs.python.org/issue18518

   (18) https://bugs.python.org/issue23094

   (19) https://bugs.python.org/issue23268

   (20) https://bugs.python.org/issue21408

   (21) https://bugs.python.org/issue19996

   (22) https://bugs.python.org/issue20188

   (23) https://bugs.python.org/issue23133

   (24) https://bugs.python.org/issue23248

   (25) https://bugs.python.org/issue23266

   (26) https://bugs.python.org/issue23098

   (27) https://bugs.python.org/issue21817

   (28) https://bugs.python.org/issue15955

   (29) https://bugs.python.org/issue23250

   (30) https://bugs.python.org/issue23063

   (31) https://bugs.python.org/issue23209

   (32) https://bugs.python.org/issue23225

   (33) https://bugs.python.org/issue17911

   (34) https://bugs.python.org/issue17911

   (35) https://bugs.python.org/issue19777

   (36) https://bugs.python.org/issue23206

   (37) https://bugs.python.org/issue23185

   (38) https://bugs.python.org/issue23186

   (39) https://bugs.python.org/issue23143

   (40) https://bugs.python.org/issue23132

   (41) https://bugs.python.org/issue19776

   (42) https://bugs.python.org/issue23112

   (43) https://bugs.python.org/issue21793

   (44) https://bugs.python.org/issue23093

   (45) https://bugs.python.org/issue23111

   (46) https://bugs.python.org/issue22585

   (47) https://bugs.python.org/issue19104

   (48) https://bugs.python.org/issue23071

   (49) https://bugs.python.org/issue22783

   (50) https://bugs.python.org/issue15513

   (51) https://bugs.python.org/issue19858

   (52) https://bugs.python.org/issue22095

   (53) https://bugs.python.org/issue23016

   (54) https://bugs.python.org/issue21775

   (55) https://bugs.python.org/issue1218234

   (56) https://bugs.python.org/issue21740

   (57) https://bugs.python.org/issue23009

   (58) https://bugs.python.org/issue22959

   (59) https://bugs.python.org/issue22696

   (60) https://bugs.python.org/issue16043

   (61) https://bugs.python.org/issue14099

   (62) https://bugs.python.org/issue22966

   (63) https://bugs.python.org/issue21971

   (64) https://bugs.python.org/issue21032

   (65) https://bugs.python.org/issue22407

   (66) https://bugs.python.org/issue22902

   (67) https://bugs.python.org/issue22960

   (68) https://bugs.python.org/issue22389

   (69) https://bugs.python.org/issue21356

   (70) https://bugs.python.org/issue22915

   (71) https://bugs.python.org/issue22609

   (72) https://bugs.python.org/issue22940

   (73) https://bugs.python.org/issue19676

   (74) https://bugs.python.org/issue22788

   (75) https://bugs.python.org/issue22921

   (76) https://bugs.python.org/issue22894

   (77) https://bugs.python.org/issue22796

   (78) https://bugs.python.org/issue22370

   (79) https://bugs.python.org/issue22841

   (80) https://bugs.python.org/issue19494

   (81) https://bugs.python.org/issue22578

   (82) https://bugs.python.org/issue22849

   (83) https://bugs.python.org/issue12728

   (84) https://bugs.python.org/issue22821

   (85) https://bugs.python.org/issue21650

   (86) https://bugs.python.org/issue22824

   (87) https://bugs.python.org/issue22824

   (88) https://bugs.python.org/issue22406

   (89) https://bugs.python.org/issue17293

   (90) https://bugs.python.org/issue22769

   (91) https://bugs.python.org/issue22417

   (92) https://bugs.python.org/issue22775

   (93) https://bugs.python.org/issue22776

   (94) https://bugs.python.org/issue22665

   (95) https://bugs.python.org/issue6623

   (96) https://bugs.python.org/issue17381

   (97) https://bugs.python.org/issue22410

   (98) https://bugs.python.org/issue22759

   (99) https://bugs.python.org/issue8876

   (100) https://bugs.python.org/issue22217

   (101) https://bugs.python.org/issue22457

   (102) https://bugs.python.org/issue18216

   (103) https://bugs.python.org/issue13918

   (104) https://bugs.python.org/issue22676

   (105) https://bugs.python.org/issue18853

   (106) https://bugs.python.org/issue9351

   (107) https://bugs.python.org/issue7559

   (108) https://bugs.python.org/issue19746

   (109) https://bugs.python.org/issue21991

   (110) https://bugs.python.org/issue22638

   (111) https://bugs.python.org/issue22641

   (112) https://bugs.python.org/issue17401

   (113) https://bugs.python.org/issue21338

   (114) https://bugs.python.org/issue20152

   (115) https://bugs.python.org/issue18643

   (116) https://bugs.python.org/issue22435

   (117) https://bugs.python.org/issue13096

   (118) https://bugs.python.org/issue11694

   (119) https://bugs.python.org/issue19380

   (120) https://bugs.python.org/issue1519638

   (121) https://bugs.python.org/issue18615

   (122) https://bugs.python.org/issue22462

   (123) https://bugs.python.org/issue21965

   (124) https://bugs.python.org/issue21173

   (125) https://bugs.python.org/issue11866

   (126) https://bugs.python.org/issue21905

   (127) https://bugs.python.org/issue11271

   (128) https://bugs.python.org/issue21883

   (129) https://bugs.python.org/issue22219

   (130) https://bugs.python.org/issue22449

   (131) https://bugs.python.org/issue22508

   (132) https://bugs.python.org/issue20076

   (133) https://bugs.python.org/issue20079

   (134) https://bugs.python.org/issue20218

   (135) https://bugs.python.org/issue22396

   (136) https://bugs.python.org/issue22517

   (137) https://bugs.python.org/issue22437

   (138) https://bugs.python.org/issue17442

   (139) https://bugs.python.org/issue23392

   (140) https://bugs.python.org/issue10510

   (141) https://bugs.python.org/issue9850

   (142) https://bugs.python.org/issue5309

   (143) https://bugs.python.org/issue22448

   (144) https://bugs.python.org/issue22427

   (145) https://bugs.python.org/issue22362

   (146) https://bugs.python.org/issue20912

   (147) https://bugs.python.org/issue21866

   (148) https://bugs.python.org/issue22278

   (149) https://bugs.python.org/issue22415

   (150) https://bugs.python.org/issue22423

   (151) https://bugs.python.org/issue21332

   (152) https://bugs.python.org/issue21091

   (153) https://bugs.python.org/issue21079

   (154) https://bugs.python.org/issue22247

   (155) https://bugs.python.org/issue22366

   (156) https://bugs.python.org/issue4180

   (157) https://bugs.python.org/issue22419

   (158) https://bugs.python.org/issue20537

   (159) https://bugs.python.org/issue22384

   (160) https://bugs.python.org/issue22168

   (161) https://bugs.python.org/issue21147

   (162) https://bugs.python.org/issue13968

   (163) https://bugs.python.org/issue21951

   (164) https://bugs.python.org/issue21951

   (165) https://bugs.python.org/issue22338

   (166) https://bugs.python.org/issue12410

   (167) https://bugs.python.org/issue21270

   (168) https://bugs.python.org/issue16662

   (169) https://bugs.python.org/issue22226

   (170) https://bugs.python.org/issue19524

   (171) https://bugs.python.org/issue20421

   (172) https://bugs.python.org/issue19546

   (173) https://bugs.python.org/issue22051

   (174) https://bugs.python.org/issue21933

   (175) https://bugs.python.org/issue21597

   (176) https://bugs.python.org/issue18132

   (177) https://bugs.python.org/issue22043

   (178) https://bugs.python.org/issue21527

   (179) https://bugs.python.org/issue22216

   (180) https://bugs.python.org/issue22098

   (181) https://bugs.python.org/issue22185

   (182) https://bugs.python.org/issue22287

   (183) https://bugs.python.org/issue22182

   (184) https://bugs.python.org/issue22042

   (185) https://bugs.python.org/issue16808

   (186) https://bugs.python.org/issue22236

   (187) https://bugs.python.org/issue2527

   (188) https://bugs.python.org/issue22118

   (189) https://bugs.python.org/issue21549

   (190) https://bugs.python.org/issue19628

   (191) https://bugs.python.org/issue15696

   (192) https://bugs.python.org/issue22068

   (193) https://bugs.python.org/issue22165

   (194) https://bugs.python.org/issue15381

   (195) https://bugs.python.org/issue8797

   (196) https://bugs.python.org/issue20729

   (197) https://bugs.python.org/issue21448

   (198) https://bugs.python.org/issue22184

   (199) https://bugs.python.org/issue17923

   (200) https://bugs.python.org/issue21725

   (201) https://bugs.python.org/issue22176

   (202) https://bugs.python.org/issue5411

   (203) https://bugs.python.org/issue21121

   (204) https://bugs.python.org/issue21975

   (205) https://bugs.python.org/issue20170

   (206) https://bugs.python.org/issue21539

   (207) https://bugs.python.org/issue22127

   (208) https://bugs.python.org/issue21047

   (209) https://bugs.python.org/issue15114

   (210) https://bugs.python.org/issue22085

   (211) https://bugs.python.org/issue21580

   (212) https://bugs.python.org/issue22003

   (213) https://bugs.python.org/issue22018

   (214) https://bugs.python.org/issue22054

   (215) https://bugs.python.org/issue17172

   (216) https://bugs.python.org/issue21704

   (217) https://bugs.python.org/issue20173

   (218) https://bugs.python.org/issue22033

   (219) https://bugs.python.org/issue21947

   (220) https://bugs.python.org/issue16133

   (221) https://bugs.python.org/issue22044

   (222) https://bugs.python.org/issue19884

   (223) https://bugs.python.org/issue4350

   (224) https://bugs.python.org/issue6167

   (225) https://bugs.python.org/issue15275

   (226) https://bugs.python.org/issue21888

   (227) https://bugs.python.org/issue22032

   (228) https://bugs.python.org/issue22031

   (229) https://bugs.python.org/issue22018

   (230) https://bugs.python.org/issue21044

   (231) https://bugs.python.org/issue21966

   (232) https://bugs.python.org/issue19076

   (233) https://bugs.python.org/issue16382

   (234) https://bugs.python.org/issue21932

   (235) https://bugs.python.org/issue21942

   (236) https://bugs.python.org/issue11259

   (237) https://bugs.python.org/issue12523

   (238) https://bugs.python.org/issue21707

   (239) https://bugs.python.org/issue20639

   (240) https://bugs.python.org/issue21714

   (241) https://bugs.python.org/issue15014

   (242) https://bugs.python.org/issue21151

   (243) https://bugs.python.org/issue21090

   (244) https://bugs.python.org/issue5800

   (245) https://bugs.python.org/issue21781

   (246) https://bugs.python.org/issue21679

   (247) https://bugs.python.org/issue21863

   (248) https://bugs.python.org/issue11453

   (249) https://bugs.python.org/issue21858

   (250) https://bugs.python.org/issue21476

   (251) https://bugs.python.org/issue20295

   (252) https://bugs.python.org/issue21729

   (253) https://bugs.python.org/issue21491

   (254) https://bugs.python.org/issue21719

   (255) https://bugs.python.org/issue21832

   (256) https://bugs.python.org/issue21722

   (257) https://bugs.python.org/issue21723

   (258) https://bugs.python.org/issue21711

   (259) https://bugs.python.org/issue17552

   (260) https://bugs.python.org/issue18039

   (261) https://bugs.python.org/issue21326

   (262) https://bugs.python.org/issue21766

   (263) https://bugs.python.org/issue21310

   (264) https://bugs.python.org/issue21256

   (265) https://bugs.python.org/issue21677

   (266) https://bugs.python.org/issue11709

   (267) https://bugs.python.org/issue21515

   (268) https://bugs.python.org/issue13223

   (269) https://bugs.python.org/issue21463

   (270) https://bugs.python.org/issue21618

   (271) https://bugs.python.org/issue20383

   (272) https://bugs.python.org/issue21552

   (273) https://bugs.python.org/issue14315

   (274) https://bugs.python.org/issue13742

   (275) https://bugs.python.org/issue21402

   (276) https://bugs.python.org/issue3015

   (277) https://bugs.python.org/issue10203

   (278) https://bugs.python.org/issue18807

   (279) https://bugs.python.org/issue20197

   (280) https://bugs.python.org/issue21513

   (281) https://bugs.python.org/issue21137

   (282) https://bugs.python.org/issue21538

   (283) https://bugs.python.org/issue21455

   (284) https://bugs.python.org/issue21525

   (285) https://bugs.python.org/issue22166

   (286) https://bugs.python.org/issue22236

   (287) https://bugs.python.org/issue10744

   (288) https://www.python.org/dev/peps/pep-3118

   (289) https://bugs.python.org/issue20826

   (290) https://bugs.python.org/issue21487

   (291) https://bugs.python.org/issue21486

   (292) https://bugs.python.org/issue13916

   (293) https://bugs.python.org/issue20998

   (294) https://bugs.python.org/issue21075

   (295) https://bugs.python.org/issue19775

   (296) https://bugs.python.org/issue21226

   (297) https://bugs.python.org/issue21398

   (298) https://bugs.python.org/issue16531

   (299) https://bugs.python.org/issue21156

   (300) https://bugs.python.org/issue21424

   (301) https://bugs.python.org/issue21396

   (302) https://bugs.python.org/issue18314

   (303) https://bugs.python.org/issue21088

   (304) https://bugs.python.org/issue21407

   (305) https://bugs.python.org/issue10650

   (306) https://bugs.python.org/issue21469

   (307) https://bugs.python.org/issue19414

   (308) https://bugs.python.org/issue21421

   (309) https://bugs.python.org/issue21101

   (310) https://bugs.python.org/issue21321

   (311) https://bugs.python.org/issue21057

   (312) https://bugs.python.org/issue20951

   (313) https://bugs.python.org/issue13248

   (314) https://bugs.python.org/issue9815

   (315) https://bugs.python.org/issue19940

   (316) https://bugs.python.org/issue13204

   (317) https://bugs.python.org/issue19385

   (318) https://bugs.python.org/issue21207

   (319) https://bugs.python.org/issue21291

   (320) https://bugs.python.org/issue21127

   (321) https://bugs.python.org/issue15002

   (322) https://bugs.python.org/issue12220

   (323) https://bugs.python.org/issue21068

   (324) https://bugs.python.org/issue21276

   (325) https://bugs.python.org/issue21262

   (326) https://bugs.python.org/issue21238

   (327) https://bugs.python.org/issue20896

   (328) https://bugs.python.org/issue21239

   (329) https://bugs.python.org/issue21203

   (330) https://bugs.python.org/issue21222

   (331) https://bugs.python.org/issue21197

   (332) https://bugs.python.org/issue17498

   (333) https://bugs.python.org/issue17826

   (334) https://bugs.python.org/issue7776

   (335) https://bugs.python.org/issue20968

   (336) https://bugs.python.org/issue21529

   (337) https://bugs.python.org/issue21169

   (338) https://bugs.python.org/issue21171

   (339) https://bugs.python.org/issue20539

   (340) https://bugs.python.org/issue21172

   (341) https://bugs.python.org/issue21155

   (342) https://bugs.python.org/issue21136

   (343) https://bugs.python.org/issue17621

   (344) https://bugs.python.org/issue21076

   (345) https://bugs.python.org/issue20636

   (346) https://bugs.python.org/issue19505

   (347) https://bugs.python.org/issue21149

   (348) https://bugs.python.org/issue21058

   (349) https://bugs.python.org/issue21200

   (350) https://bugs.python.org/issue21013

   (351) https://bugs.python.org/issue20145

   (352) https://bugs.python.org/issue20633

   (353) https://bugs.python.org/issue20980

   (354) https://bugs.python.org/issue21082

   (355) https://bugs.python.org/issue20990

   (356) https://bugs.python.org/issue21015

   (357) https://bugs.python.org/issue21000

   (358) https://bugs.python.org/issue20995

   (359) https://bugs.python.org/issue20884

   (360) https://bugs.python.org/issue21499

   (361) https://bugs.python.org/issue20627

   (362) https://bugs.python.org/issue19165

   (363) https://bugs.python.org/issue13936

   (364) https://bugs.python.org/issue18931

   (365) https://bugs.python.org/issue19977

   (366) https://bugs.python.org/issue20574

   (367) https://bugs.python.org/issue20879

   (368) https://bugs.python.org/issue19157

   (369) https://bugs.python.org/issue11599

   (370) https://bugs.python.org/issue4931

   (371) https://bugs.python.org/issue20875

   (372) https://bugs.python.org/issue11558

   (373) https://bugs.python.org/issue20283

   (374) https://bugs.python.org/issue20778

   (375) https://bugs.python.org/issue20791

   (376) https://bugs.python.org/issue19748

   (377) https://bugs.python.org/issue19573

   (378) https://bugs.python.org/issue20726

   (379) https://bugs.python.org/issue17373

   (380) https://bugs.python.org/issue20378

   (381) https://bugs.python.org/issue20816

   (382) https://bugs.python.org/issue20817

   (383) https://bugs.python.org/issue6676

   (384) https://bugs.python.org/issue21117

   (385) https://bugs.python.org/issue20334

   (386) https://bugs.python.org/issue15916

   (387) https://bugs.python.org/issue21209

   (388) https://bugs.python.org/issue163

   (389) https://bugs.python.org/issue21311

   (390) https://bugs.python.org/issue11571

   (391) https://bugs.python.org/issue21801

   (392) https://bugs.python.org/issue21923

   (393) https://bugs.python.org/issue21323

   (394) https://bugs.python.org/issue19435

   (395) https://bugs.python.org/issue22733

   (396) https://bugs.python.org/issue23302


File: python.info,  Node: IDLE<50>,  Next: 构建<62>,  Prev: 库<89>,  Up: Python 3 5 0 alpha 1

1.19.89.3 IDLE
..............

   - bpo-20577(1): 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.

   - bpo-16893(2): Update Idle doc chapter to match current Idle and add
     new information.

   - bpo-3068(3): Add Idle extension configuration dialog to Options
     menu.  Changes are written to HOME/.idlerc/config-extensions.cfg.
     Original patch by Tal Einat.

   - bpo-16233(4): 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.

   - bpo-4832(5): 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.

   - bpo-21986(6): Code objects are not normally pickled by the pickle
     module.  To match this, they are no longer pickled when running
     under Idle.

   - bpo-17390(7): Adjust Editor window title; remove ’Python’, move
     version to end.

   - bpo-14105(8): Idle debugger breakpoints no longer disappear when
     inserting or deleting lines.

   - bpo-17172(9): 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.

   - bpo-21765(10): Add support for non-ascii identifiers to
     HyperParser.

   - bpo-21940(11): Add unittest for WidgetRedirector.  Initial patch by
     Saimadhav Heblikar.

   - bpo-18592(12): Add unittest for SearchDialogBase.  Patch by Phil
     Webster.

   - bpo-21694(13): Add unittest for ParenMatch.  Patch by Saimadhav
     Heblikar.

   - bpo-21686(14): add unittest for HyperParser.  Original patch by
     Saimadhav Heblikar.

   - bpo-12387(15): Add missing upper(lower)case versions of default
     Windows key bindings for Idle so Caps Lock does not disable them.
     Patch by Roger Serwy.

   - bpo-21695(16): Closing a Find-in-files output window while the
     search is still in progress no longer closes Idle.

   - bpo-18910(17): Add unittest for textView.  Patch by Phil Webster.

   - bpo-18292(18): Add unittest for AutoExpand.  Patch by Saihadhav
     Heblikar.

   - bpo-18409(19): Add unittest for AutoComplete.  Patch by Phil
     Webster.

   - bpo-21477(20): htest.py - Improve framework, complete set of tests.
     Patches by Saimadhav Heblikar

   - bpo-18104(21): 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.

   - bpo-21139(22): Change default paragraph width to 72, the PEP 8(23)
     recommendation.

   - bpo-21284(24): Paragraph reformat test passes after user changes
     reformat width.

   - bpo-17654(25): Ensure IDLE menus are customized properly on OS X
     for non-framework builds and for all variants of Tk.

   - bpo-23180(26): Rename IDLE "Windows" menu item to "Window".  Patch
     by Al Sweigart.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue20577

   (2) https://bugs.python.org/issue16893

   (3) https://bugs.python.org/issue3068

   (4) https://bugs.python.org/issue16233

   (5) https://bugs.python.org/issue4832

   (6) https://bugs.python.org/issue21986

   (7) https://bugs.python.org/issue17390

   (8) https://bugs.python.org/issue14105

   (9) https://bugs.python.org/issue17172

   (10) https://bugs.python.org/issue21765

   (11) https://bugs.python.org/issue21940

   (12) https://bugs.python.org/issue18592

   (13) https://bugs.python.org/issue21694

   (14) https://bugs.python.org/issue21686

   (15) https://bugs.python.org/issue12387

   (16) https://bugs.python.org/issue21695

   (17) https://bugs.python.org/issue18910

   (18) https://bugs.python.org/issue18292

   (19) https://bugs.python.org/issue18409

   (20) https://bugs.python.org/issue21477

   (21) https://bugs.python.org/issue18104

   (22) https://bugs.python.org/issue21139

   (23) https://www.python.org/dev/peps/pep-0008

   (24) https://bugs.python.org/issue21284

   (25) https://bugs.python.org/issue17654

   (26) https://bugs.python.org/issue23180


File: python.info,  Node: 构建<62>,  Next: C API<43>,  Prev: IDLE<50>,  Up: Python 3 5 0 alpha 1

1.19.89.4 构建
..............

   - bpo-15506(1): Use standard PKG_PROG_PKG_CONFIG autoconf macro in
     the configure script.

   - bpo-22935(2): Allow the ssl module to be compiled if openssl
     doesn’t support SSL 3.

   - bpo-22592(3): 放弃对 Borland C 编译器构建Python的支持。distutils模
     块仍然支持它来构建扩展。

   - bpo-22591(4): 放弃对 MS-DOS 的支持，尤其是 DJGPP 编译器（GCC的
     MS-DOS端口）。

   - bpo-16537(5): Check whether self.extensions is empty in setup.py.
     Patch by Jonathan Hosmer.

   - bpo-22359(6): Remove incorrect uses of recursive make.  Patch by
     Jonas Wagner.

   - bpo-21958(7): Define HAVE_ROUND when building with Visual Studio
     2013 and above.  Patch by Zachary Turner.

   - bpo-18093(8): the programs that embed the CPython runtime are now
     in a separate "Programs" directory, rather than being kept in the
     Modules directory.

   - bpo-15759(9): "make suspicious", "make linkcheck" and "make
     doctest" in Doc/ now display special message when and only when
     there are failures.

   - bpo-21141(10): The Windows build process no longer attempts to find
     Perl, instead relying on OpenSSL source being configured and ready
     to build.  The ‘PCbuild\build_ssl.py’ script has been re-written
     and re-named to ‘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.

   - bpo-21037(11): Add a build option to enable AddressSanitizer
     support.

   - bpo-19962(12): 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.

   - bpo-21285(13): Refactor and fix curses configure check to always
     search in a ncursesw directory.

   - bpo-15234(14): 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.

   - bpo-17861(15): Tools/scripts/generate_opcode_h.py automatically
     regenerates Include/opcode.h from Lib/opcode.py if the latter gets
     any change.

   - bpo-20644(16): OS X installer build support for documentation build
     changes in 3.4.1: assume externally supplied sphinx-build is
     available in /usr/bin.

   - bpo-20022(17): Eliminate use of deprecated bundlebuilder in OS X
     builds.

   - bpo-15968(18): Incorporated Tcl, Tk, and Tix builds into the
     Windows build solution.

   - bpo-17095(19): Fix Modules/Setup `shared' support.

   - bpo-21811(20): Anticipated fixes to support OS X versions > 10.9.

   - bpo-21166(21): Prevent possible segfaults and other random failures
     of python –generate-posix-vars in pybuilddir.txt build target.

   - bpo-18096(22): Fix library order returned by python-config.

   - bpo-17219(23): Add library build dir for Python extension
     cross-builds.

   - bpo-22919(24): Windows build updated to support VC 14.0 (Visual
     Studio 2015), which will be used for the official release.

   - bpo-21236(25): Build _msi.pyd with cabinet.lib instead of fci.lib

   - bpo-17128(26): Use private version of OpenSSL for OS X 10.5+
     installer.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue15506

   (2) https://bugs.python.org/issue22935

   (3) https://bugs.python.org/issue22592

   (4) https://bugs.python.org/issue22591

   (5) https://bugs.python.org/issue16537

   (6) https://bugs.python.org/issue22359

   (7) https://bugs.python.org/issue21958

   (8) https://bugs.python.org/issue18093

   (9) https://bugs.python.org/issue15759

   (10) https://bugs.python.org/issue21141

   (11) https://bugs.python.org/issue21037

   (12) https://bugs.python.org/issue19962

   (13) https://bugs.python.org/issue21285

   (14) https://bugs.python.org/issue15234

   (15) https://bugs.python.org/issue17861

   (16) https://bugs.python.org/issue20644

   (17) https://bugs.python.org/issue20022

   (18) https://bugs.python.org/issue15968

   (19) https://bugs.python.org/issue17095

   (20) https://bugs.python.org/issue21811

   (21) https://bugs.python.org/issue21166

   (22) https://bugs.python.org/issue18096

   (23) https://bugs.python.org/issue17219

   (24) https://bugs.python.org/issue22919

   (25) https://bugs.python.org/issue21236

   (26) https://bugs.python.org/issue17128


File: python.info,  Node: C API<43>,  Next: 文档<54>,  Prev: 构建<62>,  Up: Python 3 5 0 alpha 1

1.19.89.5 C API
...............

   - bpo-14203(1): 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.

   - bpo-22445(2): 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.

   - bpo-22079(3): PyType_Ready() now checks that statically allocated
     type has no dynamically allocated bases.

   - bpo-22453(4): Removed non-documented macro PyObject_REPR().

   - bpo-18395(5): Rename ‘_Py_char2wchar()’ to *note Py_DecodeLocale():
     53e, rename ‘_Py_wchar2char()’ to *note Py_EncodeLocale(): 53f, and
     document these functions.

   - bpo-21233(6): Add new C functions: PyMem_RawCalloc(),
     PyMem_Calloc(), PyObject_Calloc(), _PyObject_GC_Calloc().
     bytes(int) is now using ‘calloc()’ instead of ‘malloc()’ for large
     objects which is faster and use less memory.

   - bpo-20942(7): 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().

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue14203

   (2) https://bugs.python.org/issue22445

   (3) https://bugs.python.org/issue22079

   (4) https://bugs.python.org/issue22453

   (5) https://bugs.python.org/issue18395

   (6) https://bugs.python.org/issue21233

   (7) https://bugs.python.org/issue20942


File: python.info,  Node: 文档<54>,  Next: 测试<58>,  Prev: C API<43>,  Up: Python 3 5 0 alpha 1

1.19.89.6 文档
..............

   - bpo-19548(1): Update the codecs module documentation to better
     cover the distinction between text encodings and other codecs,
     together with other clarifications.  Patch by Martin Panter.

   - bpo-22394(2): Doc/Makefile now supports ‘make venv
     PYTHON=../python’ to create a venv for generating the
     documentation, e.g., ‘make html PYTHON=venv/bin/python3’.

   - bpo-21514(3): The documentation of the json module now refers to
     new JSON RFC 7159 instead of obsoleted RFC 4627.

   - bpo-21777(4): 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.

   - bpo-6916(5): undocument deprecated asynchat.fifo class.

   - bpo-17386(6): Expanded functionality of the ‘Doc/make.bat’ script
     to make it much more comparable to ‘Doc/Makefile’.

   - bpo-21312(7): Update the thread_foobar.h template file to include
     newer threading APIs.  Patch by Jack McCracken.

   - bpo-21043(8): Remove the recommendation for specific CA
     organizations and to mention the ability to load the OS
     certificates.

   - bpo-20765(9): Add missing documentation for PurePath.with_name()
     and PurePath.with_suffix().

   - bpo-19407(10): 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.

   - bpo-19697(11): Document cases where __main__.__spec__ is None.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue19548

   (2) https://bugs.python.org/issue22394

   (3) https://bugs.python.org/issue21514

   (4) https://bugs.python.org/issue21777

   (5) https://bugs.python.org/issue6916

   (6) https://bugs.python.org/issue17386

   (7) https://bugs.python.org/issue21312

   (8) https://bugs.python.org/issue21043

   (9) https://bugs.python.org/issue20765

   (10) https://bugs.python.org/issue19407

   (11) https://bugs.python.org/issue19697


File: python.info,  Node: 测试<58>,  Next: 工具/示例<35>,  Prev: 文档<54>,  Up: Python 3 5 0 alpha 1

1.19.89.7 测试
..............

   - bpo-18982(1): Add tests for CLI of the calendar module.

   - bpo-19548(2): Added some additional checks to test_codecs to ensure
     that statements in the updated documentation remain accurate.
     Patch by Martin Panter.

   - bpo-22838(3): All test_re tests now work with unittest test
     discovery.

   - bpo-22173(4): Update lib2to3 tests to use unittest test discovery.

   - bpo-16000(5): Convert test_curses to use unittest.

   - bpo-21456(6): Skip two tests in test_urllib2net.py if _ssl module
     not present.  Patch by Remi Pointel.

   - bpo-20746(7): Fix test_pdb to run in refleak mode (-R). Patch by
     Xavier de Gaye.

   - bpo-22060(8): test_ctypes has been somewhat cleaned up and
     simplified; it now uses unittest test discovery to find its tests.

   - bpo-22104(9): regrtest.py no longer holds a reference to the suite
     of tests loaded from test modules that don’t define test_main().

   - bpo-22111(10): Assorted cleanups in test_imaplib.  Patch by Milan
     Oberkirch.

   - bpo-22002(11): Added ‘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.

   - bpo-21976(12): Fix test_ssl to accept LibreSSL version strings.
     Thanks to William Orr.

   - bpo-21918(13): Converted test_tools from a module to a package
     containing separate test files for each tested script.

   - bpo-9554(14): Use modern unittest features in test_argparse.
     Initial patch by Denver Coneybeare and Radu Voicilas.

   - bpo-20155(15): 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.

   - bpo-19493(16): Refactored the ctypes test package to skip tests
     explicitly rather than silently.

   - bpo-18492(17): All resources are now allowed when tests are not run
     by regrtest.py.

   - bpo-21634(18): 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.

   - bpo-21605(19): Added tests for Tkinter images.

   - bpo-21493(20): Added test for ntpath.expanduser().  Original patch
     by Claudiu Popa.

   - bpo-19925(21): Added tests for the spwd module.  Original patch by
     Vajrasky Kok.

   - bpo-21522(22): Added Tkinter tests for Listbox.itemconfigure(),
     PanedWindow.paneconfigure(), and Menu.entryconfigure().

   - bpo-17756(23): Fix test_code test when run from the installed
     location.

   - bpo-17752(24): Fix distutils tests when run from the installed
     location.

   - bpo-18604(25): Consolidated checks for GUI availability.  All
     platforms now at least check whether Tk can be instantiated when
     the GUI resource is requested.

   - bpo-21275(26): 修复KFreeBSD上的套接字测试。

   - bpo-21223(27): Pass test_site/test_startup_imports when some of the
     extensions are built as builtins.

   - bpo-20635(28): 添加了针对Tk几何管理器的测试。

   - 增加freeze包的测试用例。

   - bpo-20743(29): 修复test_tcl中的引用泄漏。

   - bpo-21097(30): 将test_namespace_pkgs 移至 test_importlib。

   - bpo-21503(31): Use test_both() consistently in test_importlib.

   - bpo-20939(32): Avoid various network test failures due to new
     redirect of ‘http://www.python.org/’ to ‘https://www.python.org’:
     use ‘http://www.example.com’ instead.

   - bpo-20668(33): asyncio tests no longer rely on tests.txt file.
     (Patch by Vajrasky Kok)

   - bpo-21093(34): Prevent failures of ctypes test_macholib on OS X if
     a copy of libz exists in $HOME/lib or /usr/local/lib.

   - bpo-22770(35): Prevent some Tk segfaults on OS X when running gui
     tests.

   - bpo-23211(36): Workaround test_logging failure on some OS X 10.6
     systems.

   - bpo-23345(37): Prevent test_ssl failures with large OpenSSL patch
     level values (like 0.9.8zc).

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18982

   (2) https://bugs.python.org/issue19548

   (3) https://bugs.python.org/issue22838

   (4) https://bugs.python.org/issue22173

   (5) https://bugs.python.org/issue16000

   (6) https://bugs.python.org/issue21456

   (7) https://bugs.python.org/issue20746

   (8) https://bugs.python.org/issue22060

   (9) https://bugs.python.org/issue22104

   (10) https://bugs.python.org/issue22111

   (11) https://bugs.python.org/issue22002

   (12) https://bugs.python.org/issue21976

   (13) https://bugs.python.org/issue21918

   (14) https://bugs.python.org/issue9554

   (15) https://bugs.python.org/issue20155

   (16) https://bugs.python.org/issue19493

   (17) https://bugs.python.org/issue18492

   (18) https://bugs.python.org/issue21634

   (19) https://bugs.python.org/issue21605

   (20) https://bugs.python.org/issue21493

   (21) https://bugs.python.org/issue19925

   (22) https://bugs.python.org/issue21522

   (23) https://bugs.python.org/issue17756

   (24) https://bugs.python.org/issue17752

   (25) https://bugs.python.org/issue18604

   (26) https://bugs.python.org/issue21275

   (27) https://bugs.python.org/issue21223

   (28) https://bugs.python.org/issue20635

   (29) https://bugs.python.org/issue20743

   (30) https://bugs.python.org/issue21097

   (31) https://bugs.python.org/issue21503

   (32) https://bugs.python.org/issue20939

   (33) https://bugs.python.org/issue20668

   (34) https://bugs.python.org/issue21093

   (35) https://bugs.python.org/issue22770

   (36) https://bugs.python.org/issue23211

   (37) https://bugs.python.org/issue23345


File: python.info,  Node: 工具/示例<35>,  Next: Windows<54>,  Prev: 测试<58>,  Up: Python 3 5 0 alpha 1

1.19.89.8 工具/示例
...................

   - bpo-22314(1): pydoc now works when the LINES environment variable
     is set.

   - bpo-22615(2): Argument Clinic now supports the "type" argument for
     the int converter.  This permits using the int converter with enums
     and typedefs.

   - bpo-20076(3): The makelocalealias.py script no longer ignores UTF-8
     mapping.

   - bpo-20079(4): The makelocalealias.py script now can parse the
     SUPPORTED file from glibc sources and supports command line options
     for source paths.

   - bpo-22201(5): Command-line interface of the zipfile module now
     correctly extracts ZIP files with directory entries.  Patch by Ryan
     Wilson.

   - bpo-22120(6): 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.)

   - bpo-18974(7): Tools/scripts/diff.py now uses argparse instead of
     optparse.

   - bpo-21906(8): 让Tools/scripts/md5sum.py可以工作在Python 3。由
     Zachary Ware提供补丁。

   - bpo-21629(9): Fix Argument Clinic’s "–converters" feature.

   - 为2to3添加 ‘yield from’ 的支持。

   - 为 2to3 添加对 PEP 465 矩阵乘法运算符的支持。

   - bpo-16047(10): Fix module exception list and __file__ handling in
     freeze.  Patch by Meador Inge.

   - bpo-11824(11): Consider ABI tags in freeze.  Patch by Meador Inge.

   - bpo-20535(12): PYTHONWARNING no longer affects the run_tests.py
     script.  Patch by Arfrever Frehtes Taifersar Arahesis.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue22314

   (2) https://bugs.python.org/issue22615

   (3) https://bugs.python.org/issue20076

   (4) https://bugs.python.org/issue20079

   (5) https://bugs.python.org/issue22201

   (6) https://bugs.python.org/issue22120

   (7) https://bugs.python.org/issue18974

   (8) https://bugs.python.org/issue21906

   (9) https://bugs.python.org/issue21629

   (10) https://bugs.python.org/issue16047

   (11) https://bugs.python.org/issue11824

   (12) https://bugs.python.org/issue20535


File: python.info,  Node: Windows<54>,  Prev: 工具/示例<35>,  Up: Python 3 5 0 alpha 1

1.19.89.9 Windows
.................

   - bpo-23260(1): 更新Windows安装器

   - 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.

   - bpo-17896(2): The Windows build scripts now expect external library
     sources to be in ‘PCbuild\..\externals’ rather than
     ‘PCbuild\..\..’.

   - bpo-17717(3): The Windows build scripts now use a copy of NASM
     pulled from svn.python.org to build OpenSSL.

   - bpo-21907(4): Improved the batch scripts provided for building
     Python.

   - bpo-22644(5): OpenSSL的捆绑版本已更新到1.0.1j。

   - bpo-10747(6): Use versioned labels in the Windows start menu.
     Patch by Olive Kilburn.

   - bpo-22980(7): .pyd files with a version and platform tag (for
     example, ".cp35-win32.pyd") will now be loaded in preference to
     those without tags.

`（有关旧版本的信息，请参阅HISTORY文件。)'

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue23260

   (2) https://bugs.python.org/issue17896

   (3) https://bugs.python.org/issue17717

   (4) https://bugs.python.org/issue21907

   (5) https://bugs.python.org/issue22644

   (6) https://bugs.python.org/issue10747

   (7) https://bugs.python.org/issue22980


File: python.info,  Node: Python 教學,  Next: Python 的設置與使用,  Prev: Python 有什麼新功能？,  Up: Top

2 Python 教學
*************

Python 是一種易學、功能強大的程式語言。它有高效能的高階資料結構，也有簡
單但有效的方法去實現物件導向程式設計。Python 優雅的語法和動態型別，結合
其直譯特性，使它成為眾多領域和大多數平臺上，撰寫腳本和快速開發應用程式的
理想語言。

使用者可以自由且免費地從 Python 官網上 (‘https://www.python.org/’) 取得
各大平台上用的 Python 直譯器和標準函式庫，下載其源碼或二進位形式執行檔，
同時，也可以將其自由地散佈。另外，Python 官網也提供了許多自由且免費的第
三方 Python 模組、程式與工具、以及額外說明文件，有興趣的使用者，可在官網
上找到相關的發行版本與連結網址。

使用 C 或 C++（或其他可被 C 呼叫的程式語言），可以很容易在 Python 直譯器
內新增功能函式及資料型別。同時，對可讓使用者自製功能的應用程式來說，
Python 也適合作為其擴充用界面語言 (extension language)。

這份教學將簡介 Python 語言與系統的基本概念及功能。除了閱讀之外、實際用
Python 直譯器寫程式跑範例，將有助於學習。但如果只用讀的，也是可行的學習
方式，因為所有範例的內容皆獨立且完整。

若想了解 Python 標準物件和模組的描述，請參閱 *note Python 標準函式庫
(Standard Library): 1330.。在 *note Python 語言參考手冊: 1331. 中，您可
以學到 Python 語言更正規的定義。想用 C 或 C++ 寫延伸套件 (extensions) 的
讀者，請閱讀 *note 擴充和嵌入 Python 直譯器: 1332. 和 *note Python/C API
參考手冊: 1333. 。此外，市面上也能找到更深入的 Python 學習書。

這份教學中，我們不會介紹每一個功能，甚至，也不打算介紹完每一個常用功能。
取而代之，我們的重心將放在介紹 Python 中最值得一提的那些功能，幫助您了解
Python 語言的特色與風格。讀完教學後，您將有能力閱讀和撰寫 Python 模組與
程式，也做好進一步學習 *note Python 標準函式庫 (Standard Library): 1330.
中各類型的 Python 函式庫模組的準備。

*note 術語表: 1334. 頁面也值得細讀。

* Menu:

* 淺嘗滋味::
* 使用 Python 直譯器::
* 一個非正式的 Python 簡介::
* 深入了解流程控制::
* 資料結構::
* 模組 (Module): 模組 Module.
* 輸入和輸出::
* 錯誤和例外::
* Class（類別）::
* Python 標準函式庫概覽::
* Python 標準函式庫概覽——第二部份::
* 虛擬環境與套件::
* 現在可以來學習些什麼？::
* 互動式輸入編輯和歷史記錄替換::
* 浮點數運算：問題與限制::
* 附錄::


File: python.info,  Node: 淺嘗滋味,  Next: 使用 Python 直譯器,  Up: Python 教學

2.1 淺嘗滋味
============

如果你經常在電腦上工作，最終總能發現有些工作你會想要自動化。舉例來說，你
會想在很多文字檔案裡做相同的搜尋取代，或者是用個複雜的規則重新命名或整理
一群照片。也有可能你想寫個自己的小資料庫，一個專門的 GUI 應用程式，或一
個小遊戲。

如果你是一個職業軟體開發者，你可能要操作數個 C/C++/Java 程式庫，卻覺得平
常寫程式碼、編譯、測試、再編譯的流程太慢；有可能你正為了一個程式庫撰寫一
套測試集，但發現寫測試單調乏味；也有可能你正在開發一個能使用某一語言擴充
的程式，但並不想要為了這程式特別設計一個全新的擴充語言。

在上述的例子中，Python 正是你合適的語言。

也許你可以為了某些任務而寫個 Unix shell 腳本或者 Windows 批次檔來處理，
但 shell 腳本最適合於搬動檔案或更動文字內容，而不適於圖形應用程式或遊戲
。你可以為此寫個 C/C++/Java 程式，但僅僅是完成個草稿也需要很長的開發時間
。相較而言，Python 更易於使用，並能在 Windows、macOS、Unix 作業系統上執
行，且能更快速地幫助你完成工作。

Python 即便易用也是個貨真價實的程式語言。它提供比 shell 腳本、批次檔更多
樣的程式架構與更多的支援。另一方面，Python 提供比 C 更豐富的錯語檢查。相
較於 C，Python 作為一個「非常高階的程式語言」，它內建了高階的資料型別如
彈性的數列與字典。因為這些多用途的資料型別，Python 適用解決比 Awk（甚至
是 Perl）能處理的更多問題上。至少在許多事情中，使用 Python 處理起來跟其
他語言是同樣容易的。

Python 允許你把程式切割成許多模組 (module) 並將他們重覆運用至其他 Python
程式中。Python 自帶了一個很大集合的標準模組，它們能做為你程式的基礎——或
把它們當作一開始學寫 Python 程式的範例。有些模組提供了如檔案 I/O、系統呼
叫、socket 的功能，甚至提供了 Tk 等圖形介面工具庫 (GUI toolkit) 的介面。

Python 是個直譯式語言，因為不需要編譯與連結，能為你在開發過程中省下可觀
的時間。它的直譯器能互動地使用，因此能很方便地實驗每個語言的功能、寫些用
完即丟的程式、幫助測試一些從細部開始開發的函式。它也是個好用的計算機。

Python 讓程式寫得精簡並易讀。用 Python 實作的程式長度往往遠比用 C、C++、
Java 實作的短。這有以下幾個原因：

   * Python 高階的資料型別能在一陳述式 (statement) 中表達很複雜的操作；

   * 陳述式的段落以縮排為區隔而非括號；

   * 不需要宣告變數和引數。

Python 是`可擴充的'：如果你會寫 C 程式，那麼要加個新的內建函式或模組到直
譯器中是很容易的。無論是為了用最快速的執行速度完成一些關鍵的操作，或是讓
Python 連結到一些僅以二進位形式 (binary form) 釋出的程式庫（例如特定供應
商的繪圖程式庫）。如果你想更多這樣的結合，你其實也可以把 Python 直譯器連
結到用 C 寫的應用程式，並在該應用程式中使用 Python 寫擴充或者作為下達指
令的語言。

順帶一提，這個語言是以 BBC 的戲劇《Monty Python’s Flying Circus》命名，
與爬蟲類完全沒有關係。在說明文件中引用他們的喜劇不但沒問題，這甚至是個被
鼓勵的行為！

如果你現在已經躍躍欲試，你會想了解 Python 更多細節，而學習語言的最好方式
就是直接使用它。接下來這個教學就將帶領你，一邊閱讀，一邊將所學用在
Python 直譯器中玩耍。

在下個章節中，將會解說如何使用該直譯器。這也許只是個普通的資訊，但你必須
試著操作接下來呈現的範例。

接下來的教學裡，將會透過許多範例介紹 Python 語言與其系統的諸多特色。一開
始是簡單的運算式 (expression)、陳述式 (statement) 和資料型別 (data
type)；接著是函式 (function) 與模組 (module)；最後會接觸一些較進階的主題
如例外 (exception) 與使用者自定義類別 (class)。


File: python.info,  Node: 使用 Python 直譯器,  Next: 一個非正式的 Python 簡介,  Prev: 淺嘗滋味,  Up: Python 教學

2.2 使用 Python 直譯器
======================

* Menu:

* 啟動直譯器::
* 直譯器與它的環境::


File: python.info,  Node: 啟動直譯器,  Next: 直譯器與它的環境,  Up: 使用 Python 直譯器

2.2.1 啟動直譯器
----------------

Python 直譯器一般安裝在 ‘/usr/local/bin/python3.9’ 路徑下；將
‘/usr/local/bin’ 加入Unix shell 的搜索路徑，輸入以下指令就可以啟動
Python：

     python3.9

能啟動 Python (1)。因為直譯器存放的目錄是個安裝選項，其他的目錄也是有可
能的；請洽談在地的 Python 達人或者系統管理員。（例如：
‘/usr/local/python’ 是個很常見的另類存放路徑。）

Windows 系統中，從 *note Microsoft Store: 133d. 安裝 Python 後，就可以使
用 ‘python3.9’ 命令了。如果安裝了 *note py.exe launcher: a70. ，則可以使
用 ‘py’ 命令。請參閱附錄：*note 附录：设置环境变量: 133e.，了解其他啟動
Python 的方式。

在主提示符輸入一個 end-of-file 字元（在 Unix 上為 ‘Control-D’；在
Windows 上為 ‘Control-Z’）會使得直譯器以零退出狀況 (zero exit status) 離
開。如果上述的做法沒有效，也可以輸入指令 ‘quit()’ 離開直譯器。

直譯器的指令列編輯功能有很多，在支援 GNU Readline(2) 函式庫的系統上包含
：互動編輯、歷史取代、指令補完等功能。最快檢查有無支援指令列編輯的方法為
：在第一個 Python 提示符後輸入 ‘Control-P’，如果出現嗶嗶聲，就代表有支援
；見附錄*note 互動式輸入編輯和歷史記錄替換: 133f.介紹相關的快速鍵。如果
什麼事都沒有發生，或者出現一個 ‘^P’，就代表並沒有指令列編輯功能；此時只
能使用 backspace 去除該行的字元。

這個直譯器使用起來像是 Unix shell：如果它被呼叫時連結至一個 tty 裝置，它
會互動式地讀取並執行指令；如果被呼叫時給定檔名為引數或者使用 stdin 傳入
檔案內容，它會將這個檔案視為`腳本'來閱讀。

另一個啟動直譯器的方式為 ‘python -c command [arg] ...’，它會執行在
`command' 裡的指令（們），行為如同 shell 的 *note -c: 1340. 選項。因為
Python 的指令包含空白等 shell 用到的特殊字元，通常建議用單引號把
`command' 包起來。

有些 Python 模組使用上如腳本般一樣方便。透過 ‘python -m module [arg]
...’ 可以執行 `module' 模組的原始碼，就如同直接傳入那個模組的完整路徑一
樣的行為。

當要執行一個腳本檔時，有時候會希望在腳本結束時進入互動模式。此時可在執行
腳本的指令加入 *note -i: ee1.。

所有指令可用的參數都詳記在*note 命令行与环境: 10bd.。

* Menu:

* 傳遞引數::
* 互動模式::

   ---------- Footnotes ----------

   (1) (1) 在 Unix 中，Python 3.x 直譯器預設安裝不會以 ‘python’ 作為執行
檔名稱，以避免與現有的 Python 2.x 執行檔名稱衝突。

   (2) https://tiswww.case.edu/php/chet/readline/rltop.html


File: python.info,  Node: 傳遞引數,  Next: 互動模式,  Up: 啟動直譯器

2.2.1.1 傳遞引數
................

當直擇器收到腳本的名稱和額外的引數後，他們會轉換為由字串所組成的 list（
串列）並指派給 ‘sys’ 模組的 ‘argv’ 變數。你可以執行 ‘import sys’ 取得這
個串列。這個串列的長度至少為一；當沒有給任何腳本名稱和引數時，
‘sys.argv[0]’ 為空字串。當腳本名為 ‘'-'’（指標準輸入）時， ‘sys.argv[0]’
為 ‘'-'’。當使用 *note -c: 1340. `command' 時， ‘sys.argv[0]’ 為 ‘'-c'’。
當使用 *note -m: 443. `module' 時， ‘sys.argv[0]’ 為該模組存在的完整路徑
。其餘非 *note -c: 1340. `command' 或 *note -m: 443. `module' 的選項不會
被 Python 直譯器吸收掉，而是留在 ‘sys.argv’ 變數中給後續的 command 或
module 使用。


File: python.info,  Node: 互動模式,  Prev: 傳遞引數,  Up: 啟動直譯器

2.2.1.2 互動模式
................

在終端 (tty) 輸入並執行指令時，直譯器在`互動模式（interactive mode）'中
運行。在這種模式中，會顯示`主提示符'，提示輸入下一條指令，主提示符通常用
三個大於號（‘>>>’）表示；輸入連續行時，顯示`次要提示符'，預設是三個點（
‘...’）。進入直譯器時，首先顯示歡迎訊息、版本訊息、版權聲明，然後才是提
示符：

     $ 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.
     >>>

接續多行的情況出現在需要多行才能建立完整指令時。舉例來說，像是 *note if:
eab. 敘述：

     >>> the_world_is_flat = True
     >>> if the_world_is_flat:
     ...     print("Be careful not to fall off!")
     ...
     Be careful not to fall off!

更多有關互動模式的使用，請見*note 互動模式: 1344.。


File: python.info,  Node: 直譯器與它的環境,  Prev: 啟動直譯器,  Up: 使用 Python 直譯器

2.2.2 直譯器與它的環境
----------------------

* Menu:

* 原始碼的字元編碼 (encoding): 原始碼的字元編碼 encoding.


File: python.info,  Node: 原始碼的字元編碼 encoding,  Up: 直譯器與它的環境

2.2.2.1 原始碼的字元編碼 (encoding)
...................................

預設 Python 原始碼檔案的字元編碼使用 UTF-8。在這個編碼中，世界上多數語言
的文字可以同時被使用在字串內容、識別名 (identifier) 及註解中 — 雖然在標
準函式庫中只使用 ASCII 字元作為識別名，這也是個任何 portable 程式碼需遵
守的慣例。如果要正確地顯示所有字元，您的編輯器需要能夠認識檔案為 UTF-8，
並且需要能顯示檔案中所有字元的字型。

如果不使用預設編碼，則要聲明檔案的編碼，檔案的`第一'行要寫成特殊註解。語
法如下：

     # -*- coding: encoding -*-

其中， `encoding' 可以是 Python 支援的任意一種 *note codecs: 1b.。

比如，聲明使用 Windows-1252 編碼，源碼檔案要寫成：

     # -*- coding: cp1252 -*-

`第一行'的規則也有一種例外情況，在源碼以 *note UNIX "shebang" line:
1349. 行開頭時。此時，編碼聲明要寫在檔案的第二行。例如：

     #!/usr/bin/env python3
     # -*- coding: cp1252 -*-

註解
....


File: python.info,  Node: 一個非正式的 Python 簡介,  Next: 深入了解流程控制,  Prev: 使用 Python 直譯器,  Up: Python 教學

2.3 一個非正式的 Python 簡介
============================

在下面的例子中，輸入與輸出的區別在於有無提示符（prompt，*note >>>: 134d.
和 *note ...: 134e.）：如果要重做範例，你必須在提示符出現的時候，輸入提
示符後方的所有內容；那些非提示符開始的文字行是直譯器的輸出。注意到在範例
中，若出現單行只有次提示符時，代表該行你必須直接換行；這被使用在多行指令
結束輸入時。

在本手冊中的許多範例中，即便他們為互動式地輸入，仍然包含註解。Python 中
的註解 (comments) 由 hash 字元 ‘#’ 開始一直到該行結束。註解可以從該行之
首、空白後、或程式碼之後開始，但不會出現在字串文本 (string literal) 之中
。hash 字元在字串文本之中時仍視為一 hash 字元。因為註解只是用來說明程式
而不會被 Python 解讀，在練習範例時不一定要輸入。

一些範例如下：

     # 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."

* Menu:

* 把 Python 當作計算機使用::
* 初探程式設計的前幾步::


File: python.info,  Node: 把 Python 當作計算機使用,  Next: 初探程式設計的前幾步,  Up: 一個非正式的 Python 簡介

2.3.1 把 Python 當作計算機使用
------------------------------

讓我們來試試一些簡單的 Python 指令。啟動直譯器並等待第一個主提示符 ‘>>>’
出現。（應該不會等太久）

* Menu:

* 數字 (Number): 數字 Number.
* 字串 (String): 字串 String.
* List（串列）::


File: python.info,  Node: 數字 Number,  Next: 字串 String,  Up: 把 Python 當作計算機使用

2.3.1.1 數字 (Number)
.....................

直譯器如同一台簡單的計算機：你可以輸入一個 expression（運算式），它會寫
出該式的值。Expression 的語法很使用：運算子 ‘+’、‘-’、‘*’ 和 ‘/’ 的行為
如同大多數的程式語言（例如：Pascal 或 C）；括號 ‘()’ 可以用來分群。例如
：

     >>> 2 + 2
     4
     >>> 50 - 5*6
     20
     >>> (50 - 5*6) / 4
     5.0
     >>> 8 / 5  # division always returns a floating point number
     1.6

整數數字（即 ‘2’、‘4’、‘20’）為 *note int: 204. 型態，數字有小數點部份的
（即 ‘5.0’、‘1.6’）為 *note float: 1fd. 型態。我們將在之後的教學中看到更
多數字相關的型態。

除法 (‘/’) 永遠回傳一個 float。如果要做 *note floor division: 1f9. 並拿
到整數的結果（即去除所有小數點的部份），你可以使用 ‘//’ 運算子；計算餘數
可以使用 ‘%’：

     >>> 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

在 Python 中，計算冪次 (powers) 可以使用 ‘**’ 運算子 (1)：

     >>> 5 ** 2  # 5 squared
     25
     >>> 2 ** 7  # 2 to the power of 7
     128

等於符號 (‘=’) 可以用於為變數賦值。賦值完之後，在下個指示符前並不會顯示
任何結果：

     >>> width = 20
     >>> height = 5 * 9
     >>> width * height
     900

如果一個變數未被「定義 (defined)」（即變數未被賦值），試著使用它時會出現
一個錯誤：

     >>> n  # try to access an undefined variable
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     NameError: name 'n' is not defined

浮點數的運算有完善的支援，運算子 (operator) 遇上混合的運算元 (operand) 時
會把整數的運算元轉換為浮點數：

     >>> 4 * 3.75 - 1
     14.0

在互動式模式中，最後一個印出的運算式的結果會被指派至變數 ‘_’ 中。這表示
當你把 Python 當作桌上計算機使用者，要接續計算變得容易許多：

     >>> tax = 12.5 / 100
     >>> price = 100.50
     >>> price * tax
     12.5625
     >>> price + _
     113.0625
     >>> round(_, 2)
     113.06

這個變數應該被使用者視為只能讀取。不應該明確地為它賦值 — 你可以創一個獨
立但名稱相同的本地變數來覆蓋掉預設變數和它的神奇行為。

除了 *note int: 204. 和 *note float: 1fd.，Python 還支援了其他的數字型態
，包含 *note Decimal: 2c0. 和 *note Fraction: 2be.。Python 亦內建支援
*note 複數 (complex numbers): 1353.，並使用 ‘j’ 和 ‘J’ 後綴來指定虛數的
部份（即 ‘3+5j’）。

   ---------- Footnotes ----------

   (1) (1) 因為 ‘**’ 擁有較 ‘-’ 高的優先次序，‘-3**2’ 會被解釋為
‘-(3**2)’ 並得到 ‘-9’。如果要避免這樣的優先順序以得到 ‘9’，你可以使用
‘(-3)**2’。


File: python.info,  Node: 字串 String,  Next: List（串列）,  Prev: 數字 Number,  Up: 把 Python 當作計算機使用

2.3.1.2 字串 (String)
.....................

除了數字之外，Python 也可以操作字串，而表達字串有數種方式。它們可以用包
含在單引號 (‘'...'’) 或雙引號 (‘"..."’) 之中，兩者會得到相同的結果(1)。
使用 ‘\’ 跳脫出現於字串中的引號：

     >>> '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.'

在互動式的直譯器中，輸出的字串會被引號包圍且特殊符號會使用反斜線 (‘\’) 跳
脫。雖然這有時會讓它看起來跟輸入的字串不相同（包圍用的引號可能會改變），
輸入和輸出兩字串實為相同。一般來說，字串包含單引號而沒有雙引號時，會使用
雙引號包圍字串。函式 *note print(): 971. 會產生更易讀的輸出，它會去除掉
包圍的引號，並且直接印出被跳脫的字元和特殊字元：

     >>> '"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.

如果你不希望字元前出現 ‘\’ 就被當成特殊字元時，可以改使用 `raw string'，
在第一個包圍引號前加上 ‘r’ ：

     >>> 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

字串文本可以跨越數行。其中一方式是使用三個重覆引號：‘"""..."""’ 或
‘'''...'''’。此時換行會被自動加入字串值中，但也可以在換行前加入 ‘\’ 來取
消這個行為。在以下的例子中：

     print("""\
     Usage: thingy [OPTIONS]
          -h                        Display this usage message
          -H hostname               Hostname to connect to
     """)

會產生以下的輸出（注意第一個換行並沒有被包含進字串值中）：

     Usage: thingy [OPTIONS]
          -h                        Display this usage message
          -H hostname               Hostname to connect to

字串可以使用 ‘+’ 運算子連接 (concatenate)，並用 ‘*’ 重覆該字串的內容：

     >>> # 3 times 'un', followed by 'ium'
     >>> 3 * 'un' + 'ium'
     'unununium'

兩個以上相鄰的字串文本（`string literal'，即被引號包圍的字串）會被自動連
接起來：

     >>> 'Py' 'thon'
     'Python'

當你想要分段一個非常長的字串時，兩相鄰字串值自動連接的特性十分有用：

     >>> text = ('Put several strings within parentheses '
     ...         'to have them joined together.')
     >>> text
     'Put several strings within parentheses to have them joined together.'

但這特性只限於兩相鄰的字串值間，而非兩相鄰變數或表達式：

     >>> 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

如果要連接變數們或一個變數與一個字串值，使用 ‘+’：

     >>> prefix + 'thon'
     'Python'

字串可以被「索引 `indexed'」(下標，即 subscripted)，第一個字元的索引值為
0。沒有獨立表示字元的型別；一個字元就是一個大小為 1 的字串：

     >>> word = 'Python'
     >>> word[0]  # character in position 0
     'P'
     >>> word[5]  # character in position 5
     'n'

索引值可以是負的，此時改成從右開始計數：

     >>> word[-1]  # last character
     'n'
     >>> word[-2]  # second-last character
     'o'
     >>> word[-6]
     'P'

注意到因為 -0 等同於 0，負的索引值由 -1 開始。

除了索引外，字串亦支援「切片 `slicing'」。索引用來拿到單獨的字元，而切片
則可以讓你拿到子字串 (substring)：

     >>> word[0:2]  # characters from position 0 (included) to 2 (excluded)
     'Py'
     >>> word[2:5]  # characters from position 2 (included) to 5 (excluded)
     'tho'

切片索引 (slice indices) 有很常用的預設值，省略起點索引值時預設為 0，而
省略第二個索引值時預設整個字串被包含在 slice 中：

     >>> 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'

注意到起點永遠被包含，而結尾永遠不被包含。這確保了 ‘s[:i] + s[i:]’ 永遠
等於 ‘s’：

     >>> word[:2] + word[2:]
     'Python'
     >>> word[:4] + word[4:]
     'Python'

這裡有個簡單記住 slice 是如何運作的方式。想像 slice 的索引值指著字元們之
間，其中第一個字元的左側邊緣由 0 計數。則 `n' 個字元的字串中最後一個字元
的右側邊緣會有索引值 `n'，例如：

      +---+---+---+---+---+---+
      | P | y | t | h | o | n |
      +---+---+---+---+---+---+
      0   1   2   3   4   5   6
     -6  -5  -4  -3  -2  -1

第一行數字給定字串索引值為 0...6 的位置；第二行則標示了負索引值的位置。
由 `i' 至 `j' 的 slice 包含了標示 `i' 和 `j' 邊緣間的所有字元。

對非負數的索引值而言，一個 slice 的長度等於其索引值之差，如果索引值落在
字串邊界內。例如，‘word[1:3]’ 的長度是 2。

嘗試使用一個過大的索引值會造成錯誤：

     >>> 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

然而，超出範圍的索引值在 slice 中會被妥善的處理：

     >>> word[4:42]
     'on'
     >>> word[42:]
     ''

Python 字串無法被改變 — 它們是 *note immutable: 1356.。因此，嘗試對字串
中某個索引位置賦值會產生錯誤：

     >>> 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

如果你需要一個不一樣的字串，你必須建立一個新的：

     >>> 'J' + word[1:]
     'Jython'
     >>> word[:2] + 'py'
     'Pypy'

內建的函式 *note len(): 28b. 回傳一個字串的長度：

     >>> s = 'supercalifragilisticexpialidocious'
     >>> len(s)
     34

也參考
......

*note 文本序列类型 — str: 1357.

     字串是 `sequence 型別'的範例之一，並支援該型別常用的操作。

*note 字符串的方法: 1358.

     字串支援非常多種基本轉換和搜尋的 method（方法）。

*note 格式字符串字面值: 296.

     包含有運算式的字串文本。

*note 格式字符串语法: de0.

     關於透過 *note str.format(): 5d4. 字串格式化 (string formatting) 的
     資訊。

*note printf 风格的字符串格式化: 1359.

     在字串為 ‘%’ 運算子的左運算元時，將觸發舊的字串格式化操作，更多的細
     節在本連結中介紹。

   ---------- Footnotes ----------

   (1) (2) 不像其他語言，特殊符號如 ‘\n’ 在單 (‘'...'’) 和雙 (‘"..."’) 引
號中有相同的意思。兩種引號的唯一差別，在於使用單引號時，不需要跳脫 ‘"’（
但必須跳脫 ‘\'’），反之亦同。


File: python.info,  Node: List（串列）,  Prev: 字串 String,  Up: 把 Python 當作計算機使用

2.3.1.3 List（串列）
....................

Python 理解數種複合型資料型別，用來組合不同的數值。當中最多樣變化的型別
為 `list'，可以寫成一系列以逗號分隔的數值（稱之元素，即 item），包含在方
括號之中。List 可以包合不同型別的元素，但通常這些元素會有相同的型別：

     >>> squares = [1, 4, 9, 16, 25]
     >>> squares
     [1, 4, 9, 16, 25]

如同字串（以及其他內建的 *note sequence: 135c. 型別），list 可以被索引和
切片 (slice)：

     >>> squares[0]  # indexing returns the item
     1
     >>> squares[-1]
     25
     >>> squares[-3:]  # slicing returns a new list
     [9, 16, 25]

所有切片操作都會回傳一個新的 list ，包含要求的元素。這意謂著以下這個切片
回傳了原本 list 的 *note 淺複製: 135d. ：

     >>> squares[:]
     [1, 4, 9, 16, 25]

List 對支援如接合 (concatenation) 等操作：

     >>> squares + [36, 49, 64, 81, 100]
     [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

不同於字串是 *note immutable: 1356.，list 是 *note mutable: 135e. 型別，
即改變 list 的內容是可能的：

     >>> 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]

你也可以在 list 的最後加入新元素，透過使用 ‘append()’ `方法' (method)（
我們稍後會看到更多方法的說明）：

     >>> 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]

也可以對 slice 賦值，這能改變 list 的大小，甚至是清空一個 list：

     >>> 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
     []

內建的函式 *note len(): 28b. 亦可以作用在 list 上：

     >>> letters = ['a', 'b', 'c', 'd']
     >>> len(letters)
     4

也可以嵌套多層 list （建立 list 包含其他 list），例如：

     >>> 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'


File: python.info,  Node: 初探程式設計的前幾步,  Prev: 把 Python 當作計算機使用,  Up: 一個非正式的 Python 簡介

2.3.2 初探程式設計的前幾步
--------------------------

當然，我們可以用 Python 來處理比 2 加 2 更複雜的工作。例如，我們可以印出
費氏數列(1)的首幾項序列：

     >>> # 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

這例子引入了許多新的特性。

   * 第一行出現了多重賦值：變數 ‘a’ 與 ‘b’ 同時得到了新的值 0 與 1。在最
     後一行同樣的賦值再被使用了一次，示範了等號的右項運算 (expression) 會
     先被計算 (evaluate)，賦值再發生。右項的運算式由左至右依序被計算。

   * *note while: 1361. 迴圈只要它的條件為真（此範例：‘a < 10’），將會一
     直重覆執行。在 Python 中如同 C 語言，任何非零的整數值為真 (true)；
     零為假 (false)。條件可以是字串、list、甚至是任何序列型別；任何非零
     長度的序列為真，空的序列即為假。本例子使用的條件是個簡單的比較。標
     準的比較運算子 (comparison operators) 使用如同 C 語言一樣的符號：
     ‘<’（小於）、‘>’（大於）、‘==’（等於）、‘<=’（小於等於）、‘>=’（大
     於等於）以及 ‘!=’（不等於）。

   * 迴圈的主體會`縮排'：縮排在 Python 中用來關連一群陳述式。在互動式提
     示符中，你必須在迴圈內的每一行一開始鍵入 tab 或者（數個）空白來維持
     縮排。實務上，你會先在文字編輯器中準備好比較複雜的輸入；多數編輯器
     都有自動縮排的功能。當一個複合陳述式以互動地方式輸入，必須在結束時
     多加一行空行來代表結束（因為語法解析器無法判斷你何時輸入複合陳述的
     最後一行）。注意在一個縮排段落內的縮排方式與數量必須維持一致。

   * *note print(): 971. 函式印出它接收到引數（們）的值。不同於先前僅我
     們寫下想要的運算（像是先前的計算機範例），它可以處理複數個引數、浮
     點數數值和字串。印出的字串將不帶有引號，並且不同項目間會插入一個空
     白，因此可以讓你容易格式化輸出，例如：

          >>> i = 256*256
          >>> print('The value of i is', i)
          The value of i is 65536

     關鍵字引數 `end' 可以被用來避免額外的換行符加入到輸出中，或者以不同
     的字串結束輸出：

          >>> 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,

註解
....

   ---------- Footnotes ----------

   (1) 
https://zh.wikipedia.org/zh-tw/%E6%96%90%E6%B3%A2%E9%82%A3%E5%A5%91%E6%95%B0%E5%88%97


File: python.info,  Node: 深入了解流程控制,  Next: 資料結構,  Prev: 一個非正式的 Python 簡介,  Up: Python 教學

2.4 深入了解流程控制
====================

除了剛才介紹的 *note while: 1361.，Python 擁有在其他程式語言中常用的流程
控制語法，並有一些不一樣的改變。

* Menu:

* if 陳述式::
* for 陳述式::
* range() 函式: range 函式.
* 迴圈內的 break 和 continue 陳述式及 else 子句::
* pass 陳述式::
* 定義函式 (function): 定義函式 function.
* 深入了解函式定義::
* 間奏曲：程式碼風格 (Coding Style): 間奏曲：程式碼風格 Coding Style.


File: python.info,  Node: if 陳述式,  Next: for 陳述式,  Up: 深入了解流程控制

2.4.1 ‘if’ 陳述式
-----------------

或許最常見的陳述式種類就是 *note if: eab. 了。舉例來說：

     >>> 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

在陳述式中，可以沒有或有許多個 *note elif: 1367. 敘述，且 *note else:
1368. 敘述並不是必要的。關鍵字 ‘elif’ 是「else if」的縮寫，用來避免過多
的縮排。一個 ‘if’ ...  ‘elif’ ...  ‘elif’ ... 序列可以用來替代其他程式語
言中的 ‘switch’ 或 ‘case’ 陳述式。


File: python.info,  Node: for 陳述式,  Next: range 函式,  Prev: if 陳述式,  Up: 深入了解流程控制

2.4.2 ‘for’ 陳述式
------------------

在 Python 中的 *note for: cfa. 陳述式有點不同於在 C 或 Pascal 中的慣用方
式。相較於只能疊代 (iterate) 一個等差數列（如 Pascal），或給予使用者定義
疊代步驟與終止條件（如 C），Python 的 ‘for’ 陳述式疊代任何序列（list 或
者字串）的元素，順序與它們出現在序列中的順序相同。例如（無意雙關）：

     >>> # Measure some strings:
     ... words = ['cat', 'window', 'defenestrate']
     >>> for w in words:
     ...     print(w, len(w))
     ...
     cat 3
     window 6
     defenestrate 12

在疊代一個集合的同時修改該集合的內容，很難獲取想要的結果。比較直觀的替代
方式，是疊代該集合的副本，或建立一個新的集合：

     # 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


File: python.info,  Node: range 函式,  Next: 迴圈內的 break 和 continue 陳述式及 else 子句,  Prev: for 陳述式,  Up: 深入了解流程控制

2.4.3 ‘range()’ 函式
--------------------

如果你需要疊代一個數列的話，使用內建 *note range(): 1f5. 函式就很方便。
它可以生成一等差數列：

     >>> for i in range(5):
     ...     print(i)
     ...
     0
     1
     2
     3
     4

給定的結束值永遠不會出現在生成的序列中；‘range(10)’ 生成的 10 個數值，即
對應存取一個長度為 10 的序列內每一個項目的索引值。也可以讓 range 從其他
數值開始計數，或者給定不同的公差（甚至為負；有時稱之為 step）：

     >>> 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]

欲疊代一個序列的索引值，你可以搭配使用 *note range(): 1f5. 和 *note
len(): 28b. 如下：

     >>> 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

然而，在多數的情況，使用 *note enumerate(): ea7. 函式將更為方便，詳見
*note 迴圈技巧: 136d.。

如果直接印出一個 range 則會出現奇怪的輸出：

     >>> range(10)
     range(0, 10)

在很多情況下，由 *note range(): 1f5. 回傳的物件表現得像是一個 list（串列
）一樣，但實際上它並不是。它是一個在疊代時能夠回傳所要求的序列中所有項目
的物件，但它不會真正建出這個序列的 list，以節省空間。

我們稱這樣的物件為 *note iterable: c7c.（可疊代物件），意即能作為函式及
架構中可以一直獲取項目直到取盡的對象。我們已經了解 *note for: cfa. 陳述
式就是如此的架構，另一個使用 iterable 的函式範例是 *note sum(): 316.：

     >>> sum(range(4))  # 0 + 1 + 2 + 3
     6

待會我們可以看到更多回傳 iterable 和使用 iterable 為引數的函式。在*note
資料結構: 136e.章節中，我們會討論更多關於 *note list(): 1f8. 的細節。


File: python.info,  Node: 迴圈內的 break 和 continue 陳述式及 else 子句,  Next: pass 陳述式,  Prev: range 函式,  Up: 深入了解流程控制

2.4.4 迴圈內的 ‘break’ 和 ‘continue’ 陳述式及 ‘else’ 子句
---------------------------------------------------------

*note break: 3fa. 陳述式，如同 C 語言，終止包含它的最內部 *note for:
cfa. 或 *note while: 1361. 迴圈。

迴圈陳述式可以帶有一個 ‘else’ 子句。當迴圈用盡所有的 iterable （在 *note
for: cfa. 中）或條件為假（在 *note while: 1361. 中）時，這個子句會被執行
；但迴圈被 *note break: 3fa. 陳述式終止時則不會執行。底下尋找質數的迴圈
即示範了這個行為：

     >>> 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

（沒錯，這是正確的程式碼。請看仔細：‘else’ 子句屬於 *note for: cfa. 迴圈
，`並非' *note if: eab. 陳述式。）

當 ‘else’ 子句用於迴圈時，相較於搭配 *note if: eab. 陳述式使用，它的行為
與 *note try: e37. 陳述式中的 ‘else’ 子句更為相似：*note try: e37. 陳述
式的 ‘else’ 子句在沒有發生例外 (exception) 時執行，而迴圈的 ‘else’ 子句
在沒有任何 ‘break’ 發生時執行。更多有關 ‘try’ 陳述式和例外的介紹，見
*note 處理例外: 1371.。

*note continue: 2bb. 陳述式，亦承襲於 C 語言，讓所屬的迴圈繼續執行下個疊
代：

     >>> 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


File: python.info,  Node: pass 陳述式,  Next: 定義函式 function,  Prev: 迴圈內的 break 和 continue 陳述式及 else 子句,  Up: 深入了解流程控制

2.4.5 ‘pass’ 陳述式
-------------------

*note pass: 1374. 陳述式不執行任何動作。它可用在語法上需要一個陳述式但程
式不需要執行任何動作的時候。例如：

     >>> while True:
     ...     pass  # Busy-wait for keyboard interrupt (Ctrl+C)
     ...

這經常用於建立簡單的 class（類別）：

     >>> class MyEmptyClass:
     ...     pass
     ...

*note pass: 1374. 亦可作為一個函式或條件判斷主體的預留位置，在你撰寫新的
程式碼時讓你保持在更抽象的思維層次。‘pass’ 會直接被忽略：

     >>> def initlog(*args):
     ...     pass   # Remember to implement this!
     ...


File: python.info,  Node: 定義函式 function,  Next: 深入了解函式定義,  Prev: pass 陳述式,  Up: 深入了解流程控制

2.4.6 定義函式 (function)
-------------------------

我們可以建立一個函式來產生費式數列到任何一個上界：

     >>> 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

關鍵字 *note def: e83. 介紹一個函式的`定義'。它之後必須連著該函式的名稱
和置於括號之中的一串參數。自下一行起，所有縮排的陳述式成為該函式的主體。

一個函式的第一個陳述式可以是一個字串文本；該字串文本被視為該函式的說明文
件字串，即 `docstring'。（關於 docstring 的細節請參見*note 說明文件字串
(Documentation Strings): 1377.段落。）有些工具可以使用 docstring 來自動
產生線上或可列印的文件，或讓使用者能以互動的方式在原始碼中瀏覽文件。在原
始碼中加入 docstring 是個好慣例，應該養成這樣的習慣。

函式`執行'時會建立一個新的符號表 (symbol table) 來儲存該函式內的區域變數
(local variable)。更精確地說，所有在函式內的變數賦值都會把該值儲存在一個
區域符號表。然而，在引用一個變數時，會先從區域符號表開始搜尋，其次為外層
函式的區域符號表，其次為全域符號表 (global symbol table)，最後為所有內建
的名稱。因此，在函式中，全域變數及外層函式變數雖然可以被引用，但無法被直
接賦值（除非全域變數是在 *note global: 1378. 陳述式中被定義，或外層函式
變數在 *note nonlocal: d07. 陳述式中被定義）。

在一個函式被呼叫的時候，實際傳入的參數（引數）會被加入至該函式的區域符號
表。因此，引數傳入的方式為`傳值呼叫 (call by value)'（這裡傳遞的`值'永遠
是一個物件的`參照 (reference)'，而不是該物件的值）。(1) 當一個函式呼叫別
的函式或遞迴呼叫它自己時，在被呼叫的函式中會建立一個新的區域符號表。

函式定義時，會把該函式名稱加入至當前的符號表。函式名稱的值帶有一個型別，
並被直譯器辨識為使用者自定函式 (user-defined function)。該值可以被指定給
別的變數名，使該變數名也可以被當作函式使用。這是常見的重新命名方式：

     >>> fib
     <function fib at 10042ed0>
     >>> f = fib
     >>> f(100)
     0 1 1 2 3 5 8 13 21 34 55 89

如果你是來自別的語言，你可能不同意 ‘fib’ 是個函式，而是個程序
(procedure)，因為它並沒有回傳值。實際上，即使一個函式缺少一個 *note
return: 2c8. 陳述式，它亦有一個固定的回傳值。這個值稱為 ‘None’（它是一個
內建名稱）。在直譯器中單獨使用 ‘None’ 時，通常不會被顯示。你可以使用
*note print(): 971. 來看到它：

     >>> fib(0)
     >>> print(fib(0))
     None

如果要寫一個函式回傳費式數列的 list 而不是直接印出它，這也很容易：

     >>> 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]

這個例子一樣示範了一些新的 Python 特性：

   * *note return: 2c8. 陳述式會讓一個函式回傳一個值。單獨使用 ‘return’
     不外加一個運算式作為引數時會回傳 ‘None’。一個函式執行到結束也會回傳
     ‘None’。

   * ‘result.append(a)’ 陳述式呼叫了一個 list 物件 ‘result’ 的 `method（
     方法）'。method 為「屬於」一個物件的函式，命名規則為
     ‘obj.methodname’，其中 ‘obj’ 為某個物件（亦可為一運算式），而
     ‘methodname’ 為該 method 的名稱，並由該物件的型別所定義。不同的型別
     定義不同的 method。不同型別的 method 可以擁有一樣的名稱而不會讓
     Python 混淆。（你可以使用 `class'（類別）定義自己的物件型別和
     method，見 *note Class（類別）: 1379.）範例中的 ‘append()’ method 定
     義在 list 物件中；它會在該 list 的末端加入一個新的元素。這個例子等
     同於 ‘result = result + [a]’，但更有效率。

   ---------- Footnotes ----------

   (1) (1) 實際上，`傳址呼叫 (call by object reference)' 的說法可能較為
貼切。因為，若傳遞的是一個可變物件時，呼叫者將看得見被呼叫者對物件做出的
任何改變（例如被插入 list 內的新項目）。


File: python.info,  Node: 深入了解函式定義,  Next: 間奏曲：程式碼風格 Coding Style,  Prev: 定義函式 function,  Up: 深入了解流程控制

2.4.7 深入了解函式定義
----------------------

定義函式時使用的引數 (argument) 數量是可變的。總共有三種可以組合使用的形
式。

* Menu:

* 預設引數值::
* 關鍵字引數::
* 特殊參數::
* 任意引數列表 (Arbitrary Argument Lists): 任意引數列表 Arbitrary Argument Lists.
* 拆解引數列表（Unpacking Argument Lists）::
* Lambda 運算式::
* 說明文件字串 (Documentation Strings): 說明文件字串 Documentation Strings.
* 函式註釋 (Function Annotations): 函式註釋 Function Annotations.


File: python.info,  Node: 預設引數值,  Next: 關鍵字引數,  Up: 深入了解函式定義

2.4.7.1 預設引數值
..................

為一個或多個引數指定預設值是很有用的方式。函式建立後，可以用比定義時更少
的引數呼叫該函式。例如：

     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)

該函式可以用以下幾種方式被呼叫：

   * 只給必要引數：‘ask_ok('Do you really want to quit?')’

   * 給予一個選擇性引數：‘ask_ok('OK to overwrite the file?', 2)’

   * 給予所有引數：‘ask_ok('OK to overwrite the file?', 2, 'Come on,
     only yes or no!')’

此例也使用了關鍵字 *note in: 179.，用於測試序列中是否包含某個特定值。

預設值是在函式定義當下，於`定義時'的作用域中求值，所以：

     i = 5

     def f(arg=i):
         print(arg)

     i = 6
     f()

將會輸出 ‘5’。

`重要警告'：預設值只求值一次。當預設值為可變物件，例如 list、
dictionary（字典）或許多類別實例時，會產生不同的結果。例如，以下函式於後
續呼叫時會累積曾經傳遞的引數：

     def f(a, L=[]):
         L.append(a)
         return L

     print(f(1))
     print(f(2))
     print(f(3))

將會輸出：

     [1]
     [1, 2]
     [1, 2, 3]

如果不想在後續呼叫之間共用預設值，應以如下方式編寫函式：

     def f(a, L=None):
         if L is None:
             L = []
         L.append(a)
         return L


File: python.info,  Node: 關鍵字引數,  Next: 特殊參數,  Prev: 預設引數值,  Up: 深入了解函式定義

2.4.7.2 關鍵字引數
..................

函式也可以使用*note 關鍵字引數: 6bb.，以 ‘kwarg=value’ 的形式呼叫。舉例
來說，以下函式：

     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, "!")

接受一個必要引數 (‘voltage’) 和三個選擇性引數 (‘state’，‘action’，和
‘type’)。該函式可用下列任一方式呼叫：

     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

但以下呼叫方式都無效：

     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

函式呼叫時，關鍵字引數 (keyword argument) 必須在位置引數 (positional
argument) 後面。所有傳遞的關鍵字引數都必須匹配一個可被函式接受的引數（
‘actor’ 不是 ‘parrot’ 函式的有效引數），而關鍵字引數的順序並不重要。此規
則也包括必要引數，（‘parrot(voltage=1000)’ 也有效）。一個引數不可多次被
賦值，下面就是一個因此限制而無效的例子：

     >>> 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'

當最後一個參數為 ‘**name’ 形式時，它接收一個 dictionary（字典，詳見
*note 映射类型 — dict: 40e.），該字典包含所有可對應形式參數以外的關鍵字
引數。‘**name’ 可以與 ‘*name’ 參數（下一小節介紹）組合使用，‘*name’ 接收
一個 *note tuple: 1380.，該 tuple 包含一般參數以外的位置引數（‘*name’ 必
須出現在 ‘**name’ 前面）。例如，若我們定義這樣的函式：

     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])

它可以被如此呼叫：

     cheeseshop("Limburger", "It's very runny, sir.",
                "It's really very, VERY runny, sir.",
                shopkeeper="Michael Palin",
                client="John Cleese",
                sketch="Cheese Shop Sketch")

輸出結果如下：

     -- 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

注意，關鍵字引數的輸出順序與呼叫函式時被提供的順序必定一致。


File: python.info,  Node: 特殊參數,  Next: 任意引數列表 Arbitrary Argument Lists,  Prev: 關鍵字引數,  Up: 深入了解函式定義

2.4.7.3 特殊參數
................

在預設情況，引數能以位置或明確地以關鍵字傳遞给 Python 函式。為了程式的可
讀性及效能，限制引數的傳遞方式是合理的，如此，開發者只需查看函式定義，即
可確定各項目是按位置，按位置或關鍵字，還是按關鍵字傳遞。

函式定義可能如以下樣式：

     def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
           -----------    ----------     ----------
             |             |                  |
             |        Positional or keyword   |
             |                                - Keyword only
              -- Positional only

‘/’ 和 ‘*’ 是選擇性的。這些符號若被使用，是表明引數被傳遞給函式的參數種
類：僅限位置、位置或關鍵字、僅限關鍵字。關鍵字參數也稱為附名參數 (named
parameters)。

* Menu:

* 位置或關鍵字引數 (Positional-or-Keyword Arguments): 位置或關鍵字引數 Positional-or-Keyword Arguments.
* 僅限位置參數 (Positional-Only Parameters): 僅限位置參數 Positional-Only Parameters.
* 僅限關鍵字引數 (Keyword-Only Arguments): 僅限關鍵字引數 Keyword-Only Arguments.
* 函式範例::
* 回顧::


File: python.info,  Node: 位置或關鍵字引數 Positional-or-Keyword Arguments,  Next: 僅限位置參數 Positional-Only Parameters,  Up: 特殊參數

2.4.7.4 位置或關鍵字引數 (Positional-or-Keyword Arguments)
..........................................................

若函式定義中未使用 ‘/’ 和 ‘*’ 時，引數可以按位置或關鍵字傳遞給函式。


File: python.info,  Node: 僅限位置參數 Positional-Only Parameters,  Next: 僅限關鍵字引數 Keyword-Only Arguments,  Prev: 位置或關鍵字引數 Positional-or-Keyword Arguments,  Up: 特殊參數

2.4.7.5 僅限位置參數 (Positional-Only Parameters)
.................................................

此處再詳述一些細節，特定參數可以標記為`僅限位置'。若參數為`僅限位置'時，
它們的順序很重要，且這些參數不能用關鍵字傳遞。僅限位置參數必須放在 ‘/’（
斜線）之前。‘/’ 用於在邏輯上分開僅限位置參數與其餘參數。如果函式定義中沒
有 ‘/’，則表示沒有任何僅限位置參數。

‘/’ 後面的參數可以是`位置或關鍵字'或`僅限關鍵字'參數。


File: python.info,  Node: 僅限關鍵字引數 Keyword-Only Arguments,  Next: 函式範例,  Prev: 僅限位置參數 Positional-Only Parameters,  Up: 特殊參數

2.4.7.6 僅限關鍵字引數 (Keyword-Only Arguments)
...............................................

要把參數標記為`僅限關鍵字'，表明參數必須以關鍵字引數傳遞，必須在引數列表
中第一個`僅限關鍵字'參數前放上 ‘*’。


File: python.info,  Node: 函式範例,  Next: 回顧,  Prev: 僅限關鍵字引數 Keyword-Only Arguments,  Up: 特殊參數

2.4.7.7 函式範例
................

請看以下的函式定義範例，注意 ‘/’ 和 ‘*’ 記號：

     >>> 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)

第一個函式定義 ‘standard_arg’ 是我們最熟悉的形式，對呼叫方式沒有任何限制
，可以按位置或關鍵字傳遞引數：

     >>> standard_arg(2)
     2

     >>> standard_arg(arg=2)
     2

第二個函式 ‘pos_only_arg’ 的函式定義中有 ‘/’，因此僅限使用位置參數：

     >>> 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'

第三個函式 ‘kwd_only_args’ 的函式定義透過 ‘*’ 表明僅限關鍵字引數：

     >>> 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

最後一個函式在同一個函式定義中，使用了全部三種呼叫方式：

     >>> 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'

最後，請看這個函式定義，如果 ‘**kwds’ 內有 ‘name’ 這個鍵，可能與位置引數
‘name’ 產生潛在衝突：

     def foo(name, **kwds):
         return 'name' in kwds

呼叫該函式不可能回傳 ‘True’，因為關鍵字 ‘'name'’ 永遠是連結在第一個參數
。例如：

     >>> foo(1, **{'name': 2})
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     TypeError: foo() got multiple values for argument 'name'
     >>>

使用 ‘/’（僅限位置引數）後，就可以了。函式定義會允許 ‘name’ 當作位置引數
，而 ‘'name'’ 也可以當作關鍵字引數中的鍵：

     def foo(name, /, **kwds):
         return 'name' in kwds
     >>> foo(1, **{'name': 2})
     True

換句話說，僅限位置參數的名稱可以在 ‘**kwds’ 中使用，而不產生歧義。


File: python.info,  Node: 回顧,  Prev: 函式範例,  Up: 特殊參數

2.4.7.8 回顧
............

此用例決定哪些參數可以用於函式定義：

     def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):

說明：

   * 如果不想讓使用者使用參數名稱，請使用僅限位置。當參數名稱沒有實際意
     義時，若你想控制引數在函式呼叫的排列順序，或同時使用位置參數和任意
     關鍵字時，這種方式很有用。

   * 當參數名稱有意義，且明確的名稱可讓函式定義更易理解，或是你不希望使
     用者依賴引數被傳遞時的位置時，請使用僅限關鍵字。

   * 對於應用程式介面 (API)，使用僅限位置，以防止未來參數名稱被修改時造
     成 API 的中斷性變更。


File: python.info,  Node: 任意引數列表 Arbitrary Argument Lists,  Next: 拆解引數列表（Unpacking Argument Lists）,  Prev: 特殊參數,  Up: 深入了解函式定義

2.4.7.9 任意引數列表 (Arbitrary Argument Lists)
...............................................

最後，有個較不常用的選項，是規定函式被呼叫時，可以使用任意數量的引數。這
些引數會被包裝進一個 tuple 中（詳見 *note Tuples 和序列 (Sequences):
1380.）。在可變數量的引數之前，可能有零個或多個普通引數：

     def write_multiple_items(file, separator, *args):
         file.write(separator.join(args))

通常，這些 ‘variadic’（可變的）引數會出現在參數列表的最末端，這樣它們就
可以把所有傳遞給函式的剩餘輸入引數都撈起來。出現在 ‘*args’ 參數後面的任
何參數必須是「僅限關鍵字」引數，意即它們只能作為關鍵字引數，而不能用作位
置引數。

     >>> def concat(*args, sep="/"):
     ...     return sep.join(args)
     ...
     >>> concat("earth", "mars", "venus")
     'earth/mars/venus'
     >>> concat("earth", "mars", "venus", sep=".")
     'earth.mars.venus'


File: python.info,  Node: 拆解引數列表（Unpacking Argument Lists）,  Next: Lambda 運算式,  Prev: 任意引數列表 Arbitrary Argument Lists,  Up: 深入了解函式定義

2.4.7.10 拆解引數列表（Unpacking Argument Lists）
.................................................

當引數們已經存在一個 list 或 tuple 裡，但為了滿足一個需要個別位置引數的
函式呼叫，而去拆解它們時，情況就剛好相反。例如，內建的 *note range():
1f5. 函式要求分開的 `start' 和 `stop' 引數。如果這些引數不是分開的，則要
在呼叫函式時，用 ‘*’ 運算子把引數們從 list 或 tuple 中拆解出來：

     >>> 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]

同樣地，dictionary（字典）可以用 ‘**’ 運算子傳遞關鍵字引數：

     >>> 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 !


File: python.info,  Node: Lambda 運算式,  Next: 說明文件字串 Documentation Strings,  Prev: 拆解引數列表（Unpacking Argument Lists）,  Up: 深入了解函式定義

2.4.7.11 Lambda 運算式
......................

*note lambda: cf9. 關鍵字用於建立小巧的匿名函式。‘lambda a, b: a+b’ 函式
返回兩個引數的和。Lambda 函式可用於任何需要函數物件的地方。在語法上，它
們被限定只能是單一運算式。在語義上，它就是一個普通函式定義的語法糖
(syntactic sugar)。與巢狀函式定義一樣，lambda 函式可以從包含它的作用域中
引用變數：

     >>> def make_incrementor(n):
     ...     return lambda x: x + n
     ...
     >>> f = make_incrementor(42)
     >>> f(0)
     42
     >>> f(1)
     43

上面的例子用 lambda 運算式回傳了一個函式。另外的用法是傳遞一個小函式當作
引數：

     >>> 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')]


File: python.info,  Node: 說明文件字串 Documentation Strings,  Next: 函式註釋 Function Annotations,  Prev: Lambda 運算式,  Up: 深入了解函式定義

2.4.7.12 說明文件字串 (Documentation Strings)
.............................................

以下是關於說明文件字串內容和格式的慣例。

第一行都是一段關於此物件目的之簡短摘要。為保持簡潔，不應在這裡明確地陳述
物件的名稱或型別，因為有其他方法可以達到相同目的（除非該名稱剛好是一個描
述函式運算的動詞）。這一行應以大寫字母開頭，以句號結尾。

文件字串為多行時，第二行應為空白行，在視覺上將摘要與其餘描述分開。後面幾
行可包含一或多個段落，描述此物件的呼叫慣例、副作用等。

Python 剖析器 (parser) 不會去除 Python 中多行字串的縮排，因此，處理說明
文件的工具應在必要時去除縮排。這項操作遵循以下慣例：在字串第一行`之後'的
第一個非空白行決定了整個說明文件字串的縮排量（不能用第一行的縮排，因為它
通常與字串的開頭引號們相鄰，其縮排在字串文本中並不明顯），然後，所有字串
行開頭處與此縮排量「等價」的空白字元會被去除。不應出現比上述縮進量更少的
字串行，但若真的出現了，這些行的全部前導空白字元都應被去除。展開 tab 鍵
後（通常為八個空格），應測試空白字元量是否等價。

下面是多行說明字串的一個範例：

     >>> 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.


File: python.info,  Node: 函式註釋 Function Annotations,  Prev: 說明文件字串 Documentation Strings,  Up: 深入了解函式定義

2.4.7.13 函式註釋 (Function Annotations)
........................................

*note 函式註釋: 1390.是選擇性的元資料（metadata）資訊，描述使用者定義函
式所使用的型別（更多資訊詳見 PEP 3107(1) 和 PEP 484(2)）。

*note 註釋: 1391.以 dictionary（字典）的形式存放在函式的
‘__annotations__’ 屬性中，且不會影響函式的任何其他部分。參數註釋的定義方
式是在參數名稱後加一個冒號，冒號後面跟著一個對註釋求值的運算式。回傳註釋
的定義方式是在參數列表和 *note def: e83. 陳述式結尾的冒號中間，用一個
‘->’ 文字接著一個運算式。以下範例註釋了一個必要引數、一個選擇性引數，以
及回傳值：

     >>> 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'

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3107

   (2) https://www.python.org/dev/peps/pep-0484


File: python.info,  Node: 間奏曲：程式碼風格 Coding Style,  Prev: 深入了解函式定義,  Up: 深入了解流程控制

2.4.8 間奏曲：程式碼風格 (Coding Style)
---------------------------------------

現在你即將要寫更長、更複雜的 Python 程式，是時候討論一下`編碼樣式'了。大
多數語言都能以不同的樣式被書寫（或更精確地說，被`格式化'），而有些樣式比
其他的更具可讀性。能讓其他人輕鬆閱讀你的程式碼永遠是一個好主意，而使用優
良的編碼樣式對此有極大的幫助。

對於 Python，大多數的專案都遵循 PEP 8(1) 的樣式指南；它推行的編碼樣式相
當可讀且賞心悅目。每個 Python 開發者都應該花點時間研讀；這裡是該指南的核
心重點：

   * 用 4 個空格縮排，不要用 tab 鍵。

     4 個空格是小縮排（容許更大的巢套深度）和大縮排（較易閱讀）之間的折
     衷方案。Tab 鍵會造成混亂，最好別用。

   * 換行，使一行不超過 79 個字元。

     換行能讓使用小顯示器的使用者方便閱讀，也可以在較大顯示器上並排陳列
     多個程式碼檔案。

   * 用空行分隔函式和 class（類別），及函式內較大塊的程式碼。

   * 如果可以，把註解放在單獨一行。

   * 使用說明字串。

   * 運算子前後、逗號後要加空格，但不要直接放在括號內側：‘a = f(1, 2) +
     g(3, 4)’。

   * Class 和函式的命名樣式要一致；按慣例，命名 class 用
     ‘UpperCamelCase’（駝峰式大小寫），命名函式與 method 用
     ‘lowercase_with_underscores’（小寫加底線）。永遠用 ‘self’ 作為
     method 第一個引數的名稱（關於 class 和 method，詳見 *note 初見
     class: 1394.）。

   * 若程式碼是為了用於國際環境時，不要用花俏的編碼。Python 預設的 UTF-8
     或甚至普通的 ASCII，就可以勝任各種情況。

   * 同樣地，若不同語言使用者閱讀或維護程式碼的可能性微乎其微，就不要在
     命名時使用非 ASCII 字元。

註解
....

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0008


File: python.info,  Node: 資料結構,  Next: 模組 Module,  Prev: 深入了解流程控制,  Up: Python 教學

2.5 資料結構
============

這個章節將會更深入的介紹一些你已經學過的東西的細節上，並且加入一些你還沒
有接觸過的部分。

* Menu:

* 進一步了解 List（串列）::
* del 陳述式::
* Tuples 和序列 (Sequences): Tuples 和序列 Sequences.
* 集合 (Sets): 集合 Sets.
* 字典（Dictionary）::
* 迴圈技巧::
* 深入了解條件 (Condition): 深入了解條件 Condition.
* 序列和其他資料類型之比較::


File: python.info,  Node: 進一步了解 List（串列）,  Next: del 陳述式,  Up: 資料結構

2.5.1 進一步了解 List（串列）
-----------------------------

List（串列）這個資料型態，具有更多操作的方法。下面條列了所有關於 list 物
件的 method：

 -- 成員函式: list.append (x)

     將一個新的項目加到 list 的尾端。等同於 ‘a[len(a):] = [x]’。

 -- 成員函式: list.extend (iterable)

     將 iterable（可疊代物件）接到 list 的尾端。等同於 ‘a[len(a):] =
     iterable’。

 -- 成員函式: list.insert (i, x)

     將一個項目插入至 list 中給定的位置。第一個引數為插入處前元素的索引
     值，所以 ‘a.insert(0, x)’ 會插入在 list 首位，而 ‘a.insert(len(a),
     x)’ 則相當於 ‘a.append(x)’。

 -- 成員函式: list.remove (x)

     刪除 list 中第一個值等於 `x' 的元素。若 list 中無此元素則會觸發
     *note ValueError: 16d.。

 -- 成員函式: list.pop ([i])

     移除 list 中給定位置的項目，並回傳它。如果沒有指定位置， ‘a.pop()’
     將會移除 list 中最後的項目並回傳它。（在 `i' 周圍的方括號代表這個參
     數是選用的，並不代表你應該在該位置輸入方括號。你將會常常在 Python 函
     式庫參考指南中看見這個表示法）

 -- 成員函式: list.clear ()

     刪除 list 中所有項目。這等同於 ‘del a[:]’。

 -- 成員函式: list.index (x[, start[, end]])

     回傳 list 中第一個值等於 `x' 的項目之索引值（從零開始的索引）。若
     list 中無此項目，則丟出 *note ValueError: 16d. 錯誤。

     引數 `start' 和 `end' 的定義跟在 slice 表示法中相同，搜尋的動作被這
     兩個引數限定在 list 中特定的子序列。但要注意的是，回傳的索引值是從
     list 的開頭開始算，而不是從 `start' 開始算。

 -- 成員函式: list.count (x)

     回傳 `x' 在 list 中所出現的次數。

 -- 成員函式: list.sort (*, key=None, reverse=False)

     將 list 中的項目排序。（可使用引數來進行客製化的排序，請參考 *note
     sorted(): 546. 部分的解釋）

 -- 成員函式: list.reverse ()

     將 list 中的項目前後順序反過來。

 -- 成員函式: list.copy ()

     回傳一個淺複製 (shallow copy) 的 list。等同於 ‘a[:]’。

以下是一個使用到許多 list 物件方法的例子：

     >>> 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'

你可能會注意到一些方法，像是 ‘insert’、‘remove’ 或者是 ‘sort’，並沒有印
出回傳值，事實上，他們回傳預設值 ‘None’ (1)。這是一個用於 Python 中所有
可變資料結構的設計法則。

另外你可能也會發現，不是所有資料都可以被排序或比較。例如，‘[None,
'hello', 10]’ 就不可排序，因為整數不能與字串比較，而 `None' 不能與其他型
別比較。有些型別根本就沒有被定義彼此之間的大小順序，例如，‘3+4j < 5+7j’
就是一個無效的比較。

* Menu:

* 將 List 作為 Stack（堆疊）使用::
* 將 List 作為 Queue（佇列）使用::
* List Comprehensions（串列綜合運算）::
* 巢狀的 List Comprehensions::

   ---------- Footnotes ----------

   (1) (1) 其他語言可以回傳變更後的物件，這就允許 method 的串連，例如
‘d->insert("a")->remove("b")->sort();’。


File: python.info,  Node: 將 List 作為 Stack（堆疊）使用,  Next: 將 List 作為 Queue（佇列）使用,  Up: 進一步了解 List（串列）

2.5.1.1 將 List 作為 Stack（堆疊）使用
......................................

List 的操作方法使得它非常簡單可以用來實作 stack（堆疊）。Stack 為一個遵
守最後加入元素最先被取回（後進先出，"last-in, first-out"）規則的資料結構
。你可以使用方法 ‘append()’ 將一個項目放到堆疊的頂層。而使用方法 ‘pop()’
且不給定索引值去取得堆疊最上面的項目。舉例而言：

     >>> 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]


File: python.info,  Node: 將 List 作為 Queue（佇列）使用,  Next: List Comprehensions（串列綜合運算）,  Prev: 將 List 作為 Stack（堆疊）使用,  Up: 進一步了解 List（串列）

2.5.1.2 將 List 作為 Queue（佇列）使用
......................................

我們也可以將 list 當作 queue（佇列）使用，即最先加入元素最先被取回（先進
先出，"first-in, first-out"）的資料結構。然而，list 在這種使用方式下效率
較差。使用 ‘append’ 和 ‘pop’ 來加入和取出尾端的元素較快，而使用 ‘insert’
和 ‘pop’ 來插入和取出頭端的元素較慢（因為其他元素都需要挪動一格）。

如果要實作 queue，請使用 *note collections.deque: 62a.，其被設計成能快速
的從頭尾兩端加入和取出。例如：

     >>> 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'])


File: python.info,  Node: List Comprehensions（串列綜合運算）,  Next: 巢狀的 List Comprehensions,  Prev: 將 List 作為 Queue（佇列）使用,  Up: 進一步了解 List（串列）

2.5.1.3 List Comprehensions（串列綜合運算）
...........................................

List comprehension（串列綜合運算）讓你可以用簡潔的方法創建 list。常見的
應用是基於一個序列或 iterable（可疊代物件），將每一個元素經過某個運算的
結果串接起來成為新的 list，或是創建一個子序列，其每一個元素皆滿足一個特
定的條件。

舉例來說，假設我們要創建一個「平方的 list」：

     >>> squares = []
     >>> for x in range(10):
     ...     squares.append(x**2)
     ...
     >>> squares
     [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

注意這是創建（或覆寫）一個變數叫 ‘x’，其在迴圈結束後仍然存在。我們可以這
樣產生平方串列而不造成任何 side effects（副作用）：

     squares = list(map(lambda x: x**2, range(10)))

或與此相等的：

     squares = [x**2 for x in range(10)]

這樣更簡潔和易讀。

一個 list comprehension 的組成，是在一對方括號內，放入一個 expression（
運算式）、一個 ‘for’ 子句、再接著零個或多個 ‘for’ 或 ‘if’ 子句。結果會是
一個新的 list，內容是在後面的 ‘for’ 和 ‘if’ 子句情境下，對前面運算式求值
的結果。例如，這個 list comprehension 組合了兩個 list 中彼此相異的元素：

     >>> [(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)]

而它就等於：

     >>> 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)]

注意 *note for: cfa. 和 *note if: eab. 在這兩段程式裡的順序是相同的。

如果 expression 是一個 tuple（例如上面例子中的 ‘(x, y)’），它必須加上括
號：

     >>> 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]

List comprehensions 可以含有複雜的 expression 和巢狀的函式：

     >>> from math import pi
     >>> [str(round(pi, i)) for i in range(1, 6)]
     ['3.1', '3.14', '3.142', '3.1416', '3.14159']


File: python.info,  Node: 巢狀的 List Comprehensions,  Prev: List Comprehensions（串列綜合運算）,  Up: 進一步了解 List（串列）

2.5.1.4 巢狀的 List Comprehensions
..................................

在 list comprehesion 中開頭的 expression 可以是任何形式的 expression，包
括再寫一個 list comprehension。

考慮以下表示 3x4 矩陣的範例，使用 list 包含 3 個長度為 4 的 list ：

     >>> matrix = [
     ...     [1, 2, 3, 4],
     ...     [5, 6, 7, 8],
     ...     [9, 10, 11, 12],
     ... ]

以下的 list comprehesion 會將矩陣的行與列作轉置：

     >>> [[row[i] for row in matrix] for i in range(4)]
     [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

如同我們在上一節看到的，此巢狀的 list comprehension 會依據後面的 *note
for: cfa. 環境被求值，所以這個例子就等於：

     >>> 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]]

而它也和這一段相同：

     >>> 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]]

在實際運用上，我們傾向於使用內建函式 (built-in functions) 而不是複雜的流
程控制陳述式。在這個例子中，使用 *note zip(): cfc. 函式會非常有效率：

     >>> list(zip(*matrix))
     [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

關於星號的更多細節，請參考*note 拆解引數列表（Unpacking Argument
Lists）: 1389.。


File: python.info,  Node: del 陳述式,  Next: Tuples 和序列 Sequences,  Prev: 進一步了解 List（串列）,  Up: 資料結構

2.5.2 ‘del’ 陳述式
------------------

有一個方法可以藉由索引而不是值來刪除 list 中的項目：*note del: 13a2. 陳
述式。這和 ‘pop()’ method 傳回一個值不同，‘del’ 陳述式可以用來刪除 list
中的片段或者清空整個 list（我們之前藉由指派一個空的 list 給想刪除的片段
來完成這件事）。例如：

     >>> 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
     []

*note del: 13a2. 也可以用來刪除整個變數：

     >>> del a

刪除之後，對 ‘a’ 的參照將會造成錯誤（至少在另一個值又被指派到它之前）。
我們將在後面看到更多關於 *note del: 13a2. 的其他用法。


File: python.info,  Node: Tuples 和序列 Sequences,  Next: 集合 Sets,  Prev: del 陳述式,  Up: 資料結構

2.5.3 Tuples 和序列 (Sequences)
-------------------------------

我們看到 list 和字串 (string) 有許多共同的特性，像是索引操作 (indexing)
以及切片操作 (slicing) 。他們是`序列'資料類型中的兩個例子（請參考*note
序列类型 — list, tuple, range: 13a4.）。由於 Python 是個持續發展中的語言
，未來可能還會有其他的序列資料類型加入。接著要介紹是下一個標準序列資料類
型：`tuple'。

一個 tuple 是由若干個值藉由逗號區隔而組成，例如：

     >>> 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])

如同我們看到的，被輸出的 tuple 總是以括號包著，如此巢狀的 tuple 才能被正
確的直譯 (interpret)；他們可以是以被括號包著或不被包著的方式當作輸入，雖
然括號的使用常常是有其必要的（譬如此 tuple 是一個較大的運算式的一部分）
。指派東西給 tuple 中的個別項目是不行的，但是可以建立含有可變物件（譬如
list）的 tuple。

雖然 tuple 和 list 看起來很類似，但是他們通常用在不同的情況與不同目的。
tuple 是 *note immutable: 1356.（不可變的），通常儲存異質的元素序列，並
可經由拆解 (unpacking)（請參考本節後段）或索引 (indexing) 來存取（或者在
使用 *note namedtuples: 1a1. 的時候藉由屬性 (attribute) 來存取）。List 是
*note mutable: 135e.（可變的），其元素通常是同質的且可藉由疊代整個 list
來存取。

一個特別的議題是，關於創建一個含有 0 個或 1 個項目的 tuple：語法上會採納
一些奇怪的用法。空的 tuple 藉由一對空括號來創建；含有一個項目的 tuple 經
由一個值加上一個逗點來創建（用括號把一個單一的值包住是不夠的）。醜，但有
效率。例如：

     >>> empty = ()
     >>> singleton = 'hello',    # <-- note trailing comma
     >>> len(empty)
     0
     >>> len(singleton)
     1
     >>> singleton
     ('hello',)

陳述式 ‘t = 12345, 54321, 'hello!'’ 就是一個 `tuple packing' 的例子：
‘12345’，‘54321’ 和 ‘'hello!'’ 一起被放進 tuple 裡。反向操作也可以：

     >>> x, y, z = t

這個正是我們所說序列拆解 (`sequence unpacking')，可運用在任何位在等號右
邊的序列。序列拆解要求等號左邊的變數數量必須與等號右邊的序列中的元素數量
相同。注意，多重指派就只是 tuple packing 和序列拆解的結合而已。


File: python.info,  Node: 集合 Sets,  Next: 字典（Dictionary）,  Prev: Tuples 和序列 Sequences,  Up: 資料結構

2.5.4 集合 (Sets)
-----------------

Python 也包含了一種用在 `set'（集合）的資料類型。一個 set 是一組無序且沒
有重複的元素。基本的使用方式包括了成員測試和消除重複元素。 Set 物件也支
援聯集、交集、差集和互斥等數學運算。

大括號或 *note set(): 1f6. 函式都可以用來創建 set。注意：要創建一個空的
set，你必須使用 ‘set()’ 而不是 ‘{}’；後者會創建一個空的 dictionary，一種
我們將在下一節討論的資料結構。

這裡是一個簡單的演示：

     >>> 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'}

和 *note list comprehensions: 139e. 類似，也有 set comprehensions（集合
綜合運算）：

     >>> a = {x for x in 'abracadabra' if x not in 'abc'}
     >>> a
     {'r', 'd'}


File: python.info,  Node: 字典（Dictionary）,  Next: 迴圈技巧,  Prev: 集合 Sets,  Up: 資料結構

2.5.5 字典（Dictionary）
------------------------

下一個常用的 Python 內建資料類型為 `dictionary'（請參考*note 映射类型 —
dict: 40e.）。 Dictionary 有時被稱為「關聯記憶體」(associative memories)
或「關聯陣列」(associative arrays)。不像序列是由一個範圍內的數字當作索引
，dictionary 是由`鍵' (key) 來當索引，鍵可以是任何不可變的類型；字串和數
字都可以當作鍵。Tuple 也可以當作鍵，如果他們只含有字串、數字或 tuple；若
一個 tuple 直接或間接地含有任何可變的物件，它就不能當作鍵。你無法使用
list 當作鍵，因為 list 可以經由索引指派 (index assignment)、切片指派
(slice assignment) 或是像 ‘append()’ 和 ‘extend()’ 等 method 被修改。

思考 dictionary 最好的方式是把它想成是一組`鍵值'對 (`key: value' pair) 的
set，其中鍵在同一個 dictionary 裡必須是獨一無二的。使用一對大括號可創建
一個空的 dictionary：‘{}’。將一串由逗號分隔的鍵值對置於大括號則可初始化
字典的鍵值對。這同樣也是字典輸出時的格式。

Dictionary 主要的操作為藉由鍵來儲存一個值並且可藉由該鍵來取出該值。也可
以使用 ‘del’ 來刪除鍵值對。如果我們使用用過的鍵來儲存，該鍵所對應的較舊
的值會被覆蓋。使用不存在的鍵來取出值會造成錯誤。

對 dictionary 使用 ‘list(d)’ 會得到一個包含該字典所有鍵的 list，其排列順
序為插入時的順序。（若想要排序，則使用 ‘sorted(d)’ 代替即可）。如果想確
認一個鍵是否已存在於字典中，可使用關鍵字 *note in: 179.。

這是個使用一個 dictionary 的簡單範例：

     >>> 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

函式 *note dict(): 164. 可直接透過一串鍵值對序列來創建 dictionary：

     >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
     {'sape': 4139, 'guido': 4127, 'jack': 4098}

此外，dict comprehensions 也可以透過任意鍵與值的運算式來創建 dictionary
：

     >>> {x: x**2 for x in (2, 4, 6)}
     {2: 4, 4: 16, 6: 36}

當鍵是簡單的字串時，使用關鍵字引數 (keyword arguments) 有時會較為簡潔：

     >>> dict(sape=4139, guido=4127, jack=4098)
     {'sape': 4139, 'guido': 4127, 'jack': 4098}


File: python.info,  Node: 迴圈技巧,  Next: 深入了解條件 Condition,  Prev: 字典（Dictionary）,  Up: 資料結構

2.5.6 迴圈技巧
--------------

當對 dictionary 作迴圈時，鍵以及其對應的值可以藉由使用 ‘items()’ method
來同時取得：

     >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
     >>> for k, v in knights.items():
     ...     print(k, v)
     ...
     gallahad the pure
     robin the brave

當對序列作迴圈時，位置索引及其對應的值可以藉由使用 *note enumerate():
ea7. 函式來同時取得：

     >>> for i, v in enumerate(['tic', 'tac', 'toe']):
     ...     print(i, v)
     ...
     0 tic
     1 tac
     2 toe

要同時對兩個以上的序列作迴圈，可以將其以成對的方式放入 *note zip(): cfc.
函式：

     >>> 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.

要對序列作反向的迴圈，首先先寫出正向的序列，再對其使用 *note reversed():
2c6. 函式：

     >>> for i in reversed(range(1, 10, 2)):
     ...     print(i)
     ...
     9
     7
     5
     3
     1

要以迴圈對序列作排序，使用 *note sorted(): 546. 函式會得到一個新的經排序
過的 list ，但不會改變原本的序列：

     >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
     >>> for i in sorted(basket):
     ...     print(i)
     ...
     apple
     apple
     banana
     orange
     orange
     pear

對序列使用 *note set(): 1f6. 可去除重複元素。對序列使用 *note sorted():
546. 加上 *note set(): 1f6.，則是對經過排序後的非重複元素跑迴圈的慣用方
法：

     >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
     >>> for f in sorted(set(basket)):
     ...     print(f)
     ...
     apple
     banana
     orange
     pear

有時我們會想要以迴圈來改變的一個 list，但是，通常創建一個新的 list 會更
簡單且安全：

     >>> 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]


File: python.info,  Node: 深入了解條件 Condition,  Next: 序列和其他資料類型之比較,  Prev: 迴圈技巧,  Up: 資料結構

2.5.7 深入了解條件 (Condition)
------------------------------

使用在 ‘while’ 和 ‘if’ 陳述式的條件句可以包含任何運算子，而不是只有比較
運算子 (comparisons) 。

比較運算子 ‘in’ 和 ‘not in’ 檢查一個值是否存在（不存在）於一個序列中。運
算子 ‘is’ 和 ‘not is’ 比較兩個物件是否真的是相同的物件。所有比較運算子的
優先度都相同且都低於數值運算子。

比較運算是可以串連在一起的。例如， ‘a < b == c’ 就是在測試 ‘a’ 是否小於
‘b’ 和 ‘b’ 是否等於 ‘c’。

比較運算可以結合布林運算子 ‘and’ 和 ‘or’，且一個比較運算的結果（或任何其
他布林運算式）可以加上 ‘not’ 來否定。這些運算子的優先度都比比較運算子還
低，其中，‘not’ 的優先度最高，‘or’ 的優先度最低，因此 ‘A and not B or C’
等同於 ‘(A and (not B)) or C’。一如往常，括號可以用來表示任何想要的組合
。

布林運算子 ‘and’ 和 ‘or’ 也被稱為`短路 (short-circuit)' 運算子：會將其引
數從左至右進行運算，當結果出現時即結束運算。例如，若 ‘A’ 和 ‘C’ 為真但
‘B’ 為假，則 ‘A and B and C’ 的運算並不會執行到 ‘C’。當運算結果被當成一
般值而非布林值時，短路運算子的回傳值為最後被求值的引數。

將一個比較運算或其他布林運算式的結果指派給一個變數是可以的。例如：

     >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
     >>> non_null = string1 or string2 or string3
     >>> non_null
     'Trondheim'

注意，Python 與 C 語言不一樣，在運算式裡進行指派必須外顯地使用*note
海象運算子: 13ac. ‘:=’。 這樣做避免了在 C 語言裡常見的一種問題：想要打
‘==’ 卻在運算式裡輸入 ‘=’。


File: python.info,  Node: 序列和其他資料類型之比較,  Prev: 深入了解條件 Condition,  Up: 資料結構

2.5.8 序列和其他資料類型之比較
------------------------------

序列物件通常可以拿來和其他相同類型的物件做比較。這種比較使用`詞典式
(lexicographical)' 順序：首先比較各自最前面的那項，若不相同，便可決定結
果；若相同，則比較下一項，以此類推，直到其中一個序列完全用完。如果被拿出
來比較的兩項本身又是相同的序列類型，則詞典式比較會遞迴地執行。如果兩個序
列所有的項目都相等，則此兩個序列被認為是相等的。如果其中一個序列是另一個
的子序列，則較短的那個序列為較小的序列。字串的詞典式順序使用 Unicode 的
碼位 (code point) 編號來排序個別字元。以下是一些相同序列類型的比較：

     (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)

注意，若使用 ‘<’ 或 ‘>’ 來比較不同類型的物件是合法的，表示物件擁有適當的
比較方法。例如，混合的數值類型是根據它們數值來做比較，所以 0 等於 0.0，
等等。否則直譯器會選擇丟出一個 *note TypeError: 1fe. 錯誤而不是提供一個
任意的排序。

註解
....


File: python.info,  Node: 模組 Module,  Next: 輸入和輸出,  Prev: 資料結構,  Up: Python 教學

2.6 模組 (Module)
=================

如果從 Python 直譯器離開後又再次進入，之前（幫函式或變數）做的定義都會消
失。因此，想要寫一些比較長的程式時，你最好使用編輯器來準備要輸入給直譯器
的內容，並且用該檔案來運行它。這就是一個`腳本 (script)'。隨著你的程式越
變越長，你可能會想要把它分開成幾個檔案，讓它比較好維護。你可能也會想用一
個你之前已經在其他程式寫好的函式，但不想要複製該函式的原始定義到所有使用
它的程式裡。

為了支援這一點，Python 有一種方法可以將定義放入檔案中，並在互動模式下的
直譯器中使用它們。這種檔案稱為`模組 (module)'；模組中的定義可以被
`import' 到其他模組中，或是被 `import' 至`主 (main)' 模組（在最頂層執行
的腳本，以及互動模式下，所使用的變數集合）。

模組是指包含 Python 定義和語句的檔案，檔案名稱是模組名稱加上 ‘.py’。在模
組中，模組的名稱（作為字串）會是全域變數 ‘__name__’ 的值。例如，用您喜歡
的文字編輯器在資料夾中創一個名為 ‘fibo.py’ 的檔案，內容如下：

     # 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

現在進入 Python 直譯器並用以下指令 import 這個模組：

     >>> import fibo

這並不會將 ‘fibo’ 中定義的函式名稱直接輸入當前的符號表中；它只會輸入
‘fibo’ 的模組名稱。使用此模組名稱，就可以存取函式：

     >>> 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'

如果您打算經常使用其中某個函式，可以將其指定至區域變數：

     >>> fib = fibo.fib
     >>> fib(500)
     0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

* Menu:

* 深入了解模組::
* 標準模組::
* dir() 函式: dir 函式.
* 套件 (Package): 套件 Package.


File: python.info,  Node: 深入了解模組,  Next: 標準模組,  Up: 模組 Module

2.6.1 深入了解模組
------------------

模組可以包含可執行的陳述式以及函式的定義。這些陳述式是作為模組的初始化，
它們只會在`第一次'被 import 時才會執行。(1)（如果檔案被當成腳本執行，也
會執行它們）。

每個模組都有它自己的私有符號表，模組內定義的函式會把該模組的私有符號表當
成全域符號表使用。因此，模組的作者可以在模組中使用全域變數，而不必擔心和
使用者的全域變數發生意外的名稱衝突。另一方面，如果你知道自己在做什麼，你
可以用這個方式取用模組的全域變數，以和引用函式一樣的寫法，
‘modname.itemname’。

在一個模組中可以 import 其他模組。把所有的 *note import: ce7. 陳述式放在
模組（就這邊來說，腳本也是一樣）的最開頭是個慣例，但並沒有強制。被
import 的模組名稱放置在原模組的全域符號表中。

*note import: ce7. 陳述式有另一種變形寫法，可以直接將名稱從欲 import 的
模組，直接 import 至原模組的符號表中。例如：

     >>> from fibo import fib, fib2
     >>> fib(500)
     0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

在 import 之後的名稱會被導入，但定義該函式的整個模組名稱並不會被引入在區
域符號表中（因此，示例中的 ‘fibo’ 未被定義）。

甚至還有另一種變形寫法，可以 import 模組定義的所有名稱：

     >>> from fibo import *
     >>> fib(500)
     0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

這個寫法會 import 模組中所有的名稱，除了使用底線（‘_’）開頭的名稱。大多
數情況下，Python 程式設計師不大使用這個功能，因為它在直譯器中引入了一組
未知的名稱，並且可能覆蓋了某些您已經定義的內容。

請注意，一般情況下並不建議從模組或套件中 import ‘*’ 的做法，因為它通常會
導致可讀性較差的程式碼。但若是使用它來在互動模式中節省打字時間，則是可以
接受的。

如果模組名稱後面出現 ‘as’，則 ‘as’ 之後的名稱將直接和被 import 模組綁定
在一起。

     >>> import fibo as fib
     >>> fib.fib(500)
     0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

這個 import 方式和 ‘import fibo’ 實質上是一樣的，唯一的差別是現在要用
‘fib’ 使用模組。

在使用 *note from: d0d. 時也可以用同樣的方式獲得類似的效果：

     >>> from fibo import fib as fibonacci
     >>> fibonacci(500)
     0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

     備註: 出於效率原因，每個模組在每個直譯器 session 中僅會被 import 一
     次。因此，如果您更改了模組，則必須重啟直譯器——或者，如果只是一個想
     要在互動模式下測試的模組，可以使用 *note importlib.reload(): 49f.。
     例如：‘import importlib; importlib.reload(modulename)’。

* Menu:

* 把模組當作腳本執行::
* 模組的搜尋路徑::
* 「編譯」Python 檔案::

   ---------- Footnotes ----------

   (1) (1) 實際上，函式定義也是「被執行」的「陳述式」；在執行模組階層的
函式定義時，會輸入函式名稱到模組的全域符號表。


File: python.info,  Node: 把模組當作腳本執行,  Next: 模組的搜尋路徑,  Up: 深入了解模組

2.6.1.1 把模組當作腳本執行
..........................

當使用以下內容運行 Python 模組時：

     python fibo.py <arguments>

如同使用 import 指令，模組中的程式碼會被執行，但 ‘__name__’ 被設為
‘"__main__"’。這意味著，透過在模組的末尾添加以下程式碼：

     if __name__ == "__main__":
         import sys
         fib(int(sys.argv[1]))

你可以將檔案作為腳本也同時可以作為被 import 的模組，因為解析 (parse) 命
令列的程式碼只會在當模組是「主」檔案時，才會執行：

     $ python fibo.py 50
     0 1 1 2 3 5 8 13 21 34

如果此模組是被 import 的，則該段程式碼不會被執行：

     >>> import fibo
     >>>

這通常是用來為模組提供方便的使用者介面，或者用於測試目的（執行測試套件時
，以腳本的方式執行模組）。


File: python.info,  Node: 模組的搜尋路徑,  Next: 「編譯」Python 檔案,  Prev: 把模組當作腳本執行,  Up: 深入了解模組

2.6.1.2 模組的搜尋路徑
......................

Import 一個名為 ‘spam’ 的模組時，直譯器首先會搜尋具有該名稱的內建模組。
如果找不到，接下來會在變數 *note sys.path: 261. 所給定的資料夾清單之中，
搜尋一個名為 ‘spam.py’ 的檔案。*note sys.path: 261. 從這些位置開始進行初
始化：

   * 輸入腳本所位在的資料夾（如未指定檔案時，則是當前資料夾）。

   * *note PYTHONPATH: a34.（一連串和 shell 變數 ‘PATH’ 的語法相同的資料
     夾名稱）。

   * 與安裝相關的預設值（按慣例會包含一個 ‘site-packages’ 資料夾，它是由
     *note site: eb. 模組所處理）。

     備註: 在支援符號連結 (symlink) 的檔案系統中，輸入腳本的所在資料夾是
     在跟隨符號連結之後才被計算的。換言之，包含符號連結的資料夾`並沒有
     '增加到模組的搜尋路徑中。

初始化之後，Python 程式可以修改 *note sys.path: 261.。執行中腳本的所在資
料夾會在搜尋路徑的開頭，在標準函式庫路徑之前。這代表該資料夾中的腳本會優
先被載入，而不是函式庫資料夾中相同名稱的模組。除非是有意要做這樣的替換，
否則這是一個錯誤。 請參見*note 標準模組: 13b8.以瞭解更多資訊。


File: python.info,  Node: 「編譯」Python 檔案,  Prev: 模組的搜尋路徑,  Up: 深入了解模組

2.6.1.3 「編譯」Python 檔案
...........................

為了加快載入模組的速度，Python 將每個模組的編譯版本暫存在 ‘__pycache__’
資料夾下，並命名為 ‘module.`version'.pyc’， 這裡的 version 是編譯後的檔
案的格式名稱，且名稱通常會包含 Python 的版本編號。例如，在 CPython 3.3 中
，spam.py 的編譯版本將被暫存為 ‘__pycache__/spam.cpython-33.pyc’。此命名
準則可以讓來自不同版本的編譯模組和 Python 的不同版本同時共存。

Python 根據原始碼最後修改的日期，檢查編譯版本是否過期而需要重新編譯。這
是一個完全自動的過程。另外，編譯後的模組獨立於平台，因此不同架構的作業系
統之間可以共用同一函式庫。

Python 在兩種情況下不檢查快取 (cache)。首先，它總是重新編譯且不儲存直接
從命令列載入的模組的結果。第二，如果沒有源模組，則不會檢查快取。要支援非
源模組（僅編譯）的發布，編譯後的模組必須位於原始資料夾中，並且不能有源模
組。

一些給專家的秘訣：

   * 可以在 Python 指令上使用開關參數 (switch) *note -O: 77e. 或 *note
     -OO: 77f. 來減小已編譯模組的大小。開關參數 ‘-O’ 刪除 assert（斷言）
     陳述式，而 ‘-OO’ 同時刪除 assert 陳述式和 __doc__ 字串。由於有些程
     式可能依賴於上述這些內容，因此只有在您知道自己在做什麼時，才應使用
     此參數。「已優化」模組有 ‘opt-’ 標記，且通常較小。未來的版本可能會
     改變優化的效果。

   * 讀取 ‘.pyc’ 檔案時，程式的執行速度並不會比讀取 ‘.py’ 檔案快。唯一比
     較快的地方是載入的速度。

   * 模組 *note compileall: 20. 可以為資料夾中的所有模組創建 .pyc 檔。

   * 更多的細節，包括決策流程圖，請參考 PEP 3147(1)。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3147


File: python.info,  Node: 標準模組,  Next: dir 函式,  Prev: 深入了解模組,  Up: 模組 Module

2.6.2 標準模組
--------------

Python 附帶了一個標準模組庫，詳細的介紹在另一份文件，稱為「Python 函式庫
參考手冊」（簡稱為「函式庫參考手冊」）。有些模組是直譯器中內建的；它們使
一些不屬於語言核心但依然內建的運算得以存取，其目的是為了提高效率，或提供
作業系統基本操作（例如系統呼叫）。這些模組的集合是一個組態選項，它們取決
於底層平台。例如：*note winreg: 133. 模組僅供 Windows 使用。值得注意的模
組是 *note sys: fd.，它被內建在每個 Python 直譯器中。變數 ‘sys.ps1’ 和
‘sys.ps2’ 則用來定義主、次提示字元的字串：

     >>> import sys
     >>> sys.ps1
     '>>> '
     >>> sys.ps2
     '... '
     >>> sys.ps1 = 'C> '
     C> print('Yuck!')
     Yuck!
     C>

只有直譯器在互動模式時，才需要定義這兩個變數。

變數 ‘sys.path’ 是一個字串 list，它決定直譯器的模組搜尋路徑。它的初始值
為環境變數 *note PYTHONPATH: a34. 中提取的預設路徑，或是當 *note
PYTHONPATH: a34. 未設定時，從內建預設值提取。你可以用標準的 list 操作修
改該變數：

     >>> import sys
     >>> sys.path.append('/ufs/guido/lib/python')


File: python.info,  Node: dir 函式,  Next: 套件 Package,  Prev: 標準模組,  Up: 模組 Module

2.6.3 ‘dir()’ 函式
------------------

內建函式 *note dir(): df9. 用於找出模組定義的所有名稱。它回傳一個排序後
的字串 list：

     >>> 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']

沒有給引數時，*note dir(): df9. 列出目前已定義的名稱：

     >>> a = [1, 2, 3, 4, 5]
     >>> import fibo
     >>> fib = fibo.fib
     >>> dir()
     ['__builtins__', '__name__', 'a', 'fib', 'fibo', 'sys']

請注意，它列出所有類型的名稱：變數、模組、函式等。

*note dir(): df9. 不會列出內建函式和變數的名稱。如果你想要列出它們，它們
被定義在標準模組 *note builtins: 12. 內：

     >>> 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']


File: python.info,  Node: 套件 Package,  Prev: dir 函式,  Up: 模組 Module

2.6.4 套件 (Package)
--------------------

套件是一種使用「點分隔模組名稱」組織 Python 模組命名空間的方法。例如，模
組名稱 ‘A.B’ 表示套件 ‘A’ 中名為 ‘B’ 的子模組。正如模組使用時，不同模組
的作者不需擔心與其他模組的全域變數名稱重複，點分隔模組名稱的使用，也讓多
模組套件（像 NumPy 或 Pillow）的作者們不須擔心其他套件的模組名稱。

假設你想設計一個能統一處理音訊檔案及音訊數據的模組集（「套件」）。因為音
訊檔案有很多的不同的格式（通常以它們的副檔名來辨識，例如：‘.wav’，
‘.aiff’，‘.au’），因此，為了不同檔案格式之間的轉換，你會需要建立和維護一
個不斷增長的模組集合。為了要達成對音訊數據的許多不同作業（例如，音訊混合
、增加回聲、套用等化器功能、創造人工立體音效），你將編寫一系列無止盡的模
組來執行這些作業。以下是你的套件可能的架構（以階層式檔案系統的方式表示）
：

     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
                   ...

Import 套件時，Python 會搜尋 ‘sys.path’ 裡的目錄，尋找套件的子目錄。

目錄中必須含有 ‘__init__.py’ 檔案，才會被 Pyhon 當成套件；這樣可以避免一
些以常用名稱命名（例如 ‘string’）的目錄，無意中隱藏了較晚出現在模組搜尋
路徑中的有效模組。在最簡單的情況，‘__init__.py’ 可以只是一個空白檔案；但
它也可以執行套件的初始化程式碼，或設置 ‘__all__’ 變數，之後會詳述。

套件使用者可以從套件中 import 個別模組，例如：

     import sound.effects.echo

這樣就載入了子模組 ‘sound.effects.echo’。引用時必須用它的全名：

     sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)

另一種 import 子模組的方法是：

     from sound.effects import echo

這段程式碼一樣可以載入子模組 ‘echo’，並且不加套件前綴也可以使用，因此能
以如下方式使用：

     echo.echofilter(input, output, delay=0.7, atten=4)

另一種變化是直接 import 所需的函式或變數：

     from sound.effects.echo import echofilter

同樣地，這樣也會載入子模組 ‘echo’，但它的函式 ‘echofilter()’ 就可以直接
使用：

     echofilter(input, output, delay=0.7, atten=4)

請注意，使用 ‘from package import item’ 時，item 可以是套件的子模組（或
子套件），也可以是套件中被定義的名稱，像是函式、class （類別）或變數。
‘import’ 陳述式首先測試套件中有沒有定義該 item；如果沒有，則會假設它是模
組，並嘗試載入。如果還是找不到 item，則會引發 *note ImportError: 16c. 例
外。

相反地，使用 ‘import item.subitem.subsubitem’ 語法時，除了最後一項之外，
每一項都必須是套件；最後一項可以是模組或套件，但不能是前一項中定義的
class、函式或變數。

* Menu:

* 從套件中 import *::
* 套件內引用::
* 多目錄中的套件::


File: python.info,  Node: 從套件中 import *,  Next: 套件內引用,  Up: 套件 Package

2.6.4.1 從套件中 import *
.........................

當使用者寫下 ‘from sound.effects import *’ 時，會發生什麼事？理想情況下
，我們可能希望程式碼會去檔案系統，尋找套件中存在的子模組，並將它們全部
import。這會花費較長的時間，且 import 子模組的過程可能會有不必要的副作用
，這些副作用只有在明確地 import 子模組時才會發生。

唯一的解法是由套件作者為套件提供明確的索引。*note import: ce7. 陳述式使
用以下慣例：如果套件的 ‘__init__.py’ 程式碼有定義一個名為 ‘__all__’ 的
list，若遇到 ‘from package import *’ 的時候，它就會是要被 import 的模組
名稱。發布套件的新版本時，套件作者可自行決定是否更新此 list。如果套件作
者認為沒有人會從他的套件中 import *，他也可能會決定不支援這個 list。舉例
來說，‘sound/effects/__init__.py’ 檔案可包含以下程式碼：

     __all__ = ["echo", "surround", "reverse"]

意思是，‘from sound.effects import *’ 將會 import ‘sound’ 套件中，這三個
被提名的子模組。

如果 ‘__all__’ 沒有被定義，‘from sound.effects import *’ 陳述式`並不會
'把 ‘sound.effects’ 套件中所有子模組都 import 到當前的命名空間；它只保證
‘sound.effects’ 套件有被 import（可能會運行 ‘__init__.py’ 中的初始化程式
碼），然後 import 套件中被定義的全部名稱。這包含 ‘__init__.py’ 定義（以
及被明確載入的子模組）的任何名稱。它也包括任何之前被 *note import: ce7.
陳述式明確載入的套件子模組。請看以下程式碼：

     import sound.effects.echo
     import sound.effects.surround
     from sound.effects import *

此例中，當 ‘from...import’ 陳述式被執行時，‘echo’ 和 ‘surround’ 模組被
import 進當前的命名空間，因為它們是在 ‘sound.effects’ 套件裡定義的。（當
‘__all__’ 有被定義時，這規則也有效。）

雖然，有些特定模組的設計，讓你使用 ‘import *’ 時，該模組只會輸出遵循特定
樣式的名稱，但在正式環境 (production) 的程式碼中這仍然被視為是不良習慣。

記住，使用 ‘from package import specific_submodule’ 不會有任何問題！實際
上，這是推薦用法，除非 import 的模組需要用到的子模組和其他套件的子模組同
名。


File: python.info,  Node: 套件內引用,  Next: 多目錄中的套件,  Prev: 從套件中 import *,  Up: 套件 Package

2.6.4.2 套件內引用
..................

當套件的結構為多個子套件的組合時（如同範例中的 ‘sound’ 套件），可以使用
「絕對 (absolute) import」，引用同層套件中的子模組。例如，要在
‘sound.filters.vocoder’ 模組中使用 ‘sound.effects’ 中的 ‘echo’ 模組時，
可以用 ‘from sound.effects import echo’。

你也可以用 ‘from module import name’ 的 import 陳述式，編寫「相對
(relative) import」。這些 import 使用前導句號指示相對 import 中的當前套
件和母套件。例如，在 ‘surround’ 模組中，你可以使用：

     from . import echo
     from .. import formats
     from ..filters import equalizer

請注意，相對 import 的運作是以目前的模組名稱為依據。因為主模組的名稱永遠
是 ‘"__main__"’，所以如果一個模組預期被用作 Python 應用程式的主模組，那
它必須永遠使用絕對 import。


File: python.info,  Node: 多目錄中的套件,  Prev: 套件內引用,  Up: 套件 Package

2.6.4.3 多目錄中的套件
......................

套件也支援一個特殊屬性 *note __path__: 13c3.。它在初始化時是一個 list，
包含該套件的 ‘__init__.py’ 檔案所在的目錄名稱，初始化時機是在這個檔案的
程式碼被執行之前。這個變數可以被修改，但這樣做會影響將來對套件內的模組和
子套件的搜尋。

雖然這個特色不太常被需要，但它可用於擴充套件中的模組集合。

註解
....


File: python.info,  Node: 輸入和輸出,  Next: 錯誤和例外,  Prev: 模組 Module,  Up: Python 教學

2.7 輸入和輸出
==============

有數種方式可以顯示程式的輸出；資料可以以人類易讀的形式印出，或是寫入檔案
以供未來所使用。這章節會討論幾種不同的方式。

* Menu:

* 更華麗的輸出格式::
* 讀寫檔案::


File: python.info,  Node: 更華麗的輸出格式,  Next: 讀寫檔案,  Up: 輸入和輸出

2.7.1 更華麗的輸出格式
----------------------

目前為止我們已經學過兩種寫值的方式：`運算式陳述 (expression statements)'
與 *note print(): 971. 函式。（第三種方法是使用檔案物件的 ‘write()’ 方法
；標準輸出的檔案是使用 ‘sys.stdout’ 來達成的。詳細的資訊請參考對應的函式
庫說明。）

通常你會想要對輸出格式有更多地控制，而不是僅列印出以空格隔開的值。以下是
幾種格式化輸出的方式。

   * 要使用*note 格式化字串文本 (formatted string literals): 13c9.，需在
     字串開始前的引號或連續三個引號前加上 ‘f’ 或 ‘F’。你可以在這個字串中
     使用 ‘{’ 與 ‘}’ 包夾 Python 的運算式，引用變數或其他字面值 (literal
     values)。

          >>> year = 2016
          >>> event = 'Referendum'
          >>> f'Results of the {year} {event}'
          'Results of the 2016 Referendum'

   * 字串的 *note str.format(): 5d4. method 需要更多手動操作。你還是可以
     用 ‘{’ 和 ‘}’ 標示欲替代變數的位置，且可給予詳細的格式指令，但你也
     需提供要被格式化的資訊。

          >>> 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%'

   * 最後，你還可以自己用字串切片 (slicing) 和串接 (concatenation) 操作
     ，完成所有的字串處理，建立任何你能想像的排版格式。字串型別有一些
     method，能以給定的欄寬填補字串，這些運算也很有用。

如果你不需要華麗的輸出，只想快速顯示變數以進行除錯，可以用 *note repr():
8b9. 或 *note str(): 205. 函式把任何的值轉換為字串。

*note str(): 205. 函式的用意是回傳一個人類易讀的表示法，而 *note repr():
8b9. 的用意是產生直譯器可讀取的表示法（如果沒有等效的語法，則造成 *note
SyntaxError: 559.）。如果物件沒有人類易讀的特定表示法，*note str(): 205.
會回傳與 *note repr(): 8b9. 相同的值。有許多的值，像是數字，或 list 及
dictionary 等結構，使用這兩個函式會有相同的表示法。而字串，則較為特別，
有兩種不同的表示法。

一些範例：

     >>> 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'))"

*note string: f6. 模組包含一個 *note Template: 4f0. class（類別），提供
了將值替代為字串的另一種方法。該方法使用 ‘$x’ 佔位符號，並以 dictionary
的值進行取代，但對格式的控制明顯較少。

* Menu:

* 格式化的字串文本 (Formatted String Literals): 格式化的字串文本 Formatted String Literals.
* 字串的 format() method: 字串的 format method.
* 手動格式化字串::
* 格式化字串的舊方法::


File: python.info,  Node: 格式化的字串文本 Formatted String Literals,  Next: 字串的 format method,  Up: 更華麗的輸出格式

2.7.1.1 格式化的字串文本 (Formatted String Literals)
....................................................

*note 格式化的字串文本: 296.（簡稱為 f-字串），透過在字串加入前綴 ‘f’ 或
‘F’，並將運算式編寫為 ‘{expression}’，讓你可以在字串內加入 Python 運算式
的值。

格式說明符 (format specifier) 是選擇性的，寫在運算式後面，可以更好地控制
值的格式化方式。以下範例將 pi 捨入到小數點後三位：

     >>> import math
     >>> print(f'The value of pi is approximately {math.pi:.3f}.')
     The value of pi is approximately 3.142.

在 ‘':'’ 後傳遞一個整數，可以設定該欄位至少為幾個字元寬，常用於將每一欄
對齊。

     >>> 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

還有一些修飾符號可以在格式化前先將值轉換過。‘'!a'’ 會套用 *note ascii():
e11.，‘'!s'’ 會套用 *note str(): 205.，‘'!r'’ 會套用 *note repr(): 8b9.：

     >>> 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'.

若要參考這些格式化字串的規格，詳見 *note 格式规格迷你语言: 5d8. 參考指南
。


File: python.info,  Node: 字串的 format method,  Next: 手動格式化字串,  Prev: 格式化的字串文本 Formatted String Literals,  Up: 更華麗的輸出格式

2.7.1.2 字串的 format() method
..............................

*note str.format(): 5d4. method 的基本用法如下：

     >>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))
     We are the knights who say "Ni!"

大括號及其內的字元（稱為格式欄位）會被取代為傳遞給 *note str.format():
5d4. method 的物件。大括號中的數字表示該物件在傳遞給 *note str.format():
5d4. method 時所在的位置。

     >>> print('{0} and {1}'.format('spam', 'eggs'))
     spam and eggs
     >>> print('{1} and {0}'.format('spam', 'eggs'))
     eggs and spam

如果在 *note str.format(): 5d4. method 中使用關鍵字引數，可以使用引數名
稱去引用它們的值。

     >>> print('This {food} is {adjective}.'.format(
     ...       food='spam', adjective='absolutely horrible'))
     This spam is absolutely horrible.

位置引數和關鍵字引數可以任意組合：

     >>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',
                                                            other='Georg'))
     The story of Bill, Manfred, and Georg.

如果你有一個不想分割的長格式化字串，比較好的方式是按名稱而不是按位置來引
用變數。這項操作可以透過傳遞字典 (dict)，並用方括號 ‘'[]'’ 使用鍵 (key)
來輕鬆完成。

     >>> 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

用 ’**’ 符號，把 table 當作關鍵字引數來傳遞，也有一樣的結果。

     >>> 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

與內建函式 *note vars(): 116d. 組合使用時，這種方式特別實用。該函式可以
回傳一個包含所有區域變數的 dictionary。

例如，下面的程式碼產生一組排列整齊的欄，列出整數及其平方與立方：

     >>> 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

關於使用 *note str.format(): 5d4. 進行字串格式化的完整概述，請見*note
格式字符串语法: de0.。


File: python.info,  Node: 手動格式化字串,  Next: 格式化字串的舊方法,  Prev: 字串的 format method,  Up: 更華麗的輸出格式

2.7.1.3 手動格式化字串
......................

下面是以手動格式化完成的同一個平方及立方的表：

     >>> 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

（請注意，使用 *note print(): 971. 讓每欄之間加入一個空格的方法：這種方
法總是在其引數間加入空格。）

字串物件的 *note str.rjust(): 13ce. method 透過在左側填補空格，使字串以
給定的欄寬進行靠右對齊。類似的 method 還有 *note str.ljust(): 13cf. 和
*note str.center(): 13d0.。這些 method 不寫入任何內容，只回傳一個新字串
，如果輸入的字串太長，它們不會截斷字串，而是不做任何改變地回傳；雖然這樣
會弄亂欄的編排，但這通常還是比另一種情況好，那種情況會讓值變得不正確。（
如果你真的想截斷字串，可以加入像 ‘x.ljust(n)[:n]’ 這樣的切片運算。）

另一種 method 是 *note str.zfill(): 13d1.，可在數值字串的左邊填補零，且
能識別正負號：

     >>> '12'.zfill(5)
     '00012'
     >>> '-3.14'.zfill(7)
     '-003.14'
     >>> '3.14159265359'.zfill(5)
     '3.14159265359'


File: python.info,  Node: 格式化字串的舊方法,  Prev: 手動格式化字串,  Up: 更華麗的輸出格式

2.7.1.4 格式化字串的舊方法
..........................

% 運算子（modulo，模數）也可用於字串格式化。在 ‘'string' % values’ 中，
‘string’ 中所有的 ‘%’ 會被 ‘values’ 的零個或多個元素所取代。此運算常被稱
為字串插值 (string interpolation)。例如：

     >>> import math
     >>> print('The value of pi is approximately %5.3f.' % math.pi)
     The value of pi is approximately 3.142.

更多資訊請見 *note printf 风格的字符串格式化: 1359.小節。


File: python.info,  Node: 讀寫檔案,  Prev: 更華麗的輸出格式,  Up: 輸入和輸出

2.7.2 讀寫檔案
--------------

*note open(): 16f. 回傳一個 *note file object: c14.，而它最常使用的兩個
引數是：‘open(filename, mode)’。

     >>> f = open('workfile', 'w')

第一個引數是一個包含檔案名稱的字串。第二個引數是另一個字串，包含了描述檔
案使用方式的幾個字元。`mode' 為 ‘'r'’ 時，表示以唯讀模式開啟檔案；為
‘'w'’ 時，表示以唯寫模式開啟檔案（已存在的同名檔案會被抹除）；為 ‘'a'’ 時
，以附加內容為目的開啟檔案，任何寫入檔案的資料會自動被加入到檔案的結尾。
‘'r+'’ 可以開啟檔案並進行讀取和寫入。`mode' 引數是選擇性的，若省略時會預
設為 ‘'r'’。

通常，檔案以 `text mode' 開啟，意即，從檔案中讀取或寫入字串時，都以特定
編碼方式進行編碼。如未指定編碼方式，則預設值會取決於系統平台（見 *note
open(): 16f.）。在 mode 加上 ‘'b'’ 會以 `binary mode' 開啟檔案：此時，資
料以位元組串物件 (bytes object) 的形式被讀寫。此模式應該使用於所有不含文
字的檔案。

在文字模式 (text mode) 下，讀取時會預設把平台特定的行尾符號（Unix 上為
‘\n’，Windows 上為 ‘\r\n’）轉換為 ‘\n’。在文字模式下寫入時，預設會把
‘\n’ 出現之處轉換回平台特定的行尾符號。這種在幕後對檔案資料的修改方式對
文字檔案來說沒有問題，但會毀壞像是 ‘JPEG’ 或 ‘EXE’ 檔案中的二進制資料。
在讀寫此類檔案時，注意一定要使用二進制模式。

在處理檔案物件時，使用 *note with: 7da. 關鍵字是個好習慣。優點是，當它的
套件結束後，即使在某個時刻引發了例外，檔案仍會正確地被關閉。使用 ‘with’
也比寫等效的 *note try: e37.-*note finally: 2bc. 區塊，來得簡短許多：

     >>> with open('workfile') as f:
     ...     read_data = f.read()

     >>> # We can check that the file has been automatically closed.
     >>> f.closed
     True

如果你沒有使用 *note with: 7da. 關鍵字，則應呼叫 ‘f.close()’ 關閉檔案，
可以立即釋放被它所使用的系統資源。

     警告: 呼叫 ‘f.write()’ 時，若未使用 ‘with’ 關鍵字或呼叫
     ‘f.close()’，即使程式成功退出，也`可能'導致 ‘f.write()’ 的引數沒有
     被完全寫入硬碟。

不論是透過 *note with: 7da. 陳述式，或呼叫 ‘f.close()’ 關閉一個檔案物件
之後，嘗試使用該檔案物件將會自動失效。

     >>> f.close()
     >>> f.read()
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     ValueError: I/O operation on closed file.

* Menu:

* 檔案物件的 method::
* 使用 json 儲存結構化資料::


File: python.info,  Node: 檔案物件的 method,  Next: 使用 json 儲存結構化資料,  Up: 讀寫檔案

2.7.2.1 檔案物件的 method
.........................

本節其餘的範例皆假設一個名為 ‘f’ 的檔案物件已被建立。

要讀取檔案的內容，可呼叫 ‘f.read(size)’，它可讀取一部份的資料，並以字串
（文字模式）或位元組串物件（二進制模式）形式回傳。`size' 是個選擇性的數
字引數。當 `size' 被省略或為負數時，檔案的全部內容會被讀取並回傳；如果檔
案是機器記憶體容量的兩倍大時，這會是你的問題。否則，最多只有等同於
`size' 數量的字元（文字模式）或 `size' 數量的位元組串（二進制模式）會被
讀取及回傳。如果之前已經到達檔案的末端，‘f.read()’ 會回傳空字串（‘''’）
。

     >>> f.read()
     'This is the entire file.\n'
     >>> f.read()
     ''

‘f.readline()’ 從檔案中讀取單獨一行；換行字元（‘\n’）會被留在字串的結尾
，只有當檔案末端不是換行字元時，它才會在檔案的最後一行被省略。這種方式讓
回傳值清晰明確；只要 ‘f.readline()’ 回傳一個空字串，就表示已經到達了檔案
末端，而空白行的表示法是 ‘'\n'’，也就是只含一個換行字元的字串。

     >>> f.readline()
     'This is the first line of the file.\n'
     >>> f.readline()
     'Second line of the file\n'
     >>> f.readline()
     ''

想從檔案中讀取多行時，可以對檔案物件進行迴圈。這種方法能有效地使用記憶體
、快速，且程式碼簡潔：

     >>> for line in f:
     ...     print(line, end='')
     ...
     This is the first line of the file.
     Second line of the file

如果你想把一個檔案的所有行讀進一個 list 裡，可以用 ‘list(f)’ 或
‘f.readlines()’。

‘f.write(string)’ 把 `string' 的內容寫入檔案，並回傳寫入的字元數。

     >>> f.write('This is a test\n')
     15

寫入其他類型的物件之前，要先把它們轉換為字串（文字模式）或位元組串物件（
二進制模式）：

     >>> value = ('the answer', 42)
     >>> s = str(value)  # convert the tuple to string
     >>> f.write(s)
     18

‘f.tell()’ 回傳一個整數，它給出檔案物件在檔案中的當前位置，在二進制模式
下表示為檔案開始至今的位元組數，在文字模式下表示為一個意義不明的數字。

使用 ‘f.seek(offset, whence)’ 可以改變檔案物件的位置。位置計算方法是從一
個參考點增加 `offset' 的偏移量；參考點則由引數 `whence' 來選擇。當
`whence' 值為 0 時，表示使用檔案開頭，1 表示使用當前的檔案位置，2 表示使
用檔案末端作為參考點。`whence' 可省略，其預設值為 0，即以檔案開頭作為參
考點。

     >>> 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'

在文字檔案（開啟時模式字串未加入 ‘b’ 的檔案）中，只允許以檔案開頭為參考
點進行尋找（但 ‘seek(0, 2)’ 尋找檔案最末端是例外），且只有從 ‘f.tell()’
回傳的值，或是 0，才是有效的 `offset' 值。其他任何 `offset' 值都會產生未
定義的行為。

檔案物件還有一些附加的 method，像是較不常使用的 ‘isatty()’ 和
‘truncate()’；檔案物件的完整指南詳見程式庫參考手冊。


File: python.info,  Node: 使用 json 儲存結構化資料,  Prev: 檔案物件的 method,  Up: 讀寫檔案

2.7.2.2 使用 ‘json’ 儲存結構化資料
..................................

字串可以簡單地從檔案中被寫入和讀取。數字則稍嫌麻煩，因為 ‘read()’ method
只回傳字串，這些字串必須傳遞給像 *note int(): 204. 這樣的函式，它接受
‘'123'’ 這樣的字串，並回傳數值 123。當你想儲存像是巢狀 list 和
dictionary（字典）等複雜的資料類型時，手動剖析 (parsing) 和序列化
(serializing) 就變得複雜。

相較於讓使用者不斷地編寫和除錯程式碼才能把複雜的資料類型儲存到檔案，
Python 支援一個普及的資料交換格式，稱為 JSON (JavaScript Object
Notation)(1)。標準模組 *note json: a4. 可接收 Python 資料階層，並將它們
轉換為字串表示法；這個過程稱為 `serializing'（序列化）。從字串表示法中重
建資料則稱為 `deserializing'（反序列化）。在序列化和反序列化之間，表示物
件的字串可以被儲存在檔案或資料中，或通過網路連接發送到遠端的機器。

     備註: JSON 格式經常地使用於現代應用程式的資料交換。許多程序設計師早
     已對它耳熟能詳，使它成為提升互操作性 (interoperability) 的好選擇。

如果你有一個物件 ‘x’，只需一行簡單的程式碼即可檢視它的 JSON 字串表示法：

     >>> import json
     >>> x = [1, 'simple', 'list']
     >>> json.dumps(x)
     '[1, "simple", "list"]'

*note dumps(): 6fc. 函式有一個變體，稱為 *note dump(): 6fb.，它單純地將
物件序列化為 *note text file: 13d9.。因此，如果 ‘f’ 是一個為了寫入而開啟
的 *note text file: 13d9. 物件，我們可以這樣做：

     json.dump(x, f)

若 ‘f’ 是一個已開啟、可讀取的 *note text file: 13d9. 物件，要再次解碼物
件的話：

     x = json.load(f)

這種簡單的序列化技術可以處理 list 和 dictionary，但要在 JSON 中序列化任
意的 class（類別）實例，則需要一些額外的工作。*note json: a4. 模組的參考
資料包含對此的說明。

也參考
......

*note pickle: ca. - pickle 模組

與 *note JSON: 13d8. 不同，`pickle' 是一種允許對任意的複雜 Python 物件進
行序列化的協定。因此，它為 Python 所特有，不能用於與其他語言編寫的應用程
式溝通。在預設情況，它也是不安全的：如果資料是由手段高明的攻擊者精心設計
，將這段來自於不受信任來源的 pickle 資料反序列化，可以執行任意的程式碼。

   ---------- Footnotes ----------

   (1) http://json.org


File: python.info,  Node: 錯誤和例外,  Next: Class（類別）,  Prev: 輸入和輸出,  Up: Python 教學

2.8 錯誤和例外
==============

到目前為止還沒有提到錯誤訊息，但如果你嘗試運行範例，你可能會發現一些錯誤
訊息。常見的（至少）兩種不同的錯誤類別為：`語法錯誤 (syntax error)' 和
`例外 (exception)'。

* Menu:

* 語法錯誤 (Syntax Error): 語法錯誤 Syntax Error.
* 例外 (Exception): 例外 Exception.
* 處理例外::
* 引發例外::
* 例外鏈接 (Exception Chaining): 例外鏈接 Exception Chaining.
* 使用者自定的例外::
* 定義清理動作::
* 預定義的清理動作::


File: python.info,  Node: 語法錯誤 Syntax Error,  Next: 例外 Exception,  Up: 錯誤和例外

2.8.1 語法錯誤 (Syntax Error)
-----------------------------

語法錯誤又稱剖析錯誤 (parsing error)，它或許是學習 Python 的過程最常聽見
的抱怨：

     >>> while True print('Hello world')
       File "<stdin>", line 1
         while True print('Hello world')
                        ^
     SyntaxError: invalid syntax

剖析器 (parser) 會重複犯錯的那一行，並用一個小「箭頭」指向該行檢測到的第
一個錯誤點。錯誤是由箭頭`之前'的標記 (token) 導致的（或至少是在這裡檢測
到的）：此例中，錯誤是在 *note print(): 971. 函式中被檢測到，因為在它前
面少了一個冒號（‘':'’）。檔案名稱和行號會被印出來，所以如果訊息是來自腳
本時，就可以知道去哪裡找問題。


File: python.info,  Node: 例外 Exception,  Next: 處理例外,  Prev: 語法錯誤 Syntax Error,  Up: 錯誤和例外

2.8.2 例外 (Exception)
----------------------

即使一段陳述式或運算式使用了正確的語法，嘗試執行時仍可能導致錯誤。執行時
檢測到的錯誤稱為`例外'，例外不一定都很嚴重：你很快就能學會在 Python 程式
中如何處理它們。不過大多數的例外不會被程式處理，並且會顯示如下的錯誤訊息
：

     >>> 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

錯誤訊息的最後一行指示發生了什麼事。例外有不同的類型，而類型名稱會作為訊
息的一部份被印出。範例中的例外類型為：*note ZeroDivisionError: 1fa.、
*note NameError: e40. 和 *note TypeError: 1fe.。作為例外類型被印出的字串
，就是發生的內建例外 (built-in exception) 的名稱。所有的內建例外都是如此
運作，但對於使用者自定的例外則不一定需要遵守（雖然這是一個有用的慣例）。
標準例外名稱是內建的識別字 (identifier)，不是保留關鍵字 (reserved
keyword)。

此行其餘部分，根據例外的類型及導致例外的原因，說明例外的細節。

錯誤訊息的開頭，用堆疊回溯 (stack traceback) 的形式顯示發生例外的語境。
一般來說，它含有一個列出源程式碼行 (source line) 的堆疊回溯；但它不會顯
示從標準輸入中讀取的程式碼。

*note 內建的例外: f73.章節列出內建的例外及它們的意義。


File: python.info,  Node: 處理例外,  Next: 引發例外,  Prev: 例外 Exception,  Up: 錯誤和例外

2.8.3 處理例外
--------------

編寫程式處理選定的例外是可行的。以下範例會要求使用者輸入內容，直到有效的
整數被輸入為止，但它允許使用者中斷程式（使用 ‘Control-C’ 或作業系統支援
的指令）；請注意，由使用者產生的程式中斷會引發 *note KeyboardInterrupt:
2cc. 例外信號。

     >>> while True:
     ...     try:
     ...         x = int(input("Please enter a number: "))
     ...         break
     ...     except ValueError:
     ...         print("Oops!  That was no valid number.  Try again...")
     ...

*note try: e37. 陳述式運作方式如下。

   * 首先，執行 `try 子句'（*note try: e37. 和 *note except: c10. 關鍵字
     之間的陳述式）。

   * 如果沒有發生例外，則 `except 子句'會被跳過，*note try: e37. 陳述式
     執行完畢。

   * 如果執行 try 子句時發生了例外，則該子句中剩下的部分會被跳過。如果例
     外的類型與 *note except: c10. 關鍵字後面的例外名稱相符，則 except 子
     句被執行，然後，繼續執行 *note try: e37. 陳述式之後的程式碼。

   * 如果發生的例外未符合 except 子句中的例外名稱，則將其傳遞到外層的
     *note try: e37. 陳述式；如果仍無法找到處理者，則它是一個`未處理例外
     (unhandled exception)'，執行將停止，並顯示如上所示的訊息。

*note try: e37. 陳述式可以有不只一個 except 子句，為不同的例外指定處理者
，而最多只有一個處理者會被執行。處理者只處理對應的 try 子句中發生的例外
，而不會處理同一 ‘try’ 陳述式裡其他處理者內的例外。一個 except 子句可以
用一組括號內的 tuple 列舉多個例外，例如：

     ... except (RuntimeError, TypeError, NameError):
     ...     pass

一個在 *note except: c10. 子句中的 class（類別）和一個例外是可相容的，只
要它與例外是同一個 class 或是為其 base class（基底類別）；反之則無法成立
——列出 derived class （衍生類別）的 except 子句並不能與 base class 相容
。例如，以下程式碼會依序印出 B、C、D：

     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")

請注意，如果 except 子句的順序被反轉（把 ‘except B’ 放到第一個），則會印
出 B、B、B ­­——第一個符合的 except 子句會被觸發。

最後一個 except 子句可以省略例外名稱，以統一處理所有其他例外。但使用上要
極其小心，因為這種方式容易遮蔽真正的程式設計錯誤！它也可用於印出錯誤訊息
，然後重新引發例外（也讓呼叫者可以處理該例外）：

     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

*note try: e37. ...  *note except: c10. 陳述式有一個選擇性的 `else 子句
'，使用時，該子句必須放在所有 except 子句之後。如果一段程式碼必須被執行
，但 try 子句又沒有引發例外時，這個子句很有用。例如：

     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()

使用 ‘else’ 子句比向 *note try: e37. 子句添加額外的程式碼要好，因為這可
以避免意外地捕獲不是由 ‘try’ ...  ‘except’ 陳述式保護的程式碼所引發的例
外。

當例外發生時，它可能有一個相關的值，也就是例外的`引數'。此引數的存在與否
及它的類型，是取決於例外的類型。

‘except’ 子句可以在例外名稱後面指定一個變數。這個變數被綁定到一個例外實
例 (instance)，其引數儲存在 ‘instance.args’ 中。為了方便，例外實例會定義
*note __str__(): ef9.，因此引數可以直接被印出而無須引用 ‘.args’。你也可
以在引發例外前就先建立一個例外實例，並隨心所欲地為它加入任何屬性。

     >>> 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

如果一個例外有引數，則它們會被印在未處理例外的訊息的最後一部分（「細節」
）。

例外的處理者不僅處理 try 子句內立即發生的例外，還處理 try 子句內（即使是
間接地）呼叫的函式內部發生的例外。例如：

     >>> 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


File: python.info,  Node: 引發例外,  Next: 例外鏈接 Exception Chaining,  Prev: 處理例外,  Up: 錯誤和例外

2.8.4 引發例外
--------------

*note raise: d0a. 陳述式可讓程式設計師強制引發指定的例外。例如：

     >>> raise NameError('HiThere')
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     NameError: HiThere

*note raise: d0a. 唯一的引數就是要引發的例外。該引數必須是一個例外實例或
例外 class（衍生自 *note Exception: 2dc. 的 class）。如果一個例外 class
被傳遞，它會不含引數地呼叫它的建構函式 (constructor) ，使它被自動建立實
例 (implicitly instantiated)：

     raise ValueError  # shorthand for 'raise ValueError()'

如果你只想判斷是否引發了例外，但並不打算處理它，則可以使用簡單的 *note
raise: d0a. 陳述式來重新引發該例外：

     >>> 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


File: python.info,  Node: 例外鏈接 Exception Chaining,  Next: 使用者自定的例外,  Prev: 引發例外,  Up: 錯誤和例外

2.8.5 例外鏈接 (Exception Chaining)
-----------------------------------

*note raise: d0a. 陳述式容許一個選擇性的 *note from: d0a.，它透過被引發
例外中的 ‘__cause__’ 屬性的設定，來啟用例外鏈接。例如：

     # exc must be exception instance or None.
     raise RuntimeError from exc

要變換例外時，這種方式很有用。例如：

     >>> 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

當例外是在一個 *note except: c10. 或 *note finally: 2bc. 段落的內部被引
發時，例外鏈接會自動發生。要禁止例外鏈接，可以使用慣用語 ‘from None’：

     >>> try:
     ...     open('database.sqlite')
     ... except OSError:
     ...     raise RuntimeError from None
     ...
     Traceback (most recent call last):
       File "<stdin>", line 4, in <module>
     RuntimeError

更多關於鏈接機制的資訊，詳見*note 內建的例外: f73.。


File: python.info,  Node: 使用者自定的例外,  Next: 定義清理動作,  Prev: 例外鏈接 Exception Chaining,  Up: 錯誤和例外

2.8.6 使用者自定的例外
----------------------

程式可以通過建立新的例外 class 來命名自己的例外（深入了解 Python class，
詳見*note Class（類別）: 1379.）。不論是直接還是間接地，例外通常應該從
*note Exception: 2dc. class 衍生出來。

Exception classes can be defined which do anything any other class can
do, but are usually kept simple, often only offering a number of
attributes that allow information about the error to be extracted by
handlers for the exception.

大多數的例外定義，都會以「Error」作為名稱結尾，類似於標準例外的命名。

許多標準模組會定義它們自己的例外，以報告在其定義的函式中發生的錯誤。更多
有關 class 的資訊，詳見*note Class（類別）: 1379.章節。


File: python.info,  Node: 定義清理動作,  Next: 預定義的清理動作,  Prev: 使用者自定的例外,  Up: 錯誤和例外

2.8.7 定義清理動作
------------------

*note try: e37. 陳述式有另一個選擇性子句，用於定義在所有情況下都必須被執
行的清理動作。例如：

     >>> try:
     ...     raise KeyboardInterrupt
     ... finally:
     ...     print('Goodbye, world!')
     ...
     Goodbye, world!
     Traceback (most recent call last):
       File "<stdin>", line 2, in <module>
     KeyboardInterrupt

如果 *note finally: 2bc. 子句存在，則 ‘finally’ 子句會是 *note try: e37.
陳述式結束前執行的最後一項任務。不論 ‘try’ 陳述式是否產生例外，都會執行
‘finally’ 子句。以下幾點將探討例外發生時，比較複雜的情況：

   * 若一個例外發生於 ‘try’ 子句的執行過程，則該例外會被某個 *note
     except: c10. 子句處理。如果該例外沒有被 ‘except’ 子句處理，它會在
     ‘finally’ 子句執行後被重新引發。

   * 一個例外可能發生於 ‘except’ 或 ‘else’ 子句的執行過程。同樣地，該例
     外會在 ‘finally’ 子句執行後被重新引發。

   * 如果 ‘finally’ 子句執行 *note break: 3fa.、*note continue: 2bb. 或
     *note return: 2c8. 陳述式，則例外不會被重新引發。

   * 如果 ‘try’ 陳述式遇到 *note break: 3fa.、*note continue: 2bb. 或
     *note return: 2c8. 陳述式，則 ‘finally’ 子句會在執行 ‘break’、
     ‘continue’ 或 ‘return’ 陳述式之前先執行。

   * 如果 ‘finally’ 子句中包含 ‘return’ 陳述式，則回傳值會是來自
     ‘finally’ 子句的 ‘return’ 陳述式的回傳值，而不是來自 ‘try’ 子句的
     ‘return’ 陳述式的回傳值。

例如：

     >>> def bool_return():
     ...     try:
     ...         return True
     ...     finally:
     ...         return False
     ...
     >>> bool_return()
     False

另一個比較複雜的範例：

     >>> 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'

如你所見，*note finally: 2bc. 子句在任何情況下都會被執行。兩個字串相除所
引發的 *note TypeError: 1fe. 沒有被 *note except: c10. 子句處理，因此會
在 ‘finally’ 子句執行後被重新引發。

在真實應用程式中，*note finally: 2bc. 子句對於釋放外部資源（例如檔案或網
路連線）很有用，無論該資源的使用是否成功。


File: python.info,  Node: 預定義的清理動作,  Prev: 定義清理動作,  Up: 錯誤和例外

2.8.8 預定義的清理動作
----------------------

某些物件定義了在物件不再被需要時的標準清理動作，無論使用該物件的作業是成
功或失敗。請看以下範例，它嘗試開啟一個檔案，並印出檔案內容至螢幕。

     for line in open("myfile.txt"):
         print(line, end="")

這段程式碼的問題在於，執行完該程式碼後，它讓檔案在一段不確定的時間內處於
開啟狀態。在簡單腳本中這不是問題，但對於較大的應用程式來說可能會是個問題
。*note with: 7da. 陳述式讓物件（例如檔案）在被使用時，能保證它們總是及
時、正確地被清理。

     with open("myfile.txt") as f:
         for line in f:
             print(line, end="")

陳述式執行完畢後，就算是在處理內容時遇到問題，檔案 `f' 總是會被關閉。和
檔案一樣，提供預定義清理動作的物件會在說明文件中表明這一點。


File: python.info,  Node: Class（類別）,  Next: Python 標準函式庫概覽,  Prev: 錯誤和例外,  Up: Python 教學

2.9 Class（類別）
=================

Class 提供了一種結合資料與功能的手段。建立一個 class 將會新增一個物件的
`型別 (type)'，並且允許建立該型別的新`實例 (instance)'。每一個 class 實
例可以擁有一些維持該實例狀態的屬性 (attribute)。Class 實例也可以有一些（
由其 class 所定義的）method（方法），用於修改該實例的狀態。

與其他程式語言相比，Python 的 class 機制為 class 增加了最少的新語法跟語
意。他混合了 C++ 和 Modula-3 的 class 機制。Python 的 class 提供了所有物
件導向程式設計 (Object Oriented Programming) 的標準特色：class 繼承機制
允許多個 base class（基底類別），一個 derived class（衍生類別）可以覆寫
(override) 其 base class 的任何 method，且一個 method 可以用相同的名稱呼
叫其 base class 的 method。物件可以包含任意數量及任意種類的資料。如同模
組一樣，class 也具有 Python 的動態特性：他們在執行期 (runtime) 被建立，
且可以在建立之後被修改。

在 C++ 的術語中，class 成員（包含資料成員）通常都是`公開'的（除了以下內
容：*note 私有變數: 13ee.），而所有的成員函式都是`虛擬'的。如同在
Modula-3 中一樣，Python 並沒有提供簡寫可以從物件的 method 裡參照其成員：
method 函式與一個外顯的 (explicit)、第一個代表物件的引數被宣告，而此引數
是在呼叫時隱性地 (implicitly) 被提供。如同在 Smalltak 中，class 都是物件
，這為 import 及重新命名提供了語意。不像 C++ 和 Modula-3，Pyhon 內建的型
別可以被使用者以 base class 用於其他擴充 (extension)。另外，如同在 C++ 中
，大多數有著特別語法的內建運算子（算術運算子、下標等）都可以為了 class 實
例而被重新定義。

（由於缺乏普遍能接受的術語來討論 class，我偶爾會使用 Smalltalk 和 C++ 的
術語。我會使用 Modula-3 的術語，因為它比 C++ 更接近 Python 的物件導向語
意，但我預期比較少的讀者會聽過它。）

* Menu:

* 關於名稱與物件的一段話::
* Python 作用域 (Scope) 及命名空間 (Namespace): Python 作用域 Scope 及命名空間 Namespace.
* 初見 class::
* 隨意的備註::
* 繼承 (Inheritance): 繼承 Inheritance.
* 私有變數::
* 補充說明::
* 疊代器 (Iterator): 疊代器 Iterator.
* 產生器 (Generator): 產生器 Generator.
* 產生器運算式::


File: python.info,  Node: 關於名稱與物件的一段話,  Next: Python 作用域 Scope 及命名空間 Namespace,  Up: Class（類別）

2.9.1 關於名稱與物件的一段話
----------------------------

物件有個體性 (individuality)，且多個名稱（在多個作用域 (scope) ）可以被
連結到相同的物件。這在其他語言中被稱為別名 (aliasing)。初次接觸 Python 時
通常不會注意這件事，而在處理不可變的基本型別（數值、字串、tuple）時，它
也可以安全地被忽略。然而，別名在含有可變物件（如 list（串列）、
dictionary（字典）、和大多數其他的型別）的 Python 程式碼語意中，可能會有
意外的效果。這通常有利於程式，因為別名在某些方面表現得像指標 (pointer)。
舉例來說，在實作時傳遞一個物件是便宜的，因為只有指標被傳遞；假如函式修改
了一個作為引數傳遞的物件，呼叫函式者 (caller) 能夠見到這些改變——這消除了
在 Pascal 中兩個相異引數傳遞機制的需求。


File: python.info,  Node: Python 作用域 Scope 及命名空間 Namespace,  Next: 初見 class,  Prev: 關於名稱與物件的一段話,  Up: Class（類別）

2.9.2 Python 作用域 (Scope) 及命名空間 (Namespace)
--------------------------------------------------

在介紹 class 之前，我必須先告訴你一些關於 Python 作用域的規則。Class
definition（類別定義）以命名空間展現了一些俐落的技巧，而你需要了解作用域
和命名空間的運作才能完整理解正在發生的事情。順帶一提，關於這個主題的知識
對任何進階的 Python 程式設計師都是很有用的。

讓我們從一些定義開始。

`命名空間'是從名稱到物件的映射。大部分的命名空間現在都是以 Python 的
dictionary 被實作，但通常不會以任何方式被察覺（除了性能），且它可能會在
未來改變。命名空間的例子有：內建名稱的集合（包含如 *note abs(): 13f3. 的
函式，和內建的例外名稱）；模組中的全域 (global) 名稱；和在函式調用中的區
域 (local) 名稱。某種意義上，物件中的屬性集合也會形成一個命名空間。關於
命名空間的重要一點是，不同命名空間中的名稱之間絕對沒有關係；舉例來說，兩
個不一樣的模組都可以定義一個 ‘maximize’ 函式而不會混淆——模組的使用者必須
為它加上前綴 (prefix) 模組名稱。

順帶一提，我使用`屬性 (attribute)' 這個字，統稱句號 (dot) 後面的任何名稱
——例如，運算式中的 ‘z.real’，‘real’ 是物件 ‘z’ 的一個屬性。嚴格來說，模
組中名稱的參照都是屬性參照：在運算式 ‘modname.funcname’ 中，‘modname’ 是
模組物件而 ‘funcname’ 是它的屬性。在這種情況下，模組的屬性和模組中定義的
全域名稱碰巧有一個直接的對映：他們共享了相同的命名空間！(1)

屬性可以是唯讀的或可寫的。在後者的情況下，對屬性的賦值是可能的。模組屬性
是可寫的：你可以寫 ‘modname.the_answer = 42’。可寫屬性也可以用 *note
del: 13a2. 陳述式刪除。例如，‘del modname.the_answer’ 將從名為 ‘modname’
的物件中刪除屬性 ‘the_answer’。

命名空間在不同的時刻被建立，並且有不同的壽命。當 Python 直譯器啟動時，含
有內建名稱的命名空間會被建立，並且永遠不會被刪除。當模組定義被讀入時，模
組的全域命名空間會被建立；一般情況下，模組的命名空間也會持續到直譯器結束
。被直譯器的頂層調用 (top-level invocation) 執行的陳述式，不論是從腳本檔
案讀取的或是互動模式中的，會被視為一個稱為 *note __main__: 1. 的模組的一
部分，因此它們具有自己的全域命名空間。（內建名稱實際上也存在一個模組中，
它被稱為 *note builtins: 12.。）

函式的區域命名空間是在呼叫函式時建立的，而當函式返回，或引發了未在函式中
處理的例外時，此命名空間將會被刪除。（實際上，忘記是描述實際發生的事情的
更好方法。） 當然，每個遞迴調用 (recursive invocation) 都有自己的區域命
名空間。

`作用域'是 Python 程式中的一個文本區域 (textual region)，在此區域，命名
空間是可直接存取的。這裡的「可直接存取的」意思是，對一個名稱的非限定參照
(unqualified reference) 可以在命名空間內嘗試尋找該名稱。

儘管作用域是靜態地被決定，但它們是動態地被使用的。在執行期間內的任何時間
點，都會有 3 或 4 個巢狀的作用域，其命名空間是可以被直接存取的：

   * 最內層作用域，會最先被搜尋，而它包含了區域名稱

   * 任何外圍函式 (enclosing function) 的作用域，會從最近的外圍作用域開
     始搜尋，它包含了非區域 (non-local) 和非全域 (non-global) 的名稱

   * 倒數第二個作用域，包含當前模組的全域名稱

   * 最外面的作用域（最後搜尋），是包含內建名稱的命名空間

如果一個名稱被宣告為全域，則所有的參照和賦值將直接轉到包含模組全域名稱的
中間作用域。要重新連結最內層作用域以外找到的變數，可以使用 *note
nonlocal: d07. 陳述式；如果那些變數沒有被宣告為 nonlocal，則它們會是唯讀
的（嘗試寫入這樣的變數只會在最內層的作用域內建立一個`新的'區域變數，同名
的外部變數則維持不變）。

通常，區域作用域會參照（文本的）當前函式的區域名稱。在函式外部，區域作用
域與全域作用域參照相同的命名空間：模組的命名空間。然而，Class definition
會在區域作用域中放置另一個命名空間。

務必要了解，作用域是按文本被決定的：在模組中定義的函式，其全域作用域便是
該模組的命名空間，無論函式是從何處或以什麼別名被呼叫。另一方面，對名稱的
實際搜尋是在執行時期 (run time) 動態完成的——但是，語言定義的發展，正朝向
在「編譯」時期 (compile time) 的靜態名稱解析 (static name resolution)，
所以不要太依賴動態名稱解析 (dynamic name resolution)！ （事實上，局部變
數已經是靜態地被決定。）

一個 Python 的特殊癖好是——假如沒有 *note global: 1378. 或 *note
nonlocal: d07. 陳述式的效果——名稱的賦值 (assignment) 都會指向最內層作用
域。賦值不會複製資料——它們只會把名稱連結至物件。刪除也是一樣：陳述式
‘del x’ 會從區域作用域參照的命名空間移除 ‘x’ 的連結。事實上，引入新名稱
的所有運算都使用區域作用域：特別是 *note import: ce7. 陳述式和函式定義，
會連結區域作用域內的模組或函式名稱。

*note global: 1378. 陳述式可以用來表示特定變數存活在全域作用域，應該被重
新綁定到那裡；*note nonlocal: d07. 陳述式表示特定變數存活在外圍作用域內
，應該被重新綁定到那裡。

* Menu:

* 作用域和命名空間的範例::

   ---------- Footnotes ----------

   (1) (1) 有一個例外。模組物件有一個秘密的唯讀屬性，稱為 *note
__dict__: 5f5.，它回傳用於實作模組命名空間的 dictionary；*note __dict__:
5f5. 這個名稱是一個屬性但不是全域名稱。顯然，使用此屬性將違反命名空間實
作的抽象化，而應該僅限用於事後除錯器 (post-mortem debugger) 之類的東西。


File: python.info,  Node: 作用域和命名空間的範例,  Up: Python 作用域 Scope 及命名空間 Namespace

2.9.2.1 作用域和命名空間的範例
..............................

這是一個範例，演示如何參照不同的作用域和命名空間，以及 *note global:
1378. 和 *note nonlocal: d07. 如何影響變數的綁定：

     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)

範例程式碼的輸出是：

     After local assignment: test spam
     After nonlocal assignment: nonlocal spam
     After global assignment: nonlocal spam
     In global scope: global spam

請注意，`區域'賦值（預設情況）不會改變 `scope_test' 對 `spam' 的連結。
*note nonlocal: d07. 賦值改變了 `scope_test' 對 `spam' 的連結，而 *note
global: 1378. 賦值改變了模組層次的連結。

你還可以發現，在 *note global: 1378. 賦值之前，沒有對 `spam' 的連結。


File: python.info,  Node: 初見 class,  Next: 隨意的備註,  Prev: Python 作用域 Scope 及命名空間 Namespace,  Up: Class（類別）

2.9.3 初見 class
----------------

Class 採用一些新的語法，三個新的物件型別，以及一些新的語意。

* Menu:

* Class definition（類別定義）語法::
* Class 物件::
* 實例物件::
* Method 物件::
* Class 及實例變數::


File: python.info,  Node: Class definition（類別定義）語法,  Next: Class 物件,  Up: 初見 class

2.9.3.1 Class definition（類別定義）語法
........................................

Class definition 最簡單的形式如下：

     class ClassName:
         <statement-1>
         .
         .
         .
         <statement-N>

Class definition，如同函式定義（*note def: e83. 陳述式），必須在它們有任
何效果前先執行。（你可以想像把 class definition 放在一個 *note if: eab.
陳述式的分支，或在函式裡。）

在實作時，class definition 內的陳述式通常會是函式定義，但其他陳述式也是
允許的，有時很有用——我們稍後會回到這裡。Class 中的函式定義通常會有一個獨
特的引數列表形式，取決於 method 的呼叫慣例——再一次地，這將會在稍後解釋。

當進入 class definition，一個新的命名空間將會被建立，並且作為區域作用域
——因此，所有區域變數的賦值將進入這個新的命名空間。特別是，函式定義會在這
裡連結新函式的名稱。

正常地（從結尾處）離開 class definition 時，一個 `class 物件'會被建立。
基本上這是一個包裝器 (wrapper)，裝著 class definition 建立的命名空間內容
；我們將在下一節中更加了解 class 物件。原始的區域作用域（在進入 class
definition 之前已生效的作用域）會恢復，在此 class 物件會被連結到 class
definition 標頭中給出的 class 名稱（在範例中為 ‘ClassName’）。


File: python.info,  Node: Class 物件,  Next: 實例物件,  Prev: Class definition（類別定義）語法,  Up: 初見 class

2.9.3.2 Class 物件
..................

Class 物件支援兩種運算：屬性參照 (attribute reference) 和實例化
(instantiation)。

`屬性參照'使用 Python 中所有屬性參照的標準語法：‘obj.name’。有效的屬性名
稱是 class 物件被建立時，class 的命名空間中所有的名稱。所以，如果 class
definition 看起來像這樣：

     class MyClass:
         """A simple example class"""
         i = 12345

         def f(self):
             return 'hello world'

那麼 ‘MyClass.i’ 和 ‘MyClass.f’ 都是有效的屬性參照，會分別回傳一個整數和
一個函式物件。Class 屬性也可以被指派 (assign)，所以您可以透過賦值改變
‘MyClass.i’ 的值。‘__doc__’ 也是一個有效的屬性，會回傳屬於該 class 的說
明字串 (docstring)：‘"A simple example class"’。

Class `實例化'使用了函式記法 (function notation)。就好像 class 物件是一
個沒有參數的函式，它回傳一個新的 class 實例。例如（假設是上述的 class）
：

     x = MyClass()

建立 class 的一個新`實例'，並將此物件指派給區域變數 ‘x’。

實例化運算（「呼叫」一個 class 物件）會建立一個空的物件。許多 class 喜歡
在建立物件時有著自訂的特定實例初始狀態。因此，class 可以定義一個名為
*note __init__(): e23. 的特別 method，像這樣：

     def __init__(self):
         self.data = []

當 class 定義了 *note __init__(): e23. method，class 實例化會為新建的
class 實例自動調用 *note __init__(): e23.。所以在這個範例中，一個新的、
初始化的實例可以如此獲得：

     x = MyClass()

當然，*note __init__(): e23. method 可能為了更多的彈性而有引數。在這種情
況下，要給 class 實例化運算子的引數會被傳遞給 *note __init__(): e23.。例
如：

     >>> 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)


File: python.info,  Node: 實例物件,  Next: Method 物件,  Prev: Class 物件,  Up: 初見 class

2.9.3.3 實例物件
................

現在，我們可以如何處理實例物件？實例物件能理解的唯一運算就是屬性參照。有
兩種有效的屬性名稱：資料屬性 (data attribute) 和 method。

`資料屬性'對應 Smalltalk 中的「實例變數」，以及 C++ 中的「資料成員」。資
料屬性不需要被宣告；和區域變數一樣，它們在第一次被賦值時就會立即存在。例
如，如果 ‘x’ 是 ‘MyClass’ 在上述例子中建立的實例，下面的程式碼將印出值
‘16’，而不留下蹤跡：

     x.counter = 1
     while x.counter < 10:
         x.counter = x.counter * 2
     print(x.counter)
     del x.counter

實例的另一種屬性參照是 `method'。Method 是一個「屬於」物件的函式。（在
Python 中，術語 method 並不是 class 實例所獨有的：其他物件型別也可以有
method。例如，list 物件具有稱為 append、insert、remove、sort 等 method。
但是，在下面的討論中，我們將用術語 method 來專門表示 class 實例物件的
method，除非另有明確說明。）

實例物件的有效 method 名稱取決於其 class。根據定義，一個 class 中所有的
函式物件屬性，就定義了實例的對應 method。所以在我們的例子中，‘x.f’ 是一
個有效的 method 參照，因為 ‘MyClass.f’ 是一個函式，但 ‘x.i’ 不是，因為
‘MyClass.i’ 不是。但 ‘x.f’ 與 ‘MyClass.f’ 是不一樣的——它是一個 `method 物
件'，而不是函式物件。


File: python.info,  Node: Method 物件,  Next: Class 及實例變數,  Prev: 實例物件,  Up: 初見 class

2.9.3.4 Method 物件
...................

通常，一個 method 在它被連結後隨即被呼叫：

     x.f()

在 ‘MyClass’ 的例子中，這將回傳字串 ‘’hello world’’。然而，並沒有必要立
即呼叫一個 method：‘x.f’ 是一個 method 物件，並且可以被儲藏起來，之後再
被呼叫。舉例來說：

     xf = x.f
     while True:
         print(xf())

將會持續印出 ‘hello world’ 直到天荒地老。

當一個 method 被呼叫時究竟會發生什麼事？你可能已經注意到 ‘x.f()’ 被呼叫
時沒有任何的引數，儘管 ‘f()’ 的函式定義有指定一個引數。這個引數發生了什
麼事？當一個需要引數的函式被呼叫而沒有給任何引數時，Python 肯定會引發例
外——即使該引數實際上沒有被使用...

事實上，你可能已經猜到了答案：method 的特殊之處在於，實例物件會作為函式
中的第一個引數被傳遞。在我們的例子中，‘x.f()’ 這個呼叫等同於
‘MyClass.f(x)’。一般來說，呼叫一個有 `n' 個引數的 method，等同於呼叫一個
對應函式，其引數列表 (argument list) 被建立時，會在第一個引數前插入該
method 的實例物件。

如果你仍然不了解 method 怎麼運作，看一眼實作可能會清楚一些事。當一個實例
的非資料屬性被參照時，該實例的 class 會被搜尋。如果該名稱是一個有效的
class 屬性，而且是一個函式物件，則一個 method 物件會被建立，建立的方法是
藉由打包（指向）該實例物件及剛被找到的函式物件，形成一個抽象的物件：這就
是 method 物件。當 method 物件帶著一個引數列表被呼叫，則一個新的引數列表
會從實例物件和該引數列表被建構，而該函式物件會以這個新的引數列表被呼叫。


File: python.info,  Node: Class 及實例變數,  Prev: Method 物件,  Up: 初見 class

2.9.3.5 Class 及實例變數
........................

一般來說，實例變數用於每一個實例的獨特資料，而 class 變數用於該 class 的
所有實例共享的屬性和 method：

     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'

如同在*note 關於名稱與物件的一段話: 13f0.的討論，共享的資料若涉及 *note
mutable: 135e. 物件，如 list 和 dictionary，可能會產生意外的影響。舉例來
說，下列程式碼的 `tricks' list 不應該作為一個 class 變數使用，因為這個
list 將會被所有的 `Dog' 實例所共享：

     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']

正確的 class 設計應該使用實例變數：

     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']


File: python.info,  Node: 隨意的備註,  Next: 繼承 Inheritance,  Prev: 初見 class,  Up: Class（類別）

2.9.4 隨意的備註
----------------

如果屬性名稱同時出現在一個實例和一個 class 中，則屬性的尋找會以實例為優
先：

     >>> 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

資料屬性可能被 method 或是被物件的一般使用者（「客戶端」）所參照。也就是
說，class 不可用於實作純粹抽象的資料型別。事實上，在 Python 中沒有任何可
能的方法，可強制隱藏資料——這都是基於慣例。（另一方面，以 C 編寫的 Python
實作可以完全隱藏實作細節並且在必要時控制物件的存取；這可以被以 C 編寫的
Python 擴充所使用。）

客戶端應該小心使用資料屬性——客戶端可能會因為覆寫他們的資料屬性，而破壞了
被 method 維護的不變性。注意，客戶端可以增加他們自己的資料屬性到實例物件
，但不影響 method 的有效性，只要避免名稱衝突即可——再一次提醒，命名慣例可
以在這裡節省很多麻煩。

在 method 中參照資料屬性（或其他 method！）是沒有簡寫的。我發現這實際上
增加了 method 的可閱讀性：在瀏覽 method 時，絕不會混淆區域變數和實例變數
。

通常，方法的第一個引數稱為 ‘self’。這僅僅只是一個慣例：‘self’ 這個名字對
Python 來說完全沒有特別的意義。但請注意，如果不遵循慣例，你的程式碼可能
對其他 Python 程式設計師來說可讀性較低，此外，也可以想像一個可能因信任此
慣例而編寫的 `class 瀏覽器 (browser)' 程式。

任何一個作為 class 屬性的函式物件都為該 class 的實例定義了一個相應的
method。函式定義不一定要包含在 class definition 的文本中：將函式物件指定
給 class 中的區域變數也是可以的。例如：

     # 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

現在 ‘f’、‘g’ 和 ‘h’ 都是 class ‘C’ 的屬性，並指向函式物件，所以他們都是
class ‘C’ 實例的 method —— ‘h’ 與 ‘g’ 是完全一樣的。請注意，這種做法通常
只會使該程式的讀者感到困惑。

Method 可以藉由使用 ‘self’ 引數的 method 屬性，呼叫其他 method：

     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)

Method 可以用與一般函式相同的方式參照全域名稱。與 method 相關的全域作用
域，就是包含其定義的模組。（class 永遠不會被用作全域作用域。）雖然人們很
少有在 method 中使用全域資料的充分理由，但全域作用域仍有許多合法的使用：
比方說，被 import 至全域作用域的函式和模組，可以被 method 以及在該作用域
中定義的函式和 class 所使用。通常，包含 method 的 class，它本身就是被定
義在這個全域作用域，在下一節，我們將看到 method 想要參照自己的 class 的
一些好原因。

每個值都是一個物件，因此都具有一個 `class'，也可以稱為它的 `type（型別）
'。它以 ‘object.__class__’ 被儲存。


File: python.info,  Node: 繼承 Inheritance,  Next: 私有變數,  Prev: 隨意的備註,  Up: Class（類別）

2.9.5 繼承 (Inheritance)
------------------------

當然，如果沒有支援繼承，「class」這個語言特色就不值得被稱為 class。一個
derived class（衍生類別）定義的語法看起來如下：

     class DerivedClassName(BaseClassName):
         <statement-1>
         .
         .
         .
         <statement-N>

名稱 ‘BaseClassName’ 被定義的作用域必須是包含 derived class 定義的作用域
。要代替 base class（基底類別）的名稱，用其他任意的運算式也是被允許的。
這會很有用，例如，當一個 base class 是在另一個模組中被定義時：

     class DerivedClassName(modname.BaseClassName):

執行 derived class 定義的過程，與執行 base class 相同。當 class 物件被建
構時，base class 會被記住。這是用於解析屬性參照：如果一個要求的屬性無法
在該 class 中找到，則會繼續在 base class 中搜尋。假如該 base class 本身
也是衍生自其他 class，則這個規則會遞迴地被應用。

關於 derived class 的實例化並沒有特別之處：‘DerivedClassName()’ 會建立該
class 的一個新實例。Method 的參照被解析如下：對應的 class 屬性會被搜尋，
如果需要，沿著 base class 的繼承鍊往下走，如果這產生了一個函式物件，則該
method 的參照是有效的。

Derived class 可以覆寫其 base class 的 method。因為 method 在呼叫同一個
物件的其他 method 時沒有特別的特權，所以當 base class 的一個 method 在呼
叫相同 base class 中定義的另一個 method 時，最終可能會呼叫到一個覆寫它的
derived class 中的 method。（給 C++ 程式設計師：Python 中所有 method 實
際上都是 ‘virtual’。）

一個在 derived class 覆寫的 method 可能事實上是想要擴充而非單純取代 base
class 中相同名稱的 method。要直接呼叫 base class 的 method 有一個簡單的
方法：只要呼叫 ‘BaseClassName.methodname(self, arguments)’。這有時對客戶
端也很有用。（請注意，只有在 base class 在全域作用域可以用
‘BaseClassName’ 被存取時，這方法才有效。）

Python 有兩個內建函式可以用於繼承：

   * 使用 *note isinstance(): 551. 判斷一個實例的型別：‘isinstance(obj,
     int)’ 只有在 ‘obj.__class__’ 是 *note int: 204. 或衍伸自 *note int:
     204. 時，結果才會是 ‘True’。

   * 使用 *note issubclass(): 552. 判斷 class 繼承：‘issubclass(bool,
     int)’ 會是 ‘True’，因為 *note bool: 2bd. 是 *note int: 204. 的
     subclass（子類別）。但是，‘issubclass(float, int)’ 是 ‘False’，因為
     *note float: 1fd. 並不是 *note int: 204. 的 subclass。

* Menu:

* 多重繼承::


File: python.info,  Node: 多重繼承,  Up: 繼承 Inheritance

2.9.5.1 多重繼承
................

Python 也支援多重繼承的形式。一個有多個 base class 的 class definition 看
起來像這樣子：

     class DerivedClassName(Base1, Base2, Base3):
         <statement-1>
         .
         .
         .
         <statement-N>

在大多數情況下，最簡單的例子裡，你可以這樣思考，對於繼承自 parent class（
父類別）的屬性，其搜尋規則為：深度優先、從左到右、在階層裡重疊的相同
class 中不重複搜尋。因此，假如有一個屬性在 ‘DerivedClassName’ 沒有被找到
，則在 ‘Base1’ 搜尋它，接著（遞迴地）在 ‘Base1’ 的 base class 中搜尋，假
如在那裡又沒有找到的話，會在 ‘Base2’ 搜尋，依此類推。

事實上，它稍微複雜一些；method 的解析順序是動態地變化，以支援對 *note
super(): 5dd. 的合作呼叫。這個方式在其他的多重繼承語言中，稱為呼叫下一個
方法 (call-next-method)，且比在單一繼承語言中的 super call（超級呼叫）來
得更強大。

動態排序是必要的，因為多重繼承的所有情況都表現一或多的菱形關係（其中至少
一個 parent class 可以從最底層 class 透過多個路徑存取）。例如，所有的
class 都繼承自 *note object: 3d2.，因此任何多重繼承的情況都提供了多個到
達 *note object: 3d2. 的路徑。為了避免 base class 被多次存取，動態演算法
以這些方式將搜尋順序線性化 (linearize)：保留每個 class 中規定的從左到右
的順序、對每個 parent 只會呼叫一次、使用單調的 (monotonic) 方式（意思是
，一個 class 可以被 subclassed（子類別化），而不會影響其 parent 的搜尋優
先順序）。總之，這些特性使設計出可靠又可擴充、具有多重繼承的 class 成為
可能。更多資訊，請見
‘https://www.python.org/download/releases/2.3/mro/’。


File: python.info,  Node: 私有變數,  Next: 補充說明,  Prev: 繼承 Inheritance,  Up: Class（類別）

2.9.6 私有變數
--------------

「私有」(private) 實例變數，指的是不在物件內部便無法存取的變數，這在
Python 中是不存在的。但是，大多數 Python 的程式碼都遵守一個慣例：前綴為
一個底線的名稱（如：‘_spam’）應被視為 API （應用程式介面）的非公有
(non-public) 部分（無論它是函式、方法或是資料成員）。這被視為一個實作細
節，如有調整，亦不另行通知。

既然 class 私有的成員已有一個有效的用例（即避免名稱與 subclass 定義的名
稱衝突），這種機制也存在另一個有限的支援，稱為 `name mangling'（名稱修飾
）。任何格式為 ‘__spam’（至少兩個前導下底線，最多一個尾隨下底線）的物件
名稱 (identifier) 會被文本地被替換為 ‘_classname__spam’，在此
‘classname’ 就是去掉前導下底線的當前 class 名稱。只要這個修飾是在 class
的定義之中發生，它就會在不考慮該物件名稱的語法位置的情況下完成。

名稱修飾對於讓 subclass 覆寫 method 而不用破壞 class 內部的 method 呼叫
，是有幫助的。舉例來說：

     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)

在上例中，就算在 ‘MappingSubclass’ 當中加入 ‘__update’ 識別符，也能順利
運作，因為在 ‘Mapping’ class 中，它會被替換為 ‘_Mapping__update’，而在
‘MappingSubclass’ class 中，它會被替換為 ‘_MappingSubclass__update’。

請注意，修飾規則是被設計來避免意外；它仍可能存取或修改一個被視為私有的變
數。這在特殊情況下甚至可能很有用，例如在除錯器 (debugger)。

另外也注意，傳遞給 ‘exec()’ 或 ‘eval()’ 的程式碼不會把調用 class 的名稱
視為當前的 class；這和 ‘global’ 陳述式的效果類似，該效果同樣僅限於整體被
位元組編譯後 (byte-compiled) 的程式碼。同樣的限制適用於 ‘getattr()’，
‘setattr()’ 和 ‘delattr()’，以及直接參照 ‘__dict__’ 時。


File: python.info,  Node: 補充說明,  Next: 疊代器 Iterator,  Prev: 私有變數,  Up: Class（類別）

2.9.7 補充說明
--------------

如果有一種資料型別，類似於 Pascal 的「record」或 C 的「struct」，可以將
一些有名稱的資料項目捆綁在一起，有時候這會很有用。其實一個空白的 class
definition 就可以勝任：

     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

用來處理特殊抽象資料型別的一段 Python 程式碼，經常能以傳遞一個 class 來
替代，此 class 模擬該資料型別的多種 method。例如，如果你有一個函式，它會
從一個檔案物件來格式化某些資料，你也可以定義一個有 ‘read()’ 和
‘readline()’ method 的 class 作為替代方式，從字串緩衝區取得資料，並將其
作為引數來傳遞。

實例的 method 物件也具有屬性：‘m.__self__’ 就是帶有 method ‘m()’ 的實例
物件，而 ‘m.__func__’ 則是該 method 所對應的函式物件。


File: python.info,  Node: 疊代器 Iterator,  Next: 產生器 Generator,  Prev: 補充說明,  Up: Class（類別）

2.9.8 疊代器 (Iterator)
-----------------------

到目前為止，你可能已經注意到大多數的容器 (container) 物件都可以使用
*note for: cfa. 陳述式來進行迴圈：

     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='')

這種存取風格清晰、簡潔且方便。疊代器的使用在 Python 中處處可見且用法一致
。在幕後，*note for: cfa. 陳述式會在容器物件上呼叫 *note iter(): ded.。
該函式回傳一個疊代器物件，此物件定義了 *note __next__(): d2c. method，而
此 method 會逐一存取容器中的元素。當元素用盡時，*note __next__(): d2c. 將
引發 *note StopIteration: 581. 例外，來通知 ‘for’ 終止迴圈。你可以使用內
建函式 *note next(): 775. 來呼叫 *note __next__(): d2c. method；這個例子
展示了它的運作方式：

     >>> 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

看過疊代器協定的幕後機制後，在你的 class 加入疊代器的行為就很容易了。定
義一個 *note __iter__(): 608. method 來回傳一個帶有 *note __next__():
d2c. method 的物件。如果 class 已定義了 ‘__next__()’，則 *note
__iter__(): 608. 可以只回傳 ‘self’：

     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]

     >>> rev = Reverse('spam')
     >>> iter(rev)
     <__main__.Reverse object at 0x00A1DB50>
     >>> for char in rev:
     ...     print(char)
     ...
     m
     a
     p
     s


File: python.info,  Node: 產生器 Generator,  Next: 產生器運算式,  Prev: 疊代器 Iterator,  Up: Class（類別）

2.9.9 產生器 (Generator)
------------------------

*note 產生器: a83.是一個用於建立疊代器的簡單而強大的工具。它們的寫法和常
規的函式一樣，但當它們要回傳資料時，會使用 *note yield: 2c7. 陳述式。每
次在產生器上呼叫 *note next(): 775. 時，它會從上次離開的位置恢復執行（它
會記得所有資料值以及上一個被執行的陳述式）。以下範例顯示，建立產生器可以
相當地容易：

     def reverse(data):
         for index in range(len(data)-1, -1, -1):
             yield data[index]

     >>> for char in reverse('golf'):
     ...     print(char)
     ...
     f
     l
     o
     g

任何可以用產生器來完成的事，也能用以 class 為基礎的疊代器來完成，如同前
一節的描述。而讓產生器的程式碼更為精簡的原因是，*note __iter__(): 608. 和
*note __next__(): 140e. method 會自動被建立。

另一個關鍵的特性在於，區域變數和執行狀態會在每次呼叫之間自動被儲存。這使
得該函式比使用 ‘self.index’ 和 ‘self.data’ 這種實例變數的方式更容易編寫
且更為清晰。

除了會自動建立 method 和儲存程式狀態，當產生器終止時，它們還會自動引發
*note StopIteration: 581.。這些特性結合在一起，使建立疊代器能與編寫常規
函式一樣容易。


File: python.info,  Node: 產生器運算式,  Prev: 產生器 Generator,  Up: Class（類別）

2.9.10 產生器運算式
-------------------

某些簡單的產生器可以寫成如運算式一般的簡潔程式碼，所用的語法類似 list
comprehension（串列綜合運算），但外層為括號而非方括號。這種運算式被設計
用於產生器將立即被外圍函式 (enclosing function) 所使用的情況。產生器運算
式與完整的產生器定義相比，程式碼較精簡但功能較少，也比等效的 list
comprehension 更為節省記憶體。

例如：

     >>> 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']

註解
....


File: python.info,  Node: Python 標準函式庫概覽,  Next: Python 標準函式庫概覽——第二部份,  Prev: Class（類別）,  Up: Python 教學

2.10 Python 標準函式庫概覽
==========================

* Menu:

* 作業系統介面::
* 檔案之萬用字元 (File Wildcards): 檔案之萬用字元 File Wildcards.
* 命令列引數::
* 錯誤輸出重新導向與程式終止::
* 字串樣式比對::
* 數學相關::
* 網路存取::
* 日期與時間::
* 資料壓縮::
* 效能量測::
* 品質控管::
* 標準模組庫::


File: python.info,  Node: 作業系統介面,  Next: 檔案之萬用字元 File Wildcards,  Up: Python 標準函式庫概覽

2.10.1 作業系統介面
-------------------

*note os: c4. 模組提供了數十個與作業系統溝通的函式：

     >>> 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

務必使用 ‘import os’ 而非 ‘from os import *’。這將避免因系統不同而有實作
差異的 *note os.open(): 758. 覆蓋內建函式 *note open(): 16f.。

在使用 *note os: c4. 諸如此類大型模組時搭配內建函式 *note dir(): df9. 和
*note help(): 175. 是非常有用的：

     >>> import os
     >>> dir(os)
     <returns a list of all module functions>
     >>> help(os)
     <returns an extensive manual page created from the module's docstrings>

對於日常檔案和目錄管理任務，*note shutil: e9. 模組提供了更容易使用的高階
介面：

     >>> import shutil
     >>> shutil.copyfile('data.db', 'archive.db')
     'archive.db'
     >>> shutil.move('/build/executables', 'installdir')
     'installdir'


File: python.info,  Node: 檔案之萬用字元 File Wildcards,  Next: 命令列引數,  Prev: 作業系統介面,  Up: Python 標準函式庫概覽

2.10.2 檔案之萬用字元 (File Wildcards)
--------------------------------------

*note glob: 88. 模組提供了一函式可以從目錄萬用字元中搜尋並產生檔案列表：

     >>> import glob
     >>> glob.glob('*.py')
     ['primes.py', 'random.py', 'quote.py']


File: python.info,  Node: 命令列引數,  Next: 錯誤輸出重新導向與程式終止,  Prev: 檔案之萬用字元 File Wildcards,  Up: Python 標準函式庫概覽

2.10.3 命令列引數
-----------------

通用工具腳本常需要處理命令列引數。這些引數會以 list（串列）形式存放在
*note sys: fd. 模組的 `argv' 屬性中。例如在命令列執行 ‘python demo.py
one two three’ 會有以下輸出結果：

     >>> import sys
     >>> print(sys.argv)
     ['demo.py', 'one', 'two', 'three']

*note argparse: 5. 模組提供了一種更複雜的機制來處理命令列引數。以下腳本
可擷取一個或多個檔案名稱，並可選擇要顯示的行數：

     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)

當 ‘python top.py --lines=5 alpha.txt beta.txt’ 在命令列執行時，該腳本會
將 ‘args.lines’ 設為 ‘5’，並將 ‘args.filenames’ 設為 ‘['alpha.txt',
'beta.txt']’。


File: python.info,  Node: 錯誤輸出重新導向與程式終止,  Next: 字串樣式比對,  Prev: 命令列引數,  Up: Python 標準函式庫概覽

2.10.4 錯誤輸出重新導向與程式終止
---------------------------------

*note sys: fd. 模組也有 `stdin'，`stdout'，和 `stderr' 等屬性。即使當
`stdout' 被重新導向時，後者 `stderr' 可輸出警告和錯誤訊息：

     >>> sys.stderr.write('Warning, log file not found starting a new one\n')
     Warning, log file not found starting a new one

終止腳本最直接的方式就是利用 ‘sys.exit()’。


File: python.info,  Node: 字串樣式比對,  Next: 數學相關,  Prev: 錯誤輸出重新導向與程式終止,  Up: Python 標準函式庫概覽

2.10.5 字串樣式比對
-------------------

*note re: dd. 模組提供正規表示式 (regular expression) 做進階的字串處理。
當要處理複雜的比對以及操作時，正規表示式是簡潔且經過最佳化的解決方案：

     >>> 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'

當只需要簡單的字串操作時，因為可讀性以及方便除錯，字串本身的 method 是比
較建議的：

     >>> 'tea for too'.replace('too', 'two')
     'tea for two'


File: python.info,  Node: 數學相關,  Next: 網路存取,  Prev: 字串樣式比對,  Up: Python 標準函式庫概覽

2.10.6 數學相關
---------------

*note math: b1. 模組提供了 C 函式庫中底層的浮點數運算的函式：

     >>> import math
     >>> math.cos(math.pi / 4)
     0.70710678118654757
     >>> math.log(1024, 2)
     10.0

*note random: dc. 模組提供了隨機選擇的工具：

     >>> 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

*note statistics: f5. 模組提供了替數值資料計算基本統計量（包括平均、中位
數、變異量數等）的功能：

     >>> 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

SciPy 專案 <‘https://scipy.org’> 上也有許多數值計算相關的模組。


File: python.info,  Node: 網路存取,  Next: 日期與時間,  Prev: 數學相關,  Up: Python 標準函式庫概覽

2.10.7 網路存取
---------------

Python 中有許多存取網路以及處理網路協定。最簡單的兩個例子包括 *note
urllib.request: 129. 模組可以從網址抓取資料以及 *note smtplib: ed. 可以
用來寄郵件：

     >>> 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()

（注意第二個例子中需要在本地端執行一個郵件伺服器。）


File: python.info,  Node: 日期與時間,  Next: 資料壓縮,  Prev: 網路存取,  Up: Python 標準函式庫概覽

2.10.8 日期與時間
-----------------

*note datetime: 30. 模組提供許多 class 可以操作日期以及時間，從簡單從複
雜都有。模組支援日期與時間的運算，而實作的重點是有效率的成員擷取以達到輸
出格式化以及操作。模組也提供支援時區換算的類別。

     >>> # 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


File: python.info,  Node: 資料壓縮,  Next: 效能量測,  Prev: 日期與時間,  Up: Python 標準函式庫概覽

2.10.9 資料壓縮
---------------

常見的解壓縮以及壓縮格式都有直接支援的模組。包括：*note zlib: 14d.、
*note gzip: 8b.、*note bz2: 13.、*note lzma: ad.、*note zipfile: 14b. 以
及 *note tarfile: 101.。

     >>> 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


File: python.info,  Node: 效能量測,  Next: 品質控管,  Prev: 資料壓縮,  Up: Python 標準函式庫概覽

2.10.10 效能量測
----------------

有一些 Python 使用者很想了解同個問題的不同實作方法的效能差異。Python 提
供了評估效能差異的工具。

舉例來說，有人可能會試著用 tuple 的打包機制來交換引數代替傳統的方式。
*note timeit: 10d. 模組可以迅速地展示效能的進步：

     >>> 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

相對於 *note timeit: 10d. 模組提供這麼細的粒度，*note profile: d3. 模組
以及 *note pstats: d4. 模組則提供了一些在大型的程式碼識別時間使用上關鍵
的區塊 (time critical section) 的工具。


File: python.info,  Node: 品質控管,  Next: 標準模組庫,  Prev: 效能量測,  Up: Python 標準函式庫概覽

2.10.11 品質控管
----------------

達到高品質軟體的一個方法，是在開發時對每個函式寫測試，以及在開發過程中要
不斷地跑這些測試。

*note doctest: 66. 模組提供了一個工具，掃描模組並根據程式中內嵌的文件字
串執行測試。撰寫測試如同簡單地將它的呼叫及輸出結果剪下並貼上到文件字串中
。透過提供範例給使用者，它強化了說明文件，並允許 doctest 模組確認程式碼
的結果與說明文件一致：

     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

*note unittest: 124. 模組不像 *note doctest: 66. 模組這般容易，但是它讓
你可以在另外一個檔案裡撰寫更完整的測試集：

     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


File: python.info,  Node: 標準模組庫,  Prev: 品質控管,  Up: Python 標準函式庫概覽

2.10.12 標準模組庫
------------------

"Batteries included" 是 Python 的設計哲學。這個理念可以透過使用它的大型
套件，感受複雜與強大的功能，來得到印證。例如：

   * 使用 *note xmlrpc.client: 148. 和 *note xmlrpc.server: 149. 模組使
     實作遠端程序呼叫變得更為容易。即使模組名稱裡有 XML，使用者並不需要
     直接操作 XML 檔案或事先具備相關知識。

   * 函式庫 *note email: 67. 套件用來管理 MIME 和其他 RFC 2822(1) 相關電
     子郵件訊息的文件。相異於 *note smtplib: ed. 和 *note poplib: d0. 這
     些實際用來發送與接收訊息的模組，email 套件擁有更完整的工具集，可用
     於建立與解析複雜訊息結構（包含附件檔案）以及實作編碼與標頭協定。

   * *note json: a4. 套件對 JSON 資料交換格式的解析，提供強大的支援。
     *note csv: 29. 模組則提供直接讀寫 CSV（以逗號分隔值的檔案格式，通常
     資料庫和電子表格都有支援）。*note xml.etree.ElementTree: 140.、
     *note xml.dom: 13d. 與 *note xml.sax: 144. 套件則支援 XML 的處理。
     綜觀所有，這些模組和套件都簡化了 Python 應用程式與其他工具之間的資
     料交換。

   * ‘sqllite3’ 模組是 SQLite 資料庫函式庫的一層包裝，提供一個具持久性的
     資料庫，可以使用稍微非標準的 SQL 語法來對它進行更新與存取。

   * 有數種支援國際化的模組，包括 *note gettext: 87.、*note locale: a9.
     和 *note codecs: 1b. 等套件。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2822.html


File: python.info,  Node: Python 標準函式庫概覽——第二部份,  Next: 虛擬環境與套件,  Prev: Python 標準函式庫概覽,  Up: Python 教學

2.11 Python 標準函式庫概覽——第二部份
====================================

第二部分涵蓋更多支援專業程式設計所需要的進階模組。這些模組很少出現在小腳
本中。

* Menu:

* 輸出格式化 (Output Formatting): 輸出格式化 Output Formatting.
* 模板化 (Templating): 模板化 Templating.
* 二進制資料記錄編排 (Binary Data Record Layouts): 二進制資料記錄編排 Binary Data Record Layouts.
* 多執行緒 (Multi-threading): 多執行緒 Multi-threading.
* 日誌記錄 (Logging): 日誌記錄 Logging.
* 弱引用 (Weak References): 弱引用 Weak References.
* 使用於 List 的工具::
* 十進制 (Decimal) 浮點數運算: 十進制 Decimal 浮點數運算.


File: python.info,  Node: 輸出格式化 Output Formatting,  Next: 模板化 Templating,  Up: Python 標準函式庫概覽——第二部份

2.11.1 輸出格式化 (Output Formatting)
-------------------------------------

*note reprlib: df. 模組提供了一個 *note repr(): 8b9. 的版本，專門用來以
簡短的形式顯示大型或深層的巢狀容器：

     >>> import reprlib
     >>> reprlib.repr(set('supercalifragilisticexpialidocious'))
     "{'a', 'c', 'd', 'e', 'f', 'g', ...}"

*note pprint: d2. 模組能對內建和使用者自定的物件提供更複雜的列印控制，並
且是以直譯器可讀的方式。當結果超過一行時，「漂亮的印表機」會加入換行和縮
排，以更清楚地顯示資料結構：

     >>> import pprint
     >>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta',
     ...     'yellow'], 'blue']]]
     ...
     >>> pprint.pprint(t, width=30)
     [[[['black', 'cyan'],
        'white',
        ['green', 'red']],
       [['magenta', 'yellow'],
        'blue']]]

*note textwrap: 10a. 模組能夠格式化文本的段落，以符合指定的螢幕寬度：

     >>> 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.

*note locale: a9. 模組能存取一個含有特定文化相關資料格式的資料庫。locale
模組的 format 函式有一個 grouping 屬性，可直接以群分隔符 (group
separator) 將數字格式化：

     >>> 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'


File: python.info,  Node: 模板化 Templating,  Next: 二進制資料記錄編排 Binary Data Record Layouts,  Prev: 輸出格式化 Output Formatting,  Up: Python 標準函式庫概覽——第二部份

2.11.2 模板化 (Templating)
--------------------------

*note string: f6. 模組包含一個多功能的 *note Template: 4f0. class，提供
的簡化語法適合使用者進行編輯時使用。它容許使用者客製化自己的應用程式，但
不必對原應用程式做出變更。

格式化方式是使用佔位符號名稱 (placeholder name)，它是由 ‘$’ 加上合法的
Python 識別符（字母、數字和下底線）構成。使用大括號包覆佔位符號以允許在
後面接上更多的字母和數字而無需插入空格。使用 ‘$$’ 將會跳脫為單一字元
‘$’：

     >>> 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.'

如果在 dictionary 或關鍵字引數中未提供某個佔位符號的值，那麼 *note
substitute(): 1433. method 將引發 *note KeyError: 3e9.。對於郵件合併
(mail-merge) 類型的應用程式，使用者提供的資料有可能是不完整的，此時使用
*note safe_substitute(): 1434. method 會更適當——如果資料有缺少，它會保持
佔位符號不變：

     >>> 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.'

Template 的 subclass（子類別）可以指定自訂的分隔符號 (delimiter)。例如，
一個相片瀏覽器的批次重新命名功能，可以選擇用百分號作為現在日期、照片序號
或檔案格式的佔位符號：

     >>> 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

模板化的另一個應用，是將程式邏輯與多樣的輸出格式細節分離開來。這樣就可以
為 XML 檔案、純文字報表和 HTML 網路報表替換自訂的模板。


File: python.info,  Node: 二進制資料記錄編排 Binary Data Record Layouts,  Next: 多執行緒 Multi-threading,  Prev: 模板化 Templating,  Up: Python 標準函式庫概覽——第二部份

2.11.3 二進制資料記錄編排 (Binary Data Record Layouts)
------------------------------------------------------

*note struct: f8. 模組提供了 *note pack(): cd6. 和 *note unpack(): 1437.
函式，用於處理可變動長度的二進制記錄格式。以下範例說明，如何在不使用
*note zipfile: 14b. 模組的情況下，使用迴圈瀏覽一個 ZIP 檔案中的標頭資訊
(header information)。壓縮程式碼 ‘"H"’ 和 ‘"I"’ 分別代表兩個和四個位元組
的無符號數 (unsigned number)。‘"<"’ 表示它們是標準大小，並使用小端
(little-endian) 位元組順序：

     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


File: python.info,  Node: 多執行緒 Multi-threading,  Next: 日誌記錄 Logging,  Prev: 二進制資料記錄編排 Binary Data Record Layouts,  Up: Python 標準函式庫概覽——第二部份

2.11.4 多執行緒 (Multi-threading)
---------------------------------

執行緒是一種用來對非順序相依 (sequentially dependent) 的多個任務進行解耦
(decoupling) 的技術。當其他任務在背景執行時，多執行緒可以用來提升應用程
式在接收使用者輸入時的反應能力。一個相關的用例是，運行 I/O 的同時，在另
一個執行緒中進行計算。

以下程式碼顯示了高階的 *note threading: 10b. 模組如何在背景運行任務，而
主程式同時繼續運行：

     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.')

多執行緒應用程式的主要挑戰是，要協調多個彼此共享資料或資源的執行緒。為此
，threading 模組提供了多個同步處理原始物件 (synchronization primitive)，
包括鎖 (lock)、事件 (event)、條件變數 (condition variable) 和號誌
(semaphore)。

儘管這些工具很強大，但很小的設計錯誤也可能導致一些難以重現的問題。所以，
任務協調的首選方法是，把所有對資源的存取集中到單一的執行緒中，然後使用
*note queue: da. 模組向該執行緒饋送來自其他執行緒的請求。應用程式若使用
*note Queue: dde. 物件進行執行緒間的通信和協調，會更易於設計、更易讀、更
可靠。


File: python.info,  Node: 日誌記錄 Logging,  Next: 弱引用 Weak References,  Prev: 多執行緒 Multi-threading,  Up: Python 標準函式庫概覽——第二部份

2.11.5 日誌記錄 (Logging)
-------------------------

*note logging: aa. 模組提供功能齊全且富彈性的日誌記錄系統。在最簡單的情
況下，日誌訊息會被發送到檔案或 ‘sys.stderr’：

     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')

這會產生以下輸出：

     WARNING:root:Warning:config file server.conf not found
     ERROR:root:Error occurred
     CRITICAL:root:Critical error -- shutting down

在預設情況，資訊和除錯訊息不會被顯示，其輸出會被發送到標準錯誤 (standard
error)。其他輸出選項包括，將訊息轉發到電子郵件、資料報 (datagram)、網路
插座 (socket) 或 HTTP 伺服器。新的過濾器可以根據訊息的優先順序，選擇不同
的路由 (routing) 方式：‘DEBUG’，‘INFO’，‘WARNING’，‘ERROR’，及
‘CRITICAL’。

日誌記錄系統可以直接從 Python 配置，也可以透過載入使用者可編輯的配置檔案
以進行客製化的日誌記錄，而無須對應用程式做出變更。


File: python.info,  Node: 弱引用 Weak References,  Next: 使用於 List 的工具,  Prev: 日誌記錄 Logging,  Up: Python 標準函式庫概覽——第二部份

2.11.6 弱引用 (Weak References)
-------------------------------

Python 會自動進行記憶體管理（對大多數物件進行參照計數 (reference
counting) 並使用 *note garbage collection: fc8. 來消除循環參照）。當一個
參照從記憶體被移除後不久，該記憶體就會被釋出。

此方式對大多數應用程式來說都沒問題，但偶爾也需要在物件仍然被其他物件所使
用時持續追蹤它們。可惜的是，儘管只是追蹤它們，也會建立一個使它們永久化
(permanent) 的參照。*note weakref: 131. 模組提供的工具可以不必建立參照就
能追蹤物件。當該物件不再被需要時，它會自動從一個弱引用表 (weakref table)
中被移除，並為弱引用物件觸發一個回呼 (callback)。典型的應用包括暫存
(cache) 那些成本較為昂貴的物件：

     >>> 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'


File: python.info,  Node: 使用於 List 的工具,  Next: 十進制 Decimal 浮點數運算,  Prev: 弱引用 Weak References,  Up: Python 標準函式庫概覽——第二部份

2.11.7 使用於 List 的工具
-------------------------

許多對於資料結構的需求，可以透過內建的 list（串列）型別來滿足。但是，有
時也會根據效能的各種取捨，需要一些替代的實作。

*note array: 6. 模組提供了一個 *note array(): 216. 物件，它像是 list，但
只能儲存同類的資料且能緊密地儲存。下面的範例展示一個數值陣列 (array)，以
兩個位元組的無符號二進數 (unsigned binary numbers) 為儲存單位（類型碼為
‘"H"’），而在 Python 整數物件的正規 list 中，每個項目通常使用 16 個位元
組：

     >>> from array import array
     >>> a = array('H', [4000, 10, 700, 22222])
     >>> sum(a)
     26932
     >>> a[1:3]
     array('H', [10, 700])

*note collections: 1d. 模組提供了一個 *note deque(): 62a. 物件，它像是
list，但從左側加入 (append) 和彈出 (pop) 的速度較快，而在中間查找的速度
則較慢。這種物件適用於實作佇列 (queue) 和廣度優先搜尋法 (breadth first
tree search)：

     >>> from collections import deque
     >>> d = deque(["task1", "task2", "task3"])
     >>> d.append("task4")
     >>> print("Handling", d.popleft())
     Handling task1

     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)

除了替代的 list 實作以外，函式庫也提供了其他工具，例如 *note bisect: 11.
模組，具有能夠操作 sorted list（已排序串列）的函式：

     >>> 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')]

*note heapq: 8d. 模組提供了一些函式，能基於正規 list 來實作堆積 (heap)。
最小值的項目會永遠保持在位置零。對於一些需要多次存取最小元素，但不想要對
整個 list 進行排序的應用程式來說，這會很有用：

     >>> 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]


File: python.info,  Node: 十進制 Decimal 浮點數運算,  Prev: 使用於 List 的工具,  Up: Python 標準函式庫概覽——第二部份

2.11.8 十進制 (Decimal) 浮點數運算
----------------------------------

*note decimal: 35. 模組提供了一個 *note Decimal: 2c0. 資料類型，用於十進
制浮點數運算。相較於內建的二進制浮點數 *note float: 1fd. 實作，該 class
特別適用於下列情境

   * 金融應用程式及其他需要準確十進位制表示法的應用，

   * 對於精確度 (precision) 的控制，

   * 控制四捨五入，以滿足法律或監管規範，

   * 追蹤有效的小數位數 (decimal place)，或

   * 使用者會期望計算結果與手工計算相符的應用程式。

例如，要計算 70 美分的手機充電加上 5％ 稅金的總價，使用十進制浮點數和二
進制浮點數，會算出不同的答案。如果把計算結果四捨五入到最接近的美分，兩者
的差異會更顯著：

     >>> from decimal import *
     >>> round(Decimal('0.70') * Decimal('1.05'), 2)
     Decimal('0.74')
     >>> round(.70 * 1.05, 2)
     0.73

*note Decimal: 2c0. 的運算結果會保留尾部的零，也會根據有兩個有效位數的被
乘數自動推斷出有四個有效位數的乘積。Decimal 可以重現手工計算的結果，以避
免產生二進制浮點數無法準確表示十進制數值時會導致的問題。

準確的表示法使得 *note Decimal: 2c0. class 能夠執行對於二進制浮點數不適
用的模數計算和相等性檢測：

     >>> 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

*note decimal: 35. 模組可提供運算中需要的足夠精確度：

     >>> getcontext().prec = 36
     >>> Decimal(1) / Decimal(7)
     Decimal('0.142857142857142857142857142857142857')


File: python.info,  Node: 虛擬環境與套件,  Next: 現在可以來學習些什麼？,  Prev: Python 標準函式庫概覽——第二部份,  Up: Python 教學

2.12 虛擬環境與套件
===================

* Menu:

* 簡介: 簡介<4>.
* 建立虛擬環境::
* 用 pip 管理套件::


File: python.info,  Node: 簡介<4>,  Next: 建立虛擬環境,  Up: 虛擬環境與套件

2.12.1 簡介
-----------

Python 應用程式通常會用到不在標準函式庫的套件和模組。應用程式有時候會需
要某個特定版本的函式庫，因為這個應用程式可能需要某個特殊的臭蟲修正，或是
這個應用程式是根據該函式庫特定版本的介面所撰寫。

這意味著不太可能安裝一套 Python 就可以滿足所有應用程式的要求。如果應用程
式 A 需要一個特定的模組的 1.0 版，但另外一個應用程式 B 需要 2.0 版，那麼
這整個需求不管安裝 1.0 或是 2.0 都會衝突，以致於應用程式無法使用。

解決方案是創建一個*note 虛擬環境 (virtual environment): 1446.，這是一個
獨立的資料夾，並且裡面裝好了特定版本的 Python，以及一系列相關的套件。

不同的應用程式可以使用不同的虛擬環境。以前述中需要被解決的例子中，應用程
式 A 能夠擁有它自己的虛擬環境，並且是裝好 1.0 版，然而應用程式 B 則可以
是用另外一個有 2.0 版的虛擬環境。要是應用程式 B 需要某個函式庫被升級到
3.0 版，這並不會影響到應用程式 A 的環境。


File: python.info,  Node: 建立虛擬環境,  Next: 用 pip 管理套件,  Prev: 簡介<4>,  Up: 虛擬環境與套件

2.12.2 建立虛擬環境
-------------------

用來建立與管理虛擬環境的模組叫做 *note venv: 12e.。*note venv: 12e. 通常
會安裝你能夠取得的最新版本的 Python。要是你的系統有不同版本的 Python，你
可以透過 ‘python3’ 這個指令選擇特定或是任意版本的 Python。

在建立虛擬環境的時候，在你決定要放該虛擬環境的資料夾之後，以腳本
(script) 執行 *note venv: 12e. 模組並且給定資料夾路徑：

     python3 -m venv tutorial-env

如果 ‘tutorial-env’ 不存在的話，這會建立 ‘tutorial-env’ 資料夾，並且也會
在裡面建立一個有 Python 直譯器的複本、標準函式庫、以及不同的支援檔案的資
料夾。

虛擬環境的常用資料夾位置是 ‘.venv’。這個名稱通常會使該資料夾在你的 shell
中保持隱藏，因此這樣命名既可以解釋資料夾存在的原因，也不會造成任何困擾。
它還能防止與某些工具所支援的 ‘.env’ 環境變數定義檔案發生衝突。

一旦你建立了一個虛擬環境，你可以啟動它。

在 Windows 系統中，使用：

     tutorial-env\Scripts\activate.bat

在 Unix 或 MacOS 系統，使用：

     source tutorial-env/bin/activate

（這段程式碼適用於 bash shell。如果你是用 ‘csh’ 或者 ‘fish’ shell，應當
使用替代的 ‘activate.csh’ 與 ‘activate.fish’ 腳本。）

啟動虛擬環境會改變你的 shell 提示字元來顯示你正在使用的虛擬環境，並且修
改環境以讓你在執行 ‘python’ 的時候可以得到特定的 Python 版本，例如：

     $ source ~/envs/tutorial-env/bin/activate
     (tutorial-env) $ python
     Python 3.5.1 (default, May  6 2016, 10:59:36)
       ...
     >>> import sys
     >>> sys.path
     ['', '/usr/local/lib/python35.zip', ...,
     '~/envs/tutorial-env/lib/python3.5/site-packages']
     >>>


File: python.info,  Node: 用 pip 管理套件,  Prev: 建立虛擬環境,  Up: 虛擬環境與套件

2.12.3 用 pip 管理套件
----------------------

你可以使用一個叫做 ‘pip’ 的程式來安裝、升級和移除套件。‘pip’ 預設會從
Python Package Index <‘https://pypi.org’> 安裝套件。你可以透過你的網頁瀏
覽器瀏覽 Python Package Index。

‘pip’ 有好幾個子指令："install"、"uninstall"、"freeze" 等等。（可以參考
*note 安裝 Python 模組: 8e2.指南，來取得 ‘pip’ 的完整說明文件。）

你可以透過指定套件名字來安裝最新版本的套件：

     (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

你也可以透過在套件名稱之後接上 ‘==’ 和版號來指定特定版本：

     (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

要是你重新執行此指令，‘pip’ 會知道該版本已經安裝過，然後什麼也不做。你可
以提供不同的版本號碼來取得該版本，或是可以執行 ‘pip install --upgrade’ 來
把套件升級到最新的版本：

     (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

‘pip uninstall’ 後面接一個或是多個套件名稱可以從虛擬環境中移除套件。

‘pip show’ 可以顯示一個特定套件的資訊：

     (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:

‘pip list’ 會顯示虛擬環境中所有已經安裝的套件：

     (tutorial-env) $ pip list
     novas (3.1.1.3)
     numpy (1.9.2)
     pip (7.0.3)
     requests (2.7.0)
     setuptools (16.0)

‘pip freeze’ 可以複製一整個已經安裝的套件清單，但是輸出使用 ‘pip
install’ 可以讀懂的格式。一個常見的慣例是放這整個清單到一個叫做
‘requirements.txt’ 的檔案：

     (tutorial-env) $ pip freeze > requirements.txt
     (tutorial-env) $ cat requirements.txt
     novas==3.1.1.3
     numpy==1.9.2
     requests==2.7.0

‘requirements.txt’ 可以提交到版本控制，並且作為釋出應用程式的一部分。使
用者可以透過 ‘install -r’ 安裝對應的的套件：

     (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

‘pip’ 還有更多功能。可以參考*note 安裝 Python 模組: 8e2.指南，來取得完整
的 ‘pip’ 說明文件。當你撰寫了一個套件並且想要讓它在 Python Package Index
上可以取得的話，可以參考*note 發布 Python 模組: 8e3.指南。


File: python.info,  Node: 現在可以來學習些什麼？,  Next: 互動式輸入編輯和歷史記錄替換,  Prev: 虛擬環境與套件,  Up: Python 教學

2.13 現在可以來學習些什麼？
===========================

閱讀本教學可能增強您對於使用 Python 的興趣——您應該非常渴望使用 Python 來
解決在現實生活中所遭遇的問題。該從哪裡學習更多呢？

本教學是 Python 文件中的一部分。這份文件集裡頭的其他文件包含：

   * *note Python 標準函式庫 (Standard Library): 1330.：

     你該好好的瀏覽這份手冊，它提供了完整（但簡潔）的參考素材像是型別、
     函式與標準函式庫裡的模組。標準的 Python 發行版本會包含`大量'的附加
     程式碼。有些模組可以讀取 Unix 信箱、通過 HTTP 來檢索文件、產生亂數
     、分析命令列選項、編寫 CGI 程式、壓縮資料、及許多其他任務。瀏覽函式
     庫參考手冊可以讓你了解有哪些模組可以用。

   * *note 安裝 Python 模組: 8e2.：說明與解釋如何安裝其他 Python 使用者
     所編寫的模組。

   * *note Python 語言參考手冊: 1331.：Python 語法以及語意的詳細說明。這
     份文件閱讀起來會有些吃力，但作為一個語言本身的完整指南是非常有用的
     。

更多 Python 的資源：

   * ‘https://www.python.org’：Python 的主要網站。它包含程式碼、文件以及
     連結到 Python 相關聯的網頁。網站為鏡像的並設置於世界各地，像是歐洲
     、日本以及澳大利亞；鏡像網站也許會比主網站來得更快，不過具體速度則
     還是取決於你所在的地理位置。

   * ‘https://docs.python.org’：快速訪問 Python 的文件。

   * ‘https://pypi.org’：Python 套件索引 (Python Package Index)，之前也
     被暱稱為 Cheese Shop (1)，彙總了使用者開發 Python 模組的索引，並提
     供模組能夠被下載。一旦開始發佈相關程式碼，你可以將開發的作品註冊到
     這裡並且讓其他人找到。

   * ‘https://code.activestate.com/recipes/langs/python/’：Python
     Cookbook 是一個相當大的程式碼集，包含程式碼範例、較大的模組以及有用
     的腳本。特別值得注意的貢獻則被收集在一本名為 Python Cookbook
     (O’Reilly & Associates, ISBN 0-596-00797-3.) 的書籍中。

   * ‘http://www.pyvideo.org’ 從研討會與使用者群組聚會裡收集與 Python 相
     關的影片連結。

   * ‘https://scipy.org’：The Scientific Python 專案是一個包含用於高速陣
     列運算與操作的模組，以及用於如線性代數、傅利葉變換、非線性求解器、
     隨機數分佈、統計分析等一系列的套件。

對於 Python 相關的疑問與問題回報，您可以張貼到新聞群組
‘comp.lang.python’，或將它們寄至 <python-list@python.org> 的郵寄清單
(mailing list)。新聞群組和郵寄清單是個閘道，因此張貼到其中的郵件都將自動
轉發給另一個。每天會有數以百計的內容，詢問（和回答）問題、建議新功能與發
佈新的模組。郵寄清單會存檔在 ‘https://mail.python.org/pipermail/’。

在張貼之前，請先確認問題是否在*note 常見問題: 144c.（也被稱為 FAQ）這個
清單內。FAQ 會回答出現很多次的問題及解答，有很多問題甚至已經包含解決問題
的方法。

註解
....

   ---------- Footnotes ----------

   (1) (1) 「Cheese Shop（起司店）」是 Monty Python 的一個短劇：一位顧客
進入一家起司店，但無論他要哪種起司，店員都說沒有貨。


File: python.info,  Node: 互動式輸入編輯和歷史記錄替換,  Next: 浮點數運算：問題與限制,  Prev: 現在可以來學習些什麼？,  Up: Python 教學

2.14 互動式輸入編輯和歷史記錄替換
=================================

有些版本的 Python 直譯器支援當前輸入內容的編輯和歷史記錄的替換 (history
substitution)，類似在 Korn shell 和 GNU Bash shell 中的功能。這個功能是
用 GNU Readline(1) 函式庫來實作，它支援多種編輯的風格。這個函式庫有它自
己的說明文件，在這裡我們就不重複了。

* Menu:

* Tab 鍵自動完成 (Tab Completion) 和歷史記錄編輯 (History Editing): Tab 鍵自動完成 Tab Completion 和歷史記錄編輯 History Editing.
* 互動式直譯器的替代方案::

   ---------- Footnotes ----------

   (1) https://tiswww.case.edu/php/chet/readline/rltop.html


File: python.info,  Node: Tab 鍵自動完成 Tab Completion 和歷史記錄編輯 History Editing,  Next: 互動式直譯器的替代方案,  Up: 互動式輸入編輯和歷史記錄替換

2.14.1 Tab 鍵自動完成 (Tab Completion) 和歷史記錄編輯 (History Editing)
-----------------------------------------------------------------------

在直譯器啟動的時候，變數和模組名稱的自動完成功能會被*note 自動啟用:
9cc.，所以可以用 ‘Tab’ 鍵來呼叫自動完成函式；它會查看 Python 的陳述式名
稱、當前區域變數名稱和可用模組名稱。對於像是 ‘string.a’ 的點分隔運算式
(dotted expression)，它會對最後一個 ‘'.'’ 之前的運算式求值，然後根據求值
結果物件的屬性，給予自動完成的建議。請注意，如果一個物件有 *note
__getattr__(): 42a. method（方法），同時又是該運算式的一部份，這樣可能會
執行應用程式自定義的程式碼。預設設定也會把你的指令歷史記錄儲存在你的使用
者資料夾內，一個名為 ‘.python_history’ 的檔案中。在下一次啟動互動式直譯
器時，這些歷史記錄依然可以被使用。


File: python.info,  Node: 互動式直譯器的替代方案,  Prev: Tab 鍵自動完成 Tab Completion 和歷史記錄編輯 History Editing,  Up: 互動式輸入編輯和歷史記錄替換

2.14.2 互動式直譯器的替代方案
-----------------------------

與早期版本的直譯器相比，上述功能的出現的確是一個巨大的進步；但還是有一些
願望沒有被實現：如果能在每次換行時給予適當的縮排建議（剖析器 (parser) 知
道下一行是否需要縮排標記 (indent token)），那就更棒了。自動完成機制可能
會使用直譯器的符號表。若有一個命令能夠檢查（或甚至建議）括號、引號和其他
符號的匹配，那也會很有用。

有一個功能增強的互動式直譯器替代方案，已經存在一段時間，稱為 IPython(1)，
它具有 Tab 鍵自動完成、物件探索和進階歷史記錄管理等特色。它也可以完全客
製化並被嵌入到其他應用程式中。另一個類似的增強型互動式環境，稱為
bpython(2)。

   ---------- Footnotes ----------

   (1) https://ipython.org/

   (2) https://www.bpython-interpreter.org/


File: python.info,  Node: 浮點數運算：問題與限制,  Next: 附錄,  Prev: 互動式輸入編輯和歷史記錄替換,  Up: Python 教學

2.15 浮點數運算：問題與限制
===========================

在計算機架構中，浮點數 (floating-point number) 是以基數為 2（二進位）的
小數表示。例如說，在十進位小數中：

     0.125

可被分為 1/10 + 2/100 + 5/1000，同樣的道理，二進位小數：

     0.001

可被分為 0/2 + 0/4 + 1/8。這兩個小數有相同的數值，而唯一真正的不同在於前
者以十進位表示，後者以二進位表示。

不幸的是，大多數十進位小數無法精準地以二進位小數表示。一般的結果為，你輸
入的十進位浮點數只能由實際儲存在計算機中的二進位浮點數近似。

在十進位中，這個問題更容易被理解。以分數 1/3 為例，你可以將其近似為十進
位小數：

     0.3

或者，更好的近似：

     0.33

或者，更好的近似：

     0.333

依此類推，不論你使用多少位數表示小數，最後的結果都無法精準地表示 1/3，但
你還是能越來越精準地表示 1/3。

同樣的道理，不論你願意以多少位數表示二進位小數，十進位小數 0.1 都無法被
二進位小數精準地表達。在二進位小數中，1/10 會是一個無限循環小數：

     0.0001100110011001100110011001100110011001100110011...

只要你停在任何有限的位數，你就只會得到近似值。而現在大多數的計算機中，浮
點數是透過二進位分數近似的，其中分子是從最高有效位元開始，用 53 個位元表
示，分母則是以二為底的指數。在 1/10 的例子中，二進位分數為
‘3602879701896397 / 2 ** 55’，而這樣的表示十分地接近，但不完全等同於
1/10 的真正數值。

由於數值顯示的方式，很多使用者並沒有發現數值是個近似值。Python 只會印出
一個十進位近似值，其近似了儲存在計算機中的二進位近似值的真正十進位數值。
在大多數的計算機中，如果 Python 真的會印出完整的十進位數值，其表示儲存在
計算機中的 0.1 的二進位近似值，它將顯示為：

     >>> 0.1
     0.1000000000000000055511151231257827021181583404541015625

這比一般人感到有用的位數還多，所以 Python 將位數保持在可以接受的範圍，只
顯示捨入後的數值：

     >>> 1 / 10
     0.1

一定要記住，雖然印出的數字看起來是精準的 1/10，但真正儲存的數值是能表示
的二進位分數中，最接近精準數值的數。

有趣的是，有許多不同的十進位數，共用同一個最接近的二進位近似分數。例如說
：數字 ‘0.1’ 和 ‘0.10000000000000001’ 和
‘0.1000000000000000055511151231257827021181583404541015625’，都由
‘3602879701896397 / 2 ** 55’ 近似。由於這三個十進位數值共用同一個近似值
，任何一個數值都可以被顯示，同時保持 ‘eval(repr(x)) == x’。

歷史上，Python 的提示字元 (prompt) 與內建的 *note repr(): 8b9. 函式會選
擇上段說明中有 17 個有效位元的數：‘0.10000000000000001’。從 Python 3.1 版
開始，Python（在大部分的系統上）現在能選擇其中最短的數並簡單地顯示為
‘0.1’。

注意，這是二進位浮點數理所當然的特性，並不是 Python 的錯誤 (bug)，更不是
你程式碼的錯誤。只要程式語言有支援硬體的浮點數運算，你將會看到同樣的事情
出現在其中（雖然有些程式語言預設不會`顯示'該差異，有些甚至是在所有的輸出
模式中都不會顯示。）

為求更優雅的輸出，你可能想要使用字串的格式化 (string formatting) 產生限
定的有效位數：

     >>> 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'

要了解一件很重要的事，在真正意義上，浮點數的表示是一種幻覺：你基本上在捨
入真正機器數值所`展示的值'。

這種幻覺可能會產生下一個幻覺。舉例來說，因為 0.1 不是真正的 1/10，把三個
0.1 的值相加，也不會產生精準的 0.3：

     >>> .1 + .1 + .1 == .3
     False

同時，因為 0.1 不能再更接近精準的 1/10，還有 0.3 不能再更接近精準的
3/10，預先用 *note round(): d35. 函式捨入並不會有幫助：

     >>> round(.1, 1) + round(.1, 1) + round(.1, 1) == round(.3, 1)
     False

雖然數字不會再更接近他們的精準數值，但 *note round(): d35. 函式可以對事
後的捨入有所幫助，如此一來，不精確的數值就變得可以互相比較：

     >>> round(.1 + .1 + .1, 10) == round(.3, 10)
     True

Binary floating-point arithmetic holds many surprises like this.  The
problem with "0.1" is explained in precise detail below, in the
"Representation Error" section.  See The Perils of Floating Point(1) for
a more complete account of other common surprises.

如同上文的末段所述，「這個問題並沒有簡單的答案。」不過，也不必對浮點過度
擔心！Python 的 float（浮點數）運算中的誤差，是從浮點硬體繼承而來，而在
大多數的計算機上，每次運算的誤差範圍不會大於 2**53 分之 1。這對大多數的
任務來說已經相當足夠，但你需要記住，它並非十進位運算，且每一次 float 運
算都可能會承受新的捨入誤差。

雖然浮點運算確實存在一些問題，但在一般情況下，如果你只是把最終結果的顯示
值，以十進位方式捨入至預期的位數，那麼仍會得到你預期的結果。*note str():
205. 通常就能滿足要求，而若想要更細緻的控制，可參閱*note 格式字符串语法:
de0.中關於 *note str.format(): 5d4. method（方法）的格式規範。

對於需要精準十進位表示法的用例，可以試著用 *note decimal: 35. 模組，它可
實作適用於會計應用程式與高精確度應用程式的十進位運算。

另一種支援精準運算的格式為 *note fractions: 81. 模組，該模組基於有理數來
實作運算（因此可以精確表示像 1/3 這樣的數字）。

如果你是浮點運算的重度使用者，你應該看一下 NumPy 套件，以及由 SciPy 專案
提供的許多用於數學和統計學運算的其他套件。請參閱 <‘https://scipy.org’>。

在罕見情況下，當你`真的'想知道一個 float 的精準值，Python 提供的工具可協
助達成。*note float.as_integer_ratio(): 1457. method 可將一個 float 的值
表示為分數：

     >>> x = 3.14159
     >>> x.as_integer_ratio()
     (3537115888337719, 1125899906842624)

由於該比率是精準的，它可無損地再現該原始值：

     >>> x == 3537115888337719 / 1125899906842624
     True

*note float.hex(): 1458. method 以十六進位（基數為 16）表示 float，一樣
可以給出你的電腦所儲存的精準值：

     >>> x.hex()
     '0x1.921f9f01b866ep+1'

這種精確的十六進位表示法可用於精準地重建 float 值：

     >>> x == float.fromhex('0x1.921f9f01b866ep+1')
     True

由於該表示法是精準的，因此適用於在不同版本的 Python 之間可靠地傳送數值（
獨立於系統平台），並與支援相同格式的其他語言（如 JAVA 和 C99）交換資料。

另一個有用的工具是 *note math.fsum(): e04. 函式，能在計算總和時幫忙減少
精確度的損失。當數值被加到運行中的總計值時，它會追蹤「失去的位數 (lost
digits)」。這可以明顯改善總體準確度 (overall accuracy)，使得誤差不至於累
積到影響最終總計值的程度：

     >>> sum([0.1] * 10) == 1.0
     False
     >>> math.fsum([0.1] * 10) == 1.0
     True

* Menu:

* 表示法誤差 (Representation Error): 表示法誤差 Representation Error.

   ---------- Footnotes ----------

   (1) https://www.lahey.com/float.htm


File: python.info,  Node: 表示法誤差 Representation Error,  Up: 浮點數運算：問題與限制

2.15.1 表示法誤差 (Representation Error)
----------------------------------------

本節將會詳細解釋「0.1」的例子，並說明你自己要如何對類似案例執行精準的分
析。 以下假設你對二進位浮點表示法已有基本程度的熟悉。

`Representation error'（表示法誤差）是指在真實情況中，有些（實際上是大多
數）十進位小數並不能精準地以二進位（基數為 2）小數表示。這是 Python（或
Perl、C、C++、JAVA、Fortran 和其他許多）通常不會顯示你期望的精準十進位數
字的主要原因。

為什麼呢？因為 1/10 無法精準地以一個二進位小數來表示。至今（2000 年 11 月
）幾乎所有的計算機皆使用 IEEE-754 浮點數運算標準，並且幾乎所有的平台都以
IEEE-754 標準中的「雙精度 (double precision)」來繪製 Python 的 float。
754 double 包含 53 位元的精度，所以在輸入時，電腦會努力把 0.1 轉換到最接
近的分數，以 `J'/2**`N' 的形式表示，此處 `J' 是一個正好包含 53 位元的整
數。可以將：

     1 / 10 ~= J / (2**N)

重寫為：

     J ~= 2**N / 10

而前面提到 `J' 有精準的 53 位元（即 ‘>= 2**52’ 但 ‘< 2**53’），所以 `N'
的最佳數值是 56：

     >>> 2**52 <=  2**56 // 10  < 2**53
     True

意即，要使 `J' 正好有 53 位元，則 56 會是 `N' 的唯一值。而 `J' 最有可能
的數值就是經過捨入後的該商數：

     >>> q, r = divmod(2**56, 10)
     >>> r
     6

由於餘數超過 10 的一半，所以最佳的近似值是透過進位而得：

     >>> q+1
     7205759403792794

所以，在 754 雙精度下，1/10 的最佳近似值是：

     7205759403792794 / 2 ** 56

將分子和分母同除以二，會約分為：

     3602879701896397 / 2 ** 55

請注意，由於我們有進位，所以這實際上比 1/10 大了一點；如果我們沒有進位，
商數將會有點小於 1/10。但在任何情況下都不可能是`精準的' 1/10！

所以電腦從來沒有「看到」1/10：它看到的是上述的精準分數，也就是它能得到的
754 double 最佳近似值：

     >>> 0.1 * 2 ** 55
     3602879701896397.0

如果將該分數乘以 10**55，則可以看到該值以 55 個十進位數字顯示：

     >>> 3602879701896397 * 10 ** 55 // 2 ** 55
     1000000000000000055511151231257827021181583404541015625

這表示儲存在電腦中的精準數值等於十進位值
0.1000000000000000055511151231257827021181583404541015625。與其顯示完整
的十進位數值，許多語言（包括 Python 的舊版本）選擇將結果捨入至 17 個有效
位數：

     >>> format(0.1, '.17f')
     '0.10000000000000001'

*note fractions: 81. 與 *note decimal: 35. 模組能使這些計算變得容易：

     >>> 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'


File: python.info,  Node: 附錄,  Prev: 浮點數運算：問題與限制,  Up: Python 教學

2.16 附錄
=========

* Menu:

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


File: python.info,  Node: 互動模式<2>,  Up: 附錄

2.16.1 互動模式
---------------

* Menu:

* 錯誤處理::
* 可執行的 Python 腳本::
* 互動式啟動檔案::
* 客製化模組::


File: python.info,  Node: 錯誤處理,  Next: 可執行的 Python 腳本,  Up: 互動模式<2>

2.16.1.1 錯誤處理
.................

當一個錯誤發生時，直譯器會印出一個錯誤訊息和堆疊回溯。在互動模式下，它將
返回主提示字元；當輸入來自檔案時，它在印出堆疊回溯後以非零退出狀態退出。
(由 *note except: c10. 子句在 *note try: e37. 陳述式中處理的例外在這種情
況下不是錯誤。) 有些錯誤是無條件嚴重的，會導致非零退出；這適用於內部不一
致和一些記憶體耗盡的情況。所有的錯誤訊息都被寫入標準錯誤輸出；被執行指令
的正常輸出被寫入標準輸出。

向主提示字元或次提示字元輸入中斷字元（通常是 ‘Control-C’ 或 ‘Delete’ ）
會取消輸入並返回到主提示字元。 (1) 在指令執行過程中輸入一個中斷，會引發
*note KeyboardInterrupt: 2cc. 例外，但可以通過 *note try: e37. 陳述式來
處理。

   ---------- Footnotes ----------

   (1) (1) GNU Readline 套件的一個問題可能會阻止這一點。


File: python.info,  Node: 可執行的 Python 腳本,  Next: 互動式啟動檔案,  Prev: 錯誤處理,  Up: 互動模式<2>

2.16.1.2 可執行的 Python 腳本
.............................

在類 BSD 的 Unix 系統上，Python 腳本可以直接執行，就像 shell 腳本一樣，
通過放置以下這行：

     #!/usr/bin/env python3.5

（假設直譯器在用戶的 ‘PATH’ 上）在腳本的開頭並給檔案一個可執行模式。
‘#!’ 必須是檔案的前兩個字元。 在某些平台上，第一行必須以 Unix 樣式的換行
(‘’\n’’) 結尾，而不是 Windows (‘’\r\n’’) 換行。 請注意，井號 ‘'#'’ 用於
在 Python 中開始註解。

可以使用 ‘chmod’ 指令為腳本賦予可執行模式或權限。

     $ chmod +x myscript.py

在 Windows 系統上，沒有「可執行模式」的概念。 Python 安裝程式會自動將
‘.py’ 檔案與 ‘python.exe’ 聯繫起來，這樣雙擊 Python 檔案就會作為腳本運行
。副檔名也可以是 ‘.pyw’，在這種情況下，通常會出現的控制台視窗會被隱藏。


File: python.info,  Node: 互動式啟動檔案,  Next: 客製化模組,  Prev: 可執行的 Python 腳本,  Up: 互動模式<2>

2.16.1.3 互動式啟動檔案
.......................

當你互動式地使用 Python 時，每次啟動直譯器時執行一些標準指令是非常方便的
。你可以通過設置一個名為 *note PYTHONSTARTUP: 9cb. 的環境變數來實現，該
變數是一個包含啟動指令的檔案名。它的功能類似 Unix shell 的 ‘.profile’ 。

這個檔案只在互動模式中被讀取，當 Python 從腳本中讀取指令時，此檔案不會被
讀取，當 :file: ‘/dev/tty’ 作為指令的明確來源時也不會（否則表現得像互動
模式）。它在執行互動式指令的同一命名空間中執行，因此它所定義或 import 的
物件可以在互動模式中不加限定地使用。你也可以在這個檔案中改變 ‘sys.ps1’ 和
‘sys.ps2’ 等提示字元。

如果你想從當前目錄中讀取一個額外的啟動檔案，你可以在全域啟動檔案中使用類
似 ‘if os.path.isfile(‘.pythonrc.py’): exec(open(‘.pythonrc.py
‘).read()’ 的程式碼設定這個行為。如果你想在一個腳本中使用啟動檔案，你必
須在腳本中明確地這樣做：

     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)


File: python.info,  Node: 客製化模組,  Prev: 互動式啟動檔案,  Up: 互動模式<2>

2.16.1.4 客製化模組
...................

Python 提供了兩個鉤子（hook）讓你可以將它客製化： ‘sitecustomize’ 和
‘usercustomize’ 。要看它是如何運作的，你首先需要找到你的 site-packages 的
位置。啟動 Python 並運行這段程式碼：

     >>> import site
     >>> site.getusersitepackages()
     '/home/user/.local/lib/python3.5/site-packages'

現在，您可以在該目錄中創建一個名為 ‘usercustomize.py’ 的檔案，並將您想要
的任何內容放入其中。它會影響 Python 的每次呼叫，除非它以 *note -s: ddb.
選項啟動以禁用自動 import 。

‘sitecustomize’ 的運作方式相同，但通常是由電腦的管理員在全域
site-packages 目錄下創建，並在 ‘usercustomize’ 之前 import 。更多細節請
參閱 *note site: eb. 模組的文件。

註解
....


File: python.info,  Node: Python 的設置與使用,  Next: Python 語言參考手冊,  Prev: Python 教學,  Up: Top

3 Python 的設置與使用
*********************

這部分的說明文件是關於在不同平台上設定 Python 環境的綜合資訊、直譯器的呼
叫，以及讓 Python 更容易使用的一些方法。

* Menu:

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


File: python.info,  Node: 命令行与环境,  Next: 在Unix平台中使用Python,  Up: Python 的設置與使用

3.1 命令行与环境
================

为获取各种设置信息，CPython 解析器会扫描命令行与环境。

`CPython implementation detail:' 其他实现的命令行方案可能会有所不同。 详
见 *note 其他实现: 146b.。

* Menu:

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


File: python.info,  Node: 命令行,  Next: 环境变量,  Up: 命令行与环境

3.1.1 命令行
------------

调用 Python 时，可以指定下列任意选项：

     python [-bBdEhiIOqsSuvVWx?] [-c command | -m module-name | script | - ] [args]

最常见的用例是启动时执行脚本：

     python myscript.py

* Menu:

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


File: python.info,  Node: 接口选项,  Next: 通用选项,  Up: 命令行

3.1.1.1 接口选项
................

解释器接口类似于 UNIX shell，但提供了额外的调用方法:

   * 用连接到 tty 设备的标准输入调用时，会提示输入并执行命令，输入 EOF （
     文件结束符，UNIX 中按 ‘Ctrl-D’，Windows 中按 ‘Ctrl-Z, Enter’）时终
     止。

   * 用文件名参数或以标准输入文件调用时，读取，并执行该脚本文件。

   * 用目录名参数调用时，从该目录读取、执行适当名称的脚本。

   * 用 ‘-c command’ 调用时，执行 `command' 表示的 Python 语句。
     `command' 可以包含用换行符分隔的多条语句。注意，前导空白字符在
     Python 语句中非常重要！

   * 用 ‘-m module-name’ 调用时，在 Python 模块路径中查找指定的模块，并
     将其作为脚本执行。

非交互模式下，先解析全部输入，再执行。

接口选项会终结解释器读入的选项列表，所有后续参数都在 *note sys.argv:
cc6. 里 – 注意，首个元素，即下标为零的元素（‘sys.argv[0]’）是表示程序来
源的字符串。

 -- 程式選項: -c <command>

     执行 `command' 中的 Python 代码。`command' 可以是一条语句，也可以是
     用换行符分隔的多条语句，其中，前导空白字符与普通模块代码中的作用一
     样。

     使用此选项时，*note sys.argv: cc6. 的首个元素为 ‘"-c"’，并会把当前
     目录加入至 *note sys.path: 261. 开头（让该目录中的模块作为顶层模块
     导入）。

     使用 ‘command’ 参数会引发 *note 审计事件: fa1.
     ‘cpython.run_command’ 。

 -- 程式選項: -m <module-name>

     在 *note sys.path: 261. 中搜索指定模块，并以 *note __main__: 1. 模
     块执行其内容。

     该参数是 `模块名'，请勿输入文件扩展名（‘.py’）。模块名应为有效的绝
     对 Python 模块名，但本实现对此不作强制要求（例如，允许使用含连字符
     ‘-’ 的名称）。

     包名称（包括命名空间包）也允许使用。使用包名称而不是普通模块名时，
     解释器把 ‘<pkg>.__main__’ 作为主模块执行。此行为特意被设计为与作为
     脚本参数传递给解释器的目录和 zip 文件的处理方式类似。

          備註: 此选项不适用于内置模块和以 C 编写的扩展模块，因为它们并
          没有对应的 Python 模块文件。 但是它仍然适用于预编译的模块，即
          使没有可用的初始源文件。

     如果给出此选项，*note sys.argv: cc6. 的首个元素将为模块文件的完整路
     径 (在定位模块文件期间，首个元素将设为 ‘"-m"’)。 与 *note -c: 1340.
     选项一样，当前目录将被加入 *note sys.path: 261. 的开头。

     *note -I: 231. 选项可用来在隔离模式下运行脚本，此模式中 *note
     sys.path: 261. 既不包含当前目录也不包含用户的 site-packages 目录。
     所有 ‘PYTHON*’ 环境变量也会被忽略。

     许多标准库模块都包含在执行时，以脚本方式调用的代码。例如 *note
     timeit: 10d. 模块：

          python -m timeit -s 'setup here' 'benchmarked code here'
          python -m timeit -h # for details

     使用 ‘module-name’ 参数会引发 *note 审计事件: fa1.
     ‘cpython.run_module’ 。

     也參考
     ......

     *note runpy.run_module(): 146f.

          Python 代码可以直接使用的等效功能

     PEP 338(1) – 将模块作为脚本执行

     3.1 版更變: 提供包名称来运行 ‘__main__’ 子模块。

     3.4 版更變: 同样支持命名空间包

 -- Describe: -

     从标准输入 (*note sys.stdin: 41e.) 读取命令。标准输入为终端时，使用
     *note -i: ee1.。

     使用此选项时，*note sys.argv: cc6. 的第一个元素是 ‘"-"’， 同时，把
     当前目录加入 *note sys.path: 261. 开头。

     没有参数时，会触发 *note 审计事件: fa1. ‘cpython.run_stdin’ 。

 -- Describe: <script>

     执行 `script' 中的 Python 代码，该参数应为（绝对或相对）文件系统路
     径，指向 Python 文件、包含 ‘__main__.py’ 文件的目录，或包含
     ‘__main__.py’ 文件的 zip 文件。

     给出此选项时，*note sys.argv: cc6. 的第一个元素就是在命令行中指定的
     脚本名称。

     如果脚本名称直接指向 Python 文件，则把该文件所在目录加入 *note
     sys.path: 261. 的开头，并且把该文件当作 *note __main__: 1. 模块来执
     行。

     如果脚本名称指向目录或 zip 文件，则把脚本名加入 *note sys.path:
     261. 的开头，并把该位置中的 ‘__main__.py’ 文件当作 *note __main__:
     1. 模块来执行。

     *note -I: 231. 选项以隔离模式运行脚本，此模式中，*note sys.path:
     261. 既不包含脚本目录，也不包含用户的 site-packages 目录，还会忽略
     所有 ‘PYTHON*’ 环境变量。

     使用 ‘filename’ 参数会引发 *note 审计事件: fa1. ‘cpython.run_file’
     。

     也參考
     ......

     *note runpy.run_path(): d79.

          Python 代码可以直接使用的等效功能

未给出接口选项时，使用 *note -i: ee1.，‘sys.argv[0]’ 为空字符串 (‘""’)，
并把当前目录加至 *note sys.path: 261. 的开头。 此外，如果系统支持，还能
自动启用 tab 补全和历史编辑（参见 *note Readline 配置: 9cc.）。

也參考
......

*note 啟動直譯器: 133c.

3.4 版更變: 自动启用 tab 补全和历史编辑。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0338


File: python.info,  Node: 通用选项,  Next: 其他选项,  Prev: 接口选项,  Up: 命令行

3.1.1.2 通用选项
................

 -- 程式選項: -?
 -- 程式選項: -h
 -- 程式選項: --help

     输出所有命令行选项的简介。

 -- 程式選項: -V
 -- 程式選項: --version

     输出 Python 版本号并退出。示例如下：

          Python 3.8.0b2+

     输入两次 ‘V’ 选项时，输出更多构建信息，例如：

          Python 3.8.0b2+ (3.8:0c076caaa8, Apr 20 2019, 21:55:00)
          [GCC 6.2.0 20161005]

     3.6 版新加入: ‘-VV’ 选项。


File: python.info,  Node: 其他选项,  Next: 不应当使用的选项,  Prev: 通用选项,  Up: 命令行

3.1.1.3 其他选项
................

 -- 程式選項: -b

     用 *note str: 205. 与 *note bytes: 172. 或 *note bytearray: 173. 对
     比， 或对比 *note bytes: 172. 与 *note int: 204. 时，会发出警告。重
     复给出该选项（‘-bb’）时会报错。

     3.5 版更變: 影响 *note bytes: 172. 与 *note int: 204. 的比较。

 -- 程式選項: -B

     给出此选项时，Python 不在导入源模块时写入 ‘.pyc’ 文件。另请参阅
     *note PYTHONDONTWRITEBYTECODE: dff.。

 -- 程式選項: --check-hash-based-pycs default|always|never

     控制基于哈希值的 ‘.pyc’ 文件的验证行为。 参见 *note
     已缓存字节码的失效: 439.。 当设为 ‘default’ 时，已选定和未选定的基
     于哈希值的字节码缓存文件将根据其默认语义进行验证。 当设为 ‘always’
     时，所有基于哈希值的 ‘.pyc’ 文件，不论是已选定还是未选定的都将根据
     其对应的源文件进行验证。 当设为 ‘never’ 时，基于哈希值的 ‘.pyc’ 文
     件将不会根据其对应的源文件进行验证。

     基于时间戳的 ‘.pyc’ 文件的语义不会受此选项影响。

 -- 程式選項: -d

     开启解析器调试输出（限专家使用，依赖于编译选项）。 另请参阅 *note
     PYTHONDEBUG: 1477.。

 -- 程式選項: -E

     忽略所有 ‘PYTHON*’ 环境变量，例如，已设置的 *note PYTHONPATH: a34.
     和 *note PYTHONHOME: 5d0.。

 -- 程式選項: -i

     脚本是第一个参数，或使用 *note -c: 1340. 时，即便 *note sys.stdin:
     41e. 不是终端，执行脚本或命令后，也会进入交互模式。不读取 *note
     PYTHONSTARTUP: 9cb. 文件。

     本选项用于，脚本触发异常时，检查全局变量或堆栈回溯。 详见 *note
     PYTHONINSPECT: ee0.。

 -- 程式選項: -I

     在隔离模式下运行 Python。 这将同时应用 -E 和 -s。 在隔离模式下
     *note sys.path: 261. 既不包含脚本所在目录也不包含用户的
     site-packages 目录。 所有 ‘PYTHON*’ 环境变量也会被忽略。 还可以施加
     更进一步的限制以防止用户注入恶意代码。

     3.4 版新加入.

 -- 程式選項: -O

     移除 assert 语句以及任何以 *note __debug__: 1137. 的值作为条件的代
     码。 通过在 ‘.pyc’ 扩展名之前添加 ‘.opt-1’ 来扩充已编译文件 (*note
     bytecode: 709.) 的文件名 (参见 PEP 488(1))。 另请参阅 *note
     PYTHONOPTIMIZE: 1478.。

     3.5 版更變: 依据 PEP 488(2) 修改 ‘.pyc’ 文件名。

 -- 程式選項: -OO

     在启用 *note -O: 77e. 的同时丢弃文档字符串。 通过在 ‘.pyc’ 扩展名之
     前添加 ‘.opt-2’ 来扩展已编译文件 (*note bytecode: 709.) 的文件名 (参
     见 PEP 488(3))。

     3.5 版更變: 依据 PEP 488(4) 修改 ‘.pyc’ 文件名。

 -- 程式選項: -q

     即使在交互模式下也不显示版权和版本信息。

     3.2 版新加入.

 -- 程式選項: -R

     开启哈希随机化。 此选项权 *note PYTHONHASHSEED: aa4. 环境变量设置为
     ‘0’ 时起作用，因为哈希随机化是默认启用的。

     在Python的早期版本中，此选项启用哈希随机化，将 str 和 bytes 的对象
     *note __hash__(): 44c. 的值 "加盐" 为不可预测的随机值。虽然它们在单
     个Python进程中保持不变，但是在重复调用的Python进程之间它们是不可预
     测的。

     Hash randomization is intended to provide protection against a
     denial-of-service caused by carefully-chosen inputs that exploit
     the worst case performance of a dict construction, O(n^2)
     complexity.  See
     ‘http://www.ocert.org/advisories/ocert-2011-003.html’ for details.

     *note PYTHONHASHSEED: aa4. 允许你为哈希种子密码设置一个固定值。

     3.7 版更變: 此选项不会再被忽略。

     3.2.3 版新加入.

 -- 程式選項: -s

     不要将 *note 用户 site-packages 目录: 147a. 添加到 *note sys.path:
     261.。

     也參考
     ......

     PEP 370(5) – 分用户的 site-packages 目录

 -- 程式選項: -S

     禁用 *note site: eb. 的导入及其所附带的基于站点对 *note sys.path:
     261. 的操作。 如果 *note site: eb. 会在稍后被显式地导入也会禁用这些
     操作 (如果你希望触发它们则应调用 *note site.main(): 147b.)。

 -- 程式選項: -u

     强制 stdout 和 stderr 流不使用缓冲。 此选项对 stdin 流无影响。

     另请参阅 *note PYTHONUNBUFFERED: 109e.。

     3.7 版更變: stdout 和 stderr 流在文本层现在不使用缓冲。

 -- 程式選項: -v

     每当一个模块被初始化时打印一条信息，显示其加载位置（文件名或内置模
     块）。 当重复给出时 (‘-vv’)，为搜索模块时所检查的每个文件都打印一条
     消息。 此外还提供退出时有关模块清理的信息A。 另请参阅 *note
     PYTHONVERBOSE: 147c.。
 -- 程式選項: -W arg

     警告控制。 Python 的警告机制在默认情况下会向 *note sys.stderr: 1ea.
     打印警告消息。 典型的警告消息具有如下形式：

          file:line: category: message

     默认情况下，每个警告都对于其发生所在的每个源行都会打印一次。 此选项
     可控制警告打印的频繁程度。

     可以给出多个 *note -W: 15b. 选项；当某个警告能与多个选项匹配时，将
     执行最后一个匹配选项的操作。 无效的 *note -W: 15b. 选项将被忽略（但
     是，在发出第一个警告时会打印有关无效选项的警告消息）。

     警告也可以使用 *note PYTHONWARNINGS: 51b. 环境变量以及使用 *note
     warnings: 12f. 模块在 Python 程序内部进行控制。

     最简单的设置是将某个特定操作无条件地应用于进程所发出所有警告 (即使
     是在默认情况下会忽略的那些警告):

          -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

     操作名称可以根据需要进行缩写 (例如 ‘-Wi’, ‘-Wd’, ‘-Wa’, ‘-We’)，解
     释器将会把它们解析为适当的操作名称。

     请参阅 *note 警告过滤器: 15d. 和 *note 警告过滤器的介绍: 147e. 了解
     更多细节。

 -- 程式選項: -x

     跳过源中第一行，以允许使用非 Unix 形式的 ‘#!cmd’。 这适用于 DOS 专
     属的破解操作。

 -- 程式選項: -X

     保留用于各种具体实现专属的选项。 CPython 目前定义了下列可用的值：

        * ‘-X faulthandler’ 启用 *note faulthandler: 7b.；

        * ‘-X oldparser’: 启用传统的 LL(1) 解析器。 另请参阅 *note
          PYTHONOLDPARSER: 1480. 和 PEP 617(6)。

        * ‘-X showrefcount’ 当程序结束或在交互解释器中的每条语句之后输出
          总引用计数和已使用内存块计数。 此选项仅在调试版本中有效。

        * ‘-X tracemalloc’ 使用 *note tracemalloc: 11d. 模块启动对
          Python 内存分配的跟踪。 默认情况下，只有最近的帧会保存在跟踪的
          回溯信息中。 使用 ‘-X tracemalloc=NFRAME’ 以启动限定回溯
          `NFRAME' 帧的跟踪。 请参阅 *note tracemalloc.start(): 1481. 了
          解详情。

        * ‘-X importtime’ 显示每次导入耗费的时间。 它会显示模块名称，累
          计时间（包括嵌套的导入）和自身时间（排除嵌套的导入）。 请注意
          它的输出在多线程应用程序中可能会出错。 典型用法如 ‘python3 -X
          importtime -c 'import asyncio'’。 另请参阅 *note
          PYTHONPROFILEIMPORTTIME: 444.。

        * ‘-X dev’: 启用 *note Python 开发模式: 160.，引入在默认情况下启
          用会导致开销过大的运行时检查。

        * ‘-X utf8’ 为操作系统接口启用 UTF-8 模式，覆盖默认的区域感知模
          式。 ‘-X utf8=0’ 显式地禁用 UTF-8 模式（即使在它应当被自动激活
          的时候）。 请参阅 *note PYTHONUTF8: 421. 了解详情。

        * ‘-X pycache_prefix=PATH’ 允许将 ‘.pyc’ 文件写入以给定目录为根
          的并行树，而不是代码树。另见 *note PYTHONPYCACHEPREFIX: 28f. 。

     它还允许传入任意值并通过 *note sys._xoptions: 1482. 字典来提取这些
     值。

     3.2 版更變: 增加了 *note -X: 290. 选项。

     3.3 版新加入: ‘-X faulthandler’ 选项。

     3.4 版新加入: ‘-X showrefcount’ 与 ‘-X tracemalloc’ 选项。

     3.6 版新加入: ‘-X showalloccount’ 选项。

     3.7 版新加入: ‘-X importtime’, ‘-X dev’ 与 ‘-X utf8’ 选项。

     3.8 版新加入: ‘-X pycache_prefix’ 选项。 ‘-X dev’ 选项现在在 *note
     io.IOBase: 30c. 析构函数中记录 ‘close()’ 异常。

     3.9 版更變: 使用 ‘-X dev’ 选项，在字符串编码和解码操作时检查
     `encoding' 和 `errors' 参数。

     The ‘-X showalloccount’ 选项已被移除。

     Deprecated since version 3.9, will be removed in version 3.10: The
     ‘-X oldparser’ 选项。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0488

   (2) https://www.python.org/dev/peps/pep-0488

   (3) https://www.python.org/dev/peps/pep-0488

   (4) https://www.python.org/dev/peps/pep-0488

   (5) https://www.python.org/dev/peps/pep-0370

   (6) https://www.python.org/dev/peps/pep-0617


File: python.info,  Node: 不应当使用的选项,  Prev: 其他选项,  Up: 命令行

3.1.1.4 不应当使用的选项
........................

 -- 程式選項: -J

     保留给 Jython(1) 使用。

   ---------- Footnotes ----------

   (1) http://www.jython.org/


File: python.info,  Node: 环境变量,  Prev: 命令行,  Up: 命令行与环境

3.1.2 环境变量
--------------

这些环境变量会影响 Python 的行为，它们是在命令行开关之前被处理的，但 -E
或 -I 除外。 根据约定，当存在冲突时命令行开关会覆盖环境变量的设置。

 -- 環境變數: PYTHONHOME

     更改标准 Python 库的位置。 默认情况下库是在
     ‘`prefix'/lib/python`version'’ 和
     ‘`exec_prefix'/lib/python`version'’ 中搜索，其中 ‘`prefix'’ 和
     ‘`exec_prefix'’ 是由安装位置确定的目录，默认都位于 ‘/usr/local’。

     当 *note PYTHONHOME: 5d0. 被设为单个目录时，它的值会同时替代
     ‘`prefix'’ 和 ‘`exec_prefix'’。 要为两者指定不同的值，请将 *note
     PYTHONHOME: 5d0. 设为 ‘`prefix':`exec_prefix'’。

 -- 環境變數: PYTHONPATH

     增加模块文件默认搜索路径。 所用格式与终端的 ‘PATH’ 相同：一个或多个
     由 *note os.pathsep: 1486. 分隔的目录路径名称（例如 Unix 上用冒号而
     在 Windows 上用分号）。 默认忽略不存在的目录。

     除了普通目录之外，单个 *note PYTHONPATH: a34. 条目可以引用包含纯
     Python模块的zip文件（源代码或编译形式）。无法从zip文件导入扩展模块
     。

     默认索引路径依赖于安装路径，但通常都是以
     ‘`prefix'/lib/python`version'’ 开始 (参见上文中的 *note PYTHONHOME:
     5d0.)。 它 `总是' 会被添加到 *note PYTHONPATH: a34.。

     有一个附加目录将被插入到索引路径的 *note PYTHONPATH: a34. 之前，正
     如上文中 *note 接口选项: 146e. 所描述的。 搜索路径可以在 Python 程
     序内作为变量 *note sys.path: 261. 来进行操作。

 -- 環境變數: PYTHONPLATLIBDIR

     如果它被设为非空字符串，则会覆盖 *note sys.platlibdir: 1e9. 值。

     3.9 版新加入.

 -- 環境變數: PYTHONSTARTUP

     这如果是一个可读文件的名称，该文件中的 Python 命令会在交互模式的首
     个提示符显示之前被执行。 该文件会在与交互式命令执行所在的同一命名空
     间中被执行，因此其中所定义或导入的对象可以在交互式会话中无限制地使
     用。 你还可以在这个文件中修改提示符 *note sys.ps1: 1487. 和 *note
     sys.ps2: 1488. 以及钩子 *note sys.__interactivehook__: 9ca.。

     使用 ‘filename’ 参数会引发 *note 审计事件: fa1.
     ‘cpython.run_startup’ 。

 -- 環境變數: PYTHONOPTIMIZE

     这如果被设为一个非空字符串，它就相当于指定 *note -O: 77e. 选项。 如
     果设为一个整数，则它就相当于多次指定 *note -O: 77e.。

 -- 環境變數: PYTHONBREAKPOINT

     此变量如果被设定，它会使用加点号的路径标记一个可调用对象。 包含该可
     调用对象的模块将被导入，随后该可调用对象将由 *note
     sys.breakpointhook(): 423. 的默认实现来运行，后者自身将由内置的
     *note breakpoint(): 40b. 来调用。 如果未设定，或设定为空字符串，则
     它相当于值 "pdb.set_trace"。 将此变量设为字符串 "0" 会导致 *note
     sys.breakpointhook(): 423. 的默认实现不做任何事而直接返回。

     3.7 版新加入.

 -- 環境變數: PYTHONDEBUG

     此变量如果被设为一个非空字符串，它就相当于指定 *note -d: 1476. 选项
     。 如果设为一个整数，则它就相当于多次指定 *note -d: 1476.。

 -- 環境變數: PYTHONOLDPARSER

     如果将该选项设为非空字符串，则启用传统的 LL(1) 解析器。

     另请参阅 *note -X: 290. ‘oldparser’ 选项和 PEP 617(1)。

     Deprecated since version 3.9, will be removed in version 3.10.

 -- 環境變數: PYTHONINSPECT

     此变量如果被设为一个非空字符串，它就相当于指定 *note -i: ee1. 选项
     。

     此变量也可由 Python 代码使用 *note os.environ: c09. 来修改以在程序
     终结时强制检查模式。

 -- 環境變數: PYTHONUNBUFFERED

     此变量如果被设为一个非空字符串，它就相当于指定 *note -u: 109d. 选项
     。

 -- 環境變數: PYTHONVERBOSE

     此变量如果被设为一个非空字符串，它就相当于指定 *note -v: e4d. 选项
     。 如果设为一个整数，则它就相当于多次指定 *note -v: e4d.。

 -- 環境變數: PYTHONCASEOK

     If this is set, Python ignores case in *note import: ce7.
     statements.  This only works on Windows and macOS.

 -- 環境變數: PYTHONDONTWRITEBYTECODE

     此变量如果被设为一个非空字符串，Python 将不会尝试在导入源模块时写入
     ‘.pyc’ 文件。 这相当于指定 *note -B: dfe. 选项。

 -- 環境變數: PYTHONPYCACHEPREFIX

     如果设置了此选项，Python将在镜像目录树中的此路径中写入 ‘.pyc’ 文件
     ，而不是源树中的 ‘__pycache__’ 目录中。这相当于指定 *note -X: 290.
     ‘pycache_prefix=PATH’ 选项。

     3.8 版新加入.

 -- 環境變數: PYTHONHASHSEED

     如果此变量未设置或设为 ‘random’，将使用一个随机值作为 str 和 bytes
     对象哈希运算的种子。

     如果 *note PYTHONHASHSEED: aa4. 被设为一个整数值，它将被作为固定的
     种子数用来生成哈希随机化所涵盖的类型的 hash() 结果。

     它的目的是允许可复现的哈希运算，例如用于解释器本身的自我检测，或允
     许一组 python 进程共享哈希值。

     该整数必须为一个 [0,4294967295] 范围内的十进制数。 指定数值 0 将禁
     用哈希随机化。

     3.2.3 版新加入.

 -- 環境變數: PYTHONIOENCODING

     如果此变量在运行解释器之前被设置，它会覆盖通过
     ‘encodingname:errorhandler’ 语法设置的 stdin/stdout/stderr 所用编码
     。 ‘encodingname’ 和 ‘:errorhandler’ 部分都是可选项，与在 *note
     str.encode(): 170. 中的含义相同。

     对于 stderr，‘:errorhandler’ 部分会被忽略；处理程序将总是为
     ‘'backslashreplace'’。

     3.4 版更變: “encodingname” 部分现在是可选的。

     3.6 版更變: 在 Windows 上，对于交互式控制台缓冲区会忽略此变量所指定
     的编码，除非还指定了 *note PYTHONLEGACYWINDOWSSTDIO: 5f3.。 通过标
     准流重定向的文件和管道则不受其影响。

 -- 環境變數: PYTHONNOUSERSITE

     如果设置了此变量，Python 将不会把 *note 用户 site-packages 目录:
     147a. 添加到 *note sys.path: 261.。

     也參考
     ......

     PEP 370(2) – 分用户的 site-packages 目录

 -- 環境變數: PYTHONUSERBASE

     定义 *note 用户基准目录: 1489.，它会在执行 ‘python setup.py install
     --user’ 时被用来计算 *note 用户 site-packages 目录: 147a. 的路径以
     及 *note Distutils 安装路径: 148a.。

     也參考
     ......

     PEP 370(3) – 分用户的 site-packages 目录

 -- 環境變數: PYTHONEXECUTABLE

     If this environment variable is set, ‘sys.argv[0]’ will be set to
     its value instead of the value got through the C runtime.  Only
     works on macOS.

 -- 環境變數: PYTHONWARNINGS

     此变量等价于 *note -W: 15b. 选项。 如果被设为一个以逗号分隔的字符串
     ，它就相当于多次指定 *note -W: 15b.，列表中后出现的过滤器优先级会高
     于列表中先出现的。

     最简单的设置是将某个特定操作无条件地应用于进程所发出所有警告 (即使
     是在默认情况下会忽略的那些警告):

          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

     请参阅 *note 警告过滤器: 15d. 和 *note 警告过滤器的介绍: 147e. 了解
     更多细节。

 -- 環境變數: PYTHONFAULTHANDLER

     如果此环境变量被设为一个非空字符串，*note faulthandler.enable():
     642. 会在启动时被调用：为 ‘SIGSEGV’, ‘SIGFPE’, ‘SIGABRT’, ‘SIGBUS’
     和 ‘SIGILL’ 等信号安装一个处理句柄以转储 Python 回溯信息。 此变量等
     价于 *note -X: 290. ‘faulthandler’ 选项。

     3.3 版新加入.

 -- 環境變數: PYTHONTRACEMALLOC

     如果此环境变量被设为一个非空字符串，则会使用 *note tracemalloc:
     11d. 模块启动对 Python 内存分配的跟踪。 该变量的值是保存于跟踪的回
     溯信息中的最大帧数。 例如，‘PYTHONTRACEMALLOC=1’ 只保存最近的帧。 请
     参阅 *note tracemalloc.start(): 1481. 了解详情。

     3.4 版新加入.

 -- 環境變數: PYTHONPROFILEIMPORTTIME

     如果此变量被设为一个非空字符串，Python 将显示每次导入花费了多长时间
     。 此变量完全等价于在命令行为设置 ‘-X importtime’。

     3.7 版新加入.

 -- 環境變數: PYTHONASYNCIODEBUG

     如果此变量被设为一个非空字符串，则会启用 *note asyncio: 9. 模块的
     *note 调试模式: 148e.。

     3.4 版新加入.

 -- 環境變數: PYTHONMALLOC

     设置 Python 内存分配器和/或安装调试钩子。

     设置 Python 所使用的内存分配器族群：

        * ‘default’: 使用 *note 默认内存分配器: 148f.。

        * ‘malloc’: 对所有域 (*note PYMEM_DOMAIN_RAW: 1490, *note
          PYMEM_DOMAIN_MEM: 602, *note PYMEM_DOMAIN_OBJ: 600.) 使用 C 库
          的 ‘malloc()’ 函数。

        * ‘pymalloc’: 对 *note PYMEM_DOMAIN_MEM: 602. 和 *note
          PYMEM_DOMAIN_OBJ: 600. 域使用 *note pymalloc 分配器: 6b8. 而对
          *note PYMEM_DOMAIN_RAW: 1490. 域使用 ‘malloc()’ 函数。

     安装调试钩子：

        * ‘debug’: 在 *note 默认内存分配器: 148f. 之上安装调试钩子。

        * ‘malloc_debug’: 与 ‘malloc’ 相同但还会安装调试钩子。

        * ‘pymalloc_debug’: 与 ‘pymalloc’ 相同但还会安装调试钩子。

     请参阅 *note 默认内存分配器: 148f. 以及 *note
     PyMem_SetupDebugHooks(): 603. 函数（在 Python 内存分配器之上安装调
     试钩子）。

     3.7 版更變: 增加了 ‘"default"’ 分配器。

     3.6 版新加入.

 -- 環境變數: PYTHONMALLOCSTATS

     如果设为一个非空字符串，Python 将在每次创建新的 pymalloc 对象区域以
     及在关闭时打印 *note pymalloc 内存分配器: 6b8. 的统计信息。

     如果 *note PYTHONMALLOC: 5fc. 环境变量被用来强制开启 C 库的
     ‘malloc()’ 分配器，或者如果 Python 的配置不支持 ‘pymalloc’，则此变
     量将被忽略。

     3.6 版更變: 此变量现在也可以被用于在发布模式下编译的 Python。 如果
     它被设置为一个空字符串则将没有任何效果。

 -- 環境變數: PYTHONLEGACYWINDOWSFSENCODING

     如果设为一个非空字符串，则默认的文件系统编码和错误模式将分别恢复为
     它们在 3.6 版之前的值 ’mbcs’ 和 ’replace’。 否则会使用新的默认值
     ’utf-8’ 和 ’surrogatepass’。

     这也可以在运行时通过 *note sys._enablelegacywindowsfsencoding():
     5f1. 来启用。

     *note 可用性: 1491.: Windows。

     3.6 版新加入: 有关更多详细信息，请参阅 PEP 529(4)。

 -- 環境變數: PYTHONLEGACYWINDOWSSTDIO

     如果设为一个非空字符串，则不使用新的控制台读取器和写入器。 这意味着
     Unicode 字符将根据活动控制台的代码页进行编码，而不是使用 utf-8。

     如果标准流被重定向（到文件或管道）而不是指向控制台缓冲区则该变量会
     被忽略。

     *note 可用性: 1491.: Windows。

     3.6 版新加入.

 -- 環境變數: PYTHONCOERCECLOCALE

     如果值设为 ‘0’，将导致主 Python 命令行应用跳过将传统的基于 ASCII 的
     C 与 POSIX 区域设置强制转换为更强大的基于 UTF-8 的替代方案。

     如果此变量 `未被' 设置（或被设为 ‘0’ 以外的值），则覆盖环境变量的
     ‘LC_ALL’ 区域选项也不会被设置，并且报告给 ‘LC_CTYPE’ 类别的当前区域
     选项或者为默认的 ‘C’ 区域，或者为显式指明的基于 ASCII 的 ‘POSIX’ 区
     域，然后 Python CLI 将在加载解释器运行时之前尝试为 ‘LC_CTYPE’ 类别
     按指定的顺序配置下列区域选项：

        * ‘C.UTF-8’

        * ‘C.utf8’

        * ‘UTF-8’

     如果成功设置了以上区域类别中的一个，则初始化 Python 运行时之前也将
     在当前进程环境中相应地设置 ‘LC_CTYPE’ 环境变量。 这会确保除了解释器
     本身和运行于同一进程中的其他可感知区域选项的组件 (例如 GNU
     ‘readline’ 库) 之外，还能在子进程 (无论这些进程是否在运行 Python 解
     释器) 以及在查询环境而非当前 C 区域的操作 (例如 Python 自己的 *note
     locale.getdefaultlocale(): 1492.) 中看到更新的设置。

     (显式地或通过上述的隐式区域强制转换) 配置其中一个区域选项将自动为
     *note sys.stdin: 41e. 和 *note sys.stdout: 41f. 启用
     ‘surrogateescape’ *note 错误处理句柄: 1493. (*note sys.stderr: 1ea.
     会继续使用 ‘backslashreplace’ 如同在任何其他区域选项中一样)。 这种
     流处理行为可以按通常方式使用 *note PYTHONIOENCODING: a14. 来覆盖。

     出于调试目的，如果激活了区域强制转换，或者如果当 Python 运行时被初
     始化时某个 `应该' 触发强制转换的区域选项仍处于激活状态则设置
     ‘PYTHONCOERCECLOCALE=warn’ 将导致 Python 在 ‘stderr’ 上发出警告消息
     。

     还要注意，即使在区域转换转换被禁用，或者在其无法找到合适的目标区域
     时，默认 *note PYTHONUTF8: 421. 仍将在传统的基于 ASCII 的区域中被激
     活。 必须同时禁用这两项特性以强制解释器使用 ‘ASCII’ 而不是 ‘UTF-8’
     作为系统接口。

     *note 可用性: 1491.: *nix。

     3.7 版新加入: 请参阅 PEP 538(5) 了解详情。

 -- 環境變數: PYTHONDEVMODE

     如果将此环境变量设为非空字符串，则启用 *note Python 开发模式: 160.，
     引入在默认情况下启用会导致开销过大的运行时检查。

     3.7 版新加入.

 -- 環境變數: PYTHONUTF8

     如果设为 ‘1’，则会启用解释器的 UTF-8 模式，将 ‘UTF-8’ 用作系统接口
     的文本编码，无论当前区域选项如何设置。

     这意味着：

             * *note sys.getfilesystemencoding(): 5ef. 将返回 ‘'UTF-8'’
               (本地编码会被忽略)。

             * *note locale.getpreferredencoding(): 4ab. 将返回
               ‘'UTF-8'’ (本地编码会被忽略，并且该函数的 ‘do_setlocale’
               参数不起作用)。

             * *note sys.stdin: 41e, *note sys.stdout: 41f. 和 *note
               sys.stderr: 1ea. 都将 UTF-8 用作它们的文本编码，并且为
               *note sys.stdin: 41e. 和 *note sys.stdout: 41f. 启用
               ‘surrogateescape’ *note 错误处理句柄: 1493. (*note
               sys.stderr: 1ea. 会继续使用 ‘backslashreplace’ 如同在默认
               的局部感知模式下一样)

     作为低层级 API 发生改变的结果，其他高层级 API 也会表现出不同的默认
     行为：

             * 命令行参数，环境变量和文件名会使用 UTF-8 编码来解码为文本
               。

             * *note os.fsdecode(): 5e8. 和 *note os.fsencode(): 5e9. 会
               使用 UTF-8 编码。

             * *note open(): 16f, *note io.open(): 74d. 和 *note
               codecs.open(): 10c3. 默认会使用 UTF-8 编码。 但是，它们默
               认仍将使用严格错误处理句柄，因此试图在文本模式下打开二进
               制文件将可能引发异常，而不是生成无意义的数据。

     请注意 UTF-8 模式下的标准流设置可以被 *note PYTHONIOENCODING: a14.
     所覆盖（在默认的区域感知模式下也同样如此）。

     如果设置为“0”，则解释器以其默认的区域识别模式运行。

     设置任何其他非空字符串会在解释器初始化期间导致错误。

     如果根本未设置此环境变量，则解释器默认使用当前区域设置，`除非' 当前
     区域被标识为基于 ASCII 的旧式区域设置（如 *note
     PYTHONCOERCECLOCALE: 41d. 所述），并且区域强制转换被禁用或失败。 在
     此类旧式区域设置中，解释器将默认启用 UTF-8 模式，除非显式地指定不这
     样做。

     也可以使用 *note -X: 290. ‘utf8’ 选项。

     3.7 版新加入: 有关更多详细信息，请参阅 PEP 540(6) 。

* Menu:

* 调试模式变量::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0617

   (2) https://www.python.org/dev/peps/pep-0370

   (3) https://www.python.org/dev/peps/pep-0370

   (4) https://www.python.org/dev/peps/pep-0529

   (5) https://www.python.org/dev/peps/pep-0538

   (6) https://www.python.org/dev/peps/pep-0540


File: python.info,  Node: 调试模式变量,  Up: 环境变量

3.1.2.1 调试模式变量
....................

设置这些变量只会在Python的调试版本中产生影响。

 -- 環境變數: PYTHONTHREADDEBUG

     如果设置，Python将打印线程调试信息。

     需要使用 ‘--with-pydebug’ 构建选项配置Python。

 -- 環境變數: PYTHONDUMPREFS

     如果设置，Python在关闭解释器，及转储对象和引用计数后仍将保持活动。

     需要使用 ‘--with-trace-refs’ 构建选项配置Python。


File: python.info,  Node: 在Unix平台中使用Python,  Next: 在 Windows 上使用 Python,  Prev: 命令行与环境,  Up: Python 的設置與使用

3.2 在Unix平台中使用Python
==========================

* Menu:

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


File: python.info,  Node: 获取最新版本的Python,  Next: 构建Python,  Up: 在Unix平台中使用Python

3.2.1 获取最新版本的Python
--------------------------

* Menu:

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


File: python.info,  Node: 在Linux中,  Next: 在FreeBSD和OpenBSD上,  Up: 获取最新版本的Python

3.2.1.1 在Linux中
.................

Python预装在大多数Linux发行版上，并作为一个包提供给所有其他用户。 但是，
您可能想要使用的某些功能在发行版提供的软件包中不可用。这时您可以从源代码
轻松编译最新版本的Python。

如果Python没有预先安装并且不在发行版提供的库中，您可以轻松地为自己使用的
发行版创建包。 参阅以下链接：

也參考
......

‘https://www.debian.org/doc/manuals/maint-guide/first.en.html’

     对于Debian用户

‘https://en.opensuse.org/Portal:Packaging’

     对于OpenSuse用户

‘https://docs-old.fedoraproject.org/en-US/Fedora_Draft_Documentation/0.1/html/RPM_Guide/ch-creating-rpms.html’

     对于Fedora用户

‘http://www.slackbook.org/html/package-management-making-packages.html’

     对于Slackware用户


File: python.info,  Node: 在FreeBSD和OpenBSD上,  Next: 在OpenSolaris系统上,  Prev: 在Linux中,  Up: 获取最新版本的Python

3.2.1.2 在FreeBSD和OpenBSD上
............................

   * FreeBSD用户，使用以下命令添加包:

          pkg install python3

   * OpenBSD用户，使用以下命令添加包:

          pkg_add -r python

          pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/<insert your architecture here>/python-<version>.tgz

     例如：i386用户获取Python 2.5.1的可用版本:

          pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/i386/python-2.5.1p2.tgz


File: python.info,  Node: 在OpenSolaris系统上,  Prev: 在FreeBSD和OpenBSD上,  Up: 获取最新版本的Python

3.2.1.3 在OpenSolaris系统上
...........................

你可以从 OpenCSW(1) 获取、安装及使用各种版本的Python。比如 ‘pkgutil -i
python27’ 。

   ---------- Footnotes ----------

   (1) https://www.opencsw.org/


File: python.info,  Node: 构建Python,  Next: 与Python相关的路径和文件,  Prev: 获取最新版本的Python,  Up: 在Unix平台中使用Python

3.2.2 构建Python
----------------

如果你想自己编译CPython，首先要做的是获取 source(1) 。您可以下载最新版本
的源代码，也可以直接提取最新的 clone(2) 。 （如果你想要制作补丁，则需要
克隆代码。）

构建过程由常用命令组成：

     ./configure
     make
     make install

特定Unix平台的配置选项和注意事项通常记录在Python源代码的根目录下的
README.rst(3) 文件中。

     警告: ‘make install’ 可以覆盖或伪装 ‘python3’ 二进制文件。因此，建
     议使用 ‘make altinstall’ 而不是 ‘make install’ ，因为后者只安装了
     ‘`exec_prefix'/bin/python`version'’ 。

   ---------- Footnotes ----------

   (1) https://www.python.org/downloads/source/

   (2) https://devguide.python.org/setup/#getting-the-source-code

   (3) https://github.com/python/cpython/tree/3.9/README.rst


File: python.info,  Node: 与Python相关的路径和文件,  Next: 杂项,  Prev: 构建Python,  Up: 在Unix平台中使用Python

3.2.3 与Python相关的路径和文件
------------------------------

这取决于本地安装惯例； ‘prefix’ （ ‘${prefix}’ ）和 ‘exec_prefix’ （
‘${exec_prefix}’ ） 取决于安装，应解释为GNU软件；它们可能相同。

例如，在大多数Linux系统上，两者的默认值是 ‘/usr’ 。

文件/目录                                           含义
                                                    
---------------------------------------------------------------------------------------------------
                                                    
‘`exec_prefix'/bin/python3’                         解释器的推荐位置
                                                    
                                                    
‘`prefix'/lib/python`version'’,                     包含标准模块的目录的推荐位置
‘`exec_prefix'/lib/python`version'’                 

‘`prefix'/include/python`version'’,                 包含开发Python扩展和嵌入解释器所需的
‘`exec_prefix'/include/python`version'’             include文件的目录的推荐位置
                                                    


File: python.info,  Node: 杂项,  Prev: 与Python相关的路径和文件,  Up: 在Unix平台中使用Python

3.2.4 杂项
----------

要在Unix上使用Python脚本，需要添加可执行权限，例如：

     $ chmod +x script

并在脚本的顶部放置一个合适的Shebang线。一个很好的选择通常是:

     #!/usr/bin/env python3

将在整个 ‘PATH’ 中搜索Python解释器。但是，某些Unix系统可能没有 ‘env’ 命
令，因此可能需要将 ‘/usr/bin/python3’ 硬编码为解释器路径。

要在Python脚本中使用shell命令，请查看 *note subprocess: f9. 模块。


File: python.info,  Node: 在 Windows 上使用 Python,  Next: 在 Mac 系統使用Python,  Prev: 在Unix平台中使用Python,  Up: Python 的設置與使用

3.3 在 Windows 上使用 Python
============================

本文档旨在概述在 Microsoft Windows 上使用 Python 时应了解的特定于
Windows 的行为。

与大多数UNIX系统和服务不同，Windows系统没有预安装Python。多年来CPython 团
队已经编译了每一个 发行版(1) 的Windows安装程序（MSI 包），已便Windows 用
户下载和安装。这些安装程序主要用于每个用户单独安装Python时，添加核心解释
器和库。安装程序还可以为一台机器的所有用户安装，并且可以为应用程序本地分
发提供单独的zip文件。

如 PEP 11(2) 所述，Python 发布版对某个 Windows 平台的支持仅限于被
Microsoft 视为处于延长支持周期内的版本。 这意味着 Python 3.9 支持
Windows 8.1 及其后的版本。 如果你需要 Windows 7 支持，请安装 Python 3.8。

Windows提供了许多不同的安装程序，每个安装程序都有一定的优点和缺点。

*note 完整安装程序: 14a2. 内含所有组件，对于使用Python 进行任何类型项目
的开发人员而言，它是最佳选择。

*note Microsoft Store包: 133d. 是一个简单的Python 安装，适用于运行脚本和
包，以及使用IDLE或其他开发环境。 它需要Windows 10，但可以安全地安装而不
会破坏其他程序。 它还提供了许多方便的命令来启动Python及其工具。

*note nuget.org 安装包: 14a3. 是用于持续集成系统的轻量级安装。它可用于构
建Python包或运行脚本，但不可更新且没有用户界面工具。

*note 可嵌入的包: 14a4. 是Python的最小安装包，适合嵌入到更大的应用程序中
。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://www.python.org/download/releases/

   (2) https://www.python.org/dev/peps/pep-0011


File: python.info,  Node: 完整安装程序,  Next: Microsoft Store包,  Up: 在 Windows 上使用 Python

3.3.1 完整安装程序
------------------

* Menu:

* 安装步骤::
* 删除 MAX_PATH 限制::
* 安裝排除使用者介面::
* 當安裝時不下載::
* 修改安装::


File: python.info,  Node: 安装步骤,  Next: 删除 MAX_PATH 限制,  Up: 完整安装程序

3.3.1.1 安装步骤
................

四个 Python 3.9 安装程序可供下载 - 32位和64位版本的各有两个。 `web
installer' （网络安装包）是一个小的初始化工具，它将在安装过程中，根据需
要自动下载所需的组件。 `offline installer' （离线安装包）内含默认安装所
需的组件，可选择功能仍需要Internet连接下载。请参阅 *note 當安裝時不下載:
14a7. 以了解在安装过程中避免下载的其他方法。

启动安装程序后，可以选择以下两个选项之一：

[python-figures/win_installer]
如果你選擇「馬上安裝」：

   * 您 `不' 需要成为管理员（除非需要对C运行库进行系统更新，或者为所有用
     户安装 *note 适用于Windows的Python启动器: a70. ）

   * Python将安装到您的用户目录中

   * *note 适用于Windows的Python启动器: a70. 将根据第一页底部的选项安装

   * 将安装标准库，测试套件，启动器和pip

   * 如果選擇，安裝目錄將被加入到你的 ‘PATH’

   * 安裝捷徑將只能被目前使用者所看見

選擇「客製化安裝」將允許你選擇所需的項目進行安裝，安裝位置與其他選擇或安
裝後的所需進行的動作。你將需要使用此選項「除錯特徵」或「二進位方式」進行
安裝。

如要为全部用户安装，应选择“自定义安装”。在这种情况下:

   * 您可能需要提供管理凭据或批准

   * Python 将安装到Program Files目录中

   * *note 适用于Windows的Python启动器: a70. 将安装到Windows目录中

   * 安装期间可以选择可选功能

   * 标准库可以预编译为字节码

   * 如果选中，安装目录将添加到系统 ‘PATH’

   * 捷徑將被所有使用者所見


File: python.info,  Node: 删除 MAX_PATH 限制,  Next: 安裝排除使用者介面,  Prev: 安装步骤,  Up: 完整安装程序

3.3.1.2 删除 MAX_PATH 限制
..........................

历史上Windows的路径长度限制为260个字符。这意味着长于此的路径将无法解决并
导致错误。

在最新版本的 Windows 中，此限制可被扩展到大约 32,000 个字符。 但需要让管
理员激活“启用 Win32 长路径”组策略，或在注册表键
‘HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem’ 中设置
‘LongPathsEnabled’ 为 ‘1’。

这允许 *note open(): 16f. 函数，*note os: c4. 模块和大多数其他路径功能接
受并返回长度超过 260 个字符的路径。

更改上述选项后，无需进一步配置。

3.6 版更變: Python中启用了对长路径的支持。


File: python.info,  Node: 安裝排除使用者介面,  Next: 當安裝時不下載,  Prev: 删除 MAX_PATH 限制,  Up: 完整安装程序

3.3.1.3 安裝排除使用者介面
..........................

安装程序UI中的所有选项也可以从命令行指定，允许脚本安装程序在许多机器上复
制安装，而无需用户交互。还可以在不禁用UI的情况下设置这些选项，以更改一些
默认值。

要完全隐藏安装程序UI并静默安装Python，请使用 ‘/quiet’ 选项。要跳过用户交
互但仍然显示进度和错误，请使用 ‘/passive’ 选项。可以通过 ‘/uninstall’ 选
项立即开始删除Python - - 不会显示任何提示。

所有其他选项都传递为 ‘name=value’ ，其中值通常是 ‘0’ 来禁用某个特性，
‘1’ 来启用某个特性或路径。可用选项的完整列表如下所示。

名称                            描述                                       預設
                                                                           
----------------------------------------------------------------------------------------------------------
                                                                           
InstallAllUsers                 为所有用户安装。                           0
                                                                           
                                                                           
TargetDir                       安裝目錄                                   基于InstallAllUsers选择
                                                                           
                                                                           
DefaultAllUsersTargetDir        为所有用户安装时的默认安装路径             ‘%ProgramFiles%\Python X.Y’
                                                                           或
                                                                           ‘%ProgramFiles(x86)%\Python
                                                                           X.Y’
                                                                           
                                                                           
DefaultJustForMeTargetDir       預設安裝目錄給 只有給我 安裝方式           ‘%LocalAppData%\Programs\PythonXY’
                                                                           或
                                                                           ‘%LocalAppData%\Programs\PythonXY-32’
                                                                           或
                                                                           ‘%LocalAppData%\Programs\PythonXY-64’
                                                                           
                                                                           
DefaultCustomTargetDir          UI中显示的默认自定义安装目录               （空）
                                                                           
                                                                           
AssociateFiles                  當執行程序也被安裝時創造檔案關聯           1
                                                                           
                                                                           
CompileAll                      編譯所有 ‘.py’ 檔案為 ‘.pyc’。             0
                                                                           
                                                                           
PrependPath                     将install和Scripts目录添加到 ‘PATH’ 以及   0
                                将 ‘.PY’ 添加到 ‘PATHEXT’                  
                                
                                                                           
Shortcuts                       如果已安装，为解释器，文档和IDLE创建快捷   1
                                方式                                       
                                
                                                                           
Include_doc                     安裝Python文件                             1
                                                                           
                                                                           
Include_debug                   安装调试二进制文件                         0
                                                                           
                                                                           
Include_dev                     安装开发人员头文件和库                     1
                                                                           
                                                                           
Include_exe                     安装 ‘python.exe’ 及相关文件               1
                                                                           
                                                                           
Include_launcher                安装                                       1
                                *note 适用于Windows的Python启动器: a70.    
                                .
                                
                                                                           
InstallLauncherAllUsers         为所有用户安装                             1
                                *note 适用于Windows的Python启动器: a70.    
                                。
                                
                                                                           
Include_lib                     安装标准库和扩展模块                       1
                                                                           
                                                                           
Include_pip                     安装捆绑的pip和setuptools                  1
                                                                           
                                                                           
Include_symbols                 安装调试符号(‘*’.pdb)                      0
                                                                           
                                                                           
Include_tcltk                   安装Tcl/Tk 支持和IDLE                      1
                                                                           
                                                                           
Include_test                    安装标准库测试套件                         1
                                                                           
                                                                           
Include_tools                   安装实用程序脚本                           1
                                                                           
                                                                           
LauncherOnly                    仅安装启动器。这将覆盖大多数其他选项。     0
                                                                           
                                                                           
SimpleInstall                   禁用大多数安装UI                           0
                                                                           
                                                                           
SimpleInstallDescription        使用简化安装UI时显示的自定义消息。         （空）
                                                                           

例如，要以静默方式全局安装默认的Python，您可以（在命令提示符>）使用以下
命令:

     python-3.9.0.exe /quiet InstallAllUsers=1 PrependPath=1 Include_test=0

要允许用户在没有测试套件的情况下轻松安装Python的个人副本，可以使用以下命
令提供快捷方式。这将显示一个简化的初始页面，不允许自定义:

     python-3.9.0.exe InstallAllUsers=0 Include_launcher=0 Include_test=0
         SimpleInstall=1 SimpleInstallDescription="Just for me, no test suite."

（请注意，省略启动器也会省略文件关联，并且仅在全局安装包含启动器时才建议
用于每用户安装。）

上面列出的选项也可以在一个名为 ‘unattend.xml’ 的文件中与可执行文件一起提
供。此文件指定选项和值的列表。作为属性提供的值，（如果可能）它将转换为数
字。作为文本提供的值，始终保留为字符串。此示例文件设置与上一示例采用相同
的选项：

     <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>


File: python.info,  Node: 當安裝時不下載,  Next: 修改安装,  Prev: 安裝排除使用者介面,  Up: 完整安装程序

3.3.1.4 當安裝時不下載
......................

由于下载的初始安装包中未包含Python的某些可选功能，如果选择安装这些功能可
能需要Internet连接。为了避免这种需要，可以按需下载所有可能的组件，以创建
一个完整的布局，该布局将不再需要internet连接，而不管所选择的特性是什么。
请注意，此下载可能比要求的要大，但是如果要执行大量安装，则拥有本地缓存​​的
副本非常有用。

从命令提示符执行以下命令以下载所有可能的必需文件。 请记得要将
‘python-3.9.0.exe’ 替换为安装程序的实际名称，并在单独的目录中创建子目录
以避免同名文件间的冲突。

     python-3.9.0.exe /layout [optional target directory]

您也可以指定 ‘/quiet’ 选项来隐藏进度显示。


File: python.info,  Node: 修改安装,  Prev: 當安裝時不下載,  Up: 完整安装程序

3.3.1.5 修改安装
................

安装Python后，您可以通过Windows中的“程序和功能”工具添加或删除功能。选择
Python条目并选择“卸载/更改”以在维护模式下打开安装程序。

“修改” 允许您通过修改复选框来添加或删除功能 - 未更改的复选框将不会安装或
删除任何内容。在此模式下无法更改某些选项，例如安装目录；要修改这些，您需
要完全删除然后重新安装Python。

“修复” 将使用当前设置验证应安装的所有文件，并替换已删除或修改的任何文件

“卸载” 将完全删除Python，但 *note 适用于Windows的Python启动器: a70. 除外
，它在“程序和功能”中有自己的条目。


File: python.info,  Node: Microsoft Store包,  Next: nuget org 安装包,  Prev: 完整安装程序,  Up: 在 Windows 上使用 Python

3.3.2 Microsoft Store包
-----------------------

3.7.2 版新加入.

Microsoft Store包是一个易于安装的Python解释器，主要用于交互式使用，例如
，学生。

要安装软件包，请确保您拥有最新的Windows 10更新，并在Microsoft Store应用
程序中搜索 "Python 3.9" 。确保您选择的应用程序由 Python Software
Foundation 发布并安装。

     警告: Python将始终在Microsoft Store上免费提供。如果要求您付款，则表
     示您没有选择正确的包。

安装完成后，可以在开始菜单中找到它来启动 Python。或者可以在命令提示符或
PowerShell 会话中输入 ‘python’ 来启动。此外可以输入 ‘pip’ 或 ‘idle’ 来使
用 pip 和 IDLE。IDLE 也在开始菜单中。

所有这三个命令也可以使用版本号后缀，例如， ‘python3.exe’ 和
‘python3.x.exe’ 以及 ‘python.exe’ （其中 ‘3.x’ 是您要启动的特定版本，例
如 3.9 ）。在 ‘设置-->主页-->应用和功能’ 页面中，点选 ‘管理可选功能’ ，
选择与每个命令关联的python版本。建议确保 ‘pip’ 和 ‘idle’ 与选择的
‘python’ 版本一致。

可以使用 ‘python -m venv’ 创建虚拟环境并激活并正常使用。

如果你已经安装了另一个版本的Python并将它添加到你的 ‘PATH’ 变量中，那么它
将作为 ‘python.exe’ 而不是来自Microsoft Store的那个。要访问新安装，请使
用 ‘python3.exe’ 或 ‘python3.x.exe’ 。

‘py.exe’ 启动器将检测此 Python 安装版，但会优先使用来自传统安装器的安装
版。

要删除Python，请打开“设置”并使用“应用程序和功能”，或者在“开始”中找到
Python，然后右键单击以选择“卸载”。卸载将删除该已安装Python程序中的所有软
件包，但不会删除任何虚拟环境

* Menu:

* 已知的问题::


File: python.info,  Node: 已知的问题,  Up: Microsoft Store包

3.3.2.1 已知的问题
..................

由于Microsoft Store应用程序的限制，Python脚本可能无法对共享位置（如
‘TEMP’ ）和注册表进行完全写入访问。相反，它将写入私人副本。如果脚本必须
修改共享位置，则需要安装完整安装程序。

有关此限制的技术原理的更多细节，请查询 Microsoft 已打包完全可信应用的文
档，当前位于
docs.microsoft.com/en-us/windows/msix/desktop/desktop-to-uwp-behind-the-scenes(1)

   ---------- Footnotes ----------

   (1) 
https://docs.microsoft.com/en-us/windows/msix/desktop/desktop-to-uwp-behind-the-scenes


File: python.info,  Node: nuget org 安装包,  Next: 可嵌入的包,  Prev: Microsoft Store包,  Up: 在 Windows 上使用 Python

3.3.3 nuget.org 安装包
----------------------

3.5.2 版新加入.

nuget.org是一个精简的Python环境，用于在没有全局安装Python的系统的持续集
成和构建。虽然Nuget是“.NET的包管理器”，但是对于包含构建时工具的包来说，
它也可以很好地工作。

访问 nuget.org(1) 获取有关使用nuget的最新信息。下面的摘要对Python开发人
员来说已经足够了。

‘nuget.exe’ 命令行工具可以直接从 ‘https://aka.ms/nugetclidl’ 下载，例如
，使用curl或PowerShell。使用该工具安装64位或32位最新版本的Python:

     nuget.exe install python -ExcludeVersion -OutputDirectory .
     nuget.exe install pythonx86 -ExcludeVersion -OutputDirectory .

要选择特定版本，请添加 ‘-Version 3.x.y’ 。输出目录可以从 ‘.’ 更改，包将
安装到子目录中。默认情况下，子目录的名称与包的名称相同，如果没有
‘-ExcludeVersion’ 选项，则此名称将包含已安装的特定版本。子目录里面是一个
包含Python安装的 ‘tools’ 目录:

     # 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

通常，nuget包不可升级，应该平行安装较新版本并使用完整路径引用。或者，手
动删除程序包目录并再次安装。如果在构建之间不保留文件，许多CI系统将自动执
行此操作。

除了 ‘tools’ 目录外，还有一个 ‘build\native’ 目录。它包含一个MSBuild属性
文件 ‘python.props’ ，可以在C++项目中使用该文件来引用Python安装。包含这
些设置将自动在生成中使用标头和导入库。

nuget.org上的包信息页是 www.nuget.org/packages/python(2) 对于64位版本和
www.nuget.org/packages/pythonx86(3) 表示32位版本。

   ---------- Footnotes ----------

   (1) https://www.nuget.org/

   (2) https://www.nuget.org/packages/python

   (3) https://www.nuget.org/packages/pythonx86


File: python.info,  Node: 可嵌入的包,  Next: 替代捆绑包,  Prev: nuget org 安装包,  Up: 在 Windows 上使用 Python

3.3.4 可嵌入的包
----------------

3.5 版新加入.

嵌入式发行版是一个包含最小Python环境的ZIP文件。它旨在作为另一个应用程序
的一部分，而不是由最终用户直接访问。

解压缩后，嵌入式发行版（几乎）与用户系统完全隔离，包括环境变量、系统注册
表设置和已安装的软件包。标准库作为预先编译和优化的 ‘.pyc’ 文件包含在
ZIP中，并提供了 ‘python3.dll’ ， ‘python37.dll’ ， ‘python.exe’ 和
‘pythonw.exe’ 文件。不包括Tcl/tk（包括所有依赖项，如Idle），pip和
Python文档。

     備註: 嵌入式发行版不包括 Microsoft C Runtime(1) ，应用程序安装程序
     负责提供此功能。运行时可能已经预先安装在用户的系统上或通过Windows
     Update自动安装，并且可以通过在系统目录中找到 ‘ucrtbase.dll’ 来检测

第三方软件包应该由应用程序与嵌入式发行版一起安装。这个发行版不支持像常规
Python安装那样使用pip来管理依赖关系，不过可以小心地将pip包含进来并使用它
进行自动更新。通常，第三方包应该作为应用程序的一部分(“打包”)处理，以便开
发人员在向用户提供更新之前能够确保与新版本兼容。

下面描述了这个发行版的两个推荐用例。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://www.microsoft.com/en-us/download/details.aspx?id=48145


File: python.info,  Node: Python应用程序,  Next: 嵌入 Python,  Up: 可嵌入的包

3.3.4.1 Python应用程序
......................

用Python编写的应用程序并不一定要求用户了解这一事实。在这种情况下，可以使
用嵌入式发行版在安装包中包含Python的私有版本。根据它应该有多透明(或者相
反，它应该看起来有多专业)，有两个选项。

使用专门的可执行文件作为启动程序需要一些编码，但为用户提供了最透明的体验
。使用定制的启动器，没有明显的迹象表明程序是在Python上运行的：图标可以定
制，公司和版本信息可以指定，文件关联可以正常运行。在大多数情况下，自定义
启动程序应该只需使用硬编码的命令行就能调用 ‘Py_Main’

更简单的方法是提供批处理文件或生成的快捷方式，使用所需的命令行参数直接调
用 ‘python.exe’ 或 ‘pythonw.exe’ 。在这种情况下，应用程序将显示为
Python而不是其实际名称，并且用户可能无法将其与其他正在运行的Python进程或
文件关联区分开来。

对于后一种方法，包应该与Python可执行文件一起作为目录安装，以确保它们在路
径上可用。使用专用的启动器，包可以位于其他位置，因为在启动应用程序之前有
机会指定搜索路径。


File: python.info,  Node: 嵌入 Python,  Prev: Python应用程序,  Up: 可嵌入的包

3.3.4.2 嵌入 Python
...................

用本地代码编写的应用程序通常需要某种形式的脚本语言，嵌入式Python发行版可
以用于此目的。通常，应用程序的大部分都是本机代码，某些部分将调用
‘python.exe’ 或直接使用 ‘python3.dll’ 。无论是哪种情况，将嵌入的发行版解
压缩到应用程序安装的子目录中就足以提供可加载的Python解释器。

与应用程序使用一样，包可以安装到任何位置，因为在初始化解释器之前有机会指
定搜索路径。否则，使用嵌入式发行版和常规安装之间没有根本区别。


File: python.info,  Node: 替代捆绑包,  Next: 設定 Python,  Prev: 可嵌入的包,  Up: 在 Windows 上使用 Python

3.3.5 替代捆绑包
----------------

除了标准的CPython发行版之外，还有一些包含附加功能的修改包。以下是热门版
本及其主要功能的列表：

ActivePython(1)

     具有多平台兼容性的安装程序，文档，PyWin32

Anaconda(2)

     流行的科学模块（如numpy，scipy和pandas）和 ‘conda’ 包管理器。

Canopy(3)

     具有编辑器和其他开发工具的“全面的Python分析环境”。

WinPython(4)

     特定于Windows的发行版，包含用于构建包的预构建科学包和工具。

请注意，这些软件包可能不包含最新版本的Python或其他库，并且不由核心
Python团队维护或支持。

   ---------- Footnotes ----------

   (1) https://www.activestate.com/activepython/

   (2) https://www.anaconda.com/download/

   (3) https://www.enthought.com/product/canopy/

   (4) https://winpython.github.io/


File: python.info,  Node: 設定 Python,  Next: UTF-8 模式,  Prev: 替代捆绑包,  Up: 在 Windows 上使用 Python

3.3.6 設定 Python
-----------------

要从命令提示符方便地运行Python，您可以考虑在Windows中更改一些默认环境变
量。虽然安装程序提供了为您配置PATH和PATHEXT变量的选项，但这仅适用于单版
本、全局安装。如果您经常使用多个版本的Python，请考虑使用 *note
适用于Windows的Python启动器: a70. 。

* Menu:

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


File: python.info,  Node: 附录：设置环境变量,  Next: 查找Python可执行文件,  Up: 設定 Python

3.3.6.1 附录：设置环境变量
..........................

Windows允许在用户级别和系统级别永久配置环境变量，或临时在命令提示符中配
置环境变量。

要临时设置环境变量，请打开命令提示符并使用 ‘set’ 命令：

     C:\>set PATH=C:\Program Files\Python 3.9;%PATH%
     C:\>set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib
     C:\>python

这些环境变量的更改将应用​​于在该控制台中执行的任何其他命令，并且，由该控制
台启动的任何应用程序都继承设这些设置。

在百分号中包含的变量名将被现有值替换，允许在开始或结束时添加新值。通过将
包含 ‘python.exe’ 的目录添加到开头来修改 ‘PATH’ 是确保启动正确版本的
Python的常用方法。

要永久修改默认环境变量，请单击“开始”并搜索“编辑环境变量”，或打开系统属性
的 高级系统设置 ，然后单击 环境变量 按钮。在此对话框中，您可以添加或修改
用户和系统变量。要更改系统变量，您需要对计算机进行无限制访问（即管理员权
限）。

     備註: Windows会将用户变量串联在系统变量 `之后' ，这可能会在修改
     ‘PATH’ 时导致意外结果。

     *note PYTHONPATH: a34. 变量被Python 2和Python 3的所有版本使用，因此
     除非它只包含与所有已安装的Python版本兼容的代码，否则不要永久配置此
     变量。

也參考
......

‘https://www.microsoft.com/en-us/wdsi/help/folder-variables’

     環境變數於 Windows NT

‘https://technet.microsoft.com/en-us/library/cc754250.aspx’

     用于临时修改环境变量的SET命令

‘https://technet.microsoft.com/en-us/library/cc755104.aspx’

     用于永久修改环境变量的SETX命令

‘https://support.microsoft.com/en-us/help/310519/how-to-manage-environment-variables-in-windows-xp’

     如何管理環境變數於 Windows XP

‘https://www.chem.gla.ac.uk/~louis/software/faq/q1.html’

     設定環境變數－Louis J. Farrugia


File: python.info,  Node: 查找Python可执行文件,  Prev: 附录：设置环境变量,  Up: 設定 Python

3.3.6.2 查找Python可执行文件
............................

3.5 版更變.

除了使用自动创建的Python解释器的开始菜单项之外，您可能还想在命令提示符下
启动Python。安装程序有一个选项可以为您设置。

在安装程序的第一页上，可以选择标记为“将Python添加到环境变量”的选项，以使
安装程序将安装位置添加到 ‘PATH’ 。还添加了 ‘Scripts\’ 文件夹的位置。这允
许你输入 ‘python’ 来运行解释器，并且 ‘pip’ 用于包安装程序。因此，您还可
以使用命令行选项执行脚本，请参阅 *note 命令行: a10. 文档。

如果在安装时未启用此选项，则始终可以重新运行安装程序，选择“修改”并启用它
。或者，您可以使用 *note 附录：设置环境变量: 133e. 的方法手动修改 ‘PATH’
。您需要将Python安装目录添加到 ‘PATH’ 环境变量中，该内容与其他条目用分号
分隔。示例变量可能如下所示（假设前两个条目已经存在）:

     C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files\Python 3.9


File: python.info,  Node: UTF-8 模式,  Next: 适用于Windows的Python启动器,  Prev: 設定 Python,  Up: 在 Windows 上使用 Python

3.3.7 UTF-8 模式
----------------

3.7 版新加入.

Windows 仍然使用传统编码格式作为系统的编码格式（ANSI 代码页）。 Python 使
用它作为文本文件默认的编码格式 (即 *note locale.getpreferredencoding():
4ab.)。

这可能会造成问题，因为因特网和大多数 Unix 系统包括 WSL (Windows
Subsystem for Linux) 广泛使用 UTF-8。

你可以使用 UTF-8 模式将默认的文本编码格式改为 UTF-8。 要启用 UTF-8 模式
可以通过 ‘-X utf8’ 命令行选项，或者 ‘PYTHONUTF8=1’ 环境变量。 请参见
*note PYTHONUTF8: 421. 了解如何启用 UTF-8 模式，并参见 *note
附录：设置环境变量: 133e. 了解如何修改环境变量。

当 UTF-8 模式被启用时：

   * *note locale.getpreferredencoding(): 4ab. 将返回 ‘'UTF-8'’ 而不是系
     统的编码格式。 此函数可用来在许多场合下获取默认的文本编码格式，包括
     *note open(): 16f, ‘Popen’, ‘Path.read_text()’ 等等。

   * *note sys.stdin: 41e, *note sys.stdout: 41f. 和 *note sys.stderr:
     1ea. 都将使用 UTF-8 作为其文本编码格式。

   * 你仍然可以通过 "mbcs" 编解码器来使用系统的编码格式。

请注意添加 ‘PYTHONUTF8=1’ 到默认环境变量将会影响你的系统中的所有 Python
3.7+ 应用。 如果你有任何 Python 3.7+ 应用仍然依赖于传统的系统编码格式，
则推荐设置临时环境变量或使用 ‘-X utf8’ 命令行选项。

     備註: 即使在不启用 UTF-8 模式时，Windows 版的 Python 也会在以下情况
     中默认使用 UTF-8：

        * 控制台 I/O 包括标准 I/O (详情见 PEP 528(1))。

        * 文件系统编码格式 (详情见 PEP 529(2))。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0528

   (2) https://www.python.org/dev/peps/pep-0529


File: python.info,  Node: 适用于Windows的Python启动器,  Next: 查找模块,  Prev: UTF-8 模式,  Up: 在 Windows 上使用 Python

3.3.8 适用于Windows的Python启动器
---------------------------------

3.3 版新加入.

用于Windows的Python启动器是一个实用程序，可帮助定位和执行不同的Python版
本。它允许脚本（或命令行）指示特定Python版本的首选项，并将定位并执行该版
本。

与 ‘PATH’ 变量不同，启动器将正确选择最合适的Python版本。它更倾向于按用户
安装而不是系统安装，并按语言版本排序，而不是使用最新安装的版本。

启动器最初是在 PEP 397(1) 中指定的。

* Menu:

* 開始::
* Shebang Lines::
* shebang lines 的参数::
* 自定义::
* 诊断::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0397


File: python.info,  Node: 開始,  Next: Shebang Lines,  Up: 适用于Windows的Python启动器

3.3.8.1 開始
............

* Menu:

* 从命令行::
* 虛擬環境（Virtual environment）::
* 从脚本::
* 從檔案關聯::


File: python.info,  Node: 从命令行,  Next: 虛擬環境（Virtual environment）,  Up: 開始

3.3.8.2 从命令行
................

3.6 版更變.

全局安装Python 3.3及更高版本将把启动器放在你的 ‘PATH’ 上。启动程序与所有
可用的Python版本兼容，因此安装哪个版本无关紧要。要检查启动程序是否可用，
请在命令提示符中执行以下命令：

     py

您应该会发现已安装的最新版本的Python已启动 - 它可以正常退出，并且将指定
的任何其他命令行参数直接发送到Python。

如果您安装了多个版本的Python（例如，2.7和 3.9 ），您会注意到Python 3.9 启
动 - 如果要启动Python 2.7，尝试命令：

     py -2.7

如果您想使用 Python 2.x 的最新版本，请尝试以下命令：

     py -2

你会发现Python 2.x 的最新版本已启动。

如果您看到以下错误，则表明您没有安装启动器：

     'py' is not recognized as an internal or external command,
     operable program or batch file.

除非在安装时选择了该选项，单个用户安装的Python不会将启动程序添加到
‘PATH’ 。


File: python.info,  Node: 虛擬環境（Virtual environment）,  Next: 从脚本,  Prev: 从命令行,  Up: 開始

3.3.8.3 虛擬環境（Virtual environment）
.......................................

3.5 版新加入.

如果启动程序运行时没有明确的Python版本，并且虚拟环境（使用标准库创建
*note venv: 12e. 模块或外部 ‘virtualenv’ 工具）处于活动状态，则启动程序
将运行虚拟环境的解释器而不是全局的。要运行全局解释器，请停用虚拟环境，或
显式指定全局Python版本。


File: python.info,  Node: 从脚本,  Next: 從檔案關聯,  Prev: 虛擬環境（Virtual environment）,  Up: 開始

3.3.8.4 从脚本
..............

让我们创建一个测试Python脚本 - 创建一个名为‘‘hello.py‘‘的文件，其中包含
以下内容

     #! python
     import sys
     sys.stdout.write("hello from Python %s\n" % (sys.version,))

从hello.py所在的目录中，执行以下命令：

     py hello.py

您应该注意到最新的Python 2.x安装的版本号已打印出来。现在尝试将第一行更改
为：

     #! python3

现在，重新执行该命令应该打印最新的Python 3.x信息。与上面的命令行示例一样
，你可以更明确的指定版本限定符。假设您安装了Python 2.6，请尝试将第一行更
改为 ‘#! python2.6’ ，你会发现打印的2.6版本信息。

请注意，与交互式使用不同，裸“python”将使用您已安装的Python 2.x的最新版本
。这是为了向后兼容及兼容Unix，其中命令 ‘python’ 通常是指Python 2。


File: python.info,  Node: 從檔案關聯,  Prev: 从脚本,  Up: 開始

3.3.8.5 從檔案關聯
..................

安装时应该将启动器与Python文件（即 ‘.py’, ‘.pyw’, ‘.pyc’ 文件）相关联。
这意味着当您从Windows资源管理器中双击其中一个文件时，将使用启动程序，因
此您可以使用上述相同的工具让脚本指定应使用的版本。

这样做的主要好处是，单个启动程序可以同时支持多个Python版本，具体取决于第
一行的内容。


File: python.info,  Node: Shebang Lines,  Next: shebang lines 的参数,  Prev: 開始,  Up: 适用于Windows的Python启动器

3.3.8.6 Shebang Lines
.....................

如果脚本文件的第一行以 ‘#!’ 开头，则称为 "shebang" 行。Linux和其他类
Unix操作系统都有对这些行的本机支持，它们通常在此类系统上用来指示应该如何
执行脚本。这个启动器允许在Windows上对Python脚本使用相同的工具，上面的示
例演示了它们的使用。

为了允许Python脚本中的shebang行在Unix和Windows之间移植，该启动器支持许多
“虚拟”命令来指定要使用的解释器。支持的虚拟命令是：

   * ‘/usr/bin/env python’

   * ‘/usr/bin/python’

   * ‘/usr/local/bin/python‘’

   * ‘python’

例如，如果脚本开始的第一行

     #! /usr/bin/python

将找到并使用默认的Python。因为在Unix上编写的许多Python脚本已经有了这一行
，你应该发现这些脚本可以由启动器使用而无需修改。如果您在Windows上编写一
个新脚本，希望在Unix上有用，那么您应该使用以 ‘/usr’ 开头的一个shebang行
。

任何上述虚拟命令都可以显式指定版本（可以仅为主要版本，也可以为主要版本加
次要版本）作为后缀。 此外，可以通过在次要版本之后添加 “-32” 来请求 32 位
版本。 例如 ‘/usr/bin/python2.7-32’ 将请求使用 32 位 python 2.7。

3.7 版新加入: 从python启动程序3.7开始，可以通过“-64”后缀调用64位版本。此
外，可以指定没有次要的主要和架构（即 ‘/usr/bin/python3-64’ ）。

shebang line的 ‘/usr/bin/env’ 形式还有一个特殊属性。在寻找已安装的
Python解释器之前，此表单将搜索可执行文件 ‘PATH’ 以获取Python可执行文件。
这对应于Unix中 ‘env’ 程序的行为，该程序将在 ‘PATH’ 执行搜索。


File: python.info,  Node: shebang lines 的参数,  Next: 自定义,  Prev: Shebang Lines,  Up: 适用于Windows的Python启动器

3.3.8.7 shebang lines 的参数
............................

shebang lines 还可以指定要传递给Python解释器的其他选项。例如，如果你有一
个shebang lines ：

     #! /usr/bin/python -v

然后Python将以 ‘-v’ 选项启动


File: python.info,  Node: 自定义,  Next: 诊断,  Prev: shebang lines 的参数,  Up: 适用于Windows的Python启动器

3.3.8.8 自定义
..............

* Menu:

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


File: python.info,  Node: 通过INI文件自定义,  Next: 自定义默认的Python版本,  Up: 自定义

3.3.8.9 通过INI文件自定义
.........................

启动程序将搜索两个.ini文件 - 在当前用户的 "application data" 目录中搜索
‘py.ini’ （即通过使用 ‘CSIDL_LOCAL_APPDATA’ 调用Windows函数
‘SHGetFolderPath’ 返回的目录）以及与启动器位于同一目录中的 ‘py.ini’ 。相
同的.ini文件既用于启动器的“控制台”版本（即 py.exe），也用于“windows”版本
（即pyw.exe）

“应用程序目录”中指定的自定义优先于可执行文件旁边.ini文件的自定义，因此对
启动程序旁边的.ini文件不具有写访问权限的用户可以覆盖该全局.ini文件中的命
令。


File: python.info,  Node: 自定义默认的Python版本,  Prev: 通过INI文件自定义,  Up: 自定义

3.3.8.10 自定义默认的Python版本
...............................

在某些情况下，可以在命令中包含版本限定符，以指定命令将使用哪个Python版本
。版本限定符以主版本号开头，可以选择后跟 (’.’) 和次版本说明符。此外，可
以通过添加 "-32" 或 “-64” 来指定是请求32位还是64位实现。

例如，一个shebang line 的 ‘#!python’ 行没有版本限定符，而 ‘#!python3’ 有
一个版本限定符，它只指定一个主要版本。

如果在命令中找不到版本限定符，则可以设置环境变量 ‘PY_PYTHON’ 以指定默认
版本限定符。 如果未设置，则默认为 "3"。 该变量可以指定能通过命令行传递的
任何值，比如 "3", "3.7", "3.7-32" 或 "3.7-64"。 （请注意 "-64" 选项仅适
用于 Python 3.7 或更高版本中包含的启动器。）

如果没有找到次要版本限定符，则可以设置环境变量 ‘PY_PYTHON{major}’ （其中
‘{major}’ 是上面确定的当前主要版本限定符）以指定完整版本。如果没有找到这
样的选项，启动器将枚举已安装的Python版本并使用为主要版本找到的最新次要版
本，尽管不能保证，但该版本可能是该系列中最新安装的版本。

在安装了相同（major.minor）Python版本的32位和64位的64位Windows上，64位版
本将始终是首选。对于启动程序的32位和64位实现都是如此 – 这对于启动程序
32位和64位都是正确的 – 如果可用，32位启动程序将倾向于执行指定版本的64位
Python安装。这样就可以预测启动器的行为，只知道PC上安装了哪些版本，而不考
虑它们的安装顺序（即，不知道32位或64位版本的Python和相应的启动器是否是最
后安装）。如上所述，可以在版本说明符上使用可选的“-32”或“-64”后缀来更改此
行为。

示例：

   * 如果没有设置相关选项，命令 ‘python’ 和 ‘python2’ 将使用安装的最新
     Python 2.x版本，命令 ‘python3’ 将使用最新安装的Python 3.x.

   * 命令 ‘python3.1’ 和 ‘python2.7’ 根本不会查阅任何选项，因为版本已完
     全指定。

   * 如果 ‘PY_PYTHON=3’ ，命令‘‘python‘‘ 和 ‘python3’ 都将使用最新安装的
     Python 3版本。

   * 如果 ‘PY_PYTHON=3.1-32’ ，命令 ‘python’ 将使用3.1的32位实现，而命令
     ‘python3’ 将使用最新安装的Python（PY_PYTHON根本没有被视为指定了主要
     版本。）

   * 如果 ‘PY_PYTHON=3’ 且 ‘PY_PYTHON3=3.1’，命令 ‘python’ 和 ‘python3’
     都将特别使用3.1

除环境变量外，还可以在启动程序使用的.INI文件中配置相同的设置。 INI文件中
的部分称为 ‘[defaults]’ ，键名称将与没有前导 ‘PY_’ 前缀的环境变量相同（
并注意INI文件中的键名不区分大小写） 。）环境变量的内容将覆盖INI文件中指
定的内容。

例如:

   * 设置 ‘PY_PYTHON=3.1’ 等同于包含以下内容的INI文件：

     [defaults]
     python=3.1

   * 设置 ‘PY_PYTHON=3’ 和 ‘PY_PYTHON3=3.1’ 相当于包含以下内容的INI文件
     ：

     [defaults]
     python=3
     python3=3.1


File: python.info,  Node: 诊断,  Prev: 自定义,  Up: 适用于Windows的Python启动器

3.3.8.11 诊断
.............

如果设置了环境变量 ‘PYLAUNCH_DEBUG’ （任何值），启动器将诊断信息打印到
stderr（即：控制台）。虽然这些信息同时具有冗长 `和' 简洁性，但它应该允许
您查看Python的版本、选择特定版本的原因以及用于执行目标Python的确切命令行
。


File: python.info,  Node: 查找模块,  Next: 附加模块,  Prev: 适用于Windows的Python启动器,  Up: 在 Windows 上使用 Python

3.3.9 查找模块
--------------

Python通常将其库（以及您的site-packages文件夹）存储在安装目录中。因此，
如果您已将Python安装到 ‘C:\Python\’ ，则默认库将驻留在 ‘C:\Python\Lib\’
中，第三方模块存储在 ‘C:\Python\Lib\site-packages\’ 。

若要完全覆盖 *note sys.path: 261. ，请创建与DLL(‘python37._pth’)或可执行
文件(“python._pth‘”)同名的 ‘._pth’ 文件，并为要添加的每个路径指定一行
*note sys.path: 261. 。基于DLL名称的文件覆盖基于可执行文件的文件，如果需
要，可以为加载运行时的任何程序限制路径。

当文件存在时，将忽略所有注册表和环境变量，启用隔离模式，并且：除非文件中
的一行指定 ‘import site’ ，否则不会导入 *note site: eb. 。以 ‘＃’ 开头的
空白路径和行将被忽略。每个路径可以是绝对的或相对于文件的位置。不允许使用
除 ‘site’ 以外的导入语句，并且不能指定任意代码。

请注意，当指定 ‘import site’ 时， ‘.pth’ 文件（没有前导下划线）将由
*note site: eb. 模块正常处理。

当找不到 ‘._pth’ 文件时， *note sys.path: 261. 是如何在Windows上填充的：

   * 在开始时，添加一个空条目，该条目对应于当前目录。

   * 如果环境变量 *note PYTHONPATH: a34. 存在，如 *note 环境变量: 1485.
     中所述，则接下来添加其条目。请注意，在Windows上，此变量中的路径必须
     用分号分隔，以区别于驱动器标识符中使用的冒号（ ‘C:\’ 等）。

   * 额外的 "应用程序路径" 可以作为子键被同时添加到注册表
     ‘HKEY_CURRENT_USER’ 和 ‘HKEY_LOCAL_MACHINE’ 分支下的
     ‘\SOFTWARE\Python\PythonCore{version}\PythonPath’ 中。 以分号分隔的
     路径字符串作为默认值的子键将导致每个路径都被添加到 *note sys.path:
     261. 中。 （请注意所有已知的安装程序都只使用 HKLM，因此 HKCU 通常为
     空。）

   * 如果设置了环境变量 *note PYTHONHOME: 5d0. ，则将其假定为 “Python 主
     目录” 。否则，主Python可执行文件的路径用于定位 “landmark 文件” （
     ‘Lib\os.py’ 或 ‘pythonXY.zip’ ）以推断 ”Python 主目录“ 。如果找到了
     Python主目录，则基于该文件夹将相关的子目录添加到 *note sys.path:
     261. （‘Lib’ , ‘plat-win’ 等）。否则，核心Python路径是从存储在注册
     表中的PythonPath构造的。

   * 如果找不到Python Home，也没有指定 *note PYTHONPATH: a34. 环境变量，
     并且找不到注册表项，则使用具有相对条目的默认路径（例如 ‘.\Lib;
     .\plat-win’ 等等）。

如果在主可执行文件旁边或在可执行文件上一级的目录中找到 ‘pyvenv.cfg’ 文件
，则以下变体适用：

   * 如果 ‘home’ 是一个绝对路径，并且 *note PYTHONHOME: 5d0. 未设置，则
     在推断起始位置时使用此路径而不是主可执行文件的路径。

最終這所有的結果為：

   * 运行 ‘python.exe’ ，或主Python目录中的任何其他.exe（安装版本，或直
     接来自PCbuild目录）时，推导出核心路径，并忽略注册表中的核心路径。始
     终读取注册表中的其他“应用程序路径”。

   * 当Python托管在另一个.exe（不同的目录，通过COM嵌入等）时，将不会推断
     出“Python Home”，因此使用了来自注册表的核心路径。始终读取注册表中的
     其他“应用程序路径”。

   * 如果Python找不到它的主目录并且没有注册表值（冻结的.exe，一些非常奇
     怪的安装设置），那么你会得到一条带有一些默认但相对的路径的路径。

对于那些想要将Python捆绑到其应用程序或发行版中的人，以下建议将防止与其他
安装冲突：

   * 在您的可执行文件中包含一个 ‘._pth’ 文件，其中包含目录。这将忽略注册
     表和环境变量中列出的路径，并忽略 *note site: eb. ，除非列出 ‘import
     site’ 。

   * 如果你在自己的可执行文件中加载 ‘python3.dll’ 或 ‘python37.dll’ ，在
     *note Py_Initialize(): 20f. 之前，要显式调用 *note Py_SetPath():
     39c. 或（至少） *note Py_SetProgramName(): 10f2.

   * 清除 和/或 覆盖 *note PYTHONPATH: a34. 并在启动来自应用程序的
     ‘python.exe’ 之前设置 *note PYTHONHOME: 5d0. 。

   * 如果您不能使用前面的建议（例如，您是一个允许人们直接运行
     ‘python.exe’ 的分发版），请确保安装目录中存在 landmark 文件
     (‘Lib\os.py’)。 （请注意，在 ZIP 文件中不会检测到该文件，但会检测到
     正确命名的 ZIP 文件。）

这些将确保系统范围安装中的文件不会优先于与应用程序捆绑在一起的标准库的副
本。否则，用户可能会在使用您的应用程序时遇到问题请注意，第一个建议是最好
的，因为其他建议可能仍然容易受到注册表和用户站点包中的非标准路径的影响。

     3.6 版更變:

        * 添加 ‘._pth’ 文件支持并从 ‘pyvenv.cfg’ 中删除 ‘applocal’ 选项

        * 当直接与可执行文件相邻时，添加 ‘pythonXX.zip’ 作为潜在的
          landmark 。

     3.6 版後已棄用: 在 ‘Modules’ （不是 ‘PythonPath’ ）下的注册表中指定
     的模块可以通过以下方式导入 *note
     importlib.machinery.WindowsRegistryFinder: 6dc. 。在Windows上，此查
     找程序在3.6.0及更早版本的可用，但可能需要在将来显式添加到 *note
     sys.meta_path: 6dd.


File: python.info,  Node: 附加模块,  Next: 編譯 Python 在 Windows,  Prev: 查找模块,  Up: 在 Windows 上使用 Python

3.3.10 附加模块
---------------

尽管Python的目标是在所有平台中都可移植，但是Windows有一些独特的特性。在
标准库和外部都有一些模块和代码片段在使用这些特性。

特定于Windows的标准模块记录在 *note Windows系统相关模块: 14c7. 中。

* Menu:

* PyWin32::
* cx_Freeze::
* WConio::


File: python.info,  Node: PyWin32,  Next: cx_Freeze,  Up: 附加模块

3.3.10.1 PyWin32
................

Mark Hammond 的 PyWin32(1) 模块是一组用于高级Windows特定支持的模块。这包
括以下实用程序：

   * 组件对象模型(2) (COM)

   * Win32 API 调用

   * 登錄檔（Registry）

   * 事件日誌（Event log）

   * Microsoft Foundation Classes(3) (MFC) 用户界面

PythonWin(4) 是PyWin32附带的一个示例MFC应用程序。它是一个内置调试器的可
嵌入IDE。

也參考
......

Win32 How Do I...?(5)

     Tim Golden 著

Python and COM(6)

     David 和 Paul Boddie 著

   ---------- Footnotes ----------

   (1) https://pypi.org/project/pywin32

   (2) 
https://docs.microsoft.com/en-us/windows/desktop/com/component-object-model–com–portal

   (3) https://msdn.microsoft.com/en-us/library/fe1cf721%28VS.80%29.aspx

   (4) 
https://web.archive.org/web/20060524042422/https://www.python.org/windows/pythonwin/

   (5) http://timgolden.me.uk/python/win32_how_do_i.html

   (6) http://www.boddie.org.uk/python/COM.html


File: python.info,  Node: cx_Freeze,  Next: WConio,  Prev: PyWin32,  Up: 附加模块

3.3.10.2 cx_Freeze
..................

cx_Freeze(1) 是一个 *note distutils: 38. 的扩展 (参见 *note 扩展
Distutils: 14ca.)，它将 Python 脚本包装成可执行的 Windows 程序
(‘`*'.exe’ 文件)。 完成此操作后，你就可以分发你的应用程序而无需用户安装
Python。

   ---------- Footnotes ----------

   (1) https://cx-freeze.readthedocs.io/en/latest/


File: python.info,  Node: WConio,  Prev: cx_Freeze,  Up: 附加模块

3.3.10.3 WConio
...............

由于Python的高级终端处理层 *note curses: 2b. 仅限于类Unix系统，因此
Windows还有一个独立的库：用于Python的Windows 控制台 I/O .

WConio(1) 是Turbo-C的 ‘CONIO.H’ 装饰器,用于创建文本用户界面。

   ---------- Footnotes ----------

   (1) http://newcenturycomputers.net/projects/wconio.html


File: python.info,  Node: 編譯 Python 在 Windows,  Next: 其他平台,  Prev: 附加模块,  Up: 在 Windows 上使用 Python

3.3.11 編譯 Python 在 Windows
-----------------------------

如果你想自己编译CPython，首先要做的是获取 source(1). 。您可以下载最新版
本的源代码，也可以重新签出 checkout(2). 。

源代码树包含Microsoft Visual Studio 2015的构建解决方案和项目文件，它是用
于构建官方Python版本的编译器。这些文件位于 ‘PCbuild’ 目录中。

检查 ‘PCbuild/readme.txt’ 以获取有关构建过程的一般信息。

有关扩展模块，请参阅 *note 在 Windows 上构建 C 和 C++ 扩展: 14cd. 。

也參考
......

Python + Windows + distutils + SWIG + gcc MinGW(3)

     或 "Creating Python extensions in C/C++ with SWIG and compiling
     them with MinGW gcc under Windows" 或 "Installing Python extension
     with distutils and without Microsoft Visual C++" by Sébastien
     Sauvage, 2003

   ---------- Footnotes ----------

   (1) https://www.python.org/downloads/source/

   (2) https://devguide.python.org/setup/#getting-the-source-code

   (3) http://sebsauvage.net/python/mingw.html


File: python.info,  Node: 其他平台,  Prev: 編譯 Python 在 Windows,  Up: 在 Windows 上使用 Python

3.3.12 其他平台
---------------

随着Python的不断发展，不再支持以前曾经支持的一些平台（由于缺少用户或开发
人员）。检查 PEP 11(1) 了解所有不支持的平台的详细信息。

   * Windows CE(2) 仍然受支持。

   * Cygwin(3) 安装包也提供安装Python解释器 (cf.  Cygwin package
     source(4), Maintainer releases(5))

有关具有预编译安装程序平台的详细信息，请参阅 Python for Windows(6)

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0011

   (2) http://pythonce.sourceforge.net/

   (3) https://cygwin.com/

   (4) 
ftp://ftp.uni-erlangen.de/pub/pc/gnuwin32/cygwin/mirrors/cygnus/release/python

   (5) http://www.tishler.net/jason/software/python/

   (6) https://www.python.org/downloads/windows/


File: python.info,  Node: 在 Mac 系統使用Python,  Next: 编辑器和集成开发环境,  Prev: 在 Windows 上使用 Python,  Up: Python 的設置與使用

3.4 在 Mac 系統使用Python
=========================


作者: Bob Savage <<bobsavage@mac.com>>

Python 執行在 Mac 的 macOS 和執行在其他 Unix 平台上原理非常相似，但值得
一提的是在 macOS 上有其他額外的功能，例如 IDE 與 套件管理。

* Menu:

* 取得和安裝 MacPython::
* 整合化開發工具::
* 安装额外的 Python 包::
* 圖形化使用者介面(GUI) 程式開發於Mac: 圖形化使用者介面 GUI 程式開發於Mac.
* 貢獻Python應用程式於 Mac::
* 其他資源::


File: python.info,  Node: 取得和安裝 MacPython,  Next: 整合化開發工具,  Up: 在 Mac 系統使用Python

3.4.1 取得和安裝 MacPython
--------------------------

Apple 在 macOS 10.8 預設安裝 Python 2.7。但你也可以到 Python website （
‘https://www.python.org’ ）更新至最新的 Python 3。Python 建立在"通用二進
位"上，使 Python 能以本地程序的形式運行在使用英特爾微處理器與 PowerPC 麥
金塔電腦上。

在安裝後你必須要做幾件事：

   * 会有一个 ‘Python 3.9’ 文件夹在你的 ‘Applications’ 文件夹中。 在这里
     你可以找到 IDLE，它是作为官方 Python 发行版标准组成部分的开发环境；
     以及 PythonLauncher，它负责处理在 Finder 中双击 Python 脚本的操作。

   * 框架 ‘/Library/Frameworks/Python.framework’ ，包括 Python 可执行文
     件和库。安装程序将此位置添加到 shell 路径。 要卸载 MacPython ，你可
     以简单地移除这三个项目。 Python 可执行文件的符号链接放在
     /usr/local/bin/ 中。

Apple 提供的 Python 版本分别安装在
‘/System/Library/Frameworks/Python.framework’ 和 ‘/usr/bin/python’ 中。
你永远不应修改或删除这些内容，因为它们由 Apple 控制并由 Apple 或第三方软
件使用。 请记住，如果你选择从 python.org 安装较新的 Python 版本，那么你
的计算机上将安装两个不同但都有用的 Python ，因此你的路径和用法与你想要执
行的操作一致非常重要。

IDLE 包含一个帮助菜单，允许你访问 Python 文档。 如果您是 Python 的新手，
你应该开始阅读该文档中的教程介绍。

如果你熟悉其他 Unix 平台上的 Python ，那么你应该阅读有关从 Unix shell 运
行 Python 脚本的部分。

* Menu:

* 如何執行Python腳本::
* 透過使用者圖形介面執行腳本::
* 設定::


File: python.info,  Node: 如何執行Python腳本,  Next: 透過使用者圖形介面執行腳本,  Up: 取得和安裝 MacPython

3.4.1.1 如何執行Python腳本
..........................

Your best way to get started with Python on macOS is through the IDLE
integrated development environment, see section *note 整合化開發工具:
14d5. and use the Help menu when the IDE is running.

If you want to run Python scripts from the Terminal window command line
or from the Finder you first need an editor to create your script.
macOS comes with a number of standard Unix command line editors, ‘vim’
and ‘emacs’ among them.  If you want a more Mac-like editor, ‘BBEdit’ or
‘TextWrangler’ from Bare Bones Software (see
‘http://www.barebones.com/products/bbedit/index.html’) are good choices,
as is ‘TextMate’ (see ‘https://macromates.com/’).  Other editors include
‘Gvim’ (‘http://macvim-dev.github.io/macvim/’) and ‘Aquamacs’
(‘http://aquamacs.org/’).

要从终端窗口运行脚本，必须确保:file:‘/usr/local/bin’ 位于 shell 搜索路径
中。

從Finder執行你的腳本時，你有兩個選項:

   * 把脚本拖拽到 ‘PythonLauncher’

   * 选择 ‘PythonLauncher’ 作为通过 finder Info 窗口打开脚本（或任何 .py
     脚本）的默认应用程序，然后双击脚本。 ‘PythonLauncher’ 有各种首选项
     来控制脚本的启动方式。 拖拽方式允许你为一次调用更改这些选项，或使用
     其“首选项”菜单全局更改内容。


File: python.info,  Node: 透過使用者圖形介面執行腳本,  Next: 設定,  Prev: 如何執行Python腳本,  Up: 取得和安裝 MacPython

3.4.1.2 透過使用者圖形介面執行腳本
..................................

With older versions of Python, there is one macOS quirk that you need to
be aware of: programs that talk to the Aqua window manager (in other
words, anything that has a GUI) need to be run in a special way.  Use
‘pythonw’ instead of ‘python’ to start such scripts.

对于 Python 3.9，你可以使用 ‘python’ 或者 ‘pythonw’。


File: python.info,  Node: 設定,  Prev: 透過使用者圖形介面執行腳本,  Up: 取得和安裝 MacPython

3.4.1.3 設定
............

Python on macOS honors all standard Unix environment variables such as
*note PYTHONPATH: a34, but setting these variables for programs started
from the Finder is non-standard as the Finder does not read your
‘.profile’ or ‘.cshrc’ at startup.  You need to create a file
‘~/.MacOSX/environment.plist’.  See Apple’s Technical Document QA1067
for details.

更多关于在 MacPython 中安装 Python 包的信息，参阅 *note 安装额外的
Python 包: 14d9. 部分。


File: python.info,  Node: 整合化開發工具,  Next: 安装额外的 Python 包,  Prev: 取得和安裝 MacPython,  Up: 在 Mac 系統使用Python

3.4.2 整合化開發工具
--------------------

MacPython 附带标准的 IDLE 开发环境。 有关使用 IDLE 的详细介绍，请访问
‘http://www.hashcollision.org/hkn/python/idle_intro/index.html’ 。


File: python.info,  Node: 安装额外的 Python 包,  Next: 圖形化使用者介面 GUI 程式開發於Mac,  Prev: 整合化開發工具,  Up: 在 Mac 系統使用Python

3.4.3 安装额外的 Python 包
--------------------------

有几个方法可以安装额外的 Python 包：

   * 可以通过标准的 Python distutils 模式（ ‘python setup.py install’ ）
     安装软件包。

   * 许多包也可以通过 ‘setuptools’ 扩展或 ‘pip’ 包装器安装，请参阅
     ‘https://pip.pypa.io/’ 。


File: python.info,  Node: 圖形化使用者介面 GUI 程式開發於Mac,  Next: 貢獻Python應用程式於 Mac,  Prev: 安装额外的 Python 包,  Up: 在 Mac 系統使用Python

3.4.4 圖形化使用者介面(GUI) 程式開發於Mac
-----------------------------------------

有許多建立圖形化使用者介面(GUI)應用程式選項使用Python於Mac上

`PyObjC' 是一个 Python 到 Apple 的 Objective-C/Cocoa 框架的绑定，这是大
多数现代 Mac 开发的基础。 有关 PyObjC 的信息，请访问
‘https://pypi.org/project/pyobjc/’。

标准的 Python GUI 工具包是 *note tkinter: 10e. ，基于跨平台的 Tk 工具包
（ ‘https://www.tcl.tk’ ）。 Apple 的 OS X 捆绑了 Aqua 原生版本的 Tk ，
最新版本可以从 ‘https://www.activestate.com’ 下载和安装；它也可以从源代
码构建。

`wxPython' is another popular cross-platform GUI toolkit that runs
natively on macOS. Packages and documentation are available from
‘https://www.wxpython.org’.

`PyQt' is another popular cross-platform GUI toolkit that runs natively
on macOS. More information can be found at
‘https://riverbankcomputing.com/software/pyqt/intro’.


File: python.info,  Node: 貢獻Python應用程式於 Mac,  Next: 其他資源,  Prev: 圖形化使用者介面 GUI 程式開發於Mac,  Up: 在 Mac 系統使用Python

3.4.5 貢獻Python應用程式於 Mac
------------------------------

在 Mac 上部署独立 Python 应用程序的标准工具是 ‘py2app’ 。有关安装和使用
py2app 的更多信息，请访问 ‘http://undefined.org/python/#py2app’ 。


File: python.info,  Node: 其他資源,  Prev: 貢獻Python應用程式於 Mac,  Up: 在 Mac 系統使用Python

3.4.6 其他資源
--------------

MacPython 郵件清單對於Python使用者和開發者於Mac 上是一個極佳的支援資源

‘https://www.python.org/community/sigs/current/pythonmac-sig/’

其他好用的資源是MacPython wiki:

‘https://wiki.python.org/moin/MacPython’


File: python.info,  Node: 编辑器和集成开发环境,  Prev: 在 Mac 系統使用Python,  Up: Python 的設置與使用

3.5 编辑器和集成开发环境
========================

有很多支持Python编程语言的集成开发环境。大多数编辑器和集成开发环境支持语
法高亮，调试工具和 PEP 8(1) 检查。

请访问 Python Editors(2) 和 Integrated Development Environments(3) 以获
取完整列表。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0008

   (2) https://wiki.python.org/moin/PythonEditors

   (3) https://wiki.python.org/moin/IntegratedDevelopmentEnvironments


File: python.info,  Node: Python 語言參考手冊,  Next: Python 標準函式庫 Standard Library,  Prev: Python 的設置與使用,  Up: Top

4 Python 語言參考手冊
*********************

這份參考手冊會描述 Python 語言的語法及「核心語意」。它雖然簡潔，但也盡量
保持精確並完整。關於非必要的 (non-essential) 內建物件型別、內建函式及模
組的語意，則在 *note Python 標準函式庫 (Standard Library): 1330. 中說明
。關於此語言的非正式介紹，請參閱 *note Python 教學: 132f.。對於 C 或 C++
程式設計師，還有另外兩個手冊：*note 擴充和嵌入 Python 直譯器: 1332.以高
階的視野說明如何編寫 Python 擴充模組，而 *note Python/C API 參考手冊:
1333.則詳細說明 C/C++ 程式設計師可用的介面。

* Menu:

* 簡介: 簡介<5>.
* 词法分析::
* 数据模型::
* 执行模型::
* 导入系统::
* 表达式::
* 简单语句::
* 复合语句::
* 顶级组件::
* 完整的語法規格書::


File: python.info,  Node: 簡介<5>,  Next: 词法分析,  Up: Python 語言參考手冊

4.1 簡介
========

本手册仅描述 Python 编程语言，不宜当作教程。

我希望尽可能地保证内容精确无误，但还是选择使用自然词句进行描述，正式的规
格定义仅用于句法和词法解析。这样应该能使文档对于普通人来说更易理解，但也
可能导致一些歧义。因此，如果你是来自火星并且想凭借这份文档把 Python 重新
实现一遍，也许有时需要自行猜测，实际上最终大概会得到一个十分不同的语言。
而在另一方面，如果你正在使用 Python 并且想了解有关该语言特定领域的精确规
则，你应该能够在这里找到它们。如果你希望查看对该语言更正式的定义，也许你
可以花些时间自己写上一份 — 或者发明一台克隆机器 :-)

在语言参考文档里加入过多的实现细节是很危险的 — 具体实现可能发生改变，对
同一语言的其他实现可能使用不同的方式。而在另一方面，CPython 是得到广泛使
用的 Python 实现 (然而其他一些实现的拥护者也在增加)，其中的特殊细节有时
也值得一提，特别是当其实现方式导致额外的限制时。因此，你会发现在正文里不
时会跳出来一些简短的 "实现注释"。

每种 Python 实现都带有一些内置和标准的模块。相关的文档可参见 *note
Python 標準函式庫 (Standard Library): 1330. 索引。少数内置模块也会在此提
及，如果它们同语言描述存在明显的关联。

* Menu:

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


File: python.info,  Node: 其他实现,  Next: 标注,  Up: 簡介<5>

4.1.1 其他实现
--------------

虽然官方 Python 实现差不多得到最广泛的欢迎，但也有一些其他实现对特定领域
的用户来说更具吸引力。

知名的实现包括:

CPython

     这是最早出现并持续维护的 Python 实现，以 C 语言编写。新的语言特性通
     常在此率先添加。

Jython

     以 Java 语言编写的 Python 实现。此实现可以作为 Java 应用的一个脚本
     语言，或者可以用来创建需要 Java 类库支持的应用。想了解更多信息可访
     问 Jython 网站(1)。

Python for .NET

     此实现实际上使用了 CPython 实现，但是属于 .NET 托管应用并且可以引入
     .NET 类库。它的创造者是 Brian Lloyd。想了解详情可访问 Python for
     .NET 主页(2)。

IronPython

     另一个 .NET 的 Python 实现，与 Python.NET 不同点在于它是生成 IL 的
     完全 Python 实现，并且将 Python 代码直接编译为 .NET 程序集。它的创
     造者就是当初创造 Jython 的 Jim Hugunin。想了解详情可访问 IronPython
     网站(3)。

PyPy

     完全使用 Python 语言编写的 Python 实现。它支持多个其他实现所没有的
     高级特性，例如非栈式支持和 JIT 编译器等。此项目的目标之一是通过允许
     方便地修改解释器 (因为它是用 Python 编写的)，鼓励该对语言本身进行试
     验。想了解详情可访问 PyPy 项目主页(4)。

以上这些实现都可能在某些方面与此参考文档手册的描述有所差异，或是引入了超
出标准 Python 文档范围的特定信息。请参考它们各自的专门文档，以确定你正在
使用的这个实现有哪些你需要了解的东西。

   ---------- Footnotes ----------

   (1) http://www.jython.org/

   (2) https://pythonnet.github.io/

   (3) http://ironpython.net/

   (4) http://pypy.org/


File: python.info,  Node: 标注,  Prev: 其他实现,  Up: 簡介<5>

4.1.2 标注
----------

句法和词法解析的描述采用经过改进的 BNF 语法标注。这包含以下定义样式:

     name      ::= lc_letter (lc_letter | "_")*
     lc_letter ::= "a"..."z"

第一行表示 ‘name’ 是 ‘lc_letter’ 之后跟零个或多个 ‘lc_letter’ 和下划线。
而 ‘lc_letter’ 则是任意单个 ‘'a'’ 至 ‘'z'’ 字符。(实际上在本文档中始终采
用此规则来定义词法和语法规则的名称。)

每条规则的开头是一个名称 (即该规则所定义的名称) 加上 ‘::=’。 竖线 (‘|’)
被用来分隔可选项，它是此标注中绑定程度最低的操作符。 星号 (‘*’) 表示前一
项的零次或多次重复，类似地，加号 (‘+’) 表示一次或多次重复，而由方括号括
起的内容 (‘[ ]’) 表示出现零次或一次 (或者说，这部分内容是可选的)。 ‘*’ 和
‘+’ 操作符的绑定是最紧密的，圆括号用于分组。 字符串字面值包含在引号内。
空格的作用仅限于分隔形符。 每条规则通常为一行，有许多个可选项的规则可能
会以竖线为界分为多行。

在词法定义中 (如上述示例)，还额外使用了两个约定: 由三个点号分隔的两个字
符字面值表示在指定 (闭) 区间范围内的任意单个 ASCII 字符。由尖括号
(‘<...>’) 括起来的内容是对于所定义符号的非正式描述；即可以在必要时用来说
明 ’控制字符’ 的意图。

虽然所用的标注方式几乎相同，但是词法定义和句法定义是存在很大区别的: 词法
定义作用于输入源中单独的字符，而句法定义则作用于由词法分析所生成的形符流
。在下一章节 ("词法分析") 中使用的 BNF 全部都是词法定义；在之后的章节中
使用的则是句法定义。


File: python.info,  Node: 词法分析,  Next: 数据模型,  Prev: 簡介<5>,  Up: Python 語言參考手冊

4.2 词法分析
============

Python 程序由 `解析器' 读取，输入解析器的是 `词法分析器' 生成的 `形符' 流
。本章介绍词法分析器怎样把文件拆成形符。

Python 将读取的程序文本转为 Unicode 代码点；编码声明用于指定源文件的编码
，默认为 UTF-8，详见 PEP 3120(1)。源文件不能解码时，触发 *note
SyntaxError: 559.。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3120


File: python.info,  Node: 行结构,  Next: 其他形符,  Up: 词法分析

4.2.1 行结构
------------

Python 程序可以拆分为多个 `逻辑行'。

* Menu:

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


File: python.info,  Node: 逻辑行,  Next: 物理行,  Up: 行结构

4.2.1.1 逻辑行
..............

NEWLINE 形符表示结束逻辑行。语句不能超出逻辑行的边界，除非句法支持
NEWLINE （例如，复合语句中的多行子语句）。根据显式或隐式 `行拼接' 规则，
一个或多个 `物理行' 可组成逻辑行。


File: python.info,  Node: 物理行,  Next: 注释,  Prev: 逻辑行,  Up: 行结构

4.2.1.2 物理行
..............

物理行是一序列字符，由行尾序列终止。源文件和字符串可使用任意标准平台行终
止序列 - Unix ASCII 字符 LF （换行）、 Windows ASCII 字符序列 CR LF （回
车换行）、或老式 Macintosh ASCII 字符 CR （回车）。不管在哪个平台，这些
形式均可等价使用。输入结束也可以用作最终物理行的隐式终止符。

嵌入 Python 时，传入 Python API 的源码字符串应使用 C 标准惯例换行符（
‘\n’，代表 ASCII 字符 LF， 行终止符）。


File: python.info,  Node: 注释,  Next: 编码声明,  Prev: 物理行,  Up: 行结构

4.2.1.3 注释
............

注释以井号 （‘#’） 开头，在物理行末尾截止。注意，井号不是字符串字面值。
除非应用隐式行拼接规则，否则，注释代表逻辑行结束。句法不解析注释。


File: python.info,  Node: 编码声明,  Next: 显式拼接行,  Prev: 注释,  Up: 行结构

4.2.1.4 编码声明
................

Python 脚本第一或第二行的注释匹配正则表达式 ‘coding[=:]\s*([-\w.]+)’ 时
，该注释会被当作编码声明；这个表达式的第一组指定了源码文件的编码。编码声
明必须独占一行，在第二行时，则第一行必须也是注释。编码表达式的形式如下：

     # -*- coding: <encoding-name> -*-

这也是 GNU Emacs 认可的形式，此外，还支持如下形式：

     # vim:fileencoding=<encoding-name>

这是 Bram Moolenaar 的 VIM 认可的形式。

没有编码声明时，默认编码为 UTF-8。此外，如果文件的首字节为 UTF-8 字节顺
序标志（‘b'\xef\xbb\xbf'’），文件编码也声明为 UTF-8（这是 Microsoft 的
‘notepad’ 等软件支持的形式）。

声明的编码名称必须是 Python 能识别的。语义字符串、注释和标识符等词法分析
都使用此编码。


File: python.info,  Node: 显式拼接行,  Next: 隐式拼接行,  Prev: 编码声明,  Up: 行结构

4.2.1.5 显式拼接行
..................

两个及两个以上的物理行可用反斜杠（‘\’）拼接为一个逻辑行，规则如下：以不
在字符串或注释内的反斜杠结尾时，物理行将与下一行拼接成一个逻辑行，并删除
反斜杠及其后的换行符。例如：

     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

以反斜杠结尾的行，不能加注释；反斜杠也不能拼接注释。除字符串字面值外，反
斜杠不能拼接形符（如，除字符串字面值外，不能用反斜杠把形符切分至两个物理
行）。反斜杠只能在代码的字符串字面值里，在其他任何位置都是非法的。


File: python.info,  Node: 隐式拼接行,  Next: 空白行,  Prev: 显式拼接行,  Up: 行结构

4.2.1.6 隐式拼接行
..................

圆括号、方括号、花括号内的表达式可以分成多个物理行，不必使用反斜杠。例如
：

     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

隐式行拼接可含注释；后续行的缩进并不重要；还支持空的后续行。隐式拼接行之
间没有 NEWLINE 形符。三引号字符串支持隐式拼接行（见下文），但不支持注释
。


File: python.info,  Node: 空白行,  Next: 缩进,  Prev: 隐式拼接行,  Up: 行结构

4.2.1.7 空白行
..............

只包含空格符、制表符、换页符、注释的逻辑行会被忽略（即不生成 NEWLINE 形
符）。交互模式输入语句时，空白行的处理方式可能因读取 - 求值 - 打印循环（
REPL）的具体实现方式而不同。标准交互模式解释器中，完全空白的逻辑行（即连
空格或注释都没有）将结束多行复合语句。


File: python.info,  Node: 缩进,  Next: 形符间的空白字符,  Prev: 空白行,  Up: 行结构

4.2.1.8 缩进
............

逻辑行开头的空白符（空格符和制表符）用于计算该行的缩进层级，决定语句组块
。

制表符（从左至右）被替换为一至八个空格，缩进空格的总数是八的倍数（与
Unix 的规则保持一致）。首个非空字符前的空格数决定了该行的缩进层次。缩进
不能用反斜杠进行多行拼接；首个反斜杠之前的空白符决定了缩进的层次。

源文件混用制表符和空格符缩进时，因空格数量与制表符相关，由此产生的不一致
将导致不能正常识别缩进层次，从而触发 *note TabError: f38.。

`跨平台兼容性说明：' 鉴于非 UNIX 平台文本编辑器本身的特性，请勿在源文件
中混用制表符和空格符。另外也请注意，不同平台有可能会显式限制最大缩进层级
。

行首含换页符时，缩进计算将忽略该换页符。换页符在行首空白符内其他位置的效
果未定义（例如，可能导致空格计数重置为零）。

连续行的缩进层级以堆栈形式生成 INDENT 和 DEDENT 形符，说明如下。

读取文件第一行前，先向栈推入一个零值，该零值不会被移除。推入栈的层级值从
底至顶持续增加。每个逻辑行开头的行缩进层级将与栈顶行比较。如果相等，则不
做处理。如果新行层级较高，则会被推入栈顶，并生成一个 INDENT 形符。如果新
行层级较低，则 `应当' 是栈中的层级数值之一；栈中高于该层级的所有数值都将
被移除，每移除一级数值生成一个 DEDENT 形符。文件末尾，栈中剩余的每个大于
零的数值生成一个 DEDENT 形符。

下面的 Python 代码缩进示例虽然正确，但含混不清：

     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

下例展示了多种缩进错误：

      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

（实际上，解析器可以识别前三个错误；只有最后一个错误由词法分析器识别 —
‘return r’ 的缩进无法匹配从栈里移除的缩进层级。）


File: python.info,  Node: 形符间的空白字符,  Prev: 缩进,  Up: 行结构

4.2.1.9 形符间的空白字符
........................

除非在逻辑行开头或字符串内，空格符、制表符、换页符等空白符都可以分隔形符
。要把两个相连形符解读为不同形符，需要用空白符分隔（例如，ab 是一个形符
，a b 则是两个形符）。


File: python.info,  Node: 其他形符,  Next: 标识符和关键字,  Prev: 行结构,  Up: 词法分析

4.2.2 其他形符
--------------

除 NEWLINE、INDENT、DEDENT 外，还有 `标识符'、`关键字'、`字面值'、`运算
符' 、`分隔符' 等形符。 空白符（前述的行终止符除外）不是形符，可用于分隔
形符。存在二义性时，将从左至右，读取尽量长的字符串组成合法形符。


File: python.info,  Node: 标识符和关键字,  Next: 字面值,  Prev: 其他形符,  Up: 词法分析

4.2.3 标识符和关键字
--------------------

标识符（也称为 `名称'）的词法定义说明如下。

Python 标识符的句法基于 Unicode 标准附件 UAX-31，并加入了下文定义的细化
与修改；详见 PEP 3131(1) 。

与 Python 2.x 一样，在 ASCII 范围内（U+0001..U+007F），有效标识符字符为
： 大小写字母 ‘A’ 至 ‘Z’、下划线 ‘_’ 、数字 ‘0’ 至 ‘9’，但不能以数字开头
。

Python 3.0 引入了 ASCII 之外的更多字符（请参阅 PEP 3131(2)）。这些字符的
分类使用 *note unicodedata: 123. 模块中的 Unicode 字符数据库版本。

标识符的长度没有限制，但区分大小写。

     identifier   ::= xid_start xid_continue*
     id_start     ::= <all characters in general categories Lu, Ll, Lt, Lm, Lo, Nl, the underscore, and characters with the Other_ID_Start property>
     id_continue  ::= <all characters in id_start, plus characters in the categories Mn, Mc, Nd, Pc and others with the Other_ID_Continue property>
     xid_start    ::= <all characters in id_start whose NFKC normalization is in "id_start xid_continue*">
     xid_continue ::= <all characters in id_continue whose NFKC normalization is in "id_continue*">

上述 Unicode 类别码的含义:

   * `Lu' - 大写字母

   * `Ll' - 小写字母

   * `Lt' - 词首大写字母

   * `Lm' - 修饰符字母

   * `Lo' - 其他字母

   * `Nl' - 字母数字

   * `Mn' - 非空白标识

   * `Mc' - 含空白标识

   * `Nd' - 十进制数字

   * `Pc' - 连接标点

   * `Other_ID_Start' - 由 PropList.txt(3) 定义的显式字符列表，用于支持
     向后兼容

   * `Other_ID_Continue' - 同上

在解析时，所有标识符都会被转换为规范形式 NFKC；标识符的比较都是基于
NFKC。

Unicode 4.1 中所有可用的标识符字符详见此 HTML 文件
‘https://www.unicode.org/Public/13.0.0/ucd/DerivedCoreProperties.txt’

* Menu:

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

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3131

   (2) https://www.python.org/dev/peps/pep-3131

   (3) https://www.unicode.org/Public/13.0.0/ucd/PropList.txt


File: python.info,  Node: 关键字,  Next: 保留的标识符类,  Up: 标识符和关键字

4.2.3.1 关键字
..............

以下标识符为保留字，或称 `关键字'，不可用于普通标识符。关键字的拼写必须
与这里列出的完全一致：

     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


File: python.info,  Node: 保留的标识符类,  Prev: 关键字,  Up: 标识符和关键字

4.2.3.2 保留的标识符类
......................

某些标识符类（除了关键字）具有特殊含义。这些类的命名模式以下划线字符开头
，并以下划线结尾：

‘_*’

     ‘from module import *’ 时，不会导入。交互式解释器中，特殊标识符 ‘_’
     用于存储最近一次求值的结果；该标识符保存在 *note builtins: 12. 模块
     里。不处于交互模式时，‘_’ 没有特殊含义，也没有预定义。详见 *note
     import 语句: ce7.。

          備註: ‘_’ 常用于连接国际化文本；详见 *note gettext: 87. 模块文
          档。

‘__*__’

     系统定义的名称，通常简称为 "dunder" 。这些名称由解释器及其实现（包
     括标准库）定义。现有系统定义名称相关的论述详见 *note 特殊方法名称:
     607. 等章节。Python 未来版本中还将定义更多此类名称。任何情况下，`任
     何' 不显式遵从 ‘__*__’ 名称的文档用法，都可能导致无警告提示的错误。

‘__*’

     类的私有名称。类定义时，此类名称以一种混合形式重写，以避免基类及派
     生类的 "私有" 属性之间产生名称冲突。详见 *note 标识符（名称）:
     1510.。


File: python.info,  Node: 字面值,  Next: 运算符,  Prev: 标识符和关键字,  Up: 词法分析

4.2.4 字面值
------------

字面值是内置类型常量值的表示法。

* Menu:

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


File: python.info,  Node: 字符串与字节串字面值,  Next: 字符串字面值合并,  Up: 字面值

4.2.4.1 字符串与字节串字面值
............................

字符串字面值的词法定义如下：

     stringliteral   ::= [stringprefix](shortstring | longstring)
     stringprefix    ::= "r" | "u" | "R" | "U" | "f" | "F"
                         | "fr" | "Fr" | "fR" | "FR" | "rf" | "rF" | "Rf" | "RF"
     shortstring     ::= "'" shortstringitem* "'" | '"' shortstringitem* '"'
     longstring      ::= "'''" longstringitem* "'''" | '"""' longstringitem* '"""'
     shortstringitem ::= shortstringchar | stringescapeseq
     longstringitem  ::= longstringchar | stringescapeseq
     shortstringchar ::= <any source character except "\" or newline or the quote>
     longstringchar  ::= <any source character except "\">
     stringescapeseq ::= "\" <any source character>

     bytesliteral   ::= bytesprefix(shortbytes | longbytes)
     bytesprefix    ::= "b" | "B" | "br" | "Br" | "bR" | "BR" | "rb" | "rB" | "Rb" | "RB"
     shortbytes     ::= "'" shortbytesitem* "'" | '"' shortbytesitem* '"'
     longbytes      ::= "'''" longbytesitem* "'''" | '"""' longbytesitem* '"""'
     shortbytesitem ::= shortbyteschar | bytesescapeseq
     longbytesitem  ::= longbyteschar | bytesescapeseq
     shortbyteschar ::= <any ASCII character except "\" or newline or the quote>
     longbyteschar  ::= <any ASCII character except "\">
     bytesescapeseq ::= "\" <any ASCII character>

上述产生式没有说明以下句法限制，*note stringprefix: 1516. 或 *note
bytesprefix: 151f. 与其他字面值之间不允许有空白符。源字符集由编码声明定
义；源文件没有编码声明时，默认为 UTF-8；详见 *note 编码声明: 14f8.。

通俗地说：两种字面值都可以用单引号（‘'’）或双引号（‘"’） 标注。也可以用
三个单引号或双引号标注（俗称 `三引号字符串'）。反斜杠（‘\’）用于转义特殊
字符，例如，换行符、反斜杠本身、引号等。

字节串字面值要加前缀 ‘'b'’ 或 ‘'B'’；生成的是类型 *note bytes: 172. 的实
例，不是类型 *note str: 205. 的实例；字节串只能包含 ASCII 字符；字节串数
值大于等于 128 时，必须用转义表示。

字符串和字节串都可以加前缀 ‘'r'’ 或 ‘'R'’，称为 `原始字符串'，原始字符串
把反斜杠当作原义字符，不执行转义操作。因此，原始字符串不转义 ‘'\U'’ 和
‘'\u'’。与 Python 2.x 的原始 unicode 字面值操作不同，Python 3.x 现已不支
持 ‘'ur'’ 句法。

3.3 版新加入: 新增原始字节串 ‘'rb'’ 前缀，是 ‘'br'’ 的同义词。

3.3 版新加入: 支持 unicode 字面值（‘u'value'’）遗留代码，简化 Python 2.x
和 3.x 并行代码库的维护工作。详见 PEP 414(1)。

前缀为 ‘'f'’ 或 ‘'F'’ 的字符串称为 `格式字符串'；详见 *note
格式字符串字面值: 296.。‘'f'’ 可与 ‘'r'’ 连用，但不能与 ‘'b'’ 或 ‘'u'’ 连
用，因此，可以使用原始格式字符串，但不能使用格式字节串字面值。

三引号字面值可以包含未转义的换行和引号（原样保留），除了连在一起的，用于
终止字面值的，未经转义的三个引号。（"引号" 是启用字面值的字符，可以是
‘'’，也可以是 ‘"’。）

如未标注 ‘'r'’ 或 ‘'R'’ 前缀，字符串和字节串字面值中，转义序列以类似 C 标
准的规则进行解释。可用的转义序列如下：

转义序列              意义                                  註解
                                                            
------------------------------------------------------------------------
                                                            
‘\newline’            忽略反斜杠与换行符
                      
                                                            
‘\\’                  反斜杠（‘\’）
                      
                                                            
‘\'’                  单引号（‘'’）
                      
                                                            
‘\"’                  双引号（‘"’）
                      
                                                            
‘\a’                  ASCII 响铃（BEL）
                      
                                                            
‘\b’                  ASCII 退格符（BS）
                      
                                                            
‘\f’                  ASCII 换页符（FF）
                      
                                                            
‘\n’                  ASCII 换行符（LF）
                      
                                                            
‘\r’                  ASCII 回车符（CR）
                      
                                                            
‘\t’                  ASCII 水平制表符（TAB）
                      
                                                            
‘\v’                  ASCII 垂直制表符（VT）
                      
                                                            
‘\ooo’                八进制数 `ooo' 字符                   (1,3)
                                                            
                                                            
‘\xhh’                十六进制数 `hh' 字符                  (2,3)
                                                            

字符串字面值专用的转义序列：

转义序列              意义                                  註解
                                                            
------------------------------------------------------------------------
                                                            
‘\N{name}’            Unicode 数据库中名为 `name' 的字符    (4)
                                                            
                                                            
‘\uxxxx’              16 位十六进制数 `xxxx' 码位的字符     (5)
                                                            
                                                            
‘\Uxxxxxxxx’          32 位 16 进制数 `xxxxxxxx' 码位的字   (6)
                      符                                    
                      

註解：

  1. 与 C 标准一致，接受最多三个八进制数字。

  2. 与 C 标准不同，必须为两个十六进制数字。

  3. `字节串' 字面值中，十六进制数和八进制数的转义码以相应数值代表每个字
     节。`字符串' 字面值中，这些转义码以相应数值代表每个 Unicode 字符。

  4. 
     3.3 版更變: 加入了对别名 (2) 的支持。

  5. 必须为 4 个十六进制数码。

  6. 表示任意 Unicode 字符。必须为 8 个十六进制数码。

与 C 标准不同，无法识别的转义序列在字符串里原样保留，即，`输出结果保留反
斜杠'。（调试时，这种方式很有用：输错转义序列时，更容易在输出结果中识别
错误。）注意，在字节串字面值内，字符串字面值专用的转义序列属于无法识别的
转义序列。

     3.6 版更變: 无法识别的转义序列触发 *note DeprecationWarning: 15a.。
     未来的 Python 发行版将改为触发 *note SyntaxWarning: 2c9.，最终会改
     为触发 *note SyntaxError: 559.。

即使在原始字面值中，引号也可以用反斜杠转义，但反斜杠会保留在输出结果里；
例如 ‘r"\""’ 是由两个字符组成的有效字符串字面值：反斜杠和双引号；‘r"\"’
则不是有效字符串字面值（原始字符串也不能以奇数个反斜杠结尾）。尤其是，
`原始字面值不能以单个反斜杠结尾' （反斜杠会转义其后的引号)。还要注意，反
斜杠加换行在字面值中被解释为两个字符，而 `不是' 连续行。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0414

   (2) (1) ‘https://www.unicode.org/Public/11.0.0/ucd/NameAliases.txt’


File: python.info,  Node: 字符串字面值合并,  Next: 格式字符串字面值,  Prev: 字符串与字节串字面值,  Up: 字面值

4.2.4.2 字符串字面值合并
........................

以空白符分隔的多个相邻字符串或字节串字面值，可用不同引号标注，等同于合并
操作。因此，‘"hello" 'world'’ 等价于 ‘"helloworld"’。此功能不需要反斜杠
，即可将长字符串分为多个物理行，还可以为不同部分的字符串添加注释，例如：

     re.compile("[A-Za-z_]"       # letter or underscore
                "[A-Za-z0-9_]*"   # letter, digit or underscore
               )

注意，此功能在句法层面定义，在编译时实现。在运行时，合并字符串表达式必须
使用 ’+’ 运算符。还要注意，字面值合并可以为每个部分应用不同的引号风格（
甚至混用原始字符串和三引号字符串)，格式字符串字面值也可以与纯字符串字面
值合并。


File: python.info,  Node: 格式字符串字面值,  Next: 数值字面值,  Prev: 字符串字面值合并,  Up: 字面值

4.2.4.3 格式字符串字面值
........................

3.6 版新加入.

`格式字符串字面值' 或称 `f-string' 是标注了 ‘'f'’ 或 ‘'F'’ 前缀的字符串
字面值。这种字符串可包含替换字段，即以 ‘{}’ 标注的表达式。其他字符串字面
值只是常量，格式字符串字面值则是可在运行时求值的表达式。

除非字面值标记为原始字符串，否则，与在普通字符串字面值中一样，转义序列也
会被解码。解码后，用于字符串内容的语法如下：

     f_string          ::= (literal_char | "{{" | "}}" | replacement_field)*
     replacement_field ::= "{" f_expression ["="] ["!" conversion] [":" format_spec] "}"
     f_expression      ::= (conditional_expression | "*" or_expr)
                             ("," conditional_expression | "," "*" or_expr)* [","]
                           | yield_expression
     conversion        ::= "s" | "r" | "a"
     format_spec       ::= (literal_char | NULL | replacement_field)*
     literal_char      ::= <any code point except "{", "}" or NULL>

双花括号 ‘'{{'’ 或 ‘'}}'’ 被替换为单花括号，花括号外的字符串仍按字面值处
理。单左花括号 ‘'{'’ 标记以 Python 表达式开头的替换字段。在表达式后加等
于号 ‘'='’，可在求值后，同时显示表达式文本及其结果（用于调试）。 随后是
用叹号 ‘'!'’ 标记的转换字段。还可以在冒号 ‘':'’ 后附加格式说明符。替换字
段以右花括号 ‘'}'’ 为结尾。

格式字符串字面值中，表达式的处理与圆括号中的常规 Python 表达式基本一样，
但也有一些不同的地方。不允许使用空表达式；*note lambda: cf9. 和赋值表达
式 ‘:=’ 必须显式用圆括号标注；替换表达式可以包含换行（例如，三引号字符串
中），但不能包含注释；在格式字符串字面值语境内，按从左至右的顺序，为每个
表达式求值。

3.7 版更變: Python 3.7 以前， 因为实现的问题，不允许在格式字符串字面值表
达式中使用 *note await: 2d8. 表达式与包含 *note async for: 3fd. 子句的推
导式。

表达式里含等号 ‘'='’ 时，输出内容包括表达式文本、‘'='’ 、求值结果。输出
内容可以保留表达式中左花括号 ‘'{'’ 后，及 ‘'='’ 后的空格。没有指定格式时
，‘'='’ 默认调用表达式的 *note repr(): 8b9.。指定了格式时，默认调用表达
式的 *note str(): 205.，除非声明了转换字段 ‘'!r'’。

3.8 版新加入: 等号 ‘'='’。

指定了转换符时，表达式求值的结果会先转换，再格式化。转换符 ‘'!s'’ 调用
*note str(): 205. 转换求值结果，‘'!r'’ 调用 *note repr(): 8b9.，‘'!a'’ 调
用 *note ascii(): e11.。

输出结果的格式化使用 *note format(): 5d5. 协议。格式说明符传入表达式或转
换结果的 *note __format__(): a2f. 方法。省略格式说明符，则传入空字符串。
然后，格式化结果包含在整个字符串的最终值里。

顶层格式说明符可以包含嵌套替换字段。嵌套字段也可以包含自己的转换字段和
*note 格式说明符: 5d8.，但不可再包含更深层嵌套的替换字段。*note
格式说明符微语言: 5d8. 与 *note str.format(): 5d4. 方法使用的微语言相同
。

格式化字符串字面值可以拼接，但是一个替换字段不能拆分到多个字面值。

格式字符串字面值示例如下：

     >>> 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" '

与常规字符串字面值的语法一样，替换字段中的字符不能与外层格式字符串字面值
的引号冲突：

     f"abc {a["x"]} def"    # error: outer string literal ended prematurely
     f"abc {a['x']} def"    # workaround: use different quoting

格式表达式中不能有反斜杠，否则会报错：

     f"newline: {ord('\n')}"  # raises SyntaxError

要使用反斜杠转义的值，则需创建临时变量。

     >>> newline = ord('\n')
     >>> f"newline: {newline}"
     'newline: 10'

即便未包含表达式，格式字符串字面值也不能用作文档字符串。

     >>> def foo():
     ...     f"Not a docstring"
     ...
     >>> foo.__doc__ is None
     True

参阅 PEP 498(1)，了解格式字符串字面值的提案，以及与格式字符串机制相关的
*note str.format(): 5d4.。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0498


File: python.info,  Node: 数值字面值,  Next: 整数字面值,  Prev: 格式字符串字面值,  Up: 字面值

4.2.4.4 数值字面值
..................

数值字面值有三种类型：整数、浮点数、虚数。没有复数字面值（复数由实数加虚
数构成）。

注意，数值字面值不含正负号；实际上，‘-1’ 等负数是由一元运算符 ’‘-’’ 和字
面值 ‘1’ 合成的。


File: python.info,  Node: 整数字面值,  Next: 浮点数字面值,  Prev: 数值字面值,  Up: 字面值

4.2.4.5 整数字面值
..................

整数字面值词法定义如下：

     integer      ::= decinteger | bininteger | octinteger | hexinteger
     decinteger   ::= nonzerodigit (["_"] digit)* | "0"+ (["_"] "0")*
     bininteger   ::= "0" ("b" | "B") (["_"] bindigit)+
     octinteger   ::= "0" ("o" | "O") (["_"] octdigit)+
     hexinteger   ::= "0" ("x" | "X") (["_"] hexdigit)+
     nonzerodigit ::= "1"..."9"
     digit        ::= "0"..."9"
     bindigit     ::= "0" | "1"
     octdigit     ::= "0"..."7"
     hexdigit     ::= digit | "a"..."f" | "A"..."F"

整数字面值的长度没有限制，能一直大到占满可用内存。

确定数值时，会忽略字面值中的下划线。下划线只是为了分组数字，让数字更易读
。下划线可在数字之间，也可在 ‘0x’ 等基数说明符后。

注意，除了 0 以外，十进制数字的开头不允许有零。以免与 Python 3.0 版之前
使用的 C 样式八进制字面值混淆。

整数字面值示例如下：

     7     2147483647                        0o177    0b100110111
     3     79228162514264337593543950336     0o377    0xdeadbeef
           100_000_000_000                   0b_1110_0101

3.6 版更變: 现已支持在字面值中，用下划线分组数字。


File: python.info,  Node: 浮点数字面值,  Next: 虚数字面值,  Prev: 整数字面值,  Up: 字面值

4.2.4.6 浮点数字面值
....................

浮点数字面值词法定义如下：

     floatnumber   ::= pointfloat | exponentfloat
     pointfloat    ::= [digitpart] fraction | digitpart "."
     exponentfloat ::= (digitpart | pointfloat) exponent
     digitpart     ::= digit (["_"] digit)*
     fraction      ::= "." digitpart
     exponent      ::= ("e" | "E") ["+" | "-"] digitpart

注意，解析时，整数和指数部分总以 10 为基数。例如，‘077e010’ 是合法的，表
示的数值与 ‘77e10’ 相同。浮点数字面值的支持范围取决于具体实现。整数字面
值支持用下划线分组数字。

浮点数字面值示例如下：

     3.14    10.    .001    1e100    3.14e-10    0e0    3.14_15_93

3.6 版更變: 现已支持在字面值中，用下划线分组数字。


File: python.info,  Node: 虚数字面值,  Prev: 浮点数字面值,  Up: 字面值

4.2.4.7 虚数字面值
..................

虚数字面值词法定义如下：

     imagnumber ::= (floatnumber | digitpart) ("j" | "J")

虚数字面值生成实部为 0.0 的复数。复数由一对浮点数表示，它们的取值范围相
同。创建实部不为零的复数，则需添加浮点数，例如 ‘(3+4j)’。虚数字面值示例
如下：

     3.14j   10.j    10j     .001j   1e100j   3.14e-10j   3.14_15_93j


File: python.info,  Node: 运算符,  Next: 分隔符,  Prev: 字面值,  Up: 词法分析

4.2.5 运算符
------------

运算符如下所示：

     +       -       *       **      /       //      %      @
     <<      >>      &       |       ^       ~       :=
     <       >       <=      >=      ==      !=


File: python.info,  Node: 分隔符,  Prev: 运算符,  Up: 词法分析

4.2.6 分隔符
------------

以下形符在语法中为分隔符：

     (       )       [       ]       {       }
     ,       :       .       ;       @       =       ->
     +=      -=      *=      /=      //=     %=      @=
     &=      |=      ^=      >>=     <<=     **=

句点也可以用于浮点数和虚数字面值。三个连续句点表示省略符。列表后半部分是
增强赋值操作符，用作词法分隔符，但也可以执行运算。

以下 ASCII 字符具有特殊含义，对词法分析器有重要意义：

     '       "       #       \

以下 ASCII 字符不用于 Python。在字符串字面值或注释外使用时，将直接报错：

     $       ?       `

註解
....


File: python.info,  Node: 数据模型,  Next: 执行模型,  Prev: 词法分析,  Up: Python 語言參考手冊

4.3 数据模型
============

* Menu:

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


File: python.info,  Node: 对象、值与类型,  Next: 标准类型层级结构,  Up: 数据模型

4.3.1 对象、值与类型
--------------------

`对象' 是 Python 中对数据的抽象。 Python 程序中的所有数据都是由对象或对
象间关系来表示的。 （从某种意义上说，按照冯·诺依曼的“存储程序计算机”模型
，代码本身也是由对象来表示的。）

每个对象都有各自的编号、类型和值。一个对象被创建后，它的 `编号' 就绝不会
改变；你可以将其理解为该对象在内存中的地址。 ’*note is: 1551.’ 运算符可
以比较两个对象的编号是否相同；*note id(): e4b. 函数能返回一个代表其编号
的整型数。

`CPython implementation detail:' 在 CPython 中，‘id(x)’ 就是存放 ‘x’ 的
内存的地址。

对象的类型决定该对象所支持的操作 (例如 "对象是否有长度属性？") 并且定义
了该类型的对象可能的取值。*note type(): 6ff. 函数能返回一个对象的类型 (类
型本身也是对象)。与编号一样，一个对象的 `类型' 也是不可改变的。(1)

有些对象的 `值' 可以改变。值可以改变的对象被称为 `可变的'；值不可以改变
的对象就被称为 `不可变的'。(一个不可变容器对象如果包含对可变对象的引用，
当后者的值改变时，前者的值也会改变；但是该容器仍属于不可变对象，因为它所
包含的对象集是不会改变的。因此，不可变并不严格等同于值不能改变，实际含义
要更微妙。) 一个对象的可变性是由其类型决定的；例如，数字、字符串和元组是
不可变的，而字典和列表是可变的。

对象绝不会被显式地销毁；然而，当无法访问时它们可能会被作为垃圾回收。允许
具体的实现推迟垃圾回收或完全省略此机制 — 如何实现垃圾回收是实现的质量问
题，只要可访问的对象不会被回收即可。

`CPython implementation detail:' CPython 目前使用带有 (可选) 延迟检测循
环链接垃圾的引用计数方案，会在对象不可访问时立即回收其中的大部分，但不保
证回收包含循环引用的垃圾。请查看 *note gc: 84. 模块的文档了解如何控制循
环垃圾的收集相关信息。其他实现会有不同的行为方式，CPython 现有方式也可能
改变。不要依赖不可访问对象的立即终结机制 (所以你应当总是显式地关闭文件
)。

注意：使用实现的跟踪或调试功能可能令正常情况下会被回收的对象继续存活。还
要注意通过 ’*note try: e37...*note except: c10.’ 语句捕捉异常也可能令对
象保持存活。

有些对象包含对 "外部" 资源的引用，例如打开文件或窗口。当对象被作为垃圾回
收时这些资源也应该会被释放，但由于垃圾回收并不确保发生，这些对象还提供了
明确地释放外部资源的操作，通常为一个 ‘close()’ 方法。强烈推荐在程序中显
式关闭此类对象。’*note try: e37...*note finally: 2bc.’ 语句和 ’*note
with: 7da.’ 语句提供了进行此种操作的更便捷方式。

有些对象包含对其他对象的引用；它们被称为 `容器'。容器的例子有元组、列表
和字典等。这些引用是容器对象值的组成部分。在多数情况下，当谈论一个容器的
值时，我们是指所包含对象的值而不是其编号；但是，当我们谈论一个容器的可变
性时，则仅指其直接包含的对象的编号。因此，如果一个不可变容器 (例如元组)
包含对一个可变对象的引用，则当该可变对象被改变时容器的值也会改变。

类型会影响对象行为的几乎所有方面。甚至对象编号的重要性也在某种程度上受到
影响: 对于不可变类型，会得出新值的运算实际上会返回对相同类型和取值的任一
现有对象的引用，而对于可变类型来说这是不允许的。例如在 ‘a = 1; b = 1’ 之
后，‘a’ 和 ‘b’ 可能会也可能不会指向同一个值为一的对象，这取决于具体实现
，但是在 ‘c = []; d = []’ 之后，‘c’ 和 ‘d’ 保证会指向两个不同、单独的新
建空列表。(请注意 ‘c = d = []’ 则是将同一个对象赋值给 ‘c’ 和 ‘d’。)

   ---------- Footnotes ----------

   (1) (1) 在某些情况下 `有可能' 基于可控的条件改变一个对象的类型。 但这
通常不是个好主意，因为如果处理不当会导致一些非常怪异的行为。


File: python.info,  Node: 标准类型层级结构,  Next: 特殊方法名称,  Prev: 对象、值与类型,  Up: 数据模型

4.3.2 标准类型层级结构
----------------------

以下是 Python 内置类型的列表。扩展模块 (具体实现会以 C, Java 或其他语言
编写) 可以定义更多的类型。未来版本的 Python 可能会加入更多的类型 (例如有
理数、高效存储的整型数组等等)，不过新增类型往往都是通过标准库来提供的。

以下部分类型的描述中包含有 ’特殊属性列表’ 段落。这些属性提供对具体实现的
访问而非通常使用。它们的定义在未来可能会改变。

None

     此类型只有一种取值。是一个具有此值的单独对象。此对象通过内置名称
     ‘None’ 访问。在许多情况下它被用来表示空值，例如未显式指明返回值的函
     数将返回 None。它的逻辑值为假。

NotImplemented

     此类型只有一种取值。 是一个具有该值的单独对象。 此对象通过内置名称
     ‘NotImplemented’ 访问。 数值方法和丰富比较方法如未实现指定运算符表
     示的运算则应返回该值。 （解释器会根据具体运算符继续尝试反向运算或其
     他回退操作。） 它不应被解读为布尔值。

     详情参见 *note 实现算术运算: 1554.。

     3.9 版更變: 作为布尔值来解读 ‘NotImplemented’ 已被弃用。 虽然它目前
     会被解读为真值，但将同时发出 *note DeprecationWarning: 15a.。 它将
     在未来的 Python 版本中引发 *note TypeError: 1fe.。

Ellipsis

     此类型只有一种取值。是一个具有此值的单独对象。此对象通过字面值
     ‘...’ 或内置名称 ‘Ellipsis’ 访问。它的逻辑值为真。

*note numbers.Number: 1555.

     此类对象由数字字面值创建，并会被作为算术运算符和算术内置函数的返回
     结果。数字对象是不可变的；一旦创建其值就不再改变。Python 中的数字当
     然非常类似数学中的数字，但也受限于计算机中的数字表示方法。

     The string representations of the numeric classes, computed by
     *note __repr__(): 44a. and *note __str__(): ef9, have the following
     properties:

        * 它们是有效的数字字面值，当被传给它们的类构造器时，将会产生具有
          原数字值的对象。

        * 表示形式会在可能的情况下采用 10 进制。

        * 开头的零，除小数点前可能存在的单个零之外，将不会被显示。

        * 末尾的零，除小数点后可能存在的单个零之外，将不会被显示。

        * 正负号仅在当数字为负值时会被显示。

     Python 区分整型数、浮点型数和复数:

     *note numbers.Integral: 1556.

          此类对象表示数学中整数集合的成员 (包括正数和负数)。

          整型数可细分为两种类型:

          整型 (*note int: 204.)

               此类对象表示任意大小的数字，仅受限于可用的内存 (包括虚拟
               内存)。在变换和掩码运算中会以二进制表示，负数会以 2 的补
               码表示，看起来像是符号位向左延伸补满空位。

          布尔型 (*note bool: 2bd.)

               此类对象表示逻辑值 False 和 True。代表 ‘False’ 和 ‘True’
               值的两个对象是唯二的布尔对象。布尔类型是整型的子类型，两
               个布尔值在各种场合的行为分别类似于数值 0 和 1，例外情况只
               有在转换为字符串时分别返回字符串 ‘"False"’ 或 ‘"True"’。

          整型数表示规则的目的是在涉及负整型数的变换和掩码运算时提供最为
          合理的解释。

     *note numbers.Real: 1557. (*note float: 1fd.)

          此类对象表示机器级的双精度浮点数。其所接受的取值范围和溢出处理
          将受制于底层的机器架构 (以及 C 或 Java 实现)。Python 不支持单
          精度浮点数；支持后者通常的理由是节省处理器和内存消耗，但这点节
          省相对于在 Python 中使用对象的开销来说太过微不足道，因此没有理
          由包含两种浮点数而令该语言变得复杂。

     *note numbers.Complex: 1558. (*note complex: 2c1.)

          此类对象以一对机器级的双精度浮点数来表示复数值。有关浮点数的附
          带规则对其同样有效。一个复数值 ‘z’ 的实部和虚部可通过只读属性
          ‘z.real’ 和 ‘z.imag’ 来获取。

序列

     此类对象表示以非负整数作为索引的有限有序集。内置函数 *note len():
     28b. 可返回一个序列的条目数量。当一个序列的长度为 `n' 时，索引集包
     含数字 0, 1, ..., `n'-1。序列 `a' 的条目 `i' 可通过 ‘a[i]’ 选择。

     序列还支持切片: ‘a[i:j]’ 选择索引号为 `k' 的所有条目，`i' ‘<=’ `k'
     ‘<’ `j'。当用作表达式时，序列的切片就是一个与序列类型相同的新序列。
     新序列的索引还是从 0 开始。

     有些序列还支持带有第三个 "step" 形参的 "扩展切片": ‘a[i:j:k]’ 选择
     `a' 中索引号为 `x' 的所有条目，‘x = i + n*k’, `n' ‘>=’ ‘0’ 且 `i'
     ‘<=’ `x' ‘<’ `j'。

     序列可根据其可变性来加以区分:

     不可变序列

          不可变序列类型的对象一旦创建就不能再改变。(如果对象包含对其他
          对象的引用，其中的可变对象就是可以改变的；但是，一个不可变对象
          所直接引用的对象集是不能改变的。)

          以下类型属于不可变对象:

          字串 (String)

               字符串是由 Unicode 码位值组成的序列。范围在 ‘U+0000 -
               U+10FFFF’ 之内的所有码位值都可在字符串中使用。Python 没有
               ‘char’ 类型；而是将字符串中的每个码位表示为一个长度为 ‘1’
               的字符串对象。内置函数 *note ord(): 1559. 可将一个码位由
               字符串形式转换成一个范围在 ‘0 - 10FFFF’ 之内的整型数；
               *note chr(): 155a. 可将一个范围在 ‘0 - 10FFFF’ 之内的整型
               数转换为长度为 ‘1’ 的对应字符串对象。*note str.encode():
               170. 可以使用指定的文本编码将 *note str: 205. 转换为
               *note bytes: 172.，而 *note bytes.decode(): 171. 则可以实
               现反向的解码。

          元组

               一个元组中的条目可以是任意 Python 对象。包含两个或以上条
               目的元组由逗号分隔的表达式构成。只有一个条目的元组 (’单项
               元组’) 可通过在表达式后加一个逗号来构成 (一个表达式本身不
               能创建为元组，因为圆括号要用来设置表达式分组)。一个空元组
               可通过一对内容为空的圆括号创建。

          字节串

               字节串对象是不可变的数组。其中每个条目都是一个 8 位字节，
               以取值范围 0 <= x < 256 的整型数表示。字节串字面值 (例如
               ‘b'abc'’) 和内置的 *note bytes(): 172. 构造器可被用来创建
               字节串对象。字节串对象还可以通过 *note decode(): 171. 方
               法解码为字符串。

     可变序列

          可变序列在被创建后仍可被改变。下标和切片标注可被用作赋值和
          *note del: 13a2. (删除) 语句的目标。

          目前有两种内生可变序列类型:

          List（串列）

               列表中的条目可以是任意 Python 对象。列表由用方括号括起并
               由逗号分隔的多个表达式构成。(注意创建长度为 0 或 1 的列表
               无需使用特殊规则。)

          字节数组

               字节数组对象属于可变数组。可以通过内置的 *note
               bytearray(): 173. 构造器来创建。除了是可变的 (因而也是不
               可哈希的)，在其他方面字节数组提供的接口和功能都与不可变的
               *note bytes: 172. 对象一致。

          扩展模块 *note array: 6. 提供了一个额外的可变序列类型示例，
          *note collections: 1d. 模块也是如此。

集合类型

     此类对象表示由不重复且不可变对象组成的无序且有限的集合。因此它们不
     能通过下标来索引。但是它们可被迭代，也可用内置函数 *note len():
     28b. 返回集合中的条目数。集合常见的用处是快速成员检测，去除序列中的
     重复项，以及进行交、并、差和对称差等数学运算。

     对于集合元素所采用的不可变规则与字典的键相同。注意数字类型遵循正常
     的数字比较规则: 如果两个数字相等 (例如 ‘1’ 和 ‘1.0’)，则同一集合中
     只能包含其中一个。

     目前有两种内生集合类型:

     集合

          此类对象表示可变集合。它们可通过内置的 *note set(): 1f6. 构造
          器创建，并且创建之后可以通过方法进行修改，例如 ‘add()’。

     冻结集合

          此类对象表示不可变集合。它们可通过内置的 *note frozenset():
          1f7. 构造器创建。由于 frozenset 对象不可变且 *note hashable:
          276.，它可以被用作另一个集合的元素或是字典的键。

映射

     此类对象表示由任意索引集合所索引的对象的集合。通过下标 ‘a[k]’ 可在
     映射 ‘a’ 中选择索引为 ‘k’ 的条目；这可以在表达式中使用，也可作为赋
     值或 *note del: 13a2. 语句的目标。内置函数 *note len(): 28b. 可返回
     一个映射中的条目数。

     目前只有一种内生映射类型:

     字典

          此类对象表示由几乎任意值作为索引的有限个对象的集合。不可作为键
          的值类型只有包含列表或字典或其他可变类型，通过值而非对象编号进
          行比较的值，其原因在于高效的字典实现需要使用键的哈希值以保持一
          致性。用作键的数字类型遵循正常的数字比较规则: 如果两个数字相等
          (例如 ‘1’ 和 ‘1.0’) 则它们均可来用来索引同一个字典条目。

          字典会保留插入顺序，这意味着键将以它们被添加的顺序在字典中依次
          产生。 替换某个现有的键不会改变其顺序，但是移除某个键再重新插
          入则会将其添加到末尾而不会保留其原有位置。

          字典是可变的；它们可通过 ‘{...}’ 标注来创建 (参见 *note
          字典显示: 741. 小节)。

          扩展模块 *note dbm.ndbm: 34. 和 *note dbm.gnu: 33. 提供了额外
          的映射类型示例，*note collections: 1d. 模块也是如此。

          3.7 版更變: 在 Python 3.6 版之前字典不会保留插入顺序。 在
          CPython 3.6 中插入顺序会被保留，但这在当时被当作是一个实现细节
          而非确定的语言特性。

可调用类型

     此类型可以被应用于函数调用操作 (参见 *note 调用: 73f. 小节):

     用户定义函数

          用户定义函数对象可通过函数定义来创建 (参见 *note 函数定义:
          1390. 小节)。它被调用时应附带一个参数列表，其中包含的条目应与
          函数所定义的形参列表一致。

          特殊属性:

          属性                          意义
                                        
          ----------------------------------------------------------------------------------
                                                                            
          ‘__doc__’                     该函数的文档字符串，没有则为        可写
                                        ‘None’；不会被子类继承。            
                                        
                                                                            
          *note __name__: d2f.          该函数的名称。                      可写
                                                                            
                                                                            
          *note __qualname__: 155b.     该函数的                            可写
                                        *note qualified name: 155c.。       
                                        
                                        3.3 版新加入.
                                        
                                                                            
          ‘__module__’                  该函数所属模块的名称，没有则为      可写
                                        ‘None’。                            
                                        
                                                                            
          ‘__defaults__’                由具有默认值的参数的默认参数值组    可写
                                        成的元组，如无任何参数具有默认值    
                                        则为 ‘None’。
                                        
                                                                            
          ‘__code__’                    表示编译后的函数体的代码对象。      可写
                                                                            
                                                                            
          ‘__globals__’                 对存放该函数中全局变量的字典的引    只读
                                        用 — 函数所属模块的全局命名空间。   
                                        
                                                                            
          *note __dict__: 5f5.          命名空间支持的函数属性。            可写
                                                                            
                                                                            
          ‘__closure__’                 ‘None’ 或包含该函数可用变量的绑定   只读
                                        的单元的元组。有关                  
                                        ‘cell_contents’ 属性的详情见下。
                                        
                                                                            
          ‘__annotations__’             包含参数标注的字典。字典的键是参    可写
                                        数名，如存在返回标注则为            
                                        ‘'return'’。
                                        
                                                                            
          ‘__kwdefaults__’              仅包含关键字参数默认值的字典。      可写
                                                                            

          大部分标有 "Writable" 的属性均会检查赋值的类型。

          函数对象也支持获取和设置任意属性，例如这可以被用来给函数附加元
          数据。使用正规的属性点号标注获取和设置此类属性。`注意当前实现
          仅支持用户定义函数属性。未来可能会增加支持内置函数属性。'

          单元对象具有 ‘cell_contents’ 属性。这可被用来获取以及设置单元
          的值。

          有关函数定义的额外信息可以从其代码对象中提取；参见下文对内部类
          型的描述。 *note cell: 155d. 类型可以在 *note types: 121. 模块
          中访问。

     实例方法

          实例方法用于结合类、类实例和任何可调用对象 (通常为用户定义函数
          )。

          特殊的只读属性: ‘__self__’ 为类实例对象本身，‘__func__’ 为函数
          对象；‘__doc__’ 为方法的文档 (与 ‘__func__.__doc__’ 作用相同
          )；*note __name__: d2f. 为方法名称 (与 ‘__func__.__name__’ 作
          用相同)；‘__module__’ 为方法所属模块的名称，没有则为 ‘None’。

          方法还支持获取 (但不能设置) 下层函数对象的任意函数属性。

          用户定义方法对象可在获取一个类的属性时被创建 (也可能通过该类的
          一个实例)，如果该属性为用户定义函数对象或类方法对象。

          当通过从类实例获取一个用户定义函数对象的方式创建一个实例方法对
          象时，类实例对象的 ‘__self__’ 属性即为该实例，并会绑定方法对象
          。该新建方法的 ‘__func__’ 属性就是原来的函数对象。

          当通过从类或实例获取一个类方法对象的方式创建一个实例对象时，实
          例对象的 ‘__self__’ 属性为该类本身，其 ‘__func__’ 属性为类方法
          对应的下层函数对象。

          当一个实例方法对象被调用时，会调用对应的下层函数 (‘__func__’)，
          并将类实例 (‘__self__’) 插入参数列表的开头。例如，当 ‘C’ 是一
          个包含了 ‘f()’ 函数定义的类，而 ‘x’ 是 ‘C’ 的一个实例，则调用
          ‘x.f(1)’ 就等同于调用 ‘C.f(x, 1)’。

          当一个实例方法对象是衍生自一个类方法对象时，保存在 ‘__self__’
          中的 "类实例" 实际上会是该类本身，因此无论是调用 ‘x.f(1)’ 还是
          ‘C.f(1)’ 都等同于调用 ‘f(C,1)’，其中 ‘f’ 为对应的下层函数。

          请注意从函数对象到实例方法对象的变换会在每一次从实例获取属性时
          发生。在某些情况下，一种高效的优化方式是将属性赋值给一个本地变
          量并调用该本地变量。还要注意这样的变换只发生于用户定义函数；其
          他可调用对象 (以及所有不可调用对象) 在被获取时都不会发生变换。
          还有一个需要关注的要点是作为一个类实例属性的用户定义函数不会被
          转换为绑定方法；这样的变换 `仅当' 函数是类属性时才会发生。

     生成器函数

          一个使用 *note yield: 2c7. 语句 （见 *note yield 语句: 2c7. 章
          节）的函数或方法被称作一个 `生成器函数'。 这样的函数在被调用时
          ，总是返回一个可以执行函数体的迭代器对象：调用该迭代器的 *note
          iterator.__next__(): d2c. 方法将会导致这个函数一直运行直到它使
          用 ‘yield’ 语句提供了一个值为止。 当这个函数执行 *note return:
          2c8. 语句或者执行到末尾时，将引发 *note StopIteration: 581. 异
          常并且这个迭代器将到达所返回的值集合的末尾。

     协程函数

          使用 *note async def: 3a9. 来定义的函数或方法就被称为 `协程函
          数'。这样的函数在被调用时会返回一个 *note coroutine: 18a. 对象
          。它可能包含 *note await: 2d8. 表达式以及 *note async with:
          736. 和 *note async for: 3fd. 语句。详情可参见 *note 协程对象:
          155e. 一节。

     异步生成器函数

          使用 *note async def: 3a9. 来定义并包含 *note yield: 2c7. 语句
          的函数或方法就被称为 `异步生成器函数'。这样的函数在被调用时会
          返回一个异步迭代器对象，该对象可在 *note async for: 3fd. 语句
          中用来执行函数体。

          Calling the asynchronous iterator’s *note aiterator.__anext__:
          155f. method will return an *note awaitable: 612. which when
          awaited will execute until it provides a value using the *note
          yield: 2c7. expression.  When the function executes an empty
          *note return: 2c8. statement or falls off the end, a *note
          StopAsyncIteration: 114a. exception is raised and the
          asynchronous iterator will have reached the end of the set of
          values to be yielded.

     内置函数

          内置函数对象是对于 C 函数的外部封装。内置函数的例子包括 *note
          len(): 28b. 和 *note math.sin(): ed1. (*note math: b1. 是一个
          标准内置模块)。内置函数参数的数量和类型由 C 函数决定。特殊的只
          读属性: ‘__doc__’ 是函数的文档字符串，如果没有则为 ‘None’;
          *note __name__: d2f. 是函数的名称; ‘__self__’ 设定为 ‘None’ (参
          见下一条目); ‘__module__’ 是函数所属模块的名称，如果没有则为
          ‘None’。

     内置方法

          此类型实际上是内置函数的另一种形式，只不过还包含了一个传入 C 函
          数的对象作为隐式的额外参数。内置方法的一个例子是
          ‘alist.append()’，其中 `alist' 为一个列表对象。在此示例中，特
          殊的只读属性 ‘__self__’ 会被设为 `alist' 所标记的对象。

     类

          Classes are callable.  These objects normally act as factories
          for new instances of themselves, but variations are possible
          for class types that override *note __new__(): 974.  The
          arguments of the call are passed to *note __new__(): 974. and,
          in the typical case, to *note __init__(): e23. to initialize
          the new instance.

     类实例

          Instances of arbitrary classes can be made callable by
          defining a *note __call__(): 1560. method in their class.

模块

     模块是 Python 代码的基本组织单元，由 *note 导入系统: 1561. 创建，由
     *note import: ce7. 语句发起调用，或者通过 *note
     importlib.import_module(): be6. 和内置的 *note __import__(): 16b. 等
     函数发起调用。 模块对象具有由字典对象实现的命名空间（这是被模块中定
     义的函数的 ‘__globals__’ 属性引用的字典）。 属性引用被转换为该字典
     中的查找，例如 ‘m.x’ 相当于 ‘m.__dict__["x"]’。 模块对象不包含用于
     初始化模块的代码对象（因为初始化完成后不需要它）。

     属性赋值会更新模块的命名空间字典，例如 ‘m.x = 1’ 等同于
     ‘m.__dict__["x"] = 1’。

     预定义的 (可写) 属性: *note __name__: dd8. 为模块的名称; ‘__doc__’
     为模块的文档字符串，如果没有则为 ‘None’; ‘__annotations__’ (可选) 为
     一个包含 *note 变量标注: 712. 的字典，它是在模块体执行时获取的;
     *note __file__: 1562. 是模块对应的被加载文件的路径名，如果它是加载
     自一个文件的话。某些类型的模块可能没有 *note __file__: 1562. 属性，
     例如 C 模块是静态链接到解释器内部的; 对于从一个共享库动态加载的扩展
     模块来说该属性为该共享库文件的路径名。

     特殊的只读属性: *note __dict__: 5f5. 为以字典对象表示的模块命名空间
     。

     `CPython implementation detail:' 由于 CPython 清理模块字典的设定，
     当模块离开作用域时模块字典将会被清理，即使该字典还有活动的引用。想
     避免此问题，可复制该字典或保持模块状态以直接使用其字典。

自定义类

     自定义类这种类型一般通过类定义来创建 (参见 *note 类定义: d32. 一节
     )。每个类都有通过一个字典对象实现的独立命名空间。类属性引用会被转化
     为在此字典中查找，例如 ‘C.x’ 会被转化为 ‘C.__dict__["x"]’ (不过也存
     在一些钩子对象以允许其他定位属性的方式)。当未在其中发现某个属性名称
     时，会继续在基类中查找。这种基类查找使用 C3 方法解析顺序，即使存在
     ’钻石形’ 继承结构即有多条继承路径连到一个共同祖先也能保持正确的行为
     。有关 Python 使用的 C3 MRO 的详情可查看配合 2.3 版发布的文档
     ‘https://www.python.org/download/releases/2.3/mro/’.

     当一个类属性引用 (假设类名为 ‘C’) 会产生一个类方法对象时，它将转化
     为一个 ‘__self__’ 属性为 ‘C’ 的实例方法对象。当其会产生一个静态方法
     对象时，它将转化为该静态方法对象所封装的对象。从类的 *note
     __dict__: 5f5. 所包含内容以外获取属性的其他方式请参看 *note
     实现描述器: 5e3. 一节。

     类属性赋值会更新类的字典，但不会更新基类的字典。

     类对象可被调用 (见上文) 以产生一个类实例 (见下文)。

     特殊属性: *note __name__: d2f. 为类的名称; ‘__module__’ 为类所在模
     块的名称; *note __dict__: 5f5. 为包含类命名空间的字典; *note
     __bases__: ecb. 为包含基类的元组，按其在基类列表中的出现顺序排列;
     ‘__doc__’ 为类的文档字符串，如果没有则为 ‘None’; ‘__annotations__’
     (可选) 为一个包含 *note 变量标注: 712. 的字典，它是在类体执行时获取
     的。

类实例

     A class instance is created by calling a class object (see above).
     A class instance has a namespace implemented as a dictionary which
     is the first place in which attribute references are searched.
     When an attribute is not found there, and the instance’s class has
     an attribute by that name, the search continues with the class
     attributes.  If a class attribute is found that is a user-defined
     function object, it is transformed into an instance method object
     whose ‘__self__’ attribute is the instance.  Static method and
     class method objects are also transformed; see above under
     "Classes".  See section *note 实现描述器: 5e3. for another way in
     which attributes of a class retrieved via its instances may differ
     from the objects actually stored in the class’s *note __dict__:
     5f5.  If no class attribute is found, and the object’s class has a
     *note __getattr__(): 42a. method, that is called to satisfy the
     lookup.

     Attribute assignments and deletions update the instance’s
     dictionary, never a class’s dictionary.  If the class has a *note
     __setattr__(): eee. or *note __delattr__(): 1563. method, this is
     called instead of updating the instance dictionary directly.

     如果类实例具有某些特殊名称的方法，就可以伪装为数字、序列或映射。参
     见 *note 特殊方法名称: 607. 一节。

     特殊属性: *note __dict__: 5f5. 为属性字典; *note __class__: ecc. 为
     实例对应的类。

I/O 对象 (或称文件对象)

     *note file object: c14. 表示一个打开的文件。有多种快捷方式可用来创
     建文件对象: *note open(): 16f. 内置函数，以及 *note os.popen():
     3cb, *note os.fdopen(): 1564. 和 socket 对象的 *note makefile():
     bec. 方法 (还可能使用某些扩展模块所提供的其他函数或方法)。

     ‘sys.stdin’, ‘sys.stdout’ 和 ‘sys.stderr’ 会初始化为对应于解释器标
     准输入、输出和错误流的文件对象；它们都会以文本模式打开，因此都遵循
     *note io.TextIOBase: d01. 抽象类所定义的接口。

内部类型

     某些由解释器内部使用的类型也被暴露给用户。它们的定义可能随未来解释
     器版本的更新而变化，为内容完整起见在此处一并介绍。

     代码对象

          代码对象表示 `编译为字节的' 可执行 Python 代码，或称 *note
          bytecode: 709.。代码对象和函数对象的区别在于函数对象包含对函数
          全局对象 (函数所属的模块) 的显式引用，而代码对象不包含上下文；
          而且默认参数值会存放于函数对象而不是代码对象内 (因为它们表示在
          运行时算出的值)。与函数对象不同，代码对象不可变，也不包含对可
          变对象的引用 (不论是直接还是间接)。

          特殊的只读属性: ‘co_name’ 给出了函数名; ‘co_argcount’ 为位置参
          数的总数量 (包括仅限位置参数和带有默认值的参数);
          ‘co_posonlyargcount’ 为仅限位置参数的数量 (包括带有默认值的参
          数); ‘co_kwonlyargcount’ 为仅限关键字参数的数量 (包括带有默认
          值的参数); ‘co_nlocals’ 为函数使用的局部变量的数量 (包括参数);
          ‘co_varnames’ 为一个包含局部变量名称的元组 (参数名排在最前面);
          ‘co_cellvars’ 为一个包含被嵌套函数所引用的局部变量名称的元组;
          ‘co_freevars’ 为一个包含自由变量名称的元组; ‘co_code’ 为一个表
          示字节码指令序列的字符口中; ‘co_consts’ 为一个包含字节码所使用
          的字面值的元组; ‘co_names’ 为一个包含字节码所使用的名称的元组;
          ‘co_filename’ 为被编码代码所在的文件名; ‘co_firstlineno’ 为函
          数首行的行号; ‘co_lnotab’ 为一个字符串，其中编码了从字节码偏移
          量到行号的映射 (详情参见解释器的源代码); ‘co_stacksize’ 为要求
          的栈大小; ‘co_flags’ 为一个整数，其中编码了解释器所用的多个旗
          标。

          以下是可用于 ‘co_flags’ 的标志位定义：如果函数使用
          ‘*arguments’ 语法来接受任意数量的位置参数，则 ‘0x04’ 位被设置
          ；如果函数使用 ‘**keywords’ 语法来接受任意数量的关键字参数，则
          ‘0x08’ 位被设置；如果函数是一个生成器，则 ‘0x20’ 位被设置。

          未来特性声明 (‘from __future__ import division’) 也使用
          ‘co_flags’ 中的标志位来指明代码对象的编译是否启用特定的特性: 如
          果函数编译时启用未来除法特性则设置 ‘0x2000’ 位; 在更早的
          Python 版本中则使用 ‘0x10’ 和 ‘0x1000’ 位。

          ‘co_flags’ 中的其他位被保留为内部使用。

          如果代码对象表示一个函数，‘co_consts’ 中的第一项将是函数的文档
          字符串，如果未定义则为 ‘None’。

     帧对象

          帧对象表示执行帧。它们可能出现在回溯对象中 (见下文)，还会被传
          递给注册跟踪函数。

          特殊的只读属性: ‘f_back’ 为前一堆栈帧 (指向调用者)，如是最底层
          堆栈帧则为 ‘None’; ‘f_code’ 为此帧中所执行的代码对象;
          ‘f_locals’ 为用于查找本地变量的字典; ‘f_globals’ 则用于查找全
          局变量; ‘f_builtins’ 用于查找内置 (固有) 名称; ‘f_lasti’ 给出
          精确指令 (这是代码对象的字节码字符串的一个索引)。

          访问 ‘f_code’ 会引发一个 *note 审计事件: fa1.
          ‘object.__getattr__’，附带参数 ‘obj’ 和 ‘"f_code"’。

          特殊的可写属性: ‘f_trace’，如果不为 ‘None’，则是在代码执行期间
          调用各类事件的函数 (由调试器使用)。通常每个新源码行会触发一个
          事件 - 这可以通过将 ‘f_trace_lines’ 设为 *note False: 48e. 来
          禁用。

          具体的实现 `可能' 会通过将 ‘f_trace_opcodes’ 设为 *note True:
          593. 来允许按操作码请求事件。请注意如果跟踪函数引发的异常逃逸
          到被跟踪的函数中，这可能会导致未定义的解释器行为。

          ‘f_lineno’ 为帧的当前行号 — 在这里写入从一个跟踪函数内部跳转的
          指定行 (仅用于最底层的帧)。调试器可以通过写入 f_lineno 实现一
          个 Jump 命令 (即设置下一语句)。

          帧对象支持一个方法:

           -- 成員函式: frame.clear ()

               此方法清除该帧持有的全部对本地变量的引用。而且如果该帧属
               于一个生成器，生成器会被完成。这有助于打破包含帧对象的循
               环引用 (例如当捕获一个异常并保存其回溯在之后使用)。

               如果该帧当前正在执行则会引发 *note RuntimeError: 3dc.。

               3.4 版新加入.

     回溯对象

          回溯对象表示一个异常的栈跟踪记录。当异常发生时会隐式地创建一个
          回溯对象，也可能通过调用 *note types.TracebackType: 441. 显式
          地创建。

          对于隐式地创建的回溯对象，当查找异常句柄使得执行栈展开时，会在
          每个展开层级的当前回溯之前插入一个回溯对象。当进入一个异常句柄
          时，栈跟踪将对程序启用。(参见 *note try 语句: e37. 一节。) 它
          可作为 ‘sys.exc_info()’ 所返回的元组的第三项，以及所捕获异常的
          ‘__traceback__’ 属性被获取。

          当程序不包含可用的句柄时，栈跟踪会 (以良好的格式) 写入标准错误
          流；如果解释器处于交互模式，它也可作为 ‘sys.last_traceback’ 对
          用户启用。

          对于显式创建的回溯对象，则由回溯对象的创建者来决定应该如何链接
          ‘tb_next’ 属性来构成完整的栈跟踪。

          特殊的只读属性: ‘tb_frame’ 指向当前层级的执行帧; ‘tb_lineno’ 给
          出发生异常所在的行号; ‘tb_lasti’ 标示具体指令。如果异常发生于
          没有匹配的 except 子句或有 finally 子句的 *note try: e37. 语句
          中，回溯对象中的行号和最后指令可能与相应帧对象中行号不同。

          访问 ‘tb_frame’ 会引发一个 *note 审计事件: fa1.
          ‘object.__getattr__’，附带参数 ‘obj’ 和 ‘"tb_frame"’。

          特殊的可写属性: ‘tb_next’ 为栈跟踪中的下一层级 (通往发生异常的
          帧)，如果没有下一层级则为 ‘None’。

          3.7 版更變: 回溯对象现在可以使用 Python 代码显式地实例化，现有
          实例的 ‘tb_next’ 属性可以被更新。

     切片对象

          Slice objects are used to represent slices for *note
          __getitem__(): 3a5. methods.  They are also created by the
          built-in *note slice(): ec8. function.

          特殊的只读属性: ‘start’ 为下界; ‘stop’ 为上界; ‘step’ 为步长值
          ; 各值如省略则为 ‘None’。这些属性可具有任意类型。

          切片对象支持一个方法:

           -- 成員函式: slice.indices (self, length)

               此方法接受一个整型参数 `length' 并计算在切片对象被应用到
               `length' 指定长度的条目序列时切片的相关信息应如何描述。 其
               返回值为三个整型数组成的元组；这些数分别为切片的 `start'
               和 `stop' 索引号以及 `step' 步长值。索引号缺失或越界则按
               照与正规切片相一致的方式处理。

     静态方法对象

          静态方法对象提供了一种避免上文所述将函数对象转换为方法对象的方
          式。静态方法对象为对任意其他对象的封装，通常用来封装用户定义方
          法对象。当从类或类实例获取一个静态方法对象时，实际返回的对象是
          封装的对象，它不会被进一步转换。静态方法对象自身不是可调用的，
          但它们所封装的对象通常都是可调用的。静态方法对象可通过内置的
          *note staticmethod(): 30a. 构造器来创建。

     类方法对象

          类方法对象和静态方法一样是对其他对象的封装，会改变从类或类实例
          获取该对象的方式。类方法对象在此类获取操作中的行为已在上文 "用
          户定义方法" 一节中描述。类方法对象可通过内置的 *note
          classmethod(): 309. 构造器来创建。


File: python.info,  Node: 特殊方法名称,  Next: 协程,  Prev: 标准类型层级结构,  Up: 数据模型

4.3.3 特殊方法名称
------------------

A class can implement certain operations that are invoked by special
syntax (such as arithmetic operations or subscripting and slicing) by
defining methods with special names.  This is Python’s approach to
`operator overloading', allowing classes to define their own behavior
with respect to language operators.  For instance, if a class defines a
method named *note __getitem__(): 3a5, and ‘x’ is an instance of this
class, then ‘x[i]’ is roughly equivalent to ‘type(x).__getitem__(x, i)’.
Except where mentioned, attempts to execute an operation raise an
exception when no appropriate method is defined (typically *note
AttributeError: 4a1. or *note TypeError: 1fe.).

Setting a special method to ‘None’ indicates that the corresponding
operation is not available.  For example, if a class sets *note
__iter__(): 608. to ‘None’, the class is not iterable, so calling *note
iter(): ded. on its instances will raise a *note TypeError: 1fe.
(without falling back to *note __getitem__(): 3a5.).  (1)

在实现模拟任何内置类型的类时，很重要的一点是模拟的实现程度对于被模拟对象
来说应当是有意义的。例如，提取单个元素的操作对于某些序列来说是适宜的，但
提取切片可能就没有意义。(这种情况的一个实例是 W3C 的文档对象模型中的
‘NodeList’ 接口。)

* Menu:

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

   ---------- Footnotes ----------

   (1) (2) The *note __hash__(): 44c, *note __iter__(): 608, *note
__reversed__(): 628, and *note __contains__(): dee. methods have special
handling for this; others will still raise a *note TypeError: 1fe, but
may do so by relying on the behavior that ‘None’ is not callable.


File: python.info,  Node: 基本定制,  Next: 自定义属性访问,  Up: 特殊方法名称

4.3.3.1 基本定制
................

 -- 成員函式: object.__new__ (cls[, ...])

     调用以创建一个 `cls' 类的新实例。*note __new__(): 974. 是一个静态方
     法 (因为是特例所以你不需要显式地声明)，它会将所请求实例所属的类作为
     第一个参数。其余的参数会被传递给对象构造器表达式 (对类的调用)。
     *note __new__(): 974. 的返回值应为新对象实例 (通常是 `cls' 的实例
     )。

     典型的实现会附带适宜的参数使用 ‘super().__new__(cls[, ...])’，通过
     超类的 *note __new__(): 974. 方法来创建一个类的新实例，然后根据需要
     修改新创建的实例再将其返回。

     If *note __new__(): 974. is invoked during object construction and
     it returns an instance of `cls', then the new instance’s *note
     __init__(): e23. method will be invoked like ‘__init__(self[,
     ...])’, where `self' is the new instance and the remaining
     arguments are the same as were passed to the object constructor.

     如果 *note __new__(): 974. 未返回一个 `cls' 的实例，则新实例的
     *note __init__(): e23. 方法就不会被执行。

     *note __new__(): 974. 的目的主要是允许不可变类型的子类 (例如 int,
     str 或 tuple) 定制实例创建过程。它也常会在自定义元类中被重载以便定
     制类创建过程。

 -- 成員函式: object.__init__ (self[, ...])

     在实例 (通过 *note __new__(): 974.) 被创建之后，返回调用者之前调用
     。其参数与传递给类构造器表达式的参数相同。一个基类如果有 *note
     __init__(): e23. 方法，则其所派生的类如果也有 *note __init__():
     e23. 方法，就必须显式地调用它以确保实例基类部分的正确初始化；例如:
     ‘super().__init__([args...])’.

     因为对象是由 *note __new__(): 974. 和 *note __init__(): e23. 协作构
     造完成的 (由 *note __new__(): 974. 创建，并由 *note __init__():
     e23. 定制)，所以 *note __init__(): e23. 返回的值只能是 ‘None’，否则
     会在运行时引发 *note TypeError: 1fe.。

 -- 成員函式: object.__del__ (self)

     在实例将被销毁时调用。 这还被称为终结器或析构器（不适当）。 如果一
     个基类具有 *note __del__(): a04. 方法，则其所派生的类如果也有 *note
     __del__(): a04. 方法，就必须显式地调用它以确保实例基类部分的正确清
     除。

     *note __del__(): a04. 方法可以 (但不推荐!) 通过创建一个该实例的新引
     用来推迟其销毁。这被称为对象 `重生'。*note __del__(): a04. 是否会在
     重生的对象将被销毁时再次被调用是由具体实现决定的 ；当前的 *note
     CPython: 1569. 实现只会调用一次。

     当解释器退出时不会确保为仍然存在的对象调用 *note __del__(): a04. 方
     法。

          備註: ‘del x’ 并不直接调用 ‘x.__del__()’ — 前者会将 ‘x’ 的引用
          计数减一，而后者仅会在 ‘x’ 的引用计数变为零时被调用。

     `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 *note cyclic garbage collector: fc8.  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.

     也參考
     ......

     *note gc: 84. 模块的文档。

          警告: 由于调用 *note __del__(): a04. 方法时周边状况已不确定，
          在其执行期间发生的异常将被忽略，改为打印一个警告到
          ‘sys.stderr’。特别地：

             * *note __del__(): a04. 可在任意代码被执行时启用，包括来自
               任意线程的代码。如果 *note __del__(): a04. 需要接受锁或启
               用其他阻塞资源，可能会发生死锁，例如该资源已被为执行
               *note __del__(): a04. 而中断的代码所获取。

             * *note __del__(): a04. 可以在解释器关闭阶段被执行。因此，
               它需要访问的全局变量（包含其他模块）可能已被删除或设为
               ‘None’。Python 会保证先删除模块中名称以单个下划线打头的全
               局变量再删除其他全局变量；如果已不存在其他对此类全局变量
               的引用，这有助于确保导入的模块在 *note __del__(): a04. 方
               法被调用时仍然可用。

 -- 成員函式: object.__repr__ (self)

     由 *note repr(): 8b9. 内置函数调用以输出一个对象的“官方”字符串表示
     。如果可能，这应类似一个有效的 Python 表达式，能被用来重建具有相同
     取值的对象（只要有适当的环境）。如果这不可能，则应返回形式如
     ‘<...some useful description...>’ 的字符串。返回值必须是一个字符串
     对象。如果一个类定义了 *note __repr__(): 44a. 但未定义 *note
     __str__(): ef9.，则在需要该类的实例的“非正式”字符串表示时也会使用
     *note __repr__(): 44a.。

     此方法通常被用于调试，因此确保其表示的内容包含丰富信息且无歧义是很
     重要的。

 -- 成員函式: object.__str__ (self)

     通过 *note str(object): 205. 以及内置函数 *note format(): 5d5. 和
     *note print(): 971. 调用以生成一个对象的“非正式”或格式良好的字符串
     表示。返回值必须为一个 *note 字符串: 1357. 对象。

     此方法与 *note object.__repr__(): 44a. 的不同点在于 *note
     __str__(): ef9. 并不预期返回一个有效的 Python 表达式：可以使用更方
     便或更准确的描述信息。

     内置类型 *note object: 3d2. 所定义的默认实现会调用 *note
     object.__repr__(): 44a.。

 -- 成員函式: object.__bytes__ (self)

     通过 *note bytes: 11f2. 调用以生成一个对象的字节串表示。这应该返回
     一个 *note bytes: 172. 对象。

 -- 成員函式: object.__format__ (self, format_spec)

     通过 *note format(): 5d5. 内置函数、扩展、*note 格式化字符串字面值:
     296. 的求值以及 *note str.format(): 5d4. 方法调用以生成一个对象的
     “格式化”字符串表示。 `format_spec' 参数为包含所需格式选项描述的字符
     串。 `format_spec' 参数的解读是由实现 *note __format__(): a2f. 的类
     型决定的，不过大多数类或是将格式化委托给某个内置类型，或是使用相似
     的格式化选项语法。

     请参看 *note 格式规格迷你语言: 5d8. 了解标准格式化语法的描述。

     返回值必须为一个字符串对象。

     3.4 版更變: ‘object’ 本身的 __format__ 方法如果被传入任何非空字符，
     将会引发一个 *note TypeError: 1fe.。

     3.7 版更變: ‘object.__format__(x, '')’ 现在等同于 ‘str(x)’ 而不再是
     ‘format(str(x), '')’。

 -- 成員函式: object.__lt__ (self, other)
 -- 成員函式: object.__le__ (self, other)
 -- 成員函式: object.__eq__ (self, other)
 -- 成員函式: object.__ne__ (self, other)
 -- 成員函式: object.__gt__ (self, other)
 -- 成員函式: object.__ge__ (self, other)

     以上这些被称为“富比较”方法。运算符号与方法名称的对应关系如下：‘x<y’
     调用 ‘x.__lt__(y)’、‘x<=y’ 调用 ‘x.__le__(y)’、‘x==y’ 调用
     ‘x.__eq__(y)’、‘x!=y’ 调用 ‘x.__ne__(y)’、‘x>y’ 调用 ‘x.__gt__(y)’、
     ‘x>=y’ 调用 ‘x.__ge__(y)’。

     如果指定的参数对没有相应的实现，富比较方法可能会返回单例对象
     ‘NotImplemented’。按照惯例，成功的比较会返回 ‘False’ 或 ‘True’。不
     过实际上这些方法可以返回任意值，因此如果比较运算符是要用于布尔值判
     断（例如作为 ‘if’ 语句的条件），Python 会对返回值调用 *note bool():
     2bd. 以确定结果为真还是假。

     在默认情况下，‘object’ 通过使用 ‘is’ 来实现 *note __eq__(): 44b.，
     并在比较结果为假值时返回 ‘NotImplemented’: ‘True if x is y else
     NotImplemented’。 对于 *note __ne__(): f18.，默认会委托给 *note
     __eq__(): 44b. 并对结果取反，除非结果为 ‘NotImplemented’。 比较运算
     符之间没有其他隐含关系或默认实现；例如，‘(x<y or x==y)’ 为真并不意
     味着 ‘x<=y’。 要根据单根运算自动生成排序操作，请参看 *note
     functools.total_ordering(): 938.。

     请查看 *note __hash__(): 44c. 的相关段落，了解创建可支持自定义比较
     运算并可用作字典键的 *note hashable: 276. 对象时要注意的一些事项。

     这些方法并没有对调参数版本（在左边参数不支持该操作但右边参数支持时
     使用）；而是 *note __lt__(): cfe. 和 *note __gt__(): d69. 互为对方
     的反射， *note __le__(): d68. 和 *note __ge__(): d6a. 互为对方的反
     射，而 *note __eq__(): 44b. 和 *note __ne__(): f18. 则是它们自己的
     反射。如果两个操作数的类型不同，且右操作数类型是左操作数类型的直接
     或间接子类，则优先选择右操作数的反射方法，否则优先选择左操作数的方
     法。虚拟子类不会被考虑。

 -- 成員函式: object.__hash__ (self)

     通过内置函数 *note hash(): aa3. 调用以对哈希集的成员进行操作，属于
     哈希集的类型包括 *note set: 1f6.、*note frozenset: 1f7. 以及 *note
     dict: 164.。*note __hash__(): 44c. 应该返回一个整数。对象比较结果相
     同所需的唯一特征属性是其具有相同的哈希值；建议的做法是把参与比较的
     对象全部组件的哈希值混在一起，即将它们打包为一个元组并对该元组做哈
     希运算。例如:

          def __hash__(self):
              return hash((self.name, self.nick, self.color))

          備註: *note hash(): aa3. 会从一个对象自定义的 *note
          __hash__(): 44c. 方法返回值中截断为 ‘Py_ssize_t’ 的大小。通常
          对 64 位构建为 8 字节，对 32 位构建为 4 字节。如果一个对象的
          *note __hash__(): 44c. 必须在不同位大小的构建上进行互操作，请
          确保检查全部所支持构建的宽度。做到这一点的简单方法是使用
          ‘python -c "import sys; print(sys.hash_info.width)"’。

     如果一个类没有定义 *note __eq__(): 44b. 方法，那么也不应该定义
     *note __hash__(): 44c. 操作；如果它定义了 *note __eq__(): 44b. 但没
     有定义 *note __hash__(): 44c.，则其实例将不可被用作可哈希集的项。如
     果一个类定义了可变对象并实现了 *note __eq__(): 44b. 方法，则不应该
     实现 *note __hash__(): 44c.，因为可哈希集的实现要求键的哈希集是不可
     变的（如果对象的哈希值发生改变，它将处于错误的哈希桶中）。

     用户定义的类默认带有 *note __eq__(): 44b. 和 *note __hash__(): 44c.
     方法；使用它们与任何对象（自己除外）比较必定不相等，并且
     ‘x.__hash__()’ 会返回一个恰当的值以确保 ‘x == y’ 同时意味着 ‘x is
     y’ 且 ‘hash(x) == hash(y)’。

     一个类如果重载了 *note __eq__(): 44b. 且没有定义 *note __hash__():
     44c. 则会将其 *note __hash__(): 44c. 隐式地设为 ‘None’。当一个类的
     *note __hash__(): 44c. 方法为 ‘None’ 时，该类的实例将在一个程序尝试
     获取其哈希值时正确地引发 *note TypeError: 1fe.，并会在检测
     ‘isinstance(obj, collections.abc.Hashable)’ 时被正确地识别为不可哈
     希对象。

     如果一个重载了 *note __eq__(): 44b. 的类需要保留来自父类的 *note
     __hash__(): 44c. 实现，则必须通过设置 ‘__hash__ =
     <ParentClass>.__hash__’ 来显式地告知解释器。

     如果一个没有重载 *note __eq__(): 44b. 的类需要去掉哈希支持，则应该
     在类定义中包含 ‘__hash__ = None’。一个自定义了 *note __hash__():
     44c. 以显式地引发 *note TypeError: 1fe. 的类会被 ‘isinstance(obj,
     collections.abc.Hashable)’ 调用错误地识别为可哈希对象。

          備註: 在默认情况下，str 和 bytes 对象的 *note __hash__(): 44c.
          值会使用一个不可预知的随机值“加盐”。 虽然它们在一个单独 Python
          进程中会保持不变，但它们的值在重复运行的 Python 间是不可预测的
          。

          This is intended to provide protection against a
          denial-of-service caused by carefully-chosen inputs that
          exploit the worst case performance of a dict insertion, O(n^2)
          complexity.  See
          ‘http://www.ocert.org/advisories/ocert-2011-003.html’ for
          details.

          改变哈希值会影响集合的迭代次序。Python 也从不保证这个次序不会
          被改变（通常它在 32 位和 64 位构建上是不一致的）。

          另见 *note PYTHONHASHSEED: aa4.

     3.3 版更變: 默认启用哈希随机化。

 -- 成員函式: object.__bool__ (self)

     调用此方法以实现真值检测以及内置的 ‘bool()’ 操作；应该返回 ‘False’
     或 ‘True’。如果未定义此方法，则会查找并调用 *note __len__(): e90. 并
     在其返回非零值时视对象的逻辑值为真。如果一个类既未定义 *note
     __len__(): e90. 也未定义 *note __bool__(): d30. 则视其所有实例的逻
     辑值为真。


File: python.info,  Node: 自定义属性访问,  Next: 自定义类创建,  Prev: 基本定制,  Up: 特殊方法名称

4.3.3.2 自定义属性访问
......................

可以定义下列方法来自定义对类实例属性访问（‘x.name’ 的使用、赋值或删除）
的具体含义.

 -- 成員函式: object.__getattr__ (self, name)

     当默认属性访问因引发 *note AttributeError: 4a1. 而失败时被调用 (可
     能是调用 *note __getattribute__(): 549. 时由于 `name' 不是一个实例
     属性或 ‘self’ 的类关系树中的属性而引发了 *note AttributeError:
     4a1.；或者是对 `name' 特性属性调用 *note __get__(): 156e. 时引发了
     *note AttributeError: 4a1.)。此方法应当返回（找到的）属性值或是引发
     一个 *note AttributeError: 4a1. 异常。

     请注意如果属性是通过正常机制找到的，*note __getattr__(): 42a. 就不
     会被调用。（这是在 *note __getattr__(): 42a. 和 *note
     __setattr__(): eee. 之间故意设置的不对称性。）这既是出于效率理由也
     是因为不这样设置的话 *note __getattr__(): 42a. 将无法访问实例的其他
     属性。要注意至少对于实例变量来说，你不必在实例属性字典中插入任何值
     （而是通过插入到其他对象）就可以模拟对它的完全控制。请参阅下面的
     *note __getattribute__(): 549. 方法了解真正获取对属性访问的完全控制
     权的办法。

 -- 成員函式: object.__getattribute__ (self, name)

     此方法会无条件地被调用以实现对类实例属性的访问。如果类还定义了
     *note __getattr__(): 42a.，则后者不会被调用，除非 *note
     __getattribute__(): 549. 显式地调用它或是引发了 *note
     AttributeError: 4a1.。此方法应当返回（找到的）属性值或是引发一个
     *note AttributeError: 4a1. 异常。为了避免此方法中的无限递归，其实现
     应该总是调用具有相同名称的基类方法来访问它所需要的任何属性，例如
     ‘object.__getattribute__(self, name)’。

          備註: 此方法在作为通过特定语法或内置函数隐式地调用的结果的情况
          下查找特殊方法时仍可能会被跳过。参见 *note 特殊方法查找:
          156f.。

     引发一个 *note 审计事件: fa1. ‘object.__getattr__’，附带参数 ‘obj’,
     ‘name’。

 -- 成員函式: object.__setattr__ (self, name, value)

     此方法在一个属性被尝试赋值时被调用。这个调用会取代正常机制（即将值
     保存到实例字典）。 `name' 为属性名称， `value' 为要赋给属性的值。

     如果 *note __setattr__(): eee. 想要赋值给一个实例属性，它应该调用同
     名的基类方法，例如 ‘object.__setattr__(self, name, value)’。

     引发一个 *note 审计事件: fa1. ‘object.__setattr__’，附带参数 ‘obj’,
     ‘name’, ‘value’。

 -- 成員函式: object.__delattr__ (self, name)

     类似于 *note __setattr__(): eee. 但其作用为删除而非赋值。此方法应该
     仅在 ‘del obj.name’ 对于该对象有意义时才被实现。

     引发一个 *note 审计事件: fa1. ‘object.__delattr__’，附带参数 ‘obj’,
     ‘name’。

 -- 成員函式: object.__dir__ (self)

     此方法会在对相应对象调用 *note dir(): df9. 时被调用。返回值必须为一
     个序列。 *note dir(): df9. 会把返回的序列转换为列表并对其排序。

* Menu:

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


File: python.info,  Node: 自定义模块属性访问,  Next: 实现描述器,  Up: 自定义属性访问

4.3.3.3 自定义模块属性访问
..........................

特殊名称 ‘__getattr__’ 和 ‘__dir__’ 还可被用来自定义对模块属性的访问。模
块层级的 ‘__getattr__’ 函数应当接受一个参数，其名称为一个属性名，并返回
计算结果值或引发一个 *note AttributeError: 4a1.。如果通过正常查找即
*note object.__getattribute__(): 549. 未在模块对象中找到某个属性，则
‘__getattr__’ 会在模块的 ‘__dict__’ 中查找，未找到时会引发一个 *note
AttributeError: 4a1.。如果找到，它会以属性名被调用并返回结果值。

‘__dir__’ 函数应当不接受任何参数，并且返回一个表示模块中可访问名称的字符
串序列。 此函数如果存在，将会重载一个模块中的标准 *note dir(): df9. 查找
。

想要更细致地自定义模块的行为（设置属性和特性属性等待），可以将模块对象的
‘__class__’ 属性设置为一个 *note types.ModuleType: 7e2. 的子类。例如:

     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

     備註: 定义模块的 ‘__getattr__’ 和设置模块的 ‘__class__’ 只会影响使
     用属性访问语法进行的查找 – 直接访问模块全局变量（不论是通过模块内的
     代码还是通过对模块全局字典的引用）是不受影响的。

3.5 版更變: ‘__class__’ 模块属性改为可写。

3.7 版新加入: ‘__getattr__’ 和 ‘__dir__’ 模块属性。

也參考
......

PEP 562(1) - 模块 __getattr__ 和 __dir__

     描述用于模块的 ‘__getattr__’ 和 ‘__dir__’ 函数。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0562


File: python.info,  Node: 实现描述器,  Next: 发起调用描述器,  Prev: 自定义模块属性访问,  Up: 自定义属性访问

4.3.3.4 实现描述器
..................

以下方法仅当一个包含该方法的类（称为 `描述器' 类）的实例出现于一个 `所有
者' 类中的时候才会起作用（该描述器必须在所有者类或其某个上级类的字典中）
。在以下示例中，“属性”指的是名称为所有者类 *note __dict__: 5f5. 中的特征
属性的键名的属性。

 -- 成員函式: object.__get__ (self, instance, owner=None)

     调用此方法以获取所有者类的属性（类属性访问）或该类的实例的属性（实
     例属性访问）。 可选的 `owner' 参数是所有者类而 `instance' 是被用来
     访问属性的实例，如果通过 `owner' 来访问属性则返回 ‘None’。

     此方法应当返回计算得到的属性值或是引发 *note AttributeError: 4a1. 异
     常。

     PEP 252(1) 指明 *note __get__(): 156e. 为带有一至二个参数的可调用对
     象。 Python 自身内置的描述器支持此规格定义；但是，某些第三方工具可
     能要求必须带两个参数。 Python 自身的 *note __getattribute__(): 549.
     实现总是会传入两个参数，无论它们是否被要求提供。

 -- 成員函式: object.__set__ (self, instance, value)

     调用此方法以设置 `instance' 指定的所有者类的实例的属性为新值
     `value'。

     请注意，添加 *note __set__(): 1572. 或 *note __delete__(): 1573. 会
     将描述器变成“数据描述器”。 更多细节请参阅 *note 发起调用描述器:
     1574.。

 -- 成員函式: object.__delete__ (self, instance)

     调用此方法以删除 `instance' 指定的所有者类的实例的属性。

 -- 成員函式: object.__set_name__ (self, owner, name)

     在所有者类 `owner' 创建时被调用。描述器会被赋值给 `name'。

          備註: *note __set_name__(): 5e2. 只是作为 *note type: 6ff. 构
          造器的一部分被隐式地调用，因此在某个类被初次创建之后又额外添加
          一个描述器时，那就需要显式地调用它并且附带适当的形参:

               class A:
                  pass
               descr = custom_descriptor()
               A.attr = descr
               descr.__set_name__(A, 'attr')

          详情参见 *note 创建类对象: 5de.。

     3.6 版新加入.

属性 ‘__objclass__’ 会被 *note inspect: a0. 模块解读为指定此对象定义所在
的类（正确设置此属性有助于动态类属性的运行时内省）。对于可调用对象来说，
它可以指明预期或要求提供一个特定类型（或子类）的实例作为第一个位置参数（
例如，CPython 会为实现于 C 中的未绑定方法设置此属性）。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0252


File: python.info,  Node: 发起调用描述器,  Next: __slots__,  Prev: 实现描述器,  Up: 自定义属性访问

4.3.3.5 发起调用描述器
......................

In general, a descriptor is an object attribute with "binding behavior",
one whose attribute access has been overridden by methods in the
descriptor protocol: *note __get__(): 156e, *note __set__(): 1572, and
*note __delete__(): 1573.  If any of those methods are defined for an
object, it is said to be a descriptor.

属性访问的默认行为是从一个对象的字典中获取、设置或删除属性。例如，‘a.x’
的查找顺序会从 ‘a.__dict__['x']’ 开始，然后是 ‘type(a).__dict__['x']’，
接下来依次查找 ‘type(a)’ 的上级基类，不包括元类。

但是，如果找到的值是定义了某个描述器方法的对象，则 Python 可能会重载默认
行为并转而发起调用描述器方法。这具体发生在优先级链的哪个环节则要根据所定
义的描述器方法及其被调用的方式来决定。

描述器发起调用的开始点是一个绑定 ‘a.x’。参数的组合方式依 ‘a’ 而定:

直接调用

     最简单但最不常见的调用方式是用户代码直接发起调用一个描述器方法:
     ‘x.__get__(a)’。

实例绑定

     如果绑定到一个对象实例，‘a.x’ 会被转换为调用:
     ‘type(a).__dict__['x'].__get__(a, type(a))’。

类绑定

     如果绑定到一个类，‘A.x’ 会被转换为调用:
     ‘A.__dict__['x'].__get__(None, A)’。

超绑定

     If ‘a’ is an instance of *note super: 5dd, then the binding
     ‘super(B, obj).m()’ searches ‘obj.__class__.__mro__’ for the base
     class ‘A’ immediately following ‘B’ and then invokes the descriptor
     with the call: ‘A.__dict__['m'].__get__(obj, obj.__class__)’.

For instance bindings, the precedence of descriptor invocation depends
on which descriptor methods are defined.  A descriptor can define any
combination of *note __get__(): 156e, *note __set__(): 1572. and *note
__delete__(): 1573.  If it does not define *note __get__(): 156e, then
accessing the attribute will return the descriptor object itself unless
there is a value in the object’s instance dictionary.  If the descriptor
defines *note __set__(): 1572. and/or *note __delete__(): 1573, it is a
data descriptor; if it defines neither, it is a non-data descriptor.
Normally, data descriptors define both *note __get__(): 156e. and *note
__set__(): 1572, while non-data descriptors have just the *note
__get__(): 156e. method.  Data descriptors with *note __get__(): 156e.
and *note __set__(): 1572. (and/or *note __delete__(): 1573.) defined
always override a redefinition in an instance dictionary.  In contrast,
non-data descriptors can be overridden by instances.

Python methods (including those decorated with *note @staticmethod: 30a.
and *note @classmethod: 309.) are implemented as non-data descriptors.
Accordingly, instances can redefine and override methods.  This allows
individual instances to acquire behaviors that differ from other
instances of the same class.

*note property(): 308. 函数是作为数据描述器来实现的。因此实例不能重载特
性属性的行为。


File: python.info,  Node: __slots__,  Prev: 发起调用描述器,  Up: 自定义属性访问

4.3.3.6 __slots__
.................

`__slots__' allow us to explicitly declare data members (like
properties) and deny the creation of *note __dict__: 5f5. and
`__weakref__' (unless explicitly declared in `__slots__' or available in
a parent.)

The space saved over using *note __dict__: 5f5. can be significant.
Attribute lookup speed can be significantly improved as well.

 -- Data: object.__slots__

     This class variable can be assigned a string, iterable, or sequence
     of strings with variable names used by instances.  `__slots__'
     reserves space for the declared variables and prevents the
     automatic creation of *note __dict__: 5f5. and `__weakref__' for
     each instance.

* Menu:

* 使用 __slots__ 的注意事项::


File: python.info,  Node: 使用 __slots__ 的注意事项,  Up: __slots__

4.3.3.7 使用 `__slots__' 的注意事项
...................................

   * When inheriting from a class without `__slots__', the *note
     __dict__: 5f5. and `__weakref__' attribute of the instances will
     always be accessible.

   * Without a *note __dict__: 5f5. variable, instances cannot be
     assigned new variables not listed in the `__slots__' definition.
     Attempts to assign to an unlisted variable name raises *note
     AttributeError: 4a1.  If dynamic assignment of new variables is
     desired, then add ‘'__dict__'’ to the sequence of strings in the
     `__slots__' declaration.

   * Without a `__weakref__' variable for each instance, classes
     defining `__slots__' do not support *note weak references: 131. to
     its instances.  If weak reference support is needed, then add
     ‘'__weakref__'’ to the sequence of strings in the `__slots__'
     declaration.

   * `__slots__' are implemented at the class level by creating *note
     descriptors: 5e3. for each variable name.  As a result, class
     attributes cannot be used to set default values for instance
     variables defined by `__slots__'; otherwise, the class attribute
     would overwrite the descriptor assignment.

   * The action of a `__slots__' declaration is not limited to the class
     where it is defined.  `__slots__' declared in parents are available
     in child classes.  However, child subclasses will get a *note
     __dict__: 5f5. and `__weakref__' unless they also define
     `__slots__' (which should only contain names of any `additional'
     slots).

   * 如果一个类定义的位置在某个基类中也有定义，则由基类位置定义的实例变
     量将不可访问（除非通过直接从基类获取其描述器的方式）。这会使得程序
     的含义变成未定义。未来可能会添加一个防止此情况的检查。

   * 非空的 `__slots__' 不适用于派生自“可变长度”内置类型例如 *note int:
     204.、*note bytes: 172. 和 *note tuple: 1a2. 的派生类。

   * Any non-string *note iterable: c7c. may be assigned to `__slots__'.

   * If a *note dictionary: 164. is used to assign `__slots__', the
     dictionary keys will be used as the slot names.  The values of the
     dictionary can be used to provide per-attribute docstrings that
     will be recognised by *note inspect.getdoc(): 307. and displayed in
     the output of *note help(): 175.

   * *note __class__: ecc. assignment works only if both classes have
     the same `__slots__'.

   * *note Multiple inheritance: 1406. with multiple slotted parent
     classes can be used, but only one parent is allowed to have
     attributes created by slots (the other bases must have empty slot
     layouts) - violations raise *note TypeError: 1fe.

   * If an *note iterator: 1171. is used for `__slots__' then a *note
     descriptor: 1579. is created for each of the iterator’s values.
     However, the `__slots__' attribute will be an empty iterator.


File: python.info,  Node: 自定义类创建,  Next: 自定义实例及子类检查,  Prev: 自定义属性访问,  Up: 特殊方法名称

4.3.3.8 自定义类创建
....................

Whenever a class inherits from another class, *note __init_subclass__():
5dc. is called on that class.  This way, it is possible to write classes
which change the behavior of subclasses.  This is closely related to
class decorators, but where class decorators only affect the specific
class they’re applied to, ‘__init_subclass__’ solely applies to future
subclasses of the class defining the method.

 -- 成員函式: classmethod object.__init_subclass__ (cls)

     当所在类派生子类时此方法就会被调用。`cls' 将指向新的子类。如果定义
     为一个普通实例方法，此方法将被隐式地转换为类方法。

     传入一个新类的关键字参数会被传给父类的 ‘__init_subclass__’。为了与
     其他使用 ‘__init_subclass__’ 的类兼容，应当根据需要去掉部分关键字参
     数再将其余的传给基类，例如:

          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

     ‘object.__init_subclass__’ 的默认实现什么都不做，只在带任意参数调用
     时引发一个错误。

          備註: 元类提示 ‘metaclass’ 将被其它类型机制消耗掉，并不会被传
          给 ‘__init_subclass__’ 的实现。实际的元类（而非显式的提示）可
          通过 ‘type(cls)’ 访问。

     3.6 版新加入.

* Menu:

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


File: python.info,  Node: 元类,  Next: 解析 MRO 条目,  Up: 自定义类创建

4.3.3.9 元类
............

默认情况下，类是使用 *note type(): 6ff. 来构建的。类体会在一个新的命名空
间内执行，类名会被局部绑定到 ‘type(name, bases, namespace)’ 的结果。

类创建过程可通过在定义行传入 ‘metaclass’ 关键字参数，或是通过继承一个包
含此参数的现有类来进行定制。在以下示例中，‘MyClass’ 和 ‘MySubclass’ 都是
‘Meta’ 的实例:

     class Meta(type):
         pass

     class MyClass(metaclass=Meta):
         pass

     class MySubclass(MyClass):
         pass

在类定义内指定的任何其他关键字参数都会在下面所描述的所有元类操作中进行传
递。

当一个类定义被执行时，将发生以下步骤:

   * 解析 MRO 条目；

   * 确定适当的元类；

   * 准备类命名空间；

   * 执行类主体；

   * 创建类对象。


File: python.info,  Node: 解析 MRO 条目,  Next: 确定适当的元类,  Prev: 元类,  Up: 自定义类创建

4.3.3.10 解析 MRO 条目
......................

如果在类定义中出现的基类不是 *note type: 6ff. 的实例，则使用
‘__mro_entries__’ 方法对其进行搜索，当找到结果时，它会以原始基类元组做参
数进行调用。此方法必须返回类的元组以替代此基类被使用。元组可以为空，在此
情况下原始基类将被忽略。

也參考
......

PEP 560(1) - 对 typing 模块和泛型类型的核心支持

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0560


File: python.info,  Node: 确定适当的元类,  Next: 准备类命名空间,  Prev: 解析 MRO 条目,  Up: 自定义类创建

4.3.3.11 确定适当的元类
.......................

为一个类定义确定适当的元类是根据以下规则:

   * 如果没有基类且没有显式指定元类，则使用 *note type(): 6ff.；

   * 如果给出一个显式元类而且 `不是' *note type(): 6ff. 的实例，则其会被
     直接用作元类；

   * 如果给出一个 *note type(): 6ff. 的实例作为显式元类，或是定义了基类
     ，则使用最近派生的元类。

最近派生的元类会从显式指定的元类（如果有）以及所有指定的基类的元类（即
‘type(cls)’）中选取。最近派生的元类应为 `所有' 这些候选元类的一个子类型
。如果没有一个候选元类符合该条件，则类定义将失败并抛出 ‘TypeError’。


File: python.info,  Node: 准备类命名空间,  Next: 执行类主体,  Prev: 确定适当的元类,  Up: 自定义类创建

4.3.3.12 准备类命名空间
.......................

Once the appropriate metaclass has been identified, then the class
namespace is prepared.  If the metaclass has a ‘__prepare__’ attribute,
it is called as ‘namespace = metaclass.__prepare__(name, bases, **kwds)’
(where the additional keyword arguments, if any, come from the class
definition).  The ‘__prepare__’ method should be implemented as a *note
classmethod: 309.  The namespace returned by ‘__prepare__’ is passed in
to ‘__new__’, but when the final class object is created the namespace
is copied into a new ‘dict’.

如果元类没有 ‘__prepare__’ 属性，则类命名空间将初始化为一个空的有序映射
。

也參考
......

PEP 3115(1) - Python 3000 中的元类

     引入 ‘__prepare__’ 命名空间钩子

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3115


File: python.info,  Node: 执行类主体,  Next: 创建类对象,  Prev: 准备类命名空间,  Up: 自定义类创建

4.3.3.13 执行类主体
...................

类主体会以（类似于） ‘exec(body, globals(), namespace)’ 的形式被执行。普
通调用与 *note exec(): d0c. 的关键区别在于当类定义发生于函数内部时，词法
作用域允许类主体（包括任何方法）引用来自当前和外部作用域的名称。

但是，即使当类定义发生于函数内部时，在类内部定义的方法仍然无法看到在类作
用域层次上定义的名称。类变量必须通过实例的第一个形参或类方法来访问，或者
是通过下一节中描述的隐式词法作用域的 ‘__class__’ 引用。


File: python.info,  Node: 创建类对象,  Next: 元类的作用,  Prev: 执行类主体,  Up: 自定义类创建

4.3.3.14 创建类对象
...................

一旦执行类主体完成填充类命名空间，将通过调用 ‘metaclass(name, bases,
namespace, **kwds)’ 创建类对象（此处的附加关键字参数与传入 ‘__prepare__’
的相同）。

如果类主体中有任何方法引用了 ‘__class__’ 或 ‘super’，这个类对象会通过零
参数形式的 *note super(): 5dd.  ‘__class__’ 所引用，这是由编译器所创建的
隐式闭包引用。这使用零参数形式的 *note super(): 5dd. 能够正确标识正在基
于词法作用域来定义的类，而被用于进行当前调用的类或实例则是基于传递给方法
的第一个参数来标识的。

`CPython implementation detail:' 在 CPython 3.6 及之后的版本中，
‘__class__’ 单元会作为类命名空间中的 ‘__classcell__’ 条目被传给元类。 如
果存在，它必须被向上传播给 ‘type.__new__’ 调用，以便能正确地初始化该类。
如果不这样做，在 Python 3.8 中将引发 *note RuntimeError: 3dc.。

当使用默认的元类 *note type: 6ff. 或者任何最终会调用 ‘type.__new__’ 的元
类时，以下额外的自定义步骤将在创建类对象之后被发起调用:

   * 首先，‘type.__new__’ 将收集类命名空间中所有定义了 *note
     __set_name__(): 5e2. 方法的描述器；

   * 接下来，所有这些 ‘__set_name__’ 方法将使用所定义的类和特定描述器所
     赋的名称进行调用；

   * 最后，将在新类根据方法解析顺序所确定的直接父类上调用 *note
     __init_subclass__(): 5dc. 钩子。

在类对象创建之后，它会被传给包含在类定义中的类装饰器（如果有的话），得到
的对象将作为已定义的类绑定到局部命名空间。

当通过 ‘type.__new__’ 创建一个新类时，提供以作为命名空间形参的对象会被复
制到一个新的有序映射并丢弃原对象。这个新副本包装于一个只读代理中，后者则
成为类对象的 *note __dict__: 5f5. 属性。

也參考
......

PEP 3135(1) - 新的超类型

     描述隐式的 ‘__class__’ 闭包引用

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3135


File: python.info,  Node: 元类的作用,  Prev: 创建类对象,  Up: 自定义类创建

4.3.3.15 元类的作用
...................

元类的潜在作用非常广泛。已经过尝试的设想包括枚举、日志、接口检查、自动委
托、自动特征属性创建、代理、框架以及自动资源锁定/同步等等。


File: python.info,  Node: 自定义实例及子类检查,  Next: 模拟泛型类型,  Prev: 自定义类创建,  Up: 特殊方法名称

4.3.3.16 自定义实例及子类检查
.............................

以下方法被用来重载 *note isinstance(): 551. 和 *note issubclass(): 552.
内置函数的默认行为。

特别地，元类 *note abc.ABCMeta: 906. 实现了这些方法以便允许将抽象基类（
ABC）作为“虚拟基类”添加到任何类或类型（包括内置类型），包括其他 ABC 之中
。

 -- 成員函式: class.__instancecheck__ (self, instance)

     如果 `instance' 应被视为 `class' 的一个（直接或间接）实例则返回真值
     。如果定义了此方法，则会被调用以实现 ‘isinstance(instance, class)’。

 -- 成員函式: class.__subclasscheck__ (self, subclass)

     Return true 如果 `subclass' 应被视为 `class' 的一个（直接或间接）子
     类则返回真值。如果定义了此方法，则会被调用以实现
     ‘issubclass(subclass, class)’。

请注意这些方法的查找是基于类的类型（元类）。它们不能作为类方法在实际的类
中被定义。这与基于实例被调用的特殊方法的查找是一致的，只有在此情况下实例
本身被当作是类。

也參考
......

PEP 3119(1) - 引入抽象基类

     新增功能描述，通过 *note __instancecheck__(): 1584. 和 *note
     __subclasscheck__(): 1585. 来定制 *note isinstance(): 551. 和 *note
     issubclass(): 552. 行为，加入此功能的动机是出于向该语言添加抽象基类
     的内容（参见 *note abc: 3. 模块）。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3119


File: python.info,  Node: 模拟泛型类型,  Next: 模拟可调用对象,  Prev: 自定义实例及子类检查,  Up: 特殊方法名称

4.3.3.17 模拟泛型类型
.....................

When using *note type annotations: 1587, it is often useful to
`parameterize' a *note generic type: fea. using Python’s square-brackets
notation.  For example, the annotation ‘list[int]’ might be used to
signify a *note list: 1f8. in which all the elements are of type *note
int: 204.

也參考
......

PEP 484(1) - Type Hints

     Introducing Python’s framework for type annotations

*note Generic Alias Types: fe5.

     Documentation for objects representing parameterized generic
     classes

*note 泛型（Generic）: 1588, *note user-defined generics: 1589. and *note typing.Generic: 100b.

     Documentation on how to implement generic classes that can be
     parameterized at runtime and understood by static type-checkers.

A class can `generally' only be parameterized if it defines the special
class method ‘__class_getitem__()’.

 -- 成員函式: classmethod object.__class_getitem__ (cls, key)

     按照 `key' 参数指定的类型返回一个表示泛型类的专门化对象。

     When defined on a class, ‘__class_getitem__()’ is automatically a
     class method.  As such, there is no need for it to be decorated
     with *note @classmethod: 309. when it is defined.

* Menu:

* The purpose of __class_getitem__::
* __class_getitem__ versus __getitem__::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0484


File: python.info,  Node: The purpose of __class_getitem__,  Next: __class_getitem__ versus __getitem__,  Up: 模拟泛型类型

4.3.3.18 The purpose of `__class_getitem__'
...........................................

The purpose of *note __class_getitem__(): 437. is to allow runtime
parameterization of standard-library generic classes in order to more
easily apply *note type hints: 158b. to these classes.

To implement custom generic classes that can be parameterized at runtime
and understood by static type-checkers, users should either inherit from
a standard library class that already implements *note
__class_getitem__(): 437, or inherit from *note typing.Generic: 100b,
which has its own implementation of ‘__class_getitem__()’.

Custom implementations of *note __class_getitem__(): 437. on classes
defined outside of the standard library may not be understood by
third-party type-checkers such as mypy.  Using ‘__class_getitem__()’ on
any class for purposes other than type hinting is discouraged.


File: python.info,  Node: __class_getitem__ versus __getitem__,  Prev: The purpose of __class_getitem__,  Up: 模拟泛型类型

4.3.3.19 `__class_getitem__' versus `__getitem__'
.................................................

Usually, the *note subscription: 158e. of an object using square
brackets will call the *note __getitem__(): 3a5. instance method defined
on the object’s class.  However, if the object being subscribed is
itself a class, the class method *note __class_getitem__(): 437. may be
called instead.  ‘__class_getitem__()’ should return a *note
GenericAlias: fe5. object if it is properly defined.

Presented with the *note expression: 158f. ‘obj[x]’, the Python
interpreter follows something like the following process to decide
whether *note __getitem__(): 3a5. or *note __class_getitem__(): 437.
should be called:

     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"
             )

In Python, all classes are themselves instances of other classes.  The
class of a class is known as that class’s *note metaclass: 1590, and
most classes have the *note type: 6ff. class as their metaclass.  *note
type: 6ff. does not define *note __getitem__(): 3a5, meaning that
expressions such as ‘list[int]’, ‘dict[str, float]’ and ‘tuple[str,
bytes]’ all result in *note __class_getitem__(): 437. being called:

     >>> # 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'>

However, if a class has a custom metaclass that defines *note
__getitem__(): 3a5, subscribing the class may result in different
behaviour.  An example of this can be found in the *note enum: 79.
module:

     >>> 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'>

也參考
......

PEP 560(1) - Core Support for typing module and generic types

     Introducing *note __class_getitem__(): 437, and outlining when a
     *note subscription: 158e. results in ‘__class_getitem__()’ being
     called instead of *note __getitem__(): 3a5.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0560


File: python.info,  Node: 模拟可调用对象,  Next: 模拟容器类型,  Prev: 模拟泛型类型,  Up: 特殊方法名称

4.3.3.20 模拟可调用对象
.......................

 -- 成員函式: object.__call__ (self[, args...])

     此方法会在实例作为一个函数被“调用”时被调用；如果定义了此方法，则
     ‘x(arg1, arg2, ...)’ 就大致可以被改写为 ‘type(x).__call__(x, arg1,
     ...)’。


File: python.info,  Node: 模拟容器类型,  Next: 模拟数字类型,  Prev: 模拟可调用对象,  Up: 特殊方法名称

4.3.3.21 模拟容器类型
.....................

The following methods can be defined to implement container objects.
Containers usually are *note sequences: 135c. (such as *note lists: 1f8.
or *note tuples: 1a2.) or *note mappings: c0b. (like *note dictionaries:
164.), but can represent other containers as well.  The first set of
methods is used either to emulate a sequence or to emulate a mapping;
the difference is that for a sequence, the allowable keys should be the
integers `k' for which ‘0 <= k < N’ where `N' is the length of the
sequence, or *note slice: ec8. objects, which define a range of items.
It is also recommended that mappings provide the methods ‘keys()’,
‘values()’, ‘items()’, ‘get()’, ‘clear()’, ‘setdefault()’, ‘pop()’,
‘popitem()’, ‘copy()’, and ‘update()’ behaving similar to those for
Python’s standard *note dictionary: 164. objects.  The *note
collections.abc: 1e. module provides a *note MutableMapping: ace. *note
abstract base class: c05. to help create those methods from a base set
of *note __getitem__(): 3a5, *note __setitem__(): d2a, *note
__delitem__(): d2b, and ‘keys()’.  Mutable sequences should provide
methods ‘append()’, ‘count()’, ‘index()’, ‘extend()’, ‘insert()’,
‘pop()’, ‘remove()’, ‘reverse()’ and ‘sort()’, like Python standard
*note list: 1f8. objects.  Finally, sequence types should implement
addition (meaning concatenation) and multiplication (meaning repetition)
by defining the methods *note __add__(): 1595, *note __radd__(): 1596,
*note __iadd__(): f30, *note __mul__(): 1597, *note __rmul__(): 1598.
and *note __imul__(): 1599. described below; they should not define
other numerical operators.  It is recommended that both mappings and
sequences implement the *note __contains__(): dee. method to allow
efficient use of the ‘in’ operator; for mappings, ‘in’ should search the
mapping’s keys; for sequences, it should search through the values.  It
is further recommended that both mappings and sequences implement the
*note __iter__(): 608. method to allow efficient iteration through the
container; for mappings, *note __iter__(): 608. should iterate through
the object’s keys; for sequences, it should iterate through the values.

 -- 成員函式: object.__len__ (self)

     调用此方法以实现内置函数 *note len(): 28b.。应该返回对象的长度，以
     一个 ‘>=’ 0 的整数表示。此外，如果一个对象未定义 *note __bool__():
     d30. 方法而其 *note __len__(): e90. 方法返回值为零，则在布尔运算中
     会被视为假值。

     `CPython implementation detail:' 在 CPython 中，要求长度最大为
     *note sys.maxsize: c15.。如果长度大于 ‘sys.maxsize’ 则某些特性 (例
     如 *note len(): 28b.) 可能会引发 *note OverflowError: a41.。要通过
     真值检测来防止引发 ‘OverflowError’，对象必须定义 *note __bool__():
     d30. 方法。

 -- 成員函式: object.__length_hint__ (self)

     调用此方法以实现 *note operator.length_hint(): 968.。 应该返回对象
     长度的估计值（可能大于或小于实际长度）。 此长度应为一个 ‘>=’ 0 的整
     数。 返回值也可以为 *note NotImplemented: 202.，这会被视作与
     ‘__length_hint__’ 方法完全不存在时一样处理。 此方法纯粹是为了优化性
     能，并不要求正确无误。

     3.4 版新加入.

     備註: 切片是通过下述三个专门方法完成的。以下形式的调用

          a[1:2] = b

     会为转写为

          a[slice(1, 2, None)] = b

     其他形式以此类推。略去的切片项总是以 ‘None’ 补全。

 -- 成員函式: object.__getitem__ (self, key)

     Called to implement evaluation of ‘self[key]’.  For *note sequence:
     135c. types, the accepted keys should be integers and slice
     objects.  Note that the special interpretation of negative indexes
     (if the class wishes to emulate a *note sequence: 135c. type) is up
     to the *note __getitem__(): 3a5. method.  If `key' is of an
     inappropriate type, *note TypeError: 1fe. may be raised; if of a
     value outside the set of indexes for the sequence (after any
     special interpretation of negative values), *note IndexError: f36.
     should be raised.  For *note mapping: c0b. types, if `key' is
     missing (not in the container), *note KeyError: 3e9. should be
     raised.

          備註: *note for: cfa. 循环在有不合法索引时会期待捕获 *note
          IndexError: f36. 以便正确地检测到序列的结束。

          備註: When *note subscripting: 158e. a `class', the special
          class method *note __class_getitem__(): 437. may be called
          instead of ‘__getitem__()’.  See *note __class_getitem__
          versus __getitem__: 158d. for more details.

 -- 成員函式: object.__setitem__ (self, key, value)

     调用此方法以实现向 ‘self[key]’ 赋值。注意事项与 *note
     __getitem__(): 3a5. 相同。为对象实现此方法应该仅限于需要映射允许基
     于键修改值或添加键，或是序列允许元素被替换时。不正确的 `key' 值所引
     发的异常应与 *note __getitem__(): 3a5. 方法的情况相同。

 -- 成員函式: object.__delitem__ (self, key)

     调用此方法以实现 ‘self[key]’ 的删除。注意事项与 *note
     __getitem__(): 3a5. 相同。为对象实现此方法应该权限于需要映射允许移
     除键，或是序列允许移除元素时。不正确的 `key' 值所引发的异常应与
     *note __getitem__(): 3a5. 方法的情况相同。

 -- 成員函式: object.__missing__ (self, key)

     此方法由 *note dict: 164.*note __getitem__(): 3a5. 在找不到字典中的
     键时调用以实现 dict 子类的 ‘self[key]’。

 -- 成員函式: object.__iter__ (self)

     此方法在需要为容器创建迭代器时被调用。此方法应该返回一个新的迭代器
     对象，它能够逐个迭代容器中的所有对象。对于映射，它应该逐个迭代容器
     中的键。

     迭代器对象也需要实现此方法；它们需要返回对象自身。有关迭代器对象的
     详情请参看 *note 迭代器类型: 159a. 一节。

 -- 成員函式: object.__reversed__ (self)

     此方法（如果存在）会被 *note reversed(): 2c6. 内置函数调用以实现逆
     向迭代。它应当返回一个新的以逆序逐个迭代容器内所有对象的迭代器对象
     。

     如果未提供 *note __reversed__(): 628. 方法，则 *note reversed():
     2c6. 内置函数将回退到使用序列协议 (*note __len__(): e90. 和 *note
     __getitem__(): 3a5.)。支持序列协议的对象应当仅在能够提供比 *note
     reversed(): 2c6. 所提供的实现更高效的实现时才提供 *note
     __reversed__(): 628. 方法。

成员检测运算符 (*note in: 179. 和 *note not in: 159b.) 通常以对容器进行
逐个迭代的方式来实现。 不过，容器对象可以提供以下特殊方法并采用更有效率
的实现，这样也不要求对象必须为可迭代对象。

 -- 成員函式: object.__contains__ (self, item)

     调用此方法以实现成员检测运算符。如果 `item' 是 `self' 的成员则应返
     回真，否则返回假。对于映射类型，此检测应基于映射的键而不是值或者键
     值对。

     对于未定义 *note __contains__(): dee. 的对象，成员检测将首先尝试通
     过 *note __iter__(): 608. 进行迭代，然后再使用 *note __getitem__():
     3a5. 的旧式序列迭代协议，参看 *note 语言参考中的相应部分: 159c.。


File: python.info,  Node: 模拟数字类型,  Next: with 语句上下文管理器,  Prev: 模拟容器类型,  Up: 特殊方法名称

4.3.3.22 模拟数字类型
.....................

定义以下方法即可模拟数字类型。特定种类的数字不支持的运算（例如非整数不能
进行位运算）所对应的方法应当保持未定义状态。

 -- 成員函式: object.__add__ (self, other)
 -- 成員函式: object.__sub__ (self, other)
 -- 成員函式: object.__mul__ (self, other)
 -- 成員函式: object.__matmul__ (self, other)
 -- 成員函式: object.__truediv__ (self, other)
 -- 成員函式: object.__floordiv__ (self, other)
 -- 成員函式: object.__mod__ (self, other)
 -- 成員函式: object.__divmod__ (self, other)
 -- 成員函式: object.__pow__ (self, other[, modulo])
 -- 成員函式: object.__lshift__ (self, other)
 -- 成員函式: object.__rshift__ (self, other)
 -- 成員函式: object.__and__ (self, other)
 -- 成員函式: object.__xor__ (self, other)
 -- 成員函式: object.__or__ (self, other)

     调用这些方法来实现二进制算术运算 (‘+’, ‘-’, ‘*’, ‘@’, ‘/’, ‘//’,
     ‘%’, *note divmod(): 28d, *note pow(): 2cf, ‘**’, ‘<<’, ‘>>’, ‘&’,
     ‘^’, ‘|’)。例如，求表达式 ‘x + y’ 的值，其中 `x' 是具有 *note
     __add__(): 1595. 方法的类的一个实例，则会调用 ‘x.__add__(y)’。*note
     __divmod__(): 876. 方法应该等价于使用 *note __floordiv__(): ef7. 和
     *note __mod__(): 15a0.，它不应该被关联到 *note __truediv__(): 875.。
     请注意如果要支持三元版本的内置 *note pow(): 2cf. 函数，则 *note
     __pow__(): 15a1. 的定义应该接受可选的第三个参数。

     如果这些方法中的某一个不支持与所提供参数进行运算，它应该返回
     ‘NotImplemented’。

 -- 成員函式: object.__radd__ (self, other)
 -- 成員函式: object.__rsub__ (self, other)
 -- 成員函式: object.__rmul__ (self, other)
 -- 成員函式: object.__rmatmul__ (self, other)
 -- 成員函式: object.__rtruediv__ (self, other)
 -- 成員函式: object.__rfloordiv__ (self, other)
 -- 成員函式: object.__rmod__ (self, other)
 -- 成員函式: object.__rdivmod__ (self, other)
 -- 成員函式: object.__rpow__ (self, other[, modulo])
 -- 成員函式: object.__rlshift__ (self, other)
 -- 成員函式: object.__rrshift__ (self, other)
 -- 成員函式: object.__rand__ (self, other)
 -- 成員函式: object.__rxor__ (self, other)
 -- 成員函式: object.__ror__ (self, other)

     调用这些方法来实现具有反射（交换）操作数的二进制算术运算 (‘+’, ‘-’,
     ‘*’, ‘@’, ‘/’, ‘//’, ‘%’, *note divmod(): 28d, *note pow(): 2cf,
     ‘**’, ‘<<’, ‘>>’, ‘&’, ‘^’, ‘|’)。这些成员函数仅会在左操作数不支持
     相应运算 (1) 且两个操作数类型不同时被调用。(2) 例如，求表达式 ‘x -
     y’ 的值，其中 `y' 是具有 *note __rsub__(): 15a7. 方法的类的一个实例
     ，则当 ‘x.__sub__(y)’ 返回 `NotImplemented' 时会调用
     ‘y.__rsub__(x)’。

     请注意三元版的 *note pow(): 2cf. 并不会尝试调用 *note __rpow__():
     15ab. (因为强制转换规则会太过复杂)。

          備註: 如果右操作数类型为左操作数类型的一个子类，且该子类提供了
          指定运算的反射方法，则此方法将先于左操作数的非反射方法被调用。
          此行为可允许子类重载其祖先类的运算符。

 -- 成員函式: object.__iadd__ (self, other)
 -- 成員函式: object.__isub__ (self, other)
 -- 成員函式: object.__imul__ (self, other)
 -- 成員函式: object.__imatmul__ (self, other)
 -- 成員函式: object.__itruediv__ (self, other)
 -- 成員函式: object.__ifloordiv__ (self, other)
 -- 成員函式: object.__imod__ (self, other)
 -- 成員函式: object.__ipow__ (self, other[, modulo])
 -- 成員函式: object.__ilshift__ (self, other)
 -- 成員函式: object.__irshift__ (self, other)
 -- 成員函式: object.__iand__ (self, other)
 -- 成員函式: object.__ixor__ (self, other)
 -- 成員函式: object.__ior__ (self, other)

     调用这些方法来实现扩展算术赋值 (‘+=’, ‘-=’, ‘*=’, ‘@=’, ‘/=’,
     ‘//=’, ‘%=’, ‘**=’, ‘<<=’, ‘>>=’, ‘&=’, ‘^=’, ‘|=’)。这些方法应该尝
     试进行自身操作 (修改 `self') 并返回结果 (结果应该但并非必须为
     `self')。如果某个方法未被定义，相应的扩展算术赋值将回退到普通方法。
     例如，如果 `x' 是具有 *note __iadd__(): f30. 方法的类的一个实例，则
     ‘x += y’ 就等价于 ‘x = x.__iadd__(y)’。否则就如 ‘x + y’ 的求值一样
     选择 ‘x.__add__(y)’ 和 ‘y.__radd__(x)’。在某些情况下，扩展赋值可导
     致未预期的错误 (参见 *note 为什么 a_tuple[i] += [’item’]
     会引发异常？: 15ba.)，但此行为实际上是数据模型的一个组成部分。

          備註: 由于 ‘**=’ 的分配机制存在一个错误，定义了 *note
          __ipow__(): 15b4. 但是返回 ‘NotImplemented’ 的类将无法回退到
          ‘x.__pow__(y)’ 和 ‘y.__rpow__(x)’。 此错误在 Python 3.10 中被
          修正。

 -- 成員函式: object.__neg__ (self)
 -- 成員函式: object.__pos__ (self)
 -- 成員函式: object.__abs__ (self)
 -- 成員函式: object.__invert__ (self)

     调用此方法以实现一元算术运算 (‘-’, ‘+’, *note abs(): 13f3. 和 ‘~’)。

 -- 成員函式: object.__complex__ (self)
 -- 成員函式: object.__int__ (self)
 -- 成員函式: object.__float__ (self)

     调用这些方法以实现内置函数 *note complex(): 2c1, *note int(): 204.
     和 *note float(): 1fd.。应当返回一个相应类型的值。

 -- 成員函式: object.__index__ (self)

     调用此方法以实现 *note operator.index(): 15bf. 以及 Python 需要无损
     地将数字对象转换为整数对象的场合（例如切片或是内置的 *note bin():
     d08, *note hex(): d2e. 和 *note oct(): d2d. 函数)。 存在此方法表明
     数字对象属于整数类型。 必须返回一个整数。

     如果未定义 *note __int__(): 2c3, *note __float__(): 2c4. 和 *note
     __complex__(): 2c5. 则相应的内置函数 *note int(): 204, *note
     float(): 1fd. 和 *note complex(): 2c1. 将回退为 *note __index__():
     2c2.。

 -- 成員函式: object.__round__ (self[, ndigits])
 -- 成員函式: object.__trunc__ (self)
 -- 成員函式: object.__floor__ (self)
 -- 成員函式: object.__ceil__ (self)

     调用这些方法以实现内置函数 *note round(): d35. 以及 *note math: b1.
     函数 *note trunc(): df4, *note floor(): df2. 和 *note ceil(): df3.。
     除了将 `ndigits' 传给 ‘__round__()’ 的情况之外这些方法的返回值都应
     当是原对象截断为 *note Integral: 1556. (通常为 *note int: 204.)。

     The built-in function *note int(): 204. falls back to *note
     __trunc__(): 15c1. if neither *note __int__(): 2c3. nor *note
     __index__(): 2c2. is defined.

   ---------- Footnotes ----------

   (1) (3) 这里的“不支持”是指该类无此方法，或方法返回 ‘NotImplemented’。
如果你想强制回退到右操作数的反射方法，请不要设置方法为 ‘None’ — 那会造成
显式地 `阻塞' 此种回退的相反效果。

   (2) (4) For operands of the same type, it is assumed that if the
non-reflected method – such as *note __add__(): 1595. – fails then the
overall operation is not supported, which is why the reflected method is
not called.


File: python.info,  Node: with 语句上下文管理器,  Next: 特殊方法查找,  Prev: 模拟数字类型,  Up: 特殊方法名称

4.3.3.23 with 语句上下文管理器
..............................

`上下文管理器' 是一个对象，它定义了在执行 *note with: 7da. 语句时要建立
的运行时上下文。 上下文管理器处理进入和退出所需运行时上下文以执行代码块
。 通常使用 ‘with’ 语句（在 *note with 语句: 7da. 中描述），但是也可以通
过直接调用它们的方法来使用。

上下文管理器的典型用法包括保存和恢复各种全局状态，锁定和解锁资源，关闭打
开的文件等等。

要了解上下文管理器的更多信息，请参阅 *note 上下文管理器类型: 15c6.。

 -- 成員函式: object.__enter__ (self)

     进入与此对象相关的运行时上下文。 *note with: 7da. 语句将会绑定这个
     方法的返回值到 ‘as’ 子句中指定的目标，如果有的话。

 -- 成員函式: object.__exit__ (self, exc_type, exc_value, traceback)

     退出关联到此对象的运行时上下文。 各个参数描述了导致上下文退出的异常
     。 如果上下文是无异常地退出的，三个参数都将为 *note None: 203.。

     如果提供了异常，并且希望方法屏蔽此异常（即避免其被传播），则应当返
     回真值。 否则的话，异常将在退出此方法时按正常流程处理。

     请注意 *note __exit__(): d5e. 方法不应该重新引发被传入的异常，这是
     调用者的责任。

也參考
......

PEP 343(1) - "with" 语句

     Python *note with: 7da. 语句的规范描述、背景和示例。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0343


File: python.info,  Node: 特殊方法查找,  Prev: with 语句上下文管理器,  Up: 特殊方法名称

4.3.3.24 特殊方法查找
.....................

对于自定义类来说，特殊方法的隐式发起调用仅保证在其定义于对象类型中时能正
确地发挥作用，而不能定义在对象实例字典中。 该行为就是以下代码会引发异常
的原因。:

     >>> 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()

The rationale behind this behaviour lies with a number of special
methods such as *note __hash__(): 44c. and *note __repr__(): 44a. that
are implemented by all objects, including type objects.  If the implicit
lookup of these methods used the conventional lookup process, they would
fail when invoked on the type object itself:

     >>> 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

以这种方式不正确地尝试发起调用一个类的未绑定方法有时被称为‘元类混淆’，可
以通过在查找特殊方法时绕过实例的方式来避免:

     >>> type(1).__hash__(1) == hash(1)
     True
     >>> type(int).__hash__(int) == hash(int)
     True

In addition to bypassing any instance attributes in the interest of
correctness, implicit special method lookup generally also bypasses the
*note __getattribute__(): 549. method even of the object’s metaclass:

     >>> 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

Bypassing the *note __getattribute__(): 549. machinery in this fashion
provides significant scope for speed optimisations within the
interpreter, at the cost of some flexibility in the handling of special
methods (the special method `must' be set on the class object itself in
order to be consistently invoked by the interpreter).


File: python.info,  Node: 协程,  Prev: 特殊方法名称,  Up: 数据模型

4.3.4 协程
----------

* Menu:

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


File: python.info,  Node: 可等待对象,  Next: 协程对象,  Up: 协程

4.3.4.1 可等待对象
..................

An *note awaitable: 612. object generally implements an *note
__await__(): 735. method.  *note Coroutine objects: 18a. returned from
*note async def: 3a9. functions are awaitable.

     備註: The *note generator iterator: 558. objects returned from
     generators decorated with *note types.coroutine(): 86b. or *note
     asyncio.coroutine(): 3a8. are also awaitable, but they do not
     implement *note __await__(): 735.

 -- 成員函式: object.__await__ (self)

     必须返回一个 *note iterator: 1171.。 应当被用来实现 *note
     awaitable: 612. 对象。 例如，*note asyncio.Future: 545. 实现了此方
     法以与 *note await: 2d8. 表达式相兼容。

3.5 版新加入.

也參考
......

PEP 492(1) 了解有关可等待对象的详细信息。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0492


File: python.info,  Node: 协程对象,  Next: 异步迭代器,  Prev: 可等待对象,  Up: 协程

4.3.4.2 协程对象
................

*note Coroutine objects: 18a. are *note awaitable: 612. objects.  A
coroutine’s execution can be controlled by calling *note __await__():
735. and iterating over the result.  When the coroutine has finished
executing and returns, the iterator raises *note StopIteration: 581, and
the exception’s ‘value’ attribute holds the return value.  If the
coroutine raises an exception, it is propagated by the iterator.
Coroutines should not directly raise unhandled *note StopIteration: 581.
exceptions.

协程也具有下面列出的方法，它们类似于生成器的对应方法 (参见 *note
生成器-迭代器的方法: 15cb.)。 但是，与生成器不同，协程并不直接支持迭代。

3.5.2 版更變: 等待一个协程超过一次将引发 *note RuntimeError: 3dc.。

 -- 成員函式: coroutine.send (value)

     Starts or resumes execution of the coroutine.  If `value' is
     ‘None’, this is equivalent to advancing the iterator returned by
     *note __await__(): 735.  If `value' is not ‘None’, this method
     delegates to the *note send(): 15cd. method of the iterator that
     caused the coroutine to suspend.  The result (return value, *note
     StopIteration: 581, or other exception) is the same as when
     iterating over the *note __await__(): 735. return value, described
     above.

 -- 成員函式: coroutine.throw (type[, value[, traceback]])

     Raises the specified exception in the coroutine.  This method
     delegates to the *note throw(): ff8. method of the iterator that
     caused the coroutine to suspend, if it has such a method.
     Otherwise, the exception is raised at the suspension point.  The
     result (return value, *note StopIteration: 581, or other exception)
     is the same as when iterating over the *note __await__(): 735.
     return value, described above.  If the exception is not caught in
     the coroutine, it propagates back to the caller.

 -- 成員函式: coroutine.close ()

     此方法会使得协程清理自身并退出。 如果协程被挂起，此方法会先委托给导
     致协程挂起的迭代器的 *note close(): 15d0. 方法，如果存在该方法。 然
     后它会在挂起点引发 *note GeneratorExit: df8.，使得协程立即清理自身
     。 最后，协程会被标记为已结束执行，即使它根本未被启动。

     当协程对象将要被销毁时，会使用以上处理过程来自动关闭。


File: python.info,  Node: 异步迭代器,  Next: 异步上下文管理器,  Prev: 协程对象,  Up: 协程

4.3.4.3 异步迭代器
..................

`异步迭代器' 可以在其 ‘__anext__’ 方法中调用异步代码。

异步迭代器可在 *note async for: 3fd. 语句中使用。

 -- 成員函式: object.__aiter__ (self)

     必须返回一个 `异步迭代器' 对象。

 -- 成員函式: object.__anext__ (self)

     必须返回一个 `可迭代对象' 输出迭代器的下一结果值。 当迭代结束时应该
     引发 *note StopAsyncIteration: 114a. 错误。

异步可迭代对象的一个示例:

     class Reader:
         async def readline(self):
             ...

         def __aiter__(self):
             return self

         async def __anext__(self):
             val = await self.readline()
             if val == b'':
                 raise StopAsyncIteration
             return val

3.5 版新加入.

3.7 版更變: Prior to Python 3.7, *note __aiter__(): 582. could return an
`awaitable' that would resolve to an *note asynchronous iterator: 738.

Starting with Python 3.7, *note __aiter__(): 582. must return an
asynchronous iterator object.  Returning anything else will result in a
*note TypeError: 1fe. error.


File: python.info,  Node: 异步上下文管理器,  Prev: 异步迭代器,  Up: 协程

4.3.4.4 异步上下文管理器
........................

`异步上下文管理器' 是 `上下文管理器' 的一种，它能够在其 ‘__aenter__’ 和
‘__aexit__’ 方法中暂停执行。

异步上下文管理器可在 *note async with: 736. 语句中使用。

 -- 成員函式: object.__aenter__ (self)

     在语义上类似于 *note __enter__(): d5d.，仅有的区别是它必须返回一个
     `可等待对象'。

 -- 成員函式: object.__aexit__ (self, exc_type, exc_value, traceback)

     在语义上类似于 *note __exit__(): d5e.，仅有的区别是它必须返回一个
     `可等待对象'。

异步上下文管理器类的一个示例:

     class AsyncContextManager:
         async def __aenter__(self):
             await log('entering context')

         async def __aexit__(self, exc_type, exc, tb):
             await log('exiting context')

3.5 版新加入.

註解
....


File: python.info,  Node: 执行模型,  Next: 导入系统,  Prev: 数据模型,  Up: Python 語言參考手冊

4.4 执行模型
============

* Menu:

* 程序的结构::
* 命名与绑定::
* 异常::


File: python.info,  Node: 程序的结构,  Next: 命名与绑定,  Up: 执行模型

4.4.1 程序的结构
----------------

Python 程序是由代码块构成的。 `代码块' 是被作为一个单元来执行的一段
Python 程序文本。 以下几个都属于代码块：模块、函数体和类定义。 交互式输
入的每条命令都是代码块。 一个脚本文件（作为标准输入发送给解释器或是作为
命令行参数发送给解释器的文件）也是代码块。 一条脚本命令（通过 *note -c:
1340. 选项在解释器命令行中指定的命令）也是代码块。 通过在命令行中使用
*note -m: 443. 参数作为最高层级脚本（即 ‘__main__’ 模块）运行的模块也是
代码块。 传递给内置函数 *note eval(): c61. 和 *note exec(): d0c. 的字符
串参数也是代码块。

代码块在 `执行帧' 中被执行。 一个帧会包含某些管理信息（用于调试）并决定
代码块执行完成后应前往何处以及如何继续执行。


File: python.info,  Node: 命名与绑定,  Next: 异常,  Prev: 程序的结构,  Up: 执行模型

4.4.2 命名与绑定
----------------

* Menu:

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


File: python.info,  Node: 名称的绑定,  Next: 名称的解析,  Up: 命名与绑定

4.4.2.1 名称的绑定
..................

`名称' 用于指代对象。 名称是通过名称绑定操作来引入的。

以下构造会绑定名称：传给函数的正式形参，*note import: ce7. 语句，类与函
数定义（这会在定义的代码块中绑定类或函数名称）以及发生以标识符为目标的赋
值，*note for: cfa. 循环的开头，或 *note with: 7da. 语句和 *note except:
c10. 子句的 ‘as’ 之后。 ‘import’ 语句的 ‘from ... import *’ 形式会绑定在
被导入模块中定义的所有名称，那些以下划线开头的除外。 这种形式仅在模块层
级上被使用。

*note del: 13a2. 语句的目标也被视作一种绑定（虽然其实际语义为解除名称绑
定）。

每条赋值或导入语句均发生于类或函数内部定义的代码块中，或是发生于模块层级
（即最高层级的代码块）。

如果名称绑定在一个代码块中，则为该代码块的局部变量，除非声明为 *note
nonlocal: d07. 或 *note global: 1378.。 如果名称绑定在模块层级，则为全局
变量。 (模块代码块的变量既为局部变量又为全局变量。) 如果变量在一个代码块
中被使用但不是在其中定义，则为 `自由变量'。

每个在程序文本中出现的名称是指由以下名称解析规则所建立的对该名称的 `绑定
'。


File: python.info,  Node: 名称的解析,  Next: 内置命名空间和受限的执行,  Prev: 名称的绑定,  Up: 命名与绑定

4.4.2.2 名称的解析
..................

`作用域' 定义了一个代码块中名称的可见性。 如果代码块中定义了一个局部变量
，则其作用域包含该代码块。 如果定义发生于函数代码块中，则其作用域会扩展
到该函数所包含的任何代码块，除非有某个被包含代码块引入了对该名称的不同绑
定。

当一个名称在代码块中被使用时，会由包含它的最近作用域来解析。 对一个代码
块可见的所有这种作用域的集合称为该代码块的 `环境'。

当一个名称完全找不到时，将会引发 *note NameError: e40. 异常。 如果当前作
用域为函数作用域，且该名称指向一个局部变量，而此变量在该名称被使用的时候
尚未绑定到特定值，将会引发 *note UnboundLocalError: f37. 异常。 *note
UnboundLocalError: f37. 为 *note NameError: e40. 的一个子类。

如果一个代码块内的任何位置发生名称绑定操作，则代码块内所有对该名称的使用
会被认为是对当前代码块的引用。 当一个名称在其被绑定前就在代码块内被使用
时则会导致错误。 这个一个很微妙的规则。 Python 缺少声明语法，并允许名称
绑定操作发生于代码块内的任何位置。 一个代码块的局部变量可通过在整个代码
块文本中扫描名称绑定操作来确定。

If the *note global: 1378. statement occurs within a block, all uses of
the names specified in the statement refer to the bindings of those
names in the top-level namespace.  Names are resolved in the top-level
namespace by searching the global namespace, i.e.  the namespace of the
module containing the code block, and the builtins namespace, the
namespace of the module *note builtins: 12.  The global namespace is
searched first.  If the names are not found there, the builtins
namespace is searched.  The ‘global’ statement must precede all uses of
the listed names.

*note global: 1378. 语句与同一代码块中名称绑定具有相同的作用域。 如果一
个自由变量的最近包含作用域中有一条 global 语句，则该自由变量也会被当作是
全局变量。

*note nonlocal: d07. 语句会使得相应的名称指向之前在最近包含函数作用域中
绑定的变量。 如果指定名称不存在于任何包含函数作用域中则将在编译时引发
*note SyntaxError: 559.。

模块的作用域会在模块第一次被导入时自动创建。 一个脚本的主模块总是被命名
为 *note __main__: 1.。

类定义代码块以及传给 *note exec(): d0c. 和 *note eval(): c61. 的参数是名
称解析上下文中的特殊情况。 类定义是可能使用并定义名称的可执行语句。 这些
引用遵循正常的名称解析规则，例外之处在于未绑定的局部变量将会在全局命名空
间中查找。 类定义的命名空间会成为该类的属性字典。 在类代码块中定义的名称
的作用域会被限制在类代码块中；它不会扩展到方法的代码块中 – 这也包括推导
式和生成器表达式，因为它们都是使用函数作用域实现的。 这意味着以下代码将
会失败:

     class A:
         a = 42
         b = list(a + i for i in range(10))


File: python.info,  Node: 内置命名空间和受限的执行,  Next: 与动态特性的交互,  Prev: 名称的解析,  Up: 命名与绑定

4.4.2.3 内置命名空间和受限的执行
................................

`CPython implementation detail:' 用户不应该接触 ‘__builtins__’，严格说来
它属于实现细节。 用户如果要重载内置命名空间中的值则应该 *note import:
ce7. *note builtins: 12. 并相应地修改该模块中的属性。

与一个代码块的执行相关联的内置命名空间实际上是通过在其全局命名空间中搜索
名称 ‘__builtins__’ 来找到的；这应该是一个字典或一个模块（在后一种情况下
会使用该模块的字典）。 默认情况下，当在 *note __main__: 1. 模块中时，
‘__builtins__’ 就是内置模块 *note builtins: 12.；当在任何其他模块中时，
‘__builtins__’ 则是 *note builtins: 12. 模块自身的字典的一个别名。


File: python.info,  Node: 与动态特性的交互,  Prev: 内置命名空间和受限的执行,  Up: 命名与绑定

4.4.2.4 与动态特性的交互
........................

自由变量的名称解析发生于运行时而不是编译时。 这意味着以下代码将打印出
42:

     i = 10
     def f():
         print(i)
     i = 42
     f()

*note eval(): c61. 和 *note exec(): d0c. 函数没有对完整环境的访问权限来
解析名称。 名称可以在调用者的局部和全局命名空间中被解析。 自由变量的解析
不是在最近包含命名空间中，而是在全局命名空间中。 (1) *note exec(): d0c.
和 *note eval(): c61. 函数有可选参数用来重载全局和局部命名空间。 如果只
指定一个命名空间，则它会同时作用于两者。

   ---------- Footnotes ----------

   (1) (1) 出现这样的限制是由于通过这些操作执行的代码在模块被编译的时候
并不可用。


File: python.info,  Node: 异常,  Prev: 命名与绑定,  Up: 执行模型

4.4.3 异常
----------

异常是中断代码块的正常控制流程以便处理错误或其他异常条件的一种方式。 异
常会在错误被检测到的位置 `引发'，它可以被当前包围代码块或是任何直接或间
接发起调用发生错误的代码块的其他代码块所 `处理'。

Python 解析器会在检测到运行时错误（例如零作为被除数）的时候引发异常。
Python 程序也可以通过 *note raise: d0a. 语句显式地引发异常。 异常处理是
通过 *note try: e37. ...  *note except: c10. 语句来指定的。 该语句的
*note finally: 2bc. 子句可被用来指定清理代码，它并不处理异常，而是无论之
前的代码是否发生异常都会被执行。

Python 的错误处理采用的是“终止”模型：异常处理器可以找出发生了什么问题，
并在外层继续执行，但它不能修复错误的根源并重试失败的操作（除非通过从顶层
重新进入出错的代码片段）。

当一个异常完全未被处理时，解释器会终止程序的执行，或者返回交互模式的主循
环。 无论是哪种情况，它都会打印栈回溯信息，除非是当异常为 *note
SystemExit: 6f3. 的时候。

异常是通过类实例来标识的。 *note except: c10. 子句会依据实例的类来选择：
它必须引用实例的类或是其所属的基类。 实例可通过处理器被接收，并可携带有
关异常条件的附加信息。

     備註: 异常消息不是 Python API 的组成部分。 其内容可能在 Python 升级
     到新版本时不经警告地发生改变，不应该被需要在多版本解释器中运行的代
     码所依赖。

另请参看 *note try 语句: e37. 小节中对 *note try: e37. 语句的描述以及
*note raise 语句: d0a. 小节中对 *note raise: d0a. 语句的描述。

註解
....


File: python.info,  Node: 导入系统,  Next: 表达式,  Prev: 执行模型,  Up: Python 語言參考手冊

4.5 导入系统
============

一个 *note module: 15e7. 内的 Python 代码通过 *note importing: 15e8. 操
作就能够访问另一个模块内的代码。 *note import: ce7. 语句是发起调用导入机
制的最常用方式，但不是唯一的方式。 *note importlib.import_module(): be6.
以及内置的 *note __import__(): 16b. 等函数也可以被用来发起调用导入机制。

*note import: ce7. 语句结合了两个操作；它先搜索指定名称的模块，然后将搜
索结果绑定到当前作用域中的名称。 ‘import’ 语句的搜索操作定义为对 *note
__import__(): 16b. 函数的调用并带有适当的参数。 *note __import__(): 16b.
的返回值会被用于执行 ‘import’ 语句的名称绑定操作。 请参阅 ‘import’ 语句
了解名称绑定操作的更多细节。

对 *note __import__(): 16b. 的直接调用将仅执行模块搜索以及在找到时的模块
创建操作。 不过也可能产生某些副作用，例如导入父包和更新各种缓存 (包括
*note sys.modules: 1051.)，只有 *note import: ce7. 语句会执行名称绑定操
作。

当 *note import: ce7. 语句被执行时，标准的内置 *note __import__(): 16b.
函数会被调用。 其他发起调用导入系统的机制 (例如 *note
importlib.import_module(): be6.) 可能会选择绕过 *note __import__(): 16b.
并使用它们自己的解决方案来实现导入机制。

当一个模块首次被导入时，Python 会搜索该模块，如果找到就创建一个 module 对
象 (1) 并初始化它。 如果指定名称的模块未找到，则会引发 *note
ModuleNotFoundError: 4a0.。 当发起调用导入机制时，Python 会实现多种策略
来搜索指定名称的模块。 这些策略可以通过使用使用下文所描述的多种钩子来加
以修改和扩展。

3.3 版更變: 导入系统已被更新以完全实现 PEP 302(2) 中的第二阶段要求。 不
会再有任何隐式的导入机制 —— 整个导入系统都通过 *note sys.meta_path: 6dd.
暴露出来。 此外，对原生命名空间包的支持也已被实现 (参见 PEP 420(3))。

* Menu:

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

   ---------- Footnotes ----------

   (1) (1) 参见 *note types.ModuleType: 7e2.。

   (2) https://www.python.org/dev/peps/pep-0302

   (3) https://www.python.org/dev/peps/pep-0420


File: python.info,  Node: importlib<8>,  Next: 包,  Up: 导入系统

4.5.1 ‘importlib’
-----------------

*note importlib: 9a. 模块提供了一个丰富的 API 用来与导入系统进行交互。 例
如 *note importlib.import_module(): be6. 提供了相比内置的 *note
__import__(): 16b. 更推荐、更简单的 API 用来发起调用导入机制。 更多细节
请参看 *note importlib: 9a. 库文档。


File: python.info,  Node: 包,  Next: 搜索,  Prev: importlib<8>,  Up: 导入系统

4.5.2 包
--------

Python 只有一种模块对象类型，所有模块都属于该类型，无论模块是用 Python、
C 还是别的语言实现。 为了帮助组织模块并提供名称层次结构，Python 还引入了
*note 包: 15eb. 的概念。

你可以把包看成是文件系统中的目录，并把模块看成是目录中的文件，但请不要对
这个类似做过于字面的理解，因为包和模块不是必须来自于文件系统。 为了方便
理解本文档，我们将继续使用这种目录和文件的类比。 与文件系统一样，包通过
层次结构进行组织，在包之内除了一般的模块，还可以有子包。

要注意的一个重点概念是所有包都是模块，但并非所有模块都是包。 或者换句话
说，包只是一种特殊的模块。 特别地，任何具有 ‘__path__’ 属性的模块都会被
当作是包。

所有模块都有自己的名字。 子包名与其父包名以点号分隔，与 Python 的标准属
性访问语法一致。 例如你可能看到一个名为 *note sys: fd. 的模块以及一个名
为 *note email: 67. 的包，这个包中又有一个名为 *note email.mime: 71. 的
子包和该子包中的名为 ‘email.mime.text’ 的子包。

* Menu:

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


File: python.info,  Node: 常规包,  Next: 命名空间包,  Up: 包

4.5.2.1 常规包
..............

Python 定义了两种类型的包，*note 常规包: 15ed. 和 *note 命名空间包:
15ee.。 常规包是传统的包类型，它们在 Python 3.2 及之前就已存在。 常规包
通常以一个包含 ‘__init__.py’ 文件的目录形式实现。 当一个常规包被导入时，
这个 ‘__init__.py’ 文件会隐式地被执行，它所定义的对象会被绑定到该包命名
空间中的名称。‘__init__.py’ 文件可以包含与任何其他模块中所包含的 Python
代码相似的代码，Python 将在模块被导入时为其添加额外的属性。

例如，以下文件系统布局定义了一个最高层级的 ‘parent’ 包和三个子包:

     parent/
         __init__.py
         one/
             __init__.py
         two/
             __init__.py
         three/
             __init__.py

导入 ‘parent.one’ 将隐式地执行 ‘parent/__init__.py’ 和
‘parent/one/__init__.py’。 后续导入 ‘parent.two’ 或 ‘parent.three’ 则将
分别执行 ‘parent/two/__init__.py’ 和 ‘parent/three/__init__.py’。


File: python.info,  Node: 命名空间包,  Prev: 常规包,  Up: 包

4.5.2.2 命名空间包
..................

命名空间包是由多个 *note 部分: 15f0. 构成的，每个部分为父包增加一个子包
。 各个部分可能处于文件系统的不同位置。 部分也可能处于 zip 文件中、网络
上，或者 Python 在导入期间可以搜索的其他地方。 命名空间包并不一定会直接
对应到文件系统中的对象；它们有可能是无实体表示的虚拟模块。

命名空间包的 ‘__path__’ 属性不使用普通的列表。 而是使用定制的可迭代类型
，如果其父包的路径 (或者最高层级包的 *note sys.path: 261.) 发生改变，这
种对象会在该包内的下一次导入尝试时自动执行新的对包部分的搜索。

命名空间包没有 ‘parent/__init__.py’ 文件。 实际上，在导入搜索期间可能找
到多个 ‘parent’ 目录，每个都由不同的部分所提供。 因此 ‘parent/one’ 的物
理位置不一定与 ‘parent/two’ 相邻。 在这种情况下，Python 将为顶级的
‘parent’ 包创建一个命名空间包，无论是它本身还是它的某个子包被导入。

另请参阅 PEP 420(1) 了解对命名空间包的规格描述。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0420


File: python.info,  Node: 搜索,  Next: 加载,  Prev: 包,  Up: 导入系统

4.5.3 搜索
----------

为了开始搜索，Python 需要被导入模块（或者包，对于当前讨论来说两者没有差
别）的完整 *note 限定名称: 155c.。 此名称可以来自 *note import: ce7. 语
句所带的各种参数，或者来自传给 *note importlib.import_module(): be6. 或
*note __import__(): 16b. 函数的形参。

此名称会在导入搜索的各个阶段被使用，它也可以是指向一个子模块的带点号路径
，例如 ‘foo.bar.baz’。 在这种情况下，Python 会先尝试导入 ‘foo’，然后是
‘foo.bar’，最后是 ‘foo.bar.baz’。 如果这些导入中的任何一个失败，都会引发
*note ModuleNotFoundError: 4a0.。

* Menu:

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


File: python.info,  Node: 模块缓存,  Next: 查找器和加载器,  Up: 搜索

4.5.3.1 模块缓存
................

在导入搜索期间首先会被检查的地方是 *note sys.modules: 1051.。 这个映射起
到缓存之前导入的所有模块的作用（包括其中间路径）。 因此如果之前导入过
‘foo.bar.baz’，则 *note sys.modules: 1051. 将包含 ‘foo’, ‘foo.bar’ 和
‘foo.bar.baz’ 条目。 每个键的值就是相应的模块对象。

在导入期间，会在 *note sys.modules: 1051. 查找模块名称，如存在则其关联的
值就是需要导入的模块，导入过程完成。 然而，如果值为 ‘None’，则会引发
*note ModuleNotFoundError: 4a0.。 如果找不到指定模块名称，Python 将继续
搜索该模块。

*note sys.modules: 1051. 是可写的。删除键可能不会破坏关联的模块（因为其
他模块可能会保留对它的引用），但它会使命名模块的缓存条目无效，导致
Python 在下次导入时重新搜索命名模块。键也可以赋值为 ‘None’ ，强制下一次
导入模块导致 *note ModuleNotFoundError: 4a0. 。

但是要小心，因为如果你还保有对某个模块对象的引用，同时停用其在 *note
sys.modules: 1051. 中的缓存条目，然后又再次导入该名称的模块，则前后两个
模块对象将 `不是' 同一个。 相反地，*note importlib.reload(): 49f. 将重用
`同一个' 模块对象，并简单地通过重新运行模块的代码来重新初始化模块内容。


File: python.info,  Node: 查找器和加载器,  Next: 导入钩子,  Prev: 模块缓存,  Up: 搜索

4.5.3.2 查找器和加载器
......................

如果指定名称的模块在 *note sys.modules: 1051. 找不到，则将发起调用
Python 的导入协议以查找和加载该模块。 此协议由两个概念性模块构成，即
*note 查找器: 15f5. 和 *note 加载器: 15f6.。 查找器的任务是确定是否能使
用其所知的策略找到该名称的模块。 同时实现这两种接口的对象称为 *note
导入器: 15f7. —— 它们在确定能加载所需的模块时会返回其自身。

Python 包含了多个默认查找器和导入器。 第一个知道如何定位内置模块，第二个
知道如何定位冻结模块。 第三个默认查找器会在 *note import path: 15f8. 中
搜索模块。 *note import path: 15f8. 是一个由文件系统路径或 zip 文件组成
的位置列表。 它还可以扩展为搜索任意可定位资源，例如由 URL 指定的资源。

导入机制是可扩展的，因此可以加入新的查找器以扩展模块搜索的范围和作用域。

查找器并不真正加载模块。 如果它们能找到指定名称的模块，会返回一个 `模块
规格说明'，这是对模块导入相关信息的封装，供后续导入机制用于在加载模块时
使用。

以下各节描述了有关查找器和加载器协议的更多细节，包括你应该如何创建并注册
新的此类对象来扩展导入机制。

3.4 版更變: 在之前的 Python 版本中，查找器会直接返回 *note 加载器:
15f6.，现在它们则返回模块规格说明，其中 `包含' 加载器。 加载器仍然在导入
期间被使用，但负担的任务有所减少。


File: python.info,  Node: 导入钩子,  Next: 元路径,  Prev: 查找器和加载器,  Up: 搜索

4.5.3.3 导入钩子
................

导入机制被设计为可扩展；其中的基本机制是 `导入钩子'。 导入钩子有两种类型
: `元钩子' 和 `导入路径钩子'。

元钩子在导入过程开始时被调用，此时任何其他导入过程尚未发生，但 *note
sys.modules: 1051. 缓存查找除外。 这允许元钩子重载 *note sys.path: 261.
过程、冻结模块甚至内置模块。 元钩子的注册是通过向 *note sys.meta_path:
6dd. 添加新的查找器对象，具体如下所述。

导入路径钩子是作为 *note sys.path: 261. (或 ‘package.__path__’) 过程的一
部分，在遇到它们所关联的路径项的时候被调用。 导入路径钩子的注册是通过向
*note sys.path_hooks: a3d. 添加新的可调用对象，具体如下所述。


File: python.info,  Node: 元路径,  Prev: 导入钩子,  Up: 搜索

4.5.3.4 元路径
..............

当指定名称的模块在 *note sys.modules: 1051. 中找不到时，Python 会接着搜
索 *note sys.meta_path: 6dd.，其中包含元路径查找器对象列表。 这些查找器
按顺序被查询以确定它们是否知道如何处理该名称的模块。 元路径查找器必须实
现名为 *note find_spec(): 564. 的方法，该方法接受三个参数：名称、导入路
径和目标模块（可选）。 元路径查找器可使用任何策略来确定它是否能处理指定
名称的模块。

如果元路径查找器知道如何处理指定名称的模块，它将返回一个说明对象。 如果
它不能处理该名称的模块，则会返回 ‘None’。 如果 *note sys.meta_path: 6dd.
处理过程到达列表末尾仍未返回说明对象，则将引发 *note
ModuleNotFoundError: 4a0.。 任何其他被引发异常将直接向上传播，并放弃导入
过程。

元路径查找器的 *note find_spec(): 564. 方法调用带有两到三个参数。 第一个
是被导入模块的完整限定名称，例如 ‘foo.bar.baz’。 第二个参数是供模块搜索
使用的路径条目。 对于最高层级模块，第二个参数为 ‘None’，但对于子模块或子
包，第二个参数为父包 ‘__path__’ 属性的值。 如果相应的 ‘__path__’ 属性无
法访问，将引发 *note ModuleNotFoundError: 4a0.。 第三个参数是一个将被作
为稍后加载目标的现有模块对象。 导入系统仅会在重加载期间传入一个目标模块
。

对于单个导入请求可以多次遍历元路径。 例如，假设所涉及的模块都尚未被缓存
，则导入 ‘foo.bar.baz’ 将首先执行顶级的导入，在每个元路径查找器 (‘mpf’)
上调用 ‘mpf.find_spec("foo", None, None)’。 在导入 ‘foo’ 之后，‘foo.bar’
将通过第二次遍历元路径来导入，调用 ‘mpf.find_spec("foo.bar",
foo.__path__, None)’。 一旦 ‘foo.bar’ 完成导入，最后一次遍历将调用
‘mpf.find_spec("foo.bar.baz", foo.bar.__path__, None)’。

有些元路径查找器只支持顶级导入。 当把 ‘None’ 以外的对象作为第三个参数传
入时，这些导入器将总是返回 ‘None’。

Python 的默认 *note sys.meta_path: 6dd. 具有三种元路径查找器，一种知道如
何导入内置模块，一种知道如何导入冻结模块，还有一种知道如何导入来自 *note
import path: 15f8. 的模块 (即 *note path based finder: 15fb.)。

3.4 版更變: 元路径查找器的 *note find_spec(): 564. 方法替代了 *note
find_module(): 563.，后者现已弃用，它将继续可用但不会再做改变，导入机制
仅会在查找器未实现 ‘find_spec()’ 时尝试使用它。


File: python.info,  Node: 加载,  Next: 基于路径的查找器,  Prev: 搜索,  Up: 导入系统

4.5.4 加载
----------

当一个模块说明被找到时，导入机制将在加载该模块时使用它（及其所包含的加载
器）。 下面是导入的加载部分所发生过程的简要说明:

     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]

请注意以下细节:

        * 如果在 *note sys.modules: 1051. 中存在指定名称的模块对象，导入
          操作会已经将其返回。

        * 在加载器执行模块代码之前，该模块将存在于 *note sys.modules:
          1051. 中。 这一点很关键，因为该模块代码可能（直接或间接地）导
          入其自身；预先将其添加到 *note sys.modules: 1051. 可防止在最坏
          情况下的无限递归和最好情况下的多次加载。

        * 如果加载失败，则该模块 – 只限加载失败的模块 – 将从 *note
          sys.modules: 1051. 中移除。 任何已存在于 *note sys.modules:
          1051. 缓存的模块，以及任何作为附带影响被成功加载的模块仍会保留
          在缓存中。 这与重新加载不同，后者会把即使加载失败的模块也保留
          在 *note sys.modules: 1051. 中。

        * 在模块创建完成但还未执行之前，导入机制会设置导入相关模块属性（
          在上面的示例伪代码中为 “_init_module_attrs”），详情参见 *note
          后续部分: 15fd.。

        * 模块执行是加载的关键时刻，在此期间将填充模块的命名空间。 执行
          会完全委托给加载器，由加载器决定要填充的内容和方式。

        * 在加载过程中创建并传递给 exec_module() 的模块并不一定就是在导
          入结束时返回的模块 (1)。

3.4 版更變: 导入系统已经接管了加载器建立样板的责任。 这些在以前是由
*note importlib.abc.Loader.load_module(): 6da. 方法来执行的。

* Menu:

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

   ---------- Footnotes ----------

   (1) (2) importlib 实现避免直接使用返回值。 而是通过在 *note
sys.modules: 1051. 中查找模块名称来获取模块对象。 这种方式的间接影响是被
导入的模块可能在 *note sys.modules: 1051. 中替换其自身。 这属于具体实现
的特定行为，不保证能在其他 Python 实现中起作用。


File: python.info,  Node: 加载器,  Next: 子模块,  Up: 加载

4.5.4.1 加载器
..............

模块加载器提供关键的加载功能：模块执行。 导入机制调用 *note
importlib.abc.Loader.exec_module(): 6db. 方法并传入一个参数来执行模块对
象。 从 *note exec_module(): 6db. 返回的任何值都将被忽略。

加载器必须满足下列要求:

        * 如果模块是一个 Python 模块（而非内置模块或动态加载的扩展），加
          载器应该在模块的全局命名空间 (‘module.__dict__’) 中执行模块的
          代码。

        * 如果加载器无法执行指定模块，它应该引发 *note ImportError:
          16c.，不过在 *note exec_module(): 6db. 期间引发的任何其他异常
          也会被传播。

在许多情况下，查找器和加载器可以是同一对象；在此情况下 *note
find_spec(): 564. 方法将返回一个规格说明，其中加载器会被设为 ‘self’。

模块加载器可以选择通过实现 *note create_module(): 64e. 方法在加载期间创
建模块对象。 它接受一个参数，即模块规格说明，并返回新的模块对象供加载期
间使用。 ‘create_module()’ 不需要在模块对象上设置任何属性。 如果模块返回
‘None’，导入机制将自行创建新模块。

3.4 版新加入: 加载器的 *note create_module(): 64e. 方法。

3.4 版更變: *note load_module(): 6da. 方法被 *note exec_module(): 6db. 所
替代，导入机制会对加载的所有样板责任作出假定。

为了与现有的加载器兼容，导入机制会使用导入器的 ‘load_module()’ 方法，如
果它存在且导入器也未实现 ‘exec_module()’。 但是，‘load_module()’ 现已弃
用，加载器应该转而实现 ‘exec_module()’。

除了执行模块之外，‘load_module()’ 方法必须实现上文描述的所有样板加载功能
。 所有相同的限制仍然适用，并带有一些附加规定:

        * 如果 *note sys.modules: 1051. 中存在指定名称的模块对象，加载器
          必须使用已存在的模块。 （否则 *note importlib.reload(): 49f. 将
          无法正确工作。） 如果该名称模块不存在于 *note sys.modules:
          1051. 中，加载器必须创建一个新的模块对象并将其加入 *note
          sys.modules: 1051.。

        * 在加载器执行模块代码之前，模块 `必须' 存在于 *note
          sys.modules: 1051. 之中，以防止无限递归或多次加载。

        * 如果加载失败，加载器必须移除任何它已加入到 *note sys.modules:
          1051. 中的模块，但它必须 `仅限' 移除加载失败的模块，且所移除的
          模块应为加载器自身显式加载的。

3.5 版更變: 当 ‘exec_module()’ 已定义但 ‘create_module()’ 未定义时将引发
*note DeprecationWarning: 15a.。

3.6 版更變: 当 ‘exec_module()’ 已定义但 ‘create_module()’ 未定义时将引发
*note ImportError: 16c.。


File: python.info,  Node: 子模块,  Next: 模块规格说明,  Prev: 加载器,  Up: 加载

4.5.4.2 子模块
..............

当使用任意机制 (例如 ‘importlib’ API, ‘import’ 及 ‘import-from’ 语句或者
内置的 ‘__import__()’) 加载一个子模块时，父模块的命名空间中会添加一个对
子模块对象的绑定。 例如，如果包 ‘spam’ 有一个子模块 ‘foo’，则在导入
‘spam.foo’ 之后，‘spam’ 将具有一个 绑定到相应子模块的 ‘foo’ 属性。 假如
现在有如下的目录结构:

     spam/
         __init__.py
         foo.py
         bar.py

并且 ‘spam/__init__.py’ 中有如下几行内容:

     from .foo import Foo
     from .bar import Bar

则执行如下代码将在 ‘spam’ 模块中添加对 ‘foo’ 和 ‘bar’ 的名称绑定:

     >>> import spam
     >>> spam.foo
     <module 'spam.foo' from '/tmp/imports/spam/foo.py'>
     >>> spam.bar
     <module 'spam.bar' from '/tmp/imports/spam/bar.py'>

按照通常的 Python 名称绑定规则，这看起来可能会令人惊讶，但它实际上是导入
系统的一个基本特性。 保持不变的一点是如果你有 ‘sys.modules['spam']’ 和
‘sys.modules['spam.foo']’ (例如在上述导入之后就是如此)，则后者必须显示为
前者的 ‘foo’ 属性。


File: python.info,  Node: 模块规格说明,  Next: 导入相关的模块属性,  Prev: 子模块,  Up: 加载

4.5.4.3 模块规格说明
....................

导入机制在导入期间会使用有关每个模块的多种信息，特别是加载之前。 大多数
信息都是所有模块通用的。 模块规格说明的目的是基于每个模块来封装这些导入
相关信息。

在导入期间使用规格说明可允许状态在导入系统各组件之间传递，例如在创建模块
规格说明的查找器和执行模块的加载器之间。 最重要的一点是，它允许导入机制
执行加载的样板操作，在没有模块规格说明的情况下这是加载器的责任。

模块的规格说明会作为模块对象的 ‘__spec__’ 属性对外公开。 有关模块规格的
详细内容请参阅 *note ModuleSpec: 1601.。

3.4 版新加入.


File: python.info,  Node: 导入相关的模块属性,  Next: module __path__,  Prev: 模块规格说明,  Up: 加载

4.5.4.4 导入相关的模块属性
..........................

导入机制会在加载期间会根据模块的规格说明填充每个模块对象的这些属性，并在
加载器执行模块之前完成。

 -- 屬性: __name__

     ‘__name__’ 属性必须被设为模块的完整限定名称。 此名称被用来在导入系
     统中唯一地标识模块。

 -- 屬性: __loader__

     ‘__loader__’ 属性必须被设为导入系统在加载模块时使用的加载器对象。 这
     主要是用于内省，但也可用于额外的加载器专用功能，例如获取关联到加载
     器的数据。

 -- 屬性: __package__

     模块的 ‘__package__’ 属性必须设定。 其取值必须为一个字符串，但可以
     与 ‘__name__’ 取相同的值。 当模块是包时，其 ‘__package__’ 值应该设
     为其 ‘__name__’ 值。 当模块不是包时，对于最高层级模块 ‘__package__’
     应该设为空字符串，对于子模块则应该设为其父包名。 更多详情可参阅 PEP
     366(1)。

     该属性取代 ‘__name__’ 被用来为主模块计算显式相对导入，相关定义见
     PEP 366(2)。 预期它与 ‘__spec__.parent’ 具有相同的值。

     3.6 版更變: ‘__package__’ 预期与 ‘__spec__.parent’ 具有相同的值。

 -- 屬性: __spec__

     ‘__spec__’ 属性必须设为在导入模块时要使用的模块规格说明。 对
     ‘__spec__’ 的正确设定将同时作用于 *note 解释器启动期间初始化的模块:
     1604.。 唯一的例外是 ‘__main__’，其中的 ‘__spec__’ 会 *note
     在某些情况下设为 None: 1605.

     当 ‘__package__’ 未定义时， ‘__spec__.parent’ 会被用作回退项。

     3.4 版新加入.

     3.6 版更變: 当 ‘__package__’ 未定义时，‘__spec__.parent’ 会被用作回
     退项。

 -- 屬性: __path__

     如果模块为包（不论是正规包还是命名空间包），则必须设置模块对象的
     ‘__path__’ 属性。 属性值必须为可迭代对象，但如果 ‘__path__’ 没有进
     一步的用处则可以为空。 如果 ‘__path__’ 不为空，则在迭代时它应该产生
     字符串。 有关 ‘__path__’ 语义的更多细节将在 *note 下文: 1606. 中给
     出。

     不是包的模块不应该具有 ‘__path__’ 属性。

 -- 屬性: __file__

 -- 屬性: __cached__

     ‘__file__’ 是可选项。 如果设置，此属性的值必须为字符串。 导入系统可
     以选择在其没有语法意义时不设置 ‘__file__’ (例如从数据库加载的模块
     )。

     如果设置了 ‘__file__’，则也可以再设置 ‘__cached__’ 属性，后者取值为
     编译版本代码（例如字节码文件）所在的路径。 设置此属性不要求文件已存
     在；该路径可以简单地指向应该存放编译文件的位置 (参见 PEP 3147(3))。

     当未设置 ‘__file__’ 时也可以设置 ‘__cached__’。 但是，那样的场景很
     不典型。 最终，加载器会使用 ‘__file__’ 和/或 ‘__cached__’。 因此如
     果一个加载器可以从缓存加载模块但是不能从文件加载，那种非典型场景就
     是适当的。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0366

   (2) https://www.python.org/dev/peps/pep-0366

   (3) https://www.python.org/dev/peps/pep-3147


File: python.info,  Node: module __path__,  Next: 模块的 repr,  Prev: 导入相关的模块属性,  Up: 加载

4.5.4.5 module.__path__
.......................

根据定义，如果一个模块具有 ‘__path__’ 属性，它就是包。

包的 ‘__path__’ 属性会在导入其子包期间被使用。 在导入机制内部，它的功能
与 *note sys.path: 261. 基本相同，即在导入期间提供一个模块搜索位置列表。
但是，‘__path__’ 通常会比 *note sys.path: 261. 受到更多限制。

‘__path__’ 必须是由字符串组成的可迭代对象，但它也可以为空。 作用于 *note
sys.path: 261. 的规则同样适用于包的 ‘__path__’，并且 *note
sys.path_hooks: a3d. (见下文) 会在遍历包的 ‘__path__’ 时被查询。

包的 ‘__init__.py’ 文件可以设置或更改包的 ‘__path__’ 属性，而且这是在
PEP 420(1) 之前实现命名空间包的典型方式。 随着 PEP 420(2) 的引入，命名空
间包不再需要提供仅包含 ‘__path__’ 操控代码的 ‘__init__.py’ 文件；导入机
制会自动为命名空间包正确地设置 ‘__path__’。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0420

   (2) https://www.python.org/dev/peps/pep-0420


File: python.info,  Node: 模块的 repr,  Next: 已缓存字节码的失效,  Prev: module __path__,  Up: 加载

4.5.4.6 模块的 repr
...................

默认情况下，全部模块都具有一个可用的 repr，但是你可以依据上述的属性设置
，在模块的规格说明中更为显式地控制模块对象的 repr。

如果模块具有 spec (‘__spec__’)，导入机制将尝试用它来生成一个 repr。 如果
生成失败或找不到 spec，导入系统将使用模块中的各种可用信息来制作一个默认
repr。 它将尝试使用 ‘module.__name__’, ‘module.__file__’ 以及
‘module.__loader__’ 作为 repr 的输入，并将任何丢失的信息赋为默认值。

以下是所使用的确切规则:

        * 如果模块具有 ‘__spec__’ 属性，其中的规格信息会被用来生成 repr。
          被查询的属性有 "name", "loader", "origin" 和 "has_location" 等
          等。

        * 如果模块具有 ‘__file__’ 属性，这会被用作模块 repr 的一部分。

        * 如果模块没有 ‘__file__’ 但是有 ‘__loader__’ 且取值不为 ‘None’，
          则加载器的 repr 会被用作模块 repr 的一部分。

        * 对于其他情况，仅在 repr 中使用模块的 ‘__name__’。

3.4 版更變: *note loader.module_repr(): a25. 已弃用，导入机制现在使用模
块规格说明来生成模块 repr。

为了向后兼容 Python 3.3，如果加载器定义了 *note module_repr(): a25. 方法
，则会在尝试上述两种方式之前先调用该方法来生成模块 repr。 但请注意此方法
已弃用。


File: python.info,  Node: 已缓存字节码的失效,  Prev: 模块的 repr,  Up: 加载

4.5.4.7 已缓存字节码的失效
..........................

在 Python 从 ‘.pyc’ 文件加载已缓存字节码之前，它会检查缓存是否由最新的
‘.py’ 源文件所生成。 默认情况下，Python 通过在所写入缓存文件中保存源文件
的最新修改时间戳和大小来实现这一点。 在运行时，导入系统会通过比对缓存文
件中保存的元数据和源文件的元数据确定该缓存的有效性。

Python 也支持“基于哈希的”缓存文件，即保存源文件内容的哈希值而不是其元数
据。 存在两种基于哈希的 ‘.pyc’ 文件：检查型和非检查型。 对于检查型基于哈
希的 ‘.pyc’ 文件，Python 会通过求哈希源文件并将结果哈希值与缓存文件中的
哈希值比对来确定缓存有效性。 如果检查型基于哈希的缓存文件被确定为失效，
Python 会重新生成并写入一个新的检查型基于哈希的缓存文件。 对于非检查型
‘.pyc’ 文件，只要其存在 Python 就会直接认定缓存文件有效。 确定基于哈希的
‘.pyc’ 文件有效性的行为可通过 *note –check-hash-based-pycs: 1475. 旗标来
重载。

3.7 版更變: 增加了基于哈希的 ‘.pyc’ 文件。在此之前，Python 只支持基于时
间戳来确定字节码缓存的有效性。


File: python.info,  Node: 基于路径的查找器,  Next: 替换标准导入系统,  Prev: 加载,  Up: 导入系统

4.5.5 基于路径的查找器
----------------------

在之前已经提及，Python 带有几种默认的元路径查找器。 其中之一是 *note
path based finder: 15fb. (*note PathFinder: a3c.)，它会搜索包含一个
*note 路径条目: 160b. 列表的 *note import path: 15f8.。 每个路径条目指定
一个用于搜索模块的位置。

基于路径的查找器自身并不知道如何进行导入。 它只是遍历单独的路径条目，将
它们各自关联到某个知道如何处理特定类型路径的路径条目查找器。

默认的路径条目查找器集合实现了在文件系统中查找模块的所有语义，可处理多种
特殊文件类型例如 Python 源码 (‘.py’ 文件)，Python 字节码 (‘.pyc’ 文件) 以
及共享库 (例如 ‘.so’ 文件)。 在标准库中 *note zipimport: 14c. 模块的支持
下，默认路径条目查找器还能处理所有来自 zip 文件的上述文件类型。

路径条目不必仅限于文件系统位置。 它们可以指向 URL、数据库查询或可以用字
符串指定的任何其他位置。

基于路径的查找器还提供了额外的钩子和协议以便能扩展和定制可搜索路径条目的
类型。 例如，如果你想要支持网络 URL 形式的路径条目，你可以编写一个实现
HTTP 语义在网络上查找模块的钩子。 这个钩子（可调用对象）应当返回一个支持
下述协议的 *note path entry finder: a92.，以被用来获取一个专门针对来自网
络的模块的加载器。

预先的警告：本节和上节都使用了 `查找器' 这一术语，并通过 *note meta path
finder: a91. 和 *note path entry finder: a92. 两个术语来明确区分它们。 这
两种类型的查找器非常相似，支持相似的协议，且在导入过程中以相似的方式运作
，但关键的一点是要记住它们是有微妙差异的。 特别地，元路径查找器作用于导
入过程的开始，主要是启动 *note sys.meta_path: 6dd. 遍历。

相比之下，路径条目查找器在某种意义上说是基于路径的查找器的实现细节，实际
上，如果需要从 *note sys.meta_path: 6dd. 移除基于路径的查找器，并不会有
任何路径条目查找器被发起调用。

* Menu:

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


File: python.info,  Node: 路径条目查找器,  Next: 路径条目查找器协议,  Up: 基于路径的查找器

4.5.5.1 路径条目查找器
......................

*note path based finder: 15fb. 会负责查找和加载通过 *note path entry:
160b. 字符串来指定位置的 Python 模块和包。 多数路径条目所指定的是文件系
统中的位置，但它们并不必受限于此。

作为一种元路径查找器，*note path based finder: 15fb. 实现了上文描述的
*note find_spec(): 564. 协议，但是它还对外公开了一些附加钩子，可被用来定
制模块如何从 *note import path: 15f8. 查找和加载。

有三个变量由 *note path based finder: 15fb, *note sys.path: 261, *note
sys.path_hooks: a3d. 和 *note sys.path_importer_cache: 597. 所使用。 包
对象的 ‘__path__’ 属性也会被使用。 它们提供了可用于定制导入机制的额外方
式。

*note sys.path: 261. 包含一个提供模块和包搜索位置的字符串列表。 它初始化
自 ‘PYTHONPATH’ 环境变量以及多种其他特定安装和实现的默认设置。 *note
sys.path: 261. 条目可指定的名称有文件系统中的目录、zip 文件和其他可用于
搜索模块的潜在“位置”（参见 *note site: eb. 模块），例如 URL 或数据库查询
等。 在 *note sys.path: 261. 中只能出现字符串和字节串；所有其他数据类型
都会被忽略。 字节串条目使用的编码由单独的 *note 路径条目查找器: a92. 来
确定。

*note path based finder: 15fb. 是一种 *note meta path finder: a91.，因此
导入机制会通过调用上文描述的基于路径的查找器的 *note find_spec(): a1e. 方
法来启动 *note import path: 15f8. 搜索。 当要向 *note find_spec(): a1e.
传入 ‘path’ 参数时，它将是一个可遍历的字符串列表 —— 通常为用来在其内部进
行导入的包的 ‘__path__’ 属性。 如果 ‘path’ 参数为 ‘None’，这表示最高层级
的导入，将会使用 *note sys.path: 261.。

基于路径的查找器会迭代搜索路径中的每个条目，并且每次都查找与路径条目对应
的 *note path entry finder: a92. (*note PathEntryFinder: a94.)。 因为这
种操作可能很耗费资源（例如搜索会有 ‘stat()’ 调用的开销），基于路径的查找
器会维持一个缓存来将路径条目映射到路径条目查找器。 这个缓存放于 *note
sys.path_importer_cache: 597. (尽管如此命名，但这个缓存实际存放的是查找
器对象而非仅限于 *note importer: 15f7. 对象)。 通过这种方式，对特定
*note path entry: 160b. 位置的 *note path entry finder: a92. 的高耗费搜
索只需进行一次。 用户代码可以自由地从 *note sys.path_importer_cache:
597. 移除缓存条目，以强制基于路径的查找器再次执行路径条目搜索 (1)。

如果路径条目不存在于缓存中，基于路径的查找器会迭代 *note sys.path_hooks:
a3d. 中的每个可调用对象。 对此列表中的每个 *note 路径条目钩子: 160d. 的
调用会带有一个参数，即要搜索的路径条目。 每个可调用对象或是返回可处理路
径条目的 *note path entry finder: a92.，或是引发 *note ImportError:
16c.。 基于路径的查找器使用 *note ImportError: 16c. 来表示钩子无法找到与
*note path entry: 160b. 相对应的 *note path entry finder: a92.。 该异常
会被忽略并继续进行 *note import path: 15f8. 的迭代。 每个钩子应该期待接
收一个字符串或字节串对象；字节串对象的编码由钩子决定（例如可以是文件系统
使用的编码 UTF-8 或其它编码），如果钩子无法解码参数，它应该引发 *note
ImportError: 16c.。

如果 *note sys.path_hooks: a3d. 迭代结束时没有返回 *note path entry
finder: a92.，则基于路径的查找器 *note find_spec(): a1e. 方法将在 *note
sys.path_importer_cache: 597. 中存入 ‘None’ (表示此路径条目没有对应的查
找器) 并返回 ‘None’，表示此 *note meta path finder: a91. 无法找到该模块
。

如果 *note sys.path_hooks: a3d. 中的某个 *note path entry hook: 160d. 可
调用对象的返回值 `是' 一个 *note path entry finder: a92.，则以下协议会被
用来向查找器请求一个模块的规格说明，并在加载该模块时被使用。

当前工作目录 – 由一个空字符串表示 – 的处理方式与 *note sys.path: 261. 中
的其他条目略有不同。 首先，如果发现当前工作目录不存在，则 *note
sys.path_importer_cache: 597. 中不会存放任何值。 其次，每个模块查找会对
当前工作目录的值进行全新查找。 第三，由 *note sys.path_importer_cache:
597. 所使用并由 *note importlib.machinery.PathFinder.find_spec(): a1e. 所
返回的路径将是实际的当前工作目录而非空字符串。

   ---------- Footnotes ----------

   (1) (3) 在遗留代码中，有可能在 *note sys.path_importer_cache: 597. 中
找到 *note imp.NullImporter: a9b. 的实例。 建议将这些代码修改为使用
‘None’ 代替。 详情参见 *note Porting Python code: be5.。


File: python.info,  Node: 路径条目查找器协议,  Prev: 路径条目查找器,  Up: 基于路径的查找器

4.5.5.2 路径条目查找器协议
..........................

为了支持模块和已初始化包的导入，也为了给命名空间包提供组成部分，路径条目
查找器必须实现 *note find_spec(): 566. 方法。

*note find_spec(): 566. 接受两个参数，即要导入模块的完整限定名称，以及（
可选的）目标模块。 ‘find_spec()’ 返回模块的完全填充好的规格说明。 这个规
格说明总是包含“加载器”集合（但有一个例外）。

为了向导入机制提示该规格说明代表一个命名空间 *note portion: 15f0.，路径
条目查找器会将 "submodule_search_locations" 设为一个包含该部分的列表。

3.4 版更變: *note find_spec(): 566. 替代了 *note find_loader(): 565. 和
*note find_module(): a1f.，后两者现在都已弃用，但会在 ‘find_spec()’ 未定
义时被使用。

较旧的路径条目查找器可能会实现这两个已弃用的方法中的一个而没有实现
‘find_spec()’。 为保持向后兼容，这两个方法仍会被接受。 但是，如果在路径
条目查找器上实现了 ‘find_spec()’，这两个遗留方法就会被忽略。

*note find_loader(): 565. 接受一个参数，即要导入模块的完整限定名称。
‘find_loader()’ 返回一个 2 元组，其中第一项是加载器而第二项是命名空间
*note portion: 15f0.。

为了向后兼容其他导入协议的实现，许多路径条目查找器也同样支持元路径查找器
所支持的传统 ‘find_module()’ 方法。 但是路径条目查找器 ‘find_module()’ 方
法的调用绝不会带有 ‘path’ 参数（它们被期望记录来自对路径钩子初始调用的恰
当路径信息）。

路径条目查找器的 ‘find_module()’ 方法已弃用，因为它不允许路径条目查找器
为命名空间包提供部分。 如果 ‘find_loader()’ 和 ‘find_module()’ 同时存在
于一个路径条目查找器中，导入系统将总是调用 ‘find_loader()’ 而不选择
‘find_module()’。


File: python.info,  Node: 替换标准导入系统,  Next: 包相对导入,  Prev: 基于路径的查找器,  Up: 导入系统

4.5.6 替换标准导入系统
----------------------

替换整个导入系统的最可靠机制是移除 *note sys.meta_path: 6dd. 的默认内容
，,将其完全替换为自定义的元路径钩子。

一个可行的方式是仅改变导入语句的行为而不影响访问导入系统的其他 API，那么
替换内置的 *note __import__(): 16b. 函数可能就够了。 这种技巧也可以在模
块层级上运用，即只在某个模块内部改变导入语句的行为。

想要选择性地预先防止在元路径上从一个钩子导入某些模块（而不是完全禁用标准
导入系统），只需直接从 *note find_spec(): 564. 引发 *note
ModuleNotFoundError: 4a0. 而非返回 ‘None’ 就足够了。 返回后者表示元路径
搜索应当继续，而引发异常则会立即终止搜索。


File: python.info,  Node: 包相对导入,  Next: 有关 __main__ 的特殊事项,  Prev: 替换标准导入系统,  Up: 导入系统

4.5.7 包相对导入
----------------

相对导入使用前缀点号。 一个前缀点号表示相对导入从当前包开始。 两个或更多
前缀点号表示对当前包的上级包的相对导入，第一个点号之后的每个点号代表一级
。 例如，给定以下的包布局结构:

     package/
         __init__.py
         subpackage1/
             __init__.py
             moduleX.py
             moduleY.py
         subpackage2/
             __init__.py
             moduleZ.py
         moduleA.py

不论是在 ‘subpackage1/moduleX.py’ 还是 ‘subpackage1/__init__.py’ 中，以
下导入都是有效的:

     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

绝对导入可以使用 ‘import <>’ 或 ‘from <> import <>’ 语法，但相对导入只能
使用第二种形式；其中的原因在于:

     import XXX.YYY.ZZZ

应当提供 ‘XXX.YYY.ZZZ’ 作为可用表达式，但 .moduleY 不是一个有效的表达式
。


File: python.info,  Node: 有关 __main__ 的特殊事项,  Next: 开放问题项,  Prev: 包相对导入,  Up: 导入系统

4.5.8 有关 __main__ 的特殊事项
------------------------------

对于 Python 的导入系统来说 *note __main__: 1. 模块是一个特殊情况。 正如
在 *note 另一节: 1604. 中所述，‘__main__’ 模块是在解释器启动时直接初始化
的，与 *note sys: fd. 和 *note builtins: 12. 很类似。 但是，与那两者不同
，它并不被严格归类为内置模块。 这是因为 ‘__main__’ 被初始化的方式依赖于
发起调用解释器所附带的旗标和其他选项。

* Menu:

* __main__.__spec__: __main__ __spec__.


File: python.info,  Node: __main__ __spec__,  Up: 有关 __main__ 的特殊事项

4.5.8.1 __main__.__spec__
.........................

根据 *note __main__: 1. 被初始化的方式，‘__main__.__spec__’ 会被设置相应
值或是 ‘None’。

当 Python 附加 *note -m: 443. 选项启动时，‘__spec__’ 会被设为相应模块或
包的模块规格说明。 ‘__spec__’ 也会在 ‘__main__’ 模块作为执行某个目录，
zip 文件或其它 *note sys.path: 261. 条目的一部分加载时被填充。

在 *note 其余的情况: 146e. 下 ‘__main__.__spec__’ 会被设为 ‘None’，因为
用于填充 *note __main__: 1. 的代码不直接与可导入的模块相对应:

   - 交互型提示

   - *note -c: 1340. 选项

   - 从 stdin 运行

   - 直接从源码或字节码文件运行

请注意在最后一种情况中 ‘__main__.__spec__’ 总是为 ‘None’，`即使' 文件从
技术上说可以作为一个模块被导入。 如果想要让 *note __main__: 1. 中的元数
据生效，请使用 *note -m: 443. 开关。

还要注意即使是在 ‘__main__’ 对应于一个可导入模块且 ‘__main__.__spec__’ 被
相应地设定时，它们仍会被视为 `不同的' 模块。 这是由于以下事实：使用 ‘if
__name__ == "__main__":’ 检测来保护的代码块仅会在模块被用来填充
‘__main__’ 命名空间时而非普通的导入时被执行。


File: python.info,  Node: 开放问题项,  Next: 参考文献,  Prev: 有关 __main__ 的特殊事项,  Up: 导入系统

4.5.9 开放问题项
----------------

XXX 最好是能增加一个图表。

XXX * (import_machinery.rst) 是否要专门增加一节来说明模块和包的属性，也
许可以扩展或移植数据模型参考页中的相关条目？

XXX 库手册中的 runpy 和 pkgutil 等等应该都在页面顶端增加指向新的导入系统
章节的“另请参阅”链接。

XXX 是否要增加关于初始化 ‘__main__’ 的不同方式的更多解释？

XXX 增加更多有关 ‘__main__’ 怪异/坑人特性的信息 (例如直接从 PEP 395(1) 复
制)。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0395


File: python.info,  Node: 参考文献,  Prev: 开放问题项,  Up: 导入系统

4.5.10 参考文献
---------------

导入机制自 Python 诞生之初至今已发生了很大的变化。 原始的 包规格说明(1)
仍然可以查阅，但在撰写该文档之后许多相关细节已被修改。

原始的 *note sys.meta_path: 6dd. 规格说明见 PEP 302(2)，后续的扩展说明见
PEP 420(3)。

PEP 420(4) 为 Python 3.3 引入了 *note 命名空间包: 15ee.。 PEP 420(5) 还
引入了 ‘find_loader()’ 协议作为 ‘find_module()’ 的替代。

PEP 366(6) 描述了新增的 ‘__package__’ 属性，用于在模块中的显式相对导入。

PEP 328(7) 引入了绝对和显式相对导入，并初次提出了 ‘__name__’ 语义，最终
由 PEP 366(8) 为 ‘__package__’ 加入规范描述。

PEP 338(9) 定义了将模块作为脚本执行。

PEP 451(10) 在 spec 对象中增加了对每个模块导入状态的封装。 它还将加载器
的大部分样板责任移交回导入机制中。 这些改变允许弃用导入系统中的一些 API
并为查找器和加载器增加一些新的方法。

註解
....

   ---------- Footnotes ----------

   (1) https://www.python.org/doc/essays/packages/

   (2) https://www.python.org/dev/peps/pep-0302

   (3) https://www.python.org/dev/peps/pep-0420

   (4) https://www.python.org/dev/peps/pep-0420

   (5) https://www.python.org/dev/peps/pep-0420

   (6) https://www.python.org/dev/peps/pep-0366

   (7) https://www.python.org/dev/peps/pep-0328

   (8) https://www.python.org/dev/peps/pep-0366

   (9) https://www.python.org/dev/peps/pep-0338

   (10) https://www.python.org/dev/peps/pep-0451


File: python.info,  Node: 表达式,  Next: 简单语句,  Prev: 导入系统,  Up: Python 語言參考手冊

4.6 表达式
==========

本章将解释 Python 中组成表达式的各种元素的的含义。

`语法注释:' 在本章和后续章节中，会使用扩展 BNF 标注来描述语法而不是词法
分析。 当（某种替代的）语法规则具有如下形式

     name ::= othername

并且没有给出语义，则这种形式的 ‘name’ 在语法上与 ‘othername’ 相同。

* Menu:

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


File: python.info,  Node: 算术转换,  Next: 原子,  Up: 表达式

4.6.1 算术转换
--------------

当对下述某个算术运算符的描述中使用了“数值参数被转换为普通类型”这样的说法
，这意味着内置类型的运算符实现采用了如下运作方式:

   * 如果任一参数为复数，另一参数会被转换为复数；

   * 否则，如果任一参数为浮点数，另一参数会被转换为浮点数；

   * 否则，两者应该都为整数，不需要进行转换。

某些附加规则会作用于特定运算符（例如，字符串作为 ’%’ 运算符的左运算参数
）。 扩展必须定义它们自己的转换行为。


File: python.info,  Node: 原子,  Next: 原型,  Prev: 算术转换,  Up: 表达式

4.6.2 原子
----------

“原子”指表达式的最基本构成元素。 最简单的原子是标识符和字面值。 以圆括号
、方括号或花括号包括的形式在语法上也被归类为原子。 原子的句法为:

     atom      ::= identifier | literal | enclosure
     enclosure ::= parenth_form | list_display | dict_display | set_display
                   | generator_expression | yield_atom

* Menu:

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


File: python.info,  Node: 标识符（名称）,  Next: 字面值<2>,  Up: 原子

4.6.2.1 标识符（名称）
......................

作为原子出现的标识符叫做名称。 请参看 *note 标识符和关键字: 1505. 一节了
解其词法定义，以及 *note 命名与绑定: 15d9. 获取有关命名与绑定的文档。

当名称被绑定到一个对象时，对该原子求值将返回相应对象。 当名称未被绑定时
，尝试对其求值将引发 *note NameError: e40. 异常。

`私有名称转换:' 当以文本形式出现在类定义中的一个标识符以两个或更多下划线
开头并且不以两个或更多下划线结尾，它会被视为该类的 `私有名称'。 私有名称
会在为其生成代码之前被转换为一种更长的形式。 转换时会插入类名，移除打头
的下划线再在名称前增加一个下划线。 例如，出现在一个名为 ‘Ham’ 的类中的标
识符 ‘__spam’ 会被转换为 ‘_Ham__spam’。 这种转换独立于标识符所使用的相关
句法。 如果转换后的名称太长（超过 255 个字符），可能发生由具体实现定义的
截断。 如果类名仅由下划线组成，则不会进行转换。


File: python.info,  Node: 字面值<2>,  Next: 带圆括号的形式,  Prev: 标识符（名称）,  Up: 原子

4.6.2.2 字面值
..............

Python 支持字符串和字节串字面值，以及几种数字字面值:

     literal ::= stringliteral | bytesliteral
                 | integer | floatnumber | imagnumber

对字面值求值将返回一个该值所对应类型的对象（字符串、字节串、整数、浮点数
、复数）。 对于浮点数和虚数（复数）的情况，该值可能为近似值。 详情参见
*note 字面值: 1512.。

所有字面值都对应与不可变数据类型，因此对象标识的重要性不如其实际值。 多
次对具有相同值的字面值求值（不论是发生在程序文本的相同位置还是不同位置）
可能得到相同对象或是具有相同值的不同对象。


File: python.info,  Node: 带圆括号的形式,  Next: 列表、集合与字典的显示,  Prev: 字面值<2>,  Up: 原子

4.6.2.3 带圆括号的形式
......................

带圆括号的形式是包含在圆括号中的可选表达式列表。

     parenth_form ::= "(" [starred_expression] ")"

带圆括号的表达式列表将返回该表达式列表所产生的任何东西：如果该列表包含至
少一个逗号，它会产生一个元组；否则，它会产生该表达式列表所对应的单一表达
式。

一对内容为空的圆括号将产生一个空的元组对象。 由于元组是不可变对象，因此
适用与字面值相同的规则（即两次出现的空元组产生的对象可能相同也可能不同）
。

请注意元组并不是由圆括号构建，实际起作用的是逗号操作符。 例外情况是空元
组，这时圆括号 `才是' 必须的 — 允许在表达式中使用不带圆括号的 "空" 会导
致歧义，并会造成常见输入错误无法被捕获。


File: python.info,  Node: 列表、集合与字典的显示,  Next: 列表显示,  Prev: 带圆括号的形式,  Up: 原子

4.6.2.4 列表、集合与字典的显示
..............................

为了构建列表、集合或字典，Python 提供了名为“显示”的特殊句法，每个类型各
有两种形式:

   * 第一种是显式地列出容器内容

   * 第二种是通过一组循环和筛选指令计算出来，称为 `推导式'。

推导式的常用句法元素为:

     comprehension ::= assignment_expression comp_for
     comp_for      ::= ["async"] "for" target_list "in" or_test [comp_iter]
     comp_iter     ::= comp_for | comp_if
     comp_if       ::= "if" or_test [comp_iter]

推导式的结构是一个单独表达式后面加至少一个 ‘for’ 子句以及零个或更多个
‘for’ 或 ‘if’ 子句。 在这种情况下，新容器的元素产生方式是将每个 ‘for’ 或
‘if’ 子句视为一个代码块，按从左至右的顺序嵌套，然后每次到达最内层代码块
时就对表达式进行求值以产生一个元素。

不过，除了最左边 ‘for’ 子句中的可迭代表达式，推导式是在另一个隐式嵌套的
作用域内执行的。 这能确保赋给目标列表的名称不会“泄露”到外层的作用域。

最左边的 ‘for’ 子句中的可迭代对象表达式会直接在外层作用域中被求值，然后
作为一个参数被传给隐式嵌套的作用域。 后续的 ‘for’ 子句以及最左侧 ‘for’ 子
句中的任何筛选条件不能在外层作用域中被求值，因为它们可能依赖于从最左侧可
迭代对象中获得的值。 例如: ‘[x*y for x in range(10) for y in range(x,
x+10)]’。

为了确保推导式得出的结果总是一个类型正确的容器，在隐式嵌套作用域内禁止使
用 ‘yield’ 和 ‘yield from’ 表达式。

从 Python 3.6 开始，在 *note async def: 3a9. 函数中可以使用 ‘async for’
子句来迭代 *note asynchronous iterator: 738.。 在 ‘async def’ 函数中构建
推导式可以通过在打头的表达式后加上 ‘for’ 或 ‘async for’ 子句，也可能包含
额外的 ‘for’ 或 ‘async for’ 子句，还可能使用 *note await: 2d8. 表达式。
如果一个推导式包含 ‘async for’ 子句或者 ‘await’ 表达式，则被称为 `异步推
导式'。 异步推导式可以暂停执行它所在的协程函数。 另请参阅 PEP 530(1)。

3.6 版新加入: 引入了异步推导式。

3.8 版更變: ‘yield’ 和 ‘yield from’ 在隐式嵌套的作用域中已被禁用。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0530


File: python.info,  Node: 列表显示,  Next: 集合显示,  Prev: 列表、集合与字典的显示,  Up: 原子

4.6.2.5 列表显示
................

列表显示是一个用方括号括起来的可能为空的表达式系列:

     list_display ::= "[" [starred_list | comprehension] "]"

列表显示会产生一个新的列表对象，其内容通过一系列表达式或一个推导式来指定
。 当提供由逗号分隔的一系列表达式时，其元素会从左至右被求值并按此顺序放
入列表对象。 当提供一个推导式时，列表会根据推导式所产生的结果元素进行构
建。


File: python.info,  Node: 集合显示,  Next: 字典显示,  Prev: 列表显示,  Up: 原子

4.6.2.6 集合显示
................

集合显示是用花括号标明的，与字典显示的区别在于没有冒号分隔的键和值:

     set_display ::= "{" (starred_list | comprehension) "}"

集合显示会产生一个新的可变集合对象，其内容通过一系列表达式或一个推导式来
指定。 当提供由逗号分隔的一系列表达式时，其元素会从左至右被求值并加入到
集合对象。 当提供一个推导式时，集合会根据推导式所产生的结果元素进行构建
。

空集合不能用 ‘{}’ 来构建；该字面值所构建的是一个空字典。


File: python.info,  Node: 字典显示,  Next: 生成器表达式,  Prev: 集合显示,  Up: 原子

4.6.2.7 字典显示
................

字典显示是一个用花括号括起来的可能为空的键/数据对系列:

     dict_display       ::= "{" [key_datum_list | dict_comprehension] "}"
     key_datum_list     ::= key_datum ("," key_datum)* [","]
     key_datum          ::= expression ":" expression | "**" or_expr
     dict_comprehension ::= expression ":" expression comp_for

字典显示会产生一个新的字典对象。

如果给出一个由逗号分隔的键/数据对序列，它们会从左至右被求值以定义字典的
条目：每个键对象会被用作在字典中存放相应数据的键。 这意味着你可以在键/数
据对序列中多次指定相同的键，最终字典的值将由最后一次给出的键决定。

双星号 ‘**’ 表示 `字典拆包'。 它的操作数必须是一个 *note mapping: c0b.。
每个映射项被会加入新的字典。 后续的值会替代先前的键/数据对和先前的字典拆
包所设置的值。

3.5 版新加入: 拆包到字典显示，最初由 PEP 448(1) 提出。

字典推导式与列表和集合推导式有所不同，它需要以冒号分隔的两个表达式，后面
带上标准的 "for" 和 "if" 子句。 当推导式被执行时，作为结果的键和值元素会
按它们的产生顺序被加入新的字典。

对键取值类型的限制已列在之前的 *note 标准类型层级结构: 1553. 一节中。 (总
的说来，键的类型应该为 *note hashable: 276.，这就把所有可变对象都排除在
外。) 重复键之间的冲突不会被检测；指定键所保存的最后一个数据 (即在显示中
排最右边的文本) 为最终有效数据。

3.8 版更變: 在 Python 3.8 之前的字典推导式中，并没有定义好键和值的求值顺
序。 在 CPython 中，值会先于键被求值。 根据 PEP 572(2) 的提议，从 3.8 开
始，键会先于值被求值。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0448

   (2) https://www.python.org/dev/peps/pep-0572


File: python.info,  Node: 生成器表达式,  Next: yield 表达式,  Prev: 字典显示,  Up: 原子

4.6.2.8 生成器表达式
....................

生成器表达式是用圆括号括起来的紧凑形式生成器标注。

     generator_expression ::= "(" expression comp_for ")"

生成器表达式会产生一个新的生成器对象。 其句法与推导式相同，区别在于它是
用圆括号而不是用方括号或花括号括起来的。

在生成器表达式中使用的变量会在为生成器对象调用 *note __next__(): 140e. 方
法的时候以惰性方式被求值（即与普通生成器相同的方式）。 但是，最左侧
‘for’ 子句内的可迭代对象是会被立即求值的，因此它所造成的错误会在生成器表
达式被定义时被检测到，而不是在获取第一个值时才出错。 后续的 ‘for’ 子句以
及最左侧 ‘for’ 子句内的任何筛选条件无法在外层作用域内被求值，因为它们可
能会依赖于从最左侧可迭代对象获取的值。 例如: ‘(x*y for x in range(10)
for y in range(x, x+10))’.

圆括号在只附带一个参数的调用中可以被省略。 详情参见 *note 调用: 73f. 一
节。

为了避免干扰到生成器表达式本身的预期操作，禁止在隐式定义的生成器中使用
‘yield’ 和 ‘yield from’ 表达式。

如果生成器表达式包含 ‘async for’ 子句或 *note await: 2d8. 表达式，则称为
`异步生成器表达式'。 异步生成器表达式会返回一个新的异步生成器对象，此对
象属于异步迭代器 (参见 *note 异步迭代器: 739.)。

3.6 版新加入: 引入了异步生成器表达式。

3.7 版更變: 在 Python 3.7 之前，异步生成器表达式只能在 *note async def:
3a9. 协和中出现。 从 3.7 开始，任何函数都可以使用异步生成器表达式。

3.8 版更變: ‘yield’ 和 ‘yield from’ 在隐式嵌套的作用域中已被禁用。


File: python.info,  Node: yield 表达式,  Prev: 生成器表达式,  Up: 原子

4.6.2.9 yield 表达式
....................

     yield_atom       ::= "(" yield_expression ")"
     yield_expression ::= "yield" [expression_list | "from" expression]

The yield expression is used when defining a *note generator: a83.
function or an *note asynchronous generator: 1640. function and thus can
only be used in the body of a function definition.  Using a yield
expression in a function’s body causes that function to be a generator
function, and using it in an *note async def: 3a9. function’s body
causes that coroutine function to be an asynchronous generator function.
For example:

     def gen():  # defines a generator function
         yield 123

     async def agen(): # defines an asynchronous generator function
         yield 123

由于它们会对外层作用域造成附带影响，‘yield’ 表达式不被允许作为用于实现推
导式和生成器表达式的隐式定义作用域的一部分。

3.8 版更變: 禁止在实现推导式和生成器表达式的隐式嵌套作用域中使用 yield 表
达式。

下面是对生成器函数的描述，异步生成器函数会在 *note 异步生成器函数: 1641.
一节中单独介绍。

当一个生成器函数被调用的时候，它返回一个迭代器，称为生成器。然后这个生成
器来控制生成器函数的执行。当这个生成器的某一个方法被调用的时候，生成器函
数开始执行。这时会一直执行到第一个 yield 表达式，在此执行再次被挂起，给
生成器的调用者返回 *note expression_list: 1642. 的值。挂起后，我们说所有
局部状态都被保留下来，包括局部变量的当前绑定，指令指针，内部求值栈和任何
异常处理的状态。通过调用生成器的某一个方法，生成器函数继续执行。此时函数
的运行就和 yield 表达式只是一个外部函数调用的情况完全一致。恢复后 yield
表达式的值取决于调用的哪个方法来恢复执行。 如果用的是 *note __next__():
140e. (通常通过语言内置的 *note for: cfa. 或是 *note next(): 775. 来调用
) 那么结果就是 *note None: 203.  否则，如果用 *note send(): 15cd, 那么结
果就是传递给send方法的值。

所有这些使生成器函数与协程非常相似；它们 yield 多次，它们具有多个入口点
，并且它们的执行可以被挂起。唯一的区别是生成器函数不能控制在它在 yield 后
交给哪里继续执行；控制权总是转移到生成器的调用者。

在 *note try: e37. 结构中的任何位置都允许yield表达式。如果生成器在(因为
引用计数到零或是因为被垃圾回收)销毁之前没有恢复执行，将调用生成器-迭代器
的 *note close(): 15d0. 方法.  close 方法允许任何挂起的 *note finally:
2bc. 子句执行。

当使用 ‘yield from <expr>’ 时，所提供的表达式必须是一个可迭代对象。 迭代
该可迭代对象所产生的值会被直接传递给当前生成器方法的调用者。 任何通过
*note send(): 15cd. 传入的值以及任何通过 *note throw(): ff8. 传入的异常
如果有适当的方法则会被传给下层迭代器。 如果不是这种情况，那么 *note
send(): 15cd. 将引发 *note AttributeError: 4a1. 或 *note TypeError:
1fe.，而 *note throw(): ff8. 将立即引发所转入的异常。

当下层迭代器完成时，被引发的 *note StopIteration: 581. 实例的 ‘value’ 属
性会成为 yield 表达式的值。 它可以在引发 *note StopIteration: 581. 时被
显式地设置，也可以在子迭代器是一个生成器时自动地设置（通过从子生成器返回
一个值）。

     3.3 版更變: 添加 ‘yield from <expr>’ 以委托控制流给一个子迭代器。

当yield表达式是赋值语句右侧的唯一表达式时，括号可以省略。

也參考
......

PEP 255(1) - 简单生成器

     在 Python 中加入生成器和 *note yield: 2c7. 语句的提议。

PEP 342(2) - 通过增强型生成器实现协程

     增强生成器 API 和语法的提议，使其可以被用作简单的协程。

PEP 380(3) - 委托给子生成器的语法

     引入 ‘yield_from’ 语法以方便地委托给子生成器的提议。

PEP 525(4) - 异步生成器

     通过给协程函数加入生成器功能对 PEP 492(5) 进行扩展的提议。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0255

   (2) https://www.python.org/dev/peps/pep-0342

   (3) https://www.python.org/dev/peps/pep-0380

   (4) https://www.python.org/dev/peps/pep-0525

   (5) https://www.python.org/dev/peps/pep-0492


File: python.info,  Node: 生成器-迭代器的方法,  Next: 示例,  Up: yield 表达式

4.6.2.10 生成器-迭代器的方法
............................

这个子小节描述了生成器迭代器的方法。 它们可被用于控制生成器函数的执行。

请注意在生成器已经在执行时调用以下任何方法都会引发 *note ValueError:
16d. 异常。

 -- 成員函式: generator.__next__ ()

     开始一个生成器函数的执行或是从上次执行的 yield 表达式位置恢复执行。
     当一个生成器函数通过 *note __next__(): 140e. 方法恢复执行时，当前的
     yield 表达式总是取值为 *note None: 203.。 随后会继续执行到下一个
     yield 表达式，其 *note expression_list: 1642. 的值会返回给 *note
     __next__(): 140e. 的调用者。 如果生成器没有产生下一个值就退出，则将
     引发 *note StopIteration: 581. 异常。

     此方法通常是隐式地调用，例如通过 *note for: cfa. 循环或是内置的
     *note next(): 775. 函数。

 -- 成員函式: generator.send (value)

     恢复执行并向生成器函数“发送”一个值。 `value' 参数将成为当前 yield 表
     达式的结果。 *note send(): 15cd. 方法会返回生成器所产生的下一个值，
     或者如果生成器没有产生下一个值就退出则会引发 *note StopIteration:
     581.。 当调用 *note send(): 15cd. 来启动生成器时，它必须以 *note
     None: 203. 作为调用参数，因为这时没有可以接收值的 yield 表达式。

 -- 成員函式: generator.throw (type[, value[, traceback]])

     在生成器暂停的位置引发 ‘type’ 类型的异常，并返回该生成器函数所产生
     的下一个值。 如果生成器没有产生下一个值就退出，则将引发 *note
     StopIteration: 581. 异常。 如果生成器函数没有捕获传入的异常，或引发
     了另一个异常，则该异常会被传播给调用者。

 -- 成員函式: generator.close ()

     在生成器函数暂停的位置引发 *note GeneratorExit: df8.。 如果之后生成
     器函数正常退出、关闭或引发 *note GeneratorExit: df8. (由于未捕获该
     异常) 则关闭并返回其调用者。 如果生成器产生了一个值，关闭会引发
     *note RuntimeError: 3dc.。 如果生成器引发任何其他异常，它会被传播给
     调用者。 如果生成器已经由于异常或正常退出则 *note close(): 15d0. 不
     会做任何事。


File: python.info,  Node: 示例,  Next: 异步生成器函数,  Prev: 生成器-迭代器的方法,  Up: yield 表达式

4.6.2.11 示例
.............

这里是一个简单的例子，演示了生成器和生成器函数的行为:

     >>> 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.

对于 ‘yield from’ 的例子, 参见“Python 有什么新变化”中的 *note PEP 380;
委托给子生成器的语法: a59.。


File: python.info,  Node: 异步生成器函数,  Next: 异步生成器-迭代器方法,  Prev: 示例,  Up: yield 表达式

4.6.2.12 异步生成器函数
.......................

在一个使用 *note async def: 3a9. 定义的函数或方法中出现的 yield 表达式会
进一步将该函数定义为一个 *note asynchronous generator: 1640. 函数。

当一个异步生成器函数被调用时，它会返回一个名为异步生成器对象的异步迭代器
。 此对象将在之后控制该生成器函数的执行。 异步生成器对象通常被用在协程函
数的 *note async for: 3fd. 语句中，类似于在 *note for: cfa. 语句中使用生
成器对象。

调用异步生成器的方法之一将返回 *note awaitable: 612. 对象，执行会在此对
象被等待时启动。 到那时，执行将前往第一个 yield 表达式，在那里它会再次暂
停，将 *note expression_list: 1642. 的值返回给等待中的协程。 与生成器一
样，挂起意味着局部的所有状态会被保留，包括局部变量的当前绑定、指令的指针
、内部求值的堆栈以及任何异常处理的状态。 当执行在等待异步生成器的方法返
回下一个对象后恢复时，该函数可以从原状态继续进行，就仿佛 yield 表达式只
是另一个外部调用。 恢复执行之后 yield 表达式的值取决于恢复执行所用的方法
。 如果使用 *note __anext__(): 1646. 则结果为 *note None: 203.。 否则的
话，如果使用 *note asend(): 177. 则结果将是传递给该方法的值。

在异步生成器函数中，yield 表达式允许出现在 *note try: e37. 结构的任何位
置。 但是，如果一个异步生成器在其被终结（由于引用计数达到零或被作为垃圾
回收）之前未被恢复，则then a yield expression within a ‘try’ 结构中的
yield 表达式可能导致挂起的 *note finally: 2bc. 子句执行失败。 在此情况下
，应由运行该异步生成器的事件循环或任务调度器来负责调用异步生成器-迭代器
的 *note aclose(): 176. 方法并运行所返回的协程对象，从而允许任何挂起的
‘finally’ 子句得以执行。

为了能处理最终化，事件循环应该定义一个 `终结器' 函数，它接受一个异步生成
器-迭代器且可能调用 *note aclose(): 176. 并执行协程。 这个 `终结器' 可能
通过调用 *note sys.set_asyncgen_hooks(): 1057. 来注册。 当首次迭代时，异
步生成器-迭代器将保存已注册的 `终结器' 以便在最终化时调用。 有关For a
reference example of a `终结器' 方法的参考示例请查看
Lib/asyncio/base_events.py(1) 中实现的
‘asyncio.Loop.shutdown_asyncgens’。

‘yield from <expr>’ 表达式如果在异步生成器函数中使用会引发语法错误。

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/Lib/asyncio/base_events.py


File: python.info,  Node: 异步生成器-迭代器方法,  Prev: 异步生成器函数,  Up: yield 表达式

4.6.2.13 异步生成器-迭代器方法
..............................

这个子小节描述了异步生成器迭代器的方法，它们可被用于控制生成器函数的执行
。

 -- 成員函式: coroutine agen.__anext__ ()

     返回一个可等待对象，它在运行时会开始执行该异步生成器或是从上次执行
     的 yield 表达式位置恢复执行。 当一个异步生成器函数通过 *note
     __anext__(): 1646. 方法恢复执行时，当前的 yield 表达式所返回的可等
     待对象总是取值为 *note None: 203.，它在运行时将继续执行到下一个
     yield 表达式。 该 yield 表达式的 *note expression_list: 1642. 的值
     会是完成的协程所引发的 *note StopIteration: 581. 异常的值。 如果异
     步生成器没有产生下一个值就退出，则该可等待对象将引发 *note
     StopAsyncIteration: 114a. 异常，提示该异步迭代操作已完成。

     此方法通常是通过 *note async for: 3fd. 循环隐式地调用。

 -- 成員函式: coroutine agen.asend (value)

     返回一个可等待对象，它在运行时会恢复该异步生成器的执行。 与生成器的
     *note send(): 15cd. 方法一样，此方法会“发送”一个值给异步生成器函数
     ，其 `value' 参数会成为当前 yield 表达式的结果值。 *note asend():
     177. 方法所返回的可等待对象将返回生成器产生的下一个值，其值为所引发
     的 *note StopIteration: 581.，或者如果异步生成器没有产生下一个值就
     退出则引发 *note StopAsyncIteration: 114a.。 当调用 *note asend():
     177. 来启动异步生成器时，它必须以 *note None: 203. 作为调用参数，因
     为这时没有可以接收值的 yield 表达式。

 -- 成員函式: coroutine agen.athrow (type[, value[, traceback]])

     返回一个可等待对象，它会在异步生成器暂停的位置引发 ‘type’ 类型的异
     常，并返回该生成器函数所产生的下一个值，其值为所引发的 *note
     StopIteration: 581. 异常。 如果异步生成器没有产生下一个值就退出，则
     将由该可等待对象引发 *note StopAsyncIteration: 114a. 异步。 如果生
     成器函数没有捕获传入的异常，或引发了另一个异常，则当可等待对象运行
     时该异常会被传播给可等待对象的调用者。

 -- 成員函式: coroutine agen.aclose ()

     返回一个可等待对象，它会在运行时向异步生成器函数暂停的位置抛入一个
     *note GeneratorExit: df8.。 如果该异步生成器函数正常退出、关闭或引
     发 *note GeneratorExit: df8. (由于未捕获该异常) 则返回的可等待对象
     将引发 *note StopIteration: 581. 异常。 后续调用异步生成器所返回的
     任何其他可等待对象将引发 *note StopAsyncIteration: 114a. 异常。 如
     果异步生成器产生了一个值，该可等待对象会引发 *note RuntimeError:
     3dc.。 如果异步生成器引发任何其他异常，它会被传播给可等待对象的调用
     者。 如果异步生成器已经由于异常或正常退出则后续调用 *note aclose():
     176. 将返回一个不会做任何事的可等待对象。


File: python.info,  Node: 原型,  Next: await 表达式,  Prev: 原子,  Up: 表达式

4.6.3 原型
----------

原型代表编程语言中最紧密绑定的操作。 它们的句法如下:

     primary ::= atom | attributeref | subscription | slicing | call

* Menu:

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


File: python.info,  Node: 属性引用,  Next: 抽取,  Up: 原型

4.6.3.1 属性引用
................

属性引用是后面带有一个句点加一个名称的原型:

     attributeref ::= primary "." identifier

此原型必须求值为一个支持属性引用的类型的对象，多数对象都支持属性引用。 随
后该对象会被要求产生以指定标识符为名称的属性。 这个产生过程可通过重载
*note __getattr__(): 42a. 方法来自定义。 如果这个属性不可用，则将引发
*note AttributeError: 4a1. 异常。 否则的话，所产生对象的类型和值会根据该
对象来确定。 对同一属性引用的多次求值可能产生不同的对象。


File: python.info,  Node: 抽取,  Next: 切片,  Prev: 属性引用,  Up: 原型

4.6.3.2 抽取
............

对序列（字符串、元组或列表）或映射（字典）对象的抽取操作通常就是从相应的
多项集中选择一项:

     subscription ::= primary "[" expression_list "]"

此原型必须求值为一个支持抽取操作的对象（例如列表或字典）。 用户定义的对
象可通过定义 *note __getitem__(): 3a5. 方法来支持抽取操作。

对于内置对象，有两种类型的对象支持抽取操作:

如果原型为映射，表达式列表必须求值为一个以该映射的键为值的对象，抽取操作
会在映射中选出该键所对应的值。（表达式列表为一个元组，除非其中只有一项。
）

如果原型为序列，表达式列表必须求值为一个整数或一个切片（详情见下节）。

正式句法规则并没有在序列中设置负标号的特殊保留条款；但是，内置序列所提供
的 *note __getitem__(): 3a5. 方法都可通过在索引中添加序列长度来解析负标
号 (这样 ‘x[-1]’ 会选出 ‘x’ 中的最后一项)。 结果值必须为一个小于序列中项
数的非负整数，抽取操作会选出标号为该值的项（从零开始数）。 由于对负标号
和切片的支持存在于对象的 *note __getitem__(): 3a5. 方法，重载此方法的子
类需要显式地添加这种支持。

字符串的项是字符。 字符不是单独的数据类型而是仅有一个字符的字符串。

对特定 *note 类: fe8. 或 *note 类型: fe9. 的抽取操作会创建一个 *note
泛型别名: fe5.。 在此情况下，用户自定义类型可通过提供 *note
__class_getitem__(): 437. 类方法来支持抽取操作。


File: python.info,  Node: 切片,  Next: 调用,  Prev: 抽取,  Up: 原型

4.6.3.3 切片
............

切片就是在序列对象（字符串、元组或列表）中选择某个范围内的项。 切片可被
用作表达式以及赋值或 *note del: 13a2. 语句的目标。 切片的句法如下:

     slicing      ::= primary "[" slice_list "]"
     slice_list   ::= slice_item ("," slice_item)* [","]
     slice_item   ::= expression | proper_slice
     proper_slice ::= [lower_bound] ":" [upper_bound] [ ":" [stride] ]
     lower_bound  ::= expression
     upper_bound  ::= expression
     stride       ::= expression

此处的正式句法中存在一点歧义：任何形似表达式列表的东西同样也会形似切片列
表，因此任何抽取操作也可以被解析为切片。 为了不使句法更加复杂，于是通过
定义将此情况解析为抽取优先于解析为切片来消除这种歧义（切片列表未包含正确
的切片就属于此情况）。

切片的语义如下所述。 元型通过一个根据下面的切片列表来构造的键进行索引（
与普通抽取一样使用 *note __getitem__(): 3a5. 方法）。 如果切片列表包含至
少一个逗号，则键将是一个包含切片项转换的元组；否则的话，键将是单个切片项
的转换。 切片项如为一个表达式，则其转换就是该表达式。 一个正确切片的转换
就是一个切片对象（参见 *note 标准类型层级结构: 1553. 一节），该对象的
‘start’, ‘stop’ 和 ‘step’ 属性将分别为表达式所给出的下界、上界和步长值，
省略的表达式将用 ‘None’ 来替换。


File: python.info,  Node: 调用,  Prev: 切片,  Up: 原型

4.6.3.4 调用
............

所谓调用就是附带可能为空的一系列 *note 参数: 165b. 来执行一个可调用对象
(例如 *note function: 165c.):

     call                 ::= primary "(" [argument_list [","] | comprehension] ")"
     argument_list        ::= positional_arguments ["," starred_and_keywords]
                                ["," keywords_arguments]
                              | starred_and_keywords ["," keywords_arguments]
                              | keywords_arguments
     positional_arguments ::= positional_item ("," positional_item)*
     positional_item      ::= assignment_expression | "*" expression
     starred_and_keywords ::= ("*" expression | keyword_item)
                              ("," "*" expression | "," keyword_item)*
     keywords_arguments   ::= (keyword_item | "**" expression)
                              ("," keyword_item | "," "**" expression)*
     keyword_item         ::= identifier "=" expression

一个可选项为在位置和关键字参数后加上逗号而不影响语义。

此原型必须求值为一个可调用对象（用户定义的函数，内置函数，内置对象的方法
，类对象，类实例的方法以及任何具有 *note __call__(): 1560. 方法的对象都
是可调用对象）。 所有参数表达式将在尝试调用前被求值。 请参阅 *note
函数定义: 1390. 一节了解正式的 *note parameter: 1664. 列表句法。

如果存在关键字参数，它们会先通过以下操作被转换为位置参数。 首先，为正式
参数创建一个未填充空位的列表. 如果有 N 个位置参数，则将它们放入前 N 个空
位。 然后，对于每个关键字参数，使用标识符来确定其对应的空位（如果标识符
与第一个正式参数名相同则使用第一个个空位，依此类推）。 如果空位已被填充
，则会引发 *note TypeError: 1fe. 异常。 否则，将参数值放入空位进行填充（
即使表达式为 ‘None’ 也会填充空位）。 当所有参数处理完毕时，尚未填充的空
位将用来自函数定义的相应默认值来填充。 （函数一旦定义其参数默认值就会被
计算；因此，当列表或字典这类可变对象被用作默认值时，将会被所有未指定相应
空位参数值的调用所共享；这种情况通常应当避免。） 如果任何一个未填充空位
没有指定默认值，则会引发 *note TypeError: 1fe. 异常。 否则的话，已填充空
位的列表会被作为调用的参数列表。

`CPython implementation detail:' 某些实现可能提供位置参数没有名称的内置
函数，即使它们在文档说明的场合下有“命名”，因此不能以关键字形式提供参数。
在 CPython 中，以 C 编写并使用 *note PyArg_ParseTuple(): 393. 来解析其参
数的函数实现就属于这种情况。

如果存在比正式参数空位多的位置参数，将会引发 *note TypeError: 1fe. 异常
，除非有一个正式参数使用了 ‘*identifier’ 句法；在此情况下，该正式参数将
接受一个包含了多余位置参数的元组（如果没有多余位置参数则为一个空元组）。

如果任何关键字参数没有与之对应的正式参数名称，将会引发 *note TypeError:
1fe. 异常，除非有一个正式参数使用了 ‘**identifier’ 句法，该正式参数将接
受一个包含了多余关键字参数的字典（使用关键字作为键而参数值作为与键对应的
值），如果没有多余关键字参数则为一个（新的）空字典。

如果函数调用中出现了 ‘*expression’ 句法，‘expression’ 必须求值为一个
*note iterable: c7c.。 来自该可迭代对象的元素会被当作是额外的位置参数。
对于 ‘f(x1, x2, *y, x3, x4)’ 调用，如果 `y' 求值为一个序列 `y1', ...,
`yM'，则它就等价于一个带有 M+4 个位置参数 `x1', `x2', `y1', ..., `yM',
`x3', `x4' 的调用。

这样做的一个后果是虽然 ‘*expression’ 句法可能出现于显式的关键字参数 `之
后'，但它会在关键字参数（以及任何 ‘**expression’ 参数 – 见下文） `之前'
被处理。 因此:

     >>> 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

在同一个调用中同时使用关键字参数和 ‘*expression’ 句法并不常见，因此实际
上这样的混淆不会发生。

如果函数调用中出现了 ‘**expression’ 句法，‘expression’ 必须求值为一个
*note mapping: c0b.，其内容会被当作是额外的关键字参数。 如果一个关键字已
存在（作为显式关键字参数，或来自另一个拆包），则将引发 *note TypeError:
1fe. 异常。

使用 ‘*identifier’ 或 ‘**identifier’ 句法的正式参数不能被用作位置参数空
位或关键字参数名称。

3.5 版更變: 函数调用接受任意数量的 ‘*’ 和 ‘**’ 拆包，位置参数可能跟在可
迭代对象拆包 (‘*’) 之后，而关键字参数可能跟在字典拆包 (‘**’) 之后。 由
PEP 448(1) 发起最初提议。

除非引发了异常，调用总是会有返回值，返回值也可能为 ‘None’。 返回值的计算
方式取决于可调用对象的类型。

如果类型为—

用户自定义函数:

     函数的代码块会被执行，并向其传入参数列表。 代码块所做的第一件事是将
     正式形参绑定到对应参数；相关描述参见 *note 函数定义: 1390. 一节。 当
     代码块执行 *note return: 2c8. 语句时，由其指定函数调用的返回值。

内置函数或方法:

     具体结果依赖于解释器；有关内置函数和方法的描述参见 *note 內建函式:
     cbe.。

类对象:

     返回该类的一个新实例。

类实例方法:

     调用相应的用户自定义函数，向其传入的参数列表会比调用的参数列表多一
     项：该实例将成为第一个参数。

类实例:

     该类必须定义有 *note __call__(): 1560. 方法；作用效果将等价于调用该
     方法。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0448


File: python.info,  Node: await 表达式,  Next: 幂运算符,  Prev: 原型,  Up: 表达式

4.6.4 await 表达式
------------------

挂起 *note coroutine: 18a. 的执行以等待一个 *note awaitable: 612. 对象。
只能在 *note coroutine function: 732. 内部使用。

     await_expr ::= "await" primary

3.5 版新加入.


File: python.info,  Node: 幂运算符,  Next: 一元算术和位运算,  Prev: await 表达式,  Up: 表达式

4.6.5 幂运算符
--------------

幂运算符的绑定比在其左侧的一元运算符更紧密；但绑定紧密程度不及在其右侧的
一元运算符。 句法如下:

     power ::= (await_expr | primary) ["**" u_expr]

因此，在一个未加圆括号的幂运算符和单目运算符序列中，运算符将从右向左求值
（这不会限制操作数的求值顺序）: ‘-1**2’ 结果将为 ‘-1’。

幂运算符与附带两个参数调用内置 *note pow(): 2cf. 函数具有相同的语义：结
果为对其左参数进行其右参数所指定幂次的乘方运算。 数值参数会先转换为相同
类型，结果也为转换后的类型。

对于 int 类型的操作数，结果将具有与操作数相同的类型，除非第二个参数为负
数；在那种情况下，所有参数会被转换为 float 类型并输出 float 类型的结果。
例如，‘10**2’ 返回 ‘100’，而 ‘10**-2’ 返回 ‘0.01’。

对 ‘0.0’ 进行负数幂次运算将导致 *note ZeroDivisionError: 1fa.。 对负数进
行分数幂次运算将返回 *note complex: 2c1. 数值。 （在早期版本中这将引发
*note ValueError: 16d.。）

此运算符可使用特殊的 *note __pow__(): 15a1. 方法来自定义。


File: python.info,  Node: 一元算术和位运算,  Next: 二元算术运算符,  Prev: 幂运算符,  Up: 表达式

4.6.6 一元算术和位运算
----------------------

所有算术和位运算具有相同的优先级:

     u_expr ::= power | "-" u_expr | "+" u_expr | "~" u_expr

单目的 ‘-’ (负值) 运算符会产生其数字参数的负值；该运算可通过 *note
__neg__(): 15bb. 特殊方法来重载。

单目的 ‘+’ (正值) 运算符会原样输出其数字参数；该运算可通过 *note
__pos__(): 15bc. 特殊方法来重载。

单目的 ‘~’ (取反) 运算符会对其整数参数按位取反。 ‘x’ 的按位取反被定义为
‘-(x+1)’。 它只作用于整数或是重载了 *note __invert__(): 15be. 特殊方法的
自定义对象。

在所有三种情况下，如果参数的类型不正确，将引发 *note TypeError: 1fe. 异
常。


File: python.info,  Node: 二元算术运算符,  Next: 移位运算,  Prev: 一元算术和位运算,  Up: 表达式

4.6.7 二元算术运算符
--------------------

二元算术运算符遵循传统的优先级。 请注意某些此类运算符也作用于特定的非数
字类型。 除幂运算符以外只有两个优先级别，一个作用于乘法型运算符，另一个
作用于加法型运算符:

     m_expr ::= u_expr | m_expr "*" u_expr | m_expr "@" m_expr |
                m_expr "//" u_expr | m_expr "/" u_expr |
                m_expr "%" u_expr
     a_expr ::= m_expr | a_expr "+" m_expr | a_expr "-" m_expr

运算符 ‘*’ (乘) 将输出其参数的乘积。 两个参数或者必须都为数字，或者一个
参数必须为整数而另一个参数必须为序列。 在前一种情况下，两个数字将被转换
为相同类型然后相乘。 在后一种情况下，将执行序列的重复；重复因子为负数将
输出空序列。

此运算可使用特殊的 *note __mul__(): 1597. 和 *note __rmul__(): 1598. 方
法来自定义。

运算符 ‘@’ (at) 的目标是用于矩阵乘法。 没有内置 Python 类型实现此运算符
。

3.5 版新加入.

运算符 ‘/’ (除) 和 ‘//’ (整除) 将输出其参数的商。 两个数字参数将先被转换
为相同类型。 整数相除会输出一个 float 值，整数相整除的结果仍是整数；整除
的结果就是使用 ’floor’ 函数进行算术除法的结果。 除以零的运算将引发 *note
ZeroDivisionError: 1fa. 异常。

This operation can be customized using the special *note __truediv__():
875. and *note __floordiv__(): ef7. methods.

运算符 ‘%’ (模) 将输出第一个参数除以第二个参数的余数。 两个数字参数将先
被转换为相同类型。 右参数为零将引发 *note ZeroDivisionError: 1fa. 异常。
参数可以为浮点数，例如 ‘3.14%0.7’ 等于 ‘0.34’ (因为 ‘3.14’ 等于 ‘4*0.7 +
0.34’)。 模运算符的结果的正负总是与第二个操作数一致（或是为零）；结果的
绝对值一定小于第二个操作数的绝对值 (1)。

整除与模运算符的联系可通过以下等式说明: ‘x == (x//y)*y + (x%y)’。 此外整
除与模也可通过内置函数 *note divmod(): 28d. 来同时进行: ‘divmod(x, y) ==
(x//y, x%y)’。 (2)。

除了对数字执行模运算，运算符 ‘%’ 还被字符串对象重载用于执行旧式的字符串
格式化（又称插值）。 字符串格式化句法的描述参见 Python 库参考的 *note
printf 风格的字符串格式化: 1359. 一节。

`取余' 运算可使用特殊的 *note __mod__(): 15a0. 方法来自定义。

整除运算符，模运算符和 *note divmod(): 28d. 函数未被定义用于复数。 如果
有必要可以使用 *note abs(): 13f3. 函数将其转换为浮点数。

运算符 ‘+’ (addition) 将输出其参数的和。 两个参数或者必须都为数字，或者
都为相同类型的序列。 在前一种情况下，两个数字将被转换为相同类型然后相加
。 在后一种情况下，将执行序列拼接操作。

此运算可使用特殊的 *note __add__(): 1595. 和 *note __radd__(): 1596. 方
法来自定义。

运算符 ‘-’ (减) 将输出其参数的差。 两个数字参数将先被转换为相同类型。

此运算可使用特殊的 *note __sub__(): 159f. 方法来自定义。

   ---------- Footnotes ----------

   (1) (1) 虽然 ‘abs(x%y) < abs(y)’ 在数学中必为真，但对于浮点数而言，由
于舍入的存在，其在数值上未必为真。 例如，假设在某个平台上的 Python 浮点
数为一个 IEEE 754 双精度数值，为了使 ‘-1e-100 % 1e100’ 具有与 ‘1e100’ 相
同的正负性，计算结果将是 ‘-1e-100 + 1e100’，这在数值上正好等于 ‘1e100’。
函数 *note math.fmod(): 1671. 返回的结果则会具有与第一个参数相同的正负性
，因此在这种情况下将返回 ‘-1e-100’。 何种方式更适宜取决于具体的应用。

   (2) (2) 如果 x 恰好非常接近于 y 的整数倍，则由于舍入的存在 ‘x//y’ 可
能会比 ‘(x-x%y)//y’ 大。 在这种情况下，Python 会返回后一个结果，以便保持
令 ‘divmod(x,y)[0] * y + x % y’ 尽量接近 ‘x’.


File: python.info,  Node: 移位运算,  Next: 二元位运算,  Prev: 二元算术运算符,  Up: 表达式

4.6.8 移位运算
--------------

移位运算的优先级低于算术运算:

     shift_expr ::= a_expr | shift_expr ("<<" | ">>") a_expr

这些运算符接受整数参数。 它们会将第一个参数左移或右移第二个参数所指定的
比特位数。

此运算可使用特殊的 *note __lshift__(): 15a2. 和 *note __rshift__():
15a3. 方法来自定义。

右移 `n' 位被定义为被 ‘pow(2,n)’ 整除。 左移 `n' 位被定义为乘以
‘pow(2,n)’。


File: python.info,  Node: 二元位运算,  Next: 比较运算,  Prev: 移位运算,  Up: 表达式

4.6.9 二元位运算
----------------

三种位运算具有各不相同的优先级:

     and_expr ::= shift_expr | and_expr "&" shift_expr
     xor_expr ::= and_expr | xor_expr "^" and_expr
     or_expr  ::= xor_expr | or_expr "|" xor_expr

‘&’ 运算符会对其参数执行按位 AND，参数必须都为整数或者其中之一必须为重载
了 *note __and__(): 15a4. 或 *note __rand__(): 15ae. 特殊方法的自定义对
象。

‘^’ 运算符会对其参数执行按位 XOR (异 OR)，参数必须都为整数或者其中之一必
须为重载了 *note __xor__(): 15a5. 或 *note __rxor__(): 15af. 特殊方法的
自定义对象。

‘|’ 运算符会对其参数执行按位 (合并) OR，参数必须都为整数或者其中之一必须
为重载了 *note __or__(): 15a6. 或 *note __ror__(): 15b0. 特殊方法的自定
义对象。


File: python.info,  Node: 比较运算,  Next: 布尔运算,  Prev: 二元位运算,  Up: 表达式

4.6.10 比较运算
---------------

与 C 不同，Python 中所有比较运算的优先级相同，低于任何算术、移位或位运算
。 另一个与 C 不同之处在于 ‘a < b < c’ 这样的表达式会按传统算术法则来解
读:

     comparison    ::= or_expr (comp_operator or_expr)*
     comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "!="
                       | "is" ["not"] | ["not"] "in"

比较运算会产生布尔值: ‘True’ 或 ‘False’。 自定义的 `富比较方法' 可能返回
非布尔值。 在此情况下 Python 将在布尔运算上下文中对该值调用 *note
bool(): 2bd.。

比较运算可以任意串连，例如 ‘x < y <= z’ 等价于 ‘x < y and y <= z’，除了
‘y’ 只被求值一次（但在两种写法下当 ‘x < y’ 值为假时 ‘z’ 都不会被求值）。

正式的说法是这样：如果 `a', `b', `c', ..., `y', `z' 为表达式而 `op1',
`op2', ..., `opN' 为比较运算符，则 ‘a op1 b op2 c ... y opN z’ 就等价于
‘a op1 b and b op2 c and ... y opN z’，不同点在于每个表达式最多只被求值
一次。

请注意 ‘a op1 b op2 c’ 不意味着在 `a' 和 `c' 之间进行任何比较，因此，如
‘x < y > z’ 这样的写法是完全合法的（虽然也许不太好看）。

* Menu:

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


File: python.info,  Node: 值比较,  Next: 成员检测运算,  Up: 比较运算

4.6.10.1 值比较
...............

运算符 ‘<’, ‘>’, ‘==’, ‘>=’, ‘<=’ 和 ‘!=’ 将比较两个对象的值。 两个对象
不要求为相同类型。

*note 对象、值与类型: 154f. 一章已说明对象都有相应的值（还有类型和标识号
）。 对象值在 Python 中是一个相当抽象的概念：例如，对象值并没有一个规范
的访问方法。 而且，对象值并不要求具有特定的构建方式，例如由其全部数据属
性组成等。 比较运算符实现了一个特定的对象值概念。 人们可以认为这是通过实
现对象比较间接地定义了对象值。

由于所有类型都是 *note object: 3d2. 的（直接或间接）子类型，它们都从
*note object: 3d2. 继承了默认的比较行为。 类型可以通过实现 `丰富比较方法
' 例如 *note __lt__(): cfe. 来定义自己的比较行为，详情参见 *note
基本定制: 1568.。

默认的一致性比较 (‘==’ 和 ‘!=’) 是基于对象的标识号。 因此，具有相同标识
号的实例一致性比较结果为相等，具有不同标识号的实例一致性比较结果为不等。
规定这种默认行为的动机是希望所有对象都应该是自反射的 (即 ‘x is y’ 就意味
着 ‘x == y’)。

次序比较 (‘<’, ‘>’, ‘<=’ 和 ‘>=’) 默认没有提供；如果尝试比较会引发 *note
TypeError: 1fe.。 规定这种默认行为的原因是缺少与一致性比较类似的固定值。

按照默认的一致性比较行为，具有不同标识号的实例总是不相等，这可能不适合某
些对象值需要有合理定义并有基于值的一致性的类型。 这样的类型需要定制自己
的比较行为，实际上，许多内置类型都是这样做的。

以下列表描述了最主要内置类型的比较行为。

   * 内置数值类型 (*note 数字类型 — int, float, complex: 1353.) 以及标准
     库类型 *note fractions.Fraction: 2be. 和 *note decimal.Decimal:
     2c0. 可进行类型内部和跨类型的比较，例外限制是复数不支持次序比较。 在
     类型相关的限制以内，它们会按数学（算法）规则正确进行比较且不会有精
     度损失。

     非数字值 ‘float('NaN')’ 和 ‘decimal.Decimal('NaN')’ 属于特例。 任何
     数字与非数字值的排序比较均返回假值。 还有一个反直觉的结果是非数字值
     不等于其自身。 举例来说，如果 ‘x = float('NaN')’ 则 ‘3 < x’, ‘x <
     3’ 和 ‘x == x’ 均为假值，而 ‘x != x’ 则为真值。 此行为是遵循 IEEE
     754 标准的。

   * ‘None’ 和 ‘NotImplemented’ 都是单例对象。 PEP 8(1) 建议单例对象的比
     较应当总是通过 ‘is’ 或 ‘is not’ 而不是等于运算符来进行。

   * 二进制码序列 (*note bytes: 172. 或 *note bytearray: 173. 的实例) 可
     进行类型内部和跨类型的比较。 它们使用其元素的数字值按字典顺序进行比
     较。

   * 字符串 (*note str: 205. 的实例) 使用其字符的 Unicode 码位数字值 (内
     置函数 *note ord(): 1559. 的结果) 按字典顺序进行比较。 (2)

     字符串和二进制码序列不能直接比较。

   * 序列 (*note tuple: 1a2, *note list: 1f8. 或 *note range: 1f5. 的实
     例) 只可进行类型内部的比较，range 还有一个限制是不支持次序比较。 以
     上对象的跨类型一致性比较结果将是不相等，跨类型次序比较将引发 *note
     TypeError: 1fe.。

     序列比较是按字典序对相应元素进行逐个比较。 内置容器通常设定同一对象
     与其自身是相等的。 这使得它们能跳过同一对象的相等性检测以提升运行效
     率并保持它们的内部不变性。

     内置多项集间的字典序比较规则如下:

        - 两个多项集若要相等，它们必须为相同类型、相同长度，并且每对相应
          的元素都必须相等（例如，‘[1,2] == (1,2)’ 为假值，因为类型不同
          ）。

        - 对于支持次序比较的多项集，排序与其第一个不相等元素的排序相同（
          例如 ‘[1,2,x] <= [1,2,y]’ 的值与‘‘x <= y‘‘ 相同）。 如果对应元
          素不存在，较短的多项集排序在前（例如 ‘[1,2] < [1,2,3]’ 为真值
          ）。

   * 两个映射 (*note dict: 164. 的实例) 若要相等，必须当且仅当它们具有相
     同的 ‘(键, 值)’ 对。 键和值的一致性比较强制规定自反射性。

     次序比较 (‘<’, ‘>’, ‘<=’ 和 ‘>=’) 将引发 *note TypeError: 1fe.。

   * 集合 (*note set: 1f6. 或 *note frozenset: 1f7. 的实例) 可进行类型内
     部和跨类型的比较。

     它们将比较运算符定义为子集和超集检测。 这类关系没有定义完全排序（例
     如 ‘{1,2}’ 和 ‘{2,3}’ 两个集合不相等，即不为彼此的子集，也不为彼此
     的超集。 相应地，集合不适宜作为依赖于完全排序的函数的参数（例如如果
     给出一个集合列表作为 *note min(): 8f6, *note max(): 8f7. 和 *note
     sorted(): 546. 的输入将产生未定义的结果）。

     集合的比较强制规定其元素的自反射性。

   * 大多数其他内置类型没有实现比较方法，因此它们会继承默认的比较行为。

在可能的情况下，用户定义类在定制其比较行为时应当遵循一些一致性规则:

   * 相等比较应该是自反射的。 换句话说，相同的对象比较时应该相等:

          ‘x is y’ 意味着 ‘x == y’

   * 比较应该是对称的。 换句话说，下列表达式应该有相同的结果:

          ‘x == y’ 和 ‘y == x’

          ‘x != y’ 和 ‘y != x’

          ‘x < y’ 和 ‘y > x’

          ‘x <= y’ 和 ‘y >= x’

   * 比较应该是可传递的。 下列（简要的）例子显示了这一点:

          ‘x > y and y > z’ 意味着 ‘x > z’

          ‘x < y and y <= z’ 意味着 ‘x < z’

   * 反向比较应该导致布尔值取反。 换句话说，下列表达式应该有相同的结果:

          ‘x == y’ 和 ‘not x != y’

          ‘x < y’ 和 ‘not x >= y’ (对于完全排序)

          ‘x > y’ 和 ‘not x <= y’ (对于完全排序)

     最后两个表达式适用于完全排序的多项集（即序列而非集合或映射）。 另请
     参阅 *note total_ordering(): 938. 装饰器。

   * *note hash(): aa3. 的结果应该与是否相等一致。 相等的对象应该或者具
     有相同的哈希值，或者标记为不可哈希。

Python 并不强制要求这些一致性规则。 实际上，非数字值就是一个不遵循这些规
则的例子。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0008

   (2) (3) Unicode 标准明确区分 `码位' (例如 U+0041) 和 `抽象字符' (例如
"大写拉丁字母 A")。 虽然 Unicode 中的大多数抽象字符都只用一个码位来代表
，但也存在一些抽象字符可使用由多个码位组成的序列来表示。 例如，抽象字符
"带有下加符的大写拉丁字母 C" 可以用 U+00C7 码位上的单个 `预设字符' 来表
示，也可以用一个 U+0043 码位上的 `基础字符' (大写拉丁字母 C) 加上一个
U+0327 码位上的 `组合字符' (组合下加符) 组成的序列来表示。

对于字符串，比较运算符会按 Unicode 码位级别进行比较。 这可能会违反人类的
直觉。 例如，‘"\u00C7" == "\u0043\u0327"’ 为 ‘False’，虽然两个字符串都代
表同一个抽象字符 "带有下加符的大写拉丁字母 C"。

要按抽象字符级别（即对人类来说更直观的方式）对字符串进行比较，应使用
*note unicodedata.normalize(): 11e4.。


File: python.info,  Node: 成员检测运算,  Next: 标识号比较,  Prev: 值比较,  Up: 比较运算

4.6.10.2 成员检测运算
.....................

运算符 *note in: 179. 和 *note not in: 159b. 用于成员检测。 如果 `x' 是
`s' 的成员则 ‘x in s’ 求值为 ‘True’，否则为 ‘False’。 ‘x not in s’ 返回
‘x in s’ 取反后的值。 所有内置序列和集合类型以及字典都支持此运算，对于字
典来说 ‘in’ 检测其是否有给定的键。 对于 list, tuple, set, frozenset,
dict 或 collections.deque 这样的容器类型，表达式 ‘x in y’ 等价于 ‘any(x
is e or x == e for e in y)’。

对于字符串和字节串类型来说，当且仅当 `x' 是 `y' 的子串时 ‘x in y’ 为
‘True’。 一个等价的检测是 ‘y.find(x) != -1’。 空字符串总是被视为任何其他
字符串的子串，因此 ‘"" in "abc"’ 将返回 ‘True’。

对于定义了 *note __contains__(): dee. 方法的用户自定义类来说，如果
‘y.__contains__(x)’ 返回真值则 ‘x in y’ 返回 ‘True’，否则返回 ‘False’。

对于未定义 *note __contains__(): dee. 但定义了 *note __iter__(): 608. 的
用户自定义类来说，如果在对 ‘y’ 进行迭代时产生了值 ‘z’ 使得表达式 ‘x is z
or x == z’ 为真，则 ‘x in y’ 为 ‘True’。 如果在迭代期间引发了异常，则等
同于 *note in: 179. 引发了该异常。

最后将会尝试旧式的迭代协议：如果一个类定义了 *note __getitem__(): 3a5.，
则当且仅当存在非负整数索引号 `i' 使得 ‘x is y[i] or x == y[i]’ 并且没有
更小的索引号引发 *note IndexError: f36. 异常时 ‘x in y’ 为 ‘True’。 （如
果引发了任何其他异常，则等同于 *note in: 179. 引发了该异常）。

运算符 *note not in: 159b. 被定义为具有与 *note in: 179. 相反的逻辑值。


File: python.info,  Node: 标识号比较,  Prev: 成员检测运算,  Up: 比较运算

4.6.10.3 标识号比较
...................

运算符 *note is: 1551. 和 *note is not: 1681. 用于检测对象的标识号：当且
仅当 `x' 和 `y' 是同一对象时 ‘x is y’ 为真。 一个对象的标识号可使用
*note id(): e4b. 函数来确定。 ‘x is not y’ 会产生相反的逻辑值。 (1)

   ---------- Footnotes ----------

   (1) (4) 由于存在自动垃圾收集、空闲列表以及描述器的动态特性，你可能会
注意到在特定情况下使用 *note is: 1551. 运算符会出现看似不正常的行为，例
如涉及到实例方法或常量之间的比较时就是如此。 更多信息请查看有关它们的文
档。


File: python.info,  Node: 布尔运算,  Next: 赋值表达式<2>,  Prev: 比较运算,  Up: 表达式

4.6.11 布尔运算
---------------

     or_test  ::= and_test | or_test "or" and_test
     and_test ::= not_test | and_test "and" not_test
     not_test ::= comparison | "not" not_test

在执行布尔运算的情况下，或是当表达式被用于流程控制语句时，以下值会被解析
为假值: ‘False’, ‘None’, 所有类型的数字零，以及空字符串和空容器（包括字
符串、元组、列表、字典、集合与冻结集合）。 所有其他值都会被解析为真值。
用户自定义对象可通过提供 *note __bool__(): d30. 方法来定制其逻辑值。

运算符 *note not: 1686. 将在其参数为假值时产生 ‘True’，否则产生 ‘False’。

表达式 ‘x and y’ 首先对 `x' 求值；如果 `x' 为假则返回该值；否则对 `y' 求
值并返回其结果值。

表达式 ‘x or y’ 首先对 `x' 求值；如果 `x' 为真则返回该值；否则对 `y' 求
值并返回其结果值。

请注意 *note and: 1683. 和 *note or: 1684. 都不限制其返回的值和类型必须
为 ‘False’ 和 ‘True’，而是返回最终求值的参数。 此行为是有必要的，例如假
设 ‘s’ 为一个当其为空时应被替换为某个默认值的字符串，表达式 ‘s or 'foo'’
将产生希望的值。 由于 *note not: 1686. 必须创建一个新值，不论其参数为何
种类型它都会返回一个布尔值（例如，‘not 'foo'’ 结果为 ‘False’ 而非 ‘''’。
）


File: python.info,  Node: 赋值表达式<2>,  Next: 条件表达式,  Prev: 布尔运算,  Up: 表达式

4.6.12 赋值表达式
-----------------

     assignment_expression ::= [identifier ":="] expression

赋值表达式（有时又被叫做“命名表达式”或“海象表达式”）将一个 *note
expression: 168c. 赋值给一个 *note identifier: 1507.，同时还返回 *note
expression: 168c. 的值。

一个常见用例是在处理匹配的正则表达式的时候:

     if matching := pattern.search(data):
         do_something(matching)

或者是在处理分块的文件流的时候:

     while chunk := file.read(9000):
         process(chunk)

3.8 版新加入: 请参阅 PEP 572(1) 了解有关赋值表达式的详情。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0572


File: python.info,  Node: 条件表达式,  Next: lambda 表达式,  Prev: 赋值表达式<2>,  Up: 表达式

4.6.13 条件表达式
-----------------

     conditional_expression ::= or_test ["if" or_test "else" expression]
     expression             ::= conditional_expression | lambda_expr

条件表达式（有时称为“三元运算符”）在所有 Python 运算中具有最低的优先级。

表达式 ‘x if C else y’ 首先是对条件 `C' 而非 `x' 求值。 如果 `C' 为真，
`x' 将被求值并返回其值；否则将对 `y' 求值并返回其值。

请参阅 PEP 308(1) 了解有关条件表达式的详情。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0308


File: python.info,  Node: lambda 表达式,  Next: 表达式列表,  Prev: 条件表达式,  Up: 表达式

4.6.14 lambda 表达式
--------------------

     lambda_expr ::= "lambda" [parameter_list] ":" expression

lambda 表达式（有时称为 lambda 构型）被用于创建匿名函数。 表达式 ‘lambda
parameters: expression’ 会产生一个函数对象 。 该未命名对象的行为类似于用
以下方式定义的函数:

     def <lambda>(parameters):
         return expression

请参阅 *note 函数定义: 1390. 了解有关参数列表的句法。 请注意通过 lambda
表达式创建的函数不能包含语句或标注。


File: python.info,  Node: 表达式列表,  Next: 求值顺序,  Prev: lambda 表达式,  Up: 表达式

4.6.15 表达式列表
-----------------

     expression_list    ::= expression ("," expression)* [","]
     starred_list       ::= starred_item ("," starred_item)* [","]
     starred_expression ::= expression | (starred_item ",")* [starred_item]
     starred_item       ::= assignment_expression | "*" or_expr

除了作为列表或集合显示的一部分，包含至少一个逗号的表达式列表将生成一个元
组。 元组的长度就是列表中表达式的数量。 表达式将从左至右被求值。

一个星号 ‘*’ 表示 `可迭代拆包'。 其操作数必须为一个 *note iterable:
c7c.。 该可迭代对象将被拆解为迭代项的序列，并被包含于在拆包位置上新建的
元组、列表或集合之中。

3.5 版新加入: 表达式列表中的可迭代对象拆包，最初由 PEP 448(1) 提出。

末尾的逗号仅在创建单独元组 (或称 `单例') 时需要；在所有其他情况下都是可
选项。 没有末尾逗号的单独表达式不会创建一个元组，而是产生该表达式的值。
（要创建一个空元组，应使用一对内容为空的圆括号: ‘()’。）

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0448


File: python.info,  Node: 求值顺序,  Next: 运算符优先级,  Prev: 表达式列表,  Up: 表达式

4.6.16 求值顺序
---------------

Python 按从左至右的顺序对表达式求值。 但注意在对赋值操作求值时，右侧会先
于左侧被求值。

在以下几行中，表达式将按其后缀的算术优先顺序被求值。:

     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


File: python.info,  Node: 运算符优先级,  Prev: 求值顺序,  Up: 表达式

4.6.17 运算符优先级
-------------------

下表对 Python 中运算符的优先顺序进行了总结，从最高优先级（最先绑定）到最
低优先级（最后绑定）。 相同单元格内的运算符具有相同优先级。 除非句法显式
地给出，否则运算符均指二元运算。 相同单元格内的运算符从左至右分组（除了
幂运算是从右至左分组）。

请注意比较、成员检测和标识号检测均为相同优先级，并具有如 *note 比较运算:
167a. 一节所描述的从左至右串连特性。

运算符                                              描述
                                                    
----------------------------------------------------------------------------------------------
                                                    
‘(expressions...)’,                                 绑定或加圆括号的表达式，列表显示，字典
                                                    显示，集合显示
‘[expressions...]’, ‘{key: value...}’,              
‘{expressions...}’

‘x[index]’, ‘x[index:index]’, ‘x(arguments...)’,    抽取，切片，调用，属性引用
‘x.attribute’                                       

*note await: 2d8. ‘x’                               await 表达式
                                                    
                                                    
‘**’                                                乘方 (1)
                                                    
                                                    
‘+x’, ‘-x’, ‘~x’                                    正，负，按位非 NOT
                                                    
                                                    
‘*’, ‘@’, ‘/’, ‘//’, ‘%’                            乘，矩阵乘，除，整除，取余 (2)
                                                    
                                                    
‘+’, ‘-’                                            加和减
                                                    
                                                    
‘<<’, ‘>>’                                          移位
                                                    
                                                    
‘&’                                                 按位与 AND
                                                    
                                                    
‘^’                                                 按位异或 XOR
                                                    
                                                    
‘|’                                                 按位或 OR
                                                    
                                                    
*note in: 179, *note not in: 159b,                  比较运算，包括成员检测和标识号检测
*note is: 1551, *note is not: 1681, ‘<’, ‘<=’,      
‘>’, ‘>=’, ‘!=’, ‘==’

*note not: 1686. ‘x’                                布尔逻辑非 NOT
                                                    
                                                    
*note and: 1683.                                    布尔逻辑与 AND
                                                    
                                                    
*note or: 1684.                                     布尔逻辑或 OR
                                                    
                                                    
*note if: 168e. – ‘else’                            条件表达式
                                                    
                                                    
*note lambda: cf9.                                  lambda 表达式
                                                    
                                                    
‘:=’                                                赋值表达式
                                                    

註解
....

   ---------- Footnotes ----------

   (1) (5) 幂运算符 ‘**’ 绑定的紧密程度低于在其右侧的算术或按位一元运算
符，也就是说 ‘2**-1’ 为 ‘0.5’。

   (2) (6) ‘%’ 运算符也被用于字符串格式化；在此场合下会使用同样的优先级
。


File: python.info,  Node: 简单语句,  Next: 复合语句,  Prev: 表达式,  Up: Python 語言參考手冊

4.7 简单语句
============

简单语句由一个单独的逻辑行构成。 多条简单语句可以存在于同一行内并以分号
分隔。 简单语句的句法为:

     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

* Menu:

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


File: python.info,  Node: 表达式语句,  Next: 赋值语句,  Up: 简单语句

4.7.1 表达式语句
----------------

表达式语句用于计算和写入值（大多是在交互模式下），或者（通常情况）调用一
个过程 (过程就是不返回有意义结果的函数；在 Python 中，过程的返回值为
‘None’)。 表达式语句的其他使用方式也是允许且有特定用处的。 表达式语句的
句法为:

     expression_stmt ::= starred_expression

表达式语句会对指定的表达式列表（也可能为单一表达式）进行求值。

在交互模式下，如果结果值不为 ‘None’，它会通过内置的 *note repr(): 8b9. 函
数转换为一个字符串，该结果字符串将以单独一行的形式写入标准输出（例外情况
是如果结果为 ‘None’，则该过程调用不产生任何输出。）


File: python.info,  Node: 赋值语句,  Next: assert 语句,  Prev: 表达式语句,  Up: 简单语句

4.7.2 赋值语句
--------------

赋值语句用于将名称（重）绑定到特定值，以及修改属性或可变对象的成员项:

     assignment_stmt ::= (target_list "=")+ (starred_expression | yield_expression)
     target_list     ::= target ("," target)* [","]
     target          ::= identifier
                         | "(" [target_list] ")"
                         | "[" [target_list] "]"
                         | attributeref
                         | subscription
                         | slicing
                         | "*" target

(请参阅 *note 原型: 164a. 一节了解 `属性引用', `抽取' 和 `切片' 的句法定
义。)

赋值语句会对指定的表达式列表进行求值（注意这可能为单一表达式或是由逗号分
隔的列表，后者将产生一个元组）并将单一结果对象从左至右逐个赋值给目标列表
。

赋值是根据目标（列表）的格式递归地定义的。 当目标为一个可变对象（属性引
用、抽取或切片）的组成部分时，该可变对象必须最终执行赋值并决定其有效性，
如果赋值操作不可接受也可能引发异常。 各种类型可用的规则和引发的异常通过
对象类型的定义给出（参见 *note 标准类型层级结构: 1553. 一节）。

对象赋值的目标对象可以包含于圆括号或方括号内，具体操作按以下方式递归地定
义。

   * 如果目标列表为后面不带逗号、可以包含于圆括号内的单一目标，则将对象
     赋值给该目标。

   * 否则：该对象必须为具有与目标列表相同项数的可迭代对象，这些项将按从
     左至右的顺序被赋值给对应的目标。

        * 如果目标列表包含一个带有星号前缀的目标，这称为“加星”目标：则该
          对象至少必须为与目标列表项数减一相同项数的可迭代对象。 该可迭
          代对象前面的项将按从左至右的顺序被赋值给加星目标之前的目标。 该
          可迭代对象末尾的项将被赋值给加星目标之后的目标。 然后该可迭代
          对象中剩余项的列表将被赋值给加星目标（该列表可以为空）。

        * 否则：该对象必须为具有与目标列表相同项数的可迭代对象，这些项将
          按从左至右的顺序被赋值给对应的目标。

对象赋值给单个目标的操作按以下方式递归地定义。

   * 如果目标为标识符（名称）:

        * 如果该名称未出现于当前代码块的 *note global: 1378. 或 *note
          nonlocal: d07. 语句中：该名称将被绑定到当前局部命名空间的对象
          。

        * 否则：该名称将被分别绑定到全局命名空间或由 *note nonlocal:
          d07. 所确定的外层命名空间的对象。

     如果该名称已经被绑定则将被重新绑定。 这可能导致之前被绑定到该名称的
     对象的引用计数变为零，造成该对象进入释放过程并调用其析构器（如果存
     在）。

   * 如果该对象为属性引用：引用中的原型表达式会被求值。 它应该产生一个具
     有可赋值属性的对象；否则将引发 *note TypeError: 1fe.。 该对象会被要
     求将可赋值对象赋值给指定的属性；如果它无法执行赋值，则会引发异常 (通
     常应为 *note AttributeError: 4a1. 但并不强制要求)。 注意：如果该对
     象为类实例并且属性引用在赋值运算符的两侧都出现，则右侧表达式 ‘a.x’
     可以访问实例属性或（如果实例属性不存在）类属性。 左侧目标 ‘a.x’ 将
     总是设定为实例属性，并在必要时创建该实例属性。 因此 ‘a.x’ 的两次出
     现不一定指向相同的属性：如果右侧表达式指向一个类属性，则左侧会创建
     一个新的实例属性作为赋值的目标:

          class Cls:
              x = 3             # class variable
          inst = Cls()
          inst.x = inst.x + 1   # writes inst.x as 4 leaving Cls.x as 3

     此描述不一定作用于描述器属性，例如通过 *note property(): 308. 创建
     的特征属性。

   * 如果目标为一个抽取项：引用中的原型表达式会被求值。 它应当产生一个可
     变序列对象（例如列表）或一个映射对象（例如字典）。 接下来，该抽取表
     达式会被求值。

     如果原型为一个可变序列对象（例如列表），抽取应产生一个整数。 如其为
     负值，则再加上序列长度。 结果值必须为一个小于序列长度的非负整数，序
     列将把被赋值对象赋值给该整数指定索引号的项。 如果索引超出范围，将会
     引发 *note IndexError: f36. (给被抽取序列赋值不能向列表添加新项)。

     如果原型为一个映射对象（例如字典），抽取必须具有与该映射的键类型相
     兼容的类型，然后映射中会创建一个将抽取映射到被赋值对象的键/值对。 这
     可以是替换一个现有键/值对并保持相同键值，也可以是插入一个新键/值对
     （如果具有相同值的键不存在）。

     对于用户定义对象，会调用 *note __setitem__(): d2a. 方法并附带适当的
     参数。

   * 如果目标为一个切片：引用中的原型表达式会被求值。 它应当产生一个可变
     序列对象（例如列表）。 被赋值对象应当是一个相同类型的序列对象。 接
     下来，下界与上界表达式如果存在的话将被求值；默认值分别为零和序列长
     度。 上下边界值应当为整数。 如果某一边界为负值，则会加上序列长度。
     求出的边界会被裁剪至介于零和序列长度的开区间中。 最后，将要求序列对
     象以被赋值序列的项替换该切片。 切片的长度可能与被赋值序列的长度不同
     ，这会在目标序列允许的情况下改变目标序列的长度。

`CPython implementation detail:' 在当前实现中，目标的句法被当作与表达式
的句法相同，无效的句法会在代码生成阶段被拒绝，导致不太详细的错误信息。

虽然赋值的定义意味着左手边与右手边的重叠是“同时”进行的（例如 ‘a, b = b,
a’ 会交换两个变量的值），但在赋值给变量的多项集 `之内' 的重叠是从左至右
进行的，这有时会令人混淆。 例如，以下程序将会打印出 ‘[0, 2]’:

     x = [0, 1]
     i = 0
     i, x[i] = 1, 2         # i is updated, then x[i] is updated
     print(x)

也參考
......

PEP 3132(1) - 扩展的可迭代对象拆包

     对 ‘*target’ 特性的规范说明。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3132


File: python.info,  Node: 增强赋值语句,  Next: 带标注的赋值语句,  Up: 赋值语句

4.7.2.1 增强赋值语句
....................

增强赋值语句就是在单个语句中将二元运算和赋值语句合为一体:

     augmented_assignment_stmt ::= augtarget augop (expression_list | yield_expression)
     augtarget                 ::= identifier | attributeref | subscription | slicing
     augop                     ::= "+=" | "-=" | "*=" | "@=" | "/=" | "//=" | "%=" | "**="
                                   | ">>=" | "<<=" | "&=" | "^=" | "|="

（请参阅 *note 原型: 164a. 一节了解最后三种符号的句法定义。）

增强赋值语句将对目标和表达式列表求值（与普通赋值语句不同的是，前者不能为
可迭代对象拆包），对两个操作数相应类型的赋值执行指定的二元运算，并将结果
赋值给原始目标。 目标仅会被求值一次。

增强赋值语句例如 ‘x += 1’ 可以改写为 ‘x = x + 1’ 获得类似但并非完全等价
的效果。 在增强赋值的版本中，‘x’ 仅会被求值一次。 而且，在可能的情况下，
实际的运算是 `原地' 执行的，也就是说并不是创建一个新对象并将其赋值给目标
，而是直接修改原对象。

不同于普通赋值，增强赋值会在对右手边求值 `之前' 对左手边求值。 例如，
‘a[i] += f(x)’ 首先查找 ‘a[i]’，然后对 ‘f(x)’ 求值并执行加法操作，最后将
结果写回到 ‘a[i]’。

除了在单个语句中赋值给元组和多个目标的例外情况，增强赋值语句的赋值操作处
理方式与普通赋值相同。 类似地，除了可能存在 `原地' 操作行为的例外情况，
增强赋值语句执行的二元运算也与普通二元运算相同。

对于属性引用类目标，针对常规赋值的 *note 关于类和实例属性的警告: 16a7. 也
同样适用。


File: python.info,  Node: 带标注的赋值语句,  Prev: 增强赋值语句,  Up: 赋值语句

4.7.2.2 带标注的赋值语句
........................

*note 标注: 712. 赋值就是在单个语句中将变量或属性标注和可选的赋值语句合
为一体:

     annotated_assignment_stmt ::= augtarget ":" expression
                                   ["=" (starred_expression | yield_expression)]

与普通 *note 赋值语句: 16a2. 的差别在于仅允许单个目标。

对于将简单名称作为赋值目标的情况，如果是在类或模块作用域中，标注会被求值
并存入一个特殊的类或模块属性 ‘__annotations__’ 中，这是一个将变量名称（
如为私有会被移除）映射到被求值标注的字典。 此属性为可写并且在类或模块体
开始执行时如果静态地发现标注就会自动创建。

对于将表达式作为赋值目标的情况，如果是在类或模块作用域中，标注会被求值，
但不会保存。

如果一个名称在函数作用域内被标注，则该名称为该作用域的局部变量。 标注绝
不会在函数作用域内被求值和保存。

如果存在右手边，带标注的赋值会在对标注求值之前（如果适用）执行实际的赋值
。 如果用作表达式目标的右手边不存在，则解释器会对目标求值，但最后的
*note __setitem__(): d2a. 或 *note __setattr__(): eee. 调用除外。

也參考
......

PEP 526(1) - 变量标注的语法

     该提议增加了标注变量（也包括类变量和实例变量）类型的语法，而不再是
     通过注释来进行表达。

PEP 484(2) - 类型提示

     该提议增加了 *note typing: 122. 模块以便为类型标注提供标准句法，可
     被静态分析工具和 IDE 所使用。

3.8 版更變: 现在带有标注的赋值允许在右边以同样的表达式作为常规赋值。 之
前，某些表达式（例如未加圆括号的元组表达式）会导致语法错误。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0526

   (2) https://www.python.org/dev/peps/pep-0484


File: python.info,  Node: assert 语句,  Next: pass 语句,  Prev: 赋值语句,  Up: 简单语句

4.7.3 ‘assert’ 语句
-------------------

assert 语句是在程序中插入调试性断言的简便方式:

     assert_stmt ::= "assert" expression ["," expression]

简单形式 ‘assert expression’ 等价于

     if __debug__:
         if not expression: raise AssertionError

扩展形式 ‘assert expression1, expression2’ 等价于

     if __debug__:
         if not expression1: raise AssertionError(expression2)

以上等价形式假定 *note __debug__: 1137. 和 *note AssertionError: 240. 指
向具有指定名称的内置变量。 在当前实现中，内置变量 *note __debug__: 1137.
在正常情况下为 ‘True’，在请求优化时为 ‘False’ (对应命令行选项为 *note
-O: 77e.)。 如果在编译时请求优化，当前代码生成器不会为 assert 语句发出任
何代码。 请注意不必在错误信息中包含失败表达式的源代码；它会被作为栈追踪
的一部分被显示。

赋值给 *note __debug__: 1137. 是非法的。 该内置变量的值会在解释器启动时
确定。


File: python.info,  Node: pass 语句,  Next: del 语句,  Prev: assert 语句,  Up: 简单语句

4.7.4 ‘pass’ 语句
-----------------

     pass_stmt ::= "pass"

*note pass: 1374. 是一个空操作 — 当它被执行时，什么都不发生。 它适合当语
法上需要一条语句但并不需要执行任何代码时用来临时占位，例如:

     def f(arg): pass    # a function that does nothing (yet)

     class C: pass       # a class with no methods (yet)


File: python.info,  Node: del 语句,  Next: return 语句,  Prev: pass 语句,  Up: 简单语句

4.7.5 ‘del’ 语句
----------------

     del_stmt ::= "del" target_list

删除是递归定义的，与赋值的定义方式非常类似。 此处不再详细说明，只给出一
些提示。

目标列表的删除将从左至右递归地删除每一个目标。

名称的删除将从局部或全局命名空间中移除该名称的绑定，具体作用域的确定是看
该名称是否有在同一代码块的 *note global: 1378. 语句中出现。 如果该名称未
被绑定，将会引发 *note NameError: e40.。

属性引用、抽取和切片的删除会被传递给相应的原型对象；删除一个切片基本等价
于赋值为一个右侧类型的空切片（但即便这一点也是由切片对象决定的）。

3.2 版更變: 在之前版本中，如果一个名称作为被嵌套代码块中的自由变量出现，
则将其从局部命名空间中删除是非法的。


File: python.info,  Node: return 语句,  Next: yield 语句,  Prev: del 语句,  Up: 简单语句

4.7.6 ‘return’ 语句
-------------------

     return_stmt ::= "return" [expression_list]

*note return: 2c8. 在语法上只会出现于函数定义所嵌套的代码，不会出现于类
定义所嵌套的代码。

如果提供了表达式列表，它将被求值，否则以 ‘None’ 替代。

*note return: 2c8. 会离开当前函数调用，并以表达式列表 (或 ‘None’) 作为返
回值。

当 *note return: 2c8. 将控制流传出一个带有 *note finally: 2bc. 子句的
*note try: e37. 语句时，该 ‘finally’ 子句会先被执行然后再真正离开该函数
。

在一个生成器函数中，*note return: 2c8. 语句表示生成器已完成并将导致
*note StopIteration: 581. 被引发。 返回值（如果有的话）会被当作一个参数
用来构建 *note StopIteration: 581. 并成为 ‘StopIteration.value’ 属性。

在一个异步生成器函数中，一个空的 *note return: 2c8. 语句表示异步生成器已
完成并将导致 *note StopAsyncIteration: 114a. 被引发。 一个非空的
‘return’ 语句在异步生成器函数中会导致语法错误。


File: python.info,  Node: yield 语句,  Next: raise 语句,  Prev: return 语句,  Up: 简单语句

4.7.7 ‘yield’ 语句
------------------

     yield_stmt ::= yield_expression

*note yield: 2c7. 语句在语义上等同于 *note yield 表达式: 163d.。 yield 语
句可用来省略在使用等效的 yield 表达式语句时所必须的圆括号。 例如，以下
yield 语句

     yield <expr>
     yield from <expr>

等同于以下 yield 表达式语句

     (yield <expr>)
     (yield from <expr>)

yield 表达式和语句仅在定义 *note generator: a83. 函数时使用，并且仅被用
于生成器函数的函数体内部。 在函数定义中使用 yield 就足以使得该定义创建的
是生成器函数而非普通函数。

有关 *note yield: 2c7. 语义的完整细节请参看 *note yield 表达式: 163d. 一
节。


File: python.info,  Node: raise 语句,  Next: break 语句,  Prev: yield 语句,  Up: 简单语句

4.7.8 ‘raise’ 语句
------------------

     raise_stmt ::= "raise" [expression ["from" expression]]

如果不带表达式，*note raise: d0a. 会重新引发当前作用域内最后一个激活的异
常。 如果当前作用域内没有激活的异常，将会引发 *note RuntimeError: 3dc. 来
提示错误。

否则的话，*note raise: d0a. 会将第一个表达式求值为异常对象。 它必须为
*note BaseException: 2db. 的子类或实例。 如果它是一个类，当需要时会通过
不带参数地实例化该类来获得异常的实例。

异常的 `类型' 为异常实例的类，`值' 为实例本身。

当异常被引发时通常会自动创建一个回溯对象并将其关联到可写的
‘__traceback__’ 属性。 你可以创建一个异常并同时使用 ‘with_traceback()’ 异
常方法（该方法将返回同一异常实例，并将回溯对象设为其参数）设置自己的回溯
，就像这样:

     raise Exception("foo occurred").with_traceback(tracebackobj)

‘from’ 子句用于异常串连：如果有该子句，则第二个 `表达式' 必须为另一个异
常类或实例。 如果第二个表达式是一个异常实例，它将作为可写的 ‘__cause__’
属性被关联到所引发的异常。 如果该表达式是一个异常类，这个类将被实例化且
所生成的异常实例将作为 ‘__cause__’ 属性被关联到所引发的异常。 如果所引发
的异常未被处理，则两个异常都将被打印出来:

     >>> 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

如果一个异常在异常处理器或 *note finally: 2bc. clause: 中被引发，类似的
机制会隐式地发挥作用，之前的异常将被关联到新异常的 ‘__context__’ 属性:

     >>> 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

异常串连可通过在 ‘from’ 子句中指定 *note None: 203. 来显式地加以抑制:

     >>> 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

有关异常的更多信息可在 *note 异常: 15e3. 一节查看，有关处理异常的信息可
在 *note try 语句: e37. 一节查看。

3.3 版更變: *note None: 203. 现在允许被用作 ‘raise X from Y’ 中的 ‘Y’。

3.3 版新加入: 使用 ‘__suppress_context__’ 属性来抑制异常上下文的自动显示
。


File: python.info,  Node: break 语句,  Next: continue 语句,  Prev: raise 语句,  Up: 简单语句

4.7.9 ‘break’ 语句
------------------

     break_stmt ::= "break"

*note break: 3fa. 在语法上只会出现于 *note for: cfa. 或 *note while:
1361. 循环所嵌套的代码，但不会出现于该循环内部的函数或类定义所嵌套的代码
。

它会终结最近的外层循环，如果循环有可选的 ‘else’ 子句，也会跳过该子句。

如果一个 *note for: cfa. 循环被 *note break: 3fa. 所终结，该循环的控制目
标会保持其当前值。

当 *note break: 3fa. 将控制流传出一个带有 *note finally: 2bc. 子句的
*note try: e37. 语句时，该 ‘finally’ 子句会先被执行然后再真正离开该循环
。


File: python.info,  Node: continue 语句,  Next: import 语句,  Prev: break 语句,  Up: 简单语句

4.7.10 ‘continue’ 语句
----------------------

     continue_stmt ::= "continue"

*note continue: 2bb. 在语法上只会出现于 *note for: cfa. 或 *note while:
1361. 循环所嵌套的代码中，但不会出现于该循环内部的函数或类定义中。 它会
继续执行最近的外层循环的下一个轮次。

当 *note continue: 2bb. 将控制流传出一个带有 *note finally: 2bc. 子句的
*note try: e37. 语句时，该 ‘finally’ 子句会先被执行然后再真正开始循环的
下一个轮次。


File: python.info,  Node: import 语句,  Next: global 语句,  Prev: continue 语句,  Up: 简单语句

4.7.11 ‘import’ 语句
--------------------

     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" "*"
     module          ::= (identifier ".")* identifier
     relative_module ::= "."* module | "."+

基本的 import 语句（不带 *note from: d0d. 子句）会分两步执行:

  1. 查找一个模块，如果有必要还会加载并初始化模块。

  2. 在局部命名空间中为 *note import: ce7. 语句发生位置所处的作用域定义
     一个或多个名称。

当语句包含多个子句（由逗号分隔）时这两个步骤将对每个子句分别执行，如同这
些子句被分成独立的 import 语句一样。

第一个步骤即查找和加载模块的详情 *note 导入系统: 1561. 一节中有更详细的
描述，其中也描述了可被导入的多种类型的包和模块，以及可用于定制导入系统的
所有钩子对象。 请注意这一步如果失败，则可能说明模块无法找到，`或者' 是在
初始化模块，包括执行模块代码期间发生了错误。

如果成功获取到请求的模块，则可以通过以下三种方式一之在局部命名空间中使用
它:

   * 如果模块名称之后带有 ‘as’，则跟在 ‘as’ 之后的名称将直接绑定到所导入
     的模块。

   * 如果没有指定其他名称，且被导入的模块为最高层级模块，则模块的名称将
     被绑定到局部命名空间作为对所导入模块的引用。

   * 如果被导入的模块 `不是' 最高层级模块，则包含该模块的最高层级包的名
     称将被绑定到局部命名空间作为对该最高层级包的引用。 所导入的模块必须
     使用其完整限定名称来访问而不能直接访问。

*note from: d0d. 形式使用的过程略微繁复一些:

  1. 查找 *note from: d0d. 子句中指定的模块，如有必要还会加载并初始化模
     块；

  2. 对于 *note import: ce7. 子句中指定的每个标识符：

       1. 检查被导入模块是否有该名称的属性

       2. 如果没有，尝试导入具有该名称的子模块，然后再次检查被导入模块是
          否有该属性

       3. 如果未找到该属性，则引发 *note ImportError: 16c.。

       4. 否则的话，将对该值的引用存入局部命名空间，如果有 ‘as’ 子句则使
          用其指定的名称，否则使用该属性的名称

例如:

     import foo                 # foo imported and bound locally
     import foo.bar.baz         # foo.bar.baz imported, foo bound locally
     import foo.bar.baz as fbb  # foo.bar.baz imported and bound as fbb
     from foo.bar import baz    # foo.bar.baz imported and bound as baz
     from foo import attr       # foo imported and foo.attr bound as attr

如果标识符列表改为一个星号 (‘'*'’)，则在模块中定义的全部公有名称都将按
*note import: ce7. 语句所在的作用域被绑定到局部命名空间。

一个模块所定义的 `公有名称' 是由在模块的命名空间中检测一个名为 ‘__all__’
的变量来确定的；如果有定义，它必须是一个字符串列表，其中的项为该模块所定
义或导入的名称。 在 ‘__all__’ 中所给出的名称都会被视为公有并且应当存在。
如果 ‘__all__’ 没有被定义，则公有名称的集合将包含在模块的命名空间中找到
的所有不以下划线字符 (‘'_'’) 打头的名称。 ‘__all__’ 应当包括整个公有
API。 它的目标是避免意外地导出不属于 API 的一部分的项（例如在模块内部被
导入和使用的库模块）。

通配符形式的导入 — ‘from module import *’ — 仅在模块层级上被允许。 尝试
在类或函数定义中使用它将引发 *note SyntaxError: 559.。

当指定要导入哪个模块时，你不必指定模块的绝对名称。 当一个模块或包被包含
在另一个包之中时，可以在同一个最高层级包中进行相对导入，而不必提及包名称
。 通过在 *note from: d0d. 之后指定的模块或包中使用前缀点号，你可以在不
指定确切名称的情况下指明在当前包层级结构中要上溯多少级。 一个前缀点号表
示是执行导入的模块所在的当前包，两个点号表示上溯一个包层级。 三个点号表
示上溯两级，依此类推。 因此如果你执行 ‘from . import mod’ 时所处位置为
‘pkg’ 包内的一个模块，则最终你将导入 ‘pkg.mod’。 如果你执行 ‘from
..subpkg2 import mod’ 时所处位置为 ‘pkg.subpkg1’ 则你将导入
‘pkg.subpkg2.mod’。 有关相对导入的规范说明包含在 *note 包相对导入: 1611.
一节中。

*note importlib.import_module(): be6. 被提供用来为动态地确定要导入模块的
应用提供支持。

引发一个 *note 审计事件: fa1. ‘import’ 附带参数 ‘module’, ‘filename’,
‘sys.path’, ‘sys.meta_path’, ‘sys.path_hooks’。

* Menu:

* future 语句::


File: python.info,  Node: future 语句,  Up: import 语句

4.7.11.1 future 语句
....................

`future 语句' 是一种针对编译器的指令，指明某个特定模块应当使用在特定的未
来某个 Python 发行版中成为标准特性的语法或语义。

future 语句的目的是使得向在语言中引入了不兼容改变的 Python 未来版本的迁
移更为容易。 它允许基于每个模块在某种新特性成为标准之前的发行版中使用该
特性。

     future_stmt ::= "from" "__future__" "import" feature ["as" identifier]
                     ("," feature ["as" identifier])*
                     | "from" "__future__" "import" "(" feature ["as" identifier]
                     ("," feature ["as" identifier])* [","] ")"
     feature     ::= identifier

future 语句必须在靠近模块开头的位置出现。 可以出现在 future 语句之前行只
有:

   * 模块的文档字符串（如果存在），

   * 注释，

   * 空行，以及

   * 其他 future 语句。

唯一需要使用 future 语句的特性是 ‘标注’ (参见 PEP 563(1))。

future 语句所启用的所有历史特性仍然为 Python 3 所认可。 其中包括
‘absolute_import’, ‘division’, ‘generators’, ‘generator_stop’,
‘unicode_literals’, ‘print_function’, ‘nested_scopes’ 和
‘with_statement’。 它们都已成为冗余项，因为它们总是为已启用状态，保留它
们只是为了向后兼容。

future 语句在编译时会被识别并做特殊对待：对核心构造语义的改变常常是通过
生成不同的代码来实现。 新的特性甚至可能会引入新的不兼容语法（例如新的保
留字），在这种情况下编译器可能需要以不同的方式来解析模块。 这样的决定不
能推迟到运行时方才作出。

对于任何给定的发布版本，编译器要知道哪些特性名称已被定义，如果某个
future 语句包含未知的特性则会引发编译时错误。

直接运行时的语义与任何 import 语句相同：存在一个后文将详细说明的标准模块
*note __future__: 0.，它会在执行 future 语句时以通常的方式被导入。

相应的运行时语义取决于 future 语句所启用的指定特性。

请注意以下语句没有任何特别之处:

     import __future__ [as name]

这并非 future 语句；它只是一条没有特殊语义或语法限制的普通 import 语句。

在默认情况下，通过对Code compiled by calls to the 内置函数 *note exec():
d0c. 和 *note compile(): 2e7. 的调用所编译的代码如果出现于一个包含有
future 语句的模块 ‘M’ 之中，就会使用 future 语句所关联的语法和语义。 此
行为可以通过 *note compile(): 2e7. 的可选参数加以控制 — 请参阅该函数的文
档以了解详情。

在交互式解释器提示符中键入的 future 语句将在解释器会话此后的交互中有效。
如果一个解释器的启动使用了 *note -i: ee1. 选项启动，并传入了一个脚本名称
来执行，且该脚本包含 future 语句，它将在交互式会话开始执行脚本之后保持有
效。

也參考
......

PEP 236(2) - 回到 __future__

     有关 __future__ 机制的最初提议。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0563

   (2) https://www.python.org/dev/peps/pep-0236


File: python.info,  Node: global 语句,  Next: nonlocal 语句,  Prev: import 语句,  Up: 简单语句

4.7.12 ‘global’ 语句
--------------------

     global_stmt ::= "global" identifier ("," identifier)*

*note global: 1378. 语句是作用于整个当前代码块的声明。 它意味着所列出的
标识符将被解读为全局变量。 要给全局变量赋值不可能不用到 ‘global’ 关键字
，不过自由变量也可以指向全局变量而不必声明为全局变量。

在 *note global: 1378. 语句中列出的名称不得在同一代码块内该 ‘global’ 语
句之前的位置中使用。

在 *note global: 1378. 语句中列出的名称不能被定义为形式参数，也不能在
*note for: cfa. 循环的控制目标、*note class: d32. 定义、函数定义、*note
import: ce7. 语句或变量标注中定义。

`CPython implementation detail:' 当前的实现并未强制要求所有的上述限制，
但程序不应当滥用这样的自由，因为未来的实现可能会改为强制要求，并静默地改
变程序的含义。

`程序员注意事项:' *note global: 1378. 是对解析器的指令。 它仅对与
‘global’ 语句同时被解析的代码起作用。 特别地，包含在提供给内置 *note
exec(): d0c. 函数字符串或代码对象中的 ‘global’ 语句并不会影响 `包含' 该
函数调用的代码块，而包含在这种字符串中的代码也不会受到包含该函数调用的代
码中的 ‘global’ 语句影响。 这同样适用于 *note eval(): c61. 和 *note
compile(): 2e7. 函数。


File: python.info,  Node: nonlocal 语句,  Prev: global 语句,  Up: 简单语句

4.7.13 ‘nonlocal’ 语句
----------------------

     nonlocal_stmt ::= "nonlocal" identifier ("," identifier)*

*note nonlocal: d07. 语句会使得所列出的名称指向之前在最近的包含作用域中
绑定的除全局变量以外的变量。 这种功能很重要，因为绑定的默认行为是先搜索
局部命名空间。 这个语句允许被封装的代码重新绑定局部作用域以外且非全局（
模块）作用域当中的变量。

与 *note global: 1378. 语句中列出的名称不同，*note nonlocal: d07. 语句中
列出的名称必须指向之前存在于包含作用域之中的绑定（在这个应当用来创建新绑
定的作用域不能被无歧义地确定）。

*note nonlocal: d07. 语句中列出的名称不得与之前存在于局部作用域中的绑定
相冲突。

也參考
......

PEP 3104(1) - 访问外层作用域中的名称

     有关 *note nonlocal: d07. 语句的规范说明。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3104


File: python.info,  Node: 复合语句,  Next: 顶级组件,  Prev: 简单语句,  Up: Python 語言參考手冊

4.8 复合语句
============

复合语句是包含其它语句（语句组）的语句；它们会以某种方式影响或控制所包含
其它语句的执行。 通常，复合语句会跨越多行，虽然在某些简单形式下整个复合
语句也可能包含于一行之内。

*note if: eab, *note while: 1361. 和 *note for: cfa. 语句用来实现传统的
控制流程构造。 *note try: e37. 语句为一组语句指定异常处理和/和清理代码，
而 *note with: 7da. 语句允许在一个代码块周围执行初始化和终结化代码。 函
数和类定义在语法上也属于复合语句。

一条复合语句由一个或多个‘子句’组成。 一个子句则包含一个句头和一个‘句体
’。 特定复合语句的子句头都处于相同的缩进层级。 每个子句头以一个作为唯一
标识的关键字开始并以一个冒号结束。 子句体是由一个子句控制的一组语句。 子
句体可以是在子句头的冒号之后与其同处一行的一条或由分号分隔的多条简单语句
，或者也可以是在其之后缩进的一行或多行语句。 只有后一种形式的子句体才能
包含嵌套的复合语句；以下形式是不合法的，这主要是因为无法分清某个后续的
*note else: 1368. 子句应该属于哪个 *note if: eab. 子句:

     if test1: if test2: print(x)

还要注意的是在这种情形下分号的绑定比冒号更紧密，因此在以下示例中，所有
*note print(): 971. 调用或者都不执行，或者都执行:

     if x < y < z: print(x); print(y); print(z)

总结:

     compound_stmt ::= if_stmt
                       | while_stmt
                       | for_stmt
                       | try_stmt
                       | with_stmt
                       | funcdef
                       | classdef
                       | async_with_stmt
                       | async_for_stmt
                       | async_funcdef
     suite         ::= stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
     statement     ::= stmt_list NEWLINE | compound_stmt
     stmt_list     ::= simple_stmt (";" simple_stmt)* [";"]

请注意语句总是以 ‘NEWLINE’ 结束，之后可能跟随一个 ‘DEDENT’。 还要注意可
选的后续子句总是以一个不能作为语句开头的关键字作为开头，因此不会产生歧义
（‘悬空的 *note else: 1368.’问题在 Python 中是通过要求嵌套的 *note if:
eab. 语句必须缩进来解决的)。

为了保证清晰，以下各节中语法规则采用将每个子句都放在单独行中的格式。
* Menu:

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


File: python.info,  Node: if 语句,  Next: while 语句,  Up: 复合语句

4.8.1 ‘if’ 语句
---------------

*note if: eab. 语句用于有条件的执行:

     if_stmt ::= "if" assignment_expression ":" suite
                 ("elif" assignment_expression ":" suite)*
                 ["else" ":" suite]

它通过对表达式逐个求值直至找到一个真值（请参阅 *note 布尔运算: 1682. 了
解真值与假值的定义）在子句体中选择唯一匹配的一个；然后执行该子句体（而且
*note if: eab. 语句的其他部分不会被执行或求值）。 如果所有表达式均为假值
，则如果 *note else: 1368. 子句体如果存在就会被执行。


File: python.info,  Node: while 语句,  Next: for 语句,  Prev: if 语句,  Up: 复合语句

4.8.2 ‘while’ 语句
------------------

*note while: 1361. 语句用于在表达式保持为真的情况下重复地执行:

     while_stmt ::= "while" assignment_expression ":" suite
                    ["else" ":" suite]

这将重复地检验表达式，并且如果其值为真就执行第一个子句体；如果表达式值为
假（这可能在第一次检验时就发生）则如果 ‘else’ 子句体存在就会被执行并终止
循环。

第一个子句体中的 *note break: 3fa. 语句在执行时将终止循环且不执行 ‘else’
子句体。 第一个子句体中的 *note continue: 2bb. 语句在执行时将跳过子句体
中的剩余部分并返回检验表达式。


File: python.info,  Node: for 语句,  Next: try 语句,  Prev: while 语句,  Up: 复合语句

4.8.3 ‘for’ 语句
----------------

*note for: cfa. 语句用于对序列（例如字符串、元组或列表）或其他可迭代对象
中的元素进行迭代:

     for_stmt ::= "for" target_list "in" expression_list ":" suite
                  ["else" ":" suite]

表达式列表会被求值一次；它应该产生一个可迭代对象。 系统将为
‘expression_list’ 的结果创建一个迭代器，然后将为迭代器所提供的每一项执行
一次子句体，具体次序与迭代器的返回顺序一致。 每一项会按标准赋值规则 (参
见 *note 赋值语句: 16a2.) 被依次赋值给目标列表，然后子句体将被执行。 当
所有项被耗尽时 (这会在序列为空或迭代器引发 *note StopIteration: 581. 异
常时立刻发生)，‘else’ 子句的子句体如果存在将会被执行，并终止循环。

第一个子句体中的 *note break: 3fa. 语句在执行时将终止循环且不执行 ‘else’
子句体。 第一个子句体中的 *note continue: 2bb. 语句在执行时将跳过子句体
中的剩余部分并转往下一项继续执行，或者在没有下一项时转往 ‘else’ 子句执行
。

for 循环会对目标列表中的变量进行赋值。 这将覆盖之前对这些变量的所有赋值
，包括在 for 循环体中的赋值:

     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

目标列表中的名称在循环结束时不会被删除，但如果序列为空，则它们根本不会被
循环所赋值。 提示：内置函数 *note range(): 1f5. 会返回一个可迭代的整数序
列，适用于模拟 Pascal 中的 ‘for i := a to b do’ 这种效果；例如
‘list(range(3))’ 会返回列表 ‘[0, 1, 2]’。

     備註: 
     当序列在循环中被修改时会有一个微妙的问题（这只可能发生于可变序列例
     如列表中）。 会有一个内部计数器被用来跟踪下一个要使用的项，每次迭代
     都会使计数器递增。 当计数器值达到序列长度时循环就会终止。 这意味着
     如果语句体从序列中删除了当前（或之前）的一项，下一项就会被跳过（因
     为其标号将变成已被处理的当前项的标号）。 类似地，如果语句体在序列当
     前项的前面插入一个新项，当前项会在循环的下一轮中再次被处理。 这会导
     致麻烦的程序错误，避免此问题的办法是对整个序列使用切片来创建一个临
     时副本，例如

          for x in a[:]:
              if x < 0: a.remove(x)


File: python.info,  Node: try 语句,  Next: with 语句,  Prev: for 语句,  Up: 复合语句

4.8.4 ‘try’ 语句
----------------

*note try: e37. 语句可为一组语句指定异常处理器和/或清理代码:

     try_stmt  ::= try1_stmt | try2_stmt
     try1_stmt ::= "try" ":" suite
                   ("except" [expression ["as" identifier]] ":" suite)+
                   ["else" ":" suite]
                   ["finally" ":" suite]
     try2_stmt ::= "try" ":" suite
                   "finally" ":" suite

*note except: c10. 子句指定一个或多个异常处理程序。 当 *note try: e37. 子
句中没有发生异常时，没有任何异常处理程序会被执行。 当 ‘try’ 子句中发生异
常时，将启动对异常处理程序的搜索。 此搜索会逐一检查 except 子句直至找到
与该异常相匹配的子句。 如果存在无表达式的 except 子句，它必须是最后一个
；它将匹配任何异常。 对于带有表达式的 except 子句，该表达式会被求值，如
果结果对象与发生的异常“兼容”则该子句将匹配该异常。 如果一个对象是异常对
象所属的类或基类，或者是包含兼容该异常的项的元组则两者就是兼容的。

如果没有 except 子句与异常相匹配，则会在周边代码和发起调用栈上继续搜索异
常处理器。 (1)

如果在对 except 子句头中的表达式求值时引发了异常，则原来对处理器的搜索会
被取消，并在周边代码和调用栈上启动对新异常的搜索（它会被视作是整个 *note
try: e37. 语句所引发的异常）。

当找到一个匹配的 except 子句时，该异常将被赋值给该 except 子句在 ‘as’ 关
键字之后指定的目标，如果存在此关键字的话，并且该 except 子句体将被执行。
所有 except 子句都必须有可执行的子句体。 当到达子句体的末尾时，通常会转
向整个 try 语句之后继续执行。 （这意味着如果对于同一异常存在有嵌套的两个
处理器，而异常发生于内层处理器的 try 子句中，则外层处理器将不会处理该异
常。）

当使用 ‘as’ 将目标赋值为一个异常时，它将在 except 子句结束时被清除。 这
就相当于

     except E as N:
         foo

被转写为

     except E as N:
         try:
             foo
         finally:
             del N

这意味着异常必须赋值给一个不同的名称才能在 except 子句之后引用它。 异常
会被清除是因为在附加了回溯信息的情况下，它们会形成堆栈帧的循环引用，使得
所有局部变量保持存活直到发生下一次垃圾回收。

在一个 except 子句体被执行之前，有关异常的详细信息存放在 *note sys: fd.
模块中，可通过 *note sys.exc_info(): d27. 来访问。 *note sys.exc_info():
d27. 返回一个 3 元组，由异常类、异常实例和回溯对象组成（参见 *note
标准类型层级结构: 1553. 一节），用于在程序中标识异常发生点。 当从处理异
常的函数返回时 *note sys.exc_info(): d27. 的值会恢复为（调用前的）原值。

如果控制流离开 *note try: e37. 子句体时没有引发异常，并且没有执行 *note
return: 2c8, *note continue: 2bb. 或 *note break: 3fa. 语句，可选的
‘else’ 子句将被执行。 ‘else’ 语句中的异常不会由之前的 *note except: c10.
子句处理。

如果存在 *note finally: 2bc.，它将指定一个‘清理’处理程序。 *note try:
e37. 子句会被执行，包括任何 *note except: c10. 和 ‘else’ 子句。 如果在这
些子句中发生任何未处理的异常，该异常会被临时保存。 ‘finally’ 子句将被执
行。 如果存在被保存的异常，它会在 ‘finally’ 子句的末尾被重新引发。 如果
‘finally’ 子句引发了另一个异常，被保存的异常会被设为新异常的上下文。 如
果 ‘finally’ 子句执行了 *note return: 2c8, *note break: 3fa. 或 *note
continue: 2bb. 语句，则被保存的异常会被丢弃:

     >>> def f():
     ...     try:
     ...         1/0
     ...     finally:
     ...         return 42
     ...
     >>> f()
     42

在 *note finally: 2bc. 子句执行期间，程序不能获取异常信息。

当 *note return: 2c8, *note break: 3fa. 或 *note continue: 2bb. 语句在一
个 ‘try’...‘finally’ 语句的 *note try: e37. 子语句体中被执行时，*note
finally: 2bc. 子语句也会‘在离开时’被执行。

函数的返回值是由最后被执行的 *note return: 2c8. 语句所决定的。 由于
*note finally: 2bc. 子句总是被执行，因此在 ‘finally’ 子句中被执行的
‘return’ 语句总是最后被执行的:

     >>> def foo():
     ...     try:
     ...         return 'try'
     ...     finally:
     ...         return 'finally'
     ...
     >>> foo()
     'finally'

有关异常的更多信息可以在 *note 异常: 15e3. 一节找到，有关使用 *note
raise: d0a. 语句生成异常的信息可以在 *note raise 语句: d0a. 一节找到。

3.8 版更變: 在 Python 3.8 之前，*note continue: 2bb. 语句不允许在 *note
finally: 2bc. 子句中使用，这是因为具体实现存在一个问题。

   ---------- Footnotes ----------

   (1) (1) 异常会被传播给发起调用栈，除非存在一个 *note finally: 2bc. 子
句正好引发了另一个异常。 新引发的异常将导致旧异常的丢失。


File: python.info,  Node: with 语句,  Next: 函数定义,  Prev: try 语句,  Up: 复合语句

4.8.5 ‘with’ 语句
-----------------

*note with: 7da. 语句用于包装带有使用上下文管理器 (参见 *note with
语句上下文管理器: 15c4. 一节) 定义的方法的代码块的执行。 这允许对普通的
*note try: e37...*note except: c10...*note finally: 2bc. 使用模式进行封
装以方便地重用。

     with_stmt ::= "with" with_item ("," with_item)* ":" suite
     with_item ::= expression ["as" target]

带有一个“项目”的 *note with: 7da. 语句的执行过程如下:

  1. 对上下文表达式 (在 *note with_item: 16e0. 中给出的表达式) 求值以获
     得一个上下文管理器。

  2. 载入上下文管理器的 *note __enter__(): d5d. 以便后续使用。

  3. 载入上下文管理器的 *note __exit__(): d5e. 以便后续使用。

  4. 发起调用上下文管理器的 *note __enter__(): d5d. 方法。

  5. 如果 *note with: 7da. 语句中包含一个目标，来自 *note __enter__():
     d5d. 的返回值将被赋值给它。

          備註: *note with: 7da. 语句会保证如果 *note __enter__(): d5d.
          方法返回时未发生错误，则 *note __exit__(): d5e. 将总是被调用。
          因此，如果在对目标列表赋值期间发生错误，则会将其视为在语句体内
          部发生的错误。 参见下面的第 6 步。

  6. 执行语句体。

  7. 发起调用上下文管理器的 *note __exit__(): d5e. 方法。 如果语句体的退
     出是由异常导致的，则其类型、值和回溯信息将被作为参数传递给 *note
     __exit__(): d5e.。 否则的话，将提供三个 *note None: 203. 参数。

     如果语句体的退出是由异常导致的，并且来自 *note __exit__(): d5e. 方
     法的返回值为假，则该异常会被重新引发。 如果返回值为真，则该异常会被
     抑制，并会继续执行 *note with: 7da. 语句之后的语句。

     如果语句体由于异常以外的任何原因退出，则来自 *note __exit__(): d5e.
     的返回值会被忽略，并会在该类退出正常的发生位置继续执行。

以下代码:

     with EXPRESSION as TARGET:
         SUITE

在语义上等价于:

     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)

如果有多个项目，则会视作存在多个 *note with: 7da. 语句嵌套来处理多个上下
文管理器:

     with A() as a, B() as b:
         SUITE

在语义上等价于:

     with A() as a:
         with B() as b:
             SUITE

3.1 版更變: 支持多个上下文表达式。

也參考
......

PEP 343(1) - "with" 语句

     Python *note with: 7da. 语句的规范描述、背景和示例。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0343


File: python.info,  Node: 函数定义,  Next: 类定义,  Prev: with 语句,  Up: 复合语句

4.8.6 函数定义
--------------

函数定义就是对用户自定义函数的定义（参见 *note 标准类型层级结构: 1553. 一
节）:

     funcdef                   ::= [decorators] "def" funcname "(" [parameter_list] ")"
                                   ["->" expression] ":" suite
     decorators                ::= decorator+
     decorator                 ::= "@" assignment_expression NEWLINE
     parameter_list            ::= defparameter ("," defparameter)* "," "/" ["," [parameter_list_no_posonly]]
                                     | parameter_list_no_posonly
     parameter_list_no_posonly ::= defparameter ("," defparameter)* ["," [parameter_list_starargs]]
                                   | parameter_list_starargs
     parameter_list_starargs   ::= "*" [parameter] ("," defparameter)* ["," ["**" parameter [","]]]
                                   | "**" parameter [","]
     parameter                 ::= identifier [":" expression]
     defparameter              ::= parameter ["=" expression]
     funcname                  ::= identifier

函数定义是一条可执行语句。 它执行时会在当前局部命名空间中将函数名称绑定
到一个函数对象（函数可执行代码的包装器）。 这个函数对象包含对当前全局命
名空间的引用，作为函数被调用时所使用的全局命名空间。

函数定义并不会执行函数体；只有当函数被调用时才会执行此操作。 (1)

一个函数定义可以被一个或多个 *note decorator: 174. 表达式所包装。 当函数
被定义时将在包含该函数定义的作用域中对装饰器表达式求值。 求值结果必须是
一个可调用对象，它会以该函数对象作为唯一参数被发起调用。 其返回值将被绑
定到函数名称而非函数对象。 多个装饰器会以嵌套方式被应用。 例如以下代码

     @f1(arg)
     @f2
     def func(): pass

大致等价于

     def func(): pass
     func = f1(arg)(f2(func))

不同之处在于原始函数并不会被临时绑定到名称 ‘func’。

3.9 版更變: 函数可使用任何有效的 *note assignment_expression: 168b. 来装
饰。 在之前版本中，此语法则更为受限，详情参见 PEP 614(2)。

当一个或多个 *note 形参: 1664. 具有 `形参' ‘=’ `表达式' 这样的形式时，该
函数就被称为具有“默认形参值”。 对于一个具有默认值的形参，其对应的 *note
argument: 165b. 可以在调用中被省略，在此情况下会用形参的默认值来替代。 如
果一个形参具有默认值，后续所有在 "‘*’" 之前的形参也必须具有默认值 — 这个
句法限制并未在语法中明确表达。

`默认形参值会在执行函数定义时按从左至右的顺序被求值。' 这意味着当函数被
定义时将对表达式求值一次，相同的“预计算”值将在每次调用时被使用。 这一点
在默认形参为可变对象，例如列表或字典的时候尤其需要重点理解：如果函数修改
了该对象（例如向列表添加了一项），则实际上默认值也会被修改。 这通常不是
人们所预期的。 绕过此问题的一个方法是使用 ‘None’ 作为默认值，并在函数体
中显式地对其进行测试，例如:

     def whats_on_the_telly(penguin=None):
         if penguin is None:
             penguin = []
         penguin.append("property of the zoo")
         return penguin

函数调用的语义在 *note 调用: 73f. 一节中有更详细的描述。 函数调用总是会
给形参列表中列出的所有形参赋值，或是用位置参数，或是用关键字参数，或是用
默认值。 如果存在 "‘*identifier’" 这样的形式，它会被初始化为一个元组来接
收任何额外的位置参数，默认为一个空元组。 如果存在 "‘**identifier’" 这样
的形式，它会被初始化为一个新的有序映射来接收任何额外的关键字参数，默认为
一个相同类型的空映射。 在 "‘*’" 或 "‘*identifier’" 之后的形参都是仅限关
键字形参因而只能通过关键字参数传入。 在 "‘/’" 之前的形参都是仅限位置形参
因而只能通过位置参数传入。

3.8 版更變: 可以使用 ‘/’ 函数形参语法来标示仅限位置形参。 请参阅 PEP
570(3) 了解详情。

形参可以带有 *note 标注: 1391.，其形式为在形参名称后加上 "‘:
expression’"。 任何形参都可以带有标注，甚至 ‘*identifier’ 或
‘**identifier’ 这样的形参也可以。 函数可以带有“返回”标注，其形式为在形参
列表后加上 "‘-> expression’"。 这些标注可以是任何有效的 Python 表达式。
标注的存在不会改变函数的语义。 标注值可以作为函数对象的
‘__annotations__’ 属性中以对应形参名称为键的字典值被访问。 如果使用了
‘annotations’ import from *note __future__: 0. 的方式，则标注会在运行时
保存为字符串以启用延迟求值特性。 否则，它们会在执行函数定义时被求值。 在
这种情况下，标注的求值顺序可能与它们在源代码中出现的顺序不同。

创建匿名函数（未绑定到一个名称的函数）以便立即在表达式中使用也是可能的。
这需要使用 lambda 表达式，具体描述见 *note lambda 表达式: cf9. 一节。 请
注意 lambda 只是简单函数定义的一种简化写法；在 "*note def: e83." 语句中
定义的函数也可以像用 lambda 表达式定义的函数一样被传递或赋值给其他名称。
"‘def’" 形式实际上更为强大，因为它允许执行多条语句和使用标注。

`程序员注意事项:' 函数属于一类对象。 在一个函数内部执行的 "‘def’" 语句会
定义一个局部函数并可被返回或传递。 在嵌套函数中使用的自由变量可以访问包
含该 def 语句的函数的局部变量。 详情参见 *note 命名与绑定: 15d9. 一节。

也參考
......

PEP 3107(4) - 函数标注

     最初的函数标注规范说明。

PEP 484(5) - 类型提示

     标注的标准含意定义：类型提示。

PEP 526(6) - 变量标注的语法

     变量声明的类型提示功能，包括类变量和实例变量

PEP 563(7) - 延迟的标注求值

     支持在运行时通过以字符串形式保存标注而非不是即求值来实现标注内部的
     向前引用。

   ---------- Footnotes ----------

   (1) (2) 作为函数体的第一条语句出现的字符串字面值会被转换为函数的
‘__doc__’ 属性，也就是该函数的 *note docstring: 16eb.。

   (2) https://www.python.org/dev/peps/pep-0614

   (3) https://www.python.org/dev/peps/pep-0570

   (4) https://www.python.org/dev/peps/pep-3107

   (5) https://www.python.org/dev/peps/pep-0484

   (6) https://www.python.org/dev/peps/pep-0526

   (7) https://www.python.org/dev/peps/pep-0563


File: python.info,  Node: 类定义,  Next: 协程<2>,  Prev: 函数定义,  Up: 复合语句

4.8.7 类定义
------------

类定义就是对类对象的定义 (参见 *note 标准类型层级结构: 1553. 一节):

     classdef    ::= [decorators] "class" classname [inheritance] ":" suite
     inheritance ::= "(" [argument_list] ")"
     classname   ::= identifier

类定义是一条可执行语句。 其中继承列表通常给出基类的列表 (进阶用法请参见
*note 元类: 157c.)，列表中的每一项都应当被求值为一个允许子类的类对象。 没
有继承列表的类默认继承自基类 *note object: 3d2.；因此，:

     class Foo:
         pass

等价于

     class Foo(object):
         pass

随后类体将在一个新的执行帧 (参见 *note 命名与绑定: 15d9.) 中被执行，使用
新创建的局部命名空间和原有的全局命名空间。 （通常，类体主要包含函数定义
。） 当类体结束执行时，其执行帧将被丢弃而其局部命名空间会被保存。 (1) 一
个类对象随后会被创建，其基类使用给定的继承列表，属性字典使用保存的局部命
名空间。 类名称将在原有的全局命名空间中绑定到该类对象。

在类体内定义的属性的顺序保存在新类的 ‘__dict__’ 中。 请注意此顺序的可靠
性只限于类刚被创建时，并且只适用于使用定义语法所定义的类。

类的创建可使用 *note 元类: 157c. 进行重度定制。

类也可以被装饰：就像装饰函数一样，:

     @f1(arg)
     @f2
     class Foo: pass

大致等价于

     class Foo: pass
     Foo = f1(arg)(f2(Foo))

装饰器表达式的求值规则与函数装饰器相同。 结果随后会被绑定到类名称。

3.9 版更變: 类可使用任何有效的 *note assignment_expression: 168b. 来装饰
。 在之前版本中，此语法则更为受限，详情参见 PEP 614(2)。

`程序员注意事项:' 在类定义内定义的变量是类属性；它们将被类实例所共享。 实
例属性可通过 ‘self.name = value’ 在方法中设定。 类和实例属性均可通过
"‘self.name’" 表示法来访问，当通过此方式访问时实例属性会隐藏同名的类属性
。 类属性可被用作实例属性的默认值，但在此场景下使用可变值可能导致未预期
的结果。 可以使用 *note 描述器: 5e3. 来创建具有不同实现细节的实例变量。

也參考
......

PEP 3115(3) - Python 3000 中的元类

     将元类声明修改为当前语法的提议，以及关于如何构建带有元类的类的语义
     描述。

PEP 3129(4) - 类装饰器

     增加类装饰器的提议。 函数和方法装饰器是在 PEP 318(5) 中被引入的。

   ---------- Footnotes ----------

   (1) (3) 作为类体的第一条语句出现的字符串字面值会被转换为命名空间的
‘__doc__’ 条目，也就是该类的 *note docstring: 16eb.。

   (2) https://www.python.org/dev/peps/pep-0614

   (3) https://www.python.org/dev/peps/pep-3115

   (4) https://www.python.org/dev/peps/pep-3129

   (5) https://www.python.org/dev/peps/pep-0318


File: python.info,  Node: 协程<2>,  Prev: 类定义,  Up: 复合语句

4.8.8 协程
----------

3.5 版新加入.

* Menu:

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


File: python.info,  Node: 协程函数定义,  Next: async for 语句,  Up: 协程<2>

4.8.8.1 协程函数定义
....................

     async_funcdef ::= [decorators] "async" "def" funcname "(" [parameter_list] ")"
                       ["->" expression] ":" suite

Python 协程可以在多个位置上挂起和恢复执行 (参见 *note coroutine: 18a.)。
在协程函数体内部，‘await’ 和 ‘async’ 标识符已成为保留关键字；*note
await: 2d8. 表达式，*note async for: 3fd. 以及 *note async with: 736. 只
能在协程函数体中使用。

使用 ‘async def’ 语法定义的函数总是为协程函数，即使它们不包含 ‘await’ 或
‘async’ 关键字。

在协程函数体中使用 ‘yield from’ 表达式将引发 *note SyntaxError: 559.。

协程函数的例子:

     async def func(param1, param2):
         do_stuff()
         await some_coroutine()


File: python.info,  Node: async for 语句,  Next: async with 语句,  Prev: 协程函数定义,  Up: 协程<2>

4.8.8.2 ‘async for’ 语句
........................

     async_for_stmt ::= "async" for_stmt

*note asynchronous iterable: 733. 提供了 ‘__aiter__’ 方法，该方法会直接
返回 *note asynchronous iterator: 738.，它可以在其 ‘__anext__’ 方法中调
用异步代码。

‘async for’ 语句允许方便地对异步可迭代对象进行迭代。

以下代码:

     async for TARGET in ITER:
         SUITE
     else:
         SUITE2

在语义上等价于:

     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

另请参阅 *note __aiter__(): 582. 和 *note __anext__(): 155f. 了解详情。

在协程函数体之外使用 ‘async for’ 语句将引发 *note SyntaxError: 559.。


File: python.info,  Node: async with 语句,  Prev: async for 语句,  Up: 协程<2>

4.8.8.3 ‘async with’ 语句
.........................

     async_with_stmt ::= "async" with_stmt

*note asynchronous context manager: 734. 是一种 *note context manager:
661.，能够在其 `enter' 和 `exit' 方法中暂停执行。

以下代码:

     async with EXPRESSION as TARGET:
         SUITE

在语义上等价于:

     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)

另请参阅 *note __aenter__(): 109a. 和 *note __aexit__(): 109b. 了解详情
。

在协程函数体之外使用 ‘async with’ 语句将引发 *note SyntaxError: 559.。

也參考
......

PEP 492(1) - 使用 async 和 await 语法实现协程

     将协程作为 Python 中的一个正式的单独概念，并增加相应的支持语法。

註解
....

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0492


File: python.info,  Node: 顶级组件,  Next: 完整的語法規格書,  Prev: 复合语句,  Up: Python 語言參考手冊

4.9 顶级组件
============

Python 解释器可以从多种源获得输入：作为标准输入或程序参数传入的脚本，以
交互方式键入的语句，导入的模块源文件等等。 这一章将给出在这些情况下所用
的语法。

* Menu:

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


File: python.info,  Node: 完整的 Python 程序,  Next: 文件输入,  Up: 顶级组件

4.9.1 完整的 Python 程序
------------------------

虽然语言规范描述不必规定如何发起调用语言解释器，但对完整的 Python 程序加
以说明还是很有用的。 一个完整的 Python 程序会在最小初始化环境中被执行：
所有内置和标准模块均为可用，但均处于未初始化状态，只有 *note sys: fd. (各
种系统服务), *note builtins: 12. (内置函数、异常以及 ‘None’) 和 *note
__main__: 1. 除外。 最后一个模块用于为完整程序的执行提供局部和全局命名空
间。

适用于一个完整 Python 程序的语法即下节所描述的文件输入。

解释器也可以通过交互模式被发起调用；在此情况下，它并不读取和执行一个完整
程序，而是每次读取和执行一条语句（可能为复合语句）。 此时的初始环境与一
个完整程序的相同；每条语句会在 *note __main__: 1. 的命名空间中被执行。

一个完整程序可通过三种形式被传递给解释器：使用 *note -c: 1340. `字符串'
命令行选项，使用一个文件作为第一个命令行参数，或者使用标准输入。 如果文
件或标准输入是一个 tty 设置，解释器会进入交互模式；否则的话，它会将文件
当作一个完整程序来执行。


File: python.info,  Node: 文件输入,  Next: 交互式输入,  Prev: 完整的 Python 程序,  Up: 顶级组件

4.9.2 文件输入
--------------

所有从非交互式文件读取的输入都具有相同的形式:

     file_input ::= (NEWLINE | statement)*

此语法用于下列几种情况:

   * 解析一个完整 Python 程序时（从文件或字符串）；

   * 解析一个模块时；

   * 解析一个传递给 *note exec(): d0c. 函数的字符串时；


File: python.info,  Node: 交互式输入,  Next: 表达式输入,  Prev: 文件输入,  Up: 顶级组件

4.9.3 交互式输入
----------------

交互模式下的输入使用以下语法进行解析:

     interactive_input ::= [stmt_list] NEWLINE | compound_stmt NEWLINE

请注意在交互模式下一条（最高层级）复合语句必须带有一个空行；这对于帮助解
析器确定输入的结束是必须的。


File: python.info,  Node: 表达式输入,  Prev: 交互式输入,  Up: 顶级组件

4.9.4 表达式输入
----------------

*note eval(): c61. 被用于表达式输入。 它会忽略开头的空白。 传递给 *note
eval(): c61. 的字符串参数必须具有以下形式:

     eval_input ::= expression_list NEWLINE*


File: python.info,  Node: 完整的語法規格書,  Prev: 顶级组件,  Up: Python 語言參考手冊

4.10 完整的語法規格書
=====================

这是完整的 Python 语法规范，直接提取自用于生成 CPython 解析器的语法 (参
见 Grammar/python.gram(1))。 这里显示的版本省略了有关代码生成和错误恢复
的细节。

所用的标记法是 EBNF(2) 和 PEG(3) 的混合体。 特别地，‘&’ 后跟一个符号、形
符或带括号的分组来表示正向前视（即要求执行匹配但不会被消耗掉），而 ‘!’ 表
示负向前视（即要求 _不_ 执行匹配）。 我们使用 ‘|’ 分隔符来表示 PEG 的“有
序选择” (在传统 PEG 语法中则写为 ‘/’)。

     # PEG grammar for Python

     @trailer '''
     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
     '''
     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") }

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Grammar/python.gram

   (2) https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form

   (3) https://en.wikipedia.org/wiki/Parsing_expression_grammar


File: python.info,  Node: Python 標準函式庫 Standard Library,  Next: 擴充和嵌入 Python 直譯器,  Prev: Python 語言參考手冊,  Up: Top

5 Python 標準函式庫 (Standard Library)
**************************************

*note Python 語言參考手冊: 1331.說明 Python 這門語言確切的文法及語意，而
這份函式庫參考手冊則是說明隨著 Python 一起發佈的標準函式庫，除此之外，其
內容也包含一些時常出現在 Python 發佈版本中的非必要套件。

Python 的標準函式庫是非常龐大的，其提供了如下所述極多且涵蓋用途極廣的許
多模組。包含一些用 C 語言撰寫，可以操作像是檔案讀寫等系統相關功能的內建
模組，當然也有用 Python 撰寫，並使用標準解法解決許多常見問題的模組。其中
有些模組則是特別針對 Python 的可攜性去設計的，為此特地將一些平台特殊相依
性的功能抽象化成可跨平台的 API。

Python 的 Windows 安裝檔基本上包含整個標準函式庫，且通常也包含許多附加的
組件；而在類 Unix 作業系統方面，Python 通常是以一系列的套件被安裝，因此
對於某些或全部的可選組件，可能都必須使用該作業系統提供的套件管理工具來安
裝。

在標準函式庫之外，還有成千上萬且不斷增加的組件（從個別的程式、模組、套件
到完整的應用程式開發框架），可以從 Python 套件索引 (Python Package
Index)(1) 中取得。

* Menu:

* 簡介: 簡介<6>.
* 內建函式::
* 內建常數::
* 內建型態::
* 內建的例外::
* 文本處理 (Text Processing) 服務: 文本處理 Text Processing 服務.
* 二进制数据服务::
* 数据类型::
* 數值與數學模組::
* 函式編程模組::
* 檔案與目錄存取::
* 数据持久化::
* 資料壓縮與保存::
* 檔案格式::
* 加密服务::
* 通用操作系统服务::
* 并发执行::
* 网络和进程间通信::
* 互联网数据处理::
* 结构化标记处理工具::
* 互联网协议和支持::
* 多媒体服务::
* 國際化::
* 程式框架::
* 以 Tk 打造 GUI::
* 開發工具::
* 调试和分析::
* 軟體封裝與發布::
* Python运行时服务::
* 自定义 Python 解释器::
* 匯入模組::
* Python 语言服务::
* 杂项服务::
* Windows系统相关模块::
* Unix 专有服务::
* 被取代的模块::
* 未创建文档的模块::
* Security Considerations::

   ---------- Footnotes ----------

   (1) https://pypi.org


File: python.info,  Node: 簡介<6>,  Next: 內建函式,  Up: Python 標準函式庫 Standard Library

5.1 簡介
========

「Python 函式庫」包含了許多不同的部分。

函式庫中包括被視為程式語言「核心」部分的資料型態，像是數字 (number) 或是
串列 (list)。對於這些型別，Python 核心對這些字面值 (literal) 的形式做定
義，並對它們的語意制定了一些限制，但在此同時卻不把文字對應的語意完全定義
。（另一方面，Python 在語法面上有確實的定義，例如拼字或是運算元次序）

Python 函式庫也囊括了內建函數與例外處理——這些物件都可以不用透過 *note
import: ce7. 陳述式來引入 Python 程式中就能使用。函式庫中有部份是被
Python 核心所定義的，但在這裡僅解釋最核心的語意部分。

整個函式庫中包含了許多模組，有許多方法可以從函式庫中取用這些模組。有些模
組是以 C 語言撰寫並建置於 Python 編譯器之中，其他的是由 Python 撰寫並以
源碼的方式 (source form) 引入。有些模組提供的功能是專屬於 Python 的，像
是把 stack trace 印出來；有些則是針對特定作業系統，去試著存取特定硬體；
還有些提供對特定應用的功能與操作介面，像是 World Wide Web。模組的使用情
況會因機器與 Python 的版本而不同，部分模組是開放所有版本以及 Port 的
Python 來使用的，但有些會因系統支援或需求在某些版本或系統下無法使用，甚
至有些僅限在特定的設定環境下才能使用。

這個手冊會「深入淺出」地介紹 Python 函式庫。它會先介紹一些內建函式、資料
型態、和一些例外處理，再來一章章的主題式介紹相關模組。

這代表如果你從這個手冊的最開始讀起，並在感到無聊時跳到下一個章節，你仍然
可以得到一個對 Python 函式庫所支援的模組與其合理應用的概觀。當然，你`沒
有必要'像是在讀一本小說一樣讀這本手冊——你可以快速瀏覽目錄（在手冊的最前
頭）、或是你可以利用最後面的索引來查詢特定的函式或模組。最後，如果你享受
閱讀一些隨機的主題，你可以選擇一個隨機的數字並開始閱讀（見 *note random:
dc. 模組) 。不管你想要以什麼順序來閱讀這個手冊，*note 內建函式: cbe.會是
一個很好的入門，因為手冊中其他章節都預設你已經對這個章節有一定的熟悉程度
。

讓我們開始吧！

* Menu:

* 可用性之註釋::


File: python.info,  Node: 可用性之註釋,  Up: 簡介<6>

5.1.1 可用性之註釋
------------------

   * 如果出現「適用：Unix」註釋，則代表該函數普遍存在於 Unix 系統中，但
     這並不保證其存在於某特定作業系統。

   * 如果沒有分別註釋的話，有標明「適用：Unix」註釋的所有函式也都於
     macOS 上支援，因其建於 Unix 核心之上。


File: python.info,  Node: 內建函式,  Next: 內建常數,  Prev: 簡介<6>,  Up: Python 標準函式庫 Standard Library

5.2 內建函式
============

Python 直譯器有內建數十個函式，隨時都可以使用這些函式。以下按照英文字母
排序列出。

                                              內建函式
                                              
---------------------------------------------------------------------------------------------------------------------
                                                                                            
*note abs(): 13f3.      *note delattr(): 170e.*note hash(): aa3.     *note memoryview(): 170f.*note set(): 1710.
                                                                                            
                                                                                            
*note all(): e4a.       *note dict(): 1711.   *note help(): 175.     *note min(): 8f6.      *note setattr(): 1712.
                                                                                            
                                                                                            
*note any(): e49.       *note dir(): df9.     *note hex(): d2e.      *note next(): 775.     *note slice(): ec8.
                                                                                            
                                                                                            
*note ascii(): e11.     *note divmod(): 28d.  *note id(): e4b.       *note object(): 3d2.   *note sorted(): 546.
                                                                                            
                                                                                            
*note bin(): d08.       *note enumerate(): ea7.*note input(): d33.   *note oct(): d2d.      *note staticmethod(): 30a.
                                                                                            
                                                                                            
*note bool(): 2bd.      *note eval(): c61.    *note int(): 204.      *note open(): 16f.     *note str(): 1713.
                                                                                            
                                                                                            
*note breakpoint(): 40b.*note exec(): d0c.    *note isinstance(): 551.*note ord(): 1559.    *note sum(): 316.
                                                                                            
                                                                                            
*note bytearray(): 11f3.*note filter(): cf8.  *note issubclass(): 552.*note pow(): 2cf.     *note super(): 5dd.
                                                                                            
                                                                                            
*note bytes(): 11f2.    *note float(): 1fd.   *note iter(): ded.     *note print(): 971.    *note tuple(): 1714.
                                                                                            
                                                                                            
*note callable(): c16.  *note format(): 5d5.  *note len(): 28b.      *note property(): 308. *note type(): 6ff.
                                                                                            
                                                                                            
*note chr(): 155a.      *note frozenset(): 1715.*note list(): 1716.  *note range(): 1717.   *note vars(): 116d.
                                                                                            
                                                                                            
*note classmethod(): 309.*note getattr(): 54b.*note locals(): 556.   *note repr(): 8b9.     *note zip(): cfc.
                                                                                            
                                                                                            
*note compile(): 2e7.   *note globals(): f55. *note map(): cf7.      *note reversed(): 2c6. *note __import__(): 16b.
                                                                                            
                                                                                            
*note complex(): 2c1.   *note hasattr(): 54a. *note max(): 8f7.      *note round(): d35.
                                                                     

 -- 函式: abs (x)

     返回一个数的绝对值。 参数可以是整数、浮点数或任何实现了 *note
     __abs__(): 15bd. 的对象。 如果参数是一个复数，则返回它的模。

 -- 函式: all (iterable)

     如果 `iterable' 的所有元素均为真值（或可迭代对象为空）则返回 ‘True’
     。 等价于:

          def all(iterable):
              for element in iterable:
                  if not element:
                      return False
              return True

 -- 函式: any (iterable)

     如果 `iterable' 的任一元素为真值则返回 ‘True’。 如果可迭代对象为空
     ，返回 ‘False’。 等价于:

          def any(iterable):
              for element in iterable:
                  if element:
                      return True
              return False

 -- 函式: ascii (object)

     与 *note repr(): 8b9. 类似，返回一个包含对象的可打印表示形式的字符
     串，但是使用 ‘\x’、‘\u’ 和 ‘\U’ 对 *note repr(): 8b9. 返回的字符串
     中非 ASCII 编码的字符进行转义。 生成的字符串和 Python 2 的 *note
     repr(): 8b9. 返回的结果相似。

 -- 函式: bin (x)

     将一个整数转变为一个前缀为“0b”的二进制字符串。结果是一个合法的
     Python 表达式。如果 `x' 不是 Python 的 *note int: 204. 对象，那它需
     要定义 *note __index__(): 2c2. 方法返回一个整数。一些例子：

          >>> bin(3)
          '0b11'
          >>> bin(-10)
          '-0b1010'

     如果不一定需要前缀“0b”，还可以使用如下的方法。

          >>> format(14, '#b'), format(14, 'b')
          ('0b1110', '1110')
          >>> f'{14:#b}', f'{14:b}'
          ('0b1110', '1110')

     另见 *note format(): 5d5. 获取更多信息。

 -- 類別: bool ([x])

     返回一个布尔值，‘True’ 或者 ‘False’。 `x' 使用标准的 *note
     真值测试过程: 1718. 来转换。 如果 `x' 是假值或者被省略，返回
     ‘False’；其他情况返回 ‘True’。 *note bool: 2bd. 类是 *note int:
     204. 的子类（参见 *note 数字类型 — int, float, complex: 1353. ）。
     其他类不能继承自它。它只有 ‘False’ 和 ‘True’ 两个实例（参见 *note
     布尔值: 1719. ）。

     3.7 版更變: `x' 现在只能作为位置参数。

 -- 函式: breakpoint (*args, **kws)

     此函数会在调用时将你陷入调试器中。具体来说，它调用 *note
     sys.breakpointhook(): 423. ，直接传递 ‘args’ 和 ‘kws’ 。默认情况下
     ， ‘sys.breakpointhook()’ 调用 *note pdb.set_trace(): 4c8. 且没有参
     数。在这种情况下，它纯粹是一个便利函数，因此您不必显式导入 *note
     pdb: c9. 且键入尽可能少的代码即可进入调试器。但是， *note
     sys.breakpointhook(): 423. 可以设置为其他一些函数并被 *note
     breakpoint(): 40b. 自动调用，以允许进入你想用的调试器。

     引发一个 *note 审计事件: fa1. ‘builtins.breakpoint’ 并附带参数
     ‘breakpointhook’。

     3.7 版新加入.

 -- 類別: bytearray ([source[, encoding[, errors]]])

     返回一个新的 bytes 数组。 *note bytearray: 173. 类是一个可变序列，
     包含范围为 0 <= x < 256 的整数。它有可变序列大部分常见的方法，见
     *note 可变序列类型: 171a. 的描述；同时有 *note bytes: 172. 类型的大
     部分方法，参见 *note bytes 和 bytearray 操作: 171b.。

     可选形参 `source' 可以用不同的方式来初始化数组：

        * 如果是一个 `string'，您必须提供 `encoding' 参数（`errors' 参数
          仍是可选的）；*note bytearray(): 173. 会使用 *note
          str.encode(): 170. 方法来将 string 转变成 bytes。

        * 如果是一个 `integer'，会初始化大小为该数字的数组，并使用 null
          字节填充。

        * 如果是一个遵循 *note 缓冲区接口: 171c. 的对象，该对象的只读缓
          冲区将被用来初始化字节数组。

        * 如果是一个 `iterable' 可迭代对象，它的元素的范围必须是 ‘0 <= x
          < 256’ 的整数，它会被用作数组的初始内容。

     如果没有实参，则创建大小为 0 的数组。

     另见 *note 二进制序列类型 — bytes, bytearray, memoryview: 171d. 和
     *note bytearray 对象: 171e.。

 -- 類別: bytes ([source[, encoding[, errors]]])

     返回一个新的“bytes”对象， 是一个不可变序列，包含范围为 ‘0 <= x <
     256’ 的整数。*note bytes: 172. 是 *note bytearray: 173. 的不可变版
     本 - 它有其中不改变序列的方法和相同的索引、切片操作。

     因此，构造函数的实参和 *note bytearray(): 173. 相同。

     字节对象还可以用字面值创建，参见 *note 字符串与字节串字面值: 1514.。

     另见 *note 二进制序列类型 — bytes, bytearray, memoryview: 171d.，
     *note bytes 对象: 171f. 和 *note bytes 和 bytearray 操作: 171b.。

 -- 函式: callable (object)

     如果参数 `object' 是可调用的就返回 *note True: 593.，否则返回 *note
     False: 48e.。 如果返回 ‘True’，调用仍可能失败，但如果返回 ‘False’，
     则调用 `object' 将肯定不会成功。 请注意类是可调用的（调用类将返回一
     个新的实例）；如果实例所属的类有 *note __call__(): 1560. 则它就是可
     调用的。

     3.2 版新加入: 这个函数一开始在 Python 3.0 被移除了，但在 Python 3.2
     被重新加入。

 -- 函式: chr (i)

     返回 Unicode 码位为整数 `i' 的字符的字符串格式。例如，‘chr(97)’ 返
     回字符串 ‘'a'’，‘chr(8364)’ 返回字符串 ‘'€'’。这是 *note ord():
     1559. 的逆函数。

     实参的合法范围是 0 到 1,114,111（16 进制表示是 0x10FFFF）。如果 `i'
     超过这个范围，会触发 *note ValueError: 16d. 异常。

 -- 函式: @classmethod

     把一个方法封装成类方法。

     一个类方法把类自己作为第一个实参，就像一个实例方法把实例自己作为第
     一个实参。请用以下习惯来声明类方法:

          class C:
              @classmethod
              def f(cls, arg1, arg2, ...): ...

     ‘@classmethod’ 这样的形式称为函数的 *note decorator: 174. – 详情参
     阅 *note 函数定义: 1390.。

     类方法的调用可以在类上进行 (例如 ‘C.f()’) 也可以在实例上进行 (例如
     ‘C().f()’)。 其所属类以外的类实例会被忽略。 如果类方法在其所属类的
     派生类上调用，则该派生类对象会被作为隐含的第一个参数被传入。

     类方法与 C++ 或 Java 中的静态方法不同。 如果你需要后者，请参阅本节
     中的 *note staticmethod(): 30a.。 有关类方法的更多信息，请参阅
     *note 标准类型层级结构: 1553.。

     3.9 版更變: 类方法现在可以包装其他 *note 描述器: 1579. 例如 *note
     property(): 308.。

 -- 函式: compile (source, filename, mode, flags=0, dont_inherit=False,
          optimize=-1)

     将 `source' 编译成代码或 AST 对象。代码对象可以被 *note exec():
     d0c. 或 *note eval(): c61. 执行。`source' 可以是常规的字符串、字节
     字符串，或者 AST 对象。参见 *note ast: 7. 模块的文档了解如何使用
     AST 对象。

     `filename' 实参需要是代码读取的文件名；如果代码不需要从文件中读取，
     可以传入一些可辨识的值（经常会使用 ‘'<string>'’）。

     `mode' 实参指定了编译代码必须用的模式。如果 `source' 是语句序列，可
     以是 ‘'exec'’；如果是单一表达式，可以是 ‘'eval'’；如果是单个交互式
     语句，可以是 ‘'single'’。（在最后一种情况下，如果表达式执行结果不是
     ‘None’ 将会被打印出来。）

     可选参数 `flags' 和 `dont_inherit' 控制应当激活哪个 *note
     编译器选项: 1720. 以及应当允许哪个 *note future 特性: 16c4.。 如果
     两者都未提供 (或都为零) 则代码会应用与调用 *note compile(): 2e7. 的
     代码相同的旗标来编译。 如果给出了 `flags' 参数而未给出
     `dont_inherit' (或者为零) 则会在无论如何都将被使用的旗标之外还会额
     外使用 `flags' 参数所指定的编译器选项和 future 语句。 如果
     `dont_inherit' 为非零整数，则只使用 `flags' 参数 – 外围代码中的旗标
     (future 特性和编译器选项) 会被忽略。

     编译器选项和 future 语句是由比特位来指明的。 比特位可以通过一起按位
     OR 来指明多个选项。 指明特定 future 特性所需的比特位可以在 *note
     __future__: 0. 模块的 ‘_Feature’ 实例的 ‘compiler_flag’ 属性中找到
     。 *note 编译器旗标: 1720. 可以在 *note ast: 7. 模块中查找带有
     ‘PyCF_’ 前缀的名称。

     `optimize' 实参指定编译器的优化级别；默认值 ‘-1’ 选择与解释器的
     *note -O: 77e. 选项相同的优化级别。显式级别为 ‘0’ （没有优化；
     ‘__debug__’ 为真）、‘1’ （断言被删除， ‘__debug__’ 为假）或 ‘2’ （
     文档字符串也被删除）。

     如果编译的源码不合法，此函数会触发 *note SyntaxError: 559. 异常；如
     果源码包含 null 字节，则会触发 *note ValueError: 16d. 异常。

     如果您想分析 Python 代码的 AST 表示，请参阅 *note ast.parse():
     2d6.。

     引发一个 *note 审计事件: fa1. ‘compile’ 附带参数 ‘source’,
     ‘filename’。

          備註: 在 ‘'single'’ 或 ‘'eval'’ 模式编译多行代码字符串时，输入
          必须以至少一个换行符结尾。 这使 *note code: 1a. 模块更容易检测
          语句的完整性。

          警告: 在将足够大或者足够复杂的字符串编译成 AST 对象时，Python
          解释器有可能因为 Python AST 编译器的栈深度限制而崩溃。

     3.2 版更變: 允许使用 Windows 和 Mac 的换行符。在 ‘'exec'’ 模式不再
     需要以换行符结尾。增加了 `optimize' 形参。

     3.5 版更變: 之前 `source' 中包含 null 字节的话会触发 *note
     TypeError: 1fe. 异常。

     3.8 版新加入: ‘ast.PyCF_ALLOW_TOP_LEVEL_AWAIT’ 现在可在旗标中传入以
     启用对最高层级 ‘await’, ‘async for’ 和 ‘async with’ 的支持。

 -- 類別: complex ([real[, imag]])

     返回值为 `real' + `imag'*1j 的复数，或将字符串或数字转换为复数。如
     果第一个形参是字符串，则它被解释为一个复数，并且函数调用时必须没有
     第二个形参。第二个形参不能是字符串。每个实参都可以是任意的数值类型
     （包括复数）。如果省略了 `imag'，则默认值为零，构造函数会像 *note
     int: 204. 和 *note float: 1fd. 一样进行数值转换。如果两个实参都省略
     ，则返回 ‘0j’。

     对于一个普通 Python 对象 ‘x’，‘complex(x)’ 会委托给
     ‘x.__complex__()’。 如果 ‘__complex__()’ 未定义则将回退至 *note
     __float__(): 2c4.。 如果 ‘__float__()’ 未定义则将回退至 *note
     __index__(): 2c2.。

          備註: 当从字符串转换时，字符串在 ‘+’ 或 ‘-’ 的周围必须不能有空
          格。例如 ‘complex('1+2j')’ 是合法的，但 ‘complex('1 + 2j')’ 会
          触发 *note ValueError: 16d. 异常。

     *note 数字类型 — int, float, complex: 1353. 描述了复数类型。

     3.6 版更變: 您可以使用下划线将代码文字中的数字进行分组。

     3.8 版更變: 如果 *note __complex__(): 2c5. 和 *note __float__():
     2c4. 未定义则回退至 *note __index__(): 2c2.。

 -- 函式: delattr (object, name)

     *note setattr(): 1712. 相关的函数。实参是一个对象和一个字符串。该字
     符串必须是对象的某个属性。如果对象允许，该函数将删除指定的属性。例
     如 ‘delattr(x, 'foobar')’ 等价于 ‘del x.foobar’ 。

 -- 類別: dict (**kwarg)

 -- 類別: dict (mapping, **kwarg)

 -- 類別: dict (iterable, **kwarg)

     创建一个新的字典。*note dict: 164. 对象是一个字典类。参见 *note
     dict: 164. 和 *note 映射类型 — dict: 40e. 了解这个类。

     其他容器类型，请参见内置的 *note list: 1f8.、*note set: 1f6. 和
     *note tuple: 1a2. 类，以及 *note collections: 1d. 模块。

 -- 函式: dir ([object])

     如果没有实参，则返回当前本地作用域中的名称列表。如果有实参，它会尝
     试返回该对象的有效属性列表。

     如果对象有一个名为 *note __dir__(): 42b. 的方法，那么该方法将被调用
     ，并且必须返回一个属性列表。这允许实现自定义 *note __getattr__():
     42a. 或 *note __getattribute__(): 549. 函数的对象能够自定义 *note
     dir(): df9. 来报告它们的属性。

     如果对象不提供 *note __dir__(): 42b.，这个函数会尝试从对象已定义的
     *note __dict__: 5f5. 属性和类型对象收集信息。结果列表并不总是完整的
     ，如果对象有自定义 *note __getattr__(): 42a.，那结果可能不准确。

     默认的 *note dir(): df9. 机制对不同类型的对象行为不同，它会试图返回
     最相关而不是最全的信息：

        * 如果对象是模块对象，则列表包含模块的属性名称。

        * 如果对象是类型或类对象，则列表包含它们的属性名称，并且递归查找
          所有基类的属性。

        * 否则，列表包含对象的属性名称，它的类属性名称，并且递归查找它的
          类的所有基类的属性。

     返回的列表按字母表排序。例如：

          >>> 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']

          備註: 因为 *note dir(): df9. 主要是为了便于在交互式时使用，所
          以它会试图返回人们感兴趣的名字集合，而不是试图保证结果的严格性
          或一致性，它具体的行为也可能在不同版本之间改变。例如，当实参是
          一个类时，metaclass 的属性不包含在结果列表中。

 -- 函式: divmod (a, b)

     它将两个（非复数）数字作为实参，并在执行整数除法时返回一对商和余数
     。对于混合操作数类型，适用双目算术运算符的规则。对于整数，结果和
     ‘(a // b, a % b)’ 一致。对于浮点数，结果是 ‘(q, a % b)’ ，`q' 通常
     是 ‘math.floor(a / b)’ 但可能会比 1 小。在任何情况下， ‘q * b + a %
     b’ 和 `a' 基本相等；如果 ‘a % b’ 非零，它的符号和 `b' 一样，并且 ‘0
     <= abs(a % b) < abs(b)’ 。

 -- 函式: enumerate (iterable, start=0)

     返回一个枚举对象。`iterable' 必须是一个序列，或 *note iterator:
     1171.，或其他支持迭代的对象。 *note enumerate(): ea7. 返回的迭代器
     的 *note __next__(): d2c. 方法返回一个元组，里面包含一个计数值（从
     `start' 开始，默认为 0）和通过迭代 `iterable' 获得的值。

          >>> 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')]

     等价于:

          def enumerate(sequence, start=0):
              n = start
              for elem in sequence:
                  yield n, elem
                  n += 1

 -- 函式: eval (expression[, globals[, locals]])

     实参是一个字符串，以及可选的 globals 和 locals。`globals' 实参必须
     是一个字典。`locals' 可以是任何映射对象。

     `expression' 参数会作为一个 Python 表达式（从技术上说是一个条件列表
     ）被解析并求值，并使用 `globals' 和 `locals' 字典作为全局和局部命名
     空间。 如果 `globals' 字典存在且不包含以 ‘__builtins__’ 为键的值，
     则会在解析 `expression' 之前插入以此为键的对内置模块 *note
     builtins: 12. 的引用。 这意味着 `expression' 通常具有对标准 *note
     builtins: 12. 模块的完全访问权限且受限的环境会被传播。 如果省略
     `locals' 字典则其默认值为 `globals' 字典。 如果两个字典同时省略，则
     表达式执行时会使用 *note eval(): c61. 被调用的环境中的 `globals' 和
     `locals'。 请注意，`eval()' 并没有对外围环境下的 (非局部) *note
     嵌套作用域: 1721. 的访问权限。

     返回值就是表达式的求值结果。 语法错误将作为异常被报告。 例如：

          >>> x = 1
          >>> eval('x+1')
          2

     这个函数也可以用来执行任何代码对象（如 *note compile(): 2e7. 创建的
     ）。这种情况下，参数是代码对象，而不是字符串。如果编译该对象时的
     `mode' 实参是 ‘'exec'’ 那么 *note eval(): c61. 返回值为 ‘None’ 。

     提示： *note exec(): d0c. 函数支持动态执行语句。 *note globals():
     f55. 和 *note locals(): 556. 函数各自返回当前的全局和本地字典，因此
     您可以将它们传递给 *note eval(): c61. 或 *note exec(): d0c. 来使用
     。

     另外可以参阅 *note ast.literal_eval(): 59f.，该函数可以安全执行仅包
     含文字的表达式字符串。

     引发一个 *note 审计事件: fa1. ‘exec’ 附带参数 ‘code_object’。

 -- 函式: exec (object[, globals[, locals]])

     This function supports dynamic execution of Python code.  `object'
     must be either a string or a code object.  If it is a string, the
     string is parsed as a suite of Python statements which is then
     executed (unless a syntax error occurs).  (1) If it is a code
     object, it is simply executed.  In all cases, the code that’s
     executed is expected to be valid as file input (see the section
     *note 文件输入: 16fb. in the Reference Manual).  Be aware that the
     *note nonlocal: d07, *note yield: 2c7, and *note return: 2c8.
     statements may not be used outside of function definitions even
     within the context of code passed to the *note exec(): d0c.
     function.  The return value is ‘None’.

     无论哪种情况，如果省略了可选项，代码将在当前作用域内执行。 如果只提
     供了 `globals'，则它必须是一个字典（不能是字典的子类），该字典将同
     时被用于全局和局部变量。 如果同时提供了 `globals' 和 `locals'，它们
     会分别被用于全局和局部变量。 如果提供了 `locals'，则它可以是任何映
     射对象。 请记住在模块层级上，globals 和 locals 是同一个字典。 如果
     exec 得到两个单独对象作为 `globals' 和 `locals'，则代码将如同嵌入类
     定义的情况一样执行。

     如果 `globals' 字典不包含 ‘__builtins__’ 键值，则将为该键插入对内建
     *note builtins: 12. 模块字典的引用。因此，在将执行的代码传递给
     *note exec(): d0c. 之前，可以通过将自己的 ‘__builtins__’ 字典插入到
     `globals' 中来控制可以使用哪些内置代码。

     引发一个 *note 审计事件: fa1. ‘exec’ 附带参数 ‘code_object’。

          備註: 内置 *note globals(): f55. 和 *note locals(): 556. 函数
          各自返回当前的全局和本地字典，因此可以将它们传递给 *note
          exec(): d0c. 的第二个和第三个实参。

          備註: 默认情况下，`locals' 的行为如下面 *note locals(): 556. 函
          数描述的一样：不要试图改变默认的 `locals' 字典。如果您想在
          *note exec(): d0c. 函数返回时知道代码对 `locals' 的变动，请明
          确地传递 `locals' 字典。

 -- 函式: filter (function, iterable)

     用 `iterable' 中函数 `function' 返回真的那些元素，构建一个新的迭代
     器。`iterable' 可以是一个序列，一个支持迭代的容器，或一个迭代器。如
     果 `function' 是 ‘None’ ，则会假设它是一个身份函数，即 `iterable' 中
     所有返回假的元素会被移除。

     请注意， ‘filter(function, iterable)’ 相当于一个生成器表达式，当
     function 不是 ‘None’ 的时候为 ‘(item for item in iterable if
     function(item))’；function 是 ‘None’ 的时候为 ‘(item for item in
     iterable if item)’ 。

     请参阅 *note itertools.filterfalse(): 1722. 了解，只有 `function' 返
     回 false 时才选取 `iterable' 中元素的补充函数。

 -- 類別: float ([x])

     返回从数字或字符串 `x' 生成的浮点数。

     如果实参是字符串，则它必须是包含十进制数字的字符串，字符串前面可以
     有符号，之前也可以有空格。可选的符号有 ‘'+'’ 和 ‘'-'’ ； ‘'+'’ 对创
     建的值没有影响。实参也可以是 NaN（非数字）、正负无穷大的字符串。确
     切地说，除去首尾的空格后，输入必须遵循以下语法：

          sign           ::= "+" | "-"
          infinity       ::= "Infinity" | "inf"
          nan            ::= "nan"
          numeric_value  ::= floatnumber | infinity | nan
          numeric_string ::= [sign] numeric_value

     这里， ‘floatnumber’ 是 Python 浮点数的字符串形式，详见 *note
     浮点数字面值: 153e.。字母大小写都可以，例如，“inf”、“Inf”、
     “INFINITY”、“iNfINity” 都可以表示正无穷大。

     另一方面，如果实参是整数或浮点数，则返回具有相同值（在 Python 浮点
     精度范围内）的浮点数。如果实参在 Python 浮点精度范围外，则会触发
     *note OverflowError: a41.。

     对于一个普通 Python 对象 ‘x’，‘float(x)’ 会委托给 ‘x.__float__()’。
     如果 ‘__float__()’ 未定义则将回退至 *note __index__(): 2c2.。

     如果没有实参，则返回 ‘0.0’ 。

     例如:

          >>> float('+1.23')
          1.23
          >>> float('   -12345\n')
          -12345.0
          >>> float('1e-003')
          0.001
          >>> float('+1E6')
          1000000.0
          >>> float('-Infinity')
          -inf

     *note 数字类型 — int, float, complex: 1353. 描述了浮点类型。

     3.6 版更變: 您可以使用下划线将代码文字中的数字进行分组。

     3.7 版更變: `x' 现在只能作为位置参数。

     3.8 版更變: 如果 *note __float__(): 2c4. 未定义则回退至 *note
     __index__(): 2c2.。

 -- 函式: format (value[, format_spec])

     将 `value' 转换为 `format_spec' 控制的“格式化”表示。`format_spec' 的
     解释取决于 `value' 实参的类型，但是大多数内置类型使用标准格式化语法
     ：*note 格式规格迷你语言: 5d8.。

     默认的 `format_spec' 是一个空字符串，它通常给出与调用 *note
     str(value): 205. 相同的结果。

     调用 ‘format(value, format_spec)’ 会转换成
     ‘type(value).__format__(value, format_spec)’ ，所以实例字典中的
     *note __format__(): a2f. 方法将不会调用。如果方法搜索回退到 *note
     object: 3d2. 类但 `format_spec' 不为空，或者如果 `format_spec' 或返
     回值不是字符串，则会触发 *note TypeError: 1fe. 异常。

     3.4 版更變: 当 `format_spec' 不是空字符串时，
     ‘object().__format__(format_spec)’ 会触发 *note TypeError: 1fe.。

 -- 類別: frozenset ([iterable])

     返回一个新的 *note frozenset: 1f7. 对象，它包含可选参数 `iterable'
     中的元素。 ‘frozenset’ 是一个内置的类。有关此类的文档，请参阅 *note
     frozenset: 1f7. 和 *note 集合类型 — set, frozenset: 1728.。

     请参阅内建的 *note set: 1f6.、*note list: 1f8.、*note tuple: 1a2. 和
     *note dict: 164. 类，以及 *note collections: 1d. 模块来了解其它的容
     器。

 -- 函式: getattr (object, name[, default])

     返回对象命名属性的值。`name' 必须是字符串。如果该字符串是对象的属性
     之一，则返回该属性的值。例如， ‘getattr(x, 'foobar')’ 等同于
     ‘x.foobar’。如果指定的属性不存在，且提供了 `default' 值，则返回它，
     否则触发 *note AttributeError: 4a1.。

          備註: 由于 *note 私有名称混合: 1621. 发生在编译时，因此必须 手
          动混合私有属性（以两个下划线打头的属性）名称以使使用 *note
          getattr(): 54b. 来提取它。

 -- 函式: globals ()

     Return the dictionary implementing the current module namespace.
     For code within functions, this is set when the function is defined
     and remains the same regardless of where the function is called.

 -- 函式: hasattr (object, name)

     该实参是一个对象和一个字符串。如果字符串是对象的属性之一的名称，则
     返回 ‘True’，否则返回 ‘False’。（此功能是通过调用 ‘getattr(object,
     name)’ 看是否有 *note AttributeError: 4a1. 异常来实现的。）

 -- 函式: hash (object)

     返回该对象的哈希值（如果它有的话）。哈希值是整数。它们在字典查找元
     素时用来快速比较字典的键。相同大小的数字变量有相同的哈希值（即使它
     们类型不同，如 1 和 1.0）。

          備註: 如果对象实现了自己的 *note __hash__(): 44c. 方法，请注意
          ，*note hash(): aa3. 根据机器的字长来截断返回值。另请参阅
          *note __hash__(): 44c.。

 -- 函式: help ([object])

     启动内置的帮助系统（此函数主要在交互式中使用）。如果没有实参，解释
     器控制台里会启动交互式帮助系统。如果实参是一个字符串，则在模块、函
     数、类、方法、关键字或文档主题中搜索该字符串，并在控制台上打印帮助
     信息。如果实参是其他任意对象，则会生成该对象的帮助页。

     请注意如果在函数的形参列表中出现了斜杠 (/)，则它在发起调用 *note
     help(): 175. 的时候意味着斜杠之前的均为仅限位置形参。 更多相关信息
     ，请参阅 *note 有关仅限位置形参的 FAQ 条目: 1729.。

     该函数通过 *note site: eb. 模块加入到内置命名空间。

     3.4 版更變: *note pydoc: d9. 和 *note inspect: a0. 的变更使得可调用
     对象的签名信息更加全面和一致。

 -- 函式: hex (x)

     将整数转换为以“0x”为前缀的小写十六进制字符串。如果 `x' 不是 Python
     *note int: 204. 对象，则必须定义返回整数的 *note __index__(): 2c2.
     方法。一些例子：

          >>> hex(255)
          '0xff'
          >>> hex(-42)
          '-0x2a'

     如果要将整数转换为大写或小写的十六进制字符串，并可选择有无“0x”前缀
     ，则可以使用如下方法：

          >>> '%#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')

     另见 *note format(): 5d5. 获取更多信息。

     另请参阅 *note int(): 204. 将十六进制字符串转换为以 16 为基数的整数
     。

          備註: 如果要获取浮点数的十六进制字符串形式，请使用 *note
          float.hex(): 1458. 方法。

 -- 函式: id (object)

     返回对象的“标识值”。该值是一个整数，在此对象的生命周期中保证是唯一
     且恒定的。两个生命期不重叠的对象可能具有相同的 *note id(): e4b. 值
     。

     `CPython implementation detail:' This is the address of the object
     in memory.

     引发一个 *note 审计事件: fa1. ‘builtins.id’，附带参数 ‘id’。

 -- 函式: input ([prompt])

     如果存在 `prompt' 实参，则将其写入标准输出，末尾不带换行符。接下来
     ，该函数从输入中读取一行，将其转换为字符串（除了末尾的换行符）并返
     回。当读取到 EOF 时，则触发 *note EOFError: d34.。例如:

          >>> s = input('--> ')
          --> Monty Python's Flying Circus
          >>> s
          "Monty Python's Flying Circus"

     如果加载了 *note readline: de. 模块，*note input(): d33. 将使用它来
     提供复杂的行编辑和历史记录功能。

     引发一个 *note 审计事件: fa1. ‘builtins.input’ 附带参数 ‘prompt’。

     在成功读取输入之后引发一个审计事件 ‘builtins.input/result’ 附带结果
     。

 -- 類別: int ([x])

 -- 類別: int (x, base=10)

     返回一个基于数字或字符串 `x' 构造的整数对象，或者在未给出参数时返回
     ‘0’。 如果 `x' 定义了 *note __int__(): 2c3.，‘int(x)’ 将返回
     ‘x.__int__()’。 如果 `x' 定义了 *note __index__(): 2c2.，它将返回
     ‘x.__index__()’。 如果 `x' 定义了 *note __trunc__(): 15c1.，它将返
     回 ‘x.__trunc__()’。 对于浮点数，它将向零舍入。

     如果 `x' 不是数字，或者有 `base' 参数，`x' 必须是字符串、*note
     bytes: 172.、表示进制为 `base' 的 *note 整数字面值: 1533. 的 *note
     bytearray: 173. 实例。该文字前可以有 ‘+’ 或 ‘-’ （中间不能有空格）
     ，前后可以有空格。一个进制为 n 的数字包含 0 到 n-1 的数，其中 ‘a’ 到
     ‘z’ （或 ‘A’ 到 ‘Z’ ）表示 10 到 35。默认的 `base' 为 10 ，允许的进
     制有 0、2-36。2、8、16 进制的数字可以在代码中用 ‘0b’/‘0B’ 、
     ‘0o’/‘0O’ 、 ‘0x’/‘0X’ 前缀来表示。进制为 0 将安照代码的字面量来精
     确解释，最后的结果会是 2、8、10、16 进制中的一个。所以 ‘int('010',
     0)’ 是非法的，但 ‘int('010')’ 和 ‘int('010', 8)’ 是合法的。

     整数类型定义请参阅 *note 数字类型 — int, float, complex: 1353. 。

     3.4 版更變: 如果 `base' 不是 *note int: 204. 的实例，但 `base' 对象
     有 *note base.__index__: 2c2. 方法，则会调用该方法来获取进制数。以
     前的版本使用 *note base.__int__: 2c3. 而不是 *note base.__index__:
     2c2.。

     3.6 版更變: 您可以使用下划线将代码文字中的数字进行分组。

     3.7 版更變: `x' 现在只能作为位置参数。

     3.8 版更變: 如果 *note __int__(): 2c3. 未定义则回退至 *note
     __index__(): 2c2.。

 -- 函式: isinstance (object, classinfo)

     如果参数 `object' 是参数 `classinfo' 的实例或者是其 (直接、间接或
     *note 虚拟: c05.) 子类则返回 ‘True’。 如果 `object' 不是给定类型的
     对象，函数将总是返回 ‘False’。 如果 `classinfo' 是类型对象元组（或
     由其他此类元组递归组成的元组），那么如果 `object' 是其中任何一个类
     型的实例就返回 ‘True’。 如果 `classinfo' 既不是类型，也不是类型元组
     或类型元组的元组，则将引发 *note TypeError: 1fe. 异常。

 -- 函式: issubclass (class, classinfo)

     Return ‘True’ if `class' is a subclass (direct, indirect or *note
     virtual: c05.) of `classinfo'.  A class is considered a subclass of
     itself.  `classinfo' may be a tuple of class objects, in which case
     return ‘True’ if `class' is a subclass of any entry in `classinfo'.
     In any other case, a *note TypeError: 1fe. exception is raised.

 -- 函式: iter (object[, sentinel])

     返回一个 *note iterator: 1171. 对象。根据是否存在第二个实参，第一个
     实参的解释是非常不同的。如果没有第二个实参，`object' 必须是支持迭代
     协议（有 *note __iter__(): 608. 方法）的集合对象，或必须支持序列协
     议（有 *note __getitem__(): 3a5. 方法，且数字参数从 ‘0’ 开始）。如
     果它不支持这些协议，会触发 *note TypeError: 1fe.。如果有第二个实参
     `sentinel'，那么 `object' 必须是可调用的对象。这种情况下生成的迭代
     器，每次迭代调用它的 *note __next__(): d2c. 方法时都会不带实参地调
     用 `object'；如果返回的结果是 `sentinel' 则触发 *note
     StopIteration: 581.，否则返回调用结果。

     另请参阅 *note 迭代器类型: 159a.。

     适合 *note iter(): ded. 的第二种形式的应用之一是构建块读取器。 例如
     ，从二进制数据库文件中读取固定宽度的块，直至到达文件的末尾:

          from functools import partial
          with open('mydata.db', 'rb') as f:
              for block in iter(partial(f.read, 64), b''):
                  process_block(block)

 -- 函式: len (s)

     返回对象的长度（元素个数）。实参可以是序列（如 string、bytes、
     tuple、list 或 range 等）或集合（如 dictionary、set 或 frozen set 等
     ）。

     `CPython implementation detail:' ‘len’ 对于大于 *note sys.maxsize:
     c15. 的长度如 *note range(2 ** 100): 1f5. 会引发 *note
     OverflowError: a41.。

 -- 類別: list ([iterable])

     虽然被称为函数，*note list: 1f8. 实际上是一种可变序列类型，详情请参
     阅 *note List（串列）: 172a. 和 *note 序列类型 — list, tuple,
     range: 13a4.。

 -- 函式: locals ()

     更新并返回表示当前本地符号表的字典。 在函数代码块但不是类代码块中调
     用 *note locals(): 556. 时将返回自由变量。 请注意在模块层级上，
     *note locals(): 556. 和 *note globals(): f55. 是同一个字典。

          備註: 不要更改此字典的内容；更改不会影响解释器使用的局部变量或
          自由变量的值。

 -- 函式: map (function, iterable, ...)

     返回一个将 `function' 应用于 `iterable' 中每一项并输出其结果的迭代
     器。 如果传入了额外的 `iterable' 参数，`function' 必须接受相同个数
     的实参并被应用于从所有可迭代对象中并行获取的项。 当有多个可迭代对象
     时，最短的可迭代对象耗尽则整个迭代就将结束。 对于函数的输入已经是参
     数元组的情况，请参阅 *note itertools.starmap(): b05.。

 -- 函式: max (iterable, *[, key, default])

 -- 函式: max (arg1, arg2, *args[, key])

     返回可迭代对象中最大的元素，或者返回两个及以上实参中最大的。

     如果只提供了一个位置参数，它必须是非空 *note iterable: c7c.，返回可
     迭代对象中最大的元素；如果提供了两个及以上的位置参数，则返回最大的
     位置参数。

     有两个可选只能用关键字的实参。`key' 实参指定排序函数用的参数，如传
     给 *note list.sort(): 547. 的。`default' 实参是当可迭代对象为空时返
     回的值。如果可迭代对象为空，并且没有给 `default' ，则会触发 *note
     ValueError: 16d.。

     如果有多个最大元素，则此函数将返回第一个找到的。这和其他稳定排序工
     具如 ‘sorted(iterable, key=keyfunc, reverse=True)[0]’ 和
     ‘heapq.nlargest(1, iterable, key=keyfunc)’ 保持一致。

     3.4 版新加入: keyword-only 实参 `default' 。

     3.8 版更變: `key' 可以为 ‘None’。

 -- 類別: memoryview (object)

     返回由给定实参创建的“内存视图”对象。有关详细信息，请参阅 *note
     内存视图: 172b.。

 -- 函式: min (iterable, *[, key, default])

 -- 函式: min (arg1, arg2, *args[, key])

     返回可迭代对象中最小的元素，或者返回两个及以上实参中最小的。

     如果只提供了一个位置参数，它必须是 *note iterable: c7c.，返回可迭代
     对象中最小的元素；如果提供了两个及以上的位置参数，则返回最小的位置
     参数。

     有两个可选只能用关键字的实参。`key' 实参指定排序函数用的参数，如传
     给 *note list.sort(): 547. 的。`default' 实参是当可迭代对象为空时返
     回的值。如果可迭代对象为空，并且没有给 `default' ，则会触发 *note
     ValueError: 16d.。

     如果有多个最小元素，则此函数将返回第一个找到的。这和其他稳定排序工
     具如 ‘sorted(iterable, key=keyfunc)[0]’ 和 ‘heapq.nsmallest(1,
     iterable, key=keyfunc)’ 保持一致。

     3.4 版新加入: keyword-only 实参 `default' 。

     3.8 版更變: `key' 可以为 ‘None’。

 -- 函式: next (iterator[, default])

     通过调用 `iterator' 的 *note __next__(): d2c. 方法获取下一个元素。
     如果迭代器耗尽，则返回给定的 `default'，如果没有默认值则触发 *note
     StopIteration: 581.。

 -- 類別: object

     返回一个没有特征的新对象。*note object: 3d2. 是所有类的基类。它具有
     所有 Python 类实例的通用方法。这个函数不接受任何实参。

          備註: 由于 *note object: 3d2. 没有 *note __dict__: 5f5.，因此
          无法将任意属性赋给 *note object: 3d2. 的实例。

 -- 函式: oct (x)

     将一个整数转变为一个前缀为“0o”的八进制字符串。结果是一个合法的
     Python 表达式。如果 `x' 不是 Python 的 *note int: 204. 对象，那它需
     要定义 *note __index__(): 2c2. 方法返回一个整数。一些例子：

          >>> oct(8)
          '0o10'
          >>> oct(-56)
          '-0o70'

     如果要将整数转换为八进制字符串，并可选择有无“0o”前缀，则可以使用如
     下方法：

          >>> '%#o' % 10, '%o' % 10
          ('0o12', '12')
          >>> format(10, '#o'), format(10, 'o')
          ('0o12', '12')
          >>> f'{10:#o}', f'{10:o}'
          ('0o12', '12')

     另见 *note format(): 5d5. 获取更多信息。

 -- 函式: open (file, mode='r', buffering=-1, encoding=None,
          errors=None, newline=None, closefd=True, opener=None)

     打开 `file' 并返回对应的 *note file object: c14.。 如果该文件不能被
     打开，则引发 *note OSError: 304.。 请参阅 *note 讀寫檔案: 13d4. 获
     取此函数的更多用法示例。

     `file' 是一个 *note path-like object: 472.，表示将要打开的文件的路
     径（绝对路径或者当前工作目录的相对路径），也可以是要被封装的整数类
     型文件描述符。（如果是文件描述符，它会随着返回的 I/O 对象关闭而关闭
     ，除非 `closefd' 被设为 ‘False’ 。）

     `mode' 是一个可选字符串，用于指定打开文件的模式。默认值是 ‘'r'’ ，
     这意味着它以文本模式打开并读取。其他常见模式有：写入 ‘'w'’ （截断已
     经存在的文件）；排它性创建 ‘'x'’ ；追加写 ‘'a'’ （在 `一些' Unix 系
     统上，无论当前的文件指针在什么位置，`所有' 写入都会追加到文件末尾）
     。在文本模式，如果 `encoding' 没有指定，则根据平台来决定使用的编码
     ：使用 ‘locale.getpreferredencoding(False)’ 来获取本地编码。（要读
     取和写入原始字节，请使用二进制模式并不要指定 `encoding'。）可用的模
     式有：

     字符          意义
                   
     ----------------------------------------------------------------------------------
                   
     ‘'r'’         读取（默认）
                   
                   
     ‘'w'’         写入，并先截断文件
                   
                   
     ‘'x'’         排它性创建，如果文件已存在则失败
                   
                   
     ‘'a'’         写入，如果文件存在则在末尾追加
                   
                   
     ‘'b'’         二进制模式
                   
                   
     ‘'t'’         文本模式（默认）
                   
                   
     ‘'+'’         打开用于更新（读取与写入）
                   

     默认模式为 ‘'r'’ (打开用于读取文本，与 ‘'rt'’ 同义)。 模式 ‘'w+'’ 与
     ‘'w+b'’ 将打开文件并清空内容。 模式 ‘'r+'’ 与 ‘'r+b'’ 将打开文件并
     不清空内容。

     正如在 *note 總覽: 172d. 中提到的，Python区分二进制和文本I/O。以二
     进制模式打开的文件（包括 `mode' 参数中的 ‘'b'’ ）返回的内容为 *note
     bytes: 172. 对象，不进行任何解码。在文本模式下（默认情况下，或者在
     `mode' 参数中包含 ‘'t'’ ）时，文件内容返回为 *note str: 205. ，首先
     使用指定的 `encoding' （如果给定）或者使用平台默认的的字节编码解码
     。

     此外还允许使用一个模式字符 ‘'U'’，该字符已不再具有任何效果，并被视
     为已弃用。 之前它会在文本模式中启用 *note universal newlines: 6eb.，
     这在 Python 3.0 中成为默认行为。 请参阅 *note newline: 172e. 形参的
     文档了解更多细节。

          備註: Python不依赖于底层操作系统的文本文件概念;所有处理都由
          Python本身完成，因此与平台无关。

     `buffering' 是一个可选的整数，用于设置缓冲策略。传递0以切换缓冲关闭
     （仅允许在二进制模式下），1选择行缓冲（仅在文本模式下可用），并且
     >1的整数以指示固定大小的块缓冲区的大小（以字节为单位）。如果没有给
     出 `buffering' 参数，则默认缓冲策略的工作方式如下:

        * 二进制文件以固定大小的块进行缓冲；使用启发式方法选择缓冲区的大
          小，尝试确定底层设备的“块大小”或使用 *note
          io.DEFAULT_BUFFER_SIZE: 172f.。在许多系统上，缓冲区的长度通常
          为4096或8192字节。

        * “交互式”文本文件（ *note isatty(): 1730. 返回 ‘True’ 的文件）
          使用行缓冲。其他文本文件使用上述策略用于二进制文件。

     `encoding' 是用于解码或编码文件的编码的名称。这应该只在文本模式下使
     用。默认编码是依赖于平台的（不 管 *note
     locale.getpreferredencoding(): 4ab. 返回何值），但可以使用任何
     Python支持的 *note text encoding: 1731. 。有关支持的编码列表，请参
     阅 *note codecs: 1b. 模块。

     `errors' 是一个可选的字符串参数，用于指定如何处理编码和解码错误 - 这
     不能在二进制模式下使用。可以使用各种标准错误处理程序（列在 *note
     错误处理方案: 1493. ），但是使用 *note codecs.register_error():
     eb9. 注册的任何错误处理名称也是有效的。标准名称包括:

        * 如果存在编码错误，‘'strict'’ 会引发 *note ValueError: 16d. 异
          常。 默认值 ‘None’ 具有相同的效果。

        * ‘'ignore'’ 忽略错误。请注意，忽略编码错误可能会导致数据丢失。

        * ‘'replace'’ 会将替换标记（例如 ‘'?'’ ）插入有错误数据的地方。

        * ‘'surrogateescape'’ 将把任何不正确的字节表示为 U+DC80 至
          U+DCFF 范围内的下方替代码位。 当在写入数据时使用
          ‘surrogateescape’ 错误处理句柄时这些替代码位会被转回到相同的字
          节。 这适用于处理具有未知编码格式的文件。

        * 只有在写入文件时才支持 ‘'xmlcharrefreplace'’。编码不支持的字符
          将替换为相应的XML字符引用 ‘&#nnn;’。

        * ‘'backslashreplace'’ 用Python的反向转义序列替换格式错误的数据
          。

        * ‘'namereplace'’ （也只在编写时支持）用 ‘\N{...}’ 转义序列替换
          不支持的字符。

     `newline' 控制 *note universal newlines: 6eb. 模式如何生效（它仅适
     用于文本模式）。它可以是 ‘None’，‘''’，‘'\n'’，‘'\r'’ 和 ‘'\r\n'’。
     它的工作原理:

        * 从流中读取输入时，如果 `newline' 为 ‘None’，则启用通用换行模式
          。输入中的行可以以 ‘'\n'’，‘'\r'’ 或 ‘'\r\n'’ 结尾，这些行被翻
          译成 ‘'\n'’ 在返回呼叫者之前。如果它是 ‘''’，则启用通用换行模
          式，但行结尾将返回给调用者未翻译。如果它具有任何其他合法值，则
          输入行仅由给定字符串终止，并且行结尾将返回给未调用的调用者。

        * 将输出写入流时，如果 `newline' 为 ‘None’，则写入的任何 ‘'\n'’
          字符都将转换为系统默认行分隔符 *note os.linesep: 1732.。如果
          `newline' 是 ‘''’ 或 ‘'\n'’，则不进行翻译。如果 `newline' 是任
          何其他合法值，则写入的任何 ‘'\n'’ 字符将被转换为给定的字符串。

     如果 `closefd' 是 ‘False’ 并且给出了文件描述符而不是文件名，那么当
     文件关闭时，底层文件描述符将保持打开状态。如果给出文件名则
     `closefd' 必须为 ‘True’ （默认值），否则将引发错误。

     可以通过传递可调用的 `opener' 来使用自定义开启器。然后通过使用参数
     （ `file'，`flags' ）调用 `opener' 获得文件对象的基础文件描述符。
     `opener' 必须返回一个打开的文件描述符（使用 *note os.open: 758. as
     `opener' 时与传递 ‘None’ 的效果相同）。

     新创建的文件是 *note 不可继承的: 8e7.。

     下面的示例使用 *note os.open(): 758. 函数的 *note dir_fd: b0b. 的形
     参，从给定的目录中用相对路径打开文件:

          >>> 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

     *note open(): 16f. 函数所返回的 *note file object: c14. 类型取决于
     所用模式。 当使用 *note open(): 16f. 以文本模式 (‘'w'’, ‘'r'’,
     ‘'wt'’, ‘'rt'’ 等) 打开文件时，它将返回 *note io.TextIOBase: d01.
     (特别是 *note io.TextIOWrapper: 6ea.) 的一个子类。 当使用缓冲以二进
     制模式打开文件时，返回的类是 *note io.BufferedIOBase: 67f. 的一个子
     类。 具体的类会有多种：在只读的二进制模式下，它将返回 *note
     io.BufferedReader: c5b.；在写入二进制和追加二进制模式下，它将返回
     *note io.BufferedWriter: 1733.，而在读/写模式下，它将返回 *note
     io.BufferedRandom: 1734.。 当禁用缓冲时，则会返回原始流，即 *note
     io.RawIOBase: af1. 的一个子类 *note io.FileIO: d6c.。

     另请参阅文件操作模块，例如 *note fileinput: 7e.、*note io: a1. （声
     明了 *note open(): 16f.）、*note os: c4.、*note os.path: c5.、*note
     tempfile: 103. 和 *note shutil: e9.。

     引发一个 *note 审计事件: fa1. ‘open’ 附带参数 ‘file’, ‘mode’,
     ‘flags’。

     ‘mode’ 与 ‘flags’ 参数可以在原始调用的基础上被修改或传递。

          3.3 版更變:

             * 增加了 `opener' 形参。

             * 增加了 ‘'x'’ 模式。

             * 过去触发的 *note IOError: a73.，现在是 *note OSError:
               304. 的别名。

             * 如果文件已存在但使用了排它性创建模式（ ‘'x'’ ），现在会触
               发 *note FileExistsError: a39.。

          3.4 版更變:

             * 文件现在禁止继承。

     Deprecated since version 3.4, will be removed in version 3.10:
     ‘'U'’ 模式。

          3.5 版更變:

             * 如果系统调用被中断，但信号处理程序没有触发异常，此函数现
               在会重试系统调用，而不是触发 *note InterruptedError: 74c.
               异常（原因详见 PEP 475(2)）。

             * 增加了 ‘'namereplace'’ 错误处理接口。

          3.6 版更變:

             * 增加对实现了 *note os.PathLike: 5e5. 对象的支持。

             * 在 Windows 上，打开一个控制台缓冲区将返回 *note
               io.RawIOBase: af1. 的子类，而不是 *note io.FileIO: d6c.。

 -- 函式: ord (c)

     对表示单个 Unicode 字符的字符串，返回代表它 Unicode 码点的整数。例
     如 ‘ord('a')’ 返回整数 ‘97’， ‘ord('€')’ （欧元符号）返回 ‘8364’ 。
     这是 *note chr(): 155a. 的逆函数。

 -- 函式: pow (base, exp[, mod])

     返回 `base' 的 `exp' 次幂；如果 `mod' 存在，则返回 `base' 的 `exp'
     次幂对 `mod' 取余（比 ‘pow(base, exp) % mod’ 更高效）。 两参数形式
     ‘pow(base, exp)’ 等价于乘方运算符: ‘base**exp’。

     The arguments must have numeric types.  With mixed operand types,
     the coercion rules for binary arithmetic operators apply.  For
     *note int: 204. operands, the result has the same type as the
     operands (after coercion) unless the second argument is negative;
     in that case, all arguments are converted to float and a float
     result is delivered.  For example, ‘pow(10, 2)’ returns ‘100’, but
     ‘pow(10, -2)’ returns ‘0.01’.  For a negative base of type *note
     int: 204. or *note float: 1fd. and a non-integral exponent, a
     complex result is delivered.  For example, ‘pow(-9, 0.5)’ returns a
     value close to ‘3j’.

     对于 *note int: 204. 操作数 `base' 和 `exp'，如果给出 `mod'，则
     `mod' 必须为整数类型并且 `mod' 必须不为零。 如果给出 `mod' 并且
     `exp' 为负值，则 `base' 必须相对于 `mod' 不可整除。 在这种情况下，
     将会返回 ‘pow(inv_base, -exp, mod)’，其中 `inv_base' 为 `base' 的倒
     数对 `mod' 取余。

     下面的例子是 ‘38’ 的倒数对 ‘97’ 取余:

          >>> pow(38, -1, mod=97)
          23
          >>> 23 * 38 % 97 == 1
          True

     3.8 版更變: 对于 *note int: 204. 操作数，三参数形式的 ‘pow’ 现在允
     许第二个参数为负值，即可以计算倒数的余数。

     3.8 版更變: 允许关键字参数。 之前只支持位置参数。

 -- 函式: print (*objects, sep=' ', end='\n', file=sys.stdout,
          flush=False)

     将 `objects' 打印到 `file' 指定的文本流，以 `sep' 分隔并在末尾加上
     `end'。 `sep', `end', `file' 和 `flush' 如果存在，它们必须以关键字
     参数的形式给出。

     所有非关键字参数都会被转换为字符串，就像是执行了 *note str(): 205.
     一样，并会被写入到流，以 `sep' 且在末尾加上 `end'。 `sep' 和 `end'
     都必须为字符串；它们也可以为 ‘None’，这意味着使用默认值。 如果没有
     给出 `objects'，则 *note print(): 971. 将只写入 `end'。

     `file' 参数必须是一个具有 ‘write(string)’ 方法的对象；如果参数不存
     在或为 ‘None’，则将使用 *note sys.stdout: 41f.。 由于要打印的参数会
     被转换为文本字符串，因此 *note print(): 971. 不能用于二进制模式的文
     件对象。 对于这些对象，应改用 ‘file.write(...)’。

     输出是否被缓存通常决定于 `file'，但如果 `flush' 关键字参数为真值，
     流会被强制刷新。

     3.3 版更變: 增加了 `flush' 关键字参数。

 -- 類別: property (fget=None, fset=None, fdel=None, doc=None)

     返回 property 属性。

     `fget' 是获取属性值的函数。 `fset' 是用于设置属性值的函数。 `fdel'
     是用于删除属性值的函数。并且 `doc' 为属性对象创建文档字符串。

     一个典型的用法是定义一个托管属性 ‘x’:

          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.")

     如果 `c' 是 `C' 的实例，‘c.x’ 将调用getter，‘c.x = value’ 将调用
     setter， ‘del c.x’ 将调用deleter。

     如果给出，`doc' 将成为该 property 属性的文档字符串。 否则该
     property 将拷贝 `fget' 的文档字符串（如果存在）。 这令使用 *note
     property(): 308. 作为 *note decorator: 174. 来创建只读的特征属性可
     以很容易地实现:

          class Parrot:
              def __init__(self):
                  self._voltage = 100000

              @property
              def voltage(self):
                  """Get the current voltage."""
                  return self._voltage

     以上 ‘@property’ 装饰器会将 ‘voltage()’ 方法转化为一个具有相同名称
     的只读属性的 "getter"，并将 `voltage' 的文档字符串设置为 "Get the
     current voltage."

     特征属性对象具有 ‘getter’, ‘setter’ 以及 ‘deleter’ 方法，它们可用作
     装饰器来创建该特征属性的副本，并将相应的访问函数设为所装饰的函数。
     这最好是用一个例子来解释:

          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

     上述代码与第一个例子完全等价。 注意一定要给附加函数与原始的特征属性
     相同的名称 (在本例中为 ‘x’。)

     返回的特征属性对象同样具有与构造器参数相对应的属性 ‘fget’, ‘fset’ 和
     ‘fdel’。

     3.5 版更變: 特征属性对象的文档字符串现在是可写的。

 -- 類別: range (stop)

 -- 類別: range (start, stop[, step])

     虽然被称为函数，但 *note range: 1f5. 实际上是一个不可变的序列类型，
     参见在 *note range 对象: 1735. 与 *note 序列类型 — list, tuple,
     range: 13a4. 中的文档说明。

 -- 函式: repr (object)

     返回包含一个对象的可打印表示形式的字符串。 对于许多类型来说，该函数
     会尝试返回的字符串将会与该对象被传递给 *note eval(): c61. 时所生成
     的对象具有相同的值，在其他情况下表示形式会是一个括在尖括号中的字符
     串，其中包含对象类型的名称与通常包括对象名称和地址的附加信息。 类可
     以通过定义 *note __repr__(): 44a. 方法来控制此函数为它的实例所返回
     的内容。

 -- 函式: reversed (seq)

     返回一个反向的 *note iterator: 1171.。 `seq' 必须是一个具有 *note
     __reversed__(): 628. 方法的对象或者是支持该序列协议（具有从 ‘0’ 开
     始的整数类型参数的 *note __len__(): e90. 方法和 *note
     __getitem__(): 3a5. 方法）。

 -- 函式: round (number[, ndigits])

     返回 `number' 舍入到小数点后 `ndigits' 位精度的值。 如果 `ndigits'
     被省略或为 ‘None’，则返回最接近输入值的整数。

     对于支持 *note round(): d35. 的内置类型，值会被舍入到最接近的 10 的
     负 `ndigits' 次幂的倍数；如果与两个倍数的距离相等，则选择偶数 (因此
     ，‘round(0.5)’ 和 ‘round(-0.5)’ 均为 ‘0’ 而 ‘round(1.5)’ 为 ‘2’)。
     任何整数值都可作为有效的 `ndigits' (正数、零或负数)。 如果
     `ndigits' 被省略或为 ‘None’ 则返回值将为整数。 否则返回值与
     `number' 的类型相同。

     对于一般的 Python 对象 ‘number’, ‘round’ 将委托给
     ‘number.__round__’。

          備註: 对浮点数执行 *note round(): d35. 的行为可能会令人惊讶：
          例如，‘round(2.675, 2)’ 将给出 ‘2.67’ 而不是期望的 ‘2.68’。 这
          不算是程序错误：这一结果是由于大多数十进制小数实际上都不能以浮
          点数精确地表示。 请参阅 *note 浮點數運算：問題與限制: 1456. 了
          解更多信息。

 -- 類別: set ([iterable])

     返回一个新的 *note set: 1f6. 对象，可以选择带有从 `iterable' 获取的
     元素。 ‘set’ 是一个内置类型。 请查看 *note set: 1f6. 和 *note
     集合类型 — set, frozenset: 1728. 获取关于这个类的文档。

     有关其他容器请参看内置的 *note frozenset: 1f7, *note list: 1f8,
     *note tuple: 1a2. 和 *note dict: 164. 类，以及 *note collections:
     1d. 模块。

 -- 函式: setattr (object, name, value)

     此函数与 *note getattr(): 54b. 两相对应。 其参数为一个对象、一个字
     符串和一个任意值。 字符串指定一个现有属性或者新增属性。 函数会将值
     赋给该属性，只要对象允许这种操作。 例如，‘setattr(x, 'foobar',
     123)’ 等价于 ‘x.foobar = 123’。

          備註: 由于 *note 私有名称混合: 1621. 发生在编译时，因此必须手
          动混合私有属性（以两个下划线打头的属性）名称以便使用 *note
          setattr(): 1712. 来设置它。

 -- 類別: slice (stop)

 -- 類別: slice (start, stop[, step])

     Return a *note slice: 1736. object representing the set of indices
     specified by ‘range(start, stop, step)’.  The `start' and `step'
     arguments default to ‘None’.  Slice objects have read-only data
     attributes ‘start’, ‘stop’ and ‘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: ‘a[start:stop:step]’ or
     ‘a[start:stop, i]’.  See *note itertools.islice(): 4a8. for an
     alternate version that returns an iterator.

 -- 函式: sorted (iterable, /, *, key=None, reverse=False)

     根据 `iterable' 中的项返回一个新的已排序列表。

     有兩個選擇性參數，只能使用關鍵字參數指定。

     `key' 指定带有单个参数的函数，用于从 `iterable' 的每个元素中提取用
     于比较的键 (例如 ‘key=str.lower’)。 默认值为 ‘None’ (直接比较元素
     )。

     `reverse' 为一个布尔值。 如果设为 ‘True’，则每个列表元素将按反向顺
     序比较进行排序。

     使用 *note functools.cmp_to_key(): c28. 可将老式的 `cmp' 函数转换为
     `key' 函数。

     内置的 *note sorted(): 546. 确保是稳定的。 如果一个排序确保不会改变
     比较结果相等的元素的相对顺序就称其为稳定的 — 这有利于进行多重排序（
     例如先按部门、再按薪级排序）。

     The sort algorithm uses only ‘<’ comparisons between items.  While
     defining an *note __lt__(): cfe. method will suffice for sorting,
     PEP 8(3) recommends that all six *note rich comparisons: 167a. be
     implemented.  This will help avoid bugs when using the same data
     with other ordering tools such as *note max(): 8f7. that rely on a
     different underlying method.  Implementing all six comparisons also
     helps avoid confusion for mixed type comparisons which can call
     reflected the *note __gt__(): d69. method.

     有关排序示例和简要排序教程，请参阅 *note 如何排序: 1737. 。

 -- 函式: @staticmethod

     将方法转换为静态方法。

     静态方法不会接收隐式的第一个参数。要声明一个静态方法，请使用此语法

          class C:
              @staticmethod
              def f(arg1, arg2, ...): ...

     ‘@staticmethod’ 这样的形式称为函数的 *note decorator: 174. – 详情参
     阅 *note 函数定义: 1390.。

     静态方法的调用可以在类上进行 (例如 ‘C.f()’) 也可以在实例上进行 (例
     如 ‘C().f()’)。

     Python中的静态方法与Java或C ++中的静态方法类似。另请参阅 *note
     classmethod(): 309. ，用于创建备用类构造函数的变体。

     像所有装饰器一样，也可以像常规函数一样调用 ‘staticmethod’ ，并对其
     结果执行某些操作。比如某些情况下需要从类主体引用函数并且您希望避免
     自动转换为实例方法。对于这些情况，请使用此语法:

          class C:
              builtin_open = staticmethod(open)

     想了解更多有关静态方法的信息，请参阅 *note 标准类型层级结构: 1553.
     。

 -- 類別: str (object='')

 -- 類別: str (object=b'', encoding='utf-8', errors='strict')

     返回一个 *note str: 205. 版本的 `object' 。有关详细信息，请参阅
     *note str(): 205. 。

     ‘str’ 是内置字符串 *note class: fe8. 。更多关于字符串的信息查看
     *note 文本序列类型 — str: 1357.。

 -- 函式: sum (iterable, /, start=0)

     从 `start' 开始自左向右对 `iterable' 的项求和并返回总计值。
     `iterable' 的项通常为数字，而 start 值则不允许为字符串。

     对某些用例来说，存在 *note sum(): 316. 的更好替代。 拼接字符串序列
     的更好更快方式是调用 ‘''.join(sequence)’。 要以扩展精度对浮点值求和
     ，请参阅 *note math.fsum(): e04.。 要拼接一系列可迭代对象，请考虑使
     用 *note itertools.chain(): 1738.。

     3.8 版更變: `start' 形参可用关键字参数形式来指定。

 -- 函式: super ([type[, object-or-type]])

     返回一个代理对象，它会将方法调用委托给 `type' 的父类或兄弟类。 这对
     于访问已在类中被重载的继承方法很有用。

     `object-or-type' 确定用于搜索的 *note method resolution order:
     1739.。 搜索会从 `type' 之后的类开始。

     举例来说，如果 `object-or-type' 的 *note __mro__: 173a. 为 ‘D -> B
     -> C -> A -> object’ 并且 `type' 的值为 ‘B’，则 *note super(): 5dd.
     将会搜索 ‘C -> A -> object’。

     `object-or-type' 的 *note __mro__: 173a. 属性列出了 *note
     getattr(): 54b. 和 *note super(): 5dd. 所共同使用的方法解析搜索顺序
     。 该属性是动态的，可以在任何继承层级结构发生更新的时候被改变。

     如果省略第二个参数，则返回的超类对象是未绑定的。 如果第二个参数为一
     个对象，则 ‘isinstance(obj, type)’ 必须为真值。 如果第二个参数为一
     个类型，则 ‘issubclass(type2, type)’ 必须为真值（这适用于类方法）。

     `super' 有两个典型用例。 在具有单继承的类层级结构中，`super' 可用来
     引用父类而不必显式地指定它们的名称，从而令代码更易维护。 这种用法与
     其他编程语言中 `super' 的用法非常相似。

     第二个用例是在动态执行环境中支持协作多重继承。 此用例为 Python 所独
     有而不存在于静态编码语言或仅支持单继承的语言当中。 这使用实现“菱形
     图”成为可能，即有多个基类实现相同的方法。 好的设计强制要求这样的方
     法在每个情况下都具有相同的调用签名（因为调用顺序是在运行时确定的，
     也因为这个顺序要适应类层级结构的更改，还因为这个顺序可能包括在运行
     时之前未知的兄弟类）。

     对于以上两个用例，典型的超类调用看起来是这样的:

          class C(B):
              def method(self, arg):
                  super().method(arg)    # This does the same thing as:
                                         # super(C, self).method(arg)

     除了方法查找之外，*note super(): 5dd. 也可用于属性查找。 一个可能的
     应用场合是在上级或同级类中调用 *note 描述器: 1579.。

     请注意 *note super(): 5dd. 是作为显式加点属性查找的绑定过程的一部分
     来实现的，例如 ‘super().__getitem__(name)’。 它做到这一点是通过实现
     自己的 *note __getattribute__(): 549. 方法，这样就能以可预测的顺序
     搜索类，并且支持协作多重继承。 对应地，*note super(): 5dd. 在像
     ‘super()[name]’ 这样使用语句或操作符进行隐式查找时则未被定义。

     还要注意的是，除了零个参数的形式以外，*note super(): 5dd. 并不限于
     在方法内部使用。 两个参数的形式明确指定参数并进行相应的引用。 零个
     参数的形式仅适用于类定义内部，因为编译器需要填入必要的细节以正确地
     检索到被定义的类，还需要让普通方法访问当前实例。

     对于有关如何使用 *note super(): 5dd. 来如何设计协作类的实用建议，请
     参阅 使用 super() 的指南(4)。

 -- 類別: tuple ([iterable])

     虽然被称为函数，但 *note tuple: 1a2. 实际上是一个不可变的序列类型，
     参见在 *note 元组: 173b. 与 *note 序列类型 — list, tuple, range:
     13a4. 中的文档说明。

 -- 類別: type (object)

 -- 類別: type (name, bases, dict, **kwds)

     传入一个参数时，返回 `object' 的类型。 返回值是一个 type 对象，通常
     与 *note object.__class__: ecc. 所返回的对象相同。

     推荐使用 *note isinstance(): 551. 内置函数来检测对象的类型，因为它
     会考虑子类的情况。

     传入三个参数时，返回一个新的 type 对象。 这在本质上是 *note class:
     d32. 语句的一种动态形式，`name' 字符串即类名并会成为 *note
     __name__: d2f. 属性；`bases' 元组包含基类并会成为 *note __bases__:
     ecb. 属性；如果为空则会添加所有类的终极基类 *note object: 3d2.。
     `dict' 字典包含类主体的属性和方法定义；它在成为 *note __dict__:
     5f5. 属性之前可能会被拷贝或包装。 下面两条语句会创建相同的 *note
     type: 6ff. 对象:

          >>> class X:
          ...     a = 1
          ...
          >>> X = type('X', (), dict(a=1))

     另请参阅 *note 类型对象: 173c.。

     提供给三参数形式的关键字参数会被传递给适当的元类机制 (通常为 *note
     __init_subclass__(): 5dc.)，相当于类定义中关键字 (除了 `metaclass')
     的行为方式。

     另请参阅 *note 自定义类创建: 5df.。

     3.6 版更變: *note type: 6ff. 的子类如果未重载 ‘type.__new__’，将不
     再能使用一个参数的形式来获取对象的类型。

 -- 函式: vars ([object])

     返回模块、类、实例或任何其它具有 *note __dict__: 5f5. 属性的对象的
     *note __dict__: 5f5. 属性。

     模块和实例这样的对象具有可更新的 *note __dict__: 5f5. 属性；但是，
     其它对象的 *note __dict__: 5f5. 属性可能会设为限制写入（例如，类会
     使用 *note types.MappingProxyType: b8e. 来防止直接更新字典）。

     不带参数时，*note vars(): 116d. 的行为类似 *note locals(): 556.。 请
     注意，locals 字典仅对于读取起作用，因为对 locals 字典的更新会被忽略
     。

     如果指定了一个对象但它没有 *note __dict__: 5f5. 属性（例如，当它所
     属的类定义了 *note __slots__: eef. 属性时）则会引发 *note
     TypeError: 1fe. 异常。

 -- 函式: zip (*iterables)

     创建一个聚合了来自每个可迭代对象中的元素的迭代器。

     返回一个元组的迭代器，其中的第 `i' 个元组包含来自每个参数序列或可迭
     代对象的第 `i' 个元素。 当所输入可迭代对象中最短的一个被耗尽时，迭
     代器将停止迭代。 当只有一个可迭代对象参数时，它将返回一个单元组的迭
     代器。 不带参数时，它将返回一个空迭代器。 相当于:

          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)

     函数会保证可迭代对象按从左至右的顺序被求值。 使得可以通过
     ‘zip(*[iter(s)]*n)’ 这样的惯用形式将一系列数据聚类为长度为 n 的分组
     。 这将重复 `同样的' 迭代器 ‘n’ 次，以便每个输出的元组具有第 ‘n’ 次
     调用该迭代器的结果。 它的作用效果就是将输入拆分为长度为 n 的数据块
     。

     当你不用关心较长可迭代对象末尾不匹配的值时，则 *note zip(): cfc. 只
     须使用长度不相等的输入即可。 如果那些值很重要，则应改用 *note
     itertools.zip_longest(): cfb.。

     *note zip(): cfc. 与 ‘*’ 运算符相结合可以用来拆解一个列表:

          >>> 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

 -- 函式: __import__ (name, globals=None, locals=None, fromlist=(),
          level=0)

          備註: 与 *note importlib.import_module(): be6. 不同，这是一个
          日常 Python 编程中不需要用到的高级函数。

     此函数会由 *note import: ce7. 语句发起调用。 它可以被替换 (通过导入
     *note builtins: 12. 模块并赋值给 ‘builtins.__import__’) 以便修改
     ‘import’ 语句的语义，但是 `强烈' 不建议这样做，因为使用导入钩子 (参
     见 PEP 302(5)) 通常更容易实现同样的目标，并且不会导致代码问题，因为
     许多代码都会假定所用的是默认实现。 同样也不建议直接使用 *note
     __import__(): 16b. 而应该用 *note importlib.import_module(): be6.。

     该函数会导入 `name' 模块，有可能使用给定的 `globals' 和 `locals' 来
     确定如何在包的上下文中解读名称。 `fromlist' 给出了应该从由 `name' 指
     定的模块导入对象或子模块的名称。 标准实现完全不使用其 `locals' 参数
     ，而仅使用 `globals' 参数来确定 *note import: ce7. 语句的包上下文。

     `level' 指定是使用绝对还是相对导入。 ‘0’ (默认值) 意味着仅执行绝对
     导入。 `level' 为正数值表示相对于模块调用 *note __import__(): 16b.
     的目录，将要搜索的父目录层数 (详情参见 PEP 328(6))。

     当 `name' 变量的形式为 ‘package.module’ 时，通常将会返回最高层级的
     包（第一个点号之前的名称），而 `不是' 以 `name' 命名的模块。 但是，
     当给出了非空的 `fromlist' 参数时，则将返回以 `name' 命名的模块。

     例如，语句 ‘import spam’ 的结果将为与以下代码作用相同的字节码:

          spam = __import__('spam', globals(), locals(), [], 0)

     语句 ‘import spam.ham’ 的结果将为以下调用:

          spam = __import__('spam.ham', globals(), locals(), [], 0)

     请注意在这里 *note __import__(): 16b. 是如何返回顶层模块的，因为这
     是通过 *note import: ce7. 语句被绑定到特定名称的对象。

     另一方面，语句 ‘from spam.ham import eggs, sausage as saus’ 的结果
     将为

          _temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0)
          eggs = _temp.eggs
          saus = _temp.sausage

     在这里， ‘spam.ham’ 模块会由 *note __import__(): 16b. 返回。 要导入
     的对象将从此对象中提取并赋值给它们对应的名称。

     如果您只想按名称导入模块（可能在包中），请使用 *note
     importlib.import_module(): be6.

     3.3 版更變: `level' 的值不再支持负数（默认值也修改为0）。

     3.9 版更變: 当使用了命令行参数 *note -E: 230. 或 *note -I: 231. 时
     ，环境变量 *note PYTHONCASEOK: 232. 现在将被忽略。

註解
....

   ---------- Footnotes ----------

   (1) (1) 解析器只接受 Unix 风格的行结束符。如果您从文件中读取代码，请
确保用换行符转换模式转换 Windows 或 Mac 风格的换行符。

   (2) https://www.python.org/dev/peps/pep-0475

   (3) https://www.python.org/dev/peps/pep-0008

   (4) 
https://rhettinger.wordpress.com/2011/05/26/super-considered-super/

   (5) https://www.python.org/dev/peps/pep-0302

   (6) https://www.python.org/dev/peps/pep-0328


File: python.info,  Node: 內建常數,  Next: 內建型態,  Prev: 內建函式,  Up: Python 標準函式庫 Standard Library

5.3 內建常數
============

有少数的常量存在于内置命名空间中。 它们是：

 -- Data: False

     *note bool: 2bd. 类型的假值。 给 ‘False’ 赋值是非法的并会引发 *note
     SyntaxError: 559.。

 -- Data: True

     *note bool: 2bd. 类型的真值。 给 ‘True’ 赋值是非法的并会引发 *note
     SyntaxError: 559.。

 -- Data: None

     ‘NoneType’ 类型的唯一值。 ‘None’ 经常用于表示缺少值，当因为默认参数
     未传递给函数时。 给 ‘None’ 赋值是非法的并会引发 *note SyntaxError:
     559.。

 -- Data: NotImplemented

     双目运算特殊方法（如 *note __eq__(): 44b, *note __lt__(): cfe,
     *note __add__(): 1595, *note __rsub__(): 15a7. 等）应返回的特殊值，
     用于表示运算没有针对其他类型的实现；也可由原地双目运算特殊方法（如
     *note __imul__(): 1599, *note __iand__(): 15b7. 等）出于同样的目的
     而返回。 它不应被作为布尔值来解读。

          備註: 当二进制（或就地）方法返回 ‘NotImplemented’ 时，解释器将
          尝试对另一种类型（或其他一些回滚操作，取决于运算符）的反射操作
          。 如果所有尝试都返回 ‘NotImplemented’，则解释器将引发适当的异
          常。 错误返回的 ‘NotImplemented’ 将导致误导性错误消息或返回到
          Python 代码中的 ‘NotImplemented’ 值。

          参见 *note 实现算术运算: 1554. 为例。

          備註: ‘NotImplementedError’ 和 ‘NotImplemented’ 不可互换，即使
          它们有相似的名称和用途。 有关何时使用它的详细信息，请参阅
          *note NotImplementedError: 704.。

     3.9 版更變: 作为布尔值来解读 ‘NotImplemented’ 已被弃用。 虽然它目前
     会被解读为真值，但将同时发出 *note DeprecationWarning: 15a.。 它将
     在未来的 Python 版本中引发 *note TypeError: 1fe.。

 -- Data: Ellipsis

     与省略号文字字面 “‘...’” 相同。 特殊值主要与用户定义的容器数据类型
     的扩展切片语法结合使用。

 -- Data: __debug__

     如果 Python 没有以 *note -O: 77e. 选项启动，则此常量为真值。 另请参
     见 *note assert: 23f. 语句。

     備註: 变量名 *note None: 203.，*note False: 48e.，*note True: 593.
     和 *note __debug__: 1137. 无法重新赋值（赋值给它们，即使是属性名，
     将引发 *note SyntaxError: 559. ），所以它们可以被认为是“真正的”常数
     。

* Menu:

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


File: python.info,  Node: 由 site 模块添加的常量,  Up: 內建常數

5.3.1 由 ‘site’ 模块添加的常量
------------------------------

*note site: eb. 模块（在启动期间自动导入，除非给出 *note -S: bf7. 命令行
选项）将几个常量添加到内置命名空间。 它们对交互式解释器 shell 很有用，并
且不应在程序中使用。

 -- Data: quit (code=None)
 -- Data: exit (code=None)

     当打印此对象时，会打印出一条消息，例如“Use quit() or Ctrl-D (i.e.
     EOF) to exit”，当调用此对象时，将使用指定的退出代码来引发 *note
     SystemExit: 6f3.。

 -- Data: copyright
 -- Data: credits

     打印或调用的对象分别打印版权或作者的文本。

 -- Data: license

     当打印此对象时，会打印出一条消息“Type license() to see the full
     license text”，当调用此对象时，将以分页形式显示完整的许可证文本（每
     次显示一屏）。


File: python.info,  Node: 內建型態,  Next: 內建的例外,  Prev: 內建常數,  Up: Python 標準函式庫 Standard Library

5.4 內建型態
============

以下部分描述了解释器中内置的标准类型。

主要内置类型有数字、序列、映射、类、实例和异常。

有些多项集类是可变的。 它们用于添加、移除或重排其成员的方法将原地执行，
并不返回特定的项，绝对不会返回多项集实例自身而是返回 ‘None’。

有些操作受多种对象类型的支持；特别地，实际上所有对象都可以比较是否相等、
检测逻辑值，以及转换为字符串（使用 *note repr(): 8b9. 函数或略有差异的
*note str(): 205. 函数）。 后一个函数是在对象由 *note print(): 971. 函数
输出时被隐式地调用的。

* 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 类型::
* 其他内置类型::
* 特殊属性::


File: python.info,  Node: 逻辑值检测,  Next: 布尔运算 --- and or not,  Up: 內建型態

5.4.1 逻辑值检测
----------------

任何对象都可以进行逻辑值的检测，以便在 *note if: eab. 或 *note while:
1361. 作为条件或是作为下文所述布尔运算的操作数来使用。

一个对象在默认情况下均被视为真值，除非当该对象被调用时其所属类定义了
*note __bool__(): d30. 方法且返回 ‘False’ 或是定义了 *note __len__():
e90. 方法且返回零。 (1) 下面基本完整地列出了会被视为假值的内置对象:

   * 被定义为假值的常量: ‘None’ 和 ‘False’。

   * 任何数值类型的零: ‘0’, ‘0.0’, ‘0j’, ‘Decimal(0)’, ‘Fraction(0, 1)’

   * 空的序列和多项集: ‘''’, ‘()’, ‘[]’, ‘{}’, ‘set()’, ‘range(0)’

产生布尔值结果的运算和内置函数总是返回 ‘0’ 或 ‘False’ 作为假值，‘1’ 或
‘True’ 作为真值，除非另行说明。 （重要例外：布尔运算 ‘or’ 和 ‘and’ 总是
返回其中一个操作数。）

   ---------- Footnotes ----------

   (1) (1) 有关这些特殊方法的额外信息可参看 Python 参考指南 (*note
基本定制: 1568.)。


File: python.info,  Node: 布尔运算 --- and or not,  Next: 比较,  Prev: 逻辑值检测,  Up: 內建型態

5.4.2 布尔运算 — ‘and’, ‘or’, ‘not’
-----------------------------------

这些属于布尔运算，按优先级升序排列:

运算              结果                                  註解
                                                        
--------------------------------------------------------------------
                                                        
‘x or y’          if `x' is false, then `y', else `x'   (1)
                                                        
                                                        
‘x and y’         if `x' is false, then `x', else `y'   (2)
                                                        
                                                        
‘not x’           if `x' is false, then ‘True’, else    (3)
                  ‘False’                               
                  

註解：

  1. 这是个短路运算符，因此只有在第一个参数为假值时才会对第二个参数求值
     。

  2. 这是个短路运算符，因此只有在第一个参数为真值时才会对第二个参数求值
     。

  3. ‘not’ 的优先级比非布尔运算符低，因此 ‘not a == b’ 会被解读为 ‘not
     (a == b)’ 而 ‘a == not b’ 会引发语法错误。


File: python.info,  Node: 比较,  Next: 数字类型 --- int float complex,  Prev: 布尔运算 --- and or not,  Up: 內建型態

5.4.3 比较
----------

在 Python 中有八种比较运算符。 它们的优先级相同（比布尔运算的优先级高）
。 比较运算可以任意串连；例如，‘x < y <= z’ 等价于 ‘x < y and y <= z’，
前者的不同之处在于 `y' 只被求值一次（但在两种情况下当 ‘x < y’ 结果为假值
时 `z' 都不会被求值）。

此表格汇总了比较运算:

运算             含义
                 
-----------------------------------------------
                 
‘<’              严格小于
                 
                 
‘<=’             小于或等于
                 
                 
‘>’              严格大于
                 
                 
‘>=’             大于或等于
                 
                 
‘==’             等于
                 
                 
‘!=’             不等于
                 
                 
‘is’             对象标识
                 
                 
‘is not’         否定的对象标识
                 

除不同的数字类型外，不同类型的对象不能进行相等比较。‘==’ 运算符总有定义
，但对于某些对象类型（例如，类对象），它等于 *note is: 1551. 。其他 ‘<’、
‘<=’、‘>’ 和 ‘>=’ 运算符仅在有意义的地方定义。例如，当参与比较的参数之一
为复数时，它们会抛出 *note TypeError: 1fe. 异常。

Non-identical instances of a class normally compare as non-equal unless
the class defines the *note __eq__(): 44b. method.

Instances of a class cannot be ordered with respect to other instances
of the same class, or other types of object, unless the class defines
enough of the methods *note __lt__(): cfe, *note __le__(): d68, *note
__gt__(): d69, and *note __ge__(): d6a. (in general, *note __lt__():
cfe. and *note __eq__(): 44b. are sufficient, if you want the
conventional meanings of the comparison operators).

*note is: 1551. 和 *note is not: 1681. 运算符无法自定义；并且它们可以被
应用于任意两个对象而不会引发异常。

还有两种具有相同语法优先级的运算 *note in: 179. 和 *note not in: 159b.，
它们被 *note iterable: c7c. 或实现了 *note __contains__(): dee. 方法的类
型所支持。


File: python.info,  Node: 数字类型 --- int float complex,  Next: 迭代器类型,  Prev: 比较,  Up: 內建型態

5.4.4 数字类型 — ‘int’, ‘float’, ‘complex’
------------------------------------------

存在三种不同的数字类型: `整数', `浮点数' 和 `复数'。 此外，布尔值属于整
数的子类型。 整数具有无限的精度。 浮点数通常使用 C 中的 ‘double’ 来实现
；有关你的程序运行所在机器上浮点数的精度和内部表示法可在 *note
sys.float_info: 10fc. 中查看。 复数包含实部和虚部，分别以一个浮点数表示
。 要从一个复数 `z' 中提取这两个部分，可使用 ‘z.real’ 和 ‘z.imag’。 （标
准库包含附加的数字类型，如表示有理数的 *note fractions.Fraction: 2be. 以
及以用户定制精度表示浮点数的 *note decimal.Decimal: 2c0.。）

数字是由数字字面值或内置函数与运算符的结果来创建的。 不带修饰的整数字面
值（包括十六进制、八进制和二进制数）会生成整数。 包含小数点或幂运算符的
数字字面值会生成浮点数。 在数字字面值末尾加上 ‘'j'’ 或 ‘'J'’ 会生成虚数
（实部为零的复数），你可以将其与整数或浮点数相加来得到具有实部和虚部的复
数。

Python 完全支持混合运算：当一个二元算术运算符的操作数有不同数值类型时，
"较窄"类型的操作数会拓宽到另一个操作数的类型，其中整数比浮点数窄，浮点数
比复数窄。不同类型的数字之间的比较，同比较这些数字的精确值一样。(1)

构造函数 *note int(): 204.、 *note float(): 1fd. 和 *note complex():
2c1. 可以用来构造特定类型的数字。

所有数字类型（复数除外）都支持下列运算（有关运算优先级，请参阅：*note
运算符优先级: 169a.）:

运算                      结果                                  註解          完整文档
                                                                              
-------------------------------------------------------------------------------------------------------
                                                                              
‘x + y’                   `x' 和 `y' 的和
                          
                                                                              
‘x - y’                   `x' 和 `y' 的差
                          
                                                                              
‘x * y’                   `x' 和 `y' 的乘积
                          
                                                                              
‘x / y’                   `x' 和 `y' 的商
                          
                                                                              
‘x // y’                  `x' 和 `y' 的商数                     (1)
                                                                
                                                                              
‘x % y’                   ‘x / y’ 的余数                        (2)
                                                                
                                                                              
‘-x’                      `x' 取反
                          
                                                                              
‘+x’                      `x' 不变
                          
                                                                              
‘abs(x)’                  `x' 的绝对值或大小                                  *note abs(): 13f3.
                                                                              
                                                                              
‘int(x)’                  将 `x' 转换为整数                     (3)(6)        *note int(): 204.
                                                                              
                                                                              
‘float(x)’                将 `x' 转换为浮点数                   (4)(6)        *note float(): 1fd.
                                                                              
                                                                              
‘complex(re, im)’         一个带有实部 `re' 和虚部 `im' 的复    (6)           *note complex(): 2c1.
                          数。`im' 默认为0。                                  
                          
                                                                              
‘c.conjugate()’           复数 `c' 的共轭
                          
                                                                              
‘divmod(x, y)’            ‘(x // y, x % y)’                     (2)           *note divmod(): 28d.
                                                                              
                                                                              
‘pow(x, y)’               `x' 的 `y' 次幂                       (5)           *note pow(): 2cf.
                                                                              
                                                                              
‘x ** y’                  `x' 的 `y' 次幂                       (5)
                                                                

註解：

  1. 也称为整数除法。 结果值是一个整数，但结果的类型不一定是 int。 运算
     结果总是向负无穷的方向舍入: ‘1//2’ 为 ‘0’, ‘(-1)//2’ 为 ‘-1’,
     ‘1//(-2)’ 为 ‘-1’ 而 ‘(-1)//(-2)’ 为 ‘0’。

  2. 不可用于复数。 而应在适当条件下使用 *note abs(): 13f3. 转换为浮点数
     。

  3. 
     从浮点数转换为整数会被舍入或是像在 C 语言中一样被截断；请参阅 *note
     math.floor(): df2. 和 *note math.ceil(): df3. 函数查看转换的完整定
     义。

  4. float 也接受字符串 "nan" 和附带可选前缀 "+" 或 "-" 的 "inf" 分别表
     示非数字 (NaN) 以及正或负无穷。

  5. Python 将 ‘pow(0, 0)’ 和 ‘0 ** 0’ 定义为 ‘1’，这是编程语言的普遍做
     法。

  6. 接受的数字字面值包括数码 ‘0’ 到 ‘9’ 或任何等效的 Unicode 字符（具有
     ‘Nd’ 特征属性的代码点）。

     请参阅
     ‘https://www.unicode.org/Public/13.0.0/ucd/extracted/DerivedNumericType.txt’
     查看具有 ‘Nd’ 特征属性的代码点的完整列表。

所有 *note numbers.Real: 1557. 类型 (*note int: 204. 和 *note float:
1fd.) 还包括下列运算:

运算                     结果
                         
---------------------------------------------------------------------------
                         
*note math.trunc(x): df4.`x' 截断为 *note Integral: 1556.
                         
                         
*note round(x[, n]): d35.`x' 舍入到 `n' 位小数，半数值会舍入到偶数。 如
                         果省略 `n'，则默认为 0。
                         
                         
*note math.floor(x): df2.<= `x' 的最大 *note Integral: 1556.
                         
                         
*note math.ceil(x): df3. >= `x' 的最小 *note Integral: 1556.
                         

有关更多的数字运算请参阅 *note math: b1. 和 *note cmath: 18. 模块。

* Menu:

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

   ---------- Footnotes ----------

   (1) (2) 作为结果，列表 ‘[1, 2]’ 与 ‘[1.0, 2.0]’ 是相等的，元组的情况
也类似。


File: python.info,  Node: 整数类型的按位运算,  Next: 整数类型的附加方法,  Up: 数字类型 --- int float complex

5.4.4.1 整数类型的按位运算
..........................

按位运算只对整数有意义。 计算按位运算的结果，就相当于使用无穷多个二进制
符号位对二的补码执行操作。

二进制按位运算的优先级全都低于数字运算，但又高于比较运算；一元运算 ‘~’ 具
有与其他一元算术运算 (‘+’ and ‘-’) 相同的优先级。

此表格是以优先级升序排序的按位运算列表:

运算             结果                                 註解
                                                      
---------------------------------------------------------------------
                                                      
‘x | y’          `x' 和 `y' 按位 `或'                 (4)
                                                      
                                                      
‘x ^ y’          `x' 和 `y' 按位 `异或'               (4)
                                                      
                                                      
‘x & y’          `x' 和 `y' 按位 `与'                 (4)
                                                      
                                                      
‘x << n’         `x' 左移 `n' 位                      (1)(2)
                                                      
                                                      
‘x >> n’         `x' 右移 `n' 位                      (1)(3)
                                                      
                                                      
‘~x’             `x' 逐位取反
                 

註解：

  1. 负的移位数是非法的，会导致引发 *note ValueError: 16d.。

  2. 左移 `n' 位等价于乘以 ‘pow(2, n)’ 。

  3. 右移 `n' 位等价于除以 ‘pow(2, n)’ ，作向下取整除法。

  4. 使用带有至少一个额外符号扩展位的有限个二进制补码表示（有效位宽度为
     ‘1 + max(x.bit_length(), y.bit_length())’ 或以上）执行这些计算就足
     以获得相当于有无数个符号位时的同样结果。


File: python.info,  Node: 整数类型的附加方法,  Next: 浮点类型的附加方法,  Prev: 整数类型的按位运算,  Up: 数字类型 --- int float complex

5.4.4.2 整数类型的附加方法
..........................

int 类型实现了 *note numbers.Integral: 1556. *note abstract base class:
c05.。 此外，它还提供了其他几个方法:

 -- 成員函式: int.bit_length ()

     返回以二进制表示一个整数所需要的位数，不包括符号位和前面的零:

          >>> n = -37
          >>> bin(n)
          '-0b100101'
          >>> n.bit_length()
          6

     更准确地说，如果 ‘x’ 非零，则 ‘x.bit_length()’ 是使得 ‘2**(k-1) <=
     abs(x) < 2**k’ 的唯一正整数 ‘k’。 同样地，当 ‘abs(x)’ 小到足以具有
     正确的舍入对数时，则 ‘k = 1 + int(log(abs(x), 2))’。 如果 ‘x’ 为零
     ，则 ‘x.bit_length()’ 返回 ‘0’。

     等价于:

          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

     3.1 版新加入.

 -- 成員函式: int.to_bytes (length, byteorder, *, signed=False)

     返回表示一个整数的字节数组。

          >>> (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'

     整数会使用 `length' 个字节来表示。 如果整数不能用给定的字节数来表示
     则会引发 *note OverflowError: a41.。

     `byteorder' 参数确定用于表示整数的字节顺序。 如果 `byteorder' 为
     ‘"big"’，则最高位字节放在字节数组的开头。 如果 `byteorder' 为
     ‘"little"’，则最高位字节放在字节数组的末尾。 要请求主机系统上的原生
     字节顺序，请使用 *note sys.byteorder: 1755. 作为字节顺序值。

     `signed' 参数确定是否使用二的补码来表示整数。 如果 `signed' 为
     ‘False’ 并且给出的是负整数，则会引发 *note OverflowError: a41.。
     `signed' 的默认值为 ‘False’。

     3.2 版新加入.

 -- 成員函式: classmethod int.from_bytes (bytes, byteorder, *,
          signed=False)

     返回由给定字节数组所表示的整数。

          >>> 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

     `bytes' 参数必须为一个 *note bytes-like object: 6df. 或是生成字节的
     可迭代对象。

     `byteorder' 参数确定用于表示整数的字节顺序。 如果 `byteorder' 为
     ‘"big"’，则最高位字节放在字节数组的开头。 如果 `byteorder' 为
     ‘"little"’，则最高位字节放在字节数组的末尾。 要请求主机系统上的原生
     字节顺序，请使用 *note sys.byteorder: 1755. 作为字节顺序值。

     `signed' 参数指明是否使用二的补码来表示整数。

     3.2 版新加入.

 -- 成員函式: int.as_integer_ratio ()

     返回一对整数，其比率正好等于原整数并且分母为正数。 整数的比率总是用
     这个整数本身作为分子，‘1’ 作为分母。

     3.8 版新加入.


File: python.info,  Node: 浮点类型的附加方法,  Next: 数字类型的哈希运算,  Prev: 整数类型的附加方法,  Up: 数字类型 --- int float complex

5.4.4.3 浮点类型的附加方法
..........................

float 类型实现了 *note numbers.Real: 1557. *note abstract base class:
c05.。 float 还具有以下附加方法。

 -- 成員函式: float.as_integer_ratio ()

     返回一对整数，其比率正好等于原浮点数并且分母为正数。 无穷大会引发
     *note OverflowError: a41. 而 NaN 则会引发 *note ValueError: 16d.。

 -- 成員函式: float.is_integer ()

     如果 float 实例可用有限位整数表示则返回 ‘True’，否则返回 ‘False’:

          >>> (-2.0).is_integer()
          True
          >>> (3.2).is_integer()
          False

两个方法均支持与十六进制数字符串之间的转换。 由于 Python 浮点数在内部存
储为二进制数，因此浮点数与 `十进制数' 字符串之间的转换往往会导致微小的舍
入错误。 而十六进制数字符串却允许精确地表示和描述浮点数。 这在进行调试和
数值工作时非常有用。

 -- 成員函式: float.hex ()

     以十六进制字符串的形式返回一个浮点数表示。 对于有限浮点数，这种表示
     法将总是包含前导的 ‘0x’ 和尾随的 ‘p’ 加指数。

 -- 成員函式: classmethod float.fromhex (s)

     返回以十六进制字符串 `s' 表示的浮点数的类方法。 字符串 `s' 可以带有
     前导和尾随的空格。

请注意 *note float.hex(): 1458. 是实例方法，而 *note float.fromhex():
1759. 是类方法。

十六进制字符串采用的形式为:

     [sign] ['0x'] integer ['.' fraction] ['p' exponent]

可选的 ‘sign’ 可以是 ‘+’ 或 ‘-’，‘integer’ 和 ‘fraction’ 是十六进制数码
组成的字符串，‘exponent’ 是带有可选前导符的十进制整数。 大小写没有影响，
在 integer 或 fraction 中必须至少有一个十六进制数码。 此语法类似于 C99 标
准的 6.4.4.2 小节中所描述的语法，也是 Java 1.5 以上所使用的语法。 特别地
，*note float.hex(): 1458. 的输出可以用作 C 或 Java 代码中的十六进制浮点
数字面值，而由 C 的 ‘%a’ 格式字符或 Java 的 ‘Double.toHexString’ 所生成
的十六进制数字符串由为 *note float.fromhex(): 1759. 所接受。

请注意 exponent 是十进制数而非十六进制数，它给出要与系数相乘的 2 的幂次
。 例如，十六进制数字符串 ‘0x3.a7p10’ 表示浮点数 ‘(3 + 10./16 +
7./16**2) * 2.0**10’ 即 ‘3740.0’:

     >>> float.fromhex('0x3.a7p10')
     3740.0

对 ‘3740.0’ 应用反向转换会得到另一个代表相同数值的十六进制数字符串:

     >>> float.hex(3740.0)
     '0x1.d380000000000p+11'


File: python.info,  Node: 数字类型的哈希运算,  Prev: 浮点类型的附加方法,  Up: 数字类型 --- int float complex

5.4.4.4 数字类型的哈希运算
..........................

For numbers ‘x’ and ‘y’, possibly of different types, it’s a requirement
that ‘hash(x) == hash(y)’ whenever ‘x == y’ (see the *note __hash__():
44c. method documentation for more details).  For ease of implementation
and efficiency across a variety of numeric types (including *note int:
204, *note float: 1fd, *note decimal.Decimal: 2c0. and *note
fractions.Fraction: 2be.) Python’s hash for numeric types is based on a
single mathematical function that’s defined for any rational number, and
hence applies to all instances of *note int: 204. and *note
fractions.Fraction: 2be, and all finite instances of *note float: 1fd.
and *note decimal.Decimal: 2c0.  Essentially, this function is given by
reduction modulo ‘P’ for a fixed prime ‘P’.  The value of ‘P’ is made
available to Python as the ‘modulus’ attribute of *note sys.hash_info:
a06.

`CPython implementation detail:' 目前所用的质数设定，在 C long 为 32 位
的机器上 ‘P = 2**31 - 1’ 而在 C long 为 64 位的机器上 ‘P = 2**61 - 1’。

详细规则如下所述:

   - 如果 ‘x = m / n’ 是一个非负的有理数且 ‘n’ 不可被 ‘P’ 整除，则定义
     ‘hash(x)’ 为 ‘m * invmod(n, P) % P’，其中 ‘invmod(n, P)’ 是对 ‘n’ 模
     ‘P’ 取反。

   - 如果 ‘x = m / n’ 是一个非负的有理数且 ‘n’ 可被 ‘P’ 整除（但 ‘m’ 不
     能）则 ‘n’ 不能对 ‘P’ 降模，以上规则不适用；在此情况下则定义
     ‘hash(x)’ 为常数值 ‘sys.hash_info.inf’。

   - 如果 ‘x = m / n’ 是一个负的有理数则定义 ‘hash(x)’ 为 ‘-hash(-x)’。
     如果结果哈希值为 ‘-1’ 则将其替换为 ‘-2’。

   - 特定值 ‘sys.hash_info.inf’, ‘-sys.hash_info.inf’ 和
     ‘sys.hash_info.nan’ 被用作正无穷、负无穷和空值（所分别对应的）哈希
     值。 （所有可哈希的空值都具有相同的哈希值。）

   - 对于一个 *note complex: 2c1. 值 ‘z’，会通过计算 ‘hash(z.real) +
     sys.hash_info.imag * hash(z.imag)’ 将实部和虚部的哈希值结合起来，并
     进行降模 ‘2**sys.hash_info.width’ 以使其处于
     ‘range(-2**(sys.hash_info.width - 1), 2**(sys.hash_info.width -
     1))’ 范围之内。 同样地，如果结果为 ‘-1’ 则将其替换为 ‘-2’。

为了阐明上述规则，这里有一些等价于内置哈希算法的 Python 代码示例，可用于
计算有理数、*note float: 1fd. 或 *note complex: 2c1. 的哈希值:

     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


File: python.info,  Node: 迭代器类型,  Next: 序列类型 --- list tuple range,  Prev: 数字类型 --- int float complex,  Up: 內建型態

5.4.5 迭代器类型
----------------

Python 支持在容器中进行迭代的概念。 这是通过使用两个单独方法来实现的；它
们被用于允许用户自定义类对迭代的支持。 将在下文中详细描述的序列总是支持
迭代方法。

容器对象要提供迭代支持，必须定义一个方法:

 -- 成員函式: container.__iter__ ()

     返回一个迭代器对象。 该对象需要支持下文所述的迭代器协议。 如果容器
     支持不同的迭代类型，则可以提供额外的方法来专门地请求不同迭代类型的
     迭代器。 （支持多种迭代形式的对象的例子有同时支持广度优先和深度优先
     遍历的树结构。） 此方法对应于 Python/C API 中 Python 对象类型结构体
     的 *note tp_iter: ef2. 槽位。

迭代器对象自身需要支持以下两个方法，它们共同组成了 `迭代器协议':

 -- 成員函式: iterator.__iter__ ()

     返回迭代器对象本身。 这是同时允许容器和迭代器配合 *note for: cfa. 和
     *note in: 179. 语句使用所必须的。 此方法对应于 Python/C API 中
     Python 对象类型结构体的 *note tp_iter: ef2. 槽位。

 -- 成員函式: iterator.__next__ ()

     从容器中返回下一项。 如果已经没有项可返回，则会引发 *note
     StopIteration: 581. 异常。 此方法对应于 Python/C API 中 Python 对象
     类型结构体的 *note tp_iternext: ef3. 槽位。

Python 定义了几种迭代器对象以支持对一般和特定序列类型、字典和其他更特别
的形式进行迭代。 除了迭代器协议的实现，特定类型的其他性质对迭代操作来说
都不重要。

一旦迭代器的 *note __next__(): d2c. 方法引发了 *note StopIteration:
581.，它必须一直对后续调用引发同样的异常。 不遵循此行为特性的实现将无法
正常使用。

* Menu:

* 生成器类型::


File: python.info,  Node: 生成器类型,  Up: 迭代器类型

5.4.5.1 生成器类型
..................

Python 的 *note generator: a83. 提供了一种实现迭代器协议的便捷方式。 如
果容器对象 *note __iter__(): 608. 方法被实现为一个生成器，它将自动返回一
个迭代器对象（从技术上说是一个生成器对象），该对象提供 *note __iter__():
608. 和 *note __next__(): 140e. 方法。 有关生成器的更多信息可以参阅
*note yield 表达式的文档: 163d.。


File: python.info,  Node: 序列类型 --- list tuple range,  Next: 文本序列类型 --- str,  Prev: 迭代器类型,  Up: 內建型態

5.4.6 序列类型 — ‘list’, ‘tuple’, ‘range’
-----------------------------------------

有三种基本序列类型：list, tuple 和 range 对象。 为处理 *note 二进制数据:
171d. 和 *note 文本字符串: 1357. 而特别定制的附加序列类型会在专门的小节
中描述。

* Menu:

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


File: python.info,  Node: 通用序列操作,  Next: 不可变序列类型,  Up: 序列类型 --- list tuple range

5.4.6.1 通用序列操作
....................

大多数序列类型，包括可变类型和不可变类型都支持下表中的操作。 *note
collections.abc.Sequence: 1764. ABC 被提供用来更容易地在自定义序列类型上
正确地实现这些操作。

此表按优先级升序列出了序列操作。 在表格中，`s' 和 `t' 是具有相同类型的序
列，`n', `i', `j' 和 `k' 是整数而 `x' 是任何满足 `s' 所规定的类型和值限
制的任意对象。

‘in’ 和 ‘not in’ 操作具有与比较操作相同的优先级。 ‘+’ (拼接) 和 ‘*’ (重
复) 操作具有与对应数值运算相同的优先级。 (1)

运算                           结果                                 註解
                                                                    
-----------------------------------------------------------------------------------
                                                                    
‘x in s’                       如果 `s' 中的某项等于 `x' 则结果为   (1)
                               ‘True’，否则为 ‘False’               
                               
                                                                    
‘x not in s’                   如果 `s' 中的某项等于 `x' 则结果为   (1)
                               ‘False’，否则为 ‘True’               
                               
                                                                    
‘s + t’                        `s' 与 `t' 相拼接                    (6)(7)
                                                                    
                                                                    
‘s * n’ 或 ‘n * s’             相当于 `s' 与自身进行 `n' 次拼接     (2)(7)
                                                                    
                                                                    
‘s[i]’                         `s' 的第 `i' 项，起始为 0            (3)
                                                                    
                                                                    
‘s[i:j]’                       `s' 从 `i' 到 `j' 的切片             (3)(4)
                                                                    
                                                                    
‘s[i:j:k]’                     `s' 从 `i' 到 `j' 步长为 `k' 的切    (3)(5)
                               片                                   
                               
                                                                    
‘len(s)’                       `s' 的长度
                               
                                                                    
‘min(s)’                       `s' 的最小项
                               
                                                                    
‘max(s)’                       `s' 的最大项
                               
                                                                    
‘s.index(x[, i[, j]])’         `x' 在 `s' 中首次出现项的索引号（    (8)
                               索引号在 `i' 或其后且在 `j' 之前）   
                               
                                                                    
‘s.count(x)’                   `x' 在 `s' 中出现的总次数
                               

相同类型的序列也支持比较。 特别地，tuple 和 list 的比较是通过比较对应元
素的字典顺序。 这意味着想要比较结果相等，则每个元素比较结果都必须相等，
并且两个序列长度必须相同。 （完整细节请参阅语言参考的 *note 比较运算:
167a. 部分。）

註解：

  1. 虽然 ‘in’ 和 ‘not in’ 操作在通常情况下仅被用于简单的成员检测，某些
     专门化序列 (例如 *note str: 205, *note bytes: 172. 和 *note
     bytearray: 173.) 也使用它们进行子序列检测:

          >>> "gg" in "eggs"
          True

  2. 小于 ‘0’ 的 `n' 值会被当作 ‘0’ 来处理 (生成一个与 `s' 同类型的空序
     列)。 请注意序列 `s' 中的项并不会被拷贝；它们会被多次引用。 这一点
     经常会令 Python 编程新手感到困扰；例如:

          >>> lists = [[]] * 3
          >>> lists
          [[], [], []]
          >>> lists[0].append(3)
          >>> lists
          [[3], [3], [3]]

     具体的原因在于 ‘[[]]’ 是一个包含了一个空列表的单元素列表，所以
     ‘[[]] * 3’ 结果中的三个元素都是对这一个空列表的引用。 修改 ‘lists’
     中的任何一个元素实际上都是对这一个空列表的修改。 你可以用以下方式创
     建以不同列表为元素的列表:

          >>> lists = [[] for i in range(3)]
          >>> lists[0].append(3)
          >>> lists[1].append(5)
          >>> lists[2].append(7)
          >>> lists
          [[3], [5], [7]]

     进一步的解释可以在 FAQ 条目 *note 如何创建多维列表？: 1765. 中查看
     。

  3. 如果 `i' 或 `j' 为负值，则索引顺序是相对于序列 `s' 的末尾: 索引号会
     被替换为 ‘len(s) + i’ 或 ‘len(s) + j’。 但要注意 ‘-0’ 仍然为 ‘0’。

  4. `s' 从 `i' 到 `j' 的切片被定义为所有满足 ‘i <= k < j’ 的索引号 `k'
     的项组成的序列。 如果 `i' 或 `j' 大于 ‘len(s)’，则使用 ‘len(s)’。 如
     果 `i' 被省略或为 ‘None’，则使用 ‘0’。 如果 `j' 被省略或为 ‘None’，
     则使用 ‘len(s)’。 如果 `i' 大于等于 `j'，则切片为空。

  5. `s' 从 `i' 到 `j' 步长为 `k' 的切片被定义为所有满足 ‘0 <= n <
     (j-i)/k’ 的索引号 ‘x = i + n*k’ 的项组成的序列。 换句话说，索引号为
     ‘i’, ‘i+k’, ‘i+2*k’, ‘i+3*k’，以此类推，当达到 `j' 时停止 (但一定不
     包括 `j')。 当 `k' 为正值时，`i' 和 `j' 会被减至不大于 ‘len(s)’。 当
     `k' 为负值时，`i' 和 `j' 会被减至不大于 ‘len(s) - 1’。 如果 `i' 或
     `j' 被省略或为 ‘None’，它们会成为“终止”值 (是哪一端的终止值则取决于
     `k' 的符号)。 请注意，`k' 不可为零。 如果 `k' 为 ‘None’，则当作 ‘1’
     处理。

  6. 拼接不可变序列总是会生成新的对象。 这意味着通过重复拼接来构建序列的
     运行时开销将会基于序列总长度的乘方。 想要获得线性的运行时开销，你必
     须改用下列替代方案之一：

        * 如果拼接 *note str: 205. 对象，你可以构建一个列表并在最后使用
          *note str.join(): 1766. 或是写入一个 *note io.StringIO: 91a. 实
          例并在结束时获取它的值

        * 如果拼接 *note bytes: 172. 对象，你可以类似地使用 *note
          bytes.join(): 1767. 或 *note io.BytesIO: 88a.，或者你也可以使
          用 *note bytearray: 173. 对象进行原地拼接。 *note bytearray:
          173. 对象是可变的，并且具有高效的重分配机制

        * 如果拼接 *note tuple: 1a2. 对象，请改为扩展 *note list: 1f8. 类

        * 对于其它类型，请查看相应的文档

  7. 某些序列类型 (例如 *note range: 1f5.) 仅支持遵循特定模式的项序列，
     因此并不支持序列拼接或重复。

  8. 当 `x' 在 `s' 中找不到时 ‘index’ 会引发 *note ValueError: 16d.。 不
     是所有实现都支持传入额外参数 `i' 和 `j'。 这两个参数允许高效地搜索
     序列的子序列。 传入这两个额外参数大致相当于使用 ‘s[i:j].index(x)’，
     但是不会复制任何数据，并且返回的索引是相对于序列的开头而非切片的开
     头。

   ---------- Footnotes ----------

   (1) (3) 它们必须如此，因为解析器无法区分这些操作数的类型。


File: python.info,  Node: 不可变序列类型,  Next: 可变序列类型,  Prev: 通用序列操作,  Up: 序列类型 --- list tuple range

5.4.6.2 不可变序列类型
......................

不可变序列类型普遍实现而可变序列类型未实现的唯一操作就是对 *note hash():
aa3. 内置函数的支持。

这种支持允许不可变类型，例如 *note tuple: 1a2. 实例被用作 *note dict:
164. 键，以及存储在 *note set: 1f6. 和 *note frozenset: 1f7. 实例中。

尝试对包含有不可哈希值的不可变序列进行哈希运算将会导致 *note TypeError:
1fe.。


File: python.info,  Node: 可变序列类型,  Next: List（串列）<2>,  Prev: 不可变序列类型,  Up: 序列类型 --- list tuple range

5.4.6.3 可变序列类型
....................

以下表格中的操作是在可变序列类型上定义的。 *note
collections.abc.MutableSequence: 79f. ABC 被提供用来更容易地在自定义序列
类型上正确实现这些操作。

表格中的 `s' 是可变序列类型的实例，`t' 是任意可迭代对象，而 `x' 是符合对
`s' 所规定类型与值限制的任何对象 (例如，*note bytearray: 173. 仅接受满足
‘0 <= x <= 255’ 值限制的整数)。

运算                               结果                                 註解
                                                                        
--------------------------------------------------------------------------------------------------
                                                                        
‘s[i] = x’                         将 `s' 的第 `i' 项替换为 `x'
                                   
                                                                        
‘s[i:j] = t’                       将 `s' 从 `i' 到 `j' 的切片替换为
                                   可迭代对象 `t' 的内容
                                   
                                                                        
‘del s[i:j]’                       等同于 ‘s[i:j] = []’
                                   
                                                                        
‘s[i:j:k] = t’                     将 ‘s[i:j:k]’ 的元素替换为 `t' 的    (1)
                                   元素                                 
                                   
                                                                        
‘del s[i:j:k]’                     从列表中移除 ‘s[i:j:k]’ 的元素
                                   
                                                                        
‘s.append(x)’                      将 `x' 添加到序列的末尾 (等同于
                                   ‘s[len(s):len(s)] = [x]’)
                                   
                                                                        
‘s.clear()’                        从 `s' 中移除所有项 (等同于 ‘del     (5)
                                   s[:]’)                               
                                   
                                                                        
‘s.copy()’                         创建 `s' 的浅拷贝 (等同于 ‘s[:]’)    (5)
                                                                        
                                                                        
‘s.extend(t)’ 或 ‘s += t’          用 `t' 的内容扩展 `s' (基本上等同
                                   于 ‘s[len(s):len(s)] = t’)
                                   
                                                                        
‘s *= n’                           使用 `s' 的内容重复 `n' 次来对其进   (6)
                                   行更新                               
                                   
                                                                        
‘s.insert(i, x)’                   在由 `i' 给出的索引位置将 `x' 插入
                                   `s' (等同于 ‘s[i:i] = [x]’)
                                   
                                                                        
‘s.pop()’ 或 ‘s.pop(i)’            提取在 `i' 位置上的项，并将其从      (2)
                                   `s' 中移除                           
                                   
                                                                        
‘s.remove(x)’                      删除 `s' 中第一个 ‘s[i]’ 等于 `x'    (3)
                                   的项目。                             
                                   
                                                                        
‘s.reverse()’                      就地将列表中的元素逆序。             (4)
                                                                        

註解：

  1. `t' 必须与它所替换的切片具有相同的长度。

  2. 可选参数 `i' 默认为 ‘-1’，因此在默认情况下会移除并返回最后一项。

  3. 当在 `s' 中找不到 `x' 时 ‘remove()’ 操作会引发 *note ValueError:
     16d.。

  4. 当反转大尺寸序列时 ‘reverse()’ 方法会原地修改该序列以保证空间经济性
     。 为提醒用户此操作是通过间接影响进行的，它并不会返回反转后的序列。

  5. 包括 ‘clear()’ 和 ‘copy()’ 是为了与不支持切片操作的可变容器 (例如
     *note dict: 164. 和 *note set: 1f6.) 的接口保持一致。 ‘copy()’ 不是
     *note collections.abc.MutableSequence: 79f. ABC 的一部分，但大多数
     具体的可变序列类都提供了它。

     3.3 版新加入: ‘clear()’ 和 ‘copy()’ 方法。

  6. `n' 值为一个整数，或是一个实现了 *note __index__(): 2c2. 的对象。
     `n' 值为零或负数将清空序列。 序列中的项不会被拷贝；它们会被多次引用
     ，正如 *note 通用序列操作: 1763. 中有关 ‘s * n’ 的说明。


File: python.info,  Node: List（串列）<2>,  Next: 元组,  Prev: 可变序列类型,  Up: 序列类型 --- list tuple range

5.4.6.4 List（串列）
....................

列表是可变序列，通常用于存放同类项目的集合（其中精确的相似程度将根据应用
而变化）。

 -- 類別: list ([iterable])

     可以用多种方式构建列表：

        * 使用一对方括号来表示空列表: ‘[]’

        * 使用方括号，其中的项以逗号分隔: ‘[a]’, ‘[a, b, c]’

        * 使用列表推导式: ‘[x for x in iterable]’

        * 使用类型的构造器: ‘list()’ 或 ‘list(iterable)’

     构造器将构造一个列表，其中的项与 `iterable' 中的项具有相同的的值与
     顺序。 `iterable' 可以是序列、支持迭代的容器或其它可迭代对象。 如果
     `iterable' 已经是一个列表，将创建并返回其副本，类似于
     ‘iterable[:]’。 例如，‘list('abc')’ 返回 ‘['a', 'b', 'c']’ 而
     ‘list( (1, 2, 3) )’ 返回 ‘[1, 2, 3]’。 如果没有给出参数，构造器将创
     建一个空列表 ‘[]’。

     其它许多操作也会产生列表，包括 *note sorted(): 546. 内置函数。

     列表实现了所有 *note 一般: 1763. 和 *note 可变: 171a. 序列的操作。
     列表还额外提供了以下方法：

      -- 成員函式: sort (*, key=None, reverse=False)

          此方法会对列表进行原地排序，只使用 ‘<’ 来进行各项间比较。 异常
          不会被屏蔽 —— 如果有任何比较操作失败，整个排序操作将失败（而列
          表可能会处于被部分修改的状态）。

          *note sort(): 547. 接受两个仅限以关键字形式传入的参数 (*note
          仅限关键字参数: 3ce.):

          `key' 指定带有一个参数的函数，用于从每个列表元素中提取比较键
          (例如 ‘key=str.lower’)。 对应于列表中每一项的键会被计算一次，
          然后在整个排序过程中使用。 默认值 ‘None’ 表示直接对列表项排序
          而不计算一个单独的键值。

          可以使用 *note functools.cmp_to_key(): c28. 将 2.x 风格的
          `cmp' 函数转换为 `key' 函数。

          `reverse' 为一个布尔值。 如果设为 ‘True’，则每个列表元素将按反
          向顺序比较进行排序。

          当顺序大尺寸序列时此方法会原地修改该序列以保证空间经济性。 为
          提醒用户此操作是通过间接影响进行的，它并不会返回排序后的序列（
          请使用 *note sorted(): 546. 显示地请求一个新的已排序列表实例）
          。

          *note sort(): 547. 方法确保是稳定的。 如果一个排序确保不会改变
          比较结果相等的元素的相对顺序就称其为稳定的 — 这有利于进行多重
          排序（例如先按部门、再接薪级排序）。

          有关排序示例和简要排序教程，请参阅 *note 如何排序: 1737. 。

          `CPython implementation detail:' 在一个列表被排序期间，尝试改
          变甚至进行检测也会造成未定义的影响。 Python 的 C 实现会在排序
          期间将列表显示为空，如果发现列表在排序期间被改变将会引发 *note
          ValueError: 16d.。


File: python.info,  Node: 元组,  Next: range 对象,  Prev: List（串列）<2>,  Up: 序列类型 --- list tuple range

5.4.6.5 元组
............

元组是不可变序列，通常用于储存异构数据的多项集（例如由 *note
enumerate(): ea7. 内置函数所产生的二元组）。 元组也被用于需要同构数据的
不可变序列的情况（例如允许存储到 *note set: 1f6. 或 *note dict: 164. 的
实例）。

 -- 類別: tuple ([iterable])

     可以用多种方式构建元组：

        * 使用一对圆括号来表示空元组: ‘()’

        * 使用一个后缀的逗号来表示单元组: ‘a,’ 或 ‘(a,)’

        * 使用以逗号分隔的多个项: ‘a, b, c’ or ‘(a, b, c)’

        * 使用内置的 *note tuple(): 1a2.: ‘tuple()’ 或 ‘tuple(iterable)’

     构造器将构造一个元组，其中的项与 `iterable' 中的项具有相同的值与顺
     序。 `iterable' 可以是序列、支持迭代的容器或其他可迭代对象。 如果
     `iterable' 已经是一个元组，会不加改变地将其返回。 例如，
     ‘tuple('abc')’ 返回 ‘('a', 'b', 'c')’ 而 ‘tuple( [1, 2, 3] )’ 返回
     ‘(1, 2, 3)’。 如果没有给出参数，构造器将创建一个空元组 ‘()’。

     请注意决定生成元组的其实是逗号而不是圆括号。 圆括号只是可选的，生成
     空元组或需要避免语法歧义的情况除外。 例如，‘f(a, b, c)’ 是在调用函
     数时附带三个参数，而 ‘f((a, b, c))’ 则是在调用函数时附带一个三元组
     。

     元组实现了所有 *note 一般: 1763. 序列的操作。

对于通过名称访问相比通过索引访问更清晰的异构数据多项集，*note
collections.namedtuple(): 1a1. 可能是比简单元组对象更为合适的选择。


File: python.info,  Node: range 对象,  Prev: 元组,  Up: 序列类型 --- list tuple range

5.4.6.6 range 对象
..................

*note range: 1f5. 类型表示不可变的数字序列，通常用于在 *note for: cfa. 循
环中循环指定的次数。

 -- 類別: range (stop)

 -- 類別: range (start, stop[, step])

     The arguments to the range constructor must be integers (either
     built-in *note int: 204. or any object that implements the *note
     __index__(): 2c2. special method).  If the `step' argument is
     omitted, it defaults to ‘1’.  If the `start' argument is omitted,
     it defaults to ‘0’.  If `step' is zero, *note ValueError: 16d. is
     raised.

     如果 `step' 为正值，确定 range ‘r’ 内容的公式为 ‘r[i] = start +
     step*i’ 其中 ‘i >= 0’ 且 ‘r[i] < stop’。

     如果 `step' 为负值，确定 range 内容的公式仍然为 ‘r[i] = start +
     step*i’，但限制条件改为 ‘i >= 0’ 且 ‘r[i] > stop’.

     如果 ‘r[0]’ 不符合值的限制条件，则该 range 对象为空。 range 对象确
     实支持负索引，但是会将其解读为从正索引所确定的序列的末尾开始索引。

     元素绝对值大于 *note sys.maxsize: c15. 的 range 对象是被允许的，但
     某些特性 (例如 *note len(): 28b.) 可能引发 *note OverflowError:
     a41.。

     一些 range 对象的例子:

          >>> 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))
          []

     range 对象实现了 *note 一般: 1763. 序列的所有操作，但拼接和重复除外
     （这是由于 range 对象只能表示符合严格模式的序列，而重复和拼接通常都
     会违反这样的模式）。

      -- 屬性: start

          `start' 形参的值 (如果该形参未提供则为 ‘0’)

      -- 屬性: stop

          `stop' 形参的值

      -- 屬性: step

          `step' 形参的值 (如果该形参未提供则为 ‘1’)

*note range: 1f5. 类型相比常规 *note list: 1f8. 或 *note tuple: 1a2. 的
优势在于一个 *note range: 1f5. 对象总是占用固定数量的（较小）内存，不论
其所表示的范围有多大（因为它只保存了 ‘start’, ‘stop’ 和 ‘step’ 值，并会
根据需要计算具体单项或子范围的值）。

range 对象实现了 *note collections.abc.Sequence: 1764. ABC，提供如包含检
测、元素索引查找、切片等特性，并支持负索引 (参见 *note 序列类型 — list,
tuple, range: 13a4.):

     >>> 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

使用 ‘==’ 和 ‘!=’ 检测 range 对象是否相等是将其作为序列来比较。 也就是说
，如果两个 range 对象表示相同的值序列就认为它们是相等的。 （请注意比较结
果相等的两个 range 对象可能会具有不同的 *note start: 176e, *note stop:
176f. 和 *note step: 1770. 属性，例如 ‘range(0) == range(2, 1, 3)’ 而
‘range(0, 3, 2) == range(0, 4, 2)’。）

3.2 版更變: 实现 Sequence ABC。 支持切片和负数索引。 使用 *note int:
204. 对象在固定时间内进行成员检测，而不是逐一迭代所有项。

3.3 版更變: 定义 ’==’ 和 ’!=’ 以根据 range 对象所定义的值序列来进行比较
（而不是根据对象的标识）。

3.3 版新加入: *note start: 176e, *note stop: 176f. 和 *note step: 1770.
属性。

也參考
......

   * linspace recipe(1) 演示了如何实现一个延迟求值版本的适合浮点数应用的
     range 对象。

   ---------- Footnotes ----------

   (1) http://code.activestate.com/recipes/579000/


File: python.info,  Node: 文本序列类型 --- str,  Next: 二进制序列类型 --- bytes bytearray memoryview,  Prev: 序列类型 --- list tuple range,  Up: 內建型態

5.4.7 文本序列类型 — ‘str’
--------------------------

在 Python 中处理文本数据是使用 *note str: 205. 对象，也称为 `字符串'。 字
符串是由 Unicode 码位构成的不可变 *note 序列: 13a4.。 字符串字面值有多种
不同的写法：

   * 单引号: ‘'允许包含有 "双" 引号'’

   * Double quotes: ‘"allows embedded 'single' quotes"’

   * 三重引号: ‘'''三重单引号'''’, ‘"""三重双引号"""’

使用三重引号的字符串可以跨越多行 —— 其中所有的空白字符都将包含在该字符串
字面值中。

作为单一表达式组成部分，之间只由空格分隔的多个字符串字面值会被隐式地转换
为单个字符串字面值。 也就是说，‘("spam " "eggs") == "spam eggs"’。

请参阅 *note 字符串与字节串字面值: 1514. 有解有关不同字符串字面值的更多
信息，包括所支持的转义序列，以及使用 ‘r’ ("raw") 前缀来禁用大多数转义序
列的处理。

字符串也可以通过使用 *note str: 205. 构造器从其他对象创建。

由于不存在单独的“字符”类型，对字符串做索引操作将产生一个长度为 1 的字符
串。 也就是说，对于一个非空字符串 `s', ‘s[0] == s[0:1]’。

不存在可变的字符串类型，但是 *note str.join(): 1766. 或 *note
io.StringIO: 91a. 可以被被用来根据多个片段高效率地构建字符串。

3.3 版更變: 为了与 Python 2 系列的向下兼容，再次允许字符串字面值使用 ‘u’
前缀。 它对字符串字面值的含义没有影响，并且不能与 ‘r’ 前缀同时出现。

 -- 類別: str (object='')

 -- 類別: str (object=b'', encoding='utf-8', errors='strict')

     返回 `object' 的 *note 字符串: 1357. 版本。 如果未提供 `object' 则
     返回空字符串。 在其他情况下 ‘str()’ 的行为取决于 `encoding' 或
     `errors' 是否有给出，具体见下。

     如果 `encoding' 或 `errors' 均未给出，‘str(object)’ 返回 *note
     object.__str__(): ef9.，这是 `object' 的“非正式”或格式良好的字符串
     表示。 对于字符串对象，这是该字符串本身。 如果 `object' 没有 *note
     __str__(): ef9. 方法，则 *note str(): 205. 将回退为返回 *note
     repr(object): 8b9.。

     如果 `encoding' 或 `errors' 至少给出其中之一，则 `object' 应该是一
     个 *note bytes-like object: 6df. (例如 *note bytes: 172. 或 *note
     bytearray: 173.)。 在此情况下，如果 `object' 是一个 *note bytes:
     172. (或 *note bytearray: 173.) 对象，则 ‘str(bytes, encoding,
     errors)’ 等价于 *note bytes.decode(encoding, errors): 171.。 否则的
     话，会在调用 *note bytes.decode(): 171. 之前获取缓冲区对象下层的
     bytes 对象。 请参阅 *note 二进制序列类型 — bytes, bytearray,
     memoryview: 171d. 与 *note 缓冲协议: 171c. 了解有关缓冲区对象的信息
     。

     将一个 *note bytes: 172. 对象传入 *note str(): 205. 而不给出
     `encoding' 或 `errors' 参数的操作属于第一种情况， 将返回非正式的字
     符串表示（另请参阅 Python 的 *note -b: 519. 命令行选项）。 例如:

          >>> str(b'Zoot!')
          "b'Zoot!'"

     有关 ‘str’ 类及其方法的更多信息，请参阅下面的 *note 文本序列类型 —
     str: 1357. 和 *note 字符串的方法: 1358. 小节。 要输出格式化字符串，
     请参阅 *note 格式字符串字面值: 296. 和 *note 格式字符串语法: de0. 小
     节。 此外还可以参阅 *note 文本處理 (Text Processing) 服務: 1772. 小
     节。

* Menu:

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


File: python.info,  Node: 字符串的方法<2>,  Next: printf 风格的字符串格式化,  Up: 文本序列类型 --- str

5.4.7.1 字符串的方法
....................

字符串实现了所有 *note 一般: 1763. 序列的操作，还额外提供了以下列出的一
些附加方法。

字符串还支持两种字符串格式化样式，一种提供了很大程度的灵活性和可定制性
(参阅 *note str.format(): 5d4, *note 格式字符串语法: de0. 和 *note
自定义字符串格式化: 1774.) 而另一种是基于 C ‘printf’ 样式的格式化，它可
处理的类型范围较窄，并且更难以正确使用，但对于它可处理的情况往往会更为快
速 (*note printf 风格的字符串格式化: 1359.)。

标准库的 *note 文本處理 (Text Processing) 服務: 1775. 部分涵盖了许多其他
模块，提供各种文本相关工具（例如包含于 *note re: dd. 模块中的正则表达式
支持）。

 -- 成員函式: str.capitalize ()

     返回原字符串的副本，其首个字符大写，其余为小写。

     3.8 版更變: 第一个字符现在被放入了 titlecase 而不是 uppercase。 这
     意味着复合字母类字符将只有首个字母改为大写，而再不是全部字符大写。

 -- 成員函式: str.casefold ()

     返回原字符串消除大小写的副本。 消除大小写的字符串可用于忽略大小写的
     匹配。

     消除大小写类似于转为小写，但是更加彻底一些，因为它会移除字符串中的
     所有大小写变化形式。 例如，德语小写字母 ‘'ß'’ 相当于 ‘"ss"’。 由于
     它已经是小写了，*note lower(): 1777. 不会对 ‘'ß'’ 做任何改变；而
     *note casefold(): 7a3. 则会将其转换为 ‘"ss"’。

     消除大小写算法的描述请参见 Unicode 标准的 3.13 节。

     3.3 版新加入.

 -- 成員函式: str.center (width[, fillchar])

     返回长度为 `width' 的字符串，原字符串在其正中。 使用指定的
     `fillchar' 填充两边的空位（默认使用 ASCII 空格符）。 如果 `width' 小
     于等于 ‘len(s)’ 则返回原字符串的副本。

 -- 成員函式: str.count (sub[, start[, end]])

     返回子字符串 `sub' 在 [`start', `end'] 范围内非重叠出现的次数。 可
     选参数 `start' 与 `end' 会被解读为切片表示法。

 -- 成員函式: str.encode (encoding="utf-8", errors="strict")

     返回原字符串编码为字节串对象的版本。 默认编码为 ‘'utf-8'’。 可以给
     出 `errors' 来设置不同的错误处理方案。 `errors' 的默认值为
     ‘'strict'’，表示编码错误会引发 *note UnicodeError: d03.。 其他可用
     的值为 ‘'ignore'’, ‘'replace'’, ‘'xmlcharrefreplace'’,
     ‘'backslashreplace'’ 以及任何其他通过 *note
     codecs.register_error(): eb9. 注册的值，请参阅 *note 错误处理方案:
     1493. 小节。 要查看可用的编码列表，请参阅 *note 标准编码: 782. 小节
     。

     `errors' 参数默认不会被检查，以获得最佳性能，而只在第一次编码错误时
     使用。启用 *note Python 开发模式: 160. ，或者使用调试构建来检查
     `errors' 。

     3.1 版更變: 加入了对关键字参数的支持。

     3.9 版更變: `errors' 现在在开发模式和调试模式下都会被检查。

 -- 成員函式: str.endswith (suffix[, start[, end]])

     如果字符串以指定的 `suffix' 结束返回 ‘True’，否则返回 ‘False’。
     `suffix' 也可以为由多个供查找的后缀构成的元组。 如果有可选项
     `start'，将从所指定位置开始检查。 如果有可选项 `end'，将在所指定位
     置停止比较。

 -- 成員函式: str.expandtabs (tabsize=8)

     返回字符串的副本，其中所有的制表符会由一个或多个空格替换，具体取决
     于当前列位置和给定的制表符宽度。 每 `tabsize' 个字符设为一个制表位
     （默认值 8 时设定的制表位在列 0, 8, 16 依次类推）。 要展开字符串，
     当前列将被设为零并逐一检查字符串中的每个字符。 如果字符为制表符
     (‘\t’)，则会在结果中插入一个或多个空格符，直到当前列等于下一个制表
     位。 （制表符本身不会被复制。） 如果字符为换行符 (‘\n’) 或回车符
     (‘\r’)，它会被复制并将当前列重设为零。 任何其他字符会被不加修改地复
     制并将当前列加一，不论该字符在被打印时会如何显示。

          >>> '01\t012\t0123\t01234'.expandtabs()
          '01      012     0123    01234'
          >>> '01\t012\t0123\t01234'.expandtabs(4)
          '01  012 0123    01234'

 -- 成員函式: str.find (sub[, start[, end]])

     返回子字符串 `sub' 在 ‘s[start:end]’ 切片内被找到的最小索引。 可选
     参数 `start' 与 `end' 会被解读为切片表示法。 如果 `sub' 未被找到则
     返回 ‘-1’。

          備註: *note find(): 88e. 方法应该只在你需要知道 `sub' 所在位置
          时使用。 要检查 `sub' 是否为子字符串，请使用 *note in: 179. 操
          作符:

               >>> 'Py' in 'Python'
               True

 -- 成員函式: str.format (*args, **kwargs)

     执行字符串格式化操作。 调用此方法的字符串可以包含字符串字面值或者以
     花括号 ‘{}’ 括起来的替换域。 每个替换域可以包含一个位置参数的数字索
     引，或者一个关键字参数的名称。 返回的字符串副本中每个替换域都会被替
     换为对应参数的字符串值。

          >>> "The sum of 1 + 2 is {0}".format(1+2)
          'The sum of 1 + 2 is 3'

     请参阅 *note 格式字符串语法: de0. 了解有关可以在格式字符串中指定的
     各种格式选项的说明。

          備註: 当使用 ‘n’ 类型 (例如: ‘'{:n}'.format(1234)’) 来格式化数
          字 (*note int: 204, *note float: 1fd, *note complex: 2c1,
          *note decimal.Decimal: 2c0. 及其子类) 的时候，该函数会临时性地
          将 ‘LC_CTYPE’ 区域设置为 ‘LC_NUMERIC’ 区域以解码
          ‘localeconv()’ 的 ‘decimal_point’ 和 ‘thousands_sep’ 字段，如
          果它们是非 ASCII 字符或长度超过 1 字节的话，并且 ‘LC_NUMERIC’
          区域会与 ‘LC_CTYPE’ 区域不一致。 这个临时更改会影响其他线程。

     3.7 版更變: 当使用 ‘n’ 类型格式化数字时，该函数在某些情况下会临时性
     地将 ‘LC_CTYPE’ 区域设置为 ‘LC_NUMERIC’ 区域。

 -- 成員函式: str.format_map (mapping)

     类似于 ‘str.format(**mapping)’，不同之处在于 ‘mapping’ 会被直接使用
     而不是复制到一个 *note dict: 164.。 适宜使用此方法的一个例子是当
     ‘mapping’ 为 dict 的子类的情况：

          >>> class Default(dict):
          ...     def __missing__(self, key):
          ...         return key
          ...
          >>> '{name} was born in {country}'.format_map(Default(name='Guido'))
          'Guido was born in country'

     3.2 版新加入.

 -- 成員函式: str.index (sub[, start[, end]])

     类似于 *note find(): 88e.，但在找不到子类时会引发 *note ValueError:
     16d.。

 -- 成員函式: str.isalnum ()

     如果字符串中的所有字符都是字母或数字且至少有一个字符，则返回 ‘True’
     ， 否则返回 ‘False’ 。 如果 ‘c.isalpha()’ ， ‘c.isdecimal()’ ，
     ‘c.isdigit()’ ，或 ‘c.isnumeric()’ 之中有一个返回 ‘True’ ，则字符
     ‘‘c‘‘是字母或数字。

 -- 成員函式: str.isalpha ()

     如果字符串中的所有字符都是字母，并且至少有一个字符，返回 ‘True’ ，
     否则返回 ‘False’ 。字母字符是指那些在 Unicode 字符数据库中定义为
     "Letter" 的字符，即那些具有 "Lm"、"Lt"、"Lu"、"Ll" 或 "Lo" 之一的通
     用类别属性的字符。 注意，这与 Unicode 标准中定义的"字母"属性不同。

 -- 成員函式: str.isascii ()

     如果字符串为空或字符串中的所有字符都是 ASCII ，返回 ‘True’ ，否则返
     回 ‘False’ 。ASCII 字符的码点范围是 U+0000-U+007F 。

     3.7 版新加入.

 -- 成員函式: str.isdecimal ()

     如果字符串中的所有字符都是十进制字符且该字符串至少有一个字符，则返
     回 ‘True’ ， 否则返回 ‘False’ 。十进制字符指那些可以用来组成10进制
     数字的字符，例如 U+0660 ，即阿拉伯字母数字0 。 严格地讲，十进制字符
     是 Unicode 通用类别 "Nd" 中的一个字符。

 -- 成員函式: str.isdigit ()

     如果字符串中的所有字符都是数字，并且至少有一个字符，返回 ‘True’ ，
     否则返回 ‘False’ 。 数字包括十进制字符和需要特殊处理的数字，如兼容
     性上标数字。这包括了不能用来组成 10 进制数的数字，如 Kharosthi 数。
     严格地讲，数字是指属性值为 Numeric_Type=Digit 或
     Numeric_Type=Decimal 的字符。

 -- 成員函式: str.isidentifier ()

     如果字符串是有效的标识符，返回 ‘True’ ，依据语言定义， *note
     标识符和关键字: 1505. 节。

     调用 *note keyword.iskeyword(): 177f. 来检测字符串 ‘s’ 是否为保留标
     识符，例如 *note def: e83. 和 *note class: d32.。

     示例：

          >>> from keyword import iskeyword

          >>> 'hello'.isidentifier(), iskeyword('hello')
          (True, False)
          >>> 'def'.isidentifier(), iskeyword('def')
          (True, True)

 -- 成員函式: str.islower ()

     如果字符串中至少有一个区分大小写的字符 (1) 且此类字符均为小写则返回
     ‘True’ ，否则返回 ‘False’ 。

 -- 成員函式: str.isnumeric ()

     如果字符串中至少有一个字符且所有字符均为数值字符则返回 ‘True’ ，否
     则返回 ‘False’ 。 数值字符包括数字字符，以及所有在 Unicode 中设置了
     数值特性属性的字符，例如 U+2155, VULGAR FRACTION ONE FIFTH。 正式的
     定义为：数值字符就是具有特征属性值 Numeric_Type=Digit,
     Numeric_Type=Decimal 或 Numeric_Type=Numeric 的字符。

 -- 成員函式: str.isprintable ()

     如果字符串中所有字符均为可打印字符或字符串为空则返回 ‘True’ ，否则
     返回 ‘False’ 。 不可打印字符是在 Unicode 字符数据库中被定义为
     "Other" 或 "Separator" 的字符，例外情况是 ASCII 空格字符 (0x20) 被
     视作可打印字符。 （请注意在此语境下可打印字符是指当对一个字符串发起
     调用 *note repr(): 8b9. 时不必被转义的字符。 它们与字符串写入 *note
     sys.stdout: 41f. 或 *note sys.stderr: 1ea. 时所需的处理无关。）

 -- 成員函式: str.isspace ()

     如果字符串中只有空白字符且至少有一个字符则返回 ‘True’ ，否则返回
     ‘False’ 。

     `空白' 字符是指在 Unicode 字符数据库 (参见 *note unicodedata: 123.)
     中主要类别为 ‘Zs’ ("Separator, space") 或所属双向类为 ‘WS’, ‘B’ 或
     ‘S’ 的字符。

 -- 成員函式: str.istitle ()

     如果字符串中至少有一个字符且为标题字符串则返回 ‘True’ ，例如大写字
     符之后只能带非大写字符而小写字符必须有大写字符打头。 否则返回
     ‘False’ 。

 -- 成員函式: str.isupper ()

     如果字符串中至少有一个区分大小写的字符 (2) 且此类字符均为大写则返回
     ‘True’ ，否则返回 ‘False’ 。

          >>> 'BANANA'.isupper()
          True
          >>> 'banana'.isupper()
          False
          >>> 'baNana'.isupper()
          False
          >>> ' '.isupper()
          False

 -- 成員函式: str.join (iterable)

     返回一个由 `iterable' 中的字符串拼接而成的字符串。 如果 `iterable'
     中存在任何非字符串值包括 *note bytes: 172. 对象则会引发 *note
     TypeError: 1fe.。 调用该方法的字符串将作为元素之间的分隔。

 -- 成員函式: str.ljust (width[, fillchar])

     返回长度为 `width' 的字符串，原字符串在其中靠左对齐。 使用指定的
     `fillchar' 填充空位 (默认使用 ASCII 空格符)。 如果 `width' 小于等于
     ‘len(s)’ 则返回原字符串的副本。

 -- 成員函式: str.lower ()

     返回原字符串的副本，其所有区分大小写的字符 (3) 均转换为小写。

     所用转换小写算法的描述请参见 Unicode 标准的 3.13 节。

 -- 成員函式: str.lstrip ([chars])

     返回原字符串的副本，移除其中的前导字符。 `chars' 参数为指定要移除字
     符的字符串。 如果省略或为 ‘None’，则 `chars' 参数默认移除空白符。 实
     际上 `chars' 参数并非指定单个前缀；而是会移除参数值的所有组合:

          >>> '   spacious   '.lstrip()
          'spacious   '
          >>> 'www.example.com'.lstrip('cmowz.')
          'example.com'

     参见 *note str.removeprefix(): 166. ，该方法将删除单个前缀字符串，
     而不是全部给定集合中的字符。 例如:

          >>> 'Arthur: three!'.lstrip('Arthur: ')
          'ee!'
          >>> 'Arthur: three!'.removeprefix('Arthur: ')
          'three!'

 -- 成員函式: static str.maketrans (x[, y[, z]])

     此静态方法返回一个可供 *note str.translate(): 1786. 使用的转换对照
     表。

     如果只有一个参数，则它必须是一个将 Unicode 码位序号（整数）或字符（
     长度为 1 的字符串）映射到 Unicode 码位序号、（任意长度的）字符串或
     ‘None’ 的字典。 字符键将会被转换为码位序号。

     如果有两个参数，则它们必须是两个长度相等的字符串，并且在结果字典中
     ，x 中每个字符将被映射到 y 中相同位置的字符。 如果有第三个参数，它
     必须是一个字符串，其中的字符将在结果中被映射到 ‘None’。

 -- 成員函式: str.partition (sep)

     在 `sep' 首次出现的位置拆分字符串，返回一个 3 元组，其中包含分隔符
     之前的部分、分隔符本身，以及分隔符之后的部分。 如果分隔符未找到，则
     返回的 3 元组中包含字符本身以及两个空字符串。

 -- 成員函式: str.removeprefix (prefix, /)

     如果字符串以 `前缀' 字符串开头，返回 ‘string[len(prefix):]’ 。否则
     ，返回原始字符串的副本：

          >>> 'TestHook'.removeprefix('Test')
          'Hook'
          >>> 'BaseTestCase'.removeprefix('Test')
          'BaseTestCase'

     3.9 版新加入.

 -- 成員函式: str.removesuffix (suffix, /)

     如果字符串以 `后缀' 字符串结尾，并且 `后缀' 非空，返回
     ‘string[:-len(suffix)]’ 。否则，返回原始字符串的副本：

          >>> 'MiscTests'.removesuffix('Tests')
          'Misc'
          >>> 'TmpDirMixin'.removesuffix('Tests')
          'TmpDirMixin'

     3.9 版新加入.

 -- 成員函式: str.replace (old, new[, count])

     返回字符串的副本，其中出现的所有子字符串 `old' 都将被替换为 `new'。
     如果给出了可选参数 `count'，则只替换前 `count' 次出现。

 -- 成員函式: str.rfind (sub[, start[, end]])

     返回子字符串 `sub' 在字符串内被找到的最大（最右）索引，这样 `sub' 将
     包含在 ‘s[start:end]’ 当中。 可选参数 `start' 与 `end' 会被解读为切
     片表示法。 如果未找到则返回 ‘-1’。

 -- 成員函式: str.rindex (sub[, start[, end]])

     类似于 *note rfind(): 88f.，但在子字符串 `sub' 未找到时会引发 *note
     ValueError: 16d.。

 -- 成員函式: str.rjust (width[, fillchar])

     返回长度为 `width' 的字符串，原字符串在其中靠右对齐。 使用指定的
     `fillchar' 填充空位 (默认使用 ASCII 空格符)。 如果 `width' 小于等于
     ‘len(s)’ 则返回原字符串的副本。

 -- 成員函式: str.rpartition (sep)

     在 `sep' 最后一次出现的位置拆分字符串，返回一个 3 元组，其中包含分
     隔符之前的部分、分隔符本身，以及分隔符之后的部分。 如果分隔符未找到
     ，则返回的 3 元组中包含两个空字符串以及字符串本身。

 -- 成員函式: str.rsplit (sep=None, maxsplit=-1)

     返回一个由字符串内单词组成的列表，使用 `sep' 作为分隔字符串。 如果
     给出了 `maxsplit'，则最多进行 `maxsplit' 次拆分，从 `最右边' 开始。
     如果 `sep' 未指定或为 ‘None’，任何空白字符串都会被作为分隔符。 除了
     从右边开始拆分，*note rsplit(): 178a. 的其他行为都类似于下文所述的
     *note split(): 890.。

 -- 成員函式: str.rstrip ([chars])

     返回原字符串的副本，移除其中的末尾字符。 `chars' 参数为指定要移除字
     符的字符串。 如果省略或为 ‘None’，则 `chars' 参数默认移除空白符。 实
     际上 `chars' 参数并非指定单个后缀；而是会移除参数值的所有组合:

          >>> '   spacious   '.rstrip()
          '   spacious'
          >>> 'mississippi'.rstrip('ipz')
          'mississ'

     要删除单个后缀字符串，而不是全部给定集合中的字符，请参见 *note
     str.removesuffix(): 167. 方法。 例如:

          >>> 'Monty Python'.rstrip(' Python')
          'M'
          >>> 'Monty Python'.removesuffix(' Python')
          'Monty'

 -- 成員函式: str.split (sep=None, maxsplit=-1)

     返回一个由字符串内单词组成的列表，使用 `sep' 作为分隔字符串。 如果
     给出了 `maxsplit'，则最多进行 `maxsplit' 次拆分（因此，列表最多会有
     ‘maxsplit+1’ 个元素）。 如果 `maxsplit' 未指定或为 ‘-1’，则不限制拆
     分次数（进行所有可能的拆分）。

     如果给出了 `sep'，则连续的分隔符不会被组合在一起而是被视为分隔空字
     符串 (例如 ‘'1,,2'.split(',')’ 将返回 ‘['1', '', '2']’)。 `sep' 参
     数可能由多个字符组成 (例如 ‘'1<>2<>3'.split('<>')’ 将返回 ‘['1',
     '2', '3']’)。 使用指定的分隔符拆分空字符串将返回 ‘['']’。

     例如:

          >>> '1,2,3'.split(',')
          ['1', '2', '3']
          >>> '1,2,3'.split(',', maxsplit=1)
          ['1', '2,3']
          >>> '1,2,,3,'.split(',')
          ['1', '2', '', '3', '']

     如果 `sep' 未指定或为 ‘None’，则会应用另一种拆分算法：连续的空格会
     被视为单个分隔符，其结果将不包含开头或末尾的空字符串，如果字符串包
     含前缀或后缀空格的话。 因此，使用 ‘None’ 拆分空字符串或仅包含空格的
     字符串将返回 ‘[]’。

     例如:

          >>> '1 2 3'.split()
          ['1', '2', '3']
          >>> '1 2 3'.split(maxsplit=1)
          ['1', '2 3']
          >>> '   1   2   3   '.split()
          ['1', '2', '3']

 -- 成員函式: str.splitlines (keepends=False)

     返回由原字符串中各行组成的列表，在行边界的位置拆分。 结果列表中不包
     含行边界，除非给出了 `keepends' 且为真值。

     此方法会以下列行边界进行拆分。 特别地，行边界是 *note universal
     newlines: 6eb. 的一个超集。

     表示符                      描述
                                 
     --------------------------------------------------------------
                                 
     ‘\n’                        换行
                                 
                                 
     ‘\r’                        回车
                                 
                                 
     ‘\r\n’                      回车 + 换行
                                 
                                 
     ‘\v’ 或 ‘\x0b’              行制表符
                                 
                                 
     ‘\f’ 或 ‘\x0c’              换表单
                                 
                                 
     ‘\x1c’                      文件分隔符
                                 
                                 
     ‘\x1d’                      组分隔符
                                 
                                 
     ‘\x1e’                      记录分隔符
                                 
                                 
     ‘\x85’                      下一行 (C1 控制码)
                                 
                                 
     ‘\u2028’                    行分隔符
                                 
                                 
     ‘\u2029’                    段分隔符
                                 

     3.2 版更變: ‘\v’ 和 ‘\f’ 被添加到行边界列表

     例如:

          >>> 'ab c\n\nde fg\rkl\r\n'.splitlines()
          ['ab c', '', 'de fg', 'kl']
          >>> 'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
          ['ab c\n', '\n', 'de fg\r', 'kl\r\n']

     不同于 *note split(): 890.，当给出了分隔字符串 `sep' 时，对于空字符
     串此方法将返回一个空列表，而末尾的换行不会令结果中增加额外的行:

          >>> "".splitlines()
          []
          >>> "One line\n".splitlines()
          ['One line']

     作为比较，‘split('\n')’ 的结果为:

          >>> ''.split('\n')
          ['']
          >>> 'Two lines\n'.split('\n')
          ['Two lines', '']

 -- 成員函式: str.startswith (prefix[, start[, end]])

     如果字符串以指定的 `prefix' 开始则返回 ‘True’，否则返回 ‘False’。
     `prefix' 也可以为由多个供查找的前缀构成的元组。 如果有可选项
     `start'，将从所指定位置开始检查。 如果有可选项 `end'，将在所指定位
     置停止比较。

 -- 成員函式: str.strip ([chars])

     返回原字符串的副本，移除其中的前导和末尾字符。 `chars' 参数为指定要
     移除字符的字符串。 如果省略或为 ‘None’，则 `chars' 参数默认移除空白
     符。 实际上 `chars' 参数并非指定单个前缀或后缀；而是会移除参数值的
     所有组合:

          >>> '   spacious   '.strip()
          'spacious'
          >>> 'www.example.com'.strip('cmowz.')
          'example'

     最外侧的前导和末尾 `chars' 参数值将从字符串中移除。 开头端的字符的
     移除将在遇到一个未包含于 `chars' 所指定字符集的字符时停止。 类似的
     操作也将在结尾端发生。 例如:

          >>> comment_string = '#....... Section 3.2.1 Issue #32 .......'
          >>> comment_string.strip('.#! ')
          'Section 3.2.1 Issue #32'

 -- 成員函式: str.swapcase ()

     返回原字符串的副本，其中大写字符转换为小写，反之亦然。 请注意
     ‘s.swapcase().swapcase() == s’ 并不一定为真值。

 -- 成員函式: str.title ()

     返回原字符串的标题版本，其中每个单词第一个字母为大写，其余字母为小
     写。

     例如:

          >>> 'Hello world'.title()
          'Hello World'

     该算法使用一种简单的与语言无关的定义，将连续的字母组合视为单词。 该
     定义在多数情况下都很有效，但它也意味着代表缩写形式与所有格的撇号也
     会成为单词边界，这可能导致不希望的结果:

          >>> "they're bill's friends from the UK".title()
          "They'Re Bill'S Friends From The Uk"

     可以使用正则表达式来构建针对撇号的特别处理:

          >>> 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."

 -- 成員函式: str.translate (table)

     返回原字符串的副本，其中每个字符按给定的转换表进行映射。 转换表必须
     是一个使用 *note __getitem__(): 3a5. 来实现索引操作的对象，通常为
     *note mapping: c0b. 或 *note sequence: 135c.。 当以 Unicode 码位序
     号（整数）为索引时，转换表对象可以做以下任何一种操作：返回 Unicode
     序号或字符串，将字符映射为一个或多个字符；返回 ‘None’，将字符从结果
     字符串中删除；或引发 *note LookupError: 1790. 异常，将字符映射为其
     自身。

     你可以使用 *note str.maketrans(): 7a6. 基于不同格式的字符到字符映射
     来创建一个转换映射表。

     另请参阅 *note codecs: 1b. 模块以了解定制字符映射的更灵活方式。

 -- 成員函式: str.upper ()

     返回原字符串的副本，其中所有区分大小写的字符 (4) 均转换为大写。 请
     注意如果 ‘s’ 包含不区分大小写的字符或者如果结果字符的 Unicode 类别
     不是 "Lu" (Letter, uppercase) 而是 "Lt" (Letter, titlecase) 则
     ‘s.upper().isupper()’ 有可能为 ‘False’。

     所用转换大写算法的描述请参见 Unicode 标准的 3.13 节。

 -- 成員函式: str.zfill (width)

     返回原字符串的副本，在左边填充 ASCII ‘'0'’ 数码使其长度变为
     `width'。 正负值前缀 (‘'+'’/‘'-'’) 的处理方式是在正负符号 `之后' 填
     充而非在之前。 如果 `width' 小于等于 ‘len(s)’ 则返回原字符串的副本
     。

     例如:

          >>> "42".zfill(5)
          '00042'
          >>> "-42".zfill(5)
          '-0042'

   ---------- Footnotes ----------

   (1) (4) 区分大小写的字符是指所属一般类别属性为 "Lu" (Letter,
uppercase), "Ll" (Letter, lowercase) 或 "Lt" (Letter, titlecase) 之一的
字符。

   (2) (4) 区分大小写的字符是指所属一般类别属性为 "Lu" (Letter,
uppercase), "Ll" (Letter, lowercase) 或 "Lt" (Letter, titlecase) 之一的
字符。

   (3) (4) 区分大小写的字符是指所属一般类别属性为 "Lu" (Letter,
uppercase), "Ll" (Letter, lowercase) 或 "Lt" (Letter, titlecase) 之一的
字符。

   (4) (4) 区分大小写的字符是指所属一般类别属性为 "Lu" (Letter,
uppercase), "Ll" (Letter, lowercase) 或 "Lt" (Letter, titlecase) 之一的
字符。


File: python.info,  Node: printf 风格的字符串格式化,  Prev: 字符串的方法<2>,  Up: 文本序列类型 --- str

5.4.7.2 ‘printf’ 风格的字符串格式化
...................................

     備註: 此处介绍的格式化操作具有多种怪异特性，可能导致许多常见错误（
     例如无法正确显示元组和字典）。 使用较新的 *note 格式化字符串字面值:
     296.，*note str.format(): 5d4. 接口或 *note 模板字符串: 1793. 有助
     于避免这样的错误。 这些替代方案中的每一种都更好地权衡并提供了简单、
     灵活以及可扩展性优势。

字符串具有一种特殊的内置操作：使用 ‘%’ (取模) 运算符。 这也被称为字符串
的 `格式化' 或 `插值' 运算符。 对于 ‘format % values’ (其中 `format' 为
一个字符串)，在 `format' 中的 ‘%’ 转换标记符将被替换为零个或多个
`values' 条目。 其效果类似于在 C 语言中使用 ‘sprintf()’。

如果 `format' 要求一个单独参数，则 `values' 可以为一个非元组对象。 (1) 否
则的话，`values' 必须或者是一个包含项数与格式字符串中指定的转换符项数相
同的元组，或者是一个单独映射对象（例如字典）。

转换标记符包含两个或更多字符并具有以下组成，且必须遵循此处规定的顺序：

  1. ‘'%'’ 字符，用于标记转换符的起始。

  2. 映射键（可选），由加圆括号的字符序列组成 (例如 ‘(somename)’)。

  3. 转换旗标（可选），用于影响某些转换类型的结果。

  4. 最小字段宽度（可选）。 如果指定为 ‘'*'’ (星号)，则实际宽度会从
     `values' 元组的下一元素中读取，要转换的对象则为最小字段宽度和可选的
     精度之后的元素。

  5. 精度（可选），以在 ‘'.'’ (点号) 之后加精度值的形式给出。 如果指定为
     ‘'*'’ (星号)，则实际精度会从 `values' 元组的下一元素中读取，要转换
     的对象则为精度之后的元素。

  6. 长度修饰符（可选）。

  7. 转换类型。

当右边的参数为一个字典（或其他映射类型）时，字符串中的格式 `必须' 包含加
圆括号的映射键，对应 ‘'%'’ 字符之后字典中的每一项。 映射键将从映射中选取
要格式化的值。 例如：

     >>> print('%(language)s has %(number)03d quote types.' %
     ...       {'language': "Python", "number": 2})
     Python has 002 quote types.

在此情况下格式中不能出现 ‘*’ 标记符（因其需要一个序列类的参数列表）。

转换旗标为：

标志          含义
              
----------------------------------------------------------------------------------------
              
‘'#'’         值的转换将使用“替代形式”（具体定义见下文）。
              
              
‘'0'’         转换将为数字值填充零字符。
              
              
‘'-'’         转换值将靠左对齐（如果同时给出 ‘'0'’ 转换，则会覆盖后者）。
              
              
‘' '’         (空格) 符号位转换产生的正数（或空字符串）前将留出一个空格。
              
              
‘'+'’         符号字符 (‘'+'’ 或 ‘'-'’) 将显示于转换结果的开头（会覆盖 "空格" 旗标）
              。
              

可以给出长度修饰符 (‘h’, ‘l’ 或 ‘L’)，但会被忽略，因为对 Python 来说没有
必要 – 所以 ‘%ld’ 等价于 ‘%d’。

转换类型为：

转换符           含义                                                      註解
                                                                           
---------------------------------------------------------------------------------------
                                                                           
‘'d'’            有符号十进制整数。
                 
                                                                           
‘'i'’            有符号十进制整数。
                 
                                                                           
‘'o'’            有符号八进制数。                                          (1)
                                                                           
                                                                           
‘'u'’            过时类型 – 等价于 ‘'d'’。                                 (6)
                                                                           
                                                                           
‘'x'’            有符号十六进制数（小写）。                                (2)
                                                                           
                                                                           
‘'X'’            有符号十六进制数（大写）。                                (2)
                                                                           
                                                                           
‘'e'’            浮点指数格式（小写）。                                    (3)
                                                                           
                                                                           
‘'E'’            浮点指数格式（大写）。                                    (3)
                                                                           
                                                                           
‘'f'’            浮点十进制格式。                                          (3)
                                                                           
                                                                           
‘'F'’            浮点十进制格式。                                          (3)
                                                                           
                                                                           
‘'g'’            浮点格式。 如果指数小于 -4 或不小于精度则使用小写指数格   (4)
                 式，否则使用十进制格式。                                  
                 
                                                                           
‘'G'’            浮点格式。 如果指数小于 -4 或不小于精度则使用大写指数格   (4)
                 式，否则使用十进制格式。                                  
                 
                                                                           
‘'c'’            单个字符（接受整数或单个字符的字符串）。
                 
                                                                           
‘'r'’            字符串（使用 *note repr(): 8b9. 转换任何 Python 对象）    (5)
                 。                                                        
                 
                                                                           
‘'s'’            字符串（使用 *note str(): 205. 转换任何 Python 对象）。   (5)
                                                                           
                                                                           
‘'a'’            字符串（使用 *note ascii(): e11. 转换任何 Python 对象）   (5)
                 。                                                        
                 
                                                                           
‘'%'’            不转换参数，在结果中输出一个 ‘'%'’ 字符。
                 

註解：

  1. 此替代形式会在第一个数码之前插入标示八进制数的前缀 (‘'0o'’)。

  2. 此替代形式会在第一个数码之前插入 ‘'0x'’ 或 ‘'0X'’ 前缀（取决于是使
     用 ‘'x'’ 还是 ‘'X'’ 格式）。

  3. 此替代形式总是会在结果中包含一个小数点，即使其后并没有数码。

     小数点后的数码位数由精度决定，默认为 6。

  4. 此替代形式总是会在结果中包含一个小数点，末尾各位的零不会如其他情况
     下那样被移除。

     小数点前后的有效数码位数由精度决定，默认为 6。

  5. 如果精度为 ‘N’，输出将截短为 ‘N’ 个字符。

  6. 参见 PEP 237(2)。

由于 Python 字符串显式指明长度，‘%s’ 转换不会将 ‘'\0'’ 视为字符串的结束
。

3.1 版更變: 绝对值超过 1e50 的 ‘%f’ 转换不会再被替换为 ‘%g’ 转换。

   ---------- Footnotes ----------

   (1) (5) 要格式化单独一个元组，那么你应当提供一个单例元组，其唯一的元
素就是要被格式化的元组。

   (2) https://www.python.org/dev/peps/pep-0237


File: python.info,  Node: 二进制序列类型 --- bytes bytearray memoryview,  Next: 集合类型 --- set frozenset,  Prev: 文本序列类型 --- str,  Up: 內建型態

5.4.8 二进制序列类型 — ‘bytes’, ‘bytearray’, ‘memoryview’
---------------------------------------------------------

操作二进制数据的核心内置类型是 *note bytes: 172. 和 *note bytearray:
173.。 它们由 *note memoryview: 386. 提供支持，该对象使用 *note
缓冲区协议: 171c. 来访问其他二进制对象所在内存，不需要创建对象的副本。

*note array: 6. 模块支持高效地存储基本数据类型，例如 32 位整数和 IEEE754
双精度浮点值。

* Menu:

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


File: python.info,  Node: bytes 对象,  Next: bytearray 对象,  Up: 二进制序列类型 --- bytes bytearray memoryview

5.4.8.1 bytes 对象
..................

bytes 对象是由单个字节构成的不可变序列。 由于许多主要二进制协议都基于
ASCII 文本编码，因此 bytes 对象提供了一些仅在处理 ASCII 兼容数据时可用，
并且在许多特性上与字符串对象紧密相关的方法。

 -- 類別: bytes ([source[, encoding[, errors]]])

     首先，表示 bytes 字面值的语法与字符串字面值的大致相同，只是添加了一
     个 ‘b’ 前缀：

        * 单引号: ‘b'同样允许嵌入 "双" 引号'’。

        * Double quotes: ‘b"still allows embedded 'single' quotes"’

        * 三重引号: ‘b'''三重单引号'''’, ‘b"""三重双引号"""’

     bytes 字面值中只允许 ASCII 字符（无论源代码声明的编码为何）。 任何
     超出 127 的二进制值必须使用相应的转义序列形式加入 bytes 字面值。

     像字符串字面值一样，bytes 字面值也可以使用 ‘r’ 前缀来禁用转义序列处
     理。 请参阅 *note 字符串与字节串字面值: 1514. 了解有关各种 bytes 字
     面值形式的详情，包括所支持的转义序列。

     虽然 bytes 字面值和表示法是基于 ASCII 文本的，但 bytes 对象的行为实
     际上更像是不可变的整数序列，序列中的每个值的大小被限制为 ‘0 <= x <
     256’ (如果违反此限制将引发 *note ValueError: 16d.)。 这种限制是有意
     设计用以强调以下事实，虽然许多二进制格式都包含基于 ASCII 的元素，可
     以通过某些面向文本的算法进行有用的操作，但情况对于任意二进制数据来
     说通常却并非如此（盲目地将文本处理算法应用于不兼容 ASCII 的二进制数
     据格式往往将导致数据损坏）。

     除了字面值形式，bytes 对象还可以通过其他几种方式来创建：

        * 指定长度的以零值填充的 bytes 对象: ‘bytes(10)’

        * 通过由整数组成的可迭代对象: ‘bytes(range(20))’

        * 通过缓冲区协议复制现有的二进制数据: ‘bytes(obj)’

     另请参阅 *note bytes: 11f2. 内置类型。

     由于两个十六进制数码精确对应一个字节，因此十六进制数是描述二进制数
     据的常用格式。 相应地，bytes 类型具有从此种格式读取数据的附加类方法
     ：

      -- 成員函式: classmethod fromhex (string)

          此 *note bytes: 172. 类方法返回一个解码给定字符串的 bytes 对象
          。 字符串必须由表示每个字节的两个十六进制数码构成，其中的
          ASCII 空白符会被忽略。

               >>> bytes.fromhex('2Ef0 F1f2  ')
               b'.\xf0\xf1\xf2'

          3.7 版更變: *note bytes.fromhex(): 43e. 现在会忽略所有 ASCII 空
          白符而不只是空格符。

     存在一个反向转换函数，可以将 bytes 对象转换为对应的十六进制表示。

      -- 成員函式: hex ([sep[, bytes_per_sep]])

          返回一个字符串对象，该对象包含实例中每个字节的两个十六进制数字
          。

               >>> b'\xf0\xf1\xf2'.hex()
               'f0f1f2'

          如果你希望令十六进制数字符串更易读，你可以指定单个字符分隔符作
          为 `sep' 形参包含于输出中。 默认会放在每个字节之间。 第二个可
          选的 `bytes_per_sep' 形参控制间距。 正值会从右开始计算分隔符的
          位置，负值则是从左开始。

               >>> value = b'\xf0\xf1\xf2'
               >>> value.hex('-')
               'f0-f1-f2'
               >>> value.hex('_', 2)
               'f0_f1f2'
               >>> b'UUDDLRLRAB'.hex(' ', -4)
               '55554444 4c524c52 4142'

          3.5 版新加入.

          3.8 版更變: *note bytes.hex(): 724. 现在支持可选的 `sep' 和
          `bytes_per_sep' 形参以在十六进制输出的字节之间插入分隔符。

由于 bytes 对象是由整数构成的序列（类似于元组），因此对于一个 bytes 对象
`b'，‘b[0]’ 将为一个整数，而 ‘b[0:1]’ 将为一个长度为 1 的 bytes 对象。 （
这与文本字符串不同，索引和切片所产生的将都是一个长度为 1 的字符串）。

bytes 对象的表示使用字面值格式 (‘b'...'’)，因为它通常都要比像
‘bytes([46, 46, 46])’ 这样的格式更好用。 你总是可以使用 ‘list(b)’ 将
bytes 对象转换为一个由整数构成的列表。

     備註: 针对 Python 2.x 用户的说明：在 Python 2.x 系列中，允许 8 位字
     符串（ 2.x 所提供的最接近内置二进制数据类型的对象）与 Unicode 字符
     串进行各种隐式转换。 这是为了实现向下兼容的变通做法，以适应 Python
     最初只支持 8 位文本而 Unicode 文本是后来才被加入这一事实。 在
     Python 3.x 中，这些隐式转换已被取消 —— 8 位二进制数据与 Unicode 文
     本间的转换必须显式地进行，bytes 与字符串对象的比较结果将总是不相等
     。


File: python.info,  Node: bytearray 对象,  Next: bytes 和 bytearray 操作,  Prev: bytes 对象,  Up: 二进制序列类型 --- bytes bytearray memoryview

5.4.8.2 bytearray 对象
......................

*note bytearray: 173. 对象是 *note bytes: 172. 对象的可变对应物。

 -- 類別: bytearray ([source[, encoding[, errors]]])

     bytearray 对象没有专属的字面值语法，它们总是通过调用构造器来创建：

        * 创建一个空实例: ‘bytearray()’

        * 创建一个指定长度的以零值填充的实例: ‘bytearray(10)’

        * 通过由整数组成的可迭代对象: ‘bytearray(range(20))’

        * 通过缓冲区协议复制现有的二进制数据: ‘bytearray(b'Hi!')’

     由于 bytearray 对象是可变的，该对象除了 *note bytes 和 bytearray
     操作: 171b. 中所描述的 bytes 和 bytearray 共有操作之外，还支持
     *note 可变: 171a. 序列操作。

     另请参见 *note bytearray: 11f3. 内置类型。

     由于两个十六进制数码精确对应一个字节，因此十六进制数是描述二进制数
     据的常用格式。 相应地，bytearray 类型具有从此种格式读取数据的附加类
     方法：

      -- 成員函式: classmethod fromhex (string)

          *note bytearray: 173. 类方法返回一个解码给定字符串的 bytearray
          对象。 字符串必须由表示每个字节的两个十六进制数码构成，其中的
          ASCII 空白符会被忽略。

               >>> bytearray.fromhex('2Ef0 F1f2  ')
               bytearray(b'.\xf0\xf1\xf2')

          3.7 版更變: *note bytearray.fromhex(): 43f. 现在会忽略所有
          ASCII 空白符而不只是空格符。

     存在一个反向转换函数，可以将 bytearray 对象转换为对应的十六进制表示
     。

      -- 成員函式: hex ([sep[, bytes_per_sep]])

          返回一个字符串对象，该对象包含实例中每个字节的两个十六进制数字
          。

               >>> bytearray(b'\xf0\xf1\xf2').hex()
               'f0f1f2'

          3.5 版新加入.

          3.8 版更變: 与 *note bytes.hex(): 724. 相似， *note
          bytearray.hex(): 725. 现在支持可选的 `sep' 和 `bytes_per_sep'
          参数以在十六进制输出的字节之间插入分隔符。

由于 bytearray 对象是由整数构成的序列（类似于列表），因此对于一个
bytearray 对象 `b'，‘b[0]’ 将为一个整数，而 ‘b[0:1]’ 将为一个长度为 1 的
bytearray 对象。 （这与文本字符串不同，索引和切片所产生的将都是一个长度
为 1 的字符串）。

bytearray 对象的表示使用 bytes 对象字面值格式 (‘bytearray(b'...')’)，因
为它通常都要比 ‘bytearray([46, 46, 46])’ 这样的格式更好用。 你总是可以使
用 ‘list(b)’ 将 bytearray 对象转换为一个由整数构成的列表。


File: python.info,  Node: bytes 和 bytearray 操作,  Next: printf 风格的字节串格式化,  Prev: bytearray 对象,  Up: 二进制序列类型 --- bytes bytearray memoryview

5.4.8.3 bytes 和 bytearray 操作
...............................

bytes 和 bytearray 对象都支持 *note 通用: 1763. 序列操作。 它们不仅能与
相同类型的操作数，也能与任何 *note bytes-like object: 6df. 进行互操作。
由于这样的灵活性，它们可以在操作中自由地混合而不会导致错误。 但是，操作
结果的返回值类型可能取决于操作数的顺序。

     備註: bytes 和 bytearray 对象的方法不接受字符串作为其参数，就像字符
     串的方法不接受 bytes 对象作为其参数一样。 例如，你必须使用以下写法:

          a = "abc"
          b = a.replace("a", "f")

     和:

          a = b"abc"
          b = a.replace(b"a", b"f")

某些 bytes 和 bytearray 操作假定使用兼容 ASCII 的二进制格式，因此在处理
任意二进数数据时应当避免使用。 这些限制会在下文中说明。

     備註: 使用这些基于 ASCII 的操作来处理未以基于 ASCII 的格式存储的二
     进制数据可能会导致数据损坏。

bytes 和 bytearray 对象的下列方法可以用于任意二进制数据。

 -- 成員函式: bytes.count (sub[, start[, end]])
 -- 成員函式: bytearray.count (sub[, start[, end]])

     返回子序列 `sub' 在 [`start', `end'] 范围内非重叠出现的次数。 可选
     参数 `start' 与 `end' 会被解读为切片表示法。

     要搜索的子序列可以是任意 *note bytes-like object: 6df. 或是 0 至
     255 范围内的整数。

     3.3 版更變: 也接受 0 至 255 范围内的整数作为子序列。

 -- 成員函式: bytes.removeprefix (prefix, /)
 -- 成員函式: bytearray.removeprefix (prefix, /)

     如果二进制数据以 `前缀' 字符串开头，返回 ‘bytes[len(prefix):]’ 。否
     则，返回原始二进制数据的副本：

          >>> b'TestHook'.removeprefix(b'Test')
          b'Hook'
          >>> b'BaseTestCase'.removeprefix(b'Test')
          b'BaseTestCase'

     前缀可以是任意 *note bytes-like object: 6df.。

          備註: 此方法的 bytearray 版本 `并非' 原地操作 —— 它总是产生一
          个新对象，即便没有做任何改变。

     3.9 版新加入.

 -- 成員函式: bytes.removesuffix (suffix, /)
 -- 成員函式: bytearray.removesuffix (suffix, /)

     如果二进制数据以 `后缀' 字符串结尾，并且 `后缀' 非空，返回
     ‘bytes[:-len(suffix)]’ 。否则，返回原始二进制数据的副本：

          >>> b'MiscTests'.removesuffix(b'Tests')
          b'Misc'
          >>> b'TmpDirMixin'.removesuffix(b'Tests')
          b'TmpDirMixin'

     后缀可以是任意 *note bytes-like object: 6df.。

          備註: 此方法的 bytearray 版本 `并非' 原地操作 —— 它总是产生一
          个新对象，即便没有做任何改变。

     3.9 版新加入.

 -- 成員函式: bytes.decode (encoding="utf-8", errors="strict")
 -- 成員函式: bytearray.decode (encoding="utf-8", errors="strict")

     返回从给定 bytes 解码出来的字符串。 默认编码为 ‘'utf-8'’。 可以给出
     `errors' 来设置不同的错误处理方案。 `errors' 的默认值为 ‘'strict'’，
     表示编码错误会引发 *note UnicodeError: d03.。 其他可用的值为
     ‘'ignore'’, ‘'replace'’ 以及任何其他通过 *note
     codecs.register_error(): eb9. 注册的名称，请参阅 *note
     错误处理方案: 1493. 小节。 要查看可用的编码列表，请参阅 *note
     标准编码: 782. 小节。

     `errors' 参数默认不会被检查，以获得最佳性能，而只在第一次解码错误时
     使用。启用 *note Python 开发模式: 160. ，或者使用调试构建来检查
     `errors' 。

          備註: 将 `encoding' 参数传给 *note str: 205. 允许直接解码任何
          *note bytes-like object: 6df.，无须创建临时的 bytes 或
          bytearray 对象。

     3.1 版更變: 加入了对关键字参数的支持。

     3.9 版更變: `errors' 现在在开发模式和调试模式下都会被检查。

 -- 成員函式: bytes.endswith (suffix[, start[, end]])
 -- 成員函式: bytearray.endswith (suffix[, start[, end]])

     如果二进制数据以指定的 `suffix' 结束则返回 ‘True’，否则返回
     ‘False’。 `suffix' 也可以为由多个供查找的后缀构成的元组。 如果有可
     选项 `start'，将从所指定位置开始检查。 如果有可选项 `end'，将在所指
     定位置停止比较。

     要搜索的后缀可以是任意 *note bytes-like object: 6df.。

 -- 成員函式: bytes.find (sub[, start[, end]])
 -- 成員函式: bytearray.find (sub[, start[, end]])

     返回子序列 `sub' 在数据中被找到的最小索引，`sub' 包含于切片
     ‘s[start:end]’ 之内。 可选参数 `start' 与 `end' 会被解读为切片表示
     法。 如果 `sub' 未被找到则返回 ‘-1’。

     要搜索的子序列可以是任意 *note bytes-like object: 6df. 或是 0 至
     255 范围内的整数。

          備註: *note find(): 17a1. 方法应该只在你需要知道 `sub' 所在位
          置时使用。 要检查 `sub' 是否为子串，请使用 *note in: 179. 操作
          符:

               >>> b'Py' in b'Python'
               True

     3.3 版更變: 也接受 0 至 255 范围内的整数作为子序列。

 -- 成員函式: bytes.index (sub[, start[, end]])
 -- 成員函式: bytearray.index (sub[, start[, end]])

     类似于 *note find(): 17a1.，但在找不到子序列时会引发 *note
     ValueError: 16d.。

     要搜索的子序列可以是任意 *note bytes-like object: 6df. 或是 0 至
     255 范围内的整数。

     3.3 版更變: 也接受 0 至 255 范围内的整数作为子序列。

 -- 成員函式: bytes.join (iterable)
 -- 成員函式: bytearray.join (iterable)

     返回一个由 `iterable' 中的二进制数据序列拼接而成的 bytes 或
     bytearray 对象。 如果 `iterable' 中存在任何非 *note 字节类对象:
     6df. 包括存在 *note str: 205. 对象值则会引发 *note TypeError: 1fe.。
     提供该方法的 bytes 或 bytearray 对象的内容将作为元素之间的分隔。

 -- 成員函式: static bytes.maketrans (from, to)
 -- 成員函式: static bytearray.maketrans (from, to)

     此静态方法返回一个可用于 *note bytes.translate(): 17a6. 的转换对照
     表，它将把 `from' 中的每个字符映射为 `to' 中相同位置上的字符；
     `from' 与 `to' 必须都是 *note 字节类对象: 6df. 并且具有相同的长度。

     3.1 版新加入.

 -- 成員函式: bytes.partition (sep)
 -- 成員函式: bytearray.partition (sep)

     在 `sep' 首次出现的位置拆分序列，返回一个 3 元组，其中包含分隔符之
     前的部分、分隔符本身或其 bytearray 副本，以及分隔符之后的部分。 如
     果分隔符未找到，则返回的 3 元组中包含原序列以及两个空的 bytes 或
     bytearray 对象。

     要搜索的分隔符可以是任意 *note bytes-like object: 6df.。

 -- 成員函式: bytes.replace (old, new[, count])
 -- 成員函式: bytearray.replace (old, new[, count])

     返回序列的副本，其中出现的所有子序列 `old' 都将被替换为 `new'。 如
     果给出了可选参数 `count'，则只替换前 `count' 次出现。

     要搜索的子序列及其替换序列可以是任意 *note bytes-like object: 6df.。

          備註: 此方法的 bytearray 版本 `并非' 原地操作 —— 它总是产生一
          个新对象，即便没有做任何改变。

 -- 成員函式: bytes.rfind (sub[, start[, end]])
 -- 成員函式: bytearray.rfind (sub[, start[, end]])

     返回子序列 `sub' 在序列内被找到的最大（最右）索引，这样 `sub' 将包
     含在 ‘s[start:end]’ 当中。 可选参数 `start' 与 `end' 会被解读为切片
     表示法。 如果未找到则返回 ‘-1’。

     要搜索的子序列可以是任意 *note bytes-like object: 6df. 或是 0 至
     255 范围内的整数。

     3.3 版更變: 也接受 0 至 255 范围内的整数作为子序列。

 -- 成員函式: bytes.rindex (sub[, start[, end]])
 -- 成員函式: bytearray.rindex (sub[, start[, end]])

     类似于 *note rfind(): 17ab.，但在子序列 `sub' 未找到时会引发 *note
     ValueError: 16d.。

     要搜索的子序列可以是任意 *note bytes-like object: 6df. 或是 0 至
     255 范围内的整数。

     3.3 版更變: 也接受 0 至 255 范围内的整数作为子序列。

 -- 成員函式: bytes.rpartition (sep)
 -- 成員函式: bytearray.rpartition (sep)

     在 `sep' 最后一次出现的位置拆分序列，返回一个 3 元组，其中包含分隔
     符之前的部分，分隔符本身或其 bytearray 副本，以及分隔符之后的部分。
     如果分隔符未找到，则返回的 3 元组中包含两个空的 bytes 或 bytearray
     对象以及原序列的副本。

     要搜索的分隔符可以是任意 *note bytes-like object: 6df.。

 -- 成員函式: bytes.startswith (prefix[, start[, end]])
 -- 成員函式: bytearray.startswith (prefix[, start[, end]])

     如果二进制数据以指定的 `prefix' 开头则返回 ‘True’，否则返回
     ‘False’。 `prefix' 也可以为由多个供查找的前缀构成的元组。 如果有可
     选项 `start'，将从所指定位置开始检查。 如果有可选项 `end'，将在所指
     定位置停止比较。

     要搜索的前缀可以是任意 *note bytes-like object: 6df.。

 -- 成員函式: bytes.translate (table, /, delete=b'')
 -- 成員函式: bytearray.translate (table, /, delete=b'')

     返回原 bytes 或 bytearray 对象的副本，移除其中所有在可选参数
     `delete' 中出现的 bytes，其余 bytes 将通过给定的转换表进行映射，该
     转换表必须是长度为 256 的 bytes 对象。

     你可以使用 *note bytes.maketrans(): cd4. 方法来创建转换表。

     对于仅需移除字符的转换，请将 `table' 参数设为 ‘None’:

          >>> b'read this short text'.translate(None, b'aeiou')
          b'rd ths shrt txt'

     3.6 版更變: 现在支持将 `delete' 作为关键字参数。

以下 bytes 和 bytearray 对象的方法的默认行为会假定使用兼容 ASCII 的二进
制格式，但通过传入适当的参数仍然可用于任意二进制数据。 请注意本小节中所
有的 bytearray 方法都 `不是' 原地执行操作，而是会产生新的对象。

 -- 成員函式: bytes.center (width[, fillbyte])
 -- 成員函式: bytearray.center (width[, fillbyte])

     返回原对象的副本，在长度为 `width' 的序列内居中，使用指定的
     `fillbyte' 填充两边的空位（默认使用 ASCII 空格符）。 对于 *note
     bytes: 172. 对象，如果 `width' 小于等于 ‘len(s)’ 则返回原序列的副本
     。

          備註: 此方法的 bytearray 版本 `并非' 原地操作 —— 它总是产生一
          个新对象，即便没有做任何改变。

 -- 成員函式: bytes.ljust (width[, fillbyte])
 -- 成員函式: bytearray.ljust (width[, fillbyte])

     返回原对象的副本，在长度为 `width' 的序列中靠左对齐。 使用指定的
     `fillbyte' 填充空位（默认使用 ASCII 空格符）。 对于 *note bytes:
     172. 对象，如果 `width' 小于等于 ‘len(s)’ 则返回原序列的副本。

          備註: 此方法的 bytearray 版本 `并非' 原地操作 —— 它总是产生一
          个新对象，即便没有做任何改变。

 -- 成員函式: bytes.lstrip ([chars])
 -- 成員函式: bytearray.lstrip ([chars])

     返回原序列的副本，移除指定的前导字节。 `chars' 参数为指定要移除字节
     值集合的二进制序列 —— 这个名称表明此方法通常是用于 ASCII 字符。 如
     果省略或为 ‘None’，则 `chars' 参数默认移除 ASCII 空白符。 `chars' 参
     数并非指定单个前缀；而是会移除参数值的所有组合:

          >>> b'   spacious   '.lstrip()
          b'spacious   '
          >>> b'www.example.com'.lstrip(b'cmowz.')
          b'example.com'

     要移除的二进制序列可以是任意 *note bytes-like object: 6df. 。 要删
     除单个前缀字符串，而不是全部给定集合中的字符，请参见 *note
     str.removeprefix(): 166. 方法。 例如:

          >>> b'Arthur: three!'.lstrip(b'Arthur: ')
          b'ee!'
          >>> b'Arthur: three!'.removeprefix(b'Arthur: ')
          b'three!'

          備註: 此方法的 bytearray 版本 `并非' 原地操作 —— 它总是产生一
          个新对象，即便没有做任何改变。

 -- 成員函式: bytes.rjust (width[, fillbyte])
 -- 成員函式: bytearray.rjust (width[, fillbyte])

     返回原对象的副本，在长度为 `width' 的序列中靠右对齐。 使用指定的
     `fillbyte' 填充空位（默认使用 ASCII 空格符）。 对于 *note bytes:
     172. 对象，如果 `width' 小于等于 ‘len(s)’ 则返回原序列的副本。

          備註: 此方法的 bytearray 版本 `并非' 原地操作 —— 它总是产生一
          个新对象，即便没有做任何改变。

 -- 成員函式: bytes.rsplit (sep=None, maxsplit=-1)
 -- 成員函式: bytearray.rsplit (sep=None, maxsplit=-1)

     将二进制序列拆分为相同类型的子序列，使用 `sep' 作为分隔符。 如果给
     出了 `maxsplit'，则最多进行 `maxsplit' 次拆分，从 `最右边' 开始。 如
     果 `sep' 未指定或为 ‘None’，任何只包含 ASCII 空白符的子序列都会被作
     为分隔符。 除了从右边开始拆分，*note rsplit(): 17bc. 的其他行为都类
     似于下文所述的 *note split(): 17bd.。

 -- 成員函式: bytes.rstrip ([chars])
 -- 成員函式: bytearray.rstrip ([chars])

     返回原序列的副本，移除指定的末尾字节。 `chars' 参数为指定要移除字节
     值集合的二进制序列 —— 这个名称表明此方法通常是用于 ASCII 字符。 如
     果省略或为 ‘None’，则 `chars' 参数默认移除 ASCII 空白符。 `chars' 参
     数并非指定单个后缀；而是会移除参数值的所有组合:

          >>> b'   spacious   '.rstrip()
          b'   spacious'
          >>> b'mississippi'.rstrip(b'ipz')
          b'mississ'

     要移除的二进制序列可以是任意 *note bytes-like object: 6df. 。 要删
     除单个后缀字符串，而不是全部给定集合中的字符，请参见 *note
     str.removesuffix(): 167. 方法。 例如:

          >>> b'Monty Python'.rstrip(b' Python')
          b'M'
          >>> b'Monty Python'.removesuffix(b' Python')
          b'Monty'

          備註: 此方法的 bytearray 版本 `并非' 原地操作 —— 它总是产生一
          个新对象，即便没有做任何改变。

 -- 成員函式: bytes.split (sep=None, maxsplit=-1)
 -- 成員函式: bytearray.split (sep=None, maxsplit=-1)

     将二进制序列拆分为相同类型的子序列，使用 `sep' 作为分隔符。 如果给
     出了 `maxsplit' 且非负值，则最多进行 `maxsplit' 次拆分（因此，列表
     最多会有 ‘maxsplit+1’ 个元素）。 如果 `maxsplit' 未指定或为 ‘-1’，
     则不限制拆分次数（进行所有可能的拆分）。

     如果给出了 `sep'，则连续的分隔符不会被组合在一起而是被视为分隔空子
     序列 (例如 ‘b'1,,2'.split(b',')’ 将返回 ‘[b'1', b'', b'2']’)。
     `sep' 参数可能为一个多字节序列 (例如 ‘b'1<>2<>3'.split(b'<>')’ 将返
     回 ‘[b'1', b'2', b'3']’)。 使用指定的分隔符拆分空序列将返回 ‘[b'']’
     或 ‘[bytearray(b'')]’，具体取决于被拆分对象的类型。 `sep' 参数可以
     是任意 *note bytes-like object: 6df.。

     例如:

          >>> 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'', b'3', b'']

     如果 `sep' 未指定或为 ‘None’，则会应用另一种拆分算法：连续的 ASCII
     空白符会被视为单个分隔符，其结果将不包含序列开头或末尾的空白符。 因
     此，在不指定分隔符的情况下对空序列或仅包含 ASCII 空白符的序列进行拆
     分将返回 ‘[]’。

     例如:

          >>> 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']

 -- 成員函式: bytes.strip ([chars])
 -- 成員函式: bytearray.strip ([chars])

     返回原序列的副本，移除指定的开头和末尾字节。 `chars' 参数为指定要移
     除字节值集合的二进制序列 —— 这个名称表明此方法通常是用于 ASCII 字符
     。 如果省略或为 ‘None’，则 `chars' 参数默认移除 ASCII 空白符。
     `chars' 参数并非指定单个前缀或后缀；而是会移除参数值的所有组合:

          >>> b'   spacious   '.strip()
          b'spacious'
          >>> b'www.example.com'.strip(b'cmowz.')
          b'example'

     要移除的字节值二进制序列可以是任意 *note bytes-like object: 6df.。

          備註: 此方法的 bytearray 版本 `并非' 原地操作 —— 它总是产生一
          个新对象，即便没有做任何改变。

以下 bytes 和 bytearray 对象的方法会假定使用兼容 ASCII 的二进制格式，不
应当被应用于任意二进制数据。 请注意本小节中所有的 bytearray 方法都 `不是
' 原地执行操作，而是会产生新的对象。

 -- 成員函式: bytes.capitalize ()
 -- 成員函式: bytearray.capitalize ()

     返回原序列的副本，其中每个字节将都将被解读为一个 ASCII 字符，并且第
     一个字节的字符大写而其余的小写。 非 ASCII 字节值将保持原样不变。

          備註: 此方法的 bytearray 版本 `并非' 原地操作 —— 它总是产生一
          个新对象，即便没有做任何改变。

 -- 成員函式: bytes.expandtabs (tabsize=8)
 -- 成員函式: bytearray.expandtabs (tabsize=8)

     返回序列的副本，其中所有的 ASCII 制表符会由一个或多个 ASCII 空格替
     换，具体取决于当前列位置和给定的制表符宽度。 每 `tabsize' 个字节设
     为一个制表位（默认值 8 时设定的制表位在列 0, 8, 16 依次类推）。 要
     展开序列，当前列位置将被设为零并逐一检查序列中的每个字节。 如果字节
     为 ASCII 制表符 (‘b'\t'’)，则并在结果中插入一个或多个空格符，直到当
     前列等于下一个制表位。 （制表符本身不会被复制。） 如果当前字节为
     ASCII 换行符 (‘b'\n'’) 或回车符 (‘b'\r'’)，它会被复制并将当前列重设
     为零。 任何其他字节会被不加修改地复制并将当前列加一，不论该字节值在
     被打印时会如何显示:

          >>> b'01\t012\t0123\t01234'.expandtabs()
          b'01      012     0123    01234'
          >>> b'01\t012\t0123\t01234'.expandtabs(4)
          b'01  012 0123    01234'

          備註: 此方法的 bytearray 版本 `并非' 原地操作 —— 它总是产生一
          个新对象，即便没有做任何改变。

 -- 成員函式: bytes.isalnum ()
 -- 成員函式: bytearray.isalnum ()

     如果序列中所有字节都是字母类 ASCII 字符或 ASCII 十进制数码并且序列
     非空则返回 ‘True’ ，否则返回 ‘False’ 。 字母类 ASCII 字符就是字节值
     包含在序列
     ‘b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'’ 中的字符
     。 ASCII 十进制数码就是字节值包含在序列 ‘b'0123456789'’ 中的字符。

     例如:

          >>> b'ABCabc1'.isalnum()
          True
          >>> b'ABC abc1'.isalnum()
          False

 -- 成員函式: bytes.isalpha ()
 -- 成員函式: bytearray.isalpha ()

     如果序列中所有字节都是字母类 ASCII 字符并且序列不非空则返回 ‘True’
     ，否则返回 ‘False’ 。 字母类 ASCII 字符就是字节值包含在序列
     ‘b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'’ 中的字符
     。

     例如:

          >>> b'ABCabc'.isalpha()
          True
          >>> b'ABCabc1'.isalpha()
          False

 -- 成員函式: bytes.isascii ()
 -- 成員函式: bytearray.isascii ()

     如果序列为空或序列中所有字节都是 ASCII 字节则返回 ‘True’ ，否则返回
     ‘False’ 。 ASCII 字节的取值范围是 0-0x7F。

     3.7 版新加入.

 -- 成員函式: bytes.isdigit ()
 -- 成員函式: bytearray.isdigit ()

     如果序列中所有字节都是 ASCII 十进制数码并且序列非空则返回 ‘True’ ，
     否则返回 ‘False’ 。 ASCII 十进制数码就是字节值包含在序列
     ‘b'0123456789'’ 中的字符。

     例如:

          >>> b'1234'.isdigit()
          True
          >>> b'1.23'.isdigit()
          False

 -- 成員函式: bytes.islower ()
 -- 成員函式: bytearray.islower ()

     如果序列中至少有一个小写的 ASCII 字符并且没有大写的 ASCII 字符则返
     回 ‘True’ ，否则返回 ‘False’ 。

     例如:

          >>> b'hello world'.islower()
          True
          >>> b'Hello world'.islower()
          False

     小写 ASCII 字符就是字节值包含在序列 ‘b'abcdefghijklmnopqrstuvwxyz'’
     中的字符。 大写 ASCII 字符就是字节值包含在序列
     ‘b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'’ 中的字符。

 -- 成員函式: bytes.isspace ()
 -- 成員函式: bytearray.isspace ()

     如果序列中所有字节都是 ASCII 空白符并且序列非空则返回 ‘True’ ，否则
     返回 ‘False’ 。 ASCII 空白符就是字节值包含在序列 ‘b' \t\n\r\x0b\f'’
     (空格, 制表, 换行, 回车, 垂直制表, 进纸) 中的字符。

 -- 成員函式: bytes.istitle ()
 -- 成員函式: bytearray.istitle ()

     如果序列为 ASCII 标题大小写形式并且序列非空则返回 ‘True’ ，否则返回
     ‘False’ 。 请参阅 *note bytes.title(): 17d5. 了解有关“标题大小写”的
     详细定义。

     例如:

          >>> b'Hello World'.istitle()
          True
          >>> b'Hello world'.istitle()
          False

 -- 成員函式: bytes.isupper ()
 -- 成員函式: bytearray.isupper ()

     如果序列中至少有一个大写字母 ASCII 字符并且没有小写 ASCII 字符则返
     回 ‘True’ ，否则返回 ‘False’ 。

     例如:

          >>> b'HELLO WORLD'.isupper()
          True
          >>> b'Hello world'.isupper()
          False

     小写 ASCII 字符就是字节值包含在序列 ‘b'abcdefghijklmnopqrstuvwxyz'’
     中的字符。 大写 ASCII 字符就是字节值包含在序列
     ‘b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'’ 中的字符。

 -- 成員函式: bytes.lower ()
 -- 成員函式: bytearray.lower ()

     返回原序列的副本，其所有大写 ASCII 字符均转换为对应的小写形式。

     例如:

          >>> b'Hello World'.lower()
          b'hello world'

     小写 ASCII 字符就是字节值包含在序列 ‘b'abcdefghijklmnopqrstuvwxyz'’
     中的字符。 大写 ASCII 字符就是字节值包含在序列
     ‘b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'’ 中的字符。

          備註: 此方法的 bytearray 版本 `并非' 原地操作 —— 它总是产生一
          个新对象，即便没有做任何改变。

 -- 成員函式: bytes.splitlines (keepends=False)
 -- 成員函式: bytearray.splitlines (keepends=False)

     返回由原二进制序列中各行组成的列表，在 ASCII 行边界符的位置拆分。 此
     方法使用 *note universal newlines: 6eb. 方式来分行。 结果列表中不包
     含换行符，除非给出了 `keepends' 且为真值。

     例如:

          >>> b'ab c\n\nde fg\rkl\r\n'.splitlines()
          [b'ab c', b'', 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']

     不同于 *note split(): 17c0.，当给出了分隔符 `sep' 时，对于空字符串
     此方法将返回一个空列表，而末尾的换行不会令结果中增加额外的行:

          >>> b"".split(b'\n'), b"Two lines\n".split(b'\n')
          ([b''], [b'Two lines', b''])
          >>> b"".splitlines(), b"One line\n".splitlines()
          ([], [b'One line'])

 -- 成員函式: bytes.swapcase ()
 -- 成員函式: bytearray.swapcase ()

     返回原序列的副本，其所有小写 ASCII 字符均转换为对应的大写形式，反之
     亦反。

     例如:

          >>> b'Hello World'.swapcase()
          b'hELLO wORLD'

     小写 ASCII 字符就是字节值包含在序列 ‘b'abcdefghijklmnopqrstuvwxyz'’
     中的字符。 大写 ASCII 字符就是字节值包含在序列
     ‘b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'’ 中的字符。

     不同于 *note str.swapcase(): 178e.，在些二进制版本下
     ‘bin.swapcase().swapcase() == bin’ 总是成立。 大小写转换在 ASCII 中
     是对称的，即使其对于任意 Unicode 码位来说并不总是成立。

          備註: 此方法的 bytearray 版本 `并非' 原地操作 —— 它总是产生一
          个新对象，即便没有做任何改变。

 -- 成員函式: bytes.title ()
 -- 成員函式: bytearray.title ()

     返回原二进制序列的标题版本，其中每个单词以一个大写 ASCII 字符为开头
     ，其余字母为小写。 不区别大小写的字节值将保持原样不变。

     例如:

          >>> b'Hello world'.title()
          b'Hello World'

     小写 ASCII 字符就是字节值包含在序列 ‘b'abcdefghijklmnopqrstuvwxyz'’
     中的字符。 大写 ASCII 字符就是字节值包含在序列
     ‘b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'’ 中的字符。 所有其他字节值都不区分大
     小写。

     该算法使用一种简单的与语言无关的定义，将连续的字母组合视为单词。 该
     定义在多数情况下都很有效，但它也意味着代表缩写形式与所有格的撇号也
     会成为单词边界，这可能导致不希望的结果:

          >>> b"they're bill's friends from the UK".title()
          b"They'Re Bill'S Friends From The Uk"

     可以使用正则表达式来构建针对撇号的特别处理:

          >>> 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."

          備註: 此方法的 bytearray 版本 `并非' 原地操作 —— 它总是产生一
          个新对象，即便没有做任何改变。

 -- 成員函式: bytes.upper ()
 -- 成員函式: bytearray.upper ()

     返回原序列的副本，其所有小写 ASCII 字符均转换为对应的大写形式。

     例如:

          >>> b'Hello World'.upper()
          b'HELLO WORLD'

     小写 ASCII 字符就是字节值包含在序列 ‘b'abcdefghijklmnopqrstuvwxyz'’
     中的字符。 大写 ASCII 字符就是字节值包含在序列
     ‘b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'’ 中的字符。

          備註: 此方法的 bytearray 版本 `并非' 原地操作 —— 它总是产生一
          个新对象，即便没有做任何改变。

 -- 成員函式: bytes.zfill (width)
 -- 成員函式: bytearray.zfill (width)

     返回原序列的副本，在左边填充 ‘b'0'’ 数码使序列长度为 `width'。 正负
     值前缀 (‘b'+'’/ ‘b'-'’) 的处理方式是在正负符号 `之后' 填充而非在之
     前。 对于 *note bytes: 172. 对象，如果 `width' 小于等于 ‘len(seq)’
     则返回原序列。

     例如:

          >>> b"42".zfill(5)
          b'00042'
          >>> b"-42".zfill(5)
          b'-0042'

          備註: 此方法的 bytearray 版本 `并非' 原地操作 —— 它总是产生一
          个新对象，即便没有做任何改变。


File: python.info,  Node: printf 风格的字节串格式化,  Next: 内存视图,  Prev: bytes 和 bytearray 操作,  Up: 二进制序列类型 --- bytes bytearray memoryview

5.4.8.4 ‘printf’ 风格的字节串格式化
...................................

     備註: 此处介绍的格式化操作具有多种怪异特性，可能导致许多常见错误（
     例如无法正确显示元组和字典）。 如果要打印的值可能为元组或字典，请将
     其放入一个元组中。

字节串对象 (‘bytes’/‘bytearray’) 具有一种特殊的内置操作：使用 ‘%’ (取模)
运算符。 这也被称为字节串的 `格式化' 或 `插值' 运算符。 对于 ‘format %
values’ (其中 `format' 为一个字节串对象)，在 `format' 中的 ‘%’ 转换标记
符将被替换为零个或多个 `values' 条目。 其效果类似于在 C 语言中使用
‘sprintf()’。

如果 `format' 要求一个单独参数，则 `values' 可以为一个非元组对象。 (1) 否
则的话，`values' 必须或是是一个包含项数与格式字节串对象中指定的转换符项
数相同的元组，或者是一个单独的映射对象（例如元组）。

转换标记符包含两个或更多字符并具有以下组成，且必须遵循此处规定的顺序：

  1. ‘'%'’ 字符，用于标记转换符的起始。

  2. 映射键（可选），由加圆括号的字符序列组成 (例如 ‘(somename)’)。

  3. 转换旗标（可选），用于影响某些转换类型的结果。

  4. 最小字段宽度（可选）。 如果指定为 ‘'*'’ (星号)，则实际宽度会从
     `values' 元组的下一元素中读取，要转换的对象则为最小字段宽度和可选的
     精度之后的元素。

  5. 精度（可选），以在 ‘'.'’ (点号) 之后加精度值的形式给出。 如果指定为
     ‘'*'’ (星号)，则实际精度会从 `values' 元组的下一元素中读取，要转换
     的对象则为精度之后的元素。

  6. 长度修饰符（可选）。

  7. 转换类型。

当右边的参数为一个字典（或其他映射类型）时，字节串对象中的格式 `必须' 包
含加圆括号的映射键，对应 ‘'%'’ 字符之后字典中的每一项。 映射键将从映射中
选取要格式化的值。 例如：

     >>> print(b'%(language)s has %(number)03d quote types.' %
     ...       {b'language': b"Python", b"number": 2})
     b'Python has 002 quote types.'

在此情况下格式中不能出现 ‘*’ 标记符（因其需要一个序列类的参数列表）。

转换旗标为：

标志          含义
              
----------------------------------------------------------------------------------------
              
‘'#'’         值的转换将使用“替代形式”（具体定义见下文）。
              
              
‘'0'’         转换将为数字值填充零字符。
              
              
‘'-'’         转换值将靠左对齐（如果同时给出 ‘'0'’ 转换，则会覆盖后者）。
              
              
‘' '’         (空格) 符号位转换产生的正数（或空字符串）前将留出一个空格。
              
              
‘'+'’         符号字符 (‘'+'’ 或 ‘'-'’) 将显示于转换结果的开头（会覆盖 "空格" 旗标）
              。
              

可以给出长度修饰符 (‘h’, ‘l’ 或 ‘L’)，但会被忽略，因为对 Python 来说没有
必要 – 所以 ‘%ld’ 等价于 ‘%d’。

转换类型为：

转换符           含义                                                      註解
                                                                           
---------------------------------------------------------------------------------------
                                                                           
‘'d'’            有符号十进制整数。
                 
                                                                           
‘'i'’            有符号十进制整数。
                 
                                                                           
‘'o'’            有符号八进制数。                                          (1)
                                                                           
                                                                           
‘'u'’            过时类型 – 等价于 ‘'d'’。                                 (8)
                                                                           
                                                                           
‘'x'’            有符号十六进制数（小写）。                                (2)
                                                                           
                                                                           
‘'X'’            有符号十六进制数（大写）。                                (2)
                                                                           
                                                                           
‘'e'’            浮点指数格式（小写）。                                    (3)
                                                                           
                                                                           
‘'E'’            浮点指数格式（大写）。                                    (3)
                                                                           
                                                                           
‘'f'’            浮点十进制格式。                                          (3)
                                                                           
                                                                           
‘'F'’            浮点十进制格式。                                          (3)
                                                                           
                                                                           
‘'g'’            浮点格式。 如果指数小于 -4 或不小于精度则使用小写指数格   (4)
                 式，否则使用十进制格式。                                  
                 
                                                                           
‘'G'’            浮点格式。 如果指数小于 -4 或不小于精度则使用大写指数格   (4)
                 式，否则使用十进制格式。                                  
                 
                                                                           
‘'c'’            单个字节（接受整数或单个字节对象）。
                 
                                                                           
‘'b'’            字节串（任何遵循 *note 缓冲区协议: 171c. 或是具有         (5)
                 *note __bytes__(): 156a. 的对象）。                       
                 
                                                                           
‘'s'’            ‘'s'’ 是 ‘'b'’ 的一个别名，只应当在基于 Python2/3 的代    (6)
                 码中使用。                                                
                 
                                                                           
‘'a'’            字节串（使用                                              (5)
                 ‘repr(obj).encode('ascii','backslashreplace)’ 转换任何    
                 Python 对象）。
                 
                                                                           
‘'r'’            ‘'r'’ 是 ‘'a'’ 的一个别名，只应当在基于 Python2/3 的代    (7)
                 码中使用。                                                
                 
                                                                           
‘'%'’            不转换参数，在结果中输出一个 ‘'%'’ 字符。
                 

註解：

  1. 此替代形式会在第一个数码之前插入标示八进制数的前缀 (‘'0o'’)。

  2. 此替代形式会在第一个数码之前插入 ‘'0x'’ 或 ‘'0X'’ 前缀（取决于是使
     用 ‘'x'’ 还是 ‘'X'’ 格式）。

  3. 此替代形式总是会在结果中包含一个小数点，即使其后并没有数码。

     小数点后的数码位数由精度决定，默认为 6。

  4. 此替代形式总是会在结果中包含一个小数点，末尾各位的零不会如其他情况
     下那样被移除。

     小数点前后的有效数码位数由精度决定，默认为 6。

  5. 如果精度为 ‘N’，输出将截短为 ‘N’ 个字符。

  6. ‘b'%s'’ 已弃用，但在 3.x 系列中将不会被移除。

  7. ‘b'%r'’ 已弃用，但在 3.x 系列中将不会被移除。

  8. 参见 PEP 237(2)。

     備註: 此方法的 bytearray 版本 `并非' 原地操作 —— 它总是产生一个新对
     象，即便没有做任何改变。

也參考
......

PEP 461(3) - 为 bytes 和 bytearray 添加 % 格式化

3.5 版新加入.

   ---------- Footnotes ----------

   (1) (5) 要格式化单独一个元组，那么你应当提供一个单例元组，其唯一的元
素就是要被格式化的元组。

   (2) https://www.python.org/dev/peps/pep-0237

   (3) https://www.python.org/dev/peps/pep-0461


File: python.info,  Node: 内存视图,  Prev: printf 风格的字节串格式化,  Up: 二进制序列类型 --- bytes bytearray memoryview

5.4.8.5 内存视图
................

*note memoryview: 386. 对象允许 Python 代码访问一个对象的内部数据，只要
该对象支持 *note 缓冲区协议: 171c. 而无需进行拷贝。

 -- 類別: memoryview (object)

     创建一个引用 `object' 的 *note memoryview: 386. 。 `object' 必须支
     持缓冲区协议。支持缓冲区协议的内置对象有 *note bytes: 172. 和 *note
     bytearray: 173. 。

     *note memoryview: 386. 有 `元素' 的概念， `元素' 指由原始 `object'
     处理的原子内存单元。对于许多简单的类型，如 *note bytes: 172. 和
     *note bytearray: 173. ，一个元素是一个字节，但其他类型，如 *note
     array.array: 216. 可能有更大的元素。

     ‘len(view)’ 与 *note tolist: 17e5. 的长度相等。 如果 ‘view.ndim =
     0’，则其长度为 1。 如果 ‘view.ndim = 1’，则其长度等于 view 中元素的
     数量。 对于更高的维度，其长度等于表示 view 的嵌套列表的长度。 *note
     itemsize: 17e6. 属性可向你给出单个元素所占的字节数。

     *note memoryview: 386. 支持通过切片和索引访问其元素。 一维切片的结
     果将是一个子视图:

          >>> v = memoryview(b'abcefg')
          >>> v[1]
          98
          >>> v[-1]
          103
          >>> v[1:4]
          <memory at 0x7f3ddc9f4350>
          >>> bytes(v[1:4])
          b'bce'

     如果 *note format: 17e7. 是一个来自于 *note struct: f8. 模块的原生
     格式说明符，则也支持使用整数或由整数构成的元组进行索引，并返回具有
     正确类型的单个 `元素'。 一维内存视图可以使用一个整数或由一个整数构
     成的元组进行索引。 多维内存视图可以使用由恰好 `ndim' 个整数构成的元
     素进行索引，`ndim' 即其维度。 零维内存视图可以使用空元组进行索引。

     这里是一个使用非字节格式的例子:

          >>> import array
          >>> a = array.array('l', [-11111111, 22222222, -33333333, 44444444])
          >>> m = memoryview(a)
          >>> m[0]
          -11111111
          >>> m[-1]
          44444444
          >>> m[::2].tolist()
          [-11111111, -33333333]

     如果下层对象是可写的，则内存视图支持一维切片赋值。 改变大小则不被允
     许:

          >>> 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')

     由带有格式符号 ’B’, ’b’ 或 ’c’ 的可哈希（只读）类型构成的一维内存视
     图同样是可哈希的。 哈希定义为 ‘hash(m) == hash(m.tobytes())’:

          >>> 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

     3.3 版更變: 一维内存视图现在可以被切片。 带有格式符号 ’B’, ’b’ 或
     ’c’ 的一维内存视图现在是可哈希的。

     3.4 版更變: 内存视图现在会自动注册为 *note
     collections.abc.Sequence: 1764.

     3.5 版更變: 内存视图现在可使用整数元组进行索引。

     *note memoryview: 386. 具有以下一些方法：

      -- 成員函式: __eq__ (exporter)

          memoryview 与 PEP 3118(1) 中的导出器这两者如果形状相同，并且如
          果当使用 *note struct: f8. 语法解读操作数的相应格式代码时所有
          对应值都相同，则它们就是等价的。

          对于 *note tolist(): 17e5. 当前所支持的 *note struct: f8. 格式
          字符串子集，如果 ‘v.tolist() == w.tolist()’ 则 ‘v’ 和 ‘w’ 相等
          :

               >>> 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

          如果两边的格式字符串都不被 *note struct: f8. 模块所支持，则两
          对象比较结果总是不相等（即使格式字符串和缓冲区内容相同）:

               >>> 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

          请注意，与浮点数的情况一样，对于内存视图对象来说，‘v is w’ 也
          `并不' 意味着 ‘v == w’。

          3.3 版更變: 之前的版本比较原始内存时会忽略条目的格式与逻辑数组
          结构。

      -- 成員函式: tobytes (order=None)

          将缓冲区中的数据作为字节串返回。 这相当于在内存视图上调用
          *note bytes: 172. 构造器。

               >>> m = memoryview(b"abc")
               >>> m.tobytes()
               b'abc'
               >>> bytes(m)
               b'abc'

          对于非连续数组，结果等于平面化表示的列表，其中所有元素都转换为
          字节串。 *note tobytes(): 17e9. 支持所有格式字符串，不符合
          *note struct: f8. 模块语法的那些也包括在内。

          3.8 版新加入: `order' 可以为 {’C’, ’F’, ’A’}。 当 `order' 为
          ’C’ 或 ’F’ 时，原始数组的数据会被转换至 C 或 Fortran 顺序。 对
          于连续视图，’A’ 会返回物理内存的精确副本。 特别地，内存中的
          Fortran 顺序会被保留。对于非连续视图，数据会先被转换为 C 形式
          。 `order=None' 与 `order=’C’' 是相同的。

      -- 成員函式: hex ([sep[, bytes_per_sep]])

          返回一个字符串对象，其中分别以两个十六进制数码表示缓冲区里的每
          个字节。

               >>> m = memoryview(b"abc")
               >>> m.hex()
               '616263'

          3.5 版新加入.

          3.8 版更變: 与 *note bytes.hex(): 724. 相似， *note
          memoryview.hex(): 726. 现在支持可选的 `sep' 和 `bytes_per_sep'
          参数以在十六进制输出的字节之间插入分隔符。

      -- 成員函式: tolist ()

          将缓冲区内的数据以一个元素列表的形式返回。

               >>> 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]

          3.3 版更變: *note tolist(): 17e5. 现在支持 *note struct: f8. 模
          块语法中的所有单字符原生格式以及多维表示形式。

      -- 成員函式: toreadonly ()

          返回 memoryview 对象的只读版本。 原始的 memoryview 对象不会被
          改变。

               >>> 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]

          3.8 版新加入.

      -- 成員函式: release ()

          释放由内存视图对象所公开的底层缓冲区。 许多对象在被视图所获取
          时都会采取特殊动作（例如，*note bytearray: 173. 将会暂时禁止调
          整大小）；因此，调用 release() 可以方便地尽早去除这些限制（并
          释放任何多余的资源）。

          在此方法被调用后，任何对视图的进一步操作将引发 *note
          ValueError: 16d. (*note release(): c0f. 本身除外，它可以被多次
          调用):

               >>> 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

          使用 ‘with’ 语句，可以通过上下文管理协议达到类似的效果:

               >>> 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

          3.2 版新加入.

      -- 成員函式: cast (format[, shape])

          将内存视图转化为新的格式或形状。 `shape' 默认为
          ‘[byte_length//new_itemsize]’，这意味着结果视图将是一维的。 返
          回值是一个新的内存视图，但缓冲区本身不会被复制。 支持的转化有
          1D -> C-*note contiguous: 17ec. 和 C-contiguous -> 1D。

          目标格式仅限于 *note struct: f8. 语法中的单一元素原生格式。 其
          中一种格式必须为字节格式 (’B’, ’b’ 或 ’c’)。 结果的字节长度必
          须与原始长度相同。

          将 1D/long 转换为 1D/unsigned bytes:

               >>> 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

          将 1D/unsigned bytes 转换为 1D/char:

               >>> 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')

          将 1D/bytes 转换为 3D/ints 再转换为 1D/signed char:

               >>> 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

          将 1D/unsigned long 转换为 2D/unsigned long:

               >>> 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]]

          3.3 版新加入.

          3.5 版更變: 当转换为字节视图时，源格式将不再受限。

     还存在一些可用的只读属性：

      -- 屬性: obj

          内存视图的下层对象:

               >>> b  = bytearray(b'xyz')
               >>> m = memoryview(b)
               >>> m.obj is b
               True

          3.3 版新加入.

      -- 屬性: nbytes

          ‘nbytes == product(shape) * itemsize == len(m.tobytes())’。 这
          是数组在连续表示时将会占用的空间总字节数。 它不一定等于
          ‘len(m)’:

               >>> 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

          多维数组:

               >>> 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

          3.3 版新加入.

      -- 屬性: readonly

          一个表明内存是否只读的布尔值。

      -- 屬性: format

          一个字符串，包含视图中每个元素的格式（表示为 *note struct: f8.
          模块样式）。 内存视图可以从具有任意格式字符串的导出器创建，但
          某些方法 (例如 *note tolist(): 17e5.) 仅限于原生的单元素格式。

          3.3 版更變: 格式 ‘'B'’ 现在会按照 struct 模块语法来处理。 这意
          味着 ‘memoryview(b'abc')[0] == b'abc'[0] == 97’。

      -- 屬性: itemsize

          memoryview 中每个元素以字节表示的大小:

               >>> import array, struct
               >>> m = memoryview(array.array('H', [32000, 32001, 32002]))
               >>> m.itemsize
               2
               >>> m[0]
               32000
               >>> struct.calcsize('H') == m.itemsize
               True

      -- 屬性: ndim

          一个整数，表示内存所代表的多维数组具有多少个维度。

      -- 屬性: shape

          一个整数元组，通过 *note ndim: 17f0. 的长度值给出内存所代表的
          N 维数组的形状。

          3.3 版更變: 当 ndim = 0 时值为空元组而不再为 ‘None’。

      -- 屬性: strides

          一个整数元组，通过 *note ndim: 17f0. 的长度给出以字节表示的大
          小，以便访问数组中每个维度上的每个元素。

          3.3 版更變: 当 ndim = 0 时值为空元组而不再为 ‘None’。

      -- 屬性: suboffsets

          供 PIL 风格的数组内部使用。 该值仅作为参考信息。

      -- 屬性: c_contiguous

          一个表明内存是否为 C-*note contiguous: 17ec. 的布尔值。

          3.3 版新加入.

      -- 屬性: f_contiguous

          一个表明内存是否为 Fortran *note contiguous: 17ec. 的布尔值。

          3.3 版新加入.

      -- 屬性: contiguous

          一个表明内存是否为 *note contiguous: 17ec. 的布尔值。

          3.3 版新加入.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3118


File: python.info,  Node: 集合类型 --- set frozenset,  Next: 映射类型 --- dict,  Prev: 二进制序列类型 --- bytes bytearray memoryview,  Up: 內建型態

5.4.9 集合类型 — ‘set’, ‘frozenset’
-----------------------------------

`set' 对象是由具有唯一性的 *note hashable: 276. 对象所组成的无序多项集。
常见的用途包括成员检测、从序列中去除重复项以及数学中的集合类计算，例如交
集、并集、差集与对称差集等等。 （关于其他容器对象请参看 *note dict: 164,
*note list: 1f8. 与 *note tuple: 1a2. 等内置类，以及 *note collections:
1d. 模块。）

与其他多项集一样，集合也支持 ‘x in set’, ‘len(set)’ 和 ‘for x in set’。
作为一种无序的多项集，集合并不记录元素位置或插入顺序。 相应地，集合不支
持索引、切片或其他序列类的操作。

目前有两种内置集合类型，*note set: 1f6. 和 *note frozenset: 1f7.。 *note
set: 1f6. 类型是可变的 — 其内容可以使用 ‘add()’ 和 ‘remove()’ 这样的方法
来改变。 由于是可变类型，它没有哈希值，且不能被用作字典的键或其他集合的
元素。 *note frozenset: 1f7. 类型是不可变并且为 *note hashable: 276. — 其
内容在被创建后不能再改变；因此它可以被用作字典的键或其他集合的元素。

除了可以使用 *note set: 1f6. 构造器，非空的 set (不是 frozenset) 还可以
通过将以逗号分隔的元素列表包含于花括号之内来创建，例如: ‘{'jack',
'sjoerd'}’。

两个类的构造器具有相同的作用方式：

 -- 類別: set ([iterable])
 -- 類別: frozenset ([iterable])

     返回一个新的 set 或 frozenset 对象，其元素来自于 `iterable'。 集合
     的元素必须为 *note hashable: 276.。 要表示由集合对象构成的集合，所
     有的内层集合必须为 *note frozenset: 1f7. 对象。 如果未指定
     `iterable'，则将返回一个新的空集合。

     集合可用多种方式来创建:

        * 使用花括号内以逗号分隔元素的方式: ‘{'jack', 'sjoerd'}’

        * 使用集合推导式: ‘{c for c in 'abracadabra' if c not in 'abc'}’

        * 使用类型构造器: ‘set()’, ‘set('foobar')’, ‘set(['a', 'b',
          'foo'])’

     *note set: 1f6. 和 *note frozenset: 1f7. 的实例提供以下操作：

      -- Describe: len(s)

          返回集合 `s' 中的元素数量（即 `s' 的基数）。

      -- Describe: x in s

          检测 `x' 是否为 `s' 中的成员。

      -- Describe: x not in s

          检测 `x' 是否非 `s' 中的成员。

      -- 成員函式: isdisjoint (other)

          如果集合中没有与 `other' 共有的元素则返回 ‘True’。 当且仅当两
          个集合的交集为空集合时，两者为不相交集合。

      -- 成員函式: issubset (other)

      -- 成員函式: set <= other

          检测是否集合中的每个元素都在 `other' 之中。

      -- 成員函式: set < other

          检测集合是否为 `other' 的真子集，即 ‘set <= other and set !=
          other’。

      -- 成員函式: issuperset (other)

      -- 成員函式: set >= other

          检测是否 `other' 中的每个元素都在集合之中。

      -- 成員函式: set > other

          检测集合是否为 `other' 的真超集，即 ‘set >= other and set !=
          other’。

      -- 成員函式: union (*others)

      -- 成員函式: set | other | ...

          返回一个新集合，其中包含来自原集合以及 others 指定的所有集合中
          的元素。

      -- 成員函式: intersection (*others)

      -- 成員函式: set & other & ...

          返回一个新集合，其中包含原集合以及 others 指定的所有集合中共有
          的元素。

      -- 成員函式: difference (*others)

      -- 成員函式: set - other - ...

          返回一个新集合，其中包含原集合中在 others 指定的其他集合中不存
          在的元素。

      -- 成員函式: symmetric_difference (other)

      -- 成員函式: set ^ other

          返回一个新集合，其中的元素或属于原集合或属于 `other' 指定的其
          他集合，但不能同时属于两者。

      -- 成員函式: copy ()

          返回原集合的浅拷贝。

     请注意，非运算符版本的 *note union(): 17fb, *note intersection():
     17fc, *note difference(): 17fd.，以及 *note symmetric_difference():
     17fe, *note issubset(): 17f9. 和 *note issuperset(): 17fa. 方法会接
     受任意可迭代对象作为参数。 相比之下，它们所对应的运算符版本则要求其
     参数为集合。 这就排除了容易出错的构造形式例如 ‘set('abc') & 'cbs'’，
     而推荐可读性更强的 ‘set('abc').intersection('cbs')’。

     *note set: 1f6. 和 *note frozenset: 1f7. 均支持集合与集合的比较。 两
     个集合当且仅当每个集合中的每个元素均包含于另一个集合之内（即各为对
     方的子集）时则相等。 一个集合当且仅当其为另一个集合的真子集（即为后
     者的子集但两者不相等）时则小于另一个集合。 一个集合当且仅当其为另一
     个集合的真超集（即为后者的超集但两者不相等）时则大于另一个集合。

     *note set: 1f6. 的实例与 *note frozenset: 1f7. 的实例之间基于它们的
     成员进行比较。 例如 ‘set('abc') == frozenset('abc')’ 返回 ‘True’，
     ‘set('abc') in set([frozenset('abc')])’ 也一样。

     子集与相等比较并不能推广为完全排序函数。 例如，任意两个非空且不相交
     的集合不相等且互不为对方的子集，因此以下 `所有' 比较均返回 ‘False’:
     ‘a<b’, ‘a==b’, or ‘a>b’。

     由于集合仅定义了部分排序（子集关系），因此由集合构成的列表 *note
     list.sort(): 547. 方法的输出并无定义。

     集合的元素，与字典的键类似，必须为 *note hashable: 276.。

     混合了 *note set: 1f6. 实例与 *note frozenset: 1f7. 的二进制位运算
     将返回与第一个操作数相同的类型。例如: ‘frozenset('ab') | set('bc')’
     将返回 *note frozenset: 1f7. 的实例。

     下表列出了可用于 *note set: 1f6. 而不能用于不可变的 *note
     frozenset: 1f7. 实例的操作：

      -- 成員函式: update (*others)

      -- 成員函式: set |= other | ...

          更新集合，添加来自 others 中的所有元素。

      -- 成員函式: intersection_update (*others)

      -- 成員函式: set &= other & ...

          更新集合，只保留其中在所有 others 中也存在的元素。

      -- 成員函式: difference_update (*others)

      -- 成員函式: set -= other | ...

          更新集合，移除其中也存在于 others 中的元素。

      -- 成員函式: symmetric_difference_update (other)

      -- 成員函式: set ^= other

          更新集合，只保留存在于集合的一方而非共同存在的元素。

      -- 成員函式: add (elem)

          将元素 `elem' 添加到集合中。

      -- 成員函式: remove (elem)

          从集合中移除元素 `elem'。 如果 `elem' 不存在于集合中则会引发
          *note KeyError: 3e9.。

      -- 成員函式: discard (elem)

          如果元素 `elem' 存在于集合中则将其移除。

      -- 成員函式: pop ()

          从集合中移除并返回任意一个元素。 如果集合为空则会引发 *note
          KeyError: 3e9.。

      -- 成員函式: clear ()

          从集合中移除所有元素。

     请注意，非运算符版本的 *note update(): 1800, *note
     intersection_update(): 1801, *note difference_update(): 1802. 和
     *note symmetric_difference_update(): 1803. 方法将接受任意可迭代对象
     作为参数。

     请注意，*note __contains__(): dee, *note remove(): 1805. 和 *note
     discard(): 1806. 方法的 `elem' 参数可能是一个 set。 为支持对一个等
     价的 frozenset 进行搜索，会根据 `elem' 临时创建一个该类型对象。


File: python.info,  Node: 映射类型 --- dict,  Next: 上下文管理器类型,  Prev: 集合类型 --- set frozenset,  Up: 內建型態

5.4.10 映射类型 — ‘dict’
------------------------

*note mapping: c0b. 对象会将 *note hashable: 276. 值映射到任意对象。 映
射属于可变对象。 目前仅有一种标准映射类型 `字典'。 （关于其他容器对象请
参看 *note list: 1f8, *note set: 1f6. 与 *note tuple: 1a2. 等内置类，以
及 *note collections: 1d. 模块。）

字典的键 `几乎' 可以是任何值。 非 *note hashable: 276. 的值，即包含列表
、字典或其他可变类型的值（此类对象基于值而非对象标识进行比较）不可用作键
。 数字类型用作键时遵循数字比较的一般规则：如果两个数值相等 (例如 ‘1’ 和
‘1.0’) 则两者可以被用来索引同一字典条目。 （但是请注意，由于计算机对于浮
点数存储的只是近似值，因此将其用作字典键是不明智的。）

字典可以通过将以逗号分隔的 ‘键: 值’ 对列表包含于花括号之内来创建，例如:
‘{'jack': 4098, 'sjoerd': 4127}’ 或 ‘{4098: 'jack', 4127: 'sjoerd'}’，也
可以通过 *note dict: 164. 构造器来创建。

 -- 類別: dict (**kwargs)

 -- 類別: dict (mapping, **kwargs)

 -- 類別: dict (iterable, **kwargs)

     返回一个新的字典，基于可选的位置参数和可能为空的关键字参数集来初始
     化。

     字典可用多种方式来创建:

        * 使用花括号内以逗号分隔 ‘键: 值’ 对的方式: ‘{'jack': 4098,
          'sjoerd': 4127}’ or ‘{4098: 'jack', 4127: 'sjoerd'}’

        * 使用字典推导式: ‘{}’, ‘{x: x ** 2 for x in range(10)}’

        * 使用类型构造器: ‘dict()’, ‘dict([('foo', 100), ('bar',
          200)])’, ‘dict(foo=100, bar=200)’

     如果没有给出位置参数，将创建一个空字典。 如果给出一个位置参数并且其
     属于映射对象，将创建一个具有与映射对象相同键值对的字典。 否则的话，
     位置参数必须为一个 *note iterable: c7c. 对象。 该可迭代对象中的每一
     项本身必须为一个刚好包含两个元素的可迭代对象。 每一项中的第一个对象
     将成为新字典的一个键，第二个对象将成为其对应的值。 如果一个键出现一
     次以上，该键的最后一个值将成为其在新字典中对应的值。

     如果给出了关键字参数，则关键字参数及其值会被加入到基于位置参数创建
     的字典。 如果要加入的键已存在，来自关键字参数的值将替代来自位置参数
     的值。

     作为演示，以下示例返回的字典均等于 ‘{"one": 1, "two": 2, "three":
     3}’:

          >>> 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

     像第一个例子那样提供关键字参数的方式只能使用有效的 Python 标识符作
     为键。 其他方式则可使用任何有效的键。

     这些是字典所支持的操作（因而自定义的映射类型也应当支持）：

      -- Describe: list(d)

          返回字典 `d' 中使用的所有键的列表。

      -- Describe: len(d)

          返回字典 `d' 中的项数。

      -- Describe: d[key]

          返回 `d' 中以 `key' 为键的项。 如果映射中不存在 `key' 则会引发
          *note KeyError: 3e9.。

          如果字典的子类定义了方法 *note __missing__(): c0d. 并且 `key'
          不存在，则 ‘d[key]’ 操作将调用该方法并附带键 `key' 作为参数。
          ‘d[key]’ 随后将返回或引发 ‘__missing__(key)’ 调用所返回或引发
          的任何对象或异常。 没有其他操作或方法会发起调用 *note
          __missing__(): c0d.。 如果未定义 *note __missing__(): c0d.，则
          会引发 *note KeyError: 3e9.。 *note __missing__(): c0d. 必须是
          一个方法；它不能是一个实例变量:

               >>> class Counter(dict):
               ...     def __missing__(self, key):
               ...         return 0
               >>> c = Counter()
               >>> c['red']
               0
               >>> c['red'] += 1
               >>> c['red']
               1

          上面的例子显示了 *note collections.Counter: ab9. 实现的部分代
          码。 还有另一个不同的 ‘__missing__’ 方法是由 *note
          collections.defaultdict: c0c. 所使用的。

      -- Describe: d[key] = value

          将 ‘d[key]’ 设为 `value'。

      -- Describe: del d[key]

          将 ‘d[key]’ 从 `d' 中移除。 如果映射中不存在 `key' 则会引发
          *note KeyError: 3e9.。

      -- Describe: key in d

          如果 `d' 中存在键 `key' 则返回 ‘True’，否则返回 ‘False’。

      -- Describe: key not in d

          等价于 ‘not key in d’。

      -- Describe: iter(d)

          返回以字典的键为元素的迭代器。 这是 ‘iter(d.keys())’ 的快捷方
          式。

      -- 成員函式: clear ()

          移除字典中的所有元素。

      -- 成員函式: copy ()

          返回原字典的浅拷贝。

      -- 成員函式: classmethod fromkeys (iterable[, value])

          使用来自 `iterable' 的键创建一个新字典，并将键值设为 `value'。

          *note fromkeys(): 180a. 是一个返回新字典的类方法。 `value' 默
          认为 ‘None’。 所有值都只引用一个单独的实例，因此让 `value' 成
          为一个可变对象例如空列表通常是没有意义的。 要获取不同的值，请
          改用 *note 字典推导式: 741.。

      -- 成員函式: get (key[, default])

          如果 `key' 存在于字典中则返回 `key' 的值，否则返回 `default'。
          如果 `default' 未给出则默认为 ‘None’，因而此方法绝不会引发
          *note KeyError: 3e9.。

      -- 成員函式: items ()

          返回由字典项 (‘(键, 值)’ 对) 组成的一个新视图。 参见 *note
          视图对象文档: 180c.。

      -- 成員函式: keys ()

          返回由字典键组成的一个新视图。 参见 *note 视图对象文档: 180c.。

      -- 成員函式: pop (key[, default])

          如果 `key' 存在于字典中则将其移除并返回其值，否则返回
          `default'。 如果 `default' 未给出且 `key' 不存在于字典中，则会
          引发 *note KeyError: 3e9.。

      -- 成員函式: popitem ()

          从字典中移除并返回一个 ‘(键, 值)’ 对。 键值对会按 LIFO (后进先
          出) 的顺序被返回。

          *note popitem(): 180e. 适用于对字典进行消耗性的迭代，这在集合
          算法中经常被使用。 如果字典为空，调用 *note popitem(): 180e. 将
          引发 *note KeyError: 3e9.。

          3.7 版更變: 现在会确保采用 LIFO 顺序。 在之前的版本中，*note
          popitem(): 180e. 会返回一个任意的键/值对。

      -- Describe: reversed(d)

          返回一个逆序获取字典键的迭代器。 这是 ‘reversed(d.keys())’ 的
          快捷方式。

          3.8 版新加入.

      -- 成員函式: setdefault (key[, default])

          如果字典存在键 `key' ，返回它的值。如果不存在，插入值为
          `default' 的键 `key' ，并返回 `default' 。 `default' 默认为
          ‘None’。

      -- 成員函式: update ([other])

          使用来自 `other' 的键/值对更新字典，覆盖原有的键。 返回
          ‘None’。

          *note update(): e8e. 接受另一个字典对象，或者一个包含键/值对（
          以长度为二的元组或其他可迭代对象表示）的可迭代对象。 如果给出
          了关键字参数，则会以其所指定的键/值对更新字典:
          ‘d.update(red=1, blue=2)’。

      -- 成員函式: values ()

          返回由字典值组成的一个新视图。 参见 *note 视图对象文档: 180c.。

          两个 ‘dict.values()’ 视图之间的相等性比较将总是返回 ‘False’。
          这在 ‘dict.values()’ 与其自身比较时也同样适用:

               >>> d = {'a': 1}
               >>> d.values() == d.values()
               False

      -- Describe: d | other

          合并 `d' 和 `other' 中的键和值来创建一个新的字典，两者必须都是
          字典。当 `d' 和 `other' 有相同键时， `other' 的值优先。

          3.9 版新加入.

      -- Describe: d |= other

          用 `other' 的键和值更新字典 `d' ，`other' 可以是 *note
          mapping: c0b. 或 *note iterable: c7c. 的键值对。当 `d' 和
          `other' 有相同键时， `other' 的值优先。

          3.9 版新加入.

     两个字典的比较当且仅当它们具有相同的 ‘(键, 值)’ 对时才会相等（不考
     虑顺序）。 排序比较 (’<’, ’<=’, ’>=’, ’>’) 会引发 *note TypeError:
     1fe.。

     字典会保留插入时的顺序。 请注意对键的更新不会影响顺序。 删除并再次
     添加的键将被插入到末尾。

          >>> 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}

     3.7 版更變: 字典顺序会确保为插入顺序。 此行为是自 3.6 版开始的
     CPython 实现细节。

     字典和字典视图都是可逆的。

          >>> 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)]

     3.8 版更變: 字典现在是可逆的。

也參考
......

*note types.MappingProxyType: b8e. 可被用来创建一个 *note dict: 164. 的
只读视图。

* Menu:

* 字典视图对象::


File: python.info,  Node: 字典视图对象,  Up: 映射类型 --- dict

5.4.10.1 字典视图对象
.....................

由 *note dict.keys(): cf4, *note dict.values(): cf6. 和 *note
dict.items(): cf5. 所返回的对象是 `视图对象'。 该对象提供字典条目的一个
动态视图，这意味着当字典改变时，视图也会相应改变。

字典视图可以被迭代以产生与其对应的数据，并支持成员检测：

 -- Describe: len(dictview)

     返回字典中的条目数。

 -- Describe: iter(dictview)

     返回字典中的键、值或项（以 ‘(键, 值)’ 为元素的元组表示）的迭代器。

     键和值是按插入时的顺序进行迭代的。 这样就允许使用 *note zip(): cfc.
     来创建 ‘(值, 键)’ 对: ‘pairs = zip(d.values(), d.keys())’。 另一个
     创建相同列表的方式是 ‘pairs = [(v, k) for (k, v) in d.items()]’.

     在添加或删除字典中的条目期间对视图进行迭代可能引发 *note
     RuntimeError: 3dc. 或者无法完全迭代所有条目。

     3.7 版更變: 字典顺序会确保为插入顺序。

 -- Describe: x in dictview

     如果 `x' 是对应字典中存在的键、值或项（在最后一种情况下 `x' 应为一
     个 ‘(键, 值)’ 元组） 则返回 ‘True’。

 -- Describe: reversed(dictview)

     返回一个逆序获取字典键、值或项的迭代器。 视图将按与插入时相反的顺序
     进行迭代。

     3.8 版更變: 字典视图现在是可逆的。

键视图类似于集合，因为其条目不重复且可哈希。 如果所有值都是可哈希的，即
‘(键, 值)’ 对也是不重复且可哈希的，那么条目视图也会类似于集合。 （值视图
则不被视为类似于集合，因其条目通常都是有重复的。） 对于类似于集合的视图
，为抽象基类 *note collections.abc.Set: 1810. 所定义的全部操作都是有效的
(例如 ‘==’, ‘<’ 或 ‘^’)。

一个使用字典视图的示例:

     >>> 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'}


File: python.info,  Node: 上下文管理器类型,  Next: GenericAlias 类型,  Prev: 映射类型 --- dict,  Up: 內建型態

5.4.11 上下文管理器类型
-----------------------

Python 的 *note with: 7da. 语句支持通过上下文管理器所定义的运行时上下文
这一概念。 此对象的实现使用了一对专门方法，允许用户自定义类来定义运行时
上下文，在语句体被执行前进入该上下文，并在语句执行完毕时退出该上下文：

 -- 成員函式: contextmanager.__enter__ ()

     进入运行时上下文并返回此对象或关联到该运行时上下文的其他对象。 此方
     法的返回值会绑定到使用此上下文管理器的 *note with: 7da. 语句的 ‘as’
     子句中的标识符。

     一个返回其自身的上下文管理器的例子是 *note file object: c14.。 文件
     对象会从 __enter__() 返回其自身，以允许 *note open(): 16f. 被用作
     *note with: 7da. 语句中的上下文表达式。

     一个返回关联对象的上下文管理器的例子是 *note
     decimal.localcontext(): 1813. 所返回的对象。 此种管理器会将活动的
     decimal 上下文设为原始 decimal 上下文的一个副本并返回该副本。 这允
     许对 *note with: 7da. 语句的语句体中的当前 decimal 上下文进行更改，
     而不会影响 ‘with’ 语句以外的代码。

 -- 成員函式: contextmanager.__exit__ (exc_type, exc_val, exc_tb)

     退出运行时上下文并返回一个布尔值旗标来表明所发生的任何异常是否应当
     被屏蔽。 如果在执行 *note with: 7da. 语句的语句体期间发生了异常，则
     参数会包含异常的类型、值以及回溯信息。 在其他情况下三个参数均为
     ‘None’。

     自此方法返回一个真值将导致 *note with: 7da. 语句屏蔽异常并继续执行
     紧随在 ‘with’ 语句之后的语句。 否则异常将在此方法结束执行后继续传播
     。 在此方法执行期间发生的异常将会取代 ‘with’ 语句的语句体中发生的任
     何异常。

     传入的异常绝对不应当被显式地重新引发 —— 相反地，此方法应当返回一个
     假值以表明方法已成功完成并且不希望屏蔽被引发的异常。 这允许上下文管
     理代码方便地检测 *note __exit__(): 1814. 方法是否确实已失败。

Python 定义了一些上下文管理器来支持简易的线程同步、文件或其他对象的快速
关闭，以及更方便地操作活动的十进制算术上下文。 除了实现上下文管理协议以
外，不同类型不会被特殊处理。 请参阅 *note contextlib: 23. 模块查看相关的
示例。

Python’s *note generator: a83.s and the *note contextlib.contextmanager:
c4f. decorator provide a convenient way to implement these protocols.
If a generator function is decorated with the *note
contextlib.contextmanager: c4f. decorator, it will return a context
manager implementing the necessary *note __enter__(): 1812. and *note
__exit__(): 1814. methods, rather than the iterator produced by an
undecorated generator function.

请注意，Python/C API 中 Python 对象的类型结构中并没有针对这些方法的专门
槽位。 想要定义这些方法的扩展类型必须将它们作为普通的 Python 可访问方法
来提供。 与设置运行时上下文的开销相比，单个类字典查找的开销可以忽略不计
。


File: python.info,  Node: GenericAlias 类型,  Next: 其他内置类型,  Prev: 上下文管理器类型,  Up: 內建型態

5.4.12 GenericAlias 类型
------------------------

‘GenericAlias’ 对象是通过对类（通常是容器类）作下标来创建的，如
‘list[int]’ 。主要用于 *note type annotations: 1587.。

通常，容器对象的 *note 抽取: 158e. 操作会调用该对象的 *note
__getitem__(): 3a5. 方法。 但是，对某些容器类执行抽取操作可能会改去调用
该类的 *note __class_getitem__(): 437. 类方法。 *note
__class_getitem__(): 437. 类方法应当会返回一个 ‘GenericAlias’ 对象。

     備註: 如果元类的 *note __getitem__(): 3a5. 存在，将优先于类定义的
     ‘__class_getitem__`（详见 :pep:`560()’）。

‘GenericAlias’ 对象作为 *note 泛型类型: fea. 的代理，具体实现 `形参化的
泛型' —— 一个泛型的具体实例，为容器元素提供类型。

用户通过 ‘GenericAlias’ 对象暴露的类型可由 *note types.GenericAlias:
27c. 访问，并用于 *note isinstance(): 551. 检查。也可用来直接创建
‘GenericAlias’ 对象。

 -- Describe: T[X, Y, ...]

     创建代表类型 ‘T’ 的 ‘GenericAlias’ ，包含 `X' 、`Y' 等类型的元素，
     元素类型更多取决于所用的 ‘T’。比如某函数需要包含 *note float: 1fd.
     元素的 *note list: 1f8. ：

          def average(values: list[float]) -> float:
              return sum(values) / len(values)

     另一个例子是关于 *note mapping: c0b. 对象的，用到了 *note dict:
     164.，泛型的两个类型参数分别代表了键类型和值类型。本例中的函数需要
     一个 ‘dict’，其键的类型为 *note str: 205.，值的类型为 *note int:
     204.:。

          def send_post_request(url: str, body: dict[str, int]) -> None:
              ...

内置函数 *note isinstance(): 551. 和 *note issubclass(): 552. 不接受第二
个参数为‘‘GenericAlias‘‘ 类型：

     >>> 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

Python 运行时不会强制执行 *note type annotations: 1587.。这种方式延伸到
了泛型及其类型参数。当由 ‘GenericAlias’ 创建对象时，不会检查容器元素的类
型。例如，以下代码虽不值得鼓励，但运行时不会出错：

     >>> t = list[str]
     >>> t([1, 2, 3])
     [1, 2, 3]

不仅如此，在创建对象的过程中，参数化的泛型还会抹除类型参数：

     >>> t = list[str]
     >>> type(t)
     <class 'types.GenericAlias'>

     >>> l = t()
     >>> type(l)
     <class 'list'>

在泛型上调用 *note repr(): 8b9. 或 *note str(): 205. 会显示应用参数之后
的类型：

     >>> repr(list[int])
     'list[int]'

     >>> str(list[int])
     'list[int]'

调用泛型的 *note __getitem__(): 3a5. 方法将触发异常，以防出现
‘dict[str][str]’ 之类的错误。

     >>> dict[str][str]
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     TypeError: There are no type variables left in dict[str]

不过在用到 *note type variables: 1588. 时，这种表达式是有效的。索引元素
数量必须与 ‘GenericAlias’ 对象的 *note __args__: 1816. 的类型变量项数一
样。

     >>> from typing import TypeVar
     >>> Y = TypeVar('Y')
     >>> dict[str, Y][int]
     dict[str, int]

* Menu:

* 标准的泛型集合类::
* 泛型的特殊属性::


File: python.info,  Node: 标准的泛型集合类,  Next: 泛型的特殊属性,  Up: GenericAlias 类型

5.4.12.1 标准的泛型集合类
.........................

以下标准集合类支持参数化泛型：

   * *note tuple: 1a2.

   * *note list: 1f8.

   * *note dict: 164.

   * *note set: 1f6.

   * *note frozenset: 1f7.

   * *note type: 6ff.

   * *note collections.deque: 62a.

   * *note collections.defaultdict: c0c.

   * *note collections.OrderedDict: 2ea.

   * *note collections.Counter: ab9.

   * *note collections.ChainMap: 5a3.

   * *note collections.abc.Awaitable: 7a9.

   * *note collections.abc.Coroutine: 7aa.

   * *note collections.abc.AsyncIterable: 7ac.

   * *note collections.abc.AsyncIterable: 7ac.

   * *note collections.abc.AsyncGenerator: 629.

   * *note collections.abc.Iterable: 1818.

   * *note collections.abc.Iterator: 1819.

   * *note collections.abc.Generator: 7a8.

   * *note collections.abc.Reversible: 627.

   * *note collections.abc.Container: 181a.

   * *note collections.abc.Collection: 626.

   * *note collections.abc.Callable: 27a.

   * *note collections.abc.Set: 1810.

   * *note collections.abc.MutableSet: 181b.

   * *note collections.abc.Mapping: 15f.

   * *note collections.abc.MutableMapping: ace.

   * *note collections.abc.Sequence: 1764.

   * *note collections.abc.MutableSequence: 79f.

   * *note collections.abc.ByteString: 181c.

   * *note collections.abc.MappingView: 181d.

   * *note collections.abc.KeysView: 181e.

   * *note collections.abc.ItemsView: 181f.

   * *note collections.abc.ValuesView: 1820.

   * *note contextlib.AbstractContextManager: 62d.

   * *note contextlib.AbstractAsyncContextManager: 480.

   * *note re.Pattern: 983.

   * *note re.Match: 984.


File: python.info,  Node: 泛型的特殊属性,  Prev: 标准的泛型集合类,  Up: GenericAlias 类型

5.4.12.2 泛型的特殊属性
.......................

应用参数后的泛型都实现了一些特殊的只读属性：

 -- 屬性: genericalias.__origin__

     本属性指向未应用参数之前的泛型类：

          >>> list[int].__origin__
          <class 'list'>

 -- 屬性: genericalias.__args__

     该属性是传给泛型容器的原始 *note __class_getitem__(): 437. 的泛型所
     组成的 *note tuple: 1a2. (长度可能为 1)。

          >>> dict[str, list[int]].__args__
          (<class 'str'>, list[int])

 -- 屬性: genericalias.__parameters__

     该属性是延迟计算出来的一个元组（可能为空），包含了 ‘__args__’ 中的
     唯一类型变量。

          >>> from typing import TypeVar

          >>> T = TypeVar('T')
          >>> list[T].__parameters__
          (~T,)

也參考
......

   * PEP 585(1) —— “标准集合类中的类型提示泛型”

   * *note __class_getitem__(): 437. —— 用于实现应用参数后的泛型。

   * *note 泛型（Generic）: 1588. —— *note typing: 122. 模块中的泛型。

3.9 版新加入.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0585


File: python.info,  Node: 其他内置类型,  Next: 特殊属性,  Prev: GenericAlias 类型,  Up: 內建型態

5.4.13 其他内置类型
-------------------

解释器支持一些其他种类的对象。 这些对象大都仅支持一两种操作。

* Menu:

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


File: python.info,  Node: 模块,  Next: 类与类实例,  Up: 其他内置类型

5.4.13.1 模块
.............

模块唯一的特殊操作是属性访问: ‘m.name’，这里 `m' 为一个模块而 `name' 访
问定义在 `m' 的符号表中的一个名称。 模块属性可以被赋值。 （请注意 *note
import: ce7. 语句严格来说也是对模块对象的一种操作；‘import foo’ 不要求存
在一个名为 `foo' 的模块对象，而是要求存在一个对于名为 `foo' 的模块的 (永
久性) `定义'。）

每个模块都有一个特殊属性 *note __dict__: 5f5.。 这是包含模块的符号表的字
典。 修改此字典将实际改变模块的符号表，但是无法直接对 *note __dict__:
5f5. 赋值 (你可以写 ‘m.__dict__['a'] = 1’，这会将 ‘m.a’ 定义为 ‘1’，但是
你不能写 ‘m.__dict__ = {}’)。 不建议直接修改 *note __dict__: 5f5.。

内置于解释器中的模块会写成这样: ‘<module 'sys' (built-in)>’。 如果是从一
个文件加载，则会写成 ‘<module 'os' from
'/usr/local/lib/pythonX.Y/os.pyc'>’。


File: python.info,  Node: 类与类实例,  Next: 函数,  Prev: 模块,  Up: 其他内置类型

5.4.13.2 类与类实例
...................

关于这些类型请参阅 *note 对象、值与类型: 154f. 和 *note 类定义: d32.。


File: python.info,  Node: 函数,  Next: 方法,  Prev: 类与类实例,  Up: 其他内置类型

5.4.13.3 函数
.............

函数对象是通过函数定义创建的。 对函数对象的唯一操作是调用它:
‘func(argument-list)’。

实际上存在两种不同的函数对象：内置函数和用户自定义函数。 两者支持同样的
操作（调用函数），但实现方式不同，因此对象类型也不同。

更多信息请参阅 *note 函数定义: 1390.。


File: python.info,  Node: 方法,  Next: 代码对象,  Prev: 函数,  Up: 其他内置类型

5.4.13.4 方法
.............

方法是使用属性表示法来调用的函数。 存在两种形式：内置方法（例如列表的
‘append()’ 方法）和类实例方法。 内置方法由支持它们的类型来描述。

如果你通过一个实例来访问方法（即定义在类命名空间内的函数），你会得到一个
特殊对象: `绑定方法' (或称 `实例方法') 对象。 当被调用时，它会将 ‘self’
参数添加到参数列表。 绑定方法具有两个特殊的只读属性: ‘m.__self__’ 操作该
方法的对象，而 ‘m.__func__’ 是实现该方法的函数。 调用 ‘m(arg-1, arg-2,
..., arg-n)’ 完全等价于调用 ‘m.__func__(m.__self__, arg-1, arg-2, ...,
arg-n)’。

与函数对象类似，绑定方法对象也支持获取任意属性。 但是，由于方法属性实际
上保存于下层的函数对象中 (‘meth.__func__’)，因此不允许设置绑定方法的方法
属性。 尝试设置方法的属性将会导致引发 *note AttributeError: 4a1.。 想要
设置方法属性，你必须在下层的函数对象中显式地对其进行设置:

     >>> 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'

更多信息请参阅 *note 标准类型层级结构: 1553.。


File: python.info,  Node: 代码对象,  Next: 类型对象,  Prev: 方法,  Up: 其他内置类型

5.4.13.5 代码对象
.................

代码对象被具体实现用来表示“伪编译”的可执行 Python 代码，例如一个函数体。
它们不同于函数对象，因为它们不包含对其全局执行环境的引用。 代码对象由内
置的 *note compile(): 2e7. 函数返回，并可通过从函数对象的 ‘__code__’ 属
性从中提取。 另请参阅 *note code: 1a. 模块。

访问 ‘__code__’ 会触发 *note 审计事件: fa1. ‘object.__getattr__’，参数为
‘obj’ 和 ‘"__code__"’。

可以通过将代码对象（而非源码字符串）传给 *note exec(): d0c. 或 *note
eval(): c61. 内置函数来执行或求值。

更多信息请参阅 *note 标准类型层级结构: 1553.。


File: python.info,  Node: 类型对象,  Next: 空对象,  Prev: 代码对象,  Up: 其他内置类型

5.4.13.6 类型对象
.................

类型对象表示各种对象类型。 对象的类型可通过内置函数 *note type(): 6ff. 来
获取。 类型没有特殊的操作。 标准库模块 *note types: 121. 定义了所有标准
内置类型的名称。

类型以这样的写法来表示: ‘<class 'int'>’。


File: python.info,  Node: 空对象,  Next: 省略符对象,  Prev: 类型对象,  Up: 其他内置类型

5.4.13.7 空对象
...............

此对象会由不显式地返回值的函数所返回。 它不支持任何特殊的操作。 空对象只
有一种值 ‘None’ (这是个内置名称)。 ‘type(None)()’ 会生成同一个单例。

该对象的写法为 ‘None’。


File: python.info,  Node: 省略符对象,  Next: 未实现对象,  Prev: 空对象,  Up: 其他内置类型

5.4.13.8 省略符对象
...................

此对象常被用于切片 (参见 *note 切片: 1652.)。 它不支持任何特殊的操作。 省
略符对象只有一种值 *note Ellipsis: 1740. (这是个内置名称)。
‘type(Ellipsis)()’ 会生成 *note Ellipsis: 1740. 单例。

该对象的写法为 ‘Ellipsis’ 或 ‘...’。


File: python.info,  Node: 未实现对象,  Next: 布尔值,  Prev: 省略符对象,  Up: 其他内置类型

5.4.13.9 未实现对象
...................

此对象会被作为比较和二元运算被应用于它们所不支持的类型时的返回值。 请参
阅 *note 比较运算: 167a. 了解更多信息。 未实现对象只有一种值
‘NotImplemented’。 ‘type(NotImplemented)()’ 会生成这个单例。

该对象的写法为 ‘NotImplemented’。


File: python.info,  Node: 布尔值,  Next: 内部对象,  Prev: 未实现对象,  Up: 其他内置类型

5.4.13.10 布尔值
................

布尔值是两个常量对象 ‘False’ 和 ‘True’。 它们被用来表示逻辑上的真假（不
过其他值也可被当作真值或假值）。 在数字类的上下文中（例如被用作算术运算
符的参数时），它们的行为分别类似于整数 0 和 1。 内置函数 *note bool():
2bd. 可被用来将任意值转换为布尔值，只要该值可被解析为一个逻辑值（参见之
前的 *note 逻辑值检测: 1718. 部分）。

该对象的写法分别为 ‘False’ 和 ‘True’。


File: python.info,  Node: 内部对象,  Prev: 布尔值,  Up: 其他内置类型

5.4.13.11 内部对象
..................

有关此对象的信息请参阅 *note 标准类型层级结构: 1553.。 其中描述了栈帧对
象、回溯对象以及切片对象等等。


File: python.info,  Node: 特殊属性,  Prev: 其他内置类型,  Up: 內建型態

5.4.14 特殊属性
---------------

语言实现为部分对象类型添加了一些特殊的只读属性，它们具有各自的作用。 其
中一些并不会被 *note dir(): df9. 内置函数所列出。

 -- 屬性: object.__dict__

     一个字典或其他类型的映射对象，用于存储对象的（可写）属性。

 -- 屬性: instance.__class__

     类实例所属的类。

 -- 屬性: class.__bases__

     由类对象的基类所组成的元组。

 -- 屬性: definition.__name__

     类、函数、方法、描述器或生成器实例的名称。

 -- 屬性: definition.__qualname__

     类、函数、方法、描述器或生成器实例的 *note qualified name: 155c.。

     3.3 版新加入.

 -- 屬性: class.__mro__

     此属性是由类组成的元组，在方法解析期间会基于它来查找基类。

 -- 成員函式: class.mro ()

     此方法可被一个元类来重载，以为其实例定制方法解析顺序。 它会在类实例
     化时被调用，其结果存储于 *note __mro__: 173a. 之中。

 -- 成員函式: class.__subclasses__ ()

     每个类都存有对直接子类的弱引用列表。本方法返回所有存活引用的列表。
     列表的顺序按照子类定义的排列。例如：

          >>> int.__subclasses__()
          [<class 'bool'>]

註解
....


File: python.info,  Node: 內建的例外,  Next: 文本處理 Text Processing 服務,  Prev: 內建型態,  Up: Python 標準函式庫 Standard Library

5.5 內建的例外
==============

在 Python 中，所有异常必须为一个派生自 *note BaseException: 2db. 的类的
实例。 在带有提及一个特定类的 *note except: c10. 子句的 *note try: e37.
语句中，该子句也会处理任何派生自该类的异常类（但不处理 `它' 所派生出的异
常类）。 通过子类化创建的两个不相关异常类永远是不等效的，既使它们具有相
同的名称。

下面列出的内置异常可通过解释器或内置函数来生成。除非另有说明，它们都会具
有一个提示导致错误详细原因的“关联值”。 这可以是一个字符串或由多个信息项
（例如一个错误码和一个解释错误的字符串）组成的元组。 关联值通常会作为参
数被传递给异常类的构造器。

用户代码可以引发内置异常。 这可被用于测试异常处理程序或报告错误条件，“就
像” 在解释器引发了相同异常的情况时一样；但是请注意，没有任何机制能防止用
户代码引发不适当的错误。

内置异常类可以被子类化以定义新的异常；鼓励程序员从 *note Exception: 2dc.
类或它的某个子类而不是从 *note BaseException: 2db. 来派生新的异常。 关于
定义异常的更多信息可以在 Python 教程的 *note 使用者自定的例外: 13e6. 部
分查看。

* Menu:

* Exception context::
* 繼承自內建的例外::
* 基类::
* 具体异常::
* 警告::
* 异常层次结构::


File: python.info,  Node: Exception context,  Next: 繼承自內建的例外,  Up: 內建的例外

5.5.1 Exception context
-----------------------

当在 *note except: c10. 或 *note finally: 2bc. 子句中引发（或重新引发）
异常时，‘__context__’ 会被自动设为所捕获的最后一个异常；如果新的异常未被
处理，则最终显示的回溯信息将包括原始的异常和最后的异常。

当引发一个新的异常（而不是简单地使用 ‘raise’ 来重新引发 当前在处理的异常
）时，隐式的异常上下文可以通过使用带有 *note raise: d0a. 的 *note from:
d0a. 子句来补充一个显式的原因:

     raise new_exc from original_exc

跟在 *note from: d0a. 之后一表达式必须为一个异常或 ‘None’。 它将在所引发
的异常上被设置为 ‘__cause__’。 设置 ‘__cause__’ 还会隐式地将
‘__suppress_context__’ 属性设为 ‘True’，这样使用 ‘raise new_exc from
None’ 可以有效地将旧异常替换为新异常来显示其目的 (例如将 *note KeyError:
3e9. 转换为 *note AttributeError: 4a1.)，同时让旧异常在 ‘__context__’ 中
保持可用状态以便在调试时进行内省。

除了异常本身的回溯以外，默认的回溯还会显示这些串连的异常。 ‘__cause__’ 中
的显式串连异常如果存在将总是显示。 ‘__context__’ 中的隐式串连异常仅在
‘__cause__’ 为 *note None: 203. 并且 ‘__suppress_context__’ 为假值时显示
。

不论在哪种情况下，异常本身总会在任何串连异常之后显示，以便回溯的最后一行
总是显示所引发的最后一个异常。


File: python.info,  Node: 繼承自內建的例外,  Next: 基类,  Prev: Exception context,  Up: 內建的例外

5.5.2 繼承自內建的例外
----------------------

User code can create subclasses that inherit from an exception type.
It’s recommended to only subclass one exception type at a time to avoid
any possible conflicts between how the bases handle the ‘args’
attribute, as well as due to possible memory layout incompatibilities.

`CPython implementation detail:' Most built-in exceptions are
implemented in C for efficiency, see: Objects/exceptions.c(1).  Some
have custom memory layouts which makes it impossible to create a
subclass that inherits from multiple exception types.  The memory layout
of a type is an implementation detail and might change between Python
versions, leading to new conflicts in the future.  Therefore, it’s
recommended to avoid subclassing multiple exception types altogether.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Objects/exceptions.c


File: python.info,  Node: 基类,  Next: 具体异常,  Prev: 繼承自內建的例外,  Up: 內建的例外

5.5.3 基类
----------

下列异常主要被用作其他异常的基类。

 -- 例外: BaseException

     所有内置异常的基类。 它不应该被用户自定义类直接继承 (这种情况请使用
     *note Exception: 2dc.)。 如果在此类的实例上调用 *note str(): 205.，
     则会返回实例的参数表示，或者当没有参数时返回空字符串。

      -- 屬性: args

          传给异常构造器的参数元组。 某些内置异常 (例如 *note OSError:
          304.) 接受特定数量的参数并赋予此元组中的元素特殊的含义，而其他
          异常通常只接受一个给出错误信息的单独字符串。

      -- 成員函式: with_traceback (tb)

          此方法将 `tb' 设为异常的新回溯信息并返回该异常对象。 它通常以
          如下的形式在异常处理程序中使用:

               try:
                   ...
               except SomeException:
                   tb = sys.exc_info()[2]
                   raise OtherException(...).with_traceback(tb)

 -- 例外: Exception

     所有内置的非系统退出类异常都派生自此类。 所有用户自定义异常也应当派
     生自此类。

 -- 例外: ArithmeticError

     此基类用于派生针对各种算术类错误而引发的内置异常: *note
     OverflowError: a41, *note ZeroDivisionError: 1fa, *note
     FloatingPointError: 1846.。

 -- 例外: BufferError

     当与 *note 缓冲区: 171c. 相关的操作无法执行时将被引发。

 -- 例外: LookupError

     此基类用于派生当映射或序列所使用的键或索引无效时引发的异常: *note
     IndexError: f36, *note KeyError: 3e9.。 这可以通过 *note
     codecs.lookup(): 238. 来直接引发。


File: python.info,  Node: 具体异常,  Next: 警告,  Prev: 基类,  Up: 內建的例外

5.5.4 具体异常
--------------

以下异常属于经常被引发的异常。

 -- 例外: AssertionError

     当 *note assert: 23f. 语句失败时将被引发。

 -- 例外: AttributeError

     当属性引用 (参见 *note 属性引用: 164c.) 或赋值失败时将被引发。 （当
     一个对象根本不支持属性引用或属性赋值时则将引发 *note TypeError:
     1fe.。）

 -- 例外: EOFError

     当 *note input(): d33. 函数未读取任何数据即达到文件结束条件 (EOF) 时
     将被引发。 （另外，‘io.IOBase.read()’ 和 *note
     io.IOBase.readline(): 1849. 方法在遇到 EOF 则将返回一个空字符串。）

 -- 例外: FloatingPointError

     目前未被使用。

 -- 例外: GeneratorExit

     当一个 *note generator: a83. 或 *note coroutine: 18a. 被关闭时将被
     引发；参见 *note generator.close(): 15d0. 和 *note
     coroutine.close(): 15cf.。 它直接继承自 *note BaseException: 2db. 而
     不是 *note Exception: 2dc.，因为从技术上来说它并不是一个错误。

 -- 例外: ImportError

     当 *note import: ce7. 语句尝试加载模块遇到麻烦时将被引发。 并且当
     ‘from ... import’ 中的 "from list" 存在无法找到的名称时也会被引发。

     ‘name’ 与 ‘path’ 属性可通过对构造器使用仅关键字参数来设定。 设定后
     它们将分别表示被尝试导入的模块名称与触发异常的任意文件所在路径。

     3.3 版更變: 添加了 ‘name’ 与 ‘path’ 属性。

 -- 例外: ModuleNotFoundError

     *note ImportError: 16c. 的子类，当一个模块无法被定位时将由 *note
     import: ce7. 引发。 当在 *note sys.modules: 1051. 中找到 ‘None’ 时
     也会被引发。

     3.6 版新加入.

 -- 例外: IndexError

     当序列抽取超出范围时将被引发。 （切片索引会被静默截短到允许的范围；
     如果指定索引不是整数则 *note TypeError: 1fe. 会被引发。）

 -- 例外: KeyError

     当在现有键集合中找不到指定的映射（字典）键时将被引发。

 -- 例外: KeyboardInterrupt

     当用户按下中断键 (通常为 ‘Control-C’ 或 ‘Delete’) 时将被引发。 在执
     行期间，会定期检测中断信号。 该异常继承自 *note BaseException: 2db.
     以确保不会被处理 *note Exception: 2dc. 的代码意外捕获，这样可以避免
     退出解释器。

 -- 例外: MemoryError

     当一个操作耗尽内存但情况仍可（通过删除一些对象）进行挽救时将被引发
     。 关联的值是一个字符串，指明是哪种（内部）操作耗尽了内存。 请注意
     由于底层的内存管理架构（C 的 ‘malloc()’ 函数），解释器也许并不总是
     能够从这种情况下完全恢复；但它毕竟可以引发一个异常，这样就能打印出
     栈回溯信息，以便找出导致问题的失控程序。

 -- 例外: NameError

     当某个局部或全局名称未找到时将被引发。 此异常仅用于非限定名称。 关
     联的值是一条错误信息，其中包含未找到的名称。

 -- 例外: NotImplementedError

     此异常派生自 *note RuntimeError: 3dc.。 在用户自定义的基类中，抽象
     方法应当在其要求所派生类重载该方法，或是在其要求所开发的类提示具体
     实现尚待添加时引发此异常。

          備註: 它不应当用来表示一个运算符或方法根本不能被支持 – 在此情
          况下应当让特定运算符 / 方法保持未定义，或者在子类中将其设为
          *note None: 203.。

          備註: ‘NotImplementedError’ 和 ‘NotImplemented’ 不可互换，即使
          它们有相似的名称和用途。 请参阅 *note NotImplemented: 202. 了
          解有关何时使用它们的详细说明。

 -- 例外: OSError ([arg])

 -- 例外: OSError (errno, strerror[, filename[, winerror[, filename2]]])

     此异常在一个系统函数返回系统相关的错误时将被引发，此类错误包括 I/O
     操作失败例如 "文件未找到" 或 "磁盘已满" 等（不包括非法参数类型或其
     他偶然性错误）。

     构造器的第二种形式可设置如下所述的相应属性。 如果未指定这些属性则默
     认为 *note None: 203.。 为了能向下兼容，如果传入了三个参数，则
     *note args: 1843. 属性将仅包含由前两个构造器参数组成的 2 元组。

     构造器实际返回的往往是 *note OSError: 304. 的某个子类，如下文 *note
     OS exceptions: 184a. 中所描述的。 具体的子类取决于最终的 *note
     errno: 184b. 值。 此行为仅在直接或通过别名来构造 *note OSError:
     304. 时发生，并且在子类化时不会被继承。

      -- 屬性: errno

          来自于 C 变量 ‘errno’ 的数字错误码。

      -- 屬性: winerror

          在 Windows 下，此参数将给出原生的 Windows 错误码。 而 *note
          errno: 184b. 属性将是该原生错误码在 POSIX 平台下的近似转换形式
          。

          在 Windows 下，如果 `winerror' 构造器参数是一个整数，则 *note
          errno: 184b. 属性会根据 Windows 错误码来确定，而 `errno' 参数
          会被忽略。 在其他平台上，`winerror' 参数会被忽略，并且 *note
          winerror: 184c. 属性将不存在。

      -- 屬性: strerror

          操作系统所提供的相应错误信息。 它在 POSIX 平台中由 C 函数
          ‘perror()’ 来格式化，在 Windows 中则是由 ‘FormatMessage()’。

      -- 屬性: filename
      -- 屬性: filename2

          对于与文件系统路径有关 (例如 *note open(): 16f. 或 *note
          os.unlink(): b18.) 的异常，*note filename: 184e. 是传给函数的
          文件名。 对于涉及两个文件系统路径的函数 (例如 *note
          os.rename(): b14.)，*note filename2: 184f. 将是传给函数的第二
          个文件名。

     3.3 版更變: *note EnvironmentError: a74, *note IOError: a73, *note
     WindowsError: a75, *note socket.error: a76, *note select.error:
     a77. 与 ‘mmap.error’ 已被合并到 *note OSError: 304.，构造器可能返回
     其中一个子类。

     3.4 版更變: *note filename: 184e. 属性现在将是传给函数的原始文件名
     ，而不是经过编码或基于文件系统编码进行解码之后的名称。 此外还添加了
     `filename2' 构造器参数和属性。

 -- 例外: OverflowError

     当算术运算的结果大到无法表示时将被引发。 这对整数来说不可能发生（宁
     可引发 *note MemoryError: f69. 也不会放弃尝试）。 但是出于历史原因
     ，有时也会在整数超出要求范围的情况下引发 OverflowError。 因为在 C 中
     缺少对浮点异常处理的标准化，大多数浮点运算都不会做检查。

 -- 例外: RecursionError

     此异常派生自 *note RuntimeError: 3dc.。 它会在解释器检测发现超过最
     大递归深度 (参见 *note sys.getrecursionlimit(): f3b.) 时被引发。

     3.5 版新加入: 在此之前将只引发 *note RuntimeError: 3dc.。

 -- 例外: ReferenceError

     此异常将在使用 *note weakref.proxy(): 37a. 函数所创建的弱引用来访问
     该引用的某个已被作为垃圾回收的属性时被引发。 有关弱引用的更多信息请
     参阅 *note weakref: 131. 模块。

 -- 例外: RuntimeError

     当检测到一个不归属于任何其他类别的错误时将被引发。 关联的值是一个指
     明究竟发生了什么问题的字符串。

 -- 例外: StopIteration

     由内置函数 *note next(): 775. 和 *note iterator: 1171. 的 *note
     __next__(): d2c. 方法所引发，用来表示该迭代器不能产生下一项。

     该异常对象只有一个属性 ‘value’，它在构造该异常时作为参数给出，默认
     值为 *note None: 203.。

     当一个 *note generator: a83. 或 *note coroutine: 18a. 函数返回时，
     将引发一个新的 *note StopIteration: 581. 实例，函数返回的值将被用作
     异常构造器的 ‘value’ 形参。

     如果某个生成器代码直接或间接地引发了 *note StopIteration: 581.，它
     会被转换为 *note RuntimeError: 3dc. (并将 *note StopIteration: 581.
     保留为导致新异常的原因)。

     3.3 版更變: 添加了 ‘value’ 属性及其被生成器函数用作返回值的功能。

     3.5 版更變: 引入了通过 ‘from __future__ import generator_stop’ 来实
     现 RuntimeError 转换，参见 PEP 479(1)。

     3.7 版更變: 默认对所有代码启用 PEP 479(2): 在生成器中引发的 *note
     StopIteration: 581. 错误将被转换为 *note RuntimeError: 3dc.。

 -- 例外: StopAsyncIteration

     必须由一个 *note asynchronous iterator: 738. 对象的 *note
     __anext__(): 155f. 方法来引发以停止迭代操作。

     3.5 版新加入.

 -- 例外: SyntaxError (message, details)

     当解析器遇到语法错误时引发。 这可以发生在 *note import: ce7. 语句，
     对内置函数 *note compile(): 2e7, *note exec(): d0c. 或 *note
     eval(): c61. 的调用，或是读取原始脚本或标准输入（也包括交互模式）的
     时候。

     异常实例的 *note str(): 205. 只返回错误消息。 错误详情为一个元组，
     其成员也可在单独的属性中分别获取。

      -- 屬性: filename

          发生语法错误所在文件的名称。

      -- 屬性: lineno

          发生错误所在文件中的行号。 行号索引从 1 开始：文件中首行的
          ‘lineno’ 为 1。

      -- 屬性: offset

          发生错误所在文件中的列号。 列号索引从 1 开始：行中首个字符的
          ‘offset’ 为 1。

      -- 屬性: text

          错误所涉及的源代码文本。

     对于 f-字符串字段中的错误，消息会带有 "f-string: " 前缀并且其位置是
     基于替换表达式构建的文本中的位置。 例如，编译 f’Bad {a b} field’ 将
     产生以下 args 属性: (’f-string: ...’, (’’, 1, 4, ’(a b)n’))。

 -- 例外: IndentationError

     与不正确的缩进相关的语法错误的基类。 这是 *note SyntaxError: 559. 的
     一个子类。

 -- 例外: TabError

     当缩进包含对制表符和空格符不一致的使用时将被引发。 这是 *note
     IndentationError: f39. 的一个子类。

 -- 例外: SystemError

     当解释器发现内部错误，但情况看起来尚未严重到要放弃所有希望时将被引
     发。 关联的值是一个指明发生了什么问题的字符串（表示为低层级的符号）
     。

     你应当将此问题报告给你所用 Python 解释器的作者或维护人员。 请确认报
     告 Python 解释器的版本号 (‘sys.version’; 它也会在交互式 Python 会话
     开始时被打印出来)，具体的错误消息（异常所关联的值）以及可能触发该错
     误的程序源码。

 -- 例外: SystemExit

     此异常由 *note sys.exit(): daa. 函数引发。 它继承自 *note
     BaseException: 2db. 而不是 *note Exception: 2dc. 以确保不会被处理
     *note Exception: 2dc. 的代码意外捕获。 这允许此异常正确地向上传播并
     导致解释器退出。 如果它未被处理，则 Python 解释器就将退出；不会打印
     任何栈回溯信息。 构造器接受的可选参数与传递给 *note sys.exit():
     daa. 的相同。 如果该值为一个整数，则它指明系统退出状态码（会传递给
     C 的 ‘exit()’ 函数）；如果该值为 ‘None’，则退出状态码为零；如果该值
     为其他类型（例如字符串），则会打印对象的值并将退出状态码设为一。

     对 *note sys.exit(): daa. 的调用会被转换为一个异常以便能执行清理处
     理程序 (*note try: e37. 语句的 *note finally: 2bc. 子句)，并且使得
     调试器可以执行一段脚本而不必冒失去控制的风险。 如果绝对确实地需要立
     即退出（例如在调用 *note os.fork(): a42. 之后的子进程中）则可使用
     *note os._exit(): 1854.

      -- 屬性: code

          传给构造器的退出状态码或错误信息（默认为 ‘None’。）

 -- 例外: TypeError

     当一个操作或函数被应用于类型不适当的对象时将被引发。 关联的值是一个
     字符串，给出有关类型不匹配的详情。

     此异常可以由用户代码引发，以表明尝试对某个对象进行的操作不受支持也
     不应当受支持。 如果某个对象应当支持给定的操作但尚未提供相应的实现，
     所要引发的适当异常应为 *note NotImplementedError: 704.。

     传入参数的类型错误 (例如在要求 *note int: 204. 时却传入了 *note
     list: 1f8.) 应当导致 *note TypeError: 1fe.，但传入参数的值错误 (例
     如传入要求范围之外的数值) 则应当导致 *note ValueError: 16d.。

 -- 例外: UnboundLocalError

     当在函数或方法中对某个局部变量进行引用，但该变量并未绑定任何值时将
     被引发。 此异常是 *note NameError: e40. 的一个子类。

 -- 例外: UnicodeError

     当发生与 Unicode 相关的编码或解码错误时将被引发。 此异常是 *note
     ValueError: 16d. 的一个子类。

     *note UnicodeError: d03. 具有一些描述编码或解码错误的属性。 例如
     ‘err.object[err.start:err.end]’ 会给出导致编解码器失败的特定无效输
     入。

      -- 屬性: encoding

          引发错误的编码名称。

      -- 屬性: reason

          描述特定编解码器错误的字符串。

      -- 屬性: object

          编解码器试图要编码或解码的对象。

      -- 屬性: start

          *note object: 3d2. 中无效数据的开始位置索引。

      -- 屬性: end

          *note object: 3d2. 中无效数据的末尾位置索引（不含）。

 -- 例外: UnicodeEncodeError

     当在编码过程中发生与 Unicode 相关的错误时将被引发。 此异常是 *note
     UnicodeError: d03. 的一个子类。

 -- 例外: UnicodeDecodeError

     当在解码过程中发生与 Unicode 相关的错误时将被引发。 此异常是 *note
     UnicodeError: d03. 的一个子类。

 -- 例外: UnicodeTranslateError

     在转写过程中发生与 Unicode 相关的错误时将被引发。 此异常是 *note
     UnicodeError: d03. 的一个子类。

 -- 例外: ValueError

     当操作或函数接收到具有正确类型但值不适合的参数，并且情况不能用更精
     确的异常例如 *note IndexError: f36. 来描述时将被引发。

 -- 例外: ZeroDivisionError

     当除法或取余运算的第二个参数为零时将被引发。 关联的值是一个字符串，
     指明操作数和运算的类型。

下列异常被保留以与之前的版本相兼容；从 Python 3.3 开始，它们都是 *note
OSError: 304. 的别名。

 -- 例外: EnvironmentError

 -- 例外: IOError

 -- 例外: WindowsError

     限在 Windows 中可用。

* Menu:

* OS 异常::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0479

   (2) https://www.python.org/dev/peps/pep-0479


File: python.info,  Node: OS 异常,  Up: 具体异常

5.5.4.1 OS 异常
...............

下列异常均为 *note OSError: 304. 的子类，它们将根据系统错误代码被引发。

 -- 例外: BlockingIOError

     当一个操作会被某个设置为非阻塞操作的对象（例如套接字）所阻塞时将被
     引发。 对应于 ‘errno’ ‘EAGAIN’, ‘EALREADY’, ‘EWOULDBLOCK’ 和
     ‘EINPROGRESS’。

     除了 *note OSError: 304. 已有的属性，*note BlockingIOError: a78. 还
     有一个额外属性：

      -- 屬性: characters_written

          一个整数，表示在被阻塞前已写入到流的字符数。 当使用来自 *note
          io: a1. 模块的带缓冲 I/O 类时此属性可用。

 -- 例外: ChildProcessError

     当一个子进程上的操作失败时将被引发。 对应于 ‘errno’ ‘ECHILD’。

 -- 例外: ConnectionError

     与连接相关问题的基类。

     其子类有 *note BrokenPipeError: a7e, *note ConnectionAbortedError:
     a7f, *note ConnectionRefusedError: a80. 和 *note
     ConnectionResetError: a81.。

 -- 例外: BrokenPipeError

     *note ConnectionError: 7d7. 的子类，当试图写入另一端已被关闭的管道
     ，或是试图写入已关闭写入的套接字时将被引发。 对应于 ‘errno’ ‘EPIPE’
     和 ‘ESHUTDOWN’。

 -- 例外: ConnectionAbortedError

     *note ConnectionError: 7d7. 的子类，当连接尝试被对端中止时将被引发
     。 对应于 ‘errno’ ‘ECONNABORTED’。

 -- 例外: ConnectionRefusedError

     *note ConnectionError: 7d7. 的子类，当连接尝试被对端拒绝时将被引发
     。 对应于 ‘errno’ ‘ECONNREFUSED’。

 -- 例外: ConnectionResetError

     *note ConnectionError: 7d7. 的子类，当连接被对端重置时将被引发。 对
     应于 ‘errno’ ‘ECONNRESET’。

 -- 例外: FileExistsError

     当试图创建一个已存在的文件或目录时将被引发。 对应于 ‘errno’
     ‘EEXIST’。

 -- 例外: FileNotFoundError

     当所请求的文件或目录不存在时将被引发。 对应于 ‘errno’ ‘ENOENT’。

 -- 例外: InterruptedError

     当系统调用被输入信号中断时将被引发。 对应于 ‘errno’ *note EINTR:
     74b.。

     3.5 版更變: 当系统调用被某个信号中断时，Python 现在会重试系统调用，
     除非该信号的处理程序引发了其它异常 (原理参见 PEP 475(1)) 而不是引发
     *note InterruptedError: 74c.。

 -- 例外: IsADirectoryError

     当请求对一个目录执行文件操作 (例如 *note os.remove(): b13.) 将被引
     发。 对应于 ‘errno’ ‘EISDIR’。

 -- 例外: NotADirectoryError

     当在非目录上请求目录操作 (例如 *note os.listdir(): b1c.) 时被引发。
     在大多数 POSIX 平台上，它还可能在某个操作尝试以目录方式打开或遍历非
     目录时被引发。 对应于 ‘errno’ ‘ENOTDIR’。

 -- 例外: PermissionError

     当在没有足够操作权限的情况下试图执行某个操作时将被引发 —— 例如缺少
     文件系统权限。 对应于 ‘errno’ ‘EACCES’ 和 ‘EPERM’。

 -- 例外: ProcessLookupError

     当给定的进程不存在时将被引发。 对应于 ‘errno’ ‘ESRCH’。

 -- 例外: TimeoutError

     当一个系统函数发生系统级超时的情况下将被引发。 对应于 ‘errno’
     ‘ETIMEDOUT’。

3.3 版新加入: 添加了以上所有 *note OSError: 304. 的子类。

也參考
......

PEP 3151(2) - 重写 OS 和 IO 异常的层次结构

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0475

   (2) https://www.python.org/dev/peps/pep-3151


File: python.info,  Node: 警告,  Next: 异常层次结构,  Prev: 具体异常,  Up: 內建的例外

5.5.5 警告
----------

下列异常被用作警告类别；请参阅 *note 警告类别: 185f. 文档了解详情。

 -- 例外: Warning

     警告类别的基类。

 -- 例外: UserWarning

     用户代码所产生警告的基类。

 -- 例外: DeprecationWarning

     如果所发出的警告是针对其他 Python 开发者的，则以此作为与已弃用特性
     相关警告的基类。

     会被默认警告过滤器忽略，在 ‘__main__’ 模块中的情况除外 ( PEP
     565(1))。 启用 *note Python 开发模式: 160. 时会显示此警告。

     The deprecation policy is described in PEP 387(2).

 -- 例外: PendingDeprecationWarning

     对于已过时并预计在未来弃用，但目前尚未弃用的特性相关警告的基类。

     这个类很少被使用，因为针对未来可能的弃用发出警告的做法并不常见，而
     针对当前已有的弃用则推荐使用 *note DeprecationWarning: 15a.。

     会被默认警告过滤器忽略。 启用 *note Python 开发模式: 160. 时会显示
     此警告。

     The deprecation policy is described in PEP 387(3).

 -- 例外: SyntaxWarning

     与模糊的语法相关的警告的基类。

 -- 例外: RuntimeWarning

     与模糊的运行时行为相关的警告的基类。

 -- 例外: FutureWarning

     如果所发出的警告是针对以 Python 所编写应用的最终用户的，则以此作为
     与已弃用特性相关警告的基类。

 -- 例外: ImportWarning

     与在模块导入中可能的错误相关的警告的基类。

     会被默认警告过滤器忽略。 启用 *note Python 开发模式: 160. 时会显示
     此警告。

 -- 例外: UnicodeWarning

     与 Unicode 相关的警告的基类。

 -- 例外: BytesWarning

     与 *note bytes: 172. 和 *note bytearray: 173. 相关的警告的基类。

 -- 例外: ResourceWarning

     资源使用相关警告的基类。

     会被默认警告过滤器忽略。 启用 *note Python 开发模式: 160. 时会显示
     此警告。

     3.2 版新加入.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0565

   (2) https://www.python.org/dev/peps/pep-0387

   (3) https://www.python.org/dev/peps/pep-0387


File: python.info,  Node: 异常层次结构,  Prev: 警告,  Up: 內建的例外

5.5.6 异常层次结构
------------------

内置异常的类层级结构如下：

     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


File: python.info,  Node: 文本處理 Text Processing 服務,  Next: 二进制数据服务,  Prev: 內建的例外,  Up: Python 標準函式庫 Standard Library

5.6 文本處理 (Text Processing) 服務
===================================

本章節介紹的模組 (module) 提供了廣泛的字串操作與其他文本處理服務。

在 *note 二进制数据服务: 1865. 下所描述的 *note codecs: 1b. 模組也與文本
處理高度相關。另外也請參閱在 *note 文本序列类型 — str: 1357. 中所描述的
Python 內建字串型別。

* 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 的补全函数


File: python.info,  Node: string --- 常见的字符串操作,  Next: re --- 正则表达式操作,  Up: 文本處理 Text Processing 服務

5.6.1 ‘string’ — 常见的字符串操作
---------------------------------

`源代码：' Lib/string.py(1)

__________________________________________________________________

也參考
......

*note 文本序列类型 — str: 1357.

*note 字符串的方法: 1358.

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/string.py


File: python.info,  Node: 字符串常量,  Next: 自定义字符串格式化,  Up: string --- 常见的字符串操作

5.6.1.1 字符串常量
..................

此模块中定义的常量为：

 -- Data: string.ascii_letters

     下文所述 *note ascii_lowercase: 1869. 和 *note ascii_uppercase:
     186a. 常量的拼连。 该值不依赖于语言区域。

 -- Data: string.ascii_lowercase

     小写字母 ‘'abcdefghijklmnopqrstuvwxyz'’。 该值不依赖于语言区域，不
     会发生改变。

 -- Data: string.ascii_uppercase

     大写字母 ‘'ABCDEFGHIJKLMNOPQRSTUVWXYZ'’。 该值不依赖于语言区域，不
     会发生改变。

 -- Data: string.digits

     字符串 ‘'0123456789'’。

 -- Data: string.hexdigits

     字符串 ‘'0123456789abcdefABCDEF'’。

 -- Data: string.octdigits

     字符串 ‘'01234567'’。

 -- Data: string.punctuation

     由在 ‘C’ 区域设置中被视为标点符号的 ASCII 字符所组成的字符串:
     ‘!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~’.

 -- Data: string.printable

     由被视为可打印符号的 ASCII 字符组成的字符串。 这是 *note digits:
     186b, *note ascii_letters: d24, *note punctuation: 186e. 和 *note
     whitespace: 1870. 的总和。

 -- Data: string.whitespace

     由被视为空白符号的 ASCII 字符组成的字符串。 其中包括空格、制表、换
     行、回车、进纸和纵向制表符。


File: python.info,  Node: 自定义字符串格式化,  Next: 格式字符串语法,  Prev: 字符串常量,  Up: string --- 常见的字符串操作

5.6.1.2 自定义字符串格式化
..........................

内置的字符串类提供了通过使用 PEP 3101(1) 所描述的 *note format(): 5d4. 方
法进行复杂变量替换和值格式化的能力。 *note string: f6. 模块中的 *note
Formatter: 8a3. 类允许你使用与内置 *note format(): 5d4. 方法相同的实现来
创建并定制你自己的字符串格式化行为。

 -- 類別: string.Formatter

     *note Formatter: 8a3. 类包含下列公有方法：

      -- 成員函式: format (format_string, /, *args, **kwargs)

          首要的 API 方法。 它接受一个格式字符串和任意一组位置和关键字参
          数。 它只是一个调用 *note vformat(): 1872. 的包装器。

          3.7 版更變: 格式字符串参数现在是 *note 仅限位置参数: 3c9.。

      -- 成員函式: vformat (format_string, args, kwargs)

          此函数执行实际的格式化操作。 它被公开为一个单独的函数，用于需
          要传入一个预定义字母作为参数，而不是使用 ‘*args’ 和 ‘**kwargs’
          语法将字典解包为多个单独参数并重打包的情况。 *note vformat():
          1872. 完成将格式字符串分解为字符数据和替换字段的工作。 它会调
          用下文所述的几种不同方法。

     此外，*note Formatter: 8a3. 还定义了一些旨在被子类替换的方法：

      -- 成員函式: parse (format_string)

          循环遍历 format_string 并返回一个由可迭代对象组成的元组
          (`literal_text', `field_name', `format_spec', `conversion')。
          它会被 *note vformat(): 1872. 用来将字符串分解为文本字面值或替
          换字段。

          元组中的值在概念上表示一段字面文本加上一个替换字段。 如果没有
          字面文本（如果连续出现两个替换字段就会发生这种情况），则
          `literal_text' 将是一个长度为零的字符串。 如果没有替换字段，则
          `field_name', `format_spec' 和 `conversion' 的值将为 ‘None’。

      -- 成員函式: get_field (field_name, args, kwargs)

          给定 `field_name' 作为 *note parse(): 1873. (见上文) 的返回值
          ，将其转换为要格式化的对象。 返回一个元组 (obj, used_key)。 默
          认版本接受在 PEP 3101(2) 所定义形式的字符串，例如 "0[name]" 或
          "label.title"。 `args' 和 `kwargs' 与传给 *note vformat():
          1872. 的一样。 返回值 `used_key' 与 *note get_value(): 1875. 的
          `key' 形参具有相同的含义。

      -- 成員函式: get_value (key, args, kwargs)

          提取给定的字段值。 `key' 参数将为整数或字符串。 如果是整数，它
          表示 `args' 中位置参数的索引；如果是字符串，它表示 `kwargs' 中
          的关键字参数名。

          `args' 形参会被设为 *note vformat(): 1872. 的位置参数列表，而
          `kwargs' 形参会被设为由关键字参数组成的字典。

          对于复合字段名称，仅会为字段名称的第一个组件调用这些函数；后续
          组件会通过普通属性和索引操作来进行处理。

          因此举例来说，字段表达式 ’0.name’ 将导致调用 *note
          get_value(): 1875. 时附带 `key' 参数值 0。 在 *note
          get_value(): 1875. 通过调用内置的 *note getattr(): 54b. 函数返
          回后将会查找 ‘name’ 属性。

          如果索引或关键字引用了一个不存在的项，则将引发 *note
          IndexError: f36. 或 *note KeyError: 3e9.。

      -- 成員函式: check_unused_args (used_args, args, kwargs)

          在必要时实现对未使用参数进行检测。 此函数的参数是是格式字符串
          中实际引用的所有参数键的集合（整数表示位置参数，字符串表示名称
          参数），以及被传给 vformat 的 `args' 和 `kwargs' 的引用。 未使
          用参数的集合可以根据这些形参计算出来。 如果检测失败则 *note
          check_unused_args(): 1876. 应会引发一个异常。

      -- 成員函式: format_field (value, format_spec)

          *note format_field(): 1877. 会简单地调用内置全局函数 *note
          format(): 5d5.。 提供该方法是为了让子类能够重载它。

      -- 成員函式: convert_field (value, conversion)

          使用给定的转换类型（来自 *note parse(): 1873. 方法所返回的元组
          ）来转换（由 *note get_field(): 1874. 所返回的）值。 默认版本
          支持 ’s’ (str), ’r’ (repr) 和 ’a’ (ascii) 等转换类型。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3101

   (2) https://www.python.org/dev/peps/pep-3101


File: python.info,  Node: 格式字符串语法,  Next: 模板字符串,  Prev: 自定义字符串格式化,  Up: string --- 常见的字符串操作

5.6.1.3 格式字符串语法
......................

*note str.format(): 5d4. 方法和 *note Formatter: 8a3. 类共享相同的格式字
符串语法（虽然对于 *note Formatter: 8a3. 来说，其子类可以定义它们自己的
格式字符串语法）。 具体语法与 *note 格式化字符串字面值: 296. 相似，但较
为简单一些，并且关键的一点是不支持任意表达式。

格式字符串包含有以花括号 ‘{}’ 括起来的“替换字段”。 不在花括号之内的内容
被视为字面文本，会不加修改地复制到输出中。 如果你需要在字面文本中包含花
括号字符，可以通过重复来转义: ‘{{’ and ‘}}’。

替换字段的语法如下：

          replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
          field_name        ::= arg_name ("." attribute_name | "[" element_index "]")*
          arg_name          ::= [identifier | digit+]
          attribute_name    ::= identifier
          element_index     ::= digit+ | index_string
          index_string      ::= <any source character except "]"> +
          conversion        ::= "r" | "s" | "a"
          format_spec       ::= <described in the next section>

用不太正式的术语来描述，替换字段开头可以用一个 `field_name' 指定要对值进
行格式化并取代替换字符被插入到输出结果的对象。 `field_name' 之后有可选的
`conversion' 字段，它是一个感叹号 ‘'!'’ 加一个 `format_spec'，并以一个冒
号 ‘':'’ 打头。 这些指明了替换值的非默认格式。

另请参阅 *note 格式规格迷你语言: 5d8. 一节。

`field_name' 本身以一个数字或关键字 `arg_name' 打头。 如果为数字，则它指
向一个位置参数，而如果为关键字，则它指向一个命名关键字参数。 如果格式字
符串中的数字 arg_names 为 0, 1, 2, ... 的序列，它们可以全部省略（而非部
分省略），数字 0, 1, 2, ... 将会按顺序自动插入。 由于 `arg_name' 不使用
引号分隔，因此无法在格式字符串中指定任意的字典键 (例如字符串 ‘'10'’ 或
‘':-]'’)。 `arg_name' 之后可以带上任意数量的索引或属性表达式。 ‘'.name'’
形式的表达式会使用 *note getattr(): 54b. 选择命名属性，而 ‘'[index]'’ 形
式的表达式会使用 *note __getitem__(): 3a5. 执行索引查找。

3.1 版更變: 位置参数说明符对于 *note str.format(): 5d4. 可以省略，因此
‘'{} {}'.format(a, b)’ 等价于 ‘'{0} {1}'.format(a, b)’。

3.4 版更變: 位置参数说明符对于 *note Formatter: 8a3. 可以省略。

一些简单的格式字符串示例

     "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'.

使用 `conversion' 字段在格式化之前进行类型强制转换。 通常，格式化值的工
作由值本身的 *note __format__(): a2f. 方法来完成。 但是，在某些情况下最
好强制将类型格式化为一个字符串，覆盖其本身的格式化定义。 通过在调用
*note __format__(): a2f. 之前将值转换为字符串，可以绕过正常的格式化逻辑
。

目前支持的转换旗标有三种: ‘'!s'’ 会对值调用 *note str(): 205.，‘'!r'’ 调
用 *note repr(): 8b9. 而 ‘'!a'’ 则调用 *note ascii(): e11.。

一些範例：

     "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

`format_spec' 字段包含值应如何呈现的规格描述，例如字段宽度、对齐、填充、
小数精度等细节信息。 每种值类型可以定义自己的“格式化迷你语言”或对
`format_spec' 的解读方式。

大多数内置类型都支持同样的格式化迷你语言，具体描述见下一节。

`format_spec' 字段还可以在其内部包含嵌套的替换字段。 这些嵌套的替换字段
可能包括字段名称、转换旗标和格式规格描述，但是不再允许更深层的嵌套。
format_spec 内部的替换字段会在解读 `format_spec' 字符串之前先被解读。 这
将允许动态地指定特定值的格式。

请参阅 *note 格式示例: 1882. 一节查看相关示例。

* Menu:

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


File: python.info,  Node: 格式规格迷你语言,  Next: 格式示例,  Up: 格式字符串语法

5.6.1.4 格式规格迷你语言
........................

“格式规格”在格式字符串所包含的替换字段内部使用，用于定义单个值应如何呈现
(参见 *note 格式字符串语法: de0. 和 *note 格式字符串字面值: 296.)。 它们
也可以被直接传给内置的 *note format(): 5d5. 函数。 每种可格式化的类型都
可以自行定义如何对格式规格进行解读。

大多数内置类型都为格式规格实现了下列选项，不过某些格式化选项只被数值类型
所支持。

一般约定空的格式描述将产生与在值上调用 *note str(): 205. 相同的结果。 非
空格式描述通常会修改此结果。

`标准格式说明符' 的一般形式如下：

     format_spec     ::= [[fill]align][sign][#][0][width][grouping_option][.precision][type]
     fill            ::= <any character>
     align           ::= "<" | ">" | "=" | "^"
     sign            ::= "+" | "-" | " "
     width           ::= digit+
     grouping_option ::= "_" | ","
     precision       ::= digit+
     type            ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

如果指定了一个有效的 `align' 值，则可以在该值前面加一个 `fill' 字符，它
可以为任意字符，如果省略则默认为空格符。 在 *note 格式化字符串字面值:
296. 或在使用 *note str.format(): 5d4. 方法时是无法使用花括号字面值
("‘{’" or "‘}’") 作为 `fill' 字符的。 但是，通过嵌套替换字段插入花括号则
是可以的。 这个限制不会影响 *note format(): 5d5. 函数。

各种对齐选项的含义如下：

     选项          意义
                   
     -----------------------------------------------------------------------------
                   
     ‘'<'’         强制字段在可用空间内左对齐（这是大多数对象的默认值）。
                   
                   
     ‘'>'’         强制字段在可用空间内右对齐（这是数字的默认值）。
                   
                   
     ‘'='’         强制将填充放置在符号（如果有）之后但在数字之前。这用于以
                   “+000000120”形式打印字段。此对齐选项仅对数字类型有效。当
                   ’0’紧接在字段宽度之前时，它成为默认值。
                   
                   
     ‘'^'’         强制字段在可用空间内居中。
                   

请注意，除非定义了最小字段宽度，否则字段宽度将始终与填充它的数据大小相同
，因此在这种情况下，对齐选项没有意义。

`sign' 选项仅对数字类型有效，可以是以下之一：

     选项          意义
                   
     -----------------------------------------------------------------------------
                   
     ‘'+'’         表示标志应该用于正数和负数。
                   
                   
     ‘'-'’         表示标志应仅用于负数（这是默认行为）。
                   
                   
     space         表示应在正数上使用前导空格，在负数上使用减号。
                   

‘'#'’ 选项可让“替代形式”被用于执行转换。 替代形式会针对不同的类型分别定
义。 此选项仅适用于整数、浮点数和复数类型。 对于整数类型，当使用二进制、
八进制或十六进制输出时，此选项会为输出值分别添加相应的 ‘'0b'’, ‘'0o'’,
‘'0x'’ 或 ‘'0X'’ 前缀。 对于浮点数和复数类型，替代形式会使得转换结果总是
包含小数点符号，即使其不带小数部分。 通常只有在带有小数部分的情况下，此
类转换的结果中才会出现小数点符号。 此外，对于 ‘'g'’ 和 ‘'G'’ 转换，末尾
的零不会从结果中被移除。

‘','’ 选项表示使用逗号作为千位分隔符。 对于感应区域设置的分隔符，请改用
‘'n'’ 整数表示类型。

3.1 版更變: 添加了 ‘','’ 选项 (另请参阅 PEP 378(1))。

‘'_'’ 选项表示对浮点表示类型和整数表示类型 ‘'d'’ 使用下划线作为千位分隔
符。 对于整数表示类型 ‘'b'’, ‘'o'’, ‘'x'’ 和 ‘'X'’，将为每 4 个数位插入
一个下划线。 对于其他表示类型指定此选项则将导致错误。

3.6 版更變: 添加了 ‘'_'’ 选项 (另请参阅 PEP 515(2))。

`width' 是一个定义最小总字段宽度的十进制整数，包括任何前缀、分隔符和其他
格式化字符。 如果未指定，则字段宽度将由内容确定。

当未显式给出对齐方式时，在 `width' 字段前加一个零 (‘'0'’) 字段将为数字类
型启用感知正负号的零填充。 这相当于设置 `fill' 字符为 ‘'0'’ 且
`alignment' 类型为 ‘'='’。

`precision' 是一个十进制数字，表示对于以 ‘'f'’ and ‘'F'’ 格式化的浮点数
值要在小数点后显示多少个数位，或者对于以 ‘'g'’ 或 ‘'G'’ 格式化的浮点数值
要在小数点前后共显示多少个数位。 对于非数字类型，该字段表示最大字段大小
—— 换句话说就是要使用多少个来自字段内容的字符。 对于整数值则不允许使用
`precision'。

最后，`type' 确定了数据应如何呈现。

可用的字符串表示类型是：

     类型          意义
                   
     -----------------------------------------------------------------------------
                   
     ‘'s'’         字符串格式。这是字符串的默认类型，可以省略。
                   
                   
     None          和 ‘'s'’ 一样。
                   

可用的整数表示类型是：

     类型          意义
                   
     -----------------------------------------------------------------------------
                   
     ‘'b'’         二进制格式。 输出以 2 为基数的数字。
                   
                   
     ‘'c'’         字符。在打印之前将整数转换为相应的unicode字符。
                   
                   
     ‘'d'’         十进制整数。 输出以 10 为基数的数字。
                   
                   
     ‘'o'’         八进制格式。 输出以 8 为基数的数字。
                   
                   
     ‘'x'’         十六进制格式。 输出以 16 为基数的数字，使用小写字母表示 9 以
                   上的数码。
                   
                   
     ‘'X'’         十六进制格式。 输出以 16 为基数的数字，使用大写字母表示 9 以
                   上的数码。 在指定 ‘'#'’ 的情况下，前缀 ‘'0x'’ 也将被转为大写
                   形式 ‘'0X'’。
                   
                   
     ‘'n'’         数字。 这与 ‘'d'’ 相似，不同之处在于它会使用当前区域设置来插
                   入适当的数字分隔字符。
                   
                   
     None          和 ‘'d'’ 相同。
                   

在上述的表示类型之外，整数还可以通过下列的浮点表示类型来格式化 (除了
‘'n'’ 和 ‘None’)。 当这样做时，会在格式化之前使用 *note float(): 1fd. 将
整数转换为浮点数。

*note float: 1fd. 和 *note Decimal: 2c0. 值的可用表示类型有:

     类型          意义
                   
     -----------------------------------------------------------------------------
                   
     ‘'e'’         科学计数法。 对于一个给定的精度 ‘p’，将数字格式化为以字母
                   ’e’ 分隔系数和指数的科学计数法形式。 系数在小数点之前有一位
                   ，之后有 ‘p’ 位，总计 ‘p + 1’ 个有效数位。 如未指定精度，则
                   会对 *note float: 1fd. 采用小数点之后 ‘6’ 位精度，而对
                   *note Decimal: 2c0. 则显示所有系数位。 如果小数点之后没有数
                   位，则小数点也会被略去，除非使用了 ‘#’ 选项。
                   
                   
     ‘'E'’         科学计数法。 与 ‘'e'’ 相似，不同之处在于它使用大写字母 ’E’ 作
                   为分隔字符。
                   
                   
     ‘'f'’         定点表示法。 对于一个给定的精度 ‘p’，将数字格式化为在小数点
                   之后恰好有 ‘p’ 位的小数形式。 如未指定精度，则会对
                   *note float: 1fd. 采用小数点之后 ‘6’ 位精度，而对
                   *note Decimal: 2c0. 则使用大到足够显示所有系数位的精度。 如
                   果小数点之后没有数位，则小数点也会被略去，除非使用了 ‘#’ 选
                   项。
                   
                   
     ‘'F'’         定点表示。 与 ‘'f'’ 相似，但会将 ‘nan’ 转为 ‘NAN’ 并将 ‘inf’
                   转为 ‘INF’。
                   
                   
     ‘'g'’         常规格式。 对于给定精度 ‘p >= 1’，这会将数值舍入到 ‘p’ 个有
                   效数位，再将结果以定点表示法或科学计数法进行格式化，具体取决
                   于其值的大小。 精度 ‘0’ 会被视为等价于精度 ‘1’。
                   
                   准确的规则如下：假设使用表示类型 ‘'e'’ 和精度 ‘p-1’ 进行格式
                   化的结果具有指数值 ‘exp’。 那么如果 ‘m <= exp < p’，其中 ‘m’
                   以 -4 表示浮点值而以 -6 表示 *note Decimal: 2c0. 值，该数字
                   将使用类型 ‘'f'’ 和精度 ‘p-1-exp’ 进行格式化。 否则的话，该
                   数字将使用表示类型 ‘'e'’ 和精度 ‘p-1’ 进行格式化。 在两种情
                   况下，都会从有效数字中移除无意义的末尾零，如果小数点之后没有
                   余下数字则小数点也会被移除，除非使用了 ‘'#'’ 选项。
                   
                   如未指定精度，会对 *note float: 1fd. 采用 ‘6’ 个有效数位的精
                   度。 对于 *note Decimal: 2c0.，结果的系数会沿用原值的系数数
                   位；对于绝对值小于 ‘1e-6’ 的值以及最小有效数位的位值大于 1 的
                   数值将会使用科学计数法，在其他情况下则会使用定点表示法。
                   
                   正负无穷，正负零和 nan 会分别被格式化为 ‘inf’, ‘-inf’, ‘0’,
                   ‘-0’ 和 ‘nan’，无论精度如何设定。
                   
                   
     ‘'G'’         常规格式。 类似于 ‘'g'’，不同之处在于当数值非常大时会切换为
                   ‘'E'’。 无穷与 NaN 也会表示为大写形式。
                   
                   
     ‘'n'’         数字。 这与 ‘'g'’ 相似，不同之处在于它会使用当前区域设置来插
                   入适当的数字分隔字符。
                   
                   
     ‘'%'’         百分比。 将数字乘以 100 并显示为定点 (‘'f'’) 格式，后面带一
                   个百分号。
                   
                   
     None          对于 *note float: 1fd. 来说这类似于 ‘'g'’，不同之处在于当使
                   用定点表示法时，小数点之后将至少显示一位。 所用的精度会大到
                   足以精确表示给定的值。
                   
                   对于 *note Decimal: 2c0. 来说这相当于 ‘'g'’ 或 ‘'G'’，具体取
                   决于当前 decimal 上下文的 ‘context.capitals’ 值。
                   
                   总体效果是将 *note str(): 205. 的输出匹配为其他格式化因子所
                   调整出的样子。
                   

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0378

   (2) https://www.python.org/dev/peps/pep-0515


File: python.info,  Node: 格式示例,  Prev: 格式规格迷你语言,  Up: 格式字符串语法

5.6.1.5 格式示例
................

本节包含 *note str.format(): 5d4. 语法的示例以及与旧式 ‘%’ 格式化的比较
。

该语法在大多数情况下与旧式的 ‘%’ 格式化类似，只是增加了 ‘{}’ 和 ‘:’ 来取
代 ‘%’。 例如，，‘'%03.2f'’ 可以被改写为 ‘'{:03.2f}'’。

新的格式语法还支持新增的不同选项，将在以下示例中说明。

按位置访问参数:

     >>> '{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'

按名称访问参数:

     >>> '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'

访问参数的属性:

     >>> 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)'

访问参数的项:

     >>> coord = (3, 5)
     >>> 'X: {0[0]};  Y: {0[1]}'.format(coord)
     'X: 3;  Y: 5'

替代 ‘%s’ 和 ‘%r’:

     >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
     "repr() shows quotes: 'test1'; str() doesn't: test2"

对齐文本以及指定宽度:

     >>> '{:<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***********'

替代 ‘%+f’, ‘%-f’ 和 ‘% f’ 以及指定正负号:

     >>> '{:+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'

替代 ‘%x’ 和 ‘%o’ 以及转换基于不同进位制的值:

     >>> # 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'

使用逗号作为千位分隔符:

     >>> '{:,}'.format(1234567890)
     '1,234,567,890'

表示为百分数:

     >>> points = 19
     >>> total = 22
     >>> 'Correct answers: {:.2%}'.format(points/total)
     'Correct answers: 86.36%'

使用特定类型的专属格式化:

     >>> 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'

嵌套参数以及更复杂的示例:

     >>> 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


File: python.info,  Node: 模板字符串,  Next: 辅助函数,  Prev: 格式字符串语法,  Up: string --- 常见的字符串操作

5.6.1.6 模板字符串
..................

模板字符串提供了由 PEP 292(1) 所描述的更简便的字符串替换方式。 模板字符
串的一个主要用例是文本国际化 (i18n)，因为在此场景下，更简单的语法和功能
使得文本翻译过程比使用 Python 的其他内置字符串格式化工具更为方便。 作为
基于模板字符串构建以实现 i18n 的库的一个示例，请参看 flufl.i18n(2) 包。

模板字符串支持基于 ‘$’ 的替换，使用以下规则：

   * ‘$$’ 为转义符号；它会被替换为单个的 ‘$’。

   * ‘$identifier’ 为替换占位符，它会匹配一个名为 ‘"identifier"’ 的映射
     键。 在默认情况下，‘"identifier"’ 限制为任意 ASCII 字母数字（包括下
     划线）组成的字符串，不区分大小写，以下划线或 ASCII 字母开头。 在
     ‘$’ 字符之后的第一个非标识符字符将表明占位符的终结。

   * ‘${identifier}’ 等价于 ‘$identifier’。 当占位符之后紧跟着有效的但又
     不是占位符一部分的标识符字符时需要使用，例如 ‘"${noun}ification"’。

在字符串的其他位置出现 ‘$’ 将导致引发 *note ValueError: 16d.。

*note string: f6. 模块提供了实现这些规则的 *note Template: 4f0. 类。
*note Template: 4f0. 有下列方法：

 -- 類別: string.Template (template)

     该构造器接受一个参数作为模板字符串。

      -- 成員函式: substitute (mapping={}, /, **kwds)

          执行模板替换，返回一个新字符串。 `mapping' 为任意字典类对象，
          其中的键将匹配模板中的占位符。 或者你也可以提供一组关键字参数
          ，其中的关键字即对应占位符。 当同时给出 `mapping' 和 `kwds' 并
          且存在重复时，则以 `kwds' 中的占位符为优先。

      -- 成員函式: safe_substitute (mapping={}, /, **kwds)

          类似于 *note substitute(): 1433.，不同之处是如果有占位符未在
          `mapping' 和 `kwds' 中找到，不是引发 *note KeyError: 3e9. 异常
          ，而是将原始占位符不加修改地显示在结果字符串中。 另一个与
          *note substitute(): 1433. 的差异是任何在其他情况下出现的 ‘$’ 将
          简单地返回 ‘$’ 而不是引发 *note ValueError: 16d.。

          此方法被认为“安全”，因为虽然仍有可能发生其他异常，但它总是尝试
          返回可用的字符串而不是引发一个异常。 从另一方面来说，*note
          safe_substitute(): 1434. 也可能根本算不上安全，因为它将静默地
          忽略错误格式的模板，例如包含多余的分隔符、不成对的花括号或不是
          合法 Python 标识符的占位符等等。

     *note Template: 4f0. 的实例还提供一个公有数据属性：

      -- 屬性: template

          这是作为构造器的 `template' 参数被传入的对象。 一般来说，你不
          应该修改它，但并不强制要求只读访问。

以下是一个如何使用模版的示例：

     >>> 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'

进阶用法：你可以派生 *note Template: 4f0. 的子类来自定义占位符语法、分隔
符，或用于解析模板字符串的整个正则表达式。 为此目的，你可以重载这些类属
性：

   * `delimiter' – 这是用来表示占位符的起始的分隔符的字符串字面值。 默认
     值为 ‘$’。 请注意此参数 `不能' 为正则表达式，因为其实现将在必要时对
     此字符串调用 *note re.escape(): 58f.。 还要注意你不能在创建类之后改
     变此分隔符（例如在子类的类命名空间中必须设置不同的分隔符）。

   * `idpattern' – 这是用来描述不带花括号的占位符的模式的正则表达式。 默
     认值为正则表达式 ‘(?a:[_a-z][_a-z0-9]*)’。 如果给出了此属性并且
     `braceidpattern' 为 ‘None’ 则此模式也将作用于带花括号的占位符。

          備註: 由于默认的 `flags' 为 ‘re.IGNORECASE’，模式 ‘[a-z]’ 可以
          匹配某些非 ASCII 字符。 因此我们在这里使用了局部旗标 ‘a’。

     3.7 版更變: `braceidpattern' 可被用来定义对花括号内部和外部进行区分
     的模式。

   * `braceidpattern' – 此属性类似于 `idpattern' 但是用来描述带花括号的
     占位符的模式。 默认值 ‘None’ 意味着回退到 `idpattern' (即在花括号内
     部和外部使用相同的模式)。 如果给出此属性，这将允许你为带花括号和不
     带花括号的占位符定义不同的模式。

     3.7 版新加入.

   * `flags' – 将在编译用于识别替换内容的正则表达式被应用的正则表达式旗
     标。 默认值为 ‘re.IGNORECASE’。 请注意 ‘re.VERBOSE’ 总是会被加为旗
     标，因此自定义的 `idpattern' 必须遵循详细正则表达式的约定。

     3.2 版新加入.

作为另一种选项，你可以通过重载类属性 `pattern' 来提供整个正则表达式模式
。 如果你这样做，该值必须为一个具有四个命名捕获组的正则表达式对象。 这些
捕获组对应于上面已经给出的规则，以及无效占位符的规则：

   * `escaped' – 这个组匹配转义序列，在默认模式中即 ‘$$’。

   * `named' – 这个组匹配不带花括号的占位符名称；它不应当包含捕获组中的
     分隔符。

   * `braced' – 这个组匹配带有花括号的占位符名称；它不应当包含捕获组中的
     分隔符或者花括号。

   * `invalid' – 这个组匹配任何其他分隔符模式（通常为单个分隔符），并且
     它应当出现在正则表达式的末尾。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0292

   (2) http://flufli18n.readthedocs.io/en/latest/


File: python.info,  Node: 辅助函数,  Prev: 模板字符串,  Up: string --- 常见的字符串操作

5.6.1.7 辅助函数
................

 -- 函式: string.capwords (s, sep=None)

     使用 *note str.split(): 890. 将参数拆分为单词，使用 *note
     str.capitalize(): 1776. 将单词转为大写形式，使用 *note str.join():
     1766. 将大写的单词进行拼接。 如果可选的第二个参数 `sep' 被省略或为
     ‘None’，则连续的空白字符会被替换为单个空格符并且开头和末尾的空白字
     符会被移除，否则 `sep' 会被用来拆分和拼接单词。


File: python.info,  Node: re --- 正则表达式操作,  Next: difflib --- 计算差异的辅助工具,  Prev: string --- 常见的字符串操作,  Up: 文本處理 Text Processing 服務

5.6.2 ‘re’ — 正则表达式操作
---------------------------

`源代码:' Lib/re.py(1)

__________________________________________________________________

本模块提供了与 Perl 语言类似的正则表达式匹配操作。

模式和被搜索的字符串既可以是 Unicode 字符串 (*note str: 205.) ，也可以是
8位字节串 (*note bytes: 172.)。 但是，Unicode 字符串与 8 位字节串不能混
用：也就是说，不能用字节串模式匹配 Unicode 字符串，反之亦然；同理，替换
操作时，替换字符串的类型也必须与所用的模式和搜索字符串的类型一致。

正则表达式用反斜杠字符 (‘'\'’) 表示特殊形式，或是允许在使用特殊字符时，
不引发它们的特殊含义。 这与 Python 的字符串字面值中对相同字符出于相同目
的的用法产生冲突；例如，要匹配一个反斜杠字面值，用户可能必须写成
‘'\\\\'’ 来作为模式字符串，因为正则表达式必须为 ‘\\’，而每个反斜杠在普通
Python 字符串字面值中又必须表示为 ‘\\’。 而且还要注意，在 Python 的字符
串字面值中使用的反斜杠如果有任何无效的转义序列，现在会触发 *note
DeprecationWarning: 15a.，但以后会改为 *note SyntaxError: 559.。 此行为
即使对于正则表达式来说有效的转义字符同样会发生。

解决办法是对于正则表达式样式使用 Python 的原始字符串表示法；在带有 ‘'r'’
前缀的字符串字面值中，反斜杠不必做任何特殊处理。 因此 ‘r"\n"’ 表示包含
‘'\'’ 和 ‘'n'’ 两个字符的字符串，而 ‘"\n"’ 则表示只包含一个换行符的字符
串。 样式在 Python 代码中通常都使用原始字符串表示法。

绝大多数正则表达式操作都提供为模块函数和方法，在 *note 编译正则表达式:
983.  这些函数是一个捷径，不需要先编译正则对象，但是损失了一些优化参数。

也參考
......

第三方模块 regex(2) , 提供了与标准库 *note re: dd. 模块兼容的 API 接口，
同时，还提供了更多功能和更全面的 Unicode 支持。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/re.py

   (2) https://pypi.org/project/regex/


File: python.info,  Node: 正则表达式语法,  Next: 模块内容,  Up: re --- 正则表达式操作

5.6.2.1 正则表达式语法
......................

正则表达式（或 RE）指定了一组与之匹配的字符串；模块内的函数可以检查某个
字符串是否与给定的正则表达式匹配（或者正则表达式是否匹配到字符串，这两种
说法含义相同）。

正则表达式可以拼接；如果 `A' 和 `B' 都是正则表达式，则 `AB' 也是正则表达
式。通常，如果字符串 `p' 匹配 `A'，并且另一个字符串 `q' 匹配 `B'，那么
`pq' 可以匹配 AB。除非 `A' 或者 `B' 包含低优先级操作，`A' 和 `B' 存在边
界条件；或者命名组引用。所以，复杂表达式可以很容易的从这里描述的简单源语
表达式构建。更多正则表达式理论和实现，详见 the Friedl book *note
[Frie09]: 1895. ，或者其他构建编译器的书籍。

以下是正则表达式格式的简要说明。更详细的信息和演示，参考 *note
如何使用正規表達式: 1896.。

正则表达式可以包含普通或者特殊字符。绝大部分普通字符，比如 ‘'A'’, ‘'a'’,
或者 ‘'0'’，都是最简单的正则表达式。它们就匹配自身。你可以拼接普通字符，
所以 ‘last’ 匹配字符串 ‘'last'’.  （在这一节的其他部分，我们将用 ‘this
special style’ 这种方式表示正则表达式，通常不带引号，要匹配的字符串用
‘'in single quotes'’ ，单引号形式。）

有些字符，比如 ‘'|'’ 或者 ‘'('’，属于特殊字符。 特殊字符既可以表示它的普
通含义， 也可以影响它旁边的正则表达式的解释。

重复修饰符 (‘*’, ‘+’, ‘?’, ‘{m,n}’, 等) 不能直接嵌套。这样避免了非贪婪后
缀 ‘?’ 修饰符，和其他实现中的修饰符产生的多义性。要应用一个内层重复嵌套
，可以使用括号。 比如，表达式 ‘(?:a{6})*’ 匹配6个 ‘'a'’ 字符重复任意次数
。

特殊字符有：

‘.’

     (点) 在默认模式，匹配除了换行的任意字符。如果指定了标签 *note
     DOTALL: 1897. ，它将匹配包括换行符的任意字符。

‘^’

     (插入符号) 匹配字符串的开头， 并且在 *note MULTILINE: 1898. 模式也
     匹配换行后的首个符号。

‘$’

     匹配字符串尾或者在字符串尾的换行符的前一个字符，在 *note MULTILINE:
     1898. 模式下也会匹配换行符之前的文本。 ‘foo’ 匹配 ’foo’ 和
     ’foobar’，但正则表达式 ‘foo$’ 只匹配 ’foo’。 更有趣的是，在
     ‘'foo1\nfoo2\n'’ 中搜索 ‘foo.$’，通常匹配 ’foo2’，但在 *note
     MULTILINE: 1898. 模式下可以匹配到 ’foo1’；在 ‘'foo\n'’ 中搜索 ‘$’ 会
     找到两个（空的）匹配：一个在换行符之前，一个在字符串的末尾。

‘*’

     对它前面的正则式匹配0到任意次重复， 尽量多的匹配字符串。 ‘ab*’ 会匹
     配 ‘'a'’，‘'ab'’，或者 ‘'a'’ 后面跟随任意个 ‘'b'’。

‘+’

     对它前面的正则式匹配1到任意次重复。 ‘ab+’ 会匹配 ‘'a'’ 后面跟随1个
     以上到任意个 ‘'b'’，它不会匹配 ‘'a'’。

‘?’

     对它前面的正则式匹配0到1次重复。 ‘ab?’ 会匹配 ‘'a'’ 或者 ‘'ab'’。

‘*?’, ‘+?’, ‘??’

     ‘'*'’, ‘'+'’，和 ‘'?'’ 修饰符都是 `贪婪的'；它们在字符串进行尽可能
     多的匹配。有时候并不需要这种行为。如果正则式 ‘<.*>’ 希望找到 ‘'<a>
     b <c>'’，它将会匹配整个字符串，而不仅是 ‘'<a>'’。在修饰符之后添加
     ‘?’ 将使样式以 `非贪婪‘方式或者 :dfn:‘最小' 方式进行匹配； 尽量 `少
     ' 的字符将会被匹配。 使用正则式 ‘<.*?>’ 将会仅仅匹配 ‘'<a>'’。

‘{m}’

     对其之前的正则式指定匹配 `m' 个重复；少于 `m' 的话就会导致匹配失败
     。比如， ‘a{6}’ 将匹配6个 ‘'a'’ , 但是不能是5个。

‘{m,n}’

     对正则式进行 `m' 到 `n' 次匹配，在 `m' 和 `n' 之间取尽量多。 比如，
     ‘a{3,5}’ 将匹配 3 到 5个 ‘'a'’。忽略 `m' 意为指定下界为0，忽略 `n'
     指定上界为无限次。 比如 ‘a{4,}b’ 将匹配 ‘'aaaab'’ 或者1000个 ‘'a'’
     尾随一个 ‘'b'’，但不能匹配 ‘'aaab'’。逗号不能省略，否则无法辨别修饰
     符应该忽略哪个边界。

‘{m,n}?’

     前一个修饰符的非贪婪模式，只匹配尽量少的字符次数。比如，对于
     ‘'aaaaaa'’， ‘a{3,5}’ 匹配 5个 ‘'a'’ ，而 ‘a{3,5}?’ 只匹配3个
     ‘'a'’。

‘\’

     转义特殊字符（允许你匹配 ‘'*'’, ‘'?'’, 或者此类其他），或者表示一个
     特殊序列；特殊序列之后进行讨论。

     如果你没有使用原始字符串（ ‘r'raw'’ ）来表达样式，要牢记Python也使
     用反斜杠作为转义序列；如果转义序列不被Python的分析器识别，反斜杠和
     字符才能出现在字符串中。如果Python可以识别这个序列，那么反斜杠就应
     该重复两次。这将导致理解障碍，所以高度推荐，就算是最简单的表达式，
     也要使用原始字符串。

‘[]’

     用于表示一个字符集合。在一个集合中：

        * 字符可以单独列出，比如 ‘[amk]’ 匹配 ‘'a'’， ‘'m'’， 或者
          ‘'k'’。

        * 可以表示字符范围，通过用 ‘'-'’ 将两个字符连起来。比如 ‘[a-z]’
          将匹配任何小写ASCII字符， ‘[0-5][0-9]’ 将匹配从 ‘00’ 到 ‘59’ 的
          两位数字， ‘[0-9A-Fa-f]’ 将匹配任何十六进制数位。 如果 ‘-’ 进
          行了转义 （比如 ‘[a\-z]’）或者它的位置在首位或者末尾（如
          ‘[-a]’ 或 ‘[a-]’），它就只表示普通字符 ‘'-'’。

        * 特殊字符在集合中，失去它的特殊含义。比如 ‘[(+*)]’ 只会匹配这几
          个文法字符 ‘'('’, ‘'+'’, ‘'*'’, or ‘')'’。

        * 字符类如 ‘\w’ 或者 ‘\S’ (如下定义) 在集合内可以接受，它们可以
          匹配的字符由 *note ASCII: 4ce. 或者 *note LOCALE: 4cf. 模式决
          定。

        * 不在集合范围内的字符可以通过 `取反' 来进行匹配。如果集合首字符
          是 ‘'^'’ ，所有 `不' 在集合内的字符将会被匹配，比如 ‘[^5]’ 将
          匹配所有字符，除了 ‘'5'’， ‘[^^]’ 将匹配所有字符，除了 ‘'^'’.
          ‘^’ 如果不在集合首位，就没有特殊含义。

        * 在集合内要匹配一个字符 ‘']'’，有两种方法，要么就在它之前加上反
          斜杠，要么就把它放到集合首位。比如， ‘[()[\]{}]’ 和 ‘[]()[{}]’
          都可以匹配括号。

        * Unicode Technical Standard #18(1) 里的嵌套集合和集合操作支持可
          能在未来添加。这将会改变语法，所以为了帮助这个改变，一个 *note
          FutureWarning: 435. 将会在有多义的情况里被 ‘raise’，包含以下几
          种情况，集合由 ‘'['’ 开始，或者包含下列字符序列 ‘'--'’,
          ‘'&&'’, ‘'~~'’, 和 ‘'||'’。为了避免警告，需要将它们用反斜杠转
          义。

     3.7 版更變: 如果一个字符串构建的语义在未来会改变的话，一个 *note
     FutureWarning: 435. 会 ‘raise’ 。

‘|’

     ‘A|B’， `A' 和 `B' 可以是任意正则表达式，创建一个正则表达式，匹配
     `A' 或者 `B'. 任意个正则表达式可以用 ‘'|'’ 连接。它也可以在组合（见
     下列）内使用。扫描目标字符串时， ‘'|'’ 分隔开的正则样式从左到右进行
     匹配。当一个样式完全匹配时，这个分支就被接受。意思就是，一旦 `A' 匹
     配成功， `B' 就不再进行匹配，即便它能产生一个更好的匹配。或者说，
     ‘'|'’ 操作符绝不贪婪。 如果要匹配 ‘'|'’ 字符，使用 ‘\|’， 或者把它
     包含在字符集里，比如 ‘[|]’.

‘(...)’

     （组合），匹配括号内的任意正则表达式，并标识出组合的开始和结尾。匹
     配完成后，组合的内容可以被获取，并可以在之后用 ‘\number’ 转义序列进
     行再次匹配，之后进行详细说明。要匹配字符 ‘'('’ 或者 ‘')'’, 用 ‘\(’
     或 ‘\)’, 或者把它们包含在字符集合里: ‘[(]’, ‘[)]’.

‘(?…)’

     这是个扩展标记法 （一个 ‘'?'’ 跟随 ‘'('’ 并无含义）。 ‘'?'’ 后面的
     第一个字符决定了这个构建采用什么样的语法。这种扩展通常并不创建新的
     组合； ‘(?P<name>...)’ 是唯一的例外。 以下是目前支持的扩展。

‘(?aiLmsux)’

     ( ‘'a'’, ‘'i'’, ‘'L'’, ‘'m'’, ‘'s'’, ‘'u'’, ‘'x'’ 中的一个或多个) 这
     个组合匹配一个空字符串；这些字符对正则表达式设置以下标记 *note
     re.A: 1899. (只匹配ASCII字符), *note re.I: 189a. (忽略大小写),
     *note re.L: 189b. (语言依赖), *note re.M: 189c. (多行模式), *note
     re.S: 189d. (点dot匹配全部字符), ‘re.U’ (Unicode匹配), and *note
     re.X: 189e. (冗长模式)。 (这些标记在 *note 模块内容: 189f. 中描述)
     如果你想将这些标记包含在正则表达式中，这个方法就很有用，免去了在
     *note re.compile(): 54c. 中传递 `flag' 参数。标记应该在表达式字符串
     首位表示。

‘(?:…)’

     正则括号的非捕获版本。 匹配在括号内的任何正则表达式，但该分组所匹配
     的子字符串 `不能' 在执行匹配后被获取或是之后在模式中被引用。

‘(?aiLmsux-imsx:…)’

     (‘'a'’, ‘'i'’, ‘'L'’, ‘'m'’, ‘'s'’, ‘'u'’, ‘'x'’ 中的0或者多个， 之
     后可选跟随 ‘'-'’ 在后面跟随 ‘'i'’ , ‘'m'’ , ‘'s'’ , ‘'x'’ 中的一到
     多个 .) 这些字符为表达式的其中一部分 `设置' 或者 `去除' 相应标记
     *note re.A: 1899. (只匹配ASCII), *note re.I: 189a. (忽略大小写),
     *note re.L: 189b. (语言依赖), *note re.M: 189c. (多行), *note re.S:
     189d. (点匹配所有字符), ‘re.U’ (Unicode匹配), and *note re.X: 189e.
     (冗长模式)。(标记描述在 *note 模块内容: 189f. .)

     ‘'a'’, ‘'L'’ and ‘'u'’ 作为内联标记是相互排斥的， 所以它们不能结合
     在一起，或者跟随 ‘'-'’ 。 当他们中的某个出现在内联组中，它就覆盖了
     括号组内的匹配模式。在Unicode样式中， ‘(?a:...)’ 切换为 只匹配
     ASCII， ‘(?u:...)’ 切换为Unicode匹配 (默认).  在byte样式中
     ‘(?L:...)’ 切换为语言依赖模式， ‘(?a:...)’ 切换为 只匹配ASCII (默认
     )。这种方式只覆盖组合内匹配，括号外的匹配模式不受影响。

     3.6 版新加入.

     3.7 版更變: 符号 ‘'a'’, ‘'L'’ 和 ‘'u'’ 同样可以用在一个组合内。

‘(?P<name>…)’

     （命名组合）类似正则组合，但是匹配到的子串组在外部是通过定义的
     `name' 来获取的。组合名必须是有效的Python标识符，并且每个组合名只能
     用一个正则表达式定义，只能定义一次。一个符号组合同样是一个数字组合
     ，就像这个组合没有被命名一样。

     命名组合可以在三种上下文中引用。如果样式是
     ‘(?P<quote>['"]).*?(?P=quote)’ （也就是说，匹配单引号或者双引号括起
     来的字符串)：

     引用组合 "quote" 的上下文                   引用方法
                                                 
     -----------------------------------------------------------------------------------
                                                 
     在正则式自身内                                 * ‘(?P=quote)’ (如示)
                                                 
                                                    * ‘\1’
                                                 
                                                 
     处理匹配对象 `m'                               * ‘m.group('quote')’
                                                 
                                                    * ‘m.end('quote')’ (等)
                                                 
                                                 
     传递到 ‘re.sub()’ 里的 `repl' 参数中           * ‘\g<quote>’
                                                 
                                                    * ‘\g<1>’
                                                 
                                                    * ‘\1’
                                                 

‘(?P=name)’

     反向引用一个命名组合；它匹配前面那个叫 `name' 的命名组中匹配到的串
     同样的字串。

‘(?#…)’

     注释；里面的内容会被忽略。

‘(?=…)’

     匹配 ‘…’ 的内容，但是并不消费样式的内容。这个叫做 `lookahead
     assertion'。比如， ‘Isaac (?=Asimov)’ 匹配 ‘'Isaac '’ 只有在后面是
     ‘'Asimov'’ 的时候。

‘(?!…)’

     匹配 ‘…’ 不符合的情况。这个叫 `negative lookahead assertion' （前视
     取反）。比如说， ‘Isaac (?!Asimov)’ 只有后面 `不' 是 ‘'Asimov'’ 的
     时候才匹配 ‘'Isaac '’ 。

‘(?<=…)’

     匹配字符串的当前位置，它的前面匹配 ‘...’ 的内容到当前位置。这叫
     `positive lookbehind assertion' （正向后视断定）。 ‘(?<=abc)def’ 会
     在 ‘'abcdef'’ 中找到一个匹配，因为后视会往后看3个字符并检查是否包含
     匹配的样式。包含的匹配样式必须是定长的，意思就是 ‘abc’ 或 ‘a|b’ 是
     允许的，但是 ‘a*’ 和 ‘a{3,4}’ 不可以。注意以 positive lookbehind
     assertions 开始的样式，如 ‘(?<=abc)def’ ，并不是从 a 开始搜索，而是
     从 d 往回看的。你可能更加愿意使用 *note search(): c82. 函数，而不是
     *note match(): c83. 函数：

          >>> import re
          >>> m = re.search('(?<=abc)def', 'abcdef')
          >>> m.group(0)
          'def'

     这个例子搜索一个跟随在连字符后的单词：

          >>> m = re.search(r'(?<=-)\w+', 'spam-egg')
          >>> m.group(0)
          'egg'

     3.5 版更變: 添加定长组合引用的支持。

‘(?<!…)’

     匹配当前位置之前不是 ‘...’ 的样式。这个叫 `negative lookbehind
     assertion' （后视断定取非）。类似正向后视断定，包含的样式匹配必须是
     定长的。由 negative lookbehind assertion 开始的样式可以从字符串搜索
     开始的位置进行匹配。

‘(?(id/name)yes-pattern|no-pattern)’

     如果给定的 `id' 或 `name' 存在，将会尝试匹配 ‘yes-pattern’ ，否则就
     尝试匹配 ‘no-pattern’，‘no-pattern’ 可选，也可以被忽略。比如，
     ‘(<)?(\w+@\w+(?:\.\w+)+)(?(1)>|$)’ 是一个email样式匹配，将匹配
     ‘'<user@host.com>'’ 或 ‘'user@host.com'’ ，但不会匹配
     ‘'<user@host.com'’ ，也不会匹配 ‘'user@host.com>'’。

由 ‘'\'’ 和一个字符组成的特殊序列在以下列出。 如果普通字符不是ASCII数位
或者ASCII字母，那么正则样式将匹配第二个字符。比如，‘\$’ 匹配字符 ‘'$'’.

‘\number’

     匹配数字代表的组合。每个括号是一个组合，组合从1开始编号。比如 ‘(.+)
     \1’ 匹配 ‘'the the'’ 或者 ‘'55 55'’, 但不会匹配 ‘'thethe'’ (注意组
     合后面的空格)。这个特殊序列只能用于匹配前面99个组合。如果 `number'
     的第一个数位是0， 或者 `number' 是三个八进制数，它将不会被看作是一
     个组合，而是八进制的数字值。在 ‘'['’ 和 ‘']'’ 字符集合内，任何数字
     转义都被看作是字符。

‘\A’

     只匹配字符串开始。

‘\b’

     匹配空字符串，但只在单词开始或结尾的位置。一个单词被定义为一个单词
     字符的序列。注意，通常 ‘\b’ 定义为 ‘\w’ 和 ‘\W’ 字符之间，或者 ‘\w’
     和字符串开始/结尾的边界， 意思就是 ‘r'\bfoo\b'’ 匹配 ‘'foo'’,
     ‘'foo.'’, ‘'(foo)'’, ‘'bar foo baz'’ 但不匹配 ‘'foobar'’ 或者
     ‘'foo3'’。

     默认情况下，Unicode字母和数字是在Unicode样式中使用的，但是可以用
     *note ASCII: 4ce. 标记来更改。如果 *note LOCALE: 4cf. 标记被设置的
     话，词的边界是由当前语言区域设置决定的，‘\b’ 表示退格字符，以便与
     Python字符串文本兼容。

‘\B’

     匹配空字符串，但 `不' 能在词的开头或者结尾。意思就是 ‘r'py\B'’ 匹配
     ‘'python'’, ‘'py3'’, ‘'py2'’, 但不匹配 ‘'py'’, ‘'py.'’, 或者
     ‘'py!'’.  ‘\B’ 是 ‘\b’ 的取非，所以Unicode样式的词语是由Unicode字母
     ，数字或下划线构成的，虽然可以用 *note ASCII: 4ce. 标志来改变。如果
     使用了 *note LOCALE: 4cf. 标志，则词的边界由当前语言区域设置。

‘\d’

     对于 Unicode (str) 样式：

          匹配任何Unicode十进制数（就是在Unicode字符目录[Nd]里的字符）。
          这包括了 ‘[0-9]’ ，和很多其他的数字字符。如果设置了 *note
          ASCII: 4ce. 标志，就只匹配 ‘[0-9]’ 。

     对于8位(bytes)样式：

          匹配任何十进制数，就是 ‘[0-9]’。

‘\D’

     匹配任何非十进制数字的字符。就是 ‘\d’ 取非。 如果设置了 *note
     ASCII: 4ce. 标志，就相当于 ‘[^0-9]’ 。

‘\s’

     对于 Unicode (str) 样式：

          匹配任何Unicode空白字符（包括 ‘[ \t\n\r\f\v]’ ，还有很多其他字
          符，比如不同语言排版规则约定的不换行空格）。如果 *note ASCII:
          4ce. 被设置，就只匹配 ‘[ \t\n\r\f\v]’ 。

     对于8位(bytes)样式：

          匹配ASCII中的空白字符，就是 ‘[ \t\n\r\f\v]’ 。

‘\S’

     匹配任何非空白字符。就是 ‘\s’ 取非。如果设置了 *note ASCII: 4ce. 标
     志，就相当于 ‘[^ \t\n\r\f\v]’ 。

‘\w’

     对于 Unicode (str) 样式：

          匹配Unicode词语的字符，包含了可以构成词语的绝大部分字符，也包
          括数字和下划线。如果设置了 *note ASCII: 4ce. 标志，就只匹配
          ‘[a-zA-Z0-9_]’ 。

     对于8位(bytes)样式：

          匹配ASCII字符中的数字和字母和下划线，就是 ‘[a-zA-Z0-9_]’ 。如
          果设置了 *note LOCALE: 4cf. 标记，就匹配当前语言区域的数字和字
          母和下划线。

‘\W’

     匹配非单词字符的字符。这与 ‘\w’ 正相反。如果使用了 *note ASCII:
     4ce. 旗标，这就等价于 ‘[^a-zA-Z0-9_]’。如果使用了 *note LOCALE:
     4cf. 旗标，则会匹配当前区域中既非字母数字也非下划线的字符。

‘\Z’

     只匹配字符串尾。

绝大部分Python的标准转义字符也被正则表达式分析器支持。:

     \a      \b      \f      \n
     \N      \r      \t      \u
     \U      \v      \x      \\

（注意 ‘\b’ 被用于表示词语的边界，它只在字符集合内表示退格，比如 ‘[\b]’
。）

‘'\u'’, ‘'\U'’ 和 ‘'\N'’ 转义序列只在 Unicode 模式中可被识别。 在 bytes
模式中它们会导致错误。 未知的 ASCII 字母转义序列保留在未来使用，会被当作
错误来处理。

八进制转义包含为一个有限形式。如果首位数字是 0， 或者有三个八进制数位，
那么就认为它是八进制转义。其他的情况，就看作是组引用。对于字符串文本，八
进制转义最多有三个数位长。

3.3 版更變: 增加了 ‘'\u'’ 和 ‘'\U'’ 转义序列。

3.6 版更變: 由 ‘'\'’ 和一个ASCII字符组成的未知转义会被看成错误。

3.8 版更變: 添加了 ‘'\N{name}'’ 转义序列。 与在字符串字面值中一样，它扩
展了命名 Unicode 字符 (例如 ‘'\N{EM DASH}'’)。

   ---------- Footnotes ----------

   (1) https://unicode.org/reports/tr18/


File: python.info,  Node: 模块内容,  Next: 正则表达式对象 （正则对象）,  Prev: 正则表达式语法,  Up: re --- 正则表达式操作

5.6.2.2 模块内容
................

模块定义了几个函数、常量，和一个异常。有些函数是编译后的正则表达式方法的
简化版本（少了一些特性）。重要的应用程序大多会在使用前先编译正则表达式。

3.6 版更變: 标志常量现在是 ‘RegexFlag’ 类的实例，这个类是 *note
enum.IntFlag: 18a1. 的子类。

 -- 函式: re.compile (pattern, flags=0)

     将正则表达式的样式编译为一个 *note 正则表达式对象: 983. （正则对象
     ），可以用于匹配，通过这个对象的方法 *note match(): 18a2, *note
     search(): 18a3. 以及其他如下描述。

     这个表达式的行为可以通过指定 `标记' 的值来改变。值可以是以下任意变
     量，可以通过位的OR操作来结合（ ‘|’ 操作符）。

     序列

          prog = re.compile(pattern)
          result = prog.match(string)

     等价于

          result = re.match(pattern, string)

     如果需要多次使用这个正则表达式的话，使用 *note re.compile(): 54c. 和
     保存这个正则对象以便复用，可以让程序更加高效。

          備註: 通过 *note re.compile(): 54c. 编译后的样式，和模块级的函
          数会被缓存， 所以少数的正则表达式使用无需考虑编译的问题。

 -- Data: re.A
 -- Data: re.ASCII

     让 ‘\w’, ‘\W’, ‘\b’, ‘\B’, ‘\d’, ‘\D’, ‘\s’ 和 ‘\S’ 只匹配ASCII，而
     不是Unicode。这只对Unicode样式有效，会被byte样式忽略。相当于前面语
     法中的内联标志 ‘(?a)’ 。

     注意，为了保持向后兼容， ‘re.U’ 标记依然存在（还有他的同义
     ‘re.UNICODE’ 和嵌入形式 ‘(?u)’ ) ， 但是这些在 Python 3 是冗余的，
     因为默认字符串已经是Unicode了（并且Unicode匹配不允许byte出现)。

 -- Data: re.DEBUG

     显示编译时的debug信息，没有内联标记。

 -- Data: re.I
 -- Data: re.IGNORECASE

     进行忽略大小写匹配；表达式如 ‘[A-Z]’ 也会匹配小写字符。Unicode匹配
     （比如 ‘Ü’ 匹配 ‘ü’）同样有用，除非设置了 *note re.ASCII: 4ce. 标记
     来禁用非ASCII匹配。当前语言区域不会改变这个标记，除非设置了 *note
     re.LOCALE: 4cf. 标记。这个相当于内联标记 ‘(?i)’ 。

     注意，当设置了 *note IGNORECASE: 18a5. 标记，搜索Unicode样式
     ‘[a-z]’ 或 ‘[A-Z]’ 的结合时，它将会匹配52个ASCII字符和4个额外的非
     ASCII字符： ’İ’ (U+0130, 拉丁大写的 I 带个点在上面), ’ı’ (U+0131, 拉
     丁小写没有点的 I ), ’ſ’ (U+017F, 拉丁小写长 s) and ’K’ (U+212A, 开
     尔文符号).如果使用 *note ASCII: 4ce. 标记，就只匹配 ’a’ 到 ’z’ 和
     ’A’ 到 ’Z’ 。

 -- Data: re.L
 -- Data: re.LOCALE

     由当前语言区域决定 ‘\w’, ‘\W’, ‘\b’, ‘\B’ 和大小写敏感匹配。这个标
     记只能对byte样式有效。这个标记不推荐使用，因为语言区域机制很不可靠
     ，它一次只能处理一个 "习惯”，而且只对8位字节有效。Unicode匹配在
     Python 3 里默认启用，并可以处理不同语言。 这个对应内联标记 ‘(?L)’ 。

     3.6 版更變: *note re.LOCALE: 4cf. 只能用于byte样式，而且不能和
     *note re.ASCII: 4ce. 一起用。

     3.7 版更變: 设置了 *note re.LOCALE: 4cf. 标记的编译正则对象不再在编
     译时依赖语言区域设置。语言区域设置只在匹配的时候影响其结果。

 -- Data: re.M
 -- Data: re.MULTILINE

     设置以后，样式字符 ‘'^'’ 匹配字符串的开始，和每一行的开始（换行符后
     面紧跟的符号）；样式字符 ‘'$'’ 匹配字符串尾，和每一行的结尾（换行符
     前面那个符号）。默认情况下，‘’^’’ 匹配字符串头，‘'$'’ 匹配字符串尾
     。对应内联标记 ‘(?m)’ 。

 -- Data: re.S
 -- Data: re.DOTALL

     让 ‘'.'’ 特殊字符匹配任何字符，包括换行符；如果没有这个标记，‘'.'’
     就匹配 `除了' 换行符的其他任意字符。对应内联标记 ‘(?s)’ 。

 -- Data: re.X
 -- Data: re.VERBOSE

     这个标记允许你编写更具可读性更友好的正则表达式。通过分段和添加注释
     。空白符号会被忽略，除非在一个字符集合当中或者由反斜杠转义，或者在
     ‘*?’, ‘(?:’ or ‘(?P<…>’ 分组之内。当一个行内有 ‘#’ 不在字符集和转义
     序列，那么它之后的所有字符都是注释。

     意思就是下面两个正则表达式等价地匹配一个十进制数字：

          a = re.compile(r"""\d +  # the integral part
                             \.    # the decimal point
                             \d *  # some fractional digits""", re.X)
          b = re.compile(r"\d+\.\d*")

     对应内联标记 ‘(?x)’ 。

 -- 函式: re.search (pattern, string, flags=0)

     扫描整个 `字符串' 找到匹配样式的第一个位置，并返回一个相应的 *note
     匹配对象: 984.。如果没有匹配，就返回一个 ‘None’ ； 注意这和找到一个
     零长度匹配是不同的。

 -- 函式: re.match (pattern, string, flags=0)

     如果 `string' 开始的0或者多个字符匹配到了正则表达式样式，就返回一个
     相应的 *note 匹配对象: 984. 。 如果没有匹配，就返回 ‘None’ ；注意它
     跟零长度匹配是不同的。

     注意即便是 *note MULTILINE: 1898. 多行模式， *note re.match(): c83.
     也只匹配字符串的开始位置，而不匹配每行开始。

     如果你想定位 `string' 的任何位置，使用 *note search(): c82. 来替代
     （也可参考 *note search() vs.  match(): 18a7. ）

 -- 函式: re.fullmatch (pattern, string, flags=0)

     如果整个 `string' 匹配到正则表达式样式，就返回一个相应的 *note
     匹配对象: 984. 。 否则就返回一个 ‘None’ ；注意这跟零长度匹配是不同
     的。

     3.4 版新加入.

 -- 函式: re.split (pattern, string, maxsplit=0, flags=0)

     用 `pattern' 分开 `string' 。 如果在 `pattern' 中捕获到括号，那么所
     有的组里的文字也会包含在列表里。如果 `maxsplit' 非零， 最多进行
     `maxsplit' 次分隔， 剩下的字符全部返回到列表的最后一个元素。

          >>> re.split(r'\W+', 'Words, words, words.')
          ['Words', 'words', 'words', '']
          >>> re.split(r'(\W+)', 'Words, words, words.')
          ['Words', ', ', 'words', ', ', 'words', '.', '']
          >>> re.split(r'\W+', 'Words, words, words.', 1)
          ['Words', 'words, words.']
          >>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
          ['0', '3', '9']

     如果分隔符里有捕获组合，并且匹配到字符串的开始，那么结果将会以一个
     空字符串开始。对于结尾也是一样

          >>> re.split(r'(\W+)', '...words, words...')
          ['', '...', 'words', ', ', 'words', '...', '']

     这样的话，分隔组将会出现在结果列表中同样的位置。

     样式的空匹配仅在与前一个空匹配不相邻时才会拆分字符串。

          >>> re.split(r'\b', 'Words, words, words.')
          ['', 'Words', ', ', 'words', ', ', 'words', '.']
          >>> re.split(r'\W*', '...words...')
          ['', '', 'w', 'o', 'r', 'd', 's', '', '']
          >>> re.split(r'(\W*)', '...words...')
          ['', '...', '', '', 'w', '', 'o', '', 'r', '', 'd', '', 's', '...', '', '', '']

     3.1 版更變: 增加了可选标记参数。

     3.7 版更變: 增加了空字符串的样式分隔。

 -- 函式: re.findall (pattern, string, flags=0)

     Return all non-overlapping matches of `pattern' in `string', as a
     list of strings or tuples.  The `string' is scanned left-to-right,
     and matches are returned in the order found.  Empty matches are
     included in the result.

     The result depends on the number of capturing groups in the
     pattern.  If there are no groups, return a list of strings matching
     the whole pattern.  If there is exactly one group, return a list of
     strings matching that group.  If multiple groups are present,
     return a list of tuples of strings matching the groups.
     Non-capturing groups do not affect the form of the result.

          >>> 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')]

     3.7 版更變: 非空匹配现在可以在前一个空匹配之后出现了。

 -- 函式: re.finditer (pattern, string, flags=0)

     `pattern' 在 `string' 里所有的非重复匹配，返回为一个迭代器 *note
     iterator: 1171. 保存了 *note 匹配对象: 984. 。 `string' 从左到右扫
     描，匹配按顺序排列。空匹配也包含在结果里。

     3.7 版更變: 非空匹配现在可以在前一个空匹配之后出现了。

 -- 函式: re.sub (pattern, repl, string, count=0, flags=0)

     返回通过使用 `repl' 替换在 `string' 最左边非重叠出现的 `pattern' 而
     获得的字符串。 如果样式没有找到，则不加改变地返回 `string'。 `repl'
     可以是字符串或函数；如为字符串，则其中任何反斜杠转义序列都会被处理
     。 也就是说，‘\n’ 会被转换为一个换行符，‘\r’ 会被转换为一个回车符，
     依此类推。 未知的 ASCII 字符转义序列保留在未来使用，会被当作错误来
     处理。 其他未知转义序列例如 ‘\&’ 会保持原样。 向后引用像是 ‘\6’ 会
     用样式中第 6 组所匹配到的子字符串来替换。 例如:

          >>> 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{'

     如果 `repl' 是一个函数，那它会对每个非重复的 `pattern' 的情况调用。
     这个函数只能有一个 *note 匹配对象: 984. 参数，并返回一个替换后的字
     符串。比如

          >>> 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'

     样式可以是一个字符串或者一个 *note 样式对象: 983. 。

     可选参数 `count' 是要替换的最大次数；`count' 必须是非负整数。如果省
     略这个参数或设为 0，所有的匹配都会被替换。 样式的空匹配仅在与前一个
     空匹配不相邻时才会被替换，所以 ‘sub('x*', '-', 'abxd')’ 返回
     ‘'-a-b--d-'’ 。

     在字符串类型的 `repl' 参数里，如上所述的转义和向后引用中，
     ‘\g<name>’ 会使用命名组合 ‘name’，（在 ‘(?P<name>…)’ 语法中定义）
     ‘\g<number>’ 会使用数字组；‘\g<2>’ 就是 ‘\2’，但它避免了二义性，如
     ‘\g<2>0’。 ‘\20’ 就会被解释为组20，而不是组2后面跟随一个字符 ‘'0'’。
     向后引用 ‘\g<0>’ 把 `pattern' 作为一整个组进行引用。

     3.1 版更變: 增加了可选标记参数。

     3.5 版更變: 不匹配的组合替换为空字符串。

     3.6 版更變: `pattern' 中的未知转义（由 ‘'\'’ 和一个 ASCII 字符组成
     ）被视为错误。

     3.7 版更變: `repl' 中的未知转义（由 ‘'\'’ 和一个 ASCII 字符组成）被
     视为错误。

     3.7 版更變: 样式中的空匹配相邻接时会被替换。

 -- 函式: re.subn (pattern, repl, string, count=0, flags=0)

     行为与 *note sub(): 579. 相同，但是返回一个元组 ‘(字符串, 替换次数
     )’.

     3.1 版更變: 增加了可选标记参数。

     3.5 版更變: 不匹配的组合替换为空字符串。

 -- 函式: re.escape (pattern)

     转义 `pattern' 中的特殊字符。如果你想对任意可能包含正则表达式元字符
     的文本字符串进行匹配，它就是有用的。比如

          >>> 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))))
          /|\-|\+|\*\*|\*

     这个函数不能被用于 *note sub(): 579. 和 *note subn(): 823. 的替换字
     符串，只有反斜杠应该被转义。 例如:

          >>> 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

     3.3 版更變: ‘'_'’ 不再被转义。

     3.7 版更變: 只有在正则表达式中具有特殊含义的字符才会被转义。 因此，
     ‘'!'’, ‘'"'’, ‘'%'’, ‘"'"’, ‘','’, ‘'/'’, ‘':'’, ‘';'’, ‘'<'’,
     ‘'='’, ‘'>'’, ‘'@'’ 和 ‘"`"’ 将不再会被转义。

 -- 函式: re.purge ()

     清除正则表达式的缓存。

 -- 例外: re.error (msg, pattern=None, pos=None)

     当传递给函数的正则表达式不合法（比如括号不匹配），或者在编译或匹配
     过程中出现其他错误时，会引发异常。所给字符串不匹配所给模式不会引发
     异常。异常实例有以下附加属性：

      -- 屬性: msg

          未格式化的错误消息。

      -- 屬性: pattern

          正则表达式的模式串。

      -- 屬性: pos

          编译失败的 `pattern' 的位置索引（可以是 ‘None’ ）。

      -- 屬性: lineno

          对应 `pos' (可以是 ‘None’) 的行号。

      -- 屬性: colno

          对应 `pos' (可以是 ‘None’) 的列号。

     3.5 版更變: 增加了额外的属性。


File: python.info,  Node: 正则表达式对象 （正则对象）,  Next: 匹配对象,  Prev: 模块内容,  Up: re --- 正则表达式操作

5.6.2.3 正则表达式对象 （正则对象）
...................................

编译后的正则表达式对象支持以下方法和属性：

 -- 成員函式: Pattern.search (string[, pos[, endpos]])

     扫描整个 `string' 寻找第一个匹配的位置， 并返回一个相应的 *note
     匹配对象: 984.。如果没有匹配，就返回 ‘None’ ；注意它和零长度匹配是
     不同的。

     可选的第二个参数 `pos' 给出了字符串中开始搜索的位置索引；默认为
     ‘0’，它不完全等价于字符串切片； ‘'^'’ 样式字符匹配字符串真正的开头
     ，和换行符后面的第一个字符，但不会匹配索引规定开始的位置。

     可选参数 `endpos' 限定了字符串搜索的结束；它假定字符串长度到
     `endpos' ， 所以只有从 ‘pos’ 到 ‘endpos - 1’ 的字符会被匹配。如果
     `endpos' 小于 `pos'，就不会有匹配产生；另外，如果 `rx' 是一个编译后
     的正则对象， ‘rx.search(string, 0, 50)’ 等价于
     ‘rx.search(string[:50], 0)’。

          >>> 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"

 -- 成員函式: Pattern.match (string[, pos[, endpos]])

     如果 `string' 的 `开始位置' 能够找到这个正则样式的任意个匹配，就返
     回一个相应的 *note 匹配对象: 984.。如果不匹配，就返回 ‘None’ ；注意
     它与零长度匹配是不同的。

     可选参数 `pos' 和 `endpos' 与 *note search(): 18a3. 含义相同。

          >>> 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'>

     如果你想定位匹配在 `string' 中的位置，使用 *note search(): 18a3. 来
     替代（另参考 *note search() vs.  match(): 18a7.）。

 -- 成員函式: Pattern.fullmatch (string[, pos[, endpos]])

     如果整个 `string' 匹配这个正则表达式，就返回一个相应的 *note
     匹配对象: 984. 。 否则就返回 ‘None’ ； 注意跟零长度匹配是不同的。

     可选参数 `pos' 和 `endpos' 与 *note search(): 18a3. 含义相同。

          >>> 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'>

     3.4 版新加入.

 -- 成員函式: Pattern.split (string, maxsplit=0)

     等价于 *note split(): 4d0. 函数，使用了编译后的样式。

 -- 成員函式: Pattern.findall (string[, pos[, endpos]])

     类似函数 *note findall(): a44. ， 使用了编译后样式，但也可以接收可
     选参数 `pos' 和 `endpos' ，限制搜索范围，就像 *note search(): c82.。

 -- 成員函式: Pattern.finditer (string[, pos[, endpos]])

     类似函数 *note finditer(): 18a8. ， 使用了编译后样式，但也可以接收
     可选参数 `pos' 和 `endpos' ，限制搜索范围，就像 *note search():
     c82.。

 -- 成員函式: Pattern.sub (repl, string, count=0)

     等价于 *note sub(): 579. 函数，使用了编译后的样式。

 -- 成員函式: Pattern.subn (repl, string, count=0)

     等价于 *note subn(): 823. 函数，使用了编译后的样式。

 -- 屬性: Pattern.flags

     正则匹配标记。这是可以传递给 *note compile(): 54c. 的参数，任何
     ‘(?…)’ 内联标记，隐性标记比如 ‘UNICODE’ 的结合。

 -- 屬性: Pattern.groups

     捕获到的模式串中组的数量。

 -- 屬性: Pattern.groupindex

     映射由 ‘(?P<id>)’ 定义的命名符号组合和数字组合的字典。如果没有符号
     组，那字典就是空的。

 -- 屬性: Pattern.pattern

     编译对象的原始样式字符串。

3.7 版更變: 添加 *note copy.copy(): 4d1. 和 *note copy.deepcopy(): 4d2.
函数的支持。编译后的正则表达式对象被认为是原子性的。


File: python.info,  Node: 匹配对象,  Next: 正则表达式例子,  Prev: 正则表达式对象 （正则对象）,  Up: re --- 正则表达式操作

5.6.2.4 匹配对象
................

匹配对象总是有一个布尔值 ‘True’。如果没有匹配的话 *note match(): 18a2. 和
*note search(): 18a3. 返回 ‘None’ 所以你可以简单的用 ‘if’ 语句来判断是否
匹配

     match = re.search(pattern, string)
     if match:
         process(match)

匹配对象支持以下方法和属性：

 -- 成員函式: Match.expand (template)

     对 `template' 进行反斜杠转义替换并且返回，就像 *note sub(): 18af. 方
     法中一样。转义如同 ‘\n’ 被转换成合适的字符，数字引用(‘\1’, ‘\2’)和
     命名组合(‘\g<1>’, ‘\g<name>’) 替换为相应组合的内容。

     3.5 版更變: 不匹配的组合替换为空字符串。

 -- 成員函式: Match.group ([group1, ...])

     返回一个或者多个匹配的子组。如果只有一个参数，结果就是一个字符串，
     如果有多个参数，结果就是一个元组（每个参数对应一个项），如果没有参
     数，组1默认到0（整个匹配都被返回）。 如果一个组N 参数值为 0，相应的
     返回值就是整个匹配字符串；如果它是一个范围 [1..99]，结果就是相应的
     括号组字符串。如果一个组号是负数，或者大于样式中定义的组数，就引发
     一个 *note IndexError: f36. 异常。如果一个组包含在样式的一部分，并
     被匹配多次，就返回最后一个匹配。:

          >>> 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')

     如果正则表达式使用了 ‘(?P<name>...)’ 语法， `groupN' 参数就也可能是
     命名组合的名字。如果一个字符串参数在样式中未定义为组合名，就引发一
     个 *note IndexError: f36. 异常。

     一个相对复杂的例子

          >>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
          >>> m.group('first_name')
          'Malcolm'
          >>> m.group('last_name')
          'Reynolds'

     命名组合同样可以通过索引值引用

          >>> m.group(1)
          'Malcolm'
          >>> m.group(2)
          'Reynolds'

     如果一个组匹配成功多次，就只返回最后一个匹配

          >>> m = re.match(r"(..)+", "a1b2c3")  # Matches 3 times.
          >>> m.group(1)                        # Returns only the last match.
          'c3'

 -- 成員函式: Match.__getitem__ (g)

     这个等价于 ‘m.group(g)’。这允许更方便的引用一个匹配

          >>> 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'

     3.6 版新加入.

 -- 成員函式: Match.groups (default=None)

     返回一个元组，包含所有匹配的子组，在样式中出现的从1到任意多的组合。
     `default' 参数用于不参与匹配的情况，默认为 ‘None’。

     例如

          >>> m = re.match(r"(\d+)\.(\d+)", "24.1632")
          >>> m.groups()
          ('24', '1632')

     如果我们使小数点可选，那么不是所有的组都会参与到匹配当中。这些组合
     默认会返回一个 ‘None’ ，除非指定了 `default' 参数。

          >>> 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')

 -- 成員函式: Match.groupdict (default=None)

     返回一个字典，包含了所有的 `命名' 子组。key就是组名。 `default' 参
     数用于不参与匹配的组合；默认为 ‘None’。 例如

          >>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
          >>> m.groupdict()
          {'first_name': 'Malcolm', 'last_name': 'Reynolds'}

 -- 成員函式: Match.start ([group])
 -- 成員函式: Match.end ([group])

     返回 `group' 匹配到的字串的开始和结束标号。`group' 默认为0（意思是
     整个匹配的子串）。如果 `group' 存在，但未产生匹配，就返回 ‘-1’ 。对
     于一个匹配对象 `m'， 和一个未参与匹配的组 `g' ，组 `g' (等价于
     ‘m.group(g)’)产生的匹配是

          m.string[m.start(g):m.end(g)]

     注意 ‘m.start(group)’ 将会等于 ‘m.end(group)’ ，如果 `group' 匹配一
     个空字符串的话。比如，在 ‘m = re.search('b(c?)', 'cba')’ 之后，
     ‘m.start(0)’ 为 1, ‘m.end(0)’ 为 2, ‘m.start(1)’ 和 ‘m.end(1)’ 都是
     2, ‘m.start(2)’ 引发一个 *note IndexError: f36. 异常。

     这个例子会从email地址中移除掉 `remove_this'

          >>> email = "tony@tiremove_thisger.net"
          >>> m = re.search("remove_this", email)
          >>> email[:m.start()] + email[m.end():]
          'tony@tiger.net'

 -- 成員函式: Match.span ([group])

     对于一个匹配 `m' ， 返回一个二元组 ‘(m.start(group), m.end(group))’
     。 注意如果 `group' 没有在这个匹配中，就返回 ‘(-1, -1)’ 。`group' 默
     认为0，就是整个匹配。

 -- 屬性: Match.pos

     `pos' 的值，会传递给 *note search(): 18a3. 或 *note match(): 18a2.
     的方法 a *note 正则对象: 983. 。这个是正则引擎开始在字符串搜索一个
     匹配的索引位置。

 -- 屬性: Match.endpos

     `endpos' 的值，会传递给 *note search(): 18a3. 或 *note match():
     18a2. 的方法 a *note 正则对象: 983. 。这个是正则引擎停止在字符串搜
     索一个匹配的索引位置。

 -- 屬性: Match.lastindex

     捕获组的最后一个匹配的整数索引值，或者 ‘None’ 如果没有匹配产生的话
     。比如，对于字符串 ‘'ab'’，表达式 ‘(a)b’, ‘((a)(b))’, 和 ‘((ab))’ 将
     得到 ‘lastindex == 1’ ， 而 ‘(a)(b)’ 会得到 ‘lastindex == 2’ 。

 -- 屬性: Match.lastgroup

     最后一个匹配的命名组名字，或者 ‘None’ 如果没有产生匹配的话。

 -- 屬性: Match.re

     返回产生这个实例的 *note 正则对象: 983. ， 这个实例是由 正则对象的
     *note match(): 18a2. 或 *note search(): 18a3. 方法产生的。

 -- 屬性: Match.string

     传递到 *note match(): 18a2. 或 *note search(): 18a3. 的字符串。

3.7 版更變: 添加了对 *note copy.copy(): 4d1. 和 *note copy.deepcopy():
4d2. 的支持。匹配对象被看作是原子性的。


File: python.info,  Node: 正则表达式例子,  Prev: 匹配对象,  Up: re --- 正则表达式操作

5.6.2.5 正则表达式例子
......................

* Menu:

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


File: python.info,  Node: 检查对子,  Next: 模拟 scanf,  Up: 正则表达式例子

5.6.2.6 检查对子
................

在这个例子里，我们使用以下辅助函数来更好地显示匹配对象:

     def displaymatch(match):
         if match is None:
             return None
         return '<Match: %r, groups=%r>' % (match.group(), match.groups())

假设你在写一个扑克程序，一个玩家的一手牌为五个字符的串，每个字符表示一张
牌，"a" 就是 A, "k" K， "q" Q, "j" J, "t" 为 10, "2" 到 "9" 表示2 到 9。

要看给定的字符串是否有效，我们可以按照以下步骤

     >>> 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=()>"

最后一手牌，‘"727ak"’ ，包含了一个对子，或者两张同样数值的牌。要用正则表
达式匹配它，应该使用向后引用如下

     >>> 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',)>"

要找出对子由什么牌组成，开发者可以按照下面的方式来使用匹配对象的 *note
group(): 18b7. 方法:

     >>> 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'


File: python.info,  Node: 模拟 scanf,  Next: search vs match,  Prev: 检查对子,  Up: 正则表达式例子

5.6.2.7 模拟 scanf()
....................

Python 目前没有一个类似c函数 ‘scanf()’ 的替代品。正则表达式通常比
‘scanf()’ 格式字符串要更强大一些，但也带来更多复杂性。下面的表格提供了
‘scanf()’ 格式符和正则表达式大致相同的映射。

‘scanf()’ 格式符                     正则表达式
                                     
---------------------------------------------------------------------------------------
                                     
‘%c’                                 ‘.’
                                     
                                     
‘%5c’                                ‘.{5}’
                                     
                                     
‘%d’                                 ‘[-+]?\d+’
                                     
                                     
‘%e’, ‘%E’, ‘%f’, ‘%g’               ‘[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?’
                                     
                                     
‘%i’                                 ‘[-+]?(0[xX][\dA-Fa-f]+|0[0-7]*|\d+)’
                                     
                                     
‘%o’                                 ‘[-+]?[0-7]+’
                                     
                                     
‘%s’                                 ‘\S+’
                                     
                                     
‘%u’                                 ‘\d+’
                                     
                                     
‘%x’, ‘%X’                           ‘[-+]?(0[xX])?[\dA-Fa-f]+’
                                     

从文件名和数字提取字符串

     /usr/sbin/sendmail - 0 errors, 4 warnings

你可以使用 ‘scanf()’ 格式化

     %s - %d errors, %d warnings

等价的正则表达式是：

     (\S+) - (\d+) errors, (\d+) warnings


File: python.info,  Node: search vs match,  Next: 制作一个电话本,  Prev: 模拟 scanf,  Up: 正则表达式例子

5.6.2.8 search() vs. match()
............................

Python 提供了两种不同的操作：基于 *note re.match(): c83. 检查字符串开头
，或者 *note re.search(): c82. 检查字符串的任意位置（默认Perl中的行为）
。

例如

     >>> re.match("c", "abcdef")    # No match
     >>> re.search("c", "abcdef")   # Match
     <re.Match object; span=(2, 3), match='c'>

在 *note search(): c82. 中，可以用 ‘'^'’ 作为开始来限制匹配到字符串的首
位

     >>> 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'>

注意 *note MULTILINE: 1898. 多行模式中函数 *note match(): c83. 只匹配字
符串的开始，但使用 *note search(): c82. 和以 ‘'^'’ 开始的正则表达式会匹
配每行的开始

     >>> 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'>


File: python.info,  Node: 制作一个电话本,  Next: 文字整理,  Prev: search vs match,  Up: 正则表达式例子

5.6.2.9 制作一个电话本
......................

*note split(): 4d0. 将字符串用参数传递的样式分隔开。这个方法对于转换文本
数据到易读而且容易修改的数据结构，是很有用的，如下面的例子证明。

首先，这里是输入。 它通常来自一个文件，这里我们使用三重引号字符串语法

     >>> 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"""

条目用一个或者多个换行符分开。现在我们将字符串转换为一个列表，每个非空行
都有一个条目:

     >>> 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']

最终，将每个条目分割为一个由名字、姓氏、电话号码和地址组成的列表。我们为
*note split(): 4d0. 使用了 ‘maxsplit’ 形参，因为地址中包含有被我们作为分
割模式的空格符:

     >>> [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']]

‘:?’ 样式匹配姓后面的冒号，因此它不出现在结果列表中。如果 ‘maxsplit’ 设
置为 ‘4’ ，我们还可以从地址中获取到房间号:

     >>> [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']]


File: python.info,  Node: 文字整理,  Next: 查找所有副词,  Prev: 制作一个电话本,  Up: 正则表达式例子

5.6.2.10 文字整理
.................

*note sub(): 579. 替换字符串中出现的样式的每一个实例。这个例子证明了使用
*note sub(): 579. 来整理文字，或者随机化每个字符的位置，除了首位和末尾字
符

     >>> 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.'


File: python.info,  Node: 查找所有副词,  Next: 查找所有的副词及其位置,  Prev: 文字整理,  Up: 正则表达式例子

5.6.2.11 查找所有副词
.....................

*note findall(): a44. 匹配样式 `所有' 的出现，不仅是像 *note search():
c82. 中的第一个匹配。比如，如果一个作者希望找到文字中的所有副词，他可能
会按照以下方法用 *note findall(): a44.

     >>> text = "He was carefully disguised but captured quickly by police."
     >>> re.findall(r"\w+ly\b", text)
     ['carefully', 'quickly']


File: python.info,  Node: 查找所有的副词及其位置,  Next: 原始字符串标记,  Prev: 查找所有副词,  Up: 正则表达式例子

5.6.2.12 查找所有的副词及其位置
...............................

如果需要匹配样式的更多信息， *note finditer(): 18a8. 可以起到作用，它提
供了 *note 匹配对象: 984. 作为返回值，而不是字符串。继续上面的例子，如果
一个作者希望找到所有副词和它的位置，可以按照下面方法使用 *note
finditer(): 18a8.

     >>> 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


File: python.info,  Node: 原始字符串标记,  Next: 写一个词法分析器,  Prev: 查找所有的副词及其位置,  Up: 正则表达式例子

5.6.2.13 原始字符串标记
.......................

原始字符串记法 (‘r"text"’) 保持正则表达式正常。否则，每个正则式里的反斜
杠(‘'\'’) 都必须前缀一个反斜杠来转义。比如，下面两行代码功能就是完全一致
的

     >>> 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 '>

当需要匹配一个字符反斜杠，它必须在正则表达式中转义。在原始字符串记法，就
是 ‘r"\\"’。否则就必须用 ‘"\\\\"’，来表示同样的意思

     >>> re.match(r"\\", r"\\")
     <re.Match object; span=(0, 1), match='\\'>
     >>> re.match("\\\\", r"\\")
     <re.Match object; span=(0, 1), match='\\'>


File: python.info,  Node: 写一个词法分析器,  Prev: 原始字符串标记,  Up: 正则表达式例子

5.6.2.14 写一个词法分析器
.........................

一个 词法器或词法分析器(1) 分析字符串，并分类成目录组。 这是写一个编译器
或解释器的第一步。

文字目录是由正则表达式指定的。这个技术是通过将这些样式合并为一个主正则式
，并且循环匹配来实现的

     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 = '''
         IF quantity THEN
             total := total + price * quantity;
             tax := price * 0.05;
         ENDIF;
     '''

     for token in tokenize(statements):
         print(token)

该词法器产生以下的输出

     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)

(Frie09) Friedl, Jeffrey.  Mastering Regular Expressions.  3rd ed.,
O’Reilly Media, 2009. 该书的第三版不再包含 Python，但第一版极详细地覆盖
了正则表达式模式串的编写。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Lexical_analysis


File: python.info,  Node: difflib --- 计算差异的辅助工具,  Next: textwrap --- 文本自动换行与填充,  Prev: re --- 正则表达式操作,  Up: 文本處理 Text Processing 服務

5.6.3 ‘difflib’ — 计算差异的辅助工具
------------------------------------

`源代码:' Lib/difflib.py(1)

__________________________________________________________________

此模块提供用于比较序列的类和函数。 例如，它可被用于比较文件，并可产生多
种格式的不同文件差异信息，包括 HTML 和上下文以及统一的 diff 数据。 有关
比较目录和文件，另请参阅 *note filecmp: 7d. 模块。

 -- 類別: difflib.SequenceMatcher

     这是一个灵活的类，可用于比较任何类型的序列对，只要序列元素为 *note
     hashable: 276. 对象。 其基本算法要早于由 Ratcliff 和 Obershelp 于
     1980 年代末期发表并以“格式塔模式匹配”的夸张名称命名的算法，并且更加
     有趣一些。 其思路是找到不包含“垃圾”元素的最长连续匹配子序列；所谓
     “垃圾”元素是指其在某种意义上没有价值，例如空白行或空白符。 （处理垃
     圾元素是对 Ratcliff 和 Obershelp 算法的一个扩展。） 然后同样的思路
     将递归地应用于匹配序列的左右序列片段。 这并不能产生最小编辑序列，但
     确实能产生在人们看来“正确”的匹配。

     `耗时:' 基本 Ratcliff-Obershelp 算法在最坏情况下为立方时间而在一般
     情况下为平方时间。 *note SequenceMatcher: a30. 在最坏情况下为平方时
     间而在一般情况下的行为受到序列中有多少相同元素这一因素的微妙影响；
     在最佳情况下则为线性时间。

     `自动垃圾启发式计算:' *note SequenceMatcher: a30. 支持使用启发式计
     算来自动将特定序列项视为垃圾。 这种启发式计算会统计每个单独项在序列
     中出现的次数。 如果某一项（在第一项之后）的重复次数超过序列长度的
     1% 并且序列长度至少有 200 项，该项会被标记为“热门”并被视为序列匹配
     中的垃圾。 这种启发式计算可以通过在创建 *note SequenceMatcher: a30.
     时将 ‘autojunk’ 参数设为 ‘False’ 来关闭。

     3.2 版新加入: `autojunk' 形参。

 -- 類別: difflib.Differ

     这个类的作用是比较由文本行组成的序列，并产生可供人阅读的差异或增量
     信息。 Differ 统一使用 *note SequenceMatcher: a30. 来完成行序列的比
     较以及相似（接近匹配）行内部字符序列的比较。

     *note Differ: 18d0. 增量的每一行均以双字母代码打头：

     双字母代码     意义
                    
     ---------------------------------------------------------------
                    
     ‘'- '’         行为序列 1 所独有
                    
                    
     ‘'+ '’         行为序列 2 所独有
                    
                    
     ‘' '’          行在两序列中相同
                    
                    
     ‘'? '’         行不存在于任一输入序列
                    

     以 ’‘?’’ 打头的行尝试将视线引至行以外而不存在于任一输入序列的差异。
     如果序列包含制表符则这些行可能会令人感到迷惑。

 -- 類別: difflib.HtmlDiff

     这个类可用于创建 HTML 表格（或包含表格的完整 HTML 文件）以并排地逐
     行显示文本比较，行间与行外的更改将突出显示。 此表格可以基于完全或上
     下文差异模式来生成。

     这个类的构造函数：

      -- 成員函式: __init__ (tabsize=8, wrapcolumn=None, linejunk=None,
               charjunk=IS_CHARACTER_JUNK)

          初始化 *note HtmlDiff: 18d1. 的实例。

          `tabsize' 是一个可选关键字参数，指定制表位的间隔，默认值为
          ‘8’。

          `wrapcolumn' 是一个可选关键字参数，指定行文本自动打断并换行的
          列位置，默认值为 ‘None’ 表示不自动换行。

          `linejunk' 和 `charjunk' 均是可选关键字参数，会传入 *note
          ndiff(): 18d3. (被 *note HtmlDiff: 18d1. 用来生成并排显示的
          HTML 差异)。 请参阅 *note ndiff(): 18d3. 文档了解参数默认值及
          其说明。

     下列是公开的方法

      -- 成員函式: make_file (fromlines, tolines, fromdesc='',
               todesc='', context=False, numlines=5, *, charset='utf-8')

          比较 `fromlines' 和 `tolines' (字符串列表) 并返回一个字符串，
          表示一个完整 HTML 文件，其中包含各行差异的表格，行间与行外的更
          改将突出显示。

          `fromdesc' 和 `todesc' 均是可选关键字参数，指定来源/目标文件的
          列标题字符串（默认均为空白字符串）。

          `context' 和 `numlines' 均是可选关键字参数。 当只要显示上下文
          差异时就将 `context' 设为 ‘True’，否则默认值 ‘False’ 为显示完
          整文件。 `numlines' 默认为 ‘5’。 当 `context' 为 ‘True’ 时
          `numlines' 将控制围绕突出显示差异部分的上下文行数。 当
          `context' 为 ‘False’ 时 `numlines' 将控制在使用 "next" 超链接
          时突出显示差异部分之前所显示的行数（设为零则会导致 "next" 超链
          接将下一个突出显示差异部分放在浏览器顶端，不添加任何前导上下文
          ）。

               備註: `fromdesc' 和 `todesc' 会被当作未转义的 HTML 来解读
               ，当接收不可信来源的输入时应该适当地进行转义。

          3.5 版更變: 增加了 `charset' 关键字参数。 HTML 文档的默认字符
          集从 ‘'ISO-8859-1'’ 更改为 ‘'utf-8'’。

      -- 成員函式: make_table (fromlines, tolines, fromdesc='',
               todesc='', context=False, numlines=5)

          比较 `fromlines' 和 `tolines' (字符串列表) 并返回一个字符串，
          表示一个包含各行差异的完整 HTML 表格，行间与行外的更改将突出显
          示。

          此方法的参数与 *note make_file(): 7bc. 方法的相同。

     ‘Tools/scripts/diff.py’ 是这个类的命令行前端，其中包含一个很好的使
     用示例。

 -- 函式: difflib.context_diff (a, b, fromfile='', tofile='',
          fromfiledate='', tofiledate='', n=3, lineterm='\n')

     比较 `a' 和 `b' (字符串列表)；返回上下文差异格式的增量信息 (一个产
     生增量行的 *note generator: a83.)。

     所谓上下文差异是一种只显示有更改的行再加几个上下文行的紧凑形式。 更
     改被显示为之前/之后的样式。 上下文行数由 `n' 设定，默认为三行。

     默认情况下，差异控制行（以 ‘***’ or ‘---’ 表示）是通过末尾换行符来
     创建的。 这样做的好处是从 *note io.IOBase.readlines(): 18d6. 创建的
     输入将得到适用于 *note io.IOBase.writelines(): 18d7. 的差异信息，因
     为输入和输出都带有末尾换行符。

     对于没有末尾换行符的输入，应将 `lineterm' 参数设为 ‘""’，这样输出内
     容将统一不带换行符。

     上下文差异格式通常带有一个记录文件名和修改时间的标头。 这些信息的部
     分或全部可以使用字符串 `fromfile', `tofile', `fromfiledate' 和
     `tofiledate' 来指定。 修改时间通常以 ISO 8601 格式表示。 如果未指定
     ，这些字符串默认为空。

          >>> 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

     请参阅 *note difflib 的命令行接口: 18d8. 获取更详细的示例。

 -- 函式: difflib.get_close_matches (word, possibilities, n=3,
          cutoff=0.6)

     返回由最佳“近似”匹配构成的列表。 `word' 为一个指定目标近似匹配的序
     列（通常为字符串），`possibilities' 为一个由用于匹配 `word' 的序列
     构成的列表（通常为字符串列表）。

     可选参数 `n' (默认为 ‘3’) 指定最多返回多少个近似匹配； `n' 必须大于
     ‘0’.

     可选参数 `cutoff' (默认为 ‘0.6’) 是一个 [0, 1] 范围内的浮点数。 与
     `word' 相似度得分未达到该值的候选匹配将被忽略。

     候选匹配中（不超过 `n' 个）的最佳匹配将以列表形式返回，按相似度得分
     排序，最相似的排在最前面。

          >>> 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']

 -- 函式: difflib.ndiff (a, b, linejunk=None,
          charjunk=IS_CHARACTER_JUNK)

     比较 `a' 和 `b' (字符串列表)；返回 *note Differ: 18d0. 形式的增量信
     息 (一个产生增量行的 *note generator: a83.)。

     可选关键字形参 `linejunk' 和 `charjunk' 均为过滤函数 (或为 ‘None’)：

     `linejunk': 此函数接受单个字符串参数，如果其为垃圾字符串则返回真值
     ，否则返回假值。 默认为 ‘None’。 此外还有一个模块层级的函数 *note
     IS_LINE_JUNK(): 18da.，它会过滤掉没有可见字符的行，除非该行添加了至
     多一个井号符 (‘'#'’) – 但是下层的 *note SequenceMatcher: a30. 类会
     动态分析哪些行的重复频繁到足以形成噪音，这通常会比使用此函数的效果
     更好。

     `charjunk': 此函数接受一个字符（长度为 1 的字符串)，如果其为垃圾字
     符则返回真值，否则返回假值。 默认为模块层级的函数 *note
     IS_CHARACTER_JUNK(): 18db.，它会过滤掉空白字符（空格符或制表符；但
     包含换行符可不是个好主意！）。

     ‘Tools/scripts/ndiff.py’ 是这个函数的命令行前端。

          >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
          ...              'ore\ntree\nemu\n'.splitlines(keepends=True))
          >>> print(''.join(diff), end="")
          - one
          ?  ^
          + ore
          ?  ^
          - two
          - three
          ?  -
          + tree
          + emu

 -- 函式: difflib.restore (sequence, which)

     返回两个序列中产生增量的那一个。

     给出一个由 *note Differ.compare(): 18dd. 或 *note ndiff(): 18d3. 产
     生的 `序列'，提取出来自文件 1 或 2 (`which' 形参) 的行，去除行前缀
     。

     示例:

          >>> 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(''.join(restore(diff, 1)), end="")
          one
          two
          three
          >>> print(''.join(restore(diff, 2)), end="")
          ore
          tree
          emu

 -- 函式: difflib.unified_diff (a, b, fromfile='', tofile='',
          fromfiledate='', tofiledate='', n=3, lineterm='\n')

     比较 `a' 和 `b' (字符串列表)；返回统一差异格式的增量信息 (一个产生
     增量行的 *note generator: a83.)。

     所以统一差异是一种只显示有更改的行再加几个上下文行的紧凑形式。 更改
     被显示为内联的样式（而不是分开的之前/之后文本块）。 上下文行数由
     `n' 设定，默认为三行。

     默认情况下，差异控制行 (以 ‘---’, ‘+++’ 或 ‘@@’ 表示) 是通过末尾换
     行符来创建的。 这样做的好处是从 *note io.IOBase.readlines(): 18d6.
     创建的输入将得到适用于 *note io.IOBase.writelines(): 18d7. 的差异信
     息，因为输入和输出都带有末尾换行符。

     对于没有末尾换行符的输入，应将 `lineterm' 参数设为 ‘""’，这样输出内
     容将统一不带换行符。

     上下文差异格式通常带有一个记录文件名和修改时间的标头。 这些信息的部
     分或全部可以使用字符串 `fromfile', `tofile', `fromfiledate' 和
     `tofiledate' 来指定。 修改时间通常以 ISO 8601 格式表示。 如果未指定
     ，这些字符串默认为空。

          >>> 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

     请参阅 *note difflib 的命令行接口: 18d8. 获取更详细的示例。

 -- 函式: difflib.diff_bytes (dfunc, a, b, fromfile=b'', tofile=b'',
          fromfiledate=b'', tofiledate=b'', n=3, lineterm=b'\n')

     使用 `dfunc' 比较 `a' 和 `b' (字节串对象列表)；产生以 `dfunc' 所返
     回格式表示的差异行列表（也是字节串）。 `dfunc' 必须是可调用对象，通
     常为 *note unified_diff(): 18de. 或 *note context_diff(): 18d5.。

     允许你比较编码未知或不一致的数据。 除 `n' 之外的所有输入都必须为字
     节串对象而非字符串。 作用方式为无损地将所有输入 (除 `n' 之外) 转换
     为字符串，并调用 ‘dfunc(a, b, fromfile, tofile, fromfiledate,
     tofiledate, n, lineterm)’。 `dfunc' 的输出会被随即转换回字节串，这
     样你所得到的增量行将具有与 `a' 和 `b' 相同的未知/不一致编码。

     3.5 版新加入.

 -- 函式: difflib.IS_LINE_JUNK (line)

     对于可忽略的行返回 ‘True’。 如果 `line' 为空行或只包含单个 ‘'#'’ 则
     `line' 行就是可忽略的，否则就是不可忽略的。 此函数被用作较旧版本
     *note ndiff(): 18d3. 中 `linejunk' 形参的默认值。

 -- 函式: difflib.IS_CHARACTER_JUNK (ch)

     对于可忽略的字符返回 ‘True’。 字符 `ch' 如果为空格符或制表符则 `ch'
     就是可忽略的，否则就是不可忽略的。 此函数被用作 *note ndiff():
     18d3. 中 `charjunk' 形参的默认值。

也參考
......

模式匹配：格式塔方法(2)

     John W. Ratcliff 和 D. E. Metzener 对于一种类似算法的讨论。 此文于
     1988 年 7 月发表于 Dr.  Dobb’s Journal(3)。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/difflib.py

   (2) 
http://www.drdobbs.com/database/pattern-matching-the-gestalt-approach/184407970

   (3) http://www.drdobbs.com/


File: python.info,  Node: SequenceMatcher 对象,  Next: SequenceMatcher 的示例,  Up: difflib --- 计算差异的辅助工具

5.6.3.1 SequenceMatcher 对象
............................

*note SequenceMatcher: a30. 类具有这样的构造器：

 -- 類別: difflib.SequenceMatcher (isjunk=None, a='', b='',
          autojunk=True)

     可选参数 `isjunk' 必须为 ‘None’ (默认值) 或为接受一个序列元素并当且
     仅当其为应忽略的“垃圾”元素时返回真值的单参数函数。 传入 ‘None’ 作为
     `isjunk' 的值就相当于传入 ‘lambda x: False’；也就是说不忽略任何值。
     例如，传入:

          lambda x: x in " \t"

     如果你以字符序列的形式对行进行比较，并且不希望区分空格符或硬制表符
     。

     可选参数 `a' 和 `b' 为要比较的序列；两者默认为空字符串。 两个序列的
     元素都必须为 *note hashable: 276.。

     可选参数 `autojunk' 可用于启用自动垃圾启发式计算。

     3.2 版新加入: `autojunk' 形参。

     SequenceMatcher 对象接受三个数据属性: `bjunk' 是 `b' 当中 `isjunk'
     为 ‘True’ 的元素集合；`bpopular' 是被启发式计算（如果其未被禁用）视
     为热门候选的非垃圾元素集合；`b2j' 是将 `b' 当中剩余元素映射到一个它
     们出现位置列表的字典。 所有三个数据属性将在 `b' 通过 *note
     set_seqs(): 18e1. 或 *note set_seq2(): 18e2. 重置时被重置。

     3.2 版新加入: `bjunk' 和 `bpopular' 属性。

     *note SequenceMatcher: a30. 对象具有以下方法：

      -- 成員函式: set_seqs (a, b)

          设置要比较的两个序列。

     *note SequenceMatcher: a30. 计算并缓存有关第二个序列的详细信息，这
     样如果你想要将一个序列与多个序列进行比较，可使用 *note set_seq2():
     18e2. 一次性地设置该常用序列并重复地对每个其他序列各调用一次 *note
     set_seq1(): 18e3.。

      -- 成員函式: set_seq1 (a)

          设置要比较的第一个序列。 要比较的第二个序列不会改变。

      -- 成員函式: set_seq2 (b)

          设置要比较的第二个序列。 要比较的第一个序列不会改变。

      -- 成員函式: find_longest_match (alo=0, ahi=None, blo=0, bhi=None)

          找出 ‘a[alo:ahi]’ 和 ‘b[blo:bhi]’ 中的最长匹配块。

          如果 `isjunk' 被省略或为 ‘None’，*note find_longest_match():
          1041. 将返回 ‘(i, j, k)’ 使得 ‘a[i:i+k]’ 等于 ‘b[j:j+k]’，其中
          ‘alo <= i <= i+k <= ahi’ 并且 ‘blo <= j <= j+k <= bhi’。 对于
          所有满足这些条件的 ‘(i', j', k')’，如果 ‘i == i'’, ‘j <= j'’ 也
          被满足，则附加条件 ‘k >= k'’, ‘i <= i'’。 换句话说，对于所有最
          长匹配块，返回在 `a' 当中最先出现的一个，而对于在 `a' 当中最先
          出现的所有最长匹配块，则返回在 `b' 当中最先出现的一个。

               >>> s = SequenceMatcher(None, " abcd", "abcd abcd")
               >>> s.find_longest_match(0, 5, 0, 9)
               Match(a=0, b=4, size=5)

          如果提供了 `isjunk'，将按上述规则确定第一个最长匹配块，但额外
          附加不允许块内出现垃圾元素的限制。 然后将通过（仅）匹配两边的
          垃圾元素来尽可能地扩展该块。 这样结果块绝对不会匹配垃圾元素，
          除非同样的垃圾元素正好与有意义的匹配相邻。

          这是与之前相同的例子，但是将空格符视为垃圾。 这将防止 ‘'
          abcd'’ 直接与第二个序列末尾的 ‘' abcd'’ 相匹配。 而只可以匹配
          ‘'abcd'’，并且是匹配第二个序列最左边的 ‘'abcd'’：

               >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
               >>> s.find_longest_match(0, 5, 0, 9)
               Match(a=1, b=0, size=4)

          如果未找到匹配块，此方法将返回 ‘(alo, blo, 0)’。

          此方法将返回一个 *note named tuple: b7b. ‘Match(a, b, size)’。

          3.9 版更變: 加入默认参数。

      -- 成員函式: get_matching_blocks ()

          返回描述非重叠匹配子序列的三元组列表。 每个三元组的形式为 ‘(i,
          j, n)’，其含义为 ‘a[i:i+n] == b[j:j+n]’。 这些三元组按 `i' 和
          `j' 单调递增排列。

          最后一个三元组用于占位，其值为 ‘(len(a), len(b), 0)’。 它是唯
          一 ‘n == 0’ 的三元组。 如果 ‘(i, j, n)’ 和 ‘(i', j', n')’ 是在
          列表中相邻的三元组，且后者不是列表中的最后一个三元组，则 ‘i+n
          < i'’ 或 ‘j+n < j'’；换句话说，相邻的三元组总是描述非相邻的相
          等块。

               >>> 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)]

      -- 成員函式: get_opcodes ()

          返回描述如何将 `a' 变为 `b' 的 5 元组列表，每个元组的形式为
          ‘(tag, i1, i2, j1, j2)’。 在第一个元组中 ‘i1 == j1 == 0’，而在
          其余的元组中 `i1' 等于前一个元组的 `i2'，并且 `j1' 也等于前一
          个元组的 `j2'。

          `tag' 值为字符串，其含义如下：

          值                  意义
                              
          ----------------------------------------------------------------------
                              
          ‘'replace'’         ‘a[i1:i2]’ 应由 ‘b[j1:j2]’ 替换。
                              
                              
          ‘'delete'’          ‘a[i1:i2]’ 应被删除。 请注意在此情况下 ‘j1 ==
                              j2’。
                              
                              
          ‘'insert'’          ‘b[j1:j2]’ 应插入到 ‘a[i1:i1]’。 请注意在此情况
                              下 ‘i1 == i2’。
                              
                              
          ‘'equal'’           ‘a[i1:i2] == b[j1:j2]’ (两个子序列相同)。
                              

          例如:

               >>> 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' --> ''
               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]       '' --> 'f'

      -- 成員函式: get_grouped_opcodes (n=3)

          返回一个带有最多 `n' 行上下文的分组的 *note generator: a83.。

          从 *note get_opcodes(): 18e5. 所返回的组开始，此方法会拆分出较
          小的更改簇并消除没有更改的间隔区域。

          这些分组以与 *note get_opcodes(): 18e5. 相同的格式返回。

      -- 成員函式: ratio ()

          返回一个取值范围 [0, 1] 的浮点数作为序列相似性度量。

          其中 T 是两个序列中元素的总数量，M 是匹配的数量，即 2.0*M / T。
          请注意如果两个序列完全相同则该值为 ‘1.0’，如果两者完全不同则为
          ‘0.0’。

          如果 *note get_matching_blocks(): 18e4. 或 *note
          get_opcodes(): 18e5. 尚未被调用则此方法运算消耗较大，在此情况
          下你可能需要先调用 *note quick_ratio(): 18e8. 或 *note
          real_quick_ratio(): 18e9. 来获取一个上界。

               備註: 注意: *note ratio(): 18e7. 调用的结果可能会取决于参
               数的顺序。 例如:

                    >>> SequenceMatcher(None, 'tide', 'diet').ratio()
                    0.25
                    >>> SequenceMatcher(None, 'diet', 'tide').ratio()
                    0.5

      -- 成員函式: quick_ratio ()

          相对快速地返回一个 *note ratio(): 18e7. 的上界。

      -- 成員函式: real_quick_ratio ()

          非常快速地返回一个 *note ratio(): 18e7. 的上界。

这三个返回匹配部分占字符总数的比率的方法可能由于不同的近似级别而给出不一
样的结果，但是 ‘quick_ratio()’ 和 ‘real_quick_ratio()’ 总是会至少与
‘ratio()’ 一样大：

     >>> s = SequenceMatcher(None, "abcd", "bcde")
     >>> s.ratio()
     0.75
     >>> s.quick_ratio()
     0.75
     >>> s.real_quick_ratio()
     1.0


File: python.info,  Node: SequenceMatcher 的示例,  Next: Differ 对象,  Prev: SequenceMatcher 对象,  Up: difflib --- 计算差异的辅助工具

5.6.3.2 SequenceMatcher 的示例
..............................

以下示例比较两个字符串，并将空格视为“垃圾”：

     >>> s = SequenceMatcher(lambda x: x == " ",
     ...                     "private Thread currentThread;",
     ...                     "private volatile Thread currentThread;")

‘ratio()’ 返回一个 [0, 1] 范围内的整数作为两个序列相似性的度量。 根据经
验，‘ratio()’ 值超过 0.6 就意味着两个序列是近似匹配的：

     >>> print(round(s.ratio(), 3))
     0.866

如果你只对两个序列相匹配的位置感兴趣，则 ‘get_matching_blocks()’ 就很方
便：

     >>> 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

请注意 ‘get_matching_blocks()’ 返回的最后一个元组总是只用于占位的
‘(len(a), len(b), 0)’，这也是元组末尾元素（匹配的元素数量）为 ‘0’ 的唯一
情况。

如果你想要知道如何将第一个序列转成第二个序列，可以使用 ‘get_opcodes()’:

     >>> 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]

也參考
......

   * 此模块中的 *note get_close_matches(): 18d9. 函数显示了如何基于
     *note SequenceMatcher: a30. 构建简单的代码来执行有用的功能。

   * 使用 *note SequenceMatcher: a30. 构建小型应用的 简易版本控制方案
     (1)。

   ---------- Footnotes ----------

   (1) https://code.activestate.com/recipes/576729/


File: python.info,  Node: Differ 对象,  Next: Differ 示例,  Prev: SequenceMatcher 的示例,  Up: difflib --- 计算差异的辅助工具

5.6.3.3 Differ 对象
...................

请注意 *note Differ: 18d0. 所生成的增量并不保证是 `最小' 差异。 相反，最
小差异往往是违反直觉的，因为它们会同步任何可能的地方，有时甚至意外产生相
距 100 页的匹配。 将同步点限制为连续匹配保留了一些局部性概念，这偶尔会带
来产生更长差异的代价。

*note Differ: 18d0. 类具有这样的构造器：

 -- 類別: difflib.Differ (linejunk=None, charjunk=None)

     可选关键字形参 `linejunk' 和 `charjunk' 均为过滤函数 (或为 ‘None’)：

     `linejunk': 接受单个字符串作为参数的函数，如果其为垃圾字符串则返回
     真值。 默认值为 ‘None’，意味着没有任何行会被视为垃圾行。

     `charjunk': 接受单个字符（长度为 1 的字符串）作为参数的函数，如果其
     为垃圾字符则返回真值。 默认值为 ‘None’，意味着没有任何字符会被视为
     垃圾字符。

     这些垃圾过滤函数可加快查找差异的匹配速度，并且不会导致任何差异行或
     字符被忽略。 请阅读 *note find_longest_match(): 1041. 方法的
     `isjunk' 形参的描述了解详情。

     *note Differ: 18d0. 对象是通过一个单独方法来使用（生成增量）的：

      -- 成員函式: compare (a, b)

          比较两个由行组成的序列，并生成增量（一个由行组成的序列）。

          每个序列必须包含一个以换行符结尾的单行字符串。 这样的序列可以
          通过文件类对象的 *note readlines(): 18d6. 方法来获取。 所生成
          的增量同样由以换行符结尾的字符串构成，可以通过文件类对象的
          *note writelines(): 18d7. 方法原样打印出来。


File: python.info,  Node: Differ 示例,  Next: difflib 的命令行接口,  Prev: Differ 对象,  Up: difflib --- 计算差异的辅助工具

5.6.3.4 Differ 示例
...................

此示例比较两段文本。 首先我们设置文本为以换行符结尾的单行字符串构成的序
列（这样的序列也可以通过文件类对象的 ‘readlines()’ 方法来获取）：

     >>> text1 = '''  1. Beautiful is better than ugly.
     ...   2. Explicit is better than implicit.
     ...   3. Simple is better than complex.
     ...   4. Complex is better than complicated.
     ... '''.splitlines(keepends=True)
     >>> len(text1)
     4
     >>> text1[0][-1]
     '\n'
     >>> text2 = '''  1. Beautiful is better than ugly.
     ...   3.   Simple is better than complex.
     ...   4. Complicated is better than complex.
     ...   5. Flat is better than nested.
     ... '''.splitlines(keepends=True)

接下来我们实例化一个 Differ 对象：

     >>> d = Differ()

请注意在实例化 *note Differ: 18d0. 对象时我们可以传入函数来过滤掉“垃圾
”行和字符。 详情参见 *note Differ(): 18d0. 构造器说明。

最后，我们比较两个序列：

     >>> result = list(d.compare(text1, text2))

‘result’ 是一个字符串列表，让我们将其美化打印出来：

     >>> 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']

作为单独的多行字符串显示出来则是这样：

     >>> 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.


File: python.info,  Node: difflib 的命令行接口,  Prev: Differ 示例,  Up: difflib --- 计算差异的辅助工具

5.6.3.5 difflib 的命令行接口
............................

这个实例演示了如何使用 difflib 来创建一个类似于 ‘diff’ 的工具。 它同样包
含在 Python 源码发布包中，文件名为 ‘Tools/scripts/diff.py’。

     #!/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()


File: python.info,  Node: textwrap --- 文本自动换行与填充,  Next: unicodedata --- Unicode 数据库,  Prev: difflib --- 计算差异的辅助工具,  Up: 文本處理 Text Processing 服務

5.6.4 ‘textwrap’ — 文本自动换行与填充
-------------------------------------

`源代码:' Lib/textwrap.py(1)

__________________________________________________________________

*note textwrap: 10a. 模块提供了一些快捷函数，以及可以完成所有工作的类
*note TextWrapper: 9d0.。 如果你只是要对一两个文本字符串进行自动换行或填
充，快捷函数应该就够用了；否则的话，你应该使用 *note TextWrapper: 9d0. 的
实例来提高效率。

 -- 函式: 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)

     对 `text' (字符串) 中的单独段落自动换行以使每行长度最多为 `width' 个
     字符。 返回由输出行组成的列表，行尾不带换行符。

     可选的关键字参数对应于 *note TextWrapper: 9d0. 的实例属性，具体文档
     见下。

     请参阅 *note TextWrapper.wrap(): 18f3. 方法了解有关 *note wrap():
     f86. 行为的详细信息。

 -- 函式: 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)

     对 `text' 中的单独段落自动换行，并返回一个包含被自动换行段落的单独
     字符串。 *note fill(): f87. 是以下语句的快捷方式

          "\n".join(wrap(text, ...))

     特别要说明的是，*note fill(): f87. 接受与 *note wrap(): f86. 完全相
     同的关键字参数。

 -- 函式: textwrap.shorten (text, width, *, fix_sentence_endings=False,
          break_long_words=True, break_on_hyphens=True, placeholder='
          [...]')

     折叠并截短给定的 `text' 以符合给定的 `width'。

     首先，将折叠 `text' 中的空格（所有连续空格替换为单个空格）。 如果结
     果能适合 `width' 则将其返回。 否则将丢弃足够数量的末尾单词以使得剩
     余单词加 ‘placeholder’ 能适合 ‘width’：

          >>> textwrap.shorten("Hello  world!", width=12)
          'Hello world!'
          >>> textwrap.shorten("Hello  world!", width=11)
          'Hello [...]'
          >>> textwrap.shorten("Hello world", width=10, placeholder="...")
          'Hello...'

     可选的关键字参数对应于 *note TextWrapper: 9d0. 的实际属性，具体见下
     文。 请注意文本在被传入 *note TextWrapper: 9d0. 的 *note fill():
     f87. 函数之前会被折叠，因此改变 *note tabsize: 18f4, *note
     expand_tabs: 18f5, *note drop_whitespace: 18f6. 和 *note
     replace_whitespace: 18f7. 的值将没有任何效果。

     3.4 版新加入.

 -- 函式: textwrap.dedent (text)

     移除 `text' 中每一行的任何相同前缀空白符。

     这可以用来清除三重引号字符串行左侧空格，而仍然在源码中显示为缩进格
     式。

     请注意制表符和空格符都被视为是空白符，但它们并不相等：以下两行 ‘"
     hello"’ 和 ‘"\thello"’ 不会被视为具有相同的前缀空白符。

     只包含空白符的行会在输入时被忽略并在输出时被标准化为单个换行符。

     例如:

          def test():
              # end first line with \ to avoid the empty line!
              s = '''\
              hello
                world
              '''
              print(repr(s))          # prints '    hello\n      world\n    '
              print(repr(dedent(s)))  # prints 'hello\n  world\n'

 -- 函式: textwrap.indent (text, prefix, predicate=None)

     将 `prefix' 添加到 `text' 中选定行的开头。

     通过调用 ‘text.splitlines(True)’ 来对行进行拆分。

     默认情况下，`prefix' 会被添加到所有不是只由空白符（包括任何行结束符
     ）组成的行。

     例如:

          >>> s = 'hello\n\n \nworld'
          >>> indent(s, '  ')
          '  hello\n\n \n  world'

     可选的 `predicate' 参数可用来控制哪些行要缩进。 例如，可以很容易地
     为空行或只有空白符的行添加 `prefix':

          >>> print(indent(s, '+ ', lambda line: True))
          + hello
          +
          +
          + world

     3.3 版新加入.

*note wrap(): f86, *note fill(): f87. 和 *note shorten(): 9d3. 的作用方
式为创建一个 *note TextWrapper: 9d0. 实例并在其上调用单个方法。 该实例不
会被重用，因此对于要使用 *note wrap(): f86. 和/或 *note fill(): f87. 来
处理许多文本字符串的应用来说，创建你自己的 *note TextWrapper: 9d0. 对象
可能会更有效率。

文本最好在空白符位置自动换行，包括带连字符单词的连字符之后；长单词仅在必
要时会被拆分，除非 *note TextWrapper.break_long_words: 18f9. 被设为假值
。

 -- 類別: textwrap.TextWrapper (**kwargs)

     *note TextWrapper: 9d0. 构造器接受多个可选的关键字参数。 每个关键字
     参数对应一个实例属性，比如说

          wrapper = TextWrapper(initial_indent="* ")

     相当于：

          wrapper = TextWrapper()
          wrapper.initial_indent = "* "

     你可以多次重用相同的 *note TextWrapper: 9d0. 对象，并且你也可以在使
     用期间通过直接向实例属性赋值来修改它的任何选项。

     *note TextWrapper: 9d0. 的实例属性（以及构造器的关键字参数）如下所
     示：

      -- 屬性: width

          (默认: ‘70’) 自动换行的最大行长度。 只要输入文本中没有长于
          *note width: 18fa. 的单个单词，*note TextWrapper: 9d0. 就能保
          证没有长于 *note width: 18fa. 个字符的输出行。

      -- 屬性: expand_tabs

          (默认: ‘True’) 如果为真值，则 `text' 中所有的制表符将使用
          `text' 的 ‘expandtabs()’ 方法扩展为空格符。

      -- 屬性: tabsize

          (默认: ‘8’) 如果 *note expand_tabs: 18f5. 为真值，则 `text' 中
          所有的制表符将扩展为零个或多个空格，具体取决于当前列位置和给定
          的制表宽度。

          3.3 版新加入.

      -- 屬性: replace_whitespace

          (default: ‘True’) 如果为真值，在制表符扩展之后、自动换行之前，
          *note wrap(): f86. 方法将把每个空白字符都替换为单个空格。 会被
          替换的空白字符如下：制表，换行，垂直制表，进纸和回车
          (‘'\t\n\v\f\r'’)。

               備註: 如果 *note expand_tabs: 18f5. 为假值且 *note
               replace_whitespace: 18f7. 为真值，每个制表符将被替换为单
               个空格，这与制表符扩展是 `不' 一样的。

               備註: 如果 *note replace_whitespace: 18f7. 为假值，在一行
               的中间有可能出现换行符并导致怪异的输出。 因此，文本应当（
               使用 *note str.splitlines(): 178c. 或类似方法）拆分为段落
               并分别进行自动换行。

      -- 屬性: drop_whitespace

          (默认: ‘True’) 如果为真值，每一行开头和末尾的空白字符（在包装
          之后、缩进之前）会被丢弃。 但是段落开头的空白字符如果后面不带
          任何非空白字符则不会被丢弃。 如果被丢弃的空白字符占据了一个整
          行，则该整行将被丢弃。

      -- 屬性: initial_indent

          (默认: ‘''’) 将被添加到被自动换行输出内容的第一行的字符串。 其
          长度会被计入第一行的长度。 空字符串不会被缩进。

      -- 屬性: subsequent_indent

          (default: ‘''’) 将被添加到被自动换行输出内容除第一行外的所有行
          的字符串。 其长度会被计入除行一行外的所有行的长度。

      -- 屬性: fix_sentence_endings

          (默认: ‘False’) 如果为真值，*note TextWrapper: 9d0. 将尝试检测
          句子结尾并确保句子间总是以恰好两个空格符分隔。 对于使用等宽字
          体的文本来说通常都需要这样。 但是，句子检测算法并不完美：它假
          定句子结尾是一个小写字母加字符 ‘'.'’, ‘'!'’ 或 ‘'?'’ 中的一个
          ，并可能带有字符 ‘'"'’ 或 ‘"'"’，最后以一个空格结束。 此算法的
          问题之一是它无法区分以下文本中的 "Dr."

               [...] Dr. Frankenstein's monster [...]

          和以下文本中的 "Spot."

               [...] See Spot. See Spot run [...]

          *note fix_sentence_endings: 18fd. 默认为假值。

          由于句子检测算法依赖于 ‘string.lowercase’ 来确定“小写字母”，以
          及约定在句点后使用两个空格来分隔处于同一行的句子，因此只适用于
          英语文本。

      -- 屬性: break_long_words

          (默认: ‘True’) 如果为真值，则长度超过 *note width: 18fa. 的单
          词将被分开以保证行的长度不会超过 *note width: 18fa.。 如果为假
          值，超长单词不会被分开，因而某些行的长度可能会超过 *note
          width: 18fa.。 （超长单词将被单独作为一行，以尽量减少超出
          *note width: 18fa. 的情况。）

      -- 屬性: break_on_hyphens

          (默认: ‘True’) 如果为真值，将根据英语的惯例首选在空白符和复合
          词的连字符之后自动换行。 如果为假值，则只有空白符会被视为合适
          的潜在断行位置，但如果你确实不希望出现分开的单词则你必须将
          *note break_long_words: 18f9. 设为假值。 之前版本的默认行为总
          是允许分开带有连字符的单词。

      -- 屬性: max_lines

          (默认: ‘None’) 如果不为 ‘None’，则输出内容将最多包含
          `max_lines' 行，并使 `placeholder' 出现在输出内容的末尾。

          3.4 版新加入.

      -- 屬性: placeholder

          (默认: ‘' [...]'’) 该文本将在输出文本被截短时出现在文本末尾。

          3.4 版新加入.

     *note TextWrapper: 9d0. 还提供了一些公有方法，类似于模块层级的便捷
     函数：

      -- 成員函式: wrap (text)

          对 `text' (字符串) 中的单独段落自动换行以使每行长度最多为
          *note width: 18fa. 个字符。 所有自动换行选项均获取自 *note
          TextWrapper: 9d0. 实例的实例属性。 返回由输出行组成的列表，行
          尾不带换行符。 如果自动换行输出结果没有任何内容，则返回空列表
          。

      -- 成員函式: fill (text)

          对 `text' 中的单独段落自动换行并返回包含被自动换行段落的单独字
          符串。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/textwrap.py


File: python.info,  Node: unicodedata --- Unicode 数据库,  Next: stringprep --- 因特网字符串预备,  Prev: textwrap --- 文本自动换行与填充,  Up: 文本處理 Text Processing 服務

5.6.5 ‘unicodedata’ — Unicode 数据库
------------------------------------

__________________________________________________________________

此模块提供了对 Unicode Character Database (UCD) 的访问，其中定义了所有
Unicode 字符的字符属性。 此数据库中包含的数据编译自 UCD 版本 13.0.0(1)。

该模块使用与 Unicode 标准附件 #44 “Unicode 字符数据库”(2) 中所定义的相同
名称和符号。 它定义了以下函数：

 -- 函式: unicodedata.lookup (name)

     按名称查找字符。如果找到具有给定名称的字符，则返回相应的字符。 如果
     没有找到，则 *note KeyError: 3e9. 被引发。

     3.3 版更變: 已添加对名称别名 (3) 和命名序列 (4) 的支持。

 -- 函式: unicodedata.name (chr[, default])

     返回分配给字符 `chr' 的名称作为字符串。如果没有定义名称，则返回
     `default' ，如果没有给出，则 *note ValueError: 16d. 被引发。

 -- 函式: unicodedata.decimal (chr[, default])

     返回分配给字符 `chr' 的十进制值作为整数。 如果没有定义这样的值，则
     返回 `default' ，如果没有给出，则 *note ValueError: 16d. 被引发。

 -- 函式: unicodedata.digit (chr[, default])

     返回分配给字符 `chr' 的数字值作为整数。 如果没有定义这样的值，则返
     回 `default' ，如果没有给出，则 *note ValueError: 16d. 被引发。

 -- 函式: unicodedata.numeric (chr[, default])

     返回分配给字符 `chr' 的数值作为浮点数。 如果没有定义这样的值，则返
     回 `default' ，如果没有给出，则 *note ValueError: 16d. 被引发。

 -- 函式: unicodedata.category (chr)

     返回分配给字符 `chr' 的常规类别为字符串。

 -- 函式: unicodedata.bidirectional (chr)

     返回分配给字符 `chr' 的双向类作为字符串。如果未定义此类值，则返回空
     字符串。

 -- 函式: unicodedata.combining (chr)

     返回分配给字符 `chr' 的规范组合类作为整数。如果没有定义组合类，则返
     回 ‘0’ 。

 -- 函式: unicodedata.east_asian_width (chr)

     返回分配给字符 `chr' 的东亚宽度作为字符串。

 -- 函式: unicodedata.mirrored (chr)

     返回分配给字符 `chr' 的镜像属性为整数。如果字符在双向文本中被识别为
     “镜像”字符，则返回 ‘1’ ，否则返回 ‘0’ 。

 -- 函式: unicodedata.decomposition (chr)

     返回分配给字符 `chr' 的字符分解映射作为字符串。如果未定义此类映射，
     则返回空字符串。

 -- 函式: unicodedata.normalize (form, unistr)

     返回 Unicode 字符串 `unistr' 的正常形式 `form' 。 `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 字符串被规范化并且人类读者看起来相同，如果一个具有
     组合字符而另一个没有，则它们可能无法相等。

 -- 函式: unicodedata.is_normalized (form, unistr)

     判断 Unicode 字符串 `unistr' 是否为正规形式 `form'。 `form' 的有效
     值为 ’NFC’, ’NFKC’, ’NFD’ 和 ’NFKD’。

     3.8 版新加入.

此外，该模块暴露了以下常量：

 -- Data: unicodedata.unidata_version

     此模块中使用的 Unicode 数据库的版本。

 -- Data: unicodedata.ucd_3_2_0

     这是一个与整个模块具有相同方法的对象，但对于需要此特定版本的
     Unicode 数据库（如 IDNA ）的应用程序，则使用 Unicode 数据库版本 3.2
     。

示例：

     >>> 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'

註解
....

   ---------- Footnotes ----------

   (1) https://www.unicode.org/Public/13.0.0/ucd

   (2) https://www.unicode.org/reports/tr44/

   (3) (1) ‘https://www.unicode.org/Public/13.0.0/ucd/NameAliases.txt’

   (4) (2)
‘https://www.unicode.org/Public/13.0.0/ucd/NamedSequences.txt’


File: python.info,  Node: stringprep --- 因特网字符串预备,  Next: readline --- GNU readline 接口,  Prev: unicodedata --- Unicode 数据库,  Up: 文本處理 Text Processing 服務

5.6.6 ‘stringprep’ — 因特网字符串预备
-------------------------------------

`源代码:' Lib/stringprep.py(1)

__________________________________________________________________

在标识因特网上的事物（例如主机名），经常需要比较这些标识是否（相等）。 这
种比较的具体执行可能会取决于应用域的不同，例如是否要区分大小写等等。 有
时也可能需要限制允许的标识为仅由“可打印”字符组成。

RFC 3454(2) 定义了在因特网协议中 Unicode 字符串的“预备”过程。 在将字符串
连线传输之前，它们会先使用预备过程进行处理，之后它们将具有特定的标准形式
。 该 RFC 定义了一系列表格，它们可以被组合为选项配置。 每个配置必须定义
所使用的表格，‘stringprep’ 过程的其他可选项也是配置的组成部分。
‘stringprep’ 配置的一个例子是 ‘nameprep’，它被用于国际化域名。

模块 *note stringprep: f7. 仅公开了来自 RFC 3454(3) 的表格。 由于这些如
果表格如果表示为字典或列表将会非常庞大，该模块在内部使用 Unicode 字符数
据库。 该模块本身的源代码是使用 ‘mkstringprep.py’ 工具生成的。

因此，这些表格以函数而非数据结构的形式公开。 在 RFC 中有两种表格：集合与
映射。 对于集合，*note stringprep: f7. 提供了“特征函数”，即如果形参是集
合的一部分则返回值为 ‘True’ 的函数。 对于映射，它提供了映射函数：它会根
据给定的键返回所关联的值。 以下是模块中所有可用函数的列表。

 -- 函式: stringprep.in_table_a1 (code)

     确定 `code' 是否属于 tableA.1 (Unicode 3.2 中的未分配码位)。

 -- 函式: stringprep.in_table_b1 (code)

     确定 `code' 是否属于 tableB.1 (通常映射为空值)。

 -- 函式: stringprep.map_table_b2 (code)

     返回 `code' 依据 tableB.2 (配合 NFKC 使用的大小写转换映射) 所映射的
     值。

 -- 函式: stringprep.map_table_b3 (code)

     返回 `code' 依据 tableB.3 (不附带正规化的大小写折叠映射) 所映射的值
     。

 -- 函式: stringprep.in_table_c11 (code)

     确定 `code' 是否属于 tableC.1.1 (ASCII 空白字符)。

 -- 函式: stringprep.in_table_c12 (code)

     确定 `code' 是否属于 tableC.1.2 (非 ASCII 空白字符)。

 -- 函式: stringprep.in_table_c11_c12 (code)

     确定 `code' 是否属于 tableC.1 (空白字符，C.1.1 和 C.1.2 的并集)。

 -- 函式: stringprep.in_table_c21 (code)

     确定 `code' 是否属于 tableC.2.1 (ASCII 控制字符)。

 -- 函式: stringprep.in_table_c22 (code)

     确定 `code' 是否属于 tableC.2.2 (非 ASCII 控制字符)。

 -- 函式: stringprep.in_table_c21_c22 (code)

     确定 `code' 是否属于 tableC.2 (控制字符，C.2.1 和 C.2.2 的并集)。

 -- 函式: stringprep.in_table_c3 (code)

     确定 `code' 是否属于 tableC.3 (私有使用)。

 -- 函式: stringprep.in_table_c4 (code)

     确定 `code' 是否属于 tableC.4 (非字符码位)。

 -- 函式: stringprep.in_table_c5 (code)

     确定 `code' 是否属于 tableC.5 (替代码)。

 -- 函式: stringprep.in_table_c6 (code)

     确定 `code' 是否属于 tableC.6 (不适用于纯文本)。

 -- 函式: stringprep.in_table_c7 (code)

     确定 `code' 是否属于 tableC.7 (不适用于规范表示)。

 -- 函式: stringprep.in_table_c8 (code)

     确定 `code' 是否属于 tableC.8 (改变显示属性或已弃用)。

 -- 函式: stringprep.in_table_c9 (code)

     确定 `code' 是否属于 tableC.9 (标记字符)。

 -- 函式: stringprep.in_table_d1 (code)

     确定 `code' 是否属于 tableD.1 (带有双向属性 "R" 或 "AL" 的字符)。

 -- 函式: stringprep.in_table_d2 (code)

     确定 `code' 是否属于 tableD.2 (带有双向属性 "L" 的字符)。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/stringprep.py

   (2) https://tools.ietf.org/html/rfc3454.html

   (3) https://tools.ietf.org/html/rfc3454.html


File: python.info,  Node: readline --- GNU readline 接口,  Next: rlcompleter --- GNU readline 的补全函数,  Prev: stringprep --- 因特网字符串预备,  Up: 文本處理 Text Processing 服務

5.6.7 ‘readline’ — GNU readline 接口
------------------------------------

__________________________________________________________________

*note readline: de. 模块定义了许多方便从 Python 解释器完成和读取/写入历
史文件的函数。 此模块可以直接使用，或通过支持在交互提示符下完成 Python 标
识符的 *note rlcompleter: e1. 模块使用。 使用此模块进行的设置会同时影响
解释器的交互提示符以及内置 *note input(): d33. 函数提供的提示符。

Readline keybindings may be configured via an initialization file,
typically ‘.inputrc’ in your home directory.  See Readline Init File(1)
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.

     備註: 底层的 Readline 库 API 可能使用 ‘libedit’ 库来实现而不是 GNU
     readline。 在 macOS 上 *note readline: de. 模块会在运行时检测所使用
     的是哪个库。

     ‘libedit’ 所用的配置文件与 GNU readline 的不同。 如果你要在程序中载
     入配置字符串你可以在 ‘readline.__doc__’ 中检测文本 "libedit" 来区分
     GNU readline 和 libedit。

     如果你是在 macOS 上使用 `editline'/‘libedit’ readline 模拟，则位于
     你的主目录中的初始化文件名称为 ‘.editrc’。 例如，‘~/.editrc’ 中的以
     下内容将开启 `vi' 按键绑定以及 TAB 补全:

          python:bind -v
          python:bind ^I rl_complete

* Menu:

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

   ---------- Footnotes ----------

   (1) https://tiswww.cwru.edu/php/chet/readline/rluserman.html#SEC9


File: python.info,  Node: 初始化文件,  Next: 行缓冲区,  Up: readline --- GNU readline 接口

5.6.7.1 初始化文件
..................

下列函数与初始化文件和用户配置有关：

 -- 函式: readline.parse_and_bind (string)

     执行在 `string' 参数中提供的初始化行。 此函数会调用底层库中的
     ‘rl_parse_and_bind()’。

 -- 函式: readline.read_init_file ([filename])

     执行一个 readline 初始化文件。 默认文件名为最近所使用的文件名。 此
     函数会调用底层库中的 ‘rl_read_init_file()’。


File: python.info,  Node: 行缓冲区,  Next: 历史文件,  Prev: 初始化文件,  Up: readline --- GNU readline 接口

5.6.7.2 行缓冲区
................

下列函数会在行缓冲区上操作。

 -- 函式: readline.get_line_buffer ()

     返回行缓冲区的当前内容 (底层库中的 ‘rl_line_buffer’)。

 -- 函式: readline.insert_text (string)

     将文本插入行缓冲区的当前游标位置。 该函数会调用底层库中的
     ‘rl_insert_text()’，但会忽略其返回值。

 -- 函式: readline.redisplay ()

     改变屏幕的显示以反映行缓冲区的当前内容。 该函数会调用底层库中的
     ‘rl_redisplay()’。


File: python.info,  Node: 历史文件,  Next: 历史列表,  Prev: 行缓冲区,  Up: readline --- GNU readline 接口

5.6.7.3 历史文件
................

下列函数会在历史文件上操作：

 -- 函式: readline.read_history_file ([filename])

     载入一个 readline 历史文件，并将其添加到历史列表。 默认文件名为
     ‘~/.history’。 此函数会调用底层库中的 ‘read_history()’。

 -- 函式: readline.write_history_file ([filename])

     将历史列表保存为 readline 历史文件，覆盖任何现有文件。 默认文件名为
     ‘~/.history’。 此函数会调用底层库中的 ‘write_history()’。

 -- 函式: readline.append_history_file (nelements[, filename])

     将历史列表的最后 `nelements' 项添加到历史文件。 默认文件名为
     ‘~/.history’。 文件必须已存在。 此函数会调用底层库中的
     ‘append_history()’。 此函数仅当 Python 编译包带有支持此功能的库版本
     时才会存在。

     3.5 版新加入.

 -- 函式: readline.get_history_length ()
 -- 函式: readline.set_history_length (length)

     设置或返回需要保存到历史文件的行数。 *note write_history_file():
     192c. 函数会通过调用底层库中的 ‘history_truncate_file()’ 以使用该值
     来截取历史文件。 负值意味着不限制历史文件的大小。


File: python.info,  Node: 历史列表,  Next: 启动钩子,  Prev: 历史文件,  Up: readline --- GNU readline 接口

5.6.7.4 历史列表
................

以下函数会在全局历史列表上操作：

 -- 函式: readline.clear_history ()

     清除当前历史。 此函数会调用底层库的 ‘clear_history()’。 此 Python 函
     数仅当 Python 编译包带有支持此功能的库版本时才会存在。

 -- 函式: readline.get_current_history_length ()

     返回历史列表的当前项数。 （此函数不同于 *note get_history_length():
     192d.，后者是返回将被写入历史文件的最大行数。）

 -- 函式: readline.get_history_item (index)

     返回序号为 `index' 的历史条目的当前内容。 条目序号从一开始。 此函数
     会调用底层库中的 ‘history_get()’。

 -- 函式: readline.remove_history_item (pos)

     从历史列表中移除指定位置上的历史条目。 条目位置从零开始。 此函数会
     调用底层库中的 ‘remove_history()’。

 -- 函式: readline.replace_history_item (pos, line)

     将指定位置上的历史条目替换为 `line'。 条目位置从零开始。 此函数会调
     用底层库中的 ‘replace_history_entry()’。

 -- 函式: readline.add_history (line)

     将 `line' 添加到历史缓冲区，相当于是最近输入的一行。 此函数会调用底
     层库中的 ‘add_history()’。

 -- 函式: readline.set_auto_history (enabled)

     启用或禁用当通过 readline 读取输入时自动调用 ‘add_history()’。
     `enabled' 参数应为一个布尔值，当其为真值时启用自动历史，当其为假值
     时禁用自动历史。

     3.6 版新加入.

     `CPython implementation detail:' Auto history is enabled by
     default, and changes to this do not persist across multiple
     sessions.


File: python.info,  Node: 启动钩子,  Next: Completion,  Prev: 历史列表,  Up: readline --- GNU readline 接口

5.6.7.5 启动钩子
................

 -- 函式: readline.set_startup_hook ([function])

     设置或移除底层库的 ‘rl_startup_hook’ 回调所发起调用的函数。 如果指
     定了 `function'，它将被用作新的钩子函数；如果省略或为 ‘None’，任何
     已安装的函数将被移除。 钩子函数将在 readline 打印第一个提示信息之前
     不带参数地被调用。

 -- 函式: readline.set_pre_input_hook ([function])

     设置或移除底层库的 ‘rl_pre_input_hook’ 回调所发起调用的函数。 如果
     指定了 `function'，它将被用作新的钩子函数；如果省略或为 ‘None’，任
     何已安装的函数将被移除。 钩子函数将在打印第一个提示信息之后、
     readline 开始读取输入字符之前不带参数地被调用。 此函数仅当 Python 编
     译包带有支持此功能的库版本时才会存在。


File: python.info,  Node: Completion,  Next: 示例<2>,  Prev: 启动钩子,  Up: readline --- GNU readline 接口

5.6.7.6 Completion
..................

以下函数与自定义单词补全函数的实现有关。 这通常使用 Tab 键进行操作，能够
提示并自动补全正在输入的单词。 默认情况下，Readline 设置为由 *note
rlcompleter: e1. 来补全交互模式解释器的 Python 标识符。 如果 *note
readline: de. 模块要配合自定义的补全函数来使用，则需要设置不同的单词分隔
符。

 -- 函式: readline.set_completer ([function])

     设置或移除补全函数。 如果指定了 `function'，它将被用作新的补全函数
     ；如果省略或为 ‘None’，任何已安装的补全函数将被移除。 补全函数的调
     用形式为 ‘function(text, state)’，其中 `state' 为 ‘0’, ‘1’, ‘2’,
     ..., 直至其返回一个非字符串值。 它应当返回下一个以 `text' 开头的候
     选补全内容。

     已安装的补全函数将由传递给底层库中 ‘rl_completion_matches()’ 的
     `entry_func' 回调函数来发起调用。 `text' 字符串来自于底层库中
     ‘rl_attempted_completion_function’ 回调函数的第一个形参。

 -- 函式: readline.get_completer ()

     获取补全函数，如果没有设置补全函数则返回 ‘None’。

 -- 函式: readline.get_completion_type ()

     获取正在尝试的补全类型。 此函数会将底层库中的 ‘rl_completion_type’
     变量作为一个整数返回。

 -- 函式: readline.get_begidx ()
 -- 函式: readline.get_endidx ()

     获取补全域的开始和结束序号。 这些序号就是传给底层库中
     ‘rl_attempted_completion_function’ 回调函数的 `start' 和 `end' 参数
     。

 -- 函式: readline.set_completer_delims (string)
 -- 函式: readline.get_completer_delims ()

     设置或获取补全的单词分隔符。 此分隔符确定了要考虑补全的单词的开始和
     结束位置（补全域）。 这些函数会访问底层库的
     ‘rl_completer_word_break_characters’ 变量。

 -- 函式: readline.set_completion_display_matches_hook ([function])

     设置或移除补全显示函数。 如果指定了 `function'，它将被用作新的补全
     显示函数；如果省略或为 ‘None’，任何已安装的补全显示函数将被移除。 此
     函数会设置或清除底层库的 ‘rl_completion_display_matches_hook’ 回调
     函数。 补全显示函数会在每次需要显示匹配项时以
     ‘function(substitution, [matches], longest_match_length)’ 的形式被
     调用。


File: python.info,  Node: 示例<2>,  Prev: Completion,  Up: readline --- GNU readline 接口

5.6.7.7 示例
............

以下示例演示了如何使用 *note readline: de. 模块的历史读取或写入函数来自
动加载和保存用户主目录下名为 ‘.python_history’ 的历史文件。 以下代码通常
应当在交互会话期间从用户的 *note PYTHONSTARTUP: 9cb. 文件自动执行。

     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)

此代码实际上会在 Python 运行于 *note 交互模式: 9c9. 时自动运行 (参见
*note Readline 配置: 9cc.)。

以下示例实现了同样的目标，但是通过只添加新历史的方式来支持并发的交互会话
。

     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)

以下示例扩展了 *note code.InteractiveConsole: 1944. 类以支持历史保存/恢
复。

     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)


File: python.info,  Node: rlcompleter --- GNU readline 的补全函数,  Prev: readline --- GNU readline 接口,  Up: 文本處理 Text Processing 服務

5.6.8 ‘rlcompleter’ — GNU readline 的补全函数
---------------------------------------------

`源代码:' Lib/rlcompleter.py(1)

__________________________________________________________________

‘rlcompeleter’ 通过补全有效的 Python 标识符和关键字定义了一个适用于
*note readline: de. 模块的补全函数。

当此模块在具有可用的 *note readline: de. 模块的 Unix 平台被导入, 一个
‘Completer’ 实例将被自动创建并且它的 ‘complete()’ 方法将设置为 *note
readline: de. 的补全器.

示例:

     >>> 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.

*note rlcompleter: e1. 模块是为了使用 Python 的 *note 交互模式: 9c9. 而
设计的。 除非 Python 是通过 *note -S: bf7. 选项运行, 这个模块总是自动地
被导入且配置 (参见 *note Readline 配置: 9cc.)。

在没有 *note readline: de. 的平台, 此模块定义的 ‘Completer’ 类仍然可以用
于自定义行为.

* Menu:

* Completer 对象::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/rlcompleter.py


File: python.info,  Node: Completer 对象,  Up: rlcompleter --- GNU readline 的补全函数

5.6.8.1 Completer 对象
......................

Completer 对象具有以下方法：

 -- 成員函式: Completer.complete (text, state)

     为 `text' 返回第 `state' 项补全。

     如果指定的 `text' 不包含句点字符 (‘'.'’)，它将根据当前 *note
     __main__: 1, *note builtins: 12. 和保留关键字（定义于 *note
     keyword: a6. 模块）所定义的名称进行补全。

     如果为带有句点的名称执行调用，它将尝试尽量求值直到最后一部分为止而
     不产生附带影响（函数不会被求值，但它可以生成对 *note __getattr__():
     42a. 的调用），并通过 *note dir(): df9. 函数来匹配剩余部分。 在对表
     达式求值期间引发的任何异常都会被捕获、静默处理并返回 *note None:
     203.。


File: python.info,  Node: 二进制数据服务,  Next: 数据类型,  Prev: 文本處理 Text Processing 服務,  Up: Python 標準函式庫 Standard Library

5.7 二进制数据服务
==================

本章介绍的模块提供了一些操作二进制数据的基本服务操作。 有关二进制数据的
其他操作，特别是与文件格式和网络协议有关的操作，将在相关章节中介绍。

下面描述的一些库 *note 文本處理 (Text Processing) 服務: 1775. 也可以使用
ASCII 兼容的二进制格式（例如 *note re: dd. ）或所有二进制数据（例如
*note difflib: 36. ）。

另外，请参阅 Python 的内置二进制数据类型的文档 *note 二进制序列类型 —
bytes, bytearray, memoryview: 171d. 。

* Menu:

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


File: python.info,  Node: struct --- 将字节串解读为打包的二进制数据,  Next: codecs --- 编解码器注册和相关基类,  Up: 二进制数据服务

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

`源代码：' Lib/struct.py(1)

__________________________________________________________________

此模块可以执行 Python 值和以 Python *note bytes: 172. 对象表示的 C 结构
之间的转换。 这可以被用来处理存储在文件中或是从网络连接等其他来源获取的
二进制数据。 它使用 *note 格式字符串: 194e. 作为 C 结构布局的精简描述以
及与 Python 值的双向转换。

     備註: 默认情况下，打包给定 C 结构的结果会包含填充字节以使得所涉及的
     C 类型保持正确的对齐；类似地，对齐在解包时也会被纳入考虑。 选择此种
     行为的目的是使得被打包结构的字节能与相应 C 结构在内存中的布局完全一
     致。 要处理平台独立的数据格式或省略隐式的填充字节，请使用
     ‘standard’ 大小和对齐而不是 ‘native’ 大小和对齐：详情参见 *note
     字节顺序，大小和对齐方式: 194f.。

某些 *note struct: f8. 的函数（以及 *note Struct: 1950. 的方法）接受一个
`buffer' 参数。 这将指向实现了 *note 缓冲协议: 171c. 并提供只读或是可读
写缓冲的对象。 用于此目的的最常见类型为 *note bytes: 172. 和 *note
bytearray: 173.，但许多其他可被视为字节数组的类型也实现了缓冲协议，因此
它们无需额外从 *note bytes: 172. 对象复制即可被读取或填充。

* Menu:

* 函数和异常::
* 格式字符串::
* 类::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/struct.py


File: python.info,  Node: 函数和异常,  Next: 格式字符串,  Up: struct --- 将字节串解读为打包的二进制数据

5.7.1.1 函数和异常
..................

此模块定义了下列异常和函数：

 -- 例外: struct.error

     会在多种场合下被引发的异常；其参数为一个描述错误信息的字符串。

 -- 函式: struct.pack (format, v1, v2, ...)

     返回一个 bytes 对象，其中包含根据格式字符串 `format' 打包的值 `v1',
     `v2', ... 参数个数必须与格式字符串所要求的值完全匹配。

 -- 函式: struct.pack_into (format, buffer, offset, v1, v2, ...)

     根据格式字符串 `format' 打包 `v1', `v2', ... 等值并将打包的字节串写
     入可写缓冲区 `buffer' 从 `offset' 开始的位置。 请注意 `offset' 是必
     需的参数。

 -- 函式: struct.unpack (format, buffer)

     根据格式字符串 `format' 从缓冲区 `buffer' 解包（假定是由
     ‘pack(format, ...)’ 打包）。 结果为一个元组，即使其只包含一个条目。
     缓冲区的字节大小必须匹配格式所要求的大小，如 *note calcsize():
     10c5. 所示。

 -- 函式: struct.unpack_from (format, /, buffer, offset=0)

     对 `buffer' 从位置 `offset' 开始根据格式字符串 `format' 进行解包。
     结果为一个元组，即使其中只包含一个条目。 缓冲区的字节大小从位置
     `offset' 开始必须至少为 *note calcsize(): 10c5. 显示的格式所要求的
     大小。

 -- 函式: struct.iter_unpack (format, buffer)

     根据格式字符串 `format' 以迭代方式从缓冲区 `buffer' 解包。 此函数返
     回一个迭代器，它将从缓冲区读取相同大小的块直至其内容全部耗尽。 缓冲
     区的字节大小必须整数倍于格式所要求的大小，如 *note calcsize():
     10c5. 所示。

     每次迭代将产生一个如格式字符串所指定的元组。

     3.4 版新加入.

 -- 函式: struct.calcsize (format)

     返回与格式字符串 `format' 相对应的结构的大小（亦即 ‘pack(format,
     ...)’ 所产生的字节串对象的大小）。


File: python.info,  Node: 格式字符串,  Next: 类,  Prev: 函数和异常,  Up: struct --- 将字节串解读为打包的二进制数据

5.7.1.2 格式字符串
..................

格式字符串是用来在打包和解包数据时指定预期布局的机制。 它们使用指定被打
包/解包数据类型的 *note 格式字符: 1955. 进行构建。 此外，还有一些特殊字
符用来控制 *note 字节顺序，大小和对齐方式: 194f.。

* Menu:

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


File: python.info,  Node: 字节顺序，大小和对齐方式,  Next: 格式字符,  Up: 格式字符串

5.7.1.3 字节顺序，大小和对齐方式
................................

默认情况下，C类型以机器的本机格式和字节顺序表示，并在必要时通过跳过填充
字节进行正确对齐（根据C编译器使用的规则）。

或者，根据下表，格式字符串的第一个字符可用于指示打包数据的字节顺序，大小
和对齐方式：

字符            字节顺序                     大小           对齐方式
                                                            
----------------------------------------------------------------------------
                                                            
‘@’             按原字节                     按原字节       按原字节
                                                            
                                                            
‘=’             按原字节                     标准           无
                                                            
                                                            
‘<’             小端                         标准           无
                                                            
                                                            
‘>’             大端                         标准           无
                                                            
                                                            
‘!’             网络（=大端）                标准           无
                                                            

如果第一个字符不是其中之一，则假定为 ‘'@'’ 。

本机字节顺序可能为大端或是小端，取决于主机系统的不同。 例如， Intel x86
和 AMD64 (x86-64) 是小端的；Motorola 68000 和 PowerPC G5 是大端的；ARM 和
Intel Itanium 具有可切换的字节顺序（双端）。 请使用 ‘sys.byteorder’ 来检
查你的系统字节顺序。

本机大小和对齐方式是使用 C 编译器的 ‘sizeof’ 表达式来确定的。 这总是会与
本机字节顺序相绑定。

标准大小仅取决于格式字符；请参阅 *note 格式字符: 1955. 部分中的表格。

请注意 ‘'@'’ 和 ‘'='’ 之间的区别：两个都使用本机字节顺序，但后者的大小和
对齐方式是标准化的。

形式 ‘'!'’ 代表网络字节顺序总是使用在 IETF RFC 1700(1) 中所定义的大端序
。

没有什么方式能指定非本机字节顺序（强制字节对调）；请正确选择使用 ‘'<'’ 或
‘'>'’。

註解：

  1. 填充只会在连续结构成员之间自动添加。 填充不会添加到已编码结构的开头
     和末尾。

  2. 当使用非本机大小和对齐方式即 ’<’, ’>’, ’=’, and ’!’ 时不会添加任何
     填充。

  3. 要将结构的末尾对齐到符合特定类型的对齐要求，请以该类型代码加重复计
     数的零作为格式结束。 参见 *note 示例: 1957.。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc1700


File: python.info,  Node: 格式字符,  Next: 示例<3>,  Prev: 字节顺序，大小和对齐方式,  Up: 格式字符串

5.7.1.4 格式字符
................

格式字符具有以下含义；C 和 Python 值之间的按其指定类型的转换应当是相当明
显的。 ‘标准大小’列是指当使用标准大小时以字节表示的已打包值大小；也就是
当格式字符串以 ‘'<'’, ‘'>'’, ‘'!'’ 或 ‘'='’ 之一开头的情况。 当使用本机
大小时，已打包值的大小取决于具体的平台。

格式         C Type                         Python 类型              标准大小             註解
                                                                                          
-----------------------------------------------------------------------------------------------------------
                                                                                          
‘x’          填充字节                       无
                                            
                                                                                          
‘c’          ‘char’                         长度为 1 的字节串        1
                                                                     
                                                                                          
‘b’          ‘signed char’                  整数                     1                    (1), (2)
                                                                                          
                                                                                          
‘B’          ‘unsigned char’                整数                     1                    (2)
                                                                                          
                                                                                          
‘?’          ‘_Bool’                        bool                     1                    (1)
                                                                                          
                                                                                          
‘h’          ‘short’                        整数                     2                    (2)
                                                                                          
                                                                                          
‘H’          ‘unsigned short’               整数                     2                    (2)
                                                                                          
                                                                                          
‘i’          ‘int’                          整数                     4                    (2)
                                                                                          
                                                                                          
‘I’          ‘unsigned int’                 整数                     4                    (2)
                                                                                          
                                                                                          
‘l’          ‘long’                         整数                     4                    (2)
                                                                                          
                                                                                          
‘L’          ‘unsigned long’                整数                     4                    (2)
                                                                                          
                                                                                          
‘q’          ‘long long’                    整数                     8                    (2)
                                                                                          
                                                                                          
‘Q’          ‘unsigned long long’           整数                     8                    (2)
                                                                                          
                                                                                          
‘n’          ‘ssize_t’                      整数                                          (3)
                                                                                          
                                                                                          
‘N’          ‘size_t’                       整数                                          (3)
                                                                                          
                                                                                          
‘e’          (6)                            float                    2                    (4)
                                                                                          
                                                                                          
‘f’          ‘float’                        float                    4                    (4)
                                                                                          
                                                                                          
‘d’          ‘double’                       float                    8                    (4)
                                                                                          
                                                                                          
‘s’          ‘char[]’                       字节串
                                            
                                                                                          
‘p’          ‘char[]’                       字节串
                                            
                                                                                          
‘P’          ‘void *’                       整数                                          (5)
                                                                                          

3.3 版更變: 增加了对 ‘'n'’ 和 ‘'N'’ 格式的支持

3.6 版更變: 添加了对 ‘'e'’ 格式的支持。

註解：

  1. 
     ‘'?'’ 转换码对应于 C99 定义的 ‘_Bool’ 类型。 如果此类型不可用，则使
     用 ‘char’ 来模拟。 在标准模式下，它总是以一个字节表示。

  2. 当尝试使用任何整数转换码打包一个非整数时，如果该非整数具有 *note
     __index__(): 2c2. 方法，则会在打包之前调用该方法将参数转换为一个整
     数。

     3.2 版更變: 增加了针对非整数使用 *note __index__(): 2c2. 方法的特性
     。

  3. ‘'n'’ 和 ‘'N'’ 转换码仅对本机大小可用（选择为默认或使用 ‘'@'’ 字节
     顺序字符）。 对于标准大小，你可以使用适合你的应用的任何其他整数格式
     。

  4. 对于 ‘'f'’, ‘'d'’ 和 ‘'e'’ 转换码，打包表示形式将使用 IEEE 754
     binary32, binary64 或 binary16 格式 (分别对应于 ‘'f'’, ‘'d'’ 或
     ‘'e'’)，无论平台使用何种浮点格式。

  5. ‘'P'’ 格式字符仅对本机字节顺序可用（选择为默认或使用 ‘'@'’ 字节顺序
     字符）。 字节顺序字符 ‘'='’ 选择使用基于主机系统的小端或大端排序。
     struct 模块不会将其解读为本机排序，因此 ‘'P'’ 格式将不可用。

  6. IEEE 754 binary16 "半精度" 类型是在 IEEE 754 标准(1) 的 2008 修订版
     中引入的。 它包含一个符号位，5 个指数位和 11 个精度位（明确存储 10
     位），可以完全精确地表示大致范围在 ‘6.1e-05’ 和 ‘6.5e+04’ 之间的数
     字。 此类型并不被 C 编译器广泛支持：在一台典型的机器上，可以使用
     unsigned short 进行存储，但不会被用于数学运算。 请参阅维基百科页面
     half-precision floating-point format(2) 了解详情。

格式字符之前可以带有整数重复计数。 例如，格式字符串 ‘'4h'’ 的含义与
‘'hhhh'’ 完全相同。

格式之间的空白字符会被忽略；但是计数及其格式字符中不可有空白字符。

对于 ‘'s'’ 格式字符，计数会被解析为字节的长度，而不是像其他格式字符那样
的重复计数；例如，‘'10s'’ 表示一个 10 字节的字节串，而 ‘'10c'’ 表示 10 个
字符。 如果未给出计数，则默认值为 1。 对于打包操作，字节串会被适当地截断
或填充空字节以符合要求。 对于解包操作，结果字节对象总是恰好具有指定数量
的字节。 作为特殊情况，‘'0s'’ 表示一个空字符串（而 ‘'0c'’ 表示 0 个字符
）。

当使用某一种整数格式 (‘'b'’, ‘'B'’, ‘'h'’, ‘'H'’, ‘'i'’, ‘'I'’, ‘'l'’,
‘'L'’, ‘'q'’, ‘'Q'’) 打包值 ‘x’ 时，如果 ‘x’ 在该格式的有效范围之外则将
引发 *note struct.error: d7c.。

3.1 版更變: 在之前版本中，某些整数格式包装了超范围的值并会引发 *note
DeprecationWarning: 15a. 而不是 *note struct.error: d7c.。

‘'p'’ 格式字符用于编码“Pascal 字符串”，即存储在由计数指定的 `固定长度字
节' 中的可变长度短字符串。 所存储的第一个字节为字符串长度或 255 中的较小
值。 之后是字符串对应的字节。 如果传入 *note pack(): cd6. 的字符串过长（
超过计数值减 1），则只有字符串前 ‘count-1’ 个字节会被存储。 如果字符串短
于 ‘count-1’，则会填充空字节以使得恰好使用了 count 个字节。 请注意对于
*note unpack(): 1437.，‘'p'’ 格式字符会消耗 ‘count’ 个字节，但返回的字符
串永远不会包含超过 255 个字节。

对于 ‘'?'’ 格式字符，返回值为 *note True: 593. 或 *note False: 48e.。 在
打包时将会使用参数对象的逻辑值。 以本机或标准 bool 类型表示的 0 或 1 将
被打包，任何非零值在解包时将为 ‘True’。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/IEEE_floating_point#IEEE_754-2008

   (2) 
https://en.wikipedia.org/wiki/Half-precision_floating-point_format


File: python.info,  Node: 示例<3>,  Prev: 格式字符,  Up: 格式字符串

5.7.1.5 示例
............

     備註: 所有示例都假定使用一台大端机器的本机字节顺序、大小和对齐方式
     。

打包/解包三个整数的基础示例:

     >>> 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

解包的字段可通过将它们赋值给变量或将结果包装为一个具名元组来命名:

     >>> 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)

格式字符的顺序可能对大小产生影响，因为满足对齐要求所需的填充是不同的:

     >>> 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

以下格式 ‘'llh0l'’ 指定在末尾有两个填充字节，假定 long 类型按 4 个字节的
边界对齐:

     >>> pack('llh0l', 1, 2, 3)
     b'\x00\x00\x00\x01\x00\x00\x00\x02\x00\x03\x00\x00'

这仅当本机大小和对齐方式生效时才会起作用；标准大小和对齐方式并不会强制进
行任何对齐。

也參考
......

模块 *note array: 6.

     被打包为二进制存储的同质数据。

模組 *note xdrlib: 13b.

     打包和解包 XDR 数据。


File: python.info,  Node: 类,  Prev: 格式字符串,  Up: struct --- 将字节串解读为打包的二进制数据

5.7.1.6 类
..........

*note struct: f8. 模块还定义了以下类型：

 -- 類別: struct.Struct (format)

     返回一个新的 Struct 对象，它会根据格式字符串 `format' 来写入和读取
     二进制数据。 一次性地创建 Struct 对象并调用其方法相比使用同样的格式
     调用 *note struct: f8. 函数更为高效，因为这样格式字符串只需被编译一
     次。

          備註: 传递给 *note Struct: 1950. 和模块层级函数的已编译版最新
          格式字符串会被缓存，因此只使用少量格式字符串的程序无需担心重用
          单独的 *note Struct: 1950. 实例。

     已编译的 Struct 对象支持以下方法和属性：

      -- 成員函式: pack (v1, v2, ...)

          等价于 *note pack(): cd6. 函数，使用了已编译的格式。
          (‘len(result)’ 将等于 *note size: 195d.。)

      -- 成員函式: pack_into (buffer, offset, v1, v2, ...)

          等价于 *note pack_into(): 1952. 函数，使用了已编译的格式。

      -- 成員函式: unpack (buffer)

          等价于 *note unpack(): 1437. 函数，使用了已编译的格式。 缓冲区
          的字节大小必须等于 *note size: 195d.。

      -- 成員函式: unpack_from (buffer, offset=0)

          等价于 *note unpack_from(): 1953. 函数，使用了已编译的格式。 缓
          冲区的字节大小从位置 `offset' 开始必须至少为 *note size:
          195d.。

      -- 成員函式: iter_unpack (buffer)

          等价于 *note iter_unpack(): 9be. 函数，使用了已编译的格式。 缓
          冲区的大小必须为 *note size: 195d. 的整数倍。

          3.4 版新加入.

      -- 屬性: format

          用于构造此 Struct 对象的格式字符串。

          3.7 版更變: 格式字符串类型现在是 *note str: 205. 而不再是
          *note bytes: 172.。

      -- 屬性: size

          计算出对应于 *note format: 5d5. 的结构大小（亦即 *note pack():
          cd6. 方法所产生的字节串对象的大小）。


File: python.info,  Node: codecs --- 编解码器注册和相关基类,  Prev: struct --- 将字节串解读为打包的二进制数据,  Up: 二进制数据服务

5.7.2 ‘codecs’ — 编解码器注册和相关基类
---------------------------------------

`源代码：' Lib/codecs.py(1)

__________________________________________________________________

这个模块定义了标准 Python 编解码器（编码器和解码器）的基类，并提供接口用
来访问内部的 Python 编解码器注册表，该注册表负责管理编解码器和错误处理的
查找过程。 大多数标准编解码器都属于 *note 文本编码: 1731.，它们可将文本
编码为字节串，但也提供了一些编解码器可将文本编码为文本，以及字节串编码为
字节串。 自定义编解码器可以在任意类型间进行编码和解码，但某些模块特性仅
适用于 *note 文本编码: 1731. 或将数据编码为 ‘字节串’ 的编解码器。

该模块定义了以下用于使用任何编解码器进行编码和解码的函数：

 -- 函式: codecs.encode (obj, encoding='utf-8', errors='strict')

     使用为 `encoding' 注册的编解码器对 `obj' 进行编码。

     可以给定 `Errors' 以设置所需要的错误处理方案。 默认的错误处理方案
     ‘'strict'’ 表示编码错误将引发 *note ValueError: 16d. (或更特定编解
     码器相关的子类，例如 *note UnicodeEncodeError: 32a.)。 请参阅 *note
     编解码器基类: 1964. 了解有关编解码器错误处理的更多信息。

 -- 函式: codecs.decode (obj, encoding='utf-8', errors='strict')

     使用为 `encoding' 注册的编解码器对 `obj' 进行解码。

     可以给定 `Errors' 以设置所需要的错误处理方案。 默认的错误处理方案
     ‘'strict'’ 表示编码错误将引发 *note ValueError: 16d. (或更特定编解
     码器相关的子类，例如 *note UnicodeDecodeError: 32b.)。 请参阅 *note
     编解码器基类: 1964. 了解有关编解码器错误处理的更多信息。

每种编解码器的完整细节也可以直接查找获取：

 -- 函式: codecs.lookup (encoding)

     在 Python 编解码器注册表中查找编解码器信息，并返回一个 *note
     CodecInfo: 1965. 对象，其定义见下文。

     首先将会在注册表缓存中查找编码，如果未找到，则会扫描注册的搜索函数
     列表。 如果没有找到 *note CodecInfo: 1965. 对象，则将引发 *note
     LookupError: 1790.。 否则，*note CodecInfo: 1965. 对象将被存入缓存
     并返回给调用者。

 -- 類別: codecs.CodecInfo (encode, decode, streamreader=None,
          streamwriter=None, incrementalencoder=None,
          incrementaldecoder=None, name=None)

     查找编解码器注册表所得到的编解码器细节信息。 构造器参数将保存为同名
     的属性：

      -- 屬性: name

          编码名称

      -- 屬性: encode
      -- 屬性: decode

          无状态的编码和解码函数。 它们必须是具有与 Codec 的 *note
          encode(): 1969. 和 *note decode(): 196a. 方法相同接口的函数或
          方法 (参见 *note Codec 接口: 196b.)。 这些函数或方法应当工作于
          无状态的模式。

      -- 屬性: incrementalencoder
      -- 屬性: incrementaldecoder

          增量式的编码器和解码器类或工厂函数。 这些函数必须分别提供由基
          类 *note IncrementalEncoder: 196e. 和 *note
          IncrementalDecoder: 196f. 所定义的接口。 增量式编解码器可以保
          持状态。

      -- 屬性: streamwriter
      -- 屬性: streamreader

          流式写入器和读取器类或工厂函数。 这些函数必须分别提供由基类
          *note StreamWriter: 1972. 和 *note StreamReader: 1973. 所定义
          的接口。 流式编解码器可以保持状态。

为了简化对各种编解码器组件的访问，本模块提供了以下附加函数，它们使用
*note lookup(): 238. 来执行编解码器查找：

 -- 函式: codecs.getencoder (encoding)

     查找给定编码的编解码器并返回其编码器函数。

     在编码无法找到时将引发 *note LookupError: 1790.。

 -- 函式: codecs.getdecoder (encoding)

     查找给定编码的编解码器并返回其解码器函数。

     在编码无法找到时将引发 *note LookupError: 1790.。

 -- 函式: codecs.getincrementalencoder (encoding)

     查找给定编码的编解码器并返回其增量式编码器类或工厂函数。

     在编码无法找到或编解码器不支持增量式编码器时将引发 *note
     LookupError: 1790.。

 -- 函式: codecs.getincrementaldecoder (encoding)

     查找给定编码的编解码器并返回其增量式解码器类或工厂函数。

     在编码无法找到或编解码器不支持增量式解码器时将引发 *note
     LookupError: 1790.。

 -- 函式: codecs.getreader (encoding)

     查找给定编码的编解码器并返回其 *note StreamReader: 1973. 类或工厂函
     数。

     在编码无法找到时将引发 *note LookupError: 1790.。

 -- 函式: codecs.getwriter (encoding)

     查找给定编码的编解码器并返回其 *note StreamWriter: 1972. 类或工厂函
     数。

     在编码无法找到时将引发 *note LookupError: 1790.。

自定义编解码器的启用是通过注册适当的编解码器搜索函数：

 -- 函式: codecs.register (search_function)

     注册一个编解码器搜索函数。 搜索函数预期接收一个参数，即全部以小写字
     母表示的编码格式名称，其中中连字符和空格会被转换为下划线，并返回一
     个 *note CodecInfo: 1965. 对象。 在搜索函数无法找到给定编码格式的情
     况下，它应当返回 ‘None’。

     3.9 版更變: 连字符和空格会被转换为下划线。

          備註: 搜索函数的注册目前是不可逆的，这在某些情况下可能导致问题
          ，例如单元测试或模块重载等。

虽然内置的 *note open(): 16f. 和相关联的 *note io: a1. 模块是操作已编码
文本文件的推荐方式，但本模块也提供了额外的工具函数和类，允许在操作二进制
文件时使用更多各类的编解码器：

 -- 函式: codecs.open (filename, mode='r', encoding=None,
          errors='strict', buffering=-1)

     使用给定的 `mode' 打开已编码的文件并返回一个 *note
     StreamReaderWriter: 197b. 的实例，提供透明的编码/解码。 默认的文件
     模式为 ‘'r'’，表示以读取模式打开文件。

          備註: 下层的已编码文件总是以二进制模式打开。 在读取和写入时不
          会自动执行 ‘'\n'’ 的转换。 `mode' 参数可以是内置 *note open():
          16f. 函数所接受的任意二进制模式；‘'b'’ 会被自动添加。

     `encoding' 指定文件所要使用的编码格式。 允许任何编码为字节串或从字
     节串解码的编码格式，而文件方法所支持的数据类型则取决于所使用的编解
     码器。

     可以指定 `errors' 来定义错误处理方案。 默认值 ‘'strict'’ 表示在出现
     编码错误时引发 *note ValueError: 16d.。

     `buffering' 的含义与内置 *note open(): 16f. 函数中的相同。 默认值
     -1 表示将使用默认的缓冲区大小。

 -- 函式: codecs.EncodedFile (file, data_encoding, file_encoding=None,
          errors='strict')

     返回一个 *note StreamRecoder: 1108. 实例，它提供了 `file' 的透明转
     码包装版本。 当包装版本被关闭时原始文件也会被关闭。

     写入已包装文件的数据会根据给定的 `data_encoding' 解码，然后以使用
     `file_encoding' 的字节形式写入原始文件。 从原始文件读取的字节串将根
     据 `file_encoding' 解码，其结果将使用 `data_encoding' 进行编码。

     如果 `file_encoding' 未给定，则默认为 `data_encoding'。

     可以指定 `errors' 来定义错误处理方案。 默认值 ‘'strict'’ 表示在出现
     编码错误时引发 *note ValueError: 16d.。

 -- 函式: codecs.iterencode (iterator, encoding, errors='strict',
          **kwargs)

     使用增量式编码器通过迭代来编码由 `iterator' 所提供的输入。 此函数属
     于 *note generator: a83.。 `errors' 参数（以及任何其他关键字参数）
     会被传递给增量式编码器。

     此函数要求编解码器接受 *note str: 205. 对象形式的文本进行编码。 因
     此它不支持字节到字节的编码器，例如 ‘base64_codec’。

 -- 函式: codecs.iterdecode (iterator, encoding, errors='strict',
          **kwargs)

     使用增量式解码器通过迭代来解码由 `iterator' 所提供的输入。 此函数属
     于 *note generator: a83.。 `errors' 参数（以及任何其他关键字参数）
     会被传递给增量式解码器。

     此函数要求编解码器接受 *note bytes: 172. 对象进行解码。 因此它不支
     持文本到文本的编码器，例如 ‘rot_13’，但是 ‘rot_13’ 可以通过同样效果
     的 *note iterencode(): 197d. 来使用。

本模块还提供了以下常量，适用于读取和写入依赖于平台的文件：

 -- Data: codecs.BOM
 -- Data: codecs.BOM_BE
 -- Data: codecs.BOM_LE
 -- Data: codecs.BOM_UTF8
 -- Data: codecs.BOM_UTF16
 -- Data: codecs.BOM_UTF16_BE
 -- Data: codecs.BOM_UTF16_LE
 -- Data: codecs.BOM_UTF32
 -- Data: codecs.BOM_UTF32_BE
 -- Data: codecs.BOM_UTF32_LE

     这些常量定义了多种字节序列，即一些编码格式的 Unicode 字节顺序标记（
     BOM）。 它们在 UTF-16 和 UTF-32 数据流中被用以指明所使用的字节顺序
     ，并在 UTF-8 中被用作 Unicode 签名。 *note BOM_UTF16: 1983. 是
     *note BOM_UTF16_BE: 1984. 或 *note BOM_UTF16_LE: 1985.，具体取决于
     平台的本机字节顺序，*note BOM: 197f. 是 *note BOM_UTF16: 1983. 的别
     名, *note BOM_LE: 1981. 是 *note BOM_UTF16_LE: 1985. 的别名，*note
     BOM_BE: 1980. 是 *note BOM_UTF16_BE: 1984. 的别名。 其他序列则表示
     UTF-8 和 UTF-32 编码格式中的 BOM。

* 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编解码器

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/codecs.py


File: python.info,  Node: 编解码器基类,  Next: 编码格式与 Unicode,  Up: codecs --- 编解码器注册和相关基类

5.7.2.1 编解码器基类
....................

*note codecs: 1b. 模块定义了一系列基类用来定义配合编解码器对象进行工作的
接口，并且也可用作定制编解码器实现的基础。

每种编解码器必须定义四个接口以便用作 Python 中的编解码器：无状态编码器、
无状态解码器、流读取器和流写入器。 流读取器和写入器通常会重用无状态编码
器/解码器来实现文件协议。 编解码器作者还需要定义编解码器将如何处理编码和
解码错误。
* Menu:

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


File: python.info,  Node: 错误处理方案,  Next: 无状态的编码和解码,  Up: 编解码器基类

5.7.2.2 错误处理方案
....................

为了简化和标准化错误处理，编解码器可以通过接受 `errors' 字符串参数来实现
不同的错误处理方案。 所有标准的 Python 编解码器都定义并实现了以下字符串
值：

值                            含义
                              
----------------------------------------------------------------------------------
                              
‘'strict'’                    引发 *note UnicodeError: d03. (或其子类)；这是默
                              认的方案。 在 *note strict_errors(): 198c. 中实现
                              。
                              
                              
‘'ignore'’                    忽略错误格式的数据并且不加进一步通知就继续执行。
                              在 *note ignore_errors(): 198d. 中实现。
                              

以下错误处理方案仅适用于 *note 文本编码: 1731.:

值                            含义
                              
----------------------------------------------------------------------------------
                              
‘'replace'’                   使用适当的替换标记进行替换；Python 内置编解码器将
                              在解码时使用官方 ‘U+FFFD’ 替换字符，而在编码时使
                              用 ’?’ 。 在 *note replace_errors(): 198e. 中实现
                              。
                              
                              
‘'xmlcharrefreplace'’         使用适当的 XML 字符引用进行替换（仅在编码时）。 在
                              *note xmlcharrefreplace_errors(): 198f. 中实现。
                              
                              
‘'backslashreplace'’          使用带反斜杠的转义序列进行替换。 在
                              *note backslashreplace_errors(): 1990. 中实现。
                              
                              
‘'namereplace'’               使用 ‘\N{...}’ 转义序列进行替换（仅在编码时）。 在
                              *note namereplace_errors(): 1991. 中实现。
                              
                              
‘'surrogateescape'’           在解码时，将字节替换为 ‘U+DC80’ 至 ‘U+DCFF’ 范围
                              内的单个代理代码。 当在编码数据时使用
                              ‘'surrogateescape'’ 错误处理方案时，此代理将被转
                              换回相同的字节。 （请参阅 PEP 383(1) 了解详情。）
                              

此外，以下错误处理方案被专门用于指定的编解码器：

值                      编解码器                     含义
                                                     
-----------------------------------------------------------------------------------------------------
                                                     
‘'surrogatepass'’       utf-8, utf-16, utf-32,       允许编码和解码代理代码。 这些编解码器通常会将
                        utf-16-be, utf-16-le,        出现的代理代码视为错误。
                        utf-32-be, utf-32-le         
                        

3.1 版新加入: ‘'surrogateescape'’ 和 ‘'surrogatepass'’ 错误处理方案。

3.4 版更變: ‘'surrogatepass'’ 错误处理方案现在适用于 utf-16* 和 utf-32*
编解码器。

3.5 版新加入: ‘'namereplace'’ 错误处理方案。

3.5 版更變: ‘'backslashreplace'’ 错误处理方案现在适用于解码和转换。

允许的值集合可以通过注册新命名的错误处理方案来扩展：

 -- 函式: codecs.register_error (name, error_handler)

     在名称 `name' 之下注册错误处理函数 `error_handler'。 当 `name' 被指
     定为错误形参时，`error_handler' 参数所指定的对象将在编码和解码期间
     发生错误的情况下被调用，

     对于编码操作，将会调用 `error_handler' 并传入一个 *note
     UnicodeEncodeError: 32a. 实例，其中包含有关错误位置的信息。 错误处
     理程序必须引发此异常或别的异常，或者也可以返回一个元组，其中包含输
     入的不可编码部分的替换对象，以及应当继续进行编码的位置。 替换对象可
     以为 *note str: 205. 或 *note bytes: 172. 类型。 如果替换对象为字节
     串，编码器将简单地将其复制到输出缓冲区。 如果替换对象为字符串，编码
     器将对替换对象进行编码。 对原始输入的编码操作会在指定位置继续进行。
     负的位置值将被视为相对于输入字符串的末尾。 如果结果位置超出范围则将
     引发 *note IndexError: f36.。

     解码和转换的做法很相似，不同之处在于将把 *note UnicodeDecodeError:
     32b. 或 *note UnicodeTranslateError: 185b. 传给处理程序，并且来自错
     误处理程序的替换对象将被直接放入输出。

之前注册的错误处理方案（包括标准错误处理方案）可通过名称进行查找：

 -- 函式: codecs.lookup_error (name)

     返回之前在名称 `name' 之下注册的错误处理方案。

     在处理方案无法找到时将引发 *note LookupError: 1790.。

以下标准错误处理方案也可通过模块层级函数的方式来使用：

 -- 函式: codecs.strict_errors (exception)

     实现 ‘'strict'’ 错误处理方案：每个编码或解码错误都会引发 *note
     UnicodeError: d03.。

 -- 函式: codecs.replace_errors (exception)

     实现 ‘'replace'’ 错误处理方案 (仅用于 *note 文本编码: 1731.)：编码
     错误替换为 ‘'?'’ (并由编解码器编码)，解码错误替换为 ‘'\ufffd'’
     (Unicode 替换字符)。

 -- 函式: codecs.ignore_errors (exception)

     实现 ‘'ignore'’ 错误处理方案：忽略错误格式的数据并且不加进一步通知
     就继续执行。

 -- 函式: codecs.xmlcharrefreplace_errors (exception)

     实现 ‘'xmlcharrefreplace'’ 错误处理方案 (仅用于 *note 文本编码:
     1731. 的编码过程)：不可编码的字符将以适当的 XML 字符引用进行替换。

 -- 函式: codecs.backslashreplace_errors (exception)

     实现 ‘'backslashreplace'’ 错误处理方案 (仅用于 *note 文本编码:
     1731.)：错误格式的数据将以带反斜杠的转义序列进行替换。

 -- 函式: codecs.namereplace_errors (exception)

     实现 ‘'namereplace'’ 错误处理方案 (仅用于 *note 文本编码: 1731. 的
     编码过程)：不可编码的字符将以 ‘\N{...}’ 转义序列进行替换。

     3.5 版新加入.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0383


File: python.info,  Node: 无状态的编码和解码,  Next: 增量式的编码和解码,  Prev: 错误处理方案,  Up: 编解码器基类

5.7.2.3 无状态的编码和解码
..........................

基本 ‘Codec’ 类定义了这些方法，同时还定义了无状态编码器和解码器的函数接
口：

 -- 成員函式: Codec.encode (input[, errors])

     编码 `input' 对象并返回一个元组 (输出对象, 消耗长度)。 例如，*note
     text encoding: 1731. 会使用特定的字符集编码格式 (例如 ‘cp1252’ 或
     ‘iso-8859-1’) 将字符串转换为字节串对象。

     `errors' 参数定义了要应用的错误处理方案。 默认为 ‘'strict'’ 处理方
     案。

     此方法不一定会在 ‘Codec’ 实例中保存状态。 可使用必须保存状态的
     *note StreamWriter: 1972. 作为编解码器以便高效地进行编码。

     编码器必须能够处理零长度的输入并在此情况下返回输出对象类型的空对象
     。

 -- 成員函式: Codec.decode (input[, errors])

     解码 `input' 对象并返回一个元组 (输出对象, 消耗长度)。 例如，*note
     text encoding: 1731. 的解码操作会使用特定的字符集编码格式将字节串对
     象转换为字符串对象。

     对于文本编码格式和字节到字节编解码器，`input' 必须为一个字节串对象
     或提供了只读缓冲区接口的对象 – 例如，缓冲区对象和映射到内存的文件。

     `errors' 参数定义了要应用的错误处理方案。 默认为 ‘'strict'’ 处理方
     案。

     此方法不一定会在 ‘Codec’ 实例中保存状态。 可使用必须保存状态的
     *note StreamReader: 1973. 作为编解码器以便高效地进行解码。

     解码器必须能够处理零长度的输入并在此情况下返回输出对象类型的空对象
     。


File: python.info,  Node: 增量式的编码和解码,  Next: 流式的编码和解码,  Prev: 无状态的编码和解码,  Up: 编解码器基类

5.7.2.4 增量式的编码和解码
..........................

*note IncrementalEncoder: 196e. 和 *note IncrementalDecoder: 196f. 类提
供了增量式编码和解码的基本接口。 对输入的编码/解码不是通过对无状态编码器
/解码器的一次调用，而是通过对增量式编码器/解码器的 *note encode():
1994./*note decode(): 1995. 方法的多次调用。 增量式编码器/解码器会在方法
调用期间跟踪编码/解码过程。

调用 *note encode(): 1994./*note decode(): 1995. 方法后的全部输出相当于
将所有通过无状态编码器/解码器进行编码/解码的单个输入连接在一起所得到的输
出。

* Menu:

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


File: python.info,  Node: IncrementalEncoder 对象,  Next: IncrementalDecoder 对象,  Up: 增量式的编码和解码

5.7.2.5 IncrementalEncoder 对象
...............................

*note IncrementalEncoder: 196e. 类用来对一个输入进行分步编码。 它定义了
以下方法，每个增量式编码器都必须定义这些方法以便与 Python 编解码器注册表
相兼容。

 -- 類別: codecs.IncrementalEncoder (errors='strict')

     *note IncrementalEncoder: 196e. 实例的构造器。

     所有增量式编码器必须提供此构造器接口。 它们可以自由地添加额外的关键
     字参数，但只有在这里定义的参数才会被 Python 编解码器注册表所使用。

     *note IncrementalEncoder: 196e. 可以通过提供 `errors' 关键字参数来
     实现不同的错误处理方案。 可用的值请参阅 *note 错误处理方案: 1493.。

     `errors' 参数将被赋值给一个同名的属性。 通过对此属性赋值就可以在
     *note IncrementalEncoder: 196e. 对象的生命期内在不同的错误处理策略
     之间进行切换。

      -- 成員函式: encode (object[, final])

          编码 `object' (会将编码器的当前状态纳入考虑) 并返回已编码的结
          果对象。 如果这是对 *note encode(): 8ef. 的最终调用则 `final'
          必须为真值（默认为假值）。

      -- 成員函式: reset ()

          将编码器重置为初始状态。 输出将被丢弃：调用 ‘.encode(object,
          final=True)’，在必要时传入一个空字节串或字符串，重置编码器并得
          到输出。

      -- 成員函式: getstate ()

          返回编码器的当前状态，该值必须为一个整数。 实现应当确保 ‘0’ 是
          最常见的状态。 （比整数更复杂的状态表示可以通过编组/选择状态并
          将结果字符串的字节数据编码为整数来转换为一个整数值）。

      -- 成員函式: setstate (state)

          将编码器的状态设为 `state'。 `state' 必须为 *note getstate():
          1999. 所返回的一个编码器状态。


File: python.info,  Node: IncrementalDecoder 对象,  Prev: IncrementalEncoder 对象,  Up: 增量式的编码和解码

5.7.2.6 IncrementalDecoder 对象
...............................

*note IncrementalDecoder: 196f. 类用来对一个输入进行分步解码。 它定义了
以下方法，每个增量式解码器都必须定义这些方法以便与 Python 编解码器注册表
相兼容。

 -- 類別: codecs.IncrementalDecoder (errors='strict')

     *note IncrementalDecoder: 196f. 实例的构造器。

     所有增量式解码器必须提供此构造器接口。 它们可以自由地添加额外的关键
     字参数，但只有在这里定义的参数才会被 Python 编解码器注册表所使用。

     *note IncrementalDecoder: 196f. 可以通过提供 `errors' 关键字参数来
     实现不同的错误处理方案。 可用的值请参阅 *note 错误处理方案: 1493.。

     `errors' 参数将被赋值给一个同名的属性。 通过对此属性赋值就可以在
     *note IncrementalDecoder: 196f. 对象的生命期内在不同的错误处理策略
     之间进行切换。

      -- 成員函式: decode (object[, final])

          解码 `object' (会将解码器的当前状态纳入考虑) 并返回已解码的结
          果对象。 如果这是对 *note decode(): 8f0. 的最终调用则 `final'
          必须为真值（默认为假值）。 如果 `final' 为真值则解码器必须对输
          入进行完全解码并且必须 刷新所有缓冲区。 如果这无法做到（例如由
          于在输入结束时字节串序列不完整）则它必须像在无状态的情况下那样
          初始化错误处理（这可能引发一个异常）。

      -- 成員函式: reset ()

          将解码器重置为初始状态。

      -- 成員函式: getstate ()

          返回解码器的当前状态。 这必须为一个二元组，第一项必须是包含尚
          未解码的输入的缓冲区。 第二项必须为一个整数，可以表示附加状态
          信息。 （实现应当确保 ‘0’ 是最常见的附加状态信息。） 如果此附
          加状态信息为 ‘0’ 则必须可以将解码器设为没有已缓冲输入并且以
          ‘0’ 作为附加状态信息，以便将先前已缓冲的输入馈送到解码器使其返
          回到先前的状态而不产生任何输出。 （比整数更复杂的附加状态信息
          可以通过编组/选择状态信息并将结果字符串的字节数据编码为整数来
          转换为一个整数值。）

      -- 成員函式: setstate (state)

          将解码器的状态设为 `state'。 `state' 必须为 *note getstate():
          199e. 所返回的一个解码器状态。


File: python.info,  Node: 流式的编码和解码,  Prev: 增量式的编码和解码,  Up: 编解码器基类

5.7.2.7 流式的编码和解码
........................

*note StreamWriter: 1972. 和 *note StreamReader: 1973. 类提供了一些泛用
工作接口，可被用来非常方便地实现新的编码格式子模块。 请参阅
‘encodings.utf_8’ 中的示例了解如何做到这一点。

* Menu:

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


File: python.info,  Node: StreamWriter 对象,  Next: StreamReader 对象,  Up: 流式的编码和解码

5.7.2.8 StreamWriter 对象
.........................

*note StreamWriter: 1972. 类是 ‘Codec’ 的子类，它定义了以下方法，每个流
式写入器都必须定义这些方法以便与 Python 编解码器注册表相兼容。

 -- 類別: codecs.StreamWriter (stream, errors='strict')

     *note StreamWriter: 1972. 实例的构造器。

     所有流式写入器必须提供此构造器接口。 它们可以自由地添加额外的关键字
     参数，但只有在这里定义的参数才会被 Python 编解码器注册表所使用。

     `stream' 参数必须为一个基于特定编解码器打开用于写入文本或二进制数据
     的文件类对象。

     *note StreamWriter: 1972. 可以通过提供 `errors' 关键字参数来实现不
     同的错误处理方案。 请参阅 *note 错误处理方案: 1493. 了解下层的流式
     编解码器可支持的标准错误处理方案。

     `errors' 参数将被赋值给一个同名的属性。 通过对此属性赋值就可以在
     *note StreamWriter: 1972. 对象的生命期内在不同的错误处理策略之间进
     行切换。

      -- 成員函式: write (object)

          将编码后的对象内容写入到流。

      -- 成員函式: writelines (list)

          将拼接后的字符串列表写入到流（可能通过重用 *note write():
          19a3. 方法）。 标准的字节到字节编解码器不支持此方法。

      -- 成員函式: reset ()

          重置用于保持内部状态的编解码器缓冲区。

          调用此方法应当确保在干净的状态下放入输出数据，以允许直接添加新
          的干净数据而无须重新扫描整个流来恢复状态。

除了上述的方法，*note StreamWriter: 1972. 还必须继承来自下层流的所有其他
方法和属性。


File: python.info,  Node: StreamReader 对象,  Next: StreamReaderWriter 对象,  Prev: StreamWriter 对象,  Up: 流式的编码和解码

5.7.2.9 StreamReader 对象
.........................

*note StreamReader: 1973. 类是 ‘Codec’ 的子类，它定义了以下方法，每个流
式读取器都必须定义这些方法以便与 Python 编解码器注册表相兼容。

 -- 類別: codecs.StreamReader (stream, errors='strict')

     *note StreamReader: 1973. 实例的构造器。

     所有流式读取器必须提供此构造器接口。 它们可以自由地添加额外的关键字
     参数，但只有在这里定义的参数才会被 Python 编解码器注册表所使用。

     `stream' 参数必须为一个基于特定编解码器打开用于读取文本或二进制数据
     的文件类对象。

     *note StreamReader: 1973. 可以通过提供 `errors' 关键字参数来实现不
     同的错误处理方案。 请参阅 *note 错误处理方案: 1493. 了解下层的流式
     编解码器可支持的标准错误处理方案。

     `errors' 参数将被赋值给一个同名的属性。 通过对此属性赋值就可以在
     *note StreamReader: 1973. 对象的生命期内在不同的错误处理策略之间进
     行切换。

     `errors' 参数所允许的值集合可以使用 *note register_error(): eb9. 来
     扩展。

      -- 成員函式: read ([size[, chars[, firstline]]])

          解码来自流的数据并返回结果对象。

          `chars' 参数指明要返回的解码后码位或字节数量。 *note read():
          19a8. 方法绝不会返回超出请求数量的数据，但如果可用数量不足，它
          可能返回少于请求数量的数据。

          `size' 参数指明要读取并解码的已编码字节或码位的最大数量近似值
          。 解码器可以适当地修改此设置。 默认值 -1 表示尽可能多地读取并
          解码。 此形参的目的是防止一次性解码过于巨大的文件。

          `firstline' 旗标指明如果在后续行发生解码错误，则仅返回第一行就
          足够了。

          此方法应当使用“贪婪”读取策略，这意味着它应当在编码格式定义和给
          定大小所允许的情况下尽可能多地读取数据，例如，如果在流上存在可
          选的编码结束或状态标记，这些内容也应当被读取。

      -- 成員函式: readline ([size[, keepends]])

          从输入流读取一行并返回解码后的数据。

          如果给定了 `size'，则将其作为 size 参数传递给流的 *note
          read(): 19a8. 方法。

          如果 `keepends' 为假值，则行结束符将从返回的行中去除。

      -- 成員函式: readlines ([sizehint[, keepends]])

          从输入流读取所有行并将其作为一个行列表返回。

          行结束符会使用编解码器的 *note decode(): 8f0. 方法来实现，并且
          如果 `keepends' 为真值则会将其包含在列表条目中。

          如果给定了 `sizehint'，则将其作为 `size' 参数传递给流的 *note
          read(): 19a8. 方法。

      -- 成員函式: reset ()

          重置用于保持内部状态的编解码器缓冲区。

          请注意不应当对流进行重定位。 使用此方法的主要目的是为了能够从
          解码错误中恢复。

除了上述的方法，*note StreamReader: 1973. 还必须继承来自下层流的所有其他
方法和属性。


File: python.info,  Node: StreamReaderWriter 对象,  Next: StreamRecoder 对象,  Prev: StreamReader 对象,  Up: 流式的编码和解码

5.7.2.10 StreamReaderWriter 对象
................................

*note StreamReaderWriter: 197b. 是一个方便的类，允许对同时工作于读取和写
入模式的流进行包装。

其设计使得开发者可以使用 *note lookup(): 238. 函数所返回的工厂函数来构造
实例。

 -- 類別: codecs.StreamReaderWriter (stream, Reader, Writer,
          errors='strict')

     创建一个 *note StreamReaderWriter: 197b. 实例。 `stream' 必须为一个
     文件类对象。 `Reader' 和 `Writer' 必须为分别提供了 *note
     StreamReader: 1973. 和 *note StreamWriter: 1972. 接口的工厂函数或类
     。 错误处理通过与流式读取器和写入器所定义的相同方式来完成。

*note StreamReaderWriter: 197b. 实例定义了 *note StreamReader: 1973. 和
*note StreamWriter: 1972. 类的组合接口。 它们还继承了来自下层流的所有其
他方法和属性。


File: python.info,  Node: StreamRecoder 对象,  Prev: StreamReaderWriter 对象,  Up: 流式的编码和解码

5.7.2.11 StreamRecoder 对象
...........................

*note StreamRecoder: 1108. 将数据从一种编码格式转换为另一种，这对于处理
不同编码环境的情况有时会很有用。

其设计使得开发者可以使用 *note lookup(): 238. 函数所返回的工厂函数来构造
实例。

 -- 類別: codecs.StreamRecoder (stream, encode, decode, Reader, Writer,
          errors='strict')

     创建一个实现了双向转换的 *note StreamRecoder: 1108. 实例: `encode'
     和 `decode' 工作于前端 — 对代码可见的数据调用 ‘read()’ 和
     ‘write()’，而 `Reader' 和 `Writer' 工作于后端 — `stream' 中的数据。

     你可以使用这些对象来进行透明转码，例如从 Latin-1 转为 UTF-8 以及反
     向转换。

     `stream' 参数必须为一个文件类对象。

     `encode' 和 `decode' 参数必须遵循 ‘Codec’ 接口。 `Reader' 和
     `Writer' 必须为分别提供了 *note StreamReader: 1973. 和 *note
     StreamWriter: 1972. 接口对象的工厂函数或类。

     错误处理通过与流式读取器和写入器所定义的相同方式来完成。

*note StreamRecoder: 1108. 实例定义了 *note StreamReader: 1973. 和 *note
StreamWriter: 1972. 类的组合接口。 它们还继承了来自下层流的所有其他方法
和属性。


File: python.info,  Node: 编码格式与 Unicode,  Next: 标准编码,  Prev: 编解码器基类,  Up: codecs --- 编解码器注册和相关基类

5.7.2.12 编码格式与 Unicode
...........................

字符串在系统内部存储为 ‘0x0’–‘0x10FFFF’ 范围内的码位序列。 （请参阅 PEP
393(1) 了解有关实现的详情。） 一旦字符串对象要在 CPU 和内存以外使用，字
节的大小端顺序和字节数组的存储方式就成为一个关键问题。 如同使用其他编解
码器一样，将字符串序列化为字节序列被称为 `编码'，而从字节序列重建字符串
被称为 `解码'。 存在许多不同的文本序列化编解码器，它们被统称为 *note
文本编码: 1731.。

最简单的文本编码格式 (称为 ‘'latin-1'’ 或 ‘'iso-8859-1'’) 将码位 0–255 映
射为字节值 ‘0x0’–‘0xff’，这意味着包含 ‘U+00FF’ 以上码位的字符串对象无法
使用此编解码器进行编码。 这样做将引发 *note UnicodeEncodeError: 32a.，其
形式类似下面这样（不过详细的错误信息可能会有所不同）:
‘UnicodeEncodeError: 'latin-1' codec can't encode character '\u1234' in
position 3: ordinal not in range(256)’。

还有另外一组编码格式（所谓的字符映射编码）会选择全部 Unicode 码位的不同
子集并设定如何将这些码位映射为字节值 ‘0x0’–‘0xff’。 要查看这是如何实现的
，只需简单地打开相应源码例如 ‘encodings/cp1252.py’ (这是一个主要在
Windows 上使用的编码格式)。 其中会有一个包含 256 个字符的字符串常量，指
明每个字符所映射的字节值。

所有这些编码格式只能对 Unicode 所定义的 1114112 个码位中的 256 个进行编
码。 一种能够存储每个 Unicode 码位的简单而直接的办法就是将每个码位存储为
四个连续的字节。 存在两种不同的可能性：以大端序存储或以小端序存储。 这两
种编码格式分别被称为 ‘UTF-32-BE’ 和 ‘UTF-32-LE’。 它们的缺点可以举例说明
：如果你在一台小端序的机器上使用 ‘UTF-32-BE’ 则你将必须在编码和解码时翻
转字节。 ‘UTF-32’ 避免了这个问题：字节的排列将总是使用自然顺序。 当这些
字节被具有不同字节顺序的 CPU 读取时，则必须进行字节翻转。 为了能够检测
‘UTF-16’ 或 ‘UTF-32’ 字节序列的大小端序，可以使用所谓的 BOM ("字节顺序标
记")。 这对应于 Unicode 字符 ‘U+FEFF’。 此字符可添加到每个 ‘UTF-16’ 或
‘UTF-32’ 字节序列的开头。 此字符的字节翻转版本 (‘0xFFFE’) 是一个不可出现
于 Unicode 文本中的非法字符。 因此当发现一个 ‘UTF-16’ 或 ‘UTF-32’ 字节序
列的首个字符是 ‘U+FFFE’ 时，就必须在解码时进行字节翻转。 不幸的是字符
‘U+FEFF’ 还有第二个含义 ‘ZERO WIDTH NO-BREAK SPACE’: 即宽度为零并且不允
许用来拆分单词的字符。 它可以被用来为语言分析算法提供提示。 在 Unicode
4.0 中用 ‘U+FEFF’ 表示 ‘ZERO WIDTH NO-BREAK SPACE’ 已被弃用（改用
‘U+2060’ (‘WORD JOINER’) 负责此任务）。 然而 Unicode 软件仍然必须能够处
理 ‘U+FEFF’ 的两个含义：作为 BOM 它被用来确定已编码字节的存储布局，并在
字节序列被解码为字符串后将其去除；作为 ‘ZERO WIDTH NO-BREAK SPACE’ 它是
一个普通字符，将像其他字符一样被解码。

There’s another encoding that is able to encode the full range of
Unicode characters: UTF-8.  UTF-8 is an 8-bit encoding, which means
there are no issues with byte order in UTF-8.  Each byte in a UTF-8 byte
sequence consists of two parts: marker bits (the most significant bits)
and payload bits.  The marker bits are a sequence of zero to four ‘1’
bits followed by a ‘0’ bit.  Unicode characters are encoded like this
(with x being payload bits, which when concatenated give the Unicode
character):

范围                                    编码
                                        
-------------------------------------------------------------------------------------------
                                        
‘U-00000000’ ...  ‘U-0000007F’          0xxxxxxx
                                        
                                        
‘U-00000080’ ...  ‘U-000007FF’          110xxxxx 10xxxxxx
                                        
                                        
‘U-00000800’ ...  ‘U-0000FFFF’          1110xxxx 10xxxxxx 10xxxxxx
                                        
                                        
‘U-00010000’ ...  ‘U-0010FFFF’          11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
                                        

Unicode 字符最不重要的一个位就是最右侧的二进制位 x。

由于 UTF-8 是一种 8 位编码格式，因此 BOM 是不必要的，并且已编码字符串中
的任何 ‘U+FEFF’ 字符（即使是作为第一个字符）都会被视为是 ‘ZERO WIDTH
NO-BREAK SPACE’。

在没有外部信息的情况下，就不可能毫无疑义地确定一个字符串使用了何种编码格
式。 每种字符映射编码格式都可以解码任意的随机字节序列。 然而对 UTF-8 来
说这却是不可能的，因为 UTF-8 字节序列具有不允许任意字节序列的特别结构。
为了提升 UTF-8 编码检测的可靠性，Microsoft 发明了一种 UTF-8 变体形式
(Python 2.5 称之为 ‘"utf-8-sig"’) 专门用于其 Notepad 程序：在任何
Unicode 字符在被写入文件之前，会先写入一个 UTF-8 编码的 BOM (它看起来是
这样一个字节序列: ‘0xef’, ‘0xbb’, ‘0xbf’)。 由于任何字符映射编码后的文件
都不大可能以这些字节值开头（例如它们会映射为

          LATIN SMALL LETTER I WITH DIAERESIS 
          RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 
          INVERTED QUESTION MARK 

对于 iso-8859-1 编码格式来说），这提升了根据字节序列来正确猜测
‘utf-8-sig’ 编码格式的成功率。 所以在这里 BOM 的作用并不是帮助确定生成字
节序列所使用的字节顺序，而是作为帮助猜测编码格式的记号。 在进行编码时
utf-8-sig 编解码器将把 ‘0xef’, ‘0xbb’, ‘0xbf’ 作为头三个字节写入文件。 在
进行解码时 ‘utf-8-sig’ 将跳过这三个字节，如果它们作为文件的头三个字节出
现的话。 在 UTF-8 中并不推荐使用 BOM，通常应当避免它们的出现。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0393


File: python.info,  Node: 标准编码,  Next: Python 专属的编码格式,  Prev: 编码格式与 Unicode,  Up: codecs --- 编解码器注册和相关基类

5.7.2.13 标准编码
.................

Python 自带了许多内置的编解码器，它们的实现或者是通过 C 函数，或者是通过
映射表。 以下表格是按名称排序的编解码器列表，并提供了一些常见别名以及编
码格式通常针对的语言。 别名和语言列表都不是详尽无遗的。 请注意仅有大小写
区别或使用连字符替代下划线的拼写形式也都是有效的别名；因此，‘'utf-8'’ 是
‘'utf_8'’ 编解码器的有效别名。

`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 等）
以及给字符所分配的码位方面存在差异。 特别是对于欧洲语言来说，通常存在以
下几种变体：

   * 某个 ISO 8859 编码集

   * 某个 Microsoft Windows 编码页，通常是派生自某个 8859 编码集，但会用
     附加的图形字符来替换控制字符。

   * 某个 IBM EBCDIC 编码页

   * 某个 IBM PC 编码页，通常会兼容 ASCII

编码                  别名                                 语言
                                                           
------------------------------------------------------------------------------------------------
                                                           
ascii                 646, us-ascii                        英语
                                                           
                                                           
big5                  big5-tw, csbig5                      繁体中文
                                                           
                                                           
big5hkscs             big5-hkscs, hkscs                    繁体中文
                                                           
                                                           
cp037                 IBM037, IBM039                       英语
                                                           
                                                           
cp273                 273, IBM273, csIBM273                德语
                                                           
                                                           3.4 版新加入.
                                                           
                                                           
cp424                 EBCDIC-CP-HE, IBM424                 希伯来语
                                                           
                                                           
cp437                 437, IBM437                          英语
                                                           
                                                           
cp500                 EBCDIC-CP-BE, EBCDIC-CP-CH, IBM500   西欧
                                                           
                                                           
cp720                                                      阿拉伯语
                                                           
                                                           
cp737                                                      希腊语
                                                           
                                                           
cp775                 IBM775                               波罗的海语言
                                                           
                                                           
cp850                 850, IBM850                          西欧
                                                           
                                                           
cp852                 852, IBM852                          中欧和东欧
                                                           
                                                           
cp855                 855, IBM855                          保加利亚语，白俄罗斯语，马其顿语，
                                                           俄语，塞尔维亚语
                                                           
                                                           
cp856                                                      希伯来语
                                                           
                                                           
cp857                 857, IBM857                          土耳其语
                                                           
                                                           
cp858                 858, IBM858                          西欧
                                                           
                                                           
cp860                 860, IBM860                          葡萄牙语
                                                           
                                                           
cp861                 861, CP-IS, IBM861                   冰岛语
                                                           
                                                           
cp862                 862, IBM862                          希伯来语
                                                           
                                                           
cp863                 863, IBM863                          加拿大语
                                                           
                                                           
cp864                 IBM864                               阿拉伯语
                                                           
                                                           
cp865                 865, IBM865                          丹麦语/挪威语
                                                           
                                                           
cp866                 866, IBM866                          俄语
                                                           
                                                           
cp869                 869, CP-GR, IBM869                   希腊语
                                                           
                                                           
cp874                                                      泰语
                                                           
                                                           
cp875                                                      希腊语
                                                           
                                                           
cp932                 932, ms932, mskanji, ms-kanji        日语
                                                           
                                                           
cp949                 949, ms949, uhc                      韩语
                                                           
                                                           
cp950                 950, ms950                           繁体中文
                                                           
                                                           
cp1006                                                     乌尔都语
                                                           
                                                           
cp1026                ibm1026                              土耳其语
                                                           
                                                           
cp1125                1125, ibm1125, cp866u, ruscii        乌克兰语
                                                           
                                                           3.4 版新加入.
                                                           
                                                           
cp1140                ibm1140                              西欧
                                                           
                                                           
cp1250                windows-1250                         中欧和东欧
                                                           
                                                           
cp1251                windows-1251                         保加利亚语，白俄罗斯语，马其顿语，
                                                           俄语，塞尔维亚语
                                                           
                                                           
cp1252                windows-1252                         西欧
                                                           
                                                           
cp1253                windows-1253                         希腊语
                                                           
                                                           
cp1254                windows-1254                         土耳其语
                                                           
                                                           
cp1255                windows-1255                         希伯来语
                                                           
                                                           
cp1256                windows-1256                         阿拉伯语
                                                           
                                                           
cp1257                windows-1257                         波罗的海语言
                                                           
                                                           
cp1258                windows-1258                         越南语
                                                           
                                                           
euc_jp                eucjp, ujis, u-jis                   日语
                                                           
                                                           
euc_jis_2004          jisx0213, eucjis2004                 日语
                                                           
                                                           
euc_jisx0213          eucjisx0213                          日语
                                                           
                                                           
euc_kr                euckr, korean, ksc5601, ks_c-5601,   韩语
                      ks_c-5601-1987, ksx1001, ks_x-1001   
                      
                                                           
gb2312                chinese, csiso58gb231280, euc-cn,    简体中文
                      euccn, eucgb2312-cn, gb2312-1980,    
                      gb2312-80, iso-ir-58
                      
                                                           
gbk                   936, cp936, ms936                    统一汉语
                                                           
                                                           
gb18030               gb18030-2000                         统一汉语
                                                           
                                                           
hz                    hzgb, hz-gb, hz-gb-2312              简体中文
                                                           
                                                           
iso2022_jp            csiso2022jp, iso2022jp,              日语
                      iso-2022-jp                          
                      
                                                           
iso2022_jp_1          iso2022jp-1, iso-2022-jp-1           日语
                                                           
                                                           
iso2022_jp_2          iso2022jp-2, iso-2022-jp-2           日语，韩语，简体中文，西欧，希腊语
                                                           
                                                           
iso2022_jp_2004       iso2022jp-2004, iso-2022-jp-2004     日语
                                                           
                                                           
iso2022_jp_3          iso2022jp-3, iso-2022-jp-3           日语
                                                           
                                                           
iso2022_jp_ext        iso2022jp-ext, iso-2022-jp-ext       日语
                                                           
                                                           
iso2022_kr            csiso2022kr, iso2022kr,              韩语
                      iso-2022-kr                          
                      
                                                           
latin_1               iso-8859-1, iso8859-1, 8859,         西欧
                      cp819, latin, latin1, L1             
                      
                                                           
iso8859_2             iso-8859-2, latin2, L2               中欧和东欧
                                                           
                                                           
iso8859_3             iso-8859-3, latin3, L3               世界语，马耳他语
                                                           
                                                           
iso8859_4             iso-8859-4, latin4, L4               波罗的海语言
                                                           
                                                           
iso8859_5             iso-8859-5, cyrillic                 保加利亚语，白俄罗斯语，马其顿语，
                                                           俄语，塞尔维亚语
                                                           
                                                           
iso8859_6             iso-8859-6, arabic                   阿拉伯语
                                                           
                                                           
iso8859_7             iso-8859-7, greek, greek8            希腊语
                                                           
                                                           
iso8859_8             iso-8859-8, hebrew                   希伯来语
                                                           
                                                           
iso8859_9             iso-8859-9, latin5, L5               土耳其语
                                                           
                                                           
iso8859_10            iso-8859-10, latin6, L6              北欧语言
                                                           
                                                           
iso8859_11            iso-8859-11, thai                    泰语
                                                           
                                                           
iso8859_13            iso-8859-13, latin7, L7              波罗的海语言
                                                           
                                                           
iso8859_14            iso-8859-14, latin8, L8              凯尔特语
                                                           
                                                           
iso8859_15            iso-8859-15, latin9, L9              西欧
                                                           
                                                           
iso8859_16            iso-8859-16, latin10, L10            东南欧
                                                           
                                                           
johab                 cp1361, ms1361                       韩语
                                                           
                                                           
koi8_r                                                     俄语
                                                           
                                                           
koi8_t                                                     塔吉克
                                                           
                                                           3.5 版新加入.
                                                           
                                                           
koi8_u                                                     乌克兰语
                                                           
                                                           
kz1048                kz_1048, strk1048_2002, rk1048       哈萨克语
                                                           
                                                           3.5 版新加入.
                                                           
                                                           
mac_cyrillic          maccyrillic                          保加利亚语，白俄罗斯语，马其顿语，
                                                           俄语，塞尔维亚语
                                                           
                                                           
mac_greek             macgreek                             希腊语
                                                           
                                                           
mac_iceland           maciceland                           冰岛语
                                                           
                                                           
mac_latin2            maclatin2, maccentraleurope,         中欧和东欧
                      mac_centeuro                         
                      
                                                           
mac_roman             macroman, macintosh                  西欧
                                                           
                                                           
mac_turkish           macturkish                           土耳其语
                                                           
                                                           
ptcp154               csptcp154, pt154, cp154,             哈萨克语
                      cyrillic-asian                       
                      
                                                           
shift_jis             csshiftjis, shiftjis, sjis, s_jis    日语
                                                           
                                                           
shift_jis_2004        shiftjis2004, sjis_2004, sjis2004    日语
                                                           
                                                           
shift_jisx0213        shiftjisx0213, sjisx0213,            日语
                      s_jisx0213                           
                      
                                                           
utf_32                U32, utf32                           所有语言
                                                           
                                                           
utf_32_be             UTF-32BE                             所有语言
                                                           
                                                           
utf_32_le             UTF-32LE                             所有语言
                                                           
                                                           
utf_16                U16, utf16                           所有语言
                                                           
                                                           
utf_16_be             UTF-16BE                             所有语言
                                                           
                                                           
utf_16_le             UTF-16LE                             所有语言
                                                           
                                                           
utf_7                 U7, unicode-1-1-utf-7                所有语言
                                                           
                                                           
utf_8                 U8, UTF, utf8, cp65001               所有语言
                                                           
                                                           
utf_8_sig                                                  所有语言
                                                           

3.4 版更變: utf-16* 和 utf-32* 编码器将不再允许编码代理码位
(‘U+D800’–‘U+DFFF’)。 utf-32* 解码器将不再解码与代理码位相对应的字节序列
。

3.8 版更變: ‘cp65001’ 现在是 ‘utf_8’ 的一个别名。


File: python.info,  Node: Python 专属的编码格式,  Next: encodings idna --- 应用程序中的国际化域名,  Prev: 标准编码,  Up: codecs --- 编解码器注册和相关基类

5.7.2.14 Python 专属的编码格式
..............................

有一些预定义编解码器是 Python 专属的，因此它们在 Python 之外没有意义。 这
些编解码器按其所预期的输入和输出类型在下表中列出（请注意虽然文本编码是编
解码器最常见的使用场景，但下层的编解码器架构支持任意数据转换而不仅是文本
编码）。 对于非对称编解码器，该列描述的含义是编码方向。

* Menu:

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


File: python.info,  Node: 文字编码,  Next: 二进制转换,  Up: Python 专属的编码格式

5.7.2.15 文字编码
.................

以下编解码器提供了 *note str: 205. 到 *note bytes: 172. 的编码和 *note
bytes-like object: 6df. 到 *note str: 205. 的解码，类似于 Unicode 文本编
码。

编码                     别名          含义
                                       
-----------------------------------------------------------------------
                                       
idna                                   实现 RFC 3490(1)，另请参阅
                                       *note encodings.idna: 75. 。
                                       仅支持 ‘errors='strict'’ 。
                                       
                                       
mbcs                     ansi, dbcs    Windows 专属：根据 ANSI 代码
                                       页（CP_ACP）对操作数进行编码
                                       。
                                       
                                       
oem                                    Windows 专属：根据 OEM 代码页
                                       （CP_OEMCP）对操作数进行编码
                                       。
                                       
                                       3.6 版新加入.
                                       
                                       
palmos                                 PalmOS 3.5 的编码格式
                                       
                                       
punycode                               实现 RFC 3492(2)。 不支持有状
                                       态编解码器。
                                       
                                       
raw_unicode_escape                     Latin-1 编码格式附带对其他码
                                       位以 ‘\uXXXX’ 和 ‘\UXXXXXXXX’
                                       进行编码。 现有反斜杠不会以任
                                       何方式转义。 它被用于 Python
                                       的 pickle 协议。
                                       
                                       
undefined                              所有转换都将引发异常，甚至对
                                       空字符串也不例外。 错误处理方
                                       案会被忽略。
                                       
                                       
unicode_escape                         适合用于以 ASCII 编码的
                                       Python 源代码中的 Unicode 字
                                       面值内容的编码格式，但引号不
                                       会被转义。 对 Latin-1 源代码
                                       进行解码。 请注意 Python 源代
                                       码实际上默认使用 UTF-8。
                                       

3.8 版更變: "unicode_internal" 编解码器已被移除。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc3490.html

   (2) https://tools.ietf.org/html/rfc3492.html


File: python.info,  Node: 二进制转换,  Next: 文字转换,  Prev: 文字编码,  Up: Python 专属的编码格式

5.7.2.16 二进制转换
...................

以下编解码器提供了二进制转换: *note bytes-like object: 6df. 到 *note
bytes: 172. 的映射。 它们不被 *note bytes.decode(): 171. 所支持（该方法
只生成 *note str: 205. 类型的输出）。

编码                       别名                   含义                               编码器/解码器
                                                                                     
------------------------------------------------------------------------------------------------------------------------
                                                                                     
base64_codec (1)           base64, base_64        将操作数转换为多行 MIME base64     *note base64.encodebytes(): 222.
                                                  (结果总是包含一个末尾的 ‘'\n'’)    /
                                                                                     *note base64.decodebytes(): 223.
                                                  3.4 版更變: 接受任意               
                                                  *note bytes-like object: 6df. 作
                                                  为输入用于编码和解码
                                                  
                                                                                     
bz2_codec                  bz2                    使用bz2压缩操作数                  *note bz2.compress(): 19b6. /
                                                                                     *note bz2.decompress(): ab6.
                                                                                     
                                                                                     
hex_codec                  hex                    将操作数转换为十六进制表示，每个   *note binascii.b2a_hex(): 19b7.
                                                  字节有两位数                       /
                                                                                     *note binascii.a2b_hex(): 19b8.
                                                                                     
                                                                                     
quopri_codec               quopri,                将操作数转换为 MIME 带引号的可打   *note quopri.encode(): 19b9. 且
                           quotedprintable,       印数据                             ‘quotetabs=True’ /
                           quoted_printable                                          *note quopri.decode(): 19ba.
                                                                                     
                                                                                     
uu_codec                   uu                     使用uuencode转换操作数             *note uu.encode(): 513. /
                                                                                     *note uu.decode(): 19bb.
                                                                                     
                                                                                     
zlib_codec                 zip, zlib              使用gzip压缩操作数                 *note zlib.compress(): 6b5. /
                                                                                     *note zlib.decompress(): 6b6.
                                                                                     

3.2 版新加入: 恢复二进制转换。

3.4 版更變: 恢复二进制转换的别名。

   ---------- Footnotes ----------

   (1) (1) 除了 *note 字节类对象: 6df.，‘'base64_codec'’ 也接受仅包含
ASCII 的 *note str: 205. 实例用于解码


File: python.info,  Node: 文字转换,  Prev: 二进制转换,  Up: Python 专属的编码格式

5.7.2.17 文字转换
.................

以下编解码器提供了文本转换: *note str: 205. 到 *note str: 205. 的映射。
它不被 *note str.encode(): 170. 所支持（该方法只生成 *note bytes: 172. 类
型的输出）。

编码                     别名          含义
                                       
-----------------------------------------------------------------------
                                       
rot_13                   rot13         返回操作数的凯撒密码加密结果
                                       

3.2 版新加入: 恢复 ‘rot_13’ 文本转换。

3.4 版更變: 恢复 ‘rot13’ 别名。


File: python.info,  Node: encodings idna --- 应用程序中的国际化域名,  Next: encodings mbcs --- Windows ANSI代码页,  Prev: Python 专属的编码格式,  Up: codecs --- 编解码器注册和相关基类

5.7.2.18 ‘encodings.idna’ — 应用程序中的国际化域名
..................................................

此模块实现了 RFC 3490(1) (应用程序中的国际化域名) 和 RFC 3492(2)
(Nameprep: 用于国际化域名 (IDN) 的 Stringprep 配置文件)。 它是在
‘punycode’ 编码格式和 *note stringprep: f7. 的基础上构建的。

如果你需要来自 RFC 5891(3) 和 RFC 5895(4) 的 IDNA 2008 标准，请使用第三
方 ‘idna 模块 <https://pypi.org/project/idna/>_’。

这些 RFC 共同定义了一个在域名中支持非 ASCII 字符的协议。 一个包含非
ASCII 字符的域名 (例如 ‘www.Alliancefrançaise.nu’) 会被转换为兼容 ASCII
的编码格式 (简称 ACE，例如 ‘www.xn--alliancefranaise-npb.nu’)。 随后此域
名的 ACE 形式可以用于所有由于特定协议而不允许使用任意字符的场合，例如
DNS 查询，HTTP ‘Host’ 字段等等。 此转换是在应用中进行的；如有可能将对用
户可见：应用应当透明地将 Unicode 域名标签转换为线上的 IDNA，并在 ACE 标
签被呈现给用户之前将其转换回 Unicode。

Python 以多种方式支持这种转换: ‘idna’ 编解码器执行 Unicode 和 ACE 之间的
转换，基于在 section 3.1 of RFC 3490(5) 中定义的分隔字符将输入字符串拆分
为标签，再根据需要将每个标签转换为 ACE，相反地又会基于 ‘.’ 分隔符将输入
字节串拆分为标签，再将找到的任何 ACE 标签转换为 Unicode。 此外，*note
socket: ef. 模块可透明地将 Unicode 主机名转换为 ACE，以便应用在将它们传
给 socket 模块时无须自行转换主机名。 除此之外，许多包含以主机名作为函数
参数的模块例如 *note http.client: 93. 和 *note ftplib: 82. 都接受
Unicode 主机名（并且 *note http.client: 93. 也会在 ‘Host’ 字段中透明地发
送 IDNA 主机名，如果它需要发送该字段的话）。

当从线路接收主机名时（例如反向名称查找），到 Unicode 的转换不会自动被执
行：希望向用户提供此种主机名的应用应当将它们解码为 Unicode。

*note encodings.idna: 75. 模块还实现了 nameprep 过程，该过程会对主机名执
行特定的规范化操作，以实现国际域名的大小写不敏感特性与合并相似的字符。 如
果有需要可以直接使用 nameprep 函数。

 -- 函式: encodings.idna.nameprep (label)

     返回 `label' 经过名称处理操作的版本。 该实现目前基于查询字符串，因
     此 ‘AllowUnassigned’ 为真值。

 -- 函式: encodings.idna.ToASCII (label)

     将标签转换为 ASCII，规则定义见 RFC 3490(6)。 ‘UseSTD3ASCIIRules’ 预
     设为假值。

 -- 函式: encodings.idna.ToUnicode (label)

     将标签转换为 Unicode，规则定义见 RFC 3490(7)。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc3490.html

   (2) https://tools.ietf.org/html/rfc3492.html

   (3) https://tools.ietf.org/html/rfc5891.html

   (4) https://tools.ietf.org/html/rfc5895.html

   (5) https://tools.ietf.org/html/rfc3490.html#section-3.1

   (6) https://tools.ietf.org/html/rfc3490.html

   (7) https://tools.ietf.org/html/rfc3490.html


File: python.info,  Node: encodings mbcs --- Windows ANSI代码页,  Next: encodings utf_8_sig --- 带BOM签名的UTF-8编解码器,  Prev: encodings idna --- 应用程序中的国际化域名,  Up: codecs --- 编解码器注册和相关基类

5.7.2.19 ‘encodings.mbcs’ — Windows ANSI代码页
..............................................

此模块实现ANSI代码页（CP_ACP）。

*note Availability: 1491.: 仅Windows可用

3.3 版更變: 支持任何错误处理

3.2 版更變: 在 3.2 版之前， `errors' 参数会被忽略；总是会使用
‘'replace'’ 进行编码，并使用 ‘'ignore'’ 进行解码。


File: python.info,  Node: encodings utf_8_sig --- 带BOM签名的UTF-8编解码器,  Prev: encodings mbcs --- Windows ANSI代码页,  Up: codecs --- 编解码器注册和相关基类

5.7.2.20 ‘encodings.utf_8_sig’ — 带BOM签名的UTF-8编解码器
.........................................................

此模块实现了 UTF-8 编解码器的一个变种：在编码时将把 UTF-8 已编码 BOM 添
加到 UTF-8 编码字节数据的开头。 对于有状态编码器此操作只执行一次（当首次
写入字节流时）。 在解码时将跳过数据开头作为可选项的 UTF-8 已编码 BOM。


File: python.info,  Node: 数据类型,  Next: 數值與數學模組,  Prev: 二进制数据服务,  Up: Python 標準函式庫 Standard Library

5.8 数据类型
============

本章所描述的模块提供了许多专门的数据类型，如日期和时间、固定类型的数组、
堆队列、双端队列、以及枚举。

Python也提供一些内置数据类型，特别是，*note dict: 164.、 *note list:
1f8.、*note set: 1f6.、*note frozenset: 1f7.、以及 *note tuple: 1a2.。
*note str: 205. 这个类是用来存储Unicode字符串的，而 *note bytes: 172. 和
*note bytearray: 173. 这两个类是用来存储二进制数据的。

本章包含以下模块的文档：

* Menu:

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


File: python.info,  Node: datetime --- 基本日期和时间类型,  Next: zoneinfo --- IANA 时区支持,  Up: 数据类型

5.8.1 ‘datetime’ — 基本日期和时间类型
-------------------------------------

`源代码：' Lib/datetime.py(1)

__________________________________________________________________

*note datetime: 30. 模块提供用于处理日期和时间的类。

在支持日期时间数学运算的同时，实现的关注点更着重于如何能够更有效地解析其
属性用于格式化输出和数据操作。

也參考
......

模块 *note calendar: 14.

     通用日历相关函数

模块 *note time: 10c.

     时间的访问和转换

Module *note zoneinfo: 14e.

     Concrete time zones representing the IANA time zone database.

dateutil(2) 包

     具有扩展时区和解析支持的第三方库。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/datetime.py

   (2) https://dateutil.readthedocs.io/en/stable/


File: python.info,  Node: 感知型对象和简单型对象,  Next: 常量,  Up: datetime --- 基本日期和时间类型

5.8.1.1 感知型对象和简单型对象
..............................

日期和时间对象可以根据它们是否包含时区信息而分为“感知型”和“简单型”两类。

充分掌握应用性算法和政治性时间调整信息例如时区和夏令时的情况下，一个 `感
知型' 对象就能相对于其他感知型对象来精确定位自身时间点。 感知型对象是用
来表示一个没有解释空间的固定时间点。 (1)

`简单型' 对象没有包含足够多的信息来无歧义地相对于其他 date/time 对象来定
位自身时间点。 不论一个简单型对象所代表的是世界标准时间（UTC）、当地时间
还是某个其他时区的时间完全取决于具体程序，就像一个特定数字所代表的是米、
英里还是质量完全取决于具体程序一样。 简单型对象更易于理解和使用，代价则
是忽略了某些现实性考量。

对于要求感知型对象的应用，*note datetime: 19f. 和 *note time: 5ec. 对象
具有一个可选的时区信息属性 ‘tzinfo’，它可被设为抽象类 *note tzinfo: 180.
的子类的一个实例。 这些 *note tzinfo: 180. 对象会捕获与 UTC 时间的差值、
时区名称以及夏令时是否生效等信息。

*note datetime: 30. 模块只提供了一个具体的 *note tzinfo: 180. 类，即
*note timezone: ae0. 类。 *note timezone: ae0. 类可以表示具有相对于 UTC
的固定时差的简单时区，例如 UTC 本身或北美的 EST 和 EDT 时区等。 支持时间
的详细程度取决于具体的应用。 世界各地的时间调整规则往往是政治性多于合理
性，经常会发生变化，除了 UTC 之外并没有一个能适合所有应用的标准。

   ---------- Footnotes ----------

   (1) (1) 就是说如果我们忽略相对论效应的话。


File: python.info,  Node: 常量,  Next: 有效的类型,  Prev: 感知型对象和简单型对象,  Up: datetime --- 基本日期和时间类型

5.8.1.2 常量
............

The *note datetime: 30. module exports the following constants:

 -- Data: datetime.MINYEAR

     *note date: 19d. 或者 *note datetime: 19f. 对象允许的最小年份。 常
     量 *note MINYEAR: 19cb. 是 ‘1’ 。

 -- Data: datetime.MAXYEAR

     *note date: 19d. 或 *note datetime: 19f. 对象允许最大的年份。常量
     *note MAXYEAR: 19cc. 是 ‘9999’ 。


File: python.info,  Node: 有效的类型,  Next: timedelta 类对象,  Prev: 常量,  Up: datetime --- 基本日期和时间类型

5.8.1.3 有效的类型
..................

 -- 類別: datetime.date

     一个理想化的简单型日期，它假设当今的公历在过去和未来永远有效。 属性
     : *note year: 19ce, *note month: 19cf, and *note day: 19d0.。

 -- 類別: datetime.time

     一个独立于任何特定日期的理想化时间，它假设每一天都恰好等于 24*60*60
     秒。 （这里没有“闰秒”的概念。） 包含属性: *note hour: 19d1, *note
     minute: 19d2, *note second: 19d3, *note microsecond: 19d4. 和 *note
     tzinfo: 19d5.。

 -- 類別: datetime.datetime

     日期和时间的结合。属性：*note year: 19d6, *note month: 19d7, *note
     day: 19d8, *note hour: 19d9, *note minute: 19da, *note second:
     19db, *note microsecond: 19dc, and *note tzinfo: 19dd.

 -- 類別: datetime.timedelta

     表示两个 *note date: 19d. 对象或者 *note time: 5ec. 对象,或者 *note
     datetime: 19f. 对象之间的时间间隔，精确到微秒。

 -- 類別: datetime.tzinfo

     一个描述时区信息对象的抽象基类。 用来给 *note datetime: 19f. 和
     *note time: 5ec. 类提供自定义的时间调整概念（例如处理时区和/或夏令
     时）。

 -- 類別: datetime.timezone

     一个实现了 *note tzinfo: 180. 抽象基类的子类，用于表示相对于 世界标
     准时间（UTC）的偏移量。

     3.2 版新加入.

这些类型的对象都是不可变的。

子类关系

     object
         timedelta
         tzinfo
             timezone
         time
         date
             datetime

* Menu:

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


File: python.info,  Node: 通用的特征属性,  Next: 确定一个对象是感知型还是简单型,  Up: 有效的类型

5.8.1.4 通用的特征属性
......................

*note date: 19d, *note datetime: 19f, *note time: 5ec. 和 *note
timezone: ae0. 类型共享这些通用特性:

   - 这些类型的对象都是不可变的。

   - 这些类型的对象是可哈希的，这意味着它们可被作为字典的键。

   - 这些类型的对象支持通过 *note pickle: ca. 模块进行高效的封存。


File: python.info,  Node: 确定一个对象是感知型还是简单型,  Prev: 通用的特征属性,  Up: 有效的类型

5.8.1.5 确定一个对象是感知型还是简单型
......................................

*note date: 19d. 类型的对象都是简单型的。

*note time: 5ec. 或 *note datetime: 19f. 类型的对象可以是感知型或者简单
型。

一个 *note datetime: 19f. 对象 `d' 在以下条件同时成立时将是感知型的：

  1. ‘d.tzinfo’ 不为 ‘None’

  2. ‘d.tzinfo.utcoffset(d)’ 不返回 ‘None’

在其他情况下，`d' 将是简单型的。

一个 *note time: 5ec. 对象 `t' 在以下条件同时成立时将是感知型的：

  1. ‘t.tzinfo’ 不为 ‘None’

  2. ‘t.tzinfo.utcoffset(None)’ 不返回 ‘None’。

在其他情况下，`t' 将是简单型的。

感知型和简单型之间的区别不适用于 *note timedelta: 2ca. 对象。


File: python.info,  Node: timedelta 类对象,  Next: date 对象,  Prev: 有效的类型,  Up: datetime --- 基本日期和时间类型

5.8.1.6 ‘timedelta’ 类对象
..........................

*note timedelta: 2ca. 对象表示两个 date 或者 time 的时间间隔。

 -- 類別: datetime.timedelta (days=0, seconds=0, microseconds=0,
          milliseconds=0, minutes=0, hours=0, weeks=0)

     所有参数都是可选的并且默认为 ‘0’。 这些参数可以是整数或者浮点数，也
     可以是正数或者负数。

     只有 `days', `seconds' 和 `microseconds' 会存储在内部。 参数单位的
     换算规则如下：

        * 1毫秒会转换成1000微秒。

        * 1分钟会转换成60秒。

        * 1小时会转换成3600秒。

        * 1星期会转换成7天。

     并且 days, seconds, microseconds 会经标准化处理以保证表达方式的唯一
     性，即：

        * ‘0 <= microseconds < 1000000’

        * ‘0 <= seconds < 3600*24’ (一天的秒数)

        * ‘-999999999 <= days <= 999999999’

     下面的例子演示了如何对 `days', `seconds' 和 `microseconds' 以外的任
     意参数执行“合并”操作并标准化为以上三个结果属性:

          >>> 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)

     在有任何参数为浮点型并且 microseconds 值为小数的情况下，从所有参数
     中余下的微秒数将被合并，并使用四舍五入偶不入奇的规则将总计值舍入到
     最接近的整数微秒值。 如果没有任何参数为浮点型的情况下，则转换和标准
     化过程将是完全精确的（不会丢失信息）。

     如果标准化后的 days 数值超过了指定范围，将会抛出 *note
     OverflowError: a41. 异常。

     请注意对负数值进行标准化的结果可能会令人感到惊讶。 例如:

          >>> from datetime import timedelta
          >>> d = timedelta(microseconds=-1)
          >>> (d.days, d.seconds, d.microseconds)
          (-1, 86399, 999999)

类属性：

 -- 屬性: timedelta.min

     The most negative *note timedelta: 2ca. object,
     ‘timedelta(-999999999)’.

 -- 屬性: timedelta.max

     The most positive *note timedelta: 2ca. object,
     ‘timedelta(days=999999999, hours=23, minutes=59, seconds=59,
     microseconds=999999)’.

 -- 屬性: timedelta.resolution

     两个不相等的 *note timedelta: 2ca. 类对象最小的间隔为
     ‘timedelta(microseconds=1)’。

需要注意的是，因为标准化的缘故，‘timedelta.max’ > ‘-timedelta.min’，
‘-timedelta.max’ 不可以表示一个 *note timedelta: 2ca. 类对象。

实例属性（只读）：

属性                   值
                       
------------------------------------------------------------------------
                       
‘days’                 -999999999 至 999999999 ，含999999999
                       
                       
‘seconds’              0 至 86399，包含86399
                       
                       
‘microseconds’         0 至 999999，包含999999
                       

支持的运算：

运算                                 结果
                                     
-----------------------------------------------------------------------------------------
                                     
‘t1 = t2 + t3’                       `t2' 和 `t3' 的和。 运算后 `t1'-`t2' == `t3' and
                                     `t1'-`t3' == `t2' 必为真值。(1)
                                     
                                     
‘t1 = t2 - t3’                       `t2' 减 `t3' 的差。 运算后 `t1' == `t2' - `t3'
                                     and `t2' == `t1' + `t3' 必为真值。 (1)(6)
                                     
                                     
‘t1 = t2 * i or t1 = i * t2’         乘以一个整数。运算后假如 ‘i != 0’ 则 `t1' // i ==
                                     `t2' 必为真值。
                                     
                                     
                                     In general, `t1' * i == `t1' * (i-1) + `t1' is
                                     true.  (1)
                                     
                                     
‘t1 = t2 * f or t1 = f * t2’         乘以一个浮点数，结果会被舍入到 timedelta 最接近的
                                     整数倍。 精度使用四舍五偶入奇不入规则。
                                     
                                     
‘f = t2 / t3’                        总时间 `t2' 除以间隔单位 `t3' (3)。 返回一个
                                     *note float: 1fd. 对象。
                                     
                                     
‘t1 = t2 / f or t1 = t2 / i’         除以一个浮点数或整数。 结果会被舍入到 timedelta 最
                                     接近的整数倍。 精度使用四舍五偶入奇不入规则。
                                     
                                     
‘t1 = t2 // i’ or ‘t1 = t2 // t3’    计算底数，其余部分（如果有）将被丢弃。在第二种情
                                     况下，将返回整数。 （3）
                                     
                                     
‘t1 = t2 % t3’                       余数为一个 *note timedelta: 2ca. 对象。(3)
                                     
                                     
‘q, r = divmod(t1, t2)’              通过 : ‘q = t1 // t2’ (3) and ‘r = t1 % t2’ 计算
                                     出商和余数。q是一个整数，r是一个
                                     *note timedelta: 2ca. 对象。
                                     
                                     
‘+t1’                                返回一个相同数值的 *note timedelta: 2ca. 对象。
                                     
                                     
‘-t1’                                等价于 *note timedelta: 2ca.(-`t1.days',
                                     -`t1.seconds', -`t1.microseconds'), 和 `t1'* -1.
                                     (1)(4)
                                     
                                     
‘abs(t)’                             当 ‘t.days >= 0``时等于 +\ *t*, 当 ``t.days < 0’
                                     时 -`t' 。 (2)
                                     
                                     
‘str(t)’                             返回一个形如 ‘[D day[s], ][H]H:MM:SS[.UUUUUU]’ 的
                                     字符串，当 ‘t’ 为负数的时候， D 也为负数。 (5)
                                     
                                     
‘repr(t)’                            返回一个 *note timedelta: 2ca. 对象的字符串表示形
                                     式，作为附带正规属性值的构造器调用。
                                     

註解：

  1. 结果正确，但可能会溢出。

  2. 结果正确，不会溢出。

  3. 除以0将会抛出异常 *note ZeroDivisionError: 1fa. 。

  4. -`timedelta.max' 不是一个 *note timedelta: 2ca. 类对象。

  5. *note timedelta: 2ca. 对象的字符串表示形式类似于其内部表示形式被规
     范化。对于负时间增量，这会导致一些不寻常的结果。例如:

          >>> timedelta(hours=-5)
          datetime.timedelta(days=-1, seconds=68400)
          >>> print(_)
          -1 day, 19:00:00

  6. 表达式 ‘t2 - t3’ 通常与 ‘t2 + (-t3)’ 是等价的，除非 t3 等于
     ‘timedelta.max’; 在这种情况下前者会返回结果，而后者则会溢出。

除了上面列举的操作以外，*note timedelta: 2ca. 对象还支持与 *note date:
19d. 和 *note datetime: 19f. 对象进行特定的相加和相减运算（见下文）。

3.2 版更變: 现在已支持 *note timedelta: 2ca. 对象与另一个 *note
timedelta: 2ca. 对象相整除或相除，包括求余运算和 *note divmod(): 28d. 函
数。 现在也支持 *note timedelta: 2ca. 对象加上或乘以一个 *note float:
1fd. 对象。

支持 *note timedelta: 2ca. 对象之间进行比较，但其中有一些注意事项。

‘==’ 或 ‘!=’ 比较 `总是' 返回一个 *note bool: 2bd. 对象，无论被比较的对
象是什么类型:

     >>> from datetime import timedelta
     >>> delta1 = timedelta(seconds=57)
     >>> delta2 = timedelta(hours=25, seconds=2)
     >>> delta2 != delta1
     True
     >>> delta2 == 5
     False

对于所有其他比较 (例如 ‘<’ 和 ‘>’)，当一个 *note timedelta: 2ca. 对象与
其他类型的对象比较时，将引发 *note TypeError: 1fe.:

     >>> 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'

在布尔运算中，*note timedelta: 2ca. 对象当且仅当其不等于 ‘timedelta(0)’
时则会被视为真值。

实例方法：

 -- 成員函式: timedelta.total_seconds ()

     返回时间间隔包含了多少秒。造价于 ‘td / timedelta(seconds=1)’。对于
     其它单位可以直接使用除法的形式 (例如 ‘td /
     timedelta(microseconds=1)’)。

     需要注意的是，时间间隔较大时，这个方法的结果中的微秒将会失真（大多
     数平台上大于270年视为一个较大的时间间隔）。

     3.2 版新加入.

* Menu:

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


File: python.info,  Node: class timedelta 用法示例,  Up: timedelta 类对象

5.8.1.7 class:‘timedelta’ 用法示例
..................................

一个标准化的附加示例:

     >>> # 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

*note timedelta: 2ca. 算术运算的示例:

     >>> 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)


File: python.info,  Node: date 对象,  Next: datetime 对象,  Prev: timedelta 类对象,  Up: datetime --- 基本日期和时间类型

5.8.1.8 ‘date’ 对象
...................

*note date: 19d. 对象代表一个理想化历法中的日期（年、月和日），即当今的
格列高利历向前后两个方向无限延伸。

公元 1 年 1 月 1日是第 1 日，公元 1 年 1 月 2 日是第 2 日，依此类推。
(1)

 -- 類別: datetime.date (year, month, day)

     所有参数都是必要的。 参数必须是在下面范围内的整数：

        * ‘MINYEAR <= year <= MAXYEAR’

        * ‘1 <= month <= 12’

        * ‘1 <= 日期 <= 给定年月对应的天数’

     如果参数不在这些范围内，则抛出 *note ValueError: 16d. 异常。

其它构造器，所有的类方法：

 -- 成員函式: classmethod date.today ()

     返回当前的本地日期。

     这等价于 ‘date.fromtimestamp(time.time())’。

 -- 成員函式: classmethod date.fromtimestamp (timestamp)

     返回对应于 POSIX 时间戳的当地时间，例如 *note time.time(): 42d. 返
     回的就是时间戳。

     这可能引发 *note OverflowError: a41.，如果时间戳数值超出所在平台 C
     ‘localtime()’ 函数的支持范围的话，并且会在 ‘localtime()’ 出错时引发
     *note OSError: 304.。 通常该数值会被限制在 1970 年至 2038 年之间。
     请注意在时间戳概念包含闰秒的非 POSIX 系统上，闰秒会被 *note
     fromtimestamp(): 19e9. 所忽略。

     3.3 版更變: 引发 *note OverflowError: a41. 而不是 *note ValueError:
     16d.，如果时间戳数值超出所在平台 C ‘localtime()’ 函数的支持范围的话
     ，并会在 ‘localtime()’ 出错时引发 *note OSError: 304. 而不是 *note
     ValueError: 16d.。

 -- 成員函式: classmethod date.fromordinal (ordinal)

     返回对应于预期格列高利历序号的日期，其中公元 1 年 1 月 1 晶的序号为
     1。

     除非 ‘1 <= ordinal <= date.max.toordinal()’ 否则会引发 *note
     ValueError: 16d.。对于任意日期 `d'，
     ‘date.fromordinal(d.toordinal()) == d’。

 -- 成員函式: classmethod date.fromisoformat (date_string)

     返回一个对应于以 ‘YYYY-MM-DD’ 格式给出的 `date_string' 的 *note
     date: 19d. 对象:

          >>> from datetime import date
          >>> date.fromisoformat('2019-12-04')
          datetime.date(2019, 12, 4)

     这是 *note date.isoformat(): 19eb. 的逆操作。 它只支持 ‘YYYY-MM-DD’
     格式。

     3.7 版新加入.

 -- 成員函式: classmethod date.fromisocalendar (year, week, day)

     返回指定 year, week 和 day 所对应 ISO 历法日期的 *note date: 19d.。
     这是函数 *note date.isocalendar(): 19e. 的逆操作。

     3.8 版新加入.

类属性：

 -- 屬性: date.min

     最小的日期 ‘date(MINYEAR, 1, 1)’ 。

 -- 屬性: date.max

     最大的日期 ，‘date(MAXYEAR, 12, 31)’。

 -- 屬性: date.resolution

     两个日期对象的最小间隔，‘timedelta(days=1)’。

实例属性（只读）：

 -- 屬性: date.year

     在 *note MINYEAR: 19cb. 和 *note MAXYEAR: 19cc. 之间，包含边界。

 -- 屬性: date.month

     1 至 12（含）

 -- 屬性: date.day

     返回1到指定年月的天数间的数字。

支持的运算：

运算                                结果
                                    
---------------------------------------------------------------------------------------
                                    
‘date2 = date1 + timedelta’         `date2' 等于从 `date1' 减去 ‘timedelta.days’ 天
                                    。 (1)
                                    
                                    
‘date2 = date1 - timedelta’         计算 `date2' 的值使得 ‘date2 + timedelta ==
                                    date1’。 (2)
                                    
                                    
‘timedelta = date1 - date2’         (3)
                                    
                                    
‘date1 < date2’                     如果 `date1' 的时间在 `date2' 之前则认为 `date1'
                                    小于 `date2' 。 (4)
                                    

註解：

  1. 如果 ‘timedelta.days > 0’ 则 `date2' 将在时间线上前进，如果
     ‘timedelta.days < 0’ 则将后退。 操作完成后 ‘date2 - date1 ==
     timedelta.days’。 ‘timedelta.seconds’ 和 ‘timedelta.microseconds’ 会
     被忽略。 如果 ‘date2.year’ 将小于 *note MINYEAR: 19cb. 或大于 *note
     MAXYEAR: 19cc. 则会引发 *note OverflowError: a41.。

  2. ‘timedelta.seconds’ 和 ‘timedelta.microseconds’ 会被忽略。

  3. 此值完全精确且不会溢出。 操作完成后 timedelta.seconds 和
     timedelta.microseconds 均为 0，并且 date2 + timedelta == date1。

  4. 换句话说，当且仅当 ‘date1.toordinal() < date2.toordinal()’ 时
     ‘date1 < date2’。 日期比较会引发 *note TypeError: 1fe.，如果比较目
     标不为 *note date: 19d. 对象的话。 不过也可能会返回
     ‘NotImplemented’，如果比较目标具有 ‘timetuple()’ 属性的话。 这个钩
     子给予其他日期对象类型实现混合类型比较的机会。 否则，当 *note date:
     19d. 对象与不同类型的对象比较时将会引发 *note TypeError: 1fe.，除非
     是 ‘==’ 或 ‘!=’ 比较。 后两种情况将分别返回 *note False: 48e. 或
     *note True: 593.。

在布尔运算中，所有 *note date: 19d. 对象都会被视为真值。

实例方法：

 -- 成員函式: date.replace (year=self.year, month=self.month,
          day=self.day)

     返回一个具有同样值的日期，除非通过任何关键字参数给出了某些形参的新
     值。

     示例:

          >>> from datetime import date
          >>> d = date(2002, 12, 31)
          >>> d.replace(day=26)
          datetime.date(2002, 12, 26)

 -- 成員函式: date.timetuple ()

     返回一个 *note time.struct_time: 690.，即 *note time.localtime():
     1080. 所返回的类型。

     hours, minutes 和 seconds 值均为 0，且 DST 旗标值为 -1。

     ‘d.timetuple()’ 等价于:

          time.struct_time((d.year, d.month, d.day, 0, 0, 0, d.weekday(), yday, -1))

     其中 ‘yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1’ 是
     当前年份中的日期序号，1 月 1 日的序号为 ‘1’。

 -- 成員函式: date.toordinal ()

     返回日期的预期格列高利历序号，其中公元 1 年 1 月 1 日的序号为 1。 对
     于任意 *note date: 19d. 对象 `d'，‘date.fromordinal(d.toordinal())
     == d’。

 -- 成員函式: date.weekday ()

     返回一个整数代表星期几，星期一为0，星期天为6。例如， ‘date(2002,
     12, 4).weekday() == 2’，表示的是星期三。参阅 *note isoweekday():
     19f3.。

 -- 成員函式: date.isoweekday ()

     返回一个整数代表星期几，星期一为1，星期天为7。例如：‘date(2002, 12,
     4).isoweekday() == 3’,表示星期三。参见 *note weekday(): 19f2, *note
     isocalendar(): 19e.。

 -- 成員函式: date.isocalendar ()

     返回一个由三部分组成的 *note named tuple: b7b. 对象: ‘year’, ‘week’
     和 ‘weekday’。

     ISO 历法是一种被广泛使用的格列高利历。 (2)

     ISO 年由 52 或 53 个完整星期构成，每个星期开始于星期一结束于星期日
     。 一个 ISO 年的第一个星期就是（格列高利）历法的一年中第一个包含星
     期四的星期。 这被称为 1 号星期，这个星期四所在的 ISO 年与其所在的格
     列高利年相同。

     例如，2004 年的第一天是星期四，因此 ISO 2004 年的第一个星期开始于
     2003 年 12 月 29 日星期一，结束于 2004 年 1 月 4 日星期日:

          >>> 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)

     3.9 版更變: 结果由元组改为 *note named tuple: b7b.。

 -- 成員函式: date.isoformat ()

     返回一个以 ISO 8601 格式 ‘YYYY-MM-DD’ 来表示日期的字符串:

          >>> from datetime import date
          >>> date(2002, 12, 4).isoformat()
          '2002-12-04'

     这是 *note date.fromisoformat(): 11cc. 的逆操作。

 -- 成員函式: date.__str__ ()

     对于日期对象 `d', ‘str(d)’ 等价于 ‘d.isoformat()’ 。

 -- 成員函式: date.ctime ()

     返回一个表示日期的字符串:

          >>> from datetime import date
          >>> date(2002, 12, 4).ctime()
          'Wed Dec  4 00:00:00 2002'

     ‘d.ctime()’ 等效于:

          time.ctime(time.mktime(d.timetuple()))

     在原生 C ‘ctime()’ 函数 (*note time.ctime(): 19f6. 会发起调用该函数
     ，但 *note date.ctime(): 19f5. 则不会) 遵循 C 标准的平台上。

 -- 成員函式: date.strftime (format)

     返回一个由显式格式字符串所指明的代表日期的字符串。 表示时、分或秒的
     格式代码值将为 0。 要获取格式指令的完整列表请参阅 *note strftime()
     和 strptime() 的行为: 19f7.。

 -- 成員函式: date.__format__ (format)

     与 *note date.strftime(): 631. 相同。 此方法使得为 *note date: 19d.
     对象指定以 *note 格式化字符串字面值: 296. 表示的格式化字符串以及使
     用 *note str.format(): 5d4. 进行格式化成为可能。 要获取格式指令的完
     整列表，请参阅 *note strftime() 和 strptime() 的行为: 19f7.。

* Menu:

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

   ---------- Footnotes ----------

   (1) (2) 这与 Dershowitz 和 Reingold 所著 `Calendrical Calculations' 中
“预期格列高利”历法的定义一致，它是适用于该书中所有运算的基础历法。 请参
阅该书了解在预期格利高利历序列与许多其他历法系统之间进行转换的算法。

   (2) (3) 请参阅 R. H. van Gent 所著 ‘ ISO 8601 历法的数学指导
<‘https://www.staff.science.uu.nl/~gent0113/calendar/isocalendar.htm’>‘_
以获取更完整的说明。


File: python.info,  Node: class date 用法示例,  Up: date 对象

5.8.1.9 class:‘date’ 用法示例
.............................

计算距离特定事件天数的例子:

     >>> 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

使用 *note date: 19d. 的更多例子：

     >>> 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)


File: python.info,  Node: datetime 对象,  Next: time 对象,  Prev: date 对象,  Up: datetime --- 基本日期和时间类型

5.8.1.10 ‘datetime’ 对象
........................

*note datetime: 19f. 对象是包含来自 *note date: 19d. 对象和 *note time:
5ec. 对象的所有信息的单一对象。

与 *note date: 19d. 对象一样，*note datetime: 19f. 假定当前的格列高利历
向前后两个方向无限延伸；与 *note time: 5ec. 对象一样，*note datetime:
19f. 假定每一天恰好有 3600*24 秒。

构造器 ：

 -- 類別: datetime.datetime (year, month, day, hour=0, minute=0,
          second=0, microsecond=0, tzinfo=None, *, fold=0)

     `year', `month' 和 `day' 参数是必须的。 `tzinfo' 可以是 ‘None’ 或者
     是一个 *note tzinfo: 180. 子类的实例。 其余的参数必须是在下面范围内
     的整数：

        * ‘MINYEAR <= year <= MAXYEAR’,

        * ‘1 <= month <= 12’,

        * ‘1 <= day <= 指定年月的天数’,

        * ‘0 <= hour < 24’,

        * ‘0 <= minute < 60’,

        * ‘0 <= second < 60’,

        * ‘0 <= microsecond < 1000000’,

        * ‘fold in [0, 1]’.

     如果参数不在这些范围内，则抛出 *note ValueError: 16d. 异常。

     3.6 版新加入: 增加了 ‘fold’ 参数。

其它构造器，所有的类方法：

 -- 成員函式: classmethod datetime.today ()

     返回表示当前地方时的 datetime 对象，其中 *note tzinfo: 19dd. 为
     ‘None’。

     等价于:

          datetime.fromtimestamp(time.time())

     另请参阅 *note now(): 113b, *note fromtimestamp(): 11c0.。

     此方法的功能等价于 *note now(): 113b.，但是不带 ‘tz’ 形参。

 -- 成員函式: classmethod datetime.now (tz=None)

     返回表示当前地方时的 date 和 time 对象。

     如果可选参数 `tz' 为 ‘None’ 或未指定，这就类似于 *note today():
     19fc.，但该方法会在可能的情况下提供比通过 *note time.time(): 42d. 时
     间戳所获时间值更高的精度（例如，在提供了 C ‘gettimeofday()’ 函数的
     平台上就可以做到这一点）。

     如果 `tz' 不为 ‘None’，它必须是 *note tzinfo: 180. 子类的一个实例，
     并且当前日期和时间将被转换到 `tz' 时区。

     此函数可以替代 *note today(): 19fc. 和 *note utcnow(): 19fd.。

 -- 成員函式: classmethod datetime.utcnow ()

     返回表示当前 UTC 时间的 date 和 time，其中 *note tzinfo: 19dd. 为
     ‘None’。

     这类似于 *note now(): 113b.，但返回的是当前 UTC 日期和时间，类型为
     简单型 *note datetime: 19f. 对象。 感知型的当前 UTC 日期时间可通过
     调用 ‘datetime.now(timezone.utc)’ 来获得。 另请参阅 *note now():
     113b.。

          警告: 由于简单型 ‘datetime’ 对象会被许多 ‘datetime’ 方法当作本
          地时间来处理，最好是使用感知型日期时间对象来表示 UTC 时间。 因
          此，创建表示当前 UTC 时间的对象的推荐方式是通过调用
          ‘datetime.now(timezone.utc)’。

 -- 成員函式: classmethod datetime.fromtimestamp (timestamp, tz=None)

     返回对应于 POSIX 时间戳例如 *note time.time(): 42d. 的返回值的本地
     日期和时间。 如果可选参数 `tz' 为 ‘None’ 或未指定，时间戳会被转换为
     所在平台的本地日期和时间，返回的 *note datetime: 19f. 对象将为天真
     型。

     如果 `tz' 不为 ‘None’，它必须是 *note tzinfo: 180. 子类的一个实例，
     并且时间戳将被转换到 `tz' 指定的时区。

     *note fromtimestamp(): 11c0. 可能会引发 *note OverflowError: a41.，
     如果时间戳数值超出所在平台 C ‘localtime()’ 或 ‘gmtime()’ 函数的支持
     范围的话，并会在 ‘localtime()’ 或 ‘gmtime()’ 报错时引发 *note
     OSError: 304.。 通常该数值会被限制在 1970 年至 2038 年之间。 请注意
     在时间戳概念包含闰秒的非 POSIX 系统上，闰秒会被 *note
     fromtimestamp(): 11c0. 所忽略，结果可能导致两个相差一秒的时间戳产生
     相同的 *note datetime: 19f. 对象。 相比 *note utcfromtimestamp():
     19fe. 更推荐使用此方法。

     3.3 版更變: 引发 *note OverflowError: a41. 而不是 *note ValueError:
     16d.，如果时间戳数值超出所在平台 C ‘localtime()’ 或 ‘gmtime()’ 函数
     的支持范围的话。 并会在 ‘localtime()’ 或 ‘gmtime()’ 出错时引发
     *note OSError: 304. 而不是 *note ValueError: 16d.。

     3.6 版更變: *note fromtimestamp(): 11c0. 可能返回 *note fold: 5ed.
     值设为 1 的实例。

 -- 成員函式: classmethod datetime.utcfromtimestamp (timestamp)

     返回对应于 POSIX 时间戳的 UTC *note datetime: 19f.，其中 *note
     tzinfo: 19dd. 值为 ‘None’。 （结果为简单型对象。）

     这可能引发 *note OverflowError: a41.，如果时间戳数值超出所在平台 C
     ‘gmtime()’ 函数的支持范围的话，并会在 ‘gmtime()’ 报错时引发 *note
     OSError: 304.。 通常该数值会被限制在 1970 至 2038 年之间。

     要得到一个感知型 *note datetime: 19f. 对象，应调用 *note
     fromtimestamp(): 11c0.:

          datetime.fromtimestamp(timestamp, timezone.utc)

     在 POSIX 兼容的平台上，它等价于以下表达式:

          datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=timestamp)

     不同之处在于后一种形式总是支持完整年份范围：从 *note MINYEAR: 19cb.
     到 *note MAXYEAR: 19cc. 的开区间。

          警告: 由于简单型 ‘datetime’ 对象会被许多 ‘datetime’ 方法当作本
          地时间来处理，最好是使用感知型日期时间对象来表示 UTC 时间。 因
          此，创建表示特定 UTC 时间戳的日期时间对象的推荐方式是通过调用
          ‘datetime.fromtimestamp(timestamp, tz=timezone.utc)’。

     3.3 版更變: 引发 *note OverflowError: a41. 而不是 *note ValueError:
     16d.，如果时间戳数值超出所在平台 C ‘gmtime()’ 函数的支持范围的话。
     并会在 ‘gmtime()’ 出错时引发 *note OSError: 304. 而不是 *note
     ValueError: 16d.。

 -- 成員函式: classmethod datetime.fromordinal (ordinal)

     返回对应于预期格列高利历序号的 *note datetime: 19f.，其中公元 1 年
     1 月 1 日的序号为 1。 除非 ‘1 <= ordinal <=
     datetime.max.toordinal()’ 否则会引发 *note ValueError: 16d.。 结果
     的 hour, minute, second 和 microsecond 值均为 0，并且 *note tzinfo:
     19dd. 值为 ‘None’。

 -- 成員函式: classmethod datetime.combine (date, time,
          tzinfo=self.tzinfo)

     返回一个新的 *note datetime: 19f. 对象，对象的日期部分等于给定的
     *note date: 19d. 对象的值，而其时间部分等于给定的 *note time: 5ec.
     对象的值。 如果提供了 `tzinfo' 参数，其值会被用来设置结果的 *note
     tzinfo: 19dd. 属性，否则将使用 `time' 参数的 *note tzinfo: 19d5. 属
     性。

     对于任意 *note datetime: 19f. 对象 `d'，‘d ==
     datetime.combine(d.date(), d.time(), d.tzinfo)’。 如果 date 是一个
     *note datetime: 19f. 对象，它的时间部分和 *note tzinfo: 19dd. 属性
     会被忽略。

     3.6 版更變: 增加了 `tzinfo' 参数。

 -- 成員函式: classmethod datetime.fromisoformat (date_string)

     返回一个对应于 *note date.isoformat(): 19eb. 和 *note
     datetime.isoformat(): 632. 所提供的某一种 `date_string' 的 *note
     datetime: 19f. 对象。

     特别地，此函数支持以下格式的字符串：

          YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]]

     其中 ‘*’ 可以匹配任意的单个字符。

          警示: 此函数 `并不' 支持解析任意 ISO 8601 字符串 —— 它的目的只
          是作为 *note datetime.isoformat(): 632. 的逆操作。 在第三方包
          dateutil(1) 中提供了一个更完善的 ISO 8601 解析器
          ‘dateutil.parser.isoparse’。

     示例:

          >>> 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)))

     3.7 版新加入.

 -- 成員函式: classmethod datetime.fromisocalendar (year, week, day)

     返回以 year, week 和 day 值指明的 ISO 历法日期所对应的 *note
     datetime: 19f.。 该datetime 对象的非日期部分将使用其标准默认值来填
     充。 这是函数 *note datetime.isocalendar(): 1a0. 的逆操作。

     3.8 版新加入.

 -- 成員函式: classmethod datetime.strptime (date_string, format)

     返回一个对应于 `date_string'，根据 `format' 进行解析得到的 *note
     datetime: 19f. 对象。

     这相当于:

          datetime(*(time.strptime(date_string, format)[0:6]))

     如果 date_string 和 format 无法被 *note time.strptime(): e56. 解析
     或它返回一个不是时间元组的值，则将引发 *note ValueError: 16d.。 要
     获取格式化指令的完整列表，请参阅 *note strftime() 和 strptime()
     的行为: 19f7.。

类属性：

 -- 屬性: datetime.min

     最早的可表示 *note datetime: 19f.，‘datetime(MINYEAR, 1, 1,
     tzinfo=None)’。

 -- 屬性: datetime.max

     最晚的可表示 *note datetime: 19f.，‘datetime(MAXYEAR, 12, 31, 23,
     59, 59, 999999, tzinfo=None)’。

 -- 屬性: datetime.resolution

     两个不相等的 *note datetime: 19f. 对象之间可能的最小间隔，
     ‘timedelta(microseconds=1)’。

实例属性（只读）：

 -- 屬性: datetime.year

     在 *note MINYEAR: 19cb. 和 *note MAXYEAR: 19cc. 之间，包含边界。

 -- 屬性: datetime.month

     1 至 12（含）

 -- 屬性: datetime.day

     返回1到指定年月的天数间的数字。

 -- 屬性: datetime.hour

     取值范围是 ‘range(24)’。

 -- 屬性: datetime.minute

     取值范围是 ‘range(60)’。

 -- 屬性: datetime.second

     取值范围是 ‘range(60)’。

 -- 屬性: datetime.microsecond

     取值范围是 ‘range(1000000)’。

 -- 屬性: datetime.tzinfo

     作为 `tzinfo' 参数被传给 *note datetime: 19f. 构造器的对象，如果没
     有传入值则为 ‘None’。

 -- 屬性: datetime.fold

     取值范围是 ‘[0, 1]’。 用于在重复的时间段中消除边界时间歧义。 （当夏
     令时结束时回拨时钟或由于政治原因导致当明时区的 UTC 时差减少就会出现
     重复的时间段。） 取值 0 (1) 表示两个时刻早于（晚于）所代表的同一边
     界时间。

     3.6 版新加入.

支持的运算：

运算                                        结果
                                            
---------------------------------------------------------------------------------
                                            
‘datetime2 = datetime1 + timedelta’         (1)
                                            
                                            
‘datetime2 = datetime1 - timedelta’         (2)
                                            
                                            
‘timedelta = datetime1 - datetime2’         (3)
                                            
                                            
‘datetime1 < datetime2’                     比较 *note datetime: 19f. 与
                                            *note datetime: 19f.。 (4)
                                            

  1. datetime2 是从 datetime1 去掉了一段 timedelta 的结果，如果
     ‘timedelta.days’ > 0 则是在时间线上前进，如果 ‘timedelta.days’ < 0
     则是在时间线上后退。 该结果具有与输入的 datetime 相同的 *note
     tzinfo: 19dd. 属性，并且操作完成后 datetime2 - datetime1 ==
     timedelta。 如果 datetime2.year 将要小于 *note MINYEAR: 19cb. 或大
     于 *note MAXYEAR: 19cc. 则会引发 *note OverflowError: a41.。 请注意
     即使输入的是一个感知型对象，该方法也不会进行时区调整。

  2. 计算 datetime2 使得 datetime2 + timedelta == datetime1。 与相加操作
     一样，结果具有与输入的 datetime 相同的 *note tzinfo: 19dd. 属性，即
     使输入的是一个感知型对象，该方法也不会进行时区调整。

  3. 从一个 *note datetime: 19f. 减去一个 *note datetime: 19f. 仅对两个
     操作数均为简单型或均为感知型时有定义。 如果一个是感知型而另一个是简
     单型，则会引发 *note TypeError: 1fe.。

     如果两个操作数都是简单型，或都是感知型并且具有相同的 *note tzinfo:
     19dd. 属性，则 *note tzinfo: 19dd. 属性会被忽略，并且结果会是一个使
     得 ‘datetime2 + t == datetime1’ 的 *note timedelta: 2ca. 对象 `t'。
     在此情况下不会进行时区调整。

     如果两个操作数都是感知型且具有不同的 *note tzinfo: 19dd. 属性，
     ‘a-b’ 操作的效果就如同 `a' 和 `b' 首先被转换为简单型 UTC 日期时间。
     结果将是 ‘(a.replace(tzinfo=None) - a.utcoffset()) -
     (b.replace(tzinfo=None) - b.utcoffset())’，除非具体实现绝对不溢出。

  4. 当 `datetime1' 的时间在 `datetime2' 之前则认为 `datetime1' 小于
     `datetime2'。

     如果比较的一方是简单型而另一方是感知型，则如果尝试进行顺序比较将引
     发 *note TypeError: 1fe.。 对于相等比较，简单型实例将永远不等于感知
     型实例。

     如果两个比较方都是感知型，且具有相同的 *note tzinfo: 19dd. 属性，则
     相同的 *note tzinfo: 19dd. 属性会被忽略并对基本日期时间值进行比较。
     如果两个比较方都是感知型且具有不同的 *note tzinfo: 19dd. 属性，则两
     个比较方将首先通过减去它们的 UTC 差值（使用 ‘self.utcoffset()’ 获取
     ）来进行调整。

     3.3 版更變: 感知型和简单型 *note datetime: 19f. 实例之间的相等比较
     不会引发 *note TypeError: 1fe.。

          備註: 为了防止比较操作回退为默认的对象地址比较方式，datetime 比
          较通常会引发 *note TypeError: 1fe.，如果比较目标不同样为 *note
          datetime: 19f. 对象的话。 不过也可能会返回 ‘NotImplemented’，
          如果比较目标具有 ‘timetuple()’ 属性的话。 这个钩子给予其他种类
          的日期对象实现混合类型比较的机会。 如果未实现，则当 *note
          datetime: 19f. 对象与不同类型比较时将会引发 *note TypeError:
          1fe.，除非是 ‘==’ 或 ‘!=’ 比较。 后两种情况将分别返回 *note
          False: 48e. 或 *note True: 593.。

实例方法：

 -- 成員函式: datetime.date ()

     返回具有同样 year, month 和 day 值的 *note date: 19d. 对象。

 -- 成員函式: datetime.time ()

     返回具有同样 hour, minute, second, microsecond 和 fold 值的 *note
     time: 5ec. 对象。 *note tzinfo: 19dd. 值为 ‘None’。 另请参见 *note
     timetz(): 1a05. 方法。

     3.6 版更變: fold 值会被复制给返回的 *note time: 5ec. 对象。

 -- 成員函式: datetime.timetz ()

     返回具有同样 hour, minute, second, microsecond, fold 和 tzinfo 属性
     性的 *note time: 5ec. 对象。 另请参见 *note time(): 10c. 方法。

     3.6 版更變: fold 值会被复制给返回的 *note time: 5ec. 对象。

 -- 成員函式: 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，除非通过任何关键字参数为某些属性
     指定了新值。 请注意可以通过指定 ‘tzinfo=None’ 来从一个感知型
     datetime 创建一个简单型 datetime 而不必转换日期和时间数据。

     3.6 版新加入: 增加了 ‘fold’ 参数。

 -- 成員函式: datetime.astimezone (tz=None)

     返回一个具有新的 *note tzinfo: 19dd. 属性 `tz' 的 *note datetime:
     19f. 对象，并会调整日期和时间数据使得结果对应的 UTC 时间与 `self' 相
     同，但为 `tz' 时区的本地时间。

     如果给出了 `tz'，则它必须是一个 *note tzinfo: 180. 子类的实例，并且
     其 *note utcoffset(): 1a07. 和 *note dst(): 1a08. 方法不可返回
     ‘None’。 如果 `self' 为简单型，它会被假定为基于系统时区表示的时间。

     如果调用时不传入参数 (或传入 ‘tz=None’) 则将假定目标时区为系统的本
     地时区。 转换后 datetime 实例的 ‘.tzinfo’ 属性将被设为一个 *note
     timezone: ae0. 实例，时区名称和时差值将从 OS 获取。

     如果 ‘self.tzinfo’ 为 `tz'，‘self.astimezone(tz)’ 等于 `self': 不会
     对日期或时间数据进行调整。 否则结果为 `tz' 时区的本地时间，代表的
     UTC 时间与 `self' 相同：在 ‘astz = dt.astimezone(tz)’ 之后，‘astz -
     astz.utcoffset()’ 将具有与 ‘dt - dt.utcoffset()’ 相同的日期和时间数
     据。

     如果你只是想要附加一个时区对象 `tz' 到一个 datetime 对象 `dt' 而不
     调整日期和时间数据，请使用 ‘dt.replace(tzinfo=tz)’。 如果你只想从一
     个感知型 datetime 对象 `dt' 移除时区对象，请使用
     ‘dt.replace(tzinfo=None)’。

     请注意默认的 *note tzinfo.fromutc(): 1a09. 方法在 *note tzinfo:
     180. 的子类中可以被重载，从而影响 *note astimezone(): 2cb. 的返回结
     果。 如果忽略出错的情况，*note astimezone(): 2cb. 的行为就类似于:

          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)

     3.3 版更變: `tz' 现在可以被省略。

     3.6 版更變: *note astimezone(): 2cb. 方法可以由简单型实例调用，这将
     假定其表示本地时间。

 -- 成員函式: datetime.utcoffset ()

     如果 *note tzinfo: 19dd. 为 ‘None’，则返回 ‘None’，否则返回
     ‘self.tzinfo.utcoffset(self)’，并且在后者不返回 ‘None’ 或者一个幅度
     小于一天的 *note timedelta: 2ca. 对象时将引发异常。

     3.7 版更變: UTC 时差不再限制为一个整数分钟值。

 -- 成員函式: datetime.dst ()

     如果 *note tzinfo: 19dd. 为 ‘None’，则返回 ‘None’，否则返回
     ‘self.tzinfo.dst(self)’，并且在后者不返回 ‘None’ 或者一个幅度小于一
     天的 *note timedelta: 2ca. 对象时将引发异常。

     3.7 版更變: DST 差值不再限制为一个整数分钟值。

 -- 成員函式: datetime.tzname ()

     如果 *note tzinfo: 19dd. 为 ‘None’，则返回 ‘None’，否则返回
     ‘self.tzinfo.tzname(self)’，如果后者不返回 ‘None’ 或者一个字符串对
     象则将引发异常。

 -- 成員函式: datetime.timetuple ()

     返回一个 *note time.struct_time: 690.，即 *note time.localtime():
     1080. 所返回的类型。

     ‘d.timetuple()’ 等价于:

          time.struct_time((d.year, d.month, d.day,
                            d.hour, d.minute, d.second,
                            d.weekday(), yday, dst))

     其中 ‘yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1’ 是
     日期在当前年份中的序号，起始序号 ‘1’ 表示 1 月 1 日。 结果的
     ‘tm_isdst’ 旗标的设定会依据 *note dst(): 1a08. 方法：如果 *note
     tzinfo: 19dd. 为 ‘None’ 或 *note dst(): 1a08. 返回 ‘None’，则
     ‘tm_isdst’ 将设为 ‘-1’；否则如果 *note dst(): 1a08. 返回一个非零值
     ，则 ‘tm_isdst’ 将设为 ‘1’；在其他情况下 ‘tm_isdst’ 将设为 ‘0’。

 -- 成員函式: datetime.utctimetuple ()

     如果 *note datetime: 19f. 实例 `d' 为简单型，这类似于
     ‘d.timetuple()’，不同之处在于 ‘tm_isdst’ 会强制设为 0，无论
     ‘d.dst()’ 返回什么结果。 DST 对于 UTC 时间永远无效。

     如果 `d' 为感知型， `d' 会通过减去 ‘d.utcoffset()’ 来标准化为 UTC 时
     间，并返回该标准化时间所对应的 *note time.struct_time: 690.。
     ‘tm_isdst’ 会强制设为 0。 请注意如果 `d'.year 为 ‘MINYEAR’ 或
     ‘MAXYEAR’ 并且 UTC 调整超出一年的边界则可能引发 *note
     OverflowError: a41.。

          警告: 由于简单型 ‘datetime’ 对象会被许多 ‘datetime’ 方法当作本
          地时间来处理，最好是使用感知型日期时间来表示 UTC 时间；因此，
          使用 ‘utcfromtimetuple’ 可能会给出误导性的结果。 如果你有一个
          表示 UTC 的简单型 ‘datetime’，请使用
          ‘datetime.replace(tzinfo=timezone.utc)’ 将其改为感知型，这样你
          才能使用 *note datetime.timetuple(): 1a0b.。

 -- 成員函式: datetime.toordinal ()

     返回日期的预期格列高利历序号。 与 ‘self.date().toordinal()’ 相同。

 -- 成員函式: datetime.timestamp ()

     返回对应于 *note datetime: 19f. 实例的 POSIX 时间戳。 此返回值是与
     *note time.time(): 42d. 返回值类似的 *note float: 1fd. 对象。

     简单型 *note datetime: 19f. 实例会假定为代表本地时间，并且此方法依
     赖于平台的 C ‘mktime()’ 函数来执行转换。 由于在许多平台上 *note
     datetime: 19f. 支持的范围比 ‘mktime()’ 更广，对于极其遥远的过去或未
     来此方法可能引发 *note OverflowError: a41.。

     对于感知型 *note datetime: 19f. 实例，返回值的计算方式为:

          (dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()

     3.3 版新加入.

     3.6 版更變: *note timestamp(): ac1. 方法使用 *note fold: 5ed. 属性
     来消除重复间隔中的时间歧义。

          備註: 没有一个方法能直接从表示 UTC 时间的简单型 *note
          datetime: 19f. 实例获取 POSIX 时间戳。 如果你的应用程序使用此
          惯例并且你的系统时区不是设为 UTC，你可以通过提供
          ‘tzinfo=timezone.utc’ 来获取 POSIX 时间戳:

               timestamp = dt.replace(tzinfo=timezone.utc).timestamp()

          或者通过直接计算时间戳:

               timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)

 -- 成員函式: datetime.weekday ()

     返回一个整数代表星期几，星期一为 0，星期天为 6。 相当于
     ‘self.date().weekday()’。 另请参阅 *note isoweekday(): 1a0f.。

 -- 成員函式: datetime.isoweekday ()

     返回一个整数代表星期几，星期一为 1，星期天为 7。 相当于
     ‘self.date().isoweekday()’。 另请参阅 *note weekday(): 1a0e, *note
     isocalendar(): 1a0.。

 -- 成員函式: datetime.isocalendar ()

     返回一个由三部分组成的 *note named tuple: b7b.: ‘year’, ‘week’ 和
     ‘weekday’。 等同于 ‘self.date().isocalendar()’。

 -- 成員函式: datetime.isoformat (sep='T', timespec='auto')

     返回一个以 ISO 8601 格式表示的日期和时间字符串：

        - ‘YYYY-MM-DDTHH:MM:SS.ffffff’，如果 *note microsecond: 19dc. 不
          为 0

        - ‘YYYY-MM-DDTHH:MM:SS’，如果 *note microsecond: 19dc. 为 0

     如果 *note utcoffset(): 1a07. 返回值不为 ‘None’，则添加一个字符串来
     给出 UTC 时差：

        - ‘YYYY-MM-DDTHH:MM:SS.ffffff+HH:MM[:SS[.ffffff]]’，如果 *note
          microsecond: 19dc. 不为 0

        - ‘YYYY-MM-DDTHH:MM:SS+HH:MM[:SS[.ffffff]]’，如果 *note
          microsecond: 19dc. 为 0

     示例:

          >>> 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'

     可选参数 `sep' (默认为 ‘'T'’) 为单个分隔字符，会被放在结果的日期和
     时间两部分之间。 例如:

          >>> 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'

     可选参数 `timespec' 要包含的额外时间组件值 (默认为 ‘'auto'’)。它可
     以是以下值之一：

        - ‘'auto'’: 如果 *note microsecond: 19dc. 为 0 则与 ‘'seconds'’
          相同，否则与 ‘'microseconds'’ 相同。

        - ‘'hours'’: 以两个数码的 ‘HH’ 格式 包含 *note hour: 19d9.。

        - ‘'minutes'’: 以 ‘HH:MM’ 格式包含 *note hour: 19d9. 和 *note
          minute: 19da.。

        - ‘'seconds'’: 以 ‘HH:MM:SS’ 格式包含 *note hour: 19d9, *note
          minute: 19da. 和 *note second: 19db.。

        - ‘'milliseconds'’: 包含完整时间，但将秒值的小数部分截断至微秒。
          格式为 ‘HH:MM:SS.sss’

        - ‘'microseconds'’: 以 ‘HH:MM:SS.ffffff’ 格式包含完整时间。

          備註: 排除掉的时间部分将被截断，而不是被舍入。

     对于无效的 `timespec' 参数将引发 *note ValueError: 16d.:

          >>> 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'

     3.6 版新加入: 增加了 `timespec' 参数。

 -- 成員函式: datetime.__str__ ()

     对于 *note datetime: 19f. 实例 `d'，‘str(d)’ 等价于 ‘d.isoformat('
     ')’。

 -- 成員函式: datetime.ctime ()

     返回一个表示日期和时间的字符串:

          >>> from datetime import datetime
          >>> datetime(2002, 12, 4, 20, 30, 40).ctime()
          'Wed Dec  4 20:30:40 2002'

     输出字符串将 `并不' 包括时区信息，无论输入的是感知型还是简单型。

     ‘d.ctime()’ 等效于:

          time.ctime(time.mktime(d.timetuple()))

     在原生 C ‘ctime()’ 函数 (*note time.ctime(): 19f6. 会发起调用该函数
     ，但 *note datetime.ctime(): 1a11. 则不会) 遵循 C 标准的平台上。

 -- 成員函式: datetime.strftime (format)

     返回一个由显式格式字符串所指明的代表日期和时间的字符串，要获取格式
     指令的完整列表，请参阅 *note strftime() 和 strptime() 的行为:
     19f7.。

 -- 成員函式: datetime.__format__ (format)

     与 *note datetime.strftime(): 630. 相同。 此方法使得为 *note
     datetime: 19f. 对象指定以 *note 格式化字符串字面值: 296. 表示的格式
     化字符串以及使用 *note str.format(): 5d4. 进行格式化成为可能。 要获
     取格式指令的完整列表，请参阅 *note strftime() 和 strptime() 的行为:
     19f7.。

* Menu:

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

   ---------- Footnotes ----------

   (1) 
https://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.isoparse


File: python.info,  Node: 用法示例 datetime,  Up: datetime 对象

5.8.1.11 用法示例: ‘datetime’
.............................

使用 *note datetime: 19f. 对象的例子：

     >>> 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.'

以下示例定义了一个 *note tzinfo: 180. 子类，它捕获 Kabul, Afghanistan 时
区的信息，该时区使用 +4 UTC 直到 1945 年，之后则使用 +4:30 UTC:

     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"

上述 ‘KabulTz’ 的用法:

     >>> 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


File: python.info,  Node: time 对象,  Next: tzinfo 对象,  Prev: datetime 对象,  Up: datetime --- 基本日期和时间类型

5.8.1.12 ‘time’ 对象
....................

一个 *note time: 10c. 对象代表某日的（本地）时间，它独立于任何特定日期，
并可通过 *note tzinfo: 180. 对象来调整。

 -- 類別: datetime.time (hour=0, minute=0, second=0, microsecond=0,
          tzinfo=None, *, fold=0)

     所有参数都是可选的。 `tzinfo' 可以是 ‘None’，或者是一个 *note
     tzinfo: 180. 子类的实例。 其余的参数必须是在下面范围内的整数：

        * ‘0 <= hour < 24’,

        * ‘0 <= minute < 60’,

        * ‘0 <= second < 60’,

        * ‘0 <= microsecond < 1000000’,

        * ‘fold in [0, 1]’.

     如果给出一个此范围以外的参数，则会引发 *note ValueError: 16d.。 所
     有参数值默认为 ‘0’，只有 `tzinfo' 默认为 *note None: 203.。

类属性：

 -- 屬性: time.min

     早最的可表示 *note time: 5ec, ‘time(0, 0, 0, 0)’。

 -- 屬性: time.max

     最晚的可表示 *note time: 5ec, ‘time(23, 59, 59, 999999)’。

 -- 屬性: time.resolution

     两个不相等的 *note time: 5ec. 对象之间可能的最小间隔，
     ‘timedelta(microseconds=1)’，但是请注意 *note time: 5ec. 对象并不支
     持算术运算。

实例属性（只读）：

 -- 屬性: time.hour

     取值范围是 ‘range(24)’。

 -- 屬性: time.minute

     取值范围是 ‘range(60)’。

 -- 屬性: time.second

     取值范围是 ‘range(60)’。

 -- 屬性: time.microsecond

     取值范围是 ‘range(1000000)’。

 -- 屬性: time.tzinfo

     作为 tzinfo 参数被传给 *note time: 5ec. 构造器的对象，如果没有传入
     值则为 ‘None’。

 -- 屬性: time.fold

     取值范围是 ‘[0, 1]’。 用于在重复的时间段中消除边界时间歧义。 （当夏
     令时结束时回拨时钟或由于政治原因导致当明时区的 UTC 时差减少就会出现
     重复的时间段。） 取值 0 (1) 表示两个时刻早于（晚于）所代表的同一边
     界时间。

     3.6 版新加入.

*note time: 5ec. 对象支持 *note time: 5ec. 与 *note time: 5ec. 的比较，
当 `a' 时间在 `b' 之前时，则认为 `a' 小于 `b'。 如果比较的一方是简单型而
另一方是感知型，则如果尝试进行顺序比较将引发 *note TypeError: 1fe.。 对
于相等比较，简单型实例将永远不等于感知型实例。

如果两个比较方都是感知型，且具有相同的 *note tzinfo: 19d5. 属性，相同的
*note tzinfo: 19d5. 属性会被忽略并对基本时间值进行比较。 如果两个比较方
都是感知型且具有不同的 *note tzinfo: 19d5. 属性，两个比较方将首先通过减
去它们的 UTC 时差（从 ‘self.utcoffset()’ 获取）来进行调整。 为了防止将混
合类型比较回退为基于对象地址的默认比较，当 *note time: 5ec. 对象与不同类
型的对象比较时，将会引发 *note TypeError: 1fe.，除非比较运算符是 ‘==’ 或
‘!=’。 在后两种情况下将分别返回 *note False: 48e. 或 *note True: 593.。

3.3 版更變: 感知型和简单型 *note time: 5ec. 实例之间的相等比较不会引发
*note TypeError: 1fe.。

在布尔运算时，*note time: 5ec. 对象总是被视为真值。

3.5 版更變: 在 Python 3.5 之前，如果一个 *note time: 5ec. 对象代表 UTC 午
夜零时则会被视为假值。 此行为被认为容易引发困惑和错误，因此从 Python 3.5
起已被去除。 详情参见 bpo-13936(1)。

其他构造方法：

 -- 成員函式: classmethod time.fromisoformat (time_string)

     返回对应于 *note time.isoformat(): 1a1a. 所提供的某种 `time_string'
     格式的 *note time: 5ec.。 特别地，此函数支持以下格式的字符串：

          HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]

          警示: 此方法 `并不' 支持解析任意 ISO 8601 字符串。 它的目的只
          是作为 *note time.isoformat(): 1a1a. 的逆操作。

     示例:

          >>> 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)))

     3.7 版新加入.

实例方法：

 -- 成員函式: time.replace (hour=self.hour, minute=self.minute,
          second=self.second, microsecond=self.microsecond,
          tzinfo=self.tzinfo, *, fold=0)

     返回一个具有同样属性值的 *note time: 5ec.，除非通过任何关键字参数指
     定了某些属性值。 请注意可以通过指定 ‘tzinfo=None’ 从一个感知型
     *note time: 5ec. 创建一个简单型 *note time: 5ec.，而不必转换时间数
     据。

     3.6 版新加入: 增加了 ‘fold’ 参数。

 -- 成員函式: time.isoformat (timespec='auto')

     返回表示为下列 ISO 8601 格式之一的时间字符串：

        - ‘HH:MM:SS.ffffff’，如果 *note microsecond: 19d4. 不为 0

        - ‘HH:MM:SS’，如果 *note microsecond: 19d4. 为 0

        - ‘HH:MM:SS.ffffff+HH:MM[:SS[.ffffff]]’，如果 *note utcoffset():
          1a1c. 不返回 ‘None’

        - ‘HH:MM:SS+HH:MM[:SS[.ffffff]]’，如果 *note microsecond: 19d4.
          为 0 并且 *note utcoffset(): 1a1c. 不返回 ‘None’

     可选参数 `timespec' 要包含的额外时间组件值 (默认为 ‘'auto'’)。它可
     以是以下值之一：

        - ‘'auto'’: 如果 *note microsecond: 19d4. 为 0 则与 ‘'seconds'’
          相同，否则与 ‘'microseconds'’ 相同。

        - ‘'hours'’: 以两个数码的 ‘HH’ 格式 包含 *note hour: 19d1.。

        - ‘'minutes'’: 以 ‘HH:MM’ 格式包含 *note hour: 19d1. 和 *note
          minute: 19d2.。

        - ‘'seconds'’: 以 ‘HH:MM:SS’ 格式包含 *note hour: 19d1, *note
          minute: 19d2. 和 *note second: 19d3.。

        - ‘'milliseconds'’: 包含完整时间，但将秒值的小数部分截断至微秒。
          格式为 ‘HH:MM:SS.sss’

        - ‘'microseconds'’: 以 ‘HH:MM:SS.ffffff’ 格式包含完整时间。

          備註: 排除掉的时间部分将被截断，而不是被舍入。

     对于无效的 `timespec' 参数将引发 *note ValueError: 16d.。

     示例:

          >>> 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'

     3.6 版新加入: 增加了 `timespec' 参数。

 -- 成員函式: time.__str__ ()

     对于时间对象 `t', ‘str(t)’ 等价于 ‘t.isoformat()’。

 -- 成員函式: time.strftime (format)

     返回一个由显式格式字符串所指明的代表时间的字符串。 要获取格式指令的
     完整列表，请参阅 *note strftime() 和 strptime() 的行为: 19f7.。

 -- 成員函式: time.__format__ (format)

     与 *note time.strftime(): 1a1e. 相同。 此方法使得为 *note time:
     5ec. 对象指定以 *note 格式化字符串字面值: 296. 表示的格式化字符串以
     及使用 *note str.format(): 5d4. 进行格式化成为可能。 要获取格式指令
     的完整列表，请参阅 *note strftime() 和 strptime() 的行为: 19f7.。

 -- 成員函式: time.utcoffset ()

     如果 *note tzinfo: 19d5. 为 ‘None’，则返回 ‘None’，否则返回
     ‘self.tzinfo.utcoffset(None)’，并且在后者不返回 ‘None’ 或一个幅度小
     于一天的 a *note timedelta: 2ca. 对象时将引发异常。

     3.7 版更變: UTC 时差不再限制为一个整数分钟值。

 -- 成員函式: time.dst ()

     如果 *note tzinfo: 19d5. 为 ‘None’，则返回 ‘None’，否则返回
     ‘self.tzinfo.dst(None)’，并且在后者不返回 ‘None’ 或者一个幅度小于一
     天的 *note timedelta: 2ca. 对象时将引发异常。

     3.7 版更變: DST 差值不再限制为一个整数分钟值。

 -- 成員函式: time.tzname ()

     如果 *note tzinfo: 19d5. 为 ‘None’，则返回 ‘None’，否则返回
     ‘self.tzinfo.tzname(None)’，如果后者不返回 ‘None’ 或者一个字符串对
     象则将引发异常。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue13936


File: python.info,  Node: 用法示例 time,  Up: time 对象

5.8.1.13 用法示例: ‘time’
.........................

使用 *note time: 5ec. 对象的例子:

     >>> 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.'


File: python.info,  Node: tzinfo 对象,  Next: timezone 对象,  Prev: time 对象,  Up: datetime --- 基本日期和时间类型

5.8.1.14 ‘tzinfo’ 对象
......................

 -- 類別: datetime.tzinfo

     这是一个抽象基类，也就是说该类不应被直接实例化。 请定义 *note
     tzinfo: 180. 的子类来捕获有关特定时区的信息。

     *note tzinfo: 180. 的（某个实体子类）的实例可以被传给 *note
     datetime: 19f. 和 *note time: 5ec. 对象的构造器。 这些对象会将它们
     的属性视为对应于本地时间，并且 *note tzinfo: 180. 对象支持展示本地
     时间与 UTC 的差值、时区名称以及 DST 差值的方法，都是与传给它们的日
     期或时间对象的相对值。

     你需要派生一个实体子类，并且（至少）提供你使用 *note datetime: 19f.
     方法所需要的标准 *note tzinfo: 180. 方法的实现。 *note datetime:
     30. 模块提供了 *note timezone: ae0.，这是 *note tzinfo: 180. 的一个
     简单实体子类，它能以与 UTC 的固定差值来表示不同的时区，例如 UTC 本
     身或北美的 EST 和 EDT。

     对于封存操作的特殊要求：一个 *note tzinfo: 180. 子类必须具有可不带
     参数调用的 *note __init__(): e23. 方法，否则它虽然可以被封存，但可
     能无法再次解封。 这是个技术性要求，在未来可能会被取消。

     一个 *note tzinfo: 180. 的实体子类可能需要实现以下方法。 具体需要实
     现的方法取决于感知型 *note datetime: 30. 对象如何使用它。 如果有疑
     问，可以简单地全都实现。

 -- 成員函式: tzinfo.utcoffset (dt)

     将本地时间与 UTC 时差返回为一个 *note timedelta: 2ca. 对象，如果本
     地时区在 UTC 以东则为正值。 如果本地时区在 UTC 以西则为负值。

     这表示与 UTC 的 `总计' 时差；举例来说，如果一个 *note tzinfo: 180.
     对象同时代表时区和 DST 调整，则 *note utcoffset(): 1a25. 应当返回两
     者的和。 如果 UTC 时差不确定则返回 ‘None’。 在其他情况下返回值必须
     为一个 *note timedelta: 2ca. 对象，其取值严格限制于
     ‘-timedelta(hours=24)’ 和 ‘timedelta(hours=24)’ 之间（差值的幅度必
     须小于一天）。 大多数 *note utcoffset(): 1a25. 的实现看起来可能像是
     以下两者之一:

          return CONSTANT                 # fixed-offset class
          return CONSTANT + self.dst(dt)  # daylight-aware class

     如果 *note utcoffset(): 1a25. 返回值不为 ‘None’，则 *note dst():
     1a26. 也不应返回 ‘None’。

     默认的 *note utcoffset(): 1a25. 实现会引发 *note
     NotImplementedError: 704.。

     3.7 版更變: UTC 时差不再限制为一个整数分钟值。

 -- 成員函式: tzinfo.dst (dt)

     将夏令时（DST）调整返回为一个 *note timedelta: 2ca. 对象，如果 DST
     信息未知则返回 ‘None’。

     如果 DST 未启用则返回 ‘timedelta(0)’。 如果 DST 已启用则将差值作为
     一个 *note timedelta: 2ca. 对象返回（参见 *note utcoffset(): 1a25.
     了解详情）。 请注意 DST 差值如果可用，就会直接被加入 *note
     utcoffset(): 1a25. 所返回的 UTC 时差，因此无需额外查询 *note dst():
     1a26. 除非你希望单独获取 DST 信息。 例如，*note
     datetime.timetuple(): 1a0b. 会调用其 *note tzinfo: 19dd. 属性的
     *note dst(): 1a26. 方法来确定应该如何设置 ‘tm_isdst’ 旗标，而 *note
     tzinfo.fromutc(): 1a09. 会调用 *note dst(): 1a26. 来在跨越时区时处
     理 DST 的改变。

     一个可以同时处理标准时和夏令时的 *note tzinfo: 180. 子类的实例 `tz'
     必须在此情形中保持一致：

     ‘tz.utcoffset(dt) - tz.dst(dt)’

     必须为具有同样的 *note tzinfo: 180. 子类实例且 ‘dt.tzinfo == tz’ 的
     每个 *note datetime: 19f. 对象 `dt' 返回同样的结果，此表达式会产生
     时区的“标准时差”，它不应取决于具体日期或时间，只取决于地理位置。
     *note datetime.astimezone(): 2cb. 的实现依赖此方法，但无法检测违反
     规则的情况；确保符合规则是程序员的责任。 如果一个 *note tzinfo:
     180. 子类不能保证这一点，也许可以重载 *note tzinfo.fromutc(): 1a09.
     的默认实现以便在任何情况下与 ‘astimezone()’ 正确配合。

     大多数 *note dst(): 1a26. 的实现可能会如以下两者之一:

          def dst(self, dt):
              # a fixed-offset class:  doesn't account for DST
              return timedelta(0)

     或者：

          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)

     默认的 *note dst(): 1a26. 实现会引发 *note NotImplementedError:
     704.。

     3.7 版更變: DST 差值不再限制为一个整数分钟值。

 -- 成員函式: tzinfo.tzname (dt)

     将对应于 *note datetime: 19f. 对象 `dt' 的时区名称作为字符串返回。
     *note datetime: 30. 模块没有定义任何字符串名称相关内容，也不要求名
     称有任何特定含义。 例如 "GMT", "UTC", "-500", "-5:00", "EDT",
     "US/Eastern", "America/New York" 都是有效的返回值。 如果字符串名称
     未知则返回 ‘None’。 请注意这是一个方法而不是一个固定的字符串，这主
     要是因为某些 *note tzinfo: 180. 子类可能需要根据所传入的特定 `dt' 值
     返回不同的名称，特别是当 *note tzinfo: 180. 类要负责处理夏令时的时
     候。

     默认的 *note tzname(): 1a27. 实现会引发 *note NotImplementedError:
     704.。

这些方法会被 *note datetime: 19f. 或 *note time: 5ec. 对象调用，用来与它
们的同名方法相对应。 *note datetime: 19f. 对象会将自身作为传入参数，而
*note time: 5ec. 对象会将 ‘None’ 作为传入参数。 这样 *note tzinfo: 180.
子类的方法应当准备好接受 `dt' 参数值为 ‘None’ 或是 *note datetime: 19f.
类的实例。

当传入 ‘None’ 时，应当由类的设计者来决定最佳回应方式。 例如，返回 ‘None’
适用于希望该类提示时间对象不参与 *note tzinfo: 180. 协议处理。 让
‘utcoffset(None)’ 返回标准 UTC 时差也许会更有用处，因为并没有其他可用于
发现标准时差的约定惯例。

当传入一个 *note datetime: 19f. 对象来回应 *note datetime: 19f. 方法时，
‘dt.tzinfo’ 与 `self' 是同一对象。 *note tzinfo: 180. 方法可以依赖这一点
，除非用户代码直接调用了 *note tzinfo: 180. 方法。 此行为的目的是使得
*note tzinfo: 180. 方法将 `dt' 解读为本地时间，而不需要担心其他时区的相
关对象。

还有一个额外的 *note tzinfo: 180. 方法，某个子类可能会希望重载它：

 -- 成員函式: tzinfo.fromutc (dt)

     此方法会由默认的 *note datetime.astimezone(): 2cb. 实现来调用。 当
     被其调用时，‘dt.tzinfo’ 为 `self'，并且 `dt' 的日期和时间数据会被视
     为表示 UTC 时间，*note fromutc(): 1a09. 的目标是调整日期和时间数据
     ，返回一个等价的 datetime 来表示 `self' 的本地时间。

     大多数 *note tzinfo: 180. 子类应该能够毫无问题地继承默认的 *note
     fromutc(): 1a09. 实现。 它的健壮性足以处理固定差值的时区以及同时负
     责标准时和夏令时的时区，对于后者甚至还能处理 DST 转换时间在各个年份
     有变化的情况。 一个默认 *note fromutc(): 1a09. 实现可能无法在所有情
     况下正确处理的例子是（与 UTC 的）标准时差取决于所经过的特定日期和时
     间，这种情况可能由于政治原因而出现。 默认的 ‘astimezone()’ 和 *note
     fromutc(): 1a09. 实现可能无法生成你希望的结果，如果这个结果恰好是跨
     越了标准时差发生改变的时刻当中的某个小时值的话。

     忽略针对错误情况的代码，默认 *note fromutc(): 1a09. 实现的行为方式
     如下:

          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

在以下 ‘tzinfo_examples.py’ 文件中有一些 *note tzinfo: 180. 类的例子：

     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")

请注意同时负责标准时和夏令时的 *note tzinfo: 180. 子类在每年两次的 DST 转
换点上会出现不可避免的微妙问题。具体而言，考虑美国东部时区 (UTC -0500)，
它的 EDT 从三月的第二个星期天 1:59 (EST) 之后一分钟开始，并在十一月的第
一天星期天 1:59 (EDT) 之后一分钟结束:

       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

当 DST 开始时（即 "start" 行），本地时钟从 1:59 跳到 3:00。 形式为 2:MM
的时间值在那一天是没有意义的，因此在 DST 开始那一天
‘astimezone(Eastern)’ 不会输出包含 ‘hour == 2’ 的结果。 例如，在 2016 年
春季时钟向前调整时，我们得到:

     >>> 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

当 DST 结束时（见 "end" 行），会有更糟糕的潜在问题：本地时间值中有一个小
时是不可能没有歧义的：夏令时的最后一小时。 即以北美东部时间表示当天夏令
时结束时的形式为 5:MM UTC 的时间。 本地时钟从 1:59 (夏令时) 再次跳回到
1:00 (标准时)。 形式为 1:MM 的本地时间就是有歧义的。 此时 ‘astimezone()’
是通过将两个相邻的 UTC 小时映射到两个相同的本地小时来模仿本地时钟的行为
。 在这个北美东部时间的示例中，形式为 5:MM 和 6:MM 的 UTC 时间在转换为北
美东部时间时都将被映射到 1:MM，但前一个时间会将 *note fold: 5ed. 属性设
为 0 而后一个时间会将其设为 1。 例如，在 2016 年秋季时钟往回调整时，我们
得到:

     >>> 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

请注意不同的 *note datetime: 19f. 实例仅通过 *note fold: 5ed. 属性值来加
以区分，它们在比较时会被视为相等。

不允许时间显示存在歧义的应用需要显式地检查 *note fold: 5ed. 属性的值，或
者避免使用混合式的 *note tzinfo: 180. 子类；当使用 *note timezone: ae0.
或者任何其他固定差值的 *note tzinfo: 180. 子类例如仅表示 EST（固定差值
-5 小时）或仅表示 EDT（固定差值 -4 小时）的类时是不会有歧义的。

也參考
......

     *note zoneinfo: 14e.

          *note datetime: 30. 模块有一个基本 *note timezone: ae0. 类（用
          来处理任意与 UTC 的固定时差）及其 *note timezone.utc: 1a28. 属
          性（一个 UTC 时区实例）。

          ‘zoneinfo’ brings the `IANA timezone database' (also known as
          the Olson database) to Python, and its usage is recommended.

IANA 时区数据库(1)

     该时区数据库 (通常称为 tz, tzdata 或 zoneinfo) 包含大量代码和数据用
     来表示全球许多有代表性的地点的本地时间的历史信息。 它会定期进行更新
     以反映各政治实体对时区边界、UTC 差值和夏令时规则的更改。

   ---------- Footnotes ----------

   (1) https://www.iana.org/time-zones


File: python.info,  Node: timezone 对象,  Next: strftime 和 strptime 的行为,  Prev: tzinfo 对象,  Up: datetime --- 基本日期和时间类型

5.8.1.15 ‘timezone’ 对象
........................

*note timezone: ae0. 类是 *note tzinfo: 180. 的子类，它的每个实例都代表
一个以与 UTC 的固定时差来定义的时区。

此类的对象不可被用于代表某些特殊地点的时区信息，这些地点在一年的不同日期
会使用不同的时差，或是在历史上对民用时间进行过调整。

 -- 類別: datetime.timezone (offset, name=None)

     `offset' 参数必须指定为一个 *note timedelta: 2ca. 对象，表示本地时
     间与 UTC 的时差。 它必须严格限制于 ‘-timedelta(hours=24)’ 和
     ‘timedelta(hours=24)’ 之间，否则会引发 *note ValueError: 16d.。

     `name' 参数是可选的。 如果指定则必须为一个字符串，它将被用作 *note
     datetime.tzname(): 1a0a. 方法的返回值。

     3.2 版新加入.

     3.7 版更變: UTC 时差不再限制为一个整数分钟值。

 -- 成員函式: timezone.utcoffset (dt)

     返回当 *note timezone: ae0. 实例被构造时指定的固定值。

     `dt' 参数会被忽略。 返回值是一个 *note timedelta: 2ca. 实例，其值等
     于本地时间与 UTC 之间的时差。

     3.7 版更變: UTC 时差不再限制为一个整数分钟值。

 -- 成員函式: timezone.tzname (dt)

     返回当 *note timezone: ae0. 实例被构造时指定的固定值。

     如果没有在构造器中提供 `name'，则 ‘tzname(dt)’ 所返回的名称将根据
     ‘offset’ 值按以下规则生成。 如果 `offset' 为 ‘timedelta(0)’，则名称
     为“UTC”，否则为字符串 ‘UTC±HH:MM’，其中 ± 为 ‘offset’ 的正负符号，
     HH 和 MM 分别为表示 ‘offset.hours’ 和 ‘offset.minutes’ 的两个数码。

     3.6 版更變: 由 ‘offset=timedelta(0)’ 生成的名称现在为简单的 ‘’UTC’’
     而不再是 ‘'UTC+00:00'’。

 -- 成員函式: timezone.dst (dt)

     总是返回 ‘None’。

 -- 成員函式: timezone.fromutc (dt)

     返回 ‘dt + offset’。 `dt' 参数必须为一个感知型 *note datetime: 19f.
     实例，其中 ‘tzinfo’ 值设为 ‘self’。

类属性：

 -- 屬性: timezone.utc

     UTC 时区，‘timezone(timedelta(0))’。


File: python.info,  Node: strftime 和 strptime 的行为,  Prev: timezone 对象,  Up: datetime --- 基本日期和时间类型

5.8.1.16 ‘strftime()’ 和 ‘strptime()’ 的行为
............................................

*note date: 19d, *note datetime: 19f. 和 *note time: 5ec. 对象都支持
‘strftime(format)’ 方法，可用来创建由一个显式格式字符串所控制的表示时间
的字符串。

相反地，*note datetime.strptime(): f91. 类会根据表示日期和时间的字符串和
相应的格式字符串来创建一个 *note datetime: 19f. 对象。

下表提供了 ‘strftime()’ 与 ‘strptime()’ 的高层级比较：

                     ‘strftime’                                                   ‘strptime’
                                                                                  
---------------------------------------------------------------------------------------------------------------------------------------------------------------------
                                                                                  
用法                 根据给定的格式将对象转换为字符串                             将字符串解析为给定相应格式的 *note datetime: 19f. 对象
                                                                                  
                                                                                  
方法类型             实例方法                                                     类方法
                                                                                  
                                                                                  
方法                 *note date: 19d.; *note datetime: 19f.; *note time: 5ec.     *note datetime: 19f.
                                                                                  
                                                                                  
签名                 ‘strftime(format)’                                           ‘strptime(date_string, format)’
                                                                                  

* Menu:

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


File: python.info,  Node: strftime 和 strptime Format Codes,  Next: 技术细节,  Up: strftime 和 strptime 的行为

5.8.1.17 ‘strftime()’ 和 ‘strptime()’ Format Codes
..................................................

以下列表显示了 1989 版 C 标准所要求的全部格式代码，它们在带有标准 C 实现
的所有平台上均可用。

指令            意义                                 示例                         註解
                                                                                  
----------------------------------------------------------------------------------------------
                                                                                  
‘%a’            当地工作日的缩写。                        Sun, Mon, ..., Sat (en_US); (1)
                                                          So, Mo, ..., Sa (de_DE) 
                                                     
                                                                                  
‘%A’            本地化的星期中每日的完整名称。            Sunday, Monday, ..., Saturday (en_US); (1)
                                                          Sonntag, Montag, ..., Samstag (de_DE) 
                                                     
                                                                                  
‘%w’            以十进制数显示的工作日，其中0表示    0, 1, ..., 6
                星期日，6表示星期六。                
                
                                                                                  
‘%d’            补零后，以十进制数显示的月份中的一   01, 02, ..., 31              (9)
                天。                                                              
                
                                                                                  
‘%b’            当地月份的缩写。                          Jan, Feb, ..., Dec (en_US); (1)
                                                          Jan, Feb, ..., Dez (de_DE) 
                                                     
                                                                                  
‘%B’            本地化的月份全名。                        January, February, ..., December (en_US); (1)
                                                          Januar, Februar, ..., Dezember (de_DE) 
                                                     
                                                                                  
‘%m’            补零后，以十进制数显示的月份。       01, 02, ..., 12              (9)
                                                                                  
                                                                                  
‘%y’            补零后，以十进制数表示的，不带世纪   00, 01, ..., 99              (9)
                的年份。                                                          
                
                                                                                  
‘%Y’            十进制数表示的带世纪的年份。         0001, 0002, ..., 2013,       (2)
                                                     2014, ..., 9998, 9999        
                                                     
                                                                                  
‘%H’            以补零后的十进制数表示的小时（24 小  00, 01, ..., 23              (9)
                时制）。                                                          
                
                                                                                  
‘%I’            以补零后的十进制数表示的小时（12 小  01, 02, ..., 12              (9)
                时制）。                                                          
                
                                                                                  
‘%p’            本地化的 AM 或 PM 。                      AM, PM (en_US);         (1), (3)
                                                          am, pm (de_DE)          
                                                     
                                                                                  
‘%M’            补零后，以十进制数显示的分钟。       00, 01, ..., 59              (9)
                                                                                  
                                                                                  
‘%S’            补零后，以十进制数显示的秒。         00, 01, ..., 59              (4), (9)
                                                                                  
                                                                                  
‘%f’            Microsecond as a decimal number,     000000, 000001, ...,         (5)
                zero-padded to 6 digits.             999999                       
                                                     
                                                                                  
‘%z’            UTC 偏移量，格式为                   (空), +0000, -0400, +1030,   (6)
                ‘±HHMM[SS[.ffffff]]’ （如果是简单    +063415, -030712.345216      
                型对象则为空字符串）。               
                
                                                                                  
‘%Z’            时区名称（如果对象为简单型则为空字   (空), UTC, GMT               (6)
                符串）。                                                          
                
                                                                                  
‘%j’            以补零后的十进制数表示的一年中的日   001, 002, ..., 366           (9)
                序号。                                                            
                
                                                                                  
‘%U’            以补零后的十进制数表示的一年中的周   00, 01, ..., 53              (7), (9)
                序号（星期日作为每周的第一天）。 在                               
                新的一年中第一个星期日之前的所有日
                子都被视为是在第 0 周。
                
                                                                                  
‘%W’            以十进制数表示的一年中的周序号（星   00, 01, ..., 53              (7), (9)
                期一作为每周的第一天）。 在新的一                                 
                年中第一个第期一之前的所有日子都被
                视为是在第 0 周。
                
                                                                                  
‘%c’            本地化的适当日期和时间表示。              Tue Aug 16 21:30:00 1988 (en_US); (1)
                                                          Di 16 Aug 21:30:00 1988 (de_DE) 
                                                     
                                                                                  
‘%x’            本地化的适当日期表示。                    08/16/88 (None);        (1)
                                                          08/16/1988 (en_US);     
                                                          16.08.1988 (de_DE) 
                                                     
                                                                                  
‘%X’            本地化的适当时间表示。                    21:30:00 (en_US);       (1)
                                                          21:30:00 (de_DE)        
                                                     
                                                                                  
‘%%’            字面的 ‘'%'’ 字符。                  %
                                                     

为了方便起见，还包括了C89标准不需要的其他一些指令。这些参数都对应于ISO
8601日期值。

指令            意义                                 示例                         註解
                                                                                  
----------------------------------------------------------------------------------------------
                                                                                  
‘%G’            带有世纪的 ISO 8601 年份，表示包含   0001, 0002, ..., 2013,       (8)
                大部分 ISO 星期 (‘%V’) 的年份。      2014, ..., 9998, 9999        
                                                     
                                                                                  
‘%u’            以十进制数显示的 ISO 8601 星期中的   1, 2, ..., 7
                日序号，其中 1 表示星期一。          
                
                                                                                  
‘%V’            以十进制数显示的 ISO 8601 星期，以   01, 02, ..., 53              (8), (9)
                星期一作为每周的第一天。 第 01 周                                 
                为包含 1 月 4 日的星期。
                

这些代码可能不是在所有平台上都可与 ‘strftime()’ 方法配合使用。 ISO 8601
年份和 ISO 8601 星期指令并不能与上面的年份和星期序号指令相互替代。 调用
‘strptime()’ 时传入不完整或有歧义的 ISO 8601 指令将引发 *note
ValueError: 16d.。

The full set of format codes supported varies across platforms, because
Python calls the platform C library’s ‘strftime()’ function, and
platform variations are common.  To see the full set of format codes
supported on your platform, consult the ‘strftime(3)’ documentation.
There are also differences between platforms in handling of unsupported
format specifiers.

3.6 版新加入: 增加了 ‘%G’, ‘%u’ 和 ‘%V’。


File: python.info,  Node: 技术细节,  Prev: strftime 和 strptime Format Codes,  Up: strftime 和 strptime 的行为

5.8.1.18 技术细节
.................

总体而言，‘d.strftime(fmt)’ 类似于 *note time: 10c. 模块的
‘time.strftime(fmt, d.timetuple())’，但是并非所有对象都支持
‘timetuple()’ 方法。

对于 *note datetime.strptime(): f91. 类方法，默认值为
‘1900-01-01T00:00:00.000’: 任何未在格式字符串中指定的部分都将从默认值中
提取。 (1)

使用 ‘datetime.strptime(date_string, format)’ 等价于:

     datetime(*(time.strptime(date_string, format)[0:6]))

除非格式中包含秒以下的部分或时区差值信息，它们在 ‘datetime.strptime’ 中
受支持但会被 ‘time.strptime’ 所丢弃。

对于 *note time: 5ec. 对象，年、月、日的格式代码不应被使用，因为 *note
time: 10c. 对象没有这些值。 如果它们被使用，则年份将被替换为 ‘1900’，而
月和日将被替换为 ‘1’。

对于 *note date: 19d. 对象，时、分、秒和微秒的格式代码不应被使用，因为
*note date: 19d. 对象没有这些值。 如果它们被使用，则它们都将被替换为
‘0’。

出于相同的原因，对于包含当前区域设置字符集所无法表示的 Unicode 码位的格
式字符串的处理方式也取决于具体平台。 在某些平台上这样的码位会不加修改地
原样输出，而在其他平台上 ‘strftime’ 则可能引发 *note UnicodeError: d03.
或只返回一个空字符串。

註解：

  1. 由于此格式依赖于当前区域设置，因此对具体输出值应当保持谨慎预期。 字
     段顺序会发生改变（例如 "month/day/year" 与 "day/month/year"），并且
     输出可能包含使用区域设置所指定的默认编码格式的 Unicode 字符（例如如
     果当前区域为 ‘ja_JP’，则默认编码格式可能为 ‘eucJP’, ‘SJIS’ 或
     ‘utf-8’ 中的一个；使用 *note locale.getlocale(): 1a32. 可确定当前区
     域设置的编码格式）。

  2. ‘strptime()’ 方法能够解析整个 [1, 9999] 范围内的年份，但 < 1000 的
     年份必须加零填充为 4 位数字宽度。

     3.2 版更變: 在之前的版本中，‘strftime()’ 方法只限于 >= 1900 的年份
     。

     3.3 版更變: 在版本3.2中，‘strftime()’ 方法只限于 years >= 1000。

  3. 当与 ‘strptime()’ 方法一起使用时，如果使用 ‘%I’ 指令来解析小时，
     ‘%p’ 指令只影响输出小时字段。

  4. 与 *note time: 10c. 模块不同的是， *note datetime: 30. 模块不支持闰
     秒。

  5. 当与 ‘strptime()’ 方法一起使用时，‘%f’ 指令可接受一至六个数码及左边
     的零填充。 ‘%f’ 是对 C 标准中格式字符集的扩展（但单独在 datetime 对
     象中实现，因此它总是可用）。

  6. 对于简单型对象，‘%z’ and ‘%Z’ 格式代码会被替换为空字符串。

     对于一个感知型对象而言：

     ‘%z’

          ‘utcoffset()’ 会被转换为 ‘±HHMM[SS[.ffffff]]’ 形式的字符串，其
          中 ‘HH’ 为给出 UTC 时差的小时部分的 2 位数码字符串，‘MM’ 为给
          出 UTC 时差的分钟部分的 2 位数码字符串，‘SS’ 为给出 UTC 时差的
          秒部分的 2 位数码字符串，而 ‘ffffff’ 为给出 UTC 时差的微秒部分
          的 6 位数码字符串。 当时差为整数秒时 ‘ffffff’ 部分将被省略，而
          当时差为整数分钟时 ‘ffffff’ 和 ‘SS’ 部分都将被省略。 例如，如
          果 ‘utcoffset()’ 返回 ‘timedelta(hours=-3, minutes=-30)’，则
          ‘%z’ 会被替换为字符串 ‘'-0330'’。

     3.7 版更變: UTC 时差不再限制为一个整数分钟值。

     3.7 版更變: 当提供 ‘%z’ 指令给 ‘strptime()’ 方法时，UTC 差值可以在
     时、分和秒之间使用冒号分隔符。 例如，‘'+01:00:00'’ 将被解读为一小时
     的差值。 此外，提供 ‘'Z'’ 就相当于 ‘'+00:00'’。

     ‘%Z’

          在 ‘strftime()’ 中，如果 ‘tzname()’ 返回 ‘None’ 则 ‘%Z’ 会被替
          换为一个空字符串；在其他情况下 ‘%Z’ 会被替换为返回值，该值必须
          为一个字符串。

          ‘strptime()’ 仅接受特定的 ‘%Z’ 值:

            1. 你的机器的区域设置可以是 ‘time.tzname’ 中的任何值

            2. 硬编码的值 ‘UTC’ 和 ‘GMT’

          这样生活在日本的人可用的值为 ‘JST’, ‘UTC’ 和 ‘GMT’，但可能没有
          ‘EST’。 它将引发 ‘ValueError’ 表示无效的值。

     3.2 版更變: 当提供 ‘%z’ 指令给 ‘strptime()’ 方法时，将产生一个感知
     型 *note datetime: 19f. 对象。 结果的 ‘tzinfo’ 将被设为一个 *note
     timezone: ae0. 实例。

  7. 当与 ‘strptime()’ 方法一起使用时，‘%U’ 和 ‘%W’ 仅用于指定星期几和日
     历年份 (‘%Y’) 的计算。

  8. 类似于 ‘%U’ 和 ‘%W’，‘%V’ 仅用于在 ‘strptime()’ 格式字符串中指定星
     期几和 ISO 年份 (‘%G’) 的计算。 还要注意 ‘%G’ 和 ‘%Y’ 是不可交换的
     。

  9. 当于 ‘strptime()’ 方法一起使用时，前导的零在格式 ‘%d’, ‘%m’, ‘%H’,
     ‘%I’, ‘%M’, ‘%S’, ‘%J’, ‘%U’, ‘%W’ 和 ‘%V’ 中是可选的。 格式 ‘%y’ 不
     要求有前导的零。

註解
....

   ---------- Footnotes ----------

   (1) (4) 传入 ‘datetime.strptime('Feb 29', '%b %d')’ 将导致错误，因为
‘1900’ 不是闰年。


File: python.info,  Node: zoneinfo --- IANA 时区支持,  Next: calendar --- 日历相关函数,  Prev: datetime --- 基本日期和时间类型,  Up: 数据类型

5.8.2 ‘zoneinfo’ — IANA 时区支持
--------------------------------

3.9 版新加入.

__________________________________________________________________

*note zoneinfo: 14e. 模块根据 PEP 615(1) 的最初说明提供了具体的时区实现
来支持 IANA 时区数据库。 按照默认设置，*note zoneinfo: 14e. 会在可能的情
况下使用系统的时区数据；如果系统时区数据不可用，该库将回退为使用 PyPI 上
提供的 tzdata(2) 第一方包。

也參考
......

模块: *note datetime: 30.

     提供 *note time: 5ec. 和 *note datetime: 19f. 类型，*note ZoneInfo:
     17f. 类被设计为可配合这两个类型使用。

包 tzdata(3)

     由 CPython 核心开发者维护以通过 PyPI 提供时区数据的第一方包。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0615

   (2) https://pypi.org/project/tzdata/

   (3) https://pypi.org/project/tzdata/


File: python.info,  Node: 使用 ZoneInfo,  Next: 数据源,  Up: zoneinfo --- IANA 时区支持

5.8.2.1 使用 ‘ZoneInfo’
.......................

*note ZoneInfo: 17f. 是 *note datetime.tzinfo: 180. 抽象基类的具体实现，
其目标是通过构造器、 *note datetime.replace: 1a06. 方法或 *note
datetime.astimezone: 2cb. 来与 ‘tzinfo’ 建立关联:

     >>> 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'

以此方式构造的日期时间对象可兼容日期时间运算并可在无需进一步干预的情况下
处理夏令时转换:

     >>> dt_add = dt + timedelta(days=1)

     >>> print(dt_add)
     2020-11-01 12:00:00-08:00

     >>> dt_add.tzname()
     'PST'

这些时区还支持在 PEP 495(1) 中引入的 *note fold: 5ed.。 在可能导致时间歧
义的时差转换中（例如夏令时到标准时的转换），当 ‘fold=0’ 时会使用转换 `之
前' 的时差，而当 ‘fold=1’ 时则使用转换 `之后' 的时差，例如:

     >>> 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

当执行来自另一时区的转换时，fold 将被设置为正确的值:

     >>> 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

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0495


File: python.info,  Node: 数据源,  Next: ZoneInfo 类,  Prev: 使用 ZoneInfo,  Up: zoneinfo --- IANA 时区支持

5.8.2.2 数据源
..............

‘zoneinfo’ 模块不直接提供时区数据，而是在可能的情况下从系统时区数据库或
PyPI 上的第一方包 tzdata(1) 获取时区信息。 某些系统，重要的一点是
Windows 系统也包括在内，并没有可用的 IANA 数据库，因此对于要保证获取时区
信息的跨平台兼容性的项目，推荐对 tzdata 声明依赖。 如果系统数据和 tzdata
均不可用，则所有对 *note ZoneInfo: 17f. 的调用都将引发 *note
ZoneInfoNotFoundError: 1a37.。

* Menu:

* 配置数据源::

   ---------- Footnotes ----------

   (1) https://pypi.org/project/tzdata/


File: python.info,  Node: 配置数据源,  Up: 数据源

5.8.2.3 配置数据源
..................

当 ‘ZoneInfo(key)’ 被调用时，此构造器首先会在 *note TZPATH: 1a3a. 所指定
的目录下搜索匹配 ‘key’ 的文件，失败时则会在 tzdata 包中查找匹配。 此行为
可通过三种方式来配置:

  1. 默认的 *note TZPATH: 1a3a. 未通过其他方式指定时可在 *note 编译时:
     1a3b. 进行配置。

  2. *note TZPATH: 1a3a. 可使用 *note 环境变量: 1a3c. 进行配置。

  3. 在 *note 运行时: 1a3d.，搜索路径可使用 *note reset_tzpath(): 1a3e.
     函数来修改。

* Menu:

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


File: python.info,  Node: 编译时配置,  Next: 环境配置,  Up: 配置数据源

5.8.2.4 编译时配置
..................

默认的 *note TZPATH: 1a3a. 包括一些时区数据库的通用布署位置（Windows 除
外，该系统没有时区数据的“通用”位置）。 在 POSIX 系统中，下游分发者和从源
码编译 Python 的开发者知道系统时区数据布署位置，他们可以通过指定编译时选
项 ‘TZPATH’ (或者更常见的是通过 ‘configure’ 旗标 ‘--with-tzpath’) 来改变
默认的时区路径，该选项应当是一个由 *note os.pathsep: 1486. 分隔的字符串
。

在所有平台上，配置值会在 *note sysconfig.get_config_var(): a45. 中以
‘TZPATH’ 键的形式提供。


File: python.info,  Node: 环境配置,  Next: 运行时配置,  Prev: 编译时配置,  Up: 配置数据源

5.8.2.5 环境配置
................

当初始化 *note TZPATH: 1a3a. 时（在导入时或不带参数调用 *note
reset_tzpath(): 1a3e. 时），‘zoneinfo’ 模块将使用环境变量
‘PYTHONTZPATH’，如果变量存在则会设置搜索路径。

 -- 環境變數: PYTHONTZPATH

     这是一个以 *note os.pathsep: 1486. 分隔的字符串，其中包含要使用的时
     区搜索路径。 它必须仅由绝对路径而非相对路径组成。 在 ‘PYTHONTZPATH’
     中指定的相对路径部分将不会被使用，但在其他情况下当指定相对路径时的
     行为该实现是有定义的；CPython 将引发 *note InvalidTZPathWarning:
     1a42.，而其他实现可自由地忽略错误部分或是引发异常。

要设置让系统忽略系统数据并改用 tzdata 包，请设置 ‘PYTHONTZPATH=""’。


File: python.info,  Node: 运行时配置,  Prev: 环境配置,  Up: 配置数据源

5.8.2.6 运行时配置
..................

TZ 搜索路径也可在运行时使用 *note reset_tzpath(): 1a3e. 函数来配置。 通
常并不建议如此操作，不过在需要使用指定时区路径（或者需要禁止访问系统时区
）的测试函数中使用它则是合理的。


File: python.info,  Node: ZoneInfo 类,  Next: 函数<2>,  Prev: 数据源,  Up: zoneinfo --- IANA 时区支持

5.8.2.7 ‘ZoneInfo’ 类
.....................

 -- 類別: zoneinfo.ZoneInfo (key)

     一个具体的 *note datetime.tzinfo: 180. 子类，它代表一个由字符串
     ‘key’ 所指定的 IANA 时区。 对主构造器的调用将总是返回可进行标识比较
     的对象；但是另一种方式，对所有的 ‘key’ 值通过 *note
     ZoneInfo.clear_cache(): 1a45. 禁止缓存失效，对以下断言将总是为真值:

          a = ZoneInfo(key)
          b = ZoneInfo(key)
          assert a is b

     ‘key’ 必须采用相对的标准化 POSIX 路径的形式，其中没有对上一层级的引
     用。 如果传入了不合要求的键则构造器将引发 *note ValueError: 16d.。

     如果没有找到匹配 ‘key’ 的文件，构造器将引发 *note
     ZoneInfoNotFoundError: 1a37.。

‘ZoneInfo’ 类具有两个替代构造器:

 -- 成員函式: classmethod ZoneInfo.from_file (fobj, /, key=None)

     基于一个返回字节串的文件类对象（例如一个以二进制模式打开的文件或是
     一个 *note io.BytesIO: 88a. 对象）构造 ‘ZoneInfo’ 对象。 不同于主构
     造器，此构造器总是会构造一个新对象。

     ‘key’ 形参设置时区名称以供 *note __str__(): ef9. 和 *note
     __repr__(): 44a. 使用。

     由此构造器创建的对象不可被封存 (参见 *note pickling: 1a47.)。

 -- 成員函式: classmethod ZoneInfo.no_cache (key)

     一个绕过构造器缓存的替代构造器。 它与主构造器很相似，但每次调用都会
     返回一个新对象。 此构造器在进行测试或演示时最为适用，但它也可以被用
     来创建具有不同缓存失效策略的系统。

     由此构造器创建的对象在被解封时也会绕过反序列化进程的缓存。

          警示: 使用此构造器可以会以令人惊讶的方式改变日期时间对象的语义
          ，只有在你确定你的需求时才使用它。

也可以使用以下的类方法:

 -- 成員函式: classmethod ZoneInfo.clear_cache (*, only_keys=None)

     一个可在 ‘ZoneInfo’ 类上禁用缓存的方法。 如果不传入参数，则会禁用所
     有缓存并且下次对每个键调用主构造器将返回一个新实例。

     如果将一个键名称的可迭代对象传给 ‘only_keys’ 形参，则将只有指定的键
     会被从缓存中移除。 传给 ‘only_keys’ 但在缓存中找不到的键会被忽略。

          警告: 发起调用此函数可能会以令人惊讶的方式改变使用 ‘ZoneInfo’
          的日期时间对象的语义；这会修改进程范围内的全局状态并因此可能产
          生大范围的影响。 只有在你确定你的需求时才使用它。

该类具有一个属性:

 -- 屬性: ZoneInfo.key

     这是一个只读的 *note attribute: 1a4a.，它返回传给构造器的 ‘key’ 的
     值，该值应为一个 IANA 时区数据库的查找键 (例如 ‘America/New_York’,
     ‘Europe/Paris’ 或 ‘Asia/Tokyo’)。

     对于不指定 ‘key’ 形参而是基于文件构造时区，该属性将设为 ‘None’。

          備註: 尽管将这些信息暴露给最终用户是一种比较普通的做法，但是这
          些值被设计作为代表相关时区的主键而不一定是面向用户的元素。
          CLDR (Unicode 通用区域数据存储库) 之类的项目可被用来根据这些键
          获取更为用户友好的字符串。

* Menu:

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


File: python.info,  Node: 字符串表示,  Next: 封存序列化,  Up: ZoneInfo 类

5.8.2.8 字符串表示
..................

当在 *note ZoneInfo: 17f. 对象上调用 *note str: 205. 时返回的字符串表示
默认会使用 *note ZoneInfo.key: 1a49. 属性（参见该属性文档中的用法注释）:

     >>> 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]'

对于基于文件而非指定 ‘key’ 形参所构建的对象，‘str’ 会回退为调用 *note
repr(): 8b9.。 ‘ZoneInfo’ 的 ‘repr’ 是由具体实现定义的并且不一定会在不同
版本间保持稳定，但它保证不会是一个有效的 ‘ZoneInfo’ 键。


File: python.info,  Node: 封存序列化,  Prev: 字符串表示,  Up: ZoneInfo 类

5.8.2.9 封存序列化
..................

‘ZoneInfo’ 对象的序列化是基于键的，而不是序列化所有过渡数据，并且基于文
件构造的 ‘ZoneInfo’ 对象（即使是指定了 ‘key’ 值的对象）不能被封存。

‘ZoneInfo’ 文件的行为取决于它的构造方式:

  1. ‘ZoneInfo(key)’: 当使用主构造器构造时，会基于键序列化一个
     ‘ZoneInfo’ 对象，而当反序列化时，反序列化过程会使用主构造器，因此预
     期它们与其他对同一时区的引用会是同一对象。 例如，如果
     ‘europe_berlin_pkl’ 是一个包含基于 ‘ZoneInfo("Europe/Berlin")’ 构建
     的封存数据的字符串，你可以预期出现以下的行为:

          >>> a = ZoneInfo("Europe/Berlin")
          >>> b = pickle.loads(europe_berlin_pkl)
          >>> a is b
          True

  2. ‘ZoneInfo.no_cache(key)’: 当通过绕过缓存的构造器构造时，‘ZoneInfo’
     对象也会基于键序列化，但当反序列化时，反序列化过程会使用绕过缓存的
     构造器。 如果 ‘europe_berlin_pkl_nc’ 是一个包含基于
     ‘ZoneInfo.no_cache("Europe/Berlin")’ 构造的封存数据的字符串，你可以
     预期出现以下的行为:

          >>> a = ZoneInfo("Europe/Berlin")
          >>> b = pickle.loads(europe_berlin_pkl_nc)
          >>> a is b
          False

  3. ‘ZoneInfo.from_file(fobj, /, key=None)’: 当通过文件构造时，
     ‘ZoneInfo’ 对象会在封存时引发异常。 如果最终用户想要封存通过文件构
     造的 ‘ZoneInfo’，则推荐他们使用包装类型或自定义序列化函数：或者基于
     键序列化，或者存储文件对象的内容并将其序列化。

该序列化方法要求所需键的时区数据在序列化和反序列化中均可用，类似于在序列
化和反序列化环境中都预期存在对类和函数的引用的方式。 这还意味着在具有不
同时区数据版本的环境中当解封被封存的 ‘ZoneInfo’ 时并不会保证结果的一致性
。


File: python.info,  Node: 函数<2>,  Next: 全局变量,  Prev: ZoneInfo 类,  Up: zoneinfo --- IANA 时区支持

5.8.2.10 函数
.............

 -- 函式: zoneinfo.available_timezones ()

     获取一个包含可用 IANA 时区的在时区路径的任何位置均可用的全部有效键
     的集合。 每次调用该函数时都会重新计算。

     此函数仅包括规范时区名称而不包括“特殊”时区如位于 ‘posix/’ 和
     ‘right/’ 目录下的时区或 ‘posixrules’ 时区。

          警示: 此函数可能会打开大量的文件，因为确定时区路径上某个文件是
          否为有效时区的最佳方式是读取开头位置的“魔术字符串”。

          備註: 这些值并不被设计用来对外公开给最终用户；对于面向用户的元
          素，应用程序应当使用 CLDR (Unicode 通用区域数据存储库) 之类来
          获取更为用户友好的字符串。 另请参阅 *note ZoneInfo.key: 1a49.
          中的提示性说明。

 -- 函式: zoneinfo.reset_tzpath (to=None)

     设置或重置模块的时区搜索路径 (*note TZPATH: 1a3a.)。 当不带参数调用
     时，*note TZPATH: 1a3a. 会被设为默认值。

     调用 ‘reset_tzpath’ 将不会使 *note ZoneInfo: 17f. 缓存失效，因而在
     缓存未命中的情况下对主 ‘ZoneInfo’ 构造器的调用将只使用新的
     ‘TZPATH’。

     ‘to’ 形参必须是由字符串或 *note os.PathLike: 5e5. 组成的 *note
     sequence: 135c. 或而不是字符串，它们必须都是绝对路径。 如果所传入的
     不是绝对路径则将引发 *note ValueError: 16d.。


File: python.info,  Node: 全局变量,  Next: 异常与警告,  Prev: 函数<2>,  Up: zoneinfo --- IANA 时区支持

5.8.2.11 全局变量
.................

 -- Data: zoneinfo.TZPATH

     一个表示时区搜索路径的只读序列 – 当通过键构造 ‘ZoneInfo’ 时，键会与
     ‘TZPATH’ 中的每个条目进行合并，并使用所找到的第一个文件。

     ‘TZPATH’ 可以只包含绝对路径，绝不包含相对路径，无论它是如何配置的。

     ‘zoneinfo.TZPATH’ 所指向的对象可能随着对 *note reset_tzpath():
     1a3e. 的调用而改变，因此推荐使用 ‘zoneinfo.TZPATH’ 而不是从
     ‘zoneinfo’ 导入 ‘TZPATH’ 或是将 ‘zoneinfo.TZPATH’ 赋值给一个长期变
     量。

     有关配置时区搜索路径的更多信息，请参阅 *note 配置数据源: 1a39.。


File: python.info,  Node: 异常与警告,  Prev: 全局变量,  Up: zoneinfo --- IANA 时区支持

5.8.2.12 异常与警告
...................

 -- 例外: zoneinfo.ZoneInfoNotFoundError

     当一个 *note ZoneInfo: 17f. 对象的构造由于在系统中找不到指定的键而
     失败时引发。 这是 *note KeyError: 3e9. 的一个子类。

 -- 例外: zoneinfo.InvalidTZPathWarning

     当 *note PYTHONTZPATH: 1a41. 包含将被过滤掉的无效组件，例如一个相对
     路径时引发。


File: python.info,  Node: calendar --- 日历相关函数,  Next: collections --- 容器資料型態,  Prev: zoneinfo --- IANA 时区支持,  Up: 数据类型

5.8.3 ‘calendar’ — 日历相关函数
-------------------------------

`源代码：' Lib/calendar.py(1)

__________________________________________________________________

这个模块让你可以输出像 Unix ‘cal’ 那样的日历，它还提供了其它与日历相关的
实用函数。 默认情况下，这些日历把星期一当作一周的第一天，星期天为一周的
最后一天（按照欧洲惯例）。 可以使用 *note setfirstweekday(): 1a53. 方法
设置一周的第一天为星期天 (6) 或者其它任意一天。 使用整数作为指定日期的参
数。 更多相关的函数，参见 *note datetime: 30. 和 *note time: 10c. 模块。

在这个模块中定义的函数和类都基于一个理想化的日历，现行公历向过去和未来两
个方向无限扩展。这与 Dershowitz 和 Reingold 的书 "历法计算" 中所有计算的
基本日历 – "proleptic Gregorian" 日历的定义相符合。 ISO 8601标准还规定了
0 和 负数年份。0年指公元前1年， -1年指公元前2年，依此类推。

 -- 類別: calendar.Calendar (firstweekday=0)

     创建一个 *note Calendar: 1a54. 对象。 `firstweekday' 是一个整数，用
     于指定一周的第一天。 ‘0’ 是星期一（默认值），‘6’ 是星期天。

     *note Calendar: 1a54. 对象提供了一些可被用于准备日历数据格式化的方
     法。 这个类本身不执行任何格式化操作。 这部分任务应由子类来完成。

     *note Calendar: 1a54. 类的实例有下列方法：

      -- 成員函式: iterweekdays ()

          返回一个迭代器，迭代器的内容为一星期的数字。迭代器的第一个值与
          *note firstweekday: 1a56. 属性的值一至。

      -- 成員函式: itermonthdates (year, month)

          返回一个迭代器，迭代器的内容为 `year' 年 `month' 月(1-12)的日
          期。这个迭代器返回当月的所有日期 ( *note datetime.date: 19d. 对
          象)，日期包含了本月头尾用于组成完整一周的日期。

      -- 成員函式: itermonthdays (year, month)

          返回一个迭代器，迭代器的内容与 *note itermonthdates(): 5a0. 类
          似，为 `year' 年 `month' 月的日期，但不受 *note datetime.date:
          19d. 范围限制。返回的日期为当月每一天的日期对应的天数。对于不
          在当月的日期，显示为 ‘0’。

      -- 成員函式: itermonthdays2 (year, month)

          返回一个迭代器，迭代器的内容与 *note itermonthdates(): 5a0. 类
          似为 `year' 年 `month' 月的日期，但不受 *note datetime.date:
          19d. 范围的限制。迭代器中的元素为一个由日期和代表星期几的数字
          组成的的元组。

      -- 成員函式: itermonthdays3 (year, month)

          返回一个迭代器，迭代器的内容与 *note itermonthdates(): 5a0. 类
          似为 `year' 年 `month' 月的日期，但不受 *note datetime.date:
          19d. 范围的限制。迭代器的元素为一个由年，月，日组成的元组。

          3.7 版新加入.

      -- 成員函式: itermonthdays4 (year, month)

          返回一个迭代器，迭代器的内容与 *note itermonthdates(): 5a0. 类
          似为 `year' 年 `month' 月的日期，但不受 *note datetime.date:
          19d. 范围的限制。迭代器的元素为一个由年，月，日和代表星期几的
          数字组成的元组。

          3.7 版新加入.

      -- 成員函式: monthdatescalendar (year, month)

          返回一个表示指定年月的周列表。周列表由七个 *note
          datetime.date: 19d. 对象组成。

      -- 成員函式: monthdays2calendar (year, month)

          返回一个表示指定年月的周列表。周列表由七个代表日期的数字和代表
          周几的数字组成的二元元组。

      -- 成員函式: monthdayscalendar (year, month)

          返回一个表示指定年月的周列表。周列表由七个代表日期的数字组成。

      -- 成員函式: yeardatescalendar (year, width=3)

          返回可以用来格式化的指定年月的数据。返回的值是一个列表，列表是
          月份组成的行。每一行包含了最多 `width' 个月(默认为3)。每个月包
          含了4到6周，每周包含1–7天。每一天使用 *note datetime.date:
          19d. 对象。

      -- 成員函式: yeardays2calendar (year, width=3)

          返回可以用来模式化的指定年月的数据(与 *note
          yeardatescalendar(): 1a5c. 类似)。周列表的元素是由表示日期的数
          字和表示星期几的数字组成的元组。不在这个月的日子为0。

      -- 成員函式: yeardayscalendar (year, width=3)

          返回可以用来模式化的指定年月的数据(与 *note
          yeardatescalendar(): 1a5c. 类似)。周列表的元素是表示日期的数字
          。不在这个月的日子为0。

 -- 類別: calendar.TextCalendar (firstweekday=0)

     可以使用这个类生成纯文本日历。

     *note TextCalendar: 1a5f. 实例有以下方法：

      -- 成員函式: formatmonth (theyear, themonth, w=0, l=0)

          返回一个多行字符串来表示指定年月的日历。`w' 为日期的宽度，但始
          终保持日期居中。`l' 指定了每星期占用的行数。以上这些还依赖于构
          造器或者 *note setfirstweekday(): 1a53. 方法指定的周的第一天是
          哪一天。

      -- 成員函式: prmonth (theyear, themonth, w=0, l=0)

          与 *note formatmonth(): 1a60. 方法一样，返回一个月的日历。

      -- 成員函式: formatyear (theyear, w=2, l=1, c=6, m=3)

          返回一个多行字符串，这个字符串为一个 `m' 列日历。可选参数 `w',
          `l', 和 `c' 分别表示日期列数， 周的行数， 和月之间的间隔。同样
          ，以上这些还依赖于构造器或者 *note setfirstweekday(): 1a53. 指
          定哪一天为一周的第一天。日历的第一年由平台依赖于使用的平台。

      -- 成員函式: pryear (theyear, w=2, l=1, c=6, m=3)

          与 *note formatyear(): 1a62. 方法一样，返回一整年的日历。

 -- 類別: calendar.HTMLCalendar (firstweekday=0)

     可以使用这个类生成 HTML 日历。

     ‘HTMLCalendar’ 实例有以下方法：

      -- 成員函式: formatmonth (theyear, themonth, withyear=True)

          返回一个 HTML 表格作为指定年月的日历。 `withyear' 为真，则年份
          将会包含在表头，否则只显示月份。

      -- 成員函式: formatyear (theyear, width=3)

          返回一个 HTML 表格作为指定年份的日历。 `width' (默认为3) 用于
          规定每一行显示月份的数量。

      -- 成員函式: formatyearpage (theyear, width=3, css='calendar.css',
               encoding=None)

          返回一个完整的 HTML 页面作为指定年份的日历。 `width*(默认为3)
          用于规定每一行显示的月份数量。 *css' 为层叠样式表的名字。如果
          不使用任何层叠样式表，可以使用 *note None: 203. 。 `encoding'
          为输出页面的编码 (默认为系统的默认编码)。

     ‘HTMLCalendar’ 有以下属性，你可以重载它们来自定义应用日历的样式。

      -- 屬性: cssclasses

          一个对应星期一到星期天的 CSS class 列表。默认列表为

               cssclasses = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]

          可以向每天加入其它样式

               cssclasses = ["mon text-bold", "tue", "wed", "thu", "fri", "sat", "sun red"]

          需要注意的是，列表的长度必须为7。

      -- 屬性: cssclass_noday

          工作日的 CSS 类在上个月或下个月发生。

          3.7 版新加入.

      -- 屬性: cssclasses_weekday_head

          用于标题行中的工作日名称的 CSS 类 列表。默认值与 *note
          cssclasses: 1a67. 相同。

          3.7 版新加入.

      -- 屬性: cssclass_month_head

          月份的头 CSS 类（由 ‘formatmonthname()’ 使用）。默认值为
          ‘"month"’ 。

          3.7 版新加入.

      -- 屬性: cssclass_month

          某个月的月历的 CSS 类（由 *note formatmonth(): 1a64. 使用）。
          默认值为 ‘"month"’ 。

          3.7 版新加入.

      -- 屬性: cssclass_year

          某年的年历的 CSS 类（由 *note formatyear(): 1a65. 使用）。默认
          值为 ‘"year"’ 。

          3.7 版新加入.

      -- 屬性: cssclass_year_head

          年历的·表头 CSS 类（由 *note formatyear(): 1a65. 使用）。默认
          值为 ‘"year"’ 。

          3.7 版新加入.

     需要注意的是，尽管上面命名的样式类都是单独出现的(如：
     ‘cssclass_month’ ‘cssclass_noday’), 但我们可以使用空格将样式类列表
     中的多个元素分隔开，例如：

          "text-bold text-red"

     下面是一个如何自定义 ‘HTMLCalendar’ 的示例

          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"

 -- 類別: calendar.LocaleTextCalendar (firstweekday=0, locale=None)

     这个子类 *note TextCalendar: 1a5f. 可以在构造函数中传递一个语言环境
     名称，并且返回月份和星期几的名称在特定语言环境中。如果此语言环境包
     含编码，则包含月份和工作日名称的所有字符串将作为 unicode 返回。

 -- 類別: calendar.LocaleHTMLCalendar (firstweekday=0, locale=None)

     This subclass of *note HTMLCalendar: 477. 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.

     備註: 这两个类的 ‘formatweekday()’ 和 ‘formatmonthname()’ 方法临时
     更改dang当前区域至给定 `locale' 。由于当前的区域设置是进程范围的设
     置，因此它们不是线程安全的。

对于简单的文本日历，这个模块提供了以下方法。

 -- 函式: calendar.setfirstweekday (weekday)

     设置每一周的开始(‘0’ 表示星期一，‘6’ 表示星期天)。calendar还提供了
     ‘MONDAY’, ‘TUESDAY’, ‘WEDNESDAY’, ‘THURSDAY’, ‘FRIDAY’, ‘SATURDAY’
     和 ‘SUNDAY’ 几个常量方便使用。例如，设置每周的第一天为星期天

          import calendar
          calendar.setfirstweekday(calendar.SUNDAY)

 -- 函式: calendar.firstweekday ()

     返回当前设置的每星期的第一天的数值。

 -- 函式: calendar.isleap (year)

     如果 `year' 是闰年则返回 *note True: 593. ,否则返回 *note False:
     48e.。

 -- 函式: calendar.leapdays (y1, y2)

     返回在范围 `y1' 至 `y2' （包含 y1 和 y2 ）之间的闰年的年数，其中
     `y1' 和 `y2' 是年份。

     此函数适用于跨越一个世纪变化的范围。

 -- 函式: calendar.weekday (year, month, day)

     返回某年（ ‘1970’ – ...），某月（ ‘1’ – ‘12’ ），某日（ ‘1’ – ‘31’
     ）是星期几（ ‘0’ 是星期一）。

 -- 函式: calendar.weekheader (n)

     返回一个包含星期几的缩写名的头。 `n' 指定星期几缩写的字符宽度。

 -- 函式: calendar.monthrange (year, month)

     返回指定 `年份' 的指定 `月份' 的第一天是星期几和这个月的天数。

 -- 函式: calendar.monthcalendar (year, month)

     返回表示一个月的日历的矩阵。 每一行代表一周；此月份外的日子由零表示
     。 每周从周一开始，除非使用 *note setfirstweekday(): 1a53. 改变设置
     。

 -- 函式: calendar.prmonth (theyear, themonth, w=0, l=0)

     打印由 *note month(): 1a77. 返回的一个月的日历。

 -- 函式: calendar.month (theyear, themonth, w=0, l=0)

     使用 *note TextCalendar: 1a5f. 类的 ‘formatmonth()’ 以多行字符串形
     式返回月份日历。

 -- 函式: calendar.prcal (year, w=0, l=0, c=6, m=3)

     打印由 *note calendar(): 14. 返回的整年的日历。

 -- 函式: calendar.calendar (year, w=2, l=1, c=6, m=3)

     使用 *note TextCalendar: 1a5f. 类的 ‘formatyear()’ 返回整年的3列的
     日历以多行字符串的形式。

 -- 函式: calendar.timegm (tuple)

     一个不相关但很好用的函数，它接受一个时间元组例如 *note time: 10c. 模
     块中的 *note gmtime(): c11. 函数的返回并返回相应的 Unix 时间戳值，
     假定 1970 年开始计数， POSIX 编码。实际上， *note time.gmtime():
     c11. 和 *note timegm(): 1a7a. 是彼此相反的。

*note calendar: 14. 模块包含以下数据属性：

 -- Data: calendar.day_name

     在当前语言环境下表示星期几的数组。

 -- Data: calendar.day_abbr

     在当前语言环境下表示星期几缩写的数组。

 -- Data: calendar.month_name

     在当前语言环境下表示一年中月份的数组。这遵循一月的月号为 1 的通常惯
     例，所以它的长度为 13 且 ‘month_name[0]’ 是空字符串。

 -- Data: calendar.month_abbr

     在当前语言环境下表示月份简写的数组。这遵循一月的月号为 1 的通常惯例
     ，所以它的长度为 13 且 ‘month_abbr[0]’ 是空字符串。

也參考
......

模块 *note datetime: 30.

     为日期和时间提供与 *note time: 10c. 模块相似功能的面向对象接口。

模块 *note time: 10c.

     底层时间相关函数。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/calendar.py


File: python.info,  Node: collections --- 容器資料型態,  Next: collections abc --- 容器的抽象基类,  Prev: calendar --- 日历相关函数,  Up: 数据类型

5.8.4 ‘collections’ — 容器資料型態
----------------------------------

`原始碼：' Lib/collections/__init__.py(1)

__________________________________________________________________

這個模組實作了一些特別的容器資料型態，用來替代 Python 一般內建的容器，例
如 *note dict: 164. 、 *note list: 1f8. 、 *note set: 1f6. 和 *note
tuple: 1a2. 。

*note namedtuple(): 1a1.  用來建立一個欄位擁有名字的 tuple 子類別的函數
                          
                          
*note deque: 62a.         一個類似 list 的容器，可以快速的在頭尾加入元素與取出元素。
                          
                          
*note ChainMap: 5a3.      一個像是 dict 的類別，用來為多個 mapping 建立單一的 view 。
                          
                          
*note Counter: ab9.       dict 的子類別，用來計算可 hash 物件的數量。
                          
                          
*note OrderedDict: 2ea.   dict 的子類別，會記錄物件被加入的順序。
                          
                          
*note defaultdict: c0c.   dict 的子類別，在值不存在 dict 當中時會呼叫一個產生函式。
                          
                          
*note UserDict: 1081.     封装了字典对象，简化了字典子类化
                          
                          
*note UserList: 1a81.     封装了列表对象，简化了列表子类化
                          
                          
*note UserString: 7a0.    封装了字符串对象，简化了字符串子类化
                          

Deprecated since version 3.3, will be removed in version 3.10: 已将
*note 容器抽象基类: 15e. 移至 *note collections.abc: 1e. 模块。 为了保持
向下兼容性，它们在 Python 3.9 版的这个模块中仍然存在。

* Menu:

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

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/Lib/collections/__init__.py


File: python.info,  Node: ChainMap objects,  Next: Counter 物件,  Up: collections --- 容器資料型態

5.8.4.1 ‘ChainMap’ objects
..........................

3.3 版新加入.

一个 *note ChainMap: 5a3. 类是为了将多个映射快速的链接到一起，这样它们就
可以作为一个单元处理。它通常比创建一个新字典和多次调用 *note update():
e8e. 要快很多。

这个类可以用于模拟嵌套作用域，并且在模版化的时候比较有用。

 -- 類別: collections.ChainMap (*maps)

     一个 *note ChainMap: 5a3. 将多个字典或者其他映射组合在一起，创建一
     个单独的可更新的视图。 如果没有 `maps' 被指定，就提供一个默认的空字
     典，这样一个新链至少有一个映射。

     底层映射被存储在一个列表中。这个列表是公开的，可以通过 `maps' 属性
     存取和更新。没有其他的状态。

     搜索查询底层映射，直到一个键被找到。不同的是，写，更新和删除只操作
     第一个映射。

     一个 *note ChainMap: 5a3. 通过引用合并底层映射。 所以，如果一个底层
     映射更新了，这些更改会反映到 *note ChainMap: 5a3. 。

     支持所有常用字典方法。另外还有一个 `maps' 属性(attribute)，一个创建
     子上下文的方法(method)， 一个存取它们首个映射的属性(property):

      -- 屬性: maps

          一个可以更新的映射列表。这个列表是按照第一次搜索到最后一次搜索
          的顺序组织的。它是仅有的存储状态，可以被修改。列表最少包含一个
          映射。

      -- 成員函式: new_child (m=None)

          返回一个新的 *note ChainMap: 5a3. 类，包含了一个新映射(map)，
          后面跟随当前实例的全部映射(map)。如果 ‘m’ 被指定，它就成为不同
          新的实例，就是在所有映射前加上 m，如果没有指定，就加上一个空字
          典，这样的话一个 ‘d.new_child()’ 调用等价于 ‘ChainMap({},
          *d.maps)’ 。这个方法用于创建子上下文，不改变任何父映射的值。

          3.4 版更變: 添加了 ‘m’ 可选参数。

      -- 屬性: parents

          属性返回一个新的 *note ChainMap: 5a3. 包含所有的当前实例的映射
          ，除了第一个。这样可以在搜索的时候跳过第一个映射。 使用的场景
          类似在 *note nested scopes: 1721. 嵌套作用域中使用 *note
          nonlocal: d07. 关键词。用例也可以类比内建函数 *note super():
          5dd. 。一个 ‘d.parents’ 的引用等价于 ‘ChainMap(*d.maps[1:])’ 。

     注意，一个 *note ChainMap(): 5a3. 的迭代顺序是通过从后往前扫描所有
     映射来确定的:

          >>> baseline = {'music': 'bach', 'art': 'rembrandt'}
          >>> adjustments = {'art': 'van gogh', 'opera': 'carmen'}
          >>> list(ChainMap(adjustments, baseline))
          ['music', 'art', 'opera']

     这给出了与 *note dict.update(): e8e. 调用序列相同的顺序，从最后一个
     映射开始:

          >>> combined = baseline.copy()
          >>> combined.update(adjustments)
          >>> list(combined)
          ['music', 'art', 'opera']

     3.9 版更變: 增加了对 ‘|’ 和 ‘|=’ 运算符的支持，相关说明见 PEP
     584(1)。

也參考
......

   * MultiContext class(2) 在 Enthought CodeTools package(3) 有支持写映
     射的选项。

   * Django 中用于模板的 Context class(4) 是只读的映射链。 它还具有上下
     文推送和弹出特性，类似于 *note new_child(): 916. 方法和 *note
     parents: 1a84. 特征属性。

   * Nested Contexts recipe(5) 提供了是否对第一个映射或其他映射进行写和
     其他修改的选项。

   * 一个 极简的只读版 Chainmap(6).

* Menu:

* ChainMap 例子和方法::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0584

   (2) 
https://github.com/enthought/codetools/blob/4.0.0/codetools/contexts/multi_context.py

   (3) https://github.com/enthought/codetools

   (4) 
https://github.com/django/django/blob/main/django/template/context.py

   (5) https://code.activestate.com/recipes/577434/

   (6) https://code.activestate.com/recipes/305268/


File: python.info,  Node: ChainMap 例子和方法,  Up: ChainMap objects

5.8.4.2 ‘ChainMap’ 例子和方法
.............................

这一节提供了多个使用链映射的案例。

模拟Python内部lookup链的例子

     import builtins
     pylookup = ChainMap(locals(), globals(), vars(builtins))

让用户指定的命令行参数优先于环境变量，优先于默认值的例子

     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'])

用 *note ChainMap: 5a3. 类模拟嵌套上下文的例子

     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

*note ChainMap: 5a3. 类只更新链中的第一个映射，但lookup会搜索整个链。 然
而，如果需要深度写和删除，也可以很容易的通过定义一个子类来实现它

     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'})


File: python.info,  Node: Counter 物件,  Next: deque 对象,  Prev: ChainMap objects,  Up: collections --- 容器資料型態

5.8.4.3 ‘Counter’ 物件
......................

提供一個計數工具支援方便且快速的對應 ，舉例：

     >>> # 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)]

 -- 類別: collections.Counter ([iterable-or-mapping])

     一个 *note Counter: ab9. 是一个 *note dict: 164. 的子类，用于计数可
     哈希对象。它是一个集合，元素像字典键(key)一样存储，它们的计数存储为
     值。计数可以是任何整数值，包括0和负数。 *note Counter: ab9. 类有点
     像其他语言中的 bags或multisets。

     被計數的元素來自一個 `iterable' 或是被其他的 `mapping' (or counter)
     初始化。

          >>> 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

     Counter 物件擁有一個字典的使用介面，除了遇到 Counter 中沒有的值時會
     回傳計數 0 取代 *note KeyError: 3e9. 這點不同。

          >>> c = Counter(['eggs', 'ham'])
          >>> c['bacon']                              # count of a missing element is zero
          0

     將一個值的計數設為 0 並不會真的從 counter 中刪除這個元素，使用
     ‘del’ 來刪除元素。

          >>> c['sausage'] = 0                        # counter entry with a zero count
          >>> del c['sausage']                        # del actually removes the entry

     3.1 版新加入.

     3.7 版更變: 作为 *note dict: 164. 的子类，*note Counter: ab9. 继承
     了记住插入顺序的功能。 `Counter' 对象进行数学运算时同样会保持顺序。
     结果会先按每个元素在运算符左边的出现时间排序，然后再按其在运算符右
     边的出现时间排序。

     除了字典的方法外，Counter 物件額外支援三個新方法。

      -- 成員函式: elements ()

          返回一个迭代器，其中每个元素将重复出现计数值所指定次。 元素会
          按首次出现的顺序返回。 如果一个元素的计数值小于一，*note
          elements(): d62. 将会忽略它。

               >>> c = Counter(a=4, b=2, c=0, d=-2)
               >>> sorted(c.elements())
               ['a', 'a', 'a', 'a', 'b', 'b']

      -- 成員函式: most_common ([n])

          返回一个列表，其中包含 `n' 个最常见的元素及出现次数，按常见程
          度由高到低排序。 如果 `n' 被省略或为 ‘None’，*note
          most_common(): d61. 将返回计数器中的 `所有' 元素。 计数值相等
          的元素按首次出现的顺序排序：

               >>> Counter('abracadabra').most_common(3)
               [('a', 5), ('b', 2), ('r', 2)]

      -- 成員函式: subtract ([iterable-or-mapping])

          从 `迭代对象' 或 `映射对象' 减去元素。像 *note dict.update():
          e8e. 但是是减去，而不是替换。输入和输出都可以是0或者负数。

               >>> 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})

          3.2 版新加入.

     通常字典方法都可用于 *note Counter: ab9. 对象，除了有两个方法工作方
     式与字典并不相同。

      -- 成員函式: fromkeys (iterable)

          这个类方法没有在 *note Counter: ab9. 中实现。

      -- 成員函式: update ([iterable-or-mapping])

          从 `迭代对象' 计数元素或者 从另一个 `映射对象' (或计数器) 添加
          。 像 *note dict.update(): e8e. 但是是加上，而不是替换。另外，
          `迭代对象' 应该是序列元素，而不是一个 ‘(key, value)’ 对。

*note Counter: ab9. 对象的常用案例

     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

提供了几个数学操作，可以结合 *note Counter: ab9. 对象，以生产 multisets
(计数器中大于0的元素）。 加和减，结合计数器，通过加上或者减去元素的相应
计数。交集和并集返回相应计数的最小或最大值。每种操作都可以接受带符号的计
数，但是输出会忽略掉结果为零或者小于零的计数。

     >>> 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})

单目加和减（一元操作符）意思是从空计数器加或者减去。

     >>> c = Counter(a=2, b=-4)
     >>> +c
     Counter({'a': 2})
     >>> -c
     Counter({'b': 4})

3.3 版新加入: 添加了对一元加，一元减和位置集合操作的支持。

     備註: 计数器主要是为了表达运行的正的计数而设计；但是，小心不要预先
     排除负数或者其他类型。为了帮助这些用例，这一节记录了最小范围和类型
     限制。

        * *note Counter: ab9. 类是一个字典的子类，不限制键和值。值用于表
          示计数，但你实际上 `可以' 存储任何其他值。

        * *note most_common(): d61. 方法在值需要排序的时候用。

        * 原地操作比如 ‘c[key] += 1’ ， 值类型只需要支持加和减。 所以分
          数，小数，和十进制都可以用，负值也可以支持。这两个方法 *note
          update(): 1a88. 和 *note subtract(): c2c. 的输入和输出也一样支
          持负数和0。

        * Multiset多集合方法只为正值的使用情况设计。输入可以是负数或者
          0，但只输出计数为正的值。没有类型限制，但值类型需要支持加，减
          和比较操作。

        * *note elements(): d62. 方法要求正整数计数。忽略0和负数计数。

也參考
......

   * Bag class(1) 在 Smalltalk。

   * Wikipedia 链接 Multisets(2).

   * C++ multisets(3) 教程和例子。

   * 数学操作和多集合用例，参考 `Knuth, Donald.  The Art of Computer
     Programming Volume II, Section 4.6.3, Exercise 19' 。

   * 在给定数量和集合元素枚举所有不同的多集合，参考 *note
     itertools.combinations_with_replacement(): ce3.

          map(Counter, combinations_with_replacement('ABC', 2)) # --> AA AB AC BB BC CC

   ---------- Footnotes ----------

   (1) 
https://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html

   (2) https://en.wikipedia.org/wiki/Multiset

   (3) 
http://www.java2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm


File: python.info,  Node: deque 对象,  Next: defaultdict 对象,  Prev: Counter 物件,  Up: collections --- 容器資料型態

5.8.4.4 ‘deque’ 对象
....................

 -- 類別: collections.deque ([iterable[, maxlen]])

     返回一个新的双向队列对象，从左到右初始化(用方法 *note append():
     1a8a.) ，从 `iterable' （迭代对象) 数据创建。如果 `iterable' 没有指
     定，新队列为空。

     Deque队列是由栈或者queue队列生成的（发音是 “deck”，”double-ended
     queue”的简称）。Deque 支持线程安全，内存高效添加(append)和弹出
     (pop)，从两端都可以，两个方向的大概开销都是 O(1) 复杂度。

     虽然 *note list: 1f8. 对象也支持类似操作，不过这里优化了定长操作和
     ‘pop(0)’ 和 ‘insert(0, v)’ 的开销。它们引起 O(n) 内存移动的操作，改
     变底层数据表达的大小和位置。

     如果 `maxlen' 没有指定或者是 ‘None’ ，deques 可以增长到任意长度。否
     则，deque就限定到指定最大长度。一旦限定长度的deque满了，当新项加入
     时，同样数量的项就从另一端弹出。限定长度deque提供类似Unix filter
     ‘tail’ 的功能。它们同样可以用与追踪最近的交换和其他数据池活动。

     双向队列(deque)对象支持以下方法：

      -- 成員函式: append (x)

          添加 `x' 到右端。

      -- 成員函式: appendleft (x)

          添加 `x' 到左端。

      -- 成員函式: clear ()

          移除所有元素，使其长度为0.

      -- 成員函式: copy ()

          创建一份浅拷贝。

          3.5 版新加入.

      -- 成員函式: count (x)

          计算 deque 中元素等于 `x' 的个数。

          3.2 版新加入.

      -- 成員函式: extend (iterable)

          扩展deque的右侧，通过添加iterable参数中的元素。

      -- 成員函式: extendleft (iterable)

          扩展deque的左侧，通过添加iterable参数中的元素。注意，左添加时
          ，在结果中iterable参数中的顺序将被反过来添加。

      -- 成員函式: index (x[, start[, stop]])

          返回 `x' 在 deque 中的位置（在索引 `start' 之后，索引 `stop' 之
          前）。 返回第一个匹配项，如果未找到则引发 *note ValueError:
          16d.。

          3.5 版新加入.

      -- 成員函式: insert (i, x)

          在位置 `i' 插入 `x' 。

          如果插入会导致一个限长 deque 超出长度 `maxlen' 的话，就引发一
          个 *note IndexError: f36.。

          3.5 版新加入.

      -- 成員函式: pop ()

          移去并且返回一个元素，deque 最右侧的那一个。 如果没有元素的话
          ，就引发一个 *note IndexError: f36.。

      -- 成員函式: popleft ()

          移去并且返回一个元素，deque 最左侧的那一个。 如果没有元素的话
          ，就引发 *note IndexError: f36.。

      -- 成員函式: remove (value)

          移除找到的第一个 `value'。 如果没有的话就引发 *note
          ValueError: 16d.。

      -- 成員函式: reverse ()

          将deque逆序排列。返回 ‘None’ 。

          3.2 版新加入.

      -- 成員函式: rotate (n=1)

          向右循环移动 `n' 步。 如果 `n' 是负数，就向左循环。

          如果deque不是空的，向右循环移动一步就等价于
          ‘d.appendleft(d.pop())’ ， 向左循环一步就等价于
          ‘d.append(d.popleft())’ 。

     Deque对象同样提供了一个只读属性:

      -- 屬性: maxlen

          Deque的最大尺寸，如果没有限定的话就是 ‘None’ 。

          3.1 版新加入.

除了以上操作，deque 还支持迭代、封存、‘len(d)’、‘reversed(d)’、
‘copy.copy(d)’、‘copy.deepcopy(d)’、成员检测运算符 *note in: 179. 以及下
标引用例如通过 ‘d[0]’ 访问首个元素等。 索引访问在两端的复杂度均为 O(1) 但
在中间则会低至 O(n)。 如需快速随机访问，请改用列表。

Deque从版本3.5开始支持 ‘__add__()’, ‘__mul__()’, 和 ‘__imul__()’ 。

示例:

     >>> 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'])

* Menu:

* deque 用法::


File: python.info,  Node: deque 用法,  Up: deque 对象

5.8.4.5 ‘deque’ 用法
....................

这一节展示了deque的多种用法。

限长deque提供了类似Unix ‘tail’ 过滤功能

     def tail(filename, n=10):
         'Return the last n lines of a file'
         with open(filename) as f:
             return deque(f, n)

另一个用法是维护一个近期添加元素的序列，通过从右边添加和从左边弹出

     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

一个 轮询调度器(1) 可以通过在 *note deque: 62a. 中放入迭代器来实现。值从
当前迭代器的位置0被取出并暂存(yield)。 如果这个迭代器消耗完毕，就用
*note popleft(): 1a90. 将其从对列中移去；否则，就通过 *note rotate():
1a92. 将它移到队列的末尾

     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()

*note rotate(): 1a92. 方法提供了一种方式来实现 *note deque: 62a. 切片和
删除。 例如， 一个纯的Python ‘del d[n]’ 实现依赖于 ‘rotate()’ 来定位要弹
出的元素

     def delete_nth(d, n):
         d.rotate(-n)
         d.popleft()
         d.rotate(n)

要实现 *note deque: 62a. 切片， 使用一个类似的方法，应用 *note rotate():
1a92. 将目标元素放到左边。通过 *note popleft(): 1a90. 移去老的条目（
entries），通过 *note extend(): 1a8d. 添加新的条目， 然后反向 rotate。这
个方法可以最小代价实现命令式的栈操作，诸如 ‘dup’, ‘drop’, ‘swap’,
‘over’, ‘pick’, ‘rot’, 和 ‘roll’ 。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Round-robin_scheduling


File: python.info,  Node: defaultdict 对象,  Next: namedtuple 命名元组的工厂函数,  Prev: deque 对象,  Up: collections --- 容器資料型態

5.8.4.6 ‘defaultdict’ 对象
..........................

 -- 類別: collections.defaultdict (default_factory=None, /[, ...])

     返回一个新的类似字典的对象。 *note defaultdict: c0c. 是内置 *note
     dict: 164. 类的子类。 它重载了一个方法并添加了一个可写的实例变量。
     其余的功能与 *note dict: 164. 类相同因而不在此文档中写明。

     本对象包含一个名为 *note default_factory: 1a95. 的属性，构造时，第
     一个参数用于为该属性提供初始值，默认为 ‘None’。所有其他参数（包括关
     键字参数）都相当于传递给 *note dict: 164. 的构造函数。

     *note defaultdict: c0c. 对象除了支持标准 *note dict: 164. 的操作，
     还支持以下方法作为扩展：

      -- 成員函式: __missing__ (key)

          如果 *note default_factory: 1a95. 属性为 ‘None’，则调用本方法
          会抛出 *note KeyError: 3e9. 异常，附带参数 `key'。

          如果 *note default_factory: 1a95. 不为 ‘None’，则它会被（不带
          参数地）调用来为 `key' 提供一个默认值，这个值和 `key' 作为一对
          键值对被插入到字典中，并作为本方法的返回值返回。

          如果调用 *note default_factory: 1a95. 时抛出了异常，这个异常会
          原封不动地向外层传递。

          在无法找到所需键值时，本方法会被 *note dict: 164. 中的 *note
          __getitem__(): 3a5. 方法调用。无论本方法返回了值还是抛出了异常
          ，都会被 *note __getitem__(): 3a5. 传递。

          注意，*note __missing__(): 1a96. `不会' 被 *note
          __getitem__(): 3a5. 以外的其他方法调用。意味着 ‘get()’ 会像正
          常的 dict 那样返回 ‘None’，而不是使用 *note default_factory:
          1a95.。

     *note defaultdict: c0c. 对象支持以下实例变量：

      -- 屬性: default_factory

          本属性由 *note __missing__(): 1a96. 方法来调用。如果构造对象时
          提供了第一个参数，则本属性会被初始化成那个参数，如果未提供第一
          个参数，则本属性为 ‘None’。

     3.9 版更變: 增加了合并 (‘|’) 与更新 (‘|=’) 运算符，相关说明见 PEP
     584(1)。

* Menu:

* defaultdict 例子::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0584


File: python.info,  Node: defaultdict 例子,  Up: defaultdict 对象

5.8.4.7 ‘defaultdict’ 例子
..........................

使用 *note list: 1f8. 作为 *note default_factory: 1a95.，很轻松地将（键
-值对组成的）序列转换为（键-列表组成的）字典：

     >>> 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])]

当每个键第一次遇见时，它还没有在字典里面，所以自动创建该条目，即调用
*note default_factory: 1a95. 方法，返回一个空的 *note list: 1f8.。
‘list.append()’ 操作添加值到这个新的列表里。当再次存取该键时，就正常操作
，‘list.append()’ 添加另一个值到列表中。这个计数比它的等价方法 *note
dict.setdefault(): a9e. 要快速和简单：

     >>> d = {}
     >>> for k, v in s:
     ...     d.setdefault(k, []).append(v)
     ...
     >>> sorted(d.items())
     [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

设置 *note default_factory: 1a95. 为 *note int: 204.，使 *note
defaultdict: c0c. 用于计数（类似其他语言中的 bag 或 multiset）：

     >>> s = 'mississippi'
     >>> d = defaultdict(int)
     >>> for k in s:
     ...     d[k] += 1
     ...
     >>> sorted(d.items())
     [('i', 4), ('m', 1), ('p', 2), ('s', 4)]

当一个字母首次遇到时，它会查询失败，则 *note default_factory: 1a95. 会调
用 *note int(): 204. 来提供一个整数 0 作为默认值。后续的自增操作建立起对
每个字母的计数。

函数 *note int(): 204. 总是返回 0，这是常数函数的特殊情况。一个更快和灵
活的方法是使用 lambda 函数，可以提供任何常量值（不只是0）：

     >>> 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>'

设置 *note default_factory: 1a95. 为 *note set: 1f6. 使 *note
defaultdict: c0c. 用于构建 set 集合：

     >>> 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})]


File: python.info,  Node: namedtuple 命名元组的工厂函数,  Next: OrderedDict 对象,  Prev: defaultdict 对象,  Up: collections --- 容器資料型態

5.8.4.8 ‘namedtuple()’ 命名元组的工厂函数
.........................................

命名元组赋予每个位置一个含义，提供可读性和自文档性。它们可以用于任何普通
元组，并添加了通过名字获取值的能力，通过索引值也是可以的。

 -- 函式: collections.namedtuple (typename, field_names, *,
          rename=False, defaults=None, module=None)

     返回一个新的元组子类，名为 `typename' 。这个新的子类用于创建类元组
     的对象，可以通过字段名来获取属性值，同样也可以通过索引和迭代获取值
     。子类实例同样有文档字符串（类名和字段名）另外一个有用的 *note
     __repr__(): 44a. 方法，以 ‘name=value’ 格式列明了元组内容。

     `field_names' 是一个像 ‘[‘x’, ‘y’]’ 一样的字符串序列。另外
     `field_names' 可以是一个纯字符串，用空白或逗号分隔开元素名，比如
     ‘'x y'’ 或者 ‘'x, y'’ 。

     任何有效的Python 标识符都可以作为字段名，除了下划线开头的那些。有效
     标识符由字母，数字，下划线组成，但首字母不能是数字或下划线，另外不
     能是关键词 *note keyword: a6. 比如 `class', `for', `return',
     `global', `pass', 或 `raise' 。

     如果 `rename' 为真， 无效字段名会自动转换成位置名。比如 ‘['abc',
     'def', 'ghi', 'abc']’ 转换成 ‘['abc', '_1', 'ghi', '_3']’ ， 消除关
     键词 ‘def’ 和重复字段名 ‘abc’ 。

     `defaults' 可以为 ‘None’ 或者是一个默认值的 *note iterable: c7c. 。
     如果一个默认值域必须跟其他没有默认值的域在一起出现，`defaults' 就应
     用到最右边的参数。比如如果域名 ‘['x', 'y', 'z']’ 和默认值 ‘(1, 2)’
     ，那么 ‘x’ 就必须指定一个参数值 ，‘y’ 默认值 ‘1’ ， ‘z’ 默认值 ‘2’
     。

     如果 `module' 值有定义，命名元组的 ‘__module__’ 属性值就被设置。

     命名元组实例没有字典，所以它们要更轻量，并且占用更小内存。

     要支持封存操作，应当将命名元组类赋值给一个匹配 `typename' 的变量。

     3.1 版更變: 添加了对 `rename' 的支持。

     3.6 版更變: `verbose' 和 `rename' 参数成为 *note 仅限关键字参数:
     3ce.

     3.6 版更變: 添加了 `module' 参数。

     3.7 版更變: 移除了 `verbose' 形参和 ‘_source’ 属性。

     3.7 版更變: 添加了 `defaults' 参数和 ‘_field_defaults’ 属性。

     >>> # 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)

命名元组尤其有用于赋值 *note csv: 29. *note sqlite3: f2. 模块返回的元组

     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)

除了继承元组的方法，命名元组还支持三个额外的方法和两个属性。为了防止字段
名冲突，方法和属性以下划线开始。

 -- 成員函式: classmethod somenamedtuple._make (iterable)

     类方法从存在的序列或迭代实例创建一个新实例。

          >>> t = [11, 22]
          >>> Point._make(t)
          Point(x=11, y=22)

 -- 成員函式: somenamedtuple._asdict ()

     返回一个新的 *note dict: 164. ，它将字段名称映射到它们对应的值：

          >>> p = Point(x=11, y=22)
          >>> p._asdict()
          {'x': 11, 'y': 22}

     3.1 版更變: 返回一个 *note OrderedDict: 2ea. 而不是 *note dict:
     164. 。

     3.8 版更變: 返回一个常规 *note dict: 164. 而不是 *note OrderedDict:
     2ea.。 因为自 Python 3.7 起，常规字典已经保证有序。 如果需要 *note
     OrderedDict: 2ea. 的额外特性，推荐的解决方案是将结果转换为需要的类
     型: ‘OrderedDict(nt._asdict())’。

 -- 成員函式: somenamedtuple._replace (**kwargs)

     返回一个新的命名元组实例，并将指定域替换为新的值

          >>> 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())

 -- 屬性: somenamedtuple._fields

     字符串元组列出了字段名。用于提醒和从现有元组创建一个新的命名元组类
     型。

          >>> 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)

 -- 屬性: somenamedtuple._field_defaults

     字典将字段名称映射到默认值。

          >>> Account = namedtuple('Account', ['type', 'balance'], defaults=[0])
          >>> Account._field_defaults
          {'balance': 0}
          >>> Account('premium')
          Account(type='premium', balance=0)

要获取这个名字域的值，使用 *note getattr(): 54b. 函数 :

     >>> getattr(p, 'x')
     11

转换一个字典到命名元组，使用 ** 两星操作符 (所述如 *note
拆解引數列表（Unpacking Argument Lists）: 1389.):

     >>> d = {'x': 11, 'y': 22}
     >>> Point(**d)
     Point(x=11, y=22)

因为一个命名元组是一个正常的Python类，它可以很容易的通过子类更改功能。这
里是如何添加一个计算域和定宽输出打印格式:

     >>> 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

上面的子类设置 ‘__slots__’ 为一个空元组。通过阻止创建实例字典保持了较低
的内存开销。

子类化对于添加和存储新的名字域是无效的。应当通过 *note _fields: 1a9b. 创
建一个新的命名元组来实现它:

     >>> Point3D = namedtuple('Point3D', Point._fields + ('z',))

文档字符串可以自定义，通过直接赋值给 ‘__doc__’ 属性:

     >>> 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'

3.5 版更變: 文档字符串属性变成可写。

也參考
......

   * 请参阅 *note typing.NamedTuple: 227. ，以获取为命名元组添加类型提示
     的方法。 它还使用 *note class: d32. 关键字提供了一种优雅的符号:

          class Component(NamedTuple):
              part_number: int
              weight: float
              description: Optional[str] = None

   * 对于以字典为底层的可变域名， 参考 *note types.SimpleNamespace():
     1d8. 。

   * *note dataclasses: 2f. 模块提供了一个装饰器和一些函数，用于自动将生
     成的特殊方法添加到用户定义的类中。


File: python.info,  Node: OrderedDict 对象,  Next: UserDict 对象,  Prev: namedtuple 命名元组的工厂函数,  Up: collections --- 容器資料型態

5.8.4.9 ‘OrderedDict’ 对象
..........................

有序词典就像常规词典一样，但有一些与排序操作相关的额外功能。由于内置的
*note dict: 164. 类获得了记住插入顺序的能力（在 Python 3.7 中保证了这种
新行为），它们变得不那么重要了。

一些与 *note dict: 164. 的不同仍然存在：

   * 常规的 *note dict: 164. 被设计为非常擅长映射操作。 跟踪插入顺序是次
     要的。

   * *note OrderedDict: 2ea. 旨在擅长重新排序操作。 空间效率、迭代速度和
     更新操作的性能是次要的。

   * 算法上， *note OrderedDict: 2ea. 可以比 *note dict: 164. 更好地处理
     频繁的重新排序操作。 这使其适用于跟踪最近的访问（例如在 LRU
     cache(1) 中）。

   * 对于 *note OrderedDict: 2ea. ，相等操作检查匹配顺序。

   * *note OrderedDict: 2ea. 类的 ‘popitem()’ 方法有不同的签名。它接受一
     个可选参数来指定弹出哪个元素。

   * *note OrderedDict: 2ea. 类有一个 ‘move_to_end()’ 方法，可以有效地将
     元素移动到任一端。

   * Python 3.8之前， *note dict: 164. 缺少 *note __reversed__(): 628. 方
     法。

 -- 類別: collections.OrderedDict ([items])

     返回一个 *note dict: 164. 子类的实例，它具有专门用于重新排列字典顺
     序的方法。

     3.1 版新加入.

      -- 成員函式: popitem (last=True)

          有序字典的 *note popitem(): d4c. 方法移除并返回一个 (key,
          value) 键值对。 如果 `last' 值为真，则按 LIFO 后进先出的顺序返
          回键值对，否则就按 FIFO 先进先出的顺序返回键值对。

      -- 成員函式: move_to_end (key, last=True)

          将现有 `key' 移动到有序字典的任一端。 如果 `last' 为真值（默认
          ）则将元素移至末尾；如果 `last' 为假值则将元素移至开头。如果
          `key' 不存在则会触发 *note KeyError: 3e9.:

               >>> d = OrderedDict.fromkeys('abcde')
               >>> d.move_to_end('b')
               >>> ''.join(d.keys())
               'acdeb'
               >>> d.move_to_end('b', last=False)
               >>> ''.join(d.keys())
               'bacde'

          3.2 版新加入.

相对于通常的映射方法，有序字典还另外提供了逆序迭代的支持，通过 *note
reversed(): 2c6. 。

*note OrderedDict: 2ea. 之间的相等测试是顺序敏感的，实现为
‘list(od1.items())==list(od2.items())’ 。 *note OrderedDict: 2ea. 对象和
其他的 *note Mapping: 15f. 的相等测试，是顺序敏感的字典测试。这允许
*note OrderedDict: 2ea. 替换为任何字典可以使用的场所。

3.5 版更變: *note OrderedDict: 2ea. 的项(item)，键(key)和值(value) *note
视图: 1a9e. 现在支持逆序迭代，通过 *note reversed(): 2c6. 。

3.6 版更變: PEP 468(2) 赞成将关键词参数的顺序保留， 通过传递给 *note
OrderedDict: 2ea. 构造器和它的 ‘update()’ 方法。

3.9 版更變: 增加了合并 (‘|’) 与更新 (‘|=’) 运算符，相关说明见 PEP
584(3)。

* Menu:

* OrderedDict 例子和用法::

   ---------- Footnotes ----------

   (1) 
https://medium.com/@krishankantsinghal/my-first-blog-on-medium-583159139237

   (2) https://www.python.org/dev/peps/pep-0468

   (3) https://www.python.org/dev/peps/pep-0584


File: python.info,  Node: OrderedDict 例子和用法,  Up: OrderedDict 对象

5.8.4.10 ‘OrderedDict’ 例子和用法
.................................

创建记住键值 `最后' 插入顺序的有序字典变体很简单。 如果新条目覆盖现有条
目，则原始插入位置将更改并移至末尾:

     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)

一个 *note OrderedDict: 2ea. 对于实现 *note functools.lru_cache(): 2f8.
的变体也很有用:

     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


File: python.info,  Node: UserDict 对象,  Next: UserList 对象,  Prev: OrderedDict 对象,  Up: collections --- 容器資料型態

5.8.4.11 ‘UserDict’ 对象
........................

*note UserDict: 1081. 类是用作字典对象的外包装。对这个类的需求已部分由直
接创建 *note dict: 164. 的子类的功能所替代；不过，这个类处理起来更容易，
因为底层的字典可以作为属性来访问。

 -- 類別: collections.UserDict ([initialdata])

     模拟字典的类。 这个实例的内容保存在一个常规字典中，它可以通过 *note
     UserDict: 1081. 实例的 *note data: 1aa1. 属性来访问。 如果提供了
     `initialdata'，则 *note data: 1aa1. 会用其内容来初始化；请注意对
     `initialdata' 的引用将不会被保留，以允许它被用于其他目的。

     *note UserDict: 1081. 实例提供了以下属性作为扩展方法和操作的支持:

      -- 屬性: data

          一个真实的字典，用于保存 *note UserDict: 1081. 类的内容。


File: python.info,  Node: UserList 对象,  Next: UserString 对象,  Prev: UserDict 对象,  Up: collections --- 容器資料型態

5.8.4.12 ‘UserList’ 对象
........................

这个类封装了列表对象。它是一个有用的基础类，对于你想自定义的类似列表的类
，可以继承和覆盖现有的方法，也可以添加新的方法。这样我们可以对列表添加新
的行为。

对这个类的需求已部分由直接创建 *note list: 1f8. 的子类的功能所替代；不过
，这个类处理起来更容易，因为底层的列表可以作为属性来访问。

 -- 類別: collections.UserList ([list])

     模拟一个列表。这个实例的内容被保存为一个正常列表，通过 *note
     UserList: 1a81. 的 *note data: 1aa3. 属性存取。实例内容被初始化为一
     个 `list' 的copy，默认为 ‘[]’ 空列表。 `list' 可以是迭代对象，比如
     一个Python列表，或者一个 *note UserList: 1a81. 对象。

     *note UserList: 1a81. 提供了以下属性作为可变序列的方法和操作的扩展:

      -- 屬性: data

          一个 *note list: 1f8. 对象用于存储 *note UserList: 1a81. 的内
          容。

`子类化的要求:' *note UserList: 1a81. 的子类需要提供一个构造器，可以无参
数调用，或者一个参数调用。返回一个新序列的列表操作需要创建一个实现类的实
例。它假定了构造器可以以一个参数进行调用，这个参数是一个序列对象，作为数
据源。

如果一个分离的类不希望依照这个需求，所有的特殊方法就必须重写；请参照源代
码进行修改。


File: python.info,  Node: UserString 对象,  Prev: UserList 对象,  Up: collections --- 容器資料型態

5.8.4.13 ‘UserString’ 对象
..........................

*note UserString: 7a0. 类是用作字符串对象的外包装。对这个类的需求已部分
由直接创建 *note str: 205. 的子类的功能所替代；不过，这个类处理起来更容
易，因为底层的字符串可以作为属性来访问。

 -- 類別: collections.UserString (seq)

     模拟一个字符串对象。这个实例对象的内容保存为一个正常字符串，通过
     *note UserString: 7a0. 的 *note data: 1aa5. 属性存取。实例内容初始
     化设置为 `seq' 的copy。`seq' 参数可以是任何可通过内建 *note str():
     205. 函数转换为字符串的对象。

     *note UserString: 7a0. 提供了以下属性作为字符串方法和操作的额外支持
     ：

      -- 屬性: data

          一个真正的 *note str: 205. 对象用来存放 *note UserString: 7a0.
          类的内容。

     3.5 版更變: 新方法 ‘__getnewargs__’, ‘__rmod__’, ‘casefold’,
     ‘format_map’, ‘isprintable’, 和 ‘maketrans’。


File: python.info,  Node: collections abc --- 容器的抽象基类,  Next: heapq --- 堆積佇列 heap queue 演算法,  Prev: collections --- 容器資料型態,  Up: 数据类型

5.8.5 ‘collections.abc’ — 容器的抽象基类
----------------------------------------

3.3 版新加入: 该模块曾是 *note collections: 1d. 模块的组成部分。

`源代码：' Lib/_collections_abc.py(1)

__________________________________________________________________

该模块定义了一些 *note 抽象基类: c05.，它们可用于判断一个具体类是否具有
某一特定的接口；例如，这个类是否可哈希，或其是否为映射类。

3.9 版新加入: These abstract classes now support ‘[]’.  See *note
GenericAlias 类型: fe5. and PEP 585(2).

* Menu:

* 容器抽象基类::

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/Lib/_collections_abc.py

   (2) https://www.python.org/dev/peps/pep-0585


File: python.info,  Node: 容器抽象基类,  Up: collections abc --- 容器的抽象基类

5.8.5.1 容器抽象基类
....................

这个容器模块提供了以下 *note ABCs: c05.:

抽象基类                       继承自                     抽象方法                    Mixin 方法
                                                                                      
-----------------------------------------------------------------------------------------------------------------------------------------------
                                                                                      
*note Container: 181a.                                    ‘__contains__’
                                                          
                                                                                      
*note Hashable: 1aa9.                                     ‘__hash__’
                                                          
                                                                                      
*note Iterable: 1818.                                     ‘__iter__’
                                                          
                                                                                      
*note Iterator: 1819.          *note Iterable: 1818.      ‘__next__’                  ‘__iter__’
                                                                                      
                                                                                      
*note Reversible: 627.         *note Iterable: 1818.      ‘__reversed__’
                                                          
                                                                                      
*note Generator: 7a8.          *note Iterator: 1819.      ‘send’, ‘throw’             ‘close’, ‘__iter__’, ‘__next__’
                                                                                      
                                                                                      
*note Sized: 1aaa.                                        ‘__len__’
                                                          
                                                                                      
*note Callable: 27a.                                      ‘__call__’
                                                          
                                                                                      
*note Collection: 626.         *note Sized: 1aaa,         ‘__contains__’,
                               *note Iterable: 1818,      ‘__iter__’, ‘__len__’
                               *note Container: 181a.     
                               
                                                                                      
*note Sequence: 1764.          *note Reversible: 627,     ‘__getitem__’, ‘__len__’    ‘__contains__’, ‘__iter__’, ‘__reversed__’, ‘index’,
                               *note Collection: 626.                                 and ‘count’
                                                                                      
                                                                                      
*note MutableSequence: 79f.    *note Sequence: 1764.      ‘__getitem__’,              继承自 *note Sequence: 1764. 的方法，以及 ‘append’,
                                                          ‘__setitem__’,              ‘reverse’, ‘extend’, ‘pop’, ‘remove’，和 ‘__iadd__’
                                                          ‘__delitem__’, ‘__len__’,   
                                                          ‘insert’
                                                          
                                                                                      
*note ByteString: 181c.        *note Sequence: 1764.      ‘__getitem__’, ‘__len__’    继承自 *note Sequence: 1764. 的方法
                                                                                      
                                                                                      
*note Set: 1810.               *note Collection: 626.     ‘__contains__’,             ‘__le__’, ‘__lt__’, ‘__eq__’, ‘__ne__’, ‘__gt__’,
                                                          ‘__iter__’, ‘__len__’       ‘__ge__’, ‘__and__’, ‘__or__’, ‘__sub__’, ‘__xor__’,
                                                                                      and ‘isdisjoint’
                                                                                      
                                                                                      
*note MutableSet: 181b.        *note Set: 1810.           ‘__contains__’,             继承自 *note Set: 1810. 的方法以及 ‘clear’, ‘pop’,
                                                          ‘__iter__’, ‘__len__’,      ‘remove’, ‘__ior__’, ‘__iand__’, ‘__ixor__’，和
                                                          ‘add’, ‘discard’            ‘__isub__’
                                                                                      
                                                                                      
*note Mapping: 15f.            *note Collection: 626.     ‘__getitem__’,              ‘__contains__’, ‘keys’, ‘items’, ‘values’, ‘get’,
                                                          ‘__iter__’, ‘__len__’       ‘__eq__’, and ‘__ne__’
                                                                                      
                                                                                      
*note MutableMapping: ace.     *note Mapping: 15f.        ‘__getitem__’,              继承自 *note Mapping: 15f. 的方法以及 ‘pop’,
                                                          ‘__setitem__’,              ‘popitem’, ‘clear’, ‘update’，和 ‘setdefault’
                                                          ‘__delitem__’,              
                                                          ‘__iter__’, ‘__len__’
                                                          
                                                                                      
*note MappingView: 181d.       *note Sized: 1aaa.                                     ‘__len__’
                                                                                      
                                                                                      
*note ItemsView: 181f.         *note MappingView: 181d,                               ‘__contains__’, ‘__iter__’
                               *note Set: 1810.                                       
                               
                                                                                      
*note KeysView: 181e.          *note MappingView: 181d,                               ‘__contains__’, ‘__iter__’
                               *note Set: 1810.                                       
                               
                                                                                      
*note ValuesView: 1820.        *note MappingView: 181d,                               ‘__contains__’, ‘__iter__’
                               *note Collection: 626.                                 
                               
                                                                                      
*note Awaitable: 7a9.                                     ‘__await__’
                                                          
                                                                                      
*note Coroutine: 7aa.          *note Awaitable: 7a9.      ‘send’, ‘throw’             ‘close’
                                                                                      
                                                                                      
*note AsyncIterable: 7ac.                                 ‘__aiter__’
                                                          
                                                                                      
*note AsyncIterator: 7ab.      *note AsyncIterable: 7ac.  ‘__anext__’                 ‘__aiter__’
                                                                                      
                                                                                      
*note AsyncGenerator: 629.     *note AsyncIterator: 7ab.  ‘asend’, ‘athrow’           ‘aclose’, ‘__aiter__’, ‘__anext__’
                                                                                      

 -- 類別: collections.abc.Container

     提供了 *note __contains__(): dee. 方法的抽象基类。

 -- 類別: collections.abc.Hashable

     提供了 *note __hash__(): 44c. 方法的抽象基类。

 -- 類別: collections.abc.Sized

     提供了 *note __len__(): e90. 方法的抽象基类。

 -- 類別: collections.abc.Callable

     提供了 *note __call__(): 1560. 方法的抽象基类。

 -- 類別: collections.abc.Iterable

     提供了 *note __iter__(): 608. 方法的抽象基类。

     使用 ‘isinstance(obj, Iterable)’ 可以检测一个类是否已经注册到了
     *note Iterable: 1818. 或者实现了 *note __iter__(): 608. 函数，但是
     无法检测这个类是否能够使用 *note __getitem__(): 3a5. 方法进行迭代。
     检测一个对象是否是 *note iterable: c7c. 的唯一可信赖的方法是调用
     ‘iter(obj)’。

 -- 類別: collections.abc.Collection

     集合了 Sized 和 Iterable 类的抽象基类。

     3.6 版新加入.

 -- 類別: collections.abc.Iterator

     提供了 *note __iter__(): 175e. 和 *note __next__(): d2c. 方法的抽象
     基类。参见 *note iterator: 1171. 的定义。

 -- 類別: collections.abc.Reversible

     为可迭代类提供了 *note __reversed__(): 628. 方法的抽象基类。

     3.6 版新加入.

 -- 類別: collections.abc.Generator

     生成器类，实现了 PEP 342(1) 中定义的协议，继承并扩展了迭代器，提供
     了 *note send(): 15cd, *note throw(): ff8. 和 *note close(): 15d0.
     方法。参见 *note generator: a83. 的定义。

     3.5 版新加入.

 -- 類別: collections.abc.Sequence
 -- 類別: collections.abc.MutableSequence
 -- 類別: collections.abc.ByteString

     只读且可变的序列 *note sequences: 135c. 的抽象基类。

     实现笔记：一些混入（Maxin）方法比如 *note __iter__(): 608, *note
     __reversed__(): 628. 和 ‘index()’ 会重复调用底层的 *note
     __getitem__(): 3a5. 方法。因此，如果实现的 *note __getitem__():
     3a5. 是常数级访问速度，那么相应的混入方法会有一个线性的表现；然而，
     如果底层方法是线性实现（例如链表），那么混入方法将会是平方级的表现
     ，这也许就需要被重构了。

     3.5 版更變: index() 方法支持 `stop' 和 `start' 参数。

 -- 類別: collections.abc.Set
 -- 類別: collections.abc.MutableSet

     只读且可变的集合的抽象基类。

 -- 類別: collections.abc.Mapping
 -- 類別: collections.abc.MutableMapping

     只读且可变的映射 *note mappings: c0b. 的抽象基类。

 -- 類別: collections.abc.MappingView
 -- 類別: collections.abc.ItemsView
 -- 類別: collections.abc.KeysView
 -- 類別: collections.abc.ValuesView

     映射及其键和值的视图 *note views: 1a9e. 的抽象基类。

 -- 類別: collections.abc.Awaitable

     为可等待对象 *note awaitable: 612. 提供的类，可以被用于 *note
     await: 2d8. 表达式中。习惯上必须实现 *note __await__(): 735. 方法。

     *note 协程: 18a. 对象和 *note Coroutine: 7aa. ABC 的实例都是这个
     ABC 的实例。

          備註: 在 CPython 里，基于生成器的协程（使用 *note
          types.coroutine(): 86b. 或 *note asyncio.coroutine(): 3a8. 包
          装的生成器）都是 `可等待对象'，即使他们不含有 *note
          __await__(): 735. 方法。使用 ‘isinstance(gencoro, Awaitable)’
          来检测他们会返回 ‘False’。要使用 *note inspect.isawaitable():
          7ea. 来检测他们。

     3.5 版新加入.

 -- 類別: collections.abc.Coroutine

     用于协程兼容类的抽象基类。实现了如下定义在 *note 协程对象: 155e.: 里
     的方法： *note send(): 15cc.，*note throw(): 15ce. 和 *note
     close(): 15cf.。通常的实现里还需要实现 *note __await__(): 735. 方法
     。所有的 *note Coroutine: 7aa. 实例都必须是 *note Awaitable: 7a9. 实
     例。参见 *note coroutine: 18a. 的定义。

          備註: 在 CPython 里，基于生成器的协程（使用 *note
          types.coroutine(): 86b. 或 *note asyncio.coroutine(): 3a8. 包
          装的生成器）都是 `可等待对象'，即使他们不含有 *note
          __await__(): 735. 方法。使用 ‘isinstance(gencoro, Coroutine)’
          来检测他们会返回 ‘False’。要使用 *note inspect.isawaitable():
          7ea. 来检测他们。

     3.5 版新加入.

 -- 類別: collections.abc.AsyncIterable

     提供了 ‘__aiter__’ 方法的抽象基类。参见 *note asynchronous
     iterable: 733. 的定义。

     3.5 版新加入.

 -- 類別: collections.abc.AsyncIterator

     提供了 ‘__aiter__’ 和 ‘__anext__’ 方法的抽象基类。参见 *note
     asynchronous iterator: 738. 的定义。

     3.5 版新加入.

 -- 類別: collections.abc.AsyncGenerator

     为异步生成器类提供的抽象基类，这些类实现了定义在 PEP 525(2) 和 PEP
     492(3) 里的协议。

     3.6 版新加入.

这些抽象基类让我们可以确定类和示例拥有某些特定的函数，例如：

     size = None
     if isinstance(myvar, collections.abc.Sized):
         size = len(myvar)

有些抽象基类也可以用作混入类（mixin），这可以更容易地开发支持容器 API 的
类。例如，要写一个支持完整 *note Set: 1810. API 的类，只需要提供下面这三
个方法： *note __contains__(): dee, *note __iter__(): 608. 和 *note
__len__(): e90.。抽象基类会补充上其余的方法，比如 *note __and__(): 15a4.
和 ‘isdisjoint()’:

     class ListBasedSet(collections.abc.Set):
         ''' Alternate set implementation favoring space over speed
             and not requiring the set elements to be hashable. '''
         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

当把 *note Set: 1810. 和 *note MutableSet: 181b. 用作混入类时需注意：

  1. 由于某些集合操作会创建新集合，默认的混入方法需要一种从可迭代对象里
     创建新实例的方式。 假定类构造器具有 ‘ClassName(iterable)’ 形式的签
     名。 这样它将执行一个名为 ‘_from_iterable()’ 的内部类方法，该方法会
     调用 ‘cls(iterable)’ 来产生一个新集合。 如果 *note Set: 1810. 混入
     类在具有不同构造器签名的类中被使用，你将需要通过类方法或常规方法来
     重载 ‘_from_iterable()’，以便基于可迭代对象参数来构造新的实例。

  2. 重载比较符时时（想必是为了速度，因为其语义都是固定的），只需要重定
     义 *note __le__(): d68. 和 *note __ge__(): d6a. 函数，然后其他的操
     作会自动跟进。

  3. 混入集合类 *note Set: 1810. 提供了一个 ‘_hash()’ 方法为集合计算哈希
     值，然而， *note __hash__(): 44c. 函数却没有被定义，因为并不是所有
     集合都是可哈希并且不可变的。为了使用混入类为集合添加哈希能力，可以
     同时继承 *note Set(): 1810. 和 *note Hashable(): 1aa9. 类，然后定义
     ‘__hash__ = Set._hash’。

也參考
......

   * OrderedSet recipe(4) 是基于 *note MutableSet: 181b. 构建的一个示例
     。

   * 对于抽象基类，参见 *note abc: 3. 模块和 PEP 3119(5)。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0342

   (2) https://www.python.org/dev/peps/pep-0525

   (3) https://www.python.org/dev/peps/pep-0492

   (4) https://code.activestate.com/recipes/576694/

   (5) https://www.python.org/dev/peps/pep-3119


File: python.info,  Node: heapq --- 堆積佇列 heap queue 演算法,  Next: bisect --- 陣列二分演算法 Array bisection algorithm,  Prev: collections abc --- 容器的抽象基类,  Up: 数据类型

5.8.6 ‘heapq’ — 堆積佇列 (heap queue) 演算法
--------------------------------------------

`原始碼：' Lib/heapq.py(1)

__________________________________________________________________

這個模組實作了堆積佇列 (heap queue) 演算法，亦被稱為優先佇列 (priority
queue) 演算法。

Heap（堆積）是一顆二元樹，樹上所有父節點的值都小於等於他的子節點的值。使
用陣列實作，對於所有從0開始的 `k' 都滿足 ‘heap[k] <= heap[2*k+1]’ 和
‘heap[k] <= heap[2*k+2]’ 。為了比較節點的值，不存在的元素被視為無限大。
heap 存在一個有趣的性質：樹上最小的元素永遠會在根節點 ‘heap[0]’ 上。

下方的 API 跟一般教科書的 heap queue 演算法有兩個方面不同：第一，我們的
索引從 0 開始計算，這會父節點與子節點之間的關係產生很微小的差異，但更符
合 Python 從 0 開始索引的設計。第二，我們的 pop 方法會回傳最小的元素而不
是最大的元素 （ 在教科書中被稱作 "min heap"，而 "max heap" 因為他很適合
做原地排序，所以更常出現在教科書中 ）。

這兩個特性使得把 heap 當作一個標準的 Python list 檢視時不會出現意外：
‘heap[0]’ 是最小的物件，‘heap.sort()’ 能保持 heap 的性質不變！

建立一個 heap 可以使用 list 初始化為 ‘[]’，或者使用函式 *note heapify():
1aad. 將一個已經有元素的 list轉成一個 heap。

此模組提供下面的函式

 -- 函式: heapq.heappush (heap, item)

     把 `item' 放進 `heap'，並保持 heap 性質不變。

 -- 函式: heapq.heappop (heap)

     從 `heap' 取出並回傳最小的元素，同時保持 heap 性質不變。如果 heap 是
     空的會產生 *note IndexError: f36. 錯誤。只存取最小元素但不取出可以
     使用 ‘heap[0]’ 。

 -- 函式: heapq.heappushpop (heap, item)

     將 `item' 放入 heap ，接著從 `heap' 取出並回傳最小的元素。這個組合
     函式比呼叫 *note heappush(): 1aae. 之後呼叫 *note heappop(): 1aaf.
     更有效率。

 -- 函式: heapq.heapify (x)

     在線性時間內將 list `x' 轉為 heap，且過程不會申請額外記憶體。

 -- 函式: heapq.heapreplace (heap, item)

     從 `heap' 取出並回傳最小的元素，接著將新的 `item' 放進heap。heap 的
     大小不會改變。如果 heap 是空的會產生 *note IndexError: f36. 錯誤。

     這個一次完成的操作會比呼叫 *note heappop(): 1aaf. 之後呼叫 *note
     heappush(): 1aae. 更有效率，並在維護 heap 的大小不變時更為適當，取
     出/放入的組合函式一定會從 heap 回傳一個元素並用 `item' 取代他。

     函式的回傳值可能會大於被加入的 `item' 。如果這不是你期望發生的，可
     以考慮使用 *note heappushpop(): 1ab0. 替代，他會回傳 heap 的最小值
     和 `item' 兩個當中比較小的那個，並將大的留在 heap 內。

這個模組也提供三個利用 heap 實作的一般用途函式

 -- 函式: heapq.merge (*iterables, key=None, reverse=False)

     合併多個已排序的輸入並產生單一且已排序的輸出（舉例：合併來自多個
     log 檔中有時間戳記的項目）。回傳一個 *note iterator: 1171. 包含已經
     排序的值。

     和 ‘sorted(itertools.chain(*iterables))’ 類似但回傳值是一個
     iterable ，不會一次把所有資料都放進記憶體中，並且假設每一個輸入都已
     經（由小到大）排序過了。

     有兩個選用參數，指定時必須被當作關鍵字參數指定。

     `key' 參數指定了一個 *note key function: 7d2. 引數，用來從每一個輸
     入的元素中決定一個比較的依據。預設的值是 ‘None’ （直接比較元素）。

     `reverse' 为一个布尔值。 如果设为 ‘True’，则输入元素将按比较结果逆
     序进行合并。 要达成与 ‘sorted(itertools.chain(*iterables),
     reverse=True)’ 类似的行为，所有可迭代对象必须是已从大到小排序的。

     3.5 版更變: 加入選用參數 `key' 和 `reverse' 。

 -- 函式: heapq.nlargest (n, iterable, key=None)

     从 `iterable' 所定义的数据集中返回前 `n' 个最大元素组成的列表。 如
     果提供了 `key' 则其应指定一个单参数的函数，用于从 `iterable' 的每个
     元素中提取比较键 (例如 ‘key=str.lower’)。 等价于: ‘sorted(iterable,
     key=key, reverse=True)[:n]’。

 -- 函式: heapq.nsmallest (n, iterable, key=None)

     从 `iterable' 所定义的数据集中返回前 `n' 个最小元素组成的列表。 如
     果提供了 `key' 则其应指定一个单参数的函数，用于从 `iterable' 的每个
     元素中提取比较键 (例如 ‘key=str.lower’)。 等价于: ‘sorted(iterable,
     key=key)[:n]’。

後兩個函式在 `n' 值比較小時有最好的表現。對於較大的 `n' 值，只用 *note
sorted(): 546. 函式會更有效率。同樣地，當 ‘n==1’ 時，使用內建函式 *note
min(): 8f6. 和 *note max(): 8f7. 會有更好的效率。如果需要重複使用這些函
式，可以考慮將 iterable 轉成真正的 heap 。

* Menu:

* 基礎範例::
* 優先佇列 (Priority Queue) 實作細節: 優先佇列 Priority Queue 實作細節.
* 原理::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/heapq.py


File: python.info,  Node: 基礎範例,  Next: 優先佇列 Priority Queue 實作細節,  Up: heapq --- 堆積佇列 heap queue 演算法

5.8.6.1 基礎範例
................

堆排序(1) 可以通过将所有值推入堆中然后每次弹出一个最小值项来实现。

     >>> 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]

雖然類似 ‘sorted(iterable)’ ，但跟 *note sorted(): 546. 不同的是，這個實
作不是 stable 的排序。

Heap 中的元素可以是 tuple 。這有利於將要比較的值（例如一個 task 的優先度
）和主要資料放在一起排序。

     >>> 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')

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Heapsort


File: python.info,  Node: 優先佇列 Priority Queue 實作細節,  Next: 原理,  Prev: 基礎範例,  Up: heapq --- 堆積佇列 heap queue 演算法

5.8.6.2 優先佇列 (Priority Queue) 實作細節
..........................................

优先队列(1) 是堆的常用场合，并且它的实现包含了多个挑战：

   * 排序的穩定性：你如何將兩個擁有相同 priority 的 task 按照他們被加入
     的順序回傳。

   * Tuple的排序在某些情況下會壞掉，例如當 Tuple (priority, task) 的
     priorities 相等且 tasks 沒有一個預設的排序時。

   * 當一個 heap 中 task 的 priority 改變時，你如何將它移到 heap 正確的
     位置上。

   * 或者一個還沒被解決的 task 需要被刪除時，你要如何從佇列中找到並刪除
     指定的 task。

一個針對前兩個問題的解法是：儲存一個包含 priority 、 entry count 和 task
三個元素的 tuple 。兩個 task 有相同 priority 時， entry count 會讓兩個
task 能根據加入的順序排序。因為沒有任何兩個 task 擁有相同的 entry count
，所以永遠不會直接使用 task 做比較。

不可比较任务问题的另一种解决方案是创建一个忽略任务条目并且只比较优先级字
段的包装器类:

     from dataclasses import dataclass, field
     from typing import Any

     @dataclass(order=True)
     class PrioritizedItem:
         priority: int
         item: Any=field(compare=False)

剩下的問題可以藉由找到要刪除的 task 並更改它的 priority 或者直接將它移除
。尋找一個 task 可以使用一個 dictionary 指向佇列當中的 entry 。

移除 entry 或更改它的 priority 更為困難，因為這會破壞 heap 的性質。所以
一個可行的方案是將原本的 entry 做一個標記表示它已經被刪除，並新增一個擁
有新的 priority 的 entry 。

     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')

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Priority_queue


File: python.info,  Node: 原理,  Prev: 優先佇列 Priority Queue 實作細節,  Up: heapq --- 堆積佇列 heap queue 演算法

5.8.6.3 原理
............

Heap 是一個陣列對於所有從0開始的 index `k' 都存在性質 ‘a[k] <= a[2*k+1]’
和 ‘a[k] <= a[2*k+2]’ 。為了方便比較，不存在的元素被視為無限大。一個有趣
的 heap 性質是 ‘a[0]’ 永遠是最小的元素。

上面的特殊不变量是用来作为一场锦标赛的高效内存表示。 下面的数字是 `k' 而
不是 ‘a[k]’:

                                    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

在上面的树中，每个 `k' 单元都位于 ‘2*k+1’ 和 ‘2*k+2’ 之上。 体育运动中我
们经常见到二元锦标赛模式，每个胜者单元都位于另两个单元之上，并且我们可以
沿着树形图向下追溯胜者所遇到的所有对手。 但是，在许多采用这种锦标赛模式
的计算机应用程序中，我们并不需要追溯胜者的历史。 为了获得更高的内存利用
效率，当一个胜者晋级时，我们会用较低层级的另一条目来替代它，因此规则变为
一个单元和它之下的两个单元包含三个不同条目，上方单元“胜过”了两个下方单元
。

如果此堆的不变量始终受到保护，则序号 0 显然是最后的赢家。 删除它并找出
“下一个”赢家的最简单算法方式是家某个输家（让我们假定是上图中的 30 号单元
）移至 0 号位置，然后将这个新的 0 号沿树下行，不断进行值的交换，直到不变
量重新建立。 这显然会是树中条目总数的对数。 通过迭代所有条目，你将得到一
个 O(n log n) 复杂度的排序。

此排序有一个很好的特性就是你可以在排序进行期间高效地插入新条目，前提是插
入的条目不比你最近取出的 0 号元素“更好”。 这在模拟上下文时特别有用，在这
种情况下树保存的是所有传入事件，“胜出”条件是最小调度时间。 当一个事件将
其他事件排入执行计划时，它们的调试时间向未来方向延长，这样它们可方便地入
堆。 因此，堆结构很适宜用来实现调度器，我的 MIDI 音序器就是用的这个 :-)。

用于实现调度器的各种结构都得到了充分的研究，堆是非常适宜的一种，因为它们
的速度相当快，并且几乎是恒定的，最坏的情况与平均情况没有太大差别。 虽然
还存在其他总体而言更高效的实现方式，但其最坏的情况却可能非常糟糕。

堆在大磁盘排序中也非常有用。 你应该已经了解大规模排序会有多个“运行轮次
”（即预排序的序列，其大小通常与 CPU 内存容量相关），随后这些轮次会进入合
并通道，轮次合并的组织往往非常巧妙 (1)。 非常重要的一点是初始排序应产生
尽可能长的运行轮次。 锦标赛模式是达成此目标的好办法。 如果你使用全部有用
内存来进行锦标赛，替换和安排恰好适合当前运行轮次的条目，你将可以对于随机
输入生成两倍于内存大小的运行轮次，对于模糊排序的输入还会有更好的效果。

另外，如果你输出磁盘上的第 0 个条目并获得一个可能不适合当前锦标赛的输入
（因为其值要“胜过”上一个输出值），它无法被放入堆中，因此堆的尺寸将缩小。
被释放的内存可以被巧妙地立即重用以逐步构建第二个堆，其增长速度与第一个堆
的缩减速度正好相同。 当第一个堆完全消失时，你可以切换新堆并启动新的运行
轮次。 这样做既聪明又高效！

总之，堆是值得了解的有用内存结构。 我在一些应用中用到了它们，并且认为保
留一个 ’heap’ 模块是很有意义的。 :-)

註解
....

   ---------- Footnotes ----------

   (1) (1) 当前时代的磁盘平衡算法与其说是巧妙，不如说是麻烦，这是由磁盘
的寻址能力导致的结果。 在无法寻址的设备例如大型磁带机上，情况则相当不同
，开发者必须非常聪明地（极为提前地）确保每次磁带转动都尽可能地高效（就是
说能够最好地加入到合并“进程”中）。 有些磁带甚至能够反向读取，这也被用来
避免倒带的耗时。 请相信我，真正优秀的磁带机排序看起来是极其壮观的，排序
从来都是一门伟大的艺术！ :-)


File: python.info,  Node: bisect --- 陣列二分演算法 Array bisection algorithm,  Next: array --- 高效率的數值型態陣列,  Prev: heapq --- 堆積佇列 heap queue 演算法,  Up: 数据类型

5.8.7 ‘bisect’ — 陣列二分演算法 (Array bisection algorithm)
-----------------------------------------------------------

`原始碼：' Lib/bisect.py(1)

__________________________________________________________________

這個模組維護一個已經排序過的 list ，當我們每次做完插入後不需要再次排序整
個 list 。一個很長的 list 的比較操作很花費時間，為了改進這點，這個模組是
其中一個常用的方法。這個模組被命名為 *note bisect: 11. 來自他使用一個基
礎的 bisection 演算法實作。模組的原始碼是這個演算法的一個完善的實作（邊
界條件已經是正確的了）。

此模組提供下面的函式

 -- 函式: bisect.bisect_left (a, x, lo=0, hi=len(a))

     在 `a' 當中找到一個位置，讓 `x' 插入後 `a' 仍然是排序好的。參數
     `lo' 和 `hi' 用來指定 list 中應該被考慮的子區間，預設是考慮整個
     list 。如果 `a' 裡面已經有 `x' 出現，插入的位置會在所有 `x' 的前面
     （左邊）。回傳值可以被當作 ‘list.insert()’ 的第一個參數，但列表 `a'
     必須先排序過。

     回傳的插入位置 `i' 將陣列 `a' 分為兩半，使得 ‘all(val < x for val
     in a[lo:i])’ 都在左側且 ‘all(val >= x for val in a[i:hi])’ 都在右側
     。

 -- 函式: bisect.bisect_right (a, x, lo=0, hi=len(a))
 -- 函式: bisect.bisect (a, x, lo=0, hi=len(a))

     類似 *note bisect_left(): 1ab9. ，但回傳的插入位置會在所有 `a' 當中
     的 `x' 的後面（右邊）。

     回傳的插入位置 `i' 將陣列 `a' 分為兩半，使得 ‘all(val <= x for val
     in a[lo:i])’ 都在左側且 ‘all(val > x for val in a[i:hi])’ 都在右側
     。

 -- 函式: bisect.insort_left (a, x, lo=0, hi=len(a))

     不破壞 `a' 的排序下插入 `x' ，這等價於
     ‘a.insert(bisect.bisect_left(a, x, lo, hi), x)’ ，注意 `a' 必須是已
     經排序過的 list 。注意搜尋只需要 O(log n) 時間而插入需要很慢的 O(n)
     時間，這使得插入操作主導了需要的花費時間。

 -- 函式: bisect.insort_right (a, x, lo=0, hi=len(a))
 -- 函式: bisect.insort (a, x, lo=0, hi=len(a))

     類似 *note insort_left(): 1abc. ，但插入的位置會在所有 `a' 當中的
     `x' 的後面（右邊）。

也參考
......

SortedCollection recipe(2) 使用 bisect 构造了一个功能完整的集合类，提供
了直接的搜索方法和对用于搜索的 key 方法的支持。所有用于搜索的键都是预先
计算的，以避免在搜索时对 key 方法的不必要调用。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/bisect.py

   (2) https://code.activestate.com/recipes/577197-sortedcollection/


File: python.info,  Node: 搜索有序列表,  Next: 其他示例,  Up: bisect --- 陣列二分演算法 Array bisection algorithm

5.8.7.1 搜索有序列表
....................

上面的 *note bisect(): 11. 函数对于找到插入点是有用的，但在一般的搜索任
务中可能会有点尴尬。下面 5 个函数展示了如何将其转变成有序列表中的标准查
找函数

     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


File: python.info,  Node: 其他示例,  Prev: 搜索有序列表,  Up: bisect --- 陣列二分演算法 Array bisection algorithm

5.8.7.2 其他示例
................

函数 *note bisect(): 11. 还可以用于数字表查询。这个例子是使用 *note
bisect(): 11. 从一个给定的考试成绩集合里，通过一个有序数字表，查出其对应
的字母等级：90 分及以上是 ’A’，80 到 89 是 ’B’，以此类推

     >>> 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']

与 *note sorted(): 546. 函数不同，对于 *note bisect(): 11. 函数来说，
`key' 或者 `reversed' 参数并没有什么意义。因为这会导致设计效率低下（连续
调用 bisect 函数时，是不会 "记住" 过去查找过的键的）。

正相反，最好去搜索预先计算好的键列表，来查找相关记录的索引。

     >>> 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)


File: python.info,  Node: array --- 高效率的數值型態陣列,  Next: weakref --- 弱引用,  Prev: bisect --- 陣列二分演算法 Array bisection algorithm,  Up: 数据类型

5.8.8 ‘array’ — 高效率的數值型態陣列
------------------------------------

__________________________________________________________________

這個模組定義了一個物件型別，可以簡潔的表達一個包含基本數值的陣列：字元、
整數、浮點數。陣列是一個非常類似 list 的序列型態，除了陣列會限制儲存的物
件型別。在建立陣列時可以使用一個字元的 `type code' 來指定儲存的資料型別
。下面是 type codes 的定義。

Type code       C Type                   Python Type             最小所需的位元組            註解
                                                                                             
---------------------------------------------------------------------------------------------------------
                                                                                             
‘'b'’           signed char              int                     1
                                                                 
                                                                                             
‘'B'’           unsigned char            int                     1
                                                                 
                                                                                             
‘'u'’           wchar_t                  Unicode character       2                           (1)
                                                                                             
                                                                                             
‘'h'’           signed short             int                     2
                                                                 
                                                                                             
‘'H'’           unsigned short           int                     2
                                                                 
                                                                                             
‘'i'’           signed int               int                     2
                                                                 
                                                                                             
‘'I'’           unsigned int             int                     2
                                                                 
                                                                                             
‘'l'’           signed long              int                     4
                                                                 
                                                                                             
‘'L'’           unsigned long            int                     4
                                                                 
                                                                                             
‘'q'’           signed long long         int                     8
                                                                 
                                                                                             
‘'Q'’           unsigned long long       int                     8
                                                                 
                                                                                             
‘'f'’           float                    float                   4
                                                                 
                                                                                             
‘'d'’           double                   float                   8
                                                                 

註解：

  1. 由于平台的不同它可能为 16 位或 32 位。

     3.9 版更變: ‘array('u')’ 现在使用 ‘wchar_t’ 作为 C 类型而不再是已弃
     用的 ‘Py_UNICODE’。 这个改变不会影响其行为，因为 ‘Py_UNICODE’ 自
     Python 3.3 起就是 ‘wchar_t’ 的别名。

     Deprecated since version 3.3, will be removed in version 4.0.

實際上數值的表示方法是被機器的架構所決定（更精準地說，被 C 的實作方法決
定）。實際的大小可以透過 ‘itemsize’ 屬性存取。

這個模組定義了下方的型別：

 -- 類別: array.array (typecode[, initializer])

     一個新的陣列中的元素被 `typecode' 限制，並由選用的 `initializer' 參
     數初始化， `initializer' 必須是一個 list、 *note bytes-like object:
     6df. 或包含適當型別變數的 iterable 。

     如果指定一個 list 或 string ，新的陣列初始化時會傳入 *note
     fromlist(): 1ac4. 、 *note frombytes(): 1ac5. 或 *note
     fromunicode(): 1ac6. 方法（參照下方）將元素新增到其中。其他型態的變
     數則會傳入 *note extend(): 1ac7. 方法初始化。

     引发一个 *note 审计事件: fa1. ‘array.__new__’ 附带参数 ‘typecode’,
     ‘initializer’。

 -- Data: array.typecodes

     一個包含所有可用的 type code 的字串。

数组对象支持普通的序列操作如索引、切片、拼接和重复等。 当使用切片赋值时
，所赋的值必须为具有相同类型码的数组对象；所有其他情况都将引发 *note
TypeError: 1fe.。 数组对象也实现了缓冲区接口，可以用于所有支持 *note
字节类对象: 6df. 的场合。

提供下方的資料物件與方法。

 -- 屬性: array.typecode

     typecode 字元被用在建立陣列時。

 -- 屬性: array.itemsize

     陣列當中的一個元素在內部需要的位元組 (bytes) 長度。

 -- 成員函式: array.append (x)

     新增一個元素 `x' 到陣列的最尾端。

 -- 成員函式: array.buffer_info ()

     回傳一個 tuple ‘(address, length)’ 表示當前的記憶體位置和陣列儲存元
     素的緩衝區記憶體長度。緩衝區的長度單位是 bytes ，並可以用
     ‘array.buffer_info()[1] * array.itemsize’ 計算得到。這偶爾會在底層
     操作需要記憶體位置的輸出輸入時很有用，例如 ‘ioctl()’ 指令。只要陣列
     存在且沒有使用任何更改長度的操作時，回傳的數值就有效。

          備註: 當使用來自 C 或 C++ 程式碼（這是唯一使得這個資訊有效的途
          徑） 的陣列物件時，更適當的做法是使用陣列物件支援的緩衝區介面
          。這個方法維護了向後兼容性，並應該在新的程式碼中避免。關於緩衝
          區介面的文件在 *note 缓冲协议: 171c. 。

 -- 成員函式: array.byteswap ()

     "Byteswap" 所有陣列中的物件。這只有支援物件長度為 1、2、4 或 8 位元
     組的陣列，其他型別的值會導致 *note RuntimeError: 3dc. 。這在從機器
     讀取位元順序不同的檔案時很有用。

 -- 成員函式: array.count (x)

     回傳 `x' 在陣列中出現了幾次。

 -- 成員函式: array.extend (iterable)

     從 `iterable' 中新增元素到陣列的尾端，如果 `iterable' 是另一個陣列
     ，他必須有完全相同的 type code ，如果不同會產生 *note TypeError:
     1fe. 。如果 `iterable' 不是一個陣列，他必須可以被迭代 (iterable) 且
     其中的元素必須是可以被加入陣列中的正確型態。

 -- 成員函式: array.frombytes (s)

     從字串中新增元素。讀取時會將字串當作一個陣列，裡面包含了 machine
     value（就像從檔案中使用 *note fromfile(): 1acf. 方法讀出的資料）。

     3.2 版新加入: 為了更明確，之前的 ‘fromstring()’ 被更名為 *note
     frombytes(): 1ac5. 。

 -- 成員函式: array.fromfile (f, n)

     從 *note file object: c14. `f' 讀取 `n' 個 machine value 類型的元素
     ，接著將這些元素加入陣列的最尾端。如果只有少於 `n' 個有效的元素會產
     生 *note EOFError: d34. 錯誤，但有效的元素仍然會被加入陣列中。

 -- 成員函式: array.fromlist (list)

     從 list 中新增元素。這等價於 ‘for x in list: a.append(x)’ ，除了有
     型態錯誤產生時，陣列會保持原狀不會被更改。

 -- 成員函式: array.fromunicode (s)

     用給定的 unicode 字串擴展這個陣列。陣列必須是型態 ‘u’ 的陣列；其他
     的型態會產生 *note ValueError: 16d. 錯誤。使用
     ‘array.frombytes(unicodestring.encode(enc))’ 來新增 Unicode 資料到
     一個其他型態的陣列。

 -- 成員函式: array.index (x)

     回傳最小的 `i' ，使得 `i' 是陣列中第一個 `x' 出現的索引值。

 -- 成員函式: array.insert (i, x)

     在位置 `i' 之前插入一個元素 `x' 。負數的索引值會從陣列尾端開始數。

 -- 成員函式: array.pop ([i])

     移除並回傳陣列索引值 `i' 的元素。選擇性的參數 `i' 預設為 ‘-1’ ，所
     以預設會刪除並回傳最後一個元素。

 -- 成員函式: array.remove (x)

     從陣列中刪除第一個出現的 `x' 。

 -- 成員函式: array.reverse ()

     將整個陣列的元素按照順序逆轉。

 -- 成員函式: array.tobytes ()

     將陣列轉為另一個 machine values 的陣列並回傳他的位元組表示（跟用
     *note tofile(): 1ad5. 方法寫入檔案時的位元序列相同）。

     3.2 版新加入: 為了明確性，過去的 ‘tostring()’ 已更名為 *note
     tobytes(): 1ad4. 。

 -- 成員函式: array.tofile (f)

     將所有元素 （以 machine code 的形式）寫入 *note file object: c14.
     `f' 。

 -- 成員函式: array.tolist ()

     不更改元素，將陣列轉為一般的 list 。

 -- 成員函式: array.tounicode ()

     將陣列轉為一個字串。陣列的型態必須為 ‘u’ 。其他型態的陣列會產生
     *note ValueError: 16d. 錯誤。使用 ‘array.tobytes().decode(enc)’ 將
     其他型態的陣列轉為字串。

当一个数组对象被打印或转换为字符串时，它会表示为 ‘array(typecode,
initializer)’。 如果数组为空则 `initializer' 会被省略，否则如果
`typecode' 为 ‘'u'’ 则它是一个字符串，否则它是一个数字列表。 使用 *note
eval(): c61. 保证能将字符串转换回具有相同类型和值的数组，只要 *note
array: 216. 类已通过 ‘from array import array’ 被引入。 例如:

     array('l')
     array('u', 'hello \u2641')
     array('l', [1, 2, 3, 4, 5])
     array('d', [1.0, 2.0, 3.14])

也參考
......

模組 *note struct: f8.

     將包含不同資料類型的二進位資料包裝與解開包裝。

模組 *note xdrlib: 13b.

     將 External Data Representation (XDR) 的資料包裝與解開包裝，這用在
     一些遠端操作的系統 ( remote procedure call systems ) 。

NumPy(1)

     NumPy 套件定義了另一個陣列型態

   ---------- Footnotes ----------

   (1) https://numpy.org/


File: python.info,  Node: weakref --- 弱引用,  Next: types --- 动态类型创建和内置类型名称,  Prev: array --- 高效率的數值型態陣列,  Up: 数据类型

5.8.9 ‘weakref’ — 弱引用
------------------------

`源码：' Lib/weakref.py(1)

__________________________________________________________________

*note weakref: 131. 模块允许Python程序员创建对象的 `weak references' 。

在下文中，术语 `referent' 表示由弱引用引用的对象。

对对象的弱引用不能保证对象存活：当对像的引用只剩弱引用时， *note garbage
collection: fc8. 可以销毁引用并将其内存重用于其他内容。但是，在实际销毁
对象之前，即使没有强引用，弱引用也一直能返回该对象。

弱引用的主要用途是实现保存大对象的高速缓存或映射，但又不希望大对象仅仅因
为它出现在高速缓存或映射中而保持存活。

例如，如果您有许多大型二进制图像对象，则可能希望将名称与每个对象关联起来
。如果您使用Python字典将名称映射到图像，或将图像映射到名称，则图像对象将
保持活动状态，因为它们在字典中显示为值或键。 *note weakref: 131. 模块提
供的 *note WeakKeyDictionary: 1054. 和 *note WeakValueDictionary: 1053.
类可以替代Python字典，使用弱引用来构造映射，这些映射不会仅仅因为它们出现
在映射对象中而使对象保持存活。例如，如果一个图像对象是 *note
WeakValueDictionary: 1053. 中的值，那么当对该图像对象的剩余引用是弱映射
对象所持有的弱引用时，垃圾回收可以回收该对象并将其在弱映射对象中相应的条
目删除。

*note WeakKeyDictionary: 1054. 和 *note WeakValueDictionary: 1053. 在它
们的实现中使用弱引用，在弱引用上设置回调函数，当键或值被垃圾回收回收时通
知弱字典。 *note WeakSet: d80. 实现了 *note set: 1f6. 接口，但像 *note
WeakKeyDictionary: 1054. 一样，只持有其元素的弱引用。

*note finalize: 3c0. 提供了注册一个对象被垃圾收集时要调用的清理函数的方
式。这比在原始弱引用上设置回调函数更简单，因为模块会自动确保对象被回收前
终结器一直保持存活。

这些弱容器类型之一或者 *note finalize: 3c0. 就是大多数程序所需要的 - 通
常不需要直接创建自己的弱引用。*note weakref: 131. 模块暴露了低级机制，以
便于高级用途。

并非所有对象都可以被弱引用；可以被弱引用的对象包括类实例，用 Python（而
不是用 C）编写的函数，实例方法、集合、冻结集合，某些 *note 文件对象:
c14.，*note 生成器: a83.，类型对象，套接字，数组，双端队列，正则表达式模
式对象以及代码对象等。

3.2 版更變: 添加了对thread.lock，threading.Lock和代码对象的支持。

几个内建类型如 *note list: 1f8. 和 *note dict: 164. 不直接支持弱引用，但
可以通过子类化添加支持:

     class Dict(dict):
         pass

     obj = Dict(red=1, green=2, blue=3)   # this object is weak referenceable

`CPython implementation detail:' 其他内置类型例如 *note tuple: 1a2. 和
*note int: 204. 不支持弱引用，即使通过子类化也不支持。

Extension types can easily be made to support weak references; see *note
Weak Reference Support: 1ada.

When ‘__slots__’ are defined for a given type, weak reference support is
disabled unless a ‘'__weakref__'’ string is also present in the sequence
of strings in the ‘__slots__’ declaration.  See *note __slots__
documentation: 1577. for details.

 -- 類別: weakref.ref (object[, callback])

     返回对 `对象' 的弱引用。如果原始对象仍然存活，则可以通过调用引用对
     象来检索原始对象；如果引用的原始对象不再存在，则调用引用对象将得到
     *note None: 203. 。如果提供了 `回调' 而且值不是 *note None: 203. ，
     并且返回的弱引用对象仍然存活，则在对象即将终结时将调用回调;弱引用对
     象将作为回调的唯一参数传递；指示物将不再可用。

     许多弱引用也允许针对相同对象来构建。 为每个弱引用注册的回调将按从最
     近注册的回调到最早注册的回调的顺序被调用。

     回调所引发的异常将记录于标准错误输出，但无法被传播；它们会按与对象
     的 *note __del__(): a04. 方法所引发的异常相同的方式被处理。

     如果 `object' 可哈希，则弱引用也为 *note hashable: 276.。 即使在
     `object' 被删除之后它们仍将保持其哈希值。 如果 *note hash(): aa3. 在
     `object' 被删除之后才首次被调用，则该调用将引发 *note TypeError:
     1fe.。

     弱引用支持相等检测，但不支持排序比较。 如果被引用对象仍然存在，两个
     引用具有与它们的被引用对象一致的相等关系（无论 `callback' 是否相同
     ）。 如果删除了任一被引用对象，则仅在两个引用对象为同一对象时两者才
     相等。

     这是一个可子类化的类型而非一个工厂函数。

      -- 屬性: __callback__

          这个只读属性会返回当前关联到弱引用的回调。 如果回调不存在或弱
          引用的被引用对象已不存在，则此属性的值为 ‘None’。

     3.4 版更變: 添加了 *note __callback__: 9f7. 属性。

 -- 函式: weakref.proxy (object[, callback])

     返回 `object' 的一个使用弱引用的代理。 此函数支持在大多数上下文中使
     用代理，而不要求显式地对所使用的弱引用对象解除引用。 返回的对象类型
     将为 ‘ProxyType’ 或 ‘CallableProxyType’，具体取决于 `object' 是否可
     调用。 Proxy 对象不是 *note hashable: 276. 对象，无论被引用对象是否
     可哈希；这可避免与它们的基本可变性质相关的多种问题，并可防止它们被
     用作字典键。 `callback' 与 *note ref(): 9f6. 函数的同名形参含义相同
     。

     3.8 版更變: 扩展代理对象所支持的运算符，包括矩阵乘法运算符 ‘@’ 和
     ‘@=’。

 -- 函式: weakref.getweakrefcount (object)

     返回指向 `object' 的弱引用和代理的数量。

 -- 函式: weakref.getweakrefs (object)

     返回由指向 `object' 的所有弱引用和代理构成的列表。

 -- 類別: weakref.WeakKeyDictionary ([dict])

     弱引用键的映射类。 当不再存在对键的强引用时，字典中的条目将被丢弃。
     这可被用来将额外数据关联到一个应用中其他部分所拥有的对象而无需在那
     些对象中添加属性。 这对于重载了属性访问的对象来说特别有用。

     3.9 版更變: 增加了对 ‘|’ 和 ‘|=’ 运算符的支持，相关说明见 PEP
     584(2)。

*note WeakKeyDictionary: 1054. 对象具有一个额外方法可以直接公开内部引用
。 这些引用不保证在它们被使用时仍然保持“存活”，因此这些引用的调用结果需
要在使用前进行检测。 此方法可用于避免创建会导致垃圾回收器将保留键超出实
际需要时长的引用。

 -- 成員函式: WeakKeyDictionary.keyrefs ()

     返回包含对键的弱引用的可迭代对象。

 -- 類別: weakref.WeakValueDictionary ([dict])

     弱引用值的映射类。 当不再存在对该值的强引用时，字典中的条目将被丢弃
     。

     3.9 版更變: 增加了对 ‘|’ 和 ‘|=’ 运算符的支持，相关说明见 PEP
     584(3)。

*note WeakValueDictionary: 1053. 对象具有一个额外方法，此方法存在与
*note WeakKeyDictionary: 1054. 对象的 ‘keyrefs()’ 方法相同的问题。

 -- 成員函式: WeakValueDictionary.valuerefs ()

     返回包含对值的弱引用的可迭代对象。

 -- 類別: weakref.WeakSet ([elements])

     保持对其元素弱引用的集合类。 当不再有对某个元素的强引用时元素将被丢
     弃。

 -- 類別: weakref.WeakMethod (method)

     一个模拟对绑定方法（即在类中定义并在实例中查找的方法）进行弱引用的
     自定义 *note ref: 9f6. 子类。 由于绑定方法是临时性的，标准弱引用无
     法保持它。 *note WeakMethod: 9f5. 包含特别代码用来重新创建绑定方法
     ，直到对象或初始函数被销毁:

          >>> 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()
          >>>

     3.4 版新加入.

 -- 類別: weakref.finalize (obj, func, /, *args, **kwargs)

     返回一个可调用的终结器对象，该对象将在 `obj' 作为垃圾回收时被调用。
     与普通的弱引用不同，终结器将总是存活，直到引用对象被回收，这极大地
     简化了生存期管理。

     终结器总是被视为 `存活' 直到它被调用（显式调用或在垃圾回收时隐式调
     用），调用之后它将 `死亡'。 调用存活的终结器将返回 ‘func(*arg,
     **kwargs)’ 的求值结果，而调用死亡的终结器将返回 *note None: 203.。

     在垃圾收集期间由终结器回调所引发异常将显示于标准错误输出，但无法被
     传播。 它们会按与对象的 *note __del__(): a04. 方法或弱引用的回调所
     引发异常相同的方式被处理。

     当程序退出时，剩余的存活终结器会被调用，除非它们的 *note atexit: b.
     属性已被设为假值。 它们会按与创建时相反的顺序被调用。

     终结器在 *note interpreter shutdown: 852. 的后期绝不会发起调用其回
     调函数，此时模块全局变量很可能已被替换为 *note None: 203.。

      -- 成員函式: __call__ ()

          如果 `self' 为存活状态则将其标记为已死亡，并返回调用
          ‘func(*args, **kwargs)’ 的结果。 如果 `self' 已死亡则返回
          *note None: 203.。

      -- 成員函式: detach ()

          如果 `self' 为存活状态则将其标记为已死亡，并返回元组 ‘(obj,
          func, args, kwargs)’。 如果 `self' 已死亡则返 *note None:
          203.。

      -- 成員函式: peek ()

          如果 `self' 为存活状态则返回元组 ‘(obj, func, args, kwargs)’。
          如果 `self' 已死亡则返回 *note None: 203.。

      -- 屬性: alive

          如果终结器为存活状态则该特征属性为真值，否则为假值。

      -- 屬性: atexit

          一个可写的布尔型特征属性，默认为真值。 当程序退出时，它会调用
          所有 *note atexit: 1ae3. 为真值的剩余存活终结器。 它们会按与创
          建时相反的顺序被调用。

          備註: 很重要的一点是确保 `func', `args' 和 `kwargs' 不拥有任何
          对 `obj' 的引用，无论是直接的或是间接的，否则的话 `obj' 将永远
          不会被作为垃圾回收。 特别地，`func' 不应当是 `obj' 的一个绑定
          方法。

     3.4 版新加入.

 -- Data: weakref.ReferenceType

     弱引用对象的类型对象。

 -- Data: weakref.ProxyType

     不可调用对象的代理的类型对象。

 -- Data: weakref.CallableProxyType

     可调用对象的代理的类型对象。

 -- Data: weakref.ProxyTypes

     包含所有代理的类型对象的序列。 这可以用于更方便地检测一个对象是否是
     代理，而不必依赖于两种代理对象的名称。

也參考
......

PEP 205(4) - 弱引用

     此特性的提议和理由，包括早期实现的链接和其他语言中类似特性的相关信
     息。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/weakref.py

   (2) https://www.python.org/dev/peps/pep-0584

   (3) https://www.python.org/dev/peps/pep-0584

   (4) https://www.python.org/dev/peps/pep-0205


File: python.info,  Node: 弱引用对象,  Next: 示例<4>,  Up: weakref --- 弱引用

5.8.9.1 弱引用对象
..................

弱引用对象没有 *note ref.__callback__: 9f7. 以外的方法和属性。 一个弱引
用对象如果存在，就允许通过调用它来获取引用:

     >>> import weakref
     >>> class Object:
     ...     pass
     ...
     >>> o = Object()
     >>> r = weakref.ref(o)
     >>> o2 = r()
     >>> o is o2
     True

如果引用已不存在，则调用引用对象将返回 *note None: 203.:

     >>> del o, o2
     >>> print(r())
     None

检测一个弱引用对象是否仍然存在应该使用表达式 ‘ref() is not None’。 通常
，需要使用引用对象的应用代码应当遵循这样的模式:

     # 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()

使用单独的“存活”测试会在多线程应用中制造竞争条件；其他线程可能导致某个弱
引用在该弱引用被调用前就失效；上述的写法在多线程应用和单线程应用中都是安
全的。

特别版本的 *note ref: 9f6. 对象可以通过子类化来创建。 在 *note
WeakValueDictionary: 1053. 的实现中就使用了这种方式来减少映射中每个条目
的内存开销。 这对于将附加信息关联到引用的情况最为适用，但也可以被用于在
调用中插入额外处理来提取引用。

这个例子演示了如何将 *note ref: 9f6. 的一个子类用于存储有关对象的附加信
息并在引用被访问时影响其所返回的值:

     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


File: python.info,  Node: 示例<4>,  Next: 终结器对象,  Prev: 弱引用对象,  Up: weakref --- 弱引用

5.8.9.2 示例
............

这个简单的例子演示了一个应用如何使用对象 ID 来提取之前出现过的对象。 然
后对象的 ID 可以在其它数据结构中使用，而无须强制对象保持存活，但处于存活
状态的对象也仍然可以通过 ID 来提取。

     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]


File: python.info,  Node: 终结器对象,  Next: 比较终结器与 __del__ 方法,  Prev: 示例<4>,  Up: weakref --- 弱引用

5.8.9.3 终结器对象
..................

使用 *note finalize: 3c0. 的主要好处在于它能更简便地注册回调函数，而无须
保留所返回的终结器对象。 例如

     >>> 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!

终结器也可以被直接调用。 但是终结器最多只能对回调函数发起一次调用。

     >>> 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

你可以使用 *note detach(): 1ae0. 方法来注销一个终结器。 该方法将销毁终结
器并返回其被创建时传给构造器的参数。

     >>> 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

除非你将 *note atexit: 1ae3. 属性设为 *note False: 48e.，否则终结器在程
序退出时如果仍然存活就将被调用。 例如

     >>> obj = Object()
     >>> weakref.finalize(obj, print, "obj dead or exiting")
     <finalize object at ...; for 'Object' at ...>
     >>> exit()
     obj dead or exiting


File: python.info,  Node: 比较终结器与 __del__ 方法,  Prev: 终结器对象,  Up: weakref --- 弱引用

5.8.9.4 比较终结器与 ‘__del__()’ 方法
.....................................

假设我们想创建一个类，用它的实例来代表临时目录。 当以下事件中的某一个发
生时，这个目录应当与其内容一起被删除：

   * 对象被作为垃圾回收，

   * 对象的 ‘remove()’ 方法被调用，或

   * 程序退出。

我们可以尝试使用 *note __del__(): a04. 方法来实现这个类，如下所示:

     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()

从 Python 3.4 开始，*note __del__(): a04. 方法不会再阻止循环引用被作为垃
圾回收，并且模块全局变量在 *note interpreter shutdown: 852. 期间不会被强
制设为 *note None: 203.。 因此这段代码在 CPython 上应该会正常运行而不会
出现任何问题。

然而，*note __del__(): a04. 方法的处理会严重地受到具体实现的影响，因为它
依赖于解释器垃圾回收实现方式的内部细节。

更健壮的替代方式可以是定义一个终结器，只引用它所需要的特定函数和对象，而
不是获取对整个对象状态的访问权:

     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

像这样定义后，我们的终结器将只接受一个对其完成正确清理目录任务所需细节的
引用。 如果对象一直未被作为垃圾回收，终结器仍会在退出时被调用。

基于弱引用的终结器还具有另一项优势，就是它们可被用来为定义由第三方控制的
类注册终结器，例如当一个模块被卸载时运行特定代码:

     import weakref, sys
     def unloading_module():
         # implicit reference to the module globals from the function body
     weakref.finalize(sys.modules[__name__], unloading_module)

     備註: 如果当程序退出时你恰好在守护线程中创建终结器对象，则有可能该
     终结器不会在退出时被调用。 但是，在一个守护线程中 *note
     atexit.register(): f46, ‘try: ... finally: ...’ 和 ‘with: ...’ 同样
     不能保证执行清理。


File: python.info,  Node: types --- 动态类型创建和内置类型名称,  Next: copy --- 浅层 shallow 和深层 deep 复制操作,  Prev: weakref --- 弱引用,  Up: 数据类型

5.8.10 ‘types’ — 动态类型创建和内置类型名称
-------------------------------------------

`源代码:' Lib/types.py(1)

__________________________________________________________________

此模块定义了一些工具函数，用于协助动态创建新的类型。

它还为某些对象类型定义了名称，这些名称由标准 Python 解释器所使用，但并不
像内置的 *note int: 204. 或 *note str: 205. 那样对外公开。

最后，它还额外提供了一些类型相关但重要程度不足以作为内置对象的工具类和函
数。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/types.py


File: python.info,  Node: 动态类型创建,  Next: 标准解释器类型,  Up: types --- 动态类型创建和内置类型名称

5.8.10.1 动态类型创建
.....................

 -- 函式: types.new_class (name, bases=(), kwds=None, exec_body=None)

     使用适当的元类动态地创建一个类对象。

     前三个参数是组成类定义头的部件：类名称，基类 (有序排列)，关键字参数
     (例如 ‘metaclass’)。

     `exec_body' 参数是一个回调函数，用于填充新创建类的命名空间。 它应当
     接受类命名空间作为其唯一的参数并使用类内容直接更新命名空间。 如果未
     提供回调函数，则它就等效于传入 ‘lambda ns: None’。

     3.3 版新加入.

 -- 函式: types.prepare_class (name, bases=(), kwds=None)

     计算适当的元类并创建类命名空间。

     参数是组成类定义头的部件：类名称，基类 (有序排列) 以及关键字参数 (例
     如 ‘metaclass’)。

     返回值是一个 3 元组: ‘metaclass, namespace, kwds’

     `metaclass' 是适当的元类，`namespace' 是预备好的类命名空间而 `kwds'
     是所传入 `kwds' 参数移除每个 ‘'metaclass'’ 条目后的已更新副本。 如
     果未传入 `kwds' 参数，这将为一个空字典。

     3.3 版新加入.

     3.6 版更變: 所返回元组中 ‘namespace’ 元素的默认值已被改变。 现在当
     元类没有 ‘__prepare__’ 方法时将会使用一个保留插入顺序的映射。

也參考
......

*note 元类: 157c.

     这些函数所支持的类创建过程的完整细节

PEP 3115(1) - Python 3000 中的元类

     引入 ‘__prepare__’ 命名空间钩子

 -- 函式: types.resolve_bases (bases)

     动态地解析 MRO 条目，具体描述见 PEP 560(2)。

     此函数会在 `bases' 中查找不是 *note type: 6ff. 的实例的项，并返回一
     个元组，其中每个具有 ‘__mro_entries__’ 方法的此种对象对象将被替换为
     调用该方法解包后的结果。 如果一个 `bases' 项是 *note type: 6ff. 的
     实例，或它不具有 ‘__mro_entries__’ 方法，则它将不加改变地被包含在返
     回的元组中。

     3.7 版新加入.

也參考
......

PEP 560(3) - 对类型模块和泛型类型的核心支持

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3115

   (2) https://www.python.org/dev/peps/pep-0560

   (3) https://www.python.org/dev/peps/pep-0560


File: python.info,  Node: 标准解释器类型,  Next: 附加工具类和函数,  Prev: 动态类型创建,  Up: types --- 动态类型创建和内置类型名称

5.8.10.2 标准解释器类型
.......................

此模块为许多类型提供了实现 Python 解释器所要求的名称。 它刻意地避免了包
含某些仅在处理过程中偶然出现的类型，例如 ‘listiterator’ 类型。

此种名称的典型应用如 *note isinstance(): 551. 或 *note issubclass():
552. 检测。

如果你要实例化这些类型中的任何一种，请注意其签名在不同 Python 版本之间可
能出现变化。

以下类型有相应的标准名称定义：

 -- Data: types.FunctionType
 -- Data: types.LambdaType

     用户自定义函数以及由 *note lambda: cf9. 表达式所创建函数的类型。

     引发一个 *note 审计事件: fa1. ‘function.__new__’，附带参数 ‘code’。

     此审计事件只会被函数对象的直接实例化引发，而不会被普通编译所引发。

 -- Data: types.GeneratorType

     *note generator: a83. 迭代器对象的类型，由生成器函数创建。

 -- Data: types.CoroutineType

     *note coroutine: 18a. 对象的类型，由 *note async def: 3a9. 函数创建
     。

     3.5 版新加入.

 -- Data: types.AsyncGeneratorType

     *note asynchronous generator: 1640. 迭代器对象的类型，由异步生成器
     函数创建。

     3.6 版新加入.

 -- 類別: types.CodeType (**kwargs)

     代码对象的类型，例如 *note compile(): 2e7. 的返回值。

     引发 *note 审计事件: fa1. ‘code.__new__’ 附带参数 ‘code’,
     ‘filename’, ‘name’, ‘argcount’, ‘posonlyargcount’,
     ‘kwonlyargcount’, ‘nlocals’, ‘stacksize’, ‘flags’。

     请注意被审计的参数可能与初始化代码所要求的名称或位置不相匹配。 审计
     事件只会被代码对象的直接实例化引发，而不会被普通编译所引发。

      -- 成員函式: replace (**kwargs)

          返回代码对象的一个副本，使用指定的新字段值。

          3.8 版新加入.

 -- Data: types.CellType

     单元对象的类型：这种对象被用作函数中自由变量的容器。

     3.8 版新加入.

 -- Data: types.MethodType

     用户自定义类实例方法的类型。

 -- Data: types.BuiltinFunctionType
 -- Data: types.BuiltinMethodType

     内置函数例如 *note len(): 28b. 或 *note sys.exit(): daa. 以及内置类
     方法的类型。 （这里所说的“内置”是指“以 C 语言编写”。）

 -- Data: types.WrapperDescriptorType

     某些内置数据类型和基类的方法的类型，例如 *note object.__init__():
     e23. 或 *note object.__lt__(): cfe.。

     3.7 版新加入.

 -- Data: types.MethodWrapperType

     某些内置数据类型和基类的 `绑定' 方法的类型。 例如
     ‘object().__str__’ 所属的类型。

     3.7 版新加入.

 -- Data: types.MethodDescriptorType

     某些内置数据类型方法例如 *note str.join(): 1766. 的类型。

     3.7 版新加入.

 -- Data: types.ClassMethodDescriptorType

     某些内置数据类型 `非绑定' 类方法例如 ‘dict.__dict__['fromkeys']’ 的
     类型。

     3.7 版新加入.

 -- 類別: types.ModuleType (name, doc=None)

     *note 模块: 15e7. 的类型。 构造器接受待创建模块的名称并以其 *note
     docstring: 16eb. 作为可选参数。

          備註: 如果你希望设置各种由导入控制的属性，请使用 *note
          importlib.util.module_from_spec(): 7e1. 来创建一个新模块。

      -- 屬性: __doc__

          模块的 *note docstring: 16eb.。 默认为 ‘None’。

      -- 屬性: __loader__

          用于加载模块的 *note loader: 15f6.。 默认为 ‘None’。

          此属性会匹配保存在 attr:‘__spec__’ 对象中的 *note
          importlib.machinery.ModuleSpec.loader: 1afd.。

               備註: A future version of Python may stop setting this
               attribute by default.  To guard against this potential
               change, preferably read from the *note __spec__: 1603.
               attribute instead or use ‘getattr(module, "__loader__",
               None)’ if you explicitly need to use this attribute.

          3.4 版更變: 默认为 ‘None’。 之前该属性为可选项。

      -- 屬性: __name__

          模块的名称。 应当能匹配 *note
          importlib.machinery.ModuleSpec.name: 1aff.。

      -- 屬性: __package__

          一个模块所属的 *note package: 15eb.。 如果模块为最高层级的（即
          不是任何特定包的组成部分）则该属性应设为 ‘''’，否则它应设为特
          定包的名称 (如果模块本身也是一个包则名称可以为 *note __name__:
          dd8.)。 默认为 ‘None’。

          此属性会匹配保存在 attr:‘__spec__’ 对象中的 *note
          importlib.machinery.ModuleSpec.parent: 1b01.。

               備註: A future version of Python may stop setting this
               attribute by default.  To guard against this potential
               change, preferably read from the *note __spec__: 1603.
               attribute instead or use ‘getattr(module, "__package__",
               None)’ if you explicitly need to use this attribute.

          3.4 版更變: 默认为 ‘None’。 之前该属性为可选项。

      -- 屬性: __spec__

          模块的导入系统相关状态的记录。 应当是一个 *note
          importlib.machinery.ModuleSpec: 1601. 的实例。

          3.4 版新加入.

 -- 類別: types.GenericAlias (t_origin, t_args)

     *note 形参化泛型: fe5. 的类型，例如 ‘list[int]’。

     ‘t_origin’ 应当是一个非形参化的泛型类，例如 ‘list’, ‘tuple’ 或
     ‘dict’。 ‘t_args’ 应当是一个形参化 ‘t_origin’ 的 *note tuple: 1a2.
     (长度可以为 1):

          >>> from types import GenericAlias

          >>> list[int] == GenericAlias(list, (int,))
          True
          >>> dict[str, int] == GenericAlias(dict, (str, int))
          True

     3.9 版新加入.

     3.9.2 版更變: 此类型现在可以被子类化。

 -- 類別: types.TracebackType (tb_next, tb_frame, tb_lasti, tb_lineno)

     回溯对象的类型，例如 ‘sys.exc_info()[2]’ 中的对象。

     请查看 *note 语言参考: 442. 了解可用属性和操作的细节，以及动态地创
     建回溯对象的指南。

 -- Data: types.FrameType

     帧对象的类型，例如 ‘tb.tb_frame’ 中的对象，其中 ‘tb’ 是一个回溯对象
     。

     请查看 *note 语言参考: 1565. 了解可用属性和操作的细节。

 -- Data: types.GetSetDescriptorType

     使用 ‘PyGetSetDef’ 在扩展模块中定义的对象的类型，例如
     ‘FrameType.f_locals’ 或 ‘array.array.typecode’。 此类型被用作对象属
     性的描述器；它的目的与 *note property: 308. 类型相同，但专门针对在
     扩展模块中定义的类。

 -- Data: types.MemberDescriptorType

     使用 ‘PyMemberDef’ 在扩展模块中定义的对象的类型，例如
     ‘datetime.timedelta.days’。 此类型被用作使用标准转换函数的简单 C 数
     据成员的描述器；它的目的与 *note property: 308. 类型相同，但专门针
     对在扩展模块中定义的类。

     `CPython implementation detail:' 在 Python 的其它实现中，此类型可能
     与 ‘GetSetDescriptorType’ 完全相同。

 -- 類別: types.MappingProxyType (mapping)

     一个映射的只读代理。 它提供了对映射条目的动态视图，这意味着当映射发
     生改变时，视图会反映这些改变。

     3.3 版新加入.

     3.9 版更變: 更新为支持 PEP 584(1) 所新增的合并 (‘|’) 运算符，它会简
     单地委托给下层的映射。

      -- Describe: key in proxy

          如果下层的映射中存在键 `key' 则返回 ‘True’，否则返回 ‘False’。

      -- Describe: proxy[key]

          返回下层的映射中以 `key' 为键的项。 如果下层的映射中不存在键
          `key' 则引发 *note KeyError: 3e9.。

      -- Describe: iter(proxy)

          返回由下层映射的键为元素的迭代器。 这是 ‘iter(proxy.keys())’ 的
          快捷方式。

      -- Describe: len(proxy)

          返回下层映射中的项数。

      -- 成員函式: copy ()

          返回下层映射的浅拷贝。

      -- 成員函式: get (key[, default])

          如果 `key' 存在于下层映射中则返回 `key' 的值，否则返回
          `default'。 如果 `default' 未给出则默认为 ‘None’，因而此方法绝
          不会引发 *note KeyError: 3e9.。

      -- 成員函式: items ()

          返回由下层映射的项 (‘(键, 值)’ 对) 组成的一个新视图。

      -- 成員函式: keys ()

          返回由下层映射的键组成的一个新视图。

      -- 成員函式: values ()

          返回由下层映射的值组成的一个新视图。

      -- Describe: reversed(proxy)

          返回一个包含下层映射的键的反向迭代器。

          3.9 版新加入.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0584


File: python.info,  Node: 附加工具类和函数,  Next: 协程工具函数,  Prev: 标准解释器类型,  Up: types --- 动态类型创建和内置类型名称

5.8.10.3 附加工具类和函数
.........................

 -- 類別: types.SimpleNamespace

     一个简单的 *note object: 3d2. 子类，提供了访问其命名空间的属性，以
     及一个有意义的 repr。

     不同于 *note object: 3d2.，对于 ‘SimpleNamespace’ 你可以添加和移除
     属性。 如果一个 ‘SimpleNamespace’ 对象使用关键字参数进行初始化，这
     些参数会被直接加入下层命名空间。

     此类型大致等价于以下代码:

          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

     ‘SimpleNamespace’ 可被用于替代 ‘class NS: pass’。 但是，对于结构化
     记录类型则应改用 *note namedtuple(): 1a1.。

     3.3 版新加入.

     3.9 版更變: repr 中的属性顺序由字母顺序改为插入顺序 (类似 ‘dict’)。

 -- 函式: types.DynamicClassAttribute (fget=None, fset=None, fdel=None,
          doc=None)

     在类上访问 __getattr__ 的路由属性。

     这是一个描述器，用于定义通过实例与通过类访问时具有不同行为的属性。
     当实例访问时保持正常行为，但当类访问属性时将被路由至类的
     __getattr__ 方法；这是通过引发 AttributeError 来完成的。

     这允许有在实例上激活的特性属性，同时又有在类上的同名虚拟属性 (一个
     例子请参见 *note enum.Enum: 48d.)。

     3.4 版新加入.


File: python.info,  Node: 协程工具函数,  Prev: 附加工具类和函数,  Up: types --- 动态类型创建和内置类型名称

5.8.10.4 协程工具函数
.....................

 -- 函式: types.coroutine (gen_func)

     此函数可将 *note generator: a83. 函数转换为返回基于生成器的协程的
     *note coroutine function: 732.。 基于生成器的协程仍然属于 *note
     generator iterator: 558.，但同时又可被视为 *note coroutine: 18a. 对
     象兼 *note awaitable: 612.。 不过，它没有必要实现 *note
     __await__(): 735. 方法。

     如果 `gen_func' 是一个生成器函数，它将被原地修改。

     如果 `gen_func' 不是一个生成器函数，则它会被包装。 如果它返回一个
     *note collections.abc.Generator: 7a8. 的实例，该实例将被包装在一个
     `awaitable' 代理对象中。 所有其他对象类型将被原样返回。

     3.5 版新加入.


File: python.info,  Node: copy --- 浅层 shallow 和深层 deep 复制操作,  Next: pprint --- 数据美化输出,  Prev: types --- 动态类型创建和内置类型名称,  Up: 数据类型

5.8.11 ‘copy’ — 浅层 (shallow) 和深层 (deep) 复制操作
-----------------------------------------------------

`源代码:' Lib/copy.py(1)

__________________________________________________________________

Python 的赋值语句不复制对象，而是创建目标和对象的绑定关系。对于自身可变
，或包含可变项的集合，有时要生成副本用于改变操作，而不必改变原始对象。本
模块提供了通用的浅层复制和深层复制操作，（如下所述）。

接口摘要：

 -- 函式: copy.copy (x)

     返回 `x' 的浅层复制。

 -- 函式: copy.deepcopy (x[, memo])

     返回 `x' 的深层复制。

 -- 例外: copy.Error

     针对模块特定错误引发。
浅层与深层复制的区别仅与复合对象（即包含列表或类的实例等其他对象的对象）
相关：

   * `浅层复制' 构造一个新的复合对象，然后（在尽可能的范围内）将原始对象
     中找到的对象的 `引用' 插入其中。

   * `深层复制' 构造一个新的复合对象，然后，递归地将在原始对象里找到的对
     象的 `副本' 插入其中。

深度复制操作通常存在两个问题, 而浅层复制操作并不存在这些问题：

   * 递归对象 (直接或间接包含对自身引用的复合对象) 可能会导致递归循环。

   * 由于深层复制会复制所有内容，因此可能会过多复制（例如本应该在副本之
     间共享的数据）。

*note deepcopy(): 4d2. 函数用以下方式避免了这些问题：

   * 保留在当前复制过程中已复制的对象的 "备忘录" （‘memo’） 字典；以及

   * 允许用户定义的类重载复制操作或复制的组件集合。

This module does not copy types like module, method, stack trace, stack
frame, file, socket, window, or any similar types.  It does "copy"
functions and classes (shallow and deeply), by returning the original
object unchanged; this is compatible with the way these are treated by
the *note pickle: ca. module.

制作字典的浅层复制可以使用 *note dict.copy(): 548. 方法，而制作列表的浅
层复制可以通过赋值整个列表的切片完成，例如，‘copied_list =
original_list[:]’。

类可以使用与控制序列化（pickling）操作相同的接口来控制复制操作，关于这些
方法的描述信息请参考 *note pickle: ca. 模块。实际上，*note copy: 25. 模
块使用的正是从 *note copyreg: 26. 模块中注册的 pickle 函数。

想要给一个类定义它自己的拷贝操作实现，可以通过定义特殊方法 ‘__copy__()’
和 ‘__deepcopy__()’。 调用前者以实现浅层拷贝操作，该方法不用传入额外参数
。 调用后者以实现深层拷贝操作；它应传入一个参数即 ‘memo’ 字典。 如果
‘__deepcopy__()’ 实现需要创建一个组件的深层拷贝，它应当调用 *note
deepcopy(): 4d2. 函数并以该组件作为第一个参数，而将 memo 字典作为第二个
参数。

也參考
......

模块 *note pickle: ca.

     讨论了支持对象状态检索和恢复的特殊方法。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/copy.py


File: python.info,  Node: pprint --- 数据美化输出,  Next: reprlib --- 另一种 repr 实现,  Prev: copy --- 浅层 shallow 和深层 deep 复制操作,  Up: 数据类型

5.8.12 ‘pprint’ — 数据美化输出
------------------------------

`源代码：' Lib/pprint.py(1)

__________________________________________________________________

*note pprint: d2. 模块提供了“美化打印”任意 Python 数据结构的功能，这种美
化形式可用作对解释器的输入。 如果经格式化的结构包含非基本 Python 类型的
对象，则其美化形式可能无法被加载。 包含文件、套接字或类对象，以及许多其
他不能用 Python 字面值来表示的对象都有可能导致这样的结果。

格式化后的形式会在可能的情况下以单行来表示对象，并在无法在允许宽度内容纳
对象的情况下将其分为多行。 如果你需要调整宽度限制则应显式地构造 *note
PrettyPrinter: 97c. 对象。

字典在计算其显示形式前会先根据键来排序。

3.9 版更變: 添加了对美化打印 *note types.SimpleNamespace: 1d8. 的支持。

*note pprint: d2. 模块定义了一个类：

 -- 類別: pprint.PrettyPrinter (indent=1, width=80, depth=None,
          stream=None, *, compact=False, sort_dicts=True)

     构造一个 *note PrettyPrinter: 97c. 实例。 此构造器接受几个关键字形
     参。 使用 `stream' 关键字可设置输出流；流对象使用的唯一方法是文件协
     议的 ‘write()’ 方法。 如果未指定此关键字，则 *note PrettyPrinter:
     97c. 会选择 ‘sys.stdout’。 每个递归层次的缩进量由 `indent' 指定；默
     认值为一。 其他值可导致输出看起来有些怪异，，但可使得嵌套结构更易区
     分。 可被打印的层级数量由 `depth' 控制；如果数据结构的层级被打印得
     过深，其所包含的下一层级会被替换为 ‘...’。 在默认情况下，对被格式化
     对象的层级深度没有限制。 希望的输出宽度可使用 `width' 形参来限制；
     默认值为 80 个字符。 如果一个结构无法在限定宽度内被格式化，则将做到
     尽可能接近。 如果 `compact' 为假值（默认）则长序列的每一项将被格式
     化为单独的行。 如果 `compact' 为真值，则将在 `width' 可容纳的的情况
     下把尽可能多的项放入每个输出行。 如果 `sort_dicts' 为真值（默认），
     字典将被格式化为按键排序，否则将按插入顺序显示。

     3.4 版更變: 增加了 `compact' 形参。

     3.8 版更變: 增加了 `sort_dicts' 形参。

          >>> 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', (...)))))))

*note pprint: d2. 模块还提供了一些快捷函数：

 -- 函式: pprint.pformat (object, indent=1, width=80, depth=None, *,
          compact=False, sort_dicts=True)

     `object' 的格式化表示作为字符串返回。 `indent', `width', `depth',
     `compact' 和 `sort_dicts' 将作为格式化形参被传入 *note
     PrettyPrinter: 97c. 构造器。

     3.4 版更變: 增加了 `compact' 形参。

     3.8 版更變: 增加了 `sort_dicts' 形参。

 -- 函式: pprint.pp (object, *args, sort_dicts=False, **kwargs)

     打印 `object' 的格式化表示并附带一个换行符。 如果 `sort_dicts' 为假
     值（默认），字典将按键的插入顺序显示，否则将按字典键排序。 `args' 和
     `kwargs' 将作为格式化形参被传给 *note pprint(): d2.。

     3.8 版新加入.

 -- 函式: pprint.pprint (object, stream=None, indent=1, width=80,
          depth=None, *, compact=False, sort_dicts=True)

     在 `stream' 上打打印 `object' 的格式化表示，并附带一个换行符。 如果
     `stream' 为 ‘None’，则使用 ‘sys.stdout’。 这可以替代 *note print():
     971. 函数在交互式解释器中使用以查看值（你甚至可以执行重新赋值
     ‘print = pprint.pprint’ 以在特定作用域中使用）。 `indent', `width',
     `depth', `compact' 和 `sort_dicts' 将作为格式化形参被传给 *note
     PrettyPrinter: 97c. 构造器。

     3.4 版更變: 增加了 `compact' 形参。

     3.8 版更變: 增加了 `sort_dicts' 形参。

          >>> 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']

 -- 函式: pprint.isreadable (object)

     确定 `object' 的格式化表示是否“可读”，或是否可被用来通过 *note
     eval(): c61. 重新构建对象的值。 此函数对于递归对象总是返回 ‘False’。

          >>> pprint.isreadable(stuff)
          False

 -- 函式: pprint.isrecursive (object)

     确定 `object' 是否需要递归表示。

此外还定义了一个支持函数：

 -- 函式: pprint.saferepr (object)

     返回 `object' 的字符串表示，并为递归数据结构提供保护。 如果
     `object' 的表示形式公开了一个递归条目，该递归引用会被表示为
     ‘<Recursion on typename with id=number>’。 该表示因而不会进行其它格
     式化。

          >>> pprint.saferepr(stuff)
          "[<Recursion on list with id=...>, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']"

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/pprint.py


File: python.info,  Node: PrettyPrinter 对象,  Next: 示例<5>,  Up: pprint --- 数据美化输出

5.8.12.1 PrettyPrinter 对象
...........................

*note PrettyPrinter: 97c. 的实例具有下列方法：

 -- 成員函式: PrettyPrinter.pformat (object)

     返回 `object' 格式化表示。 这会将传给 *note PrettyPrinter: 97c. 构
     造器的选项纳入考虑。

 -- 成員函式: PrettyPrinter.pprint (object)

     在所配置的流上打印 `object' 的格式化表示，并附加一个换行符。

下列方法提供了与同名函数相对应的实现。 在实例上使用这些方法效率会更高一
些，因为不需要创建新的 *note PrettyPrinter: 97c. 对象。

 -- 成員函式: PrettyPrinter.isreadable (object)

     确定对象的格式化表示是否“可读”，或者是否可使用 *note eval(): c61. 重
     建对象值。 请注意此方法对于递归对象将返回 ‘False’。 如果设置了
     *note PrettyPrinter: 97c. 的 `depth' 形参并且对象深度超出允许范围，
     此方法将返回 ‘False’。

 -- 成員函式: PrettyPrinter.isrecursive (object)

     确定对象是否需要递归表示。

此方法作为一个钩子提供，允许子类修改将对象转换为字符串的方式。 默认实现
使用 *note saferepr(): 1b14. 实现的内部方式。

 -- 成員函式: PrettyPrinter.format (object, context, maxlevels, level)

     返回三个值：字符串形式的 `object' 已格式化版本，指明结果是否可读的
     旗标，以及指明是否检测到递归的旗标。 第一个参数是要表示的对象。 第
     二个是以对象 *note id(): e4b. 为键的字典，这些对象是当前表示上下文
     的一部分（影响 `object' 表示的直接和间接容器）；如果需要呈现一个已
     经在 `context' 中表示的对象，则第三个返回值应当为 ‘True’。 对 *note
     format(): 1b1b. 方法的递归调用应当将容器的附加条目添加到此字典中。
     第三个参数 `maxlevels' 给出了对递归的请求限制；如果没有请求限制则其
     值将为 ‘0’。 此参数应当不加修改地传给递归调用。 第四个参数 `level'
     给出于当前层级；传给递归调用的参数值应当小于当前调用的值。


File: python.info,  Node: 示例<5>,  Prev: PrettyPrinter 对象,  Up: pprint --- 数据美化输出

5.8.12.2 示例
.............

为了演示 *note pprint(): d2. 函数及其形参的几种用法，让我们从 PyPI(1) 获
取关于某个项目的信息:

     >>> 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']

*note pprint(): d2. 以其基本形式显示了整个对象:

     >>> 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'}

结果可以被限制到特定的 `depth' (更深层的内容将使用省略号):

     >>> 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'}

此外，还可以设置建议的最大字符 `width'。 如果一个对象无法被拆分，则将超
出指定宽度:

     >>> 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'}

   ---------- Footnotes ----------

   (1) https://pypi.org


File: python.info,  Node: reprlib --- 另一种 repr 实现,  Next: enum --- 对枚举的支持,  Prev: pprint --- 数据美化输出,  Up: 数据类型

5.8.13 ‘reprlib’ — 另一种 ‘repr()’ 实现
---------------------------------------

`源代码:' Lib/reprlib.py(1)

__________________________________________________________________

*note reprlib: df. 模块提供了一种对象表示的产生方式，它会对结果字符串的
大小进行限制。 该方式被用于 Python 调试器，也适用于某些其他场景。

此模块提供了一个类、一个实例和一个函数：

 -- 類別: reprlib.Repr

     该类提供了格式化服务 适用于实现与内置 *note repr(): 8b9. 相似的方法
     ；其中附加了针对不同对象类型的大小限制，以避免生成超长的表示。

 -- Data: reprlib.aRepr

     这是 *note Repr: 1b20. 的一个实例，用于提供如下所述的 *note repr():
     1b22. 函数。 改变此对象的属性将会影响 *note repr(): 1b22. 和 Python
     调试器所使用的大小限制。

 -- 函式: reprlib.repr (obj)

     这是 ‘aRepr’ 的 *note repr(): 1b23. 方法。 它会返回与同名内置函数所
     返回字符串相似的字符串，区别在于附带了对多数类型的大小限制。

在大小限制工具以外，此模块还提供了一个装饰器，用于检测对 *note
__repr__(): 44a. 的递归调用并改用一个占位符来替换。

 -- 函式: @reprlib.recursive_repr (fillvalue="...")

     用于为 *note __repr__(): 44a. 方法检测同一线程内部递归调用的装饰器
     。 如果执行了递归调用，则会返回 `fillvalue'，否则执行正常的 *note
     __repr__(): 44a. 调用。 例如：

          >>> 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'>

     3.2 版新加入.

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/reprlib.py


File: python.info,  Node: Repr 对象,  Next: 子类化 Repr 对象,  Up: reprlib --- 另一种 repr 实现

5.8.13.1 Repr 对象
..................

*note Repr: 1b20. 实例对象包含一些属性可以用于为不同对象类型的表示提供大
小限制，还包含一些方法可以格式化特定的对象类型。

 -- 屬性: Repr.maxlevel

     创建递归表示形式的深度限制。 默认为 ‘6’。

 -- 屬性: Repr.maxdict
 -- 屬性: Repr.maxlist
 -- 屬性: Repr.maxtuple
 -- 屬性: Repr.maxset
 -- 屬性: Repr.maxfrozenset
 -- 屬性: Repr.maxdeque
 -- 屬性: Repr.maxarray

     代表命名对象类型的条目数量限制。 对于 *note maxdict: 1b27. 的默认值
     为 ‘4’，对于 *note maxarray: 1b2d. 为 ‘5’，对于其他则为 ‘6’。

 -- 屬性: Repr.maxlong

     表示整数的最大字符数量。 数码会从中间被丢弃。 默认值为 ‘40’。

 -- 屬性: Repr.maxstring

     表示字符串的字符数量限制。 请注意字符源会使用字符串的“正常”表示形式
     ：如果表示中需要用到转义序列，在缩短表示时它们可能会被破坏。 默认值
     为 ‘30’。

 -- 屬性: Repr.maxother

     此限制用于控制在 *note Repr: 1b20. 对象上没有特定的格式化方法可用的
     对象类型的大小。 它会以类似 *note maxstring: 1b2f. 的方式被应用。 默
     认值为 ‘20’。

 -- 成員函式: Repr.repr (obj)

     内置 *note repr(): 8b9. 的等价形式，它使用实例专属的格式化。

 -- 成員函式: Repr.repr1 (obj, level)

     供 *note repr(): 1b23. 使用的递归实现。 此方法使用 `obj' 的类型来确
     定要调用哪个格式化方法，并传入 `obj' 和 `level'。 类型专属的方法应
     当调用 *note repr1(): 1b31. 来执行递归格式化，在递归调用中使用
     ‘level - 1’ 作为 `level' 的值。

 -- 成員函式: Repr.repr_TYPE (obj, level)

     特定类型的格式化方法会被实现为基于类型名称来命名的方法。 在方法名称
     中，`TYPE' 会被替换为 ‘'_'.join(type(obj).__name__.split())’。 对这
     些方法的分派会由 *note repr1(): 1b31. 来处理。 需要对值进行递归格式
     化的类型专属方法应当调用 ‘self.repr1(subobj, level - 1)’。


File: python.info,  Node: 子类化 Repr 对象,  Prev: Repr 对象,  Up: reprlib --- 另一种 repr 实现

5.8.13.2 子类化 Repr 对象
.........................

通过 *note Repr.repr1(): 1b31. 使用动态分派允许 *note Repr: 1b20. 的子类
添加对额外内置对象类型的支持，或是修改对已支持类型的处理。 这个例子演示
了如何添加对文件对象的特殊支持:

     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>'


File: python.info,  Node: enum --- 对枚举的支持,  Next: graphlib --- 操作类似图的结构的功能,  Prev: reprlib --- 另一种 repr 实现,  Up: 数据类型

5.8.14 ‘enum’ — 对枚举的支持
----------------------------

3.4 版新加入.

`源代码：' Lib/enum.py(1)

__________________________________________________________________

枚举是与多个唯一常量值绑定的一组符号名（即成员）。枚举中的成员可以进行身
份比较，并且枚举自身也可迭代。

     備註: 枚举成员名称的大小写

     枚举表示的是常量，因此，建议枚举成员名称使用大写字母，本篇的示例将
     用此种风格。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/enum.py


File: python.info,  Node: 模块内容<2>,  Next: 创建 Enum,  Up: enum --- 对枚举的支持

5.8.14.1 模块内容
.................

本模块定义了四个枚举类，用来定义名称与值的唯一组合: *note Enum: 48d.、
*note IntEnum: 684.、*note Flag: 63f. 和 *note IntFlag: 18a1.。此外，还
定义了一个装饰器，*note unique(): 1b37.， 和一个辅助类，*note auto:
640.。

 -- 類別: enum.Enum

     创建枚举常量的基类。 如需了解另一种构建语法，请参阅 *note
     Functional API: 1b38. 小节。

 -- 類別: enum.IntEnum

     创建 *note int: 204. 子类枚举常量的基类。

 -- 類別: enum.IntFlag

     创建可与位运算符搭配使用，又不失去 *note IntFlag: 18a1. 成员资格的
     枚举常量的基类。*note IntFlag: 18a1. 成员也是 *note int: 204. 的子
     类。

 -- 類別: enum.Flag

     创建可与位运算符搭配使用，又不会失去 *note Flag: 63f. 成员资格的枚
     举常量的基类。

 -- 函式: enum.unique ()

     确保一个名称只绑定一个值的 Enum 类装饰器。

 -- 類別: enum.auto

     以合适的值代替 Enum 成员的实例。 初始值默认从 1 开始。

3.6 版新加入: ‘Flag’, ‘IntFlag’, ‘auto’


File: python.info,  Node: 创建 Enum,  Next: 枚举成员及其属性的编程访问,  Prev: 模块内容<2>,  Up: enum --- 对枚举的支持

5.8.14.2 创建 Enum
..................

枚举是由 *note class: d32. 句法创建的，这种方式易读、易写。 另一种创建方
法请参阅 *note Functional API: 1b38.。*note Enum: 48d. 以如下定义枚举：

     >>> from enum import Enum
     >>> class Color(Enum):
     ...     RED = 1
     ...     GREEN = 2
     ...     BLUE = 3
     ...

     備註: Enum 成员值

     成员值可以是 *note int: 204.、*note str: 205. 等。若无需设定确切值
     ，*note auto: 640. 实例可以自动为成员分配合适 的值。将 *note auto:
     640. 与其他值混用时必须要慎重。

     備註: 命名法

        - 类 ‘Color’ 是 `枚举' （或称为 `enum' ）。

        - ‘Color.RED’、‘Color.GREEN’ 等属性是 `枚举成员' （或 `enum 成员
          '），也是常量。

        - 枚举成员具有 `名称' 和 `值' (例如 ‘Color.RED’ 的名称为 ‘RED’，
          ‘Color.BLUE’ 的值为 ‘3’ 等等)

     備註: 虽然 Enum 由 *note class: d32. 语法创建，但 Enum 并不是常规的
     Python 类。详见 *note How are Enums different?: 1b3a.。

枚举成员的字符串表现形式更容易理解：

     >>> print(Color.RED)
     Color.RED

同时，它的 ‘repr’ 包含更多信息：

     >>> print(repr(Color.RED))
     <Color.RED: 1>

枚举成员的 `类型' 就是它所属的枚举：

     >>> type(Color.RED)
     <enum 'Color'>
     >>> isinstance(Color.GREEN, Color)
     True
     >>>

Enum 成员还包含 name 属性：

     >>> print(Color.RED.name)
     RED

枚举按定义的顺序进行迭代：

     >>> 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

枚举成员可哈希，可用于字典和集合：

     >>> apples = {}
     >>> apples[Color.RED] = 'red delicious'
     >>> apples[Color.GREEN] = 'granny smith'
     >>> apples == {Color.RED: 'red delicious', Color.GREEN: 'granny smith'}
     True


File: python.info,  Node: 枚举成员及其属性的编程访问,  Next: 重复的枚举成员和值,  Prev: 创建 Enum,  Up: enum --- 对枚举的支持

5.8.14.3 枚举成员及其属性的编程访问
...................................

有时，要在程序中访问枚举成员（如，开发时不知道颜色的确切值，‘Color.RED’
不适用的情况）。‘Enum’ 支持如下访问方式：

     >>> Color(1)
     <Color.RED: 1>
     >>> Color(3)
     <Color.BLUE: 3>

用 `name' 访问枚举成员时，可使用项目名称：

     >>> Color['RED']
     <Color.RED: 1>
     >>> Color['GREEN']
     <Color.GREEN: 2>

可访问枚举成员的 ‘name’ 或 ‘value’：

     >>> member = Color.RED
     >>> member.name
     'RED'
     >>> member.value
     1


File: python.info,  Node: 重复的枚举成员和值,  Next: 确保唯一枚举值,  Prev: 枚举成员及其属性的编程访问,  Up: enum --- 对枚举的支持

5.8.14.4 重复的枚举成员和值
...........................

两个枚举成员的名称不能相同：

     >>> class Shape(Enum):
     ...     SQUARE = 2
     ...     SQUARE = 3
     ...
     Traceback (most recent call last):
     ...
     TypeError: Attempted to reuse key: 'SQUARE'

但是，两个枚举成员可以有相同的值。假设，成员 A 和 B 的值相同（先定义的是
A），则 B 是 A 的别名。按值查找 A 和 B 的值返回的是 A。按名称查找 B，返
回的也是 A：

     >>> 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>

     備註: 不支持创建与已定义属性（其他成员、方法等）同名的成员，也不支
     持创建与现有成员同名的属性。


File: python.info,  Node: 确保唯一枚举值,  Next: 使用自动设定的值,  Prev: 重复的枚举成员和值,  Up: enum --- 对枚举的支持

5.8.14.5 确保唯一枚举值
.......................

默认情况下，枚举允许多个名称作为一个值的别名。如需禁用此行为，下述装饰器
可以确保枚举中的值仅能只用一次：

 -- 函式: @enum.unique

专用于枚举的 *note class: d32. 装饰器。 它会搜索一个枚举的 ‘__members__’
并收集所找到的任何别名；只要找到任何别名就会引发 *note ValueError: 16d.
并附带相关细节信息:

     >>> 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


File: python.info,  Node: 使用自动设定的值,  Next: 迭代,  Prev: 确保唯一枚举值,  Up: enum --- 对枚举的支持

5.8.14.6 使用自动设定的值
.........................

如果确切的值不重要，你可以使用 *note auto: 640.:

     >>> 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>]

值将由 ‘_generate_next_value_()’ 来选择，该函数可以被重载:

     >>> 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'>]

     備註: 默认 ‘_generate_next_value_()’ 方法的目标是提供所给出的最后一
     个 *note int: 204. 所在序列的下一个 *note int: 204.，但这种行为方式
     属于实现细节并且可能发生改变。

     備註: ‘_generate_next_value_()’ 方法定义必须在任何其他成员之前。


File: python.info,  Node: 迭代,  Next: 比较<2>,  Prev: 使用自动设定的值,  Up: enum --- 对枚举的支持

5.8.14.7 迭代
.............

对枚举成员的迭代不会给出别名:

     >>> list(Shape)
     [<Shape.SQUARE: 2>, <Shape.DIAMOND: 1>, <Shape.CIRCLE: 3>]

特殊属性 ‘__members__’ 是一个从名称到成员的只读有序映射。 它包含枚举中定
义的所有名称，包括别名:

     >>> 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>)

‘__members__’ 属性可被用于对枚举成员进行详细的程序化访问。 例如，找出所
有别名:

     >>> [name for name, member in Shape.__members__.items() if member.name != name]
     ['ALIAS_FOR_SQUARE']


File: python.info,  Node: 比较<2>,  Next: 允许的枚举成员和属性,  Prev: 迭代,  Up: enum --- 对枚举的支持

5.8.14.8 比较
.............

枚举成员是按标识号进行比较的:

     >>> Color.RED is Color.RED
     True
     >>> Color.RED is Color.BLUE
     False
     >>> Color.RED is not Color.BLUE
     True

枚举值之间的排序比较 `不被' 支持。 Enum 成员不属于整数 (另请参阅下文的
*note IntEnum: 1b41.):

     >>> Color.RED < Color.BLUE
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     TypeError: '<' not supported between instances of 'Color' and 'Color'

相等比较的定义如下:

     >>> Color.BLUE == Color.RED
     False
     >>> Color.BLUE != Color.RED
     True
     >>> Color.BLUE == Color.BLUE
     True

与非枚举值的比较将总是不相等（同样地，*note IntEnum: 684. 被显式设计成不
同的行为，参见下文）:

     >>> Color.BLUE == 2
     False


File: python.info,  Node: 允许的枚举成员和属性,  Next: 受限的 Enum 子类化,  Prev: 比较<2>,  Up: enum --- 对枚举的支持

5.8.14.9 允许的枚举成员和属性
.............................

以上示例使用整数作为枚举值。 使用整数相当简洁方便（并由 *note Functional
API: 1b38. 默认提供），但并不强制要求使用。 在大部分用例中，开发者都关心
枚举的实际值是什么。 但如果值 `确实' 重要，则枚举可以使用任意的值。

枚举属于 Python 的类，并可具有普通方法和特殊方法。 如果我们有这样一个枚
举:

     >>> 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
     ...

那么:

     >>> Mood.favorite_mood()
     <Mood.HAPPY: 3>
     >>> Mood.HAPPY.describe()
     ('HAPPY', 3)
     >>> str(Mood.FUNKY)
     'my custom str! 1'

对于允许内容的规则如下：以单下划线开头和结尾的名称是由枚举保留而不可使用
；在枚举中定义的所有其他属性将成为该枚举的成员，例外项则包括特殊方法成员
(*note __str__(): ef9, *note __add__(): 1595. 等)，描述符 (方法也属于描
述符) 以及在 ‘_ignore_’ 中列出的变量名。

注意：如果你的枚举定义了 *note __new__(): 974. 和/或 *note __init__():
e23. 那么给予枚举成员的任何值都会被传入这些方法。 请参阅示例 *note
Planet: 1b43.。


File: python.info,  Node: 受限的 Enum 子类化,  Next: 封存,  Prev: 允许的枚举成员和属性,  Up: enum --- 对枚举的支持

5.8.14.10 受限的 Enum 子类化
............................

一个新的 *note Enum: 48d. 类必须基于一个 Enum 类，至多一个实体数据类型以
及出于实际需要的任意多个基于 *note object: 3d2. 的 mixin 类。 这些基类的
顺序为:

     class EnumName([mix-in, ...,] [data-type,] base-enum):
         pass

另外，仅当一个枚举未定义任何成员时才允许子类化该枚举。 因此禁止这样的写
法:

     >>> class MoreColor(Color):
     ...     PINK = 17
     ...
     Traceback (most recent call last):
     ...
     TypeError: Cannot extend enumerations

但是允许这样的写法:

     >>> class Foo(Enum):
     ...     def some_behavior(self):
     ...         pass
     ...
     >>> class Bar(Foo):
     ...     HAPPY = 1
     ...     SAD = 2
     ...

允许子类化定义了成员的枚举将会导致违反类型与实例的某些重要的不可变规则。
在另一方面，允许在一组枚举之间共享某些通用行为也是有意义的。 （请参阅示
例 *note OrderedEnum: 1b45. 。）


File: python.info,  Node: 封存,  Next: 功能性 API,  Prev: 受限的 Enum 子类化,  Up: enum --- 对枚举的支持

5.8.14.11 封存
..............

枚举可以被封存与解封:

     >>> from test.test_enum import Fruit
     >>> from pickle import dumps, loads
     >>> Fruit.TOMATO is loads(dumps(Fruit.TOMATO))
     True

封存的常规限制同样适用：可封存枚举必须在模块的最高层级中定义，因为解封操
作要求它们可以从该模块导入。

     備註: 使用 pickle 协议版本 4 可以方便地封存嵌套在其他类中的枚举。

通过在枚举类中定义 *note __reduce_ex__(): 1b47. 可以对 Enum 成员的封存
/解封方式进行修改。


File: python.info,  Node: 功能性 API,  Next: 派生的枚举,  Prev: 封存,  Up: enum --- 对枚举的支持

5.8.14.12 功能性 API
....................

*note Enum: 48d. 类属于可调用对象，它提供了以下功能性 API:

     >>> 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>]

该 API 的主义类似于 *note namedtuple: 1a1.。 调用 *note Enum: 48d. 的第
一个参数是枚举的名称。

第二个参数是枚举成员名称的 `来源'。 它可以是一个用空格分隔的名称字符串、
名称序列、键/值对 2 元组的序列，或者名称到值的映射（例如字典）。 最后两
种选项使得可以为枚举任意赋值；其他选项会自动以从 1 开始递增的整数赋值（
使用 ‘start’ 形参可指定不同的起始值）。 返回值是一个派生自 *note Enum:
48d. 的新类。 换句话说，以上对 ‘Animal’ 的赋值就等价于:

     >>> class Animal(Enum):
     ...     ANT = 1
     ...     BEE = 2
     ...     CAT = 3
     ...     DOG = 4
     ...

默认以 ‘1’ 而以 ‘0’ 作为起始数值的原因在于 ‘0’ 的布尔值为 ‘False’，但所
有枚举成员都应被求值为 ‘True’。

对使用功能性 API 创建的枚举执行封存可能会很麻烦，因为要使用帧堆栈的实现
细节来尝试并找出枚举是在哪个模块中创建的（例如当你使用了另一个模块中的工
具函数就可能失败，在 IronPython 或 Jython 上也可能无效）。 解决办法是显
式地指定模块名称，如下所示:

     >>> Animal = Enum('Animal', 'ANT BEE CAT DOG', module=__name__)

     警告: 如果未提供 ‘module’，且 Enum 无法确定是哪个模块，新的 Enum 成
     员将不可被解封；为了让错误尽量靠近源头，封存将被禁用。

新的 pickle 协议版本 4 在某些情况下同样依赖于 *note __qualname__: 155b.
被设为特定位置以便 pickle 能够找到相应的类。 例如，类是否存在于全局作用
域的 SomeData 类中:

     >>> Animal = Enum('Animal', 'ANT BEE CAT DOG', qualname='SomeData.Animal')

完整的签名为:

     Enum(value='NewEnumName', names=<...>, *, module='...', qualname='...', type=<mixed-in class>, start=1)


值: 将被新 Enum 类将记录为其名称的数据。


名称: Enum 的成员。 这可以是一个空格或逗号分隔的字符串 (起始值将为 1，除
非另行指定):

     'RED GREEN BLUE' | 'RED,GREEN,BLUE' | 'RED, GREEN, BLUE'

或是一个名称的迭代器:

     ['RED', 'GREEN', 'BLUE']

或是一个 (名称, 值) 对的迭代器:

     [('CYAN', 4), ('MAGENTA', 5), ('YELLOW', 6)]

或是一个映射:

     {'CHARTREUSE': 7, 'SEA_GREEN': 11, 'ROSEMARY': 42}


模块: 新 Enum 类所在模块的名称。


qualname: 新 Enum 类在模块中的具体位置。


类型: 要加入新 Enum 类的类型。


start: 当只传入名称时要使用的起始数值。

3.5 版更變: 增加了 `start' 形参。


File: python.info,  Node: 派生的枚举,  Next: 何时使用 __new__ 与 __init__,  Prev: 功能性 API,  Up: enum --- 对枚举的支持

5.8.14.13 派生的枚举
....................

* Menu:

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


File: python.info,  Node: IntEnum,  Next: IntFlag,  Up: 派生的枚举

5.8.14.14 IntEnum
.................

所提供的第一个变种 *note Enum: 48d. 同时也是 *note int: 204. 的一个子类
。 *note IntEnum: 684. 的成员可与整数进行比较；通过扩展，不同类型的整数
枚举也可以相互进行比较:

     >>> 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

不过，它们仍然不可与标准 *note Enum: 48d. 枚举进行比较:

     >>> class Shape(IntEnum):
     ...     CIRCLE = 1
     ...     SQUARE = 2
     ...
     >>> class Color(Enum):
     ...     RED = 1
     ...     GREEN = 2
     ...
     >>> Shape.CIRCLE == Color.RED
     False

*note IntEnum: 684. 值在其他方面的行为都如你预期的一样类似于整数:

     >>> int(Shape.CIRCLE)
     1
     >>> ['a', 'b', 'c'][Shape.CIRCLE]
     'b'
     >>> [i for i in range(Shape.SQUARE)]
     [0, 1]


File: python.info,  Node: IntFlag,  Next: Flag,  Prev: IntEnum,  Up: 派生的枚举

5.8.14.15 IntFlag
.................

所提供的下一个 *note Enum: 48d. 的变种 *note IntFlag: 18a1. 同样是基于
*note int: 204. 的，不同之处在于 *note IntFlag: 18a1. 成员可使用按位运算
符 (&, |, ^, ~) 进行组合且结果仍然为 *note IntFlag: 18a1. 成员。 如果，
正如名称所表明的，*note IntFlag: 18a1. 成员同时也是 *note int: 204. 的子
类，并能在任何使用 *note int: 204. 的场合被使用。 *note IntFlag: 18a1. 成
员进行除按位运算以外的其他运算都将导致失去 *note IntFlag: 18a1. 成员资格
。

3.6 版新加入.

示例 *note IntFlag: 18a1. 类:

     >>> 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

对于组合同样可以进行命名:

     >>> class Perm(IntFlag):
     ...     R = 4
     ...     W = 2
     ...     X = 1
     ...     RWX = 7
     >>> Perm.RWX
     <Perm.RWX: 7>
     >>> ~Perm.RWX
     <Perm.-8: -8>

*note IntFlag: 18a1. 和 *note Enum: 48d. 的另一个重要区别在于如果没有设
置任何旗标（值为 0），则其布尔值为 *note False: 48e.:

     >>> Perm.R & Perm.X
     <Perm.0: 0>
     >>> bool(Perm.R & Perm.X)
     False

由于 *note IntFlag: 18a1. 成员同时也是 *note int: 204. 的子类，因此它们
可以相互组合:

     >>> Perm.X | 8
     <Perm.8|X: 9>


File: python.info,  Node: Flag,  Next: 其他事项,  Prev: IntFlag,  Up: 派生的枚举

5.8.14.16 Flag
..............

最后一个变种是 *note Flag: 63f.。 与 *note IntFlag: 18a1. 类似，*note
Flag: 63f. 成员可使用按位运算符 (&, |, ^, ~) 进行组合，与 *note IntFlag:
18a1. 不同的是它们不可与任何其它 *note Flag: 63f. 枚举或 *note int: 204.
进行组合或比较。 虽然可以直接指定值，但推荐使用 *note auto: 640. 作为值
以便让 *note Flag: 63f. 选择适当的值。

3.6 版新加入.

与 *note IntFlag: 18a1. 类似，如果 *note Flag: 63f. 成员的某种组合导致没
有设置任何旗标，则其布尔值为 *note False: 48e.:

     >>> 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

单个旗标的值应当为二的乘方 (1, 2, 4, 8, ...)，旗标的组合则无此限制:

     >>> class Color(Flag):
     ...     RED = auto()
     ...     BLUE = auto()
     ...     GREEN = auto()
     ...     WHITE = RED | BLUE | GREEN
     ...
     >>> Color.WHITE
     <Color.WHITE: 7>

对 "no flags set" 条件指定一个名称并不会改变其布尔值:

     >>> class Color(Flag):
     ...     BLACK = 0
     ...     RED = auto()
     ...     BLUE = auto()
     ...     GREEN = auto()
     ...
     >>> Color.BLACK
     <Color.BLACK: 0>
     >>> bool(Color.BLACK)
     False

     備註: 对于大多数新代码，强烈推荐使用 *note Enum: 48d. 和 *note
     Flag: 63f.，因为 *note IntEnum: 684. 和 *note IntFlag: 18a1. 打破了
     枚举的某些语义约定（例如可以同整数进行比较，并因而导致此行为被传递
     给其他无关的枚举）。 *note IntEnum: 684. 和 *note IntFlag: 18a1. 的
     使用应当仅限于 *note Enum: 48d. 和 *note Flag: 63f. 无法使用的场合
     ；例如，当使用枚举替代整数常量时，或是与其他系统进行交互操作时。


File: python.info,  Node: 其他事项,  Prev: Flag,  Up: 派生的枚举

5.8.14.17 其他事项
..................

虽然 *note IntEnum: 684. 是 *note enum: 79. 模块的一部分，但要独立实现也
应该相当容易:

     class IntEnum(int, Enum):
         pass

这里演示了如何定义类似的派生枚举；例如一个混合了 *note str: 205. 而不是
*note int: 204. 的 ‘StrEnum’。

几条规则：

  1. 当子类化 *note Enum: 48d. 时，在基类序列中的混合类型必须出现于
     *note Enum: 48d. 本身之前，如以上 *note IntEnum: 684. 的例子所示。

  2. 虽然 *note Enum: 48d. 可以拥有任意类型的成员，不过一旦你混合了附加
     类型，则所有成员必须为相应类型的值，如在上面的例子中即为 *note int:
     204.。 此限制不适用于仅添加方法而未指定另一数据类型的混合类。

  3. 当混合了另一数据类型时，‘value’ 属性会 `不同于' 枚举成员自身，但它
     们仍保持等价且比较结果也相等。

  4. %-style formatting: ‘%s’ 和 ‘%r’ 会分别调用 *note Enum: 48d. 类的
     *note __str__(): ef9. 和 *note __repr__(): 44a.；其他代码 (例如表示
     IntEnum 的 ‘%i’ 或 ‘%h’) 会将枚举成员视为对应的混合类型。

  5. *note 格式化字符串字面值: 296, *note str.format(): 5d4. 和 *note
     format(): 5d5. 将使用混合类型的 *note __format__(): a2f. 除非在子类
     中重载了 *note __str__(): ef9. 或 *note __format__(): a2f.，在这种
     情况下将使用被重载的方法或 *note Enum: 48d. 的方法。 请使用 !s 和
     !r 格式代码来强制使用 *note Enum: 48d. 类的 *note __str__(): ef9. 和
     *note __repr__(): 44a. 方法。


File: python.info,  Node: 何时使用 __new__ 与 __init__,  Next: 有趣的示例,  Prev: 派生的枚举,  Up: enum --- 对枚举的支持

5.8.14.18 何时使用 ‘__new__()’ 与 ‘__init__()’
..............................................

当你想要定制 *note Enum: 48d. 成员的实际值时必须使用 *note __new__():
974.。 任何其他修改可以用 *note __new__(): 974. 也可以用 *note
__init__(): e23.，应优先使用 *note __init__(): e23.。

举例来说，如果你要向构造器传入多个条目，但只希望将其中一个作为值:

     >>> 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


File: python.info,  Node: 有趣的示例,  Next: 各种枚举有何区别？,  Prev: 何时使用 __new__ 与 __init__,  Up: enum --- 对枚举的支持

5.8.14.19 有趣的示例
....................

虽然 *note Enum: 48d, *note IntEnum: 684, *note IntFlag: 18a1. 和 *note
Flag: 63f. 预期可覆盖大多数应用场景，但它们无法覆盖全部。 这里有一些不同
类型枚举的方案，它们可以被直接使用，或是作为自行创建的参考示例。

* Menu:

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


File: python.info,  Node: 省略值,  Next: OrderedEnum,  Up: 有趣的示例

5.8.14.20 省略值
................

在许多应用场景中人们都不关心枚举的实际值是什么。 有几个方式可以定义此种
类型的简单枚举：

   - 使用 *note auto: 640. 的实例作为值

   - 使用 *note object: 3d2. 的实例作为值

   - 使用描述性的字符串作为值

   - 使用元组作为值并用自定义的 *note __new__(): 974. 以一个 *note int:
     204. 值来替代该元组

使用以上任何一种方法均可向用户指明值并不重要，并且使人能够添加、移除或重
排序成员而不必改变其余成员的数值。

无论你选择何种方法，你都应当提供一个 *note repr(): 8b9. 并且它也需要隐藏
（不重要的）值:

     >>> class NoValue(Enum):
     ...     def __repr__(self):
     ...         return '<%s.%s>' % (self.__class__.__name__, self.name)
     ...

* Menu:

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


File: python.info,  Node: 使用 auto,  Next: 使用 object,  Up: 省略值

5.8.14.21 使用 ‘auto’
.....................

使用 *note auto: 640. 的形式如下:

     >>> class Color(NoValue):
     ...     RED = auto()
     ...     BLUE = auto()
     ...     GREEN = auto()
     ...
     >>> Color.GREEN
     <Color.GREEN>


File: python.info,  Node: 使用 object,  Next: 使用描述性字符串,  Prev: 使用 auto,  Up: 省略值

5.8.14.22 使用 ‘object’
.......................

使用 *note object: 3d2. 的形式如下:

     >>> class Color(NoValue):
     ...     RED = object()
     ...     GREEN = object()
     ...     BLUE = object()
     ...
     >>> Color.GREEN
     <Color.GREEN>


File: python.info,  Node: 使用描述性字符串,  Next: 使用自定义的 __new__,  Prev: 使用 object,  Up: 省略值

5.8.14.23 使用描述性字符串
..........................

使用字符串作为值的形式如下:

     >>> class Color(NoValue):
     ...     RED = 'stop'
     ...     GREEN = 'go'
     ...     BLUE = 'too fast!'
     ...
     >>> Color.GREEN
     <Color.GREEN>
     >>> Color.GREEN.value
     'go'


File: python.info,  Node: 使用自定义的 __new__,  Prev: 使用描述性字符串,  Up: 省略值

5.8.14.24 使用自定义的 ‘__new__()’
..................................

使用自动编号 *note __new__(): 974. 的形式如下:

     >>> 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

要实现更通用的 ‘AutoNumber’，请添加 ‘*args’ 到签名中:

     >>> 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
     ...

这样当你从 ‘AutoNumber’ 继承时你将可以编写你自己的 ‘__init__’ 来处理任何
附加参数:

     >>> 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'

     備註: 如果定义了 *note __new__(): 974. 则它会在创建 Enum 成员期间被
     使用；随后它将被 Enum 的 *note __new__(): 974. 所替换，该方法会在类
     创建后被用来查找现有成员。


File: python.info,  Node: OrderedEnum,  Next: DuplicateFreeEnum,  Prev: 省略值,  Up: 有趣的示例

5.8.14.25 OrderedEnum
.....................

一个有序枚举，它不是基于 *note IntEnum: 684.，因此保持了正常的 *note
Enum: 48d. 不变特性（例如不可与其他枚举进行比较）:

     >>> 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


File: python.info,  Node: DuplicateFreeEnum,  Next: Planet,  Prev: OrderedEnum,  Up: 有趣的示例

5.8.14.26 DuplicateFreeEnum
...........................

如果发现重复的成员名称则将引发错误而不是创建别名:

     >>> 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'

     備註: 这个例子适用于子类化 Enum 来添加或改变禁用别名以及其他行为。
     如果需要的改变只是禁用别名，也可以选择使用 *note unique(): 1b37. 装
     饰器。


File: python.info,  Node: Planet,  Next: TimePeriod,  Prev: DuplicateFreeEnum,  Up: 有趣的示例

5.8.14.27 Planet
................

如果定义了 *note __new__(): 974. 或 *note __init__(): e23. 则枚举成员的
值将被传给这些方法:

     >>> 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


File: python.info,  Node: TimePeriod,  Prev: Planet,  Up: 有趣的示例

5.8.14.28 TimePeriod
....................

一个演示如何使用 ‘_ignore_’ 属性的例子:

     >>> 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)>]


File: python.info,  Node: 各种枚举有何区别？,  Prev: 有趣的示例,  Up: enum --- 对枚举的支持

5.8.14.29 各种枚举有何区别？
............................

枚举具有自定义的元类，它会影响所派生枚举类及其实例（成员）的各个方面。

* Menu:

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


File: python.info,  Node: 枚举类,  Next: 枚举成员（即实例）,  Up: 各种枚举有何区别？

5.8.14.30 枚举类
................

‘EnumMeta’ 元类负责提供 *note __contains__(): dee, *note __dir__(): 42b,
*note __iter__(): 608. 及其他方法以允许用户通过 *note Enum: 48d. 类来完
成一般类做不到的事情，例如 ‘list(Color)’ 或 ‘some_enum_var in Color’。
‘EnumMeta’ 会负责确保最终 *note Enum: 48d. 类中的各种其他方法是正确的 (例
如 *note __new__(): 974, *note __getnewargs__(): 7a1, *note __str__():
ef9. 和 *note __repr__(): 44a.)。


File: python.info,  Node: 枚举成员（即实例）,  Next: 细节要点,  Prev: 枚举类,  Up: 各种枚举有何区别？

5.8.14.31 枚举成员（即实例）
............................

有关枚举成员最有趣的特点是它们都是单例对象。 ‘EnumMeta’ 会在创建 *note
Enum: 48d. 类本身时将它们全部创建完成，然后准备好一个自定义的 *note
__new__(): 974.，通过只返回现有的成员实例来确保不会再实例化新的对象。


File: python.info,  Node: 细节要点,  Prev: 枚举成员（即实例）,  Up: 各种枚举有何区别？

5.8.14.32 细节要点
..................

* Menu:

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


File: python.info,  Node: 支持的 __dunder__ 名称,  Next: 支持的 _sunder_ 名称,  Up: 细节要点

5.8.14.33 支持的 ‘__dunder__’ 名称
..................................

‘__members__’ 是一个 ‘member_name’:‘member’ 条目的只读有序映射。 它只在
类上可用。

如果指定了 *note __new__(): 974.，它必须创建并返回枚举成员；相应地设定成
员的 ‘_value_’ 也是一个很好的主意。 一旦所有成员都创建完成它就不会再被使
用。


File: python.info,  Node: 支持的 _sunder_ 名称,  Next: _Private__names,  Prev: 支持的 __dunder__ 名称,  Up: 细节要点

5.8.14.34 支持的 ‘_sunder_’ 名称
................................

   - ‘_name_’ – 成员的名称

   - ‘_value_’ – 成员的值；可以在 ‘__new__’ 中设置 / 修改

   - ‘_missing_’ – 当未发现某个值时所使用的查找函数；可被重载

   - ‘_ignore_’ – 一个名称列表，可以为 *note list: 1f8. 或 *note str:
     205.，它不会被转化为成员，并将从最终类中被移除

   - ‘_order_’ – 用于 Python 2/3 代码以确保成员顺序一致（类属性，在类创
     建期间会被移除）

   - ‘_generate_next_value_’ – 用于 *note Functional API: 1b38. 并通过
     *note auto: 640. 为枚举成员获取适当的值；可被重载

3.6 版新加入: ‘_missing_’, ‘_order_’, ‘_generate_next_value_’

3.7 版新加入: ‘_ignore_’

用来帮助 Python 2 / Python 3 代码保持同步提供 ‘_order_’ 属性。 它将与枚
举的实际顺序进行对照检查，如果两者不匹配则会引发错误:

     >>> 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_

     備註: 在 Python 2 代码中 ‘_order_’ 属性是必须的，因为定义顺序在被记
     录之前就会丢失。


File: python.info,  Node: _Private__names,  Next: Enum 成员类型,  Prev: 支持的 _sunder_ 名称,  Up: 细节要点

5.8.14.35 _Private__names
.........................

*note Private names: 1621. 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
*note DeprecationWarning: 15a.


File: python.info,  Node: Enum 成员类型,  Next: Enum 类和成员的布尔值,  Prev: _Private__names,  Up: 细节要点

5.8.14.36 ‘Enum’ 成员类型
.........................

*note Enum: 48d. 成员是其 *note Enum: 48d. 类的实例，一般通过
‘EnumClass.member’ 的形式来访问。 在特定情况下它们也可通过
‘EnumClass.member.member’ 的形式来访问，但你绝对不应这样做，因为查找可能
失败，或者更糟糕地返回你所查找的 *note Enum: 48d. 成员以外的对象（这也是
成员应使用全大写名称的另一个好理由）:

     >>> class FieldTypes(Enum):
     ...     name = 0
     ...     value = 1
     ...     size = 2
     ...
     >>> FieldTypes.value.size
     <FieldTypes.size: 2>
     >>> FieldTypes.size.value
     2

     備註: This behavior is deprecated and will be removed in 3.11.

3.5 版更變.


File: python.info,  Node: Enum 类和成员的布尔值,  Next: 带有方法的 Enum 类,  Prev: Enum 成员类型,  Up: 细节要点

5.8.14.37 ‘Enum’ 类和成员的布尔值
.................................

混合了非 *note Enum: 48d. 类型（例如 *note int: 204, *note str: 205. 等
）的 *note Enum: 48d. 成员会按所混合类型的规则被求值；在其他情况下，所有
成员都将被求值为 *note True: 593.。 要使你的自定义 Enum 的布尔值取决于成
员的值，请在你的类中添加以下代码:

     def __bool__(self):
         return bool(self.value)

*note Enum: 48d. 类总是会被求值为 *note True: 593.。


File: python.info,  Node: 带有方法的 Enum 类,  Next: 组合 Flag 的成员,  Prev: Enum 类和成员的布尔值,  Up: 细节要点

5.8.14.38 带有方法的 ‘Enum’ 类
..............................

如果你为你的 *note Enum: 48d. 子类添加了额外的方法，如同上述的 *note
Planet: 1b43. 类一样，这些方法将在对成员执行 *note dir(): df9. 时显示出
来，但对类执行时则不会显示:

     >>> dir(Planet)
     ['EARTH', 'JUPITER', 'MARS', 'MERCURY', 'NEPTUNE', 'SATURN', 'URANUS', 'VENUS', '__class__', '__doc__', '__members__', '__module__']
     >>> dir(Planet.EARTH)
     ['__class__', '__doc__', '__module__', 'name', 'surface_gravity', 'value']


File: python.info,  Node: 组合 Flag 的成员,  Prev: 带有方法的 Enum 类,  Up: 细节要点

5.8.14.39 组合 ‘Flag’ 的成员
............................

如果 Flag 成员的某种组合未被命名，则 *note repr(): 8b9. 将包含所有已命名
的旗标和值中所有已命名的旗标组合:

     >>> 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>

     備註: In 3.11 unnamed combinations of flags will only produce the
     canonical flag members (aka single-value flags).  So ‘Color(7)’
     would produce something like ‘<Color.BLUE|GREEN|RED: 7>’.


File: python.info,  Node: graphlib --- 操作类似图的结构的功能,  Prev: enum --- 对枚举的支持,  Up: 数据类型

5.8.15 ‘graphlib’ — 操作类似图的结构的功能
------------------------------------------

`源代码:' Lib/graphlib.py(1)

__________________________________________________________________

 -- 類別: graphlib.TopologicalSorter (graph=None)

     提供以拓扑方式对可哈希节点的图进行排序的功能。

     拓扑排序是指图中顶点的线性排序，使得对于每条从顶点 u 到顶点 v 的有
     向边 u -> v，顶点 u 都排在顶点 v 之前。 例如，图的顶点可以代表要执
     行的任务，而边代表某一个任务必须在另一个任务之前执行的约束条件；在
     这个例子中，拓扑排序只是任务的有效序列。 完全拓扑排序 当且仅当图不
     包含有向环，也就是说为有向无环图时，完全拓扑排序才是可能的。

     如果提供了可选的 `graph' 参数则它必须为一个表示有向无环图的字典，其
     中的键为节点而值为包含图中该节点的所有上级节点（即具有指向键中的值
     的边的节点）的可迭代对象。 额外的节点可以使用 *note add(): 1b61. 方
     法添加到图中。

     在通常情况下，对给定的图执行排序所需的步骤如下:

             * 通过可选的初始图创建一个 *note TopologicalSorter: 182. 的
               实例。

             * 添加额外的节点到图中。

             * 在图上调用 *note prepare(): 1b62.。

             * 当 *note is_active(): 1b63. 为 ‘True’ 时，迭代 *note
               get_ready(): 1b64. 所返回的节点并加以处理。 完成处理后在
               每个节点上调用 *note done(): 1b65.。

     在只需要对图中的节点进行立即排序并且不涉及并行性的情况下，可以直接
     使用便捷方法 *note TopologicalSorter.static_order(): 1b66.:

          >>> graph = {"D": {"B", "C"}, "C": {"A"}, "B": {"A"}}
          >>> ts = TopologicalSorter(graph)
          >>> tuple(ts.static_order())
          ('A', 'C', 'B', 'D')

     这个类被设计用来在节点就绪时方便地支持对其并行处理。 例如:

          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)

      -- 成員函式: add (node, *predecessors)

          将一个新节点及其上级节点添加到图中。 `node' 以及
          `predecessors' 中的所有元素都必须为可哈希对象。

          如果附带相同的节点参数多次调用，则依赖项的集合将为所有被传入依
          赖项的并集。

          可以添加不带依赖项的节点 (即不提供 `predecessors') 或者重复提
          供依赖项。 如果有先前未提供的节点包含在 `predecessors' 中则它
          将被自动添加到图中并且不带自己的上级节点。

          如果在 *note prepare(): 1b62. 之后被调用则会引发 *note
          ValueError: 16d.。

      -- 成員函式: prepare ()

          将图标记为已完成并检查图中是否存在环。 如何检测到任何环，则将
          引发 *note CycleError: 1b67.，但 *note get_ready(): 1b64. 仍可
          被用来获取尽可能多的节点直到环阻塞了操作过程。 在调用此函数后
          ，图将无法再修改，因此不能再使用 *note add(): 1b61. 添加更多的
          节点。

      -- 成員函式: is_active ()

          如果可以取得更多进展则返回 ‘True’，否则返回 ‘False’。 如果环没
          有阻塞操作，并且还存在尚未被 *note
          TopologicalSorter.get_ready(): 1b64. 返回的已就绪节点或者已标
          记为 *note TopologicalSorter.done(): 1b65. 的节点数量少于已被
          *note TopologicalSorter.get_ready(): 1b64. 所返回的节点数量则
          还可以取得进展。

          该类的 ‘__bool__()’ 方法要使用此函数，因此除了:

               if ts.is_active():
                   ...

          可能会简单地执行:

               if ts:
                   ...

          如果之前未调用 *note prepare(): 1b62. 就调用此函数则会引发
          *note ValueError: 16d.。

      -- 成員函式: done (*nodes)

          将 *note TopologicalSorter.get_ready(): 1b64. 所返回的节点集合
          标记为已处理，解除对 `nodes' 中每个节点的后续节点的阻塞以便在
          将来通过对 *note TopologicalSorter.get_ready(): 1b64. 的调用来
          返回它们。

          如果 `nodes' 中的任何节点已经被之前对该方法的调用标记为已处理
          或者如果未通过使用 *note TopologicalSorter.add(): 1b61. 将一个
          节点添加到图中，如果未调用 *note prepare(): 1b62. 即调用此方法
          或者如果节点尚未被 *note get_ready(): 1b64. 所返回则将引发
          *note ValueError: 16d.。

      -- 成員函式: get_ready ()

          返回由所有已就绪节点组成的 ‘tuple’。 初始状态下它将返回所有不
          带上级节点的节点，并且一旦通过调用 *note
          TopologicalSorter.done(): 1b65. 将它们标记为已处理，之后的调用
          将返回所有上级节点已被处理的新节点。 一旦无法再取得进展，则会
          返回空元组。

          如果之前未调用 *note prepare(): 1b62. 就调用此函数则会引发
          *note ValueError: 16d.。

      -- 成員函式: static_order ()

          返回一个迭代器，它将按照拓扑顺序来迭代所有节点。 当使用此方法
          时，*note prepare(): 1b62. 和 *note done(): 1b65. 不应被调用。
          此方法等价于:

               def static_order(self):
                   self.prepare()
                   while self.is_active():
                       node_group = self.get_ready()
                       yield from node_group
                       self.done(*node_group)

          所返回的特定顺序可能取决于条目被插入图中的顺序。 例如:

               >>> 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]

          这是由于实际上 "0" 和 "2" 在图中的级别相同（它们将在对 *note
          get_ready(): 1b64. 的同一次调用中被返回） 并且它们之间的顺序是
          由插入顺序决定的。

          如果检测到任何环，则将引发 *note CycleError: 1b67.。

     3.9 版新加入.

* Menu:

* 异常: 异常<2>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/graphlib.py


File: python.info,  Node: 异常<2>,  Up: graphlib --- 操作类似图的结构的功能

5.8.15.1 异常
.............

*note graphlib: 89. 模块定义了以下异常类:

 -- 例外: graphlib.CycleError

     *note ValueError: 16d. 的子类，当特定的图中存在环时将由 *note
     TopologicalSorter.prepare(): 1b62. 引发。 如果存在多个环，则将只报
     告其中一个未定义的选项并将其包括在异常中。

     检测到的环可以通过异常实例的 ‘args’ 属性的第二个元素来访问，它由一
     个节点列表组成，其中的每个节点在图中都是列表中下一个节点的直接上级
     节点。 在报告的列表中，开头和末尾的节点将是同一对象，以表明它是一个
     环。


File: python.info,  Node: 數值與數學模組,  Next: 函式編程模組,  Prev: 数据类型,  Up: Python 標準函式庫 Standard Library

5.9 數值與數學模組
==================

本章介绍的模块提供与数字和数学相关的函数和数据类型。 *note numbers: c1.
模块定义了数字类型的抽象层次结构。 *note math: b1. 和 *note cmath: 18. 模
块包含浮点数和复数的各种数学函数。 *note decimal: 35. 模块支持使用任意精
度算术的十进制数的精确表示。

本章记录以下模块：

* Menu:

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


File: python.info,  Node: numbers --- 数字的抽象基类,  Next: math --- 数学函数,  Up: 數值與數學模組

5.9.1 ‘numbers’ — 数字的抽象基类
--------------------------------

`源代码：' Lib/numbers.py(1)

__________________________________________________________________

*note numbers: c1. 模块 ( PEP 3141(2)) 定义了数字 *note 抽象基类: c05. 的
层级结构，其中逐级定义了更多操作。 此模块中定义的类型都不可被实例化。

 -- 類別: numbers.Number

     数字的层次结构的基础。 如果你只想确认参数 `x' 是不是数字而不关心其
     类型，则使用 ‘isinstance(x, Number)’。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/numbers.py

   (2) https://www.python.org/dev/peps/pep-3141


File: python.info,  Node: 数字的层次,  Next: 类型接口注释。,  Up: numbers --- 数字的抽象基类

5.9.1.1 数字的层次
..................

 -- 類別: numbers.Complex

     这个类型的子类描述了复数并包括了适用于内置 *note complex: 2c1. 类型
     的操作。 这些操作有: 转换为 *note complex: 2c1. 和 *note bool: 2bd,
     *note real: 1b6f, *note imag: 1b70, ‘+’, ‘-’, ‘*’, ‘/’, ‘**’, *note
     abs(): 13f3, *note conjugate(): 1b71, ‘==’ 以及 ‘!=’。 除 ‘-’ 和
     ‘!=’ 之外所有操作都是抽象的。

      -- 屬性: real

          抽象的。得到该数字的实数部分。

      -- 屬性: imag

          抽象的。得到该数字的虚数部分。

      -- 成員函式: abstractmethod conjugate ()

          抽象的。返回共轭复数。例如 ‘(1+3j).conjugate() == (1-3j)’。

 -- 類別: numbers.Real

     相对于 *note Complex: 1558.，*note Real: 1557. 加入了只有实数才能进
     行的操作。

     简单的说，它们是：转化至 *note float: 1fd.，*note math.trunc():
     df4.、 *note round(): d35.、 *note math.floor(): df2.、 *note
     math.ceil(): df3.、 *note divmod(): 28d.、 ‘//’、 ‘%’、 ‘<’、 ‘<=’、
     ‘>’、 和 ‘>=’。

     实数同样默认支持 *note complex(): 2c1.、 *note real: 1b6f.、 *note
     imag: 1b70. 和 *note conjugate(): 1b71.。

 -- 類別: numbers.Rational

     子类型 *note Real: 1557. 并加入 *note numerator: 1b72. 和 *note
     denominator: 1b73. 两种属性，这两种属性应该属于最低的级别。加入后，
     这默认支持 *note float(): 1fd.。

      -- 屬性: numerator

          抽象的。

      -- 屬性: denominator

          抽象的。

 -- 類別: numbers.Integral

     子类型 *note Rational: d20. 还增加了到 *note int: 204. 的转换操作。
     为 *note float(): 1fd, *note numerator: 1b72. 和 *note denominator:
     1b73. 提供了默认支持。 为 *note pow(): 2cf. 方法增加了求余和按位字
     符串运算的抽象方法: ‘<<’, ‘>>’, ‘&’, ‘^’, ‘|’, ‘~’。


File: python.info,  Node: 类型接口注释。,  Prev: 数字的层次,  Up: numbers --- 数字的抽象基类

5.9.1.2 类型接口注释。
......................

实现者需要注意使相等的数字相等并拥有同样的值。当这两个数使用不同的扩展模
块时，这其中的差异是很微妙的。例如，用 *note fractions.Fraction: 2be. 实
现 *note hash(): aa3. 如下:

     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))

* Menu:

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


File: python.info,  Node: 加入更多数字的ABC,  Next: 实现算术运算,  Up: 类型接口注释。

5.9.1.3 加入更多数字的ABC
.........................

当然，这里有更多支持数字的ABC，如果不加入这些，就将缺少层次感。你可以用
如下方法在 *note Complex: 1558. 和 *note Real: 1557. 中加入 ‘MyFoo’:

     class MyFoo(Complex): ...
     MyFoo.register(Real)


File: python.info,  Node: 实现算术运算,  Prev: 加入更多数字的ABC,  Up: 类型接口注释。

5.9.1.4 实现算术运算
....................

我们希望实现计算，因此，混合模式操作要么调用一个作者知道参数类型的实现，
要么转变成为最接近的内置类型并对这个执行操作。对于子类 *note Integral:
1556.，这意味着 *note __add__(): 1595. 和 *note __radd__(): 1596. 必须用
如下方式定义：

     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

*note Complex: 1558. 有 5 种不同的混合类型的操作。 我将上面提到的所有代
码作为“模板”称作 ‘MyIntegral’ 和 ‘OtherTypeIKnowAbout’。 ‘a’ 是 *note
Complex: 1558. 的子类型 ‘A’ 的实例 (‘a : A <: Complex’)，同时 ‘b : B <:
Complex’。 我将要计算 ‘a + b’:

       1. 如果 ‘A’ 被定义成一个承认 ‘b’ 的 *note __add__(): 1595.，一切
          都没有问题。

       2. 如果 ‘A’ 转回成“模板”失败，它将返回一个属于 *note __add__():
          1595. 的值，我们需要避免 ‘B’ 定义了一个更加智能的 *note
          __radd__(): 1596.，因此模板需要返回一个属于 *note __add__():
          1595. 的 *note NotImplemented: 202. 。（或者 ‘A’ 可能完全不实
          现 *note __add__(): 1595. 。）

       3. 接着看 ‘B’ 的 *note __radd__(): 1596. 。如果它承认 ‘a’ ，一切
          都没有问题。

       4. 如果没有成功回退到模板，就没有更多的方法可以去尝试，因此这里将
          使用默认的实现。

       5. 如果 ‘B <: A’ ， Python 在 ‘A.__add__’ 之前尝试 ‘B.__radd__’ 。
          这是可行的，是通过对 ‘A’ 的认识实现的，因此这可以在交给 *note
          Complex: 1558. 处理之前处理这些实例。

如果 ‘A <: Complex’ 和 ‘B <: Real’ 没有共享任何资源，那么适当的共享操作
涉及内置的 *note complex: 2c1. ，并且分别获得 *note __radd__(): 1596. ，
因此 ‘a+b == b+a’。

由于对任何一直类型的大部分操作是十分相似的，可以定义一个帮助函数，即一个
生成后续或相反的实例的生成器。例如，使用 *note fractions.Fraction: 2be.
如下：

     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)

     # ...


File: python.info,  Node: math --- 数学函数,  Next: cmath --- 关于复数的数学函数,  Prev: numbers --- 数字的抽象基类,  Up: 數值與數學模組

5.9.2 ‘math’ — 数学函数
-----------------------

__________________________________________________________________

该模块提供了对C标准定义的数学函数的访问。

这些函数不适用于复数；如果你需要计算复数，请使用 *note cmath: 18. 模块中
的同名函数。将支持计算复数的函数区分开的目的，来自于大多数开发者并不愿意
像数学家一样需要学习复数的概念。得到一个异常而不是一个复数结果使得开发者
能够更早地监测到传递给这些函数的参数中包含复数，进而调查其产生的原因。

该模块提供了以下函数。除非另有明确说明，否则所有返回值均为浮点数。

* Menu:

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


File: python.info,  Node: 数论与表示函数,  Next: 幂函数与对数函数,  Up: math --- 数学函数

5.9.2.1 数论与表示函数
......................

 -- 函式: math.ceil (x)

     返回 `x' 的上限，即大于或者等于 `x' 的最小整数。如果 `x' 不是一个浮
     点数，则委托 ‘x.__ceil__()’, 返回一个 *note Integral: 1556. 类的值
     。

 -- 函式: math.comb (n, k)

     返回不重复且无顺序地从 `n' 项中选择 `k' 项的方式总数。

     当 ‘k <= n’ 时取值为 ‘n! / (k! * (n - k)!)’；当 ‘k > n’ 时取值为零
     。

     也称为二项式系数，因为它等价于表达式 ‘(1 + x) ** n’ 的多项式展开中
     第 k 项的系数。

     如果任一参数不为整数则会引发 *note TypeError: 1fe.。 如果任一参数为
     负数则会引发 *note ValueError: 16d.。

     3.8 版新加入.

 -- 函式: math.copysign (x, y)

     返回一个基于 `x' 的绝对值和 `y' 的符号的浮点数。在支持带符号零的平
     台上，‘copysign(1.0, -0.0)’ 返回 `-1.0'.

 -- 函式: math.fabs (x)

     返回 `x' 的绝对值。

 -- 函式: math.factorial (x)

     以一个整数返回 `x' 的阶乘。 如果 `x' 不是整数或为负数时则将引发
     *note ValueError: 16d.。

     3.9 版後已棄用: 接受具有整数值的浮点数 (例如 ‘5.0’) 的行为已被弃用
     。

 -- 函式: math.floor (x)

     返回 `x' 的向下取整，小于或等于 `x' 的最大整数。如果 `x' 不是浮点数
     ，则委托 ‘x.__floor__()’ ，它应返回 *note Integral: 1556. 值。

 -- 函式: math.fmod (x, y)

     返回 ‘fmod(x, y)’ ，由平台C库定义。请注意，Python表达式 ‘x % y’ 可
     能不会返回相同的结果。C标准的目的是 ‘fmod(x, y)’ 完全（数学上；到无
     限精度）等于 ‘x - n*y’ 对于某个整数 `n' ，使得结果具有 与 `x' 相同
     的符号和小于 ‘abs(y)’ 的幅度。Python的 ‘x % y’ 返回带有 `y' 符号的
     结果，并且可能不能完全计算浮点参数。 例如， ‘fmod(-1e-100, 1e100)’
     是 ‘-1e-100’ ，但Python的 ‘-1e-100 % 1e100’ 的结果是 ‘1e100-1e-100’
     ，它不能完全表示为浮点数，并且取整为令人惊讶的 ‘1e100’ 。 出于这个
     原因，函数 *note fmod(): 1671. 在使用浮点数时通常是首选，而Python的
     ‘x % y’ 在使用整数时是首选。

 -- 函式: math.frexp (x)

     以 ‘(m, e)’ 对的形式返回 `x' 的尾数和指数。 `m' 是一个浮点数， `e'
     是一个整数，正好是 ‘x == m * 2**e’ 。 如果 `x' 为零，则返回 ‘(0.0,
     0)’ ，否则返回 ‘0.5 <= abs(m) < 1’ 。这用于以可移植方式“分离”浮点数
     的内部表示。

 -- 函式: math.fsum (iterable)

     返回迭代中的精确浮点值。通过跟踪多个中间部分和来避免精度损失:

          >>> 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

     该算法的准确性取决于IEEE-754算术保证和舍入模式为半偶的典型情况。在
     某些非Windows版本中，底层C库使用扩展精度添加，并且有时可能会使中间
     和加倍，导致它在最低有效位中关闭。

     有关待进一步讨论和两种替代方法，参见 ASPN cookbook recipes for
     accurate floating point summation(1)。

 -- 函式: math.gcd (*integers)

     返回给定的整数参数的最大公约数。 如果有一个参数非零，则返回值将是能
     同时整除所有参数的最大正整数。 如果所有参数为零，则返回值为 ‘0’。 不
     带参数的 ‘gcd()’ 返回 ‘0’。

     3.5 版新加入.

     3.9 版更變: 添加了对任意数量的参数的支持。 之前的版本只支持两个参数
     。

 -- 函式: math.isclose (a, b, *, rel_tol=1e-09, abs_tol=0.0)

     若 `a' 和 `b' 的值比较接近则返回 ‘True’，否则返回 ‘False’。

     根据给定的绝对和相对容差确定两个值是否被认为是接近的。

     `rel_tol' 是相对容差 —— 它是 `a' 和 `b' 之间允许的最大差值，相对于
     `a' 或 `b' 的较大绝对值。例如，要设置5％的容差，请传递
     ‘rel_tol=0.05’ 。默认容差为 ‘1e-09’，确保两个值在大约9位十进制数字
     内相同。 `rel_tol' 必须大于零。

     `abs_tol' 是最小绝对容差 —— 对于接近零的比较很有用。 `abs_tol' 必须
     至少为零。

     如果没有错误发生，结果将是： ‘abs(a-b) <= max(rel_tol * max(abs(a),
     abs(b)), abs_tol)’ 。

     IEEE 754特殊值 ‘NaN’ ， ‘inf’ 和 ‘-inf’ 将根据IEEE规则处理。具体来
     说， ‘NaN’ 不被认为接近任何其他值，包括 ‘NaN’ 。 ‘inf’ 和 ‘-inf’ 只
     被认为接近自己。

     3.5 版新加入.

     也參考
     ......

     PEP 485(2) —— 用于测试近似相等的函数

 -- 函式: math.isfinite (x)

     如果 `x' 既不是无穷大也不是NaN，则返回 ‘True’ ，否则返回 ‘False’ 。
     （注意 ‘0.0’ 被认为 `是' 有限的。）

     3.2 版新加入.

 -- 函式: math.isinf (x)

     如果 `x' 是正或负无穷大，则返回 ‘True’ ，否则返回 ‘False’ 。

 -- 函式: math.isnan (x)

     如果 `x' 是 NaN（不是数字），则返回 ‘True’ ，否则返回 ‘False’ 。

 -- 函式: math.isqrt (n)

     返回非负整数 `n' 的整数平方根。 这就是对 `n' 的实际平方根向下取整，
     或者相当于使得 `a'² ≤ `n' 的最大整数 `a'。

     对于某些应用来说，可以更适合取值为使得 `n' ≤ `a'² 的最小整数 `a' ，
     或者换句话说就是 `n' 的实际平方根向上取整。 对于正数 `n'，这可以使
     用 ‘a = 1 + isqrt(n - 1)’ 来计算。

     3.8 版新加入.

 -- 函式: math.lcm (*integers)

     返回给定的整数参数的最小公倍数。 如果所有参数均非零，则返回值将是为
     所有参数的整数倍的最小正整数。 如果参数之一为零，则返回值为 ‘0’。 不
     带参数的 ‘lcm()’ 返回 ‘1’。

     3.9 版新加入.

 -- 函式: math.ldexp (x, i)

     返回 ‘x * (2**i)’ 。 这基本上是函数 *note frexp(): 1b7b. 的反函数。

 -- 函式: math.modf (x)

     返回 `x' 的小数和整数部分。两个结果都带有 `x' 的符号并且是浮点数。

 -- 函式: math.nextafter (x, y)

     返回 `x' 趋向于 `y' 的最接近的浮点数值。

     如果 `x' 等于 `y' 则返回 `y'。

     示例：

        * ‘math.nextafter(x, math.inf)’ 的方向朝上：趋向于正无穷。

        * ‘math.nextafter(x, -math.inf)’ 的方向朝下：趋向于负无穷。

        * ‘math.nextafter(x, 0.0)’ 趋向于零。

        * ‘math.nextafter(x, math.copysign(math.inf, x))’ 趋向于零的反方
          向。

     另请参阅 *note math.ulp(): 1c1.。

     3.9 版新加入.

 -- 函式: math.perm (n, k=None)

     返回不重复且有顺序地从 `n' 项中选择 `k' 项的方式总数。

     当 ‘k <= n’ 时取值为 ‘n! / (n - k)!’；当 ‘k > n’ 时取值为零。

     如果 `k' 未指定或为 None，则 `k' 默认值为 `n' 并且函数将返回 ‘n!’。

     如果任一参数不为整数则会引发 *note TypeError: 1fe.。 如果任一参数为
     负数则会引发 *note ValueError: 16d.。

     3.8 版新加入.

 -- 函式: math.prod (iterable, *, start=1)

     计算输入的 `iterable' 中所有元素的积。 积的默认 `start' 值为 ‘1’。

     当可迭代对象为空时，返回起始值。 此函数特别针对数字值使用，并会拒绝
     非数字类型。

     3.8 版新加入.

 -- 函式: math.remainder (x, y)

     返回 IEEE 754 风格的 `x' 相对于 `y' 的余数。对于有限 `x' 和有限非零
     `y' ，这是差异 ‘x - n*y’ ，其中 ‘n’ 是与商 ‘x / y’ 的精确值最接近的
     整数。如果 ‘x / y’ 恰好位于两个连续整数之间，则将最接近的 `偶数' 用
     作 ‘n’ 。 余数 ‘r = remainder(x, y)’ 因此总是满足 ‘abs(r) <= 0.5 *
     abs(y)’。

     特殊情况遵循IEEE 754：特别是 ‘remainder(x, math.inf)’ 对于任何有限
     `x' 都是 `x' ，而 ‘remainder(x, 0)’ 和 ‘remainder(math.inf, x)’ 引
     发 *note ValueError: 16d. 适用于任何非NaN的 `x' 。如果余数运算的结
     果为零，则该零将具有与 `x' 相同的符号。

     在使用IEEE 754二进制浮点的平台上，此操作的结果始终可以完全表示：不
     会引入舍入错误。

     3.7 版新加入.

 -- 函式: math.trunc (x)

     返回 *note Real: 1557. 值 `x' 截断为 *note Integral: 1556. （通常是
     整数）。 委托给 *note x.__trunc__(): 15c1.。

 -- 函式: math.ulp (x)

     返回浮点数 `x' 的最小有效比特位的值:

        * 如果 `x' 是 NaN (非数字)，则返回 `x'。

        * 如果 `x' 为负数，则返回 ‘ulp(-x)’。

        * 如果 `x' 为正数，则返回 `x'。

        * 如果 `x' 等于零，则返回 `去正规化的' 可表示最小正浮点数 (小于
          `正规化的' 最小正浮点数 *note sys.float_info.min: 10fc.)。

        * 如果 `x' 等于可表示最大正浮点数，则返回 `x' 的最低有效比特位的
          值，使得小于 `x' 的第一个浮点数为 ‘x - ulp(x)’。

        * 在其他情况下 (`x' 是一个有限的正数)，则返回 `x' 的最低有效比特
          位的值，使得大于 `x' 的第一个浮点数为 ‘x + ulp(x)’。

     ULP 即 "Unit in the Last Place" 的缩写。

     另请参阅 *note math.nextafter(): 1c0. 和 *note
     sys.float_info.epsilon: 10fc.。

     3.9 版新加入.

注意 *note frexp(): 1b7b. 和 *note modf(): 1b7d. 具有与它们的C等价函数不
同的调用/返回模式：它们采用单个参数并返回一对值，而不是通过 ’输出形参’ 返
回它们的第二个返回参数（Python中没有这样的东西）。

对于 *note ceil(): df3. ， *note floor(): df2. 和 *note modf(): 1b7d. 函
数，请注意 `所有' 足够大的浮点数都是精确整数。Python浮点数通常不超过53位
的精度（与平台C double类型相同），在这种情况下，任何浮点 `x' 与 ‘abs(x)
>= 2**52’ 必然没有小数位。

   ---------- Footnotes ----------

   (1) https://code.activestate.com/recipes/393090/

   (2) https://www.python.org/dev/peps/pep-0485


File: python.info,  Node: 幂函数与对数函数,  Next: 三角函数,  Prev: 数论与表示函数,  Up: math --- 数学函数

5.9.2.2 幂函数与对数函数
........................

 -- 函式: math.exp (x)

     返回 `e' 次 `x' 幂，其中 `e' = 2.718281... 是自然对数的基数。这通常
     比 ‘math.e ** x’ 或 ‘pow(math.e, x)’ 更精确。

 -- 函式: math.expm1 (x)

     返回 `e' 的 `x' 次幂，减1。这里 `e' 是自然对数的基数。对于小浮点数
     `x' ， ‘exp(x) - 1’ 中的减法可能导致 significant loss of
     precision(1)； *note expm1(): c3a. 函数提供了一种将此数量计算为全精
     度的方法:

          >>> 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

     3.2 版新加入.

 -- 函式: math.log (x[, base])

     使用一个参数，返回 `x' 的自然对数（底为 `e' ）。

     使用两个参数，返回给定的 `base' 的对数 `x' ，计算为
     ‘log(x)/log(base)’ 。

 -- 函式: math.log1p (x)

     返回 `1+x' 的自然对数（以 `e' 为底）。 以对于接近零的 `x' 精确的方
     式计算结果。

 -- 函式: math.log2 (x)

     返回 `x' 以2为底的对数。这通常比 ‘log(x, 2)’ 更准确。

     3.3 版新加入.

     也參考
     ......

     *note int.bit_length(): 1753. 返回表示二进制整数所需的位数，不包括
     符号和前导零。

 -- 函式: math.log10 (x)

     返回 `x' 底为10的对数。这通常比 ‘log(x, 10)’ 更准确。

 -- 函式: math.pow (x, y)

     将返回 ‘x’ 的 ‘y’ 次幂。特殊情况尽可能遵循C99标准的附录’F’。特别是
     ， ‘pow(1.0, x)’ 和 ‘pow(x, 0.0)’ 总是返回 ‘1.0’ ，即使 ‘x’ 是零或
     NaN。 如果 ‘x’ 和 ‘y’ 都是有限的， ‘x’ 是负数， ‘y’ 不是整数那么
     ‘pow(x, y)’ 是未定义的，并且引发 *note ValueError: 16d. 。

     与内置的 ‘**’ 运算符不同， *note math.pow(): 1b80. 将其参数转换为
     *note float: 1fd. 类型。使用 ‘**’ 或内置的 *note pow(): 2cf. 函数来
     计算精确的整数幂。

 -- 函式: math.sqrt (x)

     返回 `x' 的平方根。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Loss_of_significance


File: python.info,  Node: 三角函数,  Next: 角度转换,  Prev: 幂函数与对数函数,  Up: math --- 数学函数

5.9.2.3 三角函数
................

 -- 函式: math.acos (x)

     返回以弧度为单位的 `x' 的反余弦值。 结果范围在 ‘0’ 到 ‘pi’ 之间。

 -- 函式: math.asin (x)

     返回以弧度为单位的 `x' 的反正弦值。 结果范围在 ‘-pi/2’ 到 ‘pi/2’ 之
     间。

 -- 函式: math.atan (x)

     返回以弧度为单位的 `x' 的反正切值。 结果范围在 ‘-pi/2’ 到 ‘pi/2’ 之
     间。.

 -- 函式: math.atan2 (y, x)

     以弧度为单位返回 ‘atan(y / x)’ 。结果是在 ‘-pi’ 和 ‘pi’ 之间。从原
     点到点 ‘(x, y)’ 的平面矢量使该角度与正X轴成正比。 *note atan2():
     1b85. 的点的两个输入的符号都是已知的，因此它可以计算角度的正确象限
     。 例如， ‘atan(1)’ 和 ‘atan2(1, 1)’ 都是 ‘pi/4’ ，但 ‘atan2(-1,
     -1)’ 是 ‘-3*pi/4’ 。

 -- 函式: math.cos (x)

     返回 `x' 弧度的余弦值。

 -- 函式: math.dist (p, q)

     返回 `p' 与 `q' 两点之间的欧几里得距离，以一个坐标序列（或可迭代对
     象）的形式给出。 两个点必须具有相同的维度。

     大致相当于：

          sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))

     3.8 版新加入.

 -- 函式: math.hypot (*coordinates)

     返回欧几里得范数，‘sqrt(sum(x**2 for x in coordinates))’。 这是从原
     点到坐标给定点的向量长度。

     对于一个二维点 ‘(x, y)’，这等价于使用毕达哥拉斯定义 ‘sqrt(x*x +
     y*y)’ 计算一个直角三角形的斜边。

     3.8 版更變: 添加了对 n 维点的支持。 之前的版本只支持二维点。

 -- 函式: math.sin (x)

     返回 `x' 弧度的正弦值。

 -- 函式: math.tan (x)

     返回 `x' 弧度的正切值。


File: python.info,  Node: 角度转换,  Next: 双曲函数,  Prev: 三角函数,  Up: math --- 数学函数

5.9.2.4 角度转换
................

 -- 函式: math.degrees (x)

     将角度 `x' 从弧度转换为度数。

 -- 函式: math.radians (x)

     将角度 `x' 从度数转换为弧度。


File: python.info,  Node: 双曲函数,  Next: 特殊函数,  Prev: 角度转换,  Up: math --- 数学函数

5.9.2.5 双曲函数
................

双曲函数(1) 是基于双曲线而非圆来对三角函数进行模拟。

 -- 函式: math.acosh (x)

     返回 `x' 的反双曲余弦值。

 -- 函式: math.asinh (x)

     返回 `x' 的反双曲正弦值。

 -- 函式: math.atanh (x)

     返回 `x' 的反双曲正切值。

 -- 函式: math.cosh (x)

     返回 `x' 的双曲余弦值。

 -- 函式: math.sinh (x)

     返回 `x' 的双曲正弦值。

 -- 函式: math.tanh (x)

     返回 `x' 的双曲正切值。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Hyperbolic_function


File: python.info,  Node: 特殊函数,  Next: 常数,  Prev: 双曲函数,  Up: math --- 数学函数

5.9.2.6 特殊函数
................

 -- 函式: math.erf (x)

     返回 `x' 处的 error function(1) 。

     *note erf(): 553. 函数可用于计算传统的统计函数，如 累积标准正态分布
     (2)

          def phi(x):
              'Cumulative distribution function for the standard normal distribution'
              return (1.0 + erf(x / sqrt(2.0))) / 2.0

     3.2 版新加入.

 -- 函式: math.erfc (x)

     返回 `x' 处的互补误差函数。 互补错误函数(3) 定义为 ‘1.0 - erf(x)’。
     它用于 `x' 的大值，从其中减去一个会导致 有效位数损失(4)。

     3.2 版新加入.

 -- 函式: math.gamma (x)

     返回 `x' 处的 伽马函数(5) 值。

     3.2 版新加入.

 -- 函式: math.lgamma (x)

     返回Gamma函数在 `x' 绝对值的自然对数。

     3.2 版新加入.

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Error_function

   (2) 
https://en.wikipedia.org/wiki/Normal_distribution#Cumulative_distribution_function

   (3) https://en.wikipedia.org/wiki/Error_function

   (4) https://en.wikipedia.org/wiki/Loss_of_significance

   (5) https://en.wikipedia.org/wiki/Gamma_function


File: python.info,  Node: 常数,  Prev: 特殊函数,  Up: math --- 数学函数

5.9.2.7 常数
............

 -- Data: math.pi

     数学常数 `π' = 3.141592...，精确到可用精度。

 -- Data: math.e

     数学常数 `e' = 2.718281...，精确到可用精度。

 -- Data: math.tau

     数学常数 `τ' = 6.283185...，精确到可用精度。Tau 是一个圆周常数，等
     于 2`π'，圆的周长与半径之比。更多关于 Tau 的信息可参考 Vi Hart 的视
     频 Pi is (still) Wrong(1)。吃两倍多的派来庆祝 Tau 日(2) 吧！

     3.6 版新加入.

 -- Data: math.inf

     浮点正无穷大。 （对于负无穷大，使用 ‘-math.inf’ 。）相当于
     ‘float('inf')’ 的输出。

     3.5 版新加入.

 -- Data: math.nan

     浮点“非数字”（NaN）值。 相当于 ‘float('nan')’ 的输出。

     3.5 版新加入.

`CPython implementation detail:' *note math: b1. 模块主要包含围绕平台C数
学库函数的简单包装器。特殊情况下的行为在适当情况下遵循C99标准的附录F。当
前的实现将引发 *note ValueError: 16d. 用于无效操作，如 ‘sqrt(-1.0)’ 或
‘log(0.0)’ （其中C99附件F建议发出无效操作信号或被零除）， 和 *note
OverflowError: a41. 用于溢出的结果（例如， ‘exp(1000.0)’ ）。除非一个或
多个输入参数是NaN，否则不会从上述任何函数返回NaN；在这种情况下，大多数函
数将返回一个NaN，但是（再次遵循C99附件F）这个规则有一些例外，例如
‘pow(float('nan'), 0.0)’ 或 ‘hypot(float('nan'), float('inf'))’ 。

请注意，Python不会将显式NaN与静默NaN区分开来，并且显式NaN的行为仍未明确
。典型的行为是将所有NaN视为静默的。

也參考
......

*note cmath: 18. 模块

     这里很多函数的复数版本。

   ---------- Footnotes ----------

   (1) https://www.youtube.com/watch?v=jG7vhMMXagQ

   (2) https://tauday.com/


File: python.info,  Node: cmath --- 关于复数的数学函数,  Next: decimal --- 十进制定点和浮点运算,  Prev: math --- 数学函数,  Up: 數值與數學模組

5.9.3 ‘cmath’ — 关于复数的数学函数
----------------------------------

__________________________________________________________________

这一模块提供了一些关于复数的数学函数。 该模块的函数的参数为整数、浮点数
或复数。 这些函数的参数也可为一个拥有 *note __complex__(): 2c5. 或 *note
__float__(): 2c4. 方法的 Python 对象，这些方法分别用于将对象转换为复数和
浮点数，这些函数作用于转换后的结果。

     備註: 在具有对于有符号零的硬件和系统级支持的平台上，涉及支割线的函
     数在支割线的 `两侧' 都是连续的：零的符号可用来区别支割线的一侧和另
     一侧。 在不支持有符号零的平台上，连续性的规则见下文。

* Menu:

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


File: python.info,  Node: 到极坐标和从极坐标的转换,  Next: 幂函数与对数函数<2>,  Up: cmath --- 关于复数的数学函数

5.9.3.1 到极坐标和从极坐标的转换
................................

使用 `矩形坐标' 或 `笛卡尔坐标' 在内部存储 Python 复数 ‘z’。 这完全取决
于它的 `实部' ‘z.real’ 和 `虚部' ‘z.imag’。 换句话说:

     z == z.real + z.imag*1j

`极坐标' 提供了另一种复数的表示方法。在极坐标中，一个复数 `z' 由模量 `r'
和相位角 `phi' 来定义。模量 `r' 是从 `z' 到坐标原点的距离，而相位角
`phi' 是以弧度为单位的，逆时针的，从正X轴到连接原点和 `z' 的线段间夹角的
角度。

下面的函数可用于原生直角坐标与极坐标的相互转换。

 -- 函式: cmath.phase (x)

     将 `x' 的相位 (也称为 `x' 的 `参数') 返回为一个浮点数。‘phase(x)’ 相
     当于 ‘math.atan2(x.imag, x.real)’。 结果处于 [-`π', `π'] 之间，以及
     这个操作的分支切断处于负实轴上，从上方连续。 在支持有符号零的系统上
     （这包涵大多数当前的常用系统），这意味着结果的符号与 ‘x.imag’ 的符
     号相同，即使 ‘x.imag’ 的值是 0:

          >>> phase(complex(-1.0, 0.0))
          3.141592653589793
          >>> phase(complex(-1.0, -0.0))
          -3.141592653589793

     備註: 一个复数 `x' 的模数（绝对值）可以通过内置函数 *note abs():
     13f3. 计算。没有单独的 *note cmath: 18. 模块函数用于这个操作。

 -- 函式: cmath.polar (x)

     在极坐标中返回 `x' 的表达方式。返回一个数对 ‘(r, phi)’，`r' 是 `x'
     的模数，`phi' 是 `x' 的相位角。 ‘polar(x)’ 相当于 ‘(abs(x),
     phase(x))’。

 -- 函式: cmath.rect (r, phi)

     通过极坐标的 `r' 和 `phi' 返回复数 `x'。相当于 ‘r * (math.cos(phi)
     + math.sin(phi)*1j)’。


File: python.info,  Node: 幂函数与对数函数<2>,  Next: 三角函数<2>,  Prev: 到极坐标和从极坐标的转换,  Up: cmath --- 关于复数的数学函数

5.9.3.2 幂函数与对数函数
........................

 -- 函式: cmath.exp (x)

     返回 `e' 的 `x' 次方，`e' 是自然对数的底数。

 -- 函式: cmath.log (x[, base])

     返回给定 `base' 的 `x' 的对数。如果没有给定 `base'，返回 `x' 的自然
     对数。 从 0 到 -∞ 存在一条支割线，沿负实轴之上连续。

 -- 函式: cmath.log10 (x)

     返回底数为 10 的 `x' 的对数。它具有与 *note log(): 1b9b. 相同的支割
     线。

 -- 函式: cmath.sqrt (x)

     返回 `x' 的平方根。 它具有与 *note log(): 1b9b. 相同的支割线。


File: python.info,  Node: 三角函数<2>,  Next: 双曲函数<2>,  Prev: 幂函数与对数函数<2>,  Up: cmath --- 关于复数的数学函数

5.9.3.3 三角函数
................

 -- 函式: cmath.acos (x)

     返回 `x' 的反余弦。这里有两条支割线：一条沿着实轴从 1 向右延伸到 ∞，
     从下面连续延伸。另外一条沿着实轴从 -1 向左延伸到 -∞，从上面连续延伸
     。

 -- 函式: cmath.asin (x)

     返回 `x' 的反正弦。它与 *note acos(): 1b9f. 有相同的支割线。

 -- 函式: cmath.atan (x)

     返回 `x' 的反正切。它具有两条支割线：一条沿着虚轴从 ‘1j’ 延伸到
     ‘∞j’，向右持续延伸。另一条是沿着虚轴从 ‘-1j’ 延伸到 ‘-∞j’ ，向左持
     续延伸。

 -- 函式: cmath.cos (x)

     返回 `x' 的余弦。

 -- 函式: cmath.sin (x)

     返回 `x' 的正弦。

 -- 函式: cmath.tan (x)

     返回 `x' 的正切。


File: python.info,  Node: 双曲函数<2>,  Next: 分类函数,  Prev: 三角函数<2>,  Up: cmath --- 关于复数的数学函数

5.9.3.4 双曲函数
................

 -- 函式: cmath.acosh (x)

     返回 `x' 的反双曲余弦。它有一条支割线沿着实轴从 1 到 -∞ 向左延伸，
     从上方持续延伸。

 -- 函式: cmath.asinh (x)

     返回 `x' 的反双曲正弦。它有两条支割线：一条沿着虚轴从 ‘1j’ 向右持续
     延伸到 ‘∞j’。另一条是沿着虚轴从 ‘-1j’ 向左持续延伸到 ‘-∞j’。

 -- 函式: cmath.atanh (x)

     返回 `x' 的反双曲正切。它有两条支割线：一条是沿着实轴从 ‘1’ 延展到
     ‘∞’，从下面持续延展。另一条是沿着实轴从 ‘-1’ 延展到 ‘-∞’，从上面持
     续延展。

 -- 函式: cmath.cosh (x)

     返回 `x' 的双曲余弦值。

 -- 函式: cmath.sinh (x)

     返回 `x' 的双曲正弦值。

 -- 函式: cmath.tanh (x)

     返回 `x' 的双曲正切值。


File: python.info,  Node: 分类函数,  Next: 常数<2>,  Prev: 双曲函数<2>,  Up: cmath --- 关于复数的数学函数

5.9.3.5 分类函数
................

 -- 函式: cmath.isfinite (x)

     如果 `x' 的实部和虚部都是有限的，则返回 ‘True’，否则返回 ‘False’。

     3.2 版新加入.

 -- 函式: cmath.isinf (x)

     如果 `x' 的实部或者虚部是无穷大的，则返回 ‘True’，否则返回 ‘False’。

 -- 函式: cmath.isnan (x)

     如果 `x' 的实部或者虚部是 NaN，则返回 ‘True’ ，否则返回 ‘False’。

 -- 函式: cmath.isclose (a, b, *, rel_tol=1e-09, abs_tol=0.0)

     若 `a' 和 `b' 的值比较接近则返回 ‘True’，否则返回 ‘False’。

     根据给定的绝对和相对容差确定两个值是否被认为是接近的。

     `rel_tol' 是相对容差 —— 它是 `a' 和 `b' 之间允许的最大差值，相对于
     `a' 或 `b' 的较大绝对值。例如，要设置5％的容差，请传递
     ‘rel_tol=0.05’ 。默认容差为 ‘1e-09’，确保两个值在大约9位十进制数字
     内相同。 `rel_tol' 必须大于零。

     `abs_tol' 是最小绝对容差 —— 对于接近零的比较很有用。 `abs_tol' 必须
     至少为零。

     如果没有错误发生，结果将是： ‘abs(a-b) <= max(rel_tol * max(abs(a),
     abs(b)), abs_tol)’ 。

     IEEE 754特殊值 ‘NaN’ ， ‘inf’ 和‘ ‘-inf‘’ 将根据IEEE规则处理。具体
     来说， ‘NaN’ 不被认为接近任何其他值，包括 ‘NaN’ 。 ‘inf’ 和 ‘-inf’
     只被认为接近自己。

     3.5 版新加入.

     也參考
     ......

     PEP 485(1) —— 用于测试近似相等的函数

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0485


File: python.info,  Node: 常数<2>,  Prev: 分类函数,  Up: cmath --- 关于复数的数学函数

5.9.3.6 常数
............

 -- Data: cmath.pi

     数学常数 `π' ，作为一个浮点数。

 -- Data: cmath.e

     数学常数 `e' ，作为一个浮点数。

 -- Data: cmath.tau

     数学常数 `τ' ，作为一个浮点数。

     3.6 版新加入.

 -- Data: cmath.inf

     浮点正无穷大。相当于 ‘float('inf')’。

     3.6 版新加入.

 -- Data: cmath.infj

     具有零实部和正无穷虚部的复数。相当于 ‘complex(0.0, float('inf'))’。

     3.6 版新加入.

 -- Data: cmath.nan

     浮点“非数字”（NaN）值。相当于 ‘float('nan')’。

     3.6 版新加入.

 -- Data: cmath.nanj

     具有零实部和 NaN 虚部的复数。相当于 ‘complex(0.0, float('nan'))’。

     3.6 版新加入.

请注意，函数的选择与模块 *note math: b1. 中的函数选择相似，但不完全相同
。 拥有两个模块的原因是因为有些用户对复数不感兴趣，甚至根本不知道它们是
什么。它们宁愿 ‘math.sqrt(-1)’ 引发异常，也不想返回一个复数。 另请注意，
被 *note cmath: 18. 定义的函数始终会返回一个复数，尽管答案可以表示为一个
实数（在这种情况下，复数的虚数部分为零）。

关于支割线的注释：它们是沿着给定函数无法连续的曲线。它们是许多复变函数的
必要特征。 假设您需要使用复变函数进行计算，您将会了解支割线的概念。 请参
阅几乎所有关于复变函数的（不太基本）的书来获得启发。 对于如何正确地基于
数值目的来选择支割线的相关信息，一个良好的参考如下：

也參考
......

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.


File: python.info,  Node: decimal --- 十进制定点和浮点运算,  Next: fractions --- 分数,  Prev: cmath --- 关于复数的数学函数,  Up: 數值與數學模組

5.9.4 ‘decimal’ — 十进制定点和浮点运算
--------------------------------------

`源码：' Lib/decimal.py(1)

__________________________________________________________________

*note decimal: 35. 模块为快速正确舍入的十进制浮点运算提供支持。 与 *note
float: 1fd. 数据类型相比，它具有以下几个优点：

   * Decimal “基于一个浮点模型，它是为人们设计的，并且必然具有最重要的指
     导原则 —— 计算机必须提供与人们在学校学习的算法相同的算法。” —— 摘自
     十进制算术规范。

   * Decimal 数字的表示是完全精确的。 相比之下，‘1.1’ 和 ‘2.2’ 这样的数
     字在二进制浮点中没有精确的表示。 最终用户通常不希望 ‘1.1 + 2.2’ 如
     二进制浮点数表示那样被显示为 ‘3.3000000000000003’。

   * 精确性延续到算术中。 在十进制浮点数中，‘0.1 + 0.1 + 0.1 - 0.3’ 恰好
     等于零。 在二进制浮点数中，结果为 ‘5.5511151231257827e-017’ 。 虽然
     接近于零，但差异妨碍了可靠的相等性检验，并且差异可能会累积。 因此，
     在具有严格相等不变量的会计应用程序中， decimal 是首选。

   * 十进制模块包含有效位的概念，因此 ‘1.30 + 1.20’ 的结果是 ‘2.50’ 。 保
     留尾随零以表示有效位。 这是货币的惯用表示方法。乘法则沿用 “教科书“
     中：保留被乘数中的所有数字的方法。 例如， ‘1.3 * 1.2’ 结果是 ‘1.56’
     而 ‘1.30 * 1.20’ 结果是 ‘1.5600’ 。

   * 与基于硬件的二进制浮点不同，十进制模块具有用户可更改的精度（默认为
     28位），可以与给定问题所需的一样大：

          >>> from decimal import *
          >>> getcontext().prec = 6
          >>> Decimal(1) / Decimal(7)
          Decimal('0.142857')
          >>> getcontext().prec = 28
          >>> Decimal(1) / Decimal(7)
          Decimal('0.1428571428571428571428571429')

   * 二进制和十进制浮点都是根据已发布的标准实现的。 虽然内置浮点类型只公
     开其功能的一小部分，但十进制模块公开了标准的所有必需部分。 在需要时
     ，程序员可以完全控制舍入和信号处理。 这包括通过使用异常来阻止任何不
     精确操作来强制执行精确算术的选项。

   * 十进制模块旨在支持“无偏见，精确的非连续十进制算术（有时称为定点算术
     ）和舍入浮点算术”。 —— 摘自十进制算术规范。

模块设计以三个概念为中心：十进制数，算术上下文和信号。

十进制数是不可变的。 它有一个符号，系数数字和一个指数。 为了保持重要性，
系数数字不会截断尾随零。十进制数也包括特殊值，例如 ‘Infinity’ ，
‘-Infinity’ ，和 ‘NaN’ 。 该标准还区分 ‘-0’ 和 ‘+0’ 。

算术的上下文是指定精度、舍入规则、指数限制、指示操作结果的标志以及确定符
号是否被视为异常的陷阱启用器的环境。 舍入选项包括 *note ROUND_CEILING:
1bb5. 、 *note ROUND_DOWN: 1bb6. 、 *note ROUND_FLOOR: 1bb7. 、 *note
ROUND_HALF_DOWN: 1bb8, *note ROUND_HALF_EVEN: 1bb9. 、 *note
ROUND_HALF_UP: 1bba. 、 *note ROUND_UP: 1bbb. 以及 *note ROUND_05UP:
1bbc.

信号是在计算过程中出现的异常条件组。 根据应用程序的需要，信号可能会被忽
略，被视为信息，或被视为异常。 十进制模块中的信号有：*note Clamped:
1bbd. 、 *note InvalidOperation: aca. 、 *note DivisionByZero: 1bbe. 、
*note Inexact: 1bbf. 、 *note Rounded: 1bc0. 、 *note Subnormal: 1bc1. 、
*note Overflow: 1bc2. 、 *note Underflow: 1bc3. 以及 *note
FloatOperation: ac4. 。

对于每个信号，都有一个标志和一个陷阱启动器。 遇到信号时，其标志设置为 1
，然后，如果陷阱启用器设置为 1 ，则引发异常。 标志是粘性的，因此用户需要
在监控计算之前重置它们。

也參考
......

   * IBM的通用十进制算术规范， The General Decimal Arithmetic
     Specification(2).

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/decimal.py

   (2) http://speleotrove.com/decimal/decarith.html


File: python.info,  Node: 快速入门教程,  Next: Decimal 对象,  Up: decimal --- 十进制定点和浮点运算

5.9.4.1 快速入门教程
....................

通常使用小数的开始是导入模块，使用 *note getcontext(): 1bc6. 查看当前上
下文，并在必要时为精度、舍入或启用的陷阱设置新值:

     >>> 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

可以从整数、字符串、浮点数或元组构造十进制实例。 从整数或浮点构造将执行
该整数或浮点值的精确转换。 十进制数包括特殊值，例如 ‘NaN’ 代表“非数字”，
正的和负的 ‘Infinity’，和 ‘-0’

     >>> 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')

如果 *note FloatOperation: ac4. 信号被捕获，构造函数中的小数和浮点数的意
外混合或排序比较会引发异常

     >>> 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

3.3 版新加入.

新 Decimal 的重要性仅由输入的位数决定。 上下文精度和舍入仅在算术运算期间
发挥作用。

     >>> 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')

如果超出了C版本的内部限制，则构造一个十进制将引发 *note
InvalidOperation: aca.

     >>> Decimal("1e9999999999999999999")
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]

3.3 版更變.

小数与 Python 的其余部分很好地交互。 这是一个小的十进制浮点飞行杂技团：

     >>> 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')

Decimal 也可以使用一些数学函数：

     >>> 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')

‘quantize()’ 方法将数字舍入为固定指数。 此方法对于将结果舍入到固定的位置
的货币应用程序非常有用：

     >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
     Decimal('7.32')
     >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
     Decimal('8')

如上所示，*note getcontext(): 1bc6. 函数访问当前上下文并允许更改设置。 这
种方法满足大多数应用程序的需求。

对于更高级的工作，使用 Context() 构造函数创建备用上下文可能很有用。 要使
用备用活动，请使用 *note setcontext(): 1bc7. 函数。

根据标准，*note decimal: 35. 模块提供了两个现成的标准上下文 *note
BasicContext: ac8. 和 *note ExtendedContext: ac9. 。 前者对调试特别有用
，因为许多陷阱都已启用：

     >>> 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

上下文还具有用于监视计算期间遇到的异常情况的信号标志。 标志保持设置直到
明确清除，因此最好通过使用 ‘clear_flags()’ 方法清除每组受监控计算之前的
标志。:

     >>> 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=[])

`flags' 条目显示对 ‘Pi’ 的有理逼近被舍入（超出上下文精度的数字被抛弃）并
且结果是不精确的（一些丢弃的数字不为零）。

使用上下文的 ‘traps’ 字段中的字典设置单个陷阱：

     >>> 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

大多数程序仅在程序开始时调整当前上下文一次。 并且，在许多应用程序中，数
据在循环内单个强制转换为 *note Decimal: 2c0. 。 通过创建上下文集和小数，
程序的大部分操作数据与其他 Python 数字类型没有区别。


File: python.info,  Node: Decimal 对象,  Next: 上下文对象,  Prev: 快速入门教程,  Up: decimal --- 十进制定点和浮点运算

5.9.4.2 Decimal 对象
....................

 -- 類別: decimal.Decimal (value="0", context=None)

     根据 `value' 构造一个新的 *note Decimal: 2c0. 对象。

     `value' 可以是整数，字符串，元组，*note float: 1fd. ，或另一个
     *note Decimal: 2c0. 对象。 如果没有给出 `value'，则返回
     ‘Decimal('0')’。 如果 `value' 是一个字符串，它应该在前导和尾随空格
     字符以及下划线被删除之后符合十进制数字字符串语法:

          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

     当上面出现 ‘digit’ 时也允许其他十进制数码。 其中包括来自各种其他语
     言系统的十进制数码（例如阿拉伯-印地语和天城文的数码）以及全宽数码
     ‘'\uff10'’ 到 ‘'\uff19'’。

     如果 `value' 是一个 *note tuple: 1a2. ，它应该有三个组件，一个符号
     （ ‘0’ 表示正数或 ‘1’ 表示负数），一个数字的 *note tuple: 1a2. 和整
     数指数。 例如， ‘Decimal((0, (1, 4, 1, 4), -3))’ 返回
     ‘Decimal('1.414')’。

     如果 `value' 是 *note float: 1fd. ，则二进制浮点值无损地转换为其精
     确的十进制等效值。 此转换通常需要53位或更多位数的精度。 例如，
     ‘Decimal(float('1.1'))’ 转换为
     ‘‘Decimal(’1.100000000000000088817841970012523233890533447265625’)‘‘。

     `context' 精度不会影响存储的位数。 这完全由 `value' 中的位数决定。
     例如，‘Decimal('3.00000')’ 记录所有五个零，即使上下文精度只有三。

     `context' 参数的目的是确定 `value' 是格式错误的字符串时该怎么做。 如
     果上下文陷阱 *note InvalidOperation: aca.，则引发异常；否则，构造函
     数返回一个新的 Decimal，其值为 ‘NaN’。

     构造完成后， *note Decimal: 2c0. 对象是不可变的。

     3.2 版更變: 现在允许构造函数的参数为 *note float: 1fd. 实例。

     3.3 版更變: *note float: 1fd. 参数在设置 *note FloatOperation: ac4.
     陷阱时引发异常。 默认情况下，陷阱已关闭。

     3.6 版更變: 允许下划线进行分组，就像代码中的整数和浮点文字一样。

     十进制浮点对象与其他内置数值类型共享许多属性，例如 *note float:
     1fd. 和 *note int: 204. 。 所有常用的数学运算和特殊方法都适用。 同
     样，十进制对象可以复制、pickle、打印、用作字典键、用作集合元素、比
     较、排序和强制转换为另一种类型（例如 *note float: 1fd. 或 *note
     int: 204. ）。

     算术对十进制对象和算术对整数和浮点数有一些小的差别。 当余数运算符
     ‘%’ 应用于Decimal对象时，结果的符号是 `被除数' 的符号，而不是除数的
     符号:

          >>> (-7) % 4
          1
          >>> Decimal(-7) % Decimal(4)
          Decimal('-3')

     整数除法运算符 ‘//’ 的行为类似，返回真商的整数部分（截断为零）而不
     是它的向下取整，以便保留通常的标识 ‘x == (x // y) * y + x % y’:

          >>> -7 // 4
          -2
          >>> Decimal(-7) // Decimal(4)
          Decimal('-1')

     ‘%’ 和 ‘//’ 运算符实现了 ‘remainder’ 和 ‘divide-integer’ 操作（分别
     ），如规范中所述。

     十进制对象通常不能与浮点数或 *note fractions.Fraction: 2be. 实例在
     算术运算中结合使用：例如,尝试将 *note Decimal: 2c0. 加到 *note
     float: 1fd. ，将引发 *note TypeError: 1fe.。 但是，可以使用 Python
     的比较运算符来比较 *note Decimal: 2c0. 实例 ‘x’ 和另一个数字 ‘y’ 。
     这样可以避免在对不同类型的数字进行相等比较时混淆结果。

     3.2 版更變: 现在完全支持 *note Decimal: 2c0. 实例和其他数字类型之间
     的混合类型比较。

     除了标准的数字属性，十进制浮点对象还有许多专门的方法：

      -- 成員函式: adjusted ()

          在移出系数最右边的数字之后返回调整后的指数，直到只剩下前导数字
          ：‘Decimal('321e+5').adjusted()’ 返回 7 。 用于确定最高有效位
          相对于小数点的位置。

      -- 成員函式: as_integer_ratio ()

          返回一对 ‘(n, d)’ 整数，表示给定的 *note Decimal: 2c0. 实例作
          为分数、最简形式项并带有正分母:

               >>> Decimal('-3.14').as_integer_ratio()
               (-157, 50)

          转换是精确的。 在 Infinity 上引发 OverflowError ，在 NaN 上引
          起 ValueError 。

     3.6 版新加入.

      -- 成員函式: as_tuple ()

          返回一个 *note named tuple: b7b. 表示的数字：
          ‘DecimalTuple(sign, digits, exponent)’。

      -- 成員函式: canonical ()

          返回参数的规范编码。 目前，一个 *note Decimal: 2c0. 实例的编码
          始终是规范的，因此该操作返回其参数不变。

      -- 成員函式: compare (other, context=None)

          比较两个 Decimal 实例的值。 *note compare(): 1bcd. 返回一个
          Decimal 实例，如果任一操作数是 NaN ，那么结果是 NaN

               a or b is a NaN  ==> Decimal('NaN')
               a < b            ==> Decimal('-1')
               a == b           ==> Decimal('0')
               a > b            ==> Decimal('1')

      -- 成員函式: compare_signal (other, context=None)

          除了所有 NaN 信号之外，此操作与 *note compare(): 1bcd. 方法相
          同。 也就是说，如果两个操作数都不是信令NaN，那么任何静默的 NaN
          操作数都被视为信令NaN。

      -- 成員函式: compare_total (other, context=None)

          使用它们的抽象表示而不是它们的数值来比较两个操作数。 类似于
          *note compare(): 1bcd. 方法，但结果给出了一个总排序 *note
          Decimal: 2c0. 实例。 两个 *note Decimal: 2c0. 实例具有相同的数
          值但不同的表示形式在此排序中比较不相等：

               >>> Decimal('12.0').compare_total(Decimal('12'))
               Decimal('-1')

          静默和发出信号的 NaN 也包括在总排序中。 这个函数的结果是
          ‘Decimal('0')’ 如果两个操作数具有相同的表示，或是
          ‘Decimal('-1')’ 如果第一个操作数的总顺序低于第二个操作数，或是
          ‘Decimal('1')’ 如果第一个操作数在总顺序中高于第二个操作数。 有
          关总排序的详细信息，请参阅规范。

          此操作不受上下文影响且静默：不更改任何标志且不执行舍入。 作为
          例外，如果无法准确转换第二个操作数，则C版本可能会引发
          InvalidOperation。

      -- 成員函式: compare_total_mag (other, context=None)

          比较两个操作数使用它们的抽象表示而不是它们的值，如 *note
          compare_total(): 1bcf.，但忽略每个操作数的符号。
          ‘x.compare_total_mag(y)’ 相当于
          ‘x.copy_abs().compare_total(y.copy_abs())’。

          此操作不受上下文影响且静默：不更改任何标志且不执行舍入。 作为
          例外，如果无法准确转换第二个操作数，则C版本可能会引发
          InvalidOperation。

      -- 成員函式: conjugate ()

          只返回self，这种方法只符合 Decimal 规范。

      -- 成員函式: copy_abs ()

          返回参数的绝对值。 此操作不受上下文影响并且是静默的：没有更改
          标志且不执行舍入。

      -- 成員函式: copy_negate ()

          回到参数的否定。 此操作不受上下文影响并且是静默的：没有标志更
          改且不执行舍入。

      -- 成員函式: copy_sign (other, context=None)

          返回第一个操作数的副本，其符号设置为与第二个操作数的符号相同。
          例如：

               >>> Decimal('2.3').copy_sign(Decimal('-1.5'))
               Decimal('-2.3')

          此操作不受上下文影响且静默：不更改任何标志且不执行舍入。 作为
          例外，如果无法准确转换第二个操作数，则C版本可能会引发
          InvalidOperation。

      -- 成員函式: exp (context=None)

          返回给定数字的（自然）指数函数‘‘e**x‘‘的值。结果使用 *note
          ROUND_HALF_EVEN: 1bb9. 舍入模式正确舍入。

               >>> Decimal(1).exp()
               Decimal('2.718281828459045235360287471')
               >>> Decimal(321).exp()
               Decimal('2.561702493119680037517373933E+139')

      -- 成員函式: from_float (f)

          将浮点数转换为十进制数的类方法。

          注意， ‘Decimal.from_float(0.1)’ 与 ‘Decimal(’0.1’)’ 不同。 由
          于 0.1 在二进制浮点中不能精确表示，因此该值存储为最接近的可表
          示值，即 ‘0x1.999999999999ap-4’ 。 十进制的等效值是
          ‘0.1000000000000000055511151231257827021181583404541015625‘。

               備註: 从 Python 3.2 开始，*note Decimal: 2c0. 实例也可以
               直接从 *note float: 1fd. 构造。

               >>> 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')

          3.1 版新加入.

      -- 成員函式: fma (other, third, context=None)

          混合乘法加法。 返回 self*other+third ，中间乘积 self*other 没
          有舍入。

               >>> Decimal(2).fma(3, 5)
               Decimal('11')

      -- 成員函式: is_canonical ()

          如果参数是规范的，则为返回 *note True: 593.，否则为 *note
          False: 48e. 。 目前，*note Decimal: 2c0. 实例总是规范的，所以
          这个操作总是返回 *note True: 593. 。

      -- 成員函式: is_finite ()

          如果参数是一个有限的数，则返回为 *note True: 593. ；如果参数为
          无穷大或 NaN ，则返回为 *note False: 48e.。

      -- 成員函式: is_infinite ()

          如果参数为正负无穷大，则返回为 *note True: 593. ，否则为 *note
          False: 48e. 。

      -- 成員函式: is_nan ()

          如果参数为 NaN （无论是否静默），则返回为 *note True: 593. ，
          否则为 *note False: 48e. 。

      -- 成員函式: is_normal (context=None)

          如果参数是一个 `标准的' 有限数则返回 *note True: 593.。 如果参
          数为零、次标准数、无穷大或 NaN 则返回 *note False: 48e.。

      -- 成員函式: is_qnan ()

          如果参数为静默 NaN，返回 *note True: 593.，否则返回 *note
          False: 48e.。

      -- 成員函式: is_signed ()

          如果参数带有负号，则返回为 *note True: 593.，否则返回 *note
          False: 48e.。注意，0 和 NaN 都可带有符号。

      -- 成員函式: is_snan ()

          如果参数为显式 NaN，则返回 *note True: 593.，否则返回 *note
          False: 48e.。

      -- 成員函式: is_subnormal (context=None)

          如果参数为次标准数，则返回 *note True: 593.，否则返回 *note
          False: 48e.。

      -- 成員函式: is_zero ()

          如果参数是0（正负皆可），则返回 *note True: 593.，否则返回
          *note False: 48e.。

      -- 成員函式: ln (context=None)

          返回操作数的自然对数（以 e 为底）。结果是使用 *note
          ROUND_HALF_EVEN: 1bb9. 舍入模式正确舍入的。

      -- 成員函式: log10 (context=None)

          返回操作数的以十为底的对数。结果是使用 *note ROUND_HALF_EVEN:
          1bb9. 舍入模式正确舍入的。

      -- 成員函式: logb (context=None)

          对于一个非零数，返回其运算数的调整后指数作为一个 *note
          Decimal: 2c0. 实例。 如果运算数为零将返回
          ‘Decimal('-Infinity')’ 并且产生 the *note DivisionByZero:
          1bbe. 标志。如果运算数是无限大则返回 ‘Decimal('Infinity')’ 。

      -- 成員函式: logical_and (other, context=None)

          *note logical_and(): 1be2. 是需要两个 `逻辑运算数' 的逻辑运算
          （参考 *note 逻辑操作数: 1be3. ）。按位输出两运算数的 ‘and’ 运
          算的结果。

      -- 成員函式: logical_invert (context=None)

          *note logical_invert(): 1be4. 是一个逻辑运算。结果是操作数的按
          位求反。

      -- 成員函式: logical_or (other, context=None)

          *note logical_or(): 1be5. 是需要两个 `logical operands' 的逻辑
          运算（请参阅 *note 逻辑操作数: 1be3. ）。结果是两个运算数的按
          位的 ‘or’ 运算。

      -- 成員函式: logical_xor (other, context=None)

          *note logical_xor(): 1be6. 是需要两个 `逻辑运算数' 的逻辑运算
          （参考 *note 逻辑操作数: 1be3. ）。结果是按位输出的两运算数的
          异或运算。

      -- 成員函式: max (other, context=None)

          像 ‘max(self, other)’ 一样，除了在返回之前应用上下文舍入规则并
          且用信号通知或忽略 ‘NaN’ 值（取决于上下文以及它们是发信号还是
          安静）。

      -- 成員函式: max_mag (other, context=None)

          与 *note max(): 1be7. 方法相似，但是操作数使用绝对值完成比较。

      -- 成員函式: min (other, context=None)

          像 ‘min(self, other)’ 一样，除了在返回之前应用上下文舍入规则并
          且用信号通知或忽略 ‘NaN’ 值（取决于上下文以及它们是发信号还是
          安静）。

      -- 成員函式: min_mag (other, context=None)

          与 *note min(): 1be9. 方法相似，但是操作数使用绝对值完成比较。

      -- 成員函式: next_minus (context=None)

          返回小于给定操作数的上下文中可表示的最大数字（或者当前线程的上
          下文中的可表示的最大数字如果没有给定上下文）。

      -- 成員函式: next_plus (context=None)

          返回大于给定操作数的上下文中可表示的最小数字（或者当前线程的上
          下文中的可表示的最小数字如果没有给定上下文）。

      -- 成員函式: next_toward (other, context=None)

          如果两运算数不相等，返回在第二个操作数的方向上最接近第一个操作
          数的数。如果两操作数数值上相等，返回将符号设置为与第二个运算数
          相同的第一个运算数的拷贝。

      -- 成員函式: normalize (context=None)

          通过去除尾随的零并将所有结果等于 ‘Decimal('0')’ 的转化为
          ‘Decimal('0e0')’ 来标准化数字。用于为等效类的属性生成规范值。
          比如， ‘Decimal('32.100')’ 和 ‘Decimal('0.321000e+2')’ 都被标
          准化为相同的值 ‘Decimal('32.1')’。

      -- 成員函式: number_class (context=None)

          返回一个字符串描述运算数的 `class' 。返回值是以下十个字符串中
          的一个。

             * ‘"-Infinity"’ ，指示运算数为负无穷大。

             * ‘"-Normal"’ ，指示该运算数是负正常数字。

             * ‘"-Subnormal"’ ，指示该运算数是负的次标准数。

             * ‘"-Zero"’ ，指示该运算数是负零。

             * ‘"-Zero"’ ，指示该运算数是正零。

             * ‘"+Subnormal"’ ，指示该运算数是正的次标准数。

             * ‘"+Normal"’ ，指示该运算数是正的标准数。

             * ‘"+Infinity"’ ，指示该运算数是正无穷。

             * ‘"NaN"’ ，指示该运算数是肃静 NaN （非数字）。

             * ‘"sNaN"’ ，指示该运算数是信号 NaN 。

      -- 成員函式: quantize (exp, rounding=None, context=None)

          返回的值等于舍入后的第一个运算数并且具有第二个操作数的指数。

               >>> Decimal('1.41421356').quantize(Decimal('1.000'))
               Decimal('1.414')

          与其他运算不同，如果量化运算后的系数长度大于精度，那么会发出一
          个 *note InvalidOperation: aca. 信号。这保证了除非有一个错误情
          况，量化指数恒等于右手运算数的指数。

          与其他运算不同，量化永不信号下溢，即使结果不正常且不精确。

          如果第二个运算数的指数大于第一个运算数的指数那或许需要舍入。在
          这种情况下，舍入模式由给定 ‘rounding’ 参数决定，其余的由给定
          ‘context’ 参数决定；如果参数都未给定，使用当前线程上下文的舍入
          模式。

          每当结果的指数大于 ‘Emax’ 或小于 ‘Etiny’ 就会返回错误。

      -- 成員函式: radix ()

          返回 ‘Decimal(10)’，即 *note Decimal: 2c0. 类进行所有算术运算
          所用的数制（基数）。 这是为保持与规范描述的兼容性而加入的。

      -- 成員函式: remainder_near (other, context=None)

          返回 `self' 除以 `other' 的余数。 这与 ‘self % other’ 的区别在
          于所选择的余数要使其绝对值最小化。 更准确地说，返回值为 ‘self
          - n * other’ 其中 ‘n’ 是最接近 ‘self / other’ 的实际值的整数，
          并且如果两个整数与实际值的差相等则会选择其中的偶数。

          如果结果为零则其符号将为 `self' 的符号。

               >>> Decimal(18).remainder_near(Decimal(10))
               Decimal('-2')
               >>> Decimal(25).remainder_near(Decimal(10))
               Decimal('5')
               >>> Decimal(35).remainder_near(Decimal(10))
               Decimal('-5')

      -- 成員函式: rotate (other, context=None)

          返回对第一个操作数的数码按第二个操作数所指定的数量进行轮转的结
          果。 第二个操作数必须为 -precision 至 precision 精度范围内的整
          数。 第二个操作数的绝对值给出要轮转的位数。 如果第二个操作数为
          正值则向左轮转；否则向右轮转。 如有必要第一个操作数的系数会在
          左侧填充零以达到 precision 所指定的长度。 第一个操作数的符号和
          指数保持不变。

      -- 成員函式: same_quantum (other, context=None)

          检测自身与 other 是否具有相同的指数或是否均为 ‘NaN’。

          此操作不受上下文影响且静默：不更改任何标志且不执行舍入。 作为
          例外，如果无法准确转换第二个操作数，则C版本可能会引发
          InvalidOperation。

      -- 成員函式: scaleb (other, context=None)

          返回第一个操作数使用第二个操作数对指数进行调整的结果。 等价于
          返回第一个操作数乘以 ‘10**other’ 的结果。 第二个操作数必须为整
          数。

      -- 成員函式: shift (other, context=None)

          返回第一个操作数的数码按第二个操作数所指定的数量进行移位的结果
          。 第二个操作数必须为 -precision 至 precision 范围内的整数。 第
          二个操作数的绝对值给出要移动的位数。 如果第二个操作数为正值则
          向左移位；否则向右移位。 移入系数的数码为零。 第一个操作数的符
          号和指数保持不变。

      -- 成員函式: sqrt (context=None)

          返回参数的平方根精确到完整精度。

      -- 成員函式: to_eng_string (context=None)

          转换为字符串，如果需要指数则会使用工程标注法。

          工程标注法的指数是 3 的倍数。 这会在十进制位的左边保留至多 3 个
          数码，并可能要求添加一至两个末尾零。

          例如，此方法会将 ‘Decimal('123E+1')’ 转换为
          ‘Decimal('1.23E+3')’。

      -- 成員函式: to_integral (rounding=None, context=None)

          与 *note to_integral_value(): 1bf9. 方法相同。 保留
          ‘to_integral’ 名称是为了与旧版本兼容。

      -- 成員函式: to_integral_exact (rounding=None, context=None)

          舍入到最接近的整数，发出信号 *note Inexact: 1bbf. 或者如果发生
          舍入则相应地发出信号 *note Rounded: 1bc0.。 如果给出
          ‘rounding’ 形参则由其确定舍入模式，否则由给定的 ‘context’ 来确
          定。 如果没有给定任何形参则会使用当前上下文的舍入模式。

      -- 成員函式: to_integral_value (rounding=None, context=None)

          舍入到最接近的整数而不发出 *note Inexact: 1bbf. 或 *note
          Rounded: 1bc0. 信号。 如果给出 `rounding' 则会应用其所指定的舍
          入模式；否则使用所提供的 `context' 或当前上下文的舍入方法。

* Menu:

* 逻辑操作数::


File: python.info,  Node: 逻辑操作数,  Up: Decimal 对象

5.9.4.3 逻辑操作数
..................

‘logical_and()’, ‘logical_invert()’, ‘logical_or()’ 和 ‘logical_xor()’ 方
法期望其参数为 `逻辑操作数'。 `逻辑操作数' 是指数位与符号位均为零的
*note Decimal: 2c0. 实例，并且其数字位均为 ‘0’ 或 ‘1’。


File: python.info,  Node: 上下文对象,  Next: 常数<3>,  Prev: Decimal 对象,  Up: decimal --- 十进制定点和浮点运算

5.9.4.4 上下文对象
..................

上下文是算术运算所在的环境。 它们管理精度、设置舍入规则、确定将哪些信号
视为异常，并限制指数的范围。

每个线程都有自己的当前上下文，可使用 *note getcontext(): 1bc6. 和 *note
setcontext(): 1bc7. 函数来读取或修改：

 -- 函式: decimal.getcontext ()

     返回活动线程的当前上下文。

 -- 函式: decimal.setcontext (c)

     将活动线程的当前上下文设为 `c'。

你也可以使用 *note with: 7da. 语句和 *note localcontext(): 1813. 函数来
临时改变活动上下文。

 -- 函式: decimal.localcontext (ctx=None)

     返回一个上下文管理器，它将在进入 with 语句时将活动线程的当前上下文
     设为 `ctx' 的一个副本并在退出 with 语句时恢复之前的上下文。 如果未
     指定上下文，则会使用当前上下文的一个副本。

     例如，以下代码会将当前 decimal 精度设为 42 位，执行一个运算，然后自
     动恢复之前的上下文:

          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

新的上下文也可使用下述的 *note Context: acf. 构造器来创建。 此外，模块还
提供了三种预设的上下文:

 -- 類別: decimal.BasicContext

     这是由通用十进制算术规范描述所定义的标准上下文。 精度设为九。 舍入
     设为 *note ROUND_HALF_UP: 1bba.。 清除所有旗标。 启用所有陷阱（视为
     异常），但 *note Inexact: 1bbf, *note Rounded: 1bc0. 和 *note
     Subnormal: 1bc1. 除外。

     由于启用了许多陷阱，此上下文适用于进行调试。

 -- 類別: decimal.ExtendedContext

     这是由通用十进制算术规范描述所定义的标准上下文。 精度设为九。 舍入
     设为 *note ROUND_HALF_EVEN: 1bb9.。 清除所有旗标。 不启用任何陷阱（
     因此在计算期间不会引发异常）。

     由于禁用了陷阱，此上下文适用于希望结果值为 ‘NaN’ 或 ‘Infinity’ 而不
     是引发异常的应用。 这允许应用在出现当其他情况下会中止程序的条件时仍
     能完成运行。

 -- 類別: decimal.DefaultContext

     此上下文被 *note Context: acf. 构造器用作新上下文的原型。 改变一个
     字段（例如精度）的效果将是改变 *note Context: acf. 构造器所创建的新
     上下文的默认值。

     此上下文最适用于多线程环境。 在线程开始前改变一个字段具有设置全系统
     默认值的效果。 不推荐在线程开始后改变字段，因为这会要求线程同步避免
     竞争条件。

     在单线程环境中，最好完全不使用此上下文。 而是简单地电显式创建上下文
     ，具体如下所述。

     默认值为 ‘prec’=‘28’, ‘rounding’=*note ROUND_HALF_EVEN: 1bb9.，并为
     *note Overflow: 1bc2, *note InvalidOperation: aca. 和 *note
     DivisionByZero: 1bbe. 启用陷阱。

在已提供的三种上下文之外，还可以使用 *note Context: acf. 构造器创建新的
上下文。

 -- 類別: decimal.Context (prec=None, rounding=None, Emin=None,
          Emax=None, capitals=None, clamp=None, flags=None, traps=None)

     创建一个新上下文。 如果某个字段未指定或为 *note None: 203.，则从
     *note DefaultContext: ac7. 拷贝默认值。 如果 `flags' 字段未指定或为
     *note None: 203.，则清空所有旗标。

     `prec' 为一个 [‘1’, *note MAX_PREC: 1bfe.] 范围内的整数，用于设置该
     上下文中算术运算的精度。

     `rounding' 选项应为 *note Rounding Modes: 1bff. 小节中列出的常量之
     一。

     `traps' 和 `flags' 字段列出要设置的任何信号。 通常，新上下文应当只
     设置 traps 而让 flags 为空。

     `Emin' 和 `Emax' 字段给定指数所允许的外部上限。 `Emin' 必须在
     [*note MIN_EMIN: 1c00, ‘0’] 范围内，`Emax' 在 [‘0’, *note MAX_EMAX:
     1c01.] 范围内。

     `capitals' 字段为 ‘0’ 或 ‘1’ (默认值)。 如果设为 ‘1’，指数将附带打
     印大写的 ‘E’；其他情况则将使用小写的 ‘e’: ‘Decimal('6.02e+23')’。

     `clamp' 字段为 ‘0’ (默认值) 或 ‘1’。 如果设为 ‘1’，则 *note
     Decimal: 2c0. 实例的指数 ‘e’ 的表示范围在此上下文中将严格限制为
     ‘Emin - prec + 1 <= e <= Emax - prec + 1’。 如果 `clamp' 为 ‘0’ 则
     将适用较弱的条件: *note Decimal: 2c0. 实例调整后的指数最大值为
     ‘Emax’。 当 `clamp' 为 ‘1’ 时，一个较大的普通数值将在可能的情况下减
     小其指数并为其系统添加相应数量的零，以便符合指数值限制；这可以保持
     数字值但会丢失有效末尾零的信息。 例如:

          >>> Context(prec=6, Emax=999, clamp=1).create_decimal('1.23e999')
          Decimal('1.23000E+999')

     `clamp' 值为 ‘1’ 时即允许与在 IEEE 754 中描述的固定宽度十进制交换格
     式保持兼容性。

     *note Context: acf. 类定义了几种通用方法以及大量直接在给定上下文中
     进行算术运算的方法。 此外，对于上述的每种 *note Decimal: 2c0. 方法
     （不包括 ‘adjusted()’ 和 ‘as_tuple()’ 方法）都有一个相应的 *note
     Context: acf. 方法。 例如，对于一个 *note Context: acf. 的实例 ‘C’
     和 *note Decimal: 2c0. 的实例 ‘x’，‘C.exp(x)’ 就等价于
     ‘x.exp(context=C)’。 每个 *note Context: acf. 方法都接受一个 Python
     整数（即 *note int: 204. 的实例）在任何接受 Decimal 的实例的地方使
     用。

      -- 成員函式: clear_flags ()

          将所有旗标重置为 ‘0’。

      -- 成員函式: clear_traps ()

          将所有陷阱重置为零 ‘0’。

          3.3 版新加入.

      -- 成員函式: copy ()

          返回上下文的一个副本。

      -- 成員函式: copy_decimal (num)

          返回 Decimal 实例 num 的一个副本。

      -- 成員函式: create_decimal (num)

          基于 `num' 创建一个新 Decimal 实例但使用 `self' 作为上下文。 与
          *note Decimal: 2c0. 构造器不同，该上下文的精度、舍入方法、旗标
          和陷阱会被应用于转换过程。

          此方法很有用处，因为常量往往被给予高于应用所需的精度。 另一个
          好处在于立即执行舍入可以消除超出当前精度的数位所导致的意外效果
          。 在下面的示例中，使用未舍入的输入意味着在总和中添加零会改变
          结果：

               >>> getcontext().prec = 3
               >>> Decimal('3.4445') + Decimal('1.0023')
               Decimal('4.45')
               >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
               Decimal('4.44')

          此方法实现了 IBM 规格描述中的转换为数字操作。 如果参数为字符串
          ，则不允许有开头或末尾的空格或下划线。

      -- 成員函式: create_decimal_from_float (f)

          基于浮点数 `f' 创建一个新的 Decimal 实例，但会使用 `self' 作为
          上下文来执行舍入。 与 *note Decimal.from_float(): c51. 类方法
          不同，上下文的精度、舍入方法、旗标和陷阱会应用到转换中。

               >>> 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

          3.1 版新加入.

      -- 成員函式: Etiny ()

          返回一个等于 ‘Emin - prec + 1’ 的值即次标准化结果中的最小指数
          值。 当发生向下溢出时，指数会设为 *note Etiny: 1c07.。

      -- 成員函式: Etop ()

          返回一个等于 ‘Emax - prec + 1’ 的值。

     使用 decimal 的通常方式是创建 *note Decimal: 2c0. 实例然后对其应用
     算术运算,这些运算发生在活动线程的当前上下文中。 一种替代方式则是使
     用上下文的方法在特定上下文中进行计算。 这些方法类似于 *note
     Decimal: 2c0. 类的方法，在此仅简单地重新列出。

      -- 成員函式: abs (x)

          返回 `x' 的绝对值。

      -- 成員函式: add (x, y)

          返回 `x' 与 `y' 的和。

      -- 成員函式: canonical (x)

          返回相同的 Decimal 对象 `x'。

      -- 成員函式: compare (x, y)

          对 `x' 与 `y' 进行数值比较。

      -- 成員函式: compare_signal (x, y)

          对两个操作数进行数值比较。

      -- 成員函式: compare_total (x, y)

          对两个操作数使用其抽象表示进行比较。

      -- 成員函式: compare_total_mag (x, y)

          对两个操作数使用其抽象表示进行比较，忽略符号。

      -- 成員函式: copy_abs (x)

          返回 `x' 的副本，符号设为 0。

      -- 成員函式: copy_negate (x)

          返回 `x' 的副本，符号取反。

      -- 成員函式: copy_sign (x, y)

          从 `y' 拷贝符号至 `x'。

      -- 成員函式: divide (x, y)

          返回 `x' 除以 `y' 的结果。

      -- 成員函式: divide_int (x, y)

          返回 `x' 除以 `y' 的结果，截短为整数。

      -- 成員函式: divmod (x, y)

          两个数字相除并返回结果的整数部分。

      -- 成員函式: exp (x)

          返回 ‘e ** x’。

      -- 成員函式: fma (x, y, z)

          返回 `x' 乘以 `y' 再加 `z' 的结果。

      -- 成員函式: is_canonical (x)

          如果 `x' 是规范的则返回 ‘True’；否则返回 ‘False’。

      -- 成員函式: is_finite (x)

          如果 `x' 为有限的则返回‘‘True‘‘；否则返回 ‘False’。

      -- 成員函式: is_infinite (x)

          如果 `x' 是无限的则返回 ‘True’；否则返回 ‘False’。

      -- 成員函式: is_nan (x)

          如果 `x' 是 qNaN 或 sNaN 则返回 ‘True’；否则返回 ‘False’。

      -- 成員函式: is_normal (x)

          如果 `x' 是标准数则返回 ‘True’；否则返回 ‘False’。

      -- 成員函式: is_qnan (x)

          如果 `x' 是静默 NaN 则返回 ‘True’；否则返回 ‘False’。

      -- 成員函式: is_signed (x)

          `x' 是负数则返回 ‘True’；否则返回 ‘False’。

      -- 成員函式: is_snan (x)

          如果 `x' 是显式 NaN 则返回 ‘True’；否则返回 ‘False’。

      -- 成員函式: is_subnormal (x)

          如果 `x' 是次标准数则返回 ‘True’；否则返回 ‘False’。

      -- 成員函式: is_zero (x)

          如果 `x' 为零则返回 ‘True’；否则返回 ‘False’。

      -- 成員函式: ln (x)

          返回 `x' 的自然对数（以 e 为底）。

      -- 成員函式: log10 (x)

          返回 `x' 的以 10 为底的对数。

      -- 成員函式: logb (x)

          返回操作数的 MSD 等级的指数。

      -- 成員函式: logical_and (x, y)

          在操作数的每个数位间应用逻辑运算 `and'。

      -- 成員函式: logical_invert (x)

          反转 `x' 中的所有数位。

      -- 成員函式: logical_or (x, y)

          在操作数的每个数位间应用逻辑运算 `or'。

      -- 成員函式: logical_xor (x, y)

          在操作数的每个数位间应用逻辑运算 `xor'。

      -- 成員函式: max (x, y)

          对两个值执行数字比较并返回其中的最大值。

      -- 成員函式: max_mag (x, y)

          对两个值执行忽略正负号的数字比较。

      -- 成員函式: min (x, y)

          对两个值执行数字比较并返回其中的最小值。

      -- 成員函式: min_mag (x, y)

          对两个值执行忽略正负号的数字比较。

      -- 成員函式: minus (x)

          对应于 Python 中的单目前缀取负运算符执行取负操作。

      -- 成員函式: multiply (x, y)

          返回 `x' 和 `y' 的积。

      -- 成員函式: next_minus (x)

          返回小于 `x' 的最大数字表示形式。

      -- 成員函式: next_plus (x)

          返回大于 `x' 的最小数字表示形式。

      -- 成員函式: next_toward (x, y)

          返回 `x' 趋向于 `y' 的最接近的数字。

      -- 成員函式: normalize (x)

          将 `x' 改写为最简形式。

      -- 成員函式: number_class (x)

          返回 `x' 的类的表示。

      -- 成員函式: plus (x)

          对应于 Python 中的单目前缀取正运算符执行取正操作。 此操作将应
          用上下文精度和舍入，因此它 `不是' 标识运算。

      -- 成員函式: power (x, y, modulo=None)

          返回 ‘x’ 的 ‘y’ 次方，如果给出了模数 ‘modulo’ 则取其余数。

          如为两个参数则计算 ‘x**y’。 如果 ‘x’ 为负值则 ‘y’ 必须为整数。
          除非 ‘y’ 为整数且结果为有限值并可在 ’precision’ 位内精确表示否
          则结果将是不精确的。 上下文的舍入模式将被使用。 结果在 Python
          版中总是会被正确地舍入。

          ‘Decimal(0) ** Decimal(0)’ 结果为 ‘InvalidOperation’，而如果
          ‘InvalidOperation’ 未被捕获，则结果为 ‘Decimal('NaN')’。

          3.3 版更變: C 模块计算 *note power(): 1c33. 时会使用已正确舍入
          的 *note exp(): 1c15. 和 *note ln(): 1c20. 函数。 结果是经过良
          好定义的，但仅限于“几乎总是正确地舍入”。

          带有三个参数时，计算 ‘(x**y) % modulo’。 对于三个参数的形式，
          参数将会应用以下限制：

                  - 三个参数必须都是整数

                  - ‘y’ 必须是非负数

                  - ‘x’ 或 ‘y’ 至少有一个不为零

                  - ‘modulo’ 必须不为零且至多有 ’precision’ 位

          来自 ‘Context.power(x, y, modulo)’ 的结果值等于使用无限精度计
          算 ‘(x**y) % modulo’ 所得到的值，但其计算过程更高效。 结果的指
          数为零，无论 ‘x’, ‘y’ 和 ‘modulo’ 的指数是多少。 结果值总是完
          全精确的。

      -- 成員函式: quantize (x, y)

          返回的值等于 `x' (舍入后)，并且指数为 `y'。

      -- 成員函式: radix ()

          恰好返回 10，因为这是 Decimal 对象 :)

      -- 成員函式: remainder (x, y)

          返回整除所得到的余数。

          结果的符号，如果不为零，则与原始除数的符号相同。

      -- 成員函式: remainder_near (x, y)

          返回 ‘x - y * n’，其中 `n' 为最接近 ‘x / y’ 实际值的整数（如结
          果为 0 则其符号将与 `x' 的符号相同）。

      -- 成員函式: rotate (x, y)

          返回 `x' 翻转 `y' 次的副本。

      -- 成員函式: same_quantum (x, y)

          如果两个操作数具有相同的指数则返回 ‘True’。

      -- 成員函式: scaleb (x, y)

          返回第一个操作数添加第二个值的指数后的结果。

      -- 成員函式: shift (x, y)

          返回 `x' 变换 `y' 次的副本。

      -- 成員函式: sqrt (x)

          非负数基于上下文精度的平方根。

      -- 成員函式: subtract (x, y)

          返回 `x' 和 `y' 的差。

      -- 成員函式: to_eng_string (x)

          转换为字符串，如果需要指数则会使用工程标注法。

          工程标注法的指数是 3 的倍数。 这会在十进制位的左边保留至多 3 个
          数码，并可能要求添加一至两个末尾零。

      -- 成員函式: to_integral_exact (x)

          舍入到一个整数。

      -- 成員函式: to_sci_string (x)

          使用科学计数法将一个数字转换为字符串。


File: python.info,  Node: 常数<3>,  Next: 舍入模式,  Prev: 上下文对象,  Up: decimal --- 十进制定点和浮点运算

5.9.4.5 常数
............

本节中的常量仅与 C 模块相关。 它们也被包含在纯 Python 版本以保持兼容性。

                          32位                      64位
                                                    
----------------------------------------------------------------------------------------
                                                    
 -- Data:                 ‘425000000’               ‘999999999999999999’
          decimal.MAX_PREC                          

 -- Data:                 ‘425000000’               ‘999999999999999999’
          decimal.MAX_EMAX                          

 -- Data:                 ‘-425000000’              ‘-999999999999999999’
          decimal.MIN_EMIN                          

 -- Data:                 ‘-849999999’              ‘-1999999999999999997’
          decimal.MIN_ETINY                         

 -- Data: decimal.HAVE_THREADS

     该值为 ‘True’。 已弃用，因为 Python 现在总是启用线程。

3.9 版後已棄用.

 -- Data: decimal.HAVE_CONTEXTVAR

     默认值为 ‘True’。 如果 Python 的编译带有
     ‘--without-decimal-contextvar’ 选项，则 C 版本会使用线程局部而不是
     协程局部上下文并且该值为 ‘False’。 这在某些嵌套上下文场景中将稍快一
     些。

3.9 版新加入: 向下移植到 3.7 和 3.8。


File: python.info,  Node: 舍入模式,  Next: 信号,  Prev: 常数<3>,  Up: decimal --- 十进制定点和浮点运算

5.9.4.6 舍入模式
................

 -- Data: decimal.ROUND_CEILING

     舍入方向为 ‘Infinity’。

 -- Data: decimal.ROUND_DOWN

     舍入方向为零。

 -- Data: decimal.ROUND_FLOOR

     舍入方向为 ‘-Infinity’。

 -- Data: decimal.ROUND_HALF_DOWN

     舍入到最接近的数，同样接近则舍入方向为零。

 -- Data: decimal.ROUND_HALF_EVEN

     舍入到最接近的数，同样接近则舍入到最接近的偶数。

 -- Data: decimal.ROUND_HALF_UP

     舍入到最接近的数，同样接近则舍入到零的反方向。

 -- Data: decimal.ROUND_UP

     舍入到零的反方向。

 -- Data: decimal.ROUND_05UP

     如果最后一位朝零的方向舍入后为 0 或 5 则舍入到零的反方向；否则舍入
     方向为零。


File: python.info,  Node: 信号,  Next: 浮点数说明,  Prev: 舍入模式,  Up: decimal --- 十进制定点和浮点运算

5.9.4.7 信号
............

信号代表在计算期间引发的条件。 每个信号对应于一个上下文旗标和一个上下文
陷阱启用器。

上下文旗标将在遇到特定条件时被设定。 在完成计算之后，将为了获得信息而检
测旗标（例如确定计算是否精确）。 在检测旗标后，请确保在开始下一次计算之
前清除所有旗标。

如果为信号设定了上下文的陷阱启用器，则条件会导致特定的 Python 异常被引发
。 举例来说，如果设定了 *note DivisionByZero: 1bbe. 陷阱，则当遇到此条件
时就将引发 *note DivisionByZero: 1bbe. 异常。

 -- 類別: decimal.Clamped

     修改一个指数以符合表示限制。

     通常，限位将在一个指数超出上下文的 ‘Emin’ 和 ‘Emax’ 限制时发生。 在
     可能的情况下，会通过给系数添加零来将指数缩减至符合限制。

 -- 類別: decimal.DecimalException

     其他信号的基类，并且也是 *note ArithmeticError: 1845. 的一个子类。

 -- 類別: decimal.DivisionByZero

     非无限数被零除的信号。

     可在除法、取余队法或对一个数求负数次幂时发生。 如果此信号未被陷阱捕
     获，则返回 ‘Infinity’ 或 ‘-Infinity’ 并且由对计算的输入来确定正负符
     号。

 -- 類別: decimal.Inexact

     表明发生了舍入且结果是不精确的。

     有非零数位在舍入期间被丢弃的信号。 舍入结果将被返回。 此信号旗标或
     陷阱被用于检测结果不精确的情况。

 -- 類別: decimal.InvalidOperation

     执行了一个无效的操作。

     表明请求了一个无意义的操作。 如未被陷阱捕获则返回 ‘NaN’。 可能的原
     因包括:

          Infinity - Infinity
          0 * Infinity
          Infinity / Infinity
          x % 0
          Infinity % x
          sqrt(-x) and x > 0
          0 ** 0
          x ** (non-integer)
          x ** Infinity

 -- 類別: decimal.Overflow

     数值的溢出。

     表明在发生舍入之后的指数大于 ‘Emax’。 如果未被陷阱捕获，则结果将取
     决于舍入模式，或者向下舍入为最大的可表示有限数，或者向上舍入为
     ‘Infinity’。 无论哪种情况，都将引发 *note Inexact: 1bbf. 和 *note
     Rounded: 1bc0. 信号。

 -- 類別: decimal.Rounded

     发生了舍入，但或许并没有信息丢失。

     一旦舍入丢弃了数位就会发出此信号；即使被丢弃的数位是零 (例如将
     ‘5.00’ 舍入为 ‘5.0’)。 如果未被陷阱捕获，则不经修改地返回结果。 此
     信号用于检测有效位数的丢弃。

 -- 類別: decimal.Subnormal

     在舍入之前指数低于 ‘Emin’。

     当操作结果是次标准数（即指数过小）时就会发出此信号。 如果未被陷阱捕
     获，则不经修改过返回结果。

 -- 類別: decimal.Underflow

     数字向下溢出导致结果舍入到零。

     当一个次标准数结果通过舍入转为零时就会发出此信号。 同时还将引发
     *note Inexact: 1bbf. 和 *note Subnormal: 1bc1. 信号。

 -- 類別: decimal.FloatOperation

     为 float 和 Decimal 的混合启用更严格的语义。

     如果信号未被捕获（默认），则在 *note Decimal: 2c0. 构造器、*note
     create_decimal(): acb. 和所有比较运算中允许 float 和 Decimal 的混合
     。 转换和比较都是完全精确的。 发生的任何混合运算都将通过在上下文旗
     标中设置 *note FloatOperation: ac4. 来静默地记录。 通过 *note
     from_float(): c51. 或 *note create_decimal_from_float(): 1c06. 进行
     显式转换则不会设置旗标。

     在其他情况下（即信号被捕获），则只静默执行相等性比较和显式转换。 所
     有其他混合运算都将引发 *note FloatOperation: ac4.。

以下表格总结了信号的层级结构:

     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)


File: python.info,  Node: 浮点数说明,  Next: 使用线程,  Prev: 信号,  Up: decimal --- 十进制定点和浮点运算

5.9.4.8 浮点数说明
..................

* Menu:

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


File: python.info,  Node: 通过提升精度来解决舍入错误,  Next: 特殊的值,  Up: 浮点数说明

5.9.4.9 通过提升精度来解决舍入错误
..................................

使用十进制浮点数可以消除十进制表示错误（即能够完全精确地表示 ‘0.1’ 这样
的数）；然而，某些运算在非零数位超出给定的精度时仍然可能导致舍入错误。

舍入错误的影响可能因接近相互抵销的加减运算被放大从而导致丢失有效位。
Knuth 提供了两个指导性示例，其中出现了精度不足的浮点算术舍入，导致加法的
交换律和分配律被打破：

     # 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')

*note decimal: 35. 模块则可以通过充分地扩展精度来避免有效位的丢失：

     >>> 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')


File: python.info,  Node: 特殊的值,  Prev: 通过提升精度来解决舍入错误,  Up: 浮点数说明

5.9.4.10 特殊的值
.................

*note decimal: 35. 模块的数字系统提供了一些特殊的值，包括 ‘NaN’, ‘sNaN’,
‘-Infinity’, ‘Infinity’ 以及两种零值 ‘+0’ 和 ‘-0’。

无穷大可以使用 ‘Decimal('Infinity')’ 来构建。 它们也可以在不捕获 *note
DivisionByZero: 1bbe. 信号捕获时通过除以零来产生。 类似地，当不捕获
*note Overflow: 1bc2. 信号时，也可以通过舍入到超出最大可表示数字限制的方
式产生无穷大的结果。

无穷大是有符号的（仿射）并可用于算术运算，它们会被当作极其巨大的不确定数
字来处理。 例如，无穷大加一个常量结果也将为无穷大。

某些不存在有效结果的运算将会返回 ‘NaN’，或者如果捕获了 *note
InvalidOperation: aca. 信号则会引发一个异常。 例如，‘0/0’ 会返回 ‘NaN’ 表
示结果“不是一个数字”。 这样的 ‘NaN’ 是静默产生的，并且在产生之后参与其它
计算时总是会得到 ‘NaN’ 的结果。 这种行为对于偶而缺少输入的各类计算都很有
用处 — 它允许在将特定结果标记为无效的同时让计算继续运行。

另一种变体形式是 ‘sNaN’，它在每次运算后会发出信号而不是保持静默。 当对于
无效结果需要中断计算进行特别处理时，这是一个很有用的返回值。

Python 中比较运算符的行为在涉及 ‘NaN’ 时可能会令人有点惊讶。 相等性检测
在操作数中有静默型或信号型 ‘NaN’ 时总是会返回 *note False: 48e. (即使是
执行 ‘Decimal('NaN')==Decimal('NaN')’)，而不等性检测总是会返回 *note
True: 593.。 当尝试使用 ‘<’, ‘<=’, ‘>’ 或 ‘>=’ 运算符中的任何一个来比较
两个 Decimal 值时，如果运算数中有 ‘NaN’ 则将引发 *note InvalidOperation:
aca. 信号，如果此信号未被捕获则将返回 *note False: 48e.。 请注意通用十进
制算术规范并未规定直接比较行为；这些涉及 ‘NaN’ 的比较规则来自于 IEEE 854
标准 (见第 5.7 节表 3)。 要确保严格符合标准，请改用 ‘compare()’ 和
‘compare-signal()’ 方法。

有符号零值可以由向下溢出的运算产生。 它们保留符号是为了让运算结果能以更
高的精度传递。 由于它们的大小为零，正零和负零会被视为相等，且它们的符号
具有信息。

在这两个不相同但却相等的有符号零之外，还存在几种零的不同表示形式，它们的
精度不同但值也都相等。 这需要一些时间来逐渐适应。 对于习惯了标准浮点表示
形式的眼睛来说，以下运算返回等于零的值并不是显而易见的：

     >>> 1 / Decimal('Infinity')
     Decimal('0E-1000026')


File: python.info,  Node: 使用线程,  Next: 例程,  Prev: 浮点数说明,  Up: decimal --- 十进制定点和浮点运算

5.9.4.11 使用线程
.................

*note getcontext(): 1bc6. 函数会为每个线程访问不同的 *note Context: acf.
对象。 具有单独线程上下文意味着线程可以修改上下文 (例如
‘getcontext().prec=10’) 而不影响其他线程。

类似的 *note setcontext(): 1bc7. 会为当前上下文的目标自动赋值。

如果在调用 *note setcontext(): 1bc7. 之前调用了 *note getcontext():
1bc6.，则 *note getcontext(): 1bc6. 将自动创建一个新的上下文在当前线程中
使用。

新的上下文拷贝自一个名为 `DefaultContext' 的原型上下文。 要控制默认值以
便每个线程在应用运行期间都使用相同的值，可以直接修改 `DefaultContext' 对
象。 这应当在任何线程启动 `之前' 完成以使得调用 *note getcontext():
1bc6. 的线程之间不会产生竞争条件。 例如:

     # 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()
      . . .


File: python.info,  Node: 例程,  Next: Decimal 常见问题,  Prev: 使用线程,  Up: decimal --- 十进制定点和浮点运算

5.9.4.12 例程
.............

以下是一些用作工具函数的例程，它们演示了使用 *note Decimal: 2c0. 类的各
种方式:

     def moneyfmt(value, places=2, curr='', sep=',', dp='.',
                  pos='', neg='-', trailneg=''):
         """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='', neg='', 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 ''.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


File: python.info,  Node: Decimal 常见问题,  Prev: 例程,  Up: decimal --- 十进制定点和浮点运算

5.9.4.13 Decimal 常见问题
.........................

Q. 总是输入 ‘decimal.Decimal('1234.5')’ 是否过于笨拙。 在使用交互解释器
时有没有最小化输入量的方式？

A. 有些用户会将构造器简写为一个字母：

     >>> D = decimal.Decimal
     >>> D('1.23') + D('3.45')
     Decimal('4.68')

Q. 在带有两个十进制位的定点数应用中，有些输入值具有许多位，需要被舍入。
另一些数则不应具有多余位，需要验证有效性。 这种情况应该用什么方法？

A. 用 ‘quantize()’ 方法舍入到固定数量的十进制位。 如果设置了 *note
Inexact: 1bbf. 陷阱，它也适用于验证有效性：

     >>> TWOPLACES = Decimal(10) ** -2       # same as Decimal('0.01')

     >>> # Round to two places
     >>> Decimal('3.214').quantize(TWOPLACES)
     Decimal('3.21')

     >>> # Validate that a number does not exceed two places
     >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
     Decimal('3.21')

     >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
     Traceback (most recent call last):
        ...
     Inexact: None

Q. 当我使用两个有效位的输入时，我要如何在一个应用中保持有效位不变？

A. 某些运算例如与整数相加、相减和相乘将会自动保留固定的小数位数。 其他运
算，例如相除和非整数相乘则将会改变小数位数，需要再加上 ‘quantize()’ 处理
步骤：

     >>> 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')

在开发定点数应用时，更方便的做法是定义处理 ‘quantize()’ 步骤的函数：

     >>> def mul(x, y, fp=TWOPLACES):
     ...     return (x * y).quantize(fp)
     >>> def div(x, y, fp=TWOPLACES):
     ...     return (x / y).quantize(fp)

     >>> mul(a, b)                       # Automatically preserve fixed-point
     Decimal('325.62')
     >>> div(b, a)
     Decimal('0.03')

Q. 表示同一个值有许多方式。 数字 ‘200’, ‘200.000’, ‘2E2’ 和 ‘02E+4’ 的值
都相同但有精度不同。 是否有办法将它们转换为一个可识别的规范值？

A. ‘normalize()’ 方法可将所有相同的值映射为统一表示形式：

     >>> 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')]

Q. 有些十进制值总是被打印为指数表示形式。 是否有办法得到一个非指数表示形
式？

A. 对于某些值来说，指数表示形式是表示系数中有效位的唯一办法。 例如，将
‘5.0E+3’ 表示为 ‘5000’ 可以让值保持恒定，但是无法显示原本的两位有效数字
。

如果一个应用不必关心追踪有效位，则可以很容易地移除指数和末尾的零，丢弃有
效位但让值保持不变：

     >>> def remove_exponent(d):
     ...     return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()

     >>> remove_exponent(Decimal('5E+3'))
     Decimal('5000')

Q. 是否有办法将一个普通浮点数转换为 *note Decimal: 2c0.？

A. 是的，任何二进制浮点数都可以精确地表示为 Decimal 值，但完全精确的转换
可能需要比平常感觉更高的精度：

     >>> Decimal(math.pi)
     Decimal('3.141592653589793115997963468544185161590576171875')

Q. 在一个复杂的计算中，我怎样才能保证不会得到由精度不足和舍入异常所导致
的虚假结果。

A. 使用 decimal 模块可以很容易地检测结果。 最好的做法是使用更高的精度和
不同的舍入模式重新进行计算。 明显不同的结果表明存在精度不足、舍入模式问
题、不符合条件的输入或是结果不稳定的算法。

Q. 我发现上下文精度的应用只针对运算结果而不针对输入。在混合使用不同精度
的值时有什么需要注意的吗？

A. 是的。 原则上所有值都会被视为精确值，在这些值上进行的算术运算也是如此
。 只有结果会被舍入。 对于输入来说其好处是“所输入即所得”。 而其缺点则是
如果你忘记了输入没有被舍入，结果看起来可能会很奇怪：

     >>> getcontext().prec = 3
     >>> Decimal('3.104') + Decimal('2.104')
     Decimal('5.21')
     >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')
     Decimal('5.20')

解决办法是提高精度或使用单目加法运算对输入执行强制舍入：

     >>> getcontext().prec = 3
     >>> +Decimal('1.23456789')      # unary plus triggers rounding
     Decimal('1.23')

此外，还可以使用 *note Context.create_decimal(): acb. 方法在创建输入时执
行舍入：

     >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
     Decimal('1.2345')

Q. CPython 实现对于巨大数字是否足够快速？

A. 是的。 在 CPython 和 PyPy3 实现中，decimal 模块的 C/CFFI 版本集成了高
速 libmpdec(1) 库用于实现任意精度正确舍入的十进制浮点算术 (2)。
‘libmpdec’ 会对中等大小的数字使用 Karatsuba 乘法(3) 而对非常巨大的数字使
用 数字原理变换(4)。

必须要对任意精度算术适配上下文。 ‘Emin’ 和 ‘Emax’ 应当总是设为最大值，
‘clamp’ 应当总是设为 0 (默认值)。 设置 ‘prec’ 需要十分谨慎。

进行大数字算术的最便捷方式也是使用 ‘prec’ 的最大值 (5):

     >>> setcontext(Context(prec=MAX_PREC, Emax=MAX_EMAX, Emin=MIN_EMIN))
     >>> x = Decimal(2) ** 256
     >>> x / 128
     Decimal('904625697166532776746648320380374280103671755200316906558262375061821325312')

对于不精确的结果，在 64 位平台上 *note MAX_PREC: 1bfe. 的值太大了，可用
的内存将会不足:

     >>> Decimal(1) / 3
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     MemoryError

在具有超量分配的系统上 (即 Linux)，一种更复杂的方式根据可用的 RAM 大小来
调整 ‘prec’。 假设你有 8GB 的 RAM 并期望同时有 10 个操作数，每个最多使用
500MB:

     >>> 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'>]

总体而言（特别是在没有超量分配的系统上），如果期望所有计算都是精确的则推
荐预估更严格的边界并设置 *note Inexact: 1bbf. 陷阱。

   ---------- Footnotes ----------

   (1) https://www.bytereef.org/mpdecimal/doc/libmpdec/index.html

   (2) (1)

3.3 版新加入.

   (3) https://en.wikipedia.org/wiki/Karatsuba_algorithm

   (4) 
https://en.wikipedia.org/wiki/Discrete_Fourier_transform_(general)#Number-theoretic_transform

   (5) (2)

3.9 版更變: 此方式现在适用于除了非整数乘方以外的所有精确结果。


File: python.info,  Node: fractions --- 分数,  Next: random --- 生成伪随机数,  Prev: decimal --- 十进制定点和浮点运算,  Up: 數值與數學模組

5.9.5 ‘fractions’ — 分数
------------------------

`源代码' Lib/fractions.py(1)

__________________________________________________________________

*note fractions: 81. 模块支持分数运算。

分数实例可以由一对整数，一个分数，或者一个字符串构建而成。

 -- 類別: fractions.Fraction (numerator=0, denominator=1)

 -- 類別: fractions.Fraction (other_fraction)

 -- 類別: fractions.Fraction (float)

 -- 類別: fractions.Fraction (decimal)

 -- 類別: fractions.Fraction (string)

     第一个版本要求 `numerator' 和 `denominator' 是 *note
     numbers.Rational: d20. 的实例，并返回一个新的 *note Fraction: 2be.
     实例，其值为 ‘numerator/denominator’。 如果 `denominator' 为 ‘0’ 将
     会引发 *note ZeroDivisionError: 1fa.。 第二个版本要求
     `other_fraction' 是 *note numbers.Rational: d20. 的实例，并返回一个
     *note Fraction: 2be. 实例且与传入值相等。 下两个版本接受 *note
     float: 1fd. 或 *note decimal.Decimal: 2c0. 的实例，并返回一个 *note
     Fraction: 2be. 实例且与传入值完全相等。 请注意由于二进制浮点数通常
     存在的问题 (参见 *note 浮點數運算：問題與限制: 1456.)，
     ‘Fraction(1.1)’ 的参数并不会精确等于 11/10，因此 ‘Fraction(1.1)’ 也
     `不会' 返回用户所期望的 ‘Fraction(11, 10)’。 （请参阅下文中 *note
     limit_denominator(): 1c54. 方法的文档。） 构造器的最后一个版本接受
     一个字符串或 unicode 实例。 此实例的通常形式为:

          [sign] numerator ['/' denominator]

     其中的可选项 ‘sign’ 可以为 ’+’ 或 ’-’ 并且 ‘numerator’ 和
     ‘denominator’ (如果存在) 是十进制数码的字符串。 此外，*note float:
     1fd. 构造器所接受的任何表示一个有限值的字符串也都为 *note Fraction:
     2be. 构造器所接受。 不论哪种形式的输入字符串也都可以带有前缀和/或后
     缀的空格符。 这里是一些示例:

          >>> 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)

     *note Fraction: 2be. 类继承自抽象基类 *note numbers.Rational: d20.，
     并实现了该类的所有方法和操作。 *note Fraction: 2be. 实例是可哈希的
     ，并应当被视为不可变对象。 此外，*note Fraction: 2be. 还具有以下属
     性和方法：

     3.2 版更變: *note Fraction: 2be. 构造器现在接受 *note float: 1fd. 和
     *note decimal.Decimal: 2c0. 实例。

     3.9 版更變: 现在会使用 *note math.gcd(): 1be. 函数来正规化
     `numerator' 和 `denominator'。 *note math.gcd(): 1be. 总是返回
     *note int: 204. 类型。 在之前版本中，GCD 的类型取决于 `numerator' 和
     `denominator' 的类型。

      -- 屬性: numerator

          最简分数形式的分子。

      -- 屬性: denominator

          最简分数形式的分母。

      -- 成員函式: as_integer_ratio ()

          返回由两个整数组成的元组，两数之比等于该分数的值且其分母为正数
          。

          3.8 版新加入.

      -- 成員函式: from_float (flt)

          此类方法可构造一个 *note Fraction: 2be. 来表示 `flt' 的精确值
          ，该参数必须是一个 *note float: 1fd.。 请注意
          ‘Fraction.from_float(0.3)’ 的值并不等于 ‘Fraction(3, 10)’。

               備註: 从 Python 3.2 开始，在构造 *note Fraction: 2be. 实
               例时可以直接使用 *note float: 1fd.。

      -- 成員函式: from_decimal (dec)

          此类方法可构造一个 *note Fraction: 2be. 来表示 `dec' 的精确值
          ，该参数必须是一个 *note decimal.Decimal: 2c0. 实例。

               備註: 从 Python 3.2 开始，在构造 *note Fraction: 2be. 实
               例时可以直接使用 *note decimal.Decimal: 2c0. 实例。

      -- 成員函式: limit_denominator (max_denominator=1000000)

          找到并返回一个 *note Fraction: 2be. 使得其值最接近 ‘self’ 并且
          分母不大于 max_denominator。 此方法适用于找出给定浮点数的有理
          数近似值：

               >>> from fractions import Fraction
               >>> Fraction('3.1415926535897932').limit_denominator(1000)
               Fraction(355, 113)

          或是用来恢复被表示为一个浮点数的有理数：

               >>> 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)

      -- 成員函式: __floor__ ()

          返回最大的 *note int: 204. ‘<= self’。 此方法也可通过 *note
          math.floor(): df2. 函数来使用：

               >>> from math import floor
               >>> floor(Fraction(355, 113))
               3

      -- 成員函式: __ceil__ ()

          返回最小的 *note int: 204. ‘>= self’。 此方法也可通过 *note
          math.ceil(): df3. 函数来使用。

      -- 成員函式: __round__ ()

      -- 成員函式: __round__ (ndigits)

          第一个版本返回一个 *note int: 204. 使得其值最接近 ‘self’，位值
          为二分之一时只对偶数舍入。第二个版本会将 ‘self’ 舍入到最接近
          ‘Fraction(1, 10**ndigits)’ 的倍数（如果 ‘ndigits’ 为负值则为逻
          辑运算），位值为二分之一时同样只对偶数舍入。 此方法也可通过
          *note round(): d35. 函数来使用。

也參考
......

*note numbers: c1. 模块

     构成数字塔的所有抽象基类。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/fractions.py


File: python.info,  Node: random --- 生成伪随机数,  Next: statistics --- 數學統計函式,  Prev: fractions --- 分数,  Up: 數值與數學模組

5.9.6 ‘random’ — 生成伪随机数
-----------------------------

`源码：' Lib/random.py(1)

__________________________________________________________________

该模块实现了各种分布的伪随机数生成器。

对于整数，从范围中有统一的选择。 对于序列，存在随机元素的统一选择、用于
生成列表的随机排列的函数、以及用于随机抽样而无需替换的函数。

在实数轴上，有计算均匀、正态（高斯）、对数正态、负指数、伽马和贝塔分布的
函数。 为了生成角度分布，可以使用 von Mises 分布。

几乎所有模块函数都依赖于基本函数 *note random(): 1c5d. ，它在半开放区间
[0.0,1.0) 内均匀生成随机浮点数。 Python 使用 Mersenne Twister 作为核心生
成器。 它产生 53 位精度浮点数，周期为 2**19937-1 ，其在 C 中的底层实现既
快又线程安全。 Mersenne Twister 是现存最广泛测试的随机数发生器之一。 但
是，因为完全确定性，它不适用于所有目的，并且完全不适合加密目的。

这个模块提供的函数实际上是 *note random.Random: 1c5e. 类的隐藏实例的绑定
方法。 你可以实例化自己的 *note Random: 1c5e. 类实例以获取不共享状态的生
成器。

如果你想使用自己设计的不同基础生成器，类 *note Random: 1c5e. 也可以作为
子类：在这种情况下，重载 ‘random()’ 、 ‘seed()’ 、 ‘getstate()’ 以及
‘setstate()’ 方法。可选地，新生成器可以提供 ‘getrandbits()’ 方法——这允许
*note randrange(): c8b. 在任意大的范围内产生选择。

*note random: dc. 模块还提供 *note SystemRandom: 1c5f. 类，它使用系统函
数 *note os.urandom(): 5cb. 从操作系统提供的源生成随机数。

     警告: 不应将此模块的伪随机生成器用于安全目的。 有关安全性或加密用途
     ，请参阅 *note secrets: e4. 模块。

也參考
......

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(2) 用于兼容的替代随机数发生器，
具有长周期和相对简单的更新操作。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/random.py

   (2) https://code.activestate.com/recipes/576707/


File: python.info,  Node: 簿记功能,  Next: 用于字节数据的函数,  Up: random --- 生成伪随机数

5.9.6.1 簿记功能
................

 -- 函式: random.seed (a=None, version=2)

     初始化随机数生成器。

     如果 `a' 被省略或为 ‘None’ ，则使用当前系统时间。 如果操作系统提供
     随机源，则使用它们而不是系统时间（有关可用性的详细信息，请参阅
     *note os.urandom(): 5cb. 函数）。

     如果 `a' 是 int 类型，则直接使用。

     对于版本2（默认的），*note str: 205. 、 *note bytes: 172. 或 *note
     bytearray: 173. 对象转换为 *note int: 204. 并使用它的所有位。

     对于版本1（用于从旧版本的Python再现随机序列），用于 *note str: 205.
     和 *note bytes: 172. 的算法生成更窄的种子范围。

     3.2 版更變: 已移至版本2方案，该方案使用字符串种子中的所有位。

     3.9 版後已棄用: 在将来，`seed' 必须是下列类型之一: `NoneType',
     *note int: 204, *note float: 1fd, *note str: 205, *note bytes: 172.
     或 *note bytearray: 173.。

 -- 函式: random.getstate ()

     返回捕获生成器当前内部状态的对象。 这个对象可以传递给 *note
     setstate(): 1c62. 来恢复状态。

 -- 函式: random.setstate (state)

     `state' 应该是从之前调用 *note getstate(): 1c61. 获得的，并且 *note
     setstate(): 1c62. 将生成器的内部状态恢复到 *note getstate(): 1c61.
     被调用时的状态。


File: python.info,  Node: 用于字节数据的函数,  Next: 整数用函数,  Prev: 簿记功能,  Up: random --- 生成伪随机数

5.9.6.2 用于字节数据的函数
..........................

 -- 函式: random.randbytes (n)

     生成 `n' 个随机字节。

     此方法不可用于生成安全凭据。 那应当使用 *note
     secrets.token_bytes(): 1c64.。

     3.9 版新加入.


File: python.info,  Node: 整数用函数,  Next: 序列用函数,  Prev: 用于字节数据的函数,  Up: random --- 生成伪随机数

5.9.6.3 整数用函数
..................

 -- 函式: random.randrange (stop)

 -- 函式: random.randrange (start, stop[, step])

     从 ‘range(start, stop, step)’ 返回一个随机选择的元素。 这相当于
     ‘choice(range(start, stop, step))’ ，但实际上并没有构建一个 range 对
     象。

     位置参数模式匹配 *note range(): 1f5. 。不应使用关键字参数，因为该函
     数可能以意外的方式使用它们。

     3.2 版更變: *note randrange(): c8b. 在生成均匀分布的值方面更为复杂
     。 以前它使用了像‘‘int(random()*n)‘‘这样的形式，它可以产生稍微不均
     匀的分布。

 -- 函式: random.randint (a, b)

     返回随机整数 `N' 满足 ‘a <= N <= b’。相当于 ‘randrange(a, b+1)’。

 -- 函式: random.getrandbits (k)

     返回具有 `k' 个随机比特位的非负 Python 整数。 此方法随
     MersenneTwister 生成器一起提供，其他一些生成器也可能将其作为 API 的
     可选部分提供。 在可能的情况下，*note getrandbits(): a17. 会启用
     *note randrange(): c8b. 来处理任意大的区间。

     3.9 版更變: 此方法现在接受零作为 `k' 的值。


File: python.info,  Node: 序列用函数,  Next: 实值分布,  Prev: 整数用函数,  Up: random --- 生成伪随机数

5.9.6.4 序列用函数
..................

 -- 函式: random.choice (seq)

     从非空序列 `seq' 返回一个随机元素。 如果 `seq' 为空，则引发 *note
     IndexError: f36.。

 -- 函式: random.choices (population, weights=None, *, cum_weights=None,
          k=1)

     从*population*中选择替换，返回大小为 `k' 的元素列表。 如果
     `population' 为空，则引发 *note IndexError: f36.。

     如果指定了 `weight' 序列，则根据相对权重进行选择。 或者，如果给出
     `cum_weights' 序列，则根据累积权重（可能使用 *note
     itertools.accumulate(): 30e. 计算）进行选择。 例如，相对权重‘‘[10,
     5, 30, 5]‘‘相当于累积权重‘‘[10, 15, 45, 50]‘‘。 在内部，相对权重在
     进行选择之前会转换为累积权重，因此提供累积权重可以节省工作量。

     如果既未指定 `weight' 也未指定 `cum_weights' ，则以相等的概率进行选
     择。 如果提供了权重序列，则它必须与 `population' 序列的长度相同。 一
     个 *note TypeError: 1fe. 指定了 `weights' 和*cum_weights*。

     `weights' 或 `cum_weights' 可使用 *note random(): dc. 所返回的能与
     *note float: 1fd. 值进行相互运算的任何数字类型（包括 int、float、
     Fraction 但不包括 Decimal）。 权重为负值的行为未有定义。 如果权重为
     负值则将引发 *note ValueError: 16d.。

     对于给定的种子，具有相等加权的 *note choices(): 66b. 函数通常产生与
     重复调用 *note choice(): c8d. 不同的序列。 *note choices(): 66b. 使
     用的算法使用浮点运算来实现内部一致性和速度。 *note choice(): c8d. 使
     用的算法默认为重复选择的整数运算，以避免因舍入误差引起的小偏差。

     3.6 版新加入.

     3.9 版更變: 如果所有权重均为负值则将引发 *note ValueError: 16d.。

 -- 函式: random.shuffle (x[, random])

     将序列 `x' 随机打乱位置。

     可选参数 `random' 是一个0参数函数，在 [0.0, 1.0) 中返回随机浮点数；
     默认情况下，这是函数 *note random(): 1c5d. 。

     要改变一个不可变的序列并返回一个新的打乱列表，请使用‘‘sample(x,
     k=len(x))‘‘。

     请注意，即使对于小的 ‘len(x)’，`x' 的排列总数也可以快速增长，大于大
     多数随机数生成器的周期。 这意味着长序列的大多数排列永远不会产生。 例
     如，长度为2080的序列是可以在 Mersenne Twister 随机数生成器的周期内
     拟合的最大序列。

     Deprecated since version 3.9, will be removed in version 3.11: 可选
     形参 `random'。

 -- 函式: random.sample (population, k, *, counts=None)

     返回从总体序列或集合中选择的唯一元素的 `k' 长度列表。 用于无重复的
     随机抽样。

     返回包含来自总体的元素的新列表，同时保持原始总体不变。 结果列表按选
     择顺序排列，因此所有子切片也将是有效的随机样本。 这允许抽奖获奖者（
     样本）被划分为大奖和第二名获胜者（子切片）。

     总体成员不必是 *note hashable: 276. 或 unique 。 如果总体包含重复，
     则每次出现都是样本中可能的选择。

     重复的元素可以一个个地直接列出，或使用可选的仅限关键字形参 `counts'
     来指定。 例如，‘sample(['red', 'blue'], counts=[4, 2], k=5)’ 等价于
     ‘sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5)’。

     要从一系列整数中选择样本，请使用 *note range(): 1f5. 对象作为参数。
     对于从大量人群中采样，这种方法特别快速且节省空间：
     ‘sample(range(10000000), k=60)’ 。

     如果样本大小大于总体大小，则引发 *note ValueError: 16d. 。

     3.9 版更變: 增加了 `counts' 形参。

     3.9 版後已棄用: 在将来，`population' 必须是一个序列。 *note set:
     1f6. 的实例将不再被支持。 集合必须先转换为 *note list: 1f8. 或
     *note tuple: 1a2.，最好是固定顺序以使抽样是可重现的。


File: python.info,  Node: 实值分布,  Next: 替代生成器,  Prev: 序列用函数,  Up: random --- 生成伪随机数

5.9.6.5 实值分布
................

以下函数生成特定的实值分布。如常用数学实践中所使用的那样, 函数参数以分布
方程中的相应变量命名;大多数这些方程都可以在任何统计学教材中找到。

 -- 函式: random.random ()

     返回 [0.0, 1.0) 范围内的下一个随机浮点数。

 -- 函式: random.uniform (a, b)

     返回一个随机浮点数 `N' ，当 ‘a <= b’ 时 ‘a <= N <= b’ ，当 ‘b < a’
     时 ‘b <= N <= a’ 。

     取决于等式 ‘a + (b-a) * random()’ 中的浮点舍入，终点 ‘b’ 可以包括或
     不包括在该范围内。

 -- 函式: random.triangular (low, high, mode)

     返回一个随机浮点数 `N' ，使得 ‘low <= N <= high’ 并在这些边界之间使
     用指定的 `mode' 。 `low' 和 `high' 边界默认为零和一。 `mode' 参数默
     认为边界之间的中点，给出对称分布。

 -- 函式: random.betavariate (alpha, beta)

     Beta 分布。 参数的条件是 ‘alpha > 0’ 和 ‘beta > 0’。 返回值的范围介
     于 0 和 1 之间。

 -- 函式: random.expovariate (lambd)

     指数分布。 `lambd' 是 1.0 除以所需的平均值，它应该是非零的。 （该参
     数本应命名为 “lambda” ，但这是 Python 中的保留字。）如果 `lambd' 为
     正，则返回值的范围为 0 到正无穷大；如果 `lambd' 为负，则返回值从负
     无穷大到 0。

 -- 函式: random.gammavariate (alpha, beta)

     Gamma 分布。 （ `不是' gamma 函数！ ） 参数的条件是 ‘alpha > 0’ 和
     ‘beta > 0’。

     概率分布函数是:

                    x ** (alpha - 1) * math.exp(-x / beta)
          pdf(x) =  --------------------------------------
                      math.gamma(alpha) * beta ** alpha

 -- 函式: random.gauss (mu, sigma)

     高斯分布。 `mu' 是平均值，`sigma' 是标准差。 这比下面定义的 *note
     normalvariate(): 1c6f. 函数略快。

     多线程注意事项：当两个线程同时调用此方法时，它们有可能将获得相同的
     返回值。 这可以通过三种办法来避免。 1) 让每个线程使用不同的随机数生
     成器实例。 2) 在所有调用外面加锁。 3) 改用速度较慢但是线程安全的
     *note normalvariate(): 1c6f. 函数。

 -- 函式: random.lognormvariate (mu, sigma)

     对数正态分布。 如果你采用这个分布的自然对数，你将得到一个正态分布，
     平均值为 `mu' 和标准差为 `sigma' 。 `mu' 可以是任何值，`sigma' 必须
     大于零。

 -- 函式: random.normalvariate (mu, sigma)

     正态分布。 `mu' 是平均值，`sigma' 是标准差。

 -- 函式: random.vonmisesvariate (mu, kappa)

     冯·米塞斯分布。 `mu' 是平均角度，以弧度表示，介于0和 2*`pi' 之间，
     `kappa' 是浓度参数，必须大于或等于零。 如果 `kappa' 等于零，则该分
     布在 0 到 2*`pi' 的范围内减小到均匀的随机角度。

 -- 函式: random.paretovariate (alpha)

     帕累托分布。 `alpha' 是形状参数。

 -- 函式: random.weibullvariate (alpha, beta)

     威布尔分布。 `alpha' 是比例参数，`beta' 是形状参数。


File: python.info,  Node: 替代生成器,  Next: 关于再现性的说明,  Prev: 实值分布,  Up: random --- 生成伪随机数

5.9.6.6 替代生成器
..................

 -- 類別: random.Random ([seed])

     该类实现了 *note random: dc. 模块所用的默认伪随机数生成器。

     3.9 版後已棄用: 在将来，`seed' 必须是下列类型之一: ‘NoneType’,
     *note int: 204, *note float: 1fd, *note str: 205, *note bytes: 172.
     或 *note bytearray: 173.。

 -- 類別: random.SystemRandom ([seed])

     使用 *note os.urandom(): 5cb. 函数的类，用从操作系统提供的源生成随
     机数。 这并非适用于所有系统。 也不依赖于软件状态，序列不可重现。 因
     此，*note seed(): cd3. 方法没有效果而被忽略。 *note getstate():
     1c61. 和 *note setstate(): 1c62. 方法如果被调用则引发 *note
     NotImplementedError: 704.。


File: python.info,  Node: 关于再现性的说明,  Next: 例子,  Prev: 替代生成器,  Up: random --- 生成伪随机数

5.9.6.7 关于再现性的说明
........................

有时能够重现伪随机数生成器给出的序列是很有用处的。 通过重用一个种子值，
只要没有运行多线程，相同的序列就应当可在多次运行中重现。

大多数随机模块的算法和种子函数都会在 Python 版本中发生变化，但保证两个方
面不会改变：

   * 如果添加了新的播种方法，则将提供向后兼容的播种机。

   * 当兼容的播种机被赋予相同的种子时，生成器的 ‘random()’ 方法将继续产
     生相同的序列。


File: python.info,  Node: 例子,  Next: 例程<2>,  Prev: 关于再现性的说明,  Up: random --- 生成伪随机数

5.9.6.8 例子
............

基本示例:

     >>> 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]

模拟:

     >>> # 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

statistical bootstrapping(1) 的示例，使用重新采样和替换来估计一个样本的
均值的置信区间:

     # 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}')

使用 重新采样排列测试(2) 来确定统计学显著性或者使用 p-值(3) 来观察药物与
安慰剂的作用之间差异的示例:

     # 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.')

多服务器队列的到达时间和服务交付模拟:

     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}.')

也參考
......

Statistics for Hackers(4) Jake Vanderplas(5) 撰写的视频教程，使用一些基
本概念进行统计分析，包括模拟、抽样、改组和交叉验证。

Economics Simulation(6) Peter Norvig(7) 编写的市场模拟，显示了该模块提供
的许多工具和分布的有效使用（高斯、均匀、样本、beta变量、选择、三角和随机
范围等）。

A Concrete Introduction to Probability (using Python)(8) Peter Norvig(9)
撰写的教程，涵盖了概率论基础知识，如何编写模拟，以及如何使用 Python 进行
数据分析。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Bootstrapping_(statistics)

   (2) 
https://en.wikipedia.org/wiki/Resampling_(statistics)#Permutation_tests

   (3) https://en.wikipedia.org/wiki/P-value

   (4) https://www.youtube.com/watch?v=Iq9DzN6mvYA

   (5) https://us.pycon.org/2016/speaker/profile/295/

   (6) 
http://nbviewer.jupyter.org/url/norvig.com/ipython/Economics.ipynb

   (7) http://norvig.com/bio.html

   (8) 
http://nbviewer.jupyter.org/url/norvig.com/ipython/Probability.ipynb

   (9) http://norvig.com/bio.html


File: python.info,  Node: 例程<2>,  Prev: 例子,  Up: random --- 生成伪随机数

5.9.6.9 例程
............

默认的 *note random(): 1c5d. 返回在 `0.0 ≤ x < 1.0' 范围内 2⁻⁵³ 的倍数。
所有这些数值间隔相等并能精确表示为 Python 浮点数。 但是在此间隔上有许多
其他可表示浮点数是不可能的选择。 例如，‘0.05954861408025609’ 就不是 2⁻⁵³
的整数倍。

以下规范程序采取了一种不同的方式。 在间隔上的所有浮点数都是可能的选择。
它们的尾数取值来自 `2⁵² ≤ 尾数 < 2⁵³' 范围内整数的均匀分布。 指数取值则
来自几何分布，其中小于 `-53' 的指数的出现频率为下一个较大指数的一半。

     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)

该类中所有的 *note 实值分布: 1c68. 都将使用新的方法:

     >>> fr = FullRandom()
     >>> fr.random()
     0.05954861408025609
     >>> fr.expovariate(0.25)
     8.87925541791544

该规范程序在概念上等效于在 `0.0 ≤ x < 1.0' 范围内对所有 2⁻¹⁰⁷⁴ 的倍数进
行选择的算法。 所有这样的数字间隔都相等，但大多必须向下舍入为最接近的
Python 浮点数表示形式。 （2⁻¹⁰⁷⁴ 这个数值是等于 ‘math.ulp(0.0)’ 的未经正
规化的最小正浮点数。）

也參考
......

生成伪随机浮点数值(1) 为 Allen B. Downey 所撰写的描述如何生成相比通过
*note random(): 1c5d. 正常生成的数值更细粒度浮点数的论文。

   ---------- Footnotes ----------

   (1) https://allendowney.com/research/rand/downey07randfloat.pdf


File: python.info,  Node: statistics --- 數學統計函式,  Prev: random --- 生成伪随机数,  Up: 數值與數學模組

5.9.7 ‘statistics’ — 數學統計函式
---------------------------------

3.4 版新加入.

`Source code:' Lib/statistics.py(1)

__________________________________________________________________

该模块提供了用于计算数字 (*note Real: 1557.-valued) 数据的数理统计量的函
数。

此模块并不是诸如 NumPy(2) ， SciPy(3) 等第三方库或者诸如 Minitab ， SAS
， Matlab 等针对专业统计学家的专有全功能统计软件包的竞品。此模块针对图形
和科学计算器的水平。

除非明确注释，这些函数支持 *note int: 204. ， *note float: 1fd. ， *note
Decimal: 2c0. 和 *note Fraction: 2be. 。当前不支持同其他类型（是否在数字
塔中）的行为。混合类型的集合也是未定义的，并且依赖于实现。如果你输入的数
据由混合类型组成，你应该能够使用 *note map(): cf7. 来确保一个一致的结果
，比如： ‘map(float, input_data)’ 。

* Menu:

* 平均值與中央位置量數::
* 離度 (spread) 的測量: 離度 spread 的測量.
* 函式細節::
* 异常: 异常<3>.
* NormalDist 对象::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/statistics.py

   (2) https://numpy.org

   (3) https://www.scipy.org/


File: python.info,  Node: 平均值與中央位置量數,  Next: 離度 spread 的測量,  Up: statistics --- 數學統計函式

5.9.7.1 平均值與中央位置量數
............................

這些函式計算來自一個母體或樣本的平均值或代表值。

*note mean(): 2ce.          數據的算術平均（平均值）。
                            
                            
*note fmean(): 354.         快速的，浮点算数平均数。
                            
                            
*note geometric_mean(): 355.数据的几何平均数
                            
                            
*note harmonic_mean(): 686. 数据的调和均值
                            
                            
*note median(): 1c7b.       數據的中位數（中間值）。
                            
                            
*note median_low(): 1c7c.   數據中較小的中位數。
                            
                            
*note median_high(): 1c7d.  數據中較大的中位數。
                            
                            
*note median_grouped(): 1c7e.分組數據的中位數或50%處。
                            
                            
*note mode(): 3dd.          离散的或标称的数据的单个众数（出现最多的值）。
                            
                            
*note multimode(): 356.     离散的或标称的数据的众数列表（出现最多的值）。
                            
                            
*note quantiles(): 357.     将数据以相等的概率分为多个间隔。
                            


File: python.info,  Node: 離度 spread 的測量,  Next: 函式細節,  Prev: 平均值與中央位置量數,  Up: statistics --- 數學統計函式

5.9.7.2 離度 (spread) 的測量
............................

這些函式計算母體或樣本偏離平均值的程度。

*note pstdev(): 1c80.       數據的母體標準差
                            
                            
*note pvariance(): 1c81.    數據的母體變異數
                            
                            
*note stdev(): 1c82.        數據的樣本標準差
                            
                            
*note variance(): 1c83.     數據的樣本變異數
                            


File: python.info,  Node: 函式細節,  Next: 异常<3>,  Prev: 離度 spread 的測量,  Up: statistics --- 數學統計函式

5.9.7.3 函式細節
................

注释：这些函数不需要对提供给它们的数据进行排序。但是，为了方便阅读，大多
数例子展示的是已排序的序列。

 -- 函式: statistics.mean (data)

     返回 `data' 的样本算术平均数，形式为序列或迭代器。

     算术平均数是数据之和与数据点个数的商。通常称作“平均数”，尽管它指示
     诸多数学平均数之一。它是数据的中心位置的度量。

     若 `data' 为空，将会引发 *note StatisticsError: 1c85.。

     一些用法示例：

          >>> 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')

          備註: The mean is strongly affected by outliers(1) and is not
          necessarily a typical example of the data points.  For a more
          robust, although less efficient, measure of central
          tendency(2), see *note median(): 1c7b.

          样本均值给出了一个无偏向的真实总体均值的估计，因此当平均抽取所
          有可能的样本， ‘mean(sample)’ 收敛于整个总体的真实均值。如果
          `data' 代表整个总体而不是样本，那么 ‘mean(data)’ 等同于计算真
          实整体均值 μ 。

 -- 函式: statistics.fmean (data)

     将 `data' 转换成浮点数并且计算算术平均数。

     此函数的运行速度比 *note mean(): 2ce. 函数快并且它总是返回一个
     *note float: 1fd.。 `data' 可以为序列或可迭代对象。 如果输入数据集
     为空，则会引发 *note StatisticsError: 1c85.。

          >>> fmean([3.5, 4.0, 5.25])
          4.25

     3.8 版新加入.

 -- 函式: statistics.geometric_mean (data)

     将 `data' 转换成浮点数并且计算几何平均数。

     几何平均值使用值的乘积表示 `数据' 的中心趋势或典型值（与使用它们的
     总和的算术平均值相反）。

     如果输入数据集为空、包含零或包含负值则将引发 *note StatisticsError:
     1c85.。 `data' 可以是序列或可迭代对象。

     无需做出特殊努力即可获得准确的结果。（但是，将来或许会修改。）

          >>> round(geometric_mean([54, 24, 36]), 1)
          36.0

     3.8 版新加入.

 -- 函式: statistics.harmonic_mean (data)

     返回 `data' 调和均值，该参数可以是序列或包含实数值的可迭代对象。

     调和均值,也叫次相反均值，所有数据的倒数的算术平均数 *note mean():
     2ce. 的倒数。比如说，数据 `a' ， `b' ， `c' 的调和均值等于 ‘3/(1/a
     + 1/b + 1/c)’ 。如果其中一个值为零，结果为零。

     调和均值是一种均值类型，是数据中心位置的度量。它通常适合于求比率和
     比例的平均值，比如速率。

     假设一辆车在 40 km/hr 的速度下行驶了 10 km ，然后又以 60 km/hr 的速
     度行驶了 10 km 。车辆的平均速率是多少？

          >>> harmonic_mean([40, 60])
          48.0

     假设一名投资者在三家公司各购买了等价值的股票，以 2.5， 3 ， 10 的
     P/E (价格/收益) 率。投资者投资组合的平均市盈率是多少？

          >>> harmonic_mean([2.5, 3, 10])  # For an equal investment portfolio.
          3.6

     如果 `data' 为空或者 任何一个元素的值小于零，会引发 *note
     StatisticsError: 1c85. 。

     当前算法在输入中遇到零时会提前退出。这意味着不会测试后续输入的有效
     性。（此行为将来可能会更改。）

     3.6 版新加入.

 -- 函式: statistics.median (data)

     使用普通的“取中间两数平均值”方法返回数值数据的中位数（中间值）。 如
     果 `data' 为空，则将引发 *note StatisticsError: 1c85.。 `data' 可以
     是序列或可迭代对象。

     中位数是衡量中间位置的可靠方式，并且较少受到极端值的影响。 当数据点
     的总数为奇数时，将返回中间数据点：

          >>> median([1, 3, 5])
          3

     当数据点的总数为偶数时，中位数将通过对两个中间值求平均进行插值得出
     ：

          >>> median([1, 3, 5, 7])
          4.0

     这适用于当你的数据是离散的，并且你不介意中位数不是实际数据点的情况
     。

     如果数据是有序的（支持排序操作）但不是数字（不支持加法），请考虑改
     用 *note median_low(): 1c7c. 或 *note median_high(): 1c7d.。

 -- 函式: statistics.median_low (data)

     返回数值数据的低中位数。 如果 `data' 为空则将引发 *note
     StatisticsError: 1c85.。 `data' 可以是序列或可迭代对象。

     低中位数一定是数据集的成员。 当数据点总数为奇数时，将返回中间值。 当
     其为偶数时，将返回两个中间值中较小的那个。

          >>> median_low([1, 3, 5])
          3
          >>> median_low([1, 3, 5, 7])
          3

     当你的数据是离散的，并且你希望中位数是一个实际数据点而非插值结果时
     可以使用低中位数。

 -- 函式: statistics.median_high (data)

     返回数据的高中位数。 如果 `data' 为空则将引发 *note
     StatisticsError: 1c85.。 `data' 可以是序列或可迭代对象。

     高中位数一定是数据集的成员。 当数据点总数为奇数时，将返回中间值。 当
     其为偶数时，将返回两个中间值中较大的那个。

          >>> median_high([1, 3, 5])
          3
          >>> median_high([1, 3, 5, 7])
          5

     当你的数据是离散的，并且你希望中位数是一个实际数据点而非插值结果时
     可以使用高中位数。

 -- 函式: statistics.median_grouped (data, interval=1)

     返回分组的连续数据的中位数，根据第 50 个百分点的位置使用插值来计算
     。 如果 `data' 为空则将引发 *note StatisticsError: 1c85.。 `data' 可
     以是序列或可迭代对象。

          >>> median_grouped([52, 52, 53, 54])
          52.5

     在下面的示例中，数据已经过舍入，这样每个值都代表数据分类的中间点，
     例如 1 是 0.5–1.5 分类的中间点，2 是 1.5–2.5 分类的中间点，3 是
     2.5–3.5 的中间点等待。 根据给定的数据，中间值应落在 3.5–4.5 分类之
     内，并可使用插值法来进行估算：

          >>> median_grouped([1, 2, 2, 3, 4, 4, 4, 4, 4, 5])
          3.7

     可选参数 `interval' 表示分类间隔，默认值为 1。 改变分类间隔自然会改
     变插件结果：

          >>> median_grouped([1, 3, 3, 5, 7], interval=1)
          3.25
          >>> median_grouped([1, 3, 3, 5, 7], interval=2)
          3.5

     此函数不会检查数据点之间是否至少相隔 `interval' 的距离。

     `CPython implementation detail:' 在某些情况下，*note
     median_grouped(): 1c7e. 可以会将数据点强制转换为浮点数。 此行为在未
     来有可能会发生改变。

     也參考
     ......

        * "Statistics for the Behavioral Sciences", Frederick J
          Gravetter and Larry B Wallnau (8th Edition).

        * Gnome Gnumeric 电子表格中的 SSMEDIAN(3) 函数，包括 这篇讨论
          (4)。

 -- 函式: statistics.mode (data)

     从离散或标称的 `data' 返回单个出现最多的数据点。 此众数（如果存在）
     是最典型的值，并可用来度量中心的位置。

     如果存在具有相同频率的多个众数，则返回在 `data' 中遇到的第一个。 如
     果想要其中最小或最大的一个，请使用 ‘min(multimode(data))’ 或
     ‘max(multimode(data))’。 如果输入的 `data' 为空，则会引发 *note
     StatisticsError: 1c85.。

     ‘mode’ 将假定是离散数据并返回一个单一的值。 这是通常的学校教学中标
     准的处理方式：

          >>> mode([1, 1, 2, 3, 3, 3, 3, 4])
          3

     此众数的独特之处在于它是这个包中唯一还可应用于标称（非数字）数据的
     统计信息：

          >>> mode(["red", "blue", "blue", "red", "green", "red", "red"])
          'red'

     3.8 版更變: 现在会通过返回所遇到的第一个众数来处理多模数据集。 之前
     它会在遇到超过一个的众数时引发 *note StatisticsError: 1c85.。

 -- 函式: statistics.multimode (data)

     返回最频繁出现的值的列表，并按它们在 `data' 中首次出现的位置排序。
     如果存在多个众数则将返回一个以上的众数，或者如果 `data' 为空则将返
     回空列表：

          >>> multimode('aabbbbccddddeeffffgg')
          ['b', 'd', 'f']
          >>> multimode('')
          []

     3.8 版新加入.

 -- 函式: statistics.pstdev (data, mu=None)

     返回总体标准差（总体方差的平方根）。 请参阅 *note pvariance():
     1c81. 了解参数和其他细节。

          >>> pstdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
          0.986893273527251

 -- 函式: statistics.pvariance (data, mu=None)

     返回非空序列或包含实数值的可迭代对象 `data' 的总体方差。 方差或称相
     对于均值的二阶距，是对数据变化幅度（延展度或分散度）的度量。 方差值
     较大表明数据的散布范围较大；方差值较小表明它紧密聚集于均值附近。

     如果给出了可选的第二个参数 `mu'，它通常是 `data' 的均值。 它也可以
     被用来计算相对于一个非均值点的二阶距。 如果该参数省略或为 ‘None’ (默
     认值)，则会自动进行算术均值的计算。

     使用此函数可根据所有数值来计算方差。 要根据一个样本来估算方差，通常
     *note variance(): 1c83. 函数是更好的选择。

     如果 `data' 为空则会引发 *note StatisticsError: 1c85.。

     示例：

          >>> data = [0.0, 0.25, 0.25, 1.25, 1.5, 1.75, 2.75, 3.25]
          >>> pvariance(data)
          1.25

     如果你已经计算过数据的平均值，你可以将其作为可选的第二个参数 `mu' 传
     入以避免重复计算：

          >>> mu = mean(data)
          >>> pvariance(data, mu)
          1.25

     同样也支持使用 Decimal 和 Fraction 值：

          >>> 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)

          備註: 当调用时附带完整的总体数据时，这将给出总体方差 σ²。 而当
          调用时只附带一个样本时，这将给出偏置样本方差 s²，也被称为带有
          N 个自由度的方差。

          如果你通过某种方式知道了真实的总体平均值 μ，则可以使用此函数来
          计算一个样本的方差，并将已知的总体平均值作为第二个参数。 假设
          数据点是总体的一个随机样本，则结果将为总体方差的无偏估计值。

 -- 函式: statistics.stdev (data, xbar=None)

     返回样本标准差（样本方差的平方根）。 请参阅 *note variance(): 1c83.
     了解参数和其他细节。

          >>> stdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
          1.0810874155219827

 -- 函式: statistics.variance (data, xbar=None)

     返回包含至少两个实数值的可迭代对象 `data' 的样本方差。 方差或称相对
     于均值的二阶矩，是对数据变化幅度（延展度或分散度）的度量。 方差值较
     大表明数据的散布范围较大；方差值较小表明它紧密聚集于均值附近。

     如果给出了可选的第二个参数 `xbar'，它应当是 `data' 的均值。 如果该
     参数省略或为 ‘None’ (默认值)，则会自动进行均值的计算。

     当你的数据是总体数据的样本时请使用此函数。 要根据整个总体数据来计算
     方差，请参见 *note pvariance(): 1c81.。

     如果 `data' 包含的值少于两个则会引发 *note StatisticsError: 1c85.。

     示例：

          >>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
          >>> variance(data)
          1.3720238095238095

     如果你已经计算过数据的平均值，你可以将其作为可选的第二个参数 `xbar'
     传入以避免重复计算：

          >>> m = mean(data)
          >>> variance(data, m)
          1.3720238095238095

     此函数不会试图检查你所传入的 `xbar' 是否为真实的平均值。 使用任意值
     作为 `xbar' 可能导致无效或不可能的结果。

     同样也支持使用 Decimal 和 Fraction 值：

          >>> 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)

          備註: 这是附带贝塞尔校正的样本方差 s²，也称为具有 N-1 自由度的
          方差。 假设数据点具有代表性（即为独立且均匀的分布），则结果应
          当是对总体方差的无偏估计。

          如果你通过某种方式知道了真实的总体平均值 μ 则应当调用 *note
          pvariance(): 1c81. 函数并将该值作为 `mu' 形参传入以得到一个样
          本的方差。

 -- 函式: statistics.quantiles (data, *, n=4, method='exclusive')

     将 `data' 分隔为具有相等概率的 `n' 个连续区间。 返回分隔这些区间的
     ‘n - 1’ 个分隔点的列表。

     将 `n' 设为 4 以使用四分位（默认值）。 将 `n' 设为 10 以使用十分位
     。 将 `n' 设为 100 以使用百分位，即给出 99 个分隔点来将 `data' 分隔
     为 100 个大小相等的组。 如果 `n' 小于 1 则将引发 *note
     StatisticsError: 1c85.。

     `data' 可以是包含样本数据的任意可迭代对象。 为了获得有意义的结果，
     `data' 中数据点的数量应当大于 `n'。 如果数据点的数量小于两个则将引
     发 *note StatisticsError: 1c85.。

     分隔点是通过对两个最接近的数据点进行线性插值得到的。 例如，如果一个
     分隔点落在两个样本值 ‘100’ 和 ‘112’ 之间距离三分之一的位置，则分隔
     点的取值将为 ‘104’。

     `method' 用于计算分位值，它会由于 `data' 是包含还是排除总体的最低和
     最高可能值而有所不同。

     默认 `method' 是 “唯一的” 并且被用于在总体中数据采样这样可以有比样
     本中找到的更多的极端值。落在 `m' 个排序数据点的第 `i-th' 个以下的总
     体部分被计算为 ‘i / (m + 1)’ 。给定九个样本值，方法排序它们并且分配
     一下的百分位： 10%, 20%, 30%, 40%, 50%, 60%, 70%, 80%, 90% 。

     将 `method' 设为 "inclusive" 可用于描述总体数据或已明确知道包含有总
     体数据中最极端值的样本。 `data' 中的最小值会被作为第 0 个百分位而最
     大值会被作为第 100 个百分位。 总体数据里处于 `m' 个已排序数据点中
     `第 i 个' 以下的部分会以 ‘(i - 1) / (m - 1)’ 来计算。 给定 11 个样
     本值，该方法会对它们进行排序并赋予以下百分位: 0%, 10%, 20%, 30%,
     40%, 50%, 60%, 70%, 80%, 90%, 100%。

          # 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]

     3.8 版新加入.

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Outlier

   (2) https://en.wikipedia.org/wiki/Central_tendency

   (3) 
https://help.gnome.org/users/gnumeric/stable/gnumeric.html#gnumeric-function-SSMEDIAN

   (4) 
https://mail.gnome.org/archives/gnumeric-list/2011-April/msg00018.html


File: python.info,  Node: 异常<3>,  Next: NormalDist 对象,  Prev: 函式細節,  Up: statistics --- 數學統計函式

5.9.7.4 异常
............

只定义了一个异常：

 -- 例外: statistics.StatisticsError

     *note ValueError: 16d. 的子类，表示统计相关的异常。


File: python.info,  Node: NormalDist 对象,  Prev: 异常<3>,  Up: statistics --- 數學統計函式

5.9.7.5 ‘NormalDist’ 对象
.........................

*note NormalDist: 358. 工具可用于创建和操纵 随机变量(1) 的正态分布。 这
个类将数据度量值的平均值和标准差作为单一实体来处理。

正态分布的概念来自于 中央极限定理(2) 并且在统计学中有广泛的应用。

 -- 類別: statistics.NormalDist (mu=0.0, sigma=1.0)

     返回一个新的 `NormalDist' 对象，其中 `mu' 代表 算术平均值(3) 而
     `sigma' 代表 标准差(4)。

     若 `sigma' 为负数，将会引发 *note StatisticsError: 1c85.。

      -- 屬性: mean

          一个只读特征属性，表示特定正态分布的 算术平均值(5)。

      -- 屬性: median

          一个只读特征属性，表示特定正态分布的 中位数(6)。

      -- 屬性: mode

          一个只读特征属性，表示特定正态分布的 众数(7)。

      -- 屬性: stdev

          一个只读特征属性，表示特定正态分布的 标准差(8)。

      -- 屬性: variance

          一个只读特征属性，表示特定正态分布的 方差(9)。 等于标准差的平
          方。

      -- 成員函式: classmethod from_samples (data)

          传入使用 *note fmean(): 354. 和 *note stdev(): 1c82. 基于
          `data' 估算出的 `mu' 和 `sigma' 形参创建一个正态分布实例。

          `data' 可以是任何 *note iterable: c7c. 并且应当包含能被转换为
          *note float: 1fd. 类型的值。 如果 `data' 不包含至少两个元素，
          则会引发 *note StatisticsError: 1c85.，因为估算中心值至少需要
          一个点而估算分散度至少需要两个点。

      -- 成員函式: samples (n, *, seed=None)

          对于给定的平均值和标准差生成 `n' 个随机样本。 返回一个由 *note
          float: 1fd. 值组成的 *note list: 1f8.。

          当给定 `seed' 时，创建一个新的底层随机数生成器实例。 这适用于
          创建可重现的结果，即使对于多线程上下文也有效。

      -- 成員函式: pdf (x)

          使用 概率密度函数 (pdf)(10)，计算一个随机变量 `X' 趋向于给定值
          `x' 的相对可能性。 在数学意义上，它是当 `dx' 趋向于零时比率
          ‘P(x <= X < x+dx) / dx’ 的极限。

          相对可能性的计算方法是用一个狭窄区间内某个样本出现的概率除以区
          间的宽度（因此使用“密度”一词）。 由于可能性是相对于其他点的，
          它的值可以大于 ‘1.0’。

      -- 成員函式: cdf (x)

          使用 累积分布函数 (cdf)(11)，计算一个随机变量 `X' 小于等于 `x'
          的概率。 在数学上，它表示为 ‘P(X <= x)’。

      -- 成員函式: inv_cdf (p)

          计算反向累积分布函数，也称为 分位数函数(12) 或 百分点(13) 函数
          。 在数学上，它表示为 ‘x : P(X <= x) = p’。

          找出随机变量 `X' 的值 `x' 使得该变量小于等于该值的概率等于给定
          的概率 `p'。

      -- 成員函式: overlap (other)

          测量两个正态概率分布之间的一致性。 返回介于 0.0 和 1.0 之间的
          值，给出 两个概率密度函数的重叠区域(14)。

      -- 成員函式: quantiles (n=4)

          将指定正态分布划分为 `n' 个相等概率的连续分隔区。 返回这些分隔
          区对应的 (n - 1) 个分隔点的列表。

          将 `n' 设为 4 以使用四分位（默认值）。 将 `n' 设为 10 以使用十
          分位。将 `n' 设为 100 以使用百分位，即给出 99 个分隔点来将正态
          分布分隔为 100 个大小相等的组。

      -- 成員函式: zscore (x)

          计算 标准分(15) 即以高于或低于正态分布的平均值的标准差数值的形
          式来描述 `x': ‘(x - mean) / stdev’.

          3.9 版新加入.

     *note NormalDist: 358. 的实例支持加上、减去、乘以或除以一个常量。 这
     些运算被用于转换和缩放。 例如：

          >>> temperature_february = NormalDist(5, 2.5)             # Celsius
          >>> temperature_february * (9/5) + 32                     # Fahrenheit
          NormalDist(mu=41.0, sigma=4.5)

     不允许一个常量除以 *note NormalDist: 358. 的实例，因为结果将不是正
     态分布。

     由于正态分布是由独立变量的累加效应产生的，因此允许表示为 *note
     NormalDist: 358. 实例的 两组独立正态分布的随机变量相加和相减(16)。
     例如：

          >>> 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

     3.8 版新加入.

* Menu:

* NormalDist 示例和用法::

   ---------- Footnotes ----------

   (1) http://www.stat.yale.edu/Courses/1997-98/101/ranvar.htm

   (2) https://en.wikipedia.org/wiki/Central_limit_theorem

   (3) https://en.wikipedia.org/wiki/Arithmetic_mean

   (4) https://en.wikipedia.org/wiki/Standard_deviation

   (5) https://en.wikipedia.org/wiki/Arithmetic_mean

   (6) https://en.wikipedia.org/wiki/Median

   (7) https://en.wikipedia.org/wiki/Mode_(statistics)

   (8) https://en.wikipedia.org/wiki/Standard_deviation

   (9) https://en.wikipedia.org/wiki/Variance

   (10) https://en.wikipedia.org/wiki/Probability_density_function

   (11) https://en.wikipedia.org/wiki/Cumulative_distribution_function

   (12) https://en.wikipedia.org/wiki/Quantile_function

   (13) 
https://www.statisticshowto.datasciencecentral.com/inverse-distribution-function/

   (14) https://www.rasch.org/rmt/rmt101r.htm

   (15) 
https://www.statisticshowto.com/probability-and-statistics/z-score/

   (16) 
https://en.wikipedia.org/wiki/Sum_of_normally_distributed_random_variables


File: python.info,  Node: NormalDist 示例和用法,  Up: NormalDist 对象

5.9.7.6 ‘NormalDist’ 示例和用法
...............................

*note NormalDist: 358. 适合用来解决经典概率问题。

举例来说，如果 SAT 考试的历史数据(1) 显示分数呈平均值为 1060 且标准差为
195 的正态分布，则可以确定考试分数处于 1100 和 1200 之间的学生的百分比舍
入到最接近的整数应为：

     >>> sat = NormalDist(1060, 195)
     >>> fraction = sat.cdf(1200 + 0.5) - sat.cdf(1100 - 0.5)
     >>> round(fraction * 100.0, 1)
     18.4

求 SAT 分数的 四分位(2) 和 十分位(3)：

     >>> list(map(round, sat.quantiles()))
     [928, 1060, 1192]
     >>> list(map(round, sat.quantiles(n=10)))
     [810, 896, 958, 1011, 1060, 1109, 1162, 1224, 1310]

为了估算一个不易解析的模型分布，*note NormalDist: 358. 可以生成用于 蒙特
卡洛模拟(4) 的输入样本：

     >>> 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]

当样本量较大并且成功试验的可能性接近 50% 时，正态分布可以被用来模拟 二项
分布(5)。

例如，一次开源会议有 750 名与会者和两个可分别容纳 500 人的会议厅。 会上
有一场关于 Python 的演讲和一场关于 Ruby 的演讲。 在往届会议中，65% 的与
会者更愿意去听关于 Python 的演讲。 假定人群的偏好没有发生改变，那么
Python 演讲的会议厅不超出其容量上限的可能性是多少？

     >>> 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

在机器学习问题中也经常会出现正态分布。

Wikipedia 上有一个 朴素贝叶斯分类器的好例子(6)。 挑战的问题是根据对多个
正态分布的特征测量值包括身高、体重和足部尺码来预测一个人的性别。

我们得到了由八个人的测量值组成的训练数据集。 假定这些测量值是正态分布的
，因此我们用 *note NormalDist: 358. 来总结数据：

     >>> 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])

接下来，我们遇到一个特征测量值已知但性别未知的新人：

     >>> ht = 6.0        # height
     >>> wt = 130        # weight
     >>> fs = 8          # foot size

从是男是女各 50% 的 先验概率(7) 出发，我们通过将该先验概率乘以给定性别的
特征度量值的可能性累积值来计算后验概率：

     >>> 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))

最终预测值应为最大后验概率值。 这种算法被称为 maximum a posteriori(8) 或
MAP：

     >>> 'male' if posterior_male > posterior_female else 'female'
     'female'

   ---------- Footnotes ----------

   (1) https://nces.ed.gov/programs/digest/d17/tables/dt17_226.40.asp

   (2) https://en.wikipedia.org/wiki/Quartile

   (3) https://en.wikipedia.org/wiki/Decile

   (4) https://en.wikipedia.org/wiki/Monte_Carlo_method

   (5) http://mathworld.wolfram.com/BinomialDistribution.html

   (6) 
https://en.wikipedia.org/wiki/Naive_Bayes_classifier#Sex_classification

   (7) https://en.wikipedia.org/wiki/Prior_probability

   (8) https://en.wikipedia.org/wiki/Maximum_a_posteriori_estimation


File: python.info,  Node: 函式編程模組,  Next: 檔案與目錄存取,  Prev: 數值與數學模組,  Up: Python 標準函式庫 Standard Library

5.10 函式編程模組
=================

本章里描述的模块提供了函数和类，以支持函数式编程风格和在可调用对象上的通
用操作。

本章对下列模块进行说明：

* Menu:

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


File: python.info,  Node: itertools --- 为高效循环而创建迭代器的函数,  Next: functools --- 高阶函数和可调用对象上的操作,  Up: 函式編程模組

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

__________________________________________________________________

本模块实现一系列 *note iterator: 1171. ，这些迭代器受到APL，Haskell和
SML的启发。为了适用于Python，它们都被重新写过。

本模块标准化了一个快速、高效利用内存的核心工具集，这些工具本身或组合都很
有用。它们一起形成了“迭代器代数”，这使得在纯Python中有可能创建简洁又高效
的专用工具。

例如，SML有一个制表工具： ‘tabulate(f)’，它可产生一个序列 ‘f(0), f(1),
...’。在Python中可以组合 *note map(): cf7. 和 *note count(): ce5. 实现：
‘map(f, count())’。

这些内置工具同时也能很好地与 *note operator: c2. 模块中的高效函数配合使
用。例如，我们可以将两个向量的点积映射到乘法运算符：
‘sum(map(operator.mul, vector1, vector2))’ 。

`无穷迭代器：'

迭代器                 实参                  结果                                                  示例
                                                                                                   
-------------------------------------------------------------------------------------------------------------------------------------------------
                                                                                                   
*note count(): ce5.    start, [step]         start, start+step, start+2*step, ...                  ‘count(10) --> 10 11 12 13 14 ...’
                                                                                                   
                                                                                                   
*note cycle(): 1c9a.   p                     p0, p1, ...  plast, p0, p1, ...                       ‘cycle('ABCD') --> A B C D A B C D ...’
                                                                                                   
                                                                                                   
*note repeat(): 11e7.  elem [,n]             elem, elem, elem, ... 重复无限次或n次                 ‘repeat(10, 3) --> 10 10 10’
                                                                                                   

`根据最短输入序列长度停止的迭代器：'

迭代器                           实参                             结果                                                  示例
                                                                                                                        
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
                                                                                                                        
*note accumulate(): 30e.         p [,func]                        p0, p0+p1, p0+p1+p2, ...                              ‘accumulate([1,2,3,4,5]) --> 1 3 6 10 15’
                                                                                                                        
                                                                                                                        
*note chain(): 1738.             p, q, ...                        p0, p1, ...  plast, q0, q1, ...                       ‘chain('ABC', 'DEF') --> A B C D E F’
                                                                                                                        
                                                                                                                        
*note chain.from_iterable(): 1c9b.iterable                        p0, p1, ...  plast, q0, q1, ...                       ‘chain.from_iterable(['ABC', 'DEF']) --> A B C D E F’
                                                                                                                        
                                                                                                                        
*note compress(): ce4.           data, selectors                  (d[0] if s[0]), (d[1] if s[1]), ...                   ‘compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F’
                                                                                                                        
                                                                                                                        
*note dropwhile(): 1c9c.         pred, seq                        seq[n], seq[n+1], ... 从pred首次真值测试失败开始      ‘dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1’
                                                                                                                        
                                                                                                                        
*note filterfalse(): 1722.       pred, seq                        seq中pred(x)为假值的元素，x是seq中的元素。            ‘filterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8’
                                                                                                                        
                                                                                                                        
*note groupby(): 1c9d.           iterable[, key]                  根据key(v)值分组的迭代器
                                                                  
                                                                                                                        
*note islice(): 4a8.             seq, [start,] stop [, step]      seq[start:stop:step]中的元素                          ‘islice('ABCDEFG', 2, None) --> C D E F G’
                                                                                                                        
                                                                                                                        
*note starmap(): b05.            func, seq                        func(*seq[0]), func(*seq[1]), ...                     ‘starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000’
                                                                                                                        
                                                                                                                        
*note takewhile(): 1c9e.         pred, seq                        seq[0], seq[1], ..., 直到pred真值测试失败             ‘takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4’
                                                                                                                        
                                                                                                                        
*note tee(): 1c9f.               it, n                            it1, it2, ...  itn 将一个迭代器拆分为n个迭代器
                                                                  
                                                                                                                        
*note zip_longest(): cfb.        p, q, ...                        (p[0], q[0]), (p[1], q[1]), ...                       ‘zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-’
                                                                                                                        

`排列组合迭代器：'

迭代器                                             实参                     结果
                                                                            
----------------------------------------------------------------------------------------------------------------------------------------------
                                                                            
*note product(): d6f.                              p, q, ...  [repeat=1]    笛卡尔积，相当于嵌套的for循环
                                                                            
                                                                            
*note permutations(): fc9.                         p[, r]                   长度r元组，所有可能的排列，无重复元素
                                                                            
                                                                            
*note combinations(): d6e.                         p, r                     长度r元组，有序，无重复元素
                                                                            
                                                                            
*note combinations_with_replacement(): ce3.        p, r                     长度r元组，有序，元素可重复
                                                                            

例子                                               结果
                                                   
---------------------------------------------------------------------------------------------------------------------
                                                   
‘product('ABCD', repeat=2)’                        ‘AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD’
                                                   
                                                   
‘permutations('ABCD', 2)’                          ‘AB AC AD BA BC BD CA CB CD DA DB DC’
                                                   
                                                   
‘combinations('ABCD', 2)’                          ‘AB AC AD BC BD CD’
                                                   
                                                   
‘combinations_with_replacement('ABCD', 2)’         ‘AA AB AC AD BB BC BD CC CD DD’
                                                   

* Menu:

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


File: python.info,  Node: Itertool函数,  Next: itertools 配方,  Up: itertools --- 为高效循环而创建迭代器的函数

5.10.1.1 Itertool函数
.....................

下列模块函数均创建并返回迭代器。有些迭代器不限制输出流长度，所以它们只应
在能截断输出流的函数或循环中使用。

 -- 函式: itertools.accumulate (iterable[, func, *, initial=None])

     创建一个迭代器，返回累积汇总值或其他双目运算函数的累积结果值（通过
     可选的 `func' 参数指定）。

     如果提供了 `func'，它应当为带有两个参数的函数。 输入 `iterable' 的
     元素可以是能被 `func' 接受为参数的任意类型。 （例如，对于默认的加法
     运算，元素可以是任何可相加的类型包括 *note Decimal: 2c0. 或 *note
     Fraction: 2be.。）

     通常，输出的元素数量与输入的可迭代对象是一致的。 但是，如果提供了关
     键字参数 `initial'，则累加会以 `initial' 值开始，这样输出就比输入的
     可迭代对象多一个元素。

     大致相当于：

          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

     `func' 参数有几种用法。它可以被设为 *note min(): 8f6. 最终得到一个
     最小值，或者设为 *note max(): 8f7. 最终得到一个最大值，或设为 *note
     operator.mul(): 1ca2. 最终得到一个乘积。摊销表可通过累加利息和支付
     款项得到。给iterable设置初始值并只将参数 `func' 设为累加总数可以对
     一阶 递归关系(1) 建模。

          >>> 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']

     参考一个类似函数 *note functools.reduce(): d37. ，它只返回一个最终
     累积值。

     3.2 版新加入.

     3.3 版更變: 增加可选参数 `func' 。

     3.8 版更變: 添加了可选的 `initial' 形参。

 -- 函式: itertools.chain (*iterables)

     创建一个迭代器，它首先返回第一个可迭代对象中所有元素，接着返回下一
     个可迭代对象中所有元素，直到耗尽所有可迭代对象中的元素。可将多个序
     列处理为单个序列。大致相当于：

          def chain(*iterables):
              # chain('ABC', 'DEF') --> A B C D E F
              for it in iterables:
                  for element in it:
                      yield element

 -- 成員函式: classmethod chain.from_iterable (iterable)

     构建类似 *note chain(): 1738. 迭代器的另一个选择。从一个单独的可迭
     代参数中得到链式输入，该参数是延迟计算的。大致相当于：

          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

 -- 函式: itertools.combinations (iterable, r)

     返回由输入 `iterable' 中元素组成长度为 `r' 的子序列。

     组合元组会以字典顺序根据所输入 `iterable' 的顺序发出。 因此，如果所
     输入 `iterable' 是已排序的，组合元组也将按已排序的顺序生成。

     即使元素的值相同，不同位置的元素也被认为是不同的。如果元素各自不同
     ，那么每个组合中没有重复元素。

     大致相当于：

          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)

     *note combinations(): d6e. 的代码可被改写为 *note permutations():
     fc9. 过滤后的子序列，（相对于元素在输入中的位置）元素不是有序的。

          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)

     当 ‘0 <= r <= n’ 时，返回项的个数是 ‘n! / r! / (n-r)!’；当 ‘r > n’
     时，返回项个数为0。

 -- 函式: itertools.combinations_with_replacement (iterable, r)

     返回由输入 `iterable' 中元素组成的长度为 `r' 的子序列，允许每个元素
     可重复出现。

     组合元组会以字典顺序根据所输入 `iterable' 的顺序发出。 因此，如果所
     输入 `iterable' 是已排序的，组合元组也将按已排序的顺序生成。

     不同位置的元素是不同的，即使它们的值相同。因此如果输入中的元素都是
     不同的话，返回的组合中元素也都会不同。

     大致相当于：

          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)

     *note combinations_with_replacement(): ce3. 的代码可被改写为
     ‘production()’ 过滤后的子序列，（相对于元素在输入中的位置）元素不是
     有序的。

          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)

     当 ‘n > 0’ 时，返回项个数为 ‘(n+r-1)! / r! / (n-1)!’.

     3.1 版新加入.

 -- 函式: itertools.compress (data, selectors)

     创建一个迭代器，它返回 `data' 中经 `selectors' 真值测试为 ‘True’ 的
     元素。迭代器在两者较短的长度处停止。大致相当于：

          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)

     3.1 版新加入.

 -- 函式: itertools.count (start=0, step=1)

     创建一个迭代器，它从 `start' 值开始，返回均匀间隔的值。常用于 *note
     map(): cf7. 中的实参来生成连续的数据点。此外，还用于 *note zip():
     cfc. 来添加序列号。大致相当于：

          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

     当对浮点数计数时，替换为乘法代码有时精度会更好，例如： ‘(start +
     step * i for i in count())’ 。

     3.1 版更變: 增加参数 `step' ，允许非整型。

 -- 函式: itertools.cycle (iterable)

     创建一个迭代器，返回 `iterable' 中所有元素并保存一个副本。当取完
     `iterable' 中所有元素，返回副本中的所有元素。无限重复。大致相当于：

          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

     注意，该函数可能需要相当大的辅助空间（取决于 `iterable' 的长度）。

 -- 函式: itertools.dropwhile (predicate, iterable)

     创建一个迭代器，如果 `predicate' 为true，迭代器丢弃这些元素，然后返
     回其他元素。注意，迭代器在 `predicate' 首次为false之前不会产生任何
     输出，所以可能需要一定长度的启动时间。大致相当于：

          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

 -- 函式: itertools.filterfalse (predicate, iterable)

     创建一个迭代器，只返回 `iterable' 中 `predicate' 为 ‘False’ 的元素
     。如果 `predicate' 是 ‘None’，返回真值测试为false的元素。大致相当于
     ：

          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

 -- 函式: itertools.groupby (iterable, key=None)

     创建一个迭代器，返回 `iterable' 中连续的键和组。`key' 是一个计算元
     素键值函数。如果未指定或为 ‘None’，`key' 缺省为恒等函数（identity
     function），返回元素不变。一般来说，`iterable' 需用同一个键值函数预
     先排序。

     *note groupby(): 1c9d. 操作类似于Unix中的 ‘uniq’。当每次 `key' 函数
     产生的键值改变时，迭代器会分组或生成一个新组（这就是为什么通常需要
     使用同一个键值函数先对数据进行排序）。这种行为与SQL的GROUP BY操作不
     同，SQL的操作会忽略输入的顺序将相同键值的元素分在同组中。

     返回的组本身也是一个迭代器，它与 *note groupby(): 1c9d. 共享底层的
     可迭代对象。因为源是共享的，当 *note groupby(): 1c9d. 对象向后迭代
     时，前一个组将消失。因此如果稍后还需要返回结果，可保存为列表：

          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)

     *note groupby(): 1c9d. 大致相当于：

          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)

 -- 函式: itertools.islice (iterable, stop)

 -- 函式: itertools.islice (iterable, start, stop[, step])

     创建一个迭代器，返回从 `iterable' 里选中的元素。如果 `start' 不是
     0，跳过 `iterable' 中的元素，直到到达 `start' 这个位置。之后迭代器
     连续返回元素，除非 `step' 设置的值很高导致被跳过。如果 `stop' 为
     ‘None’，迭代器耗光为止；否则，在指定的位置停止。与普通的切片不同，
     *note islice(): 4a8. 不支持将 `start' ， `stop' ，或 `step' 设为负
     值。可用来从内部数据结构被压平的数据中提取相关字段（例如一个多行报
     告，它的名称字段出现在每三行上）。大致相当于：

          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

     如果 `start' 为 ‘None’，迭代从0开始。如果 `step' 为 ‘None’ ，步长缺
     省为1。

 -- 函式: itertools.permutations (iterable, r=None)

     连续返回由 `iterable' 元素生成长度为 `r' 的排列。

     如果 `r' 未指定或为 ‘None’ ，`r' 默认设置为 `iterable' 的长度，这种
     情况下，生成所有全长排列。

     排列元组会以字典顺序根据所输入 `iterable' 的顺序发出。 因此，如果所
     输入 `iterable' 是已排序的，组合元组也将按已排序的顺序生成。

     即使元素的值相同，不同位置的元素也被认为是不同的。如果元素值都不同
     ，每个排列中的元素值不会重复。

     大致相当于：

          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

     *note permutations(): fc9. 的代码也可被改写为 *note product(): d6f.
     的子序列，只要将含有重复元素（来自输入中同一位置的）的项排除。

          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)

     当 ‘0 <= r <= n’ ，返回项个数为 ‘n! / (n-r)!’ ；当 ‘r > n’ ，返回项
     个数为0。

 -- 函式: itertools.product (*iterables, repeat=1)

     可迭代对象输入的笛卡儿积。

     大致相当于生成器表达式中的嵌套循环。例如， ‘product(A, B)’ 和
     ‘((x,y) for x in A for y in B)’ 返回结果一样。

     嵌套循环像里程表那样循环变动，每次迭代时将最右侧的元素向后迭代。这
     种模式形成了一种字典序，因此如果输入的可迭代对象是已排序的，笛卡尔
     积元组依次序发出。

     要计算可迭代对象自身的笛卡尔积，将可选参数 `repeat' 设定为要重复的
     次数。例如，‘product(A, repeat=4)’ 和 ‘product(A, A, A, A)’ 是一样
     的。

     该函数大致相当于下面的代码，只不过实际实现方案不会在内存中创建中间
     结果。

          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)

     在 *note product(): d6f. 运行之前，它会完全耗尽输入的可迭代对象，在
     内存中保留值的临时池以生成结果积。 相应地，它只适用于有限的输入。

 -- 函式: itertools.repeat (object[, times])

     创建一个迭代器，不断重复 `object' 。除非设定参数 `times' ，否则将无
     限重复。可用于 *note map(): cf7. 函数中的参数，被调用函数可得到一个
     不变参数。也可用于 *note zip(): cfc. 的参数以在元组记录中创建一个不
     变的部分。

     大致相当于：

          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

     `repeat' 最常见的用途就是在 `map' 或 `zip' 提供一个常量流：

          >>> list(map(pow, range(10), repeat(2)))
          [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

 -- 函式: itertools.starmap (function, iterable)

     创建一个迭代器，使用从可迭代对象中获取的参数来计算该函数。当参数对
     应的形参已从一个单独可迭代对象组合为元组时（数据已被“预组对”）可用
     此函数代替 *note map(): cf7.。*note map(): cf7. 与 *note starmap():
     b05. 之间的区别可以类比 ‘function(a,b)’ 与 ‘function(*c)’ 的区别。
     大致相当于:

          def starmap(function, iterable):
              # starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000
              for args in iterable:
                  yield function(*args)

 -- 函式: itertools.takewhile (predicate, iterable)

     创建一个迭代器，只要 predicate 为真就从可迭代对象中返回元素。大致相
     当于:

          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

 -- 函式: itertools.tee (iterable, n=2)

     从一个可迭代对象中返回 `n' 个独立的迭代器。

     下面的Python代码能帮助解释 `tee' 做了什么（尽管实际的实现更复杂，而
     且仅使用了一个底层的 FIFO 队列）。

     大致相当于：

          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)

     一旦 *note tee(): 1c9f. 实施了一次分裂，原有的 `iterable' 不应再被
     使用；否则tee对象无法得知 `iterable' 可能已向后迭代。

     ‘tee’ 迭代器不是线程安全的。当同时使用由同一个 *note tee(): 1c9f. 调
     用所返回的迭代器时可能引发 *note RuntimeError: 3dc.，即使原本的
     `iterable' 是线程安全的。

     该迭代工具可能需要相当大的辅助存储空间（这取决于要保存多少临时数据
     ）。通常，如果一个迭代器在另一个迭代器开始之前就要使用大部份或全部
     数据，使用 *note list(): 1f8. 会比 *note tee(): 1c9f. 更快。

 -- 函式: itertools.zip_longest (*iterables, fillvalue=None)

     创建一个迭代器，从每个可迭代对象中收集元素。如果可迭代对象的长度未
     对齐，将根据 `fillvalue' 填充缺失值。迭代持续到耗光最长的可迭代对象
     。大致相当于：

          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)

     如果其中一个可迭代对象有无限长度，*note zip_longest(): cfb. 函数应
     封装在限制调用次数的场景中（例如 *note islice(): 4a8. 或 *note
     takewhile(): 1c9e.）。除非指定， `fillvalue' 默认为 ‘None’ 。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Recurrence_relation


File: python.info,  Node: itertools 配方,  Prev: Itertool函数,  Up: itertools --- 为高效循环而创建迭代器的函数

5.10.1.2 itertools 配方
.......................

本节将展示如何使用现有的 itertools 作为基础构件来创建扩展的工具集。

基本上所有这些西方和许许多多其他的配方都可以通过 Python Package Index 上
的 more-itertools 项目(1) 来安装:

     pip install more-itertools

扩展的工具提供了与底层工具集相同的高性能。保持了超棒的内存利用率，因为一
次只处理一个元素，而不是将整个可迭代对象加载到内存。代码量保持得很小，以
函数式风格将这些工具连接在一起，有助于消除临时变量。速度依然很快，因为倾
向于使用“矢量化”构件来取代解释器开销大的 for 循环和 *note generator:
a83. 。

     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)

   ---------- Footnotes ----------

   (1) https://pypi.org/project/more-itertools/


File: python.info,  Node: functools --- 高阶函数和可调用对象上的操作,  Next: operator --- 标准运算符替代函数,  Prev: itertools --- 为高效循环而创建迭代器的函数,  Up: 函式編程模組

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

`源代码:' Lib/functools.py(1)

__________________________________________________________________

*note functools: 83. 模块应用于高阶函数，即参数或（和）返回值为其他函数
的函数。 通常来说，此模块的功能适用于所有可调用对象。

*note functools: 83. 模块定义了以下函数:

 -- 函式: @functools.cache (user_function)

     简单轻量级未绑定函数缓存。 有时称为 "memoize"(2)。

     返回值与 ‘lru_cache(maxsize=None)’ 相同，创建一个查找函数参数的字典
     的简单包装器。 因为它不需要移出旧值，所以比带有大小限制的 *note
     lru_cache(): 2f8. 更小更快。

     例如:

          @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

     3.9 版新加入.

 -- 函式: @functools.cached_property (func)

     将一个类方法转换为特征属性，一次性计算该特征属性的值，然后将其缓存
     为实例生命周期内的普通属性。 类似于 *note property(): 308. 但增加了
     缓存功能。 对于在其他情况下实际不可变的高计算资源消耗的实例特征属性
     来说该函数非常有用。

     示例:

          class DataSet:

              def __init__(self, sequence_of_numbers):
                  self._data = tuple(sequence_of_numbers)

              @cached_property
              def stdev(self):
                  return statistics.stdev(self._data)

     *note cached_property(): 2f9. 的设定与 *note property(): 308. 有所
     不同。 常规的 property 会阻止属性写入，除非定义了 setter。 与之相反
     ，`cached_property' 则允许写入。

     `cached_property' 装饰器仅在执行查找且不存在同名属性时才会运行。 当
     运行时，`cached_property' 会写入同名的属性。 后续的属性读取和写入操
     作会优先于 `cached_property' 方法，其行为就像普通的属性一样。

     缓存的值可通过删除该属性来清空。 这允许 `cached_property' 方法再次
     运行。

     注意，这个装饰器会影响 PEP 412(3) 键共享字典的操作。 这意味着相应的
     字典实例可能占用比通常时更多的空间。

     而且，这个装饰器要求每个实例上的 ‘__dict__’ 是可变的映射。 这意味着
     它将不适用于某些类型，例如元类（因为类型实例上的 ‘__dict__’ 属性是
     类命名空间的只读代理），以及那些指定了 ‘__slots__’ 但未包括
     ‘__dict__’ 作为所定义的空位之一的类（因为这样的类根本没有提供
     ‘__dict__’ 属性）。

     如果可变的映射不可用或者如果想要节省空间的键共享，可以通过在 *note
     cache(): 1ca6. 之上堆叠一个 *note property(): 308. 来实现类似 *note
     cached_property(): 2f9. 的效果:

          class DataSet:
              def __init__(self, sequence_of_numbers):
                  self._data = sequence_of_numbers

              @property
              @cache
              def stdev(self):
                  return statistics.stdev(self._data)

     3.8 版新加入.

 -- 函式: functools.cmp_to_key (func)

     将(旧式的)比较函数转换为新式的 *note key function: 7d2. .  在类似于
     *note sorted(): 546. ， *note min(): 8f6. ， *note max(): 8f7. ，
     *note heapq.nlargest(): 1ab2. ， *note heapq.nsmallest(): 1ab3. ，
     *note itertools.groupby(): 1c9d. 等函数的 ‘key’ 参数中使用。此函数
     主要用作将 Python 2 程序转换至新版的转换工具，以保持对比较函数的兼
     容。

     比较函数意为一个可调用对象，该对象接受两个参数并比较它们，结果为小
     于则返回一个负数，相等则返回零，大于则返回一个正数。key function则
     是一个接受一个参数，并返回另一个用以排序的值的可调用对象。

     示例:

          sorted(iterable, key=cmp_to_key(locale.strcoll))  # locale-aware sort order

     有关排序示例和简要排序教程，请参阅 *note 如何排序: 1737. 。

     3.2 版新加入.

 -- 函式: @functools.lru_cache (user_function)

 -- 函式: @functools.lru_cache (maxsize=128, typed=False)

     一个为函数提供缓存功能的装饰器，缓存 `maxsize' 组传入参数，在下次以
     相同参数调用时直接返回上一次的结果。用以节约高开销或I/O函数的调用时
     间。

     由于使用了字典存储缓存，所以该函数的固定参数和关键字参数必须是可哈
     希的。

     不同模式的参数可能被视为不同从而产生多个缓存项，例如, ‘f(a=1, b=2)’
     和 ‘f(b=2, a=1)’ 因其参数顺序不同，可能会被缓存两次。

     如果指定了 `user_function'，它必须是一个可调用对象。 这允许
     `lru_cache' 装饰器被直接应用于一个用户自定义函数，让 `maxsize' 保持
     其默认值 128:

          @lru_cache
          def count_vowels(sentence):
              sentence = sentence.casefold()
              return sum(sentence.count(vowel) for vowel in 'aeiou')

     如果 `maxsize' 设为 ‘None’，LRU 特性将被禁用且缓存可无限增长。

     如果 `typed' 设置为true，不同类型的函数参数将被分别缓存。例如，
     ‘f(3)’ 和 ‘f(3.0)’ 将被视为不同而分别缓存。

     被包装的函数配有一个 ‘cache_parameters()’ 函数，该函数返回一个新的
     *note dict: 164. 用来显示 `maxsize' 和 `typed' 的值。 这只是出于显
     示信息的目的。 改变值没有任何效果。

     为了衡量缓存的有效性以便调整 `maxsize' 形参，被装饰的函数带有一个
     ‘cache_info()’ 函数。当调用 ‘cache_info()’ 函数时，返回一个具名元组
     ，包含命中次数 `hits'，未命中次数 `misses' ，最大缓存数量 `maxsize'
     和 当前缓存大小 `currsize'。在多线程环境中，命中数与未命中数是不完
     全准确的。

     该装饰器也提供了一个用于清理/使缓存失效的函数 ‘cache_clear()’ 。

     原始的未经装饰的函数可以通过 ‘__wrapped__’ 属性访问。它可以用于检查
     、绕过缓存，或使用不同的缓存再次装饰原始函数。

     LRU（最久未使用算法）缓存(4) 在最近的调用是即将到来的调用的最佳预测
     值时性能最好（例如，新闻服务器上最热门文章倾向于每天更改）。 缓存的
     大小限制可确保缓存不会在长期运行进程如网站服务器上无限制地增长。

     一般来说，LRU缓存只在当你想要重用之前计算的结果时使用。因此，用它缓
     存具有副作用的函数、需要在每次调用时创建不同、易变的对象的函数或者
     诸如time（）或random（）之类的不纯函数是没有意义的。

     静态 Web 内容的 LRU 缓存示例:

          @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)

     以下是使用缓存通过 动态规划(5) 计算 斐波那契数列(6) 的例子。

          @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)

     3.2 版新加入.

     3.3 版更變: 添加 `typed' 选项。

     3.8 版更變: 添加了 `user_function' 选项。

     3.9 版新加入: 新增函数 ‘cache_parameters()’

 -- 函式: @functools.total_ordering

     给定一个声明一个或多个全比较排序方法的类，这个类装饰器实现剩余的方
     法。这减轻了指定所有可能的全比较操作的工作。

     此类必须包含以下方法之一：*note __lt__(): cfe. 、*note __le__():
     d68.、*note __gt__(): d69. 或 *note __ge__(): d6a.。另外，此类必须
     支持 *note __eq__(): 44b. 方法。

     例如:

          @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()))

          備註: 虽然此装饰器使得创建具有良好行为的完全有序类型变得非常容
          易，但它 `确实' 是以执行速度更缓慢和派生比较方法的堆栈回溯更复
          杂为代价的。 如果性能基准测试表明这是特定应用的瓶颈所在，则改
          为实现全部六个富比较方法应该会轻松提升速度。

     3.2 版新加入.

     3.4 版更變: 现在已支持从未识别类型的下层比较函数返回 NotImplemented
     异常。

 -- 函式: functools.partial (func, /, *args, **keywords)

     返回一个新的 *note 部分对象: 1ca7.，当被调用时其行为类似于 `func' 附
     带位置参数 `args' 和关键字参数 `keywords' 被调用。 如果为调用提供了
     更多的参数，它们会被附加到 `args'。 如果提供了额外的关键字参数，它
     们会扩展并重载 `keywords'。 大致等价于:

          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

     *note partial(): 8b5. 会被“冻结了”一部分函数参数和/或关键字的部分函
     数应用所使用，从而得到一个具有简化签名的新对象。 例如，*note
     partial(): 8b5. 可用来创建一个行为类似于 *note int(): 204. 函数的可
     调用对象，其中 `base' 参数默认为二：

          >>> from functools import partial
          >>> basetwo = partial(int, base=2)
          >>> basetwo.__doc__ = 'Convert base 2 string to an int.'
          >>> basetwo('10010')
          18

 -- 類別: functools.partialmethod (func, /, *args, **keywords)

     返回一个新的 *note partialmethod: 3bf. 描述器，其行为类似 *note
     partial: 8b5. 但它被设计用作方法定义而非直接用作可调用对象。

     `func' 必须是一个 *note descriptor: 1579. 或可调用对象（同属两者的
     对象例如普通函数会被当作描述器来处理）。

     当 `func' 是一个描述器（例如普通 Python 函数, *note classmethod():
     309, *note staticmethod(): 30a, ‘abstractmethod()’ 或其他 *note
     partialmethod: 3bf. 的实例）时, 对 ‘__get__’ 的调用会被委托给底层的
     描述器，并会返回一个适当的 *note 部分对象: 1ca7. 作为结果。

     当 `func' 是一个非描述器类可调用对象时，则会动态创建一个适当的绑定
     方法。 当用作方法时其行为类似普通 Python 函数：将会插入 `self' 参数
     作为第一个位置参数，其位置甚至会处于提供给 *note partialmethod:
     3bf. 构造器的 `args' 和 `keywords' 之前。

     示例:

          >>> 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

     3.4 版新加入.

 -- 函式: functools.reduce (function, iterable[, initializer])

     将两个参数的 `function' 从左至右积累地应用到 `iterable' 的条目，以
     便将该可迭代对象缩减为单一的值。 例如，‘reduce(lambda x, y: x+y,
     [1, 2, 3, 4, 5])’ 是计算 ‘((((1+2)+3)+4)+5)’ 的值。 左边的参数 `x'
     是积累值而右边的参数 `y' 则是来自 `iterable' 的更新值。 如果存在可
     选项 `initializer'，它会被放在参与计算的可迭代对象的条目之前，并在
     可迭代对象为空时作为默认值。 如果没有给出 `initializer' 并且
     `iterable' 仅包含一个条目，则将返回第一项。

     大致相当于：

          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

     请参阅 *note itertools.accumulate(): 30e. 了解有关可产生所有中间值
     的迭代器。

 -- 函式: @functools.singledispatch

     将一个函数转换为 *note 单分派: 2fb. *note generic function: 2fc.。

     To define a generic function, decorate it with the
     ‘@singledispatch’ decorator.  When defining a function using
     ‘@singledispatch’, note that the dispatch happens on the type of
     the first argument:

          >>> from functools import singledispatch
          >>> @singledispatch
          ... def fun(arg, verbose=False):
          ...     if verbose:
          ...         print("Let me just say,", end=" ")
          ...     print(arg)

     To add overloaded implementations to the function, use the
     ‘register()’ attribute of the generic function, which can be used
     as a decorator.  For functions annotated with types, the decorator
     will infer the type of the first argument automatically:

          >>> @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)

     对于不使用类型标注的代码，可以将适当的类型参数显式地传给装饰器本身:

          >>> @fun.register(complex)
          ... def _(arg, verbose=False):
          ...     if verbose:
          ...         print("Better than complicated.", end=" ")
          ...     print(arg.real, arg.imag)
          ...

     To enable registering *note lambdas: 1ca8. and pre-existing
     functions, the ‘register()’ attribute can also be used in a
     functional form:

          >>> def nothing(arg, verbose=False):
          ...     print("Nothing.")
          ...
          >>> fun.register(type(None), nothing)

     The ‘register()’ attribute returns the undecorated function.  This
     enables decorator stacking, *note pickling: ca, and the creation of
     unit tests for each variant independently:

          >>> @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

     在调用时，泛型函数会根据第一个参数的类型进行分派:

          >>> 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

     Where there is no registered implementation for a specific type,
     its method resolution order is used to find a more generic
     implementation.  The original function decorated with
     ‘@singledispatch’ is registered for the base *note object: 3d2.
     type, which means it is used if no better implementation is found.

     If an implementation is registered to an *note abstract base class:
     c05, virtual subclasses of the base class will be dispatched to
     that implementation:

          >>> 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

     To check which implementation the generic function will choose for
     a given type, use the ‘dispatch()’ attribute:

          >>> fun.dispatch(float)
          <function fun_num at 0x1035a2840>
          >>> fun.dispatch(dict)    # note: default implementation
          <function fun at 0x103fe0000>

     要访问所有忆注册实现，请使用只读的 ‘registry’ 属性:

          >>> 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>

     3.4 版新加入.

     3.7 版更變: The ‘register()’ attribute now supports using type
     annotations.

 -- 類別: functools.singledispatchmethod (func)

     将一个方法转换为 *note 单分派: 2fb. *note generic function: 2fc.。

     To define a generic method, decorate it with the
     ‘@singledispatchmethod’ decorator.  When defining a function using
     ‘@singledispatchmethod’, note that the dispatch happens on the type
     of the first non-`self' or non-`cls' argument:

          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

     ‘@singledispatchmethod’ supports nesting with other decorators such
     as *note @classmethod: 309.  Note that to allow for
     ‘dispatcher.register’, ‘singledispatchmethod’ must be the `outer
     most' decorator.  Here is the ‘Negator’ class with the ‘neg’
     methods bound to the class, rather than an instance of the class:

          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

     The same pattern can be used for other similar decorators: *note
     @staticmethod: 30a, *note @abstractmethod: aad, and others.

     3.8 版新加入.

 -- 函式: functools.update_wrapper (wrapper, wrapped,
          assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)

     更新一个 `wrapper' 函数以使其类似于 `wrapped' 函数。 可选参数为指明
     原函数的哪些属性要直接被赋值给 wrapper 函数的匹配属性的元组，并且这
     些 wrapper 函数的属性将使用原函数的对应属性来更新。 这些参数的默认
     值是模块级常量 ‘WRAPPER_ASSIGNMENTS’ (它将被赋值给 wrapper 函数的
     ‘__module__’, ‘__name__’, ‘__qualname__’, ‘__annotations__’ 和
     ‘__doc__’ 即文档字符串) 以及 ‘WRAPPER_UPDATES’ (它将更新 wrapper 函
     数的 ‘__dict__’ 即实例字典)。

     为了允许出于内省和其他目的访问原始函数（例如绕过 *note lru_cache():
     2f8. 之类的缓存装饰器），此函数会自动为 wrapper 添加一个指向被包装
     函数的 ‘__wrapped__’ 属性。

     此函数的主要目的是在 *note decorator: 174. 函数中用来包装被装饰的函
     数并返回包装器。 如果包装器函数未被更新，则被返回函数的元数据将反映
     包装器定义而不是原始函数定义，这通常没有什么用处。

     *note update_wrapper(): a3b. 可以与函数之外的可调用对象一同使用。 在
     `assigned' 或 `updated' 中命名的任何属性如果不存在于被包装对象则会
     被忽略（即该函数将不会尝试在包装器函数上设置它们）。 如果包装器函数
     自身缺少在 `updated' 中命名的任何属性则仍将引发 *note
     AttributeError: 4a1.。

     3.2 版新加入: 自动添加 ‘__wrapped__’ 属性。

     3.2 版新加入: 默认拷贝 ‘__annotations__’ 属性。

     3.2 版更變: 不存在的属性将不再触发 *note AttributeError: 4a1.。

     3.4 版更變: ‘__wrapped__’ 属性现在总是指向被包装的函数，即使该函数
     定义了 ‘__wrapped__’ 属性。 (参见 bpo-17482(7))

 -- 函式: @functools.wraps (wrapped, assigned=WRAPPER_ASSIGNMENTS,
          updated=WRAPPER_UPDATES)

     这是一个便捷函数，用于在定义包装器函数时发起调用 *note
     update_wrapper(): a3b. 作为函数装饰器。 它等价于
     ‘partial(update_wrapper, wrapped=wrapped, assigned=assigned,
     updated=updated)’。 例如:

          >>> 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'

     如果不使用这个装饰器工厂函数，则 example 函数的名称将变为
     ‘'wrapper'’，并且 ‘example()’ 原本的文档字符串将会丢失。

* Menu:

* partial 对象::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/functools.py

   (2) https://en.wikipedia.org/wiki/Memoization

   (3) https://www.python.org/dev/peps/pep-0412

   (4) 
https://en.wikipedia.org/wiki/Cache_replacement_policies#Least_recently_used_(LRU)

   (5) https://zh.wikipedia.org/wiki/动态规划

   (6) https://zh.wikipedia.org/wiki/斐波那契数列

   (7) https://bugs.python.org/issue17482


File: python.info,  Node: partial 对象,  Up: functools --- 高阶函数和可调用对象上的操作

5.10.2.1 ‘partial’ 对象
.......................

*note partial: 8b5. 对象是由 *note partial(): 8b5. 创建的可调用对象。 它
们具有三个只读属性：

 -- 屬性: partial.func

     一个可调用对象或函数。 对 *note partial: 8b5. 对象的调用将被转发给
     *note func: 1caa. 并附带新的参数和关键字。

 -- 屬性: partial.args

     最左边的位置参数将放置在提供给 *note partial: 8b5. 对象调用的位置参
     数之前。

 -- 屬性: partial.keywords

     当调用 *note partial: 8b5. 对象时将要提供的关键字参数。

*note partial: 8b5. 对象与 ‘function’ 对象的类似之处在于它们都是可调用、
可弱引用的对象并可拥有属性。 但两者也存在一些重要的区别。 例如前者不会自
动创建 *note __name__: d2f. 和 ‘__doc__’ 属性。 而且，在类中定义的 *note
partial: 8b5. 对象的行为类似于静态方法，并且不会在实例属性查找期间转换为
绑定方法。


File: python.info,  Node: operator --- 标准运算符替代函数,  Prev: functools --- 高阶函数和可调用对象上的操作,  Up: 函式編程模組

5.10.3 ‘operator’ — 标准运算符替代函数
--------------------------------------

`源代码:' Lib/operator.py(1)

__________________________________________________________________

*note operator: c2. 模块提供了一套与Python的内置运算符对应的高效率函数。
例如，‘operator.add(x, y)’ 与表达式 ‘x+y’ 相同。 许多函数名与特殊方法名
相同，只是没有双下划线。为了向后兼容性，也保留了许多包含双下划线的函数。
为了表述清楚，建议使用没有双下划线的函数。

函数包含的种类有：对象的比较运算、逻辑运算、数学运算以及序列运算。

对象比较函数适用于所有的对象，函数名根据它们对应的比较运算符命名。

 -- 函式: operator.lt (a, b)
 -- 函式: operator.le (a, b)
 -- 函式: operator.eq (a, b)
 -- 函式: operator.ne (a, b)
 -- 函式: operator.ge (a, b)
 -- 函式: operator.gt (a, b)
 -- 函式: operator.__lt__ (a, b)
 -- 函式: operator.__le__ (a, b)
 -- 函式: operator.__eq__ (a, b)
 -- 函式: operator.__ne__ (a, b)
 -- 函式: operator.__ge__ (a, b)
 -- 函式: operator.__gt__ (a, b)

     在 `a' 和 `b' 之间进行全比较。具体的，‘lt(a, b)’ 与 ‘a < b’ 相同，
     ‘le(a, b)’ 与 ‘a <= b’ 相同，‘eq(a, b)’ 与 ‘a == b’ 相同，‘ne(a,
     b)’ 与 ‘a != b’ 相同，‘gt(a, b)’ 与 ‘a > b’ 相同，‘ge(a, b)``与 ``a
     >= b’ 相同。注意这些函数可以返回任何值，无论它是否可当作布尔值。关
     于全比较的更多信息请参考 *note 比较运算: 167a. 。

逻辑运算通常也适用于所有对象，并且支持真值检测、标识检测和布尔运算：

 -- 函式: operator.not_ (obj)
 -- 函式: operator.__not__ (obj)

     返回 *note not: 1686. `obj' 的结果。 （请注意对象实例并没有 *note
     __not__(): 1cbc. 方法；只有解释器核心可定义此操作。 结果会受 *note
     __bool__(): d30. 和 *note __len__(): e90. 方法影响。）

 -- 函式: operator.truth (obj)

     如果 `obj' 为真值则返回 *note True: 593.，否则返回 *note False:
     48e.。 这等价于使用 *note bool: 2bd. 构造器。

 -- 函式: operator.is_ (a, b)

     返回 ‘a is b’。 检测对象标识。

 -- 函式: operator.is_not (a, b)

     返回 ‘a is not b’。 检测对象标识。

数学和按位运算的种类是最多的：

 -- 函式: operator.abs (obj)
 -- 函式: operator.__abs__ (obj)

     返回 `obj' 的绝对值。

 -- 函式: operator.add (a, b)
 -- 函式: operator.__add__ (a, b)

     对于数字 `a' 和 `b'，返回 ‘a + b’。

 -- 函式: operator.and_ (a, b)
 -- 函式: operator.__and__ (a, b)

     返回 `x' 和 `y' 按位与的结果。

 -- 函式: operator.floordiv (a, b)
 -- 函式: operator.__floordiv__ (a, b)

     返回 ‘a // b’。

 -- 函式: operator.index (a)
 -- 函式: operator.__index__ (a)

     返回 `a' 转换为整数的结果。 等价于 ‘a.__index__()’。

 -- 函式: operator.inv (obj)
 -- 函式: operator.invert (obj)
 -- 函式: operator.__inv__ (obj)
 -- 函式: operator.__invert__ (obj)

     返回数字 `obj' 按位取反的结果。 这等价于 ‘~obj’。

 -- 函式: operator.lshift (a, b)
 -- 函式: operator.__lshift__ (a, b)

     返回 `a' 左移 `b' 位的结果。

 -- 函式: operator.mod (a, b)
 -- 函式: operator.__mod__ (a, b)

     返回 ‘a % b’。

 -- 函式: operator.mul (a, b)
 -- 函式: operator.__mul__ (a, b)

     对于数字 `a' 和 `b'，返回 ‘a * b’。

 -- 函式: operator.matmul (a, b)
 -- 函式: operator.__matmul__ (a, b)

     返回 ‘a @ b’。

     3.5 版新加入.

 -- 函式: operator.neg (obj)
 -- 函式: operator.__neg__ (obj)

     返回 `obj' 取负的结果 (‘-obj’)。

 -- 函式: operator.or_ (a, b)
 -- 函式: operator.__or__ (a, b)

     返回 `a' 和 `b' 按位或的结果。

 -- 函式: operator.pos (obj)
 -- 函式: operator.__pos__ (obj)

     返回 `obj' 取正的结果 (‘+obj’)。

 -- 函式: operator.pow (a, b)
 -- 函式: operator.__pow__ (a, b)

     对于数字 `a' 和 `b'，返回 ‘a ** b’。

 -- 函式: operator.rshift (a, b)
 -- 函式: operator.__rshift__ (a, b)

     返回 `a' 右移 `b' 位的结果。

 -- 函式: operator.sub (a, b)
 -- 函式: operator.__sub__ (a, b)

     返回 ‘a - b’。

 -- 函式: operator.truediv (a, b)
 -- 函式: operator.__truediv__ (a, b)

     返回 ‘a / b’ 例如 2/3 将等于 .66 而不是 0。 这也被称为“真”除法。

 -- 函式: operator.xor (a, b)
 -- 函式: operator.__xor__ (a, b)

     返回 `a' 和 `b' 按位异或的结果。

适用于序列的操作（其中一些也适用于映射）包括：

 -- 函式: operator.concat (a, b)
 -- 函式: operator.__concat__ (a, b)

     对于序列 `a' 和 `b'，返回 ‘a + b’。

 -- 函式: operator.contains (a, b)
 -- 函式: operator.__contains__ (a, b)

     返回 ‘b in a’ 检测的结果。 请注意操作数是反序的。

 -- 函式: operator.countOf (a, b)

     返回 `b' 在 `a' 中的出现次数。

 -- 函式: operator.delitem (a, b)
 -- 函式: operator.__delitem__ (a, b)

     移除 `a' 中索引号为 `b' 的值。

 -- 函式: operator.getitem (a, b)
 -- 函式: operator.__getitem__ (a, b)

     返回 `a' 中索引为 `b' 的值。

 -- 函式: operator.indexOf (a, b)

     返回 `b' 在 `a' 中首次出现所在的索引号。

 -- 函式: operator.setitem (a, b, c)
 -- 函式: operator.__setitem__ (a, b, c)

     将 `a' 中索引号为 `b' 的值设为 `c'。

 -- 函式: operator.length_hint (obj, default=0)

     返回对象 `o' 的估计长度。 首先尝试返回其实际长度，再使用 *note
     object.__length_hint__(): 8f9. 得出估计值，最后返回默认值。

     3.4 版新加入.

*note operator: c2. 模块还定义了一些用于常规属性和条目查找的工具。 这些
工具适合用来编写快速字段提取器作为 *note map(): cf7, *note sorted():
546, *note itertools.groupby(): 1c9d. 或其他需要相应函数参数的函数的参数
。

 -- 函式: operator.attrgetter (attr)

 -- 函式: operator.attrgetter (*attrs)

     返回一个可从操作数中获取 `attr' 的可调用对象。 如果请求了一个以上的
     属性，则返回一个属性元组。 属性名称还可包含点号。 例如：

        * 在 ‘f = attrgetter('name')’ 之后，调用 ‘f(b)’ 将返回 ‘b.name’。

        * 在 ‘f = attrgetter('name', 'date')’ 之后，调用 ‘f(b)’ 将返回
          ‘(b.name, b.date)’。

        * 在 ‘f = attrgetter('name.first', 'name.last')’ 之后，调用
          ‘f(b)’ 将返回 ‘(b.name.first, b.name.last)’。

     等价于:

          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

 -- 函式: operator.itemgetter (item)

 -- 函式: operator.itemgetter (*items)

     返回一个使用操作数的 *note __getitem__(): 1ce9. 方法从操作数中获取
     `item' 的可调用对象。 如果指定了多个条目，则返回一个查找值的元组。
     例如：

        * 在 ‘f = itemgetter(2)’ 之后，调用 ‘f(r)’ 将返回 ‘r[2]’。

        * 在 ‘g = itemgetter(2, 5, 3)’ 之后，调用 ‘g(r)’ 将返回 ‘(r[2],
          r[5], r[3])’。

     等价于:

          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

     传入的条目可以为操作数的 *note __getitem__(): 1ce9. 所接受的任何类
     型。 字典接受任意可哈希的值。 列表、元组和字符串接受 index 或 slice
     对象：

          >>> 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'

     使用 *note itemgetter(): 38b. 从元组的记录中提取特定字段的例子：

          >>> 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)]

 -- 函式: operator.methodcaller (name, /, *args, **kwargs)

     返回一个在操作数上调用 `name' 方法的可调用对象。 如果给出额外的参数
     和/或关键字参数，它们也将被传给该方法。 例如：

        * 在 ‘f = methodcaller('name')’ 之后，调用 ‘f(b)’ 将返回
          ‘b.name()’。

        * 在 ‘f = methodcaller('name', 'foo', bar=1)’ 之后，调用 ‘f(b)’
          将返回 ‘b.name('foo', bar=1)’。

     等价于:

          def methodcaller(name, /, *args, **kwargs):
              def caller(obj):
                  return getattr(obj, name)(*args, **kwargs)
              return caller

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/operator.py


File: python.info,  Node: 将运算符映射到函数,  Next: 原地运算符,  Up: operator --- 标准运算符替代函数

5.10.3.1 将运算符映射到函数
...........................

以下表格显示了抽象运算是如何对应于 Python 语法中的运算符和 *note
operator: c2. 模块中的函数的。

运算                        语法                          函数
                                                          
------------------------------------------------------------------------------------------------------
                                                          
加法                        ‘a + b’                       ‘add(a, b)’
                                                          
                                                          
字符串拼接                  ‘seq1 + seq2’                 ‘concat(seq1, seq2)’
                                                          
                                                          
包含测试                    ‘obj in seq’                  ‘contains(seq, obj)’
                                                          
                                                          
除法                        ‘a / b’                       ‘truediv(a, b)’
                                                          
                                                          
除法                        ‘a // b’                      ‘floordiv(a, b)’
                                                          
                                                          
按位与                      ‘a & b’                       ‘and_(a, b)’
                                                          
                                                          
按位异或                    ‘a ^ b’                       ‘xor(a, b)’
                                                          
                                                          
按位取反                    ‘~ a’                         ‘invert(a)’
                                                          
                                                          
按位或                      ‘a | b’                       ‘or_(a, b)’
                                                          
                                                          
取幂                        ‘a ** b’                      ‘pow(a, b)’
                                                          
                                                          
标识                        ‘a is b’                      ‘is_(a, b)’
                                                          
                                                          
标识                        ‘a is not b’                  ‘is_not(a, b)’
                                                          
                                                          
索引赋值                    ‘obj[k] = v’                  ‘setitem(obj, k, v)’
                                                          
                                                          
索引删除                    ‘del obj[k]’                  ‘delitem(obj, k)’
                                                          
                                                          
索引取值                    ‘obj[k]’                      ‘getitem(obj, k)’
                                                          
                                                          
左移                        ‘a << b’                      ‘lshift(a, b)’
                                                          
                                                          
取模                        ‘a % b’                       ‘mod(a, b)’
                                                          
                                                          
乘法                        ‘a * b’                       ‘mul(a, b)’
                                                          
                                                          
矩阵乘法                    ‘a @ b’                       ‘matmul(a, b)’
                                                          
                                                          
取反（算术）                ‘- a’                         ‘neg(a)’
                                                          
                                                          
取反（逻辑）                ‘not a’                       ‘not_(a)’
                                                          
                                                          
正数                        ‘+ a’                         ‘pos(a)’
                                                          
                                                          
右移                        ‘a >> b’                      ‘rshift(a, b)’
                                                          
                                                          
切片赋值                    ‘seq[i:j] = values’           ‘setitem(seq, slice(i, j), values)’
                                                          
                                                          
切片删除                    ‘del seq[i:j]’                ‘delitem(seq, slice(i, j))’
                                                          
                                                          
切片取值                    ‘seq[i:j]’                    ‘getitem(seq, slice(i, j))’
                                                          
                                                          
字符串格式化                ‘s % obj’                     ‘mod(s, obj)’
                                                          
                                                          
减法                        ‘a - b’                       ‘sub(a, b)’
                                                          
                                                          
真值测试                    ‘obj’                         ‘truth(obj)’
                                                          
                                                          
比较                        ‘a < b’                       ‘lt(a, b)’
                                                          
                                                          
比较                        ‘a <= b’                      ‘le(a, b)’
                                                          
                                                          
相等                        ‘a == b’                      ‘eq(a, b)’
                                                          
                                                          
不等                        ‘a != b’                      ‘ne(a, b)’
                                                          
                                                          
比较                        ‘a >= b’                      ‘ge(a, b)’
                                                          
                                                          
比较                        ‘a > b’                       ‘gt(a, b)’
                                                          


File: python.info,  Node: 原地运算符,  Prev: 将运算符映射到函数,  Up: operator --- 标准运算符替代函数

5.10.3.2 原地运算符
...................

许多运算都有“原地”版本。 以下列出的是提供对原地运算符相比通常语法更底层
访问的函数，例如 *note statement: 1cef. ‘x += y’ 相当于 ‘x =
operator.iadd(x, y)’。 换一种方式来讲就是 ‘z = operator.iadd(x, y)’ 等价
于语句块 ‘z = x; z += y’。

在这些例子中，请注意当调用一个原地方法时，运算和赋值是分成两个步骤来执行
的。 下面列出的原地函数只执行第一步即调用原地方法。 第二步赋值则不加处理
。

对于不可变的目标例如字符串、数字和元组，更新的值会被计算，但不会被再被赋
值给输入变量：

     >>> a = 'hello'
     >>> iadd(a, ' world')
     'hello world'
     >>> a
     'hello'

对于可变的目标例如列表和字典，原地方法将执行更新，因此不需要后续赋值操作
：

     >>> 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']

 -- 函式: operator.iadd (a, b)
 -- 函式: operator.__iadd__ (a, b)

     ‘a = iadd(a, b)’ 等价于 ‘a += b’。

 -- 函式: operator.iand (a, b)
 -- 函式: operator.__iand__ (a, b)

     ‘a = iand(a, b)’ 等价于 ‘a &= b’。

 -- 函式: operator.iconcat (a, b)
 -- 函式: operator.__iconcat__ (a, b)

     ‘a = iconcat(a, b)’ 等价于 ‘a += b’ 其中 `a' 和 `b' 为序列。

 -- 函式: operator.ifloordiv (a, b)
 -- 函式: operator.__ifloordiv__ (a, b)

     ‘a = ifloordiv(a, b)’ 等价于 ‘a //= b’。

 -- 函式: operator.ilshift (a, b)
 -- 函式: operator.__ilshift__ (a, b)

     ‘a = ilshift(a, b)’ 等价于 ‘a <<= b’。

 -- 函式: operator.imod (a, b)
 -- 函式: operator.__imod__ (a, b)

     ‘a = imod(a, b)’ 等价于 ‘a %= b’。

 -- 函式: operator.imul (a, b)
 -- 函式: operator.__imul__ (a, b)

     ‘a = imul(a, b)’ 等价于 ‘a *= b’。

 -- 函式: operator.imatmul (a, b)
 -- 函式: operator.__imatmul__ (a, b)

     ‘a = imatmul(a, b)’ 等价于 ‘a @= b’。

     3.5 版新加入.

 -- 函式: operator.ior (a, b)
 -- 函式: operator.__ior__ (a, b)

     ‘a = ior(a, b)’ 等价于 ‘a |= b’。

 -- 函式: operator.ipow (a, b)
 -- 函式: operator.__ipow__ (a, b)

     ‘a = ipow(a, b)’ 等价于 ‘a **= b’。

 -- 函式: operator.irshift (a, b)
 -- 函式: operator.__irshift__ (a, b)

     ‘a = irshift(a, b)’ 等价于 ‘a >>= b’。

 -- 函式: operator.isub (a, b)
 -- 函式: operator.__isub__ (a, b)

     ‘a = isub(a, b)’ 等价于 ‘a -= b’。

 -- 函式: operator.itruediv (a, b)
 -- 函式: operator.__itruediv__ (a, b)

     ‘a = itruediv(a, b)’ 等价于 ‘a /= b’。

 -- 函式: operator.ixor (a, b)
 -- 函式: operator.__ixor__ (a, b)

     ‘a = ixor(a, b)’ 等价于 ‘a ^= b’。


File: python.info,  Node: 檔案與目錄存取,  Next: 数据持久化,  Prev: 函式編程模組,  Up: Python 標準函式庫 Standard Library

5.11 檔案與目錄存取
===================

本章中描述的模块处理磁盘文件和目录。 例如，有一些模块用于读取文件的属性
，以可移植的方式操作路径以及创建临时文件。 本章的完整模块列表如下：

* 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 --- 高阶文件操作. 高阶文件操作


File: python.info,  Node: pathlib --- 面向对象的文件系统路径,  Next: os path --- 常用路径操作,  Up: 檔案與目錄存取

5.11.1 ‘pathlib’ — 面向对象的文件系统路径
-----------------------------------------

3.4 版新加入.

`源代码' Lib/pathlib.py(1)

__________________________________________________________________

该模块提供表示文件系统路径的类，其语义适用于不同的操作系统。路径类被分为
提供纯计算操作而没有 I/O 的 *note 纯路径: 1d10.，以及从纯路径继承而来但
提供 I/O 操作的 *note 具体路径: 1d11.。

[python-figures/pathlib-inheritance]
如果以前从未用过此模块，或不确定哪个类适合完成任务，那要用的可能就是
*note Path: 32f.。它在运行代码的平台上实例化为 *note 具体路径: 1d11.。

在一些用例中纯路径很有用，例如：

  1. 如果你想要在 Unix 设备上操作 Windows 路径（或者相反）。你不应在
     Unix 上实例化一个 *note WindowsPath: 1d12.，但是你可以实例化 *note
     PureWindowsPath: 1d13.。

  2. 你只想操作路径但不想实际访问操作系统。在这种情况下，实例化一个纯路
     径是有用的，因为它们没有任何访问操作系统的操作。

也參考
......

PEP 428(2)：pathlib 模块 – 面向对象的的文件系统路径。

也參考
......

对于底层的路径字符串操作，你也可以使用 *note os.path: c5. 模块。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/pathlib.py

   (2) https://www.python.org/dev/peps/pep-0428


File: python.info,  Node: 基础使用,  Next: 纯路径,  Up: pathlib --- 面向对象的文件系统路径

5.11.1.1 基础使用
.................

导入主类:

     >>> from pathlib import Path

列出子目录:

     >>> p = Path('.')
     >>> [x for x in p.iterdir() if x.is_dir()]
     [PosixPath('.hg'), PosixPath('docs'), PosixPath('dist'),
      PosixPath('__pycache__'), PosixPath('build')]

列出当前目录树下的所有 Python 源代码文件:

     >>> list(p.glob('**/*.py'))
     [PosixPath('test_pathlib.py'), PosixPath('setup.py'),
      PosixPath('pathlib.py'), PosixPath('docs/conf.py'),
      PosixPath('build/lib/pathlib.py')]

在目录树中移动:

     >>> p = Path('/etc')
     >>> q = p / 'init.d' / 'reboot'
     >>> q
     PosixPath('/etc/init.d/reboot')
     >>> q.resolve()
     PosixPath('/etc/rc.d/init.d/halt')

查询路径的属性:

     >>> q.exists()
     True
     >>> q.is_dir()
     False

打开一个文件:

     >>> with q.open() as f: f.readline()
     ...
     '#!/bin/bash\n'


File: python.info,  Node: 纯路径,  Next: 具体路径,  Prev: 基础使用,  Up: pathlib --- 面向对象的文件系统路径

5.11.1.2 纯路径
...............

纯路径对象提供了不实际访问文件系统的路径处理操作。有三种方式来访问这些类
，也是不同的风格：

 -- 類別: pathlib.PurePath (*pathsegments)

     一个通用的类，代表当前系统的路径风格（实例化为 *note PurePosixPath:
     1d16. 或者 *note PureWindowsPath: 1d13.）:

          >>> PurePath('setup.py')      # Running on a Unix machine
          PurePosixPath('setup.py')

     每一个 `pathsegments' 的元素可能是一个代表路径片段的字符串，一个返
     回字符串的实现了 *note os.PathLike: 5e5. 接口的对象，或者另一个路径
     对象:

          >>> PurePath('foo', 'some/path', 'bar')
          PurePosixPath('foo/some/path/bar')
          >>> PurePath(Path('foo'), Path('bar'))
          PurePosixPath('foo/bar')

     当 `pathsegments' 为空的时候，假定为当前目录:

          >>> PurePath()
          PurePosixPath('.')

     当给出一些绝对路径，最后一位将被当作锚（模仿 *note os.path.join():
     10c7. 的行为）:

          >>> PurePath('/etc', '/usr', 'lib64')
          PurePosixPath('/usr/lib64')
          >>> PureWindowsPath('c:/Windows', 'd:bar')
          PureWindowsPath('d:bar')

     但是，在 Windows 路径中，改变本地根目录并不会丢弃之前盘符的设置:

          >>> PureWindowsPath('c:/Windows', '/Program Files')
          PureWindowsPath('c:/Program Files')

     假斜线和单独的点都会被消除，但是双点 （‘‘..’’） 不会，以防改变符号
     链接的含义。

          >>> PurePath('foo//bar')
          PurePosixPath('foo/bar')
          >>> PurePath('foo/./bar')
          PurePosixPath('foo/bar')
          >>> PurePath('foo/../bar')
          PurePosixPath('foo/../bar')

     （一个很 naïve 的做法是让 ‘PurePosixPath('foo/../bar')’ 等同于
     ‘PurePosixPath('bar')’，如果 ‘foo’ 是一个指向其他目录的符号链接那么
     这个做法就将出错）

     纯路径对象实现了 *note os.PathLike: 5e5. 接口，允许它们在任何接受此
     接口的地方使用。

     3.6 版更變: 添加了 *note os.PathLike: 5e5. 接口支持。

 -- 類別: pathlib.PurePosixPath (*pathsegments)

     一个 *note PurePath: 235. 的子类，路径风格不同于 Windows 文件系统:

          >>> PurePosixPath('/etc')
          PurePosixPath('/etc')

     `pathsegments' 参数的指定和 *note PurePath: 235. 相同。

 -- 類別: pathlib.PureWindowsPath (*pathsegments)

     *note PurePath: 235. 的一个子类，路径风格为 Windows 文件系统路径:

          >>> PureWindowsPath('c:/Program Files/')
          PureWindowsPath('c:/Program Files')

     `pathsegments' 参数的指定和 *note PurePath: 235. 相同。

无论你正运行什么系统，你都可以实例化这些类，因为它们提供的操作不做任何系
统调用。

* Menu:

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


File: python.info,  Node: 通用性质,  Next: 运算符<2>,  Up: 纯路径

5.11.1.3 通用性质
.................

路径是不可变并可哈希的。相同风格的路径可以排序与比较。这些性质尊重对应风
格的大小写转换语义:

     >>> PurePosixPath('foo') == PurePosixPath('FOO')
     False
     >>> PureWindowsPath('foo') == PureWindowsPath('FOO')
     True
     >>> PureWindowsPath('FOO') in { PureWindowsPath('foo') }
     True
     >>> PureWindowsPath('C:') < PureWindowsPath('d:')
     True

不同风格的路径比较得到不等的结果并且无法被排序:

     >>> 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'


File: python.info,  Node: 运算符<2>,  Next: 访问个别部分,  Prev: 通用性质,  Up: 纯路径

5.11.1.4 运算符
...............

斜杠 ‘/’ 操作符有助于创建子路径，就像 *note os.path.join(): 10c7. 一样:

     >>> p = PurePath('/etc')
     >>> p
     PurePosixPath('/etc')
     >>> p / 'init.d' / 'apache2'
     PurePosixPath('/etc/init.d/apache2')
     >>> q = PurePath('bin')
     >>> '/usr' / q
     PurePosixPath('/usr/bin')

文件对象可用于任何接受 *note os.PathLike: 5e5. 接口实现的地方。

     >>> import os
     >>> p = PurePath('/etc')
     >>> os.fspath(p)
     '/etc'

路径的字符串表示法为它自己原始的文件系统路径（以原生形式，例如在 Windows
下使用反斜杠）。你可以传递给任何需要字符串形式路径的函数。

     >>> p = PurePath('/etc')
     >>> str(p)
     '/etc'
     >>> p = PureWindowsPath('c:/Program Files')
     >>> str(p)
     'c:\\Program Files'

类似地，在路径上调用 *note bytes: 172. 将原始文件系统路径作为字节对象给
出，就像被 *note os.fsencode(): 5e9. 编码一样:

     >>> bytes(p)
     b'/etc'

     備註: 只推荐在 Unix 下调用 *note bytes: 172.。在 Windows， unicode
     形式是文件系统路径的规范表示法。


File: python.info,  Node: 访问个别部分,  Next: 方法和特征属性,  Prev: 运算符<2>,  Up: 纯路径

5.11.1.5 访问个别部分
.....................

为了访问路径独立的部分 （组件），使用以下特征属性：

 -- Data: PurePath.parts

     一个元组，可以访问路径的多个组件:

          >>> p = PurePath('/usr/bin/python3')
          >>> p.parts
          ('/', 'usr', 'bin', 'python3')

          >>> p = PureWindowsPath('c:/Program Files/PSF')
          >>> p.parts
          ('c:\\', 'Program Files', 'PSF')

     （注意盘符和本地根目录是如何重组的）


File: python.info,  Node: 方法和特征属性,  Prev: 访问个别部分,  Up: 纯路径

5.11.1.6 方法和特征属性
.......................

纯路径提供以下方法和特征属性：

 -- Data: PurePath.drive

     一个表示驱动器盘符或命名的字符串，如果存在:

          >>> PureWindowsPath('c:/Program Files/').drive
          'c:'
          >>> PureWindowsPath('/Program Files/').drive
          ''
          >>> PurePosixPath('/etc').drive
          ''

     UNC 分享也被认作驱动器:

          >>> PureWindowsPath('//host/share/foo.txt').drive
          '\\\\host\\share'

 -- Data: PurePath.root

     一个表示（本地或全局）根的字符串，如果存在:

          >>> PureWindowsPath('c:/Program Files/').root
          '\\'
          >>> PureWindowsPath('c:Program Files/').root
          ''
          >>> PurePosixPath('/etc').root
          '/'

     UNC 分享一样拥有根:

          >>> PureWindowsPath('//host/share').root
          '\\'

 -- Data: PurePath.anchor

     驱动器和根的联合:

          >>> PureWindowsPath('c:/Program Files/').anchor
          'c:\\'
          >>> PureWindowsPath('c:Program Files/').anchor
          'c:'
          >>> PurePosixPath('/etc').anchor
          '/'
          >>> PureWindowsPath('//host/share').anchor
          '\\\\host\\share\\'

 -- Data: PurePath.parents

     An immutable sequence providing access to the logical ancestors of
     the path:

          >>> 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:/')

 -- Data: PurePath.parent

     此路径的逻辑父路径:

          >>> p = PurePosixPath('/a/b/c/d')
          >>> p.parent
          PurePosixPath('/a/b/c')

     你不能超过一个 anchor 或空路径:

          >>> p = PurePosixPath('/')
          >>> p.parent
          PurePosixPath('/')
          >>> p = PurePosixPath('.')
          >>> p.parent
          PurePosixPath('.')

          備註: 这是一个单纯的词法操作，因此有以下行为:

               >>> p = PurePosixPath('foo/..')
               >>> p.parent
               PurePosixPath('foo')

          如果你想要向上移动任意文件系统路径，推荐先使用 *note
          Path.resolve(): 1d21. 来解析符号链接以及消除 ‘".."’ 组件。

 -- Data: PurePath.name

     一个表示最后路径组件的字符串，排除了驱动器与根目录，如果存在的话:

          >>> PurePosixPath('my/library/setup.py').name
          'setup.py'

     UNC 驱动器名不被考虑:

          >>> PureWindowsPath('//some/share/setup.py').name
          'setup.py'
          >>> PureWindowsPath('//some/share').name
          ''

 -- Data: PurePath.suffix

     最后一个组件的文件扩展名，如果存在:

          >>> PurePosixPath('my/library/setup.py').suffix
          '.py'
          >>> PurePosixPath('my/library.tar.gz').suffix
          '.gz'
          >>> PurePosixPath('my/library').suffix
          ''

 -- Data: PurePath.suffixes

     路径的文件扩展名列表:

          >>> PurePosixPath('my/library.tar.gar').suffixes
          ['.tar', '.gar']
          >>> PurePosixPath('my/library.tar.gz').suffixes
          ['.tar', '.gz']
          >>> PurePosixPath('my/library').suffixes
          []

 -- Data: PurePath.stem

     最后一个路径组件，除去后缀:

          >>> PurePosixPath('my/library.tar.gz').stem
          'library.tar'
          >>> PurePosixPath('my/library.tar').stem
          'library'
          >>> PurePosixPath('my/library').stem
          'library'

 -- 成員函式: PurePath.as_posix ()

     返回使用正斜杠（‘/’）的路径字符串:

          >>> p = PureWindowsPath('c:\\windows')
          >>> str(p)
          'c:\\windows'
          >>> p.as_posix()
          'c:/windows'

 -- 成員函式: PurePath.as_uri ()

     将路径表示为 ‘file’ URL。如果并非绝对路径，抛出 *note ValueError:
     16d.。

          >>> p = PurePosixPath('/etc/passwd')
          >>> p.as_uri()
          'file:///etc/passwd'
          >>> p = PureWindowsPath('c:/Windows')
          >>> p.as_uri()
          'file:///c:/Windows'

 -- 成員函式: PurePath.is_absolute ()

     返回此路径是否为绝对路径。如果路径同时拥有驱动器符与根路径（如果风
     格允许）则将被认作绝对路径。

          >>> 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

 -- 成員函式: PurePath.is_relative_to (*other)

     返回此路径是否相对于 `other' 的路径。

          >>> p = PurePath('/etc/passwd')
          >>> p.is_relative_to('/etc')
          True
          >>> p.is_relative_to('/usr')
          False

     3.9 版新加入.

 -- 成員函式: PurePath.is_reserved ()

     在 *note PureWindowsPath: 1d13.，如果路径是被 Windows 保留的则返回
     ‘True’，否则 ‘False’。在 *note PurePosixPath: 1d16.，总是返回
     ‘False’。

          >>> PureWindowsPath('nul').is_reserved()
          True
          >>> PurePosixPath('nul').is_reserved()
          False

     当保留路径上的文件系统被调用，则可能出现玄学失败或者意料之外的效应
     。

 -- 成員函式: PurePath.joinpath (*other)

     调用此方法等同于将每个 `other' 参数中的项目连接在一起:

          >>> 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')

 -- 成員函式: PurePath.match (pattern)

     将此路径与提供的通配符风格的模式匹配。如果匹配成功则返回 ‘True’，否
     则返回 ‘False’。

     如果 `pattern' 是相对的，则路径可以是相对路径或绝对路径，并且匹配是
     从右侧完成的：

          >>> 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

     如果 `pattern' 是绝对的，则路径必须是绝对的，并且路径必须完全匹配:

          >>> PurePath('/a.py').match('/*.py')
          True
          >>> PurePath('a/b.py').match('/*.py')
          False

     与其他方法一样，是否大小写敏感遵循平台的默认规则:

          >>> PurePosixPath('b.py').match('*.PY')
          False
          >>> PureWindowsPath('b.py').match('*.PY')
          True

 -- 成員函式: PurePath.relative_to (*other)

     计算此路径相对 `other' 表示路径的版本。如果不可计算，则抛出
     ValueError:

          >>> 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.

     注意：此函数是 *note PurePath: 235. 的一部分并且适用于字符串。 它不
     会检查或访问下层的文件结构。

 -- 成員函式: PurePath.with_name (name)

     返回一个新的路径并修改 *note name: 1d22.。如果原本路径没有 name，
     ValueError 被抛出:

          >>> 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

 -- 成員函式: PurePath.with_stem (stem)

     返回一个带有修改后 *note stem: 1d25. 的新路径。 如果原路径没有名称
     ，则会引发 ValueError:

          >>> 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('')
          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

     3.9 版新加入.

 -- 成員函式: PurePath.with_suffix (suffix)

     返回一个新的路径并修改 *note suffix: 1d23.。如果原本的路径没有后缀
     ，新的 `suffix' 则被追加以代替。如果 `suffix' 是空字符串，则原本的
     后缀被移除:

          >>> 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('')
          PureWindowsPath('README')


File: python.info,  Node: 具体路径,  Next: 对应的 os 模块的工具,  Prev: 纯路径,  Up: pathlib --- 面向对象的文件系统路径

5.11.1.7 具体路径
.................

具体路径是纯路径的子类。除了后者提供的操作之外，它们还提供了对路径对象进
行系统调用的方法。有三种方法可以实例化具体路径:

 -- 類別: pathlib.Path (*pathsegments)

     一个 *note PurePath: 235. 的子类，此类以当前系统的路径风格表示路径
     （实例化为 *note PosixPath: 1d31. 或 *note WindowsPath: 1d12.）:

          >>> Path('setup.py')
          PosixPath('setup.py')

     `pathsegments' 参数的指定和 *note PurePath: 235. 相同。

 -- 類別: pathlib.PosixPath (*pathsegments)

     一个 *note Path: 32f. 和 *note PurePosixPath: 1d16. 的子类，此类表
     示一个非 Windows 文件系统的具体路径:

          >>> PosixPath('/etc')
          PosixPath('/etc')

     `pathsegments' 参数的指定和 *note PurePath: 235. 相同。

 -- 類別: pathlib.WindowsPath (*pathsegments)

     *note Path: 32f. 和 *note PureWindowsPath: 1d13. 的子类，从类表示一
     个 Windows 文件系统的具体路径:

          >>> WindowsPath('c:/Program Files/')
          WindowsPath('c:/Program Files')

     `pathsegments' 参数的指定和 *note PurePath: 235. 相同。

你只能实例化与当前系统风格相同的类（允许系统调用作用于不兼容的路径风格可
能在应用程序中导致缺陷或失败）:

     >>> 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

* Menu:

* 方法: 方法<2>.


File: python.info,  Node: 方法<2>,  Up: 具体路径

5.11.1.8 方法
.............

除纯路径方法外，实体路径还提供以下方法。 如果系统调用失败（例如因为路径
不存在）这些方法中许多都会引发 *note OSError: 304.。

3.8 版更變: 对于包含 OS 层级无法表示字符的路径，*note exists(): 330,
*note is_dir(): 331, *note is_file(): 332, *note is_mount(): 333, *note
is_symlink(): 334, *note is_block_device(): 335, *note is_char_device():
336, *note is_fifo(): 337, *note is_socket(): 338. 现在将返回 ‘False’ 而
不是引发异常。

 -- 成員函式: classmethod Path.cwd ()

     返回一个新的表示当前目录的路径对象（和 *note os.getcwd(): 1119. 返
     回的相同）:

          >>> Path.cwd()
          PosixPath('/home/antoine/pathlib')

 -- 成員函式: classmethod Path.home ()

     返回一个表示当前用户家目录的新路径对象（和 *note
     os.path.expanduser(): 32c. 构造含 ‘~’ 路径返回的相同）:

          >>> Path.home()
          PosixPath('/home/antoine')

     Note that unlike *note os.path.expanduser(): 32c, on POSIX systems
     a *note KeyError: 3e9. or *note RuntimeError: 3dc. will be raised,
     and on Windows systems a *note RuntimeError: 3dc. will be raised if
     home directory can’t be resolved.

     3.5 版新加入.

 -- 成員函式: Path.stat ()

     返回一个 *note os.stat_result: 11bf. 对象，其中包含有关此路径的信息
     ，例如 *note os.stat(): 321.。 结果会在每次调用此方法时重新搜索。

          >>> p = Path('setup.py')
          >>> p.stat().st_size
          956
          >>> p.stat().st_mtime
          1327883547.852554

 -- 成員函式: Path.chmod (mode)

     改变文件的模式和权限，和 *note os.chmod(): b0f. 一样:

          >>> p = Path('setup.py')
          >>> p.stat().st_mode
          33277
          >>> p.chmod(0o444)
          >>> p.stat().st_mode
          33060

 -- 成員函式: Path.exists ()

     此路径是否指向一个已存在的文件或目录:

          >>> Path('.').exists()
          True
          >>> Path('setup.py').exists()
          True
          >>> Path('/etc').exists()
          True
          >>> Path('nonexistentfile').exists()
          False

          備註: 如果路径指向一个符号链接， *note exists(): 330. 返回此符
          号链接是否指向存在的文件或目录。

 -- 成員函式: Path.expanduser ()

     返回展开了包含 ‘~’ 和 ‘~user’ 的构造，就和 *note
     os.path.expanduser(): 32c. 一样:

          >>> p = PosixPath('~/films/Monty Python')
          >>> p.expanduser()
          PosixPath('/home/eric/films/Monty Python')

     Note that unlike *note os.path.expanduser(): 32c, on POSIX systems
     a *note KeyError: 3e9. or *note RuntimeError: 3dc. will be raised,
     and on Windows systems a *note RuntimeError: 3dc. will be raised if
     home directory can’t be resolved.

     3.5 版新加入.

 -- 成員函式: Path.glob (pattern)

     解析相对于此路径的通配符 `pattern'，产生所有匹配的文件:

          >>> sorted(Path('.').glob('*.py'))
          [PosixPath('pathlib.py'), PosixPath('setup.py'), PosixPath('test_pathlib.py')]
          >>> sorted(Path('.').glob('*/*.py'))
          [PosixPath('docs/conf.py')]

     "‘**’" 模式表示 “此目录以及所有子目录，递归”。换句话说，它启用递归
     通配:

          >>> sorted(Path('.').glob('**/*.py'))
          [PosixPath('build/lib/pathlib.py'),
           PosixPath('docs/conf.py'),
           PosixPath('pathlib.py'),
           PosixPath('setup.py'),
           PosixPath('test_pathlib.py')]

          備註: 在一个较大的目录树中使用 "‘**’" 模式可能会消耗非常多的时
          间。

     引发一个 *note 审计事件: fa1. ‘pathlib.Path.glob’ 附带参数 ‘self’,
     ‘pattern’。

 -- 成員函式: Path.group ()

     返回拥有此文件的用户组。如果文件的 GID 无法在系统数据库中找到，将抛
     出 *note KeyError: 3e9. 。

 -- 成員函式: Path.is_dir ()

     如果路径指向一个目录（或者一个指向目录的符号链接）则返回 ‘True’，如
     果指向其他类型的文件则返回 ‘False’。

     当路径不存在或者是一个破损的符号链接时也会返回 ‘False’；其他错误（
     例如权限错误）被传播。

 -- 成員函式: Path.is_file ()

     如果路径指向一个正常的文件（或者一个指向正常文件的符号链接）则返回
     ‘True’，如果指向其他类型的文件则返回 ‘False’。

     当路径不存在或者是一个破损的符号链接时也会返回 ‘False’；其他错误（
     例如权限错误）被传播。

 -- 成員函式: Path.is_mount ()

     如果路径是一个 `挂载点 <mount point>'：在文件系统中被其他不同的文件
     系统挂载的地点。在 POSIX 系统，此函数检查 `path' 的父级 ——
     ‘path/..’ 是否处于一个和 `path' 不同的设备中，或者 file:‘path/..’ 和
     `path' 是否指向相同设备的相同 i-node —— 这能检测所有 Unix 以及
     POSIX 变种上的挂载点。 Windows 上未实现。

     3.7 版新加入.

 -- 成員函式: Path.is_symlink ()

     如果路径指向符号链接则返回 ‘True’， 否则 ‘False’。

     如果路径不存在也返回 ‘False’；其他错误（例如权限错误）被传播。

 -- 成員函式: Path.is_socket ()

     如果路径指向一个 Unix socket 文件（或者指向 Unix socket 文件的符号
     链接）则返回 ‘True’，如果指向其他类型的文件则返回 ‘False’。

     当路径不存在或者是一个破损的符号链接时也会返回 ‘False’；其他错误（
     例如权限错误）被传播。

 -- 成員函式: Path.is_fifo ()

     如果路径指向一个先进先出存储（或者指向先进先出存储的符号链接）则返
     回 ‘True’ ，指向其他类型的文件则返回 ‘False’。

     当路径不存在或者是一个破损的符号链接时也会返回 ‘False’；其他错误（
     例如权限错误）被传播。

 -- 成員函式: Path.is_block_device ()

     如果文件指向一个块设备（或者指向块设备的符号链接）则返回 ‘True’，指
     向其他类型的文件则返回 ‘False’。

     当路径不存在或者是一个破损的符号链接时也会返回 ‘False’；其他错误（
     例如权限错误）被传播。

 -- 成員函式: Path.is_char_device ()

     如果路径指向一个字符设备（或指向字符设备的符号链接）则返回 ‘True’，
     指向其他类型的文件则返回 ‘False’。

     当路径不存在或者是一个破损的符号链接时也会返回 ‘False’；其他错误（
     例如权限错误）被传播。

 -- 成員函式: Path.iterdir ()

     当路径指向一个目录时，产生该路径下的对象的路径:

          >>> 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')

     子条目会以任意顺序生成，并且不包括特殊条目 ‘'.'’ 和 ‘'..'’。 如果有
     文件在迭代器创建之后在目录中被移除或添加，是否要包括该文件对应的路
     径对象并没有规定。

 -- 成員函式: Path.lchmod (mode)

     就像 *note Path.chmod(): 1d35. 但是如果路径指向符号链接则是修改符号
     链接的模式，而不是修改符号链接的目标。

 -- 成員函式: Path.lstat ()

     就和 *note Path.stat(): 1d34. 一样，但是如果路径指向符号链接，则是
     返回符号链接而不是目标的信息。

 -- 成員函式: Path.mkdir (mode=0o777, parents=False, exist_ok=False)

     新建给定路径的目录。如果给出了 `mode' ，它将与当前进程的 ‘umask’ 值
     合并来决定文件模式和访问标志。如果路径已经存在，则抛出 *note
     FileExistsError: a39.。

     如果 `parents' 为 true，任何找不到的父目录都会伴随着此路径被创建；
     它们会以默认权限被创建，而不考虑 `mode' 设置（模仿 POSIX 的 ‘mkdir
     -p’ 命令）。

     如果 `parents' 为 false（默认），则找不到的父级目录会导致 *note
     FileNotFoundError: 8ad. 被抛出。

     如果 `exist_ok' 为 false（默认），则在目标已存在的情况下抛出 *note
     FileExistsError: a39.。

     如果 `exist_ok' 为 true， 则 *note FileExistsError: a39. 异常将被忽
     略（和 POSIX ‘mkdir -p’ 命令行为相同），但是只有在最后一个路径组件
     不是现存的非目录文件时才生效。

     3.5 版更變: `exist_ok' 形参被加入。

 -- 成員函式: Path.open (mode='r', buffering=-1, encoding=None,
          errors=None, newline=None)

     打开路径指向的文件，就像内置的 *note open(): 16f. 函数所做的一样:

          >>> p = Path('setup.py')
          >>> with p.open() as f:
          ...     f.readline()
          ...
          '#!/usr/bin/env python3\n'

 -- 成員函式: Path.owner ()

     返回拥有此文件的用户名。如果文件的 UID 无法在系统数据库中找到，则抛
     出 *note KeyError: 3e9.。

 -- 成員函式: Path.read_bytes ()

     以字节对象的形式返回路径指向的文件的二进制内容:

          >>> p = Path('my_binary_file')
          >>> p.write_bytes(b'Binary file contents')
          20
          >>> p.read_bytes()
          b'Binary file contents'

     3.5 版新加入.

 -- 成員函式: Path.read_text (encoding=None, errors=None)

     以字符串形式返回路径指向的文件的解码后文本内容。

          >>> p = Path('my_text_file')
          >>> p.write_text('Text file contents')
          18
          >>> p.read_text()
          'Text file contents'

     文件先被打开然后关闭。有和 *note open(): 16f. 一样的可选形参。

     3.5 版新加入.

 -- 成員函式: Path.readlink ()

     返回符号链接所指向的路径（即 *note os.readlink(): 1d1. 的返回值）:

          >>> p = Path('mylink')
          >>> p.symlink_to('setup.py')
          >>> p.readlink()
          PosixPath('setup.py')

     3.9 版新加入.

 -- 成員函式: Path.rename (target)

     将文件或目录重命名为给定的 `target'，并返回一个新的指向 `target' 的
     Path 实例。 在 Unix 上，如果 `target' 存在且为一个文件，如果用户有
     足够权限，则它将被静默地替换。 `target' 可以是一个字符串或者另一个
     路径对象:

          >>> p = Path('foo')
          >>> p.open('w').write('some text')
          9
          >>> target = Path('bar')
          >>> p.rename(target)
          PosixPath('bar')
          >>> target.open().read()
          'some text'

     目标路径可能为绝对或相对路径。 相对路径将被解释为相对于当前工作目录
     ，而 `不是' 相对于 Path 对象的目录。

     3.8 版更變: 添加了返回值，返回新的 Path 实例。

 -- 成員函式: Path.replace (target)

     将文件名目录重命名为给定的 `target'，并返回一个新的指向 `target' 的
     Path 实例。 如果 `target' 指向一个现有文件或目录，则它将被无条件地
     替换。

     目标路径可能为绝对或相对路径。 相对路径将被解释为相对于当前工作目录
     ，而 `不是' 相对于 Path 对象的目录。

     3.8 版更變: 添加了返回值，返回新的 Path 实例。

 -- 成員函式: Path.resolve (strict=False)

     将路径绝对化，解析任何符号链接。返回新的路径对象:

          >>> p = Path()
          >>> p
          PosixPath('.')
          >>> p.resolve()
          PosixPath('/home/antoine/pathlib')

     "‘..’" 组件也将被消除（只有这一种方法这么做）:

          >>> p = Path('docs/../setup.py')
          >>> p.resolve()
          PosixPath('/home/antoine/pathlib/setup.py')

     如果路径不存在并且 `strict' 设为 ‘True’，则抛出 *note
     FileNotFoundError: 8ad.。如果 `strict' 为 ‘False’，则路径将被尽可能
     地解析并且任何剩余部分都会被不检查是否存在地追加。如果在解析路径上
     发生无限循环，则抛出 *note RuntimeError: 3dc.。

     3.6 版新加入: 加入*strict* 参数（3.6之前的版本相当于strict值为
     True）

 -- 成員函式: Path.rglob (pattern)

     这就像调用 ‘Path.glob`时在给定的相对 *pattern* 前面添加了
     "``**/`()’"

          >>> sorted(Path().rglob("*.py"))
          [PosixPath('build/lib/pathlib.py'),
           PosixPath('docs/conf.py'),
           PosixPath('pathlib.py'),
           PosixPath('setup.py'),
           PosixPath('test_pathlib.py')]

     引发一个 *note 审计事件: fa1. ‘pathlib.Path.rglob’ 附带参数 ‘self’,
     ‘pattern’。

 -- 成員函式: Path.rmdir ()

     移除此目录。此目录必须为空的。

 -- 成員函式: Path.samefile (other_path)

     返回此目录是否指向与可能是字符串或者另一个路径对象的 `other_path' 相
     同的文件。语义类似于 *note os.path.samefile(): 96d. 与 *note
     os.path.samestat(): 96c.。

     如果两者都以同一原因无法访问，则抛出 *note OSError: 304.。

          >>> p = Path('spam')
          >>> q = Path('eggs')
          >>> p.samefile(q)
          False
          >>> p.samefile('spam')
          True

     3.5 版新加入.

 -- 成員函式: Path.symlink_to (target, target_is_directory=False)

     将此路径创建为指向 `target' 的符号链接。在 Windows 下，如果链接的目
     标是一个目录则 `target_is_directory' 必须为 true （默认为 ‘False’）
     。在 POSIX 下， `target_is_directory' 的值将被忽略。

          >>> 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

          備註: 参数的顺序（link, target) 和 *note os.symlink(): b17. 是
          相反的。

 -- 成員函式: Path.link_to (target)

     创建硬链接 `target' 指向此路径。

          警告: 此函数不是将此路径设为指向 `target' 的硬链接，这与函数和
          参数名的本义不同。 参数顺序 (target, link) 与 *note
          Path.symlink_to(): 1d3f. 相反，而与 *note os.link(): b11. 一致
          。

     3.8 版新加入.

 -- 成員函式: Path.touch (mode=0o666, exist_ok=True)

     将给定的路径创建为文件。如果给出了 `mode' 它将与当前进程的 ‘umask’
     值合并以确定文件的模式和访问标志。如果文件已经存在，则当 `exist_ok'
     为 true 则函数仍会成功（并且将它的修改事件更新为当前事件），否则抛
     出 *note FileExistsError: a39.。

 -- 成員函式: Path.unlink (missing_ok=False)

     移除此文件或符号链接。如果路径指向目录，则用 *note Path.rmdir():
     1d3e. 代替。

     如果 `missing_ok' 为假值（默认），则如果路径不存在将会引发 *note
     FileNotFoundError: 8ad.。

     如果 `missing_ok' 为真值，则 *note FileNotFoundError: 8ad. 异常将被
     忽略（和 POSIX ‘rm -f’ 命令的行为相同）。

     3.8 版更變: 增加了 `missing_ok' 形参。

 -- 成員函式: Path.write_bytes (data)

     将文件以二进制模式打开，写入 `data' 并关闭:

          >>> p = Path('my_binary_file')
          >>> p.write_bytes(b'Binary file contents')
          20
          >>> p.read_bytes()
          b'Binary file contents'

     一个同名的现存文件将被覆盖。

     3.5 版新加入.

 -- 成員函式: Path.write_text (data, encoding=None, errors=None)

     将文件以文本模式打开，写入 `data' 并关闭:

          >>> p = Path('my_text_file')
          >>> p.write_text('Text file contents')
          18
          >>> p.read_text()
          'Text file contents'

     同名的现有文件会被覆盖。 可选形参的含义与 *note open(): 16f. 的相同
     。

     3.5 版新加入.


File: python.info,  Node: 对应的 os 模块的工具,  Prev: 具体路径,  Up: pathlib --- 面向对象的文件系统路径

5.11.1.9 对应的 ‘os’ 模块的工具
...............................

以下是一个映射了 *note os: c4. 与 *note PurePath: 235./*note Path: 32f.
对应相同的函数的表。

     備註: 尽管 *note os.path.relpath(): 1d42. 和 *note
     PurePath.relative_to(): 1d2d. 拥有相同的重叠的用例，但是它们语义相
     差很大，不能认为它们等价。

os 和 os.path                            pathlib
                                         
----------------------------------------------------------------------------
                                         
*note os.path.abspath(): d78.            *note Path.resolve(): 1d21.
                                         
                                         
*note os.chmod(): b0f.                   *note Path.chmod(): 1d35.
                                         
                                         
*note os.mkdir(): b12.                   *note Path.mkdir(): 818.
                                         
                                         
*note os.makedirs(): 4c3.                *note Path.mkdir(): 818.
                                         
                                         
*note os.rename(): b14.                  *note Path.rename(): 1d3c.
                                         
                                         
*note os.replace(): b15.                 *note Path.replace(): 1d3d.
                                         
                                         
*note os.rmdir(): b16.                   *note Path.rmdir(): 1d3e.
                                         
                                         
*note os.remove(): b13,                  *note Path.unlink(): 1109.
*note os.unlink(): b18.                  

*note os.getcwd(): 1119.                 *note Path.cwd(): 1d33.
                                         
                                         
*note os.path.exists(): 325.             *note Path.exists(): 330.
                                         
                                         
*note os.path.expanduser(): 32c.         *note Path.expanduser(): 819. 和
                                         *note Path.home(): 81a.
                                         
                                         
*note os.listdir(): b1c.                 *note Path.iterdir(): 1d37.
                                         
                                         
*note os.path.isdir(): 327.              *note Path.is_dir(): 331.
                                         
                                         
*note os.path.isfile(): 328.             *note Path.is_file(): 332.
                                         
                                         
*note os.path.islink(): 323.             *note Path.is_symlink(): 334.
                                         
                                         
*note os.link(): b11.                    *note Path.link_to(): 339.
                                         
                                         
*note os.symlink(): b17.                 *note Path.symlink_to(): 1d3f.
                                         
                                         
*note os.readlink(): 1d1.                *note Path.readlink(): 1d0.
                                         
                                         
*note os.stat(): 321.                    *note Path.stat(): 1d34,
                                         *note Path.owner(): 1d3b,
                                         *note Path.group(): 1d36.
                                         
                                         
*note os.path.isabs(): 1d43.             *note PurePath.is_absolute(): 1d28.
                                         
                                         
*note os.path.join(): 10c7.              *note PurePath.joinpath(): 1d2b.
                                         
                                         
*note os.path.basename(): 1d44.          *note PurePath.name: 1d22.
                                         
                                         
*note os.path.dirname(): 1d45.           *note PurePath.parent: 1d20.
                                         
                                         
*note os.path.samefile(): 96d.           *note Path.samefile(): 817.
                                         
                                         
*note os.path.splitext(): 1d46.          *note PurePath.suffix: 1d23.
                                         


File: python.info,  Node: os path --- 常用路径操作,  Next: fileinput --- 迭代来自多个输入流的行,  Prev: pathlib --- 面向对象的文件系统路径,  Up: 檔案與目錄存取

5.11.2 ‘os.path’ — 常用路径操作
-------------------------------

`源代码：' Lib/posixpath.py(1) （用于 POSIX）和 Lib/ntpath.py(2) （用于
Windows NT）

__________________________________________________________________

该模块在路径名上实现了一些有用的功能：如需读取或写入文件，请参见 *note
open(): 16f. ；有关访问文件系统的信息，请参见 *note os: c4. 模块。路径参
数可以字符串或字节形式传递。我们鼓励应用程序将文件名表示为（Unicode）字
符串。不幸的是，某些文件名在Unix上可能无法用字符串表示，因此在Unix上平台
上需要支持任意文件名的应用程序，应使用字节对象来表示路径名。反之亦然，在
Windows平台上仅使用字节对象，不能表示的所有文件名（以标准 ‘mbcs’ 编码）
，因此Windows应用程序应使用字符串对象来访问所有文件。

与unix shell不同，Python不执行任何 `自动' 路径扩展。当应用程序需要类似
shell的路径扩展时，可以显式调用诸如 *note expanduser(): 32c. 和 *note
expandvars(): e09. 之类的函数。 （另请参见 *note glob: 88. 模块。）

也參考
......

*note pathlib: c8. 模块提供高级路径对象。

     備註: 所有这些函数都仅接受字节或字符串对象作为其参数。如果返回路径
     或文件名，则结果是相同类型的对象。

     備註: 由于不同的操作系统具有不同的路径名称约定，因此标准库中有此模
     块的几个版本。*note os.path: c5. 模块始终是适合 Python 运行的操作系
     统的路径模块，因此可用于本地路径。但是，如果操作的路径 `总是' 以一
     种不同的格式显示，那么也可以分别导入和使用各个模块。它们都具有相同
     的接口：

        * ‘posixpath’ 用于Unix 样式的路径

        * ‘ntpath’ 用于 Windows 路径

3.8 版更變: *note exists(): 325.、*note lexists(): 326.、*note isdir():
327.、*note isfile(): 328.、*note islink(): 323. 和 *note ismount():
329. 现在遇到系统层面上不可表示的字符或字节的路径时，会返回 ‘False’，而
不是抛出异常。

 -- 函式: os.path.abspath (path)

     返回路径 `path' 的绝对路径（标准化的）。在大多数平台上，这等同于用
     ‘normpath(join(os.getcwd(), path))’ 的方式调用 *note normpath():
     d77. 函数。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.path.basename (path)

     返回路径 `path' 的基本名称。这是将 `path' 传入函数 *note split():
     1d49. 之后，返回的一对值中的第二个元素。请注意，此函数的结果与Unix
     ‘basename’ 程序不同。‘basename’ 在 ‘'/foo/bar/'’ 上返回 ‘'bar'’，而
     *note basename(): 1d44. 函数返回一个空字符串 (‘''’)。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.path.commonpath (paths)

     接受包含多个路径的序列 `paths'，返回 `paths' 的最长公共子路径。如果
     `paths' 同时包含绝对路径和相对路径，或 `paths' 在不同的驱动器上，或
     `paths' 为空，则抛出 *note ValueError: 16d. 异常。与 *note
     commonprefix(): 815. 不同，本方法返回有效路径。

     *note 可用性: 1491.: Unix, Windows。

     3.5 版新加入.

     3.6 版更變: 接受一个 *note 类路径对象: 472. 序列。

 -- 函式: os.path.commonprefix (list)

     接受包含多个路径的 `列表'，返回所有路径的最长公共前缀（逐字符比较）
     。如果 `列表' 为空，则返回空字符串 (‘''’)。

          備註: 此函数是逐字符比较，因此可能返回无效路径。要获取有效路径
          ，参见 *note commonpath(): 814.。

               >>> os.path.commonprefix(['/usr/lib', '/usr/local/lib'])
               '/usr/l'

               >>> os.path.commonpath(['/usr/lib', '/usr/local/lib'])
               '/usr'

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.path.dirname (path)

     返回路径 `path' 的目录名称。这是将 `path' 传入函数 *note split():
     1d49. 之后，返回的一对值中的第一个元素。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.path.exists (path)

     如果 `path' 指向一个已存在的路径或已打开的文件描述符，返回 ‘True’。
     对于失效的符号链接，返回 ‘False’。在某些平台上，如果使用 *note
     os.stat(): 321. 查询到目标文件没有执行权限，即使 `path' 确实存在，
     本函数也可能返回 ‘False’。

     3.3 版更變: `path' 现在可以是一个整数：如果该整数是一个已打开的文件
     描述符，返回 ‘True’，否则返回 ‘False’。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.path.lexists (path)

     如果 `path' 指向一个已存在的路径，返回 ‘True’。对于失效的符号链接，
     也返回 ‘True’。在缺失 *note os.lstat(): 322. 的平台上等同于 *note
     exists(): 325.。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.path.expanduser (path)

     在 Unix 和 Windows 上，将参数中开头部分的 ‘~’ 或 ‘~user’ 替换为当前
     `用户' 的家目录并返回。

     在 Unix 上，开头的 ‘~’ 会被环境变量 ‘HOME’ 代替，如果变量未设置，则
     通过内置模块 *note pwd: d6. 在 password 目录中查找当前用户的主目录
     。以 ‘~user’ 开头则直接在 password 目录中查找。

     在 Windows 上，如果设置了 ‘USERPROFILE’，就使用这个变量，否则会将
     ‘HOMEPATH’ 和 ‘HOMEDRIVE’ 结合在一起使用。以 ‘~user’ 开头则将上述方
     法生成路径的最后一截目录替换成 user。

     如果展开路径失败，或者路径不是以波浪号开头，则路径将保持不变。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

     3.8 版更變: Windows 不再使用 ‘HOME’。

 -- 函式: os.path.expandvars (path)

     输入带有环境变量的路径作为参数，返回展开变量以后的路径。‘$name’ 或
     ‘${name}’ 形式的子字符串被环境变量 `name' 的值替换。格式错误的变量
     名称和对不存在变量的引用保持不变。

     在 Windows 上，除了 ‘$name’ 和 ‘${name}’ 外，还可以展开 ‘%name%’。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.path.getatime (path)

     返回 `path' 的最后访问时间。返回值是一个浮点数，为纪元秒数（参见
     *note time: 10c. 模块）。如果该文件不存在或不可访问，则抛出 *note
     OSError: 304. 异常。

 -- 函式: os.path.getmtime (path)

     返回 `path' 的最后修改时间。返回值是一个浮点数，为纪元秒数（参见
     *note time: 10c. 模块）。如果该文件不存在或不可访问，则抛出 *note
     OSError: 304. 异常。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.path.getctime (path)

     返回 `path' 在系统中的 ctime，在有些系统（比如 Unix）上，它是元数据
     的最后修改时间，其他系统（比如 Windows）上，它是 `path' 的创建时间
     。返回值是一个数，为纪元秒数（参见 *note time: 10c. 模块）。如果该
     文件不存在或不可访问，则抛出 *note OSError: 304. 异常。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.path.getsize (path)

     返回 `path' 的大小，以字节为单位。如果该文件不存在或不可访问，则抛
     出 *note OSError: 304. 异常。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.path.isabs (path)

     如果 `path' 是一个绝对路径，则返回 ‘True’。在 Unix 上，它就是以斜杠
     开头，而在 Windows 上，它可以是去掉驱动器号后以斜杠（或反斜杠）开头
     。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.path.isfile (path)

     如果 `path' 是 *note 现有的: 325. 常规文件，则返回 ‘True’。本方法会
     跟踪符号链接，因此，对于同一路径，*note islink(): 323. 和 *note
     isfile(): 328. 都可能为 ‘True’。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.path.isdir (path)

     如果 `path' 是 *note 现有的: 325. 目录，则返回 ‘True’。本方法会跟踪
     符号链接，因此，对于同一路径，*note islink(): 323. 和 *note
     isdir(): 327. 都可能为 ‘True’。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.path.islink (path)

     如果 `path' 指向的 *note 现有: 325. 目录条目是一个符号链接，则返回
     ‘True’。如果 Python 运行时不支持符号链接，则总是返回 ‘False’。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.path.ismount (path)

     如果路径 `path' 是 `挂载点' （文件系统中挂载其他文件系统的点），则
     返回 ‘True’。在 POSIX 上，该函数检查 `path' 的父目录 ‘`path'/..’ 是
     否在与 `path' 不同的设备上，或者 ‘`path'/..’ 和 `path' 是否指向同一
     设备上的同一 inode（这一检测挂载点的方法适用于所有 Unix 和 POSIX 变
     体）。本方法不能可靠地检测同一文件系统上的绑定挂载 (bind mount)。在
     Windows 上，盘符和共享 UNC 始终是挂载点，对于任何其他路径，将调用
     ‘GetVolumePathName’ 来查看它是否与输入的路径不同。

     3.4 版新加入: 支持在 Windows 上检测非根挂载点。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.path.join (path, *paths)

     智能地拼接一个或多个路径部分。 返回值是 `path' 和 `*paths' 的所有成
     员的拼接，其中每个非空部分后面都紧跟一个目录分隔符，最后一个部分除
     外，这意味着如果最后一个部分为空，则结果将以分隔符结尾。 如果某个部
     分为绝对路径，则之前的所有部分会被丢弃并从绝对路径部分开始继续拼接
     。

     在 Windows 上，遇到绝对路径部分（例如 ‘r'\foo'’）时，不会重置盘符。
     如果某部分路径包含盘符，则会丢弃所有先前的部分，并重置盘符。请注意
     ，由于每个驱动器都有一个“当前目录”，所以 ‘os.path.join("c:",
     "foo")’ 表示驱动器 ‘C:’ 上当前目录的相对路径 (‘c:foo’)，而不是
     ‘c:\foo’。

     3.6 版更變: 接受一个 *note 类路径对象: 472. 用于 `path' 和 `paths'
     。

 -- 函式: os.path.normcase (path)

     规范路径的大小写。在 Windows 上，将路径中的所有字符都转换为小写，并
     将正斜杠转换为反斜杠。在其他操作系统上返回原路径。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.path.normpath (path)

          通过折叠多余的分隔符和对上级目录的引用来标准化路径名，所以
          ‘A//B’、‘A/B/’、‘A/./B’ 和 ‘A/foo/../B’ 都会转换成 ‘A/B’。这个
          字符串操作可能会改变带有符号链接的路径的含义。在 Windows 上，
          本方法将正斜杠转换为反斜杠。要规范大小写，请使用 *note
          normcase(): 1d4e.。

          備註: 
               在 POSIX 系统上，根据 IEEE Std 1003.1 2013 Edition; 4.13
               Pathname Resolution(3)，如果一个路径名称以两个斜杠开始，
               则开始字符之后的第一个部分将以具体实现所定义的方式来解读
               ，但是超过两个开始字符则将被视为单个字符。

          3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.path.realpath (path)

     返回指定文件的规范路径，消除路径中存在的任何符号链接（如果操作系统
     支持）。

          備註: 当发生符号链接循环时，返回的路径将是该循环的某个组成部分
          ，但不能保证是哪个部分。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

     3.8 版更變: 在 Windows 上现在可以正确解析符号链接和交接点 (junction
     point)。

 -- 函式: os.path.relpath (path, start=os.curdir)

     返回从当前目录或可选的 `start' 目录至 `path' 的相对文件路径。 这只
     是一个路径计算：不会访问文件系统来确认 `path' 或 `start' 是否存在或
     其性质。 在 Windows 上，当 `path' 和 `start' 位于不同驱动器时将引发
     *note ValueError: 16d.。

     `start' 默认为 *note os.curdir: 1d4f.。

     *note 可用性: 1491.: Unix, Windows。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.path.samefile (path1, path2)

     如果两个路径都指向相同的文件或目录，则返回 ‘True’。这由设备号和
     inode 号确定，在任一路径上调用 *note os.stat(): 321. 失败则抛出异常
     。

     *note 可用性: 1491.: Unix, Windows。

     3.2 版更變: 添加了 Windows 支持。

     3.4 版更變: Windows现在使用与其他所有平台相同的实现。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.path.sameopenfile (fp1, fp2)

     如果文件描述符 `fp1' 和 `fp2' 指向相同文件，则返回 ‘True’。

     *note 可用性: 1491.: Unix, Windows。

     3.2 版更變: 添加了 Windows 支持。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.path.samestat (stat1, stat2)

     如果 stat 元组 `stat1' 和 `stat2' 指向相同文件，则返回 ‘True’。这些
     stat 元组可能是由 *note os.fstat(): 752.、*note os.lstat(): 322. 或
     *note os.stat(): 321. 返回的。本函数实现了 *note samefile(): 96d. 和
     *note sameopenfile(): 1d50. 底层所使用的比较过程。

     *note 可用性: 1491.: Unix, Windows。

     3.4 版更變: 添加了 Windows 支持。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.path.split (path)

     将路径 `path' 拆分为一对，即 ‘(head, tail)’，其中，`tail' 是路径的
     最后一部分，而 `head' 里是除最后部分外的所有内容。`tail' 部分不会包
     含斜杠，如果 `path' 以斜杠结尾，则 `tail' 将为空。如果 `path' 中没
     有斜杠，`head' 将为空。如果 `path' 为空，则 `head' 和 `tail' 均为空
     。`head' 末尾的斜杠会被去掉，除非它是根目录（即它仅包含一个或多个斜
     杠）。在所有情况下，‘join(head, tail)’ 指向的位置都与 `path' 相同（
     但字符串可能不同）。另请参见函数 *note dirname(): 1d45. 和 *note
     basename(): 1d44.。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.path.splitdrive (path)

     将路径 `path' 拆分为一对，即 ‘(drive, tail)’，其中 `drive' 是挂载点
     或空字符串。在没有驱动器概念的系统上，`drive' 将始终为空字符串。在
     所有情况下，‘drive + tail’ 都与 `path' 相同。

     在 Windows 上，本方法将路径拆分为驱动器/UNC 根节点和相对路径。

     如果路径 path 包含盘符，则 drive 将包含冒号之前的所有内容包括冒号本
     身:

          >>> splitdrive("c:/dir")
          ("c:", "/dir")

     如果路径 path 包含 UNC 路径，则 drive 将包含主机名和 share，直至第
     四个分隔符但不包括该分隔符:

          >>> splitdrive("//host/computer/dir")
          ("//host/computer", "/dir")

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.path.splitext (path)

     将路径名称 `path' 拆分为 ‘(root, ext)’ 对使得 ‘root + ext == path’，
     并且扩展名 `ext' 为空或以句点打头并最多只包含一个句点。

     如果路径 path 不包含扩展名，则 `ext' 将为 ‘''’:

          >>> splitext('bar')
          ('bar', '')

     如果路径 path 包含扩展名，则 `ext' 将被设为该扩展名，包括打头的句点
     。 请注意在其之前的句点将被忽略:

          >>> splitext('foo.bar.exe')
          ('foo.bar', '.exe')
          >>> splitext('/foo/bar.exe')
          ('/foo/bar', '.exe')

     Leading periods of the last component of the path are considered to
     be part of the root:

          >>> splitext('.cshrc')
          ('.cshrc', '')
          >>> splitext('/foo/....jpg')
          ('/foo/....jpg', '')

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- Data: os.path.supports_unicode_filenames

     如果（在文件系统限制下）允许将任意 Unicode 字符串用作文件名，则为
     ‘True’。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/posixpath.py

   (2) https://github.com/python/cpython/tree/3.9/Lib/ntpath.py

   (3) 
http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13


File: python.info,  Node: fileinput --- 迭代来自多个输入流的行,  Next: stat --- 解析 stat 结果,  Prev: os path --- 常用路径操作,  Up: 檔案與目錄存取

5.11.3 ‘fileinput’ — 迭代来自多个输入流的行
-------------------------------------------

`源代码:' Lib/fileinput.py(1)

__________________________________________________________________

此模块实现了一个辅助类和一些函数用来快速编写访问标准输入或文件列表的循环
。 如果你只想要读写一个文件请参阅 *note open(): 16f.。

典型用法为:

     import fileinput
     for line in fileinput.input():
         process(line)

此程序会迭代 ‘sys.argv[1:]’ 中列出的所有文件内的行，如果列表为空则会使用
‘sys.stdin’。 如果有一个文件名为 ‘'-'’，它也会被替换为 ‘sys.stdin’ 并且
可选参数 `mode' 和 `openhook' 会被忽略。 要指定替代文件列表，请将其作为
第一个参数传给 *note input(): 3cf.。 也允许使用单个文件。

所有文件都默认以文本模式打开，但你可以通过在调用 *note input(): 3cf. 或
*note FileInput: 3a4. 时指定 `mode' 形参来重载此行为。 如果在打开或读取
文件时发生了 I/O 错误，将会引发 *note OSError: 304.。

3.3 版更變: 原来会引发 *note IOError: a73.；现在它是 *note OSError: 304.
的别名。

如果 ‘sys.stdin’ 被使用超过一次，则第二次之后的使用将不返回任何行，除非
是被交互式的使用，或都是被显式地重置 (例如使用 ‘sys.stdin.seek(0)’)。

空文件打开后将立即被关闭；它们在文件列表中会被注意到的唯一情况只有当最后
打开的文件为空的时候。

反回的行不会对换行符做任何处理，这意味着文件中的最后一行可能不带换行符。

想要控制文件的打开方式，你可以通过将 `openhook' 形参传给 *note
fileinput.input(): 3cf. 或 *note FileInput(): 3a4. 来提供一个打开钩子。
此钩子必须为一个函数，它接受两个参数，`filename' 和 `mode'，并返回一个以
相应模式打开的文件类对象。 此模块已经提供了两个有用的钩子。

以下函数是此模块的初始接口：

 -- 函式: fileinput.input (files=None, inplace=False, backup='', *,
          mode='r', openhook=None)

     创建一个 *note FileInput: 3a4. 类的实例。 该实例将被用作此模块中函
     数的全局状态，并且还将在迭代期间被返回使用。 此函数的形参将被继续传
     递给 *note FileInput: 3a4. 类的构造器。

     *note FileInput: 3a4. 实例可以在 *note with: 7da. 语句中被用作上下
     文管理器。 在这个例子中，`input' 在 ‘with’ 语句结束后将会被关闭，即
     使发生了异常也是如此:

          with fileinput.input(files=('spam.txt', 'eggs.txt')) as f:
              for line in f:
                  process(line)

     3.2 版更變: 可以被用作上下文管理器。

     3.8 版更變: 关键字形参 `mode' 和 `openhook' 现在是仅限关键字形参。

下列函数会使用 *note fileinput.input(): 3cf. 所创建的全局状态；如果没有
活动的状态，则会引发 *note RuntimeError: 3dc.。

 -- 函式: fileinput.filename ()

     返回当前被读取的文件名。 在第一行被读取之前，返回 ‘None’。

 -- 函式: fileinput.fileno ()

     返回以整数表示的当前文件“文件描述符”。 当未打开文件时（处在第一行和
     文件之间），返回 ‘-1’。

 -- 函式: fileinput.lineno ()

     返回已被读取的累计行号。 在第一行被读取之前，返回 ‘0’。 在最后一个
     文件的最后一行被读取之后，返回该行的行号。

 -- 函式: fileinput.filelineno ()

     返回当前文件中的行号。 在第一行被读取之前，返回 ‘0’。 在最后一个文
     件的最后一行被读取之后，返回此文件中该行的行号。

 -- 函式: fileinput.isfirstline ()

     如果刚读取的行是其所在文件的第一行则返回 ‘True’，否则返回 ‘False’。

 -- 函式: fileinput.isstdin ()

     如果最后读取的行来自 ‘sys.stdin’ 则返回 ‘True’，否则返回 ‘False’。

 -- 函式: fileinput.nextfile ()

     关闭当前文件以使下次迭代将从下一个文件（如果存在）读取第一行；不是
     从该文件读取的行将不会被计入累计行数。 直到下一个文件的第一行被读取
     之后文件名才会改变。 在第一行被读取之前，此函数将不会生效；它不能被
     用来跳过第一个文件。 在最后一个文件的最后一行被读取之后，此函数将不
     再生效。

 -- 函式: fileinput.close ()

     关闭序列。

此模块所提供的实现了序列行为的类同样也可用于子类化：

 -- 類別: fileinput.FileInput (files=None, inplace=False, backup='', *,
          mode='r', openhook=None)

     类 *note FileInput: 3a4. 是一个实现；它的方法 *note filename():
     1d53, *note fileno(): 1d54, *note lineno(): 1d55, *note
     filelineno(): 1d56, *note isfirstline(): 1d57, *note isstdin():
     1d58, *note nextfile(): 1d59. 和 *note close(): 1d5a. 对应于此模块
     中具有相同名称的函数。 此外它还有一个 *note readline(): 1d5b. 方法
     可返回下一个输入行，以及一个 *note __getitem__(): 3a5. 方法，该方法
     实现了序列行为。 这种序列必须以严格的序列顺序来读写；随机读写和
     *note readline(): 1d5b. 不可以被混用。

     通过 `mode' 你可以指定要传给 *note open(): 16f. 的文件模式。 它必须
     为 ‘'r'’, ‘'rU'’, ‘'U'’ 和 ‘'rb'’ 中的一个。

     `openhook' 如果给出则必须为一个函数，它接受两个参数 `filename' 和
     `mode'，并相应地返回一个打开的文件类对象。 你不能同时使用 `inplace'
     和 `openhook'。

     *note FileInput: 3a4. 实例可以在 *note with: 7da. 语句中被用作上下
     文管理器。 在这个例子中，`input' 在 ‘with’ 语句结束后将会被关闭，即
     使发生了异常也是如此:

          with FileInput(files=('spam.txt', 'eggs.txt')) as input:
              process(input)

     3.2 版更變: 可以被用作上下文管理器。

     3.4 版後已棄用: ‘'rU'’ 和 ‘'U'’ 模式。

     3.8 版後已棄用: 对 *note __getitem__(): 3a5. 方法的支持已弃用。

     3.8 版更變: 关键字形参 `mode' 和 `openhook' 现在是仅限关键字形参。

`可选的原地过滤:' 如果传递了关键字参数 ‘inplace=True’ 给 *note
fileinput.input(): 3cf. 或 *note FileInput: 3a4. 构造器，则文件会被移至
备份文件并将标准输出定向到输入文件（如果已存在与备份文件同名的文件，它将
被静默地替换）。 这使得编写一个能够原地重写其输入文件的过滤器成为可能。
如果给出了 `backup' 形参 (通常形式为 ‘backup='.<some extension>'’)，它将
指定备份文件的扩展名，并且备份文件会被保留；默认情况下扩展名为 ‘'.bak'’
并且它会在输出文件关闭时被删除。 在读取标准输入时原地过滤会被禁用。

此模块提供了以下两种打开文件钩子：

 -- 函式: fileinput.hook_compressed (filename, mode)

     使用 *note gzip: 8b. 和 *note bz2: 13. 模块透明地打开 gzip 和 bzip2
     压缩的文件（通过扩展名 ‘'.gz'’ 和 ‘'.bz2'’ 来识别）。 如果文件扩展
     名不是 ‘'.gz'’ 或 ‘'.bz2'’，文件会以正常方式打开（即使用 *note
     open(): 16f. 并且不带任何解压操作）。

     使用示例: ‘fi =
     fileinput.FileInput(openhook=fileinput.hook_compressed)’

 -- 函式: fileinput.hook_encoded (encoding, errors=None)

     返回一个通过 *note open(): 16f. 打开每个文件的钩子，使用给定的
     `encoding' 和 `errors' 来读取文件。

     使用示例: ‘fi =
     fileinput.FileInput(openhook=fileinput.hook_encoded("utf-8",
     "surrogateescape"))’

     3.6 版更變: 添加了可选的 `errors' 形参。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/fileinput.py


File: python.info,  Node: stat --- 解析 stat 结果,  Next: filecmp --- 文件及目录的比较,  Prev: fileinput --- 迭代来自多个输入流的行,  Up: 檔案與目錄存取

5.11.4 ‘stat’ — 解析 ‘stat()’ 结果
----------------------------------

`源代码：' Lib/stat.py(1)

__________________________________________________________________

*note stat: f4. 模块定义了一些用于解析 *note os.stat(): 321, *note
os.fstat(): 752. 和 *note os.lstat(): 322. (如果它们存在) 输出结果的常量
和函数。 有关 ‘stat()’, ‘fstat()’ 和 ‘lstat()’ 调用的完整细节，请参阅你
的系统文档。

3.4 版更變: stat 模块是通过 C 实现来支持的。

*note stat: f4. 模块定义了以下函数来检测特定文件类型：

 -- 函式: stat.S_ISDIR (mode)

     如果 mode 来自一个目录则返回非零值。

 -- 函式: stat.S_ISCHR (mode)

     如果 mode 来自一个字符特殊设备文件则返回非零值。

 -- 函式: stat.S_ISBLK (mode)

     如果 mode 来自一个块特殊设备文件则返回非零值。

 -- 函式: stat.S_ISREG (mode)

     如果 mode 来自一个常规文件则返回非零值。

 -- 函式: stat.S_ISFIFO (mode)

     如果 mode 来自一个 FIFO (命名管道) 则返回非零值。

 -- 函式: stat.S_ISLNK (mode)

     如果 mode 来自一个符号链接则返回非零值。

 -- 函式: stat.S_ISSOCK (mode)

     如果 mode 来自一个套接字则返回非零值。

 -- 函式: stat.S_ISDOOR (mode)

     如果 mode 来自一个门则返回非零值。

     3.4 版新加入.

 -- 函式: stat.S_ISPORT (mode)

     如果 mode 来自一个事件端口则返回非零值。

     3.4 版新加入.

 -- 函式: stat.S_ISWHT (mode)

     如果 mode 来自一个白输出则返回非零值。

     3.4 版新加入.

定义了两个附加函数用于对文件模式进行更一般化的操作：

 -- 函式: stat.S_IMODE (mode)

     返回文件模式中可由 *note os.chmod(): b0f. 进行设置的部分 — 即文件的
     permission 位，加上 sticky 位、set-group-id 以及 set-user-id 位（在
     支持这些部分的系统上）。

 -- 函式: stat.S_IFMT (mode)

     返回文件模式中描述文件类型的部分（供上面的 ‘S_IS*()’ 函数使用）。

通常，你应当使用 ‘os.path.is*()’ 函数来检测文件的类型；这里提供的函数则
适用于当你要对同一文件执行多项检测并且希望避免每项检测的 ‘stat()’ 系统调
用开销的情况。 这些函数也适用于检测有关未被 *note os.path: c5. 处理的信
息，例如检测块和字符设备等。

示例:

     import os, sys
     from stat import *

     def walktree(top, callback):
         '''recursively descend the directory tree rooted at top,
            calling the callback function for each regular file'''

         for f in os.listdir(top):
             pathname = os.path.join(top, f)
             mode = os.stat(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)

另外还提供了一个附加的辅助函数用来将文件模式转换为人类易读的字符串：

 -- 函式: stat.filemode (mode)

     将文件模式转换为 ’-rwxrwxrwx’ 形式的字符串。

     3.3 版新加入.

     3.4 版更變: 此函数支持 *note S_IFDOOR: 9ba, *note S_IFPORT: 9bb.
     and *note S_IFWHT: 9bc.。

以下所有变量是一些简单的符号索引，用于访问 *note os.stat(): 321, *note
os.fstat(): 752. 或 *note os.lstat(): 322. 所返回的 10 条目元组。

 -- Data: stat.ST_MODE

     inode 保护模式。

 -- Data: stat.ST_INO

     Inode 号

 -- Data: stat.ST_DEV

     Inode 所在的设备。

 -- Data: stat.ST_NLINK

     Inode 拥有的链接数量。

 -- Data: stat.ST_UID

     所有者的用户 ID。

 -- Data: stat.ST_GID

     所有者的用户组ID。

 -- Data: stat.ST_SIZE

     以字节为单位的普通文件大小；对于某些特殊文件则是所等待的数据量。

 -- Data: stat.ST_ATIME

     上次访问的时间。

 -- Data: stat.ST_MTIME

     上次修改的时间。

 -- Data: stat.ST_CTIME

     操作系统所报告的 "ctime"。 在某些系统上（例如 Unix）是元数据的最后
     修改时间，而在其他系统上（例如 Windows）则是创建时间（请参阅系统平
     台的文档了解相关细节）。

对于“文件大小”的解析可因文件类型的不同而变化。 对于普通文件就是文件的字
节数。 对于大部分种类的 Unix（特别包括 Linux）的 FIFO 和套接字来说，“大
小”则是指在调用 *note os.stat(): 321, *note os.fstat(): 752. 或 *note
os.lstat(): 322. 时等待读取的字节数；这在某些时候很有用处，特别是在一个
非阻塞的打开后轮询这些特殊文件中的一个时。 其他字符和块设备的文件大小字
段的含义还会有更多变化，具体取决于底层系统调用的实现方式。

以下变量定义了在 *note ST_MODE: 9b9. 字段中使用的旗标。

使用上面的函数会比使用第一组旗标更容易移植：

 -- Data: stat.S_IFSOCK

     套接字。

 -- Data: stat.S_IFLNK

     符号链接。

 -- Data: stat.S_IFREG

     普通文件。

 -- Data: stat.S_IFBLK

     块设备。

 -- Data: stat.S_IFDIR

     目录。

 -- Data: stat.S_IFCHR

     字符设备。

 -- Data: stat.S_IFIFO

     先进先出。

 -- Data: stat.S_IFDOOR

     门。

     3.4 版新加入.

 -- Data: stat.S_IFPORT

     事件端口。

     3.4 版新加入.

 -- Data: stat.S_IFWHT

     白输出。

     3.4 版新加入.

     備註: *note S_IFDOOR: 9ba, *note S_IFPORT: 9bb. or *note S_IFWHT:
     9bc. 等文件类型在不受系统平台支持时会被定义为 0。

以下旗标还可以 *note os.chmod(): b0f. 的在 `mode' 参数中使用：

 -- Data: stat.S_ISUID

     设置 UID 位。

 -- Data: stat.S_ISGID

     设置分组 ID 位。 这个位有几种特殊用途。 对于目录它表示该目录将使用
     BSD 语义：在其中创建的文件将从目录继承其分组 ID，而不是从创建进程的
     有效分组 ID 继承，并且在其中创建的目录也将设置 *note S_ISGID: 1d79.
     位。 对于没有设置分组执行位 (*note S_IXGRP: 1d7a.) 的文件，设置分组
     ID 位表示强制性文件/记录锁定 (另请参见 *note S_ENFMT: 1d7b.)。

 -- Data: stat.S_ISVTX

     固定位。 当对目录设置该位时则意味着此目录中的文件只能由文件所有者、
     目录所有者或特权进程来重命名或删除。

 -- Data: stat.S_IRWXU

     文件所有者权限的掩码。

 -- Data: stat.S_IRUSR

     所有者具有读取权限。

 -- Data: stat.S_IWUSR

     所有者具有写入权限。

 -- Data: stat.S_IXUSR

     所有者具有执行权限。

 -- Data: stat.S_IRWXG

     组权限的掩码。

 -- Data: stat.S_IRGRP

     组具有读取权限。

 -- Data: stat.S_IWGRP

     组具有写入权限。

 -- Data: stat.S_IXGRP

     组具有执行权限。

 -- Data: stat.S_IRWXO

     其他人（不在组中）的权限掩码。

 -- Data: stat.S_IROTH

     其他人具有读取权限。

 -- Data: stat.S_IWOTH

     其他人具有写入权限。

 -- Data: stat.S_IXOTH

     其他人具有执行权限。

 -- Data: stat.S_ENFMT

     System V 执行文件锁定。 此旗标是与 *note S_ISGID: 1d79. 共享的：文
     件/记录锁定会针对未设置分组执行位 (*note S_IXGRP: 1d7a.) 的文件强制
     执行。

 -- Data: stat.S_IREAD

     Unix V7 中 *note S_IRUSR: 1d7e. 的同义词。

 -- Data: stat.S_IWRITE

     Unix V7 中 *note S_IWUSR: 1d7f. 的同义词。

 -- Data: stat.S_IEXEC

     Unix V7 中 *note S_IXUSR: 1d80. 的同义词。

以下旗标可以在 *note os.chflags(): b0e. 的 `flags' 参数中使用：

 -- Data: stat.UF_NODUMP

     不要转储文件。

 -- Data: stat.UF_IMMUTABLE

     文件不能被更改。

 -- Data: stat.UF_APPEND

     文件只能被附加。

 -- Data: stat.UF_OPAQUE

     当通过联合堆栈查看时，目录是不透明的。

 -- Data: stat.UF_NOUNLINK

     文件不能重命名或删除。

 -- Data: stat.UF_COMPRESSED

     The file is stored compressed (macOS 10.6+).

 -- Data: stat.UF_HIDDEN

     The file should not be displayed in a GUI (macOS 10.5+).

 -- Data: stat.SF_ARCHIVED

     文件可能已存档。

 -- Data: stat.SF_IMMUTABLE

     文件不能被更改。

 -- Data: stat.SF_APPEND

     文件只能被附加。

 -- Data: stat.SF_NOUNLINK

     文件不能重命名或删除。

 -- Data: stat.SF_SNAPSHOT

     文件有一个快照文件

See the *BSD or macOS systems man page ‘chflags(2)’ for more
information.

在 Windows 上，以下文件属性常量可被用来检测 *note os.stat(): 321. 所返回
的 ‘st_file_attributes’ 成员中的位。 请参阅 Windows API 文档(2) 了解有关
这些常量含义的详情。

 -- Data: stat.FILE_ATTRIBUTE_ARCHIVE
 -- Data: stat.FILE_ATTRIBUTE_COMPRESSED
 -- Data: stat.FILE_ATTRIBUTE_DEVICE
 -- Data: stat.FILE_ATTRIBUTE_DIRECTORY
 -- Data: stat.FILE_ATTRIBUTE_ENCRYPTED
 -- Data: stat.FILE_ATTRIBUTE_HIDDEN
 -- Data: stat.FILE_ATTRIBUTE_INTEGRITY_STREAM
 -- Data: stat.FILE_ATTRIBUTE_NORMAL
 -- Data: stat.FILE_ATTRIBUTE_NOT_CONTENT_INDEXED
 -- Data: stat.FILE_ATTRIBUTE_NO_SCRUB_DATA
 -- Data: stat.FILE_ATTRIBUTE_OFFLINE
 -- Data: stat.FILE_ATTRIBUTE_READONLY
 -- Data: stat.FILE_ATTRIBUTE_REPARSE_POINT
 -- Data: stat.FILE_ATTRIBUTE_SPARSE_FILE
 -- Data: stat.FILE_ATTRIBUTE_SYSTEM
 -- Data: stat.FILE_ATTRIBUTE_TEMPORARY
 -- Data: stat.FILE_ATTRIBUTE_VIRTUAL

     3.5 版新加入.

在 Windows 上，以下常量可被用来与 *note os.lstat(): 322. 所返回的
‘st_reparse_tag’ 成员进行比较。 这些是最主要的常量，而不是详尽的清单。

 -- Data: stat.IO_REPARSE_TAG_SYMLINK
 -- Data: stat.IO_REPARSE_TAG_MOUNT_POINT
 -- Data: stat.IO_REPARSE_TAG_APPEXECLINK

     3.8 版新加入.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/stat.py

   (2) 
https://msdn.microsoft.com/en-us/library/windows/desktop/gg258117.aspx


File: python.info,  Node: filecmp --- 文件及目录的比较,  Next: tempfile --- 生成临时文件和目录,  Prev: stat --- 解析 stat 结果,  Up: 檔案與目錄存取

5.11.5 ‘filecmp’ — 文件及目录的比较
-----------------------------------

`源代码:' Lib/filecmp.py(1)

__________________________________________________________________

*note filecmp: 7d. 模块定义了用于比较文件及目录的函数，并且可以选取多种
关于时间和准确性的折衷方案。对于文件的比较，另见 *note difflib: 36. 模块
。

*note filecmp: 7d. 模块定义了如下函数：

 -- 函式: filecmp.cmp (f1, f2, shallow=True)

     比较名为 `f1' 和 `f2' 的文件，如果它们似乎相等则返回 ‘True’ ，否则
     返回 ‘False’ 。

     如果 `shallow' 为真值且两个文件的 *note os.stat(): 321. 签名信息（
     文件类型、大小和修改时间）一致，则文件会被视为相同。

     在其他情况下，如果文件大小或内容不同则它们会被视为不同。

     需要注意，没有外部程序被该函数调用，这赋予了该函数可移植性与效率。

     该函数会缓存过去的比较及其结果，且在文件的 *note os.stat(): 321. 信
     息变化后缓存条目失效。所有的缓存可以通过 *note clear_cache(): 934.
     清除。

 -- 函式: filecmp.cmpfiles (dir1, dir2, common, shallow=True)

     比较在两个目录 `dir1' 和 `dir2' 中，由 `common' 所确定名称的文件。

     返回三组文件名列表： `match', `mismatch', `errors' 。 `match' 含有
     相匹配的文件， `mismatch' 含有那些不匹配的，然后 `errors' 列出那些
     未被比较文件的名称。如果文件不存在于两目录中的任一个，或者用户缺少
     读取它们的权限，又或者因为其他的一些原因而无法比较，那么这些文件将
     会被列在 `errors' 中。

     参数 `shallow' 具有同 *note filecmp.cmp(): f85. 一致的含义与默认值
     。

     例如， ‘cmpfiles('a', 'b', ['c', 'd/e'])’ 将会比较 ‘a/c’ 与 ‘b/c’ 以
     及 ‘a/d/e’ 与 ‘b/d/e’ 。 ‘'c'’ 和 ‘'d/e'’ 将会各自出现在返回的三个
     列表里的某一个列表中。

 -- 函式: filecmp.clear_cache ()

     清除 filecmp 缓存。如果一个文件过快地修改，以至于超过底层文件系统记
     录修改时间的精度，那么该函数可能有助于比较该类文件。

     3.4 版新加入.

* Menu:

* dircmp 类::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/filecmp.py


File: python.info,  Node: dircmp 类,  Up: filecmp --- 文件及目录的比较

5.11.5.1 ‘dircmp’ 类
....................

 -- 類別: filecmp.dircmp (a, b, ignore=None, hide=None)

     创建一个用于比较目录 `a' 和 `b' 的新的目录比较对象。 `ignore' 是需
     要忽略的文件名列表，且默认为 *note filecmp.DEFAULT_IGNORES: 935. 。
     `hide' 是需要隐藏的文件名列表，且默认为 ‘[os.curdir, os.pardir]’ 。

     *note dircmp: 936. 类如 *note filecmp.cmp(): f85. 中所描述的那样对
     文件进行 `shallow' 比较。

     *note dircmp: 936. 类提供以下方法：

      -- 成員函式: report ()

          将 `a' 与 `b' 之间的比较打印（到 *note sys.stdout: 41f. ）。

      -- 成員函式: report_partial_closure ()

          打印 `a' 与 `b' 及共同直接子目录的比较结果。

      -- 成員函式: report_full_closure ()

          打印 `a' 与 `b' 及共同子目录比较结果（递归地）。

     *note dircmp: 936. 类提供了一些有趣的属性，用以得到关于参与比较的目
     录树的各种信息。

     需要注意，通过 *note __getattr__(): 42a. 钩子，所有的属性将会惰性求
     值，因此如果只使用那些计算简便的属性，将不会有速度损失。

      -- 屬性: left

          目录 `a' 。

      -- 屬性: right

          目录 `b' 。

      -- 屬性: left_list

          经 `hide' 和 `ignore' 过滤，目录 `a' 中的文件与子目录。

      -- 屬性: right_list

          经 `hide' 和 `ignore' 过滤，目录 `b' 中的文件与子目录。

      -- 屬性: common

          同时存在于目录 `a' 和 `b' 中的文件和子目录。

      -- 屬性: left_only

          仅在目录 `a' 中的文件和子目录。

      -- 屬性: right_only

          仅在目录 `b' 中的文件和子目录。

      -- 屬性: common_dirs

          同时存在于目录 `a' 和 `b' 中的子目录。

      -- 屬性: common_files

          同时存在于目录 `a' 和 `b' 中的文件。

      -- 屬性: common_funny

          在目录 `a' 和 `b' 中类型不同的名字，或者那些 *note os.stat():
          321. 报告错误的名字。

      -- 屬性: same_files

          在目录 `a' 和 `b' 中使用类的文件比较操作符相等的文件。

      -- 屬性: diff_files

          在目录 `a' 和 `b' 中，根据类的文件比较操作符判定内容不等的文件
          。

      -- 屬性: funny_files

          在目录 `a' 和 `b' 中无法比较的文件。

      -- 屬性: subdirs

          一个将 *note common_dirs: 1dba. 中名称映射为 *note dircmp:
          936. 对象的字典。

 -- 屬性: filecmp.DEFAULT_IGNORES

     3.4 版新加入.

     默认被 *note dircmp: 936. 忽略的目录列表。

下面是一个简单的例子，使用 ‘subdirs’ 属性递归搜索两个目录以显示公共差异
文件：

     >>> 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)


File: python.info,  Node: tempfile --- 生成临时文件和目录,  Next: glob --- Unix 风格路径名模式扩展,  Prev: filecmp --- 文件及目录的比较,  Up: 檔案與目錄存取

5.11.6 ‘tempfile’ — 生成临时文件和目录
--------------------------------------

`源代码：' Lib/tempfile.py(1)

__________________________________________________________________

该模块用于创建临时文件和目录，它可以跨平台使用。*note TemporaryFile:
1dc3.、*note NamedTemporaryFile: e0e.、*note TemporaryDirectory: c96. 和
*note SpooledTemporaryFile: b7e. 是带有自动清理功能的高级接口，可用作上
下文管理器。*note mkstemp(): 1dc4. 和 *note mkdtemp(): 1dc5. 是低级函数
，使用完毕需手动清理。

所有由用户调用的函数和构造函数都带有参数，这些参数可以设置临时文件和临时
目录的路径和名称。该模块生成的文件名包括一串随机字符，在公共的临时目录中
，这些字符可以让创建文件更加安全。为了保持向后兼容性，参数的顺序有些奇怪
。所以为了代码清晰，建议使用关键字参数。

这个模块定义了以下内容供用户调用：

 -- 函式: tempfile.TemporaryFile (mode='w+b', buffering=-1,
          encoding=None, newline=None, suffix=None, prefix=None,
          dir=None, *, errors=None)

     返回一个 *note file-like object: 1dc6. （文件类对象）作为临时存储区
     域。创建该文件使用了与 *note mkstemp(): 1dc4. 相同的安全规则。它将
     在关闭后立即销毁（包括垃圾回收机制关闭该对象时）。在 Unix 下，该文
     件在目录中的条目根本不创建，或者创建文件后立即就被删除了，其他平台
     不支持此功能。您的代码不应依赖使用此功能创建的临时文件名称，因为它
     在文件系统中的名称可能是可见的，也可能是不可见的。

     生成的对象可以用作上下文管理器（参见 *note 示例: 1dc7.）。完成上下
     文或销毁临时文件对象后，临时文件将从文件系统中删除。

     `mode' 参数默认值为 ‘'w+b'’，所以创建的文件不用关闭，就可以读取或写
     入。因为用的是二进制模式，所以无论存的是什么数据，它在所有平台上都
     表现一致。`buffering'、`encoding'、`errors' 和 `newline' 的含义与
     *note open(): 16f. 中的相同。

     参数 `dir'、`prefix' 和 `suffix' 的含义和默认值都与它们在 *note
     mkstemp(): 1dc4. 中的相同。

     在 POSIX 平台上，它返回的对象是真实的文件对象。在其他平台上，它是一
     个文件类对象 (file-like object)，它的 ‘file’ 属性是底层的真实文件对
     象。

     如果可用，则使用 *note os.O_TMPFILE: 96f. 标志（仅限于 Linux，需要
     3.11 及更高版本的内核）。

     引发一个 ‘tempfile.mkstemp’ *note 审计事件: fa1.，附带参数
     ‘fullpath’。

     3.5 版更變: 如果可用，现在用的是 *note os.O_TMPFILE: 96f. 标志。

     3.8 版更變: 添加了 `errors' 参数。

 -- 函式: tempfile.NamedTemporaryFile (mode='w+b', buffering=-1,
          encoding=None, newline=None, suffix=None, prefix=None,
          dir=None, delete=True, *, errors=None)

     此函数执行的操作与 *note TemporaryFile(): 1dc3. 完全相同，但确保了
     该临时文件在文件系统中具有可见的名称（在 Unix 上表现为目录条目不取
     消链接）。从返回的文件类对象的 ‘name’ 属性中可以检索到文件名。在临
     时文件仍打开时，是否允许用文件名第二次打开文件，在各个平台上是不同
     的（在 Unix 上可以，但在 Windows NT 或更高版本上不行）。如果
     `delete' 为 true（默认值），则文件会在关闭后立即被删除。该函数返回
     的对象始终是文件类对象 (file-like object)，它的 ‘file’ 属性是底层的
     真实文件对象。文件类对象可以像普通文件一样在 *note with: 7da. 语句
     中使用。

     引发一个 ‘tempfile.mkstemp’ *note 审计事件: fa1.，附带参数
     ‘fullpath’。

     3.8 版更變: 添加了 `errors' 参数。

 -- 函式: tempfile.SpooledTemporaryFile (max_size=0, mode='w+b',
          buffering=-1, encoding=None, newline=None, suffix=None,
          prefix=None, dir=None, *, errors=None)

     此函数执行的操作与 *note TemporaryFile(): 1dc3. 完全相同，但会将数
     据缓存在内存中，直到文件大小超过 `max_size'，或调用文件的
     ‘fileno()’ 方法为止，此时数据会被写入磁盘，并且写入操作与 *note
     TemporaryFile(): 1dc3. 相同。

     此函数生成的文件对象有一个额外的方法——‘rollover()’，可以忽略文件大
     小，让文件立即写入磁盘。

     返回的对象是文件类对象 (file-like object)，它的 ‘_file’ 属性是
     *note io.BytesIO: 88a. 或 *note io.TextIOWrapper: 6ea. 对象（取决于
     指定的是二进制模式还是文本模式）或真实的文件对象（取决于是否已调用
     ‘rollover()’）。文件类对象可以像普通文件一样在 *note with: 7da. 语
     句中使用。

     3.3 版更變: 现在，文件的 truncate 方法可接受一个 ‘size’ 参数。

     3.8 版更變: 添加了 `errors' 参数。

 -- 函式: tempfile.TemporaryDirectory (suffix=None, prefix=None,
          dir=None)

     此函数会安全地创建一个临时目录，且使用与 *note mkdtemp(): 1dc5. 相
     同的规则。此函数返回的对象可用作上下文管理器（参见 *note 示例:
     1dc7.）。完成上下文或销毁临时目录对象后，新创建的临时目录及其所有内
     容将从文件系统中删除。

     可以从返回对象的 ‘name’ 属性中找到临时目录的名称。当返回的对象用作
     上下文管理器时，这个 ‘name’ 会作为 *note with: 7da. 语句中 ‘as’ 子
     句的目标（如果有 as 的话）。

     可以调用 ‘cleanup()’ 方法来手动清理目录。

     引发一个 ‘tempfile.mkdtemp’ *note 审计事件: fa1.，附带参数
     ‘fullpath’。

     3.2 版新加入.

 -- 函式: tempfile.mkstemp (suffix=None, prefix=None, dir=None,
          text=False)

     以最安全的方式创建一个临时文件。假设所在平台正确实现了 *note
     os.open(): 758. 的 *note os.O_EXCL: 1dc8. 标志，则创建文件时不会有
     竞争的情况。该文件只能由创建者读写，如果所在平台用权限位来标记文件
     是否可执行，那么没有人有执行权。文件描述符不会过继给子进程。

     与 *note TemporaryFile(): 1dc3. 不同，*note mkstemp(): 1dc4. 用户用
     完临时文件后需要自行将其删除。

     如果 `suffix' 不是 ‘None’ 则文件名将以该后缀结尾，是 ‘None’ 则没有
     后缀。*note mkstemp(): 1dc4. 不会在文件名和后缀之间加点，如果需要加
     一个点号，请将其放在 `suffix' 的开头。

     如果 `prefix' 不是 ‘None’，则文件名将以该前缀开头，是 ‘None’ 则使用
     默认前缀。默认前缀是 *note gettempprefix(): 1dc9. 或 *note
     gettempprefixb(): 1dca. 函数的返回值（自动调用合适的函数）。

     如果 `dir' 不为 ‘None’，则在指定的目录创建文件，是 ‘None’ 则使用默
     认目录。默认目录是从一个列表中选择出来的，这个列表不同平台不一样，
     但是用户可以设置 `TMPDIR'、`TEMP' 或 `TMP' 环境变量来设置目录的位置
     。因此，不能保证生成的临时文件路径很规范，比如，通过 ‘os.popen()’ 将
     路径传递给外部命令时仍需要加引号。

     如果 `suffix'、`prefix' 和 `dir' 中的任何一个不是 ‘None’，就要保证
     它们是同一数据类型。如果它们是 bytes，则返回的名称的类型就是 bytes
     而不是 str。如果确实要用默认参数，但又想要返回值是 bytes 类型，请传
     入 ‘suffix=b''’。

     如果指定了 `text' 且为真值，文件会以文本模式打开。 否则，文件（默认
     ）会以二进制模式打开。

     *note mkstemp(): 1dc4. 返回一个元组，元组中第一个元素是句柄，它是一
     个系统级句柄，指向一个打开的文件（等同于 *note os.open(): 758. 的返
     回值），第二元素是该文件的绝对路径。

     引发一个 ‘tempfile.mkstemp’ *note 审计事件: fa1.，附带参数
     ‘fullpath’。

     3.5 版更變: 现在，`suffix'、`prefix' 和 `dir' 可以以 bytes 类型按顺
     序提供，以获得 bytes 类型的返回值。之前只允许使用 str。`suffix' 和
     `prefix' 现在可以接受 ‘None’，并且默认为 ‘None’ 以使用合适的默认值
     。

     3.6 版更變: `dir' 参数现在可接受一个路径类对象 (*note path-like
     object: 472.)。

 -- 函式: tempfile.mkdtemp (suffix=None, prefix=None, dir=None)

     以最安全的方式创建一个临时目录，创建该目录时不会有竞争的情况。该目
     录只能由创建者读取、写入和搜索。

     *note mkdtemp(): 1dc5. 用户用完临时目录后需要自行将其删除。

     `prefix'、`suffix' 和 `dir' 的含义与它们在 *note mkstemp(): 1dc4. 中
     的相同。

     *note mkdtemp(): 1dc5. 返回新目录的绝对路径。

     引发一个 ‘tempfile.mkdtemp’ *note 审计事件: fa1.，附带参数
     ‘fullpath’。

     3.5 版更變: 现在，`suffix'、`prefix' 和 `dir' 可以以 bytes 类型按顺
     序提供，以获得 bytes 类型的返回值。之前只允许使用 str。`suffix' 和
     `prefix' 现在可以接受 ‘None’，并且默认为 ‘None’ 以使用合适的默认值
     。

     3.6 版更變: `dir' 参数现在可接受一个路径类对象 (*note path-like
     object: 472.)。

 -- 函式: tempfile.gettempdir ()

     返回放置临时文件的目录的名称。这个方法的返回值就是本模块所有函数的
     `dir' 参数的默认值。

     Python 搜索标准目录列表，以找到调用者可以在其中创建文件的目录。这个
     列表是：

       1. ‘TMPDIR’ 环境变量指向的目录。

       2. ‘TEMP’ 环境变量指向的目录。

       3. ‘TMP’ 环境变量指向的目录。

       4. 与平台相关的位置：

             * 在 Windows 上，依次为 ‘C:\TEMP’、‘C:\TMP’、‘\TEMP’ 和
               ‘\TMP’。

             * 在所有其他平台上，依次为 ‘/tmp’、‘/var/tmp’ 和
               ‘/usr/tmp’。

       5. 不得已时，使用当前工作目录。

     搜索的结果会缓存起来，参见下面 *note tempdir: 1dcc. 的描述。

 -- 函式: tempfile.gettempdirb ()

     与 *note gettempdir(): 1dcb. 相同，但返回值为字节类型。

     3.5 版新加入.

 -- 函式: tempfile.gettempprefix ()

     返回用于创建临时文件的文件名前缀，它不包含目录部分。

 -- 函式: tempfile.gettempprefixb ()

     与 *note gettempprefix(): 1dc9. 相同，但返回值为字节类型。

     3.5 版新加入.

本模块使用一个全局变量来存储由 *note gettempdir(): 1dcb. 返回的临时文件
目录路径。可以直接给它赋值，这样可以覆盖自动选择的路径，但是不建议这样做
。本模块中的所有函数都带有一个 `dir' 参数，该参数可用于指定目录，这是推
荐的方法。

 -- Data: tempfile.tempdir

     当设置为 ‘None’ 以外的其他值时，此变量将决定本模块所有函数的 `dir'
     参数的默认值。

     如果在调用除 *note gettempprefix(): 1dc9. 外的上述任何函数时
     ‘tempdir’ 为 ‘None’ (默认值) 则它会按照 *note gettempdir(): 1dcb. 中
     所描述的算法来初始化。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/tempfile.py


File: python.info,  Node: 示例<6>,  Next: 已弃用的函数和变量,  Up: tempfile --- 生成临时文件和目录

5.11.6.1 示例
.............

以下是 *note tempfile: 103. 模块典型用法的一些示例:

     >>> 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


File: python.info,  Node: 已弃用的函数和变量,  Prev: 示例<6>,  Up: tempfile --- 生成临时文件和目录

5.11.6.2 已弃用的函数和变量
...........................

创建临时文件有一种历史方法，首先使用 *note mktemp(): f7d. 函数生成一个文
件名，然后使用该文件名创建文件。不幸的是，这是不安全的，因为在调用 *note
mktemp(): f7d. 与随后尝试创建文件的进程之间的时间里，其他进程可能会使用
该名称创建文件。解决方案是将两个步骤结合起来，立即创建文件。这个方案目前
被 *note mkstemp(): 1dc4. 和上述其他函数所采用。

 -- 函式: tempfile.mktemp (suffix='', prefix='tmp', dir=None)

     2.3 版後已棄用: 使用 *note mkstemp(): 1dc4. 来代替。

     返回一个绝对路径，这个路径指向的文件在调用本方法时不存在。
     `prefix'、`suffix' 和 `dir' 参数与 *note mkstemp(): 1dc4. 中的同名
     参数类似，不同之处在于不支持字节类型的文件名，不支持 ‘suffix=None’
     和 ‘prefix=None’。

          警告: 使用此功能可能会在程序中引入安全漏洞。当你开始使用本方法
          返回的文件执行任何操作时，可能有人已经捷足先登了。*note
          mktemp(): f7d. 的功能可以很轻松地用 *note
          NamedTemporaryFile(): e0e. 代替，当然需要传递 ‘delete=False’ 参
          数:

               >>> 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


File: python.info,  Node: glob --- Unix 风格路径名模式扩展,  Next: fnmatch --- Unix 文件名模式匹配,  Prev: tempfile --- 生成临时文件和目录,  Up: 檔案與目錄存取

5.11.7 ‘glob’ — Unix 风格路径名模式扩展
---------------------------------------

`源代码:' Lib/glob.py(1)

__________________________________________________________________

*note glob: 88. 模块可根据 Unix 终端所用规则找出所有匹配特定模式的路径名
，但会按不确定的顺序返回结果。 波浪号扩展不会生效，但 ‘*’, ‘?’ 以及表示
为 ‘[]’ 的字符范围将被正确地匹配。 这是通过配合使用 *note os.scandir():
389. 和 *note fnmatch.fnmatch(): 1dd3. 函数来实现的，而不是通过实际发起
调用子终端。 请注意不同于 *note fnmatch.fnmatch(): 1dd3.，*note glob:
88. 会将以点号 (‘.’) 开头的文件名作为特殊情况来处理。 （对于波浪号和终端
变量扩展，请使用 *note os.path.expanduser(): 32c. 和 *note
os.path.expandvars(): e09.。）

对于字面值匹配，请将原字符用方括号括起来。 例如，‘'[?]'’ 将匹配字符
‘'?'’。

也參考
......

*note pathlib: c8. 模块提供高级路径对象。

 -- 函式: glob.glob (pathname, *, recursive=False)

     返回匹配 `pathname' 的可能为空的路径名列表，其中的元素必须为包含路
     径信息的字符串。 `pathname' 可以是绝对路径 (如
     ‘/usr/src/Python-1.5/Makefile’) 或相对路径 (如
     ‘../../Tools/*/*.gif’)，并且可包含 shell 风格的通配符。 结果也将包
     含无效的符号链接（与在 shell 中一样）。 结果是否排序取决于具体文件
     系统。 如果某个符合条件的文件在调用此函数期间被移除或添加，是否包括
     该文件的路径是没有规定的。

     如果 `recursive' 为真值，则模式 "‘**’" 将匹配目录中的任何文件以及零
     个或多个目录、子目录和符号链接。 如果模式加了一个 *note os.sep:
     1dd4. 或 *note os.altsep: 1dd5. 则将不匹配文件。

     引发一个 *note 审计事件: fa1. ‘glob.glob’ 附带参数 ‘pathname’,
     ‘recursive’。

          備註: 在一个较大的目录树中使用 "‘**’" 模式可能会消耗非常多的时
          间。

     3.5 版更變: 支持使用 "‘**’" 的递归 glob。

 -- 函式: glob.iglob (pathname, *, recursive=False)

     返回一个 *note iterator: 1171.，它会产生与 *note glob(): 88. 相同的
     结果，但不会实际地同时保存它们。

     引发一个 *note 审计事件: fa1. ‘glob.glob’ 附带参数 ‘pathname’,
     ‘recursive’。

 -- 函式: glob.escape (pathname)

     转义所有特殊字符 (‘'?'’, ‘'*'’ 和 ‘'['’)。 这适用于当你想要匹配可能
     带有特殊字符的任意字符串字面值的情况。 在 drive/UNC 共享点中的特殊
     字符不会被转义，例如在 Windows 上 ‘escape('//?/c:/Quo vadis?.txt')’
     将返回 ‘'//?/c:/Quo vadis[?].txt'’。

     3.4 版新加入.

例如，考虑一个包含以下内容的目录：文件 ‘1.gif’, ‘2.txt’, ‘card.gif’ 以及
一个子目录 ‘sub’ 其中只包含一个文件 ‘3.txt’.  *note glob(): 88. 将产生如
下结果。 请注意路径的任何开头部分都将被保留。:

     >>> 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/']

如果目录包含以 ‘.’ 打头的文件，它们默认将不会被匹配。 例如，考虑一个包含
‘card.gif’ 和 ‘.card.gif’ 的目录:

     >>> import glob
     >>> glob.glob('*.gif')
     ['card.gif']
     >>> glob.glob('.c*')
     ['.card.gif']

也參考
......

模块 *note fnmatch: 7f.

     Shell 风格文件名（而非路径）扩展

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/glob.py


File: python.info,  Node: fnmatch --- Unix 文件名模式匹配,  Next: linecache --- 随机读写文本行,  Prev: glob --- Unix 风格路径名模式扩展,  Up: 檔案與目錄存取

5.11.8 ‘fnmatch’ — Unix 文件名模式匹配
--------------------------------------

`源代码:' Lib/fnmatch.py(1)

__________________________________________________________________

此模块提供了 Unix shell 风格的通配符，它们 `并不' 等同于正则表达式（关于
后者的文档参见 *note re: dd. 模块）。 shell 风格通配符所使用的特殊字符如
下：

模式             意义
                 
----------------------------------------------------------
                 
‘*’              匹配所有
                 
                 
‘?’              匹配任何单个字符
                 
                 
‘[seq]’          匹配 `seq' 中的任何字符
                 
                 
‘[!seq]’         匹配任何不在 `seq' 中的字符
                 

对于字面值匹配，请将原字符用方括号括起来。 例如，‘'[?]'’ 将匹配字符
‘'?'’。

注意文件名分隔符 (Unix 上为 ‘'/'’) `不是' 此模块所特有的。 请参见 *note
glob: 88. 模块了解文件名扩展 (*note glob: 88. 使用 *note filter(): 1dd8.
来匹配文件名的各个部分)。 类似地，以一个句点打头的文件名也不是此模块所特
有的，可以通过 ‘*’ 和 ‘?’ 模式来匹配。

 -- 函式: fnmatch.fnmatch (filename, pattern)

     检测 `filename' 字符串是否匹配 `pattern' 字符串，返回 *note True:
     593. 或 *note False: 48e.。 两个形参都会使用 *note
     os.path.normcase(): 1d4e. 进行大小写正规化。 *note fnmatchcase():
     1dd9. 可被用于执行大小写敏感的比较，无论这是否为所在操作系统的标准
     。

     这个例子将打印当前目录下带有扩展名 ‘.txt’ 的所有文件名:

          import fnmatch
          import os

          for file in os.listdir('.'):
              if fnmatch.fnmatch(file, '*.txt'):
                  print(file)

 -- 函式: fnmatch.fnmatchcase (filename, pattern)

     检测 `filename' 是否匹配 `pattern'，返回 *note True: 593. 或 *note
     False: 48e.；此比较是大小写敏感的，并且不会应用 *note
     os.path.normcase(): 1d4e.。

 -- 函式: fnmatch.filter (names, pattern)

     基于可迭代对象 `names' 中匹配 `pattern' 的元素构造一个列表。 它等价
     于 ‘[n for n in names if fnmatch(n, pattern)]’，但实现得更有效率。

 -- 函式: fnmatch.translate (pattern)

     返回 shell 风格 `pattern' 转换成的正则表达式以便用于 *note
     re.match(): c83.。

     示例:

          >>> 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'>

也參考
......

模块 *note glob: 88.

     Unix shell 风格路径扩展。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/fnmatch.py


File: python.info,  Node: linecache --- 随机读写文本行,  Next: shutil --- 高阶文件操作,  Prev: fnmatch --- Unix 文件名模式匹配,  Up: 檔案與目錄存取

5.11.9 ‘linecache’ — 随机读写文本行
-----------------------------------

`源代码:' Lib/linecache.py(1)

__________________________________________________________________

*note linecache: a8. 模块允许从一个 Python 源文件中获取任意的行，并会尝
试使用缓存进行内部优化，常应用于从单个文件读取多行的场合。 此模块被
*note traceback: 11c. 模块用来提取源码行以便包含在格式化的回溯中。

*note tokenize.open(): 1ddc. 函数被用于打开文件。 此函数使用 *note
tokenize.detect_encoding(): 1ddd. 来获取文件的编码格式；如果未指明编码格
式，则默认编码为 UTF-8。

*note linecache: a8. 模块定义了下列函数：

 -- 函式: linecache.getline (filename, lineno, module_globals=None)

     从名为 `filename' 的文件中获取 `lineno' 行，此函数绝不会引发异常 —
     出现错误时它将返回 ‘''’ (所有找到的行都将包含换行符作为结束)。

     如果找不到名为 `filename' 的文件，此函数会先在 `module_globals' 中
     检查 PEP 302(2) ‘__loader__’。 如果存在这样的加载器并且它定义了
     ‘get_source’ 方法，则由该方法来确定源行 (如果 ‘get_source()’ 返回
     ‘None’，则该函数返回 ‘''’)。 最后，如果 `filename' 是一个相对路径文
     件名，则它会在模块搜索路径 ‘sys.path’ 中按条目的相对位置进行查找。

 -- 函式: linecache.clearcache ()

     清空缓存。 如果你不再需要之前使用 *note getline(): 7fa. 从文件读取
     的行即可使用此函数。

 -- 函式: linecache.checkcache (filename=None)

     检查缓存有效性。 如果缓存中的文件在磁盘上发生了改变，而你需要更新后
     的版本即可使用此函数。 如果省略了 `filename'，它会检查缓存中的所有
     条目。

 -- 函式: linecache.lazycache (filename, module_globals)

     捕获有关某个非基于文件的模块的足够细节信息，以允许稍后再通过 *note
     getline(): 7fa. 来获取其中的行，即使当稍后调用时 `module_globals' 为
     ‘None’。 这可以避免在实际需要读取行之前执行 I/O，也不必始终保持模块
     全局变量。

     3.5 版新加入.

示例:

     >>> import linecache
     >>> linecache.getline(linecache.__file__, 8)
     'import sys\n'

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/linecache.py

   (2) https://www.python.org/dev/peps/pep-0302


File: python.info,  Node: shutil --- 高阶文件操作,  Prev: linecache --- 随机读写文本行,  Up: 檔案與目錄存取

5.11.10 ‘shutil’ — 高阶文件操作
-------------------------------

`源代码：' Lib/shutil.py(1)

__________________________________________________________________

*note shutil: e9. 模块提供了一系列对文件和文件集合的高阶操作。 特别是提
供了一些支持文件拷贝和删除的函数。 对于单个文件的操作，请参阅 *note os:
c4. 模块。

     警告: 即便是高阶文件拷贝函数 (*note shutil.copy(): 383, *note
     shutil.copy2(): 384.) 也无法拷贝所有的文件元数据。

     在 POSIX 平台上，这意味着将丢失文件所有者和组以及 ACL 数据。 在 Mac
     OS 上，资源钩子和其他元数据不被使用。 这意味着将丢失这些资源并且文
     件类型和创建者代码将不正确。 在 Windows 上，将不会拷贝文件所有者、
     ACL 和替代数据流。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/shutil.py


File: python.info,  Node: 目录和文件操作,  Next: 归档操作,  Up: shutil --- 高阶文件操作

5.11.10.1 目录和文件操作
........................

 -- 函式: shutil.copyfileobj (fsrc, fdst[, length])

     将文件类对象 `fsrc' 的内容拷贝到文件类对象 `fdst'。 整数值 `length'
     如果给出则为缓冲区大小。 特别地， `length' 为负值表示拷贝数据时不对
     源数据进行分块循环处理；默认情况下会分块读取数据以避免不受控制的内
     存消耗。 请注意如果 `fsrc' 对象的当前文件位置不为 0，则只有从当前文
     件位置到文件末尾的内容会被拷贝。

 -- 函式: shutil.copyfile (src, dst, *, follow_symlinks=True)

     将名为 `src' 的文件的内容（不包括元数据）拷贝到名为 `dst' 的文件并
     以尽可能高效的方式返回 `dst'。 `src' 和 `dst' 均为路径类对象或以字
     符串形式给出的路径名。

     `dst' 必须是完整的目标文件名；对于接受目标目录路径的拷贝请参见
     *note copy(): 383.。 如果 `src' 和 `dst' 指定了同一个文件，则将引发
     *note SameFileError: 99a.。

     目标位置必须是可写的；否则将引发 *note OSError: 304. 异常。 如果
     `dst' 已经存在，它将被替换。 特殊文件如字符或块设备以及管道无法用此
     函数来拷贝。

     如果 `follow_symlinks' 为假值且 `src' 为符号链接，则将创建一个新的
     符号链接而不是拷贝 `src' 所指向的文件。

     引发一个 *note 审计事件: fa1. ‘shutil.copyfile’ 附带参数 ‘src’,
     ‘dst’。

     3.3 版更變: 曾经是引发 *note IOError: a73. 而不是 *note OSError:
     304.。 增加了 `follow_symlinks' 参数。 现在是返回 `dst'。

     3.4 版更變: 引发 *note SameFileError: 99a. 而不是 *note Error:
     999.。 由于前者是后者的子类，此改变是向后兼容的。

     3.8 版更變: 可能会在内部使用平台专属的快速拷贝系统调用以更高效地拷
     贝文件。 参见 *note 依赖于具体平台的高效拷贝操作: 388. 一节。

 -- 例外: shutil.SameFileError

     此异常会在 *note copyfile(): 382. 中的源和目标为同一文件时被引发。

     3.4 版新加入.

 -- 函式: shutil.copymode (src, dst, *, follow_symlinks=True)

     从 `src' 拷贝权限位到 `dst'。 文件的内容、所有者和分组将不受影响。
     `src' 和 `dst' 均为路径类对象或字符串形式的路径名。 如果
     `follow_symlinks' 为假值，并且 `src' 和 `dst' 均为符号链接，*note
     copymode(): 1de4. 将尝试修改 `dst' 本身的模式（而非它所指向的文件）
     。 此功能并不是在所有平台上均可用；请参阅 *note copystat(): b52. 了
     解详情。 如果 *note copymode(): 1de4. 无法修改本机平台上的符号链接
     ，而它被要求这样做，它将不做任何操作即返回。

     引发一个 *note 审计事件: fa1. ‘shutil.copymode’ 附带参数 ‘src’,
     ‘dst’。

     3.3 版更變: 加入 `follow_symlinks' 参数。

 -- 函式: shutil.copystat (src, dst, *, follow_symlinks=True)

     从 `src' 拷贝权限位、最近访问时间、最近修改时间以及旗标到 `dst'。 在
     Linux上，*note copystat(): b52. 还会在可能的情况下拷贝“扩展属性”。
     文件的内容、所有者和分组将不受影响。 `src' 和 `dst' 均为路径类对象
     或字符串形式的路径名。

     如果 `follow_symlinks' 为假值，并且 `src' 和 `dst' 均指向符号链接，
     *note copystat(): b52. 将作用于符号链接本身而非该符号链接所指向的文
     件 — 从 `src' 符号链接读取信息，并将信息写入 `dst' 符号链接。

          備註: 并非所有平台者提供检查和修改符号链接的功能。 Python 本身
          可以告诉你哪些功能是在本机上可用的。

             * 如果 ‘os.chmod in os.supports_follow_symlinks’ 为 ‘True’，
               则 *note copystat(): b52. 可以修改符号链接的权限位。

             * 如果 ‘os.utime in os.supports_follow_symlinks’ 为 ‘True’，
               则 *note copystat(): b52. 可以修改符号链接的最近访问和修
               改时间。

             * 如果 ‘os.chflags in os.supports_follow_symlinks’ 为
               ‘True’，则 *note copystat(): b52. 可以修改符号链接的旗标
               。 (‘os.chflags’ 不是在所有平台上均可用。)

          在此功能部分或全部不可用的平台上，当被要求修改一个符号链接时，
          *note copystat(): b52. 将尽量拷贝所有内容。 *note copystat():
          b52. 一定不会返回失败信息。

          更多信息请参阅 *note os.supports_follow_symlinks: 1de5.。

     引发一个 *note 审计事件: fa1. ‘shutil.copystat’ 附带参数 ‘src’,
     ‘dst’。

     3.3 版更變: 添加了 `follow_symlinks' 参数并且支持 Linux 扩展属性。

 -- 函式: shutil.copy (src, dst, *, follow_symlinks=True)

     将文件 `src' 拷贝到文件或目录 `dst'。 `src' 和 `dst' 应为 *note
     路径类对象: 472. 或字符串。 如果 `dst' 指定了一个目录，文件将使用
     `src' 中的基准文件名拷贝到 `dst' 中。 将返回新创建文件所对应的路径
     。

     如果 `follow_symlinks' 为假值且 `src' 为符号链接，则 `dst' 也将被创
     建为符号链接。 如果 `follow_symlinks' 为真值且 `src' 为符号链接，
     `dst' 将成为 `src' 所指向的文件的一个副本。

     *note copy(): 383. 会拷贝文件数据和文件的权限模式 (参见 *note
     os.chmod(): b0f.)。 其他元数据，例如文件的创建和修改时间不会被保留
     。 要保留所有原有的元数据，请改用 *note copy2(): 384. 。

     引发一个 *note 审计事件: fa1. ‘shutil.copyfile’ 附带参数 ‘src’,
     ‘dst’。

     引发一个 *note 审计事件: fa1. ‘shutil.copymode’ 附带参数 ‘src’,
     ‘dst’。

     3.3 版更變: 添加了 `follow_symlinks' 参数。 现在会返回新创建文件的
     路径。

     3.8 版更變: 可能会在内部使用平台专属的快速拷贝系统调用以更高效地拷
     贝文件。 参见 *note 依赖于具体平台的高效拷贝操作: 388. 一节。

 -- 函式: shutil.copy2 (src, dst, *, follow_symlinks=True)

     类似于 *note copy(): 383.，区别在于 *note copy2(): 384. 还会尝试保
     留文件的元数据。

     当 `follow_symlinks' 为假值且 `src' 为符号链接时，*note copy2():
     384. 会尝试将来自 `src' 符号链接的所有元数据拷贝到新创建的 `dst' 符
     号链接。 但是，此功能不是在所有平台上均可用。 在此功能部分或全部不
     可用的平台上，*note copy2(): 384. 将尽量保留所有元数据；*note
     copy2(): 384. 一定不会由于无法保留文件元数据而引发异常。

     *note copy2(): 384. 会使用 *note copystat(): b52. 来拷贝文件元数据
     。 请参阅 *note copystat(): b52. 了解有关修改符号链接元数据的平台支
     持的更多信息。

     引发一个 *note 审计事件: fa1. ‘shutil.copyfile’ 附带参数 ‘src’,
     ‘dst’。

     引发一个 *note 审计事件: fa1. ‘shutil.copystat’ 附带参数 ‘src’,
     ‘dst’。

     3.3 版更變: 添加了 `follow_symlinks' 参数，还会尝试拷贝扩展文件系统
     属性（目前仅限 Linux）。 现在会返回新创建文件的路径。

     3.8 版更變: 可能会在内部使用平台专属的快速拷贝系统调用以更高效地拷
     贝文件。 参见 *note 依赖于具体平台的高效拷贝操作: 388. 一节。

 -- 函式: shutil.ignore_patterns (*patterns)

     这个工厂函数会创建一个函数，它可被用作 *note copytree(): 347. 的
     `ignore' 可调用对象参数，以忽略那些匹配所提供的 glob 风格的
     `patterns' 之一的文件和目录。 参见以下示例。

 -- 函式: shutil.copytree (src, dst, symlinks=False, ignore=None,
          copy_function=copy2, ignore_dangling_symlinks=False,
          dirs_exist_ok=False)

     将以 `src' 为根起点的整个目录树拷贝到名为 `dst' 的目录并返回目标目
     录。 `dirs_exist_ok' 指明是否要在 `dst' 或任何丢失的父目录已存在的
     情况下引发异常。

     目录的权限和时间会通过 *note copystat(): b52. 来拷贝，单个文件则会
     使用 *note copy2(): 384. 来拷贝。

     如果 `symlinks' 为真值，源目录树中的符号链接会在新目录树中表示为符
     号链接，并且原链接的元数据在平台允许的情况下也会被拷贝；如果为假值
     或省略，则会将被链接文件的内容和元数据拷贝到新目录树。

     当 `symlinks' 为假值时，如果符号链接所指向的文件不存在，则会在拷贝
     进程的末尾将一个异常添加到 *note Error: 999. 异常中的错误列表。 如
     果你希望屏蔽此异常那就将可选的 `ignore_dangling_symlinks' 旗标设为
     真值。 请注意此选项在不支持 *note os.symlink(): b17. 的平台上将不起
     作用。

     如果给出了 `ignore'，它必须是一个可调用对象，该对象将接受 *note
     copytree(): 347. 所访问的目录以及 *note os.listdir(): b1c. 所返回的
     目录内容列表作为其参数。 由于 *note copytree(): 347. 是递归地被调用
     的，`ignore' 可调用对象对于每个被拷贝目录都将被调用一次。 该可调用
     对象必须返回一个相对于当前目录的目录和文件名序列（即其第二个参数的
     子集）；随后这些名称将在拷贝进程中被忽略。 *note ignore_patterns():
     1de6. 可被用于创建这种基于 glob 风格模式来忽略特定名称的可调用对象
     。

     如果发生了（一个或多个）异常，将引发一个附带原因列表的 *note Error:
     999.。

     如果给出了 `copy_function'，它必须是一个将被用来拷贝每个文件的可调
     用对象。 它在被调用时会将源路径和目标路径作为参数传入。 默认情况下
     ，*note copy2(): 384. 将被使用，但任何支持同样签名（与 *note
     copy(): 383. 一致）都可以使用。

     引发一个 *note 审计事件: fa1. ‘shutil.copytree’ 附带参数 ‘src’,
     ‘dst’。

     3.3 版更變: 当 `symlinks' 为假值时拷贝元数据。 现在会返回 `dst'。

     3.2 版更變: 添加了 `copy_function' 参数以允许提供定制的拷贝函数。 添
     加了 `ignore_dangling_symlinks' 参数以便在 `symlinks' 为假值时屏蔽
     符号链接错误。

     3.8 版更變: 可能会在内部使用平台专属的快速拷贝系统调用以更高效地拷
     贝文件。 参见 *note 依赖于具体平台的高效拷贝操作: 388. 一节。

     3.8 版新加入: `dirs_exist_ok' 形参。

 -- 函式: shutil.rmtree (path, ignore_errors=False, onerror=None)

     删除一个完整的目录树；`path' 必须指向一个目录（但不能是一个目录的符
     号链接）。 如果 `ignore_errors' 为真值，删除失败导致的错误将被忽略
     ；如果为假值或是省略，此类错误将通过调用由 `onerror' 所指定的处理程
     序来处理，或者如果此参数被省略则将引发一个异常。

          備註: 在支持必要的基于 fd 的函数的平台上，默认会使用 *note
          rmtree(): 349. 的可防御符号链接攻击的版本。 在其他平台上，
          *note rmtree(): 349. 较易遭受符号链接攻击：给定适当的时间和环
          境，攻击者可以操纵文件系统中的符号链接来删除他们在其他情况下无
          法访问的文件。 应用程序可以使用 *note
          rmtree.avoids_symlink_attacks: 1de7. 函数属性来确定此类情况具
          体是哪一些。

     如果提供了 `onerror'，它必须为接受三个形参的可调用对象: `function',
     `path' 和 `excinfo'。

     第一个形参 `function' 是引发异常的函数；它依赖于具体的平台和实现。
     第二个形参 `path' 将是传递给 `function' 的路径名。 第三个形参
     `excinfo' 将是由 *note sys.exc_info(): d27. 所返回的异常信息。 由
     `onerror' 所引发的异常将不会被捕获。

     引发一个 *note 审计事件: fa1. ‘shutil.rmtree’ 附带参数 ‘path’。

     3.3 版更變: 添加了一个防御符号链接攻击的版本，如果平台支持基于 fd 的
     函数就会被使用。

     3.8 版更變: 在 Windows 上将不会再在移除连接之前删除目录连接中的内容
     。

      -- 屬性: rmtree.avoids_symlink_attacks

          指明当前平台和实现是否提供防御符号链接攻击的 *note rmtree():
          349. 版本。 目前它仅在平台支持基于 fd 的目录访问函数时才返回真
          值。

          3.3 版新加入.

 -- 函式: shutil.move (src, dst, copy_function=copy2)

     递归地将一个文件或目录 (`src') 移至另一位置 (`dst') 并返回目标位置
     。

     如果目标是已存在的目录，则 `src' 会被移至该目录下。 如果目标已存在
     但不是目录，它可能会被覆盖，具体取决于 *note os.rename(): b14. 的语
     义。

     如果目标是在当前文件系统中，则会使用 *note os.rename(): b14.。 在其
     他情况下，`src' 将被拷贝至 `dst'，使用的函数为 `copy_function'，然
     后目标会被移除。 对于符号链接，则将在 `dst' 之下或以其本身为名称创
     建一个指向 `src' 目标的新符号链接，并且 `src' 将被移除。

     如果给出了 `copy_function'，则它必须为接受两个参数 `src' 和 `dst' 的
     可调用对象，并将在 *note os.rename(): b14. 无法使用时被用来将 `src'
     拷贝到 `dst'。 如果源是一个目录，则会调用 *note copytree(): 347.，
     并向它传入 ‘copy_function()’。 默认的 `copy_function' 是 *note
     copy2(): 384.。 使用 *note copy(): 383. 作为 `copy_function' 允许在
     无法附带拷贝元数据时让移动操作成功执行，但其代价是不拷贝任何元数据
     。

     引发一个 *note 审计事件: fa1. ‘shutil.move’ 附带参数 ‘src’, ‘dst’。

     3.3 版更變: 为异类文件系统添加了显式的符号链接处理，以便使它适应
     GNU 的 ‘mv’ 的行为。 现在会返回 `dst'。

     3.5 版更變: 增加了 `copy_function' 关键字参数。

     3.8 版更變: 可能会在内部使用平台专属的快速拷贝系统调用以更高效地拷
     贝文件。 参见 *note 依赖于具体平台的高效拷贝操作: 388. 一节。

     3.9 版更變: 接受一个 *note path-like object: 472. 作为 `src' 和
     `dst'。

 -- 函式: shutil.disk_usage (path)

     返回给定路径的磁盘使用统计数据，形式为一个 *note named tuple: b7b.，
     其中包含 `total', `used' 和 `free' 属性，分别表示总计、已使用和未使
     用空间的字节数。 `path' 可以是一个文件或是一个目录。

     3.3 版新加入.

     3.8 版更變: 在 Windows 上，`path' 现在可以是一个文件或目录。

     *note 可用性: 1491.: Unix, Windows。

 -- 函式: shutil.chown (path, user=None, group=None)

     修改给定 `path' 的所有者 `user' 和/或 `group'。

     `user' 可以是一个系统用户名或 uid；`group' 同样如此。 要求至少有一
     个参数。

     另请参阅下层的函数 *note os.chown(): b10.。

     引发一个 *note 审计事件: fa1. ‘shutil.chown’ 附带参数 ‘path’,
     ‘user’, ‘group’。

     *note Availability: 1491.: Unix.

     3.3 版新加入.

 -- 函式: shutil.which (cmd, mode=os.F_OK | os.X_OK, path=None)

     返回当给定的 `cmd' 被调用时将要运行的可执行文件的路径。 如果没有
     `cmd' 会被调用则返回 ‘None’。

     `mode' 是一个传递给 *note os.access(): b0d. 的权限掩码，在默认情况
     下将确定文件是否存在并且为可执行文件。

     当未指定 `path' 时，将会使用 *note os.environ(): c09. 的结果，返回
     "PATH" 的值或回退为 *note os.defpath: 111a.。

     在 Windows 上当前目录总是会被添加为 `path' 的第一项，无论你是否使用
     默认值或提供你自己的路径，这是命令行终端在查找可执行文件时所采用的
     行为方式。 此外，当在 `path' 中查找 `cmd' 时，还会检查 ‘PATHEXT’ 环
     境变量。 例如，如果你调用 ‘shutil.which("python")’，*note which():
     fe6. 将搜索 ‘PATHEXT’ 来确定它要在 `path' 目录中查找 ‘python.exe’。
     例如，在 Windows 上:

          >>> shutil.which("python")
          'C:\\Python33\\python.EXE'

     3.3 版新加入.

     3.8 版更變: 现在可以接受 *note bytes: 172. 类型。 如果 `cmd' 的类型
     为 *note bytes: 172.，结果的类型也将为 *note bytes: 172.。

 -- 例外: shutil.Error

     此异常会收集在多文件操作期间所引发的异常。 对于 *note copytree():
     347.，此异常参数将是一个由三元组 (`srcname', `dstname',
     `exception') 构成的列表。

* Menu:

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


File: python.info,  Node: 依赖于具体平台的高效拷贝操作,  Next: copytree 示例,  Up: 目录和文件操作

5.11.10.2 依赖于具体平台的高效拷贝操作
......................................

从 Python 3.8 开始，所有涉及文件拷贝的函数 (*note copyfile(): 382, *note
copy(): 383, *note copy2(): 384, *note copytree(): 347. 以及 *note
move(): 385.) 将会使用平台专属的 "fast-copy" 系统调用以便更高效地拷贝文
件 (参见 bpo-33671(1))。 "fast-copy" 意味着拷贝操作将发生于内核之中，避
免像在 "‘outfd.write(infd.read())’" 中那样使用 Python 用户空间的缓冲区。

在 macOS 上将会使用 fcopyfile(2) 来拷贝文件内容（不含元数据）。

在 Linux 上将会使用 *note os.sendfile(): 461.。

在 Windows 上 *note shutil.copyfile(): 382. 将会使用更大的默认缓冲区（1
MiB 而非 64 KiB）并且会使用基于 *note memoryview(): 386. 的 *note
shutil.copyfileobj(): 387. 变种形式。

如果快速拷贝操作失败并且没有数据被写入目标文件，则 shutil 将在内部静默地
回退到使用效率较低的 *note copyfileobj(): 387. 函数。

3.8 版更變.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33671

   (2) http://www.manpagez.com/man/3/copyfile/


File: python.info,  Node: copytree 示例,  Next: rmtree 示例,  Prev: 依赖于具体平台的高效拷贝操作,  Up: 目录和文件操作

5.11.10.3 copytree 示例
.......................

这个示例就是上面所描述的 *note copytree(): 347. 函数的实现，其中省略了文
档字符串。 它还展示了此模块所提供的许多其他函数。

     def copytree(src, dst, symlinks=False):
         names = os.listdir(src)
         os.makedirs(dst)
         errors = []
         for name in names:
             srcname = os.path.join(src, name)
             dstname = os.path.join(dst, name)
             try:
                 if symlinks and os.path.islink(srcname):
                     linkto = os.readlink(srcname)
                     os.symlink(linkto, dstname)
                 elif os.path.isdir(srcname):
                     copytree(srcname, dstname, symlinks)
                 else:
                     copy2(srcname, dstname)
                 # XXX What about devices, sockets etc.?
             except OSError as why:
                 errors.append((srcname, dstname, str(why)))
             # catch the Error from the recursive copytree so that we can
             # continue with other files
             except Error as err:
                 errors.extend(err.args[0])
         try:
             copystat(src, dst)
         except OSError as why:
             # can't copy file access times on Windows
             if why.winerror is None:
                 errors.extend((src, dst, str(why)))
         if errors:
             raise Error(errors)

另一个使用 *note ignore_patterns(): 1de6. 辅助函数的例子:

     from shutil import copytree, ignore_patterns

     copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))

这将会拷贝除 ‘.pyc’ 文件和以 ‘tmp’ 打头的文件或目录以外的所有条目.

另一个使用 `ignore' 参数来添加记录调用的例子:

     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)


File: python.info,  Node: rmtree 示例,  Prev: copytree 示例,  Up: 目录和文件操作

5.11.10.4 rmtree 示例
.....................

这个例子演示了如何在 Windows 上删除一个目录树，其中部分文件设置了只读属
性位。 它会使用 onerror 回调函数来清除只读属性位并再次尝试删除。 任何后
续的失败都将被传播。

     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)


File: python.info,  Node: 归档操作,  Next: 查询输出终端的尺寸,  Prev: 目录和文件操作,  Up: shutil --- 高阶文件操作

5.11.10.5 归档操作
..................

3.2 版新加入.

3.5 版更變: 添加了对 `xztar' 格式的支持。

本模块也提供了用于创建和读取压缩和归档文件的高层级工具。 它们依赖于
*note zipfile: 14b. 和 *note tarfile: 101. 模块。

 -- 函式: shutil.make_archive (base_name, format[, root_dir[, base_dir[,
          verbose[, dry_run[, owner[, group[, logger]]]]]]])

     创建一个归档文件（例如 zip 或 tar）并返回其名称。

     `base_name' 是要创建的文件名称，包括路径，去除任何特定格式的扩展名
     。 `format' 是归档格式：为 "zip" (如果 *note zlib: 14d. 模块可用),
     "tar", "gztar" (如果 *note zlib: 14d. 模块可用), "bztar" (如果
     *note bz2: 13. 模块可用) 或 "xztar" (如果 *note lzma: ad. 模块可用)
     中的一个。

     `root_dir' 是一个目录，它将作为归档文件的根目录，归档中的所有路径都
     将是它的相对路径；例如，我们通常会在创建归档之前用 chdir 命令切换到
     `root_dir'。

     `base_dir' 是我们要执行归档的起始目录；也就是说 `base_dir' 将成为归
     档中所有文件和目录共有的路径前缀。 `base_dir' 必须相对于 `root_dir'
     给出。 请参阅 *note 使用 base_dir 的归档程序示例: 1dee. 了解如何同
     时使用 `base_dir' 和 `root_dir'。

     `root_dir' 和 `base_dir' 默认均为当前目录。

     如果 `dry_run' 为真值，则不会创建归档文件，但将要被执行的操作会被记
     录到 `logger'。

     `owner' 和 `group' 将在创建 tar 归档文件时被使用。 默认会使用当前的
     所有者和分组。

     `logger' 必须是一个兼容 PEP 282(1) 的对象，通常为 *note
     logging.Logger: 4ad. 的实例。

     `verbose' 参数已不再使用并进入弃用状态。

     引发一个 *note 审计事件: fa1. ‘shutil.make_archive’ 并附带参数
     ‘base_name’, ‘format’, ‘root_dir’, ‘base_dir’。

          備註: 这个函数不是线程安全的。

     3.8 版更變: 现在对于通过 ‘format="tar"’ 创建的归档文件将使用新式的
     pax (POSIX.1-2001) 格式而非旧式的 GNU 格式。

 -- 函式: shutil.get_archive_formats ()

     返回支持的归档格式列表。 所返回序列中的每个元素为一个元组 ‘(name,
     description)’。

     默认情况下 *note shutil: e9. 提供以下格式:

        - `zip': ZIP 文件（如果 *note zlib: 14d. 模块可用）。

        - `tar': 未压缩的 tar 文件。 对于新归档文件将使用 POSIX.1-2001
          pax 格式。

        - `gztar': gzip 压缩的 tar 文件（如果 *note zlib: 14d. 模块可用
          ）。

        - `bztar': bzip2 压缩的 tar 文件（如果 *note bz2: 13. 模块可用）
          。

        - `xztar': xz 压缩的 tar 文件（如果 *note lzma: ad. 模块可用）。

     你可以通过使用 *note register_archive_format(): 1df0. 注册新的格式
     或为任何现有格式提供你自己的归档器。

 -- 函式: shutil.register_archive_format (name, function[, extra_args[,
          description]])

     为 `name' 格式注册一个归档器。

     `function' 是将被用来解包归档文件的可调用对象。 该可调用对象将接收
     要创建文件的 `base_name'，再加上要归档内容的 `base_dir' (其默认值为
     *note os.curdir: 1d4f.)。 更多参数会被作为关键字参数传入: `owner',
     `group', `dry_run' 和 `logger' (与向 *note make_archive(): 348. 传
     入的参数一致)。

     如果给出了 `extra_args'，则其应为一个 ‘(name, value)’ 对的序列，将
     在归档器可调用对象被使用时作为附加的关键字参数。

     `description' 由 *note get_archive_formats(): 1def. 使用，它将返回
     归档器的列表。 默认值为一个空字符串。

 -- 函式: shutil.unregister_archive_format (name)

     从支持的格式中移除归档格式 `name'。

 -- 函式: shutil.unpack_archive (filename[, extract_dir[, format]])

     解包一个归档文件。 `filename' 是归档文件的完整路径。

     `extract_dir' 是归档文件解包的目标目录名称。 如果未提供，则将使用当
     前工作目录。

     `format' 是归档格式：应为 "zip", "tar", "gztar", "bztar" 或 "xztar"
     之一。 或者任何通过 *note register_unpack_format(): 1df2. 注册的其
     他格式。 如果未提供，*note unpack_archive(): c68. 将使用归档文件的
     扩展名来检查是否注册了对应于该扩展名的解包器。 在未找到任何解包器的
     情况下，将引发 *note ValueError: 16d.。

     引发一个 *note 审计事件: fa1. ‘shutil.unpack_archive’ 附带参数
     ‘filename’, ‘extract_dir’, ‘format’。

     3.7 版更變: 接受一个 *note path-like object: 472. 作为 `filename' 和
     `extract_dir'。

 -- 函式: shutil.register_unpack_format (name, extensions, function[,
          extra_args[, description]])

     注册一个解包格式。 `name' 为格式名称而 `extensions' 为对应于该格式
     的扩展名列表，例如 Zip 文件的扩展名为 ‘.zip’。

     `function' 是将被用来解包归档文件的可调用对象。 该可调用对象将接受
     归档文件的路径，加上该归档文件要被解包的目标目录。

     如果提供了 `extra_args'，则其应为一个 ‘(name, value)’ 元组的序列，
     将被作为关键字参数传递给该可调用对象。

     可以提供 `description' 来描述该格式，它将被 *note
     get_unpack_formats(): 1df3. 返回。

 -- 函式: shutil.unregister_unpack_format (name)

     撤销注册一个解包格式。 `name' 为格式的名称。

 -- 函式: shutil.get_unpack_formats ()

     返回所有已注册的解包格式列表。 所返回序列中的每个元素为一个元组
     ‘(name, extensions, description)’。

     默认情况下 *note shutil: e9. 提供以下格式:

        - `zip': ZIP 文件（只有在相应模块可用时才能解包压缩文件）。

        - `tar': 未压缩的 tar 文件。

        - `gztar': gzip 压缩的 tar 文件（如果 *note zlib: 14d. 模块可用
          ）。

        - `bztar': bzip2 压缩的 tar 文件（如果 *note bz2: 13. 模块可用）
          。

        - `xztar': xz 压缩的 tar 文件（如果 *note lzma: ad. 模块可用）。

     你可以通过使用 *note register_unpack_format(): 1df2. 注册新的格式或
     为任何现有格式提供你自己的解包器。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0282


File: python.info,  Node: 归档程序示例,  Next: 使用 base_dir 的归档程序示例,  Up: 归档操作

5.11.10.6 归档程序示例
......................

在这个示例中，我们创建了一个 gzip 压缩的 tar 归档文件，其中包含用户的
‘.ssh’ 目录下的所有文件:

     >>> 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'

结果归档文件中包含有:

     $ 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


File: python.info,  Node: 使用 base_dir 的归档程序示例,  Prev: 归档程序示例,  Up: 归档操作

5.11.10.7 使用 `base_dir' 的归档程序示例
........................................

在这个例子中，与 *note 上面的例子: 1df6. 类似，我们演示了如何使用 *note
make_archive(): 348.，但这次是使用 `base_dir'。 我们现在具有如下的目录结
构:

     $ tree tmp
     tmp
     └── root
         └── structure
             ├── content
                 └── please_add.txt
             └── do_not_add.txt

在最终的归档中，应当会包括 ‘please_add.txt’，但不应当包括
‘do_not_add.txt’。 因此我们使用以下代码:

     >>> 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'

列出结果归档中的文件我们将会得到:

     $ python -m tarfile -l /Users/tarek/myarchive.tar
     structure/content/
     structure/content/please_add.txt


File: python.info,  Node: 查询输出终端的尺寸,  Prev: 归档操作,  Up: shutil --- 高阶文件操作

5.11.10.8 查询输出终端的尺寸
............................

 -- 函式: shutil.get_terminal_size (fallback=(columns, lines))

     获取终端窗口的尺寸。

     对于两个维度中的每一个，会分别检查环境变量 ‘COLUMNS’ 和 ‘LINES’。 如
     果定义了这些变量并且其值为正整数，则将使用这些值。

     如果未定义 ‘COLUMNS’ 或 ‘LINES’，这是通常的情况，则连接到 *note
     sys.__stdout__: 1df9. 的终端将通过发起调用 *note
     os.get_terminal_size(): b24. 被查询。

     如果由于系统不支持查询，或是由于我们未连接到某个终端而导致查询终端
     尺寸不成功，则会使用在 ‘fallback’ 形参中给出的值。 ‘fallback’ 默认
     为 ‘(80, 24)’，这是许多终端模拟器所使用的默认尺寸。

     返回的值是一个 *note os.terminal_size: 1dfa. 类型的具名元组。

     另请参阅: The Single UNIX Specification, Version 2, Other
     Environment Variables(1).

     3.3 版新加入.

也參考
......

模块 *note os: c4.

     操作系统接口，包括处理比 Python *note 文件对象: c14. 更低级别文件的
     功能。

模块 *note io: a1.

     Python的内置 I/O 库，包括抽象类和一些具体的类，如文件 I/O 。

内置函数 *note open(): 16f.

     使用 Python 打开文件进行读写的标准方法。

   ---------- Footnotes ----------

   (1) 
http://pubs.opengroup.org/onlinepubs/7908799/xbd/envvar.html#tag_002_003


File: python.info,  Node: 数据持久化,  Next: 資料壓縮與保存,  Prev: 檔案與目錄存取,  Up: Python 標準函式庫 Standard Library

5.12 数据持久化
===============

本章中描述的模块支持在磁盘上以持久形式存储 Python 数据。 *note pickle:
ca. 和 *note marshal: b0. 模块可以将许多 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 接口模块


File: python.info,  Node: pickle --- Python 对象序列化,  Next: copyreg --- 注册配合 pickle 模块使用的函数,  Up: 数据持久化

5.12.1 ‘pickle’ — Python 对象序列化
-----------------------------------

`源代码：' Lib/pickle.py(1)

__________________________________________________________________

模块 *note pickle: ca. 实现了对一个 Python 对象结构的二进制序列化和反序
列化。 `"pickling"' 是将 Python 对象及其所拥有的层次结构转化为一个字节流
的过程，而 `"unpickling"' 是相反的操作，会将（来自一个 *note binary
file: 1e01. 或者 *note bytes-like object: 6df. 的）字节流转化回一个对象
层次结构。 pickling（和 unpickling）也被称为“序列化”, “编组” (2) 或者 “平
面化”。而为了避免混乱，此处采用术语 “封存 (pickling)” 和 “解封
(unpickling)”。

     警告: ‘pickle’ 模块**并不安全**。你只应该对你信任的数据进行
     unpickle操作。

     构建恶意的 pickle 数据来**在解封时执行任意代码**是可能的。绝对不要
     对不信任来源的数据和可能被篡改过的数据进行解封。

     请考虑使用 *note hmac: 8e. 来对数据进行签名，确保数据没有被篡改。

     在你处理不信任数据时，更安全的序列化格式如 *note json: a4. 可能更为
     适合。参见 *note 与 json 模块的比较: 1e02. 。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/pickle.py

   (2) (1) 不要把它与 *note marshal: b0. 模块混淆。


File: python.info,  Node: 与其他 Python 模块间的关系,  Next: 数据流格式,  Up: pickle --- Python 对象序列化

5.12.1.1 与其他 Python 模块间的关系
...................................

* Menu:

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


File: python.info,  Node: 与 marshal 间的关系,  Next: 与 json 模块的比较,  Up: 与其他 Python 模块间的关系

5.12.1.2 与 ‘marshal’ 间的关系
..............................

Python 有一个更原始的序列化模块称为 *note marshal: b0.，但一般地 *note
pickle: ca. 应该是序列化 Python 对象时的首选。*note marshal: b0. 存在主
要是为了支持 Python 的 ‘.pyc’ 文件.

*note pickle: ca. 模块与 *note marshal: b0. 在如下几方面显著地不同：

   * *note pickle: ca. 模块会跟踪已被序列化的对象，所以该对象之后再次被
     引用时不会再次被序列化。*note marshal: b0. 不会这么做。

     这隐含了递归对象和共享对象。递归对象指包含对自己的引用的对象。这种
     对象并不会被 marshal 接受，并且实际上尝试 marshal 递归对象会让你的
     Python 解释器崩溃。对象共享发生在对象层级中存在多处引用同一对象时。
     *note pickle: ca. 只会存储这些对象一次，并确保其他的引用指向同一个
     主副本。共享对象将保持共享，这可能对可变对象非常重要。

   * *note marshal: b0. 不能被用于序列化用户定义类及其实例。*note
     pickle: ca. 能够透明地存储并保存类实例，然而此时类定义必须能够从与
     被存储时相同的模块被引入。

   * 同样用于序列化的 *note marshal: b0. 格式不保证数据能移植到不同的
     Python 版本中。因为它的主要任务是支持 ‘.pyc’ 文件，必要时会以破坏向
     后兼容的方式更改这种序列化格式，为此 Python 的实现者保留了更改格式
     的权利。*note pickle: ca. 序列化格式可以在不同版本的 Python 中实现
     向后兼容，前提是选择了合适的 pickle 协议。如果你的数据要在 Python 2
     与 Python 3 之间跨越传递，封存和解封的代码在 2 和 3 之间也是不同的
     。


File: python.info,  Node: 与 json 模块的比较,  Prev: 与 marshal 间的关系,  Up: 与其他 Python 模块间的关系

5.12.1.3 与 ‘json’ 模块的比较
.............................

Pickle 协议和 JSON (JavaScript Object Notation)(1) 间有着本质的不同：

   * JSON 是一个文本序列化格式（它输出 unicode 文本，尽管在大多数时候它
     会接着以 ‘utf-8’ 编码），而 pickle 是一个二进制序列化格式；

   * JSON 是我们可以直观阅读的，而 pickle 不是；

   * JSON是可互操作的，在Python系统之外广泛使用，而pickle则是Python专用
     的；

   * 默认情况下，JSON 只能表示 Python 内置类型的子集，不能表示自定义的类
     ；但 pickle 可以表示大量的 Python 数据类型（可以合理使用 Python 的
     对象内省功能自动地表示大多数类型，复杂情况可以通过实现 *note
     specific object APIs: 1e06. 来解决）。

   * 不像pickle，对一个不信任的JSON进行反序列化的操作本身不会造成任意代
     码执行漏洞。

也參考
......

*note json: a4. 模块:一个允许JSON序列化和反序列化的标准库模块

   ---------- Footnotes ----------

   (1) http://json.org


File: python.info,  Node: 数据流格式,  Next: 模块接口,  Prev: 与其他 Python 模块间的关系,  Up: pickle --- Python 对象序列化

5.12.1.4 数据流格式
...................

*note pickle: ca. 所使用的数据格式仅可用于 Python。这样做的好处是没有外
部标准给该格式强加限制，比如 JSON 或 XDR（不能表示共享指针）标准；但这也
意味着非 Python 程序可能无法重新读取 pickle 封存的 Python 对象。

默认情况下，*note pickle: ca. 格式使用相对紧凑的二进制来存储。如果需要让
文件更小，可以高效地 *note 压缩: 1e08. 由 pickle 封存的数据。

*note pickletools: cb. 模块包含了相应的工具用于分析 *note pickle: ca. 生
成的数据流。*note pickletools: cb. 源码中包含了对 pickle 协议使用的操作
码的大量注释。

当前共有 6 种不同的协议可用于封存操作。 使用的协议版本越高，读取所生成
pickle 对象所需的 Python 版本就要越新。

   * v0 版协议是原始的“人类可读”协议，并且向后兼容早期版本的 Python。

   * v1 版协议是较早的二进制格式，它也与早期版本的 Python 兼容。

   * v2 版协议是在 Python 2.3 中引入的。它为存储 *note new-style class:
     1e09. 提供了更高效的机制。欲了解有关第 2 版协议带来的改进，请参阅
     PEP 307(1)。

   * v3 版协议是在 Python 3.0 中引入的。 它显式地支持 *note bytes: 172.
     字节对象，不能使用 Python 2.x 解封。这是 Python 3.0-3.7 的默认协议
     。

   * v4 版协议添加于 Python 3.4。它支持存储非常大的对象，能存储更多种类
     的对象，还包括一些针对数据格式的优化。它是Python 3.8使用的默认协议
     。有关第 4 版协议带来改进的信息，请参阅 PEP 3154(2)。

   * 第 5 版协议是在 Python 3.8 中加入的。 它增加了对带外数据的支持，并
     可加速带内数据处理。 请参阅 PEP 574(3) 了解第 5 版协议所带来的改进
     的详情。

     備註: 序列化是一种比持久化更底层的概念，虽然 *note pickle: ca. 读取
     和写入的是文件对象，但它不处理持久对象的命名问题，也不处理对持久对
     象的并发访问（甚至更复杂）的问题。*note pickle: ca. 模块可以将复杂
     对象转换为字节流，也可以将字节流转换为具有相同内部结构的对象。处理
     这些字节流最常见的做法是将它们写入文件，但它们也可以通过网络发送或
     存储在数据库中。*note shelve: e7. 模块提供了一个简单的接口，用于在
     DBM 类型的数据库文件上封存和解封对象。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0307

   (2) https://www.python.org/dev/peps/pep-3154

   (3) https://www.python.org/dev/peps/pep-0574


File: python.info,  Node: 模块接口,  Next: 可以被封存/解封的对象,  Prev: 数据流格式,  Up: pickle --- Python 对象序列化

5.12.1.5 模块接口
.................

要序列化某个包含层次结构的对象，只需调用 *note dumps(): ec3. 函数即可。
同样，要反序列化数据流，可以调用 *note loads(): 6ba. 函数。但是，如果要
对序列化和反序列化加以更多的控制，可以分别创建 *note Pickler: 33b. 或
*note Unpickler: 1e0b. 对象。

*note pickle: ca. 模块包含了以下常量：

 -- Data: pickle.HIGHEST_PROTOCOL

     整数，可用的最高 *note 协议版本: 666.。此值可以作为 `协议' 值传递给
     *note dump(): 1e0c. 和 *note dumps(): ec3. 函数，以及 *note
     Pickler: 33b. 的构造函数。

 -- Data: pickle.DEFAULT_PROTOCOL

     整数，用于 pickle 数据的默认 *note 协议版本: 666.。它可能小于 *note
     HIGHEST_PROTOCOL: ec4.。当前默认协议是 v4，它在 Python 3.4 中首次引
     入，与之前的版本不兼容。

     3.0 版更變: 默认协议版本是 3。

     3.8 版更變: 默认协议版本是 4。

*note pickle: ca. 模块提供了以下方法，让封存过程更加方便：

 -- 函式: pickle.dump (obj, file, protocol=None, *, fix_imports=True,
          buffer_callback=None)

     将对象 `obj' 封存以后的对象写入已打开的 *note file object: c14.
     `file'。它等同于 ‘Pickler(file, protocol).dump(obj)’。

     参数 `file'、`protocol'、`fix_imports' 和 `buffer_callback' 的含义
     与它们在 *note Pickler: 33b. 的构造函数中的含义相同。

     3.8 版更變: 加入了 `buffer_callback' 参数。

 -- 函式: pickle.dumps (obj, protocol=None, *, fix_imports=True,
          buffer_callback=None)

     将 `obj' 封存以后的对象作为 *note bytes: 172. 类型直接返回，而不是
     将其写入到文件。

     参数 `protocol'、`fix_imports' 和 `buffer_callback' 的含义与它们在
     *note Pickler: 33b. 的构造函数中的含义相同。

     3.8 版更變: 加入了 `buffer_callback' 参数。

 -- 函式: pickle.load (file, *, fix_imports=True, encoding="ASCII",
          errors="strict", buffers=None)

     从已打开的 *note file object: c14. `文件' 中读取封存后的对象，重建
     其中特定对象的层次结构并返回。它相当于 ‘Unpickler(file).load()’。

     Pickle 协议版本是自动检测出来的，所以不需要参数来指定协议。封存对象
     以外的其他字节将被忽略。

     参数 `file'、`fix_imports'、`encoding'、`errors'、`strict' 和
     `buffers' 的含义与它们在 *note Unpickler: 1e0b. 的构造函数中的含义
     相同。

     3.8 版更變: 加入了 `buffers' 参数。

 -- 函式: pickle.loads (data, /, *, fix_imports=True, encoding="ASCII",
          errors="strict", buffers=None)

     重建并返回一个对象的封存表示形式 `data' 的对象层级结构。 `data' 必
     须为 *note bytes-like object: 6df.。

     Pickle 协议版本是自动检测出来的，所以不需要参数来指定协议。封存对象
     以外的其他字节将被忽略。

     参数 `file'、`fix_imports'、`encoding'、`errors'、`strict' 和
     `buffers' 的含义与它们在 *note Unpickler: 1e0b. 的构造函数中的含义
     相同。

     3.8 版更變: 加入了 `buffers' 参数。

*note pickle: ca. 模块定义了以下 3 个异常：

 -- 例外: pickle.PickleError

     其他 pickle 异常的基类。它是 *note Exception: 2dc. 的一个子类。

 -- 例外: pickle.PicklingError

     当 *note Pickler: 33b. 遇到无法解封的对象时抛出此错误。它是 *note
     PickleError: 1e0e. 的子类。

     参考 *note 可以被封存/解封的对象: 1e10. 来了解哪些对象可以被封存。

 -- 例外: pickle.UnpicklingError

     当解封出错时抛出此异常，例如数据损坏或对象不安全。它是 *note
     PickleError: 1e0e. 的子类。

     注意，解封时可能还会抛出其他异常，包括（但不限于） AttributeError、
     EOFError、ImportError 和 IndexError。

*note pickle: ca. 模块包含了 3 个类，*note Pickler: 33b.、*note
Unpickler: 1e0b. 和 *note PickleBuffer: 1e12.：

 -- 類別: pickle.Pickler (file, protocol=None, *, fix_imports=True,
          buffer_callback=None)

     它接受一个二进制文件用于写入 pickle 数据流。

     可选参数 `protocol' 是一个整数，告知 pickler 使用指定的协议，可选择
     的协议范围从 0 到 *note HIGHEST_PROTOCOL: ec4.。如果没有指定，这一
     参数默认值为 *note DEFAULT_PROTOCOL: 1e0d.。指定一个负数就相当于指
     定 *note HIGHEST_PROTOCOL: ec4.。

     参数 `file' 必须有一个 write() 方法，该 write() 方法要能接收字节作
     为其唯一参数。因此，它可以是一个打开的磁盘文件（用于写入二进制内容
     ），也可以是一个 *note io.BytesIO: 88a. 实例，也可以是满足这一接口
     的其他任何自定义对象。

     如果 `fix_imports' 为 True 且 `protocol' 小于 3，pickle 将尝试将
     Python 3 中的新名称映射到 Python 2 中的旧模块名称，因此 Python 2 也
     可以读取封存的数据流。

     如果 `buffer_callback' 为 None（默认情况），缓冲区视图（buffer
     view）将会作为 pickle 流的一部分被序列化到 `file' 中。

     如果 `buffer_callback' 不为 None，那它可以用缓冲区视图调用任意次。
     如果某次调用返回了 False 值（例如 None），则给定的缓冲区是 *note
     带外的: 1e13.，否则缓冲区是带内的（例如保存在了 pickle 流里面）。

     如果 `buffer_callback' 不是 None 且 `protocol' 是 None 或小于 5，就
     会出错。

     3.8 版更變: 加入了 `buffer_callback' 参数。

      -- 成員函式: dump (obj)

          将 `obj' 封存后的内容写入已打开的文件对象，该文件对象已经在构
          造函数中指定。

      -- 成員函式: persistent_id (obj)

          默认无动作，子类继承重载时使用。

          如果 *note persistent_id(): 1e14. 返回 ‘None’，`obj' 会被照常
          pickle。如果返回其他值，*note Pickler: 33b. 会将这个函数的返回
          值作为 `obj' 的持久化 ID（Pickler 本应得到序列化数据流并将其写
          入文件，若此函数有返回值，则得到此函数的返回值并写入文件）。这
          个持久化 ID 的解释应当定义在 *note
          Unpickler.persistent_load(): 1e15. 中（该方法定义还原对象的过
          程，并返回得到的对象）。注意，*note persistent_id(): 1e14. 的
          返回值本身不能拥有持久化 ID。

          参阅 *note 持久化外部对象: 1e16. 获取详情和使用示例。

      -- 屬性: dispatch_table

          Pickler 对象的 dispatch 表是 *note copyreg.pickle(): 1e17. 中
          用到的 `reduction 函数' 的注册。dispatch 表本身是一个 class 到
          其 reduction 函数的映射键值对。一个 reduction 函数只接受一个参
          数，就是其关联的 class，函数行为应当遵守 *note __reduce__():
          2d0. 接口规范。

          Pickler 对象默认并没有 *note dispatch_table: b44. 属性，该对象
          默认使用 *note copyreg: 26. 模块中定义的全局 dispatch 表。如果
          要为特定 Pickler 对象自定义序列化过程，可以将 *note
          dispatch_table: b44. 属性设置为类字典对象（dict-like object）
          。另外，如果 *note Pickler: 33b. 的子类设置了 *note
          dispatch_table: b44. 属性，则该子类的实例会使用这个表作为默认
          的 dispatch 表。

          参阅 *note Dispatch 表: 1e18. 获取使用示例。

          3.3 版新加入.

      -- 成員函式: reducer_override (self, obj)

          可以在 *note Pickler: 33b. 的子类中定义的特殊 reducer。此方法
          的优先级高于 *note dispatch_table: b44. 中的任何 reducer。它应
          该与 *note __reduce__(): 2d0. 方法遵循相同的接口，它也可以返回
          ‘NotImplemented’，这将使用 *note dispatch_table: b44. 里注册的
          reducer 来封存 ‘obj’。

          参阅 *note 类型，函数和其他对象的自定义归约: 1e19. 获取详细的
          示例。

          3.8 版新加入.

      -- 屬性: fast

          已弃用。设为 True 则启用快速模式。快速模式禁用了“备忘录”
          (memo) 的使用，即不生成多余的 PUT 操作码来加快封存过程。不应将
          其与自指 (self-referential) 对象一起使用，否则将导致 *note
          Pickler: 33b. 无限递归。

          如果需要进一步提高 pickle 的压缩率，请使用 *note
          pickletools.optimize(): 1e1b.。

 -- 類別: pickle.Unpickler (file, *, fix_imports=True, encoding="ASCII",
          errors="strict", buffers=None)

     它接受一个二进制文件用于读取 pickle 数据流。

     Pickle 协议版本是自动检测出来的，所以不需要参数来指定协议。

     参数 `file' 必须有三个方法，read() 方法接受一个整数参数，readinto()
     方法接受一个缓冲区作为参数，readline() 方法不需要参数，这与 *note
     io.BufferedIOBase: 67f. 里定义的接口是相同的。因此 `file' 可以是一
     个磁盘上用于二进制读取的文件，也可以是一个 *note io.BytesIO: 88a. 实
     例，也可以是满足这一接口的其他任何自定义对象。

     可选的参数是 `fix_imports', `encoding' 和 `errors'，用于控制由
     Python 2 生成的 pickle 流的兼容性。如果 `fix_imports' 为 True，则
     pickle 将尝试将旧的 Python 2 名称映射到 Python 3 中对应的新名称。
     `encoding' 和 `errors' 参数告诉 pickle 如何解码 Python 2 存储的 8 位
     字符串实例；这两个参数默认分别为 ’ASCII’ 和 ’strict’。`encoding' 参
     数可置为 ’bytes’ 来将这些 8 位字符串实例读取为字节对象。读取 NumPy
     array 和 Python 2 存储的 *note datetime: 19f.、*note date: 19d. 和
     *note time: 5ec. 实例时，请使用 ‘encoding='latin1'’。

     如果 `buffers' 为 None（默认值），则反序列化所需的所有数据都必须包
     含在 pickle 流中。这意味着在实例化 *note Pickler: 33b. 时（或调用
     *note dump(): 1e0c. 或 *note dumps(): ec3. 时），参数
     `buffer_callback' 为 None。

     如果 `buffers' 不为 None，则每次 pickle 流引用 *note 带外: 1e13. 缓
     冲区视图时，消耗的对象都应该是可迭代的启用缓冲区的对象。这样的缓冲
     区应该按顺序地提供给 Pickler 对象的 `buffer_callback' 方法。

     3.8 版更變: 加入了 `buffers' 参数。

      -- 成員函式: load ()

          从构造函数中指定的文件对象里读取封存好的对象，重建其中特定对象
          的层次结构并返回。封存对象以外的其他字节将被忽略。

      -- 成員函式: persistent_load (pid)

          默认抛出 *note UnpicklingError: 1e11. 异常。

          如果定义了此方法，*note persistent_load(): 1e15. 应当返回持久
          化 ID `pid' 所指定的对象。 如果遇到无效的持久化 ID，则应当引发
          *note UnpicklingError: 1e11.。

          参阅 *note 持久化外部对象: 1e16. 获取详情和使用示例。

      -- 成員函式: find_class (module, name)

          如有必要，导入 `module' 模块并返回其中名叫 `name' 的对象，其中
          `module' 和 `name' 参数都是 *note str: 205. 对象。注意，不要被
          这个函数的名字迷惑， *note find_class(): 1e1d. 同样可以用来导
          入函数。

          子类可以重载此方法，来控制加载对象的类型和加载对象的方式，从而
          尽可能降低安全风险。参阅 *note 限制全局变量: 1e1e. 获取更详细
          的信息。

          引发一个 *note 审计事件: fa1. ‘pickle.find_class’ 附带参数
          ‘module’、‘name’。

 -- 類別: pickle.PickleBuffer (buffer)

     缓冲区的包装器 (wrapper)，缓冲区中包含着可封存的数据。`buffer' 必须
     是一个 *note buffer-providing: 171c. 对象，比如 *note bytes-like
     object: 6df. 或多维数组。

     *note PickleBuffer: 1e12. 本身就可以生成缓冲区对象，因此可以将其传
     递给需要缓冲区生成器的其他 API，比如 *note memoryview: 386.。

     *note PickleBuffer: 1e12. 对象只能用 pickle 版本 5 及以上协议进行序
     列化。它们符合 *note 带外序列化: 1e13. 的条件。

     3.8 版新加入.

      -- 成員函式: raw ()

          返回该缓冲区底层内存区域的 *note memoryview: 386.。 返回的对象
          是一维的、C 连续布局的 memoryview，格式为 ‘B’ (无符号字节)。 如
          果缓冲区既不是 C 连续布局也不是 Fortran 连续布局的，则抛出
          *note BufferError: 1847. 异常。

      -- 成員函式: release ()

          释放由 PickleBuffer 占用的底层缓冲区。


File: python.info,  Node: 可以被封存/解封的对象,  Next: 封存类实例,  Prev: 模块接口,  Up: pickle --- Python 对象序列化

5.12.1.6 可以被封存/解封的对象
..............................

下列类型可以被封存：

   * ‘None’、‘True’ 和 ‘False’

   * 整数、浮点数、复数

   * str、byte、bytearray

   * 只包含可封存对象的集合，包括 tuple、list、set 和 dict

   * 定义在模块最外层的函数（使用 *note def: e83. 定义，*note lambda:
     cf9. 函数则不可以）

   * 定义在模块最外层的内置函数

   * 定义在模块最外层的类

   * 某些类实例，这些类的 *note __dict__: 5f5. 属性值或 *note
     __getstate__(): ec5. 函数的返回值可以被封存（详情参阅 *note
     封存类实例: 1e06. 这一段）。

尝试封存不能被封存的对象会抛出 *note PicklingError: 1e0f. 异常，异常发生
时，可能有部分字节已经被写入指定文件中。尝试封存递归层级很深的对象时，可
能会超出最大递归层级限制，此时会抛出 *note RecursionError: 727. 异常，可
以通过 *note sys.setrecursionlimit(): f3c. 调整递归层级，不过请谨慎使用
这个函数，因为可能会导致解释器崩溃。

注意，函数（内置函数或用户自定义函数）在被封存时，引用的是函数全名。(1)
这意味着只有函数所在的模块名，与函数名会被封存，函数体及其属性不会被封存
。因此，在解封的环境中，函数所属的模块必须是可以被导入的，而且模块必须包
含这个函数被封存时的名称，否则会抛出异常。(2)

同样的，类也只封存名称，所以在解封环境中也有和函数相同的限制。注意，类体
及其数据不会被封存，所以在下面的例子中类属性 ‘attr’ 不会存在于解封后的环
境中：

     class Foo:
         attr = 'A class attribute'

     picklestring = pickle.dumps(Foo)

这些限制决定了为什么必须在一个模块的最外层定义可封存的函数和类。

类似的，在封存类的实例时，其类体和类数据不会跟着实例一起被封存，只有实例
数据会被封存。这样设计是有目的的，在将来修复类中的错误、给类增加方法之后
，仍然可以载入原来版本类实例的封存数据来还原该实例。如果你准备长期使用一
个对象，可能会同时存在较多版本的类体，可以为对象添加版本号，这样就可以通
过类的 *note __setstate__(): 2d1. 方法将老版本转换成新版本。

   ---------- Footnotes ----------

   (1) (2) 这就是为什么 *note lambda: cf9. 函数不可以被封存：所有的匿名
函数都有同一个名字：‘<lambda>’。

   (2) (3) 抛出的异常有可能是 *note ImportError: 16c. 或 *note
AttributeError: 4a1.，也可能是其他异常。


File: python.info,  Node: 封存类实例,  Next: 类型，函数和其他对象的自定义归约,  Prev: 可以被封存/解封的对象,  Up: pickle --- Python 对象序列化

5.12.1.7 封存类实例
...................

在本节中，我们描述了可用于定义、自定义和控制如何封存和解封类实例的通用流
程。

通常，使一个实例可被封存不需要附加任何代码。Pickle 默认会通过 Python 的
内省机制获得实例的类及属性。而当实例解封时，它的 *note __init__(): e23.
方法通常 `不会' 被调用。其默认动作是：先创建一个未初始化的实例，然后还原
其属性，下面的代码展示了这种行为的实现机制：

     def save(obj):
         return (obj.__class__, obj.__dict__)

     def load(cls, attributes):
         obj = cls.__new__(cls)
         obj.__dict__.update(attributes)
         return obj

类可以改变默认行为，只需定义以下一种或几种特殊方法：

 -- 成員函式: object.__getnewargs_ex__ ()

     对于使用第 2 版或更高版协议的 pickle，实现了 *note
     __getnewargs_ex__(): 1e23. 方法的类可以控制在解封时传给 *note
     __new__(): 974. 方法的参数。本方法必须返回一对 ‘(args, kwargs)’ 用
     于构建对象，其中 `args' 是表示位置参数的 tuple，而 `kwargs' 是表示
     命名参数的 dict。它们会在解封时传递给 *note __new__(): 974. 方法。

     如果类的 *note __new__(): 974. 方法只接受关键字参数，则应当实现这个
     方法。否则，为了兼容性，更推荐实现 *note __getnewargs__(): 7a1. 方
     法。

     3.6 版更變: *note __getnewargs_ex__(): 1e23. 现在可用于第 2 和第 3
     版协议。

 -- 成員函式: object.__getnewargs__ ()

     这个方法与上一个 *note __getnewargs_ex__(): 1e23. 方法类似，但仅支
     持位置参数。它要求返回一个 tuple 类型的 ‘args’，用于解封时传递给
     *note __new__(): 974. 方法。

     如果定义了 *note __getnewargs_ex__(): 1e23.，那么 *note
     __getnewargs__(): 7a1. 就不会被调用。

     3.6 版更變: 在 Python 3.6 前，第 2、3 版协议会调用 *note
     __getnewargs__(): 7a1.，更高版本协议会调用 *note
     __getnewargs_ex__(): 1e23.。

 -- 成員函式: object.__getstate__ ()

     类还可以进一步控制其实例的封存过程。如果类定义了 *note
     __getstate__(): ec5.，它就会被调用，其返回的对象是被当做实例内容来
     封存的，否则封存的是实例的 __dict__。如果 *note __getstate__():
     ec5. 未定义，实例的 *note __dict__: 5f5. 会被照常封存。

 -- 成員函式: object.__setstate__ (state)

     当解封时，如果类定义了 *note __setstate__(): 2d1.，就会在已解封状态
     下调用它。此时不要求实例的 state 对象必须是 dict。没有定义此方法的
     话，先前封存的 state 对象必须是 dict，且该 dict 内容会在解封时赋给
     新实例的 __dict__。

          備註: 如果 *note __getstate__(): ec5. 返回 False，那么在解封时
          就不会调用 *note __setstate__(): 2d1. 方法。

参考 *note 处理有状态的对象: 1e24. 一段获取如何使用 *note
__getstate__(): ec5. 和 *note __setstate__(): 2d1. 方法的更多信息。

     備註: 在解封时，实例的某些方法例如 *note __getattr__(): 42a, *note
     __getattribute__(): 549. 或 *note __setattr__(): eee. 可能会被调用
     。 由于这些方法可能要求某些内部不变量为真值，因此该类型应当实现
     *note __new__(): 974. 以建立这样的不变量，因为当解封一个实例时
     *note __init__(): e23. 并不会被调用。

可以看出，其实 pickle 并不直接调用上面的几个函数。事实上，这几个函数是复
制协议的一部分，它们实现了 *note __reduce__(): 2d0. 这一特殊接口。复制协
议提供了统一的接口，用于在封存或复制对象的过程中取得所需数据。(1)

尽管这个协议功能很强，但是直接在类中实现 *note __reduce__(): 2d0. 接口容
易产生错误。因此，设计类时应当尽可能的使用高级接口（比如 *note
__getnewargs_ex__(): 1e23.、*note __getstate__(): ec5. 和 *note
__setstate__(): 2d1.）。后面仍然可以看到直接实现 *note __reduce__():
2d0. 接口的状况，可能别无他法，可能为了获得更好的性能，或者两者皆有之。

 -- 成員函式: object.__reduce__ ()

     该接口当前定义如下。*note __reduce__(): 2d0. 方法不带任何参数，并且
     应返回字符串或最好返回一个元组（返回的对象通常称为“reduce 值”）。

     如果返回字符串，该字符串会被当做一个全局变量的名称。它应该是对象相
     对于其模块的本地名称，pickle 模块会搜索模块命名空间来确定对象所属的
     模块。这种行为常在单例模式使用。

     如果返回的是元组，则应当包含 2 到 6 个元素，可选元素可以省略或设置
     为 ‘None’。每个元素代表的意义如下：

        * 一个可调用对象，该对象会在创建对象的最初版本时调用。

        * 可调用对象的参数，是一个元组。如果可调用对象不接受参数，必须提
          供一个空元组。

        * 可选元素，用于表示对象的状态，将被传给前述的 *note
          __setstate__(): 2d1. 方法。 如果对象没有此方法，则这个元素必须
          是字典类型，并会被添加至 *note __dict__: 5f5. 属性中。

        * 可选元素，一个返回连续项的迭代器（而不是序列）。这些项会被
          ‘obj.append(item)’ 逐个加入对象，或被
          ‘obj.extend(list_of_items)’ 批量加入对象。这个元素主要用于
          list 的子类，也可以用于那些正确实现了 ‘append()’ 和 ‘extend()’
          方法的类。（具体是使用 ‘append()’ 还是 ‘extend()’ 取决于
          pickle 协议版本以及待插入元素的项数，所以这两个方法必须同时被
          类支持。）

        * 可选元素，一个返回连续键值对的迭代器（而不是序列）。这些键值对
          将会以 ‘obj[key] = value’ 的方式存储于对象中。该元素主要用于
          dict 子类，也可以用于那些实现了 *note __setitem__(): d2a. 的类
          。

        * 可选元素，一个带有 ‘(obj, state)’ 签名的可调用对象。该可调用对
          象允许用户以编程方式控制特定对象的状态更新行为，而不是使用
          ‘obj’ 的静态 *note __setstate__(): 2d1. 方法。如果此处不是
          ‘None’，则此可调用对象的优先级高于 ‘obj’ 的 *note
          __setstate__(): 2d1.。

          3.8 版新加入: 新增了元组的第 6 项，可选元素 ‘(obj, state)’。

 -- 成員函式: object.__reduce_ex__ (protocol)

     作为替代选项，也可以实现 *note __reduce_ex__(): 1b47. 方法。 此方法
     的唯一不同之处在于它应接受一个整型参数用于指定协议版本。 如果定义了
     这个函数，则会覆盖 *note __reduce__(): 2d0. 的行为。 此外，*note
     __reduce__(): 2d0. 方法会自动成为扩展版方法的同义词。 这个函数主要
     用于为以前的 Python 版本提供向后兼容的 reduce 值。

* Menu:

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

   ---------- Footnotes ----------

   (1) (4) *note copy: 25. 模块使用这一协议实现浅层 (shallow) 和深层
(deep) 复制操作。


File: python.info,  Node: 持久化外部对象,  Next: Dispatch 表,  Up: 封存类实例

5.12.1.8 持久化外部对象
.......................

为了获取对象持久化的利益， *note pickle: ca. 模块支持引用已封存数据流之
外的对象。 这样的对象是通过一个持久化 ID 来引用的，它应当是一个由字母数
字类字符组成的字符串 (对于第 0 版协议) (1) 或是一个任意对象 (用于任意新
版协议)。

*note pickle: ca. 模块不提供对持久化 ID 的解析工作，它将解析工作分配给用
户定义的方法，分别是 pickler 中的 *note persistent_id(): 1e14. 方法和
unpickler 中的 *note persistent_load(): 1e15. 方法。

要通过持久化 ID 将外部对象封存，必须在 pickler 中实现 *note
persistent_id(): 1e14. 方法，该方法接受需要被封存的对象作为参数，返回一
个 ‘None’ 或返回该对象的持久化 ID。如果返回 ‘None’，该对象会被按照默认方
式封存为数据流。如果返回字符串形式的持久化 ID，则会封存这个字符串并加上
一个标记，这样 unpickler 才能将其识别为持久化 ID。

要解封外部对象，Unpickler 必须实现 *note persistent_load(): 1e15. 方法，
接受一个持久化 ID 对象作为参数并返回一个引用的对象。

下面是一个全面的例子，展示了如何使用持久化 ID 来封存外部对象。

     # 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()

   ---------- Footnotes ----------

   (1) (5) 对字母数字类字符的限制是由于持久化 ID 在协议版本 0 中是由分行
符来分隔的。 因此如果持久化 ID 中出现任何形式的分行符，封存结果就将变得
无法读取。


File: python.info,  Node: Dispatch 表,  Next: 处理有状态的对象,  Prev: 持久化外部对象,  Up: 封存类实例

5.12.1.9 Dispatch 表
....................

如果想对某些类进行自定义封存，而又不想在类中增加用于封存的代码，就可以创
建带有特殊 dispatch 表的 pickler。

在 *note copyreg: 26. 模块的 ‘copyreg.dispatch_table’ 中定义了全局
dispatch 表。因此，可以使用 ‘copyreg.dispatch_table’ 修改后的副本作为自
有 dispatch 表。

例如

     f = io.BytesIO()
     p = pickle.Pickler(f)
     p.dispatch_table = copyreg.dispatch_table.copy()
     p.dispatch_table[SomeClass] = reduce_SomeClass

创建了一个带有自有 dispatch 表的 *note pickle.Pickler: 33b. 实例，它可以
对 ‘SomeClass’ 类进行特殊处理。另外，下列代码

     class MyPickler(pickle.Pickler):
         dispatch_table = copyreg.dispatch_table.copy()
         dispatch_table[SomeClass] = reduce_SomeClass
     f = io.BytesIO()
     p = MyPickler(f)

完成了相同的操作，但所有 ‘MyPickler’ 的实例都会共用同一份 dispatch 表。
使用 *note copyreg: 26. 模块实现的等效代码是

     copyreg.pickle(SomeClass, reduce_SomeClass)
     f = io.BytesIO()
     p = pickle.Pickler(f)


File: python.info,  Node: 处理有状态的对象,  Prev: Dispatch 表,  Up: 封存类实例

5.12.1.10 处理有状态的对象
..........................

下面的示例展示了如何修改类在封存时的行为。其中 ‘TextReader’ 类打开了一个
文本文件，每次调用其 ‘readline()’ 方法则返回行号和该行的字符。 在封存这
个 ‘TextReader’ 的实例时，`除了' 文件对象，其他属性都会被保存。 当解封实
例时，需要重新打开文件，然后从上次的位置开始继续读取。实现这些功能需要实
现 *note __setstate__(): 2d1. 和 *note __getstate__(): ec5. 方法。

     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

使用方法如下所示：

     >>> 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!'


File: python.info,  Node: 类型，函数和其他对象的自定义归约,  Next: 外部缓冲区,  Prev: 封存类实例,  Up: pickle --- Python 对象序列化

5.12.1.11 类型，函数和其他对象的自定义归约
..........................................

3.8 版新加入.

有时，*note dispatch_table: b44. 可能不够灵活。 特别是当我们想要基于对象
类型以外的其他规则来对封存进行定制，或是当我们想要对函数和类的封存进行定
制的时候。

对于那些情况，可能要基于 *note Pickler: 33b. 类进行子类化并实现 *note
reducer_override(): 33c. 方法。 此方法可返回任意的归约元组 (参见 *note
__reduce__(): 2d0.)。 它也可以选择返回 ‘NotImplemented’ 来回退到传统行为
。

如果同时定义了 *note dispatch_table: b44. 和 *note reducer_override():
33c.，则 *note reducer_override(): 33c. 方法具有优先权。

     備註: 出于性能理由，可能不会为以下对象调用 *note
     reducer_override(): 33c.: ‘None’, ‘True’, ‘False’, 以及 *note int:
     204, *note float: 1fd, *note bytes: 172, *note str: 205, *note
     dict: 164, *note set: 1f6, *note frozenset: 1f7, *note list: 1f8. 和
     *note tuple: 1a2. 的具体实例。

以下是一个简单的例子，其中我们允许封存并重新构建一个给定的类:

     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


File: python.info,  Node: 外部缓冲区,  Next: 限制全局变量,  Prev: 类型，函数和其他对象的自定义归约,  Up: pickle --- Python 对象序列化

5.12.1.12 外部缓冲区
....................

3.8 版新加入.

在某些场景中，*note pickle: ca. 模块会被用来传输海量的数据。 因此，最小
化内存复制次数以保证性能和节省资源是很重要的。 但是 *note pickle: ca. 模
块的正常运作会将图类对象结构转换为字节序列流，因此在本质上就要从封存流中
来回复制数据。

如果 `provider' (待传输对象类型的实现) 和 `consumer' (通信系统的实现) 都
支持 pickle 第 5 版或更高版本所提供的外部传输功能，则此约束可以被撤销。

* Menu:

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


File: python.info,  Node: 提供方 API,  Next: 使用方 API,  Up: 外部缓冲区

5.12.1.13 提供方 API
....................

大的待封存数据对象必须实现协议 5 及以上版本专属的 *note __reduce_ex__():
1b47. 方法，该方法将为任意大的数据返回一个 *note PickleBuffer: 1e12. 实
例（而不是 *note bytes: 172. 对象等）。

*note PickleBuffer: 1e12. 对象会 `表明' 底层缓冲区可被用于外部数据传输。
那些对象仍将保持与 *note pickle: ca. 模块的正常用法兼容。 但是，使用方也
可以选择告知 *note pickle: ca. 它们将自行处理那些缓冲区。


File: python.info,  Node: 使用方 API,  Next: 示例<7>,  Prev: 提供方 API,  Up: 外部缓冲区

5.12.1.14 使用方 API
....................

当序列化一个对象图时，通信系统可以启用对所生成 *note PickleBuffer: 1e12.
对象的定制处理。

发送端需要传递 `buffer_callback' 参数到 *note Pickler: 33b. (或是到
*note dump(): 1e0c. 或 *note dumps(): ec3. 函数)，该回调函数将在封存对象
图时附带每个所生成的 *note PickleBuffer: 1e12. 被调用。 由
`buffer_callback' 所累积的缓冲区的数据将不会被拷贝到 pickle 流，而是仅插
入一个简单的标记。

接收端需要传递 `buffers' 参数到 *note Unpickler: 1e0b. (或是到 *note
load(): 6b9. 或 *note loads(): 6ba. 函数)，其值是一个由缓冲区组成的可迭
代对象，它会被传递给 `buffer_callback'。 该可迭代对象应当按其被传递给
`buffer_callback' 时的顺序产生缓冲区。 这些缓冲区将提供对象重构造器所期
望的数据，对这些数据的封存产生了原本的 *note PickleBuffer: 1e12. 对象。

在发送端和接受端之间，通信系统可以自由地实现它自己用于外部缓冲区的传输机
制。 潜在的优化包括使用共享内存或基于特定数据类型的压缩等。


File: python.info,  Node: 示例<7>,  Prev: 使用方 API,  Up: 外部缓冲区

5.12.1.15 示例
..............

下面是一个小例子，在其中我们实现了一个 *note bytearray: 173. 的子类，能
够用于外部缓冲区封存:

     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)

重构造器 (‘_reconstruct’ 类方法) 会在缓冲区的提供对象具有正确类型时返回
该对象。 在此小示例中这是模拟零拷贝行为的便捷方式。

在使用方，我们可以按通常方式封存那些对象，它们在反序列化时将提供原始对象
的一个副本:

     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

但是如果我们传入 `buffer_callback' 然后在反序列化时给回累积的缓冲区，我
们就能够取回原始对象:

     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

这个例子受限于 *note bytearray: 173. 会自行分配内存这一事实：你无法基于
另一个对象的内存创建 *note bytearray: 173. 的实例。 但是，第三方数据类型
例如 NumPy 数组则没有这种限制，允许在单独进程或系统间传输时使用零拷贝的
封存（或是尽可能少地拷贝） 。

也參考
......

PEP 574(1) – 带有外部数据缓冲区的 pickle 协议 5

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0574


File: python.info,  Node: 限制全局变量,  Next: 性能<2>,  Prev: 外部缓冲区,  Up: pickle --- Python 对象序列化

5.12.1.16 限制全局变量
......................

默认情况下，解封将会导入在 pickle 数据中找到的任何类或函数。 对于许多应
用来说，此行为是不可接受的，因为它会允许解封器导入并发起调用任意代码。 只
须考虑当这个手工构建的 pickle 数据流被加载时会做什么:

     >>> import pickle
     >>> pickle.loads(b"cos\nsystem\n(S'echo hello world'\ntR.")
     hello world
     0

在这个例子里，解封器导入 *note os.system(): e86. 函数然后应用字符串参数
"echo hello world"。 虽然这个例子不具攻击性，但是不难想象别人能够通过此
方式对你的系统造成损害。

出于这样的理由，你可能会希望通过定制 *note Unpickler.find_class(): 1e1d.
来控制要解封的对象。 与其名称所提示的不同，*note Unpickler.find_class():
1e1d. 会在执行对任何全局对象（例如一个类或一个函数）的请求时被调用。 因
此可以完全禁止全局对象或是将它们限制在一个安全的子集中。

下面的例子是一个解封器，它只允许某一些安全的来自 *note builtins: 12. 模
块的类被加载:

     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()

我们这个解封器的一个示例用法所达成的目标:

     >>> 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

正如我们这个例子所显示的，对于允许解封的对象你必须要保持谨慎。 因此如果
要保证安全，你可以考虑其他选择例如 *note xmlrpc.client: 148. 中的编组
API 或是第三方解决方案。


File: python.info,  Node: 性能<2>,  Next: 示例<8>,  Prev: 限制全局变量,  Up: pickle --- Python 对象序列化

5.12.1.17 性能
..............

较新版本的 pickle 协议（第 2 版或更高）具有针对某些常见特性和内置类型的
高效二进制编码格式。 此外，*note pickle: ca. 模块还拥有一个以 C 编写的透
明优化器。


File: python.info,  Node: 示例<8>,  Prev: 性能<2>,  Up: pickle --- Python 对象序列化

5.12.1.18 示例
..............

对于最简单的代码，请使用 *note dump(): 1e0c. 和 *note load(): 6b9. 函数
。

     import pickle

     # An arbitrary collection of objects supported by pickle.
     data = {
         'a': [1, 2.0, 3, 4+6j],
         '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)

以下示例读取之前封存的数据。

     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)

也參考
......

模块 *note copyreg: 26.

     为扩展类型提供 pickle 接口所需的构造函数。

模块 *note pickletools: cb.

     用于处理和分析已封存数据的工具。

模块 *note shelve: e7.

     带索引的数据库，用于存放对象，使用了 *note pickle: ca. 模块。

模块 *note copy: 25.

     浅层 (shallow) 和深层 (deep) 复制对象操作

模块 *note marshal: b0.

     高效地序列化内置类型的数据。

註解
....


File: python.info,  Node: copyreg --- 注册配合 pickle 模块使用的函数,  Next: shelve --- Python 对象持久化,  Prev: pickle --- Python 对象序列化,  Up: 数据持久化

5.12.2 ‘copyreg’ — 注册配合 ‘pickle’ 模块使用的函数
---------------------------------------------------

`源代码:' Lib/copyreg.py(1)

__________________________________________________________________

*note copyreg: 26. 模块提供了可在封存特定对象时使用的一种定义函数方式。
*note pickle: ca. 和 *note copy: 25. 模块会在封存/拷贝特定对象时使用这些
函数。 此模块提供了非类对象构造器的相关配置信息。 这样的构造器可以是工厂
函数或类实例。

 -- 函式: copyreg.constructor (object)

     将 `object' 声明为一个有效的构造器。 如果 `object' 是不可调用的（因
     而不是一个有效的构造器）则会引发 *note TypeError: 1fe.。

 -- 函式: copyreg.pickle (type, function, constructor=None)

     声明该 `function' 应当被用作 `type' 类型对象的“归约函数”。
     `function' 应当返回字符串或包含两到三个元素的元组。

     如果提供了可选的 `constructor' 形参，它应当是一个可用来重建相应对象
     的可调用对象，在调用该对象时应传入由 `function' 所返回的参数元组。
     如果 `object' 是一个类或 `constructor' 是不可调用的则将引发 *note
     TypeError: 1fe.。

     请查看 *note pickle: ca. 模块了解 `function' 和 `constructor' 所要
     求的接口的详情。 请注意一个 pickler 对象或 *note pickle.Pickler:
     33b. 的子类的 *note dispatch_table: b44. 属性也可以被用来声明归约函
     数。

* Menu:

* 示例: 示例<9>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/copyreg.py


File: python.info,  Node: 示例<9>,  Up: copyreg --- 注册配合 pickle 模块使用的函数

5.12.2.1 示例
.............

以下示例将会显示如何注册一个封存函数，以及如何来使用它：

     >>> 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...


File: python.info,  Node: shelve --- Python 对象持久化,  Next: marshal --- 内部 Python 对象序列化,  Prev: copyreg --- 注册配合 pickle 模块使用的函数,  Up: 数据持久化

5.12.3 ‘shelve’ — Python 对象持久化
-----------------------------------

`源代码:' Lib/shelve.py(1)

__________________________________________________________________

"Shelf" 是一种持久化的类似字典的对象。 与 "dbm" 数据库的区别在于 Shelf 中
的值（不是键！）实际上可以为任意 Python 对象 — 即 *note pickle: ca. 模块
能够处理的任何东西。 这包括大部分类实例、递归数据类型，以及包含大量共享
子对象的对象。 键则为普通的字符串。

 -- 函式: shelve.open (filename, flag='c', protocol=None,
          writeback=False)

     打开一个持久化字典。 filename 指定下层数据库的基准文件名。 作为附带
     效果，会为 filename 添加一个扩展名并且可能创建更多的文件。 默认情况
     下，下层数据库会以读写模式打开。 可选的 `flag' 形参具有与 *note
     dbm.open(): 91d. `flag' 形参相同的含义。

     默认会使用第 3 版 pickle 协议来序列化值。 pickle 协议版本可通过
     `protocol' 形参来指定。

     由于 Python 语义的限制，Shelf 对象无法确定一个可变的持久化字典条目
     在何时被修改。 默认情况下 `只有' 在被修改对象再赋值给 shelf 时才会
     写入该对象 (参见 *note 示例: 1e38.)。 如果可选的 `writeback' 形参设
     为 ‘True’，则所有被访问的条目都将在内存中被缓存，并会在 *note
     sync(): 1e39. 和 *note close(): 1e3a. 时被写入；这可以使得对持久化
     字典中可变条目的修改更方便，但是如果访问的条目很多，这会消耗大量内
     存作为缓存，并会使得关闭操作变得非常缓慢，因为所有被访问的条目都需
     要写回到字典（无法确定被访问的条目中哪个是可变的，也无法确定哪个被
     实际修改了）。

          備註: 请不要依赖于 Shelf 的自动关闭功能；当你不再需要时应当总
          是显式地调用 *note close(): 1e3a.，或者使用 *note
          shelve.open(): 1e37. 作为上下文管理器:

               with shelve.open('spam') as db:
                   db['eggs'] = 'eggs'
     警告: 由于 *note shelve: e7. 模块需要 *note pickle: ca. 的支持，因
     此从不可靠的来源载入 shelf 是不安全的。 与 pickle 一样，载入 Shelf
     时可以执行任意代码。

Shelf 对象支持字典所支持的大多数方法和运算（除了拷贝、构造器以及 ‘|’ 和
‘|=’ 运算符）。 这样就能方便地将基于字典的脚本转换为要求持久化存储的脚本
。

额外支持的两个方法：

 -- 成員函式: Shelf.sync ()

     如果 Shelf 打开时将 `writeback' 设为 *note True: 593. 则写回缓存中
     的所有条目。 如果可行还会清空缓存并将持久化字典同步到磁盘。 此方法
     会在使用 *note close(): 1e3a. 关闭 Shelf 时自动被调用。

 -- 成員函式: Shelf.close ()

     同步并关闭持久化 `dict' 对象。 对已关闭 Shelf 的操作将失败并引发
     *note ValueError: 16d.。

也參考
......

持久化字典方案(2)，使用了广泛支持的存储格式并具有原生字典的速度。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/shelve.py

   (2) https://code.activestate.com/recipes/576642/


File: python.info,  Node: 限制,  Next: 示例<10>,  Up: shelve --- Python 对象持久化

5.12.3.1 限制
.............

   * 可选择使用哪种数据库包 (例如 *note dbm.ndbm: 34. 或 *note dbm.gnu:
     33.) 取决于支持哪种接口。 因此使用 *note dbm: 31. 直接打开数据库是
     不安全的。 如果使用了 *note dbm: 31.，数据库同样会（不幸地）受限于
     它 — 这意味着存储在数据库中的（封存形式的）对象尺寸应当较小，并且在
     少数情况下键冲突有可能导致数据库拒绝更新。

   * *note shelve: e7. 模块不支持对 Shelf 对象的 `并发' 读/写访问。 （多
     个同时读取访问则是安全的。） 当一个程序打开一个 shelve 对象来写入时
     ，不应再有其他程序同时打开它来读取或写入。 Unix 文件锁定可被用来解
     决此问题，但这在不同 Unix 版本上会存在差异，并且需要有关所用数据库
     实现的细节知识。

 -- 類別: shelve.Shelf (dict, protocol=None, writeback=False,
          keyencoding='utf-8')

     *note collections.abc.MutableMapping: ace. 的一个子类，它会将封存的
     值保存在 `dict' 对象中。

     默认会使用第 3 版 pickle 协议来序列化值。 pickle 协议版本可通过
     `protocol' 形参来指定。 请参阅 *note pickle: ca. 文档来查看 pickle
     协议的相关讨论。

     如果 `writeback' 形参为 ‘True’，对象将为所有访问过的条目保留缓存并
     在同步和关闭时将它们写回到 `dict'。 这允许对可变的条目执行自然操作
     ，但是会消耗更多内存并让同步和关闭花费更长时间。

     `keyencoding' 形参是在下层字典被使用之前用于编码键的编码格式。

     *note Shelf: 997. 对象还可以被用作上下文管理器，在这种情况下它将在
     *note with: 7da. 语句块结束时自动被关闭。

     3.2 版更變: 添加了 `keyencoding' 形参；之前，键总是使用 UTF-8 编码
     。

     3.4 版更變: 添加了上下文管理器支持

 -- 類別: shelve.BsdDbShelf (dict, protocol=None, writeback=False,
          keyencoding='utf-8')

     *note Shelf: 997. 的一个子类，将 ‘first()’, ‘next()’, ‘previous()’,
     ‘last()’ 和 ‘set_location()’ 对外公开，在来自 pybsddb(1) 的第三方
     ‘bsddb’ 模块中可用，但在其他数据库模块中不可用。 传给构造器的
     `dict' 对象必须支持这些方法。 这通常是通过调用 ‘bsddb.hashopen()’,
     ‘bsddb.btopen()’ 或 ‘bsddb.rnopen()’ 之一来完成的。 可选的
     `protocol', `writeback' 和 `keyencoding' 形参具有与 *note Shelf:
     997. 类相同的含义。

 -- 類別: shelve.DbfilenameShelf (filename, flag='c', protocol=None,
          writeback=False)

     *note Shelf: 997. 的一个子类，它接受一个 `filename' 而非字典类对象
     。 下层文件将使用 *note dbm.open(): 91d. 来打开。 默认情况下，文件
     将以读写模式打开。 可选的 `flag' 形参具有与 *note open(): 1e37. 函
     数相同的含义。 可选的 `protocol' 和 `writeback' 形参具有与 *note
     Shelf: 997. 类相同的含义。

   ---------- Footnotes ----------

   (1) https://www.jcea.es/programacion/pybsddb.htm


File: python.info,  Node: 示例<10>,  Prev: 限制,  Up: shelve --- Python 对象持久化

5.12.3.2 示例
.............

对接口的总结如下 (‘key’ 为字符串，‘data’ 为任意对象):

     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

也參考
......

模块 *note dbm: 31.

     ‘dbm’ 风格数据库的泛型接口。

模块 *note pickle: ca.

     *note shelve: e7. 所使用的对象序列化。


File: python.info,  Node: marshal --- 内部 Python 对象序列化,  Next: dbm --- Unix "数据库" 接口,  Prev: shelve --- Python 对象持久化,  Up: 数据持久化

5.12.4 ‘marshal’ — 内部 Python 对象序列化
-----------------------------------------

__________________________________________________________________

此模块包含一此能以二进制格式来读写 Python 值的函数。 这种格式是 Python 专
属的，但是独立于特定的机器架构（即你可以在一台 PC 上写入某个 Python 值，
将文件传到一台 Sun 上并在那里读取它）。 这种格式的细节有意不带文档说明；
它可能在不同 Python 版本中发生改变（但这种情况极少发生）。 (1)

这不是一个通用的“持久化”模块。 对于通用的持久化以及通过 RPC 调用传递
Python 对象，请参阅 *note pickle: ca. 和 *note shelve: e7. 等模块。
*note marshal: b0. 模块主要是为了支持读写 ‘.pyc’ 文件形式“伪编译”代码的
Python 模块。 因此，Python 维护者保留在必要时以不向下兼容的方式修改
marshal 格式的权利。 如果你要序列化和反序列化 Python 对象，请改用 *note
pickle: ca. 模块 – 其执行效率相当，版本独立性有保证，并且 pickle 还支持
比 marshal 更多样的对象类型。

     警告: *note marshal: b0. 模块对于错误或恶意构建的数据来说是不安全的
     。 永远不要 unmarshal 来自不受信任的或未经验证的来源的数据。

不是所有 Python 对象类型都受支持；一般来说，此模块只能写入和读取不依赖于
特定 Python 调用的对象。 下列类型是受支持的：布尔值、整数、浮点数、复数
、字符串、字节串、字节数组、元组、列表、集合、冻结集合、字典和代码对象，
需要了解的一点是元组、列表、集合、冻结集合和字典只在其所包含的值也是这些
值时才受支持。 单例对象 *note None: 203, *note Ellipsis: 1740. and *note
StopIteration: 581. 也可以被 marshal 和 unmarshal。 对于 `version' 低于
3 的格式，递归列表、集合和字典无法被写入（见下文）。

有些函数可以读/写文件，还有些函数可以操作字节类对象。

这个模块定义了以下函数：

 -- 函式: marshal.dump (value, file[, version])

     向打开的文件写入值。 值必须为受支持的类型。 文件必须为可写的 *note
     binary file: 1e01.。

     如果值具有（或所包含的对象具有）不受支持的类型，则会引发 *note
     ValueError: 16d. — 但是将向文件写入垃圾数据。 对象也将不能正确地通
     过 *note load(): 112b. 重新读取。

     `version' 参数指明 ‘dump’ 应当使用的数据格式（见下文）。

     引发一个 *note 审计事件: fa1. ‘marshal.dumps’，附带参数 ‘value’,
     ‘version’。

 -- 函式: marshal.load (file)

     从打开的文件读取一个值并返回。 如果读不到有效的值（例如由于数据为不
     同 Python 版本的不兼容 marshal 格式），则会引发 *note EOFError:
     d34, *note ValueError: 16d. 或 *note TypeError: 1fe.。 文件必须为可
     读的 *note binary file: 1e01.。

     引发一个 *note 审计事件: fa1. ‘marshal.load’，没有附带参数。

          備註: 如果通过 *note dump(): 1e42. marshal 了一个包含不受支持
          类型的对象，*note load(): 112b. 将为不可 marshal 的类型替换
          ‘None’。

     3.9.7 版更變: 使用此调用为每个代码对象引发一个 ‘code.__new__’ 审计
     事件。 现在它会为整个载入操作引发单个 ‘marshal.load’ 事件。

 -- 函式: marshal.dumps (value[, version])

     返回将通过 ‘dump(value, file)’ 被写入一个文件的字节串对象。 值必须
     属于受支持的类型。 如果值属于（或包含的对象属于）不受支持的类型则会
     引发 *note ValueError: 16d.。

     `version' 参数指明 ‘dumps’ 应当使用的数据类型（见下文）。

     引发一个 *note 审计事件: fa1. ‘marshal.dumps’，附带参数 ‘value’,
     ‘version’。

 -- 函式: marshal.loads (bytes)

     将 *note bytes-like object: 6df. 转换为一个值。 如果找不到有效的值
     ，则会引发 *note EOFError: d34, *note ValueError: 16d. 或 *note
     TypeError: 1fe.。 输入的额外字节串会被忽略。

     引发一个 *note 审计事件: fa1. ‘marshal.loads’，附带参数 ‘bytes’。

     3.9.7 版更變: 使用此调用为每个代码对象引发一个 ‘code.__new__’ 审计
     事件。 现在它会为整个载入操作引发单个 ‘marshal.loads’ 事件。

此外，还定义了以下常量：

 -- Data: marshal.version

     指明模块所使用的格式。 第 0 版为历史格式，第 1 版为共享固化的字符串
     ，第 2 版对浮点数使用二进制格式。 第 3 版添加了对于对象实例化和递归
     的支持。 目前使用的为第 4 版。

註解
....

   ---------- Footnotes ----------

   (1) (1) 此模块的名称来源于 Modula-3 (及其他语言) 的设计者所使用的术语
，他们使用术语 "marshal" 来表示以自包含的形式传输数据。 严格地说，将数据
从内部形式转换为外部形式 (例如用于 RPC 缓冲区) 称为 "marshal" 而其逆过程
则称为 "unmarshal"。


File: python.info,  Node: dbm --- Unix "数据库" 接口,  Next: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块,  Prev: marshal --- 内部 Python 对象序列化,  Up: 数据持久化

5.12.5 ‘dbm’ — Unix "数据库" 接口
---------------------------------

`源代码:' Lib/dbm/__init__.py(1)

__________________________________________________________________

*note dbm: 31. 是一种泛用接口，针对各种 DBM 数据库 — 包括 *note dbm.gnu:
33. 或 *note dbm.ndbm: 34.。 如果未安装这些模块中的任何一种，则将使用
*note dbm.dumb: 32. 模块中慢速但简单的实现。 还有一个适用于 Oracle
Berkeley DB 的 第三方接口(2)。

 -- 例外: dbm.error

     一个元组，其中包含每个受支持的模块可引发的异常，另外还有一个名为
     *note dbm.error: 1e47. 的特殊异常作为第一项 — 后者最在引发 *note
     dbm.error: 1e47. 时被使用。

 -- 函式: dbm.whichdb (filename)

     此函数会猜测各种简单数据库模块中的哪一个是可用的 — *note dbm.gnu:
     33, *note dbm.ndbm: 34. 还是 *note dbm.dumb: 32. — 应该被用来打开给
     定的文件。

     返回下列值中的一个：如果文件由于不可读或不存在而无法打开则返回
     ‘None’；如果文件的格式无法猜测则返回空字符串 (‘''’)；或是包含所需模
     块名称的字符串，例如 ‘'dbm.ndbm'’ 或 ‘'dbm.gnu'’。

 -- 函式: dbm.open (file, flag='r', mode=0o666)

     打开数据库文件 `file' 并返回一个相应的对象。

     如果数据库文件已存在，则使用 *note whichdb(): 1e48. 函数来确定其类
     型和要使用的适当模块；如果文件不存在，则会使用上述可导入模块中的第
     一个。

     可选的 `flag' 参数可以是：

     值            意义
                   
     --------------------------------------------------------------
                   
     ‘'r'’         以只读方式打开现有数据库（默认）
                   
                   
     ‘'w'’         以读写方式打开现有数据库
                   
                   
     ‘'c'’         以读写方式打开数据库，如果不存在则创建它
                   
                   
     ‘'n'’         始终创建一个新的空数据库，以读写方式打开
                   

     可选的 `mode' 参数是文件的 Unix 模式，仅在要创建数据库时才会被使用
     。 其默认值为八进制数 ‘0o666’ (并将被当前的 umask 所修改)。

*note open(): 91d. 所返回的对象支持与字典相同的基本功能；可以存储、获取
和删除键及其对应的值，并可使用 *note in: 179. 运算符和 ‘keys()’ 方法，以
及 ‘get()’ 和 ‘setdefault()’。

3.2 版更變: 现在 ‘get()’ 和 ‘setdefault()’ 在所有数据库模块中均可用。

3.8 版更變: 从只读数据库中删除键将引发数据库模块专属的错误而不是 *note
KeyError: 3e9.。

键和值总是被存储为字节串。 这意味着当使用字符串时它们会在被存储之前隐式
地转换至默认编码格式。

这些对象也支持在 *note with: 7da. 语句中使用，当语句结束时将自动关闭它们
。

3.4 版更變: 向 *note open(): 91d. 所返回的对象添加了上下文管理协议的原生
支持。

以下示例记录了一些主机名和对应的标题，随后将数据库的内容打印出来。:

     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.

也參考
......

模块 *note shelve: e7.

     存储非字符串数据的持久化模块。

以下部分描述了各个单独的子模块。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/dbm/__init__.py

   (2) https://www.jcea.es/programacion/pybsddb.htm


File: python.info,  Node: dbm gnu --- GNU 对 dbm 的重解析,  Next: dbm ndbm --- 基于 ndbm 的接口,  Up: dbm --- Unix "数据库" 接口

5.12.5.1 ‘dbm.gnu’ — GNU 对 dbm 的重解析
........................................

`源代码:' Lib/dbm/gnu.py(1)

__________________________________________________________________

此模块与 *note dbm: 31. 模块很相似，但是改用 GNU 库 ‘gdbm’ 来提供某些附
加功能。 请注意由 *note dbm.gnu: 33. 与 *note dbm.ndbm: 34. 所创建的文件
格式是不兼容的。

*note dbm.gnu: 33. 模块提供了对 GNU DBM 库的接口。 ‘dbm.gnu.gdbm’ 对象的
行为类似于映射（字典），区别在于其键和值总是会在存储之前被转换为字节串。
打印 ‘gdbm’ 对象不会打印出键和值，并且 ‘items()’ 和 ‘values()’ 等方法也
不受支持。

 -- 例外: dbm.gnu.error

     针对 *note dbm.gnu: 33. 专属错误例如 I/O 错误引发。 *note KeyError:
     3e9. 的引发则针对一般映射错误例如指定了不正确的键。

 -- 函式: dbm.gnu.open (filename[, flag[, mode]])

     打开一个 ‘gdbm’ 数据库并返回 ‘gdbm’ 对象。 `filename' 参数为数据库
     文件名称。

     可选的 `flag' 参数可以是：

     值            意义
                   
     --------------------------------------------------------------
                   
     ‘'r'’         以只读方式打开现有数据库（默认）
                   
                   
     ‘'w'’         以读写方式打开现有数据库
                   
                   
     ‘'c'’         以读写方式打开数据库，如果不存在则创建它
                   
                   
     ‘'n'’         始终创建一个新的空数据库，以读写方式打开
                   

     下列附加字符可被添加至旗标以控制数据库的打开方式：

     值            意义
                   
     ---------------------------------------------------------------
                   
     ‘'f'’         以快速模式打开数据库。写入数据库将不会同步。
                   
                   
     ‘'s'’         同步模式。这将导致数据库的更改立即写入文件。
                   
                   
     ‘'u'’         不要鎖住資料庫
                   

     不是所有旗标都可用于所有版本的 ‘gdbm’。 模块常量 ‘open_flags’ 为包
     含受支持旗标字符的字符串。 如果指定了无效的旗标则会引发 *note
     error: 3e7.。

     可选的 `mode' 参数是文件的 Unix 模式，仅在要创建数据库时才会被使用
     。 其默认值为八进制数 ‘0o666’。

     除了与字典类似的方法，‘gdbm’ 对象还有以下方法：

      -- 成員函式: gdbm.firstkey ()

          使用此方法和 *note nextkey(): 1e4b. 方法可以循环遍历数据库中的
          每个键。 遍历的顺序是按照 ‘gdbm’ 的内部哈希值，而不会根据键的
          值排序。 此方法将返回起始键。

      -- 成員函式: gdbm.nextkey (key)

          在遍历中返回 `key' 之后的的下一个键。 以下代码将打印数据库
          ‘db’ 中的每个键，而不会在内存中创建一个包含所有键的列表:

               k = db.firstkey()
               while k is not None:
                   print(k)
                   k = db.nextkey(k)

      -- 成員函式: gdbm.reorganize ()

          如果你进行了大量删除操作并且想要缩减 ‘gdbm’ 文件所使用的空间，
          此例程将可重新组织数据库。 除非使用此重组功能否则 ‘gdbm’ 对象
          不会缩减数据库文件大小；在其他情况下，被删除的文件空间将会保留
          并在添加新的 (键, 值) 对时被重用。

      -- 成員函式: gdbm.sync ()

          当以快速模式打开数据库时，此方法会将任何未写入数据强制写入磁盘
          。

      -- 成員函式: gdbm.close ()

          关闭 ‘gdbm’ 数据库。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/dbm/gnu.py


File: python.info,  Node: dbm ndbm --- 基于 ndbm 的接口,  Next: dbm dumb --- 便携式 DBM 实现,  Prev: dbm gnu --- GNU 对 dbm 的重解析,  Up: dbm --- Unix "数据库" 接口

5.12.5.2 ‘dbm.ndbm’ — 基于 ndbm 的接口
......................................

`源代码:' Lib/dbm/ndbm.py(1)

__________________________________________________________________

*note dbm.ndbm: 34. 模块提供了对 Unix "(n)dbm" 库的接口。 Dbm 对象的行为
类似于映射（字典），区别在于其键和值总是被存储为字节串。 打印 ‘dbm’ 对象
不会打印出键和值，并且 ‘items()’ 和 ‘values()’ 等方法也不受支持。

此模块可与 "经典classic" ndbm 接口或 GNU GDBM 兼容接口一同使用。 在 Unix
上，‘configure’ 脚本将尝试定位适当的头文件来简化此模块的构建。

 -- 例外: dbm.ndbm.error

     针对 *note dbm.ndbm: 34. 专属错误例如 I/O 错误引发。 *note
     KeyError: 3e9. 的引发则针对一般映射错误例如指定了不正确的键。

 -- Data: dbm.ndbm.library

     所使用的 ‘ndbm’ 实现库的名称。

 -- 函式: dbm.ndbm.open (filename[, flag[, mode]])

     打开一个 dbm 数据库并返回 ‘ndbm’ 对象。 `filename' 参数为数据库文件
     名称（不带 ‘.dir’ 或 ‘.pag’ 扩展名）。

     可选的 `flag' 参数必须是下列值之一：

     值            意义
                   
     --------------------------------------------------------------
                   
     ‘'r'’         以只读方式打开现有数据库（默认）
                   
                   
     ‘'w'’         以读写方式打开现有数据库
                   
                   
     ‘'c'’         以读写方式打开数据库，如果不存在则创建它
                   
                   
     ‘'n'’         始终创建一个新的空数据库，以读写方式打开
                   

     可选的 `mode' 参数是文件的 Unix 模式，仅在要创建数据库时才会被使用
     。 其默认值为八进制数 ‘0o666’ (并将被当前的 umask 所修改)。

     除了与字典类似的方法，‘ndbm’ 对象还有以下方法：

      -- 成員函式: ndbm.close ()

          关闭 ‘ndbm’ 数据库。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/dbm/ndbm.py


File: python.info,  Node: dbm dumb --- 便携式 DBM 实现,  Prev: dbm ndbm --- 基于 ndbm 的接口,  Up: dbm --- Unix "数据库" 接口

5.12.5.3 ‘dbm.dumb’ — 便携式 DBM 实现
.....................................

`源代码:' Lib/dbm/dumb.py(1)

     備註: *note dbm.dumb: 32. 模块的目的是在更健壮的模块不可用时作为
     *note dbm: 31. 模块的最终回退项。 *note dbm.dumb: 32. 不是为高速运
     行而编写的，也不像其他数据库模块一样被经常使用。

__________________________________________________________________

*note dbm.dumb: 32. 模块提供了一个完全以 Python 编写的持久化字典类接口。
不同于 *note dbm.gnu: 33. 等其他模块，它不需要外部库。 与其他持久化映射
一样，它的键和值也总是被存储为字节串。

该模块定义以下内容：

 -- 例外: dbm.dumb.error

     针对 *note dbm.dumb: 32. 专属错误例如 I/O 错误引发。 *note
     KeyError: 3e9. 的引发则针对一般映射例如指定了不正确的键。

 -- 函式: dbm.dumb.open (filename[, flag[, mode]])

     打开一个 ‘dumbdbm’ 数据库并返回 dumbdbm 对象。 `filename' 参数为数
     据库文件的主名称（不带任何特定扩展名）。 创建一个 dumbdbm 数据库时
     将创建多个带有 ‘.dat’ 和 ‘.dir’ 扩展名的文件。

     可选的 `flag' 参数可以是：

     值            意义
                   
     --------------------------------------------------------------
                   
     ‘'r'’         以只读方式打开现有数据库（默认）
                   
                   
     ‘'w'’         以读写方式打开现有数据库
                   
                   
     ‘'c'’         以读写方式打开数据库，如果不存在则创建它
                   
                   
     ‘'n'’         始终创建一个新的空数据库，以读写方式打开
                   

     可选的 `mode' 参数是文件的 Unix 模式，仅在要创建数据库时才会被使用
     。 其默认值为八进制数 ‘0o666’ (并将被当前的 umask 所修改)。

          警告: 当载入包含足够巨大/复杂条目的数据库时有可能导致 Python 解
          释器的崩溃，这是由于 Python AST 编译器有栈深度限制。

     3.5 版更變: *note open(): 3e1. 在 flag 值为 ‘'n'’ 时将总是创建一个
     新的数据库。

     3.8 版更變: 附带 ‘'r'’ 旗标打开的数据库现在将是只读的。 附带 ‘'r'’
     和 ‘'w'’ 旗标的打开操作不会再创建数据库。

     除了 *note collections.abc.MutableMapping: ace. 类所提供的方法，
     ‘dumbdbm’ 对象还提供了以下方法：

      -- 成員函式: dumbdbm.sync ()

          同步磁盘上的目录和数据文件。 此方法会由 ‘Shelve.sync()’ 方法来
          调用。

      -- 成員函式: dumbdbm.close ()

          关闭 ‘dumbdbm’ 数据库。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/dbm/dumb.py


File: python.info,  Node: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块,  Prev: dbm --- Unix "数据库" 接口,  Up: 数据持久化

5.12.6 ‘sqlite3’ — SQLite 数据库 DB-API 2.0 接口模块
----------------------------------------------------

`源代码：' Lib/sqlite3/(1)

__________________________________________________________________

SQLite 是一个C语言库，它可以提供一种轻量级的基于磁盘的数据库，这种数据库
不需要独立的服务器进程，也允许需要使用一种非标准的 SQL 查询语言来访问它
。一些应用程序可以使用 SQLite 作为内部数据存储。可以用它来创建一个应用程
序原型，然后再迁移到更大的数据库，比如 PostgreSQL 或 Oracle。

sqlite3 模块由 Gerhard Häring 编写。它提供了符合 DB-API 2.0 规范的接口，
这个规范是 PEP 249(2)。

To use the module, start by creating a *note Connection: 4de. object
that represents the database.  Here the data will be stored in the
‘example.db’ file:

     import sqlite3
     con = sqlite3.connect('example.db')

The special path name ‘:memory:’ can be provided to create a temporary
database in RAM.

Once a *note Connection: 4de. has been established, create a *note
Cursor: 1e57. object and call its *note execute(): 1e58. method to
perform SQL commands:

     cur = con.cursor()

     # Create table
     cur.execute('''CREATE TABLE stocks
                    (date text, trans text, symbol text, qty real, price real)''')

     # 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()

The saved data is persistent: it can be reloaded in a subsequent session
even after restarting the Python interpreter:

     import sqlite3
     con = sqlite3.connect('example.db')
     cur = con.cursor()

To retrieve data after executing a SELECT statement, either treat the
cursor as an *note iterator: 1171, call the cursor’s *note fetchone():
1e59. method to retrieve a single matching row, or call *note
fetchall(): 1e5a. to get a list of the matching rows.

下面是一个使用迭代器形式的例子：

     >>> 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)
SQL operations usually need to use values from Python variables.
However, beware of using Python’s string operations to assemble queries,
as they are vulnerable to SQL injection attacks (see the xkcd
webcomic(3) for a humorous example of what can go wrong):

     # Never do this -- insecure!
     symbol = 'RHAT'
     cur.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)

Instead, use the DB-API’s parameter substitution.  To insert a variable
into a query string, use a placeholder in the string, and substitute the
actual values into the query by providing them as a *note tuple: 1a2. of
values to the second argument of the cursor’s *note execute(): 1e58.
method.  An SQL statement may use one of two kinds of placeholders:
question marks (qmark style) or named placeholders (named style).  For
the qmark style, ‘parameters’ must be a *note sequence: 135c.  For the
named style, it can be either a *note sequence: 135c. or *note dict:
164. instance.  The length of the *note sequence: 135c. must match the
number of placeholders, or a *note ProgrammingError: ff3. is raised.  If
a *note dict: 164. is given, it must contain keys for all named
parameters.  Any extra items are ignored.  Here’s an example of both
styles:

     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()

也參考
......

‘https://www.sqlite.org’

     SQLite的主页；它的文档详细描述了它所支持的 SQL 方言的语法和可用的数
     据类型。

‘https://www.w3schools.com/sql/’

     学习 SQL 语法的教程、参考和例子。

PEP 249(4) - DB-API 2.0 规范

     Marc-André Lemburg 写的 PEP。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/sqlite3/

   (2) https://www.python.org/dev/peps/pep-0249

   (3) https://xkcd.com/327/

   (4) https://www.python.org/dev/peps/pep-0249


File: python.info,  Node: 模块函数和常量,  Next: 连接对象（Connection）,  Up: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块

5.12.6.1 模块函数和常量
.......................

 -- Data: sqlite3.apilevel

     String constant stating the supported DB-API level.  Required by
     the DB-API. Hard-coded to ‘"2.0"’.

 -- Data: sqlite3.paramstyle

     String constant stating the type of parameter marker formatting
     expected by the *note sqlite3: f2. module.  Required by the DB-API.
     Hard-coded to ‘"qmark"’.

          備註: The *note sqlite3: f2. module supports both ‘qmark’ and
          ‘numeric’ DB-API parameter styles, because that is what the
          underlying SQLite library supports.  However, the DB-API does
          not allow multiple values for the ‘paramstyle’ attribute.

 -- Data: sqlite3.version

     这个模块的版本号，是一个字符串。不是 SQLite 库的版本号。

 -- Data: sqlite3.version_info

     这个模块的版本号，是一个由整数组成的元组。不是 SQLite 库的版本号。

 -- Data: sqlite3.sqlite_version

     使用中的 SQLite 库的版本号，是一个字符串。

 -- Data: sqlite3.sqlite_version_info

     使用中的 SQLite 库的版本号，是一个整数组成的元组。

 -- Data: sqlite3.threadsafety

     Integer constant required by the DB-API, stating the level of
     thread safety the *note sqlite3: f2. module supports.  Currently
     hard-coded to ‘1’, meaning `"Threads may share the module, but not
     connections."'  However, this may not always be true.  You can
     check the underlying SQLite library’s compile-time threaded mode
     using the following query:

          import sqlite3
          con = sqlite3.connect(":memory:")
          con.execute("""
              select * from pragma_compile_options
              where compile_options like 'THREADSAFE=%'
          """).fetchall()

     Note that the SQLITE_THREADSAFE levels(1) do not match the DB-API
     2.0 ‘threadsafety’ levels.

 -- Data: sqlite3.PARSE_DECLTYPES

     这个常量可以作为 *note connect(): 4e0. 函数的 `detect_types' 参数。

     设置这个参数后，*note sqlite3: f2. 模块将解析它返回的每一列申明的类
     型。它会申明的类型的第一个单词，比如“integer primary key”，它会解析
     出“integer”，再比如“number(10)”，它会解析出“number”。然后，它会在转
     换器字典里查找那个类型注册的转换器函数，并调用它。

 -- Data: sqlite3.PARSE_COLNAMES

     这个常量可以作为 *note connect(): 4e0. 函数的 `detect_types' 参数。

     设置此参数可使得 SQLite 接口解析它所返回的每一列的列名。 它将在其中
     查找形式为 [mytype] 的字符串，然后将 ’mytype’ 确定为列的类型。 它将
     尝试在转换器字典中查找 ’mytype’ 条目，然后用找到的转换器函数来返回
     值。 在 *note Cursor.description: 1e67. 中找到的列名并不包括类型，
     举例来说，如果你在你的 SQL 中使用了像 ‘'as "Expiration date
     [datetime]"'’ 这样的写法，那么我们将解析出在第一个 ‘'['’ 之前的所有
     内容并去除前导空格作为列名：即列名将为 "Expiration date"。

 -- 函式: sqlite3.connect (database[, timeout, detect_types,
          isolation_level, check_same_thread, factory,
          cached_statements, uri])

     连接 SQLite 数据库 `database'。默认返回 *note Connection: 4de. 对象
     ，除非使用了自定义的 `factory' 参数。

     `database' 是准备打开的数据库文件的路径（绝对路径或相对于当前目录的
     相对路径），它是 *note path-like object: 472.。你也可以用
     ‘":memory:"’ 在内存中打开一个数据库。

     当一个数据库被多个连接访问的时候，如果其中一个进程修改这个数据库，
     在这个事务提交之前，这个 SQLite 数据库将会被一直锁定。`timeout' 参
     数指定了这个连接等待锁释放的超时时间，超时之后会引发一个异常。这个
     超时时间默认是 5.0（5秒）。

     `isolation_level' 参数，请查看 *note Connection: 4de. 对象的 *note
     isolation_level: 1e68. 属性。

     SQLite 原生只支持5种类型：TEXT，INTEGER，REAL，BLOB 和 NULL。如果你
     想用其它类型，你必须自己添加相应的支持。使用 `detect_types' 参数和
     模块级别的 *note register_converter(): 1e69. 函数注册**转换器** 可
     以简单的实现。

     `detect_types' 默认为 0 (即关闭，不进行类型检测)，你可以将其设为任
     意的 *note PARSE_DECLTYPES: 1e65. 和 *note PARSE_COLNAMES: 1e66. 组
     合来启用类型检测。 由于 SQLite 的行为，生成的字段类型 (例如
     ‘max(data)’) 不能被检测，即使在设置了 `detect_types' 形参时也是如此
     。 在此情况下，返回的类型为 *note str: 205.。

     默认情况下，`check_same_thread' 为 *note True: 593.，只有当前的线程
     可以使用该连接。 如果设置为 *note False: 48e.，则多个线程可以共享返
     回的连接。 当多个线程使用同一个连接的时候，用户应该把写操作进行序列
     化，以避免数据损坏。

     默认情况下，当调用 connect 方法的时候，*note sqlite3: f2. 模块使用
     了它的 *note Connection: 4de. 类。当然，你也可以创建 *note
     Connection: 4de. 类的子类，然后创建提供了 `factory' 参数的 *note
     connect(): 4e0. 方法。

     详情请查阅当前手册的 *note SQLite 与 Python 类型: 1e6a. 部分。

     *note sqlite3: f2. 模块在内部使用语句缓存来避免 SQL 解析开销。 如果
     要显式设置当前连接可以缓存的语句数，可以设置 `cached_statements' 参
     数。 当前实现的默认值是缓存100条语句。

     如果 `uri' 为真，则 `database' 被解释为 URI。 它允许您指定选项。 例
     如，以只读模式打开数据库：

          db = sqlite3.connect('file:path/to/database?mode=ro', uri=True)

     有关此功能的更多信息，包括已知选项的列表，可以在 ‘ SQLite URI 文档
     <‘https://www.sqlite.org/uri.html’>‘_ 中找到。

     引发一个 *note 审计事件: fa1. ‘sqlite3.connect’，附带参数
     ‘database’。

     3.4 版更變: 增加了 `uri' 参数。

     3.7 版更變: `database' 现在可以是一个 *note path-like object: 472.
     对象了，不仅仅是字符串。

 -- 函式: sqlite3.register_converter (typename, callable)

     注册一个回调对象 `callable', 用来转换数据库中的字节串为自定的
     Python 类型。所有类型为 `typename' 的数据库的值在转换时，都会调用这
     个回调对象。通过指定 *note connect(): 4e0. 函数的 `detect-types' 参
     数来设置类型检测的方式。注意，`typename' 与查询语句中的类型名进行匹
     配时不区分大小写。

 -- 函式: sqlite3.register_adapter (type, callable)

     注册一个回调对象 `callable'，用来转换自定义Python类型为一个 SQLite
     支持的类型。 这个回调对象 `callable' 仅接受一个 Python 值作为参数，
     而且必须返回以下某个类型的值：int，float，str 或 bytes。

 -- 函式: sqlite3.complete_statement (sql)

     如果字符串 `sql' 包含一个或多个完整的 SQL 语句（以分号结束）则返回
     *note True: 593.。它不会验证 SQL 语法是否正确，仅会验证字符串字面上
     是否完整，以及是否以分号结束。

     它可以用来构建一个 SQLite shell，下面是一个例子：

          # 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()

 -- 函式: sqlite3.enable_callback_tracebacks (flag)

     默认情况下，您不会获得任何用户定义函数中的回溯消息，比如聚合，转换
     器，授权器回调等。如果要调试它们，可以设置 `flag' 参数为 ‘True’ 并
     调用此函数。 之后，回调中的回溯信息将会输出到 ‘sys.stderr’。 再次使
     用 *note False: 48e. 来禁用该功能。

   ---------- Footnotes ----------

   (1) https://sqlite.org/compile.html#threadsafe


File: python.info,  Node: 连接对象（Connection）,  Next: Cursor 对象,  Prev: 模块函数和常量,  Up: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块

5.12.6.2 连接对象（Connection）
...............................

 -- 類別: sqlite3.Connection

     SQLite 数据库连接对象有如下的属性和方法：

      -- 屬性: isolation_level

          获取或设置当前默认的隔离级别。 表示自动提交模式的 *note None:
          203. 以及 "DEFERRED", "IMMEDIATE" 或 "EXCLUSIVE" 其中之一。 详
          细描述请参阅 *note 控制事务: 1e70.。

      -- 屬性: in_transaction

          如果是在活动事务中（还没有提交改变），返回 *note True: 593.，
          否则，返回 *note False: 48e.。它是一个只读属性。

          3.2 版新加入.

      -- 成員函式: cursor (factory=Cursor)

          这个方法接受一个可选参数 `factory'，如果要指定这个参数，它必须
          是一个可调用对象，而且必须返回 *note Cursor: 1e57. 类的一个实
          例或者子类。

      -- 成員函式: commit ()

          这个方法提交当前事务。如果没有调用这个方法，那么从上一次提交
          ‘commit()’ 以来所有的变化在其他数据库连接上都是不可见的。如果
          你往数据库里写了数据，但是又查询不到，请检查是否忘记了调用这个
          方法。

      -- 成員函式: rollback ()

          这个方法回滚从上一次调用 *note commit(): 1e73. 以来所有数据库
          的改变。

      -- 成員函式: close ()

          关闭数据库连接。注意，它不会自动调用 *note commit(): 1e73. 方
          法。如果在关闭数据库连接之前没有调用 *note commit(): 1e73.，那
          么你的修改将会丢失！

      -- 成員函式: execute (sql[, parameters])

          这是一个非标准的快捷方法，它会调用 *note cursor(): 1e72. 方法
          来创建一个游标对象，并使用给定的 `parameters' 参数来调用游标对
          象的 *note execute(): 1e58. 方法，最后返回这个游标对象。

      -- 成員函式: executemany (sql[, parameters])

          这是一个非标准的快捷方法，它会调用 *note cursor(): 1e72. 方法
          来创建一个游标对象，并使用给定的 `parameters' 参数来调用游标对
          象的 *note executemany(): 1e78. 方法，最后返回这个游标对象。

      -- 成員函式: executescript (sql_script)

          这是一个非标准的快捷方法，它会调用 *note cursor(): 1e72. 方法
          来创建一个游标对象，并使用给定的 `sql_script' 参数来调用游标对
          象的 *note executescript(): 1e7a. 方法，最后返回这个游标对象。

      -- 成員函式: create_function (name, num_params, func, *,
               deterministic=False)

          创建一个可以在 SQL 语句中使用的用户自定义函数，函数名为
          `name'。 `num_params' 为该函数所接受的形参个数（如果
          `num_params' 为 -1，则该函数可接受任意数量的参数）， `func' 是
          一个 Python 可调用对象，它将作为 SQL 函数被调用。 如果
          `deterministic' 为真值，则所创建的函数将被标记为
          deterministic(1)，这允许 SQLite 执行额外的优化。 此旗标在
          SQLite 3.8.3 或更高版本中受到支持，如果在旧版本中使用将引发
          *note NotSupportedError: 1e7b.。

          此函数可返回任何 SQLite 所支持的类型: bytes, str, int, float 和
          ‘None’。

          3.8 版更變: 增加了 `deterministic' 形参。

          示例:

               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()

      -- 成員函式: create_aggregate (name, num_params, aggregate_class)

          创建一个自定义的聚合函数。

          参数中 `aggregate_class' 类必须实现两个方法：‘step’ 和
          ‘finalize’。‘step’ 方法接受 `num_params' 个参数（如果
          `num_params' 为 -1，那么这个函数可以接受任意数量的参数）；
          ‘finalize’ 方法返回最终的聚合结果。

          ‘finalize’ 方法可以返回任何 SQLite 支持的类型：bytes，str，
          int，float 和 ‘None’。

          示例:

               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()

      -- 成員函式: create_collation (name, callable)

          使用 `name' 和 `callable' 创建排序规则。这个 `callable' 接受两
          个字符串对象，如果第一个小于第二个则返回 -1， 如果两个相等则返
          回 0，如果第一个大于第二个则返回 1。注意，这是用来控制排序的（
          SQL 中的 ORDER BY），所以它不会影响其它的 SQL 操作。

          注意，这个 `callable' 可调用对象会把它的参数作为 Python 字节串
          ，通常会以 UTF-8 编码格式对它进行编码。

          以下示例显示了使用“错误方式”进行排序的自定义排序规则：

               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()

          要移除一个排序规则，需要调用 ‘create_collation’ 并设置
          callable 参数为 ‘None’。

               con.create_collation("reverse", None)

      -- 成員函式: interrupt ()

          可以从不同的线程调用这个方法来终止所有查询操作，这些查询操作可
          能正在连接上执行。此方法调用之后， 查询将会终止，而且查询的调
          用者会获得一个异常。

      -- 成員函式: set_authorizer (authorizer_callback)

          此方法注册一个授权回调对象。每次在访问数据库中某个表的某一列的
          时候，这个回调对象将会被调用。如果要允许访问，则返回
          ‘SQLITE_OK’，如果要终止整个 SQL 语句，则返回 ‘SQLITE_DENY’，如
          果这一列需要当做 NULL 值处理，则返回 ‘SQLITE_IGNORE’。这些常量
          可以在 *note sqlite3: f2. 模块中找到。

          回调的第一个参数表示要授权的操作类型。 第二个和第三个参数将是
          参数或 *note None: 203.，具体取决于第一个参数的值。 第 4 个参
          数是数据库的名称（“main”，“temp”等），如果需要的话。 第 5 个参
          数是负责访问尝试的最内层触发器或视图的名称，或者如果此访问尝试
          直接来自输入 SQL 代码，则为 *note None: 203.。

          请参阅 SQLite 文档，了解第一个参数的可能值以及第二个和第三个参
          数的含义，具体取决于第一个参数。 所有必需的常量都可以在 *note
          sqlite3: f2. 模块中找到。

      -- 成員函式: set_progress_handler (handler, n)

          此例程注册回调。 对SQLite虚拟机的每个多指令调用回调。 如果要在
          长时间运行的操作期间从SQLite调用（例如更新用户界面），这非常有
          用。

          如果要清除以前安装的任何进度处理程序，调用该方法时请将
          `handler' 参数设置为 *note None: 203.。

          从处理函数返回非零值将终止当前正在执行的查询并导致它引发 *note
          OperationalError: 1e7e. 异常。

      -- 成員函式: set_trace_callback (trace_callback)

          为每个 SQLite 后端实际执行的 SQL 语句注册要调用的
          `trace_callback'。

          The only argument passed to the callback is the statement (as
          *note str: 205.) that is being executed.  The return value of
          the callback is ignored.  Note that the backend does not only
          run statements passed to the *note Cursor.execute(): 1e58.
          methods.  Other sources include the *note transaction
          management: 1e70. of the sqlite3 module and the execution of
          triggers defined in the current database.

          将传入的 `trace_callback' 设为 *note None: 203. 将禁用跟踪回调
          。

               備註: Exceptions raised in the trace callback are not
               propagated.  As a development and debugging aid, use
               *note enable_callback_tracebacks(): 1e6d. to enable
               printing tracebacks from exceptions raised in the trace
               callback.

          3.3 版新加入.

      -- 成員函式: enable_load_extension (enabled)

          此例程允许/禁止SQLite引擎从共享库加载SQLite扩展。 SQLite扩展可
          以定义新功能，聚合或全新的虚拟表实现。 一个众所周知的扩展是与
          SQLite一起分发的全文搜索扩展。

          默认情况下禁用可加载扩展。 见 (2).

          3.2 版新加入.

               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()

      -- 成員函式: load_extension (path)

          此例程从共享库加载SQLite扩展。 在使用此例程之前，必须使用
          *note enable_load_extension(): c6a. 启用扩展加载。

          默认情况下禁用可加载扩展。 见 (3).

          3.2 版新加入.

      -- 屬性: row_factory

          您可以将此属性更改为可接受游标和原始行作为元组的可调用对象，并
          将返回实际结果行。 这样，您可以实现更高级的返回结果的方法，例
          如返回一个可以按名称访问列的对象。

          示例:

               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()

          如果返回一个元组是不够的，并且你想要对列进行基于名称的访问，你
          应该考虑将 *note row_factory: 1e7f. 设置为高度优化的 *note
          sqlite3.Row: 84d. 类型。 *note Row: 84d. 提供基于索引和不区分
          大小写的基于名称的访问，几乎没有内存开销。 它可能比您自己的基
          于字典的自定义方法甚至基于 db_row 的解决方案更好。

      -- 屬性: text_factory

          Using this attribute you can control what objects are returned
          for the ‘TEXT’ data type.  By default, this attribute is set
          to *note str: 205. and the *note sqlite3: f2. module will
          return *note str: 205. objects for ‘TEXT’.  If you want to
          return *note bytes: 172. instead, you can set it to *note
          bytes: 172.

          您还可以将其设置为接受单个 bytestring 参数的任何其他可调用对象
          ，并返回结果对象。

          请参阅以下示例代码以进行说明：

               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()

      -- 屬性: total_changes

          返回自打开数据库连接以来已修改，插入或删除的数据库行的总数。

      -- 成員函式: iterdump ()

          返回以SQL文本格式转储数据库的迭代器。 保存内存数据库以便以后恢
          复时很有用。 此函数提供与 ‘sqlite3’ shell 中的 ‘.dump’ 命令相
          同的功能。

          示例:

               # 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()

      -- 成員函式: backup (target, *, pages=-1, progress=None,
               name="main", sleep=0.250)

          即使在 SQLite 数据库被其他客户端访问时，或者同时由同一连接访问
          ，该方法也会对其进行备份。 该副本将写入强制参数 `target'，该参
          数必须是另一个 *note Connection: 4de. 实例。

          默认情况下，或者当 `pages' 为 ‘0’ 或负整数时，整个数据库将在一
          个步骤中复制；否则该方法一次循环复制 `pages' 规定数量的页面。

          如果指定了 `progress'，则它必须为 ‘None’ 或一个将在每次迭代时
          附带三个整数参数执行的可调用对象，这三个参数分别是前一次迭代的
          状态 `status'，将要拷贝的剩余页数 `remaining' 以及总页数
          `total'。

          `name' 参数指定将被拷贝的数据库名称：它必须是一个字符串，其内
          容为表示主数据库的默认值 ‘"main"’，表示临时数据库的 ‘"temp"’ 或
          是在 ‘ATTACH DATABASE’ 语句的 ‘AS’ 关键字之后指定表示附加数据
          库的名称。

          `sleep' 参数指定在备份剩余页的连续尝试之间要休眠的秒数，可以指
          定为一个整数或一个浮点数值。

          示例一，将现有数据库复制到另一个数据库中：

               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()

          示例二，将现有数据库复制到临时副本中：

               import sqlite3

               source = sqlite3.connect('existing_db.db')
               dest = sqlite3.connect(':memory:')
               source.backup(dest)

          可用性：SQLite 3.6.11 或以上版本

          3.7 版新加入.

   ---------- Footnotes ----------

   (1) https://sqlite.org/deterministic.html

   (2) (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 ‘--enable-loadable-sqlite-extensions’
to configure.

   (3) (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 ‘--enable-loadable-sqlite-extensions’
to configure.


File: python.info,  Node: Cursor 对象,  Next: 行对象,  Prev: 连接对象（Connection）,  Up: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块

5.12.6.3 Cursor 对象
....................

 -- 類別: sqlite3.Cursor

     *note Cursor: 1e57. 游标实例具有以下属性和方法。

      -- 成員函式: execute (sql[, parameters])

          执行一条 SQL 语句。 可以使用 *note 占位符: 1e5b. 将值绑定到语
          句中。

          *note execute(): 1e58. 将只执行一条单独的 SQL 语句。 如果你尝
          试用它执行超过一条语句，将会引发 *note Warning: 1e85.。 如果你
          想要用一次调用执行多条 SQL 语句请使用 *note executescript():
          1e7a.。

      -- 成員函式: executemany (sql, seq_of_parameters)

          执行一条 *note 带形参的: 1e5b. SQL 命令，使用所有形参序列或在
          序列 `seq_of_parameters' 中找到的映射。 *note sqlite3: f2. 模
          块还允许使用 *note iterator: 1171. 代替序列来产生形参。

               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()

          这是一个使用生成器 *note generator: a83. 的简短示例：

               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()

      -- 成員函式: executescript (sql_script)

          这是用于一次性执行多条 SQL 语句的非标准便捷方法。 它会首先发出
          一条 ‘COMMIT’ 语句，然后执行通过参数获得的 SQL 脚本。 此方法会
          忽略 ‘isolation_level’；任何事件控制都必须被添加到
          `sql_script'。

          `sql_script' 可以是一个 *note str: 205. 类的实例。

          示例:

               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''s Holistic Detective Agency',
                       'Douglas Adams',
                       1987
                   );
                   """)
               con.close()

      -- 成員函式: fetchone ()

          获取一个查询结果集的下一行，返回一个单独序列，或是在没有更多可
          用数据时返回 *note None: 203.。

      -- 成員函式: fetchmany (size=cursor.arraysize)

          获取下一个多行查询结果集，返回一个列表。 当没有更多可用行时将
          返回一个空列表。

          每次调用获取的行数由 `size' 形参指定。 如果没有给出该形参，则
          由 cursor 的 arraysize 决定要获取的行数。 此方法将基于 size 形
          参值尝试获取指定数量的行。 如果获取不到指定的行数，则可能返回
          较少的行。

          请注意 `size' 形参会涉及到性能方面的考虑。为了获得优化的性能，
          通常最好是使用 arraysize 属性。 如果使用 `size' 形参，则最好在
          从一个 *note fetchmany(): 1e86. 调用到下一个调用之间保持相同的
          值。

      -- 成員函式: fetchall ()

          获取一个查询结果的所有（剩余）行，返回一个列表。 请注意 cursor
          的 arraysize 属性会影响此操作的执行效率。 当没有可用行时将返回
          一个空列表。

      -- 成員函式: close ()

          立即关闭 cursor（而不是在当 ‘__del__’ 被调用的时候）。

          从这一时刻起该 cursor 将不再可用，如果再尝试用该 cursor 执行任
          何操作将引发 *note ProgrammingError: ff3. 异常。

      -- 成員函式: setinputsizes (sizes)

          Required by the DB-API. Is a no-op in *note sqlite3: f2.

      -- 成員函式: setoutputsize (size[, column])

          Required by the DB-API. Is a no-op in *note sqlite3: f2.

      -- 屬性: rowcount

          虽然 *note sqlite3: f2. 模块的 *note Cursor: 1e57. 类实现了此
          属性，但数据库引擎本身对于确定 "受影响行"/"已选择行" 的支持并
          不完善。

          对于 *note executemany(): 1e78. 语句，修改行数会被汇总至 *note
          rowcount: 1e8a.。

          根据 Python DB API 规格描述的要求，*note rowcount: 1e8a. 属性
          "当未在 cursor 上执行 ‘executeXX()’ 或者上一次操作的 rowcount
          不是由接口确定时为 -1"。 这包括 ‘SELECT’ 语句，因为我们无法确
          定一次查询将产生的行计数，而要等获取了所有行时才会知道。

          在 SQLite 的 3.6.5 版之前，如果你执行 ‘DELETE FROM table’ 时不
          附带任何条件，则 *note rowcount: 1e8a. 将被设为 0。

      -- 屬性: lastrowid

          This read-only attribute provides the row id of the last
          inserted row.  It is only updated after successful ‘INSERT’ or
          ‘REPLACE’ statements using the *note execute(): 1e58. method.
          For other statements, after *note executemany(): 1e78. or
          *note executescript(): 1e7a, or if the insertion failed, the
          value of ‘lastrowid’ is left unchanged.  The initial value of
          ‘lastrowid’ is *note None: 203.

               備註: Inserts into ‘WITHOUT ROWID’ tables are not
               recorded.

          3.6 版更變: 增加了 ‘REPLACE’ 语句的支持。

      -- 屬性: arraysize

          用于控制 *note fetchmany(): 1e86. 返回行数的可读取/写入属性。
          该属性的默认值为 1，表示每次调用将获取单独一行。

      -- 屬性: description

          这个只读属性将提供上一次查询的列名称。 为了与 Python DB API 保
          持兼容，它会为每个列返回一个 7 元组，每个元组的最后六个条目均
          为 *note None: 203.。

          对于没有任何匹配行的 ‘SELECT’ 语句同样会设置该属性。

      -- 屬性: connection

          这个只读属性将提供 *note Cursor: 1e57. 对象所使用的 SQLite 数
          据库 *note Connection: 4de.。 通过调用 *note con.cursor():
          1e72. 创建的 *note Cursor: 1e57. 对象所包含的 *note
          connection: 1e8c. 属性将指向 `con':

               >>> con = sqlite3.connect(":memory:")
               >>> cur = con.cursor()
               >>> cur.connection == con
               True


File: python.info,  Node: 行对象,  Next: 异常<4>,  Prev: Cursor 对象,  Up: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块

5.12.6.4 行对象
...............

 -- 類別: sqlite3.Row

     一个 *note Row: 84d. 实例，该实例将作为用于 *note Connection: 4de.
     对象的高度优化的 *note row_factory: 1e7f.。 它的大部分行为都会模仿
     元组的特性。

     它支持使用列名称的映射访问以及索引、迭代、文本表示、相等检测和
     *note len(): 28b. 等操作。

     如果两个 *note Row: 84d. 对象具有完全相同的列并且其成员均相等，则它
     们的比较结果为相等。

      -- 成員函式: keys ()

          此方法会在一次查询之后立即返回一个列名称的列表，它是 *note
          Cursor.description: 1e67. 中每个元组的第一个成员。

     3.5 版更變: 添加了对切片操作的支持。

让我们假设我们如上面的例子所示初始化一个表:

     con = sqlite3.connect(":memory:")
     cur = con.cursor()
     cur.execute('''create table stocks
     (date text, trans text, symbol text,
      qty real, price real)''')
     cur.execute("""insert into stocks
                 values ('2006-01-05','BUY','RHAT',100,35.14)""")
     con.commit()
     cur.close()

现在我们将 *note Row: 84d. 插入:

     >>> 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


File: python.info,  Node: 异常<4>,  Next: SQLite 与 Python 类型,  Prev: 行对象,  Up: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块

5.12.6.5 异常
.............

 -- 例外: sqlite3.Warning

     *note Exception: 2dc. 的一个子类。

 -- 例外: sqlite3.Error

     此模块中其他异常的基类。 它是 *note Exception: 2dc. 的一个子类。

 -- 例外: sqlite3.DatabaseError

     针对数据库相关错误引发的异常。

 -- 例外: sqlite3.IntegrityError

     当数据库的关系一致性受到影响时引发的异常。 例如外键检查失败等。 它
     是 *note DatabaseError: 1e93. 的子类。

 -- 例外: sqlite3.ProgrammingError

     编程错误引发的异常，例如表未找到或已存在，SQL 语句存在语法错误，指
     定的形参数量错误等。 它是 *note DatabaseError: 1e93. 的子类。

 -- 例外: sqlite3.OperationalError

     与数据库操作相关而不一定能受程序员掌控的错误引发的异常，例如发生非
     预期的连接中断，数据源名称未找到，事务无法被执行等。 它是 *note
     DatabaseError: 1e93. 的子类。

 -- 例外: sqlite3.NotSupportedError

     在使用了某个数据库不支持的方法或数据库 API 时引发的异常，例如在一个
     不支持事务或禁用了事务的连接上调用 *note rollback(): 1e74. 方法等。
     它是 *note DatabaseError: 1e93. 的子类。


File: python.info,  Node: SQLite 与 Python 类型,  Next: 控制事务,  Prev: 异常<4>,  Up: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块

5.12.6.6 SQLite 与 Python 类型
..............................

* Menu:

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


File: python.info,  Node: 簡介<7>,  Next: 使用适配器将额外的 Python 类型保存在 SQLite 数据库中。,  Up: SQLite 与 Python 类型

5.12.6.7 簡介
.............

SQLite 原生支持如下的类型： ‘NULL’，‘INTEGER’，‘REAL’，‘TEXT’，‘BLOB’。

因此可以将以下Python类型发送到SQLite而不会出现任何问题：

Python 类型                         SQLite 类型
                                    
------------------------------------------------------
                                    
*note None: 203.                    ‘NULL’
                                    
                                    
*note int: 204.                     ‘INTEGER’
                                    
                                    
*note float: 1fd.                   ‘REAL’
                                    
                                    
*note str: 205.                     ‘TEXT’
                                    
                                    
*note bytes: 172.                   ‘BLOB’
                                    

这是SQLite类型默认转换为Python类型的方式：

SQLite 类型       Python 类型
                  
---------------------------------------------------------------------
                  
‘NULL’            *note None: 203.
                  
                  
‘INTEGER’         *note int: 204.
                  
                  
‘REAL’            *note float: 1fd.
                  
                  
‘TEXT’            取决于 *note text_factory: 1e80. , 默认为
                  *note str: 205.
                  
                  
‘BLOB’            *note bytes: 172.
                  

*note sqlite3: f2. 模块的类型系统可通过两种方式来扩展：你可以通过对象适
配将额外的 Python 类型保存在 SQLite 数据库中，你也可以让 *note sqlite3:
f2. 模块通过转换器将 SQLite 类型转换为不同的 Python 类型。


File: python.info,  Node: 使用适配器将额外的 Python 类型保存在 SQLite 数据库中。,  Next: 将SQLite 值转换为自定义Python 类型,  Prev: 簡介<7>,  Up: SQLite 与 Python 类型

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

如上文所述，SQLite 只包含对有限类型集的原生支持。 要让 SQLite 能使用其他
Python 类型，你必须将它们 `适配' 至 sqlite3 模块所支持的 SQLite 类型中的
一种：NoneType, int, float, str, bytes。

有两种方式能让 *note sqlite3: f2. 模块将某个定制的 Python 类型适配为受支
持的类型。

* Menu:

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


File: python.info,  Node: 让对象自行适配,  Next: 注册可调用的适配器,  Up: 使用适配器将额外的 Python 类型保存在 SQLite 数据库中。

5.12.6.9 让对象自行适配
.......................

如果类是你自己编写的，这将是一个很好的方式。 假设你有这样一个类:

     class Point:
         def __init__(self, x, y):
             self.x, self.y = x, y

现在你可将这种点对象保存在一个 SQLite 列中。 首先你必须选择一种受支持的
类型用来表示点对象。 让我们就用 str 并使用一个分号来分隔坐标值。 然后你
需要给你的类加一个方法 ‘__conform__(self, protocol)’，它必须返回转换后的
值。 形参 `protocol' 将为 ‘PrepareProtocol’。

     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()


File: python.info,  Node: 注册可调用的适配器,  Prev: 让对象自行适配,  Up: 使用适配器将额外的 Python 类型保存在 SQLite 数据库中。

5.12.6.10 注册可调用的适配器
............................

另一种可能的做法是创建一个将该类型转换为字符串表示的函数并使用 *note
register_adapter(): 1e6b. 注册该函数。

     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()

*note sqlite3: f2. 模块有两个适配器可用于 Python 的内置 *note
datetime.date: 19d. 和 *note datetime.datetime: 19f. 类型。 现在假设我们
想要存储 *note datetime.datetime: 19f. 对象，但不是表示为 ISO 格式，而是
表示为 Unix 时间戳。

     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()


File: python.info,  Node: 将SQLite 值转换为自定义Python 类型,  Next: 默认适配器和转换器,  Prev: 使用适配器将额外的 Python 类型保存在 SQLite 数据库中。,  Up: SQLite 与 Python 类型

5.12.6.11 将SQLite 值转换为自定义Python 类型
............................................

编写适配器让你可以将定制的 Python 类型发送给 SQLite。 但要令它真正有用，
我们需要实现从 Python 到 SQLite 再回到 Python 的双向转换。

输入转换器。

让我们回到 ‘Point’ 类。 我们以字符串形式在 SQLite 中存储了 x 和 y 坐标值
。

首先，我们将定义一个转换器函数，它接受这样的字符串作为形参并根据该参数构
造一个 ‘Point’ 对象。

     備註: 转换器函数在调用时 `总是' 会附带一个 *note bytes: 172. 对象，
     无论你将何种数据类型的值发给 SQLite。

     def convert_point(s):
         x, y = map(float, s.split(b";"))
         return Point(x, y)

现在你需要让 *note sqlite3: f2. 模块知道你从数据库中选取的其实是一个点对
象。 有两种方式都可以做到这件事：

   * 隐式的声明类型

   * 显式的通过列名

这两种方式会在 *note 模块函数和常量: 1e5d. 一节中描述，相应条目为 *note
PARSE_DECLTYPES: 1e65. 和 *note PARSE_COLNAMES: 1e66. 常量。

下面的示例说明了这两种方法。

     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()


File: python.info,  Node: 默认适配器和转换器,  Prev: 将SQLite 值转换为自定义Python 类型,  Up: SQLite 与 Python 类型

5.12.6.12 默认适配器和转换器
............................

对于 datetime 模块中的 date 和 datetime 类型已提供了默认的适配器。 它们
将会以 ISO 日期/ISO 时间戳的形式发给 SQLite。

默认转换器使用的注册名称是针对 *note datetime.date: 19d. 的 "date" 和针
对 *note datetime.datetime: 19f. 的 "timestamp"。

通过这种方式，你可以在大多数情况下使用 Python 的 date/timestamp 对象而无
须任何额外处理。 适配器的格式还与实验性的 SQLite date/time 函数兼容。

下面的示例演示了这一点。

     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()

如果存储在 SQLite 中的时间戳的小数位多于 6 个数字，则时间戳转换器会将该
值截断至微秒精度。

     備註: The default "timestamp" converter ignores UTC offsets in the
     database and always returns a naive *note datetime.datetime: 19f.
     object.  To preserve UTC offsets in timestamps, either leave
     converters disabled, or register an offset-aware converter with
     *note register_converter(): 1e69.


File: python.info,  Node: 控制事务,  Next: 有效使用 sqlite3,  Prev: SQLite 与 Python 类型,  Up: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块

5.12.6.13 控制事务
..................

底层的 ‘sqlite3’ 库默认会以 ‘autocommit’ 模式运行，但 Python 的 *note
sqlite3: f2. 模块默认则不使用此模式。

‘autocommit’ 模式意味着修改数据库的操作会立即生效。 ‘BEGIN’ 或
‘SAVEPOINT’ 语句会禁用 ‘autocommit’ 模式，而用于结束外层事务的 ‘COMMIT’,
‘ROLLBACK’ 或 ‘RELEASE’ 则会恢复 ‘autocommit’ 模式。

Python 的 *note sqlite3: f2. 模块默认会在数据修改语言 (DML) 类语句 (即
‘INSERT’/‘UPDATE’/‘DELETE’/‘REPLACE’) 之前隐式地执行一条 ‘BEGIN’ 语句。

你可以控制 *note sqlite3: f2. 隐式执行的 ‘BEGIN’ 语句的种类，具体做法是
通过将 `isolation_level' 形参传给 *note connect(): 4e0. 调用，或者通过指
定连接的 ‘isolation_level’ 属性。 如果你没有指定 `isolation_level'，将使
用基本的 ‘BEGIN’，它等价于指定 ‘DEFERRED’。 其他可能的值为 ‘IMMEDIATE’ 和
‘EXCLUSIVE’。

你可以禁用 *note sqlite3: f2. 模块的隐式事务管理，具体做法是将
‘isolation_level’ 设为 ‘None’。 这将使得下层的 ‘sqlite3’ 库采用
‘autocommit’ 模式。 随后你可以通过在代码中显式地使用 ‘BEGIN’,
‘ROLLBACK’, ‘SAVEPOINT’ 和 ‘RELEASE’ 语句来完全控制事务状态。

请注意 *note executescript(): 1e7a. 会忽略 ‘isolation_level’；任何事务控
制必要要显式地添加。

3.6 版更變: 以前 *note sqlite3: f2. 会在 DDL 语句之前隐式地提交未完成事
务。 现在则不会再这样做。


File: python.info,  Node: 有效使用 sqlite3,  Prev: 控制事务,  Up: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块

5.12.6.14 有效使用 ‘sqlite3’
............................

* Menu:

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


File: python.info,  Node: 使用快捷方式,  Next: 通过名称而不是索引访问索引,  Up: 有效使用 sqlite3

5.12.6.15 使用快捷方式
......................

使用 *note Connection: 4de. 对象的非标准 ‘execute()’, ‘executemany()’ 和
‘executescript()’ 方法，可以更简洁地编写代码，因为不必显式创建（通常是多
余的） *note Cursor: 1e57. 对象。相反， *note Cursor: 1e57. 对象是隐式创
建的，这些快捷方法返回游标对象。这样，只需对 *note Connection: 4de. 对象
调用一次，就能直接执行 ‘SELECT’ 语句并遍历对象。

     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()


File: python.info,  Node: 通过名称而不是索引访问索引,  Next: 使用连接作为上下文管理器,  Prev: 使用快捷方式,  Up: 有效使用 sqlite3

5.12.6.16 通过名称而不是索引访问索引
....................................

*note sqlite3: f2. 模块的一个有用功能是内置的 *note sqlite3.Row: 84d. 类
，该类旨在用作行工厂。

该类的行装饰器可以用索引（如元组）和不区分大小写的名称访问：

     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()


File: python.info,  Node: 使用连接作为上下文管理器,  Prev: 通过名称而不是索引访问索引,  Up: 有效使用 sqlite3

5.12.6.17 使用连接作为上下文管理器
..................................

连接对象可以用来作为上下文管理器，它可以自动提交或者回滚事务。如果出现异
常，事务会被回滚；否则，事务会被提交。

     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()

註解
....


File: python.info,  Node: 資料壓縮與保存,  Next: 檔案格式,  Prev: 数据持久化,  Up: Python 標準函式庫 Standard Library

5.13 資料壓縮與保存
===================

本章中描述的模块支持 zlib、gzip、bzip2 和 lzma 数据压缩算法，以及创建
ZIP 和 tar 格式的归档文件。参见由 *note shutil: e9. 模块提供的 *note
归档操作: c67. 。

* 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归档文件


File: python.info,  Node: zlib --- 与 gzip 兼容的压缩,  Next: gzip --- 对 gzip 格式的支持,  Up: 資料壓縮與保存

5.13.1 ‘zlib’ — 与 ‘gzip’ 兼容的压缩
------------------------------------

__________________________________________________________________

对于需要数据压缩的应用，此模块中的函数允许使用 zlib 库进行压缩和解压缩。
zlib 库的项目主页是 ‘https://www.zlib.net’。 已知此 Python 模块与 1.1.3
之前版本的 zlib 库存在不兼容；1.1.3 版则存在一个 安全缺陷(1)，因此我们推
荐使用 1.1.4 或更新的版本。

zlib 的函数有很多选项，一般需要按特定顺序使用。本文档没有覆盖全部的用法
。更多详细信息请于 ‘http://www.zlib.net/manual.html’ 参阅官方手册。

要读写 ‘.gz’ 格式的文件，请参考 *note gzip: 8b. 模块。

此模块中可用的异常和函数如下：

 -- 例外: zlib.error

     在压缩或解压缩过程中发生错误时的异常。

 -- 函式: zlib.adler32 (data[, value])

     计算 `data' 的 Adler-32 校验值。(Adler-32 校验的可靠性与 CRC32 基本
     相当，但比计算 CRC32 更高效。) 计算的结果是一个 32 位的整数。参数
     `value' 是校验时的起始值，其默认值为 1。借助参数 `value' 可为分段的
     输入计算校验值。此算法没有加密强度，不应用于身份验证和数字签名。此
     算法的目的仅为验证数据的正确性，不适合作为通用散列算法。

     3.0 版更變: 返回值永远是无符号数。要在所有的 Python 版本和平台上获
     得相同的值，请使用 ‘adler32(data) & 0xffffffff’。

 -- 函式: zlib.compress (data, /, level=-1)

     压缩 `data' 中的字节，返回含有已压缩内容的 bytes 对象。参数 `level'
     为整数，可取值为 ‘0’ 到 ‘9’ 或 ‘-1’，用于指定压缩等级。‘1’
     (Z_BEST_SPEED) 表示最快速度和最低压缩率，‘9’ (Z_BEST_COMPRESSION) 表
     示最慢速度和最高压缩率。‘0’ (Z_NO_COMPRESSION) 表示不压缩。参数默认
     值为 ‘-1’ (Z_DEFAULT_COMPRESSION)。Z_DEFAULT_COMPRESSION 是速度和压
     缩率之间的平衡 (一般相当于设压缩等级为 6)。函数发生错误时抛出 *note
     error: 1ea5. 异常。

     3.6 版更變: 现在，`level' 可作为关键字参数。

 -- 函式: zlib.compressobj (level=-1, method=DEFLATED, wbits=MAX_WBITS,
          memLevel=DEF_MEM_LEVEL, strategy=Z_DEFAULT_STRATEGY[, zdict])

     返回一个 压缩对象，用来压缩内存中难以容下的数据流。

     参数 `level' 为压缩等级，是整数，可取值为 ‘0’ 到 ‘9’ 或 ‘-1’。‘1’
     (Z_BEST_SPEED) 表示最快速度和最低压缩率，‘9’ (Z_BEST_COMPRESSION) 表
     示最慢速度和最高压缩率。‘0’ (Z_NO_COMPRESSION) 表示不压缩。参数默认
     值为 ‘-1’ (Z_DEFAULT_COMPRESSION)。Z_DEFAULT_COMPRESSION 是速度和压
     缩率之间的平衡 (一般相当于设压缩等级为 6)。

     `method' 表示压缩算法。现在只支持 ‘DEFLATED’ 这个算法。

     参数 `wbits' 指定压缩数据时所使用的历史缓冲区的大小 (窗口大小)，并
     指定压缩输出是否包含头部或尾部。参数的默认值是 ‘15’ (MAX_WBITS)。参
     数的值分为几个范围：

        * +9 至 +15：窗口大小以二为底的对数。 即这些值对应着 512 至
          32768 的窗口大小。 更大的值会提供更好的压缩，同时内存开销也会
          更大。 压缩输出会包含 zlib 特定格式的头部和尾部。

        * −9 至 −15：绝对值为窗口大小以二为底的对数。 压缩输出仅包含压缩
          数据，没有头部和尾部。

        * +25 至 +31 = 16 + (9 至 15)：后 4 个比特位为窗口大小以二为底的
          对数。 压缩输出包含一个基本的 ‘gzip’ 头部，并以校验和为尾部。

     参数 `memLevel' 指定内部压缩操作时所占用内存大小。参数取 ‘1’ 到
     ‘9’。更大的值占用更多的内存，同时速度也更快输出也更小。

     参数 `strategy' 用于调节压缩算法。可取值为 ‘Z_DEFAULT_STRATEGY’、
     ‘Z_FILTERED’、‘Z_HUFFMAN_ONLY’、‘Z_RLE’ (zlib 1.2.0.1) 或 ‘Z_FIXED’
     (zlib 1.2.2.2)。

     参数 `zdict' 指定预定义的压缩字典。它是一个字节序列 (如 *note
     bytes: 172. 对象)，其中包含用户认为要压缩的数据中可能频繁出现的子序
     列。频率高的子序列应当放在字典的尾部。

     3.3 版更變: 添加关键字参数 `zdict'。

 -- 函式: zlib.crc32 (data[, value])

     计算 `data' 的 CRC (循环冗余校验) 值。计算的结果是一个 32 位的整数
     。参数 `value' 是校验时的起始值，其默认值为 0。借助参数 `value' 可
     为分段的输入计算校验值。此算法没有加密强度，不应用于身份验证和数字
     签名。此算法的目的仅为验证数据的正确性，不适合作为通用散列算法。

     3.0 版更變: 返回值永远是无符号数。要在所有的 Python 版本和平台上获
     得相同的值，请使用 ‘crc32(data) & 0xffffffff’。

 -- 函式: zlib.decompress (data, /, wbits=MAX_WBITS,
          bufsize=DEF_BUF_SIZE)

     解压 `data' 中的字节，返回含有已解压内容的 bytes 对象。参数 `wbits'
     取决于 `data' 的格式，具体参见下边的说明。`bufsize' 为输出缓冲区的
     起始大小。函数发生错误时抛出 *note error: 1ea5. 异常。 `wbits' 形参
     控制历史缓冲区的大小（或称“窗口大小”）以及所期望的头部和尾部格式。
     它类似于 *note compressobj(): 1ea7. 的形参，但可接受更大范围的值：

        * +8 至 +15：窗口尺寸以二为底的对数。 输入必须包含 zlib 头部和尾
          部。

        * 0：根据 zlib 头部自动确定窗口大小。 只从 zlib 1.2.3.5 版起受支
          持。

        * −8 至 −15：使用 `wbits' 的绝对值作为窗口大小以二为底的对数。 输
          入必须为原始数据流，没有头部和尾部。

        * +24 至 +31 = 16 + (8 至 15)：使用后 4 个比特位作为窗口大小以二
          为底的对数。 输入必须包括 gzip 头部和尾部。

        * +40 至 +47 = 32 + (8 至 15)：使用后 4 个比特位作为窗口大小以二
          为底的对数，并且自动接受 zlib 或 gzip 格式。

     当解压缩一个数据流时，窗口大小必须不小于用于压缩数据流的原始窗口大
     小；使用太小的值可能导致 *note error: 1ea5. 异常。 默认 `wbits' 值
     对应于最大的窗口大小并且要求包括 zlib 头部和尾部。

     `bufsize' 是用于存放解压数据的缓冲区初始大小。 如果需要更大空间，缓
     冲区大小将按需增加，因此你不需要让这个值完全精确；对其进行调整仅会
     节省一点对 ‘malloc()’ 的调用次数。

     3.6 版更變: `wbits' 和 `bufsize' 可用作关键字参数。

 -- 函式: zlib.decompressobj (wbits=MAX_WBITS[, zdict])

     返回一个解压对象，用来解压无法被一次性放入内存的数据流。

     `wbits' 形参控制历史缓冲区的大小（或称“窗口大小”）以及所期望的头部
     和尾部格式。 它的含义与 *note 对 decompress() 的描述: 1ea9. 相同。

     `zdict' 形参指定指定一个预定义的压缩字典。 如果提供了此形参，它必须
     与产生将解压数据的压缩器所使用的字典相同。

          備註: 如果 `zdict' 是一个可变对象 (例如 *note bytearray:
          173.)，则你不可在对 *note decompressobj(): 1eaa. 的调用和对解
          压器的 ‘decompress()’ 方法的调用之间修改其内容。

     3.3 版更變: 增加了 `zdict' 形参。

压缩对象支持以下方法：

 -- 成員函式: Compress.compress (data)

     压缩 `data' 并返回 bytes 对象，这个对象含有 `data' 的部分或全部内容
     的已压缩数据。所得的对象必须拼接在上一次调用 *note compress(): 6b5.
     方法所得数据的后面。缓冲区中可能留存部分输入以供下一次调用。

 -- 成員函式: Compress.flush ([mode])

     压缩所有缓冲区的数据并返回已压缩的数据。参数 `mode' 可以传入的常量
     为：‘Z_NO_FLUSH’、‘Z_PARTIAL_FLUSH’、‘Z_SYNC_FLUSH’、
     ‘Z_FULL_FLUSH’、‘Z_BLOCK’ (zlib 1.2.3.4) 或 ‘Z_FINISH’。默认值为
     ‘Z_FINISH’。‘Z_FINISH’ 关闭已压缩数据流并不允许再压缩其他数据，
     ‘Z_FINISH’ 以外的值皆允许这个对象继续压缩数据。调用 *note flush():
     1eac. 方法并将 `mode' 设为 ‘Z_FINISH’ 后会无法再次调用 *note
     compress(): 6b5.，此时只能删除这个对象。

 -- 成員函式: Compress.copy ()

     返回此压缩对象的一个拷贝。它可以用来高效压缩一系列拥有相同前缀的数
     据。

3.8 版更變: 添加了对压缩对象执行 *note copy.copy(): 4d1. 和 *note
copy.deepcopy(): 4d2. 的支持。

解压缩对象支持以下方法：

 -- 屬性: Decompress.unused_data

     一个 bytes 对象，其中包含压缩数据结束之后的任何字节数据。 也就是说
     ，它将为 ‘b""’ 直到包含压缩数据的末尾字节可用。 如果整个结果字节串
     都包含压缩数据，它将为一个空的 bytes 对象 ‘b""’。

 -- 屬性: Decompress.unconsumed_tail

     一个 bytes 对象，其中包含未被上一次 *note decompress(): 6b6. 调用所
     消耗的任何数据。 此数据不能被 zlib 机制看到，因此你必须将其送回（可
     能要附带额外的数据拼接）到后续的 *note decompress(): 6b6. 方法调用
     以获得正确的输出。

 -- 屬性: Decompress.eof

     一个布尔值，指明是否已到达压缩数据流的末尾。

     这使得区分正确构造的压缩数据流和不完整或被截断的压缩数据流成为可能
     。

     3.3 版新加入.

 -- 成員函式: Decompress.decompress (data, max_length=0)

     解压缩 `data' 并返回 bytes 对象，其中包含对应于 `string' 中至少一部
     分数据的解压缩数据。 此数据应当被拼接到之前任何对 *note
     decompress(): 6b6. 方法的调用所产生的输出。 部分输入数据可能会被保
     留在内部缓冲区以供后续处理。

     如果可选的形参 `max_length' 非零则返回值将不会长于 `max_length'。 这
     可能意味着不是所有已压缩输入都能被处理；并且未被消耗的数据将被保存
     在 *note unconsumed_tail: 1eaf. 属性中。 如果要继续解压缩则这个字节
     串必须被传给对 *note decompress(): 6b6. 的后续调用。 如果
     `max_length' 为零则整个输入都会被解压缩，并且 *note
     unconsumed_tail: 1eaf. 将为空。

     3.6 版更變: `max_length' 可用作关键字参数。

 -- 成員函式: Decompress.flush ([length])

     所有挂起的输入会被处理，并且返回包含剩余未压缩输出的 bytes 对象。 在
     调用 *note flush(): 1eb1. 之后，*note decompress(): 6b6. 方法将无法
     被再次调用；唯一可行的操作是删除该对象。

     可选的形参 `length' 设置输出缓冲区的初始大小。

 -- 成員函式: Decompress.copy ()

     返回解压缩对象的一个拷贝。 它可以用来在数据流的中途保存解压缩器的状
     态以便加快随机查找数据流后续位置的速度。

3.8 版更變: 添加了对解压缩对象执行 *note copy.copy(): 4d1. 和 *note
copy.deepcopy(): 4d2. 的支持。

通过下列常量可获取模块所使用的 zlib 库的版本信息：

 -- Data: zlib.ZLIB_VERSION

     构建此模块时所用的 zlib 库的版本字符串。它的值可能与运行时所加载的
     zlib 不同。运行时加载的 zlib 库的版本字符串为 *note
     ZLIB_RUNTIME_VERSION: b9e.。

 -- Data: zlib.ZLIB_RUNTIME_VERSION

     解释器所加载的 zlib 库的版本字符串。

     3.3 版新加入.

也參考
......

模块 *note gzip: 8b.

     读写 ‘gzip’ 格式的文件。

‘http://www.zlib.net’

     zlib 库项目主页。

‘http://www.zlib.net/manual.html’

     zlib 库用户手册。提供了库的许多功能的解释和用法。

   ---------- Footnotes ----------

   (1) https://zlib.net/zlib_faq.html#faq33


File: python.info,  Node: gzip --- 对 gzip 格式的支持,  Next: bz2 --- 对 bzip2 压缩算法的支持,  Prev: zlib --- 与 gzip 兼容的压缩,  Up: 資料壓縮與保存

5.13.2 ‘gzip’ — 对 ‘gzip’ 格式的支持
------------------------------------

`源代码：' Lib/gzip.py(1)

__________________________________________________________________

此模块提供的简单接口帮助用户压缩和解压缩文件，功能类似于 GNU 应用程序
‘gzip’ 和 ‘gunzip’。

数据压缩由 *note zlib: 14d. 模块提供。

*note gzip: 8b. 模块提供 *note GzipFile: 206. 类和 *note open(): 1eb6.、
*note compress(): 302.、*note decompress(): c5a. 几个便利的函数。*note
GzipFile: 206. 类可以读写 ‘gzip’ 格式的文件，还能自动压缩和解压缩数据，
这让操作压缩文件如同操作普通的 *note file object: c14. 一样方便。

注意，此模块不支持部分可以被 ‘gzip’ 和 ‘gunzip’ 解压的格式，如利用
‘compress’ 或 ‘pack’ 压缩所得的文件。

这个模块定义了以下内容：

 -- 函式: gzip.open (filename, mode='rb', compresslevel=9,
          encoding=None, errors=None, newline=None)

     以二进制方式或者文本方式打开一个 gzip 格式的压缩文件，返回一个
     *note file object: c14.。

     `filename' 参数可以是一个实际的文件名(一个a *note str: 205. 对象或
     者 *note bytes: 172. 对象), 或者是一个用来读写的已存在的文件对象。

     `mode' 参数可以是二进制模式： ‘'r'’, ‘'rb'’, ‘'a'’, ‘'ab'’, ‘'w'’,
     ‘'wb'’, ‘'x'’ or ‘'xb'’ , 或者是文本模式 ‘'rt'’, ‘'at'’, ‘'wt'’, or
     ‘'xt'’。默认值是 ‘'rb'’。

     The `compresslevel' argument is an integer from 0 to 9, as for the
     *note GzipFile: 206. constructor.

     对于二进制模式，这个函数等价于 *note GzipFile: 206. 构造器：
     ‘GzipFile(filename, mode, compresslevel)’。在这个例子中，
     `encoding', `errors' 和 `newline' 三个参数一定不要设置。

     对于文本模式，将会创建一个 *note GzipFile: 206. 对象，并将它封装到
     一个 *note io.TextIOWrapper: 6ea. 实例中， 这个实例默认了指定编码，
     错误抓获行为和行。

     3.3 版更變: 支持 `filename' 为一个文件对象，支持文本模式和
     `encoding', `errors' 和 `newline' 参数。

     3.4 版更變: 支持 ‘'x'’, ‘'xb'’ 和‘‘’xt’‘‘ 三种模式。

     3.6 版更變: 接受一个 *note path-like object: 472.。

 -- 例外: gzip.BadGzipFile

     针对无效 gzip 文件引发的异常。 它继承自 *note OSError: 304.。 针对
     无效 gzip 文件也可能引发 *note EOFError: d34. 和 *note zlib.error:
     1ea5.。

     3.8 版新加入.

 -- 類別: gzip.GzipFile (filename=None, mode=None, compresslevel=9,
          fileobj=None, mtime=None)

     *note GzipFile: 206. 类的构造器支持 ‘truncate()’ 的异常，与 *note
     file object: c14. 的大多数方法非常相似。`fileobj' 和 `filename' 至
     少有一个不为空。

     新的实例基于 `fileobj'，它可以是一个普通文件，一个 *note
     io.BytesIO: 88a. 对象，或者任何一个与文件相似的对象。当 `filename'
     是一个文件对象时，它的默认值是 ‘None’。

     当 `fileobj' 为 ‘None’ 时， `filename' 参数只用于 ‘gzip’ 文件头中，
     这个文件有可能包含未压缩文件的源文件名。如果文件可以被识别，默认
     `fileobj' 的文件名；否则默认为空字符串，在这种情况下文件头将不包含
     源文件名。

     `mode' 参数可以是 ‘'r'’, ‘'rb'’, ‘'a'’, ‘'ab'’, ‘'w'’, ‘'wb'’,
     ‘'x'’ 或 ‘'xb'’ 中的一个，具体取决于文件将被读取还是被写入。 如果可
     识别则默认为 `fileobj' 的模式；否则默认为 ‘'rb'’。 在未来的 Python
     发布版中将不再使用 `fileobj' 的模式。 最好总是指定 `mode' 为写入模
     式。

     需要注意的是，文件默认使用二进制模式打开。如果要以文本模式打开文件
     一个压缩文件，请使用 *note open(): 1eb6. 方法(或者使用 *note
     io.TextIOWrapper: 6ea. 包装 *note GzipFile: 206. )。

     `compresslevel' 参数是一个从 ‘0’ 到 ‘9’ 的整数，用于控制压缩等级；
     ‘1’ 最快但压缩比例最小，‘9’ 最慢但压缩比例最大。 ‘0’ 不压缩。默认为
     ‘9’。

     `mtime' 参数是一个可选的数字时间戳用于写入流的最后修改字段，。
     `mtime' 只在压缩模式中使用。如果省略或者值为 ‘None’，则使用当前时间
     。更多细节，详见 *note mtime: 1eb7. 属性。

     调用 *note GzipFile: 206. 的 ‘close()’ 方法不会关闭 `fileobj'，因为
     你可以希望增加其它内容到已经压缩的数中。你可以将一个 *note
     io.BytesIO: 88a. 对象作为 `fileobj'，也可以使用 *note io.BytesIO:
     88a. 的 *note getvalue(): 1eb8. 方法从内存缓存中恢复数据。

     *note GzipFile: 206. 支持 *note io.BufferedIOBase: 67f. 类的接口, 包
     括迭代和 *note with: 7da. 语句。只有 ‘truncate()’ 方法没有实现。

     *note GzipFile: 206. 还提供了以下的方法和属性:

      -- 成員函式: peek (n)

          在不移动文件指针的情况下读取 `n' 个未压缩字节。最多只有一个单
          独的读取流来服务这个方法调用。返回的字节数不一定刚好等于要求的
          数量。

               備註: 调用 *note peek(): c59. 并没有改变 *note GzipFile:
               206. 的文件指针，它可能改变潜在文件对象(例如： *note
               GzipFile: 206. 使用 `fileobj' 参数进行初始化)。

          3.2 版新加入.

      -- 屬性: mtime

          在解压的过程中，最后修改时间字段的值可能来自于这个属性，以整数
          的形式出现。在读取任何文件头信息前，初始值为 ‘None’。

          所有 ‘gzip’ 东方压缩流中必须包含时间戳这个字段。以便于像
          ‘gunzip’这样的程序可以使用时间戳。格式与 *note time.time():
          42d. 的返回值和 *note os.stat(): 321. 对象的 *note st_mtime:
          1eb9. 属性值一样。

     3.1 版更變: 支持 *note with: 7da. 语句，构造器参数 `mtime' 和 *note
     mtime: 1eb7. 属性。

     3.2 版更變: 添加了对零填充和不可搜索文件的支持。

     3.3 版更變: 实现 *note io.BufferedIOBase.read1(): 1eba. 方法。

     3.4 版更變: 支持 ‘'x'’ and ‘'xb'’ 两种模式。

     3.5 版更變: 支持写入任意 *note bytes-like objects: 6df.。*note
     read(): 1ebb. 方法可以接受‘‘None‘‘为参数。

     3.6 版更變: 接受一个 *note path-like object: 472.。

     3.9 版後已棄用: 打开 *note GzipFile: 206. 用于写入而不指定 `mode' 参
     数的做法已被弃用。

 -- 函式: gzip.compress (data, compresslevel=9, *, mtime=None)

     压缩 `data'，返回一个包含压缩数据的 *note bytes: 172. 对象。
     `compresslevel' 和 `mtime' 的含义与上文中 *note GzipFile: 206. 构造
     器的相同。

     3.2 版新加入.

     3.8 版更變: 添加了 `mtime' 形参用于可重复的输出。

 -- 函式: gzip.decompress (data)

     解压缩 `data'，返回一个包含未压缩数据的 *note bytes: 172. 对象。

     3.2 版新加入.

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/gzip.py


File: python.info,  Node: 用法示例,  Next: 命令行界面,  Up: gzip --- 对 gzip 格式的支持

5.13.2.1 用法示例
.................

读取压缩文件示例：

     import gzip
     with gzip.open('/home/joe/file.txt.gz', 'rb') as f:
         file_content = f.read()

创建GZIP 文件示例：

     import gzip
     content = b"Lots of content here"
     with gzip.open('/home/joe/file.txt.gz', 'wb') as f:
         f.write(content)

使用 GZIP 压缩已有的文件示例：

     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)

使用 GZIP 压缩二进制字符串示例：

     import gzip
     s_in = b"Lots of content here"
     s_out = gzip.compress(s_in)

也參考
......

模块 *note zlib: 14d.

     支持 ‘gzip’ 格式所需要的基本压缩模块。


File: python.info,  Node: 命令行界面,  Prev: 用法示例,  Up: gzip --- 对 gzip 格式的支持

5.13.2.2 命令行界面
...................

*note gzip: 8b. 模块提供了简单的命令行界面用于压缩和解压缩文件。

在执行后 *note gzip: 8b. 模块会保留输入文件。

3.8 版更變: 添加一个带有用法说明的新命令行界面命令。 默认情况下，当你要
执行 CLI 时，默认压缩等级为 6。

* Menu:

* 命令行选项::


File: python.info,  Node: 命令行选项,  Up: 命令行界面

5.13.2.3 命令行选项
...................

 -- 程式選項: file

     如果 `file' 未指定，则从 *note sys.stdin: 41e. 读取。

 -- 程式選項: --fast

     指明最快速的压缩方法（较低压缩率）。

 -- 程式選項: --best

     指明最慢速的压缩方法（最高压缩率）。

 -- 程式選項: -d, --decompress

     解压缩给定的文件。

 -- 程式選項: -h, --help

     显示帮助消息。


File: python.info,  Node: bz2 --- 对 bzip2 压缩算法的支持,  Next: lzma --- 用 LZMA 算法压缩,  Prev: gzip --- 对 gzip 格式的支持,  Up: 資料壓縮與保存

5.13.3 ‘bz2’ — 对 ‘bzip2’ 压缩算法的支持
----------------------------------------

`源代码：' Lib/bz2.py(1)

__________________________________________________________________

此模块提供了使用 bzip2 压缩算法压缩和解压数据的一套完整的接口。

*note bz2: 13. 模块包含：

   * 用于读写压缩文件的 *note open(): ab5. 函数和 *note BZ2File: 224. 类
     。

   * 用于增量压缩和解压的 *note BZ2Compressor: 1ec7. 和 *note
     BZ2Decompressor: 1ec8. 类。

   * 用于一次性压缩和解压的 *note compress(): 19b6. 和 *note
     decompress(): ab6. 函数。

此模块中的所有类都能安全地从多个线程访问。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/bz2.py


File: python.info,  Node: 文件压缩和解压,  Next: 增量压缩和解压,  Up: bz2 --- 对 bzip2 压缩算法的支持

5.13.3.1 文件压缩和解压
.......................

 -- 函式: bz2.open (filename, mode='rb', compresslevel=9, encoding=None,
          errors=None, newline=None)

     以二进制或文本模式打开 bzip2 压缩文件，返回一个 *note file object:
     c14.。

     和 *note BZ2File: 224. 的构造函数类似，`filename' 参数可以是一个实
     际的文件名（*note str: 205. 或 *note bytes: 172. 对象），或是已有的
     可供读取或写入的文件对象。

     `mode' 参数可设为二进制模式的 ‘'r'’、‘'rb'’、‘'w'’、‘'wb'’、‘'x'’、
     ‘'xb'’、‘'a'’ 或 ‘'ab'’，或者文本模式的 ‘'rt'’、‘'wt'’、‘'xt'’ 或
     ‘'at'’。默认是 ‘'rb'’。

     `compresslevel' 参数是 1 到 9 的整数，和 *note BZ2File: 224. 的构造
     函数一样。

     对于二进制模式，这个函数等价于 *note BZ2File: 224. 构造器:
     ‘BZ2File(filename, mode, compresslevel=compresslevel)’。 在这种情况
     下，不可提供 `encoding', `errors' 和 `newline' 参数。

     对于文本模式，将会创建一个 *note BZ2File: 224. 对象，并将它包装到一
     个 *note io.TextIOWrapper: 6ea. 实例中，此实例带有指定的编码格式、
     错误处理行为和行结束符。

     3.3 版新加入.

     3.4 版更變: 添加了 ‘'x'’ (单独创建) 模式。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 類別: bz2.BZ2File (filename, mode='r', *, compresslevel=9)

     用二进制模式打开 bzip2 压缩文件。

     如果 `filename' 是一个 *note str: 205. 或 *note bytes: 172. 对象，
     则打开名称对应的文件目录。 否则的话，`filename' 应当是一个 *note
     file object: c14.，它将被用来读取或写入压缩数据。

     `mode' 参数可以是表示读取的 ‘'r'’ (默认值)，表示覆写的 ‘'w'’，表示
     单独创建的 ‘'x'’，或表示添加的 ‘'a'’。 这些模式还可分别以 ‘'rb'’,
     ‘'wb'’, ‘'xb'’ 和 ‘'ab'’ 的等价形式给出。

     如果 `filename' 是一个文件对象（而不是实际的文件名），则 ‘'w'’ 模式
     并不会截断文件，而是会等价于 ‘'a'’。

     如果 `mode' 为 ‘'w'’ 或 ‘'a'’，则 `compresslevel' 可以是 ‘1’ 到 ‘9’
     之间的整数，用于指定压缩等级: ‘1’ 产生最低压缩率，而 ‘9’ (默认值) 产
     生最高压缩率。

     如果 `mode' 为 ‘'r'’，则输入文件可以为多个压缩流的拼接。

     *note BZ2File: 224. 提供了 *note io.BufferedIOBase: 67f. 所指定的所
     有成员，但 ‘detach()’ 和 ‘truncate()’ 除外。 并支持迭代和 *note
     with: 7da. 语句。

     *note BZ2File: 224. 还提供了以下方法：

      -- 成員函式: peek ([n])

          返回缓冲的数据而不前移文件位置。 至少将返回一个字节的数据（除
          非为 EOF）。 实际返回的字节数不确定。

               備註: 虽然调用 *note peek(): 1eca. 不会改变 *note
               BZ2File: 224. 的文件位置，但它可能改变下层文件对象的位置
               （举例来说如果 *note BZ2File: 224. 是通过传入一个文件对象
               作为 `filename' 的话）。

          3.3 版新加入.

     3.1 版更變: 添加了对 *note with: 7da. 语句的支持。

     3.3 版更變: 添加了 ‘fileno()’, ‘readable()’, ‘seekable()’,
     ‘writable()’, ‘read1()’ 和 ‘readinto()’ 方法。

     3.3 版更變: 添加了对 `filename' 使用 *note file object: c14. 而非实
     际文件名的支持。

     3.3 版更變: 添加了 ‘'a'’ (append) 模式，以及对读取多数据流文件的支
     持。

     3.4 版更變: 添加了 ‘'x'’ (单独创建) 模式。

     3.5 版更變: *note read(): 1ebb. 方法现在接受 ‘None’ 作为参数。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

     3.9 版更變: `buffering' 形参已被移除。 它自 Python 3.0 起即被忽略并
     弃用。 请传入一个打开文件对象来控制文件的打开方式。

     `compresslevel' 形参成为仅限关键字参数。


File: python.info,  Node: 增量压缩和解压,  Next: 一次性压缩或解压缩,  Prev: 文件压缩和解压,  Up: bz2 --- 对 bzip2 压缩算法的支持

5.13.3.2 增量压缩和解压
.......................

 -- 類別: bz2.BZ2Compressor (compresslevel=9)

     创建一个新的压缩器对象。 此对象可被用来执行增量数据压缩。 对于一次
     性压缩，请改用 *note compress(): 19b6. 函数。

     如果给定 `compresslevel'，它必须为 ‘1’ 至 ‘9’ 之间的整数。 默认值为
     ‘9’。

      -- 成員函式: compress (data)

          向压缩器对象提供数据。 在可能的情况下返回一段已压缩数据，否则
          返回空字节串。

          当你已结束向压缩器提供数据时，请调用 *note flush(): 1ecd. 方法
          来完成压缩进程。

      -- 成員函式: flush ()

          结束压缩进程，返回内部缓冲中剩余的压缩完成的数据。

          调用此方法之后压缩器对象将不可再被使用。

 -- 類別: bz2.BZ2Decompressor

     创建一个新的解压缩器对象。 此对象可被用来执行增量数据解压缩。 对于
     一次性解压缩，请改用 *note decompress(): ab6. 函数。

          備註: 这个类不会透明地处理包含多个已压缩数据流的输入，这不同于
          *note decompress(): ab6. 和 *note BZ2File: 224.。 如果你需要通
          过 *note BZ2Decompressor: 1ec8. 来解压缩多个数据流输入，你必须
          为每个数据流都使用新的解压缩器。

      -- 成員函式: decompress (data, max_length=-1)

          解压缩 `data' (一个 *note bytes-like object: 6df.)，返回字节串
          形式的解压缩数据。 某些 `data' 可以在内部被缓冲，以便用于后续
          的 *note decompress(): ab6. 调用。 返回的数据应当与之前任何
          *note decompress(): ab6. 调用的输出进行拼接。

          如果 `max_length' 为非负数，将返回至多 `max_length' 个字节的解
          压缩数据。 如果达到此限制并且可以产生后续输出，则 *note
          needs_input: 1ece. 属性将被设为 ‘False’。 在这种情况下，下一次
          *note decompress(): 796. 调用提供的 `data' 可以为 ‘b''’ 以获取
          更多的输出。

          如果所有输入数据都已被解压缩并返回（或是因为它少于
          `max_length' 个字节，或是因为 `max_length' 为负数），则 *note
          needs_input: 1ece. 属性将被设为 ‘True’。

          在到达数据流末尾之后再尝试解压缩数据会引发 ‘EOFError’。 在数据
          流末尾之后获取的任何数据都会被忽略并存储至 *note unused_data:
          1ecf. 属性。

          3.5 版更變: 添加了 `max_length' 形参。

      -- 屬性: eof

          若达到了数据流的末尾标记则为 ‘True’。

          3.3 版新加入.

      -- 屬性: unused_data

          在压缩数据流的末尾之后获取的数据。

          如果在达到数据流末尾之前访问此属性，其值将为 ‘b''’。

      -- 屬性: needs_input

          如果在要求新的未解压缩输入之前 *note decompress(): 796. 方法可
          以提供更多的解压缩数据则为 ‘False’。

          3.5 版新加入.


File: python.info,  Node: 一次性压缩或解压缩,  Next: 用法示例<2>,  Prev: 增量压缩和解压,  Up: bz2 --- 对 bzip2 压缩算法的支持

5.13.3.3 一次性压缩或解压缩
...........................

 -- 函式: bz2.compress (data, compresslevel=9)

     压缩 `data'，此参数为一个 *note 字节类对象: 6df.。

     如果给定 `compresslevel'，它必须为 ‘1’ 至 ‘9’ 之间的整数。 默认值为
     ‘9’。

     对于增量压缩，请改用 *note BZ2Compressor: 1ec7.。

 -- 函式: bz2.decompress (data)

     解压缩 `data'，此参数为一个 *note 字节类对象: 6df.。

     如果 `data' 是多个压缩数据流的拼接，则解压缩所有数据流。

     对于增量解压缩，请改用 *note BZ2Decompressor: 1ec8.。

     3.3 版更變: 支持了多数据流的输入。


File: python.info,  Node: 用法示例<2>,  Prev: 一次性压缩或解压缩,  Up: bz2 --- 对 bzip2 压缩算法的支持

5.13.3.4 用法示例
.................

以下是 *note bz2: 13. 模块典型用法的一些示例。

使用 *note compress(): 19b6. 和 *note decompress(): ab6. 来显示往复式的
压缩：

     >>> 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

使用 *note BZ2Compressor: 1ec7. 进行增量压缩：

     >>> 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()

上面的示例使用了十分“非随机”的数据流（即 ‘b"z"’ 块数据流）。 随机数据的
压缩率通常很差，而有序、重复的数据通常会产生很高的压缩率。

用二进制模式写入和读取 bzip2 压缩文件：

     >>> 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


File: python.info,  Node: lzma --- 用 LZMA 算法压缩,  Next: zipfile --- 使用ZIP存档,  Prev: bz2 --- 对 bzip2 压缩算法的支持,  Up: 資料壓縮與保存

5.13.4 ‘lzma’ — 用 LZMA 算法压缩
--------------------------------

3.3 版新加入.

`源代码：' Lib/lzma.py(1)

__________________________________________________________________

此模块提供了可以压缩和解压缩使用 LZMA 压缩算法的数据的类和便携函数。 其
中还包含支持 ‘xz’ 工具所使用的 ‘.xz’ 和旧式 ‘.lzma’ 文件格式的文件接口，
以及相应的原始压缩数据流。

此模块所提供的接口与 *note bz2: 13. 模块的非常类似。 但是，请注意 *note
LZMAFile: a16. `不是' 线程安全的，这与 *note bz2.BZ2File: 224. 不同，因
此如果你需要在多个线程中使用单个 *note LZMAFile: a16. 实例，则需要通过锁
来保护它。

 -- 例外: lzma.LZMAError

     当在压缩或解压缩期间或是在初始化压缩器/解压缩器的状态期间发生错误时
     此异常会被引发。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/lzma.py


File: python.info,  Node: 读写压缩文件,  Next: 在内存中压缩和解压缩数据,  Up: lzma --- 用 LZMA 算法压缩

5.13.4.1 读写压缩文件
.....................

 -- 函式: lzma.open (filename, mode="rb", *, format=None, check=-1,
          preset=None, filters=None, encoding=None, errors=None,
          newline=None)

     以二进制或文本模式打开 LZMA 压缩文件，返回一个 *note file object:
     c14.。

     `filename' 参数可以是一个实际的文件名（以 *note str: 205, *note
     bytes: 172. 或 *note 路径类: 472. 对象的形式给出），在此情况下会打
     开指定名称的文件，或者可以是一个用于读写的现有文件对象。

     `mode' 参数可以是二进制模式的 ‘"r"’, ‘"rb"’, ‘"w"’, ‘"wb"’, ‘"x"’,
     ‘"xb"’, ‘"a"’ 或 ‘"ab"’，或者文本模式的 ‘"rt"’, ‘"wt"’, ‘"xt"’ 或
     ‘"at"’。 默认值为 ‘"rb"’。

     当打开一个文件用于读取时，`format' 和 `filters' 参数具有与 *note
     LZMADecompressor: 1ed9. 的参数相同的含义。 在此情况下，`check' 和
     `preset' 参数不应被使用。

     当打开一个文件用于写入的，`format', `check', `preset' 和 `filters'
     参数具有与 *note LZMACompressor: 1eda. 的参数相同的含义。

     对于二进制模式，这个函数等价于 *note LZMAFile: a16. 构造器:
     ‘LZMAFile(filename, mode, ...)’。 在这种情况下，不可提供
     `encoding', `errors' 和 `newline' 参数。

     对于文本模式，将会创建一个 *note LZMAFile: a16. 对象，并将它包装到
     一个 *note io.TextIOWrapper: 6ea. 实例中，此实例带有指定的编码格式
     、错误处理行为和行结束符。

     3.4 版更變: 增加了对 ‘"x"’, ‘"xb"’ 和 ‘"xt"’ 模式的支持。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 類別: lzma.LZMAFile (filename=None, mode="r", *, format=None,
          check=-1, preset=None, filters=None)

     以二进制模式打开一个 LZMA 压缩文件。

     *note LZMAFile: a16. 可以包装在一个已打开的 *note file object: c14.
     中，或者是在给定名称的文件上直接操作。 `filename' 参数指定所包装的
     文件对象，或是要打开的文件名称（类型为 *note str: 205, *note bytes:
     172. 或 *note 路径类: 472. 对象）。 如果是包装现有的文件对象，被包
     装的文件在 *note LZMAFile: a16. 被关闭时将不会被关闭。

     `mode' 参数可以是表示读取的 ‘"r"’ (默认值)，表示覆写的 ‘"w"’，表示
     单独创建的 ‘"x"’，或表示添加的 ‘"a"’。 这些模式还可以分别以 ‘"rb"’,
     ‘"wb"’, ‘"xb"’ 和 ‘"ab"’ 的等价形式给出。

     如果 `filename' 是一个文件对象（而不是实际的文件名），则 ‘"w"’ 模式
     并不会截断文件，而会等价于 ‘"a"’。

     当打开一个文件用于读取时，输入文件可以为多个独立压缩流的拼接。 它们
     会被作为单个逻辑流被透明地解码。

     当打开一个文件用于读取时，`format' 和 `filters' 参数具有与 *note
     LZMADecompressor: 1ed9. 的参数相同的含义。 在此情况下，`check' 和
     `preset' 参数不应被使用。

     当打开一个文件用于写入的，`format', `check', `preset' 和 `filters'
     参数具有与 *note LZMACompressor: 1eda. 的参数相同的含义。

     *note LZMAFile: a16. 支持 *note io.BufferedIOBase: 67f. 所指定的所
     有成员，但 ‘detach()’ 和 ‘truncate()’ 除外。 并支持迭代和 *note
     with: 7da. 语句。

     也提供以下方法：

      -- 成員函式: peek (size=-1)

          返回缓冲的数据而不前移文件位置。 至少将返回一个字节的数据，除
          非已经到达 EOF。 实际返回的字节数不确定（会忽略 `size' 参数）
          。

               備註: 虽然调用 *note peek(): 1edb. 不会改变 *note
               LZMAFile: a16. 的文件位置，但它可能改变下层文件对象的位置
               （举例来说如果 *note LZMAFile: a16. 是通过传入一个文件对
               象作为 `filename' 的话）。

     3.4 版更變: 增加了对 ‘"x"’ 和 ‘"xb"’ 模式的支持。

     3.5 版更變: *note read(): 1ebb. 方法现在接受 ‘None’ 作为参数。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。


File: python.info,  Node: 在内存中压缩和解压缩数据,  Next: 杂项<2>,  Prev: 读写压缩文件,  Up: lzma --- 用 LZMA 算法压缩

5.13.4.2 在内存中压缩和解压缩数据
.................................

 -- 類別: lzma.LZMACompressor (format=FORMAT_XZ, check=-1, preset=None,
          filters=None)

     创建一个压缩器对象，此对象可被用来执行增量压缩。

     压缩单个数据块的更便捷方式请参阅 *note compress(): 1edd.。

     `format' 参数指定应当使用哪种容器格式。 可能的值有：

        * 
          ‘FORMAT_XZ’: ‘.xz’ 容器格式。

               这是默认格式。

        * 
          ‘FORMAT_ALONE’: 传统的 ‘.lzma’ 容器格式。

               这种格式相比 ‘.xz’ 更为受限 – 它不支持一致性检查或多重过
               滤器。

        * 
          ‘FORMAT_RAW’: 原始数据流，不使用任何容器格式。

               这个格式描述器不支持一致性检查，并且要求你必须指定一个自
               定义的过滤器链（用于压缩和解压缩）。 此外，以这种方式压缩
               的数据不可使用 ‘FORMAT_AUTO’ 来解压缩 (参见 *note
               LZMADecompressor: 1ed9.)。

     `check' 参数指定要包含在压缩数据中的一致性检查类型。 这种检查在解压
     缩时使用，以确保数据没有被破坏。 可能的值是：

        * ‘CHECK_NONE’: 没有一致性检查。 这是 ‘FORMAT_ALONE’ 和
          ‘FORMAT_RAW’ 的默认值（也是唯一可接受的值）。

        * ‘CHECK_CRC32’: 32 位循环冗余检查。

        * ‘CHECK_CRC64’: 64 位循环冗余检查。 这是 ‘FORMAT_XZ’ 的默认值。

        * ‘CHECK_SHA256’: 256 位安全哈希算法。

     如果指定的检查不受支持，则会引发 *note LZMAError: 1ed6.。

     压缩设置可被指定为一个预设的压缩等级（通过 `preset' 参数）或以自定
     义过滤器链来详细设置（通过 `filters' 参数）。

     `preset' 参数（如果提供）应当为一个 ‘0’ 到 ‘9’ (包括边界) 之间的整
     数，可以选择与常数 ‘PRESET_EXTREME’ 进行 OR 运算。 如果 `preset' 和
     `filters' 均未给出，则默认行为是使用 ‘PRESET_DEFAULT’ (预设等级
     ‘6’)。 更高的预设等级会产生更小的输出，但会使得压缩过程更缓慢。

          備註: 除了更加 CPU 密集，使用更高的预设等级来压缩还需要更多的
          内存（并产生需要更多内存来解压缩的输出）。 例如使用预设等级
          ‘9’ 时，一个 *note LZMACompressor: 1eda. 对象的开销可以高达
          800 MiB。 出于这样的原因，通常最好是保持使用默认预设等级。

     `filters' 参数（如果提供）应当指定一个过滤器链。 详情参见 *note
     指定自定义的过滤器链: 1ede.。

      -- 成員函式: compress (data)

          压缩 `data' (一个 *note bytes: 172. object)，返回包含针对输入
          的至少一部分已压缩数据的 *note bytes: 172. 对象。 一部 `data'
          可能会被放入内部缓冲区，以便用于后续的 *note compress(): 1edd.
          和 *note flush(): 1ee0. 调用。 返回的数据应当与之前任何 *note
          compress(): 1edd. 调用的输出进行拼接。

      -- 成員函式: flush ()

          结束压缩进程，返回包含保存在压缩器的内部缓冲区中的任意数据的
          *note bytes: 172. 对象。

          调用此方法之后压缩器将不可再被使用。

 -- 類別: lzma.LZMADecompressor (format=FORMAT_AUTO, memlimit=None,
          filters=None)

     创建一个压缩器对象，此对象可被用来执行增量解压缩。

     一次性解压缩整个压缩数据流的更便捷方式请参阅 *note decompress():
     1ee1.。

     `format' 参数指定应当被使用的容器格式。 默认值为 ‘FORMAT_AUTO’，它
     可以解压缩 ‘.xz’ 和 ‘.lzma’ 文件。 其他可能的值为 ‘FORMAT_XZ’,
     ‘FORMAT_ALONE’ 和 ‘FORMAT_RAW’。

     `memlimit' 参数指定解压缩器可以使用的内存上限（字节数）。 当使用此
     参数时，如果不可能在给定内存上限之内解压缩输入数据则解压缩将失败并
     引发 *note LZMAError: 1ed6.。

     `filters' 参数指定用于创建被解压缩数据流的过滤器链。 此参数在
     `format' 为 ‘FORMAT_RAW’ 时要求提供，但对于其他格式不应使用。 有关
     过滤器链的更多信息请参阅 *note 指定自定义的过滤器链: 1ede.。

          備註: 这个类不会透明地处理包含多个已压缩数据流的输入，这不同于
          *note decompress(): 1ee1. 和 *note LZMAFile: a16.。 要通过
          *note LZMADecompressor: 1ed9. 来解压缩多个数据流输入，你必须为
          每个数据流都创建一个新的解压缩器。

      -- 成員函式: decompress (data, max_length=-1)

          解压缩 `data' (一个 *note bytes-like object: 6df.)，返回字节串
          形式的解压缩数据。 某些 `data' 可以在内部被缓冲，以便用于后续
          的 *note decompress(): 1ee1. 调用。 返回的数据应当与之前任何
          *note decompress(): 1ee1. 调用的输出进行拼接。

          如果 `max_length' 为非负数，将返回至多 `max_length' 个字节的解
          压缩数据。 如果达到此限制并且可以产生后续输出，则 *note
          needs_input: 1ee2. 属性将被设为 ‘False’。 在这种情况下，下一次
          *note decompress(): 805. 调用提供的 `data' 可以为 ‘b''’ 以获取
          更多的输出。

          如果所有输入数据都已被解压缩并返回（或是因为它少于
          `max_length' 个字节，或是因为 `max_length' 为负数），则 *note
          needs_input: 1ee2. 属性将被设为 ‘True’。

          在到达数据流末尾之后再尝试解压缩数据会引发 ‘EOFError’。 在数据
          流末尾之后获取的任何数据都会被忽略并存储至 *note unused_data:
          1ee3. 属性。

          3.5 版更變: 添加了 `max_length' 形参。

      -- 屬性: check

          输入流使用的一致性检查的 ID。 这可能为 ‘CHECK_UNKNOWN’ 直到已
          解压了足够的输入数据来确定它所使用的一致性检查。

      -- 屬性: eof

          若达到了数据流末尾标识符则为 ‘True’。

      -- 屬性: unused_data

          压缩数据流的末尾还有数据。

          在达到数据流末尾之前，这个值将为 ‘b""’。

      -- 屬性: needs_input

          如果在要求新的未解压缩输入之前 *note decompress(): 805. 方法可
          以提供更多的解压缩数据则为 ‘False’。

          3.5 版新加入.

 -- 函式: lzma.compress (data, format=FORMAT_XZ, check=-1, preset=None,
          filters=None)

     压缩 `data' (一个 *note bytes: 172. 对象)，返回包含压缩数据的 *note
     bytes: 172. 对象。

     参见上文的 *note LZMACompressor: 1eda. 了解有关 `format', `check',
     `preset' 和 `filters' 参数的说明。

 -- 函式: lzma.decompress (data, format=FORMAT_AUTO, memlimit=None,
          filters=None)

     解压缩 `data' (一个 *note bytes: 172. 对象)，返回包含解压缩数据的
     *note bytes: 172. 对象。

     如果 `data' 是多个单独压缩数据流的拼接，则解压缩所有相应数据流，并
     返回结果的拼接。

     参见上文的 *note LZMADecompressor: 1ed9. 了解有关 `format',
     `memlimit' 和 `filters' 参数的说明。


File: python.info,  Node: 杂项<2>,  Next: 指定自定义的过滤器链,  Prev: 在内存中压缩和解压缩数据,  Up: lzma --- 用 LZMA 算法压缩

5.13.4.3 杂项
.............

 -- 函式: lzma.is_check_supported (check)

     如果本系统支持给定的一致性检查则返回 ‘True’。

     ‘CHECK_NONE’ 和 ‘CHECK_CRC32’ 总是受支持。 ‘CHECK_CRC64’ 和
     ‘CHECK_SHA256’ 或许不可用，如果你正在使用基于受限制特性集编译的
     ‘liblzma’ 版本的话。


File: python.info,  Node: 指定自定义的过滤器链,  Next: 示例<11>,  Prev: 杂项<2>,  Up: lzma --- 用 LZMA 算法压缩

5.13.4.4 指定自定义的过滤器链
.............................

过滤器链描述符是由字典组成的序列，其中每个字典包含单个过滤器的 ID 和选项
。 每个字典必须包含键 ‘"id"’，并可能包含额外的键用来指定基于过滤器的选项
。 有效的过滤器 ID 如下：

   * 
     压缩过滤器：

             * ‘FILTER_LZMA1’ (配合 ‘FORMAT_ALONE’ 使用)

             * ‘FILTER_LZMA2’ (配合 ‘FORMAT_XZ’ 和 ‘FORMAT_RAW’ 使用)

   * 
     Delta 过滤器：

             * ‘FILTER_DELTA’

   * 
     Branch-Call-Jump (BCJ) 过滤器：

             * ‘FILTER_X86’

             * ‘FILTER_IA64’

             * ‘FILTER_ARM’

             * ‘FILTER_ARMTHUMB’

             * ‘FILTER_POWERPC’

             * ‘FILTER_SPARC’

一个过滤器链最多可由 4 个过滤器组成，并且不能为空。 过滤器链中的最后一个
过滤器必须为压缩过滤器，其他过滤器必须为 Delta 或 BCJ 过滤器。

压缩过滤器支持下列选项（指定为表示过滤器的字典中的附加条目）：

        * ‘preset’: 压缩预设选项，用于作为未显式指定的选项的默认值的来源
          。

        * ‘dict_size’: 以字节表示的字典大小。 这应当在 4 KiB 和 1.5 GiB
          之间（包含边界）。

        * ‘lc’: 字面值上下文的比特数。

        * ‘lp’: 字面值位置的比特数。 总计值 ‘lc + lp’ 必须不大于 4。

        * ‘pb’: 位置的比特数；必须不大于 4。

        * ‘mode’: ‘MODE_FAST’ 或 ‘MODE_NORMAL’。

        * ‘nice_len’: 对于一个匹配应当被视为“适宜长度”的值。 这应当小于
          或等于 273。

        * ‘mf’: 要使用的匹配查找器 – ‘MF_HC3’, ‘MF_HC4’, ‘MF_BT2’,
          ‘MF_BT3’ 或 ‘MF_BT4’。

        * ‘depth’: 匹配查找器使用的最大查找深度。 0 (默认值) 表示基于其
          他过滤器选项自动选择。

Delta 过滤器保存字节数据之间的差值，在特定环境下可产生更具重复性的输入。
它支持一个 ‘dist’ 选项，指明要减去的字节之间的差值大小。 默认值为 1，即
相邻字节之间的差值。

BCJ 过滤器主要作用于机器码。 它们会转换机器码内的相对分支、调用和跳转以
使用绝对寻址，其目标是提升冗余度以供压缩器利用。 这些过滤器支持一个
‘start_offset’ 选项，指明应当被映射到输入数据开头的地址。 默认值为 0。


File: python.info,  Node: 示例<11>,  Prev: 指定自定义的过滤器链,  Up: lzma --- 用 LZMA 算法压缩

5.13.4.5 示例
.............

在已压缩的数据中读取:

     import lzma
     with lzma.open("file.xz") as f:
         file_content = f.read()

创建一个压缩文件:

     import lzma
     data = b"Insert Data Here"
     with lzma.open("file.xz", "w") as f:
         f.write(data)

在内存中压缩文件:

     import lzma
     data_in = b"Insert Data Here"
     data_out = lzma.compress(data_in)

增量压缩:

     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])

写入已压缩数据到已打开的文件:

     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")

使用自定义过滤器链创建一个已压缩文件:

     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")


File: python.info,  Node: zipfile --- 使用ZIP存档,  Next: tarfile --- 读写tar归档文件,  Prev: lzma --- 用 LZMA 算法压缩,  Up: 資料壓縮與保存

5.13.5 ‘zipfile’ — 使用ZIP存档
------------------------------

`源代码：' Lib/zipfile.py(1)

__________________________________________________________________

ZIP 文件格式是一个常用的归档与压缩标准。 这个模块提供了创建、读取、写入
、添加及列出 ZIP 文件的工具。 任何对此模块的进阶使用都将需要理解此格式，
其定义参见 PKZIP 应用程序笔记(2)。

此模块目前不能处理分卷 ZIP 文件。它可以处理使用 ZIP64 扩展（超过 4 GB 的
ZIP 文件）的 ZIP 文件。它支持解密 ZIP 归档中的加密文件，但是目前不能创建
一个加密的文件。解密非常慢，因为它是使用原生 Python 而不是 C 实现的。

这个模块定义了以下内容：

 -- 例外: zipfile.BadZipFile

     为损坏的 ZIP 文件抛出的错误。

     3.2 版新加入.

 -- 例外: zipfile.BadZipfile

     *note BadZipFile: 1eec. 的别名，与旧版本 Python 保持兼容性。

     3.2 版後已棄用.

 -- 例外: zipfile.LargeZipFile

     当 ZIP 文件需要 ZIP64 功能但是未启用时会抛出此错误。

 -- 類別: zipfile.ZipFile

     用于读写 ZIP 文件的类。 欲了解构造函数的描述，参阅段落 *note
     ZipFile 对象: 1eef.。

 -- 類別: zipfile.Path

     用于 zip 文件的兼容 pathlib 的包装器。 详情参见 *note Path 对象:
     1ef0.。

     3.8 版新加入.

 -- 類別: zipfile.PyZipFile

     用于创建包含 Python 库的 ZIP 归档的类。

 -- 類別: zipfile.ZipInfo (filename='NoName', date_time=(1980, 1, 1, 0,
          0, 0))

     用于表示档案内一个成员信息的类。 此类的实例会由 *note ZipFile: 522.
     对象的 *note getinfo(): 1ef1. 和 *note infolist(): 1ef2. 方法返回。
     大多数 *note zipfile: 14b. 模块的用户都不必创建它们，只需使用此模块
     所创建的实例。 `filename' 应当是档案成员的全名，`date_time' 应当是
     包含六个字段的描述最近修改时间的元组；这些字段的描述请参阅 *note
     ZipInfo 对象: 1ef3.。

 -- 函式: zipfile.is_zipfile (filename)

     根据文件的 Magic Number，如果 `filename' 是一个有效的 ZIP 文件则返
     回 ‘True’，否则返回 ‘False’。 `filename' 也可能是一个文件或类文件对
     象。

     3.1 版更變: 支持文件或类文件对象。

 -- Data: zipfile.ZIP_STORED

     未被压缩的归档成员的数字常数。

 -- Data: zipfile.ZIP_DEFLATED

     常用的 ZIP 压缩方法的数字常数。需要 *note zlib: 14d. 模块。

 -- Data: zipfile.ZIP_BZIP2

     BZIP2 压缩方法的数字常数。需要 *note bz2: 13. 模块。

     3.3 版新加入.

 -- Data: zipfile.ZIP_LZMA

     LZMA 压缩方法的数字常数。需要 *note lzma: ad. 模块。

     3.3 版新加入.

          備註: ZIP 文件格式规范包括自 2001 年以来对 bzip2 压缩的支持，
          以及自 2006 年以来对 LZMA 压缩的支持。但是，一些工具（包括较旧
          的 Python 版本）不支持这些压缩方法，并且可能拒绝完全处理 ZIP 文
          件，或者无法提取单个文件。

也參考
......

PKZIP 应用程序笔记(3)

     Phil Katz 编写的 ZIP 文件格式文档，此格式和使用的算法的创建者。

Info-ZIP 主页(4)

     有关 Info-ZIP 项目的 ZIP 存档程序和开发库的信息。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/zipfile.py

   (2) https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT

   (3) https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT

   (4) http://www.info-zip.org/


File: python.info,  Node: ZipFile 对象,  Next: Path 对象,  Up: zipfile --- 使用ZIP存档

5.13.5.1 ZipFile 对象
.....................

 -- 類別: zipfile.ZipFile (file, mode='r', compression=ZIP_STORED,
          allowZip64=True, compresslevel=None, *,
          strict_timestamps=True)

     打开一个 ZIP 文件，`file' 为一个指向文件的路径（字符串），一个类文
     件对象或者一个 *note path-like object: 472.。

     形参 `mode' 应当为 ‘'r'’ 来读取一个存在的文件，‘'w'’ 来截断并写入新
     的文件， ‘'a'’ 来添加到一个存在的文件，或者 ‘'x'’ 来仅新建并写入新
     的文件。如果 `mode' 为 ‘'x'’ 并且 `file' 指向已经存在的文件，则抛出
     *note FileExistsError: a39.。如果 `mode' 为 ‘'a'’ 且 `file' 为已存
     在的文件，则格外的文件将被加入。如果 `file' 不指向 ZIP 文件，之后一
     个新的 ZIP 归档将被追加为此文件。这是为了将 ZIP 归档添加到另一个文
     件（例如 ‘python.exe’）。如果 `mode' 为 ‘'a'’ 并且文件不存在， 则会
     新建。如果 `mode' 为 ‘'r'’ 或 ‘'a'’， 则文件应当可定位。

     `compression' 是在写入归档时要使用的 ZIP 压缩方法，应为 *note
     ZIP_STORED: 1ef4, *note ZIP_DEFLATED: 1ef5, *note ZIP_BZIP2: 1ef6.
     或 *note ZIP_LZMA: 1ef7.；不可识别的值将导致引发 *note
     NotImplementedError: 704.。 如果指定了 *note ZIP_DEFLATED: 1ef5,
     *note ZIP_BZIP2: 1ef6. 或 *note ZIP_LZMA: 1ef7. 但相应的模块 (*note
     zlib: 14d, *note bz2: 13. 或 *note lzma: ad.) 不可用，则会引发
     *note RuntimeError: 3dc.。 默认值为 *note ZIP_STORED: 1ef4.。

     如果 `allowZip64' 为 ‘True’ (默认值) 则当 zipfile 大于 4 GiB 时
     zipfile 将创建使用 ZIP64 扩展的 ZIP 文件。 如果该参数为 ‘false’ 则
     当 ZIP 文件需要 ZIP64 扩展时 *note zipfile: 14b. 将引发异常。

     `compresslevel' 形参控制在将文件写入归档时要使用的压缩等级。 当使用
     *note ZIP_STORED: 1ef4. 或 *note ZIP_LZMA: 1ef7. 时无压缩效果。 当
     使用 *note ZIP_DEFLATED: 1ef5. 时接受整数 ‘0’ 至 ‘9’ (更多信息参见
     *note zlib: 1ea7.)。 当使用 *note ZIP_BZIP2: 1ef6. 时接受整数 ‘1’ 至
     ‘9’ (更多信息参见 *note bz2: 224.)。

     `strict_timestamps' 参数在设为 ‘False’ 时允许压缩早于 1980-01-01 的
     文件，代价时会将时间戳设为 1980-01-01。 类似的行为也会对晚于
     2107-12-31 的文件发生，时间戳也会被设为该上限值。

     如果创建文件时使用 ‘'w'’, ‘'x'’ 或 ‘'a'’ 模式并且未向归档添加任何文
     件就执行了 *note closed: 1ef9.，则会将适当的空归档 ZIP 结构写入文件
     。

     ZipFile 也是一个上下文管理器，因此支持 *note with: 7da. 语句。 在这
     个示例中，`myzip' 将在 ‘with’ 语句块执行完成之后被关闭 — 即使是发生
     了异常:

          with ZipFile('spam.zip', 'w') as myzip:
              myzip.write('eggs.txt')

     3.2 版新加入: 添加了将 *note ZipFile: 522. 用作上下文管理员的功能。

     3.3 版更變: 添加了对 *note bzip2: 13. 和 *note lzma: ad. 压缩的支持
     。

     3.4 版更變: 默认启用 ZIP64 扩展。

     3.5 版更變: 添加了对不可查找数据流的支持。 并添加了对 ‘'x'’ 模式的
     支持。

     3.6 版更變: 在此之前，对于不可识别的压缩值将引发普通的 *note
     RuntimeError: 3dc.。

     3.6.2 版更變: `file' 形参接受一个 *note path-like object: 472.。

     3.7 版更變: 添加了 `compresslevel' 形参。

     3.8 版新加入: `strict_timestamps' 仅限关键字参数

 -- 成員函式: ZipFile.close ()

     关闭归档文件。 你必须在退出程序之前调用 *note close(): 1ef9. 否则将
     不会写入关键记录数据。

 -- 成員函式: ZipFile.getinfo (name)

     返回一个 *note ZipInfo: 6b1. 对象，其中包含有关归档成员 `name' 的信
     息。 针对一个目前并不包含于归档中的名称调用 *note getinfo(): 1ef1.
     将会引发 *note KeyError: 3e9.。

 -- 成員函式: ZipFile.infolist ()

     返回一个列表，其中包含每个归档成员的 *note ZipInfo: 6b1. 对象。 如
     果是打开一个现有归档则这些对象的排列顺序与它们对应条目在磁盘上的实
     际 ZIP 文件中的顺序一致。

 -- 成員函式: ZipFile.namelist ()

     返回按名称排序的归档成员列表。

 -- 成員函式: ZipFile.open (name, mode='r', pwd=None, *,
          force_zip64=False)

     以二进制文件类对象的形式访问一个归档成员。 `name' 可以是归档内某个
     文件的名称也可以是某个 *note ZipInfo: 6b1. 对象。 如果包含了 `mode'
     形参，则它必须为 ‘'r'’ (默认值) 或 ‘'w'’。 `pwd' 为用于解密已加密
     ZIP 文件的密码。

     *note open(): 6b3. 也是一个上下文管理器，因此支持 *note with: 7da.
     语句:

          with ZipFile('spam.zip') as myzip:
              with myzip.open('eggs.txt') as myfile:
                  print(myfile.read())

     如果 `mode' 为 ‘'r'’ 则文件类对象 (‘ZipExtFile’) 将为只读并且提供下
     列方法: *note read(): 1ebb, *note readline(): 1849, *note
     readlines(): 18d6, *note seek(): 1efb, *note tell(): 1efc, *note
     __iter__(): 608, *note __next__(): d2c.。 这些对象可独立于 ZipFile
     进行操作。

     如果 ‘mode='w'’ 则返回一个可写入的文件句柄，它将支持 *note write():
     680. 方法。 当一个可写入的文件句柄被打开时，尝试读写 ZIP 文件中的其
     他文件将会引发 *note ValueError: 16d.。

     当写入一个文件时，如果文件大小不能预先确定但是可能超过 2 GiB，可传
     入 ‘force_zip64=True’ 以确保标头格式能够支持超大文件。 如果文件大小
     可以预先确定，则在构造 *note ZipInfo: 6b1. 对象时应设置 *note
     file_size: 1efd.，并将其用作 `name' 形参。

          備註: *note open(): 6b3, *note read(): d81. 和 *note
          extract(): 1efe. 方法可接受文件名或 *note ZipInfo: 6b1. 对象。
          当尝试读取一个包含重复名称成员的 ZIP 文件时你将发现此功能很有
          好处。

     3.6 版更變: 移除了对 ‘mode='U'’ 的支持。 请使用 *note
     io.TextIOWrapper: 6ea. 以在 *note universal newlines: 6eb. 模式中读
     取已压缩的文本文件。

     3.6 版更變: *note open(): 16f. 现在可以被用来配合 ‘mode='w'’ 选项来
     将文件写入归档。

     3.6 版更變: 在已关闭的 ZipFile 上调用 *note open(): 6b3. 将引发
     *note ValueError: 16d.。 在之前的版本中则会引发 *note RuntimeError:
     3dc.。

 -- 成員函式: ZipFile.extract (member, path=None, pwd=None)

     从归档中提取出一个成员放入当前工作目录；`member' 必须为成员的完整名
     称或 *note ZipInfo: 6b1. 对象。 成员的文件信息会尽可能精确地被提取
     。 `path' 指定一个要提取到的不同目录。 `member' 可以是一个文件名或
     *note ZipInfo: 6b1. 对象。 `pwd' 是用于解密文件的密码。

     返回所创建的经正规化的路径（对应于目录或新文件）。

          備註: 如果一个成员文件名为绝对路径，则将去掉驱动器/UNC共享点和
          前导的（反）斜杠，例如: ‘///foo/bar’ 在 Unix 上将变为
          ‘foo/bar’，而 ‘C:\foo\bar’ 在 Windows 上将变为 ‘foo\bar’。 并
          且一个成员文件名中的所有 ‘".."’ 都将被移除，例如:
          ‘../../foo../../ba..r’ 将变为 ‘foo../ba..r’。 在 Windows 上非
          法字符 (‘:’, ‘<’, ‘>’, ‘|’, ‘"’, ‘?’, and ‘*’) 会被替换为下划
          线 (‘_’)。

     3.6 版更變: 在已关闭的 ZipFile 上调用 *note extract(): 1efe. 将引发
     *note ValueError: 16d.。 在之前的版本中则将引发 *note RuntimeError:
     3dc.。

     3.6.2 版更變: `path' 形参接受一个 *note path-like object: 472.。

 -- 成員函式: ZipFile.extractall (path=None, members=None, pwd=None)

     从归档中提取出所有成员放入当前工作目录。 `path' 指定一个要提取到的
     不同目录。 `members' 为可选项且必须为 *note namelist(): 1efa. 所返
     回列表的一个子集。 `pwd' 是用于解密文件的密码。

          警告: 绝不要未经预先检验就从不可靠的源中提取归档文件。 这样有
          可能在 `path' 之外创建文件，例如某些成员具有以 ‘"/"’ 开始的文
          件名或带有两个点号 ‘".."’ 的文件名。 此模块会尝试防止这种情况
          。 参见 *note extract(): 1efe. 的注释。

     3.6 版更變: 在已关闭的 ZipFile 上调用 *note extractall(): 1eff. 将
     引发 *note ValueError: 16d.。 在之前的版本中则将引发 *note
     RuntimeError: 3dc.。

     3.6.2 版更變: `path' 形参接受一个 *note path-like object: 472.。

 -- 成員函式: ZipFile.printdir ()

     将归档的目录表打印到 ‘sys.stdout’。

 -- 成員函式: ZipFile.setpassword (pwd)

     设置 `pwd' 为用于提取已加密文件的默认密码。

 -- 成員函式: ZipFile.read (name, pwd=None)

     返回归档中文件 `name' 的字节数据。 `name' 是归档中文件的名称，或是
     一个 *note ZipInfo: 6b1. 对象。 归档必须以读取或追加方式打开。
     `pwd' 为用于已加密文件的密码，并且如果指定该参数则它将覆盖通过
     *note setpassword(): 1f01. 设置的默认密码。 on a ZipFile that uses
     a compression method 在使用 *note ZIP_STORED: 1ef4. , *note
     ZIP_DEFLATED: 1ef5, *note ZIP_BZIP2: 1ef6. 或 *note ZIP_LZMA: 1ef7.
     以外的压缩方法的 ZipFile 上调用 *note read(): d81. 将引发 *note
     NotImplementedError: 704.。 如果相应的压缩模块不可用也会引发错误。

     3.6 版更變: 在已关闭的 ZipFile 上调用 *note read(): d81. 将引发
     *note ValueError: 16d.。 在之前的版本中则会引发 *note RuntimeError:
     3dc.。

 -- 成員函式: ZipFile.testzip ()

     读取归档中的所有文件并检查它们的 CRC 和文件头。 返回第一个已损坏文
     件的名称，在其他情况下则返回 ‘None’。

     3.6 版更變: 在已关闭的 ZipFile 上调用 *note testzip(): 1f02. 将引发
     *note ValueError: 16d.。 在之前的版本中则将引发 *note RuntimeError:
     3dc.。

 -- 成員函式: ZipFile.write (filename, arcname=None, compress_type=None,
          compresslevel=None)

     将名为 `filename' 的文件写入归档，给予的归档名为 `arcname' (默认情
     况下将与 `filename' 一致，但是不带驱动器盘符并会移除开头的路径分隔
     符)。 `compress_type' 如果给出，它将覆盖作为构造器 `compression' 形
     参对于新条目所给出的值。 类似地，`compresslevel' 如果给出也将覆盖构
     造器。 归档必须使用 ‘'w'’, ‘'x'’ 或 ‘'a'’ 模式打开。

          備註: 归档名称应当是基于归档根目录的相对路径，也就是说，它们不
          应以路径分隔符开头。

          備註: 如果 ‘arcname’ (或 ‘filename’，如果 ‘arcname’ 未给出) 包
          含一个空字节，则归档中该文件的名称将在空字节位置被截断。

          備註: 文件名开头有一个斜杠可能导致存档文件无法在 Windows 系统
          上的某些 zip 程序中打开。

     3.6 版更變: 在使用 ‘'r'’ 模式创建的 ZipFile 或已关闭的 ZipFile 上调
     用 *note write(): 705. 将引发 *note ValueError: 16d.。 在之前的版本
     中则会引发 *note RuntimeError: 3dc.。

 -- 成員函式: ZipFile.writestr (zinfo_or_arcname, data,
          compress_type=None, compresslevel=None)

     将一个文件写入归档。 内容为 `data'，它可以是一个 *note str: 205. 或
     *note bytes: 172. 的实例；如果是 *note str: 205.，则会先使用 UTF-8
     进行编码。 `zinfo_or_arcname' 可以是它在归档中将被给予的名称，或者
     是 *note ZipInfo: 6b1. 的实例。 如果它是一个实例，则至少必须给定文
     件名、日期和时间。 如果它是一个名称，则日期和时间会被设为当前日期和
     时间。 归档必须以 ‘'w'’, ‘'x'’ 或 ‘'a'’ 模式打开。

     如果给定了 `compress_type'，它将会覆盖作为新条目构造器的
     `compression' 形参或在 `zinfo_or_arcname' (如果是一个 *note
     ZipInfo: 6b1. 实例) 中所给出的值。 类似地，如果给定了
     `compresslevel'，它将会覆盖构造器。

          備註: 当传入一个 *note ZipInfo: 6b1. 实例作为
          `zinfo_or_arcname' 形参时，所使用的压缩方法将为在给定的 *note
          ZipInfo: 6b1. 实例的 `compress_type' 成员中指定的方法。 默认情
          况下，*note ZipInfo: 6b1. 构造器将将此成员设为 *note
          ZIP_STORED: 1ef4.。

     3.2 版更變: `compress_type' 参数。

     3.6 版更變: 在使用 ‘'r'’ 模式创建的 ZipFile 或已关闭的 ZipFile 上调
     用 *note writestr(): d83. 将引发 *note ValueError: 16d.。 在之前的
     版本中则会引发 *note RuntimeError: 3dc.。

以下数据属性也是可用的:

 -- 屬性: ZipFile.filename

     ZIP 文件的名称。

 -- 屬性: ZipFile.debug

     要使用的调试输出等级。 这可以设为从 ‘0’ (默认无输出) 到 ‘3’ (最多输
     出) 的值。 调试信息会被写入 ‘sys.stdout’。

 -- 屬性: ZipFile.comment

     关联到 ZIP 文件的 *note bytes: 172. 对象形式的说明。 如果将说明赋给
     以 ‘'w'’, ‘'x'’ 或 ‘'a'’ 模式创建的 *note ZipFile: 522. 实例，它的
     长度不应超过 65535 字节。 超过此长度的说明将被截断。


File: python.info,  Node: Path 对象,  Next: PyZipFile 对象,  Prev: ZipFile 对象,  Up: zipfile --- 使用ZIP存档

5.13.5.2 Path 对象
..................

 -- 類別: zipfile.Path (root, at='')

     根据 ‘root’ zipfile (它可以是一个 *note ZipFile: 522. 实例或适合传
     给 *note ZipFile: 522. 构造器的 ‘file’) 构造一个 Path 对象。

     ‘at’ 指定此 Path 在 zipfile 中的位置，例如 ’dir/file.txt’, ’dir/’ 或
     ’’。 默认为空字符串，即指定跟目录。

Path 对象会公开 *note pathlib.Path: 32f. 对象的下列特性:

Path 对象可以使用 ‘/’ 操作符进行遍历。

 -- 屬性: Path.name

     最终的路径组成部分。

 -- 成員函式: Path.open (mode='r', *, pwd, **)

     在当前路径上发起调用 *note ZipFile.open(): 6b3.。 允许通过支持的模
     式打开用于读取或写入文本或二进制数据: ’r’, ’w’, ’rb’, ’wb’。 当以文
     本模式打开时位置和关键字参数会被传给 *note io.TextIOWrapper: 6ea.，
     在其他情况下则会被忽略。 ‘pwd’ 是要传给 *note ZipFile.open(): 6b3.
     的 ‘pwd’ 形参。

     3.9 版更變: 增加了对以文本和二进制模式打开的支持。 现在默认为文本模
     式。

 -- 成員函式: Path.iterdir ()

     枚举当前目录的子目录。

 -- 成員函式: Path.is_dir ()

     如果当前上下文引用了一个目录则返回 ‘True’。

 -- 成員函式: Path.is_file ()

     如果当前上下文引用了一个文件则返回 ‘True’。

 -- 成員函式: Path.exists ()

     如果当前上下文引用了 zip 文件内的一个文件或目录则返回 ‘True’。

 -- 成員函式: Path.read_text (*, **)

     读取当前文件为 unicode 文本。 位置和关键字参数会被传递给 *note
     io.TextIOWrapper: 6ea. (‘buffer’ 除外，它将由上下文确定)。

 -- 成員函式: Path.read_bytes ()

     读取当前文件为字节串。


File: python.info,  Node: PyZipFile 对象,  Next: ZipInfo 对象,  Prev: Path 对象,  Up: zipfile --- 使用ZIP存档

5.13.5.3 PyZipFile 对象
.......................

*note PyZipFile: a00. 构造器接受与 *note ZipFile: 522. 构造器相同的形参
，以及一个额外的形参 `optimize'。

 -- 類別: zipfile.PyZipFile (file, mode='r', compression=ZIP_STORED,
          allowZip64=True, optimize=-1)

     3.2 版新加入: `optimize' 形参。

     3.4 版更變: 默认启用 ZIP64 扩展。

     实例在 *note ZipFile: 522. 对象所具有的方法以外还附加了一个方法:

      -- 成員函式: writepy (pathname, basename='', filterfunc=None)

          查找 ‘*.py’ 文件并将相应的文件添加到归档。

          如果 *note PyZipFile: a00. 的 `optimize' 形参未给定或为 ‘-1’，
          则相应的文件为 ‘*.pyc’ 文件，并在必要时进行编译。

          如果 *note PyZipFile: a00. 的 `optimize' 形参为 ‘0’, ‘1’ 或
          ‘2’，则限具有相应优化级别 (参见 *note compile(): 2e7.) 的文件
          会被添加到归档，并在必要时进行编译。

          如果 `pathname' 是文件，则文件名必须以 ‘.py’ 为后缀，并且只有
          (相应的 ‘*.pyc’) 文件会被添加到最高层级（不带路径信息）。 如果
          `pathname' 不是以 ‘.py’ 为后缀的文件，则将引发 *note
          RuntimeError: 3dc.。 如果它是目录，并且该目录不是一个包目录，
          则所有的 ‘*.pyc’ 文件会被添加到最高层级。 如果目录是一个包目录
          ，则所有的 ‘*.pyc’ 会被添加到包名所表示的文件路径下，并且如果
          有任何子目录为包目录，则会以排好的顺序递归地添加这些目录。

          `basename' 仅限在内部使用。

          如果给定 `filterfunc'，则它必须是一个接受单个字符串参数的函数
          。 在将其添加到归档之前它将被传入每个路径（包括每个单独的完整
          路径）。 如果 `filterfunc' 返回假值，则路径将不会被添加，而如
          果它是一个目录则其内容将被忽略。 例如，如果我们的测试文件全都
          位于 ‘test’ 目录或以字符串 ‘test_’ 打头，则我们可以使用一个
          `filterfunc' 来排除它们:

               >>> 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)

          *note writepy(): 9ff. 方法会产生带有这样一些文件名的归档:

               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

          3.4 版新加入: `filterfunc' 形参。

          3.6.2 版更變: `pathname' 形参接受一个 *note path-like object:
          472.。

          3.7 版更變: 递归排序目录条目。


File: python.info,  Node: ZipInfo 对象,  Next: 命令行界面<2>,  Prev: PyZipFile 对象,  Up: zipfile --- 使用ZIP存档

5.13.5.4 ZipInfo 对象
.....................

*note ZipInfo: 6b1. 类的实例会通过 *note getinfo(): 1ef1. 和 *note
ZipFile: 522. 对象的 *note infolist(): 1ef2. 方法返回。 每个对象将存储关
于 ZIP 归档的一个成员的信息。

有一个类方法可以为文件系统文件创建 *note ZipInfo: 6b1. 实例:

 -- 成員函式: classmethod ZipInfo.from_file (filename, arcname=None, *,
          strict_timestamps=True)

     为文件系统中的文件构造一个 *note ZipInfo: 6b1. 实例，并准备将其添加
     到一个 zip 文件。

     `filename' 应为文件系统中某个文件或目录的路径。

     如果指定了 `arcname'，它会被用作归档中的名称。 如果未指定
     `arcname'，则所用名称与 `filename' 相同，但将去除任何驱动器盘符和打
     头的路径分隔符。

     `strict_timestamps' 参数在设为 ‘False’ 时允许压缩早于 1980-01-01 的
     文件，代价时会将时间戳设为 1980-01-01。 类似的行为也会对晚于
     2107-12-31 的文件发生，时间戳也会被设为该上限值。

     3.6 版新加入.

     3.6.2 版更變: `filename' 形参接受一个 *note path-like object: 472.。

     3.8 版新加入: `strict_timestamps' 仅限关键字参数

实例具有下列方法和属性:

 -- 成員函式: ZipInfo.is_dir ()

     如果此归档成员是一个目录则返回 ‘True’。

     这会使用条目的名称：目录应当总是以 ‘/’ 结尾。

     3.6 版新加入.

 -- 屬性: ZipInfo.filename

     归档中的文件名称。

 -- 屬性: ZipInfo.date_time

     上次修改存档成员的时间和日期。这是六个值的元组：

     索引        值
                 
     -------------------------------------------
                 
     ‘0’         Year (>= 1980)
                 
                 
     ‘1’         月（1为基数）
                 
                 
     ‘2’         月份中的日期（1为基数）
                 
                 
     ‘3’         小时（0为基数）
                 
                 
     ‘4’         分钟（0为基数）
                 
                 
     ‘5’         秒（0为基数）
                 

          備註: ZIP文件格式不支持1980年以前的时间戳。

 -- 屬性: ZipInfo.compress_type

     归档成员的压缩类型。

 -- 屬性: ZipInfo.comment

     *note bytes: 172. 对象形式的单个归档成员的注释。

 -- 屬性: ZipInfo.extra

     扩展字段数据。 PKZIP Application Note(1) 包含一些保存于该 *note
     bytes: 172. 对象中的内部结构的注释。

 -- 屬性: ZipInfo.create_system

     创建 ZIP 归档所用的系统。

 -- 屬性: ZipInfo.create_version

     创建 ZIP 归档所用的 PKZIP 版本。

 -- 屬性: ZipInfo.extract_version

     需要用来提取归档的 PKZIP 版本。

 -- 屬性: ZipInfo.reserved

     必须为零。

 -- 屬性: ZipInfo.flag_bits

     ZIP 标志位。

 -- 屬性: ZipInfo.volume

     文件头的分卷号。

 -- 屬性: ZipInfo.internal_attr

     内部属性。

 -- 屬性: ZipInfo.external_attr

     外部文件属性。

 -- 屬性: ZipInfo.header_offset

     文件头的字节偏移量。

 -- 屬性: ZipInfo.CRC

     未压缩文件的 CRC-32。

 -- 屬性: ZipInfo.compress_size

     已压缩数据的大小。

 -- 屬性: ZipInfo.file_size

     未压缩文件的大小。

   ---------- Footnotes ----------

   (1) https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT


File: python.info,  Node: 命令行界面<2>,  Next: 解压缩的障碍,  Prev: ZipInfo 对象,  Up: zipfile --- 使用ZIP存档

5.13.5.5 命令行界面
...................

*note zipfile: 14b. 模块提供了简单的命令行接口用于与 ZIP 归档的交互。

如果你想要创建一个新的 ZIP 归档，请在 *note -c: 1f24. 选项后指定其名称然
后列出应当被包含的文件名:

     $ python -m zipfile -c monty.zip spam.txt eggs.txt

传入一个目录也是可接受的:

     $ python -m zipfile -c monty.zip life-of-brian_1979/

如果你想要将一个 ZIP 归档提取到指定的目录，请使用 *note -e: 1f25. 选项:

     $ python -m zipfile -e monty.zip target-dir/

要获取一个 ZIP 归档中的文件列表，请使用 *note -l: 1f26. 选项:

     $ python -m zipfile -l monty.zip

* Menu:

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


File: python.info,  Node: 命令行选项<2>,  Up: 命令行界面<2>

5.13.5.6 命令行选项
...................

 -- 程式選項: -l <zipfile>
 -- 程式選項: --list <zipfile>

     列出一个 zipfile 中的文件名。

 -- 程式選項: -c <zipfile> <source1> ... <sourceN>
 -- 程式選項: --create <zipfile> <source1> ... <sourceN>

     基于源文件创建 zipfile。

 -- 程式選項: -e <zipfile> <output_dir>
 -- 程式選項: --extract <zipfile> <output_dir>

     将 zipfile 提取到目标目录中。

 -- 程式選項: -t <zipfile>
 -- 程式選項: --test <zipfile>

     检测 zipfile 是否有效。


File: python.info,  Node: 解压缩的障碍,  Prev: 命令行界面<2>,  Up: zipfile --- 使用ZIP存档

5.13.5.7 解压缩的障碍
.....................

zipfile 模块的提取操作可能会由于下面列出的障碍而失败。

* Menu:

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


File: python.info,  Node: 由于文件本身,  Next: 文件系统限制,  Up: 解压缩的障碍

5.13.5.8 由于文件本身
.....................

解压缩可能由于不正确的密码 / CRC 校验和 / ZIP 格式或不受支持的压缩 / 解
密方法而失败。


File: python.info,  Node: 文件系统限制,  Next: 资源限制,  Prev: 由于文件本身,  Up: 解压缩的障碍

5.13.5.9 文件系统限制
.....................

超出特定文件系统上的限制可能会导致解压缩失败。 例如目录条目所允许的字符
、文件名的长度、路径名的长度、单个文件的大小以及文件的数量等等。


File: python.info,  Node: 资源限制,  Next: 中断,  Prev: 文件系统限制,  Up: 解压缩的障碍

5.13.5.10 资源限制
..................

缺乏内存或磁盘空间将会导致解压缩失败。 例如，作用于 zipfile 库的解压缩炸
弹 (即 ZIP bomb(1)) 就可能造成磁盘空间耗尽。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Zip_bomb


File: python.info,  Node: 中断,  Next: 提取的默认行为,  Prev: 资源限制,  Up: 解压缩的障碍

5.13.5.11 中断
..............

在解压缩期间中断执行，例如按下 ctrl-C 或杀死解压缩进程可能会导致归档文件
的解压缩不完整。


File: python.info,  Node: 提取的默认行为,  Prev: 中断,  Up: 解压缩的障碍

5.13.5.12 提取的默认行为
........................

不了解提取的默认行为可能导致不符合期望的解压缩结果。 例如，当提取相同归
档两次时，它会不经询问地覆盖文件。


File: python.info,  Node: tarfile --- 读写tar归档文件,  Prev: zipfile --- 使用ZIP存档,  Up: 資料壓縮與保存

5.13.6 ‘tarfile’ — 读写tar归档文件
----------------------------------

`源代码:' Lib/tarfile.py(1)

__________________________________________________________________

*note tarfile: 101. 模块可以用来读写 tar 归档，包括使用 gzip, bz2 和
lzma 压缩的归档。 请使用 *note zipfile: 14b. 模块来读写 ‘.zip’ 文件，或
者使用 *note shutil: c67. 的高层级函数。

一些事实和数字:

   * 读写 *note gzip: 8b, *note bz2: 13. 和 *note lzma: ad. 解压的归档要
     求相应的模块可用。

   * 支持读取 / 写入 POSIX.1-1988 (ustar) 格式。

   * 对 GNU tar 格式的读/写支持，包括 `longname' 和 `longlink' 扩展，对
     所有种类 `sparse' 扩展的只读支持，包括 sparse 文件的恢复。

   * 对 POSIX.1-2001 (pax) 格式的读/写支持。

   * 处理目录、正常文件、硬链接、符号链接、fifo 管道、字符设备和块设备，
     并且能够获取和恢复文件信息例如时间戳、访问权限和所有者等。

3.3 版更變: 添加了对 *note lzma: ad. 压缩的支持。

 -- 函式: tarfile.open (name=None, mode='r', fileobj=None,
          bufsize=10240, **kwargs)

     针对路径名 `name' 返回 *note TarFile: c5d. 对象。 有关 *note
     TarFile: c5d. 对象以及所允许的关键字参数的详细信息请参阅 *note
     TarFile 对象: 1f37.。

     `mode' 必须是 ‘'filemode[:compression]'’ 形式的字符串，其默认值为
     ‘'r'’。 以下是模式组合的完整列表:

     模式                   动作
                            
     -------------------------------------------------------------------------
                            
     ‘'r' or 'r:*'’         打开和读取使用透明压缩（推荐）。
                            
                            
     ‘'r:'’                 打开和读取不使用压缩。
                            
                            
     ‘'r:gz'’               打开和读取使用gzip 压缩。
                            
                            
     ‘'r:bz2'’              打开和读取使用bzip2 压缩。
                            
                            
     ‘'r:xz'’               打开和读取使用lzma 压缩。
                            
                            
     ‘'x'’ 或 ‘'x:'’        创建tarfile不进行压缩。如果文件已经存在，则抛出
                            *note FileExistsError: a39. 异常。
                            
                            
     ‘'x:gz'’               使用gzip压缩创建tarfile。如果文件已经存在，则抛
                            出 *note FileExistsError: a39. 异常。
                            
                            
     ‘'x:bz2'’              使用bzip2 压缩创建tarfile。如果文件已经存在，则
                            抛出 *note FileExistsError: a39. 异常。
                            
                            
     ‘'x:xz'’               使用lzma 压缩创建tarfile。如果文件已经存在，则
                            抛出 *note FileExistsError: a39. 异常。
                            
                            
     ‘'a' or 'a:'’          打开以便在没有压缩的情况下追加。如果文件不存在
                            ，则创建该文件。
                            
                            
     ‘'w' or 'w:'’          打开用于未压缩的写入。
                            
                            
     ‘'w:gz'’               打开用于 gzip 压缩的写入。
                            
                            
     ‘'w:bz2'’              打开用于 bzip2 压缩的写入。
                            
                            
     ‘'w:xz'’               打开用于 lzma 压缩的写入。
                            

     请注意 ‘'a:gz'’, ‘'a:bz2'’ 或 ‘'a:xz'’ 是不可能的组合。 如果 `mode'
     不适用于打开特定（压缩的）文件用于读取，则会引发 *note ReadError:
     f71.。 请使用 `mode' ‘'r'’ 来避免这种情况。 如果某种压缩方法不受支
     持，则会引发 *note CompressionError: 1f38.。

     如果指定了 `fileobj'，它会被用作对应于 `name' 的以二进制模式打开的
     *note file object: c14. 的替代。 它会被设定为处在位置 0。

     对于 ‘'w:gz'’, ‘'r:gz'’, ‘'w:bz2'’, ‘'r:bz2'’, ‘'x:gz'’, ‘'x:bz2'’
     等模式，*note tarfile.open(): 855. 接受关键字参数 `compresslevel'
     (默认值为 ‘9’) 来指定文件的压缩等级。

     对于 ‘'w:xz'’ 和 ‘'x:xz'’ 模式，*note tarfile.open(): 855. 接受关键
     字参数 `preset' 来指定文件的压缩等级。

     针对特殊的目的，还存在第二种 `mode' 格式:
     ‘'filemode|[compression]'’。 *note tarfile.open(): 855. 将返回一个
     将其数据作为数据块流来处理的 *note TarFile: c5d. 对象。 对此文件将
     不能执行随机查找。 如果给定了 `fileobj'，它可以是任何具有 ‘read()’
     或 ‘write()’ 方法 (由 `mode' 确定) 的对象。 `bufsize' 指定块大小，
     默认值为 ‘20 * 512’ 字节。 可与此格式组合使用的有 ‘sys.stdin’, 套接
     字 *note file object: c14. 或磁带设备等。 但是，对于这样的 *note
     TarFile: c5d. 对象存在不允许随机访问的限制，参见 *note 示例: 1f39.。
     目前可用的模式如下:

     模式              动作
                       
     -------------------------------------------------------------------
                       
     ‘'r|*'’           打开 tar 块的 `流' 以进行透明压缩读取。
                       
                       
     ‘'r|'’            打开一个未压缩的 tar 块的 `stream' 用于读取。
                       
                       
     ‘'r|gz'’          打开一个 gzip 压缩的 `stream' 用于读取。
                       
                       
     ‘'r|bz2'’         打开一个 bzip2 压缩的 `stream' 用于读取。
                       
                       
     ‘'r|xz'’          打开一个 lzma 压缩 `stream' 用于读取。
                       
                       
     ‘'w|'’            打开一个未压缩的 `stream' 用于写入。
                       
                       
     ‘'w|gz'’          打开一个 gzip 压缩的 `stream' 用于写入。
                       
                       
     ‘'w|bz2'’         打开一个 bzip2 压缩的 `stream' 用于写入。
                       
                       
     ‘'w|xz'’          打开一个 lzma 压缩的 `stream' 用于写入。
                       

     3.5 版更變: 添加了 ‘'x'’ (仅创建) 模式。

     3.6 版更變: `name' 形参接受一个 *note path-like object: 472.。

 -- 類別: tarfile.TarFile

     用于读取和写入 tar 归档的类。 请不要直接使用这个类：而要使用 *note
     tarfile.open(): 855.。 参见 *note TarFile 对象: 1f37.。

 -- 函式: tarfile.is_tarfile (name)

     如果 `name' 是一个 *note tarfile: 101. 能读取的 tar 归档文件则返回
     *note True: 593.。 `name' 可以为 *note str: 205.，文件或文件类对象
     。

     3.9 版更變: 支持文件或类文件对象。

*note tarfile: 101. 模块定义了以下异常:

 -- 例外: tarfile.TarError

     所有 *note tarfile: 101. 异常的基类。

 -- 例外: tarfile.ReadError

     当一个不能被 *note tarfile: 101. 模块处理或者因某种原因而无效的 tar
     归档被打开时将被引发。

 -- 例外: tarfile.CompressionError

     当一个压缩方法不受支持或者当数据无法被正确解码时将被引发。

 -- 例外: tarfile.StreamError

     当达到流式 *note TarFile: c5d. 对象的典型限制时将被引发。

 -- 例外: tarfile.ExtractError

     当使用 *note TarFile.extract(): 857. 时针对 `non-fatal' 所引发的异
     常，但是仅限 ‘TarFile.errorlevel’‘== 2’。

 -- 例外: tarfile.HeaderError

     如果获取的缓冲区无效则会由 *note TarInfo.frombuf(): 1f3e. 引发的异
     常。

以下常量在模块层级上可用:

 -- Data: tarfile.ENCODING

     默认的字符编码格式：在 Windows 上为 ‘'utf-8'’，其他系统上则为 *note
     sys.getfilesystemencoding(): 5ef. 所返回的值。

以下常量各自定义了一个 *note tarfile: 101. 模块能够创建的 tar 归档格式。
相关细节请参阅 *note 受支持的 tar 格式: 1f40. 小节。

 -- Data: tarfile.USTAR_FORMAT

     POSIX.1-1988 (ustar) 格式。

 -- Data: tarfile.GNU_FORMAT

     GNU tar 格式。

 -- Data: tarfile.PAX_FORMAT

     POSIX.1-2001 (pax) 格式。

 -- Data: tarfile.DEFAULT_FORMAT

     用于创建归档的默认格式。 目前为 *note PAX_FORMAT: 1f43.。

     3.8 版更變: 新归档的默认格式已更改为 *note PAX_FORMAT: 1f43. 而不再
     是 *note GNU_FORMAT: 1f42.。

也參考
......

模块 *note zipfile: 14b.

     *note zipfile: 14b. 标准模块的文档。

*note 归档操作: c67.

     标准 *note shutil: e9. 模块所提供的高层级归档工具的文档。

GNU tar manual, Basic Tar Format(2)

     针对 tar 归档文件的文档，包含 GNU tar 扩展。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/tarfile.py

   (2) https://www.gnu.org/software/tar/manual/html_node/Standard.html


File: python.info,  Node: TarFile 对象,  Next: TarInfo 对象,  Up: tarfile --- 读写tar归档文件

5.13.6.1 TarFile 对象
.....................

*note TarFile: c5d. 对象提供了一个 tar 归档的接口。 一个 tar 归档就是数
据块的序列。 一个归档成员（被保存文件）是由一个标头块加多个数据块组成的
。 一个文件可以在一个 tar 归档中多次被保存。 每个归档成员都由一个 *note
TarInfo: c5e. 对象来代表，详情参见 *note TarInfo 对象: 1f46.。

*note TarFile: c5d. 对象可在 *note with: 7da. 语句中作为上下文管理器使用
。 当语句块结束时它将自动被关闭。 请注意在发生异常事件时被打开用于写入的
归档将不会被终结；只有内部使用的文件对象将被关闭。 相关用例请参见 *note
示例: 1f39.。

3.2 版新加入: 添加了对上下文管理器协议的支持。

 -- 類別: 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=0)

     下列所有参数都是可选项并且也可作为实例属性来访问。

     `name' 是归档的路径名称。 `name' 可以是一个 *note path-like object:
     472.。 如果给定了 `fileobj' 则它可以被省略。 在此情况下，如果对象的
     ‘name’ 属性存在则它会被使用。

     `mode' 可以为 ‘'r'’ 表示从现有归档读取，‘'a'’ 表示将数据追加到现有
     文件，‘'w'’ 表示创建新文件覆盖现有文件，或者 ‘'x'’ 表示仅在文件不存
     在时创建新文件。

     如果给定了 `fileobj'，它会被用于读取或写入数据。 如果可以被确定，则
     `mode' 会被 `fileobj' 的模式所覆盖。 `fileobj' 的使用将从位置 0 开
     始。

          備註: 当 *note TarFile: c5d. 被关闭时，`fileobj' 不会被关闭。

     `format' 控制用于写入的归档格式。 它必须为在模块层级定义的常量
     *note USTAR_FORMAT: 1f41, *note GNU_FORMAT: 1f42. 或 *note
     PAX_FORMAT: 1f43. 中的一个。 当读取时，格式将被自动检测，即使单个归
     档中存在不同的格式。

     `tarinfo' 参数可以被用来将默认的 *note TarInfo: c5e. 类替换为另一个
     。

     如果 `dereference' 为 *note False: 48e.，则会将符号链接和硬链接添加
     到归档中。 如果为 *note True: 593.，则会将目标文件的内容添加到归档
     中。 在不支持符号链接的系统上参数将不起作用。

     如果 `ignore_zeros' 为 *note False: 48e.，则会将空的数据块当作归档
     的末尾来处理。 如果为 *note True: 593.，则会跳过空的（和无效的）数
     据块并尝试获取尽可能多的成员。 此参数仅适用于读取拼接的或损坏的归档
     。

     `debug' 可设为从 ‘0’ (无调试消息) 到 ‘3’ (全部调试消息)。 消息会被
     写入到 ‘sys.stderr’。

     如果 `errorlevel' 为 ‘0’，则当使用 *note TarFile.extract(): 857. 时
     会忽略所有错误。 无论何种情况，当启用调试时它们都将被显示为调试输出
     的错误消息。 如果为 ‘1’，则所有 `fatal' 错误会被作为 *note OSError:
     304. 异常被引发。 如果为 ‘2’，则所有 `non-fatal' 错误也会被作为
     *note TarError: 1f3a. 异常被引发。

     `encoding' 和 `errors' 参数定义了读取或写入归档所使用的字符编码格式
     以及要如何处理转换错误。 默认设置将适用于大多数用户。 要深入了解详
     情可参阅 *note Unicode 问题: 1f47. 小节。

     可选的 `pax_headers' 参数是字符串的字典，如果 `format' 为 *note
     PAX_FORMAT: 1f43. 它将被作为 pax 全局标头被添加。

     3.2 版更變: 使用 ‘'surrogateescape'’ 作为 `errors' 参数的默认值。

     3.5 版更變: 添加了 ‘'x'’ (仅创建) 模式。

     3.6 版更變: `name' 形参接受一个 *note path-like object: 472.。

 -- 成員函式: classmethod TarFile.open (...)

     作为替代的构造器。 *note tarfile.open(): 855. 函数实际上是这个类方
     法的快捷方式。

 -- 成員函式: TarFile.getmember (name)

     返回成员 `name' 的 *note TarInfo: c5e. 对象。 如果 `name' 在归档中
     找不到，则会引发 *note KeyError: 3e9.。

          備註: 如果一个成员在归档中出现超过一次，它的最后一次出现会被视
          为是最新的版本。

 -- 成員函式: TarFile.getmembers ()

     以 *note TarInfo: c5e. 对象列表的形式返回归档的成员。 列表的顺序与
     归档中成员的顺序一致。

 -- 成員函式: TarFile.getnames ()

     以名称列表的形式返回成员。 它的顺序与 *note getmembers(): 859. 所返
     回列表的顺序一致。

 -- 成員函式: TarFile.list (verbose=True, *, members=None)

     将内容清单打印到 ‘sys.stdout’。 如果 `verbose' 为 *note False:
     48e.，则将只打印成员名称。 如果为 *note True: 593.，则输出将类似于
     ‘ls -l’ 的输出效果。 如果给定了可选的 `members'，它必须为 *note
     getmembers(): 859. 所返回的列表的一个子集。

     3.5 版更變: 添加了 `members' 形参。

 -- 成員函式: TarFile.next ()

     当 *note TarFile: c5d. 被打开用于读取时，以 *note TarInfo: c5e. 对
     象的形式返回归档的下一个成员。 如果不再有可用对象则返回 *note None:
     203.。

 -- 成員函式: TarFile.extractall (path=".", members=None, *,
          numeric_owner=False)

     将归档中的所有成员提取到当前工作目录或 `path' 目录。 如果给定了可选
     的 `members'，则它必须为 *note getmembers(): 859. 所返回的列表的一
     个子集。 字典信息例如所有者、修改时间和权限会在所有成员提取完毕后被
     设置。 这样做是为了避免两个问题：目录的修改时间会在每当在其中创建文
     件时被重置。 并且如果目录的权限不允许写入，提取文件到目录的操作将失
     败。

     如果 `numeric_owner' 为 *note True: 593.，则将使用来自 tarfile 的
     uid 和 gid 数值来设置被提取文件的所有者/用户组。 在其他情况下，则会
     使用来自 tarfile 的名称值。

          警告: 绝不要未经预先检验就从不可靠的源中提取归档文件。 这样有
          可能在 `path' 之外创建文件，例如某些成员具有以 ‘"/"’ 开始的绝
          对路径文件名或带有两个点号 ‘".."’ 的文件名。

     3.5 版更變: 添加了 `numeric_owner' 形参。

     3.6 版更變: `path' 形参接受一个 *note path-like object: 472.。

 -- 成員函式: TarFile.extract (member, path="", set_attrs=True, *,
          numeric_owner=False)

     从归档中提取出一个成员放入当前工作目录，将使用其完整名称。 成员的文
     件信息会尽可能精确地被提取。 `member' 可以是一个文件名或 *note
     TarInfo: c5e. 对象。 你可以使用 `path' 指定一个不同的目录。 `path'
     可以是一个 *note path-like object: 472.。 将会设置文件属性 (owner,
     mtime, mode) 除非 `set_attrs' 为假值。

     如果 `numeric_owner' 为 *note True: 593.，则将使用来自 tarfile 的
     uid 和 gid 数值来设置被提取文件的所有者/用户组。 在其他情况下，则会
     使用来自 tarfile 的名称值。

          備註: *note extract(): 857. 方法不会处理某些提取问题。 在大多
          数情况下你应当考虑使用 *note extractall(): 856. 方法。

          警告: 查看 *note extractall(): 856. 的警告信息。

     3.2 版更變: 添加了 `set_attrs' 形参。

     3.5 版更變: 添加了 `numeric_owner' 形参。

     3.6 版更變: `path' 形参接受一个 *note path-like object: 472.。

 -- 成員函式: TarFile.extractfile (member)

     将归档中的一个成员提取为文件对象。 `member' 可以是一个文件名或
     *note TarInfo: c5e. 对象。 如果 `member' 是一个常规文件或链接，则会
     返回一个 *note io.BufferedReader: c5b. 对象。 对于所有其他现有成员
     ，则都将返回 *note None: 203.。 如果 `member' 未在归档中出现，则会
     引发 *note KeyError: 3e9.。

     3.3 版更變: 返回一个 *note io.BufferedReader: c5b. 对象。

 -- 成員函式: TarFile.add (name, arcname=None, recursive=True, *,
          filter=None)

     将文件 `name' 添加到归档。 `name' 可以为任意类型的文件（目录、
     fifo、符号链接等等）。 如果给出 `arcname' 则它将为归档中的文件指定
     一个替代名称。 默认情况下会递归地添加目录。 这可以通过将
     `recursive' 设为 *note False: 48e. 来避免。 递归操作会按排序顺序添
     加条目。 如果给定了 `filter'，它应当为一个接受 *note TarInfo: c5e.
     对象并返回已修改 *note TarInfo: c5e. 对象的函数。 如果它返回 *note
     None: 203. 则 *note TarInfo: c5e. 对象将从归档中被排除。 具体示例参
     见 *note 示例: 1f39.。

     3.2 版更變: 添加了 `filter' 形参。

     3.7 版更變: 递归操作按排序顺序添加条目。

 -- 成員函式: TarFile.addfile (tarinfo, fileobj=None)

     将 *note TarInfo: c5e. 对象 `tarinfo' 添加到归档。 如果给定了
     `fileobj'，它应当是一个 *note binary file: 1e01.，并会从中读取
     ‘tarinfo.size’ 个字节添加到归档。 你可以直接创建 *note TarInfo:
     c5e. 对象，或是使用 *note gettarinfo(): 1f4e. 来创建。

 -- 成員函式: TarFile.gettarinfo (name=None, arcname=None, fileobj=None)

     基于 *note os.stat(): 321. 的结果或者现有文件的相同数据创建一个
     *note TarInfo: c5e.。 文件或者是命名为 `name'，或者是使用文件描述符
     指定为一个 *note file object: c14. `fileobj'。 `name' 可以是一个
     *note path-like object: 472.。 如果给定了 `arcname'，则它将为归档中
     的文件指定一个替代名称，在其他情况下，名称将从 `fileobj' 的 *note
     name: 1f4f. 属性或 `name' 参数获取。 名称应当是一个文本字符串。

     你可以在使用 *note addfile(): 1f4d. 添加 *note TarInfo: c5e. 的某些
     属性之前修改它们。 如果文件对象不是从文件开头进行定位的普通文件对象
     ，*note size: 1f50. 之类的属性就可能需要修改。 例如 *note GzipFile:
     206. 之类的文件就属于这种情况。 *note name: 1f51. 也可以被修改，在
     这种情况下 `arcname' 可以是一个占位字符串。

     3.6 版更變: `name' 形参接受一个 *note path-like object: 472.。

 -- 成員函式: TarFile.close ()

     关闭 *note TarFile: c5d.。 在写入模式下，会向归档添加两个表示结束的
     零数据块。

 -- 屬性: TarFile.pax_headers

     一个包含 pax 全局标头的键值对的字典。


File: python.info,  Node: TarInfo 对象,  Next: 命令行界面<3>,  Prev: TarFile 对象,  Up: tarfile --- 读写tar归档文件

5.13.6.2 TarInfo 对象
.....................

*note TarInfo: c5e. 对象代表 *note TarFile: c5d. 中的一个文件。 除了会存
储所有必要的文件属性（例如文件类型、大小、时间、权限、所有者等），它还提
供了一些确定文件类型的有用方法。 此对象 `并不' 包含文件数据本身。

*note TarInfo: c5e. 对象可通过 *note TarFile: c5d. 的方法 ‘getmember()’,
‘getmembers()’ 和 ‘gettarinfo()’ 返回。

 -- 類別: tarfile.TarInfo (name="")

     创建一个 *note TarInfo: c5e. 对象。

 -- 成員函式: classmethod TarInfo.frombuf (buf, encoding, errors)

     基于字符串缓冲区 `buf' 创建并返回一个 *note TarInfo: c5e. 对象。

     如果缓冲区无效则会引发 *note HeaderError: 1f3d.。

 -- 成員函式: classmethod TarInfo.fromtarfile (tarfile)

     从 *note TarFile: c5d. 对象 `tarfile' 读取下一个成员并将其作为
     *note TarInfo: c5e. 对象返回。

 -- 成員函式: TarInfo.tobuf (format=DEFAULT_FORMAT, encoding=ENCODING,
          errors='surrogateescape')

     基于 *note TarInfo: c5e. 对象创建一个字符串缓冲区。 有关参数的信息
     请参见 *note TarFile: c5d. 类的构造器。

     3.2 版更變: 使用 ‘'surrogateescape'’ 作为 `errors' 参数的默认值。

‘TarInfo’ 对象具有以下公有数据属性:

 -- 屬性: TarInfo.name

     归档成员的名称。

 -- 屬性: TarInfo.size

     以字节表示的大小。

 -- 屬性: TarInfo.mtime

     上次修改的时间。

 -- 屬性: TarInfo.mode

     权限位。

 -- 屬性: TarInfo.type

     文件类型。 `type' 通常为以下常量之一: ‘REGTYPE’, ‘AREGTYPE’,
     ‘LNKTYPE’, ‘SYMTYPE’, ‘DIRTYPE’, ‘FIFOTYPE’, ‘CONTTYPE’, ‘CHRTYPE’,
     ‘BLKTYPE’, ‘GNUTYPE_SPARSE’。 要更方便地确定一个 *note TarInfo:
     c5e. 对象的类型，请使用下述的 ‘is*()’ 方法。

 -- 屬性: TarInfo.linkname

     目标文件名的名称，该属性仅在类型为 ‘LNKTYPE’ 和 ‘SYMTYPE’ 的 *note
     TarInfo: c5e. 对象中存在。

 -- 屬性: TarInfo.uid

     最初保存该成员的用户的用户 ID。

 -- 屬性: TarInfo.gid

     最初保存该成员的用户的分组 ID。

 -- 屬性: TarInfo.uname

     用户名。

 -- 屬性: TarInfo.gname

     分组名。

 -- 屬性: TarInfo.pax_headers

     一个包含所关联的 pax 扩展标头的键值对的字典。

*note TarInfo: c5e. 对象还提供了一些便捷查询方法:

 -- 成員函式: TarInfo.isfile ()

     如果 ‘Tarinfo’ 对象为普通文件则返回 *note True: 593.。

 -- 成員函式: TarInfo.isreg ()

     与 *note isfile(): 1f60. 相同。

 -- 成員函式: TarInfo.isdir ()

     如果为目录则返回 *note True: 593.。

 -- 成員函式: TarInfo.issym ()

     如果为符号链接则返回 *note True: 593.。

 -- 成員函式: TarInfo.islnk ()

     如果为硬链接则返回 *note True: 593.。

 -- 成員函式: TarInfo.ischr ()

     如果为字符设备则返回 *note True: 593.。

 -- 成員函式: TarInfo.isblk ()

     如果为块设备则返回 *note True: 593.。

 -- 成員函式: TarInfo.isfifo ()

     如果为 FIFO 则返回 *note True: 593.。.

 -- 成員函式: TarInfo.isdev ()

     如果为字符设备、块设备或 FIFO 之一则返回 *note True: 593.。


File: python.info,  Node: 命令行界面<3>,  Next: 示例<12>,  Prev: TarInfo 对象,  Up: tarfile --- 读写tar归档文件

5.13.6.3 命令行界面
...................

3.4 版新加入.

*note tarfile: 101. 模块提供了简单的命令行接口以便与 tar 归档进行交互。

如果你想要创建一个新的 tar 归档，请在 *note -c: 1f6a. 选项后指定其名称然
后列出应当被包含的文件名:

     $ python -m tarfile -c monty.tar  spam.txt eggs.txt

传入一个字典也是可接受的:

     $ python -m tarfile -c monty.tar life-of-brian_1979/

如果你想要将一个 tar 归档提取到指定的目录，请使用 *note -e: 1f6b. 选项:

     $ python -m tarfile -e monty.tar

你也可以通过传入目录名称将一个 tar 归档提取到不同的目录:

     $ python -m tarfile -e monty.tar  other-dir/

要获取一个 tar 归档中文件的列表，请使用 *note -l: 1f6c. 选项:

     $ python -m tarfile -l monty.tar

* Menu:

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


File: python.info,  Node: 命令行选项<3>,  Up: 命令行界面<3>

5.13.6.4 命令行选项
...................

 -- 程式選項: -l <tarfile>
 -- 程式選項: --list <tarfile>

     列出一个 tarfile 中的文件名。

 -- 程式選項: -c <tarfile> <source1> ... <sourceN>
 -- 程式選項: --create <tarfile> <source1> ... <sourceN>

     基于源文件创建 tarfile。

 -- 程式選項: -e <tarfile> [<output_dir>]
 -- 程式選項: --extract <tarfile> [<output_dir>]

     如果未指定 `output_dir' 则会将 tarfile 提取到当前目录。

 -- 程式選項: -t <tarfile>
 -- 程式選項: --test <tarfile>

     检测 tarfile 是否有效。

 -- 程式選項: -v, --verbose

     更详细地输出结果。


File: python.info,  Node: 示例<12>,  Next: 受支持的 tar 格式,  Prev: 命令行界面<3>,  Up: tarfile --- 读写tar归档文件

5.13.6.5 示例
.............

如何将整个 tar 归档提取到当前工作目录:

     import tarfile
     tar = tarfile.open("sample.tar.gz")
     tar.extractall()
     tar.close()

如何通过 *note TarFile.extractall(): 856. 使用生成器函数而非列表来提取一
个 tar 归档的子集:

     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()

如何基于一个文件名列表创建未压缩的 tar 归档:

     import tarfile
     tar = tarfile.open("sample.tar", "w")
     for name in ["foo", "bar", "quux"]:
         tar.add(name)
     tar.close()

使用 *note with: 7da. 语句的同一个示例:

     import tarfile
     with tarfile.open("sample.tar", "w") as tar:
         for name in ["foo", "bar", "quux"]:
             tar.add(name)

如何读取一个 gzip 压缩的 tar 归档并显示一些成员信息:

     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()

如何创建一个归档并使用 *note TarFile.add(): 57a. 中的 `filter' 形参来重
置用户信息:

     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()


File: python.info,  Node: 受支持的 tar 格式,  Next: Unicode 问题,  Prev: 示例<12>,  Up: tarfile --- 读写tar归档文件

5.13.6.6 受支持的 tar 格式
..........................

通过 *note tarfile: 101. 模块可以创建三种 tar 格式:

   * The POSIX.1-1988 ustar 格式 (*note USTAR_FORMAT: 1f41.)。 它支持最
     多 256 个字符的文件名长度和最多 100 个字符的链接名长度。 文件大小上
     限为 8 GiB。 这是一种老旧但广受支持的格式。

   * GNU tar 格式 (*note GNU_FORMAT: 1f42.)。 它支持长文件名和链接名、大
     于 8 GiB 的文件以及稀疏文件。 它是 GNU/Linux 系统上的事实标准。
     *note tarfile: 101. 完全支持针对长名称的 GNU tar 扩展，稀疏文件支持
     则限制为只读。

   * POSIX.1-2001 pax 格式 (*note PAX_FORMAT: 1f43.)。 它是几乎无限制的
     最灵活格式。 它支持长文件名和链接名，大文件以及使用便捷方式存储路径
     名。 现代的 tar 实现，包括 GNU tar, bsdtar/libarchive 和 star，完全
     支持扩展 `pax' 特性；某些老旧或不维护的库可能不受支持，但应当会将
     `pax' 归档视为广受支持的 `ustar' 格式。 这是目前新建归档的默认格式
     。

     它扩展了现有的 `ustar' 格式，包括用于无法以其他方式存储的附加标头。
     存在两种形式的 pax 标头：扩展标头只影响后续的文件标头，全局标头则适
     用于完整归档并会影响所有后续的文件。 为了便于移植，在 pax 标头中的
     所有数据均以 `UTF-8' 编码。

还有一些 tar 格式的其他变种，它们可以被读取但不能被创建:

   * 古老的 V7 格式。 这是来自 Unix 第七版的第一个 tar 格式，它只存储常
     规文件和目录。 名称长度不能超过 100 个字符，并且没有用户/分组名信息
     。 某些归档在带有非 ASCII 字符字段的情况下会产生计算错误的标头校验
     和。

   * SunOS tar 扩展格式。 此格式是 POSIX.1-2001 pax 格式的一个变种，但并
     不保持兼容。


File: python.info,  Node: Unicode 问题,  Prev: 受支持的 tar 格式,  Up: tarfile --- 读写tar归档文件

5.13.6.7 Unicode 问题
.....................

最初 tar 格式被设计用来在磁带机上生成备份，主要关注于保存文件系统信息。
现在 tar 归档通常用于文件分发和在网络上交换归档。 最初格式（它是所有其他
格式的基础）的一个问题是它没有支持不同字符编码格式的概念。 例如，一个在
`UTF-8' 系统上创建的普通 tar 归档如果包含非 `ASCII' 字符则将无法在
`Latin-1' 系统上被正确读取。 文本元数据（例如文件名，链接名，用户/分组名
）将变为损坏状态。 不幸的是，没有什么办法能够自动检测一个归档的编码格式
。 pax 格式被设计用来解决这个问题。 它使用通用字符编码格式 `UTF-8' 来存
储非 ASCII 元数据。

在 *note tarfile: 101. 中字符转换的细节由 *note TarFile: c5d. 类的
`encoding' 和 `errors' 关键字参数控制。

`encoding' 定义了用于归档中元数据的字符编码格式。 默认值为 *note
sys.getfilesystemencoding(): 5ef. 或是回退选项 ‘'ascii'’。 根据归档是被
读取还是被写入，元数据必须被解码或编码。 如果没有正确设置 `encoding'，转
换可能会失败。

`errors' 参数定义了不能被转换的字符将如何处理。 可能的取值在 *note
错误处理方案: 1493. 小节列出。 默认方案为 ‘'surrogateescape'’，它也被
Python 用于文件系统调用，参见 *note 文件名，命令行参数，以及环境变量。:
1f77.。

对于 *note PAX_FORMAT: 1f43. 归档（默认格式），`encoding' 通常是不必要的
，因为所有元数据都使用 `UTF-8' 来存储。 `encoding' 仅在解码二进制 pax 标
头或存储带有替代字符的字符串等少数场景下会被使用。


File: python.info,  Node: 檔案格式,  Next: 加密服务,  Prev: 資料壓縮與保存,  Up: Python 標準函式庫 Standard Library

5.14 檔案格式
=============

本章中描述的模块解析各种不是标记语言且与电子邮件无关的杂项文件格式。

* Menu:

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


File: python.info,  Node: csv --- CSV 文件读写,  Next: configparser --- 配置文件解析器,  Up: 檔案格式

5.14.1 ‘csv’ — CSV 文件读写
---------------------------

`源代码：' Lib/csv.py(1)

__________________________________________________________________

CSV (Comma Separated Values) 格式是电子表格和数据库中最常见的输入、输出
文件格式。在 RFC 4180(2) 规范推出的很多年前，CSV 格式就已经被开始使用了
，由于当时并没有合理的标准，不同应用程序读写的数据会存在细微的差别。这种
差别让处理多个来源的 CSV 文件变得困难。但尽管分隔符会变化，此类文件的大
致格式是相似的，所以编写一个单独的模块以高效处理此类数据，将程序员从读写
数据的繁琐细节中解放出来是有可能的。

*note csv: 29. 模块实现了 CSV 格式表单数据的读写。其提供了诸如“以兼容
Excel 的方式输出数据文件”或“读取 Excel 程序输出的数据文件”的功能，程序员
无需知道 Excel 所采用 CSV 格式的细节。此模块同样可以用于定义其他应用程序
可用的 CSV 格式或定义特定需求的 CSV 格式。

*note csv: 29. 模块中的 *note reader: 101a. 类和 *note writer: ec0. 类可
用于读写序列化的数据。也可使用 *note DictReader: 2ee. 类和 *note
DictWriter: c4b. 类以字典的形式读写数据。

也參考
......

该实现在“Python 增强提议” - PEP ‘305’ (CSV 文件 API) 中被提出

     《Python 增强提议》提出了对 Python 的这一补充。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/csv.py

   (2) https://tools.ietf.org/html/rfc4180.html


File: python.info,  Node: 模块内容<3>,  Next: 变种与格式参数,  Up: csv --- CSV 文件读写

5.14.1.1 模块内容
.................

*note csv: 29. 模块定义了以下函数：

 -- 函式: csv.reader (csvfile, dialect='excel', **fmtparams)

     返回一个 reader 对象，该对象将逐行遍历 `csvfile'。`csvfile' 可以是
     任何对象，只要这个对象支持 *note iterator: 1171. 协议并在每次调用
     ‘__next__()’ 方法时都返回字符串，*note 文件对象: c14. 和列表对象均
     适用。如果 `csvfile' 是文件对象，则打开它时应使用 ‘newline=''’。
     (1) 可选参数 `dialect' 是用于不同的 CSV 变种的特定参数组。它可以是
     *note Dialect: f6c. 类的子类的实例，也可以是 *note list_dialects():
     1f7f. 函数返回的字符串之一。另一个可选关键字参数 `fmtparams' 可以覆
     写当前变种格式中的单个格式设置。有关变种和格式设置参数的完整详细信
     息，请参见 *note 变种与格式参数: 1f80. 部分。

     csv 文件的每一行都读取为一个由字符串组成的列表。除非指定了
     ‘QUOTE_NONNUMERIC’ 格式选项（在这种情况下，未加引号的字段会转换为浮
     点数），否则不会执行自动数据类型转换。

     一个简短的用法示例:

          >>> import csv
          >>> with open('eggs.csv', newline='') 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

 -- 函式: csv.writer (csvfile, dialect='excel', **fmtparams)

     返回一个 writer 对象，该对象负责将用户的数据在给定的文件类对象上转
     换为带分隔符的字符串。 `csvfile' 可以是任何具有 ‘write()’ 方法的对
     象。 如果 `csvfile' 是一个文件对象，则打开它时应使用 ‘newline=''’
     (2)。 可以给出可选的 `dialect' 形参用来定义一组特定 CSV 变种专属的
     形参。 它可以是 *note Dialect: f6c. 类的某个子类的实例或是 *note
     list_dialects(): 1f7f. 函数所返回的字符串之一。 还可以给出另一个可
     选的 `fmtparams' 关键字参数来覆盖当前变种中的单个格式化形参。 有关
     各个变种和格式化形参的完整细节，请参阅 *note 变种与格式参数: 1f80.
     部分。 为了尽量简化与实现 DB API 的模块之间的接口，*note None: 203.
     值会被当作空字符串写入。 虽然这个转换是不可逆的，但它可以简化 SQL
     NULL 数据值到 CSV 文件的转储而无需预处理从 ‘cursor.fetch*’ 调用返回
     的数据。 在被写入之前所有其他非字符串数据都会先用 *note str(): 205.
     来转转为字符串。

     一个简短的用法示例:

          import csv
          with open('eggs.csv', 'w', newline='') 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'])

 -- 函式: csv.register_dialect (name[, dialect[, **fmtparams]])

     将 `dialect' 与 `name' 关联起来。 `name' 必须是字符串。 变种的指定
     可以通过传入一个 *note Dialect: f6c. 的子类，或通过 `fmtparams' 关
     键字参数，或是两者同时传入，此时关键字参数会覆盖 dialect 形参。 有
     关变种和格式化形参的完整细节，请参阅 *note 变种与格式参数: 1f80. 部
     分。

 -- 函式: csv.unregister_dialect (name)

     从变种注册表中删除 `name' 对应的变种。如果 `name' 不是已注册的变种
     名称，则抛出 *note Error: 1f83. 异常。

 -- 函式: csv.get_dialect (name)

     返回 `name' 对应的变种。如果 `name' 不是已注册的变种名称，则抛出
     *note Error: 1f83. 异常。该函数返回的是不可变的 *note Dialect: f6c.
     对象。

 -- 函式: csv.list_dialects ()

     返回所有已注册变种的名称。

 -- 函式: csv.field_size_limit ([new_limit])

     返回解析器当前允许的最大字段大小。如果指定了 `new_limit'，则它将成
     为新的最大字段大小。

*note csv: 29. 模块定义了以下类：

 -- 類別: csv.DictReader (f, fieldnames=None, restkey=None,
          restval=None, dialect='excel', *args, **kwds)

     创建一个对象，该对象在操作上类似于常规 reader，但是将每行中的信息映
     射到一个 *note dict: 164.，该 dict 的键由 `fieldnames' 可选参数给出
     。

     `fieldnames' 参数是一个 *note sequence: 135c.。如果省略
     `fieldnames'，则文件 `f' 第一行中的值将用作字段名。无论字段名是如何
     确定的，字典都将保留其原始顺序。

     如果某一行中的字段多于字段名，则剩余数据会被放入一个列表，并与
     `restkey' 所指定的字段名 (默认为 ‘None’) 一起保存。 如果某个非空白
     行的字段少于字段名，则缺失的值会使用 `restval' 的值来填充 (默认为
     ‘None’)。

     所有其他可选或关键字参数都传递给底层的 *note reader: 101a. 实例。

     3.6 版更變: 返回的行现在的类型是 ‘OrderedDict’。

     3.8 版更變: 现在，返回的行是 *note dict: 164. 类型。

     一个简短的用法示例:

          >>> import csv
          >>> with open('names.csv', newline='') 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'}

 -- 類別: csv.DictWriter (f, fieldnames, restval='',
          extrasaction='raise', dialect='excel', *args, **kwds)

     创建一个对象，该对象在操作上类似常规 writer，但会将字典映射到输出行
     。 `fieldnames' 参数是由键组成的 *note 序列: 1e.，它指定字典中值的
     顺序，这些值会按指定顺序传递给 ‘writerow()’ 方法并写入文件 `f'。 如
     果字典缺少 `fieldnames' 中的键，则可选参数 `restval' 用于指定要写入
     的值。 如果传递给 ‘writerow()’ 方法的字典的某些键在 `fieldnames' 中
     找不到，则可选参数 `extrasaction' 用于指定要执行的操作。 如果将其设
     置为默认值 ‘'raise'’，则会引发 *note ValueError: 16d.。 如果将其设
     置为 ‘'ignore'’，则字典中的其他键值将被忽略。 所有其他可选或关键字
     参数都传递给底层的 *note writer: ec0. 实例。

     注意，与 *note DictReader: 2ee. 类不同，*note DictWriter: c4b. 类的
     `fieldnames' 参数不是可选参数。

     一个简短的用法示例:

          import csv

          with open('names.csv', 'w', newline='') 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'})

 -- 類別: csv.Dialect

     *note Dialect: f6c. 类是一个容器类，其属性包含有如何处理双引号、空
     白符、分隔符等的信息。 由于缺少严格的 CSV 规格描述，不同的应用程序
     会产生略有差别的 CSV 数据。 *note Dialect: f6c. 实例定义了 *note
     reader: 101a. 和 *note writer: ec0. 实例将具有怎样的行为。

     所有可用的 *note Dialect: f6c. 名称会由 *note list_dialects():
     1f7f. 返回，并且它们可由特定的 *note reader: 101a. 和 *note writer:
     ec0. 类通过它们的初始化函数 (‘__init__’) 来注册，例如:

          import csv

          with open('students.csv', 'w', newline='') as csvfile:
              writer = csv.writer(csvfile, dialect='unix')
                                           ^^^^^^^^^^^^^^

 -- 類別: csv.excel

     *note excel: 1f86. 类定义了 Excel 生成的 CSV 文件的常规属性。它在变
     种注册表中的名称是 ‘'excel'’。

 -- 類別: csv.excel_tab

     *note excel_tab: 1f87. 类定义了 Excel 生成的、制表符分隔的 CSV 文件
     的常规属性。它在变种注册表中的名称是 ‘'excel-tab'’。

 -- 類別: csv.unix_dialect

     *note unix_dialect: c4a. 类定义了在 UNIX 系统上生成的 CSV 文件的常
     规属性，即使用 ‘'\n'’ 作为换行符，且所有字段都有引号包围。它在变种
     注册表中的名称是 ‘'unix'’。

     3.2 版新加入.

 -- 類別: csv.Sniffer

     *note Sniffer: 1f88. 类用于推断 CSV 文件的格式。

     *note Sniffer: 1f88. 类提供了两个方法：

      -- 成員函式: sniff (sample, delimiters=None)

          分析给定的 `sample' 并返回一个 *note Dialect: f6c. 子类，该子
          类中包含了分析出的格式参数。如果给出可选的 `delimiters' 参数，
          则该参数会被解释为字符串，该字符串包含了可能的有效定界符。

      -- 成員函式: has_header (sample)

          分析示例文本（假定为 CSV 格式），如果第一行很可能是一系列列标
          题，则返回 *note True: 593.。

使用 *note Sniffer: 1f88. 的示例：

     with open('example.csv', newline='') as csvfile:
         dialect = csv.Sniffer().sniff(csvfile.read(1024))
         csvfile.seek(0)
         reader = csv.reader(csvfile, dialect)
         # ... process CSV file contents here ...

*note csv: 29. 模块定义了以下常量：

 -- Data: csv.QUOTE_ALL

     指示 *note writer: ec0. 对象给所有字段加上引号。

 -- Data: csv.QUOTE_MINIMAL

     指示 *note writer: ec0. 对象仅为包含特殊字符（例如 `定界符'、`引号
     字符' 或 `行结束符' 中的任何字符）的字段加上引号。

 -- Data: csv.QUOTE_NONNUMERIC

     指示 *note writer: ec0. 对象为所有非数字字段加上引号。

     指示 reader 将所有未用引号引出的字段转换为 `float' 类型。

 -- Data: csv.QUOTE_NONE

     指示 *note writer: ec0. 对象不使用引号引出字段。当 `定界符' 出现在
     输出数据中时，其前面应该有 `转义符'。如果未设置 `转义符'，则遇到任
     何需要转义的字符时，writer 都会抛出 *note Error: 1f83. 异常。

     指示 *note reader: 101a. 不对引号字符进行特殊处理。

*note csv: 29. 模块定义了以下异常：

 -- 例外: csv.Error

     该异常可能由任何发生错误的函数抛出。

   ---------- Footnotes ----------

   (1) (1) 如果没有指定 ‘newline=''’，则嵌入引号中的换行符将无法正确解析
，并且在写入时，使用 ‘\r\n’ 换行的平台会有多余的 ‘\r’ 写入。由于 csv 模
块会执行自己的（*note 通用: 6eb.）换行符处理，因此指定 ‘newline=''’ 应该
总是安全的。

   (2) (1) 如果没有指定 ‘newline=''’，则嵌入引号中的换行符将无法正确解析
，并且在写入时，使用 ‘\r\n’ 换行的平台会有多余的 ‘\r’ 写入。由于 csv 模
块会执行自己的（*note 通用: 6eb.）换行符处理，因此指定 ‘newline=''’ 应该
总是安全的。


File: python.info,  Node: 变种与格式参数,  Next: Reader 对象,  Prev: 模块内容<3>,  Up: csv --- CSV 文件读写

5.14.1.2 变种与格式参数
.......................

为了更容易指定输入和输出记录的格式，特定的一组格式参数组合为一个
dialect（变种）。一个 dialect 是一个 *note Dialect: f6c. 类的子类，它具
有一组特定的方法和一个 ‘validate()’ 方法。创建 *note reader: 101a. 或
*note writer: ec0. 对象时，程序员可以将某个字符串或 *note Dialect: f6c.
类的子类指定为 dialect 参数。要想补充或覆盖 `dialect' 参数，程序员还可以
单独指定某些格式参数，这些参数的名称与下面 *note Dialect: f6c. 类定义的
属性相同。

Dialect 类支持以下属性：

 -- 屬性: Dialect.delimiter

     一个用于分隔字段的单字符，默认为 ‘','’。

 -- 屬性: Dialect.doublequote

     控制出现在字段中的 `引号字符' 本身应如何被引出。当该属性为 *note
     True: 593. 时，双写引号字符。如果该属性为 *note False: 48e.，则在
     `引号字符' 的前面放置 `转义符'。默认值为 *note True: 593.。

     在输出时，如果 `doublequote' 是 *note False: 48e.，且 `转义符' 未指
     定，且在字段中发现 `引号字符' 时，会抛出 *note Error: 1f83. 异常。

 -- 屬性: Dialect.escapechar

     一个用于 writer 的单字符，用来在 `quoting' 设置为 *note QUOTE_NONE:
     1f8e. 的情况下转义 `定界符'，在 `doublequote' 设置为 *note False:
     48e. 的情况下转义 `引号字符'。在读取时，`escapechar' 去除了其后所跟
     字符的任何特殊含义。该属性默认为 *note None: 203.，表示禁用转义。

 -- 屬性: Dialect.lineterminator

     放在 *note writer: ec0. 产生的行的结尾，默认为 ‘'\r\n'’。

          備註: *note reader: 101a. 经过硬编码，会识别 ‘'\r'’ 或 ‘'\n'’
          作为行尾，并忽略 `lineterminator'。未来可能会更改这一行为。

 -- 屬性: Dialect.quotechar

     一个单字符，用于包住含有特殊字符的字段，特殊字符如 `定界符' 或 `引
     号字符' 或换行符。默认为 ‘'"'’。

 -- 屬性: Dialect.quoting

     控制 writer 何时生成引号，以及 reader 何时识别引号。该属性可以等于
     任何 ‘QUOTE_*’ 常量（参见 *note 模块内容: 1f7d. 段落），默认为
     *note QUOTE_MINIMAL: 1f8c.。

 -- 屬性: Dialect.skipinitialspace

     如果为 *note True: 593.，则忽略 `定界符' 之后的空格。默认值为 *note
     False: 48e.。

 -- 屬性: Dialect.strict

     如果为 ‘True’，则在输入错误的 CSV 时抛出 *note Error: 1f83. 异常。
     默认值为 ‘False’。


File: python.info,  Node: Reader 对象,  Next: Writer 对象,  Prev: 变种与格式参数,  Up: csv --- CSV 文件读写

5.14.1.3 Reader 对象
....................

Reader 对象（*note DictReader: 2ee. 实例和 *note reader(): 101a. 函数返
回的对象）具有以下公开方法：

 -- 成員函式: csvreader.__next__ ()

     返回 reader 的可迭代对象的下一行，它可以是一个列表（如果对象是由
     *note reader(): 101a. 返回）或字典（如果是一个 *note DictReader:
     2ee. 实例），根据当前 *note Dialect: f6c. 来解析。 通常你应当以
     ‘next(reader)’ 的形式来调用它。

Reader 对象具有以下公开属性：

 -- 屬性: csvreader.dialect

     变种描述，只读，供解析器使用。

 -- 屬性: csvreader.line_num

     源迭代器已经读取了的行数。它与返回的记录数不同，因为记录可能跨越多
     行。

DictReader 对象具有以下公开属性：

 -- 屬性: csvreader.fieldnames

     字段名称。如果在创建对象时未传入字段名称，则首次访问时或从文件中读
     取第一条记录时会初始化此属性。


File: python.info,  Node: Writer 对象,  Next: 示例<13>,  Prev: Reader 对象,  Up: csv --- CSV 文件读写

5.14.1.4 Writer 对象
....................

‘Writer’ 对象（*note DictWriter: c4b. 实例和 *note writer(): ec0. 函数返
回的对象）具有下面的公开方法。对于 ‘Writer’ 对象，`行' 必须是（一组可迭
代的）字符串或数字。对于 *note DictWriter: c4b. 对象，`行' 必须是一个字
典，这个字典将字段名映射为字符串或数字（数字要先经过 *note str(): 205. 转
换类型）。请注意，输出的复数会有括号包围。这样其他程序读取 CSV 文件时可
能会有一些问题（假设它们完全支持复数）。

 -- 成員函式: csvwriter.writerow (row)

     将 `row' 形参写入到 writer 的文件对象，根据当前 *note Dialect: f6c.
     进行格式化。 返回对下层文件对象的 `write' 方法的调用的返回值。

     3.5 版更變: 开始支持任意类型的迭代器。

 -- 成員函式: csvwriter.writerows (rows)

     将 `rows*（即能迭代出多个上述 *row' 对象的迭代器）中的所有元素写入
     writer 的文件对象，并根据当前设置的变种进行格式化。

Writer 对象具有以下公开属性：

 -- 屬性: csvwriter.dialect

     变种描述，只读，供 writer 使用。

DictWriter 对象具有以下公开方法：

 -- 成員函式: DictWriter.writeheader ()

     在 writer 的文件对象中，写入一行字段名称（字段名称在构造函数中指定
     ），并根据当前设置的变种进行格式化。本方法的返回值就是内部使用的
     *note csvwriter.writerow(): 7b7. 方法的返回值。

     3.2 版新加入.

     3.8 版更變: 现在 *note writeheader(): c4c. 也返回其内部使用的 *note
     csvwriter.writerow(): 7b7. 方法的返回值。


File: python.info,  Node: 示例<13>,  Prev: Writer 对象,  Up: csv --- CSV 文件读写

5.14.1.5 示例
.............

读取 CSV 文件最简单的一个例子:

     import csv
     with open('some.csv', newline='') as f:
         reader = csv.reader(f)
         for row in reader:
             print(row)

读取其他格式的文件:

     import csv
     with open('passwd', newline='') as f:
         reader = csv.reader(f, delimiter=':', quoting=csv.QUOTE_NONE)
         for row in reader:
             print(row)

相应最简单的写入示例是:

     import csv
     with open('some.csv', 'w', newline='') as f:
         writer = csv.writer(f)
         writer.writerows(someiterable)

由于使用 *note open(): 16f. 来读取 CSV 文件，因此默认情况下，将使用系统
默认编码来解码文件并转换为 unicode（请参阅 *note
locale.getpreferredencoding(): 4ab.）。要使用其他编码来解码文件，请使用
open 的 ‘encoding’ 参数:

     import csv
     with open('some.csv', newline='', encoding='utf-8') as f:
         reader = csv.reader(f)
         for row in reader:
             print(row)

这同样适用于写入非系统默认编码的内容：打开输出文件时，指定 encoding 参数
。

注册一个新的变种:

     import csv
     csv.register_dialect('unixpwd', delimiter=':', quoting=csv.QUOTE_NONE)
     with open('passwd', newline='') as f:
         reader = csv.reader(f, 'unixpwd')

Reader 的更高级用法——捕获并报告错误:

     import csv, sys
     filename = 'some.csv'
     with open(filename, newline='') 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))

尽管该模块不直接支持解析字符串，但仍可如下轻松完成:

     import csv
     for row in csv.reader(['one,two,three']):
         print(row)

註解
....


File: python.info,  Node: configparser --- 配置文件解析器,  Next: netrc --- netrc 文件处理,  Prev: csv --- CSV 文件读写,  Up: 檔案格式

5.14.2 ‘configparser’ — 配置文件解析器
--------------------------------------

`源代码:' Lib/configparser.py(1)

__________________________________________________________________

此模块提供了它实现一种基本配置语言 *note ConfigParser: 5a4. 类，这种语言
所提供的结构与 Microsoft Windows INI 文件的类似。 你可以使用这种语言来编
写能够由最终用户来自定义的 Python 程序。

     備註: 这个库 `并不' 能够解析或写入在 Windows Registry 扩展版本 INI
     语法中所使用的值-类型前缀。

也參考
......

模块 *note shlex: e8.

     支持创建可被用作应用配置文件的替代的 Unix 终端式微语言。

模块 *note json: a4.

     json 模块实现了一个 JavaScript 语法的子集，它也可被用于这种目的。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/configparser.py


File: python.info,  Node: 快速起步,  Next: 支持的数据类型,  Up: configparser --- 配置文件解析器

5.14.2.1 快速起步
.................

让我们准备一个非常基本的配置文件，它看起来是这样的:

     [DEFAULT]
     ServerAliveInterval = 45
     Compression = yes
     CompressionLevel = 9
     ForwardX11 = yes

     [bitbucket.org]
     User = hg

     [topsecret.server.com]
     Port = 50022
     ForwardX11 = no

INI 文件的结构描述见 *note 以下章节: 1fa5.。 总的来说，这种文件由多个节
组成，每个节包含多个带有值的键。 *note configparser: 22. 类可以读取和写
入这种文件。 让我们先通过程序方式来创建上述的配置文件。

     >>> 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)
     ...

如你所见，我们可以把配置解析器当作一个字典来处理。 两者确实存在差异，
*note 将在后文说明: 1fa6.，但是其行为非常接近于字典所具有一般行为。

现在我们已经创建并保存了一个配置文件，让我们再将它读取出来并探究其中包含
的数据。

     >>> 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'

正如我们在上面所看到的，相关的 API 相当直观。 唯一有些神奇的地方是
‘DEFAULT’ 小节，它为所有其他小节提供了默认值 (1)。 还要注意小节中的键大
小写不敏感并且会存储为小写形式 (2)。

   ---------- Footnotes ----------

   (1) (1) 配置解析器允许重度定制。 如果你有兴趣改变脚注说明中所介绍的行
为，请参阅 *note Customizing Parser Behaviour: 1fa7. 一节。

   (2) (1) 配置解析器允许重度定制。 如果你有兴趣改变脚注说明中所介绍的行
为，请参阅 *note Customizing Parser Behaviour: 1fa7. 一节。


File: python.info,  Node: 支持的数据类型,  Next: 回退值,  Prev: 快速起步,  Up: configparser --- 配置文件解析器

5.14.2.2 支持的数据类型
.......................

配置解析器并不会猜测配置文件中值的类型，而总是将它们在内部存储为字符串。
这意味着如果你需要其他数据类型，你应当自己来转换:

     >>> int(topsecret['Port'])
     50022
     >>> float(topsecret['CompressionLevel'])
     9.0

由于这种任务十分常用，配置解析器提供了一系列便捷的获取方法来处理整数、浮
点数和布尔值。 最后一个类型的处理最为有趣，因为简单地将值传给 ‘bool()’ 是
没有用的，‘bool('False')’ 仍然会是 ‘True’。 为解决这个问题配置解析器还提
供了 *note getboolean(): 1fa9.。 这个方法对大小写不敏感并可识别
‘'yes'’/‘'no'’, ‘'on'’/‘'off'’, ‘'true'’/‘'false'’ 和 ‘'1'’/‘'0'’ (1) 等
布尔值。 例如:

     >>> topsecret.getboolean('ForwardX11')
     False
     >>> config['bitbucket.org'].getboolean('ForwardX11')
     True
     >>> config.getboolean('bitbucket.org', 'Compression')
     True

除了 *note getboolean(): 1fa9.，配置解析器还提供了同类的 *note getint():
1faa. 和 *note getfloat(): 1fab. 方法。 你可以注册你自己的转换器并或是定
制已提供的转换器。 (2)

   ---------- Footnotes ----------

   (1) (1) 配置解析器允许重度定制。 如果你有兴趣改变脚注说明中所介绍的行
为，请参阅 *note Customizing Parser Behaviour: 1fa7. 一节。

   (2) (1) 配置解析器允许重度定制。 如果你有兴趣改变脚注说明中所介绍的行
为，请参阅 *note Customizing Parser Behaviour: 1fa7. 一节。


File: python.info,  Node: 回退值,  Next: 受支持的 INI 文件结构,  Prev: 支持的数据类型,  Up: configparser --- 配置文件解析器

5.14.2.3 回退值
...............

与字典类似，你可以使用某个小节的 ‘get()’ 方法来提供回退值:

     >>> topsecret.get('Port')
     '50022'
     >>> topsecret.get('CompressionLevel')
     '9'
     >>> topsecret.get('Cipher')
     >>> topsecret.get('Cipher', '3des-cbc')
     '3des-cbc'

请注意默认值会优先于回退值。 例如，在我们的示例中 ‘'CompressionLevel'’ 键
仅在 ‘'DEFAULT'’ 小节被指定。 如果你尝试在 ‘'topsecret.server.com'’ 小节
获取它，我们将总是获取到默认值，即使我们指定了一个回退值:

     >>> topsecret.get('CompressionLevel', '3')
     '9'

还需要注意的一点是解析器层级的 ‘get()’ 方法提供了自定义的更复杂接口，它
被维护用于向下兼容。 当使用此方法时，回退值可以通过 ‘fallback’ 仅限关键
字参数来提供:

     >>> config.get('bitbucket.org', 'monster',
     ...            fallback='No such things as monsters')
     'No such things as monsters'

同样的 ‘fallback’ 参数也可在 *note getint(): 1faa, *note getfloat():
1fab. 和 *note getboolean(): 1fa9. 方法中使用，例如:

     >>> 'BatchMode' in topsecret
     False
     >>> topsecret.getboolean('BatchMode', fallback=True)
     True
     >>> config['DEFAULT']['BatchMode'] = 'no'
     >>> topsecret.getboolean('BatchMode', fallback=True)
     False


File: python.info,  Node: 受支持的 INI 文件结构,  Next: 值的插值,  Prev: 回退值,  Up: configparser --- 配置文件解析器

5.14.2.4 受支持的 INI 文件结构
..............................

A configuration file consists of sections, each led by a ‘[section]’
header, followed by key/value entries separated by a specific string
(‘=’ or ‘:’ by default (1)).  By default, section names are case
sensitive but keys are not (2).  Leading and trailing whitespace is
removed from keys and values.  Values can be omitted if the parser is
configured to allow it (3), in which case the key/value delimiter may
also be left out.  Values can also span multiple lines, as long as they
are indented deeper than the first line of the value.  Depending on the
parser’s mode, blank lines may be treated as parts of multiline values
or ignored.

配置文件可以包含注释，要带有指定字符前缀 (默认为 ‘#’ 和 ‘;’ (4))。 注释
可以单独出现于原本的空白行，并可使用缩进。 (5)

例如:

     [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?

   ---------- Footnotes ----------

   (1) (1) 配置解析器允许重度定制。 如果你有兴趣改变脚注说明中所介绍的行
为，请参阅 *note Customizing Parser Behaviour: 1fa7. 一节。

   (2) (1) 配置解析器允许重度定制。 如果你有兴趣改变脚注说明中所介绍的行
为，请参阅 *note Customizing Parser Behaviour: 1fa7. 一节。

   (3) (1) 配置解析器允许重度定制。 如果你有兴趣改变脚注说明中所介绍的行
为，请参阅 *note Customizing Parser Behaviour: 1fa7. 一节。

   (4) (1) 配置解析器允许重度定制。 如果你有兴趣改变脚注说明中所介绍的行
为，请参阅 *note Customizing Parser Behaviour: 1fa7. 一节。

   (5) (1) 配置解析器允许重度定制。 如果你有兴趣改变脚注说明中所介绍的行
为，请参阅 *note Customizing Parser Behaviour: 1fa7. 一节。


File: python.info,  Node: 值的插值,  Next: 映射协议访问,  Prev: 受支持的 INI 文件结构,  Up: configparser --- 配置文件解析器

5.14.2.5 值的插值
.................

在核心功能之上，*note ConfigParser: 5a4. 还支持插值。 这意味着值可以在被
‘get()’ 调用返回之前进行预处理。

 -- 類別: configparser.BasicInterpolation

     默认实现由 *note ConfigParser: 5a4. 来使用。 它允许值包含引用了相同
     小节中其他值或者特殊的默认小节中的值的格式字符串 (1)。 额外的默认值
     可以在初始化时提供。

     例如:

          [Paths]
          home_dir: /Users
          my_dir: %(home_dir)s/lumberjack
          my_pictures: %(my_dir)s/Pictures

          [Escape]
          gain: 80%%  # use a %% to escape the % sign (% is the only character that needs to be escaped)

     在上面的例子里，*note ConfigParser: 5a4. 的 `interpolation' 设为
     ‘BasicInterpolation()’，这会将 ‘%(home_dir)s’ 求解为 ‘home_dir’ 的
     值 (在这里是 ‘/Users’)。 ‘%(my_dir)s’ 的将被实际求解为
     ‘/Users/lumberjack’。 所有插值都是按需进行的，这样引用链中使用的键
     不必以任何特定顺序在配置文件中指明。

     当 ‘interpolation’ 设为 ‘None’ 时，解析器会简单地返回
     ‘%(my_dir)s/Pictures’ 作为 ‘my_pictures’ 的值，并返回
     ‘%(home_dir)s/lumberjack’ 作为 ‘my_dir’ 的值。

 -- 類別: configparser.ExtendedInterpolation

     一个用于插值的替代处理程序实现了更高级的语法，它被用于
     ‘zc.buildout’ 中的实例。 扩展插值使用 ‘${section:option}’ 来表示来
     自外部小节的值。 插值可以跨越多个层级。 为了方便使用，‘section:’ 部
     分可被省略，插值会默认作用于当前小节（可能会从特殊小节获取默认值）
     。

     例如，上面使用基本插值描述的配置，使用扩展插值将是这个样子:

          [Paths]
          home_dir: /Users
          my_dir: ${home_dir}/lumberjack
          my_pictures: ${my_dir}/Pictures

          [Escape]
          cost: $$80  # use a $$ to escape the $ sign ($ is the only character that needs to be escaped)

     来自其他小节的值也可以被获取:

          [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}

   ---------- Footnotes ----------

   (1) (1) 配置解析器允许重度定制。 如果你有兴趣改变脚注说明中所介绍的行
为，请参阅 *note Customizing Parser Behaviour: 1fa7. 一节。


File: python.info,  Node: 映射协议访问,  Next: 定制解析器行为,  Prev: 值的插值,  Up: configparser --- 配置文件解析器

5.14.2.6 映射协议访问
.....................

3.2 版新加入.

映射协议访问这个通用名称是指允许以字典的方式来使用自定义对象的功能。 在
*note configparser: 22. 中，映射接口的实现使用了
‘parser['section']['option']’ 标记法。

‘parser['section']’ 专门为解析器中的小节数据返回一个代理。 这意味着其中
的值不会被拷贝，而是在需要时从原始解析器中获取。 更为重要的是，当值在小
节代理上被修改时，它们其实是在原始解析器中发生了改变。

*note configparser: 22. 对象的行为会尽可能地接近真正的字典。 映射接口是
完整而且遵循 *note MutableMapping: ace. ABC 规范的。 但是，还是有一些差
异应当被纳入考虑:

   * 默认情况下，小节中的所有键是以大小写不敏感的方式来访问的 (1)。 例如
     ‘for option in parser["section"]’ 只会产生 ‘optionxform’ 形式的选项
     键名称。 也就是说默认使用小写字母键名。 与此同时，对于一个包含键
     ‘'a'’ 的小节，以下两个表达式均将返回 ‘True’:

          "a" in parser["section"]
          "A" in parser["section"]

   * 所有小节也包括 ‘DEFAULTSECT’，这意味着对一个小节执行 ‘.clear()’ 可
     能无法使得该小节显示为空。 这是因为默认值是无法从小节中被删除的（因
     为从技术上说它们并不在那里）。 如果它们在小节中被覆盖，删除将导致默
     认值重新变为可见。 尝试删除默认值将会引发 *note KeyError: 3e9.。

   * ‘DEFAULTSECT’ 无法从解析器中被移除:

        * 尝试删除将引发 *note ValueError: 16d.，

        * ‘parser.clear()’ 会保留其原状，

        * ‘parser.popitem()’ 绝不会将其返回。

   * ‘parser.get(section, option, **kwargs)’ - 第二个参数 `并非' 回退值
     。 但是请注意小节层级的 ‘get()’ 方法可同时兼容映射协议和经典配置解
     析器 API。

   * ‘parser.items()’ 兼容映射协议（返回 `section_name', `section_proxy'
     对的列表，包括 DEFAULTSECT）。 但是，此方法也可以带参数发起调用:
     ‘parser.items(section, raw, vars)’。 这种调用形式返回指定 ‘section’
     的 `option', `value' 对的列表，将展开所有插值（除非提供了
     ‘raw=True’ 选项）。

映射协议是在现有的传统 API 之上实现的，以便重载原始接口的子类仍然具有符
合预期的有效映射。

   ---------- Footnotes ----------

   (1) (1) 配置解析器允许重度定制。 如果你有兴趣改变脚注说明中所介绍的行
为，请参阅 *note Customizing Parser Behaviour: 1fa7. 一节。


File: python.info,  Node: 定制解析器行为,  Next: 旧式 API 示例,  Prev: 映射协议访问,  Up: configparser --- 配置文件解析器

5.14.2.7 定制解析器行为
.......................

INI 格式的变种数量几乎和使用此格式的应用一样多。 *note configparser: 22.
花费了很大力气来为尽量大范围的可用 INI 样式提供支持。 默认的可用功能主要
由历史状况来确定，你很可能会想要定制某些特性。

改变特定配置解析器行为的最常见方式是使用 *note __init__(): e23. 选项:

   * `defaults'，默认值: ‘None’

     此选项接受一个键值对的字典，它将被首先放入 ‘DEFAULT’ 小节。 这实现
     了一种优雅的方式来支持简洁的配置文件，它不必指定与已记录的默认值相
     同的值。

     提示：如果你想要为特定的小节指定默认的值，请在读取实际文件之前使用
     ‘read_dict()’。

   * `dict_type'，默认值: *note dict: 164.

     此选项主要影响映射协议的行为和写入配置文件的外观。 使用标准字典时，
     每个小节是按照它们被加入解析器的顺序保存的。 在小节内的选项也是如此
     。

     还有其他替换的字典类型可以使用，例如在写回数据时对小节和选项进行排
     序。

     请注意：存在其他方式只用一次操作来添加键值对的集合。 当你在这些操作
     中使用一个常规字典时，键将按顺序进行排列。 例如:

          >>> 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']

   * `allow_no_value'，默认值: ‘False’

     已知某些配置文件会包括不带值的设置，但其在其他方面均符合 *note
     configparser: 22. 所支持的语法。 构造器的 `allow_no_value' 形参可用
     于指明应当接受这样的值:

          >>> 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'

   * `delimiters'，默认值: ‘('=', ':')’

     分隔符是用于在小节内分隔键和值的子字符串。 在一行中首次出现的分隔子
     字符串会被视为一个分隔符。 这意味着值可以包含分隔符（但键不可以）。

     另请参见 *note ConfigParser.write(): 1faf. 的
     `space_around_delimiters' 参数。

   * `comment_prefixes'，默认值: ‘('#', ';')’

   * `inline_comment_prefixes'，默认值: ‘None’

     注释前缀是配置文件中用于标示一条有效注释的开头的字符串。
     `comment_prefixes' 仅用在被视为空白的行（可以缩进）之前而
     `inline_comment_prefixes' 可用在每个有效值之后（例如小节名称、选项
     以及空白的行）。 默认情况下禁用行内注释，并且 ‘'#'’ 和 ‘';'’ 都被用
     作完整行注释的前缀。

     3.2 版更變: 在之前的 *note configparser: 22. 版本中行为匹配
     ‘comment_prefixes=('#',';')’ 和 ‘inline_comment_prefixes=(';',)’。

     请注意配置解析器不支持对注释前缀的转义，因此使用
     `inline_comment_prefixes' 可能妨碍用户将被用作注释前缀的字符指定为
     可选值。 当有疑问时，请避免设置 `inline_comment_prefixes'。 在许多
     情况下，在多行值的一行开头存储注释前缀字符的唯一方式是进行前缀插值
     ，例如:

          >>> 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

   * `strict'，默认值: ‘True’

     当设为 ‘True’ 时，解析器在从单一源读取 (使用 ‘read_file()’,
     ‘read_string()’ 或 ‘read_dict()’) 期间将不允许任何小节或选项出现重
     复。 推荐在新的应用中使用严格解析器。

     3.2 版更變: 在之前的 *note configparser: 22. 版本中行为匹配
     ‘strict=False’。

   * `empty_lines_in_values'，默认值: ‘True’

     在配置解析器中，值可以包含多行，只要它们的缩进级别低于它们所对应的
     键。 默认情况下解析器还会将空行视为值的一部分。 于此同时，键本身也
     可以任意缩进以提升可读性。 因此，当配置文件变得非常庞大而复杂时，用
     户很容易失去对文件结构的掌控。 例如:

          [Section]
          key = multiline
            value with a gotcha

           this = is still a part of the multiline value of 'key'

     在用户查看时这可能会特别有问题，如果她是使用比例字体来编辑文件的话
     。 这就是为什么当你的应用不需要带有空行的值时，你应该考虑禁用它们。
     这将使得空行每次都会作为键之间的分隔。 在上面的示例中，空行产生了两
     个键，‘key’ 和 ‘this’。

   * `default_section'，默认值: ‘configparser.DEFAULTSECT’ (即:
     ‘"DEFAULT"’)

     允许设置一个保存默认值的特殊节在其他节或插值等目的中使用的惯例是这
     个库所拥有的一个强大概念，使得用户能够创建复杂的声明性配置。 这种特
     殊节通常称为 ‘"DEFAULT"’ 但也可以被定制为指向任何其他有效的节名称。
     一些典型的值包括: ‘"general"’ 或 ‘"common"’。 所提供的名称在从任意
     节读取的时候被用于识别默认的节，而且也会在将配置写回文件时被使用。
     它的当前值可以使用 ‘parser_instance.default_section’ 属性来获取，并
     且可以在运行时被修改（即将文件从一种格式转换为另一种格式）。

   * `interpolation'，默认值: ‘configparser.BasicInterpolation’

     插值行为可以用通过提供 `interpolation' 参数提供自定义处理程序的方式
     来定制。 ‘None’ 可用来完全禁用插值，‘ExtendedInterpolation()’ 提供
     了一种更高级的变体形式，它的设计受到了 ‘zc.buildout’ 的启发。 有关
     该主题的更多信息请参见 *note 专门的文档章节: 1fad.。 *note
     RawConfigParser: 95c. 具有默认的值 ‘None’。

   * `converters'，默认值: 不设置

     配置解析器提供了可选的值获取方法用来执行类型转换。 默认实现包括
     *note getint(): 1faa, *note getfloat(): 1fab. 以及 *note
     getboolean(): 1fa9.。 如果还需要其他获取方法，用户可以在子类中定义
     它们，或者传入一个字典，其中每个键都是一个转换器的名称而每个值都是
     一个实现了特定转换的可调用对象。 例如，传入 ‘{'decimal':
     decimal.Decimal}’ 将对解释器对象和所有节代理添加 ‘getdecimal()’。 换
     句话说，可以同时编写 ‘parser_instance.getdecimal('section', 'key',
     fallback=0)’ 和 ‘parser_instance['section'].getdecimal('key', 0)’。

     如果转换器需要访问解析器的状态，可以在配置解析器子类上作为一个方法
     来实现。 如果该方法的名称是以 ‘get’ 打头的，它将在所有节代理上以兼
     容字典的形式提供（参见上面的 ‘getdecimal()’ 示例）。

更多高级定制选项可通过重载这些解析器属性的默认值来达成。 默认值是在类中
定义的，因此它们可以通过子类或属性赋值来重载。

 -- 屬性: ConfigParser.BOOLEAN_STATES

     默认情况下当使用 *note getboolean(): 1fa9. 时，配置解析器会将下列值
     视为 ‘True’: ‘'1'’, ‘'yes'’, ‘'true'’, ‘'on'’ 而将下列值视为
     ‘False’: ‘'0'’, ‘'no'’, ‘'false'’, ‘'off'’。 你可以通过指定一个自定
     义的字符串键及其对应的布尔值字典来重载此行为。 例如:

          >>> 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

     其他典型的布尔值对包括 ‘accept’/‘reject’ 或 ‘enabled’/‘disabled’。

 -- 成員函式: ConfigParser.optionxform (option)

     这个方法会转换每次 read, get, 或 set 操作的选项名称。 默认会将名称
     转换为小写形式。 这也意味着当一个配置文件被写入时，所有键都将为小写
     形式。 如果此行为不合适则要重载此方法。 例如:

          >>> 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']

          備註: optionxform 函数会将选项名称转换为规范形式。 这应该是一
          个幂等函数：如果名称已经为规范形式，则应不加修改地将其返回。

 -- 屬性: ConfigParser.SECTCRE

     一个已编译正则表达式会被用来解析节标头。 默认将 ‘[section]’ 匹配到
     名称 ‘"section"’。 空格会被视为节名称的一部分，因此 ‘[ larch ]’ 将
     被读取为一个名称为 ‘" larch "’ 的节。 如果此行为不合适则要重载此属
     性。 例如:

          >>> 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']

          備註: 虽然 ConfigParser 对象也使用 ‘OPTCRE’ 属性来识别选项行，
          但并不推荐重载它，因为这会与构造器选项 `allow_no_value' 和
          `delimiters' 产生冲突。


File: python.info,  Node: 旧式 API 示例,  Next: ConfigParser 对象,  Prev: 定制解析器行为,  Up: configparser --- 配置文件解析器

5.14.2.8 旧式 API 示例
......................

主要出于向下兼容性的考虑，*note configparser: 22. 还提供了一种采用显式
‘get’/‘set’ 方法的旧式 API。 虽然以下介绍的方法存在有效的用例，但对于新
项目仍建议采用映射协议访问。 旧式 API 在多数时候都更复杂、更底层并且完全
违反直觉。

一个写入配置文件的示例:

     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)

一个再次读取配置文件的示例:

     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'))

要获取插值，请使用 *note ConfigParser: 5a4.:

     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

默认值在两种类型的 ConfigParser 中均可用。 它们将在当某个选项未在别处定
义时被用于插值。

     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!"


File: python.info,  Node: ConfigParser 对象,  Next: RawConfigParser 对象,  Prev: 旧式 API 示例,  Up: configparser --- 配置文件解析器

5.14.2.9 ConfigParser 对象
..........................

 -- 類別: 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={})

     主配置解析器。 当给定 `defaults' 时，它会被初始化为包含固有默认值的
     字典。 当给定 `dict_type' 时，它将被用来创建包含节、节中的选项以及
     默认值的字典。

     当给定 `delimiters' 时，它会被用作分隔键与值的子字符串的集合。 当给
     定 `comment_prefixes' 时，它将被用作在否则为空行的注释的前缀子字符
     串的集合。 注释可以被缩进。 当给定 `inline_comment_prefixes' 时，它
     将被用作非空行的注释的前缀子字符串的集合。

     当 `strict' 为 ‘True’ (默认值) 时，解析器在从单个源（文件、字符串或
     字典）读取时将不允许任何节或选项出现重复，否则会引发 *note
     DuplicateSectionError: cd0. 或 *note DuplicateOptionError: cd1.。 当
     `empty_lines_in_values' 为 ‘False’ (默认值: ‘True’) 时，每个空行均
     表示一个选项的结束。 在其他情况下，一个多行选项内部的空行会被保留为
     值的一部分。 当 `allow_no_value' 为 ‘True’ (默认值: ‘False’) 时，将
     接受没有值的选项；此种选项的值将为 ‘None’ 并且它们会以不带末尾分隔
     符的形式被序列化。

     当给定 `default_section' 时，它将指定存放其他节的默认值和用于插值的
     特殊节的名称 (通常命名为 ‘"DEFAULT"’)。 该值可通过使用
     ‘default_section’ 实例属性在运行时被读取或修改。

     插值行为可通过给出 `interpolation' 参数提供自定义处理程序的方式来定
     制。 ‘None’ 可用来完全禁用插值，‘ExtendedInterpolation()’ 提供了一
     种更高级的变体形式，它的设计受到了 ‘zc.buildout’ 的启发。 有关该主
     题的更多信息请参见 *note 专门的文档章节: 1fad.。

     插值中使用的所有选项名称将像任何其他选项名称引用一样通过 *note
     optionxform(): 1fb5. 方法来传递。 例如，使用 *note optionxform():
     1fb5. 的默认实现（它会将选项名称转换为小写形式）时，值 ‘foo
     %(bar)s’ 和 ‘foo %(BAR)s’ 是等价的。

     当给定 `converters' 时，它应当为一个字典，其中每个键代表一个类型转
     换器的名称而每个值则为实现从字符串到目标数据类型的转换的可调用对象
     。 每个转换器会获得其在解析器对象和节代理上对应的 ‘get*()’ 方法。

     3.1 版更變: 默认的 `dict_type' 为 *note collections.OrderedDict:
     2ea.。

     3.2 版更變: 添加了 `allow_no_value', `delimiters',
     `comment_prefixes', `strict', `empty_lines_in_values',
     `default_section' 以及 `interpolation'。

     3.5 版更變: 添加了 `converters' 参数。

     3.7 版更變: `defaults' 参数会通过 *note read_dict(): 1fb6. 来读取，
     提供全解析器范围内一致的行为：非字符串类型的键和值会被隐式地转换为
     字符串。

     3.8 版更變: 默认的 `dict_type' 为 *note dict: 164.，因为它现在会保
     留插入顺序。

      -- 成員函式: defaults ()

          返回包含实例范围内默认值的字典。

      -- 成員函式: sections ()

          返回可用节的列表；`default section' 不包括在该列表中。

      -- 成員函式: add_section (section)

          向实例添加一个名为 `section' 的节。 如果给定名称的节已存在，将
          会引发 *note DuplicateSectionError: cd0.。 如果传入了 `default
          section' 名称，则会引发 *note ValueError: 16d.。 节名称必须为
          字符串；如果不是则会引发 *note TypeError: 1fe.。

          3.2 版更變: 非字符串的节名称将引发 *note TypeError: 1fe.。

      -- 成員函式: has_section (section)

          指明相应名称的 `section' 是否存在于配置中。 `default section'
          不包含在内。

      -- 成員函式: options (section)

          返回指定 `section' 中可用选项的列表。

      -- 成員函式: has_option (section, option)

          如果给定的 `section' 存在并且包含给定的 `option' 则返回 *note
          True: 593.；否则返回 *note False: 48e.。 如果指定的 `section'
          为 *note None: 203. 或空字符串，则会使用 DEFAULT。

      -- 成員函式: read (filenames, encoding=None)

          尝试读取并解析一个包含文件名的可迭代对象，返回一个被成功解析的
          文件名列表。

          如果 `filenames' 为字符串、*note bytes: 172. 对象或 *note
          path-like object: 472.，它会被当作单个文件来处理。 如果
          `filenames' 中名称对应的某个文件无法被打开，该文件将被忽略。 这
          样的设计使得你可以指定包含多个潜在配置文件位置的可迭代对象（例
          如当前目录、用户家目录以及某个系统级目录），存在于该可迭代对象
          中的所有配置文件都将被读取。

          如果名称对应的文件全都不存在，则 *note ConfigParser: 5a4. 实例
          将包含一个空数据集。 一个要求从文件加载初始值的应用应当在调用
          *note read(): 11d9. 来获取任何可选文件之前使用 *note
          read_file(): 1fbc. 来加载所要求的一个或多个文件:

               import configparser, os

               config = configparser.ConfigParser()
               config.read_file(open('defaults.cfg'))
               config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')],
                           encoding='cp1250')

          3.2 版新加入: `encoding' 形参。 在之前的版本中，所有文件都将使
          用 *note open(): 16f. 的默认编码格式来读取。

          3.6.1 版新加入: `filenames' 形参接受一个 *note path-like
          object: 472.。

          3.7 版新加入: `filenames' 形参接受一个 *note bytes: 172. 对象
          。

      -- 成員函式: read_file (f, source=None)

          从 `f' 读取并解析配置数据，它必须是一个产生 Unicode 字符串的可
          迭代对象（例如以文本模式打开的文件）。

          可选参数 `source' 指定要读取的文件名称。 如果未给出并且 `f' 具
          有 ‘name’ 属性，则该属性会被用作 `source'；默认值为 ‘'<???>'’。

          3.2 版新加入: 替代 *note readfp(): 1fbd.。

      -- 成員函式: read_string (string, source='<string>')

          从字符串中解析配置数据。

          可选参数 `source' 指定一个所传入字符串的上下文专属名称。 如果
          未给出，则会使用 ‘'<string>'’。 这通常应为一个文件系统路径或
          URL。

          3.2 版新加入.

      -- 成員函式: read_dict (dictionary, source='<dict>')

          从任意一个提供了类似于字典的 ‘items()’ 方法的对象加载配置。 键
          为节名称，值为包含节中所出现的键和值的字典。 如果所用的字典类
          型会保留顺序，则节和其中的键将按顺序加入。 值会被自动转换为字
          符串。

          可选参数 `source' 指定一个所传入字曲的上下文专属名称。 如果未
          给出，则会使用 ‘<dict>’。

          此方法可被用于在解析器之间拷贝状态。

          3.2 版新加入.

      -- 成員函式: get (section, option, *, raw=False, vars=None[,
               fallback])

          获取指定名称的 `section' 的一个 `option' 的值。 如果提供了
          `vars'，则它必须为一个字典。 `option' 的查找顺序为 `vars*（如
          果有提供）、*section' 以及 `DEFAULTSECT'。 如果未找到该键并且
          提供了 `fallback'，则它会被用作回退值。 可以提供 ‘None’ 作为
          `fallback' 值。

          所有 ‘'%'’ 插值会在返回值中被展开，除非 `raw' 参数为真值。 插
          值键所使用的值会按与选项相同的方式来查找。

          3.2 版更變: `raw', `vars' 和 `fallback' 都是仅限关键字参数，以
          防止用户试图使用第三个参数作业为 `fallback' 回退值（特别是在使
          用映射 协议的时候）。

      -- 成員函式: getint (section, option, *, raw=False, vars=None[,
               fallback])

          将在指定 `section' 中的 `option' 强制转换为整数的便捷方法。 参
          见 *note get(): ccd. 获取对于 `raw', `vars' 和 `fallback' 的解
          释。

      -- 成員函式: getfloat (section, option, *, raw=False, vars=None[,
               fallback])

          将在指定 `section' 中的 `option' 强制转换为浮点数的便捷方法。
          参见 *note get(): ccd. 获取对于 `raw', `vars' 和 `fallback' 的
          解释。

      -- 成員函式: getboolean (section, option, *, raw=False,
               vars=None[, fallback])

          将在指定 `section' 中的 `option' 强制转换为布尔值的便捷方法。
          请注意选项所接受的值为 ‘'1'’, ‘'yes'’, ‘'true'’ 和 ‘'on'’，它
          们会使得此方法返回 ‘True’，以及 ‘'0'’, ‘'no'’, ‘'false'’ 和
          ‘'off'’，它们会使得此方法返回 ‘False’。 这些字符串值会以对大小
          写不敏感的方式被检测。 任何其他值都将导致引发 *note
          ValueError: 16d.。 参见 *note get(): ccd. 获取对于 `raw',
          `vars' 和 `fallback' 的解释。

      -- 成員函式: items (raw=False, vars=None)

      -- 成員函式: items (section, raw=False, vars=None)

          当未给出 `section' 时，将返回由 `section_name',
          `section_proxy' 对组成的列表，包括 DEFAULTSECT。

          在其他情况下，将返回给定的 `section' 中的 option 的 `name',
          `value' 对组成的列表。 可选参数具有与 *note get(): ccd. 方法的
          参数相同的含义。

          3.8 版更變: `vars' 中的条目将不在结果中出现。 之前的行为混淆了
          实际的解析器选项和为插值提供的变量。

      -- 成員函式: set (section, option, value)

          如果给定的节存在，则将所给出的选项设为指定的值；在其他情况下将
          引发 *note NoSectionError: 1fc0.。 `option' 和 `value' 必须为
          字符串；如果不是则将引发 *note TypeError: 1fe.。

      -- 成員函式: write (fileobject, space_around_delimiters=True)

          将配置的表示形式写入指定的 *note file object: c14.，该对象必须
          以文本模式打开（接受字符串）。 此表示形式可由将来的 *note
          read(): 11d9. 调用进行解析。 如果 `space_around_delimiters' 为
          真值，键和值之前的分隔符两边将加上空格。

          備註: 原始配置文件中的注释在写回配置时不会被保留。 具体哪些会
          被当作注释，取决于为 `comment_prefix' 和
          `inline_comment_prefix' 所指定的值。

      -- 成員函式: remove_option (section, option)

          将指定的 `option' 从指定的 `section' 中移除。 如果指定的节不存
          在则会引发 *note NoSectionError: 1fc0.。 如果要移除的选项存在
          则返回 *note True: 593.；在其他情况下将返回 *note False: 48e.。

      -- 成員函式: remove_section (section)

          从配置中移除指定的 `section'。 如果指定的节确实存在则返回
          ‘True’。 在其他情况下将返回 ‘False’。

      -- 成員函式: optionxform (option)

          将选项名 `option' 转换为输入文件中的形式或客户端代码所传入的应
          当在内部结构中使用的形式。 默认实现将返回 `option' 的小写形式
          版本；子类可以重载此行为，或者客户端代码也可以在实例上设置一个
          具有此名称的属性来影响此行为。

          你不需要子类化解析器来使用此方法，你也可以在一个实例上设置它，
          或使用一个接受字符串参数并返回字符串的函数。 例如将它设为
          ‘str’ 将使得选项名称变得大小写敏感:

               cfgparser = ConfigParser()
               cfgparser.optionxform = str

          请注意当读取配置文件时，选项名称两边的空格将在调用 *note
          optionxform(): 1fb5. 之前被去除。

      -- 成員函式: readfp (fp, filename=None)

          3.2 版後已棄用: 使用 *note read_file(): 1fbc. 来代替。

          3.2 版更變: *note readfp(): 1fbd. 现在将在 `fp' 上执行迭代而不
          是调用 ‘fp.readline()’。

          对于调用 *note readfp(): 1fbd. 时传入不支持迭代的参数的现有代
          码，可以在文件类对象外使用以下生成器作为包装器:

               def readline_generator(fp):
                   line = fp.readline()
                   while line:
                       yield line
                       line = fp.readline()

          不再使用 ‘parser.readfp(fp)’ 而是改用
          ‘parser.read_file(readline_generator(fp))’。

 -- Data: configparser.MAX_INTERPOLATION_DEPTH

     当 `raw' 形参为假值时 ‘get()’ 所采用的递归插值的最大深度。 这只在使
     用默认的 `interpolation' 时会起作用。


File: python.info,  Node: RawConfigParser 对象,  Next: 异常<5>,  Prev: ConfigParser 对象,  Up: configparser --- 配置文件解析器

5.14.2.10 RawConfigParser 对象
..............................

 -- 類別: 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])

     旧式 *note ConfigParser: 5a4.。 它默认禁用插值并且允许通过不安全的
     ‘add_section’ 和 ‘set’ 方法以及旧式 ‘defaults=’ 关键字参数处理来设
     置非字符串的节名、选项名和值。

     3.8 版更變: 默认的 `dict_type' 为 *note dict: 164.，因为它现在会保
     留插入顺序。

          備註: 考虑改用 *note ConfigParser: 5a4.，它会检查内部保存的值
          的类型。 如果你不想要插值，你可以使用
          ‘ConfigParser(interpolation=None)’。

      -- 成員函式: add_section (section)

          向实例添加一个名为 `section' 的节。 如果给定名称的节已存在，将
          会引发 *note DuplicateSectionError: cd0.。 如果传入了 `default
          section' 名称，则会引发 *note ValueError: 16d.。

          不检查 `section' 以允许用户创建以非字符串命名的节。 此行为已不
          受支持并可能导致内部错误。

      -- 成員函式: set (section, option, value)

          如果给定的节存在，则将给定的选项设为指定的值；在其他情况下将引
          发 *note NoSectionError: 1fc0.。 虽然可能使用 *note
          RawConfigParser: 95c. (或使用 *note ConfigParser: 5a4. 并将
          `raw' 形参设为真值) 以便实现非字符串值的 `internal' 存储，但是
          完整功能（包括插值和输出到文件）只能使用字符串值来实现。

          此方法允许用户在内部将非字符串值赋给键。 此行为已不受支持并会
          在尝试写入到文件或在非原始模式下获取数据时导致错误。 `请使用映
          射协议 API'，它不允许出现这样的赋值。


File: python.info,  Node: 异常<5>,  Prev: RawConfigParser 对象,  Up: configparser --- 配置文件解析器

5.14.2.11 异常
..............

 -- 例外: configparser.Error

     所有其他 *note configparser: 22. 异常的基类。

 -- 例外: configparser.NoSectionError

     当找不到指定节时引发的异常。

 -- 例外: configparser.DuplicateSectionError

     当调用 ‘add_section()’ 时传入已存在的节名称，或者在严格解析器中当单
     个输入文件、字符串或字典内出现重复的节时引发的异常。

     3.2 版新加入: 将可选的 ‘source’ 和 ‘lineno’ 属性和参数添加到 *note
     __init__(): e23.。

 -- 例外: configparser.DuplicateOptionError

     当单个选项在从单个文件、字符串或字典读取时出现两次时引发的异常。 这
     会捕获拼写错误和大小写敏感相关的错误，例如一个字典可能包含两个键分
     别代表同一个大小写不敏感的配置键。

 -- 例外: configparser.NoOptionError

     当指定的选项未在指定的节中被找到时引发的异常。

 -- 例外: configparser.InterpolationError

     当执行字符串插值发生问题时所引发的异常的基类。

 -- 例外: configparser.InterpolationDepthError

     当字符串插值由于迭代次数超出 *note MAX_INTERPOLATION_DEPTH: 1fc3. 而
     无法完成所引发的异常。 为 *note InterpolationError: 1fcb. 的子类。

 -- 例外: configparser.InterpolationMissingOptionError

     当从某个值引用的选项并不存在时引发的异常。 为 *note
     InterpolationError: 1fcb. 的子类。

 -- 例外: configparser.InterpolationSyntaxError

     当将要执行替换的源文本不符合要求的语法时引发的异常。 为 *note
     InterpolationError: 1fcb. 的子类。

 -- 例外: configparser.MissingSectionHeaderError

     当尝试解析一个不带节标头的文件时引发的异常。

 -- 例外: configparser.ParsingError

     当尝试解析一个文件而发生错误时引发的异常。

     3.2 版更變: ‘filename’ 属性和 *note __init__(): e23. 参数被重命名为
     ‘source’ 以保持一致性。

註解
....


File: python.info,  Node: netrc --- netrc 文件处理,  Next: xdrlib --- 编码与解码 XDR 数据,  Prev: configparser --- 配置文件解析器,  Up: 檔案格式

5.14.3 ‘netrc’ — netrc 文件处理
-------------------------------

`源代码:' Lib/netrc.py(1)

__________________________________________________________________

*note netrc: 11d5. 类解析并封装了 Unix 的 ‘ftp’ 程序和其他 FTP 客户端所
使用的 netrc 文件格式。

 -- 類別: netrc.netrc ([file])

     *note netrc: 11d5. 的实例或其子类的实例会被用来封装来自 netrc 文件
     的数据。 如果有初始化参数，它将指明要解析的文件。 如果未给出参数，
     则位于用户家目录的 ‘.netrc’ 文件 – 即 *note os.path.expanduser():
     32c. 所确定的文件 – 将会被读取。 在其他情况下，则将引发 *note
     FileNotFoundError: 8ad. 异常。 解析错误将引发 *note
     NetrcParseError: 1fd3. 并附带诊断信息，包括文件名、行号以及终止令牌
     。 如果在 POSIX 系统上未指明参数，则当 ‘.netrc’ 文件中有密码时，如
     果文件归属或权限不安全（归属的用户不是运行进程的用户，或者可供任何
     其他用户读取或写入）将引发 *note NetrcParseError: 1fd3.。 这实现了
     与 ftp 和其他使用 ‘.netrc’ 的程序同等的安全行为。

     3.4 版更變: 添加了 POSIX 权限检查。

     3.7 版更變: 当未将 `file' 作为参数传入时会使用 *note
     os.path.expanduser(): 32c. 来查找 ‘.netrc’ 文件的位置。

 -- 例外: netrc.NetrcParseError

     当在源文本中遇到语法错误时由 *note netrc: 11d5. 类引发的异常。 此异
     常的实例提供了三个有用属性: ‘msg’ 为错误的文本说明，‘filename’ 为源
     文件的名称，而 ‘lineno’ 给出了错误所在的行号。

* Menu:

* netrc 对象::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/netrc.py


File: python.info,  Node: netrc 对象,  Up: netrc --- netrc 文件处理

5.14.3.1 netrc 对象
...................

*note netrc: 11d5. 实例具有下列方法:

 -- 成員函式: netrc.authenticators (host)

     针对 `host' 的身份验证者返回一个 3 元组 ‘(login, account,
     password)’。 如果 netrc 文件不包含针对给定主机的条目，则返回关联到
     ’default’ 条目的元组。 如果匹配的主机或默认条目均不可用，则返回
     ‘None’。

 -- 成員函式: netrc.__repr__ ()

     将类数据以 netrc 文件的格式转储为一个字符串。 （这会丢弃注释并可能
     重排条目顺序。）

*note netrc: 11d5. 的实例具有一些公共实例变量:

 -- 屬性: netrc.hosts

     将主机名映射到 ‘(login, account, password)’ 元组的字典。 如果存在
     ’default’ 条目，则会表示为使用该名称的伪主机。

 -- 屬性: netrc.macros

     将宏名称映射到字符串列表的字典。

     備註: 密码会被限制为 ASCII 字符集的一个子集。 所有 ASCII 标点符号均
     可用作密码，但是要注意空白符和非打印字符不允许用作密码。 这是
     .netrc 文件解析方式带来的限制，在未来可能会被解除。


File: python.info,  Node: xdrlib --- 编码与解码 XDR 数据,  Next: plistlib --- 生成与解析 Apple plist 文件,  Prev: netrc --- netrc 文件处理,  Up: 檔案格式

5.14.4 ‘xdrlib’ — 编码与解码 XDR 数据
-------------------------------------

`源代码:' Lib/xdrlib.py(1)

__________________________________________________________________

*note xdrlib: 13b. 模块为外部数据表示标准提供支持，该标准的描述见 RFC
1014(2)，由 Sun Microsystems, Inc. 在 1987 年 6 月撰写。 它支持该 RFC 中
描述的大部分数据类型。

*note xdrlib: 13b. 模块定义了两个类，一个用于将变量打包为 XDR 表示形式，
另一个用于从 XDR 表示形式解包。 此外还有两个异常类。

 -- 類別: xdrlib.Packer

     *note Packer: 1fdc. 是用于将数据打包为 XDR 表示形式的类。 *note
     Packer: 1fdc. 类的实例化不附带参数。

 -- 類別: xdrlib.Unpacker (data)

     ‘Unpacker’ 是用于相应地从字符串缓冲区解包 XDR 数据值的类。 输入缓冲
     区将作为 `data' 给出。

也參考
......

RFC 1014(3) - XDR: 外部数据表示标准

     这个 RFC 定义了最初编写此模块时 XDR 所用的数据编码格式。 显然它已被
     RFC 1832(4) 所淘汰。

RFC 1832(5) - XDR: 外部数据表示标准

     更新的 RFC，它提供了经修订的 XDR 定义。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/xdrlib.py

   (2) https://tools.ietf.org/html/rfc1014.html

   (3) https://tools.ietf.org/html/rfc1014.html

   (4) https://tools.ietf.org/html/rfc1832.html

   (5) https://tools.ietf.org/html/rfc1832.html


File: python.info,  Node: Packer 对象,  Next: Unpacker 对象,  Up: xdrlib --- 编码与解码 XDR 数据

5.14.4.1 Packer 对象
....................

*note Packer: 1fdc. 实例具有下列方法:

 -- 成員函式: Packer.get_buffer ()

     将当前打包缓冲区以字符串的形式返回。

 -- 成員函式: Packer.reset ()

     将打包缓冲区重置为空字符串。

总体来说，你可以通过调用适当的 ‘pack_type()’ 方法来打包任何最常见的 XDR
数据类型。 每个方法都是接受单个参数，即要打包的值。 受支持的简单数据类型
打包方法如下: ‘pack_uint()’, ‘pack_int()’, ‘pack_enum()’, ‘pack_bool()’,
‘pack_uhyper()’ 以及 ‘pack_hyper()’。

 -- 成員函式: Packer.pack_float (value)

     打包单精度浮点数 `value'。

 -- 成員函式: Packer.pack_double (value)

     打包双精度浮点数 `value'。

以下方法支持打包字符串、字节串以及不透明数据。

 -- 成員函式: Packer.pack_fstring (n, s)

     打包固定长度字符串 `s'。 `n' 为字符串的长度，但它 `不会' 被打包进数
     据缓冲区。 如有必要字符串会以空字节串填充以保证 4 字节对齐。

 -- 成員函式: Packer.pack_fopaque (n, data)

     打包固定长度不透明数据流，类似于 *note pack_fstring(): 1fe4.。

 -- 成員函式: Packer.pack_string (s)

     打包可变长度字符串 `s'。 先将字符串的长度打包为无符号整数，再用
     *note pack_fstring(): 1fe4. 来打包字符串数据。

 -- 成員函式: Packer.pack_opaque (data)

     打包可变长度不透明数据流，类似于 *note pack_string(): 1fe6.。

 -- 成員函式: Packer.pack_bytes (bytes)

     打包可变长度字节流，类似于 *note pack_string(): 1fe6.。

下列方法支持打包数组和列表:

 -- 成員函式: Packer.pack_list (list, pack_item)

     打包由同质条目构成的 `list'。 此方法适用于不确定长度的列表；即其长
     度无法在遍历整个列表之前获知。 对于列表中的每个条目，先打包一个无符
     号整数 ‘1’，再添加列表中数据的值。 `pack_item' 是在打包单个条目时要
     调用的函数。 在列表的末尾，会再打包一个无符号整数 ‘0’。

     例如，要打包一个整数列表，代码看起来会是这样:

          import xdrlib
          p = xdrlib.Packer()
          p.pack_list([1, 2, 3], p.pack_int)

 -- 成員函式: Packer.pack_farray (n, array, pack_item)

     打包由同质条目构成的固定长度列表 (`array')。 `n' 为列表长度；它 `不
     会' 被打包到缓冲区，但是如果 ‘len(array)’ 不等于 `n' 则会引发 *note
     ValueError: 16d.。 如上所述，`pack_item' 是在打包每个元素时要使用的
     函数。

 -- 成員函式: Packer.pack_array (list, pack_item)

     打包由同质条目构成的可变长度 `list'。 先将列表的长度打包为无符号整
     数，再像上面的 *note pack_farray(): 1fea. 一样打包每个元素。


File: python.info,  Node: Unpacker 对象,  Next: 异常<6>,  Prev: Packer 对象,  Up: xdrlib --- 编码与解码 XDR 数据

5.14.4.2 Unpacker 对象
......................

*note Unpacker: 1fdd. 类提供以下方法:

 -- 成員函式: Unpacker.reset (data)

     使用给定的 `data' 重置字符串缓冲区。

 -- 成員函式: Unpacker.get_position ()

     返回数据缓冲区中的当前解包位置。

 -- 成員函式: Unpacker.set_position (position)

     将数据缓冲区的解包位置设为 `position'。 你应当小心使用 *note
     get_position(): 1fef. 和 *note set_position(): 1ff0.。

 -- 成員函式: Unpacker.get_buffer ()

     将当前解包数据缓冲区以字符串的形式返回。

 -- 成員函式: Unpacker.done ()

     表明解包完成。 如果数据没有全部完成解包则会引发 *note Error: 1ff3.
     异常。

此外，每种可通过 *note Packer: 1fdc. 打包的数据类型都可通过 *note
Unpacker: 1fdd. 来解包。 解包方法的形式为 ‘unpack_type()’，并且不接受任
何参数。 该方法将返回解包后的对象。

 -- 成員函式: Unpacker.unpack_float ()

     解包单精度浮点数。

 -- 成員函式: Unpacker.unpack_double ()

     解包双精度浮点数，类似于 *note unpack_float(): 1ff4.。

此外，以下方法可用来解包字符串、字节串以及不透明数据:

 -- 成員函式: Unpacker.unpack_fstring (n)

     解包并返回固定长度字符串。 `n' 为期望的字符数量。 会预设以空字节串
     填充以保证 4 字节对齐。

 -- 成員函式: Unpacker.unpack_fopaque (n)

     解包并返回固定长度数据流，类似于 *note unpack_fstring(): 1ff6.。

 -- 成員函式: Unpacker.unpack_string ()

     解包并返回可变长度字符串。 先将字符串的长度解包为无符号整数，再用
     *note unpack_fstring(): 1ff6. 来解包字符串数据。

 -- 成員函式: Unpacker.unpack_opaque ()

     解包并返回可变长度不透明数据流，类似于 *note unpack_string():
     1ff8.。

 -- 成員函式: Unpacker.unpack_bytes ()

     解包并返回可变长度字节流，类似于 *note unpack_string(): 1ff8.。

下列方法支持解包数组和列表:

 -- 成員函式: Unpacker.unpack_list (unpack_item)

     解包并返回同质条目的列表。 该列表每次解包一个元素，先解包一个无符号
     整数旗标。 如果旗标为 ‘1’，则解包条目并将其添加到列表。 旗标为 ‘0’
     表明列表结束。 `unpack_item' 为在解包条目时调用的函数。

 -- 成員函式: Unpacker.unpack_farray (n, unpack_item)

     解包并（以列表形式）返回由同质条目构成的固定长度数组。 `n' 为期望的
     缓冲区内列表元素数量。 如上所述，`unpack_item' 是解包每个元素时要使
     用的函数。

 -- 成員函式: Unpacker.unpack_array (unpack_item)

     解包并返回由同质条目构成的可变长度 `list'。 先将列表的长度解包为无
     符号整数，再像上面的 *note unpack_farray(): 1ffc. 一样解包每个元素
     。


File: python.info,  Node: 异常<6>,  Prev: Unpacker 对象,  Up: xdrlib --- 编码与解码 XDR 数据

5.14.4.3 异常
.............

此模块中的异常会表示为类实例代码:

 -- 例外: xdrlib.Error

     基本异常类。 *note Error: 1ff3. 具有一个公共属性 ‘msg’，其中包含对
     错误的描述。

 -- 例外: xdrlib.ConversionError

     从 *note Error: 1ff3. 所派生的类。 不包含额外的实例变量。

以下是一个应该如何捕获这些异常的示例:

     import xdrlib
     p = xdrlib.Packer()
     try:
         p.pack_double(8.01)
     except xdrlib.ConversionError as instance:
         print('packing the double failed:', instance.msg)


File: python.info,  Node: plistlib --- 生成与解析 Apple plist 文件,  Prev: xdrlib --- 编码与解码 XDR 数据,  Up: 檔案格式

5.14.5 ‘plistlib’ — 生成与解析 Apple ‘.plist’ 文件
--------------------------------------------------

`源代码:' Lib/plistlib.py(1)

__________________________________________________________________

此模块提供了可读写 Apple "property list" 文件的接口，它主要用于 macOS 和
iOS 系统。 此模块同时支持二进制和 XML plist 文件。

property list (‘.plist’) 文件格式是一种简单的序列化格式，它支持一些基本
对象类型，例如字典、列表、数字和字符串等。 通常使用一个字典作为最高层级
对象。

要写入和解析 plist 文件，请使用 *note dump(): 220. 和 *note load(): 21e.
函数。

要以字节串对象形式操作 plist 数据，请使用 *note dumps(): 221. 和 *note
loads(): 21f.。

值可以为字符串、整数、浮点数、布尔值、元组、列表、字典（但只允许用字符串
作为键）、*note bytes: 172.、*note bytearray: 173. 或 *note
datetime.datetime: 19f. 对象。

3.4 版更變: 新版 API，旧版 API 已被弃用。 添加了对二进制 plist 格式的支
持。

3.8 版更變: 添加了在二进制 plist 中读写 *note UID: 33e. 令牌的支持，例如
用于 NSKeyedArchiver 和 NSKeyedUnarchiver。

3.9 版更變: 旧 API 已被移除。

也參考
......

PList 指南页面(2)

     针对该文件格式的 Apple 文档。

这个模块定义了以下函数：

 -- 函式: plistlib.load (fp, *, fmt=None, dict_type=dict)

     读取 plist 文件。 `fp' 应当可读并且为二进制文件对象。 返回已解包的
     根对象（通常是一个字典）。

     `fmt' 为文件的格式，有效的值如下:

        * *note None: 203.: 自动检测文件格式

        * *note FMT_XML: 976.: XML 文件格式

        * *note FMT_BINARY: 977.: 二进制 plist 格式

     `dict_type' 为字典用来从 plist 文件读取的类型。

     *note FMT_XML: 976. 格式的 XML 数据 会使用来自 *note
     xml.parsers.expat: 141. 的 Expat 解析器 – 请参阅其文档了解错误格式
     XML 可能引发的异常。 未知元素将被 plist 解析器直接略过。

     当文件无法被解析时二进制格式的解析器将引发 ‘InvalidFileException’。

     3.4 版新加入.

 -- 函式: plistlib.loads (data, *, fmt=None, dict_type=dict)

     从一个 bytes 对象加载 plist。 参阅 *note load(): 21e. 获取相应关键
     字参数的说明。

     3.4 版新加入.

 -- 函式: plistlib.dump (value, fp, *, fmt=FMT_XML, sort_keys=True,
          skipkeys=False)

     将 `value' 写入 plist 文件。 `Fp' 应当可写并且为二进制文件对象。

     `fmt' 参数指定 plist 文件的格式，可以是以下值之一:

        * *note FMT_XML: 976.: XML 格式的 plist 文件

        * *note FMT_BINARY: 977.: 二进制格式的 plist 文件

     当 `sort_keys' 为真值（默认）时字典的键将经过排序再写入 plist，否则
     将按字典的迭代顺序写入。

     当 `skipkeys' 为假值（默认）时该函数将在字典的键不为字符串时引发
     *note TypeError: 1fe.，否则将跳过这样的键。

     如果对象是不受支持的类型或者是包含不受支持类型的对象的容器则将引发
     *note TypeError: 1fe.。

     对于无法在（二进制）plist 文件中表示的整数值，将会引发 *note
     OverflowError: a41.。

     3.4 版新加入.

 -- 函式: plistlib.dumps (value, *, fmt=FMT_XML, sort_keys=True,
          skipkeys=False)

     将 `value' 以 plist 格式字节串对象的形式返回。 参阅 *note dump():
     220. 的文档获取此函数的关键字参数的说明。

     3.4 版新加入.

可以使用以下的类:

 -- 類別: plistlib.UID (data)

     包装一个 *note int: 204.。 该类将在读取或写入 NSKeyedArchiver 编码
     的数据时被使用，其中包含 UID（参见 PList 指南）。

     It has one attribute, ‘data’, which can be used to retrieve the int
     value of the UID. ‘data’ must be in the range ‘0 <= data < 2**64’.

     3.8 版新加入.

可以使用以下的常量:

 -- Data: plistlib.FMT_XML

     用于 plist 文件的 XML 格式。

     3.4 版新加入.

 -- Data: plistlib.FMT_BINARY

     用于 plist 文件的二进制格式。

     3.4 版新加入.

* Menu:

* 示例: 示例<14>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/plistlib.py

   (2) 
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/PropertyLists/


File: python.info,  Node: 示例<14>,  Up: plistlib --- 生成与解析 Apple plist 文件

5.14.5.1 示例
.............

生成一个 plist:

     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)

解析一个 plist:

     with open(fileName, 'rb') as fp:
         pl = load(fp)
     print(pl["aKey"])


File: python.info,  Node: 加密服务,  Next: 通用操作系统服务,  Prev: 檔案格式,  Up: Python 標準函式庫 Standard Library

5.15 加密服务
=============

本章中描述的模块实现了加密性质的各种算法。 它们可以在安装时自行选择。 在
Unix 系统上，*note crypt: 28. 模块也可以使用。 以下是为内容概要：

* Menu:

* hashlib: hashlib --- 安全哈希与消息摘要. 安全哈希与消息摘要
* hmac: hmac --- 基于密钥的消息验证. 基于密钥的消息验证
* secrets: secrets --- 產生用於管理機密的安全亂數. 產生用於管理機密的安全亂數


File: python.info,  Node: hashlib --- 安全哈希与消息摘要,  Next: hmac --- 基于密钥的消息验证,  Up: 加密服务

5.15.1 ‘hashlib’ — 安全哈希与消息摘要
-------------------------------------

`源码：' Lib/hashlib.py(1)

__________________________________________________________________

这个模块针对不同的安全哈希和消息摘要算法实现了一个通用的接口。包括 FIPS
的 SHA1, SHA224, SHA256, SHA384, and SHA512 (定义于 FIPS 180-2) 算法，以
及 RSA 的 MD5 算法( 定义于 Internet RFC 1321(2))。术语“安全哈希”和“消息
摘要”是可互换的，较旧的算法被称为消息摘要，现代术语是安全哈希。

     備註: 如果你想找到 adler32 或 crc32 哈希函数，它们在 *note zlib:
     14d. 模块中。

     警告: 有些算法已知存在哈希碰撞弱点，请参考最后的“另请参阅”段。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/hashlib.py

   (2) https://tools.ietf.org/html/rfc1321.html


File: python.info,  Node: 哈希算法,  Next: SHAKE 可变长度摘要,  Up: hashlib --- 安全哈希与消息摘要

5.15.1.1 哈希算法
.................

每种类型的 `hash' 都有一个构造器方法。 它们都返回一个具有相同的简单接口
的 hash 对象。 例如，使用 use ‘sha256()’ 创建一个 SHA-256 hash 对象。 你
可以使用 ‘update()’ 方法向这个对象输入 *note 字节类对象: 6df. (通常是
*note bytes: 172.)。 在任何时候你都可以使用 ‘digest()’ 或 ‘hexdigest()’
方法获得到目前为止输入这个对象的拼接数据的 `digest'。

     備註: 为了更好的多线程性能，在对象创建或者更新时，若数据大于2047字
     节则 Python 的 *note GIL: 20e. 会被释放。

     備註: 向 ‘update()’ 输入字符串对象是不被支持的，因为哈希基于字节而
     非字符。

此模块中总是可用的哈希算法构造器有 ‘sha1()’, ‘sha224()’, ‘sha256()’,
‘sha384()’, ‘sha512()’, *note blake2b(): 646. 和 *note blake2s(): 647.。
‘md5()’ 通常也是可用的，但如果你在使用少见的 "FIPS 兼容" 的 Python 编译
版本则可能会找不到它。 此外还可能有一些附加的算法，具体取决于你的平台上
的 Python 所使用的 OpenSSL 库。 在大部分平台上可用的还有 ‘sha3_224()’,
‘sha3_256()’, ‘sha3_384()’, ‘sha3_512()’, ‘shake_128()’, ‘shake_256()’ 等
等。·

3.6 版新加入: SHA3 (Keccak) 和 SHAKE 构造器 ‘sha3_224()’, ‘sha3_256()’,
‘sha3_384()’, ‘sha3_512()’, ‘shake_128()’, ‘shake_256()’.

3.6 版新加入: 添加了 *note blake2b(): 646. 和 *note blake2s(): 647. 。

3.9 版更變: 所有 hashlib 的构造器都接受仅限关键字参数 `usedforsecurity'
且其默认值为 ‘True’。 设为假值即允许在受限的环境中使用不安全且阻塞的哈希
算法。 ‘False’ 表示此哈希算法不可用于安全场景，例如用作非加密的单向压缩
函数。

现在 hashlib 会使用 OpenSSL 1.1.1 或更新版本的 SHA3 和 SHAKE。

例如，如果想获取字节串 ‘b'Nobody inspects the spammish repetition'’ 的摘
要:

     >>> 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

更简要的写法：

     >>> hashlib.sha224(b"Nobody inspects the spammish repetition").hexdigest()
     'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2'

 -- 函式: hashlib.new (name[, data], *, usedforsecurity=True)

     一个接受所希望的算法对应的字符串 `name' 作为第一个形参的通用构造器
     。 它还允许访问上面列出的哈希算法以及你的 OpenSSL 库可能提供的任何
     其他算法。 同名的构造器要比 *note new(): 1030. 更快所以应当优先使用
     。

使用 *note new(): 1030. 并附带由 OpenSSL 所提供了算法:

     >>> h = hashlib.new('sha256')
     >>> h.update(b"Nobody inspects the spammish repetition")
     >>> h.hexdigest()
     '031edd7d41651593c5fe5c006fa5752b37fddff7bc4e843aa6af0c950f4b9406'

Hashlib 提供下列常量属性：

 -- Data: hashlib.algorithms_guaranteed

     一个集合，其中包含此模块在所有平台上都保证支持的哈希算法的名称。 请
     注意 ’md5’ 也在此清单中，虽然某些上游厂商提供了一个怪异的排除了此算
     法的 "FIPS 兼容" Python 编译版本。

     3.2 版新加入.

 -- Data: hashlib.algorithms_available

     一个集合，其中包含在所运行的 Python 解释器上可用的哈希算法的名称。
     将这些名称传给 *note new(): 1030. 时将可被识别。 *note
     algorithms_guaranteed: dc2. 将总是它的一个子集。 同样的算法在此集合
     中可能以不同的名称出现多次（这是 OpenSSL 的原因）。

     3.2 版新加入.

下列值会以构造器所返回的哈希对象的常量属性的形式被提供:

 -- Data: hash.digest_size

     以字节表示的结果哈希对象的大小。

 -- Data: hash.block_size

     以字节表示的哈希算法的内部块大小。

hash 对象具有以下属性：

 -- 屬性: hash.name

     此哈希对象的规范名称，总是为小写形式并且总是可以作为 *note new():
     1030. 的形参用来创建另一个此类型的哈希对象。

     3.4 版更變: 该属性名称自被引入起即存在于 CPython 中，但在 Python
     3.4 之前并未正式指明，因此可能不存在于某些平台上。

哈希对象具有下列方法:

 -- 成員函式: hash.update (data)

     用 *note bytes-like object: 6df. 来更新哈希对象。 重复调用相当于单
     次调用并传入所有参数的拼接结果: ‘m.update(a); m.update(b)’ 等价于
     ‘m.update(a+b)’。

     3.1 版更變: 当使用 OpenSSL 提供的哈希算法在大于 2047 字节的数据上执
     行哈希更新时 Python GIL 会被释放以允许其他线程运行。

 -- 成員函式: hash.digest ()

     返回当前已传给 *note update(): 200e. 方法的数据摘要。 这是一个大小
     为 *note digest_size: 200c. 的字节串对象，字节串中可包含 0 至 255 的
     完整取值范围。

 -- 成員函式: hash.hexdigest ()

     类似于 *note digest(): 200f. 但摘要会以两倍长度字符串对象的形式返回
     ，其中仅包含十六进制数码。 这可以被用于在电子邮件或其他非二进制环境
     中安全地交换数据值。

 -- 成員函式: hash.copy ()

     返回哈希对象的副本（“克隆”）。 这可被用来高效地计算共享相同初始子串
     的数据的摘要。


File: python.info,  Node: SHAKE 可变长度摘要,  Next: 密钥派生,  Prev: 哈希算法,  Up: hashlib --- 安全哈希与消息摘要

5.15.1.2 SHAKE 可变长度摘要
...........................

‘shake_128()’ 和 ‘shake_256()’ 算法提供安全的 length_in_bits//2 至 128 或
256 位可变长度摘要。 为此，它们的摘要需指定一个长度。 SHAKE 算法不限制最
大长度。

 -- 成員函式: shake.digest (length)

     返回当前已传给 ‘update()’ 方法的数据摘要。 这是一个大小为 `length'
     的字节串对象，字节串中可包含 0 to 255 的完整取值范围。

 -- 成員函式: shake.hexdigest (length)

     类似于 *note digest(): 115d. 但摘要会以两倍长度字符串对象的形式返回
     ，其中仅包含十六进制数码。 这可以被用于在电子邮件或其他非二进制环境
     中安全地交换数据值。


File: python.info,  Node: 密钥派生,  Next: BLAKE2,  Prev: SHAKE 可变长度摘要,  Up: hashlib --- 安全哈希与消息摘要

5.15.1.3 密钥派生
.................

密钥派生和密钥延展算法被设计用于安全密码哈希。 ‘sha1(password)’ 这样的简
单算法无法防御暴力攻击。 好的密码哈希函数必须可以微调、放慢步调，并且包
含 加盐(1)。

 -- 函式: hashlib.pbkdf2_hmac (hash_name, password, salt, iterations,
          dklen=None)

     此函数提供 PKCS#5 基于密码的密钥派生函数 2。 它使用 HMAC 作为伪随机
     函数。

     字符串 `hash_name' 是要求用于 HMAC 的哈希摘要算法的名称，例如
     ’sha1’ 或 ’sha256’。 `password' 和 `salt' 会以字节串缓冲区的形式被
     解析。 应用和库应当将 `password' 限制在合理长度 (例如 1024)。
     `salt' 应当为适当来源例如 *note os.urandom(): 5cb. 的大约 16 个或更
     多的字节串数据。

     `iterations' 数值应当基于哈希算法和算力来选择。 在 2013 年时，建议
     至少为 100,000 次 SHA-256 迭代。

     `dklen' 为派生密钥的长度。 如果 `dklen' 为 ‘None’ 则会使用哈希算法
     `hash_name' 的摘要大小，例如 SHA-512 为 64。

          >>> import hashlib
          >>> dk = hashlib.pbkdf2_hmac('sha256', b'password', b'salt', 100000)
          >>> dk.hex()
          '0394a2ede332c9a13eb82e9b24631604c31df978b4e2f0fbd2c549944f9d79a5'

     3.4 版新加入.

          備註: 随同 OpenSSL 提供了一个快速的 `pbkdf2_hmac' 实现。
          Python 实现是使用 *note hmac: 8e. 的内联版本。 它的速度大约要
          慢上三倍并且不会释放 GIL。

 -- 函式: hashlib.scrypt (password, *, salt, n, r, p, maxmem=0,
          dklen=64)

     此函数提供基于密码加密的密钥派生函数，其定义参见 RFC 7914(2)。

     `password' 和 `salt' 必须为 *note 字节类对象: 6df.。 应用和库应当将
     `password' 限制在合理长度 (例如 1024)。 `salt' 应当为适当来源例如
     *note os.urandom(): 5cb. 的大约 16 个或更多的字节串数据。

     `n' 为 CPU/内存开销因子，`r' 为块大小，`p' 为并行化因子，`maxmem' 为
     内存限制 (OpenSSL 1.1.0 默认为 32 MiB)。 `dklen' 为派生密钥的长度。

     *note 可用性: 1491.: OpenSSL 1.1+。

     3.6 版新加入.

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Salt_%28cryptography%29

   (2) https://tools.ietf.org/html/rfc7914.html


File: python.info,  Node: BLAKE2,  Prev: 密钥派生,  Up: hashlib --- 安全哈希与消息摘要

5.15.1.4 BLAKE2
...............

BLAKE2(1) 是在 RFC 7693(2) 中定义的加密哈希函数，它有两种形式:

   * `BLAKE2b'，针对 64 位平台进行优化，并会生成长度介于 1 和 64 字节之
     间任意大小的摘要。

   * `BLAKE2s'，针对 8 至 32 位平台进行优化，并会生成长度介于 1 和 32 字
     节之间任意大小的摘要。

BLAKE2 支持 `keyed mode' (HMAC(3) 的更快速更简单的替代), `salted
hashing', `personalization' 和 `tree hashing'.

此模块的哈希对象遵循标准库 *note hashlib: 8c. 对象的 API。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://blake2.net

   (2) https://tools.ietf.org/html/rfc7693.html

   (3) 
https://en.wikipedia.org/wiki/Hash-based_message_authentication_code


File: python.info,  Node: 创建哈希对象,  Next: 常数<4>,  Up: BLAKE2

5.15.1.5 创建哈希对象
.....................

新哈希对象可通过调用构造器函数来创建:

 -- 函式: hashlib.blake2b (data=b'', *, digest_size=64, key=b'',
          salt=b'', person=b'', fanout=1, depth=1, leaf_size=0,
          node_offset=0, node_depth=0, inner_size=0, last_node=False,
          usedforsecurity=True)

 -- 函式: hashlib.blake2s (data=b'', *, digest_size=32, key=b'',
          salt=b'', person=b'', fanout=1, depth=1, leaf_size=0,
          node_offset=0, node_depth=0, inner_size=0, last_node=False,
          usedforsecurity=True)

这些函数返回用于计算 BLAKE2b 或 BLAKE2s 的相应的哈希对象。 它们接受下列
可选通用形参:

   * `data': 要哈希的初始数据块，它必须为 *note bytes-like object: 6df.。
     它只能作为位置参数传入。

   * `digest_size': 以字节数表示的输出摘要大小。

   * `key': 用于密钥哈希的密钥（对于 BLAKE2b 最长 64 字节，对于 BLAKE2s
     最长 32 字节）。

   * `salt': 用于随机哈希的盐值（对于 BLAKE2b 最长 16 字节，对于 BLAKE2s
     最长 8 字节）。

   * `person': 个性化字符串（对于 BLAKE2b 最长 16 字节，对于 BLAKE2s 最
     长 8 字节）。

下表显示了常规参数的限制（以字节为单位）：

Hash        目标长度        长度（键）   长度（盐）    长度（个人）
                                                       
-----------------------------------------------------------------------
                                                       
BLAKE2b     64              64           16            16
                                                       
                                                       
BLAKE2s     32              32           8             8
                                                       

     備註: BLAKE2 规格描述为盐值和个性化形参定义了固定的长度，但是为了方
     便起见，此实现接受指定在长度以内的任意大小的字节串。 如果形参长度小
     于指定值，它将以零值进行填充，因此举例来说，‘b'salt'’ 和
     ‘b'salt\x00'’ 为相同的值 (`key' 的情况则并非如此。)

如下面的模块 *note constants: 2016. 所描述，这些是可用的大小取值。

构造器函数还接受下列树形哈希形参:

   * `fanout': 扇出值 (0 至 255，如无限制即为 0，连续模式下为 1)。

   * `depth': 树的最大深度 (1 至 255，如无限制则为 255，连续模式下为 1)。

   * `leaf_size': maximal byte length of leaf (0 to ‘2**32-1’, 0 if
     unlimited or in sequential mode).

   * `node_offset': node offset (0 to ‘2**64-1’ for BLAKE2b, 0 to
     ‘2**48-1’ for BLAKE2s, 0 for the first, leftmost, leaf, or in
     sequential mode).

   * `node_depth': 节点深度 (0 至 255，对于叶子或在连续模式下则为 0)。

   * `inner_size': 内部摘要大小 (对于 BLAKE2b 为 0 至 64，对于 BLAKE2s 为
     0 至 32，连续模式下则为 0)。

   * `last_node': 一个布尔值，指明所处理的节点是否为最后一个 (连续模式下
     则为 ‘False’)。

[Explanation of tree mode parameters.]
Figure

请参阅 BLAKE2 规格描述(1) 第 2.10 节获取有关树形哈希的完整说明。

   ---------- Footnotes ----------

   (1) https://blake2.net/blake2_20130129.pdf


File: python.info,  Node: 常数<4>,  Next: 示例<15>,  Prev: 创建哈希对象,  Up: BLAKE2

5.15.1.6 常数
.............

 -- Data: blake2b.SALT_SIZE

 -- Data: blake2s.SALT_SIZE

盐值长度（构造器所接受的最大长度）。

 -- Data: blake2b.PERSON_SIZE

 -- Data: blake2s.PERSON_SIZE

个性化字符串长度（构造器所接受的最大长度）。

 -- Data: blake2b.MAX_KEY_SIZE

 -- Data: blake2s.MAX_KEY_SIZE

最大密钥长度。

 -- Data: blake2b.MAX_DIGEST_SIZE

 -- Data: blake2s.MAX_DIGEST_SIZE

哈希函数可输出的最大摘要长度。


File: python.info,  Node: 示例<15>,  Next: 开发人员,  Prev: 常数<4>,  Up: BLAKE2

5.15.1.7 示例
.............

* Menu:

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


File: python.info,  Node: 简单哈希,  Next: 使用不同的摘要大小,  Up: 示例<15>

5.15.1.8 简单哈希
.................

要计算某个数据的哈希值，你应该首先通过调用适当的构造器函数 (*note
blake2b(): 646. 或 *note blake2s(): 647.) 来构造一个哈希对象，然后通过在
该对象上调用 ‘update()’ 来更新目标数据，最后通过调用 ‘digest()’ (或针对
十六进制编码字符串的 ‘hexdigest()’) 来获取该对象的摘要。

     >>> from hashlib import blake2b
     >>> h = blake2b()
     >>> h.update(b'Hello world')
     >>> h.hexdigest()
     '6ff843ba685842aa82031d3f53c48b66326df7639a63d128974c5c14f31a0f33343a8c65551134ed1ae0f2b0dd2bb495dc81039e3eeb0aa1bb0388bbeac29183'

作为快捷方式，你可以直接以位置参数的形式向构造器传入第一个数据块来直接更
新:

     >>> from hashlib import blake2b
     >>> blake2b(b'Hello world').hexdigest()
     '6ff843ba685842aa82031d3f53c48b66326df7639a63d128974c5c14f31a0f33343a8c65551134ed1ae0f2b0dd2bb495dc81039e3eeb0aa1bb0388bbeac29183'

你可以多次调用 *note hash.update(): 200e. 至你所想要的任意次数以迭代地更
新哈希值:

     >>> from hashlib import blake2b
     >>> items = [b'Hello', b' ', b'world']
     >>> h = blake2b()
     >>> for item in items:
     ...     h.update(item)
     >>> h.hexdigest()
     '6ff843ba685842aa82031d3f53c48b66326df7639a63d128974c5c14f31a0f33343a8c65551134ed1ae0f2b0dd2bb495dc81039e3eeb0aa1bb0388bbeac29183'


File: python.info,  Node: 使用不同的摘要大小,  Next: 密钥哈希,  Prev: 简单哈希,  Up: 示例<15>

5.15.1.9 使用不同的摘要大小
...........................

BLAKE2 具有可配置的摘要大小，对于 BLAKE2b 最多 64 字节，对于 BLAKE2s 最
多 32 字节。 例如，要使用 BLAKE2b 来替代 SHA-1 而不改变输出大小，我们可
以让 BLAKE2b 产生 20 个字节的摘要:

     >>> 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

不同摘要大小的哈希对象具有完全不同的输出（较短哈希值 `并非' 较长哈希值的
前缀）；即使输出长度相同，BLAKE2b 和 BLAKE2s 也会产生不同的输出:

     >>> 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'


File: python.info,  Node: 密钥哈希,  Next: 随机哈希,  Prev: 使用不同的摘要大小,  Up: 示例<15>

5.15.1.10 密钥哈希
..................

Keyed hashing can be used for authentication as a faster and simpler
replacement for Hash-based message authentication code(1) (HMAC). BLAKE2
can be securely used in prefix-MAC mode thanks to the
indifferentiability property inherited from BLAKE.

这个例子演示了如何使用密钥 ‘b'pseudorandom key'’ 来为 ‘b'message data'’
获取一个（十六进制编码的）128 位验证代码:

     >>> from hashlib import blake2b
     >>> h = blake2b(key=b'pseudorandom key', digest_size=16)
     >>> h.update(b'message data')
     >>> h.hexdigest()
     '3d363ff7401e02026f4a4687d4863ced'

作为实际的例子，一个 Web 应用可为发送给用户的 cookies 进行对称签名，并在
之后对其进行验证以确保它们没有被篡改:

     >>> 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

即使存在原生的密钥哈希模式，BLAKE2 也同样可在 *note hmac: 8e. 模块的
HMAC 构造过程中使用:

     >>> import hmac, hashlib
     >>> m = hmac.new(b'secret key', digestmod=hashlib.blake2s)
     >>> m.update(b'message')
     >>> m.hexdigest()
     'e3c8102868d28b5ff85fc35dda07329970d1a01e273c37481326fe0c861c8142'

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/HMAC


File: python.info,  Node: 随机哈希,  Next: 个性化,  Prev: 密钥哈希,  Up: 示例<15>

5.15.1.11 随机哈希
..................

用户可通过设置 `salt' 形参来为哈希函数引入随机化。 随机哈希适用于防止对
数字签名中使用的哈希函数进行碰撞攻击。

     随机哈希被设计用来处理当一方（消息准备者）要生成由另一方（消息签名
     者）进行签名的全部或部分消息的情况。 如果消息准备者能够找到加密哈希
     函数的碰撞现象（即两条消息产生相同的哈希值），则他们就可以准备将产
     生相同哈希值和数字签名但却具有不同结果的有意义的消息版本（例如向某
     个账户转入 $1,000,000 而不是 $10）。 加密哈希函数的设计都是以防碰撞
     性能为其主要目标之一的，但是当前针对加密哈希函数的集中攻击可能导致
     特定加密哈希函数所提供的防碰撞性能低于预期。 随机哈希为签名者提供了
     额外的保护，可以降低准备者在数字签名生成过程中使得两条或更多条消息
     最终产生相同哈希值的可能性 — 即使为特定哈希函数找到碰撞现象是可行的
     。 但是，当消息的所有部分均由签名者准备时，使用随机哈希可能降低数字
     签名所提供的安全性。

     (NIST SP-800-106 "数字签名的随机哈希"(1))

在 BLAKE2 中，盐值会在初始化期间作为对哈希函数的一次性输入而不是对每个压
缩函数的输入来处理。

     警告: 使用 BLAKE2 或任何其他通用加密哈希函数例如 SHA-256 进行 `加盐
     哈希' (或纯哈希) 并不适用于哈希密码。 请参阅 BLAKE2 FAQ(2) 了解更多
     信息。

     >>> 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

   ---------- Footnotes ----------

   (1) https://csrc.nist.gov/publications/detail/sp/800-106/final

   (2) https://blake2.net/#qa


File: python.info,  Node: 个性化,  Next: 树形模式,  Prev: 随机哈希,  Up: 示例<15>

5.15.1.12 个性化
................

出于不同的目的强制让哈希函数为相同的输入生成不同的摘要有时也是有用的。 正
如 Skein 哈希函数的作者所言:

     我们建议所有应用设计者慎重考虑这种做法；我们已看到有许多协议在协议
     的某一部分中计算出来的哈希值在另一个完全不同的部分中也可以被使用，
     因为两次哈希计算是针对类似或相关的数据进行的，这样攻击者可以强制应
     用为相同的输入生成哈希值。 个性化协议中所使用的每个哈希函数将有效地
     阻止这种类型的攻击。

     (Skein 哈希函数族(1), p.  21)

BLAKE2 可通过向 `person' 参数传入字节串来进行个性化:

     >>> 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'

个性化配合密钥模式也可被用来从单个密钥派生出多个不同密钥。

     >>> 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=

   ---------- Footnotes ----------

   (1) http://www.skein-hash.info/sites/default/files/skein1.3.pdf


File: python.info,  Node: 树形模式,  Prev: 个性化,  Up: 示例<15>

5.15.1.13 树形模式
..................

以下是对包含两个叶子节点的最小树进行哈希的例子:

       10
      /  \
     00  01

这个例子使用 64 字节内部摘要，返回 32 字节最终摘要:

     >>> 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'


File: python.info,  Node: 开发人员,  Prev: 示例<15>,  Up: BLAKE2

5.15.1.14 开发人员
..................

BLAKE2(1) 是由 `Jean-Philippe Aumasson', `Samuel Neves', `Zooko
Wilcox-O’Hearn' 和 `Christian Winnerlein' 基于 `Jean-Philippe Aumasson',
`Luca Henzen', `Willi Meier' 和 `Raphael C.-W. Phan' 所创造的 SHA-3(2) 入
围方案 BLAKE(3) 进行设计的。

它使用的核心算法来自由 `Daniel J. Bernstein' 所设计的 ChaCha(4) 加密。

stdlib 实现是基于 pyblake2(5) 模块的。 它由 `Dmitry Chestnykh' 在
`Samuel Neves' 所编写的 C 实现的基础上编写。 此文档拷贝自 pyblake2(6) 并
由 `Dmitry Chestnykh' 撰写。

C 代码由 `Christian Heimes' 针对 Python 进行了部分的重写。

以下公共领域贡献同时适用于 C 哈希函数实现、扩展代码和本文档:

     在法律许可的范围内，作者已将此软件的全部版权以及关联和邻接权利贡献
     到全球公共领域。 此软件的发布不附带任何担保。

     你应该已收到此软件附带的 CC0 公共领域专属证书的副本。 如果没有，请
     参阅 ‘https://creativecommons.org/publicdomain/zero/1.0/’。

根据创意分享公共领域贡献 1.0 通用规范，下列人士为此项目的开发提供了帮助
或对公共领域的修改作出了贡献:

   * `Alexandr Sokolovskiy'

也參考
......

模块 *note hmac: 8e.

     使用哈希运算来生成消息验证代码的模块。

模块 *note base64: d.

     针对非二进制环境对二进制哈希值进行编辑的另一种方式。

‘https://blake2.net’

     BLAKE2 官方网站

‘https://csrc.nist.gov/csrc/media/publications/fips/180/2/archive/2002-08-01/documents/fips180-2.pdf’

     有关安全哈希算法的 FIPS 180-2 出版物。

‘https://en.wikipedia.org/wiki/Cryptographic_hash_function#Cryptographic_hash_algorithms’

     包含关于哪些算法存在已知问题以及对其使用所造成的影响的信息的
     Wikipedia 文章。

‘https://www.ietf.org/rfc/rfc2898.txt’

     PKCS #5: 基于密码的加密规范描述 2.0 版

   ---------- Footnotes ----------

   (1) https://blake2.net

   (2) https://en.wikipedia.org/wiki/NIST_hash_function_competition

   (3) https://131002.net/blake/

   (4) https://cr.yp.to/chacha.html

   (5) https://pythonhosted.org/pyblake2/

   (6) https://pythonhosted.org/pyblake2/


File: python.info,  Node: hmac --- 基于密钥的消息验证,  Next: secrets --- 產生用於管理機密的安全亂數,  Prev: hashlib --- 安全哈希与消息摘要,  Up: 加密服务

5.15.2 ‘hmac’ — 基于密钥的消息验证
----------------------------------

`源代码:' Lib/hmac.py(1)

__________________________________________________________________

此模块实现了 HMAC 算法，算法的描述参见 RFC 2104(2)。

 -- 函式: hmac.new (key, msg=None, digestmod='')

     返回一个新的 hmac 对象。 `key' 是一个指定密钥的 bytes 或 bytearray
     对象。 如果提供了 `msg'，将会调用 ‘update(msg)’ 方法。 `digestmod'
     为 HMAC 对象所用的摘要名称、摘要构造器或模块。 它可以是适用于 *note
     hashlib.new(): 1030. 的任何名称。 虽然该参数位置靠后，但它却是必须
     的。

     3.4 版更變: 形参 `key' 可以为 bytes 或 bytearray 对象。 形参 `msg'
     可以为 *note hashlib: 8c. 所支持的任意类型。 形参 `digestmod' 可以
     为某种哈希算法的名称。

     Deprecated since version 3.4, removed in version 3.8: MD5 作为
     `digestmod' 的隐式默认摘要已被弃用。 digestmod 形参现在是必须的。 请
     将其作为关键字参数传入以避免当你没有初始 msg 时将导致的麻烦。

 -- 函式: hmac.digest (key, msg, digest)

     基于给定密钥 `key' 和 `digest' 返回 `msg' 的摘要。 此函数等价于
     ‘HMAC(key, msg, digest).digest()’，但使用了优化的 C 或内联实现，对
     放入内存的消息能处理得更快。 形参 `key', `msg' 和 `digest' 具有与
     *note new(): 940. 中相同的含义。

     作为 CPython 的实现细节，优化的 C 实现仅当 `digest' 为字符串并且是
     一个 OpenSSL 所支持的摘要算法的名称时才会被使用。

     3.7 版新加入.

HMAC 对象具有下列方法:

 -- 成員函式: HMAC.update (msg)

     用 `msg' 来更新 hmac 对象。 重复调用相当于单次调用并传入所有参数的
     拼接结果: ‘m.update(a); m.update(b)’ 等价于 ‘m.update(a + b)’。

     3.4 版更變: 形参 `msg' 可以为 *note hashlib: 8c. 所支持的任何类型。

 -- 成員函式: HMAC.digest ()

     返回当前已传给 *note update(): 941. 方法的字节串数据的摘要。 这个字
     节串数据的长度将与传给构造器的摘要的长度 `digest_size' 相同。 它可
     以包含非 ASCII 的字节，包括 NUL 字节。

          警告: 在验证例程运行期间将 *note digest(): 496. 的输出与外部提
          供的摘要进行比较时，建议使用 *note compare_digest(): aea. 函数
          而不是 ‘==’ 运算符以减少定时攻击防御力的不足。

 -- 成員函式: HMAC.hexdigest ()

     类似于 *note digest(): 496. 但摘要会以两倍长度字符串的形式返回，其
     中仅包含十六进制数码。 这可以被用于在电子邮件或其他非二进制环境中安
     全地交换数据值。

          警告: 在验证例程运行期间将 *note hexdigest(): 202a. 的输出与外
          部提供的摘要进行比较时，建议使用 *note compare_digest(): aea.
          函数而不是 ‘==’ 运算符以减少定时攻击防御力的不足。

 -- 成員函式: HMAC.copy ()

     返回 hmac 对象的副本（“克隆）。 这可被用来高效地计算共享相同初始子
     串的数据的摘要。

hash 对象具有以下属性：

 -- 屬性: HMAC.digest_size

     以字节表示的结果 HMAC 摘要的大小。

 -- 屬性: HMAC.block_size

     以字节表示的哈希算法的内部块大小。

     3.4 版新加入.

 -- 屬性: HMAC.name

     HMAC 的规范名称，总是为小写形式，例如 ‘hmac-md5’。

     3.4 版新加入.

3.9 版後已棄用: 未写入文档的属性 ‘HMAC.digest_cons’, ‘HMAC.inner’ 和
‘HMAC.outer’ 属于内部实现细节，将在 Python 3.10 中被移除。

这个模块还提供了下列辅助函数:

 -- 函式: hmac.compare_digest (a, b)

     返回 ‘a == b’。 此函数使用一种经专门设计的方式通过避免基于内容的短
     路行为来防止定时分析，使得它适合处理密码。 `a' 和 `b' 必须为相同的
     类型：或者是 *note str: 205. (仅限 ASCII 字符，如 *note
     HMAC.hexdigest(): 202a. 的返回值)，或者是 *note bytes-like object:
     6df.。

          備註: 如果 `a' 和 `b' 具有不同的长度，或者如果发生了错误，定时
          攻击在理论上可以获取有关 `a' 和 `b' 的类型和长度信息 — 但不能
          获取它们的值。

     3.3 版新加入.

     3.9 版更變: 此函数在可能的情况下会在内部使用 OpenSSL 的
     ‘CRYPTO_memcmp()’。

也參考
......

模块 *note hashlib: 8c.

     提供安全哈希函数的 Python 模块。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/hmac.py

   (2) https://tools.ietf.org/html/rfc2104.html


File: python.info,  Node: secrets --- 產生用於管理機密的安全亂數,  Prev: hmac --- 基于密钥的消息验证,  Up: 加密服务

5.15.3 ‘secrets’ — 產生用於管理機密的安全亂數
---------------------------------------------

3.6 版新加入.

`原始碼:' Lib/secrets.py(1)

__________________________________________________________________

*note secrets: e4. 模組可用於產生高加密強度的亂數，適合用來管理諸如密碼
、帳號認證、安全性權杖（security tokens）這類資料，以及管理其他相關的機
密資料。

尤其應優先使用 *note secrets: e4. 作為預設來替代 *note random: dc. 模組
中的預設偽亂數產生器（pseudo-random number generator），該模組被設計用於
建模和模擬，而非用於安全性和加密。

也參考
......

PEP 506(2)

* Menu:

* 亂數::
* 產生權杖（token）::
* 其他函式::
* 應用技巧和典範實務（best practices）::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/secrets.py

   (2) https://www.python.org/dev/peps/pep-0506


File: python.info,  Node: 亂數,  Next: 產生權杖（token）,  Up: secrets --- 產生用於管理機密的安全亂數

5.15.3.1 亂數
.............

The *note secrets: e4. module provides access to the most secure source
of randomness that your operating system provides.

 -- 類別: secrets.SystemRandom

     一個用來產生亂數的類別，用的是作業系統提供的最高品質來源。 請參閱
     *note random.SystemRandom: 1c5f. 以獲取更多細節。

 -- 函式: secrets.choice (sequence)

     從一非空序列中，回傳一個隨機選取的元素。

 -- 函式: secrets.randbelow (n)

     回傳一個 [0, `n') 範圍之內的隨機整數。

 -- 函式: secrets.randbits (k)

     回傳一個具 `k' 個隨機位元的整數。


File: python.info,  Node: 產生權杖（token）,  Next: 其他函式,  Prev: 亂數,  Up: secrets --- 產生用於管理機密的安全亂數

5.15.3.2 產生權杖（token）
..........................

*note secrets: e4. 模組提供了一些產生安全性權杖的函式，適合用於諸如重設
密碼、難以猜測的 URL，或類似的應用。

 -- 函式: secrets.token_bytes ([nbytes=None])

     回傳一個隨機位元組字串，其中含有 `nbytes' 位元組的數字。 如果
     `nbytes' 為 ‘None’ 或未提供，則會使用一合理預設值。

          >>> token_bytes(16)
          b'\xebr\x17D*t\xae\xd4\xe3S\xb6\xe2\xebP1\x8b'

 -- 函式: secrets.token_hex ([nbytes=None])

     回傳一以十六進位表示的隨機字串。 字串具有 `nbytes' 個隨機位元組，每
     個位元組會轉成兩個十六進位的數字。 如果 `nbytes' 為 ‘None’ 或未提供
     ，則會使用一個合理的預設值。

          >>> token_hex(16)
          'f9bf78b9a18ce6d46a0cd2b0b86df9da'

 -- 函式: secrets.token_urlsafe ([nbytes=None])

     回傳一個 URL 安全的隨機文本字串，包含 `nbytes' 個隨機位元組。 文本
     將使用 Base64 編碼，因此平均來說每個位元組會對應到約 1.3 個字元。 如
     果 `nbytes' 為 ‘None’ 或未提供，則會使用一個合理的預設值。

          >>> token_urlsafe(16)
          'Drmhze6EPcv0fN_81Bj-nA'

* Menu:

* 權杖應當使用多少個位元組？::


File: python.info,  Node: 權杖應當使用多少個位元組？,  Up: 產生權杖（token）

5.15.3.3 權杖應當使用多少個位元組？
...................................

為了在面對 暴力攻擊(1) 時能保證安全，權杖必須具有足夠的隨機性。 不幸的是
，對隨機性是否足夠的標準，會隨著電腦越來越強大並能夠在更短時間內進行更多
猜測而不斷提高。 在 2015 年時，人們認為 32 位元組（256 位元）的隨機性對
於 *note secrets: e4. 模組所預期的一般使用場景來說是足夠的。

對於想自行管理權杖長度的使用者，你可以對各種 ‘token_*’ 函式明白地指定
*note int: 204. 引數（argument）來指定權杖要使用的隨機性程度。 該引數以
位元組數來表示要使用的隨機性程度。

否則，如未提供引數，或者如果引數為 ‘None’，則 ‘token_*’ 函式則會使用一個
合理的預設值。

     備註: 該預設值可能在任何時候被改變，包括在維護版本更新的時候。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Brute-force_attack


File: python.info,  Node: 其他函式,  Next: 應用技巧和典範實務（best practices）,  Prev: 產生權杖（token）,  Up: secrets --- 產生用於管理機密的安全亂數

5.15.3.4 其他函式
.................

 -- 函式: secrets.compare_digest (a, b)

     如果字串 `a' 與 `b' 相等則回傳 ‘True’，否則回傳 ‘False’，這樣的處理
     方式可降低 時序攻擊(1) 的風險。 請參閱 *note hmac.compare_digest():
     aea. 以了解更多細節。

   ---------- Footnotes ----------

   (1) https://codahale.com/a-lesson-in-timing-attacks/


File: python.info,  Node: 應用技巧和典範實務（best practices）,  Prev: 其他函式,  Up: secrets --- 產生用於管理機密的安全亂數

5.15.3.5 應用技巧和典範實務（best practices）
.............................................

本節展示了一些使用 *note secrets: e4. 來管理基本安全等級的應用技巧和典範
實務。

產生八個字元長的字母數字密碼：

     import string
     import secrets
     alphabet = string.ascii_letters + string.digits
     password = ''.join(secrets.choice(alphabet) for i in range(8))

     備註: 應用程式不能 以可復原的格式存儲密碼(1)，無論是用純文本還是經
     過加密。 它們應當先加鹽（salt），再使用高加密強度的單向（不可逆）雜
     湊函數來產生雜湊值。

產生十個字元長的字母數字密碼，其中包含至少一個小寫字母，至少一個大寫字母
以及至少三個數字:

     import string
     import secrets
     alphabet = string.ascii_letters + string.digits
     while True:
         password = ''.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

產生 XKCD 風格的 passphrase(2):

     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))

產生難以猜測的暫時性 URL，內含回復密碼時所用的一個安全性權杖：

     import secrets
     url = 'https://mydomain.com/reset=' + secrets.token_urlsafe()

   ---------- Footnotes ----------

   (1) http://cwe.mitre.org/data/definitions/257.html

   (2) https://xkcd.com/936/


File: python.info,  Node: 通用操作系统服务,  Next: 并发执行,  Prev: 加密服务,  Up: Python 標準函式庫 Standard Library

5.16 通用操作系统服务
=====================

本章中描述的各模块提供了在（几乎）所有的操作系统上可用的操作系统特性的接
口，例如文件和时钟。这些接口通常以 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 的外部函数库


File: python.info,  Node: os --- 多种操作系统接口,  Next: io --- 处理流的核心工具,  Up: 通用操作系统服务

5.16.1 ‘os’ — 多种操作系统接口
------------------------------

`源代码：' Lib/os.py(1)

__________________________________________________________________

本模块提供了一种使用与操作系统相关的功能的便捷式途径。 如果你只是想读写
一个文件，请参阅 *note open(): 16f.，如果你想操作文件路径，请参阅 *note
os.path: c5. 模块，如果你想读取通过命令行给出的所有文件中的所有行，请参
阅 *note fileinput: 7e. 模块。 为了创建临时文件和目录，请参阅 *note
tempfile: 103. 模块，对于高级文件和目录处理，请参阅 *note shutil: e9. 模
块。

关于这些函数的可用性的说明：

   * Python中所有依赖于操作系统的内置模块的设计都是这样，只要不同的操作
     系统某一相同的功能可用，它就使用相同的接口。例如，函数
     ‘os.stat(path)’ 以相同的格式返回关于 `path' 的状态信息（该格式源于
     POSIX 接口）。

   * 特定于某一操作系统的扩展通过操作 *note os: c4. 模块也是可用的，但是
     使用它们当然是对可移植性的一种威胁。

   * 所有接受路径或文件名的函数都同时支持字节串和字符串对象，并在返回路
     径或文件名时使用相应类型的对象作为结果。

   * 在 VxWorks 系统上，os.fork, os.execv 和 os.spawn*p* 不被支持。

     備註: 如果使用无效或无法访问的文件名与路径，或者其他类型正确但操作
     系统不接受的参数，此模块的所有函数都抛出 *note OSError: 304. （或者
     它的子类）。

 -- 例外: os.error

     内建的 *note OSError: 304. 异常的一个别名。

 -- Data: os.name

     导入的依赖特定操作系统的模块的名称。以下名称目前已注册: ‘'posix'’,
     ‘'nt'’, ‘'java'’.

     也參考
     ......

     *note sys.platform: 3d3. 有更详细的描述.  *note os.uname(): b38. 只
     给出系统提供的版本信息。

     *note platform: ce. 模块对系统的标识有更详细的检查。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/os.py


File: python.info,  Node: 文件名，命令行参数，以及环境变量。,  Next: 进程参数,  Up: os --- 多种操作系统接口

5.16.1.1 文件名，命令行参数，以及环境变量。
...........................................

在 Python 中，使用字符串类型表示文件名、命令行参数和环境变量。 在某些系
统上，在将这些字符串传递给操作系统之前，必须将这些字符串解码为字节。
Python 使用文件系统编码来执行此转换（请参阅 *note
sys.getfilesystemencoding(): 5ef. ）。

3.1 版更變: 在某些系统上，使用文件系统编码进行转换可能会失败。 在这种情
况下，Python 会使用 *note 代理转义编码错误处理器: 198a.，这意味着在解码
时，不可解码的字节被 Unicode 字符 U+DCxx 替换，并且这些字节在编码时再次
转换为原始字节。

文件系统编码必须保证成功解码小于 128 的所有字节。如果文件系统编码无法提
供此保证， API 函数可能会引发 UnicodeErrors 。


File: python.info,  Node: 进程参数,  Next: 创建文件对象,  Prev: 文件名，命令行参数，以及环境变量。,  Up: os --- 多种操作系统接口

5.16.1.2 进程参数
.................

这些函数和数据项提供了操作当前进程和用户的信息。

 -- 函式: os.ctermid ()

     返回与进程控制终端对应的文件名。

     *note 可用性: 1491.: Unix。

 -- Data: os.environ

     A *note mapping: c0b. object where keys and values are strings that
     represent the process environment.  For example, ‘environ['HOME']’
     is the pathname of your home directory (on some platforms), and is
     equivalent to ‘getenv("HOME")’ in C.

     这个映射是在第一次导入 *note os: c4. 模块时捕获的，通常作为 Python
     启动时处理 ‘site.py’ 的一部分。除了通过直接修改 ‘os.environ’ 之外，
     在此之后对环境所做的更改不会反映在 ‘os.environ’ 中。

     该映射除了可以用于查询环境外，还能用于修改环境。当该映射被修改时，
     将自动调用 *note putenv(): 1cd.。

     在Unix系统上，键和值会使用 *note sys.getfilesystemencoding(): 5ef.
     和 ‘'surrogateescape'’ 的错误处理。如果你想使用其他的编码，使用
     *note environb: c65.。

          備註: 直接调用 *note putenv(): 1cd. 并不会影响 ‘os.environ’，
          所以推荐直接修改 ‘os.environ’。

          備註: 在某些平台上，包括 FreeBSD 和 macOS，设置 ‘environ’ 可能
          导致内存泄漏。 请参阅 ‘putenv()’ 的系统文档。

     可以删除映射中的元素来删除对应的环境变量。当从 ‘os.environ’ 删除元
     素时，以及调用 ‘pop()’ 或 ‘clear()’ 之一时，将自动调用 *note
     unsetenv(): 1cc.。

     3.9 版更變: 已更新并支持了 PEP 584(1) 的合并 (‘|’) 和更新 (‘|=’) 运
     算符。

 -- Data: os.environb

     Bytes version of *note environ: c09.: a *note mapping: c0b. object
     where both keys and values are *note bytes: 172. objects
     representing the process environment.  *note environ: c09. and
     *note environb: c65. are synchronized (modifying *note environb:
     c65. updates *note environ: c09, and vice versa).

     只有在 *note supports_bytes_environ: c63. 为 ‘True’ 的时候 *note
     environb: c65. 才是可用的。

     3.2 版新加入.

     3.9 版更變: 已更新并支持了 PEP 584(2) 的合并 (‘|’) 和更新 (‘|=’) 运
     算符。

 -- 函式: os.chdir (path)

 -- 函式: os.fchdir (fd)

 -- 函式: os.getcwd ()

     以上函数请参阅 *note 文件和目录: 2046. 。

 -- 函式: os.fsencode (filename)

     将 *note 路径类: 472. `filename' 编码为文件系统编码，使用
     ‘'surrogateescape'’ 错误回调方法，在 Windows 上会使用 ‘'strict'’，
     *note bytes: 172. 类型则原样返回。

     *note fsdecode(): 5e8. 是此函数的逆向函数。

     3.2 版新加入.

     3.6 版更變: 增加对实现了 *note os.PathLike: 5e5. 接口的对象的支持。

 -- 函式: os.fsdecode (filename)

     将 *note 路径类: 472. `filename' 从文件系统编码方式解码，编码方式应
     使用的是 ‘'surrogateescape'’ 错误回调方法，在 Windows 上应使用的是
     ‘'strict'’ 方法。*note str: 205. 字符串则原样返回。

     *note fsencode(): 5e9. 是此函数的逆向函数。

     3.2 版新加入.

     3.6 版更變: 增加对实现了 *note os.PathLike: 5e5. 接口的对象的支持。

 -- 函式: os.fspath (path)

     返回路径的文件系统表示。

     如果传入的是 *note str: 205. 或 *note bytes: 172. 类型的字符串，将
     原样返回。否则 *note __fspath__(): 5e6. 将被调用，如果得到的是一个
     *note str: 205. 或 *note bytes: 172. 类型的对象，那就返回这个值。其
     他所有情况则会抛出 *note TypeError: 1fe.  异常。

     3.6 版新加入.

 -- 類別: os.PathLike

     某些对象用于表示文件系统中的路径（如 *note pathlib.PurePath: 235. 对
     象），本类是这些对象的 *note 抽象基类: c05.。

     3.6 版新加入.

      -- 成員函式: abstractmethod __fspath__ ()

          返回当前对象的文件系统表示。

          这个方法只应该返回一个 *note str: 205. 字符串或 *note bytes:
          172. 字节串，请优先选择 *note str: 205. 字符串。

 -- 函式: os.getenv (key, default=None)

     如果存在，返回环境变量 `key' 的值，否则返回 `default'。 `key' ，
     `default' 和返回值均为 str 字符串类型。

     在Unix系统上，键和值会使用 *note sys.getfilesystemencoding():
     5ef. 和‘‘’surrogateescape’‘‘ 错误处理进行解码。如果你想使用其他的编
     码，使用 *note os.getenvb(): c64.。

     *note 可用性: 1491.: 大部分的Unix系统，Windows。

 -- 函式: os.getenvb (key, default=None)

     如果存在环境变量 `key' 那么返回其值，否则返回 `default'。 `key' ，
     `default' 和返回值均为bytes字节串类型。

     *note getenvb(): c64. 仅在 *note supports_bytes_environ: c63. 为
     ‘True’ 时可用。

     *note 可用性: 1491.: 大部分的Unix系统。

     3.2 版新加入.

 -- 函式: os.get_exec_path (env=None)

     返回将用于搜索可执行文件的目录列表，与在外壳程序中启动一个进程时相
     似。指定的 `env' 应为用于搜索 PATH 的环境变量字典。默认情况下，当
     `env' 为 ‘None’ 时，将会使用 *note environ: c09. 。

     3.2 版新加入.

 -- 函式: os.getegid ()

     返回当前进程的有效组ID。对应当前进程执行文件的 "set id" 位。

     *note 可用性: 1491.: Unix。

 -- 函式: os.geteuid ()

     返回当前进程的有效用户ID。

     *note 可用性: 1491.: Unix。

 -- 函式: os.getgid ()

     返回当前进程的实际组ID。

     *note 可用性: 1491.: Unix。

 -- 函式: os.getgrouplist (user, group)

     返回该用户所在的组 ID 列表。可能 `group' 参数没有在返回的列表中，实
     际上用户应该也是属于该 `group'。`group' 参数一般可以从储存账户信息
     的密码记录文件中找到。

     *note 可用性: 1491.: Unix。

     3.3 版新加入.

 -- 函式: os.getgroups ()

     返回当前进程对应的组ID列表

     *note 可用性: 1491.: Unix。

          備註: 在 macOS 中，*note getgroups(): 204c. 会和其他 Unix 平台
          有所不同。 如果 Python 解释器是在 ‘10.5’ 或更早版本中部署的，
          则 *note getgroups(): 204c. 会返回与当前用户进程相关联的有效组
          ID 列表；该列表受限于系统预定义的条目数量，通常为 16，并且在适
          当的权限下还可通过调用 *note setgroups(): 204d. 来修改。 如果
          是在高于 ‘10.5’ 的版本中部署的，则 *note getgroups(): 204c. 会
          返回与进程的有效用户 ID 相关联的当前组访问列表；组访问列表可能
          会在进程的生命周期之内发生改变，它不会受对 *note setgroups():
          204d. 的调用影响，且其长度也不被限制为 16。 部署目标值
          ‘MACOSX_DEPLOYMENT_TARGET’ 可以通过 *note
          sysconfig.get_config_var(): a45. 来获取。

 -- 函式: os.getlogin ()

     返回通过控制终端进程进行登录的用户名。在多数情况下，使用 *note
     getpass.getuser(): 204f. 会更有效，因为后者会通过检查环境变量
     ‘LOGNAME’ 或 ‘USERNAME’ 来查找用户，再由
     ‘pwd.getpwuid(os.getuid())[0]’ 来获取当前用户 ID 的登录名。

     *note 可用性: 1491.: Unix, Windows。

 -- 函式: os.getpgid (pid)

     根据进程id `pid' 返回进程的组 ID 列表。如果 `pid' 为 0，则返回当前
     进程的进程组 ID 列表

     *note 可用性: 1491.: Unix。

 -- 函式: os.getpgrp ()

     返回当时进程组的ID

     *note 可用性: 1491.: Unix。

 -- 函式: os.getpid ()

     返回当前进程ID

 -- 函式: os.getppid ()

     返回父进程ID。当父进程已经结束，在Unix中返回的ID是初始进程(1)中的一
     个，在Windows中仍然是同一个进程ID，该进程ID有可能已经被进行进程所占
     用。

     *note 可用性: 1491.: Unix, Windows。

     3.2 版更變: 添加WIndows的支持。

 -- 函式: os.getpriority (which, who)

     获取程序调度优先级。`which' 参数值可以是 *note PRIO_PROCESS: 2054.，
     *note PRIO_PGRP: 2055.，或 *note PRIO_USER: 2056. 中的一个，`who' 是
     相对于 `which' (*note PRIO_PROCESS: 2054. 的进程标识符，*note
     PRIO_PGRP: 2055. 的进程组标识符和 *note PRIO_USER: 2056. 的用户
     ID)。当 `who' 为 0 时（分别）表示调用的进程，调用进程的进程组或调用
     进程所属的真实用户 ID。

     *note 可用性: 1491.: Unix。

     3.3 版新加入.

 -- Data: os.PRIO_PROCESS
 -- Data: os.PRIO_PGRP
 -- Data: os.PRIO_USER

     函数 *note getpriority(): b21. 和 *note setpriority(): b22. 的参数
     。

     *note 可用性: 1491.: Unix。

     3.3 版新加入.

 -- 函式: os.getresuid ()

     返回一个由 (ruid, euid, suid) 所组成的元组，分别表示当前进程的真实
     用户ID，有效用户ID和甲暂存用户ID。

     *note 可用性: 1491.: Unix。

     3.2 版新加入.

 -- 函式: os.getresgid ()

     返回一个由 (rgid, egid, sgid) 所组成的元组，分别表示当前进程的真实
     组ID，有效组ID和暂存组ID。

     *note 可用性: 1491.: Unix。

     3.2 版新加入.

 -- 函式: os.getuid ()

     返回当前进程的真实用户ID。

     *note 可用性: 1491.: Unix。

 -- 函式: os.initgroups (username, gid)

     调用系统 initgroups()，使用指定用户所在的所有值来初始化组访问列表，
     包括指定的组ID。

     *note 可用性: 1491.: Unix。

     3.2 版新加入.

 -- 函式: os.putenv (key, value)

     将名为 `key' 的环境变量值设置为 `value'。该变量名修改会影响由 *note
     os.system(): e86.， *note popen(): 3cb. ，*note fork(): a42. 和
     *note execv(): 2058. 发起的子进程。

     ‘os.environ’ 中的参数赋值会自动转换为对 *note putenv(): 1cd. 的调用
     。不过 *note putenv(): 1cd. 的调用不会更新 ‘os.environ’，因此最好使
     用 ‘os.environ’ 对变量赋值。

          備註: 在某些平台上，包括 FreeBSD 和 macOS，设置 ‘environ’ 可能
          导致内存泄漏。 请参阅 ‘putenv()’ 的系统文档。

     引发一个 *note 审计事件: fa1. ‘os.putenv’，附带参数 ‘key’, ‘value’。

     3.9 版更變: 该函数现在总是可用。

 -- 函式: os.setegid (egid)

     设置当前进程的有效组ID。

     *note 可用性: 1491.: Unix。

 -- 函式: os.seteuid (euid)

     设置当前进程的有效用户ID。

     *note 可用性: 1491.: Unix。

 -- 函式: os.setgid (gid)

     设置当前进程的组ID。

     *note 可用性: 1491.: Unix。

 -- 函式: os.setgroups (groups)

     将 `group' 参数值设置为与当进程相关联的附加组ID列表。`group' 参数必
     须为一个序列，每个元素应为每个组的数字ID。该操作通常只适用于超级用
     户。

     *note 可用性: 1491.: Unix。

          備註: 在 macOS 中，`groups' 的长度不能超过系统定义的最大有效组
          ID 数量，通常为 16。 对于未返回与调用 setgroups() 产生的相同组
          列表的情况，请参阅 *note getgroups(): 204c. 的文档。

 -- 函式: os.setpgrp ()

     根据已实现的版本（如果有）来调用系统 ‘setpgrp()’ 或 ‘setpgrp(0, 0)’
     。相关说明，请参考 Unix 手册。

     *note 可用性: 1491.: Unix。

 -- 函式: os.setpgid (pid, pgrp)

     使用系统调用 ‘setpgid()’，将 `pid' 对应进程的组ID设置为 `pgrp'。相
     关说明，请参考 Unix 手册。

     *note 可用性: 1491.: Unix。

 -- 函式: os.setpriority (which, who, priority)

     设置程序调度优先级。 `which' 的值为 *note PRIO_PROCESS: 2054, *note
     PRIO_PGRP: 2055. 或 *note PRIO_USER: 2056. 之一，而 `who' 会相对于
     `which' (*note PRIO_PROCESS: 2054. 的进程标识符, *note PRIO_PGRP:
     2055. 的进程组标识符和 *note PRIO_USER: 2056. 的用户 ID) 被解析。
     `who' 值为零 (分别) 表示调用进程，调用进程的进程组或调用进程的真实
     用户 ID。 `priority' 是范围在 -20 至 19 的值。 默认优先级为 0；较小
     的优先级数值会更优先被调度。

     *note 可用性: 1491.: Unix。

     3.3 版新加入.

 -- 函式: os.setregid (rgid, egid)

     设置当前进程的真实和有效组ID。

     *note 可用性: 1491.: Unix。

 -- 函式: os.setresgid (rgid, egid, sgid)

     设置当前进程的真实，有效和暂存组ID。

     *note 可用性: 1491.: Unix。

     3.2 版新加入.

 -- 函式: os.setresuid (ruid, euid, suid)

     设置当前进程的真实，有效和暂存用户ID。

     *note 可用性: 1491.: Unix。

     3.2 版新加入.

 -- 函式: os.setreuid (ruid, euid)

     设置当前进程的真实和有效用户ID。

     *note 可用性: 1491.: Unix。

 -- 函式: os.getsid (pid)

     调用系统调用 ‘getsid()’。相关说明，请参考 Unix 手册。

     *note 可用性: 1491.: Unix。

 -- 函式: os.setsid ()

     使用系统调用 ‘getsid()’。相关说明，请参考 Unix 手册。

     *note 可用性: 1491.: Unix。

 -- 函式: os.setuid (uid)

     设置当前进程的用户ID。

     *note 可用性: 1491.: Unix。

 -- 函式: os.strerror (code)

     根据 `code' 中的错误码返回错误消息。 在某些平台上当给出未知错误码时
     ‘strerror()’ 将返回 ‘NULL’ 并会引发 *note ValueError: 16d.。

 -- Data: os.supports_bytes_environ

     如果操作系统上原生环境类型是字节型则为 ‘True’ (例如在 Windows 上为
     ‘False’)。

     3.2 版新加入.

 -- 函式: os.umask (mask)

     设定当前数值掩码并返回之前的掩码。

 -- 函式: os.uname ()

     返回当前操作系统的识别信息。返回值是一个有5个属性的对象：

        * ‘sysname’ - 操作系统名

        * ‘nodename’ - 机器在网络上的名称（需要先设定）

        * ‘release’ - 操作系统发行信息

        * ‘version’ - 操作系统版本信息

        * ‘machine’ - 硬件标识符

     为了向后兼容，该对象也是可迭代的，像是一个按照 ‘sysname’，
     ‘nodename’，‘release’，‘version’，和 ‘machine’ 顺序组成的元组。

     有些系统会将 ‘nodename’ 截短为 8 个字符或截短至前缀部分；获取主机名
     的一个更好方式是 *note socket.gethostname(): 2064. 或甚至可以用
     ‘socket.gethostbyaddr(socket.gethostname())’。

     *note 可用性: 1491.: 较新的 Unix 版本。

     3.3 版更變: 返回结果的类型由元组变成一个类似元组的对象，同时具有命
     名的属性。

 -- 函式: os.unsetenv (key)

     取消设置（删除）名为 `key' 的环境变量。变量名的改变会影响由 *note
     os.system(): e86.，*note popen(): 3cb.，*note fork(): a42. 和 *note
     execv(): 2058. 触发的子进程。

     删除在 ‘os.environ’ 中的变量会自动转换为对 *note unsetenv(): 1cc. 的
     调用。但是 *note unsetenv(): 1cc. 不能更新 ‘os.environ’，因此最好直
     接删除 ‘os.environ’ 中的变量。

     引发一个 *note 审计事件: fa1. ‘os.unsetenv’，附带参数 ‘key’。

     3.9 版更變: 该函数现在总是可用，并且在 Windows 上也可用。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0584

   (2) https://www.python.org/dev/peps/pep-0584


File: python.info,  Node: 创建文件对象,  Next: 文件描述符操作,  Prev: 进程参数,  Up: os --- 多种操作系统接口

5.16.1.3 创建文件对象
.....................

这些函数创建新的 *note file objects: c14. 。（参见 *note open(): 758. 以
获取打开文件描述符的相关信息。）

 -- 函式: os.fdopen (fd, *args, **kwargs)

     返回打开文件描述符 `fd' 对应文件的对象。类似内建 *note open(): 16f.
     函数，二者接受同样的参数。不同之处在于 *note fdopen(): 1564. 第一个
     参数应该为整数。


File: python.info,  Node: 文件描述符操作,  Next: 文件和目录,  Prev: 创建文件对象,  Up: os --- 多种操作系统接口

5.16.1.4 文件描述符操作
.......................

这些函数对文件描述符所引用的 I/O 流进行操作。

文件描述符是一些小的整数，对应于当前进程所打开的文件。例如，标准输入的文
件描述符通常是0，标准输出是1，标准错误是2。之后被进程打开的文件的文件描
述符会被依次指定为3，4，5等。“文件描述符”这个词有点误导性，在 Unix 平台
中套接字和管道也被文件描述符所引用。

当需要时，可以用 *note fileno(): 2069. 可以获得 *note file object: c14.
所对应的文件描述符。需要注意的是，直接使用文件描述符会绕过文件对象的方法
，会忽略如数据内部缓冲等情况。

 -- 函式: os.close (fd)

     关闭文件描述符 `fd'。

          備註: 该功能适用于低级 I/O 操作，必须用于 *note os.open():
          758. 或 *note pipe(): 206a. 返回的文件描述符。若要关闭由内建函
          数 *note open(): 16f.、*note popen(): 3cb. 或 *note fdopen():
          1564. 返回的 "文件对象"，则应使用其相应的 *note close(): 1147.
          方法。

 -- 函式: os.closerange (fd_low, fd_high)

     关闭从 `fd_low' （包括）到 `fd_high' （排除）间的文件描述符，并忽略
     错误。类似（但快于）:

          for fd in range(fd_low, fd_high):
              try:
                  os.close(fd)
              except OSError:
                  pass

 -- 函式: os.copy_file_range (src, dst, count, offset_src=None,
          offset_dst=None)

     从文件描述符 `src' 复制 `count' 字节，从偏移量 `offset_src' 开始读
     取，到文件描述符 `dst'，从偏移量 `offset_dst' 开始写入。如果
     `offset_src' 为 None，则 `src' 将从当前位置开始读取；`offset_dst' 同
     理。`src' 和 `dst' 指向的文件必须处于相同的文件系统，否则将会抛出一
     个 *note errno: 184b. 被设为 *note errno.EXDEV: 206d. 的 *note
     OSError: 304. 。

     此复制的完成没有额外的从内核到用户空间再回到内核的数据转移花费。另
     外，一些文件系统可能实现额外的优化。完成复制就如同打开两个二进制文
     件一样。

     返回值是复制的字节的数目。这可能低于需求的数目。

     *note Availability: 1491.: Linux kernel >= 4.5 或 glibc >= 2.27。

     3.8 版新加入.

 -- 函式: os.device_encoding (fd)

     如果连接到终端，则返回一个与 `fd' 关联的设备描述字符，否则返回
     *note None: 203.。

 -- 函式: os.dup (fd)

     返回一个文件描述符 `fd' 的副本。该文件描述符的副本是 *note
     不可继承的: 8e7.。

     在 Windows 中，当复制一个标准流（0: stdin, 1: stdout, 2: stderr）时
     ，新的文件描述符是 *note 可继承的: 8e7.。

     3.4 版更變: 新的文件描述符现在是不可继承的。

 -- 函式: os.dup2 (fd, fd2, inheritable=True)

     把文件描述符 `fd' 复制为 `fd2'，必要时先关闭后者。返回 `fd2'。新的
     文件描述符默认是 *note 可继承的: 8e7.，除非在 `inheritable' 为
     ‘False’ 时，是不可继承的。

     3.4 版更變: 添加可选参数 `inheritable'。

     3.7 版更變: 成功时返回 `fd2'，以过去的版本中，总是返回 ‘None’。

 -- 函式: os.fchmod (fd, mode)

     将 `fd' 指定文件的权限状态修改为 `mode'。可以参考 *note chmod():
     b0f. 中列出 `mode' 的可用值。从Python 3.3开始，这相当于
     ‘os.chmod(fd, mode)’。

     引发一个 *note 审计事件: fa1. ‘os.chmod’，附带参数 ‘path’、‘mode’、
     ‘dir_fd’。

     *note 可用性: 1491.: Unix。

 -- 函式: os.fchown (fd, uid, gid)

     分别将 `fd' 指定文件的所有者和组 ID 修改为 `uid' 和 `gid' 的值。若
     不想变更其中的某个 ID，可将相应值设为 -1。参考 *note chown(): b10.。
     从 Python 3.3 开始，这相当于 ‘os.chown(fd, uid, gid)’。

     引发一个 *note 审计事件: fa1. ‘os.chown’，附带参数 ‘path’、‘uid’、
     ‘gid’、‘dir_fd’。

     *note 可用性: 1491.: Unix。

 -- 函式: os.fdatasync (fd)

     强制将文件描述符 `fd' 指定文件写入磁盘。不强制更新元数据。

     *note 可用性: 1491.: Unix。

          備註: 该功能在 MacOS 中不可用。

 -- 函式: os.fpathconf (fd, name)

     返回与打开的文件有关的系统配置信息。`name' 指定要查找的配置名称，它
     可以是字符串，是一个系统已定义的名称，这些名称定义在不同标准（
     POSIX.1，Unix 95，Unix 98 等）中。一些平台还定义了额外的其他名称。
     当前操作系统已定义的名称在 ‘pathconf_names’ 字典中给出。对于未包含
     在该映射中的配置名称，也可以传递一个整数作为 `name'。

     如果 `name' 是一个字符串且不是已定义的名称，将抛出 *note
     ValueError: 16d. 异常。如果当前系统不支持 `name' 指定的配置名称，即
     使该名称存在于 ‘pathconf_names’，也会抛出 *note OSError: 304. 异常
     ，错误码为 *note errno.EINVAL: 1104.。

     从 Python 3.3 起，此功能等价于 ‘os.pathconf(fd, name)’。

     *note 可用性: 1491.: Unix。

 -- 函式: os.fstat (fd)

     获取文件描述符 `fd' 的状态. 返回一个 *note stat_result: 11bf. 对象
     。

     从 Python 3.3 起，此功能等价于 ‘os.stat(fd)’。

     也參考
     ......

     *note stat(): 321. 函数。

 -- 函式: os.fstatvfs (fd)

     返回文件系统的信息，该文件系统是文件描述符 `fd' 指向的文件所在的文
     件系统，与 *note statvfs(): b1e. 一样。从 Python 3.3 开始，它等效于
     ‘os.statvfs(fd)’。

     *note 可用性: 1491.: Unix。

 -- 函式: os.fsync (fd)

     强制将文件描述符 `fd' 指向的文件写入磁盘。在 Unix，这将调用原生
     ‘fsync()’ 函数；在 Windows，则是 MS ‘_commit()’ 函数。

     如果要写入的是缓冲区内的 Python *note 文件对象: c14. `f'，请先执行
     ‘f.flush()’，然后执行 ‘os.fsync(f.fileno())’，以确保与 `f' 关联的所
     有内部缓冲区都写入磁盘。

     *note 可用性: 1491.: Unix, Windows。

 -- 函式: os.ftruncate (fd, length)

     截断文件描述符 `fd' 指向的文件，以使其最大为 `length' 字节。从
     Python 3.3 开始，它等效于 ‘os.truncate(fd, length)’。

     引发一个 *note 审计事件: fa1. ‘os.truncate’，附带参数 ‘fd’,
     ‘length’。

     *note 可用性: 1491.: Unix, Windows。

     3.5 版更變: 添加了 Windows 支持

 -- 函式: os.get_blocking (fd)

     获取文件描述符的阻塞模式：如果设置了 *note O_NONBLOCK: 812. 标志位
     ，返回 ‘False’，如果该标志位被清除，返回 ‘True’。

     参见 *note set_blocking(): 811. 和 *note
     socket.socket.setblocking(): 206f.。

     *note 可用性: 1491.: Unix。

     3.5 版新加入.

 -- 函式: os.isatty (fd)

     如果文件描述符 `fd' 打开且已连接至 tty 设备（或类 tty 设备），返回
     ‘True’，否则返回 ‘False’。

 -- 函式: os.lockf (fd, cmd, len)

     在打开的文件描述符上，使用、测试或删除 POSIX 锁。`fd' 是一个打开的
     文件描述符。`cmd' 指定要进行的操作，它们是 *note F_LOCK: 2070.、
     *note F_TLOCK: 2071.、*note F_ULOCK: 2072. 或 *note F_TEST: 2073. 中
     的一个。`len' 指定哪部分文件需要锁定。

     引发一个 *note 审计事件: fa1. ‘os.lockf’，附带参数 ‘fd’、‘cmd’、
     ‘len’。

     *note 可用性: 1491.: Unix。

     3.3 版新加入.

 -- Data: os.F_LOCK
 -- Data: os.F_TLOCK
 -- Data: os.F_ULOCK
 -- Data: os.F_TEST

     标志位，用于指定 *note lockf(): b35. 进行哪一种操作。

     *note 可用性: 1491.: Unix。

     3.3 版新加入.

 -- 函式: os.lseek (fd, pos, how)

     将文件描述符 `fd' 的当前位置设置为 `pos'，位置的计算方式 `how' 如下
     ：设置为 *note SEEK_SET: e59. 或 ‘0’ 表示从文件开头计算，设置为
     *note SEEK_CUR: e5a. 或 ‘1’ 表示从文件当前位置计算，设置为 *note
     SEEK_END: e5b. 或 ‘2’ 表示文件末尾计算。返回新指针位置，这个位置是
     从文件开头计算的，单位是字节。

 -- Data: os.SEEK_SET
 -- Data: os.SEEK_CUR
 -- Data: os.SEEK_END

     *note lseek(): b39. 函数的参数，它们的值分别为 0、1 和 2。

     3.3 版新加入: 某些操作系统可能支持其他值，例如 ‘os.SEEK_HOLE’ 或
     ‘os.SEEK_DATA’。

 -- 函式: os.open (path, flags, mode=0o777, *, dir_fd=None)

     打开文件 `path'，根据 `flags' 设置各种标志位，并根据 `mode' 设置其
     权限状态。当计算 `mode' 时，会首先根据当前 umask 值将部分权限去除。
     本方法返回新文件的描述符。新的文件描述符是 *note 不可继承: 8e7. 的
     。

     有关 flag 和 mode 取值的说明，请参见 C 运行时文档。标志位常量（如
     *note O_RDONLY: 2074. 和 *note O_WRONLY: 2075.）在 *note os: c4. 模
     块中定义。特别地，在 Windows 上需要添加 *note O_BINARY: 2076. 才能
     以二进制模式打开文件。

     本函数带有 `dir_fd' 参数，支持 *note 基于目录描述符的相对路径:
     b0b.。

     引发一个 *note 审计事件: fa1. ‘open’，附带参数 ‘path’、‘mode’、
     ‘flags’。

     3.4 版更變: 新的文件描述符现在是不可继承的。

          備註: 本函数适用于底层的 I/O。常规用途请使用内置函数 *note
          open(): 16f.，该函数的 ‘read()’ 和 ‘write()’ 方法（及其他方法
          ）会返回 *note 文件对象: c14.。要将文件描述符包装在文件对象中
          ，请使用 *note fdopen(): 1564.。

     3.3 版新加入: `dir_fd' 参数。

     3.5 版更變: 如果系统调用被中断，但信号处理程序没有触发异常，此函数
     现在会重试系统调用，而不是触发 *note InterruptedError: 74c. 异常 (原
     因详见 PEP 475(1))。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

以下常量是 *note open(): 758. 函数 `flags' 参数的选项。可以用按位或运算
符 ‘|’ 将它们组合使用。部分常量并非在所有平台上都可用。有关其可用性和用
法的说明，请参阅 ‘open(2)’ 手册（Unix 上）或 MSDN(2) （Windows 上）。

 -- Data: os.O_RDONLY
 -- Data: os.O_WRONLY
 -- Data: os.O_RDWR
 -- Data: os.O_APPEND
 -- Data: os.O_CREAT
 -- Data: os.O_EXCL
 -- Data: os.O_TRUNC

     上述常量在 Unix 和 Windows 上均可用。

 -- Data: os.O_DSYNC
 -- Data: os.O_RSYNC
 -- Data: os.O_SYNC
 -- Data: os.O_NDELAY
 -- Data: os.O_NONBLOCK
 -- Data: os.O_NOCTTY
 -- Data: os.O_CLOEXEC

     这个常数仅在 Unix 系统中可用。

     3.3 版更變: 增加 *note O_CLOEXEC: aa2. 常量。

 -- Data: os.O_BINARY
 -- Data: os.O_NOINHERIT
 -- Data: os.O_SHORT_LIVED
 -- Data: os.O_TEMPORARY
 -- Data: os.O_RANDOM
 -- Data: os.O_SEQUENTIAL
 -- Data: os.O_TEXT

     这个常数仅在 Windows 系统中可用。

 -- Data: os.O_ASYNC
 -- Data: os.O_DIRECT
 -- Data: os.O_DIRECTORY
 -- Data: os.O_NOFOLLOW
 -- Data: os.O_NOATIME
 -- Data: os.O_PATH
 -- Data: os.O_TMPFILE
 -- Data: os.O_SHLOCK
 -- Data: os.O_EXLOCK

     上述常量是扩展常量，如果 C 库未定义它们，则不存在。

     3.4 版更變: 在支持的系统上增加 *note O_PATH: 96e.。增加 *note
     O_TMPFILE: 96f.，仅在 Linux Kernel 3.11 或更高版本可用。

 -- 函式: os.openpty ()

     打开一对新的伪终端，返回一对文件描述符 ‘（主，从）’，分别为 pty 和
     tty。新的文件描述符是 *note 不可继承: 8e7. 的。对于（稍微）轻量一些
     的方法，请使用 *note pty: d5. 模块。

     *note 可用性: 1491.: 某些 Unix。

     3.4 版更變: 新的文件描述符不再可继承。

 -- 函式: os.pipe ()

     创建一个管道，返回一对分别用于读取和写入的文件描述符 ‘(r, w)’。新的
     文件描述符是 *note 不可继承: 8e7. 的。

     *note 可用性: 1491.: Unix, Windows。

     3.4 版更變: 新的文件描述符不再可继承。

 -- 函式: os.pipe2 (flags)

     创建带有 `flags' 标志位的管道。可通过对以下一个或多个值进行“或”运算
     来构造这些 `flags'：*note O_NONBLOCK: 812.、*note O_CLOEXEC: aa2.。
     返回一对分别用于读取和写入的文件描述符 ‘(r, w)’。

     *note 可用性: 1491.: 某些 Unix。

     3.3 版新加入.

 -- 函式: os.posix_fallocate (fd, offset, len)

     确保为 `fd' 指向的文件分配了足够的磁盘空间，该空间从偏移量 `offset'
     开始，到 `len' 字节为止。

     *note 可用性: 1491.: Unix。

     3.3 版新加入.

 -- 函式: os.posix_fadvise (fd, offset, len, advice)

     声明即将以特定模式访问数据，使内核可以提前进行优化。数据范围是从
     `fd' 所指向文件的 `offset' 开始，持续 `len' 个字节。`advice' 的取值
     是如下之一：*note POSIX_FADV_NORMAL: 208c, *note
     POSIX_FADV_SEQUENTIAL: 208d, *note POSIX_FADV_RANDOM: 208e, *note
     POSIX_FADV_NOREUSE: 208f, *note POSIX_FADV_WILLNEED: 2090. 或 *note
     POSIX_FADV_DONTNEED: 2091.。

     *note 可用性: 1491.: Unix。

     3.3 版新加入.

 -- Data: os.POSIX_FADV_NORMAL
 -- Data: os.POSIX_FADV_SEQUENTIAL
 -- Data: os.POSIX_FADV_RANDOM
 -- Data: os.POSIX_FADV_NOREUSE
 -- Data: os.POSIX_FADV_WILLNEED
 -- Data: os.POSIX_FADV_DONTNEED

     用于 *note posix_fadvise(): 759. 的 `advice' 参数的标志位，指定可能
     使用的访问模式。

     *note 可用性: 1491.: Unix。

     3.3 版新加入.

 -- 函式: os.pread (fd, n, offset)

     从文件描述符 `fd' 所指向文件的偏移位置 `offset' 开始，读取至多 `n'
     个字节，而保持文件偏移量不变。

     返回所读取字节的字节串 (bytestring)。如果到达了 `fd' 指向的文件末尾
     ，则返回空字节对象。

     *note 可用性: 1491.: Unix。

     3.3 版新加入.

 -- 函式: os.preadv (fd, buffers, offset, flags=0)

     从文件描述符 `fd' 所指向文件的偏移位置 `offset' 开始，将数据读取至
     可变 *note 字节类对象: 6df. 缓冲区 `buffers' 中，保持文件偏移量不变
     。将数据依次存放到每个缓冲区中，填满一个后继续存放到序列中的下一个
     缓冲区，来保存其余数据。

     flags 参数可以由零个或多个标志位进行按位或运算来得到：

        - *note RWF_HIPRI: 2092.

        - *note RWF_NOWAIT: 2093.

     返回实际读取的字节总数，该总数可以小于所有对象的总容量。

     操作系统可能对允许使用的缓冲区数量有限制（使用 *note sysconf():
     2094. 获取 ‘'SC_IOV_MAX'’ 值）。

     本方法结合了 *note os.readv(): 4be. 和 *note os.pread(): 4bf. 的功
     能。

     *note 可用性: 1491.：Linux 2.6.30 或更高版本，FreeBSD 6.0 或更高版
     本，OpenBSD 2.7 或更高版本，AIX 7.1 或更高版本。使用标志位需要
     Linux 4.6 或更高版本。

     3.7 版新加入.

 -- Data: os.RWF_NOWAIT

     不要等待无法立即获得的数据。如果指定了此标志，那么当需要从后备存储
     器中读取数据，或等待文件锁时，系统调用将立即返回。

     如果成功读取数据，则返回读取的字节数。如果未读取到数据，则返回
     ‘-1’，并将错误码 errno 置为 *note errno.EAGAIN: 2095.。

     *note 可用性: 1491.：Linux 4.14 或更高版本。

     3.7 版新加入.

 -- Data: os.RWF_HIPRI

     高优先级读/写。允许基于块的文件系统对设备进行轮询，这样可以降低延迟
     ，但可能会占用更多资源。

     目前在 Linux 上，此功能仅在使用 *note O_DIRECT: 2087. 标志打开的文
     件描述符上可用。

     *note 可用性: 1491.：Linux 4.6 或更高版本。

     3.7 版新加入.

 -- 函式: os.pwrite (fd, str, offset)

     将 `str' 中的字节串 (bytestring) 写入文件描述符 `fd' 的偏移位置
     `offset' 处，保持文件偏移量不变。

     返回实际写入的字节数。

     *note 可用性: 1491.: Unix。

     3.3 版新加入.

 -- 函式: os.pwritev (fd, buffers, offset, flags=0)

     将缓冲区 `buffers' 的内容写入文件描述符 `fd' 的偏移位置 `offset' 处
     ，保持文件偏移量不变。缓冲区 `buffers' 必须是由 *note 字节类对象:
     6df. 组成的序列。缓冲区以数组顺序处理。先写入第一个缓冲区的全部内容
     ，再写入第二个缓冲区，照此继续。

     flags 参数可以由零个或多个标志位进行按位或运算来得到：

        - *note RWF_DSYNC: 2096.

        - *note RWF_SYNC: 2097.

     返回实际写入的字节总数。

     操作系统可能对允许使用的缓冲区数量有限制（使用 *note sysconf():
     2094. 获取 ‘'SC_IOV_MAX'’ 值）。

     本方法结合了 *note os.writev(): 4c1. 和 *note os.pwrite(): 4c2. 的
     功能。

     *note 可用性: 1491.：Linux 2.6.30 或更高版本，FreeBSD 6.0 或更高版
     本，OpenBSD 2.7 或更高版本，AIX 7.1 或更高版本。使用标志位需要
     Linux 4.7 或更高版本。

     3.7 版新加入.

 -- Data: os.RWF_DSYNC

     提供立即写入功能，等效于 *note O_DSYNC: 207b. ‘open(2)’ 标志。该标
     志仅作用于系统调用写入的数据。

     *note 可用性: 1491.：Linux 4.7 或更高版本。

     3.7 版新加入.

 -- Data: os.RWF_SYNC

     提供立即写入功能，等效于 *note O_SYNC: 207d. ‘open(2)’ 标志。该标志
     仅作用于系统调用写入的数据。

     *note 可用性: 1491.：Linux 4.7 或更高版本。

     3.7 版新加入.

 -- 函式: os.read (fd, n)

     从文件描述符 `fd' 中读取至多 `n' 个字节。

     返回所读取字节的字节串 (bytestring)。如果到达了 `fd' 指向的文件末尾
     ，则返回空字节对象。

          備註: 该功能适用于低级 I/O 操作，必须用于 *note os.open():
          758. 或 *note pipe(): 206a. 返回的文件描述符。若要读取由内建函
          数 *note open(): 16f.、*note popen(): 3cb.、*note fdopen():
          1564. 或 *note sys.stdin: 41e. 返回的 "文件对象"，则应使用其相
          应的 ‘read()’ 或 ‘readline()’ 方法。

     3.5 版更變: 如果系统调用被中断，但信号处理程序没有触发异常，此函数
     现在会重试系统调用，而不是触发 *note InterruptedError: 74c. 异常 (原
     因详见 PEP 475(3))。

 -- 函式: os.sendfile (out_fd, in_fd, offset, count)

 -- 函式: os.sendfile (out_fd, in_fd, offset, count, headers=(),
          trailers=(), flags=0)

     将文件描述符 `in_fd' 中的 `count' 字节复制到文件描述符 `out_fd' 的
     偏移位置 `offset' 处。返回复制的字节数，如果到达 EOF，返回 ‘0’。

     定义了 *note sendfile(): 461. 的所有平台均支持第一种函数用法。

     在 Linux 上，将 `offset' 设置为 ‘None’，则从 `in_fd' 的当前位置开始
     读取，并更新 `in_fd' 的位置。

     第二种情况可以被用于 macOS 和 FreeBSD，其中 `headers' 和 `trailers'
     是任意的缓冲区序列，它们会在写入来自 `in_fd' 的数据之前被写入。 它
     的返回内容与第一种情况相同。

     在 macOS 和 FreeBSD 上，传入 ‘0’ 值作为 `count' 将指定持续发送直至
     到达 `in_fd' 的末尾。

     所有平台都支持将套接字作为 `out_fd' 文件描述符，有些平台也支持其他
     类型（如常规文件或管道）。

     跨平台应用程序不应使用 `headers'、`trailers' 和 `flags' 参数。

     *note 可用性: 1491.: Unix。

          備註: 有关 *note sendfile(): 461. 的高级封装，参见 *note
          socket.socket.sendfile(): 839.。

     3.3 版新加入.

     3.9 版更變: `out' 和 `in' 参数被重命名为 `out_fd' 和 `in_fd'。

 -- 函式: os.set_blocking (fd, blocking)

     设置指定文件描述符的阻塞模式：如果 blocking 为 ‘False’，则为该描述
     符设置 *note O_NONBLOCK: 812. 标志位，反之则清除该标志位。

     参见 *note get_blocking(): 810. 和 *note
     socket.socket.setblocking(): 206f.。

     *note 可用性: 1491.: Unix。

     3.5 版新加入.

 -- Data: os.SF_NODISKIO
 -- Data: os.SF_MNOWAIT
 -- Data: os.SF_SYNC

     *note sendfile(): 461. 函数的参数（假设当前实现支持这些参数）。

     *note 可用性: 1491.: Unix。

     3.3 版新加入.

 -- 函式: os.readv (fd, buffers)

     从文件描述符 `fd' 将数据读取至多个可变的 *note 字节类对象: 6df. 缓
     冲区 `buffers' 中。将数据依次存放到每个缓冲区中，填满一个后继续存放
     到序列中的下一个缓冲区，来保存其余数据。

     返回实际读取的字节总数，该总数可以小于所有对象的总容量。

     操作系统可能对允许使用的缓冲区数量有限制（使用 *note sysconf():
     2094. 获取 ‘'SC_IOV_MAX'’ 值）。

     *note 可用性: 1491.: Unix。

     3.3 版新加入.

 -- 函式: os.tcgetpgrp (fd)

     返回与 `fd' 指定的终端相关联的进程组（`fd' 是由 *note os.open():
     758. 返回的已打开的文件描述符）。

     *note 可用性: 1491.: Unix。

 -- 函式: os.tcsetpgrp (fd, pg)

     设置与 `fd' 指定的终端相关联的进程组为 `pg*（*fd' 是由 *note
     os.open(): 758. 返回的已打开的文件描述符）。

     *note 可用性: 1491.: Unix。

 -- 函式: os.ttyname (fd)

     返回一个字符串，该字符串表示与文件描述符 `fd' 关联的终端。如果 `fd'
     没有与终端关联，则抛出异常。

     *note 可用性: 1491.: Unix。

 -- 函式: os.write (fd, str)

     将 `str' 中的字节串 (bytestring) 写入文件描述符 `fd'。

     返回实际写入的字节数。

          備註: 该功能适用于低级 I/O 操作，必须用于 *note os.open():
          758. 或 *note pipe(): 206a. 返回的文件描述符。若要写入由内建函
          数 *note open(): 16f.、*note popen(): 3cb.、*note fdopen():
          1564.、*note sys.stdout: 41f. 或 *note sys.stderr: 1ea. 返回的
          "文件对象"，则应使用其相应的 ‘write()’ 方法。

     3.5 版更變: 如果系统调用被中断，但信号处理程序没有触发异常，此函数
     现在会重试系统调用，而不是触发 *note InterruptedError: 74c. 异常 (原
     因详见 PEP 475(4))。

 -- 函式: os.writev (fd, buffers)

     将缓冲区 `buffers' 的内容写入文件描述符 `fd'。缓冲区 `buffers' 必须
     是由 *note 字节类对象: 6df. 组成的序列。缓冲区以数组顺序处理。先写
     入第一个缓冲区的全部内容，再写入第二个缓冲区，照此继续。

     返回实际写入的字节总数。

     操作系统可能对允许使用的缓冲区数量有限制（使用 *note sysconf():
     2094. 获取 ‘'SC_IOV_MAX'’ 值）。

     *note 可用性: 1491.: Unix。

     3.3 版新加入.

* Menu:

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

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0475

   (2) https://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx

   (3) https://www.python.org/dev/peps/pep-0475

   (4) https://www.python.org/dev/peps/pep-0475


File: python.info,  Node: 查询终端的尺寸,  Next: 文件描述符的继承,  Up: 文件描述符操作

5.16.1.5 查询终端的尺寸
.......................

3.3 版新加入.

 -- 函式: os.get_terminal_size (fd=STDOUT_FILENO)

     返回终端窗口的尺寸，格式为 ‘(columns, lines)’，它是类型为 *note
     terminal_size: 1dfa. 的元组。

     可选参数 ‘fd’ （默认为 ‘STDOUT_FILENO’ 或标准输出）指定应查询的文件
     描述符。

     如果文件描述符未连接到终端，则抛出 *note OSError: 304. 异常。

     *note shutil.get_terminal_size(): b25. 是供常规使用的高阶函数，
     ‘os.get_terminal_size’ 是其底层的实现。

     *note 可用性: 1491.: Unix, Windows。

 -- 類別: os.terminal_size

     元组的子类，存储终端窗口尺寸 ‘(columns, lines)’。

      -- 屬性: columns

          终端窗口的宽度，单位为字符。

      -- 屬性: lines

          终端窗口的高度，单位为字符。


File: python.info,  Node: 文件描述符的继承,  Prev: 查询终端的尺寸,  Up: 文件描述符操作

5.16.1.6 文件描述符的继承
.........................

3.4 版新加入.

每个文件描述符都有一个 "inheritable"（可继承）标志位，该标志位控制了文件
描述符是否可以由子进程继承。从 Python 3.4 开始，由 Python 创建的文件描述
符默认是不可继承的。

在 UNIX 上，执行新程序时，不可继承的文件描述符在子进程中是关闭的，其他文
件描述符将被继承。

在 Windows 上，不可继承的句柄和文件描述符在子进程中是关闭的，但标准流（
文件描述符 0、1 和 2 即标准输入、标准输出和标准错误）是始终继承的。如果
使用 *note spawn*: 20a3. 函数，所有可继承的句柄和文件描述符都将被继承。
如果使用 *note subprocess: f9. 模块，将关闭除标准流以外的所有文件描述符
，并且仅当 `close_fds' 参数为 ‘False’ 时才继承可继承的句柄。

 -- 函式: os.get_inheritable (fd)

     获取指定文件描述符的“可继承”标志位（为布尔值）。

 -- 函式: os.set_inheritable (fd, inheritable)

     设置指定文件描述符的“可继承”标志位。

 -- 函式: os.get_handle_inheritable (handle)

     获取指定句柄的“可继承”标志位（为布尔值）。

     *note 可用性: 1491.: Windows。

 -- 函式: os.set_handle_inheritable (handle, inheritable)

     设置指定句柄的“可继承”标志位。

     *note 可用性: 1491.: Windows。


File: python.info,  Node: 文件和目录,  Next: 进程管理,  Prev: 文件描述符操作,  Up: os --- 多种操作系统接口

5.16.1.7 文件和目录
...................

在某些 Unix 平台上，许多函数支持以下一项或多项功能：

   * `指定文件描述符为参数：' 通常在 *note os: c4. 模块中提供给函数的
     `path' 参数必须是表示文件路径的字符串，但是，某些函数现在可以接受其
     `path' 参数为打开文件描述符，该函数将对描述符指向的文件进行操作。（
     对于 POSIX 系统，Python 将调用以 ‘f’ 开头的函数变体（如调用
     ‘fchdir’ 而不是 ‘chdir’）。）

     可以用 *note os.supports_fd: b1f. 检查某个函数在你的平台上是否支持
     将 `path' 参数指定为文件描述符。如果不支持，使用该功能将抛出 *note
     NotImplementedError: 704. 异常。

     如果该函数还支持 `dir_fd' 或 `follow_symlinks' 参数，那么用文件描述
     符作为 `path' 后就不能再指定上述参数了。

   * `基于目录描述符的相对路径：' 如果 `dir_fd' 不是 ‘None’，它就应该是
     一个指向目录的文件描述符，这时待操作的 path 应该是相对路径，相对路
     径是相对于前述目录的。如果 path 是绝对路径，则 `dir_fd' 将被忽略。
     （对于 POSIX 系统，Python 将调用该函数的变体，变体以 ‘at’ 结尾，可
     能以 ‘f’ 开头（如调用 ‘faccessat’ 而不是 ‘access’）。

     可以用 *note os.supports_dir_fd: b1a. 检查某个函数在你的平台上是否
     支持 `dir_fd'。如果不支持，使用该功能将抛出 *note
     NotImplementedError: 704. 异常。

   * `不跟踪符号链接：' 如果 `follow_symlinks' 为 ‘False’，并且待操作路
     径的最后一个元素是符号链接，则该函数将在符号链接本身而不是链接所指
     向的文件上操作。（对于 POSIX 系统，Python 将调用该函数的 ‘l...’ 变
     体。）

     可以用 *note os.supports_follow_symlinks: 1de5. 检查某个函数在你的
     平台上是否支持 `follow_symlinks'。如果不支持，使用该功能将抛出
     *note NotImplementedError: 704. 异常。

 -- 函式: os.access (path, mode, *, dir_fd=None, effective_ids=False,
          follow_symlinks=True)

     使用 实际用户ID/用户组ID 测试对 `path' 的访问。请注意，大多数测试操
     作将使用 有效用户ID/用户组ID，因此可以在 suid/sgid 环境中运用此例程
     ，来测试调用用户是否具有对 `path' 的指定访问权限。`mode' 为 *note
     F_OK: 20a5. 时用于测试 `path' 是否存在，也可以对 *note R_OK: 20a6.、
     *note W_OK: 20a7. 和 *note X_OK: 20a8. 中的一个或多个进行“或”运算来
     测试指定权限。允许访问则返回 *note True: 593.，否则返回 *note
     False: 48e.。更多信息请参见 Unix 手册页 ‘access(2)’。

     本函数支持指定 *note 基于目录描述符的相对路径: b0b. 和 *note
     不跟踪符号链接: b0c.。

     如果 `effective_ids' 为 ‘True’，*note access(): b0d. 将使用 有效用
     户ID/用户组ID 而非 实际用户ID/用户组ID 进行访问检查。您的平台可能不
     支持 `effective_ids'，您可以使用 *note os.supports_effective_ids:
     b20. 检查它是否可用。如果不可用，使用它时会抛出 *note
     NotImplementedError: 704. 异常。

          備註: 使用 *note access(): b0d. 来检查用户是否具有某项权限（如
          打开文件的权限），然后再使用 *note open(): 16f. 打开文件，这样
          做存在一个安全漏洞，因为用户可能会在检查和打开文件之间的时间里
          做其他操作。推荐使用 *note EAFP: 20a9. 技术。如:

               if os.access("myfile", os.R_OK):
                   with open("myfile") as fp:
                       return fp.read()
               return "some default data"

          最好写成:

               try:
                   fp = open("myfile")
               except PermissionError:
                   return "some default data"
               else:
                   with fp:
                       return fp.read()

          備註: 即使 *note access(): b0d. 指示 I/O 操作会成功，但实际操
          作仍可能失败，尤其是对网络文件系统的操作，其权限语义可能超出常
          规的 POSIX 权限位模型。

     3.3 版更變: 添加 `dir_fd'、`effective_ids' 和 `follow_symlinks' 参
     数。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- Data: os.F_OK
 -- Data: os.R_OK
 -- Data: os.W_OK
 -- Data: os.X_OK

     作为 *note access(): b0d. 的 `mode' 参数的可选值，分别测试 `path' 的
     存在性、可读性、可写性和可执行性。

 -- 函式: os.chdir (path)

     将当前工作目录更改为 `path'。

     本函数支持 *note 指定文件描述符为参数: 4bb.。其中，描述符必须指向打
     开的目录，不能是打开的文件。

     本函数可以抛出 *note OSError: 304. 及其子类的异常，如 *note
     FileNotFoundError: 8ad.、*note PermissionError: 6f6. 和 *note
     NotADirectoryError: a7b. 异常。

     引发一个 *note 审计事件: fa1. ‘os.chdir’，附带参数 ‘path’。

     3.3 版新加入: 在某些平台上新增支持将 `path' 参数指定为文件描述符。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.chflags (path, flags, *, follow_symlinks=True)

     将 `path' 的 flags 设置为其他由数字表示的 `flags'。`flags' 可以用以
     下值按位或组合起来（以下值在 *note stat: f4. 模块中定义）：

        * *note stat.UF_NODUMP: 1d8b.

        * *note stat.UF_IMMUTABLE: 1d8c.

        * *note stat.UF_APPEND: 1d8d.

        * *note stat.UF_OPAQUE: 1d8e.

        * *note stat.UF_NOUNLINK: 1d8f.

        * *note stat.UF_COMPRESSED: 1d90.

        * *note stat.UF_HIDDEN: 1d91.

        * *note stat.SF_ARCHIVED: 1d92.

        * *note stat.SF_IMMUTABLE: 1d93.

        * *note stat.SF_APPEND: 1d94.

        * *note stat.SF_NOUNLINK: 1d95.

        * *note stat.SF_SNAPSHOT: 1d96.

     本函数支持 *note 不跟踪符号链接: b0c.。

     引发一个 *note 审计事件: fa1. ‘os.chflags’，附带参数 ‘path’、
     ‘flags’。

     *note 可用性: 1491.: Unix。

     3.3 版新加入: `follow_symlinks' 参数。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.chmod (path, mode, *, dir_fd=None, follow_symlinks=True)

     将 `path' 的 mode 更改为其他由数字表示的 `mode'。`mode' 可以用以下
     值之一，也可以将它们按位或组合起来（以下值在 *note stat: f4. 模块中
     定义）：

        * *note stat.S_ISUID: 1d78.

        * *note stat.S_ISGID: 1d79.

        * *note stat.S_ENFMT: 1d7b.

        * *note stat.S_ISVTX: 1d7c.

        * *note stat.S_IREAD: 1d88.

        * *note stat.S_IWRITE: 1d89.

        * *note stat.S_IEXEC: 1d8a.

        * *note stat.S_IRWXU: 1d7d.

        * *note stat.S_IRUSR: 1d7e.

        * *note stat.S_IWUSR: 1d7f.

        * *note stat.S_IXUSR: 1d80.

        * *note stat.S_IRWXG: 1d81.

        * *note stat.S_IRGRP: 1d82.

        * *note stat.S_IWGRP: 1d83.

        * *note stat.S_IXGRP: 1d7a.

        * *note stat.S_IRWXO: 1d84.

        * *note stat.S_IROTH: 1d85.

        * *note stat.S_IWOTH: 1d86.

        * *note stat.S_IXOTH: 1d87.

     本函数支持 *note 指定文件描述符: 4bb.、*note
     指定基于目录描述符的相对路径: b0b. 和 *note 不跟踪符号链接: b0c.。

          備註: 尽管 Windows 支持 *note chmod(): b0f.，但只能用它设置文
          件的只读标志（‘stat.S_IWRITE’ 和 ‘stat.S_IREAD’ 常量或对应的整
          数值）。所有其他标志位都会被忽略。

     引发一个 *note 审计事件: fa1. ‘os.chmod’，附带参数 ‘path’、‘mode’、
     ‘dir_fd’。

     3.3 版新加入: 添加了指定 `path' 为文件描述符的支持，以及 `dir_fd' 和
     `follow_symlinks' 参数。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.chown (path, uid, gid, *, dir_fd=None,
          follow_symlinks=True)

     将 `path' 的用户和组 ID 分别修改为数字形式的 `uid' 和 `gid'。若要使
     其中某个 ID 保持不变，请将其置为 -1。

     本函数支持 *note 指定文件描述符: 4bb.、*note
     指定基于目录描述符的相对路径: b0b. 和 *note 不跟踪符号链接: b0c.。

     参见更高阶的函数 *note shutil.chown(): b51.，除了数字 ID 之外，它也
     接受名称。

     引发一个 *note 审计事件: fa1. ‘os.chown’，附带参数 ‘path’、‘uid’、
     ‘gid’、‘dir_fd’。

     *note 可用性: 1491.: Unix。

     3.3 版新加入: 添加了指定 `path' 为文件描述符的支持，以及 `dir_fd' 和
     `follow_symlinks' 参数。

     3.6 版更變: 支持 *note 类路径对象: 472.。

 -- 函式: os.chroot (path)

     将当前进程的根目录更改为 `path'。

     *note 可用性: 1491.: Unix。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.fchdir (fd)

     将当前工作目录更改为文件描述符 `fd' 指向的目录。fd 必须指向打开的目
     录而非文件。从 Python 3.3 开始，它等效于 ‘os.chdir(fd)’。

     引发一个 *note 审计事件: fa1. ‘os.chdir’，附带参数 ‘path’。

     *note 可用性: 1491.: Unix。

 -- 函式: os.getcwd ()

     返回表示当前工作目录的字符串。

 -- 函式: os.getcwdb ()

     返回表示当前工作目录的字节串 (bytestring)。

     3.8 版更變: 在 Windows 上，本函数现在会使用 UTF-8 编码格式而不是
     ANSI 代码页：请参看 PEP 529(1) 了解具体原因。 该函数在 Windows 上不
     再被弃用。

 -- 函式: os.lchflags (path, flags)

     将 `path' 的 flags 设置为其他由数字表示的 `flags'，与 *note
     chflags(): b0e. 类似，但不跟踪符号链接。从 Python 3.3 开始，它等效
     于 ‘os.chflags(path, flags, follow_symlinks=False)’。

     引发一个 *note 审计事件: fa1. ‘os.chflags’，附带参数 ‘path’、
     ‘flags’。

     *note 可用性: 1491.: Unix。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.lchmod (path, mode)

     将 `path' 的权限状态修改为 `mode'。如果 path 是符号链接，则影响符号
     链接本身而非链接目标。可以参考 *note chmod(): b0f. 中列出 `mode' 的
     可用值。从 Python 3.3 开始，它等效于 ‘os.chmod(path, mode,
     follow_symlinks=False)’。

     引发一个 *note 审计事件: fa1. ‘os.chmod’，附带参数 ‘path’、‘mode’、
     ‘dir_fd’。

     *note 可用性: 1491.: Unix。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.lchown (path, uid, gid)

     将 `path' 的用户和组 ID 分别修改为数字形式的 `uid' 和 `gid'，本函数
     不跟踪符号链接。从 Python 3.3 开始，它等效于 ‘os.chown(path, uid,
     gid, follow_symlinks=False)’。

     引发一个 *note 审计事件: fa1. ‘os.chown’，附带参数 ‘path’、‘uid’、
     ‘gid’、‘dir_fd’。

     *note 可用性: 1491.: Unix。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.link (src, dst, *, src_dir_fd=None, dst_dir_fd=None,
          follow_symlinks=True)

     创建一个指向 `src' 的硬链接，名为 `dst'。

     本函数支持将 `src_dir_fd' 和 `dst_dir_fd' 中的一个或两个指定为
     *note 基于目录描述符的相对路径: b0b.，支持 *note 不跟踪符号链接:
     b0c.。

     引发一个 *note 审计事件: fa1. ‘os.link’ 附带参数 ‘src’、‘dst’、
     ‘src_dir_fd’、‘dst_dir_fd’。

     *note 可用性: 1491.: Unix, Windows。

     3.2 版更變: 添加了对 Windows 的支持。

     3.3 版新加入: 添加 `src_dir_fd'、`dst_dir_fd' 和 `follow_symlinks'
     参数。

     3.6 版更變: 接受一个 *note 类路径对象: 472. 作为 `src' 和 `dst'。

 -- 函式: os.listdir (path='.')

     返回一个包含由 `path' 指定目录中条目名称组成的列表。 该列表按任意顺
     序排列，并且不包括特殊条目 ‘'.'’ 和 ‘'..'’，即使它们存在于目录中。
     如果有文件在调用此函数期间在被移除或添加到目录中，是否要包括该文件
     的名称并没有规定。

     `path' 可以是 *note 类路径对象: 472.。如果 `path' 是（直接传入或通
     过 *note PathLike: 5e5. 接口间接传入） ‘bytes’ 类型，则返回的文件名
     也将是 ‘bytes’ 类型，其他情况下是 ‘str’ 类型。

     本函数也支持 *note 指定文件描述符为参数: 4bb.，其中描述符必须指向目
     录。

     引发一个 *note 审计事件: fa1. ‘os.listdir’，附带参数 ‘path’。

          備註: 要将 ‘str’ 类型的文件名编码为 ‘bytes’，请使用 *note
          fsencode(): 5e9.。

     也參考
     ......

     *note scandir(): 389. 函数返回目录内文件名的同时，也返回文件属性信
     息，它在某些具体情况下能提供更好的性能。

     3.2 版更變: `path' 变为可选参数。

     3.3 版新加入: 新增支持将 `path' 参数指定为打开的文件描述符。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.lstat (path, *, dir_fd=None)

     在给定路径上执行本函数，其操作相当于 ‘lstat()’ 系统调用，类似于
     *note stat(): 321. 但不跟踪符号链接。返回值是 *note stat_result:
     11bf. 对象。

     在不支持符号链接的平台上，本函数是 *note stat(): 321. 的别名。

     从 Python 3.3 起，此功能等价于 ‘os.stat(path, dir_fd=dir_fd,
     follow_symlinks=False)’。

     本函数支持 *note 基于目录描述符的相对路径: b0b.。

     也參考
     ......

     *note stat(): 321. 函数。

     3.2 版更變: 添加对 Windows 6.0 (Vista) 符号链接的支持。

     3.3 版更變: 添加了 `dir_fd' 参数。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

     3.8 版更變: 目前在 Windows 上，遇到表示另一个路径的重解析点（即名称
     代理，包括符号链接和目录结点），本函数将打开它。其他种类的重解析点
     由 *note stat(): 321. 交由操作系统解析。

 -- 函式: os.mkdir (path, mode=0o777, *, dir_fd=None)

     创建一个名为 `path' 的目录，应用以数字表示的权限模式 `mode'。

     如果目录已存在，则抛出 *note FileExistsError: a39. 异常。 某些系统
     会忽略 `mode'。如果没有忽略它，那么将首先从它中减去当前的 umask 值
     。如果除最后 9 位（即 `mode' 八进制的最后 3 位）之外，还设置了其他
     位，则其他位的含义取决于各个平台。在某些平台上，它们会被忽略，应显
     式调用 *note chmod(): b0f. 进行设置。

     本函数支持 *note 基于目录描述符的相对路径: b0b.。

     如果需要创建临时目录，请参阅 *note tempfile: 103. 模块中的 *note
     tempfile.mkdtemp(): 1dc5. 函数。

     引发一个 *note 审计事件: fa1. ‘os.mkdir’，附带参数 ‘path’、‘mode’、
     ‘dir_fd’。

     3.3 版新加入: `dir_fd' 参数。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.makedirs (name, mode=0o777, exist_ok=False)

     递归目录创建函数。与 *note mkdir(): b12. 类似，但会自动创建到达最后
     一级目录所需要的中间目录。

     `mode' 参数会传递给 *note mkdir(): b12.，用来创建最后一级目录，对于
     该参数的解释，请参阅 *note mkdir() 中的描述: 20ac.。要设置某些新建
     的父目录的权限，可以在调用 *note makedirs(): 4c3. 之前设置 umask。
     现有父目录的权限不会更改。

     如果 `exist_ok' 为 ‘False’ (默认值)，则如果目标目录已存在将引发
     *note FileExistsError: a39.。

          備註: 如果要创建的路径元素包含 *note pardir: 20ad. (如 UNIX 系
          统中的 "..")  *note makedirs(): 4c3. 将无法明确目标。

     本函数能正确处理 UNC 路径。

     引发一个 *note 审计事件: fa1. ‘os.mkdir’，附带参数 ‘path’、‘mode’、
     ‘dir_fd’。

     3.2 版新加入: `exist_ok' 参数。

     3.4.1 版更變: 在 Python 3.4.1 以前，如果 `exist_ok' 为 ‘True’，且目
     录已存在，且 `mode' 与现有目录的权限不匹配，*note makedirs(): 4c3.
     仍会抛出错误。由于无法安全地实现此行为，因此在 Python 3.4.1 中将该
     行为删除。请参阅 bpo-21082(2)。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

     3.7 版更變: `mode' 参数不再影响新创建的中间目录的权限。

 -- 函式: os.mkfifo (path, mode=0o666, *, dir_fd=None)

     创建一个名为 `path' 的 FIFO（命名管道，一种先进先出队列），具有以数
     字表示的权限状态 `mode'。将从 mode 中首先减去当前的 umask 值。

     本函数支持 *note 基于目录描述符的相对路径: b0b.。

     FIFO 是可以像常规文件一样访问的管道。FIFO 如果没有被删除（如使用
     *note os.unlink(): b18.），会一直存在。通常，FIFO 用作“客户端”和“服
     务器”进程之间的汇合点：服务器打开 FIFO 进行读取，而客户端打开 FIFO
     进行写入。请注意，*note mkfifo(): 756. 不会打开 FIFO — 它只是创建汇
     合点。

     *note 可用性: 1491.: Unix。

     3.3 版新加入: `dir_fd' 参数。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.mknod (path, mode=0o600, device=0, *, dir_fd=None)

     创建一个名为 `path' 的文件系统节点（文件，设备专用文件或命名管道）
     。`mode' 指定权限和节点类型，方法是将权限与下列节点类型
     ‘stat.S_IFREG’、‘stat.S_IFCHR’、‘stat.S_IFBLK’ 和 ‘stat.S_IFIFO’ 之
     一（按位或）组合（这些常量可以在 *note stat: f4. 模块中找到）。对于
     ‘stat.S_IFCHR’ 和 ‘stat.S_IFBLK’，`device' 参数指定了新创建的设备专
     用文件（可能会用到 *note os.makedev(): 20ae.），否则该参数将被忽略
     。

     本函数支持 *note 基于目录描述符的相对路径: b0b.。

     *note 可用性: 1491.: Unix。

     3.3 版新加入: `dir_fd' 参数。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.major (device)

     提取主设备号，提取自原始设备号（通常是 ‘stat’ 中的 ‘st_dev’ 或
     ‘st_rdev’ 字段）。

 -- 函式: os.minor (device)

     提取次设备号，提取自原始设备号（通常是 ‘stat’ 中的 ‘st_dev’ 或
     ‘st_rdev’ 字段）。

 -- 函式: os.makedev (major, minor)

     将主设备号和次设备号组合成原始设备号。

 -- 函式: os.pathconf (path, name)

     返回所给名称的文件有关的系统配置信息。`name' 指定要查找的配置名称，
     它可以是字符串，是一个系统已定义的名称，这些名称定义在不同标准（
     POSIX.1，Unix 95，Unix 98 等）中。一些平台还定义了额外的其他名称。
     当前操作系统已定义的名称在 ‘pathconf_names’ 字典中给出。对于未包含
     在该映射中的配置名称，也可以传递一个整数作为 `name'。

     如果 `name' 是一个字符串且不是已定义的名称，将抛出 *note
     ValueError: 16d. 异常。如果当前系统不支持 `name' 指定的配置名称，即
     使该名称存在于 ‘pathconf_names’，也会抛出 *note OSError: 304. 异常
     ，错误码为 *note errno.EINVAL: 1104.。

     本函数支持 *note 指定文件描述符为参数: 4bb.。

     *note 可用性: 1491.: Unix。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- Data: os.pathconf_names

     字典，表示映射关系，为 *note pathconf(): b1d. 和 *note fpathconf():
     206e. 可接受名称与操作系统为这些名称定义的整数值之间的映射。这可用
     于判断系统已定义了哪些名称。

     *note 可用性: 1491.: Unix。

 -- 函式: os.readlink (path, *, dir_fd=None)

     返回一个字符串，为符号链接指向的实际路径。其结果可以是绝对或相对路
     径。如果是相对路径，则可用 ‘os.path.join(os.path.dirname(path),
     result)’ 转换为绝对路径。

     如果 `path' 是字符串对象（直接传入或通过 *note PathLike: 5e5. 接口
     间接传入），则结果也将是字符串对象，且此类调用可能会引发
     UnicodeDecodeError。如果 `path' 是字节对象（直接传入或间接传入），
     则结果将会是字节对象。

     本函数支持 *note 基于目录描述符的相对路径: b0b.。

     当尝试解析的路径可能含有链接时，请改用 *note realpath(): 32d. 以正
     确处理递归和平台差异。

     *note 可用性: 1491.: Unix, Windows。

     3.2 版更變: 添加对 Windows 6.0 (Vista) 符号链接的支持。

     3.3 版新加入: `dir_fd' 参数。

     3.6 版更變: 在 Unix 上可以接受一个 *note 类路径对象: 472.。

     3.8 版更變: 在 Windows 上接受 *note 类路径对象: 472. 和字节对象。

     3.8 版更變: 增加了对目录链接的支持，且返回值改为了“替换路径”的形式
     （通常带有 ‘\\?\’ 前缀），而不是先前那样返回可选的 "print name" 字
     段。

 -- 函式: os.remove (path, *, dir_fd=None)

     移除（删除）文件 `path'。 如果 `path' 是目录，则会引发 *note
     IsADirectoryError: a7a.。 请使用 *note rmdir(): b16. 来删除目录。 如
     果文件不存在，则会引发 *note FileNotFoundError: 8ad.。

     本函数支持 *note 基于目录描述符的相对路径: b0b.。

     在 Windows 上，尝试删除正在使用的文件会抛出异常。而在 Unix 上，虽然
     该文件的条目会被删除，但分配给文件的存储空间仍然不可用，直到原始文
     件不再使用为止。

     本函数在语义上与 *note unlink(): b18. 相同。

     引发一个 *note 审计事件: fa1. ‘os.remove’，附带参数 ‘path’、
     ‘dir_fd’。

     3.3 版新加入: `dir_fd' 参数。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.removedirs (name)

     递归删除目录。工作方式类似于 *note rmdir(): b16.，不同之处在于，如
     果成功删除了末尾一级目录，*note removedirs(): 20b2. 会尝试依次删除
     `path' 中提到的每个父目录，直到抛出错误为止（但该错误会被忽略，因为
     这通常表示父目录不是空目录）。例如，‘os.removedirs('foo/bar/baz')’
     将首先删除目录 ‘'foo/bar/baz'’，然后如果 ‘'foo/bar'’ 和 ‘'foo'’ 为
     空，则继续删除它们。如果无法成功删除末尾一级目录，则抛出 *note
     OSError: 304. 异常。

     引发一个 *note 审计事件: fa1. ‘os.remove’，附带参数 ‘path’、
     ‘dir_fd’。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.rename (src, dst, *, src_dir_fd=None, dst_dir_fd=None)

     将文件或目录 `src' 重命名为 `dst'。如果 `dst' 已存在，则下列情况下
     将会操作失败，并抛出 *note OSError: 304. 的子类：

     在 Windows 上，如果 `dst' 已存在，则抛出 *note FileExistsError:
     a39. 异常。

     在 Unix 上，如果 `src' 是文件而 `dst' 是目录，将抛出 *note
     IsADirectoryError: a7a. 异常，反之则抛出 *note NotADirectoryError:
     a7b. 异常。如果两者都是目录且 `dst' 为空，则 `dst' 将被静默替换。如
     果 `dst' 是非空目录，则抛出 *note OSError: 304. 异常。如果两者都是
     文件，则在用户具有权限的情况下，将对 `dst' 进行静默替换。如果 `src'
     和 `dst' 在不同的文件系统上，则本操作在某些 Unix 分支上可能会失败。
     如果成功，重命名操作将是一个原子操作（这是 POSIX 的要求）。

     本函数支持将 `src_dir_fd' 和 `dst_dir_fd' 中的一个或两个指定为
     *note 基于目录描述符的相对路径: b0b.。

     如果需要在不同平台上都能替换目标，请使用 *note replace(): b15.。

     引发一个 *note 审计事件: fa1. ‘os.rename’ 附带参数 ‘src’、‘dst’、
     ‘src_dir_fd’、‘dst_dir_fd’。

     3.3 版新加入: `src_dir_fd' 和 `dst_dir_fd' 参数。

     3.6 版更變: 接受一个 *note 类路径对象: 472. 作为 `src' 和 `dst'。

 -- 函式: os.renames (old, new)

     递归重命名目录或文件。工作方式类似 *note rename(): b14.，除了会首先
     创建新路径所需的中间目录。重命名后，将调用 *note removedirs():
     20b2. 删除旧路径中不需要的目录。

          備註: 如果用户没有权限删除末级的目录或文件，则本函数可能会无法
          建立新的目录结构。

     引发一个 *note 审计事件: fa1. ‘os.rename’ 附带参数 ‘src’、‘dst’、
     ‘src_dir_fd’、‘dst_dir_fd’。

     3.6 版更變: 接受一个 *note 类路径对象: 472. 作为 `old' 和 `new'。

 -- 函式: os.replace (src, dst, *, src_dir_fd=None, dst_dir_fd=None)

     将文件或目录 `src' 重命名为 `dst'。如果 `dst' 是目录，将抛出 *note
     OSError: 304. 异常。如果 `dst' 已存在且为文件，则在用户具有权限的情
     况下，将对其进行静默替换。如果 `src' 和 `dst' 在不同的文件系统上，
     本操作可能会失败。如果成功，重命名操作将是一个原子操作（这是 POSIX
     的要求）。

     本函数支持将 `src_dir_fd' 和 `dst_dir_fd' 中的一个或两个指定为
     *note 基于目录描述符的相对路径: b0b.。

     引发一个 *note 审计事件: fa1. ‘os.rename’ 附带参数 ‘src’、‘dst’、
     ‘src_dir_fd’、‘dst_dir_fd’。

     3.3 版新加入.

     3.6 版更變: 接受一个 *note 类路径对象: 472. 作为 `src' 和 `dst'。

 -- 函式: os.rmdir (path, *, dir_fd=None)

     移除（删除）目录 `path'。如果目录不存在或不为空，则会分别抛出 *note
     FileNotFoundError: 8ad. 或 *note OSError: 304. 异常。要删除整个目录
     树，可以使用 *note shutil.rmtree(): 349.。

     本函数支持 *note 基于目录描述符的相对路径: b0b.。

     引发一个 *note 审计事件: fa1. ‘os.rmdir’，附带参数 ‘path’、
     ‘dir_fd’。

     3.3 版新加入: `dir_fd' 参数。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.scandir (path='.')

     返回一个 *note os.DirEntry: 5ea. 对象的迭代器，它们对应于由 `path'
     指定目录中的条目。 这些条目会以任意顺序生成，并且不包括特殊条目
     ‘'.'’ 和 ‘'..'’。 如果有文件在迭代器创建之后在目录中被移除或添加，
     是否要包括该文件对应的条目并没有规定。

     如果需要文件类型或文件属性信息，使用 *note scandir(): 389. 代替
     *note listdir(): b1c. 可以大大提高这部分代码的性能，因为如果操作系
     统在扫描目录时返回的是 *note os.DirEntry: 5ea. 对象，则该对象包含了
     这些信息。所有 *note os.DirEntry: 5ea. 的方法都可能执行一次系统调用
     ，但是 *note is_dir(): 20b4. 和 *note is_file(): 748. 通常只在有符
     号链接时才执行一次系统调用。*note os.DirEntry.stat(): 20b5. 在 Unix
     上始终需要一次系统调用，而在 Windows 上只在有符号链接时才需要。

     `path' 可以是 *note 类路径对象: 472.。如果 `path' 是（直接传入或通
     过 *note PathLike: 5e5. 接口间接传入的） ‘bytes’ 类型，那么每个
     *note os.DirEntry: 5ea. 的 *note name: 20b6. 和 *note path: 20b7. 属
     性将是 ‘bytes’ 类型，其他情况下是 ‘str’ 类型。

     本函数也支持 *note 指定文件描述符为参数: 4bb.，其中描述符必须指向目
     录。

     引发一个 *note 审计事件: fa1. ‘os.scandir’，附带参数 ‘path’。

     *note scandir(): 389. 迭代器支持 *note 上下文管理: 661. 协议，并具
     有以下方法：

      -- 成員函式: scandir.close ()

          关闭迭代器并释放占用的资源。

          当迭代器迭代完毕，或垃圾回收，或迭代过程出错时，将自动调用本方
          法。但仍建议显式调用它或使用 *note with: 7da. 语句。

          3.6 版新加入.

     下面的例子演示了 *note scandir(): 389. 的简单用法，用来显示给定
     `path' 中所有不以 ‘'.'’ 开头的文件（不包括目录）。‘entry.is_file()’
     通常不会增加一次额外的系统调用:

          with os.scandir(path) as it:
              for entry in it:
                  if not entry.name.startswith('.') and entry.is_file():
                      print(entry.name)

          備註: 在基于 Unix 的系统上，*note scandir(): 389. 使用系统的
          opendir()(3) 和 readdir()(4) 函数。在 Windows 上，它使用 Win32
          FindFirstFileW(5) 和 FindNextFileW(6) 函数。

     3.5 版新加入.

     3.6 版新加入: 添加了对 *note 上下文管理: 661. 协议和 *note close():
     660. 方法的支持。如果 *note scandir(): 389. 迭代器没有迭代完毕且没
     有显式关闭，其析构函数将发出 *note ResourceWarning: 5ca. 警告。

     本函数接受一个 *note 类路径对象: 472.。

     3.7 版更變: 在 Unix 上新增支持 *note 指定文件描述符为参数: 4bb.。

 -- 類別: os.DirEntry

     由 *note scandir(): 389. 生成的对象，用于显示目录内某个条目的文件路
     径和其他文件属性。

     *note scandir(): 389. 将在不进行额外系统调用的情况下，提供尽可能多
     的此类信息。每次进行 ‘stat()’ 或 ‘lstat()’ 系统调用时，
     ‘os.DirEntry’ 对象会将结果缓存下来。

     ‘os.DirEntry’ 实例不适合存储在长期存在的数据结构中，如果你知道文件
     元数据已更改，或者自调用 *note scandir(): 389. 以来已经经过了很长时
     间，请调用 ‘os.stat(entry.path)’ 来获取最新信息。

     因为 ‘os.DirEntry’ 方法可以进行系统调用，所以它也可能抛出 *note
     OSError: 304. 异常。如需精确定位错误，可以逐个调用 ‘os.DirEntry’ 中
     的方法来捕获 *note OSError: 304.，并适当处理。

     为了能直接用作 *note 类路径对象: 472.，‘os.DirEntry’ 实现了 *note
     PathLike: 5e5. 接口。

     ‘os.DirEntry’ 实例所包含的属性和方法如下：

      -- 屬性: name

          本条目的基本文件名，是根据 *note scandir(): 389. 的 `path' 参
          数得出的相对路径。

          如果 *note scandir(): 389. 的 `path' 参数是 ‘bytes’ 类型，则
          *note name: 2040. 属性也是 ‘bytes’ 类型，否则为 ‘str’。使用
          *note fsdecode(): 5e8. 解码 byte 类型的文件名。

      -- 屬性: path

          本条目的完整路径：等效于 ‘os.path.join(scandir_path,
          entry.name)’，其中 `scandir_path' 就是 *note scandir(): 389. 的
          `path' 参数。仅当 *note scandir(): 389. 的 `path' 参数为绝对路
          径时，本路径才是绝对路径。如果 *note scandir(): 389. 的 `path'
          参数是 *note 文件描述符: 4bb.，则 *note path: c5. 属性与上述
          *note name: 2040. 属性相同。

          如果 *note scandir(): 389. 的 `path' 参数是 ‘bytes’ 类型，则
          *note path: c5. 属性也是 ‘bytes’ 类型，否则为 ‘str’。使用
          *note fsdecode(): 5e8. 解码 byte 类型的文件名。

      -- 成員函式: inode ()

          返回本条目的索引节点号 (inode number)。

          这一结果是缓存在 ‘os.DirEntry’ 对象中的，请调用
          ‘os.stat(entry.path, follow_symlinks=False).st_ino’ 来获取最新
          信息。

          一开始没有缓存时，在 Windows 上需要一次系统调用，但在 Unix 上
          不需要。

      -- 成員函式: is_dir (*, follow_symlinks=True)

          如果本条目是目录，或是指向目录的符号链接，则返回 ‘True’。如果
          本条目是文件，或指向任何其他类型的文件，或该目录不再存在，则返
          回 ‘False’。

          如果 `follow_symlinks' 是 ‘False’，那么仅当本条目为目录时返回
          ‘True’ （不跟踪符号链接），如果本条目是任何类型的文件，或该文
          件不再存在，则返回 ‘False’。

          这一结果是缓存在 ‘os.DirEntry’ 对象中的，且 `follow_symlinks'
          为 ‘True’ 和 ‘False’ 时的缓存是分开的。请调用 *note os.stat():
          321. 和 *note stat.S_ISDIR(): 1d5f. 来获取最新信息。

          一开始没有缓存时，大多数情况下不需要系统调用。特别是对于非符号
          链接，Windows 和 Unix 都不需要系统调用，除非某些 Unix 文件系统
          （如网络文件系统）返回了 ‘dirent.d_type == DT_UNKNOWN’。如果本
          条目是符号链接，则需要一次系统调用来跟踪它（除非
          `follow_symlinks' 为 ‘False’）。

          本方法可能抛出 *note OSError: 304. 异常，如 *note
          PermissionError: 6f6. 异常，但 *note FileNotFoundError: 8ad. 异
          常会被内部捕获且不会抛出。

      -- 成員函式: is_file (*, follow_symlinks=True)

          如果本条目是文件，或是指向文件的符号链接，则返回 ‘True’。如果
          本条目是目录，或指向目录，或指向其他非文件条目，或该文件不再存
          在，则返回 ‘False’。

          如果 `follow_symlinks' 是 ‘False’，那么仅当本条目为文件时返回
          ‘True’ （不跟踪符号链接），如果本条目是目录或其他非文件条目，
          或该文件不再存在，则返回 ‘False’。

          这一结果是缓存在 ‘os.DirEntry’ 对象中的。缓存、系统调用、异常
          抛出都与 *note is_dir(): 20b4. 一致。

      -- 成員函式: is_symlink ()

          如果本条目是符号链接（即使是断开的链接），返回 ‘True’。如果是
          目录或任何类型的文件，或本条目不再存在，返回 ‘False’。

          这一结果是缓存在 ‘os.DirEntry’ 对象中的，请调用 *note
          os.path.islink(): 323. 来获取最新信息。

          一开始没有缓存时，大多数情况下不需要系统调用。其实 Windows 和
          Unix 都不需要系统调用，除非某些 Unix 文件系统（如网络文件系统
          ）返回了 ‘dirent.d_type == DT_UNKNOWN’。

          本方法可能抛出 *note OSError: 304. 异常，如 *note
          PermissionError: 6f6. 异常，但 *note FileNotFoundError: 8ad. 异
          常会被内部捕获且不会抛出。

      -- 成員函式: stat (*, follow_symlinks=True)

          返回本条目对应的 *note stat_result: 11bf. 对象。本方法默认会跟
          踪符号链接，要获取符号链接本身的 stat，请添加
          ‘follow_symlinks=False’ 参数。

          在 Unix 上，本方法需要一次系统调用。在 Windows 上，仅在
          `follow_symlinks' 为 ‘True’ 且该条目是一个重解析点（如符号链接
          或目录结点）时，才需要一次系统调用。

          在 Windows 上，*note stat_result: 11bf. 的 ‘st_ino’、‘st_dev’
          和 ‘st_nlink’ 属性总是为零。请调用 *note os.stat(): 321. 以获
          得这些属性。

          这一结果是缓存在 ‘os.DirEntry’ 对象中的，且 `follow_symlinks'
          为 ‘True’ 和 ‘False’ 时的缓存是分开的。请调用 *note os.stat():
          321. 来获取最新信息。

     注意，‘os.DirEntry’ 和 *note pathlib.Path: 32f. 的几个属性和方法之
     间存在很好的对应关系。具体来说是 ‘name’ 属性，以及 ‘is_dir()’、
     ‘is_file()’、‘is_symlink()’ 和 ‘stat()’ 方法，在两个类中具有相同的
     含义。

     3.5 版新加入.

     3.6 版更變: 添加了对 *note PathLike: 5e5. 接口的支持。在 Windows 上
     添加了对 *note bytes: 172. 类型路径的支持。

 -- 函式: os.stat (path, *, dir_fd=None, follow_symlinks=True)

     获取文件或文件描述符的状态。在所给路径上执行等效于 ‘stat()’ 系统调
     用的操作。`path' 可以是字符串类型，或（直接传入或通过 *note
     PathLike: 5e5. 接口间接传入的） bytes 类型，或打开的文件描述符。返
     回一个 *note stat_result: 11bf. 对象。

     本函数默认会跟踪符号链接，要获取符号链接本身的 stat，请添加
     ‘follow_symlinks=False’ 参数，或使用 *note lstat(): 322.。

     本函数支持 *note 指定文件描述符为参数: 4bb. 和 *note
     不跟踪符号链接: b0c.。

     在 Windows 上，传入 ‘follow_symlinks=False’ 将禁用所有名称代理重解
     析点，其中包括符号链接和目录结点。其他类型的重解析点将直接打开，比
     如不像链接的或系统无法跟踪的重解析点。当多个链接形成一个链时，本方
     法可能会返回原始链接的 stat，无法完整遍历到非链接的对象。在这种情况
     下，要获取最终路径的 stat，请使用 *note os.path.realpath(): 32d. 函
     数尽可能地解析路径，并在解析结果上调用 *note lstat(): 322.。这不适
     用于空链接或交接点，否则会抛出异常。

     示例:

          >>> 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

     也參考
     ......

     *note fstat(): 752. 和 *note lstat(): 322. 函数。

     3.3 版新加入: 增加 `dir_fd' 和 `follow_symlinks' 参数，可指定文件描
     述符代替路径。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

     3.8 版更變: 在 Windows 上，本方法将跟踪系统能解析的所有重解析点，并
     且传入 ‘follow_symlinks=False’ 会停止跟踪所有名称代理重解析点。现在
     ，如果操作系统遇到无法跟踪的重解析点，`stat' 将返回原始路径的信息，
     就像已指定 ‘follow_symlinks=False’ 一样，而不会抛出异常。

 -- 類別: os.stat_result

     本对象的属性大致对应于 ‘stat’ 结构体成员，主要作为 *note os.stat():
     321.、*note os.fstat(): 752. 和 *note os.lstat(): 322. 的返回值。

     属性：

      -- 屬性: st_mode

          文件模式：包括文件类型和文件模式位（即权限位）。

      -- 屬性: st_ino

          与平台有关，但如果不为零，则根据 ‘st_dev’ 值唯一地标识文件。通
          常：

             * 在 Unix 上该值表示索引节点号 (inode number)。

             * 在 Windows 上该值表示 文件索引号(7) 。

      -- 屬性: st_dev

          该文件所在设备的标识符。

      -- 屬性: st_nlink

          硬链接的数量。

      -- 屬性: st_uid

          文件所有者的用户 ID。

      -- 屬性: st_gid

          文件所有者的用户组 ID。

      -- 屬性: st_size

          文件大小（以字节为单位），文件可以是常规文件或符号链接。符号链
          接的大小是它包含的路径的长度，不包括末尾的空字节。

     时间戳：

      -- 屬性: st_atime

          最近的访问时间，以秒为单位。

      -- 屬性: st_mtime

          最近的修改时间，以秒为单位。

      -- 屬性: st_ctime

          取决于平台：

             * 在 Unix 上表示最近的元数据更改时间，

             * 在 Windows 上表示创建时间，以秒为单位。

      -- 屬性: st_atime_ns

          最近的访问时间，以纳秒表示，为整数。

      -- 屬性: st_mtime_ns

          最近的修改时间，以纳秒表示，为整数。

      -- 屬性: st_ctime_ns

          取决于平台：

             * 在 Unix 上表示最近的元数据更改时间，

             * 在 Windows 上表示创建时间，以纳秒表示，为整数。

          備註: *note st_atime: 20c1.、*note st_mtime: 1eb9. 和 *note
          st_ctime: 20c2. 属性的确切含义和分辨率取决于操作系统和文件系统
          。例如，在使用 FAT 或 FAT32 文件系统的 Windows 上，*note
          st_mtime: 1eb9. 有 2 秒的分辨率，而 *note st_atime: 20c1. 仅有
          1 天的分辨率。详细信息请参阅操作系统文档。

          类似地，尽管 *note st_atime_ns: 20c3.、*note st_mtime_ns:
          20c4. 和 *note st_ctime_ns: 20c5. 始终以纳秒表示，但许多系统并
          不提供纳秒精度。在确实提供纳秒精度的系统上，用于存储 *note
          st_atime: 20c1.、*note st_mtime: 1eb9. 和 *note st_ctime:
          20c2. 的浮点对象无法保留所有精度，因此不够精确。如果需要确切的
          时间戳，则应始终使用 *note st_atime_ns: 20c3.、*note
          st_mtime_ns: 20c4. 和 *note st_ctime_ns: 20c5.。

     在某些 Unix 系统上（如 Linux 上），以下属性可能也可用：

      -- 屬性: st_blocks

          为文件分配的字节块数，每块 512 字节。文件是稀疏文件时，它可能
          小于 *note st_size: 20c0./512。

      -- 屬性: st_blksize

          “首选的” 块大小，用于提高文件系统 I/O 效率。写入文件时块大小太
          小可能会导致读取-修改-重写效率低下。

      -- 屬性: st_rdev

          设备类型（如果是 inode 设备）。

      -- 屬性: st_flags

          用户定义的文件标志位。

     在其他 Unix 系统上（如 FreeBSD 上），以下属性可能可用（但仅当 root
     使用它们时才被填充）：

      -- 屬性: st_gen

          文件生成号。

      -- 屬性: st_birthtime

          文件创建时间。

     在 Solaris 及其衍生版本上，以下属性可能也可用：

      -- 屬性: st_fstype

          文件所在文件系统的类型的唯一标识，为字符串。

     On macOS systems, the following attributes may also be available:

      -- 屬性: st_rsize

          文件的实际大小。

      -- 屬性: st_creator

          文件的创建者。

      -- 屬性: st_type

          文件类型。

     在 Windows 系统上，以下属性也可用：

      -- 屬性: st_file_attributes

          Windows 文件属性：‘dwFileAttributes’，由
          ‘GetFileInformationByHandle()’ 返回的
          ‘BY_HANDLE_FILE_INFORMATION’ 结构体的成员之一。请参阅 *note
          stat: f4. 模块中的 ‘FILE_ATTRIBUTE_*’ 常量。

      -- 屬性: st_reparse_tag

          当 *note st_file_attributes: 80f. 存在
          ‘FILE_ATTRIBUTE_REPARSE_POINT’ 集合时，本字段包含重解析点类型
          标记。请参阅 *note stat: f4. 模块中的 ‘IO_REPARSE_TAG_*’ 常量
          。

     标准模块 *note stat: f4. 中定义了函数和常量，这些函数和常量可用于从
     ‘stat’ 结构体中提取信息。（在 Windows 上，某些项填充的是虚值。）

     为了向后兼容，一个 *note stat_result: 11bf. 实例还可以作为至少包含
     10 个整数的元组访问，以提供 ‘stat’ 结构中最重要（和可移植）的成员，
     整数顺序为 *note st_mode: 20ba, *note st_ino: 20bb, *note st_dev:
     20bc, *note st_nlink: 20bd, *note st_uid: 20be, *note st_gid: 20bf,
     *note st_size: 20c0, *note st_atime: 20c1, *note st_mtime: 1eb9,
     *note st_ctime: 20c2.。某些实现可能在末尾还有更多项。为了与旧版
     Python 兼容，以元组形式访问 *note stat_result: 11bf. 始终返回整数。

     3.3 版新加入: 添加了 *note st_atime_ns: 20c3.、*note st_mtime_ns:
     20c4. 和 *note st_ctime_ns: 20c5. 成员。

     3.5 版新加入: 在 Windows 上添加了 *note st_file_attributes: 80f. 成
     员。

     3.5 版更變: 在 Windows 上，如果可用，会返回文件索引作为 *note
     st_ino: 20bb. 的值。

     3.7 版新加入: 在 Solaris 及其衍生版本上添加了 *note st_fstype: 4c5.
     成员。

     3.8 版新加入: 在 Windows 上添加了 *note st_reparse_tag: 20cf. 成员
     。

     3.8 版更變: 在 Windows 上，*note st_mode: 20ba. 成员现在可以根据需
     要将特殊文件标识为 ‘S_IFCHR’、‘S_IFIFO’ 或 ‘S_IFBLK’。

 -- 函式: os.statvfs (path)

     在所给的路径上执行 ‘statvfs()’ 系统调用。返回值是一个对象，其属性描
     述了所给路径上的文件系统，并且与 ‘statvfs’ 结构体的成员相对应，即：
     ‘f_bsize’, ‘f_frsize’, ‘f_blocks’, ‘f_bfree’, ‘f_bavail’,
     ‘f_files’, ‘f_ffree’, ‘f_favail’, ‘f_flag’, ‘f_namemax’, ‘f_fsid’。

     为 ‘f_flag’ 属性位定义了两个模块级常量：如果存在 ‘ST_RDONLY’ 位，则
     文件系统以只读挂载；如果存在 ‘ST_NOSUID’ 位，则文件系统禁用或不支持
     setuid/setgid 位。

     为基于 GNU/glibc 的系统还定义了额外的模块级常量。它们是 ‘ST_NODEV’
     （禁止访问设备专用文件），‘ST_NOEXEC’ （禁止执行程序），
     ‘ST_SYNCHRONOUS’ （写入后立即同步），‘ST_MANDLOCK’ （允许文件系统上
     的强制锁定），‘ST_WRITE’ （写入文件/目录/符号链接），‘ST_APPEND’ （
     仅追加文件），‘ST_IMMUTABLE’ （不可变文件），‘ST_NOATIME’ （不更新
     访问时间），‘ST_NODIRATIME’ （不更新目录访问时间），‘ST_RELATIME’ （
     相对于 mtime/ctime 更新访问时间）。

     本函数支持 *note 指定文件描述符为参数: 4bb.。

     *note 可用性: 1491.: Unix。

     3.2 版更變: 添加了 ‘ST_RDONLY’ 和 ‘ST_NOSUID’ 常量。

     3.3 版新加入: 新增支持将 `path' 参数指定为打开的文件描述符。

     3.4 版更變: 添加了 ‘ST_NODEV’、‘ST_NOEXEC’、‘ST_SYNCHRONOUS’、
     ‘ST_MANDLOCK’、‘ST_WRITE’、‘ST_APPEND’、‘ST_IMMUTABLE’、
     ‘ST_NOATIME’、‘ST_NODIRATIME’ 和 ‘ST_RELATIME’ 常量。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

     3.7 版新加入: 添加了 ‘f_fsid’。

 -- Data: os.supports_dir_fd

     一个 *note set: 1f6. 对象，指示 *note os: c4. 模块中的哪些函数接受
     一个打开的文件描述符作为 `dir_fd' 参数。不同平台提供的功能不同，且
     Python 用于实现 `dir_fd' 参数的底层函数并非在 Python 支持的所有平台
     上都可用。考虑到一致性，支持 `dir_fd' 的函数始终允许指定描述符，但
     如果在底层不支持时调用了该函数，则会抛出异常。（在所有平台上始终支
     持将 `dir_fd' 指定为 ‘None’。）

     要检查某个函数是否接受打开的文件描述符作为 `dir_fd' 参数，请在
     ‘supports_dir_fd’ 前使用 ‘in’ 运算符。例如，如果 *note os.stat():
     321. 在当前平台上接受打开的文件描述符作为 `dir_fd' 参数，则此表达式
     的计算结果为 ‘True’:

          os.stat in os.supports_dir_fd

     目前 `dir_fd' 参数仅在 Unix 平台上有效，在 Windows 上均无效。

     3.3 版新加入.

 -- Data: os.supports_effective_ids

     一个 *note set: 1f6. 对象，指示 *note os.access(): b0d. 是否允许在
     当前平台上将其 `effective_ids' 参数指定为 ‘True’。（所有平台都支持
     将 `effective_ids' 指定为 ‘False’。）如果当前平台支持，则集合将包含
     *note os.access(): b0d.，否则集合为空。

     如果当前平台上的 *note os.access(): b0d. 支持 ‘effective_ids=True’，
     则此表达式的计算结果为 ‘True’:

          os.access in os.supports_effective_ids

     目前仅 Unix 平台支持 `effective_ids'，Windows 不支持。

     3.3 版新加入.

 -- Data: os.supports_fd

     一个 *note set: 1f6. 对象，指示在当前平台上 *note os: c4. 模块中的
     哪些函数接受一个打开的文件描述符作为 `path' 参数。不同平台提供的功
     能不同，且 Python 所使用到的底层函数（用于实现接受描述符作为
     `path'）并非在 Python 支持的所有平台上都可用。

     要判断某个函数是否接受打开的文件描述符作为 `path' 参数，请在
     ‘supports_fd’ 前使用 ‘in’ 运算符。例如，如果 *note os.chdir(): 16e.
     在当前平台上接受打开的文件描述符作为 `path' 参数，则此表达式的计算
     结果为 ‘True’:

          os.chdir in os.supports_fd

     3.3 版新加入.

 -- Data: os.supports_follow_symlinks

     一个 *note set: 1f6. 对象，指示在当前平台上 *note os: c4. 模块中的
     哪些函数的 `follow_symlinks' 参数可指定为 ‘False’。不同平台提供的功
     能不同，且 Python 用于实现 `follow_symlinks' 的底层函数并非在
     Python 支持的所有平台上都可用。考虑到一致性，支持 `follow_symlinks'
     的函数始终允许将其指定为 ‘False’，但如果在底层不支持时调用了该函数
     ，则会抛出异常。（在所有平台上始终支持将 `follow_symlinks' 指定为
     ‘True’。）

     要检查某个函数的 `follow_symlinks' 参数是否可以指定为 ‘False’，请在
     ‘supports_follow_symlinks’ 前使用 ‘in’ 运算符。例如，如果在当前平台
     上调用 *note os.stat(): 321. 时可以指定 ‘follow_symlinks=False’，则
     此表达式的计算结果为 ‘True’:

          os.stat in os.supports_follow_symlinks

     3.3 版新加入.

 -- 函式: os.symlink (src, dst, target_is_directory=False, *,
          dir_fd=None)

     创建一个指向 `src' 的符号链接，名为 `dst'。

     在 Windows 上，符号链接可以表示文件或目录两种类型，并且不会动态改变
     类型。如果目标存在，则新建链接的类型将与目标一致。否则，如果
     `target_is_directory' 为 ‘True’，则符号链接将创建为目录链接，为
     ‘False’ （默认）将创建为文件链接。在非 Windows 平台上，
     `target_is_directory' 被忽略。

     本函数支持 *note 基于目录描述符的相对路径: b0b.。

          備註: 在 Windows 10 或更高版本上，如果启用了开发人员模式，非特
          权帐户可以创建符号链接。如果开发人员模式不可用/未启用，则需要
          `SeCreateSymbolicLinkPrivilege' 权限，或者该进程必须以管理员身
          份运行。

          当本函数由非特权账户调用时，抛出 *note OSError: 304. 异常。

     引发一个 *note 审计事件: fa1. ‘os.symlink’，附带参数 ‘src’、‘dst’、
     ‘dir_fd’。

     *note 可用性: 1491.: Unix, Windows。

     3.2 版更變: 添加对 Windows 6.0 (Vista) 符号链接的支持。

     3.3 版新加入: 添加了 `dir_fd' 参数，现在在非 Windows 平台上允许
     `target_is_directory' 参数。

     3.6 版更變: 接受一个 *note 类路径对象: 472. 作为 `src' 和 `dst'。

     3.8 版更變: 针对启用了开发人员模式的 Windows，添加了非特权账户创建
     符号链接的支持。

 -- 函式: os.sync ()

     强制将所有内容写入磁盘。

     *note 可用性: 1491.: Unix。

     3.3 版新加入.

 -- 函式: os.truncate (path, length)

     截断 `path' 对应的文件，以使其最大为 `length' 字节。

     本函数支持 *note 指定文件描述符为参数: 4bb.。

     引发一个 *note 审计事件: fa1. ‘os.truncate’，附带参数 ‘path’,
     ‘length’。

     *note 可用性: 1491.: Unix, Windows。

     3.3 版新加入.

     3.5 版更變: 添加了 Windows 支持

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.unlink (path, *, dir_fd=None)

     移除（删除）文件 `path'。该函数在语义上与 *note remove(): b13. 相同
     ，‘unlink’ 是其传统的 Unix 名称。请参阅 *note remove(): b13. 的文档
     以获取更多信息。

     引发一个 *note 审计事件: fa1. ‘os.remove’，附带参数 ‘path’、
     ‘dir_fd’。

     3.3 版新加入: `dir_fd' 参数。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.utime (path, times=None, *[, ns], dir_fd=None,
          follow_symlinks=True)

     设置文件 `path' 的访问时间和修改时间。

     *note utime(): b19. 有 `times' 和 `ns' 两个可选参数，它们指定了设置
     给 `path' 的时间，用法如下：

        - 如果指定 `ns'，它必须是一个 ‘(atime_ns, mtime_ns)’ 形式的二元
          组，其中每个成员都是一个表示纳秒的整数。

        - 如果 `times' 不为 ‘None’，则它必须是 ‘(atime, mtime)’ 形式的二
          元组，其中每个成员都是一个表示秒的 int 或 float。

        - 如果 `times' 为 ‘None’ 且未指定 `ns'，则相当于指定
          ‘ns=(atime_ns, mtime_ns)’，其中两个时间均为当前时间。

     同时为 `times' 和 `ns' 指定元组会出错。

     注意，根据操作系统记录访问时间和修改时间的分辨率，后续的 *note
     stat(): 321. 调用可能不会返回此处设置的确切时间。请参阅 *note
     stat(): 321.。保留精确时间的最佳方法是使用 *note os.stat(): 321. 结
     果对象中的 `st_atime_ns' 和 `st_mtime_ns' 字段，并将 `ns' 参数设置
     为 ‘utime’。

     本函数支持 *note 指定文件描述符: 4bb.、*note
     指定基于目录描述符的相对路径: b0b. 和 *note 不跟踪符号链接: b0c.。

     引发一个 *note 审计事件: fa1. ‘os.utime’，附带参数 ‘path’、
     ‘times’、‘ns’、‘dir_fd’。

     3.3 版新加入: 新增支持将 `path' 参数指定为打开的文件描述符，以及支
     持 `dir_fd'、`follow_symlinks' 和 `ns' 参数。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.walk (top, topdown=True, onerror=None, followlinks=False)

     生成目录树中的文件名，方式是按上->下或下->上顺序浏览目录树。对于以
     `top' 为根的目录树中的每个目录（包括 `top' 本身），它都会生成一个三
     元组 ‘(dirpath, dirnames, filenames)’。

     `dirpath' 是表示目录路径的字符串。 `dirnames' 是 `dirpath' 中子目录
     名称组成的列表 (excluding ‘'.'’ and ‘'..'’)。 `filenames' 是
     `dirpath' 中非目录文件名称组成的列表。 请注意列表中的名称不带路径部
     分。 要获取 `dirpath' 中文件或目录的完整路径（以 `top' 打头），请执
     行 ‘os.path.join(dirpath, name)’。 列表是否排序取决于具体文件系统。
     如果有文件或列表生成期间被移除或添加到 `dirpath' 目录中，是否要包括
     该文件的名称并没有规定。

     如果可选参数 `topdown' 为 ‘True’ 或未指定，则在所有子目录的三元组之
     前生成父目录的三元组（目录是自上而下生成的）。如果 `topdown' 为
     ‘False’，则在所有子目录的三元组生成之后再生成父目录的三元组（目录是
     自下而上生成的）。无论 `topdown' 为何值，在生成目录及其子目录的元组
     之前，都将检索全部子目录列表。

     当 `topdown' 为 ‘True’ 时，调用者可以就地修改 `dirnames' 列表（也许
     用到了 *note del: 13a2. 或切片），而 *note walk(): 747. 将仅仅递归
     到仍保留在 `dirnames' 中的子目录内。这可用于减少搜索、加入特定的访
     问顺序，甚至可在继续 *note walk(): 747. 之前告知 *note walk(): 747.
     由调用者新建或重命名的目录的信息。当 `topdown' 为 ‘False’ 时，修改
     `dirnames' 对 walk 的行为没有影响，因为在自下而上模式中，`dirnames'
     中的目录是在 `dirpath' 本身之前生成的。

     默认将忽略 *note scandir(): 389. 调用中的错误。如果指定了可选参数
     `onerror'，它应该是一个函数。出错时它会被调用，参数是一个 *note
     OSError: 304. 实例。它可以报告错误然后继续遍历，或者抛出异常然后中
     止遍历。注意，可以从异常对象的 ‘filename’ 属性中获取出错的文件名。

     *note walk(): 747. 默认不会递归进指向目录的符号链接。可以在支持符号
     链接的系统上将 `followlinks' 设置为 ‘True’，以访问符号链接指向的目
     录。

          備註: 注意，如果链接指向自身的父目录，则将 `followlinks' 设置
          为 ‘True’ 可能导致无限递归。*note walk(): 747. 不会记录它已经
          访问过的目录。

          備註: 如果传入的是相对路径，请不要在恢复 *note walk(): 747. 之
          间更改当前工作目录。*note walk(): 747. 不会更改当前目录，并假
          定其调用者也不会更改当前目录。

     下面的示例遍历起始目录内所有子目录，打印每个目录内的文件占用的字节
     数，CVS 子目录不会被遍历:

          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

     在下一个示例（*note shutil.rmtree(): 349. 的简单实现）中，必须使树
     自下而上遍历，因为 *note rmdir(): b16. 只允许在目录为空时删除目录:

          # 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))

     引发一个 *note 审计事件: fa1. ‘os.walk’，附带参数 ‘top’, ‘topdown’,
     ‘onerror’, ‘followlinks’。

     3.5 版更變: 现在，本函数调用的是 *note os.scandir(): 389. 而不是
     *note os.listdir(): b1c.，从而减少了调用 *note os.stat(): 321. 的次
     数而变得更快。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.fwalk (top='.', topdown=True, onerror=None, *,
          follow_symlinks=False, dir_fd=None)

     本方法的行为与 *note walk(): 747. 完全一样，除了它产生的是 4 元组
     ‘(dirpath, dirnames, filenames, dirfd)’，并且它支持 ‘dir_fd’。

     `dirpath'、`dirnames' 和 `filenames' 与 *note walk(): 747. 输出的相
     同，`dirfd' 是指向目录 `dirpath' 的文件描述符。

     本函数始终支持 *note 基于目录描述符的相对路径: b0b. 和 *note
     不跟踪符号链接: b0c.。但是请注意，与其他函数不同，*note fwalk():
     4ba. 的 `follow_symlinks' 的默认值为 ‘False’。

          備註: 由于 *note fwalk(): 4ba. 会生成文件描述符，而它们仅在下
          一个迭代步骤前有效，因此如果要将描述符保留更久，则应复制它们（
          比如使用 *note dup(): 10e9.）。

     下面的示例遍历起始目录内所有子目录，打印每个目录内的文件占用的字节
     数，CVS 子目录不会被遍历:

          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

     在下一个示例中，必须使树自下而上遍历，因为 *note rmdir(): b16. 只允
     许在目录为空时删除目录:

          # 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)

     引发一个 *note 审计事件: fa1. ‘os.fwalk’，附带参数 ‘top’,
     ‘topdown’, ‘onerror’, ‘follow_symlinks’, ‘dir_fd’。

     *note 可用性: 1491.: Unix。

     3.3 版新加入.

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

     3.7 版更變: 添加了对 *note bytes: 172. 类型路径的支持。

 -- 函式: os.memfd_create (name[, flags=os.MFD_CLOEXEC])

     创建一个匿名文件，返回指向该文件的文件描述符。`flags' 必须是系统上
     可用的 ‘os.MFD_*’ 常量之一（或将它们按位“或”组合起来）。新文件描述
     符默认是 *note 不可继承的: 8e7.。

     `name' 提供的名称会被用作文件名，并且 ‘/proc/self/fd/’ 目录中相应符
     号链接的目标将显示为该名称。显示的名称始终以 ‘memfd:’ 为前缀，并且
     仅用于调试目的。名称不会影响文件描述符的行为，因此多个文件可以有相
     同的名称，不会有副作用。

     *note 可用性: 1491.：Linux 3.17 或更高版本，且装有 glibc 2.27 或更
     高版本。

     3.8 版新加入.

 -- Data: os.MFD_CLOEXEC
 -- Data: os.MFD_ALLOW_SEALING
 -- Data: os.MFD_HUGETLB
 -- Data: os.MFD_HUGE_SHIFT
 -- Data: os.MFD_HUGE_MASK
 -- Data: os.MFD_HUGE_64KB
 -- Data: os.MFD_HUGE_512KB
 -- Data: os.MFD_HUGE_1MB
 -- Data: os.MFD_HUGE_2MB
 -- Data: os.MFD_HUGE_8MB
 -- Data: os.MFD_HUGE_16MB
 -- Data: os.MFD_HUGE_32MB
 -- Data: os.MFD_HUGE_256MB
 -- Data: os.MFD_HUGE_512MB
 -- Data: os.MFD_HUGE_1GB
 -- Data: os.MFD_HUGE_2GB
 -- Data: os.MFD_HUGE_16GB

     以上标志位可以传递给 *note memfd_create(): 320.。

     *note 可用性: 1491.：Linux 3.17 或更高版本，且装有 glibc 2.27 或更
     高版本。‘MFD_HUGE*’ 标志仅在 Linux 4.14 及以上可用。

     3.8 版新加入.

* Menu:

* Linux 扩展属性::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0529

   (2) https://bugs.python.org/issue21082

   (3) 
http://pubs.opengroup.org/onlinepubs/009695399/functions/opendir.html

   (4) 
http://pubs.opengroup.org/onlinepubs/009695399/functions/readdir_r.html

   (5) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa364418(v=vs.85).aspx

   (6) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa364428(v=vs.85).aspx

   (7) https://msdn.microsoft.com/en-us/library/aa363788


File: python.info,  Node: Linux 扩展属性,  Up: 文件和目录

5.16.1.8 Linux 扩展属性
.......................

3.3 版新加入.

这些函数仅在 Linux 上可用。

 -- 函式: os.getxattr (path, attribute, *, follow_symlinks=True)

     返回 `path' 的扩展文件系统属性 `attribute' 的值。`attribute' 可以是
     bytes 或 str （直接传入或通过 *note PathLike: 5e5. 接口间接传入）。
     如果是 str，则使用文件系统编码来编码字符串。

     本函数支持 *note 指定文件描述符为参数: 4bb. 和 *note
     不跟踪符号链接: b0c.。

     引发一个 *note 审计事件: fa1. ‘os.getxattr’，附带参数 ‘path’、
     ‘attribute’。

     3.6 版更變: 接受一个 *note 类路径对象: 472. 作为 `path' 和
     `attribute'。

 -- 函式: os.listxattr (path=None, *, follow_symlinks=True)

     返回一个列表，包含 `path' 的所有扩展文件系统属性。列表中的属性都表
     示为字符串，它们是根据文件系统编码解码出来的。如果 `path' 为
     ‘None’，则 *note listxattr(): b27. 将检查当前目录。

     本函数支持 *note 指定文件描述符为参数: 4bb. 和 *note
     不跟踪符号链接: b0c.。

     引发一个 *note 审计事件: fa1. ‘os.listxattr’，附带参数 ‘path’。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os.removexattr (path, attribute, *, follow_symlinks=True)

     从 `path' 中删除扩展文件系统属性 `attribute'。`attribute' 应该是
     bytes 或 str （直接传入或通过 *note PathLike: 5e5. 接口间接传入）。
     如果是 str，则使用文件系统编码来编码字符串。

     本函数支持 *note 指定文件描述符为参数: 4bb. 和 *note
     不跟踪符号链接: b0c.。

     引发一个 *note 审计事件: fa1. ‘os.removexattr’，附带参数 ‘path’、
     ‘attribute’。

     3.6 版更變: 接受一个 *note 类路径对象: 472. 作为 `path' 和
     `attribute'。

 -- 函式: os.setxattr (path, attribute, value, flags=0, *,
          follow_symlinks=True)

     将 `path' 的扩展文件系统属性 `attribute' 设为 `value'。 `attribute'
     必须是没有内嵌 NUL 的字节串或字符串（直接或通过 *note PathLike:
     5e5. 间接传入）。 如果是字符串，则使用文件系统编码格式进行编码。
     `flags' 可以为 *note XATTR_REPLACE: 20e2. 或 *note XATTR_CREATE:
     20e3.。 如果指定 *note XATTR_REPLACE: 20e2. 而该属性不存在，则将引
     发 ‘ENODATA’。 如果指定 *note XATTR_CREATE: 20e3. 而该属性已存在，
     则将不创建该属性并将引发 ‘EEXISTS’。

     本函数支持 *note 指定文件描述符为参数: 4bb. 和 *note
     不跟踪符号链接: b0c.。

          備註: Linux kernel 2.6.39 以下版本的一个 bug 导致在某些文件系
          统上，flags 参数会被忽略。

     引发一个 *note 审计事件: fa1. ‘os.setxattr’，附带参数 ‘path’、
     ‘attribute’、‘value’、‘flags’。

     3.6 版更變: 接受一个 *note 类路径对象: 472. 作为 `path' 和
     `attribute'。

 -- Data: os.XATTR_SIZE_MAX

     一条扩展属性的值的最大大小。在当前的 Linux 上是 64 KiB。

 -- Data: os.XATTR_CREATE

     这是 *note setxattr(): b29. 的 flags 参数的可取值，它表示该操作必须
     创建一个属性。

 -- Data: os.XATTR_REPLACE

     这是 *note setxattr(): b29. 的 flags 参数的可取值，它表示该操作必须
     替换现有属性。


File: python.info,  Node: 进程管理,  Next: 调度器接口,  Prev: 文件和目录,  Up: os --- 多种操作系统接口

5.16.1.9 进程管理
.................

下列函数可用于创建和管理进程。

所有 *note exec*: 20e7. 函数都接受一个参数列表，用来给新程序加载到它的进
程中。在所有情况下，传递给新程序的第一个参数是程序本身的名称，而不是用户
在命令行上输入的参数。对于 C 程序员来说，这就是传递给 ‘main()’ 函数的
‘argv[0]’。例如，‘os.execv('/bin/echo', ['foo', 'bar'])’ 只会在标准输出
上打印 ‘bar’，而 ‘foo’ 会被忽略。

 -- 函式: os.abort ()

     发送 ‘SIGABRT’ 信号到当前进程。在 Unix 上，默认行为是生成一个核心转
     储。在 Windows 上，该进程立即返回退出代码 ‘3’。请注意，使用 *note
     signal.signal(): b58. 可以为 ‘SIGABRT’ 注册 Python 信号处理程序，而
     调用本函数将不会调用按前述方法注册的程序。

 -- 函式: os.add_dll_directory (path)

     将路径添加到 DLL 搜索路径。

     当需要解析扩展模块的依赖时（扩展模块本身通过 sys.path 解析），会使
     用该搜索路径，*note ctypes: 2a. 也会使用该搜索路径。

     要移除目录，可以在返回的对象上调用 `close()'，也可以在 *note with:
     7da. 语句内使用本方法。

     参阅 Microsoft 文档(1) 获取如何加载 DLL 的信息。

     引发一个 *note 审计事件: fa1. ‘os.add_dll_directory’，附带参数
     ‘path’。

     *note 可用性: 1491.: Windows。

     3.8 版新加入: 早期版本的 CPython 解析 DLL 时用的是当前进程的默认行
     为。这会导致不一致，比如不是每次都会去搜索 ‘PATH’ 和当前工作目录，
     且系统函数（如 ‘AddDllDirectory’ ）失效。

     在 3.8 中，DLL 的两种主要加载方式现在可以显式覆盖进程的行为，以确保
     一致性。请参阅 *note 移植说明: 3ec. 了解如何更新你的库。

 -- 函式: os.execl (path, arg0, arg1, ...)
 -- 函式: os.execle (path, arg0, arg1, ..., env)
 -- 函式: os.execlp (file, arg0, arg1, ...)
 -- 函式: os.execlpe (file, arg0, arg1, ..., env)
 -- 函式: os.execv (path, args)
 -- 函式: os.execve (path, args, env)
 -- 函式: os.execvp (file, args)
 -- 函式: os.execvpe (file, args, env)

     这些函数都将执行一个新程序，以替换当前进程。它们没有返回值。在 Unix
     上，新程序会加载到当前进程中，且进程号与调用者相同。过程中的错误会
     被报告为 *note OSError: 304. 异常。

     当前进程会被立即替换。打开的文件对象和描述符都不会刷新，因此如果这
     些文件上可能缓冲了数据，则应在调用 *note exec*: 20e7. 函数之前使用
     ‘sys.stdout.flush()’ 或 *note os.fsync(): 754. 刷新它们。

     *note exec*: 20e7. 函数的 "l" 和 "v" 变体不同在于命令行参数的传递方
     式。如果在编码时固定了参数数量，则 "l" 变体可能是最方便的，各参数作
     为 ‘execl*()’ 函数的附加参数传入即可。当参数数量可变时，"v" 变体更
     方便，参数以列表或元组的形式作为 `args' 参数传递。在这两种情况下，
     子进程的第一个参数都应该是即将运行的命令名称，但这不是强制性的。

     结尾包含 "p" 的变体（*note execlp(): 20ea.、*note execlpe(): 20eb.、
     *note execvp(): 20ec. 和 *note execvpe(): 20ed. ）将使用 ‘PATH’ 环
     境变量来查找程序 `file'。当环境被替换时（使用下一段讨论的 *note
     exec*e: 20e7. 变体之一）， ‘PATH’ 变量将来自于新环境。其他变体
     *note execl(): 20e7.、*note execle(): 20e9.、*note execv(): 2058. 和
     *note execve(): b1b. 不使用 ‘PATH’ 变量来查找程序，因此 `path' 必须
     包含正确的绝对或相对路径。

     对于 *note execle(): 20e9.、*note execlpe(): 20eb.、*note execve():
     b1b. 和 *note execvpe(): 20ed. （都以 "e" 结尾），`env' 参数是一个
     映射，用于定义新进程的环境变量（代替当前进程的环境变量）。而函数
     *note execl(): 20e7.、*note execlp(): 20ea.、*note execv(): 2058. 和
     *note execvp(): 20ec. 会将当前进程的环境变量过继给新进程。

     某些平台上的 *note execve(): b1b. 可以将 `path' 指定为打开的文件描
     述符。当前平台可能不支持此功能，可以使用 *note os.supports_fd: b1f.
     检查它是否支持。如果不可用，则使用它会抛出 *note
     NotImplementedError: 704. 异常。

     引发一个 *note 审计事件: fa1. ‘os.exec’，附带参数 ‘path’、‘args’、
     ‘env’。

     *note 可用性: 1491.: Unix, Windows。

     3.3 版新加入: 新增支持将 *note execve(): b1b. 的 `path' 参数指定为
     打开的文件描述符。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: os._exit (n)

     以状态码 `n' 退出进程，不会调用清理处理程序，不会刷新 stdio，等等。

          備註: 退出的标准方法是使用 ‘sys.exit(n)’。而 *note _exit():
          1854. 通常只应在 *note fork(): a42. 出的子进程中使用。

以下是已定义的退出代码，可以用于 *note _exit(): 1854.，尽管它们不是必需
的。这些退出代码通常用于 Python 编写的系统程序，例如邮件服务器的外部命令
传递程序。

     備註: 其中部分退出代码在部分 Unix 平台上可能不可用，因为平台间存在
     差异。如果底层平台定义了这些常量，那上层也会定义。

 -- Data: os.EX_OK

     退出代码，表示未发生任何错误。

     *note 可用性: 1491.: Unix。

 -- Data: os.EX_USAGE

     退出代码，表示命令使用不正确，如给出的参数数量有误。

     *note 可用性: 1491.: Unix。

 -- Data: os.EX_DATAERR

     退出代码，表示输入数据不正确。

     *note 可用性: 1491.: Unix。

 -- Data: os.EX_NOINPUT

     退出代码，表示某个输入文件不存在或不可读。

     *note 可用性: 1491.: Unix。

 -- Data: os.EX_NOUSER

     退出代码，表示指定的用户不存在。

     *note 可用性: 1491.: Unix。

 -- Data: os.EX_NOHOST

     退出代码，表示指定的主机不存在。

     *note 可用性: 1491.: Unix。

 -- Data: os.EX_UNAVAILABLE

     退出代码，表示所需的服务不可用。

     *note 可用性: 1491.: Unix。

 -- Data: os.EX_SOFTWARE

     退出代码，表示检测到内部软件错误。

     *note 可用性: 1491.: Unix。

 -- Data: os.EX_OSERR

     退出代码，表示检测到操作系统错误，例如无法 fork 或创建管道。

     *note 可用性: 1491.: Unix。

 -- Data: os.EX_OSFILE

     退出代码，表示某些系统文件不存在、无法打开或发生其他错误。

     *note 可用性: 1491.: Unix。

 -- Data: os.EX_CANTCREAT

     退出代码，表示无法创建用户指定的输出文件。

     *note 可用性: 1491.: Unix。

 -- Data: os.EX_IOERR

     退出代码，表示对某些文件进行读写时发生错误。

     *note 可用性: 1491.: Unix。

 -- Data: os.EX_TEMPFAIL

     退出代码，表示发生了暂时性故障。它可能并非意味着真正的错误，例如在
     可重试的情况下无法建立网络连接。

     *note 可用性: 1491.: Unix。

 -- Data: os.EX_PROTOCOL

     退出代码，表示协议交换是非法的、无效的或无法解读的。

     *note 可用性: 1491.: Unix。

 -- Data: os.EX_NOPERM

     退出代码，表示没有足够的权限执行该操作（但不适用于文件系统问题）。

     *note 可用性: 1491.: Unix。

 -- Data: os.EX_CONFIG

     退出代码，表示发生某种配置错误。

     *note 可用性: 1491.: Unix。

 -- Data: os.EX_NOTFOUND

     退出代码，表示的内容类似于“找不到条目”。

     *note 可用性: 1491.: Unix。

 -- 函式: os.fork ()

     Fork 出一个子进程。在子进程中返回 ‘0’，在父进程中返回子进程的进程号
     。如果发生错误，则抛出 *note OSError: 304. 异常。

     注意，当从线程中使用 ‘fork()’ 时，某些平台（包括 FreeBSD <= 6.3 和
     Cygwin）存在已知问题。

     引发一个 *note 审计事件: fa1. ‘os.fork’，没有附带参数。

     3.8 版更變: 不再支持在子解释器中调用 ‘fork()’ （将抛出 *note
     RuntimeError: 3dc. 异常）。

          警告: 有关 SSL 模块与 fork() 结合的应用，请参阅 *note ssl:
          f3.。

     *note 可用性: 1491.: Unix。

 -- 函式: os.forkpty ()

     Fork 出一个子进程，使用新的伪终端作为子进程的控制终端。返回一对
     ‘(pid, fd)’，其中 `pid' 在子进程中为 ‘0’，这是父进程中新子进程的进
     程号，而 `fd' 是伪终端主设备的文件描述符。对于更便于移植的方法，请
     使用 *note pty: d5. 模块。如果发生错误，则抛出 *note OSError: 304.
     异常。

     引发一个 *note 审计事件: fa1. ‘os.forkpty’，没有附带参数。

     3.8 版更變: 不再支持在子解释器中调用 ‘forkpty()’ （将抛出 *note
     RuntimeError: 3dc. 异常）。

     *note 可用性: 1491.: 某些 Unix。

 -- 函式: os.kill (pid, sig)

     将信号 `sig' 发送至进程 `pid'。特定平台上可用的信号常量定义在 *note
     signal: ea. 模块中。

     Windows： *note signal.CTRL_C_EVENT: 2100. 和 *note
     signal.CTRL_BREAK_EVENT: 2101. 信号是特殊信号，只能发送给共享同一个
     控制台窗口的控制台进程，如某些子进程。`sig' 取任何其他值将导致该进
     程被 TerminateProcess API 无条件终止，且退出代码为 `sig'。Windows 版
     本的 *note kill(): db9. 还需要传入待结束进程的句柄。

     另请参阅 *note signal.pthread_kill(): b55.。

     引发一个 *note 审计事件: fa1. ‘os.kill’，附带参数 ‘pid’、‘sig’。

     3.2 版新加入: Windows 支持。

 -- 函式: os.killpg (pgid, sig)

     将信号 `sig' 发送给进程组 `pgid'。

     引发一个 *note 审计事件: fa1. ‘os.killpg’，附带参数 ‘pgid’、‘sig’。

     *note 可用性: 1491.: Unix。

 -- 函式: os.nice (increment)

     将进程的优先级（nice 值）增加 `increment'，返回新的 nice 值。

     *note 可用性: 1491.: Unix。

 -- 函式: os.pidfd_open (pid, flags=0)

     返回一个文件描述符，它指向进程 `pid'。该描述符可用于管理进程，避免
     出现竞争和信号。`flags' 参数提供给将来扩展使用，当前没有定义标志值
     。

     更多详细信息请参阅 ‘pidfd_open(2)’ 手册页。

     *note 可用性: 1491.: Linux 5.3+。

     3.9 版新加入.

 -- 函式: os.plock (op)

     将程序段锁定到内存中。`op' 的值（定义在 ‘<sys/lock.h>’ 中）决定了哪
     些段被锁定。

     *note 可用性: 1491.: Unix。

 -- 函式: os.popen (cmd, mode='r', buffering=-1)

     打开一个管道，它通往 / 接受自命令 `cmd'。返回值是连接到管道的文件对
     象，根据 `mode' 是 ‘'r'’ （默认）还是 ‘'w'’ 决定该对象可以读取还是
     写入。`buffering' 参数与内置函数 *note open(): 16f. 相应的参数含义
     相同。返回的文件对象只能读写文本字符串，不能是字节类型。

     如果子进程成功退出，则 ‘close’ 方法返回 *note None: 203.。如果发生
     错误，则返回子进程的返回码。在 POSIX 系统上，如果返回码为正，则它就
     是进程返回值左移一个字节后的值。如果返回码为负，则进程是被信号终止
     的，返回码取反后就是该信号。（例如，如果子进程被终止，则返回值可能
     是 ‘- signal.SIGKILL’。）在 Windows 系统上，返回值包含子进程的返回
     码（有符号整数）。

     在 Unix 上，*note waitstatus_to_exitcode(): 1ce. 可以将 ‘close’ 方
     法的返回值（即退出状态，不能是 ‘None’）转换为退出码。在 Windows 上
     ，‘close’ 方法的结果直接就是退出码（或 ‘None’ ）。

     本方法是使用 *note subprocess.Popen: 3db. 实现的，如需更强大的方法
     来管理和沟通子进程，请参阅该类的文档。

 -- 函式: os.posix_spawn (path, argv, env, *, file_actions=None,
          setpgroup=None, resetids=False, setsid=False, setsigmask=(),
          setsigdef=(), scheduler=None)

     包装 ‘posix_spawn()’ C 库 API，使其可以从 Python 调用。

     大多数用户应使用 *note subprocess.run(): 4f2. 代替 *note
     posix_spawn(): 381.。

     仅位置参数 (Positional-only arguments) `path'、`args' 和 `env' 与
     *note execve(): b1b. 中的类似。

     `path' 形参是可执行文件的路径，`path' 中应当包含目录。 使用 *note
     posix_spawnp(): 114d. 可传入不带目录的可执行文件。

     `file_actions' 参数可以是由元组组成的序列，序列描述了对子进程中指定
     文件描述符采取的操作，这些操作会在 C 库实现的 ‘fork()’ 和 ‘exec()’
     步骤间完成。每个元组的第一个元素必须是下面列出的三个类型指示符之一
     ，用于描述元组剩余的元素：

      -- Data: os.POSIX_SPAWN_OPEN

          (‘os.POSIX_SPAWN_OPEN’, `fd', `path', `flags', `mode')

          执行 ‘os.dup2(os.open(path, flags, mode), fd)’。

      -- Data: os.POSIX_SPAWN_CLOSE

          (‘os.POSIX_SPAWN_CLOSE’, `fd')

          执行 ‘os.close(fd)’。

      -- Data: os.POSIX_SPAWN_DUP2

          (‘os.POSIX_SPAWN_DUP2’, `fd', `new_fd')

          执行 ‘os.dup2(fd, new_fd)’。

     这些元组对应于 C 库 ‘posix_spawn_file_actions_addopen()’，
     ‘posix_spawn_file_actions_addclose()’ 和
     ‘posix_spawn_file_actions_adddup2()’ API 调用，它们为调用
     ‘posix_spawn()’ 自身做准备。

     `setpgroup' 参数将子进程的进程组设置为指定值。如果指定值为 0，则子
     进程的进程组 ID 将与其进程 ID 相同。如果未设置 `setpgroup' 值，则子
     进程将继承父进程的进程组 ID。本参数对应于 C 库
     ‘POSIX_SPAWN_SETPGROUP’ 标志。

     如果 `resetids' 参数为 ‘True’，则会将子进程的有效用户 ID 和有效组
     ID 重置为父进程的实际用户 ID 和实际组 ID。如果该参数为 ‘False’，则
     子进程保留父进程的有效用户 ID 和有效组 ID。无论哪种情况，若在可执行
     文件上启用了 “设置用户 ID” 和 “设置组 ID” 权限位，它们将覆盖有效用
     户 ID 和有效组 ID 的设置。本参数对应于 C 库 ‘POSIX_SPAWN_RESETIDS’
     标志。

     如果 `setsid' 参数为 ‘True’，它将为 ‘posix_spawn’ 新建一个会话 ID。
     `setsid' 需要 ‘POSIX_SPAWN_SETSID’ 或 ‘POSIX_SPAWN_SETSID_NP’ 标志
     ，否则会抛出 *note NotImplementedError: 704. 异常。

     `setsigmask' 参数将信号掩码设置为指定的信号集合。如果未使用该参数，
     则子进程将继承父进程的信号掩码。本参数对应于 C 库
     ‘POSIX_SPAWN_SETSIGMASK’ 标志。

     `sigdef' 参数将集合中所有信号的操作全部重置为默认。本参数对应于 C 库
     ‘POSIX_SPAWN_SETSIGDEF’ 标志。

     `scheduler' 参数必须是一个元组，其中包含调度器策略（可选）以及携带
     了调度器参数的 *note sched_param: 2106. 实例。在调度器策略所在位置
     为 ‘None’ 表示未提供该值。本参数是 C 库 ‘POSIX_SPAWN_SETSCHEDPARAM’
     和 ‘POSIX_SPAWN_SETSCHEDULER’ 标志的组合。

     引发一个 *note 审计事件: fa1. ‘os.posix_spawn’，附带参数 ‘path’、
     ‘argv’、‘env’。

     3.8 版新加入.

     *note 可用性: 1491.: Unix。

 -- 函式: os.posix_spawnp (path, argv, env, *, file_actions=None,
          setpgroup=None, resetids=False, setsid=False, setsigmask=(),
          setsigdef=(), scheduler=None)

     包装 ‘posix_spawnp()’ C 库 API，使其可以从 Python 调用。

     与 *note posix_spawn(): 381. 相似，但是系统会在 ‘PATH’ 环境变量指定
     的目录列表中搜索可执行文件 `executable' （与 ‘execvp(3)’ 相同）。

     引发一个 *note 审计事件: fa1. ‘os.posix_spawn’，附带参数 ‘path’、
     ‘argv’、‘env’。

     3.8 版新加入.

     *note 可用性: 1491.: 请参阅 *note posix_spawn(): 381. 文档。

 -- 函式: os.register_at_fork (*, before=None, after_in_parent=None,
          after_in_child=None)

     注册可调用对象，在使用 *note os.fork(): a42. 或类似的进程克隆 API 派
     生新的子进程时，这些对象会运行。参数是可选的，且为仅关键字
     (Keyword-only) 参数。每个参数指定一个不同的调用点。

        * `before' 是一个函数，在 fork 子进程前调用。

        * `after_in_parent' 是一个函数，在 fork 子进程后从父进程调用。

        * `after_in_child' 是一个函数，从子进程中调用。

     只有希望控制权回到 Python 解释器时，才进行这些调用。典型的 *note
     子进程: f9. 启动时不会触发它们，因为子进程不会重新进入解释器。

     在注册的函数中，用于 fork 前运行的函数将按与注册相反的顺序调用。用
     于 fork 后（从父进程或子进程）运行的函数按注册顺序调用。

     注意，第三方 C 代码的 ‘fork()’ 调用可能不会调用这些函数，除非它显式
     调用了 *note PyOS_BeforeFork(): 535.、*note
     PyOS_AfterFork_Parent(): 536. 和 *note PyOS_AfterFork_Child():
     3ef.。

     函数注册后无法注销。

     *note 可用性: 1491.: Unix。

     3.7 版新加入.

 -- 函式: os.spawnl (mode, path, ...)
 -- 函式: os.spawnle (mode, path, ..., env)
 -- 函式: os.spawnlp (mode, file, ...)
 -- 函式: os.spawnlpe (mode, file, ..., env)
 -- 函式: os.spawnv (mode, path, args)
 -- 函式: os.spawnve (mode, path, args, env)
 -- 函式: os.spawnvp (mode, file, args)
 -- 函式: os.spawnvpe (mode, file, args, env)

     在新进程中执行程序 `path'。

     （注意，*note subprocess: f9. 模块提供了更强大的工具来生成新进程并
     跟踪执行结果，使用该模块比使用这些函数更好。尤其应当检查 *note 使用
     subprocess 模块替换旧函数: bc1. 部分。）

     `mode' 为 *note P_NOWAIT: 210e. 时，本函数返回新进程的进程号。
     `mode' 为 *note P_WAIT: 210f. 时，如果进程正常退出，返回退出代码，
     如果被终止，返回 ‘-signal’，其中 `signal' 是终止进程的信号。在
     Windows 上，进程号实际上是进程句柄，因此可以与 *note waitpid():
     760. 函数一起使用。

     注意在 VxWorks 上，新进程被终止时，本函数不会返回 ‘-signal’，而是会
     抛出 OSError 异常。

     *note spawn*: 20a3. 函数的 "l" 和 "v" 变体不同在于命令行参数的传递
     方式。如果在编码时固定了参数数量，则 "l" 变体可能是最方便的，各参数
     作为 ‘spawnl*()’ 函数的附加参数传入即可。当参数数量可变时，"v" 变体
     更方便，参数以列表或元组的形式作为 `args' 参数传递。在这两种情况下
     ，子进程的第一个参数都必须是即将运行的命令名称。

     结尾包含第二个 "p" 的变体（*note spawnlp(): 2108.、*note
     spawnlpe(): 2109.、*note spawnvp(): 210c. 和 *note spawnvpe():
     210d.）将使用 ‘PATH’ 环境变量来查找程序 `file'。当环境被替换时（使
     用下一段讨论的 *note spawn*e: 20a3. 变体之一）， ‘PATH’ 变量将来自
     于新环境。其他变体 *note spawnl(): 20a3.、*note spawnle(): 2107.、
     *note spawnv(): 210a. 和 *note spawnve(): 210b. 不使用 ‘PATH’ 变量
     来查找程序，因此 `path' 必须包含正确的绝对或相对路径。

     对于 *note spawnle(): 2107.、*note spawnlpe(): 2109.、*note
     spawnve(): 210b. 和 *note spawnvpe(): 210d. （都以 "e" 结尾），
     `env' 参数是一个映射，用于定义新进程的环境变量（代替当前进程的环境
     变量）。而函数 *note spawnl(): 20a3.、*note spawnlp(): 2108.、*note
     spawnv(): 210a. 和 *note spawnvp(): 210c. 会将当前进程的环境变量过
     继给新进程。注意，`env' 字典中的键和值必须是字符串。无效的键或值将
     导致函数出错，返回值为 ‘127’。

     例如，以下对 *note spawnlp(): 2108. 和 *note spawnvpe(): 210d. 的调
     用是等效的:

          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)

     引发一个 *note 审计事件: fa1. ‘os.spawn’，附带参数 ‘mode’、‘path’、
     ‘args’、‘env’。

     *note 可用性: 1491.: Unix, Windows。*note spawnlp(): 2108.、*note
     spawnlpe(): 2109.、*note spawnvp(): 210c. 和 *note spawnvpe():
     210d. 在 Windows 上不可用。*note spawnle(): 2107. 和 *note
     spawnve(): 210b. 在 Windows 上不是线程安全的，建议使用 *note
     subprocess: f9. 模块替代。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- Data: os.P_NOWAIT
 -- Data: os.P_NOWAITO

     *note spawn*: 20a3. 系列函数的 `mode' 参数的可取值。如果给出这些值
     中的任何一个，则 ‘spawn*()’ 函数将在创建新进程后立即返回，且返回值
     为进程号。

     *note 可用性: 1491.: Unix, Windows。

 -- Data: os.P_WAIT

     *note spawn*: 20a3. 系列函数的 `mode' 参数的可取值。如果将 `mode' 指
     定为该值，则 ‘spawn*()’ 函数将在新进程运行完毕后返回，运行成功则返
     回进程的退出代码，被信号终止则返回 ‘-signal’。

     *note 可用性: 1491.: Unix, Windows。

 -- Data: os.P_DETACH
 -- Data: os.P_OVERLAY

     *note spawn*: 20a3. 系列函数的 `mode' 参数的可取值。它们比上面列出
     的值可移植性差。*note P_DETACH: 2111. 与 *note P_NOWAIT: 210e. 相似
     ，但是新进程会与父进程的控制台脱离。使用 *note P_OVERLAY: 2112. 则
     会替换当前进程，*note spawn*: 20a3. 函数将不会返回。

     *note 可用性: 1491.: Windows。

 -- 函式: os.startfile (path[, operation])

     使用已关联的应用程序打开文件。

     当 `operation' 未指定或指定为 ‘'open'’ 时，这类似于在 Windows 资源
     管理器中双击文件，或在交互式命令行中将文件名作为 ‘start’ 命令的参数
     ：通过扩展名相关联的应用程序（如果有）打开文件。

     当指定另一个 `operation' 时，它必须是一个“命令动词” ("command
     verb")，该词指定对文件执行的操作。Microsoft 文档中的常用动词有
     ‘'print'’ 和 ‘'edit'’ （用于文件），以及 ‘'explore'’ 和 ‘'find'’ （
     用于目录）。

     关联的应用程序启动后 *note startfile(): 2113. 就会立即返回。 本函数
     没有等待应用程序关闭的选项，也没有办法检索应用程序的退出状态。
     `path' 形参是基于当前目录的相对路径。 如果要使用绝对路径，请确保第
     一个字符不是斜杠 (‘'/'’)；如果是斜杠的话则底层的 Win32
     ‘ShellExecute()’ 函数将失效。 请使用 *note os.path.normpath(): d77.
     函数来确保路径已针对 Win32 正确编码。

     为了减少解释器的启动开销，直到第一次调用本函数后，才解析 Win32
     ‘ShellExecute()’ 函数。如果无法解析该函数​​，则抛出 *note
     NotImplementedError: 704. 异常。

     引发一个 *note 审计事件: fa1. ‘os.startfile’，附带参数 ‘path’、
     ‘operation’。

     *note 可用性: 1491.: Windows。

 -- 函式: os.system (command)

     在子外壳程序中执行此命令（一个字符串）。 这是通过调用标准 C 函数
     ‘system()’ 来实现的，并受到同样的限制。 对 *note sys.stdin: 41e. 的
     更改等不会反映在所执行命令的环境中。 如果 `command' 生成了任何输出
     ，它将被发送到解释器的标准输出流。 C 标准没有指明这个 C 函数返回值
     的含义，因此这个 Python 函数的返回值取决于具体系统。

     在 Unix 上，返回值为进程的退出状态，以针对 *note wait(): 75e. 而指
     定的格式进行编码。

     在 Windows 上，返回值是运行 `command' 后系统 Shell 返回的值。该
     Shell 由 Windows 环境变量 ‘COMSPEC’: 给出：通常是 ‘cmd.exe’，它会返
     回命令的退出状态。在使用非原生 Shell 的系统上，请查阅 Shell 的文档
     。

     *note subprocess: f9. 模块提供了更强大的工具来生成新进程并跟踪执行
     结果，使用该模块比使用本函数更好。参阅 *note subprocess: f9. 文档中
     的 *note 使用 subprocess 模块替换旧函数: bc1. 部分以获取有用的帮助
     。

     在 Unix 上，*note waitstatus_to_exitcode(): 1ce. 可以将返回值（即退
     出状态）转换为退出码。在 Windows 上，返回值就是退出码。

     引发一个 *note 审计事件: fa1. ‘os.system’，附带参数 ‘command’。

     *note 可用性: 1491.: Unix, Windows。

 -- 函式: os.times ()

     返回当前的全局进程时间。返回值是一个有 5 个属性的对象：

        * ‘user’ - user time

        * ‘system’ - system time

        * ‘children_user’ - user time of all child processes

        * ‘children_system’ - system time of all child processes

        * ‘elapsed’ - elapsed real time since a fixed point in the past

     For backwards compatibility, this object also behaves like a
     five-tuple containing ‘user’, ‘system’, ‘children_user’,
     ‘children_system’, and ‘elapsed’ in that order.

     See the Unix manual page ‘times(2)’ and ‘times(3)’ manual page on
     Unix or the GetProcessTimes MSDN(2) on Windows.  On Windows, only
     ‘user’ and ‘system’ are known; the other attributes are zero.

     *note 可用性: 1491.: Unix, Windows。

     3.3 版更變: 返回结果的类型由元组变成一个类似元组的对象，同时具有命
     名的属性。

 -- 函式: os.wait ()

     等待子进程执行完毕，返回一个元组，包含其 pid 和退出状态指示：一个
     16 位数字，其低字节是终止该进程的信号编号，高字节是退出状态码（信号
     编号为零的情况下），如果生成了核心文件，则低字节的高位会置位。

     可以使用 *note waitstatus_to_exitcode(): 1ce. 来将退出状态转换为退
     出码。

     *note 可用性: 1491.: Unix。

     也參考
     ......

     *note waitpid(): 760. 可以等待特定的子进程执行完毕，且支持更多选项
     。

 -- 函式: os.waitid (idtype, id, options)

     等待一个或多个子进程执行完毕。`idtype' 可以是 *note P_PID: 2114,
     *note P_PGID: 2115, *note P_ALL: 2116, 或 *note P_PIDFD: 1cb. （
     Linux 可用）。`id' 指定要等待的 pid。`options' 是由 *note WEXITED:
     2117.、*note WSTOPPED: 2118. 或 *note WCONTINUED: 2119. 中的一个或
     多个进行或运算构造的，且额外可以与 *note WNOHANG: 211a. 或 *note
     WNOWAIT: 211b. 进行或运算。返回值是一个对象，对应着 ‘siginfo_t’ 结
     构体中的数据，即： ‘si_pid’, ‘si_uid’, ‘si_signo’, ‘si_status’,
     ‘si_code’ 或 ‘None’ （如果指定了 *note WNOHANG: 211a. 且没有子进程
     处于等待状态）。

     *note 可用性: 1491.: Unix。

     3.3 版新加入.

 -- Data: os.P_PID
 -- Data: os.P_PGID
 -- Data: os.P_ALL

     *note waitid(): 75f. 的 `idtype' 参数的可取值。它们影响 `id' 的解释
     方式。

     *note 可用性: 1491.: Unix。

     3.3 版新加入.

 -- Data: os.P_PIDFD

     这是仅 Linux 上存在的一种 `idtype'，它表示 `id' 是指向一个进程的文
     件描述符。

     *note 可用性: 1491.: Linux 5.4+

     3.9 版新加入.

 -- Data: os.WEXITED
 -- Data: os.WSTOPPED
 -- Data: os.WNOWAIT

     用于 *note waitid(): 75f. 的 `options' 参数的标志位，指定要等待的子
     进程信号。

     *note 可用性: 1491.: Unix。

     3.3 版新加入.

 -- Data: os.CLD_EXITED
 -- Data: os.CLD_KILLED
 -- Data: os.CLD_DUMPED
 -- Data: os.CLD_TRAPPED
 -- Data: os.CLD_STOPPED
 -- Data: os.CLD_CONTINUED

     *note waitid(): 75f. 返回的结果中，‘si_code’ 的可取值。

     *note 可用性: 1491.: Unix。

     3.3 版新加入.

     3.9 版更變: 添加了 *note CLD_KILLED: 1c9. 和 *note CLD_STOPPED:
     1ca. 值。

 -- 函式: os.waitpid (pid, options)

     本函数的细节在 Unix 和 Windows 上有不同之处。

     在 Unix 上：等待进程号为 `pid' 的子进程执行完毕，返回一个元组，内含
     其进程 ID 和退出状态指示（编码与 *note wait(): 75e. 相同）。调用的
     语义受整数 `options' 的影响，常规操作下该值应为 ‘0’。

     如果 `pid' 大于 ‘0’，则 *note waitpid(): 760. 会获取该指定进程的状
     态信息。如果 `pid' 为 ‘0’，则获取当前进程所在进程组中的所有子进程的
     状态。如果 `pid' 为 ‘-1’，则获取当前进程的子进程状态。如果 `pid' 小
     于 ‘-1’，则获取进程组 ‘-pid’ （ `pid' 的绝对值）中所有进程的状态。

     当系统调用返回 -1 时，将抛出带有错误码的 *note OSError: 304. 异常。

     在 Windows 上：等待句柄为 `pid' 的进程执行完毕，返回一个元组，内含
     `pid' 以及左移 8 位后的退出状态码（移位简化了跨平台使用本函数）。小
     于或等于 ‘0’ 的 `pid' 在 Windows 上没有特殊含义，且会抛出异常。整数
     值 `options' 无效。`pid' 可以指向任何 ID 已知的进程，不一定是子进程
     。调用 *note spawn*: 20a3. 函数时传入 *note P_NOWAIT: 210e. 将返回
     合适的进程句柄。

     可以使用 *note waitstatus_to_exitcode(): 1ce. 来将退出状态转换为退
     出码。

     3.5 版更變: 如果系统调用被中断，但信号处理程序没有触发异常，此函数
     现在会重试系统调用，而不是触发 *note InterruptedError: 74c. 异常 (原
     因详见 PEP 475(3))。

 -- 函式: os.wait3 (options)

     与 *note waitpid(): 760. 相似，差别在于没有进程 ID 参数，且返回一个
     3 元组，其中包括子进程 ID，退出状态指示和资源使用信息。关于资源使用
     信息的详情，请参考 *note resource: e0.*note getrusage(): e5e.。
     option 参数与传入 *note waitpid(): 760. 和 *note wait4(): 75d. 的相
     同。

     可以使用 *note waitstatus_to_exitcode(): 1ce. 来将退出状态转换为退
     出码。

     *note 可用性: 1491.: Unix。

 -- 函式: os.wait4 (pid, options)

     与 *note waitpid(): 760. 相似，差别在本方法返回一个 3 元组，其中包
     括子进程 ID，退出状态指示和资源使用信息。关于资源使用信息的详情，请
     参考 *note resource: e0.*note getrusage(): e5e.。*note wait4():
     75d. 的参数与 *note waitpid(): 760. 的参数相同。

     可以使用 *note waitstatus_to_exitcode(): 1ce. 来将退出状态转换为退
     出码。

     *note 可用性: 1491.: Unix。

 -- 函式: os.waitstatus_to_exitcode (status)

     将等待状态转换为退出码。

     在 Unix 上：

        * 如果进程正常退出（当 ‘WIFEXITED(status)’ 为真值），则返回进程
          退出状态 (返回 ‘WEXITSTATUS(status)’): 结果值大于等于 0。

        * 如果进程被信号终止（当 ‘WIFSIGNALED(status)’ 为真值），则返回
          ‘-signum’ 其中 `signum' 为导致进程终止的信号数值 (返回
          ‘-WTERMSIG(status)’): 结果值小于 0。

        * 否则将抛出 *note ValueError: 16d. 异常。

     在 Windows 上，返回 `status' 右移 8 位的结果。

     在 Unix 上，如果进程正被追踪或 *note waitpid(): 760. 附带 *note
     WUNTRACED: 2120. 选项被调用，则调用者必须先检查
     ‘WIFSTOPPED(status)’ 是否为真值。 如果 ‘WIFSTOPPED(status)’ 为真值
     则此函数不可被调用。

     也參考
     ......

     *note WIFEXITED(): 2121, *note WEXITSTATUS(): 2122, *note
     WIFSIGNALED(): 2123, *note WTERMSIG(): 2124, *note WIFSTOPPED():
     2125, *note WSTOPSIG(): 2126. 函数。

     3.9 版新加入.

 -- Data: os.WNOHANG

     用于 *note waitpid(): 760. 的选项，如果没有立即可用的子进程状态，则
     立即返回。在这种情况下，函数返回 ‘(0, 0)’。

     *note 可用性: 1491.: Unix。

 -- Data: os.WCONTINUED

     被任务控制 (job control) 停止的子进程，如果上次报告状态后已恢复运行
     ，则此选项将报告这些子进程。

     *note 可用性: 1491.: 部分 Unix 系统。

 -- Data: os.WUNTRACED

     已停止的子进程，如果自停止以来尚未报告其当前状态，则此选项将报告这
     些子进程。

     *note 可用性: 1491.: Unix。

下列函数采用进程状态码作为参数，状态码由 *note system(): e86.、*note
wait(): 75e. 或 *note waitpid(): 760. 返回。它们可用于确定进程上发生的操
作。

 -- 函式: os.WCOREDUMP (status)

     如果为该进程生成了核心转储，返回 ‘True’，否则返回 ‘False’。

     此函数应当仅在 *note WIFSIGNALED(): 2123. 为真值时使用。

     *note 可用性: 1491.: Unix。

 -- 函式: os.WIFCONTINUED (status)

     如果一个已停止的子进程通过传送 *note SIGCONT: 2129. 获得恢复（如果
     该进程是从任务控制停止后再继续的）则返回 ‘True’，否则返回 ‘False’。

     参见 *note WCONTINUED: 2119. 选项。

     *note 可用性: 1491.: Unix。

 -- 函式: os.WIFSTOPPED (status)

     如果进程是通过传送一个信号来停止的则返回 ‘True’，否则返回 ‘False’。

     *note WIFSTOPPED(): 2125. 只有在当 *note waitpid(): 760. 调用是通过
     使用 *note WUNTRACED: 2120. 选项来完成或者当该进程正被追踪时 (参见
     ‘ptrace(2)’) 才返回 ‘True’。

     *note 可用性: 1491.: Unix。

 -- 函式: os.WIFSIGNALED (status)

     如果进程是通过一个信号来终止的则返回 ‘True’ ，否则返回 ‘False’。

     *note 可用性: 1491.: Unix。

 -- 函式: os.WIFEXITED (status)

     如果进程正常终止退出则返回 ‘True’，也就是说通过调用 ‘exit()’ 或
     ‘_exit()’，或者通过从 ‘main()’ 返回；在其他情况下则返回 ‘False’。

     *note 可用性: 1491.: Unix。

 -- 函式: os.WEXITSTATUS (status)

     返回进程退出状态。

     此函数应当仅在 *note WIFEXITED(): 2121. 为真值时使用。

     *note 可用性: 1491.: Unix。

 -- 函式: os.WSTOPSIG (status)

     返回导致进程停止的信号。

     此函数应当仅在 *note WIFSTOPPED(): 2125. 为真值时使用。

     *note 可用性: 1491.: Unix。

 -- 函式: os.WTERMSIG (status)

     返回导致进程终止的信号的编号。

     此函数应当仅在 *note WIFSIGNALED(): 2123. 为真值时使用。

     *note 可用性: 1491.: Unix。

   ---------- Footnotes ----------

   (1) https://msdn.microsoft.com/44228cf2-6306-466c-8f16-f513cd3ba8b5

   (2) 
https://docs.microsoft.com/windows/win32/api/processthreadsapi/nf-processthreadsapi-getprocesstimes

   (3) https://www.python.org/dev/peps/pep-0475


File: python.info,  Node: 调度器接口,  Next: 其他系统信息,  Prev: 进程管理,  Up: os --- 多种操作系统接口

5.16.1.10 调度器接口
....................

这些函数控制操作系统如何为进程分配 CPU 时间。 它们仅在某些 Unix 平台上可
用。 更多细节信息请查阅你所用 Unix 的指南页面。

3.3 版新加入.

以下调度策略如果被操作系统支持就会对外公开。

 -- Data: os.SCHED_OTHER

     默认调度策略。

 -- Data: os.SCHED_BATCH

     用于 CPU 密集型进程的调度策略，它会尽量为计算机中的其余任务保留交互
     性。

 -- Data: os.SCHED_IDLE

     用于极低优先级的后台任务的调度策略。

 -- Data: os.SCHED_SPORADIC

     用于偶发型服务程序的调度策略。

 -- Data: os.SCHED_FIFO

     先进先出的调度策略。

 -- Data: os.SCHED_RR

     循环式的调度策略。

 -- Data: os.SCHED_RESET_ON_FORK

     此旗标可与任何其他调度策略进行 OR 运算。 当带有此旗标的进程设置分叉
     时，其子进程的调度策略和优先级会被重置为默认值。

 -- 類別: os.sched_param (sched_priority)

     这个类表示在 *note sched_setparam(): b31, *note
     sched_setscheduler(): b32. 和 *note sched_getparam(): b2d. 中使用的
     可修改调度形参。 它属于不可变对象。

     目前它只有一个可能的形参：

      -- 屬性: sched_priority

          一个调度策略的调度优先级。

 -- 函式: os.sched_get_priority_min (policy)

     获取 `policy' 的最小优先级数值。 `policy' 是以上调度策略常量之一。

 -- 函式: os.sched_get_priority_max (policy)

     获取 `policy' 的最高优先级数值。 `policy' 是以上调度策略常量之一。

 -- 函式: os.sched_setscheduler (pid, policy, param)

     设置 PID 为 `pid' 的进程的调度策略。`pid' 为 0 指的是调用本方法的进
     程。`policy' 是以上调度策略常量之一。`param' 是一个 *note
     sched_param: 2106. 实例。

 -- 函式: os.sched_getscheduler (pid)

     返回 PID 为 `pid' 的进程的调度策略。`pid' 为 0 指的是调用本方法的进
     程。返回的结果是以上调度策略常量之一。

 -- 函式: os.sched_setparam (pid, param)

     设置 PID 为 `pid' 的进程的调度参数。 `pid' 为 0 表示调用方过程。
     `param' 是一个 *note sched_param: 2106. 实例。

 -- 函式: os.sched_getparam (pid)

     返回 PID 为 `pid' 的进程的调度参数为一个 *note sched_param: 2106. 实
     例。`pid' 为 0 指的是调用本方法的进程。

 -- 函式: os.sched_rr_get_interval (pid)

     返回 PID 为 `pid' 的进程在时间片轮转调度下的时间片长度（单位为秒）
     。`pid' 为 0 指的是调用本方法的进程。

 -- 函式: os.sched_yield ()

     自愿放弃 CPU。

 -- 函式: os.sched_setaffinity (pid, mask)

     将 PID 为 `pid' 的进程（为零则为当前进程）限制到一组 CPU 上。`mask'
     是整数的可迭代对象，表示应将进程限制在其中的一组 CPU。

 -- 函式: os.sched_getaffinity (pid)

     返回 PID 为 `pid' 的进程（为零则为当前进程）被限制到的那一组 CPU。


File: python.info,  Node: 其他系统信息,  Next: 随机数,  Prev: 调度器接口,  Up: os --- 多种操作系统接口

5.16.1.11 其他系统信息
......................

 -- 函式: os.confstr (name)

     返回字符串格式的系统配置信息。`name' 指定要查找的配置名称，它可以是
     字符串，是一个系统已定义的名称，这些名称定义在不同标准（POSIX，Unix
     95，Unix 98 等）中。一些平台还定义了额外的其他名称。当前操作系统已
     定义的名称在 ‘confstr_names’ 字典的键中给出。对于未包含在该映射中的
     配置名称，也可以传递一个整数作为 `name'。

     如果 `name' 指定的配置值未定义，返回 ‘None’。

     如果 `name' 是一个字符串且不是已定义的名称，将抛出 *note
     ValueError: 16d. 异常。如果当前系统不支持 `name' 指定的配置名称，即
     使该名称存在于 ‘confstr_names’，也会抛出 *note OSError: 304. 异常，
     错误码为 *note errno.EINVAL: 1104.。

     *note 可用性: 1491.: Unix。

 -- Data: os.confstr_names

     字典，表示映射关系，为 *note confstr(): 2135. 可接受名称与操作系统
     为这些名称定义的整数值之间的映射。这可用于判断系统已定义了哪些名称
     。

     *note 可用性: 1491.: Unix。

 -- 函式: os.cpu_count ()

     返回系统的 CPU 数量。不确定则返回 ‘None’。

     该数量不同于当前进程可以使用的CPU数量。可用的CPU数量可以由
     ‘len(os.sched_getaffinity(0))’ 方法获得。

     3.4 版新加入.

 -- 函式: os.getloadavg ()

     返回系统运行队列中最近 1、5 和 15 分钟内的平均进程数。无法获得平均
     负载则抛出 *note OSError: 304. 异常。

     *note 可用性: 1491.: Unix。

 -- 函式: os.sysconf (name)

     返回整数格式的系统配置信息。如果 `name' 指定的配置值未定义，返回
     ‘-1’。对 *note confstr(): 2135. 的 `name' 参数的注释在此处也适用。
     当前已知的配置名称在 ‘sysconf_names’ 字典中提供。

     *note 可用性: 1491.: Unix。

 -- Data: os.sysconf_names

     字典，表示映射关系，为 *note sysconf(): 2094. 可接受名称与操作系统
     为这些名称定义的整数值之间的映射。这可用于判断系统已定义了哪些名称
     。

     *note 可用性: 1491.: Unix。

以下数据值用于支持对路径本身的操作。所有平台都有定义。

对路径的高级操作在 *note os.path: c5. 模块中定义。

 -- Data: os.curdir

     操作系统用来表示当前目录的常量字符串。在 Windows 和 POSIX 上是
     ‘'.'’。在 *note os.path: c5. 中也可用。

 -- Data: os.pardir

     操作系统用来表示父目录的常量字符串。在 Windows 和 POSIX 上是
     ‘'..'’。在 *note os.path: c5. 中也可用。

 -- Data: os.sep

     操作系统用来分隔路径不同部分的字符。在 POSIX 上是 ‘'/'’，在 Windows
     上是是 ‘'\\'’。注意，仅了解它不足以能解析或连接路径，请使用 *note
     os.path.split(): 1d49. 和 *note os.path.join(): 10c7.，但它有时是有
     用的。在 *note os.path: c5. 中也可用。

 -- Data: os.altsep

     操作系统用来分隔路径不同部分的替代字符。如果仅存在一个分隔符，则为
     ‘None’。在 ‘sep’ 是反斜杠的 Windows 系统上，该值被设为 ‘'/'’。在
     *note os.path: c5. 中也可用。

 -- Data: os.extsep

     分隔基本文件名与扩展名的字符，如 ‘os.py’ 中的 ‘'.'’。在 *note
     os.path: c5. 中也可用。

 -- Data: os.pathsep

     操作系统通常用于分隔搜索路径（如 ‘PATH’）中不同部分的字符，如 POSIX
     上是 ‘':'’，Windows 上是 ‘';'’。在 *note os.path: c5. 中也可用。

 -- Data: os.defpath

     在环境变量没有 ‘'PATH'’ 键的情况下，*note exec*p*: 20e7. and *note
     spawn*p*: 20a3. 使用的默认搜索路径。在 *note os.path: c5. 中也可用
     。

 -- Data: os.linesep

     当前平台用于分隔（或终止）行的字符串。它可以是单个字符，如 POSIX 上
     是 ‘'\n'’，也可以是多个字符，如 Windows 上是 ‘'\r\n'’。在写入以文本
     模式（默认模式）打开的文件时，请不要使用 `os.linesep' 作为行终止符
     ，请在所有平台上都使用一个 ‘'\n'’ 代替。

 -- Data: os.devnull

     空设备的文件路径。如 POSIX 上为 ‘'/dev/null'’，Windows 上为
     ‘'nul'’。在 *note os.path: c5. 中也可用。

 -- Data: os.RTLD_LAZY
 -- Data: os.RTLD_NOW
 -- Data: os.RTLD_GLOBAL
 -- Data: os.RTLD_LOCAL
 -- Data: os.RTLD_NODELETE
 -- Data: os.RTLD_NOLOAD
 -- Data: os.RTLD_DEEPBIND

     *note setdlopenflags(): b41. 和 *note getdlopenflags(): f10. 函数所
     使用的标志。请参阅 Unix 手册页 ‘dlopen(3)’ 获取不同标志的含义。

     3.3 版新加入.


File: python.info,  Node: 随机数,  Prev: 其他系统信息,  Up: os --- 多种操作系统接口

5.16.1.12 随机数
................

 -- 函式: os.getrandom (size, flags=0)

     获得最多为 `size' 的随机字节。本函数返回的字节数可能少于请求的字节
     数。

     这些字节可用于为用户空间的随机数生成器提供种子，或用于加密目的。

     ‘getrandom()’ 依赖于从设备驱动程序和其他环境噪声源收集的熵。不必要
     地读取大量数据将对使用 ‘/dev/random’ 和 ‘/dev/urandom’ 设备的其他用
     户产生负面影响。

     flags 参数是一个位掩码，可以是零个或多个下列值以或运算组合： *note
     os.GRND_RANDOM: 213b. 和 *note GRND_NONBLOCK: 213c.。

     另请参阅 Linux getrandom() 手册页(1) 。

     *note 可用性: 1491.：Linux 3.17 或更高版本。

     3.6 版新加入.

 -- 函式: os.urandom (size)

     返回大小为 `size' 的字符串，它是适合加密使用的随机字节。

     本函数从系统指定的随机源获取随机字节。对于加密应用程序，返回的数据
     应有足够的不可预测性，尽管其确切的品质取决于操作系统的实现。

     在 Linux 上，如果 ‘getrandom()’ 系统调用可用，它将以阻塞模式使用：
     阻塞直到系统的 urandom 熵池初始化完毕（内核收集了 128 位熵）。原理
     请参阅 PEP 524(2)。在 Linux 上，*note getrandom(): 662. 可以以非阻
     塞模式（使用 *note GRND_NONBLOCK: 213c. 标志）获取随机字节，或者轮
     询直到系统的 urandom 熵池初始化完毕。

     在类 Unix 系统上，随机字节是从 ‘/dev/urandom’ 设备读取的。如果
     ‘/dev/urandom’ 设备不可用或不可读，则抛出 *note
     NotImplementedError: 704. 异常。

     在 Windows 上将使用 ‘CryptGenRandom()’。

     也參考
     ......

     *note secrets: e4. 模块提供了更高级的功能。所在平台会提供随机数生成
     器，有关其易于使用的接口，请参阅 *note random.SystemRandom: 1c5f.。

     3.6.0 版更變: 在 Linux 上，‘getrandom()’ 现在以阻塞模式使用，以提高
     安全性。

     3.5.2 版更變: 在 Linux 上，如果 ‘getrandom()’ 系统调用阻塞（urandom
     熵池尚未初始化完毕），则退回一步读取 ‘/dev/urandom’。

     3.5 版更變: 在 Linux 3.17 和更高版本上，现在使用 ‘getrandom()’ 系统
     调用（如果可用）。在 OpenBSD 5.6 和更高版本上，现在使用
     ‘getentropy()’ C 函数。这些函数避免了使用内部文件描述符。

 -- Data: os.GRND_NONBLOCK

     默认情况下，从 ‘/dev/random’ 读取时，如果没有可用的随机字节，则
     *note getrandom(): 662. 会阻塞；从 ‘/dev/urandom’ 读取时，如果熵池
     尚未初始化，则会阻塞。

     如果设置了 *note GRND_NONBLOCK: 213c. 标志，则这些情况下 *note
     getrandom(): 662. 不会阻塞，而是立即抛出 *note BlockingIOError:
     a78. 异常。

     3.6 版新加入.

 -- Data: os.GRND_RANDOM

     如果设置了此标志位，那么将从 ‘/dev/random’ 池而不是 ‘/dev/urandom’
     池中提取随机字节。

     3.6 版新加入.

   ---------- Footnotes ----------

   (1) http://man7.org/linux/man-pages/man2/getrandom.2.html

   (2) https://www.python.org/dev/peps/pep-0524


File: python.info,  Node: io --- 处理流的核心工具,  Next: time --- 时间的访问和转换,  Prev: os --- 多种操作系统接口,  Up: 通用操作系统服务

5.16.2 ‘io’ — 处理流的核心工具
------------------------------

`源代码:' Lib/io.py(1)

__________________________________________________________________

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/io.py


File: python.info,  Node: 總覽,  Next: 高阶模块接口,  Up: io --- 处理流的核心工具

5.16.2.1 總覽
.............

*note io: a1. 模块提供了 Python 用于处理各种 I/O 类型的主要工具。三种主
要的 I/O类型分别为: `文本 I/O', `二进制 I/O' 和 `原始 I/O'。这些是泛型类
型，有很多种后端存储可以用在他们上面。一个隶属于任何这些类型的具体对象被
称作 *note file object: c14.。 其他同类的术语还有 `流' 和 `类文件对象'。

独立于其类别，每个具体流对象也将具有各种功能：它可以是只读，只写或读写。
它还可以允许任意随机访问（向前或向后寻找任何位置），或仅允许顺序访问（例
如在套接字或管道的情况下）。

所有流对提供给它们的数据类型都很敏感。例如将 *note str: 205. 对象给二进
制流的 ‘write()’ 方法会引发 *note TypeError: 1fe.。将 *note bytes: 172.
对象提供给文本流的 ‘write()’ 方法也是如此。

3.3 版更變: 由于 *note IOError: a73. 现在是 *note OSError: 304. 的别名，
因此用于引发 *note IOError: a73. 的操作现在会引发 *note OSError: 304. 。

* Menu:

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


File: python.info,  Node: 文本 I/O,  Next: 二进制 I/O,  Up: 總覽

5.16.2.2 文本 I/O
.................

文本I/O预期并生成 *note str: 205. 对象。这意味着，无论何时后台存储是由字
节组成的（例如在文件的情况下），数据的编码和解码都是透明的，并且可以选择
转换特定于平台的换行符。

创建文本流的最简单方法是使用 *note open(): 16f.，可以选择指定编码：

     f = open("myfile.txt", "r", encoding="utf-8")

内存中文本流也可以作为 *note StringIO: 91a. 对象使用：

     f = io.StringIO("some initial text data")

*note TextIOBase: d01. 的文档中详细描述了文本流的API


File: python.info,  Node: 二进制 I/O,  Next: 原始 I/O,  Prev: 文本 I/O,  Up: 總覽

5.16.2.3 二进制 I/O
...................

二进制I/O（也称为缓冲I/O）预期 *note bytes-like objects: 6df. 并生成
*note bytes: 172. 对象。不执行编码、解码或换行转换。这种类型的流可以用于
所有类型的非文本数据，并且还可以在需要手动控制文本数据的处理时使用。

创建二进制流的最简单方法是使用 *note open(): 16f.，并在模式字符串中指定
‘'b'’ ：

     f = open("myfile.jpg", "rb")

内存中二进制流也可以作为 *note BytesIO: 88a. 对象使用：

     f = io.BytesIO(b"some initial binary data: \x00\x01")

*note BufferedIOBase: 67f. 的文档中详细描述了二进制流的API

其他库模块可以提供额外的方式来创建文本或二进制流。参见 *note
socket.socket.makefile(): bec. 的示例。


File: python.info,  Node: 原始 I/O,  Prev: 二进制 I/O,  Up: 總覽

5.16.2.4 原始 I/O
.................

原始 I/O（也称为 `非缓冲 I/O'）通常用作二进制和文本流的低级构建块。用户
代码直接操作原始流的用法非常罕见。不过，可以通过在禁用缓冲的情况下以二进
制模式打开文件来创建原始流：

     f = open("myfile.jpg", "rb", buffering=0)

*note RawIOBase: af1. 的文档中详细描述了原始流的API


File: python.info,  Node: 高阶模块接口,  Next: 类的层次结构,  Prev: 總覽,  Up: io --- 处理流的核心工具

5.16.2.5 高阶模块接口
.....................

 -- Data: io.DEFAULT_BUFFER_SIZE

     包含模块缓冲I/O类使用的默认缓冲区大小的整数。（如果可能） *note
     open(): 16f. 将使用文件的blksize（由 *note os.stat(): 321. 获得）。

 -- 函式: io.open (file, mode='r', buffering=-1, encoding=None,
          errors=None, newline=None, closefd=True, opener=None)

     这是内置的 *note open(): 16f. 函数的别名。

     ‘open’ 附带参数 ‘path’、‘mode’、‘flags’ 会引发 *note 审计事件:
     fa1.。

 -- 函式: io.open_code (path)

     以 ‘'rb'’ 模式打开提供的文件。如果目的是将文件内容做为可执行代码，
     则应使用此函数。

     ‘path’ 应当为 *note str: 205. 类型并且是一个绝对路径。

     此函数的行为可以由对 *note PyFile_SetOpenCodeHook(): 2144. 的先期调
     用所重载。 但是，如果 ‘path’ 为 *note str: 205. 类型并且是一个绝对
     路径，‘open_code(path)’ 的行为应当总是与 ‘open(path, 'rb')’ 一致。
     重载此行为的目的是为了给文件附加额外的验证或预处理。

     3.8 版新加入.

 -- 例外: io.BlockingIOError

     这是内置的 *note BlockingIOError: a78. 异常的兼容性别名。

 -- 例外: io.UnsupportedOperation

     在流上调用不支持的操作时引发的继承 *note OSError: 304. 和 *note
     ValueError: 16d. 的异常。

也參考
......

*note sys: fd.

     包含标准IO流: *note sys.stdin: 41e, *note sys.stdout: 41f. 和 *note
     sys.stderr: 1ea. 。


File: python.info,  Node: 类的层次结构,  Next: 性能<3>,  Prev: 高阶模块接口,  Up: io --- 处理流的核心工具

5.16.2.6 类的层次结构
.....................

I/O 流被安排为按类的层次结构实现。 首先是 *note 抽象基类: c05. (ABC)，用
于指定流的各种类别，然后是提供标准流实现的具体类。

          備註: 抽象基类还提供某些方法的默认实现，以帮助实现具体的流类。
          例如 *note BufferedIOBase: 67f. 提供了 ‘readinto()’ 和 *note
          readline(): 1849. 的未优化实现。

I/O层次结构的顶部是抽象基类 *note IOBase: 30c. 。它定义了流的基本接口。
但是请注意，对流的读取和写入之间没有分离。如果实现不支持指定的操作，则会
引发 *note UnsupportedOperation: 1083. 。

抽象基类 *note RawIOBase: af1. 是 *note IOBase: 30c. 的子类。它负责将字
节读取和写入流中。 *note RawIOBase: af1. 的子类 *note FileIO: d6c. 提供
计算机文件系统中文件的接口。

抽象基类 *note BufferedIOBase: 67f. 继承了 *note IOBase: 30c. ，处理原始
二进制流（ *note RawIOBase: af1. ）上的缓冲。其子类 *note
BufferedWriter: 1733. 、 *note BufferedReader: c5b. 和 *note
BufferedRWPair: 2147. 分别缓冲可读、可写以及可读写的原始二进制流。 *note
BufferedRandom: 1734. 提供了带缓冲的可随机访问流接口。 *note
BufferedIOBase: 67f. 的另一个子类 *note BytesIO: 88a. 是内存中字节流。

抽象基类 *note TextIOBase: d01. 继承了 *note IOBase: 30c. 。它处理可表示
文本的流，并处理字符串的编码和解码。类 *note TextIOWrapper: 6ea. 继承了
*note TextIOBase: d01. ，是原始缓冲流（ *note BufferedIOBase: 67f. ）的
缓冲文本接口。最后， *note StringIO: 91a. 是文本的内存流。

参数名不是规范的一部分，只有 *note open(): 16f. 的参数才用作关键字参数。

下表总结了抽象基类提供的 *note io: a1. 模块：

抽象基类                      继承                   抽象方法                     Mixin方法和属性
                                                                                  
-----------------------------------------------------------------------------------------------------------------------------------------
                                                                                  
*note IOBase: 30c.                                   ‘fileno’, ‘seek’, 和         ‘close’, ‘closed’, ‘__enter__’, ‘__exit__’, ‘flush’,
                                                     ‘truncate’                   ‘isatty’, ‘__iter__’, ‘__next__’, ‘readable’,
                                                                                  ‘readline’, ‘readlines’, ‘seekable’, ‘tell’,
                                                                                  ‘writable’ 和 ‘writelines’
                                                                                  
                                                                                  
*note RawIOBase: af1.         *note IOBase: 30c.     ‘readinto’ 和 ‘write’        继承 *note IOBase: 30c. 方法, ‘read’, 和 ‘readall’
                                                                                  
                                                                                  
*note BufferedIOBase: 67f.    *note IOBase: 30c.     ‘detach’, ‘read’, ‘read1’,   继承 *note IOBase: 30c. 方法, ‘readinto’, 和
                                                     和 ‘write’                   ‘readinto1’
                                                                                  
                                                                                  
*note TextIOBase: d01.        *note IOBase: 30c.     ‘detach’, ‘read’,            继承 *note IOBase: 30c. 方法, ‘encoding’, ‘errors’,
                                                     ‘readline’, 和 ‘write’       和 ‘newlines’
                                                                                  

* Menu:

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


File: python.info,  Node: I/O 基类,  Next: 原始文件 I/O,  Up: 类的层次结构

5.16.2.7 I/O 基类
.................

 -- 類別: io.IOBase

     所有 I/O 类的抽象基类，作用于字节流。没有公共构造函数。

     此类为许多方法提供了空的抽象实现，派生类可以有选择地重写。默认实现
     代表一个无法读取、写入或查找的文件。

     尽管 *note IOBase: 30c. 没有声明 ‘read()’ 或 ‘write()’ ，因为它们的
     签名会有所不同，但是实现和客户端应该将这些方法视为接口的一部分。此
     外，当调用不支持的操作时可能会引发 *note ValueError: 16d. （或
     *note UnsupportedOperation: 1083. ）。

     从文件读取或写入文件的二进制数据的基本类型为 *note bytes: 172. 。其
     他 *note bytes-like objects: 6df. 也可以作为方法参数。文本I/O类使用
     *note str: 205. 数据。

     请注意，在关闭的流上调用任何方法（甚至查询）都是未定义的（
     undefined）。在这种情况下，实现可能会引发 *note ValueError: 16d. 。

     *note IOBase: 30c. （及其子类）支持迭代器协议，这意味着可以迭代
     *note IOBase: 30c. 对象以产生流中的行。根据流是二进制流（产生字节）
     还是文本流（产生字符串），行的定义略有不同。请参见下面的 *note
     readline(): 1849. 。

     *note IOBase: 30c. 也是一个上下文管理器，因此支持 *note with: 7da.
     语句。 在这个示例中，`file' 将在 ‘with’ 语句块执行完成之后被关闭 —
     即使是发生了异常:

          with open('spam.txt', 'w') as file:
              file.write('Spam and eggs!')

     *note IOBase: 30c. 提供以下数据属性和方法：

      -- 成員函式: close ()

          刷新并关闭此流。如果文件已经关闭，则此方法无效。文件关闭后，对
          文件的任何操作（例如读取或写入）都会引发 *note ValueError:
          16d. 。

          为方便起见，允许多次调用此方法。但是，只有第一个调用才会生效。

      -- 屬性: closed

          如果流已关闭，则返回 True。

      -- 成員函式: fileno ()

          返回流的底层文件描述符（整数）—如果存在。如果 IO 对象不使用文
          件描述符，则会引发 *note OSError: 304. 。

      -- 成員函式: flush ()

          刷新流的写入缓冲区（如果适用）。这对只读和非阻塞流不起作用。

      -- 成員函式: isatty ()

          如果流是交互式的（即连接到终端/tty设备），则返回 ‘True’ 。

      -- 成員函式: readable ()

          如果可以读取流，则返回 ‘True’ 。否则为 ‘False’ ，且 ‘read()’ 将
          引发 *note OSError: 304. 错误。

      -- 成員函式: readline (size=-1)

          从流中读取并返回一行。如果指定了 `size'，将至多读取 `size' 个
          字节。

          对于二进制文件行结束符总是 ‘b'\n'’；对于文本文件，可以用将
          `newline' 参数传给 *note open(): 16f. 的方式来选择要识别的行结
          束符。

      -- 成員函式: readlines (hint=-1)

          从流中读取并返回包含多行的列表。可以指定 `hint' 来控制要读取的
          行数：如果（以字节/字符数表示的）所有行的总大小超出了 `hint' 则
          将不会读取更多的行。

          ‘0’ 或更小的 `hint' 值以及 ‘None’，会被视为没有 hint。

          请注意使用 ‘for line in file: ...’ 就足够对文件对象进行迭代了
          ，可以不必调用 ‘file.readlines()’。

      -- 成員函式: seek (offset, whence=SEEK_SET)

          将流位置修改到给定的字节 `offset'。 `offset' 将相对于由
          `whence' 指定的位置进行解析。 `whence' 的默认值为 ‘SEEK_SET’。
          `whence' 的可用值有：

             * ‘SEEK_SET’ 或 ‘0’ – 流的开头（默认值）；`offset' 应为零或
               正值

             * ‘SEEK_CUR’ or ‘1’ – 当前流位置；`offset' 可以为负值

             * ‘SEEK_END’ or ‘2’ – 流的末尾；`offset' 通常为负值

          返回新的绝对位置。

          3.1 版新加入: ‘SEEK_*’ 常量.

          3.3 版新加入: 某些操作系统还可支持其他的值，例如
          ‘os.SEEK_HOLE’ 或 ‘os.SEEK_DATA’。特定文件的可用值还会取决于它
          是以文本还是二进制模式打开。

      -- 成員函式: seekable ()

          如果流支持随机访问则返回 ‘True’。 如为 ‘False’，则 *note
          seek(): 1efb, *note tell(): 1efc. 和 *note truncate(): d6d. 将
          引发 *note OSError: 304.。

      -- 成員函式: tell ()

          返回当前流的位置。

      -- 成員函式: truncate (size=None)

          将流的大小调整为给定的 `size' 个字节（如果未指定 `size' 则调整
          至当前位置）。 当前的流位置不变。 这个调整操作可扩展或减小当前
          文件大小。 在扩展的情况下，新文件区域的内容取决于具体平台（在
          大多数系统上，额外的字节会填充为零）。 返回新的文件大小。

          3.5 版更變: 现在Windows在扩展时将文件填充为零。

      -- 成員函式: writable ()

          如果流支持写入则返回 ‘True’。 如为 ‘False’，则 ‘write()’ 和
          *note truncate(): d6d. 将引发 *note OSError: 304.。

      -- 成員函式: writelines (lines)

          将行列表写入到流。 不会添加行分隔符，因此通常所提供的每一行都
          带有末尾行分隔符。

      -- 成員函式: __del__ ()

          为对象销毁进行准备。 *note IOBase: 30c. 提供了此方法的默认实现
          ，该实现会调用实例的 *note close(): 1147. 方法。

 -- 類別: io.RawIOBase

     原始二进制流的基类。 它继承自 *note IOBase: 30c. 类。 没有公共构造
     器。

     原始二进制流通常会提供对下层 OS 设备或 API 的低层级访问，而不是尝试
     将其封装到高层级的基元中（此功能是在更高层级的缓冲二进制流和文本流
     中实现的，将在下文中描述）。

     *note RawIOBase: af1. 在 *note IOBase: 30c. 的现有成员以外还提供了
     下列方法:

      -- 成員函式: read (size=-1)

          从对象中读取 `size' 个字节并将其返回。 作为一个便捷选项，如果
          `size' 未指定或为 -1，则返回所有字节直到 EOF。 在其他情况下，
          仅会执行一次系统调用。 如果操作系统调用返回字节数少于 `size' 则
          此方法也可能返回少于 `size' 个字节。

          如果返回 0 个字节而 `size' 不为零 0，这表明到达文件末尾。 如果
          处于非阻塞模式并且没有更多字节可用，则返回 ‘None’。

          默认实现会转至 *note readall(): 214e. 和 *note readinto():
          7f4.。

      -- 成員函式: readall ()

          从流中读取并返回所有字节直到 EOF，如有必要将对流执行多次调用。

      -- 成員函式: readinto (b)

          将字节数据读入预先分配的可写 *note bytes-like object: 6df.
          `b'，并返回所读取的字节数。 例如，`b' 可以是一个 *note
          bytearray: 173.。 如果对象处理非阻塞模式并且没有更多字节可用，
          则返回 ‘None’。

      -- 成員函式: write (b)

          将给定的 *note bytes-like object: 6df. `b' 写入到下层的原始流
          ，并返回所写入的字节数。 这可以少于 `b' 的总字节数，具体取决于
          下层原始流的设定，特别是如果它处于非阻塞模式的话。 如果原始流
          设为非阻塞并且不能真正向其写入单个字节时则返回 ‘None’。 调用者
          可以在此方法返回后释放或改变 `b'，因此该实现应该仅在方法调用期
          间访问 `b'。

 -- 類別: io.BufferedIOBase

     支持某种缓冲的二进制流的基类。 它继承自 *note IOBase: 30c.。 没有公
     共构造器。

     与 *note RawIOBase: af1. 的主要差别在于 *note read(): 1ebb, *note
     readinto(): 2150. 和 *note write(): 680. 等方法将（分别）尝试按照要
     求读取尽可能多的输入或是耗尽所有给定的输出，其代价是可能会执行一次
     以上的系统调用。

     除此之外，那些方法还可能引发 *note BlockingIOError: a78.，如果下层
     的原始数据流处于非阻塞模式并且无法接受或给出足够数据的话；不同于对
     应的 *note RawIOBase: af1. 方法，它们将永远不会返回 ‘None’。

     并且，*note read(): 1ebb. 方法也没有转向 *note readinto(): 2150. 的
     默认实现。

     典型的 *note BufferedIOBase: 67f. 实现不应当继承自 *note RawIOBase:
     af1. 实现，而要包装一个该实现，正如 *note BufferedWriter: 1733. 和
     *note BufferedReader: c5b. 所做的那样。

     *note BufferedIOBase: 67f. 在 *note IOBase: 30c. 的现有成员以外还提
     供或重载了下列数据属性和方法:

      -- 屬性: raw

          由 *note BufferedIOBase: 67f. 处理的下层原始流 (*note
          RawIOBase: af1. 的实例)。 它不是 *note BufferedIOBase: 67f.
          API 的组成部分并且不存在于某些实现中。

      -- 成員函式: detach ()

          从缓冲区分离出下层原始流并将其返回。

          在原始流被分离之后，缓冲区将处于不可用的状态。

          某些缓冲区例如 *note BytesIO: 88a. 并无可从此方法返回的单独原
          始流的概念。 它们将会引发 *note UnsupportedOperation: 1083.。

          3.1 版新加入.

      -- 成員函式: read (size=-1)

          读取并返回最多 `size' 个字节。 如果此参数被省略、为 ‘None’ 或
          为负值，则读取并返回所有数据直到 EOF。 如果流已经到达 EOF 则返
          回一个空的 *note bytes: 172. 对象。

          如果此参数为正值，并且下层原始流不可交互，则可能发起多个原始读
          取以满足字节计数（直至先遇到 EOF）。 但对于可交互原始流，则将
          至多发起一个原始读取，并且简短的结果并不意味着已到达 EOF。

          *note BlockingIOError: a78. 会在下层原始流不处于阻塞模式，并且
          当前没有可用数据时被引发。

      -- 成員函式: read1 ([size])

          通过至多一次对下层流的 *note read(): 7f3. (或 *note
          readinto(): 7f4.) 方法的调用读取并返回至多 `size' 个字节。 这
          适用于在 *note BufferedIOBase: 67f. 对象之上实现你自己的缓冲区
          的情况。

          如果 `size' 为 ‘-1’ (默认值)，则返回任意数量的字节（多于零字节
          ，除非已到达 EOF）。

      -- 成員函式: readinto (b)

          将字节数据读入预先分配的可写 *note bytes-like object: 6df. `b'
          并返回所读取的字节数。 例如，`b' 可以是一个 *note bytearray:
          173.。

          类似于 *note read(): 1ebb.，可能对下层原始流发起多次读取，除非
          后者为交互式。

          *note BlockingIOError: a78. 会在下层原始流不处于阻塞模式，并且
          当前没有可用数据时被引发。

      -- 成員函式: readinto1 (b)

          将字节数据读入预先分配的可写 *note bytes-like object: 6df.
          `b'，其中至多使用一次对下层原始流 *note read(): 7f3. (或 *note
          readinto(): 7f4.) 方法的调用。 返回所读取的字节数。

          *note BlockingIOError: a78. 会在下层原始流不处于阻塞模式，并且
          当前没有可用数据时被引发。

          3.5 版新加入.

      -- 成員函式: write (b)

          写入给定的 *note bytes-like object: 6df. `b'，并返回写入的字节
          数 (总是等于 `b' 的字节长度，因为如果写入失败则会引发 *note
          OSError: 304.)。 根据具体实现的不同，这些字节可能被实际写入下
          层流，或是出于运行效率和冗余等考虑而暂存于缓冲区。

          当处于非阻塞模式时，如果需要将数据写入原始流但它无法在不阻塞的
          情况下接受所有数据则将引发 *note BlockingIOError: a78.。

          调用者可能会在此方法返回后释放或改变 `b'，因此该实现应当仅在方
          法调用期间访问 `b'。


File: python.info,  Node: 原始文件 I/O,  Next: 缓冲流,  Prev: I/O 基类,  Up: 类的层次结构

5.16.2.8 原始文件 I/O
.....................

 -- 類別: io.FileIO (name, mode='r', closefd=True, opener=None)

     代表一个包含字节数据的 OS 层级文件的原始二进制流。 它继承自 *note
     RawIOBase: af1.。

     `name' 可以是以下两项之一：

        * 代表将被打开的文件路径的字符串或 *note bytes: 172. 对象。 在此
          情况下 closefd 必须为 ‘True’ (默认值) 否则将会引发异常。

        * 代表一个现有 OS 层级文件描述符的号码的整数，作为结果的 *note
          FileIO: d6c. 对象将可访问该文件。 当 FileIO 对象被关闭时此 fd
          也将被关闭，除非 `closefd' 设为 ‘False’。

     `mode' 可以为 ‘'r'’, ‘'w'’, ‘'x'’ 或 ‘'a'’ 分别表示读取（默认模式）
     、写入、独占新建或添加。 如果以写入或添加模式打开的文件不存在将自动
     新建；当以写入模式打开时文件将先清空。 以新建模式打开时如果文件已存
     在则将引发 *note FileExistsError: a39.。 以新建模式打开文件也意味着
     要写入，因此该模式的行为与 ‘'w'’ 类似。 在模式中附带 ‘'+'’ 将允许同
     时读取和写入。

     该类的 ‘read()’ (当附带正值参数调用时), ‘readinto()’ 和 ‘write()’ 方
     法将只执行一次系统调用。

     可以通过传入一个可调用对象作为 `opener' 来使用自定义文件打开器。 然
     后通过调用 `opener' 并传入 (`name', `flags') 来获取文件对象所对应的
     下层文件描述符。 `opener' 必须返回一个打开文件描述符（传入 *note
     os.open: 758. 作为 `opener' 的结果在功能上将与传入 ‘None’ 类似）。

     新创建的文件是 *note 不可继承的: 8e7.。

     有关 opener 参数的示例，请参见内置函数 *note open(): 16f. 。

     3.3 版更變: 增加了 `opener' 参数。增加了 ‘'x'’ 模式。

     3.4 版更變: 文件现在禁止继承。

     *note FileIO: d6c. 在继承自 *note RawIOBase: af1. 和 *note IOBase:
     30c. 的现有成员以外还提供了以下数据属性和方法:

      -- 屬性: mode

          构造函数中给定的模式。

      -- 屬性: name

          文件名。当构造函数中没有给定名称时，这是文件的文件描述符。


File: python.info,  Node: 缓冲流,  Next: 文本 I/O<2>,  Prev: 原始文件 I/O,  Up: 类的层次结构

5.16.2.9 缓冲流
...............

相比原始 I/O，缓冲 I/O 流提供了针对 I/O 设备的更高层级接口。

 -- 類別: io.BytesIO ([initial_bytes])

     一个使用内在字节缓冲区的二进制流。 它继承自 *note BufferedIOBase:
     67f.。 在 *note close(): 1147. 方法被调用时将会丢弃缓冲区。

     可选参数 `initial_bytes' 是一个包含初始数据的 *note bytes-like
     object: 6df.。

     *note BytesIO: 88a. 在继承自 *note BufferedIOBase: 67f. 和 *note
     IOBase: 30c. 的成员以外还提供或重载了下列方法:

      -- 成員函式: getbuffer ()

          返回一个对应于缓冲区内容的可读写视图而不必拷贝其数据。 此外，
          改变视图将透明地更新缓冲区内容:

               >>> b = io.BytesIO(b"abcdef")
               >>> view = b.getbuffer()
               >>> view[2:4] = b"56"
               >>> b.getvalue()
               b'ab56ef'

               備註: 只要视图保持存在，*note BytesIO: 88a. 对象就无法被
               改变大小或关闭。

          3.2 版新加入.

      -- 成員函式: getvalue ()

          返回包含整个缓冲区内容的 *note bytes: 172.。

      -- 成員函式: read1 ([size])

          在 *note BytesIO: 88a. 中，这与 *note read(): 1ebb. 相同。

          3.7 版更變: `size' 参数现在是可选的。

      -- 成員函式: readinto1 (b)

          在 *note BytesIO: 88a. 中，这与 *note readinto(): 2150. 相同。

          3.5 版新加入.

 -- 類別: io.BufferedReader (raw, buffer_size=DEFAULT_BUFFER_SIZE)

     一个提供对可读、不可查找的 *note RawIOBase: af1. 原始二进制流的高层
     级访问的缓冲二进制流。 它继承自 *note BufferedIOBase: 67f.。

     当从此对象读取数据时，可能会从下层原始流请求更大量的数据，并存放到
     内部缓冲区中。 接下来可以在后续读取时直接返回缓冲数据。

     根据给定的可读 `raw' 流和 `buffer_size' 创建 *note BufferedReader:
     c5b. 的构造器。 如果省略 `buffer_size'，则会使用 *note
     DEFAULT_BUFFER_SIZE: 172f.。

     *note BufferedReader: c5b. 在继承自 *note BufferedIOBase: 67f. 和
     *note IOBase: 30c. 的成员以外还提供或重载了下列方法:

      -- 成員函式: peek ([size])

          从流返回字节数据而不前移位置。 完成此调用将至多读取一次原始流
          。 返回的字节数量可能少于或多于请求的数量。

      -- 成員函式: read ([size])

          读取并返回 `size' 个字节，如果 `size' 未给定或为负值，则读取至
          EOF 或是在非阻塞模式下读取调用将会阻塞。

      -- 成員函式: read1 ([size])

          在原始流上通过单次调用读取并返回至多 `size' 个字节。 如果至少
          缓冲了一个字节，则只返回缓冲的字节。 在其他情况下，将执行一次
          原始流读取。

          3.7 版更變: `size' 参数现在是可选的。

 -- 類別: io.BufferedWriter (raw, buffer_size=DEFAULT_BUFFER_SIZE)

     一个提供对可写、不可查找的 *note RawIOBase: af1. 原始二进制流的高层
     级访问的缓冲二进制流。 它继承自 *note BufferedIOBase: 67f.。

     当写入到此对象时，数据通常会被放入到内部缓冲区中。 缓冲区将在满足某
     些条件的情况下被写到下层的 *note RawIOBase: af1. 对象，包括:

        * 当缓冲区对于所有挂起数据而言太小时；

        * 当 *note flush(): 215b. 被调用时

        * 当（为 *note BufferedRandom: 1734. 对象）请求 ‘seek()’ 时；

        * 当 *note BufferedWriter: 1733. 对象被关闭或销毁时。

     该构造器会为给定的可写 `raw' 流创建一个 *note BufferedWriter:
     1733.。 如果未给定 `buffer_size'，则使用默认的 *note
     DEFAULT_BUFFER_SIZE: 172f.。

     *note BufferedWriter: 1733. 在继承自 *note BufferedIOBase: 67f. 和
     *note IOBase: 30c. 的成员以外还提供或重载了下列方法:

      -- 成員函式: flush ()

          将缓冲区中保存的字节数据强制放入原始流。 如果原始流发生阻塞则
          应当引发 *note BlockingIOError: a78.。

      -- 成員函式: write (b)

          写入 *note bytes-like object: 6df. `b' 并返回写入的字节数。 当
          处于非阻塞模式时，如果缓冲区需要被写入但原始流发生阻塞则将引发
          *note BlockingIOError: a78.。

 -- 類別: io.BufferedRandom (raw, buffer_size=DEFAULT_BUFFER_SIZE)

     一个提供对不可查找的 *note RawIOBase: af1. 原始二进制流的高层级访问
     的缓冲二进制流。 它继承自 *note BufferedReader: c5b. 和 *note
     BufferedWriter: 1733.。

     该构造器会为在第一个参数中给定的可查找原始流创建一个读取器和写入器
     。 如果省略 `buffer_size' 则使用默认的 *note DEFAULT_BUFFER_SIZE:
     172f.。

     *note BufferedRandom: 1734. 能做到 *note BufferedReader: c5b. 或
     *note BufferedWriter: 1733. 所能做的任何事。 此外，还会确保实现
     ‘seek()’ 和 ‘tell()’。

 -- 類別: io.BufferedRWPair (reader, writer,
          buffer_size=DEFAULT_BUFFER_SIZE)

     一个提供对两个不可查找的 *note RawIOBase: af1. 原始二进制流的高层级
     访问的缓冲二进制流 — 一个可读，另一个可写。 它继承自 *note
     BufferedIOBase: 67f.。

     `reader' 和 `writer' 分别是可读和可写的 *note RawIOBase: af1. 对象
     。 如果省略 `buffer_size' 则使用默认的 *note DEFAULT_BUFFER_SIZE:
     172f.。

     *note BufferedRWPair: 2147. 实现了 *note BufferedIOBase: 67f. 的所
     有方法，但 *note detach(): 2152. 除外，调用该方法将引发 *note
     UnsupportedOperation: 1083.。

          警告: *note BufferedRWPair: 2147. 不会尝试同步访问其下层的原始
          流。 你不应当将传给它与读取器和写入器相同的对象；而要改用
          *note BufferedRandom: 1734.。


File: python.info,  Node: 文本 I/O<2>,  Prev: 缓冲流,  Up: 类的层次结构

5.16.2.10 文本 I/O
..................

 -- 類別: io.TextIOBase

     文本流的基类。 该类提供了基于字符和行的流 I/O 接口。 它继承自 *note
     IOBase: 30c.。 该类无公有构造器。

     *note TextIOBase: d01. 在来自 *note IOBase: 30c. 的成员以外还提供或
     重载了以下数据属性和方法:

      -- 屬性: encoding

          用于将流的字节串解码为字符串以及将字符串编码为字节串的编码格式
          名称。

      -- 屬性: errors

          解码器或编码器的错误设置。

      -- 屬性: newlines

          一个字符串、字符串元组或者 ‘None’，表示目前已经转写的新行。 根
          据具体实现和初始构造器旗标的不同，此属性或许会不可用。

      -- 屬性: buffer

          由 *note TextIOBase: d01. 处理的下层二进制缓冲区（为一个 *note
          BufferedIOBase: 67f. 的实例）。 它不是 *note TextIOBase: d01.
          API 的组成部分并且不存在于某些实现中。

      -- 成員函式: detach ()

          从 *note TextIOBase: d01. 分离出下层二进制缓冲区并将其返回。

          在下层缓冲区被分离后，*note TextIOBase: d01. 将处于不可用的状
          态。

          某些 *note TextIOBase: d01. 的实现，例如 *note StringIO: 91a.
          可能并无下层缓冲区的概念，因此调用此方法将引发 *note
          UnsupportedOperation: 1083.。

          3.1 版新加入.

      -- 成員函式: read (size=-1)

          从流中读取至多 `size' 个字符并以单个 *note str: 205. 的形式返
          回。 如果 `size' 为负值或 ‘None’，则读取至 EOF。

      -- 成員函式: readline (size=-1)

          读取至换行符或 EOF 并返回单个 ‘str’。 如果流已经到达 EOF，则将
          返回一个空字符串。

          如果指定了 `size' ，最多将读取 `size' 个字符。

      -- 成員函式: seek (offset, whence=SEEK_SET)

          将流位置改为给定的偏移位置 `offset'。 具体行为取决于 `whence'
          形参。 `whence' 的默认值为 ‘SEEK_SET’。

             * ‘SEEK_SET’ 或 ‘0’: 从流的开始位置起查找（默认值）；
               `offset' 必须为 *note TextIOBase.tell(): 2164. 所返回的数
               值或为零。 任何其他 `offset' 值都将导致未定义的行为。

             * ‘SEEK_CUR’ 或 ‘1’: "查找" 到当前位置；`offset' 必须为零，
               表示无操作（所有其他值均不受支持）。

             * ‘SEEK_END’ 或 ‘2’: 查找到流的末尾；`offset' 必须为零（所
               有其他值均不受支持）。

          以不透明数字形式返回新的绝对位置。

          3.1 版新加入: ‘SEEK_*’ 常量.

      -- 成員函式: tell ()

          以不透明数字形式返回当前流的位置。 该数字通常并不代表下层二进
          制存储中对应的字节数。

      -- 成員函式: write (s)

          将字符串 `s' 写入到流并返回写入的字符数。

 -- 類別: io.TextIOWrapper (buffer, encoding=None, errors=None,
          newline=None, line_buffering=False, write_through=False)

     一个提供对 *note BufferedIOBase: 67f. 缓冲二进制流的高层级访问的缓
     冲文本流。 它继承自 *note TextIOBase: d01.。

     `encoding' 给出流被解码或编码时将使用的编码格式。 它默认为 *note
     locale.getpreferredencoding(False): 4ab.。

     `errors' 是一个可选的字符串，它指明编码格式和编码格式错误的处理方式
     。 传入 ‘'strict'’ 将在出现编码格式错误时引发 *note ValueError:
     16d. (默认值 ‘None’ 具有相同的效果)，传入 ‘'ignore'’ 将忽略错误。
     (请注意忽略编码格式错误会导致数据丢失。) ‘'replace'’ 会在出现错误数
     据时插入一个替换标记 (例如 ‘'?'’)。 ‘'backslashreplace'’ 将把错误数
     据替换为一个反斜杠转义序列。 在写入时，还可以使用
     ‘'xmlcharrefreplace'’ (替换为适当的 XML 字符引用) 或
     ‘'namereplace'’ (替换为 ‘\N{...}’ 转义序列)。 任何其他通过 *note
     codecs.register_error(): eb9. 注册的错误处理方式名称也可以被接受。

     `newline' 控制行结束符处理方式。 它可以为 ‘None’, ‘''’, ‘'\n'’,
     ‘'\r'’ 和 ‘'\r\n'’。 其工作原理如下:

        * 当从流读取输入时，如果 `newline' 为 ‘None’，则将启用 *note
          universal newlines: 6eb. 模式。 输入中的行结束符可以为 ‘'\n'’,
          ‘'\r'’ 或 ‘'\r\n'’，在返回给调用者之前它们会被统一转写为
          ‘'\n'’。 如果 `newline' 为 ‘''’，也会启用通用换行模式，但行结
          束符会不加转写即返回给调用者。 如果 `newline' 具有任何其他合法
          的值，则输入行将仅由给定的字符串结束，并且行结束符会不加转写即
          返回给调用者。

        * 将输出写入流时，如果 `newline' 为 ‘None’，则写入的任何 ‘'\n'’
          字符都将转换为系统默认行分隔符 *note os.linesep: 1732.。如果
          `newline' 是 ‘''’ 或 ‘'\n'’，则不进行翻译。如果 `newline' 是任
          何其他合法值，则写入的任何 ‘'\n'’ 字符将被转换为给定的字符串。

     如果 `line_buffering' 为 ‘True’，则当一个写入调用包含换行符或回车时
     将会应用 ‘flush()’。

     如果 `write_through' 为 ‘True’，对 ‘write()’ 的调用会确保不被缓冲：
     在 *note TextIOWrapper: 6ea. 对象上写入的任何数据会立即交给其下层的
     `buffer' 来处理。

     3.3 版更變: 已添加 `write_through' 参数

     3.3 版更變: 默认的 `encoding' 现在将为
     ‘locale.getpreferredencoding(False)’ 而非
     ‘locale.getpreferredencoding()’。 不要使用 *note
     locale.setlocale(): 2166. 来临时改变区域编码格式，要使用当前区域编
     码格式而不是用户的首选编码格式。

     *note TextIOWrapper: 6ea. 在继承自 *note TextIOBase: d01. 和 *note
     IOBase: 30c. 的现有成员以外还提供了以下数据属性和方法:

      -- 屬性: line_buffering

          是否启用行缓冲。

      -- 屬性: write_through

          写入是否要立即传给下层的二进制缓冲。

          3.7 版新加入.

      -- 成員函式: reconfigure (*[, encoding][, errors][, newline][,
               line_buffering][, write_through])

          使用 `encoding', `errors', `newline', `line_buffering' 和
          `write_through' 的新设置来重新配置此文本流。

          未指定的形参将保留当前设定，例外情况是当指定了 `encoding' 但未
          指定 `errors' 时将会使用 ‘errors='strict'’。

          如果已经有数据从流中被读取则将无法再改变编码格式或行结束符。 另
          一方面，在写入数据之后再改变编码格式则是可以的。

          此方法会在设置新的形参之前执行隐式的流刷新。

          3.7 版新加入.

 -- 類別: io.StringIO (initial_value='', newline='\n')

     一个使用内存文本缓冲的文本流。 它继承自 *note TextIOBase: d01.。

     当 *note close(): 1147. 方法被调用时将会丢弃文本缓冲区。

     缓冲区的初始值可通过提供 `initial_value' 来设置。 如果启用了行结束
     符转写，换行将以 *note write(): 2165. 所用的方式被编码。 数据流位置
     将被设为缓冲区的开头。

     `newline' 参数的规则与 *note TextIOWrapper: 6ea. 所用的一致，不同之
     处在于当将输出写入到流时，如果 `newline' 为 ‘None’，则在所有平台上
     换行符都会被写入为 ‘\n’。

     *note StringIO: 91a. 在继承自 *note TextIOBase: d01. 和 *note
     IOBase: 30c. 的现有成员以外还提供了以下方法:

      -- 成員函式: getvalue ()

          返回一个包含缓冲区全部内容的 ‘str’。 换行符会以与 *note
          read(): 2162. 相同的方式被编码，但是流的位置不会被改变。

     用法示例：

          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()

 -- 類別: io.IncrementalNewlineDecoder

     用于在 *note universal newlines: 6eb. 模式下解码换行符的辅助编解码
     器。 它继承自 *note codecs.IncrementalDecoder: 196f.。


File: python.info,  Node: 性能<3>,  Prev: 类的层次结构,  Up: io --- 处理流的核心工具

5.16.2.11 性能
..............

本节讨论所提供的具体 I/O 实现的性能。

* Menu:

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


File: python.info,  Node: 二进制 I/O<2>,  Next: 文本 I/O<3>,  Up: 性能<3>

5.16.2.12 二进制 I/O
....................

即使在用户请求单个字节时，也只读取和写入大块数据。通过该方法，缓冲 I/O 隐
藏了操作系统调用和执行无缓冲 I/O 例程时的任何低效性。增益取决于操作系统
和执行的 I/O 类型。例如，在某些现代操作系统上（例如 Linux），无缓冲磁盘
I/O 可以与缓冲 I/O 一样快。但最重要的是，无论平台和支持设备如何，缓冲
I/O 都能提供可预测的性能。因此，对于二进制数据，应首选使用缓冲的 I/O 而
不是未缓冲的 I/O 。


File: python.info,  Node: 文本 I/O<3>,  Next: 多线程<2>,  Prev: 二进制 I/O<2>,  Up: 性能<3>

5.16.2.13 文本 I/O
..................

二进制存储（如文件）上的文本 I/O 比同一存储上的二进制 I/O 慢得多，因为它
需要使用字符编解码器在Unicode和二进制数据之间进行转换。这在处理大量文本
数据（如大型日志文件）时会变得非常明显。此外，由于使用的重构算法
‘TextIOWrapper.tell()’ 和 ‘TextIOWrapper.seek()’ 都相当慢。

*note StringIO: 91a. 是原生的内存 Unicode 容器，速度与 *note BytesIO:
88a. 相似。


File: python.info,  Node: 多线程<2>,  Next: 可重入性,  Prev: 文本 I/O<3>,  Up: 性能<3>

5.16.2.14 多线程
................

*note FileIO: d6c. 对象是线程安全的，只要它们封装的操作系统调用（比如
Unix下的 ‘read(2)’ ）也是线程安全的。

二进制缓冲对象（例如 *note BufferedReader: c5b, *note BufferedWriter:
1733, *note BufferedRandom: 1734. 和 *note BufferedRWPair: 2147.）使用锁
来保护其内部结构；因此，可以安全地一次从多个线程中调用它们。

*note TextIOWrapper: 6ea. 对象不再是线程安全的。


File: python.info,  Node: 可重入性,  Prev: 多线程<2>,  Up: 性能<3>

5.16.2.15 可重入性
..................

二进制缓冲对象（ *note BufferedReader: c5b. ， *note BufferedWriter:
1733. ， *note BufferedRandom: 1734. 和 *note BufferedRWPair: 2147. 的实
例）不是可重入的。虽然在正常情况下不会发生可重入调用，但仍可能会在 *note
signal: ea. 处理程序执行 I/O 时产生。如果线程尝试重入已经访问的缓冲对象
，则会引发 *note RuntimeError: 3dc. 。注意，这并不禁止其他线程进入缓冲对
象。

上面的内容隐式地扩展到文本文件中，因为 *note open(): 16f. 函数将把缓冲对
象封装在 *note TextIOWrapper: 6ea. 中。 这包括标准流，因而也会影响内置的
*note print(): 971. 函数。


File: python.info,  Node: time --- 时间的访问和转换,  Next: argparse --- 命令行选项、参数和子命令解析器,  Prev: io --- 处理流的核心工具,  Up: 通用操作系统服务

5.16.3 ‘time’ — 时间的访问和转换
--------------------------------

__________________________________________________________________

该模块提供了各种与时间相关的函数。相关功能还可以参阅 *note datetime: 30.
和 *note calendar: 14. 模块。

尽管所有平台皆可使用此模块，但模块内的函数并非所有平台都可用。此模块中定
义的大多数函数的实现都是调用其所在平台的C语言库的同名函数。因为这些函数
的语义可能因平台而异，所以使用时最好查阅对应平台的相关文档。

下面是一些术语和惯例的解释.

   * `epoch' 是时间开始的点，其值取决于平台。对于Unix， epoch 是1970年
     1月1日00:00:00（UTC）。要找出给定平台上的 epoch ，请查看
     ‘time.gmtime(0)’ 。

   * 术语 `纪元秒数' 是指自 epoch （纪元）时间点以来经过的总秒数，通常不
     包括 闰秒(1)。 在所有符合 POSIX 标准的平台上，闰秒都不会记录在总秒
     数中。

   * 此模块中的函数可能无法处理纪元之前或遥远未来的日期和时间。“遥远未来
     ”的定义由对应的C语言库决定；对于32位系统，它通常是指2038年及以后。

   * 函数 *note strptime(): e56. 在接收到 ‘%y’ 格式代码时可以解析使用 2
     位数表示的年份。当解析 2 位数年份时，函数会按照 POSIX 和 ISO C 标准
     进行年份转换：数值 69–99 被映射为 1969–1999；数值 0–68 被映射为
     2000–2068。

   * UTC是协调世界时（Coordinated Universal Time）的缩写。它以前也被称为
     格林威治标准时间（GMT）。使用UTC而不是CUT作为缩写是英语与法语（
     Temps Universel Coordonné）之间妥协的结果，不是什么低级错误。

   * DST是夏令时（Daylight Saving Time）的缩写，在一年的某一段时间中将当
     地时间调整（通常）一小时。 DST的规则非常神奇（由当地法律确定），并
     且每年的起止时间都不同。C语言库中有一个表格，记录了各地的夏令时规则
     （实际上，为了灵活性，C语言库通常是从某个系统文件中读取这张表）。从
     这个角度而言，这张表是夏令时规则的唯一权威真理。

   * 由于平台限制，各种实时函数的精度可能低于其值或参数所要求（或给定）
     的精度。例如，在大多数Unix系统上，时钟频率仅为每秒50或100次。

   * 另一方面， *note time(): 42d. 和 *note sleep(): 773. 的精度优于它们
     的Unix等价物：时间表示为浮点数，*note time(): 42d. 返回最准确的时间
     （使用Unix ‘gettimeofday()’ 如果可用），并且 *note sleep(): 773. 将
     接受非零分数的时间（Unix ‘select()’ 用于实现此功能，如果可用）。

   * 时间值由 *note gmtime(): c11.，*note localtime(): 1080. 和 *note
     strptime(): e56. 返回，并被 *note asctime(): c35.， *note mktime():
     c36. 和 *note strftime(): c37. 接受，是一个 9 个整数的序列。 *note
     gmtime(): c11.， *note localtime(): 1080. 和 *note strptime(): e56.
     的返回值还提供各个字段的属性名称。

     请参阅 *note struct_time: 690. 以获取这些对象的描述。

     3.3 版更變: 在平台支持相应的 ‘struct tm’ 成员时，*note struct_time:
     690. 类型被扩展提供 ‘tm_gmtoff’ 和 ‘tm_zone’ 属性。

     3.6 版更變: *note struct_time: 690. 的属性 ‘tm_gmtoff’ 和 ‘tm_zone’
     现在可在所有平台上使用。

   * 使用以下函数在时间表示之间进行转换：

     从                            到                            使用
                                                                 
     ------------------------------------------------------------------------------------------
                                                                 
     自纪元以来的秒数              UTC 的                        *note gmtime(): c11.
                                   *note struct_time: 690.       
                                   
                                                                 
     自纪元以来的秒数              本地时间的                    *note localtime(): 1080.
                                   *note struct_time: 690.       
                                   
                                                                 
     UTC 的                        自纪元以来的秒数              *note calendar.timegm(): 1a7a.
     *note struct_time: 690.                                     

     本地时间的                    自纪元以来的秒数              *note mktime(): c36.
     *note struct_time: 690.                                     

* Menu:

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

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Leap_second


File: python.info,  Node: 函数<3>,  Next: Clock ID 常量,  Up: time --- 时间的访问和转换

5.16.3.1 函数
.............

 -- 函式: time.asctime ([t])

     转换由 *note gmtime(): c11. 或 *note localtime(): 1080. 所返回的表
     示时间的元组或 *note struct_time: 690. 为以下形式的字符串: ‘'Sun
     Jun 20 23:21:05 1993'’。 日期字段的长度为两个字符，如果日期只有一个
     数字则会以零填充，例如: ‘'Wed Jun 9 04:26:40 1993'’。

     如果未提供 `t'，则会使用 *note localtime(): 1080. 所返回的当前时间
     。 *note asctime(): c35. 不会使用区域设置信息。

          備註: 与同名的C函数不同， *note asctime(): c35. 不添加尾随换行
          符。

 -- 函式: time.pthread_getcpuclockid (thread_id)

     返回指定的 `thread_id' 的特定于线程的CPU时间时钟的 `clk_id' 。

     使用 *note threading.Thread: 21a. 对象的 *note
     threading.get_ident(): b87. 或 *note ident: 2175. 属性为
     `thread_id' 获取合适的值。

          警告: 传递无效的或过期的 `thread_id' 可能会导致未定义的行为，
          例如段错误。

     *note 可用性: 1491. ： Unix（有关详细信息，请参见
     ‘pthread_getcpuclockid(3)’ 的手册页）。

     3.7 版新加入.

 -- 函式: time.clock_getres (clk_id)

     返回指定时钟 `clk_id' 的分辨率（精度）。有关 `clk_id' 的可接受值列
     表，请参阅 *note Clock ID 常量: 2176. 。

     *note Availability: 1491.: Unix.

     3.3 版新加入.

 -- 函式: time.clock_gettime (clk_id) -> float

     返回指定 `clk_id' 时钟的时间。有关 `clk_id' 的可接受值列表，请参阅
     *note Clock ID 常量: 2176. 。

     *note Availability: 1491.: Unix.

     3.3 版新加入.

 -- 函式: time.clock_gettime_ns (clk_id) -> int

     与 *note clock_gettime(): b8b. 相似，但返回时间为纳秒。

     *note Availability: 1491.: Unix.

     3.7 版新加入.

 -- 函式: time.clock_settime (clk_id, time: float)

     设置指定 `clk_id' 时钟的时间。 目前， *note CLOCK_REALTIME: f6d. 是
     `clk_id' 唯一可接受的值。

     *note Availability: 1491.: Unix.

     3.3 版新加入.

 -- 函式: time.clock_settime_ns (clk_id, time: int)

     与 *note clock_settime(): b8c. 相似，但设置时间为纳秒。

     *note Availability: 1491.: Unix.

     3.7 版新加入.

 -- 函式: time.ctime ([secs])

     转换以距离初始纪元的秒数表示的时间为以下形式的字符串: ‘'Sun Jun 20
     23:21:05 1993'’ 代表本地时间。 日期字段的长度为两个字符，如果日期只
     有一个数字则会以零填充，例如: ‘'Wed Jun 9 04:26:40 1993'’。

     如果 `secs' 未提供或为 *note None: 203.，则使用 *note time(): 42d.
     所返回的当前时间。 ‘ctime(secs)’ 等价于 ‘asctime(localtime(secs))’。
     *note ctime(): 19f6. 不会使用区域设置信息。

 -- 函式: time.get_clock_info (name)

     获取有关指定时钟的信息作为命名空间对象。 支持的时钟名称和读取其值的
     相应函数是：

        * ‘'monotonic'’: *note time.monotonic(): 85e.

        * ‘'perf_counter'’: *note time.perf_counter(): 3cc.

        * ‘'process_time'’: *note time.process_time(): 3cd.

        * ‘'thread_time'’: *note time.thread_time(): 1e7.

        * ‘'time'’: *note time.time(): 42d.

     结果具有以下属性：

        - `adjustable' ： 如果时钟可以自动更改（例如通过NTP守护程序）或
          由系统管理员手动更改，则为 ‘True’ ，否则为 ‘False’ 。

        - `implementation' ： 用于获取时钟值的基础C函数的名称。有关可能
          的值，请参阅 *note Clock ID 常量: 2176. 。

        - `monotonic' ：如果时钟不能倒退，则为 ‘True’ ，否则为 ‘False’ 。

        - `resolution' ： 以秒为单位的时钟分辨率（ *note float: 1fd. ）

     3.3 版新加入.

 -- 函式: time.gmtime ([secs])

     将以自 epoch 开始的秒数表示的时间转换为 UTC 的 *note struct_time:
     690. ，其中 dst 标志始终为零。 如果未提供 `secs' 或为 *note None:
     203. ，则使用 *note time(): 42d. 所返回的当前时间。 一秒以内的小数
     将被忽略。 有关 *note struct_time: 690. 对象的说明请参见上文。 有关
     此函数的逆操作请参阅 *note calendar.timegm(): 1a7a.。

 -- 函式: time.localtime ([secs])

     与 *note gmtime(): c11. 相似但转换为当地时间。如果未提供 `secs' 或
     为 *note None: 203. ，则使用由 *note time(): 42d. 返回的当前时间。
     当 DST 适用于给定时间时，dst标志设置为 ‘1’ 。

 -- 函式: time.mktime (t)

     这是 *note localtime(): 1080. 的反函数。它的参数是 *note
     struct_time: 690. 或者完整的 9 元组（因为需要 dst 标志；如果它是未
     知的则使用 ‘-1’ 作为dst标志），它表示 `local' 的时间，而不是 UTC 。
     它返回一个浮点数，以便与 *note time(): 42d. 兼容。如果输入值不能表
     示为有效时间，则 *note OverflowError: a41. 或 *note ValueError:
     16d. 将被引发（这取决于Python或底层C库是否捕获到无效值）。它可以生
     成时间的最早日期取决于平台。

 -- 函式: time.monotonic () -> float

     （以小数表示的秒为单位）返回一个单调时钟的值，即不能倒退的时钟。 该
     时钟不受系统时钟更新的影响。 返回值的参考点未被定义，因此只有两次调
     用之间的差值才是有效的。

     3.3 版新加入.

     3.5 版更變: 该功能现在始终可用且始终在系统范围内。

 -- 函式: time.monotonic_ns () -> int

     与 *note monotonic(): 85e. 相似，但是返回时间为纳秒数。

     3.7 版新加入.

 -- 函式: time.perf_counter () -> float

     （以小数表示的秒为单位）返回一个性能计数器的值，即用于测量较短持续
     时间的具有最高有效精度的时钟。 它会包括睡眠状态所消耗的时间并且作用
     于全系统范围。 返回值的参考点未被定义，因此只有两次调用之间的差值才
     是有效的。

     3.3 版新加入.

 -- 函式: time.perf_counter_ns () -> int

     与 *note perf_counter(): 3cc. 相似，但是返回时间为纳秒。

     3.7 版新加入.

 -- 函式: time.process_time () -> float

     （以小数表示的秒为单位）返回当前进程的系统和用户 CPU 时间的总计值。
     它不包括睡眠状态所消耗的时间。 根据定义它只作用于进程范围。 返回值
     的参考点未被定义，因此只有两次调用之间的差值才是有效的。

     3.3 版新加入.

 -- 函式: time.process_time_ns () -> int

     与 *note process_time(): 3cd. 相似，但是返回时间为纳秒。

     3.7 版新加入.

 -- 函式: time.sleep (secs)

     调用该方法的线程将被暂停执行 ‘secs’ 秒。参数可以是浮点数，以表示更
     为精确的睡眠时长。由于任何捕获到的信号都会终止 *note sleep(): 773.
     引发的该睡眠过程并开始执行信号的处理例程，因此实际的暂停时长可能小
     于请求的时长；此外，由于系统需要调度其他活动，实际暂停时长也可能比
     请求的时间长。

     3.5 版更變: 现在，即使该睡眠过程被信号中断，该函数也会保证调用它的
     线程至少会睡眠 `secs' 秒。信号处理例程抛出异常的情况除外。（欲了解
     我们做出这次改变的原因，请参见 PEP 475(1) ）

 -- 函式: time.strftime (format[, t])

     转换一个元组或 *note struct_time: 690. 表示的由 *note gmtime():
     c11. 或 *note localtime(): 1080. 返回的时间到由 `format' 参数指定的
     字符串。如果未提供 `t' ，则使用由 *note localtime(): 1080. 返回的当
     前时间。 `format' 必须是一个字符串。如果 `t' 中的任何字段超出允许范
     围，则引发 *note ValueError: 16d. 。

     0是时间元组中任何位置的合法参数；如果它通常是非法的，则该值被强制改
     为正确的值。

     以下指令可以嵌入 `format' 字符串中。它们显示时没有可选的字段宽度和
     精度规范，并被 *note strftime(): c37. 结果中的指示字符替换：

     指令            意义                                                 註解
                                                                          
     ---------------------------------------------------------------------------------
                                                                          
     ‘%a’            本地化的缩写星期中每日的名称。
                     
                                                                          
     ‘%A’            本地化的星期中每日的完整名称。
                     
                                                                          
     ‘%b’            本地化的月缩写名称。
                     
                                                                          
     ‘%B’            本地化的月完整名称。
                     
                                                                          
     ‘%c’            本地化的适当日期和时间表示。
                     
                                                                          
     ‘%d’            十进制数 [01,31] 表示的月中日。
                     
                                                                          
     ‘%H’            十进制数 [00,23] 表示的小时（24小时制）。
                     
                                                                          
     ‘%I’            十进制数 [01,12] 表示的小时（12小时制）。
                     
                                                                          
     ‘%j’            十进制数 [001,366] 表示的年中日。
                     
                                                                          
     ‘%m’            十进制数 [01,12] 表示的月。
                     
                                                                          
     ‘%M’            十进制数 [00,59] 表示的分钟。
                     
                                                                          
     ‘%p’            本地化的 AM 或 PM 。                                 (1)
                                                                          
                                                                          
     ‘%S’            十进制数 [00,61] 表示的秒。                          (2)
                                                                          
                                                                          
     ‘%U’            十进制数 [00,53] 表示的一年中的周数（星期日作为一    (3)
                     周的第一天）。 在第一个星期日之前的新年中的所有日    
                     子都被认为是在第 0 周。
                     
                                                                          
     ‘%w’            十进制数 [0(星期日),6] 表示的周中日。
                     
                                                                          
     ‘%W’            十进制数 [00,53] 表示的一年中的周数（星期一作为一    (3)
                     周的第一天）。 在第一个星期一之前的新年中的所有日    
                     子被认为是在第 0 周。
                     
                                                                          
     ‘%x’            本地化的适当日期表示。
                     
                                                                          
     ‘%X’            本地化的适当时间表示。
                     
                                                                          
     ‘%y’            十进制数 [00,99] 表示的没有世纪的年份。
                     
                                                                          
     ‘%Y’            十进制数表示的带世纪的年份。
                     
                                                                          
     ‘%z’            时区偏移以格式 +HHMM 或 -HHMM 形式的 UTC/GMT 的正
                     或负时差指示，其中H表示十进制小时数字，M表示小数分
                     钟数字 [-23:59, +23:59] 。
                     
                                                                          
     ‘%Z’            时区名称（如果不存在时区，则不包含字符）。
                     
                                                                          
     ‘%%’            字面的 ‘'%'’ 字符。
                     

     註解：

       1. 当与 *note strptime(): e56. 函数一起使用时，如果使用 ‘%I’ 指令
          来解析小时， ‘%p’ 指令只影响输出小时字段。

       2. 范围真的是 ‘0’ 到 ‘61’ ；值 ‘60’ 在表示 leap seconds(2) 的时间
          戳中有效，并且由于历史原因支持值 ‘61’ 。

       3. 当与 *note strptime(): e56. 函数一起使用时， ‘%U’ 和 ‘%W’ 仅用
          于指定星期几和年份的计算。

     下面是一个示例，一个与 RFC 2822(3) Internet电子邮件标准以兼容的日期
     格式。 (4)

          >>> from time import gmtime, strftime
          >>> strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
          'Thu, 28 Jun 2001 14:17:15 +0000'

     某些平台可能支持其他指令，但只有此处列出的指令具有 ANSI C 标准化的
     含义。要查看平台支持的完整格式代码集，请参阅 ‘strftime(3)’ 文档。

     在某些平台上，可选的字段宽度和精度规范可以按照以下顺序紧跟在指令的
     初始 ‘'%'’ 之后；这也不可移植。字段宽度通常为2，除了 ‘%j’ ，它是3。

 -- 函式: time.strptime (string[, format])

     根据格式解析表示时间的字符串。 返回值为一个被 *note gmtime(): c11.
     或 *note localtime(): 1080. 返回的 *note struct_time: 690. 。

     `format' 参数使用与 *note strftime(): c37. 相同的指令。 它默认为匹
     配 *note ctime(): 19f6. 所返回的格式 ‘"%a %b %d %H:%M:%S %Y"`’ 。 如
     果 `string' 不能根据 `format' 来解析，或者解析后它有多余的数据，则
     会引发 *note ValueError: 16d.。 当无法推断出更准确的值时，用于填充
     任何缺失数据的默认值是 ‘(1900, 1, 1, 0, 0, 0, 0, 1, -1)’ 。
     `string' 和 `format' 都必须为字符串。

     例如:

          >>> 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)

     支持 ‘%Z’ 指令是基于 ‘tzname’ 中包含的值以及 ‘daylight’ 是否为真。
     因此，它是特定于平台的，除了识别始终已知的 UTC 和 GMT （并且被认为
     是非夏令时时区）。

     仅支持文档中指定的指令。因为每个平台都实现了 ‘strftime()’ ，它有时
     会提供比列出的指令更多的指令。但是 ‘strptime()’ 独立于任何平台，因
     此不一定支持所有未记录为支持的可用指令。

 -- 類別: time.struct_time

     返回的时间值序列的类型为 *note gmtime(): c11. 、 *note localtime():
     1080. 和 *note strptime(): e56. 。它是一个带有 *note named tuple:
     b7b. 接口的对象：可以通过索引和属性名访问值。 存在以下值：

     索引        属性                    值
                                         
     --------------------------------------------------------------------------
                                         
     0           ‘tm_year’               （例如，1993）
                                         
                                         
     1           ‘tm_mon’                range [1, 12]
                                         
                                         
     2           ‘tm_mday’               range [1, 31]
                                         
                                         
     3           ‘tm_hour’               range [0, 23]
                                         
                                         
     4           ‘tm_min’                range [0, 59]
                                         
                                         
     5           ‘tm_sec’                range [0, 61]； 见
                                         *note strftime(): c37. 介绍中的
                                         `(2)'
                                         
                                         
     6           ‘tm_wday’               range [0, 6] ，周一为 0
                                         
                                         
     7           ‘tm_yday’               range [1, 366]
                                         
                                         
     8           ‘tm_isdst’              0, 1 或 -1；如下所示
                                         
                                         
     N/A         ‘tm_zone’               时区名称的缩写
                                         
                                         
     N/A         ‘tm_gmtoff’             以秒为单位的UTC以东偏离
                                         

     请注意，与C结构不同，月份值是 [1,12] 的范围，而不是 [0,11] 。

     在调用 *note mktime(): c36. 时， ‘tm_isdst’ 可以在夏令时生效时设置
     为1，而在夏令时不生效时设置为0。 值-1表示这是未知的，并且通常会导致
     填写正确的状态。

     当一个长度不正确的元组被传递给期望 *note struct_time: 690. 的函数，
     或者具有错误类型的元素时，会引发 *note TypeError: 1fe. 。

 -- 函式: time.time () -> float

     返回以浮点数表示的从 *note epoch: 2172. 开始的秒数的时间值。 epoch
     的具体日期和 leap seconds(5) 的处理取决于平台。 在 Windows 和大多数
     Unix 系统中， epoch 是 1970 年 1 月 1 日 00:00:00 (UTC)，并且闰秒将
     不计入从 epoch 开始的秒数。 这通常被称为 Unix 时间(6)。 要了解给定
     平台上 epoch 的具体定义，请查看 ‘gmtime(0)’。

     请注意，即使时间总是作为浮点数返回，但并非所有系统都提供高于1秒的精
     度。虽然此函数通常返回非递减值，但如果在两次调用之间设置了系统时钟
     ，则它可以返回比先前调用更低的值。

     返回的数字 *note time(): 42d. 可以通过将其传递给 *note gmtime():
     c11. 函数或转换为UTC中更常见的时间格式（即年、月、日、小时等）或通
     过将它传递给 *note localtime(): 1080. 函数获得本地时间。在这两种情
     况下都返回一个 *note struct_time: 690. 对象，日历日期组件可以从中作
     为属性访问。

 -- 函式: time.thread_time () -> float

     （以小数表示的秒为单位）返回当前线程的系统和用户 CPU 时间的总计值。
     它不包括睡眠状态所消耗的时间。 根据定义它只作用于线程范围。 返回值
     的参考点未被定义，因此只有两次调用之间的差值才是有效的。

     *note 可用性: 1491. ： Windows、 Linux、 Unix 系统支持
     ‘CLOCK_THREAD_CPUTIME_ID’ 。

     3.7 版新加入.

 -- 函式: time.thread_time_ns () -> int

     与 *note thread_time(): 1e7. 相似，但返回纳秒时间。

     3.7 版新加入.

 -- 函式: time.time_ns () -> int

     与 *note time(): 42d. 相似，但返回时间为用整数表示的自 *note epoch:
     2172. 以来所经过的纳秒数。

     3.7 版新加入.

 -- 函式: time.tzset ()

     重置库例程使用的时间转换规则。环境变量 ‘TZ’ 指定如何完成。它还将设
     置变量 ‘tzname’ （来自 ‘TZ’ 环境变量）， ‘timezone’ （UTC的西部非
     DST秒）， ‘altzone’ （UTC以西的DST秒）和 ‘daylight’ （如果此时区没
     有任何夏令时规则则为0，如果有夏令时适用的时间，无论过去、现在或未来
     ，则为非零）。

     *note Availability: 1491.: Unix.

          備註: 虽然在很多情况下，更改 ‘TZ’ 环境变量而不调用 *note
          tzset(): 2177. 可能会影响函数的输出，例如 *note localtime():
          1080. ，不应该依赖此行为。

          ‘TZ’ 不应该包含空格。

     ‘TZ’ 环境变量的标准格式是（为了清晰起见，添加了空格）:

          std offset [dst [offset [,start[/time], end[/time]]]]

     组件的位置是：

     ‘std’ 和 ‘dst’

          三个或更多字母数字，给出时区缩写。这些将传到 time.tzname

     ‘offset’

          偏移量的形式为： ‘± hh[:mm[:ss]]’ 。这表示添加到达UTC的本地时
          间的值。如果前面有 ’-’ ，则时区位于本初子午线的东边；否则，在
          它是西边。如果dst之后没有偏移，则假设夏令时比标准时间提前一小
          时。

     ‘start[/time], end[/time]’

          指示何时更改为DST和从DST返回。开始日期和结束日期的格式为以下之
          一：

          ‘J`n'’

               Julian日 `n' （1 <= `n' <= 365）。闰日不计算在内，因此在
               所有年份中，2月28日是第59天，3月1日是第60天。

          ‘`n'’

               从零开始的Julian日（0 <= `n' <= 365）。 闰日计入，可以引
               用2月29日。

          ‘M`m'.`n'.`d'’

               一年中 `m' 月的第 `n' 周（1 <= `n' <= 5 ，1 <= `m' <= 12
               ，第 5 周表示 “可能在 `m' 月第 4 周或第 5 周出现的最后第
               `d' 日”）的第 `d' 天（0 <= `d' <= 6）。 第 1 周是第 `d' 天
               发生的第一周。 第 0 天是星期天。

          ‘time’ 的格式与 ‘offset’ 的格式相同，但不允许使用前导符号（
          ’-’ 或 ’+’ ）。如果没有给出时间，则默认值为02:00:00。

          >>> 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'

     在许多Unix系统（包括 *BSD ， Linux ， Solaris 和 Darwin 上），使用
     系统的区域信息（ ‘tzfile(5)’ ）数据库来指定时区规则会更方便。为此，
     将 ‘TZ’ 环境变量设置为所需时区数据文件的路径，相对于系统 ’zoneinfo’
     时区数据库的根目录，通常位于 ‘/usr/share/zoneinfo’ 。 例如，
     ‘'US/Eastern'’ 、 ‘'Australia/Melbourne'’ 、 ‘'Egypt'’ 或
     ‘'Europe/Amsterdam'’。

          >>> os.environ['TZ'] = 'US/Eastern'
          >>> time.tzset()
          >>> time.tzname
          ('EST', 'EDT')
          >>> os.environ['TZ'] = 'Egypt'
          >>> time.tzset()
          >>> time.tzname
          ('EET', 'EEST')

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0475

   (2) https://en.wikipedia.org/wiki/Leap_second

   (3) https://tools.ietf.org/html/rfc2822.html

   (4) (1) 现在不推荐使用 ‘%Z’ ，但是所有 ANSI C 库都不支持扩展为首选小
时/分钟偏移量的‘‘%z‘‘转义符。 此外，严格的 1982 年原始 RFC 822
(https://tools.ietf.org/html/rfc822.html) 标准要求两位数的年份（%y而不是
%Y），但是实际在2000年之前很久就转移到了4位数年。之后， RFC 822
(https://tools.ietf.org/html/rfc822.html) 已经废弃了，4位数的年份首先被
推荐 RFC 1123 (https://tools.ietf.org/html/rfc1123.html) ，然后被 RFC
2822 (https://tools.ietf.org/html/rfc2822.html) 强制执行。

   (5) https://en.wikipedia.org/wiki/Leap_second

   (6) https://en.wikipedia.org/wiki/Unix_time


File: python.info,  Node: Clock ID 常量,  Next: 时区常量,  Prev: 函数<3>,  Up: time --- 时间的访问和转换

5.16.3.2 Clock ID 常量
......................

这些常量用作 *note clock_getres(): b8a. 和 *note clock_gettime(): b8b. 的
参数。

 -- Data: time.CLOCK_BOOTTIME

     与 *note CLOCK_MONOTONIC: 4fb. 相同，除了它还包括系统暂停的任何时间
     。

     这允许应用程序获得一个暂停感知的单调时钟，而不必处理 *note
     CLOCK_REALTIME: f6d. 的复杂性，如果使用 ‘settimeofday()’ 或类似的时
     间更改时间可能会有不连续性。

     *note 可用性: 1491.: Linux 2.6.39 或更新

     3.7 版新加入.

 -- Data: time.CLOCK_HIGHRES

     Solaris OS 有一个 ‘CLOCK_HIGHRES’ 计时器，试图使用最佳硬件源，并可
     能提供接近纳秒的分辨率。 ‘CLOCK_HIGHRES’ 是不可调节的高分辨率时钟。

     *note 可用性: 1491.: Solaris.

     3.3 版新加入.

 -- Data: time.CLOCK_MONOTONIC

     无法设置的时钟，表示自某些未指定的起点以来的单调时间。

     *note Availability: 1491.: Unix.

     3.3 版新加入.

 -- Data: time.CLOCK_MONOTONIC_RAW

     类似于 *note CLOCK_MONOTONIC: 4fb. ，但可以访问不受NTP调整影响的原
     始硬件时间。

     *note 可用性: 1491.: Linux 2.6.28 和更新版本， macOS 10.12 和更新版
     本。

     3.3 版新加入.

 -- Data: time.CLOCK_PROCESS_CPUTIME_ID

     来自CPU的高分辨率每进程计时器。

     *note Availability: 1491.: Unix.

     3.3 版新加入.

 -- Data: time.CLOCK_PROF

     来自CPU的高分辨率每进程计时器。

     *note 可用性: 1491.: FreeBSD， NetBSD 7 或更新， OpenBSD.

     3.7 版新加入.

 -- Data: time.CLOCK_TAI

     国际原子时间(1)

     该系统必须有一个当前闰秒表以便能给出正确的回答。 PTP 或 NTP 软件可
     以用来维护闰秒表。

     *note 可用性: 1491.: Linux。

     3.9 版新加入.

 -- Data: time.CLOCK_THREAD_CPUTIME_ID

     特定于线程的CPU时钟。

     *note Availability: 1491.: Unix.

     3.3 版新加入.

 -- Data: time.CLOCK_UPTIME

     该时间的绝对值是系统运行且未暂停的时间，提供准确的正常运行时间测量
     ，包括绝对值和间隔值。

     *note 可用性: 1491.: FreeBSD， OpenBSD 5.5 或更新。

     3.7 版新加入.

 -- Data: time.CLOCK_UPTIME_RAW

     单调递增的时钟，记录从一个任意起点开始的时间，不受频率或时间调整的
     影响，并且当系统休眠时将不会递增。

     *note 可用性: 1491.: macOS 10.12 和更新版本。

     3.8 版新加入.

以下常量是唯一可以发送到 *note clock_settime(): b8c. 的参数。

 -- Data: time.CLOCK_REALTIME

     系统范围的实时时钟。 设置此时钟需要适当的权限。

     *note Availability: 1491.: Unix.

     3.3 版新加入.

   ---------- Footnotes ----------

   (1) 
https://www.nist.gov/pml/time-and-frequency-division/nist-time-frequently-asked-questions-faq#tai


File: python.info,  Node: 时区常量,  Prev: Clock ID 常量,  Up: time --- 时间的访问和转换

5.16.3.3 时区常量
.................

 -- Data: time.altzone

     本地DST时区的偏移量，以UTC为单位的秒数，如果已定义。如果当地DST时区
     在UTC以东（如在西欧，包括英国），则是负数。 只有当 ‘daylight’ 非零
     时才使用它。 见下面的注释。

 -- Data: time.daylight

     如果定义了DST时区，则为非零。 见下面的注释。

 -- Data: time.timezone

     本地（非DST）时区的偏移量，UTC以西的秒数（西欧大部分地区为负，美国
     为正，英国为零）。 见下面的注释。

 -- Data: time.tzname

     两个字符串的元组：第一个是本地非DST时区的名称，第二个是本地DST时区
     的名称。 如果未定义DST时区，则不应使用第二个字符串。 见下面的注释。

     備註: 对于上述时区常量（ *note altzone: 217f. 、 *note daylight:
     2180. 、 *note timezone: 2181. 和 *note tzname: 2182. ），该值由模
     块加载时有效的时区规则确定，或者最后一次 *note tzset(): 2177. 被调
     用时，并且在过去的时间可能不正确。建议使用来自 *note localtime():
     1080. 结果的 ‘tm_gmtoff’ 和 ‘tm_zone’ 来获取时区信息。

也參考
......

模块 *note datetime: 30.

     更多面向对象的日期和时间接口。

模块 *note locale: a9.

     国际化服务。 区域设置会影响 *note strftime(): c37. 和 *note
     strptime(): e56. 中许多格式说明符的解析。

模块 *note calendar: 14.

     一般日历相关功能。这个模块的 ‘timegm()’ 是函数 *note gmtime(): c11.
     的反函数。

註解
....


File: python.info,  Node: argparse --- 命令行选项、参数和子命令解析器,  Next: getopt --- C 风格的命令行选项解析器,  Prev: time --- 时间的访问和转换,  Up: 通用操作系统服务

5.16.4 ‘argparse’ — 命令行选项、参数和子命令解析器
--------------------------------------------------

3.2 版新加入.

`源代码：' Lib/argparse.py(1)

__________________________________________________________________

教程
....

此页面包含该 API 的参考信息。有关 Python 命令行解析更细致的介绍，请参阅
*note argparse 教程: 2185.。

*note argparse: 5. 模块可以让人轻松编写用户友好的命令行接口。程序定义它
需要的参数，然后 *note argparse: 5. 将弄清如何从 *note sys.argv: cc6. 解
析出那些参数。 *note argparse: 5. 模块还会自动生成帮助和使用手册，并在用
户给程序传入无效参数时报出错误信息。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/argparse.py


File: python.info,  Node: 示例<16>,  Next: ArgumentParser 对象,  Up: argparse --- 命令行选项、参数和子命令解析器

5.16.4.1 示例
.............

以下代码是一个 Python 程序，它获取一个整数列表并计算总和或者最大值：

     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))

假设上面的 Python 代码保存在名为 ‘prog.py’ 的文件中，它可以在命令行运行
并提供有用的帮助消息：

     $ 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)

当使用适当的参数运行时，它会输出命令行传入整数的总和或者最大值：

     $ python prog.py 1 2 3 4
     4

     $ python prog.py 1 2 3 4 --sum
     10

如果传入无效参数，则会报出错误：

     $ python prog.py a b c
     usage: prog.py [-h] [--sum] N [N ...]
     prog.py: error: argument N: invalid int value: 'a'

以下部分将引导你完成这个示例。

* Menu:

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


File: python.info,  Node: 创建一个解析器,  Next: 添加参数,  Up: 示例<16>

5.16.4.2 创建一个解析器
.......................

使用 *note argparse: 5. 的第一步是创建一个 *note ArgumentParser: 788. 对
象：

     >>> parser = argparse.ArgumentParser(description='Process some integers.')

*note ArgumentParser: 788. 对象包含将命令行解析成 Python 数据类型所需的
全部信息。


File: python.info,  Node: 添加参数,  Next: 解析参数,  Prev: 创建一个解析器,  Up: 示例<16>

5.16.4.3 添加参数
.................

给一个 *note ArgumentParser: 788. 添加程序参数信息是通过调用 *note
add_argument(): 2189. 方法完成的。通常，这些调用指定 *note
ArgumentParser: 788. 如何获取命令行字符串并将其转换为对象。这些信息在
*note parse_args(): 218a. 调用时被存储和使用。例如：

     >>> 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)')

稍后，调用 *note parse_args(): 218a. 将返回一个具有 ‘integers’ 和
‘accumulate’ 两个属性的对象。‘integers’ 属性将是一个包含一个或多个整数的
列表，而 ‘accumulate’ 属性当命令行中指定了 ‘--sum’ 参数时将是 *note
sum(): 316. 函数，否则则是 *note max(): 8f7. 函数。


File: python.info,  Node: 解析参数,  Prev: 添加参数,  Up: 示例<16>

5.16.4.4 解析参数
.................

*note ArgumentParser: 788. 通过 *note parse_args(): 218a. 方法解析参数。
它将检查命令行，把每个参数转换为适当的类型然后调用相应的操作。在大多数情
况下，这意味着一个简单的 *note Namespace: 218c. 对象将从命令行参数中解析
出的属性构建：

     >>> parser.parse_args(['--sum', '7', '-1', '42'])
     Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])

在脚本中，通常 *note parse_args(): 218a. 会被不带参数调用，而 *note
ArgumentParser: 788. 将自动从 *note sys.argv: cc6. 中确定命令行参数。


File: python.info,  Node: ArgumentParser 对象,  Next: add_argument 方法,  Prev: 示例<16>,  Up: argparse --- 命令行选项、参数和子命令解析器

5.16.4.5 ArgumentParser 对象
............................

 -- 類別: 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)

     创建一个新的 *note ArgumentParser: 788. 对象。所有的参数都应当作为
     关键字参数传入。每个参数在下面都有它更详细的描述，但简而言之，它们
     是：

        * *note prog: 218e. - 程序的名称（默认：‘sys.argv[0]’）

        * *note usage: 218f. - 描述程序用途的字符串（默认值：从添加到解
          析器的参数生成）

        * *note description: 2190. - 在参数帮助文档之前显示的文本（默认
          值：无）

        * *note epilog: 2191. - 在参数帮助文档之后显示的文本（默认值：无
          ）

        * *note parents: 2192. - 一个 *note ArgumentParser: 788. 对象的
          列表，它们的参数也应包含在内

        * *note formatter_class: 2193. - 用于自定义帮助文档输出格式的类

        * *note prefix_chars: 2194. - 可选参数的前缀字符集合（默认值：
          ’-’）

        * *note fromfile_prefix_chars: 2195. - 当需要从文件中读取其他参
          数时，用于标识文件名的前缀字符集合（默认值：‘None’）

        * *note argument_default: 2196. - 参数的全局默认值（默认值：
          ‘None’）

        * *note conflict_handler: 2197. - 解决冲突选项的策略（通常是不必
          要的）

        * *note add_help: 2198. - 为解析器添加一个 ‘-h/--help’ 选项（默
          认值： ‘True’）

        * *note allow_abbrev: 78a. - 如果缩写是无歧义的，则允许缩写长选
          项 （默认值：‘True’）

        * *note exit_on_error: 2199. - 决定当错误发生时是否让
          ArgumentParser 附带错误信息退出。 (默认值: ‘True’)

     3.5 版更變: 添加 `allow_abbrev' 参数。

     3.8 版更變: 在之前的版本中，`allow_abbrev' 还会禁用短旗标分组，例如
     ‘-vv’ 表示为 ‘-v -v’。

     3.9 版更變: 添加了 `exit_on_error' 形参。

以下部分描述这些参数如何使用。

* Menu:

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


File: python.info,  Node: prog,  Next: usage,  Up: ArgumentParser 对象

5.16.4.6 prog
.............

默认情况下，*note ArgumentParser: 788. 对象使用 ‘sys.argv[0]’ 来确定如何
在帮助消息中显示程序名称。这一默认值几乎总是可取的，因为它将使帮助消息与
从命令行调用此程序的方式相匹配。例如，对于有如下代码的名为
‘myprogram.py’ 的文件：

     import argparse
     parser = argparse.ArgumentParser()
     parser.add_argument('--foo', help='foo help')
     args = parser.parse_args()

该程序的帮助信息将显示 ‘myprogram.py’ 作为程序名称（无论程序从何处被调用
）：

     $ 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

要更改这样的默认行为，可以使用 ‘prog=’ 参数为 *note ArgumentParser: 788.
提供另一个值：

     >>> parser = argparse.ArgumentParser(prog='myprogram')
     >>> parser.print_help()
     usage: myprogram [-h]

     optional arguments:
      -h, --help  show this help message and exit

需要注意的是，无论是从 ‘sys.argv[0]’ 或是从 ‘prog=’ 参数确定的程序名称，
都可以在帮助消息里通过 ‘%(prog)s’ 格式串来引用。

     >>> 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


File: python.info,  Node: usage,  Next: description,  Prev: prog,  Up: ArgumentParser 对象

5.16.4.7 usage
..............

默认情况下，*note ArgumentParser: 788. 根据它包含的参数来构建用法消息：

     >>> 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

可以通过 ‘usage=’ 关键字参数覆盖这一默认消息：

     >>> 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

在用法消息中可以使用 ‘%(prog)s’ 格式说明符来填入程序名称。


File: python.info,  Node: description,  Next: epilog,  Prev: usage,  Up: ArgumentParser 对象

5.16.4.8 description
....................

大多数对 *note ArgumentParser: 788. 构造方法的调用都会使用
‘description=’ 关键字参数。 这个参数简要描述这个程序做什么以及怎么做。 在
帮助消息中，这个描述会显示在命令行用法字符串和各种参数的帮助消息之间:

     >>> 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

在默认情况下，description 将被换行以便适应给定的空间。如果想改变这种行为
，见 *note formatter_class: 2193. 参数。


File: python.info,  Node: epilog,  Next: parents,  Prev: description,  Up: ArgumentParser 对象

5.16.4.9 epilog
...............

一些程序喜欢在 description 参数后显示额外的对程序的描述。这种文字能够通
过给 *note ArgumentParser: 788.:: 提供 ‘epilog=’ 参数而被指定。

     >>> 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

和 *note description: 2190. 参数一样，‘epilog=’ text 在默认情况下会换行
，但是这种行为能够被调整通过提供 *note formatter_class: 2193. 参数给
‘ArgumentParse’.


File: python.info,  Node: parents,  Next: formatter_class,  Prev: epilog,  Up: ArgumentParser 对象

5.16.4.10 parents
.................

有些时候，少数解析器会使用同一系列参数。 单个解析器能够通过提供
‘parents=’ 参数给 *note ArgumentParser: 788. 而使用相同的参数而不是重复
这些参数的定义。‘parents=’ 参数使用 *note ArgumentParser: 788. 对象的列
表，从它们那里收集所有的位置和可选的行为，然后将这写行为加到正在构建的
*note ArgumentParser: 788. 对象。

     >>> 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)

请注意大多数父解析器会指定 ‘add_help=False’ . 否则， ‘ArgumentParse’ 将
会看到两个 ‘-h/--help’ 选项（一个在父参数中一个在子参数中）并且产生一个
错误。

     備註: 你在通过‘‘parents=‘‘ 传递解析器之前必须完全初始化它们。 如果
     你在子解析器之后改变父解析器，这些改变将不会反映在子解析器上。


File: python.info,  Node: formatter_class,  Next: prefix_chars,  Prev: parents,  Up: ArgumentParser 对象

5.16.4.11 formatter_class
.........................

*note ArgumentParser: 788. 对象允许通过指定备用格式化类来自定义帮助格式
。目前，有四种这样的类。

 -- 類別: argparse.RawDescriptionHelpFormatter
 -- 類別: argparse.RawTextHelpFormatter
 -- 類別: argparse.ArgumentDefaultsHelpFormatter
 -- 類別: argparse.MetavarTypeHelpFormatter

*note RawDescriptionHelpFormatter: 219a. 和 *note RawTextHelpFormatter:
219b. 在正文的描述和展示上给与了更多的控制。*note ArgumentParser: 788. 对
象会将 *note description: 2190. 和 *note epilog: 2191. 的文字在命令行中
自动换行。

     >>> parser = argparse.ArgumentParser(
     ...     prog='PROG',
     ...     description='''this description
     ...         was indented weird
     ...             but that is okay''',
     ...     epilog='''
     ...             likewise for this epilog whose whitespace will
     ...         be cleaned up and whose words will be wrapped
     ...         across a couple lines''')
     >>> 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

传 *note RawDescriptionHelpFormatter: 219a. 给 ‘formatter_class=’ 表示
*note description: 2190. 和 *note epilog: 2191. 已经被正确的格式化了，不
能在命令行中被自动换行:

     >>> parser = argparse.ArgumentParser(
     ...     prog='PROG',
     ...     formatter_class=argparse.RawDescriptionHelpFormatter,
     ...     description=textwrap.dedent('''\
     ...         Please do not mess up this text!
     ...         --------------------------------
     ...             I have indented it
     ...             exactly the way
     ...             I want it
     ...         '''))
     >>> 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

*note RawTextHelpFormatter: 219b. 保留所有种类文字的空格，包括参数的描述
。然而，多重的新行会被替换成一行。如果你想保留多重的空白行，可以在新行之
间加空格。

*note ArgumentDefaultsHelpFormatter: f80. 自动添加默认的值的信息到每一个
帮助信息的参数中:

     >>> 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)

*note MetavarTypeHelpFormatter: 219c. 为它的值在每一个参数中使用 *note
type: 219d. 的参数名当作它的显示名（而不是使用通常的格式 *note dest:
219e. ):

     >>> 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


File: python.info,  Node: prefix_chars,  Next: fromfile_prefix_chars,  Prev: formatter_class,  Up: ArgumentParser 对象

5.16.4.12 prefix_chars
......................

许多命令行会使用 ‘-’ 当作前缀，比如 ‘-f/--foo’。如果解析器需要支持不同的
或者额外的字符，比如像 ‘+f’ 或者 ‘/foo’ 的选项，可以在参数解析构建器中使
用 ‘prefix_chars=’ 参数。

     >>> 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')

‘prefix_chars=’ 参数默认使用 ‘'-'’。 提供一组不包括 ‘-’ 的字符将导致
‘-f/--foo’ 选项不被允许。


File: python.info,  Node: fromfile_prefix_chars,  Next: argument_default,  Prev: prefix_chars,  Up: ArgumentParser 对象

5.16.4.13 fromfile_prefix_chars
...............................

有些时候，先举个例子，当处理一个特别长的参数列表的时候，把它存入一个文件
中而不是在命令行打出来会很有意义。如果 ‘fromfile_prefix_chars=’ 参数提供
给 *note ArgumentParser: 788. 构造函数，之后所有类型的字符的参数都会被当
成文件处理，并且会被文件包含的参数替代。举个栗子:

     >>> 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')

从文件读取的参数在默认情况下必须一个一行（但是可参见 *note
convert_arg_line_to_args(): 219f.）并且它们被视为与命令行上的原始文件引
用参数位于同一位置。所以在以上例子中，‘['-f', 'foo', '@args.txt']’ 的表
示和 ‘['-f', 'foo', '-f', 'bar']’ 的表示相同。

‘fromfile_prefix_chars=’ 参数默认为 ‘None’，意味着参数不会被当作文件对待
。


File: python.info,  Node: argument_default,  Next: allow_abbrev,  Prev: fromfile_prefix_chars,  Up: ArgumentParser 对象

5.16.4.14 argument_default
..........................

一般情况下，参数默认会通过设置一个默认到 *note add_argument(): 2189. 或
者调用带一组指定键值对的 *note ArgumentParser.set_defaults(): 21a0. 方法
。但是有些时候，为参数指定一个普遍适用的解析器会更有用。这能够通过传输
‘argument_default=’ 关键词参数给 *note ArgumentParser: 788. 来完成。举个
栗子，要全局禁止在 *note parse_args(): 218a. 中创建属性，我们提供
‘argument_default=SUPPRESS’:

     >>> 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()


File: python.info,  Node: allow_abbrev,  Next: conflict_handler,  Prev: argument_default,  Up: ArgumentParser 对象

5.16.4.15 allow_abbrev
......................

正常情况下，当你向 *note ArgumentParser: 788. 的 *note parse_args():
218a. 方法传入一个参数列表时，它会 *note recognizes abbreviations: 789.。

这个特性可以设置 ‘allow_abbrev’ 为 ‘False’ 来关闭:

     >>> 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

3.5 版新加入.


File: python.info,  Node: conflict_handler,  Next: add_help,  Prev: allow_abbrev,  Up: ArgumentParser 对象

5.16.4.16 conflict_handler
..........................

*note ArgumentParser: 788. 对象不允许在相同选项字符串下有两种行为。默认
情况下， *note ArgumentParser: 788. 对象会产生一个异常如果去创建一个正在
使用的选项字符串参数。

     >>> 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

有些时候（例如：使用 *note parents: 2192.），重写旧的有相同选项字符串的
参数会更有用。为了产生这种行为， ‘'resolve'’ 值可以提供给 *note
ArgumentParser: 788. 的 ‘conflict_handler=’ 参数:

     >>> 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

注意 *note ArgumentParser: 788. 对象只能移除一个行为如果它所有的选项字符
串都被重写。所以，在上面的例子中，旧的 ‘-f/--foo’ 行为 回合 ‘-f’ 行为保
持一样, 因为只有 ‘--foo’ 选项字符串被重写。


File: python.info,  Node: add_help,  Next: exit_on_error,  Prev: conflict_handler,  Up: ArgumentParser 对象

5.16.4.17 add_help
..................

默认情况下，ArgumentParser 对象添加一个简单的显示解析器帮助信息的选项。
举个栗子，考虑一个名为 ‘myprogram.py’ 的文件包含如下代码:

     import argparse
     parser = argparse.ArgumentParser()
     parser.add_argument('--foo', help='foo help')
     args = parser.parse_args()

如果 ‘-h’ or ‘--help’ 在命令行中被提供, 参数解析器帮助信息会打印:

     $ python myprogram.py --help
     usage: myprogram.py [-h] [--foo FOO]

     optional arguments:
      -h, --help  show this help message and exit
      --foo FOO   foo help

有时候可能会需要关闭额外的帮助信息。这可以通过在 *note ArgumentParser:
788. 中设置 ‘add_help=’ 参数为 ‘False’ 来实现。

     >>> 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

帮助选项一般为 ‘-h/--help’。如果 ‘prefix_chars=’ 被指定并且没有包含 ‘-’
字符，在这种情况下， ‘-h’ ‘--help’ 不是有效的选项。此时， ‘prefix_chars’
的第一个字符将用作帮助选项的前缀。

     >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
     >>> parser.print_help()
     usage: PROG [+h]

     optional arguments:
       +h, ++help  show this help message and exit


File: python.info,  Node: exit_on_error,  Prev: add_help,  Up: ArgumentParser 对象

5.16.4.18 exit_on_error
.......................

正常情况下，当你向 *note ArgumentParser: 788. 的 *note parse_args():
218a. 方法传入一个无效的参数列表时，它将会退出并发出错误信息。

如果用户想要手动捕获错误，可通过将 ‘exit_on_error’ 设为 ‘False’ 来启用该
特性:

     >>> 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

3.9 版新加入.


File: python.info,  Node: add_argument 方法,  Next: parse_args 方法,  Prev: ArgumentParser 对象,  Up: argparse --- 命令行选项、参数和子命令解析器

5.16.4.19 add_argument() 方法
.............................

 -- 成員函式: ArgumentParser.add_argument (name or flags...[, action][,
          nargs][, const][, default][, type][, choices][, required][,
          help][, metavar][, dest])

     定义单个的命令行参数应当如何解析。每个形参都在下面有它自己更多的描
     述，长话短说有：

        * *note name or flags: 21a3. - 一个命名或者一个选项字符串的列表
          ，例如 ‘foo’ 或 ‘-f, --foo’。

        * *note action: 21a4. - 当参数在命令行中出现时使用的动作基本类型
          。

        * *note nargs: 21a5. - 命令行参数应当消耗的数目。

        * *note const: 21a6. - 被一些 *note action: 21a4. 和 *note
          nargs: 21a5. 选择所需求的常数。

        * *note default: 21a7. - 当参数未在命令行中出现并且也不存在于命
          名空间对象时所产生的值。

        * *note type: 219d. - 命令行参数应当被转换成的类型。

        * *note choices: 21a8. - 可用的参数的容器。

        * *note required: 21a9. - 此命令行选项是否可省略 （仅选项可用）
          。

        * *note help: 21aa. - 一个此选项作用的简单描述。

        * *note metavar: 21ab. - 在使用方法消息中使用的参数值示例。

        * *note dest: 219e. - 被添加到 *note parse_args(): 218a. 所返回
          对象上的属性名。

以下部分描述这些参数如何使用。

* Menu:

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


File: python.info,  Node: name or flags,  Next: action,  Up: add_argument 方法

5.16.4.20 name or flags
.......................

*note add_argument(): 2189. 方法必须知道它是否是一个选项，例如 ‘-f’ 或
‘--foo’，或是一个位置参数，例如一组文件名。第一个传递给 *note
add_argument(): 2189. 的参数必须是一系列 flags 或者是一个简单的参数名。
例如，可以选项可以被这样创建:

     >>> parser.add_argument('-f', '--foo')

而位置参数可以这么创建:

     >>> parser.add_argument('bar')

当 *note parse_args(): 218a. 被调用，选项会以 ‘-’ 前缀识别，剩下的参数则
会被假定为位置参数:

     >>> 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


File: python.info,  Node: action,  Next: nargs,  Prev: name or flags,  Up: add_argument 方法

5.16.4.21 action
................

*note ArgumentParser: 788. 对象将命令行参数与动作相关联。这些动作可以做
与它们相关联的命令行参数的任何事，尽管大多数动作只是简单的向 *note
parse_args(): 218a. 返回的对象上添加属性。‘action’ 命名参数指定了这个命
令行参数应当如何处理。供应的动作有：

   * ‘'store'’ - 存储参数的值。这是默认的动作。例如:

          >>> parser = argparse.ArgumentParser()
          >>> parser.add_argument('--foo')
          >>> parser.parse_args('--foo 1'.split())
          Namespace(foo='1')

   * ‘'store_const'’ - 存储被 *note const: 21a6. 命名参数指定的值。
     ‘'store_const'’ 动作通常用在选项中来指定一些标志。例如:

          >>> parser = argparse.ArgumentParser()
          >>> parser.add_argument('--foo', action='store_const', const=42)
          >>> parser.parse_args(['--foo'])
          Namespace(foo=42)

   * ‘'store_true'’ and ‘'store_false'’ - 这些是 ‘'store_const'’ 分别用
     作存储 ‘True’ 和 ‘False’ 值的特殊用例。另外，它们的默认值分别为
     ‘False’ 和 ‘True’。例如:

          >>> 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)

   * ‘'append'’ - 存储一个列表，并且将每个参数值追加到列表中。在允许多次
     使用选项时很有用。例如:

          >>> parser = argparse.ArgumentParser()
          >>> parser.add_argument('--foo', action='append')
          >>> parser.parse_args('--foo 1 --foo 2'.split())
          Namespace(foo=['1', '2'])

   * ‘'append_const'’ - 这存储一个列表，并将 *note const: 21a6. 命名参数
     指定的值追加到列表中。（注意 *note const: 21a6. 命名参数默认为
     ‘None’。）‘‘’append_const’‘‘ 动作一般在多个参数需要在同一列表中存储
     常数时会有用。例如:

          >>> 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'>])

   * ‘'count'’ - 计算一个关键字参数出现的数目或次数。例如，对于一个增长
     的详情等级来说有用:

          >>> parser = argparse.ArgumentParser()
          >>> parser.add_argument('--verbose', '-v', action='count', default=0)
          >>> parser.parse_args(['-vvv'])
          Namespace(verbose=3)

     请注意，`default' 将为 ‘None’，除非显式地设为 `0'。

   * ‘'help'’ - 打印所有当前解析器中的选项和参数的完整帮助信息，然后退出
     。默认情况下，一个 help 动作会被自动加入解析器。关于输出是如何创建
     的，参与 *note ArgumentParser: 788.。

   * ‘'version'’ - 期望有一个 ‘version=’ 命名参数在 *note
     add_argument(): 2189. 调用中，并打印版本信息并在调用后退出:

          >>> 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

   * ‘'extend'’ - 这会存储一个列表，并将每个参数值加入到列表中。 示例用
     法:

          >>> 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'])

     3.8 版新加入.

你还可以通过传递一个 Action 子类或实现相同接口的其他对象来指定任意操作。
‘BooleanOptionalAction’ 在 ‘argparse’ 中可用并会添加对布尔型操作例如
‘--foo’ 和 ‘--no-foo’ 的支持:

     >>> import argparse
     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--foo', action=argparse.BooleanOptionalAction)
     >>> parser.parse_args(['--no-foo'])
     Namespace(foo=False)

3.9 版新加入.

创建自定义动作的推荐方式是扩展 *note Action: 21ac.，重载 ‘__call__’ 方法
以及可选的 ‘__init__’ 和 ‘format_usage’ 方法。

一个自定义动作的例子:

     >>> 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')

更多描述，见 *note Action: 21ac.。


File: python.info,  Node: nargs,  Next: const,  Prev: action,  Up: add_argument 方法

5.16.4.22 nargs
...............

ArgumentParser 对象通常关联一个单独的命令行参数到一个单独的被执行的动作
。 ‘nargs’ 命名参数关联不同数目的命令行参数到单一动作。支持的值有：

   * ‘N’ （一个整数）。命令行中的 ‘N’ 个参数会被聚集到一个列表中。 例如:

          >>> 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'])

     注意 ‘nargs=1’ 会产生一个单元素列表。这和默认的元素本身是不同的。

   * ‘'?'’。如果可能的话，会从命令行中消耗一个参数，并产生一个单一项。如
     果当前没有命令行参数，则会产生 *note default: 21a7. 值。注意，对于
     选项，有另外的用例 - 选项字符串出现但没有跟随命令行参数，则会产生
     *note const: 21a6. 值。一些说用用例:

          >>> 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')

     ‘nargs='?'’ 的一个更普遍用法是允许可选的输入或输出文件:

          >>> 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'>)

   * ‘'*'’。所有当前命令行参数被聚集到一个列表中。注意通过 ‘nargs='*'’ 来
     实现多个位置参数通常没有意义，但是多个选项是可能的。例如:

          >>> 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'])

   * ‘'+'’。和 ‘'*'’ 类似，所有当前命令行参数被聚集到一个列表中。另外，
     当前没有至少一个命令行参数时会产生一个错误信息。例如:

          >>> 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

如果不提供 ‘nargs’ 命名参数，则消耗参数的数目将被 *note action: 21a4. 决
定。通常这意味着单一项目（非列表）消耗单一命令行参数。


File: python.info,  Node: const,  Next: default,  Prev: nargs,  Up: add_argument 方法

5.16.4.23 const
...............

*note add_argument(): 2189. 的‘‘const‘‘ 参数用于保存不从命令行中读取但被
各种 *note ArgumentParser: 788. 动作需求的常数值。最常用的两例为：

   * 当 *note add_argument(): 2189. 通过 ‘action='store_const'’ 或
     ‘action='append_const’ 调用时。这些动作将 ‘const’ 值添加到 *note
     parse_args(): 218a. 返回的对象的属性中。在 *note action: 21a4. 的描
     述中查看案例。

   * 当 *note add_argument(): 2189. 通过选项（例如 ‘-f’ 或 ‘--foo’）调用
     并且 ‘nargs='?'’ 时。这会创建一个可以跟随零个或一个命令行参数的选项
     。当解析命令行时，如果选项后没有参数，则将用 ‘const’ 代替。在 *note
     nargs: 21a5. 描述中查看案例。

对 ‘'store_const'’ 和 ‘'append_const'’ 动作， ‘const’ 命名参数必须给出。
对其他动作，默认为 ‘None’。


File: python.info,  Node: default,  Next: type,  Prev: const,  Up: add_argument 方法

5.16.4.24 default
.................

所有选项和一些位置参数可能在命令行中被忽略。*note add_argument(): 2189.
的命名参数 ‘default’，默认值为 ‘None’，指定了在命令行参数未出现时应当使
用的值。对于选项， ‘default’ 值在选项未在命令行中出现时使用:

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--foo', default=42)
     >>> parser.parse_args(['--foo', '2'])
     Namespace(foo='2')
     >>> parser.parse_args([])
     Namespace(foo=42)

如果目标命名空间已经有一个属性集，则 `default' 动作不会覆盖它:

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--foo', default=42)
     >>> parser.parse_args([], namespace=argparse.Namespace(foo=101))
     Namespace(foo=101)

如果 ‘default’ 值是一个字符串，解析器解析此值就像一个命令行参数。特别是
，在将属性设置在 *note Namespace: 218c. 的返回值之前，解析器应用任何提供
的 *note type: 219d. 转换参数。否则解析器使用原值:

     >>> 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)

对于 *note nargs: 21a5. 等于 ‘?’ 或 ‘*’ 的位置参数， ‘default’ 值在没有
命令行参数出现时使用。

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('foo', nargs='?', default=42)
     >>> parser.parse_args(['a'])
     Namespace(foo='a')
     >>> parser.parse_args([])
     Namespace(foo=42)

提供 ‘default=argparse.SUPPRESS’ 导致命令行参数未出现时没有属性被添加:

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
     >>> parser.parse_args([])
     Namespace()
     >>> parser.parse_args(['--foo', '1'])
     Namespace(foo='1')


File: python.info,  Node: type,  Next: choices,  Prev: default,  Up: add_argument 方法

5.16.4.25 type
..............

默认情况下，解析器会将命令行参数当作简单字符串读入。 然而，命令行字符串
经常应当被解读为其他类型，例如 *note float: 1fd. 或 *note int: 204.。
*note add_argument(): 2189. 的 ‘type’ 关键字允许执行任何必要的类型检查和
类型转换。

如果 *note type: 219d. 关键字使用了 *note default: 21a7. 关键字，则类型
转换器仅会在默认值为字符串时被应用。

传给 ‘type’ 的参数可以是任何接受单个字符串的可调用对象。 如果函数引发了
‘ArgumentTypeError’, *note TypeError: 1fe. 或 *note ValueError: 16d.，异
常会被捕获并显示经过良好格式化的错误消息。 其他异常类型则不会被处理。

普通内置类型和函数可被用作类型转换器:

     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)

用户自定义的函数也可以被使用:

     >>> 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')

不建议将 *note bool(): 2bd. 函数用作类型转换器。 它所做的只是将空字符串
转为 ‘False’ 而将非空字符串转为 ‘True’。 这通常不是用户所想要的。

通常，‘type’ 关键字是仅应被用于只会引发上述三种被支持的异常的简单转换的
便捷选项。 任何具有更复杂错误处理或资源管理的转换都应当在参数被解析后由
下游代码来完成。

For example, JSON or YAML conversions have complex error cases that
require better reporting than can be given by the ‘type’ keyword.  A
*note JSONDecodeError: 7f7. would not be well formatted and a
‘FileNotFound’ exception would not be handled at all.

即使 *note FileType: 90d. 在用于 ‘type’ 关键字时也存在限制。 如果一个参
数使用了 `FileType' 并且有一个后续参数出错，则将报告一个错误但文件并不会
被自动关闭。 在此情况下，更好的做法是等待直到解析器运行完毕再使用 *note
with: 7da. 语句来管理文件。

对于简单地检查一组固定值的类型检查器，请考虑改用 *note choices: 21a8. 关
键字。


File: python.info,  Node: choices,  Next: required,  Prev: type,  Up: add_argument 方法

5.16.4.26 choices
.................

某些命令行参数应当从一组受限值中选择。 这可通过将一个容器对象作为
`choices' 关键字参数传给 *note add_argument(): 2189. 来处理。 当执行命令
行解析时，参数值将被检查，如果参数不是可接受的值之一就将显示错误消息:

     >>> 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')

请注意 `choices' 容器包含的内容会在执行任意 *note type: 219d. 转换之后被
检查，因此 `choices' 容器中对象的类型应当与指定的 *note type: 219d. 相匹
配:

     >>> 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)

任何容器都可作为 `choices' 值传入，因此 *note list: 1f8. 对象，*note
set: 1f6. 对象以及自定义容器都是受支持的。

不建议使用 *note enum.Enum: 48d.，因为要控制其在用法、帮助和错误消息中的
外观是很困难的。

已格式化的选项会覆盖默认的 `metavar'，该值一般是派生自 `dest'。 这通常就
是你所需要的，因为用户永远不会看到 `dest' 形参。 如果不想要这样的显示（
或许因为有很多选择），只需指定一个显式的 *note metavar: 21ab.。


File: python.info,  Node: required,  Next: help,  Prev: choices,  Up: add_argument 方法

5.16.4.27 required
..................

通常，*note argparse: 5. 模块会认为 ‘-f’ 和 ‘--bar’ 等旗标是指明 `可选的
' 参数，它们总是可以在命令行中被忽略。 要让一个选项成为 `必需的'，则可以
将 ‘True’ 作为 ‘required=’ 关键字参数传给 *note add_argument(): 2189.:

     >>> 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

如这个例子所示，如果一个选项被标记为 ‘required’，则当该选项未在命令行中
出现时，*note parse_args(): 218a. 将会报告一个错误。

     備註: 必需的选项通常被认为是不适宜的，因为用户会预期 `options' 都是
     `可选的'，因此在可能的情况下应当避免使用它们。


File: python.info,  Node: help,  Next: metavar,  Prev: required,  Up: add_argument 方法

5.16.4.28 help
..............

‘help’ 值是一个包含参数简短描述的字符串。 当用户请求帮助时（一般是通过在
命令行中使用 ‘-h’ 或 ‘--help’ 的方式），这些 ‘help’ 描述将随每个参数一同
显示:

     >>> 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

‘help’ 字符串可包括各种格式描述符以避免重复使用程序名称或参数 *note
default: 21a7. 等文本。 有效的描述符包括程序名称 ‘%(prog)s’ 和传给 *note
add_argument(): 2189. 的大部分关键字参数，例如 ‘%(default)s’, ‘%(type)s’
等等:

     >>> 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

由于帮助字符串支持 %-formatting，如果你希望在帮助字符串中显示 ‘%’ 字面值
，你必须将其转义为 ‘%%’。

*note argparse: 5. 支持静默特定选项的帮助，具体做法是将 ‘help’ 的值设为
‘argparse.SUPPRESS’:

     >>> 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


File: python.info,  Node: metavar,  Next: dest,  Prev: help,  Up: add_argument 方法

5.16.4.29 metavar
.................

当 *note ArgumentParser: 788. 生成帮助消息时，它需要用某种方式来引用每个
预期的参数。 默认情况下，ArgumentParser 对象使用 *note dest: 219e. 值作
为每个对象的 "name"。 默认情况下，对于位置参数动作，*note dest: 219e. 值
将被直接使用，而对于可选参数动作，*note dest: 219e. 值将被转为大写形式。
因此，一个位置参数 ‘dest='bar'’ 的引用形式将为 ‘bar’。 一个带有单独命令
行参数的可选参数 ‘--foo’ 的引用形式将为 ‘FOO’。 示例如下:

     >>> 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

可以使用 ‘metavar’ 来指定一个替代名称:

     >>> 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

请注意 ‘metavar’ 仅改变 `显示的' 名称 - *note parse_args(): 218a. 对象的
属性名称仍然会由 *note dest: 219e. 值确定。

不同的 ‘nargs’ 值可能导致 metavar 被多次使用。 提供一个元组给 ‘metavar’
即为每个参数指定不同的显示信息:

     >>> 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


File: python.info,  Node: dest,  Next: Action 类,  Prev: metavar,  Up: add_argument 方法

5.16.4.30 dest
..............

大多数 *note ArgumentParser: 788. 动作会添加一些值作为 *note
parse_args(): 218a. 所返回对象的一个属性。 该属性的名称由 *note
add_argument(): 2189. 的 ‘dest’ 关键字参数确定。 对于位置参数动作，
‘dest’ 通常会作为 *note add_argument(): 2189. 的第一个参数提供:

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('bar')
     >>> parser.parse_args(['XXX'])
     Namespace(bar='XXX')

对于可选参数动作，‘dest’ 的值通常取自选项字符串。 *note ArgumentParser:
788. 会通过接受第一个长选项字符串并去掉开头的 ‘--’ 字符串来生成 ‘dest’ 的
值。 如果没有提供长选项字符串，则 ‘dest’ 将通过接受第一个短选项字符串并
去掉开头的 ‘-’ 字符来获得。 任何内部的 ‘-’ 字符都将被转换为 ‘_’ 字符以确
保字符串是有效的属性名称。 下面的例子显示了这种行为:

     >>> 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')

‘dest’ 允许提供自定义属性名称:

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--foo', dest='bar')
     >>> parser.parse_args('--foo XXX'.split())
     Namespace(bar='XXX')


File: python.info,  Node: Action 类,  Prev: dest,  Up: add_argument 方法

5.16.4.31 Action 类
...................

Action 类实现了 Action API，它是一个返回可调用对象的可调用对象，返回的可
调用对象可处理来自命令行的参数。 任何遵循此 API 的对象均可作为 ‘action’
形参传给 ‘add_argument()’。

 -- 類別: argparse.Action (option_strings, dest, nargs=None, const=None,
          default=None, type=None, choices=None, required=False,
          help=None, metavar=None)

Action 对象会被 ArgumentParser 用来表示解析从命令行中的一个或多个字符串
中解析出单个参数所必须的信息。 Action 类必须接受两个位置参数以及传给
*note ArgumentParser.add_argument(): 2189. 的任何关键字参数，除了
‘action’ 本身。

Action 的实例（或作为or return value of any callable to the ‘action’ 形
参的任何可调用对象的返回值）应当定义 "dest", "option_strings",
"default", "type", "required", "help" 等属性。 确保这些属性被定义的最容
易方式是调用 ‘Action.__init__’。

Action 的实例应当为可调用对象，因此所有子类都必须重载 ‘__call__’ 方法，
该方法应当接受四个形参:

   * ‘parser’ - 包含此动作的 ArgumentParser 对象。

   * ‘namespace’ - 将由 *note parse_args(): 218a. 返回的 *note
     Namespace: 218c. 对象。 大多数动作会使用 *note setattr(): 1712. 为
     此对象添加属性。

   * ‘values’ - 已关联的命令行参数，并提供相应的类型转换。 类型转换由
     *note add_argument(): 2189. 的 *note type: 219d. 关键字参数来指定。

   * ‘option_string’ - 被用来发起调用此动作的选项字符串。
     ‘option_string’ 参数是可选的，且此参数在动作关联到位置参数时将被略
     去。

‘__call__’ 方法可以执行任意动作，但通常将基于 ‘dest’ 和 ‘values’ 来设置
‘namespace’ 的属性。

动作子类可定义 ‘format_usage’ 方法，该方法不带参数，所返回的字符串将被用
于打印程序的用法说明。 如果未提供此方法，则将使用适当的默认值。


File: python.info,  Node: parse_args 方法,  Next: 其它实用工具,  Prev: add_argument 方法,  Up: argparse --- 命令行选项、参数和子命令解析器

5.16.4.32 parse_args() 方法
...........................

 -- 成員函式: ArgumentParser.parse_args (args=None, namespace=None)

     将参数字符串转换为对象并将其设为命名空间的属性。 返回带有成员的命名
     空间。

     之前对 *note add_argument(): 2189. 的调用决定了哪些对象被创建以及它
     们如何被赋值。 请参阅 *note add_argument(): 2189. 的文档了解详情。

        * *note args: 21af. - 要解析的字符串列表。 默认值是从 *note
          sys.argv: cc6. 获取。

        * *note namespace: 21b0. - 用于获取属性的对象。 默认值是一个新的
          空 *note Namespace: 218c. 对象。

* Menu:

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


File: python.info,  Node: 选项值语法,  Next: 无效的参数,  Up: parse_args 方法

5.16.4.33 选项值语法
....................

*note parse_args(): 218a. 方法支持多种指定选项值的方式（如果它接受选项的
话）。 在最简单的情况下，选项和它的值是作为两个单独参数传入的:

     >>> 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)

对于长选项（名称长度超过一个字符的选项），选项和值也可以作为单个命令行参
数传入，使用 ‘=’ 分隔它们即可:

     >>> parser.parse_args(['--foo=FOO'])
     Namespace(foo='FOO', x=None)

对于短选项（长度只有一个字符的选项），选项和它的值可以拼接在一起:

     >>> parser.parse_args(['-xX'])
     Namespace(foo=None, x='X')

有些短选项可以使用单个 ‘-’ 前缀来进行合并，如果仅有最后一个选项（或没有
任何选项）需要值的话:

     >>> 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')


File: python.info,  Node: 无效的参数,  Next: 包含 - 的参数,  Prev: 选项值语法,  Up: parse_args 方法

5.16.4.34 无效的参数
....................

在解析命令行时，*note parse_args(): 218a. 会检测多种错误，包括有歧义的选
项、无效的类型、无效的选项、错误的位置参数个数等等。 当遇到这种错误时，
它将退出并打印出错误文本同时附带用法消息:

     >>> 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


File: python.info,  Node: 包含 - 的参数,  Next: 参数缩写（前缀匹配）,  Prev: 无效的参数,  Up: parse_args 方法

5.16.4.35 包含 ‘-’ 的参数
.........................

*note parse_args(): 218a. 方法会在用户明显出错时尝试给出错误信息，但某些
情况本身就存在歧义。 例如，命令行参数 ‘-1’ 可能是尝试指定一个选项也可能
是尝试提供一个位置参数。 *note parse_args(): 218a. 方法在此会谨慎行事：
位置参数只有在它们看起来像负数并且解析器中没有任何选项看起来像负数时才能
以 ‘-’ 打头。:

     >>> 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

如果你有必须以 ‘-’ 打头的位置参数并且看起来不像负数，你可以插入伪参数
‘'--'’ 以告诉 *note parse_args(): 218a. 在那之后的内容是一个位置参数:

     >>> parser.parse_args(['--', '-f'])
     Namespace(foo='-f', one=None)


File: python.info,  Node: 参数缩写（前缀匹配）,  Next: 在 sys argv 以外,  Prev: 包含 - 的参数,  Up: parse_args 方法

5.16.4.36 参数缩写（前缀匹配）
..............................

*note parse_args(): 218a. 方法 *note 在默认情况下: 78a. 允许将长选项缩写
为前缀，如果缩写无歧义（即前缀与一个特定选项相匹配）的话:

     >>> 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

可产生一个以上选项的参数会引发错误。 此特定可通过将 *note allow_abbrev:
78a. 设为 ‘False’ 来禁用。


File: python.info,  Node: 在 sys argv 以外,  Next: 命名空间对象,  Prev: 参数缩写（前缀匹配）,  Up: parse_args 方法

5.16.4.37 在 ‘sys.argv’ 以外
............................

有时在 *note sys.argv: cc6. 以外用 ArgumentParser 解析参数也是有用的。 这
可以通过将一个字符串列表传给 *note parse_args(): 218a. 来实现。 它适用于
在交互提示符下进行检测:

     >>> 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])


File: python.info,  Node: 命名空间对象,  Prev: 在 sys argv 以外,  Up: parse_args 方法

5.16.4.38 命名空间对象
......................

 -- 類別: argparse.Namespace

     由 *note parse_args(): 218a. 默认使用的简单类，可创建一个存放属性的
     对象并将其返回。

这个类被有意做得很简单，只是一个具有可读字符串表示形式的 *note object:
3d2.。 如果你更喜欢类似字典的属性视图，你可以使用标准 Python 中惯常的
*note vars(): 116d.:

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--foo')
     >>> args = parser.parse_args(['--foo', 'BAR'])
     >>> vars(args)
     {'foo': 'BAR'}

另一个用处是让 *note ArgumentParser: 788. 为一个已存在对象而不是为一个新
的 *note Namespace: 218c. 对象的属性赋值。 这可以通过指定 ‘namespace=’ 关
键字参数来实现:

     >>> class C:
     ...     pass
     ...
     >>> c = C()
     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--foo')
     >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
     >>> c.foo
     'BAR'


File: python.info,  Node: 其它实用工具,  Next: 升级 optparse 代码,  Prev: parse_args 方法,  Up: argparse --- 命令行选项、参数和子命令解析器

5.16.4.39 其它实用工具
......................

* Menu:

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


File: python.info,  Node: 子命令,  Next: FileType 对象,  Up: 其它实用工具

5.16.4.40 子命令
................

 -- 成員函式: ArgumentParser.add_subparsers ([title][, description][,
          prog][, parser_class][, action][, option_string][, dest][,
          required][, help][, metavar])

     许多程序都会将其功能拆分为一系列子命令，例如，‘svn’ 程序包含的子命
     令有 ‘svn checkout’, ‘svn update’ 和 ‘svn commit’。 当一个程序能执
     行需要多组不同种类命令行参数时这种拆分功能的方式是一个非常好的主意
     。 *note ArgumentParser: 788. 通过 *note add_subparsers(): 59e. 方
     法支持创建这样的子命令。 *note add_subparsers(): 59e. 方法通常不带
     参数地调用并返回一个特殊的动作对象。 这种对象只有一个方法
     ‘add_parser()’，它接受一个命令名称和任意多个 *note ArgumentParser:
     788. 构造器参数，并返回一个可以通常方式进行修改的 *note
     ArgumentParser: 788. 对象。

     形参的描述

        * title - 输出帮助的子解析器分组的标题；如果提供了描述则默认为
          "subcommands"，否则使用位置参数的标题

        * description - 输出帮助中对子解析器的描述，默认为 ‘None’

        * prog - 将与子命令帮助一同显示的用法信息，默认为程序名称和子解
          析器参数之前的任何位置参数。

        * parser_class - 将被用于创建子解析器实例的类，默认为当前解析器
          类（例如 ArgumentParser）

        * *note action: 21a4. - 当此参数在命令行中出现时要执行动作的基本
          类型

        * *note dest: 219e. - 将被用于保存子命令名称的属性名；默认为
          ‘None’ 即不保存任何值

        * *note required: 21a9. - 是否必须要提供子命令，默认为 ‘False’
          (在 3.7 中新增)

        * *note help: 21aa. - 在输出帮助中的子解析器分组帮助信息，默认为
          ‘None’

        * *note metavar: 21ab. - 帮助信息中表示可用子命令的字符串；默认
          为 ‘None’ 并以 {cmd1, cmd2, ..} 的形式表示子命令

     一些使用示例:

          >>> # 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)

     请注意 *note parse_args(): 218a. 返回的对象将只包含主解析器和由命令
     行所选择的子解析器的属性（而没有任何其他子解析器）。 因此在上面的例
     子中，当指定了 ‘a’ 命令时，将只存在 ‘foo’ 和 ‘bar’ 属性，而当指定了
     ‘b’ 命令时，则只存在 ‘foo’ 和 ‘baz’ 属性。

     类似地，当从一个子解析器请求帮助消息时，只有该特定解析器的帮助消息
     会被打印出来。 帮助消息将不包括父解析器或同级解析器的消息。 （每个
     子解析器命令一条帮助消息，但是，也可以像上面那样通过提供 ‘help=’ 参
     数给 ‘add_parser()’ 来给出。）

          >>> 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

     *note add_subparsers(): 59e. 方法也支持 ‘title’ 和 ‘description’ 关
     键字参数。 当两者都存在时，子解析器的命令将出现在输出帮助消息中它们
     自己的分组内。 例如:

          >>> 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

     此外，‘add_parser’ 还支持附加的 ‘aliases’ 参数，它允许多个字符串指
     向同一子解析器。 这个例子类似于 ‘svn’，将别名 ‘co’ 设为 ‘checkout’
     的缩写形式:

          >>> 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')

     一个特别有效的处理子命令的方式是将 *note add_subparsers(): 59e. 方
     法与对 *note set_defaults(): 21a0. 的调用结合起来使用，这样每个子解
     析器就能知道应当执行哪个 Python 函数。 例如:

          >>> # 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))

     通过这种方式，你可以在参数解析结束后让 *note parse_args(): 218a. 执
     行调用适当函数的任务。 像这样将函数关联到动作通常是你处理每个子解析
     器的不同动作的最简便方式。 但是，如果有必要检查被发起调用的子解析器
     的名称，则 *note add_subparsers(): 59e. 调用的 ‘dest’ 关键字参数将
     可实现:

          >>> 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')

     3.7 版更變: 新增 `required' 关键字参数。


File: python.info,  Node: FileType 对象,  Next: 参数组,  Prev: 子命令,  Up: 其它实用工具

5.16.4.41 FileType 对象
.......................

 -- 類別: argparse.FileType (mode='r', bufsize=-1, encoding=None,
          errors=None)

     *note FileType: 90d. 工厂类用于创建可作为 *note
     ArgumentParser.add_argument(): 2189. 的 type 参数传入的对象。 以
     *note FileType: 90d. 对象作为其类型的参数将使用命令行参数以所请求模
     式、缓冲区大小、编码格式和错误处理方式打开文件（请参阅 *note
     open(): 16f. 函数了解详情）:

          >>> 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'>)

     FileType 对象能理解伪参数 ‘'-'’ 并会自动将其转换为 ‘sys.stdin’ 用于
     可读的 *note FileType: 90d. 对象，或是 ‘sys.stdout’ 用于可写的
     *note FileType: 90d. 对象:

          >>> parser = argparse.ArgumentParser()
          >>> parser.add_argument('infile', type=argparse.FileType('r'))
          >>> parser.parse_args(['-'])
          Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>)

     3.4 版新加入: `encodings' 和 `errors' 关键字参数。


File: python.info,  Node: 参数组,  Next: 互斥,  Prev: FileType 对象,  Up: 其它实用工具

5.16.4.42 参数组
................

 -- 成員函式: ArgumentParser.add_argument_group (title=None,
          description=None)

     在默认情况下，*note ArgumentParser: 788. 会在显示帮助消息时将命令行
     参数分为“位置参数”和“可选参数”两组。 当存在比默认更好的参数分组概念
     时，可以使用 *note add_argument_group(): 21bb. 方法来创建适当的分组
     :

          >>> 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

     *note add_argument_group(): 21bb. 方法返回一个具有 *note
     add_argument(): 2189. 方法的参数分组对象，这与常规的 *note
     ArgumentParser: 788. 一样。 当一个参数被加入分组时，解析器会将它视
     为一个正常的参数，但是会在不同的帮助消息分组中显示该参数。 *note
     add_argument_group(): 21bb. 方法接受 `title' 和 `description' 参数
     ，它们可被用来定制显示内容:

          >>> 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

     请注意任意不在你的自定义分组中的参数最终都将回到通常的“位置参数”和
     “可选参数”分组中。


File: python.info,  Node: 互斥,  Next: 解析器默认值,  Prev: 参数组,  Up: 其它实用工具

5.16.4.43 互斥
..............

 -- 成員函式: ArgumentParser.add_mutually_exclusive_group
          (required=False)

     创建一个互斥组。 *note argparse: 5. 将会确保互斥组中只有一个参数在
     命令行中可用:

          >>> 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

     *note add_mutually_exclusive_group(): 21bd. 方法也接受一个
     `required' 参数，表示在互斥组中至少有一个参数是需要的:

          >>> 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

     注意，目前互斥参数组不支持 *note add_argument_group(): 21bb. 的
     `title' 和 `description' 参数。


File: python.info,  Node: 解析器默认值,  Next: 打印帮助,  Prev: 互斥,  Up: 其它实用工具

5.16.4.44 解析器默认值
......................

 -- 成員函式: ArgumentParser.set_defaults (**kwargs)

     在大多数时候，*note parse_args(): 218a. 所返回对象的属性将完全通过
     检查命令行参数和参数动作来确定。 *note set_defaults(): 21a0. 则允许
     加入一些无须任何命令行检查的额外属性:

          >>> 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)

     请注意解析器层级的默认值总是会覆盖参数层级的默认值:

          >>> parser = argparse.ArgumentParser()
          >>> parser.add_argument('--foo', default='bar')
          >>> parser.set_defaults(foo='spam')
          >>> parser.parse_args([])
          Namespace(foo='spam')

     解析器层级默认值在需要多解析器时会特别有用。 请参阅 *note
     add_subparsers(): 59e. 方法了解此类型的一个示例。

 -- 成員函式: ArgumentParser.get_default (dest)

     获取一个命名空间属性的默认值，该值是由 *note add_argument(): 2189.
     或 *note set_defaults(): 21a0. 设置的:

          >>> parser = argparse.ArgumentParser()
          >>> parser.add_argument('--foo', default='badger')
          >>> parser.get_default('foo')
          'badger'


File: python.info,  Node: 打印帮助,  Next: 部分解析,  Prev: 解析器默认值,  Up: 其它实用工具

5.16.4.45 打印帮助
..................

在大多数典型应用中，*note parse_args(): 218a. 将负责任何用法和错误消息的
格式化和打印。 但是，也可使用某些其他格式化方法:

 -- 成員函式: ArgumentParser.print_usage (file=None)

     打印一段简短描述，说明应当如何在命令行中发起调用 *note
     ArgumentParser: 788.。 如果 `file' 为 ‘None’，则默认使用 *note
     sys.stdout: 41f.。

 -- 成員函式: ArgumentParser.print_help (file=None)

     打印一条帮助消息，包括程序用法和通过 *note ArgumentParser: 788. 注
     册的相关参数信息。 如果 `file' 为 ‘None’，则默认使用 *note
     sys.stdout: 41f.。

还存在这些方法的几个变化形式，它们只返回字符串而不打印消息:

 -- 成員函式: ArgumentParser.format_usage ()

     返回一个包含简短描述的字符串，说明应当如何在命令行中发起调用 *note
     ArgumentParser: 788.。

 -- 成員函式: ArgumentParser.format_help ()

     反回一个包含帮助消息的字符串，包括程序用法和通过 *note
     ArgumentParser: 788. 注册的相关参数信息。


File: python.info,  Node: 部分解析,  Next: 自定义文件解析,  Prev: 打印帮助,  Up: 其它实用工具

5.16.4.46 部分解析
..................

 -- 成員函式: ArgumentParser.parse_known_args (args=None,
          namespace=None)

有时一个脚本可能只解析部分命令行参数，而将其余的参数继续传递给另一个脚本
或程序。 在这种情况下，*note parse_known_args(): 21c5. 方法会很有用处。
它的作用方式很类似 *note parse_args(): 218a. 但区别在于当存在额外参数时
它不会产生错误。 而是会返回一个由两个条目构成的元组，其中包含带成员的命
名空间和剩余参数字符串的列表。

     >>> 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'])

     警告: *note 前缀匹配: 789. 规则应用于 ‘parse_known_args()’。 一个选
     项即使只是已知选项的前缀部分解析器也能识别该选项，不会将其放入剩余
     参数列表。


File: python.info,  Node: 自定义文件解析,  Next: 退出方法,  Prev: 部分解析,  Up: 其它实用工具

5.16.4.47 自定义文件解析
........................

 -- 成員函式: ArgumentParser.convert_arg_line_to_args (arg_line)

     从文件读取的参数（见 *note ArgumentParser: 788. 的
     `fromfile_prefix_chars' 关键字参数）将是一行读取一个参数。 *note
     convert_arg_line_to_args(): 219f. 可被重载以使用更复杂的读取方式。

     此方法接受从参数文件读取的字符串形式的单个参数 `arg_line'。 它返回
     从该字符串解析出的参数列表。 此方法将在每次按顺序从参数文件读取一行
     时被调用一次。

     此方法的一个有用的重载是将每个以空格分隔的单词视为一个参数。 下面的
     例子演示了如何实现此重载:

          class MyArgumentParser(argparse.ArgumentParser):
              def convert_arg_line_to_args(self, arg_line):
                  return arg_line.split()


File: python.info,  Node: 退出方法,  Next: 混合解析,  Prev: 自定义文件解析,  Up: 其它实用工具

5.16.4.48 退出方法
..................

 -- 成員函式: ArgumentParser.exit (status=0, message=None)

     此方法将终结程序，退出时附带指定的 `status'，并且如果给出了
     `message' 则会在退出前将其打印输出。 用户可重载此方法以不同方式来处
     理这些步骤:

          class ErrorCatchingArgumentParser(argparse.ArgumentParser):
              def exit(self, status=0, message=None):
                  if status:
                      raise Exception(f'Exiting because of an error: {message}')
                  exit(status)

 -- 成員函式: ArgumentParser.error (message)

     此方法将向标准错误打印包括 `message' 的用法消息并附带状态码 2 终结
     程序。


File: python.info,  Node: 混合解析,  Prev: 退出方法,  Up: 其它实用工具

5.16.4.49 混合解析
..................

 -- 成員函式: ArgumentParser.parse_intermixed_args (args=None,
          namespace=None)

 -- 成員函式: ArgumentParser.parse_known_intermixed_args (args=None,
          namespace=None)

许多 Unix 命令允许用户混用可选参数与位置参数。 *note
parse_intermixed_args(): 451. 和 *note parse_known_intermixed_args():
21cb. 方法均支持这种解析风格。

这些解析器并不支持所有的 argparse 特性，并且当未支持的特性被使用时将会引
发异常。 特别地，子解析器，‘argparse.REMAINDER’ 以及同时包括可选与位置参
数的互斥分组是不受支持的。

下面的例子显示了 *note parse_known_args(): 21c5. 与 *note
parse_intermixed_args(): 451. 之间的差异：前者会将 ‘['2', '3']’ 返回为未
解析的参数，而后者会将所有位置参数收集至 ‘rest’ 中。

     >>> 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])

*note parse_known_intermixed_args(): 21cb. 返回由两个条目组成的元组，其
中包含带成员的命名空间以及剩余参数字符串列表。 当存在任何剩余的未解析参
数字符串时 *note parse_intermixed_args(): 451. 将引发一个错误。

3.7 版新加入.


File: python.info,  Node: 升级 optparse 代码,  Prev: 其它实用工具,  Up: argparse --- 命令行选项、参数和子命令解析器

5.16.4.50 升级 optparse 代码
............................

起初，*note argparse: 5. 曾经尝试通过 *note optparse: c3. 来维持兼容性。
但是，*note optparse: c3. 很难透明地扩展，特别是那些为支持新的 ‘nargs=’
描述方式和更好的用法消息所需的修改。当When most everything in *note
optparse: c3. 中几乎所有内容都已被复制粘贴或打上补丁时，维持向下兼容看来
已是不切实际的。

*note argparse: 5. 模块在许多方面对标准库的 *note optparse: c3. 模块进行
了增强，包括:

   * 处理位置参数。

   * 支持子命令。

   * 允许替代选项前缀例如 ‘+’ 和 ‘/’。

   * 处理零个或多个以及一个或多个风格的参数。

   * 生成更具信息量的用法消息。

   * 提供用于定制 ‘type’ 和 ‘action’ 的更为简单的接口。

从 *note optparse: c3. 到 *note argparse: 5. 的部分升级路径:

   * 将所有 *note optparse.OptionParser.add_option(): 21cd. 调用替换为
     *note ArgumentParser.add_argument(): 2189. 调用。

   * 将 ‘(options, args) = parser.parse_args()’ 替换为 ‘args =
     parser.parse_args()’ 并为位置参数添加额外的 *note
     ArgumentParser.add_argument(): 2189. 调用。 请注意之前所谓的
     ‘options’ 在 *note argparse: 5. 上下文中被称为 ‘args’。

   * 通过使用 *note parse_intermixed_args(): 451. 而非 *note
     parse_args(): 218a. 来替换 *note
     optparse.OptionParser.disable_interspersed_args(): 21ce.。

   * 将回调动作和 ‘callback_*’ 关键字参数替换为 ‘type’ 或 ‘action’ 参数
     。

   * 将 ‘type’ 关键字参数字符串名称替换为相应的类型对象（例如 int,
     float, complex 等）。

   * 将 ‘optparse.Values’ 替换为 *note Namespace: 218c. 并将
     ‘optparse.OptionError’ 和 ‘optparse.OptionValueError’ 替换为
     ‘ArgumentError’。

   * 将隐式参数字符串例如使用标准 Python 字典语法的 ‘%default’ 或
     ‘%prog’ 替换为格式字符串，即 ‘%(default)s’ 和 ‘%(prog)s’。

   * 将 OptionParser 构造器 ‘version’ 参数替换为对
     ‘parser.add_argument('--version', action='version', version='<the
     version>')’ 的调用。


File: python.info,  Node: getopt --- C 风格的命令行选项解析器,  Next: logging --- Python 的日志记录工具,  Prev: argparse --- 命令行选项、参数和子命令解析器,  Up: 通用操作系统服务

5.16.5 ‘getopt’ — C 风格的命令行选项解析器
------------------------------------------

`源代码:' Lib/getopt.py(1)

     備註: *note getopt: 85. 模块是一个命令行选项解析器，其 API 设计会让
     C ‘getopt()’ 函数的用户感到熟悉。 不熟悉 C ‘getopt()’ 函数或者希望
     写更少代码并获得更完善帮助和错误消息的用户应当考虑改用 *note
     argparse: 5. 模块。

__________________________________________________________________

此模块可协助脚本解析 ‘sys.argv’ 中的命令行参数。 它支持与 Unix
‘getopt()’ 函数相同的惯例（包括形式如 ’‘-’’ 与 ’‘--’’ 的参数的特殊含义）
。 也能通过可选的第三个参数来使用与 GNU 软件所支持形式相类似的长选项。

此模块提供了两个函数和一个异常:

 -- 函式: getopt.getopt (args, shortopts, longopts=[])

     解析命令行选项与形参列表。 `args' 为要解析的参数列表，不包含最开头
     的对正在运行的程序的引用。 通常这意味着 ‘sys.argv[1:]’。
     `shortopts' 为脚本所要识别的字母选项，包含要求后缀一个冒号 (‘':'’；
     即与 Unix ‘getopt()’ 所用的格式相同) 的选项。

          備註: 与 GNU ‘getopt()’ 不同，在非选项参数之后，所有后续参数都
          会被视为非选项。 这类似于非 GNU Unix 系统的运作方式。

     如果指定了 `longopts'，则必须为一个由应当被支持的长选项名称组成的列
     表。 开头的 ‘'--'’ 字符不应被包括在选项名称中。 要求参数的长选项后
     应当带一个等号 (‘'='’)。 可选参数不被支持。 如果想仅接受长选项，则
     `shortopts' 应为一个空字符串。 命令行中的长选项只要提供了恰好能匹配
     可接受选项之一的选项名称前缀即可被识别。 举例来说，如果 `longopts'
     为 ‘['foo', 'frob']’，则选项 ‘--fo’ 将匹配为 ‘--foo’，但 ‘--f’ 将不
     能得到唯一匹配，因此将引发 *note GetoptError: 21d2.。

     返回值由两个元素组成：第一个是 ‘(option, value)’ 对的列表；第二个是
     在去除该选项列表后余下的程序参数列表（这也就是 `args' 的尾部切片）
     。每个被返回的选项与值对的第一个元素是选项，短选项前缀一个连字符 (例
     如 ‘'-x'’)，长选项则前缀两个连字符 (例如 ‘'--long-option'’)，第二个
     元素是选项参数，如果选项不带参数则为空字符串。 列表中选项的排列顺序
     与它们被解析的顺序相同，因此允许多次出现。 长选项与短选项可以混用。

 -- 函式: getopt.gnu_getopt (args, shortopts, longopts=[])

     此函数与 *note getopt(): 85. 类似，区别在于它默认使用 GNU 风格的扫
     描模式。 这意味着选项和非选项参数可能会混在一起。 *note getopt():
     85. 函数将在遇到非选项参数时立即停止处理选项。

     如果选项字符串的第一个字符为 ‘'+'’，或者如果设置了环境变量
     ‘POSIXLY_CORRECT’，则选项处理会在遇到非选项参数时立即停止。

 -- 例外: getopt.GetoptError

     This is raised当参数列表中出现不可识别的选项或者当一个需要参数的选
     项未带参数时将引发此异常。 此异常的参数是一个指明错误原因的字符串。
     对于长选项，将一个参数传给不需要参数的选项也将导致引发此异常。
     ‘msg’ 和 ‘opt’ 属性会给出错误消息和关联的选项；如果没有关联到异常的
     特定选项，则 ‘opt’ 将为空字符串。

 -- 例外: getopt.error

     *note GetoptError: 21d2. 的别名；用于向后兼容。

一个仅使用 Unix 风格选项的例子:

     >>> 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', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
     >>> args
     ['a1', 'a2']

使用长选项名也同样容易:

     >>> 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', ''), ('--output-file', 'abc.def'), ('-x', '')]
     >>> args
     ['a1', 'a2']

在脚本中，典型的用法类似这样:

     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()

请注意通过 *note argparse: 5. 模块可以使用更少的代码并附带更详细的帮助与
错误消息生成等价的命令行接口:

     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 ..

也參考
......

模块 *note argparse: 5.

     替代的命令行选项和参数解析库。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/getopt.py


File: python.info,  Node: logging --- Python 的日志记录工具,  Next: logging config --- 日志记录配置,  Prev: getopt --- C 风格的命令行选项解析器,  Up: 通用操作系统服务

5.16.6 ‘logging’ — Python 的日志记录工具
----------------------------------------

`源代码：' Lib/logging/__init__.py(1)

Important
.........

此页面仅包含 API 参考信息。教程信息和更多高级用法的讨论，请参阅

   * *note 基础教程: c43.

   * *note 进阶教程: c44.

   * *note 日志操作手册: c45.

__________________________________________________________________

这个模块为应用与库实现了灵活的事件日志系统的函数与类。

使用标准库提供的 logging API 最主要的好处是，所有的 Python 模块都可能参
与日志输出，包括你自己的日志消息和第三方模块的日志消息。

这个模块提供许多强大而灵活的功能。如果对 logging 不太熟悉， 掌握它最好的
方式就是查看它对应的教程（详见右侧的链接）。

该模块定义的基础类和函数都列在下面。

   * 记录器暴露了应用程序代码直接使用的接口。

   * 处理器将日志记录（由记录器创建）发送到适当的目标。

   * 过滤器提供了更细粒度的功能，用于确定要输出的日志记录。

   * 格式器指定最终输出中日志记录的样式。

* Menu:

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

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/Lib/logging/__init__.py


File: python.info,  Node: 记录器对象,  Next: 日志级别,  Up: logging --- Python 的日志记录工具

5.16.6.1 记录器对象
...................

记录器有以下的属性和方法。注意 `永远' 不要直接实例化记录器，应当通过模块
级别的函数 ‘logging.getLogger(name)’ 。多次使用相同的名字调用 *note
getLogger(): 234. 会一直返回相同的 Logger 对象的引用。

‘name’ 一般是句点分割的层级值, 像‘‘foo.bar.baz‘‘ (尽管也可以只是普通的
‘foo’)。层次结构列表中位于下方的记录器是列表中较高位置的记录器的子级。例
如，有个名叫 ‘foo’ 的记录器，而名字是 ‘foo.bar’，‘foo.bar.baz’，和
‘foo.bam’ 的记录器都是 ‘foo’ 的子级。记录器的名字分级类似 Python 包的层
级，如果使用建议的结构 ‘logging.getLogger(__name__)’ 在每个模块的基础上
组织记录器，则与之完全相同。这是因为在模块里，‘__name__’ 是该模块在
Python 包命名空间中的名字。

 -- 類別: logging.Logger

      -- 屬性: propagate

          如果这个属性为真，记录到这个记录器的事件除了会发送到此记录器的
          所有处理程序外，还会传递给更高级别（祖先）记录器的处理器，此外
          任何关联到这个记录器的处理器。消息会直接传递给祖先记录器的处理
          器 —— 不考虑祖先记录器的级别和过滤器。

          如果为假，记录消息将不会传递给当前记录器的祖先记录器的处理器。

          Spelling it out with an example: If the propagate attribute of
          the logger named ‘A.B.C’ evaluates to true, any event logged
          to ‘A.B.C’ via a method call such as
          ‘logging.getLogger('A.B.C').error(...)’ will [subject to
          passing that logger’s level and filter settings] be passed in
          turn to any handlers attached to loggers named ‘A.B’, ‘A’ and
          the root logger, after first being passed to any handlers
          attached to ‘A.B.C’.  If any logger in the chain ‘A.B.C’,
          ‘A.B’, ‘A’ has its ‘propagate’ attribute set to false, then
          that is the last logger whose handlers are offered the event
          to handle, and propagation stops at that point.

          构造器将这个属性初始化为 ‘True’。

               備註: 如果将处理器附加到记录器 `和' 其一个或多个祖先记录
               器，它可能发出多次相同的记录。通常，不需要将处理器附加到
               一个以上的记录器上 —— 如果把它附加到记录器层次结构中最高
               的适当记录器上，则它将看到所有后代记录器记录的所有事件，
               前提是它们的传播设置保留为 ‘True’。仅将处理器附加到根记录
               器，通过传播来处理其余部分这种方案是比较常用的。

      -- 成員函式: setLevel (level)

          给记录器设置阈值为 `level' 。日志等级小于 `level' 会被忽略。严
          重性为 `level' 或更高的日志消息将由该记录器的任何一个或多个处
          理器发出，除非将处理器的级别设置为比 `level' 更高的级别。

          创建记录器时，级别默认设置为 ‘NOTSET’ （当记录器是根记录器时，
          将处理所有消息；如果记录器不是根记录器，则将委托给父级）。请注
          意，根记录器的默认级别为 ‘WARNING’ 。

          委派给父级的意思是如果记录器的级别设置为 NOTSET，将遍历其祖先
          记录器，直到找到级别不是 NOTSET 的记录器，或者到根记录器为止。

          如果发现某个父级的级别不是 NOTSET ，那么该父级的级别将被视为发
          起搜索的记录器的有效级别，并用于确定如何处理日志事件。

          如果搜索到达根记录器，并且其级别为 NOTSET，则将处理所有消息。
          否则，将使用根记录器的级别作为有效级别。

          参见 *note 日志级别: 21db. 级别列表。

          3.2 版更變: 现在 `level' 参数可以接受形如 ’INFO’ 的级别字符串
          表示形式，以代替形如 ‘INFO’ 的整数常量。 但是请注意，级别在内
          部存储为整数，并且 *note getEffectiveLevel(): 21dc. 和 *note
          isEnabledFor(): 21dd. 等方法的传入/返回值也为整数。

      -- 成員函式: isEnabledFor (level)

          指示此记录器是否将处理级别为 `level' 的消息。此方法首先检查由
          ‘logging.disable(level)’ 设置的模块级的级别，然后检查由 *note
          getEffectiveLevel(): 21dc. 确定的记录器的有效级别。

      -- 成員函式: getEffectiveLevel ()

          指示此记录器的有效级别。如果通过 *note setLevel(): 21da. 设置
          了除 ‘NOTSET’ 以外的值，则返回该值。否则，将层次结构遍历到根，
          直到找到除 ‘NOTSET’ 以外的其他值，然后返回该值。返回的值是一个
          整数，通常为 ‘logging.DEBUG’、 ‘logging.INFO’ 等等。

      -- 成員函式: getChild (suffix)

          返回由后缀确定的该记录器的后代记录器。 因此，
          ‘logging.getLogger('abc').getChild('def.ghi')’ 与
          ‘logging.getLogger('abc.def.ghi')’ 将返回相同的记录器。 这是一
          个便捷方法，当使用如 ‘__name__’ 而不是字符串字面值命名父记录器
          时很有用。

          3.2 版新加入.

      -- 成員函式: debug (msg, *args, **kwargs)

          在此记录器上记录 ‘DEBUG’ 级别的消息。 `msg' 是消息格式字符串，
          而 `args' 是用于字符串格式化操作合并到 `msg' 的参数。（注意，
          这里的意思是可以在格式字符串中使用关键字，及单个字典参数。）未
          提供 `args' 时，不会对 `msg' 执行 ％ 格式化操作。

          `kwargs' 中会检查四个关键字参数： `exc_info' ，`stack_info' ，
          `stacklevel' 和 `extra' 。

          如果 `exc_info' 的求值结果不为 false ，则它将异常信息添加到日
          志消息中。如果提供了异常元组（按照 *note sys.exc_info(): d27.
          返回的格式）或异常实例，则它将被使用；否则，调用 *note
          sys.exc_info(): d27. 以获取异常信息。

          第二个可选关键字参数是 `stack_info'，默认为 ‘False’。如果为
          True，则将堆栈信息添加到日志消息中，包括实际的日志调用。请注意
          ，这与通过指定 `exc_info' 显示的堆栈信息不同：前者是从堆栈底部
          到当前线程中的日志记录调用的堆栈帧，而后者是在搜索异常处理程序
          时，跟踪异常而打开的堆栈帧的信息。

          您可以独立于 `exc_info' 来指定 `stack_info'，例如，即使在未引
          发任何异常的情况下，也可以显示如何到达代码中的特定点。堆栈帧在
          标题行之后打印：

               Stack (most recent call last):

          这模仿了显示异常帧时所使用的 ‘Traceback (most recent call
          last):’ 。

          第三个可选关键字参数是 `stacklevel' ，默认为 ‘1’ 。如果大于 1
          ，则在为日志记录事件创建的 *note LogRecord: 9ec. 中计算行号和
          函数名时，将跳过相应数量的堆栈帧。可以在记录帮助器时使用它，以
          便记录的函数名称，文件名和行号不是帮助器的函数/方法的信息，而
          是其调用方的信息。此参数是 *note warnings: 12f. 模块中的同名等
          效参数。

          第四个关键字参数是 `extra' ，传递一个字典，该字典用于填充为日
          志记录事件创建的、带有用户自定义属性的 *note LogRecord: 9ec. 中
          的 __dict__ 。然后可以按照需求使用这些自定义属性。例如，可以将
          它们合并到已记录的消息中：

               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)

          输出类似于

               2006-02-08 22:20:02,165 192.168.0.1 fbloggs  Protocol problem: connection reset

          `extra' 中传入的字典的键不应与日志系统使用的键冲突。（有关日志
          系统使用哪些键的更多信息，请参见 *note Formatter: 21de. 的文档
          。）

          如果在已记录的消息中使用这些属性，则需要格外小心。例如，在上面
          的示例中，*note Formatter: 21de. 已设置了格式字符串，其在
          *note LogRecord: 9ec. 的属性字典中键值为 “clientip” 和 “user”。
          如果缺少这些内容，则将不会记录该消息，因为会引发字符串格式化异
          常。因此，在这种情况下，您始终需要使用 `extra' 字典传递这些键
          。

          尽管这可能很烦人，但此功能旨在用于特殊情况，例如在多个上下文中
          执行相同代码的多线程服务器，并且出现的有趣条件取决于此上下文（
          例如在上面的示例中就是远程客户端IP地址和已验证用户名）。在这种
          情况下，很可能将专门的 *note Formatter: 21de. 与特定的 *note
          Handler: 21df. 一起使用。

          3.2 版更變: 增加了 `stack_info' 参数。

          3.5 版更變: `exc_info' 参数现在可以接受异常实例。

          3.8 版更變: 增加了 `stacklevel' 参数。

      -- 成員函式: info (msg, *args, **kwargs)

          在此记录器上记录 ‘INFO’ 级别的消息。参数解释同 *note debug():
          21e1.。

      -- 成員函式: warning (msg, *args, **kwargs)

          在此记录器上记录 ‘WARNING’ 级别的消息。参数解释同 *note
          debug(): 21e1.。

               備註: 有一个功能上与 ‘warning’ 一致的方法 ‘warn’。由于
               ‘warn’ 已被弃用，请勿再用 —— 改为使用 ‘warning’。

      -- 成員函式: error (msg, *args, **kwargs)

          在此记录器上记录 ‘ERROR’ 级别的消息。参数解释同 *note debug():
          21e1.。

      -- 成員函式: critical (msg, *args, **kwargs)

          在此记录器上记录 ‘CRITICAL’ 级别的消息。参数解释同 *note
          debug(): 21e1.。

      -- 成員函式: log (level, msg, *args, **kwargs)

          在此记录器上记录 `level' 整数代表的级别的消息。参数解释同
          *note debug(): 21e1.。

      -- 成員函式: exception (msg, *args, **kwargs)

          在此记录器上记录 ‘ERROR’ 级别的消息。参数解释同 *note debug():
          21e1.。异常信息将添加到日志消息中。仅应从异常处理程序中调用此
          方法。

      -- 成員函式: addFilter (filter)

          将指定的过滤器 `filter' 添加到此记录器。

      -- 成員函式: removeFilter (filter)

          从此记录器中删除指定的过滤器 `filter'。

      -- 成員函式: filter (record)

          将此记录器的过滤器应用于记录，如果记录能被处理则返回 ‘True’。
          过滤器会被依次使用，直到其中一个返回假值为止。如果它们都不返回
          假值，则记录将被处理（传递给处理器）。如果返回任一为假值，则不
          会对该记录做进一步处理。

      -- 成員函式: addHandler (hdlr)

          将指定的处理器 `hdlr' 添加到此记录器。

      -- 成員函式: removeHandler (hdlr)

          从此记录器中删除指定的处理器 `hdlr'。

      -- 成員函式: findCaller (stack_info=False, stacklevel=1)

          查找调用源的文件名和行号，以 文件名，行号，函数名称和堆栈信息
          4元素元组的形式返回。堆栈信息将返回 ‘None’，除非 `stack_info'
          为 ‘True’。

          `stacklevel' 参数用于调用 *note debug(): 21e1. 和其他 API。如
          果大于 1，则多余部分将用于跳过堆栈帧，然后再确定要返回的值。当
          从帮助器/包装器代码调用日志记录 API 时，这通常很有用，以便事件
          日志中的信息不是来自帮助器/包装器代码，而是来自调用它的代码。

      -- 成員函式: handle (record)

          通过将记录传递给与此记录器及其祖先关联的所有处理器来处理（直到
          某个 `propagate' 值为 false）。此方法用于从套接字接收的未序列
          化的以及在本地创建的记录。使用 *note filter(): 21e6. 进行记录
          器级别过滤。

      -- 成員函式: makeRecord (name, level, fn, lno, msg, args,
               exc_info, func=None, extra=None, sinfo=None)

          这是一种工厂方法，可以在子类中对其进行重写以创建专门的 *note
          LogRecord: 9ec. 实例。

      -- 成員函式: hasHandlers ()

          检查此记录器是否配置了任何处理器。通过在此记录器及其记录器层次
          结构中的父级中查找处理器完成此操作。如果找到处理器则返回
          ‘True’，否则返回 ‘False’。只要找到 “propagate” 属性设置为假值
          的记录器，该方法就会停止搜索层次结构 —— 其将是最后一个检查处理
          器是否存在的记录器。

          3.2 版新加入.

     3.7 版更變: 现在可以对处理器进行序列化和反序列化。


File: python.info,  Node: 日志级别,  Next: 处理器对象,  Prev: 记录器对象,  Up: logging --- Python 的日志记录工具

5.16.6.2 日志级别
.................

日志记录级别的数值在下表中给出。如果你想要定义自己的级别，并且需要它们具
有相对于预定义级别的特定值，那么这你可能对以下内容感兴趣。如果你定义具有
相同数值的级别，它将覆盖预定义的值；预定义的名称将失效。

级别               数值
                   
---------------------------------------
                   
‘CRITICAL’         50
                   
                   
‘ERROR’            40
                   
                   
‘WARNING’          30
                   
                   
‘INFO’             20
                   
                   
‘DEBUG’            10
                   
                   
‘NOTSET’           0
                   


File: python.info,  Node: 处理器对象,  Next: 格式器对象,  Prev: 日志级别,  Up: logging --- Python 的日志记录工具

5.16.6.3 处理器对象
...................

Handler 有以下属性和方法。注意不要直接实例化 *note Handler: 21df. ；这个
类用来派生其他更有用的子类。但是，子类的 *note __init__(): e23. 方法需要
调用 *note Handler.__init__(): 21f0. 。

 -- 類別: logging.Handler

      -- 成員函式: __init__ (level=NOTSET)

          初始化 *note Handler: 21df. 实例时，需要设置它的级别，将过滤列
          表置为空，并且创建锁（通过 *note createLock(): 21f1. ）来序列
          化对 I/O 的访问。

      -- 成員函式: createLock ()

          初始化一个线程锁，用来序列化对底层的 I/O 功能的访问，底层的
          I/O 功能可能不是线程安全的。

      -- 成員函式: acquire ()

          获取由 *note createLock(): 21f1. 创建的线程锁。

      -- 成員函式: release ()

          释放由 *note acquire(): 21f2. 获取的线程锁。

      -- 成員函式: setLevel (level)

          给处理器设置阈值为 `level' 。日志级别小于 `level' 将被忽略。创
          建处理器时，日志级别被设置为 ‘NOTSET’ （所有的消息都会被处理）
          。

          参见 *note 日志级别: 21db. 级别列表。

          3.2 版更變: `level' 形参现在接受像 ’INFO’ 这样的字符串形式的级
          别表达方式，也可以使用像 ‘INFO’ 这样的整数常量。

      -- 成員函式: setFormatter (fmt)

          将此处理器的 *note Formatter: 21de. 设置为 `fmt'。

      -- 成員函式: addFilter (filter)

          将指定的过滤器 `filter' 添加到此处理器。

      -- 成員函式: removeFilter (filter)

          从此处理器中删除指定的过滤器 `filter' 。

      -- 成員函式: filter (record)

          将此处理器的过滤器应用于记录，在要处理记录时返回 ‘True’ 。依次
          查询过滤器，直到其中一个返回假值为止。如果它们都不返回假值，则
          将发出记录。如果返回一个假值，则处理器将不会发出记录。

      -- 成員函式: flush ()

          确保所有日志记录从缓存输出。此版本不执行任何操作，并且应由子类
          实现。

      -- 成員函式: close ()

          回收处理器使用的所有资源。此版本不输出，但从内部处理器列表中删
          除处理器，内部处理器在 *note shutdown(): 21fb. 被调用时关闭 。
          子类应确保从重写的 *note close(): 21fa. 方法中调用此方法。

      -- 成員函式: handle (record)

          经已添加到处理器的过滤器过滤后，有条件地发出指定的日志记录。用
          获取/释放 I/O 线程锁包装了记录的实际发出行为。

      -- 成員函式: handleError (record)

          调用 *note emit(): 21fe. 期间遇到异常时，应从处理器中调用此方
          法。如果模块级属性 ‘raiseExceptions’ 是 ‘False’，则异常将被静
          默忽略。这是大多数情况下日志系统需要的 —— 大多数用户不会关心日
          志系统中的错误，他们对应用程序错误更感兴趣。但是，你可以根据需
          要将其替换为自定义处理器。指定的记录是发生异常时正在处理的记录
          。（‘raiseExceptions’ 的默认值是 ‘True’，因为这在开发过程中是
          比较有用的）。

      -- 成員函式: format (record)

          如果设置了格式器则用其对记录进行格式化。否则，使用模块的默认格
          式器。

      -- 成員函式: emit (record)

          执行实际记录给定日志记录所需的操作。这个版本应由子类实现，因此
          这里直接引发 *note NotImplementedError: 704. 异常。

有关作为标准随附的处理器列表，请参见 *note logging.handlers: ac.。


File: python.info,  Node: 格式器对象,  Next: 过滤器对象,  Prev: 处理器对象,  Up: logging --- Python 的日志记录工具

5.16.6.4 格式器对象
...................

*note Formatter: 21de. 对象拥有以下的属性和方法。一般情况下，它们负责将
*note LogRecord: 9ec. 转换为可由人或外部系统解释的字符串。基础的 *note
Formatter: 21de. 允许指定格式字符串。如果未提供任何值，则使用默认值
‘'%(message)s'’ ，它仅将消息包括在日志记录调用中。要在格式化输出中包含其
他信息（如时间戳），请阅读下文。

格式器可以使用格式化字符串来初始化，该字符串利用 *note LogRecord: 9ec. 的
属性 —— 例如上述默认值，用户的消息和参数预先格式化为 *note LogRecord:
9ec. 的 `message' 属性后被使用。此格式字符串包含标准的 Python %-s 样式映
射键。有关字符串格式的更多信息，请参见 *note printf 风格的字符串格式化:
1359.。

*note LogRecord 属性: 2202. 一节中给出了 *note LogRecord: 9ec. 中有用的
映射键。

 -- 類別: logging.Formatter (fmt=None, datefmt=None, style='%',
          validate=True)

     返回 *note Formatter: 21de. 类的新实例。实例将使用整个消息的格式字
     符串以及消息的日期/时间部分的格式字符串进行初始化。如果未指定 `fmt'
     ，则使用 ‘'%(message)s'’。如果未指定 `datefmt'，则使用 *note
     formatTime(): 2203. 文档中描述的格式。

     `style' 形参可以是 ’%’, ’{’ 或 ’$’ 之一，它决定格式字符串将如何与数
     据进行合并：使用 %-formatting, *note str.format(): 5d4. 或是 *note
     string.Template: 4f0.。 这仅适用于格式字符串 `fmt' (例如
     ‘'%(message)s'’ 或 ‘{message}’)，不适用于传递给 ‘Logger.debug’ 的实
     际日志消息等；请参阅 *note 生效于整个应用程序的格式化样式: 2204. 了
     解有关在日志消息中使用 {- 和 $-formatting 的更多详情。

     3.2 版更變: 加入了 `style' 形参。

     3.8 版更變: 加入*validate* 参数。不正确或不匹配的样式和格式将引发
     ‘ValueError’ 错误。例如: ‘logging.Formatter('%(asctime)s -
     %(message)s', style='{')’。

      -- 成員函式: format (record)

          记录的属性字典用作字符串格式化操作的参数。返回结果字符串。在格
          式化字典之前，需要执行几个准备步骤。 使用 `msg' % `args' 计算
          记录的 `message' 属性。如果格式化字符串包含 ‘'(asctime)'’，则
          调用 *note formatTime(): 2203. 来格式化事件时间。如果有异常信
          息，则使用 *note formatException(): 2206. 将其格式化并附加到消
          息中。请注意，格式化的异常信息缓存在属性 `exc_text' 中。这很有
          用，因为可以对异常信息进行序列化并通过网络发送，但是如果您有不
          止一个定制了异常信息格式的 *note Formatter: 21de. 子类，则应格
          外小心。在这种情况下，您必须在格式器完成格式化后清除缓存的值，
          以便下一个处理事件的格式器不使用缓存的值，而是重新计算它。

          如果栈信息可用，它将被添加在异常信息之后，如有必要请使用 *note
          formatStack(): 2207. 来转换它。

      -- 成員函式: formatTime (record, datefmt=None)

          此方法应由想要使用格式化时间的格式器中的 *note format(): 5d5.
          调用。可以在格式器中重写此方法以提供任何特定要求，但是基本行为
          如下：如果指定了 `datefmt' （字符串），则将其用于 *note
          time.strftime(): c37. 来格式化记录的创建时间。否则，使用格式
          ’%Y-%m-%d %H:%M:%S,uuu’，其中 uuu 部分是毫秒值，其他字母根据
          *note time.strftime(): c37. 文档。这种时间格式的示例为
          ‘2003-01-23 00:29:50,411’。返回结果字符串。

          此函数使用一个用户可配置函数将创建时间转换为元组。 默认情况下
          ，使用 *note time.localtime(): 1080.；要为特定格式化程序实例更
          改此项，请将实例的 ‘converter’ 属性设为具有与 *note
          time.localtime(): 1080. 或 *note time.gmtime(): c11. 相同签名
          的函数。 要为所有格式化程序更改此项，例如当你希望所有日志时间
          都显示为 GMT，请在 ‘Formatter’ 类中设置 ‘converter’ 属性。

          3.3 版更變: 在之前版本中，默认格式是被硬编码的，例如这个例子:
          ‘2010-09-06 22:38:15,292’ 其中逗号之前的部分由 strptime 格式字
          符串 (‘'%Y-%m-%d %H:%M:%S'’) 处理，而逗号之后的部分为毫秒值。
          因为 strptime 没有表示毫秒的占位符，毫秒值使用了另外的格式字符
          串来添加 ‘'%s,%03d'’ — 这两个格式字符串代码都是硬编码在该方法
          中的。 经过修改，这些字符串被定义为类层级的属性，当需要时可以
          在实例层级上被重载。 属性的名称为 ‘default_time_format’ (用于
          strptime 格式字符串) 和 ‘default_msec_format’ (用于添加毫秒值
          )。

          3.9 版更變: ‘default_msec_format’ 可以为 ‘None’。

      -- 成員函式: formatException (exc_info)

          将指定的异常信息（由 *note sys.exc_info(): d27. 返回的标准异常
          元组）格式化为字符串。默认实现只是使用了 *note
          traceback.print_exception(): 2208.。 结果字符串将被返回。

      -- 成員函式: formatStack (stack_info)

          将指定的堆栈信息（由 *note traceback.print_stack(): 869. 返回
          的字符串，但移除末尾的换行符）格式化为字符串。 默认实现只是返
          回输入值。


File: python.info,  Node: 过滤器对象,  Next: LogRecord 属性,  Prev: 格式器对象,  Up: logging --- Python 的日志记录工具

5.16.6.5 过滤器对象
...................

‘Filters’ 可被 ‘Handlers’ 和 ‘Loggers’ 用来实现比按层级提供更复杂的过滤
操作。 基本过滤器类只允许低于日志记录器层级结构中低于特定层级的事件。 例
如，一个用 ’A.B’ 初始化的过滤器将允许 ’A.B’, ’A.B.C’, ’A.B.C.D’, ’A.B.D’
等日志记录器所记录的事件。 但 ’A.BB’, ’B.A.B’ 等则不允许。 如果用空字符
串初始化，则所有事件都会通过。

 -- 類別: logging.Filter (name='')

     返回一个 *note Filter: c48. 类的实例。 如果指定了 `name'，则它将被
     用来为日志记录器命名，该类及其子类将通过该过滤器允许指定事件通过。
     如果 `name' 为空字符串，则允许所有事件通过。

      -- 成員函式: filter (record)

          是否要记录指定的记录？返回零表示否，非零表示是。如果认为合适，
          则可以通过此方法就地修改记录。

请注意关联到处理器的过滤器会在事件由处理器发出之前被查询，而关联到日志记
录器的过滤器则会在有事件被记录的的任何时候（使用 *note debug(): 21e1,
*note info(): 220c. 等等）在将事件发送给处理器之前被查询。 这意味着由后
代日志记录器生成的事件将不会被父代日志记录器的过滤器设置所过滤，除非该过
滤器也已被应用于后代日志记录器。

你实际上不需要子类化 ‘Filter’ ：你可以传入任何一个包含有相同语义的
‘filter’ 方法的实例。

3.2 版更變: 你不需要创建专门的 ‘Filter’ 类，或使用具有 ‘filter’ 方法的其
他类：你可以使用一个函数（或其他可调用对象）作为过滤器。 过滤逻辑将检查
过滤器对象是否具有 ‘filter’ 属性：如果有，就会将它当作是 ‘Filter’ 并调用
它的 *note filter(): 220b. 方法。 在其他情况下，则会将它当作是可调用对象
并将记录作为唯一的形参进行调用。 返回值应当与 *note filter(): 220b. 的返
回值相一致。

尽管过滤器主要被用来构造比层级更复杂的规则以过滤记录，但它们可以查看由它
们关联的处理器或记录器所处理的每条记录：当你想要执行统计特定记录器或处理
器共处理了多少条记录，或是在所处理的 *note LogRecord: 9ec. 中添加、修改
或移除属性这样的任务时该特性将很有用处。 显然改变 LogRecord 时需要相当小
心，但将上下文信息注入日志确实是被允许的 (参见 *note 利用 Filter
传递上下文信息: 220d.)。


File: python.info,  Node: LogRecord 属性,  Next: LogRecord 属性<2>,  Prev: 过滤器对象,  Up: logging --- Python 的日志记录工具

5.16.6.6 LogRecord 属性
.......................

*note LogRecord: 9ec. 实例是每当有日志被记录时由 *note Logger: 4ad. 自动
创建的，并且可通过 *note makeLogRecord(): 2210. 手动创建（例如根据从网络
接收的已封存事件创建）。

 -- 類別: logging.LogRecord (name, level, pathname, lineno, msg, args,
          exc_info, func=None, sinfo=None)

     包含与被记录的事件相关的所有信息。

     主要信息是在 ‘msg’ 和 ‘args’ 中传递的，它们使用 ‘msg % args’ 组合到
     一起以创建记录的 ‘message’ 字段。


     參數:

        * ‘name’ – 用于记录由此 LogRecord 所表示事件的记录器名称。 请注
          意此名称将始终为该值，即使它可能是由附加到不同（祖先）日志记录
          器的处理器所发出的。

        * ‘level’ – 以数字表示的日志记录事件层级（如 DEBUG, INFO 等）。
          请注意这会转换为 LogRecord 的 `两个' 属性: ‘levelno’ 为数字值
          而 ‘levelname’ 为对应的层级名称。

        * ‘pathname’ – 进行日志记录调用的文件的完整路径名。

        * ‘lineno’ – 记录调用所在源文件中的行号。

        * ‘msg’ – 事件描述消息，可能为带有可变数据占位符的格式字符串。

        * ‘args’ – 要合并到 `msg' 参数以获得事件描述的可变数据。

        * ‘exc_info’ – 包含当前异常信息的异常元组，或者如果没有可用异常
          信息则为 ‘None’。

        * ‘func’ – 发起调用日志记录调用的函数或方法名称。

        * ‘sinfo’ – 一个文本字符串，表示当前线程中从堆栈底部直到日志记录
          调用的堆栈信息。

      -- 成員函式: getMessage ()

          在将 *note LogRecord: 9ec. 实例与任何用户提供的参数合并之后，
          返回此实例的消息。 如果用户提供给日志记录调用的消息参数不是字
          符串，则会在其上调用 *note str(): 205. 以将它转换为字符串。 此
          方法允许将用户定义的类用作消息，类的 ‘__str__’ 方法可以返回要
          使用的实际格式字符串。

     3.2 版更變: 通过提供用于创建记录的工厂方法已使得 *note LogRecord:
     9ec. 的创建更易于配置。 该工厂方法可使用 *note
     getLogRecordFactory(): 2212. 和 *note setLogRecordFactory(): 2213.
     （在此可查看工厂方法的签名）来设置。

     在创建时可使用此功能将你自己的值注入 *note LogRecord: 9ec.。 你可以
     使用以下模式:

          old_factory = logging.getLogRecordFactory()

          def record_factory(*args, **kwargs):
              record = old_factory(*args, **kwargs)
              record.custom_attribute = 0xdecafbad
              return record

          logging.setLogRecordFactory(record_factory)

     通过此模式，多个工厂方法可以被链接起来，并且只要它们不重载彼此的属
     性或是在无意中覆盖了上面列出的标准属性，就不会发生意外。


File: python.info,  Node: LogRecord 属性<2>,  Next: LoggerAdapter 对象,  Prev: LogRecord 属性,  Up: logging --- Python 的日志记录工具

5.16.6.7 LogRecord 属性
.......................

LogRecord 具有许多属性，它们大多数来自于传递给构造器的形参。 （请注意
LogRecord 构造器形参与 LogRecord 属性的名称并不总是完全彼此对应的。） 这
些属性可被用于将来自记录的数据合并到格式字符串中。 下面的表格（按字母顺
序）列出了属性名称、它们的含义以及相应的 %-style 格式字符串内占位符。

如果是使用 {}-格式化（*note str.format(): 5d4.），你可以将 ‘{attrname}’
用作格式字符串内的占位符。 如果是使用 $-格式化（*note string.Template:
4f0.），则会使用 ‘${attrname}’ 的形式。 当然在这两种情况下，都应当将
‘attrname’ 替换为你想要使用的实际属性名称。

在 {}-格式化的情况下，你可以在属性名称之后放置指定的格式化旗标，并用冒号
来分隔两者。 例如，占位符 ‘{msecs:03d}’ 会将毫秒值 ‘4’ 格式化为 ‘004’。
请参看 *note str.format(): 5d4. 文档了解你所能使用的选项的完整细节。

属性名称             格式                          描述
                                                   
-------------------------------------------------------------------------------------------------------
                                                   
args                 此属性不需要用户进行格式化    合并到 ‘msg’ 以产生 ‘message’ 的包含参数的元组，
                     。                            或是其中的值将被用于合并的字典（当只有一个参数且
                                                   其类型为字典时）。
                                                   
                                                   
asctime              ‘%(asctime)s’                 表示 *note LogRecord: 9ec. 何时被创建的供人查看时
                                                   间值。 默认形式为 ’2003-07-08 16:49:45,896’ （逗
                                                   号之后的数字为时间的毫秒部分）。
                                                   
                                                   
created              ‘%(created)f’                 *note LogRecord: 9ec. 被创建的时间（即
                                                   *note time.time(): 42d. 的返回值）。
                                                   
                                                   
exc_info             此属性不需要用户进行格式化    异常元组（例如 ‘sys.exc_info’）或者如未发生异常则
                     。                            为 ‘None’。
                                                   
                                                   
filename             ‘%(filename)s’                ‘pathname’ 的文件名部分。
                                                   
                                                   
funcName             ‘%(funcName)s’                函数名包括调用日志记录.
                                                   
                                                   
levelname            ‘%(levelname)s’               消息文本记录级别（‘'DEBUG'’，‘'INFO'’，
                                                   ‘'WARNING'’，‘'ERROR'’，‘'CRITICAL'’）。
                                                   
                                                   
levelno              ‘%(levelno)s’                 消息数字的记录级别 (‘DEBUG’, ‘INFO’, ‘WARNING’,
                                                   ‘ERROR’, ‘CRITICAL’).
                                                   
                                                   
lineno               ‘%(lineno)d’                  发出日志记录调用所在的源行号（如果可用）。
                                                   
                                                   
message              ‘%(message)s’                 记入日志的消息，即 ‘msg % args’ 的结果。 这是在发
                                                   起调用 *note Formatter.format(): 2205. 时设置的。
                                                   
                                                   
module               ‘%(module)s’                  模块 (‘filename’ 的名称部分)。
                                                   
                                                   
msecs                ‘%(msecs)d’                   *note LogRecord: 9ec. 被创建的时间的毫秒部分。
                                                   
                                                   
msg                  此属性不需要用户进行格式化    在原始日志记录调用中传入的格式字符串。 与 ‘args’
                     。                            合并以产生 ‘message’，或是一个任意对象 (参见
                                                   *note 使用任意对象作为消息: 2215.)。
                                                   
                                                   
name                 ‘%(name)s’                    用于记录调用的日志记录器名称。
                                                   
                                                   
pathname             ‘%(pathname)s’                发出日志记录调用的源文件的完整路径名（如果可用）
                                                   。
                                                   
                                                   
process              ‘%(process)d’                 进程ID（如果可用）
                                                   
                                                   
processName          ‘%(processName)s’             进程名（如果可用）
                                                   
                                                   
relativeCreated      ‘%(relativeCreated)d’         以毫秒数表示的 LogRecord 被创建的时间，即相对于
                                                   logging 模块被加载时间的差值。
                                                   
                                                   
stack_info           此属性不需要用户进行格式化    当前线程中从堆栈底部起向上直到包括日志记录调用并
                     。                            引发创建当前记录堆栈帧创建的堆栈帧信息（如果可用
                                                   ）。
                                                   
                                                   
thread               ‘%(thread)d’                  线程ID（如果可用）
                                                   
                                                   
threadName           ‘%(threadName)s’              线程名（如果可用）
                                                   

3.1 版更變: 添加了 `processName'


File: python.info,  Node: LoggerAdapter 对象,  Next: 线程安全,  Prev: LogRecord 属性<2>,  Up: logging --- Python 的日志记录工具

5.16.6.8 LoggerAdapter 对象
...........................

*note LoggerAdapter: d54. 实例会被用来方便地将上下文信息传入日志记录调用
。 要获取用法示例，请参阅 *note 添加上下文信息到你的日志记录输出: 2218.
部分。

 -- 類別: logging.LoggerAdapter (logger, extra)

     返回一个 *note LoggerAdapter: d54. 的实例，该实例的初始化使用了下层
     的 *note Logger: 4ad. 实例和一个字典类对象。

      -- 成員函式: process (msg, kwargs)

          修改传递给日志记录调用的消息和/或关键字参数以便插入上下文信息
          。 此实现接受以 `extra' 形式传给构造器的对象并使用 ’extra’ 键
          名将其加入 `kwargs'。 返回值为一个 (`msg', `kwargs') 元组，其
          包含（可能经过修改的）传入参数。

在上述方法之外，*note LoggerAdapter: d54. 还支持 *note Logger: 4ad. 的下
列方法: *note debug(): 801, *note info(): 21e0.，*note warning(): 21e2.，
*note error(): 21e3, *note exception(): 7ff, *note critical(): 800.，
*note log(): 7fe.，*note isEnabledFor(): 21dd.，*note
getEffectiveLevel(): 21dc.，*note setLevel(): 21da. 以及 *note
hasHandlers(): 21ec.。 这些方法具有与它们在 *note Logger: 4ad. 中的对应
方法相同的签名，因此你可以互换使用这两种类型的实例。

3.2 版更變: *note isEnabledFor(): 21dd, *note getEffectiveLevel(): 21dc,
*note setLevel(): 21da. 和 *note hasHandlers(): 21ec. 方法已被添加到
*note LoggerAdapter: d54.。 这些方法会委托给下层的日志记录器。

3.6 版更變: 增加了 ‘manager’ 属性和 ‘_log()’ 方法，它们会委托给下层的日
志记录器并允许适配器嵌套。


File: python.info,  Node: 线程安全,  Next: 模块级函数,  Prev: LoggerAdapter 对象,  Up: logging --- Python 的日志记录工具

5.16.6.9 线程安全
.................

logging 模块的目标是使客户端不必执行任何特殊操作即可确保线程安全。 它通
过使用线程锁来达成这个目标；用一个锁来序列化对模块共享数据的访问，并且每
个处理程序也会创建一个锁来序列化对其下层 I/O 的访问。

如果你要使用 *note signal: ea. 模块来实现异步信号处理程序，则可能无法在
这些处理程序中使用 logging。 这是因为 *note threading: 10b. 模块中的锁实
现并非总是可重入的，所以无法从此类信号处理程序发起调用。


File: python.info,  Node: 模块级函数,  Next: 模块级属性,  Prev: 线程安全,  Up: logging --- Python 的日志记录工具

5.16.6.10 模块级函数
....................

在上述的类之外，还有一些模块级的函数。

 -- 函式: logging.getLogger (name=None)

     返回具有指定 name 的日志记录器，或者当 name 为 ‘None’ 时返回层级结
     构中的根日志记录器。 如果指定了 name，它通常是以点号分隔的带层级结
     构的名称，如 `’a’'、`’a.b’' 或 `’a.b.c.d’'。 这些名称的选择完全取决
     于使用 logging 的开发者。

     所有用给定的 name 对该函数的调用都将返回相同的日志记录器实例。 这意
     味着日志记录器实例不需要在应用的各部分间传递。

 -- 函式: logging.getLoggerClass ()

     返回标准的 *note Logger: 4ad. 类，或是最近传给 *note
     setLoggerClass(): 221d. 的类。 此函数可以从一个新的类定义中调用，以
     确保安装自定义的 *note Logger: 4ad. 类不会撤销其他代码已经应用的自
     定义操作。 例如:

          class MyLogger(logging.getLoggerClass()):
              # ... override behaviour here

 -- 函式: logging.getLogRecordFactory ()

     返回一个被用来创建 *note LogRecord: 9ec. 的可调用对象。

     3.2 版新加入: 此函数与 *note setLogRecordFactory(): 2213. 一起提供
     ，以允许开发者对表示日志记录事件的 *note LogRecord: 9ec. 的构造有更
     好的控制。

     请参阅 *note setLogRecordFactory(): 2213. 了解有关如何调用该工厂方
     法的更多信息。

 -- 函式: logging.debug (msg, *args, **kwargs)

     在根日志记录器上记录一条 ‘DEBUG’ 级别的消息。 `msg' 是消息格式字符
     串，而 `args' 是要使用字符串格式化运算符合并到 `msg' 的参数。 （请
     注意这意味着你可以在格式字符串中使用关键字以及单个字典参数。）

     在 `kwargs' 中有三个关键字参数会被检查: `exc_info' 参数如果不为假值
     则会将异常信息添加到日志记录消息。 如果提供了异常元组（为 *note
     sys.exc_info(): d27. 的返回值格式）或异常实例则它会被使用；在其他情
     况下，会调用 *note sys.exc_info(): d27. 以获取异常信息。

     第二个可选关键字参数是 `stack_info'，默认为 ‘False’。如果为 True，
     则将堆栈信息添加到日志消息中，包括实际的日志调用。请注意，这与通过
     指定 `exc_info' 显示的堆栈信息不同：前者是从堆栈底部到当前线程中的
     日志记录调用的堆栈帧，而后者是在搜索异常处理程序时，跟踪异常而打开
     的堆栈帧的信息。

     您可以独立于 `exc_info' 来指定 `stack_info'，例如，即使在未引发任何
     异常的情况下，也可以显示如何到达代码中的特定点。堆栈帧在标题行之后
     打印：

          Stack (most recent call last):

     这模仿了显示异常帧时所使用的 ‘Traceback (most recent call last):’ 。

     第三个可选关键字参数是 `extra'，它可被用来传递一个字典，该字典会被
     用来填充为日志记录事件创建并附带用户自定义属性的 LogRecord 的
     __dict__。 之后将可按你的需要使用这些自定义属性。 例如，可以将它们
     合并到已记录的消息中。 举例来说:

          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)

     应当会打印出这样的内容:

          2006-02-08 22:20:02,165 192.168.0.1 fbloggs  Protocol problem: connection reset

     `extra' 中传入的字典的键不应与日志系统使用的键冲突。（有关日志系统
     使用哪些键的更多信息，请参见 *note Formatter: 21de. 的文档。）

     如果你选择在已记录的消息中使用这些属性，则需要格外小心。 例如在上面
     的示例中，*note Formatter: 21de. 已设置了格式字符串，其在 LogRecord
     的属性字典中应有 ’clientip’ 和 ’user’。 如果缺少这些属性，消息将不
     被记录，因为会引发字符串格式化异常，你始终需要传入带有这些键的
     `extra' 字典。

     尽管这可能很烦人，但此功能旨在用于特殊情况，例如在多个上下文中执行
     相同代码的多线程服务器，并且出现的有趣条件取决于此上下文（例如在上
     面的示例中就是远程客户端IP地址和已验证用户名）。在这种情况下，很可
     能将专门的 *note Formatter: 21de. 与特定的 *note Handler: 21df. 一
     起使用。

     3.2 版更變: 增加了 `stack_info' 参数。

 -- 函式: logging.info (msg, *args, **kwargs)

     在根日志记录器上记录一条 ‘INFO’ 级别的消息。 参数解释同 *note
     debug(): 21e1.。

 -- 函式: logging.warning (msg, *args, **kwargs)

     在根日志记录器上记录一条 ‘WARNING’ 级别的消息。 参数解释同 *note
     debug(): 21e1.。

          備註: 有一个已过时方法 ‘warn’ 其功能与 ‘warning’ 一致。 由于
          ‘warn’ 已被弃用，请不要使用它 —— 而是改用 ‘warning’。

 -- 函式: logging.error (msg, *args, **kwargs)

     在根日志记录器上记录一条 ‘ERROR’ 级别的消息。 参数解释同 *note
     debug(): 21e1.。

 -- 函式: logging.critical (msg, *args, **kwargs)

     在根日志记录器上记录一条 ‘CRITICAL’ 级别的消息。 参数解释同 *note
     debug(): 21e1.。

 -- 函式: logging.exception (msg, *args, **kwargs)

     在根日志记录器上记录一条 ‘ERROR’ 级别的消息。 参数解释同 *note
     debug(): 21e1.。 异常信息将被添加到日志消息中。 此函数应当仅从异常
     处理程序中调用。

 -- 函式: logging.log (level, msg, *args, **kwargs)

     在根日志记录器上记录一条 `level' 级别的消息。 其他参数解释同 *note
     debug(): 21e1.。

          備註: 上述模块级的便捷函数均委托给根日志记录器，它们会调用
          *note basicConfig(): 311. 以确保至少有一个处理器可用。 因此，
          在 Python 2.7.1 和 3.2 之前的版本中，除非线程启动 `之前' 已向
          根日志记录器添加了至少一个处理器，它们 `不应' 在线程中使用。 在
          较早的 Python 版本中，由于 *note basicConfig(): 311. 中存在线
          程安全性的不足，这（在少数情况下）可能导致处理器被多次加入根日
          志记录器，这会导致同一事件出现多条消息。

 -- 函式: logging.disable (level=CRITICAL)

     为所有日志记录器提供重载的级别 `level'，其优先级高于日志记录器自己
     的级别。 当需要临时限制整个应用程序中的日志记录输出时，此功能会很有
     用。 它的效果是禁用所有重要程度为 `level' 及以下的日志记录调用，因
     此如果你附带 INFO 值调用它，则所有 INFO 和 DEBUG 事件就会被丢弃，而
     重要程度为 WARNING 以及上的事件将根据日志记录器的当前有效级别来处理
     。 如果 ‘logging.disable(logging.NOTSET)’ 被调用，它将移除这个重载
     的级别，因此日志记录输出会再次取决于单个日志记录器的有效级别。

     请注意如果你定义了任何高于 ‘CRITICAL’ 的自定义日志级别（并不建议这
     样做），你就将无法沿用 `level' 形参的默认值，而必须显式地提供适当的
     值。

     3.7 版更變: `level' 形参默认级别为 ‘CRITICAL’。 请参阅 bpo-28524(1)
     了解此项改变的更多细节。

 -- 函式: logging.addLevelName (level, levelName)

     在一个内部字典中关联级别 `level' 与文本 `levelName'，该字典会被用来
     将数字级别映射为文本表示形式，例如在 *note Formatter: 21de. 格式化
     消息的时候。 此函数也可被用来定义你自己的级别。 唯一的限制是自定义
     的所有级别必须使用此函数来注册，级别值必须为正整数并且其应随严重程
     度而递增。

          備註: 如果你考虑要定义你自己的级别，请参阅 *note 自定义级别:
          2224. 部分。

 -- 函式: logging.getLevelName (level)

     返回日志记录级别 `level' 的字符串表示。

     如果 `level' 为预定义的级别 ‘CRITICAL’, ‘ERROR’, ‘WARNING’, ‘INFO’
     或 ‘DEBUG’ 之一则你会得到相应的字符串。 如果你使用 *note
     addLevelName(): 2223. 将级别关联到名称则返回你为 `level' 所关联的名
     称。 如果传入了与已定义级别相对应的数字值，则返回对应的字符串表示。

     `level' 形参也接受级别的字符串表示例如 ’INFO’。 在这种情况下，此函
     数将返回级别所对应的数字值。

     如果未传入可匹配的数字或字符串值，则返回字符串 ’Level %s’ % level。

          備註: 级别在内部以整数表示（因为它们在日志记录逻辑中需要进行比
          较）。 此函数被用于在整数级别与通过 ‘%(levelname)s’ 格式描述符
          方式在格式化日志输出中显示的级别名称之间进行相互的转换 (参见
          *note LogRecord 属性: 2202.)。

     3.4 版更變: 在早于 3.4 的 Python 版本中，此函数也可传入一个字符串形
     式的级别名称，并将返回对应的级别数字值。 此未记入文档的行为被视为是
     一个错误，并在 Python 3.4 中被移除，但又在 3.4.2 中被恢复以保持向下
     兼容性。

 -- 函式: logging.makeLogRecord (attrdict)

     创建并返回一个新的 *note LogRecord: 9ec. 实例，实例属性由
     `attrdict' 定义。 此函数适用于接受一个通过套接字传输的封存好的
     *note LogRecord: 9ec. 属性字典，并在接收端将其重建为一个 *note
     LogRecord: 9ec. 实例。

 -- 函式: logging.basicConfig (**kwargs)

     通过使用默认的 *note Formatter: 21de. 创建一个 *note StreamHandler:
     c46. 并将其加入根日志记录器来为日志记录系统执行基本配置。 如果没有
     为根日志记录器定义处理器则 *note debug(): 21e1, *note info(): 220c,
     *note warning(): 221e, *note error(): 221f. 和 *note critical():
     2220. 等函数将自动调用 *note basicConfig(): 311.。

     如果根日志记录器已配置了处理器则此函数将不执行任何操作，除非关键字
     参数 `force' 被设为 ‘True’。

          備註: 此函数应当在其他线程启动之前从主线程被调用。 在 2.7.1 和
          3.2 之前的 Python 版本中，如果此函数从多个线程被调用，一个处理
          器（在极少的情况下）有可能被多次加入根日志记录器，导致非预期的
          结果例如日志中的消息出现重复。

     支持以下关键字参数。

     格式               描述
                        
     ---------------------------------------------------------------------
                        
     `filename'         使用指定的文件名而不是 StreamHandler 创建
                        FileHandler。
                        
                        
     `filemode'         如果指定了 `filename'，则用此 *note 模式: 172c.
                        打开该文件。 默认模式为 ‘'a'’。
                        
                        
     `format'           使用指定的格式字符串作为处理器。 默认为属性以冒
                        号分隔的 ‘levelname’, ‘name’ 和 ‘message’。
                        
                        
     `datefmt'          使用指定的日期/时间格式，与
                        *note time.strftime(): c37. 所接受的格式相同。
                        
                        
     `style'            如果指定了 `format'，将为格式字符串使用此风格。
                        ‘'%'’, ‘'{'’ 或 ‘'$'’ 分别对应于
                        *note printf 风格: 1359,
                        *note str.format(): 5d4. 或
                        *note string.Template: 4f0.。 默认为 ‘'%'’。
                        
                        
     `level'            设置根记录器级别去指定 *note level: 21db.
                        
                        
     `stream'           使用指定的流初始化 StreamHandler。 请注意此参数
                        与 `filename' 是不兼容的 - 如果两者同时存在，则
                        会引发 ‘ValueError’。
                        
                        
     `handlers'         如果指定，这应为一个包含要加入根日志记录器的已
                        创建处理器的可迭代对象。 任何尚未设置格式描述符
                        的处理器将被设置为在此函数中创建的默认格式描述
                        符。 请注意此参数与 `filename' 或 `stream' 不兼
                        容 —— 如果两者同时存在，则会引发 ‘ValueError’。
                        
                        
     `force'            如果将此关键字参数指定为 true，则在执行其他参数
                        指定的配置之前，将移除并关闭附加到根记录器的所
                        有现有处理器。
                        
                        
     `encoding'         如果此关键字参数与 `filename' 一同被指定，则该
                        值会在创建 FileHandler 时被使用，因而也会在打开
                        输出文件时被使用。
                        
                        
     `errors'           如果此关键字参数与 `filename' 一同被指定，则该
                        值会在创建 FileHandler 时被使用，因而也会在打开
                        输出文件时被使用。 如果未指定，则会使用值
                        ’backslashreplace’。 请注意如果指定为 ‘None’，
                        它将被原样传给 func:‘open’，这意味着将会与传入
                        ’errors’ 一样处理。
                        

     3.2 版更變: 增加了 `style' 参数。

     3.3 版更變: 增加了 `handlers' 参数。 增加了额外的检查来捕获指定不兼
     容参数的情况 (例如同时指定 `handlers' 与 `stream' 或 `filename'，或
     者同时指定 `stream' 与 `filename')。

     3.8 版更變: 增加了 `force' 参数。

     3.9 版更變: 增加了 `encoding' 和 `errors' 参数。

 -- 函式: logging.shutdown ()

     通过刷新和关闭所有处理程序来通知日志记录系统执行有序停止。 此函数应
     当在应用退出时被调用并且在此调用之后不应再使用日志记录系统。

     当 logging 模块被导入时，它会将此函数注册为退出处理程序 (参见 *note
     atexit: b.)，因此通常不需要手动执行该操作。

 -- 函式: logging.setLoggerClass (klass)

     通知日志记录系统在实例化日志记录器时使用 `klass' 类。 该类应当定义
     *note __init__(): e23. 使其只要求一个 name 参数，并且 *note
     __init__(): e23. 应当调用 ‘Logger.__init__()’。 此函数通常会在需要
     使用自定义日志记录器行为的应用程序实例化任何日志记录器之前被调用。
     在此调用之后，在任何其他时刻都不要使用该子类来直接实例化日志记录器
     ：请继续使用 *note logging.getLogger(): 234. API 来获取你的日志记录
     器。

 -- 函式: logging.setLogRecordFactory (factory)

     设置一个用来创建 *note LogRecord: 9ec. 的可调用对象。


     參數: ‘factory’ – 用来实例化日志记录的工厂可调用对象。

     3.2 版新加入: 此函数与 *note getLogRecordFactory(): 2212. 一起提供
     ，以便允许开发者对如何构造表示日志记录事件的 *note LogRecord: 9ec.
     有更好的控制。

     可调用对象 factory 具有如下签名:

     ‘factory(name, level, fn, lno, msg, args, exc_info, func=None,
     sinfo=None, **kwargs)’


          name: 日志记录器名称


          level: 日志记录级别（数字）。


          fn: 进行日志记录调用的文件的完整路径名。


          lno: 记录调用所在文件中的行号。


          msg: 日志消息。


          args: 日志记录消息的参数。


          exc_info: 异常元组，或 ‘None’ 。


          func: 调用日志记录调用的函数或方法的名称。


          sinfo: 与 *note traceback.print_stack(): 869. 所提供的类似的栈
          回溯信息，显示调用的层级结构。


          kwargs: 其他关键字参数。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue28524


File: python.info,  Node: 模块级属性,  Next: 与警告模块集成,  Prev: 模块级函数,  Up: logging --- Python 的日志记录工具

5.16.6.11 模块级属性
....................

 -- 屬性: logging.lastResort

     通过此属性提供的“最后处理者”。 这是一个以 ‘WARNING’ 级别写入到
     ‘sys.stderr’ 的 *note StreamHandler: c46.，用于在没有任何日志记录配
     置的情况下处理日志记录事件。 最终结果就是将消息打印到 ‘sys.stderr’，
     这会替代先前形式为 "no handlers could be found for logger XYZ" 的错
     误消息。 如果出于某种原因你需要先前的行为，可将 ‘lastResort’ 设为
     ‘None’。

     3.2 版新加入.


File: python.info,  Node: 与警告模块集成,  Prev: 模块级属性,  Up: logging --- Python 的日志记录工具

5.16.6.12 与警告模块集成
........................

*note captureWarnings(): 2228. 函数可用来将 *note logging: aa. 和 *note
warnings: 12f. 模块集成。

 -- 函式: logging.captureWarnings (capture)

     此函数用于打开和关闭日志系统对警告的捕获。

     如果 `capture' 是 ‘True’，则 *note warnings: 12f. 模块发出的警告将
     重定向到日志记录系统。具体来说，将使用 *note
     warnings.formatwarning(): 112d. 格式化警告信息，并将结果字符串使用
     ‘WARNING’ 等级记录到名为 ‘'py.warnings'’ 的记录器中。

     如果 `capture' 是 ‘False’，则将停止将警告重定向到日志记录系统，并且
     将警告重定向到其原始目标（即在 ‘captureWarnings(True)’ 调用之前的有
     效目标）。

也參考
......

*note logging.config: ab. 模块

     日志记录模块的配置 API 。

*note logging.handlers: ac. 模块

     日志记录模块附带的有用处理器。

PEP 282(1) - Logging 系统

     该提案描述了Python标准库中包含的这个特性。

Original Python logging package(2)

     这是该 *note logging: aa. 包的原始来源。该站点提供的软件包版本适用
     于 Python 1.5.2、2.1.x 和 2.2.x，它们不被 *note logging: aa. 包含在
     标准库中。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0282

   (2) https://old.red-dove.com/python_logging.html


File: python.info,  Node: logging config --- 日志记录配置,  Next: logging handlers --- 日志处理程序,  Prev: logging --- Python 的日志记录工具,  Up: 通用操作系统服务

5.16.7 ‘logging.config’ — 日志记录配置
--------------------------------------

`源代码：' Lib/logging/config.py(1)

Important
.........

此页面仅包含参考信息。有关教程，请参阅

   * *note 基础教程: c43.

   * *note 进阶教程: c44.

   * *note 日志操作手册: c45.

__________________________________________________________________

这一节描述了用于配置 logging 模块的 API。

* Menu:

* 配置函数::
* Security considerations::
* 配置字典架构::
* 配置文件格式::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/logging/config.py


File: python.info,  Node: 配置函数,  Next: Security considerations,  Up: logging config --- 日志记录配置

5.16.7.1 配置函数
.................

下列函数可配置 logging 模块。 它们位于 *note logging.config: ab. 模块中
。 它们的使用是可选的 — 要配置 logging 模块你可以使用这些函数，也可以通
过调用主 API (在 *note logging: aa. 本身定义) 并定义在 *note logging:
aa. 或 *note logging.handlers: ac. 中声明的处理程序。

 -- 函式: logging.config.dictConfig (config)

     从一个字典获取日志记录配置。 字典的内容描述见下文的 *note
     配置字典架构: 222c.。

     如果在配置期间遇到错误，此函数将引发 *note ValueError: 16d, *note
     TypeError: 1fe, *note AttributeError: 4a1. 或 *note ImportError:
     16c. 并附带适当的描述性消息。 下面是将会引发错误的（可能不完整的）
     条件列表:

        * ‘level’ 不是字符串或者不是对应于实际日志记录级别的字符串。

        * ‘propagate’ 值不是布尔类型。

        * id 没有对应的目标。

        * 在增量调用期间发现不存在的处理程序 id。

        * 无效的日志记录器名称。

        * 无法解析为内部或外部对象。

     解析由 ‘DictConfigurator’ 类执行，该类的构造器可传入用于配置的字典
     ，并且具有 ‘configure()’ 方法。 *note logging.config: ab. 模块具有
     可调用属性 ‘dictConfigClass’，其初始值设为 ‘DictConfigurator’。 你
     可以使用你自己的适当实现来替换 ‘dictConfigClass’ 的值。

     *note dictConfig(): bfe. 会调用 ‘dictConfigClass’ 并传入指定的字典
     ，然后在所返回的对象上调用 ‘configure()’ 方法以使配置生效:

          def dictConfig(config):
              dictConfigClass(config).configure()

     例如，‘DictConfigurator’ 的子类可以在它自己的 *note __init__():
     e23. 中调用 ‘DictConfigurator.__init__()’，然后设置可以在后续
     ‘configure()’ 调用中使用的自定义前缀。 ‘dictConfigClass’ 将被绑定到
     这个新的子类，然后就可以与在默认的未定制状态下完全相同的方式调用
     *note dictConfig(): bfe.。

     3.2 版新加入.

 -- 函式: logging.config.fileConfig (fname, defaults=None,
          disable_existing_loggers=True)

     从一个 *note configparser: 22. 格式文件中读取日志记录配置。 文件格
     式应当与 *note 配置文件格式: 222d. 中的描述一致。 此函数可在应用程
     序中被多次调用，以允许最终用户在多个预设配置中进行选择（如果开发者
     提供了展示选项并加载选定配置的机制）。


     參數:

        * ‘fname’ – 一个文件名，或一个文件类对象，或是一个派生自 *note
          RawConfigParser: 95c. 的实例。 如果传入了一个派生自
          ‘RawConfigParser’ 的实例，它会被原样使用。 否则，将会实例化一
          个 ‘Configparser’，并且它会从作为 ‘fname’ 传入的对象中读取配置
          。 如果存在 *note readline(): de. 方法，则它会被当作一个文件类
          对象并使用 *note read_file(): 1fbc. 来读取；在其它情况下，它会
          被当作一个文件名并传递给 *note read(): 11d9.。

        * ‘defaults’ – 要传递给 ConfigParser 的默认值可在此参数中指定。

        * ‘disable_existing_loggers’ – 如果指定为 ‘False’，则当执行此调
          用时已存在的日志记录器会保持启用。 默认值为 ‘True’ 因为这将以
          向下兼容方式启用旧行为。 此行为是禁用任何现有的非根日志记录器
          除非它们或它们的上级在日志记录配置中被显式地命名。

     3.4 版更變: 现在接受 *note RawConfigParser: 95c. 子类的实例作为
     ‘fname’ 的值。 这有助于:

        * 使用一个配置文件，其中日志记录配置只是全部应用程序配置的一部分
          。

        * 使用从一个文件读取的配置，它随后会在被传给 ‘fileConfig’ 之前由
          使用配置的应用程序来修改（例如基于命令行参数或运行时环境的其他
          部分）。

 -- 函式: logging.config.listen (port=DEFAULT_LOGGING_CONFIG_PORT,
          verify=None)

     在指定的端口上启动套接字服务器，并监听新的配置。 如果未指定端口，则
     会使用模块默认的 ‘DEFAULT_LOGGING_CONFIG_PORT’。 日志记录配置将作为
     适合由 *note dictConfig(): bfe. 或 *note fileConfig(): 4af. 进行处
     理的文件来发送。 返回一个 *note Thread: 21a. 实例，你可以在该实例上
     调用 *note start(): 222e. 来启动服务器，对该服务器你可以在适当的时
     候执行 *note join(): c32.。 要停止该服务器，请调用 *note
     stopListening(): 222f.。

     如果指定 ‘verify’ 参数，则它应当是一个可调用对象，该对象应当验证通
     过套接字接收的字节数据是否有效且应被处理。 这可以通过对通过套接字发
     送的内容进行加密和/或签名来完成，这样 ‘verify’ 可调用对象就能执行签
     名验证和/或解密。 ‘verify’ 可调用对象的调用会附带一个参数 —— 通过套
     接字接收的字节数据 —— 并应当返回要处理的字节数据，或者返回 ‘None’ 来
     指明这些字节数据应当被丢弃。 返回的字节数据可以与传入的字节数据相同
     （例如在只执行验证的时候），或者也可以完全不同（例如在可能执行了解
     密的时候）。

     要将配置发送到套接字，请读取配置文件并将其作为字节序列发送到套接字
     ，字节序列要以使用 ‘struct.pack('>L', n)’ 打包为二进制格式的四字节
     长度的字符串打头。
          備註: Because portions of the configuration are passed through
          *note eval(): c61, use of this function may open its users to
          a security risk.  While the function only binds to a socket on
          ‘localhost’, and so does not accept connections from remote
          machines, there are scenarios where untrusted code could be
          run under the account of the process which calls *note
          listen(): 95d.  Specifically, if the process calling *note
          listen(): 95d. runs on a multi-user machine where users cannot
          trust each other, then a malicious user could arrange to run
          essentially arbitrary code in a victim user’s process, simply
          by connecting to the victim’s *note listen(): 95d. socket and
          sending a configuration which runs whatever code the attacker
          wants to have executed in the victim’s process.  This is
          especially easy to do if the default port is used, but not
          hard even if a different port is used.  To avoid the risk of
          this happening, use the ‘verify’ argument to *note listen():
          95d. to prevent unrecognised configurations from being
          applied.

     3.4 版更變: 添加了 ‘verify’ 参数。

          備註: 如果你希望将配置发送给未禁用现有日志记录器的监听器，你将
          需要使用 JSON 格式的配置，该格式将使用 *note dictConfig():
          bfe. 进行配置。 此方法允许你在你发送的配置中将
          ‘disable_existing_loggers’ 指定为 ‘False’。

 -- 函式: logging.config.stopListening ()

     停止通过对 *note listen(): 95d. 的调用所创建的监听服务器。 此函数的
     调用通常会先于在 *note listen(): 95d. 的返回值上调用 ‘join()’。


File: python.info,  Node: Security considerations,  Next: 配置字典架构,  Prev: 配置函数,  Up: logging config --- 日志记录配置

5.16.7.2 Security considerations
................................

The logging configuration functionality tries to offer convenience, and
in part this is done by offering the ability to convert text in
configuration files into Python objects used in logging configuration -
for example, as described in *note 用户定义对象: 2232.  However, these
same mechanisms (importing callables from user-defined modules and
calling them with parameters from the configuration) could be used to
invoke any code you like, and for this reason you should treat
configuration files from untrusted sources with `extreme caution' and
satisfy yourself that nothing bad can happen if you load them, before
actually loading them.


File: python.info,  Node: 配置字典架构,  Next: 配置文件格式,  Prev: Security considerations,  Up: logging config --- 日志记录配置

5.16.7.3 配置字典架构
.....................

描述日志记录配置需要列出要创建的不同对象及它们之间的连接；例如，你可以创
建一个名为 ’console’ 的处理程序，然后名为 ’startup’ 的日志记录器将可以把
它的消息发送给 ’console’ 处理程序。 这些对象并不仅限于 *note logging:
aa. 模块所提供的对象，因为你还可以编写你自己的格式化或处理程序类。 这些
类的形参可能还需要包括 ‘sys.stderr’ 这样的外部对象。 描述这些对象和连接
的语法会在下面的 *note 对象连接: 2234. 中定义。

* Menu:

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


File: python.info,  Node: 字典架构细节,  Next: 增量配置,  Up: 配置字典架构

5.16.7.4 字典架构细节
.....................

传给 *note dictConfig(): bfe. 的字典必须包含以下的键:

   * `version' - 应设为代表架构版本的整数值。 目前唯一有效的值是 1，使用
     此键可允许架构在继续演化的同时保持向下兼容性。

所有其他键都是可选项，但如存在它们将根据下面的描述来解读。 在下面提到
’configuring dict’ 的所有情况下，都将检查它的特殊键 ‘'()'’ 以确定是否需
要自定义实例化。 如果需要，则会使用下面 *note 用户定义对象: 2232. 所描述
的机制来创建一个实例；否则，会使用上下文来确定要实例化的对象。

   * `formatters' - 对应的值将是一个字典，其中每个键是一个格式器 ID 而每
     个值则是一个描述如何配置相应 *note Formatter: 21de. 实例的字典。

     将在配置字典中搜索键 ‘format’ 和 ‘datefmt’ (默认值均为 ‘None’) 并且
     这些键会被用于构造 *note Formatter: 21de. 实例。

     3.8 版更變: 一个 ‘validate’ 键 (默认值为 ‘True’) 可被添加到配置字典
     的 ‘formatters’ 部分，这会被用来验证格式的有效性。

   * `filters' - 对应的值将是一个字典，其中每个键是一个过滤器 ID 而每个
     值则是一个描述如何配置相应 Filter 实例的字典。

     将在配置字典中搜索键 ‘name’ (默认值为空字符串) 并且该键会被用于构造
     *note logging.Filter: c48. 实例。

   * `handlers' - 对应的值将是一个字典，其中每个键是一个处理程序 ID 而每
     个值则是一个描述如何配置相应 Handler 实例的字典。

     将在配置字典中搜索下列键:

        * ‘class’ (强制)。 这是处理程序类的完整限定名称。

        * ‘level’ (可选)。 处理程序的级别。

        * ‘formatter’ (可选)。 处理程序所对应格式化器的 ID。

        * ‘filters’ (可选)。 由处理程序所对应过滤器的 ID 组成的列表。

     所有 `其他' 键会被作为关键字参数传递给处理程序类的构造器。 例如，给
     定如下配置:

          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

     ID 为 ‘console’ 的处理程序会被实例化为 *note logging.StreamHandler:
     c46.，并使用 ‘sys.stdout’ 作为下层流。 ID 为 ‘file’ 的处理程序会被
     实例化为 *note logging.handlers.RotatingFileHandler: 2236.，并附带
     关键字参数 ‘filename='logconfig.log', maxBytes=1024,
     backupCount=3’。

   * `loggers' - 对应的值将是一个字典，其中每个键是一个日志记录器名称而
     每个值则是一个描述如何配置相应 Logger 实例的字典。

     将在配置字典中搜索下列键:

        * ‘level’ (可选)。 日志记录器的级别。

        * ‘propagate’ (可选)。 日志记录器的传播设置。

        * ‘filters’ (可选)。 由日志记录器对应过滤器的 ID 组成的列表。

        * ‘handlers’ (可选)。 由日志记录器对应处理程序的 ID 组成的列表。

     指定的日志记录器将根据指定的级别、传播、过滤器和处理程序来配置。

   * `root' - 这将成为根日志记录器对应的配置。 配置的处理方式将与所有日
     志记录器一致，除了 ‘propagate’ 设置将不可用之外。

   * `incremental' - 配置是否要被解读为在现有配置上新增。 该值默认为
     ‘False’，这意味着指定的配置将以与当前 *note fileConfig(): 4af. API
     所使用的相同语义来替代现有的配置。

     如果指定的值为 ‘True’，配置会按照 *note 增量配置: 2237. 部分所描述
     的方式来处理。

   * `disable_existing_loggers' - 是否要禁用任何现有的非根日志记录器。 该
     设置对应于 *note fileConfig(): 4af. 中的同名形参。 如果省略，则此形
     参默认为 ‘True’。 如果 `incremental' 为 ‘True’ 则该省会被忽略。


File: python.info,  Node: 增量配置,  Next: 对象连接,  Prev: 字典架构细节,  Up: 配置字典架构

5.16.7.5 增量配置
.................

为增量配置提供完全的灵活性是很困难的。 例如，由于过滤器和格式化器这样的
对象是匿名的，一旦完成配置，在增加配置时就不可能引用这些匿名对象。

此外，一旦完成了配置，在运行时任意改变日志记录器、处理程序、过滤器、格式
化器的对象图就不是很有必要；日志记录器和处理程序的详细程度只需通过设置级
别即可实现控制（对于日志记录器则可设置传播旗标）。 在多线程环境中以安全
的方式任意改变对象图也许会导致问题；虽然并非不可能，但这样做的好处不足以
抵销其所增加的实现复杂度。

这样，当配置字典的 ‘incremental’ 键存在且为 ‘True’ 时，系统将完全忽略任
何 ‘formatters’ 和 ‘filters’ 条目，并仅会处理 ‘handlers’ 条目中的
‘level’ 设置，以及 ‘loggers’ 和 ‘root’ 条目中的 ‘level’ 和 ‘propagate’ 设
置。

使用配置字典中的值可让配置以封存字典对象的形式通过线路传送给套接字监听器
。 这样，长时间运行的应用程序的日志记录的详细程度可随时间改变而无须停止
并重新启动应用程序。


File: python.info,  Node: 对象连接,  Next: 用户定义对象,  Prev: 增量配置,  Up: 配置字典架构

5.16.7.6 对象连接
.................

该架构描述了一组日志记录对象 —— 日志记录器、处理程序、格式化器、过滤器
—— 它们在对象图中彼此连接。 因此，该架构需要能表示对象之间的连接。 例如
，在配置完成后，一个特定的日志记录器关联到了一个特定的处理程序。 出于讨
论的目的，我们可以说该日志记录器代表两者间连接的源头，而处理程序则代表对
应的目标。 当然在已配置对象中这是由包含对处理程序的引用的日志记录器来代
表的。 在配置字典中，这是通过给每个目标对象一个 ID 来无歧义地标识它，然
后在源头对象中使用该 ID 来实现的。

因此，举例来说，考虑以下 YAML 代码段:

     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]

（注：这里使用 YAML 是因为它的可读性比表示字典的等价 Python 源码形式更好
。）

日志记录器 ID 就是日志记录器的名称，它会在程序中被用来获取对日志记录器的
引用，例如 ‘foo.bar.baz’。 格式化器和过滤器的 ID 可以是任意字符串值 (例
如上面的 ‘brief’, ‘precise’) 并且它们是瞬态的，因为它们仅对处理配置字典
有意义并会被用来确定对象之间的连接，而当配置调用完成时不会在任何地方保留
。

上面的代码片段指明名为 ‘foo.bar.baz’ 的日志记录器应当关联到两个处理程序
，它们的 ID 是 ‘h1’ 和 ‘h2’。 ‘h1’ 的格式化器的 ID 是 ‘brief’，而 ‘h2’ 的
格式化器的 ID 是 ‘precise’。


File: python.info,  Node: 用户定义对象,  Next: 访问外部对象,  Prev: 对象连接,  Up: 配置字典架构

5.16.7.7 用户定义对象
.....................

此架构支持用户定义对象作为处理程序、过滤器和格式化器。 （日志记录器的不
同实例不需要具有不同类型，因此这个配置架构并不支持用户定义日志记录器类。
）

要配置的对象是由字典描述的，其中包含它们的配置详情。 在某些地方，日志记
录系统将能够从上下文中推断出如何实例化一个对象，但是当要实例化一个用户自
定义对象时，系统将不知道要如何做。 为了提供用户自定义对象实例化的完全灵
活性，用户需要提供一个‘工厂’函数 —— 即在调用时传入配置字典并返回实例化对
象的可调用对象。 这是用一个通过特殊键 ‘'()'’ 来访问的工厂函数的绝对导入
路径来标示的。 下面是一个实际的例子:

     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

上面的 YAML 代码片段定义了三个格式化器。 第一个的 ID 为 ‘brief’，是带有
特殊格式字符串的标准 *note logging.Formatter: 21de. 实例。 第二个的 ID 为
‘default’，具有更长的格式同时还显式地定义了时间格式，并将最终实例化一个
带有这两个格式字符串的 *note logging.Formatter: 21de.。 以 Python 源代码
形式显示的 ‘brief’ 和 ‘default’ 格式化器分别具有下列配置子字典:

     {
       'format' : '%(message)s'
     }

和:

     {
       'format' : '%(asctime)s %(levelname)-8s %(name)-15s %(message)s',
       'datefmt' : '%Y-%m-%d %H:%M:%S'
     }

并且由于这些字典不包含特殊键 ‘'()'’，实例化方式是从上下文中推断出来的：
结果会创建标准的 *note logging.Formatter: 21de. 实例。 第三个格式器的 ID
为 ‘custom’，对应配置子字典为:

     {
       '()' : 'my.package.customFormatterFactory',
       'bar' : 'baz',
       'spam' : 99.9,
       'answer' : 42
     }

并且它包含特殊键 ‘'()'’，这意味着需要用户自定义实例化方式。 在此情况下，
将使用指定的工厂可调用对象。 如果它本身就是一个可调用对象则将被直接使用
—— 否则如果你指定了一个字符串（如这个例子所示）则将使用正常的导入机制来
定位实例的可调用对象。 调用该可调用对象将传入配置子字典中 `剩余的' 条目
作为关键字参数。 在上面的例子中，调用将预期返回 ID 为 ‘custom’ 的格式化
器:

     my.package.customFormatterFactory(bar='baz', spam=99.9, answer=42)

将 ‘'()'’ 用作特殊键是因为它不是一个有效的关键字形参名称，这样就不会与调
用中使用的关键字参数发生冲突。 ‘'()'’ 还被用作表明对应值为可调用对象的助
记符。


File: python.info,  Node: 访问外部对象,  Next: 访问内部对象,  Prev: 用户定义对象,  Up: 配置字典架构

5.16.7.8 访问外部对象
.....................

有时一个配置需要引用配置以外的对象，例如 ‘sys.stderr’。 如果配置字典是使
用 Python 代码构造的，这会很直观，但是当配置是通过文本文件（例如 JSON,
YAML）提供的时候就会引发问题。 在一个文本文件中，没有将 ‘sys.stderr’ 与
字符串字面值 ‘'sys.stderr'’ 区分开来的标准方式。 为了实现这种区分，配置
系统会在字符串值中查找规定的特殊前缀并对其做特殊处理。 例如，如果在配置
中将字符串字面值 ‘'ext://sys.stderr'’ 作为一个值来提供，则 ‘ext://’ 将被
去除而该值的剩余部分将使用正常导入机制来处理。

此类前缀的处理方式类似于协议处理：存在一种通用机制来查找与正则表达式
‘^(?P<prefix>[a-z]+)://(?P<suffix>.*)$’ 相匹配的前缀，如果识别出了
‘prefix’，则 ‘suffix’ 会以与前缀相对应的方式来处理并且处理的结果将替代原
字符串值。 如果未识别出前缀，则原字符串将保持不变。


File: python.info,  Node: 访问内部对象,  Next: 导入解析与定制导入器,  Prev: 访问外部对象,  Up: 配置字典架构

5.16.7.9 访问内部对象
.....................

除了外部对象，有时还需要引用配置中的对象。 这将由配置系统针对它所了解的
内容隐式地完成。 例如，在日志记录器或处理程序中表示 ‘level’ 的字符串值
‘'DEBUG'’ 将被自动转换为值 ‘logging.DEBUG’，而 ‘handlers’, ‘filters’ 和
‘formatter’ 条目将接受一个对象 ID 并解析为适当的目标对象。

但是，对于 *note logging: aa. 模块所不了解的用户自定义对象则需要一种更通
用的机制。 例如，考虑 *note logging.handlers.MemoryHandler: 223f.，它接
受一个 ‘target’ 参数即其所委托的另一个处理程序。 由于系统已经知道存在该
类，因而在配置中，给定的 ‘target’ 只需为相应目标处理程序的的对象 ID 即可
，而系统将根据该 ID 解析出处理程序。 但是，如果用户定义了一个具有
‘alternate’ 处理程序的 ‘my.package.MyHandler’，则配置程序将不知道
‘alternate’ 指向的是一个处理程序。 为了应对这种情况，通用解析系统允许用
户指定:

     handlers:
       file:
         # configuration of file handler goes here

       custom:
         (): my.package.MyHandler
         alternate: cfg://handlers.file

字符串字面值 ‘'cfg://handlers.file'’ 将按照与 ‘ext://’ 前缀类似的方式被
解析为结果字符串，但查找操作是在配置自身而不是在导入命名空间中进行。 该
机制允许按点号或按索引来访问，与 ‘str.format’ 所提供的方式类似。 这样，
给定以下代码段:

     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.

在该配置中，字符串 ‘'cfg://handlers'’ 将解析为带有 ‘handlers’ 键的字典，
字符串 ‘'cfg://handlers.email’ 将解析为 ‘handlers’ 字典中带有 ‘email’ 键
的字典，依此类推。 字符串 ‘'cfg://handlers.email.toaddrs[1]’ 将解析为
‘'dev_team.domain.tld'’ 而字符串 ‘'cfg://handlers.email.toaddrs[0]'’ 将
解析为值 ‘'support_team@domain.tld'’。 ‘subject’ 值可以使用
‘'cfg://handlers.email.subject'’ 或者等价的
‘'cfg://handlers.email[subject]'’ 来访问。 后一种形式仅在键包含空格或非
字母数字类字符的情况下才需要使用。 如果一个索引仅由十进制数码构成，则将
尝试使用相应的整数值来访问，如果有必要则将回退为字符串值。

给定字符串 ‘cfg://handlers.myhandler.mykey.123’，这将解析为
‘config_dict['handlers']['myhandler']['mykey']['123']’。 如果字符串被指
定为 ‘cfg://handlers.myhandler.mykey[123]’，系统将尝试从
‘config_dict['handlers']['myhandler']['mykey'][123]’ 中提取值，并在尝试
失败时回退为 ‘config_dict['handlers']['myhandler']['mykey']['123']’。


File: python.info,  Node: 导入解析与定制导入器,  Prev: 访问内部对象,  Up: 配置字典架构

5.16.7.10 导入解析与定制导入器
..............................

导入解析默认使用内置的 *note __import__(): 16b. 函数来执行导入。 你可能
想要将其替换为你自己的导入机制：如果是这样的话，你可以替换
‘DictConfigurator’ 或其超类 ‘BaseConfigurator’ 类的 ‘importer’ 属性。 但
是你必须小心谨慎，因为函数是从类中通过描述器方式来访问的。 如果你使用
Python 可调用对象来执行导入，并且你希望在类层级而不是在实例层级上定义它
，则你需要用 *note staticmethod(): 30a. 来装饰它。 例如:

     from importlib import import_module
     from logging.config import BaseConfigurator

     BaseConfigurator.importer = staticmethod(import_module)

如果你是在一个配置器的 `实例' 上设置导入可调用对象则你不需要用 *note
staticmethod(): 30a. 来装饰。


File: python.info,  Node: 配置文件格式,  Prev: 配置字典架构,  Up: logging config --- 日志记录配置

5.16.7.11 配置文件格式
......................

*note fileConfig(): 4af. 所能理解的配置文件格式是基于 *note
configparser: 22. 功能的。 该文件必须包含 ‘[loggers]’, ‘[handlers]’ 和
‘[formatters]’ 等小节，它们通过名称来标识文件中定义的每种类型的实体。 对
于每个这样的实体，都有单独的小节来标识实体的配置方式。 因此，对于
‘[loggers]’ 小节中名为 ‘log01’ 的日志记录器，相应的配置详情保存在
‘[logger_log01]’ 小节中。 类似地，对于 ‘[handlers]’ 小节中名为 ‘hand01’
的处理程序，其配置将保存在名为 ‘[handler_hand01]’ 的小节中，而对于
‘[formatters]’ 小节中名为 ‘form01’ 的格式化器，其配置将在名为
‘[formatter_form01]’ 的小节中指定。 根日志记录器的配置必须在名为
‘[logger_root]’ 的小节中指定。

     備註: *note fileConfig(): 4af. API 比 *note dictConfig(): bfe. API
     更旧因而没有提供涵盖日志记录特定方面的功能。 例如，你无法配置 *note
     Filter: c48. 对象，该对象使用 *note fileConfig(): 4af. 提供超出简单
     整数级别的消息过滤功能。 如果你想要在你的日志记录配置中包含 *note
     Filter: c48. 的实例，你将必须使用 *note dictConfig(): bfe.。 请注意
     未来还将向 *note dictConfig(): bfe. 添加对配置功能的强化，因此值得
     考虑在方便的时候转换到这个新 API。

在文件中这些小节的例子如下所示。

     [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

根日志记录器必须指定一个级别和一个处理程序列表。 根日志小节的例子如下所
示。

     [logger_root]
     level=NOTSET
     handlers=hand01

‘level’ 条目可以为 ‘DEBUG, INFO, WARNING, ERROR, CRITICAL’ 或 ‘NOTSET’ 之
一。 其中 ‘NOTSET’ 仅适用于根日志记录器，表示将会记录所有消息。 级别值会
在 ‘logging’ 包命名空间的上下文中通过 *note eval(): c61. 来得出。

‘handlers’ 条目是以逗号分隔的处理程序名称列表，它必须出现于 ‘[handlers]’
小节并且在配置文件中有相应的小节。

对于根日志记录器以外的日志记录器，还需要某些附加信息。 下面的例子演示了
这些信息。

     [logger_parser]
     level=DEBUG
     handlers=hand01
     propagate=1
     qualname=compiler.parser

‘level’ 和 ‘handlers’ 条目的解释方式与根日志记录器的一致，不同之处在于如
果一个非根日志记录器的级别被指定为 ‘NOTSET’，则系统会咨询更高层级的日志
记录器来确定该日志记录器的有效级别。 ‘propagate’ 条目设为 1 表示消息必须
从此日志记录器传播到更高层级的处理程序，设为 0 表示消息 `不会' 传播到更
高层级的处理程序。 ‘qualname’ 条目是日志记录器的层级通道名称，也就是应用
程序获取日志记录器所用的名称。

指定处理程序配置的小节说明如下。

     [handler_hand01]
     class=StreamHandler
     level=NOTSET
     formatter=form01
     args=(sys.stdout,)

‘class’ 条目指明处理程序的类（由 ‘logging’ 包命名空间中的 *note eval():
c61. 来确定）。 ‘level’ 会以与日志记录器相同的方式来解读，‘NOTSET’ 会被
视为表示‘记录一切消息’。

‘formatter’ 条目指明此处理程序的格式化器的键名称。 如为空白，则会使用默
认的格式化器 (‘logging._defaultFormatter’)。 如果指定了名称，则它必须出
现于 ‘[formatters]’ 小节并且在配置文件中有相应的小节。

‘args’ 条目，当在 ‘logging’ 包命名空间的上下文中执行 *note eval(): c61.
时将是传给处理程序类构造器的参数列表。 请参阅相应处理程序的构造器说明或
者下面的示例，以了解典型的条目是如何构造的。 如果未提供，则默认为 ‘()’。

可选的 ‘kwargs’ 条目，当在 ‘logging’ 包命名空间的上下文中执行 *note
eval(): c61. 时将是传给处理程序的构造器的关键字参数字典。 如果未提供，则
默认为 ‘{}’。

     [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', '', '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}

指定格式化器配置的小节说明如下。

     [formatter_form01]
     format=F1 %(asctime)s %(levelname)s %(message)s
     datefmt=
     class=logging.Formatter

‘format’ 是整个格式字符串，而 ‘datefmt’ 条目则是兼容 ‘strftime()’ 的日期
/时间格式字符串。 如果为空，此包将替换任何接近于日期格式字符串
‘'%Y-%m-%d %H:%M:%S'’ 的内容。 此格式还指定了毫秒，并使用逗号分隔符将其
附加到结果当中。 此格式的时间示例如 ‘2003-01-23 00:29:50,411’。

‘class’ 条目是可选的。 它指明格式化器类的名称（形式为带点号的模块名加类
名。） 此选项适用于实例化 *note Formatter: 21de. 的子类。 *note
Formatter: 21de. 的子类可通过扩展或收缩格式来显示异常回溯信息。

     備註: 由于如上所述使用了 *note eval(): c61.，因此使用 *note
     listen(): 95d. 通过套接字来发送和接收配置会导致潜在的安全风险。 此
     风险仅限于相互间没有信任的多个用户在同一台机器上运行代码的情况；请
     参阅 *note listen(): 95d. 了解更多信息。

也參考
......

模块 *note logging: aa.

     日志记录模块的 API 参考。

模块 *note logging.handlers: ac.

     日志记录模块附带的有用处理程序。


File: python.info,  Node: logging handlers --- 日志处理程序,  Next: getpass --- 便携式密码输入工具,  Prev: logging config --- 日志记录配置,  Up: 通用操作系统服务

5.16.8 ‘logging.handlers’ — 日志处理程序
----------------------------------------

`源代码:' Lib/logging/handlers.py(1)

Important
.........

此页面仅包含参考信息。有关教程，请参阅

   * *note 基础教程: c43.

   * *note 进阶教程: c44.

   * *note 日志记录操作手册: c45.

__________________________________________________________________

这个包提供了以下有用的处理程序。 请注意有三个处理程序类 (*note
StreamHandler: c46, *note FileHandler: 2245. 和 *note NullHandler: ce6.)
实际上是在 *note logging: aa. 模块本身定义的，但其文档与其他处理程序一同
记录在此。

* Menu:

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

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/Lib/logging/handlers.py


File: python.info,  Node: StreamHandler,  Next: FileHandler,  Up: logging handlers --- 日志处理程序

5.16.8.1 StreamHandler
......................

*note StreamHandler: c46. 类位于核心 *note logging: aa. 包，它可将日志记
录输出发送到数据流例如 `sys.stdout', `sys.stderr' 或任何文件类对象（或者
更精确地说，任何支持 ‘write()’ 和 ‘flush()’ 方法的对象）。

 -- 類別: logging.StreamHandler (stream=None)

     返回一个新的 *note StreamHandler: c46. 类。 如果指定了 `stream'，则
     实例将用它作为日志记录输出；在其他情况下将使用 `sys.stderr'。

      -- 成員函式: emit (record)

          如果指定了一个格式化器，它会被用来格式化记录。 随后记录会被写
          入到 *note terminator: 2249. 之后的流中。 如果存在异常信息，则
          会使用 *note traceback.print_exception(): 2208. 来格式化并添加
          到流中。

      -- 成員函式: flush ()

          通过调用流的 *note flush(): 224a. 方法来刷新它。 请注意
          ‘close()’ 方法是继承自 *note Handler: 21df. 的所以没有输出，因
          此有时可能需要显式地调用 *note flush(): 224a.。

      -- 成員函式: setStream (stream)

          将实例的流设为指定值，如果两者不一致的话。 旧的流会在设置新的
          流之前被刷新。


          參數: ‘stream’ – 处理程序应当使用的流。


          傳回: 旧的流，如果流已被改变的话，如果未被改变则为 `None'。

          3.7 版新加入.

      -- 屬性: terminator

          当将已格式化的记录写入到流时被用作终止符的字符串。 默认值为
          ‘'\n'’。

          如果你不希望以换行符终止，你可以将处理程序类实例的
          ‘terminator’ 属性设为空字符串。

          在较早的版本中，终止符被硬编码为 ‘'\n'’。

          3.2 版新加入.


File: python.info,  Node: FileHandler,  Next: NullHandler,  Prev: StreamHandler,  Up: logging handlers --- 日志处理程序

5.16.8.2 FileHandler
....................

*note FileHandler: 2245. 类位于核心 *note logging: aa. 包，它可将日志记
录输出到磁盘文件中。 它从 *note StreamHandler: c46. 继承了输出功能。

 -- 類別: logging.FileHandler (filename, mode='a', encoding=None,
          delay=False, errors=None)

     返回一个 *note FileHandler: 2245. 类的新实例。 将打开指定的文件并将
     其用作日志记录流。 如果未指定 `mode'，则会使用 ‘'a'’。 如果
     `encoding' 不为 ‘None’，则会将其用作打开文件的编码格式。 如果
     `delay' 为真值，则文件打开会被推迟至第一次调用 *note emit(): 224d.
     时。 默认情况下，文件会无限增长。 如果指定了 `errors'，它会被用于确
     定编码格式错误的处理方式。

     3.6 版更變: 除了字符串值，也接受 *note Path: 32f. 对象作为
     `filename' 参数。

     3.9 版更變: 增加了 `errors' 形参。

      -- 成員函式: close ()

          关闭文件。

      -- 成員函式: emit (record)

          将记录输出到文件。


File: python.info,  Node: NullHandler,  Next: WatchedFileHandler,  Prev: FileHandler,  Up: logging handlers --- 日志处理程序

5.16.8.3 NullHandler
....................

3.1 版新加入.

*note NullHandler: ce6. 类位于核心 *note logging: aa. 包，它不执行任何格
式化或输出。 它实际上是一个供库开发者使用的‘无操作’处理程序。

 -- 類別: logging.NullHandler

     返回一个 *note NullHandler: ce6. 类的新实例。

      -- 成員函式: emit (record)

          此方法不执行任何操作。

      -- 成員函式: handle (record)

          此方法不执行任何操作。

      -- 成員函式: createLock ()

          此方法会对锁返回 ‘None’，因为没有下层 I/O 的访问需要被序列化。

请参阅 *note 配置库的日志记录: 2254. 了解有关如何使用 *note NullHandler:
ce6. 的更多信息。


File: python.info,  Node: WatchedFileHandler,  Next: BaseRotatingHandler,  Prev: NullHandler,  Up: logging handlers --- 日志处理程序

5.16.8.4 WatchedFileHandler
...........................

*note WatchedFileHandler: 2257. 类位于 *note logging.handlers: ac. 模块
，这个 ‘FileHandler’ 用于监视它所写入日志记录的文件。 如果文件发生变化，
它会被关闭并使用文件名重新打开。

发生文件更改可能是由于使用了执行文件轮换的程序例如 `newsyslog' 和
`logrotate'。 这个处理程序在 Unix/Linux 下使用，它会监视文件来查看自上次
发出数据后是否有更改。 （如果文件的设备或 inode 发生变化就认为已被更改。
） 如果文件被更改，则会关闭旧文件流，并再打开文件以获得新文件流。

这个处理程序不适合在 Windows 下使用，因为在 Windows 下打开的日志文件无法
被移动或改名 —— 日志记录会使用排他的锁来打开文件 —— 因此这样的处理程序是
没有必要的。 此外，`ST_INO' 在 Windows 下不受支持；*note stat(): 321. 将
总是为该值返回零。

 -- 類別: logging.handlers.WatchedFileHandler (filename, mode='a',
          encoding=None, delay=False, errors=None)

     返回一个 *note WatchedFileHandler: 2257. 类的新实例。 将打开指定的
     文件并将其用作日志记录流。 如果未指定 `mode'，则会使用 ‘'a'’。 如果
     `encoding' 不为 ‘None’，则会将其用作打开文件的编码格式。 如果
     `delay' 为真值，则文件打开会被推迟至第一次调用 *note emit(): 2258.
     时。 默认情况下，文件会无限增长。 如果提供了 `errors'，它会被用于确
     定编码格式错误的处理方式。

     3.6 版更變: 除了字符串值，也接受 *note Path: 32f. 对象作为
     `filename' 参数。

     3.9 版更變: 增加了 `errors' 形参。

      -- 成員函式: reopenIfNeeded ()

          检查文件是否已更改。 如果已更改，则会刷新并关闭现有流然后重新
          打开文件，这通常是将记录输出到文件的先导操作。

          3.6 版新加入.

      -- 成員函式: emit (record)

          将记录输出到文件，但如果文件已更改则会先调用 *note
          reopenIfNeeded(): 65b. 来重新打开它。


File: python.info,  Node: BaseRotatingHandler,  Next: RotatingFileHandler,  Prev: WatchedFileHandler,  Up: logging handlers --- 日志处理程序

5.16.8.5 BaseRotatingHandler
............................

*note BaseRotatingHandler: 225b. 类位于 *note logging.handlers: ac. 模块
中，它是轮换文件处理程序类 *note RotatingFileHandler: 2236. 和 *note
TimedRotatingFileHandler: 959. 的基类。 你不需要实例化此类，但它具有你可
能需要重载的属性和方法。

 -- 類別: logging.handlers.BaseRotatingHandler (filename, mode,
          encoding=None, delay=False, errors=None)

     类的形参与 ‘FileHandler’ 的相同。 其属性有:

      -- 屬性: namer

          如果此属性被设为一个可调用对象，则 *note rotation_filename():
          225d. 方法会委托给该可调用对象。 传给该可调用对象的形参与传给
          *note rotation_filename(): 225d. 的相同。

               備註: namer 函数会在轮换期间被多次调用，因此它应当尽可能
               的简单快速。 它还应当对给定的输入每次都返回相同的输出，否
               则轮换行为可能无法按预期工作。

               It’s also worth noting that care should be taken when
               using a namer to preserve certain attributes in the
               filename which are used during rotation.  For example,
               *note RotatingFileHandler: 2236. expects to have a set of
               log files whose names contain successive integers, so
               that rotation works as expected, and *note
               TimedRotatingFileHandler: 959. deletes old log files
               (based on the ‘backupCount’ parameter passed to the
               handler’s initializer) by determining the oldest files to
               delete.  For this to happen, the filenames should be
               sortable using the date/time portion of the filename, and
               a namer needs to respect this.  (If a namer is wanted
               that doesn’t respect this scheme, it will need to be used
               in a subclass of *note TimedRotatingFileHandler: 959.
               which overrides the *note getFilesToDelete(): 225e.
               method to fit in with the custom naming scheme.)

          3.3 版新加入.

      -- 屬性: rotator

          如果此属性被设为一个可调用对象，则 *note rotate(): 2260. 方法
          会委托给该可调用对象。 传给该可调用对象的形参与传给 *note
          rotate(): 2260. 的相同。

          3.3 版新加入.

      -- 成員函式: rotation_filename (default_name)

          当轮换时修改日志文件的文件名。

          提供该属性以便可以提供自定义文件名。

          默认实现会调用处理程序的 ’namer’ 属性，如果它是可调用对象的话
          ，并传给它默认的名称。 如果该属性不是可调用对象 (默认值为
          ‘None’)，则将名称原样返回。


          參數: ‘default_name’ – 日志文件的默认名称。

          3.3 版新加入.

      -- 成員函式: rotate (source, dest)

          当执行轮换时，轮换当前日志。

          默认实现会调用处理程序的 ’rotator’ 属性，如果它是可调用对象的
          话，并传给它 source 和 dest 参数。 如果该属性不是可调用对象 (默
          认值为 ‘None’)，则将源简单地重命名为目标。


          參數:

             * ‘source’ – 源文件名。 这通常为基本文件名，例如
               ’test.log’。

             * ‘dest’ – 目标文件名。 这通常是源被轮换后的名称，例如
               ’test.log.1’。

          3.3 版新加入.

该属性存在的理由是让你不必进行子类化 —— 你可以使用与 *note
RotatingFileHandler: 2236. 和 *note TimedRotatingFileHandler: 959. 的实
例相同的可调用对象。 如果 namer 或 rotator 可调用对象引发了异常，将会按
照与 ‘emit()’ 调用期间的任何其他异常相同的方式来处理，例如通过处理程序的
‘handleError()’ 方法。

如果你需要对轮换进程执行更多的修改，你可以重载这些方法。

请参阅 *note 利用 rotator 和 namer 自定义日志轮换操作: 2261. 获取具体示
例。


File: python.info,  Node: RotatingFileHandler,  Next: TimedRotatingFileHandler,  Prev: BaseRotatingHandler,  Up: logging handlers --- 日志处理程序

5.16.8.6 RotatingFileHandler
............................

*note RotatingFileHandler: 2236. 类位于 *note logging.handlers: ac. 模块
，它支持磁盘日志文件的轮换。

 -- 類別: logging.handlers.RotatingFileHandler (filename, mode='a',
          maxBytes=0, backupCount=0, encoding=None, delay=False,
          errors=None)

     返回一个 *note RotatingFileHandler: 2236. 类的新实例。 将打开指定的
     文件并将其用作日志记录流。 如果未指定 `mode'，则会使用 ‘'a'’。 如果
     `encoding' 不为 ‘None’，则会将其用作打开文件的编码格式。 如果
     `delay' 为真值，则文件打开会被推迟至第一次调用 *note emit(): 2264.。
     默认情况下，文件会无限增长。 如果提供了 `errors'，它会被用于确定编
     码格式错误的处理方式。

     你可以使用 `maxBytes' 和 `backupCount' 值来允许文件以预定的大小执行
     `rollover'。 当即将超出预定大小时，将关闭旧文件并打开一个新文件用于
     输出。 只要当前日志文件长度接近 `maxBytes' 就会发生轮换；但是如果
     `maxBytes' 或 `backupCount' 两者之一的值为零，就不会发生轮换，因此
     你通常要设置 `backupCount' 至少为 1，而 `maxBytes' 不能为零。 当
     `backupCount' 为非零值时，系统将通过为原文件名添加扩展名 ’.1’, ’.2’
     等来保存旧日志文件。 例如，当 `backupCount' 为 5 而基本文件名为
     ‘app.log’ 时，你将得到 ‘app.log’, ‘app.log.1’, ‘app.log.2’ 直至
     ‘app.log.5’。 当前被写入的文件总是 ‘app.log’。 当此文件写满时，它会
     被关闭并重户名为 ‘app.log.1’，而如果文件 ‘app.log.1’, ‘app.log.2’ 等
     存在，则它们会被分别重命名为 ‘app.log.2’, ‘app.log.3’ 等等。

     3.6 版更變: 除了字符串值，也接受 *note Path: 32f. 对象作为
     `filename' 参数。

     3.9 版更變: 增加了 `errors' 形参。

      -- 成員函式: doRollover ()

          执行上文所描述的轮换。

      -- 成員函式: emit (record)

          将记录输出到文件，以适应上文所描述的轮换。


File: python.info,  Node: TimedRotatingFileHandler,  Next: SocketHandler,  Prev: RotatingFileHandler,  Up: logging handlers --- 日志处理程序

5.16.8.7 TimedRotatingFileHandler
.................................

*note TimedRotatingFileHandler: 959. 类位于 *note logging.handlers: ac.
模块，它支持基于特定时间间隔的磁盘日志文件轮换。

 -- 類別: logging.handlers.TimedRotatingFileHandler (filename, when='h',
          interval=1, backupCount=0, encoding=None, delay=False,
          utc=False, atTime=None, errors=None)

     返回一个新的 *note TimedRotatingFileHandler: 959. 类实例。 指定的文
     件会被打开并用作日志记录的流。 对于轮换操作它还会设置文件名前缀。 轮
     换的发生是基于 `when' 和 `interval' 的积。

     你可以使用 `when' 来指定 `interval' 的类型。 可能的值列表如下。 请
     注意它们不是大小写敏感的。

     值                   间隔类型                         如果/如何使用 `atTime'
                                                           
     ------------------------------------------------------------------------------------
                                                           
     ‘'S'’                秒                               忽略
                                                           
                                                           
     ‘'M'’                分钟                             忽略
                                                           
                                                           
     ‘'H'’                小时                             忽略
                                                           
                                                           
     ‘'D'’                天                               忽略
                                                           
                                                           
     ‘'W0'-'W6'’          工作日(0=星期一)                 用于计算初始轮换时间
                                                           
                                                           
     ‘'midnight'’         如果未指定 `atTime' 则在午夜执   用于计算初始轮换时间
                          行轮换，否则将使用 `atTime'。    
                          

     当使用基于星期的轮换时，星期一为 ’W0’，星期二为 ’W1’，以此类推直至
     星期日为 ’W6’。 在这种情况下，传入的 `interval' 值不会被使用。

     系统将通过为文件名添加扩展名来保存旧日志文件。 扩展名是基于日期和时
     间的，根据轮换间隔的长短使用 strftime 格式 ‘%Y-%m-%d_%H-%M-%S’ 或是
     其中有变动的部分。

     当首次计算下次轮换的时间时（即当处理程序被创建时），现有日志文件的
     上次被修改时间或者当前时间会被用来计算下次轮换的发生时间。

     如果 `utc' 参数为真值，将使用 UTC 时间；否则会使用本地时间。

     如果 `backupCount' 不为零，则最多将保留 `backupCount' 个文件，而如
     果当轮换发生时创建了更多的文件，则最旧的文件会被删除。 删除逻辑使用
     间隔时间来确定要删除的文件，因此改变间隔时间可能导致旧文件被继续保
     留。

     如果 `delay' 为真值，则会将文件打开延迟到首次调用 *note emit():
     2268. 的时候。

     如果 `atTime' 不为 ‘None’，则它必须是一个 ‘datetime.time’ 的实例，
     该实例指定轮换在一天内的发生时间，用于轮换被设为“在午夜”或“在每星期
     的某一天”之类的情况。 请注意在这些情况下，`atTime' 值实际上会被用于
     计算 `初始' 轮换，而后续轮换将会通过正常的间隔时间计算来得出。

     如果指定了 `errors'，它会被用来确定编码错误的处理方式。

          備註: 初始轮换时间的计算是在处理程序被初始化时执行的。 后续轮
          换时间的计算则仅在轮换发生时执行，而只有当提交输出时轮换才会发
          生。 如果不记住这一点，你就可能会感到困惑。 例如，如果设置时间
          间隔为“每分钟”，那并不意味着你总会看到（文件名中）带有间隔一分
          钟时间的日志文件；如果在应用程序执行期间，日志记录输出的生成频
          率高于每分钟一次，`那么' 你可以预期看到间隔一分钟时间的日志文
          件。 另一方面，如果（假设）日志记录消息每五分钟才输出一次，那
          么文件时间将会存在对应于没有输出（因而没有轮换）的缺失。

     3.4 版更變: 添加了 `atTime' 形参。

     3.6 版更變: 除了字符串值，也接受 *note Path: 32f. 对象作为
     `filename' 参数。

     3.9 版更變: 增加了 `errors' 形参。

      -- 成員函式: doRollover ()

          执行上文所描述的轮换。

      -- 成員函式: emit (record)

          将记录输出到文件，以适应上文所描述的轮换。

      -- 成員函式: getFilesToDelete ()

          Returns a list of filenames which should be deleted as part of
          rollover.  These are the absolute paths of the oldest backup
          log files written by the handler.


File: python.info,  Node: SocketHandler,  Next: DatagramHandler,  Prev: TimedRotatingFileHandler,  Up: logging handlers --- 日志处理程序

5.16.8.8 SocketHandler
......................

*note SocketHandler: 95a. 类位于 *note logging.handlers: ac. 模块，它会
将日志记录输出发送到网络套接字。 基类所使用的是 TCP 套接字。

 -- 類別: logging.handlers.SocketHandler (host, port)

     返回一个 *note SocketHandler: 95a. 类的新实例，该实例旨在与使用
     `host' 与 `port' 给定地址的远程主机进行通信。

     3.4 版更變: 如果 ‘port’ 指定为 ‘None’，会使用 ‘host’ 中的值来创建一
     个 Unix 域套接字 —— 在其他情况下，则会创建一个 TCP 套接字。

      -- 成員函式: close ()

          关闭套接字。

      -- 成員函式: emit ()

          对记录的属性字典执行封存并以二进制格式将其写入套接字。 如果套
          接字存在错误，则静默地丢弃数据包。 如果连接在此之前丢失，则重
          新建立连接。 要在接收端将记录解封并输出到 *note LogRecord:
          9ec.，请使用 *note makeLogRecord(): 2210. 函数。

      -- 成員函式: handleError ()

          处理在 *note emit(): 226d. 期间发生的错误。 最可能的原因是连接
          丢失。 关闭套接字以便我们能在下次事件时重新尝试。

      -- 成員函式: makeSocket ()

          这是一个工厂方法，它允许子类定义它们想要的套接字的准确类型。 默
          认实现会创建一个 TCP 套接字 (*note socket.SOCK_STREAM: d52.)。

      -- 成員函式: makePickle (record)

          将记录的属性字典封存为带有长度前缀的二进制格式，并将其返回以准
          备通过套接字进行传输。 此操作在细节上相当于:

               data = pickle.dumps(record_attr_dict, 1)
               datalen = struct.pack('>L', len(data))
               return datalen + data

          请注意封存操作不是绝对安全的。 如果你关心安全问题，你可能会想
          要重载此方法以实现更安全的机制。 例如，你可以使用 HMAC 对封存
          对象进行签名然后在接收端验证它们，或者你也可以在接收端禁用全局
          对象的解封操作。

      -- 成員函式: send (packet)

          将封存后的字节串 `packet' 发送到套接字。 所发送字节串的格式与
          *note makePickle(): 2270. 文档中的描述一致。

          此函数允许部分发送，这可能会在网络繁忙时发生。

      -- 成員函式: createSocket ()

          尝试创建一个套接字；失败时将使用指数化回退算法处理。 在失败初
          次发生时，处理程序将丢弃它正尝试发送的消息。 当后续消息交由同
          一实例处理时，它将不会尝试连接直到经过一段时间以后。 默认形参
          设置为初始延迟一秒，如果在延迟之后连接仍然无法建立，处理程序将
          每次把延迟翻倍直至达到 30 秒的最大值。

          此行为由下列处理程序属性控制:

             * ‘retryStart’ (初始延迟，默认为 1.0 秒)。

             * ‘retryFactor’ (倍数，默认为 2.0)。

             * ‘retryMax’ (最大延迟，默认为 30.0 秒)。

          这意味着如果远程监听器在处理程序被使用 `之后' 启动，你可能会丢
          失消息（因为处理程序在延迟结束之前甚至不会尝试连接，而在延迟期
          间静默地丢弃消息）。


File: python.info,  Node: DatagramHandler,  Next: SysLogHandler,  Prev: SocketHandler,  Up: logging handlers --- 日志处理程序

5.16.8.9 DatagramHandler
........................

*note DatagramHandler: 95b. 类位于 *note logging.handlers: ac. 模块，它
继承自 *note SocketHandler: 95a.，支持通过 UDP 套接字发送日志记录消息。

 -- 類別: logging.handlers.DatagramHandler (host, port)

     返回一个 *note DatagramHandler: 95b. 类的新实例，该实例旨在与使用
     `host' 与 `port' 给定地址的远程主机进行通信。

     3.4 版更變: 如果 ‘port’ 指定为 ‘None’，会使用 ‘host’ 中的值来创建一
     个 Unix 域套接字 —— 在其他情况下，则会创建一个 UDP 套接字。

      -- 成員函式: emit ()

          对记录的属性字典执行封存并以二进制格式将其写入套接字。 如果套
          接字存在错误，则静默地丢弃数据包。 要在接收端将记录解封并输出
          到 *note LogRecord: 9ec.，请使用 *note makeLogRecord(): 2210.
          函数。

      -- 成員函式: makeSocket ()

          *note SocketHandler: 95a. 的工厂方法会在此被重载以创建一个 UDP
          套接字 (*note socket.SOCK_DGRAM: d51.)。

      -- 成員函式: send (s)

          将封存后的字节串发送到套接字。 所发送字节串的格式与 *note
          SocketHandler.makePickle(): 2270. 文档中的描述一致。


File: python.info,  Node: SysLogHandler,  Next: NTEventLogHandler,  Prev: DatagramHandler,  Up: logging handlers --- 日志处理程序

5.16.8.10 SysLogHandler
.......................

*note SysLogHandler: afb. 类位于 *note logging.handlers: ac. 模块，它支
持将日志记录消息发送到远程或本地 Unix syslog。

 -- 類別: logging.handlers.SysLogHandler (address=('localhost',
          SYSLOG_UDP_PORT), facility=LOG_USER,
          socktype=socket.SOCK_DGRAM)

     返回一个 *note SysLogHandler: afb. 类的新实例用来与通过 `address' 以
     ‘(host, port)’ 元组形式给出地址的远程 Unix 机器进行通讯。 如果未指
     定 `address'，则使用 ‘('localhost', 514)’。 该地址会被用于打开套接
     字。 提供 ‘(host, port)’ 元组的一种替代方式是提供字符串形式的地址，
     例如 ’/dev/log’。 在这种情况下，会使用 Unix 域套接字将消息发送到
     syslog。 如果未指定 `facility'，则使用 ‘LOG_USER’。 打开的套接字类
     型取决于 `socktype' 参数，该参数的默认值为 *note socket.SOCK_DGRAM:
     d51. 即打开一个 UDP 套接字。 要打开一个 TCP 套接字（用来配合较新的
     syslog 守护程序例如 rsyslog 使用），请指定值为 *note
     socket.SOCK_STREAM: d52.。

     请注意如果你的服务器不是在 UDP 端口 514 上进行侦听，则 *note
     SysLogHandler: afb. 可能无法正常工作。 在这种情况下，请检查你应当为
     域套接字所使用的地址 —— 它依赖于具体的系统。 例如，在 Linux 上通常
     为 ’/dev/log’ 而在 OS/X 上则为 ’/var/run/syslog’。 你需要检查你的系
     统平台并使用适当的地址（如果你的应用程序需要在多个平台上运行则可能
     需要在运行时进行这样的检查）。 在 Windows 上，你大概必须要使用 UDP
     选项。

     3.2 版更變: 添加了 `socktype'。

      -- 成員函式: close ()

          关闭连接远程主机的套接字。

      -- 成員函式: emit (record)

          记录会被格式化，然后发送到 syslog 服务器。 如果存在异常信息，
          则它 `不会' 被发送到服务器。

          3.2.1 版更變: (参见: bpo-12168(1)。) 在较早的版本中，发送至
          syslog 守护程序的消息总是以一个 NUL 字节结束，因为守护程序的早
          期版本期望接收一个以 NUL 结束的消息 —— 即使它不包含于对应的规
          范说明 ( RFC 5424(2))。 这些守护程序的较新版本不再期望接收 NUL
          字节，如果其存在则会将其去除，而最新的守护程序（更紧密地遵循
          RFC 5424）会将 NUL 字节作为消息的一部分传递出去。

          为了在面对所有这些不同守护程序行为时能够更方便地处理 syslog 消
          息，通过使用类层级属性 ‘append_nul’，添加 NUL 字节的操作已被作
          为可配置项。 该属性默认为 ‘True’ (保留现有行为) 但可在
          ‘SysLogHandler’ 实例上设为 ‘False’ 以便让实例 `不会' 添加 NUL
          结束符。

          3.3 版更變: (参见: bpo-12419(3)。) 在较早的版本中，没有
          "ident" 或 "tag" 前缀工具可以用来标识消息的来源。 现在则可以使
          用一个类层级属性来设置它，该属性默认为 ‘""’ 表示保留现有行为，
          但可在 ‘SysLogHandler’ 实例上重载以便让实例不会为所处理的每条
          消息添加标识。 请注意所提供的标识必须为文本而非字节串，并且它
          会被原封不动地添加到消息中。

      -- 成員函式: encodePriority (facility, priority)

          将功能和优先级编码为一个整数。 你可以传入字符串或者整数 —— 如
          果传入的是字符串，则会使用内部的映射字典将其转换为整数。

          符号 ‘LOG_’ 的值在 *note SysLogHandler: afb. 中定义并且是
          ‘sys/syslog.h’ 头文件中所定义值的镜像。

          `优先级'

          名称（字符串）                 符号值
                                         
          ---------------------------------------------------
                                         
          ‘alert’                        LOG_ALERT
                                         
                                         
          ‘crit’ 或 ‘critical’           LOG_CRIT
                                         
                                         
          ‘debug’                        LOG_DEBUG
                                         
                                         
          ‘emerg’ 或 ‘panic’             LOG_EMERG
                                         
                                         
          ‘err’ 或 ‘error’               LOG_ERR
                                         
                                         
          ‘info’                         LOG_INFO
                                         
                                         
          ‘notice’                       LOG_NOTICE
                                         
                                         
          ‘warn’ 或 ‘warning’            LOG_WARNING
                                         

          `设备'

          名称（字符串）      符号值
                              
          ----------------------------------------
                              
          ‘auth’              LOG_AUTH
                              
                              
          ‘authpriv’          LOG_AUTHPRIV
                              
                              
          ‘cron’              LOG_CRON
                              
                              
          ‘daemon’            LOG_DAEMON
                              
                              
          ‘ftp’               LOG_FTP
                              
                              
          ‘kern’              LOG_KERN
                              
                              
          ‘lpr’               LOG_LPR
                              
                              
          ‘mail’              LOG_MAIL
                              
                              
          ‘news’              LOG_NEWS
                              
                              
          ‘syslog’            LOG_SYSLOG
                              
                              
          ‘user’              LOG_USER
                              
                              
          ‘uucp’              LOG_UUCP
                              
                              
          ‘local0’            LOG_LOCAL0
                              
                              
          ‘local1’            LOG_LOCAL1
                              
                              
          ‘local2’            LOG_LOCAL2
                              
                              
          ‘local3’            LOG_LOCAL3
                              
                              
          ‘local4’            LOG_LOCAL4
                              
                              
          ‘local5’            LOG_LOCAL5
                              
                              
          ‘local6’            LOG_LOCAL6
                              
                              
          ‘local7’            LOG_LOCAL7
                              

      -- 成員函式: mapPriority (levelname)

          将日志记录级别名称映射到 syslog 优先级名称。 如果你使用自定义
          级别，或者如果默认算法不适合你的需要，你可能需要重载此方法。 默
          认算法将 ‘DEBUG’, ‘INFO’, ‘WARNING’, ‘ERROR’ 和 ‘CRITICAL’ 映
          射到等价的 syslog 名称，并将所有其他级别名称映射到 ’warning’。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue12168

   (2) https://tools.ietf.org/html/rfc5424.html

   (3) https://bugs.python.org/issue12419


File: python.info,  Node: NTEventLogHandler,  Next: SMTPHandler,  Prev: SysLogHandler,  Up: logging handlers --- 日志处理程序

5.16.8.11 NTEventLogHandler
...........................

*note NTEventLogHandler: 2280. 类位于 *note logging.handlers: ac. 模块，
它支持将日志记录消息发送到本地 Windows NT, Windows 2000 或 Windows XP 事
件日志。 在你使用它之前，你需要安装 Mark Hammond 的 Python Win32 扩展。

 -- 類別: logging.handlers.NTEventLogHandler (appname, dllname=None,
          logtype='Application')

     返回一个 *note NTEventLogHandler: 2280. 类的新实例。 `appname' 用来
     定义出现在事件日志中的应用名称。 将使用此名称创建适当的注册表条目。
     `dllname' 应当给出要包含在日志中的消息定义的 .dll 或 .exe 的完整限
     定路径名称（如未指定则会使用 ‘'win32service.pyd'’ —— 此文件随 Win32
     扩展安装且包含一些基本的消息定义占位符。 请注意使用这些占位符将使你
     的事件日志变得很大，因为整个消息源都会被放入日志。 如果你希望有较小
     的日志，你必须自行传入包含你想要在事件日志中使用的消息定义的 .dll 或
     .exe 名称）。 `logtype' 为 ‘'Application'’, ‘'System'’ 或
     ‘'Security'’ 之一，且默认值为 ‘'Application'’。

      -- 成員函式: close ()

          这时，你就可以从注册表中移除作为事件日志条目来源的应用名称。 但
          是，如果你这样做，你将无法如你所预期的那样在事件日志查看器中看
          到这些事件 —— 它必须能访问注册表来获取 .dll 名称。 当前版本并
          不会这样做。

      -- 成員函式: emit (record)

          确定消息 ID，事件类别和事件类型，然后将消息记录到 NT 事件日志
          中。

      -- 成員函式: getEventCategory (record)

          返回记录的事件类别。 如果你希望指定你自己的类别就要重载此方法
          。 此版本将返回 0。

      -- 成員函式: getEventType (record)

          返回记录的事件类型。 如果你希望指定你自己的类型就要重载此方法
          。 此版本将使用处理程序的 typemap 属性来执行映射，该属性在
          *note __init__(): e23. 被设置为一个字典，其中包含 ‘DEBUG’,
          ‘INFO’, ‘WARNING’, ‘ERROR’ 和 ‘CRITICAL’ 的映射。 如果你使用你
          自己的级别，你将需要重载此方法或者在处理程序的 `typemap' 属性
          中放置一个合适的字典。

      -- 成員函式: getMessageID (record)

          返回记录的消息 ID。 如果你使用你自己的消息，你可以通过将 `msg'
          传给日志记录器作为 ID 而非格式字符串实现此功能。 然后，你可以
          在这里使用字典查找来获取消息 ID。 此版本将返回 1，是
          ‘win32service.pyd’ 中的基本消息 ID。


File: python.info,  Node: SMTPHandler,  Next: MemoryHandler,  Prev: NTEventLogHandler,  Up: logging handlers --- 日志处理程序

5.16.8.12 SMTPHandler
.....................

*note SMTPHandler: 2288. 类位于 *note logging.handlers: ac. 模块，它支持
将日志记录消息通过 SMTP 发送到一个电子邮件地址。

 -- 類別: logging.handlers.SMTPHandler (mailhost, fromaddr, toaddrs,
          subject, credentials=None, secure=None, timeout=1.0)

     返回一个 *note SMTPHandler: 2288. 类的新实例。 该实例使用电子邮件的
     发件人、收件人地址和主题行进行初始化。 `toaddrs' 应当为字符串列表。
     要指定一个非标准 SMTP 端口，请使用 (host, port) 元组格式作为
     `mailhost' 参数。 如果你使用一个字符串，则会使用标准 SMTP 端口。 如
     果你的 SMTP 服务器要求验证，你可以指定一个 (username, password) 元
     组作为 `credentials' 参数。

     要指定使用安全协议 (TLS)，请传入一个元组作为 `secure' 参数。 这将仅
     在提供了验证凭据时才能被使用。 元组应当或是一个空元组，或是一个包含
     密钥文件名的单值元组，或是一个包含密钥文件和证书文件的 2 值元组。 （
     此元组会被传给 *note smtplib.SMTP.starttls(): b5c. 方法。）

     可以使用 `timeout' 参数为与 SMTP 服务器的通信指定超时限制。

     3.3 版新加入: 增加了 `timeout' 参数。

      -- 成員函式: emit (record)

          对记录执行格式化并将其发送到指定的地址。

      -- 成員函式: getSubject (record)

          如果你想要指定一个基于记录的主题行，请重载此方法。


File: python.info,  Node: MemoryHandler,  Next: HTTPHandler,  Prev: SMTPHandler,  Up: logging handlers --- 日志处理程序

5.16.8.13 MemoryHandler
.......................

*note MemoryHandler: 223f. 类位于 *note logging.handlers: ac. 模块，它支
持在内存中缓冲日志记录，并定期将其刷新到 `target' 处理程序中。 刷新会在
缓冲区满的时候，或是在遇到特定或更高严重程度事件的时候发生。

*note MemoryHandler: 223f. 是更通用的 *note BufferingHandler: 228d. 的子
类，后者属于抽象类。 它会在内存中缓冲日志记录。 当每条记录被添加到缓冲区
时，会通过调用 ‘shouldFlush()’ 来检查缓冲区是否应当刷新。 如果应当刷新，
则要使用 ‘flush()’ 来执行刷新。

 -- 類別: logging.handlers.BufferingHandler (capacity)

     使用指定容量的缓冲区初始化处理程序。 这里，`capacity' 是指缓冲的日
     志记录数量。

      -- 成員函式: emit (record)

          将记录添加到缓冲区。 如果 *note shouldFlush(): 228f. 返回真值
          ，则会调用 *note flush(): 2290. 来处理缓冲区。

      -- 成員函式: flush ()

          你可以重载此方法来实现自定义的刷新行为。 此版本只是将缓冲区清
          空。

      -- 成員函式: shouldFlush (record)

          如果缓冲区容量已满则返回 ‘True’。 可以重载此方法以实现自定义的
          刷新策略。

 -- 類別: logging.handlers.MemoryHandler (capacity, flushLevel=ERROR,
          target=None, flushOnClose=True)

     返回一个 *note MemoryHandler: 223f. 类的新实例。 该实例使用
     `capacity' 指定的缓冲区大小（要缓冲的记录数量）来初始化。 如果
     `flushLevel' 未指定，则使用 ‘ERROR’。 如果未指定 `target'，则需要在
     此处理程序执行任何实际操作之前使用 *note setTarget(): 2291. 来设置
     目标。 如果 `flushOnClose' 指定为 ‘False’，则当处理程序被关闭时 `不
     会' 刷新缓冲区。 如果未指定或指定为 ‘True’，则当处理程序被关闭时将
     会发生之前的缓冲区刷新行为。

     3.6 版更變: 增加了 `flushOnClose' 形参。

      -- 成員函式: close ()

          调用 *note flush(): 2293.，设置目标为 ‘None’ 并清空缓冲区。

      -- 成員函式: flush ()

          对于 *note MemoryHandler: 223f.，刷新是指将缓冲的记录发送到目
          标，如果存在目标的话。 当此行为发生时缓冲区也将被清空。 如果你
          想要不同的行为请重载此方法。

      -- 成員函式: setTarget (target)

          设置此处理程序的目标处理程序。

      -- 成員函式: shouldFlush (record)

          检测缓冲区是否已满或是有记录为 `flushLevel' 或更高级别。


File: python.info,  Node: HTTPHandler,  Next: QueueHandler,  Prev: MemoryHandler,  Up: logging handlers --- 日志处理程序

5.16.8.14 HTTPHandler
.....................

*note HTTPHandler: 802. 类位于 *note logging.handlers: ac. 模块，它支持
使用 ‘GET’ 或 ‘POST’ 语义将日志记录消息发送到 Web 服务器。

 -- 類別: logging.handlers.HTTPHandler (host, url, method='GET',
          secure=False, credentials=None, context=None)

     返回一个 *note HTTPHandler: 802. 类的新实例。 `host' 可以为
     ‘host:port’ 的形式，如果你需要使用指定端口号的话。 如果没有指定
     `method'，则会使用 ‘GET’。 如果 `secure' 为真值，则将使用 HTTPS 连
     接。 `context' 形参可以设为一个 *note ssl.SSLContext: 4e9. 实例以配
     置用于 HTTPS 连接的 SSL 设置。 如果指定了 `credentials'，它应当为包
     含 userid 和 password 的二元组，该元组将被放入使用 Basic 验证的
     HTTP ’Authorization’ 标头中。 如果你指定了 credentials，你还应当指
     定 secure=True 这样你的 userid 和 password 就不会以明文在线路上传输
     。

     3.5 版更變: 增加了 `context' 形参。

      -- 成員函式: mapLogRecord (record)

          基于 ‘record’ 提供一个字典，它将被执行 URL 编码并发送至 Web 服
          务器。 默认实现仅返回 ‘record.__dict__’。 在只需将 *note
          LogRecord: 9ec. 的某个子集发送至 Web 服务器，或者需要对发送至
          服务器的内容进行更多定制时可以重载此方法。

      -- 成員函式: emit (record)

          将记录以经 URL 编码的形式发送至 Web 服务器。 会使用 *note
          mapLogRecord(): 2297. 方法来将要发送的记录转换为字典。

          備註: 由于记录发送至 Web 服务器所需的预处理与通用的格式化操作
          不同，使用 *note setFormatter(): 21f5. 来指定一个 *note
          Formatter: 21de. 用于 *note HTTPHandler: 802. 是没有效果的。 此
          处理程序不会调用 *note format(): 21ff.，而是调用 *note
          mapLogRecord(): 2297. 然后再调用 *note
          urllib.parse.urlencode(): 87a. 来以适合发送至 Web 服务器的形式
          对字典进行编码。


File: python.info,  Node: QueueHandler,  Next: QueueListener,  Prev: HTTPHandler,  Up: logging handlers --- 日志处理程序

5.16.8.15 QueueHandler
......................

3.2 版新加入.

*note QueueHandler: 229b. 类位于 *note logging.handlers: ac. 模块，它支
持将日志记录消息发送到一个队列，例如在 *note queue: da. 或 *note
multiprocessing: b7. 模块中实现的队列。

配合 *note QueueListener: 803. 类使用，*note QueueHandler: 229b. 可用来
使处理程序在与执行日志记录的线程不同的线程上完成工作。 这对 Web 应用程序
以及其他服务于客户端的线程需要尽可能快地响应的服务应用程序来说很重要，任
何潜在的慢速操作（例如通过 *note SMTPHandler: 2288. 发送邮件）都要在单独
的线程上完成。

 -- 類別: logging.handlers.QueueHandler (queue)

     返回一个 *note QueueHandler: 229b. 类的新实例。 该实例使用队列来初
     始化以向其发送消息。 `queue' 可以为任何队列类对象；它由 *note
     enqueue(): 229c. 方法来使用，该方法需要知道如何向其发送消息。 队列
     `不要求' 具有任务跟踪 API，这意味着你可以为 `queue' 使用 *note
     SimpleQueue: 4cc. 实例。

      -- 成員函式: emit (record)

          将准备 LogRecord 的结果排入队列。 如果发生了异常（例如由于有界
          队列已满），则会调用 *note handleError(): 21fd. 方法来处理错误
          。 这可能导致记录被静默地丢弃 (如果 ‘logging.raiseExceptions’
          为 ‘False’) 或者消息被打印到 ‘sys.stderr’ (如果
          ‘logging.raiseExceptions’ 为 ‘True’)。

      -- 成員函式: prepare (record)

          准备用于队列的记录。 此方法返回的对象会被排入队列。

          基本实现会格式化记录以合并消息、参数以及可能存在的异常信息。 它
          还会从记录中原地移除无法封存的条目。

          如果你想要将记录转换为 dict 或 JSON 字符串，或者发送记录被修改
          后的副本而让初始记录保持原样，则你可能会想要重载此方法。

      -- 成員函式: enqueue (record)

          使用 ‘put_nowait()’ 将记录排入队列；如果你想要使用阻塞行为，或
          超时设置，或自定义的队列实现，则你可能会想要重载此方法。


File: python.info,  Node: QueueListener,  Prev: QueueHandler,  Up: logging handlers --- 日志处理程序

5.16.8.16 QueueListener
.......................

3.2 版新加入.

*note QueueListener: 803. 类位于 *note logging.handlers: ac. 模块，它支
持从一个队列接收日志记录消息，例如在 *note queue: da. 或 *note
multiprocessing: b7. 模块中实现的队列。 消息是在内部线程中从队列接收并在
同一线程上传递到一个或多个处理程序进行处理的。 尽管 *note QueueListener:
803. 本身并不是一个处理程序，但由于它要与 *note QueueHandler: 229b. 配合
工作，因此也在此处介绍。

配合 *note QueueHandler: 229b. 类使用，*note QueueListener: 803. 可用来
使处理程序在与执行日志记录的线程不同的线程上完成工作。 这对 Web 应用程序
以及其他服务与客户端的线程需要尽可能快地响应的服务应用程序来说很重要，任
何潜在的慢速动作（例如通过 *note SMTPHandler: 2288. 发送邮件）都要在单独
的线程上完成。

 -- 類別: logging.handlers.QueueListener (queue, *handlers,
          respect_handler_level=False)

     返回一个 *note QueueListener: 803. 类的新实例。 该实例初始化时要传
     入一个队列以向其发送消息，还要传入一个处理程序列表用来处理放置在队
     列中的条目。 队列可以是任何队列类对象；它会被原样传给 *note
     dequeue(): 22a1. 方法，该方法需要知道如何从其获取消息。 队列 `不要
     求' 具有任务跟踪 API（但如提供则会使用它），这意味着你可以为
     `queue' 使用 *note SimpleQueue: 4cc. 实例。

     如果 ‘respect_handler_level’ 为 ‘True’，则在决定是否将消息传递给处
     理程序之前会遵循处理程序的级别（与消息的级别进行比较）；在其他情况
     下，其行为与之前的 Python 版本一致 —— 总是将每条消息传递给每个处理
     程序。

     3.5 版更變: 增加了 ‘respect_handler_level’ 参数。

      -- 成員函式: dequeue (block)

          从队列移出一条记录并将其返回，可以选择阻塞。

          基本实现使用 ‘get()’。 如果你想要使用超时设置或自定义的队列实
          现，则你可能会想要重载此方法。

      -- 成員函式: prepare (record)

          准备一条要处理的记录。

          该实现只是返回传入的记录。 如果你想要对记录执行任何自定义的
          marshal 操作或在将其传给处理程序之前进行调整，则你可能会想要重
          载此方法。

      -- 成員函式: handle (record)

          处理一条记录。

          此方法简单地循环遍历处理程序，向它们提供要处理的记录。 实际传
          给处理程序的对象就是从 *note prepare(): 22a2. 返回的对象。

      -- 成員函式: start ()

          启动监听器。

          此方法启动一个后台线程来监视 LogRecords 队列以进行处理。

      -- 成員函式: stop ()

          停止监听器。

          此方法要求线程终止，然后等待它完成终止操作。 请注意在你的应用
          程序退出之前如果你没有调用此方法，则可能会有一些记录在留在队列
          中，它们将不会被处理。

      -- 成員函式: enqueue_sentinel ()

          将一个标记写入队列以通知监听器退出。 此实现会使用
          ‘put_nowait()’。 如果你想要使得超时设置或自定义的队列实现，则
          你可能会想要重载此方法。

          3.3 版新加入.

也參考
......

模块 *note logging: aa.

     日志记录模块的 API 参考。

模块 *note logging.config: ab.

     日志记录模块的配置 API 。


File: python.info,  Node: getpass --- 便携式密码输入工具,  Next: curses --- 终端字符单元显示的处理,  Prev: logging handlers --- 日志处理程序,  Up: 通用操作系统服务

5.16.9 ‘getpass’ — 便携式密码输入工具
-------------------------------------

`源代码:' Lib/getpass.py(1)

__________________________________________________________________

*note getpass: 86. 模块提供了两个函数：

 -- 函式: getpass.getpass (prompt='Password: ', stream=None)

     提示用户输入一个密码且不会回显。 用户会看到字符串 `prompt' 作为提示
     ，其默认值为 ‘'Password: '’。 在 Unix 上，如有必要提示会使用替换错
     误句柄写入到文件类对象 `stream'。 `stream' 默认指向控制终端
     (‘/dev/tty’)，如果不可用则指向 ‘sys.stderr’ (此参数在 Windows 上会
     被忽略)。

     如果回显自由输入不可用则 getpass() 将回退为打印一条警告消息到
     `stream' 并且从 ‘sys.stdin’ 读取同时发出 *note GetPassWarning:
     22aa.。

          備註: 如果你从 IDLE 内部调用 getpass，输入可能是在你启动 IDLE
          的终端中而非在 IDLE 窗口本身中完成。

 -- 例外: getpass.GetPassWarning

     一个当密码输入可能被回显时发出的 *note UserWarning: 1861. 子类。

 -- 函式: getpass.getuser ()

     返回用户的“登录名称”。

     此函数会按顺序检查环境变量 ‘LOGNAME’, ‘USER’, ‘LNAME’ 和
     ‘USERNAME’，并返回其中第一个被设置为非空字符串的值。 如果均未设置，
     则在支持 *note pwd: d6. 模块的系统上将返回来自密码数据库的登录名，
     否则将引发一个异常。

     通常情况下，此函数应优先于 *note os.getlogin(): 204e. 使用。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/getpass.py


File: python.info,  Node: curses --- 终端字符单元显示的处理,  Next: curses textpad --- 用于 curses 程序的文本输入控件,  Prev: getpass --- 便携式密码输入工具,  Up: 通用操作系统服务

5.16.10 ‘curses’ — 终端字符单元显示的处理
-----------------------------------------

__________________________________________________________________

*note curses: 2b. 模块提供了 curses 库的接口，这是可移植高级终端处理的事
实标准。

虽然 curses 在 Unix 环境中使用最为广泛，但也有适用于 Windows，DOS 以及其
他可能的系统的版本。此扩展模块旨在匹配 ncurses 的 API，这是一个部署在
Linux 和 Unix 的 BSD 变体上的开源 curses 库。

     備註: 每当文档提到 `字符' 时，它可以被指定为一个整数，一个单字符
     Unicode 字符串或者一个单字节的字节字符串。

     每当此文档提到 `字符串' 时，它可以被指定为一个 Unicode 字符串或者一
     个字节字符串。

     備註: 从 5.4 版本开始，ncurses 库使用 ‘nl_langinfo’ 函数来决定如何
     解释非 ASCII 数据。这意味着你需要在程序中调用 *note
     locale.setlocale(): 2166. 函数，并使用一种系统中可用的编码方法来编
     码 Unicode 字符串。这个例子使用了系统默认的编码:

          import locale
          locale.setlocale(locale.LC_ALL, '')
          code = locale.getpreferredencoding()

     然后使用 `code' 作为 *note str.encode(): 170. 调用的编码。

也參考
......

模块 *note curses.ascii: 2c.

     在 ASCII 字符上工作的工具，无论你的区域设置是什么。

模块 *note curses.panel: 2d.

     为 curses 窗口添加深度的面板栈扩展。

模块 *note curses.textpad: 2e.

     用于使 curses 支持 ‘Emacs’ 式绑定的可编辑文本部件。

*note 用 Python 进行 Curses 编程: 22ad.

     关于配合 Python 使用 curses 的教学材料，由 Andrew Kuchling 和 Eric
     Raymond 撰写。

Python 源码发布包的 Tools/demo/(1) 目录包含了一些使用此模块所提供的
curses 绑定的示例程序。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Tools/demo/


File: python.info,  Node: 函数<4>,  Next: Window 对象,  Up: curses --- 终端字符单元显示的处理

5.16.10.1 函数
..............

*note curses: 2b. 模块定义了以下异常：

 -- 例外: curses.error

     当 curses 库中函数返回一个错误时引发的异常。

     備註: 只要一个函数或方法的 `x' 或 `y' 参数是可选项，它们会默认为当
     前光标位置。 而当 `attr' 是可选项时，它会默认为 ‘A_NORMAL’。

*note curses: 2b. 模块定义了以下函数：

 -- 函式: curses.baudrate ()

     以每秒比特数为单位返回终端输出速度。 在软件终端模拟器上它将具有一个
     固定的最高值。 此函数出于历史原因被包括；在以前，它被用于写输出循环
     以提供时间延迟，并偶尔根据线路速度来改变接口。

 -- 函式: curses.beep ()

     发出短促的提醒声音。

 -- 函式: curses.can_change_color ()

     根据程序员能否改变终端显示的颜色返回 ‘True’ 或 ‘False’。

 -- 函式: curses.cbreak ()

     进入 cbreak 模式。 在 cbreak 模式（有时也称为“稀有”模式）通常的 tty
     行缓冲会被关闭并且字符可以被一个一个地读取。 但是，与原始模式不同，
     特殊字符（中断、退出、挂起和流程控制）会在 tty 驱动和调用程序上保留
     其效果。 首先调用 *note raw(): 22b5. 然后调用 *note cbreak(): 22b4.
     会将终端置于 cbreak 模式。

 -- 函式: curses.color_content (color_number)

     返回颜色值 `color_number' 中红、绿和蓝（RGB）分量的强度，此强度值必
     须介于 ‘0’ 和 ‘COLORS - 1’ 之间。 返回一个 3 元组，其中包含给定颜色
     的 R,G,B 值，它们必须介于 ‘0’ (无分量) 和 ‘1000’ (最大分量) 之间。

 -- 函式: curses.color_pair (pair_number)

     返回用于以指定颜色对显示文本的属性值。 仅支持前 256 个颜色对。 该属
     性值可与 ‘A_STANDOUT’, ‘A_REVERSE’ 以及其他 ‘A_*’ 属性组合使用。
     *note pair_number(): 22b8. 是此函数的对应操作。

 -- 函式: curses.curs_set (visibility)

     设置光标状态。 `visibility' 可设为 ‘0’, ‘1’ 或 ‘2’ 表示不可见、正常
     与高度可见。 如果终端支持所请求的可见性，则返回之前的光标状态；否则
     会引发异常。 在许多终端上，“正常可见”模式为下划线光标而“高度可见”模
     式为方块形光标。

 -- 函式: curses.def_prog_mode ()

     将当前终端模式保存为 "program" 模式，即正在运行的程序使用 curses 的
     模式。 （与其相对的是 "shell" 模式，即程序不使用 curses。） 对
     *note reset_prog_mode(): 22bb. 的后续调用将恢复此模式。

 -- 函式: curses.def_shell_mode ()

     将当前终端模式保存为 "shell" 模式，即正在运行的程序不使用 curses 的
     模式。 （与其相对的是 "program" 模式，即程序使用 功能。） 对 *note
     reset_shell_mode(): 22bd. 的后续调用将恢复此模式。

 -- 函式: curses.delay_output (ms)

     在输出中插入 `ms' 毫秒的暂停。

 -- 函式: curses.doupdate ()

     更新物理屏幕。 curses 库会保留两个数据结构，一个代表当前物理屏幕的
     内容以及一个虚拟屏幕代表需要的后续状态。 *note doupdate(): 22bf. 整
     体更新物理屏幕以匹配虚拟屏幕。

     虚拟屏幕可以通过在写入操作例如在一个窗口上执行 *note addstr():
     22c0. 之后调用 *note noutrefresh(): 22c1. 来刷新。 普通的 *note
     refresh(): 22c2. 调用只是简单的 ‘noutrefresh()’ 加 ‘doupdate()’；如
     果你需要更新多个窗口，你可以通过在所有窗口上发出 ‘noutrefresh()’ 调
     用再加单次 ‘doupdate()’ 来提升性能并可减少屏幕闪烁。

 -- 函式: curses.echo ()

     进入 echo 模式。 在 echo 模式下，输入的每个字符都会在输入后回显到屏
     幕上。

 -- 函式: curses.endwin ()

     撤销库的初始化，使终端返回正常状态。

 -- 函式: curses.erasechar ()

     将用户的当前擦除字符以单字节字节串对象的形式返回。 在 Unix 操作系统
     下这是 curses 程序用来控制 tty 的属性，而不是由 curses 库本身来设置
     的。

 -- 函式: curses.filter ()

     如果要使用 *note filter(): 22c6. 例程，它必须在调用 *note
     initscr(): 22c7. 之前被调用。 其效果是在这些调用期间， ‘LINES’ 会被
     设为 ‘1’；‘clear’, ‘cup’, ‘cud’, ‘cud1’, ‘cuu1’, ‘cuu’, ‘vpa’ 等功
     能会被禁用；而 ‘home’ 字符串会被设为 ‘cr’ 的值。 其影响是光标会被限
     制在当前行内，屏幕刷新也是如此。 这可被用于启用单字符模式的行编辑而
     不触及屏幕的其余部分。

 -- 函式: curses.flash ()

     闪烁屏幕。 也就是将其改为反显并在很短的时间内将其改回原状。 有些人
     更喜欢这样的‘视觉响铃’而非 *note beep(): 22b2. 所产生的听觉提醒信号
     。

 -- 函式: curses.flushinp ()

     刷新所有输入缓冲区。 这会丢弃任何已被用户输入但尚未被程序处理的预输
     入内容。

 -- 函式: curses.getmouse ()

     在 *note getch(): 22cb. 返回 ‘KEY_MOUSE’ 以发出鼠标事件信号之后，应
     当调用此方法来获取加入队列的鼠标事件，事件以一个 5 元组 ‘(id, x, y,
     z, bstate)’ 来表示。 `id' 为用于区分多个设置的 ID 值， `x', `y',
     `z' 为事件的坐标。 (`z' 目前未被使用。) `bstate' 为一个整数值，其各
     比特位将设置用于表示事件类型，并将是下列常量中一个或多个按位 OR 的
     结果，其中 `n' 是以 1 至 4 表示的键号: ‘BUTTONn_PRESSED’,
     ‘BUTTONn_RELEASED’, ‘BUTTONn_CLICKED’, ‘BUTTONn_DOUBLE_CLICKED’,
     ‘BUTTONn_TRIPLE_CLICKED’, ‘BUTTON_SHIFT’, ‘BUTTON_CTRL’,
     ‘BUTTON_ALT’。

 -- 函式: curses.getsyx ()

     将当前虚拟屏幕光标的坐标作为元组 ‘(y, x)’ 返回。 如果 *note
     leaveok: 22cd. 当前为 ‘True’，则返回 ‘(-1, -1)’。

 -- 函式: curses.getwin (file)

     读取由之前的 ‘putwin()’ 调用存放在文件中的窗口相关数据。 该例程随后
     将使用该数据创建并初始化一个新窗口，并返回该新窗口对象。

 -- 函式: curses.has_colors ()

     如果终端能显示彩色则返回 ‘True’；否则返回 ‘False’。

 -- 函式: curses.has_ic ()

     如果终端具有插入和删除字符的功能则返回 ‘True’。 此函数仅是出于历史
     原因而被包括的，因为所有现代软件终端模拟器都具有这些功能。

 -- 函式: curses.has_il ()

     如果终端具有插入和删除字符功能，或者能够使用滚动区域来模拟这些功能
     则返回 ‘True’。 此函数仅是出于历史原因而被包括的，因为所有现代软件
     终端模拟器都具有这些功能。

 -- 函式: curses.has_key (ch)

     接受一个键值 `ch'，并在当前终端类型能识别出具有该值的键时返回
     ‘True’。

 -- 函式: curses.halfdelay (tenths)

     用于半延迟模式，与 cbreak 模式的类似之处是用户所键入的字符会立即对
     程序可用。 但是，在阻塞 `tenths' 个十分之一秒之后，如果还未输入任何
     内容则将引发异常。 `tenths' 值必须为 ‘1’ 和 ‘255’ 之间的数字。 使用
     *note nocbreak(): 22d4. 可退出半延迟模式。

 -- 函式: curses.init_color (color_number, r, g, b)

     更改某个颜色的定义，接受要更改的颜色编号以及三个 RGB 值（表示红绿蓝
     三分量的强度）。 `color_number' 值必须为 ‘0’ 和 ‘COLORS - 1’ 之间的
     数字。 `r', `g', `b' 值必须为 ‘0’ 和 ‘1000’ 之间的数字。 当使用
     *note init_color(): 22d5. 时，出现在屏幕上的对应颜色会立即按照新定
     义来更改。 此函数在大多数终端上都是无操作的；它仅会在 *note
     can_change_color(): 22b3. 返回 ‘True’ 时生效。

 -- 函式: curses.init_pair (pair_number, fg, bg)

     更改某个颜色对的定义。 它接受三个参数：要更改的颜色对编号，前景色编
     号和背景色编号。 `pair_number' 值必须为 ‘1’ 和 ‘COLOR_PAIRS - 1’ 之
     间的数字（并且 ‘0’ 号颜色对固定为黑底白字而无法更改）。 `fg' 和
     `bg' 参数必须为 ‘0’ 和 ‘COLORS - 1’ 之间的数字，或者在调用 *note
     use_default_colors(): 22d7. 之后则为 ‘-1’。 如果颜色对之前已被初始
     化，则屏幕会被刷新使得出现在屏幕上的该颜色会立即按照新定义来更改。

 -- 函式: curses.initscr ()

     初始化库。 返回代表整个屏幕的 *note 窗口: 22d8. 对象。

          備註: 如果打开终端时发生错误，则下层的 curses 库可能会导致解释
          器退出。

 -- 函式: curses.is_term_resized (nlines, ncols)

     如果 *note resize_term(): 22da. 会修改窗口结构则返回 ‘True’，否则返
     回 ‘False’。

 -- 函式: curses.isendwin ()

     如果 *note endwin(): 22c4. 已经被调用（即 curses 库已经被撤销初始化
     则返回 ‘True’。

 -- 函式: curses.keyname (k)

     将编号为 `k' 的键名称作为字节串对象返回。 生成可打印 ASCII 字符的键
     名称就是键所对应的字符。 Ctrl-键组合的键名称则是一个两字节的字节串
     对象，它由插入符 (‘b'^'’) 加对应的可打印 ASCII 字符组成。 Alt-键组
     合 (128–255) 的键名称则是由前缀 ‘b'M-'’ 加对应的可打印 ASCII 字符组
     成的字节串对象。

 -- 函式: curses.killchar ()

     将用户的当前行删除字符以单字节字节串对象的形式返回。 在 Unix 操作系
     统下这是 curses 程序用来控制 tty 的属性，而不是由 curses 库本身来设
     置的。

 -- 函式: curses.longname ()

     返回一个字节串对象，其中包含描述当前终端的 terminfo 长名称字段。 详
     细描述的最大长度为 128 个字符。 它仅在调用 *note initscr(): 22c7. 之
     后才会被定义。

 -- 函式: curses.meta (flag)

     如果 `flag' 为 ‘True’，则允许输入 8 比特位的字符。 如果 `flag' 为
     ‘False’，则只允许 7 比特位的字符。

 -- 函式: curses.mouseinterval (interval)

     以毫秒为单位设置能够被识别为点击的按下和释放事件之间可以间隔的最长
     时间，并返回之前的间隔值。 默认值为 200 毫秒，即五分之一秒。

 -- 函式: curses.mousemask (mousemask)

     设置要报告的鼠标事件，并返回一个元组 ‘(availmask, oldmask)’。
     `availmask' 表明指定的鼠标事件中哪些可以被报告；当完全失败时将返回
     ‘0’。 `oldmask' 是给定窗口的鼠标事件之前的掩码值。 如果从未调用此函
     数，则不会报告任何鼠标事件。

 -- 函式: curses.napms (ms)

     休眠 `ms' 毫秒。

 -- 函式: curses.newpad (nlines, ncols)

     创建并返回一个指向具有给定行数和列数新的面板数据结构的指针。 将面板
     作为窗口对象返回。

     面板类似于窗口，区别在于它不受屏幕大小的限制，并且不必与屏幕的特定
     部分相关联。 面板可以在需要使用大窗口时使用，并且每次只需将窗口的一
     部分放在屏幕上。 面板不会发生自动刷新（例如由于滚动或输入回显）。 面
     板的 *note refresh(): 22c2. 和 *note noutrefresh(): 22c1. 方法需要
     6 个参数来指定面板要显示的部分以及要用于显示的屏幕位置。 这些参数是
     `pminrow', `pmincol', `sminrow', `smincol', `smaxrow', `smaxcol'；
     `p' 参数表示要显示的面板区域的左上角而 `s' 参数定义了要显示的面板区
     域在屏幕上的剪切框。

 -- 函式: curses.newwin (nlines, ncols)

 -- 函式: curses.newwin (nlines, ncols, begin_y, begin_x)

     返回一个新的 *note 窗口: 22d8.，其左上角位于 ‘(begin_y, begin_x)’，
     并且其高度/宽度为 `nlines'/`ncols'。

     默认情况下，窗口将从指定位置扩展到屏幕的右下角。

 -- 函式: curses.nl ()

     进入 newline 模式。 此模式会在输入时将回车转换为换行符，并在输出时
     将换行符转换为回车加换行。 newline 模式会在初始时启用。

 -- 函式: curses.nocbreak ()

     退出 cbreak 模式。 返回具有行缓冲的正常 "cooked" 模式。

 -- 函式: curses.noecho ()

     退出 echo 模式。 关闭输入字符的回显。

 -- 函式: curses.nonl ()

     退出 newline 模式。 停止在输入时将回车转换为换行，并停止在输出时从
     换行到换行/回车的底层转换（但这不会改变 ‘addch('\n')’ 的行为，此行
     为总是在虚拟屏幕上执行相当于回车加换行的操作）。 当停止转换时，
     curses 有时能使纵向移动加快一些；并且，它将能够在输入时检测回车键。

 -- 函式: curses.noqiflush ()

     当使用 ‘noqiflush()’ 例程时，与 ‘INTR’, ‘QUIT’ 和 ‘SUSP’ 字符相关联
     的输入和输出队列的正常刷新将不会被执行。 如果你希望在处理程序退出后
     还能继续输出，就像没有发生过中断一样，你可能会想要在信号处理程序中
     调用 ‘noqiflush()’。

 -- 函式: curses.noraw ()

     退出 raw 模式。 返回具有行缓冲的正常 "cooked" 模式。

 -- 函式: curses.pair_content (pair_number)

     返回包含对应于所请求颜色对的元组 ‘(fg, bg)’。 `pair_number' 的值必
     须在 ‘0’ 和 ‘COLOR_PAIRS - 1’ 之间。

 -- 函式: curses.pair_number (attr)

     返回通过属性值 `attr' 所设置的颜色对的编号。 *note color_pair():
     22b7. 是此函数的对应操作。

 -- 函式: curses.putp (str)

     等价于 ‘tputs(str, 1, putchar)’；为当前终端发出指定 terminfo 功能的
     值。 请注意 *note putp(): 22eb. 的输出总是前往标准输出。

 -- 函式: curses.qiflush ([flag])

     如果 `flag' 为 ‘False’，则效果与调用 *note noqiflush(): 22e8. 相同
     。 如果 `flag' 为 ‘True’ 或未提供参数，则在读取这些控制字符时队列将
     被刷新。

 -- 函式: curses.raw ()

     进入 raw 模式。 在 raw 模式下，正常的行缓冲和对中断、退出、挂起和流
     程控制键的处理会被关闭；字符会被逐个地提交给 curses 输入函数。

 -- 函式: curses.reset_prog_mode ()

     将终端恢复到 "program" 模式，如之前由 *note def_prog_mode(): 22ba.
     所保存的一样。

 -- 函式: curses.reset_shell_mode ()

     将终端恢复到 "shell" 模式，如之前由 *note def_shell_mode(): 22bc. 所
     保存的一样。

 -- 函式: curses.resetty ()

     将终端模式恢复到最后一次调用 *note savetty(): 22ee. 时的状态。

 -- 函式: curses.resize_term (nlines, ncols)

     由 *note resizeterm(): 22ef. 用来执行大部分工作的后端函数；当调整窗
     口大小时，*note resize_term(): 22da. 会以空白填充扩展区域。 调用方
     应用程序应当以适当的数据填充这些区域。 ‘resize_term()’ 函数会尝试调
     整所有窗口的大小。 但是，由于面板的调用约定，在不与应用程序进行额外
     交互的情况下是无法调整其大小的。

 -- 函式: curses.resizeterm (nlines, ncols)

     将标准窗口和当前窗口的大小调整为指定的尺寸，并调整由 curses 库所使
     用的记录窗口尺寸的其他记录数据（特别是 SIGWINCH 处理程序）。

 -- 函式: curses.savetty ()

     将终端模式的当前状态保存在缓冲区中，可供 *note resetty(): 22ed. 使
     用。

 -- 函式: curses.get_escdelay ()

     提取通过 *note set_escdelay(): 199. 设置的值。

     3.9 版新加入.

 -- 函式: curses.set_escdelay (ms)

     设置读取一个转义字符后要等待的毫秒数，以区分在键盘上输入的单个转义
     字符与通过光标和功能键发送的转义序列。

     3.9 版新加入.

 -- 函式: curses.get_tabsize ()

     提取通过 *note set_tabsize(): 19b. 设置的值。

     3.9 版新加入.

 -- 函式: curses.set_tabsize (size)

     设置 curses 库在将制表符添加到窗口时将制表符转换为空格所使用的列数
     。

     3.9 版新加入.

 -- 函式: curses.setsyx (y, x)

     将虚拟屏幕光标设置到 `y', `x'。 如果 `y' 和 `x' 均为 ‘-1’，则 *note
     leaveok: 22cd. 将设为 ‘True’。

 -- 函式: curses.setupterm (term=None, fd=-1)

     初始化终端。 `term' 为给出终端名称的字符串或为 ‘None’；如果省略或为
     ‘None’，则将使用 ‘TERM’ 环境变量的值。 `fd' 是任何初始化序列将被发
     送到的文件描述符；如未指定或为 ‘-1’，则将使用 ‘sys.stdout’ 的文件描
     述符。

 -- 函式: curses.start_color ()

     如果程序员想要使用颜色，则必须在任何其他颜色操作例程被调用之前调用
     它。 在 *note initscr(): 22c7. 之后立即调用此例程是一个很好的做法。

     *note start_color(): 22f2. 会初始化八种基本颜色（黑、红、绿、黄、蓝
     、品、青和白）以及 *note curses: 2b. 模块中的两个全局变量 ‘COLORS’
     和 ‘COLOR_PAIRS’，其中包含终端可支持的颜色和颜色对的最大数量。 它还
     会将终端中的颜色恢复为终端刚启动时的值。

 -- 函式: curses.termattrs ()

     返回终端所支持的所有视频属性逻辑 OR 的值。 此信息适用于当 curses 程
     序需要对屏幕外观进行完全控制的情况。

 -- 函式: curses.termname ()

     将环境变量 ‘TERM’ 的值截短至 14 个字节，作为字节串对象返回。

 -- 函式: curses.tigetflag (capname)

     将与 terminfo 功能名称 `capname' 相对应的布尔功能值以整数形式返回。
     如果 `capname' 不是一个布尔功能则返回 ‘-1’，如果其被取消或不存在于
     终端描述中则返回 ‘0’。

 -- 函式: curses.tigetnum (capname)

     将与 terminfo 功能名称 `capname' 相对应的数字功能值以整数形式返回。
     如果 `capname' 不是一个数字功能则返回 ‘-2’，如果其被取消或不存在于
     终端描述中则返回 ‘-1’。

 -- 函式: curses.tigetstr (capname)

     将与 terminfo 功能名称 `capname' 相对应的字符串功能值以字节串对象形
     式返回。 如果 `capname' 不是一个 terminfo "字符串功能" 或者如果其被
     取消或不存在于终端描述中则返回 ‘None’。

 -- 函式: curses.tparm (str[, ...])

     使用提供的形参初始化字节串对象 `str'，其中 `str' 应当是从 terminfo
     数据库获取的参数化字符串。 例如 ‘tparm(tigetstr("cup"), 5, 3)’ 的结
     果可能为 ‘b'\033[6;4H'’，实际结果将取决于终端类型。

 -- 函式: curses.typeahead (fd)

     指定将被用于预输入检查的文件描述符 `fd'。 如果 `fd' 为 ‘-1’，则不执
     行预输入检查。

     curses 库会在更新屏幕时通过定期查找预输入来执行 "断行优化"。 如果找
     到了输入，并且输入是来自于 tty，则会将当前更新推迟至 refresh 或
     doupdate 再次被调用的时候，以便允许更快地响应预先输入的命令。 此函
     数允许为预输入检查指定其他的文件描述符。

 -- 函式: curses.unctrl (ch)

     返回一个字节串对象作为字符 `ch' 的可打印表示形式。 控制字符会表示为
     一个变换符加相应的字符，例如 ‘b'^C'’。 可打印字符则会保持原样。

 -- 函式: curses.ungetch (ch)

     推送 `ch' 以便让下一个 *note getch(): 22cb. 返回该字符。

          備註: 在 ‘getch()’ 被调用之前只能推送一个 `ch'。

 -- 函式: curses.update_lines_cols ()

     更新 ‘LINES’ 和 ‘COLS’。 适用于检测屏幕大小的手动调整。

     3.5 版新加入.

 -- 函式: curses.unget_wch (ch)

     推送 `ch' 以便让下一个 *note get_wch(): abe. 返回该字符。

          備註: 在 ‘get_wch()’ 被调用之前只能推送一个 `ch'。

     3.3 版新加入.

 -- 函式: curses.ungetmouse (id, x, y, z, bstate)

     将 ‘KEY_MOUSE’ 事件推送到输入队列，将其与给定的状态数据进行关联。

 -- 函式: curses.use_env (flag)

     如果使用此函数，则应当在调用 *note initscr(): 22c7. 或 newterm 之前
     调用它。 当 `flag' 为 ‘False’ 时，将会使用在 terminfo 数据库中指定
     的行和列的值，即使设置了环境变量 ‘LINES’ 和 ‘COLUMNS’ (默认使用)，
     或者如果 curses 是在窗口中运行（在此情况下如果未设置 ‘LINES’ 和
     ‘COLUMNS’ 则默认行为将是使用窗口大小）。

 -- 函式: curses.use_default_colors ()

     允许在支持此特性的终端上使用默认的颜色值。 使用此函数可在你的应用程
     序中支持透明效果。 默认颜色会被赋给颜色编号 ‘-1’。 举例来说，在调用
     此函数后，‘init_pair(x, curses.COLOR_RED, -1)’ 会将颜色对 `x' 初始
     化为红色前景和默认颜色背景。

 -- 函式: curses.wrapper (func, /, *args, **kwargs)

     初始化 curses 并调用另一个可调用对象 `func'，该对象应当为你的使用
     curses 的应用程序的其余部分。 如果应用程序引发了异常，此函数将在重
     新引发异常并生成回溯信息之前将终端恢复到正常状态。 随后可调用对象
     `func' 会被传入主窗口 ’stdscr’ 作为其第一个参数，再带上其他所有传给
     ‘wrapper()’ 的参数。 在调用 `func' 之前，‘wrapper()’ 会启用 cbreak
     模式，关闭回显，启用终端键盘，并在终端具有颜色支持的情况下初始化颜
     色。 在退出时（无论是正常退出还是异常退出）它会恢复 cooked 模式，打
     开回显，并禁用终端键盘。


File: python.info,  Node: Window 对象,  Next: 常量<2>,  Prev: 函数<4>,  Up: curses --- 终端字符单元显示的处理

5.16.10.2 Window 对象
.....................

Window 对象会由上面的 *note initscr(): 22c7. 和 *note newwin(): 22e4. 返
回，它具有以下方法和属性:

 -- 成員函式: window.addch (ch[, attr])

 -- 成員函式: window.addch (y, x, ch[, attr])

     将带有属性 `attr' 的字符 `ch' 绘制到 ‘(y, x)’，覆盖之前在该位置上绘
     制的任何字符。 默认情况下，字符的位置和属性均为窗口对象的当前设置。

          備註: 在窗口、子窗口或面板之外写入会引发 *note curses.error:
          22b0.。 尝试在窗口、子窗口或面板的右下角写入将在字符被打印之后
          导致异常被引发。

 -- 成員函式: window.addnstr (str, n[, attr])

 -- 成員函式: window.addnstr (y, x, str, n[, attr])

     将带有属性 `attr' 的字符串 `str' 中的至多 `n' 个字符绘制到 ‘(y,
     x)’，覆盖之前在屏幕上的任何内容。

 -- 成員函式: window.addstr (str[, attr])

 -- 成員函式: window.addstr (y, x, str[, attr])

     将带有属性 `attr' 的字符串 `str' 绘制到 ‘(y, x)’，覆盖之前在屏幕上
     的任何内容。

          備註: 
             * 在窗口、子窗口或面板之外写入会引发 *note curses.error:
               22b0.。 尝试在窗口、子窗口或面板的右下角写入将在字符串被
               打印之后导致异常被引发。

             * 此 Python 模块的后端 ncurses 中的一个缺陷(1) 会在调整窗口
               大小时导致段错误。 此缺陷已在 ncurses-6.1-20190511 中被修
               复。 如果你必须使用较早版本的 ncurses，则你只要在调用
               *note addstr(): 22c0. 时不传入嵌入了换行符的 `str' 即可避
               免触发此错误。 请为每一行分别调用 *note addstr(): 22c0.。

 -- 成員函式: window.attroff (attr)

     从应用于写入到当前窗口的 "background" 集中移除属性 `attr'。

 -- 成員函式: window.attron (attr)

     向应用于写入到当前窗口的 "background" 集中添加属性 `attr'。

 -- 成員函式: window.attrset (attr)

     将 "background" 属性集设为 `attr'。 该集合初始时为 ‘0’ (无属性)。

 -- 成員函式: window.bkgd (ch[, attr])

     将窗口 background 特征属性设为带有属性 `attr' 的字符 `ch'。 随后此
     修改将应用于放置到该窗口中的每个字符。

        * 窗口中每个字符的属性会被修改为新的 background 属性。

        * 不论之前的 background 字符出现在哪里，它都会被修改为新的
          background 字符。

 -- 成員函式: window.bkgdset (ch[, attr])

     设置窗口的背景。 窗口的背景由字符和属性的任意组合构成。 背景的属性
     部分会与写入窗口的所有非空白字符合并（即 OR 运算）。 背景和字符和属
     性部分均会与空白字符合并。 背景将成为字符的特征属性并在任何滚动与插
     入/删除行/字符操作中与字符一起移动。

 -- 成員函式: window.border ([ls[, rs[, ts[, bs[, tl[, tr[, bl[,
          br]]]]]]]])

     在窗口边缘绘制边框。每个参数指定用于边界特定部分的字符;请参阅下表了
     解更多详情。

          備註: 任何形参的值为 ‘0’ 都将导致该形参使用默认字符。 关键字形
          参 `不可' 被使用。 默认字符在下表中列出:

     参数            描述                      默认值
                                               
     ----------------------------------------------------------------------
                                               
     `ls'            左侧                      ‘ACS_VLINE’
                                               
                                               
     `rs'            右侧                      ‘ACS_VLINE’
                                               
                                               
     `ts'            顶部                      ‘ACS_HLINE’
                                               
                                               
     `bs'            底部                      ‘ACS_HLINE’
                                               
                                               
     `tl'            左上角                    ‘ACS_ULCORNER’
                                               
                                               
     `tr'            右上角                    ‘ACS_URCORNER’
                                               
                                               
     `bl'            左下角                    ‘ACS_LLCORNER’
                                               
                                               
     `br'            右下角                    ‘ACS_LRCORNER’
                                               

 -- 成員函式: window.box ([vertch, horch])

     类似于 *note border(): 2306.，但 `ls' 和 `rs' 均为 `vertch' 而 `ts'
     和 `bs' 均为 `horch'。 此函数总是会使用默认的转角字符。

 -- 成員函式: window.chgat (attr)

 -- 成員函式: window.chgat (num, attr)

 -- 成員函式: window.chgat (y, x, attr)

 -- 成員函式: window.chgat (y, x, num, attr)

     在当前光标位置或是在所提供的位置 ‘(y, x)’ 设置 `num' 个字符的属性。
     如果 `num' 未给出或为 ‘-1’，则将属性设置到所有字符上直至行尾。 如果
     提供了位置 ‘(y, x)’ 则此函数会将光标移至该位置。 修改过的行将使用
     *note touchline(): 2309. 方法处理以便下次窗口刷新时内容会重新显示。

 -- 成員函式: window.clear ()

     类似于 *note erase(): 230b.，但还会导致在下次调用 *note refresh():
     22c2. 时整个窗口被重新绘制。

 -- 成員函式: window.clearok (flag)

     如果 `flag' 为 ‘True’，则在下次调用 *note refresh(): 22c2. 时将完全
     清除窗口。

 -- 成員函式: window.clrtobot ()

     从光标位置开始擦除直至窗口末端：光标以下的所有行都会被删除，然后会
     执行 *note clrtoeol(): 230e. 的等效操作。

 -- 成員函式: window.clrtoeol ()

     从光标位置开始擦除直至行尾。

 -- 成員函式: window.cursyncup ()

     更新窗口所有上级窗口的当前光标位置以反映窗口的当前光标位置。

 -- 成員函式: window.delch ([y, x])

     删除位于 ‘(y, x)’ 的任何字符。

 -- 成員函式: window.deleteln ()

     删除在光标之下的行。 所有后续的行都会上移一行。

 -- 成員函式: window.derwin (begin_y, begin_x)

 -- 成員函式: window.derwin (nlines, ncols, begin_y, begin_x)

     "derive window" 的缩写，*note derwin(): 2312. 与调用 *note
     subwin(): 2313. 等效，不同之处在于 `begin_y' 和 `begin_x' 是想对于
     窗口的初始位置，而不是相对于整个屏幕。 返回代表所派生窗口的窗口对象
     。

 -- 成員函式: window.echochar (ch[, attr])

     使用属性 `attr' 添加字符 `ch'，并立即在窗口上调用 *note refresh():
     22c2.。

 -- 成員函式: window.enclose (y, x)

     检测给定的相对屏幕的字符-单元格坐标是否被给定的窗口所包围，返回
     ‘True’ 或 ‘False’。 它适用于确定是哪个屏幕窗口子集包围着某个鼠标事
     件的位置。

 -- 屬性: window.encoding

     用于编码方法参数（Unicode 字符串和字符）的编码格式。 encoding 属性
     是在创建子窗口时从父窗口继承的，例如通过 *note window.subwin():
     2313.。 默认情况下，会使用当前区域的编码格式 (参见 *note
     locale.getpreferredencoding(): 4ab.)。

     3.3 版新加入.

 -- 成員函式: window.erase ()

     清空窗口。

 -- 成員函式: window.getbegyx ()

     返回左上角坐标的元组 ‘(y, x)’。

 -- 成員函式: window.getbkgd ()

     返回给定窗口的当前背景字符/属性对。

 -- 成員函式: window.getch ([y, x])

     获取一个字符。 请注意所返回的整数 `不一定' 要在 ASCII 范围以内：功
     能键、小键盘键等等是由大于 255 的数字表示的。 在无延迟模式下，如果
     没有输入则返回 ‘-1’，在其他情况下都会等待直至有键被按下。

 -- 成員函式: window.get_wch ([y, x])

     获取一个宽字符。 对于大多数键都是返回一个字符，对于功能键、小键盘键
     和其他特殊键则是返回一个整数。 在无延迟模式下，如果没有输入则引发一
     个异常。

     3.3 版新加入.

 -- 成員函式: window.getkey ([y, x])

     获取一个字符，返回一个字符串而不是像 *note getch(): 22cb. 那样返回
     一个整数。 功能键、小键盘键和其他特殊键则是返回一个包含键名的多字节
     字符串。 在无延迟模式下，如果没有输入则引发一个异常。

 -- 成員函式: window.getmaxyx ()

     返回窗口高度和宽度的元组 ‘(y, x)’。

 -- 成員函式: window.getparyx ()

     将此窗口相对于父窗口的起始坐标作为元组 ‘(y, x)’ 返回。 如果此窗口没
     有父窗口则返回 ‘(-1, -1)’。

 -- 成員函式: window.getstr ()

 -- 成員函式: window.getstr (n)

 -- 成員函式: window.getstr (y, x)

 -- 成員函式: window.getstr (y, x, n)

     从用户读取一个字节串对象，附带基本的行编辑功能。

 -- 成員函式: window.getyx ()

     返回当前光标相对于窗口左上角的位置的元组 ‘(y, x)’。

 -- 成員函式: window.hline (ch, n)

 -- 成員函式: window.hline (y, x, ch, n)

     显示一条起始于 ‘(y, x)’ 长度为 `n' 个字符 `ch' 的水平线。

 -- 成員函式: window.idcok (flag)

     如果 `flag' 为 ‘False’，curses 将不再考虑使用终端的硬件插入/删除字
     符功能；如果 `flag' 为 ‘True’，则会启用字符插入和删除。 当 curses 首
     次初始化时，默认会启用字符插入/删除。

 -- 成員函式: window.idlok (flag)

     如果 `flag' 为 ‘True’，*note curses: 2b. 将尝试使用硬件行编辑功能。
     否则，行插入/删除会被禁用。

 -- 成員函式: window.immedok (flag)

     如果 `flag' 为 ‘True’，窗口图像中的任何改变都会自动导致窗口被刷新；
     你不必再自己调用 *note refresh(): 22c2.。 但是，这可能会由于重复调
     用 wrefresh 而显著降低性能。 此选项默认被禁用。

 -- 成員函式: window.inch ([y, x])

     返回窗口中给定位置上的字符。 下面的 8 个比特位是字符本身，上面的比
     特位则为属性。

 -- 成員函式: window.insch (ch[, attr])

 -- 成員函式: window.insch (y, x, ch[, attr])

     将带有属性 `attr' 的字符 `ch' 绘制到 ‘(y, x)’，将该行从位置 `x' 开
     始右移一个字符。

 -- 成員函式: window.insdelln (nlines)

     在指定窗口的当前行上方插入 `nlines' 行。 下面的 `nlines' 行将丢失。
     对于 `nlines' 为负值的情况，则从光标下方的行开始删除 `nlines' 行，
     并将其余的行向上移动。 下面的 `nlines' 行会被清空。 当前光标位置将
     保持不变。

 -- 成員函式: window.insertln ()

     在光标下方插入一个空行。 所有后续的行都会下移一行。

 -- 成員函式: window.insnstr (str, n[, attr])

 -- 成員函式: window.insnstr (y, x, str, n[, attr])

     在光标下方的字符之前插入一个至多为 `n' 个字符的字符串（字符数量将与
     该行相匹配）。 如果 `n' 为零或负数，则插入整个字符串。 光标右边的所
     有字符将被右移，该行右端的字符将丢失。 光标位置将保持不变（在移到可
     能指定的 `y', `x' 之后）。

 -- 成員函式: window.insstr (str[, attr])

 -- 成員函式: window.insstr (y, x, str[, attr])

     在光标下方的字符之前插入一个字符串（字符数量将与该行相匹配）。 光标
     右边的所有字符将被右移，该行右端的字符将丢失。 光标位置将保持不变（
     在移到可能指定的 `y', `x' 之后）。

 -- 成員函式: window.instr ([n])

 -- 成員函式: window.instr (y, x[, n])

     返回从窗口的当前光标位置，或者指定的 `y', `x' 开始提取的字符所对应
     的字节串对象。 属性会从字符中去除。 如果指定了 `n'，*note instr():
     2327. 将返回长度至多为 `n' 个字符的字符串（不包括末尾的 NUL）。

 -- 成員函式: window.is_linetouched (line)

     如果指定的行自上次调用 *note refresh(): 22c2. 后发生了改变则返回
     ‘True’；否则返回 ‘False’。 如果 `line' 对于给定的窗口不可用则会引发
     *note curses.error: 22b0. 异常。

 -- 成員函式: window.is_wintouched ()

     如果指定的窗口自上次调用 *note refresh(): 22c2. 后发生了改变则返回
     ‘True’；否则返回 ‘False’。

 -- 成員函式: window.keypad (flag)

     如果 `flag' 为 ‘True’，则某些键（小键盘键、功能键等）生成的转义序列
     将由 *note curses: 2b. 来解析。 如果 `flag' 为 ‘False’，转义序列将
     保持在输入流中的原样。

 -- 成員函式: window.leaveok (flag)

     如果 `flag' 为 ‘True’，则在更新时光标将停留在原地，而不是在“光标位
     置”。 这将可以减少光标的移动。 在可能的情况下光标将变为不可见。

     如果 `flag' 为 ‘False’，光标在更新后将总是位于“光标位置”。

 -- 成員函式: window.move (new_y, new_x)

     将光标移至 ‘(new_y, new_x)’。

 -- 成員函式: window.mvderwin (y, x)

     让窗口在其父窗口内移动。 窗口相对于屏幕的参数不会被更改。 此例程用
     于在屏幕的相同物理位置显示父窗口的不同部分。

 -- 成員函式: window.mvwin (new_y, new_x)

     移动窗口以使其左上角位于 ‘(new_y, new_x)’。

 -- 成員函式: window.nodelay (flag)

     如果 `flag' 为 ‘True’，则 *note getch(): 22cb. 将为非阻塞的。

 -- 成員函式: window.notimeout (flag)

     如果 `flag' 为 ‘True’，则转义序列将不会发生超时。

     如果 `flag' 为 ‘False’，则在几毫秒之后，转义序列将不会被解析，并将
     保持在输入流中的原样。

 -- 成員函式: window.noutrefresh ()

     标记为刷新但保持等待。 此函数会更新代表预期窗口状态的数据结构，但并
     不强制更新物理屏幕。 要完成后者，请调用 *note doupdate(): 22bf.。

 -- 成員函式: window.overlay (destwin[, sminrow, smincol, dminrow,
          dmincol, dmaxrow, dmaxcol])

     将窗口覆盖在 `destwin' 上方。 窗口的大小不必相同，只有重叠的区域会
     被复制。 此复制是非破坏性的，这意味着当前背景字符不会覆盖掉
     `destwin' 的旧内容。

     为了获得对被复制区域的细粒度控制，可以使用 *note overlay(): 2330. 的
     第二种形式。 `sminrow' 和 `smincol' 是源窗口的左上角坐标，而其他变
     量则在目标窗口中标记出一个矩形。

 -- 成員函式: window.overwrite (destwin[, sminrow, smincol, dminrow,
          dmincol, dmaxrow, dmaxcol])

     将窗口覆盖在 `destwin' 上方。 窗口的大小不必相同，此时只有重叠的区
     域会被复制。 此复制是破坏性的，这意味着当前背景字符会覆盖掉
     `destwin' 的旧内容。

     为了获得对被复制区域的细粒度控制，可以使用 *note overwrite(): 2331.
     的第二种形式。 `sminrow' 和 `smincol' 是源窗口的左上角坐标，而其他
     变量则在目标窗口中标记出一个矩形。

 -- 成員函式: window.putwin (file)

     将关联到窗口的所有数据写入到所提供的文件对象。 此信息可在以后使用
     *note getwin(): 22ce. 函数来提取。

 -- 成員函式: window.redrawln (beg, num)

     指明从 `beg' 行开始的 `num' 个屏幕行已被破坏并且应当在下次 *note
     refresh(): 22c2. 调用时完全重绘。

 -- 成員函式: window.redrawwin ()

     触碰整个窗口，以使其在下次 *note refresh(): 22c2. 调用时完全重绘。

 -- 成員函式: window.refresh ([pminrow, pmincol, sminrow, smincol,
          smaxrow, smaxcol])

     立即更新显示（将实际屏幕与之前的绘制/删除方法进行同步）。

     6 个可选参数仅在窗口为使用 *note newpad(): 22e3. 创建的面板时可被指
     定。 需要额外的形参来指定所涉及到的是面板和屏幕的哪一部分。
     `pminrow' 和 `pmincol' 指定要在面板中显示的矩形的左上角。
     `sminrow', `smincol', `smaxrow' 和 `smaxcol' 指定要在屏幕中显示的矩
     形的边。 要在面板中显示的矩形的右下角是根据屏幕坐标计算出来的，由于
     矩形的大小必须相同。 两个矩形都必须完全包含在其各自的结构之内。 负
     的 `pminrow', `pmincol', `sminrow' 或 `smincol' 值会被视为将它们设
     为零值。

 -- 成員函式: window.resize (nlines, ncols)

     为 curses 窗口重新分配存储空间以将其尺寸调整为指定的值。 如果任一维
     度的尺寸大于当前值，则窗口的数据将以具有合并了当前背景渲染（由
     *note bkgdset(): 2305. 设置）的空白来填充。

 -- 成員函式: window.scroll ([lines=1])

     将屏幕或滚动区域向上滚动 `lines' 行。

 -- 成員函式: window.scrollok (flag)

     控制当一个窗口的光标移出窗口或滚动区域边缘时会发生什么，这可能是在
     底端行执行换行操作，或者在最后一行输入最后一个字符导致的结果。 如果
     `flag' 为 ‘False’，光标会留在底端行。 如果 `flag' 为 ‘True’，窗口会
     向上滚动一行。 请注意为了在终端上获得实际的滚动效果，还需要调用
     *note idlok(): 231f.。

 -- 成員函式: window.setscrreg (top, bottom)

     设置从 `top' 行至 `bottom' 行的滚动区域。 所有滚动操作将在此区域中
     进行。

 -- 成員函式: window.standend ()

     关闭 standout 属性。 在某些终端上此操作会有关闭所有属性的副作用。

 -- 成員函式: window.standout ()

     启用属性 `A_STANDOUT'。

 -- 成員函式: window.subpad (begin_y, begin_x)

 -- 成員函式: window.subpad (nlines, ncols, begin_y, begin_x)

     返回一个子窗口，其左上角位于 ‘(begin_y, begin_x)’，并且其宽度/高度
     为 `ncols'/`nlines'。

 -- 成員函式: window.subwin (begin_y, begin_x)

 -- 成員函式: window.subwin (nlines, ncols, begin_y, begin_x)

     返回一个子窗口，其左上角位于 ‘(begin_y, begin_x)’，并且其宽度/高度
     为 `ncols'/`nlines'。

     默认情况下，子窗口将从指定位置扩展到窗口的右下角。

 -- 成員函式: window.syncdown ()

     触碰已在上级窗口上被触碰的每个位置。 此例程由 *note refresh():
     22c2. 调用，因此几乎从不需要手动调用。

 -- 成員函式: window.syncok (flag)

     如果 `flag' 为 ‘True’，则 *note syncup(): 233e. 会在窗口发生改变的
     任何时候自动被调用。

 -- 成員函式: window.syncup ()

     触碰已在窗口中被改变的此窗口的各个上级窗口中的所有位置。

 -- 成員函式: window.timeout (delay)

     为窗口设置阻塞或非阻塞读取行为。 如果 `delay' 为负值，则会使用阻塞
     读取（这将无限期地等待输入）。 如果 `delay' 为零，则会使用非阻塞读
     取，并且当没有输入在等待时 *note getch(): 22cb. 将返回 ‘-1’。 如果
     `delay' 为正值，则 *note getch(): 22cb. 将阻塞 `delay' 毫秒，并且当
     此延时结束时仍无输入将返回 ‘-1’。

 -- 成員函式: window.touchline (start, count[, changed])

     假定从行 `start' 开始的 `count' 行已被更改。 如果提供了 `changed'，
     它将指明是将受影响的行标记为已更改 (`changed'‘=True’) 还是未更改
     (`changed'‘=False’)。

 -- 成員函式: window.touchwin ()

     假定整个窗口已被更改，其目的是用于绘制优化。

 -- 成員函式: window.untouchwin ()

     将自上次调用 *note refresh(): 22c2. 以来窗口中的所有行标记为未改变
     。

 -- 成員函式: window.vline (ch, n)

 -- 成員函式: window.vline (y, x, ch, n)

     显示一条起始于 ‘(y, x)’ 长度为 `n' 个字符 `ch' 的垂直线。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue35924


File: python.info,  Node: 常量<2>,  Prev: Window 对象,  Up: curses --- 终端字符单元显示的处理

5.16.10.3 常量
..............

*note curses: 2b. 模块定义了以下数据成员:

 -- Data: curses.ERR

     一些返回整数的 curses 例程，例如 *note getch(): 22cb.，在失败时将返
     回 *note ERR: 2344.。

 -- Data: curses.OK

     一些返回整数的 curses 例程，例如 *note napms(): 22e2.，在成功时将返
     回 *note OK: 2345.。

 -- Data: curses.version

     一个代表当前模块版本的字节串对象。 也作 ‘__version__’。

 -- Data: curses.ncurses_version

     一个具名元组，它包含构成 ncurses 库版本号的三个数字: `major',
     `minor' 和 `patch'。 三个值均为整数。 三个值也可通过名称来访问，因
     此 ‘curses.ncurses_version[0]’ 等价于
     ‘curses.ncurses_version.major’，依此类推。

     可用性：如果使用了 ncurses 库。

     3.8 版新加入.

有些常量可用于指定字符单元属性。 实际可用的常量取决于具体的系统。

属性                   含义
                       
-----------------------------------------------------------
                       
‘A_ALTCHARSET’         备用字符集模式
                       
                       
‘A_BLINK’              闪烁模式
                       
                       
‘A_BOLD’               粗体模式
                       
                       
‘A_DIM’                暗淡模式
                       
                       
‘A_INVIS’              不可见或空白模式
                       
                       
‘A_ITALIC’             斜体模式
                       
                       
‘A_NORMAL’             正常属性
                       
                       
‘A_PROTECT’            保护模式
                       
                       
‘A_REVERSE’            反转背景色和前景色
                       
                       
‘A_STANDOUT’           突出模式
                       
                       
‘A_UNDERLINE’          下划线模式
                       
                       
‘A_HORIZONTAL’         水平突出显示
                       
                       
‘A_LEFT’               左高亮
                       
                       
‘A_LOW’                底部高亮
                       
                       
‘A_RIGHT’              右高亮
                       
                       
‘A_TOP’                顶部高亮
                       
                       
‘A_VERTICAL’           垂直突出显示
                       
                       
‘A_CHARTEXT’           用于提取字符的位掩码
                       

3.7 版新加入: ‘A_ITALIC’ was added.

有几个常量可用于提取某些方法返回的相应属性。

位掩码                 含义
                       
-----------------------------------------------------------
                       
‘A_ATTRIBUTES’         用于提取属性的位掩码
                       
                       
‘A_CHARTEXT’           用于提取字符的位掩码
                       
                       
‘A_COLOR’              用于提取颜色对字段信息的位掩码
                       

键由名称以 ‘KEY_’ 开头的整数常量引用。确切的可用键取决于系统。

关键常数                键
                        
-------------------------------------------------------------------------
                        
‘KEY_MIN’               最小键值
                        
                        
‘KEY_BREAK’             中断键（不可靠）
                        
                        
‘KEY_DOWN’              向下箭头
                        
                        
‘KEY_UP’                向上箭头
                        
                        
‘KEY_LEFT’              向左箭头
                        
                        
‘KEY_RIGHT’             向右箭头
                        
                        
‘KEY_HOME’              Home 键 (上+左箭头)
                        
                        
‘KEY_BACKSPACE’         退格（不可靠）
                        
                        
‘KEY_F0’                功能键。 支持至多 64 个功能键。
                        
                        
‘KEY_Fn’                功能键 `n' 的值
                        
                        
‘KEY_DL’                删除行
                        
                        
‘KEY_IL’                插入行
                        
                        
‘KEY_DC’                删除字符
                        
                        
‘KEY_IC’                插入字符或进入插入模式
                        
                        
‘KEY_EIC’               退出插入字符模式
                        
                        
‘KEY_CLEAR’             清空屏幕
                        
                        
‘KEY_EOS’               清空至屏幕底部
                        
                        
‘KEY_EOL’               清空至行尾
                        
                        
‘KEY_SF’                向前滚动 1 行
                        
                        
‘KEY_SR’                向后滚动 1 行 (反转)
                        
                        
‘KEY_NPAGE’             下一页
                        
                        
‘KEY_PPAGE’             上一页
                        
                        
‘KEY_STAB’              设置制表符
                        
                        
‘KEY_CTAB’              清除制表符
                        
                        
‘KEY_CATAB’             清除所有制表符
                        
                        
‘KEY_ENTER’             回车或发送 (不可靠)
                        
                        
‘KEY_SRESET’            软 (部分) 重置 (不可靠)
                        
                        
‘KEY_RESET’             重置或硬重置 (不可靠)
                        
                        
‘KEY_PRINT’             打印
                        
                        
‘KEY_LL’                Home 向下或到底 (左下)
                        
                        
‘KEY_A1’                键盘的左上角
                        
                        
‘KEY_A3’                键盘的右上角
                        
                        
‘KEY_B2’                键盘的中心
                        
                        
‘KEY_C1’                键盘左下方
                        
                        
‘KEY_C3’                键盘右下方
                        
                        
‘KEY_BTAB’              回退制表符
                        
                        
‘KEY_BEG’               Beg (开始)
                        
                        
‘KEY_CANCEL’            取消
                        
                        
‘KEY_CLOSE’             关闭
                        
                        
‘KEY_COMMAND’           Cmd (命令行)
                        
                        
‘KEY_COPY’              复制
                        
                        
‘KEY_CREATE’            创建
                        
                        
‘KEY_END’               End
                        
                        
‘KEY_EXIT’              退出
                        
                        
‘KEY_FIND’              查找
                        
                        
‘KEY_HELP’              帮助
                        
                        
‘KEY_MARK’              标记
                        
                        
‘KEY_MESSAGE’           消息
                        
                        
‘KEY_MOVE’              移动
                        
                        
‘KEY_NEXT’              下一个
                        
                        
‘KEY_OPEN’              打开
                        
                        
‘KEY_OPTIONS’           选项
                        
                        
‘KEY_PREVIOUS’          Prev (上一个)
                        
                        
‘KEY_REDO’              重做
                        
                        
‘KEY_REFERENCE’         Ref (引用)
                        
                        
‘KEY_REFRESH’           刷新
                        
                        
‘KEY_REPLACE’           替换
                        
                        
‘KEY_RESTART’           重启
                        
                        
‘KEY_RESUME’            恢复
                        
                        
‘KEY_SAVE’              保存
                        
                        
‘KEY_SBEG’              Shift + Beg (开始)
                        
                        
‘KEY_SCANCEL’           Shift + Cancel
                        
                        
‘KEY_SCOMMAND’          Shift + Command
                        
                        
‘KEY_SCOPY’             Shift + Copy
                        
                        
‘KEY_SCREATE’           Shift + Create
                        
                        
‘KEY_SDC’               Shift + 删除字符
                        
                        
‘KEY_SDL’               Shift + 删除行
                        
                        
‘KEY_SELECT’            选择
                        
                        
‘KEY_SEND’              Shift + End
                        
                        
‘KEY_SEOL’              Shift + 清空行
                        
                        
‘KEY_SEXIT’             Shift + 退出
                        
                        
‘KEY_SFIND’             Shift + 查找
                        
                        
‘KEY_SHELP’             Shift + 帮助
                        
                        
‘KEY_SHOME’             Shift + Home
                        
                        
‘KEY_SIC’               Shift + 输入
                        
                        
‘KEY_SLEFT’             Shift + 向左箭头
                        
                        
‘KEY_SMESSAGE’          Shift + 消息
                        
                        
‘KEY_SMOVE’             Shift + 移动
                        
                        
‘KEY_SNEXT’             Shift + 下一个
                        
                        
‘KEY_SOPTIONS’          Shift + 选项
                        
                        
‘KEY_SPREVIOUS’         Shift + 上一个
                        
                        
‘KEY_SPRINT’            Shift + 打印
                        
                        
‘KEY_SREDO’             Shift + 重做
                        
                        
‘KEY_SREPLACE’          Shift + 替换
                        
                        
‘KEY_SRIGHT’            Shift + 向右箭头
                        
                        
‘KEY_SRSUME’            Shift + 恢复
                        
                        
‘KEY_SSAVE’             Shift + 保存
                        
                        
‘KEY_SSUSPEND’          Shift + 挂起
                        
                        
‘KEY_SUNDO’             Shift + 撤销
                        
                        
‘KEY_SUSPEND’           挂起
                        
                        
‘KEY_UNDO’              撤销操作
                        
                        
‘KEY_MOUSE’             鼠标事件已发生
                        
                        
‘KEY_RESIZE’            终端大小改变事件
                        
                        
‘KEY_MAX’               最大键值
                        

在VT100及其软件仿真（例如X终端仿真器）上，通常至少有四个功能键（
‘KEY_F1’, ‘KEY_F2’, ‘KEY_F3’, ‘KEY_F4’ ）可用，并且箭头键以明显的方式映
射到 ‘KEY_UP’, ‘KEY_DOWN’, ‘KEY_LEFT’ 和 ‘KEY_RIGHT’ 。如果您的机器有一
个PC键盘，可以安全地使用箭头键和十二个功能键（旧的PC键盘可能只有十个功能
键）;此外，以下键盘映射是标准的：

键帽                   常数
                       
---------------------------------------
                       
‘Insert’               KEY_IC
                       
                       
‘Delete’               KEY_DC
                       
                       
‘Home’                 KEY_HOME
                       
                       
‘End’                  KEY_END
                       
                       
‘Page Up’              KEY_PPAGE
                       
                       
‘Page Down’            KEY_NPAGE
                       

下表列出了替代字符集中的字符。 这些字符继承自 VT100 终端，在 X 终端等软
件模拟器上通常均为可用。 当没有可用的图形时，curses 会回退为粗糙的可打印
ASCII 近似符号。

     備註: 只有在调用 *note initscr(): 22c7. 之后才能使用它们

ACS代码                含义
                       
----------------------------------------------------------------------
                       
‘ACS_BBSS’             右上角的别名
                       
                       
‘ACS_BLOCK’            实心方块
                       
                       
‘ACS_BOARD’            正方形
                       
                       
‘ACS_BSBS’             水平线的别名
                       
                       
‘ACS_BSSB’             左上角的别名
                       
                       
‘ACS_BSSS’             顶部 T 型的别名
                       
                       
‘ACS_BTEE’             底部 T 型
                       
                       
‘ACS_BULLET’           正方形
                       
                       
‘ACS_CKBOARD’          棋盘（点刻）
                       
                       
‘ACS_DARROW’           向下箭头
                       
                       
‘ACS_DEGREE’           等级符
                       
                       
‘ACS_DIAMOND’          菱形
                       
                       
‘ACS_GEQUAL’           大于或等于
                       
                       
‘ACS_HLINE’            水平线
                       
                       
‘ACS_LANTERN’          灯形符号
                       
                       
‘ACS_LARROW’           向左箭头
                       
                       
‘ACS_LEQUAL’           小于或等于
                       
                       
‘ACS_LLCORNER’         左下角
                       
                       
‘ACS_LRCORNER’         右下角
                       
                       
‘ACS_LTEE’             左侧 T 型
                       
                       
‘ACS_NEQUAL’           不等号
                       
                       
‘ACS_PI’               字母π
                       
                       
‘ACS_PLMINUS’          正负号
                       
                       
‘ACS_PLUS’             加号
                       
                       
‘ACS_RARROW’           向右箭头
                       
                       
‘ACS_RTEE’             右侧 T 型
                       
                       
‘ACS_S1’               扫描线 1
                       
                       
‘ACS_S3’               扫描线3
                       
                       
‘ACS_S7’               扫描线7
                       
                       
‘ACS_S9’               扫描线 9
                       
                       
‘ACS_SBBS’             右下角的别名
                       
                       
‘ACS_SBSB’             垂直线的别名
                       
                       
‘ACS_SBSS’             右侧 T 型的别名
                       
                       
‘ACS_SSBB’             左下角的别名
                       
                       
‘ACS_SSBS’             底部 T 型的别名
                       
                       
‘ACS_SSSB’             左侧 T 型的别名
                       
                       
‘ACS_SSSS’             交叉或大加号的替代名称
                       
                       
‘ACS_STERLING’         英镑
                       
                       
‘ACS_TTEE’             顶部 T 型
                       
                       
‘ACS_UARROW’           向上箭头
                       
                       
‘ACS_ULCORNER’         左上角
                       
                       
‘ACS_URCORNER’         右上角
                       
                       
‘ACS_VLINE’            垂线
                       

下表列出了预定义的颜色：

常数                    颜色
                        
---------------------------------------------------------
                        
‘COLOR_BLACK’           黑色
                        
                        
‘COLOR_BLUE’            蓝色
                        
                        
‘COLOR_CYAN’            青色（浅绿蓝色）
                        
                        
‘COLOR_GREEN’           绿色
                        
                        
‘COLOR_MAGENTA’         洋红色（紫红色）
                        
                        
‘COLOR_RED’             红色
                        
                        
‘COLOR_WHITE’           白色
                        
                        
‘COLOR_YELLOW’          黄色
                        


File: python.info,  Node: curses textpad --- 用于 curses 程序的文本输入控件,  Next: curses ascii --- 用于 ASCII 字符的工具,  Prev: curses --- 终端字符单元显示的处理,  Up: 通用操作系统服务

5.16.11 ‘curses.textpad’ — 用于 curses 程序的文本输入控件
---------------------------------------------------------

*note curses.textpad: 2e. 模块提供了一个 *note Textbox: 2348. 类，该类在
curses 窗口中处理基本的文本编辑，支持一组与 Emacs 类似的键绑定（因此这也
适用于 Netscape Navigator, BBedit 6.x, FrameMaker 和许多其他程序）。 该
模块还提供了一个绘制矩形的函数，适用于容纳文本框或其他目的。

*note curses.textpad: 2e. 模块定义了以下函数:

 -- 函式: curses.textpad.rectangle (win, uly, ulx, lry, lrx)

     绘制一个矩形。 第一个参数必须为窗口对象；其余参数均为相对于该窗口的
     坐标值。 第二和第三个参数为要绘制的矩形的左上角的 y 和 x 坐标值；第
     四和第五个参数为其右下角的 y 和 x 坐标值。 将会使用 VT100/IBM PC 形
     式的字符在可用的终端上（包括 xterm 和大多数其他软件终端模拟器）绘制
     矩形。 在其他情况下则将使用 ASCII 横杠、竖线和加号绘制。

* Menu:

* 文本框对象::


File: python.info,  Node: 文本框对象,  Up: curses textpad --- 用于 curses 程序的文本输入控件

5.16.11.1 文本框对象
....................

你可以通过如下方式实例化一个 *note Textbox: 2348.:

 -- 類別: curses.textpad.Textbox (win)

     返回一个文本框控件对象。 `win' 参数必须是一个 curses *note 窗口:
     22d8. 对象，文本框将被包含在其中。 文本框的编辑光标在初始时位于包含
     窗口的左上角，坐标值为 ‘(0, 0)’。 实例的 *note stripspaces: 234c. 旗
     标初始时为启用。

     *note Textbox: 2348. 对象具有以下方法:

      -- 成員函式: edit ([validator])

          这是你通常将使用的入口点。 它接受编辑按键直到键入了一个终止按
          键。 如果提供了 `validator'，它必须是一个函数。 它将在每次按键
          时被调用并传入相应的按键作作为形参；命令发送将在结果上执行。 此
          方法会以字符串形式返回窗口内容；是否包括窗口中的空白将受到
          *note stripspaces: 234c. 属性的影响。

      -- 成員函式: do_command (ch)

          处理单个按键命令。以下是支持的特殊按键：

          按键                   动作
                                 
          -----------------------------------------------------------------------
                                 
          ‘Control-A’            转到窗口的左边缘。
                                 
                                 
          ‘Control-B’            光标向左，如果可能，包含前一行。
                                 
                                 
          ‘Control-D’            删除光标下的字符。
                                 
                                 
          ‘Control-E’            前往右边缘（stripspaces 关闭时）或者行尾（
                                 stripspaces 启用时）。
                                 
                                 
          ‘Control-F’            向右移动光标，适当时换行到下一行。
                                 
                                 
          ‘Control-G’            终止，返回窗口内容。
                                 
                                 
          ‘Control-H’            向后删除字符。
                                 
                                 
          ‘Control-J’            如果窗口是1行则终止，否则插入换行符。
                                 
                                 
          ‘Control-K’            如果行为空，则删除它，否则清除到行尾。
                                 
                                 
          ‘Control-L’            刷新屏幕。
                                 
                                 
          ‘Control-N’            光标向下;向下移动一行。
                                 
                                 
          ‘Control-O’            在光标位置插入一个空行。
                                 
                                 
          ‘Control-P’            光标向上;向上移动一行。
                                 

          如果光标位于无法移动的边缘，则移动操作不执行任何操作。在可能的
          情况下，支持以下同义词：

          常数                         按键
                                       
          ----------------------------------------------------
                                       
          ‘KEY_LEFT’                   ‘Control-B’
                                       
                                       
          ‘KEY_RIGHT’                  ‘Control-F’
                                       
                                       
          ‘KEY_UP’                     ‘Control-P’
                                       
                                       
          ‘KEY_DOWN’                   ‘Control-N’
                                       
                                       
          ‘KEY_BACKSPACE’              ‘Control-h’
                                       

          所有其他按键将被视为插入给定字符并右移的命令（带有自动折行）。

      -- 成員函式: gather ()

          以字符串形式返回窗口内容；是否包括窗口中的空白将受到 *note
          stripspaces: 234c. 成员的影响。

      -- 屬性: stripspaces

          此属性是控制窗口中空白解读方式的旗标。 当启用时，每一行的末尾
          空白会被忽略；任何将光标定位至末尾空白的光标动作都将改为前往该
          行末尾，并且在收集窗口内容时将去除末尾空白。


File: python.info,  Node: curses ascii --- 用于 ASCII 字符的工具,  Next: curses panel --- curses 的面板栈扩展,  Prev: curses textpad --- 用于 curses 程序的文本输入控件,  Up: 通用操作系统服务

5.16.12 ‘curses.ascii’ — 用于 ASCII 字符的工具
----------------------------------------------

__________________________________________________________________

*note curses.ascii: 2c. 模块提供了一些 ASCII 字符的名称常量以及在各种
ASCII 字符类中执行成员检测的函数。 所提供的控制字符常量如下:

名称               含义
                   
----------------------------------------------------------------------
                   
‘NUL’

‘SOH’              标题开始，控制台中断
                   
                   
‘STX’              文本开始
                   
                   
‘ETX’              文本结束
                   
                   
‘EOT’              传输结束
                   
                   
‘ENQ’              查询，附带 ‘ACK’ 流量控制
                   
                   
‘ACK’              确认
                   
                   
‘BEL’              蜂鸣器
                   
                   
‘BS’               退格
                   
                   
‘TAB’              制表符
                   
                   
‘HT’               ‘TAB’ 的别名： "水平制表符”
                   
                   
‘LF’               换行
                   
                   
‘NL’               ‘LF’ 的别名： "新行"
                   
                   
‘VT’               垂直制表符
                   
                   
‘FF’               换页
                   
                   
‘CR’               回车
                   
                   
‘SO’               Shift-out，开始替换字符集
                   
                   
‘SI’               Shift-in，恢复默认字符集
                   
                   
‘DLE’              Data-link escape，数据链接转义
                   
                   
‘DC1’              XON，用于流程控制
                   
                   
‘DC2’              Device control 2，块模式流程控制
                   
                   
‘DC3’              XOFF，用于流程控制
                   
                   
‘DC4’              设备控制4
                   
                   
‘NAK’              否定确认
                   
                   
‘SYN’              同步空闲
                   
                   
‘ETB’              末端传输块
                   
                   
‘CAN’              取消
                   
                   
‘EM’               媒体结束
                   
                   
‘SUB’              替换
                   
                   
‘ESC’              退出
                   
                   
‘FS’               文件分隔符
                   
                   
‘GS’               组分隔符
                   
                   
‘RS’               Record separator，块模式终止符
                   
                   
‘US’               单位分隔符
                   
                   
‘SP’               空格
                   
                   
‘DEL’              删除
                   

请注意其中有许多在现今已经没有实际作用。 这些助记符是来源于数字计算机之
前的电传打印机规范。

此模块提供了下列函数，对应于标准 C 库中的函数:

 -- 函式: curses.ascii.isalnum (c)

     检测 ASCII 字母数字类字符；它等价于 ‘isalpha(c) 或 isdigit(c)’。

 -- 函式: curses.ascii.isalpha (c)

     检测 ASCII 字母类字符；它等价于 ‘isupper(c) or islower(c)’。

 -- 函式: curses.ascii.isascii (c)

     检测字符值是否在 7 位 ASCII 集范围内。

 -- 函式: curses.ascii.isblank (c)

     检测 ASCII 空白字符；包括空格或水平制表符。

 -- 函式: curses.ascii.iscntrl (c)

     检测 ASCII 控制字符（在 0x00 到 0x1f 或 0x7f 范围内）。

 -- 函式: curses.ascii.isdigit (c)

     检测 ASCII 十进制数码，即 ‘'0'’ 至 ‘'9'’。 它等价于 ‘c in
     string.digits’。

 -- 函式: curses.ascii.isgraph (c)

     检测任意 ASCII 可打印字符，不包括空白符。

 -- 函式: curses.ascii.islower (c)

     检测 ASCII 小写字母字符。

 -- 函式: curses.ascii.isprint (c)

     检测任意 ASCII 可打印字符，包括空白符。

 -- 函式: curses.ascii.ispunct (c)

     检测任意 ASCII 可打印字符，不包括空白符或字母数字类字符。

 -- 函式: curses.ascii.isspace (c)

     检测 ASCII 空白字符；包括空格，换行，回车，进纸，水平制表和垂直制表
     。

 -- 函式: curses.ascii.isupper (c)

     检测 ASCII 大写字母字符。

 -- 函式: curses.ascii.isxdigit (c)

     检测 ASCII 十六进制数码。 这等价于 ‘c in string.hexdigits’。

 -- 函式: curses.ascii.isctrl (c)

     检测 ASCII 控制字符（码位值 0 至 31）。

 -- 函式: curses.ascii.ismeta (c)

     检测非 ASCII 字符（码位值 0x80 及以上）。

这些函数接受整数或单字符字符串；当参数为字符串时，会先使用内置函数 *note
ord(): 1559. 进行转换。

请注意所有这些函数都是检测根据你传入的字符串的字符所生成的码位值；它们实
际上完全不会知晓本机的字符编码格式。

以下两个函数接受单字符字符串或整数形式的字节值；它们会返回相同类型的值。

 -- 函式: curses.ascii.ascii (c)

     返回对应于 `c' 的下个 7 比特位的 ASCII 值。

 -- 函式: curses.ascii.ctrl (c)

     返回对应于给定字符的控制字符（字符比特值会与 0x1f 进行按位与运算）
     。

 -- 函式: curses.ascii.alt (c)

     返回对应于给定 ASCII 字符的 8 比特位字符（字符比特值会与 0x80 进行
     按位或运算）。

以下函数接受单字符字符串或整数值；它会返回一个字符串。

 -- 函式: curses.ascii.unctrl (c)

     返回 ASCII 字符 `c' 的字符串表示形式。 如果 `c' 是可打印字符，则字
     符串为字符本身。 如果该字符是控制字符 (0x00–0x1f) 则字符串由一个插
     入符 (‘'^'’) 加相应的大写字母组成。 如果该字符是 ASCII 删除符
     (0x7f) 则字符串为 ‘'^?'’。 如果该字符设置了元比特位 (0x80)，元比特
     位会被去除，应用以上规则后将在结果之前添加 ‘'!'’。

 -- Data: curses.ascii.controlnames

     一个 33 元素的字符串数据，其中按从 0 (NUL) 到 0x1f (US) 的顺序包含
     了三十二个 ASCII 控制字符的 ASCII 助记符，另加空格符的助记符 ‘SP’。


File: python.info,  Node: curses panel --- curses 的面板栈扩展,  Next: platform --- 获取底层平台的标识数据,  Prev: curses ascii --- 用于 ASCII 字符的工具,  Up: 通用操作系统服务

5.16.13 ‘curses.panel’ — curses 的面板栈扩展
--------------------------------------------

__________________________________________________________________

面板是具有添加深度功能的窗口，因此它们可以从上至下堆叠为栈，只有显示每个
窗口的可见部分会显示出来。 面板可以在栈中被添加、上移或下移，也可以被移
除。

* Menu:

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


File: python.info,  Node: 函数<5>,  Next: Panel 对象,  Up: curses panel --- curses 的面板栈扩展

5.16.13.1 函数
..............

*note curses.panel: 2d. 模块定义了以下函数:

 -- 函式: curses.panel.bottom_panel ()

     返回面板栈中的底部面板。

 -- 函式: curses.panel.new_panel (win)

     返回一个面板对象，将其与给定的窗口 `win' 相关联。 请注意你必须显式
     地保持所返回的面板对象。 如果你不这样做，面板对象会被垃圾回收并从面
     板栈中被移除。

 -- 函式: curses.panel.top_panel ()

     返回面板栈中的顶部面板。

 -- 函式: curses.panel.update_panels ()

     在面板栈发生改变后更新虚拟屏幕。 这不会调用 *note
     curses.doupdate(): 22bf.，因此你不必自己执行此操作。


File: python.info,  Node: Panel 对象,  Prev: 函数<5>,  Up: curses panel --- curses 的面板栈扩展

5.16.13.2 Panel 对象
....................

Panel 对象，如上面 *note new_panel(): 236b. 所返回的对象，是带有栈顺序的
多个窗口。 总是会有一个窗口与确定内容的面板相关联，面板方法会负责窗口在
面板栈中的深度。

Panel 对象具有以下方法:

 -- 成員函式: Panel.above ()

     返回当前面板之上的面板。

 -- 成員函式: Panel.below ()

     返回当前面板之下的面板。

 -- 成員函式: Panel.bottom ()

     将面板推至栈底部。

 -- 成員函式: Panel.hidden ()

     如果面板被隐藏（不可见）则返回 ‘True’，否则返回 ‘False’。

 -- 成員函式: Panel.hide ()

     隐藏面板。 这不会删除对象，它只是让窗口在屏幕上不可见。

 -- 成員函式: Panel.move (y, x)

     将面板移至屏幕坐标 ‘(y, x)’。

 -- 成員函式: Panel.replace (win)

     将与面板相关联的窗口改为窗口 `win'。

 -- 成員函式: Panel.set_userptr (obj)

     将面板的用户指向设为 `obj'。 这被用来将任意数据与面板相关联，数据可
     以是任何 Python 对象。

 -- 成員函式: Panel.show ()

     显示面板（面板可能已被隐藏）。

 -- 成員函式: Panel.top ()

     将面板推至栈顶部。

 -- 成員函式: Panel.userptr ()

     返回面板的用户指针。 这可以是任何 Python 对象。

 -- 成員函式: Panel.window ()

     返回与面板相关联的窗口对象。


File: python.info,  Node: platform --- 获取底层平台的标识数据,  Next: errno --- 标准 errno 系统符号,  Prev: curses panel --- curses 的面板栈扩展,  Up: 通用操作系统服务

5.16.14 ‘platform’ — 获取底层平台的标识数据
-------------------------------------------

`源代码：' Lib/platform.py(1)

__________________________________________________________________

     備註: 特定平台按字母顺序排列，Linux 包括在 Unix 小节之中。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/platform.py


File: python.info,  Node: 跨平台,  Next: Java平台,  Up: platform --- 获取底层平台的标识数据

5.16.14.1 跨平台
................

 -- 函式: platform.architecture (executable=sys.executable, bits='',
          linkage='')

     查询给定的可执行文件（默认为 Python 解释器二进制码文件）来获取各种
     架构信息。

     返回一个元素 ‘(bits, linkage)’，其中包含可执行文件所使用的位架构和
     链接格式信息。 这两个值均以字符串形式返回。

     无法确定的值将返回为形参预设所给出的值。 如果给出的位数为 ‘''’，则
     会使用 ‘sizeof(pointer)’ (或者当 Python 版本 < 1.5.2 时为
     ‘sizeof(long)’) 作为所支持的指针大小的提示。

     此函数依赖于系统的 ‘file’ 命令来执行实际的操作。 这在几乎所有 Unix
     平台和某些非 Unix 平台上只有当可执行文件指向 Python 解释器时才可用
     。 当以上要求不满足时将会使用合理的默认值。

          備註: 在 macOS (也许还有其他平台) 上，可执行文件可能是包含多种
          架构的通用文件。

          要获取当前解释器的“64 位性”，更可靠的做法是查询 *note
          sys.maxsize: c15. 属性:

               is_64bits = sys.maxsize > 2**32

 -- 函式: platform.machine ()

     返回机器类型，例如 ‘'i386'’。 如果该值无法确定则会返回一个空字符串
     。

 -- 函式: platform.node ()

     返回计算机的网络名称（可能不是完整限定名称！）。 如果该值无法确定则
     会返回一个空字符串。

 -- 函式: platform.platform (aliased=0, terse=0)

     返回一个标识底层平台的字符串，其中带有尽可能多的有用信息。

     输出信息的目标是“人类易读”而非机器易解析。 它在不同平台上可能看起来
     不一致，这是有意为之的。

     如果 `aliased' 为真值，此函数将使用各种平台不同与其通常名称的别名来
     报告系统名称，例如 SunOS 将被报告为 Solaris。 *note system_alias():
     2381. 函数将被用于实现此功能。

     将 `terse' 设为真值将导致此函数只返回标识平台所必须的最小量信息。

     3.8 版更變: 在 macOS 上，此函数现在会在 *note mac_ver(): 1154. 返回
     的发布版字符串非空时使用它，以便获取 macOS 版本而非 darwin 版本。

 -- 函式: platform.processor ()

     返回（真实的）处理器名称，例如 ‘'amdk6'’。

     如果该值无法确定则将返回空字符串。 请注意许多平台都不提供此信息或是
     简单地返回与 *note machine(): 237f. 相同的值。 NetBSD 则会提供此信
     息。

 -- 函式: platform.python_build ()

     返回一个元组 ‘(buildno, builddate)’，以字符串表示的 Python 编译代码
     和日期。

 -- 函式: platform.python_compiler ()

     返回一个标识用于编译 Python 的编译器的的字符串。

 -- 函式: platform.python_branch ()

     返回一个标识 Python 实现的 SCM 分支的字符串。

 -- 函式: platform.python_implementation ()

     返回一个标识 Python 实现的字符串。 可能的返回值有: ’CPython’,
     ’IronPython’, ’Jython’, ’PyPy’。

 -- 函式: platform.python_revision ()

     返回一个标识 Python 实现的 SCM 修订版的字符串。

 -- 函式: platform.python_version ()

     将 Python 版本以字符串 ‘'major.minor.patchlevel'’ 形式返回。

     请注意此返回值不同于 Python ‘sys.version’，它将总是包括 patchlevel
     (默认为 0)。

 -- 函式: platform.python_version_tuple ()

     将 Python 版本以字符串元组 ‘(major, minor, patchlevel)’ 形式返回。

     请注意此返回值不同于 Python ‘sys.version’，它将总是包括 patchlevel
     (默认为 ‘'0'’)。

 -- 函式: platform.release ()

     返回系统的发布版本，例如 ‘'2.2.0'’ 或 ‘'NT'’，如果该值无法确定则将
     返回一个空字符串。

 -- 函式: platform.system ()

     返回系统平台/OS的名称，例如 ‘'Linux'’, ‘'Darwin'’, ‘'Java'’,
     ‘'Windows'’。 如果该值无法确定则将返回一个空字符串。

 -- 函式: platform.system_alias (system, release, version)

     返回别名为某些系统所使用的常见营销名称的 ‘(system, release,
     version)’。 它还会在可能导致混淆的情况下对信息进行一些重排序操作。

 -- 函式: platform.version ()

     返回系统的发布版本信息，例如 ‘'#3 on degas'’。 如果该值无法确定则将
     返回一个空字符串。

 -- 函式: platform.uname ()

     具有高可移植性的 uname 接口。 返回包含六个属性的 *note
     namedtuple(): 1a1.: *note system: 238b, *note node: 2380, *note
     release: 238a, *note version: 238c, *note machine: 237f. 和 *note
     processor: 2382.。

     请注意此函数添加的第六个属性 (*note processor: 2382.) 并不存在于
     *note os.uname(): b38. 的结果中。 并且前两个属性的属性名称也不一致
     ；*note os.uname(): b38. 是将它们称为 ‘sysname’ 和 ‘nodename’。

     无法确定的条目会被设为 ‘''’。

     3.3 版更變: 将结果从元组改为命名元组。


File: python.info,  Node: Java平台,  Next: Windows平台,  Prev: 跨平台,  Up: platform --- 获取底层平台的标识数据

5.16.14.2 Java平台
..................

 -- 函式: platform.java_ver (release='', vendor='', vminfo=('', '', ''),
          osinfo=('', '', ''))

     Jython 的版本接口

     返回一个元组 ‘(release, vendor, vminfo, osinfo)’，其中 `vminfo' 为
     元组 ‘(vm_name, vm_release, vm_vendor)’ 而 `osinfo' 为元组
     ‘(os_name, os_version, os_arch)’。 无法确定的值将设为由形参所给出的
     默认值 (默认均为 ‘''’)。


File: python.info,  Node: Windows平台,  Next: macOS Platform,  Prev: Java平台,  Up: platform --- 获取底层平台的标识数据

5.16.14.3 Windows平台
.....................

 -- 函式: platform.win32_ver (release='', version='', csd='', ptype='')

     从 Windows 注册表获取额外的版本信息并返回一个元组 ‘(release,
     version, csd, ptype)’ 表示 OS 发行版, 版本号, CSD 级别 (Service
     Pack) 和 OS 类型 (多个/单个处理器)。

     一点提示: `ptype' 在单个处理器的 NT 机器上为 ‘'Uniprocessor Free'’
     而在多个处理器的机器上为 ‘'Multiprocessor Free'’。 `’Free’' 是指该
     OS 版本没有调试代码。 它还可能显示 `’Checked’' 表示该 OS 版本使用了
     调试代码，即检测参数、范围等的代码。

 -- 函式: platform.win32_edition ()

     返回一个代表当前 Windows 版本的字符串。 可能的值包括但不限于
     ‘'Enterprise'’, ‘'IoTUAP'’, ‘'ServerStandard'’ 和 ‘'nanoserver'’。

     3.8 版新加入.

 -- 函式: platform.win32_is_iot ()

     如果 *note win32_edition(): 2390. 返回的 Windows 版本被识别为 IoT 版
     则返回 ‘True’。

     3.8 版新加入.


File: python.info,  Node: macOS Platform,  Next: Unix 平台,  Prev: Windows平台,  Up: platform --- 获取底层平台的标识数据

5.16.14.4 macOS Platform
........................

 -- 函式: platform.mac_ver (release='', versioninfo=('', '', ''),
          machine='')

     Get macOS version information and return it as tuple ‘(release,
     versioninfo, machine)’ with `versioninfo' being a tuple ‘(version,
     dev_stage, non_release_version)’.

     无法确定的条目会被设为 ‘''’。 所有元组条目均为字符串。


File: python.info,  Node: Unix 平台,  Prev: macOS Platform,  Up: platform --- 获取底层平台的标识数据

5.16.14.5 Unix 平台
...................

 -- 函式: platform.libc_ver (executable=sys.executable, lib='',
          version='', chunksize=16384)

     尝试确定可执行文件（默认为 Python 解释器）所链接到的 libc 版本。 返
     回一个字符串元组 ‘(lib, version)’，当查找失败时其默认值将设为给定的
     形参值。

     请注意此函数对于不同 libc 版本向可执行文件添加符号的方式有深层的关
     联，可能仅适用于使用 ‘gcc’ 编译出来的可执行文件。

     文件将按 `chunksize' 个字节的分块来读取和扫描。


File: python.info,  Node: errno --- 标准 errno 系统符号,  Next: ctypes --- Python 的外部函数库,  Prev: platform --- 获取底层平台的标识数据,  Up: 通用操作系统服务

5.16.15 ‘errno’ — 标准 errno 系统符号
-------------------------------------

__________________________________________________________________

本模块提供标准的 ‘errno’ 系统符号。每个符号的值是其对应的整数值。符号的
名称和描述来自 ‘linux/include/errno.h’，应该是非常全面的。

 -- Data: errno.errorcode

     提供从 errno 值到底层系统中字符串名称的映射的字典。例如，
     ‘errno.errorcode[errno.EPERM]’ 映射为 ‘'EPERM'’ 。

如果要将数字的错误代码转换为错误信息，请使用 *note os.strerror(): 2062.。

在下面的列表中，当前平台上没有使用的符号没有被本模块定义。 已定义的符号
的具体列表可参见 ‘errno.errorcode.keys()’。 可用的符号包括：

 -- Data: errno.EPERM

     操作不被允许

 -- Data: errno.ENOENT

     无此文件或目录

 -- Data: errno.ESRCH

     无此进程

 -- Data: errno.EINTR

     系统调用中断。

     也參考
     ......

     此错误被映射到异常 *note InterruptedError: 74c.。

 -- Data: errno.EIO

     I/O 错误

 -- Data: errno.ENXIO

     无此设备或地址

 -- Data: errno.E2BIG

     参数列表过长

 -- Data: errno.ENOEXEC

     执行格式错误

 -- Data: errno.EBADF

     错误的文件号

 -- Data: errno.ECHILD

     没有子进程

 -- Data: errno.EAGAIN

     重试

 -- Data: errno.ENOMEM

     内存不足

 -- Data: errno.EACCES

     没有权限

 -- Data: errno.EFAULT

     错误的地址

 -- Data: errno.ENOTBLK

     需要块设备

 -- Data: errno.EBUSY

     设备或资源忙

 -- Data: errno.EEXIST

     文件已存在

 -- Data: errno.EXDEV

     跨设备链接

 -- Data: errno.ENODEV

     无此设备

 -- Data: errno.ENOTDIR

     不是目录

 -- Data: errno.EISDIR

     是目录

 -- Data: errno.EINVAL

     无效的参数

 -- Data: errno.ENFILE

     文件表溢出

 -- Data: errno.EMFILE

     打开的文件过多

 -- Data: errno.ENOTTY

     不是打字机

 -- Data: errno.ETXTBSY

     文本文件忙

 -- Data: errno.EFBIG

     文件过大

 -- Data: errno.ENOSPC

     设备已无可用空间

 -- Data: errno.ESPIPE

     非法查找

 -- Data: errno.EROFS

     只读文件系统

 -- Data: errno.EMLINK

     链接过多

 -- Data: errno.EPIPE

     管道已损坏

 -- Data: errno.EDOM

     数学参数超出函数范围

 -- Data: errno.ERANGE

     数学运算结果无法表示

 -- Data: errno.EDEADLK

     将发生资源死锁

 -- Data: errno.ENAMETOOLONG

     文件名过长

 -- Data: errno.ENOLCK

     没有可用的记录锁

 -- Data: errno.ENOSYS

     功能未实现

 -- Data: errno.ENOTEMPTY

     目录非空

 -- Data: errno.ELOOP

     遇到过多的符号链接

 -- Data: errno.EWOULDBLOCK

     操作将阻塞

 -- Data: errno.ENOMSG

     没有所需类型的消息

 -- Data: errno.EIDRM

     标识符被移除

 -- Data: errno.ECHRNG

     信道编号超出范围

 -- Data: errno.EL2NSYNC

     级别 2 未同步

 -- Data: errno.EL3HLT

     级别 3 已停止

 -- Data: errno.EL3RST

     级别 3 重置

 -- Data: errno.ELNRNG

     链接编号超出范围

 -- Data: errno.EUNATCH

     未附加协议驱动

 -- Data: errno.ENOCSI

     没有可用的 CSI 结构

 -- Data: errno.EL2HLT

     级别 2 已停止

 -- Data: errno.EBADE

     无效的交换

 -- Data: errno.EBADR

     无效的请求描述符

 -- Data: errno.EXFULL

     交换已满

 -- Data: errno.ENOANO

     没有阳极

 -- Data: errno.EBADRQC

     无效的请求码·

 -- Data: errno.EBADSLT

     无效的槽位

 -- Data: errno.EDEADLOCK

     文件锁定死锁错误

 -- Data: errno.EBFONT

     错误的字体文件格式

 -- Data: errno.ENOSTR

     设备不是流

 -- Data: errno.ENODATA

     没有可用的数据

 -- Data: errno.ETIME

     计时器已到期

 -- Data: errno.ENOSR

     流资源不足

 -- Data: errno.ENONET

     机器不在网络上

 -- Data: errno.ENOPKG

     包未安装

 -- Data: errno.EREMOTE

     对象是远程的

 -- Data: errno.ENOLINK

     链接已被切断

 -- Data: errno.EADV

     广告错误

 -- Data: errno.ESRMNT

     挂载错误

 -- Data: errno.ECOMM

     发送时通讯错误

 -- Data: errno.EPROTO

     协议错误

 -- Data: errno.EMULTIHOP

     已尝试多跳

 -- Data: errno.EDOTDOT

     RFS 专属错误

 -- Data: errno.EBADMSG

     非数据消息

 -- Data: errno.EOVERFLOW

     值相对于已定义数据类型过大

 -- Data: errno.ENOTUNIQ

     名称在网络上不唯一

 -- Data: errno.EBADFD

     文件描述符处于错误状态

 -- Data: errno.EREMCHG

     远端地址已改变

 -- Data: errno.ELIBACC

     无法访问所需的共享库

 -- Data: errno.ELIBBAD

     访问已损坏的共享库

 -- Data: errno.ELIBSCN

     a.out 中的 .lib 部分已损坏

 -- Data: errno.ELIBMAX

     尝试链接过多的共享库

 -- Data: errno.ELIBEXEC

     无法直接执行共享库

 -- Data: errno.EILSEQ

     非法字节序列

 -- Data: errno.ERESTART

     已中断系统调用需要重启

 -- Data: errno.ESTRPIPE

     流管道错误

 -- Data: errno.EUSERS

     用户过多

 -- Data: errno.ENOTSOCK

     在非套接字上执行套接字操作

 -- Data: errno.EDESTADDRREQ

     需要目标地址

 -- Data: errno.EMSGSIZE

     消息过长

 -- Data: errno.EPROTOTYPE

     套接字的协议类型错误

 -- Data: errno.ENOPROTOOPT

     协议不可用

 -- Data: errno.EPROTONOSUPPORT

     协议不受支持

 -- Data: errno.ESOCKTNOSUPPORT

     套接字类型不受支持

 -- Data: errno.EOPNOTSUPP

     操作在传输端点上不受支持

 -- Data: errno.EPFNOSUPPORT

     协议族不受支持

 -- Data: errno.EAFNOSUPPORT

     地址族不受协议支持

 -- Data: errno.EADDRINUSE

     地址已被使用

 -- Data: errno.EADDRNOTAVAIL

     无法分配要求的地址

 -- Data: errno.ENETDOWN

     网络已断开

 -- Data: errno.ENETUNREACH

     网络不可达

 -- Data: errno.ENETRESET

     网络因重置而断开连接

 -- Data: errno.ECONNABORTED

     软件导致连接中止

 -- Data: errno.ECONNRESET

     连接被对方重置

 -- Data: errno.ENOBUFS

     没有可用的缓冲区空间

 -- Data: errno.EISCONN

     传输端点已连接

 -- Data: errno.ENOTCONN

     传输端点未连接

 -- Data: errno.ESHUTDOWN

     传输端点关闭后无法发送

 -- Data: errno.ETOOMANYREFS

     引用过多：无法拼接

 -- Data: errno.ETIMEDOUT

     连接超时

 -- Data: errno.ECONNREFUSED

     连接被拒

 -- Data: errno.EHOSTDOWN

     主机已关闭

 -- Data: errno.EHOSTUNREACH

     没有到主机的路由

 -- Data: errno.EALREADY

     操作已在进行

 -- Data: errno.EINPROGRESS

     操作正在进行

 -- Data: errno.ESTALE

     过期的 NFS 文件句柄

 -- Data: errno.EUCLEAN

     结构需要清理

 -- Data: errno.ENOTNAM

     不是 XENIX 命名类型文件

 -- Data: errno.ENAVAIL

     没有可用的 XENIX 信标

 -- Data: errno.EISNAM

     是命名类型文件

 -- Data: errno.EREMOTEIO

     远程 I/O 错误

 -- Data: errno.EDQUOT

     超出配额


File: python.info,  Node: ctypes --- Python 的外部函数库,  Prev: errno --- 标准 errno 系统符号,  Up: 通用操作系统服务

5.16.16 ‘ctypes’ — Python 的外部函数库
--------------------------------------

__________________________________________________________________

*note ctypes: 2a. 是 Python 的外部函数库。它提供了与 C 兼容的数据类型，
并允许调用 DLL 或共享库中的函数。可使用该模块以纯 Python 形式对这些库进
行封装。

* Menu:

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


File: python.info,  Node: ctypes 教程,  Next: ctypes 参考手册,  Up: ctypes --- Python 的外部函数库

5.16.16.1 ctypes 教程
.....................

Note: The code samples in this tutorial use *note doctest: 66. to make
sure that they actually work.  Since some code samples behave
differently under Linux, Windows, or macOS, they contain doctest
directives in comments.

注意：部分示例代码引用了 ctypes *note c_int: 240f. 类型。在
‘sizeof(long) == sizeof(int)’ 的平台上此类型是 *note c_long: 2410. 的一
个别名。所以，在程序输出 *note c_long: 2410. 而不是你期望的 *note c_int:
240f. 时不必感到迷惑 — 它们实际上是同一种类型。

* Menu:

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


File: python.info,  Node: 载入动态连接库,  Next: 操作导入的动态链接库中的函数,  Up: ctypes 教程

5.16.16.2 载入动态连接库
........................

*note ctypes: 2a. 导出了 `cdll' 对象，在 Windows 系统中还导出了 `windll'
和 `oledll' 对象用于载入动态连接库。

通过操作这些对象的属性，你可以载入外部的动态链接库。`cdll' 载入按标准的
‘cdecl’ 调用协议导出的函数，而 `windll' 导入的库按 ‘stdcall’ 调用协议调
用其中的函数。 `oledll' 也按 ‘stdcall’ 调用协议调用其中的函数，并假定该
函数返回的是 Windows ‘HRESULT’ 错误代码，并当函数调用失败时，自动根据该
代码甩出一个 *note OSError: 304. 异常。

3.3 版更變: 原来在 Windows 下抛出的异常类型 *note WindowsError: a75. 现
在是 *note OSError: 304. 的一个别名。

这是一些 Windows 下的例子。注意：‘msvcrt’ 是微软 C 标准库，包含了大部分
C 标准函数，这些函数都是以 cdecl 调用协议进行调用的。

     >>> from ctypes import *
     >>> print(windll.kernel32)
     <WinDLL 'kernel32', handle ... at ...>
     >>> print(cdll.msvcrt)
     <CDLL 'msvcrt', handle ... at ...>
     >>> libc = cdll.msvcrt
     >>>

Windows 会自动添加通常的 ‘.dll’ 文件扩展名。

     備註: 通过 ‘cdll.msvcrt’ 调用的标准 C 函数，可能会导致调用一个过时
     的，与当前 Python 所不兼容的函数。因此，请尽量使用标准的 Python 函
     数，而不要使用 ‘msvcrt’ 模块。

在 Linux 下，必须使用 `包含' 文件扩展名的文件名来导入共享库。因此不能简
单使用对象属性的方式来导入库。因此，你可以使用方法 ‘LoadLibrary()’，或构
造 CDLL 对象来导入库。

     >>> cdll.LoadLibrary("libc.so.6")
     <CDLL 'libc.so.6', handle ... at ...>
     >>> libc = CDLL("libc.so.6")
     >>> libc
     <CDLL 'libc.so.6', handle ... at ...>
     >>>


File: python.info,  Node: 操作导入的动态链接库中的函数,  Next: 调用函数,  Prev: 载入动态连接库,  Up: ctypes 教程

5.16.16.3 操作导入的动态链接库中的函数
......................................

通过操作dll对象的属性来操作这些函数。

     >>> 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
     >>>

注意：Win32 系统的动态库，比如 ‘kernel32’ 和 ‘user32’，通常会同时导出同
一个函数的 ANSI 版本和 UNICODE 版本。UNICODE 版本通常会在名字最后以 ‘W’
结尾，而 ANSI 版本的则以 ‘A’ 结尾。 win32的 ‘GetModuleHandle’ 函数会根据
一个模块名返回一个 `模块句柄'，该函数暨同时包含这样的两个版本的原型函数
，并通过宏 UNICODE 是否定义，来决定宏 ‘GetModuleHandle’ 导出的是哪个具体
函数。

     /* ANSI version */
     HMODULE GetModuleHandleA(LPCSTR lpModuleName);
     /* UNICODE version */
     HMODULE GetModuleHandleW(LPCWSTR lpModuleName);

`windll' 不会通过这样的魔法手段来帮你决定选择哪一种函数，你必须显式的调
用 ‘GetModuleHandleA’ 或 ‘GetModuleHandleW’，并分别使用字节对象或字符串
对象作参数。

有时候，dlls的导出的函数名不符合 Python 的标识符规范，比如
‘"??2@YAPAXI@Z"’。此时，你必须使用 *note getattr(): 54b. 方法来获得该函
数。

     >>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")
     <_FuncPtr object at 0x...>
     >>>

Windows 下，有些 dll 导出的函数没有函数名，而是通过其顺序号调用。对此类
函数，你也可以通过 dll 对象的数值索引来操作这些函数。

     >>> 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
     >>>


File: python.info,  Node: 调用函数,  Next: 基础数据类型,  Prev: 操作导入的动态链接库中的函数,  Up: ctypes 教程

5.16.16.4 调用函数
..................

你可以貌似是调用其它 Python 函数那样直接调用这些函数。在这个例子中，我们
调用了 ‘time()’ 函数，该函数返回一个系统时间戳（从 Unix 时间起点到现在的
秒数），而‘‘GetModuleHandleA()‘‘ 函数返回一个 win32 模块句柄。

此函数中调用的两个函数都使用了空指针（用 ‘None’ 作为空指针）:

     >>> print(libc.time(None))
     1150640792
     >>> print(hex(windll.kernel32.GetModuleHandleA(None)))
     0x1d000000
     >>>

如果你用 ‘cdecl’ 调用方式调用 ‘stdcall’ 约定的函数，则会甩出一个异常
*note ValueError: 16d.。反之亦然。

     >>> 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)
     >>>

你必须阅读这些库的头文件或说明文档来确定它们的调用协议。

在 Windows 中，*note ctypes: 2a. 使用 win32 结构化异常处理来防止由于在调
用函数时使用非法参数导致的程序崩溃。

     >>> windll.kernel32.GetModuleHandleA(32)
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     OSError: exception: access violation reading 0x00000020
     >>>

然而，总有许多办法，通过调用 *note ctypes: 2a. 使得 Python 程序崩溃。因
此，你必须小心使用。 *note faulthandler: 7b. 模块可以用于帮助诊断程序崩
溃的原因。（比如由于错误的C库函数调用导致的段错误）。

‘None’，整型，字节对象和（UNICODE）字符串是仅有的可以直接作为函数参数使
用的四种Python本地数据类型。‘None‘’ 作为C的空指针 (‘NULL’)，字节和字符串
类型作为一个指向其保存数据的内存块指针 （‘char *’ 或 ‘wchar_t *’)。
Python 的整型则作为平台默认的C的 ‘int’ 类型，他们的数值被截断以适应C类型
的整型长度。

在我们开始调用函数前，我们必须先了解作为函数参数的 *note ctypes: 2a. 数
据类型。


File: python.info,  Node: 基础数据类型,  Next: 调用函数，继续,  Prev: 调用函数,  Up: ctypes 教程

5.16.16.5 基础数据类型
......................

*note ctypes: 2a. 定义了一些和C兼容的基本数据类型：

ctypes 类型                C 类型                                         Python 数据类型
                                                                          
-----------------------------------------------------------------------------------------------------------
                                                                          
*note c_bool: 2419.        ‘_Bool’                                        bool (1)
                                                                          
                                                                          
*note c_char: 241a.        ‘char’                                         单字符字节串对象
                                                                          
                                                                          
*note c_wchar: 241b.       ‘wchar_t’                                      单字符字符串
                                                                          
                                                                          
*note c_byte: 241c.        ‘char’                                         int
                                                                          
                                                                          
*note c_ubyte: 241d.       ‘unsigned char’                                int
                                                                          
                                                                          
*note c_short: 241e.       ‘short’                                        int
                                                                          
                                                                          
*note c_ushort: 241f.      ‘unsigned short’                               int
                                                                          
                                                                          
*note c_int: 240f.         ‘int’                                          int
                                                                          
                                                                          
*note c_uint: 2420.        ‘unsigned int’                                 int
                                                                          
                                                                          
*note c_long: 2410.        ‘long’                                         int
                                                                          
                                                                          
*note c_ulong: 2421.       ‘unsigned long’                                int
                                                                          
                                                                          
*note c_longlong: 2422.    ‘__int64’ 或 ‘long long’                       int
                                                                          
                                                                          
*note c_ulonglong: 2423.   ‘unsigned __int64’ 或 ‘unsigned long long’     int
                                                                          
                                                                          
*note c_size_t: 2424.      ‘size_t’                                       int
                                                                          
                                                                          
*note c_ssize_t: c9f.      ‘ssize_t’ 或 ‘Py_ssize_t’                      int
                                                                          
                                                                          
*note c_float: 2425.       ‘float’                                        float
                                                                          
                                                                          
*note c_double: fc4.       ‘double’                                       float
                                                                          
                                                                          
*note c_longdouble: fc5.   ‘long double’                                  float
                                                                          
                                                                          
*note c_char_p: 2426.      ‘char *’ (NUL terminated)                      字节串对象或 ‘None’
                                                                          
                                                                          
*note c_wchar_p: fa9.      ‘wchar_t *’ (NUL terminated)                   字符串或 ‘None’
                                                                          
                                                                          
*note c_void_p: 2427.      ‘void *’                                       int 或 ‘None’
                                                                          

  1. 构造函数接受任何具有真值的对象。

所有这些类型都可以通过使用正确类型和值的可选初始值调用它们来创建:

     >>> c_int()
     c_long(0)
     >>> c_wchar_p("Hello, World")
     c_wchar_p(140018365411392)
     >>> c_ushort(-3)
     c_ushort(65533)
     >>>

由于这些类型是可变的，它们的值也可以在以后更改:

     >>> i = c_int(42)
     >>> print(i)
     c_long(42)
     >>> print(i.value)
     42
     >>> i.value = -99
     >>> print(i.value)
     -99
     >>>

当给指针类型的对象 *note c_char_p: 2426, *note c_wchar_p: fa9. 和 *note
c_void_p: 2427. 等赋值时，将改变它们所指向的 `内存地址'，而 `不是' 它们
所指向的内存区域的 `内容' (这是理所当然的，因为 Python 的 bytes 对象是不
可变的):

     >>> 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
     >>>

但你要注意不能将它们传递给会改变指针所指内存的函数。如果你需要可改变的内
存块，ctypes 提供了 *note create_string_buffer(): 2428. 函数，它提供多种
方式创建这种内存块。当前的内存块内容可以通过 ‘raw’ 属性存取，如果你希望
将它作为NUL结束的字符串，请使用 ‘value’ 属性:

     >>> 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'
     >>>

*note create_string_buffer(): 2428. 函数替代以前的ctypes版本中的
‘c_buffer()’ 函数 (仍然可当作别名使用)和 ‘c_string()’ 函数。*note
create_unicode_buffer(): 10d7. 函数创建包含 unicode 字符的可变内存块，与
之对应的C语言类型是 ‘wchar_t’。


File: python.info,  Node: 调用函数，继续,  Next: 使用自定义的数据类型调用函数,  Prev: 基础数据类型,  Up: ctypes 教程

5.16.16.6 调用函数，继续
........................

注意 printf 将打印到真正标准输出设备，而*不是* *note sys.stdout: 41f.，
因此这些实例只能在控制台提示符下工作，而不能在 `IDLE' 或 `PythonWin' 中
运行。

     >>> 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
     >>>

正如前面所提到过的，除了整数、字符串以及字节串之外，所有的 Python 类型都
必须使用它们对应的 *note ctypes: 2a. 类型包装，才能够被正确地转换为所需
的C语言类型。

     >>> printf(b"An int %d, a double %f\n", 1234, c_double(3.14))
     An int 1234, a double 3.140000
     31
     >>>


File: python.info,  Node: 使用自定义的数据类型调用函数,  Next: 指定必选参数的类型 函数原型,  Prev: 调用函数，继续,  Up: ctypes 教程

5.16.16.7 使用自定义的数据类型调用函数
......................................

你也可以通过自定义 *note ctypes: 2a. 参数转换方式来允许自定义类型作为参
数。 *note ctypes: 2a. 会寻找 ‘_as_parameter_’ 属性并使用它作为函数参数
。当然，它必须是数字、字符串或者二进制字符串:

     >>> 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
     >>>

如果你不想把实例的数据存储到 ‘_as_parameter_’ 属性。可以通过定义 *note
property: 308. 函数计算出这个属性。


File: python.info,  Node: 指定必选参数的类型 函数原型,  Next: 返回类型,  Prev: 使用自定义的数据类型调用函数,  Up: ctypes 教程

5.16.16.8 指定必选参数的类型(函数原型)
......................................

可以通过设置 ‘argtypes’ 属性的方法指定从 DLL 中导出函数的必选参数类型。

‘argtypes’ 必须是一个 C 数据类型的序列 (这里的 ‘printf’ 可能不是个好例子
，因为它是变长参数，而且每个参数的类型依赖于格式化字符串，不过尝试这个功
能也很方便):

     >>> 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
     >>>

指定数据类型可以防止不合理的参数传递（就像 C 函数的原型），并且会自动尝
试将参数转换为需要的类型:

     >>> 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
     >>>

如果你想通过自定义类型传递参数给函数，必须实现 ‘from_param()’ 类方法，才
能够将此自定义类型用于 ‘argtypes’ 序列。‘from_param()’ 类方法接受一个
Python 对象作为函数输入，它应该进行类型检查或者其他必要的操作以保证接收
到的对象是合法的，然后返回这个对象，或者它的 ‘_as_parameter_’ 属性，或者
其他你想要传递给 C 函数的参数。这里也一样，返回的结果必须是整型、字符串
、二进制字符串、 *note ctypes: 2a. 类型，或者一个具有 ‘_as_parameter_’ 属
性的对象。


File: python.info,  Node: 返回类型,  Next: 传递指针（或以引用方式传递形参）,  Prev: 指定必选参数的类型 函数原型,  Up: ctypes 教程

5.16.16.9 返回类型
..................

默认情况下都会假定函数返回 C ‘int’ 类型。 其他返回类型可以通过设置函数对
象的 ‘restype’ 属性来指定。

这是个更高级的例子，它调用了 ‘strchr’ 函数，这个函数接收一个字符串指针以
及一个字符作为参数，返回另一个字符串指针。

     >>> 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
     >>>

如果希望避免上述的 ‘ord("x")’ 调用，可以设置 ‘argtypes’ 属性，第二个参数
就会将单字符的 Python 二进制字符对象转换为 C 字符:

     >>> 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'
     >>>

如果外部函数返回了一个整数，你也可以使用要给可调用的 Python 对象（比如函
数或者类）作为 ‘restype’ 属性的值。将会以 C 函数返回的 `整数' 对象作为参
数调用这个可调用对象，执行后的结果作为最终函数返回值。这在错误返回值校验
和自动抛出异常等方面比较有用。

     >>> 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.
     >>>

‘WinError’ 函数可以调用 Windows 的 ‘FormatMessage()’ API 获取错误码的字
符串说明，然后 `返回' 一个异常。 ‘WinError’ 接收一个可选的错误码作为参数
，如果没有的话，它将调用 *note GetLastError(): 2431. 获取错误码。

请注意，使用 ‘errcheck’ 属性可以实现更强大的错误检查手段；详情请见参考手
册。


File: python.info,  Node: 传递指针（或以引用方式传递形参）,  Next: 结构体和联合,  Prev: 返回类型,  Up: ctypes 教程

5.16.16.10 传递指针（或以引用方式传递形参）
...........................................

有时候 C 函数接口可能由于要往某个地址写入值，或者数据太大不适合作为值传
递，从而希望接收一个 `指针' 作为数据参数类型。这和 `传递参数引用' 类似。

*note ctypes: 2a. 暴露了 *note byref(): 2434. 函数用于通过引用传递参数，
使用 *note pointer(): 2435. 函数也能达到同样的效果，只不过 *note
pointer(): 2435. 需要更多步骤，因为它要先构造一个真实指针对象。所以在
Python 代码本身不需要使用这个指针对象的情况下，使用 *note byref(): 2434.
效率更高。

     >>> 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''
     >>> 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'
     >>>


File: python.info,  Node: 结构体和联合,  Next: 结构体/联合字段对齐及字节顺序,  Prev: 传递指针（或以引用方式传递形参）,  Up: ctypes 教程

5.16.16.11 结构体和联合
.......................

结构体和联合必须继承自 *note ctypes: 2a. 模块中的 *note Structure: 2438.
和 *note Union: 2439. 。子类必须定义 ‘_fields_’ 属性。 ‘_fields_’ 是一个
二元组列表，二元组中包含 `field name' 和 `field type' 。

type 字段必须是一个 *note ctypes: 2a. 类型，比如 *note c_int: 240f.，或
者其他 *note ctypes: 2a. 类型: 结构体、联合、数组、指针。

这是一个简单的 POINT 结构体，它包含名称为 `x' 和 `y' 的两个变量，还展示
了如何通过构造函数初始化结构体。

     >>> 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
     >>>

当然，你可以构造更复杂的结构体。一个结构体可以通过设置 type 字段包含其他
结构体或者自身。

这是以一个 RECT 结构体，他包含了两个 POINT ，分别叫 `upperleft' 和
`lowerright':

     >>> 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
     >>>

嵌套结构体可以通过几种方式构造初始化:

     >>> r = RECT(POINT(1, 2), POINT(3, 4))
     >>> r = RECT((1, 2), (3, 4))

可以通过 `类' 获取字段 *note descriptor: 1579. ，它能提供很多有用的调试
信息。

     >>> print(POINT.x)
     <Field type=c_long, ofs=0, size=4>
     >>> print(POINT.y)
     <Field type=c_long, ofs=4, size=4>
     >>>
     警告: *note ctypes: 2a. 不支持带位域的结构体、联合以值的方式传给函
     数。这可能在 32 位 x86 平台上可以正常工作，但是对于一般情况，这种行
     为是未定义的。带位域的结构体、联合应该总是通过指针传递给函数。


File: python.info,  Node: 结构体/联合字段对齐及字节顺序,  Next: 结构体和联合中的位域,  Prev: 结构体和联合,  Up: ctypes 教程

5.16.16.12 结构体/联合字段对齐及字节顺序
........................................

默认情况下，结构体和联合的字段与 C 的字节对齐是一样的。也可以在定义子类
的时候指定类的 ‘_pack_’ 属性来覆盖这种行为。 它必须设置为一个正整数，表
示字段的最大对齐字节。这和 MSVC 中的 ‘#pragma pack(n)’ 功能一样。

*note ctypes: 2a. 中的结构体和联合使用的是本地字节序。要使用非本地字节序
，可以使用 *note BigEndianStructure: 243c, *note LittleEndianStructure:
243d, ‘BigEndianUnion’, and ‘LittleEndianUnion’ 作为基类。这些类不能包含
指针字段。


File: python.info,  Node: 结构体和联合中的位域,  Next: 数组,  Prev: 结构体/联合字段对齐及字节顺序,  Up: ctypes 教程

5.16.16.13 结构体和联合中的位域
...............................

结构体和联合中是可以包含位域字段的。位域只能用于整型字段，位长度通过
‘_fields_’ 中的第三个参数指定:

     >>> 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>
     >>>


File: python.info,  Node: 数组,  Next: 指针,  Prev: 结构体和联合中的位域,  Up: ctypes 教程

5.16.16.14 数组
...............

数组是一个序列，包含指定个数元素，且必须类型相同。

创建数组类型的推荐方式是使用一个类型乘以一个正数:

     TenPointsArrayType = POINT * 10

下面是一个构造的数据案例，结构体中包含了4个 POINT 和一些其他东西。

     >>> 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
     >>>

和平常一样，通过调用它创建实例:

     arr = TenPointsArrayType()
     for pt in arr:
         print(pt.x, pt.y)

以上代码会打印几行 ‘0 0’ ，因为数组内容被初始化为 0.

也能通过指定正确类型的数据来初始化:

     >>> 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
     >>>


File: python.info,  Node: 指针,  Next: 类型转换,  Prev: 数组,  Up: ctypes 教程

5.16.16.15 指针
...............

可以将 *note ctypes: 2a. 类型数据传入 *note pointer(): 2435. 函数创建指
针:

     >>> from ctypes import *
     >>> i = c_int(42)
     >>> pi = pointer(i)
     >>>

指针实例拥有 *note contents: 2444. 属性，它返回指针指向的真实对象，如上
面的 ‘i’ 对象:

     >>> pi.contents
     c_long(42)
     >>>

注意 *note ctypes: 2a. 并没有 OOR （返回原始对象）, 每次访问这个属性时都
会构造返回一个新的相同对象:

     >>> pi.contents is i
     False
     >>> pi.contents is pi.contents
     False
     >>>

将这个指针的 contents 属性赋值为另一个 *note c_int: 240f. 实例将会导致该
指针指向该实例的内存地址:

     >>> i = c_int(99)
     >>> pi.contents = i
     >>> pi.contents
     c_long(99)
     >>>

指针对象也可以通过整数下标进行访问:

     >>> pi[0]
     99
     >>>

通过整数下标赋值可以改变指针所指向的真实内容:

     >>> print(i)
     c_long(99)
     >>> pi[0] = 22
     >>> print(i)
     c_long(22)
     >>>

使用 0 以外的索引也是合法的，但是你必须确保知道自己为什么这么做，就像 C
语言中: 你可以访问或者修改任意内存内容。 通常只会在函数接收指针是才会使
用这种特性，而且你 `知道' 这个指针指向的是一个数组而不是单个值。

内部细节, *note pointer(): 2435. 函数不只是创建了一个指针实例，它首先创
建了一个指针 `类型' 。这是通过调用 *note POINTER(): 2445. 函数实现的，它
接收 *note ctypes: 2a. 类型为参数，返回一个新的类型:

     >>> 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...>
     >>>

无参调用指针类型可以创建一个 ‘NULL’ 指针。 ‘NULL’ 指针的布尔值是 ‘False’

     >>> null_ptr = POINTER(c_int)()
     >>> print(bool(null_ptr))
     False
     >>>

解引用指针的时候， *note ctypes: 2a. 会帮你检测是否指针为 ‘NULL’ (但是解
引用无效的 非 ‘NULL’ 指针仍会导致 Python 崩溃):

     >>> 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
     >>>


File: python.info,  Node: 类型转换,  Next: 不完整类型,  Prev: 指针,  Up: ctypes 教程

5.16.16.16 类型转换
...................

通常情况下, ctypes 具有严格的类型检查。这代表着, 如果在函数 ‘argtypes’ 中
或者结构体定义成员中有 ‘POINTER(c_int)’ 类型，只有相同类型的实例才会被接
受。 也有一些例外。比如，你可以传递兼容的数组实例给指针类型。所以，对于
‘POINTER(c_int)’ ，ctypes 也可以接受 c_int 类型的数组:

     >>> 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
     >>>

另外，如果一个函数 ‘argtypes’ 列表中的参数显式的定义为指针类型(如
‘POINTER(c_int)’ )，指针所指向的 类型 (这个例子中是 ‘c_int’ )也可以传递
给函数。ctypes 会自动调用对应的 *note byref(): 2434. 转换。

可以给指针内容赋值为 None 将其设置为 ‘Null’

     >>> bar.values = None
     >>>

有时候你拥有一个不兼容的类型。 在 C 中，你可以将一个类型强制转换为另一个
。 *note ctypes: 2a. 中的 a *note cast(): 114b. 函数提供了相同的功能。 上
面的结构体 ‘Bar’ 的 ‘value’ 字段接收 ‘POINTER(c_int)’ 指针或者 *note
c_int: 240f. 数组，但是不能接受其他类型的实例:

     >>> 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
     >>>

这种情况下, 需要手动使用 *note cast(): 114b. 函数。

*note cast(): 114b. 函数可以将一个指针实例强制转换为另一种 ctypes 类型。
*note cast(): 114b. 接收两个参数，一个 ctypes 指针对象或者可以被转换为指
针的其他类型对象，和一个 ctypes 指针类型。 返回第二个类型的一个实例，该
返回实例和第一个参数指向同一片内存空间:

     >>> a = (c_byte * 4)()
     >>> cast(a, POINTER(c_int))
     <ctypes.LP_c_long object at ...>
     >>>

所以 *note cast(): 114b. 可以用来给结构体 ‘Bar’ 的 ‘values’ 字段赋值:

     >>> bar = Bar()
     >>> bar.values = cast((c_byte * 4)(), POINTER(c_int))
     >>> print(bar.values[0])
     0
     >>>


File: python.info,  Node: 不完整类型,  Next: 回调函数,  Prev: 类型转换,  Up: ctypes 教程

5.16.16.17 不完整类型
.....................

`不完整类型' 即还没有定义成员的结构体、联合或者数组。在 C 中，它们通常用
于前置声明，然后在后面定义:

     struct cell; /* forward declaration */

     struct cell {
         char *name;
         struct cell *next;
     };

直接翻译成 ctypes 的代码如下，但是这行不通:

     >>> 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
     >>>

因为新的 ‘cell 类’ 在 class 语句结束之前还没有完成定义。在 *note ctypes:
2a. 中，我们可以先定义 ‘cell’ 类，在 class 语句结束之后再设置 ‘_fields_’
属性:

     >>> from ctypes import *
     >>> class cell(Structure):
     ...     pass
     ...
     >>> cell._fields_ = [("name", c_char_p),
     ...                  ("next", POINTER(cell))]
     >>>

让我们试试。我们定义两个 ‘cell’ 实例，让它们互相指向对方，然后通过指针链
式访问几次:

     >>> 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
     >>>


File: python.info,  Node: 回调函数,  Next: 访问 dll 的导出变量,  Prev: 不完整类型,  Up: ctypes 教程

5.16.16.18 回调函数
...................

*note ctypes: 2a. 允许创建一个指向 Python 可调用对象的 C 函数。它们有时
候被称为 `回调函数' 。

首先，你必须为回调函数创建一个类，这个类知道调用约定，包括返回值类型以及
函数接收的参数类型及个数。

*note CFUNCTYPE(): 244c. 工厂函数使用 ‘cdecl’ 调用约定创建回调函数类型。
在 Windows 上， *note WINFUNCTYPE(): 244d. 工厂函数使用 ‘stdcall’ 调用约
定为回调函数创建类型。

这些工厂函数的第一个参数是返回值类型，回调函数的参数类型作为剩余参数。

这里展示一个使用 C 标准库函数 ‘qsort()’ 的例子，它使用一个回调函数对数据
进行排序。 ‘qsort()’ 将用来给整数数组排序:

     >>> IntArray5 = c_int * 5
     >>> ia = IntArray5(5, 1, 7, 33, 99)
     >>> qsort = libc.qsort
     >>> qsort.restype = None
     >>>

‘qsort()’ 必须接收的参数，一个指向待排序数据的指针，元素个数，每个元素的
大小，以及一个指向排序函数的指针，即回调函数。然后回调函数接收两个元素的
指针，如果第一个元素小于第二个，则返回一个负整数，如果相等则返回0，否则
返回一个正整数。

所以，我们的回调函数要接收两个整数指针，返回一个整数。首先我们创建回调函
数的 ‘类型’

     >>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
     >>>

首先，这是一个简单的回调，它会显示传入的值:

     >>> def py_cmp_func(a, b):
     ...     print("py_cmp_func", a[0], b[0])
     ...     return 0
     ...
     >>> cmp_func = CMPFUNC(py_cmp_func)
     >>>

结果:

     >>> 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
     >>>

现在我们可以比较两个元素并返回有用的结果了:

     >>> 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
     >>>

我们可以轻易地验证，现在数组是有序的了:

     >>> for i in ia: print(i, end=" ")
     ...
     1 5 7 33 99
     >>>

这些工厂函数可以当作装饰器工厂，所以可以这样写:

     >>> @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
     >>>

     備註: 请确保你维持的 *note CFUNCTYPE(): 244c. 对象的引用周期与它们
     在 C 代码中的使用期一样长。 *note ctypes: 2a. 不会确保这一点，如果
     不这样做，它们可能会被垃圾回收，导致程序在执行回调函数时发生崩溃。

     注意，如果回调函数在Python之外的另外一个线程使用(比如，外部代码调用
     这个回调函数)， ctypes 会在每一次调用上创建一个虚拟 Python 线程。这
     个行为在大多数情况下是合理的，但也意味着如果有数据使用 *note
     threading.local: 244e. 方式存储，将无法访问，就算它们是在同一个 C 线
     程中调用的 。


File: python.info,  Node: 访问 dll 的导出变量,  Next: 意外,  Prev: 回调函数,  Up: ctypes 教程

5.16.16.19 访问 dll 的导出变量
..............................

一些动态链接库不仅仅导出函数，也会导出变量。一个例子就是 Python 库本身的
*note Py_OptimizeFlag: 2451. ，根据启动选项 *note -O: 77e. 、 *note -OO:
77f. 的不同，它是值可能为 0、1、2 的整型。

*note ctypes: 2a. 可以通过 ‘in_dll()’ 类方法访问这类变量 。 `pythonapi'
是用于访问 Python C 接口的预定义符号:

     >>> opt_flag = c_int.in_dll(pythonapi, "Py_OptimizeFlag")
     >>> print(opt_flag)
     c_long(0)
     >>>

如果解释器使用 *note -O: 77e. 选项启动，这个例子会打印 ‘c_long(1)’ ， 如
果使用 *note -OO: 77f. 启动，则会打印 ‘c_long(2)’ 。

一个扩展例子, 同时也展示了使用指针访问 Python 导出的 *note
PyImport_FrozenModules: 2452. 指针对象。

对文档中这个值的解释说明

     该指针被初始化为指向 ‘struct _frozen’ 数组，以 ‘NULL’ 或者 0 作为结
     束标记。当一个冻结模块被导入，首先要在这个表中搜索。第三方库可以以
     此来提供动态创建的冻结模块集合。

这足以证明修改这个指针是很有用的。为了让实例大小不至于太长，这里只展示如
何使用 *note ctypes: 2a. 读取这个表:

     >>> from ctypes import *
     >>>
     >>> class struct_frozen(Structure):
     ...     _fields_ = [("name", c_char_p),
     ...                 ("code", POINTER(c_ubyte)),
     ...                 ("size", c_int)]
     ...
     >>>

我们定义了 ‘struct _frozen’  数据类型，接着就可以获取这张表的指针了:

     >>> FrozenTable = POINTER(struct_frozen)
     >>> table = FrozenTable.in_dll(pythonapi, "PyImport_FrozenModules")
     >>>

由于 ‘table’ 是指向 ‘struct_frozen’ 数组的 ‘指针’ ，我们可以遍历它，只不
过需要自己判断循环是否结束，因为指针本身并不包含长度。它早晚会因为访问到
野指针或者什么的把自己搞崩溃，所以我们最好在遇到 ‘NULL’ 后就让它退出循环
:

     >>> 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
     >>>

Python 的冻结模块和冻结包(由负 ‘size’ 成员表示)并不是广为人知的事情，它
们仅仅用于实验。例如，可以使用 ‘import __hello__’ 尝试一下这个功能。


File: python.info,  Node: 意外,  Next: 变长数据类型,  Prev: 访问 dll 的导出变量,  Up: ctypes 教程

5.16.16.20 意外
...............

*note ctypes: 2a. 也有自己的边界，有时候会发生一些意想不到的事情。

比如下面的例子:

     >>> 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
     >>>

嗯。我们预想应该打印 ‘3 4 1 2’ 。但是为什么呢? 这是 ‘rc.a, rc.b = rc.b,
rc.a’ 这行代码展开后的步骤:

     >>> temp0, temp1 = rc.b, rc.a
     >>> rc.a = temp0
     >>> rc.b = temp1
     >>>

注意 ‘temp0’ 和 ‘temp1’ 对象始终引用了对象 ‘rc’ 的内容。然后执行 ‘rc.a =
temp0’ 会把 ‘temp0’ 的内容拷贝到 ‘rc’ 的空间。这也改变了 ‘temp1’ 的内容
。最终导致赋值语句 ‘rc.b = temp1’ 没有产生预想的效果。

记住，访问被包含在结构体、联合、数组中的对象并不会将其 `复制' 出来，而是
得到了一个代理对象，它是对根对象的内部内容的一层包装。

下面是另一个可能和预期有偏差的例子:

     >>> s = c_char_p()
     >>> s.value = b"abc def ghi"
     >>> s.value
     b'abc def ghi'
     >>> s.value is s.value
     False
     >>>

     備註: 使用 *note c_char_p: 2426.  实例化的对象只能将其值设置为
     bytes 或者整数。

为什么这里打印了 ‘False’ ？ ctypes 实例是一些内存块加上一些用于访问这些
内存块的 *note descriptor: 1579. 组成。将 Python 对象存储在内存块并不会
存储对象本身，而是存储了对象的 ‘内容’ 。每次访问对象的内容都会构造一个新
的 Python 对象。


File: python.info,  Node: 变长数据类型,  Prev: 意外,  Up: ctypes 教程

5.16.16.21 变长数据类型
.......................

*note ctypes: 2a. 对变长数组和结构体提供了一些支持 。

The *note resize(): 2457. 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 *note ValueError: 16d. is raised if
this is tried:

     >>> 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
     >>>

这非常好，但是要怎么访问数组中额外的元素呢？因为数组类型已经定义包含4个
元素，导致我们访问新增元素时会产生以下错误:

     >>> short_array[:]
     [0, 0, 0, 0]
     >>> short_array[7]
     Traceback (most recent call last):
         ...
     IndexError: invalid index
     >>>

使用 *note ctypes: 2a. 访问变长数据类型的一个可行方法是利用 Python 的动
态特性，根据具体情况，在知道这个数据的大小后，(重新)指定这个数据的类型。


File: python.info,  Node: ctypes 参考手册,  Prev: ctypes 教程,  Up: ctypes --- Python 的外部函数库

5.16.16.22 ctypes 参考手册
..........................

* Menu:

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


File: python.info,  Node: 寻找动态链接库,  Next: 加载动态链接库,  Up: ctypes 参考手册

5.16.16.23 寻找动态链接库
.........................

在编译型语言中，动态链接库会在编译、链接或者程序运行时访问。

The purpose of the ‘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.

‘ctypes.util’ 模块提供了一个函数，可以帮助确定需要加载的库。

 -- Data: ctypes.util.find_library (name)

     尝试寻找一个库然后返回其路径名， `name' 是库名称, 且去除了 `lib' 等
     前缀和 ‘.so’ 、 ‘.dylib’ 、版本号等后缀(这是 posix 连接器 ‘-l’ 选项
     使用的格式)。如果没有找到对应的库，则返回 ‘None’ 。

确切的功能取决于系统。

在 Linux 上， ‘find_library()’ 会尝试运行外部程序(‘/sbin/ldconfig’,
‘gcc’, ‘objdump’ 以及 ‘ld’) 来寻找库文件。返回库文件的文件名。

3.6 版更變: 在Linux 上，如果其他方式找不到的话，会使用环境变量
‘LD_LIBRARY_PATH’ 搜索动态链接库。

这是一些例子:

     >>> 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'
     >>>

On macOS, ‘find_library()’ tries several predefined naming schemes and
paths to locate the library, and returns a full pathname if successful:

     >>> 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'
     >>>

在 Windows 上， ‘find_library()’ 在系统路径中搜索，然后返回全路径，但是
如果没有预定义的命名方案， ‘find_library("c")’ 调用会返回 ‘None’

使用 *note ctypes: 2a. 包装动态链接库，更好的方式 `可能' 是在开发的时候
就确定名称，然后硬编码到包装模块中去，而不是在运行时使用
‘find_library()’ 寻找库。


File: python.info,  Node: 加载动态链接库,  Next: 外部函数,  Prev: 寻找动态链接库,  Up: ctypes 参考手册

5.16.16.24 加载动态链接库
.........................

有很多方式可以将动态链接库加载到 Python 进程。其中之一是实例化以下类的其
中一个:

 -- 類別: ctypes.CDLL (name, mode=DEFAULT_MODE, handle=None,
          use_errno=False, use_last_error=False, winmode=None)

     此类的实例即已加载的动态链接库。库中的函数使用标准 C 调用约定，并假
     定返回 ‘int’ 。

     在 Windows 上创建 *note CDLL: 2f2. 实例可能会失败，即使 DLL 名称确
     实存在。 当某个被加载 DLL 所依赖的 DLL 未找到时，将引发 *note
     OSError: 304. 错误并附带消息 `"[WinError 126] The specified module
     could not be found".' 此错误消息不包含缺失 DLL 的名称，因为 Windows
     API 并不会返回此类信息，这使得此错误难以诊断。 要解决此错误并确定是
     哪一个 DLL 未找到，你需要找出所依赖的 DLL 列表并使用 Windows 调试与
     跟踪工具确定是哪一个未找到。

也參考
......

Microsoft DUMPBIN 工具(1) – 一个用于查找 DLL 依赖的工具。

 -- 類別: ctypes.OleDLL (name, mode=DEFAULT_MODE, handle=None,
          use_errno=False, use_last_error=False, winmode=None)

     仅 Windows : 此类的实例即加载好的动态链接库，其中的函数使用
     ‘stdcall’ 调用约定，并且假定返回 windows 指定的 *note HRESULT:
     245f. 返回码。 *note HRESULT: 245f. 的值包含的信息说明函数调用成功
     还是失败，以及额外错误码。 如果返回值表示失败，会自动抛出 *note
     OSError: 304. 异常。

     3.3 版更變: 以前是引发 *note WindowsError: a75.。

 -- 類別: ctypes.WinDLL (name, mode=DEFAULT_MODE, handle=None,
          use_errno=False, use_last_error=False, winmode=None)

     仅 Windows: 此类的实例即加载好的动态链接库，其中的函数使用
     ‘stdcall’ 调用约定，并假定默认返回 ‘int’ 。

     在 Windows CE 上，只能使用 stdcall 调用约定，为了方便， *note
     WinDLL: 2460. 和 *note OleDLL: 245e. 在这个平台上都使用标准调用约定
     。

调用动态库导出的函数之前，Python会释放 *note global interpreter lock:
5ff. ，并在调用后重新获取。

 -- 類別: ctypes.PyDLL (name, mode=DEFAULT_MODE, handle=None)

     这个类实例的行为与 *note CDLL: 2f2. 类似，只不过 `不会' 在调用函数
     的时候释放 GIL 锁，且调用结束后会检查 Python 错误码。 如果错误码被
     设置，会抛出一个 Python 异常。

     所以，它只在直接调用 Python C 接口函数的时候有用。

通过使用至少一个参数（共享库的路径名）调用它们，可以实例化所有这些类。也
可以传入一个已加载的动态链接库作为 ‘handler’ 参数，其他情况会调用系统底
层的 ‘dlopen’ 或 ‘LoadLibrary’ 函数将库加载到进程，并获取其句柄。

`mode' 可以指定库加载方式。详情请参见 ‘dlopen(3)’ 手册页。 在 Windows 上
， 会忽略 `mode' ，在 posix 系统上， 总是会加上 RTLD_NOW ，且无法配置。

`use_errno' 参数如果设置为 true，可以启用ctypes的机制，通过一种安全的方
法获取系统的 *note errno: 7a. 错误码。 *note ctypes: 2a. 维护了一个线程
局部变量，它是系统 *note errno: 7a. 的一份拷贝；如果调用了使用
‘use_errno=True’ 创建的外部函数， *note errno: 7a. 的值会与 ctypes 自己
拷贝的那一份进行交换，函数执行完后立即再交换一次。

The function *note ctypes.get_errno(): 2462. returns the value of the
ctypes private copy, and the function *note ctypes.set_errno(): 2463.
changes the ctypes private copy to a new value and returns the former
value.

`use_last_error' 参数如果设置为 true，可以在 Windows 上启用相同的策略，
它是通过 Windows API 函数 *note GetLastError(): 2431.  和
‘SetLastError()’ 管理的。 *note ctypes.get_last_error(): 2464. 和 *note
ctypes.set_last_error(): 2465. 可用于获取和设置 ctypes 自己维护的
windows 错误码拷贝。

`winmode' 参数用于在 Windows 平台上指定库的加载方式( 因为 `mode' 会被忽
略)。他接受任何与 Win32 API 的 ‘LoadLibraryEx’ 的标志兼容的值作为参数。
省略时，默认设置使用最安全的DLL加载的标志，以避免DLL劫持等问题。传入 DLL
的全路径是保证正确加载库及其依赖最安全的方法。

3.8 版更變: 增加了 `winmode' 参数。

 -- Data: ctypes.RTLD_GLOBAL

     用于 `mode' 参数的标识值。在此标识不可用的系统上，它被定义为整数0。

 -- Data: ctypes.RTLD_LOCAL

     Flag to use as `mode' parameter.  On platforms where this is not
     available, it is the same as `RTLD_GLOBAL'.

 -- Data: ctypes.DEFAULT_MODE

     加载动态链接库的默认模式。在 OSX 10.3 上，它是 `RTLD_GLOBAL' ，其余
     系统上是 `RTLD_LOCAL' 。

这些类的实例没有共用方法。动态链接库的导出函数可以通过属性或者索引的方式
访问。注意，通过属性的方式访问会缓存这个函数，因而每次访问它时返回的都是
同一个对象。另一方面，通过索引访问，每次都会返回一个新的对象:

     >>> from ctypes import CDLL
     >>> libc = CDLL("libc.so.6")  # On Linux
     >>> libc.time == libc.time
     True
     >>> libc['time'] == libc['time']
     False

还有下面这些属性可用，他们的名称以下划线开头，以避免和导出函数重名:

 -- 屬性: PyDLL._handle

     用于访问库的系统句柄。

 -- 屬性: PyDLL._name

     传入构造函数的库名称。

共享库也可以通用使用一个预制对象来加载，这种对象是 *note LibraryLoader:
2468. 类的实例，具体做法或是通过调用 ‘LoadLibrary()’ 方法，或是通过将库
作为加载器实例的属性来提取。

 -- 類別: ctypes.LibraryLoader (dlltype)

     加载共享库的类。 `dlltype' 应当为 *note CDLL: 2f2, *note PyDLL:
     2461, *note WinDLL: 2460. 或 *note OleDLL: 245e. 类型之一。

     *note __getattr__(): 42a. 具有特殊的行为：它允许通过将一个共享库作
     为库加载器实例的属性进行访问来加载它。 加载结果将被缓存，因此重复的
     属性访问每次都会返回相同的库。

      -- 成員函式: LoadLibrary (name)

          加载一个共享库到进程中并将其返回。 此方法总是返回一个新的库实
          例。

可用的预制库加载器有如下这些:

 -- Data: ctypes.cdll

     创建 *note CDLL: 2f2. 实例。

 -- Data: ctypes.windll

     仅限 Windows：创建 *note WinDLL: 2460. 实例.

 -- Data: ctypes.oledll

     仅限 Windows：创建 *note OleDLL: 245e. 实例。

 -- Data: ctypes.pydll

     创建 *note PyDLL: 2461. 实例。

要直接访问 C Python api，可以使用一个现成的 Python 共享库对象:

 -- Data: ctypes.pythonapi

     一个 *note PyDLL: 2461. 的实例，它将 Python C API 函数作为属性公开
     。 请注意所有这些函数都应返回 C ‘int’，当然这也不是绝对的，因此你必
     须分配正确的 ‘restype’ 属性以使用这些函数。

引发一个 *note 审计事件: fa1. ‘ctypes.dlopen’，附带参数 ‘name’。

引发一个审计事件 ‘ctypes.dlsym’，附带参数 ‘library’, ‘name’。

引发一个审计事件 ‘ctypes.dlsym/handle’，附带参数 ‘handle’, ‘name’。

   ---------- Footnotes ----------

   (1) https://docs.microsoft.com/cpp/build/reference/dependents


File: python.info,  Node: 外部函数,  Next: 函数原型,  Prev: 加载动态链接库,  Up: ctypes 参考手册

5.16.16.25 外部函数
...................

正如之前小节的说明，外部函数可作为被加载共享库的属性来访问。 用此方式创
建的函数对象默认接受任意数量的参数，接受任意 ctypes 数据实例作为参数，并
且返回库加载器所指定的默认结果类型。 它们是一个私有类的实例:

 -- 類別: ctypes._FuncPtr

     C 可调用外部函数的基类。

     外部函数的实例也是兼容 C 的数据类型；它们代表 C 函数指针。

     此行为可通过对外部函数对象的特殊属性赋值来自定义。

      -- 屬性: restype

          赋值为一个 ctypes 类型来指定外部函数的结果类型。 使用 ‘None’ 表
          示 ‘void’，即不返回任何结果的函数。

          赋值为一个不为 ctypes 类型的可调用 Python 对象也是可以的，在此
          情况下函数应返回 C ‘int’，该可调用对象将附带此整数被调用，以允
          许进一步的处理或错误检测。 这种用法已被弃用，为了更灵活的后续
          处理或错误检测请使用一个 ctypes 数据类型作为 *note restype:
          246d. 并将 *note errcheck: 246e. 属性赋值为一个可调用对象。

      -- 屬性: argtypes

          赋值为一个 ctypes 类型的元组来指定函数所接受的参数类型。 使用
          ‘stdcall’ 调用规范的函数只能附带与此元组长度相同数量的参数进行
          调用；使用 C 调用规范的函数还可接受额外的未指明参数。

          当外部函数被调用时，每个实际参数都会被传给 *note argtypes:
          246f. 元组中条目的 ‘from_param()’ 类方法，此方法允许将实际参数
          适配为此外部函数所接受的对象。 例如，*note argtypes: 246f. 元
          组中的 *note c_char_p: 2426. 条目将使用 ctypes 约定规则把作为
          参数传入的字符串转换为字节串对象。

          新增：现在可以将不是 ctypes 类型的条目放入 argtypes，但每个条
          目都必须具有 ‘from_param()’ 方法用于返回可作为参数的值（整数、
          字符串、ctypes 实例）。 这样就允许定义可将自定义对象适配为函数
          形参的适配器。

      -- 屬性: errcheck

          将一个 Python 函数或其他可调用对象赋值给此属性。 该可调用对象
          将附带三个及以上的参数被调用。

           -- 函式: callable (result, func, arguments)

               `result' 是外部函数返回的结果，由 ‘restype’ 属性指明。

               `func' 是外部函数对象本身，这样就允许重新使用相同的可调用
               对象来对多个函数进行检查或后续处理。

               `arguments' 是一个包含最初传递给函数调用的形参的元组，这
               样就允许对所用参数的行为进行特别处理。

          此函数所返回的对象将会由外部函数调用返回，但它还可以在外部函数
          调用失败时检查结果并引发异常。

 -- 例外: ctypes.ArgumentError

     此异常会在外部函数无法对某个传入参数执行转换时被引发。

引发一个审计事件 ‘ctypes.seh_exception’ 并附带参数 ‘code’。

引发一个审计事件 ‘ctypes.call_function’，附带参数 ‘func_pointer’,
‘arguments’。


File: python.info,  Node: 函数原型,  Next: 工具函数,  Prev: 外部函数,  Up: ctypes 参考手册

5.16.16.26 函数原型
...................

外部函数也可通过实例化函数原型来创建。 函数原型类似于 C 中的函数原型；它
们在不定义具体实现的情况下描述了一个函数（返回类型、参数类型、调用约定）
。 工厂函数必须使用函数所需要的结果类型和参数类型来调用，并可被用作装饰
器工厂函数，在此情况下可以通过 ‘@wrapper’ 语法应用于函数。 请参阅 *note
回调函数: 244b. 了解有关示例。

 -- 函式: ctypes.CFUNCTYPE (restype, *argtypes, use_errno=False,
          use_last_error=False)

     返回的函数原型会创建使用标准 C 调用约定的函数。 该函数在调用过程中
     将释放 GIL。 如果 `use_errno' 设为真值，则在调用之前和之后系统
     *note errno: 7a. 变量的 ctypes 私有副本会与真正的 *note errno: 7a.
     值进行交换；`use_last_error' 会为 Windows 错误码执行同样的操作。

 -- 函式: ctypes.WINFUNCTYPE (restype, *argtypes, use_errno=False,
          use_last_error=False)

     仅限 Windows only：返回的函数原型会创建使用 ‘stdcall’ 调用约定的函
     数，但在 Windows CE 上 *note WINFUNCTYPE(): 244d. 则会与 *note
     CFUNCTYPE(): 244c. 相同。 该函数在调用过程中将释放 GIL。
     `use_errno' 和 `use_last_error' 具有与前面相同的含义。

 -- 函式: ctypes.PYFUNCTYPE (restype, *argtypes)

     返回的函数原型会创建使用 Python 调用约定的函数。 该函数在调用过程中
     将 `不会' 释放 GIL。

这些工厂函数所创建的函数原型可通过不同的方式来实例化，具体取决于调用中的
类型与数量:

      -- 函式: prototype (address)

          在指定地址上返回一个外部函数，地址值必须为整数。

      -- 函式: prototype (callable)

          基于 Python `callable' 创建一个 C 可调用函数（回调函数）。

      -- 函式: prototype (func_spec[, paramflags])

          返回由一个共享库导出的外部函数。 `func_spec' 必须为一个 2 元组
          ‘(name_or_ordinal, library)’。 第一项是字符串形式的所导出函数
          名称，或小整数形式的所导出函数序号。 第二项是该共享库实例。

      -- 函式: prototype (vtbl_index, name[, paramflags[, iid]])

          返回将调用一个 COM 方法的外部函数。 `vtbl_index' 虚拟函数表中
          的索引。 `name' 是 COM 方法的名称。 `iid' 是可选的指向接口标识
          符的指针，它被用于扩展的错误报告。

          COM 方法使用特殊的调用约定：除了在 ‘argtypes’ 元组中指定的形参
          ，它们还要求一个指向 COM 接口的指针作为第一个参数。

     可选的 `paramflags' 形参会创建相比上述特性具有更多功能的外部函数包
     装器。

     `paramflags' 必须为一个与 ‘argtypes’ 长度相同的元组。

     此元组中的每一项都包含有关形参的更多信息，它必须为包含一个、两个或
     更多条目的元组。

     第一项是包含形参指令旗标组合的整数。

          1

               指定函数的一个输入形参。

          2

               输出形参。 外部函数会填入一个值。

          4

               默认为整数零值的输入形参。

     可选的第二项是字符串形式的形参名称。 如果指定此项，则可以使用该形参
     名称来调用外部函数。

     可选的第三项是该形参的默认值。

这个例子演示了如何包装 Windows 的 ‘MessageBoxW’ 函数以使其支持默认形参和
已命名参数。 相应 windows 头文件的 C 声明是这样的:

     WINUSERAPI int WINAPI
     MessageBoxW(
         HWND hWnd,
         LPCWSTR lpText,
         LPCWSTR lpCaption,
         UINT uType);

这是使用 *note ctypes: 2a. 的包装:

     >>> 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)

现在 ‘MessageBox’ 外部函数可以通过以下方式来调用:

     >>> MessageBox()
     >>> MessageBox(text="Spam, spam, spam")
     >>> MessageBox(flags=2, text="foo bar")

第二个例子演示了输出形参。 这个 win32 ‘GetWindowRect’ 函数通过将指定窗口
的维度拷贝至调用者必须提供的 ‘RECT’ 结构体来提取这些值。 这是相应的 C 声
明:

     WINUSERAPI BOOL WINAPI
     GetWindowRect(
          HWND hWnd,
          LPRECT lpRect);

这是使用 *note ctypes: 2a. 的包装:

     >>> 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)
     >>>

带有输出形参的函数如果输出形参存在单一值则会自动返回该值，或是当输出形参
存在多个值时返回包含这些值的元组，因此当 GetWindowRect 被调用时现在将返
回一个 RECT 实例。

输出形参可以与 ‘errcheck’ 协议相结合以执行进一步的输出处理与错误检查。
Win32 ‘GetWindowRect’ API 函数返回一个 ‘BOOL’ 来表示成功或失败，因此此函
数可执行错误检查，并在 API 调用失败时引发异常:

     >>> def errcheck(result, func, args):
     ...     if not result:
     ...         raise WinError()
     ...     return args
     ...
     >>> GetWindowRect.errcheck = errcheck
     >>>

如果 ‘errcheck’ 不加更改地返回它所接收的参数元组，则 *note ctypes: 2a. 会
继续对输出形参执行常规处理。 如果你希望返回一个窗口坐标的元组而非 ‘RECT’
实例，你可以从函数中提取这些字段并返回它们，常规处理将不会再执行:

     >>> 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
     >>>


File: python.info,  Node: 工具函数,  Next: 数据类型<2>,  Prev: 函数原型,  Up: ctypes 参考手册

5.16.16.27 工具函数
...................

 -- 函式: ctypes.addressof (obj)

     以整数形式返回内存缓冲区地址。 `obj' 必须为一个 ctypes 类型的实例。

     引发一个 *note 审计事件: fa1. ‘ctypes.addressof’，附带参数 ‘obj’。

 -- 函式: ctypes.alignment (obj_or_type)

     返回一个 ctypes 类型的对齐要求。 `obj_or_type' 必须为一个 ctypes 类
     型或实例。

 -- 函式: ctypes.byref (obj[, offset])

     返回指向 `obj' 的轻量指针，该对象必须为一个 ctypes 类型的实例。
     `offset' 默认值为零，且必须为一个将被添加到内部指针值的整数。

     ‘byref(obj, offset)’ 对应于这段 C 代码:

          (((char *)&obj) + offset)

     返回的对象只能被用作外部函数调用形参。 它的行为类似于
     ‘pointer(obj)’，但构造起来要快很多。

 -- 函式: ctypes.cast (obj, type)

     此函数类似于 C 的强制转换运算符。 它返回一个 `type' 的新实例，该实
     例指向与 `obj' 相同的内存块。 `type' 必须为指针类型，而 `obj' 必须
     为可以被作为指针来解读的对象。

 -- 函式: ctypes.create_string_buffer (init_or_size, size=None)

     此函数会创建一个可变的字符缓冲区。 返回的对象是一个 *note c_char:
     241a. 的 ctypes 数组。

     `init_or_size' 必须是一个指明数组大小的整数，或者是一个将被用来初始
     化数组条目的字节串对象。

     如果将一个字节串对象指定为第一个参数，则将使缓冲区大小比其长度多一
     项以便数组的最后一项为一个 NUL 终结符。 可以传入一个整数作为第二个
     参数以允许在不使用字节串长度的情况下指定数组大小。

     引发一个 *note 审计事件: fa1. ‘ctypes.create_string_buffer’，附带参
     数 ‘init’, ‘size’。

 -- 函式: ctypes.create_unicode_buffer (init_or_size, size=None)

     此函数会创建一个可变的 unicode 字符缓冲区。 返回的对象是一个 *note
     c_wchar: 241b. 的 ctypes 数组。

     `init_or_size' 必须是一个指明数组大小的整数，或者是一个将被用来初始
     化数组条目的字符串。

     如果将一个字符串指定为第一个参数，则将使缓冲区大小比其长度多一项以
     便数组的最后一项为一个 NUL 终结符。 可以传入一个整数作为第二个参数
     以允许在不使用字符串长度的情况下指定数组大小。

     引发一个 *note 审计事件: fa1. ‘ctypes.create_unicode_buffer’，附带
     参数 ‘init’, ‘size’。

 -- 函式: ctypes.DllCanUnloadNow ()

     仅限 Windows：此函数是一个允许使用 ctypes 实现进程内 COM 服务的钩子
     。 它将由 _ctypes 扩展 dll 所导出的 DllCanUnloadNow 函数来调用。

 -- 函式: ctypes.DllGetClassObject ()

     仅限 Windows：此函数是一个允许使用 ctypes 实现进程内 COM 服务的钩子
     。 它将由 ‘_ctypes’ 扩展 dll 所导出的 DllGetClassObject 函数来调用
     。

 -- 函式: ctypes.util.find_library (name)

     尝试寻找一个库并返回路径名称。 `name' 是库名称并且不带任何前缀如
     ‘lib’ 以及后缀如 ‘.so’，‘.dylib’ 或版本号（形式与 posix 链接器选项
     ‘-l’ 所用的一致）。 如果找不到库，则返回 ‘None’。

     确切的功能取决于系统。

 -- 函式: ctypes.util.find_msvcrt ()

     仅限 Windows：返回 Python 以及扩展模块所使用的 VC 运行时库的文件名
     。 如果无法确定库名称，则返回 ‘None’。

     如果你需要通过调用 ‘free(void *)’ 来释放内存，例如某个扩展模块所分
     配的内存，重要的一点是你应当使用分配内存的库中的函数。

 -- 函式: ctypes.FormatError ([code])

     仅限 Windows：返回错误码 `code' 的文本描述。 如果未指定错误码，则会
     通过调用 Windows api 函数 GetLastError 来获得最新的错误码。

 -- 函式: ctypes.GetLastError ()

     仅限 Windows：返回 Windows 在调用线程中设置的最新错误码。 此函数会
     直接调用 Windows ‘GetLastError()’ 函数，它并不返回错误码的 ctypes 私
     有副本。

 -- 函式: ctypes.get_errno ()

     返回调用线程中系统 *note errno: 7a. 变量的 ctypes 私有副本的当前值
     。

     引发一个 *note 审计事件: fa1. ‘ctypes.get_errno’，不附带任何参数。

 -- 函式: ctypes.get_last_error ()

     仅限 Windows：返回调用线程中系统 ‘LastError’ 变量的 ctypes 私有副本
     的当前值。

     引发一个 *note 审计事件: fa1. ‘ctypes.get_last_error’，不附带任何参
     数。

 -- 函式: ctypes.memmove (dst, src, count)

     与标准 C memmove 库函数相同：将 `count' 个字节从 `src' 拷贝到
     `dst'。 `dst' 和 `src' 必须为整数或可被转换为指针的 ctypes 实例。

 -- 函式: ctypes.memset (dst, c, count)

     与标准 C memset 库函数相同：将位于地址 `dst' 的内存块用 `count' 个
     字节的 `c' 值填充。 `dst' 必须为指定地址的整数或 ctypes 实例。

 -- 函式: ctypes.POINTER (type)

     这个工厂函数创建并返回一个新的 ctypes 指针类型。 指针类型会被缓存并
     在内部重用，因此重复调用此函数耗费不大。 `type' 必须为 ctypes 类型
     。

 -- 函式: ctypes.pointer (obj)

     此函数会创建一个新的指向 `obj' 的指针实例。 返回的对象类型为
     ‘POINTER(type(obj))’。

     注意：如果你只是想向外部函数调用传递一个对象指针，你应当使用更为快
     速的 ‘byref(obj)’。

 -- 函式: ctypes.resize (obj, size)

     此函数可改变 `obj' 的内部内存缓冲区大小，其参数必须为 ctypes 类型的
     实例。 没有可能将缓冲区设为小于对象类型的本机大小值，该值由
     ‘sizeof(type(obj))’ 给出，但将缓冲区加大则是可能的。

 -- 函式: ctypes.set_errno (value)

     设置调用线程中系统 *note errno: 7a. 变量的 ctypes 私有副本的当前值
     为 `value' 并返回原来的值。

     引发一个 *note 审计事件: fa1. ‘ctypes.set_errno’ 附带参数 ‘errno’。

 -- 函式: ctypes.set_last_error (value)

     仅限 Windows：设置调用线程中系统 ‘LastError’ 变量的 ctypes 私有副本
     的当前值为 `value' 并返回原来的值。

     引发一个 *note 审计事件: fa1. ‘ctypes.set_last_error’，附带参数
     ‘error’。

 -- 函式: ctypes.sizeof (obj_or_type)

     返回 ctypes 类型或实例的内存缓冲区以字节表示的大小。 其功能与 C
     ‘sizeof’ 运算符相同。

 -- 函式: ctypes.string_at (address, size=-1)

     此函数返回从内存地址 `address' 开始的以字节串表示的 C 字符串。 如果
     指定了 size，则将其用作长度，否则将假定字符串以零值结尾。

     引发一个 *note 审计事件: fa1. ‘ctypes.string_at’，附带参数
     ‘address’, ‘size’。

 -- 函式: ctypes.WinError (code=None, descr=None)

     仅限 Windows：此函数可能是 ctypes 中名字起得最差的函数。 它会创建一
     个 OSError 的实例。 如果未指定 `code'，则会调用 ‘GetLastError’ 来确
     定错误码。 如果未指定 `descr'，则会调用 *note FormatError(): 247b.
     来获取错误的文本描述。

     3.3 版更變: 以前是会创建一个 *note WindowsError: a75. 的实例。

 -- 函式: ctypes.wstring_at (address, size=-1)

     此函数返回从内存地址 `address' 开始的以字符串表示的宽字节字符串。 如
     果指定了 `size'，则将其用作字符串中的字符数量，否则将假定字符串以零
     值结尾。

     引发一个 *note 审计事件: fa1. ‘ctypes.wstring_at’，附带参数
     ‘address’, ‘size’。


File: python.info,  Node: 数据类型<2>,  Next: 基础数据类型<2>,  Prev: 工具函数,  Up: ctypes 参考手册

5.16.16.28 数据类型
...................

 -- 類別: ctypes._CData

     这个非公有类是所有 ctypes 数据类型的共同基类。 另外，所有 ctypes 类
     型的实例都包含一个存放 C 兼容数据的内存块；该内存块的地址可由 *note
     addressof(): 2476. 辅助函数返回。 还有一个实例变量被公开为 *note
     _objects: 2484.；此变量包含其他在内存块包含指针的情况下需要保持存活
     的 Python 对象。

     ctypes 数据类型的通用方法，它们都是类方法（严谨地说，它们是 *note
     metaclass: 1590. 的方法）:

      -- 成員函式: from_buffer (source[, offset])

          此方法返回一个共享 `source' 对象缓冲区的 ctypes 实例。
          `source' 对象必须支持可写缓冲区接口。 可选的 `offset' 形参指定
          以字节表示的源缓冲区内偏移量；默认值为零。 如果源缓冲区不够大
          则会引发 *note ValueError: 16d.。

          引发一个 *note 审计事件: fa1. ‘ctypes.cdata/buffer’ 附带参数
          ‘pointer’, ‘size’, ‘offset’。

      -- 成員函式: from_buffer_copy (source[, offset])

          此方法创建一个 ctypes 实例，从 `source' 对象缓冲区拷贝缓冲区，
          该对象必须是可读的。 可选的 `offset' 形参指定以字节表示的源缓
          冲区内偏移量；默认值为零。 如果源缓冲区不够大则会引发 *note
          ValueError: 16d.。

          引发一个 *note 审计事件: fa1. ‘ctypes.cdata/buffer’ 附带参数
          ‘pointer’, ‘size’, ‘offset’。

      -- 成員函式: from_address (address)

          此方法会使用 `address' 所指定的内存返回一个 ctypes 类型的实例
          ，该参数必须为一个整数。

          引发一个 *note 审计事件: fa1. ‘ctypes.cdata’，附带参数
          ‘address’。

      -- 成員函式: from_param (obj)

          此方法会将 `obj' 适配为一个 ctypes 类型。 它调用时会在当该类型
          存在于外部函数的 ‘argtypes’ 元组时传入外部函数调用所使用的实际
          对象；它必须返回一个可被用作函数调用参数的对象。

          所有 ctypes 数据类型都带有这个类方法的默认实现，它通常会返回
          `obj'，如果该对象是此类型的实例的话。 某些类型也能接受其他对象
          。

      -- 成員函式: in_dll (library, name)

          此方法返回一个由共享库导出的 ctypes 类型。 `name' 为导出数据的
          符号名称，`library' 为所加载的共享库。

     ctypes 数据类型的通用实例变量:

      -- 屬性: _b_base_

          有时 ctypes 数据实例并不拥有它们所包含的内存块，它们只是共享了
          某个基对象的部分内存块。 *note _b_base_: 248a. 只读成员是拥有
          内存块的根 ctypes 对象。

      -- 屬性: _b_needsfree_

          这个只读变量在 ctypes 数据实例自身已分配了内存块时为真值，否则
          为假值。

      -- 屬性: _objects

          这个成员或者为 ‘None’，或者为一个包含需要保持存活以使内存块的
          内存保持有效的 Python 对象的字典。 这个对象只是出于调试目的而
          对外公开；绝对不要修改此字典的内容。


File: python.info,  Node: 基础数据类型<2>,  Next: 结构化数据类型,  Prev: 数据类型<2>,  Up: ctypes 参考手册

5.16.16.29 基础数据类型
.......................

 -- 類別: ctypes._SimpleCData

     这个非公有类是所有基本 ctypes 数据类型的基类。 它在这里被提及是因为
     它包含基本 ctypes 数据类型共有的属性。 *note _SimpleCData: 248e. 是
     *note _CData: 11e5. 的子类，因此继承了其方法和属性。 非指针及不包含
     指针的 ctypes 数据类型现在将可以被封存。

     实例拥有一个属性:

      -- 屬性: value

          这个属性包含实例的实际值。 对于整数和指针类型，它是一个整数，
          对于字符类型，它是一个单字符字符串对象或字符串，对于字符指针类
          型，它是一个 Python 字节串对象或字符串。

          当从 ctypes 实例提取 ‘value’ 属性时，通常每次会返回一个新的对
          象。 *note ctypes: 2a. 并 `没有' 实现原始对象返回，它总是会构
          造一个新的对象。 所有其他 ctypes 对象实例也同样如此。

基本数据类型当作为外部函数调用结果被返回或者作为结构字段成员或数组项被提
取时，会透明地转换为原生 Python 类型。 换句话说，如果某个外部函数具有
*note c_char_p: 2426. 的 ‘restype’，你将总是得到一个 Python 字节串对象，
而 `不是' 一个 *note c_char_p: 2426. 实例。

基本数据类型的子类并 `没有' 继续此行为。 因此，如果一个外部函数的
‘restype’ 是 *note c_void_p: 2427. 的一个子类，你将从函数调用得到一个该
子类的实例。 当然，你可以通过访问 ‘value’ 属性来获取指针的值。

这些是基本 ctypes 数据类型:

 -- 類別: ctypes.c_byte

     代表 C ‘signed char’ 数据类型，并将值解读为一个小整数。 该构造器接
     受一个可选的整数初始化器；不会执行溢出检查。

 -- 類別: ctypes.c_char

     代表 C ‘char’ 数据类型，并将值解读为单个字符。 该构造器接受一个可选
     的字符串初始化器，字符串的长度必须恰好为一个字符。

 -- 類別: ctypes.c_char_p

     当指向一个以零为结束符的字符串时代表 C ‘char *’ 数据类型。 对于通用
     字符指针来说也可能指向二进制数据，必须要使用 ‘POINTER(c_char)’。 该
     构造器接受一个整数地址，或者一个字节串对象。

 -- 類別: ctypes.c_double

     代表 C ‘double’ 数据类型。 该构造器接受一个可选的浮点数初始化器。

 -- 類別: ctypes.c_longdouble

     代表 C ‘long double’ 数据类型。 该构造器接受一个可选的浮点数初始化
     器。 在 ‘sizeof(long double) == sizeof(double)’ 的平台上它是 *note
     c_double: fc4. 的一个别名。

 -- 類別: ctypes.c_float

     代表 C ‘float’ 数据类型。 该构造器接受一个可选的浮点数初始化器。

 -- 類別: ctypes.c_int

     代表 C ‘signed int’ 数据类型。 该构造器接受一个可选的整数初始化器；
     不会执行溢出检查。 在 ‘sizeof(int) == sizeof(long)’ 的平台上它是
     *note c_long: 2410. 的一个别名。

 -- 類別: ctypes.c_int8

     代表 C 8 位 ‘signed int’ 数据类型。 通常是 *note c_byte: 241c. 的一
     个别名。

 -- 類別: ctypes.c_int16

     代表 C 16 位 ‘signed int’ 数据类型。 通常是 *note c_short: 241e. 的
     一个别名。

 -- 類別: ctypes.c_int32

     代表 C 32 位 ‘signed int’ 数据类型。 通常是 *note c_int: 240f. 的一
     个别名。

 -- 類別: ctypes.c_int64

     代表 C 64 位 ‘signed int’ 数据类型。 通常是 *note c_longlong: 2422.
     的一个别名。

 -- 類別: ctypes.c_long

     代表 C ‘signed long’ 数据类型。 该构造器接受一个可选的整数初始化器
     ；不会执行溢出检查。

 -- 類別: ctypes.c_longlong

     代表 C ‘signed long long’ 数据类型。 该构造器接受一个可选的整数初始
     化器；不会执行溢出检查。

 -- 類別: ctypes.c_short

     代表 C ‘signed short’ 数据类型。 该构造器接受一个可选的整数初始化器
     ；不会执行溢出检查。

 -- 類別: ctypes.c_size_t

     代表 C ‘size_t’ 数据类型。

 -- 類別: ctypes.c_ssize_t

     代表 C ‘ssize_t’ 数据类型。

     3.2 版新加入.

 -- 類別: ctypes.c_ubyte

     代表 C ‘unsigned char’ 数据类型，它将值解读为一个小整数。 该构造器
     接受一个可选的整数初始化器；不会执行溢出检查。

 -- 類別: ctypes.c_uint

     代表 C ‘unsigned int’ 数据类型。 该构造器接受一个可选的整数初始化器
     ；不会执行溢出检查。 在 ‘sizeof(int) == sizeof(long)’ 的平台上它是
     *note c_ulong: 2421. 的一个别名。

 -- 類別: ctypes.c_uint8

     代表 C 8 位 ‘unsigned int’ 数据类型。 通常是 *note c_ubyte: 241d. 的
     一个别名。

 -- 類別: ctypes.c_uint16

     代表 C 16 位 ‘unsigned int’ 数据类型。 通常是 *note c_ushort: 241f.
     的一个别名。

 -- 類別: ctypes.c_uint32

     代表 C 32 位 ‘unsigned int’ 数据类型。 通常是 *note c_uint: 2420. 的
     一个别名。

 -- 類別: ctypes.c_uint64

     代表 C 64 位 ‘unsigned int’ 数据类型。 通常是 *note c_ulonglong:
     2423. 的一个别名。

 -- 類別: ctypes.c_ulong

     代表 C ‘unsigned long’ 数据类型。 该构造器接受一个可选的整数初始化
     器；不会执行溢出检查。

 -- 類別: ctypes.c_ulonglong

     代表 C ‘unsigned long long’ 数据类型。 该构造器接受一个可选的整数初
     始化器；不会执行溢出检查。

 -- 類別: ctypes.c_ushort

     代表 C ‘unsigned short’ 数据类型。 该构造器接受一个可选的整数初始化
     器；不会执行溢出检查。

 -- 類別: ctypes.c_void_p

     代表 C ‘void *’ 类型。 该值被表示为整数形式。 该构造器接受一个可选
     的整数初始化器。

 -- 類別: ctypes.c_wchar

     代表 C ‘wchar_t’ 数据类型，并将值解读为一单个字符的 unicode 字符串
     。 该构造器接受一个可选的字符串初始化器，字符串的长度必须恰好为一个
     字符。

 -- 類別: ctypes.c_wchar_p

     代表 C ‘wchar_t *’ 数据类型，它必须为指向以零为结束符的宽字符串的指
     针。 该构造器接受一个整数地址或者一个字符串。

 -- 類別: ctypes.c_bool

     代表 C ‘bool’ 数据类型 (更准确地说是 C99 ‘_Bool’)。 它的值可以为
     ‘True’ 或 ‘False’，并且该构造器接受任何具有逻辑值的对象。

 -- 類別: ctypes.HRESULT

     Windows 专属：代表一个 ‘HRESULT’ 值，它包含某个函数或方法调用的成功
     或错误信息。

 -- 類別: ctypes.py_object

     代表 C *note PyObject *: 5b4. 数据类型。 不带参数地调用此构造器将创
     建一个 ‘NULL’ *note PyObject *: 5b4. 指针。

‘ctypes.wintypes’ 模块提供了其他许多 Windows 专属的数据类型，例如
‘HWND’, ‘WPARAM’ 或 ‘DWORD’。 还定义了一些有用的结构体例如 ‘MSG’ 或
‘RECT’。


File: python.info,  Node: 结构化数据类型,  Next: 数组与指针,  Prev: 基础数据类型<2>,  Up: ctypes 参考手册

5.16.16.30 结构化数据类型
.........................

 -- 類別: ctypes.Union (*args, **kw)

     本机字节序的联合所对应的抽象基类。

 -- 類別: ctypes.BigEndianStructure (*args, **kw)

     `大端' 字节序的结构体所对应的抽象基类。

 -- 類別: ctypes.LittleEndianStructure (*args, **kw)

     `小端' 字节序的结构体所对应的抽象基类。

非本机字节序的结构体不能包含指针类型字段，或任何其他包含指针类型字段的数
据类型。

 -- 類別: ctypes.Structure (*args, **kw)

     `本机' 字节序的结构体所对应的抽象基类。

     实际的结构体和联合类型必须通过子类化这些类型之一来创建，并且至少要
     定义一个 *note _fields_: 249b. 类变量。 *note ctypes: 2a. 将创建
     *note descriptor: 1579.，它允许通过直接属性访问来读取和写入字段。 这
     些是

      -- 屬性: _fields_

          一个定义结构体字段的序列。 其中的条目必须为 2 元组或 3 元组。
          元组的第一项是字段名称，第二项指明字段类型；它可以是任何
          ctypes 数据类型。

          对于整数类型字段例如 *note c_int: 240f.，可以给定第三个可选项
          。 它必须是一个定义字段比特位宽度的小正整数。

          字段名称在一个结构体或联合中必须唯一。 不会检查这个唯一性，但
          当名称出现重复时将只有一个字段可被访问。

          可以在定义 Structure 子类的类语句 `之后' 再定义 *note
          _fields_: 249b. 类变量，这将允许创建直接或间接引用其自身的数据
          类型:

               class List(Structure):
                   pass
               List._fields_ = [("pnext", POINTER(List)),
                                ...
                               ]

          但是，*note _fields_: 249b. 类变量必须在类型第一次被使用（创建
          实例，调用 *note sizeof(): 247e. 等等）之前进行定义。 在此之后
          对 *note _fields_: 249b. 类变量赋值将会引发 AttributeError。

          可以定义结构体类型的子类，它们会继承基类的字段再加上在子类中定
          义的任何 *note _fields_: 249b.。

      -- 屬性: _pack_

          一个可选的小整数，它允许覆盖实体中结构体字段的对齐方式。 当
          *note _fields_: 249b. 被赋值时必须已经定义了 *note _pack_:
          249c.，否则它将没有效果。

      -- 屬性: _anonymous_

          一个可选的序列，它会列出未命名（匿名）字段的名称。 当 *note
          _fields_: 249b. 被赋值时必须已经定义了 *note _anonymous_:
          249d.，否则它将没有效果。

          在此变量中列出的字段必须为结构体或联合类型字段。 *note ctypes:
          2a. 将在结构体类型中创建描述器以允许直接访问嵌套字段，而无需创
          建对应的结构体或联合字段。

          以下是一个示例类型（Windows）:

               class _U(Union):
                   _fields_ = [("lptdesc", POINTER(TYPEDESC)),
                               ("lpadesc", POINTER(ARRAYDESC)),
                               ("hreftype", HREFTYPE)]

               class TYPEDESC(Structure):
                   _anonymous_ = ("u",)
                   _fields_ = [("u", _U),
                               ("vt", VARTYPE)]

          ‘TYPEDESC’ 结构体描述了一个 COM 数据类型，‘vt’ 字段指明哪个联
          合字段是有效的。 由于 ‘u’ 字段被定义为匿名字段，现在可以直接从
          TYPEDESC 实例访问成员。 ‘td.lptdesc’ 和 ‘td.u.lptdesc’ 是等价
          的，但前者速度更快，因为它不需要创建临时的联合实例:

               td = TYPEDESC()
               td.vt = VT_PTR
               td.lptdesc = POINTER(some_type)
               td.u.lptdesc = POINTER(some_type)

     可以定义结构体的子类，它们会继承基类的字段。 如果子类定义具有单独的
     *note _fields_: 249b. 变量，在其中指定的字段会被添加到基类的字段中
     。

     结构体和联合的构造器均可接受位置和关键字参数。 位置参数用于按照
     *note _fields_: 249b. 中的出现顺序来初始化成员字段。 构造器中的关键
     字参数会被解读为属性赋值，因此它们将以相应的名称来初始化 *note
     _fields_: 249b.，或为不存在于 *note _fields_: 249b. 中的名称创建新
     的属性。


File: python.info,  Node: 数组与指针,  Prev: 结构化数据类型,  Up: ctypes 参考手册

5.16.16.31 数组与指针
.....................

 -- 類別: ctypes.Array (*args)

     数组的抽象基类。

     创建实际数组类型的推荐方式是通过将任意 *note ctypes: 2a. 类型与一个
     正整数相乘。 作为替代方式，你也可以子类化这个类型并定义 *note
     _length_: 24a0. 和 *note _type_: 24a1. 类变量。 数组元素可使用标准
     的抽取和切片方式来读写；对于切片读取，结果对象本身 `并非' 一个
     *note Array: 1145.。

      -- 屬性: _length_

          一个指明数组中元素数量的正整数。 超出范围的抽取会导致 *note
          IndexError: f36.。 该值将由 *note len(): 28b. 返回。

      -- 屬性: _type_

          指明数组中每个元素的类型。

     Array 子类构造器可接受位置参数，用来按顺序初始化元素。

 -- 類別: ctypes._Pointer

     私有对象，指针的抽象基类。

     实际的指针类型是通过调用 *note POINTER(): 2445. 并附带其将指向的类
     型来创建的；这会由 *note pointer(): 2435. 自动完成。

     如果一个指针指向的是数组，则其元素可使用标准的抽取和切片方式来读写
     。 指针对象没有长度，因此 *note len(): 28b. 将引发 *note TypeError:
     1fe.。 抽取负值将会从指针 `之前' 的内存中读取（与 C 一样），并且超
     出范围的抽取将可能因非法访问而导致崩溃（视你的运气而定）。

      -- 屬性: _type_

          指明所指向的类型。

      -- 屬性: contents

          返回指针所指向的对象。 对此属性赋值会使指针改为指向所赋值的对
          象。


File: python.info,  Node: 并发执行,  Next: 网络和进程间通信,  Prev: 通用操作系统服务,  Up: Python 標準函式庫 Standard Library

5.17 并发执行
=============

本章中描述的模块支持并发执行代码。 适当的工具选择取决于要执行的任务（
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


File: python.info,  Node: threading --- 基于线程的并行,  Next: multiprocessing --- 基于进程的并行,  Up: 并发执行

5.17.1 ‘threading’ — 基于线程的并行
-----------------------------------

`源代码:' Lib/threading.py(1)

__________________________________________________________________

这个模块在较低级的模块 *note _thread: 2. 基础上建立较高级的线程接口。参
见： *note queue: da. 模块。

3.7 版更變: 这个模块曾经为可选项，但现在总是可用。

     備註: 虽然他们没有在下面列出，这个模块仍然支持Python 2.x系列的这个
     模块下以 ‘camelCase’ （驼峰法）命名的方法和函数。

`CPython implementation detail:' 在 CPython 中，由于存在 *note
全局解释器锁: 5ff.，同一时刻只有一个线程可以执行 Python 代码（虽然某些性
能导向的库可能会去除此限制）。 如果你想让你的应用更好地利用多核心计算机
的计算资源，推荐你使用 *note multiprocessing: b7. 或 *note
concurrent.futures.ProcessPoolExecutor: 196.。 但是，如果你想要同时运行
多个 I/O 密集型任务，则多线程仍然是一个合适的模型。

这个模块定义了以下函数：

 -- 函式: threading.active_count ()

     返回当前存活的 *note Thread: 21a. 对象的数量。 返回值与 *note
     enumerate(): f90. 所返回的列表长度一致。

 -- 函式: threading.current_thread ()

     返回当前对应调用者的控制线程的 *note Thread: 21a. 对象。如果调用者
     的控制线程不是利用 *note threading: 10b. 创建，会返回一个功能受限的
     虚拟线程对象。

 -- 函式: threading.excepthook (args, /)

     处理由 *note Thread.run(): 35f. 引发的未捕获异常。

     `args' 参数具有以下属性:

        * `exc_type': 异常类型

        * `exc_value': 异常值，可以是 ‘None’.

        * `exc_traceback': 异常回溯，可以是 ‘None’.

        * `thread': 引发异常的线程，可以为 ‘None’。

     如果 `exc_type' 为 *note SystemExit: 6f3.，则异常会被静默地忽略。 在
     其他情况下，异常将被打印到 *note sys.stderr: 1ea.。

     如果此函数引发了异常，则会调用 *note sys.excepthook(): f24. 来处理
     它。

     *note threading.excepthook(): 35e. 可以被重载以控制由 *note
     Thread.run(): 35f. 引发的未捕获异常的处理方式。

     使用定制钩子存放 `exc_value' 可能会创建引用循环。 它应当在不再需要
     异常时被显式地清空以打破引用循环。

     使用定制钩子存放 `thread' 可能会在它设为被终结对象时将其重生。 请避
     免在定制钩子完成后存放 `thread' 以避免对象的重生。

     也參考
     ......

     *note sys.excepthook(): f24. 处理未捕获的异常。

     3.8 版新加入.

 -- 函式: threading.get_ident ()

     返回当前线程的 “线程标识符”。它是一个非零的整数。它的值没有直接含义
     ，主要是用作 magic cookie，比如作为含有线程相关数据的字典的索引。线
     程标识符可能会在线程退出，新线程创建时被复用。

     3.3 版新加入.

 -- 函式: threading.get_native_id ()

     返回内核分配给当前线程的原生集成线程 ID。 这是一个非负整数。 它的值
     可被用来在整个系统中唯一地标识这个特定线程（直到线程终结，在那之后
     该值可能会被 OS 回收再利用）。

     *note 可用性: 1491.: Windows, FreeBSD, Linux, macOS, OpenBSD,
     NetBSD, AIX。

     3.8 版新加入.

 -- 函式: threading.enumerate ()

     返回当前所有存活的 *note Thread: 21a. 对象的列表。 该列表包括守护线
     程以及 *note current_thread(): 24aa. 创建的空线程。 它不包括已终结
     的和尚未开始的线程。 但是，主线程将总是结果的一部分，即使是在已终结
     的时候。

 -- 函式: threading.main_thread ()

     返回主 *note Thread: 21a. 对象。一般情况下，主线程是Python解释器开
     始时创建的线程。

     3.4 版新加入.

 -- 函式: threading.settrace (func)

     为所有 *note threading: 10b. 模块开始的线程设置追踪函数。在每个线程
     的 *note run(): 35f. 方法被调用前，`func' 会被传递给 *note
     sys.settrace(): f00. 。

 -- 函式: threading.setprofile (func)

     为所有 *note threading: 10b. 模块开始的线程设置性能测试函数。在每个
     线程的 *note run(): 35f. 方法被调用前，`func' 会被传递给 *note
     sys.setprofile(): eff. 。

 -- 函式: threading.stack_size ([size])

     返回创建线程时用的堆栈大小。可选参数 `size' 指定之后新建的线程的堆
     栈大小，而且一定要是0（根据平台或者默认配置）或者最小是
     32,768(32KiB)的一个正整数。如果 `size' 没有指定，默认是0。如果不支
     持改变线程堆栈大小，会抛出 *note RuntimeError: 3dc. 错误。如果指定
     的堆栈大小不合法，会抛出 *note ValueError: 16d. 错误并且不会修改堆
     栈大小。32KiB是当前最小的能保证解释器有足够堆栈空间的堆栈大小。需要
     注意的是部分平台对于堆栈大小会有特定的限制，例如要求大于32KiB的堆栈
     大小或者需要根据系统内存页面的整数倍进行分配 - 应当查阅平台文档有关
     详细信息（4KiB页面比较普遍，在没有更具体信息的情况下，建议的方法是
     使用4096的倍数作为堆栈大小）。

     *note 适用于: 1491.: Windows，具有 POSIX 线程的系统。

这个模块同时定义了以下常量：

 -- Data: threading.TIMEOUT_MAX

     阻塞函数（ *note Lock.acquire(): 85b, *note RLock.acquire(): 85c,
     *note Condition.wait(): f97, ...）中形参 `timeout' 允许的最大值。传
     入超过这个值的 timeout 会抛出 *note OverflowError: a41. 异常。

     3.2 版新加入.

这个模块定义了许多类，详见以下部分。

该模块的设计基于 Java的线程模型。 但是，在Java里面，锁和条件变量是每个对
象的基础特性，而在Python里面，这些被独立成了单独的对象。 Python 的 *note
Thread: 21a. 类只是 Java 的 Thread 类的一个子集；目前还没有优先级，没有
线程组，线程还不能被销毁、停止、暂停、恢复或中断。 Java 的 Thread 类的静
态方法在实现时会映射为模块级函数。

下述方法的执行都是原子性的。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/threading.py


File: python.info,  Node: 线程本地数据,  Next: 线程对象,  Up: threading --- 基于线程的并行

5.17.1.1 线程本地数据
.....................

线程本地数据是特定线程的数据。管理线程本地数据，只需要创建一个 *note
local: 244e. （或者一个子类型）的实例并在实例中储存属性：

     mydata = threading.local()
     mydata.x = 1

在不同的线程中，实例的值会不同。

 -- 類別: threading.local

     一个代表线程本地数据的类。

     更多相关细节和大量示例，参见 ‘_threading_local’ 模块的文档。


File: python.info,  Node: 线程对象,  Next: 锁对象,  Prev: 线程本地数据,  Up: threading --- 基于线程的并行

5.17.1.2 线程对象
.................

The *note Thread: 21a. 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
*note run(): 35f. method in a subclass.  No other methods (except for
the constructor) should be overridden in a subclass.  In other words,
`only' override the ‘__init__()’ and *note run(): 35f. methods of this
class.

当线程对象一但被创建，其活动一定会因调用线程的 *note start(): 222e. 方法
开始。这会在独立的控制线程调用 *note run(): 35f. 方法。

一旦线程活动开始，该线程会被认为是 ’存活的’ 。当它的 *note run(): 35f. 方
法终结了（不管是正常的还是抛出未被处理的异常），就不是’存活的’。 *note
is_alive(): 21b. 方法用于检查线程是否存活。

其他线程可以调用一个线程的 *note join(): c32. 方法。这会阻塞调用该方法的
线程，直到被调用 *note join(): c32. 方法的线程终结。

线程有名字。名字可以传递给构造函数，也可以通过 *note name: 24b2. 属性读
取或者修改。

如果 *note run(): 35f. 方法引发了异常，则会调用 *note
threading.excepthook(): 35e. 来处理它。 在默认情况下，*note
threading.excepthook(): 35e. 会静默地忽略 *note SystemExit: 6f3.。

一个线程可以被标记成一个“守护线程”。 这个标识的意义是，当剩下的线程都是
守护线程时，整个 Python 程序将会退出。 初始值继承于创建线程。 这个标识可
以通过 *note daemon: 24b3. 特征属性或者 `daemon' 构造器参数来设置。

     備註: 守护线程在程序关闭时会突然关闭。他们的资源（例如已经打开的文
     档，数据库事务等等）可能没有被正确释放。如果你想你的线程正常停止，
     设置他们成为非守护模式并且使用合适的信号机制，例如： *note Event:
     b85.。

有个 "主线程" 对象；这对应Python程序里面初始的控制线程。它不是一个守护线
程。

"虚拟线程对象" 是可以被创建的。这些是对应于“外部线程”的线程对象，它们是
在线程模块外部启动的控制线程，例如直接来自C代码。虚拟线程对象功能受限；
他们总是被认为是存活的和守护模式，不能被 *note join(): c32. 。因为无法检
测外来线程的终结，它们永远不会被删除。

 -- 類別: threading.Thread (group=None, target=None, name=None, args=(),
          kwargs={}, *, daemon=None)

     调用这个构造函数时，必需带有关键字参数。参数如下：

     `group' 应该为 ‘None’；为了日后扩展 ‘ThreadGroup’ 类实现而保留。

     `target' 是用于 *note run(): 35f. 方法调用的可调用对象。默认是
     ‘None’，表示不需要调用任何方法。

     `name' 是线程名称。默认情况下，由 "Thread-`N'" 格式构成一个唯一的名
     称，其中 `N' 是小的十进制数。

     `args' 是用于调用目标函数的参数元组。默认是 ‘()’。

     `kwargs' 是用于调用目标函数的关键字参数字典。默认是 ‘{}’。

     如果不是 ‘None’，`daemon' 参数将显式地设置该线程是否为守护模式。 如
     果是 ‘None’ (默认值)，线程将继承当前线程的守护模式属性。

     如果子类型重载了构造函数，它一定要确保在做任何事前，先发起调用基类
     构造器(‘Thread.__init__()’)。

     3.3 版更變: 加入 `daemon' 参数。

      -- 成員函式: start ()

          开始线程活动。

          它在一个线程里最多只能被调用一次。它安排对象的 *note run():
          35f. 方法在一个独立的控制进程中调用。

          如果同一个线程对象中调用这个方法的次数大于一次，会抛出 *note
          RuntimeError: 3dc. 。

      -- 成員函式: run ()

          代表线程活动的方法。

          你可以在子类型里重载这个方法。 标准的 *note run(): 35f. 方法会
          对作为 `target' 参数传递给该对象构造器的可调用对象（如果存在）
          发起调用，并附带从 `args' 和 `kwargs' 参数分别获取的位置和关键
          字参数。

      -- 成員函式: join (timeout=None)

          等待，直到线程终结。这会阻塞调用这个方法的线程，直到被调用
          *note join(): c32. 的线程终结 – 不管是正常终结还是抛出未处理异
          常 – 或者直到发生超时，超时选项是可选的。

          当 `timeout' 参数存在而且不是 ‘None’ 时，它应该是一个用于指定
          操作超时的以秒为单位的浮点数（或者分数）。因为 *note join():
          c32. 总是返回 ‘None’ ，所以你一定要在 *note join(): c32. 后调
          用 *note is_alive(): 21b. 才能判断是否发生超时 – 如果线程仍然
          存活，则 *note join(): c32. 超时。

          当 `timeout' 参数不存在或者是 ‘None’ ，这个操作会阻塞直到线程
          终结。

          一个线程可以被 *note join(): c32. 很多次。

          如果尝试加入当前线程会导致死锁， *note join(): c32. 会引起
          *note RuntimeError: 3dc. 异常。如果尝试 *note join(): c32. 一
          个尚未开始的线程，也会抛出相同的异常。

      -- 屬性: name

          只用于识别的字符串。它没有语义。多个线程可以赋予相同的名称。 初
          始名称由构造函数设置。

      -- 成員函式: getName ()
      -- 成員函式: setName ()

          旧的 *note name: 24b2. 取值/设值 API；请改为直接以特征属性方式
          使用它。

      -- 屬性: ident

          这个线程的 ’线程标识符’，如果线程尚未开始则为 ‘None’ 。这是个
          非零整数。参见 *note get_ident(): b87. 函数。当一个线程退出而
          另外一个线程被创建，线程标识符会被复用。即使线程退出后，仍可得
          到标识符。

      -- 屬性: native_id

          此线程的原生集成线程 ID。 这是一个非负整数，或者如果线程还未启
          动则为 ‘None’。 请参阅 *note get_native_id(): 360. 函数。 这表
          示线程 ID (‘TID’) 已被 OS (内核) 赋值给线程。 它的值可能被用来
          在全系统范围内唯一地标识这个特定线程（直到线程终结，在那之后该
          值可能会被 OS 回收再利用）。

               備註: 类似于进程 ID，线程 ID 的有效期（全系统范围内保证唯
               一）将从线程被创建开始直到线程被终结。

          *note 可用性: 1491.: 需要 *note get_native_id(): 360. 函数。

          3.8 版新加入.

      -- 成員函式: is_alive ()

          返回线程是否存活。

          当 *note run(): 35f. 方法刚开始直到 *note run(): 35f. 方法刚结
          束，这个方法返回 ‘True’ 。模块函数 *note enumerate(): f90. 返
          回包含所有存活线程的列表。

      -- 屬性: daemon

          一个表示这个线程是（True）否（False）守护线程的布尔值。一定要
          在调用 *note start(): 222e. 前设置好，不然会抛出 *note
          RuntimeError: 3dc. 。初始值继承于创建线程；主线程不是守护线程
          ，因此主线程创建的所有线程默认都是 *note daemon: 24b3. =
          ‘False’。

          当没有存活的非守护线程时，整个Python程序才会退出。

      -- 成員函式: isDaemon ()
      -- 成員函式: setDaemon ()

          旧的 *note daemon: 24b3. 取值/设值 API；请改为直接以特性属性方
          式使用它。


File: python.info,  Node: 锁对象,  Next: 递归锁对象,  Prev: 线程对象,  Up: threading --- 基于线程的并行

5.17.1.3 锁对象
...............

原始锁是一个在锁定时不属于特定线程的同步基元组件。在Python中，它是能用的
最低级的同步基元组件，由 *note _thread: 2. 扩展模块直接实现。

原始锁处于 "锁定" 或者 "非锁定" 两种状态之一。它被创建时为非锁定状态。它
有两个基本方法， *note acquire(): 85b. 和 *note release(): 24ba. 。当状
态为非锁定时， *note acquire(): 85b. 将状态改为 锁定 并立即返回。当状态
是锁定时， *note acquire(): 85b. 将阻塞至其他线程调用 *note release():
24ba. 将其改为非锁定状态，然后 *note acquire(): 85b. 调用重置其为锁定状
态并返回。 *note release(): 24ba. 只在锁定状态下调用； 它将状态改为非锁
定并立即返回。如果尝试释放一个非锁定的锁，则会引发 *note RuntimeError:
3dc.  异常。

锁同样支持 *note 上下文管理协议: 24bb.。

当多个线程在 *note acquire(): 85b. 等待状态转变为未锁定被阻塞，然后
*note release(): 24ba. 重置状态为未锁定时，只有一个线程能继续执行；至于
哪个等待线程继续执行没有定义，并且会根据实现而不同。

所有方法的执行都是原子性的。

 -- 類別: threading.Lock

     实现原始锁对象的类。一旦一个线程获得一个锁，会阻塞随后尝试获得锁的
     线程，直到它被释放；任何线程都可以释放它。

     需要注意的是 ‘Lock’ 其实是一个工厂函数，返回平台支持的具体锁类中最
     有效的版本的实例。

      -- 成員函式: acquire (blocking=True, timeout=-1)

          可以阻塞或非阻塞地获得锁。

          当调用时参数 `blocking' 设置为 ‘True’ （缺省值），阻塞直到锁被
          释放，然后将锁锁定并返回 ‘True’ 。

          在参数 `blocking' 被设置为 ‘False’ 的情况下调用，将不会发生阻
          塞。如果调用时 `blocking' 设为 ‘True’ 会阻塞，并立即返回
          ‘False’ ；否则，将锁锁定并返回 ‘True’。

          当浮点型 `timeout' 参数被设置为正值调用时，只要无法获得锁，将
          最多阻塞 `timeout' 设定的秒数。`timeout' 参数被设置为 ‘-1’ 时
          将无限等待。当 `blocking' 为 false 时，`timeout' 指定的值将被
          忽略。

          如果成功获得锁，则返回 ‘True’，否则返回 ‘False’ (例如发生 `超
          时' 的时候)。

          3.2 版更變: 新的 `timeout' 形参。

          3.2 版更變: 现在如果底层线程实现支持，则可以通过POSIX上的信号
          中断锁的获取。

      -- 成員函式: release ()

          释放一个锁。这个方法可以在任何线程中调用，不单指获得锁的线程。

          当锁被锁定，将它重置为未锁定，并返回。如果其他线程正在等待这个
          锁解锁而被阻塞，只允许其中一个允许。

          在未锁定的锁调用时，会引发 *note RuntimeError: 3dc. 异常。

          没有返回值。

      -- 成員函式: locked ()

          如果获得了锁则返回真值。


File: python.info,  Node: 递归锁对象,  Next: 条件对象,  Prev: 锁对象,  Up: threading --- 基于线程的并行

5.17.1.4 递归锁对象
...................

重入锁是一个可以被同一个线程多次获取的同步基元组件。在内部，它在基元锁的
锁定/非锁定状态上附加了 "所属线程" 和 "递归等级" 的概念。在锁定状态下，
某些线程拥有锁 ； 在非锁定状态下， 没有线程拥有它。

若要锁定锁，线程调用其 *note acquire(): 85c. 方法；一旦线程拥有了锁，方
法将返回。若要解锁，线程调用 *note release(): 24ba. 方法。 *note
acquire(): 85b./*note release(): 24ba. 对可以嵌套；只有最终 *note
release(): 24ba. (最外面一对的 *note release(): 24ba. ) 将锁解开，才能让
其他线程继续处理 *note acquire(): 85b. 阻塞。

递归锁也支持 *note 上下文管理协议: 24bb.。

 -- 類別: threading.RLock

     此类实现了重入锁对象。重入锁必须由获取它的线程释放。一旦线程获得了
     重入锁，同一个线程再次获取它将不阻塞；线程必须在每次获取它时释放一
     次。

     需要注意的是 ‘RLock’ 其实是一个工厂函数，返回平台支持的具体递归锁类
     中最有效的版本的实例。

      -- 成員函式: acquire (blocking=True, timeout=-1)

          可以阻塞或非阻塞地获得锁。

          当无参数调用时： 如果这个线程已经拥有锁，递归级别增加一，并立
          即返回。否则，如果其他线程拥有该锁，则阻塞至该锁解锁。一旦锁被
          解锁(不属于任何线程)，则抢夺所有权，设置递归等级为一，并返回。
          如果多个线程被阻塞，等待锁被解锁，一次只有一个线程能抢到锁的所
          有权。在这种情况下，没有返回值。

          当发起调用时将 `blocking' 参数设为真值，则执行与无参数调用时一
          样的操作，然后返回 ‘True’。

          当发起调用时将 `blocking' 参数设为假值，则不进行阻塞。 如果一
          个无参数调用将要阻塞，则立即返回 ‘False’；在其他情况下，执行与
          无参数调用时一样的操作，然后返回 ‘True’。

          当发起调用时将浮点数的 `timeout' 参数设为正值时，只要无法获得
          锁，将最多阻塞 `timeout' 所指定的秒数。 如果已经获得锁则返回
          ‘True’，如果超时则返回假值。

          3.2 版更變: 新的 `timeout' 形参。

      -- 成員函式: release ()

          释放锁，自减递归等级。如果减到零，则将锁重置为非锁定状态(不被
          任何线程拥有)，并且，如果其他线程正被阻塞着等待锁被解锁，则仅
          允许其中一个线程继续。如果自减后，递归等级仍然不是零，则锁保持
          锁定，仍由调用线程拥有。

          只有当前线程拥有锁才能调用这个方法。如果锁被释放后调用这个方法
          ，会引起 *note RuntimeError: 3dc. 异常。

          没有返回值。


File: python.info,  Node: 条件对象,  Next: 信号量对象,  Prev: 递归锁对象,  Up: threading --- 基于线程的并行

5.17.1.5 条件对象
.................

条件变量总是与某种类型的锁对象相关联，锁对象可以通过传入获得，或者在缺省
的情况下自动创建。当多个条件变量需要共享同一个锁时，传入一个锁很有用。锁
是条件对象的一部分，你不必单独地跟踪它。

条件变量遵循 *note 上下文管理协议: 24bb. ：使用 ‘with’ 语句会在它包围的
代码块内获取关联的锁。 *note acquire(): 24c3. 和 *note release(): 24c4.
方法也能调用关联锁的相关方法。

其它方法必须在持有关联的锁的情况下调用。 *note wait(): f97. 方法释放锁，
然后阻塞直到其它线程调用 *note notify(): 24c5. 方法或 *note
notify_all(): 24c6. 方法唤醒它。一旦被唤醒， *note wait(): f97. 方法重新
获取锁并返回。它也可以指定超时时间。

The *note notify(): 24c5. method wakes up one of the threads waiting for
the condition variable, if any are waiting.  The *note notify_all():
24c6. method wakes up all threads waiting for the condition variable.

注意： *note notify(): 24c5. 方法和 *note notify_all(): 24c6. 方法并不会
释放锁，这意味着被唤醒的线程不会立即从它们的 *note wait(): f97. 方法调用
中返回，而是会在调用了 *note notify(): 24c5. 方法或 *note notify_all():
24c6. 方法的线程最终放弃了锁的所有权后返回。

使用条件变量的典型编程风格是将锁用于同步某些共享状态的权限，那些对状态的
某些特定改变感兴趣的线程，它们重复调用 *note wait(): f97. 方法，直到看到
所期望的改变发生；而对于修改状态的线程，它们将当前状态改变为可能是等待者
所期待的新状态后，调用 *note notify(): 24c5. 方法或者 *note
notify_all(): 24c6. 方法。例如，下面的代码是一个通用的无限缓冲区容量的生
产者-消费者情形：

     # 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()

使用 ‘while’ 循环检查所要求的条件成立与否是有必要的，因为 *note wait():
f97. 方法可能要经过不确定长度的时间后才会返回，而此时导致 *note
notify(): 24c5. 方法调用的那个条件可能已经不再成立。这是多线程编程所固有
的问题。 *note wait_for(): 24c7. 方法可自动化条件检查，并简化超时计算。

     # Consume an item
     with cv:
         cv.wait_for(an_item_is_available)
         get_an_available_item()

选择 *note notify(): 24c5. 还是 *note notify_all(): 24c6. ，取决于一次状
态改变是只能被一个还是能被多个等待线程所用。例如在一个典型的生产者-消费
者情形中，添加一个项目到缓冲区只需唤醒一个消费者线程。

 -- 類別: threading.Condition (lock=None)

     实现条件变量对象的类。一个条件变量对象允许一个或多个线程在被其它线
     程所通知之前进行等待。

     如果给出了非 ‘None’ 的 `lock' 参数，则它必须为 *note Lock: 24bc. 或
     者 *note RLock: cba. 对象，并且它将被用作底层锁。否则，将会创建新的
     *note RLock: cba. 对象，并将其用作底层锁。

     3.3 版更變: 从工厂函数变为类。

      -- 成員函式: acquire (*args)

          请求底层锁。此方法调用底层锁的相应方法，返回值是底层锁相应方法
          的返回值。

      -- 成員函式: release ()

          释放底层锁。此方法调用底层锁的相应方法。没有返回值。

      -- 成員函式: wait (timeout=None)

          等待直到被通知或发生超时。如果线程在调用此方法时没有获得锁，将
          会引发 *note RuntimeError: 3dc. 异常。

          这个方法释放底层锁，然后阻塞，直到在另外一个线程中调用同一个条
          件变量的 *note notify(): 24c5. 或 *note notify_all(): 24c6. 唤
          醒它，或者直到可选的超时发生。一旦被唤醒或者超时，它重新获得锁
          并返回。

          当提供了 `timeout' 参数且不是 ‘None’ 时，它应该是一个浮点数，
          代表操作的超时时间，以秒为单位（可以为小数）。

          当底层锁是个 *note RLock: cba. ，不会使用它的 *note release():
          24c4. 方法释放锁，因为当它被递归多次获取时，实际上可能无法解锁
          。相反，使用了 *note RLock: cba. 类的内部接口，即使多次递归获
          取它也能解锁它。 然后，在重新获取锁时，使用另一个内部接口来恢
          复递归级别。

          返回 ‘True’ ，除非提供的 `timeout' 过期，这种情况下返回
          ‘False’。

          3.2 版更變: 很明显，方法总是返回 ‘None’。

      -- 成員函式: wait_for (predicate, timeout=None)

          等待，直到条件计算为真。 `predicate' 应该是一个可调用对象而且
          它的返回值可被解释为一个布尔值。可以提供 `timeout' 参数给出最
          大等待时间。

          这个实用方法会重复地调用 *note wait(): f97. 直到满足判断式或者
          发生超时。返回值是判断式最后一个返回值，而且如果方法发生超时会
          返回 ‘False’ 。

          忽略超时功能，调用此方法大致相当于编写:

               while not predicate():
                   cv.wait()

          因此，规则同样适用于 *note wait(): f97. ：锁必须在被调用时保持
          获取，并在返回时重新获取。 随着锁定执行判断式。

          3.2 版新加入.

      -- 成員函式: notify (n=1)

          默认唤醒一个等待这个条件的线程。如果调用线程在没有获得锁的情况
          下调用这个方法，会引发 *note RuntimeError: 3dc. 异常。

          这个方法唤醒最多 `n' 个正在等待这个条件变量的线程；如果没有线
          程在等待，这是一个空操作。

          当前实现中，如果至少有 `n' 个线程正在等待，准确唤醒 `n' 个线程
          。但是依赖这个行为并不安全。未来，优化的实现有时会唤醒超过 `n'
          个线程。

          注意：被唤醒的线程并没有真正恢复到它调用的 *note wait(): f97.
          ，直到它可以重新获得锁。 因为 *note notify(): 24c5. 不释放锁，
          其调用者才应该这样做。

      -- 成員函式: notify_all ()

          唤醒所有正在等待这个条件的线程。这个方法行为与 *note notify():
          24c5. 相似，但并不只唤醒单一线程，而是唤醒所有等待线程。如果调
          用线程在调用这个方法时没有获得锁，会引发 *note RuntimeError:
          3dc. 异常。


File: python.info,  Node: 信号量对象,  Next: 事件对象,  Prev: 条件对象,  Up: threading --- 基于线程的并行

5.17.1.6 信号量对象
...................

这是计算机科学史上最古老的同步原语之一，早期的荷兰科学家 Edsger W.
Dijkstra 发明了它。（他使用名称 ‘P()’ 和 ‘V()’ 而不是 *note acquire():
cb8. 和 *note release(): 24ca. ）。

一个信号量管理一个内部计数器，该计数器因 *note acquire(): cb8. 方法的调
用而递减，因 *note release(): 24ca. 方法的调用而递增。 计数器的值永远不
会小于零；当 *note acquire(): cb8. 方法发现计数器为零时，将会阻塞，直到
其它线程调用 *note release(): 24ca. 方法。

信号量对象也支持 *note 上下文管理协议: 24bb. 。

 -- 類別: threading.Semaphore (value=1)

     该类实现信号量对象。信号量对象管理一个原子性的计数器，代表 *note
     release(): 24ca. 方法的调用次数减去 *note acquire(): cb8. 的调用次
     数再加上一个初始值。如果需要， *note acquire(): cb8. 方法将会阻塞直
     到可以返回而不会使得计数器变成负数。在没有显式给出 `value' 的值时，
     默认为1。

     可选参数 `value' 赋予内部计数器初始值，默认值为 ‘1’ 。如果 `value'
     被赋予小于0的值，将会引发 *note ValueError: 16d. 异常。

     3.3 版更變: 从工厂函数变为类。

      -- 成員函式: acquire (blocking=True, timeout=None)

          获取一个信号量。

          在不带参数的情况下调用时：

             * 如果在进入时内部计数器的值大于零，则将其减一并立即返回
               ‘True’.

             * 如果在进入时内部计数器的值为零，则将会阻塞直到被对 *note
               release(): 24ca. 的调用唤醒。 一旦被唤醒（并且计数器的值
               大于 0），则将计数器减 1 并返回 ‘True’。 每次对 *note
               release(): 24ca. 的调用将只唤醒一个线程。 线程被唤醒的次
               序是不可确定的。

          当发起调用时将 `blocking' 设为假值，则不进行阻塞。 如果一个无
          参数调用将要阻塞，则立即返回 ‘False’；在其他情况下，执行与无参
          数调用时一样的操作，然后返回 ‘True’。

          当发起调用时如果 `timeout' 不为 ‘None’，则它将阻塞最多
          `timeout' 秒。 请求在此时段时未能成功完成获取则将返回 ‘False’。
          在其他情况下返回 ‘True’。

          3.2 版更變: 新的 `timeout' 形参。

      -- 成員函式: release (n=1)

          释放一个信号量，将内部计数器的值增加 `n'。 当进入时值为零且有
          其他线程正在等待它再次变为大于零时，则唤醒那 `n' 个线程。

          3.9 版更變: 增加了 `n' 形参以一次性释放多个等待线程。

 -- 類別: threading.BoundedSemaphore (value=1)

     该类实现有界信号量。有界信号量通过检查以确保它当前的值不会超过初始
     值。如果超过了初始值，将会引发 *note ValueError: 16d. 异常。在大多
     情况下，信号量用于保护数量有限的资源。如果信号量被释放的次数过多，
     则表明出现了错误。没有指定时， `value' 的值默认为1。

     3.3 版更變: 从工厂函数变为类。

* Menu:

* Semaphore 例子::


File: python.info,  Node: Semaphore 例子,  Up: 信号量对象

5.17.1.7 ‘Semaphore’ 例子
.........................

信号量通常用于保护数量有限的资源，例如数据库服务器。在资源数量固定的任何
情况下，都应该使用有界信号量。在生成任何工作线程前，应该在主线程中初始化
信号量。

     maxconnections = 5
     # ...
     pool_sema = BoundedSemaphore(value=maxconnections)

工作线程生成后，当需要连接服务器时，这些线程将调用信号量的 acquire 和
release 方法：

     with pool_sema:
         conn = connectdb()
         try:
             # ... use connection ...
         finally:
             conn.close()

使用有界信号量能减少这种编程错误：信号量的释放次数多于其请求次数。


File: python.info,  Node: 事件对象,  Next: 定时器对象,  Prev: 信号量对象,  Up: threading --- 基于线程的并行

5.17.1.8 事件对象
.................

这是线程之间通信的最简单机制之一：一个线程发出事件信号，而其他线程等待该
信号。

一个事件对象管理一个内部标识，调用 *note set(): 24cf. 方法可将其设置为
true ，调用 *note clear(): 24d0. 方法可将其设置为 false ，调用 *note
wait(): d7f. 方法将进入阻塞直到标识为 true 。

 -- 類別: threading.Event

     实现事件对象的类。事件对象管理一个内部标识，调用 *note set(): 24cf.
     方法可将其设置为true。调用 *note clear(): 24d0. 方法可将其设置为
     false 。调用 *note wait(): d7f. 方法将进入阻塞直到标识为true。这个
     标识初始时为 false 。

     3.3 版更變: 从工厂函数变为类。

      -- 成員函式: is_set ()

          当且仅当内部标识为 true 时返回 ‘True’ 。

      -- 成員函式: set ()

          将内部标识设置为 true 。所有正在等待这个事件的线程将被唤醒。当
          标识为 true 时，调用 *note wait(): d7f. 方法的线程不会被被阻塞
          。

      -- 成員函式: clear ()

          将内部标识设置为 false 。之后调用 *note wait(): d7f. 方法的线
          程将会被阻塞，直到调用 *note set(): 24cf. 方法将内部标识再次设
          置为 true 。

      -- 成員函式: wait (timeout=None)

          阻塞线程直到内部变量为 true 。如果调用时内部标识为 true，将立
          即返回。否则将阻塞线程，直到调用 *note set(): 24cf. 方法将标识
          设置为 true 或者发生可选的超时。

          当提供了timeout参数且不是 ‘None’ 时，它应该是一个浮点数，代表
          操作的超时时间，以秒为单位（可以为小数）。

          当且仅当内部旗标在等待调用之前或者等待开始之后被设为真值时此方
          法将返回 ‘True’，也就是说，它将总是返回 ‘True’ 除非设定了超时
          且操作发生了超时。

          3.1 版更變: 很明显，方法总是返回 ‘None’。


File: python.info,  Node: 定时器对象,  Next: 栅栏对象,  Prev: 事件对象,  Up: threading --- 基于线程的并行

5.17.1.9 定时器对象
...................

此类表示一个操作应该在等待一定的时间之后运行 — 相当于一个定时器。 *note
Timer: b86. 类是 *note Thread: 21a. 类的子类，因此可以像一个自定义线程一
样工作。

与线程一样，通过调用 ‘start()’ 方法启动定时器。而 *note cancel(): 24d4.
方法可以停止计时器（在计时结束前）， 定时器在执行其操作之前等待的时间间
隔可能与用户指定的时间间隔不完全相同。

例如:

     def hello():
         print("hello, world")

     t = Timer(30.0, hello)
     t.start()  # after 30 seconds, "hello, world" will be printed

 -- 類別: threading.Timer (interval, function, args=None, kwargs=None)

     创建一个定时器，在经过 `interval' 秒的间隔事件后，将会用参数 `args'
     和关键字参数 `kwargs' 调用 `function'。如果 `args' 为 ‘None’ （默认
     值），则会使用一个空列表。如果 `kwargs' 为 ‘None’ （默认值），则会
     使用一个空字典。

     3.3 版更變: 从工厂函数变为类。

      -- 成員函式: cancel ()

          停止定时器并取消执行计时器将要执行的操作。仅当计时器仍处于等待
          状态时有效。


File: python.info,  Node: 栅栏对象,  Next: 在 with 语句中使用锁、条件和信号量,  Prev: 定时器对象,  Up: threading --- 基于线程的并行

5.17.1.10 栅栏对象
..................

3.2 版新加入.

栅栏类提供一个简单的同步原语，用于应对固定数量的线程需要彼此相互等待的情
况。线程调用 *note wait(): 24d6. 方法后将阻塞，直到所有线程都调用了
*note wait(): 24d6. 方法。此时所有线程将被同时释放。

栅栏对象可以被多次使用，但进程的数量不能改变。

这是一个使用简便的方法实现客户端进程与服务端进程同步的例子：

     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)

 -- 類別: threading.Barrier (parties, action=None, timeout=None)

     创建一个需要 `parties' 个线程的栅栏对象。如果提供了可调用的
     `action' 参数，它会在所有线程被释放时在其中一个线程中自动调用。
     `timeout' 是默认的超时时间，如果没有在 *note wait(): 24d6. 方法中指
     定超时时间的话。

      -- 成員函式: wait (timeout=None)

          冲出栅栏。当栅栏中所有线程都已经调用了这个函数，它们将同时被释
          放。如果提供了 `timeout' 参数，这里的 `timeout' 参数优先于创建
          栅栏对象时提供的 `timeout' 参数。

          函数返回值是一个整数，取值范围在0到 `parties' – 1，在每个线程
          中的返回值不相同。可用于从所有线程中选择唯一的一个线程执行一些
          特别的工作。例如：

               i = barrier.wait()
               if i == 0:
                   # Only one thread needs to print this
                   print("passed the barrier")

          如果创建栅栏对象时在构造函数中提供了 `action' 参数，它将在其中
          一个线程释放前被调用。如果此调用引发了异常，栅栏对象将进入损坏
          态。

          如果发生了超时，栅栏对象将进入破损态。

          如果栅栏对象进入破损态，或重置栅栏时仍有线程等待释放，将会引发
          *note BrokenBarrierError: c33. 异常。

      -- 成員函式: reset ()

          重置栅栏为默认的初始态。如果栅栏中仍有线程等待释放，这些线程将
          会收到 *note BrokenBarrierError: c33. 异常。

          请注意使用此函数时，如果存在状态未知的其他线程，则可能需要执行
          外部同步。 如果栅栏已损坏则最好将其废弃并新建一个。

      -- 成員函式: abort ()

          使栅栏处于损坏状态。 这将导致任何现有和未来对 *note wait():
          24d6. 的调用失败并引发 *note BrokenBarrierError: c33.。 例如可
          以在需要中止某个线程时使用此方法，以避免应用程序的死锁。

          更好的方式是：创建栅栏时提供一个合理的超时时间，来自动避免某个
          线程出错。

      -- 屬性: parties

          冲出栅栏所需要的线程数量。

      -- 屬性: n_waiting

          当前时刻正在栅栏中阻塞的线程数量。

      -- 屬性: broken

          一个布尔值，值为 ‘True’ 表明栅栏为破损态。

 -- 例外: threading.BrokenBarrierError

     异常类，是 *note RuntimeError: 3dc. 异常的子类，在 *note Barrier:
     c31. 对象重置时仍有线程阻塞时和对象进入破损态时被引发。


File: python.info,  Node: 在 with 语句中使用锁、条件和信号量,  Prev: 栅栏对象,  Up: threading --- 基于线程的并行

5.17.1.11 在 ‘with’ 语句中使用锁、条件和信号量
..............................................

这个模块提供的带有 ‘acquire()’ 和 ‘release()’ 方法的对象，可以被用作
*note with: 7da. 语句的上下文管理器。当进入语句块时 ‘acquire()’ 方法会被
调用，退出语句块时 ‘release()’ 会被调用。因此，以下片段:

     with some_lock:
         # do something...

相当于:

     some_lock.acquire()
     try:
         # do something...
     finally:
         some_lock.release()

现在 *note Lock: 24bc. 、 *note RLock: cba. 、 *note Condition: b82. 、
*note Semaphore: b83. 和 *note BoundedSemaphore: b84. 对象可以用作 *note
with: 7da. 语句的上下文管理器。


File: python.info,  Node: multiprocessing --- 基于进程的并行,  Next: multiprocessing shared_memory --- 可从进程直接访问的共享内存,  Prev: threading --- 基于线程的并行,  Up: 并发执行

5.17.2 ‘multiprocessing’ — 基于进程的并行
-----------------------------------------

`源代码' Lib/multiprocessing/(1)

__________________________________________________________________

* Menu:

* 簡介: 簡介<8>.
* 参考::
* 编程指导::
* 示例: 示例<17>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/multiprocessing/


File: python.info,  Node: 簡介<8>,  Next: 参考,  Up: multiprocessing --- 基于进程的并行

5.17.2.1 簡介
.............

*note multiprocessing: b7. 是一个支持使用与 *note threading: 10b. 模块类
似的 API 来产生进程的包。 *note multiprocessing: b7. 包同时提供了本地和
远程并发操作，通过使用子进程而非线程有效地绕过了 *note 全局解释器锁:
5ff.。 因此，*note multiprocessing: b7. 模块允许程序员充分利用给定机器上
的多个处理器。 它在 Unix 和 Windows 上均可运行。

*note multiprocessing: b7. 模块还引入了在 *note threading: 10b. 模块中没
有的API。一个主要的例子就是 *note Pool: 966. 对象，它提供了一种快捷的方
法，赋予函数并行化处理一系列输入值的能力，可以将输入数据分配给不同进程处
理（数据并行）。下面的例子演示了在模块中定义此类函数的常见做法，以便子进
程可以成功导入该模块。这个数据并行的基本例子使用了 *note Pool: 966. ，

     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]))

将在标准输出中打印

     [1, 4, 9]

* Menu:

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


File: python.info,  Node: Process 类,  Next: 上下文和启动方法,  Up: 簡介<8>

5.17.2.2 ‘Process’ 类
.....................

在 *note multiprocessing: b7. 中，通过创建一个 *note Process: 4b8. 对象
然后调用它的 ‘start()’ 方法来生成进程。 *note Process: 4b8. 和 *note
threading.Thread: 21a. API 相同。 一个简单的多进程程序示例是:

     from multiprocessing import Process

     def f(name):
         print('hello', name)

     if __name__ == '__main__':
         p = Process(target=f, args=('bob',))
         p.start()
         p.join()

要显示所涉及的各个进程ID，这是一个扩展示例:

     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()

关于为什么 ‘if __name__ == '__main__'’ 部分是必需的解释，请参见 *note
编程指导: 24e1.。


File: python.info,  Node: 上下文和启动方法,  Next: 在进程之间交换对象,  Prev: Process 类,  Up: 簡介<8>

5.17.2.3 上下文和启动方法
.........................

根据不同的平台， *note multiprocessing: b7. 支持三种启动进程的方法。这些
`启动方法' 有

     `spawn'

          父进程会启动一个全新的 python 解释器进程。 子进程将只继承那些
          运行进程对象的 *note run(): 24e3. 方法所必需的资源。 特别地，
          来自父进程的非必需文件描述符和句柄将不会被继承。 使用此方法启
          动进程相比使用 `fork' 或 `forkserver' 要慢上许多。

          可在Unix和Windows上使用。 Windows上的默认设置。

     `fork'

          父进程使用 *note os.fork(): a42. 来产生 Python 解释器分叉。子
          进程在开始时实际上与父进程相同。父进程的所有资源都由子进程继承
          。请注意，安全分叉多线程进程是棘手的。

          只存在于Unix。Unix中的默认值。

     `forkserver'

          程序启动并选择* forkserver * 启动方法时，将启动服务器进程。从
          那时起，每当需要一个新进程时，父进程就会连接到服务器并请求它分
          叉一个新进程。分叉服务器进程是单线程的，因此使用 *note
          os.fork(): a42. 是安全的。没有不必要的资源被继承。

          可在Unix平台上使用，支持通过Unix管道传递文件描述符。

3.8 版更變: 对于 macOS，`spawn' 启动方式是默认方式。 因为 `fork' 可能导
致subprocess崩溃，被认为是不安全的，查看 bpo-33725(1) 。

3.4 版更變: 在所有unix平台上添加支持了 `spawn' ，并且为一些unix平台添加
了 `forkserver' 。在Windows上子进程不再继承所有可继承的父进程句柄。

在 Unix 上通过 `spawn' 和 `forkserver' 方式启动多进程会同时启动一个 `资
源追踪' 进程，负责追踪当前程序的进程产生的、并且不再被使用的命名系统资源
(如命名信号量以及 *note SharedMemory: 24e4. 对象)。当所有进程退出后，资
源追踪会负责释放这些仍被追踪的的对象。通常情况下是不会有这种对象的，但是
假如一个子进程被某个信号杀死，就可能存在这一类资源的“泄露”情况。（泄露的
信号量以及共享内存不会被释放，直到下一次系统重启，对于这两类资源来说，这
是一个比较大的问题，因为操作系统允许的命名信号量的数量是有限的，而共享内
存也会占据主内存的一片空间）

要选择一个启动方法，你应该在主模块的 ‘if __name__ == '__main__'’ 子句中
调用 *note set_start_method(): 964. 。例如：

     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()

在程序中 *note set_start_method(): 964. 不应该被多次调用。

或者，你可以使用 *note get_context(): 965. 来获取上下文对象。上下文对象
与 multiprocessing 模块具有相同的API，并允许在同一程序中使用多种启动方法
。:

     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()

请注意，对象在不同上下文创建的进程间可能并不兼容。 特别是，使用 `fork' 上
下文创建的锁不能传递给使用 `spawn' 或 `forkserver' 启动方法启动的进程。

想要使用特定启动方法的库应该使用 *note get_context(): 965. 以避免干扰库
用户的选择。

     警告: ‘'spawn'’ 和 ‘'forkserver'’ 启动方法当前不能在Unix上和“冻结的
     ”可执行内容一同使用（例如，有类似 `PyInstaller' 和 `cx_Freeze' 的包
     产生的二进制文件）。 ‘'fork'’ 启动方法可以使用。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33725


File: python.info,  Node: 在进程之间交换对象,  Next: 进程间同步,  Prev: 上下文和启动方法,  Up: 簡介<8>

5.17.2.4 在进程之间交换对象
...........................

*note multiprocessing: b7. 支持进程之间的两种通信通道：

`队列'

     *note Queue: 24e6. 类是一个近似 *note queue.Queue: dde. 的克隆。 例
     如:

          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()

     队列是线程和进程安全的。

`管道'

     *note Pipe(): 24e7. 函数返回一个由管道连接的连接对象，默认情况下是
     双工（双向）。例如:

          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()

     返回的两个连接对象 *note Pipe(): 24e7. 表示管道的两端。每个连接对象
     都有 ‘send()’ 和 ‘recv()’ 方法（相互之间的）。请注意，如果两个进程
     （或线程）同时尝试读取或写入管道的 `同一' 端，则管道中的数据可能会
     损坏。当然，在不同进程中同时使用管道的不同端的情况下不存在损坏的风
     险。


File: python.info,  Node: 进程间同步,  Next: 进程间共享状态,  Prev: 在进程之间交换对象,  Up: 簡介<8>

5.17.2.5 进程间同步
...................

对于所有在 *note threading: 10b. 存在的同步原语，*note multiprocessing:
b7. 中都有类似的等价物。例如，可以使用锁来确保一次只有一个进程打印到标准
输出:

     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()

不使用锁的情况下，来自于多进程的输出很容易产生混淆。


File: python.info,  Node: 进程间共享状态,  Next: 使用工作进程,  Prev: 进程间同步,  Up: 簡介<8>

5.17.2.6 进程间共享状态
.......................

如上所述，在进行并发编程时，通常最好尽量避免使用共享状态。使用多个进程时
尤其如此。

但是，如果你真的需要使用一些共享数据，那么 *note multiprocessing: b7. 提
供了两种方法。

`共享内存'

     可以使用 *note Value: 24ea. 或 *note Array: 24eb. 将数据存储在共享
     内存映射中。例如，以下代码:

          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[:])

     将打印

          3.1415927
          [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]

     创建 ‘num’ 和 ‘arr’ 时使用的 ‘'d'’ 和 ‘'i'’ 参数是 *note array: 6.
     模块使用的类型的 typecode ： ‘'d'’ 表示双精度浮点数， ‘'i'’ 表示有
     符号整数。这些共享对象将是进程和线程安全的。

     为了更灵活地使用共享内存，可以使用 *note
     multiprocessing.sharedctypes: bd. 模块，该模块支持创建从共享内存分
     配的任意ctypes对象。

`服务进程'

     由 ‘Manager()’ 返回的管理器对象控制一个服务进程，该进程保存Python对
     象并允许其他进程使用代理操作它们。

     ‘Manager()’ 返回的管理器支持类型： *note list: 1f8. 、 *note dict:
     164. 、 *note Namespace: 24ec. 、 *note Lock: 24ed. 、 *note RLock:
     24ee. 、 *note Semaphore: 24ef. 、 *note BoundedSemaphore: 24f0. 、
     *note Condition: 24f1. 、 *note Event: 24f2. 、 *note Barrier:
     24f3. 、 *note Queue: 24e6. 、 *note Value: 24ea. 和 *note Array:
     24eb. 。例如

          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)

     将打印

          {0.25: None, 1: '1', '2': 2}
          [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

     使用服务进程的管理器比使用共享内存对象更灵活，因为它们可以支持任意
     对象类型。此外，单个管理器可以通过网络由不同计算机上的进程共享。但
     是，它们比使用共享内存慢。


File: python.info,  Node: 使用工作进程,  Prev: 进程间共享状态,  Up: 簡介<8>

5.17.2.7 使用工作进程
.....................

*note Pool: 966. 类表示一个工作进程池。它具有允许以几种不同方式将任务分
配到工作进程的方法。

例如:

     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")

请注意，进程池的方法只能由创建它的进程使用。

     備註: 这个包中的功能要求子进程可以导入 ‘__main__’ 模块。虽然这在
     *note 编程指导: 24e1. 中有描述，但还是需要提前说明一下。这意味着一
     些示例在交互式解释器中不起作用，比如 *note
     multiprocessing.pool.Pool: 966. 示例。例如:

          >>> 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'

     （如果尝试执行上面的代码，它会以一种半随机的方式将三个完整的堆栈内
     容交替输出，然后你只能以某种方式停止父进程。)


File: python.info,  Node: 参考,  Next: 编程指导,  Prev: 簡介<8>,  Up: multiprocessing --- 基于进程的并行

5.17.2.8 参考
.............

*note multiprocessing: b7. 包主要复制了 *note threading: 10b. 模块的
API。

* Menu:

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


File: python.info,  Node: Process 和异常,  Next: 管道和队列,  Up: 参考

5.17.2.9 ‘Process’ 和异常
.........................

 -- 類別: multiprocessing.Process (group=None, target=None, name=None,
          args=(), kwargs={}, *, daemon=None)

     进程对象表示在单独进程中运行的活动。 *note Process: 4b8. 类拥有和
     *note threading.Thread: 21a. 等价的大部分方法。

     应始终使用关键字参数调用构造函数。 `group' 应该始终是 ‘None’ ；它仅
     用于兼容 *note threading.Thread: 21a. 。 `target' 是由 *note run():
     24e3. 方法调用的可调用对象。它默认为 ‘None’ ，意味着什么都没有被调
     用。 `name' 是进程名称（有关详细信息，请参阅 *note name: 24f7. ）。
     `args' 是目标调用的参数元组。 `kwargs' 是目标调用的关键字参数字典。
     如果提供，则键参数 `daemon' 将进程 *note daemon: 24f8. 标志设置为
     ‘True’ 或 ‘False’ 。如果是 ‘None’ （默认值），则该标志将从创建的进
     程继承。

     默认情况下，不会将任何参数传递给 `target' 。

     如果子类重写构造函数，它必须确保它在对进程执行任何其他操作之前调用
     基类构造函数（ ‘Process.__init__()’ ）。

     3.3 版更變: 加入 `daemon' 参数。

      -- 成員函式: run ()

          表示进程活动的方法。

          你可以在子类中重载此方法。标准 *note run(): 24e3. 方法调用传递
          给对象构造函数的可调用对象作为目标参数（如果有），分别从
          `args' 和 `kwargs' 参数中获取顺序和关键字参数。

      -- 成員函式: start ()

          启动进程活动。

          这个方法每个进程对象最多只能调用一次。它会将对象的 *note
          run(): 24e3. 方法安排在一个单独的进程中调用。

      -- 成員函式: join ([timeout])

          如果可选参数 `timeout' 是 ‘None’ （默认值），则该方法将阻塞，
          直到调用 *note join(): 24fa. 方法的进程终止。如果 `timeout' 是
          一个正数，它最多会阻塞 `timeout' 秒。请注意，如果进程终止或方
          法超时，则该方法返回 ‘None’ 。检查进程的 *note exitcode: 24fb.
          以确定它是否终止。

          一个进程可以被 join 多次。

          进程无法join自身，因为这会导致死锁。尝试在启动进程之前join进程
          是错误的。

      -- 屬性: name

          进程的名称。该名称是一个字符串，仅用于识别目的。它没有语义。可
          以为多个进程指定相同的名称。

          初始名称由构造器设定。 如果没有为构造器提供显式名称，则会构造
          一个形式为 ’Process-N[1]:N[2]:...:N[k]’ 的名称，其中每个 N[k]
          是其父亲的第 N 个孩子。

      -- 成員函式: is_alive ()

          返回进程是否还活着。

          粗略地说，从 *note start(): 24f9. 方法返回到子进程终止之前，进
          程对象仍处于活动状态。

      -- 屬性: daemon

          进程的守护标志，一个布尔值。这必须在 *note start(): 24f9. 被调
          用之前设置。

          初始值继承自创建进程。

          当进程退出时，它会尝试终止其所有守护进程子进程。

          请注意，不允许在守护进程中创建子进程。这是因为当守护进程由于父
          进程退出而中断时，其子进程会变成孤儿进程。 另外，这些 `不是'
          Unix 守护进程或服务，它们是正常进程，如果非守护进程已经退出，
          它们将被终止（并且不被合并）。

     除了 *note threading.Thread: 21a. API ，*note Process: 4b8. 对象还
     支持以下属性和方法：

      -- 屬性: pid

          返回进程ID。在生成该进程之前，这将是 ‘None’ 。

      -- 屬性: exitcode

          子进程的退出代码。如果进程尚未终止，这将是 ‘None’ 。负值 `-N'
          表示子进程被信号 `N' 终止。

      -- 屬性: authkey

          进程的身份验证密钥（字节字符串）。

          当 *note multiprocessing: b7. 初始化时，主进程使用 *note
          os.urandom(): 5cb. 分配一个随机字符串。

          当创建 *note Process: 4b8. 对象时，它将继承其父进程的身份验证
          密钥，尽管可以通过将 *note authkey: 24fe. 设置为另一个字节字符
          串来更改。

          参见 *note 认证密码: 24ff. 。

      -- 屬性: sentinel

          系统对象的数字句柄，当进程结束时将变为 "ready" 。

          如果要使用 *note multiprocessing.connection.wait(): b01. 一次
          等待多个事件，可以使用此值。否则调用 *note join(): 24fa. 更简
          单。

          在Windows上，这是一个操作系统句柄，可以与
          ‘WaitForSingleObject’ 和 ‘WaitForMultipleObjects’ 系列API调用
          一起使用。在Unix上，这是一个文件描述符，可以使用来自 *note
          select: e5. 模块的原语。

          3.3 版新加入.

      -- 成員函式: terminate ()

          终止进程。 在Unix上，这是使用 ‘SIGTERM’ 信号完成的；在
          Windows上使用 ‘TerminateProcess()’ 。 请注意，不会执行退出处理
          程序和finally子句等。

          请注意，进程的后代进程将不会被终止 —— 它们将简单地变成孤立的。

               警告: 如果在关联进程使用管道或队列时使用此方法，则管道或
               队列可能会损坏，并可能无法被其他进程使用。类似地，如果进
               程已获得锁或信号量等，则终止它可能导致其他进程死锁。

      -- 成員函式: kill ()

          与 *note terminate(): 2500. 相同，但在Unix上使用 ‘SIGKILL’ 信
          号。

          3.7 版新加入.

      -- 成員函式: close ()

          关闭 *note Process: 4b8. 对象，释放与之关联的所有资源。如果底
          层进程仍在运行，则会引发 *note ValueError: 16d. 。一旦 *note
          close(): 4b6. 成功返回， *note Process: 4b8. 对象的大多数其他
          方法和属性将引发 *note ValueError: 16d. 。

          3.7 版新加入.

     注意 *note start(): 24f9. 、 *note join(): 24fa. 、 *note
     is_alive(): 24fc. 、 *note terminate(): 2500. 和 *note exitcode:
     24fb. 方法只能由创建进程对象的进程调用。

     *note Process: 4b8. 一些方法的示例用法：

           >>> 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

 -- 例外: multiprocessing.ProcessError

     所有 *note multiprocessing: b7. 异常的基类。

 -- 例外: multiprocessing.BufferTooShort

     当提供的缓冲区对象太小而无法读取消息时，
     ‘Connection.recv_bytes_into()’ 引发的异常。

     如果 ‘e’ 是一个 *note BufferTooShort: 2502. 实例，那么 ‘e.args[0]’
     将把消息作为字节字符串给出。

 -- 例外: multiprocessing.AuthenticationError

     出现身份验证错误时引发。

 -- 例外: multiprocessing.TimeoutError

     有超时的方法超时时引发。


File: python.info,  Node: 管道和队列,  Next: 杂项<3>,  Prev: Process 和异常,  Up: 参考

5.17.2.10 管道和队列
....................

使用多进程时，一般使用消息机制实现进程间通信，尽可能避免使用同步原语，例
如锁。

消息机制包含： *note Pipe(): 24e7. (可以用于在两个进程间传递消息)，以及
队列(能够在多个生产者和消费者之间通信)。

*note Queue: 24e6, *note SimpleQueue: 1c3. 以及 *note JoinableQueue:
2506. 都是多生产者，多消费者，并且实现了 FIFO 的队列类型，其表现与标准库
中的 *note queue.Queue: dde. 类相似。 不同之处在于 *note Queue: 24e6. 缺
少标准库的 *note queue.Queue: dde. 从 Python 2.5 开始引入的 *note
task_done(): 2507. 和 *note join(): 2508. 方法。

如果你使用了 *note JoinableQueue: 2506. ，那么你 `必须' 对每个已经移出队
列的任务调用 *note JoinableQueue.task_done(): 2509.。 不然的话用于统计未
完成任务的信号量最终会溢出并抛出异常。

另外还可以通过使用一个管理器对象创建一个共享队列，详见 *note 管理器:
250a. 。

     備註: *note multiprocessing: b7. 使用了普通的 *note queue.Empty:
     250b. 和 *note queue.Full: 250c. 异常去表示超时。 你需要从 *note
     queue: da. 中导入它们，因为它们并不在 *note multiprocessing: b7. 的
     命名空间中。

     備註: 当一个对象被放入一个队列中时，这个对象首先会被一个后台线程用
     pickle 序列化，并将序列化后的数据通过一个底层管道的管道传递到队列中
     。 这种做法会有点让人惊讶，但一般不会出现什么问题。 如果它们确实妨
     碍了你，你可以使用一个由管理器 *note manager: 250a. 创建的队列替换
     它。

       1. 将一个对象放入一个空队列后，可能需要极小的延迟，队列的方法
          *note empty(): 250d.  才会返回 *note False: 48e. 。而 *note
          get_nowait(): 250e. 可以不抛出 *note queue.Empty: 250b. 直接返
          回。

       2. 如果有多个进程同时将对象放入队列，那么在队列的另一端接受到的对
          象可能是无序的。但是由同一个进程放入的多个对象的顺序在另一端输
          出时总是一样的。

     警告: 如果一个进程在尝试使用 *note Queue: 24e6. 期间被 *note
     Process.terminate(): 2500. 或 *note os.kill(): db9. 调用终止了，那
     么队列中的数据很可能被破坏。 这可能导致其他进程在尝试使用该队列时发
     生异常。

     警告: 正如刚才提到的，如果一个子进程将一些对象放进队列中 (并且它没
     有用 *note JoinableQueue.cancel_join_thread: 250f. 方法)，那么这个
     进程在所有缓冲区的对象被刷新进管道之前，是不会终止的。

     这意味着，除非你确定所有放入队列中的对象都已经被消费了，否则如果你
     试图等待这个进程，你可能会陷入死锁中。相似地，如果该子进程不是后台
     进程，那么父进程可能在试图等待所有非后台进程退出时挂起。

     注意用管理器创建的队列不存在这个问题，详见 *note 编程指导: 24e1. 。

该 *note 示例: 2510. 展示了如何使用队列实现进程间通信。

 -- 函式: multiprocessing.Pipe ([duplex])

     返回一对 *note Connection: 2511. 对象 ‘(conn1, conn2)’ ， 分别表示
     管道的两端。

     如果 `duplex' 被置为 ‘True’ (默认值)，那么该管道是双向的。如果
     `duplex' 被置为 ‘False’ ，那么该管道是单向的，即 ‘conn1’ 只能用于接
     收消息，而 ‘conn2’ 仅能用于发送消息。

 -- 類別: multiprocessing.Queue ([maxsize])

     返回一个使用一个管道和少量锁和信号量实现的共享队列实例。当一个进程
     将一个对象放进队列中时，一个写入线程会启动并将对象从缓冲区写入管道
     中。

     一旦超时，将抛出标准库 *note queue: da. 模块中常见的异常 *note
     queue.Empty: 250b. 和 *note queue.Full: 250c.。

     除了 *note task_done(): 2507. 和 *note join(): 2508. 之外，*note
     Queue: 24e6.  实现了标准库类 *note queue.Queue: dde. 中所有的方法。

      -- 成員函式: qsize ()

          返回队列的大致长度。由于多线程或者多进程的上下文，这个数字是不
          可靠的。

          Note that this may raise *note NotImplementedError: 704. on
          Unix platforms like macOS where ‘sem_getvalue()’ is not
          implemented.

      -- 成員函式: empty ()

          如果队列是空的，返回 ‘True’ ，反之返回 ‘False’ 。 由于多线程或
          多进程的环境，该状态是不可靠的。

      -- 成員函式: full ()

          如果队列是满的，返回 ‘True’ ，反之返回 ‘False’ 。 由于多线程或
          多进程的环境，该状态是不可靠的。

      -- 成員函式: put (obj[, block[, timeout]])

          将 obj 放入队列。如果可选参数 `block' 是 ‘True’ (默认值) 而且
          `timeout' 是 ‘None’ (默认值), 将会阻塞当前进程，直到有空的缓冲
          槽。如果 `timeout' 是正数，将会在阻塞了最多 `timeout' 秒之后还
          是没有可用的缓冲槽时抛出 *note queue.Full: 250c.  异常。反之
          (`block' 是 ‘False’ 时)，仅当有可用缓冲槽时才放入对象，否则抛
          出 *note queue.Full: 250c. 异常 (在这种情形下 `timeout' 参数会
          被忽略)。

          3.8 版更變: 如果队列已经关闭，会抛出 *note ValueError: 16d. 而
          不是 *note AssertionError: 240. 。

      -- 成員函式: put_nowait (obj)

          相当于 ‘put(obj, False)’。

      -- 成員函式: get ([block[, timeout]])

          从队列中取出并返回对象。如果可选参数 `block' 是 ‘True’ (默认值
          ) 而且 `timeout' 是 ‘None’ (默认值), 将会阻塞当前进程，直到队
          列中出现可用的对象。如果 `timeout' 是正数，将会在阻塞了最多
          `timeout' 秒之后还是没有可用的对象时抛出 *note queue.Empty:
          250b. 异常。反之 (`block' 是 ‘False’ 时)，仅当有可用对象能够取
          出时返回，否则抛出 *note queue.Empty: 250b. 异常 (在这种情形下
          `timeout' 参数会被忽略)。

          3.8 版更變: 如果队列已经关闭，会抛出 *note ValueError: 16d. 而
          不是 *note OSError: 304. 。

      -- 成員函式: get_nowait ()

          相当于 ‘get(False)’。

     *note multiprocessing.Queue: 24e6. 类有一些在 *note queue.Queue:
     dde. 类中没有出现的方法。这些方法在大多数情形下并不是必须的。

      -- 成員函式: close ()

          指示当前进程将不会再往队列中放入对象。一旦所有缓冲区中的数据被
          写入管道之后，后台的线程会退出。这个方法在队列被gc回收时会自动
          调用。

      -- 成員函式: join_thread ()

          等待后台线程。这个方法仅在调用了 *note close(): 2515. 方法之后
          可用。这会阻塞当前进程，直到后台线程退出，确保所有缓冲区中的数
          据都被写入管道中。

          默认情况下，如果一个不是队列创建者的进程试图退出，它会尝试等待
          这个队列的后台线程。这个进程可以使用 *note
          cancel_join_thread(): 250f. 让 *note join_thread(): 2516. 方法
          什么都不做直接跳过。

      -- 成員函式: cancel_join_thread ()

          防止 *note join_thread(): 2516. 方法阻塞当前进程。具体而言，这
          防止进程退出时自动等待后台线程退出。详见 *note join_thread():
          2516.。

          可能这个方法称为”‘allow_exit_without_flush()’“ 会更好。这有可
          能会导致正在排队进入队列的数据丢失，大多数情况下你不需要用到这
          个方法，仅当你不关心底层管道中可能丢失的数据，只是希望进程能够
          马上退出时使用。

          備註: 该类的功能依赖于宿主操作系统具有可用的共享信号量实现。否
          则该类将被禁用，任何试图实例化一个 *note Queue: 24e6. 对象的操
          作都会抛出 *note ImportError: 16c. 异常，更多信息详见
          bpo-3770(1) 。后续说明的任何专用队列对象亦如此。

 -- 類別: multiprocessing.SimpleQueue

     这是一个简化的 *note Queue: 24e6. 类的实现，很像带锁的 *note Pipe:
     24e7. 。

      -- 成員函式: close ()

          关闭队列：释放内部资源。

          队列在被关闭后就不可再被使用。 例如不可再调用 *note get():
          2517, *note put(): 2518. 和 *note empty(): 2519. 等方法。

          3.9 版新加入.

      -- 成員函式: empty ()

          如果队列为空返回 ‘True’ ，否则返回 ‘False’ 。

      -- 成員函式: get ()

          从队列中移出并返回一个对象。

      -- 成員函式: put (item)

          将 `item' 放入队列。

 -- 類別: multiprocessing.JoinableQueue ([maxsize])

     *note JoinableQueue: 2506. 类是 *note Queue: 24e6. 的子类，额外添加
     了 *note task_done(): 2509. 和 *note join(): 251a. 方法。

      -- 成員函式: task_done ()

          指出之前进入队列的任务已经完成。由队列的消费者进程使用。对于每
          次调用 *note get(): 1164. 获取的任务，执行完成后调用 *note
          task_done(): 2509. 告诉队列该任务已经处理完成。

          如果 *note join(): 2508. 方法正在阻塞之中，该方法会在所有对象
          都被处理完的时候返回 (即对之前使用 *note put(): 1163. 放进队列
          中的所有对象都已经返回了对应的 *note task_done(): 2509. ) 。

          如果被调用的次数多于放入队列中的项目数量，将引发 *note
          ValueError: 16d. 异常 。

      -- 成員函式: join ()

          阻塞至队列中所有的元素都被接收和处理完毕。

          当条目添加到队列的时候，未完成任务的计数就会增加。每当消费者进
          程调用 *note task_done(): 2509. 表示这个条目已经被回收，该条目
          所有工作已经完成，未完成计数就会减少。当未完成计数降到零的时候
          ， ‘join()’ 阻塞被解除。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue3770


File: python.info,  Node: 杂项<3>,  Next: 连接（Connection）对象,  Prev: 管道和队列,  Up: 参考

5.17.2.11 杂项
..............

 -- 函式: multiprocessing.active_children ()

     返回当前进程存活的子进程的列表。

     调用该方法有“等待”已经结束的进程的副作用。

 -- 函式: multiprocessing.cpu_count ()

     返回系统的CPU数量。

     该数量不同于当前进程可以使用的CPU数量。可用的CPU数量可以由
     ‘len(os.sched_getaffinity(0))’ 方法获得。

     When the number of CPUs cannot be determined a *note
     NotImplementedError: 704. is raised.

     也參考
     ......

     *note os.cpu_count(): 96a.

 -- 函式: multiprocessing.current_process ()

     返回与当前进程相对应的 *note Process: 4b8. 对象。

     和 *note threading.current_thread(): 24aa. 相同。

 -- 函式: multiprocessing.parent_process ()

     返回父进程 *note Process: 4b8.  对象，和父进程调用 *note
     current_process(): 251d. 返回的对象一样。如果一个进程已经是主进程，
     ‘parent_process’ 会返回 ‘None’.

     3.8 版新加入.

 -- 函式: multiprocessing.freeze_support ()

     为使用了 *note multiprocessing: b7.  的程序，提供冻结以产生 Windows
     可执行文件的支持。(在 `py2exe', `PyInstaller' 和 `cx_Freeze' 上测试
     通过)

     需要在 main 模块的 ‘if __name__ == '__main__'’ 该行之后马上调用该函
     数。例如：

          from multiprocessing import Process, freeze_support

          def f():
              print('hello world!')

          if __name__ == '__main__':
              freeze_support()
              Process(target=f).start()

     如果没有调用 ‘freeze_support()’ 在尝试运行被冻结的可执行文件时会抛
     出 *note RuntimeError: 3dc. 异常。

     对 ‘freeze_support()’ 的调用在非 Windows 平台上是无效的。如果该模块
     在 Windows 平台的 Python 解释器中正常运行 (该程序没有被冻结)， 调用
     ‘‘freeze_support()‘‘ 也是无效的。

 -- 函式: multiprocessing.get_all_start_methods ()

     返回支持的启动方法的列表，该列表的首项即为默认选项。可能的启动方法
     有 ‘'fork'’ ， ‘'spawn'’ 和‘‘’forkserver’‘‘ 。在 Windows 中，只有
     ‘'spawn'’ 是可用的。 Unix 平台总是支持 ‘'fork'’ 和 ‘'spawn'’ ，且
     ‘'fork'’ 是默认值。

     3.4 版新加入.

 -- 函式: multiprocessing.get_context (method=None)

     返回一个 Context 对象。该对象具有和 *note multiprocessing: b7. 模块
     相同的API。

     如果 `method' 设置成 ‘None’ 那么将返回默认上下文对象。否则
     `method'  应该是 ‘'fork'’, ‘'spawn'’, ‘'forkserver'’ 。 如果指定的
     启动方法不存在，将抛出 *note ValueError: 16d.  异常。

     3.4 版新加入.

 -- 函式: multiprocessing.get_start_method (allow_none=False)

     返回启动进程时使用的启动方法名。

     如果启动方法已经固定，并且 `allow_none' 被设置成 False ，那么启动方
     法将被固定为默认的启动方法，并且返回其方法名。如果启动方法没有设定
     ，并且 `allow_none' 被设置成 True ，那么将返回 ‘None’  。

     The return value can be ‘'fork'’, ‘'spawn'’, ‘'forkserver'’ or
     ‘None’.  ‘'fork'’ is the default on Unix, while ‘'spawn'’ is the
     default on Windows and macOS.

3.8 版更變: 对于 macOS，`spawn' 启动方式是默认方式。 因为 `fork' 可能导
致subprocess崩溃，被认为是不安全的，查看 bpo-33725(1) 。

3.4 版新加入.

 -- 函式: multiprocessing.set_executable ()

     设置在启动子进程时使用的 Python 解释器路径。 ( 默认使用 *note
     sys.executable: 39d. ) 嵌入式编程人员可能需要这样做：

          set_executable(os.path.join(sys.exec_prefix, 'pythonw.exe'))

     以使他们可以创建子进程。

     3.4 版更變: 现在在 Unix 平台上使用 ‘'spawn'’  启动方法时支持调用该
     方法。

 -- 函式: multiprocessing.set_start_method (method)

     设置启动子进程的方法。 `method' 可以是 ‘'fork'’ , ‘'spawn'’ 或者
     ‘'forkserver'’ 。

     注意这最多只能调用一次，并且需要藏在 main 模块中，由 ‘if __name__
     == '__main__'’ 进行保护。

     3.4 版新加入.

     備註: *note multiprocessing: b7. 并没有包含类似 *note
     threading.active_count(): 24a9. , *note threading.enumerate(): f90.
     , *note threading.settrace(): 24ab. , *note threading.setprofile():
     24ac, *note threading.Timer: b86. , 或者 *note threading.local:
     244e. 的方法和类。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue33725


File: python.info,  Node: 连接（Connection）对象,  Next: 同步原语,  Prev: 杂项<3>,  Up: 参考

5.17.2.12 连接（Connection）对象
................................

Connection 对象允许收发可以序列化的对象或字符串。它们可以看作面向消息的
连接套接字。

通常使用 *note Pipe: 24e7. 创建 Connection 对象。详见 ： *note
监听器及客户端: 2522.

 -- 類別: multiprocessing.connection.Connection

      -- 成員函式: send (obj)

          将一个对象发送到连接的另一端，可以用 *note recv(): 2524. 读取
          。

          发送的对象必须是可以序列化的，过大的对象 ( 接近 32MiB+ ，这个
          值取决于操作系统 ) 有可能引发 *note ValueError: 16d.  异常。

      -- 成員函式: recv ()

          返回一个由另一端使用 *note send(): 2523. 发送的对象。该方法会
          一直阻塞直到接收到对象。 如果对端关闭了连接或者没有东西可接收
          ，将抛出 *note EOFError: d34.  异常。

      -- 成員函式: fileno ()

          返回由连接对象使用的描述符或者句柄。

      -- 成員函式: close ()

          关闭连接对象。

          当连接对象被垃圾回收时会自动调用。

      -- 成員函式: poll ([timeout])

          返回连接对象中是否有可以读取的数据。

          如果未指定 `timeout' ，此方法会马上返回。如果 `timeout' 是一个
          数字，则指定了最大阻塞的秒数。如果 `timeout' 是 ‘None’  ，那么
          将一直等待，不会超时。

          注意通过使用 *note multiprocessing.connection.wait(): b01. 可
          以一次轮询多个连接对象。

      -- 成員函式: send_bytes (buffer[, offset[, size]])

          从一个 *note bytes-like object: 6df.  （字节类对象）对象中取出
          字节数组并作为一条完整消息发送。

          如果由 `offset'  给定了在 `buffer' 中读取数据的位置。 如果给定
          了 `size' ，那么将会从缓冲区中读取多个字节。 过大的缓冲区 ( 接
          近 32MiB+ ，此值依赖于操作系统 ) 有可能引发 *note ValueError:
          16d.  异常。

      -- 成員函式: recv_bytes ([maxlength])

          以字符串形式返回一条从连接对象另一端发送过来的字节数据。此方法
          在接收到数据前将一直阻塞。 如果连接对象被对端关闭或者没有数据
          可读取，将抛出 *note EOFError: d34.  异常。

          如果给定了 `maxlength' 并且消息长于 `maxlength' 那么将抛出
          *note OSError: 304. 并且该连接对象将不再可读。

          3.3 版更變: 曾经该函数抛出 *note IOError: a73. ，现在这是
          *note OSError: 304. 的别名。

      -- 成員函式: recv_bytes_into (buffer[, offset])

          将一条完整的字节数据消息读入 `buffer' 中并返回消息的字节数。 此
          方法在接收到数据前将一直阻塞。 如果连接对象被对端关闭或者没有
          数据可读取，将抛出 *note EOFError: d34.  异常。

          `buffer' must be a writable *note bytes-like object: 6df.  If
          `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 `buffer' (in bytes).

          如果缓冲区太小，则将引发 ‘BufferTooShort’  异常，并且完整的消
          息将会存放在异常实例 ‘e’ 的 ‘e.args[0]’ 中。

     3.3 版更變: 现在连接对象自身可以通过 *note Connection.send(): 2523.
     和 *note Connection.recv(): 2524. 在进程之间传递。

     3.3 版新加入: 连接对象现已支持上下文管理协议 – 参见 see *note
     上下文管理器类型: 15c6. 。 *note __enter__(): 1812. 返回连接对象，
     *note __exit__(): 1814. 会调用 *note close(): 2526. 。

例如:

     >>> 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])
     警告: *note Connection.recv(): 2524. 方法会自动解封它收到的数据，除
     非你能够信任发送消息的进程，否则此处可能有安全风险。

     因此， 除非连接对象是由 ‘Pipe()’ 产生的，否则你应该仅在使用了某种认
     证手段之后才使用 *note recv(): 2524. 和 *note send(): 2523. 方法。
     参考 *note 认证密码: 24ff.。

     警告: 如果一个进程在试图读写管道时被终止了，那么管道中的数据很可能
     是不完整的，因为此时可能无法确定消息的边界。


File: python.info,  Node: 同步原语,  Next: 共享 ctypes 对象,  Prev: 连接（Connection）对象,  Up: 参考

5.17.2.13 同步原语
..................

通常来说同步原语在多进程环境中并不像它们在多线程环境中那么必要。参考
*note threading: 10b.  模块的文档。

注意可以使用管理器对象创建同步原语，参考 *note 管理器: 250a. 。

 -- 類別: multiprocessing.Barrier (parties[, action[, timeout]])

     类似 *note threading.Barrier: c31. 的栅栏对象。

     3.3 版新加入.

 -- 類別: multiprocessing.BoundedSemaphore ([value])

     非常类似 *note threading.BoundedSemaphore: b84. 的有界信号量对象。

     一个小小的不同在于，它的 ‘acquire’  方法的第一个参数名是和 *note
     Lock.acquire(): 252d. 一样的 `block' 。

          備註: On macOS, this is indistinguishable from *note
          Semaphore: 24ef. because ‘sem_getvalue()’ is not implemented
          on that platform.

 -- 類別: multiprocessing.Condition ([lock])

     条件变量： *note threading.Condition: b82. 的别名。

     指定的 `lock' 参数应该是 *note multiprocessing: b7. 模块中的 *note
     Lock: 24ed. 或者 *note RLock: 24ee. 对象。

     3.3 版更變: 新增了 *note wait_for(): 24c7.  方法。

 -- 類別: multiprocessing.Event

     A clone of *note threading.Event: b85.

 -- 類別: multiprocessing.Lock

     原始锁（非递归锁）对象，类似于 *note threading.Lock: 24bc. 。一旦一
     个进程或者线程拿到了锁，后续的任何其他进程或线程的其他请求都会被阻
     塞直到锁被释放。任何进程或线程都可以释放锁。除非另有说明，否则
     *note multiprocessing.Lock: 24ed.  用于进程或者线程的概念和行为都和
     *note threading.Lock: 24bc.  一致。

     注意 *note Lock: 24ed. 实际上是一个工厂函数。它返回由默认上下文初始
     化的 ‘multiprocessing.synchronize.Lock’  对象。

     *note Lock: 24ed. supports the *note context manager: 661. protocol
     and thus may be used in *note with: 7da. statements.

      -- 成員函式: acquire (block=True, timeout=None)

          获得锁，阻塞或非阻塞的。

          如果 `block' 参数被设为 ‘True’ ( 默认值 ) ， 对该方法的调用在
          锁处于释放状态之前都会阻塞，然后将锁设置为锁住状态并返回
          ‘True’ 。需要注意的是第一个参数名与 *note
          threading.Lock.acquire(): 85b. 的不同。

          如果 `block' 参数被设置成 ‘False’ ，方法的调用将不会阻塞。 如
          果锁当前处于锁住状态，将返回 ‘False’ ； 否则将锁设置成锁住状态
          ，并返回 ‘True’ 。

          当 `timeout' 是一个正浮点数时，会在等待锁的过程中最多阻塞等待
          `timeout' 秒，当 `timeout' 是负数时，效果和 `timeout' 为0时一
          样，当 `timeout' 是 ‘None’ （默认值）时，等待时间是无限长。需
          要注意的是，对于 `timeout' 参数是负数和 ‘None’ 的情况, 其行为
          与 *note threading.Lock.acquire(): 85b. 是不一样的。当 `block'
          参数 为 ‘False’ 时， `timeout' 并没有实际用处，会直接忽略。否
          则，函数会在拿到锁后返回 ‘True’ 或者 超时没拿到锁后返回
          ‘False’ 。

      -- 成員函式: release ()

          释放锁，可以在任何进程、线程使用，并不限于锁的拥有者。

          当尝试释放一个没有被持有的锁时，会抛出 *note ValueError: 16d.
          异常，除此之外其行为与 *note threading.Lock.release(): 24ba. 一
          样。

 -- 類別: multiprocessing.RLock

     递归锁对象: 类似于 *note threading.RLock: cba. 。递归锁必须由持有线
     程、进程亲自释放。如果某个进程或者线程拿到了递归锁，这个进程或者线
     程可以再次拿到这个锁而不需要等待。但是这个进程或者线程的拿锁操作和
     释放锁操作的次数必须相同。

     注意 *note RLock: 24ee. 是一个工厂函数，调用后返回一个使用默认
     context 初始化的 ‘multiprocessing.synchronize.RLock’ 实例。

     *note RLock: 24ee. 支持 *note context manager: 661.，所以可在 *note
     with: 7da. 语句内使用。

      -- 成員函式: acquire (block=True, timeout=None)

          获得锁，阻塞或非阻塞的。

          当 `block' 参数设置为 ‘True’ 时，会一直阻塞直到锁处于空闲状态
          （没有被任何进程、线程拥有），除非当前进程或线程已经拥有了这把
          锁。然后当前进程/线程会持有这把锁（在锁没有其他持有者的情况下
          ），锁内的递归等级加一，并返回 ‘True’ . 注意， 这个函数第一个
          参数的行为和 *note threading.RLock.acquire(): 85c. 的实现有几
          个不同点，包括参数名本身。

          当 `block' 参数是 ‘False’ , 将不会阻塞，如果此时锁被其他进程或
          者线程持有，当前进程、线程获取锁操作失败，锁的递归等级也不会改
          变，函数返回 ‘False’ , 如果当前锁已经处于释放状态，则当前进程
          、线程则会拿到锁，并且锁内的递归等级加一，函数返回 ‘True’ 。

          `timeout' 参数的使用方法及行为与 *note Lock.acquire(): 252d. 一
          样。但是要注意 `timeout' 的其中一些行为和 *note
          threading.RLock.acquire(): 85c. 中实现的行为是不同的。

      -- 成員函式: release ()

          释放锁，使锁内的递归等级减一。如果释放后锁内的递归等级降低为
          0，则会重置锁的状态为释放状态（即没有被任何进程、线程持有），
          重置后如果有有其他进程和线程在等待这把锁，他们中的一个会获得这
          个锁而继续运行。如果释放后锁内的递归等级还没到达0，则这个锁仍
          将保持未释放状态且当前进程和线程仍然是持有者。

          只有当前进程或线程是锁的持有者时，才允许调用这个方法。如果当前
          进程或线程不是这个锁的拥有者，或者这个锁处于已释放的状态(即没
          有任何拥有者)，调用这个方法会抛出 *note AssertionError: 240. 异
          常。注意这里抛出的异常类型和 *note threading.RLock.release():
          24c0. 中实现的行为不一样。

 -- 類別: multiprocessing.Semaphore ([value])

     一种信号量对象: 类似于 *note threading.Semaphore: b83.

     一个小小的不同在于，它的 ‘acquire’  方法的第一个参数名是和 *note
     Lock.acquire(): 252d. 一样的 `block' 。

     備註: On macOS, ‘sem_timedwait’ is unsupported, so calling
     ‘acquire()’ with a timeout will emulate that function’s behavior
     using a sleeping loop.

     備註: 假如信号 SIGINT 是来自于 ‘Ctrl-C’ ，并且主线程被
     ‘BoundedSemaphore.acquire()’, *note Lock.acquire(): 252d, *note
     RLock.acquire(): 252f, ‘Semaphore.acquire()’, ‘Condition.acquire()’
     或 ‘Condition.wait()’ 阻塞，则调用会立即中断同时抛出 *note
     KeyboardInterrupt: 2cc. 异常。

     这和 *note threading: 10b. 的行为不同，此模块中当执行对应的阻塞调用
     时，SIGINT 会被忽略。

     備註: 这个包的某些功能依赖于宿主机系统的共享信号量的实现，如果系统
     没有这个特性， ‘multiprocessing.synchronize’ 会被禁用，尝试导入这个
     模块会引发 *note ImportError: 16c. 异常，详细信息请查看 bpo-3770(1)
     。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue3770


File: python.info,  Node: 共享 ctypes 对象,  Next: 管理器,  Prev: 同步原语,  Up: 参考

5.17.2.14 共享 ‘ctypes’ 对象
............................

在共享内存上创建可被子进程继承的共享对象时是可行的。

 -- 函式: multiprocessing.Value (typecode_or_type, *args, lock=True)

     返回一个从共享内存上创建的 *note ctypes: 2a. 对象。默认情况下返回的
     对象实际上是经过了同步器包装过的。可以通过 *note Value: 24ea. 的
     `value' 属性访问这个对象本身。

     `typecode_or_type' 指明了返回的对象类型: 它可能是一个 ctypes 类型或
     者 *note array: 6.  模块中每个类型对应的单字符长度的字符串。
     `*args' 会透传给这个类的构造函数。

     如果 `lock' 参数是 ‘True’ （默认值）, 将会新建一个递归锁用于同步对
     于此值的访问操作。 如果 `lock' 是 *note Lock: 24ed. 或者 *note
     RLock: 24ee. 对象，那么这个传入的锁将会用于同步对这个值的访问操作，
     如果 `lock' 是 ‘False’ , 那么对这个对象的访问将没有锁保护，也就是说
     这个变量不是进程安全的。

     诸如 ‘+=’ 这类的操作会引发独立的读操作和写操作，也就是说这类操作符
     并不具有原子性。所以，如果你想让递增共享变量的操作具有原子性，仅仅
     以这样的方式并不能达到要求:

          counter.value += 1

     共享对象内部关联的锁是递归锁(默认情况下就是)的情况下， 你可以采用这
     种方式

          with counter.get_lock():
              counter.value += 1

     注意 `lock' 只能是命名参数。

 -- 函式: multiprocessing.Array (typecode_or_type, size_or_initializer,
          *, lock=True)

     从共享内存中申请并返回一个具有ctypes类型的数组对象。默认情况下返回
     值实际上是被同步器包装过的数组对象。

     `typecode_or_type' 指明了返回的数组中的元素类型: 它可能是一个
     ctypes 类型或者 *note array: 6. 模块中每个类型对应的单字符长度的字
     符串。 如果 `size_or_initializer' 是一个整数，那就会当做数组的长度
     ，并且整个数组的内存会初始化为0。否则，如果 `size_or_initializer' 会
     被当成一个序列用于初始化数组中的每一个元素，并且会根据元素个数自动
     判断数组的长度。

     如果 `lock' 为 ‘True’ (默认值) 则将创建一个新的锁对象用于同步对值的
     访问。 如果 `lock' 为一个 *note Lock: 24ed. 或 *note RLock: 24ee. 对
     象则该对象将被用于同步对值的访问。 如果 `lock' 为 ‘False’ 则对返回
     对象的访问将不会自动得到锁的保护，也就是说它不是“进程安全的”。

     请注意 `lock' 是一个仅限关键字参数。

     请注意 *note ctypes.c_char: 241a. 的数组具有 `value' 和 `raw' 属性
     ，允许被用来保存和提取字符串。

* Menu:

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


File: python.info,  Node: multiprocessing sharedctypes 模块,  Up: 共享 ctypes 对象

5.17.2.15 ‘multiprocessing.sharedctypes’ 模块
.............................................

*note multiprocessing.sharedctypes: bd. 模块提供了一些函数，用于分配来自
共享内存的、可被子进程继承的 *note ctypes: 2a. 对象。

     備註: 虽然可以将指针存储在共享内存中，但请记住它所引用的是特定进程
     地址空间中的位置。 而且，指针很可能在第二个进程的上下文中无效，尝试
     从第二个进程对指针进行解引用可能会导致崩溃。

 -- 函式: multiprocessing.sharedctypes.RawArray (typecode_or_type,
          size_or_initializer)

     从共享内存中申请并返回一个 ctypes 数组。

     `typecode_or_type' 指明了返回的数组中的元素类型: 它可能是一个
     ctypes 类型或者 *note array: 6. 模块中使用的类型字符。 如果
     `size_or_initializer' 是一个整数，那就会当做数组的长度，并且整个数
     组的内存会初始化为0。否则，如果 `size_or_initializer' 会被当成一个
     序列用于初始化数组中的每一个元素，并且会根据元素个数自动判断数组的
     长度。

     注意对元素的访问、赋值操作可能是非原子操作 - 使用 *note Array():
     2534. , 从而借助其中的锁保证操作的原子性。

 -- 函式: multiprocessing.sharedctypes.RawValue (typecode_or_type,
          *args)

     从共享内存中申请并返回一个 ctypes 对象。

     `typecode_or_type' 指明了返回的对象类型: 它可能是一个 ctypes 类型或
     者 *note array: 6.  模块中每个类型对应的单字符长度的字符串。
     `*args' 会透传给这个类的构造函数。

     注意对 value 的访问、赋值操作可能是非原子操作 - 使用 *note Value():
     2536. ，从而借助其中的锁保证操作的原子性。

     请注意 *note ctypes.c_char: 241a. 的数组具有 `value' 和 `raw' 属性
     ，允许被用来保存和提取字符串 - 请查看 *note ctypes: 2a. 文档。

 -- 函式: multiprocessing.sharedctypes.Array (typecode_or_type,
          size_or_initializer, *, lock=True)

     返回一个纯 ctypes 数组, 或者在此之上经过同步器包装过的进程安全的对
     象，这取决于 `lock' 参数的值，除此之外，和 *note RawArray(): 2533.
     一样。

     如果 `lock' 为 ‘True’ (默认值) 则将创建一个新的锁对象用于同步对值的
     访问。 如果 `lock' 为一个 ‘Lock’ 或 ‘RLock’ 对象则该对象将被用于同
     步对值的访问。 如果 `lock' 为 ‘False’ 则对返回对象的访问将不会自动
     得到锁的保护，也就是说它不是“进程安全的”。

     注意 `lock' 只能是命名参数。

 -- 函式: multiprocessing.sharedctypes.Value (typecode_or_type, *args,
          lock=True)

     返回一个纯 ctypes 数组, 或者在此之上经过同步器包装过的进程安全的对
     象，这取决于 `lock' 参数的值，除此之外，和 ‘RawArray()’ 一样。

     如果 `lock' 为 ‘True’ (默认值) 则将创建一个新的锁对象用于同步对值的
     访问。 如果 `lock' 为一个 ‘Lock’ 或 ‘RLock’ 对象则该对象将被用于同
     步对值的访问。 如果 `lock' 为 ‘False’ 则对返回对象的访问将不会自动
     得到锁的保护，也就是说它不是“进程安全的”。

     注意 `lock' 只能是命名参数。

 -- 函式: multiprocessing.sharedctypes.copy (obj)

     从共享内存中申请一片空间将 ctypes 对象 `obj' 过来，然后返回一个新的
     ctypes 对象。

 -- 函式: multiprocessing.sharedctypes.synchronized (obj[, lock])

     将一个 ctypes 对象包装为进程安全的对象并返回，使用 `lock' 同步对于
     它的操作。如果 `lock' 是 ‘None’ (默认值) ，则会自动创建一个 *note
     multiprocessing.RLock: 24ee. 对象。

     同步器包装后的对象会在原有对象基础上额外增加两个方法: ‘get_obj()’ 返
     回被包装的对象， ‘get_lock()’ 返回内部用于同步的锁。

     需要注意的是，访问包装后的ctypes对象会比直接访问原来的纯 ctypes 对
     象慢得多。

     3.5 版更變: 同步器包装后的对象支持 *note context manager: 661. 协议
     。

下面的表格对比了创建普通ctypes对象和基于共享内存上创建共享ctypes对象的语
法。（表格中的 ‘MyStruct’ 是 *note ctypes.Structure: 2438. 的子类）

ctypes                   使用类型的共享ctypes           使用 typecode 的共享 ctypes
                                                        
----------------------------------------------------------------------------------------
                                                        
c_double(2.4)            RawValue(c_double, 2.4)        RawValue(’d’, 2.4)
                                                        
                                                        
MyStruct(4, 6)           RawValue(MyStruct, 4, 6)
                         
                                                        
(c_short * 7)()          RawArray(c_short, 7)           RawArray(’h’, 7)
                                                        
                                                        
(c_int * 3)(9, 2, 8)     RawArray(c_int, (9, 2, 8))     RawArray(’i’, (9, 2, 8))
                                                        

下面是一个在子进程中修改多个ctypes对象的例子。

     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])

输出如下

     49
     0.1111111111111111
     HELLO WORLD
     [(3.515625, 39.0625), (33.0625, 4.0), (5.640625, 90.25)]


File: python.info,  Node: 管理器,  Next: 代理对象,  Prev: 共享 ctypes 对象,  Up: 参考

5.17.2.16 管理器
................

管理器提供了一种创建共享数据的方法，从而可以在不同进程中共享，甚至可以通
过网络跨机器共享数据。管理器维护一个用于管理 `共享对象' 的服务。其他进程
可以通过代理访问这些共享对象。

 -- 函式: multiprocessing.Manager ()

     返回一个已启动的 *note SyncManager: 253a. 管理器对象，这个对象可以
     用于在不同进程中共享数据。返回的管理器对象对应了一个已经启动的子进
     程，并且拥有一系列方法可以用于创建共享对象、返回对应的代理。

当管理器被垃圾回收或者父进程退出时，管理器进程会立即退出。管理器类定义在
*note multiprocessing.managers: ba. 模块:

 -- 類別: multiprocessing.managers.BaseManager ([address[, authkey]])

     创建一个 BaseManager 对象。

     一旦创建，应该及时调用 *note start(): 253c. 或者
     ‘get_server().serve_forever()’ 以确保管理器对象对应的管理进程已经启
     动。

     `address' 是管理器服务进程监听的地址。如果 `address' 是 ‘None’ ,则
     允许和任意主机的请求建立连接。

     `authkey' 是认证标识，用于检查连接服务进程的请求合法性。如果
     `authkey' 是 ‘None’, 则会使用 ‘current_process().authkey’ , 否则，
     就使用 `authkey' , 需要保证它必须是 byte 类型的字符串。

      -- 成員函式: start ([initializer[, initargs]])

          为管理器开启一个子进程，如果 `initializer' 不是 ‘None’ , 子进
          程在启动时将会调用 ‘initializer(*initargs)’ 。

      -- 成員函式: get_server ()

          返回一个 ‘Server’  对象，它是管理器在后台控制的真实的服务。
          ‘Server’  对象拥有 ‘serve_forever()’ 方法。

               >>> from multiprocessing.managers import BaseManager
               >>> manager = BaseManager(address=('', 50000), authkey=b'abc')
               >>> server = manager.get_server()
               >>> server.serve_forever()

          ‘Server’ 额外拥有一个 *note address: 253e. 属性。

      -- 成員函式: connect ()

          将本地管理器对象连接到一个远程管理器进程:

               >>> from multiprocessing.managers import BaseManager
               >>> m = BaseManager(address=('127.0.0.1', 50000), authkey=b'abc')
               >>> m.connect()

      -- 成員函式: shutdown ()

          停止管理器的进程。这个方法只能用于已经使用 *note start():
          253c. 启动的服务进程。

          它可以被多次调用。

      -- 成員函式: register (typeid[, callable[, proxytype[, exposed[,
               method_to_typeid[, create_method]]]]])

          一个 classmethod，可以将一个类型或者可调用对象注册到管理器类。

          `typeid' 是一种 "类型标识符"，用于唯一表示某种共享对象类型，必
          须是一个字符串。

          `callable' 是一个用来为此类型标识符创建对象的可调用对象。如果
          一个管理器实例将使用 *note connect(): 253f. 方法连接到服务器，
          或者 `create_method' 参数为 ‘False’，那么这里可留下 ‘None’。

          `proxytype' 是 *note BaseProxy: 2542.  的子类，可以根据
          `typeid' 为共享对象创建一个代理，如果是 ‘None’ , 则会自动创建
          一个代理类。

          `exposed' 是一个函数名组成的序列，用来指明只有这些方法可以使用
          *note BaseProxy._callmethod(): 2543. 代理。(如果 `exposed' 是
          ‘None’, 则会在 ‘proxytype._exposed_’ 存在的情况下转而使用它) 当
          暴露的方法列表没有指定的时候，共享对象的所有 “公共方法” 都会被
          代理。（这里的“公共方法”是指所有拥有 *note __call__(): 1560. 方
          法并且不是以 ‘'_'’ 开头的属性）

          `method_to_typeid' 是一个映射，用来指定那些应该返回代理对象的
          暴露方法所返回的类型。（如果 `method_to_typeid' 是 ‘None’, 则
          ‘proxytype._method_to_typeid_’ 会在存在的情况下被使用）如果方
          法名称不在这个映射中或者映射是 ‘None’ ,则方法返回的对象会是一
          个值拷贝。

          `create_method' 指明，是否要创建一个以 `typeid' 命名并返回一个
          代理对象的方法，这个函数会被服务进程用于创建共享对象，默认为
          ‘True’ 。

     *note BaseManager: 253b. 实例也有一个只读属性。

      -- 屬性: address

          管理器所用的地址。

     3.3 版更變: 管理器对象支持上下文管理协议 - 查看 *note
     上下文管理器类型: 15c6. 。*note __enter__(): 1812. 启动服务进程（如
     果它还没有启动）并且返回管理器对象， *note __exit__(): 1814. 会调用
     *note shutdown(): 2540. 。

     在之前的版本中，如果管理器服务进程没有启动， *note __enter__():
     1812. 不会负责启动它。

 -- 類別: multiprocessing.managers.SyncManager

     *note BaseManager: 253b. 的子类，可用于进程的同步。这个类型的对象使
     用 ‘multiprocessing.Manager()’ 创建。

     它拥有一系列方法，可以为大部分常用数据类型创建并返回 *note
     代理对象: 65e. 代理，用于进程间同步。甚至包括共享列表和字典。

      -- 成員函式: Barrier (parties[, action[, timeout]])

          创建一个共享的 *note threading.Barrier: c31. 对象并返回它的代
          理。

          3.3 版新加入.

      -- 成員函式: BoundedSemaphore ([value])

          创建一个共享的 *note threading.BoundedSemaphore: b84. 对象并返
          回它的代理。

      -- 成員函式: Condition ([lock])

          创建一个共享的 *note threading.Condition: b82. 对象并返回它的
          代理。

          如果提供了 `lock' 参数，那它必须是 *note threading.Lock: 24bc.
          或 *note threading.RLock: cba. 的代理对象。

          3.3 版更變: 新增了 *note wait_for(): 24c7.  方法。

      -- 成員函式: Event ()

          创建一个共享的 *note threading.Event: b85. 对象并返回它的代理
          。

      -- 成員函式: Lock ()

          创建一个共享的 *note threading.Lock: 24bc. 对象并返回它的代理
          。

      -- 成員函式: Namespace ()

          创建一个共享的 *note Namespace: 24ec. 对象并返回它的代理。

      -- 成員函式: Queue ([maxsize])

          创建一个共享的 *note queue.Queue: dde. 对象并返回它的代理。

      -- 成員函式: RLock ()

          创建一个共享的 *note threading.RLock: cba. 对象并返回它的代理
          。

      -- 成員函式: Semaphore ([value])

          创建一个共享的 *note threading.Semaphore: b83. 对象并返回它的
          代理。

      -- 成員函式: Array (typecode, sequence)

          创建一个数组并返回它的代理。

      -- 成員函式: Value (typecode, value)

          创建一个具有可写 ‘value’ 属性的对象并返回它的代理。

      -- 成員函式: dict ()

      -- 成員函式: dict (mapping)

      -- 成員函式: dict (sequence)

          创建一个共享的 *note dict: 164. 对象并返回它的代理。

      -- 成員函式: list ()

      -- 成員函式: list (sequence)

          创建一个共享的 *note list: 1f8. 对象并返回它的代理。

     3.6 版更變: 共享对象能够嵌套。例如, 共享的容器对象如共享列表，可以
     包含另一个共享对象，他们全都会在 *note SyncManager: 253a. 中进行管
     理和同步。

 -- 類別: multiprocessing.managers.Namespace

     一个可以注册到 *note SyncManager: 253a. 的类型。

     命名空间对象没有公共方法，但是拥有可写的属性。直接print会显示所有属
     性的值。

     值得一提的是，当对命名空间对象使用代理的时候，访问所有名称以 ‘'_'’
     开头的属性都只是代理器上的属性，而不是命名空间对象的属性。

          >>> 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')

* Menu:

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


File: python.info,  Node: 自定义管理器,  Next: 使用远程管理器,  Up: 管理器

5.17.2.17 自定义管理器
......................

要创建一个自定义的管理器，需要新建一个 *note BaseManager: 253b. 的子类，
然后使用这个管理器类上的 *note register(): 2541. 类方法将新类型或者可调
用方法注册上去。例如:

     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


File: python.info,  Node: 使用远程管理器,  Prev: 自定义管理器,  Up: 管理器

5.17.2.18 使用远程管理器
........................

可以将管理器服务运行在一台机器上，然后使用客户端从其他机器上访问。(假设
它们的防火墙允许)

运行下面的代码可以启动一个服务，此付包含了一个共享队列，允许远程客户端访
问:

     >>> 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=('', 50000), authkey=b'abracadabra')
     >>> s = m.get_server()
     >>> s.serve_forever()

远程客户端可以通过下面的方式访问服务:

     >>> 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')

也可以通过下面的方式:

     >>> 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'

本地进程也可以访问这个队列，利用上面的客户端代码通过远程方式访问:

     >>> 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=('', 50000), authkey=b'abracadabra')
     >>> s = m.get_server()
     >>> s.serve_forever()


File: python.info,  Node: 代理对象,  Next: 进程池,  Prev: 管理器,  Up: 参考

5.17.2.19 代理对象
..................

代理是一个 `指向' 其他共享对象的对象，这个对象(很可能)在另外一个进程中。
共享对象也可以说是代理 `指涉' 的对象。多个代理对象可能指向同一个指涉对象
。

代理对象代理了指涉对象的一系列方法调用(虽然并不是指涉对象的每个方法都有
必要被代理)。通过这种方式，代理的使用方法可以和它的指涉对象一样:

     >>> 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]

注意，对代理使用 *note str(): 205. 函数会返回指涉对象的字符串表示，但是
*note repr(): 8b9. 却会返回代理本身的内部字符串表示。

被代理的对象很重要的一点是必须可以被序列化，这样才能允许他们在进程间传递
。因此，指涉对象可以包含 *note 代理对象: 65e. 。这允许管理器中列表、字典
或者其他 *note 代理对象: 65e. 对象之间的嵌套。

     >>> 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']

类似地，字典和列表代理也可以相互嵌套:

     >>> 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}

如果指涉对象包含了普通 *note list: 1f8. 或 *note dict: 164. 对象，对这些
内部可变对象的修改不会通过管理器传播，因为代理无法得知被包含的值什么时候
被修改了。但是把存放在容器代理中的值本身是会通过管理器传播的（会触发代理
对象中的 ‘__setitem__’ ）从而有效修改这些对象，所以可以把修改过的值重新
赋值给容器代理:

     # 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

在大多是使用情形下，这种实现方式并不比嵌套 *note 代理对象: 65e. 方便，但
是依然演示了对于同步的一种控制级别。

     備註: *note multiprocessing: b7. 中的代理类并没有提供任何对于代理值
     比较的支持。所以，我们会得到如下结果:

          >>> manager.list([1,2,3]) == [1,2,3]
          False

     当需要比较值的时候，应该替换为使用指涉对象的拷贝。

 -- 類別: multiprocessing.managers.BaseProxy

     代理对象是 *note BaseProxy: 2542. 派生类的实例。

      -- 成員函式: _callmethod (methodname[, args[, kwds]])

          调用指涉对象的方法并返回结果。

          如果 ‘proxy’ 是一个代理且其指涉的是 ‘obj’ , 那么下面的表达式:

               proxy._callmethod(methodname, args, kwds)

          相当于求取以下表达式的值:

               getattr(obj, methodname)(*args, **kwds)

          于管理器进程。

          返回结果会是一个值拷贝或者一个新的共享对象的代理 - 见函数
          *note BaseManager.register(): 2541. 中关于参数
          `method_to_typeid' 的文档。

          如果这个调用熬出了异常，则这个异常会被 *note _callmethod():
          2543. 透传出来。如果是管理器进程本身抛出的一些其他异常，则会被
          *note _callmethod(): 2543. 转换为 ‘RemoteError’ 异常重新抛出。

          特别注意，如果 `methodname' 没有 `暴露' 出来，将会引发一个异常
          。

          *note _callmethod(): 2543. 的一个使用示例:

               >>> 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

      -- 成員函式: _getvalue ()

          返回指涉对象的一份拷贝。

          如果指涉对象无法序列化，则会抛出一个异常。

      -- 成員函式: __repr__ ()

          返回代理对象的内部字符串表示。

      -- 成員函式: __str__ ()

          返回指涉对象的内部字符串表示。

* Menu:

* 清理::


File: python.info,  Node: 清理,  Up: 代理对象

5.17.2.20 清理
..............

代理对象使用了一个弱引用回调函数，当它被垃圾回收时，会将自己从拥有此指涉
对象的管理器上反注册，

当共享对象没有被任何代理器引用时，会被管理器进程删除。


File: python.info,  Node: 进程池,  Next: 监听器及客户端,  Prev: 代理对象,  Up: 参考

5.17.2.21 进程池
................

可以创建一个进程池，它将使用 *note Pool: 966. 类执行提交给它的任务。

 -- 類別: multiprocessing.pool.Pool ([processes[, initializer[,
          initargs[, maxtasksperchild[, context]]]]])

     一个进程池对象，它控制可以提交作业的工作进程池。它支持带有超时和回
     调的异步结果，以及一个并行的 map 实现。

     `processes' 是要使用的工作进程数目。如果 `processes' 为 ‘None’，则
     使用 *note os.cpu_count(): 96a. 返回的值。

     如果 `initializer' 不为 ‘None’，则每个工作进程将会在启动时调用
     ‘initializer(*initargs)’。

     `maxtasksperchild' 是一个工作进程在它退出或被一个新的工作进程代替之
     前能完成的任务数量，为了释放未使用的资源。默认的 `maxtasksperchild'
     是 ‘None’，意味着工作进程寿与池齐。

     `context' 可被用于指定启动的工作进程的上下文。通常一个进程池是使用
     函数 ‘multiprocessing.Pool()’ 或者一个上下文对象的 *note Pool():
     966. 方法创建的。在这两种情况下， `context' 都是适当设置的。

     注意，进程池对象的方法只有创建它的进程能够调用。

          警告: *note multiprocessing.pool: bb. 对象具有需要正确管理的内
          部资源 （像任何其他资源一样），具体方式是将进程池用作上下文管
          理器，或者手动调用 *note close(): 2559. 和 *note terminate():
          255a.。 未做此类操作将导致进程在终结阶段挂起。

          请注意依赖垃圾回收器来销毁进程池是 `不正确' 的做法，因为
          CPython 并不保证会调用进程池终结程序（请参阅 *note
          object.__del__(): a04. 来了解详情）。

     3.2 版新加入: `maxtasksperchild'

     3.4 版新加入: `context'

          備註: 通常来说，*note Pool: 966. 中的 Worker 进程的生命周期和
          进程池的工作队列一样长。一些其他系统中（如 Apache, mod_wsgi 等
          ）也可以发现另一种模式，他们会让工作进程在完成一些任务后退出，
          清理、释放资源，然后启动一个新的进程代替旧的工作进程。 *note
          Pool: 966. 的 `maxtasksperchild' 参数给用户提供了这种能力。

      -- 成員函式: apply (func[, args[, kwds]])

          使用 `args' 参数以及 `kwds' 命名参数调用 `func' , 它会返回结果
          前阻塞。这种情况下，*note apply_async(): 255c. 更适合并行化工
          作。另外 `func' 只会在一个进程池中的一个工作进程中执行。

      -- 成員函式: apply_async (func[, args[, kwds[, callback[,
               error_callback]]]])

          *note apply(): 255b. 方法的一个变种，返回一个 *note
          AsyncResult: 255d. 对象。

          如果指定了 `callback' , 它必须是一个接受单个参数的可调用对象。
          当执行成功时， `callback' 会被用于处理执行后的返回结果，否则，
          调用 `error_callback' 。

          如果指定了 `error_callback' , 它必须是一个接受单个参数的可调用
          对象。当目标函数执行失败时， 会将抛出的异常对象作为参数传递给
          `error_callback' 执行。

          回调函数应该立即执行完成，否则会阻塞负责处理结果的线程。

      -- 成員函式: map (func, iterable[, chunksize])

          内置 *note map(): cf7. 函数的并行版本 (但它只支持一个
          `iterable' 参数，对于多个可迭代对象请参阅 *note starmap():
          b03.)。 它会保持阻塞直到获得结果。

          这个方法会将可迭代对象分割为许多块，然后提交给进程池。可以将
          `chunksize' 设置为一个正整数从而（近似）指定每个块的大小可以。

          注意对于很长的迭代对象，可能消耗很多内存。可以考虑使用 *note
          imap(): 255e. 或 *note imap_unordered(): 255f. 并且显示指定
          `chunksize' 以提升效率。

      -- 成員函式: map_async (func, iterable[, chunksize[, callback[,
               error_callback]]])

          *note map(): b06. 方法的一个变种，返回一个 *note AsyncResult:
          255d. 对象。

          如果指定了 `callback' , 它必须是一个接受单个参数的可调用对象。
          当执行成功时， `callback' 会被用于处理执行后的返回结果，否则，
          调用 `error_callback' 。

          如果指定了 `error_callback' , 它必须是一个接受单个参数的可调用
          对象。当目标函数执行失败时， 会将抛出的异常对象作为参数传递给
          `error_callback' 执行。

          回调函数应该立即执行完成，否则会阻塞负责处理结果的线程。

      -- 成員函式: imap (func, iterable[, chunksize])

          *note map(): b06. 的延迟执行版本。

          `chunksize' 参数的作用和 *note map(): b06. 方法的一样。对于很
          长的迭代器，给 `chunksize' 设置一个很大的值会比默认值 ‘1’ `极
          大' 地加快执行速度。

          同样，如果 `chunksize' 是 ‘1’ , 那么 *note imap(): 255e. 方法
          所返回的迭代器的 ‘next()’ 方法拥有一个可选的 `timeout' 参数：
          如果无法在 `timeout' 秒内执行得到结果，则‘‘next(timeout)‘‘ 会
          抛出 *note multiprocessing.TimeoutError: 2504. 异常。

      -- 成員函式: imap_unordered (func, iterable[, chunksize])

          和 *note imap(): 255e. 相同，只不过通过迭代器返回的结果是任意
          的。（当进程池中只有一个工作进程的时候，返回结果的顺序才能认为
          是"有序"的）

      -- 成員函式: starmap (func, iterable[, chunksize])

          Like *note map(): b06. except that the elements of the
          `iterable' are expected to be iterables that are unpacked as
          arguments.

          比如可迭代对象 ‘[(1,2), (3, 4)]’ 会转化为等价于 ‘[func(1,2),
          func(3,4)]’ 的调用。

          3.3 版新加入.

      -- 成員函式: starmap_async (func, iterable[, chunksize[,
               callback[, error_callback]]])

          相当于 *note starmap(): b03. 与 *note map_async(): b07. 的结合
          ，迭代 `iterable' 的每一项，解包作为 `func' 的参数并执行，返回
          用于获取结果的对象。

          3.3 版新加入.

      -- 成員函式: close ()

          阻止后续任务提交到进程池，当所有任务执行完成后，工作进程会退出
          。

      -- 成員函式: terminate ()

          不必等待未完成的任务，立即停止工作进程。当进程池对象被垃圾回收
          时，会立即调用 *note terminate(): 255a.。

      -- 成員函式: join ()

          等待工作进程结束。调用 *note join(): 2560. 前必须先调用 *note
          close(): 2559. 或者 *note terminate(): 255a. 。

     3.3 版新加入: 进程池对象现在支持上下文管理器协议 - 参见 *note
     上下文管理器类型: 15c6. 。*note __enter__(): 1812. 返回进程池对象,
     *note __exit__(): 1814. 会调用 *note terminate(): 255a. 。

 -- 類別: multiprocessing.pool.AsyncResult

     *note Pool.apply_async(): 255c. 和 *note Pool.map_async(): b07. 返
     回对象所属的类。

      -- 成員函式: get ([timeout])

          用于获取执行结果。如果 `timeout' 不是 ‘None’ 并且在 `timeout'
          秒内仍然没有执行完得到结果，则抛出 *note
          multiprocessing.TimeoutError: 2504. 异常。如果远程调用发生异常
          ，这个异常会通过 *note get(): 2561. 重新抛出。

      -- 成員函式: wait ([timeout])

          阻塞，直到返回结果，或者 `timeout' 秒后超时。

      -- 成員函式: ready ()

          返回执行状态，是否已经完成。

      -- 成員函式: successful ()

          判断调用是否已经完成并且未引发异常。 如果还未获得结果则将引发
          *note ValueError: 16d.。

          3.7 版更變: 如果没有执行完，会抛出 *note ValueError: 16d.  异
          常而不是 *note AssertionError: 240. 。

下面的例子演示了进程池的用法:

     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


File: python.info,  Node: 监听器及客户端,  Next: 认证密码,  Prev: 进程池,  Up: 参考

5.17.2.22 监听器及客户端
........................

通常情况下，进程间通过队列或者 *note Pipe(): 24e7. 返回的 *note
Connection: 2511. 传递消息。

不过，*note multiprocessing.connection: b8. 模块其实提供了一些更灵活的特
性。最基础的用法是通过它抽象出来的高级API来操作socket或者Windows命名管道
。也提供一些高级用法，如通过 *note hmac: 8e. 模块来支持 `摘要认证'，以及
同时监听多个管道连接。

 -- 函式: multiprocessing.connection.deliver_challenge (connection,
          authkey)

     发送一个随机生成的消息到另一端，并等待回复。

     如果收到的回复与使用 `authkey' 作为键生成的信息摘要匹配成功，就会发
     送一个欢迎信息给管道另一端。否则抛出 *note AuthenticationError:
     2503. 异常。

 -- 函式: multiprocessing.connection.answer_challenge (connection,
          authkey)

     接收一条信息，使用 `authkey' 作为键计算信息摘要，然后将摘要发送回去
     。

     如果没有收到欢迎消息，就抛出 *note AuthenticationError: 2503. 异常
     。

 -- 函式: multiprocessing.connection.Client (address[, family[,
          authkey]])

     尝试使用 `address' 地址上的监听器建立一个连接，返回 *note
     Connection: 2511. 。

     连接的类型取决于 `family' 参数，但是通常可以省略，因为可以通过
     `address' 的格式推导出来。(查看 *note 地址格式: 2569. )

     如果提供了 `authkey' 参数并且不是 None，那它必须是一个字符串并且会
     被当做基于 HMAC 认证的密钥。如果 `authkey' 是None 则不会有认证行为
     。认证失败抛出 *note AuthenticationError: 2503. 异常，请查看 See
     *note 认证密码: 24ff. 。

 -- 類別: multiprocessing.connection.Listener ([address[, family[,
          backlog[, authkey]]]])

     可以监听连接请求，是对于绑定套接字或者 Windows 命名管道的封装。

     `address' 是监听器对象中的绑定套接字或命名管道使用的地址。

          備註: 如果使用 ’0.0.0.0’ 作为监听地址，那么在Windows上这个地址
          无法建立连接。想要建立一个可连接的端点，应该使用 ’127.0.0.1’ 。

     `family' 是套接字(或者命名管道)使用的类型。它可以是以下一种:
     ‘'AF_INET'’ ( TCP 套接字类型), ‘'AF_UNIX'’ ( Unix 域套接字) 或者
     ‘'AF_PIPE'’ ( Windows 命名管道)。其中只有第一个保证各平台可用。如果
     `family' 是 ‘None’ ,那么 family 会根据 `address' 的格式自动推导出来
     。如果 `address' 也是 ‘None’ , 则取默认值。默认值为可用类型中速度最
     快的。见 *note 地址格式: 2569. 。注意，如果 `family' 是 ‘'AF_UNIX'’
     而address是‘‘None‘‘ ,套接字会在一个 *note tempfile.mkstemp(): 1dc4.
     创建的私有临时目录中创建。

     如果监听器对象使用了套接字，`backlog' (默认值为1) 会在套接字绑定后
     传递给它的 *note listen(): 83a. 方法。

     如果提供了 `authkey' 参数并且不是 None，那它必须是一个字符串并且会
     被当做基于 HMAC 认证的密钥。如果 `authkey' 是None 则不会有认证行为
     。认证失败抛出 *note AuthenticationError: 2503. 异常，请查看 See
     *note 认证密码: 24ff. 。

      -- 成員函式: accept ()

          接受一个连接并返回一个 *note Connection: 2511. 对象，其连接到
          的监听器对象已绑定套接字或者命名管道。如果已经尝试过认证并且失
          败了，则会抛出 *note AuthenticationError: 2503. 异常。

      -- 成員函式: close ()

          关闭监听器对象上的绑定套接字或者命名管道。此函数会在监听器被垃
          圾回收后自动调用。不过仍然建议显式调用函数关闭。

     监听器对象拥有下列只读属性:

      -- 屬性: address

          监听器对象使用的地址。

      -- 屬性: last_accepted

          最后一个连接所使用的地址。如果没有的话就是 ‘None’ 。

     3.3 版新加入: 监听器对象现在支持了上下文管理协议 - 见 *note
     上下文管理器类型: 15c6. 。 *note __enter__(): 1812. 返回一个监听器
     对象, *note __exit__(): 1814. 会调用 *note close(): 256b. 。

 -- 函式: multiprocessing.connection.wait (object_list, timeout=None)

     一直等待直到 `object_list' 中某个对象处于就绪状态。返回
     `object_list' 中处于就绪状态的对象。如果 `timeout' 是一个浮点型，该
     方法会最多阻塞这么多秒。如果 `timeout' 是 ‘None’ ，则会允许阻塞的事
     件没有限制。timeout为负数的情况下和为0的情况相同。

     对于 Unix 和 Windows ，满足下列条件的对象可以出现在 `object_list' 中

        * 可读的 *note Connection: 2511. 对象；

        * 一个已连接并且可读的 *note socket.socket: 767. 对象；或者

        * *note Process: 4b8. 对象中的 *note sentinel: b02. 属性。

     当一个连接或者套接字对象拥有有效的数据可被读取的时候，或者另一端关
     闭后，这个对象就处于就绪状态。

     `Unix': ‘wait(object_list, timeout)’ 和 ‘select.select(object_list,
     [], [], timeout)’ 几乎相同。差别在于，如果 *note select.select():
     766. 被信号中断，它会抛出一个附带错误号为 ‘EINTR’ 的 *note OSError:
     304. 异常，而 *note wait(): b01. 不会。

     `Windows': `object_list' 中的元素必须是一个表示为整数的可等待的句柄
     (按照 Win32 函数 ‘WaitForMultipleObjects()’ 的文档中所定义) 或者一
     个拥有 ‘fileno()’ 方法的对象，这个对象返回一个套接字句柄或者管道句
     柄。（注意管道和套接字两种句柄 `不是' 可等待的句柄）

     3.3 版新加入.

`示例'

下面的服务代码创建了一个使用 ‘'secret password'’ 作为认证密码的监听器。
它会等待连接然后发送一些数据给客户端:

     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]))

下面的代码连接到服务然后从服务器上j接收一些数据:

     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])

下面的代码使用了 *note wait(): b01. ，以便在同时等待多个进程发来消息。

     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)

* Menu:

* 地址格式::


File: python.info,  Node: 地址格式,  Up: 监听器及客户端

5.17.2.23 地址格式
..................

   * ‘'AF_INET'’ 地址是 ‘(hostname, port)’ 形式的元组类型，其中
     `hostname' 是一个字符串，`port' 是整数。

   * ‘'AF_UNIX'’ 地址是文件系统上文件名的字符串。

   * ‘'AF_PIPE'’ 地址是一个 ‘r'\.\pipe{PipeName}'’ 形式的字符串。 要使用
     *note Client(): 2568. 来连接到远程计算机上一个名为 `ServerName' 的
     命名管道，则应当改用 ‘r'\`ServerName'\pipe{PipeName}'’ 形式的地址。

注意，使用两个反斜线开头的字符串默认被当做 ‘'AF_PIPE'’ 地址而不是
‘'AF_UNIX'’  。


File: python.info,  Node: 认证密码,  Next: 日志,  Prev: 监听器及客户端,  Up: 参考

5.17.2.24 认证密码
..................

当使用 *note Connection.recv: 2524. 接收数据时，数据会自动被反序列化。不
幸的是，对于一个不可信的数据源发来的数据，反序列化是存在安全风险的。所以
*note Listener: 106b. 和 *note Client(): 2568. 之间使用 *note hmac: 8e.
模块进行摘要认证。

认证密钥是一个 byte 类型的字符串，可以认为是和密码一样的东西，连接建立好
后，双方都会要求另一方证明知道认证密钥。（这个证明过程不会通过连接发送密
钥）

如果要求认证但是没有指定认证密钥，则会使用 ‘current_process().authkey’ 的
返回值 (参见 *note Process: 4b8. )。 这个值会被当前进程所创建的任何
*note Process: 4b8. 对象自动继承。 这意味着（默认情况下）当一个多进程程
序的所有进程在彼此之间建立连接的时候，会共享同一个认证密钥。

*note os.urandom(): 5cb. 也可以用来生成合适的认证密钥。


File: python.info,  Node: 日志,  Next: multiprocessing dummy 模块,  Prev: 认证密码,  Up: 参考

5.17.2.25 日志
..............

当前模块也提供了一些对 logging 的支持。注意， *note logging: aa. 模块本
身并没有使用进程间共享的锁，所以来自于多个进程的日志可能（具体取决于使用
的日志 handler 类型）相互覆盖或者混杂。

 -- 函式: multiprocessing.get_logger ()

     返回 *note multiprocessing: b7. 使用的 logger，必要的话会创建一个新
     的。

     如果创建的首个 logger 日志级别为 ‘logging.NOTSET’ 并且没有默认
     handler。通过这个 logger 打印的消息不会传递到根 logger。

     注意在 Windows 上，子进程只会继承父进程 logger 的日志级别 - 对于
     logger的其他自定义项不会继承。

 -- 函式: multiprocessing.log_to_stderr (level=None)

     This function performs a call to *note get_logger(): 2571. but in
     addition to returning the logger created by get_logger, it adds a
     handler which sends output to *note sys.stderr: 1ea. using format
     ‘'[%(levelname)s/%(processName)s] %(message)s'’.  You can modify
     ‘levelname’ of the logger by passing a ‘level’ argument.

下面是一个在交互式解释器中打开日志功能的例子:

     >>> 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

要查看日志等级的完整列表，见 *note logging: aa. 模块。


File: python.info,  Node: multiprocessing dummy 模块,  Prev: 日志,  Up: 参考

5.17.2.26 ‘multiprocessing.dummy’ 模块
......................................

*note multiprocessing.dummy: b9. 复制了 *note multiprocessing: b7. 的
API，不过是在 *note threading: 10b. 模块之上包装了一层。

特别地，*note multiprocessing.dummy: b9. 所提供的 ‘Pool’ 函数会返回一个
*note ThreadPool: fce. 的实例，该类是 *note Pool: 966. 的子类，它支持所
有相同的方法调用但会使用一个工作线程池而非工作进程池。

 -- 類別: multiprocessing.pool.ThreadPool ([processes[, initializer[,
          initargs]]])

     一个线程池对象，用来控制可向其提交任务的工作线程池。 *note
     ThreadPool: fce. 实例与 *note Pool: 966. 实例是完全接口兼容的，并且
     它们的资源也必须被正确地管理，或者是将线程池作为上下文管理器来使用
     ，或者是通过手动调用 *note close(): 2559. 和 *note terminate():
     255a.。

     `processes' 是要使用的工作线程数目。 如果 `processes' 为 ‘None’，则
     使用 *note os.cpu_count(): 96a. 返回的值。

     如果 `initializer' 不为 ‘None’，则每个工作进程将会在启动时调用
     ‘initializer(*initargs)’。

     不同于 *note Pool: 966.，`maxtasksperchild' 和 `context' 不可被提供
     。

               備註: *note ThreadPool: fce. 具有与 *note Pool: 966. 相同
               的接口，它围绕一个进程池进行设计并且先于 *note
               concurrent.futures: 21. 模块的引入。 因此，它继承了一些对
               于基于线程的池来说没有意义的操作，并且它具有自己的用于表
               示异步任务状态的类型 *note AsyncResult: 255d.，该类型不为
               任何其他库所知。

               用户通常应该倾向于使用 *note
               concurrent.futures.ThreadPoolExecutor: 18c.，它拥有从一开
               始就围绕线程进行设计的更简单接口，并且返回与许多其他库相
               兼容的 *note concurrent.futures.Future: c00. 实例，包括
               *note asyncio: 9. 库。


File: python.info,  Node: 编程指导,  Next: 示例<17>,  Prev: 参考,  Up: multiprocessing --- 基于进程的并行

5.17.2.27 编程指导
..................

使用 *note multiprocessing: b7. 时，应遵循一些指导原则和习惯用法。

* Menu:

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


File: python.info,  Node: 所有start方法,  Next: spawn 和 forkserver 启动方式,  Up: 编程指导

5.17.2.28 所有start方法
.......................

下面这些适用于所有start方法。

避免共享状态

     应该尽可能避免在进程间传递大量数据，越少越好。

     最好坚持使用队列或者管道进行进程间通信，而不是底层的同步原语。

可序列化

     保证所代理的方法的参数是可以序列化的。

代理的线程安全性

     不要在多线程中同时使用一个代理对象，除非你用锁保护它。

     （而在不同进程中使用 `相同' 的代理对象却没有问题。）

使用 Join 避免僵尸进程

     在 Unix 上，如果一个进程执行完成但是没有被 join，就会变成僵尸进程。
     一般来说，僵尸进程不会很多，因为每次新启动进程（或者 *note
     active_children(): 251c. 被调用）时，所有已执行完成且没有被 join 的
     进程都会自动被 join，而且对一个执行完的进程调用 *note
     Process.is_alive: 24fc. 也会 join 这个进程。尽管如此，对自己启动的
     进程显式调用 join 依然是最佳实践。

继承优于序列化、反序列化

     当使用 `spawn' 或者 `forkserver' 的启动方式时，*note
     multiprocessing: b7. 中的许多类型都必须是可序列化的，这样子进程才能
     使用它们。但是通常我们都应该避免使用管道和队列发送共享对象到另外一
     个进程，而是重新组织代码，对于其他进程创建出来的共享对象，让那些需
     要访问这些对象的子进程可以直接将这些对象从父进程继承过来。

避免杀死进程

     听过 *note Process.terminate: 2500.  停止一个进程很容易导致这个进程
     正在使用的共享资源（如锁、信号量、管道和队列）损坏或者变得不可用，
     无法在其他进程中继续使用。

     所以，最好只对那些从来不使用共享资源的进程调用 *note
     Process.terminate: 2500. 。

Join 使用队列的进程

     记住，往队列放入数据的进程会一直等待直到队列中所有项被"feeder" 线程
     传给底层管道。（子进程可以调用队列的 *note
     Queue.cancel_join_thread: 250f. 方法禁止这种行为）

     这意味着，任何使用队列的时候，你都要确保在进程join之前，所有存放到
     队列中的项将会被其他进程、线程完全消费。否则不能保证这个写过队列的
     进程可以正常终止。记住非精灵进程会自动 join 。

     下面是一个会导致死锁的例子:

          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()

     交换最后两行可以修复这个问题（或者直接删掉 ‘p.join()’）。

显式传递资源给子进程

     在Unix上，使用 `fork' 方式启动的子进程可以使用父进程中全局创建的共
     享资源。不过，最好是显式将资源对象通过参数的形式传递给子进程。

     除了（部分原因）让代码兼容 Windows 以及其他的进程启动方式外，这种形
     式还保证了在子进程生命期这个对象是不会被父进程垃圾回收的。如果父进
     程中的某些对象被垃圾回收会导致资源释放，这就变得很重要。

     所以对于实例：

          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()

     应当重写成这样：

          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()

谨防将 *note sys.stdin: 41e. 数据替换为 “类似文件的对象”

     *note multiprocessing: b7. 原本会无条件地这样调用:

          os.close(sys.stdin.fileno())

     在 ‘multiprocessing.Process._bootstrap()’  方法中 —— 这会导致与"进
     程中的进程"相关的一些问题。这已经被修改成了:

          sys.stdin.close()
          sys.stdin = open(os.open(os.devnull, os.O_RDONLY), closefd=False)

     它解决了进程相互冲突导致文件描述符错误的根本问题，但是对使用带缓冲
     的“文件类对象”替换 *note sys.stdin(): 41e. 作为输出的应用程序造成了
     潜在的危险。如果多个进程调用了此文件类对象的 *note close(): 1147. 方
     法，会导致相同的数据多次刷写到此对象，损坏数据。

     如果你写入文件类对象并实现了自己的缓存，可以在每次追加缓存数据时记
     录当前进程id，从而将其变成 fork 安全的，当发现进程id变化后舍弃之前
     的缓存，例如:

          @property
          def cache(self):
              pid = os.getpid()
              if pid != self._pid:
                  self._pid = pid
                  self._cache = []
              return self._cache

     需要更多信息，请查看 bpo-5155(1), bpo-5313(2) 以及 bpo-5331(3)

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue5155

   (2) https://bugs.python.org/issue5313

   (3) https://bugs.python.org/issue5331


File: python.info,  Node: spawn 和 forkserver 启动方式,  Prev: 所有start方法,  Up: 编程指导

5.17.2.29 `spawn' 和 `forkserver' 启动方式
..........................................

相对于 `fork' 启动方式，有一些额外的限制。

更依赖序列化

     ‘Process.__init__()’ 的所有参数都必须可序列化。同样的，当你继承
     *note Process: 4b8. 时，需要保证当调用 *note Process.start: 24f9. 方
     法时，实例可以被序列化。

全局变量

     记住，如果子进程中的代码尝试访问一个全局变量，它所看到的值（如果有
     ）可能和父进程中执行 *note Process.start: 24f9. 那一刻的值不一样。

     当全局变量知识模块级别的常量时，是不会有问题的。

安全导入主模块

     确保主模块可以被新启动的Python解释器安全导入而不会引发什么副作用（
     比如又启动了一个子进程）

     例如，使用 `spawn' 或 `forkserver' 启动方式执行下面的模块，会引发
     *note RuntimeError: 3dc. 异常而失败。

          from multiprocessing import Process

          def foo():
              print('hello')

          p = Process(target=foo)
          p.start()

     应该通过下面的方法使用 ‘if __name__ == '__main__':’ ，从而保护程序
     "入口点":

          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()

     （如果程序将正常运行而不是冻结，则可以省略 ‘freeze_support()’ 行）

     这允许新启动的 Python 解释器安全导入模块然后运行模块中的 ‘foo()’ 函
     数。

     如果主模块中创建了进程池或者管理器，这个规则也适用。


File: python.info,  Node: 示例<17>,  Prev: 编程指导,  Up: multiprocessing --- 基于进程的并行

5.17.2.30 示例
..............

创建和使用自定义管理器、代理的示例:

     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()

使用 *note Pool: 966.:

     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()

一个演示如何使用队列来向一组工作进程提供任务并收集结果的例子：

     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()


File: python.info,  Node: multiprocessing shared_memory --- 可从进程直接访问的共享内存,  Next: concurrent 包,  Prev: multiprocessing --- 基于进程的并行,  Up: 并发执行

5.17.3 ‘multiprocessing.shared_memory’ — 可从进程直接访问的共享内存
-------------------------------------------------------------------

`源代码:' Lib/multiprocessing/shared_memory.py(1)

3.8 版新加入.

__________________________________________________________________

该模块提供了一个 *note SharedMemory: 24e4. 类，用于分配和管理多核或对称
多处理器（SMP）机器上进程间的共享内存。为了协助管理不同进程间的共享内存
生命周期，‘multiprocessing.managers’ 模块也提供了一个 *note BaseManager:
253b. 的子类： ‘SharedMemoryManager’。

本模块中，共享内存是指 "System V 类型" 的共享内存块（虽然实现方式可能不
完全一致）而不是 “分布式共享内存”。这种类型的的共享内存允许不同进程读写
一片公共（或者共享）的易失性存储区域。一般来说，进程被限制只能访问属于自
己进程空间的内存，但是共享内存允许跨进程共享数据，从而避免通过进程间发送
消息的形式传递数据。与通过磁盘、套接字或者其他要求序列化、反序列化和复制
数据的共享形式相比，直接通过内存共享数据拥有更出色的性能。

 -- 類別: multiprocessing.shared_memory.SharedMemory (name=None,
          create=False, size=0)

     创建一个新的共享内存块或者连接到一片已经存在的共享内存块。每个共享
     内存块都被指定了一个全局唯一的名称。通过这种方式，进程可以使用一个
     特定的名字创建共享内存区块，然后其他进程使用同样的名字连接到这个共
     享内存块。

     作为一种跨进程共享数据的方式，共享内存块的寿命可能超过创建它的原始
     进程。一个共享内存块可能同时被多个进程使用，当一个进程不再需要访问
     这个共享内存块的时候，应该调用 *note close(): 257a. 方法。当一个共
     享内存块不被任何进程使用的时候，应该调用 *note unlink(): 257b. 方法
     以保证必要的清理。

     `name' 是共享内存的唯一名称，字符串类型。如果创建一个新共享内存块的
     时候，名称指定为 ‘None’ (默认值)，将会随机产生一个新名称。

     `create' 指定创建一个新的共享内存块 (‘True’) 还是连接到已存在的共享
     内存块 (‘False’) 。

     如果是新创建共享内存块则 `size' 用于指定块的大小为多少字节。由于某
     些平台是以内存页大小为最小单位来分配内存的，最终得到的内存块大小可
     能大于或等于要求的大小。如果是连接到已经存在的共享内存块， ‘size’ 参
     数会被忽略。

      -- 成員函式: close ()

          关闭实例对于共享内存的访问连接。所有实例确认自己不再需要使用共
          享内存的时候都应该调用 ‘close()’ ，以保证必要的资源清理。调用
          ‘close()’ 并不会销毁共享内存区域。

      -- 成員函式: unlink ()

          请求销毁底层的共享内存块。为了执行必要的资源清理， 在所有使用
          这个共享内存块的进程中， ‘unlink()’ 应该调用一次(且只能调用一
          次) 。发出此销毁请求后，共享内存块可能会、也可能不会立即销毁，
          且此行为在不同操作系统之间可能不同。调用 ‘unlink()’ 后再尝试方
          位其中的数据可能导致内存错误。注意: 最后一个关闭共享内存访问权
          限的进程可以以任意顺序调用 ‘unlink()’ 和 *note close(): 257a.
          。

      -- 屬性: buf

          共享内存块内容的 memoryview 。

      -- 屬性: name

          共享内存块的唯一标识，只读属性。

      -- 屬性: size

          共享内存块的字节大小，只读属性。

以下示例展示了 *note SharedMemory: 24e4. 底层的用法:

     >>> 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

以下示例展示了一个现实中的例子，使用 *note SharedMemory: 24e4. 类和
NumPy arrays(2) 结合, 从两个 Python shell 中访问同一个 ‘numpy.ndarray’ :

     >>> # 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

 -- 類別: multiprocessing.managers.SharedMemoryManager ([address[,
          authkey]])

     *note BaseManager: 253b. 的子类，可用于管理跨进程的共享内存块。

     调用 *note SharedMemoryManager: 257f. 实例上的 *note start(): 253c.
     方法会启动一个新进程。这个新进程的唯一目的就是管理所有由它创建的共
     享内存块的生命周期。想要释放此进程管理的所有共享内存块，可以调用实
     例的 *note shutdown(): 2540. 方法。这会触发执行它管理的所有 *note
     SharedMemory: 2580. 对象的 ‘SharedMemory.unlink()’ 方法，然后停止这
     个进程。通过 ‘SharedMemoryManager’ 创建 ‘SharedMemory’ 实例，我们可
     以避免手动跟踪和释放共享内存资源。

     这个类提供了创建和返回 *note SharedMemory: 2580. 实例的方法，以及以
     共享内存为基础创建一个列表类对象 (*note ShareableList: 2581.) 的方
     法。

     有关继承的可选输入参数 `address' 和 `authkey' 以及他们如何用于从进
     程连接已经存在的 ‘SharedMemoryManager’ 服务，参见 *note
     multiprocessing.managers.BaseManager: 253b. 。

      -- 成員函式: SharedMemory (size)

          使用 ‘size’ 参数，创建一个新的指定字节大小的 *note
          SharedMemory: 2580. 对象并返回。

      -- 成員函式: ShareableList (sequence)

          创建并返回一个新的 *note ShareableList: 2581. 对象，通过输入参
          数 ‘sequence’ 初始化。

下面的案例展示了 ‘SharedMemoryManager’ 的基本机制:

     >>> 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

以下案例展示了 ‘SharedMemoryManager’ 对象的一种可能更方便的使用方式，通
过 *note with: 7da. 语句来保证所有共享内存块在使用完后被释放。

     >>> 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

在 *note with: 7da. 语句中使用 ‘SharedMemoryManager’  对象的时候，使用这
个管理器创建的共享内存块会在 *note with: 7da. 语句代码块结束后被释放。

 -- 類別: multiprocessing.shared_memory.ShareableList (sequence=None, *,
          name=None)

     提供一个可修改的类 list 对象，其中所有值都存放在共享内存块中。这限
     制了可被存储在其中的值只能是 ‘int’, ‘float’, ‘bool’, ‘str’ （每条数
     据小于10M）, ‘bytes’ （每条数据小于10M）以及 ‘None’ 这些内置类型。
     它另一个显著区别于内置 ‘list’ 类型的地方在于它的长度无法修改（比如
     ，没有 append, insert 等操作）且不支持通过切片操作动态创建新的
     *note ShareableList: 1055.  实例。

     `sequence' 会被用来为一个新的 ‘ShareableList’ 填充值。 设为 ‘None’
     则会基于唯一的共享内存名称关联到已经存在的 ‘ShareableList’。

     `name' 是所请求的共享内存的唯一名称，与 *note SharedMemory: 24e4. 的
     定义中所描述的一致。 当关联到现有的 ‘ShareableList’ 时，则指明其共
     享内存块的唯一名称并将 ‘sequence’ 设为 ‘None’。

      -- 成員函式: count (value)

          返回 ‘value’ 出现的次数。

      -- 成員函式: index (value)

          返回 ‘value’ 首次出现的位置，如果 ‘value’ 不存在, 则抛出 *note
          ValueError: 16d. 异常。

      -- 屬性: format

          包含由所有当前存储值所使用的 *note struct: f8. 打包格式的只读
          属性。

      -- 屬性: shm

          存储了值的 *note SharedMemory: 24e4. 实例。

下面的例子演示了 *note ShareableList: 1055. 实例的基本用法:

     >>> 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

下面的例子演示了一个、两个或多个进程如何通过提供下层的共享内存块名称来访
问同一个 *note ShareableList: 1055.:

     >>> 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()

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/Lib/multiprocessing/shared_memory.py

   (2) https://www.numpy.org/


File: python.info,  Node: concurrent 包,  Next: concurrent futures --- 启动并行任务,  Prev: multiprocessing shared_memory --- 可从进程直接访问的共享内存,  Up: 并发执行

5.17.4 ‘concurrent’ 包
----------------------

目前，此包中只有一个模块：

   * *note concurrent.futures: 21. —— 启动并行任务


File: python.info,  Node: concurrent futures --- 启动并行任务,  Next: subprocess --- 子进程管理,  Prev: concurrent 包,  Up: 并发执行

5.17.5 ‘concurrent.futures’ — 启动并行任务
------------------------------------------

3.2 版新加入.

`源码:' Lib/concurrent/futures/thread.py(1) 和
Lib/concurrent/futures/process.py(2)

__________________________________________________________________

*note concurrent.futures: 21. 模块提供异步执行回调高层接口。

异步执行可以由 *note ThreadPoolExecutor: 18c. 使用线程或由 *note
ProcessPoolExecutor: 196. 使用单独的进程来实现。 两者都是实现抽像类
*note Executor: 258a. 定义的接口。

* Menu:

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

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/Lib/concurrent/futures/thread.py

   (2) 
https://github.com/python/cpython/tree/3.9/Lib/concurrent/futures/process.py


File: python.info,  Node: Executor 对象,  Next: ThreadPoolExecutor,  Up: concurrent futures --- 启动并行任务

5.17.5.1 Executor 对象
......................

 -- 類別: concurrent.futures.Executor

     抽象类提供异步执行调用方法。要通过它的子类调用，而不是直接调用。

           -- 成員函式: submit (fn, /, *args, **kwargs)

               Schedules the callable, `fn', to be executed as
               ‘fn(*args, **kwargs)’ and returns a *note Future: c00.
               object representing the execution of the callable.

                    with ThreadPoolExecutor(max_workers=1) as executor:
                        future = executor.submit(pow, 323, 1235)
                        print(future.result())

           -- 成員函式: map (func, *iterables, timeout=None,
                    chunksize=1)

               类似于 *note map(func, *iterables): cf7. 函数，除了以下两
               点：

                  * `iterables' 是立即执行而不是延迟执行的；

                  * `func' 是异步执行的，对 `func' 的多个调用可以并发执
                    行。

               如果 *note __next__(): d2c. 已被调用且返回的结果在对
               *note Executor.map(): 7b1. 的原始调用经过 `timeout' 秒后
               还不可用，则已返回的迭代器将引发 *note
               concurrent.futures.TimeoutError: 258c.。 `timeout' 可以为
               int 或 float 类型。 如果 `timeout' 未指定或为 ‘None’，则
               不限制等待时间。

               如果 `func' 调用引发一个异常，当从迭代器中取回它的值时这
               个异常将被引发。

               使用 *note ProcessPoolExecutor: 196. 时，这个方法会将
               `iterables' 分割任务块并作为独立的任务并提交到执行池中。
               这些块的大概数量可以由 `chunksize' 指定正整数设置。 对很
               长的迭代器来说，使用大的 `chunksize' 值比默认值 1 能显著
               地提高性能。 `chunksize' 对 *note ThreadPoolExecutor:
               18c. 没有效果。

               3.5 版更變: 加入 `chunksize' 参数。

           -- 成員函式: shutdown (wait=True, *, cancel_futures=False)

               当待执行的 future 对象完成执行后向执行者发送信号，它就会
               释放正在使用的任何资源。 在关闭后调用 *note
               Executor.submit(): 3c6. 和 *note Executor.map(): 7b1. 将
               会引发 *note RuntimeError: 3dc.。

               如果 `wait' 为 ‘True’ 则此方法只有在所有待执行的 future 对
               象完成执行且释放已分配的资源后才会返回。 如果 `wait' 为
               ‘False’，方法立即返回，所有待执行的 future 对象完成执行后
               会释放已分配的资源。 不管 `wait' 的值是什么，整个 Python
               程序将等到所有待执行的 future 对象完成执行后才退出。

               如果 `cancel_futures' 为 ‘True’，此方法将取消所有执行器还
               未开始运行的挂起的 Future。 任何已完成或正在运行的 Future
               将不会被取消，无论 `cancel_futures' 的值是什么？

               如果 `cancel_futures' 和 `wait' 均为 ‘True’，则执行器已开
               始运行的所有 Future 将在此方法返回之前完成。 其余的
               Future 会被取消。

               如果使用 *note with: 7da. 语句，你就可以避免显式调用这个
               方法，它将会停止 *note Executor: 258a. (就好像 *note
               Executor.shutdown(): 195. 调用时 `wait' 设为 ‘True’ 一样
               等待):

                    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')

               3.9 版更變: 增加了 `cancel_futures'。


File: python.info,  Node: ThreadPoolExecutor,  Next: ProcessPoolExecutor,  Prev: Executor 对象,  Up: concurrent futures --- 启动并行任务

5.17.5.2 ThreadPoolExecutor
...........................

*note ThreadPoolExecutor: 18c. 是 *note Executor: 258a. 的子类，它使用线
程池来异步执行调用。

当回调已关联了一个 *note Future: c00. 然后再等待另一个 *note Future:
c00. 的结果时就会发生死锁情况。 例如:

     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)

And:

     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)

 -- 類別: concurrent.futures.ThreadPoolExecutor (max_workers=None,
          thread_name_prefix='', initializer=None, initargs=())

     *note Executor: 258a. 的一个子类，使用最多 `max_workers' 个线程的线
     程池来异步执行调用。

     `initializer' 是在每个工作者线程开始处调用的一个可选可调用对象。
     `initargs' 是传递给初始化器的元组参数。任何向池提交更多工作的尝试，
     `initializer' 都将引发一个异常，当前所有等待的工作都会引发一个
     *note BrokenThreadPool: 258e.。

     3.5 版更變: 如果 `max_workers' 为 ‘None’ 或没有指定，将默认为机器处
     理器的个数，假如 *note ThreadPoolExecutor: 18c. 侧重于 I/O 操作而不
     是 CPU 运算，那么可以乘以 ‘5’，同时工作线程的数量可以比 *note
     ProcessPoolExecutor: 196. 的数量高。

     3.6 版新加入: 添加 `thread_name_prefix' 参数允许用户控制由线程池创
     建的 *note threading.Thread: 21a. 工作线程名称以方便调试。

     3.7 版更變: 加入 `initializer' 和*initargs* 参数。

     3.8 版更變: `max_workers' 的默认值已改为 ‘min(32, os.cpu_count() +
     4)’。 这个默认值会保留至少 5 个工作线程用于 I/O 密集型任务。 对于那
     些释放了 GIL 的 CPU 密集型任务，它最多会使用 32 个 CPU 核心。这样能
     够避免在多核机器上不知不觉地使用大量资源。

     现在 ThreadPoolExecutor 在启动 `max_workers' 个工作线程之前也会重用
     空闲的工作线程。

* Menu:

* ThreadPoolExecutor 例子::


File: python.info,  Node: ThreadPoolExecutor 例子,  Up: ThreadPoolExecutor

5.17.5.3 ThreadPoolExecutor 例子
................................

     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://some-made-up-domain.com/']

     # 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)))


File: python.info,  Node: ProcessPoolExecutor,  Next: Future 对象,  Prev: ThreadPoolExecutor,  Up: concurrent futures --- 启动并行任务

5.17.5.4 ProcessPoolExecutor
............................

*note ProcessPoolExecutor: 196. 类是 *note Executor: 258a. 的子类，它使
用进程池来异步地执行调用。 *note ProcessPoolExecutor: 196. 会使用 *note
multiprocessing: b7. 模块，这允许它绕过 *note 全局解释器锁: 5ff. 但也意
味着只可以处理和返回可封存的对象。

‘__main__’ 模块必须可以被工作者子进程导入。这意味着 *note
ProcessPoolExecutor: 196. 不可以工作在交互式解释器中。

从提交给 *note ProcessPoolExecutor: 196. 的回调中调用 *note Executor:
258a. 或 *note Future: c00. 方法会导致死锁。

 -- 類別: concurrent.futures.ProcessPoolExecutor (max_workers=None,
          mp_context=None, initializer=None, initargs=())

     异步地执行调用的 *note Executor: 258a. 子类使用最多具有
     `max_workers' 个进程的进程池。 如果 `max_workers' 为 ‘None’ 或未给
     出，它将默认为机器的处理器个数。 如果 `max_workers' 小于等于 ‘0’，
     则将引发 *note ValueError: 16d.。 在 Windows 上，`max_workers' 必须
     小于等于 ‘61’，否则将引发 *note ValueError: 16d.。 如果
     `max_workers' 为 ‘None’，则所选择的默认值最多为 ‘61’，即使存在更多
     的处理器。 `mp_context' 可以是一个多进程上下文或是 None。 它将被用
     来启动工作进程。 如果 `mp_context' 为 ‘None’ 或未给出，则将使用默认
     的多进程上下文。

     `initializer' 是一个可选的可调用对象，它会在每个工作进程启动时被调
     用；`initargs' 是传给 initializer 的参数元组。 如果 `initializer' 引
     发了异常，则所有当前在等待的任务以及任何向进程池提交更多任务的尝试
     都将引发 *note BrokenProcessPool: 2591.。

     3.3 版更變: 如果其中一个工作进程被突然终止，‘BrokenProcessPool’ 就
     会马上触发。 可预计的行为没有定义，但执行器上的操作或它的 future 对
     象会被冻结或死锁。

     3.7 版更變: 添加 `mp_context' 参数允许用户控制由进程池创建给工作者
     进程的开始方法 。

     加入 `initializer' 和*initargs* 参数。

* Menu:

* ProcessPoolExecutor 例子::


File: python.info,  Node: ProcessPoolExecutor 例子,  Up: ProcessPoolExecutor

5.17.5.5 ProcessPoolExecutor 例子
.................................

     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()


File: python.info,  Node: Future 对象,  Next: 模块函数,  Prev: ProcessPoolExecutor,  Up: concurrent futures --- 启动并行任务

5.17.5.6 Future 对象
....................

*note Future: c00. 类将可调用对象封装为异步执行。*note Future: c00. 实例
由 *note Executor.submit(): 3c6. 创建。

 -- 類別: concurrent.futures.Future

     将可调用对象封装为异步执行。*note Future: c00. 实例由 *note
     Executor.submit(): 3c6. 创建，除非测试，不应直接创建。

           -- 成員函式: cancel ()

               尝试取消调用。 如果调用正在执行或已结束运行不能被取消则该
               方法将返回 ‘False’，否则调用会被取消并且该方法将返回
               ‘True’。

           -- 成員函式: cancelled ()

               如果调用成功取消返回 ‘True’。

           -- 成員函式: running ()

               如果调用正在执行而且不能被取消那么返回‘‘True‘‘。

           -- 成員函式: done ()

               如果调用已被取消或正常结束那么返回 ‘True’。

           -- 成員函式: result (timeout=None)

               返回调用返回的值。如果调用还没完成那么这个方法将等待
               `timeout' 秒。如果在 `timeout' 秒内没有执行完成，*note
               concurrent.futures.TimeoutError: 258c. 将会被触发。
               `timeout' 可以是整数或浮点数。如果 `timeout' 没有指定或为
               ‘None’，那么等待时间就没有限制。

               如果 futrue 在完成前被取消则 *note CancelledError: 2dd. 将
               被触发。

               如果调用引发了一个异常，这个方法也会引发同样的异常。

           -- 成員函式: exception (timeout=None)

               返回由调用引发的异常。如果调用还没完成那么这个方法将等待
               `timeout' 秒。如果在 `timeout' 秒内没有执行完成，*note
               concurrent.futures.TimeoutError: 258c. 将会被触发。
               `timeout' 可以是整数或浮点数。如果 `timeout' 没有指定或为
               ‘None’，那么等待时间就没有限制。

               如果 futrue 在完成前被取消则 *note CancelledError: 2dd. 将
               被触发。

               如果调用正常完成那么返回 ‘None’。

           -- 成員函式: add_done_callback (fn)

               附加可调用 `fn' 到 future 对象。当 future 对象被取消或完
               成运行时，将会调用 `fn'，而这个 future 对象将作为它唯一的
               参数。

               加入的可调用对象总被属于添加它们的进程中的线程按加入的顺
               序调用。如果可调用对象引发一个 *note Exception: 2dc. 子类
               ，它会被记录下来并被忽略掉。如果可调用对象引发一个 *note
               BaseException: 2db. 子类，这个行为没有定义。

               如果 future 对象已经完成或已取消，`fn' 会被立即调用。

     下面这些 *note Future: c00. 方法用于单元测试和 *note Executor:
     258a. 实现。

           -- 成員函式: set_running_or_notify_cancel ()

               这个方法只可以在执行关联 *note Future: c00. 工作之前由
               *note Executor: 258a. 实现调用或由单测试调用。

               如果这个方法返回 ‘False’ 那么 *note Future: c00. 已被取消
               ，即 *note Future.cancel(): 2594. 已被调用并返回 ‘True’ 。
               等待 *note Future: c00. 完成 (即通过 *note
               as_completed(): 1223. 或 *note wait(): f50.) 的线程将被唤
               醒。

               如果这个方法返回 ‘True’ 那么 *note Future: c00. 不会被取
               消并已将它变为正在运行状态，也就是说调用 *note
               Future.running(): 2596. 时将返回 ‘True’。

               这个方法只可以被调用一次并且不能在调用 *note
               Future.set_result(): 259c. 或 *note
               Future.set_exception(): 259d. 之后再调用。

           -- 成員函式: set_result (result)

               设置将 *note Future: c00. 关联工作的结果给 `result' 。

               这个方法只可以由 *note Executor: 258a. 实现和单元测试使用
               。

               3.8 版更變: 如果 *note Future: c00. 已经完成则此方法会引
               发 *note concurrent.futures.InvalidStateError: 259e.。

           -- 成員函式: set_exception (exception)

               设置 *note Future: c00. 关联工作的结果给 *note Exception:
               2dc. `exception' 。

               这个方法只可以由 *note Executor: 258a. 实现和单元测试使用
               。

               3.8 版更變: 如果 *note Future: c00. 已经完成则此方法会引
               发 *note concurrent.futures.InvalidStateError: 259e.。


File: python.info,  Node: 模块函数,  Next: Exception 类,  Prev: Future 对象,  Up: concurrent futures --- 启动并行任务

5.17.5.7 模块函数
.................

 -- 函式: concurrent.futures.wait (fs, timeout=None,
          return_when=ALL_COMPLETED)

     Wait for the *note Future: c00. instances (possibly created by
     different *note Executor: 258a. instances) given by `fs' to
     complete.  Duplicate futures given to `fs' are removed and will be
     returned only once.  Returns a named 2-tuple of sets.  The first
     set, named ‘done’, contains the futures that completed (finished or
     cancelled futures) before the wait completed.  The second set,
     named ‘not_done’, contains the futures that did not complete
     (pending or running futures).

     `timeout' 可以用来控制返回前最大的等待秒数。 `timeout' 可以为 int 或
     float 类型。 如果 `timeout' 未指定或为 ‘None’ ，则不限制等待时间。

     `return_when' 指定此函数应在何时返回。它必须为以下常数之一:

     常数                              描述
                                       
     -------------------------------------------------------------------------------
                                       
     ‘FIRST_COMPLETED’                 函数将在任意可等待对象结束或取消时返回。
                                       
                                       
     ‘FIRST_EXCEPTION’                 函数将在任意可等待对象因引发异常而结束时返
                                       回。当没有引发任何异常时它就相当于
                                       ‘ALL_COMPLETED’。
                                       
                                       
     ‘ALL_COMPLETED’                   函数将在所有可等待对象结束或取消时返回。
                                       

 -- 函式: concurrent.futures.as_completed (fs, timeout=None)

     返回一个包含 `fs' 所指定的 *note Future: c00. 实例（可能由不同的
     *note Executor: 258a. 实例创建）的迭代器，这些实例会在完成时生成
     future 对象（包括正常结束或被取消的 future 对象）。 任何由 `fs' 所
     指定的重复 future 对象将只被返回一次。 任何在 *note as_completed():
     1223. 被调用之前完成的 future 对象将优先被生成。 如果 *note
     __next__(): d2c. 被调用并且在对 *note as_completed(): 1223. 的原始
     调用 `timeout' 秒之后结果仍不可用，则返回的迭代器将引发 *note
     concurrent.futures.TimeoutError: 258c.。 `timeout' 可以为整数或浮点
     数。 如果 `timeout' 未指定或为 ‘None’，则不限制等待时间。

也參考
......

PEP 3148(1) – futures - 异步执行指令。

     该提案描述了Python标准库中包含的这个特性。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3148


File: python.info,  Node: Exception 类,  Prev: 模块函数,  Up: concurrent futures --- 启动并行任务

5.17.5.8 Exception 类
.....................

 -- 例外: concurrent.futures.CancelledError

     future 对象被取消时会触发。

 -- 例外: concurrent.futures.TimeoutError

     future 对象执行超出给定的超时数值时引发。

 -- 例外: concurrent.futures.BrokenExecutor

     当执行器被某些原因中断而且不能用来提交或执行新任务时就会被引发派生
     于 *note RuntimeError: 3dc. 的异常类。

     3.7 版新加入.

 -- 例外: concurrent.futures.InvalidStateError

     当某个操作在一个当前状态所不允许的 future 上执行时将被引发。

     3.8 版新加入.

 -- 例外: concurrent.futures.thread.BrokenThreadPool

     当 ‘ThreadPoolExecutor’ 中的其中一个工作者初始化失败时会引发派生于
     *note BrokenExecutor: 25a1. 的异常类。

     3.7 版新加入.

 -- 例外: concurrent.futures.process.BrokenProcessPool

     当 ‘ThreadPoolExecutor’ 中的其中一个工作者不完整终止时(比如，被外部
     杀死)会引发派生于 *note BrokenExecutor: 25a1. ( 原名 *note
     RuntimeError: 3dc. ) 的异常类。

     3.3 版新加入.


File: python.info,  Node: subprocess --- 子进程管理,  Next: sched --- 事件调度器,  Prev: concurrent futures --- 启动并行任务,  Up: 并发执行

5.17.6 ‘subprocess’ — 子进程管理
--------------------------------

`源代码:' Lib/subprocess.py(1)

__________________________________________________________________

*note subprocess: f9. 模块允许你生成新的进程，连接它们的输入、输出、错误
管道，并且获取它们的返回码。此模块打算代替一些老旧的模块与功能：

     os.system
     os.spawn*

在下面的段落中，你可以找到关于 *note subprocess: f9. 模块如何代替这些模
块和功能的相关信息。

也參考
......

PEP 324(2) – 提出 subprocess 模块的 PEP

* Menu:

* 使用 subprocess 模块::
* 安全考量::
* Popen 对象::
* Windows Popen 助手::
* 较旧的高阶 API::
* 使用 subprocess 模块替换旧函数::
* 旧式的 Shell 发起函数::
* 註解::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/subprocess.py

   (2) https://www.python.org/dev/peps/pep-0324


File: python.info,  Node: 使用 subprocess 模块,  Next: 安全考量,  Up: subprocess --- 子进程管理

5.17.6.1 使用 ‘subprocess’ 模块
...............................

推荐的调用子进程的方式是在任何它支持的用例中使用 *note run(): 4f2. 函数
。对于更进阶的用例，也可以使用底层的 *note Popen: 3db. 接口。

*note run(): 4f2. 函数是在 Python 3.5 被添加的；如果你需要与旧版本保持兼
容，查看 *note 较旧的高阶 API: 25a5. 段落。

 -- 函式: 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)

     运行被 `arg' 描述的指令。等待指令完成，然后返回一个 *note
     CompletedProcess: 84f. 实例。

     以上显示的参数仅仅是最简单的一些，下面 *note 常用参数: 25a6. 描述（
     因此在缩写签名中使用仅关键字标示）。完整的函数头和 *note Popen:
     3db. 的构造函数一样，此函数接受的大多数参数都被传递给该接口。（
     `timeout', `input', `check' 和 `capture_output' 除外）。

     如果 `capture_output' 设为 true，stdout 和 stderr 将会被捕获。在使
     用时，内置的 *note Popen: 3db. 对象将自动用 ‘stdout=PIPE’ 和
     ‘stderr=PIPE’ 创建。`stdout' 和 `stderr' 参数不应当与
     `capture_output' 同时提供。如果你希望捕获并将两个流合并在一起，使用
     ‘stdout=PIPE’ 和 ‘stderr=STDOUT’ 来代替 `capture_output'。

     `timeout' 参数将被传递给 *note Popen.communicate(): 25a7.。如果发生
     超时，子进程将被杀死并等待。 *note TimeoutExpired: 25a8. 异常将在子
     进程中断后被抛出。

     `input' 参数将被传递给 *note Popen.communicate(): 25a7. 以及子进程
     的标准输入。 如果使用此参数，它必须是一个字节序列。 如果指定了
     `encoding' 或 `errors' 或者将 `text' 设置为 ‘True’，那么也可以是一
     个字符串。 当使用此参数时，在创建内部 *note Popen: 3db. 对象时将自
     动带上 ‘stdin=PIPE’，并且不能再手动指定 `stdin' 参数。

     如果 `check' 设为 True, 并且进程以非零状态码退出, 一个 *note
     CalledProcessError: d7d. 异常将被抛出. 这个异常的属性将设置为参数,
     退出码, 以及标准输出和标准错误, 如果被捕获到.

     如果 `encoding' 或者 `error' 被指定, 或者 `text' 被设为 True, 标准
     输入, 标准输出和标准错误的文件对象将通过指定的 `encoding' 和
     `errors' 以文本模式打开, 否则以默认的 *note io.TextIOWrapper: 6ea.
     打开.  `universal_newline' 参数等同于 `text' 并且提供了向后兼容性.
     默认情况下, 文件对象是以二进制模式打开的.

     如果 `env' 不是 ‘None’, 它必须是一个字典, 为新的进程设置环境变量; 它
     用于替换继承的当前进程的环境的默认行为. 它将直接被传递给 *note
     Popen: 3db.

     例如:

          >>> 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'')

     3.5 版新加入.

     3.6 版更變: 添加了 `encoding' 和 `errors' 形参.

     3.7 版更變: 添加了 `text' 形参, 作为 `universal_newlines' 的一个更
     好理解的别名. 添加了 `capture_output' 形参.

 -- 類別: subprocess.CompletedProcess

     *note run(): 4f2. 的返回值, 代表一个进程已经结束.

      -- 屬性: args

          被用作启动进程的参数. 可能是一个列表或字符串.

      -- 屬性: returncode

          子进程的退出状态码. 通常来说, 一个为 0 的退出码表示进程运行正
          常.

          一个负值 ‘-N’ 表示子进程被信号 ‘N’ 中断 (仅 POSIX).

      -- 屬性: stdout

          从子进程捕获到的标准输出. 一个字节序列, 或一个字符串, 如果
          *note run(): 4f2. 是设置了 `encoding', `errors' 或者
          ‘text=True’ 来运行的. 如果未有捕获, 则为 ‘None’.

          如果你通过 ‘stderr=subprocess.STDOUT’ 运行进程，标准输入和标准
          错误将被组合在这个属性中，并且 *note stderr: 25ac. 将为
          ‘None’。

      -- 屬性: stderr

          捕获到的子进程的标准错误. 一个字节序列, 或者一个字符串, 如果
          *note run(): 4f2. 是设置了参数 `encoding', `errors' 或者
          ‘text=True’ 运行的. 如果未有捕获, 则为 ‘None’.

      -- 成員函式: check_returncode ()

          如果 *note returncode: 25aa. 非零, 抛出 *note
          CalledProcessError: d7d.

     3.5 版新加入.

 -- Data: subprocess.DEVNULL

     可被 *note Popen: 3db. 的 `stdin', `stdout' 或者 `stderr' 参数使用
     的特殊值, 表示使用特殊文件 *note os.devnull: 1152.

     3.3 版新加入.

 -- Data: subprocess.PIPE

     可被 *note Popen: 3db. 的 `stdin', `stdout' 或者 `stderr' 参数使用
     的特殊值, 表示打开标准流的管道. 常用于 *note Popen.communicate():
     25a7.

 -- Data: subprocess.STDOUT

     可被 *note Popen: 3db. 的 `stdin' ， `stdout' 或者 `stderr' 参数使
     用的特殊值， 表示标准错误与标准输出使用同一句柄。

 -- 例外: subprocess.SubprocessError

     此模块的其他异常的基类。

     3.3 版新加入.

 -- 例外: subprocess.TimeoutExpired

     *note SubprocessError: 25af. 的子类，等待子进程的过程中发生超时时被
     抛出。

      -- 屬性: cmd

          用于创建子进程的指令。

      -- 屬性: timeout

          超时秒数。

      -- 屬性: output

          子进程的输出， 如果被 *note run(): 4f2. 或 *note
          check_output(): 9c1. 捕获。否则为 ‘None’。

      -- 屬性: stdout

          对 output 的别名，对应的有 *note stderr: 25b4.。

      -- 屬性: stderr

          子进程的标准错误输出，如果被 *note run(): 4f2. 捕获。 否则为
          ‘None’。

     3.3 版新加入.

     3.5 版更變: 添加了 `stdout' 和 `stderr' 属性。

 -- 例外: subprocess.CalledProcessError

     *note SubprocessError: 25af. 的子类，当一个被 *note check_call():
     25b5. 或 *note check_output(): 9c1. 函数运行的子进程返回了非零退出
     码时被抛出。

      -- 屬性: returncode

          子进程的退出状态。如果程序由一个信号终止，这将会被设为一个负的
          信号码。

      -- 屬性: cmd

          用于创建子进程的指令。

      -- 屬性: output

          子进程的输出， 如果被 *note run(): 4f2. 或 *note
          check_output(): 9c1. 捕获。否则为 ‘None’。

      -- 屬性: stdout

          对 output 的别名，对应的有 *note stderr: 25ba.。

      -- 屬性: stderr

          子进程的标准错误输出，如果被 *note run(): 4f2. 捕获。 否则为
          ‘None’。

     3.5 版更變: 添加了 `stdout' 和 `stderr' 属性。

* Menu:

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


File: python.info,  Node: 常用参数,  Next: Popen 构造函数,  Up: 使用 subprocess 模块

5.17.6.2 常用参数
.................

为了支持丰富的使用案例， *note Popen: 3db. 的构造函数（以及方便的函数）
接受大量可选的参数。对于大多数典型的用例，许多参数可以被安全地留以它们的
默认值。通常需要的参数有：

     `args' 被所有调用需要，应当为一个字符串，或者一个程序参数序列。提供
     一个参数序列通常更好，它可以更小心地使用参数中的转义字符以及引用（
     例如允许文件名中的空格）。如果传递一个简单的字符串，则 `shell' 参数
     必须为 *note True: 593. （见下文）或者该字符串中将被运行的程序名必
     须用简单的命名而不指定任何参数。

     `stdin'， `stdout' 和 `stderr' 分别指定了执行的程序的标准输入、输出
     和标准错误文件句柄。合法的值有 *note PIPE: 4f3. 、 *note DEVNULL:
     b78. 、 一个现存的文件描述符（一个正整数）、一个现存的文件对象以及
     ‘None’。 *note PIPE: 4f3. 表示应该新建一个对子进程的管道。 *note
     DEVNULL: b78. 表示使用特殊的文件 *note os.devnull: 1152.。当使用默
     认设置 ‘None’ 时，将不会进行重定向，子进程的文件流将继承自父进程。
     另外， `stderr' 可能为 *note STDOUT: 25ae.，表示来自于子进程的标准
     错误数据应该被 `stdout' 相同的句柄捕获。

     如果 `encoding' 或 `errors' 被指定，或者 `text' （也名为
     `universal_newlines'）为真，则文件对象 `stdin' 、 `stdout' 与
     `stderr' 将会使用在此次调用中指定的 `encoding' 和 `errors' 以文本模
     式打开或者为默认的 *note io.TextIOWrapper: 6ea.。

     当构造函数的 `newline' 参数为 ‘None’ 时。对于 `stdin'， 输入的换行
     符 ‘'\n'’ 将被转换为默认的换行符 *note os.linesep: 1732.。对于
     `stdout' 和 `stderr'， 所有输出的换行符都被转换为 ‘'\n'’。更多信息
     ，查看 *note io.TextIOWrapper: 6ea. 类的文档。

     如果文本模式未被使用， `stdin'， `stdout' 和 `stderr' 将会以二进制
     流模式打开。没有编码与换行符转换发生。

     3.6 版新加入: 添加了 `encoding' 和 `errors' 形参。

     3.7 版新加入: 添加了 `text' 形参作为 `universal_newlines' 的别名。

          備註: 文件对象 *note Popen.stdin: 25bc. 、 *note Popen.stdout:
          25bd. 和 *note Popen.stderr: 25be. 的换行符属性不会被 *note
          Popen.communicate(): 25a7. 方法更新。

     如果 `shell' 设为 ‘True’,，则使用 shell 执行指定的指令。如果您主要
     使用 Python 增强的控制流（它比大多数系统 shell 提供的强大），并且仍
     然希望方便地使用其他 shell 功能，如 shell 管道、文件通配符、环境变
     量展开以及 ‘~’ 展开到用户家目录，这将非常有用。但是，注意 Python 自
     己也实现了许多类似 shell 的特性（例如 *note glob: 88, *note
     fnmatch: 7f, *note os.walk(): 747, *note os.path.expandvars(): e09,
     *note os.path.expanduser(): 32c. 和 *note shutil: e9.）。

     3.3 版更變: 当 `universal_newline' 被设为 ‘True’，则类使用 *note
     locale.getpreferredencoding(False): 4ab. 编码来代替
     ‘locale.getpreferredencoding()’。关于它们的区别的更多信息，见 *note
     io.TextIOWrapper: 6ea.。

          備註: 在使用 ‘shell=True’ 之前， 请阅读 *note Security
          Considerations: 25bf. 段落。

这些选项以及所有其他选项在 *note Popen: 3db. 构造函数文档中有更详细的描
述。


File: python.info,  Node: Popen 构造函数,  Next: 异常<7>,  Prev: 常用参数,  Up: 使用 subprocess 模块

5.17.6.3 Popen 构造函数
.......................

此模块的底层的进程创建与管理由 *note Popen: 3db. 类处理。它提供了很大的
灵活性，因此开发者能够处理未被便利函数覆盖的不常见用例。

 -- 類別: 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，此类使用类似于 *note
     os.execvp(): 20ec. 的行为来执行子程序。在 Windows，此类使用了
     Windows ‘CreateProcess()’ 函数。 *note Popen: 3db. 的参数如下：

     `args' 应当是一个程序参数的序列或者是一个单独的字符串或 *note
     path-like object: 472.。 默认情况下，如果 `args' 是序列则要运行的程
     序为 `args' 中的第一项。 如果 `args' 是字符串，则其解读依赖于具体平
     台，如下所述。 请查看 `shell' 和 `executable' 参数了解其与默认行为
     的其他差异。 除非另有说明，否则推荐以序列形式传入 `args'。

     向外部函数传入序列形式参数的一个例子如下:

          Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])

     在 POSIX，如果 `args' 是一个字符串，此字符串被作为将被执行的程序的
     命名或路径解释。但是，只有在不传递任何参数给程序的情况下才能这么做
     。

          備註: 将 shell 命令拆分为参数序列的方式可能并不很直观，特别是
          在复杂的情况下。 *note shlex.split(): 210. 可以演示如何确定
          `args' 适当的拆分形式:

               >>> 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!

          特别注意，由 shell 中的空格分隔的选项（例如 `-input'）和参数（
          例如 `eggs.txt' ）位于分开的列表元素中，而在需要时使用引号或反
          斜杠转义的参数在 shell （例如包含空格的文件名或上面显示的
          `echo' 命令）是单独的列表元素。

     在 Windows，如果 `args' 是一个序列，他将通过一个在 *note 在 Windows
     上将参数列表转换为一个字符串: 25c1. 描述的方式被转换为一个字符串。
     这是因为底层的 ‘CreateProcess()’ 只处理字符串。

     3.6 版更變: 在 POSIX 上如果 `shell' 为 ‘False’ 并且序列包含路径类对
     象则 `args' 形参可以接受一个 *note path-like object: 472.。

     3.8 版更變: 如果在Windows 上 `shell' 为 ‘False’ 并且序列包含字节串
     和路径类对象则 `args' 形参可以接受一个 *note path-like object:
     472.。

     参数 `shell' （默认为 ‘False’）指定是否使用 shell 执行程序。如果
     `shell' 为 ‘True’，更推荐将 `args' 作为字符串传递而非序列。

     在 POSIX，当 ‘shell=True’， shell 默认为 ‘/bin/sh’。如果 `args' 是
     一个字符串，此字符串指定将通过 shell 执行的命令。这意味着字符串的格
     式必须和在命令提示符中所输入的完全相同。这包括，例如，引号和反斜杠
     转义包含空格的文件名。如果 `args' 是一个序列，第一项指定了命令，另
     外的项目将作为传递给 shell （而非命令） 的参数对待。也就是说，
     *note Popen: 3db. 等同于:

          Popen(['/bin/sh', '-c', args[0], args[1], ...])

     在 Windows，使用 ‘shell=True’，环境变量 ‘COMSPEC’ 指定了默认 shell。
     在 Windows 你唯一需要指定 ‘shell=True’ 的情况是你想要执行内置在
     shell 中的命令（例如 ‘dir’ 或者 ‘copy’）。在运行一个批处理文件或者
     基于控制台的可执行文件时，不需要 ‘shell=True’。

          備註: 在使用 ‘shell=True’ 之前， 请阅读 *note Security
          Considerations: 25bf. 段落。

     `bufsize' 将在 *note open(): 16f. 函数创建了 stdin/stdout/stderr 管
     道文件对象时作为对应的参数供应:

        - ‘0’ 表示不使用缓冲区 （读取与写入是一个系统调用并且可以返回短
          内容）

        - ‘1’ 表示行缓冲（只有 ‘universal_newlines=True’ 时才有用，例如
          ，在文本模式中）

        - 任何其他正值表示使用一个约为对应大小的缓冲区

        - 负的 `bufsize' （默认）表示使用系统默认的
          io.DEFAULT_BUFFER_SIZE。

     3.3.1 版更變: `bufsize' 现在默认为 -1 来启用缓冲，以符合大多数代码
     所期望的行为。在 Python 3.2.4 和 3.3.1 之前的版本中，它错误地将默认
     值设为了为 ‘0’，这是无缓冲的并且允许短读取。这是无意的，并且与大多
     数代码所期望的 Python 2 的行为不一致。

     `executable' 参数指定一个要执行的替换程序。这很少需要。当
     ‘shell=True’， `executable' 替换 `args' 指定运行的程序。但是，原始
     的 `args' 仍然被传递给程序。大多数程序将被 `args' 指定的程序作为命
     令名对待，这可以与实际运行的程序不同。在 POSIX， `args' 名作为实际
     调用程序中可执行文件的显示名称，例如 ‘ps’。如果 ‘shell=True’，在
     POSIX， `executable' 参数指定用于替换默认 shell ‘/bin/sh’ 的 shell。

     3.6 版更變: 在POSIX 上 `executable' 形参可以接受一个 *note
     path-like object: 472.。

     3.8 版更變: 在Windows 上 `executable' 形参可以接受一个字节串和
     *note path-like object: 472.。

     `stdin', `stdout' 和 `stderr' 分别指定被运行的程序的标准输入、输出
     和标准错误的文件句柄。合法的值有 *note PIPE: 4f3. ， *note DEVNULL:
     b78. ， 一个存在的文件描述符（一个正整数），一个存在的 *note
     文件对象: c14. 以及 ‘None’。 *note PIPE: 4f3. 表示应创建一个新的对
     子进程的管道。 *note DEVNULL: b78. 表示使用特殊的 *note os.devnull:
     1152. 文件。使用默认的 ‘None’，则不进行成定向；子进程的文件流将继承
     自父进程。另外， `stderr' 可设为 *note STDOUT: 25ae.，表示应用程序
     的标准错误数据应和标准输出一同捕获。

     如果 `preexec_fn' 被设为一个可调用对象，此对象将在子进程刚创建时被
     调用。（仅 POSIX）

          警告: `preexec_fn' 形参在应用程序中存在多线程时是不安全的。子
          进程在调用前可能死锁。如果你必须使用它，保持警惕！最小化你调用
          的库的数量。

          備註: 如果你需要修改子进程环境，使用 `env' 形参而非在
          `preexec_fn' 中进行。 `start_new_session' 形参可以代替之前常用
          的 `preexec_fn' 来在子进程中调用 os.setsid()。

     3.8 版更變: `preexec_fn' 形参在子解释器中已不再受支持。 在子解释器
     中使用此形参将引发 *note RuntimeError: 3dc.。 这个新限制可能会影响
     部署在 mod_wsgi, uWSGI 和其他嵌入式环境中的应用。

     如果 `close_fds' 为真，所有文件描述符除了 ‘0’, ‘1’, ‘2’ 之外都会在
     子进程执行前关闭。而当 `close_fds' 为假时，文件描述符遵守它们继承的
     标志，如 *note 文件描述符的继承: 8e7. 所述。

     在 Windows，如果 `close_fds' 为真， 则子进程不会继承任何句柄，除非
     在 ‘STARTUPINFO.IpAttributeList’ 的 ‘handle_list’ 的键中显式传递，
     或者通过标准句柄重定向传递。

     3.2 版更變: `close_fds' 的默认值已经从 *note False: 48e. 修改为上述
     值。

     3.7 版更變: 在 Windows，当重定向标准句柄时 `close_fds' 的默认值从
     *note False: 48e. 变为 *note True: 593.。现在重定向标准句柄时有可能
     设置 `close_fds' 为 *note True: 593.。（标准句柄指三个 stdio 的句柄
     ）

     `pass_fds' 是一个可选的在父子进程间保持打开的文件描述符序列。提供任
     何 `pass_fds' 将强制 `close_fds' 为 *note True: 593.。（仅 POSIX）

     3.2 版更變: 加入了 `pass_fds' 形参。

     如果 `cwd' 不为 ‘None’，此函数在执行子进程前会将当前工作目录改为
     `cwd'。 `cwd' 可以是一个字符串、字节串或 *note 路径类对象: 472. 。
     特别地，当可执行文件的路径为相对路径时，此函数会相对于*cwd* 来查找
     `executable' (或 `args' 中的第一个条目)。

     3.6 版更變: 在 POSIX 上 `cwd' 形参接受一个 *note path-like object:
     472.。

     3.7 版更變: 在 Windows 上 `cwd' 形参接受一个 *note path-like
     object: 472.。

     3.8 版更變: 在 Windows 上 `cwd' 形参接受一个字节串对象。

     如果 `restore_signals' 为 true（默认值），则 Python 设置为 SIG_IGN
     的所有信号将在 exec 之前的子进程中恢复为 SIG_DFL。目前，这包括
     SIGPIPE ，SIGXFZ 和 SIGXFSZ 信号。 （仅 POSIX）

     3.2 版更變: `restore_signals' 被加入。

     如果 `start_new_session' 为 true，则 setsid() 系统调用将在子进程执
     行之前被执行。（仅 POSIX）

     3.2 版更變: `start_new_session' 被添加。

     如果 `group' 不为 ‘None’，则 setregid() 系统调用将于子进程执行之前
     在下级进程中进行。 如果所提供的值为一个字符串，将通过 *note
     grp.getgrnam(): 1162. 来查找它，并将使用 ‘gr_gid’ 中的值。 如果该值
     为一个整数，它将被原样传递。 （POSIX 专属）

     *note 可用性: 1491.: POSIX

     3.9 版新加入.

     如果 `extra_groups' 不为 ‘None’，则 setgroups() 系统调用将于子进程
     之前在下级进程中进行。 在 `extra_groups' 中提供的字符串将通过 *note
     grp.getgrnam(): 1162. 来查找，并将使用 ‘gr_gid’ 中的值。 整数值将被
     原样传递。 （POSIX 专属）

     *note 可用性: 1491.: POSIX

     3.9 版新加入.

     如果 `user' 不为 ‘None’，则 setreuid() 系统调用将于子进程执行之前在
     下级进程中进行。 如果所提供的值为一个字符串，将通过 *note
     pwd.getpwnam(): 1161. 来查找它，并将使用 ‘pw_uid’ 中的值。 如果该值
     为一个整数，它将被原样传递。 （POSIX 专属）

     *note 可用性: 1491.: POSIX

     3.9 版新加入.

     如果 `umask' 不为负值，则 umask() 系统调用将在子进程执行之前在下级
     进程中进行。

     *note 可用性: 1491.: POSIX

     3.9 版新加入.

     如果 `env' 不为 ‘None’，则必须为一个为新进程定义了环境变量的字典；
     这些用于替换继承的当前进程环境的默认行为。

          備註: 如果指定， `env' 必须提供所有被子进程需求的变量。在
          Windows，为了运行一个 side-by-side assembly(1) ，指定的 `env'
          `必须' 包含一个有效的 ‘SystemRoot’。

     如果 `encoding' 或 `errors' 被指定，或者 `text' 为 true，则文件对象
     `stdin', `stdout' 和 `stderr' 将会以指定的编码和 `errors' 以文本模
     式打开，如同 *note 常用参数: 25a6. 所述。 `universal_newlines' 参数
     等同于 `text' 并且提供向后兼容性。默认情况下，文件对象都以二进制模
     式打开。

     3.6 版新加入: `encoding' 和 `errors' 被添加。

     3.7 版新加入: `text' 作为 `universal_newlines' 的一个更具可读性的别
     名被添加。

     如果给出， `startupinfo' 将是一个将被传递给底层的 ‘CreateProcess’ 函
     数的 *note STARTUPINFO: 25c2. 对象。 `creationflags'，如果给出，可
     以是一个或多个以下标志之一：

             * *note CREATE_NEW_CONSOLE: 25c3.

             * *note CREATE_NEW_PROCESS_GROUP: 25c4.

             * *note ABOVE_NORMAL_PRIORITY_CLASS: 25c5.

             * *note BELOW_NORMAL_PRIORITY_CLASS: 25c6.

             * *note HIGH_PRIORITY_CLASS: 25c7.

             * *note IDLE_PRIORITY_CLASS: 25c8.

             * *note NORMAL_PRIORITY_CLASS: 25c9.

             * *note REALTIME_PRIORITY_CLASS: 25ca.

             * *note CREATE_NO_WINDOW: 25cb.

             * *note DETACHED_PROCESS: 25cc.

             * *note CREATE_DEFAULT_ERROR_MODE: 25cd.

             * *note CREATE_BREAKAWAY_FROM_JOB: 25ce.

     Popen 对象支持通过 *note with: 7da. 语句作为上下文管理器，在退出时
     关闭文件描述符并等待进程:

          with Popen(["ifconfig"], stdout=PIPE) as proc:
              log.write(proc.stdout.read())

     引发一个 *note 审计事件: fa1. ‘subprocess.Popen’，附带参数
     ‘executable’, ‘args’, ‘cwd’, ‘env’。

     3.2 版更變: 添加了上下文管理器支持。

     3.6 版更變: 现在，如果 Popen 析构时子进程仍然在运行，则析构器会发送
     一个 *note ResourceWarning: 5ca. 警告。

     3.8 版更變: 在某些情况下 Popen 可以使用 *note os.posix_spawn():
     381. 以获得更好的性能。在适用于 Linux 的 Windows 子系统和 QEMU 用户
     模拟器上，使用 *note os.posix_spawn(): 381. 的 Popen 构造器不再会因
     找不到程序等错误而引发异常，而是上下级进程失败并返回一个非零的
     *note returncode: 10a5.。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Side-by-Side_Assembly


File: python.info,  Node: 异常<7>,  Prev: Popen 构造函数,  Up: 使用 subprocess 模块

5.17.6.4 异常
.............

在子进程中抛出的异常，在新的进程开始执行前，将会被再次在父进程中抛出。

被引发的最一般异常是 *note OSError: 304.。 例如这会在尝试执行一个不存在
的文件时发生。 应用程序应当为 *note OSError: 304. 异常做好准备。 请注意
，如果 ‘shell=True’，则 *note OSError: 304. 仅会在未找到选定的 shell 本
身时被引发。 要确定 shell 是否未找到所请求的应用程序，必须检查来自子进程
的返回码或输出。

如果 *note Popen: 3db. 调用时有无效的参数，则一个 *note ValueError: 16d.
将被抛出。

*note check_call(): 25b5. 与 *note check_output(): 9c1. 在调用的进程返回
非零退出码时将抛出 *note CalledProcessError: d7d.。

所有接受 `timeout' 形参的函数与方法，例如 *note call(): 4f4. 和 *note
Popen.communicate(): 25a7. 将会在进程退出前超时到期时抛出 *note
TimeoutExpired: 25a8.。

此模块中定义的异常都继承自 *note SubprocessError: 25af.。

     3.3 版新加入: 基类 *note SubprocessError: 25af. 被添加。


File: python.info,  Node: 安全考量,  Next: Popen 对象,  Prev: 使用 subprocess 模块,  Up: subprocess --- 子进程管理

5.17.6.5 安全考量
.................

不像一些其他的 popen 功能，此实现绝不会隐式调用一个系统 shell。这意味着
任何字符，包括 shell 元字符，可以安全地被传递给子进程。如果 shell 被明确
地调用，通过 ‘shell=True’ 设置，则确保所有空白字符和元字符被恰当地包裹在
引号内以避免 shell 注入(1) 漏洞就由应用程序负责了。

当使用 ‘shell=True’， *note shlex.quote(): b4e. 函数可以作为在将被用于构
造 shell 指令的字符串中转义空白字符以及 shell 元字符的方案。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Shell_injection#Shell_injection


File: python.info,  Node: Popen 对象,  Next: Windows Popen 助手,  Prev: 安全考量,  Up: subprocess --- 子进程管理

5.17.6.6 Popen 对象
...................

*note Popen: 3db. 类的实例拥有以下方法：

 -- 成員函式: Popen.poll ()

     检查子进程是否已被终止。设置并返回 *note returncode: 10a5. 属性。否
     则返回 ‘None’。

 -- 成員函式: Popen.wait (timeout=None)

     等待子进程被终止。设置并返回 *note returncode: 10a5. 属性。

     如果进程在 `timeout' 秒后未中断，抛出一个 *note TimeoutExpired:
     25a8. 异常，可以安全地捕获此异常并重新等待。

          備註: 当 ‘stdout=PIPE’ 或者 ‘stderr=PIPE’ 并且子进程产生了足以
          阻塞 OS 管道缓冲区接收更多数据的输出到管道时，将会发生死锁。当
          使用管道时用 *note Popen.communicate(): 25a7. 来规避它。

          備註: 此函数使用了一个 busy loop （非阻塞调用以及短睡眠） 实现
          。使用 *note asyncio: 9. 模块进行异步等待： 参阅 *note
          asyncio.create_subprocess_exec: 3b4.。

     3.3 版更變: `timeout' 被添加

 -- 成員函式: Popen.communicate (input=None, timeout=None)

     与进程交互：将数据发送到 stdin。 从 stdout 和 stderr 读取数据，直到
     抵达文件结尾。 等待进程终止并设置 *note returncode: 10a5. 属性。 可
     选的 `input' 参数应为要发送到下级进程的数据，或者如果没有要发送到下
     级进程的数据则为 ‘None’。 如果流是以文本模式打开的，则 `input' 必须
     为字符串。 在其他情况下，它必须为字节串。

     *note communicate(): 25a7. 返回一个 ‘(stdout_data, stderr_data)’ 元
     组。如果文件以文本模式打开则为字符串；否则字节。

     注意如果你想要向进程的 stdin 传输数据，你需要通过 ‘stdin=PIPE’ 创建
     此 Popen 对象。类似的，要从结果元组获取任何非 ‘None’ 值，你同样需要
     设置 ‘stdout=PIPE’ 或者 ‘stderr=PIPE’。

     如果进程在 `timeout' 秒后未终止，一个 *note TimeoutExpired: 25a8. 异
     常将被抛出。捕获此异常并重新等待将不会丢失任何输出。

     如果超时到期，子进程不会被杀死，所以为了正确清理一个行为良好的应用
     程序应该杀死子进程并完成通讯。

          proc = subprocess.Popen(...)
          try:
              outs, errs = proc.communicate(timeout=15)
          except TimeoutExpired:
              proc.kill()
              outs, errs = proc.communicate()

          備註: 内存里数据读取是缓冲的，所以如果数据尺寸过大或无限，不要
          使用此方法。

     3.3 版更變: `timeout' 被添加

 -- 成員函式: Popen.send_signal (signal)

     将信号 `signal' 发送给子进程。

     如果进程已完成则不做任何操作。

          備註: 在 Windows， SIGTERM 是一个 *note terminate(): 25d3. 的
          别名。 CTRL_C_EVENT 和 CTRL_BREAK_EVENT 可以被发送给以包含
          ‘CREATE_NEW_PROCESS’ 的 `creationflags' 形参启动的进程。

 -- 成員函式: Popen.terminate ()

     停止子进程。 在 POSIX 操作系统上，此方法会发送 SIGTERM 给子进程。 在
     Windows 上则会调用 Win32 API 函数 ‘TerminateProcess()’ 来停止子进程
     。

 -- 成員函式: Popen.kill ()

     杀死子进程。 在 POSIX 操作系统上，此函数会发送 SIGKILL 给子进程。 在
     Windows 上 *note kill(): 25d4. 则是 *note terminate(): 25d3. 的别名
     。

以下属性也是可用的：

 -- 屬性: Popen.args

     `args' 参数传递给 *note Popen: 3db. – 一个程序参数的序列或者一个简
     单字符串。

     3.3 版新加入.

 -- 屬性: Popen.stdin

     如果 `stdin' 参数为 *note PIPE: 4f3.，此属性是一个类似 *note
     open(): 16f. 返回的可写的流对象。如果 `encoding' 或 `errors' 参数被
     指定或者 `universal_newlines' 参数为 ‘True’，则此流是一个文本流，否
     则是字节流。如果 `stdin' 参数非 *note PIPE: 4f3.， 此属性为 ‘None’。

 -- 屬性: Popen.stdout

     如果 `stdout' 参数是 *note PIPE: 4f3.，此属性是一个类似 *note
     open(): 16f. 返回的可读流。从流中读取子进程提供的输出。如果
     `encoding' 或 `errors' 参数被指定或者 `universal_newlines' 参数为
     ‘True’，此流为文本流，否则为字节流。如果 `stdout' 参数非 *note
     PIPE: 4f3.，此属性为 ‘None’。

 -- 屬性: Popen.stderr

     如果 `stderr' 参数是 *note PIPE: 4f3.，此属性是一个类似 *note
     open(): 16f. 返回的可读流。从流中读取子进程提供的输出。如果
     `encoding' 或 `errors' 参数被指定或者 `universal_newlines' 参数为
     ‘True’，此流为文本流，否则为字节流。如果 `stderr' 参数非 *note
     PIPE: 4f3.，此属性为 ‘None’。

     警告: 使用 *note communicate(): 25a7. 而非 *note .stdin.write:
     25bc.， *note .stdout.read: 25bd. 或者 *note .stderr.read: 25be. 来
     避免由于任意其他 OS 管道缓冲区被子进程填满阻塞而导致的死锁。

 -- 屬性: Popen.pid

     子进程的进程号。

     注意如果你设置了 `shell' 参数为 ‘True’，则这是生成的子 shell 的进程
     号。

 -- 屬性: Popen.returncode

     此进程的退出码，由 *note poll(): 25d2. 和 *note wait(): 689. 设置（
     以及直接由 *note communicate(): 25a7. 设置）。一个 ‘None’ 值 表示此
     进程仍未结束。

     一个负值 ‘-N’ 表示子进程被信号 ‘N’ 中断 (仅 POSIX).


File: python.info,  Node: Windows Popen 助手,  Next: 较旧的高阶 API,  Prev: Popen 对象,  Up: subprocess --- 子进程管理

5.17.6.7 Windows Popen 助手
...........................

*note STARTUPINFO: 25c2. 类和以下常数仅在 Windows 有效。

 -- 類別: subprocess.STARTUPINFO (*, dwFlags=0, hStdInput=None,
          hStdOutput=None, hStdError=None, wShowWindow=0,
          lpAttributeList=None)

     在 *note Popen: 3db. 创建时部分支持 Windows 的 STARTUPINFO(1) 结构
     。接下来的属性仅能通过关键词参数设置。

     3.7 版更變: 仅关键词参数支持被加入。

      -- 屬性: dwFlags

          一个位域，用于确定属性 *note STARTUPINFO: 25c2. 是否在进程创建
          窗口时使用。

               si = subprocess.STARTUPINFO()
               si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW

      -- 屬性: hStdInput

          如果 *note dwFlags: 25d8. 被指定为 *note STARTF_USESTDHANDLES:
          25da.，此值是进程的标准输入句柄，如果 *note
          STARTF_USESTDHANDLES: 25da. 未指定，则默认的标准输入是键盘缓冲
          区。

      -- 屬性: hStdOutput

          如果 *note dwFlags: 25d8. 指定为 *note STARTF_USESTDHANDLES:
          25da.，此属性是进程的标准输出句柄。除此之外，此此属性将被忽略
          并且默认标准输出是控制台窗口缓冲区。

      -- 屬性: hStdError

          如果 *note dwFlags: 25d8. 被指定为 *note STARTF_USESTDHANDLES:
          25da.，则此属性是进程的标准错误句柄。除此之外，此属性将被忽略
          并且默认标准错误为控制台窗口的缓冲区。

      -- 屬性: wShowWindow

          如果 *note dwFlags: 25d8. 指定了 *note STARTF_USESHOWWINDOW:
          25de.，此属性可为能被指定为 函数 ShowWindow(2) 的nCmdShow 的形
          参的任意值，除了 ‘SW_SHOWDEFAULT’。如此之外，此属性被忽略。

          *note SW_HIDE: 25df. 被提供给此属性。它在 *note Popen: 3db. 由
          ‘shell=True’ 调用时使用。

      -- 屬性: lpAttributeList

          ‘STARTUPINFOEX’ 给出的用于进程创建的额外属性字典，参阅
          UpdateProcThreadAttribute(3)。

          支持的属性：

          `handle_list'

               将被继承的句柄的序列。如果非空， `close_fds' 必须为 true。

               当传递给 *note Popen: 3db. 构造函数时，这些句柄必须暂时地
               能被 *note os.set_handle_inheritable(): 8eb. 继承，否则
               *note OSError: 304. 将以 Windows error
               ‘ERROR_INVALID_PARAMETER’ (87) 抛出。

                    警告: 在多线程进程中，请谨慎使用，以便在将此功能与对
                    继承所有句柄的其他进程创建函数（例如 *note
                    os.system(): e86.）的并发调用相结合时，避免泄漏标记
                    为可继承的句柄。这也应用于临时性创建可继承句柄的标准
                    句柄重定向。

          3.7 版新加入.

* Menu:

* Windows 常数::

   ---------- Footnotes ----------

   (1) https://msdn.microsoft.com/en-us/library/ms686331(v=vs.85).aspx

   (2) https://msdn.microsoft.com/en-us/library/ms633548(v=vs.85).aspx

   (3) 
https://msdn.microsoft.com/en-us/library/windows/desktop/ms686880(v=vs.85).aspx


File: python.info,  Node: Windows 常数,  Up: Windows Popen 助手

5.17.6.8 Windows 常数
.....................

*note subprocess: f9. 模块曝出以下常数。

 -- Data: subprocess.STD_INPUT_HANDLE

     标准输入设备，这是控制台输入缓冲区 ‘CONIN$’。

 -- Data: subprocess.STD_OUTPUT_HANDLE

     标准输出设备。最初，这是活动控制台屏幕缓冲区 ‘CONOUT$’。

 -- Data: subprocess.STD_ERROR_HANDLE

     标准错误设备。最初，这是活动控制台屏幕缓冲区 ‘CONOUT$’。

 -- Data: subprocess.SW_HIDE

     隐藏窗口。另一个窗口将被激活。

 -- Data: subprocess.STARTF_USESTDHANDLES

     指明 *note STARTUPINFO.hStdInput: 25d9, *note
     STARTUPINFO.hStdOutput: 25db. 和 *note STARTUPINFO.hStdError: 25dc.
     属性包含额外的信息。

 -- Data: subprocess.STARTF_USESHOWWINDOW

     指明 *note STARTUPINFO.wShowWindow: 25dd. 属性包含额外的信息。

 -- Data: subprocess.CREATE_NEW_CONSOLE

     新的进程将有新的控制台，而不是继承父进程的（默认）控制台。

 -- Data: subprocess.CREATE_NEW_PROCESS_GROUP

     用于指明将创建一个新的进程组的 *note Popen: 3db. ‘creationflags’ 形
     参。 这个旗标对于在子进程上使用 *note os.kill(): db9. 来说是必须的
     。

     如果指定了 *note CREATE_NEW_CONSOLE: 25c3. 则这个旗标会被忽略。

 -- Data: subprocess.ABOVE_NORMAL_PRIORITY_CLASS

     用于指明一个新进程将具有高于平均的优先级的 *note Popen: 3db.
     ‘creationflags’ 形参。

     3.7 版新加入.

 -- Data: subprocess.BELOW_NORMAL_PRIORITY_CLASS

     用于指明一个新进程将具有低于平均的优先级的 *note Popen: 3db.
     ‘creationflags’ 形参。

     3.7 版新加入.

 -- Data: subprocess.HIGH_PRIORITY_CLASS

     用于指明一个新进程将具有高优先级的 *note Popen: 3db.
     ‘creationflags’ 形参。

     3.7 版新加入.

 -- Data: subprocess.IDLE_PRIORITY_CLASS

     用于指明一个新进程将具有空闲（最低）优先级的 *note Popen: 3db.
     ‘creationflags’ 形参。

     3.7 版新加入.

 -- Data: subprocess.NORMAL_PRIORITY_CLASS

     用于指明一个新进程将具有正常（默认）优先级的 *note Popen: 3db.
     ‘creationflags’ 形参。

     3.7 版新加入.

 -- Data: subprocess.REALTIME_PRIORITY_CLASS

     用于指明一个新进程将具有实时优先级的 *note Popen: 3db.
     ‘creationflags’ 形参。 你应当几乎永远不使用
     REALTIME_PRIORITY_CLASS，因为这会中断管理鼠标输入、键盘输入以及后台
     磁盘刷新的系统线程。 这个类只适用于直接与硬件“对话”，或者执行短暂任
     务具有受限中断的应用。

     3.7 版新加入.

 -- Data: subprocess.CREATE_NO_WINDOW

     指明一个新进程将不会创建窗口的 *note Popen: 3db. ‘creationflags’ 形
     参。

     3.7 版新加入.

 -- Data: subprocess.DETACHED_PROCESS

     指明一个新进程将不会继承其父控制台的 *note Popen: 3db.
     ‘creationflags’ 形参。 这个值不能与 CREATE_NEW_CONSOLE 一同使用。

     3.7 版新加入.

 -- Data: subprocess.CREATE_DEFAULT_ERROR_MODE

     指明一个新进程不会继承调用方进程的错误模式的 *note Popen: 3db.
     ‘creationflags’ 形参。 新进程会转为采用默认的错误模式。 这个特性特
     别适用于运行时禁用硬错误的多线程 shell 应用。

     3.7 版新加入.

 -- Data: subprocess.CREATE_BREAKAWAY_FROM_JOB

     指明一个新进程不会关联到任务的 *note Popen: 3db. ‘creationflags’ 形
     参。

     3.7 版新加入.


File: python.info,  Node: 较旧的高阶 API,  Next: 使用 subprocess 模块替换旧函数,  Prev: Windows Popen 助手,  Up: subprocess --- 子进程管理

5.17.6.9 较旧的高阶 API
.......................

在 Python 3.5 之前，这三个函数组成了 subprocess 的高阶 API。 现在你可以
在许多情况下使用 *note run(): 4f2.，但有大量现在代码仍会调用这些函数。

 -- 函式: subprocess.call (args, *, stdin=None, stdout=None,
          stderr=None, shell=False, cwd=None, timeout=None,
          **other_popen_kwargs)

     运行由 `args' 所描述的命令。 等待命令完成，然后返回 *note
     returncode: 10a5. 属性。

     需要捕获 stdout 或 stderr 的代码应当改用 *note run(): 4f2.:

          run(...).returncode

     要屏蔽 stdout 或 stderr，可提供 *note DEVNULL: b78. 这个值。

     上面显示的参数只是常见的一些。 完整的函数签名与 *note Popen: 3db. 构
     造器的相同 —— 此函数会将所提供的 `timeout' 之外的全部参数直接传递给
     目标接口。

          備註: 请不要在此函数中使用 ‘stdout=PIPE’ 或 ‘stderr=PIPE’。 如
          果子进程向管道生成了足以填满 OS 管理缓冲区的输出而管道还未被读
          取时它将会阻塞。

     3.3 版更變: `timeout' 被添加

 -- 函式: subprocess.check_call (args, *, stdin=None, stdout=None,
          stderr=None, shell=False, cwd=None, timeout=None,
          **other_popen_kwargs)

     Run command with arguments.  Wait for command to complete.  If the
     return code was zero then return, otherwise raise *note
     CalledProcessError: d7d.  The *note CalledProcessError: d7d. object
     will have the return code in the *note returncode: 25b6. attribute.
     If *note check_call(): 25b5. was unable to start the process it
     will propagate the exception that was raised.

     需要捕获 stdout 或 stderr 的代码应当改用 *note run(): 4f2.:

          run(..., check=True)

     要屏蔽 stdout 或 stderr，可提供 *note DEVNULL: b78. 这个值。

     上面显示的参数只是常见的一些。 完整的函数签名与 *note Popen: 3db. 构
     造器的相同 —— 此函数会将所提供的 `timeout' 之外的全部参数直接传递给
     目标接口。

          備註: 请不要在此函数中使用 ‘stdout=PIPE’ 或 ‘stderr=PIPE’。 如
          果子进程向管道生成了足以填满 OS 管理缓冲区的输出而管道还未被读
          取时它将会阻塞。

     3.3 版更變: `timeout' 被添加

 -- 函式: 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)

     附带参数运行命令并返回其输出。

     如果返回码非零则会引发 *note CalledProcessError: d7d.。 *note
     CalledProcessError: d7d. 对象将在 *note returncode: 25b6. 属性中保
     存返回码并在 *note output: 25b8. 属性中保存所有输出。

     这相当于:

          run(..., check=True, stdout=PIPE).stdout

     上面显示的参数只是常见的一些。 完整的函数签名与 *note run(): 4f2. 的
     大致相同 —— 大部分参数会通过该接口直接传递。 存在一个与 *note
     run(): 4f2. 行为不同的 API 差异：传递 ‘input=None’ 的行为将与
     ‘input=b''’ (或 ‘input=''’，具体取决于其他参数) 一样而不是使用父对
     象的标准输入文件处理。

     默认情况下，此函数将把数据返回为已编码的字节串。 输出数据的实际编码
     格式将取决于发起调用的命令，因此解码为文本的操作往往需要在应用程序
     层级上进行处理。

     此行为可以通过设置 `text', `encoding', `errors' 或将
     `universal_newlines' 设为 ‘True’ 来重载，具体描述见 *note 常用参数:
     25a6. 和 *note run(): 4f2.。

     要在结果中同时捕获标准错误，请使用 ‘stderr=subprocess.STDOUT’:

          >>> subprocess.check_output(
          ...     "ls non_existent_file; exit 0",
          ...     stderr=subprocess.STDOUT,
          ...     shell=True)
          'ls: non_existent_file: No such file or directory\n'

     3.1 版新加入.

     3.3 版更變: `timeout' 被添加

     3.4 版更變: 增加了对 `input' 关键字参数的支持。

     3.6 版更變: 增加了 `encoding' 和 `errors'。 详情参见 *note run():
     4f2.。

     3.7 版新加入: `text' 作为 `universal_newlines' 的一个更具可读性的别
     名被添加。


File: python.info,  Node: 使用 subprocess 模块替换旧函数,  Next: 旧式的 Shell 发起函数,  Prev: 较旧的高阶 API,  Up: subprocess --- 子进程管理

5.17.6.10 使用 ‘subprocess’ 模块替换旧函数
..........................................

在这一节中，"a 改为 b" 意味着 b 可以被用作 a 的替代。

     備註: 在这一节中的所有 "a" 函数会在找不到被执行的程序时（差不多）静
     默地失败；"b" 替代函数则会改为引发 *note OSError: 304.。

     此外，在使用 *note check_output(): 9c1. 时如果替代函数所请求的操作
     产生了非零返回值则将失败并引发 *note CalledProcessError: d7d.。 操
     作的输出仍能以所引发异常的 *note output: 25b8. 属性的方式被访问。

在下列例子中，我们假定相关的函数都已从 *note subprocess: f9. 模块中导入
了。

* Menu:

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


File: python.info,  Node: 替代 /bin/sh shell 命令替换,  Next: 替代 shell 管道,  Up: 使用 subprocess 模块替换旧函数

5.17.6.11 替代 ‘/bin/sh’ shell 命令替换
.......................................

     output=$(mycmd myarg)

改为:

     output = check_output(["mycmd", "myarg"])


File: python.info,  Node: 替代 shell 管道,  Next: 替代 os system,  Prev: 替代 /bin/sh shell 命令替换,  Up: 使用 subprocess 模块替换旧函数

5.17.6.12 替代 shell 管道
.........................

     output=$(dmesg | grep hda)

改为:

     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]

启动 p2 之后再执行 ‘p1.stdout.close()’ 调用很重要，这是为了让 p1 能在 p2
先于 p1 退出时接收到 SIGPIPE。

另外，对于受信任的输入，shell 本身的管道支持仍然可被直接使用:

     output=$(dmesg | grep hda)

改为:

     output=check_output("dmesg | grep hda", shell=True)


File: python.info,  Node: 替代 os system,  Next: 替代 os spawn 函数族,  Prev: 替代 shell 管道,  Up: 使用 subprocess 模块替换旧函数

5.17.6.13 替代 ‘os.system()’
............................

     sts = os.system("mycmd" + " myarg")
     # becomes
     retcode = call("mycmd" + " myarg", shell=True)

註解：

   * 通过 shell 来调用程序通常是不必要的。

   * *note call(): 4f4. 返回值的编码方式与 *note os.system(): e86. 的不
     同。

   * *note os.system(): e86. 函数在命令运行期间会忽略 SIGINT 和 SIGQUIT
     信号，但调用方必须在使用 *note subprocess: f9. 模块时分别执行此操作
     。

一个更现实的例子如下所示:

     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)


File: python.info,  Node: 替代 os spawn 函数族,  Next: 替代 os popen os popen2 os popen3,  Prev: 替代 os system,  Up: 使用 subprocess 模块替换旧函数

5.17.6.14 替代 ‘os.spawn’ 函数族
................................

P_NOWAIT 示例:

     pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
     ==>
     pid = Popen(["/bin/mycmd", "myarg"]).pid

P_WAIT 示例:

     retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
     ==>
     retcode = call(["/bin/mycmd", "myarg"])

Vector 示例:

     os.spawnvp(os.P_NOWAIT, path, args)
     ==>
     Popen([path] + args[1:])

Environment 示例:

     os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
     ==>
     Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})


File: python.info,  Node: 替代 os popen os popen2 os popen3,  Next: 来自 popen2 模块的替代函数,  Prev: 替代 os spawn 函数族,  Up: 使用 subprocess 模块替换旧函数

5.17.6.15 替代 ‘os.popen()’, ‘os.popen2()’, ‘os.popen3()’
.........................................................

     (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)

     (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)

     (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)

返回码以如下方式处理转写:

     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")


File: python.info,  Node: 来自 popen2 模块的替代函数,  Prev: 替代 os popen os popen2 os popen3,  Up: 使用 subprocess 模块替换旧函数

5.17.6.16 来自 ‘popen2’ 模块的替代函数
......................................

     備註: 如果 popen2 函数的 cmd 参数是一个字符串，命令会通过 /bin/sh 来
     执行。 如果是一个列表，命令会被直接执行。

     (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)

     (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)

‘popen2.Popen3’ 和 ‘popen2.Popen4’ 基本上类似于 *note subprocess.Popen:
3db.，不同之处在于:

   * *note Popen: 3db. 如果执行失败会引发一个异常。

   * `capturestderr' 参数被替换为 `stderr' 参数。

   * 必须指定 ‘stdin=PIPE’ 和 ‘stdout=PIPE’。

   * popen2 默认会关闭所有文件描述符，但对于 *note Popen: 3db. 你必须指
     明 ‘close_fds=True’ 以才能在所有平台或较旧的 Python 版本中确保此行
     为。


File: python.info,  Node: 旧式的 Shell 发起函数,  Next: 註解,  Prev: 使用 subprocess 模块替换旧函数,  Up: subprocess --- 子进程管理

5.17.6.17 旧式的 Shell 发起函数
...............................

此模块还提供了以下来自 2.x ‘commands’ 模块的旧版函数。 这些操作会隐式地
发起调用系统 shell 并且上文所描述的有关安全与异常处理一致性保证都不适用
于这些函数。

 -- 函式: subprocess.getstatusoutput (cmd)

     返回在 shell 中执行 `cmd' 产生的 ‘(exitcode, output)’。

     在 shell 中以 ‘Popen.check_output()’ 执行字符串 `cmd' 并返回一个 2
     元组 ‘(exitcode, output)’。 会使用当前区域设置的编码格式；请参阅
     *note 常用参数: 25a6. 中的说明来了解详情。

     末尾的一个换行符会从输出中被去除。 命令的退出码可被解读为子进程的返
     回码。 例如:

          >>> 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, '')

     *note 可用性: 1491.: POSIX 和 Windows。

     3.3.4 版更變: 添加了 Windows 支持。

     此函数现在返回 (exitcode, output) 而不是像 Python 3.3.3 及更早的版
     本那样返回 (status, output)。 exitcode 的值与 *note returncode:
     10a5. 相同。

 -- 函式: subprocess.getoutput (cmd)

     返回在 shell 中执行 `cmd' 产生的输出（stdout 和 stderr）。

     类似于 *note getstatusoutput(): 9c2.，但退出码会被忽略并且返回值为
     包含命令输出的字符串。 例如:

          >>> subprocess.getoutput('ls /bin/ls')
          '/bin/ls'

     *note 可用性: 1491.: POSIX 和 Windows。

     3.3.4 版更變: 添加了 Windows 支持


File: python.info,  Node: 註解,  Prev: 旧式的 Shell 发起函数,  Up: subprocess --- 子进程管理

5.17.6.18 註解
..............

* Menu:

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


File: python.info,  Node: 在 Windows 上将参数列表转换为一个字符串,  Up: 註解

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

在 Windows 上，`args' 序列会被转换为可使用以下规则来解析的字符串（对应于
MS C 运行时所使用的规则）:

  1. 参数以空白符分隔，即空格符或制表符。

  2. 用双引号标示的字符串会被解读为单个参数，而不再考虑其中的空白符。 一
     个参数可以嵌套用引号标示的字符串。

  3. 带有一个反斜杠前缀的双引号会被解读为双引号字面值。

  4. 反斜杠会按字面值解读，除非它是作为双引号的前缀。

  5. 如果反斜杠被作为双引号的前缀，则每个反斜杠对会被解读为一个反斜杠字
     面值。 如果反斜杠数量为奇数，则最后一个反斜杠会如规则 3 所描述的那
     样转义下一个双引号。

也參考
......

*note shlex: e8.

     此模块提供了用于解析和转义命令行的函数。


File: python.info,  Node: sched --- 事件调度器,  Next: queue --- 一个同步的队列类,  Prev: subprocess --- 子进程管理,  Up: 并发执行

5.17.7 ‘sched’ — 事件调度器
---------------------------

`源码：' Lib/sched.py(1)

__________________________________________________________________

*note sched: e3. 模块定义了一个实现通用事件调度程序的类：

 -- 類別: sched.scheduler (timefunc=time.monotonic,
          delayfunc=time.sleep)

     *note scheduler: b49. 类定义了一个调度事件的通用接口。 它需要两个函
     数来实际处理“外部世界” —— `timefunc' 应当不带参数地调用，并返回一个
     数字（“时间”，可以为任意单位）。 `delayfunc' 函数应当带一个参数调用
     ，与 `timefunc' 的输出相兼容，并且应当延迟其所指定的时间单位。 每个
     事件运行后还将调用 `delayfunc' 并传入参数 ‘0’ 以允许其他线程有机会
     在多线程应用中运行。

     3.3 版更變: `timefunc' 和 `delayfunc' 参数是可选的。

     3.3 版更變: *note scheduler: b49. 类可以安全的在多线程环境中使用。

示例:

     >>> 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

* Menu:

* 调度器对象::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/sched.py


File: python.info,  Node: 调度器对象,  Up: sched --- 事件调度器

5.17.7.1 调度器对象
...................

*note scheduler: b49. 实例拥有以下方法和属性：

 -- 成員函式: scheduler.enterabs (time, priority, action, argument=(),
          kwargs={})

     安排一个新事件。 `time' 参数应该有一个数字类型兼容的返回值，与传递
     给构造函数的 `timefunc' 函数的返回值兼容。 计划在相同 `time' 的事件
     将按其 `priority' 的顺序执行。 数字越小表示优先级越高。

     执行事件意为执行 ‘action(*argument, **kwargs)’。 `argument' 是包含
     有 `action' 的位置参数的序列。 `kwargs' 是包含 `action' 的关键字参
     数的字典。

     返回值是一个事件，可用于以后取消事件（ 参见 *note cancel(): 25f4. ）
     。

     3.3 版更變: `argument' 参数是可选的。

     3.3 版更變: 添加了 `kwargs' 形参。

 -- 成員函式: scheduler.enter (delay, priority, action, argument=(),
          kwargs={})

     安排延后 `delay' 时间单位的事件。 除了相对时间，其他参数、效果和返
     回值与 *note enterabs(): b4b. 的相同。

     3.3 版更變: `argument' 参数是可选的。

     3.3 版更變: 添加了 `kwargs' 形参。

 -- 成員函式: scheduler.cancel (event)

     从队列中删除事件。 如果 `event' 不是当前队列中的事件，则此方法将引
     发 *note ValueError: 16d.。

 -- 成員函式: scheduler.empty ()

     如果事件队列为空则返回 ‘True’。

 -- 成員函式: scheduler.run (blocking=True)

     运行所有预定事件。 此方法将等待（使用传递给构造函数的 ‘delayfunc()’
     函数）进行下一个事件，然后执行它，依此类推，直到没有更多的计划事件
     。

     如果 `blocking' 为false，则执行由于最快到期（如果有）的预定事件，然
     后在调度程序中返回下一个预定调用的截止时间（如果有）。

     `action' 或 `delayfunc' 都可以引发异常。 在任何一种情况下，调度程序
     都将保持一致状态并传播异常。 如果 `action' 引发异常，则在将来调用
     *note run(): b48. 时不会尝试该事件。

     如果一系列事件的运行时间大于下一个事件发生前的可用时间，那么调度程
     序将完全落后。 没有事件会被丢弃；调用代码负责取消不再相关的事件。

     3.3 版更變: 添加了 `blocking' 形参。

 -- 屬性: scheduler.queue

     只读属性按照将要运行的顺序返回即将发生的事件列表。 每个事件都显示为
     *note named tuple: b7b. ，包含以下字段：time、priority、action、
     argument、kwargs。


File: python.info,  Node: queue --- 一个同步的队列类,  Next: contextvars --- 上下文变量,  Prev: sched --- 事件调度器,  Up: 并发执行

5.17.8 ‘queue’ — 一个同步的队列类
---------------------------------

`源代码:' Lib/queue.py(1)

__________________________________________________________________

*note queue: da. 模块实现了多生产者、多消费者队列。这特别适用于消息必须
安全地在多线程间交换的线程编程。模块中的 *note Queue: dde. 类实现了所有
所需的锁定语义。

模块实现了三种类型的队列，它们的区别仅仅是条目取回的顺序。在 FIFO 队列中
，先添加的任务先取回。在 LIFO 队列中，最近被添加的条目先取回(操作类似一
个堆栈)。优先级队列中，条目将保持排序( 使用 *note heapq: 8d. 模块 ) 并且
最小值的条目第一个返回。

在内部，这三个类型的队列使用锁来临时阻塞竞争线程；然而，它们并未被设计用
于线程的重入性处理。

此外，模块实现了一个 "简单的" FIFO 队列类型， *note SimpleQueue: 4cc. ，
这个特殊实现为小功能在交换中提供额外的保障。

*note queue: da. 模块定义了下列类和异常：

 -- 類別: queue.Queue (maxsize=0)

     Constructor for a FIFO queue.  `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 `maxsize' is less than or equal
     to zero, the queue size is infinite.

 -- 類別: queue.LifoQueue (maxsize=0)

     LIFO 队列构造函数。 `maxsize' 是个整数，用于设置可以放入队列中的项
     目数的上限。当达到这个大小的时候，插入操作将阻塞至队列中的项目被消
     费掉。如果 `maxsize' 小于等于零，队列尺寸为无限大。

 -- 類別: queue.PriorityQueue (maxsize=0)

     优先级队列构造函数。 `maxsize' 是个整数，用于设置可以放入队列中的项
     目数的上限。当达到这个大小的时候，插入操作将阻塞至队列中的项目被消
     费掉。如果 `maxsize' 小于等于零，队列尺寸为无限大。

     最小值先被取出( 最小值条目是由 ‘sorted(list(entries))[0]’ 返回的条
     目)。条目的典型模式是一个以下形式的元组： ‘(priority_number, data)’
     。

     如果 `data' 元素没有可比性，数据将被包装在一个类中，忽略数据值，仅
     仅比较优先级数字 ：

          from dataclasses import dataclass, field
          from typing import Any

          @dataclass(order=True)
          class PrioritizedItem:
              priority: int
              item: Any=field(compare=False)

 -- 類別: queue.SimpleQueue

     无界的 FIFO 队列构造函数。简单的队列，缺少任务跟踪等高级功能。

     3.7 版新加入.

 -- 例外: queue.Empty

     对空的 *note Queue: dde. 对象，调用非阻塞的 *note get(): 25fb. (or
     *note get_nowait(): 25fc.) 时，引发的异常。

 -- 例外: queue.Full

     对满的 *note Queue: dde. 对象，调用非阻塞的 *note put(): 25fd. (or
     *note put_nowait(): 25fe.) 时，引发的异常。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/queue.py


File: python.info,  Node: Queue对象,  Next: SimpleQueue 对象,  Up: queue --- 一个同步的队列类

5.17.8.1 Queue对象
..................

队列对象 (*note Queue: dde, *note LifoQueue: 25f9, 或者 *note
PriorityQueue: 25fa.) 提供下列描述的公共方法。

 -- 成員函式: Queue.qsize ()

     返回队列的大致大小。注意，qsize() > 0 不保证后续的 get() 不被阻塞，
     qsize() < maxsize 也不保证 put() 不被阻塞。

 -- 成員函式: Queue.empty ()

     如果队列为空，返回 ‘True’ ，否则返回 ‘False’ 。如果 empty() 返回
     ‘True’ ，不保证后续调用的 put() 不被阻塞。类似的，如果 empty() 返回
     ‘False’ ，也不保证后续调用的 get() 不被阻塞。

 -- 成員函式: Queue.full ()

     如果队列是满的返回 ‘True’ ，否则返回 ‘False’ 。如果 full() 返回
     ‘True’ 不保证后续调用的 get() 不被阻塞。类似的，如果 full() 返回
     ‘False’ 也不保证后续调用的 put() 不被阻塞。

 -- 成員函式: Queue.put (item, block=True, timeout=None)

     将 `item' 放入队列。如果可选参数 `block' 是 true 并且 `timeout' 是
     ‘None’ (默认)，则在必要时阻塞至有空闲插槽可用。如果 `timeout' 是个
     正数，将最多阻塞 `timeout' 秒，如果在这段时间没有可用的空闲插槽，将
     引发 *note Full: 250c. 异常。反之 (`block' 是 false)，如果空闲插槽
     立即可用，则把 `item' 放入队列，否则引发 *note Full: 250c. 异常 ( 在
     这种情况下，`timeout' 将被忽略)。

 -- 成員函式: Queue.put_nowait (item)

     相当于 ‘put(item, False)’ 。

 -- 成員函式: Queue.get (block=True, timeout=None)

     从队列中移除并返回一个项目。如果可选参数 `block' 是 true 并且
     `timeout' 是 ‘None’ (默认值)，则在必要时阻塞至项目可得到。如果
     `timeout' 是个正数，将最多阻塞 `timeout' 秒，如果在这段时间内项目不
     能得到，将引发 *note Empty: 250b. 异常。反之 (`block' 是 false) , 如
     果一个项目立即可得到，则返回一个项目，否则引发 *note Empty: 250b. 异
     常 (这种情况下，`timeout' 将被忽略)。

     POSIX系统3.0之前，以及所有版本的Windows系统中，如果 `block' 是 true
     并且 `timeout' 是 ‘None’ ， 这个操作将进入基础锁的不间断等待。这意
     味着，没有异常能发生，尤其是 SIGINT 将不会触发 *note
     KeyboardInterrupt: 2cc. 异常。

 -- 成員函式: Queue.get_nowait ()

     相当于 ‘get(False)’ 。

提供了两个方法，用于支持跟踪 排队的任务 是否 被守护的消费者线程 完整的处
理。

 -- 成員函式: Queue.task_done ()

     表示前面排队的任务已经被完成。被队列的消费者线程使用。每个 *note
     get(): 25fb. 被用于获取一个任务， 后续调用 *note task_done(): 2507.
     告诉队列，该任务的处理已经完成。

     如果 *note join(): 2508. 当前正在阻塞，在所有条目都被处理后，将解除
     阻塞(意味着每个 *note put(): 25fd. 进队列的条目的 *note
     task_done(): 2507. 都被收到)。

     如果被调用的次数多于放入队列中的项目数量，将引发 *note ValueError:
     16d. 异常 。

 -- 成員函式: Queue.join ()

     阻塞至队列中所有的元素都被接收和处理完毕。

     当条目添加到队列的时候，未完成任务的计数就会增加。每当消费者线程调
     用 *note task_done(): 2507. 表示这个条目已经被回收，该条目所有工作
     已经完成，未完成计数就会减少。当未完成计数降到零的时候， *note
     join(): 2508. 阻塞被解除。

如何等待排队的任务被完成的示例：

     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='')

     # block until all tasks are done
     q.join()
     print('All work completed')


File: python.info,  Node: SimpleQueue 对象,  Prev: Queue对象,  Up: queue --- 一个同步的队列类

5.17.8.2 SimpleQueue 对象
.........................

*note SimpleQueue: 4cc. 对象提供下列描述的公共方法。

 -- 成員函式: SimpleQueue.qsize ()

     返回队列的大致大小。注意，qsize() > 0 不保证后续的 get() 不被阻塞。

 -- 成員函式: SimpleQueue.empty ()

     如果队列为空，返回 ‘True’ ，否则返回 ‘False’ 。如果 empty() 返回
     ‘False’ ，不保证后续调用的 get() 不被阻塞。

 -- 成員函式: SimpleQueue.put (item, block=True, timeout=None)

     将 `item' 放入队列。此方法永不阻塞，始终成功（除了潜在的低级错误，
     例如内存分配失败）。可选参数 `block' 和 `timeout' 仅仅是为了保持
     *note Queue.put(): 25fd. 的兼容性而提供，其值被忽略。

     `CPython implementation detail:' This method has a C implementation
     which is reentrant.  That is, a ‘put()’ or ‘get()’ call can be
     interrupted by another ‘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 ‘__del__’
     methods or *note weakref: 131. callbacks.

 -- 成員函式: SimpleQueue.put_nowait (item)

     相当于 ‘put(item)’ ，仅为保持 *note Queue.put_nowait(): 25fe. 兼容
     性而提供。

 -- 成員函式: SimpleQueue.get (block=True, timeout=None)

     从队列中移除并返回一个项目。如果可选参数 `block' 是 true 并且
     `timeout' 是 ‘None’ (默认值)，则在必要时阻塞至项目可得到。如果
     `timeout' 是个正数，将最多阻塞 `timeout' 秒，如果在这段时间内项目不
     能得到，将引发 *note Empty: 250b. 异常。反之 (`block' 是 false) , 如
     果一个项目立即可得到，则返回一个项目，否则引发 *note Empty: 250b. 异
     常 (这种情况下，`timeout' 将被忽略)。

 -- 成員函式: SimpleQueue.get_nowait ()

     相当于 ‘get(False)’ 。

也參考
......

类 *note multiprocessing.Queue: 24e6.

     一个用于多进程上下文的队列类（而不是多线程）。

*note collections.deque: 62a. 是无界队列的一个替代实现，具有快速的不需要
锁并且支持索引的原子化 *note append(): 1a8a. 和 *note popleft(): 1a90. 操
作。


File: python.info,  Node: contextvars --- 上下文变量,  Next: _thread --- 底层多线程 API,  Prev: queue --- 一个同步的队列类,  Up: 并发执行

5.17.9 ‘contextvars’ — 上下文变量
---------------------------------

__________________________________________________________________

本模块提供了相关API用于管理、存储和访问上下文相关的状态。 *note
ContextVar: 260d. 类用于声明 `上下文变量' 并与其一起使用。函数 *note
copy_context(): 260e.  和类 *note Context: 260f. 用于管理当前上下文和异
步框架中。

在多并发环境中，有状态上下文管理器应该使用上下文变量，而不是 *note
threading.local(): 244e. 来防止他们的状态意外泄露到其他代码。

更多信息参见 PEP 567(1) 。

3.7 版新加入.

* Menu:

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

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0567


File: python.info,  Node: 上下文变量,  Next: 手动上下文管理,  Up: contextvars --- 上下文变量

5.17.9.1 上下文变量
...................

 -- 類別: contextvars.ContextVar (name[, *, default])

     此类用于声明一个新的上下文变量，如:

          var: ContextVar[int] = ContextVar('var', default=42)

     `name' 参数用于内省和调试，必需。

     调用 *note ContextVar.get(): 2611. 时，如果上下文中没有找到此变量的
     值，则返回可选的仅命名参数 `default' 。

     `重要：' 上下文变量应该在顶级模块中创建，且永远不要在闭包中创建。
     *note Context: 260f. 对象拥有对上下文变量的强引用，这可以让上下文变
     量被垃圾收集器正确回收。

      -- 屬性: name

          上下文变量的名称，只读属性。

          3.7.1 版新加入.

      -- 成員函式: get ([default])

          返回当前上下文中此上下文变量的值。

          如果当前上下文中此变量没有值，则此方法会:

             * 如果提供了得 话，返回传入的 `default' 值；或者

             * 返回上下文变量本身的默认值， 如果创建此上下文变量时提供了
               默认值；或者

             * 抛出 *note LookupError: 1790. 异常。

      -- 成員函式: set (value)

          调用此方法设置上下文变量在当前上下文中的值。

          必选参数 `value' 是上下文变量的新值。

          返回一个 *note Token: 2614.  对象，可通过 *note
          ContextVar.reset(): 2615. 方法将上下文变量还原为之前某个状态。

      -- 成員函式: reset (token)

          将上下文变量重置为调用 *note ContextVar.set(): 2613. 之前、创
          建 `token' 时候的状态。

          例如:

               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.

 -- 類別: contextvars.Token

     *note ContextVar.set(): 2613. 方法返回 `Token' 对象。此对象可以传递
     给 *note ContextVar.reset(): 2615. 方法用于将上下文变量还原为调用
     `set' 前的状态。

      -- 屬性: var

          只读属性。指向创建此 token 的 *note ContextVar: 260d. 对象。

      -- 屬性: old_value

          一个只读属性。 会被设为在创建此令牌的 *note ContextVar.set():
          2613. 方法调用之前该变量所具有的值。 如果调用之前变量没有设置
          值，则它指向 *note Token.MISSING: 2618. 。

      -- 屬性: MISSING

          *note Token.old_value: 2617. 会用到的一个标记对象。


File: python.info,  Node: 手动上下文管理,  Next: asyncio 支持,  Prev: 上下文变量,  Up: contextvars --- 上下文变量

5.17.9.2 手动上下文管理
.......................

 -- 函式: contextvars.copy_context ()

     返回当前上下文中 *note Context: 260f. 对象的拷贝。

     以下代码片段会获取当前上下文的拷贝并打印设置到其中的所有变量及其值:

          ctx: Context = copy_context()
          print(list(ctx.items()))

     此函数复杂度为 O(1) ，也就是说对于只包含几个上下文变量和很多上下文
     变量的情况，他们是一样快的。

 -- 類別: contextvars.Context

     *note ContextVars: 260d. 中所有值的映射。

     ‘Context()’ 创建一个不包含任何值的空上下文。如果要获取当前上下文的
     拷贝，使用 *note copy_context(): 260e. 函数。

     Context 实现了 *note collections.abc.Mapping: 15f. 接口。

      -- 成員函式: run (callable, *args, **kwargs)

          按照 `run' 方法中的参数在上下文对象中执行 ‘callable(*args,
          **kwargs)’ 代码。返回执行结果，如果发生异常，则将异常透传出来
          。

          `callable' 对上下文变量所做的任何修改都会保留在上下文对象中:

               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'

          当在多个系统线程或者递归调用同一个上下文对象的此方法，抛出
          *note RuntimeError: 3dc. 异常。

      -- 成員函式: copy ()

          返回此上下文对象的浅拷贝。

      -- Describe: var in context

          如果*context* 中含有名称为 `var' 的变量，返回 ‘True’ ， 否则返
          回 ‘False’ 。

      -- Describe: context[var]

          返回名称为 `var' 的 *note ContextVar: 260d. 变量。如果上下文对
          象中不包含这个变量，则抛出 *note KeyError: 3e9. 异常。

      -- 成員函式: get (var[, default])

          如果 `var' 在上下文对象中具有值则返回 `var' 的值。 在其他情况
          下返回 `default'。 如果未给出 `default' 则返回 ‘None’。

      -- Describe: iter(context)

          返回一个存储在上下文对象中的变量的迭代器。

      -- Describe: len(proxy)

          返回上下文对象中所设的变量的数量。

      -- 成員函式: keys ()

          返回上下文对象中的所有变量的列表。

      -- 成員函式: values ()

          返回上下文对象中所有变量值的列表。

      -- 成員函式: items ()

          返回包含上下文对象中所有变量及其值的 2 元组的列表。


File: python.info,  Node: asyncio 支持,  Prev: 手动上下文管理,  Up: contextvars --- 上下文变量

5.17.9.3 asyncio 支持
.....................

上下文变量在 *note asyncio: 9. 中有原生的支持并且无需任何额外配置即可被
使用。 例如，以下是一个简单的回显服务器，它使用上下文变量来让远程客户端
的地址在处理该客户端的 Task 中可用:

     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

以下是上述某些服务的支持模块：


File: python.info,  Node: _thread --- 底层多线程 API,  Prev: contextvars --- 上下文变量,  Up: 并发执行

5.17.10 ‘_thread’ — 底层多线程 API
----------------------------------

__________________________________________________________________

该模块提供了操作多个线程（也被称为 `轻量级进程' 或 `任务'）的底层原语 ——
多个控制线程共享全局数据空间。为了处理同步问题，也提供了简单的锁机制（也
称为 `互斥锁' 或 `二进制信号'）。*note threading: 10b. 模块基于该模块提
供了更易用的高级多线程 API。

3.7 版更變: 这个模块曾经是可选的，但现在总是可用的。

这个模块定义了以下常量和函数：

 -- 例外: _thread.error

     发生线程相关错误时抛出。

     3.3 版更變: 现在是内建异常 *note RuntimeError: 3dc. 的别名。

 -- Data: _thread.LockType

     锁对象的类型。

 -- 函式: _thread.start_new_thread (function, args[, kwargs])

     开启一个新线程并返回其标识。 线程执行函数 `function' 并附带参数列表
     `args' (必须是元组)。 可选的 `kwargs' 参数指定一个关键字参数字典。

     当函数返回时，线程会静默地退出。

     当函数因某个未处理异常而终结时，*note sys.unraisablehook(): 35a. 会
     被调用以处理异常。 钩子参数的 `object' 属性为 `function'。 在默认情
     况下，会打印堆栈回溯然后该线程将退出（但其他线程会继续运行）。

     当函数引发 *note SystemExit: 6f3. 异常时，它会被静默地忽略。

     3.8 版更變: 现在会使用 *note sys.unraisablehook(): 35a. 来处理未处
     理的异常。

 -- 函式: _thread.interrupt_main ()

     模拟一个 *note signal.SIGINT: 2626. 信号到达主线程的效果。 线程可以
     使用这个函数来中断主线程。

     如果 Python 没有处理 *note signal.SIGINT: 2626. (将它设为 *note
     signal.SIG_DFL: 2627. 或 *note signal.SIG_IGN: 2628.)，此函数将不做
     任何事。

 -- 函式: _thread.exit ()

     抛出 *note SystemExit: 6f3. 异常。如果没有捕获的话，这个异常会使线
     程退出。

 -- 函式: _thread.allocate_lock ()

     返回一个新的锁对象。锁中的方法在后面描述。初始情况下锁处于解锁状态
     。

 -- 函式: _thread.get_ident ()

     返回当前线程的 “线程描述符”。它是一个非零的整型数。它的值没有什么含
     义，主要是作为 magic cookie 使用，比如作为含有线程相关数据的字典的
     索引。线程描述符可能会在线程退出，新线程创建时复用。

 -- 函式: _thread.get_native_id ()

     返回内核分配给当前线程的原生集成线程 ID。 这是一个非负整数。 它的值
     可被用来在整个系统中唯一地标识这个特定线程（直到线程终结，在那之后
     该值可能会被 OS 回收再利用）。

     *note 可用性: 1491.: Windows, FreeBSD, Linux, macOS, OpenBSD,
     NetBSD, AIX。

     3.8 版新加入.

 -- 函式: _thread.stack_size ([size])

     返回新建线程时使用的堆栈大小。可选参数 `size' 指定之后新建的线程的
     堆栈大小，而且一定要是0（根据平台或者默认配置）或者最小是
     32,768(32KiB)的一个正整数。如果*size*没有指定，默认是0。如果不支持
     改变线程堆栈大小，会抛出 *note RuntimeError: 3dc. 错误。如果指定的
     堆栈大小不合法，会抛出 *note ValueError: 16d. 错误并且不会修改堆栈
     大小。32KiB是当前最小的能保证解释器足够堆栈空间的堆栈大小。需要注意
     的是部分平台对于堆栈大小会有特定的限制，例如要求大于32KiB的堆栈大小
     或者需要根据系统内存页面的整数倍进行分配 - 应当查阅平台文档有关详细
     信息（4KiB页面比较普遍，在没有更具体信息的情况下，建议的方法是使用
     4096的倍数作为堆栈大小）

     *note 可用性: 1491.: Windows，具有 POSIX 线程的系统。

 -- Data: _thread.TIMEOUT_MAX

     ‘Lock.acquire()’ 方法中 `timeout' 参数允许的最大值。传入超过这个值
     的 timeout 会抛出 *note OverflowError: a41. 异常。

     3.2 版新加入.

锁对象有以下方法：

 -- 成員函式: lock.acquire (waitflag=1, timeout=-1)

     没有任何可选参数时，该方法无条件申请获得锁，有必要的话会等待其他线
     程释放锁（同时只有一个线程能获得锁 —— 这正是锁存在的原因）。

     如果传入了整型参数 `waitflag'，具体的行为取决于传入的值：如果是 0 的
     话，只会在能够立刻获取到锁时才获取，不会等待，如果是非零的话，会像
     之前提到的一样，无条件获取锁。

     如果传入正浮点数参数 `timeout'，相当于指定了返回之前等待得最大秒数
     。如果传入负的 `timeout'，相当于无限期等待。如果 `waitflag' 是 0 的
     话，不能指定 `timeout'。

     如果成功获取到所会返回 ‘True’，否则返回 ‘False’。

     3.2 版更變: `timeout' 形参是新增的。

     3.2 版更變: 现在获取锁的操作可以被 POSIX 信号中断。

 -- 成員函式: lock.release ()

     释放锁。锁必须已经被获取过，但不一定是同一个线程获取的。

 -- 成員函式: lock.locked ()

     返回锁的状态：如果已被某个线程获取，返回 ‘True’，否则返回 ‘False’。

除了这些方法之外，锁对象也可以通过 *note with: 7da. 语句使用，例如：

     import _thread

     a_lock = _thread.allocate_lock()

     with a_lock:
         print("a_lock is locked while this executes")

`注意事项：'

   * 线程与中断奇怪地交互：*note KeyboardInterrupt: 2cc. 异常可能会被任
     意一个线程捕获。（如果 *note signal: ea. 模块可用的话，中断总是会进
     入主线程。）

   * 调用 *note sys.exit(): daa. 或是抛出 *note SystemExit: 6f3. 异常等
     效于调用 *note _thread.exit(): 2629.。

   * 不可能中断锁的 ‘acquire()’ 方法 —— *note KeyboardInterrupt: 2cc. 一
     场会在锁获取到之后发生。

   * 当主线程退出时，由系统决定其他线程是否存活。在大多数系统中，这些线
     程会直接被杀掉，不会执行 *note try: e37. ...  *note finally: 2bc. 语
     句，也不会执行对象析构函数。

   * 当主线程退出时，不会进行正常的清理工作（除非使用了 *note try: e37.
     ...  *note finally: 2bc. 语句），标准 I/O 文件也不会刷新。


File: python.info,  Node: 网络和进程间通信,  Next: 互联网数据处理,  Prev: 并发执行,  Up: Python 標準函式庫 Standard Library

5.18 网络和进程间通信
=====================

本章介绍的模块提供了网络和进程间通信的机制。

某些模块仅适用于同一台机器上的两个进程，例如 *note signal: ea. 和 *note
mmap: b3. 。 其他模块支持两个或多个进程可用于跨机器通信的网络协议。

本章中描述的模块列表是：

* 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 复用库
* asyncore: asyncore --- 异步套接字处理器. 异步套接字处理器
* asynchat: asynchat --- 异步套接字指令/响应处理程序. 异步套接字指令/响应处理程序
* signal: signal --- 设置异步事件处理程序. 设置异步事件处理程序
* mmap: mmap --- 内存映射文件支持. 内存映射文件支持


File: python.info,  Node: asyncio --- 异步 I/O,  Next: socket --- 底层网络接口,  Up: 网络和进程间通信

5.18.1 ‘asyncio’ — 异步 I/O
---------------------------

__________________________________________________________________

Hello World!
............

     import asyncio

     async def main():
         print('Hello ...')
         await asyncio.sleep(1)
         print('... World!')

     # Python 3.7+
     asyncio.run(main())

asyncio 是用来编写 `并发' 代码的库，使用 `async/await' 语法。

asyncio 被用作多个提供高性能 Python 异步框架的基础，包括网络和网站服务，
数据库连接库，分布式任务队列等等。

asyncio 往往是构建 IO 密集型和高层级 `结构化' 网络代码的最佳选择。

asyncio 提供一组 `高层级' API 用于:

   * 并发地 *note 运行 Python 协程: 2637. 并对其执行过程实现完全控制;

   * 执行 *note 网络 IO 和 IPC: 2638.;

   * 控制 *note 子进程: 2639.;

   * 通过 *note 队列: 263a. 实现分布式任务;

   * *note 同步: 263b. 并发代码;

此外，还有一些 `低层级' API 以支持 `库和框架的开发者' 实现:

   * 创建和管理 *note 事件循环: 737.，以提供异步 API 用于 *note 网络化:
     465, 运行 *note 子进程: 263c.，处理 *note OS 信号: 263d. 等等;

   * 使用 *note transports: 263e. 实现高效率协议;

   * 通过 async/await 语法 *note 桥接: 263f. 基于回调的库和代码。

参考引用
........

* Menu:

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


File: python.info,  Node: 协程与任务,  Next: 流,  Up: asyncio --- 异步 I/O

5.18.1.1 协程与任务
...................

本节将简述用于协程与任务的高层级 API。

* Menu:

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


File: python.info,  Node: 协程<3>,  Next: 可等待对象<2>,  Up: 协程与任务

5.18.1.2 协程
.............

*note 协程: 18a. 通过 async/await 语法进行声明，是编写 asyncio 应用的推
荐方式。 例如，以下代码段（需要 Python 3.7+）会打印 "hello"，等待 1 秒，
再打印 "world":

     >>> import asyncio

     >>> async def main():
     ...     print('hello')
     ...     await asyncio.sleep(1)
     ...     print('world')

     >>> asyncio.run(main())
     hello
     world

注意：简单地调用一个协程并不会使其被调度执行

     >>> main()
     <coroutine object main at 0x1053bb7c8>

要真正运行一个协程，asyncio 提供了三种主要机制:

   * *note asyncio.run(): 18d. 函数用来运行最高层级的入口点 "main()" 函
     数 (参见上面的示例。)

   * 等待一个协程。以下代码段会在等待 1 秒后打印 "hello"，然后 `再次' 等
     待 2 秒后打印 "world":

          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())

     预期的输出:

          started at 17:13:52
          hello
          world
          finished at 17:13:55

   * *note asyncio.create_task(): 2e1. 函数用来并发运行作为 asyncio
     *note 任务: 2e0. 的多个协程。

     让我们修改以上示例，`并发' 运行两个 ‘say_after’ 协程:

          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')}")

     注意，预期的输出显示代码段的运行时间比之前快了 1 秒:

          started at 17:14:32
          hello
          world
          finished at 17:14:34


File: python.info,  Node: 可等待对象<2>,  Next: 运行 asyncio 程序,  Prev: 协程<3>,  Up: 协程与任务

5.18.1.3 可等待对象
...................

如果一个对象可以在 *note await: 2d8. 语句中使用，那么它就是 `可等待' 对
象。许多 asyncio API 都被设计为接受可等待对象。

`可等待' 对象有三种主要类型: `协程', `任务' 和 `Future'.

协程
....

Python 协程属于 `可等待' 对象，因此可以在其他协程中被等待:

     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())

     重要: 在本文档中 "协程" 可用来表示两个紧密关联的概念:

        * `协程函数': 定义形式为 *note async def: 3a9. 的函数;

        * `协程对象': 调用 `协程函数' 所返回的对象。

asyncio 也支持旧式的 *note 基于生成器的: 2645. 协程。

任务
....

`任务' 被用来“并行的”调度协程

当一个协程通过 *note asyncio.create_task(): 2e1. 等函数被封装为一个 `任
务'，该协程会被自动调度执行:

     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())

Future 对象
...........

*note Future: 545. 是一种特殊的 `低层级' 可等待对象，表示一个异步操作的
`最终结果'。

当一个 Future 对象 `被等待'，这意味着协程将保持等待直到该 Future 对象在
其他地方操作完毕。

在 asyncio 中需要 Future 对象以便允许通过 async/await 使用基于回调的代码
。

通常情况下 `没有必要' 在应用层级的代码中创建 Future 对象。

Future 对象有时会由库和某些 asyncio API 暴露给用户，用作可等待对象:

     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()
         )

一个很好的返回对象的低层级函数的示例是 *note loop.run_in_executor():
190.。


File: python.info,  Node: 运行 asyncio 程序,  Next: 创建任务,  Prev: 可等待对象<2>,  Up: 协程与任务

5.18.1.4 运行 asyncio 程序
..........................

 -- 函式: asyncio.run (coro, *, debug=False)

     执行 *note coroutine: 18a. `coro' 并返回结果。

     此函数会运行传入的协程，负责管理 asyncio 事件循环，`终结异步生成器
     '，并关闭线程池。

     当有其他 asyncio 事件循环在同一线程中运行时，此函数不能被调用。

     如果 `debug' 为 ‘True’，事件循环将以调试模式运行。

     此函数总是会创建一个新的事件循环并在结束时关闭之。它应当被用作
     asyncio 程序的主入口点，理想情况下应当只被调用一次。

     示例:

          async def main():
              await asyncio.sleep(1)
              print('hello')

          asyncio.run(main())

     3.7 版新加入.

     3.9 版更變: 更新为使用 *note loop.shutdown_default_executor():
     18b.。

          備註: ‘asyncio.run()’ 的源代码可以在 Lib/asyncio/runners.py(1)
          中找到。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/asyncio/runners.py


File: python.info,  Node: 创建任务,  Next: 休眠,  Prev: 运行 asyncio 程序,  Up: 协程与任务

5.18.1.5 创建任务
.................

 -- 函式: asyncio.create_task (coro, *, name=None)

     将 `coro' *note 协程: 2637. 封装为一个 *note Task: 2e0. 并调度其执
     行。返回 Task 对象。

     `name' 不为 ‘None’，它将使用 *note Task.set_name(): 2e3. 来设为任务
     的名称。

     该任务会在 *note get_running_loop(): 45c. 返回的循环中执行，如果当
     前线程没有在运行的循环则会引发 *note RuntimeError: 3dc.。

     此函数 `在 Python 3.7 中被加入'。在 Python 3.7 之前，可以改用低层级
     的 *note asyncio.ensure_future(): 610. 函数。

          async def coro():
              ...

          # In Python 3.7+
          task = asyncio.create_task(coro())
          ...

          # This works in all Python versions but is less readable
          task = asyncio.ensure_future(coro())
          ...

          重要: Save a reference to the result of this function, to
          avoid a task disappearing mid execution.

     3.7 版新加入.

     3.8 版更變: 添加了 ‘name’ 形参。


File: python.info,  Node: 休眠,  Next: 并发运行任务,  Prev: 创建任务,  Up: 协程与任务

5.18.1.6 休眠
.............

 -- 函式: coroutine asyncio.sleep (delay, result=None, *, loop=None)

     阻塞 `delay' 指定的秒数。

     如果指定了 `result'，则当协程完成时将其返回给调用者。

     ‘sleep()’ 总是会挂起当前任务，以允许其他任务运行。

     将 delay 设为 0 将提供一个经优化的路径以允许其他任务运行。 这可供长
     期间运行的函数使用以避免在函数调用的全过程中阻塞事件循环。

     Deprecated since version 3.8, will be removed in version 3.10:
     `loop' 形参。

     以下协程示例运行 5 秒，每秒显示一次当前日期:

          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())


File: python.info,  Node: 并发运行任务,  Next: 屏蔽取消操作,  Prev: 休眠,  Up: 协程与任务

5.18.1.7 并发运行任务
.....................

 -- 函式: awaitable asyncio.gather (*aws, loop=None,
          return_exceptions=False)

     `并发' 运行 `aws' 序列中的 *note 可等待对象: 2643.。

     如果 `aws' 中的某个可等待对象为协程，它将自动被作为一个任务调度。

     如果所有可等待对象都成功完成，结果将是一个由所有返回值聚合而成的列
     表。结果值的顺序与 `aws' 中可等待对象的顺序一致。

     如果 `return_exceptions' 为 ‘False’ (默认)，所引发的首个异常会立即
     传播给等待 ‘gather()’ 的任务。`aws' 序列中的其他可等待对象 `不会被
     取消' 并将继续运行。

     如果 `return_exceptions' 为 ‘True’，异常会和成功的结果一样处理，并
     聚合至结果列表。

     如果 ‘gather()’ `被取消'，所有被提交 (尚未完成) 的可等待对象也会 `被
     取消'。

     如果 `aws' 序列中的任一 Task 或 Future 对象 `被取消'，它将被当作引
     发了 *note CancelledError: 2da. 一样处理 – 在此情况下 ‘gather()’ 调
     用 `不会' 被取消。这是为了防止一个已提交的 Task/Future 被取消导致其
     他 Tasks/Future 也被取消。

     Deprecated since version 3.8, will be removed in version 3.10:
     `loop' 形参。

     示例:

          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]

          備註: 如果 `return_exceptions' 为 False，则在 gather() 被标记
          为已完成后取消它将不会取消任何已提交的可等待对象。 例如，在将
          一个异常传播给调用者之后，gather 可被标记为已完成，因此，在从
          gather 捕获一个（由可等待对象所引发的）异常之后调用
          ‘gather.cancel()’ 将不会取消任何其他可等待对象。

     3.7 版更變: 如果 `gather' 本身被取消，则无论 `return_exceptions' 取
     值为何，消息都会被传播。


File: python.info,  Node: 屏蔽取消操作,  Next: 超时,  Prev: 并发运行任务,  Up: 协程与任务

5.18.1.8 屏蔽取消操作
.....................

 -- 函式: awaitable asyncio.shield (aw, *, loop=None)

     保护一个 *note 可等待对象: 2643. 防止其被 *note 取消: 264d.。

     如果 `aw' 是一个协程，它将自动被作为任务调度。

     以下语句:

          res = await shield(something())

     相当于:

          res = await something()

     `不同之处' 在于如果包含它的协程被取消，在 ‘something()’ 中运行的任
     务不会被取消。从 ‘something()’ 的角度看来，取消操作并没有发生。然而
     其调用者已被取消，因此 "await" 表达式仍然会引发 *note
     CancelledError: 2da.。

     如果通过其他方式取消 ‘something()’ (例如在其内部操作) 则 ‘shield()’
     也会取消。

     如果希望完全忽略取消操作 (不推荐) 则 ‘shield()’ 函数需要配合一个
     try/except 代码段，如下所示:

          try:
              res = await shield(something())
          except CancelledError:
              res = None

     Deprecated since version 3.8, will be removed in version 3.10:
     `loop' 形参。


File: python.info,  Node: 超时,  Next: 简单等待,  Prev: 屏蔽取消操作,  Up: 协程与任务

5.18.1.9 超时
.............

 -- 函式: coroutine asyncio.wait_for (aw, timeout, *, loop=None)

     等待 `aw' *note 可等待对象: 2643. 完成，指定 timeout 秒数后超时。

     如果 `aw' 是一个协程，它将自动被作为任务调度。

     `timeout' 可以为 ‘None’，也可以为 float 或 int 型数值表示的等待秒数
     。如果 `timeout' 为 ‘None’，则等待直到完成。

     如果发生超时，任务将取消并引发 *note asyncio.TimeoutError: 264f.

     要避免任务 *note 取消: 264d.，可以加上 *note shield(): 3ac.。

     此函数将等待直到 Future 确实被取消，所以总等待时间可能超过
     `timeout'。 如果在取消期间发生了异常，异常将会被传播。

     如果等待被取消，则 `aw' 指定的对象也会被取消。

     Deprecated since version 3.8, will be removed in version 3.10:
     `loop' 形参。

     示例:

          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!

     3.7 版更變: 当 `aw' 因超时被取消，‘wait_for’ 会等待 `aw' 被取消。之
     前版本则将立即引发 *note asyncio.TimeoutError: 264f.。


File: python.info,  Node: 简单等待,  Next: 在线程中运行,  Prev: 超时,  Up: 协程与任务

5.18.1.10 简单等待
..................

 -- 函式: coroutine asyncio.wait (aws, *, loop=None, timeout=None,
          return_when=ALL_COMPLETED)

     并发地运行 `aws' 可迭代对象中的 *note 可等待对象: 2643. 并进入阻塞
     状态直到满足 `return_when' 所指定的条件。

     `aws' 可迭代对象必须不为空。

     返回两个 Task/Future 集合: ‘(done, pending)’。

     用法:

          done, pending = await asyncio.wait(aws)

     如指定 `timeout' (float 或 int 类型) 则它将被用于控制返回之前等待的
     最长秒数。

     请注意此函数不会引发 *note asyncio.TimeoutError: 264f.。当超时发生
     时，未完成的 Future 或 Task 将在指定秒数后被返回。

     `return_when' 指定此函数应在何时返回。它必须为以下常数之一:

     常数                              描述
                                       
     -------------------------------------------------------------------------------
                                       
     ‘FIRST_COMPLETED’                 函数将在任意可等待对象结束或取消时返回。
                                       
                                       
     ‘FIRST_EXCEPTION’                 函数将在任意可等待对象因引发异常而结束时返
                                       回。当没有引发任何异常时它就相当于
                                       ‘ALL_COMPLETED’。
                                       
                                       
     ‘ALL_COMPLETED’                   函数将在所有可等待对象结束或取消时返回。
                                       

     与 *note wait_for(): 191. 不同，‘wait()’ 在超时发生时不会取消可等待
     对象。

     3.8 版後已棄用: 如果 `aws' 中的某个可等待对象为协程，它将自动被作为
     任务调度。直接向 ‘wait()’ 传入协程对象已弃用，因为这会导致 *note
     令人迷惑的行为: 2652.。

     Deprecated since version 3.8, will be removed in version 3.10:
     `loop' 形参。

          備註: ‘wait()’ 会自动以任务的形式调度协程，之后将以 ‘(done,
          pending)’ 集合形式返回显式创建的任务对象。因此以下代码并不会有
          预期的行为:

               async def foo():
                   return 42

               coro = foo()
               done, pending = await asyncio.wait({coro})

               if coro in done:
                   # This branch will never be run!

          以上代码段的修正方法如下:

               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.

     Deprecated since version 3.8, will be removed in version 3.11: 直接
     向 ‘wait()’ 传入协程对象的方式已弃用。

 -- 函式: asyncio.as_completed (aws, *, loop=None, timeout=None)

     并发地运行 `aws' 可迭代对象中的 *note 可等待对象: 2643.。 返回一个
     协程的迭代器。 所返回的每个协程可被等待以从剩余的可等待对象的可迭代
     对象中获得最早的下一个结果。

     如果在所有 Future 对象完成前发生超时则将引发 *note
     asyncio.TimeoutError: 264f.。

     Deprecated since version 3.8, will be removed in version 3.10:
     `loop' 形参。

     示例:

          for coro in as_completed(aws):
              earliest_result = await coro
              # ...


File: python.info,  Node: 在线程中运行,  Next: 跨线程调度,  Prev: 简单等待,  Up: 协程与任务

5.18.1.11 在线程中运行
......................

 -- 函式: coroutine asyncio.to_thread (func, /, *args, **kwargs)

     在不同的线程中异步地运行函数 `func'。

     向此函数提供的任何 *args 和 **kwargs 会被直接传给 `func'。 并且，当
     前 *note contextvars.Context: 260f. 会被传播，允许在不同的线程中访
     问来自事件循环的上下文变量。

     返回一个可被等待以获取 `func' 的最终结果的协程。

     这个协程函数主要是用于执行在其他情况下会阻塞事件循环的 IO 密集型函
     数/方法。 例如:

          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

     在任何协程中直接调用 ‘blocking_io()’ 将会在调用期间阻塞事件循环，导
     致额外的 1 秒运行时间。 而通过改用 ‘asyncio.to_thread()’，我们可以
     在不同的线程中运行它从而不会阻塞事件循环。

          備註: 由于 *note GIL: 20e. 的存在，‘asyncio.to_thread()’ 通常
          只能被用来将 IO 密集型函数变为非阻塞的。 但是，对于会释放 GIL
          的扩展模块或无此限制的替代性 Python 实现来说，
          ‘asyncio.to_thread()’ 也可被用于 CPU 密集型函数。

     3.9 版新加入.


File: python.info,  Node: 跨线程调度,  Next: 内省,  Prev: 在线程中运行,  Up: 协程与任务

5.18.1.12 跨线程调度
....................

 -- 函式: asyncio.run_coroutine_threadsafe (coro, loop)

     向指定事件循环提交一个协程。（线程安全）

     返回一个 *note concurrent.futures.Future: c00. 以等待来自其他 OS 线
     程的结果。

     此函数应该从另一个 OS 线程中调用，而非事件循环运行所在线程。示例:

          # 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

     如果在协程内产生了异常，将会通知返回的 Future 对象。它也可被用来取
     消事件循环中的任务:

          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}')

     查看 *note 并发和多线程: 2655. 章节的文档。

     不同与其他 asyncio 函数，此函数要求显式地传入 `loop' 参数。

     3.5.1 版新加入.


File: python.info,  Node: 内省,  Next: Task 对象,  Prev: 跨线程调度,  Up: 协程与任务

5.18.1.13 内省
..............

 -- 函式: asyncio.current_task (loop=None)

     返回当前运行的 *note Task: 2e0. 实例，如果没有正在运行的任务则返回
     ‘None’。

     如果 `loop' 为 ‘None’ 则会使用 *note get_running_loop(): 45c. 获取
     当前事件循环。

     3.7 版新加入.

 -- 函式: asyncio.all_tasks (loop=None)

     返回事件循环所运行的未完成的 *note Task: 2e0. 对象的集合。

     如果 `loop' 为 ‘None’，则会使用 *note get_running_loop(): 45c. 获取
     当前事件循环。

     3.7 版新加入.


File: python.info,  Node: Task 对象,  Next: 基于生成器的协程,  Prev: 内省,  Up: 协程与任务

5.18.1.14 Task 对象
...................

 -- 類別: asyncio.Task (coro, *, loop=None, name=None)

     一个与 *note Future 类似: 545. 的对象，可运行 Python *note 协程:
     2637.。非线程安全。

     Task 对象被用来在事件循环中运行协程。如果一个协程在等待一个 Future
     对象，Task 对象会挂起该协程的执行并等待该 Future 对象完成。当该
     Future 对象 `完成'，被打包的协程将恢复执行。

     事件循环使用协同日程调度: 一个事件循环每次运行一个 Task 对象。而一
     个 Task 对象会等待一个 Future 对象完成，该事件循环会运行其他 Task、
     回调或执行 IO 操作。

     使用高层级的 *note asyncio.create_task(): 2e1. 函数来创建 Task 对象
     ，也可用低层级的 *note loop.create_task(): 2e2. 或 *note
     ensure_future(): 610. 函数。不建议手动实例化 Task 对象。

     要取消一个正在运行的 Task 对象可使用 *note cancel(): 264d. 方法。调
     用此方法将使该 Task 对象抛出一个 *note CancelledError: 2da. 异常给
     打包的协程。如果取消期间一个协程正在等待一个 Future 对象，该 Future
     对象也将被取消。

     *note cancelled(): 2658. 可被用来检测 Task 对象是否被取消。如果打包
     的协程没有抑制 *note CancelledError: 2da. 异常并且确实被取消，该方
     法将返回 ‘True’。

     *note asyncio.Task: 2e0. 从 *note Future: 545. 继承了其除 *note
     Future.set_result(): 2659. 和 *note Future.set_exception(): 265a. 以
     外的所有 API。

     Task 对象支持 *note contextvars: 24. 模块。当一个 Task 对象被创建，
     它将复制当前上下文，然后在复制的上下文中运行其协程。

     3.7 版更變: 加入对 *note contextvars: 24. 模块的支持。

     3.8 版更變: 添加了 ‘name’ 形参。

     Deprecated since version 3.8, will be removed in version 3.10:
     `loop' 形参。

      -- 成員函式: cancel (msg=None)

          请求取消 Task 对象。

          这将安排在下一轮事件循环中抛出一个 *note CancelledError: 2da.
          异常给被封包的协程。

          协程在之后有机会进行清理甚至使用 *note try: e37. ...  ...
          ‘except CancelledError’ ...  *note finally: 2bc. 代码块抑制异
          常来拒绝请求。不同于 *note Future.cancel(): 265b.，*note
          Task.cancel(): 264d. 不保证 Task 会被取消，虽然抑制完全取消并
          不常见，也很不鼓励这样做。

          3.9 版更變: 增加了 ‘msg’ 形参。

          以下示例演示了协程是如何侦听取消请求的:

               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

      -- 成員函式: cancelled ()

          如果 Task 对象 `被取消' 则返回 ‘True’。

          当使用 *note cancel(): 264d. 发出取消请求时 Task 会被 `取消'，
          其封包的协程将传播被抛入的 *note CancelledError: 2da. 异常。

      -- 成員函式: done ()

          如果 Task 对象 `已完成' 则返回 ‘True’。

          当 Task 所封包的协程返回一个值、引发一个异常或 Task 本身被取消
          时，则会被认为 `已完成'。

      -- 成員函式: result ()

          返回 Task 的结果。

          如果 Task 对象 `已完成'，其封包的协程的结果会被返回 (或者当协
          程引发异常时，该异常会被重新引发。)

          如果 Task 对象 `被取消'，此方法会引发一个 *note
          CancelledError: 2da. 异常。

          如果 Task 对象的结果还不可用，此方法会引发一个 *note
          InvalidStateError: 265f. 异常。

      -- 成員函式: exception ()

          返回 Task 对象的异常。

          如果所封包的协程引发了一个异常，该异常将被返回。如果所封包的协
          程正常返回则该方法将返回 ‘None’。

          如果 Task 对象 `被取消'，此方法会引发一个 *note
          CancelledError: 2da. 异常。

          如果 Task 对象尚未 `完成'，此方法将引发一个 *note
          InvalidStateError: 265f. 异常。

      -- 成員函式: add_done_callback (callback, *, context=None)

          添加一个回调，将在 Task 对象 `完成' 时被运行。

          此方法应该仅在低层级的基于回调的代码中使用。

          要了解更多细节请查看 *note Future.add_done_callback(): 459. 的
          文档。

      -- 成員函式: remove_done_callback (callback)

          从回调列表中移除 `callback' 指定的回调。

          此方法应该仅在低层级的基于回调的代码中使用。

          要了解更多细节请查看 *note Future.remove_done_callback():
          2663. 的文档。

      -- 成員函式: get_stack (*, limit=None)

          返回此 Task 对象的栈框架列表。

          如果所封包的协程未完成，这将返回其挂起所在的栈。如果协程已成功
          完成或被取消，这将返回一个空列表。如果协程被一个异常终止，这将
          返回回溯框架列表。

          框架总是从按从旧到新排序。

          每个被挂起的协程只返回一个栈框架。

          可选的 `limit' 参数指定返回框架的数量上限；默认返回所有框架。
          返回列表的顺序要看是返回一个栈还是一个回溯：栈返回最新的框架，
          回溯返回最旧的框架。(这与 traceback 模块的行为保持一致。)

      -- 成員函式: print_stack (*, limit=None, file=None)

          打印此 Task 对象的栈或回溯。

          此方法产生的输出类似于 traceback 模块通过 *note get_stack():
          2664. 所获取的框架。

          `limit' 参数会直接传递给 *note get_stack(): 2664.。

          `file' 参数是输出所写入的 I/O 流；默认情况下输出会写入 *note
          sys.stderr: 1ea.。

      -- 成員函式: get_coro ()

          返回由 *note Task: 2e0. 包装的协程对象。

          3.8 版新加入.

      -- 成員函式: get_name ()

          返回 Task 的名称。

          如果没有一个 Task 名称被显式地赋值，默认的 asyncio Task 实现会
          在实例化期间生成一个默认名称。

          3.8 版新加入.

      -- 成員函式: set_name (value)

          设置 Task 的名称。

          `value' 参数可以为任意对象，它随后会被转换为字符串。

          在默认的 Task 实现中，名称将在任务对象的 *note repr(): 8b9. 输
          出中可见。

          3.8 版新加入.


File: python.info,  Node: 基于生成器的协程,  Prev: Task 对象,  Up: 协程与任务

5.18.1.15 基于生成器的协程
..........................

     備註: 对基于生成器的协程的支持 `已弃用' 并计划在 Python 3.10 中移除
     。

基于生成器的协程是 async/await 语法的前身。它们是使用 ‘yield from’ 语句
创建的 Python 生成器，可以等待 Future 和其他协程。

基于生成器的协程应该使用 *note @asyncio.coroutine: 3a8. 装饰，虽然这并非
强制。

 -- 函式: @asyncio.coroutine

     用来标记基于生成器的协程的装饰器。

     此装饰器使得旧式的基于生成器的协程能与 async/await 代码相兼容:

          @asyncio.coroutine
          def old_style_coroutine():
              yield from asyncio.sleep(1)

          async def main():
              await old_style_coroutine()

     此装饰器不应该被用于 *note async def: 3a9. 协程。

     Deprecated since version 3.8, will be removed in version 3.10: 请改
     用 *note async def: 3a9.。

 -- 函式: asyncio.iscoroutine (obj)

     如果 `obj' 是一个 *note 协程对象: 2637. 则返回 ‘True’。

     此方法不同于 *note inspect.iscoroutine(): 7e8. 因为它对基于生成器的
     协程返回 ‘True’。

 -- 函式: asyncio.iscoroutinefunction (func)

     如果 `func' 是一个 *note 协程函数: 2637. 则返回 ‘True’。

     此方法不同于 *note inspect.iscoroutinefunction(): 7e9. 因为它对以
     *note @coroutine: 3a8. 装饰的基于生成器的协程函数返回 ‘True’。


File: python.info,  Node: 流,  Next: 同步原语<2>,  Prev: 协程与任务,  Up: asyncio --- 异步 I/O

5.18.1.16 流
............

`源码:' Lib/asyncio/streams.py(1)

__________________________________________________________________

流是用于处理网络连接的支持 async/await 的高层级原语。 流允许发送和接收数
据，而不需要使用回调或低级协议和传输。 下面是一个使用 asyncio streams 编
写的 TCP echo 客户端示例:

     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!'))

参见下面的 *note Examples: 266c. 部分。

Stream 函数
...........

下面的高级 asyncio 函数可以用来创建和处理流:

 -- 函式: 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)

     建立网络连接并返回一对 ‘(reader, writer)’ 对象。

     返回的 `reader' 和 `writer' 对象是 *note StreamReader: 1105. 和
     *note StreamWriter: 1106. 类的实例。

     `loop' 参数是可选的，当从协程中等待该函数时，总是可以自动确定。

     `limit' 确定返回的 *note StreamReader: 1105. 实例使用的缓冲区大小限
     制。默认情况下，`limit' 设置为 64 KiB 。

     其余的参数直接传递到 *note loop.create_connection(): 2e5. 。

     3.7 版新加入: `ssl_handshake_timeout' 形参。

 -- 函式: 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)

     启动套接字服务。

     当一个新的客户端连接被建立时，回调函数 `client_connected_cb' 会被调
     用。该函数会接收到一对参数 ‘(reader, writer)’ ，reader是类 *note
     StreamReader: 1105. 的实例，而writer是类 *note StreamWriter: 1106.
     的实例。

     `client_connected_cb' 即可以是普通的可调用对象也可以是一个 *note
     协程函数: 2637.; 如果它是一个协程函数，它将自动作为 *note Task:
     2e0. 被调度。

     `loop' 参数是可选的。当在一个协程中await该方法时，该参数始终可以自
     动确定。

     `limit' 确定返回的 *note StreamReader: 1105. 实例使用的缓冲区大小限
     制。默认情况下，`limit' 设置为 64 KiB 。

     余下的参数将会直接传递给 *note loop.create_server(): 465.

     3.7 版新加入: The `ssl_handshake_timeout' and `start_serving'
     parameters.

Unix 套接字
...........

 -- 函式: coroutine asyncio.open_unix_connection (path=None, *,
          loop=None, limit=None, ssl=None, sock=None,
          server_hostname=None, ssl_handshake_timeout=None)

     建立一个 Unix 套接字连接并返回 ‘(reader, writer)’ 这对返回值。

     与 *note open_connection(): 46b. 相似，但是是在 Unix 套接字上的操作
     。

     请看文档 *note loop.create_unix_connection(): 266e.

     *note 可用性: 1491.: Unix。

     3.7 版新加入: `ssl_handshake_timeout' 形参。

     3.7 版更變: `path' 现在是一个 *note path-like object: 472.

 -- 函式: 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 套接字服务。

     与 *note start_server(): 46c. 相似，但是是在 Unix 套接字上的操作。

     请看文档 *note loop.create_unix_server(): 466.

     *note 可用性: 1491.: Unix。

     3.7 版新加入: The `ssl_handshake_timeout' and `start_serving'
     parameters.

     3.7 版更變: `path' 形参现在可以是 *note path-like object: 472. 对象
     。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/asyncio/streams.py


File: python.info,  Node: StreamReader,  Next: StreamWriter,  Up: 流

5.18.1.17 StreamReader
......................

 -- 類別: asyncio.StreamReader

     这个类表示一个读取器对象，该对象提供api以便于从IO流中读取数据。

     不推荐直接实例化 `StreamReader' 对象，建议使用 *note
     open_connection(): 46b. 和 *note start_server(): 46c. 来获取
     `StreamReader' 实例。

      -- 成員函式: coroutine read (n=-1)

          至多读取 `n' 个byte。 如果没有设置 `n' , 则自动置为 ‘-1’ ，
          -1时表示读至 EOF 并返回所有读取的byte。

          如果读到EOF，且内部缓冲区为空，则返回一个空的 ‘bytes’ 对象。

      -- 成員函式: coroutine readline ()

          读取一行，其中“行”指的是以 ‘\n’ 结尾的字节序列。

          如果读到EOF而没有找到 ‘\n’ ，该方法返回部分读取的数据。

          如果读到EOF，且内部缓冲区为空，则返回一个空的 ‘bytes’ 对象。

      -- 成員函式: coroutine readexactly (n)

          精确读取 `n' 个 bytes，不会超过也不能少于。

          如果在读取完 `n' 个byte之前读取到EOF，则会引发 *note
          IncompleteReadError: fdb. 异常。使用 *note
          IncompleteReadError.partial: 2673. 属性来获取到达流结束之前读
          取的 bytes 字符串。

      -- 成員函式: coroutine readuntil (separator=b'\n')

          从流中读取数据直至遇到 `separator'

          成功后，数据和指定的separator将从内部缓冲区中删除(或者说被消费
          掉)。返回的数据将包括在末尾的指定separator。

          如果读取的数据量超过了配置的流限制，将引发 *note
          LimitOverrunError: 2674. 异常，数据将留在内部缓冲区中并可以再
          次读取。

          如果在找到完整的separator之前到达EOF，则会引发 *note
          IncompleteReadError: fdb. 异常，并重置内部缓冲区。 *note
          IncompleteReadError.partial: 2673. 属性可能包含指定separator的
          一部分。

          3.5.2 版新加入.

      -- 成員函式: at_eof ()

          如果缓冲区为空并且 ‘feed_eof()’ 被调用，则返回 ‘True’ 。


File: python.info,  Node: StreamWriter,  Next: 示例<18>,  Prev: StreamReader,  Up: 流

5.18.1.18 StreamWriter
......................

 -- 類別: asyncio.StreamWriter

     这个类表示一个写入器对象，该对象提供api以便于写数据至IO流中。

     不建议直接实例化 `StreamWriter'；而应改用 *note open_connection():
     46b. 和 *note start_server(): 46c.。

      -- 成員函式: write (data)

          此方法会尝试立即将 `data' 写入到下层的套接字。 如果写入失败，
          数据会被排入内部写缓冲队列直到可以被发送。

          此方法应当与 ‘drain()’ 方法一起使用:

               stream.write(data)
               await stream.drain()

      -- 成員函式: writelines (data)

          此方法会立即尝试将一个字节串列表（或任何可迭代对象）写入到下层
          的套接字。 如果写入失败，数据会被排入内部写缓冲队列直到可以被
          发送。

          此方法应当与 ‘drain()’ 方法一起使用:

               stream.writelines(lines)
               await stream.drain()

      -- 成員函式: close ()

          此方法会关闭流以及下层的套接字。

          此方法应与 ‘wait_closed()’ 方法一起使用:

               stream.close()
               await stream.wait_closed()

      -- 成員函式: can_write_eof ()

          如果下层的传输支持 *note write_eof(): 267b. 方法则返回
          ‘‘True‘‘，否则返回 ‘False’。

      -- 成員函式: write_eof ()

          在已缓冲的写入数据被刷新后关闭流的写入端。

      -- 屬性: transport

          返回下层的 asyncio 传输。

      -- 成員函式: get_extra_info (name, default=None)

          访问可选的传输信息；详情参见 *note
          BaseTransport.get_extra_info(): 3ea.。

      -- 成員函式: coroutine drain ()

          等待直到可以适当地恢复写入到流。 示例:

               writer.write(data)
               await writer.drain()

          这是一个与下层的 IO 写缓冲区进行交互的流程控制方法。 当缓冲区
          大小达到最高水位（最大上限）时，`drain()' 会阻塞直到缓冲区大小
          减少至最低水位以便恢复写入。 当没有要等待的数据时，*note
          drain(): 267e. 会立即返回。

      -- 成員函式: is_closing ()

          如果流已被关闭或正在被关闭则返回 ‘True’。

          3.7 版新加入.

      -- 成員函式: coroutine wait_closed ()

          等待直到流被关闭。

          应当在 *note close(): 2679. 之后被调用以便等待直到下层的连接被
          关闭。

          3.7 版新加入.


File: python.info,  Node: 示例<18>,  Prev: StreamWriter,  Up: 流

5.18.1.19 示例
..............

* Menu:

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


File: python.info,  Node: 使用流的 TCP 回显客户端,  Next: 使用流的 TCP 回显服务器,  Up: 示例<18>

5.18.1.20 使用流的 TCP 回显客户端
.................................

使用 *note asyncio.open_connection(): 46b. 函数的 TCP 回显客户端:

     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!'))

也參考
......

使用低层级 *note loop.create_connection(): 2e5. 方法的 *note TCP
回显客户端协议: 2681. 示例。


File: python.info,  Node: 使用流的 TCP 回显服务器,  Next: 获取 HTTP 标头,  Prev: 使用流的 TCP 回显客户端,  Up: 示例<18>

5.18.1.21 使用流的 TCP 回显服务器
.................................

TCP 回显服务器使用 *note asyncio.start_server(): 46c. 函数:

     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())

也參考
......

使用 *note loop.create_server(): 465. 方法的 *note TCP 回显服务器协议:
2684. 示例。


File: python.info,  Node: 获取 HTTP 标头,  Next: 注册一个打开的套接字以等待使用流的数据,  Prev: 使用流的 TCP 回显服务器,  Up: 示例<18>

5.18.1.22 获取 HTTP 标头
........................

查询命令行传入 URL 的 HTTP 标头的简单示例:

     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))

用法:

     python example.py http://example.com/path/page.html

或使用 HTTPS:

     python example.py https://example.com/path/page.html


File: python.info,  Node: 注册一个打开的套接字以等待使用流的数据,  Prev: 获取 HTTP 标头,  Up: 示例<18>

5.18.1.23 注册一个打开的套接字以等待使用流的数据
................................................

使用 *note open_connection(): 46b. 函数实现等待直到套接字接收到数据的协
程:

     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())

也參考
......

使用低层级协议以及 *note loop.create_connection(): 2e5. 方法的 *note
注册一个打开的套接字以等待使用协议的数据: 2688. 示例。

使用低层级的 *note loop.add_reader(): 2689. 方法来监视文件描述符的 *note
监视文件描述符以读取事件: 268a. 示例。


File: python.info,  Node: 同步原语<2>,  Next: 子进程,  Prev: 流,  Up: asyncio --- 异步 I/O

5.18.1.24 同步原语
..................

`源代码:' Lib/asyncio/locks.py(1)

__________________________________________________________________

asyncio 同步原语被设计为与 *note threading: 10b. 模块的类似，但有两个关
键注意事项:

   * asyncio 原语不是线程安全的，因此它们不应被用于 OS 线程同步 (而应当
     使用 *note threading: 10b.)；

   * 这些同步原语的方法不接受 `timeout' 参数；请使用 *note
     asyncio.wait_for(): 191. 函数来执行带有超时的操作。

asyncio 具有下列基本同步原语:

   * *note Lock: 3ae.

   * *note Event: 3af.

   * *note Condition: 3b0.

   * *note Semaphore: 3b1.

   * *note BoundedSemaphore: 3b2.

__________________________________________________________________

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/asyncio/locks.py


File: python.info,  Node: Lock,  Next: Event,  Up: 同步原语<2>

5.18.1.25 Lock
..............

 -- 類別: asyncio.Lock (*, loop=None)

     实现一个用于 asyncio 任务的互斥锁。 非线程安全。

     asyncio 锁可被用来保证对共享资源的独占访问。

     使用 Lock 的推荐方式是通过 *note async with: 736. 语句:

          lock = asyncio.Lock()

          # ... later
          async with lock:
              # access shared state

     这等价于:

          lock = asyncio.Lock()

          # ... later
          await lock.acquire()
          try:
              # access shared state
          finally:
              lock.release()

     Deprecated since version 3.8, will be removed in version 3.10:
     `loop' 形参。

      -- 成員函式: coroutine acquire ()

          获取锁。

          此方法会等待直至锁为 `unlocked'，将其设为 `locked' 并返回
          ‘True’。

          当有一个以上的协程在 *note acquire(): 268e. 中被阻塞则会等待解
          锁，最终只有一个协程会被执行。

          锁的获取是 `公平的': 被执行的协程将是第一个开始等待锁的协程。

      -- 成員函式: release ()

          释放锁。

          当锁为 `locked' 时，将其设为 `unlocked' 并返回。

          如果锁为 `unlocked'，则会引发 *note RuntimeError: 3dc.。

      -- 成員函式: locked ()

          如果锁为 `locked' 则返回 ‘True’。


File: python.info,  Node: Event,  Next: Condition,  Prev: Lock,  Up: 同步原语<2>

5.18.1.26 Event
...............

 -- 類別: asyncio.Event (*, loop=None)

     事件对象。 该对象不是线程安全的。

     asyncio 事件可被用来通知多个 asyncio 任务已经有事件发生。

     Event 对象会管理一个内部旗标，可通过 *note set(): 2692. 方法将其设
     为 `true' 并通过 *note clear(): 2693. 方法将其重设为 `false'。
     *note wait(): 2694. 方法会阻塞直至该旗标被设为 `true'。 该旗标初始
     时会被设为 `false'。

     Deprecated since version 3.8, will be removed in version 3.10:
     `loop' 形参。

     示例:

          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())

      -- 成員函式: coroutine wait ()

          等待直至事件被设置。

          如果事件已被设置，则立即返回 ‘True’。 否则将阻塞直至另一个任务
          调用 *note set(): 2692.。

      -- 成員函式: set ()

          设置事件。

          所有等待事件被设置的任务将被立即唤醒。

      -- 成員函式: clear ()

          清空（取消设置）事件。

          通过 *note wait(): 2694. 进行等待的任务现在将会阻塞直至 *note
          set(): 2692. 方法被再次调用。

      -- 成員函式: is_set ()

          如果事件已被设置则返回 ‘True’。


File: python.info,  Node: Condition,  Next: Semaphore,  Prev: Event,  Up: 同步原语<2>

5.18.1.27 Condition
...................

 -- 類別: asyncio.Condition (lock=None, *, loop=None)

     条件对象。 该对象不是线程安全的。

     asyncio 条件原语可被任务用于等待某个事件发生，然后获取对共享资源的
     独占访问。

     在本质上，Condition 对象合并了 *note Event: 3af. 和 *note Lock:
     3ae. 的功能。 多个 Condition 对象有可能共享一个 Lock，这允许关注于
     共享资源的特定状态的不同任务实现对共享资源的协同独占访问。

     可选的 `lock' 参数必须为 *note Lock: 3ae. 对象或 ‘None’。 在后一种
     情况下会自动创建一个新的 Lock 对象。

     Deprecated since version 3.8, will be removed in version 3.10:
     `loop' 形参。

     使用 Condition 的推荐方式是通过 *note async with: 736. 语句:

          cond = asyncio.Condition()

          # ... later
          async with cond:
              await cond.wait()

     这等价于:

          cond = asyncio.Condition()

          # ... later
          await cond.acquire()
          try:
              await cond.wait()
          finally:
              cond.release()

      -- 成員函式: coroutine acquire ()

          获取下层的锁。

          此方法会等待直至下层的锁为 `unlocked'，将其设为 `locked' 并返
          回 returns ‘True’。

      -- 成員函式: notify (n=1)

          唤醒最多 `n' 个正在等待此条件的任务（默认为 1 个）。 如果没有
          任务正在等待则此方法为空操作。

          锁必须在此方法被调用前被获取并在随后被快速释放。 如果通过一个
          `unlocked' 锁调用则会引发 *note RuntimeError: 3dc.。

      -- 成員函式: locked ()

          如果下层的锁已被获取则返回 ‘True’。

      -- 成員函式: notify_all ()

          唤醒所有正在等待此条件的任务。

          此方法的行为类似于 *note notify(): 2699.，但会唤醒所有正在等待
          的任务。

          锁必须在此方法被调用前被获取并在随后被快速释放。 如果通过一个
          `unlocked' 锁调用则会引发 *note RuntimeError: 3dc.。

      -- 成員函式: release ()

          释放下层的锁。

          当在未锁定的锁上发起调用时，会引发 *note RuntimeError: 3dc.。

      -- 成員函式: coroutine wait ()

          等待直至收到通知。

          当此方法被调用时如果调用方任务未获得锁，则会引发 *note
          RuntimeError: 3dc.。

          这个方法会释放下层的锁，然后保持阻塞直到被 *note notify():
          2699. 或 *note notify_all(): 269b. 调用所唤醒。 一旦被唤醒，
          Condition 会重新获取它的锁并且此方法将返回 ‘True’。

      -- 成員函式: coroutine wait_for (predicate)

          等待直到目标值变为 `true'。

          目标必须为一个可调用对象，其结果将被解读为一个布尔值。 最终的
          值将为返回值。


File: python.info,  Node: Semaphore,  Next: BoundedSemaphore,  Prev: Condition,  Up: 同步原语<2>

5.18.1.28 Semaphore
...................

 -- 類別: asyncio.Semaphore (value=1, *, loop=None)

     信号量对象。 该对象不是线程安全的。

     信号量会管理一个内部计数器，该计数器会随每次 *note acquire(): 26a0.
     调用递减并随每次 *note release(): 26a1. 调用递增。 计数器的值永远不
     会降到零以下；当 *note acquire(): 26a0. 发现其值为零时，它将保持阻
     塞直到有某个任务调用了 *note release(): 26a1.。

     可选的 `value' 参数用来为内部计数器赋初始值 (默认值为 ‘1’)。 如果给
     定的值小于 ‘0’ 则会引发 *note ValueError: 16d.。

     Deprecated since version 3.8, will be removed in version 3.10:
     `loop' 形参。

     使用 Semaphore 的推荐方式是通过 *note async with: 736. 语句。:

          sem = asyncio.Semaphore(10)

          # ... later
          async with sem:
              # work with shared resource

     这等价于:

          sem = asyncio.Semaphore(10)

          # ... later
          await sem.acquire()
          try:
              # work with shared resource
          finally:
              sem.release()

      -- 成員函式: coroutine acquire ()

          获取一个信号量。

          如果内部计数器的值大于零，则将其减一并立即返回 ‘True’。 如果其
          值为零，则会等待直到 *note release(): 26a1. 并调用并返回
          ‘True’。

      -- 成員函式: locked ()

          如果信号量对象无法被立即获取则返回 ‘True’。

      -- 成員函式: release ()

          释放一个信号量对象，将内部计数器的值加一。 可以唤醒一个正在等
          待获取信号量对象的任务。

          不同于 *note BoundedSemaphore: 3b2.，*note Semaphore: 3b1. 允
          许执行的 ‘release()’ 调用多于 ‘acquire()’ 调用。


File: python.info,  Node: BoundedSemaphore,  Prev: Semaphore,  Up: 同步原语<2>

5.18.1.29 BoundedSemaphore
..........................

 -- 類別: asyncio.BoundedSemaphore (value=1, *, loop=None)

     绑定的信号量对象。 该对象不是线程安全的。

     BoundedSemaphore 是特殊版本的 *note Semaphore: 3b1.，如果在 *note
     release(): 26a1. 中内部计数器值增加到初始 `value' 以上它将引发一个
     *note ValueError: 16d.。

     Deprecated since version 3.8, will be removed in version 3.10:
     `loop' 形参。

__________________________________________________________________

3.9 版更變: 使用 ‘await lock’ 或 ‘yield from lock’ 以及/或者 *note with:
7da. 语句 (‘with await lock’, ‘with (yield from lock)’) 来获取锁的操作已
被移除。 请改用 ‘async with lock’。


File: python.info,  Node: 子进程,  Next: 队列集,  Prev: 同步原语<2>,  Up: asyncio --- 异步 I/O

5.18.1.30 子进程
................

`源代码:' Lib/asyncio/subprocess.py(1),
Lib/asyncio/base_subprocess.py(2)

__________________________________________________________________

本节介绍了用于创建和管理子进程的高层级 async/await asyncio API。 下面的
例子演示了如何用 asyncio 运行一个 shell 命令并获取其结果:

     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'))

将打印:

     ['ls /zzz' exited with 1]
     [stderr]
     ls: /zzz: No such file or directory

由于所有 asyncio 子进程函数都是异步的并且 asyncio 提供了许多工具用来配合
这些函数使用，因此并行地执行和监视多个子进程十分容易。 要修改上面的例子
来同时运行多个命令确实是非常简单的:

     async def main():
         await asyncio.gather(
             run('ls /zzz'),
             run('sleep 1; echo "hello"'))

     asyncio.run(main())

另请参阅 *note Examples: 26a7. 小节。

* Menu:

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

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/Lib/asyncio/subprocess.py

   (2) 
https://github.com/python/cpython/tree/3.9/Lib/asyncio/base_subprocess.py


File: python.info,  Node: 创建子进程,  Next: 常数<5>,  Up: 子进程

5.18.1.31 创建子进程
....................

 -- 函式: coroutine asyncio.create_subprocess_exec (program, *args,
          stdin=None, stdout=None, stderr=None, loop=None, limit=None,
          **kwds)

     创建一个子进程。

     `limit' 参数为 ‘Process.stdout’ 和 ‘Process.stderr’ 设置 *note
     StreamReader: 1105. 包装器的缓冲区上限（如果将 *note
     subprocess.PIPE: 4f3. 传给了 `stdout' 和 `stderr' 参数）。

     返回一个 *note Process: 26a9. 实例。

     有关其他形参的说明请查阅 *note loop.subprocess_exec(): 263c. 的文档
     。

     Deprecated since version 3.8, will be removed in version 3.10:
     `loop' 形参。

 -- 函式: coroutine asyncio.create_subprocess_shell (cmd, stdin=None,
          stdout=None, stderr=None, loop=None, limit=None, **kwds)

     运行 `cmd' shell 命令。

     `limit' 参数为 ‘Process.stdout’ 和 ‘Process.stderr’ 设置 *note
     StreamReader: 1105. 包装器的缓冲区上限（如果将 *note
     subprocess.PIPE: 4f3. 传给了 `stdout' 和 `stderr' 参数）。

     返回一个 *note Process: 26a9. 实例。

     有关其他形参的说明请查阅 *note loop.subprocess_shell(): 26aa. 的文
     档。

          重要: 应用程序要负责确保正确地转义所有空白字符和特殊字符以防止
          shell 注入(1) 漏洞。 *note shlex.quote(): b4e. 函数可以被用来
          正确地转义字符串中可以被用来构造 shell 命令的空白字符和特殊
          shell 字符。

     Deprecated since version 3.8, will be removed in version 3.10:
     `loop' 形参。

     備註: 如果使用了 *note ProactorEventLoop: 2de. 则子进程将在 Windows
     中可用。 详情参见 *note Windows 上的子进程支持: 26ab.。

也參考
......

asyncio 还有下列 `低层级' API 可配合子进程使用: *note
loop.subprocess_exec(): 263c, *note loop.subprocess_shell(): 26aa, *note
loop.connect_read_pipe(): 26ac, *note loop.connect_write_pipe(): 26ad. 以
及 *note 子进程传输: 26ae. 和 *note 子进程协议: 26af.。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Shell_injection#Shell_injection


File: python.info,  Node: 常数<5>,  Next: 与子进程交互,  Prev: 创建子进程,  Up: 子进程

5.18.1.32 常数
..............

 -- Data: asyncio.subprocess.PIPE

     可以被传递给 `stdin', `stdout' 或 `stderr' 形参。

     如果 `PIPE' 被传递给 `stdin' 参数，则 *note Process.stdin: 26b2. 属
     性将会指向一个 *note StreamWriter: 1106. 实例。

     如果 `PIPE' 被传递给 `stdout' 或 `stderr' 参数，则 *note
     Process.stdout: 26b3. 和 *note Process.stderr: 26b4. 属性将会指向
     *note StreamReader: 1105. 实例。

 -- Data: asyncio.subprocess.STDOUT

     可以用作 `stderr' 参数的特殊值，表示标准错误应当被重定向到标准输出
     。

 -- Data: asyncio.subprocess.DEVNULL

     可以用作 `stdin', `stdout' 或 `stderr' 参数来处理创建函数的特殊值。
     它表示将为相应的子进程流使用特殊文件 *note os.devnull: 1152.。


File: python.info,  Node: 与子进程交互,  Prev: 常数<5>,  Up: 子进程

5.18.1.33 与子进程交互
......................

*note create_subprocess_exec(): 3b4. 和 *note create_subprocess_shell():
3b5. 函数都返回 `Process' 类的实例。 `Process' 是一个高层级包装器，它允
许与子进程通信并监视其完成情况。

 -- 類別: asyncio.subprocess.Process

     一个用于包装 *note create_subprocess_exec(): 3b4. and *note
     create_subprocess_shell(): 3b5. 函数创建的 OS 进程的对象。

     这个类被设计为具有与 *note subprocess.Popen: 3db. 类相似的 API，但
     两者有一些重要的差异:

        * 不同于 Popen，Process 实例没有与 *note poll(): 25d2. 方法等价
          的方法；

        * *note communicate(): 26b8. 和 *note wait(): 26b9. 方法没有
          `timeout' 形参；要使用 *note wait_for(): 191. 函数；

        * *note Process.wait(): 26b9. 方法是异步的，而 *note
          subprocess.Popen.wait(): 689. 方法则被实现为阻塞型忙循环；

        * `universal_newlines' 形参不被支持。

     这个类 *note 不是线程安全的: 2655.。

     请参阅 *note 子进程和线程: 26ba. 部分。

      -- 成員函式: coroutine wait ()

          等待子进程终结。

          设置并返回 *note returncode: 26bb. 属性。

               備註: 当使用 ‘stdout=PIPE’ 或 ‘stderr=PIPE’ 并且子进程产
               生了足以阻塞 OS 管道缓冲区等待接收更多的数据的输出时，此
               方法会发生死锁。 当使用管道时请使用 *note communicate():
               26b8. 方法来避免这种情况。

      -- 成員函式: coroutine communicate (input=None)

          与进程交互:

            1. 发送数据到 `stdin' (如果 `input' 不为 ‘None’)；

            2. 从 `stdout' 和 `stderr' 读取数据，直至到达 EOF；

            3. 等待进程终结。

          可选的 `input' 参数为将被发送到子进程的数据 (*note bytes: 172.
          对象)。

          返回一个元组 ‘(stdout_data, stderr_data)’。

          如果在将 `input' 写入到 `stdin' 时引发了 *note
          BrokenPipeError: a7e. 或 *note ConnectionResetError: a81. 异常
          ，异常会被忽略。 此条件会在进程先于所有数据被写入到 `stdin' 之
          前退出时发生。

          如果想要将数据发送到进程的 `stdin'，则创建进程时必须使用
          ‘stdin=PIPE’。 类似地，要在结果元组中获得任何不为 ‘None’ 的值
          ，则创建进程时必须使用 ‘stdout=PIPE’ 和/或 ‘stderr=PIPE’ 参数
          。

          注意，数据读取在内存中是带缓冲的，因此如果数据量过大或不受则不
          要使用此方法。

      -- 成員函式: send_signal (signal)

          将信号 `signal' 发送给子进程。

               備註: 在 Windows 上，‘SIGTERM’ 是 *note terminate():
               26bd. 的别名。 ‘CTRL_C_EVENT’ 和 ‘CTRL_BREAK_EVENT’ 可被
               发送给创建时设置了 `creationflags' 形参且其中包括
               ‘CREATE_NEW_PROCESS_GROUP’ 的进程。

      -- 成員函式: terminate ()

          停止子进程。

          在 POSIX 系统中此方法会发送 *note signal.SIGTERM: 26be. 给子进
          程。

          在 Windows 上会调用 Win32 API 函数 ‘TerminateProcess()’ 以停止
          子进程。

      -- 成員函式: kill ()

          杀掉子进程。

          在 POSIX 系统中此方法会发送 ‘SIGKILL’ 给子进程。

          在 Windows 上此方法是 *note terminate(): 26bd. 的别名。

      -- 屬性: stdin

          标准输入流 (*note StreamWriter: 1106.) 或者如果进程创建时设置
          了 ‘stdin=None’ 则为 ‘None’。

      -- 屬性: stdout

          标准输出流 (*note StreamReader: 1105.) 或者如果进程创建时设置
          了 ‘stdout=None’ 则为 ‘None’。

      -- 屬性: stderr

          标准错误流 (*note StreamReader: 1105.) 或者如果进程创建时设置
          了 ‘stderr=None’ 则为 ‘None’。

          警告: 使用 *note communicate(): 26b8. 方法而非 *note
          process.stdin.write(): 26b2, *note await
          process.stdout.read(): 26b3. 或 *note await
          process.stderr.read: 26b4.。 这可以避免由于流暂停读取或写入并
          阻塞子进程而导致的死锁。

      -- 屬性: pid

          进程标识号（PID）。

          注意对于由Note that for processes created by the *note
          create_subprocess_shell(): 3b5. 函数所创建的进程，这个属性将是
          所生成的 shell 的 PID。

      -- 屬性: returncode

          当进程退出时返回其代号。

          ‘None’ 值表示进程尚未终止。

          一个负值 ‘-N’ 表示子进程被信号 ‘N’ 中断 (仅 POSIX).

* Menu:

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


File: python.info,  Node: 子进程和线程,  Next: 示例<19>,  Up: 与子进程交互

5.18.1.34 子进程和线程
......................

标准 asyncio 事件循环默认支持从不同线程中运行子进程。

在 Windows 上子进程（默认）只由 *note ProactorEventLoop: 2de. 提供，
*note SelectorEventLoop: 26c2. 没有子进程支持。

在 UNIX 上会使用 `child watchers' 来让子进程结束等待，详情请参阅 *note
进程监视器: 26c3.。

3.8 版更變: UNIX 对于从不同线程中无限制地生成子进程会切换为使用 *note
ThreadedChildWatcher: 26c4.。

使用 `不活动的' 当前子监视器生成子进程将引发 *note RuntimeError: 3dc.。

请注意其他的事件循环实现可能有其本身的限制；请查看它们各自的文档。

也參考
......

*note asyncio 中的并发和多线程: 2655. 章节。


File: python.info,  Node: 示例<19>,  Prev: 子进程和线程,  Up: 与子进程交互

5.18.1.35 示例
..............

一个使用 *note Process: 26a9. 类来控制子进程并用 *note StreamReader:
1105. 类来从其标准输出读取信息的示例。 这个子进程是由 *note
create_subprocess_exec(): 3b4. 函数创建的:

     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}")

另请参阅使用低层级 API 编写的 *note 相同示例: 26c6.。


File: python.info,  Node: 队列集,  Next: 异常<9>,  Prev: 子进程,  Up: asyncio --- 异步 I/O

5.18.1.36 队列集
................

`源代码:' Lib/asyncio/queues.py(1)

__________________________________________________________________

asyncio 队列被设计成与 *note queue: da. 模块类似。尽管 asyncio队列不是线
程安全的，但是他们是被设计专用于 async/await 代码。

注意asyncio 的队列没有 `timeout' 形参；请使用 *note asyncio.wait_for():
191. 函数为队列添加超时操作。

参见下面的 *note Examples: 26c9. 部分

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/asyncio/queues.py


File: python.info,  Node: 队列,  Next: 优先级队列,  Up: 队列集

5.18.1.37 队列
..............

 -- 類別: asyncio.Queue (maxsize=0, *, loop=None)

     先进，先出（FIFO）队列

     如果 `maxsize' 小于等于零，则队列尺寸是无限的。如果是大于 ‘0’ 的整
     数，则当队列达到 `maxsize' 时， ‘await put()’ 将阻塞至某个元素被
     *note get(): 26cb. 取出。

     不像标准库中的并发型 *note queue: da. ，队列的尺寸一直是已知的，可
     以通过调用 *note qsize(): 26cc. 方法返回。

     Deprecated since version 3.8, will be removed in version 3.10:
     `loop' 形参。

     这个类 *note 不是线程安全的: 2655.。

      -- 屬性: maxsize

          队列中可存放的元素数量。

      -- 成員函式: empty ()

          如果队列为空返回 ‘True’ ，否则返回 ‘False’ 。

      -- 成員函式: full ()

          如果有 *note maxsize: 26cd. 个条目在队列中，则返回 ‘True’ 。

          如果队列用 ‘maxsize=0’ （默认）初始化，则 *note full(): 26cf.
          永远不会返回 ‘True’ 。

      -- 成員函式: coroutine get ()

          从队列中删除并返回一个元素。如果队列为空，则等待，直到队列中有
          元素。

      -- 成員函式: get_nowait ()

          立即返回一个队列中的元素，如果队列内有值，否则引发异常 *note
          QueueEmpty: 26d1. 。

      -- 成員函式: coroutine join ()

          阻塞至队列中所有的元素都被接收和处理完毕。

          当条目添加到队列的时候，未完成任务的计数就会增加。每当消费协程
          调用 *note task_done(): 793. 表示这个条目已经被回收，该条目所
          有工作已经完成，未完成计数就会减少。当未完成计数降到零的时候，
          *note join(): 792. 阻塞被解除。

      -- 成員函式: coroutine put (item)

          添加一个元素进队列。如果队列满了，在添加元素之前，会一直等待空
          闲插槽可用。

      -- 成員函式: put_nowait (item)

          不阻塞的放一个元素入队列。

          如果没有立即可用的空闲槽，引发 *note QueueFull: 26d4. 异常。

      -- 成員函式: qsize ()

          返回队列用的元素数量。

      -- 成員函式: task_done ()

          表明前面排队的任务已经完成，即get出来的元素相关操作已经完成。

          由队列使用者控制。每个 *note get(): 26cb. 用于获取一个任务，任
          务最后调用 *note task_done(): 793. 告诉队列，这个任务已经完成
          。

          如果 *note join(): 792. 当前正在阻塞，在所有条目都被处理后，将
          解除阻塞(意味着每个 *note put(): 26d2. 进队列的条目的 *note
          task_done(): 793. 都被收到)。

          如果被调用的次数多于放入队列中的项目数量，将引发 *note
          ValueError: 16d. 。


File: python.info,  Node: 优先级队列,  Next: 后进先出队列,  Prev: 队列,  Up: 队列集

5.18.1.38 优先级队列
....................

 -- 類別: asyncio.PriorityQueue

     *note Queue: 3b3. 的变体；按优先级顺序取出条目 (最小的先取出)。

     条目通常是 ‘(priority_number, data)’ 形式的元组。


File: python.info,  Node: 后进先出队列,  Next: 异常<8>,  Prev: 优先级队列,  Up: 队列集

5.18.1.39 后进先出队列
......................

 -- 類別: asyncio.LifoQueue

     *note Queue: 3b3. 的变体，先取出最近添加的条目（后进，先出）。


File: python.info,  Node: 异常<8>,  Next: 示例<20>,  Prev: 后进先出队列,  Up: 队列集

5.18.1.40 异常
..............

 -- 例外: asyncio.QueueEmpty

     当队列为空的时候，调用 *note get_nowait(): 26d0. 方法而引发这个异常
     。

 -- 例外: asyncio.QueueFull

     当队列中条目数量已经达到它的 `maxsize' 的时候，调用 *note
     put_nowait(): 26d3. 方法而引发的异常。


File: python.info,  Node: 示例<20>,  Prev: 异常<8>,  Up: 队列集

5.18.1.41 示例
..............

队列能被用于多个的并发任务的工作量分配：

     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())


File: python.info,  Node: 异常<9>,  Next: 事件循环,  Prev: 队列集,  Up: asyncio --- 异步 I/O

5.18.1.42 异常
..............

`源代码:' Lib/asyncio/exceptions.py(1)

__________________________________________________________________

 -- 例外: asyncio.TimeoutError

     该操作已超过规定的截止日期。

          重要: 这个异常与内置 *note TimeoutError: a7d. 异常不同。

 -- 例外: asyncio.CancelledError

     该操作已被取消。

     取消asyncio任务时，可以捕获此异常以执行自定义操作。在几乎所有情况下
     ，都必须重新引发异常。

     3.8 版更變: *note CancelledError: 2da. 现在是 *note BaseException:
     2db. 的子类。

 -- 例外: asyncio.InvalidStateError

     *note Task: 2e0. 或 *note Future: 545. 的内部状态无效。

     在为已设置结果值的未来对象设置结果值等情况下，可以引发此问题。

 -- 例外: asyncio.SendfileNotAvailableError

     "sendfile" 系统调用不适用于给定的套接字或文件类型。

     子类 *note RuntimeError: 3dc. 。

 -- 例外: asyncio.IncompleteReadError

     请求的读取操作未完全完成。

     由 *note asyncio stream APIs: 2638. 提出

     此异常是 *note EOFError: d34. 的子类。

      -- 屬性: expected

          预期字节的总数（ *note int: 204. ）。

      -- 屬性: partial

          到达流结束之前读取的 *note bytes: 172. 字符串。

 -- 例外: asyncio.LimitOverrunError

     在查找分隔符时达到缓冲区大小限制。

     由 *note asyncio stream APIs: 2638. 提出

      -- 屬性: consumed

          要消耗的字节总数。

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/Lib/asyncio/exceptions.py


File: python.info,  Node: 事件循环,  Next: Futures,  Prev: 异常<9>,  Up: asyncio --- 异步 I/O

5.18.1.43 事件循环
..................

`源代码:' Lib/asyncio/events.py(1), Lib/asyncio/base_events.py(2)

__________________________________________________________________

前言
....

事件循环是每个 asyncio 应用的核心。 事件循环会运行异步任务和回调，执行网
络 IO 操作，以及运行子进程。

应用开发者通常应当使用高层级的 asyncio 函数，例如 *note asyncio.run():
18d.，应当很少有必要引用循环对象或调用其方法。 本节所针对的主要是低层级
代码、库和框架的编写者，他们需要更细致地控制事件循环行为。

获取事件循环
............

以下低层级函数可被用于获取、设置或创建事件循环:

 -- 函式: asyncio.get_running_loop ()

     返回当前 OS 线程中正在运行的事件循环。

     如果没有正在运行的事件循环则会引发 *note RuntimeError: 3dc.。 此函
     数只能由协程或回调来调用。

     3.7 版新加入.

 -- 函式: asyncio.get_event_loop ()

     获取当前事件循环。

     如果当前 OS 线程没有设置当前事件循环，该 OS 线程为主线程，并且
     *note set_event_loop(): 26e3. 还没有被调用，则 asyncio 将创建一个新
     的事件循环并将其设为当前事件循环。

     由于此函数具有相当复杂的行为（特别是在使用了自定义事件循环策略的时
     候），更推荐在协程和回调中使用 *note get_running_loop(): 45c. 函数
     而非 *note get_event_loop(): 45d.。

     应该考虑使用 *note asyncio.run(): 18d. 函数而非使用低层级函数来手动
     创建和关闭事件循环。

 -- 函式: asyncio.set_event_loop (loop)

     将 `loop' 设置为当前 OS 线程的当前事件循环。

 -- 函式: asyncio.new_event_loop ()

     Create and return a new event loop object.

请注意 *note get_event_loop(): 45d, *note set_event_loop(): 26e3. 以及
*note new_event_loop(): 26e4. 函数的行为可以通过 *note
设置自定义事件循环策略: 26e5. 来改变。

内容
....

本文档包含下列小节:

   * *note 事件循环方法集: 26e6. 章节是事件循环APIs的参考文档；

   * *note 回调处理: 26e7. 章节是从调度方法 例如 *note loop.call_soon():
     455. 和 *note loop.call_later(): 457. 中返回 *note Handle: 11d7. 和
     *note TimerHandle: 26e8. 实例的文档。

   * *note Server Objects: 26e9. 章节记录了从事件循环方法返回的类型，比
     如 *note loop.create_server(): 465. ；

   * *note Event Loop Implementations: 26ea. 章节记录了 *note
     SelectorEventLoop: 26c2. 和 *note ProactorEventLoop: 2de. 类；

   * *note Examples: 26eb. 章节展示了如何使用某些事件循环API。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/asyncio/events.py

   (2) 
https://github.com/python/cpython/tree/3.9/Lib/asyncio/base_events.py


File: python.info,  Node: 事件循环方法集,  Next: 回调处理,  Up: 事件循环

5.18.1.44 事件循环方法集
........................

事件循环有下列 `低级' APIs：

* Menu:

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


File: python.info,  Node: 运行和停止循环,  Next: 安排回调,  Up: 事件循环方法集

5.18.1.45 运行和停止循环
........................

 -- 成員函式: loop.run_until_complete (future)

     运行直到 `future' ( *note Future: 545. 的实例 ) 被完成。

     如果参数是 *note coroutine object: 2637. ，将被隐式调度为 *note
     asyncio.Task: 2e0. 来运行。

     返回 Future 的结果 或者引发相关异常。

 -- 成員函式: loop.run_forever ()

     运行事件循环直到 *note stop(): 619. 被调用。

     如果 *note stop(): 619. 在调用 *note run_forever(): 26ed. 之前被调
     用，循环将轮询一次 I/O 选择器并设置超时为零，再运行所有已加入计划任
     务的回调来响应 I/O 事件（以及已加入计划任务的事件），然后退出。

     如果 *note stop(): 619. 在 *note run_forever(): 26ed. 运行期间被调
     用，循环将运行当前批次的回调然后退出。 请注意在此情况下由回调加入计
     划任务的新回调将不会运行；它们将会在下次 *note run_forever(): 26ed.
     或 *note run_until_complete(): 611. 被调用时运行。

 -- 成員函式: loop.stop ()

     停止事件循环。

 -- 成員函式: loop.is_running ()

     返回 ‘True’ 如果事件循环当前正在运行。

 -- 成員函式: loop.is_closed ()

     如果事件循环已经被关闭，返回 ‘True’ 。

 -- 成員函式: loop.close ()

     关闭事件循环。

     当这个函数被调用的时候，循环必须处于非运行状态。pending状态的回调将
     被丢弃。

     此方法清除所有的队列并立即关闭执行器，不会等待执行器完成。

     这个方法是幂等的和不可逆的。事件循环关闭后，不应调用其他方法。

 -- 成員函式: coroutine loop.shutdown_asyncgens ()

     安排所有当前打开的 *note asynchronous generator: 1640. 对象通过
     *note aclose(): 176. 调用来关闭。 在调用此方法后，如果有新的异步生
     成器被迭代事件循环将会发出警告。 这应当被用来可靠地完成所有已加入计
     划任务的异步生成器。

     请注意当使用 *note asyncio.run(): 18d. 时不必调用此函数。

     示例:

          try:
              loop.run_forever()
          finally:
              loop.run_until_complete(loop.shutdown_asyncgens())
              loop.close()

     3.6 版新加入.

 -- 成員函式: coroutine loop.shutdown_default_executor ()

     安排默认执行器的关闭并等待它合并 ‘ThreadPoolExecutor’ 中的所有线程
     。 在调用此方法后，如果在使用默认执行器期间调用了 *note
     loop.run_in_executor(): 190. 则将会引发 *note RuntimeError: 3dc.。

     请注意当使用 *note asyncio.run(): 18d. 时不必调用此函数。

     3.9 版新加入.


File: python.info,  Node: 安排回调,  Next: 调度延迟回调,  Prev: 运行和停止循环,  Up: 事件循环方法集

5.18.1.46 安排回调
..................

 -- 成員函式: loop.call_soon (callback, *args, context=None)

     安排 `callback' *note callback: 26f1. 在事件循环的下一次迭代时附带
     `args' 参数被调用。

     回调按其注册顺序被调用。每个回调仅被调用一次。

     可选的仅关键字型参数 `context' 允许为要运行的 `callback' 指定一个自
     定义 *note contextvars.Context: 260f. 。如果没有提供 `context' ，则
     使用当前上下文。

     返回一个能用来取消回调的 *note asyncio.Handle: 11d7. 实例。

     这个方法不是线程安全的。

 -- 成員函式: loop.call_soon_threadsafe (callback, *args, context=None)

     *note call_soon(): 455. 的线程安全变体。必须被用于安排 `来自其他线
     程' 的回调。

     如果在已被关闭的循环上调用则会引发 *note RuntimeError: 3dc.。 这可
     能会在主应用程序被关闭时在二级线程上发生。

     查看 *note 并发和多线程: 2655. 章节的文档。

3.7 版更變: 仅用于关键字形参的参数 `context' 已经被添加。请参阅： PEP
567(1) 查看更多细节。

     備註: 大多数 *note asyncio: 9. 的调度函数不让传递关键字参数。为此，
     请使用 *note functools.partial(): 8b5. ：

          # will schedule "print("Hello", flush=True)"
          loop.call_soon(
              functools.partial(print, "Hello", flush=True))

     使用 partial 对象通常比使用lambda更方便，asyncio 在调试和错误消息中
     能更好的呈现 partial 对象。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0567


File: python.info,  Node: 调度延迟回调,  Next: 创建 Future 和 Task,  Prev: 安排回调,  Up: 事件循环方法集

5.18.1.47 调度延迟回调
......................

事件循环提供安排调度函数在将来某个时刻调用的机制。事件循环使用单调时钟来
跟踪时间。

 -- 成員函式: loop.call_later (delay, callback, *args, context=None)

     安排 `callback' 在给定的 `delay' 秒（可以是 int 或者 float）后被调
     用。

     返回一个 *note asyncio.TimerHandle: 26e8. 实例，该实例能用于取消回
     调。

     `callback' 只被调用一次。如果两个回调被安排在同样的时间点，执行顺序
     未限定。

     可选的位置参数 `args' 在被调用的时候传递给 `callback'  。 如果你想
     把关键字参数传递给 `callback' ，请使用 *note functools.partial():
     8b5. 。

     可选的仅关键字型参数 `context' 允许为要运行的 `callback' 指定一个自
     定义 *note contextvars.Context: 260f. 。如果没有提供 `context' ，则
     使用当前上下文。

     3.7 版更變: 仅用于关键字形参的参数 `context' 已经被添加。请参阅：
     PEP 567(1) 查看更多细节。

     3.8 版更變: 在 Python 3.7 和更早版本的默认事件循环实现中， `delay'
     不能超过一天。 这在 Python 3.8 中已被修复。

 -- 成員函式: loop.call_at (when, callback, *args, context=None)

     安排 `callback' 在给定的绝对时间戳 `when' (int 或 float) 被调用，使
     用与 *note loop.time(): 26f5. 同样的时间参考。

     这个函数的行为与 *note call_later(): 457. 相同。

     返回一个 *note asyncio.TimerHandle: 26e8. 实例，该实例能用于取消回
     调。

     3.7 版更變: 仅用于关键字形参的参数 `context' 已经被添加。请参阅：
     PEP 567(2) 查看更多细节。

     3.8 版更變: 在 Python 3.7 和更早版本的默认事件循环实现中，`when' 和
     当前时间相差不能超过一天。 在这 Python 3.8 中已被修复。

 -- 成員函式: loop.time ()

     根据时间循环内部的单调时钟，返回当前时间为一个 *note float: 1fd. 值
     。

     備註: 
     3.8 版更變: 在 Python 3.7 和更早版本中超时 (相对的 `delay' 或绝对的
     `when') 不能超过一天。 这在 Python 3.8 中已被修复。

也參考
......

*note asyncio.sleep(): 3aa. 函数

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0567

   (2) https://www.python.org/dev/peps/pep-0567


File: python.info,  Node: 创建 Future 和 Task,  Next: 打开网络连接,  Prev: 调度延迟回调,  Up: 事件循环方法集

5.18.1.48 创建 Future 和 Task
.............................

 -- 成員函式: loop.create_future ()

     创建一个附加到事件循环中的 *note asyncio.Future: 545. 对象。

     这是在asyncio中创建Futures的首选方式。这让第三方事件循环可以提供
     Future 对象的替代实现(更好的性能或者功能)。

     3.5.2 版新加入.

 -- 成員函式: loop.create_task (coro, *, name=None)

     安排一个 *note 协程: 2637. 的执行。返回一个 *note Task: 2e0. 对象。

     三方的事件循环可以使用它们自己定义的 *note Task: 2e0. 类的子类来实
     现互操作性。这个例子里，返回值的类型是 *note Task: 2e0. 的子类。

     如果提供了 `name' 参数且不为 ‘None’，它会使用 *note
     Task.set_name(): 2e3. 来设为任务的名称。

     3.8 版更變: 添加了 ‘name’ 形参。

 -- 成員函式: loop.set_task_factory (factory)

     设置一个任务工厂，它将由 *note loop.create_task(): 2e2. 来使用。

     如果 `factory' 为 ‘None’ 则将设置默认的任务工厂。 在其他情况下，
     `factory' 必须为一个 `可调用对象' 且签名匹配 ‘(loop, coro)’，其中
     `loop' 是对活动事件循环的引用，而 `coro' 是一个协程对象。 该可调用
     对象必须返回一个兼容 *note asyncio.Future: 545. 的对象。

 -- 成員函式: loop.get_task_factory ()

     返回一个任务工厂，或者如果是使用默认值则返回 ‘None’。


File: python.info,  Node: 打开网络连接,  Next: 创建网络服务,  Prev: 创建 Future 和 Task,  Up: 事件循环方法集

5.18.1.49 打开网络连接
......................

 -- 成員函式: 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)

     打开一个流式传输连接，连接到由 `host' 和 `port' 指定的地址。

     套接字族可以是 *note AF_INET: 26f8. 或 *note AF_INET6: 26f9.，具体
     取决于 `host' (或 `family' 参数，如果有提供的话)。

     套接字类型将为 *note SOCK_STREAM: d52.。

     `protocol_factory' 必须为一个返回 *note asyncio 协议: 26fa. 实现的
     可调用对象。

     这个方法会尝试在后台创建连接。当创建成功，返回 ‘(transport,
     protocol)’ 组合。

     基本操作的时间顺序如下：

       1. 创建连接并为其创建一个 *note 传输: 26fb.。

       2. 不带参数地调用 `protocol_factory' 并预期返回一个 *note 协议:
          26fa. 实例。

       3. 协议实例通过调用其 *note connection_made(): 26fc. 方法与传输进
          行配对。

       4. 成功时返回一个 ‘(transport, protocol)’ 元组。

     创建的传输是一个具体实现相关的双向流。

     其他参数：

        * `ssl': 如果给定该参数且不为假值，则会创建一个 SSL/TLS 传输（默
          认创建一个纯 TCP 传输）。 如果 `ssl' 是一个 *note
          ssl.SSLContext: 4e9. 对象，则会使用此上下文来创建传输对象；如
          果 `ssl' 为 *note True: 593.，则会使用从 *note
          ssl.create_default_context(): 9a7. 返回的默认上下文。

          也參考
          ......

          *note SSL/TLS安全事项: 26fd.

        * `server_hostname' 设置或重载目标服务器的证书将要匹配的主机名。
          应当只在 `ssl' 不为 ‘None’ 时传入。 默认情况下会使用 `host' 参
          数的值。 如果 `host' 为空那就没有默认值，你必须为
          `server_hostname' 传入一个值。 如果 `server_hostname' 为空字符
          串，则主机名匹配会被禁用（这是一个严重的安全风险，使得潜在的中
          间人攻击成为可能）。

        * `family'，`proto'，`flags' 是可选的地址族，协议和标志，通过传
          递给 getaddrinfo() 来解析 `host'。如果给出，这些应该都是来自
          *note socket: ef. 模块相应的常量的整数。

        * 如果给出 `happy_eyeballs_delay'，它将为此链接启用 Happy
          Eyeballs。 该函数应当为一个表示在开始下一个并行尝试之前要等待
          连接尝试完成的秒数的浮点数。 这也就是在 RFC 8305(1) 中定义的
          "连接尝试延迟"。 该 RFC 所推荐的合理默认值为 ‘0.25’ (250 毫秒
          )。

        * `interleave' 控制当主机名解析为多个 IP 地址时的地址重排序。 如
          果该参数为 ‘0’ 或未指定，则不会进行重排序，这些地址会按 *note
          getaddrinfo(): 59b. 所返回的顺序进行尝试。 如果指定了一个正整
          数，这些地址会按地址族交错排列，而指定的整数会被解读为 RFC
          8305(2) 所定义的 "首个地址族计数"。 如果
          `happy_eyeballs_delay' 未指定则默认值为 ‘0’，否则为 ‘1’。

        * 如果给出 `sock'，它应当是一个已存在、已连接并将被传输所使用的
          *note socket.socket: 767. 对象。 如果给出了 `sock'，则 `host',
          `port', `family', `proto', `flags', `happy_eyeballs_delay',
          `interleave' 和 `local_addr' 都不应当被指定。

        * 如果给出 `local_addr'，它应当是一个用来在本地绑定套接字的
          ‘(local_host, local_port)’ 元组。 `local_host' 和 `local_port'
          会使用 ‘getaddrinfo()’ 来查找，这与 `host' 和 `port' 类似。

        * `ssl_handshake_timeout' 是（用于 TLS 连接的）在放弃连接之前要
          等待 TLS 握手完成的秒数。 如果参数为 ‘None’ 则使用 (默认的)
          ‘60.0’。

     3.8 版新加入: 增加了 `happy_eyeballs_delay' 和 `interleave' 形参。

     Happy Eyeballs 算法：成功使用双栈主机。 当服务器的 IPv4 路径和协议
     工作正常，但服务器的 IPv6 路径和协议工作不正常时，双栈客户端应用程
     序相比单独 IPv4 客户端会感受到明显的连接延迟。 这是不可接受的因为它
     会导致双栈客户端糟糕的用户体验。 此文档指明了减少这种用户可见延迟的
     算法要求并提供了具体的算法。

     详情参见: ‘https://tools.ietf.org/html/rfc6555’

     3.7 版新加入: `ssl_handshake_timeout' 形参。

     3.6 版更變: 套接字选项 ‘TCP_NODELAY’ 默认已为所有 TCP 连接进行了设
     置。

     3.5 版更變: *note ProactorEventLoop: 2de. 类中添加 SSL/TLS 支持。

     也參考
     ......

     *note open_connection(): 46b. 函数是一个高层级的替代 API。 它返回一
     对 (*note StreamReader: 1105, *note StreamWriter: 1106.)，可在
     async/await 代码中直接使用。

 -- 成員函式: 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)

          備註: 形参 `reuse_address' 已不再受支持，因为使用
          ‘SO_REUSEADDR’ 会对 UDP 造成显著的安全问题。 显式地传入
          ‘reuse_address=True’ 将会引发异常。

          当具有不同 UID 的多个进程将套接字赋给具有 ‘SO_REUSEADDR’ 的相
          同 UDP 套接字地址时，传入的数据包可能会在套接字间随机分配。

          对于受支持的平台，`reuse_port' 可以被用作类似功能的替代。 通过
          `reuse_port' 将改用 ‘SO_REUSEPORT’，它能够防止具有不同 UID 的
          进程将套接字赋给相同的套接字地址。

     创建一个数据报连接。

     套接字族可以是 *note AF_INET: 26f8, *note AF_INET6: 26f9. 或 *note
     AF_UNIX: 26fe.，具体取决于 `host' (或 `family' 参数，如果有提供的话
     )。

     socket类型将是 *note SOCK_DGRAM: d51. 。

     `protocol_factory' 必须为一个返回 *note 协议: 26fa. 实现的可调用对
     象。

     成功时返回一个 ‘(transport, protocol)’ 元组。

     其他参数：

        * 如果给出 `local_addr'，它应当是一个用来在本地绑定套接字的
          ‘(local_host, local_port)’ 元组。 `local_host' 和 `local_port'
          是使用 *note getaddrinfo(): 59b. 来查找的。

        * `remote_addr'，如果指定的话，就是一个 ‘(remote_host,
          remote_port)’ 元组，用于同一个远程地址连接。`remote_host' 和
          `remote_port' 是使用 *note getaddrinfo(): 59b. 来查找的。

        * `family', `proto', `flags' 是可选的地址族，协议和标志，其会被
          传递给 *note getaddrinfo(): 59b. 来完成 `host' 的解析。如果要
          指定的话，这些都应该是来自于 *note socket: ef. 模块的对应常量
          。

        * `reuse_port' 告知内核，只要在创建时都设置了这个旗标，就允许此
          端点绑定到其他现有端点所绑定的相同端口上。 这个选项在 Windows
          和某些 Unix 上不受支持。 如果 ‘SO_REUSEPORT’ 常量未定义则此功
          能就是不受支持的。

        * `allow_broadcast' 告知内核允许此端点向广播地址发送消息。

        * `sock' 可选择通过指定此值用于使用一个预先存在的，已经处于连接
          状态的 *note socket.socket: 767. 对象，并将其提供给此传输对象
          使用。如果指定了这个值， `local_addr' 和 `remote_addr' 就应该
          被忽略 (必须为 *note None: 203.)。

     参见 *note UDP echo 客户端协议: 26ff. 和 *note UDP echo 服务端协议:
     2700. 的例子。

     3.4.4 版更變: 添加了 `family', `proto', `flags', `reuse_address',
     `reuse_port', `allow_broadcast' 和 `sock' 等参数。

     3.8.1 版更變: 出于安全考虑，`reuse_address' 形参已不再受支持。

     3.8 版更變: 添加WIndows的支持。

 -- 成員函式: coroutine loop.create_unix_connection (protocol_factory,
          path=None, *, ssl=None, sock=None, server_hostname=None,
          ssl_handshake_timeout=None)

     创建Unix 连接

     套接字族将为 *note AF_UNIX: 26fe.；套接字类型将为 *note
     SOCK_STREAM: d52.。

     成功时返回一个 ‘(transport, protocol)’ 元组。

     `path' 是所要求的 Unix 域套接字的名字，除非指定了 `sock' 形参。 抽
     象的 Unix 套接字, *note str: 205, *note bytes: 172. 和 *note Path:
     32f. 路径都是受支持的。

     请查看 *note loop.create_connection(): 2e5. 方法的文档了解有关此方
     法的参数的信息。

     *note 可用性: 1491.: Unix。

     3.7 版新加入: `ssl_handshake_timeout' 形参。

     3.7 版更變: `path' 形参现在可以是 *note path-like object: 472. 对象
     。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc8305.html

   (2) https://tools.ietf.org/html/rfc8305.html


File: python.info,  Node: 创建网络服务,  Next: 传输文件,  Prev: 打开网络连接,  Up: 事件循环方法集

5.18.1.50 创建网络服务
......................

 -- 成員函式: 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 类型 *note SOCK_STREAM: d52. ) 监听 `host' 地址
     的 `port' 端口。

     返回一个 *note Server: 464. 对象。

     参数：

        * `protocol_factory' 必须为一个返回 *note 协议: 26fa. 实现的可调
          用对象。

        * `host' 形参可被设为几种类型，它确定了服务器所应监听的位置:

             - 如果 `host' 是一个字符串，则 TCP 服务器会被绑定到 `host'
               所指明的单一网络接口。

             - 如果 `host' 是一个字符串序列，则 TCP 服务器会被绑定到序列
               所指明的所有网络接口。

             - 如果 `host' 是一个空字符串或 ‘None’，则会应用所有接口并将
               返回包含多个套接字的列表（通常是一个 IPv4 的加一个 IPv6 的
               ）。

        * The `port' parameter can be set to specify which port the
          server should listen on.  If ‘0’ or ‘None’ (the default), a
          random unused port will be selected (note that if `host'
          resolves to multiple network interfaces, a different random
          port will be selected for each interface).

        * `family' 可被设为 *note socket.AF_INET: 26f8. 或 *note
          AF_INET6: 26f9. 以强制此套接字使用 IPv4 或 IPv6。 如果未设定，
          则 `family' 将通过主机名称来确定 (默认为 ‘AF_UNSPEC’)。

        * `flags' 是用于 *note getaddrinfo(): 59b. 的位掩码。

        * 可以选择指定 `sock' 以便使用预先存在的套接字对象。 如果指定了
          此参数，则不可再指定 `host' 和 `port'。

        * `backlog' 是传递给 *note listen(): 83a. 的最大排队连接的数量（
          默认为100）。

        * `ssl' 可被设置为一个 *note SSLContext: 4e9. 实例以在所接受的连
          接上启用 TLS。

        * `reuse_address' 告知内核要重用一个处于 ‘TIME_WAIT’ 状态的本地
          套接字，而不是等待其自然超时失效。 如果未指定此参数则在 Unix 上
          将自动设置为 ‘True’。

        * `reuse_port' 告知内核，只要在创建的时候都设置了这个标志，就允
          许此端点绑定到其它端点列表所绑定的同样的端口上。这个选项在
          Windows 上是不支持的。

        * `ssl_handshake_timeout' 是（用于 TLS 服务器的）在放弃连接之前
          要等待 TLS 握手完成的秒数。 如果参数为 (默认值) ‘None’ 则为
          ‘60.0’ 秒。

        * `start_serving' 设置成 ‘True’ (默认值) 会导致创建server并立即
          开始接受连接。设置成 ‘False’ ，用户需要等待 *note
          Server.start_serving(): 467. 或者 *note
          Server.serve_forever(): 468. 以使server开始接受连接。

     3.7 版新加入: 增加了 `ssl_handshake_timeout' 和 `start_serving' 形
     参。

     3.6 版更變: 套接字选项 ‘TCP_NODELAY’ 默认已为所有 TCP 连接进行了设
     置。

     3.5 版更變: *note ProactorEventLoop: 2de. 类中添加 SSL/TLS 支持。

     3.5.1 版更變: `host' 形参可以是一个字符串的序列。

     也參考
     ......

     *note start_server(): 46c. 函数是一个高层级的替代 API，它返回一对
     *note StreamReader: 1105. 和 *note StreamWriter: 1106.，可在
     async/await 代码中使用。

 -- 成員函式: coroutine loop.create_unix_server (protocol_factory,
          path=None, *, sock=None, backlog=100, ssl=None,
          ssl_handshake_timeout=None, start_serving=True)

     与 *note loop.create_server(): 465. 类似但是专用于 *note AF_UNIX:
     26fe. 套接字族。

     `path' 是必要的 Unix 域套接字名称，除非提供了 `sock' 参数。 抽象的
     Unix 套接字, *note str: 205, *note bytes: 172. 和 *note Path: 32f.
     路径都是受支持的。

     请查看 *note loop.create_server(): 465. 方法的文档了解有关此方法的
     参数的信息。

     *note 可用性: 1491.: Unix。

     3.7 版新加入: The `ssl_handshake_timeout' and `start_serving'
     parameters.

     3.7 版更變: `path' 形参现在可以是 *note Path: 32f. 对象。

 -- 成員函式: coroutine loop.connect_accepted_socket (protocol_factory,
          sock, *, ssl=None, ssl_handshake_timeout=None)

     将已被接受的连接包装成一个传输/协议对。

     此方法可被服务器用来接受 asyncio 以外的连接，但是使用 asyncio 来处
     理它们。

     参数：

        * `protocol_factory' 必须为一个返回 *note 协议: 26fa. 实现的可调
          用对象。

        * `sock' 是一个预先存在的套接字对象，它是由 *note socket.accept:
          768. 返回的。

        * `ssl' 可被设置为一个 *note SSLContext: 4e9. 以在接受的连接上启
          用 SSL。

        * `ssl_handshake_timeout' 是(为一个SSL连接)在中止连接前，等待
          SSL握手完成的时间【单位秒】。如果为 ‘None’ (缺省) 则是 ‘60.0’
          秒。

     返回一个 ‘(transport, protocol)’ 对。

     3.7 版新加入: `ssl_handshake_timeout' 形参。

     3.5.3 版新加入.


File: python.info,  Node: 传输文件,  Next: TLS 升级,  Prev: 创建网络服务,  Up: 事件循环方法集

5.18.1.51 传输文件
..................

 -- 成員函式: coroutine loop.sendfile (transport, file, offset=0,
          count=None, *, fallback=True)

     将 `file' 通过 `transport' 发送。 返回所发送的字节总数。

     如果可用的话，该方法将使用高性能的 *note os.sendfile(): 461.。

     `file' 必须是个二进制模式打开的常规文件对象。

     `offset' 指明从何处开始读取文件。 如果指定了 `count'，它是要传输的
     字节总数而不再一直发送文件直至抵达 EOF。 文件位置总是会被更新，即使
     此方法引发了错误，并可以使用 *note file.tell(): 1efc. 来获取实际发
     送的字节总数。

     `fallback' 设为 ‘True’ 会使得 asyncio 在平台不支持 sendfile 系统调
     用时手动读取并发送文件（例如 Windows 或 Unix 上的 SSL 套接字）。

     如果系统不支持 `sendfile' 系统调用且 `fallback' 为 ‘False’ 则会引发
     *note SendfileNotAvailableError: 26de.。

     3.7 版新加入.


File: python.info,  Node: TLS 升级,  Next: 监控文件描述符,  Prev: 传输文件,  Up: 事件循环方法集

5.18.1.52 TLS 升级
..................

 -- 成員函式: coroutine loop.start_tls (transport, protocol, sslcontext,
          *, server_side=False, server_hostname=None,
          ssl_handshake_timeout=None)

     将现有基于传输的连接升级到 TLS。

     返回一个新的传输实例，其中 `protocol' 必须在 `await' 之后立即开始使
     用。 传给 `start_tls' 方法的 `transport' 实例应永远不会被再次使用。

     参数：

        * `transport' 和 `protocol' 实例的方法与 *note create_server():
          465. 和 *note create_connection(): 2e5. 所返回的类似。

        * `sslcontext' ：一个已经配置好的 *note SSLContext: 4e9. 实例。

        * 当服务端连接已升级时 (如 *note create_server(): 465. 所创建的
          对象) `server_side' 会传入 ‘True’。

        * `server_hostname' ：设置或者覆盖目标服务器证书中相对应的主机名
          。

        * `ssl_handshake_timeout' 是（用于 TLS 连接的）在放弃连接之前要
          等待 TLS 握手完成的秒数。 如果参数为 ‘None’ 则使用 (默认的)
          ‘60.0’。

     3.7 版新加入.


File: python.info,  Node: 监控文件描述符,  Next: 直接使用 socket 对象,  Prev: TLS 升级,  Up: 事件循环方法集

5.18.1.53 监控文件描述符
........................

 -- 成員函式: loop.add_reader (fd, callback, *args)

     开始监视 `fd' 文件描述符以获取读取的可用性，一旦 `fd' 可用于读取，
     使用指定的参数调用 `callback' 。

 -- 成員函式: loop.remove_reader (fd)

     停止对文件描述符 `fd' 读取可用性的监视。

 -- 成員函式: loop.add_writer (fd, callback, *args)

     开始监视 `fd' 文件描述符的写入可用性，一旦 `fd' 可用于写入，使用指
     定的参数调用 `callback' 。

     使用 *note functools.partial(): 8b5. *note 传递关键字参数: 26f2. 给
     `callback'.

 -- 成員函式: loop.remove_writer (fd)

     停止对文件描述符 `fd' 的写入可用性监视。

另请查看 *note 平台支持: 2709. 一节了解以上方法的某些限制。


File: python.info,  Node: 直接使用 socket 对象,  Next: DNS,  Prev: 监控文件描述符,  Up: 事件循环方法集

5.18.1.54 直接使用 socket 对象
..............................

通常，使用基于传输的 API 的协议实现，例如 *note
loop.create_connection(): 2e5. 和 *note loop.create_server(): 465. 比直
接使用套接字的实现更快。 但是，在某些应用场景下性能并不非常重要，直接使
用 *note socket: 767. 对象会更方便。

 -- 成員函式: coroutine loop.sock_recv (sock, nbytes)

     从 `sock' 接收至多 `nbytes'。 *note socket.recv(): 76a. 的异步版本
     。

     返回接收到的数据【bytes对象类型】。

     `sock' 必须是个非阻塞socket。

     3.7 版更變: 虽然这个方法总是被记录为协程方法，但它在 Python 3.7 之
     前的发行版中会返回一个 *note Future: 545.。 从 Python 3.7 开始它则
     是一个 ‘async def’ 方法。

 -- 成員函式: coroutine loop.sock_recv_into (sock, buf)

     从 `sock' 接收数据放入 `buf' 缓冲区。 模仿了阻塞型的 *note
     socket.recv_into(): d7a. 方法。

     返回写入缓冲区的字节数。

     `sock' 必须是个非阻塞socket。

     3.7 版新加入.

 -- 成員函式: coroutine loop.sock_sendall (sock, data)

     将 `data' 发送到 `sock' 套接字。 *note socket.sendall(): 76e. 的异
     步版本。

     此方法会持续发送数据到套接字直至 `data' 中的所有数据发送完毕或是有
     错误发生。 当成功时会返回 ‘None’。 当发生错误时，会引发一个异常。 此
     外，没有办法能确定有多少数据或是否有数据被连接的接收方成功处理。

     `sock' 必须是个非阻塞socket。

     3.7 版更變: 虽然这个方法一直被标记为协程方法。但是，Python 3.7 之前
     ，该方法返回 *note Future: 545. ，从Python 3.7 开始，这个方法是
     ‘async def’ 方法。

 -- 成員函式: coroutine loop.sock_connect (sock, address)

     将 `sock' 连接到位于 `address' 的远程套接字。

     *note socket.connect(): 769. 的异步版本。

     `sock' 必须是个非阻塞socket。

     3.5.2 版更變: ‘address’ 不再需要被解析。 ‘sock_connect’ 将尝试检查
     `address' 是否已通过调用 *note socket.inet_pton(): 237. 被解析。 如
     果没有，则将使用 *note loop.getaddrinfo(): 59b. 来解析 `address'。

     也參考
     ......

     *note loop.create_connection(): 2e5. 和 *note
     asyncio.open_connection(): 46b. 。

 -- 成員函式: coroutine loop.sock_accept (sock)

     接受一个连接。 模仿了阻塞型的 *note socket.accept(): 768. 方法。

     此 `scoket' 必须绑定到一个地址上并且监听连接。返回值是一个 ‘(conn,
     address)’ 对，其中 `conn' 是一个 `新*的套接字对象，用于在此连接上收
     发数据，*address' 是连接的另一端的套接字所绑定的地址。

     `sock' 必须是个非阻塞socket。

     3.7 版更變: 虽然这个方法一直被标记为协程方法。但是，Python 3.7 之前
     ，该方法返回 *note Future: 545. ，从Python 3.7 开始，这个方法是
     ‘async def’ 方法。

     也參考
     ......

     *note loop.create_server(): 465. 和 *note start_server(): 46c.。

 -- 成員函式: coroutine loop.sock_sendfile (sock, file, offset=0,
          count=None, *, fallback=True)

     在可能的情况下使用高性能的 *note os.sendfile: 461. 发送文件。 返回
     所发送的字节总数。

     *note socket.sendfile(): 839. 的异步版本。

     `sock' 必须为非阻塞型的 *note socket.SOCK_STREAM: d52. *note
     socket: 767.。

     `file' 必须是个用二进制方式打开的常规文件对象。

     `offset' 指明从何处开始读取文件。 如果指定了 `count'，它是要传输的
     字节总数而不再一直发送文件直至抵达 EOF。 文件位置总是会被更新，即使
     此方法引发了错误，并可以使用 *note file.tell(): 1efc. 来获取实际发
     送的字节总数。

     当 `fallback' 被设为 ‘True’ 时，会使用 asyncio 在平台不支持
     sendfile 系统调用时手动读取并发送文件（例如 Windows 或 Unix 上的
     SSL 套接字）。

     如果系统不支持 `sendfile' 并且 `fallback' 为 ‘False’ ，引发 *note
     SendfileNotAvailableError: 26de. 异常。

     `sock' 必须是个非阻塞socket。

     3.7 版新加入.


File: python.info,  Node: DNS,  Next: 使用管道,  Prev: 直接使用 socket 对象,  Up: 事件循环方法集

5.18.1.55 DNS
.............

 -- 成員函式: coroutine loop.getaddrinfo (host, port, *, family=0,
          type=0, proto=0, flags=0)

     异步版的 *note socket.getaddrinfo(): 270c. 。

 -- 成員函式: coroutine loop.getnameinfo (sockaddr, flags=0)

     异步版的 *note socket.getnameinfo(): 270d. 。

3.7 版更變: `getaddrinfo' 和 `getnameinfo' 方法一直被标记返回一个协程，
但是Python 3.7之前，实际返回的是 *note asyncio.Future: 545. 对象。从
Python 3.7 开始，这两个方法是协程。


File: python.info,  Node: 使用管道,  Next: Unix 信号,  Prev: DNS,  Up: 事件循环方法集

5.18.1.56 使用管道
..................

 -- 成員函式: coroutine loop.connect_read_pipe (protocol_factory, pipe)

     在事件循环中注册 `pipe' 的读取端。

     `protocol_factory' 必须为一个返回 *note asyncio 协议: 26fa. 实现的
     可调用对象。

     `pipe' 是个 *note 类似文件型对象: c14.

     返回一对 ‘(transport, protocol)’，其中 `transport' 支持 *note
     ReadTransport: 270f. 接口而 `protocol' 是由 `protocol_factory' 所实
     例化的对象。

     使用 *note SelectorEventLoop: 26c2. 事件循环， `pipe' 被设置为非阻
     塞模式。

 -- 成員函式: coroutine loop.connect_write_pipe (protocol_factory, pipe)

     在事件循环中注册 `pipe' 的写入端。

     `protocol_factory' 必须为一个返回 *note asyncio 协议: 26fa. 实现的
     可调用对象。

     `pipe' 是个 *note 类似文件型对象: c14.

     返回一对 ‘(transport, protocol)’，其中 `transport' 支持 *note
     WriteTransport: 2710. 接口而 `protocol' 是由 `protocol_factory' 所
     实例化的对象。

     使用 *note SelectorEventLoop: 26c2. 事件循环， `pipe' 被设置为非阻
     塞模式。

     備註: 在 Windows 中 *note SelectorEventLoop: 26c2. 不支持上述方法。
     对于 Windows 请改用 *note ProactorEventLoop: 2de.。

也參考
......

*note loop.subprocess_exec(): 263c. 和 *note loop.subprocess_shell():
26aa. 方法。


File: python.info,  Node: Unix 信号,  Next: 在线程或者进程池中执行代码。,  Prev: 使用管道,  Up: 事件循环方法集

5.18.1.57 Unix 信号
...................

 -- 成員函式: loop.add_signal_handler (signum, callback, *args)

     设置 `callback' 作为 `signum' 信号的处理程序。

     此回调将与该事件循环中其他加入队列的回调和可运行协程一起由 `loop' 发
     起调用。 不同与使用 *note signal.signal(): b58. 注册的信号处理程序
     ，使用此函数注册的回调可以与事件循环进行交互。

     如果信号数字非法或者不可捕获，就抛出一个 *note ValueError: 16d. 。
     如果建立处理器的过程中出现问题，会抛出一个 *note RuntimeError: 3dc.
     。

     使用 *note functools.partial(): 8b5. *note 传递关键字参数: 26f2. 给
     `callback'.

     和 *note signal.signal(): b58. 一样，这个函数只能在主线程中调用。

 -- 成員函式: loop.remove_signal_handler (sig)

     移除 `sig' 信号的处理程序。

     如果信号处理程序被移除则返回 ‘True’，否则如果给定信号未设置处理程序
     则返回 ‘False’。

     *note 可用性: 1491.: Unix。

也參考
......

*note signal: ea. 模块。


File: python.info,  Node: 在线程或者进程池中执行代码。,  Next: 错误处理API,  Prev: Unix 信号,  Up: 事件循环方法集

5.18.1.58 在线程或者进程池中执行代码。
......................................

 -- 成員函式: awaitable loop.run_in_executor (executor, func, *args)

     安排在指定的执行器中调用 `func' 。

     The `executor' argument should be an *note
     concurrent.futures.Executor: 258a. instance.  The default executor
     is used if `executor' is ‘None’.

     示例:

          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())

     这个方法返回一个 *note asyncio.Future: 545. 对象。

     使用 *note functools.partial(): 8b5. *note 传递关键字参数: 26f2. 给
     `func' 。

     3.5.3 版更變: *note loop.run_in_executor(): 190. 不会再配置它所创建
     的线程池执行器的 ‘max_workers’，而是将其留给线程池执行器 (*note
     ThreadPoolExecutor: 18c.) 来设置默认值。

 -- 成員函式: loop.set_default_executor (executor)

     将 `executor' 设为 *note run_in_executor(): 190. 所使用的默认执行器
     。 `executor' 应当是 *note ThreadPoolExecutor: 18c. 的实例。

     3.8 版後已棄用: 使用不是Using an executor that is not an instance
     of *note ThreadPoolExecutor: 18c. 实例的执行器的做法已被弃用并将在
     Python 3.9 中引起错误。

     `executor' 必须是个 *note concurrent.futures.ThreadPoolExecutor:
     18c. 的实例。


File: python.info,  Node: 错误处理API,  Next: 开启调试模式,  Prev: 在线程或者进程池中执行代码。,  Up: 事件循环方法集

5.18.1.59 错误处理API
.....................

允许自定义事件循环中如何去处理异常。

 -- 成員函式: loop.set_exception_handler (handler)

     将 `handler' 设置为新的事件循环异常处理器。

     如果 `handler' 为 ‘None’，将设置默认的异常处理程序。 在其他情况下，
     `handler' 必须是一个可调用对象且签名匹配 ‘(loop, context)’，其中
     ‘loop’ 是对活动事件循环的引用，而 ‘context’ 是一个包含异常详情的
     ‘dict’ (请查看 *note call_exception_handler(): 2716. 文档来获取关于
     上下文的更多信息)。

 -- 成員函式: loop.get_exception_handler ()

     返回当前的异常处理器，如果没有设置异常处理器，则返回 ‘None’ 。

     3.5.2 版新加入.

 -- 成員函式: loop.default_exception_handler (context)

     默认的异常处理器。

     此方法会在发生异常且未设置异常处理程序时被调用。 此方法也可以由想要
     具有不同于默认处理程序的行为的自定义异常处理程序来调用。

     `context' 参数和 *note call_exception_handler(): 2716. 中的同名参数
     完全相同。

 -- 成員函式: loop.call_exception_handler (context)

     调用当前事件循环异常处理器。

     `context' 是个包含下列键的 ‘dict’ 对象(未来版本的Python可能会引入新
     键)：

        * ’message’: 错误消息；

        * ’exception’ （可选）: 异常对象；

        * ’future’ （可选）: *note asyncio.Future: 545. 实例。

        * ’handle’ （可选）: *note asyncio.Handle: 11d7. 实例；

        * ’protocol’ （可选）: *note Protocol: 26fa. 实例；

        * ’transport’ （可选）: *note Transport: 26fb. 实例；

        * ’socket’ （可选）： *note socket.socket: 767. 实例。

          備註: 此方法不应在子类化的事件循环中被重载。 对于自定义的异常
          处理，请使用 *note set_exception_handler(): 2715. 方法。


File: python.info,  Node: 开启调试模式,  Next: 运行子进程,  Prev: 错误处理API,  Up: 事件循环方法集

5.18.1.60 开启调试模式
......................

 -- 成員函式: loop.get_debug ()

     获取事件循环调试模式状态（*note bool: 2bd.）。

     如果环境变量 *note PYTHONASYNCIODEBUG: 148d. 是一个非空字符串，就返
     回 ‘True’ ，否则就返回 ‘False’ 。

 -- 成員函式: loop.set_debug (enabled: bool)

     设置事件循环的调试模式。

     3.7 版更變: 现在也可以通过新的 *note Python 开发模式: 160. 来启用调
     试模式。

也參考
......

*note debug mode of asyncio: 148e.


File: python.info,  Node: 运行子进程,  Prev: 开启调试模式,  Up: 事件循环方法集

5.18.1.61 运行子进程
....................

本小节所描述的方法都是低层级的。 在常规 async/await 代码中请考虑改用高层
级的 *note asyncio.create_subprocess_shell(): 3b5. 和 *note
asyncio.create_subprocess_exec(): 3b4. 便捷函数。

     備註: On Windows, the default event loop *note ProactorEventLoop:
     2de. supports subprocesses, whereas *note SelectorEventLoop: 26c2.
     does not.  See *note Subprocess Support on Windows: 26ab. for
     details.

 -- 成員函式: coroutine loop.subprocess_exec (protocol_factory, *args,
          stdin=subprocess.PIPE, stdout=subprocess.PIPE,
          stderr=subprocess.PIPE, **kwargs)

     用 `args' 指定的一个或者多个字符串型参数创建一个子进程。

     `args' 必须是个由下列形式的字符串组成的列表：

        * *note str: 205.;

        * 或者由 *note 文件系统编码格式: 2042. 编码的 *note bytes: 172.。

     第一个字符串指定可执行程序，其余的字符串指定其参数。 所有字符串参数
     共同组成了程序的 ‘argv’。

     此方法类似于调用标准库 *note subprocess.Popen: 3db. 类，设置
     ‘shell=False’ 并将字符串列表作为第一个参数传入；但是，*note Popen:
     3db. 只接受一个单独的字符串列表参数，而 `subprocess_exec' 接受多个
     字符串参数。

     `protocol_factory' 必须为一个返回 *note asyncio.SubprocessProtocol:
     271a. 类的子类的可调用对象。

     其他参数：

        * `stdin' 可以是以下对象之一:

             * 一个文件类对象，表示要使用 *note connect_write_pipe():
               26ad. 连接到子进程的标准输入流的管道

             * *note subprocess.PIPE: 4f3. 常量（默认），将创建并连接一
               个新的管道。

             * ‘None’ 值，这将使得子进程继承来自此进程的文件描述符

             * *note subprocess.DEVNULL: b78. 常量，这表示将使用特殊的
               *note os.devnull: 1152. 文件

        * `stdout' 可以是以下对象之一:

             * 一个文件类对象，表示要使用 *note connect_write_pipe():
               26ad. 连接到子进程的标准输出流的管道

             * *note subprocess.PIPE: 4f3. 常量（默认），将创建并连接一
               个新的管道。

             * ‘None’ 值，这将使得子进程继承来自此进程的文件描述符

             * *note subprocess.DEVNULL: b78. 常量，这表示将使用特殊的
               *note os.devnull: 1152. 文件

        * `stderr' 可以是以下对象之一:

             * 一个文件类对象，表示要使用 *note connect_write_pipe():
               26ad. 连接到子进程的标准错误流的管道

             * *note subprocess.PIPE: 4f3. 常量（默认），将创建并连接一
               个新的管道。

             * ‘None’ 值，这将使得子进程继承来自此进程的文件描述符

             * *note subprocess.DEVNULL: b78. 常量，这表示将使用特殊的
               *note os.devnull: 1152. 文件

             * *note subprocess.STDOUT: 25ae. 常量，将把标准错误流连接到
               进程的标准输出流

        * 所有其他关键字参数会被不加解释地传给 *note subprocess.Popen:
          3db.，除了 `bufsize', `universal_newlines', `shell', `text',
          `encoding' 和 `errors'，它们都不应当被指定。

          ‘asyncio’ 子进程 API 不支持将流解码为文本。 可以使用 *note
          bytes.decode(): 171. 来将从流返回的字节串转换为文本。

     其他参数的文档，请参阅 *note subprocess.Popen: 3db. 类的构造函数。

     返回一对 ‘(transport, protocol)’，其中 `transport' 来自 *note
     asyncio.SubprocessTransport: 271b. 基类而 `protocol' 是由
     `protocol_factory' 所实例化的对象。

 -- 成員函式: coroutine loop.subprocess_shell (protocol_factory, cmd, *,
          stdin=subprocess.PIPE, stdout=subprocess.PIPE,
          stderr=subprocess.PIPE, **kwargs)

     基于 `cmd' 创建一个子进程，该参数可以是一个 *note str: 205. 或者按
     *note 文件系统编码格式: 2042. 编码得到的 *note bytes: 172. ，使用平
     台的 "shell" 语法。

     这类似与用 ‘shell=True’ 调用标准库的 *note subprocess.Popen: 3db. 类
     。

     `protocol_factory' 必须为一个返回 *note SubprocessProtocol: 271a. 类
     的子类的可调用对象。

     请参阅 *note subprocess_exec(): 263c. 了解有关其余参数的详情。

     返回一对 ‘(transport, protocol)’，其中 `transport' 来自 *note
     SubprocessTransport: 271b. 基类而 `protocol' 是由
     `protocol_factory' 所实例化的对象。

     備註: 应用程序要负责确保正确地转义所有空白字符和特殊字符以防止
     shell 注入(1) 漏洞。 *note shlex.quote(): b4e. 函数可以被用来正确地
     转义字符串中可能被用来构造 shell 命令的空白字符和特殊字符。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Shell_injection#Shell_injection


File: python.info,  Node: 回调处理,  Next: Server 对象,  Prev: 事件循环方法集,  Up: 事件循环

5.18.1.62 回调处理
..................

 -- 類別: asyncio.Handle

     由 *note loop.call_soon(): 455, *note loop.call_soon_threadsafe():
     456. 所返回的回调包装器对象。

      -- 成員函式: cancel ()

          取消回调。 如果此回调已被取消或已被执行，此方法将没有任何效果
          。

      -- 成員函式: cancelled ()

          如果此回调已被取消则返回 ‘True’。

          3.7 版新加入.

 -- 類別: asyncio.TimerHandle

     由 *note loop.call_later(): 457. 和 *note loop.call_at(): 458. 所返
     回的回调包装器对象。

     这个类是 *note Handle: 11d7. 的子类。

      -- 成員函式: when ()

          返回加入计划任务的回调时间，以 *note float: 1fd. 值表示的秒数
          。

          时间值是一个绝对时间戳，使用与 *note loop.time(): 26f5. 相同的
          时间引用。

          3.7 版新加入.


File: python.info,  Node: Server 对象,  Next: 事件循环实现,  Prev: 回调处理,  Up: 事件循环

5.18.1.63 Server 对象
.....................

Server 对象可使用 *note loop.create_server(): 465, *note
loop.create_unix_server(): 466, *note start_server(): 46c. 和 *note
start_unix_server(): 266f. 等函数来创建。

请不要直接实例化该类。

 -- 類別: asyncio.Server

     `Server' 对象是异步上下文管理器。当用于 ‘async with’ 语句时，异步上
     下文管理器可以确保 Server 对象被关闭，并且在 ‘async with’ 语句完成
     后，不接受新的连接。

          srv = await loop.create_server(...)

          async with srv:
              # some code

          # At this point, srv is closed and no longer accepts new connections.

     3.7 版更變: Python3.7 开始，Server 对象是一个异步上下文管理器。

      -- 成員函式: close ()

          停止服务：关闭监听的套接字并且设置 *note sockets: 59d. 属性为
          ‘None’ 。

          用于表示已经连进来的客户端连接会保持打开的状态。

          服务器是被异步关闭的，使用 *note wait_closed(): 271e. 协程来等
          待服务器关闭。

      -- 成員函式: get_loop ()

          返回与服务器对象相关联的事件循环。

          3.7 版新加入.

      -- 成員函式: coroutine start_serving ()

          开始接受连接。

          这个方法是幂等的【相同参数重复执行，能获得相同的结果】，所以此
          方法能在服务已经运行的时候调用。

          传给 *note loop.create_server(): 465. 和 *note
          asyncio.start_server(): 46c. 的 `start_serving' 仅限关键字形参
          允许创建不接受初始连接的 Server 对象。 在此情况下可以使用
          ‘Server.start_serving()’ 或 *note Server.serve_forever(): 468.
          让 Server 对象开始接受连接。

          3.7 版新加入.

      -- 成員函式: coroutine serve_forever ()

          开始接受连接，直到协程被取消。 ‘serve_forever’ 任务的取消将导
          致服务器被关闭。

          如果服务器已经在接受连接了，这个方法可以被调用。每个 `Server'
          对象，仅能有一个 ‘serve_forever’ 任务。

          示例:

               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))

          3.7 版新加入.

      -- 成員函式: is_serving ()

          如果服务器正在接受新连接的状态，返回 ‘True’ 。

          3.7 版新加入.

      -- 成員函式: coroutine wait_closed ()

          等待 *note close(): 271d. 方法执行完毕。

      -- 屬性: sockets

          服务器监听的 *note socket.socket: 767. 对象列表。

          3.7 版更變: 在 Python 3.7 之前 ‘Server.sockets’ 会直接返回内部
          的服务器套接字列表。 在 3.7 版则会返回该列表的副本。


File: python.info,  Node: 事件循环实现,  Next: 示例<21>,  Prev: Server 对象,  Up: 事件循环

5.18.1.64 事件循环实现
......................

asyncio 带有两种不同的事件循环实现: *note SelectorEventLoop: 26c2. 和
*note ProactorEventLoop: 2de.。

默认情况下 asyncio 被配置为在 Unix 上使用 *note SelectorEventLoop: 26c2.
而在 Windows 上使用 *note ProactorEventLoop: 2de.。

 -- 類別: asyncio.SelectorEventLoop

     基于 *note selectors: e6. 模块的事件循环。

     使用给定平台中最高效的可用 `selector'。 也可以手动配置要使用的特定
     selector:

          import asyncio
          import selectors

          selector = selectors.SelectSelector()
          loop = asyncio.SelectorEventLoop(selector)
          asyncio.set_event_loop(loop)

     *note 可用性: 1491.: Unix, Windows。

 -- 類別: asyncio.ProactorEventLoop

     用 "I/O Completion Ports" (IOCP) 构建的专为Windows 的事件循环。

     *note 可用性: 1491.: Windows。

     也參考
     ......

     有关 I/O 完成端口的 MSDN 文档(1)。

 -- 類別: asyncio.AbstractEventLoop

     asyncio 兼容事件循环的抽象基类。

     *note 事件循环方法: 737. 一节列出了 ‘AbstractEventLoop’ 的替代实现
     应当定义的所有方法。

   ---------- Footnotes ----------

   (1) 
https://docs.microsoft.com/en-ca/windows/desktop/FileIO/i-o-completion-ports


File: python.info,  Node: 示例<21>,  Prev: 事件循环实现,  Up: 事件循环

5.18.1.65 示例
..............

请注意本节中的所有示例都 `有意地' 演示了如何使用低层级的事件循环 API，例
如 *note loop.run_forever(): 26ed. 和 *note loop.call_soon(): 455.。 现
代的 asyncio 应用很少需要以这样的方式编写；请考虑使用高层级的函数例如
*note asyncio.run(): 18d.。

* Menu:

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


File: python.info,  Node: call_soon 的 Hello World 示例。,  Next: 使用 call_later 来展示当前的日期,  Up: 示例<21>

5.18.1.66 call_soon() 的 Hello World 示例。
...........................................

一个使用 *note loop.call_soon(): 455. 方法来安排回调的示例。 回调会显示
‘"Hello World"’ 然后停止事件循环:

     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()

也參考
......

一个类似的 *note Hello World: 2637. 示例，使用协程和 *note run(): 18d. 函
数创建。


File: python.info,  Node: 使用 call_later 来展示当前的日期,  Next: 监控一个文件描述符的读事件,  Prev: call_soon 的 Hello World 示例。,  Up: 示例<21>

5.18.1.67 使用 call_later() 来展示当前的日期
............................................

一个每秒刷新显示当前日期的示例。 回调使用 *note loop.call_later(): 457.
方法在 5 秒后将自身重新加入计划日程，然后停止事件循环:

     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()

也參考
......

一个类似的 *note current date: 2649. 示例，使用协程和 *note run(): 18d.
函数创建。


File: python.info,  Node: 监控一个文件描述符的读事件,  Next: 为SIGINT和SIGTERM设置信号处理器,  Prev: 使用 call_later 来展示当前的日期,  Up: 示例<21>

5.18.1.68 监控一个文件描述符的读事件
....................................

使用 *note loop.add_reader(): 2689. 方法，等到文件描述符收到一些数据，然
后关闭事件循环：

     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()

也參考
......

   * 一个类似的 *note 示例: 2688.，使用传输、协议和 *note
     loop.create_connection(): 2e5. 方法创建。

   * 另一个类似的 *note 示例: 2686.，使用了高层级的 *note
     asyncio.open_connection(): 46b. 函数和流。


File: python.info,  Node: 为SIGINT和SIGTERM设置信号处理器,  Prev: 监控一个文件描述符的读事件,  Up: 示例<21>

5.18.1.69 为SIGINT和SIGTERM设置信号处理器
.........................................

（这个 ‘signals’ 示例只适用于 Unix。）

使用 *note loop.add_signal_handler(): 263d. 方法为信号 ‘SIGINT’ 和
‘SIGTERM’ 注册处理程序:

     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())


File: python.info,  Node: Futures,  Next: 传输和协议,  Prev: 事件循环,  Up: asyncio --- 异步 I/O

5.18.1.70 Futures
.................

`源代码:' Lib/asyncio/futures.py(1), Lib/asyncio/base_futures.py(2)

__________________________________________________________________

`Future' 对象用来链接 `底层回调式代码' 和高层异步/等待式代码。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/asyncio/futures.py

   (2) 
https://github.com/python/cpython/tree/3.9/Lib/asyncio/base_futures.py


File: python.info,  Node: Future 函数,  Next: Future 对象<2>,  Up: Futures

5.18.1.71 Future 函数
.....................

 -- 函式: asyncio.isfuture (obj)

     如果 `obj' 为下面任意对象，返回 ‘True’：

        * 一个 *note asyncio.Future: 545. 类的实例，

        * 一个 *note asyncio.Task: 2e0. 类的实例，

        * 带有 ‘_asyncio_future_blocking’ 属性的类似 Future 的对象。

     3.5 版新加入.

 -- 函式: asyncio.ensure_future (obj, *, loop=None)

     返回：

        * `obj' 参数会是保持原样，如果 `obj' 是 *note Future: 545.、
          *note Task: 2e0. 或 类似 Future 的对象( *note isfuture():
          272a. 用于测试。)

        * 封装了 `obj' 的 *note Task: 2e0. 对象，如果 `obj' 是一个协程
          (使用 *note iscoroutine(): 2667. 进行检测)；在此情况下该协程将
          通过 ‘ensure_future()’ 加入执行计划。

        * 等待 `obj' 的 *note Task: 2e0. 对象，如果 `obj' 是一个可等待对
          象( *note inspect.isawaitable(): 7ea. 用于测试)

     如果 `obj' 不是上述对象会引发一个 *note TypeError: 1fe. 异常。

          重要: 查看 *note create_task(): 2e1. 函数，它是创建新任务的首
          选途径。

          Save a reference to the result of this function, to avoid a
          task disappearing mid execution.

     3.5.1 版更變: 这个函数接受任意 *note awaitable: 612. 对象。

 -- 函式: asyncio.wrap_future (future, *, loop=None)

     将一个 *note concurrent.futures.Future: c00. 对象封装到 *note
     asyncio.Future: 545. 对象中。


File: python.info,  Node: Future 对象<2>,  Prev: Future 函数,  Up: Futures

5.18.1.72 Future 对象
.....................

 -- 類別: asyncio.Future (*, loop=None)

     一个 Future 代表一个异步运算的最终结果。线程不安全。

     Future 是一个 *note awaitable: 612. 对象。协程可以等待 Future 对象
     直到它们有结果或异常集合或被取消。

     通常 Future 用于支持底层回调式代码(例如在协议实现中使用asyncio
     *note transports: 263e.) 与高层异步/等待式代码交互。

     经验告诉我们永远不要面向用户的接口暴露 Future 对象，同时建议使用
     *note loop.create_future(): 615. 来创建 Future 对象。这种方法可以让
     Future 对象使用其它的事件循环实现，它可以注入自己的优化实现。

     3.7 版更變: 加入对 *note contextvars: 24. 模块的支持。

      -- 成員函式: result ()

          返回 Future 的结果。

          如果 Future 状态为 `完成' ，并由 *note set_result(): 2659. 方
          法设置一个结果，则返回这个结果。

          如果 Future 状态为 `完成' ，并由 *note set_exception(): 265a.
          方法设置一个异常，那么这个方法会引发异常。

          如果 Future 已 `取消'，方法会引发一个 *note CancelledError:
          2da. 异常。

          如果 Future 的结果还不可用，此方法会引发一个 *note
          InvalidStateError: 265f. 异常。

      -- 成員函式: set_result (result)

          将 Future 标记为 `完成' 并设置结果。

          如果 Future 已经 `完成' 则抛出一个 *note InvalidStateError:
          265f. 错误。

      -- 成員函式: set_exception (exception)

          将 Future 标记为 `完成' 并设置一个异常。

          如果 Future 已经 `完成' 则抛出一个 *note InvalidStateError:
          265f. 错误。

      -- 成員函式: done ()

          如果 Future 为已 `完成' 则返回 ‘True’ 。

          如果 Future 为 `取消' 或调用 *note set_result(): 2659. 设置了
          结果或调用 *note set_exception(): 265a. 设置了异常，那么它就是
          `完成' 。

      -- 成員函式: cancelled ()

          如果 Future 已 `取消' 则返回 ‘True’

          这个方法通常在设置结果或异常前用来检查 Future 是否已 `取消' 。

               if not fut.cancelled():
                   fut.set_result(42)

      -- 成員函式: add_done_callback (callback, *, context=None)

          添加一个在 Future `完成' 时运行的回调函数。

          调用 `callback' 时，Future 对象是它的唯一参数。

          如果调用这个方法时 Future 已经 `完成'，回调函数会被 *note
          loop.call_soon(): 455. 调度。

          可选键值类的参数 `context' 允许 `callback' 运行在一个指定的自
          定义 *note contextvars.Context: 260f. 对象中。如果没有提供
          `context' ，则使用当前上下文。

          可以用 *note functools.partial(): 8b5. 给回调函数传递参数，例
          如:

               # Call 'print("Future:", fut)' when "fut" is done.
               fut.add_done_callback(
                   functools.partial(print, "Future:"))

          3.7 版更變: 加入键值类形参 `context'。请参阅 PEP 567(1) 查看更
          多细节。

      -- 成員函式: remove_done_callback (callback)

          从回调列表中移除 `callback' 。

          返回被移除的回调函数的数量，通常为1，除非一个回调函数被添加多
          次。

      -- 成員函式: cancel (msg=None)

          取消 Future 并调度回调函数。

          如果 Future 已经 `完成' 或 `取消' ，返回 ‘False’ 。否则将
          Future 状态改为 `取消' 并在调度回调函数后返回 ‘True’ 。

          3.9 版更變: 增加了 ‘msg’ 形参。

      -- 成員函式: exception ()

          返回 Future 已设置的异常。

          只有 Future 在 `完成' 时才返回异常（或者 ‘None’ ，如果没有设置
          异常）。

          如果 Future 已 `取消'，方法会引发一个 *note CancelledError:
          2da. 异常。

          如果 Future 还没 `完成' ，这个方法会引发一个 *note
          InvalidStateError: 265f. 异常。

      -- 成員函式: get_loop ()

          返回 Future 对象已绑定的事件循环。

          3.7 版新加入.

这个例子创建一个 Future 对象，创建和调度一个异步任务去设置 Future 结果，
然后等待其结果:

     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())

     重要: 该 Future 对象是为了模仿 *note concurrent.futures.Future:
     c00. 类。主要差异包含：

        - 与 asyncio 的 Future 不同，*note concurrent.futures.Future:
          c00. 实例不是可等待对象。

        - *note asyncio.Future.result(): 272d. 和 *note
          asyncio.Future.exception(): 2730. 不接受 `timeout' 参数。

        - Future 没有 `完成' 时 *note asyncio.Future.result(): 272d. 和
          *note asyncio.Future.exception(): 2730. 抛出一个 *note
          InvalidStateError: 265f. 异常。

        - 使用 *note asyncio.Future.add_done_callback(): 459. 注册的回调
          函数不会立即调用，而是被 *note loop.call_soon(): 455. 调度。

        - asyncio Future 不能兼容 *note concurrent.futures.wait(): f50.
          和 *note concurrent.futures.as_completed(): 1223. 函数。

        - *note asyncio.Future.cancel(): 265b. 接受一个可选的 ‘msg’ 参数
          ，但 ‘concurrent.futures.cancel()’ 无此参数。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0567


File: python.info,  Node: 传输和协议,  Next: 策略,  Prev: Futures,  Up: asyncio --- 异步 I/O

5.18.1.73 传输和协议
....................

前言
....

传输和协议会被像 *note loop.create_connection(): 2e5. 这类 `底层' 事件循
环接口使用。它们使用基于回调的编程风格支持网络或IPC协议（如HTTP）的高性
能实现。

基本上，传输和协议应只在库和框架上使用，而不应该在高层的异步应用中使用它
们。

本文档包含 *note Transports: 2734. 和 *note Protocols: 2735. 。

概述
....

在最顶层，传输只关心 `怎样' 传送字节内容，而协议决定传送 `哪些' 字节内容
(还要在一定程度上考虑何时)。

也可以这样说：从传输的角度来看，传输是套接字(或类似的I/O终端)的抽象，而
协议是应用程序的抽象。

换另一种说法，传输和协议一起定义网络I/0和进程间I/O的抽象接口。

传输对象和协议对象总是一对一关系：协议调用传输方法来发送数据，而传输在接
收到数据时调用协议方法传递数据。

大部分面向连接的事件循环方法(如 *note loop.create_connection(): 2e5. ) 通
常接受 `protocol_factory' 参数为接收到的链接创建 `协议' 对象，并用 `传输
' 对象来表示。这些方法一般会返回 ‘(transport, protocol)’ 元组。

内容
....

本文档包含下列小节:

   * *note 传输: 2734. 部分记载异步IO *note BaseTransport: 2736. 、
     *note ReadTransport: 270f. 、 *note WriteTransport: 2710. 、 *note
     Transport: 2737. 、 *note DatagramTransport: 2738. 和 *note
     SubprocessTransport: 271b. 等类。

   * The *note Protocols: 2735. section documents asyncio *note
     BaseProtocol: 2739, *note Protocol: 273a, *note BufferedProtocol:
     3eb, *note DatagramProtocol: 273b, and *note SubprocessProtocol:
     271a. classes.

   * *note 例子: 273c. 部分展示怎样使用传输、协议和底层事件循环接口。

* Menu:

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


File: python.info,  Node: 传输,  Next: 协议,  Up: 传输和协议

5.18.1.74 传输
..............

`源码:' Lib/asyncio/transports.py(1)

__________________________________________________________________

传输属于 *note asyncio: 9. 模块中的类，用来抽象各种通信通道。

传输对象总是由 *note 异步IO事件循环: 737. 实例化。

异步IO实现TCP、UDP、SSL和子进程管道的传输。传输上可用的方法由传输的类型
决定。

传输类属于 *note 线程不安全: 2655. 。

* Menu:

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

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/Lib/asyncio/transports.py


File: python.info,  Node: 传输层级,  Next: 基础传输,  Up: 传输

5.18.1.75 传输层级
..................

 -- 類別: asyncio.BaseTransport

     所有传输的基类。包含所有异步IO传输共用的方法。

 -- 類別: asyncio.WriteTransport (BaseTransport)

     只写链接的基础传输。

     `WriteTransport' 类的实例由 *note loop.connect_write_pipe(): 26ad.
     事件循环方法返回，也被子进程相关的方法如 *note
     loop.subprocess_exec(): 263c. 使用。

 -- 類別: asyncio.ReadTransport (BaseTransport)

     只读链接的基础传输。

     `ReadTransport' 类的实例由 *note loop.connect_read_pipe(): 26ac. 事
     件循环方法返回，也被子进程相关的方法如 *note
     loop.subprocess_exec(): 263c. 使用。

 -- 類別: asyncio.Transport (WriteTransport, ReadTransport)

     接口代表一个双向传输，如TCP链接。

     用户不用直接实例化传输；调用一个功能函数，给它传递协议工厂和其它需
     要的信息就可以创建传输和协议。

     `传输' 类实例由如 *note loop.create_connection(): 2e5. 、 *note
     loop.create_unix_connection(): 266e. 、 *note loop.create_server():
     465. 、 *note loop.sendfile(): 2703. 等这类事件循环方法使用或返回。

 -- 類別: asyncio.DatagramTransport (BaseTransport)

     数据报(UDP)传输链接。

     `DatagramTransport' 类实例由事件循环方法 *note
     loop.create_datagram_endpoint(): 189. 返回。

 -- 類別: asyncio.SubprocessTransport (BaseTransport)

     表示父进程和子进程之间连接的抽象。

     `SubprocessTransport' 类的实例由事件循环方法 *note
     loop.subprocess_shell(): 26aa. 和 *note loop.subprocess_exec():
     263c. 返回。


File: python.info,  Node: 基础传输,  Next: 只读传输,  Prev: 传输层级,  Up: 传输

5.18.1.76 基础传输
..................

 -- 成員函式: BaseTransport.close ()

     关闭传输。

     如果传输具有发送数据缓冲区，将会异步发送已缓存的数据。在所有已缓存
     的数据都已处理后，就会将 *note None: 203. 作为协议 *note
     protocol.connection_lost(): 2740. 方法的参数并进行调用。在这之后，
     传输不再接收任何数据。

 -- 成員函式: BaseTransport.is_closing ()

     返回 ‘True’ ，如果传输正在关闭或已经关闭。。

 -- 成員函式: BaseTransport.get_extra_info (name, default=None)

     返回 传输或它使用的相关资源信息。

     `name' 是表示要获取传输特定信息的字符串。

     `default' 是在信息不可用或传输不支持第三方事件循环实现或当前平台查
     询时返回的值。

     例如下面代码尝试获取传输相关套接字对象:

          sock = transport.get_extra_info('socket')
          if sock is not None:
              print(sock.getsockopt(...))

     传输可查询信息类别:

        * 套接字:

             - ‘'peername'’: 套接字链接时的远端地址，*note
               socket.socket.getpeername(): 2741. 方法的结果 (出错时为
               ‘None’ )

             - ‘'socket'’: *note socket.socket: 767. 实例

             - ‘'sockname'’: 套接字本地地址， *note
               socket.socket.getsockname(): 2742. 方法的结果

        * SSL套接字

             - ‘'compression'’: 用字符串指定压缩算法，或者链接没有压缩时
               为 ‘None’ ；*note ssl.SSLSocket.compression(): b6d. 的结
               果。

             - ‘'cipher'’: 一个三值的元组，包含使用密码的名称，定义使用
               的SSL协议的版本，使用的加密位数。 *note
               ssl.SSLSocket.cipher(): 2743. 的结果。

             - ‘'peercert'’: 远端凭证； *note
               ssl.SSLSocket.getpeercert(): 9b7. 结果。

             - ‘'sslcontext'’: *note ssl.SSLContext: 4e9. 实例

             - ‘'ssl_object'’: *note ssl.SSLObject: 4e8. 或 *note
               ssl.SSLSocket: 192. 实例

        * 管道：

             - ‘'pipe'’: 管道对象

        * 子进程：

             - ‘'subprocess'’: *note subprocess.Popen: 3db. 实例

 -- 成員函式: BaseTransport.set_protocol (protocol)

     设置一个新协议。

     只有两种协议都写明支持切换才能完成切换协议。

 -- 成員函式: BaseTransport.get_protocol ()

     返回当前协议。


File: python.info,  Node: 只读传输,  Next: 只写传输,  Prev: 基础传输,  Up: 传输

5.18.1.77 只读传输
..................

 -- 成員函式: ReadTransport.is_reading ()

     如果传输接收到新数据时返回 ‘True’ 。

     3.7 版新加入.

 -- 成員函式: ReadTransport.pause_reading ()

     暂停传输的接收端。*note protocol.data_received(): 2747. 方法将不会
     收到数据，除非 *note resume_reading(): 470.  被调用。

     3.7 版更變: 这个方法幂等的， 它可以在传输已经暂停或关闭时调用。

 -- 成員函式: ReadTransport.resume_reading ()

     恢复接收端。如果有数据可读取时，协议方法 *note
     protocol.data_received(): 2747. 将再次被调用。

     3.7 版更變: 这个方法幂等的， 它可以在传输已经准备好读取数据时调用。


File: python.info,  Node: 只写传输,  Next: 数据报传输,  Prev: 只读传输,  Up: 传输

5.18.1.78 只写传输
..................

 -- 成員函式: WriteTransport.abort ()

     立即关闭传输，不会等待已提交的操作处理完毕。已缓存的数据将会丢失。
     不会接收更多数据。 最终 *note None: 203. 将作为协议的 *note
     protocol.connection_lost(): 2740. 方法的参数被调用。

 -- 成員函式: WriteTransport.can_write_eof ()

     如果传输支持 *note write_eof(): 274b. 返回 *note True: 593. 否则返
     回 *note False: 48e. 。

 -- 成員函式: WriteTransport.get_write_buffer_size ()

     返回传输使用输出缓冲区的当前大小。

 -- 成員函式: WriteTransport.get_write_buffer_limits ()

     获取写入流控制 `high' 和 `low' 高低标记位。返回元组 ‘(low, high)’ ，
     `low' 和 `high' 为正字节数。

     使用 *note set_write_buffer_limits(): 274d. 设置限制。

     3.4.2 版新加入.

 -- 成員函式: WriteTransport.set_write_buffer_limits (high=None,
          low=None)

     设置写入流控制 `high' 和 `low' 高低标记位。

     这两个值（以字节数表示）控制何时调用协议的 *note
     protocol.pause_writing(): 274e. 和 *note protocol.resume_writing():
     274f. 方法。 如果指明，则低水位必须小于或等于高水位。 `high' 和
     `low' 都不能为负值。

     *note pause_writing(): 274e. 会在缓冲区尺寸大于或等于 `high' 值时被
     调用。 如果写入已经被暂停，*note resume_writing(): 274f. 会在缓冲区
     尺寸小于或等于 `low' 值时被调用。

     默认值是实现专属的。 如果只给出了高水位值，则低水位值默认为一个小于
     或等于高水位值的实现传属值。 将 `high' 设为零会强制将 `low' 也设为
     零，并使得 *note pause_writing(): 274e. 在缓冲区变为非空的任何时刻
     被调用。 将 `low' 设为零会使得 *note resume_writing(): 274f. 在缓冲
     区为空时只被调用一次。 对于上下限都使用零值通常是不够优化的，因为它
     减少了并发执行 I/O 和计算的机会。

     可使用 *note get_write_buffer_limits(): 78f. 来获取上下限值。

 -- 成員函式: WriteTransport.write (data)

     将一些 `data' 字节串写入传输。

     此方法不会阻塞；它会缓冲数据并安排其被异步地发出。

 -- 成員函式: WriteTransport.writelines (list_of_data)

     将数据字节串的列表（或任意可迭代对象）写入传输。 这在功能上等价于在
     可迭代对象产生的每个元素上调用 *note write(): 2750.，但其实现可能更
     为高效。

 -- 成員函式: WriteTransport.write_eof ()

     在刷新所有已缓冲数据之后关闭传输的写入端。 数据仍可以被接收。

     如果传输（例如 SSL）不支持半关闭的连接，此方法会引发 *note
     NotImplementedError: 704.。


File: python.info,  Node: 数据报传输,  Next: 子进程传输,  Prev: 只写传输,  Up: 传输

5.18.1.79 数据报传输
....................

 -- 成員函式: DatagramTransport.sendto (data, addr=None)

     将 `data' 字节串发送到 `addr' (基于传输的目标地址) 所给定的远端对等
     方。 如果 `addr' 为 *note None: 203.，则将数据发送到传输创建时给定
     的目标地址。

     此方法不会阻塞；它会缓冲数据并安排其被异步地发出。

 -- 成員函式: DatagramTransport.abort ()

     立即关闭传输，不会等待已提交的操作执行完毕。 已缓存的数据将会丢失。
     不会接收更多的数据。 协议的 *note protocol.connection_lost(): 2740.
     方法最终将附带 *note None: 203. 作为参数被调用。


File: python.info,  Node: 子进程传输,  Prev: 数据报传输,  Up: 传输

5.18.1.80 子进程传输
....................

 -- 成員函式: SubprocessTransport.get_pid ()

     将子进程的进程 ID 以整数形式返回。

 -- 成員函式: SubprocessTransport.get_pipe_transport (fd)

     返回对应于整数文件描述符 `fd' 的通信管道的传输:

        * ‘0’: 标准输入 (`stdin') 的可读流式传输，如果子进程创建时未设置
          ‘stdin=PIPE’ 则为 *note None: 203.

        * ‘1’: 标准输出 (`stdout') 的可写流式传输，如果子进程创建时未设
          置 ‘stdout=PIPE’ 则为 *note None: 203.

        * ‘2’: 标准错误 (`stderr') 的可写流式传输，如果子进程创建时未设
          置 ‘stderr=PIPE’ 则为 *note None: 203.

        * 其他 `fd': *note None: 203.

 -- 成員函式: SubprocessTransport.get_returncode ()

     返回整数形式的进程返回码，或者如果还未返回则为 *note None: 203.，这
     类似于 *note subprocess.Popen.returncode: 10a5. 属性。

 -- 成員函式: SubprocessTransport.kill ()

     杀死子进程。

     在 POSIX 系统中，函数会发送 SIGKILL 到子进程。 在 Windows 中，此方
     法是 *note terminate(): 275a. 的别名。

     另请参见 *note subprocess.Popen.kill(): 25d4.。

 -- 成員函式: SubprocessTransport.send_signal (signal)

     发送 `signal' 编号到子进程，与 *note
     subprocess.Popen.send_signal(): 10a4. 一样。

 -- 成員函式: SubprocessTransport.terminate ()

     停止子进程。

     在 POSIX 系统中，此方法会发送 SIGTERM 到子进程。 在 Windows 中，则
     会调用 Windows API 函数 TerminateProcess() 来停止子进程。

     另请参见 *note subprocess.Popen.terminate(): 25d3.。

 -- 成員函式: SubprocessTransport.close ()

     通过调用 *note kill(): 2759. 方法来杀死子进程。

     如果子进程尚未返回，并关闭 `stdin', `stdout' 和 `stderr' 管道的传输
     。


File: python.info,  Node: 协议,  Next: 示例<22>,  Prev: 传输,  Up: 传输和协议

5.18.1.81 协议
..............

`源码:' Lib/asyncio/protocols.py(1)

__________________________________________________________________

asyncio 提供了一组抽象基类，它们应当被用于实现网络协议。 这些类被设计为
与 *note 传输: 26fb. 配合使用。

抽象基础协议类的子类可以实现其中的部分或全部方法。 所有这些方法都是回调
：它们由传输或特定事件调用，例如当数据被接收的时候。 基础协议方法应当由
相应的传输来调用。

* Menu:

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

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/Lib/asyncio/protocols.py


File: python.info,  Node: 基础协议,  Next: 基础协议<2>,  Up: 协议

5.18.1.82 基础协议
..................

 -- 類別: asyncio.BaseProtocol

     带有所有协议的共享方法的基础协议。

 -- 類別: asyncio.Protocol (BaseProtocol)

     用于实现流式协议（TCP, Unix 套接字等等）的基类。

 -- 類別: asyncio.BufferedProtocol (BaseProtocol)

     用于实现可对接收缓冲区进行手动控制的流式协议的基类。

 -- 類別: asyncio.DatagramProtocol (BaseProtocol)

     用于实现数据报（UDP）协议的基类。

 -- 類別: asyncio.SubprocessProtocol (BaseProtocol)

     用于实现与子进程通信（单向管道）的协议的基类。


File: python.info,  Node: 基础协议<2>,  Next: 流式协议,  Prev: 基础协议,  Up: 协议

5.18.1.83 基础协议
..................

所有 asyncio 协议均可实现基础协议回调。

连接回调
........

连接回调会在所有协议上被调用，每个成功的连接将恰好调用一次。 所有其他协
议回调只能在以下两个方法之间被调用。

 -- 成員函式: BaseProtocol.connection_made (transport)

     连接建立时被调用。

     `transport' 参数是代表连接的传输。 此协议负责将引用保存至对应的传输
     。

 -- 成員函式: BaseProtocol.connection_lost (exc)

     连接丢失或关闭时将被调用。

     方法的参数是一个异常对象或为 *note None: 203.。 后者意味着收到了常
     规的 EOF，或者连接被连接的一端取消或关闭。

流程控制回调
............

流程控制回调可由传输来调用以暂停或恢复协议所执行的写入操作。

请查看 *note set_write_buffer_limits(): 274d. 方法的文档了解详情。

 -- 成員函式: BaseProtocol.pause_writing ()

     当传输的缓冲区升至高水位以上时将被调用。

 -- 成員函式: BaseProtocol.resume_writing ()

     当传输的缓冲区降到低水位以下时将被调用。

如果缓冲区大小等于高水位值，则 *note pause_writing(): 274e. 不会被调用：
缓冲区大小必须要高于该值。

相反地，*note resume_writing(): 274f. 会在缓冲区大小等于或小于低水位值时
被调用。 这些结束条件对于当两个水位取零值时也能确保符合预期的行为是很重
要的。


File: python.info,  Node: 流式协议,  Next: 缓冲流协议,  Prev: 基础协议<2>,  Up: 协议

5.18.1.84 流式协议
..................

事件方法，例如 *note loop.create_server(): 465, *note
loop.create_unix_server(): 466, *note loop.create_connection(): 2e5,
*note loop.create_unix_connection(): 266e, *note
loop.connect_accepted_socket(): 46d, *note loop.connect_read_pipe():
26ac. 和 *note loop.connect_write_pipe(): 26ad. 都接受返回流式协议的工厂
。

 -- 成員函式: Protocol.data_received (data)

     当收到数据时被调用。 `data' 为包含入站数据的非空字节串对象。

     数据是否会被缓冲、分块或重组取决于具体传输。 通常，你不应依赖于特定
     的语义而应使你的解析具有通用性和灵活性。 但是，数据总是要以正确的顺
     序被接收。

     此方法在连接打开期间可以被调用任意次数。

     但是，*note protocol.eof_received(): 2760. 最多只会被调用一次。 一
     旦 ‘eof_received()’ 被调用，‘data_received()’ 就不会再被调用。

 -- 成員函式: Protocol.eof_received ()

     当发出信号的另一端不再继续发送数据时（例如通过调用 *note
     transport.write_eof(): 274b.，如果另一端也使用 asyncio 的话）被调用
     。

     此方法可能返回假值 (包括 ‘None’)，在此情况下传输将会自行关闭。 相反
     地，如果此方法返回真值，将以所用的协议来确定是否要关闭传输。 由于默
     认实现是返回 ‘None’，因此它会隐式地关闭连接。

     某些传输，包括 SSL 在内，并不支持半关闭的连接，在此情况下从该方法返
     回真值将导致连接被关闭。

状态机：

     start -> connection_made
         [-> data_received]*
         [-> eof_received]?
     -> connection_lost -> end


File: python.info,  Node: 缓冲流协议,  Next: 数据报协议,  Prev: 流式协议,  Up: 协议

5.18.1.85 缓冲流协议
....................

3.7 版新加入.

带缓冲的协议可与任何支持 *note 流式协议: 275f. 的事件循环方法配合使用。

‘BufferedProtocol’ 实现允许显式手动分配和控制接收缓冲区。 随后事件循环可
以使用协议提供的缓冲区来避免不必要的数据复制。 这对于接收大量数据的协议
来说会有明显的性能提升。 复杂的协议实现能显著地减少缓冲区分配的数量。

以下回调是在 *note BufferedProtocol: 3eb. 实例上被调用的:

 -- 成員函式: BufferedProtocol.get_buffer (sizehint)

     调用后会分配新的接收缓冲区。

     `sizehint' 是推荐的返回缓冲区最小尺寸。 返回小于或大于 `sizehint' 推
     荐尺寸的缓冲区也是可接受的。 当设为 -1 时，缓冲区尺寸可以是任意的。
     返回尺寸为零的缓冲区则是错误的。

     ‘get_buffer()’ 必须返回一个实现了 *note 缓冲区协议: 171c. 的对象。

 -- 成員函式: BufferedProtocol.buffer_updated (nbytes)

     用接收的数据更新缓冲区时被调用。

     `nbytes' 是被写入到缓冲区的字节总数。

 -- 成員函式: BufferedProtocol.eof_received ()

     请查看 *note protocol.eof_received(): 2760. 方法的文档。

在连接期间 *note get_buffer(): 2762. 可以被调用任意次数。 但是，*note
protocol.eof_received(): 2760. 最多只能被调用一次，如果被调用，则在此之
后 *note get_buffer(): 2762. 和 *note buffer_updated(): 2763. 不能再被调
用。

状态机：

     start -> connection_made
         [-> get_buffer
             [-> buffer_updated]?
         ]*
         [-> eof_received]?
     -> connection_lost -> end


File: python.info,  Node: 数据报协议,  Next: 子进程协议,  Prev: 缓冲流协议,  Up: 协议

5.18.1.86 数据报协议
....................

数据报协议实例应当由传递给 *note loop.create_datagram_endpoint(): 189. 方
法的协议工厂来构造。

 -- 成員函式: DatagramProtocol.datagram_received (data, addr)

     当接收到数据报时被调用。 `data' 是包含传入数据的字节串对象。 `addr'
     是发送数据的对等端地址；实际的格式取决于具体传输。

 -- 成員函式: DatagramProtocol.error_received (exc)

     当前一个发送或接收操作引发 *note OSError: 304. 时被调用。 `exc' 是
     *note OSError: 304. 的实例。

     此方法会在当传输（例如UDP）检测到无法将数据报传给接收方等极少数情况
     下被调用。 而在大多数情况下，无法送达的数据报将被静默地丢弃。

     備註: 在 BSD 系统（macOS, FreeBSD 等等）上，数据报协议不支持流控制
     ，因为没有可靠的方式来检测因写入多过包所导致的发送失败。

     套接字总是显示为 ’ready’ 且多余的包会被丢弃。 有一定的可能性会引发
     *note OSError: 304. 并设置 ‘errno’ 为 *note errno.ENOBUFS: 23f9.；
     如果此异常被引发，它将被报告给 *note
     DatagramProtocol.error_received(): 2767.，在其他情况下则会被忽略。


File: python.info,  Node: 子进程协议,  Prev: 数据报协议,  Up: 协议

5.18.1.87 子进程协议
....................

子进程协议实例应当由传递给 *note loop.subprocess_exec(): 263c. 和 *note
loop.subprocess_shell(): 26aa. 方法的协议工厂函数来构造。

 -- 成員函式: SubprocessProtocol.pipe_data_received (fd, data)

     当子进程向其 stdout 或 stderr 管道写入数据时被调用。

     `fd' 是以整数表示的管道文件描述符。

     `data' 是包含已接收数据的非空字节串对象。

 -- 成員函式: SubprocessProtocol.pipe_connection_lost (fd, exc)

     与子进程通信的其中一个管道关闭时被调用。

     `fd' 以整数表示的已关闭文件描述符。

 -- 成員函式: SubprocessProtocol.process_exited ()

     子进程退出时被调用。


File: python.info,  Node: 示例<22>,  Prev: 协议,  Up: 传输和协议

5.18.1.88 示例
..............

* Menu:

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


File: python.info,  Node: TCP 回显服务器,  Next: TCP 回显客户端,  Up: 示例<22>

5.18.1.89 TCP 回显服务器
........................

使用 *note loop.create_server(): 465. 方法创建 TCP 回显服务器，发回已接
收的数据，并关闭连接:

     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())

也參考
......

*note 使用流的 TCP 回显服务器: 2682. 示例，使用了高层级的 *note
asyncio.start_server(): 46c. 函数。


File: python.info,  Node: TCP 回显客户端,  Next: UDP 回显服务器,  Prev: TCP 回显服务器,  Up: 示例<22>

5.18.1.90 TCP 回显客户端
........................

使用 *note loop.create_connection(): 2e5. 方法的 TCP 回显客户端，发送数
据并等待，直到连接被关闭:

     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())

也參考
......

*note 使用流的 TCP 回显客户端: 267f. 示例，使用了高层级的 *note
asyncio.open_connection(): 46b. 函数。


File: python.info,  Node: UDP 回显服务器,  Next: UDP 回显客户端,  Prev: TCP 回显客户端,  Up: 示例<22>

5.18.1.91 UDP 回显服务器
........................

使用 *note loop.create_datagram_endpoint(): 189. 方法的 UDB 回显服务器，
发回已接收的数据:

     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())


File: python.info,  Node: UDP 回显客户端,  Next: 链接已存在的套接字,  Prev: UDP 回显服务器,  Up: 示例<22>

5.18.1.92 UDP 回显客户端
........................

使用 *note loop.create_datagram_endpoint(): 189. 方法的 UDP 回显客户端，
发送数据并在收到回应时关闭传输:

     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())


File: python.info,  Node: 链接已存在的套接字,  Next: loop subprocess_exec 与 SubprocessProtocol,  Prev: UDP 回显客户端,  Up: 示例<22>

5.18.1.93 链接已存在的套接字
............................

附带一个协议使用 *note loop.create_connection(): 2e5. 方法，等待直到套接
字接收数据:

     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())

也參考
......

使用低层级的 *note loop.add_reader(): 2689. 方法来注册一个 FD 的 *note
监视文件描述符以读取事件: 268a. 示例。

使用在协程中通过 *note open_connection(): 46b. 函数创建的高层级流的
*note 注册一个打开的套接字以等待使用流的数据: 2686. 示例。


File: python.info,  Node: loop subprocess_exec 与 SubprocessProtocol,  Prev: 链接已存在的套接字,  Up: 示例<22>

5.18.1.94 loop.subprocess_exec() 与 SubprocessProtocol
......................................................

一个使用子进程协议来获取子进程的输出并等待子进程退出的示例。

这个子进程是由 *note loop.subprocess_exec(): 263c. 方法创建的:

     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}")

另请参阅使用高层级 API 编写的 *note 相同示例: 26c5.。


File: python.info,  Node: 策略,  Next: 平台支持,  Prev: 传输和协议,  Up: asyncio --- 异步 I/O

5.18.1.95 策略
..............

事件循环策略是各个进程的全局对象 ，它控制事件循环的管理。每个事件循环都
有一个默认策略，可以使用策略API更改和定制该策略。

策略定义了“上下文”的概念，每个上下文管理一个单独的事件循环。默认策略将
*context*定义为当前线程。

通过使用自定义事件循环策略，可以自定义 *note get_event_loop(): 45d. 、
*note set_event_loop(): 26e3. 和 *note new_event_loop(): 26e4. 函数的行
为。

策略对象应该实现 *note AbstractEventLoopPolicy: 2774. 抽象基类中定义的
API。

* Menu:

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


File: python.info,  Node: 获取和设置策略,  Next: 策略对象,  Up: 策略

5.18.1.96 获取和设置策略
........................

可以使用下面函数获取和设置当前进程的策略:

 -- 函式: asyncio.get_event_loop_policy ()

     返回当前进程域的策略。

 -- 函式: asyncio.set_event_loop_policy (policy)

     将 `policy' 设置为当前进程域策略。

     如果 `policy' 设为 ‘None’ 将恢复默认策略。


File: python.info,  Node: 策略对象,  Next: 进程监视器,  Prev: 获取和设置策略,  Up: 策略

5.18.1.97 策略对象
..................

抽象事件循环策略基类定义如下:

 -- 類別: asyncio.AbstractEventLoopPolicy

     异步策略的抽象基类。

      -- 成員函式: get_event_loop ()

          为当前上下文获取事件循环。

          返回一个实现 *note AbstractEventLoop: 233. 接口的事件循环对象
          。

          该方法永远不应返回 ‘None’。

          3.6 版更變.

      -- 成員函式: set_event_loop (loop)

          将当前上下文的事件循环设置为 `loop' 。

      -- 成員函式: new_event_loop ()

          创建并返回一个新的事件循环对象。

          该方法永远不应返回 ‘None’。

      -- 成員函式: get_child_watcher ()

          获取子进程监视器对象。

          返回一个实现 *note AbstractChildWatcher: 277d. 接口的监视器对
          象。

          该函数仅支持Unix。

      -- 成員函式: set_child_watcher (watcher)

          将当前子进程监视器设置为 `watcher' 。

          该函数仅支持Unix。

asyncio附带下列内置策略:

 -- 類別: asyncio.DefaultEventLoopPolicy

     默认的 asyncio 策略。 在 Unix 上使用 *note SelectorEventLoop: 26c2.
     而在 Windows 上使用 *note ProactorEventLoop: 2de.。

     不需要手动安装默认策略。asyncio已配置成自动使用默认策略。

     3.8 版更變: 在 Windows 上，现在默认会使用 *note ProactorEventLoop:
     2de.。

 -- 類別: asyncio.WindowsSelectorEventLoopPolicy

     一个使用 *note SelectorEventLoop: 26c2. 事件循环实现的替代事件循环
     策略。

     *note 可用性: 1491.: Windows。

 -- 類別: asyncio.WindowsProactorEventLoopPolicy

     使用 *note ProactorEventLoop: 2de. 事件循环实现的另一种事件循环策略
     。

     *note 可用性: 1491.: Windows。


File: python.info,  Node: 进程监视器,  Next: 自定义策略,  Prev: 策略对象,  Up: 策略

5.18.1.98 进程监视器
....................

进程监视器允许定制事件循环如何监视Unix子进程。具体来说，事件循环需要知道
子进程何时退出。

在asyncio中子进程由 *note create_subprocess_exec(): 3b4. 和 *note
loop.subprocess_exec(): 263c. 函数创建。

asyncio 定义了 *note AbstractChildWatcher: 277d. 抽象基类，子监视器必须
要实现它，并具有四种不同实现: *note ThreadedChildWatcher: 26c4. (已配置
为默认使用), *note MultiLoopChildWatcher: 2783, *note SafeChildWatcher:
2784. 和 *note FastChildWatcher: 2785.。

请参阅 *note 子进程和线程: 26ba. 部分。

以下两个函数可用于自定义子进程监视器实现，它将被asyncio事件循环使用:

 -- 函式: asyncio.get_child_watcher ()

     返回当前策略的当前子监视器。

 -- 函式: asyncio.set_child_watcher (watcher)

     将当前策略的子监视器设置为 `watcher' 。`watcher' 必须实现 *note
     AbstractChildWatcher: 277d. 基类定义的方法。

     備註: 第三方事件循环实现可能不支持自定义子监视器。对于这样的事件循
     环，禁止使用 *note set_child_watcher(): 2787. 或不起作用。

 -- 類別: asyncio.AbstractChildWatcher

      -- 成員函式: add_child_handler (pid, callback, *args)

          注册一个新的子处理回调函数。

          安排 ‘callback(pid, returncode, *args)’ 在进程的PID与 `pid' 相
          等时调用。指定另一个同进程的回调函数替换之前的回调处理函数。

          回调函数 `callback' 必须是线程安全。

      -- 成員函式: remove_child_handler (pid)

          删除进程PID与 `pid' 相等的进程的处理函数。

          处理函数成功删除时返回 ‘True’ ，没有删除时返回 ‘False’ 。

      -- 成員函式: attach_loop (loop)

          给一个事件循环绑定监视器。

          如果监视器之前已绑定另一个事件循环，那么在绑定新循环前会先解绑
          原来的事件循环。

          注意：循环有可能是 ‘None’ 。

      -- 成員函式: is_active ()

          如果监视器已准备好使用则返回 ‘True’。

          使用 `不活动的' 当前子监视器生成子进程将引发 *note
          RuntimeError: 3dc.。

          3.8 版新加入.

      -- 成員函式: close ()

          关闭监视器。

          必须调用这个方法以确保相关资源会被清理。

 -- 類別: asyncio.ThreadedChildWatcher

     此实现会为每个生成的子进程启动一具新的等待线程。

     即使是当 asyncio 事件循环运行在非主 OS 线程上时它也能可靠地工作。

     当处理大量子进程时不存在显著的开销 (每次子进程结束时为 `O(1)')，但
     当每个进程启动一个线程时则需要额外的内存。

     此监视器会默认被使用。

     3.8 版新加入.

 -- 類別: asyncio.MultiLoopChildWatcher

     此实现会在实例化时注册一个 ‘SIGCHLD’ 信号处理程序。 这可能会破坏为
     ‘SIGCHLD’ 信号安装自定义处理程序的第三方代码。

     此监视器会在收到 ‘SIGCHLD’ 信号时通过显式地轮询每个进程来避免干扰其
     他代码生成的进程。

     该监视器一旦被安装就不会限制从不同线程运行子进程。

     该解决方案是安全的，但在处理大量进程时会有显著的开销 (每收到一个
     ‘SIGCHLD’ 时为 `O(n)')。

     3.8 版新加入.

 -- 類別: asyncio.SafeChildWatcher

     该实现会使用主线程中的活动事件循环来处理 ‘SIGCHLD’ 信号。 如果主线
     程没有正在运行的事件循环，则其他线程无法生成子进程 (会引发 *note
     RuntimeError: 3dc.)。

     此监视器会在收到 ‘SIGCHLD’ 信号时通过显式地轮询每个进程来避免干扰其
     他代码生成的进程。

     该解决方案与 *note MultiLoopChildWatcher: 2783. 同样安全并同样具有
     `O(N)' 复杂度，但需要主线程有正在运行的事件循环才能工作。

 -- 類別: asyncio.FastChildWatcher

     这种实现直接调用 ‘os.waitpid(-1)’ 来获取所有已结束的进程，可能会中
     断其它代码洐生进程并等待它们结束。

     在处理大量子监视器时没有明显的开销( `O(1)' 每次子监视器结束)。

     该解决方案需要主线程有正在运行的事件循环才能工作，这与 *note
     SafeChildWatcher: 2784. 一样。

 -- 類別: asyncio.PidfdChildWatcher

     这个实现会轮询处理文件描述符 (pidfds) 以等待子进程终结。 在某些方面
     ，*note PidfdChildWatcher: 18e. 是一个“理想的”子进程监视器实现。 它
     不需要使用信号或线程，不会介入任何在事件循环以外发起的进程，并能随
     事件循环发起的子进程数量进行线性伸缩。 其主要缺点在于 pidfds 是
     Linux 专属的，并且仅在较近版本的核心（5.3+）上可用。

     3.9 版新加入.


File: python.info,  Node: 自定义策略,  Prev: 进程监视器,  Up: 策略

5.18.1.99 自定义策略
....................

要实现一个新的事件循环策略，建议子类化 *note DefaultEventLoopPolicy:
277f. 并重写需要定制行为的方法，例如:

     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())


File: python.info,  Node: 平台支持,  Next: 高层级 API 索引,  Prev: 策略,  Up: asyncio --- 异步 I/O

5.18.1.100 平台支持
...................

*note asyncio: 9. 模块被设计为可移植的,但由于平台的底层架构和功能，一些
平台存在细微的差异和限制。

* Menu:

* 所有平台::
* Windows: Windows<55>.
* macOS: macOS<30>.


File: python.info,  Node: 所有平台,  Next: Windows<55>,  Up: 平台支持

5.18.1.101 所有平台
...................

   * *note loop.add_reader(): 2689. 和 *note loop.add_writer(): 2707. 不
     能用来监视文件I/O。


File: python.info,  Node: Windows<55>,  Next: macOS<30>,  Prev: 所有平台,  Up: 平台支持

5.18.1.102 Windows
..................

`源代码:' Lib/asyncio/proactor_events.py(1),
Lib/asyncio/windows_events.py(2), Lib/asyncio/windows_utils.py(3)

__________________________________________________________________

3.8 版更變: 在 Windows 上，*note ProactorEventLoop: 2de. 现在是默认的事
件循环。

Windows上的所有事件循环都不支持以下方法:

   * 不支持 *note loop.create_unix_connection(): 266e. 和 *note
     loop.create_unix_server(): 466. 。 *note socket.AF_UNIX: 26fe. 套接
     字相关参数仅限于Unix。

   * 不支持 *note loop.add_signal_handler(): 263d. 和 *note
     loop.remove_signal_handler(): 2712. 。

*note SelectorEventLoop: 26c2. 有下列限制:

   * *note SelectSelector: 2792. 只被用于等待套接字事件：它支持套接字且
     最多支持512个套接字。

   * *note loop.add_reader(): 2689. 和 *note loop.add_writer(): 2707. 只
     接受套接字处理回调函数(如管道、文件描述符等都不支持)。

   * 因为不支持管道，所以 *note loop.connect_read_pipe(): 26ac. 和 *note
     loop.connect_write_pipe(): 26ad. 方法没有实现。

   * 不支持 *note Subprocesses: 2639. ，也就是 *note
     loop.subprocess_exec(): 263c. 和 *note loop.subprocess_shell():
     26aa. 方法没有实现。

*note ProactorEventLoop: 2de. 有下列限制:

   * 不支持 *note loop.add_reader(): 2689. 和 *note loop.add_writer():
     2707. 方法。

Windows上单调时钟的分辨率大约为 15.6 毫秒。最佳的分辨率是 0.5 毫秒。分辨
率依赖于具体的硬件（HPET(4)）和Windows的设置。

* Menu:

* Windows的子进程支持::

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/Lib/asyncio/proactor_events.py

   (2) 
https://github.com/python/cpython/tree/3.9/Lib/asyncio/windows_events.py

   (3) 
https://github.com/python/cpython/tree/3.9/Lib/asyncio/windows_utils.py

   (4) https://zh.wikipedia.org/wiki/高精度事件计时器


File: python.info,  Node: Windows的子进程支持,  Up: Windows<55>

5.18.1.103 Windows的子进程支持
..............................

在 Windows 上，默认的事件循环 *note ProactorEventLoop: 2de. 支持子进程，
而 *note SelectorEventLoop: 26c2. 则不支持。

也不支持 *note policy.set_child_watcher(): 277e. 函数，*note
ProactorEventLoop: 2de. 有不同的机制来监视子进程。


File: python.info,  Node: macOS<30>,  Prev: Windows<55>,  Up: 平台支持

5.18.1.104 macOS
................

完整支持流行的macOS版本。

macOS <= 10.8
.............

在 macOS 10.6, 10.7 和 10.8 上，默认的事件循环使用 *note
selectors.KqueueSelector: 2795.，在这些版本上它并不支持字符设备。 可以手
工配置 *note SelectorEventLoop: 26c2. 来使用 *note SelectSelector: 2792.
或 *note PollSelector: 54e. 以在这些较老版本的 macOS 上支持字符设备。 例
如:

     import asyncio
     import selectors

     selector = selectors.SelectSelector()
     loop = asyncio.SelectorEventLoop(selector)
     asyncio.set_event_loop(loop)


File: python.info,  Node: 高层级 API 索引,  Next: 低层级 API 索引,  Prev: 平台支持,  Up: asyncio --- 异步 I/O

5.18.1.105 高层级 API 索引
..........................

这个页面列举了所有能用于 async/wait 的高层级asyncio API 集。

* Menu:

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


File: python.info,  Node: Tasks,  Next: 队列集<2>,  Up: 高层级 API 索引

5.18.1.106 Tasks
................

运行异步程序，创建Task对象，等待多件事运行超时的公共集。

*note run(): 18d.                                      创建事件循环，运行一个协程，关闭事件循环。
                                                       
                                                       
*note create_task(): 2e1.                              启动一个asyncio的Task对象。
                                                       
                                                       
‘await’ *note sleep(): 3aa.                            休眠几秒。
                                                       
                                                       
‘await’ *note gather(): 3ab.                           并发执行所有事件的调度和等待。
                                                       
                                                       
‘await’ *note wait_for(): 191.                         有超时控制的运行。
                                                       
                                                       
‘await’ *note shield(): 3ac.                           屏蔽取消操作
                                                       
                                                       
‘await’ *note wait(): 207.                             完成情况的监控器
                                                       
                                                       
*note current_task(): 228.                             返回当前Task对象
                                                       
                                                       
*note all_tasks(): 229.                                返回事件循环中所有的task对象。
                                                       
                                                       
*note Task: 2e0.                                       Task对象
                                                       
                                                       
*note to_thread(): 18f.                                在不同的 OS 线程中异步地运行一个函数。
                                                       
                                                       
*note run_coroutine_threadsafe(): 613.                 从其他OS线程中调度一个协程。
                                                       
                                                       
‘for in’ *note as_completed(): 3ad.                    用 ‘for’ 循环监控完成情况。
                                                       

示例
....

   * *note 使用 asyncio.gather() 并行运行: 264b.

   * *note 使用 asyncio.wait_for() 强制超时: 2650.

   * *note 撤销协程: 265c.

   * *note asyncio.sleep() 的用法: 2649.

   * 请主要参阅 *note 协程与任务文档: 2637.


File: python.info,  Node: 队列集<2>,  Next: 子进程集,  Prev: Tasks,  Up: 高层级 API 索引

5.18.1.107 队列集
.................

队列集被用于多个异步Task对象的运行调度，实现连接池以及发布/订阅模式。

*note Queue: 3b3.                                      先进先出队列
                                                       
                                                       
*note PriorityQueue: 26d6.                             优先级队列。
                                                       
                                                       
*note LifoQueue: 26d8.                                 后进先出队列。
                                                       

示例
....

   * *note 使用 asyncio.Queue 在多个并发任务间分配工作量: 26da.

   * 请参阅 *note 队列集文档: 263a.


File: python.info,  Node: 子进程集,  Next: 流<2>,  Prev: 队列集<2>,  Up: 高层级 API 索引

5.18.1.108 子进程集
...................

用于生成子进程和运行shell命令的工具包。

‘await’ *note create_subprocess_exec(): 3b4.           创建一个子进程。
                                                       
                                                       
‘await’ *note create_subprocess_shell(): 3b5.          运行一个shell命令。
                                                       

示例
....

   * *note 执行一个shell命令: 26a6.

   * 请参阅 *note 子进程 APIs: 2639. 相关文档.


File: python.info,  Node: 流<2>,  Next: 同步,  Prev: 子进程集,  Up: 高层级 API 索引

5.18.1.109 流
.............

用于网络IO处理的高级API集。

‘await’ *note open_connection(): 46b.                  建立一个TCP连接。
                                                       
                                                       
‘await’ *note open_unix_connection(): 266d.            建立一个Unix socket连接。
                                                       
                                                       
‘await’ *note start_server(): 46c.                     启动TCP服务。
                                                       
                                                       
‘await’ *note start_unix_server(): 266f.               启动一个Unix socket服务。
                                                       
                                                       
*note StreamReader: 1105.                              接收网络数据的高级async/await对象。
                                                       
                                                       
*note StreamWriter: 1106.                              发送网络数据的高级async/await对象。
                                                       

示例
....

   * *note TCP 客户端样例: 266b.

   * 请参阅 *note streams APIs: 2638. 文档。


File: python.info,  Node: 同步,  Next: 异常<10>,  Prev: 流<2>,  Up: 高层级 API 索引

5.18.1.110 同步
...............

能被用于Task对象集的，类似线程的同步基元组件。

*note Lock: 3ae.                                       互斥锁。
                                                       
                                                       
*note Event: 3af.                                      事件对象。
                                                       
                                                       
*note Condition: 3b0.                                  条件对象
                                                       
                                                       
*note Semaphore: 3b1.                                  信号量
                                                       
                                                       
*note BoundedSemaphore: 3b2.                           有界的信号量。
                                                       

示例
....

   * *note asyncio.Event 的用法: 2695.

   * 请参阅asyncio文档 *note synchronization primitives: 263b.


File: python.info,  Node: 异常<10>,  Prev: 同步,  Up: 高层级 API 索引

5.18.1.111 异常
...............

*note asyncio.TimeoutError: 264f.                      类似 *note wait_for(): 191. 等函数在超时时候被引发。
                                                       请注意 ‘asyncio.TimeoutError’ 与内建异常
                                                       *note TimeoutError: a7d. 无关。
                                                       
                                                       
*note asyncio.CancelledError: 2da.                     当一个Task对象被取消的时候被引发。请参阅
                                                       *note Task.cancel(): 264d.。
                                                       

示例
....

   * *note 在取消请求发生的运行代码中如何处理CancelledError异常: 265c.

   * 请参阅完整的 *note asyncio 专用异常: 26dc. 列表.


File: python.info,  Node: 低层级 API 索引,  Next: 用 asyncio 开发,  Prev: 高层级 API 索引,  Up: asyncio --- 异步 I/O

5.18.1.112 低层级 API 索引
..........................

本页列出所有低层级的 asyncio API。

* Menu:

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


File: python.info,  Node: 获取事件循环,  Next: 事件循环方法集<2>,  Up: 低层级 API 索引

5.18.1.113 获取事件循环
.......................

*note asyncio.get_running_loop(): 45c.                 获取当前运行的事件循环 `首选' 函数。
                                                       
                                                       
*note asyncio.get_event_loop(): 45d.                   获得一个事件循环实例(当前或通过策略)。
                                                       
                                                       
*note asyncio.set_event_loop(): 26e3.                  通过当前策略将事件循环设置当前事件循环。
                                                       
                                                       
*note asyncio.new_event_loop(): 26e4.                  创建一个新的事件循环。
                                                       

示例
....

   * *note 使用asyncio.get_running_loop(): 2731.。


File: python.info,  Node: 事件循环方法集<2>,  Next: 传输<2>,  Prev: 获取事件循环,  Up: 低层级 API 索引

5.18.1.114 事件循环方法集
.........................

查阅 *note 事件循环方法: 737. 相关的主要文档段落 。

生命周期
........

*note loop.run_until_complete(): 611.                  运行一个期程/任务/可等待对象直到完成。
                                                       
                                                       
*note loop.run_forever(): 26ed.                        一直运行事件循环。
                                                       
                                                       
*note loop.stop(): 619.                                停止事件循环。
                                                       
                                                       
*note loop.close(): 26ef.                              关闭事件循环。
                                                       
                                                       
*note loop.is_running(): 26ee.                         返回 ‘True’ ， 如果事件循环正在运行。
                                                       
                                                       
*note loop.is_closed(): 78e.                           返回 ‘True’ ，如果事件循环已经被关闭 。
                                                       
                                                       
‘await’ *note loop.shutdown_asyncgens(): 61a.          关闭异步生成器。
                                                       

调试
....

*note loop.set_debug(): 78c.                           开启或禁用调试模式。
                                                       
                                                       
*note loop.get_debug(): 78d.                           获取当前测试模式。
                                                       

调度回调函数
............

*note loop.call_soon(): 455.                           尽快调用回调。
                                                       
                                                       
*note loop.call_soon_threadsafe(): 456.                *note loop.call_soon(): 455. 方法线程安全的变体。
                                                       
                                                       
*note loop.call_later(): 457.                          在给定时间 `之后' 调用回调函数。
                                                       
                                                       
*note loop.call_at(): 458.                             在 `指定' 时间调用回调函数。
                                                       

线程/进程池
...........

‘await’ *note loop.run_in_executor(): 190.             在 *note concurrent.futures: 21. 执行器中运行一个独
                                                       占CPU或其它阻塞函数。
                                                       
                                                       
*note loop.set_default_executor(): 3a1.                设置 *note loop.run_in_executor(): 190. 默认执行器。
                                                       

任务与期程
..........

*note loop.create_future(): 615.                       创建一个 *note Future: 545. 对象。
                                                       
                                                       
*note loop.create_task(): 2e2.                         将协程当作 *note Task: 2e0. 一样调度。
                                                       
                                                       
*note loop.set_task_factory(): 790.                    设置 *note loop.create_task(): 2e2. 使用的工厂，它将
                                                       用来创建 *note Tasks: 2e0. 。
                                                       
                                                       
*note loop.get_task_factory(): 791.                    获取 *note loop.create_task(): 2e2. 使用的工厂，它用
                                                       来创建 *note Tasks: 2e0. 。
                                                       

DNS
...

‘await’ *note loop.getaddrinfo(): 59b.                 异步版的 *note socket.getaddrinfo(): 270c. 。
                                                       
                                                       
‘await’ *note loop.getnameinfo(): 59c.                 异步版的 *note socket.getnameinfo(): 270d. 。
                                                       

网络和IPC
.........

‘await’ *note loop.create_connection(): 2e5.           打开一个TCP链接。
                                                       
                                                       
‘await’ *note loop.create_server(): 465.               创建一个TCP服务。
                                                       
                                                       
‘await’ *note loop.create_unix_connection(): 266e.     打开一个Unix socket连接。
                                                       
                                                       
‘await’ *note loop.create_unix_server(): 466.          创建一个Unix socket服务。
                                                       
                                                       
‘await’ *note loop.connect_accepted_socket(): 46d.     将 *note socket: 767. 包装成 ‘(transport, protocol)’
                                                       对。
                                                       
                                                       
‘await’ *note loop.create_datagram_endpoint(): 189.    打开一个数据报(UDP)连接。
                                                       
                                                       
‘await’ *note loop.sendfile(): 2703.                   通过传输通道发送一个文件。
                                                       
                                                       
‘await’ *note loop.start_tls(): 45a.                   将一个已建立的链接升级到TLS。
                                                       
                                                       
‘await’ *note loop.connect_read_pipe(): 26ac.          将管道读取端包装成 ‘(transport, protocol)’ 对。
                                                       
                                                       
‘await’ *note loop.connect_write_pipe(): 26ad.         将管道写入端包装成 ‘(transport, protocol)’ 对。
                                                       

套接字
......

‘await’ *note loop.sock_recv(): 598.                   从 *note socket: 767. 接收数据。
                                                       
                                                       
‘await’ *note loop.sock_recv_into(): 45b.              从 *note socket: 767. 接收数据到一个缓冲区中。
                                                       
                                                       
‘await’ *note loop.sock_sendall(): 599.                发送数据到 *note socket: 767. 。
                                                       
                                                       
‘await’ *note loop.sock_connect(): 794.                链接 ‘await’ *note loop.sock_connect(): 794. 。
                                                       
                                                       
‘await’ *note loop.sock_accept(): 59a.                 接受一个 *note socket: 767. 链接。
                                                       
                                                       
‘await’ *note loop.sock_sendfile(): 460.               利用 *note socket: 767. 发送一个文件。
                                                       
                                                       
*note loop.add_reader(): 2689.                         开始对一个文件描述符的可读性的监视。
                                                       
                                                       
*note loop.remove_reader(): 2706.                      停止对一个文件描述符的可读性的监视。
                                                       
                                                       
*note loop.add_writer(): 2707.                         开始对一个文件描述符的可写性的监视。
                                                       
                                                       
*note loop.remove_writer(): 2708.                      停止对一个文件描述符的可写性的监视。
                                                       

Unix信号
........

*note loop.add_signal_handler(): 263d.                 给 *note signal: ea. 添加一个处理回调函数。
                                                       
                                                       
*note loop.remove_signal_handler(): 2712.              删除 *note signal: ea. 的处理回调函数。
                                                       

子进程
......

*note loop.subprocess_exec(): 263c.                    衍生一个子进程
                                                       
                                                       
*note loop.subprocess_shell(): 26aa.                   从终端命令衍生一个子进程。
                                                       

错误处理
........

*note loop.call_exception_handler(): 2716.             调用异常处理器。
                                                       
                                                       
*note loop.set_exception_handler(): 2715.              设置一个新的异常处理器。
                                                       
                                                       
*note loop.get_exception_handler(): 616.               获取当前异常处理器。
                                                       
                                                       
*note loop.default_exception_handler(): 2717.          默认异常处理器实现。
                                                       

示例
....

   * *note 使用 asyncio.get_event_loop() 和 loop.run_forever(): 2720.

   * *note 使用 loop.call_later(): 2722.

   * 使用 ‘loop.create_connection()’ 实现 *note echo客户端: 2681.

   * 使用 ‘loop.create_connection()’ 去 *note 链接socket: 2688.

   * *note 使用add_reader()监听FD(文件描述符)的读取事件: 268a.

   * *note 使用loop.add_signal_handler(): 2725.

   * *note 使用loop.add_signal_handler(): 26c6.。


File: python.info,  Node: 传输<2>,  Next: 协议<2>,  Prev: 事件循环方法集<2>,  Up: 低层级 API 索引

5.18.1.115 传输
...............

所有传输都实现以下方法:

*note transport.close(): 273f.                         关闭传输。
                                                       
                                                       
*note transport.is_closing(): 614.                     返回 ‘True’ ，如果传输正在关闭或已经关闭。
                                                       
                                                       
*note transport.get_extra_info(): 3ea.                 请求传输的相关信息。
                                                       
                                                       
*note transport.set_protocol(): 2744.                  设置一个新协议。
                                                       
                                                       
*note transport.get_protocol(): 2745.                  返回当前协议。
                                                       

传输可以接收数据(TCP和Unix链接，管道等)。它通过 *note
loop.create_connection(): 2e5, *note loop.create_unix_connection():
266e, *note loop.connect_read_pipe(): 26ac. 等方法返回。

读取传输
........

*note transport.is_reading(): 46f.                     返回 ‘True’ ，如果传输正在接收。
                                                       
                                                       
*note transport.pause_reading(): 471.                  暂停接收。
                                                       
                                                       
*note transport.resume_reading(): 470.                 继续接收。
                                                       

传输可以发送数据(TCP和Unix链接，管道等)。它通过 *note
loop.create_connection(): 2e5, *note loop.create_unix_connection():
266e, *note loop.connect_write_pipe(): 26ad. 等方法返回。

写入传输
........

*note transport.write(): 2750.                         向传输写入数据。
                                                       
                                                       
*note transport.write(): 2750.                         向传输写入缓冲。
                                                       
                                                       
*note transport.can_write_eof(): 274a.                 返回 *note True: 593. ，如果传输支持发送 EOF。
                                                       
                                                       
*note transport.write_eof(): 274b.                     在冲洗已缓冲的数据后关闭传输和发送EOF。
                                                       
                                                       
*note transport.abort(): 2749.                         立即关闭传输。
                                                       
                                                       
*note transport.get_write_buffer_size(): 274c.         返回写入流控制的高位标记位和低位标记位。
                                                       
                                                       
*note transport.set_write_buffer_limits(): 274d.       设置新的写入流控制的高位标记位和低位标记位。
                                                       

由 *note loop.create_datagram_endpoint(): 189. 返回的传输:

数据报传输
..........

*note transport.sendto(): 2753.                        发送数据到远程链接端。
                                                       
                                                       
*note transport.abort(): 2754.                         立即关闭传输。
                                                       

基于子进程的底层抽象传输，它由 *note loop.subprocess_exec(): 263c. 和
*note loop.subprocess_shell(): 26aa. 返回:

子进程传输
..........

*note transport.get_pid(): 2756.                       返回子进程的进程ID。
                                                       
                                                       
*note transport.get_pipe_transport(): 2757.            返回请求通信管道 (`stdin', `stdout', 或 `stderr')的
                                                       传输。
                                                       
                                                       
*note transport.get_returncode(): 2758.                返回子进程的返回代号。
                                                       
                                                       
*note transport.kill(): 2759.                          杀死子进程。
                                                       
                                                       
*note transport.send_signal(): 275b.                   发送一个信号到子进程。
                                                       
                                                       
*note transport.terminate(): 275a.                     停止子进程。
                                                       
                                                       
*note transport.close(): 275c.                         杀死子进程并关闭所有管道。
                                                       


File: python.info,  Node: 协议<2>,  Next: 事件循环策略,  Prev: 传输<2>,  Up: 低层级 API 索引

5.18.1.116 协议
...............

协议类可以由下面 `回调方法' 实现：

‘callback’ *note connection_made(): 26fc.              链接建立时被调用。
                                                       
                                                       
‘callback’ *note connection_lost(): 2740.              链接丢失或关闭时被调用。
                                                       
                                                       
‘callback’ *note pause_writing(): 274e.                传输的缓冲区超过高位标记位时被调用。
                                                       
                                                       
‘callback’ *note resume_writing(): 274f.               传输的缓冲区传送到低位标记位时被调用。
                                                       

流协议 (TCP, Unix 套接字, 管道)
...............................

‘callback’ *note data_received(): 2747.                接收到数据时被调用。
                                                       
                                                       
‘callback’ *note eof_received(): 2760.                 接收到EOF时被调用。
                                                       

缓冲流协议
..........

‘callback’ *note get_buffer(): 2762.                   调用后会分配新的接收缓冲区。
                                                       
                                                       
‘callback’ *note buffer_updated(): 2763.               用接收的数据更新缓冲区时被调用。
                                                       
                                                       
‘callback’ *note eof_received(): 2764.                 接收到EOF时被调用。
                                                       

数据报协议
..........

‘callback’ *note datagram_received(): 2766.            接收到数据报时被调用。
                                                       
                                                       
‘callback’ *note error_received(): 2767.               前一个发送或接收操作引发 *note OSError: 304. 时被调
                                                       用。
                                                       

子进程协议
..........

‘callback’ *note pipe_data_received(): 2769.           子进程向 `stdout' 或 `stderr' 管道写入数据时被调用。
                                                       
                                                       
‘callback’ *note pipe_connection_lost(): 276a.         与子进程通信的其中一个管道关闭时被调用。
                                                       
                                                       
‘callback’ *note process_exited(): 276b.               子进程退出时被调用。
                                                       


File: python.info,  Node: 事件循环策略,  Prev: 协议<2>,  Up: 低层级 API 索引

5.18.1.117 事件循环策略
.......................

策略是改变 *note asyncio.get_event_loop(): 45d. 这类函数行为的一个底层机
制。更多细节可以查阅 *note 策略部分: 26e5.。

访问策略
........

*note asyncio.get_event_loop_policy(): 2776.           返回当前进程域的策略。
                                                       
                                                       
*note asyncio.set_event_loop_policy(): 2777.           设置一个新的进程域策略。
                                                       
                                                       
*note AbstractEventLoopPolicy: 2774.                   策略对象的基类。
                                                       


File: python.info,  Node: 用 asyncio 开发,  Prev: 低层级 API 索引,  Up: asyncio --- 异步 I/O

5.18.1.118 用 asyncio 开发
..........................

异步编程与传统的“顺序”编程不同。

本页列出常见的错误和陷阱，并解释如何避免它们。

* Menu:

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


File: python.info,  Node: Debug 模式,  Next: 并发性和多线程,  Up: 用 asyncio 开发

5.18.1.119 Debug 模式
.....................

默认情况下，asyncio以生产模式运行。为了简化开发，asyncio还有一种*debug 模
式* 。

有几种方法可以启用异步调试模式:

   * 将 *note PYTHONASYNCIODEBUG: 148d. 环境变量设置为 ‘1’ 。

   * 使用 *note Python 开发模式: 160.。

   * 将 ‘debug=True’ 传递给 *note asyncio.run(): 18d. 。

   * 调用 *note loop.set_debug(): 78c. 。

除了启用调试模式外，还要考虑:

   * 将 *note asyncio logger: 27a9. 的日志级别设置为 ‘logging.DEBUG’，例
     如，下面的代码片段可以在应用程序启动时运行:

          logging.basicConfig(level=logging.DEBUG)

   * 配置 *note warnings: 12f. 模块以显示 *note ResourceWarning: 5ca. 警
     告。一种方法是使用 *note -W: 15b. ‘default’ 命令行选项。

启用调试模式时:

   * asyncio 检查 *note 未被等待的协程: 27aa. 并记录他们；这将消除“被遗
     忘的等待”问题。

   * 许多非线程安全的异步 APIs (例如 *note loop.call_soon(): 455. 和
     *note loop.call_at(): 458. 方法)，如果从错误的线程调用，则会引发异
     常。

   * 如果执行I/O操作花费的时间太长，则记录I/O选择器的执行时间。

   * 执行时间超过100毫秒的回调将会载入日志。 属性
     ‘loop.slow_callback_duration’ 可用于设置以秒为单位的最小执行持续时
     间，这被视为“缓慢”。


File: python.info,  Node: 并发性和多线程,  Next: 运行阻塞的代码,  Prev: Debug 模式,  Up: 用 asyncio 开发

5.18.1.120 并发性和多线程
.........................

事件循环在线程中运行(通常是主线程)，并在其线程中执行所有回调和任务。当一
个任务在事件循环中运行时，没有其他任务可以在同一个线程中运行。当一个任务
执行一个 ‘await’ 表达式时，正在运行的任务被挂起，事件循环执行下一个任务
。

要调度来自另一 OS 线程的 *note callback: 26f1.，应该使用 *note
loop.call_soon_threadsafe(): 456. 方法。 例如:

     loop.call_soon_threadsafe(callback, *args)

几乎所有异步对象都不是线程安全的，这通常不是问题，除非在任务或回调函数之
外有代码可以使用它们。如果需要这样的代码来调用低级异步API，应该使用
*note loop.call_soon_threadsafe(): 456. 方法，例如:

     loop.call_soon_threadsafe(fut.cancel)

要从不同的OS线程调度一个协程对象，应该使用 *note
run_coroutine_threadsafe(): 613. 函数。它返回一个 *note
concurrent.futures.Future: c00. 。查询结果:

     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()

为了能够处理信号和执行子进程，事件循环必须运行于主线程中。

方法 *note loop.run_in_executor(): 190. 可以和 *note
concurrent.futures.ThreadPoolExecutor: 18c. 一起使用，用于在一个不同的操
作系统线程中执行阻塞代码，并避免阻塞运行事件循环的那个操作系统线程。

目前没有什么办法能直接从另一个进程 (例如通过 *note multiprocessing: b7.
启动的进程) 安排协程或回调。 *note 事件循环方法: 737. 小节列出了可以从管
道读取并监视文件描述符而不会阻塞事件循环的 API。 此外，asyncio 的 *note
子进程: 2639. API 提供了一种启动进程并从事件循环与其通信的办法。 最后，
之前提到的 *note loop.run_in_executor(): 190. 方法也可配合 *note
concurrent.futures.ProcessPoolExecutor: 196. 使用以在另一个进程中执行代
码。


File: python.info,  Node: 运行阻塞的代码,  Next: 日志<2>,  Prev: 并发性和多线程,  Up: 用 asyncio 开发

5.18.1.121 运行阻塞的代码
.........................

不应该直接调用阻塞( CPU 绑定)代码。例如，如果一个函数执行1秒的 CPU 密集
型计算，那么所有并发异步任务和 IO 操作都将延迟1秒。

可以用执行器在不同的线程甚至不同的进程中运行任务，以避免使用事件循环阻塞
OS 线程。 请参阅 *note loop.run_in_executor(): 190. 方法了解详情。


File: python.info,  Node: 日志<2>,  Next: 检测 never-awaited 协同程序,  Prev: 运行阻塞的代码,  Up: 用 asyncio 开发

5.18.1.122 日志
...............

asyncio使用 *note logging: aa. 模块，所有日志记录都是通过 ‘"asyncio"’
logger执行的。

默认日志级别是 ‘logging.INFO’ 。可以很容易地调整:

     logging.getLogger("asyncio").setLevel(logging.WARNING)


File: python.info,  Node: 检测 never-awaited 协同程序,  Next: 检测就再也没异常,  Prev: 日志<2>,  Up: 用 asyncio 开发

5.18.1.123 检测 never-awaited 协同程序
......................................

当协程函数被调用而不是被等待时 (即执行 ‘coro()’ 而不是 ‘await coro()’) 或
者协程没有通过 *note asyncio.create_task(): 2e1. 被排入计划日程，asyncio
将会发出一条 *note RuntimeWarning: 3e2.:

     import asyncio

     async def test():
         print("never scheduled")

     async def main():
         test()

     asyncio.run(main())

输出:

     test.py:7: RuntimeWarning: coroutine 'test' was never awaited
       test()

调试模式的输出:

     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()

通常的修复方法是等待协程或者调用 *note asyncio.create_task(): 2e1. 函数:

     async def main():
         await test()


File: python.info,  Node: 检测就再也没异常,  Prev: 检测 never-awaited 协同程序,  Up: 用 asyncio 开发

5.18.1.124 检测就再也没异常
...........................

如果调用 *note Future.set_exception(): 265a. ，但不等待 Future 对象，将
异常传播到用户代码。在这种情况下，当 Future 对象被垃圾收集时，asyncio将
发出一条日志消息。

未处理异常的例子:

     import asyncio

     async def bug():
         raise Exception("not consumed")

     async def main():
         asyncio.create_task(bug())

     asyncio.run(main())

输出:

     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

*note 激活调试模式: 148e. 以获取任务创建处的跟踪信息:

     asyncio.run(main(), debug=True)

调试模式的输出:

     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

     備註: asyncio 的源代码可以在 Lib/asyncio/(1) 中找到。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/asyncio/


File: python.info,  Node: socket --- 底层网络接口,  Next: ssl --- 套接字对象的 TLS/SSL 包装器,  Prev: asyncio --- 异步 I/O,  Up: 网络和进程间通信

5.18.2 ‘socket’ — 底层网络接口
------------------------------

`源代码:' Lib/socket.py(1)

__________________________________________________________________

这个模块提供了访问 BSD `套接字' 的接口。在所有现代 Unix 系统、Windows、
macOS 和其他一些平台上可用。

     備註: 一些行为可能因平台不同而异，因为调用的是操作系统的套接字API。

这个Python接口是用Python的面向对象风格对Unix系统调用和套接字库接口的直译
：函数 ‘socket()’ 返回一个 `套接字对象' ，其方法是对各种套接字系统调用的
实现。形参类型一般与C接口相比更高级：例如在Python文件 ‘read()’ 和
‘write()’ 操作中，接收操作的缓冲区分配是自动的，发送操作的缓冲区长度是隐
式的。

也參考
......

模块 *note socketserver: f0.

     用于简化网络服务端编写的类。

模块 *note ssl: f3.

     套接字对象的TLS/SSL封装。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/socket.py


File: python.info,  Node: 套接字协议族,  Next: 模块内容<4>,  Up: socket --- 底层网络接口

5.18.2.1 套接字协议族
.....................

根据系统以及构建选项，此模块提供了各种套接字协议簇。

特定的套接字对象需要的地址格式将根据此套接字对象被创建时指定的地址族被自
动选择。套接字地址表示如下：

   - 一个绑定在文件系统节点上的 *note AF_UNIX: 26fe. 套接字的地址表示为
     一个字符串，使用文件系统字符编码和 ‘'surrogateescape'’ 错误回调方法
     （see PEP 383(1)）。一个地址在 Linux 的抽象命名空间被返回为带有初始
     的 null 字节的 *note 字节类对象: 6df. ；注意在这个命名空间种的套接
     字可能与普通文件系统套接字通信，所以打算运行在 Linux 上的程序可能需
     要解决两种地址类型。当传递为参数时，一个字符串或字节类对象可以用于
     任一类型的地址。

     3.3 版更變: 之前，*note AF_UNIX: 26fe. 套接字路径被假设使用 UTF-8 编
     码。

     3.5 版更變: 现在支持可写的 *note 字节类对象: 6df.。

   - 一对 ‘(host, port)’ 被用于 *note AF_INET: 26f8. 地址族，`host' 是一
     个表示为互联网域名表示法之内的主机名或者一个 IPv4 地址的字符串，例
     如 ‘'daring.cwi.nl'’ 或 ‘'100.50.200.5'’，`port' 是一个整数。

        - 对于 IPv4 地址，有两种可接受的特殊形式被用来代替一个主机地址：
          ‘''’ 代表 ‘INADDR_ANY’，用来绑定到所有接口；字符串
          ‘'<broadcast>'’ 代表 ‘INADDR_BROADCAST’。此行为不兼容 IPv6，因
          此，如果你的 Python 程序打算支持 IPv6，则可能需要避开这些。

   - 对于 *note AF_INET6: 26f9. 地址族，使用一个四元组 ‘(host, port,
     flowinfo, scope_id)’，其中 `flowinfo' 和 `scope_id' 代表了 C 库
     ‘struct sockaddr_in6’ 中的 ‘sin6_flowinfo’ 和 ‘sin6_scope_id’ 成员
     。对于 *note socket: ef. 模块中的方法， `flowinfo' 和 `scope_id' 可
     以被省略，只为了向后兼容。注意，省略 `scope_id' 可能会导致操作带有
     领域 (Scope) 的 IPv6 地址时出错。

     3.7 版更變: 对于多播地址（其 `scope_id' 起作用），`地址' 中可以不包
     含 ‘%scope_id’ （或 ‘zone id’ ）部分，这部分是多余的，可以放心省略
     （推荐）。

   - ‘AF_NETLINK’ 套接字由一对 ‘(pid, groups)’ 表示。

   - 指定 ‘AF_TIPC’ 地址族可以使用仅 Linux 支持的 TIPC 协议。TIPC 是一种
     开放的、非基于 IP 的网络协议，旨在用于集群计算环境。其地址用元组表
     示，其中的字段取决于地址类型。一般元组形式为 ‘(addr_type, v1, v2,
     v3 [, scope])’，其中：

        - `addr_type' 取 ‘TIPC_ADDR_NAMESEQ’、‘TIPC_ADDR_NAME’ 或
          ‘TIPC_ADDR_ID’ 中的一个。

        - `scope' 取 ‘TIPC_ZONE_SCOPE’、‘TIPC_CLUSTER_SCOPE’ 和
          ‘TIPC_NODE_SCOPE’ 中的一个。

        - 如果 `addr_type' 为 ‘TIPC_ADDR_NAME’，那么 `v1' 是服务器类型，
          `v2' 是端口标识符，`v3' 应为 0。

          如果 `addr_type' 为 ‘TIPC_ADDR_NAMESEQ’，那么 `v1' 是服务器类
          型，`v2' 是端口号下限，而 `v3' 是端口号上限。

          如果 `addr_type' 为 ‘TIPC_ADDR_ID’，那么 `v1' 是节点 (node)，
          `v2' 是 ref，`v3' 应为 0。

   - *note AF_CAN: 27b5. 地址族使用元组 ‘(interface, )’，其中
     `interface' 是表示网络接口名称的字符串，如 ‘'can0'’。网络接口名
     ‘''’ 可以用于接收本族所有网络接口的数据包。

        - *note CAN_ISOTP: 27b6. 协议接受一个元组 ‘(interface, rx_addr,
          tx_addr)’，其中两个额外参数都是无符号长整数，都表示 CAN 标识符
          （标准或扩展标识符）。

        - *note CAN_J1939: 1e3. 协议接受一个元组 ‘(interface, name, pgn,
          addr)’，其中额外参数有：表示 ECU 名称的 64 位无符号整数，表示
          参数组号 (Parameter Group Number, PGN) 的 32 位无符号整数，以
          及表示地址的 8 位整数。

   - ‘PF_SYSTEM’ 协议簇的 ‘SYSPROTO_CONTROL’ 协议接受一个字符串或元组
     ‘(id, unit)’。其中字符串是内核控件的名称，该控件使用动态分配的 ID。
     而如果 ID 和内核控件的单元 (unit) 编号都已知，或使用了已注册的 ID，
     可以采用元组。

     3.3 版新加入.

   - ‘AF_BLUETOOTH’ 支持以下协议和地址格式：

        - ‘BTPROTO_L2CAP’ 接受 ‘(bdaddr, psm)’，其中 ‘bdaddr’ 为字符串格
          式的蓝牙地址，‘psm’ 是一个整数。

        - ‘BTPROTO_RFCOMM’ 接受 ‘(bdaddr, channel)’，其中 ‘bdaddr’ 为字
          符串格式的蓝牙地址，‘channel’ 是一个整数。

        - ‘BTPROTO_HCI’ 接受 ‘(device_id,)’，其中 ‘device_id’ 为整数或字
          符串，它表示接口对应的蓝牙地址（具体取决于你的系统，NetBSD 和
          DragonFlyBSD 需要蓝牙地址字符串，其他系统需要整数）。

          3.2 版更變: 添加了对 NetBSD 和 DragonFlyBSD 的支持。

        - ‘BTPROTO_SCO’ 接受 ‘bdaddr’，其中 ‘bdaddr’ 是 *note bytes:
          172. 对象，其中含有字符串格式的蓝牙地址（如
          ‘b'12:23:34:45:56:67'’ ），FreeBSD 不支持此协议。

   - *note AF_ALG: 67b. 是一个仅 Linux 可用的、基于套接字的接口，用于连
     接内核加密算法。算法套接字可用包括 2 至 4 个元素的元组来配置
     ‘(type, name [, feat [, mask]])’，其中：

        - `type' 是表示算法类型的字符串，如 ‘aead’、‘hash’、‘skcipher’ 或
          ‘rng’。

        - `name' 是表示算法类型和操作模式的字符串，如 ‘sha256’、
          ‘hmac(sha256)’、‘cbc(aes)’ 或 ‘drbg_nopr_ctr_aes256’。

        - `feat' 和 `mask' 是无符号 32 位整数。

     *note Availability: 1491.: Linux 2.6.38, some algorithm types
     require more recent Kernels.

     3.6 版新加入.

   - *note AF_VSOCK: 4d9. 用于支持虚拟机与宿主机之间的通讯。该套接字用
     ‘(CID, port)’ 元组表示，其中 Context ID (CID) 和 port 都是整数。

     *note Availability: 1491.: Linux >= 4.8 QEMU >= 2.8 ESX >= 4.0 ESX
     Workstation >= 6.5.

     3.7 版新加入.

   - *note AF_PACKET: 27b7. 是一个底层接口，直接连接至网卡。数据包使用元
     组 ‘(ifname, proto[, pkttype[, hatype[, addr]]])’ 表示，其中：

        - `ifname' - 指定设备名称的字符串。

        - `proto' - 一个用网络字节序表示的整数，指定以太网协议版本号。

        - `pkttype' - 指定数据包类型的整数（可选）：

             - ‘PACKET_HOST’ （默认） - 寻址到本地主机的数据包。

             - ‘PACKET_BROADCAST’ - 物理层广播的数据包。

             - ‘PACKET_MULTIHOST’ - 发送到物理层多播地址的数据包。

             - ‘PACKET_OTHERHOST’ - 被（处于混杂模式的）网卡驱动捕获的、
               发送到其他主机的数据包。

             - ‘PACKET_OUTGOING’ - 来自本地主机的、回环到一个套接字的数
               据包。

        - `hatype' - 可选整数，指定 ARP 硬件地址类型。

        - `addr' - 可选的类字节串对象，用于指定硬件物理地址，其解释取决
          于各设备。

          *note Availability: 1491.: Linux >= 2.2.

   - *note AF_QIPCRTR: 27b8. 是一个仅 Linux 可用的、基于套接字的接口，用
     于与高通平台中协处理器上运行的服务进行通信。该地址簇用一个 ‘(node,
     port)’ 元组表示，其中 `node' 和 `port' 为非负整数。

          *note Availability: 1491.: Linux >= 4.7.

     3.8 版新加入.

   - ‘IPPROTO_UDPLITE’ 是一种 UDP 的变体，允许指定数据包的哪一部分计算入
     校验码内。它添加了两个可以修改的套接字选项。
     ‘self.setsockopt(IPPROTO_UDPLITE, UDPLITE_SEND_CSCOV, length)’ 修改
     传出数据包的哪一部分计算入校验码内，而
     ‘self.setsockopt(IPPROTO_UDPLITE, UDPLITE_RECV_CSCOV, length)’ 将过
     滤掉计算入校验码的数据太少的数据包。在这两种情况下，‘length’ 都应在
     ‘range(8, 2**16, 8)’ 范围内。

     对于 IPv4，应使用 ‘socket(AF_INET, SOCK_DGRAM, IPPROTO_UDPLITE)’ 来
     构造这样的套接字；对于 IPv6，应使用 ‘socket(AF_INET6, SOCK_DGRAM,
     IPPROTO_UDPLITE)’ 来构造这样的套接字。

     *note Availability: 1491.: Linux >= 2.6.20, FreeBSD >= 10.1-RELEASE

     3.9 版新加入.

如果你在 IPv4/v6 套接字地址的 `host' 部分中使用了一个主机名，此程序可能
会表现不确定行为，因为 Python 使用 DNS 解析返回的第一个地址。套接字地址
在实际的 IPv4/v6 中以不同方式解析，根据 DNS 解析和/或 host 配置。为了确
定行为，在 `host' 部分中使用数字的地址。

所有的错误都抛出异常。对于无效的参数类型和内存溢出异常情况可能抛出普通异
常；从 Python 3.3 开始，与套接字或地址语义有关的错误抛出 *note OSError:
304. 或它的子类之一（常用 *note socket.error: a76.）。

可以用 *note setblocking(): 206f. 设置非阻塞模式。一个基于超时的
generalization 通过 *note settimeout(): 27b9. 支持。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0383


File: python.info,  Node: 模块内容<4>,  Next: 套接字对象,  Prev: 套接字协议族,  Up: socket --- 底层网络接口

5.18.2.2 模块内容
.................

*note socket: ef. 模块包含下列元素。

* Menu:

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


File: python.info,  Node: 异常<11>,  Next: 常数<6>,  Up: 模块内容<4>

5.18.2.3 异常
.............

 -- 例外: socket.error

     一个被弃用的 *note OSError: 304. 的别名。

     3.3 版更變: 根据 PEP 3151(1)，这个类是 *note OSError: 304. 的别名。

 -- 例外: socket.herror

     *note OSError: 304. 的子类，本异常通常表示与地址相关的错误，比如那
     些在 POSIX C API 中使用了 `h_errno' 的函数，包括 *note
     gethostbyname_ex(): fae. 和 *note gethostbyaddr(): fad.。附带的值是
     一对 ‘(h_errno, string)’，代表库调用返回的错误。`h_errno' 是一个数
     字，而 `string' 表示 `h_errno' 的描述，它们由 C 函数 ‘hstrerror()’
     返回。

     3.3 版更變: 此类是 *note OSError: 304. 的子类。

 -- 例外: socket.gaierror

     *note OSError: 304. 的子类，本异常来自 *note getaddrinfo(): 270c. 和
     *note getnameinfo(): 270d.，表示与地址相关的错误。附带的值是一对
     ‘(error, string)’，代表库调用返回的错误。`string' 表示 `error' 的描
     述，它由 C 函数 ‘gai_strerror()’ 返回。数字值 `error' 与本模块中定
     义的 ‘EAI_*’ 常量之一匹配。

     3.3 版更變: 此类是 *note OSError: 304. 的子类。

 -- 例外: socket.timeout

     *note OSError: 304. 的子类，当套接字发生超时，且事先已调用过 *note
     settimeout(): 27b9. （或隐式地通过 *note setdefaulttimeout(): 27be.
     ）启用了超时，则会抛出此异常。附带的值是一个字符串，其值总是 "timed
     out"。

     3.3 版更變: 此类是 *note OSError: 304. 的子类。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3151


File: python.info,  Node: 常数<6>,  Next: 函数<6>,  Prev: 异常<11>,  Up: 模块内容<4>

5.18.2.4 常数
.............

     AF_* 和 SOCK_* 常量现在都在 ‘AddressFamily’ 和 ‘SocketKind’ 这两个
     *note IntEnum: 684. 集合内。

     3.4 版新加入.

 -- Data: socket.AF_UNIX
 -- Data: socket.AF_INET
 -- Data: socket.AF_INET6

     这些常量表示地址（和协议）簇，用于 ‘socket()’ 的第一个参数。如果
     *note AF_UNIX: 26fe. 常量未定义，即表示不支持该协议。不同系统可能会
     有更多其他常量可用。

 -- Data: socket.SOCK_STREAM
 -- Data: socket.SOCK_DGRAM
 -- Data: socket.SOCK_RAW
 -- Data: socket.SOCK_RDM
 -- Data: socket.SOCK_SEQPACKET

     这些常量表示套接字类型，用于 ‘socket()’ 的第二个参数。不同系统可能
     会有更多其他常量可用。（一般只有 *note SOCK_STREAM: d52. 和 *note
     SOCK_DGRAM: d51. 可用）

 -- Data: socket.SOCK_CLOEXEC
 -- Data: socket.SOCK_NONBLOCK

     这两个常量（如果已定义）可以与上述套接字类型结合使用，允许你设置这
     些原子性相关的 flags （从而避免可能的竞争条件和单独调用的需要）。

     也參考
     ......

     Secure File Descriptor Handling （安全地处理文件描述符）(1) 提供了
     更详尽的解释。

     *note 可用性: 1491.： Linux >= 2.6.27。

     3.2 版新加入.

 -- Data: SO_*
 -- Data: socket.SOMAXCONN

 -- Data: MSG_*

 -- Data: SOL_*

 -- Data: SCM_*

 -- Data: IPPROTO_*

 -- Data: IPPORT_*

 -- Data: INADDR_*

 -- Data: IP_*

 -- Data: IPV6_*

 -- Data: EAI_*

 -- Data: AI_*

 -- Data: NI_*

 -- Data: TCP_*

     此列表内的许多常量，记载在 Unix 文档中的套接字和/或 IP 协议部分，同
     时也定义在本 socket 模块中。它们通常用于套接字对象的 ‘setsockopt()’
     和 ‘getsockopt()’ 方法的参数中。在大多数情况下，仅那些在 Unix 头文
     件中有定义的符号会在本模块中定义，部分符号提供了默认值。

     3.6 版更變: 添加了 ‘SO_DOMAIN’, ‘SO_PROTOCOL’, ‘SO_PEERSEC’,
     ‘SO_PASSSEC’, ‘TCP_USER_TIMEOUT’, ‘TCP_CONGESTION’。

     3.6.5 版更變: 在 Windows 上，如果 Windows 运行时支持，则
     ‘TCP_FASTOPEN’、‘TCP_KEEPCNT’ 可用。

     3.7 版更變: 添加了 ‘TCP_NOTSENT_LOWAT’。

     在 Windows 上，如果 Windows 运行时支持，则 ‘TCP_KEEPIDLE’、
     ‘TCP_KEEPINTVL’ 可用。

 -- Data: socket.AF_CAN
 -- Data: socket.PF_CAN

 -- Data: SOL_CAN_*

 -- Data: CAN_*

     此列表内的许多常量，记载在 Linux 文档中，同时也定义在本 socket 模块
     中。

     *note 可用性: 1491.： Linux >= 2.6.25。

     3.3 版新加入.

 -- Data: socket.CAN_BCM

 -- Data: CAN_BCM_*

     CAN 协议簇内的 CAN_BCM 是广播管理器（Bbroadcast Manager – BCM）协议
     ，广播管理器常量在 Linux 文档中有所记载，在本 socket 模块中也有定义
     。

     *note 可用性: 1491.： Linux >= 2.6.25。

          備註: ‘CAN_BCM_CAN_FD_FRAME’ 旗标仅在 Linux >= 4.8 时可用。

     3.4 版新加入.

 -- Data: socket.CAN_RAW_FD_FRAMES

     在 CAN_RAW 套接字中启用 CAN FD 支持，默认是禁用的。它使应用程序可以
     发送 CAN 和 CAN FD 帧。但是，从套接字读取时，也必须同时接受 CAN 和
     CAN FD 帧。

     此常量在 Linux 文档中有所记载。

     *note 可用性: 1491.： Linux >= 3.6。

     3.5 版新加入.

 -- Data: socket.CAN_RAW_JOIN_FILTERS

     加入已应用的 CAN 过滤器，这样只有与所有 CAN 过滤器匹配的 CAN 帧才能
     传递到用户空间。

     此常量在 Linux 文档中有所记载。

     *note 可用性: 1491.： Linux >= 4.1。

     3.9 版新加入.

 -- Data: socket.CAN_ISOTP

     CAN 协议簇中的 CAN_ISOTP 就是 ISO-TP (ISO 15765-2) 协议。ISO-TP 常
     量在 Linux 文档中有所记载。

     *note 可用性: 1491.： Linux >= 2.6.25。

     3.7 版新加入.

 -- Data: socket.CAN_J1939

     CAN 协议族中的 CAN_J1939 即 SAE J1939 协议。 J1939 常量记录在 Linux
     文档中。

     *note 可用性: 1491.： Linux >= 5.4。

     3.9 版新加入.

 -- Data: socket.AF_PACKET
 -- Data: socket.PF_PACKET

 -- Data: PACKET_*

     此列表内的许多常量，记载在 Linux 文档中，同时也定义在本 socket 模块
     中。

     *note 可用性: 1491.： Linux >= 2.2。

 -- Data: socket.AF_RDS
 -- Data: socket.PF_RDS
 -- Data: socket.SOL_RDS

 -- Data: RDS_*

     此列表内的许多常量，记载在 Linux 文档中，同时也定义在本 socket 模块
     中。

     *note 可用性: 1491.： Linux >= 2.6.30。

     3.3 版新加入.

 -- Data: socket.SIO_RCVALL
 -- Data: socket.SIO_KEEPALIVE_VALS
 -- Data: socket.SIO_LOOPBACK_FAST_PATH

 -- Data: RCVALL_*

     Windows 的 WSAIoctl() 的常量。这些常量用于套接字对象的 *note
     ioctl(): 677. 方法的参数。

     3.6 版更變: 添加了 ‘SIO_LOOPBACK_FAST_PATH’。

 -- Data: TIPC_*

     TIPC 相关常量，与 C socket API 导出的常量一致。更多信息请参阅 TIPC
     文档。

 -- Data: socket.AF_ALG
 -- Data: socket.SOL_ALG

 -- Data: ALG_*

     用于 Linux 内核加密算法的常量。

     *note 可用性: 1491.： Linux >= 2.6.38。

     3.6 版新加入.

 -- Data: socket.AF_VSOCK
 -- Data: socket.IOCTL_VM_SOCKETS_GET_LOCAL_CID

 -- Data: VMADDR*

 -- Data: SO_VM*

     用于 Linux 宿主机/虚拟机通讯的常量。

     *note 可用性: 1491.： Linux >= 4.8。

     3.7 版新加入.

 -- Data: socket.AF_LINK

     *note Availability: 1491.: BSD, macOS.

     3.4 版新加入.

 -- Data: socket.has_ipv6

     本常量为一个布尔值，该值指示当前平台是否支持 IPv6。

 -- Data: socket.BDADDR_ANY
 -- Data: socket.BDADDR_LOCAL

     这些是字符串常量，包含蓝牙地址，这些地址具有特殊含义。例如，当用
     ‘BTPROTO_RFCOMM’ 指定绑定套接字时， *note BDADDR_ANY: 27cd. 表示“任
     何地址”。

 -- Data: socket.HCI_FILTER
 -- Data: socket.HCI_TIME_STAMP
 -- Data: socket.HCI_DATA_DIR

     与 ‘BTPROTO_HCI’ 一起使用。 *note HCI_FILTER: 27cf. 在 NetBSD 或
     DragonFlyBSD 上不可用。 *note HCI_TIME_STAMP: 27d0. 和 *note
     HCI_DATA_DIR: 27d1. 在 FreeBSD、NetBSD 或 DragonFlyBSD 上不可用。

 -- Data: socket.AF_QIPCRTR

     高通 IPC 路由协议的常数，用于与提供远程处理器的服务进行通信。

     *note 可用性: 1491.： Linux >= 4.7。

   ---------- Footnotes ----------

   (1) http://udrepper.livejournal.com/20407.html


File: python.info,  Node: 函数<6>,  Prev: 常数<6>,  Up: 模块内容<4>

5.18.2.5 函数
.............

* Menu:

* 创建套接字::
* 其他功能::


File: python.info,  Node: 创建套接字,  Next: 其他功能,  Up: 函数<6>

5.18.2.6 创建套接字
...................

下列函数都能创建 *note 套接字对象: 27d4.

 -- 類別: socket.socket (family=AF_INET, type=SOCK_STREAM, proto=0,
          fileno=None)

     使用给定的地址族、套接字类型和协议号创建一个新的套接字。 地址族应为
     *note AF_INET: 26f8. (默认值), *note AF_INET6: 26f9, *note AF_UNIX:
     26fe, *note AF_CAN: 27b5, *note AF_PACKET: 27b7. 或 *note AF_RDS:
     27c5. 之一。 套接字类型应为 *note SOCK_STREAM: d52. (默认值), *note
     SOCK_DGRAM: d51, *note SOCK_RAW: 27c0. 或其他可能的 ‘SOCK_’ 常量之
     一。 协议号通常为零并且可以省略，或在协议族为 *note AF_CAN: 27b5. 的
     情况下，协议应为 ‘CAN_RAW’, *note CAN_BCM: 9a0, *note CAN_ISOTP:
     27b6. 或 *note CAN_J1939: 1e3. 之一。

     如果指定了 `fileno'，那么将从这一指定的文件描述符中自动检测
     `family'、`type' 和 `proto' 的值。如果调用本函数时显式指定了
     `family'、`type' 或 `proto' 参数，可以覆盖自动检测的值。这只会影响
     Python 表示诸如 *note socket.getpeername(): 2741. 一类函数的返回值
     的方式，而不影响实际的操作系统资源。与 *note socket.fromfd(): 27d5.
     不同，`fileno' 将返回原先的套接字，而不是复制出新的套接字。这有助于
     在分离的套接字上调用 *note socket.close(): 4d7. 来关闭它。

     新创建的套接字是 *note 不可继承的: 8e7.。

     引发一个 *note 审计事件: fa1. ‘socket.__new__’ 附带参数 ‘self’、
     ‘family’、‘type’、‘protocol’。

     3.3 版更變: 添加了 AF_CAN 簇。添加了 AF_RDS 簇。

     3.4 版更變: 添加了 CAN_BCM 协议。

     3.4 版更變: 返回的套接字现在是不可继承的。

     3.7 版更變: 添加了 CAN_ISOTP 协议。

     3.7 版更變: 当将 *note SOCK_NONBLOCK: 590. 或 *note SOCK_CLOEXEC:
     591. 标志位应用于 `type' 上时，它们会被清除，且 *note socket.type:
     592. 反映不出它们。但它们仍将传递给底层系统的 ‘socket()’ 调用。因此
     ，

          sock = socket.socket(
              socket.AF_INET,
              socket.SOCK_STREAM | socket.SOCK_NONBLOCK)

     仍将在支持 ‘SOCK_NONBLOCK’ 的系统上创建一个非阻塞的套接字，但是
     ‘sock.type’ 会被置为 ‘socket.SOCK_STREAM’。

     3.9 版更變: 添加了 CAN_J1939 协议。

 -- 函式: socket.socketpair ([family[, type[, proto]]])

     构建一对已连接的套接字对象，使用给定的地址簇、套接字类型和协议号。
     地址簇、套接字类型和协议号与上述 ‘socket()’ 函数相同。默认地址簇为
     *note AF_UNIX: 26fe. （需要当前平台支持，不支持则默认为 *note
     AF_INET: 26f8. ）。

     新创建的套接字都是 *note 不可继承的: 8e7.。

     3.2 版更變: 现在，返回的套接字对象支持全部套接字 API，而不是全部
     API 的一个子集。

     3.4 版更變: 返回的套接字现在都是不可继承的。

     3.5 版更變: 添加了 Windows 支持。

 -- 函式: socket.create_connection (address[, timeout[,
          source_address]])

     连接到一个 TCP 服务，该服务正在侦听 Internet `address' （用二元组
     ‘(host, port)’ 表示）。连接后返回套接字对象。这是比 *note
     socket.connect(): 769. 更高级的函数：如果 `host' 是非数字主机名，它
     将尝试从 *note AF_INET: 26f8. 和 *note AF_INET6: 26f9. 解析它，然后
     依次尝试连接到所有可能的地址，直到连接成功。这使得编写兼容 IPv4 和
     IPv6 的客户端变得容易。

     传入可选参数 `timeout' 可以在套接字实例上设置超时（在尝试连接前）。
     如果未提供 `timeout'，则使用由 *note getdefaulttimeout(): 27d6. 返
     回的全局默认超时设置。

     如果提供了 `source_address'，它必须为二元组 ‘(host, port)’，以便套
     接字在连接之前绑定为其源地址。如果 host 或 port 分别为 ’’ 或 0，则
     使用操作系统默认行为。

     3.2 版更變: 添加了 `source_address'。

 -- 函式: socket.create_server (address, *, family=AF_INET,
          backlog=None, reuse_port=False, dualstack_ipv6=False)

     便捷函数，创建绑定到 `address' （二元组 ‘(host, port)’ ）的 TCP 套
     接字，返回套接字对象。

     `family' 应设置为 *note AF_INET: 26f8. 或 *note AF_INET6: 26f9.。
     `backlog' 是传递给 *note socket.listen(): 83a. 的队列大小，当它为
     ‘0’ 则表示默认的合理值。`reuse_port' 表示是否设置 ‘SO_REUSEPORT’ 套
     接字选项。

     如果 `dualstack_ipv6' 为 true 且平台支持，则套接字能接受 IPv4 和
     IPv6 连接，否则将抛出 *note ValueError: 16d. 异常。大多数 POSIX 平
     台和 Windows 应该支持此功能。启用此功能后，*note
     socket.getpeername(): 2741. 在进行 IPv4 连接时返回的地址将是一个（
     映射到 IPv4 的）IPv6 地址。在默认启用该功能的平台上（如 Linux），如
     果 `dualstack_ipv6' 为 false，即显式禁用此功能。该参数可以与 *note
     has_dualstack_ipv6(): 34c. 结合使用：

          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)

          備註: 在 POSIX 平台上，设置 ‘SO_REUSEADDR’ 套接字选项是为了立
          即重用以前绑定在同一 `address' 上并保持 TIME_WAIT 状态的套接字
          。

     3.8 版新加入.

 -- 函式: socket.has_dualstack_ipv6 ()

     如果平台支持创建 IPv4 和 IPv6 连接都可以处理的 TCP 套接字，则返回
     ‘True’。

     3.8 版新加入.

 -- 函式: socket.fromfd (fd, family, type, proto=0)

     复制文件描述符 `fd' （一个由文件对象的 ‘fileno()’ 方法返回的整数）
     ，然后从结果中构建一个套接字对象。地址簇、套接字类型和协议号与上述
     ‘socket()’ 函数相同。文件描述符应指向一个套接字，但不会专门去检查
     ——如果文件描述符是无效的，则对该对象的后续操作可能会失败。本函数很
     少用到，但是在将套接字作为标准输入或输出传递给程序（如 Unix inet 守
     护程序启动的服务器）时，可以使用本函数获取或设置套接字选项。套接字
     将处于阻塞模式。

     新创建的套接字是 *note 不可继承的: 8e7.。

     3.4 版更變: 返回的套接字现在是不可继承的。

 -- 函式: socket.fromshare (data)

     根据 *note socket.share(): 58d. 方法获得的数据实例化套接字。套接字
     将处于阻塞模式。

     *note 可用性: 1491.: Windows。

     3.3 版新加入.

 -- Data: socket.SocketType

     这是一个 Python 类型对象，表示套接字对象的类型。它等同于
     ‘type(socket(...))’。


File: python.info,  Node: 其他功能,  Prev: 创建套接字,  Up: 函数<6>

5.18.2.7 其他功能
.................

*note socket: ef. 模块还提供多种网络相关服务：

 -- 函式: socket.close (fd)

     关闭一个套接字文件描述符。它类似于 *note os.close(): 4d8.，但专用于
     套接字。在某些平台上（特别是在 Windows 上），*note os.close(): 4d8.
     对套接字文件描述符无效。

     3.7 版新加入.

 -- 函式: socket.getaddrinfo (host, port, family=0, type=0, proto=0,
          flags=0)

     将 `host'/`port' 参数转换为 5 元组的序列，其中包含创建（连接到某服
     务的）套接字所需的所有参数。`host' 是域名，是字符串格式的 IPv4/v6 地
     址或 ‘None’。`port' 是字符串格式的服务名称，如 ‘'http'’ 、端口号（
     数字）或 ‘None’。传入 ‘None’ 作为 `host' 和 `port' 的值，相当于将
     ‘NULL’ 传递给底层 C API。

     可以指定 `family'、`type' 和 `proto' 参数，以缩小返回的地址列表。向
     这些参数分别传入 0 表示保留全部结果范围。`flags' 参数可以是 ‘AI_*’
     常量中的一个或多个，它会影响结果的计算和返回。例如，
     ‘AI_NUMERICHOST’ 会禁用域名解析，此时如果 `host' 是域名，则会抛出错
     误。

     本函数返回一个列表，其中的 5 元组具有以下结构：

     ‘(family, type, proto, canonname, sockaddr)’

     在这些元组中，`family', `type', `proto' 都是整数且其作用是被传入
     ‘socket()’ 函数。 如果 ‘AI_CANONNAME’ 是 `flags' 参数的一部分则
     `canonname' 将是表示 `host' 规范名称的字符串；否则 `canonname' 将为
     空。 `sockaddr' 是一个描述套接字地址的元组，其具体格式取决于返回的
     `family' (对于 *note AF_INET: 26f8. 为 ‘(address, port)’ 2 元组，对
     于 *note AF_INET6: 26f9. 则为 ‘(address, port, flowinfo, scope_id)’
     4 元组)，其作用是被传入 *note socket.connect(): 769. 方法。

     引发一个 *note 审计事件: fa1. ‘socket.getaddrinfo’ 附带参数 ‘host’、
     ‘port’、‘family’、‘type’、‘protocol’。

     下面的示例获取了 TCP 连接地址信息，假设该连接通过 80 端口连接至
     ‘example.org’ （如果系统未启用 IPv6，则结果可能会不同）:

          >>> socket.getaddrinfo("example.org", 80, proto=socket.IPPROTO_TCP)
          [(<AddressFamily.AF_INET6: 10>, <SocketType.SOCK_STREAM: 1>,
           6, '', ('2606:2800:220:1:248:1893:25c8:1946', 80, 0, 0)),
           (<AddressFamily.AF_INET: 2>, <SocketType.SOCK_STREAM: 1>,
           6, '', ('93.184.216.34', 80))]

     3.2 版更變: 现在可以使用关键字参数的形式来传递参数。

     3.7 版更變: 对于 IPv6 多播地址，表示地址的字符串将不包含
     ‘%scope_id’ 部分。

 -- 函式: socket.getfqdn ([name])

     Return a fully qualified domain name for `name'.  If `name' is
     omitted or empty, it is interpreted as the local host.  To find the
     fully qualified name, the hostname returned by *note
     gethostbyaddr(): fad. is checked, followed by aliases for the host,
     if available.  The first name which includes a period is selected.
     In case no fully qualified domain name is available and `name' was
     provided, it is returned unchanged.  If `name' was empty or equal
     to ‘'0.0.0.0'’, the hostname from *note gethostname(): 2064. is
     returned.

 -- 函式: socket.gethostbyname (hostname)

     将主机名转换为 IPv4 地址格式。IPv4 地址以字符串格式返回，如
     ‘'100.50.200.5'’。如果主机名本身是 IPv4 地址，则原样返回。更完整的
     接口请参考 *note gethostbyname_ex(): fae.。 *note gethostbyname():
     27da. 不支持 IPv6 名称解析，应使用 *note getaddrinfo(): 270c. 来支
     持 IPv4/v6 双协议栈。

     引发一个 *note 审计事件: fa1. ‘socket.gethostbyname’，附带参数
     ‘hostname’。

 -- 函式: socket.gethostbyname_ex (hostname)

     Translate a host name to IPv4 address format, extended interface.
     Return a triple ‘(hostname, aliaslist, ipaddrlist)’ where
     `hostname' is the host’s primary host name, `aliaslist' is a
     (possibly empty) list of alternative host names for the same
     address, and `ipaddrlist' is a list of IPv4 addresses for the same
     interface on the same host (often but not always a single address).
     *note gethostbyname_ex(): fae. does not support IPv6 name
     resolution, and *note getaddrinfo(): 270c. should be used instead
     for IPv4/v6 dual stack support.

     引发一个 *note 审计事件: fa1. ‘socket.gethostbyname’，附带参数
     ‘hostname’。

 -- 函式: socket.gethostname ()

     返回一个字符串，包含当前正在运行 Python 解释器的机器的主机名。

     引发一个 *note 审计事件: fa1. ‘socket.gethostname’，没有附带参数。

     注意： *note gethostname(): 2064. 并不总是返回全限定域名，必要的话
     请使用 *note getfqdn(): 27d9.。

 -- 函式: socket.gethostbyaddr (ip_address)

     返回三元组 ‘(hostname, aliaslist, ipaddrlist)’，其中 `hostname' 是
     响应给定 `ip_address' 的主要主机名，`aliaslist' 是相同地址的其他可
     用主机名的列表（可能为空），而 `ipaddrlist' 是 IPv4/v6 地址列表，包
     含相同主机名、相同接口的不同地址（很可能仅包含一个地址）。要查询全
     限定域名，请使用函数 *note getfqdn(): 27d9.。*note gethostbyaddr():
     fad. 支持 IPv4 和 IPv6。

     引发一个 *note 审计事件: fa1. ‘socket.gethostbyaddr’，附带参数
     ‘ip_address’。

 -- 函式: socket.getnameinfo (sockaddr, flags)

     将套接字地址 `sockaddr' 转换为二元组 ‘(host, port)’。`host' 的形式
     可能是全限定域名，或是由数字表示的地址，具体取决于 `flags' 的设置。
     同样，`port' 可以包含字符串格式的端口名称或数字格式的端口号。

     对于 IPv6 地址，如果 `sockaddr' 包含有意义的 `scope_id'，则
     ‘%scope_id’ 会被附加到主机部分。 这种情况通常发生在多播地址上。

     关于 `flags' 的更多信息可参阅 ‘getnameinfo(3)’。

     引发一个 *note 审计事件: fa1. ‘socket.getnameinfo’，附带参数
     ‘sockaddr’。

 -- 函式: socket.getprotobyname (protocolname)

     将 Internet 协议名称（如 ‘'icmp'’ ）转换为常量，该常量适用于
     ‘socket()’ 函数的第三个（可选）参数。通常只有在 "raw" 模式 (*note
     SOCK_RAW: 27c0.) 中打开的套接字才需要使用该常量。在正常的套接字模式
     下，协议省略或为零时，会自动选择正确的协议。

 -- 函式: socket.getservbyname (servicename[, protocolname])

     将 Internet 服务名称和协议名称转换为该服务的端口号。协议名称是可选
     的，如果提供的话应为 ‘'tcp'’ 或 ‘'udp'’，否则将匹配出所有协议。

     引发一个 *note 审计事件: fa1. ‘socket.getservbyname’，附带参数
     ‘servicename’、‘protocolname’。

 -- 函式: socket.getservbyport (port[, protocolname])

     将 Internet 端口号和协议名称转换为该服务的服务名称。协议名称是可选
     的，如果提供的话应为 ‘'tcp'’ 或 ‘'udp'’，否则将匹配出所有协议。

     引发一个 *note 审计事件: fa1. ‘socket.getservbyport’，附带参数
     ‘port’、‘protocolname’。

 -- 函式: socket.ntohl (x)

     将 32 位正整数从网络字节序转换为主机字节序。在主机字节序与网络字节
     序相同的计算机上，这是一个空操作。字节序不同将执行 4 字节交换操作。

 -- 函式: socket.ntohs (x)

     将 16 位正整数从网络字节序转换为主机字节序。在主机字节序与网络字节
     序相同的计算机上，这是一个空操作。字节序不同将执行 2 字节交换操作。

     3.7 版後已棄用: 如果 `x' 不符合 16 位无符号整数，但符合 C 语言的正
     整数，则它会被静默截断为 16 位无符号整数。此静默截断功能已弃用，未
     来版本的 Python 将对此抛出异常。

 -- 函式: socket.htonl (x)

     将 32 位正整数从主机字节序转换为网络字节序。在主机字节序与网络字节
     序相同的计算机上，这是一个空操作。字节序不同将执行 4 字节交换操作。

 -- 函式: socket.htons (x)

     将 16 位正整数从主机字节序转换为网络字节序。在主机字节序与网络字节
     序相同的计算机上，这是一个空操作。字节序不同将执行 2 字节交换操作。

     3.7 版後已棄用: 如果 `x' 不符合 16 位无符号整数，但符合 C 语言的正
     整数，则它会被静默截断为 16 位无符号整数。此静默截断功能已弃用，未
     来版本的 Python 将对此抛出异常。

 -- 函式: socket.inet_aton (ip_string)

     将 IPv4 地址从点分十进制字符串格式（如 ’123.45.67.89’ ）转换为 32 位
     压缩二进制格式，转换后为字节对象，长度为四个字符。与那些使用标准 C
     库，且需要 ‘struct in_addr’ 类型的对象的程序交换信息时，本函数很有
     用。 该类型即本函数返回的 32 位压缩二进制的 C 类型。

     *note inet_aton(): 236. 也接受句点数少于三的字符串，详情请参阅 Unix
     手册 ‘inet(3)’。

     如果传入本函数的 IPv4 地址字符串无效，则抛出 *note OSError: 304.。
     注意，具体什么样的地址有效取决于 ‘inet_aton()’ 的底层 C 实现。

     *note inet_aton(): 236. 不支持 IPv6，在 IPv4/v6 双协议栈下应使用
     *note inet_pton(): 237. 来代替。

 -- 函式: socket.inet_ntoa (packed_ip)

     将 32 位压缩 IPv4 地址（一个 *note 类字节对象: 6df.，长 4 个字节）
     转换为标准的点分十进制字符串形式（如 ’123.45.67.89’ ）。与那些使用
     标准 C 库，且需要 ‘struct in_addr’ 类型的对象的程序交换信息时，本函
     数很有用。 该类型即本函数参数中的 32 位压缩二进制数据的 C 类型。

     如果传入本函数的字节序列长度不是 4 个字节，则抛出 *note OSError:
     304.。*note inet_ntoa(): 27e0. 不支持 IPv6，在 IPv4/v6 双协议栈下应
     使用 *note inet_ntop(): 9a2. 来代替。

     3.5 版更變: 现在支持可写的 *note 字节类对象: 6df.。

 -- 函式: socket.inet_pton (address_family, ip_string)

     将特定地址簇的 IP 地址（字符串）转换为压缩二进制格式。当库或网络协
     议需要接受 ‘struct in_addr’ 类型的对象（类似 *note inet_aton():
     236. ）或 ‘struct in6_addr’ 类型的对象时，*note inet_pton(): 237. 很
     有用。

     目前 `address_family' 支持 *note AF_INET: 26f8. 和 *note AF_INET6:
     26f9.。如果 IP 地址字符串 `ip_string' 无效，则抛出 *note OSError:
     304.。注意，具体什么地址有效取决于 `address_family' 的值和
     ‘inet_pton()’ 的底层实现。

     *note 可用性: 1491.： Unix（可能非所有平台都可用）、Windows。

     3.4 版更變: 添加了 Windows 支持

 -- 函式: socket.inet_ntop (address_family, packed_ip)

     将压缩 IP 地址（一个 *note 类字节对象: 6df.，数个字节长）转换为标准
     的、特定地址簇的字符串形式（如 ‘'7.10.0.5'’ 或 ‘'5aef:2b::8'’ ）。
     当库或网络协议返回 ‘struct in_addr’ 类型的对象（类似 *note
     inet_ntoa(): 27e0. ）或 ‘struct in6_addr’ 类型的对象时，*note
     inet_ntop(): 9a2. 很有用。

     目前 `address_family' 支持 *note AF_INET: 26f8. 和 *note AF_INET6:
     26f9.。如果字节对象 `packed_ip' 与指定的地址簇长度不符，则抛出
     *note ValueError: 16d.。针对 *note inet_ntop(): 9a2. 调用的错误则抛
     出 *note OSError: 304.。

     *note 可用性: 1491.： Unix（可能非所有平台都可用）、Windows。

     3.4 版更變: 添加了 Windows 支持

     3.5 版更變: 现在支持可写的 *note 字节类对象: 6df.。

 -- 函式: socket.CMSG_LEN (length)

     返回给定 `length' 所关联数据的辅助数据项的总长度（不带尾部填充）。
     此值通常用作 *note recvmsg(): 76c. 接收一个辅助数据项的缓冲区大小，
     但是 RFC 3542(1) 要求可移植应用程序使用 *note CMSG_SPACE(): 1158.，
     以此将尾部填充的空间计入，即使该项在缓冲区的最后。如果 `length' 超
     出允许范围，则抛出 *note OverflowError: a41.。

     *note 可用性: 1491.： 大多数 Unix 平台，其他平台也可能可用。

     3.3 版新加入.

 -- 函式: socket.CMSG_SPACE (length)

     返回 *note recvmsg(): 76c. 所需的缓冲区大小，以接收给定 `length' 所
     关联数据的辅助数据项，带有尾部填充。接收多个项目所需的缓冲区空间是
     关联数据长度的 *note CMSG_SPACE(): 1158. 值的总和。如果 `length' 超
     出允许范围，则抛出 *note OverflowError: a41.。

     请注意，某些系统可能支持辅助数据，但不提供本函数。还需注意，如果使
     用本函数的结果来设置缓冲区大小，可能无法精确限制可接收的辅助数据量
     ，因为可能会有其他数据写入尾部填充区域。

     *note 可用性: 1491.： 大多数 Unix 平台，其他平台也可能可用。

     3.3 版新加入.

 -- 函式: socket.getdefaulttimeout ()

     返回用于新套接字对象的默认超时（以秒为单位的浮点数）。值 ‘None’ 表
     示新套接字对象没有超时。首次导入 socket 模块时，默认值为 ‘None’。

 -- 函式: socket.setdefaulttimeout (timeout)

     设置用于新套接字对象的默认超时（以秒为单位的浮点数）。首次导入
     socket 模块时，默认值为 ‘None’。可能的取值及其各自的含义请参阅
     *note settimeout(): 27b9.。

 -- 函式: socket.sethostname (name)

     将计算机的主机名设置为 `name'。如果权限不足将抛出 *note OSError:
     304.。

     引发一个 *note 审计事件: fa1. ‘socket.sethostname’，附带参数
     ‘name’。

     *note Availability: 1491.: Unix.

     3.3 版新加入.

 -- 函式: socket.if_nameindex ()

     返回一个列表，包含网络接口（网卡）信息二元组（整数索引，名称字符串
     ）。系统调用失败则抛出 *note OSError: 304.。

     *note 可用性: 1491.: Unix, Windows。

     3.3 版新加入.

     3.8 版更變: 添加了 Windows 支持。

          備註: 在 Windows 中网络接口在不同上下文中具有不同的名称（所有
          名称见对应示例）:

             * UUID: ‘{FB605B73-AAC2-49A6-9A2F-25416AEA0573}’

             * 名称: ‘ethernet_32770’

             * 友好名称: ‘vEthernet (nat)’

             * 描述: ‘Hyper-V Virtual Ethernet Adapter’

          此函数返回列表中第二种形式的名称，在此示例中为
          ‘ethernet_32770’。

 -- 函式: socket.if_nametoindex (if_name)

     返回网络接口名称相对应的索引号。如果没有所给名称的接口，则抛出
     *note OSError: 304.。

     *note 可用性: 1491.: Unix, Windows。

     3.3 版新加入.

     3.8 版更變: 添加了 Windows 支持。

     也參考
     ......

     "Interface name" 为 *note if_nameindex(): 34d. 中所描述的名称。

 -- 函式: socket.if_indextoname (if_index)

     返回网络接口索引号相对应的接口名称。如果没有所给索引号的接口，则抛
     出 *note OSError: 304.。

     *note 可用性: 1491.: Unix, Windows。

     3.3 版新加入.

     3.8 版更變: 添加了 Windows 支持。

     也參考
     ......

     "Interface name" 为 *note if_nameindex(): 34d. 中所描述的名称。

 -- 函式: socket.send_fds (sock, buffers, fds[, flags[, address]])

     将文件描述符列表 `fds' 通过一个 *note AF_UNIX: 26fe. 套接字 `sock'
     进行发送。 `fds' 形参是由文件描述符构成的序列。 请查看 ‘sendmsg()’
     获取这些形参的文档。

     *note 可用性: 1491.: 支持 *note sendmsg(): 76f. 和 ‘SCM_RIGHTS’ 机
     制的 Unix 系统。

     3.9 版新加入.

 -- 函式: socket.recv_fds (sock, bufsize, maxfds[, flags])

     接收至多 `maxfds' 个来自 *note AF_UNIX: 26fe. 套接字 `sock' 的文件
     描述符。 返回 ‘(msg, list(fds), flags, addr)’。 请查看 ‘recvmsg()’
     获取有些形参的文档。

     *note 可用性: 1491.: 支持 *note recvmsg(): 76c. 和 ‘SCM_RIGHTS’ 机
     制的 Unix 系统。

     3.9 版新加入.

          備註: 位于文件描述符列表末尾的任何被截断整数。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc3542.html


File: python.info,  Node: 套接字对象,  Next: 关于套接字超时的说明,  Prev: 模块内容<4>,  Up: socket --- 底层网络接口

5.18.2.8 套接字对象
...................

套接字对象具有以下方法。除了 *note makefile(): bec.，其他都与套接字专用
的 Unix 系统调用相对应。

3.2 版更變: 添加了对 *note 上下文管理器: 661. 协议的支持。退出上下文管理
器与调用 *note close(): 4d7. 等效。

 -- 成員函式: socket.accept ()

     接受一个连接。此 socket 必须绑定到一个地址上并且监听连接。返回值是
     一个 ‘(conn, address)’ 对，其中 `conn' 是一个 `新' 的套接字对象，用
     于在此连接上收发数据，`address' 是连接另一端的套接字所绑定的地址。

     新创建的套接字是 *note 不可继承的: 8e7.。

     3.4 版更變: 该套接字现在是不可继承的。

     3.5 版更變: 如果系统调用被中断，但信号处理程序没有触发异常，此方法
     现在会重试系统调用，而不是触发 *note InterruptedError: 74c. 异常 (原
     因详见 PEP 475(1))。

 -- 成員函式: socket.bind (address)

     将套接字绑定到 `address'。套接字必须尚未绑定。（ `address' 的格式取
     决于地址簇 —— 参见上文）

     引发一个 *note 审计事件: fa1. ‘socket.bind’，附带参数 ‘self’、
     ‘address’。

 -- 成員函式: socket.close ()

     将套接字标记为关闭。当 *note makefile(): bec. 创建的所有文件对象都
     关闭时，底层系统资源（如文件描述符）也将关闭。一旦上述情况发生，将
     来对套接字对象的所有操作都会失败。对端将接收不到任何数据（清空队列
     数据后）。

     垃圾回收时，套接字会自动关闭，但建议显式 *note close(): 4d7. 它们，
     或在它们周围使用 *note with: 7da. 语句。

     3.6 版更變: 现在，如果底层的 ‘close()’ 调用出错，会抛出 *note
     OSError: 304.。

          備註: *note close(): 4d7. 释放与连接相关联的资源，但不一定立即
          关闭连接。如果需要及时关闭连接，请在调用 *note close(): 4d7. 之
          前调用 *note shutdown(): 27e3.。

 -- 成員函式: socket.connect (address)

     连接到 `address' 处的远程套接字。（ `address' 的格式取决于地址簇 ——
     参见上文）

     如果连接被信号中断，则本方法将等待，直到连接完成。如果信号处理程序
     未抛出异常，且套接字阻塞中或已超时，则在超时后抛出 *note
     socket.timeout: cd9.。对于非阻塞套接字，如果连接被信号中断，则本方
     法将抛出 *note InterruptedError: 74c. 异常（或信号处理程序抛出的异
     常）。

     引发一个 *note 审计事件: fa1. ‘socket.connect’，附带参数 ‘self’、
     ‘address’。

     3.5 版更變: 本方法现在将等待，直到连接完成，而不是在以下情况抛出
     *note InterruptedError: 74c. 异常。该情况为，连接被信号中断，信号处
     理程序未抛出异常，且套接字阻塞中或已超时（具体解释请参阅 PEP 475(2)
     ）。

 -- 成員函式: socket.connect_ex (address)

     类似于 ‘connect(address)’，但是对于 C 级别的 ‘connect()’ 调用返回的
     错误，本函数将返回错误指示器，而不是抛出异常（对于其他问题，如“找不
     到主机”，仍然可以抛出异常）。如果操作成功，则错误指示器为 ‘0’，否则
     为 ‘errno’ 变量的值。这对支持如异步连接很有用。

     引发一个 *note 审计事件: fa1. ‘socket.connect’，附带参数 ‘self’、
     ‘address’。

 -- 成員函式: socket.detach ()

     将套接字对象置于关闭状态，而底层的文件描述符实际并不关闭。返回该文
     件描述符，使其可以重新用于其他目的。

     3.2 版新加入.

 -- 成員函式: socket.dup ()

     创建套接字的副本。

     新创建的套接字是 *note 不可继承的: 8e7.。

     3.4 版更變: 该套接字现在是不可继承的。

 -- 成員函式: socket.fileno ()

     返回套接字的文件描述符（一个小整数），失败返回 -1。配合 *note
     select.select(): 766. 使用很有用。

     在 Windows 下，此方法返回的小整数在允许使用文件描述符的地方无法使用
     （如 *note os.fdopen(): 1564. ）。Unix 无此限制。

 -- 成員函式: socket.get_inheritable ()

     获取套接字文件描述符或套接字句柄的 *note 可继承标志: 8e7. ：如果子
     进程可以继承套接字则为 ‘True’，否则为 ‘False’。

     3.4 版新加入.

 -- 成員函式: socket.getpeername ()

     返回套接字连接到的远程地址。举例而言，这可以用于查找远程 IPv4/v6 套
     接字的端口号。（返回的地址格式取决于地址簇 —— 参见上文。）部分系统
     不支持此函数。

 -- 成員函式: socket.getsockname ()

     返回套接字本身的地址。举例而言，这可以用于查找 IPv4/v6 套接字的端口
     号。（返回的地址格式取决于地址簇 —— 参见上文。）

 -- 成員函式: socket.getsockopt (level, optname[, buflen])

     返回指定套接字选项的值（参阅 Unix 手册页 ‘getsockopt(2)’ ）。所需的
     符号常量（ ‘SO_*’ 等）已定义在本模块中。如果未指定 `buflen'，则认为
     该选项值为整数，由本函数返回该整数值。如果指定 `buflen'，则它定义了
     用于存放选项值的缓冲区的最大长度，且该缓冲区将作为字节对象返回。对
     缓冲区的解码工作由调用者自行完成（针对编码为字节串的 C 结构，其解码
     方法请参阅可选的内置模块 *note struct: f8. ）。

 -- 成員函式: socket.getblocking ()

     如果套接字处于阻塞模式，返回 ‘True’，非阻塞模式返回 ‘False’。

     这相当于检测 ‘socket.gettimeout() == 0’。

     3.7 版新加入.

 -- 成員函式: socket.gettimeout ()

     返回套接字操作相关的超时秒数（浮点数），未设置超时则返回 ‘None’。它
     反映最后一次调用 *note setblocking(): 206f. 或 *note settimeout():
     27b9. 后的设置。

 -- 成員函式: socket.ioctl (control, option)


     平台: Windows

     *note ioctl(): 677. 方法是 WSAIoctl 系统接口的有限接口。请参考
     Win32 文档(3) 以获取更多信息。

     在其他平台上，可以使用通用的 *note fcntl.fcntl(): 27e8. 和 *note
     fcntl.ioctl(): ea2. 函数，它们接受套接字对象作为第一个参数。

     当前仅支持以下控制码： ‘SIO_RCVALL’、‘SIO_KEEPALIVE_VALS’ 和
     ‘SIO_LOOPBACK_FAST_PATH’。

     3.6 版更變: 添加了 ‘SIO_LOOPBACK_FAST_PATH’。

 -- 成員函式: socket.listen ([backlog])

     启动一个服务器用于接受连接。如果指定 `backlog'，则它最低为 0（小于
     0 会被置为 0），它指定系统允许暂未 accept 的连接数，超过后将拒绝新
     连接。未指定则自动设为合理的默认值。

     3.5 版更變: `backlog' 参数现在是可选的。

 -- 成員函式: socket.makefile (mode='r', buffering=None, *,
          encoding=None, errors=None, newline=None)

     返回与套接字关联的 *note 文件对象: c14.。返回的对象的具体类型取决于
     *note makefile(): bec. 的参数。这些参数的解释方式与内置的 *note
     open(): 16f. 函数相同，其中 `mode' 的值仅支持 ‘'r'’ （默认），‘'w'’
     和 ‘'b'’。

     套接字必须处于阻塞模式，它可以有超时，但是如果发生超时，文件对象的
     内部缓冲区可能会以不一致的状态结尾。

     关闭 *note makefile(): bec. 返回的文件对象不会关闭原始套接字，除非
     所有其他文件对象都已关闭且在套接字对象上调用了 *note
     socket.close(): 4d7.。

          備註: 在 Windows 上，由 *note makefile(): bec. 创建的文件类对
          象无法作为带文件描述符的文件对象使用，如无法作为 *note
          subprocess.Popen(): 3db. 的流参数。

 -- 成員函式: socket.recv (bufsize[, flags])

     从套接字接收数据。返回值是一个字节对象，表示接收到的数据。`bufsize'
     指定一次接收的最大数据量。可选参数 `flags' 的含义请参阅 Unix 手册页
     ‘recv(2)’，它默认为零。

          備註: 为了最佳匹配硬件和网络的实际情况，`bufsize' 的值应为 2 的
          相对较小的幂，如 4096。

     3.5 版更變: 如果系统调用被中断，但信号处理程序没有触发异常，此方法
     现在会重试系统调用，而不是触发 *note InterruptedError: 74c. 异常 (原
     因详见 PEP 475(4))。

 -- 成員函式: socket.recvfrom (bufsize[, flags])

     从套接字接收数据。返回值是一对 ‘(bytes, address)’，其中 `bytes' 是
     字节对象，表示接收到的数据，`address' 是发送端套接字的地址。可选参
     数 `flags' 的含义请参阅 Unix 手册页 ‘recv(2)’，它默认为零。（
     `address' 的格式取决于地址簇 —— 参见上文）

     3.5 版更變: 如果系统调用被中断，但信号处理程序没有触发异常，此方法
     现在会重试系统调用，而不是触发 *note InterruptedError: 74c. 异常 (原
     因详见 PEP 475(5))。

     3.7 版更變: 对于多播 IPv6 地址，`address' 的第一项不会再包含
     ‘%scope_id’ 部分。 要获得完整的 IPv6 地址请使用 *note
     getnameinfo(): 270d.。

 -- 成員函式: socket.recvmsg (bufsize[, ancbufsize[, flags]])

     从套接字接收普通数据（至多 `bufsize' 字节）和辅助数据。`ancbufsize'
     参数设置用于接收辅助数据的内部缓冲区的大小（以字节为单位），默认为
     0，表示不接收辅助数据。可以使用 *note CMSG_SPACE(): 1158. 或 *note
     CMSG_LEN(): 1159. 计算辅助数据缓冲区的合适大小，无法放入缓冲区的项
     目可能会被截断或丢弃。`flags' 参数默认为 0，其含义与 *note recv():
     76a. 中的相同。

     返回值是一个四元组： ‘(data, ancdata, msg_flags, address)’。`data'
     项是一个 *note bytes: 172. 对象，用于保存接收到的非辅助数据。
     `ancdata' 项是零个或多个元组 ‘(cmsg_level, cmsg_type, cmsg_data)’ 组
     成的列表，表示接收到的辅助数据（控制消息）：`cmsg_level' 和
     `cmsg_type' 是分别表示协议级别和协议类型的整数，而 `cmsg_data' 是保
     存相关数据的 *note bytes: 172. 对象。`msg_flags' 项由各种标志按位或
     组成，表示接收消息的情况，详细信息请参阅系统文档。如果接收端套接字
     断开连接，则 `address' 是发送端套接字的地址（如果有），否则该值无指
     定。

     某些系统上可以利用 *note AF_UNIX: 26fe. 套接字通过 *note sendmsg():
     76f. 和 *note recvmsg(): 76c. 在进程之间传递文件描述符。使用此功能
     时（通常仅限于 *note SOCK_STREAM: d52. 套接字），*note recvmsg():
     76c. 将在其辅助数据中返回以下格式的项 ‘(socket.SOL_SOCKET,
     socket.SCM_RIGHTS, fds)’，其中 `fds' 是一个 *note bytes: 172. 对象
     ，是新文件描述符表示为原生 C ‘int’ 类型的二进制数组。如果 *note
     recvmsg(): 76c. 在系统调用返回后抛出异常，它将首先关闭此机制接收到
     的所有文件描述符。

     对于仅接收到一部分的辅助数据项，一些系统没有指示其截断长度。如果某
     个项目可能超出了缓冲区的末尾，*note recvmsg(): 76c. 将发出 *note
     RuntimeWarning: 3e2.，并返回其在缓冲区内的部分，前提是该对象被截断
     于关联数据开始后。

     在支持 ‘SCM_RIGHTS’ 机制的系统上，下方的函数将最多接收 `maxfds' 个
     文件描述符，返回消息数据和包含描述符的列表（同时忽略意外情况，如接
     收到无关的控制消息）。另请参阅 *note sendmsg(): 76f.。

          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)

     *note 可用性: 1491.： 大多数 Unix 平台，其他平台也可能可用。

     3.3 版新加入.

     3.5 版更變: 如果系统调用被中断，但信号处理程序没有触发异常，此方法
     现在会重试系统调用，而不是触发 *note InterruptedError: 74c. 异常 (原
     因详见 PEP 475(6))。

 -- 成員函式: socket.recvmsg_into (buffers[, ancbufsize[, flags]])

     从套接字接收普通数据和辅助数据，其行为与 *note recvmsg(): 76c. 相同
     ，但将非辅助数据分散到一系列缓冲区中，而不是返回新的字节对象。
     `buffers' 参数必须是可迭代对象，它迭代出可供写入的缓冲区（如 *note
     bytearray: 173. 对象），这些缓冲区将被连续的非辅助数据块填充，直到
     数据全部写完或缓冲区用完为止。在允许使用的缓冲区数量上，操作系统可
     能会有限制（ *note sysconf(): 2094. 的 ‘SC_IOV_MAX’ 值）。
     `ancbufsize' 和 `flags' 参数的含义与 *note recvmsg(): 76c. 中的相同
     。

     返回值为四元组： ‘(nbytes, ancdata, msg_flags, address)’，其中
     `nbytes' 是写入缓冲区的非辅助数据的字节总数，而 `ancdata'、
     `msg_flags' 和 `address' 与 *note recvmsg(): 76c. 中的相同。

     示例:

          >>> 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---')]

     *note 可用性: 1491.： 大多数 Unix 平台，其他平台也可能可用。

     3.3 版新加入.

 -- 成員函式: socket.recvfrom_into (buffer[, nbytes[, flags]])

     从套接字接收数据，将其写入 `buffer' 而不是创建新的字节串。返回值是
     一对 ‘(nbytes, address)’，其中 `nbytes' 是收到的字节数，`address' 是
     发送端套接字的地址。可选参数 `flags' 的含义请参阅 Unix 手册页
     ‘recv(2)’，它默认为零。（ `address' 的格式取决于地址簇 —— 参见上文
     ）

 -- 成員函式: socket.recv_into (buffer[, nbytes[, flags]])

     从套接字接收至多 `nbytes' 个字节，将其写入缓冲区而不是创建新的字节
     串。如果 `nbytes' 未指定（或指定为 0），则接收至所给缓冲区的最大可
     用大小。返回接收到的字节数。可选参数 `flags' 的含义请参阅 Unix 手册
     页 ‘recv(2)’，它默认为零。

 -- 成員函式: socket.send (bytes[, flags])

     发送数据给套接字。本套接字必须已连接到远程套接字。可选参数
     `flags' 的含义与上述 *note recv(): 76a. 中的相同。本方法返回已发送
     的字节数。应用程序要负责检查所有数据是否已发送，如果仅传输了部分数
     据，程序需要自行尝试传输其余数据。有关该主题的更多信息，请参考
     *note 套接字编程指南: 27e9.。

     3.5 版更變: 如果系统调用被中断，但信号处理程序没有触发异常，此方法
     现在会重试系统调用，而不是触发 *note InterruptedError: 74c. 异常 (原
     因详见 PEP 475(7))。

 -- 成員函式: socket.sendall (bytes[, flags])

     发送数据给套接字。本套接字必须已连接到远程套接字。可选参数 `flags'
     的含义与上述 *note recv(): 76a. 中的相同。与 *note send(): 76d. 不
     同，本方法持续从 `bytes' 发送数据，直到所有数据都已发送或发生错误为
     止。成功后会返回 ‘None’。出错后会抛出一个异常，此时并没有办法确定成
     功发送了多少数据。

     3.5 版更變: 每次成功发送数据后，套接字超时不再重置。现在，套接字超
     时是发送所有数据的最大总持续时间。

     3.5 版更變: 如果系统调用被中断，但信号处理程序没有触发异常，此方法
     现在会重试系统调用，而不是触发 *note InterruptedError: 74c. 异常 (原
     因详见 PEP 475(8))。

 -- 成員函式: socket.sendto (bytes, address)

 -- 成員函式: socket.sendto (bytes, flags, address)

     发送数据给套接字。本套接字不应连接到远程套接字，而应由 `address' 指
     定目标套接字。可选参数 `flags' 的含义与上述 *note recv(): 76a. 中的
     相同。本方法返回已发送的字节数。（ `address' 的格式取决于地址簇 ——
     参见上文。）

     引发一个 *note 审计事件: fa1. ‘socket.sendto’，附带参数 ‘self’、
     ‘address’。

     3.5 版更變: 如果系统调用被中断，但信号处理程序没有触发异常，此方法
     现在会重试系统调用，而不是触发 *note InterruptedError: 74c. 异常 (原
     因详见 PEP 475(9))。

 -- 成員函式: socket.sendmsg (buffers[, ancdata[, flags[, address]]])

     将普通数据和辅助数据发送给套接字，将从一系列缓冲区中收集非辅助数据
     ，并将其拼接为一条消息。`buffers' 参数指定的非辅助数据应为可迭代的
     *note 字节类对象: 6df. （如 *note bytes: 172. 对象），在允许使用的
     缓冲区数量上，操作系统可能会有限制（ *note sysconf(): 2094. 的
     ‘SC_IOV_MAX’ 值）。`ancdata' 参数指定的辅助数据（控制消息）应为可迭
     代对象，迭代出零个或多个 ‘(cmsg_level, cmsg_type, cmsg_data)’ 元组
     ，其中 `cmsg_level' 和 `cmsg_type' 是分别指定协议级别和协议类型的整
     数，而 `cmsg_data' 是保存相关数据的字节类对象。请注意，某些系统（特
     别是没有 *note CMSG_SPACE(): 1158. 的系统）可能每次调用仅支持发送一
     条控制消息。`flags' 参数默认为 0，与 *note send(): 76d. 中的含义相
     同。如果 `address' 指定为除 ‘None’ 以外的值，它将作为消息的目标地址
     。返回值是已发送的非辅助数据的字节数。

     在支持 ‘SCM_RIGHTS’ 机制的系统上，下方的函数通过一个 *note AF_UNIX:
     26fe. 套接字来发送文件描述符列表 `fds'。另请参阅 *note recvmsg():
     76c.。

          import socket, array

          def send_fds(sock, msg, fds):
              return sock.sendmsg([msg], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", fds))])

     *note 可用性: 1491.： 大多数 Unix 平台，其他平台也可能可用。

     引发一个 *note 审计事件: fa1. ‘socket.sendmsg’，附带参数 ‘self’、
     ‘address’。

     3.3 版新加入.

     3.5 版更變: 如果系统调用被中断，但信号处理程序没有触发异常，此方法
     现在会重试系统调用，而不是触发 *note InterruptedError: 74c. 异常 (原
     因详见 PEP 475(10))。

 -- 成員函式: socket.sendmsg_afalg ([msg], *, op[, iv[, assoclen[,
          flags]]])

     为 *note AF_ALG: 67b. 套接字定制的 *note sendmsg(): 76f. 版本。可为
     *note AF_ALG: 67b. 套接字设置模式、IV、AEAD 关联数据的长度和标志位
     。

     *note 可用性: 1491.： Linux >= 2.6.38。

     3.6 版新加入.

 -- 成員函式: socket.sendfile (file, offset=0, count=None)

     使用高性能的 *note os.sendfile: 461. 发送文件，直到达到文件的 EOF 为
     止，返回已发送的字节总数。`file' 必须是一个以二进制模式打开的常规文
     件对象。如果 *note os.sendfile: 461. 不可用（如 Windows）或 `file'
     不是常规文件，将使用 *note send(): 76d. 代替。`offset' 指示从哪里开
     始读取文件。如果指定了 `count'，它确定了要发送的字节总数，而不会持
     续发送直到达到文件的 EOF。返回时或发生错误时，文件位置将更新，在这
     种情况下，*note file.tell(): 1efc. 可用于确定已发送的字节数。套接字
     必须为 *note SOCK_STREAM: d52. 类型。不支持非阻塞的套接字。

     3.5 版新加入.

 -- 成員函式: socket.set_inheritable (inheritable)

     设置套接字文件描述符或套接字句柄的 *note 可继承标志: 8e7.。

     3.4 版新加入.

 -- 成員函式: socket.setblocking (flag)

     设置套接字为阻塞或非阻塞模式：如果 `flag' 为 false，则将套接字设置
     为非阻塞，否则设置为阻塞。

     本方法是某些 *note settimeout(): 27b9. 调用的简写：

        * ‘sock.setblocking(True)’ 相当于 ‘sock.settimeout(None)’

        * ‘sock.setblocking(False)’ 相当于 ‘sock.settimeout(0.0)’

     3.7 版更變: 本方法不再对 *note socket.type: 592. 属性设置 *note
     SOCK_NONBLOCK: 590. 标志。

 -- 成員函式: socket.settimeout (value)

     为阻塞套接字的操作设置超时。`value' 参数可以是非负浮点数，表示秒，
     也可以是 ‘None’。如果赋为一个非零值，那么如果在操作完成前超过了超时
     时间 `value'，后续的套接字操作将抛出 *note timeout: cd9. 异常。如果
     赋为 0，则套接字将处于非阻塞模式。如果指定为 ‘None’，则套接字将处于
     阻塞模式。

     更多信息请查阅 *note 关于套接字超时的说明: 27ea.。

     3.7 版更變: 本方法不再修改 *note socket.type: 592. 属性的 *note
     SOCK_NONBLOCK: 590. 标志。

 -- 成員函式: socket.setsockopt (level, optname, value: int)

 -- 成員函式: socket.setsockopt (level, optname, value: buffer)

 -- 成員函式: socket.setsockopt (level, optname, None, optlen: int)

     设置给定套接字选项的值（参阅 Unix 手册页 ‘setsockopt(2)’ ）。所需的
     符号常量（ ‘SO_*’ 等）已定义在本 *note socket: ef. 模块中。该值可以
     是整数、‘None’ 或表示缓冲区的 *note 字节类对象: 6df.。在后一种情况
     下，由调用者确保字节串中包含正确的数据位（关于将 C 结构体编码为字节
     串的方法，请参阅可选的内置模块 *note struct: f8. ）。当 `value' 设
     置为 ‘None’ 时，必须设置 `optlen' 参数。这相当于调用 ‘setsockopt()’
     C 函数时使用了 ‘optval=NULL’ 和 ‘optlen=optlen’ 参数。

     3.5 版更變: 现在支持可写的 *note 字节类对象: 6df.。

     3.6 版更變: 添加了 setsockopt(level, optname, None, optlen: int) 调
     用形式。

 -- 成員函式: socket.shutdown (how)

     关闭一半或全部的连接。如果 `how' 为 ‘SHUT_RD’，则后续不再允许接收。
     如果 `how' 为 ‘SHUT_WR’，则后续不再允许发送。如果 `how' 为
     ‘SHUT_RDWR’，则后续的发送和接收都不允许。

 -- 成員函式: socket.share (process_id)

     复制套接字，并准备将其与目标进程共享。目标进程必须以 `process_id' 形
     式提供。然后可以利用某种形式的进程间通信，将返回的字节对象传递给目
     标进程，还可以使用 *note fromshare(): 58e. 在新进程中重新创建套接字
     。一旦本方法调用完毕，就可以安全地将套接字关闭，因为操作系统已经为
     目标进程复制了该套接字。

     *note 可用性: 1491.: Windows。

     3.3 版新加入.

注意此处没有 ‘read()’ 或 ‘write()’ 方法，请使用不带 `flags' 参数的 *note
recv(): 76a. 和 *note send(): 76d. 来替代。

套接字对象还具有以下（只读）属性，这些属性与传入 *note socket: 767. 构造
函数的值相对应。

 -- 屬性: socket.family

     套接字的协议簇。

 -- 屬性: socket.type

     套接字的类型。

 -- 屬性: socket.proto

     套接字的协议。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0475

   (2) https://www.python.org/dev/peps/pep-0475

   (3) https://msdn.microsoft.com/en-us/library/ms741621%28VS.85%29.aspx

   (4) https://www.python.org/dev/peps/pep-0475

   (5) https://www.python.org/dev/peps/pep-0475

   (6) https://www.python.org/dev/peps/pep-0475

   (7) https://www.python.org/dev/peps/pep-0475

   (8) https://www.python.org/dev/peps/pep-0475

   (9) https://www.python.org/dev/peps/pep-0475

   (10) https://www.python.org/dev/peps/pep-0475


File: python.info,  Node: 关于套接字超时的说明,  Next: 示例<23>,  Prev: 套接字对象,  Up: socket --- 底层网络接口

5.18.2.9 关于套接字超时的说明
.............................

一个套接字对象可以处于以下三种模式之一：阻塞、非阻塞或超时。套接字默认以
阻塞模式创建，但是可以调用 *note setdefaulttimeout(): 27be. 来更改。

   * 在 `blocking mode' （阻塞模式）中，操作将阻塞，直到操作完成或系统返
     回错误（如连接超时）。

   * 在 `non-blocking mode' （非阻塞模式）中，如果操作无法立即完成，则操
     作将失败（不幸的是，不同系统返回的错误不同）：位于 *note select:
     e5. 中的函数可用于了解套接字何时以及是否可以读取或写入。

   * 在 `timeout mode' （超时模式）下，如果无法在指定的超时内完成操作（
     抛出 *note timeout: cd9. 异常），或如果系统返回错误，则操作将失败。

     備註: 在操作系统层面上，`超时模式' 下的套接字在内部都设置为非阻塞模
     式。同时，阻塞和超时模式在文件描述符和套接字对象之间共享，这些描述
     符和对象均应指向同一个网络端点。如果，比如你决定使用套接字的 *note
     fileno(): 27e6.，这一实现细节可能导致明显的结果。

* Menu:

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


File: python.info,  Node: 超时与 connect 方法,  Next: 超时与 accept 方法,  Up: 关于套接字超时的说明

5.18.2.10 超时与 ‘connect’ 方法
...............................

*note connect(): 769. 操作也受超时设置的约束，通常建议在调用 *note
connect(): 769. 之前调用 *note settimeout(): 27b9.，或将超时参数直接传递
给 *note create_connection(): c6f.。但是，无论 Python 套接字超时设置如何
，系统网络栈都有可能返回自带的连接超时错误。


File: python.info,  Node: 超时与 accept 方法,  Prev: 超时与 connect 方法,  Up: 关于套接字超时的说明

5.18.2.11 超时与 ‘accept’ 方法
..............................

如果 *note getdefaulttimeout(): 27d6. 的值不是 *note None: 203.，则
*note accept(): 768. 方法返回的套接字将继承该超时值。若是 None，返回的套
接字行为取决于侦听套接字的设置：

   * 如果侦听套接字处于 `阻塞模式' 或 `超时模式'，则 *note accept():
     768. 返回的套接字处于 `阻塞模式'；

   * 如果侦听套接字处于 `非阻塞模式'，那么 *note accept(): 768. 返回的套
     接字是阻塞还是非阻塞取决于操作系统。如果要确保跨平台时的正确行为，
     建议手动覆盖此设置。


File: python.info,  Node: 示例<23>,  Prev: 关于套接字超时的说明,  Up: socket --- 底层网络接口

5.18.2.12 示例
..............

以下是 4 个使用 TCP/IP 协议的最小示例程序：一台服务器，它将收到的所有数
据原样返回（仅服务于一个客户端），还有一个使用该服务器的客户端。注意，服
务器必须按序执行 ‘socket()’, *note bind(): 27e2, *note listen(): 83a,
*note accept(): 768. （可能需要重复执行 *note accept(): 768. 以服务多个
客户端），而客户端仅需要按序执行 ‘socket()’, *note connect(): 769.。还须
注意，服务器不在侦听套接字上发送 *note sendall(): 76e./*note recv():
76a.，而是在 *note accept(): 768. 返回的新套接字上发送。

前两个示例仅支持 IPv4。

     # Echo server program
     import socket

     HOST = ''                 # 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)

     # 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))

下两个例子与上两个很像，但是同时支持 IPv4 和 IPv6。 服务端将监听第一个可
用的地址族（它本应同时监听两个）。 在大多数支持 IPv6 的系统上，IPv6 将有
优先权并且服务端可能不会接受 IPv4 流量。 客户端将尝试连接到作为名称解析
结果被返回的所有地址，并将流量发送给连接成功的第一个地址。

     # 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)

     # 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))

下面的例子演示了如何在 Windows 上使用原始套接字编写一个非常简单的网络嗅
探器。 这个例子需要管理员权限来修改接口:

     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)

下面的例子演示了如何使用 socket 接口与采用原始套接字协议的 CAN 网络进行
通信。 要改为通过广播管理器协议来使用 CAN，则要用以下方式打开一个
socket:

     socket.socket(socket.AF_CAN, socket.SOCK_DGRAM, socket.CAN_BCM)

在绑定 (‘CAN_RAW’) 或连接 (*note CAN_BCM: 9a0.) socket 之后，你将可以在
socket 对象上正常使用 *note socket.send(): 76d. 以及 *note
socket.recv(): 76a. 操作（及同类操作）。

最后一个例子可能需要特别的权限:

     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')

多次运行一个示例，且每次执行之间等待时间过短，可能导致这个错误:

     OSError: [Errno 98] Address already in use

这是因为前一次运行使套接字处于 ‘TIME_WAIT’ 状态，无法立即重用。

要防止这种情况，需要设置一个 *note socket: ef. 标志
‘socket.SO_REUSEADDR’:

     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
     s.bind((HOST, PORT))

‘SO_REUSEADDR’ 标志告诉内核将处于 ‘TIME_WAIT’ 状态的本地套接字重新使用，
而不必等到固有的超时到期。

也參考
......

关于套接字编程（C 语言）的介绍，请参阅以下文章：

   - `An Introductory 4.3BSD Interprocess Communication Tutorial'，作者
     Stuart Sechrest

   - `An Advanced 4.3BSD Interprocess Communication Tutorial'，作者
     Samuel J. Leffler et al,

两篇文章都在 UNIX 开发者手册，补充文档 1（第 PS1:7 和 PS1:8 节）中。那些
特定于平台的参考资料，它们包含与套接字有关的各种系统调用，也是套接字语义
细节的宝贵信息来源。对于 Unix，请参考手册页。对于 Windows，请参阅
WinSock（或 Winsock 2）规范。如果需要支持 IPv6 的 API，读者可能希望参考
RFC 3493(1)，标题为 Basic Socket Interface Extensions for IPv6。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc3493.html


File: python.info,  Node: ssl --- 套接字对象的 TLS/SSL 包装器,  Next: select --- 等待 I/O 完成,  Prev: socket --- 底层网络接口,  Up: 网络和进程间通信

5.18.3 ‘ssl’ — 套接字对象的 TLS/SSL 包装器
------------------------------------------

`源代码:' Lib/ssl.py(1)

__________________________________________________________________

This module provides access to Transport Layer Security (often known as
"Secure Sockets Layer") encryption and peer authentication facilities
for network sockets, both client-side and server-side.  This module uses
the OpenSSL library.  It is available on all modern Unix systems,
Windows, macOS, and probably additional platforms, as long as OpenSSL is
installed on that platform.

     備註: 某些行为可能具有平台依赖，因为调用是根据操作系统的嵌套字API。
     不同版本的Open SSL也会引起差异：例如Open SSL版本1.0.1 自带TLSv1.1 和
     TLSv1.2

     警告: 在阅读 *note 安全考量: 26fd. 前不要使用此模块。 这样做可能会
     导致虚假的安全感，因为ssl模块的默认设置不一定适合你的应用程序。

本文档记录"ssl"模块的对象和函数；更多关于TLS,SSL,和证书的信息，请参阅下
方的“详情”选项

本模块提供了一个类 *note ssl.SSLSocket: 192.，它派生自 *note
socket.socket: 767. 类型，并提供类似套接字的包装器，也能够对通过带 SSL 套
接字的数据进行加密和解密。 它支持一些额外方法例如 ‘getpeercert()’，该方
法可从连接的另一端获取证书，还有 ‘cipher()’，该方法可获取安全连接所使用
的密码。

对于更复杂的应用程序，*note ssl.SSLContext: 4e9. 类有助于管理设置项和证
书，进而可以被使用 *note SSLContext.wrap_socket(): 4ea. 方法创建的 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 会话::
* 安全考量: 安全考量<2>.
* TLS 1.3: TLS 1 3.
* LibreSSL 支持::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/ssl.py


File: python.info,  Node: 方法、常量和异常处理,  Next: SSL 套接字,  Up: ssl --- 套接字对象的 TLS/SSL 包装器

5.18.3.1 方法、常量和异常处理
.............................

* Menu:

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


File: python.info,  Node: 套接字创建,  Next: 上下文创建,  Up: 方法、常量和异常处理

5.18.3.2 套接字创建
...................

从 Python 3.2 和 2.7.9 开始，建议使用 *note SSLContext: 4e9. 实例的
*note SSLContext.wrap_socket(): 4ea. 来将套接字包装为 *note SSLSocket:
192. 对象。 辅助函数 *note create_default_context(): 9a7. 会返回一个新的
带有安全默认设置的上下文。 旧的 *note wrap_socket(): 570. 函数已被弃用，
因为它效率较差并且不支持服务器名称提示（SNI）和主机匹配。

客户端套接字实例，采用默认上下文和IPv4/IPv6双栈:

     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())

客户端套接字示例，带有自定义上下文和IPv4:

     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())

服务器套接字实例，在localhost上监听IPv4:

     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()
             ...


File: python.info,  Node: 上下文创建,  Next: 异常<12>,  Prev: 套接字创建,  Up: 方法、常量和异常处理

5.18.3.3 上下文创建
...................

便捷函数，可以帮助创建 *note SSLContext: 4e9. 对象，用于常见的目的。

 -- 函式: ssl.create_default_context (purpose=Purpose.SERVER_AUTH,
          cafile=None, capath=None, cadata=None)

     返回一个新的 *note SSLContext: 4e9. 对象，使用给定 `purpose' 的默认
     设置。 该设置由 *note ssl: f3. 模块选择，并且通常是代表一个比直接调
     用 *note SSLContext: 4e9. 构造器时更高的安全等级。

     `cafile', `capath', `cadata' 代表用于进行证书核验的可选受信任 CA 证
     书，与 *note SSLContext.load_verify_locations(): 8d8. 的一致。 如果
     三个参数均为 *note None: 203.，此函数可以转而选择信任系统的默认 CA
     证书。

     设置为: *note PROTOCOL_TLS: 27f7, *note OP_NO_SSLv2: c71. 和 *note
     OP_NO_SSLv3: 27f8.，带有不含 RC4 及未认证的高强度加密密码套件。 传
     入 *note SERVER_AUTH: 9b2. 作为 `purpose' 会将 *note verify_mode:
     27f9. 设为 *note CERT_REQUIRED: 27fa. 并加载 CA 证书 (若给出
     `cafile', `capath' 或 `cadata' 之一) 或用 *note
     SSLContext.load_default_certs(): 9b1. 加载默认 CA 证书。

     当 *note keylog_filename: 27fb. 受支持并且设置了环境变量
     ‘SSLKEYLOGFILE’ 时，*note create_default_context(): 9a7. 会启用密钥
     日志记录。

          備註: 协议、选项、密码和其他设置可随时更改为更具约束性的值而无
          须事先弃用。 这些值代表了兼容性和安全性之间的合理平衡。

          如果你的应用需要特定的设置，你应当创建一个 *note SSLContext:
          4e9. 并自行应用设置。

          備註: 如果你发现当某些较旧的客户端或服务器尝试与用此函数创建的
          *note SSLContext: 4e9. 进行连接时收到了报错提示 "Protocol or
          cipher suite mismatch"，这可能是因为它们只支持 SSL3.0 而它被此
          函数用 *note OP_NO_SSLv3: 27f8. 排除掉了。 SSL3.0 被广泛认为 完
          全不可用(1)。 如果你仍希望继续使用此函数但仍允许 SSL 3.0 连接
          ，你可以使用以下代码重新启用它们:

               ctx = ssl.create_default_context(Purpose.CLIENT_AUTH)
               ctx.options &= ~ssl.OP_NO_SSLv3

     3.4 版新加入.

     3.4.4 版更變: RC4 被从默认密码字符串中丢弃。

     3.6 版更變: ChaCha20/Poly1305 被添加到默认密码字符串中。

     3DES 被从默认密码字符串中丢弃。

     3.8 版更變: 增加了对密钥日志记录至 ‘SSLKEYLOGFILE’ 的支持。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/POODLE


File: python.info,  Node: 异常<12>,  Next: 随机生成,  Prev: 上下文创建,  Up: 方法、常量和异常处理

5.18.3.4 异常
.............

 -- 例外: ssl.SSLError

     引发此异常以提示来自下层 SSL 实现（目前由 OpenSSL 库提供）的错误。
     它表示在下层网络连接之上叠加的高层级加密和验证层存在某种问题。 此错
     误是 *note OSError: 304. 的一个子类型。 *note SSLError: cda. 实例的
     错误和消息是由 OpenSSL 库提供的。

     3.3 版更變: *note SSLError: cda. 曾经是 *note socket.error: a76. 的
     一个子类型。

      -- 屬性: library

          一个字符串形式的助记符，用来指明发生错误的 OpenSSL 子模块，例
          如 ‘SSL’, ‘PEM’ 或 ‘X509’。 可能的取值范围依赖于 OpenSSL 的版
          本。

          3.3 版新加入.

      -- 屬性: reason

          一个字符串形式的助记符，用来指明发生错误的原因，例如
          ‘CERTIFICATE_VERIFY_FAILED’。 可能的取值范围依赖于 OpenSSL 的
          版本。

          3.3 版新加入.

 -- 例外: ssl.SSLZeroReturnError

     *note SSLError: cda. 的子类，当尝试读取或写入且 SSL 连接已被完全关
     闭时会被引发。 请注意这并不意味着下层的传输（读取 TCP）已被关闭。

     3.3 版新加入.

 -- 例外: ssl.SSLWantReadError

     *note SSLError: cda. 的子类，当尝试读取或写入数据，但在请求被满足之
     前还需要在下层的 TCP 传输上接收更多数据时会被 *note 非阻塞型 SSL
     套接字: 27fe. 引发。

     3.3 版新加入.

 -- 例外: ssl.SSLWantWriteError

     *note SSLError: cda. 的子类，当尝试读取或写入数据，但在请求被满足之
     前还需要在下层的 TCP 传输上发送更多数据时会被 *note 非阻塞型 SSL
     套接字: 27fe. 引发。

     3.3 版新加入.

 -- 例外: ssl.SSLSyscallError

     *note SSLError: cda. 的子类，当尝试在 SSL 套接字上执行操作时遇到系
     统错误时会被引发。 不幸的是，没有简单的方式能检查原始 errno 编号。

     3.3 版新加入.

 -- 例外: ssl.SSLEOFError

     *note SSLError: cda. 的子类，当 SSL 连接被突然终止时会被引发。 通常
     ，当遇到此错误时你不应再尝试重用下层的传输。

     3.3 版新加入.

 -- 例外: ssl.SSLCertVerificationError

     *note SSLError: cda. 的子类，当证书验证失败时会被引发。

     3.7 版新加入.

      -- 屬性: verify_code

          一个数字形式的错误编号，用于表示验证错误。

      -- 屬性: verify_message

          用于表示验证错误的人类可读的字符串。

 -- 例外: ssl.CertificateError

     *note SSLCertVerificationError: 4e3. 的别名。

     3.7 版更變: 此异常现在是 *note SSLCertVerificationError: 4e3. 的别
     名。


File: python.info,  Node: 随机生成,  Next: 证书处理,  Prev: 异常<12>,  Up: 方法、常量和异常处理

5.18.3.5 随机生成
.................

 -- 函式: ssl.RAND_bytes (num)

     返回 `num' 个高加密强度伪随机字节数据。 如果 PRNG 未使用足够的数据
     作为随机种子或者如果当前 RAND 方法不支持该操作则会引发 *note
     SSLError: cda.。 *note RAND_status(): 2805. 可被用来检查 PRNG 的状
     态而 *note RAND_add(): 2806. 可被用来为 PRNG 设置随机种子。

     对于几乎所有应用程序都更推荐使用 *note os.urandom(): 5cb.。

     请阅读维基百科文章 Cryptographically secure pseudorandom number
     generator (CSPRNG)(1) 以了解对于高加密强度生成器的具体要求。

     3.3 版新加入.

 -- 函式: ssl.RAND_pseudo_bytes (num)

     返回 (bytes, is_cryptographic): bytes 是 `num' 个伪随机字节数据，如
     果所生成的字节数据为高加密强度则 is_cryptographic 为 ‘True’。 如果
     当前 RAND 方法不支持此操作则会引发 *note SSLError: cda.。

     所生成的伪随机字节序列如果具有足够的长度则将会具有唯一性，并是并非
     不可预测。 它们可被用于非加密目的以及加密协议中的特定目的，但通常不
     可被用于密钥生成等目的。

     对于几乎所有应用程序都更推荐使用 *note os.urandom(): 5cb.。

     3.3 版新加入.

     3.6 版後已棄用: OpenSSL 已弃用了 *note ssl.RAND_pseudo_bytes():
     b68.，请改用 *note ssl.RAND_bytes(): b67.。

 -- 函式: ssl.RAND_status ()

     如果 SSL 伪随机数生成器已使用‘足够的’随机性作为种子则返回 ‘True’，
     否则返回 ‘False’。 你可以使用 *note ssl.RAND_egd(): 2807. 和 *note
     ssl.RAND_add(): 2806. 来增加伪随机数生成器的随机性。

 -- 函式: ssl.RAND_egd (path)

     如果你在某处运行了一个熵收集守护程序（EGD），且 `path' 是向其打开的
     套接字连接路径名，此函数将从该套接字读取 256 个字节的随机性数据，并
     将其添加到 SSL 伪随机数生成器以增加所生成密钥的安全性。 此操作通常
     只在没有更好随机性源的系统上才是必要的。

     请查看 ‘http://egd.sourceforge.net/’ 或
     ‘http://prngd.sourceforge.net/’ 来了解有关熵收集守护程序源的信息。

     *note 可用性: 1491.: 对于 LibreSSL 和 OpenSSL > 1.1.0 不可用。

 -- 函式: ssl.RAND_add (bytes, entropy)

     将给定的 `bytes' 混合到 SSL 伪随机数生成器中。 形参 `entropy'
     (float 类型) 是数据所包含的熵的下界 (因此你可以总是使用 ‘0.0’)。 请
     查看 RFC 1750(2) 了解有关熵源的更多信息。

     3.5 版更變: 现在接受可写的 *note 字节类对象: 6df.。

   ---------- Footnotes ----------

   (1) 
https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator

   (2) https://tools.ietf.org/html/rfc1750.html


File: python.info,  Node: 证书处理,  Next: 常量<3>,  Prev: 随机生成,  Up: 方法、常量和异常处理

5.18.3.6 证书处理
.................

 -- 函式: ssl.match_hostname (cert, hostname)

     验证 `cert' (使用 *note SSLSocket.getpeercert(): 9b7. 所返回的已解
     码格式) 是否匹配给定的 `hostname'。 所应用的规则是在 RFC 2818(1),
     RFC 5280(2) 和 RFC 6125(3) 中描述的检查 HTTPS 服务器身份的规则。 除
     了 HTTPS，此函数还应当适用于各种基于 SSL 协议的服务器身份检查操作，
     例如 FTPS, IMAPS, POPS 等等。

     失败时引发 *note CertificateError: 2803.。 成功时此函数无返回值:

          >>> 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'

     3.2 版新加入.

     3.3.3 版更變: 此函数现在遵循 RFC 6125(4), 6.4.3 小节，它不会匹配多
     个通配符 (例如 ‘*.*.com’ 或 ‘*a*.example.org’) 也不匹配国际化域名
     (IDN) 片段内部的通配符。 IDN A 标签例如 ‘www*.xn--pthon-kva.org’ 仍
     然受支持，但 ‘x*.python.org’ 不再能匹配 ‘xn--tda.python.org’。

     3.5 版更變: 现在支持匹配存在于证书的 subjectAltName 字段中的 IP 地
     址。

     3.7 版更變: 此函数不再被用于 TLS 连接。 主机匹配现在是由 OpenSSL 执
     行的。

     允许位于段的最左端且为唯一字符的通配符。 部分通配符例如
     ‘www*.example.com’ 已不再受支持。

     3.7 版後已棄用.

 -- 函式: ssl.cert_time_to_seconds (cert_time)

     返回距离 Unix 纪元零时的秒数，给定的 ‘cert_time’ 字符串代表来自证书
     的 "notBefore" 或 "notAfter" 日期值，采用 ‘"%b %d %H:%M:%S %Y %Z"’
     strptime 格式（C 区域）。

     以下为示例代码:

          >>> 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

     "notBefore" 或 "notAfter" 日期值必须使用 GMT ( RFC 5280(5))。

     3.5 版更變: 将输入时间解读为 UTC 时间，基于输入字符串中指明的 ’GMT’
     时区。 在之前使用的是本地时区。 返回一个整数（不带输入格式中秒的分
     数部分）

 -- 函式: ssl.get_server_certificate (addr, ssl_version=PROTOCOL_TLS,
          ca_certs=None)

     带 SSL 保护的服务器的地址 ‘addr’ 以 (`hostname', `port-number') 对
     的形式给出，获取服务器的证书，并将其以 PEM 编码字符串的形式返回。 如
     果指定了 ‘ssl_version’，则使用该版本的 SSL 协议尝试连接服务器。 如
     果指定了 ‘ca_certs’，它应当是一个包含根证书列表的文件，使用与 *note
     SSLContext.wrap_socket(): 4ea. 中同名形参一致的格式。 该调用将尝试
     根据指定的根证书集来验证服务器证书，如果验证失败则该调用也将失败。

     3.3 版更變: 此函数现在是 IPv6 兼容的。-compatible.

     3.5 版更變: 默认的 `ssl_version' 从 *note PROTOCOL_SSLv3: 2809. 改
     为 *note PROTOCOL_TLS: 27f7. 以保证与现代服务器的最大兼容性。

 -- 函式: ssl.DER_cert_to_PEM_cert (DER_cert_bytes)

     根据给定的 DER 编码字节块形式的证书，返回同一证书的 PEM 编码字符串
     版本。

 -- 函式: ssl.PEM_cert_to_DER_cert (PEM_cert_string)

     根据给定的 ASCII PEM 字符串形式的证书，返回同一证书的 DER 编码字节
     序列。

 -- 函式: ssl.get_default_verify_paths ()

     返回包含 OpenSSL 的默认 cafile 和 capath 的路径的命名元组。 此路径
     与 *note SSLContext.set_default_verify_paths(): 9a9. 所使用的相同。
     返回值是一个 *note named tuple: b7b. ‘DefaultVerifyPaths’:

        * ‘cafile’ - 解析出的 cafile 路径或者如果文件不存在则为 ‘None’,

        * ‘capath’ - 解析出的 capath 路径或者如果目录不存在则为 ‘None’,

        * ‘openssl_cafile_env’ - 指向一个 cafile 的 OpenSSL 环境键,

        * ‘openssl_cafile’ - 一个 cafile 的硬编码路径,

        * ‘openssl_capath_env’ - 指向一个 capath 的 OpenSSL 环境键,

        * ‘openssl_capath’ - 一个 capath 目录的硬编码路径

     *note 可用性: 1491.: LibreSSL 会忽略环境变量 ‘openssl_cafile_env’ 和
     ‘openssl_capath_env’。

     3.4 版新加入.

 -- 函式: ssl.enum_certificates (store_name)

     从 Windows 的系统证书库中检索证书。 `store_name' 可以是 ‘CA’,
     ‘ROOT’ 或 ‘MY’ 中的一个。 Windows 也可能会提供额外的证书库。

     此函数返回一个包含 (cert_bytes, encoding_type, trust) 元组的列表。
     encoding_type 指明 cert_bytes 的编码格式。 它可以为 ‘x509_asn’ 以表
     示 X.509 ASN.1 数据或是 ‘pkcs_7_asn’ 以表示 PKCS#7 ASN.1 数据。
     trust 以 OIDS 集合的形式指明证书的目的，或者如果证书对于所有目的都
     可以信任则为 ‘True’。

     示例:

          >>> 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)]

     *note 可用性: 1491.: Windows。

     3.4 版新加入.

 -- 函式: ssl.enum_crls (store_name)

     Windows 的系统证书库中检索 CRL。 `store_name' 可以是 ‘CA’, ‘ROOT’ 或
     ‘MY’ 中的一个。 Windows 也可能会提供额外的证书库。

     此函数返回一个包含 (cert_bytes, encoding_type, trust) 元组的列表。
     encoding_type 指明 cert_bytes 的编码格式。 它可以为 ‘x509_asn’ 以表
     示 X.509 ASN.1 数据或是 ‘pkcs_7_asn’ 以表示 PKCS#7 ASN.1 数据。

     *note 可用性: 1491.: Windows。

     3.4 版新加入.

 -- 函式: 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)

     接受一个 *note socket.socket: 767. 的实例 ‘sock’，并返回一个 *note
     ssl.SSLSocket: 192. 的实例，该类型是 *note socket.socket: 767. 的子
     类型，它将下层的套接字包装在一个 SSL 上下文中。 ‘sock’ 必须是一个
     *note SOCK_STREAM: d52. 套接字；其他套接字类型不被支持。

     在内部，该函数会创建一个 *note SSLContext: 4e9.，其协议版本为
     `ssl_version' 且 *note SSLContext.options: 280c. 设为 `cert_reqs'。
     如果设置了 `keyfile', `certfile', `ca_certs' 或 `ciphers' 等形参，
     则参数值会被传给 *note SSLContext.load_cert_chain(): b69, *note
     SSLContext.load_verify_locations(): 8d8. 以及 *note
     SSLContext.set_ciphers(): 280d.。

     参数 `server_side', `do_handshake_on_connect' 和
     `suppress_ragged_eofs' 具有与 *note SSLContext.wrap_socket(): 4ea.
     相同的含义。

     3.7 版後已棄用: 从 Python 3.2 和 2.7.9 开始，建议使用 *note
     SSLContext.wrap_socket(): 4ea. 来代替 *note wrap_socket(): 570.。 模
     块级函数的功能受限并且将创建不安全的客户端套接字，不带服务器名称提
     示或主机名匹配。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2818.html

   (2) https://tools.ietf.org/html/rfc5280.html

   (3) https://tools.ietf.org/html/rfc6125.html

   (4) https://tools.ietf.org/html/rfc6125.html

   (5) https://tools.ietf.org/html/rfc5280.html


File: python.info,  Node: 常量<3>,  Prev: 证书处理,  Up: 方法、常量和异常处理

5.18.3.7 常量
.............

     所有常量现在都是 *note enum.IntEnum: 684. 或 *note enum.IntFlag:
     18a1. 多项集的成员。

     3.6 版新加入.

 -- Data: ssl.CERT_NONE

     *note SSLContext.verify_mode: 27f9. 或 *note wrap_socket(): 570. 的
     ‘cert_reqs’ 形参可能的取值。 *note PROTOCOL_TLS_CLIENT: 2810. 除外
     ，这是默认的模式。 对于客户端套接字，几乎任何证书都是可接受的。 验
     证错误例如不受信任或过期的证书错误会被忽略并且不会中止 TLS/SSL 握手
     。

     在服务器模式下，不会从客户端请求任何证书，因此客户端不会发送任何用
     于客户端证书身份验证的证书。

     参见下文对于 *note 安全考量: 26fd. 的讨论。

 -- Data: ssl.CERT_OPTIONAL

     *note SSLContext.verify_mode: 27f9. 或 *note wrap_socket(): 570. 的
     ‘cert_reqs’ 形参可能的取值。 *note CERT_OPTIONAL: 2811. 具有与
     *note CERT_REQUIRED: 27fa. 相同的含义。 对于客户端套接字推荐改用
     *note CERT_REQUIRED: 27fa.。

     在服务器模式下，客户端证书请求会被发送给客户端。 客户端可以忽略请求
     也可以发送一个证书以执行 TLS 客户端证书身份验证。 如果客户端选择发
     送证书，则将对其执行验证。 任何验证错误都将立即中止 TLS 握手。

     使用此设置要求将一组有效的 CA 证书传递给 *note
     SSLContext.load_verify_locations(): 8d8. 或是作为 *note
     wrap_socket(): 570. 的 ‘ca_certs’ 形参值。

 -- Data: ssl.CERT_REQUIRED

     *note SSLContext.verify_mode: 27f9. 或 *note wrap_socket(): 570. 的
     ‘cert_reqs’ 形参可能的取值。 在此模式下，需要从套接字连接的另一端获
     取证书；如果未提供证书或验证失败则将引发 *note SSLError: cda.。 此
     模式 `不能' 在客户端模式下对证书进行验证，因为它不会匹配主机名。
     *note check_hostname: 2812. 也必须被启用以验证证书的真实性。 *note
     PROTOCOL_TLS_CLIENT: 2810. 会使用 *note CERT_REQUIRED: 27fa. 并默认
     启用 *note check_hostname: 2812.。

     对于服务器套接字，此模式会提供强制性的 TLS 客户端证书验证。 客户端
     证书请求会被发送给客户端并且客户端必须提供有效且受信任的证书。

     使用此设置要求将一组有效的 CA 证书传递给 *note
     SSLContext.load_verify_locations(): 8d8. 或是作为 *note
     wrap_socket(): 570. 的 ‘ca_certs’ 形参值。

 -- 類別: ssl.VerifyMode

     CERT_* 常量的 *note enum.IntEnum: 684. 多项集。

     3.6 版新加入.

 -- Data: ssl.VERIFY_DEFAULT

     *note SSLContext.verify_flags: 9ac. 可能的取值。 在此模式下，证书吊
     销列表（CRL）并不会被检查。 OpenSSL 默认不要求也不验证 CRL。

     3.4 版新加入.

 -- Data: ssl.VERIFY_CRL_CHECK_LEAF

     *note SSLContext.verify_flags: 9ac. 可能的取值。 在此模式下， 只会
     检查对等证书而不检查任何中间 CA 证书。 此模式要求提供由对等证书颁发
     者（其直接上级 CA）签名的有效 CRL。 如果未使用 *note
     SSLContext.load_verify_locations: 8d8. 加载正确的 CRL，则验证将失败
     。

     3.4 版新加入.

 -- Data: ssl.VERIFY_CRL_CHECK_CHAIN

     *note SSLContext.verify_flags: 9ac. 可能的取值。 在此模式下，会检查
     对等证书链中所有证书的 CRL。

     3.4 版新加入.

 -- Data: ssl.VERIFY_X509_STRICT

     *note SSLContext.verify_flags: 9ac. 可能的取值，用于禁用已损坏
     X.509 证书的绕过操作。

     3.4 版新加入.

 -- Data: ssl.VERIFY_X509_TRUSTED_FIRST

     *note SSLContext.verify_flags: 9ac. 可能的取值。 它指示 OpenSSL 在
     构建用于验证某个证书的信任链时首选受信任的证书。 此旗标将默认被启用
     。

     3.4.4 版新加入.

 -- 類別: ssl.VerifyFlags

     VERIFY_* 常量的 *note enum.IntFlag: 18a1. 多项集。

     3.6 版新加入.

 -- Data: ssl.PROTOCOL_TLS

     选择客户端和服务器均支持的最高协议版本。 此选项名称并不准确，实际上
     "SSL" 和 "TLS" 协议均可被选择。

     3.6 版新加入.

 -- Data: ssl.PROTOCOL_TLS_CLIENT

     像 *note PROTOCOL_TLS: 27f7. 一样地自动协商最高协议版本，但是只支持
     客户端 *note SSLSocket: 192. 连接。 此协议默认会启用 *note
     CERT_REQUIRED: 27fa. 和 *note check_hostname: 2812.。

     3.6 版新加入.

 -- Data: ssl.PROTOCOL_TLS_SERVER

     像 *note PROTOCOL_TLS: 27f7. 一样地自动协商最高协议版本，但是只支持
     服务器 *note SSLSocket: 192. 连接。

     3.6 版新加入.

 -- Data: ssl.PROTOCOL_SSLv23

     *note PROTOCOL_TLS: 27f7. 的别名。

     3.6 版後已棄用: 请改用 *note PROTOCOL_TLS: 27f7.。

 -- Data: ssl.PROTOCOL_SSLv2

     选择 SSL 版本 2 作为通道加密协议。

     如果 OpenSSL 编译时使用了 ‘OPENSSL_NO_SSL2’ 旗标则此协议将不可用。

          警告: SSL 版本 2 并不安全。 极不建议使用它。

     3.6 版後已棄用: OpenSSL 已经移除了对 SSLv2 的支持。

 -- Data: ssl.PROTOCOL_SSLv3

     选择 SSL 版本 3 作为通道加密协议。

     如果 OpenSSL 编译时使用了 ‘OPENSSL_NO_SSLv3’ 旗标则此协议将不可用。

          警告: SSL 版本 3 并不安全。 极不建议使用它。

     3.6 版後已棄用: OpenSSL 已经弃用了所有带有特定版本号的协议。 请改用
     默认协议 *note PROTOCOL_TLS: 27f7. 并附带 *note OP_NO_SSLv3: 27f8.
     等旗标。

 -- Data: ssl.PROTOCOL_TLSv1

     选择 TLS 版本 1.0 作为通道加密协议。

     3.6 版後已棄用: OpenSSL 已经弃用了所有带有特定版本号的协议。 请改用
     默认协议 *note PROTOCOL_TLS: 27f7. 并附带 *note OP_NO_SSLv3: 27f8.
     等旗标。

 -- Data: ssl.PROTOCOL_TLSv1_1

     选择 TLS 版本 1.1 作为通道加密协议。 仅适用于 openssl 版本 1.0.1+。

     3.4 版新加入.

     3.6 版後已棄用: OpenSSL 已经弃用了所有带有特定版本号的协议。 请改用
     默认协议 *note PROTOCOL_TLS: 27f7. 并附带 *note OP_NO_SSLv3: 27f8.
     等旗标。

 -- Data: ssl.PROTOCOL_TLSv1_2

     选译 TLS 版本 1.2 作为通道加密协议。 这是最新的版本，也应是能提供最
     大保护的最佳选择，如果通信双方都支持它的话。 仅适用于 openssl 版本
     1.0.1+。

     3.4 版新加入.

     3.6 版後已棄用: OpenSSL 已经弃用了所有带有特定版本号的协议。 请改用
     默认协议 *note PROTOCOL_TLS: 27f7. 并附带 *note OP_NO_SSLv3: 27f8.
     等旗标。

 -- Data: ssl.OP_ALL

     对存在于其他 SSL 实现中的各种缺陷启用绕过操作。 默认会设置此选项。
     没有必要设置与 OpenSSL 的 ‘SSL_OP_ALL’ 常量同名的旗标。

     3.2 版新加入.

 -- Data: ssl.OP_NO_SSLv2

     阻止 SSLv2 连接。 此选项仅可与 *note PROTOCOL_TLS: 27f7. 结合使用。
     它会阻止对等方选择 SSLv2 作为协议版本。

     3.2 版新加入.

     3.6 版後已棄用: SSLv2 已被弃用

 -- Data: ssl.OP_NO_SSLv3

     阻止 SSLv3 连接。 此选项仅可与 *note PROTOCOL_TLS: 27f7. 结合使用。
     它会阻止对等方选择 SSLv3 作为协议版本。

     3.2 版新加入.

     3.6 版後已棄用: SSLv3 已被弃用

 -- Data: ssl.OP_NO_TLSv1

     阻止 TLSv1 连接。 此选项仅可与 *note PROTOCOL_TLS: 27f7. 结合使用。
     它会阻止对等方选择 TLSv1 作为协议版本。

     3.2 版新加入.

     3.7 版後已棄用: 此选项自 OpenSSL 1.1.0 起已被弃用，请改用新的 *note
     SSLContext.minimum_version: 4ec. 和 *note
     SSLContext.maximum_version: 4ed.。

 -- Data: ssl.OP_NO_TLSv1_1

     阻止 TLSv1.1 连接。 此选项仅可与 *note PROTOCOL_TLS: 27f7. 结合使用
     。 它会阻止对等方选择 TLSv1.1 作为协议版本。 仅适用于 openssl 版本
     1.0.1+。

     3.4 版新加入.

     3.7 版後已棄用: 此选项自 OpenSSL 1.1.0 起已被弃用。

 -- Data: ssl.OP_NO_TLSv1_2

     阻止 TLSv1.2 连接。 此选项仅可与 *note PROTOCOL_TLS: 27f7. 结合使用
     。 它会阻止对等方选择 TLSv1.2 作为协议版本。 仅适用于 openssl 版本
     1.0.1+。

     3.4 版新加入.

     3.7 版後已棄用: 此选项自 OpenSSL 1.1.0 起已被弃用。

 -- Data: ssl.OP_NO_TLSv1_3

     阻止 TLSv1.3 连接。 此选项仅可与 *note PROTOCOL_TLS: 27f7. 结合使用
     。 它会阻止对等方选择 TLSv1.3 作为协议版本。 TLS 1.3 适用于 OpenSSL
     1.1.1 或更新的版本。 当 Python 编译是基于较旧版本的 OpenSSL 时，该
     旗标默认为 `0'。

     3.7 版新加入.

     3.7 版後已棄用: 此选项自 OpenSSL 1.1.0 起已被弃用。 它被添加到
     2.7.15, 3.6.3 和 3.7.0 是为了向下兼容 OpenSSL 1.0.2。

 -- Data: ssl.OP_NO_RENEGOTIATION

     禁用所有 TLSv1.2 和更早版本的重协商操作。 不发送 HelloRequest 消息
     ，并忽略通过 ClientHello 发起的重协商请求。

     此选项仅适用于 OpenSSL 1.1.0h 及更新的版本。

     3.7 版新加入.

 -- Data: ssl.OP_CIPHER_SERVER_PREFERENCE

     使用服务器的密码顺序首选项，而不是客户端的首选项。 此选项在客户端套
     接字和 SSLv2 服务器套接字上无效。

     3.3 版新加入.

 -- Data: ssl.OP_SINGLE_DH_USE

     阻止对于单独的 SSL 会话重用相同的 DH 密钥。 这会提升前向保密性但需
     要更多的计算资源。 此选项仅适用于服务器套接字。

     3.3 版新加入.

 -- Data: ssl.OP_SINGLE_ECDH_USE

     阻止对于单独的 SSL 会话重用相同的 ECDH 密钥。 这会提升前向保密性但
     需要更多的计算资源。 此选项仅适用于服务器套接字。

     3.3 版新加入.

 -- Data: ssl.OP_ENABLE_MIDDLEBOX_COMPAT

     在 TLS 1.3 握手中发送虚拟更改密码规格（CCS）消息以使得 TLS 1.3 连接
     看起来更像是 TLS 1.2 连接。

     此选项仅适用于 OpenSSL 1.1.1 及更新的版本。

     3.8 版新加入.

 -- Data: ssl.OP_NO_COMPRESSION

     在 SSL 通道上禁用压缩。 这适用于应用协议支持自己的压缩方案的情况。

     此选项仅适用于 OpenSSL 1.0.0 及更新的版本。

     3.3 版新加入.

 -- 類別: ssl.Options

     OP_* 常量的 *note enum.IntFlag: 18a1. 多项集。

 -- Data: ssl.OP_NO_TICKET

     阻止客户端请求会话凭据。

     3.6 版新加入.

 -- Data: ssl.OP_IGNORE_UNEXPECTED_EOF

     忽略 TLS 连接的意外关闭。

     此选项仅适用于 OpenSSL 3.0.0 及更新的版本。

     3.10 版新加入.

 -- Data: ssl.HAS_ALPN

     OpenSSL 库是否具有对 RFC 7301(1) 中描述的 `应用层协议协商' TLS 扩展
     的内置支持。

     3.5 版新加入.

 -- Data: ssl.HAS_NEVER_CHECK_COMMON_NAME

     OpenSSL 库是否具有对不检测目标通用名称的内置支持且 *note
     SSLContext.hostname_checks_common_name: 4e4. 为可写状态。

     3.7 版新加入.

 -- Data: ssl.HAS_ECDH

     OpenSSL 库是否具有对基于椭圆曲线的 Diffie-Hellman 密钥交换的内置支
     持。 此常量应当为真值，除非发布者明确地禁用了此功能。

     3.3 版新加入.

 -- Data: ssl.HAS_SNI

     OpenSSL 库是否具有对 `服务器名称提示' 扩展（在 RFC 6066(2) 中定义）
     的内置支持。

     3.2 版新加入.

 -- Data: ssl.HAS_NPN

     OpenSSL 库是否具有对 应用层协议协商(3) 中描述的 `下一协议协商' 的内
     置支持。 当此常量为真值时，你可以使用 *note
     SSLContext.set_npn_protocols(): b6f. 方法来公告你想要支持的协议。

     3.3 版新加入.

 -- Data: ssl.HAS_SSLv2

     OpenSSL 库是否具有对 SSL 2.0 协议的内置支持。

     3.7 版新加入.

 -- Data: ssl.HAS_SSLv3

     OpenSSL 库是否具有对 SSL 3.0 协议的内置支持。

     3.7 版新加入.

 -- Data: ssl.HAS_TLSv1

     OpenSSL 库是否具有对 TLS 1.0 协议的内置支持。

     3.7 版新加入.

 -- Data: ssl.HAS_TLSv1_1

     OpenSSL 库是否具有对 TLS 1.1 协议的内置支持。

     3.7 版新加入.

 -- Data: ssl.HAS_TLSv1_2

     OpenSSL 库是否具有对 TLS 1.2 协议的内置支持。

     3.7 版新加入.

 -- Data: ssl.HAS_TLSv1_3

     OpenSSL 库是否具有对 TLS 1.3 协议的内置支持。

     3.7 版新加入.

 -- Data: ssl.CHANNEL_BINDING_TYPES

     受支持的 TLS 通道绑定类型组成的列表。 此列表中的字符串可被用作传给
     *note SSLSocket.get_channel_binding(): b6c. 的参数。

     3.3 版新加入.

 -- Data: ssl.OPENSSL_VERSION

     解释器所加载的 OpenSSL 库的版本字符串:

          >>> ssl.OPENSSL_VERSION
          'OpenSSL 1.0.2k  26 Jan 2017'

     3.2 版新加入.

 -- Data: ssl.OPENSSL_VERSION_INFO

     代表 OpenSSL 库的版本信息的五个整数所组成的元组:

          >>> ssl.OPENSSL_VERSION_INFO
          (1, 0, 2, 11, 15)

     3.2 版新加入.

 -- Data: ssl.OPENSSL_VERSION_NUMBER

     OpenSSL 库的原始版本号，以单个整数表示:

          >>> ssl.OPENSSL_VERSION_NUMBER
          268443839
          >>> hex(ssl.OPENSSL_VERSION_NUMBER)
          '0x100020bf'

     3.2 版新加入.

 -- Data: ssl.ALERT_DESCRIPTION_HANDSHAKE_FAILURE
 -- Data: ssl.ALERT_DESCRIPTION_INTERNAL_ERROR

 -- Data: ALERT_DESCRIPTION_*

     来自 RFC 5246(4) 等文档的警报描述。 IANA TLS Alert Registry(5) 中包
     含了这个列表及对定义其含义的 RFC 引用。

     被用作 *note SSLContext.set_servername_callback(): 9b6. 中的回调函
     数的返回值。

     3.4 版新加入.

 -- 類別: ssl.AlertDescription

     ALERT_DESCRIPTION_* 常量的 *note enum.IntEnum: 684. 多项集。

     3.6 版新加入.

 -- Data: Purpose.SERVER_AUTH

     *note create_default_context(): 9a7. 和 *note
     SSLContext.load_default_certs(): 9b1. 的选项值。 这个值表明此上下文
     可以被用来验证 Web 服务器（因此，它将被用来创建客户端套接字）。

     3.4 版新加入.

 -- Data: Purpose.CLIENT_AUTH

     *note create_default_context(): 9a7. 和 *note
     SSLContext.load_default_certs(): 9b1. 的选项值。 这个值表明此上下文
     可以被用来验证 Web 客户端（因此，它将被用来创建服务器端套接字）。

     3.4 版新加入.

 -- 類別: ssl.SSLErrorNumber

     SSL_ERROR_* 常量的 *note enum.IntEnum: 684. 多项集。

     3.6 版新加入.

 -- 類別: ssl.TLSVersion

     *note SSLContext.maximum_version: 4ed. 和 *note
     SSLContext.minimum_version: 4ec. 中的 SSL 和 TLS 版本的 *note
     enum.IntEnum: 684. 多项集。

     3.7 版新加入.

 -- 屬性: TLSVersion.MINIMUM_SUPPORTED

 -- 屬性: TLSVersion.MAXIMUM_SUPPORTED

     受支持的最低和最高 SSL 或 TLS 版本。 这些常量被称为魔术常量。 它们
     的值并不反映可用的最低和最高 TLS/SSL 版本。

 -- 屬性: TLSVersion.SSLv3

 -- 屬性: TLSVersion.TLSv1

 -- 屬性: TLSVersion.TLSv1_1

 -- 屬性: TLSVersion.TLSv1_2

 -- 屬性: TLSVersion.TLSv1_3

     SSL 3.0 至 TLS 1.3。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc7301.html

   (2) https://tools.ietf.org/html/rfc6066.html

   (3) 
https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation

   (4) https://tools.ietf.org/html/rfc5246.html

   (5) 
https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6


File: python.info,  Node: SSL 套接字,  Next: SSL 上下文,  Prev: 方法、常量和异常处理,  Up: ssl --- 套接字对象的 TLS/SSL 包装器

5.18.3.8 SSL 套接字
...................

 -- 類別: ssl.SSLSocket (socket.socket)

     SSL 套接字提供了 *note 套接字对象: 27d4. 的下列方法:

        - *note accept(): 768.

        - *note bind(): 27e2.

        - *note close(): 6f7.

        - *note connect(): 769.

        - *note detach(): c6e.

        - *note fileno(): 27e6.

        - *note getpeername(): 2741, *note getsockname(): 2742.

        - *note getsockopt(): 679, *note setsockopt(): 67a.

        - *note gettimeout(): 27e7, *note settimeout(): 27b9, *note
          setblocking(): 206f.

        - *note listen(): 83a.

        - *note makefile(): bec.

        - *note recv(): 76a, *note recv_into(): d7a. (but passing a
          non-zero ‘flags’ argument is not allowed)

        - *note send(): 76d, *note sendall(): 76e. (with the same
          limitation)

        - *note sendfile(): 839. (but *note os.sendfile: 461. will be
          used for plain-text sockets only, else *note send(): 76d. will
          be used)

        - *note shutdown(): 27e3.

     但是，由于 SSL（和 TLS）协议在 TCP 之上具有自己的框架，因此 SSL 套
     接字抽象在某些方面可能与常规的 OS 层级套接字存在差异。 特别是要查看
     *note 非阻塞型套接字说明: 27fe.。

     *note SSLSocket: 192. 的实例必须使用 *note
     SSLContext.wrap_socket(): 4ea. 方法来创建。

     3.5 版更變: 新增了 ‘sendfile()’ 方法。

     3.5 版更變: ‘shutdown()’ 不会在每次接收或发送字节数据后重置套接字超
     时。 现在套接字超时为关闭的最大总持续时间。

     3.6 版後已棄用: 直接创建 *note SSLSocket: 192. 实例的做法已被弃用，
     请使用 *note SSLContext.wrap_socket(): 4ea. 来包装套接字。

     3.7 版更變: *note SSLSocket: 192. 的实例必须使用 *note
     wrap_socket(): 4ea. 来创建。 在较早的版本中，直接创建实例是可能的。
     但这从未被记入文档或是被正式支持。

SSL 套接字还具有下列方法和属性:

 -- 成員函式: SSLSocket.read (len=1024, buffer=None)

     从 SSL 套接字读取至多 `len' 个字节的数据并将结果作为 ‘bytes’ 实例返
     回。 如果指定了 `buffer'，则改为读取到缓冲区，并返回所读取的字节数
     。

     如果套接字为 *note 非阻塞型: 27fe. 则会引发 *note SSLWantReadError:
     845. 或 *note SSLWantWriteError: 846. 且读取将阻塞。

     由于在任何时候重新协商都是可能的，因此调用 *note read(): 84a. 也可
     能导致写入操作。

     3.5 版更變: 套接字超时在每次接收或发送字节数据后不会再被重置。 现在
     套接字超时为读取至多 `len' 个字节数据的最大总持续时间。

     3.6 版後已棄用: 请使用 ‘recv()’ 来代替 *note read(): 84a.。

 -- 成員函式: SSLSocket.write (buf)

     将 `buf' 写入到 SSL 套接字并返回所写入的字节数。 `buf' 参数必须为支
     持缓冲区接口的对象。

     如果套接字为 *note 非阻塞型: 27fe. 则会引发 *note SSLWantReadError:
     845. 或 *note SSLWantWriteError: 846. 且读取将阻塞。

     由于在任何时候重新协商都是可能的，因此调用 *note write(): 84b. 也可
     能导致读取操作。

     3.5 版更變: 套接字超时在每次接收或发送字节数据后不会再被重置。 现在
     套接字超时为写入 `buf' 的最大总持续时间。

     3.6 版後已棄用: 请使用 ‘send()’ 来代替 *note write(): 84b.。

     備註: *note read(): 84a. 和 *note write(): 84b. 方法是读写未加密的
     应用级数据，并将其解密/加密为带加密的线路级数据的低层级方法。 这些
     方法需要有激活的 SSL 连接，即握手已完成而 *note SSLSocket.unwrap():
     283c. 尚未被调用。

     通常你应当使用套接字 API 方法例如 *note recv(): 76a. 和 *note
     send(): 76d. 来代替这些方法。

 -- 成員函式: SSLSocket.do_handshake ()

     执行 SSL 设置握手。

     3.4 版更變: 当套接字的 *note context: 283d. 的 *note
     check_hostname: 2812. 属性为真值时此握手方法还会执行 *note
     match_hostname(): 4e2.。

     3.5 版更變: 套接字超时在每次接收或发送字节数据时不会再被重置。 现在
     套接字超时为握手的最大总持续时间。

     3.7 版更變: 主机名或 IP 地址会在握手期间由 OpenSSL 进行匹配。 函数
     *note match_hostname(): 4e2. 将不再被使用。 在 OpenSSL 拒绝主机名和
     IP 地址的情况下，握手将提前被中止并向对等方发送 TLS 警告消息。

 -- 成員函式: SSLSocket.getpeercert (binary_form=False)

     如果连接另一端的对等方没有证书，则返回 ‘None’。 如果 SSL 握手还未完
     成，则会引发 *note ValueError: 16d.。

     如果 ‘binary_form’ 形参为 *note False: 48e.，并且从对等方接收到了证
     书，此方法将返回一个 *note dict: 164. 实例。 如果证书未通过验证，则
     字典将为空。 如果证书通过验证，它将返回由多个密钥组成的字典，其中包
     括 ‘subject’ (证书颁发给的主体) 和 ‘issuer’ (颁发证书的主体)。 如果
     证书包含一个 `Subject Alternative Name' 扩展的实例 (see RFC
     3280(1))，则字典中还将有一个 ‘subjectAltName’ 键。

     ‘subject’ 和 ‘issuer’ 字段都是包含在证书中相应字段的数据结构中给出
     的相对专有名称（RDN）序列的元组，每个 RDN 均为 name-value 对的序列
     。 这里是一个实际的示例:

          {'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}

          備註: 要验证特定服务的证书，你可以使用 *note match_hostname():
          4e2. 函数。

     如果 ‘binary_form’ 形参为 *note True: 593.，并且提供了证书，此方法
     会将整个证书的 DER 编码形式作为字节序列返回，或者如果对等方未提供证
     书则返回 *note None: 203.。 对等方是否提供证书取决于 SSL 套接字的角
     色:

        * 对于客户端 SSL 套接字，服务器将总是提供证书，无论是否需要进行
          验证;

        * 对于服务器 SSL 套接字，客户端将仅在服务器要求时才提供证书；因
          此如果你使用了 *note CERT_NONE: 280f. (而不是 *note
          CERT_OPTIONAL: 2811. 或 *note CERT_REQUIRED: 27fa.) 则 *note
          getpeercert(): 9b7. 将返回 *note None: 203.。

     3.2 版更變: 返回的字典包括额外的条目例如 ‘issuer’ 和 ‘notBefore’。

     3.4 版更變: 如果握手未完成则会引发 *note ValueError: 16d.。 返回的
     字典包括额外的 X509v3 扩展条目例如 ‘crlDistributionPoints’,
     ‘caIssuers’ 和 ‘OCSP’ URI。

     3.9 版更變: IPv6 地址字符串不再附带末尾换行符。

 -- 成員函式: SSLSocket.cipher ()

     返回由三个值组成的元组，其中包含所使用的密码名称，定义其使用方式的
     SSL 协议版本，以及所使用的加密比特位数。 如果尚未建立连接，则返回
     ‘None’。

 -- 成員函式: SSLSocket.shared_ciphers ()

     返回在握手期间由客户端共享的密码列表。 所返回列表的每个条目都是由三
     个值组成的元组，其中包括密码名称，定义其使用方式的 SSL 协议版本，以
     及密码所使用的加密比特位数。 如果尚未建立连接或套接字为客户端套接字
     则 *note shared_ciphers(): 848. 将返回 ‘None’。

     3.5 版新加入.

 -- 成員函式: SSLSocket.compression ()

     以字符串形式返回所使用的压缩算法，或者如果连接没有使用压缩则返回
     ‘None’。

     如果高层级的协议支持自己的压缩机制，你可以使用 *note
     OP_NO_COMPRESSION: b6e. 来禁用 SSL 层级的压缩。

     3.3 版新加入.

 -- 成員函式: SSLSocket.get_channel_binding (cb_type="tls-unique")

     为当前连接获取字节串形式的通道绑定数据。 如果尚未连接或握手尚未完成
     则返回 ‘None’。

     `cb_type' 形参允许选择需要的通道绑定类型。 有效的通道绑定类型在
     *note CHANNEL_BINDING_TYPES: 282e. 列表中列出。 目前只支持由 RFC
     5929(2) 所定义的 ’tls-unique’ 通道绑定。 如果请求了一个不受支持的通
     道绑定类型则将引发 *note ValueError: 16d.。

     3.3 版新加入.

 -- 成員函式: SSLSocket.selected_alpn_protocol ()

     返回在 TLS 握手期间所选择的协议。 如果 *note
     SSLContext.set_alpn_protocols(): 840. 未被调用，如果另一方不支持
     ALPN，如果此套接字不支持任何客户端所用的协议，或者如果握手尚未发生
     ，则将返回 ‘None’。

     3.5 版新加入.

 -- 成員函式: SSLSocket.selected_npn_protocol ()

     返回在Return the higher-level protocol that was selected during the
     TLS/SSL 握手期间所选择的高层级协议。 如果 *note
     SSLContext.set_npn_protocols(): b6f. 未被调用，或者如果另一方不支持
     NPN，或者如果握手尚未发生，则将返回 ‘None’。

     3.3 版新加入.

 -- 成員函式: SSLSocket.unwrap ()

     执行 SSL 关闭握手，这会从下层的套接字中移除 TLS 层，并返回下层的套
     接字对象。 这可被用来通过一个连接将加密操作转为非加密。 返回的套接
     字应当总是被用于同连接另一方的进一步通信，而不是原始的套接字。

 -- 成員函式: SSLSocket.verify_client_post_handshake ()

     向一个 TLS 1.3 客户端请求握手后身份验证（PHA）。 只有在初始 TLS 握
     手之后且双方都启用了 PHA 的情况下才能为服务器端套接字的 TLS 1.3 连
     接启用 PHA，参见 *note SSLContext.post_handshake_auth: 351.。

     此方法不会立即执行证书交换。 服务器端会在下一次写入事件期间发送
     CertificateRequest 并期待客户端在下一次读取事件期间附带证书进行响应
     。

     如果有任何前置条件未被满足（例如非 TLS 1.3，PHA 未启用），则会引发
     *note SSLError: cda.。

          備註: 仅在 OpenSSL 1.1.1 且 TLS 1.3 被启用时可用。 没有 TLS
          1.3 支持，此方法将引发 *note NotImplementedError: 704.。

     3.8 版新加入.

 -- 成員函式: SSLSocket.version ()

     以字符串形式返回由连接协商确定的实际 SSL 协议版本，或者如果未建立安
     全连接则返回 ‘None’。 在撰写本文档时，可能的返回值包括 ‘"SSLv2"’,
     ‘"SSLv3"’, ‘"TLSv1"’, ‘"TLSv1.1"’ 和 ‘"TLSv1.2"’。 最新的 OpenSSL 版
     本可能会定义更多的返回值。

     3.5 版新加入.

 -- 成員函式: SSLSocket.pending ()

     返回在连接上等待被读取的已解密字节数。

 -- 屬性: SSLSocket.context

     此 SSL 套接字所联结的 *note SSLContext: 4e9. 对象。 如果 SSL 套接字
     是使用已弃用的 *note wrap_socket(): 570. 函数 (而非 *note
     SSLContext.wrap_socket(): 4ea.) 创建的，则这将是为此 SSL 套接字创建
     的自定义上下文对象。

     3.2 版新加入.

 -- 屬性: SSLSocket.server_side

     一个布尔值，对于服务器端套接字为 ‘True’ 而对于客户端套接字则为
     ‘False’。

     3.2 版新加入.

 -- 屬性: SSLSocket.server_hostname

     服务器的主机名: *note str: 205. 类型，对于服务器端套接字或者如果构
     造器中未指定主机名则为 ‘None’。

     3.2 版新加入.

     3.7 版更變: 现在该属性将始终为 ASCII 文本。 当 ‘server_hostname’ 为
     一个国际化域名（IDN）时，该属性现在会保存为 A 标签形式
     (‘"xn--pythn-mua.org"’) 而非 U 标签形式 (‘"pythön.org"’)。

 -- 屬性: SSLSocket.session

     用于 SSL 连接的 *note SSLSession: 682.。 该会话将在执行 TLS 握手后
     对客户端和服务器端套接字可用。 对于客户端套接字该会话可以在调用
     *note do_handshake(): 849. 之前被设置以重用一个会话。

     3.6 版新加入.

 -- 屬性: SSLSocket.session_reused

     3.6 版新加入.

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc3280.html

   (2) https://tools.ietf.org/html/rfc5929.html


File: python.info,  Node: SSL 上下文,  Next: 证书,  Prev: SSL 套接字,  Up: ssl --- 套接字对象的 TLS/SSL 包装器

5.18.3.9 SSL 上下文
...................

3.2 版新加入.

SSL 上下文可保存各种比单独 SSL 连接寿命更长的数据，例如 SSL 配置选项，证
书和私钥等。 它还可为服务器端套接字管理缓存，以加快来自相同客户端的重复
连接。

 -- 類別: ssl.SSLContext (protocol=PROTOCOL_TLS)

     创建一个新的 SSL 上下文。 你可以传入 `protocol'，它必须为此模块中定
     义的 ‘PROTOCOL_*’ 常量之一。 该形参指定要使用哪个 SSL 协议版本。 通
     常，服务器会选择一个特定的协议版本，而客户端必须适应服务器的选择。
     大多数版本都不能与其他版本互操作。 如果未指定，则默认值为 *note
     PROTOCOL_TLS: 27f7.；它提供了与其他版本的最大兼容性。

     这个表显示了客户端（横向）的哪个版本能够连接服务器（纵向）的哪个版
     本。

          `客户端' / `服务器'          `SSLv2'          `SSLv3'          `TLS' (1)         `TLSv1'       `TLSv1.1'       `TLSv1.2'
                                                                                                                         
                                                                                                                         
          `SSLv2'                      是               否               否 (2)            否            否              否
                                                                                                                         
                                                                                                                         
          `SSLv3'                      否               是               否 (3)            否            否              否
                                                                                                                         
                                                                                                                         
          `TLS' (`SSLv23') (4)         否 (5)           否 (6)           是                是            是              是
                                                                                                                         
                                                                                                                         
          `TLSv1'                      否               否               是                是            否              否
                                                                                                                         
                                                                                                                         
          `TLSv1.1'                    否               否               是                否            是              否
                                                                                                                         
                                                                                                                         
          `TLSv1.2'                    否               否               是                否            否              是
                                                                                                                         

     脚注
     ....

     也參考
     ......

     *note create_default_context(): 9a7. 让 *note ssl: f3. 为特定目标选
     择安全设置。

     3.6 版更變: 上下文会使用安全默认值来创建。 默认设置的选项有 *note
     OP_NO_COMPRESSION: b6e, *note OP_CIPHER_SERVER_PREFERENCE: b73,
     *note OP_SINGLE_DH_USE: 2820, *note OP_SINGLE_ECDH_USE: 2821, *note
     OP_NO_SSLv2: c71. (except for *note PROTOCOL_SSLv2: 2818.) 和 *note
     OP_NO_SSLv3: 27f8. (except for *note PROTOCOL_SSLv3: 2809.)。 初始
     密码集列表只包含 ‘HIGH’ 密码，不包含 ‘NULL’ 密码和 ‘MD5’ 密码
     (*note PROTOCOL_SSLv2: 2818. 除外)。

*note SSLContext: 4e9. 对象具有以下方法和属性:

 -- 成員函式: SSLContext.cert_store_stats ()

     获取以字典表示的有关已加载的 X.509 证书数量，被标记为 CA 证书的
     X.509 证书数量以及证书吊销列表的统计信息。

     具有一个 CA 证书和一个其他证书的上下文示例:

          >>> context.cert_store_stats()
          {'crl': 0, 'x509_ca': 1, 'x509': 2}

     3.4 版新加入.

 -- 成員函式: SSLContext.load_cert_chain (certfile, keyfile=None,
          password=None)

     加载一个私钥及对应的证书。 `certfile' 字符串必须为以 PEM 格式表示的
     单个文件路径，该文件中包含证书以及确立证书真实性所需的任意数量的 CA
     证书。 如果存在 `keyfile' 字符串，它必须指向一个包含私钥的文件。 否
     则私钥也将从 `certfile' 中提取。 请参阅 *note 证书: 2844. 中的讨论
     来了解有关如何将证书存储至 `certfile' 的更多信息。

     `password' 参数可以是一个函数，调用时将得到用于解密私钥的密码。 它
     在私钥被加密且需要密码时才会被调用。 它调用时将不带任何参数，并且应
     当返回一个字符串、字节串或字节数组。 如果返回值是一个字符串，在用它
     解密私钥之前它将以 UTF-8 进行编码。 或者也可以直接将字符串、字节串
     或字节数组值作为 `password' 参数提供。 如果私钥未被加密且不需要密码
     则它将被忽略。

     如果未指定 `password' 参数且需要一个密码，将会使用 OpenSSL 内置的密
     码提示机制来交互式地提示用户输入密码。

     如果私钥不能匹配证书则会引发 *note SSLError: cda.。

     3.3 版更變: 新增可选参数 `password'。

 -- 成員函式: SSLContext.load_default_certs
          (purpose=Purpose.SERVER_AUTH)

     Load a set of default "certification authority" (CA) certificates
     from default locations.  On Windows it loads CA certs from the ‘CA’
     and ‘ROOT’ system stores.  On all systems it calls *note
     SSLContext.set_default_verify_paths(): 9a9.  In the future the
     method may load CA certificates from other locations, too.

     `purpose' 旗标指明要加载哪一类 CA 证书。 默认设置 *note
     Purpose.SERVER_AUTH: 9b2. 加载被标记且被信任用于 TLS Web 服务器验证
     （客户端套接字）的证书。 *note Purpose.CLIENT_AUTH: 9b3. 则加载用于
     在服务器端进行客户端证书验证的 CA 证书。

     3.4 版新加入.

 -- 成員函式: SSLContext.load_verify_locations (cafile=None,
          capath=None, cadata=None)

     当 *note verify_mode: 27f9. 不为 *note CERT_NONE: 280f. 时加载一组
     用于验证其他对等方证书的 "证书颁发机构" (CA) 证书。 必须至少指定
     `cafile' 或 `capath' 中的一个。

     此方法还可加载 PEM 或 DER 格式的证书吊销列表 (CRL)，为此必须正确配
     置 *note SSLContext.verify_flags: 9ac.。

     如果存在 `cafile' 字符串，它应为 PEM 格式的级联 CA 证书文件的路径。
     请参阅 *note 证书: 2844. 中的讨论来了解有关如何处理此文件中的证书的
     更多信息。

     如果存在 `capath' 字符串，它应为包含多个 PEM 格式的 CA 证书的目录的
     路径，并遵循 OpenSSL 专属布局(7)。

     如果存在 `cadata' 对象，它应为一个或多个 PEM 编码的证书的 ASCII 字
     符串或者 DER 编码的证书的 *note bytes-like object: 6df.。 与
     `capath' 一样 PEM 编码的证书之外的多余行会被忽略，但至少要有一个证
     书。

     3.4 版更變: 新增可选参数 `cadata'

 -- 成員函式: SSLContext.get_ca_certs (binary_form=False)

     获取已离开法人 "证书颁发机构" (CA) 证书列表。 如果 ‘binary_form’ 形
     参为 *note False: 48e. 则每个列表条目都是一个类似于 *note
     SSLSocket.getpeercert(): 9b7. 输出的字典。 在其他情况下此方法将返回
     一个 DER 编码的证书的列表。 返回的列表不包含来自 `capath' 的证书，
     除非 SSL 连接请求并加载了一个证书。

          備註: capath 目录中的证书不会被加载，除非它们已至少被使用过一
          次。

     3.4 版新加入.

 -- 成員函式: SSLContext.get_ciphers ()

     获取已启用密码的列表。 该列表将按密码的优先级排序。 参见 *note
     SSLContext.set_ciphers(): 280d.。

     示例:

          >>> 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}]

     在 OpenSSL 1.1 及更新的版本中密码字典会包含额外的字段:

          >>> 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'}]

     *note 可用性: 1491.: OpenSSL 1.0.2+。

     3.6 版新加入.

 -- 成員函式: SSLContext.set_default_verify_paths ()

     从构建 OpenSSL 库时定义的文件系统路径中加载一组默认的 "证书颁发机构
     " (CA) 证书。 不幸的是，没有一种简单的方式能知道此方法是否执行成功
     ：如果未找到任何证书也不会返回错误。 不过，当 OpenSSL 库是作为操作
     系统的一部分被提供时，它的配置应当是正确的。

 -- 成員函式: SSLContext.set_ciphers (ciphers)

     为使用此上下文创建的套接字设置可用密码。 它应当为 OpenSSL 密码列表
     格式(8) 的字符串。 如果没有可被选择的密码（由于编译时选项或其他配置
     禁止使用所指定的任何密码），则将引发 *note SSLError: cda.。

          備註: 在连接后，SSL 套接字的 *note SSLSocket.cipher(): 2743. 方
          法将给出当前所选择的密码。

          在默认情况下 OpenSSL 1.1.1 会启用 TLS 1.3 密码套件。 该套件不
          能通过 *note set_ciphers(): 280d. 来禁用。

 -- 成員函式: SSLContext.set_alpn_protocols (protocols)

     指定在 SSL/TLS 握手期间套接字应当通告的协议。 它应为由 ASCII 字符串
     组成的列表，例如 ‘['http/1.1', 'spdy/2']’，按首选顺序排列。 协议的
     选择将在握手期间发生，并依据 RFC 7301(9) 来执行。 在握手成功后，
     *note SSLSocket.selected_alpn_protocol(): 841. 方法将返回已达成一致
     的协议。

     如果 *note HAS_ALPN: 842. 为 ‘False’ 则此方法将引发 *note
     NotImplementedError: 704.。

     当双方都支持 ALPN 但不能就协议达成一致时 OpenSSL 1.1.0 至 1.1.0e 将
     中止并引发 *note SSLError: cda.。 1.1.0f+ 的行为类似于 1.0.2，*note
     SSLSocket.selected_alpn_protocol(): 841. 返回 None。

     3.5 版新加入.

 -- 成員函式: SSLContext.set_npn_protocols (protocols)

     指定在Specify which protocols the socket should advertise during
     the SSL/TLS 握手期间套接字应当通告的协议。 它应为由字符串组成的列表
     ，例如 ‘['http/1.1', 'spdy/2']’，按首选顺序排列。 协议的选择将在握
     手期间发生，并将依据 应用层协议协商(10) 来执行。 在握手成功后，
     *note SSLSocket.selected_npn_protocol(): 283e. 方法将返回已达成一致
     的协议。

     如果 *note HAS_NPN: 2828. 为 ‘False’ 则此方法将引发 *note
     NotImplementedError: 704.。

     3.3 版新加入.

 -- 屬性: SSLContext.sni_callback

     注册一个回调函数，当 TLS 客户端指定了一个服务器名称提示时，该回调函
     数将在 SSL/TLS 服务器接收到 TLS Client Hello 握手消息后被调用。 服
     务器名称提示机制的定义见 RFC 6066(11) section 3 - Server Name
     Indication。

     每个 ‘SSLContext’ 只能设置一个回调。 如果 `sni_callback' 被设置为
     ‘None’ 则会禁用回调。 对该函数的后续调用将禁用之前注册的回调。

     此回调函数将附带三个参数来调用；第一个参数是 *note ssl.SSLSocket:
     192.，第二个参数是代表客户端准备与之通信的服务器的字符串 (或者如果
     TLS Client Hello 不包含服务器名称则为 *note None: 203.) 而第三个参
     数是原来的 *note SSLContext: 4e9.。 服务器名称参数为文本形式。 对于
     国际化域名，服务器名称是一个 IDN A 标签 (‘"xn--pythn-mua.org"’)。

     此回调的一个典型用法是将 *note ssl.SSLSocket: 192. 的 *note
     SSLSocket.context: 283d. 属性修改为一个 *note SSLContext: 4e9. 类型
     的新对象，该对象代表与服务器相匹配的证书链。

     由于 TLS 连接处于早期协商阶段，因此仅能使用有限的方法和属性例如
     *note SSLSocket.selected_alpn_protocol(): 841. 和 *note
     SSLSocket.context: 283d.。 *note SSLSocket.getpeercert(): 9b7,
     *note SSLSocket.getpeercert(): 9b7, *note SSLSocket.cipher(): 2743.
     和 ‘SSLSocket.compress()’ 方法要求 TLS 连接已经过 TLS Client Hello
     因而将既不包含返回有意义的值，也不能安全地调用它们。

     `sni_callback' 函数必须返回 ‘None’ 以允许 TLS 协商继续进行。 如果想
     要 TLS 失败，则可以返回常量 *note ALERT_DESCRIPTION_*: 2830.。 其他
     返回值将导致 TLS 的致命错误 *note ALERT_DESCRIPTION_INTERNAL_ERROR:
     2830.。

     如果从 `sni_callback' 函数引发了异常，则 TLS 连接将终止并发出 TLS 致
     命警告消息 *note ALERT_DESCRIPTION_HANDSHAKE_FAILURE: 282f.。

     如果 OpenSSL library 库在构建时定义了 OPENSSL_NO_TLSEXT 则此方法将
     返回 *note NotImplementedError: 704.。

     3.7 版新加入.

 -- 屬性: SSLContext.set_servername_callback (server_name_callback)

     这是被保留用于向下兼容的旧式 API。 在可能的情况下，你应当改用 *note
     sni_callback: fba.。 给出的 `server_name_callback' 类似于
     `sni_callback'，不同之处在于当服务器主机名是 IDN 编码的国际化域名时
     ，`server_name_callback' 会接收到一个已编码的 U 标签
     (‘"pythön.org"’)。

     如果发生了服务器名称解码错误。 TLS 连接将终止并向客户端发出 *note
     ALERT_DESCRIPTION_INTERNAL_ERROR: 2830. 最严重 TLS 警告消息。

     3.4 版新加入.

 -- 成員函式: SSLContext.load_dh_params (dhfile)

     加载密钥生成参数用于 Diffie-Hellman (DH) 密钥交换。 使用 DH 密钥交
     换能以消耗（服务器和客户端的）计算资源为代价提升前向保密性。
     `dhfile' 参数应当为指向一个包含 PEM 格式的 DH 形参的文件的路径。

     此设置不会应用于客户端套接字。 你还可以使用 *note OP_SINGLE_DH_USE:
     2820. 选项来进一步提升安全性。

     3.3 版新加入.

 -- 成員函式: SSLContext.set_ecdh_curve (curve_name)

     为基于椭圆曲线的 Elliptic Curve-based Diffie-Hellman (ECDH) 密钥交
     换设置曲线名称。 ECDH 显著快于常规 DH 同时据信同样安全。
     `curve_name' 形参应为描述某个知名椭圆曲线的字符串，例如受到广泛支持
     的曲线 ‘prime256v1’。

     此设置不会应用于客户端套接字。 你还可以使用 *note
     OP_SINGLE_ECDH_USE: 2821. 选项来进一步提升安全性。

     如果 *note HAS_ECDH: 2826. 为 ‘False’ 则此方法将不可用。

     3.3 版新加入.

     也參考
     ......

     SSL/TLS 与完美的前向保密性(12)

          Vincent Bernat。

 -- 成員函式: SSLContext.wrap_socket (sock, server_side=False,
          do_handshake_on_connect=True, suppress_ragged_eofs=True,
          server_hostname=None, session=None)

     包装一个现有的 Python 套接字 `sock' 并返回一个 *note
     SSLContext.sslsocket_class: 2845. 的实例 (默认为 *note SSLSocket:
     192.)。 返回的 SSL 套接字会绑定上下文、设置以及证书。 `sock' 必须是
     一个 *note SOCK_STREAM: d52. 套接字；其他套接字类型不被支持。

     形参 ‘server_side’ 是一个布尔值，它标明希望从该套接字获得服务器端行
     为还是客户端行为。

     对于客户端套接字，上下文的构造会延迟执行；如果下层的套接字尚未连接
     ，上下文的构造将在对套接字调用 ‘connect()’ 之后执行。 对于服务器端
     套接字，如果套接字没有远端对等方，它会被视为一个监听套接字，并且服
     务器端 SSL 包装操作会在通过 ‘accept()’ 方法所接受的客户端连接上自动
     执行。 此方法可能会引发 *note SSLError: cda.。

     在客户端连接上，可选形参 `server_hostname' 指定所要连接的服务的主机
     名。 这允许单个服务器托管具有单独证书的多个基于 SSL 的服务，很类似
     于 HTTP 虚拟主机。 如果 `server_side' 为真值则指定
     `server_hostname' 将引发 *note ValueError: 16d.。

     形参 ‘do_handshake_on_connect’ 指明是否要在调用 ‘socket.connect()’
     之后自动执行 SSL 握手，还是要通过发起调用 *note
     SSLSocket.do_handshake(): 849. 方法让应用程序显式地调用它。 显式地
     调用 *note SSLSocket.do_handshake(): 849. 可给予程序对握手中所涉及
     的套接字 I/O 阻塞行为的控制。

     形参 ‘suppress_ragged_eofs’ 指明 ‘SSLSocket.recv()’ 方法应当如何从
     连接的另一端发送非预期的 EOF 信号。 如果指定为 *note True: 593. (默
     认值)，它将返回正常的 EOF (空字节串对象) 来响应从下层套接字引发的非
     预期的 EOF 错误；如果指定为 *note False: 48e.，它将向调用方引发异常
     。

     `session'，参见 *note session: 2841.。

     3.5 版更變: 总是允许传送 server_hostname，即使 OpenSSL 没有 SNI。

     3.6 版更變: 增加了 `session' 参数。

     3.7 版更變: 此方法返回 *note SSLContext.sslsocket_class: 2845. 的实
     例而非硬编码的 *note SSLSocket: 192.。

 -- 屬性: SSLContext.sslsocket_class

     *note SSLContext.wrap_socket(): 4ea. 的返回类型，默认为 *note
     SSLSocket: 192.。 该属性可以在类实例上被重载以便返回自定义的 *note
     SSLSocket: 192. 的子类。

     3.7 版新加入.

 -- 成員函式: SSLContext.wrap_bio (incoming, outgoing,
          server_side=False, server_hostname=None, session=None)

     包装 BIO 对象 `incoming' 和 `outgoing' 并返回一个 *note
     SSLContext.sslobject_class: 2846. (默认为 *note SSLObject: 4e8.) 的
     实例。 SSL 例程将从 BIO 中读取输入数据并将数据写入到 outgoing BIO。

     `server_side', `server_hostname' 和 `session' 形参具有与 *note
     SSLContext.wrap_socket(): 4ea. 中相同的含义。

     3.6 版更變: 增加了 `session' 参数。

     3.7 版更變: 此方法返回 *note SSLContext.sslobject_class: 2846. 的实
     例则非硬编码的 *note SSLObject: 4e8.。

 -- 屬性: SSLContext.sslobject_class

     *note SSLContext.wrap_bio(): 4eb. 的返回类型，默认为 *note
     SSLObject: 4e8.。 该属性可以在类实例上被重载以便返回自定义的 *note
     SSLObject: 4e8. 的子类。

     3.7 版新加入.

 -- 成員函式: SSLContext.session_stats ()

     获取由此上下文所创建或管理的 SSL 会话的相关统计信息。 返回将每个 信
     息片(13) 的名称映射到其数字值的字典。 例如，以下是自上下文被创建以
     来会话缓存中命中和未命中的总数:

          >>> stats = context.session_stats()
          >>> stats['hits'], stats['misses']
          (0, 0)

 -- 屬性: SSLContext.check_hostname

     是否要将匹配 *note SSLSocket.do_handshake(): 849. 中对等方证书的主
     机名。 该上下文的 *note verify_mode: 27f9. 必须被设为 *note
     CERT_OPTIONAL: 2811. 或 *note CERT_REQUIRED: 27fa.，并且你必须将
     `server_hostname' 传给 *note wrap_socket(): 4ea. 以便匹配主机名。 启
     用主机名检查会自动将 *note verify_mode: 27f9. 从 *note CERT_NONE:
     280f. 设为 *note CERT_REQUIRED: 27fa.。 只要启用了主机名检查就无法
     将其设回 *note CERT_NONE: 280f.。 *note PROTOCOL_TLS_CLIENT: 2810.
     协议默认启用主机名检查。 对于其他协议，则必须显式地启用主机名检查。

     示例:

          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))

     3.4 版新加入.

     3.7 版更變: 现在当主机名检查被启用且 *note verify_mode: 27f9. 为
     *note CERT_NONE: 280f. 时 *note verify_mode: 27f9. 会自动更改为
     *note CERT_REQUIRED: 27fa.。 在之前版本中同样的操作将失败并引发
     *note ValueError: 16d.。

          備註: 此特性要求 OpenSSL 0.9.8f 或更新的版本。

 -- 屬性: SSLContext.keylog_filename

     每当生成或接收到密钥时，将 TLS 密钥写入到一个密钥日志文件。 密钥日
     志文件的设计仅适用于调试目的。 文件的格式由 NSS 指明并为许多流量分
     析工具例如 Wireshark 所使用。 日志文件会以追加模式打开。 写入操作会
     在线程之间同步，但不会在进程之间同步。

     3.8 版新加入.

          備註: 此特性要求 OpenSSL 1.1.1 或更新的版本。

 -- 屬性: SSLContext.maximum_version

     一个代表所支持的最高 TLS 版本的 *note TLSVersion: 2833. 枚举成员。
     该值默认为 *note TLSVersion.MAXIMUM_SUPPORTED: 2835.。 这个属性对于
     *note PROTOCOL_TLS: 27f7, *note PROTOCOL_TLS_CLIENT: 2810. 和 *note
     PROTOCOL_TLS_SERVER: 2816. 以外的其他协议来说都是只读的。

     *note maximum_version: 4ed, *note minimum_version: 4ec. 和 *note
     SSLContext.options: 280c. 等属性都会影响上下文所支持的 SSL 和 TLS 版
     本。 这个实现不会阻止无效的组合。 例如一个 *note options: 280c. 为
     *note OP_NO_TLSv1_2: 281d. 而 *note maximum_version: 4ed. 设为
     *note TLSVersion.TLSv1_2: 2839. 的上下文将无法建立 TLS 1.2 连接。

          備註: 除非 ssl 模块使用 OpenSSL 1.1.0g 或更新的版本编译否则这
          个属性将不可用。

     3.7 版新加入.

 -- 屬性: SSLContext.minimum_version

     与 *note SSLContext.maximum_version: 4ed. 类似，区别在于它是所支持
     的最低版本或为 *note TLSVersion.MINIMUM_SUPPORTED: 2834.。

          備註: 除非 ssl 模块使用 OpenSSL 1.1.0g 或更新的版本编译否则这
          个属性将不可用。

     3.7 版新加入.

 -- 屬性: SSLContext.num_tickets

     控制 ‘TLS_PROTOCOL_SERVER’ 上下文的 TLS 1.3 会话凭据数量。 这个设置
     不会影响 TLS 1.0 到 1.2 连接。

          備註: 除非 ssl 模块使用 OpenSSL 1.1.1 或更新的版本编译否则这个
          属性将不可用。

     3.8 版新加入.

 -- 屬性: SSLContext.options

     一个代表此上下文中所启用的 SSL 选项集的整数。 默认值为 *note
     OP_ALL: 281a.，但你也可以通过在选项间进行 OR 运算来指定其他选项例如
     *note OP_NO_SSLv2: c71.。

          備註: 对于 0.9.8m 之前的 OpenSSL 版本，只能设置选项，而不能清
          除它们。 尝试（通过重置相应比特位）清除选项将会引发 *note
          ValueError: 16d.。

     3.6 版更變: *note SSLContext.options: 280c. 返回 *note Options:
     2823. 旗标:

          >>> ssl.create_default_context().options
          <Options.OP_ALL|OP_NO_SSLv3|OP_NO_SSLv2|OP_NO_COMPRESSION: 2197947391>

 -- 屬性: SSLContext.post_handshake_auth

     启用 TLS 1.3 握手后客户端身份验证。 握手后验证默认是被禁用的，服务
     器只能在初始握手期间请求 TLS 客户端证书。 当启用时，服务器可以在握
     手之后的任何时候请求 TLS 客户端证书。

     当在客户端套接字上启用时，客户端会向服务器发信号说明它支持握手后身
     份验证。

     当在服务器端套接字上启用时，*note SSLContext.verify_mode: 27f9. 也
     必须被设为 *note CERT_OPTIONAL: 2811. 或 *note CERT_REQUIRED:
     27fa.。 实际的客户端证书交换会被延迟直至 *note
     SSLSocket.verify_client_post_handshake(): 352. 被调用并执行了一些
     I/O 操作后再进行。

          備註: 仅在 OpenSSL 1.1.1 且 TLS 1.3 被启用时可用。 如果没有
          TLS 1.3 支持，该属性值将为 None 且不可被更改

     3.8 版新加入.

 -- 屬性: SSLContext.protocol

     构造上下文时所选择的协议版本。 这个属性是只读的。

 -- 屬性: SSLContext.hostname_checks_common_name

     在没有目标替代名称扩展的情况下 *note check_hostname: 2812. 是否要回
     退为验证证书的通用名称（默认为真值）。

          備註: 仅在 OpenSSL 1.1.0 或更新的版本上可写。

     3.7 版新加入.

     3.9.3 版更變: 此旗标在 OpenSSL 1.1.1k 之前的版本上不起作用。 Python
     3.8.9, 3.9.3, 和 3.10 包含了针对之前版本的变通处理。

 -- 屬性: SSLContext.verify_flags

     证书验证操作的旗标。 你可以通过对 *note VERIFY_CRL_CHECK_LEAF: 9ae.
     等值执行 OR 运算来设置组合旗标。 在默认情况下 OpenSSL 不会要求也不
     会验证证书吊销列表（CRL）。 仅在 openssl 版本 0.9.8+ 上可用。

     3.4 版新加入.

     3.6 版更變: *note SSLContext.verify_flags: 9ac. 返回 *note
     VerifyFlags: 2815. 旗标:

          >>> ssl.create_default_context().verify_flags
          <VerifyFlags.VERIFY_X509_TRUSTED_FIRST: 32768>

 -- 屬性: SSLContext.verify_mode

     是否要尝试验证其他对等方的证书以及如果验证失败应采取何种行为。 该属
     性值必须为 *note CERT_NONE: 280f, *note CERT_OPTIONAL: 2811. 或
     *note CERT_REQUIRED: 27fa. 之一。

     3.6 版更變: *note SSLContext.verify_mode: 27f9. 返回 *note
     VerifyMode: 2813. 枚举:

          >>> ssl.create_default_context().verify_mode
          <VerifyMode.CERT_REQUIRED: 2>

   ---------- Footnotes ----------

   (1) (3) TLS 1.3 协议在 OpenSSL >= 1.1.1 中设置 *note PROTOCOL_TLS:
27f7. 时可用。 没有专门针对 TLS 1.3 的 PROTOCOL 常量。

   (2) (1) *note SSLContext: 4e9. 默认设置 *note OP_NO_SSLv2: c71. 以禁
用 SSLv2。

   (3) (2) *note SSLContext: 4e9. 默认设置 *note OP_NO_SSLv3: 27f8. 以禁
用 SSLv3。

   (4) (3) TLS 1.3 协议在 OpenSSL >= 1.1.1 中设置 *note PROTOCOL_TLS:
27f7. 时可用。 没有专门针对 TLS 1.3 的 PROTOCOL 常量。

   (5) (1) *note SSLContext: 4e9. 默认设置 *note OP_NO_SSLv2: c71. 以禁
用 SSLv2。

   (6) (2) *note SSLContext: 4e9. 默认设置 *note OP_NO_SSLv3: 27f8. 以禁
用 SSLv3。

   (7) 
https://www.openssl.org/docs/manmaster/man3/SSL_CTX_load_verify_locations.html

   (8) https://www.openssl.org/docs/manmaster/man1/ciphers.html

   (9) https://tools.ietf.org/html/rfc7301.html

   (10) 
https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation

   (11) https://tools.ietf.org/html/rfc6066.html

   (12) 
https://vincent.bernat.im/en/blog/2011-ssl-perfect-forward-secrecy

   (13) 
https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_sess_number.html


File: python.info,  Node: 证书,  Next: 示例<24>,  Prev: SSL 上下文,  Up: ssl --- 套接字对象的 TLS/SSL 包装器

5.18.3.10 证书
..............

总的来说证书是公钥/私钥系统的一个组成部分。 在这个系统中，每 个 `主体'
(可能是一台机器、一个人或者一个组织) 都会分配到唯一的包含两部分的加密密
钥。 一部分密钥是公开的，称为 `公钥'；另一部分密钥是保密的，称为 `私钥
'。 这两个部分是互相关联的，就是说如果你用其中一个部分来加密一条消息，你
将能用并且 `只能' 用另一个部分来解密它。

在一个证书中包含有两个主体的相关信息。 它包含 `目标方' 的名称和目标方的
公钥。 它还包含由第二个主体 `颁发方' 所发布的声明：目标方的身份与他们所
宣称的一致，包含的公钥也确实是目标方的公钥。 颁发方的声明使用颁发方的私
钥进行签名，该私钥的内容只有颁发方自己才知道。 但是，任何人都可以找到颁
发方的公钥，用它来解密这个声明，并将其与证书中的其他信息进行比较来验证颁
发方声明的真实性。 证书还包含有关其有效期限的信息。 这被表示为两个字段，
即 "notBefore" 和 "notAfter"。

在 Python 中应用证书时，客户端或服务器可以用证书来证明自己的身份。 还可
以要求网络连接的另一方提供证书，提供的证书可以用于验证以满足客户端或服务
器的验证要求。 如果验证失败，连接尝试可被设置为引发一个异常。 验证是由下
层的 OpenSSL 框架来自动执行的；应用程序本身不必关注其内部的机制。 但是应
用程序通常需要提供一组证书以允许此过程的发生。

Python 使用文件来包含证书。 它们应当采用 "PEM" 格式 (参见 RFC 1422(1))，
这是一种带有头部行和尾部行的 base-64 编码包装形式:

     -----BEGIN CERTIFICATE-----
     ... (certificate in base64 PEM encoding) ...
     -----END CERTIFICATE-----

* Menu:

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

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc1422.html


File: python.info,  Node: 证书链,  Next: CA 证书,  Up: 证书

5.18.3.11 证书链
................

包含证书的 Python 文件可以包含一系列的证书，有时被称为 `证书链'。 这个证
书链应当以 "作为" 客户端或服务器的主体的专属证书打头，然后是证书颁发方的
证书，然后是 `上述' 证书的颁发方的证书，证书链就这样不断上溯直到你得到一
个 `自签名' 的证书，即具有相同目标方和颁发方的证书，有时也称为 `根证书
'。 在证书文件中这些证书应当被拼接为一体。 例如，假设我们有一个包含三个
证书的证书链，以我们的服务器证书打头，然后是为我们的服务器证书签名的证书
颁发机构的证书，最后是为证书颁发机构的证书颁发证书的机构的根证书:

     -----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-----


File: python.info,  Node: CA 证书,  Next: 合并的密钥和证书,  Prev: 证书链,  Up: 证书

5.18.3.12 CA 证书
.................

如果你想要求对连接的另一方的证书进行验证，你必须提供一个 "CA 证书" 文件
，其中包含了你愿意信任的每个颁发方的证书链。 同样地，这个文件的内容就是
这些证书链拼接在一起的结果。 为了进行验证，Python 将使用它在文件中找到的
第一个匹配的证书链。 可以通过调用 *note SSLContext.load_default_certs():
9b1. 来使用系统平台的证书文件，这可以由 *note create_default_context():
9a7. 自动完成。


File: python.info,  Node: 合并的密钥和证书,  Next: 自签名证书,  Prev: CA 证书,  Up: 证书

5.18.3.13 合并的密钥和证书
..........................

私钥往往与证书存储在相同的文件中；在此情况下，只需要将 ‘certfile’ 形参传
给 *note SSLContext.load_cert_chain(): b69. 和 *note wrap_socket():
570.。 如果私钥是与证书一起存储的，则它应当放在证书链的第一个证书之前:

     -----BEGIN RSA PRIVATE KEY-----
     ... (private key in base64 encoding) ...
     -----END RSA PRIVATE KEY-----
     -----BEGIN CERTIFICATE-----
     ... (certificate in base64 PEM encoding) ...
     -----END CERTIFICATE-----


File: python.info,  Node: 自签名证书,  Prev: 合并的密钥和证书,  Up: 证书

5.18.3.14 自签名证书
....................

如果你准备创建一个提供 SSL 加密连接服务的服务器，你需要为该服务获取一份
证书。 有许多方式可以获取合适的证书，例如从证书颁发机构购买。 另一种常见
做法是生成自签名证书。 生成自签名证书的最简单方式是使用 OpenSSL 软件包，
代码如下所示:

     % 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
     %

自签名证书的缺点在于它是它自身的根证书，因此不会存在于别人的已知（且信任
的）根证书缓存当中。


File: python.info,  Node: 示例<24>,  Next: 关于非阻塞套接字的说明,  Prev: 证书,  Up: ssl --- 套接字对象的 TLS/SSL 包装器

5.18.3.15 示例
..............

* Menu:

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


File: python.info,  Node: 检测 SSL 支持,  Next: 客户端操作,  Up: 示例<24>

5.18.3.16 检测 SSL 支持
.......................

要检测一个 Python 安装版中是否带有 SSL 支持，用户代码应当使用以下例程:

     try:
         import ssl
     except ImportError:
         pass
     else:
         ...  # do something that requires SSL support


File: python.info,  Node: 客户端操作,  Next: 服务器端操作,  Prev: 检测 SSL 支持,  Up: 示例<24>

5.18.3.17 客户端操作
....................

这个例子创建了一个 SSL 上下文并使用客户端套接字的推荐安全设置，包括自动
证书验证:

     >>> context = ssl.create_default_context()

如果你喜欢自行调整安全设置，你可能需要从头创建一个上下文（但是请请注意避
免不正确的设置）:

     >>> context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
     >>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt")

(这段代码假定你的操作系统将所有 CA 证书打包存放于
‘/etc/ssl/certs/ca-bundle.crt’；如果不是这样，你将收到报错信息，必须修改
此位置)

*note PROTOCOL_TLS_CLIENT: 2810. 协议配置用于证书验证和主机名验证的上下
文。 *note verify_mode: 27f9. 设为 *note CERT_REQUIRED: 27fa. 而 *note
check_hostname: 2812. 设为 ‘True’。 所有其他协议都会使用不安全的默认值创
建 SSL 上下文。

当你使用此上下文去连接服务器时，*note CERT_REQUIRED: 27fa. 和 *note
check_hostname: 2812. 会验证服务器证书；它将确认服务器证书使用了某个 CA
证书进行签名，检查签名是否正确，并验证其他属性例如主机名的有效性和身份真
实性:

     >>> conn = context.wrap_socket(socket.socket(socket.AF_INET),
     ...                            server_hostname="www.python.org")
     >>> conn.connect(("www.python.org", 443))

你可以随后获取该证书:

     >>> cert = conn.getpeercert()

可视化检查显示证书能够证明目标服务 (即 HTTPS 主机 ‘www.python.org’) 的身
份:

     >>> 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}

现在 SSL 通道已建立并已验证了证书，你可以继续与服务器对话了:

     >>> 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'',
      b'']

参见下文对于 *note 安全考量: 26fd. 的讨论。


File: python.info,  Node: 服务器端操作,  Prev: 客户端操作,  Up: 示例<24>

5.18.3.18 服务器端操作
......................

对于服务器操作，通常你需要在文件中存放服务器证书和私钥各一份。 你将首先
创建一个包含密钥和证书的上下文，这样客户端就能检查你的身份真实性。 然后
你将打开一个套接字，将其绑定到一个端口，在其上调用 ‘listen()’，并开始等
待客户端连接:

     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.mydomain.com', 10023))
     bindsocket.listen(5)

当有客户端连接时，你将在套接字上调用 ‘accept()’ 以从另一端获取新的套接字
，并使用上下文的 *note SSLContext.wrap_socket(): 4ea. 方法来为连接创建一
个服务器端 SSL 套接字:

     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()

随后你将从 ‘connstream’ 读取数据并对其进行处理，直至你结束与客户端的会话
（或客户端结束与你的会话）:

     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

并返回至监听新的客户端连接（当然，真正的服务器应当会在单独的线程中处理每
个客户端连接，或者将套接字设为 *note 非阻塞模式: 27fe. 并使用事件循环）
。


File: python.info,  Node: 关于非阻塞套接字的说明,  Next: 内存 BIO 支持<2>,  Prev: 示例<24>,  Up: ssl --- 套接字对象的 TLS/SSL 包装器

5.18.3.19 关于非阻塞套接字的说明
................................

在非阻塞模式下 SSL 套接字的行为与常规套接字略有不同。 当使用非阻塞模式时
，你需要注意下面这些事情:

   - 如果一个 I/O 操作会阻塞，大多数 *note SSLSocket: 192. 方法都将引发
     *note SSLWantWriteError: 846. 或 *note SSLWantReadError: 845. 而非
     *note BlockingIOError: a78.。 如果有必要在下层套接字上执行读取操作
     将引发 *note SSLWantReadError: 845.，在下层套接字上执行写入操作则将
     引发 *note SSLWantWriteError: 846.。 请注意尝试 `写入' 到 SSL 套接
     字可能需要先从下层套接字 `读取'，而尝试从 SSL 套接字 `读取' 则可能
     需要先向下层套接字 `写入'。

     3.5 版更變: 在较早的 Python 版本中，‘SSLSocket.send()’ 方法会返回零
     值而非引发 *note SSLWantWriteError: 846. 或 *note SSLWantReadError:
     845.。

   - 调用 *note select(): 766. 将告诉你可以从 OS 层级的套接字读取（或向
     其写入），但这并不意味着在上面的 SSL 层有足够的数据。 例如，可能只
     有部分 SSL 帧已经到达。 因此，你必须准备好处理 ‘SSLSocket.recv()’ 和
     ‘SSLSocket.send()’ 失败的情况，并在再次调用 *note select(): 766. 之
     后重新尝试。

   - 相反地，由于 SSL 层具有自己的帧机制，一个 SSL 套接字可能仍有可读取
     的数据而 *note select(): 766. 并不知道这一点。 因此，你应当先调用
     ‘SSLSocket.recv()’ 取走所有潜在的可用数据，然后只在必要时对 *note
     select(): 766. 调用执行阻塞。

     (当然，类似的保留规则在使用其他原语例如 *note poll(): 2854.，或
     *note selectors: e6. 模块中的原语时也适用)

   - SSL 握手本身将是非阻塞的: *note SSLSocket.do_handshake(): 849. 方法
     必须不断重试直至其成功返回。 下面是一个使用 *note select(): 766. 来
     等待套接字就绪的简短例子:

          while True:
              try:
                  sock.do_handshake()
                  break
              except ssl.SSLWantReadError:
                  select.select([sock], [], [])
              except ssl.SSLWantWriteError:
                  select.select([], [sock], [])

也參考
......

*note asyncio: 9. 模块支持 *note 非阻塞 SSL 套接字: 27fe. 并提供了更高层
级的 API。 它会使用 *note selectors: e6. 模块来轮询事件并处理 *note
SSLWantWriteError: 846, *note SSLWantReadError: 845. 和 *note
BlockingIOError: a78. 等异常。 它还会异步地执行 SSL 握手。


File: python.info,  Node: 内存 BIO 支持<2>,  Next: SSL 会话,  Prev: 关于非阻塞套接字的说明,  Up: ssl --- 套接字对象的 TLS/SSL 包装器

5.18.3.20 内存 BIO 支持
.......................

3.5 版新加入.

自从 SSL 模块在 Python 2.6 起被引入之后，*note SSLSocket: 192. 类提供了
两个互相关联但彼此独立的功能分块:

   - SSL 协议处理

   - 网络 IO

网络 IO API 与 *note socket.socket: 767. 所提供的功能一致，*note
SSLSocket: 192. 也是从那里继承而来的。 这允许 SSL 套接字被用作常规套接字
的替代，使得向现有应用程序添加 SSL 支持变得非常容易。

将 SSL 协议处理与网络 IO 结合使用通常都能运行良好，但在某些情况下则不能
。 此情况的一个例子是 async IO 框架，该框架要使用不同的 IO 多路复用模型
而非 (基于就绪状态的) "在文件描述器上执行选择/轮询" 模型，该模型是 *note
socket.socket: 767. 和内部 OpenSSL 套接字 IO 例程正常运行的假设前提。 这
种情况在该模型效率不高的 Windows 平台上最为常见。 为此还提供了一个 *note
SSLSocket: 192. 的简化形式，称为 *note SSLObject: 4e8.。

 -- 類別: ssl.SSLObject

     *note SSLSocket: 192. 的简化形式，表示一个不包含任何网络 IO 方法的
     SSL 协议实例。 这个类通常由想要通过内存缓冲区为 SSL 实现异步 IO 的
     框架作者来使用。

     这个类在低层级 SSL 对象上实现了一个接口，与 OpenSSL 所实现的类似。
     此对象会捕获 SSL 连接的状态但其本身不提供任何网络 IO。 IO 需要通过
     单独的 "BIO" 对象来执行，该对象是 OpenSSL 的 IO 抽象层。

     这个类没有公有构造器。 *note SSLObject: 4e8. 实例必须使用 *note
     wrap_bio(): 4eb. 方法来创建。 此方法将创建 *note SSLObject: 4e8. 实
     例并将其绑定到一个 BIO 对。 其中 `incoming' BIO 用来将数据从 Python
     传递到 SSL 协议实例，而 `outgoing' BIO 用来进行数据反向传递。

     可以使用以下方法：

        - *note context: 283d.

        - *note server_side: 2840.

        - *note server_hostname: 4e6.

        - *note session: 2841.

        - *note session_reused: 2842.

        - *note read(): 84a.

        - *note write(): 84b.

        - *note getpeercert(): 9b7.

        - *note selected_alpn_protocol(): 841.

        - *note selected_npn_protocol(): 283e.

        - *note cipher(): 2743.

        - *note shared_ciphers(): 848.

        - *note compression(): b6d.

        - *note pending(): 283f.

        - *note do_handshake(): 849.

        - *note verify_client_post_handshake(): 352.

        - *note unwrap(): 283c.

        - *note get_channel_binding(): b6c.

        - *note version(): 844.

     与 *note SSLSocket: 192. 相比，此对象缺少下列特性:

        - 任何形式的网络 IO; ‘recv()’ 和 ‘send()’ 仅对下层的 *note
          MemoryBIO: 83e. 缓冲区执行读取和写入。

        - 不存在 `do_handshake_on_connect' 机制。 你必须总是手动调用
          *note do_handshake(): 849. 来开始握手操作。

        - 不存在对 `suppress_ragged_eofs' 的处理。 所有违反协议的文件结
          束条件将通过 *note SSLEOFError: 2800. 异常来报告。

        - 方法 *note unwrap(): 283c. 的调用不返回任何东西，不会如 SSL 套
          接字那样返回下层的套接字。

        - `server_name_callback' 回调被传给 *note
          SSLContext.set_servername_callback(): 9b6. 时将获得一个 *note
          SSLObject: 4e8. 实例而非 *note SSLSocket: 192. 实例作为其第一
          个形参。

     有关 *note SSLObject: 4e8. 用法的一些说明:

        - 在 *note SSLObject: 4e8. 上的所有 IO 都是 *note 非阻塞的:
          27fe.。 这意味着例如 *note read(): 84a. 在其需要比 incoming
          BIO 可用的更多数据时将会引发 *note SSLWantReadError: 845.。

        - 不存在模块层级的 ‘wrap_bio()’ 调用，就像 *note wrap_socket():
          4ea. 那样。 *note SSLObject: 4e8. 总是通过 *note SSLContext:
          4e9. 来创建。

     3.7 版更變: *note SSLObject: 4e8. 的实例必须使用 *note wrap_bio():
     4eb. 来创建。 在较早的版本中，直接创建实例是可能的。 但这从未被记入
     文档或是被正式支持。

SSLObject 会使用内存缓冲区与外部世界通信。 *note MemoryBIO: 83e. 类提供
了可被用于此目的的内存缓冲区。 它包装了一个 OpenSSL 内存 BIO (Basic IO)
对象:

 -- 類別: ssl.MemoryBIO

     一个可被用来在 Python 和 SSL 协议实例之间传递数据的内存缓冲区。

      -- 屬性: pending

          返回当前存在于内存缓冲区的字节数。

      -- 屬性: eof

          一个表明内存 BIO 目前是否位于文件末尾的布尔值。

      -- 成員函式: read (n=-1)

          从内存缓冲区读取至多 `n' 个字节。 如果 `n' 未指定或为负值，则
          返回全部字节数据。

      -- 成員函式: write (buf)

          将字节数据从 `buf' 写入到内存 BIO。 `buf' 参数必须为支持缓冲区
          协议的对象。

          返回值为写入的字节数，它总是与 `buf' 的长度相等。

      -- 成員函式: write_eof ()

          将一个 EOF 标记写入到内存 BIO。 在此方法被调用以后，再调用
          *note write(): 2859. 将是非法的。 属性 *note eof: 2857. will 在
          缓冲区当前的所有数据都被读取之后将变为真值。


File: python.info,  Node: SSL 会话,  Next: 安全考量<2>,  Prev: 内存 BIO 支持<2>,  Up: ssl --- 套接字对象的 TLS/SSL 包装器

5.18.3.21 SSL 会话
..................

3.6 版新加入.

 -- 類別: ssl.SSLSession

     *note session: 2841. 所使用的会话对象。

      -- 屬性: id

      -- 屬性: time

      -- 屬性: timeout

      -- 屬性: ticket_lifetime_hint

      -- 屬性: has_ticket


File: python.info,  Node: 安全考量<2>,  Next: TLS 1 3,  Prev: SSL 会话,  Up: ssl --- 套接字对象的 TLS/SSL 包装器

5.18.3.22 安全考量
..................

* Menu:

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


File: python.info,  Node: 最佳默认值,  Next: 手动设置,  Up: 安全考量<2>

5.18.3.23 最佳默认值
....................

针对 `客户端使用'，如果你对于安全策略没有任何特殊要求，则强烈推荐你使用
*note create_default_context(): 9a7. 函数来创建你的 SSL 上下文。 它将加
载系统的受信任 CA 证书，启用证书验证和主机名检查，并尝试合理地选择安全的
协议和密码设置。

例如，以下演示了你应当如何使用 *note smtplib.SMTP: 1de. 类来创建指向一个
SMTP 服务器的受信任且安全的连接:

     >>> 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')

如果连接需要客户端证书，可使用 *note SSLContext.load_cert_chain(): b69.
来添加。

作为对比，如果你通过自行调用 *note SSLContext: 4e9. 构造器来创建 SSL 上
下文，它默认将不会启用证书验证和主机名检查。 如果你这样做，请阅读下面的
段落以达到良好的安全级别。


File: python.info,  Node: 手动设置,  Next: 多进程,  Prev: 最佳默认值,  Up: 安全考量<2>

5.18.3.24 手动设置
..................

* Menu:

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


File: python.info,  Node: 验证证书,  Next: 协议版本,  Up: 手动设置

5.18.3.25 验证证书
..................

当直接调用 *note SSLContext: 4e9. 构造器时，默认会使用 *note CERT_NONE:
280f.。 由于它不会验证对等方的身份真实性，因此是不安全的，特别是在客户端
模式下，大多数时候你都希望能保证你所连接的服务器的身份真实性。 因此，当
处于客户端模式时，强烈推荐使用 *note CERT_REQUIRED: 27fa.。 但是，光这样
还不够；你还必须检查服务器证书，这可以通过调用 *note
SSLSocket.getpeercert(): 9b7. 来获取并匹配目标服务。 对于许多协议和应用
来说，服务可通过主机名来标识；在此情况下，可以使用 *note
match_hostname(): 4e2. 函数。 这种通用检测会在 *note
SSLContext.check_hostname: 2812. 被启用时自动执行。

3.7 版更變: 主机名匹配现在是由 OpenSSL 来执行的。 Python 不会再使用
*note match_hostname(): 4e2.。

在服务器模式下，如果你想要使用 SSL 层来验证客户端（而不是使用更高层级的
验证机制），你也必须要指定 *note CERT_REQUIRED: 27fa. 并以类似方式检查客
户端证书。


File: python.info,  Node: 协议版本,  Next: 密码选择,  Prev: 验证证书,  Up: 手动设置

5.18.3.26 协议版本
..................

SSL 版本 2 和 3 被认为是不安全的因而使用它们会有风险。 如果你想要客户端
和服务器之间有最大的兼容性，推荐使用 *note PROTOCOL_TLS_CLIENT: 2810. 或
*note PROTOCOL_TLS_SERVER: 2816. 作为协议版本。 SSLv2 和 SSLv3 默认会被
禁用。

     >>> client_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
     >>> client_context.options |= ssl.OP_NO_TLSv1
     >>> client_context.options |= ssl.OP_NO_TLSv1_1

前面创建的 SSL 上下文将只允许 TLSv1.2 及更新版本（如果你的系统支持）的服
务器连接。 *note PROTOCOL_TLS_CLIENT: 2810. 默认会使用证书验证和主机名检
查。 你必须将证书加载到上下文中。


File: python.info,  Node: 密码选择,  Prev: 协议版本,  Up: 手动设置

5.18.3.27 密码选择
..................

如果你有更高级的安全要求，也可以通过 *note SSLContext.set_ciphers():
280d. 方法在协商 SSL 会话时对所启用的加密进行微调。 从 Python 3.2.3 开始
，ssl 默认会禁用某些较弱的加密，但你还可能希望进一步限制加密选项。 请确
保仔细阅读 OpenSSL 文档中有关 加密列表格式(1) 的部分。 如果你想要检查给
定的加密列表启用了哪些加密，可以使用 *note SSLContext.get_ciphers():
683. 或所在系统的 ‘openssl ciphers’ 命令。

   ---------- Footnotes ----------

   (1) 
https://www.openssl.org/docs/manmaster/man1/ciphers.html#CIPHER-LIST-FORMAT


File: python.info,  Node: 多进程,  Prev: 手动设置,  Up: 安全考量<2>

5.18.3.28 多进程
................

如果使用此模块作为多进程应用的一部分（例如使用 *note multiprocessing:
b7. 或 *note concurrent.futures: 21. 模块），请注意 OpenSSL 的内部随机数
字生成器并不能正确处理分支进程。 应用程序必须修改父进程的 PRNG 状态，如
果它们要使用任何包含 *note os.fork(): a42. 的 SSL 特性的话。 任何对
*note RAND_add(): 2806, *note RAND_bytes(): b67. 或 *note
RAND_pseudo_bytes(): b68. 都可以 做到这一点。


File: python.info,  Node: TLS 1 3,  Next: LibreSSL 支持,  Prev: 安全考量<2>,  Up: ssl --- 套接字对象的 TLS/SSL 包装器

5.18.3.29 TLS 1.3
.................

3.7 版新加入.

Python 通过 OpenSSL 1.1.1 提供了临时性和实验性的 TLS 1.3 支持。 这个新协
议的行为与之前版本的 TLS/SSL 略有不同。 某些新的 TLS 1.3 特性暂时还不可
用。

   - TLS 1.3 使用一组不同的加密套件集。 默认情况下所有 AES-GCM 和
     ChaCha20 加密套件都会被启用。 *note SSLContext.set_ciphers(): 280d.
     方法还不能启用或禁用任何 TLS 1.3 加密，但 *note
     SSLContext.get_ciphers(): 683. 会返回它们。

   - 会话凭据不再会作为初始握手的组成部分被发送而是以不同的方式来处理。
     *note SSLSocket.session: 2841. 和 *note SSLSession: 682. 与 TLS 1.3
     不兼容。

   - 客户端证书在初始握手期间也不会再被验证。 服务器可以在任何时候请求证
     书。 客户端会在它们从服务器发送或接收应用数据时处理证书请求。

   - 早期数据、延迟的 TLS 客户端证书请求、签名算法配置和密钥重生成等 TLS
     1.3 特性尚未被支持。


File: python.info,  Node: LibreSSL 支持,  Prev: TLS 1 3,  Up: ssl --- 套接字对象的 TLS/SSL 包装器

5.18.3.30 LibreSSL 支持
.......................

LibreSSL 是 OpenSSL 1.0.1 的一个分支。 ssl 模块包含对 LibreSSL 的有限支
持。 当 ssl 模块使用 LibreSSL 进行编译时某些特性将不可用。

   * LibreSSL >= 2.6.1 不再支持 NPN。 *note
     SSLContext.set_npn_protocols(): b6f. 和 *note
     SSLSocket.selected_npn_protocol(): 283e. 方法将不可用。

   * *note SSLContext.set_default_verify_paths(): 9a9. 会忽略环境变量
     ‘SSL_CERT_FILE’ 和 ‘SSL_CERT_PATH’，虽然 *note
     get_default_verify_paths(): 9a8. 仍然支持它们。

也參考
......

Class *note socket.socket: 767.

     下层 *note socket: ef. 类的文档

SSL/TLS 高强度加密：概述(1)

     Apache HTTP Server文档介绍

RFC 1422: 因特网电子邮件的隐私加强：第二部分：基于证书的密钥管理(2)

     Steve Kent

RFC 4086: 确保安全的随机性要求(3)

     Donald E., Jeffrey I. Schiller

RFC 5280: 互联网 X.509 公钥基础架构证书和证书吊销列表 (CRL) 配置文件(4)

     D. Cooper

RFC 5246: 传输层安全性 (TLS) 协议版本 1.2(5)

     T. Dierks et.  al.

RFC 6066: 传输层安全性 (TLS) 的扩展(6)

     D. Eastlake

IANA TLS: 传输层安全性 (TLS) 的参数(7)

     IANA

RFC 7525: 传输层安全性 (TLS) 和数据报传输层安全性 (DTLS) 的安全使用建议(8)

     IETF

Mozilla 的服务器端 TLS 建议(9)

     Mozilla

   ---------- Footnotes ----------

   (1) https://httpd.apache.org/docs/trunk/en/ssl/ssl_intro.html

   (2) https://tools.ietf.org/html/rfc1422.html

   (3) https://tools.ietf.org/html/rfc4086.html

   (4) https://tools.ietf.org/html/rfc5280.html

   (5) https://tools.ietf.org/html/rfc5246.html

   (6) https://tools.ietf.org/html/rfc6066.html

   (7) 
https://www.iana.org/assignments/tls-parameters/tls-parameters.xml

   (8) https://tools.ietf.org/html/rfc7525.html

   (9) https://wiki.mozilla.org/Security/Server_Side_TLS


File: python.info,  Node: select --- 等待 I/O 完成,  Next: selectors --- 高级 I/O 复用库,  Prev: ssl --- 套接字对象的 TLS/SSL 包装器,  Up: 网络和进程间通信

5.18.4 ‘select’ — 等待 I/O 完成
-------------------------------

__________________________________________________________________

该模块提供了对 ‘select()’ 和 ‘poll()’ 函数的访问，这些函数在大多数操作系
统中是可用的。在 Solaris 及其衍生版本上可用 ‘devpoll()’，在 Linux 2.5+ 上
可用 ‘epoll()’，在大多数 BSD 上可用 ‘kqueue()’。注意，在 Windows 上，本
模块仅适用于套接字；在其他操作系统上，本模块也适用于其他文件类型（特别地
，在 Unix 上也适用于管道）。本模块不能用于常规文件，不能检测出（自上次读
取文件后）文件是否有新数据写入。

     備註: *note selectors: e6. 模块是在 *note select: e5. 模块原型的基
     础上进行高级且高效的 I/O 复用。推荐用户改用 *note selectors: e6. 模
     块，除非用户希望对 OS 级的函数原型进行精确控制。

该模块定义以下内容：

 -- 例外: select.error

     一个被弃用的 *note OSError: 304. 的别名。

     3.3 版更變: 根据 PEP 3151(1)，这个类是 *note OSError: 304. 的别名。

 -- 函式: select.devpoll ()

     （仅支持 Solaris 及其衍生版本）返回一个 ‘/dev/poll’ 轮询对象，请参
     阅下方 *note /dev/poll 轮询对象: 286d. 获取 devpoll 对象所支持的方
     法。

     ‘devpoll()’ 对象与实例化时允许的文件描述符数量有关，如果在程序中降
     低了此数值，‘devpoll()’ 调用将失败。如果程序提高了此数值，
     ‘devpoll()’ 可能会返回一个不完整的活动文件描述符列表。

     新的文件描述符是 *note 不可继承的: 8e7.。

     3.3 版新加入.

     3.4 版更變: 新的文件描述符现在是不可继承的。

 -- 函式: select.epoll (sizehint=-1, flags=0)

     （仅支持 Linux 2.5.44 或更高版本）返回一个 edge poll 对象，该对象可
     作为 I/O 事件的边缘触发或水平触发接口。

     `sizehint' 指示 epoll 预计需要注册的事件数。它必须为正数，或为 ‘-1’
     以使用默认值。它仅在 ‘epoll_create1()’ 不可用的旧系统上会被用到，其
     他情况下它没有任何作用（尽管仍会检查其值）。

     `flags' 已经弃用且完全被忽略。但是，如果提供该值，则它必须是 ‘0’ 或
     ‘select.EPOLL_CLOEXEC’，否则会抛出 ‘OSError’ 异常。

     请参阅下方 *note 边缘触发和水平触发的轮询 (epoll) 对象: 286e. 获取
     epoll 对象所支持的方法。

     ‘epoll’ 对象支持上下文管理器：当在 *note with: 7da. 语句中使用时，
     新建的文件描述符会在运行至语句块结束时自动关闭。

     新的文件描述符是 *note 不可继承的: 8e7.。

     3.3 版更變: 增加了 `flags' 参数。

     3.4 版更變: 增加了对 *note with: 7da. 语句的支持。新的文件描述符现
     在是不可继承的。

     3.4 版後已棄用: `flags' 参数。现在默认采用 ‘select.EPOLL_CLOEXEC’ 标
     志。使用 *note os.set_inheritable(): 8e9. 来让文件描述符可继承。

 -- 函式: select.poll ()

     （部分操作系统不支持）返回一个 poll 对象，该对象支持注册和注销文件
     描述符，支持对描述符进行轮询以获取 I/O 事件。请参阅下方 *note Poll
     对象: 286f. 获取 poll 对象所支持的方法。

 -- 函式: select.kqueue ()

     （仅支持 BSD）返回一个内核队列对象，请参阅下方 *note Kqueue 对象:
     2871. 获取 kqueue 对象所支持的方法。

     新的文件描述符是 *note 不可继承的: 8e7.。

     3.4 版更變: 新的文件描述符现在是不可继承的。

 -- 函式: select.kevent (ident, filter=KQ_FILTER_READ, flags=KQ_EV_ADD,
          fflags=0, data=0, udata=0)

     （仅支持 BSD）返回一个内核事件对象，请参阅下方 *note Kevent 对象:
     2873. 获取 kevent 对象所支持的方法。

 -- 函式: select.select (rlist, wlist, xlist[, timeout])

     这是一个明白直观的 Unix ‘select()’ 系统调用接口。 前三个参数是由‘可
     等待对象’组成的序列：可以是代表文件描述符的整数，或是带有名为 *note
     fileno(): 2069. 的返回这样的整数的无形参方法的对象:

        * `rlist'：等待，直到可以开始读取

        * `wlist'：等待，直到可以开始写入

        * `xlist'：等待“异常情况”（请参阅当前系统的手册，以获取哪些情况
          称为异常情况）

     允许空的可迭代对象，但是否接受三个空的可迭代对象则取决于具体平台。
     （已知在 Unix 上可行但在 Windows 上不可行。） 可选的 `timeout' 参数
     以一个浮点数表示超时秒数。 当省略 `timeout' 参数时该函数将阻塞直到
     至少有一个文件描述符准备就绪。 超时值为零表示执行轮询且永不阻塞。

     返回值是三个列表，包含已就绪对象，返回的三个列表是前三个参数的子集
     。当超时时间已到且没有文件描述符就绪时，返回三个空列表。

     可迭代对象中可接受的对象类型有 Python *note 文件对象: c14. (例如
     ‘sys.stdin’ 以及 *note open(): 16f. 或 *note os.popen(): 3cb. 所返
     回的对象)，由 *note socket.socket(): 767. 返回的套接字对象等。 你也
     可以自定义一个 `wrapper' 类，只要它具有适当的 *note fileno(): 2069.
     方法（该方法要确实返回一个文件描述符，而不能只是一个随机整数）。

          備註: 
          Windows 上不接受文件对象，但接受套接字。在 Windows 上，底层的
          ‘select()’ 函数由 WinSock 库提供，且不处理不是源自 WinSock 的
          文件描述符。

     3.5 版更變: 现在，当本函数被信号中断时，重试超时将从头开始计时，不
     会抛出 *note InterruptedError: 74c. 异常。除非信号处理程序抛出异常
     （相关原理请参阅 PEP 475(2)）。

 -- 屬性: select.PIPE_BUF

     当一个管道已经被 *note select(): 766.、*note poll(): 2854. 或本模块
     中的某个接口报告为可写入时，可以在不阻塞该管道的情况下写入的最小字
     节数。它不适用于套接字等其他类型的文件类对象。

     POSIX 上须保证该值不小于 512。

     *note 可用性: 1491.: Unix

     3.2 版新加入.

* Menu:

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

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3151

   (2) https://www.python.org/dev/peps/pep-0475


File: python.info,  Node: /dev/poll 轮询对象,  Next: 边缘触发和水平触发的轮询 epoll 对象,  Up: select --- 等待 I/O 完成

5.18.4.1 ‘/dev/poll’ 轮询对象
.............................

Solaris 及其衍生版本具备 ‘/dev/poll’。‘select()’ 复杂度为 O（最高文件描
述符），‘poll()’ 为 O（文件描述符数量），而 ‘/dev/poll’ 为 O（活动的文件
描述符）。

‘/dev/poll’ 的行为与标准 ‘poll()’ 对象十分类似。

 -- 成員函式: devpoll.close ()

     关闭轮询对象的文件描述符。

     3.4 版新加入.

 -- 屬性: devpoll.closed

     如果轮询对象已关闭，则返回 ‘True’。

     3.4 版新加入.

 -- 成員函式: devpoll.fileno ()

     返回轮询对象的文件描述符对应的数字。

     3.4 版新加入.

 -- 成員函式: devpoll.register (fd[, eventmask])

     在轮询对象中注册文件描述符。这样，将来调用 *note poll(): 2854. 方法
     时将检查文件描述符是否有未处理的 I/O 事件。`fd' 可以是整数，也可以
     是带有 *note fileno(): 2069. 方法的对象（该方法返回一个整数）。文件
     对象已经实现了 ‘fileno()’，因此它们也可以用作参数。

     `eventmask' 是可选的位掩码，用于指定要检查的事件类型。这些常量与
     ‘poll()’ 对象所用的相同。本参数的默认值是常量 ‘POLLIN’、‘POLLPRI’ 和
     ‘POLLOUT’ 的组合。

          警告: 注册已注册过的文件描述符不会报错，但是结果是不确定的。正
          确的操作是先注销或直接修改它。与 ‘poll()’ 相比，这是一个重要的
          区别。

 -- 成員函式: devpoll.modify (fd[, eventmask])

     此方法先执行 *note unregister(): 2877. 后执行 *note register():
     2875.。直接执行此操作效率（稍微）高一些。

 -- 成員函式: devpoll.unregister (fd)

     删除轮询对象正在跟踪的某个文件描述符。与 *note register(): 2875. 方
     法类似，`fd' 可以是整数，也可以是带有 *note fileno(): 2069. 方法的
     对象（该方法返回一个整数）。

     尝试删除从未注册过的文件描述符将被安全地忽略。

 -- 成員函式: devpoll.poll ([timeout])

     轮询已注册的文件描述符的集合，并返回一个列表，列表可能为空，也可能
     有多个 ‘(fd, event)’ 二元组，其中包含了要报告事件或错误的描述符。
     `fd' 是文件描述符，`event' 是一个位掩码，表示该描述符所报告的事件 —
     ‘POLLIN’ 表示可以读取，‘POLLOUT’ 表示该描述符可以写入，依此类推。空
     列表表示调用超时，没有任何文件描述符报告事件。如果指定了 `timeout'，
     它将指定系统等待事件时，等待多长时间后返回（以毫秒为单位）。如果
     `timeout' 为空，-1 或 *note None: 203.，则本调用将阻塞，直到轮询对
     象发生事件为止。

     3.5 版更變: 现在，当本函数被信号中断时，重试超时将从头开始计时，不
     会抛出 *note InterruptedError: 74c. 异常。除非信号处理程序抛出异常
     （相关原理请参阅 PEP 475(1)）。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0475


File: python.info,  Node: 边缘触发和水平触发的轮询 epoll 对象,  Next: Poll 对象,  Prev: /dev/poll 轮询对象,  Up: select --- 等待 I/O 完成

5.18.4.2 边缘触发和水平触发的轮询 (epoll) 对象
..............................................

     ‘https://linux.die.net/man/4/epoll’

     `eventmask'

     常数                          意义
                                   
     ----------------------------------------------------------------------------------
                                   
     ‘EPOLLIN’                     可读
                                   
                                   
     ‘EPOLLOUT’                    可写
                                   
                                   
     ‘EPOLLPRI’                    紧急数据读取
                                   
                                   
     ‘EPOLLERR’                    在关联的文件描述符上有错误情况发生
                                   
                                   
     ‘EPOLLHUP’                    关联的文件描述符已挂起
                                   
                                   
     ‘EPOLLET’                     设置触发方式为边缘触发，默认为水平触发
                                   
                                   
     ‘EPOLLONESHOT’                设置 one-shot 模式。触发一次事件后，该描述符会在
                                   轮询对象内部被禁用。
                                   
                                   
     ‘EPOLLEXCLUSIVE’              当已关联的描述符发生事件时，仅唤醒一个 epoll 对象
                                   。默认（如果未设置此标志）是唤醒所有轮询该描述符
                                   的 epoll 对象。
                                   
                                   
     ‘EPOLLRDHUP’                  流套接字的对侧关闭了连接或关闭了写入到一半的连接
                                   。
                                   
                                   
     ‘EPOLLRDNORM’                 等同于 ‘EPOLLIN’
                                   
                                   
     ‘EPOLLRDBAND’                 可以读取优先数据带。
                                   
                                   
     ‘EPOLLWRNORM’                 等同于 ‘EPOLLOUT’
                                   
                                   
     ‘EPOLLWRBAND’                 可以写入优先级数据。
                                   
                                   
     ‘EPOLLMSG’                    忽略
                                   

     3.6 版新加入: 增加了 ‘EPOLLEXCLUSIVE’。仅支持 Linux Kernel 4.5 或更
     高版本。

 -- 成員函式: epoll.close ()

     关闭用于控制 epoll 对象的文件描述符。

 -- 屬性: epoll.closed

     如果 epoll 对象已关闭，则返回 ‘True’。

 -- 成員函式: epoll.fileno ()

     返回文件描述符对应的数字，该描述符用于控制 epoll 对象。

 -- 成員函式: epoll.fromfd (fd)

     根据给定的文件描述符创建 epoll 对象。

 -- 成員函式: epoll.register (fd[, eventmask])

     在 epoll 对象中注册一个文件描述符。

 -- 成員函式: epoll.modify (fd, eventmask)

     修改一个已注册的文件描述符。

 -- 成員函式: epoll.unregister (fd)

     从 epoll 对象中删除一个已注册的文件描述符。

     3.9 版更變: 此方法不会再忽略 *note EBADF: 22f. 错误。

 -- 成員函式: epoll.poll (timeout=None, maxevents=-1)

     等待事件发生，timeout 是浮点数，单位为秒。

     3.5 版更變: 现在，当本函数被信号中断时，重试超时将从头开始计时，不
     会抛出 *note InterruptedError: 74c. 异常。除非信号处理程序抛出异常
     （相关原理请参阅 PEP 475(1)）。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0475


File: python.info,  Node: Poll 对象,  Next: Kqueue 对象,  Prev: 边缘触发和水平触发的轮询 epoll 对象,  Up: select --- 等待 I/O 完成

5.18.4.3 Poll 对象
..................

大多数 Unix 系统支持 ‘poll()’ 系统调用，为服务器提供了更好的可伸缩性，使
服务器可以同时服务于大量客户端。‘poll()’ 的伸缩性更好，因为该调用内部仅
列出所关注的文件描述符，而 ‘select()’ 会构造一个 bitmap，在其中将所关注
的描述符所对应的 bit 打开，然后重新遍历整个 bitmap。因此 ‘select()’ 复杂
度是 O（最高文件描述符），而 ‘poll()’ 是 O（文件描述符数量）。

 -- 成員函式: poll.register (fd[, eventmask])

     在轮询对象中注册文件描述符。这样，将来调用 *note poll(): 2854. 方法
     时将检查文件描述符是否有未处理的 I/O 事件。`fd' 可以是整数，也可以
     是带有 *note fileno(): 2069. 方法的对象（该方法返回一个整数）。文件
     对象已经实现了 ‘fileno()’，因此它们也可以用作参数。

     `eventmask' 是可选的位掩码，用于指定要检查的事件类型，它可以是常量
     ‘POLLIN’、‘POLLPRI’ 和 ‘POLLOUT’ 的组合，如下表所述。如果未指定本参
     数，默认将会检查所有 3 种类型的事件。

     常数                    意义
                             
     -----------------------------------------------------------------------
                             
     ‘POLLIN’                有要读取的数据
                             
                             
     ‘POLLPRI’               有紧急数据需要读取
                             
                             
     ‘POLLOUT’               准备输出：写不会阻塞
                             
                             
     ‘POLLERR’               某种错误条件
                             
                             
     ‘POLLHUP’               挂起
                             
                             
     ‘POLLRDHUP’             流套接字的对侧关闭了连接，或关闭了写入到一半
                             的连接
                             
                             
     ‘POLLNVAL’              无效的请求：描述符未打开
                             

     注册已注册过的文件描述符不会报错，且等同于只注册一次该描述符。

 -- 成員函式: poll.modify (fd, eventmask)

     修改一个已注册的文件描述符，等同于 ‘register(fd, eventmask)’。尝试
     修改未注册的文件描述符会抛出 *note OSError: 304. 异常，错误码为
     ‘ENOENT’。

 -- 成員函式: poll.unregister (fd)

     删除轮询对象正在跟踪的某个文件描述符。与 *note register(): 287f. 方
     法类似，`fd' 可以是整数，也可以是带有 *note fileno(): 2069. 方法的
     对象（该方法返回一个整数）。

     尝试删除从未注册过的文件描述符会抛出 *note KeyError: 3e9. 异常。

 -- 成員函式: poll.poll ([timeout])

     轮询已注册的文件描述符的集合，并返回一个列表，列表可能为空，也可能
     有多个 ‘(fd, event)’ 二元组，其中包含了要报告事件或错误的描述符。
     `fd' 是文件描述符，`event' 是一个位掩码，表示该描述符所报告的事件 —
     ‘POLLIN’ 表示可以读取，‘POLLOUT’ 表示该描述符可以写入，依此类推。空
     列表表示调用超时，没有任何文件描述符报告事件。如果指定了 `timeout'，
     它将指定系统等待事件时，等待多长时间后返回（以毫秒为单位）。如果
     `timeout' 为空、负数 或 *note None: 203.，则本调用将阻塞，直到轮询
     对象发生事件为止。

     3.5 版更變: 现在，当本函数被信号中断时，重试超时将从头开始计时，不
     会抛出 *note InterruptedError: 74c. 异常。除非信号处理程序抛出异常
     （相关原理请参阅 PEP 475(1)）。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0475


File: python.info,  Node: Kqueue 对象,  Next: Kevent 对象,  Prev: Poll 对象,  Up: select --- 等待 I/O 完成

5.18.4.4 Kqueue 对象
....................

 -- 成員函式: kqueue.close ()

     关闭用于控制 kqueue 对象的文件描述符。

 -- 屬性: kqueue.closed

     如果 kqueue 对象已关闭，则返回 ‘True’。

 -- 成員函式: kqueue.fileno ()

     返回文件描述符对应的数字，该描述符用于控制 epoll 对象。

 -- 成員函式: kqueue.fromfd (fd)

     根据给定的文件描述符创建 kqueue 对象。

 -- 成員函式: kqueue.control (changelist, max_events[, timeout]) ->
          eventlist

     Kevent 的低级接口

        - changelist 必须是一个可迭代对象，迭代出 kevent 对象，否则置为
          ‘None’。

        - max_events 必须是 0 或一个正整数。

        - timeout 单位为秒（一般为浮点数），默认为 ‘None’，即永不超时。

     3.5 版更變: 现在，当本函数被信号中断时，重试超时将从头开始计时，不
     会抛出 *note InterruptedError: 74c. 异常。除非信号处理程序抛出异常
     （相关原理请参阅 PEP 475(1)）。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0475


File: python.info,  Node: Kevent 对象,  Prev: Kqueue 对象,  Up: select --- 等待 I/O 完成

5.18.4.5 Kevent 对象
....................

‘https://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2’

 -- 屬性: kevent.ident

     用于区分事件的标识值。其解释取决于筛选器，但该值通常是文件描述符。
     在构造函数中，该标识值可以是整数或带有 *note fileno(): 2069. 方法的
     对象。kevent 在内部存储整数。

 -- 屬性: kevent.filter

     内核筛选器的名称。

     常数                            意义
                                     
     ----------------------------------------------------------------------------------
                                     
     ‘KQ_FILTER_READ’                获取描述符，并在有数据可读时返回
                                     
                                     
     ‘KQ_FILTER_WRITE’               获取描述符，并在有数据可写时返回
                                     
                                     
     ‘KQ_FILTER_AIO’                 AIO 请求
                                     
                                     
     ‘KQ_FILTER_VNODE’               当在 `fflag' 中监视的一个或多个请求事件发生时返
                                     回
                                     
                                     
     ‘KQ_FILTER_PROC’                监视进程ID上的事件
                                     
                                     
     ‘KQ_FILTER_NETDEV’              Watch for events on a network device [not
                                     available on macOS]
                                     
                                     
     ‘KQ_FILTER_SIGNAL’              每当监视的信号传递到进程时返回
                                     
                                     
     ‘KQ_FILTER_TIMER’               建立一个任意的计时器
                                     

 -- 屬性: kevent.flags

     筛选器操作。

     常数                            意义
                                     
     ----------------------------------------------------------------------------------
                                     
     ‘KQ_EV_ADD’                     添加或修改事件
                                     
                                     
     ‘KQ_EV_DELETE’                  从队列中删除事件
                                     
                                     
     ‘KQ_EV_ENABLE’                  Permitscontrol() 返回事件
                                     
                                     
     ‘KQ_EV_DISABLE’                 禁用事件
                                     
                                     
     ‘KQ_EV_ONESHOT’                 在第一次发生后删除事件
                                     
                                     
     ‘KQ_EV_CLEAR’                   检索事件后重置状态
                                     
                                     
     ‘KQ_EV_SYSFLAGS’                内部事件
                                     
                                     
     ‘KQ_EV_FLAG1’                   内部事件
                                     
                                     
     ‘KQ_EV_EOF’                     筛选特定EOF条件
                                     
                                     
     ‘KQ_EV_ERROR’                   请参阅返回值
                                     

 -- 屬性: kevent.fflags

     筛选特定标志。

     ‘KQ_FILTER_READ’ 和 ‘KQ_FILTER_WRITE’ 筛选标志：

     常数                             意义
                                      
     ----------------------------------------------------------------------------------
                                      
     ‘KQ_NOTE_LOWAT’                  套接字缓冲区的低水线
                                      

     ‘KQ_FILTER_VNODE’ 筛选标志：

     常数                             意义
                                      
     ----------------------------------------------------------------------------------
                                      
     ‘KQ_NOTE_DELETE’                 已调用 `unlink()'
                                      
                                      
     ‘KQ_NOTE_WRITE’                  发生写入
                                      
                                      
     ‘KQ_NOTE_EXTEND’                 文件已扩展
                                      
                                      
     ‘KQ_NOTE_ATTRIB’                 属性已更改
                                      
                                      
     ‘KQ_NOTE_LINK’                   链接计数已更改
                                      
                                      
     ‘KQ_NOTE_RENAME’                 文件已重命名
                                      
                                      
     ‘KQ_NOTE_REVOKE’                 对文件的访问权限已被撤销
                                      

     ‘KQ_FILTER_PROC’ filter flags:

     常数                             意义
                                      
     ----------------------------------------------------------------------------------
                                      
     ‘KQ_NOTE_EXIT’                   进程已退出
                                      
                                      
     ‘KQ_NOTE_FORK’                   该进程调用了 `fork()'
                                      
                                      
     ‘KQ_NOTE_EXEC’                   进程已执行新进程
                                      
                                      
     ‘KQ_NOTE_PCTRLMASK’              内部筛选器标志
                                      
                                      
     ‘KQ_NOTE_PDATAMASK’              内部筛选器标志
                                      
                                      
     ‘KQ_NOTE_TRACK’                  跨 `fork()' 执行进程
                                      
                                      
     ‘KQ_NOTE_CHILD’                  在 `NOTE_TRACK' 的子进程上返回
                                      
                                      
     ‘KQ_NOTE_TRACKERR’               无法附加到子对象
                                      

     ‘KQ_FILTER_NETDEV’ filter flags (not available on macOS):

     常数                             意义
                                      
     ----------------------------------------------------------------------------------
                                      
     ‘KQ_NOTE_LINKUP’                 链接已建立
                                      
                                      
     ‘KQ_NOTE_LINKDOWN’               链接已断开
                                      
                                      
     ‘KQ_NOTE_LINKINV’                链接状态无效
                                      

 -- 屬性: kevent.data

     筛选特定数据。

 -- 屬性: kevent.udata

     用户自定义值。


File: python.info,  Node: selectors --- 高级 I/O 复用库,  Next: asyncore --- 异步套接字处理器,  Prev: select --- 等待 I/O 完成,  Up: 网络和进程间通信

5.18.5 ‘selectors’ — 高级 I/O 复用库
------------------------------------

3.4 版新加入.

`源码:' Lib/selectors.py(1)

__________________________________________________________________

* Menu:

* 簡介: 簡介<9>.
* 类: 类<2>.
* 示例: 示例<25>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/selectors.py


File: python.info,  Node: 簡介<9>,  Next: 类<2>,  Up: selectors --- 高级 I/O 复用库

5.18.5.1 簡介
.............

此模块允许高层级且高效率的 I/O 复用，它建立在 *note select: e5. 模块原型
的基础之上。 推荐用户改用此模块，除非他们希望对所使用的 OS 层级原型进行
精确控制。

它定义了一个 *note BaseSelector: 2891. 抽象基类，以及多个实际的实现
(*note KqueueSelector: 2795, *note EpollSelector: 54d...)，它们可被用于
在多个文件对象上等待 I/O 就绪通知。 在下文中，"文件对象" 是指任何具有
‘fileno()’ 方法的对象，或是一个原始文件描述器。 参见 *note file object:
c14.。

*note DefaultSelector: 2892. 是一个指向当前平台上可用的最高效实现的别名
：这应为大多数用户的默认选择。

     備註: 受支持的文件对象类型取决于具体平台：在 Windows 上，支持套接字
     但不支持管道，而在 Unix 上两者均受支持（某些其他类型也可能受支持，
     例如 fifo 或特殊文件设备等）。

也參考
......

*note select: e5.

     低层级的 I/O 多路复用模块。


File: python.info,  Node: 类<2>,  Next: 示例<25>,  Prev: 簡介<9>,  Up: selectors --- 高级 I/O 复用库

5.18.5.2 类
...........

类的层次结构:

     BaseSelector
     +-- SelectSelector
     +-- PollSelector
     +-- EpollSelector
     +-- DevpollSelector
     +-- KqueueSelector

下文中，`events' 一个位掩码，指明哪些 I/O 事件要在给定的文件对象上执行等
待。 它可以是以下模块级常量的组合:

     常量                        含意
                                 
     --------------------------------------------------------------------------------
                                 
     ‘EVENT_READ’                可读
                                 
                                 
     ‘EVENT_WRITE’               可写
                                 

 -- 類別: selectors.SelectorKey

     *note SelectorKey: 2894. 是一个 *note namedtuple: 1a1.，用来将文件
     对象关联到其下层的文件描述器、选定事件掩码和附加数据等。 它会被某些
     *note BaseSelector: 2891. 方法返回。

      -- 屬性: fileobj

          已注册的文件对象。

      -- 屬性: fd

          下层的文件描述器。

      -- 屬性: events

          必须在此文件对象上被等待的事件。

      -- 屬性: data

          可选的关联到此文件对象的不透明数据：例如，这可被用来存储各个客
          户端的会话 ID。

 -- 類別: selectors.BaseSelector

     一个 *note BaseSelector: 2891.，用来在多个文件对象上等待 I/O 事件就
     绪。 它支持文件流注册、注销，以及在这些流上等待 I/O 事件的方法。 它
     是一个抽象基类，因此不能被实例化。 请改用 *note DefaultSelector:
     2892.，或者 *note SelectSelector: 2792, *note KqueueSelector: 2795.
     等。 如果你想要指明使用某个实现，并且你的平台支持它的话。 *note
     BaseSelector: 2891. 及其具体实现支持 *note context manager: 661. 协
     议。

      -- 成員函式: abstractmethod register (fileobj, events, data=None)

          注册一个用于选择的文件对象，在其上监视 I/O 事件。

          `fileobj' 是要监视的文件对象。 它可以是整数形式的文件描述符或
          者具有 ‘fileno()’ 方法的对象。 `events' 是要监视的事件的位掩码
          。 `data' 是一个不透明对象。

          这将返回一个新的 *note SelectorKey: 2894. 实例，或在出现无效事
          件掩码或文件描述符时引发 *note ValueError: 16d.，或在文件对象
          已被注册时引发 *note KeyError: 3e9.。

      -- 成員函式: abstractmethod unregister (fileobj)

          注销对一个文件对象的选择，移除对它的监视。 在文件对象被关闭之
          前应当先将其注销。

          `fileobj' 必须是之前已注册的文件对象。

          这将返回已关联的 *note SelectorKey: 2894. 实例，或者如果
          `fileobj' 未注册则会引发 *note KeyError: 3e9.。 It will raise
          *note ValueError: 16d. 如果 `fileobj' 无效（例如它没有
          ‘fileno()’ 方法或其 ‘fileno()’ 方法返回无效值）。

      -- 成員函式: modify (fileobj, events, data=None)

          更改已注册文件对象所监视的事件或所附带的数据。

          这等价于 ‘BaseSelector.unregister(fileobj)()’ 加
          ‘BaseSelector.register(fileobj, events, data)()’，区别在于它可
          以被更高效地实现。

          这将返回一个新的 *note SelectorKey: 2894. 实例，或在出现无效事
          件掩码或文件描述符时引发 *note ValueError: 16d.，或在文件对象
          未被注册时引发 *note KeyError: 3e9.。

      -- 成員函式: abstractmethod select (timeout=None)

          等待直到有已注册的文件对象就绪，或是超过时限。

          如果 ‘timeout > 0’，这指定以秒数表示的最大等待时间。 如果
          ‘timeout <= 0’，调用将不会阻塞，并将报告当前就绪的文件对象。 如
          果 `timeout' 为 ‘None’，调用将阻塞直到某个被监视的文件对象就绪
          。

          这将返回由 ‘(key, events)’ 元组构成的列表，每项各表示一个就绪
          的文件对象。

          `key' 是对应于就绪文件对象的 *note SelectorKey: 2894. 实例。
          `events' 是在此文件对象上等待的事件位掩码。

               備註: 如果当前进程收到一个信号，此方法可在任何文件对象就
               绪之前或超出时限时返回：在此情况下，将返回一个空列表。

          3.5 版更變: 现在当被某个信号中断时，如果信号处理程序没有引发异
          常，选择器会用重新计算的超时值进行重试（请查看 PEP 475(1) 其理
          由），而不是在超时之前返回空的事件列表。

      -- 成員函式: close ()

          关闭选择器。

          必须调用这个方法以确保下层资源会被释放。 选择器被关闭后将不可
          再使用。

      -- 成員函式: get_key (fileobj)

          返回关联到某个已注册文件对象的键。

          此方法将返回关联到文件对象的 *note SelectorKey: 2894. 实例，或
          在文件对象未注册时引发 *note KeyError: 3e9.。

      -- 成員函式: abstractmethod get_map ()

          返回从文件对象到选择器键的映射。

          这将返回一个将已注册文件对象映射到与其相关联的 *note
          SelectorKey: 2894. 实例的 *note Mapping: 15f. 实例。

 -- 類別: selectors.DefaultSelector

     默认的选择器类，使用当前平台上可用的最高效实现。 这应为大多数用户的
     默认选择。

 -- 類別: selectors.SelectSelector

     基于 *note select.select(): 766. 的选择器。

 -- 類別: selectors.PollSelector

     基于 *note select.poll(): 2854. 的选择器。

 -- 類別: selectors.EpollSelector

     基于 *note select.epoll(): 990. 的选择器。

      -- 成員函式: fileno ()

          此方法将返回由下层 *note select.epoll(): 990. 对象所使用的文件
          描述符。

 -- 類別: selectors.DevpollSelector

     基于 *note select.devpoll(): 992. 的选择器。

      -- 成員函式: fileno ()

          此方法将返回由下层 *note select.devpoll(): 992. 对象所使用的文
          件描述符。

     3.5 版新加入.

 -- 類別: selectors.KqueueSelector

     基于 *note select.kqueue(): 2870. 的选择器。

      -- 成員函式: fileno ()

          此方法将返回由下层 *note select.kqueue(): 2870. 对象所使用的文
          件描述符。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0475


File: python.info,  Node: 示例<25>,  Prev: 类<2>,  Up: selectors --- 高级 I/O 复用库

5.18.5.3 示例
.............

下面是一个简单的回显服务器实现:

     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)


File: python.info,  Node: asyncore --- 异步套接字处理器,  Next: asynchat --- 异步套接字指令/响应处理程序,  Prev: selectors --- 高级 I/O 复用库,  Up: 网络和进程间通信

5.18.6 ‘asyncore’ — 异步套接字处理器
------------------------------------

`源码：' Lib/asyncore.py(1)

3.6 版後已棄用: 请使用 *note asyncio: 9. 替代。

__________________________________________________________________

     備註: 该模块仅为提供向后兼容。我们推荐在新代码中使用 *note asyncio:
     9. 。

该模块提供用于编写异步套接字服务客户端与服务端的基础构件。

只有两种方法让单个处理器上的程序“同一时间完成不止一件事”。 多线程编程是
最简单和最流行的方法，但是还有另一种非常不同的技术，它可以让你拥有多线程
的几乎所有优点，而无需实际使用多线程。 它仅仅在你的程序主要受 I/O 限制时
有用，那么。 如果你的程序受处理器限制，那么先发制人的预定线程可能就是你
真正需要的。 但是，网络服务器很少受处理器限制。

如果你的操作系统在其 I/O 库中支持 ‘select()’ 系统调用（几乎所有操作系统
），那么你可以使用它来同时处理多个通信通道；在 I/O 正在“后台”时进行其他
工作。 虽然这种策略看起来很奇怪和复杂，特别是起初，它在很多方面比多线程
编程更容易理解和控制。 *note asyncore: a. 模块为您解决了许多难题，使得构
建复杂的高性能网络服务器和客户端的任务变得轻而易举。 对于“会话”应用程序
和协议，伴侣 *note asynchat: 8. 模块是非常宝贵的。

这两个模块背后的基本思想是创建一个或多个网络 `通道' ，类的实例 *note
asyncore.dispatcher: c91. 和 *note asynchat.async_chat: 99c. 。 创建通道
会将它们添加到全局映射中，如果你不为它提供自己的 `映射' ，则由 *note
loop(): 28a5. 函数使用。

一旦创建了初始通道，调用 *note loop(): 28a5. 函数将激活通道服务，该服务
将一直持续到最后一个通道（包括在异步服务期间已添加到映射中的任何通道）关
闭。

 -- 函式: asyncore.loop ([timeout[, use_poll[, map[, count]]]])

     进入一个轮询循环，其在循环计数超出或所有打开的通道关闭后终止。 所有
     参数都是可选的。 `count' 形参默认为 ‘None’ ，导致循环仅在所有通道关
     闭时终止。 `timeout' 形参为适当的 *note select(): 766. 或 *note
     poll(): 2854. 调用设置超时参数，以秒为单位; 默认值为30秒。
     `use_poll' 形参，如果为 True ，则表示 *note poll(): 2854. 应优先使
     用 *note select(): 766. (默认为‘‘False‘‘)。

     `map' 形参是一个条目为所监视通道的字典。 当通道关闭时它们会被从映射
     中删除。 如果省略 `map'，则会使用一个全局映射。 通道 (*note
     asyncore.dispatcher: c91, *note asynchat.async_chat: 99c. 及其子类
     的实例) 可以在映射中任意混合。

 -- 類別: asyncore.dispatcher

     *note dispatcher: c91. 类是对低层级套接字对象的轻量包装器。 要让它
     更有用处，可以从异步循环调用一些事件处理方法。 在其他方面，它可以被
     当作是普通的非阻塞型套接字对象。

     在特定时间或特定连接状态下触发的低层级事件可通知异步循环发生了特定
     的高层级事件。 例如，如果我们请求了一个套接字以连接到另一台主机，我
     们会在套接字首次变得可写时得知连接已建立（在此刻你将知道可以向其写
     入并预期能够成功）。 包含的高层级事件有:

     事件                       描述
                                
     ------------------------------------------------------------------------
                                
     ‘handle_connect()’         由首个读取或写入事件引起
                                
                                
     ‘handle_close()’           由不带可用数据的读取事件引起
                                
                                
     ‘handle_accepted()’        由在监听套接字上的读取事件引起
                                

     在异步处理过程中，每个已映射通道的 *note readable(): 28a6. 和 *note
     writable(): 28a7. 方法会被用来确定是否要将通道的套接字添加到已执行
     ‘select()’ 或 ‘poll()’ 用于读取和写入事件的通道列表中。

     因此，通道事件的集合要大于基本套接字事件。 可以在你的子类中被重载的
     全部方法集合如下:

      -- 成員函式: handle_read ()

          当异步循环检测到通道的套接字上的 ‘read()’ 调用将要成功时会被调
          用。

      -- 成員函式: handle_write ()

          当异步循环检测到一个可写套接字可以被写入时会被调用。 通常此方
          法将实现必要的缓冲机制以保证运行效率。 例如:

               def handle_write(self):
                   sent = self.send(self.buffer)
                   self.buffer = self.buffer[sent:]

      -- 成員函式: handle_expt ()

          当一个套接字连接存在带外（OOB）数据时会被调用。 这几乎从来不会
          发生，因为 OOB 虽然受支持但很少被使用。

      -- 成員函式: handle_connect ()

          当活动打开方的套接字实际建立连接时会被调用。 可能会发送一条“欢
          迎”消息，或者向远程端点发起协议协商等。

      -- 成員函式: handle_close ()

          当套接字关闭时会被调用。

      -- 成員函式: handle_error ()

          当一个异常被引发并且未获得其他处理时会被调用。 默认版本将打印
          精简的回溯信息。

      -- 成員函式: handle_accept ()

          当可以与发起对本地端点的 *note connect(): 28ae. 调用的新远程端
          点建立连接时会在侦听通道（被动打开方）上被调用。 在 3.2 版中已
          被弃用；请改用 *note handle_accepted(): c92.。

          3.2 版後已棄用.

      -- 成員函式: handle_accepted (sock, addr)

          当与发起对本地端点的 *note connect(): 28ae. 调用的新远程端点已
          建立连接时会在侦听通道（被动打开方）上被调用。 `sock' 是可被用
          于在连接上发送和接收数据的 `新建' 套接字对象，而 `addr' 是绑定
          到连接另一端的套接字的地址。

          3.2 版新加入.

      -- 成員函式: readable ()

          每次在异步循环之外被调用以确定是否应当将一个通道的套接字添加到
          可能在其上发生读取事件的列表中。 默认方法会简单地返回 ‘True’，
          表示在默认情况下，所有通道都希望能读取事件。

      -- 成員函式: writable ()

          每次在异步循环之外被调用以确定是否应当将一个通道的套接字添加到
          可能在其上发生写入事件的列表中。 默认方法会简单地返回 ‘True’，
          表示在默认情况下，所有通道都希望能写入事件。

     此外，每个通道都委托或扩展了许多套接字方法。 它们大部分都与其套接字
     的对应方法几乎一样。

      -- 成員函式: create_socket (family=socket.AF_INET,
               type=socket.SOCK_STREAM)

          这与普通套接字的创建相同，并会使用同样的创建选项。 请参阅
          *note socket: ef. 文档了解有关创建套接字的信息。

          3.3 版更變: `family' 和 `type' 参数可以被省略。

      -- 成員函式: connect (address)

          与普通套接字对象一样，`address' 是一个元组，它的第一个元素是要
          连接的主机，第二个元素是端口号。

      -- 成員函式: send (data)

          将 `data' 发送到套接字的远程端点。

      -- 成員函式: recv (buffer_size)

          从套接字的远程端点读取至多 `buffer_size' 个字节。 读到空字节串
          表明通道已从另一端被关闭。

          请注意 *note recv(): 28b1. 可能会引发 *note BlockingIOError:
          a78.，即使 *note select.select(): 766. 或 *note select.poll():
          2854. 报告套接字已准备好被读取。

      -- 成員函式: listen (backlog)

          侦听与套接字的连接。 `backlog' 参数指明排入连接队列的最大数量
          且至少应为 1；最大值取决于具体系统（通常为 5）。

      -- 成員函式: bind (address)

          将套接字绑定到 `address'。 套接字必须尚未被绑定。 (`address' 的
          格式取决于具体的地址族 — 请参阅 *note socket: ef. 文档了解更多
          信息。) 要将套接字标记为可重用的 (设置 ‘SO_REUSEADDR’ 选项)，
          请调用 *note dispatcher: c91. 对象的 ‘set_reuse_addr()’ 方法。

      -- 成員函式: accept ()

          接受一个连接。 此套接字必须绑定到一个地址上并且侦听连接。 返回
          值可以是 ‘None’ 或一个 ‘(conn, address)’ 对，其中 `conn' 是一
          个可用来在此连接上发送和接收数据的 `新的' 套接字对象，而
          `address' 是绑定到连接另一端套接字的地址。 当返回 ‘None’ 时意
          味着连接没有建立，在此情况下服务器应当忽略此事件并继续侦听后续
          的入站连接。

      -- 成員函式: close ()

          关闭套接字。 在此套接字对象上的后续操作都将失败。 远程端点将不
          再接收任何数据（在排入队列的数据被清空之后）。 当套接字被垃圾
          回收时会自动关闭。

 -- 類別: asyncore.dispatcher_with_send

     *note dispatcher: c91. 的一个添加了简单缓冲输出功能的子类，适用于简
     单客户端。 对于更复杂的用法请使用 *note asynchat.async_chat: 99c.。

 -- 類別: asyncore.file_dispatcher

     file_dispatcher 接受一个文件描述符或 *note file object: c14. 以及一
     个可选的 map 参数，并对其进行包装以配合 ‘poll()’ 或 ‘loop()’ 函数使
     用。 如果提供一个文件对象或任何具有 ‘fileno()’ 方法的对象，其方法将
     被调用并传递给 *note file_wrapper: 28b7. 构造器。

     *note Availability: 1491.: Unix.

 -- 類別: asyncore.file_wrapper

     file_wrapper 接受一个整数形式的文件描述符并调用 *note os.dup():
     10e9. 来复制其句柄，以便原始句柄可以独立于 file_wrapper 被关闭。 这
     个类实现了足够的方法来模拟套接字以供 *note file_dispatcher: 28b6. 类
     使用。

     *note Availability: 1491.: Unix.

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/asyncore.py


File: python.info,  Node: asyncore 示例基本 HTTP 客户端,  Next: asyncore 示例基本回显服务器,  Up: asyncore --- 异步套接字处理器

5.18.6.1 asyncore 示例基本 HTTP 客户端
......................................

下面是一个非常基本的 HTTP 客户端，它使用了 *note dispatcher: c91. 类来实
现套接字处理:

     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()


File: python.info,  Node: asyncore 示例基本回显服务器,  Prev: asyncore 示例基本 HTTP 客户端,  Up: asyncore --- 异步套接字处理器

5.18.6.2 asyncore 示例基本回显服务器
....................................

下面是一个基本的回显服务器，它使用了 *note dispatcher: c91. 类来接受连接
并将入站连接发送给处理程序:

     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()


File: python.info,  Node: asynchat --- 异步套接字指令/响应处理程序,  Next: signal --- 设置异步事件处理程序,  Prev: asyncore --- 异步套接字处理器,  Up: 网络和进程间通信

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

`源代码:' Lib/asynchat.py(1)

3.6 版後已棄用: 请使用 *note asyncio: 9. 替代。

__________________________________________________________________

     備註: 该模块仅为提供向后兼容。我们推荐在新代码中使用 *note asyncio:
     9. 。

此模块在 *note asyncore: a. 框架之上构建，简化了异步客户端和服务器并使得
处理元素为以任意字符串结束或者为可变长度的协议更加容易。 *note asynchat:
8. 定义了一个可以由你来子类化的抽象类 *note async_chat: 99c.，提供了
‘collect_incoming_data()’ 和 ‘found_terminator()’ 等方法的实现。 它使用
与 *note asyncore: a. 相同的异步循环，并且可以在通道映射中自由地混合
*note asyncore.dispatcher: c91. 和 *note asynchat.async_chat: 99c. 这两
种类型的通道。 一般来说 *note asyncore.dispatcher: c91. 服务器通道在接收
到传入的连接请求时会生成新的 *note asynchat.async_chat: 99c. 通道对象。

 -- 類別: asynchat.async_chat

     这个类是 *note asyncore.dispatcher: c91. 的抽象子类。 对于实际使用
     的代码你必须子类化 *note async_chat: 99c.，提供有意义的 *note
     collect_incoming_data(): 28be. 和 *note found_terminator(): 28bf. 方
     法。 *note asyncore.dispatcher: c91. 的方法也可以被使用，但它们在消
     息/响应上下文中并不是全都有意义。

     与 *note asyncore.dispatcher: c91. 类似，*note async_chat: 99c. 也
     定义了一组通过对 ‘select()’ 调用之后的套接字条件进行分析所生成的事
     件。 一旦启动轮询循环 *note async_chat: 99c. 对象的方法就会被事件处
     理框架调用而无须程序员方面做任何操作。

     两个可被修改的类属性，用以提升性能，甚至也可能会节省内存。

      -- Data: ac_in_buffer_size

          异步输入缓冲区大小 (默认为 ‘4096’)。

      -- Data: ac_out_buffer_size

          异步输出缓冲区大小 (默认为 ‘4096’)。

     与 *note asyncore.dispatcher: c91. 不同，*note async_chat: 99c. 允
     许你定义一个 FIFO 队列 `producers'。 其中的生产者只需要一个方法
     ‘more()’，该方法应当返回要在通道上传输的数据。 生产者通过让其
     ‘more()’ 方法返回空字节串对象来表明其处于耗尽状态 (`意即' 它已不再
     包含数据)。 此时 *note async_chat: 99c. 对象会将该生产者从队列中移
     除并开始使用下一个生产者，如果有下一个的话。 当生产者队列为空时
     ‘handle_write()’ 方法将不执行任何操作。 你要使用通道对象的 *note
     set_terminator(): 28c2. 方法来描述如何识别来自远程端点的入站传输的
     结束或是重要的中断点。

     要构建一个可用的 *note async_chat: 99c. 子类，你的输入方法 *note
     collect_incoming_data(): 28be. 和 *note found_terminator(): 28bf. 必
     须要处理通道异步接收的数据。 这些参数的描述见下文。

 -- 成員函式: async_chat.close_when_done ()

     将 ‘None’ 推入生产者队列。 当此生产者被弹出队列时它将导致通道被关闭
     。

 -- 成員函式: async_chat.collect_incoming_data (data)

     调用时附带 `data'，其中包含任意数量的已接收数据。 必须被重载的默认
     方法将引发一个 *note NotImplementedError: 704. 异常。

 -- 成員函式: async_chat.discard_buffers ()

     在紧急情况下此方法将丢弃输入和/或输出缓冲区以及生产者队列中的任何数
     据。

 -- 成員函式: async_chat.found_terminator ()

     当输入数据流能匹配 *note set_terminator(): 28c2. 所设定的终结条件时
     会被调用。 必须被重载的默认方法将引发一个 *note
     NotImplementedError: 704. 异常。 被缓冲的输入数据应当可以通过实例属
     性来获取。

 -- 成員函式: async_chat.get_terminator ()

     返回通道的当前终结器。

 -- 成員函式: async_chat.push (data)

     将数据推入通道的队列以确保其被传输。 要让通道将数据写到网络中你只需
     要这样做就足够了，虽然以更复杂的方式使用你自己的生产者也是有可能的
     ，例如为了实现加密和分块。

 -- 成員函式: async_chat.push_with_producer (producer)

     获取一个生产者对象并将其加入到与通道相关联的生产者队列中。 当所有当
     前已推入的生产者都已被耗尽时通道将通过调用其 ‘more()’ 方法来耗用此
     生产者的数据并将数据发送至远程端点。

 -- 成員函式: async_chat.set_terminator (term)

     设置可在通道上被识别的终结条件。 ‘term’ 可以是三种类型值中的任意一
     种 ，对应于处理入站协议数据的三种不同方式。

     term            描述
                     
     ------------------------------------------------------------------
                     
     `string'        当在输入流中发现该字符串时将会调用
                     *note found_terminator(): 28bf.
                     
                     
     `integer'       当接收到指定数量的字符时将会调用
                     *note found_terminator(): 28bf.
                     
                     
     ‘None’          通道会不断地持续收集数据
                     

     请注意终结器之后的任何数据将可在 *note found_terminator(): 28bf. 被
     调用后由通道来读取。

* Menu:

* asynchat 示例::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/asynchat.py


File: python.info,  Node: asynchat 示例,  Up: asynchat --- 异步套接字指令/响应处理程序

5.18.7.1 asynchat 示例
......................

下面的例子片段显示了如何通过 *note async_chat: 99c. 来读取 HTTP 请求。
Web 服务器可以为每个入站的客户端连接创建 ‘http_request_handler’ 对象。 请
注意在初始时通道终结器会被设置为匹配 HTTP 标头末尾的空行，并且会用一个旗
标来指明标头正在被读取。

一旦完成了标头的读取，如果请求类型为 POST (表明输入流中存在更多的数据) 则
会使用 ‘Content-Length:’ 标头来设置一个数值终结器以从通道读取适当数量的
数据。

一旦完成了对所有相关输入的处理，将会在设置通道终结器为 ‘None’ 以确保忽略
掉 Web 客户端所发送的任何无关数据之后调用 ‘handle_request()’ 方法。

     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()


File: python.info,  Node: signal --- 设置异步事件处理程序,  Next: mmap --- 内存映射文件支持,  Prev: asynchat --- 异步套接字指令/响应处理程序,  Up: 网络和进程间通信

5.18.8 ‘signal’ — 设置异步事件处理程序
--------------------------------------

__________________________________________________________________

该模块提供了在 Python 中使用信号处理程序的机制。

* Menu:

* 一般规则::
* 模块内容: 模块内容<5>.
* 示例: 示例<26>.
* 对于 SIGPIPE 的说明::


File: python.info,  Node: 一般规则,  Next: 模块内容<5>,  Up: signal --- 设置异步事件处理程序

5.18.8.1 一般规则
.................

*note signal.signal(): b58. 函数允许定义在接收到信号时执行的自定义处理程
序。少量的默认处理程序已经设置： *note SIGPIPE: 28cd. 被忽略（因此管道和
套接字上的写入错误可以报告为普通的 Python 异常）以及如果父进程没有更改
*note SIGINT: 2626. ，则其会被翻译成 *note KeyboardInterrupt: 2cc. 异常
。

一旦设置，特定信号的处理程序将保持安装，直到它被显式重置（ Python 模拟
BSD 样式接口而不管底层实现），但 *note SIGCHLD: 28ce. 的处理程序除外，它
遵循底层实现。

* Menu:

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


File: python.info,  Node: 执行 Python 信号处理程序,  Next: 信号与线程,  Up: 一般规则

5.18.8.2 执行 Python 信号处理程序
.................................

Python 信号处理程序不会在低级（ C ）信号处理程序中执行。相反，低级信号处
理程序设置一个标志，告诉 *note virtual machine: 28d0. 稍后执行相应的
Python 信号处理程序（例如在下一个 *note bytecode: 709. 指令）。这会导致
：

   * 捕获同步错误是没有意义的，例如 *note SIGFPE: 28d1. 或 *note
     SIGSEGV: 28d2. ，它们是由 C 代码中的无效操作引起的。Python 将从信号
     处理程序返回到 C 代码，这可能会再次引发相同的信号，导致 Python 显然
     的挂起。 从Python 3.3开始，你可以使用 *note faulthandler: 7b. 模块
     来报告同步错误。

   * 纯 C 中实现的长时间运行的计算（例如在大量文本上的正则表达式匹配）可
     以在任意时间内不间断地运行，而不管接收到任何信号。计算完成后将调用
     Python 信号处理程序。


File: python.info,  Node: 信号与线程,  Prev: 执行 Python 信号处理程序,  Up: 一般规则

5.18.8.3 信号与线程
...................

Python 信号处理程序总是会在主 Python 主解释器的主线程中执行，即使信号是
在另一个线程中接收的。 这意味着信号不能被用作线程间通信的手段。 你可以改
用 *note threading: 10b. 模块中的同步原语。

此外，只有主解释器的主线程才被允许设置新的信号处理程序。


File: python.info,  Node: 模块内容<5>,  Next: 示例<26>,  Prev: 一般规则,  Up: signal --- 设置异步事件处理程序

5.18.8.4 模块内容
.................

3.5 版更變: 信号（ SIG* ），处理程序（ *note SIG_DFL: 2627. ， *note
SIG_IGN: 2628.）和 sigmask（ *note SIG_BLOCK: 28d6. ， *note
SIG_UNBLOCK: 28d7. ， *note SIG_SETMASK: 28d8. ）下面列出的相关常量变成
了 *note enums: 684. 。 *note getsignal(): 28d9. ， *note
pthread_sigmask(): b54. ， *note sigpending(): b56. 和 *note sigwait():
b57. 函数返回人类可读的 *note enums: 684. 。

在 *note signal: ea. 模块中定义的变量是：

 -- Data: signal.SIG_DFL

     这是两种标准信号处理选项之一；它只会执行信号的默认函数。 例如，在大
     多数系统上，对于 ‘SIGQUIT’ 的默认操作是转储核心并退出，而对于 *note
     SIGCHLD: 28ce. 的默认操作是简单地忽略它。

 -- Data: signal.SIG_IGN

     这是另一个标准信号处理程序，它将简单地忽略给定的信号。

 -- Data: signal.SIGABRT

     来自 ‘abort(3)’ 的中止信号。

 -- Data: signal.SIGALRM

     来自 ‘alarm(2)’ 的计时器信号。

     *note 可用性: 1491.: Unix。

 -- Data: signal.SIGBREAK

     来自键盘的中断 (CTRL + BREAK)。

     *note 可用性: 1491.: Windows。

 -- Data: signal.SIGBUS

     总线错误 (非法的内存访问)。

     *note 可用性: 1491.: Unix。

 -- Data: signal.SIGCHLD

     子进程被停止或终结。

     *note 可用性: 1491.: Unix。

 -- Data: signal.SIGCLD

     *note SIGCHLD: 28ce. 的别名。

 -- Data: signal.SIGCONT

     如果进程当前已停止则继续执行它

     *note 可用性: 1491.: Unix。

 -- Data: signal.SIGFPE

     浮点异常。 例如除以零。

     也參考
     ......

     当除法或求余运算的第二个参数为零时会引发 *note ZeroDivisionError:
     1fa. 。

 -- Data: signal.SIGHUP

     在控制终端上检测到挂起或控制进程的终止。

     *note 可用性: 1491.: Unix。

 -- Data: signal.SIGILL

     非法指令。

 -- Data: signal.SIGINT

     来自键盘的中断 (CTRL + C)。

     默认的动作是引发 *note KeyboardInterrupt: 2cc.。

 -- Data: signal.SIGKILL

     终止信号。

     它不能被捕获、阻塞或忽略。

     *note 可用性: 1491.: Unix。

 -- Data: signal.SIGPIPE

     损坏的管道：写入到没有读取器的管道。

     默认的动作是忽略此信号。

     *note 可用性: 1491.: Unix。

 -- Data: signal.SIGSEGV

     段错误：无效的内存引用。

 -- Data: signal.SIGTERM

     终结信号。

 -- Data: signal.SIGUSR1

     用户自定义信号 1。

     *note 可用性: 1491.: Unix。

 -- Data: signal.SIGUSR2

     用户自定义信号 2。

     *note 可用性: 1491.: Unix。

 -- Data: signal.SIGWINCH

     窗口调整大小信号。

     *note 可用性: 1491.: Unix。

 -- Data: SIG*

     所有信号编号都是符号化定义的。 例如，挂起信号被定义为 *note
     signal.SIGHUP: 28df.；变量的名称与 C 程序中使用的名称相同，具体见
     ‘<signal.h>’。 ’‘signal()’’ 的 Unix 手册页面列出了现有的信号 (在某
     些系统上这是 ‘signal(2)’，在其他系统中此列表则是在 ‘signal(7)’ 中
     )。 请注意并非所有系统都会定义相同的信号名称集；只有系统所定义的名
     称才会由此模块来定义。

 -- Data: signal.CTRL_C_EVENT

     对应于 ‘Ctrl+C’ 击键事件的信号。此信号只能用于 *note os.kill():
     db9. 。

     *note 可用性: 1491.: Windows。

     3.2 版新加入.

 -- Data: signal.CTRL_BREAK_EVENT

     对应于 ‘Ctrl+Break’ 击键事件的信号。此信号只能用于 *note os.kill():
     db9. 。

     *note 可用性: 1491.: Windows。

     3.2 版新加入.

 -- Data: signal.NSIG

     比最高信号数多一。

 -- Data: signal.ITIMER_REAL

     实时递减间隔计时器，并在到期时发送 *note SIGALRM: 28db. 。

 -- Data: signal.ITIMER_VIRTUAL

     仅在进程执行时递减间隔计时器，并在到期时发送 SIGVTALRM 。

 -- Data: signal.ITIMER_PROF

     当进程执行时以及当系统替进程执行时都会减小间隔计时器。 这个计时器与
     ITIMER_VIRTUAL 相配结，通常被用于分析应用程序在用户和内核空间中花费
     的时间。 SIGPROF 会在超期时被发送。

 -- Data: signal.SIG_BLOCK

     *note pthread_sigmask(): b54. 的 `how' 形参的一个可能的值，表明信号
     将会被阻塞。

     3.3 版新加入.

 -- Data: signal.SIG_UNBLOCK

     *note pthread_sigmask(): b54. 的 `how' 形参的是个可能的值，表明信号
     将被解除阻塞。

     3.3 版新加入.

 -- Data: signal.SIG_SETMASK

     *note pthread_sigmask(): b54. 的 `how' 形参的一个可能的值，表明信号
     掩码将要被替换。

     3.3 版新加入.

*note signal: ea. 模块定义了一个异常:

 -- 例外: signal.ItimerError

     作为来自下层 *note setitimer(): 28ea. 或 *note getitimer(): 28eb. 实
     现错误的信号被引发。 如果将无效的定时器或负的时间值传给 *note
     setitimer(): 28ea. 就导致这个错误。 此错误是 *note OSError: 304. 的
     子类型。

     3.3 版新加入: 此错误是 *note IOError: a73. 的子类型，现在则是 *note
     OSError: 304. 的别名。

*note signal: ea. 模块定义了以下函数:

 -- 函式: signal.alarm (time)

     如果 `time' 值非零，则此函数将要求将一个 *note SIGALRM: 28db. 信号
     在 `time' 秒内发往进程。 任何在之前排入计划的警报都会被取消（在任何
     时刻都只能有一个警报被排入计划）。 后续的返回值将是任何之前设置的警
     报被传入之前的秒数。 如果 `time' 值为零，则不会将任何警报排入计划，
     并且任何已排入计划的警报都会被取消。 如果返回值为零，则目前没有任何
     警报被排入计划。

     *note 可用性: 1491.: Unix。 更多信息请参见手册页面 ‘alarm(2)’。

 -- 函式: signal.getsignal (signalnum)

     返回当前用于信号 `signalnum' 的信号处理程序。 返回值可以是一个
     Python 可调用对象，或是特殊值 *note signal.SIG_IGN: 2628, *note
     signal.SIG_DFL: 2627. 或 *note None: 203. 之一。 在这里，*note
     signal.SIG_IGN: 2628. 表示信号在之前被忽略，*note signal.SIG_DFL:
     2627. 表示之前在使用默认的信号处理方式，而 ‘None’ 表示之前的信号处
     理程序未由 Python 安装。

 -- 函式: signal.strsignal (signalnum)

     返回信号 `signalnum' 的系统描述，例如 "Interrupt", "Segmentation
     fault" 等等。 如果信号无法被识别则返回 *note None: 203.。

     3.8 版新加入.

 -- 函式: signal.valid_signals ()

     返回本平台上的有效信号编号集。 这可能会少于 ‘range(1, NSIG)’，如果
     某些信号被系统保留作为内部使用的话。

     3.8 版新加入.

 -- 函式: signal.pause ()

     使进程休眠直至接收到一个信号；然后将会调用适当的处理程序。 返回空值
     。

     *note 可用性: 1491.: Unix。 更多信息请参见手册页面 ‘signal(2)’。

     另请参阅 *note sigwait(): b57, *note sigwaitinfo(): 772, *note
     sigtimedwait(): 771. 和 *note sigpending(): b56.。

 -- 函式: signal.raise_signal (signum)

     向调用方进程发送一个信号。 返回空值。

     3.8 版新加入.

 -- 函式: signal.pidfd_send_signal (pidfd, sig, siginfo=None, flags=0)

     发送信号 `sig' 到文件描述符 `pidfd' 所指向的进程。 Python 目前不支
     持 `siginfo' 形参；它必须为 ‘None’。 提供 `flags' 参数是为了将来扩
     展；当前未定义旗标值。

     更多信息请参阅 ‘pidfd_send_signal(2)’ 手册页面。

     *note 可用性: 1491.: Linux 5.1+

     3.9 版新加入.

 -- 函式: signal.pthread_kill (thread_id, signalnum)

     将信号 `signalnum' 发送至与调用者在同一进程中另一线程 `thread_id'。
     目标线程可被用于执行任何代码（Python或其它）。 但是，如果目标线程是
     在执行 Python 解释器，则 Python 信号处理程序将 *note
     由主解释器的主线程来执行: 28d4.。 因此，将信号发送给特定 Python 线
     程的唯一作用在于强制让一个正在运行的系统调用失败并抛出 *note
     InterruptedError: 74c.。

     使用 *note threading.get_ident(): b87. 或 *note threading.Thread:
     21a. 对象的 *note ident: 2175. 属性为 `thread_id' 获取合适的值。

     如果 `signalnum' 为 0，则不会发送信号，但仍然会执行错误检测；这可被
     用来检测目标线程是否仍在运行。

     引发一个 *note 审计事件: fa1. ‘signal.pthread_kill’，附带参数
     ‘thread_id’, ‘signalnum’。

     *note 可用性: 1491.: Unix。 更多信息请参见手册页面
     ‘pthread_kill(3)’。

     另请参阅 *note os.kill(): db9.。

     3.3 版新加入.

 -- 函式: signal.pthread_sigmask (how, mask)

     获取和/或修改调用方线程的信号掩码。 信号掩码是一组传送过程目前为调
     用者而阻塞的信号集。 返回旧的信号掩码作为一组信号。

     该调用的行为取决于 `how' 的值，具体见下。

        * *note SIG_BLOCK: 28d6.: 被阻塞信号集是当前集与 `mask' 参数的并
          集。

        * *note SIG_UNBLOCK: 28d7.: `mask' 中的信号会从当前已阻塞信号集
          中被移除。 允许尝试取消对一个非阻塞信号的阻塞。

        * *note SIG_SETMASK: 28d8.: 已阻塞信号集会被设为 `mask' 参数的值
          。

     `mask' 是一个信号编号集合 (例如 {*note signal.SIGINT: 2626, *note
     signal.SIGTERM: 26be.})。 请使用 *note valid_signals(): 28ed. 表示
     包含所有信号的完全掩码。

     例如，‘signal.pthread_sigmask(signal.SIG_BLOCK, [])’ 会读取调用方线
     程的信号掩码。

     *note SIGKILL: 28e1. 和 ‘SIGSTOP’ 不能被阻塞。

     *note 可用性: 1491.: Unix。 更多信息请参见手册页面 ‘sigprocmask(3)’
     和 ‘pthread_sigmask(3)’。

     另请参阅 *note pause(): 28ee, *note sigpending(): b56. 和 *note
     sigwait(): b57.。

     3.3 版新加入.

 -- 函式: signal.setitimer (which, seconds, interval=0.0)

     设置由 `which' 指明的给定间隔计时器 (*note signal.ITIMER_REAL:
     28e6, *note signal.ITIMER_VIRTUAL: 28e7. 或 *note
     signal.ITIMER_PROF: 28e8. 之一) 在 `seconds' 秒 (接受浮点数值，为与
     *note alarm(): 28ec. 之差) 之后开始并在每 `interval' 秒间隔时 (如果
     `interval' 不为零) 启动。 由 `which' 指明的间隔计时器可通过将
     `seconds' 设为零来清空。

     当一个间隔计时器启动时，会有信号发送至进程。 所发送的具体信号取决于
     所使用的计时器；*note signal.ITIMER_REAL: 28e6. 将发送 *note
     SIGALRM: 28db, *note signal.ITIMER_VIRTUAL: 28e7. 将发送
     ‘SIGVTALRM’, 而 *note signal.ITIMER_PROF: 28e8. 将发送 ‘SIGPROF’.

     原有的值会以元组: (delay, interval) 的形式被返回。

     尝试传入无效的计时器将导致 *note ItimerError: 28e9.。

     *note 可用性: 1491.: Unix。

 -- 函式: signal.getitimer (which)

     返回由 `which' 指明的给定间隔计时器当前的值。

     *note 可用性: 1491.: Unix。

 -- 函式: signal.set_wakeup_fd (fd, *, warn_on_full_buffer=True)

     将唤醒文件描述符设为 `fd'。 当接收到信号时，会将信号编号以单个字节
     的形式写入 fd。 这可被其它库用来唤醒一次 poll 或 select 调用，以允
     许该信号被完全地处理。

     原有的唤醒 fd 会被返回（或者如果未启用文件描述符唤醒则返回 -1）。 如
     果 `fd' 为 -1，文件描述符唤醒会被禁用。 如果不为 -1，则 `fd' 必须为
     非阻塞型。 需要由库来负责在重新调用 poll 或 select 之前从 `fd' 移除
     任何字节数据。

     当启用线程用时，此函数只能从 *note 主解释器的主线程: 28d4. 被调用；
     尝试从另一线程调用它将导致 *note ValueError: 16d. 异常被引发。

     使用此函数有两种通常的方式。 在两种方式下，当有信号到达时你都是用
     fd 来唤醒，但之后它们在确定达到的一个或多个信号 `which' 时存在差异
     。

     在第一种方式下，我们从 fd 的缓冲区读取数据，这些字节值会给你信号编
     号。 这种方式很简单，但在少数情况下会发生问题：通常 fd 将有缓冲区空
     间大小限制，如果信号到达得太多且太快，缓冲区可能会爆满，有些信号可
     能丢失。 如果你使用此方式，则你应当设置 ‘warn_on_full_buffer=True’，
     当信号丢失时这至少能将警告消息打印到 stderr。

     在第二种方式下，我们 `只会' 将唤醒 fd 用于唤醒，而忽略实际的字节值
     。 在此情况下，我们所关心的只有 fd 的缓冲区为空还是不为空；爆满的缓
     冲区完全不会导致问题。 如果你使用此方式，则你应当设置
     ‘warn_on_full_buffer=False’，这样你的用户就不会被虚假的警告消息所迷
     惑。

     3.5 版更變: 在 Windows 上，此函数现在也支持套接字处理。

     3.7 版更變: 添加了 ‘warn_on_full_buffer’ 形参。

 -- 函式: signal.siginterrupt (signalnum, flag)

     更改系统调用重启行为：如果 `flag' 为 *note False: 48e.，系统调用将
     在被信号 `signalnum' 中断时重启，否则系统调用将被中断。 返回空值。

     *note 可用性: 1491.: Unix。 更多信息请参见手册页面
     ‘siginterrupt(3)’。

     请注意用 *note signal(): ea. 安装信号处理程序将重启行为重置为可通过
     显式调用 ‘siginterrupt()’ 并为给定信号的 `flag' 设置真值来实现中断
     。

 -- 函式: signal.signal (signalnum, handler)

     将信号 `signalnum' 的处理程序设为函数 `handler'。 `handler' 可以为
     接受两个参数（见下）的 Python 可调用对象，或者为特殊值 *note
     signal.SIG_IGN: 2628. 或 *note signal.SIG_DFL: 2627. 之一。 之前的
     信号处理程序将被返回（参见上文 *note getsignal(): 28d9. 的描述）。
     （更多信息请参阅 Unix 手册页面 ‘signal(2)’。）

     当启用线程用时，此函数只能从 *note 主解释器的主线程: 28d4. 被调用；
     尝试从另一线程调用它将导致 *note ValueError: 16d. 异常被引发。

     `handler' 将附带两个参数调用：信号编号和当前堆栈帧 (‘None’ 或一个帧
     对象；有关帧对象的描述请参阅 *note 类型层级结构描述: 1565. 或者参阅
     *note inspect: a0. 模块中的属性描述)。

     在 Windows 上，*note signal(): ea. 调用只能附带 *note SIGABRT:
     28da, *note SIGFPE: 28d1, *note SIGILL: 28e0, *note SIGINT: 2626,
     *note SIGSEGV: 28d2, *note SIGTERM: 26be. 或 *note SIGBREAK: 28dc.。
     任何其他值都将引发 *note ValueError: 16d.。 请注意不是所有系统都定
     义了同样的信号名称集合；如果一个信号名称未被定义为 ‘SIG*’ 模块层级
     常量则将引发 *note AttributeError: 4a1.。

 -- 函式: signal.sigpending ()

     检查正在等待传送给调用方线程的信号集合（即在阻塞期间被引发的信号）
     。 返回正在等待的信号集合。

     *note 可用性: 1491.: Unix。 更多信息请参见手册页面 ‘sigpending(2)’。

     另请参阅 *note pause(): 28ee, *note pthread_sigmask(): b54. 和
     *note sigwait(): b57.。

     3.3 版新加入.

 -- 函式: signal.sigwait (sigset)

     挂起调用方线程的执行直到信号集合 `sigset' 中指定的信号之一被传送。
     此函数会接受该信号（将其从等待信号列表中移除），并返回信号编号。

     *note 可用性: 1491.: Unix。 更多信息请参见手册页面 ‘sigwait(3)’。

     另请参阅 *note pause(): 28ee, *note pthread_sigmask(): b54, *note
     sigpending(): b56, *note sigwaitinfo(): 772. 和 *note
     sigtimedwait(): 771.。

     3.3 版新加入.

 -- 函式: signal.sigwaitinfo (sigset)

     挂起调用方线程的执行直到信号集合 `sigset' 中指定的信号之一被传送。
     此函数会接受该信号并将其从等待信号列表中移除。 如果 `sigset' 中的信
     号之一已经在等待调用方线程，此函数将立即返回并附带有关该信号的信息
     。 被传送信号的信号处理程序不会被调用。 如果该函数被某个不在
     `sigset' 中的信号中断则会引发 *note InterruptedError: 74c.。

     返回值是一个代表 ‘siginfo_t’ 结构体所包含数据的对象，具体为:
     ‘si_signo’, ‘si_code’, ‘si_errno’, ‘si_pid’, ‘si_uid’, ‘si_status’,
     ‘si_band’。

     *note 可用性: 1491.: Unix。 更多信息请参见手册页面
     ‘sigwaitinfo(2)’。

     另请参阅 *note pause(): 28ee, *note sigwait(): b57. 和 *note
     sigtimedwait(): 771.。

     3.3 版新加入.

     3.5 版更變: 当被某个 不在 `sigset' 中的信号中断时本函数将进行重试并
     且信号处理程序不会引发异常（请参阅 PEP 475(1) 了解其理由）。

 -- 函式: signal.sigtimedwait (sigset, timeout)

     类似于 *note sigwaitinfo(): 772.，但会接受一个额外的 `timeout' 参数
     来指定超时限制。 如果将 `timeout' 指定为 ‘0’，则会执行轮询。 如果发
     生超时则返回 *note None: 203.。

     *note 可用性: 1491.: Unix。 更多信息请参见手册页面
     ‘sigtimedwait(2)’。

     另请参阅 *note pause(): 28ee, *note sigwait(): b57. 和 *note
     sigwaitinfo(): 772.。

     3.3 版新加入.

     3.5 版更變: 现在当此函数被某个不在 `sigset' 中的信号中断时将以计算
     出的 `timeout' 进行重试并且信号处理程序不会引发异常（请参阅 PEP
     475(2) 了解其理由）。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0475

   (2) https://www.python.org/dev/peps/pep-0475


File: python.info,  Node: 示例<26>,  Next: 对于 SIGPIPE 的说明,  Prev: 模块内容<5>,  Up: signal --- 设置异步事件处理程序

5.18.8.5 示例
.............

这是一个最小示例程序。 它使用 *note alarm(): 28ec. 函数来限制等待打开一
个文件所花费的时间；这在文件为无法开启的串行设备时会很有用处，此情况通常
会导致 *note os.open(): 758. 无限期地挂起。 解决办法是在打开文件之前设置
5 秒钟的 alarm；如果操作耗时过长，将会发送 alarm 信号，并且处理程序会引
发一个异常。

     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


File: python.info,  Node: 对于 SIGPIPE 的说明,  Prev: 示例<26>,  Up: signal --- 设置异步事件处理程序

5.18.8.6 对于 SIGPIPE 的说明
............................

将你的程序用管道输出到工具例如 ‘head(1)’ 将会导致 *note SIGPIPE: 28cd. 信
号在其标准输出的接收方提前关闭时被发送到你的进程。 这将引发一个异常例如
‘BrokenPipeError: [Errno 32] Broken pipe’。 要处理这种情况，请对你的入口
点进行包装以捕获此异常，如下所示:

     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()

不要将 *note SIGPIPE: 28cd. 的处置方式设为 *note SIG_DFL: 2627. 以避免
*note BrokenPipeError: a7e.。 这样做还会在你的程序所写入的任何套接字连接
中断时导致你的程序异常退出。


File: python.info,  Node: mmap --- 内存映射文件支持,  Prev: signal --- 设置异步事件处理程序,  Up: 网络和进程间通信

5.18.9 ‘mmap’ — 内存映射文件支持
--------------------------------

__________________________________________________________________

内存映射文件对象的行为既像 *note bytearray: 173. 又像 *note 文件对象:
c14.。 你可以在大部分接受 *note bytearray: 173. 的地方使用 mmap 对象；例
如，你可以使用 *note re: dd. 模块来搜索一个内存映射文件。 你也可以通过执
行 ‘obj[index] = 97’ 来修改单个字节，或者通过对切片赋值来修改一个子序列:
‘obj[i1:i2] = b'...'’。 你还可以在文件的当前位置开始读取和写入数据，并使
用 ‘seek()’ 前往另一个位置。

内存映射文件是由 *note mmap: 31c. 构造函数创建的，其在 Unix 和 Windows 上
是不同的。 无论哪种情况，你都必须为一个打开的文件提供文件描述符以进行更
新。 如果你希望映射一个已有的 Python 文件对象，请使用该对象的 ‘fileno()’
方法来获取 `fileno' 参数的正确值。 否则，你可以使用 *note os.open():
758. 函数来打开这个文件，这会直接返回一个文件描述符（结束时仍然需要关闭
该文件）。

     備註: 如果要为可写的缓冲文件创建内存映射，则应当首先 *note flush():
     2149. 该文件。 这确保了对缓冲区的本地修改在内存映射中可用。

对于 Unix 和 Windows 版本的构造函数，可以将 `access' 指定为可选的关键字
参数。 `access' 接受以下四个值之一： ‘ACCESS_READ’ ， ‘ACCESS_WRITE’ 或
‘ACCESS_COPY’ 分别指定只读，直写或写时复制内存，或 ‘ACCESS_DEFAULT’ 推迟
到 `prot' 。 `access' 可以在 Unix 和 Windows 上使用。如果未指定 `access'
，则 Windows mmap 返回直写映射。这三种访问类型的初始内存值均取自指定的文
件。向 ‘ACCESS_READ’ 内存映射赋值会引发 *note TypeError: 1fe. 异常。 向
‘ACCESS_WRITE’ 内存映射赋值会影响内存和底层的文件。 向 ‘ACCESS_COPY’ 内
存映射赋值会影响内存，但不会更新底层的文件。

3.7 版更變: 添加了 ‘ACCESS_DEFAULT’ 常量。

要映射匿名内存，应将 -1 作为 fileno 和 length 一起传递。

 -- 類別: mmap.mmap (fileno, length, tagname=None,
          access=ACCESS_DEFAULT[, offset])

     `（ Windows 版本）' 映射被文件句柄 `fileno' 指定的文件的 `length' 个
     字节，并创建一个 mmap 对象。如果 `length' 大于当前文件大小，则文件
     将扩展为包含 `length' 个字节。如果 `length' 为 ‘0’，则映射的最大长
     度为当前文件大小。如果文件为空， Windows 会引发异常（你无法在
     Windows上创建空映射）。

     如果 `tagname' 被指定且不是 ‘None’ ，则是为映射提供标签名称的字符串
     。 Windows 允许你对同一文件拥有许多不同的映射。如果指定现有标签的名
     称，则会打开该标签，否则将创建该名称的新标签。如果省略此参数或设置
     为 ‘None’ ，则创建的映射不带名称。避免使用 tag 参数将有助于使代码在
     Unix和Windows之间可移植。

     `offset' 可以被指定为非负整数偏移量。 mmap 引用将相对于从文件开头的
     偏移。 `offset' 默认为0。 `offeset' 必须是 ‘ALLOCATIONGRANULARITY’
     的倍数。

     引发一个 *note 审计事件: fa1. ‘mmap.__new__’ 附带参数 ‘fileno’,
     ‘length’, ‘access’, ‘offset’。

 -- 類別: mmap.mmap (fileno, length, flags=MAP_SHARED,
          prot=PROT_WRITE|PROT_READ, access=ACCESS_DEFAULT[, offset])

     `(Unix 版本)' 映射文件描述符 `fileno' 指定的文件的 `length' 个字节
     ，并返回一个 mmap 对象。如果 `length' 为 ‘0’ ，则当调用 *note mmap:
     31c. 时，映射的最大长度将为文件的当前大小。

     `flags' 指明映射的性质。 ‘MAP_PRIVATE’ 会创建私有的写入时拷贝映射，
     因此对 mmap 对象内容的修改将为该进程所私有，而 ‘MAP_SHARED’ 会创建
     与其他映射同一文件区域的进程所共享的映射。 默认值为 ‘MAP_SHARED’。

     如果指明了 `prot'，它将给出所需的内存保护方式；最有用的两个值是
     ‘PROT_READ’ 和 ‘PROT_WRITE’，分别指明页面为可读或可写。 `prot' 默认
     为 ‘PROT_READ | PROT_WRITE’。

     可以指定 `access' 作为替代 `flags' 和 `prot' 的可选关键字形参。 同
     时指定 `flags', `prot' 和 `access' 将导致错误。 请参阅上文中
     `access' 的描述了解有关如何使用此形参的信息。

     `offset' 可以被指定为非负整数偏移量。 mmap 引用将相对于从文件开头的
     偏移。 `offset' 默认为 0。 `offset' 必须是 ‘ALLOCATIONGRANULARITY’
     的倍数，它在 Unix 系统上等价于 ‘PAGESIZE’。

     To ensure validity of the created memory mapping the file specified
     by the descriptor `fileno' is internally automatically synchronized
     with physical backing store on macOS and OpenVMS.

     这个例子演示了使用 *note mmap: 31c. 的简单方式:

          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()

     *note mmap: 31c. 也可以在 *note with: 7da. 语句中被用作上下文管理器
     :

          import mmap

          with mmap.mmap(-1, 13) as mm:
              mm.write(b"Hello world!")

     3.2 版新加入: 上下文管理器支持。

     下面的例子演示了如何创建一个匿名映射并在父进程和子进程之间交换数据
     。:

          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()

     引发一个 *note 审计事件: fa1. ‘mmap.__new__’ 附带参数 ‘fileno’,
     ‘length’, ‘access’, ‘offset’。

     映射内存的文件对象支持以下方法:

      -- 成員函式: close ()

          关闭 mmap。 后续调用该对象的其他方法将导致引发 ValueError 异常
          。 此方法将不会关闭打开的文件。

      -- 屬性: closed

          如果文件已关闭则返回 ‘True’。

          3.2 版新加入.

      -- 成員函式: find (sub[, start[, end]])

          返回子序列 `sub' 在对象内被找到的最小索引号，使得 `sub' 被包含
          在 [`start', `end'] 范围中。 可选参数 `start' 和 `end' 会被解
          读为切片表示法。 如果未找到则返回 ‘-1’。

          3.5 版更變: 现在支持可写的 *note 字节类对象: 6df.。

      -- 成員函式: flush ([offset[, size]])

          将对文件的内存副本的修改刷新至磁盘。 如果不使用此调用则无法保
          证在对象被销毁前将修改写回存储。 如果指定了 `offset' 和
          `size'，则只将对指定范围内字节的修改刷新至磁盘；在其他情况下，
          映射的全部范围都会被刷新。 `offset' 必须为 ‘PAGESIZE’ 或
          ‘ALLOCATIONGRANULARITY’ 的倍数。

          返回 ‘None’ 以表示成功。 当调用失败时将引发异常。

          3.8 版更變: 在之前版本中，成功时将返回非零值；在 Windows 下当
          发生错误时将返回零。 在 Unix 下 成功时将返回零值；当发生错误时
          将引发异常。

      -- 成員函式: madvise (option[, start[, length]])

          将有关内存区域的建议 `option' 发送至内核，从 `start' 开始扩展
          `length' 个字节。 `option' 必须为系统中可用的 *note MADV_*
          常量: 28f8. 之一。 如果省略 `start' 和 `length'，则会包含整个
          映射。 在某些系统中（包括 Linux），`start' 必须为 ‘PAGESIZE’ 的
          倍数。

          可用性: 具有 ‘madvise()’ 系统调用的系统。

          3.8 版新加入.

      -- 成員函式: move (dest, src, count)

          将从偏移量 `src' 开始的 `count' 个字节拷贝到目标索引号 `dest'。
          如果 mmap 创建时设置了 ‘ACCESS_READ’，则调用 move 将引发 *note
          TypeError: 1fe. 异常。

      -- 成員函式: read ([n])

          返回一个 *note bytes: 172.，其中包含从当前文件位置开始的至多
          `n' 个字节。 如果参数省略，为 ‘None’ 或负数，则返回从当前文件
          位置开始直至映射结尾的所有字节。 文件位置会被更新为返回字节数
          据之后的位置。

          3.3 版更變: 参数可被省略或为 ‘None’。

      -- 成員函式: read_byte ()

          将当前文件位置上的一个字节以整数形式返回，并让文件位置前进 1。

      -- 成員函式: readline ()

          返回一个单独的行，从当前文件位置开始直到下一个换行符。 文件位
          置会被更新为返回字节数据之后的位置。

      -- 成員函式: resize (newsize)

          改变映射以及下层文件的大小，如果存在的话。 如果 mmap 创建时设
          置了 ‘ACCESS_READ’ 或 ‘ACCESS_COPY’，则改变映射大小将引发
          *note TypeError: 1fe. 异常。

      -- 成員函式: rfind (sub[, start[, end]])

          返回子序列 `sub' 在对象内被找到的最大索引号，使得 `sub' 被包含
          在 [`start', `end'] 范围中。 可选参数 `start' 和 `end' 会被解
          读为切片表示法。 如果未找到则返回 ‘-1’。

          3.5 版更變: 现在支持可写的 *note 字节类对象: 6df.。

      -- 成員函式: seek (pos[, whence])

          设置文件的当前位置。 `whence' 参数为可选项并且默认为
          ‘os.SEEK_SET’ 或 ‘0’ (绝对文件定位)；其他值还有 ‘os.SEEK_CUR’
          或 ‘1’ (相对当前位置查找) 和 ‘os.SEEK_END’ 或 ‘2’ (相对文件末
          尾查找)。

      -- 成員函式: size ()

          返回文件的长度，该数值可以大于内存映射区域的大小。

      -- 成員函式: tell ()

          返回文件指针的当前位置。

      -- 成員函式: write (bytes)

          将 `bytes' 中的字节数据写入文件指针当前位置的内存并返回写入的
          字节总数 (一定不小于 ‘len(bytes)’，因为如果写入失败，将会引发
          *note ValueError: 16d.)。 在字节数据被写入后文件位置将会更新。
          如果 mmap 创建时设置了 ‘ACCESS_READ’，则向其写入将引发 *note
          TypeError: 1fe. 异常。

          3.5 版更變: 现在支持可写的 *note 字节类对象: 6df.。

          3.6 版更變: 现在会返回写入的字节总数。

      -- 成員函式: write_byte (byte)

          将整数值 `byte' 写入文件指针当前位置的内存；文件位置前进 ‘1’。
          如果 mmap 创建时设置了 ‘ACCESS_READ’，则向其写入将引发 *note
          TypeError: 1fe. 异常。

* Menu:

* MADV_* 常量::


File: python.info,  Node: MADV_* 常量,  Up: mmap --- 内存映射文件支持

5.18.9.1 MADV_* 常量
....................

 -- Data: mmap.MADV_NORMAL
 -- Data: mmap.MADV_RANDOM
 -- Data: mmap.MADV_SEQUENTIAL
 -- Data: mmap.MADV_WILLNEED
 -- Data: mmap.MADV_DONTNEED
 -- Data: mmap.MADV_REMOVE
 -- Data: mmap.MADV_DONTFORK
 -- Data: mmap.MADV_DOFORK
 -- Data: mmap.MADV_HWPOISON
 -- Data: mmap.MADV_MERGEABLE
 -- Data: mmap.MADV_UNMERGEABLE
 -- Data: mmap.MADV_SOFT_OFFLINE
 -- Data: mmap.MADV_HUGEPAGE
 -- Data: mmap.MADV_NOHUGEPAGE
 -- Data: mmap.MADV_DONTDUMP
 -- Data: mmap.MADV_DODUMP
 -- Data: mmap.MADV_FREE
 -- Data: mmap.MADV_NOSYNC
 -- Data: mmap.MADV_AUTOSYNC
 -- Data: mmap.MADV_NOCORE
 -- Data: mmap.MADV_CORE
 -- Data: mmap.MADV_PROTECT

     这些选项可被传给 *note mmap.madvise(): 31d.。 不是每个选项都存在于
     每个系统中。

     可用性: 具有 madvise() 系统调用的系统。

     3.8 版新加入.


File: python.info,  Node: 互联网数据处理,  Next: 结构化标记处理工具,  Prev: 网络和进程间通信,  Up: Python 標準函式庫 Standard Library

5.19 互联网数据处理
===================

本章介绍了支持处理互联网上常用数据格式的模块。

* Menu:

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


File: python.info,  Node: email --- 电子邮件与 MIME 处理包,  Next: json --- JSON 编码和解码器,  Up: 互联网数据处理

5.19.1 ‘email’ — 电子邮件与 MIME 处理包
---------------------------------------

`源代码:' Lib/email/__init__.py(1)

__________________________________________________________________

*note email: 67. 包是一个用于管理电子邮件消息的库。 它 `并非' 被设计为执
行向 SMTP ( RFC 2821(2)), NNTP 或其他服务器发送电子邮件消息的操作；这些
是 *note smtplib: ed. 和 *note nntplib: c0. 等模块的功能。 *note email:
67. 包试图尽可能地遵循 RFC，支持 RFC 5322(3) 和 RFC 6532(4)，以及与 MIME
相关的各个 RFC 例如 RFC 2045(5), RFC 2046(6), RFC 2047(7), RFC 2183(8) 和
RFC 2231(9)。

email 包的总体结构可以分为三个主要组件，另外还有第四个组件用于控制其他组
件的行为。

这个包的中心组件是代表电子邮件消息的“对象模型”。 应用程序主要通过在
*note message: 70. 子模块中定义的对象模型接口与这个包进行交互。 应用程序
可以使用此 API 来询问有关现有电子邮件的问题、构造新的电子邮件，或者添加
或移除自身也使用相同对象模型接口的电子邮件子组件。 也就是说，遵循电子邮
件消息及其 MIME 子组件的性质，电子邮件对象模型是所有提供 *note
EmailMessage: 63c. API 的对象所构成的树状结构。

这个包的另外两个主要组件是 *note parser: 72. 和 *note generator: 6c.。
parser 接受电子邮件消息的序列化版本（字节流）并将其转换为 *note
EmailMessage: 63c. 对象树。 generator 接受 *note EmailMessage: 63c. 并将
其转回序列化的字节流。 (parser 和 generator 还能处理文本字符流，但不建议
这种用法，因为这很容易导致某种形式的无效消息。

控制组件是 *note policy: 73. 模块。 每一个 *note EmailMessage: 63c.、每
一个 *note generator: 6c. 和每一个 *note parser: 72. 都有一个相关联的
*note policy: 73. 对象来控制其行为。 通常应用程序只有在 *note
EmailMessage: 63c. 被创建时才需要指明控制策略，或者通过直接实例代 *note
EmailMessage: 63c. 来新建电子邮件，或者通过使用 *note parser: 72. 来解析
输入流。 但是策略也可以在使用 *note generator: 6c. 序列化消息时被更改。
例如，这允许从磁盘解析通用电子邮件消息，而在将消息发送到电子邮件服务器时
使用标准 SMTP 设置对其进行序列化。

email 包会尽量地对应用程序隐藏各种控制类 RFC 的细节。 从概念上讲应用程序
应当能够将电子邮件消息视为 Unicode 文本和二进制附件的结构化树，而不必担
心在序列化时要如何表示它们。 但在实际中，经常有必要至少了解一部分控制类
MIME 消息及其结构的规划，特别是 MIME "内容类型" 的名称和性质以及它们是如
何标识多部分文档的。 在大多数情况下这些知识应当仅对于更复杂的应用程序来
说才是必需的，并且即便在那时它也应当仅是特定的高层级结构，而不是如何表示
这些结构的细节信息。 由于 MIME 内容类型被广泛应用于现代因特网软件（而非
只是电子邮件），因此这对许多程序员来说将是很熟悉的概念。

以下小节描述了 *note email: 67. 包的具体功能。 我们会从 *note message:
70. 对象模型开始，它是应用程序将要使用的主要接口，之后是 *note parser:
72. 和 *note generator: 6c. 组件。 然后我们会介绍 *note policy: 73. 控制
组件，它将完成对这个库的主要组件的处理。

接下来的三个小节会介绍这个包可能引发的异常以及 *note parser: 72. 可能检
测到的缺陷（即与 RFC 不相符）。 然后我们会介绍 *note headerregistry: 6e.
和 *note contentmanager: 69. 子组件，它们分别提供了用于更精细地操纵标题
和载荷的工具。 这两个组件除了包含使用与生成非简单消息的相关特性，还记录
了它们的可扩展性 API，这将是高级应用程序所感兴趣的内容。

在此之后是一组使用之前小节所介绍的 API 的基本部分的示例。

前面的内容是 email 包的现代（对 Unicode 支持良好）API。 从 *note
Message: 63b. 类开始的其余小节则介绍了旧式 *note compat32: 63a. API，它
会更直接地处理如何表示电子邮件消息的细节。 *note compat32: 63a. API `不
会' 向应用程序隐藏 RFC 的相关细节，但对于需要进行此种层级操作的应用程序
来说将是很有用的工具。 此文档对于因向下兼容理由而仍然使用 *note
compat32: 63a. API 的应用程序也是很适合的。

3.6 版更變: 文档经过重新组织和撰写以鼓励使用新的 *note EmailMessage:
63c./*note EmailPolicy: ad7. API。

*note email: 67. 包文档的内容:

* 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 迭代器.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/email/__init__.py

   (2) https://tools.ietf.org/html/rfc2821.html

   (3) https://tools.ietf.org/html/rfc5322.html

   (4) https://tools.ietf.org/html/rfc6532.html

   (5) https://tools.ietf.org/html/rfc2045.html

   (6) https://tools.ietf.org/html/rfc2046.html

   (7) https://tools.ietf.org/html/rfc2047.html

   (8) https://tools.ietf.org/html/rfc2183.html

   (9) https://tools.ietf.org/html/rfc2231.html


File: python.info,  Node: email message 表示一封电子邮件信息,  Next: email parser 解析电子邮件信息,  Up: email --- 电子邮件与 MIME 处理包

5.19.1.1 ‘email.message’: 表示一封电子邮件信息
..............................................

`源代码:' Lib/email/message.py(1)

__________________________________________________________________

3.6 版新加入: (2)

位于 *note email: 67. 包的中心的类就是 *note EmailMessage: 63c. 类。这个
类导入自 *note email.message: 70. 模块。它是 *note email: 67. 对象模型的
基类。*note EmailMessage: 63c. 为设置和查询头字段内容、访问信息体的内容
、以及创建和修改结构化信息提供了核心功能。

一份电子邮件信息由 `标头' 和 `载荷' （又被称为 `内容' ）组成。 标头遵循
RFC 5322(3) 或者 RFC 6532(4) 风格的字段名和值，字段名和字段值之间由一个
冒号隔开。 这个冒号既不属于字段名，也不属于字段值。信息的载荷可能是一段
简单的文字消息，也可能是一个二进制的对象，更可能是由多个拥有各自标头和载
荷的子信息组成的结构化子信息序列。 对于后者类型的载荷，信息的 MIME 类型
将会被指明为诸如 ‘multipart/*’ 或 ‘message/rfc822’ 的类型。

*note EmailMessage: 63c. 对象所提供的抽象概念模型是一个头字段组成的有序
字典加一个代表 RFC 5322(5) 标准的信息体的 `载荷' 。 载荷有可能是一系列子
‘EmailMessage’ 对象的列表。你除了可以通过一般的字典方法来访问头字段名和
值，还可以使用特制方法来访问头的特定字段（比如说 MIME 内容类型字段）、操
纵载荷、生成信息的序列化版本、递归遍历对象树。

*note EmailMessage: 63c. 的类字典接口的字典索引是头字段名，头字段名必须
是ASCII值。字典值是带有一些附加方法的字符串。虽然头字段的存储和获取都是
保留其原始大小写的，但是字段名的匹配是大小写不敏感的。与真正的字典不同，
键与键之间不但存在顺序关系，还可以重复。我们提供了额外的方法来处理含有重
复键的头。

`载荷' 是多样的。对于简单的信息对象，它是字符串或字节对象；对于诸如
‘multipart/*’ 和 ‘message/rfc822’ 信息对象的 MIME 容器文档，它是一个
*note EmailMessage: 63c. 对象列表。

 -- 類別: email.message.EmailMessage (policy=default)

     如果指定了 `policy' ，消息将由这个 `policy' 所指定的规则来更新和序
     列化信息的表达。如果没有指定 `policy' ，其将默认使用 *note default:
     2922. 策略。这个策略遵循电子邮件的RFC标准，除了行终止符号（RFC要求
     使用 ‘\r\n’ ，此策略使用Python标准的 ‘\n’ 行终止符）。请前往 *note
     policy: 73. 的文档获取更多信息。

      -- 成員函式: as_string (unixfrom=False, maxheaderlen=None,
               policy=None)

          以一段扁平的字符串的形式返回整个信息对象。若可选的 `unixform'
          参数为真，返回的字符串会包含信封头。 `unixform' 的默认值是
          ‘False’ 。为了保持与基类 *note Message: 63b. 的兼容性，
          `maxheaderlen' 是被接受的，但是其默认值是 ‘None’ 。这个默认值
          表示行长度由策略的 ‘max_line_length’ 属性所控制。从信息实例所
          获取到的策略可以通过 `policy' 参数重写。这样可以对该方法所产生
          的输出进行略微的控制，因为指定的 `policy' 会被传递到 *note
          Generator: c1e. 当中。

          扁平化信息可能会对 *note EmailMessage: 63c. 做出修改。这是因为
          为了完成向字符串的转换，一些内容需要使用默认值填入（举个例子，
          MIME 边界字段可能会被生成或被修改）。

          请注意，这个方法是为了便利而提供，不一定是适合你的应用程序的最
          理想的序列化信息的方法。这在你处理多封信息的时候尤甚。如果你需
          要使用更加灵活的API来序列化信息，请参见 *note
          email.generator.Generator: c1e. 。同时请注意，当 *note utf8:
          7c5. 属性为其默认值 ‘False’ 的时候，本方法将限制其行为为生成以
          “7 bit clean”方式序列化的信息。

          3.6 版更變: `maxheaderlen' 没有被指定时的默认行为从默认为0修改
          为默认为策略的 `max_line_length' 值。

      -- 成員函式: __str__ ()

          与 ‘as_string(policy=self.policy.clone(utf8=True))’ 等价。这将
          让 ‘str(msg)’ 产生的字符串包含人类可读的的序列化信息内容。

          3.4 版更變: 本方法开始使用 ‘utf8=True’ ，而非 *note
          as_string(): 2923. 的直接替身。使用 ‘utf8=True’ 会产生类似于
          RFC 6531(6) 的信息表达。

      -- 成員函式: as_bytes (unixfrom=False, policy=None)

          以字节串对象的形式返回整个扁平化后的消息。 当可选的 `unixfrom'
          为真值时，返回的字符串会包含信封标头。 `unixfrom' 的默认值为
          ‘False’。 `policy' 参数可被用于重载从消息实例获取的默认
          policy。 这可被用来控制该方法所产生的部分格式效果，因为指定的
          `policy' 将被传递给 *note BytesGenerator: c1f.。

          扁平化信息可能会对 *note EmailMessage: 63c. 做出修改。这是因为
          为了完成向字符串的转换，一些内容需要使用默认值填入（举个例子，
          MIME 边界字段可能会被生成或被修改）。

          请注意，这个方法是为了便利而提供，不一定是适合你的应用程序的最
          理想的序列化信息的方法。这在你处理多封信息的时候尤甚。如果你需
          要使用更加灵活的API来序列化信息，请参见 *note
          email.generator.BytesGenerator: c1f. 。

      -- 成員函式: __bytes__ ()

          与 *note as_bytes(): 2925. 等价。这将让 ‘bytes(msg)’ 产生一个
          包含序列化信息内容的字节序列对象。

      -- 成員函式: is_multipart ()

          如果该信息的载荷是一个子 *note EmailMessage: 63c. 对象列表，返
          回 ‘True’ ；否则返回 ‘False’ 。在 *note is_multipart(): 2927.
          返回 ‘True’ 的场合下，载荷应当是一个字符串对象（有可能是一个使
          用了内容传输编码进行编码的二进制载荷）。请注意， *note
          is_multipart(): 2927. 返回 ‘True’ 不意味着
          ‘msg.get_content_maintype() == 'multipart'’ 也会返回 ‘True’ 。
          举个例子， ‘is_multipart’ 在 *note EmailMessage: 63c. 是
          ‘message/rfc822’ 类型的信息的情况下，其返回值也是 ‘True’ 。

      -- 成員函式: set_unixfrom (unixfrom)

          将信息的信封头设置为 `unixform' ，这应当是一个字符串。（在
          *note mboxMessage: 2929. 中有关于这个头的一段简短介绍。）

      -- 成員函式: get_unixfrom ()

          返回消息的信封头。如果信封头从未被设置过，默认返回 ‘None’ 。

     以下方法实现了对信息的头字段进行访问的类映射接口。请留意，只是类映
     射接口，这与平常的映射接口（比如说字典映射）有一些语义上的不同。举
     个例子，在一个字典当中，键之间不可重复，但是信息头字段是可以重复的
     。不光如此，在字典当中调用 *note keys(): 292b. 方法返回的结果，其顺
     序没有保证；但是在一个 *note EmailMessage: 63c. 对象当中，返回的头
     字段永远以其在原信息当中出现的顺序，或以其加入信息的顺序为序。任何
     删了后又重新加回去的头字段总是添加在当时列表的末尾。

     这些语义上的不同是刻意而为之的，是出于在绝大多数常见使用情景中都方
     便的初衷下设计的。

     还请留意，无论在什么情况下，消息当中的任何信封头字段都不会包含在映
     射接口当中。

      -- 成員函式: __len__ ()

          返回头字段的总数，重复的也计算在内。

      -- 成員函式: __contains__ (name)

          如果消息对象中有一个名为 `name' 的字段，其返回值为 ‘True’ 。匹
          配无视大小写差异， `name' 也不包含末尾的的冒号。 ‘in’ 操作符的
          实现中用到了这个方法，比如说：

               if 'message-id' in myMessage:
                  print('Message-ID:', myMessage['message-id'])

      -- 成員函式: __getitem__ (name)

          返回头字段名对应的字段值。 `name' 不含冒号分隔符。如果字段未找
          到，返回 ‘None’ 。 *note KeyError: 3e9. 异常永不抛出。

          请注意，如果对应名字的字段找到了多个，具体返回哪个字段值是未定
          义的。请使用 *note get_all(): 292f. 方法获取当前匹配字段名的所
          有字段值。

          使用标准策略（非 ‘compat32’）时，返回值是 *note
          email.headerregistry.BaseHeader: 2930. 的某个子类的一个实例。

      -- 成員函式: __setitem__ (name, val)

          在信息头中添加名为 `name' 值为 `val' 的字段。这个字段会被添加
          在已有字段列表的结尾处。

          请注意，这个方法 `既不会' 覆盖 `也不会' 删除任何字段名重名的已
          有字段。如果你确实想保证新字段是整个信息头当中唯一拥有 `name'
          字段名的字段，你需要先把旧字段删除。例如：

               del msg['subject']
               msg['subject'] = 'Python roolz!'

          如果 ‘policy’ 明确要求某些字段是唯一的（至少标准策略就有这么做
          ），对这些字段在已有同名字段的情况下仍然调用此方法尝试为字段名
          赋值会引发 *note ValueError: 16d. 异常。这是为了一致性而刻意设
          计出的行为，不过我们随时可能会突然觉得“还是在这种情况下自动把
          旧字段删除比较好吧”而把这个行为改掉，所以不要以为这是特性而依
          赖这个行为。

      -- 成員函式: __delitem__ (name)

          删除信息头当中字段名匹配 `name' 的所有字段。如果匹配指定名称的
          字段没有找到，也不会抛出任何异常。

      -- 成員函式: keys ()

          以列表形式返回消息头中所有的字段名。

      -- 成員函式: values ()

          以列表形式返回消息头中所有的字段值。

      -- 成員函式: items ()

          以二元元组的列表形式返回消息头中所有的字段名和字段值。

      -- 成員函式: get (name, failobj=None)

          返回对应字段名的字段值。这个方法与 *note __getitem__(): 292e.
          是一样的，只不过如果对应字段名的字段没有找到，该方法会返回
          `failobj' 。这个参数是可选的（默认值为 ‘None’ ）。

     以下是一些与头有关的更多有用方法：

      -- 成員函式: get_all (name, failobj=None)

          返回字段名为 `name' 的所有字段值的列表。如果信息内不存在匹配的
          字段，返回 `failobj' （其默认值为 ‘None’ ）。

      -- 成員函式: add_header (_name, _value, **_params)

          高级头字段设定。这个方法与 *note __setitem__(): 2931. 类似，不
          过你可以使用关键字参数为字段提供附加参数。 `_name' 是字段名，
          `_value' 是字段 `主' 值。

          对于关键字参数字典 `_params' 的每个键值对而言，它的键被用作参
          数的名字，其中下划线被替换为短横杠（毕竟短横杠不是合法的
          Python标识符）。一般来讲，参数以 ‘键="值"’ 的方式添加，除非值
          是 ‘None’ 。要真的是这样的话，只有键会被添加。

          如果值含有非ASCII字符，你可以将值写成 ‘(CHARSET, LANGUAGE,
          VALUE)’ 形式的三元组，这样你可以人为控制字符的字符集和语言。
          ‘CHARSET’ 是一个字符串，它为你的值的编码命名； ‘LANGUAGE’ 一般
          可以直接设为 ‘None’ ，也可以直接设为空字符串（其他可能取值参见
          :rfc‘2231‘ ）； ‘VALUE’ 是一个字符串值，其包含非ASCII的码点。
          如果你没有使用三元组，你的字符串又含有非ASCII字符，那么它就会
          使用 RFC 2231(7) 中， ‘CHARSET’ 为 ‘utf-8’ ， ‘LANGUAGE’ 为
          ‘None’ 的格式编码。

          例如：

               msg.add_header('Content-Disposition', 'attachment', filename='bud.gif')

          会添加一个形如下文的头字段：

               Content-Disposition: attachment; filename="bud.gif"

          带有非ASCII字符的拓展接口：

               msg.add_header('Content-Disposition', 'attachment',
                              filename=('iso-8859-1', '', 'Fußballer.ppt'))

      -- 成員函式: replace_header (_name, _value)

          替换头字段。只会替换掉信息内找到的第一个字段名匹配 `_name' 的
          字段值。字段的顺序不变，原字段名的大小写也不变。如果没有找到匹
          配的字段，抛出 *note KeyError: 3e9. 异常。

      -- 成員函式: get_content_type ()

          返回信息的内容类型，其形如 ‘maintype/subtype’ ，强制全小写。如
          果信息的 ‘Content-Type’ 头字段不存在则返回 *note
          get_default_type(): 2939. 的返回值；如果信息的 ‘Content-Type’
          头字段无效则返回 ‘text/plain’ 。

          （根据 RFC 2045(8) 所述，信息永远都有一个默认类型，所以 *note
          get_content_type(): 2938. 一定会返回一个值。 RFC 2045(9) 定义
          信息的默认类型为 ‘text/plain’ 或 ‘message/rfc822’ ，其中后者仅
          出现在消息头位于一个 ‘multipart/digest’ 容器中的场合中。如果消
          息头的 ‘Content-Type’ 字段所指定的类型是无效的， RFC 2045(10)
          令其默认类型为 ‘text/plain’ 。）

      -- 成員函式: get_content_maintype ()

          返回信息的主要内容类型。准确来说，此方法返回的是 *note
          get_content_type(): 2938. 方法所返回的形如 ‘maintype/subtype’
          的字符串当中的 ‘maintype’ 部分。

      -- 成員函式: get_content_subtype ()

          返回信息的子内容类型。准确来说，此方法返回的是 *note
          get_content_type(): 2938. 方法所返回的形如 ‘maintype/subtype’
          的字符串当中的 ‘subtype’ 部分。

      -- 成員函式: get_default_type ()

          返回默认的内容类型。绝大多数的信息，其默认内容类型都是
          ‘text/plain’ 。作为 ‘multipart/digest’ 容器内子部分的信息除外
          ，它们的默认内容类型是 ‘message/rfc822’ 。

      -- 成員函式: set_default_type (ctype)

          设置默认的内容类型。 尽管并非强制，但是 `ctype' 仍应当是
          ‘text/plain’ 或 ‘message/rfc822’ 二者取一。默认内容类型并不存
          储在 ‘Content-Type’ 头字段当中，所以设置此项的唯一作用就是决定
          当 ‘Content-Type’ 头字段在信息中不存在时，‘get_content_type’ 方
          法的返回值。

      -- 成員函式: set_param (param, value, header='Content-Type',
               requote=True, charset=None, language='', replace=False)

          在 ‘Content-Type’ 头字段当中设置一个参数。如果该参数已于字段中
          存在，将其旧值替换为 `value' 。如果 `header' 是 ‘Content-Type’
          （默认值），并且该头字段于信息中尚未存在，则会先添加该字段，将
          其值设置为 ‘text/plain’ ，并附加参数值。可选的 `header' 可以让
          你指定 ‘Content-Type’ 之外的另一个头字段。

          如果值包含非ASCII字符，其字符集和语言可以通过可选参数
          `charset' 和 `language' 显式指定。可选参数 `language' 指定 RFC
          2231(11) 当中的语言，其默认值是空字符串。 `charset' 和
          `language' 都应当字符串。默认使用的是 ‘utf8’ `charset' ，
          `language' 为 ‘None’ 。

          如果 `replace' 为 ‘False’ （默认值），该头字段会被移动到所有头
          字段列表的末尾。如果 `replace' 为 ‘True’ ，字段会被原地更新。

          于 *note EmailMessage: 63c. 对象而言， `requote' 参数已被弃用
          。

          请注意，头字段已有的参数值可以通过头字段的 ‘params’ 属性来访问
          （举例： ‘msg['Content-Type'].params['charset']’ ）。

          3.4 版更變: 添加了 ‘replace’ 关键字。

      -- 成員函式: del_param (param, header='content-type',
               requote=True)

          从 ‘Content-Type’ 头字段中完全移去给定的参数。头字段会被原地重
          写，重写后的字段不含参数和值。可选的 `header' 可以让你指定
          ‘Content-Type’ 之外的另一个字段。

          于 *note EmailMessage: 63c. 对象而言， `requote' 参数已被弃用
          。

      -- 成員函式: get_filename (failobj=None)

          返回信息头当中 ‘Content-Disposition’ 字段当中名为 ‘filename’ 的
          参数值。如果该字段当中没有此参数，该方法会退而寻找
          ‘Content-Type’ 字段当中的 ‘name’ 参数值。如果这个也没有找到，
          或者这些个字段压根就不存在，返回 `failobj' 。返回的字符串永远
          按照 *note email.utils.unquote(): 2940. 方法去除引号。

      -- 成員函式: get_boundary (failobj=None)

          返回信息头当中 ‘Content-Type’ 字段当中名为 ‘boundary’ 的参数值
          。如果字段当中没有此参数，或者这些个字段压根就不存在，返回
          `failobj' 。返回的字符串永远按照 *note email.utils.unquote():
          2940. 方法去除引号。

      -- 成員函式: set_boundary (boundary)

          将 ‘Content-Type’ 头字段的 ‘boundary’ 参数设置为 `boundary' 。
          *note set_boundary(): 2942. 方法永远都会在必要的时候为
          `boundary' 添加引号。如果信息对象中没有 ‘Content-Type’ 头字段
          ，抛出 *note HeaderParseError: 2943. 异常。

          请注意使用这个方法与直接删除旧的 ‘Content-Type’ 头字段然后使用
          *note add_header(): 2936. 方法添加一个带有新边界值参数的
          ‘Content-Type’ 头字段有细微差距。 *note set_boundary(): 2942.
          方法会保留 ‘Content-Type’ 头字段在原信息头当中的位置。

      -- 成員函式: get_content_charset (failobj=None)

          返回 ‘Content-Type’ 头字段中的 ‘charset’ 参数，强制小写。如果
          字段当中没有此参数，或者这个字段压根不存在，返回 `failobj' 。

      -- 成員函式: get_charsets (failobj=None)

          返回一个包含了信息内所有字符集名字的列表。 如果信息是
          ‘multipart’ 类型的，那么列表当中的每一项都对应其载荷的子部分的
          字符集名字。 否则，该列表是一个长度为 1 的列表。

          列表当中的每一项都是一个字符串，其值为对应子部分的
          ‘Content-Type’ 头字段的 ‘charset’ 参数值。如果该子部分没有此头
          字段，或者没有此参数，或者其主要 MIME 类型并非 ‘text’ ，那么列
          表中的那一项即为 `failobj' 。

      -- 成員函式: is_attachment ()

          如果信息头当中存在一个名为 ‘Content-Disposition’ 的字段，且该
          字段的值为 ‘attachment’ （大小写无关），返回 ‘True’ 。否则，返
          回 ‘False’ 。

          3.4.2 版更變: 为了与 *note is_multipart(): 2947. 方法一致，
          is_attachment 现在是一个方法，不再是属性了。

      -- 成員函式: get_content_disposition ()

          如果信息的 ‘Content-Disposition’ 头字段存在，返回其字段值；否
          则返回 ‘None’ 。返回的值均为小写，不包含参数。如果信息遵循 RFC
          2183(12) 标准，则此方法的返回值只可能在 `inline' 、
          `attachment' 和 ‘None’ 之间选择。

          3.5 版新加入.

     下列方法与信息内容（载荷）之访问与操控有关。

      -- 成員函式: walk ()

          *note walk(): 2949. 方法是一个多功能生成器。它可以被用来以深度
          优先顺序遍历信息对象树的所有部分和子部分。一般而言， *note
          walk(): 2949. 会被用作 ‘for’ 循环的迭代器，每一次迭代都返回其
          下一个子部分。

          以下例子会打印出一封具有多部分结构之信息的每个部分的 MIME 类型
          。

               >>> 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

          ‘walk’ 会遍历所有 *note is_multipart(): 2927. 方法返回 ‘True’
          的部分之子部分，哪怕 ‘msg.get_content_maintype() ==
          'multipart'’ 返回的是 ‘False’ 。使用 ‘_structure’ 除错帮助函数
          可以帮助我们在下面这个例子当中看清楚这一点：

               >>> 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

          在这里， ‘message’ 的部分并非 ‘multiparts’ ，但是它们真的包含
          子部分！ ‘is_multipart()’ 返回 ‘True’ ， ‘walk’ 也深入进这些子
          部分中。

      -- 成員函式: get_body (preferencelist=('related', 'html',
               'plain'))

          返回信息的 MIME 部分。这个部分是最可能成为信息体的部分。

          `preferencelist' 必须是一个字符串序列，其内容从 ‘related’ 、
          ‘html’ 和 ‘plain’ 这三者组成的集合中选取。这个序列代表着返回的
          部分的内容类型之偏好。

          在 ‘get_body’ 方法被调用的对象上寻找匹配的候选者。

          如果 ‘related’ 未包括在 `preferencelist' 中，可考虑将所遇到的
          任意相关的根部分（或根部分的子部分）在该（子）部分与一个首选项
          相匹配时作为候选项。

          当遇到一个 ‘multipart/related’ 时，将检查 ‘start’ 形参并且如果
          找到了一个匹配 ‘Content-ID’ 的部分，在查找候选匹配时只考虑它。
          在其他情况下则只考虑 ‘multipart/related’ 的第一个（默认的根）
          部分。

          如果一个部分具有 ‘Content-Disposition’ 标头，则当标头值为
          ‘inline’ 时将只考虑将该部分作为候选匹配。

          如果没有任何候选部分匹配 `preferencelist' 中的任何首选项，则返
          回 ‘None’。

          注: (1) 对于大多数应用来说有意义的 `preferencelist' 组合仅有
          ‘('plain',)’, ‘('html', 'plain')’ 以及默认的 ‘('related',
          'html', 'plain')’。 (2) 由于匹配是从调用 ‘get_body’ 的对象开始
          的，因此在 ‘multipart/related’ 上调用 ‘get_body’ 将返回对象本
          身，除非 `preferencelist' 具有非默认值。 (3) 未指定
          ‘Content-Type’ 或者 ‘Content-Type’ 标头无效的消息（或消息部分
          ）将被当作具有 ‘text/plain’ 类型来处理，这有时可能导致
          ‘get_body’ 返回非预期的结果。

      -- 成員函式: iter_attachments ()

          返回包含所有不是候选 "body" 部分的消息的直接子部分的迭代器。 也
          就是说，跳过首次出现的每个 ‘text/plain’, ‘text/html’,
          ‘multipart/related’ 或 ‘multipart/alternative’ (除非通过
          ‘Content-Disposition: attachment’ 将它们显式地标记为附件)，并
          返回所有的其余部分。 当直接应用于 ‘multipart/related’ 时，将返
          回包含除根部分之外所有相关部分的迭代器（即由 ‘start’ 形参所指
          向的部分，或者当没有 ‘start’ 形参或 ‘start’ 形参不能匹配任何部
          分的 ‘Content-ID’ 时则为第一部分）。 当直接应用于
          ‘multipart/alternative’ 或非 ‘multipart’ 时，将返回一个空迭代
          器。

      -- 成員函式: iter_parts ()

          返回包含消息的所有直接子部分的迭代器，对于非 ‘multipart’ 将为
          空对象。 （另请参阅 *note walk(): 2949.。）

      -- 成員函式: get_content (*args, content_manager=None, **kw)

          调用 `content_manager' 的 *note get_content(): 294e. 方法，将
          自身作为消息对象传入，并将其他参数或关键字作为额外参数传入。 如
          果未指定 `content_manager'，则会使用当前 *note policy: 73. 所
          指定的 ‘content_manager’。

      -- 成員函式: set_content (*args, content_manager=None, **kw)

          调用 `content_manager' 的 *note set_content(): 294f. 方法，将
          自身作为消息传入，并将其他参数或关键字作为额外参数传入。 如果
          未指定 `content_manager'，则会使用当前 *note policy: 73. 所指
          定的 ‘content_manager’。

      -- 成員函式: make_related (boundary=None)

          将非 ‘multipart’ 消息转换为 ‘multipart/related’ 消息，将任何现
          有的 ‘Content-’ 标头和载荷移入 ‘multipart’ 的（新加）首部分。
          如果指定了 `boundary'，会用它作为 multipart 中的分界字符串，否
          则会在必要时自动创建分界（例如当消息被序列化时）。

      -- 成員函式: make_alternative (boundary=None)

          将非 ‘multipart’ 或 ‘multipart/related’ 转换为
          ‘multipart/alternative’，将任何现有的 ‘Content-’ 标头和载荷移
          入 ‘multipart’ 的（新加）首部分。 如果指定了 `boundary'，会用
          它作为 multipart 中的分界字符串，否则会在必要时自动创建分界（
          例如当消息被序列化时）。

      -- 成員函式: make_mixed (boundary=None)

          将非 ‘multipart’, ‘multipart/related’ 或
          ‘multipart-alternative’ 转换为 ‘multipart/mixed’，将任何现有的
          ‘Content-’ 标头和载荷移入 ‘multipart’ 的（新加）首部分。 如果
          指定了 `boundary'，会用它作为 multipart 中的分界字符串，否则会
          在必要时自动创建分界（例如当消息被序列化时）。

      -- 成員函式: add_related (*args, content_manager=None, **kw)

          如果消息为 ‘multipart/related’，则创建一个新的消息对象，将所有
          参数传给其 *note set_content(): f81. 方法，并将其 *note
          attach(): 2954. 到 ‘multipart’。 如果消息为非 ‘multipart’，则
          先调用 *note make_related(): 2950. 然后再继续上述步骤。 如果消
          息为任何其他类型的 ‘multipart’，则会引发 *note TypeError:
          1fe.。 如果未指定 `content_manager'，则使用当前 *note policy:
          73. 所指定的 ‘content_manager’。 如果添加的部分没有
          ‘Content-Disposition’ 标头，则会添加一个值为 ‘inline’ 的标头。

      -- 成員函式: add_alternative (*args, content_manager=None, **kw)

          如果消息为 ‘multipart/alternative’，则创建一个新的消息对象，将
          所有参数传给其 *note set_content(): f81. 方法，并将其 *note
          attach(): 2954. 到 ‘multipart’。 如果消息为非 ‘multipart’ 或
          ‘multipart/related’，则先调用 *note make_alternative(): 2951.
          然后再继续上述步骤。 如果消息为任何其他类型的 ‘multipart’，则
          会引发 *note TypeError: 1fe.。 如果未指定 `content_manager'，
          则会使用当前 *note policy: 73. 所指定的 ‘content_manager’。

      -- 成員函式: add_attachment (*args, content_manager=None, **kw)

          如果消息为 ‘multipart/mixed’，则创建一个新的消息对象，将所有参
          数传给其 *note set_content(): f81. 方法，并将其 *note
          attach(): 2954. 到 ‘multipart’。 如果消息为非 ‘multipart’,
          ‘multipart/related’ 或 ‘multipart/alternative’，则先调用 *note
          make_mixed(): 2952. 然后再继续上述步骤。 如果未指定
          `content_manager'，则使用当前 *note policy: 73. 所指定的
          ‘content_manager’。 如果添加的部分没有 ‘Content-Disposition’ 标
          头，则会添加一个值为 ‘attachment’ 的标头。 此方法对于显式附件
          (‘Content-Disposition: attachment’) 和 ‘inline’ 附件
          (‘Content-Disposition: inline’) 均可使用，只须向
          ‘content_manager’ 传入适当的选项即可。

      -- 成員函式: clear ()

          移除所有载荷和所有标头。

      -- 成員函式: clear_content ()

          移除载荷以及所有 ‘Content-’ 标头，其他标头不加改变并且保持其原
          有顺序。

     *note EmailMessage: 63c. 对象具有下列实例属性:

      -- 屬性: preamble

          MIME 文档格式在标头之后的空白行以及第一个多部分的分界字符串之
          间允许添加一些文本， 通常，此文本在支持 MIME 的邮件阅读器中永
          远不可见，因为它处在标准 MIME 保护范围之外。 但是，当查看消息
          的原始文本，或当在不支持 MIME 的阅读器中查看消息时，此文本会变
          得可见。

          `preamble' 属性包含 MIME 文档开头部分的这些处于保护范围之外的
          文本。 当 *note Parser: beb. 在标头之后及第一个分界字符串之前
          发现一些文本时，它会将这些文本赋值给消息的 `preamble' 属性。 当
          *note Generator: c1e. 写出 MIME 消息的纯文本表示形式时，如果它
          发现消息具有 `preamble' 属性，它将在标头及第一个分界之间区域写
          出这些文本。 请参阅 *note email.parser: 72. 和 *note
          email.generator: 6c. 了解更多细节。

          请注意如果消息对象没有前导文本，则 `preamble' 属性将为 ‘None’。

      -- 屬性: epilogue

          `epilogue' 属性的作用方式与 `preamble' 相同，区别在于它包含在
          最后一个分界及消息结尾之间出现的文本。 与 *note preamble:
          2959. 类似，如果没有附加文本，则此属性将为 ‘None’。

      -- 屬性: defects

          `defects' 属性包含在解析消息时发现的所有问题的列表。 请参阅
          *note email.errors: 6b. 了解可能的解析缺陷的详细描述。

 -- 類別: email.message.MIMEPart (policy=default)

     这个类代表 MIME 消息的子部分。 它与 *note EmailMessage: 63c. 相似，
     不同之处在于当 *note set_content(): f81. 被调用时不会添加
     ‘MIME-Version’ 标头，因为子部分不需要有它们自己的 ‘MIME-Version’ 标
     头。

脚注
....

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/email/message.py

   (2) (1) 原先在3.4版本中以 *note provisional module: a61. 添加。过时的
文档被移动至 *note email.message.Message; 使用 compat32 API
来表示电子邮件消息: 2921. 。

   (3) https://tools.ietf.org/html/rfc5322.html

   (4) https://tools.ietf.org/html/rfc6532.html

   (5) https://tools.ietf.org/html/rfc5322.html

   (6) https://tools.ietf.org/html/rfc6531.html

   (7) https://tools.ietf.org/html/rfc2231.html

   (8) https://tools.ietf.org/html/rfc2045.html

   (9) https://tools.ietf.org/html/rfc2045.html

   (10) https://tools.ietf.org/html/rfc2045.html

   (11) https://tools.ietf.org/html/rfc2231.html

   (12) https://tools.ietf.org/html/rfc2183.html


File: python.info,  Node: email parser 解析电子邮件信息,  Next: email generator 生成 MIME 文档,  Prev: email message 表示一封电子邮件信息,  Up: email --- 电子邮件与 MIME 处理包

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

`源代码': Lib/email/parser.py(1)

__________________________________________________________________

使用以下两种方法的其中一种以创建消息对象结构：直接创建一个 *note
EmailMessage: 63c. 对象，使用字典接口添加消息头，并且使用 *note
set_content(): f81. 和其他相关方法添加消息负载；或者通过解析一个电子邮件
消息的序列化表达来创建消息对象结构。

*note email: 67. 包提供了一个可以理解包含 MIME 文档在内的绝大多数电子邮
件文档结构的标准语法分析程序。 你可以传递给语法分析程序一个字节串、字符
串或者文件对象，语法分析程序会返回给你对应于该对象结构的根 *note
EmailMessage: 63c. 实例。 对于简单的、非 MIME 的消息，这个根对象的负载很
可能就是一个包含了该消息文字内容的字符串。 对于 MIME 消息，调用根对象的
*note is_multipart(): 2927. 方法会返回 ‘True’，其子项可以通过负载操纵方
法来进行访问，例如 *note get_body(): 294a.、*note iter_parts(): 294c. 还
有 *note walk(): 2949.。

事实上你可以使用的语法分析程序接口有两种: *note Parser: beb. API 和增量
式的 *note FeedParser: 295e. API。当你的全部消息内容都在内存当中，或者整
个消息都保存在文件系统内的一个文件当中的时候，*note Parser: beb. API非常
有用。当你从可能会为了等待更多输入而阻塞的数据流当中读取消息（比如从套接
字当中读取电子邮件消息）的时候，*note FeedParser: 295e. 会更合适。*note
FeedParser: 295e. 会增量读取并解析消息，并且只有在你关闭语法分析程序的时
候才会返回根对象。

请注意，语法分析程序可以进行有限的拓展，你当然也可以完全从零开始实现你自
己的语法分析程序。将 *note email: 67. 包中内置的语法分析程序和 *note
EmailMessage: 63c. 类连接起来的所有逻辑代码都包含在 ‘policy’ 类当中，所
以如有必要，自定义的语法分析程序可以通过实现自定义的对应 ‘policy’ 方法来
创建对应的消息对象树。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/email/parser.py


File: python.info,  Node: FeedParser API,  Next: Parser API,  Up: email parser 解析电子邮件信息

5.19.1.3 FeedParser API
.......................

从 ‘email.feedparser’ 模块导入的 *note BytesFeedParser: c1b. 类提供了一
个适合于增量解析电子邮件消息的API，比如说在从一个可能会阻塞（例如套接字
）的源当中读取消息文字的场合中它就会变得很有用。当然， *note
BytesFeedParser: c1b. 也可以用来解析一个已经完整包含在一个 *note
bytes-like object: 6df. 、字符串或文件内的电子邮件消息，但是在这些场合下
使用 *note BytesParser: c1c. API可能会更加方便。这两个语法分析程序API的
语义和最终结果是一致的。

*note BytesFeedParser: c1b. 的API十分简洁易懂：你创建一个语法分析程序的
实例，向它不断输入大量的字节直到尽头，然后关闭这个语法分析程序就可以拿到
根消息对象了。 在处理符合标准的消息的时候 *note BytesFeedParser: c1b. 非
常准确；在处理不符合标准的消息的时候它做的也不差，但这视消息损坏的程度而
定。它会向消息对象的 *note defects: 295b. 属性中写入它从消息中找到的问题
列表。关于它能找到的所有问题类型的列表，详见 *note email.errors: 6b. 模
块。

这里是 *note BytesFeedParser: c1b. 的 API：

 -- 類別: email.parser.BytesFeedParser (_factory=None, *,
          policy=policy.compat32)

     创建一个 *note BytesFeedParser: c1b. 实例。可选的 `_factory' 参数是
     一个不带参数的可调用对象；如果没有被指定，就会使用 `policy' 参数的
     *note message_factory: 639. 属性。 每当需要一个新的消息对象的时候，
     `_factory' 都会被调用。

     如果指定了 `policy' 参数，它就会使用这个参数所指定的规则来更新消息
     的表达方式。 如果没有设定 `policy' 参数，它就会使用 *note compat32:
     ad4. 策略。 这个策略维持了对 Python 3.2 版本的 email 包的后向兼容性
     ，并且使用 *note Message: 63b. 作为默认的工厂。 其他策略使用 *note
     EmailMessage: 63c. 作为默认的 `_factory'。 关于 `policy' 还会控制什
     么，参见 *note policy: 73. 的文档。

     注：`一定要指定policy关键字'。在未来版本的Python当中，它的默认值会
     变成 *note email.policy.default: 2922. 。

     3.2 版新加入.

     3.3 版更變: 添加了 `policy' 关键字。

     3.6 版更變: `_factory' 默认为策略 ‘message_factory’。

      -- 成員函式: feed (data)

          向语法分析程序输入更多数据。`data' 应当是一个包含一行或多行内
          容的 *note bytes-like object: 6df.。 行内容可以是不完整的，语
          法分析程序会妥善的将这些不完整的行缝合在一起。每一行可以使用以
          下三种常见的终止符号的其中一种：回车符、换行符或回车符加换行符
          （三者甚至可以混合使用）。

      -- 成員函式: close ()

          完成之前输入的所有数据的解析并返回根消息对象。如果在这个方法被
          调用之后仍然调用 *note feed(): 2960. 方法，结果是未定义的。

 -- 類別: email.parser.FeedParser (_factory=None, *,
          policy=policy.compat32)

     行为跟 *note BytesFeedParser: c1b. 类一致，只不过向 *note feed():
     2960. 方法输入的内容必须是字符串。它的实用性有限，因为这种消息只有
     在其只含有ASCII文字，或者 ‘utf8’ 被设置为 ‘True’ 且没有二进制格式的
     附件的时候，才会有效。

     3.3 版更變: 添加了 `policy' 关键字。


File: python.info,  Node: Parser API,  Next: 附加说明,  Prev: FeedParser API,  Up: email parser 解析电子邮件信息

5.19.1.4 Parser API
...................

*note BytesParser: c1c. 类从 *note email.parser: 72. 模块导入，当消息的
完整内容包含在一个 *note bytes-like object: 6df. 或文件中时它提供了可用
于解析消息的 API。 *note email.parser: 72. 模块还提供了 *note Parser:
beb. 用来解析字符串，以及只用来解析消息头的 *note BytesHeaderParser:
adb. 和 *note HeaderParser: adc.，如果你只对消息头感兴趣就可以使用后两者
。 在这种场合下 *note BytesHeaderParser: adb. 和 *note HeaderParser:
adc. 速度非常快，因为它们并不会尝试解析消息体，而是将载荷设为原始数据。

 -- 類別: email.parser.BytesParser (_class=None, *,
          policy=policy.compat32)

     创建一个 *note BytesParser: c1c. 实例。 `_class' 和 `policy' 参数在
     含义和语义上与 *note BytesFeedParser: c1b. 的 `_factory' 和
     `policy' 参数一致。

     注：`一定要指定policy关键字'。在未来版本的Python当中，它的默认值会
     变成 *note email.policy.default: 2922. 。

     3.3 版更變: 移除了在2.4版本中被弃用的 `strict' 参数。新增了
     `policy' 关键字。

     3.6 版更變: `_class' 默认为策略 ‘message_factory’。

      -- 成員函式: parse (fp, headersonly=False)

          从二进制的类文件对象 `fp' 中读取全部数据、解析其字节内容、并返
          回消息对象。 `fp' 必须同时支持 *note readline(): 1849. 方法和
          ‘read()’ 方法。

          `fp' 内包含的字节内容必须是一块遵循 RFC 5322(1) （如果 ‘utf8’
          为 ‘True’，则为 RFC 6532(2) ）格式风格的消息头和消息头延续行，
          并可能紧跟一个信封头。 头块要么以数据结束，要么以一个空行为终
          止。 跟着头块的是消息体（消息体内可能包含 MIME 编码的子部分，
          这也包括 ‘Content-Transfer-Encoding’ 字段为 ‘8bit’ 的子部分）
          。

          可选的 `headersonly' 指示了是否应当在读取完消息头后就终止。默
          认值为 ‘False’ ，意味着它会解析整个文件的全部内容。

      -- 成員函式: parsebytes (bytes, headersonly=False)

          与 *note parse(): 2963. 方法类似，只不过它要求输入为一个 *note
          bytes-like object: 6df. 而不是类文件对象。于一个 *note
          bytes-like object: 6df. 调用此方法相当于先将这些字节包装于一个
          *note BytesIO: 88a. 实例中，然后调用 *note parse(): 2963. 方法
          。

          可选的 `headersonly' 与 *note parse(): 2963. 方法中的
          `headersonly' 是一致的。

     3.2 版新加入.

 -- 類別: email.parser.BytesHeaderParser (_class=None, *,
          policy=policy.compat32)

     除了 `headersonly' 默认为 ‘True’，其他与 *note BytesParser: c1c. 类
     完全一样。

     3.3 版新加入.

 -- 類別: email.parser.Parser (_class=None, *, policy=policy.compat32)

     这个类与 *note BytesParser: c1c. 一样，但是处理字符串输入。

     3.3 版更變: 移除了 `strict' 参数。添加了 `policy' 关键字。

     3.6 版更變: `_class' 默认为策略 ‘message_factory’。

      -- 成員函式: parse (fp, headersonly=False)

          从文本模式的文件类对象 `fp' 读取所有数据，解析所读取的文本，并
          返回根消息对象。 `fp' 必须同时支持文件类对象上的 *note
          readline(): 1d5b. 和 *note read(): 2162. 方法。

          除了文字模式的要求外，这个方法跟 *note BytesParser.parse():
          2963. 的运行方式一致。

      -- 成員函式: parsestr (text, headersonly=False)

          与 *note parse(): 2965. 方法类似，只不过它要求输入为一个字符串
          而不是类文件对象。于一个字符串对象调用此方法相当于先将 `text'
          包装于一个 *note StringIO: 91a. 实例中，然后调用 *note
          parse(): 2965. 方法。

          可选的 `headersonly' 与 *note parse(): 2965. 方法中的
          `headersonly' 是一致的。

 -- 類別: email.parser.HeaderParser (_class=None, *,
          policy=policy.compat32)

     除了 `headersonly' 默认为 ‘True’ ，其他与 *note Parser: beb. 类完全
     一样。

考虑到从一个字符串或一个文件对象中创建一个消息对象是非常常见的任务，我们
提供了四个方便的函数。它们于顶层 *note email: 67. 包命名空间内可用。

 -- 函式: email.message_from_bytes (s, _class=None, *,
          policy=policy.compat32)

     从一个 *note bytes-like object: 6df. 中返回消息对象。 这与
     ‘BytesParser().parsebytes(s)’ 等价。 可选的 `_class' 和 `policy' 参
     数与 *note BytesParser: c1c. 类的构造函数的参数含义一致。

     3.2 版新加入.

     3.3 版更變: 移除了 `strict' 参数。添加了 `policy' 关键字。

 -- 函式: email.message_from_binary_file (fp, _class=None, *,
          policy=policy.compat32)

     从打开的二进制 *note file object: c14. 中返回消息对象。 这与
     ‘BytesParser().parse(fp)’ 等价。 `_class' 和 `policy' 参数与 *note
     BytesParser: c1c. 类的构造函数的参数含义一致。

     3.2 版新加入.

     3.3 版更變: 移除了 `strict' 参数。添加了 `policy' 关键字。

 -- 函式: email.message_from_string (s, _class=None, *,
          policy=policy.compat32)

     从一个字符串中返回消息对象。 这与 ‘Parser().parsestr(s)’ 等价。
     `_class' 和 `policy' 参数与 *note Parser: beb. 类的构造函数的参数含
     义一致。

     3.3 版更變: 移除了 `strict' 参数。添加了 `policy' 关键字。

 -- 函式: email.message_from_file (fp, _class=None, *,
          policy=policy.compat32)

     从一个打开的 *note file object: c14. 中返回消息对象。 这与
     ‘Parser().parse(fp)’ 等价。 `_class' 和 `policy' 参数与 *note
     Parser: beb. 类的构造函数的参数含义一致。

     3.3 版更變: 移除了 `strict' 参数。添加了 `policy' 关键字。

     3.6 版更變: `_class' 默认为策略 ‘message_factory’。

这里是一个展示了你如何在Python交互式命令行中使用 *note
message_from_bytes(): c19. 的例子：

     >>> import email
     >>> msg = email.message_from_bytes(myBytes)

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc5322.html

   (2) https://tools.ietf.org/html/rfc6532.html


File: python.info,  Node: 附加说明,  Prev: Parser API,  Up: email parser 解析电子邮件信息

5.19.1.5 附加说明
.................

在解析语义的时候请注意：

   * 大多数非 ‘multipart’ 类型的消息都会被解析为一个带有字符串负载的消息
     对象。这些对象在调用 *note is_multipart(): 2927. 的时候会返回
     ‘False’ ，调用 *note iter_parts(): 294c. 的时候会产生一个空列表。

   * 所有 ‘multipart’ 类型的消息都会被解析成一个容器消息对象。该对象的负
     载是一个子消息对象列表。外层的容器消息在调用 *note is_multipart():
     2927. 的时候会返回 ‘True’ ，在调用 *note iter_parts(): 294c. 的时候
     会产生一个子部分列表。

   * 大多数内容类型为 ‘message/*’ （例如 ‘message/delivery-status’ 和
     ‘message/rfc822’ ）的消息也会被解析为一个负载是长度为1的列表的容器
     对象。在它们身上调用 *note is_multipart(): 2927. 方法会返回 ‘True’
     ，调用 *note iter_parts(): 294c. 所产生的单个元素会是一个子消息对象
     。

   * 一些不遵循标准的消息在其内部关于它是否为 ‘multipart’ 类型前后不一。
     这些消息可能在消息头的 ‘Content-Type’ 字段中写明为 ‘multipart’ ，但
     它们的 *note is_multipart(): 2927. 方法的返回值可能是 ‘False’ 。如
     果这种消息被 *note FeedParser: 295e. 类解析，它们的 `defects' 属性
     列表当中会有一个 ‘MultipartInvariantViolationDefect’ 类的实例。关于
     更多信息，详见 *note email.errors: 6b. 。


File: python.info,  Node: email generator 生成 MIME 文档,  Next: email policy Policy 对象,  Prev: email parser 解析电子邮件信息,  Up: email --- 电子邮件与 MIME 处理包

5.19.1.6 ‘email.generator’: 生成 MIME 文档
..........................................

`源代码:' Lib/email/generator.py(1)

__________________________________________________________________

最普通的一种任务是生成由消息对象结构体表示的电子邮件消息的扁平（序列化）
版本。 如果你想通过 *note smtplib.SMTP.sendmail(): 833. 或 *note
nntplib: c0. 模块来发送你的消息或是将消息打印到控制台就将需要这样做。 接
受一个消息对象结构体并生成其序列化表示就是这些生成器类的工作。

与 *note email.parser: 72. 模块一样，你并不会受限于已捆绑生成器的功能；
你可以自己从头写一个。 不过，已捆绑生成器知道如何以符合标准的方式来生成
大多数电子邮件，应该能够很好地处理 MIME 和非 MIME 电子邮件消息，并且被设
计为面向字节的解析和生成操作是互逆的，它假定两者都使用同样的非转换型
*note policy: 73.。 也就是说，通过 *note BytesParser: c1c. 类来解析序列
化字节流然后再使用 *note BytesGenerator: c1f. 来重新生成序列化字节流应当
得到与输入相同的结果 (2)。 （而另一方面，在由程序所构造的 *note
EmailMessage: 63c. 上使用生成器可能导致对默认填入的 *note EmailMessage:
63c. 对象的改变。。）

可以使用 *note Generator: c1e. 类将消息扁平化为文本（而非二进制数据）的
序列化表示形式，但是由于 Unicode 无法直接表示二进制数据，因此消息有必要
被转换为仅包含 ASCII 字符的数据，这将使用标准电子邮件 RFC 内容传输编码格
式技术来编码电子邮件消息以便通过非 “8 比特位兼容”的信道来传输。

为了适应 SMIME 签名消息的可重现处理过程，*note Generator: c1e. 禁用了针
对 ‘multipart/signed’ 类型的消息部分及所有子部分的标头折叠。

 -- 類別: email.generator.BytesGenerator (outfp, mangle_from_=None,
          maxheaderlen=None, *, policy=None)

     返回一个 *note BytesGenerator: c1f. 对象，该对象将把提供给 *note
     flatten(): 296c. 方法的任何消息或者提供给 *note write(): 296d. 方法
     的任何经过代理转义编码的文本写入到 *note file-like object: 1dc6.
     `outfp'。 `outfp' 必须支持接受二进制数据的 ‘write’ 方法。

     如果可选的 `mangle_from_' 为 ‘True’，则会将一个 ‘>’ 字符放到恰好以
     字符串 ‘"From "’ 打头，即开头文本为 ‘From’ 加一个空格的的行前面。
     `mangle_from_' 默认为 `policy' 的 *note mangle_from_: 7c3. 设置值
     (对于 *note compat32: 63a. 策略为 ‘True’，对于所有其他策略则为
     ‘False’)。 `mangle_from_' 被设计为在当消息以 unix mbox 格式存储时使
     用 (参见 *note mailbox: ae. 和 WHY THE CONTENT-LENGTH FORMAT IS
     BAD(3))。

     如果 `maxheaderlen' 不为 ‘None’，则重新折叠任何长于 `maxheaderlen'
     的标头行，或者如果为 ‘0’，则不重新包装任何标头。 如果
     `manheaderlen' 为 ‘None’ (默认值)，则根据 `policy' 设置包装标头和其
     他消息行。

     如果指定了 `policy'，则使用该策略来控制消息的生成。 如果 `policy' 为
     ‘None’ (默认值)，则使用与传递给 ‘flatten’ 的 *note Message: 63b. 或
     *note EmailMessage: 63c. 对象相关联的策略来控制消息的生成。 请参阅
     *note email.policy: 73. 了解有关 `policy' 所控制内容的详情。

     3.2 版新加入.

     3.3 版更變: 添加了*policy*关键字。

     3.6 版更變: `mangle_from_' 和 `maxheaderlen' 形参的默认行为是遵循策
     略。

      -- 成員函式: flatten (msg, unixfrom=False, linesep=None)

          将将以 `msg' 为根的消息对象结构体的文本表示形式打印到创建
          *note BytesGenerator: c1f. 实例时指定的输出文件。

          如果 *note policy: 73. 选项 *note cte_type: 296e. 为 ‘8bit’ (默
          认值)，则会将未被修改的原始已解析消息中的任何标头拷贝到输出，
          其中会重新生成与原始数据相同的高比特位组字节数据，并保留具有它
          们的任何消息体部分的非 ASCII ‘Content-Transfer-Encoding’。 如
          果 ‘cte_type’ 为 ‘7bit’，则会根据需要使用兼容 ASCII 的
          ‘Content-Transfer-Encoding’ 来转换高比特位组字节数据。 也就是
          说，将具有非 ASCII ‘Content-Transfer-Encoding’
          (‘Content-Transfer-Encoding: 8bit’) 的部分转换为兼容 ASCII 的
          ‘Content-Transfer-Encoding’，并使用 MIME ‘unknown-8bit’ 字符集
          来编码标头中不符合 RFC 的非 ASCII 字节数据，以使其符合 RFC。

          如果 `unixfrom' 为 ‘True’，则会在根消息对象的第一个 RFC
          5322(4) 标头之前打印 Unix mailbox 格式 (参见 *note mailbox:
          ae.) 所使用的封包标头分隔符。 如果根对象没有封包标头，则会创建
          一个标准标头。 默认值为 ‘False’。 请注意对于子部分来说，不会打
          印任何封包标头。

          如果 `linesep' 不为 ‘None’，则会将其用作扁平化消息的所有行之间
          的分隔符。 如果 `linesep' 为 ‘None’ (默认值)，则使用在
          `policy' 中指定的值。

      -- 成員函式: clone (fp)

          返回此 *note BytesGenerator: c1f. 实例的独立克隆，具有完全相同
          的选项设置，而 `fp' 为新的 `outfp'。

      -- 成員函式: write (s)

          使用 ‘ASCII’ 编解码器和 ‘surrogateescape’ 错误处理程序编码
          `s'，并将其传递给传入到 *note BytesGenerator: c1f. 的构造器的
          `outfp' 的 `write' 方法 。

作为一个便捷工具，*note EmailMessage: 63c. 提供了 *note as_bytes():
2925. 和 ‘bytes(aMessage)’ (即 *note __bytes__(): 2926.) 等方法，它们简
单地生成一个消息对象的序列化二进制表示形式。 更多细节请参阅 *note
email.message: 70.。

因为字符串无法表示二进制数据，*note Generator: c1e. 类必须将任何消息中扁
平化的任何二进制数据转换为兼容 ASCII 的格式，具体将其转换为兼容 ASCII 的
‘Content-Transfer_Encoding’。 使用电子邮件 RFC 的术语，你可以将其视作
*note Generator: c1e. 序列化为不 "支持 8 比特" 的 I/O 流。 换句话说，大
部分应用程序将需要使用 *note BytesGenerator: c1f.，而非 *note Generator:
c1e.。

 -- 類別: email.generator.Generator (outfp, mangle_from_=None,
          maxheaderlen=None, *, policy=None)

     返回一个 *note Generator: c1e.，它将把提供给 *note flatten(): 2970.
     方法的任何消息，或者提供给 *note write(): 2971. 方法的任何文本写入
     到 *note file-like object: 1dc6. `outfp'。 `outfp' 必须支持接受字符
     串数据的 ‘write’ 方法。

     如果可选的 `mangle_from_' 为 ‘True’，则会将一个 ‘>’ 字符放到恰好以
     字符串 ‘"From "’ 打头，即开头文本为 ‘From’ 加一个空格的的行前面。
     `mangle_from_' 默认为 `policy' 的 *note mangle_from_: 7c3. 设置值
     (对于 *note compat32: 63a. 策略为 ‘True’，对于所有其他策略则为
     ‘False’)。 `mangle_from_' 被设计为在当消息以 unix mbox 格式存储时使
     用 (参见 *note mailbox: ae. 和 WHY THE CONTENT-LENGTH FORMAT IS
     BAD(5))。

     如果 `maxheaderlen' 不为 ‘None’，则重新折叠任何长于 `maxheaderlen'
     的标头行，或者如果为 ‘0’，则不重新包装任何标头。 如果
     `manheaderlen' 为 ‘None’ (默认值)，则根据 `policy' 设置包装标头和其
     他消息行。

     如果指定了 `policy'，则使用该策略来控制消息的生成。 如果 `policy' 为
     ‘None’ (默认值)，则使用与传递给 ‘flatten’ 的 *note Message: 63b. 或
     *note EmailMessage: 63c. 对象相关联的策略来控制消息的生成。 请参阅
     *note email.policy: 73. 了解有关 `policy' 所控制内容的详情。

     3.3 版更變: 添加了*policy*关键字。

     3.6 版更變: `mangle_from_' 和 `maxheaderlen' 形参的默认行为是遵循策
     略。

      -- 成員函式: flatten (msg, unixfrom=False, linesep=None)

          将以 `msg' 为根的消息对象结构体的文本表示形式打印到当 *note
          Generator: c1e. 实例被创建时所指定的输出文件。

          如果 *note policy: 73. 选项 *note cte_type: 296e. 为 ‘8bit’，
          则视同选项被设为 ‘7bit’ 来生成消息。 （这是必需的，因为字符串
          无法表示非 ASCII 字节数据。） 将使用兼容 ASCII 的
          ‘Content-Transfer-Encoding’ 按需转换任何具有高比特位组的字节数
          据。 也就是说，将具有非 ASCII ‘Content-Transfer-Encoding’
          (‘Content-Transfer-Encoding: 8bit’) 的部分转换为兼容 ASCII 的
          ‘Content-Transfer-Encoding’，并使用 MIME ‘unknown-8bit’ 字符集
          来编码标头中不符合 RFC 的非 ASCII 字节数据，以使其符合 RFC。

          如果 `unixfrom' 为 ‘True’，则会在根消息对象的第一个 RFC
          5322(6) 标头之前打印 Unix mailbox 格式 (参见 *note mailbox:
          ae.) 所使用的封包标头分隔符。 如果根对象没有封包标头，则会创建
          一个标准标头。 默认值为 ‘False’。 请注意对于子部分来说，不会打
          印任何封包标头。

          如果 `linesep' 不为 ‘None’，则会将其用作扁平化消息的所有行之间
          的分隔符。 如果 `linesep' 为 ‘None’ (默认值)，则使用在
          `policy' 中指定的值。

          3.2 版更變: 添加了对重编码 ‘8bit’ 消息体的支持，以及 `linesep'
          参数。

      -- 成員函式: clone (fp)

          返回此 *note Generator: c1e. 实例的独立克隆，具有完全相同的选
          项设置，而 `fp' 为新的 `outfp'。

      -- 成員函式: write (s)

          将 `s' 写入到传给 *note Generator: c1e. 的构造器的 `outfp' 的
          `write' 方法。 这足够为 *note Generator: c1e. 实际提供可用于
          *note print(): 971. 函数的文件类 API。

作为一个便捷工具，*note EmailMessage: 63c. 提供了 *note as_string():
2923. 和 ‘str(aMessage)’ (即 *note __str__(): 2924.) 等方法，它们简单地
生成一个消息对象的已格式化字符串表示形式。 更多细节请参阅 *note
email.message: 70.。

*note email.generator: 6c. 模块还提供了一个派生类 *note
DecodedGenerator: 638.，它类似于 *note Generator: c1e. 基类，不同之处在
于非 ‘text’ 部分不会被序列化，而是被表示为 基于模板并填写了有关该部分的
信息的字符串输出流的形式。

 -- 類別: email.generator.DecodedGenerator (outfp, mangle_from_=None,
          maxheaderlen=None, fmt=None, *, policy=None)

     行为类似于 *note Generator: c1e.，不同之处在于对传给 *note
     Generator.flatten(): 2970. 的消息的任何子部分，如果该子部分的主类型
     为 ‘text’，则打印该子部分的已解码载荷，而如果其主类型不为 ‘text’，
     则不直接打印它而是使用来自该部分的信息填入字符串 `fmt' 并将填写完成
     的字符串打印出来。

     要填入 `fmt'，则执行 ‘fmt % part_info’，其中 ‘part_info’ 是由下列键
     和值组成的字典:

        * ‘type’ – 非 ‘text’ 部分的完整 MIME 类型

        * ‘maintype’ – 非 ‘text’ 部分的主 MIME 类型

        * ‘subtype’ – 非 ‘text’ 部分的子 MIME 类型

        * ‘filename’ – 非 ‘text’ 部分的文件名

        * ‘description’ – 与非 ‘text’ 部分相关联的描述

        * ‘encoding’ – 非 ‘text’ 部分的内容转换编码格式

     如果 `fmt' 为 ‘None’，则使用下列默认 `fmt':

          "[忽略消息的非文本 (%(type)s) 部分，文件名 %(filename)s]"

     可选的 `_mangle_from_' 和 `maxheaderlen' 与 *note Generator: c1e. 基
     类的相同。

註解
....

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/email/generator.py

   (2) (1) 此语句假定你使用了正确的 ‘unixfrom’ 设置，并且没有用于自动调
整的 ‘policy’ 设置调用（例如 ‘refold_source’ 必须为 ‘none’，这 `不是' 默
认值）。 这也不是 100% 为真，因为如果消息不遵循 RFC 标准则有时实际原始文
本的信息会在解析错误恢复时丢失。 它的目标是在可能的情况下修复这些后续边
缘情况。

   (3) https://www.jwz.org/doc/content-length.html

   (4) https://tools.ietf.org/html/rfc5322.html

   (5) https://www.jwz.org/doc/content-length.html

   (6) https://tools.ietf.org/html/rfc5322.html


File: python.info,  Node: email policy Policy 对象,  Next: email errors 异常和缺陷类,  Prev: email generator 生成 MIME 文档,  Up: email --- 电子邮件与 MIME 处理包

5.19.1.7 ‘email.policy’: Policy 对象
....................................

3.3 版新加入.

`源代码:' Lib/email/policy.py(1)

__________________________________________________________________

*note email: 67. 的主要焦点是按照各种电子邮件和 MIME RFC 的描述来处理电
子邮件消息。 但是电子邮件消息的基本格式（一个由名称加冒号加值的标头字段
构成的区块，后面再加一个空白行和任意的‘消息体’）是在电子邮件领域以外也获
得应用的格式。 这些应用的规则有些与主要电子邮件 RFC 十分接近，有些则很不
相同。 即使是操作电子邮件，有时也可能需要打破严格的 RFC 规则，例如生成可
与某些并不遵循标准的电子邮件服务器互联的电子邮件，或者是实现希望应用某些
破坏标准的操作方式的扩展。

Policy 对象给予 email 包处理这些不同用例的灵活性。

*note Policy: ad3. 对象封装了一组属性和方法用来在使用期间控制 email 包中
各个组件的行为。 *note Policy: ad3. 实例可以被传给 email 包中的多个类和
方法以更改它们的默认行为。 可设置的值及其默认值如下所述。

在 email 包中的所有类会使用一个默认的策略。 对于所有 *note parser: 72. 类
及相关的便捷函数，还有对于 *note Message: 63b. 类来说，它是 *note
Compat32: ad4. 策略，通过其对应的预定义实例 *note compat32: 63a. 来使用
。 这个策略提供了与 Python3.3 版之前的 email 包的完全向下兼容性（在某些
情况下，也包括对缺陷的兼容性）。

传给 *note EmailMessage: 63c. 的 `policy' 关键字的默认值是 *note
EmailPolicy: ad7. 策略，表示为其预定义的实例 *note default: 2922.。

在创建 *note Message: 63b. 或 *note EmailMessage: 63c. 对象时，它需要一
个策略。 如果消息是由 *note parser: 72. 创建的，则传给该解析器的策略将是
它所创建的消息所使用的策略。 如果消息是由程序创建的，则该策略可以在创建
它的时候指定。 当消息被传递给 *note generator: 6c. 时，生成器默认会使用
来自该消息的策略，但你也可以将指定的策略传递给生成器，这将覆盖存储在消息
对象上的策略。

*note email.parser: 72. 类和解析器便捷函数的 `policy' 关键字的默认值在未
来的 Python 版本中 `将会改变'。 因此在调用任何 *note parser: 72. 模块所
描述的类和函数时你应当 `总是显式地指定你想要使用的策略'。

本文档的第一部分介绍了 *note Policy: ad3. 的特性，它是一个 *note
abstract base class: c05.，定义了所有策略对象包括 *note compat32: 63a. 的
共有特性。 这些特性包括一些由 email 包内部调用的特定钩子方法，自定义策略
可以重载这些方法以获得不同行为。 第二部分描述了实体类 *note EmailPolicy:
ad7. 和 *note Compat32: ad4.，它们分别实现了提供标准行为和向下兼容行为与
特性的钩子。

*note Policy: ad3. 实例是不可变的，但它们可以被克隆，接受与类构造器一致
的关键字参数并返回一个新的 *note Policy: ad3. 实例，新实例是原实例的副本
，但具有被改变的指定属性。

例如，以下代码可以被用来从一个 Unix 系统的磁盘文件中读取电子邮件消息并将
其传递给系统的 ‘sendmail’ 程序:

     >>> 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()

这里我们让 *note BytesGenerator: c1f. 在创建要送入 ‘sendmail's’ ‘stdin’
的二进制字串时使用符合 RFC 的行分隔字符，默认的策略将会使用 ‘\n’ 行分隔
符。

某些 email 包的方法接受一个 `policy' 关键字参数，允许为该方法重载策略。
例如，以下代码使用了来自之前示例的 `msg' 对象的 *note as_bytes(): 92d. 方
法并使用其运行所在平台的本机行分隔符将消息写入一个文件:

     >>> import os
     >>> with open('converted.txt', 'wb') as f:
     ...     f.write(msg.as_bytes(policy=msg.policy.clone(linesep=os.linesep)))
     17

Policy 对象也可使用加法运算符进行组合来产生一个新策略对象，其设置是被加
总对象的非默认值的组合:

     >>> compat_SMTP = policy.compat32.clone(linesep='\r\n')
     >>> compat_strict = policy.compat32.clone(raise_on_defect=True)
     >>> compat_strict_SMTP = compat_SMTP + compat_strict

此运算不满足交换律；也就是说对象的添加顺序很重要。 见以下演示:

     >>> 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

 -- 類別: email.policy.Policy (**kw)

     这是所有策略类的 *note abstract base class: c05.。 它提供了一些简单
     方法的默认实现，以及不可变特征属性，*note clone(): ad5. 方法以及构
     造器语义的实现。

     可以向策略类的构造器传入各种关键字参数。 可以指定的参数是该类的任何
     非方法特征属性，以及实体类的任何额外非方法特征属性。 在构造器中指定
     的值将覆盖相应属性的默认值。

     这个类定义了下列特征属性，因此下列值可以被传给任何策略类的构造器:

      -- 屬性: max_line_length

          序列化输出中任何行的最大长度，不计入行字符的末尾。 默认值为
          78，基于 RFC 5322(2)。 值为 ‘0’ 或 *note None: 203. 表示完全没
          有行包装。

      -- 屬性: linesep

          用来在序列化输出中确定行的字符串。 默认值为 ‘\n’ 因为这是
          Python 所使用的内部行结束符规范，但 RFC 的要求是 ‘\r\n’。

      -- 屬性: cte_type

          控制可能要求使用的内容传输编码格式类型。 可能的值包括:

          ‘7bit’       所有数据必须为 "纯 7 比特位" (仅 ASCII)。 这意味着在必要情况下数
                       据将使用可打印引用形式或 base64 编码格式进行编码。
                       
                       
          ‘8bit’       数据不会被限制为纯 7 比特位。 标头中的数据仍要求仅 ASCII 因此将被
                       编码（参阅下文的 *note fold_binary(): 2977. 和 *note utf8: 7c5. 了
                       解例外情况），但消息体部分可能使用 ‘8bit’ CTE。
                       

          ‘cte_type’ 值为 ‘8bit’ 仅适用于 ‘BytesGenerator’ 而非
          ‘Generator’，因为字符串不能包含二进制数据。 如果 ‘Generator’ 运
          行于指定了 ‘cte_type=8bit’ 的策略，它的行为将与 ‘cte_type’ 为
          ‘7bit’ 相同。

      -- 屬性: raise_on_defect

          如为 *note True: 593.，则遇到的任何缺陷都将引发错误。 如为
          *note False: 48e. (默认值)，则缺陷将被传递给 *note
          register_defect(): 2979. 方法。

      -- 屬性: mangle_from_

          如为 *note True: 593.，则消息体中以 `"From "' 开头的行会通过在
          其前面放一个 ‘>’ 来进行转义。 当消息被生成器执行序列化时会使用
          此形参。 默认值t: *note False: 48e.。

          3.5 版新加入: `mangle_from_' 形参。

      -- 屬性: message_factory

          用来构造新的空消息对象的工厂函数。 在构建消息时由解析器使用。
          默认为 ‘None’，在此情况下会使用 *note Message: 63b.。

          3.6 版新加入.

     下列 *note Policy: ad3. 方法是由使用 email 库的代码来调用以创建具有
     自室外设置的策略实例:

      -- 成員函式: clone (**kw)

          返回一个新的 *note Policy: ad3. 实例，其属性与当前实例具有相同
          的值，除非是那些由关键字参数给出了新值的属性。

     其余的 *note Policy: ad3. 方法是由 email 包代码来调用的，而不应当被
     使用 email 包的应用程序所调用。 自定义的策略必须实现所有这些方法。

      -- 成員函式: handle_defect (obj, defect)

          处理在 `obj' 上发现的 `defect'。 当 email 包调用此方法时，
          `defect' 将总是 ‘Defect’ 的一个子类。

          默认实现会检查 *note raise_on_defect: 2978. 旗标。 如果其为
          ‘True’，则 `defect' 会被作为异常来引发。 如果其为 ‘False’ (默
          认值)，则 `obj' 和 `defect' 会被传递给 *note
          register_defect(): 2979.。

      -- 成員函式: register_defect (obj, defect)

          在 `obj' 上注册一个 `defect'。 在 email 包中，`defect' 将总是
          ‘Defect’ 的一个子类。

          默认实现会调用 `obj' 的 ‘defects’ 属性的 ‘append’ 方法。 当
          email 包调用 *note handle_defect: 297a. 时，`obj' 通常将具有一
          个带 ‘append’ 方法的 ‘defects’ 属性。 配合 email 包使用的自定
          义对象类型（例如自定义的 ‘Message’ 对象）也应当提供这样的属性
          ，否则在被解析消息中的缺陷将引发非预期的错误。

      -- 成員函式: header_max_count (name)

          返回名为 `name' 的标头的最大允许数量。

          当添加一个标头到 *note EmailMessage: 63c. 或 *note Message:
          63b. 对象时被调用。 如果返回值不为 ‘0’ 或 ‘None’，并且已有的名
          称为 `name' 的标头数量大于等于所返回的值，则会引发 *note
          ValueError: 16d.。

          由于 ‘Message.__setitem__’ 的默认行为是将值添加到标头列表，因
          此很容易不知情地创建重复的标头。 此方法允许在程序中限制可以被
          添加到 ‘Message’ 中的特定标头的实例数量。 （解析器不会考虑此限
          制，它将忠实地产生被解析消息中存在的任意数量的标头。）

          默认实现对于所有标头名称都返回 ‘None’。

      -- 成員函式: header_source_parse (sourcelines)

          email 包调用此方法时将传入一个字符串列表，其中每个字符串以在被
          解析源中找到的行分隔符结束。 第一行包括字段标头名称和分隔符。
          源中的所有空白符都会被保留。 此方法应当返回 ‘(name, value)’ 元
          组以保存至 ‘Message’ 中来代表被解析的标头。

          如果一个实现希望保持与现有 email 包策略的兼容性，则 `name' 应
          当为保留大小写形式的名称（所有字符直至 ’‘:’’ 分隔符），而
          `value' 应当为展开后的值（移除所有行分隔符，但空白符保持不变）
          ，并移除开头的空白符。

          `sourcelines' 可以包含经替代转义的二进制数据。

          此方法没有默认实现

      -- 成員函式: header_store_parse (name, value)

          当一个应用通过程序代码修改 ‘Message’ (而不是由解析器创建
          ‘Message’) 时，email 包会调用此方法并附带应用程序所提供的名称
          和值。 此方法应当返回 ‘(name, value)’ 元组以保存至 ‘Message’ 中
          用来表示标头。

          如果一个实现希望保持与现有 email 包策略的兼容性，则 `name' 和
          `value' 应当为字符串或字符串的子类，它们不会修改在参数中传入的
          内容。

          此方法没有默认实现

      -- 成員函式: header_fetch_parse (name, value)

          当标头被应用程序所请求时，email 包会调用此方法并附带当前保存在
          ‘Message’ 中的 `name' 和 `value'，并且无论此方法返回什么它都会
          被回传给应用程序作为被提取标头的值。 请注意可能会有多个相同名
          称的标头被保存在 ‘Message’ 中；此方法会将指定标头的名称和值返
          回给应用程序。

          `value' 可能包含经替代转义的二进制数据。 此方法所返回的值应当
          没有经替代转义的二进制数据。

          此方法没有默认实现

      -- 成員函式: fold (name, value)

          email 包调用此方法时会附带当前保存在 ‘Message’ 中的给定标头的
          `name' 和 `value'。 此方法应当返回一个代表该标头的（根据策略设
          置）通过处理 `name' 和 `value' 并在适当位置插入 *note linesep:
          2976. 字符来正确地“折叠”的字符串。 请参阅 RFC 5322(3) 了解有关
          折叠电子邮件标头的规则的讨论。

          `value' 可能包含经替代转义的二进制数据。 此方法所返回的字符串
          应当没有经替代转义的二进制数据。

      -- 成員函式: fold_binary (name, value)

          与 *note fold(): 297f. 类似，不同之处在于返回的值应当为字节串
          对象而非字符串。

          `value' 可能包含经替代转义的二进制数据。 这些数据可以在被返回
          的字节串对象中被转换回二进制数据。

 -- 類別: email.policy.EmailPolicy (**kw)

     这个实体 *note Policy: ad3. 提供了完全遵循当前电子邮件 RFC 的行为。
     这包括 (但不限于) RFC 5322(4), RFC 2047(5) 以及当前的各种 MIME RFC。

     此策略添加了新的标头解析和折叠算法。 标头不是简单的字符串，而是带有
     依赖于字段类型的属性的 ‘str’ 的子类。 这个解析和折叠算法完整实现了
     RFC 2047(6) 和 RFC 5322(7)。

     *note message_factory: 639. 属性的默认值为 *note EmailMessage:
     63c.。

     除了上面列出的适用于所有策略的可设置属性，此策略还添加了下列额外属
     性:

     3.6 版新加入: (8)

      -- 屬性: utf8

          如为 ‘False’，则遵循 RFC 5322(9)，通过编码为“已编码字”来支持标
          头中的非 ASCII 字符。 如为 ‘True’，则遵循 RFC 6532(10) 并对标
          头使用 ‘utf-8’ 编码格式。 以此方式格式化的消息可被传递给支持
          ‘SMTPUTF8’ 扩展 ( RFC 6531(11)) 的 SMTP 服务器。

      -- 屬性: refold_source

          如果 ‘Message’ 对象中标头的值源自 *note parser: 72. (而非由程
          序设置)，此属性会表明当将消息转换回序列化形式时是否应当由生成
          器来重新折叠该值。 可能的值如下:

          ‘none’       所有源值使用原始折叠
                       
                       
          ‘long’       具有任何长度超过 ‘max_line_length’ 的行的源值将被折叠
                       
                       
          ‘all’        所有值会被重新折叠。
                       

          默认值为 ‘long’。

      -- 屬性: header_factory

          该可调用对象接受两个参数，‘name’ 和 ‘value’，其中 ‘name’ 为标
          头字段名而 ‘value’ 为展开后的标头字段值，并返回一个表示该标头
          的字符串子类。 已提供的默认 ‘header_factory’ (参见 *note
          headerregistry: 6e.) 支持对各种地址和日期 RFC 5322(12) 标头字
          段类型及主要 MIME 标头字段类型的自定义解析。 未来还将添加对其
          他自定义解析的支持。

      -- 屬性: content_manager

          此对象至少有两个方法: get_content 和 set_content。 当一个
          *note EmailMessage: 63c. 对象的 *note get_content(): 294d. 或
          *note set_content(): f81. 方法被调用时，它会调用此对象的相应方
          法，将消息对象作为其第一个参数，并将传给它的任何参数或关键字作
          为附加参数传入。 默认情况下 ‘content_manager’ 会被设为 *note
          raw_data_manager: 2982.。

          3.4 版新加入.

     这个类提供了下列对 *note Policy: ad3. 的抽象方法的具体实现:

      -- 成員函式: header_max_count (name)

          返回用来表示具有给定名称的标头的专用类的 *note max_count:
          2984. 属性的值。

      -- 成員函式: header_source_parse (sourcelines)

          此名称会被作为到 ’‘:’’ 止的所有内容来解析。 该值是通过从第一行
          的剩余部分去除前导空格，再将所有后续行连接到一起，并去除所有末
          尾回车符或换行符来确定的。

      -- 成員函式: header_store_parse (name, value)

          name 将会被原样返回。 如果输入值具有 ‘name’ 属性并可在忽略大小
          写的情况下匹配 `name'，则 value 也会被原样返回。 在其他情况下
          `name' 和 `value' 会被传递给 ‘header_factory’，并将结果标头对
          象作为值返回。 在此情况下如果输入值包含 CR 或 LF 字符则会引发
          ‘ValueError’。

      -- 成員函式: header_fetch_parse (name, value)

          如果值具有 ‘name’ 属性，它会被原样返回。 在其他情况下 `name' 和
          移除了所有 CR 和 LF 字符的 `value' 会被传递给
          ‘header_factory’，并返回结果标头对象。 任何经替代转义的字节串
          会被转换为 unicode 未知字符字形。

      -- 成員函式: fold (name, value)

          标头折叠是由 *note refold_source: 2980. 策略设置来控制的。 当
          且仅当一个值没有 ‘name’ 属性（具有 ‘name’ 属性就意味着它是某种
          标头对象）它才会被当作是“源值”。 如果一个原值需要按照策略来重
          新折叠，则会通过将 `name' 和去除了所有 CR 和 LF 字符的 `value'
          传递给 ‘header_factory’ 来将其转换为标头对象。 标头对象的折叠
          是通过调用其 ‘fold’ 方法并附带当前策略来完成的。

          源值会使用 *note splitlines(): 178c. 来拆分成多行。 如果该值不
          被重新折叠，则会使用策略中的 ‘linesep’ 重新合并这些行并将其返
          回。 例外的是包含非 ascii 二进制数据的行。 在此情况下无论
          ‘refold_source’ 如何设置该值都会被重新折叠，这会导致二进制数据
          使用 ‘unknown-8bit’ 字符集进行 CTE 编码。

      -- 成員函式: fold_binary (name, value)

          如果 *note cte_type: 296e. 为 ‘7bit’ 则与 *note fold(): 2988.
          类似，不同之处在于返回的值是字节串。

          如果 *note cte_type: 296e. 为 ‘8bit’，则将非 ASCII 二进制数据
          转换回字节串。 带有二进制数据的标头不会被重新折叠，无论
          ‘refold_header’ 设置如何，因为无法知晓该二进制数据是由单字节字
          符还是多字节字符组成的。

以下 *note EmailPolicy: ad7. 的实例提供了适用于特定应用领域的默认值。 请
注意在未来这些实例（特别是 ‘HTTP’ 实例）的行为可能会被调整以便更严格地遵
循与其领域相关的 RFC。

 -- Data: email.policy.default

     一个未改变任何默认值的 ‘EmailPolicy’ 实例。 此策略使用标准的 Python
     ‘\n’ 行结束符而非遵循 RFC 的 ‘\r\n’。

 -- Data: email.policy.SMTP

     适用于按照符合电子邮件 RFC 的方式来序列化消息。 与 ‘default’ 类似，
     但 ‘linesep’ 被设为遵循 RFC 的 ‘\r\n’。

 -- Data: email.policy.SMTPUTF8

     与 ‘SMTP’ 类似但是 *note utf8: 7c5. 为 ‘True’。 适用于在不使用标头
     内已编码字的情况下对消息进行序列化。 如果发送方或接收方地址具有非
     ASCII 字符则应当只被用于 SMTP 传输 (*note
     smtplib.SMTP.send_message(): 834. 方法会自动如此处理)。

 -- Data: email.policy.HTTP

     适用于序列化标头以在 HTTP 通信中使用。 与 ‘SMTP’ 类似但是
     ‘max_line_length’ 被设为 ‘None’ (无限制)。

 -- Data: email.policy.strict

     便捷实例。 与 ‘default’ 类似但是 ‘raise_on_defect’ 被设为 ‘True’。
     这样可以允许通过以下写法来严格地设置任何策略:

          somepolicy + policy.strict

因为所有这些 *note EmailPolicies: ad7.，email 包的高效 API 相比 Python
3.2 API 发生了以下几方面变化:

        * 在 *note Message: 63b. 中设置标头将使得该标头被解析并创建一个
          标头对象。

        * 从 *note Message: 63b. 提取标头将使得该标头被解析并创建和返回
          一个标头对象。

        * 任何标头对象或任何由于策略设置而被重新折叠的标头都会使用一种完
          全实现了 RFC 折叠算法的算法来进行折叠，包括知道在休息需要并允
          许已编码字。

从应用程序的视角来看，这意味着任何通过 *note EmailMessage: 63c. 获得的标
头都是具有附加属性的标头对象，其字符串值都是该标头的完全解码后的 unicode
值。 类似地，可以使用 unicode 对象为一个标头赋予新的值，或创建一个新的标
头对象，并且该策略将负责把该 unicode 字符串转换为正确的 RFC 已编码形式。

标头对象及其属性的描述见 *note headerregistry: 6e.。

 -- 類別: email.policy.Compat32 (**kw)

     这个实体 *note Policy: ad3. 为向下兼容策略。 它复制了 Python 3.2 中
     email 包的行为。 *note policy: 73. 模块还定义了该类的一个实例 *note
     compat32: 63a.，用来作为默认策略。 因此 email 包的默认行为会保持与
     Python 3.2 的兼容性。

     下列属性具有与 *note Policy: ad3. 默认值不同的值:

      -- 屬性: mangle_from_

          默认值为 ‘True’。

     这个类提供了下列对 *note Policy: ad3. 的抽象方法的具体实现:

      -- 成員函式: header_source_parse (sourcelines)

          此名称会被作为到 ’‘:’’ 止的所有内容来解析。 该值是通过从第一行
          的剩余部分去除前导空格，再将所有后续行连接到一起，并去除所有末
          尾回车符或换行符来确定的。

      -- 成員函式: header_store_parse (name, value)

          name 和 value 会被原样返回。

      -- 成員函式: header_fetch_parse (name, value)

          如果 value 包含二进制数据，则会使用 ‘unknown-8bit’ 字符集来将
          其转换为 *note Header: f83. 对象。 在其他情况下它会被原样返回
          。

      -- 成員函式: fold (name, value)

          标头会使用 *note Header: f83. 折叠算法进行折叠，该算法保留
          value 中现有的换行，并将每个结果行的长度折叠至
          ‘max_line_length’。 非 ASCII 二进制数据会使用 ‘unknown-8bit’ 字
          符串进行 CTE 编码。

      -- 成員函式: fold_binary (name, value)

          标头会使用 *note Header: f83. 折叠算法进行折叠，该算法保留
          value 中现有的换行，并将每个结果行的长度折叠至
          ‘max_line_length’。 如果 ‘cte_type’ 为 ‘7bit’，则非 ascii 二进
          制数据会使用 ‘unknown-8bit’ 字符集进行 CTE 编码。 在其他情况下
          则会使用原始的源标头，这将保留其现有的换行和所包含的任何（不符
          合 RFC 的）二进制数据。

 -- Data: email.policy.compat32

     *note Compat32: ad4. 的实例，提供与 Python 3.2 中的 email 包行为的
     向下兼容性。

脚注
....

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/email/policy.py

   (2) https://tools.ietf.org/html/rfc5322.html

   (3) https://tools.ietf.org/html/rfc5322.html

   (4) https://tools.ietf.org/html/rfc5322.html

   (5) https://tools.ietf.org/html/rfc2047.html

   (6) https://tools.ietf.org/html/rfc2047.html

   (7) https://tools.ietf.org/html/rfc5322.html

   (8) (1) 最初在 3.3 中作为 *note 暂定特性: a61. 添加。

   (9) https://tools.ietf.org/html/rfc5322.html

   (10) https://tools.ietf.org/html/rfc6532.html

   (11) https://tools.ietf.org/html/rfc6531.html

   (12) https://tools.ietf.org/html/rfc5322.html


File: python.info,  Node: email errors 异常和缺陷类,  Next: email headerregistry 自定义标头对象,  Prev: email policy Policy 对象,  Up: email --- 电子邮件与 MIME 处理包

5.19.1.8 ‘email.errors’: 异常和缺陷类
.....................................

`源代码:' Lib/email/errors.py(1)

__________________________________________________________________

以下异常类在 *note email.errors: 6b. 模块中定义：

 -- 例外: email.errors.MessageError

     这是 *note email: 67. 包可以引发的所有异常的基类。 它源自标准异常
     *note Exception: 2dc. 类，这个类没有定义其他方法。

 -- 例外: email.errors.MessageParseError

     这是由 *note Parser: beb. 类引发的异常的基类。它派生自 *note
     MessageError: 2996.。 *note headerregistry: 6e. 使用的解析器也在内
     部使用这个类。

 -- 例外: email.errors.HeaderParseError

     在解析消息的 RFC 5322(2) 标头时，某些错误条件下会触发，此类派生自
     *note MessageParseError: 2997.。 如果在调用方法时内容类型未知，则
     *note set_boundary(): 2942. 方法将引发此错误。 当尝试创建一个看起来
     包含嵌入式标头的标头时 *note Header: f83. 可能会针对某些 base64 解
     码错误引发此错误（也就是说，应该是一个 没有前导空格并且看起来像标题
     的延续行）。

 -- 例外: email.errors.BoundaryError

     已弃用和不再使用的。

 -- 例外: email.errors.MultipartConversionError

     当使用 ‘add_payload()’ 将有效负载添加到 *note Message: 63b. 对象时
     ，有效负载已经是一个标量，而消息的 ‘Content-Type’ 主类型不是
     ‘multipart’ 或者缺少时触发该异常。 *note MultipartConversionError:
     2999. 多重继承自 *note MessageError: 2996. 和内置的 *note
     TypeError: 1fe.。

     由于 ‘Message.add_payload()’ 已被弃用，此异常实际上极少会被引发。 但
     是如果在派生自 *note MIMENonMultipart: f59. 的类 (例如 *note
     MIMEImage: 299a.) 的实例上调用 *note attach(): 2954. 方法也可以引发
     此异常。

以下是 *note FeedParser: 295e. 在解析消息时可发现的缺陷列表。 请注意这些
缺陷会在问题被发现时加入到消息中，因此举例来说，如果某条嵌套在
‘multipart/alternative’ 中的消息具有错误的标头，该嵌套消息对象就会有一条
缺陷，但外层消息对象则没有。

所有缺陷类都是 ‘email.errors.MessageDefect’ 的子类。

   * ‘NoBoundaryInMultipartDefect’ – 一条消息宣称有多个部分，但却没有
     ‘boundary’ 形参。

   * ‘StartBoundaryNotFoundDefect’ – 在 ‘Content-Type’ 标头中宣称的开始
     边界无法被找到。

   * ‘CloseBoundaryNotFoundDefect’ – 找到了开始边界，但相应的结束边界无
     法被找到。

     3.3 版新加入.

   * ‘FirstHeaderLineIsContinuationDefect’ – 消息以一个继续行作为其第一
     个标头行。

   * ‘MisplacedEnvelopeHeaderDefect’ - 在标头块中间发现了一个 "Unix
     From" 标头。

   * ‘MissingHeaderBodySeparatorDefect’ - 在解析没有前缀空格但又不包含
     ’:’ 的标头期间找到一行内容。 解析将假定该行表示消息体的第一行以继续
     执行。

     3.3 版新加入.

   * ‘MalformedHeaderDefect’ – 找到一个缺失了冒号或格式错误的标头。

     3.3 版後已棄用: 此缺陷在近几个 Python 版本中已不再使用。

   * ‘MultipartInvariantViolationDefect’ – 一条消息宣称为 ‘multipart’，
     但无法找到任何子部分。 请注意当一条消息有此缺陷时，其 *note
     is_multipart(): 2947. 方法可能返回 ‘False’，即使其内容类型宣称为
     ‘multipart’。

   * ‘InvalidBase64PaddingDefect’ – 当解码一个 base64 编码的字节分块时，
     填充的数据不正确。 虽然添加了足够的填充数据以执行解码，但作为结果的
     已解码字节串可能无效。

   * ‘InvalidBase64CharactersDefect’ – 当解码一个 base64 编码的字节分块
     时，遇到了 base64 字符表以外的字符。 这些字符会被忽略，但作为结果的
     已解码字节串可能无效。

   * ‘InvalidBase64LengthDefect’ – 当解码一个 base64 编码的字节分块时，
     非填充 base64 字符的数量无效（比 4 的倍数多 1）。 已编码分块会保持
     原样。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/email/errors.py

   (2) https://tools.ietf.org/html/rfc5322.html


File: python.info,  Node: email headerregistry 自定义标头对象,  Next: email contentmanager 管理 MIME 内容,  Prev: email errors 异常和缺陷类,  Up: email --- 电子邮件与 MIME 处理包

5.19.1.9 ‘email.headerregistry’: 自定义标头对象
...............................................

`源代码:' Lib/email/headerregistry.py(1)

__________________________________________________________________

3.6 版新加入: (2)

标头是由 *note str: 205. 的自定义子类来表示的。 用于表示给定标头的特定类
则由创建标头时生效的 *note policy: 73. 的 *note header_factory: 2981. 确
定。 这一节记录了 email 包为处理兼容 RFC 5322(3) 的电子邮件消息所实现的
特定 ‘header_factory’，它不仅为各种标头类型提供了自定义的标头对象，还为
应用程序提供了添加其自定义标头类型的扩展机制。

当使用派生自 *note EmailPolicy: ad7. 的任何策略对象时，所有标头都通过
*note HeaderRegistry: 299d. 产生并且以 *note BaseHeader: 2930. 作为其最
后一个基类。 每个标头类都有一个由该标头类型确定的附加基类。 例如，许多标
头都以 *note UnstructuredHeader: 299e. 类作为其另一个基类。 一个标头专用
的第二个类是由标头名称使用存储在 *note HeaderRegistry: 299d. 中的查找表
来确定的。 所有这些都针对典型应用程序进行透明的管理，但也为修改默认行为
提供了接口，以便由更复杂的应用使用。

以下各节首先记录了标头基类及其属性，然后是用于修改 *note HeaderRegistry:
299d. 行为的 API，最后是用于表示从结构化标头解析的数据的支持类。

 -- 類別: email.headerregistry.BaseHeader (name, value)

     `name' 和 `value' 会从 *note header_factory: 2981. 调用传递给
     ‘BaseHeader’。 任何标头对象的字符串值都是完成解码为 unicode 的
     `value'。

     这个基类定义了下列只读属性:

      -- 屬性: name

          标头的名称（字段在 ’:’ 之前的部分）。 这就是 `name' 的 *note
          header_factory: 2981. 调用所传递的值；也就是说会保持大小写形式
          。

      -- 屬性: defects

          一个包含 ‘HeaderDefect’ 实例的元组，这些实例报告了在解析期间发
          现的任何 RFC 合规性问题。 email 包会尝试尽可能地检测合规性问题
          。 请参阅 *note errors: 6b. 模块了解可能被报告的缺陷类型的相关
          讨论。

      -- 屬性: max_count

          此类型标头可具有相同 ‘name’ 的最大数量。 ‘None’ 值表示无限制。
          此属性的 ‘BaseHeader’ 值为 ‘None’；专用的标头类预期将根据需要
          重载这个值。

     ‘BaseHeader’ 还提供了以下方法，它由 email 库代码调用，通常不应当由
     应用程序来调用。

      -- 成員函式: fold (*, policy)

          返回一个字符串，其中包含用来根据 `policy' 正确地折叠标头的
          *note linesep: 2976. 字符。 *note cte_type: 296e. 为 ‘8bit’ 时
          将被作为 ‘7bit’ 来处理，因为标头不能包含任意二进制数据。 如果
          *note utf8: 7c5. 为 ‘False’，则非 ASCII 数据将根据 RFC 2047(4)
          来编码。

     ‘BaseHeader’ 本身不能被用于创建标头对象。 它定义了一个与每个专用标
     头相配合的协议以便生成标头对象。 具体来说，‘BaseHeader’ 要求专用类
     提供一个名为 ‘parse’ 的 *note classmethod(): 309.。 此方法的调用形
     式如下:

          parse(string, kwds)

     ‘kwds’ 是包含了一个预初始化键 ‘defects’ 的字典。 ‘defects’ 是一个空
     列表。 parse 方法应当将任何已检测到的缺陷添加到此列表中。 在返回时
     ，‘kwds’ 字典 `必须' 至少包含 ‘decoded’ 和 ‘defects’ 等键的值。
     ‘decoded’ 应当是标头的字符串值（即完全解码为 unicode 的标头值）。
     parse 方法应当假定 `string' 可能包含 content-transfer-encoded 部分
     ，但也应当正确地处理全部有效的 unicode 字符以便它能解析未经编码的标
     头值。

     随后 ‘BaseHeader’ 的 ‘__new__’ 会创建标头实例，并调用其 ‘init’ 方法
     。 专属类如果想要设置 ‘BaseHeader’ 自身所提供的属性之外的附加属性，
     只需提供一个 ‘init’ 方法。 这样的 ‘init’ 看起来应该是这样:

          def init(self, /, *args, **kw):
              self._myattr = kw.pop('myattr')
              super().init(*args, **kw)

     也就是说，专属类放入 ‘kwds’ 字典的任何额外内容都应当被移除和处理，
     并且 ‘kw’ (和 ‘args’) 的剩余内容会被传递给 ‘BaseHeader’ ‘init’ 方法
     。

 -- 類別: email.headerregistry.UnstructuredHeader

     "非结构化" 标头是 RFC 5322(5) 中默认的标头类型。 任何没有指定语法的
     标头都会被视为是非结构化的。 非结构化标头的经典例子是 ‘Subject’ 标
     头。

     在 RFC 5322(6) 中，非结构化标头是指一段以 ASCII 字符集表示的任意文
     本。 但是 RFC 2047(7) 具有一个 RFC 5322(8) 兼容机制用来将标头值中的
     非 ASCII 文本编码为 ASCII 字符。 当包含已编码字的 `value' 被传递给
     构造器时，‘UnstructuredHeader’ 解析器会按照非结构化文本的 RFC
     2047(9) 规则将此类已编码字转换为 unicode。 解析器会使用启发式机制来
     尝试解码一些不合规的已编码字。 在此种情况下各类缺陷，例如已编码字或
     未编码文本中的无效字符问题等缺陷将会被注册。

     此标头类型未提供附加属性。

 -- 類別: email.headerregistry.DateHeader

     RFC 5322(10) 为电子邮件标头内的日期指定了非常明确的格式。
     ‘DateHeader’ 解析器会识别该日期格式，并且也能识别间或出现的一些“不
     规范”变种形式。

     这个标头类型提供了以下附加属性。

      -- 屬性: datetime

          如果标头值能被识别为某一种有效的日期形式，此属性将包含一个代表
          该日期的 *note datetime: 19f. 实例。 如果输入日期的时区被指定
          为 ‘-0000’ (表示为 UTC 但不包含源时区的相关信息)，则 *note
          datetime: 29a3. 将为简单型 *note datetime: 19f.。 如果找到了特
          定的时区时差值 (包括 ‘+0000’)，则 *note datetime: 29a3. 将包含
          使用 *note datetime.timezone: ae0. 来记录时区时差时的感知型
          ‘datetime’。

     标头的 ‘decoded’ 值是由按照 RFC 5322(11) 对 ‘datetime’ 进行格式化来
     确定的；也就是说，它会被设为:

          email.utils.format_datetime(self.datetime)

     当创建 ‘DateHeader’ 时，`value' 可以为 *note datetime: 19f. 实例。
     例如这意味着以下代码是有效的并能实现人们预期的行为:

          msg['Date'] = datetime(2011, 7, 15, 21)

     因为这是个简单型 ‘datetime’ 它将被解读为 UTC 时间戳，并且结果值的时
     区将为 ‘-0000’。 使用来自 *note utils: 74. 模块的 *note
     localtime(): adf. 函数会更有用:

          msg['Date'] = utils.localtime()

     这个例子将日期标头设为使用当前时区时差值的当前时间和日期。

 -- 類別: email.headerregistry.AddressHeader

     地址标头是最复杂的结构化标头类型之一。 ‘AddressHeader’ 类提供了适合
     任何地址标头的泛用型接口。

     这个标头类型提供了以下附加属性。

      -- 屬性: groups

          编码了在标头值中找到的地址和分组的 *note Group: 29a6. 对象的元
          组。 非分组成员的地址在此列表中表示为 *note display_name:
          29a7. 为 ‘None’ 的单地址 ‘Groups’。

      -- 屬性: addresses

          编码了来自标头值的所有单独地址的 *note Address: 29a9. 对象的元
          组。 如果标头值包含任何分组，则来自分组的单个地址将包含在该分
          组出现在值中的点上列出（也就是说，地址列表会被“展平”为一维列表
          ）。

     标头的 ‘decoded’ 值将为所有已编码字解码为 unicode 的结果。 *note
     idna: 75. 编码的域名也将被解码为 unicode。 ‘decoded’ 值是通过对
     ‘groups’ 属性的元素的 *note str: 205. 值使用 ‘', '’ 进行 *note
     join: 1766. 来设置的。

     可以使用 *note Address: 29a9. 与 *note Group: 29a6. 对象的任意组合
     的列表来设置一个地址标头的值。 ‘display_name’ 为 ‘None’ 的 ‘Group’
     对象将被解读为单独地址，这允许一个地址列表可以附带通过使用从源标头
     的 ‘groups’ 属性获取的列表而保留原分组。

 -- 類別: email.headerregistry.SingleAddressHeader

     *note AddressHeader: 29a4. 的子类，添加了一个额外的属性:

      -- 屬性: address

          由标头值编码的单个地址。 如果标头值实际上包含一个以上的地址（
          这在默认 *note policy: 73. 下将违反 RFC），则访问此属性将导致
          *note ValueError: 16d.。

上述类中许多还具有一个 ‘Unique’ 变体 (例如 ‘UniqueUnstructuredHeader’)。
其唯一差别是在 ‘Unique’ 变体中 *note max_count: 2984. 被设为 1。

 -- 類別: email.headerregistry.MIMEVersionHeader

     实际上 ‘MIME-Version’ 标头只有一个有效的值，即 ‘1.0’。 为了将来的扩
     展，这个标头类还支持其他的有效版本号。 如果一个版本号是 RFC
     2045(12) 的有效值，则标头对象的以下属性将具有不为 ‘None’ 的值:

      -- 屬性: version

          字符串形式的版本号。 任何空格和/或注释都会被移除。

      -- 屬性: major

          整数形式的主版本号

      -- 屬性: minor

          整数形式的次版本号

 -- 類別: email.headerregistry.ParameterizedMIMEHeader

     MIME 标头都以前缀 ’Content-’ 打头。 每个特定标头都具有特定的值，其
     描述在该标头的类之中。 有些也可以接受一个具有通用格式的补充形参形表
     。 这个类被用作所有接受形参的 MIME 标头的基类。

      -- 屬性: params

          一个将形参名映射到形参值的字典。

 -- 類別: email.headerregistry.ContentTypeHeader

     处理 ‘Content-Type’ 标头的 *note ParameterizedMIMEHeader: 29b0. 类
     。

      -- 屬性: content_type

          ‘maintype/subtype’ 形式的内容类型字符串。

      -- 屬性: maintype

      -- 屬性: subtype

 -- 類別: email.headerregistry.ContentDispositionHeader

     处理 ‘Content-Disposition’ 标头的 *note ParameterizedMIMEHeader:
     29b0. 类。

      -- 屬性: content_disposition

          ‘inline’ 和 ‘attachment’ 是仅有的常用有效值。

 -- 類別: email.headerregistry.ContentTransferEncoding

     处理 ‘Content-Transfer-Encoding’ 标头。

      -- 屬性: cte

          可用的有效值为 ‘7bit’, ‘8bit’, ‘base64’ 和 ‘quoted-printable’。
          更多信息请参阅 RFC 2045(13)。

 -- 類別: email.headerregistry.HeaderRegistry (base_class=BaseHeader,
          default_class=UnstructuredHeader, use_default_map=True)

     这是由 *note EmailPolicy: ad7. 在默认情况下使用的工厂函数。
     ‘HeaderRegistry’ 会使用 `base_class' 和从它所保存的注册表中获取的专
     用类来构建用于动态地创建标头实例的类。 当给定的标头名称未在注册表中
     出现时，则会使用由 `default_class' 所指定的类作为专用类。 当
     `use_default_map' 为 ‘True’ (默认值) 时，则会在初始化期间把将标头名
     称与类的标准映射拷贝到注册表中。 `base_class' 始终会是所生成类的
     ‘__bases__’ 列表中的最后一个类。

     默认的映射有:


          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

     ‘HeaderRegistry’ 具有下列方法:

      -- 成員函式: map_to_type (self, name, cls)

          `name' 是要映射的标头名称。 它将在注册表中被转换为小写形式。
          `cls' 是要与 `base_class' 一起被用来创建用于实例化与 `name' 相
          匹配的标头的类的专用类。

      -- 成員函式: __getitem__ (name)

          构造并返回一个类来处理 `name' 标头的创建。

      -- 成員函式: __call__ (name, value)

          从注册表获得与 `name' 相关联的专用标头 (如果 `name' 未在注册表
          中出现则使用 `default_class') 并将其与 `base_class' 相组合以产
          生类，调用被构造类的构造器，传入相同的参数列表，并最终返回由此
          创建的类实例。

以下的类是用于表示从结构化标头解析的数据的类，并且通常会由应用程序使用以
构造结构化的值并赋给特定的标头。

 -- 類別: email.headerregistry.Address (display_name='', username='',
          domain='', addr_spec=None)

     用于表示电子邮件地址的类。 地址的一般形式为:

          [display_name] <username@domain>

     或是：

          username@domain

     其中每个部分都必须符合在 RFC 5322(14) 中阐述的特定语法规则。

     为了方便起见可以指定 `addr_spec' 来替代 `username' 和 `domain'，在
     此情况下 `username' 和 `domain' 将从 `addr_spec' 中解析。
     `addr_spec' 应当是一个正确地引用了 RFC 的字符串；如果它不是
     ‘Address’ 则将引发错误。 Unicode 字符也允许使用并将在序列化时被正确
     地编码。 但是，根据 RFC，地址的 username 部分 `不允许' 有 unicode。

      -- 屬性: display_name

          地址的显示名称部分（如果有的话）并去除所有引用项。 如果地址没
          有显示名称，则此属性将为空字符串。

      -- 屬性: username

          地址的 ‘username’ 部分，去除所有引用项。

      -- 屬性: domain

          地址的 ‘domain’ 部分。

      -- 屬性: addr_spec

          地址的 ‘username@domain’ 部分，经过正确引用处理以作为纯地址使
          用（上面显示的第二种形式）。 此属性不可变。

      -- 成員函式: __str__ ()

          对象的 ‘str’ 值是根据 RFC 5322(15) 规则进行引用处理的地址，但
          不带任何非 ASCII 字符的 Content Transfer Encoding。

     为了支持 SMTP ( RFC 5321(16))，‘Address’ 会处理一种特殊情况：如果
     ‘username’ 和 ‘domain’ 均为空字符串 (或为 ‘None’)，则 ‘Address’ 的
     字符串值为 ‘<>’。

 -- 類別: email.headerregistry.Group (display_name=None, addresses=None)

     用于表示地址组的类。 地址组的一般形式为:

          display_name: [address-list];

     作为处理由组和单个地址混合构成的列表的便捷方式，‘Group’ 也可以通过
     将 `display_name' 设为 ‘None’ 以用来表示不是某个组的一部分的单独地
     址并提供单独地址的列表作为 `addresses'。

      -- 屬性: display_name

          组的 ‘display_name’。 如果其为 ‘None’ 并且恰好有一个 ‘Address’
          在 ‘addresses’ 中，则 ‘Group’ 表示一个不在某个组中的单独地址。

      -- 屬性: addresses

          一个可能为空的表示组中地址的包含 *note Address: 29a9. 对象的元
          组。

      -- 成員函式: __str__ ()

          ‘Group’ 的 ‘str’ 值会根据 RFC 5322(17) 进行格式化，但不带任何
          非 ASCII 字符的 Content Transfer Encoding。 如果
          ‘display_name’ 为空值且只有一个单独 ‘Address’ 在 ‘addresses’ 列
          表中，则 ‘str’ 值将与该单独 ‘Address’ 的 ‘str’ 相同。

脚注
....

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/Lib/email/headerregistry.py

   (2) (1) 最初在 3.3 中作为 *note 暂定模块: a61. 添加

   (3) https://tools.ietf.org/html/rfc5322.html

   (4) https://tools.ietf.org/html/rfc2047.html

   (5) https://tools.ietf.org/html/rfc5322.html

   (6) https://tools.ietf.org/html/rfc5322.html

   (7) https://tools.ietf.org/html/rfc2047.html

   (8) https://tools.ietf.org/html/rfc5322.html

   (9) https://tools.ietf.org/html/rfc2047.html

   (10) https://tools.ietf.org/html/rfc5322.html

   (11) https://tools.ietf.org/html/rfc5322.html

   (12) https://tools.ietf.org/html/rfc2045.html

   (13) https://tools.ietf.org/html/rfc2045.html

   (14) https://tools.ietf.org/html/rfc5322.html

   (15) https://tools.ietf.org/html/rfc5322.html

   (16) https://tools.ietf.org/html/rfc5321.html

   (17) https://tools.ietf.org/html/rfc5322.html


File: python.info,  Node: email contentmanager 管理 MIME 内容,  Next: email 示例,  Prev: email headerregistry 自定义标头对象,  Up: email --- 电子邮件与 MIME 处理包

5.19.1.10 ‘email.contentmanager’: 管理 MIME 内容
................................................

`源代码:' Lib/email/contentmanager.py(1)

__________________________________________________________________

3.6 版新加入: (2)

 -- 類別: email.contentmanager.ContentManager

     内容管理器的基类。 提供注册 MIME 内容和其他表示形式间转换器的标准注
     册机制，以及 ‘get_content’ 和 ‘set_content’ 发送方法。

      -- 成員函式: get_content (msg, *args, **kw)

          基于 `msg' 的 ‘mimetype’ 查找处理函数（参见下一段），调用该函
          数，传递所有参数，并返回调用的结果。 预期的效果是处理程序将从
          `msg' 中提取有效载荷并返回编码了有关被提取数据信息的对象。

          要找到处理程序，将在注册表中查找以下键，找到第一个键即停止:

                  * 表示完整 MIME 类型的字符串 (‘maintype/subtype’)

                  * 表示 ‘maintype’ 的字符串

                  * 空字符串

          如果这些键都没有产生处理程序，则为完整 MIME 类型引发一个 *note
          KeyError: 3e9.。

      -- 成員函式: set_content (msg, obj, *args, **kw)

          如果 ‘maintype’ 为 ‘multipart’，则引发 *note TypeError: 1fe.；
          否则基于 `obj' 的类型（参见下一段）查找处理函数，在 `msg' 上调
          用 *note clear_content(): 2958.，并调用处理函数，传递所有参数
          。 预期的效果是处理程序将转换 `obj' 并存入 `msg'，并可能对
          `msg' 进行其他更改，例如添加各种 MIME 标头来编码需要用来解释所
          存储数据的信息。

          要找到处理程序，将获取 `obj' 的类型 (‘typ = type(obj)’)，并在
          注册表中查找以下键，找到第一个键即停止:

                  * 类型本身 (‘typ’)

                  * 类型的完整限定名称 (‘typ.__module__ + '.' +
                    typ.__qualname__’)。

                  * 类型的 qualname (‘typ.__qualname__’)

                  * 类型的 name (‘typ.__name__’)。

          如果未匹配到上述的任何一项，则在 *note MRO: 29c7.
          (‘typ.__mro__’) 中为每个类型重复上述的所有检测。 最后，如果没
          有其他键产生处理程序，则为 ‘None’ 键检测处理程序。 如果也没有
          ‘None’ 的处理程序，则为该类型的完整限定名称引发 *note
          KeyError: 3e9.。

          并会添加一个 ‘MIME-Version’ 标头，如果没有的话 (另请参见 *note
          MIMEPart: 930.)。

      -- 成員函式: add_get_handler (key, handler)

          将 `handler' 函数记录为 `key' 的处理程序。 对于可能的 `key' 键
          ，请参阅 *note get_content(): 29c9.。

      -- 成員函式: add_set_handler (typekey, handler)

          将 `handler' 记录为当一个匹配 `typekey' 的类型对象被传递给
          *note set_content(): 29cb. 时所要调用的函数。 对于可能的
          `typekey' 值，请参阅 *note set_content(): 29cb.。

* Menu:

* 内容管理器实例::

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/Lib/email/contentmanager.py

   (2) (1) 最初在 3.4 中作为 *note 暂定模块: a61. 添加


File: python.info,  Node: 内容管理器实例,  Up: email contentmanager 管理 MIME 内容

5.19.1.11 内容管理器实例
........................

目前 email 包只提供了一个实体内容管理器 *note raw_data_manager: 2982.，
不过在未来可能会添加更多。 *note raw_data_manager: 2982. 是由 *note
EmailPolicy: ad7. 及其衍生工具所提供的 *note content_manager: 931.。

 -- Data: email.contentmanager.raw_data_manager

     这个内容管理器仅提供了超出 *note Message: 63b. 本身提供内容的最小接
     口：它只处理文本、原始字节串和 *note Message: 63b. 对象。 不过相比
     基础 API，它具有显著的优势：在文本部分上执行 ‘get_content’ 将返回一
     个 unicode 字符串而无需由应用程序来手动解码，‘set_content’ 为控制添
     加到一个部分的标头和控制内容传输编码格式提供了丰富的选项集合，并且
     它还启用了多种 ‘add_’ 方法，从而简化了多部分消息的创建过程。

      -- 成員函式: email.contentmanager.get_content (msg,
               errors='replace')

          将指定部分的有效载荷作为字符串（对于 ‘text’ 部分）, *note
          EmailMessage: 63c. 对象（对于 ‘message/rfc822’ 部分）或
          ‘bytes’ 对象（对于所有其他非多部分类型）返回。 如果是在
          ‘multipart’ 上调用则会引发 *note KeyError: 3e9.。 如果指定部分
          是一个 ‘text’ 部分并且指明了 `errors'，则会在将载荷解码为
          unicode 时将其用作错误处理程序。 默认的错误处理程序是
          ‘replace’。

      -- 成員函式: email.contentmanager.set_content (msg, <'str'>,
               subtype="plain", charset='utf-8', cte=None,
               disposition=None, filename=None, cid=None, params=None,
               headers=None)

      -- 成員函式: email.contentmanager.set_content (msg, <'bytes'>,
               maintype, subtype, cte="base64", disposition=None,
               filename=None, cid=None, params=None, headers=None)

      -- 成員函式: email.contentmanager.set_content (msg,
               <'EmailMessage'>, cte=None, disposition=None,
               filename=None, cid=None, params=None, headers=None)

          向 `msg' 添加标头和有效载荷:

          添加一个带有 ‘maintype/subtype’ 值的 ‘Content-Type’ 标头。

                  * 对于 ‘str’，将 MIME ‘maintype’ 设为 ‘text’，如果指定
                    了子类型 `subtype' 则设为指定值，否则设为 ‘plain’。

                  * 对于 ‘bytes’，将使用指定的 `maintype' 和 `subtype'，
                    如果未指定则会引发 *note TypeError: 1fe.。

                  * 对于 *note EmailMessage: 63c. 对象，将 maintype 设为
                    ‘message’，并将指定的 subtype 设为 `subtype'，如果未
                    指定则设为 ‘rfc822’。 如果 `subtype' 为 ‘partial’，
                    则引发一个错误（必须使用 ‘bytes’ 对象来构造
                    ‘message/partial’ 部分）。

          如果提供了 `charset' (这只对 ‘str’ 适用)，则使用指定的字符集将
          字符串编码为字节串。 默认值为 ‘utf-8’。 如果指定的 `charset' 是
          某个标准 MIME 字符集名称的已知别名，则会改用该标准字符集。

          如果设置了 `cte'，则使用指定的内容传输编码格式对有效载荷进行编
          码，并将 ‘Content-Transfer-Encoding’ 标头设为该值。 可能的
          `cte' 值有 ‘quoted-printable’, ‘base64’, ‘7bit’, ‘8bit’ 和
          ‘binary’。 如果输入无法以指定的编码格式被编码 (例如，对于包含
          非 ASCII 值的输入指定 `cte' 值为 ‘7bit’)，则会引发 *note
          ValueError: 16d.。

                  * 对于 ‘str’ 对象，如果 `cte' 未设置则会使用启发方式来
                    确定最紧凑的编码格式。

                  * 对于 *note EmailMessage: 63c.，按照 RFC 2046(1)，如
                    果为 `subtype' ‘rfc822’ 请求的 `cte' 为
                    ‘quoted-printable’ 或 ‘base64’ ，而为 ‘7bit’ 以外的
                    任何 `cte' 为 `subtype' ‘external-body’ 则会引发一个
                    错误。 对于 ‘message/rfc822’，如果 `cte' 未指定则会
                    使用 ‘8bit’。 对于所有其他 `subtype' 值，都会使用
                    ‘7bit’。

               備註: `cte' 值为 ‘binary’ 实际上还不能正确工作。 由
               ‘set_content’ 所修改的 ‘EmailMessage’ 对象是正确的，但
               *note BytesGenerator: c1f. 不会正确地将其序列化。

          如果设置了 `disposition'，它会被用作 ‘Content-Disposition’ 标
          头的值。 如果未设置，并且指定了 `filename'，则添加值为
          ‘attachment’ 的标头。 如果未设置 `disposition' 并且也未指定
          `filename'，则不添加标头。 `disposition' 的有效值仅有
          ‘attachment’ 和 ‘inline’。

          如果设置了 `filename'，则将其用作 ‘Content-Disposition’ 标头的
          ‘filename’ 参数的值。

          如果设置了 `cid'，则添加一个 ‘Content-ID’ 标头并将其值设为
          `cid'。

          如果设置了 `params'，则迭代其 ‘items’ 方法并使用输出的 ‘(key,
          value)’ 结果对在 ‘Content-Type’ 标头上设置附加参数。

          如果设置了 `headers' 并且为 ‘headername: headervalue’ 形式的字
          符串的列表或为 ‘header’ 对象的列表（通过一个 ‘name’ 属性与字符
          串相区分），则将标头添加到 `msg'。

脚注
....

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2046.html


File: python.info,  Node: email 示例,  Next: email message Message 使用 compat32 API 来表示电子邮件消息,  Prev: email contentmanager 管理 MIME 内容,  Up: email --- 电子邮件与 MIME 处理包

5.19.1.12 ‘email’: 示例
.......................

以下是一些如何使用 *note email: 67. 包来读取、写入和发送简单电子邮件以及
更复杂的MIME邮件的示例。

首先，让我们看看如何创建和发送简单的文本消息（文本内容和地址都可能包含
unicode字符）：

     # 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()

解析 RFC 822(1) 标题可以通过使用 *note parser: 72. 模块中的类来轻松完成
：

     # 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))

以下是如何发送包含可能在目录中的一系列家庭照片的MIME消息示例：

     # 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)

以下是如何将目录的全部内容作为电子邮件消息发送的示例： (2)

     #!/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()

以下是如何将上述MIME消息解压缩到文件目录中的示例：

     #!/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()

以下是如何使用备用纯文本版本创建 HTML 消息的示例。 为了让事情变得更有趣
，我们在 html 部分中包含了一个相关的图像，我们保存了一份我们要发送的内容
到硬盘中，然后发送它。

     #!/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)

如果我们发送最后一个示例中的消息，这是我们可以处理它的一种方法：

     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(''.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.

直到输出提示，上面的输出是：

     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.

脚注
....

旧式 API:

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc822.html

   (2) (1) 感谢 Matthew Dixon Cowles 提供最初的灵感和示例。


File: python.info,  Node: email message Message 使用 compat32 API 来表示电子邮件消息,  Next: email mime 从头创建电子邮件和 MIME 对象,  Prev: email 示例,  Up: email --- 电子邮件与 MIME 处理包

5.19.1.13 ‘email.message.Message’: 使用 ‘compat32’ API 来表示电子邮件消息
.........................................................................

*note Message: 63b. 类与 *note EmailMessage: 63c. 类非常相似，但没有该类
所添加的方法，并且某些方法的默认行为也略有不同。 我们还在这里记录了一些
虽然被 *note EmailMessage: 63c. 类所支持但并不推荐的方法，除非你是在处理
旧有代码。

在其他情况下这两个类的理念和结构都是相同的。

本文档描述了默认 (对于 *note Message: 63b.) 策略 *note Compat32: ad4. 之
下的行为。 如果你要使用其他策略，你应当改用 *note EmailMessage: 63c. 类
。

电子邮件消息由多个 `标头' 和一个 `载荷' 组成。 标头必须为 RFC 5322(1) 风
格的名称和值，其中字典名和值由冒号分隔。 冒号不是字段名或字段值的组成部
分。 载荷可以是简单的文本消息，或是二进制对象，或是多个子消息的结构化序
列，每个子消息都有自己的标头集合和自己的载荷。 后一种类型的载荷是由具有
‘multipart/*’ 或 ‘message/rfc822’ 等 MIME 类型的消息来指明的。

*note Message: 63b. 对象所提供了概念化模型是由标头组成的有序字典，加上用
于访问标头中的特殊信息以及访问载荷的额外方法，以便能生成消息的序列化版本
，并递归地遍历对象树。 请注意重复的标头是受支持的，但必须使用特殊的方法
来访问它们。

*note Message: 63b. 伪字典以标头名作为索引，标头名必须为 ASCII 值。 字典
的值为应当只包含 ASCII 字符的字符串；对于非 ASCII 输入有一些特殊处理，但
这并不总能产生正确的结果。 标头以保留原大小写的形式存储和返回，但字段名
称匹配对大小写不敏感。 还可能会有一个单独的封包标头，也称 `Unix-From' 标
头或 ‘From_’ 标头。 `载荷' 对于简单消息对象的情况是一个字符串或字节串，
对于 MIME 容器文档的情况 (例如 ‘multipart/*’ 和 ‘message/rfc822’) 则是一
个 *note Message: 63b. 对象。

以下是 *note Message: 63b. 类的方法:

 -- 類別: email.message.Message (policy=compat32)

     如果指定了 `policy' (它必须为 *note policy: 73. 类的实例) 则使用它
     所设置的规则来更新和序列化消息的表示形式。 如果未设置 `policy'，则
     使用 *note compat32: ad4. 策略，该策略会保持对 Python 3.2 版 email
     包的向下兼容性。 更多信息请参阅 *note policy: 73. 文档。

     3.3 版更變: 增加了 `policy' 关键字参数。

      -- 成員函式: as_string (unixfrom=False, maxheaderlen=0,
               policy=None)

          以展平的字符串形式返回整个消息对象。 或可选的 `unixfrom' 为真
          值，返回的字符串会包括封包标头。 `unixfrom' 的默认值是
          ‘False’。 出于保持向下兼容性的原因，`maxheaderlen' 的默认值是
          ‘0’，因此如果你想要不同的值你必须显式地重载它（在策略中为
          `max_line_length' 指定的值将被此方法忽略）。 `policy' 参数可被
          用于覆盖从消息实例获取的默认策略。 这可以用来对该方法所输出的
          格式进行一些控制，因为指定的 `policy' 将被传递给 ‘Generator’。

          如果需要填充默认值以完成对字符串的转换则展平消息可能触发对
          *note Message: 63b. 的修改（例如，MIME 边界可能会被生成或被修
          改）。

          请注意此方法是出于便捷原因提供的，可能无法总是以你想要的方式格
          式化消息。 例如，在默认情况下它不会按 unix mbox 格式的要求对以
          ‘From’ 打头的行执行调整。 为了获得更高灵活性，请实例化一个
          *note Generator: c1e. 实例并直接使用其 *note flatten(): 2970.
          方法。 例如:

               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()

          如果消息对象包含未按照 RFC 标准进行编码的二进制数据，则这些不
          合规数据将被 unicode "unknown character" 码位值所替代。 （另请
          参阅 *note as_bytes(): 92d. 和 *note BytesGenerator: c1f.。）

          3.4 版更變: 增加了 `policy' 关键字参数。

      -- 成員函式: __str__ ()

          与 *note as_string(): 92c. 等价。 这将让 ‘str(msg)’ 产生一个包
          含已格式化消息的字符号。

      -- 成員函式: as_bytes (unixfrom=False, policy=None)

          以字节串对象的形式返回整个扁平化后的消息。 当可选的 `unixfrom'
          为真值时，返回的字符串会包括封包标头。 `unixfrom' 的默认值为
          ‘False’。 `policy' 参数可被用于重载从消息实例获取的默认策略。
          这可被用来控制该方法所产生的部分格式化效果，因为指定的
          `policy' 将被传递给 ‘BytesGenerator’。

          如果需要填充默认值以完成对字符串的转换则展平消息可能触发对
          *note Message: 63b. 的修改（例如，MIME 边界可能会被生成或被修
          改）。

          请注意此方法是出于便捷原因提供的，可能无法总是以你想要的方式格
          式化消息。 例如，在默认情况下它不会按 unix mbox 格式的要求对以
          ‘From’ 打头的行执行调整。 为了获得更高灵活性，请实例化一个
          *note BytesGenerator: c1f. 实例并直接使用其 *note flatten():
          296c. 方法。 例如:

               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()

          3.4 版新加入.

      -- 成員函式: __bytes__ ()

          与 *note as_bytes(): 92d. 等价。 这将让 ‘bytes(msg)’ 产生一个
          包含已格式化消息的字节串对象。

          3.4 版新加入.

      -- 成員函式: is_multipart ()

          如果该消息的载荷是一个子 *note Message: 63b. 对象列表则返回
          ‘True’，否则返回 ‘False’。 当 *note is_multipart(): 2947. 返回
          ‘False’ 时，载荷应当是一个字符串对象（有可能是一个 CTE 编码的
          二进制载荷）。 （请注意 *note is_multipart(): 2947. 返回
          ‘True’ 并不意味着 "msg.get_content_maintype() == ’multipart’"
          将返回 ‘True’。 例如，‘is_multipart’ 在 *note Message: 63b. 类
          型为 ‘message/rfc822’ 时也将返回 ‘True’。）

      -- 成員函式: set_unixfrom (unixfrom)

          将消息的封包标头设为 `unixfrom'，这应当是一个字符串。

      -- 成員函式: get_unixfrom ()

          返回消息的信封头。如果信封头从未被设置过，默认返回 ‘None’ 。

      -- 成員函式: attach (payload)

          将给定的 `payload' 添加到当前载荷中，当前载荷在该调用之前必须
          为 ‘None’ 或是一个 *note Message: 63b. 对象列表。 在调用之后，
          此载荷将总是一个 *note Message: 63b. 对象列表。 如果你想将此载
          荷设为一个标量对象（如字符串），请改用 *note set_payload():
          29d4.。

          这是一个过时的方法。 在 ‘EmailMessage’ 类上它的功能已被 *note
          set_content(): f81. 及相应的 ‘make’ 和 ‘add’ 方法所替代。

      -- 成員函式: get_payload (i=None, decode=False)

          返回当前的载荷，它在 *note is_multipart(): 2947. 为 ‘True’ 时
          将是一个 *note Message: 63b. 对象列表，在 *note
          is_multipart(): 2947. 为 ‘False’ 时则是一个字符串。 如果该载荷
          是一个列表且你修改了这个列表对象，那么你就是原地修改了消息的载
          荷。

          传入可选参数 `i' 时，如果 *note is_multipart(): 2947. 为
          ‘True’，*note get_payload(): c1d. 将返回载荷从零开始计数的第
          `i' 个元素。 如果 `i' 小于 0 或大于等于载荷中的条目数则将引发
          *note IndexError: f36.。 如果载荷是一个字符串 (即 *note
          is_multipart(): 2947. 为 ‘False’) 且给出了 `i'，则会引发 *note
          TypeError: 1fe.。

          可选的 `decode' 是一个指明载荷是否应根据
          ‘Content-Transfer-Encoding’ 标头被解码的旗标。 当其值为 ‘True’
          且消息没有多个部分时，如果此标头值为 ‘quoted-printable’ 或
          ‘base64’ 则载荷将被解码。 如果使用了其他编码格式，或者找不到
          ‘Content-Transfer-Encoding’ 标头时，载荷将被原样返回（不编码）
          。 在所有情况下返回值都是二进制数据。 如果消息有多个部分且
          `decode' 旗标为 ‘True’，则将返回 ‘None’。 如果载荷为 base64 但
          内容不完全正确（如缺少填充符、存在 base64 字母表以外的字符等）
          ，则将在消息的缺陷属性中添加适当的缺陷值 (分别为
          ‘InvalidBase64PaddingDefect’ 或
          ‘InvalidBase64CharactersDefect’)。

          当 `decode' 为 ‘False’ (默认值) 时消息体会作为字符串返回而不解
          码 ‘Content-Transfer-Encoding’。 但是，对于
          ‘Content-Transfer-Encoding’ 为 8bit 的情况，会尝试使用
          ‘Content-Type’ 标头指定的 ‘charset’ 来解码原始字节串，并使用
          ‘replace’ 错误处理程序。 如果未指定 ‘charset’，或者如果指定的
          ‘charset’ 未被 email 包所识别，则会使用默认的 ASCII 字符集来解
          码消息体。

          这是一个过时的方法。 在 ‘EmailMessage’ 类上它的功能已被 *note
          get_content(): 294d. 和 *note iter_parts(): 294c. 方法所替代。

      -- 成員函式: set_payload (payload, charset=None)

          将整个消息对象的载荷设为 `payload'。 客户端要负责确保载荷的不
          变性。 可选的 `charset' 用于设置消息的默认字符集；详情请参阅
          *note set_charset(): 29d5.。

          这是一个过时的方法。 在 ‘EmailMessage’ 类上它的功能已被 *note
          set_content(): f81. 方法所替代。

      -- 成員函式: set_charset (charset)

          将载荷的字符集设为 `charset'，它可以是 *note Charset: 7c7. 实
          例 (参见 *note email.charset: 68.)、字符集名称字符串或 ‘None’。
          如果是字符串，它将被转换为一个 *note Charset: 7c7. 实例。 如果
          `charset' 是 ‘None’，‘charset’ 形参将从 ‘Content-Type’ 标头中
          被删除（消息将不会进行其他修改）。 任何其他值都将导致 *note
          TypeError: 1fe.。

          如果 ‘MIME-Version’ 标头不存在则将被添加。 如果 ‘Content-Type’
          标头不存在，则将添加一个值为 ‘text/plain’ 的该标头。 无论
          ‘Content-Type’ 标头是否已存在，其 ‘charset’ 形参都将被设为
          `charset.output_charset'。 如果 `charset.input_charset' 和
          `charset.output_charset' 不同，则载荷将被重编码为
          `output_charset'。 如果 ‘Content-Transfer-Encoding’ 标头不存在
          ，则载荷将在必要时使用指定的 *note Charset: 7c7. 来转换编码，
          并将添加一个具有相应值的标头。 如果
          ‘Content-Transfer-Encoding’ 标头已存在，则会假定载荷已使用该
          ‘Content-Transfer-Encoding’ 进行正确编码并不会再被修改。

          这是一个过时的方法。 在 ‘EmailMessage’ 类上它的功能已被
          ‘email.emailmessage.EmailMessage.set_content()’ 方法的
          `charset' 形参所替代。

      -- 成員函式: get_charset ()

          返回与消息的载荷相关联的 *note Charset: 7c7. 实例。

          这是一个过时的方法。 在 ‘EmailMessage’ 类上它将总是返回
          ‘None’。

     以下方法实现了用于访问消息的 RFC 2822(2) 标头的类映射接口。 请注意
     这些方法和普通映射（例如字典）接口之间存在一些语义上的不同。 举例来
     说，在一个字典中不能有重复的键，但消息标头则可能有重复。 并且，在字
     典中由 *note keys(): 29d7. 返回的键的顺序是没有保证的，但在 *note
     Message: 63b. 对象中，标头总是会按它们在原始消息中的出现或后继加入
     顺序返回。 任何已删除再重新加入的标头总是会添加到标头列表的末尾。

     这些语义上的差异是有意为之且其目的是为了提供最大的便利性。

     请注意在任何情况下，消息当中的任何封包标头都不会包含在映射接口当中
     。

     在由字节串生成的模型中，任何包含非 ASCII 字节数据（违反 RFC）的标头
     值当通过此接口来获取时，将被表示为使用 ‘unknown-8bit’ 字符集的
     *note Header: f83. 对象。

      -- 成員函式: __len__ ()

          返回标头的总数，包括重复项。

      -- 成員函式: __contains__ (name)

          如果消息对象中有一个名为 `name' 的字段则返回 ‘True’。 匹配操作
          对大小写不敏感并且 `name' 不应包括末尾的冒号。 用于 ‘in’ 运算
          符，例如:

               if 'message-id' in myMessage:
                  print('Message-ID:', myMessage['message-id'])

      -- 成員函式: __getitem__ (name)

          返回指定名称标头字段的值。 `name' 不应包括作为字段分隔符的冒号
          。 如果标头未找到，则返回 ‘None’；*note KeyError: 3e9. 永远不
          会被引发。

          请注意如果指定名称的字段在消息标头中多次出现，具体将返回哪个字
          段值是未定义的。 请使用 *note get_all(): 29db. 方法来获取所有
          指定名称标头的值。

      -- 成員函式: __setitem__ (name, val)

          将具有字段名 `name' 和值 `val' 的标头添加到消息中。 字段会被添
          加到消息的现有字段的末尾。

          请注意，这个方法 `既不会' 覆盖 `也不会' 删除任何字段名重名的已
          有字段。如果你确实想保证新字段是整个信息头当中唯一拥有 `name'
          字段名的字段，你需要先把旧字段删除。例如：

               del msg['subject']
               msg['subject'] = 'Python roolz!'

      -- 成員函式: __delitem__ (name)

          删除信息头当中字段名匹配 `name' 的所有字段。如果匹配指定名称的
          字段没有找到，也不会抛出任何异常。

      -- 成員函式: keys ()

          以列表形式返回消息头中所有的字段名。

      -- 成員函式: values ()

          以列表形式返回消息头中所有的字段值。

      -- 成員函式: items ()

          以二元元组的列表形式返回消息头中所有的字段名和字段值。

      -- 成員函式: get (name, failobj=None)

          返回指定名称标头字段的值。 这与 *note __getitem__(): 29da. 是
          一样的，不同之处在于如果指定名称标头未找到则会返回可选的
          `failobj' (默认为 ‘None’)。

     以下是一些有用的附加方法:

      -- 成員函式: get_all (name, failobj=None)

          返回字段名为 `name' 的所有字段值的列表。如果信息内不存在匹配的
          字段，返回 `failobj' （其默认值为 ‘None’ ）。

      -- 成員函式: add_header (_name, _value, **_params)

          高级头字段设定。这个方法与 *note __setitem__(): 29dc. 类似，不
          过你可以使用关键字参数为字段提供附加参数。 `_name' 是字段名，
          `_value' 是字段 `主' 值。

          对于关键字参数字典 `_params' 中的每一项，其键会被当作形参名，
          并执行下划线和连字符间的转换（因为连字符不是合法的 Python 标识
          符）。 通常，形参将以 ‘key="value"’ 的形式添加，除非值为
          ‘None’，在这种情况下将只添加键。 如果值包含非 ASCII 字符，可将
          其指定为格式为 ‘(CHARSET, LANGUAGE, VALUE)’ 的三元组，其中
          ‘CHARSET’ 为要用来编码值的字符集名称字符串，‘LANGUAGE’ 通常可
          设为 ‘None’ 或空字符串（请参阅 RFC 2231(3) 了解其他可能的取值
          ），而 ‘VALUE’ 为包含非 ASCII 码位的字符串值。 如果不是传入一
          个三元组且值包含非 ASCII 字符，则会自动以 RFC 2231(4) 格式使用
          ‘CHARSET’ 为 ‘utf-8’ 和 ‘LANGUAGE’ 为 ‘None’ 对其进行编码。

          以下是为示例代码:

               msg.add_header('Content-Disposition', 'attachment', filename='bud.gif')

          会添加一个形如下文的头字段：

               Content-Disposition: attachment; filename="bud.gif"

          使用非 ASCII 字符的示例代码:

               msg.add_header('Content-Disposition', 'attachment',
                              filename=('iso-8859-1', '', 'Fußballer.ppt'))

          它的输出结果为

               Content-Disposition: attachment; filename*="iso-8859-1''Fu%DFballer.ppt"

      -- 成員函式: replace_header (_name, _value)

          替换一个标头。 将替换在匹配 `_name' 的消息中找到的第一个标头，
          标头顺序和字段名大小写保持不变。 如果未找到匹配的标头，则会引
          发 *note KeyError: 3e9.。

      -- 成員函式: get_content_type ()

          返回消息的内容类型。 返回的字符串会强制转换为
          ‘maintype/subtype’ 的全小写形式。 如果消息中没有
          ‘Content-Type’ 标头则将返回由 *note get_default_type(): 29e4.
          给出的默认类型。 因为根据 RFC 2045(5)，消息总是要有一个默认类
          型，所以 *note get_content_type(): 29e3. 将总是返回一个值。

          RFC 2045(6) 将消息的默认类型定义为 ‘text/plain’，除非它是出现
          在 ‘multipart/digest’ 容器内，在这种情况下其类型应为
          ‘message/rfc822’。 如果 ‘Content-Type’ 标头指定了无效的类型，
          RFC 2045(7) 规定其默认类型应为 ‘text/plain’。

      -- 成員函式: get_content_maintype ()

          返回信息的主要内容类型。准确来说，此方法返回的是 *note
          get_content_type(): 29e3. 方法所返回的形如 ‘maintype/subtype’
          的字符串当中的 ‘maintype’ 部分。

      -- 成員函式: get_content_subtype ()

          返回信息的子内容类型。准确来说，此方法返回的是 *note
          get_content_type(): 29e3. 方法所返回的形如 ‘maintype/subtype’
          的字符串当中的 ‘subtype’ 部分。

      -- 成員函式: get_default_type ()

          返回默认的内容类型。绝大多数的信息，其默认内容类型都是
          ‘text/plain’ 。作为 ‘multipart/digest’ 容器内子部分的信息除外
          ，它们的默认内容类型是 ‘message/rfc822’ 。

      -- 成員函式: set_default_type (ctype)

          设置默认的内容类型。 `ctype' 应当为 ‘text/plain’ 或者
          ‘message/rfc822’，尽管这并非强制。 默认的内容类型不会存储在
          ‘Content-Type’ 标头中。

      -- 成員函式: get_params (failobj=None, header='content-type',
               unquote=True)

          将消息的 ‘Content-Type’ 形参作为列表返回。 所返回列表的元素为
          以 ‘'='’ 号拆分出的键/值对 2 元组。 ‘'='’ 左侧的为键，右侧的为
          值。 如果形参值中没有 ‘'='’ 号，否则该将值如 *note
          get_param(): 29e9. 描述并且在可选 `unquote' 为 ‘True’ (默认值)
          时会被取消转义。

          可选的 `failobj' 是在没有 ‘Content-Type’ 标头时要返回的对象。
          可选的 `header' 是要替代 ‘Content-Type’ 被搜索的标头。

          这是一个过时的方法。 在 ‘EmailMessage’ 类上它的功能已被标头访
          问方法所返回的单独标头对象的 `params' 特征属性所替代。

      -- 成員函式: get_param (param, failobj=None,
               header='content-type', unquote=True)

          将 ‘Content-Type’ 标头的形参 `param' 作为字符串返回。 如果消息
          没有 ‘Content-Type’ 标头或者没有这样的形参，则返回 `failobj'
          (默认为 ‘None’)。

          如果给出可选的 `header'，它会指定要替代 ‘Content-Type’ 来使用
          的消息标头。

          形参的键总是以大小写不敏感的方式来比较的。 返回值可以是一个字
          符串，或者如果形参以 RFC 2231(8) 编码则是一个 3 元组。 当为 3
          元组时，值中的元素采用 ‘(CHARSET, LANGUAGE, VALUE)’ 的形式。 请
          注意 ‘CHARSET’ 和 ‘LANGUAGE’ 都可以为 ‘None’，在此情况下你应当
          将 ‘VALUE’ 当作以 ‘us-ascii’ 字符集来编码。 你可以总是忽略
          ‘LANGUAGE’。

          如果你的应用不关心形参是否以 RFC 2231(9) 来编码，你可以通过调
          用 *note email.utils.collapse_rfc2231_value(): 29ea. 来展平形
          参值，传入来自 *note get_param(): 29e9. 的返回值。 当值为元组
          时这将返回一个经适当编码的 Unicode 字符串，否则返回未经转换的
          原字符串。 例如:

               rawparam = msg.get_param('foo')
               param = email.utils.collapse_rfc2231_value(rawparam)

          无论在哪种情况下，形参值（或为返回的字符串，或为 3 元组形式的
          ‘VALUE’ 条目）总是未经转换的，除非 `unquote' 被设为 ‘False’。

          这是一个过时的方法。 在 ‘EmailMessage’ 类上它的功能已被标头访
          问方法所返回的单独标头对象的 `params' 特征属性所替代。

      -- 成員函式: set_param (param, value, header='Content-Type',
               requote=True, charset=None, language='', replace=False)

          在 ‘Content-Type’ 标头中设置一个形参。 如果该形参已存在于标头
          中，它的值将被替换为 `value'。 如果此消息还未定义
          ‘Content-Type’ 标头，它将被设为 ‘text/plain’ 且新的形参值将按
          RFC 2045(10) 的要求添加。

          可选的 `header' 指定一个 ‘Content-Type’ 的替代标头，并且所有形
          参将根据需要被转换，除非可选的 `requote' 为 ‘False’ (默认为
          ‘True’)。

          如果指定了可选的 `charset'，形参将按照 RFC 2231(11) 来编码。 可
          选的 `language' 指定了 RFC 2231 的语言，默认为空字符串。
          `charset' 和 `language' 都应为字符串。

          如果 `replace' 为 ‘False’ （默认值），该头字段会被移动到所有头
          字段的末尾。如果 `replace' 为 ‘True’ ，字段会被原地更新。

          3.4 版更變: 添加了 ‘replace’ 关键字。

      -- 成員函式: del_param (param, header='content-type',
               requote=True)

          从 ‘Content-Type’ 标头中完全移除给定的形参。 标头将被原地重写
          并不带该形参或它的值。 所有的值将根据需要被转换，除非
          `requote' 为 ‘False’ (默认为 ‘True’)。 可选的 `header' 指定
          ‘Content-Type’ 的一个替代项。

      -- 成員函式: set_type (type, header='Content-Type', requote=True)

          设置 ‘Content-Type’ 标头的主类型和子类型。 `type' 必须为
          ‘maintype/subtype’ 形式的字符串，否则会引发 *note ValueError:
          16d.。

          此方法可替换 ‘Content-Type’ 标头，并保持所有形参不变。 如果
          `requote' 为 ‘False’，这会保持原有标头引用转换不变，否则形参将
          被引用转换（默认行为）。

          可以在 `header' 参数中指定一个替代标头。 当 ‘Content-Type’ 标
          头被设置时也会添加一个 ‘MIME-Version’ 标头。

          这是一个过时的方法。 在 ‘EmailMessage’ 类上它的功能已被
          ‘make_’ 和 ‘add_’ 方法所替代。

      -- 成員函式: get_filename (failobj=None)

          返回信息头当中 ‘Content-Disposition’ 字段当中名为 ‘filename’ 的
          参数值。如果该字段当中没有此参数，该方法会退而寻找
          ‘Content-Type’ 字段当中的 ‘name’ 参数值。如果这个也没有找到，
          或者这些个字段压根就不存在，返回 `failobj' 。返回的字符串永远
          按照 *note email.utils.unquote(): 2940. 方法去除引号。

      -- 成員函式: get_boundary (failobj=None)

          返回信息头当中 ‘Content-Type’ 字段当中名为 ‘boundary’ 的参数值
          。如果字段当中没有此参数，或者这些个字段压根就不存在，返回
          `failobj' 。返回的字符串永远按照 *note email.utils.unquote():
          2940. 方法去除引号。

      -- 成員函式: set_boundary (boundary)

          将 ‘Content-Type’ 头字段的 ‘boundary’ 参数设置为 `boundary' 。
          *note set_boundary(): 29ef. 方法永远都会在必要的时候为
          `boundary' 添加引号。如果信息对象中没有 ‘Content-Type’ 头字段
          ，抛出 *note HeaderParseError: 2943. 异常。

          请注意使用这个方法与删除旧的 ‘Content-Type’ 标头并通过 *note
          add_header(): 29e1. 添加一个带有新边界的新标头有细微的差异，因
          为 *note set_boundary(): 29ef. 会保留 ‘Content-Type’ 标头在原
          标头列表中的顺序。 但是，它 `不会' 保留原 ‘Content-Type’ 标头
          中可能存在的任何连续的行。

      -- 成員函式: get_content_charset (failobj=None)

          返回 ‘Content-Type’ 头字段中的 ‘charset’ 参数，强制小写。如果
          字段当中没有此参数，或者这个字段压根不存在，返回 `failobj' 。

          请注意此方法不同于 *note get_charset(): 29d6.，后者会返回
          *note Charset: 7c7. 实例作为消息体的默认编码格式。

      -- 成員函式: get_charsets (failobj=None)

          返回一个包含了信息内所有字符集名字的列表。如果信息是
          ‘multipart’ 类型的，那么列表当中的每一项都对应其负载的子部分的
          字符集名字。否则，该列表是一个长度为1的列表。

          列表中的每一项都是字符串，它们是其所表示的子部分的
          ‘Content-Type’ 标头中 ‘charset’ 形参的值。 但是，如果该子部分
          没有 ‘Content-Type’ 标头，或没有 ‘charset’ 形参，或者主 MIME 类
          型不是 ‘text’，则所返回列表中的对应项将为 `failobj'。

      -- 成員函式: get_content_disposition ()

          如果信息的 ‘Content-Disposition’ 头字段存在，返回其字段值；否
          则返回 ‘None’ 。返回的值均为小写，不包含参数。如果信息遵循 RFC
          2183(12) 标准，则返回值只可能在 `inline' 、 `attachment' 和
          ‘None’ 之间选择。

          3.5 版新加入.

      -- 成員函式: walk ()

          *note walk(): 29f2. 方法是一个多功能生成器。它可以被用来以深度
          优先顺序遍历信息对象树的所有部分和子部分。一般而言， *note
          walk(): 29f2. 会被用作 ‘for’ 循环的迭代器，每一次迭代都返回其
          下一个子部分。

          以下例子会打印出一封具有多部分结构之信息的每个部分的 MIME 类型
          。

               >>> 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

          ‘walk’ 会遍历所有 *note is_multipart(): 2947. 方法返回 ‘True’
          的部分之子部分，哪怕 ‘msg.get_content_maintype() ==
          'multipart'’ 返回的是 ‘False’ 。使用 ‘_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

          在这里， ‘message’ 的部分并非 ‘multiparts’ ，但是它们真的包含
          子部分！ ‘is_multipart()’ 返回 ‘True’ ， ‘walk’ 也深入进这些子
          部分中。

     *note Message: 63b. 对象也可以包含两个可选的实例属性，它们可被用于
     生成纯文本的 MIME 消息。

      -- 屬性: preamble

          MIME 文档格式在标头之后的空白行以及第一个多部分的分界字符串之
          间允许添加一些文本， 通常，此文本在支持 MIME 的邮件阅读器中永
          远不可见，因为它处在标准 MIME 防护范围之外。 但是，当查看消息
          的原始文本，或当在不支持 MIME 的阅读器中查看消息时，此文本会变
          得可见。

          `preamble' 属性包含 MIME 文档开头部分的这些处于保护范围之外的
          文本。 当 *note Parser: beb. 在标头之后及第一个分界字符串之前
          发现一些文本时，它会将这些文本赋值给消息的 `preamble' 属性。 当
          *note Generator: c1e. 写出 MIME 消息的纯文本表示形式时，如果它
          发现消息具有 `preamble' 属性，它将在标头及第一个分界之间区域写
          出这些文本。 请参阅 *note email.parser: 72. 和 *note
          email.generator: 6c. 了解更多细节。

          请注意如果消息对象没有前导文本，则 `preamble' 属性将为 ‘None’。

      -- 屬性: epilogue

          `epilogue' 属性的作用方式与 `preamble' 属性相同，区别在于它包
          含出现于最后一个分界与消息结尾之间的文本。

          你不需要将 epilogue 设为空字符串以便让 *note Generator: c1e. 在
          文件末尾打印一个换行符。

      -- 屬性: defects

          `defects' 属性包含在解析消息时发现的所有问题的列表。 请参阅
          *note email.errors: 6b. 了解可能的解析缺陷的详细描述。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc5322.html

   (2) https://tools.ietf.org/html/rfc2822.html

   (3) https://tools.ietf.org/html/rfc2231.html

   (4) https://tools.ietf.org/html/rfc2231.html

   (5) https://tools.ietf.org/html/rfc2045.html

   (6) https://tools.ietf.org/html/rfc2045.html

   (7) https://tools.ietf.org/html/rfc2045.html

   (8) https://tools.ietf.org/html/rfc2231.html

   (9) https://tools.ietf.org/html/rfc2231.html

   (10) https://tools.ietf.org/html/rfc2045.html

   (11) https://tools.ietf.org/html/rfc2231.html

   (12) https://tools.ietf.org/html/rfc2183.html


File: python.info,  Node: email mime 从头创建电子邮件和 MIME 对象,  Next: email header 国际化标头,  Prev: email message Message 使用 compat32 API 来表示电子邮件消息,  Up: email --- 电子邮件与 MIME 处理包

5.19.1.14 ‘email.mime’: 从头创建电子邮件和 MIME 对象
....................................................

`源代码:' Lib/email/mime/(1)

__________________________________________________________________

此模块是旧版 (‘Compat32’) 电子邮件 API 的组成部分。 它的功能在新版 API 中
被 *note contentmanager: 69. 部分替代，但在某些应用中这些类仍可能有用，
即使是在非旧版代码中。

通常，你是通过传递一个文件或一些文本到解析器来获得消息对象结构体的，解析
器会解析文本并返回根消息对象。 不过你也可以从头开始构建一个完整的消息结
构体，甚至是手动构建单独的 *note Message: 63b. 对象。 实际上，你也可以接
受一个现有的结构体并添加新的 *note Message: 63b. 对象并移动它们。 这为切
片和分割 MIME 消息提供了非常方便的接口。

你可以通过创建 *note Message: 63b. 实例并手动添加附件和所有适当的标头来
创建一个新的对象结构体。 不过对于 MIME 消息来说，*note email: 67. 包提供
了一些便捷子类来让事情变得更容易。

这些类列示如下:

 -- 類別: email.mime.base.MIMEBase (_maintype, _subtype, *,
          policy=compat32, **_params)

     模块: ‘email.mime.base’

     这是 *note Message: 63b. 的所有 MIME 专属子类。 通常你不会创建专门
     的 *note MIMEBase: 29f8. 实例，尽管你可以这样做。 *note MIMEBase:
     29f8. 主要被提供用来作为更具体的 MIME 感知子类的便捷基类。

     `_maintype' 是 ‘Content-Type’ 的主类型 (例如 ‘text’ 或 ‘image’)，而
     `_subtype' 是 ‘Content-Type’ 的次类型 (例如 ‘plain’ 或 ‘gif’)。
     `_params' 是一个形参键/值字典并会被直接传递给 *note
     Message.add_header: 29e1.。

     如果指定了 `policy' (默认为 *note compat32: ad4. 策略)，它将被传递
     给 *note Message: 63b.。

     *note MIMEBase: 29f8. 类总是会添加一个 ‘Content-Type’ 标头 (基于
     `_maintype', `_subtype' 和 `_params')，以及一个 ‘MIME-Version’ 标头
     (总是设为 ‘1.0’)。

     3.6 版更變: 添加了 `policy' 仅限关键字形参。

 -- 類別: email.mime.nonmultipart.MIMENonMultipart

     模块: ‘email.mime.nonmultipart’

     *note MIMEBase: 29f8. 的子类，这是用于非 ‘multipart’ MIME 消息的中
     间基类。 这个类的主要目标是避免使用 *note attach(): 2954. 方法，该
     方法仅对 ‘multipart’ 消息有意义。 如果 *note attach(): 2954. 被调用
     ，则会引发 *note MultipartConversionError: 2999. 异常。

 -- 類別: email.mime.multipart.MIMEMultipart (_subtype='mixed',
          boundary=None, _subparts=None, *, policy=compat32, **_params)

     模块: ‘email.mime.multipart’

     *note MIMEBase: 29f8. 的子类，这是用于 ‘multipart’ MIME 消息的中间
     基类。 可选的 `_subtype' 默认为 ‘mixed’，但可被用来指定消息的子类型
     。 将会在消息对象中添加一个:mimetype:‘multipart/_subtype’ 的
     ‘Content-Type’ 标头。 并还将添加一个 ‘MIME-Version’ 标头。

     可选的 `boundary' 是多部分边界字符串。 当为 ‘None’ (默认值) 时，则
     会在必要时（例如当消息被序列化时）计算边界。

     `_subparts' 是载荷初始子部分的序列。 此序列必须可以被转换为列表。 你
     总是可以使用 *note Message.attach: 2954. 方法将新的子部分附加到消息
     中。

     可选的 `policy' 参数默认为 *note compat32: ad4.。

     用于 ‘Content-Type’ 标头的附加形参会从关键字参数中获取，或者传入到
     `_params' 参数，该参数是一个关键字的字典。

     3.6 版更變: 添加了 `policy' 仅限关键字形参。

 -- 類別: email.mime.application.MIMEApplication (_data,
          _subtype='octet-stream',
          _encoder=email.encoders.encode_base64, *, policy=compat32,
          **_params)

     模块: ‘email.mime.application’

     *note MIMENonMultipart: f59. 的子类，*note MIMEApplication: 29fa. 类
     被用来表示主类型为 ‘application’ 的 MIME 消息。 `_data' 是包含原始
     字节数据的字符串。 可选的 `_subtype' 指定 MIME 子类型并默认为
     ‘octet-stream’。

     可选的 `_encoder' 是一个可调用对象（即函数），它将执行实际的数据编
     码以便传输。 这个可调用对象接受一个参数，该参数是 *note
     MIMEApplication: 29fa. 的实例。 它应当使用 *note get_payload():
     c1d. 和 *note set_payload(): 29d4. 来将载荷改为已编码形式。 它还应
     根据需要将任何 ‘Content-Transfer-Encoding’ 或其他标头添加到消息对象
     中。 默认编码格式为 base64。 请参阅 *note email.encoders: 6a. 模块
     来查看内置编码器列表。

     可选的 `policy' 参数默认为 *note compat32: ad4.。

     `_params' 会被直接传递给基类的构造器。

     3.6 版更變: 添加了 `policy' 仅限关键字形参。

 -- 類別: email.mime.audio.MIMEAudio (_audiodata, _subtype=None,
          _encoder=email.encoders.encode_base64, *, policy=compat32,
          **_params)

     模块: ‘email.mime.audio’

     *note MIMENonMultipart: f59. 的子类，*note MIMEAudio: 29fb. 类被用
     来创建主类型为 ‘audio’ 的 MIME 消息。 `_audiodata' 是包含原始音频数
     据的字符串。 如果此数据可由标准 Python 模块 *note sndhdr: ee. 来解
     码，则其子类型将被自动包括在 ‘Content-Type’ 标头中。 在其他情况下你
     可以通过 `_subtype' 参数显式地指定音频子类型 。 如果无法猜测出主类
     型并且未给出 `_subtype'，则会引发 *note TypeError: 1fe.。

     可选的 `_encoder' 是一个可调用对象（即函数），它将执行实际的音频数
     据编码以便传输。 这个可调用对象接受一个参数，该参数是 *note
     MIMEAudio: 29fb. 的实例。 它应当使用 *note get_payload(): c1d. 和
     *note set_payload(): 29d4. 来将载荷改为已编码形式。 它还应根据需要
     将任何 ‘Content-Transfer-Encoding’ 或其他标头添加到消息对象中。 默
     认编码格式为 base64。 请参阅 *note email.encoders: 6a. 模块来查看内
     置编码器列表。

     可选的 `policy' 参数默认为 *note compat32: ad4.。

     `_params' 会被直接传递给基类的构造器。

     3.6 版更變: 添加了 `policy' 仅限关键字形参。

 -- 類別: email.mime.image.MIMEImage (_imagedata, _subtype=None,
          _encoder=email.encoders.encode_base64, *, policy=compat32,
          **_params)

     模块: ‘email.mime.image’

     *note MIMENonMultipart: f59. 的子类，*note MIMEImage: 299a. 类被用
     来创建主类型为 ‘image’ 的 MIME 消息对象。 `_imagedata' 是包含原始图
     像数据的字符串。 如果此数据可由标准 Python 模块 *note imghdr: 98. 来
     解码，则其子类型将被自动包括在 ‘Content-Type’ 标头中。 在其他情况下
     你可以通过 `_subtype' 参数显式地指定图像子类型。 如果无法猜测出主类
     型并且未给出 `_subtype'，则会引发 *note TypeError: 1fe.。

     可选的 `_encoder' 是一个可调用对象（即函数），它将执行实际的图像数
     据编码以便传输。 这个可调用对象接受一个参数，该参数是 *note
     MIMEImage: 299a. 的实例。 它应当使用 *note get_payload(): c1d. 和
     *note set_payload(): 29d4. 来将载荷改为已编码形式。 它还应根据需要
     将任何 ‘Content-Transfer-Encoding’ 或其他标头添加到消息对象中。 默
     认编码格式为 base64。 请参阅 *note email.encoders: 6a. 模块来查看内
     置编码器列表。

     可选的 `policy' 参数默认为 *note compat32: ad4.。

     `_params' 会被直接传递给 *note MIMEBase: 29f8. 构造器。

     3.6 版更變: 添加了 `policy' 仅限关键字形参。

 -- 類別: email.mime.message.MIMEMessage (_msg, _subtype='rfc822', *,
          policy=compat32)

     模块: ‘email.mime.message’

     *note MIMENonMultipart: f59. 的子类，*note MIMEMessage: 29fc. 类被
     用来创建主类型为 ‘message’ 的 MIME 对象。 `_msg' 将被用作载荷，并且
     必须为 *note Message: 63b. 类（或其子类）的实例，否则会引发 *note
     TypeError: 1fe.。

     可选的 `_subtype' 设置消息的子类型；它的默认值为 ‘rfc822’。

     可选的 `policy' 参数默认为 *note compat32: ad4.。

     3.6 版更變: 添加了 `policy' 仅限关键字形参。

 -- 類別: email.mime.text.MIMEText (_text, _subtype='plain',
          _charset=None, *, policy=compat32)

     模块: ‘email.mime.text’

     *note MIMENonMultipart: f59. 的子类，*note MIMEText: 7c6. 类被用来
     创建主类型为 ‘text’ 的 MIME 对象。 `_text' 是用作载荷的字符串。
     `_subtype' 指定子类型并且默认为 ‘plain’。 `_charset' 是文本的字符集
     并会作为参数传递给 *note MIMENonMultipart: f59. 构造器；如果该字符
     串仅包含 ‘ascii’ 码位则其默认值为 ‘us-ascii’，否则为 ‘utf-8’。
     `_charset' 形参接受一个字符串或是一个 *note Charset: 7c7. 实例。

     除非 `_charset' 参数被显式地设为 ‘None’，否则所创建的 MIMEText 对象
     将同时具有附带 ‘charset’ 形参的 ‘Content-Type’ 标头，以及
     ‘Content-Transfer-Encoding’ 标头。 这意味着后续的 ‘set_payload’ 调
     用将不再产生已编码的载荷，即使它在 ‘set_payload’ 命令中被传入。 你
     可以通过删除 ‘Content-Transfer-Encoding’ 标头来“重置”此行为，在此之
     后的 ‘set_payload’ 调用将自动编码新的载荷（并添加新的
     ‘Content-Transfer-Encoding’ 标头）。

     可选的 `policy' 参数默认为 *note compat32: ad4.。

     3.5 版更變: `_charset' 也可接受 *note Charset: 7c7. 实例。

     3.6 版更變: 添加了 `policy' 仅限关键字形参。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/email/mime/


File: python.info,  Node: email header 国际化标头,  Next: email charset 表示字符集,  Prev: email mime 从头创建电子邮件和 MIME 对象,  Up: email --- 电子邮件与 MIME 处理包

5.19.1.15 ‘email.header’: 国际化标头
....................................

`源代码:' Lib/email/header.py(1)

__________________________________________________________________

此模块是旧式 (‘Compat32’) email API 的一部分。 在当前的 API 中标头的编码
和解码是由 *note EmailMessage: 63c. 类的字典型 API 来透明地处理的。 除了
在旧有代码中使用，此模块在需要完全控制当编码标头时所使用的字符集时也很有
用处。

本节中的其余文本是此模块的原始文档。

RFC 2822(2) 是描述电子邮件消息格式的基础标准。 它派生自更早的 RFC 822(3)
标准，该标准在大多数电子邮件仅由 ASCII 字符组成时已被广泛使用。 RFC
2822(4) 所描述的规范假定电子邮件都只包含 7 位 ASCII 字符。

当然，随着电子邮件在全球部署，它已经变得国际化了，例如电子邮件消息中现在
可以使用特定语言的专属字符集。 这个基础标准仍然要求电子邮件消息只使用 7
位 ASCII 字符来进行传输，为此编写了大量 RFC 来描述如何将包含非 ASCII 字
符的电子邮件编码为符合 RFC 2822(5) 的格式。 这些 RFC 包括 RFC 2045(6),
RFC 2046(7), RFC 2047(8) 和 RFC 2231(9)。 *note email: 67. 包在其 *note
email.header: 6d. 和 *note email.charset: 68. 模块中支持了这些标准。

如果你想在你的电子邮件标头中包括非 ASCII 字符，比如说是在 ‘Subject’ 或
‘To’ 字段中，你应当使用 *note Header: f83. 类并将 *note Message: 63b. 对
象中的字段赋值为 *note Header: f83. 的实例而不是使用字符串作为字段值。 请
从 *note email.header: 6d. 模块导入 *note Header: f83. 类。 例如:

     >>> 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'

是否注意到这里我们是如何希望 ‘Subject’ 字段包含非 ASCII 字符的？ 我们通
过创建一个 *note Header: f83. 实例并传入字节串编码所用的字符集来做到这一
点。 当后续的 *note Message: 63b. 实例被展平时，‘Subject’ 字段会正确地按
RFC 2047(10) 来编码。 可感知 MIME 的电子邮件阅读器将会使用嵌入的
ISO-8859-1 字符来显示此标头。

以下是 *note Header: f83. 类描述:

 -- 類別: email.header.Header (s=None, charset=None, maxlinelen=None,
          header_name=None, continuation_ws=' ', errors='strict')

     创建符合 MIME 要求的标头，其中可包含不同字符集的字符串。

     可选的 `s' 是初始标头值。 如果为 ‘None’ (默认值)，则表示初始标头值
     未设置。 你可以在稍后使用 *note append(): 29ff. 方法调用向标头添加
     新值。 `s' 可以是 *note bytes: 172. 或 *note str: 205. 的实例，注意
     参阅 *note append(): 29ff. 文档了解相关语义。

     可选的 `charset' 用于两种目的：它的含义与 *note append(): 29ff. 方
     法的 `charset' 参数相同。 它还会为所有省略了 `charset' 参数的后续
     *note append(): 29ff. 调用设置默认字符集。 如果 `charset' 在构造器
     中未提供（默认设置），则会将 ‘us-ascii’ 字符集用作 `s' 的初始字符集
     以及后续 *note append(): 29ff. 调用的默认字符集。

     通过 `maxlinelen' 可以显式指定最大行长度。 要将第一行拆分为更短的值
     (以适应未被包括在to account for the field header which isn’t
     included in `s' 中的字段标头，例如 ‘Subject’)，则将字段名称作为
     `header_name' 传入。 `maxlinelen' 默认值为 76，而 `header_name' 默
     认值为 ‘None’，表示不考虑拆分超长标头的第一行。

     可选的 `continuation_ws' 必须为符合 RFC 2822(11) 的折叠用空白符，通
     常是空格符或硬制表符。 这个字符将被加缀至连续行的开头。
     `continuation_ws' 默认为一个空格符。

     可选的 `errors' 会被直接传递给 *note append(): 29ff. 方法。

      -- 成員函式: append (s, charset=None, errors='strict')

          将字符串 `s' 添加到 MIME 标头。

          如果给出可选的 `charset'，它应当是一个 *note Charset: 7c7. 实
          例 (参见 *note email.charset: 68.) 或字符集名称，该参数将被转
          换为一个 *note Charset: 7c7. 实例。 如果为 ‘None’ (默认值) 则
          表示会使用构造器中给出的 `charset'。

          `s' 可以是 *note bytes: 172. 或 *note str: 205. 的实例。 如果
          它是 *note bytes: 172. 的实例，则 `charset' 为该字节串的编码格
          式，如果字节串无法用该字符集来解码则将引发 *note UnicodeError:
          d03.。

          如果 `s' 是 *note str: 205. 的实例，则 `charset' 是用来指定字
          符串中字符字符集的提示。

          在这两种情况下，当使用 RFC 2047(12) 规则产生符合 RFC 2822(13)
          的标头时，将使用指定字符集的输出编解码器来编码字符串。 如果字
          符串无法使用该输出编解码器来编码，则将引发 UnicodeError。

          可选的 `errors' 会在 `s' 为字节串时被作为 errors 参数传递给
          decode 调用。

      -- 成員函式: encode (splitchars=';, \t', maxlinelen=None,
               linesep='\n')

          将消息标头编码为符合 RFC 的格式，可能会对过长的行采取折行并将
          非 ASCII 部分以 base64 或 quoted-printable 编码格式进行封装。

          可选的 `splitchars' 是一个字符串，其中包含应在正常的标头折行处
          理期间由拆分算法赋予额外权重的字符。 这是对于 RFC 2822(14) 中
          ’更高层级语法拆分’ 的很粗略的支持：在拆分期间会首选在
          splitchar 之前的拆分点，字符的优先级是基于它们在字符串中的出现
          顺序。 字符串中可包含空格和制表符以指明当其他拆分字符未在被拆
          分行中出现时是否要将某个字符作为优先于另一个字符的首选拆分点。
          拆分字符不会影响以 RFC 2047(15) 编码的行。

          如果给出 `maxlinelen'，它将覆盖实例的最大行长度值。

          `linesep' 指定用来分隔已折叠标头行的字符。 它默认为 Python 应
          用程序代码中最常用的值 (‘\n’)，但也可以指定为 ‘\r\n’ 以便产生
          带有符合 RFC 的行分隔符的标头。

          3.2 版更變: 增加了 `linesep' 参数。

     *note Header: f83. 类还提供了一些方法以支持标准运算符和内置函数。

      -- 成員函式: __str__ ()

          以字符串形式返回 *note Header: f83. 的近似表示，使用不受限制的
          行长度。 所有部分都会使用指定编码格式转换为 unicode 并适当地连
          接起来。 任何带有 ‘'unknown-8bit'’ 字符集的部分都会使用
          ‘'replace'’ 错误处理程序解码为 ASCII。

          3.2 版更變: 增加对 ‘'unknown-8bit'’ 字符集的处理。

      -- 成員函式: __eq__ (other)

          这个方法允许你对两个 *note Header: f83. 实例进行相等比较。

      -- 成員函式: __ne__ (other)

          这个方法允许你对两个 *note Header: f83. 实例进行不等比较。

*note email.header: 6d. 模块还提供了下列便捷函数。

 -- 函式: email.header.decode_header (header)

     在不转换字符集的情况下对消息标头值进行解码。 `header' 为标头值。

     这个函数返回一个 ‘(decoded_string, charset)’ 对的列表，其中包含标头
     的每个已解码部分。 对于标头的未编码部分 `charset' 为 ‘None’，在其他
     情况下则为一个包含已编码字符串中所指定字符集名称的小写字符串。

     以下是为示例代码:

          >>> from email.header import decode_header
          >>> decode_header('=?iso-8859-1?q?p=F6stal?=')
          [(b'p\xf6stal', 'iso-8859-1')]

 -- 函式: email.header.make_header (decoded_seq, maxlinelen=None,
          header_name=None, continuation_ws=' ')

     基于 *note decode_header(): ad8. 所返回的数据对序列创建一个 *note
     Header: f83. 实例。

     *note decode_header(): ad8. 接受一个标头值字符串并返回格式为
     ‘(decoded_string, charset)’ 的数据对序列，其中 `charset' 是字符集名
     称。

     这个函数接受这样的数据对序列并返回一个 *note Header: f83. 实例。 可
     选的 `maxlinelen', `header_name' 和 `continuation_ws' 与 *note
     Header: f83. 构造器中的含义相同。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/email/header.py

   (2) https://tools.ietf.org/html/rfc2822.html

   (3) https://tools.ietf.org/html/rfc822.html

   (4) https://tools.ietf.org/html/rfc2822.html

   (5) https://tools.ietf.org/html/rfc2822.html

   (6) https://tools.ietf.org/html/rfc2045.html

   (7) https://tools.ietf.org/html/rfc2046.html

   (8) https://tools.ietf.org/html/rfc2047.html

   (9) https://tools.ietf.org/html/rfc2231.html

   (10) https://tools.ietf.org/html/rfc2047.html

   (11) https://tools.ietf.org/html/rfc2822.html

   (12) https://tools.ietf.org/html/rfc2047.html

   (13) https://tools.ietf.org/html/rfc2822.html

   (14) https://tools.ietf.org/html/rfc2822.html

   (15) https://tools.ietf.org/html/rfc2047.html


File: python.info,  Node: email charset 表示字符集,  Next: email encoders 编码器,  Prev: email header 国际化标头,  Up: email --- 电子邮件与 MIME 处理包

5.19.1.16 ‘email.charset’: 表示字符集
.....................................

`源代码:' Lib/email/charset.py(1)

__________________________________________________________________

此模块是旧版 (‘Compat32’) email API 的组成部分。 在新版 API 中只会使用其
中的别名表。

本段落中的剩余文本是该模块的原始文档。

此模块提供了一个 *note Charset: 7c7. 类用来表示电子邮件消息中的字符集和
字符集转换操作，以及一个字符集注册表和几个用于操作此注册表的便捷方法。
*note Charset: 7c7. 的实例在 *note email: 67. 包的其他几个模块中也有使用
。

请从 *note email.charset: 68. 模块导入这个类。

 -- 類別: email.charset.Charset (input_charset=DEFAULT_CHARSET)

     将字符集映射到其 email 特征属性。

     这个类提供了特定字符集对于电子邮件的要求的相关信息。 考虑到适用编解
     码器的可用性，它还为字符集之间的转换提供了一些便捷例程。 在给定字符
     集的情况下，它将尽可能地以符合 RFC 的方式在电子邮件消息中提供有关如
     何使用该字符集的信息。

     特定字符集当在电子邮件标头或消息体中使用时必须以 quoted-printable 或
     base64 来编码。 某些字符集则必须被立即转换，不允许在电子邮件中使用
     。

     可选的 `input_charset' 说明如下；它总是会被强制转为小写。 在进行别
     名正规化后它还会被用来查询字符集注册表以找出用于该字符集的标头编码
     格式、消息体编码格式和输出转换编解码器。 举例来说，如果
     `input_charset' 为 ‘iso-8859-1’，则标头和消息体将会使用
     quoted-printable 来编码并且不需要输出转换编解码器。 如果
     `input_charset' 为 ‘euc-jp’，则标头将使用 base64 来编码，消息体将不
     会被编码，但输出文本将从 ‘euc-jp’ 字符集转换为 ‘iso-2022-jp’ 字符集
     。

     *note Charset: 7c7. 实例具有下列数据属性:

      -- 屬性: input_charset

          指定的初始字符集。 通用别名会被转换为它们的 `官方' 电子邮件名
          称 (例如 ‘latin_1’ 会被转换为 ‘iso-8859-1’)。 默认值为 7 位
          ‘us-ascii’。

      -- 屬性: header_encoding

          如果字符集在用于电子邮件标头之前必须被编码，此属性将被设为
          ‘Charset.QP’ (表示 quoted-printable 编码格式),
          ‘Charset.BASE64’ (表示 base64 编码格式) 或 ‘Charset.SHORTEST’
          表示 QP 或 BASE64 编码格式中最简短的一个。 在其他情况下，该属
          性将为 ‘None’。

      -- 屬性: body_encoding

          与 `header_encoding' 一样，但是用来描述电子邮件消息体的编码格
          式，它实际上可以与标头编码格式不同。 ‘Charset.SHORTEST’ 不允许
          被用作 `body_encoding'。

      -- 屬性: output_charset

          某些字符集在用于电子邮件标头或消息体之前必须被转换。 如果
          `input_charset' 是这些字符集之一，该属性将包含输出将要转换的字
          符集名称。 在其他情况下，该属性将为 ‘None’。

      -- 屬性: input_codec

          用于将 `input_charset' 转换为 Unicode 的 Python 编解码器名称。
          如果不需要任何转换编解码器，该属性将为 ‘None’。

      -- 屬性: output_codec

          用于将 Unicode 转换为 `output_charset' 的 Python 编解码器名称
          。 如果不需要任何转换编解码器，该属性将具有与 `input_codec' 相
          同的值。

     *note Charset: 7c7. 实例还有下列方法:

      -- 成員函式: get_body_encoding ()

          返回用于消息体编码的内容转换编码格式。

          根据所使用的编码格式返回 ‘quoted-printable’ 或 ‘base64’，或是
          返回一个函数，在这种情况下你应当调用该函数并附带一个参数，即被
          编码的消息对象。 该函数应当自行将 ‘Content-Transfer-Encoding’
          标头设为适当的值。

          如果 `body_encoding' 为 ‘QP’ 则返回字符串 ‘quoted-printable’，
          如果 `body_encoding' 为 ‘BASE64’ 则返回字符串 ‘base64’，并在其
          他情况下返回字符串 ‘7bit’。

      -- 成員函式: get_output_charset ()

          返回输出字符集。

          如果 `output_charset' 属性不为 ‘None’ 则返回该属性，否则返回
          `input_charset'。

      -- 成員函式: header_encode (string)

          对字符串 `string' 执行标头编码。

          编码格式的类型 (base64 或 quoted-printable) 将取决于
          `header_encoding' 属性。

      -- 成員函式: header_encode_lines (string, maxlengths)

          通过先将 `string' 转换为字节串来对其执行标头编码。

          这类似于 *note header_encode(): 2a0e.，区别是字符串会被调整至
          参数 `maxlengths' 所给出的最大行长度，它应当是一个迭代器：该迭
          代器返回的每个元素将提供下一个最大行长度。

      -- 成員函式: body_encode (string)

          对字符串 `string' 执行消息体编码。

          编码格式的类型 (base64 或 quoted-printable) 将取决于
          `body_encoding' 属性。

     *note Charset: 7c7. 类还提供了一些方法以支持标准运算和内置函数。

      -- 成員函式: __str__ ()

          将 `input_charset' 以强制转为小写的字符串形式返回。 *note
          __repr__(): 44a. 是 *note __str__(): 2a11. 的别名。

      -- 成員函式: __eq__ (other)

          这个方法允许你对两个 *note Charset: 7c7. 实例进行相等比较。

      -- 成員函式: __ne__ (other)

          这个方法允许你对两个 *note Charset: 7c7. 实例进行相等比较。

*note email.charset: 68. 模块还提供了下列函数用于向全局字符集、别名以及
编解码器注册表添加新条目:

 -- 函式: email.charset.add_charset (charset, header_enc=None,
          body_enc=None, output_charset=None)

     向全局注册表添加字符特征属性。

     `charset' 是输入字符集，它必须为某个字符集的正规名称。

     可选的 `header_enc' 和 `body_enc' 可以是 ‘Charset.QP’ 表示
     quoted-printable, ‘Charset.BASE64’ 表示 base64 编码格式,
     ‘Charset.SHORTEST’ 表示 quoted-printable 或 base64 编码格式中较短的
     一个，或者为 ‘None’ 表示没有编码格式。 ‘SHORTEST’ 是 `header_enc' 的
     唯一有效值。 默认值为 ‘None’ 表示没有编码格式。

     可选的 `output_charset' 是输出所应当采用的字符集。 当
     ‘Charset.convert()’ 方法被调用时将会执行从输入字符集到输出字符集的
     转换。 默认情况下输出字符集将与输入字符集相同。

     `input_charset' 和 `output_charset' 都必须在模块的字符集-编解码器映
     射中具有 Unicode 编解码器条目；使用 *note add_codec(): 2a15. 可添加
     本模块还不知道的编解码器。 请参阅 *note codecs: 1b. 模块的文档来了
     解更多信息。

     全局字符集注册表保存在模块全局字典 ‘CHARSETS’ 中。

 -- 函式: email.charset.add_alias (alias, canonical)

     添加一个字符集别名。 `alias' 为特定的别名，例如 ‘latin-1’。
     `canonical' 是字符集的正规名称，例如 ‘iso-8859-1’。

     全局字符集注册表保存在模块全局字典 ‘ALIASES’ 中。

 -- 函式: email.charset.add_codec (charset, codecname)

     添加在给定字符集的字符和 Unicode 之间建立映射的编解码器。

     `charset' 是某个字符集的正规名称。 `codecname' 是某个 Python 编解码
     器的名称，可以被用来作为 *note str: 205. 的 *note encode(): 170. 方
     法的第二个参数。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/email/charset.py


File: python.info,  Node: email encoders 编码器,  Next: email utils 其他工具,  Prev: email charset 表示字符集,  Up: email --- 电子邮件与 MIME 处理包

5.19.1.17 ‘email.encoders’: 编码器
..................................

`源代码:' Lib/email/encoders.py(1)

__________________________________________________________________

此模块是旧版 (‘Compat32’) email API 的组成部分。 在新版 API 中将由 *note
set_content(): f81. 方法的 `cte' 形参提供该功能。

此模块在 Python 3 中已弃用。 这里提供的函数不应被显式地调用，因为 *note
MIMEText: 7c6. 类会在类实例化期间使用 `_subtype' 和 `_charset' 值来设置
内容类型和 CTE 标头。

本段落中的剩余文本是该模块的原始文档。

当创建全新的 *note Message: 63b. 对象时，你经常需要对载荷编码以便通过兼
容的邮件服务器进行传输。 对于包含二进制数据的 ‘image/*’ 和 ‘text/*’ 类型
的消息来说尤其如此。

*note email: 67. 包在其 ‘encoders’ 模块中提供了一些方便的编码器。 这些编
码器实际上由 *note MIMEAudio: 29fb. 和 *note MIMEImage: 299a. 类构造器所
使用以提供默认编码格式。 所有编码器函数都只接受一个参数，即要编码的消息
对象。 它们通常会提取有效载荷，对其进行编码，并将载荷重置为这种新编码的
值。 它们还应当相应地设置 ‘Content-Transfer-Encoding’ 标头。

请注意，这些函数对于多段消息没有意义。 它们必须应用到各个单独的段上面，
而不是整体。如果直接传递一个多段类型的消息，会产生一个 *note TypeError:
1fe. 错误。

下面是提供的编码函数：

 -- 函式: email.encoders.encode_quopri (msg)

     将有效数据编码为经转换的可打印形式，并将
     ‘Content-Transfer-Encoding’ 标头设置为 ‘quoted-printable’ (2)。 当
     大多数实际的数据是普通的可打印数据但包含少量不可打印的字符时，这是
     一个很好的编码。

 -- 函式: email.encoders.encode_base64 (msg)

     将有效载荷编码为 base64 形式，并将 ‘Content-Transfer-Encoding’ 标头
     设为 ‘base64’。 当你的载荷主要包含不可打印数据时这是一种很好用的编
     码格式，因为它比 quoted-printable 更紧凑。 base64 编码格式的缺点是
     它会使文本变成人类不可读的形式。

 -- 函式: email.encoders.encode_7or8bit (msg)

     此函数并不实际改变消息的有效载荷，但它会基于载荷数据将
     ‘Content-Transfer-Encoding’ 标头相应地设为 ‘7bit’ 或 ‘8bit’。

 -- 函式: email.encoders.encode_noop (msg)

     此函数什么都不会做；它甚至不会设置 ‘Content-Transfer-Encoding’ 标头
     。

註解
....

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/email/encoders.py

   (2) (1) 请注意使用 *note encode_quopri(): 2a19. 编码格式还会对数据中
的所有制表符和空格符进行编码。


File: python.info,  Node: email utils 其他工具,  Next: email iterators 迭代器,  Prev: email encoders 编码器,  Up: email --- 电子邮件与 MIME 处理包

5.19.1.18 ‘email.utils’: 其他工具
.................................

`源代码:' Lib/email/utils.py(1)

__________________________________________________________________

*note email.utils: 74. 模块提供如下几个工具

 -- 函式: email.utils.localtime (dt=None)

     以感知型 datetime 对象返回当地时间。 如果调用时参数为空，则返回当前
     时间。 否则 `dt' 参数应该是一个 *note datetime: 19f. 实例，并根据系
     统时区数据库转换为当地时区。 如果 `dt' 是简单型的 (即 ‘dt.tzinfo’ 是
     ‘None’ )，则假定为当地时间。 在这种情况下，为正值或零的 `isdst' 会
     使 ‘localtime’ 假定夏季时间（例如，夏令时）对指定时间生效或不生效。
     负值 `isdst' 会使 ‘localtime’ 预测夏季时间对指定时间是否生效。

     3.3 版新加入.

 -- 函式: email.utils.make_msgid (idstring=None, domain=None)

     返回一个适合作为兼容 RFC 2822(2) 的 ‘Message-ID’ 标头的字符串。可选
     参数 `idstring' 可传入一字符串以增强该消息 ID 的唯一性。可选参数
     `domain' 可用于提供消息 ID 中字符 ’@’ 之后的部分，其默认值是本机的
     主机名。正常情况下无需覆盖此默认值，但在特定情况下覆盖默认值可能会
     有用，比如构建一个分布式系统，在多台主机上采用一致的域名。

     3.2 版更變: 增加了关键字 `domain'

下列函数是旧（‘Compat32’）电子邮件 API 的一部分。新 API 提供的解析和格式
化在标头解析机制中已经被自动完成，故在使用新 API 时没有必要直接使用它们
函数。

 -- 函式: email.utils.quote (str)

     返回一个新的字符串， `str' 中的反斜杠被替换为两个反斜杠，并且双引号
     被替换为反斜杠加双引号。

 -- 函式: email.utils.unquote (str)

     返回 `str' 被去除引用后的字符串。如果 `str' 开头和结尾均是双引号，
     则这对双引号被去除。类似地，如果 `str' 开头和结尾都是尖角括号，这对
     尖角括号会被去除。

 -- 函式: email.utils.parseaddr (address)

     将地址（应为诸如 ‘To’ 或者 ‘Cc’ 之类包含地址的字段值）解析为构成之
     的 `真实名字' 和 `电子邮件地址' 部分。返回包含这两个信息的一个元组
     ；如若解析失败，则返回一个二元组 ‘('', '')’ 。

 -- 函式: email.utils.formataddr (pair, charset='utf-8')

     是 *note parseaddr(): 2a21. 的逆操作，接受一个 ‘(真实名字, 电子邮件
     地址)’ 的二元组，并返回适合于 ‘To’ or ‘Cc’ 标头的字符串。如果第一个
     元素为假性值，则第二个元素将被原样返回。

     可选地，如果指定 `charset'，则被视为一符合 RFC 2047(3) 的编码字符集
     ，用于编码 ‘真实名字’ 中的非 ASCII 字符。可以是一个 *note str: 205.
     类的实例，或者一个 *note Charset: 7c7. 类。默认为 ‘utf-8’ 。

     3.3 版更變: 添加了 `charset' 选项。

 -- 函式: email.utils.getaddresses (fieldvalues)

     该方法返回一个形似 ‘parseaddr()’ 返回的二元组的列表。 `fieldvalues'
     是一个序列，包含了形似 *note Message.get_all: 29db. 返回值的标头字
     段值。获取了一消息的所有收件人的简单示例如下：

          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)

 -- 函式: email.utils.parsedate (date)

     尝试根据 RFC 2822(4) 的规则解析一个日期。然而，有些寄信人不严格遵守
     这一格式，所以这种情况下 *note parsedate(): 2a22. 会尝试猜测其形式
     。`date' 是一个字符串包含了一个形如 ‘"Mon, 20 Nov 1995 19:12:08
     -0500"’ 的 RFC 2822(5) 格式日期。如果日期解析成功， *note
     parsedate(): 2a22. 将返回一个九元组，可直接传递给 *note
     time.mktime(): c36.；否则返回 ‘None’。注意返回的元组中下标为 6、7、
     8 的部分是无用的。

 -- 函式: email.utils.parsedate_tz (date)

     执行与 *note parsedate(): 2a22. 相同的功能，但会返回 ‘None’ 或是一
     个 10 元组；前 9 个元素构成一个可以直接传给 *note time.mktime():
     c36. 的元组，而第十个元素则是该日期的时区与 UTC (格林威治平均时 GMT
     的正式名称) (6) 的时差。 如果输入字符串不带时区，则所返回元组的最后
     一个元素将为 ‘0’，这表示 UTC。 请注意结果元组的索引号 6, 7 和 8 是
     不可用的。

 -- 函式: email.utils.parsedate_to_datetime (date)

     *note format_datetime(): add. 的逆操作。 执行与 *note parsedate():
     2a22. 相同的功能，但会在成功时返回一个 *note datetime: 19f.。 如果
     输入日期的时区值为 ‘-0000’，则 ‘datetime’ 将为一个简单型
     ‘datetime’，而如果日期符合 RFC 标准则它将代表一个 UTC 时间，但是并
     不指明日期所在消息的实际源时区。 如果输入日期具有任何其他有效的时区
     差值，则 ‘datetime’ 将为一个感知型 ‘datetime’ 并与 *note timezone:
     ae0. *note tzinfo: 180. 相对应。

     3.3 版新加入.

 -- 函式: email.utils.mktime_tz (tuple)

     将 *note parsedate_tz(): f6a. 所返回的 10 元组转换为一个 UTC 时间戳
     （相距 Epoch 纪元初始的秒数）。 如果元组中的时区项为 ‘None’，则视为
     当地时间。

 -- 函式: email.utils.formatdate (timeval=None, localtime=False,
          usegmt=False)

     返回 RFC 2822(7) 标准的日期字符串，例如:

          Fri, 09 Nov 2001 01:08:47 -0000

     可选的 `timeval' 如果给出，则是一个可被 *note time.gmtime(): c11. 和
     *note time.localtime(): 1080. 接受的浮点数时间值，否则会使得当前时
     间。

     可选的 `localtime' 是一个旗标，当为 ‘True’ 时，将会解析 `timeval'，
     并返回一个相对于当地时区而非 UTC 的日期值，并会适当地考虑夏令时。 默
     认值 ‘False’ 表示使用 UTC。

     可选的 `usegmt' 是一个旗标，当为 ‘True’ 时，将会输出一个日期字符串
     ，其中时区表示为 ascii 字符串 ‘GMT’ 而非数字形式的 ‘-0000’。 这对某
     些协议（例如 HTTP）来说是必要的。 这仅在 `localtime' 为 ‘False’ 时
     应用。 默认值为 ‘False’。

 -- 函式: email.utils.format_datetime (dt, usegmt=False)

     类似于 ‘formatdate’，但输入的是一个 *note datetime: 30. 实例。 如果
     实例是一个简单型 datetime，它会被视为 "不带源时区信息的 UTC"，并且
     使用传统的 ‘-0000’ 作为时区。 如果实例是一个感知型 ‘datetime’，则会
     使用数字形式的时区时差。 如果实例是感知型且时区时差为零，则
     `usegmt' 可能会被设为 ‘True’，在这种情况下将使用字符串 ‘GMT’ 而非数
     字形式的时区时差。 这提供了一种生成符合标准 HTTP 日期标头的方式。

     3.3 版新加入.

 -- 函式: email.utils.decode_rfc2231 (s)

     根据 RFC 2231(8) 解码字符串 `s'。

 -- 函式: email.utils.encode_rfc2231 (s, charset=None, language=None)

     根据 RFC 2231(9) 对字符串 `s' 进行编码。 可选的 `charset' 和
     `language' 如果给出，则为指明要使用的字符集名称和语言名称。 如果两
     者均未给出，则会原样返回 `s'。 如果给出 `charset' 但未给出
     `language'，则会使用空字符串作为 `language' 值来对字符串进行编码。

 -- 函式: email.utils.collapse_rfc2231_value (value, errors='replace',
          fallback_charset='us-ascii')

     当以 RFC 2231(10) 格式来编码标头形参时，*note Message.get_param:
     29e9. 可能返回一个包含字符集、语言和值的 3 元组。 *note
     collapse_rfc2231_value(): 29ea. 会将此返回为一个 unicode 字符串。 可
     选的 `errors' 会被传递给 *note str: 205. 的 *note encode(): 170. 方
     法的 `errors' 参数；它的默认值为 ‘'replace'’。 可选的
     `fallback_charset' 指定当 RFC 2231(11) 标头中的字符集无法被 Python
     识别时要使用的字符集；它的默认值为 ‘'us-ascii'’。

     为方便起见，如果传给 *note collapse_rfc2231_value(): 29ea. 的
     `value' 不是一个元组，则应为一个字符串并会将其原样返回。

 -- 函式: email.utils.decode_params (params)

     根据 RFC 2231(12) 解码参数列表。 `params' 是一个包含
     ‘(content-type, string-value)’ 形式的元素的 2 元组的序列。

备注
....

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/email/utils.py

   (2) https://tools.ietf.org/html/rfc2822.html

   (3) https://tools.ietf.org/html/rfc2047.html

   (4) https://tools.ietf.org/html/rfc2822.html

   (5) https://tools.ietf.org/html/rfc2822.html

   (6) (1) 请注意时区时差的符号与同一时区的 ‘time.timezone’ 变量的符号相
反；后者遵循 POSIX 标准而此模块遵循 RFC 2822
(https://tools.ietf.org/html/rfc2822.html)。

   (7) https://tools.ietf.org/html/rfc2822.html

   (8) https://tools.ietf.org/html/rfc2231.html

   (9) https://tools.ietf.org/html/rfc2231.html

   (10) https://tools.ietf.org/html/rfc2231.html

   (11) https://tools.ietf.org/html/rfc2231.html

   (12) https://tools.ietf.org/html/rfc2231.html


File: python.info,  Node: email iterators 迭代器,  Prev: email utils 其他工具,  Up: email --- 电子邮件与 MIME 处理包

5.19.1.19 ‘email.iterators’: 迭代器
...................................

`源代码:' Lib/email/iterators.py(1)

__________________________________________________________________

通过 *note Message.walk: 29f2. 方法来迭代消息对象树是相当容易的。 *note
email.iterators: 6f. 模块提供了一些适用于消息对象树的高层级迭代器。

 -- 函式: email.iterators.body_line_iterator (msg, decode=False)

     此函数会迭代 `msg' 的所有子部分中的所有载荷，逐行返回字符串载荷。 它
     会跳过所有子部分的标头，并且它也会跳过任何包含不为 Python 字符串的
     载荷的子部分。 这基本上等价于使用 *note readline(): 1d5b. 从一个文
     件读取消息的纯文本表示形式，并跳过所有中间的标头。

     可选的 `decode' 会被传递给 *note Message.get_payload: c1d.。

 -- 函式: email.iterators.typed_subpart_iterator (msg, maintype='text',
          subtype=None)

     此函数会迭代 `msg' 的所有子部分，只返回其中与 `maintype' 和
     `subtype' 所指定的 MIME 类型相匹配的子部分。

     请注意 `subtype' 是可选项；如果省略，则仅使用主类型来进行子部分
     MIME 类型的匹配。 `maintype' 也是可选项；它的默认值为 ‘text’。

     因此，在默认情况下 *note typed_subpart_iterator(): 2a2b. 会返回每一
     个 MIME 类型为 ‘text/*’ 的子部分。

增加了以下函数作为有用的调试工具。 它 `不应当' 被视为该包所支持的公共接
口的组成部分。

 -- 函式: email.iterators._structure (msg, fp=None, level=0,
          include_default=False)

     打印消息对象结构的内容类型的缩进表示形式。 例如:

          >>> 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

     可选项 `fp' 是一个作为打印输出目标的文件类对象。 它必须适用于
     Python 的 *note print(): 971. 函数。 `level' 是供内部使用的。
     `include_default' 如果为真值，则会同时打印默认类型。

也參考
......

*note smtplib: ed. 模块

     SMTP (简单邮件传输协议) 客户端

*note poplib: d0. 模块

     POP (邮局协议) 客户端

*note imaplib: 97. 模块

     IMAP (互联网消息访问协议) 客户端

*note nntplib: c0. 模块

     NNTP (网络新闻传输协议) 客户端

*note mailbox: ae. 模块

     创建、读取和管理使用保存在磁盘中的多种标准格式的消息集的工具。

*note smtpd: ec. 模块

     SMTP 服务器框架 (主要适用于测试)

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/email/iterators.py


File: python.info,  Node: json --- JSON 编码和解码器,  Next: mailcap --- Mailcap 文件处理,  Prev: email --- 电子邮件与 MIME 处理包,  Up: 互联网数据处理

5.19.2 ‘json’ — JSON 编码和解码器
---------------------------------

`源代码:' Lib/json/__init__.py(1)

__________________________________________________________________

JSON (JavaScript Object Notation)(2), specified by RFC 7159(3) (which
obsoletes RFC 4627(4)) and by ECMA-404(5), is a lightweight data
interchange format inspired by JavaScript(6) object literal syntax
(although it is not a strict subset of JavaScript (7) ).

*note json: a4. 提供了与标准库 *note marshal: b0. 和 *note pickle: ca. 相
似的API接口。

对基本的 Python 对象层次结构进行编码：

     >>> 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"]'

紧凑编码:

     >>> import json
     >>> json.dumps([1, 2, 3, {'4': 5, '6': 7}], separators=(',', ':'))
     '[1,2,3,{"4":5,"6":7}]'

美化輸出：

     >>> import json
     >>> print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4))
     {
         "4": 5,
         "6": 7
     }

JSON解码:

     >>> 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']

特殊JSON对象解码:

     >>> 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')

扩展 *note JSONEncoder: 6fd.:

     >>> 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', ']']

从命令行使用 *note json.tool: a5. 来验证并美化输出：

     $ 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)

详细文档请参见 *note 命令行界面: 2a2f.。

     備註: JSON 是 YAML(8) 1.2 的一个子集。由该模块的默认设置生成的 JSON
     （尤其是默认的 “分隔符” 设置值）也是 YAML 1.0 and 1.1 的一个子集。
     因此该模块也能够用于序列化为 YAML。

     備註: 这个模块的编码器和解码器默认保护输入和输出的顺序。仅当底层的
     容器未排序时才会失去顺序。

     在 Python 3.7 之前，*note dict: 164. 并不保证有序，因此输入和输出通
     常都是乱序的，除非是明确地请求 *note collections.OrderedDict: 2ea.。
     从 Python 3.7 开始，普通的 *note dict: 164. 会保留顺序，因此不必再
     为 JSON 的生成和解析指定使用 *note collections.OrderedDict: 2ea.。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/json/__init__.py

   (2) https://json.org

   (3) https://tools.ietf.org/html/rfc7159.html

   (4) https://tools.ietf.org/html/rfc4627.html

   (5) 
https://www.ecma-international.org/publications-and-standards/standards/ecma-404/

   (6) https://en.wikipedia.org/wiki/JavaScript

   (7) (1) 正如 RFC 7159 的勘误表
(https://www.rfc-editor.org/errata_search.php?rfc=7159) 所说明的，JSON 允
许以字符串表示字面值字符 U+2028 (LINE SEPARATOR) 和 U+2029 (PARAGRAPH
SEPARATOR)，而 JavaScript (在 ECMAScript 5.1 版中) 不允许。

   (8) http://yaml.org/


File: python.info,  Node: 基本使用,  Next: 编码器和解码器,  Up: json --- JSON 编码和解码器

5.19.2.1 基本使用
.................

 -- 函式: 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)

     使用这个 *note 转换表: 2a31. 将 `obj' 序列化为 JSON 格式化流形式的
     `fp' (支持 ‘.write()’ 的 *note file-like object: 1dc6.)。

     如果 `skipkeys' 是 true （默认为 ‘False’），那么那些不是基本对象（
     包括 *note str: 205, *note int: 204.、*note float: 1fd.、*note
     bool: 2bd.、‘None’）的字典的键会被跳过；否则引发一个 *note
     TypeError: 1fe.。

     *note json: a4. 模块始终产生 *note str: 205. 对象而非 *note bytes:
     172. 对象。因此，‘fp.write()’ 必须支持 *note str: 205. 输入。

     如果 `ensure_ascii' 是 true （即默认值），输出保证将所有输入的非
     ASCII 字符转义。如果 `ensure_ascii' 是 false，这些字符会原样输出。

     If `check_circular' is false (default: ‘True’), then the circular
     reference check for container types will be skipped and a circular
     reference will result in an *note RecursionError: 727. (or worse).

     如果 `allow_nan' 是 false（默认为 ‘True’），那么在对严格 JSON 规格
     范围外的 *note float: 1fd. 类型值（‘nan’、‘inf’ 和 ‘-inf’）进行序列
     化时会引发一个 *note ValueError: 16d.。如果 `allow_nan' 是 true，则
     使用它们的 JavaScript 等价形式（‘NaN’、‘Infinity’ 和 ‘-Infinity’）
     。

     如果 `indent' 是一个非负整数或者字符串，那么 JSON 数组元素和对象成
     员会被美化输出为该值指定的缩进等级。 如果缩进等级为零、负数或者
     ‘""’，则只会添加换行符。 ‘None’ (默认值) 选择最紧凑的表达。 使用一
     个正整数会让每一层缩进同样数量的空格。 如果 `indent' 是一个字符串
     (比如 ‘"\t"’)，那个字符串会被用于缩进每一层。

     3.2 版更變: 允许使用字符串作为 `indent' 而不再仅仅是整数。

     当指定时，`separators' 应当是一个 ‘(item_separator, key_separator)’
     元组。当 `indent' 为 ‘None’ 时，默认值取 ‘(', ', ': ')’，否则取
     ‘(',', ': ')’。为了得到最紧凑的 JSON 表达式，你应该指定其为 ‘(',',
     ':')’ 以消除空白字符。

     3.4 版更變: 现当 `indent' 不是 ‘None’ 时，采用 ‘(',', ': ')’ 作为默
     认值。

     当 `default' 被指定时，其应该是一个函数，每当某个对象无法被序列化时
     它会被调用。它应该返回该对象的一个可以被 JSON 编码的版本或者引发一
     个 *note TypeError: 1fe.。如果没有被指定，则会直接引发 *note
     TypeError: 1fe.。

     如果 `sort_keys' 是 true（默认为 ‘False’），那么字典的输出会以键的
     顺序排序。

     为了使用一个自定义的 *note JSONEncoder: 6fd. 子类（比如：覆盖了
     ‘default()’ 方法来序列化额外的类型）， 通过 `cls' 关键字参数来指定
     ；否则将使用 *note JSONEncoder: 6fd.。

     3.6 版更變: 所有的可选参数现在是 *note keyword-only: 3ce. 的了。

          備註: 与 *note pickle: ca. 和 *note marshal: b0. 不同，JSON 不
          是一个具有框架的协议，所以尝试多次使用同一个 `fp' 调用 *note
          dump(): 6fb. 来序列化多个对象会产生一个不合规的 JSON 文件。

 -- 函式: 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)

     使用这个 *note 转换表: 2a31. 将 `obj' 序列化为 JSON 格式的 *note
     str: 205.。 其参数的含义与 *note dump(): 6fb. 中的相同。

          備註: JSON 中的键-值对中的键永远是 *note str: 205. 类型的。当
          一个对象被转化为 JSON 时，字典中所有的键都会被强制转换为字符串
          。这所造成的结果是字典被转换为 JSON 然后转换回字典时可能和原来
          的不相等。换句话说，如果 x 具有非字符串的键，则有
          ‘loads(dumps(x)) != x’。

 -- 函式: json.load (fp, *, cls=None, object_hook=None,
          parse_float=None, parse_int=None, parse_constant=None,
          object_pairs_hook=None, **kw)

     使用这个 *note 转换表: 2a32. 将 `fp' (一个支持 ‘.read()’ 并包含一个
     JSON 文档的 *note text file: 13d9. 或者 *note binary file: 1e01.) 反
     序列化为一个 Python 对象。

     `object_hook' 是一个可选的函数，它会被调用于每一个解码出的对象字面
     量（即一个 *note dict: 164.）。`object_hook' 的返回值会取代原本的
     *note dict: 164.。这一特性能够被用于实现自定义解码器（如
     JSON-RPC(1) 的类型提示)。

     `object_pairs_hook' 是一个可选的函数，它会被调用于每一个有序列表对
     解码出的对象字面量。 `object_pairs_hook' 的返回值将会取代原本的
     *note dict: 164. 。这一特性能够被用于实现自定义解码器。如果
     `object_hook' 也被定义， `object_pairs_hook' 优先。

     3.1 版更變: 添加了对 `object_pairs_hook' 的支持。

     `parse_float' ，如果指定，将与每个要解码 JSON 浮点数的字符串一同调
     用。默认状态下，相当于 ‘float(num_str)’ 。可以用于对 JSON 浮点数使
     用其它数据类型和语法分析程序 （比如 *note decimal.Decimal: 2c0. ）
     。

     `parse_int' ，如果指定，将与每个要解码 JSON 整数的字符串一同调用。
     默认状态下，相当于 ‘int(num_str)’ 。可以用于对 JSON 整数使用其它数
     据类型和语法分析程序 （比如 *note float: 1fd. ）。

     `parse_constant' ，如果指定，将要与以下字符串中的一个一同调用：
     ‘'-Infinity'’ ， ‘'Infinity'’ ， ‘'NaN'’ 。如果遇到无效的 JSON 数字
     则可以使用它引发异常。

     3.1 版更變: `parse_constant' 不再调用 ’null’ ， ’true’ ， ’false’ 。

     要使用自定义的 *note JSONDecoder: 6fe. 子类，用 ‘cls’ 指定他；否则
     使用 *note JSONDecoder: 6fe. 。额外的关键词参数会通过类的构造函数传
     递。

     如果反序列化的数据不是有效 JSON 文档，引发 *note JSONDecodeError:
     7f7. 错误。

     3.6 版更變: 所有的可选参数现在是 *note keyword-only: 3ce. 的了。

     3.6 版更變: `fp' 现在可以是 *note binary file: 1e01. 。输入编码应当
     是 UTF-8 ， UTF-16 或者 UTF-32 。

 -- 函式: json.loads (s, *, cls=None, object_hook=None,
          parse_float=None, parse_int=None, parse_constant=None,
          object_pairs_hook=None, **kw)

     使用这个 *note 转换表: 2a32. 将 `s' (一个包含 JSON 文档的 *note
     str: 205, *note bytes: 172. 或 *note bytearray: 173. 实例) 反序列化
     为 Python 对象。

     其他参数的含义与 *note load(): 659. 中的相同。

     如果反序列化的数据不是有效 JSON 文档，引发 *note JSONDecodeError:
     7f7. 错误。

     3.6 版更變: `s' 现在可以为 *note bytes: 172. 或 *note bytearray:
     173. 类型。 输入编码应为 UTF-8, UTF-16 或 UTF-32。

     3.9 版更變: 关键字参数 `encoding' 已被移除。

   ---------- Footnotes ----------

   (1) http://www.jsonrpc.org


File: python.info,  Node: 编码器和解码器,  Next: 例外,  Prev: 基本使用,  Up: json --- JSON 编码和解码器

5.19.2.2 编码器和解码器
.......................

 -- 類別: json.JSONDecoder (*, object_hook=None, parse_float=None,
          parse_int=None, parse_constant=None, strict=True,
          object_pairs_hook=None)

     简单的JSON解码器。

     默认情况下，解码执行以下翻译:

     JSON                Python
                         
     --------------------------------------------
                         
     object              dict
                         
                         
     array               list
                         
                         
     string              str
                         
                         
     number (int)        int
                         
                         
     number (real)       float
                         
                         
     true                True
                         
                         
     false               False
                         
                         
     null                None
                         

     它还将“NaN”、“Infinity”和“-Infinity”理解为它们对应的“float”值，这超
     出了JSON规范。

     如果指定了 `object_hook'，它将被调用并传入每个已解码 JSON 对象的结
     果，并且其返回值将被用来替代给定的 *note dict: 164.。 它可被用于提
     供自定义的反序列化操作（例如支持 JSON-RPC(1) 类提示）。

     如果指定了 `object_pairs_hook' 则它将被调用并传入以对照值有序列表进
     行解码的每个 JSON 对象的结果。 `object_pairs_hook' 的结果值将被用来
     替代 *note dict: 164.。 这一特性可被用于实现自定义解码器。 如果还定
     义了 `object_hook'，则 `object_pairs_hook' 的优先级更高。

     3.1 版更變: 添加了对 `object_pairs_hook' 的支持。

     `parse_float' ，如果指定，将与每个要解码 JSON 浮点数的字符串一同调
     用。默认状态下，相当于 ‘float(num_str)’ 。可以用于对 JSON 浮点数使
     用其它数据类型和语法分析程序 （比如 *note decimal.Decimal: 2c0. ）
     。

     `parse_int' ，如果指定，将与每个要解码 JSON 整数的字符串一同调用。
     默认状态下，相当于 ‘int(num_str)’ 。可以用于对 JSON 整数使用其它数
     据类型和语法分析程序 （比如 *note float: 1fd. ）。

     `parse_constant' ，如果指定，将要与以下字符串中的一个一同调用：
     ‘'-Infinity'’ ， ‘'Infinity'’ ， ‘'NaN'’ 。如果遇到无效的 JSON 数字
     则可以使用它引发异常。

     如果 `strict' 为 false （默认为 ‘True’ ），那么控制字符将被允许在字
     符串内。在此上下文中的控制字符编码在范围 0–31 内的字符，包括 ‘'\t'’
     (制表符）， ‘'\n'’ ， ‘'\r'’ 和 ‘'\0'’ 。

     如果反序列化的数据不是有效 JSON 文档，引发 *note JSONDecodeError:
     7f7. 错误。

     3.6 版更變: 所有形参现在都是 *note 仅限关键字参数: 3ce.。

      -- 成員函式: decode (s)

          返回 `s' 的 Python 表示形式（包含一个 JSON 文档的 *note str:
          205. 实例）。

          如果给定的 JSON 文档无效则将引发 *note JSONDecodeError: 7f7.。

      -- 成員函式: raw_decode (s)

          从 `s' 中解码出 JSON 文档（以 JSON 文档开头的一个 *note str:
          205. 对象）并返回一个 Python 表示形式为 2 元组以及指明该文档在
          `s' 中结束位置的序号。

          这可以用于从一个字符串解码JSON文档，该字符串的末尾可能有无关的
          数据。

 -- 類別: json.JSONEncoder (*, skipkeys=False, ensure_ascii=True,
          check_circular=True, allow_nan=True, sort_keys=False,
          indent=None, separators=None, default=None)

     用于Python数据结构的可扩展JSON编码器。

     默认支持以下对象和类型：

     Python                                       JSON
                                                  
     -----------------------------------------------------------------
                                                  
     dict                                         object
                                                  
                                                  
     list, tuple                                  array
                                                  
                                                  
     str                                          string
                                                  
                                                  
     int, float, int 和 float 派生的枚举          number
                                                  
                                                  
     True                                         true
                                                  
                                                  
     False                                        false
                                                  
                                                  
     None                                         null
                                                  

     3.4 版更變: 添加了对 int 和 float 派生的枚举类的支持

     为了将其拓展至识别其他对象，需要子类化并实现 *note default(): 2a36.
     方法于另一种返回 ‘o’ 的可序列化对象的方法如果可行，否则它应该调用超
     类实现（来引发 *note TypeError: 1fe. ）。

     如果 `skipkeys' 为假值（默认），则当尝试对非 *note str: 205, *note
     int: 204, *note float: 1fd. 或 ‘None’ 的键进行编码时将会引发 *note
     TypeError: 1fe.。 如果 `skipkeys' 为真值，这些条目将被直接跳过。

     如果 `ensure_ascii' 是 true （即默认值），输出保证将所有输入的非
     ASCII 字符转义。如果 `ensure_ascii' 是 false，这些字符会原样输出。

     If `check_circular' is true (the default), then lists, dicts, and
     custom encoded objects will be checked for circular references
     during encoding to prevent an infinite recursion (which would cause
     an *note RecursionError: 727.).  Otherwise, no such check takes
     place.

     如果 `allow_nan' 为 true （默认），那么 ‘NaN’ ， ‘Infinity’ ，和
     ‘-Infinity’ 进行编码。此行为不符合 JSON 规范，但与大多数的基于
     Javascript 的编码器和解码器一致。否则，它将是一个 *note ValueError:
     16d. 来编码这些浮点数。

     如果 `sort_keys' 为 true （默认为： ‘False’ ），那么字典的输出是按
     照键排序；这对回归测试很有用，以确保可以每天比较 JSON 序列化。

     如果 `indent' 是一个非负整数或者字符串，那么 JSON 数组元素和对象成
     员会被美化输出为该值指定的缩进等级。 如果缩进等级为零、负数或者
     ‘""’，则只会添加换行符。 ‘None’ (默认值) 选择最紧凑的表达。 使用一
     个正整数会让每一层缩进同样数量的空格。 如果 `indent' 是一个字符串
     (比如 ‘"\t"’)，那个字符串会被用于缩进每一层。

     3.2 版更變: 允许使用字符串作为 `indent' 而不再仅仅是整数。

     当指定时，`separators' 应当是一个 ‘(item_separator, key_separator)’
     元组。当 `indent' 为 ‘None’ 时，默认值取 ‘(', ', ': ')’，否则取
     ‘(',', ': ')’。为了得到最紧凑的 JSON 表达式，你应该指定其为 ‘(',',
     ':')’ 以消除空白字符。

     3.4 版更變: 现当 `indent' 不是 ‘None’ 时，采用 ‘(',', ': ')’ 作为默
     认值。

     当 `default' 被指定时，其应该是一个函数，每当某个对象无法被序列化时
     它会被调用。它应该返回该对象的一个可以被 JSON 编码的版本或者引发一
     个 *note TypeError: 1fe.。如果没有被指定，则会直接引发 *note
     TypeError: 1fe.。

     3.6 版更變: 所有形参现在都是 *note 仅限关键字参数: 3ce.。

      -- 成員函式: default (o)

          在子类中实现这种方法使其返回 `o' 的可序列化对象，或者调用基础
          实现（引发 *note TypeError: 1fe. ）。

          例如，为了支持任意的迭代器，你可以这样来实现 *note default():
          2a36.:

               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)

      -- 成員函式: encode (o)

          返回 Python `o' 数据结构的 JSON 字符串表达方式。例如:

               >>> json.JSONEncoder().encode({"foo": ["bar", "baz"]})
               '{"foo": ["bar", "baz"]}'

      -- 成員函式: iterencode (o)

          编码给定对象 `o' ，并且让每个可用的字符串表达方式。例如:

               for chunk in json.JSONEncoder().iterencode(bigobject):
                   mysocket.write(chunk)

   ---------- Footnotes ----------

   (1) http://www.jsonrpc.org


File: python.info,  Node: 例外,  Next: 标准符合性和互操作性,  Prev: 编码器和解码器,  Up: json --- JSON 编码和解码器

5.19.2.3 例外
.............

 -- 例外: json.JSONDecodeError (msg, doc, pos)

     拥有以下附加属性的 *note ValueError: 16d. 的子类：

      -- 屬性: msg

          未格式化的错误消息。

      -- 屬性: doc

          正在解析的 JSON 文档。

      -- 屬性: pos

          The start index of `doc' where parsing failed.

      -- 屬性: lineno

          The line corresponding to `pos'.

      -- 屬性: colno

          The column corresponding to `pos'.

     3.5 版新加入.


File: python.info,  Node: 标准符合性和互操作性,  Next: 命令行界面<4>,  Prev: 例外,  Up: json --- JSON 编码和解码器

5.19.2.4 标准符合性和互操作性
.............................

The JSON format is specified by RFC 7159(1) and by ECMA-404(2).  This
section details this module’s level of compliance with the RFC. For
simplicity, *note JSONEncoder: 6fd. and *note JSONDecoder: 6fe.
subclasses, and parameters other than those explicitly mentioned, are
not considered.

此模块不严格遵循于 RFC ，它实现了一些扩展是有效的 Javascript 但不是有效
的 JSON。尤其是：

   - 无限和 NaN 数值是被接受并输出；

   - 对象内的重复名称是接受的，并且仅使用最后一对属性-值对的值。

自从 RFC 允许符合 RFC 的语法分析程序接收 不符合 RFC 的输入文本以来，这个
模块的解串器在默认状态下默认符合 RFC 。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc7159.html

   (2) 
https://www.ecma-international.org/publications-and-standards/standards/ecma-404/


File: python.info,  Node: 字符编码,  Next: Infinite 和 NaN 数值,  Up: 标准符合性和互操作性

5.19.2.5 字符编码
.................

RFC 要求使用 UTF-8 ， UTF-16 ，或 UTF-32 之一来表示 JSON ，为了最大互通
性推荐使用 UTF-8 。

RFC允许，尽管不是必须的，这个模块的序列化默认设置为 `ensure_ascii=True'
，这样消除输出以便结果字符串至容纳 ASCII 字符。

`ensure_ascii' 参数以外，此模块是严格的按照在 Python 对象和 *note
Unicode strings: 205. 间的转换定义的，并且因此不能直接解决字符编码的问题
。

RFC 禁止添加字符顺序标记（ BOM ）在 JSON 文本的开头，这个模块的序列化器
不添加 BOM 标记在它的输出上。 RFC，准许 JSON 反序列化器忽略它们输入中的
初始 BOM 标记，但不要求。此模块的反序列化器引发 *note ValueError: 16d. 当
存在初始 BOM 标记。

RFC 不会明确禁止包含字节序列的 JSON 字符串这不对应有效的 Unicode 字符（
比如 不成对的 UTF-16 的替代物），但是它确实指出它们可能会导致互操作性问
题。默认下，模块对这样的序列接受和输出（当在原始 *note str: 205. 存在时
）代码点。


File: python.info,  Node: Infinite 和 NaN 数值,  Next: 对象中的重复名称,  Prev: 字符编码,  Up: 标准符合性和互操作性

5.19.2.6 Infinite 和 NaN 数值
.............................

RFC 不允许 infinite 或者 NaN 数值的表达方式。尽管这样，默认情况下，此模
块接受并且输出 ‘Infinity’ ， ‘-Infinity’，和 ‘NaN’ 好像它们是有效的
JSON数字字面值

     >>> # 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

序列化器中， `allow_nan' 参数可用于替代这个行为。反序列化器中，
`parse_constant' 参数，可用于替代这个行为。


File: python.info,  Node: 对象中的重复名称,  Next: 顶级非对象，非数组值,  Prev: Infinite 和 NaN 数值,  Up: 标准符合性和互操作性

5.19.2.7 对象中的重复名称
.........................

RFC 具体说明了 在 JSON对象里的名字应该是唯一的，但没有规定如何处理JSON对
象中的重复名称。默认下，此模块不引发异常；作为替代，对于给定名它将忽略除
姓-值对之外的所有对:

     >>> weird_json = '{"x": 1, "x": 2, "x": 3}'
     >>> json.loads(weird_json)
     {'x': 3}

The `object_pairs_hook' parameter can be used to alter this behavior.


File: python.info,  Node: 顶级非对象，非数组值,  Next: 实现限制,  Prev: 对象中的重复名称,  Up: 标准符合性和互操作性

5.19.2.8 顶级非对象，非数组值
.............................

过时的 RFC 4627(1) 指定的旧版本 JSON 要求 JSON 文本顶级值必须是 JSON 对
象或数组（ Python *note dict: 164. 或 *note list: 1f8. ），并且不能是
JSON null 值，布尔值，数值或者字符串值。 RFC 7159(2) 移除这个限制，此模
块没有并且从未在序列化器和反序列化器中实现这个限制。

无论如何，为了最大化地获取互操作性，你可能希望自己遵守该原则。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc4627.html

   (2) https://tools.ietf.org/html/rfc7159.html


File: python.info,  Node: 实现限制,  Prev: 顶级非对象，非数组值,  Up: 标准符合性和互操作性

5.19.2.9 实现限制
.................

一些 JSON 反序列化器的实现应该在以下方面做出限制：

   * 可接受的 JSON 文本大小

   * 嵌套 JSON 对象和数组的最高水平

   * JSON 数字的范围和精度

   * JSON 字符串的内容和最大长度

此模块不强制执行任何上述限制，除了相关的 Python 数据类型本身或者 Python
解释器本身的限制以外。

当序列化为 JSON ，在应用中当心此类限制这可能破坏你的 JSON 。特别是，通常
将 JSON 数字反序列化为 IEEE 754 双精度数字，从而受到该表示方式的范围和精
度限制。这是特别相关的，当序列化非常大的 Python *note int: 204. 值时，或
者当序列化 "exotic" 数值类型的实例时比如 *note decimal.Decimal: 2c0. 。


File: python.info,  Node: 命令行界面<4>,  Prev: 标准符合性和互操作性,  Up: json --- JSON 编码和解码器

5.19.2.10 命令行界面
....................

`源代码：' Lib/json/tool.py(1)

__________________________________________________________________

The *note json.tool: a5. module provides a simple command line interface
to validate and pretty-print JSON objects.

如果未指定可选的 ‘infile’ 和 ‘outfile’ 参数，则将分别使用 *note
sys.stdin: 41e. 和 *note sys.stdout: 41f.:

     $ 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)

3.5 版更變: 输出现在将与输入顺序保持一致。 请使用 *note –sort-keys:
2a46. 选项来将输出按照键的字母顺序排序。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/json/tool.py


File: python.info,  Node: 命令行选项<4>,  Up: 命令行界面<4>

5.19.2.11 命令行选项
....................

 -- 程式選項: infile

     要被验证或美化打印的 JSON 文件：

          $ 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
              }
          ]

     如果 `infile' 未指定，则从 *note sys.stdin: 41e. 读取。

 -- 程式選項: outfile

     将 `infile' 输出写入到给定的 `outfile'。 在其他情况下写入到 *note
     sys.stdout: 41f.。

 -- 程式選項: --sort-keys

     将字典输出按照键的字母顺序排序。

     3.5 版新加入.

 -- 程式選項: --no-ensure-ascii

     禁用非 ASCII 字符的转义，详情参见 *note json.dumps(): 6fc.。

     3.9 版新加入.

 -- 程式選項: --json-lines

     将每个输入行解析为单独的 JSON 对象。

     3.8 版新加入.

 -- 程式選項: --indent, --tab, --no-indent, --compact

     用于空白符控制的互斥选项。

     3.9 版新加入.

 -- 程式選項: -h, --help

     显示帮助消息。

註解
....


File: python.info,  Node: mailcap --- Mailcap 文件处理,  Next: mailbox --- 操作多种格式的邮箱,  Prev: json --- JSON 编码和解码器,  Up: 互联网数据处理

5.19.3 ‘mailcap’ — Mailcap 文件处理
-----------------------------------

`源代码:' Lib/mailcap.py(1)

__________________________________________________________________

Mailcap 文件可用来配置支持 MIME 的应用例如邮件阅读器和 Web 浏览器如何响
应具有不同 MIME 类型的文件。 （"mailcap" 这个名称源自短语"mail
capability"。） 例如，一个 mailcap 文件可能包含 ‘video/mpeg; xmpeg %s’ 这
样的行。 然后，如果用户遇到 MIME 类型为 ‘video/mpeg’ 的邮件消息或 Web 文
档时，‘%s’ 将被替换为一个文件名（通常是一个临时文件）并且将自动启动
‘xmpeg’ 程序来查看该文件。

mailcap 格式的文档见 RFC 1524(2), "A User Agent Configuration Mechanism
For Multimedia Mail Format Information"，但它并不是一个因特网标准。 不过
，mailcap 文件在大多数 Unix 系统上都受到支持。

 -- 函式: mailcap.findmatch (caps, MIMEtype, key='view',
          filename='/dev/null', plist=[])

     返回一个 2 元组；其中第一个元素是包含所要执行命令的字符串 (它可被传
     递给 *note os.system(): e86.)，第二个元素是对应于给定 MIME 类型的
     mailcap 条目。 如果找不到匹配的 MIME 类型，则将返回 ‘(None, None)’。

     `key' 是所需字段的名称，它代表要执行的活动类型；默认值是 ’view’，因
     为在最通常的情况下你只是想要查看 MIME 类型数据的正文。 其他可能的值
     还有 ’compose’ 和 ’edit’，分别用于想要创建给定 MIME 类型正文或修改
     现有正文数据的情况。 请参阅 RFC 1524(3) 获取这些字段的完整列表。

     `filename' 是在命令行中用来替换 ‘%s’ 的文件名；默认值 ‘'/dev/null'’
     几乎肯定不是你想要的，因此通常你要通过指定一个文件名来重载它。

     `plist' 可以是一个包含命名形参的列表；默认值只是一个空列表。 列表中
     的每个条目必须为包含形参名称的字符串、等于号 (‘'='’) 以及形参的值。
     Mailcap 条目可以包含形如 ‘%{foo}’ 的命名形参，它将由名为 ’foo’ 的形
     参的值所替换。 例如，如果命令行 ‘showpartial %{id} %{number}
     %{total}’ 是在一个 mailcap 文件中，并且 `plist' 被设为 ‘['id=1',
     'number=2', 'total=3']’，则结果命令行将为 ‘'showpartial 1 2 3'’。

     在 mailcap 文件中，可以指定可选的 "test" 字段来检测某些外部条件（例
     如所使用的机器架构或窗口系统）来确定是否要应用 mailcap 行。 *note
     findmatch(): 2a50. 将自动检查此类条件并在检查未通过时跳过条目。

 -- 函式: mailcap.getcaps ()

     返回一个将 MIME 类型映射到 mailcap 文件条目列表的字典。 此字典必须
     被传给 *note findmatch(): 2a50. 函数。 条目会被存储为字典列表，但并
     不需要了解此表示形式的细节。

     此信息来自在系统中找到的所有 mailcap 文件。 用户的 mailcap 文件
     ‘$HOME/.mailcap’ 中的设置将覆盖系统 mailcap 文件 ‘/etc/mailcap’,
     ‘/usr/etc/mailcap’ 和 ‘/usr/local/etc/mailcap’ 中的设置。

一个用法示例:

     >>> import mailcap
     >>> d = mailcap.getcaps()
     >>> mailcap.findmatch(d, 'video/mpeg', filename='tmp1223')
     ('xmpeg tmp1223', {'view': 'xmpeg %s'})

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/mailcap.py

   (2) https://tools.ietf.org/html/rfc1524.html

   (3) https://tools.ietf.org/html/rfc1524.html


File: python.info,  Node: mailbox --- 操作多种格式的邮箱,  Next: mimetypes --- 映射文件名到 MIME 类型,  Prev: mailcap --- Mailcap 文件处理,  Up: 互联网数据处理

5.19.4 ‘mailbox’ — 操作多种格式的邮箱
-------------------------------------

`源代码：' Lib/mailbox.py(1)

__________________________________________________________________

本模块定义了两个类，*note Mailbox: cb1. 和 *note Message: cb5.，用于访问
和操作磁盘中的邮箱及其所包含的电子邮件。 *note Mailbox: cb1. 提供了类似
字典的从键到消息的映射。 *note Message: cb5. 为 *note email.message: 70.
模块的 *note Message: 63b. 类增加了特定格式专属的状态和行为。 支持的邮箱
格式有 Maildir, mbox, MH, Babyl 以及 MMDF。

也參考
......

模块 *note email: 67.

     表示和操作邮件消息。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/mailbox.py


File: python.info,  Node: Mailbox 对象,  Next: Message 对象,  Up: mailbox --- 操作多种格式的邮箱

5.19.4.1 ‘Mailbox’ 对象
.......................

 -- 類別: mailbox.Mailbox

     一个邮箱，它可以被检视和修改。

     *note Mailbox: cb1. 类定义了一个接口并且它不应被实例化。 而是应该让
     格式专属的子类继承 *note Mailbox: cb1. 并且你的代码应当实例化一个特
     定的子类。

     *note Mailbox: cb1. 接口类似于字典，其中每个小键都有对应的消息。 键
     是由 *note Mailbox: cb1. 实例发出的，它们将由实例来使用并且只对该
     *note Mailbox: cb1. 实例有意义。 键会持续标识一条消息，即使对应的消
     息已被修改，例如被另一条消息所替代。

     可以使用 set 型方法 *note add(): cb0. 将消息添加到 *note Mailbox:
     cb1. 并可以使用 ‘del’ 语句或 set 型方法 *note remove(): 2a56. 和
     *note discard(): 2a57. 将其移除。

     *note Mailbox: cb1. 接口语义在某些值得注意的方面与字典语义有所不同
     。 每次请求消息时，都会基于邮箱的当前状态生成一个新的表示形式（通常
     为 *note Message: cb5. 实例）。 类似地，当向 *note Mailbox: cb1. 实
     例添加消息时，所提供的消息表示形式的内容将被复制。 无论在哪种情况下
     *note Mailbox: cb1. 实例都不会保留对消息表示形式的引用。

     默认的 *note Mailbox: cb1. 迭代器会迭代消息表示形式，而不像默认的字
     典迭代器那样迭代键。 此外，在迭代期间修改邮箱是安全且有明确定义的。
     在创建迭代器之后被添加到邮箱的消息将对该迭代不可见。 在迭代器产出消
     息之前被从邮箱移除的消息将被静默地跳过，但是使用来自迭代器的键也有
     可能导致 *note KeyError: 3e9. 异常，如果对应的消息后来被移除的话。

          警告: 在修改可能同时被其他某个进程修改的邮箱时要非常小心。 用
          于此种任务的最安全邮箱格式是 Maildir；请尽量避免使用 mbox 之类
          的单文件格式进行并发写入。 如果你正在修改一个邮箱，你 `必须' 在
          读取文件中的任何消息或者执行添加或删除消息等修改操作 `之前' 通
          过调用 *note lock(): 2a58. 以及 *note unlock(): 2a59. 方法来锁
          定它。 如果未锁定邮箱则将导致丢失消息或损坏整个邮箱的风险。

     *note Mailbox: cb1. 实例具有下列方法:

      -- 成員函式: add (message)

          将 `message' 添加到邮箱并返回分配给它的键。

          形参 `message' 可以是 *note Message: cb5. 实例、*note
          email.message.Message: 63b. 实例、字符串、字节串或文件类对象（
          应当以二进制模式打开）。 如果 `message' 是适当的格式专属 *note
          Message: cb5. 子类的实例（举例来说，如果它是一个 *note
          mboxMessage: 2929. 实例而这是一个 *note mbox: 2a5a. 实例），将
          使用其格式专属的信息。 在其他情况下，则会使用合理的默认值作为
          格式专属的信息。

          3.2 版更變: 增加了对二进制输入的支持。

      -- 成員函式: remove (key)
      -- 成員函式: __delitem__ (key)
      -- 成員函式: discard (key)

          从邮箱中删除对应于 `key' 的消息。

          当消息不存在时，如果此方法是作为 *note remove(): 2a56. 或
          *note __delitem__(): 2a5b. 调用则会引发 *note KeyError: 3e9. 异
          常，而如果此方法是作为 *note discard(): 2a57. 调用则不会引发异
          常。 如果下层邮箱格式支持来自其他进程的并发修改则 *note
          discard(): 2a57. 的行为可能是更为适合的。

      -- 成員函式: __setitem__ (key, message)

          将 `key' 所对应的消息替换为 `message'。 如果没有与 `key' 所对
          应的消息则会引发 *note KeyError: 3e9. 异常。

          与 *note add(): cb0. 一样，形参 `message' 可以是 *note
          Message: cb5. 实例、*note email.message.Message: 63b. 实例、字
          符串、字节串或文件类对象（应当以二进制模式打开）。 如果
          `message' 是适当的格式专属 *note Message: cb5. 子类的实例（举
          例来说，如果它是一个 *note mboxMessage: 2929. 实例而这是一个
          *note mbox: 2a5a. 实例），将使用其格式专属的信息。 在其他情况
          下，当前与 `key' 所对应的消息的格式专属信息则会保持不变。

      -- 成員函式: iterkeys ()
      -- 成員函式: keys ()

          如果通过 *note iterkeys(): 2a5d. 调用则返回一个迭代所有键的迭
          代器，或者如果通过 *note keys(): 2a5e. 调用则返回一个键列表。

      -- 成員函式: itervalues ()
      -- 成員函式: __iter__ ()
      -- 成員函式: values ()

          如果通过 *note itervalues(): 2a5f. 或 *note __iter__(): 2a60.
          调用则返回一个迭代所有消息的表示形式的迭代器，或者如果通过
          *note values(): 2a61. 调用则返回一个由这些表示形式组成的列表。
          消息会被表示为适当的格式专属 *note Message: cb5. 子类的实例，
          除非当 *note Mailbox: cb1. 实例被初始化时指定了自定义的消息工
          厂函数。

               備註: *note __iter__(): 2a60. 的行为与字典不同，后者是对
               键进行迭代。

      -- 成員函式: iteritems ()
      -- 成員函式: items ()

          如果通过 *note iteritems(): 2a62. 调用则返回一个迭代 (`key',
          `message') 对的迭代器，其中 `key' 为键而 `message' 为消息的表
          示形式，或者如果通过 *note items(): 2a63. 调用则返回一个由这种
          键值对组成的列表。 消息会被表示为适当的格式专属 *note Message:
          cb5. 子类的实例，除非当 *note Mailbox: cb1. 实例被初始化时指定
          了自定义的消息工厂函数。

      -- 成員函式: get (key, default=None)
      -- 成員函式: __getitem__ (key)

          返回对应于 `key' 的消息的表示形式。 当对应的消息不存在时，如果
          通过 *note get(): 2a64. 调用则返回 `default' 而如果通过 *note
          __getitem__(): 2a65. 调用此方法则会引发 *note KeyError: 3e9. 异
          常。 消息会被表示为适当的格式专属 *note Message: cb5. 子类的实
          例，除非当 *note Mailbox: cb1. 实例被初始化时指定了自定义的消
          息工厂函数。

      -- 成員函式: get_message (key)

          将对应于 `key' 的消息的表示形式作为适当的格式专属 *note
          Message: cb5. 子类的实例返回，或者如果对应的消息不存在则会引发
          *note KeyError: 3e9. 异常。

      -- 成員函式: get_bytes (key)

          返回对应于 `key' 的消息的字节表示形式，或者如果对应的消息不存
          在则会引发 *note KeyError: 3e9. 异常。

          3.2 版新加入.

      -- 成員函式: get_string (key)

          返回对应于 `key' 的消息的字符串表示形式，或者如果对应的消息不
          存在则会引发 *note KeyError: 3e9. 异常。 消息是通过 *note
          email.message.Message: 63b. 处理来将其转换为纯 7bit 表示形式的
          。

      -- 成員函式: get_file (key)

          返回对应于 `key' 的消息的文件类表示形式，或者如果对应的消息不
          存在则会引发 *note KeyError: 3e9. 异常。 文件类对象的行为相当
          于以二进制模式打开。 当不再需要此文件时应当将其关闭。

          3.2 版更變: 此文件对象实际上是二进制文件；之前它被不正确地以文
          本模式返回。 并且，此文件类对象现在还支持上下文管理协议：你可
          以使用 *note with: 7da. 语句来自动关闭它。

               備註: 不同于其他消息表示形式，文件类表示形式并不一定独立
               于创建它们的 *note Mailbox: cb1. 实例或下层的邮箱。 每个
               子类都会提供更具体的文档。

      -- 成員函式: __contains__ (key)

          如果 `key' 有对应的消息则返回 ‘True’，否则返回 ‘False’。

      -- 成員函式: __len__ ()

          返回邮箱中消息的数量。

      -- 成員函式: clear ()

          从邮箱中删除所有消息。

      -- 成員函式: pop (key, default=None)

          返回对应于 `key' 的消息的表示形式并删除该消息。 如果对应的消息
          不存在则返回 `default'。 消息会被表示为适当的格式专属 *note
          Message: cb5. 子类的实例，除非当 *note Mailbox: cb1. 实例被初
          始化时指定了自定义的消息工厂函数。

      -- 成員函式: popitem ()

          返回一个任意的 (`key', `message') 对，其中 `key' 为键而
          `message' 为消息的表示形式，并删除对应的消息。 如果邮箱为空，
          则会引发 *note KeyError: 3e9. 异常。 消息会被表示为适当的格式
          专属 *note Message: cb5. 子类的实例，除非当 *note Mailbox:
          cb1. 实例被初始化时指定了自定义的消息工厂函数。

      -- 成員函式: update (arg)

          形参 `arg' 应当是 `key' 到 `message' 的映射或 (`key',
          `message') 对的可迭代对象。 用来更新邮箱以使得对于每个给定的
          `key' 和 `message'，与 `key' 相对应的消息会被设为 `message'，
          就像通过使用 *note __setitem__(): 2a5c. 一样。 类似于 *note
          __setitem__(): 2a5c.，每个 `key' 都必须在邮箱中有一个对应的消
          息否则将会引发 *note KeyError: 3e9. 异常，因此在通常情况下将
          `arg' 设为 *note Mailbox: cb1. 实例是不正确的。

               備註: 与字典不同，关键字参数是不受支持的。

      -- 成員函式: flush ()

          将所有待定的更改写入到文件系统。 对于某些 *note Mailbox: cb1.
          子类来说，更改总是被立即写入因而 *note flush(): 2a6d. 并不会做
          任何事，但您仍然应当养成调用此方法的习惯。

      -- 成員函式: lock ()

          在邮箱上获取一个独占式咨询锁以使其他进程知道不能修改它。 如果
          锁无法被获取则会引发 *note ExternalClashError: 2a6e.。 所使用
          的具体锁机制取决于邮箱的格式。 在对邮箱内容进行任何修改之前你
          应当 `总是' 锁定它。

      -- 成員函式: unlock ()

          释放邮箱上的锁，如果存在的话。

      -- 成員函式: close ()

          刷新邮箱，如果必要则将其解锁。 并关闭所有打开的文件。 对于某些
          *note Mailbox: cb1. 子类来说，此方法并不会做任何事。

* Menu:

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


File: python.info,  Node: Maildir,  Next: mbox,  Up: Mailbox 对象

5.19.4.2 ‘Maildir’
..................

 -- 類別: mailbox.Maildir (dirname, factory=None, create=True)

     *note Mailbox: cb1. 的一个子类，用于 Maildir 格式的邮箱。 形参
     `factory' 是一个可调用对象，它接受一个文件类消息表示形式（其行为相
     当于以二进制模式打开）并返回一个自定义的表示形式。 如果 `factory' 为
     ‘None’，则会使用 *note MaildirMessage: 2a72. 作为默认的消息表示形式
     。 如果 `create' 为 ‘True’，则当邮箱不存在时会创建它。

     如果 `create' 为 ‘True’ 且 `dirname' 路径存在，它将被视为已有的
     maildir 而无需尝试验证其目录布局。

     使用 `dirname' 这个名称而不使用 `path' 是出于历史原因。

     Maildir 是一种基于目录的邮箱格式，它是针对 qmail 邮件传输代理而发明
     的，现在也得到了其他程序的广泛支持。 Maildir 邮箱中的消息存储在一个
     公共目录结构中的单独文件内。 这样的设计允许 Maildir 邮箱被多个彼此
     无关的程序访问和修改而不会导致数据损坏，因此文件锁定操作是不必要的
     。

     Maildir 邮箱包含三个子目录，分别是: ‘tmp’, ‘new’ 和 ‘cur’。 消息会
     不时地在 ‘tmp’ 子目录中创建然后移至 ‘new’ 子目录来结束投递。 后续电
     子邮件客户端可能将消息移至 ‘cur’ 子目录并将有关消息状态的信息存储在
     附带到其文件名的特殊 "info" 小节中。

     Courier 电子邮件传输代理所引入的文件夹风格也是受支持的。 主邮箱中任
     何子目录只要其名称的第一个字符是 ‘'.'’ 就会被视为文件夹。 文件夹名
     称会被 *note Maildir: d70. 表示为不带前缀 ‘'.'’ 的形式。 每个文件夹
     自身都是一个 Maildir 邮箱但不应包含其他文件夹。 逻辑嵌套关系是使用
     ‘'.'’ 来划定层级，例如 "Archived.2005.07"。

          備註: Maildir 规范要求使用在特定消息文件名中使用冒号 (‘':'’)。
          但是，某些操作系统不允许将此字符用于文件名，如果你希望在这些操
          作系统上使用类似 Maildir 的格式，你应当指定改用另一个字符。 叹
          号 (‘'!'’) 是一个受欢迎的选择。 例如:

               import mailbox
               mailbox.Maildir.colon = '!'

          ‘colon’ 属性也可以在每个实例上分别设置。

     *note Maildir: d70. 实例具有 *note Mailbox: cb1. 的所有方法及下列附
     加方法:

      -- 成員函式: list_folders ()

          返回所有文件夹名称的列表。

      -- 成員函式: get_folder (folder)

          返回表示名称为 `folder' 的文件夹的 *note Maildir: d70. 实例。
          如果文件夹不存在则会引发 *note NoSuchMailboxError: 2a75. 异常
          。

      -- 成員函式: add_folder (folder)

          创建名称为 `folder' 的文件夹并返回表示它的 *note Maildir: d70.
          实例。

      -- 成員函式: remove_folder (folder)

          删除名称为 `folder' 的文件夹。 如果文件夹包含任何消息，则将引
          发 *note NotEmptyError: 2a78. 异常且该文件夹将不会被删除。

      -- 成員函式: clean ()

          从邮箱中删除最近 36 小时内未被访问过的临时文件。 Maildir 规范
          要求邮件阅读程序应当时常进行此操作。

     *note Maildir: d70. 所实现的某些 *note Mailbox: cb1. 方法值得进行特
     别的说明:

      -- 成員函式: add (message)
      -- 成員函式: __setitem__ (key, message)
      -- 成員函式: update (arg)

               警告: 这些方法会基于当前进程 ID 来生成唯一文件名。 当使用
               多线程时，可能发生未被检测到的名称冲突并导致邮箱损坏，除
               非是对线程进行协调以避免使用这些方法同时操作同一个邮箱。

      -- 成員函式: flush ()

          对 Maildir 邮箱的所有更改都会立即被应用，所以此方法并不会做任
          何事情。

      -- 成員函式: lock ()
      -- 成員函式: unlock ()

          Maildir 邮箱不支持（或要求）锁定操作，所以此方法并不会做任何事
          情。

      -- 成員函式: close ()

          *note Maildir: d70. 实例不保留任何打开的文件并且下层的邮箱不支
          持锁定操作，所以此方法不会做任何事情。

      -- 成員函式: get_file (key)

          根据主机平台的不同，当返回的文件保持打开状态时可能无法修改或移
          除下层的消息。

也參考
......

Courier 上的 maildir 指南页面(1)

     该格式的规格说明。 描述了用于支持文件夹的通用扩展。

使用 maildir 格式(2)

     Maildir 发明者对它的说明。 包括已更新的名称创建方案和 "info" 语义的
     相关细节。

   ---------- Footnotes ----------

   (1) http://www.courier-mta.org/maildir.html

   (2) https://cr.yp.to/proto/maildir.html


File: python.info,  Node: mbox,  Next: MH,  Prev: Maildir,  Up: Mailbox 对象

5.19.4.3 ‘mbox’
...............

 -- 類別: mailbox.mbox (path, factory=None, create=True)

     *note Mailbox: cb1. 的子类，用于 mbox 格式的邮箱。 形参 `factory' 是
     一个可调用对象，它接受一个文件类消息表示形式（其行为相当于以二进制
     模式打开）并返回一个自定义的表示形式。 如果 `factory' 为 ‘None’，则
     会使用 *note mboxMessage: 2929. 作为默认的消息表示形式。 如果
     `create' 为 ‘True’，则当邮箱不存在时会创建它。

     mbox 格式是在 Unix 系统上存储电子邮件的经典格式。 mbox 邮箱中的所有
     消息都存储在一个单独文件中，每条消息的开头由前五个字符为 "From " 的
     行来指明。

     还有一些 mbox 格式变种对原始格式中发现的缺点做了改进，*note mbox:
     2a5a. 只实现原始格式，有时被称为 `mboxo'。 这意味着当存储消息时
     ‘Content-Length’ 标头如果存在则会被忽略并且消息体中出现于行开头的任
     何 "From " 会被转换为 ">From "，但是当读取消息时 ">From " 则不会被
     转换为 "From "。

     *note mbox: 2a5a. 所实现的某些 *note Mailbox: cb1. 方法值得进行特别
     的说明:

      -- 成員函式: get_file (key)

          在 *note mbox: 2a5a. 实例上调用 ‘flush()’ 或 ‘close()’ 之后再
          使用文件可能产生无法预料的结果或者引发异常。

      -- 成員函式: lock ()
      -- 成員函式: unlock ()

          使用三种锁机制 — dot 锁，以及可能情况下的 ‘flock()’ 和
          ‘lockf()’ 系统调用。

也參考
......

tin 上的 mbox 指南页面(1)

     该格式的规格说明，包括有关锁的详情。

在 Unix 上配置 Netscape Mail: 为何 Content-Length 格式是不好的(2)

     使用原始 mbox 格式而非其变种的一些理由。

"mbox" 是由多个彼此不兼容的邮箱格式构成的家族(3)

     有关 mbox 变种的历史。

   ---------- Footnotes ----------

   (1) http://www.tin.org/bin/man.cgi?section=5&topic=mbox

   (2) https://www.jwz.org/doc/content-length.html

   (3) 
https://www.loc.gov/preservation/digital/formats/fdd/fdd000383.shtml


File: python.info,  Node: MH,  Next: Babyl,  Prev: mbox,  Up: Mailbox 对象

5.19.4.4 ‘MH’
.............

 -- 類別: mailbox.MH (path, factory=None, create=True)

     *note Mailbox: cb1. 的子类，用于 MH 格式的邮箱。 形参 `factory' 是
     一个可调用对象，它接受一个文件类消息表示形式（其行为相当于以二进制
     模式打开）并返回一个自定义的表示形式。 如果 `factory' 为 ‘None’，则
     会使用 *note MHMessage: 2a8a. 作为默认的消息表示形式。 如果
     `create' 为 ‘True’，则当邮箱不存在时会创建它。

     MH 是一种基于目录的邮箱格式，它是针对 MH Message Handling System 电
     子邮件用户代理而发明的。 在 MH 邮箱的每条消息都放在单独文件中。 MH
     邮箱中除了邮件消息还可以包含其他 MH 邮箱 (称为 `文件夹')。 文件夹可
     以无限嵌套。 MH 邮箱还支持 `序列'，这是一种命名列表，用来对消息进行
     逻辑分组而不必将其移入子文件夹。 序列是在每个文件夹中名为
     ‘.mh_sequences’ 的文件内定义的。

     *note MH: 2a89. 类可以操作 MH 邮箱，但它并不试图模拟 ‘mh’ 的所有行
     为。 特别地，它并不会修改 ‘context’ 或 ‘.mh_profile’ 文件也不会受其
     影响，这两个文件是 ‘mh’ 用来存储状态和配置数据的。

     *note MH: 2a89. 实例具有 *note Mailbox: cb1. 的所有方法及下列附加方
     法:

      -- 成員函式: list_folders ()

          返回所有文件夹名称的列表。

      -- 成員函式: get_folder (folder)

          返回表示名称为 `folder' 的文件夹的 *note MH: 2a89. 实例。 如果
          文件夹不存在则会引发 *note NoSuchMailboxError: 2a75. 异常。

      -- 成員函式: add_folder (folder)

          创建名称为 `folder' 的文件夹并返回表示它的 *note MH: 2a89. 实
          例。

      -- 成員函式: remove_folder (folder)

          删除名称为 `folder' 的文件夹。 如果文件夹包含任何消息，则将引
          发 *note NotEmptyError: 2a78. 异常且该文件夹将不会被删除。

      -- 成員函式: get_sequences ()

          返回映射到键列表的序列名称字典。 如果不存在任何序列，则返回空
          字典。

      -- 成員函式: set_sequences (sequences)

          根据由映射到键列表的名称组成的字典 `sequences' 来重新定义邮箱
          中的序列，该字典与 *note get_sequences(): 2a8f. 返回值的形式一
          样。

      -- 成員函式: pack ()

          根据需要重命名邮箱中的消息以消除序号中的空缺。 序列列表中的条
          目会做相应的修改。

               備註: 已发送的键会因此操作而失效并且不应当被继续使用。

     *note MH: 2a89. 所实现的某些 *note Mailbox: cb1. 方法值得进行特别的
     说明:

      -- 成員函式: remove (key)
      -- 成員函式: __delitem__ (key)
      -- 成員函式: discard (key)

          这些方法会立即删除消息。 通过在名称前加缀一个冒号作为消息删除
          标记的 MH 惯例不会被使用。

      -- 成員函式: lock ()
      -- 成員函式: unlock ()

          使用三种锁机制 — dot 锁，以及可能情况下下 ‘flock()’ 和
          ‘lockf()’ 系统调用。 对于 MH 邮箱来说，锁定邮箱意味着锁定
          ‘.mh_sequences’ 文件，并且仅在执行会影响单独消息文件的操作期间
          锁定单独消息文件。

      -- 成員函式: get_file (key)

          根据主机平台的不同，当返回的文件保持打开状态时可能无法移除下层
          的消息。

      -- 成員函式: flush ()

          对 MH 邮箱的所有更改都会立即被应用，所以此方法并不会做任何事情
          。

      -- 成員函式: close ()

          *note MH: 2a89. 实例不保留任何打开的文件，所以此方法等价于
          *note unlock(): 2a96.。

也參考
......

nmh - Message Handling System(1)

     ‘nmh’ 的主页，这是原始 ‘mh’ 的更新版本。

MH & nmh: Email for Users & Programmers(2)

     使用 GPL 许可证的介绍 ‘mh’ 与 ‘nmh’ 的图书，包含有关该邮箱格式的各
     种信息。

   ---------- Footnotes ----------

   (1) http://www.nongnu.org/nmh/

   (2) https://rand-mh.sourceforge.io/book/


File: python.info,  Node: Babyl,  Next: MMDF,  Prev: MH,  Up: Mailbox 对象

5.19.4.5 ‘Babyl’
................

 -- 類別: mailbox.Babyl (path, factory=None, create=True)

     *note Mailbox: cb1. 的子类，用于 Babyl 格式的邮箱。 形参 `factory'
     是一个可调用对象，它接受一个文件类表示形式（其行为相当于以二进制模
     式打开）并返回一个自定义的表示形式。 如果 `factory' 为 ‘None’，则会
     使用 *note BabylMessage: 2a9d. 作为默认的消息表示形式。 如果
     `create' 为 ‘True’，则当邮箱不存在时会创建它。

     Babyl 是 Rmail 电子邮箱用户代理所使用单文件邮箱格式，包括在 Emacs 中
     。 每条消息的开头由一个包含 Control-Underscore (‘'\037'’) 和
     Control-L (‘'\014'’) 这两个字符的行来指明。 消息的结束由下一条消息
     的开头来指明，或者当为最后一条消息时则由一个包含 Control-Underscore
     (‘'\037'’) 字符的行来指明。

     Babyl 邮箱中的消息带有两组标头：原始标头和所谓的可见标头。 可见标头
     通常为原始标头经过重格式化和删减以更易读的子集。 Babyl 邮箱中的每条
     消息都附带了一个 `标签' 列表，即记录消息相关额外信息的短字符串，邮
     箱中所有的用户定义标签列表会存储于 Babyl 的选项部分。

     *note Babyl: 2a9c. 实例具有 *note Mailbox: cb1. 的所有方法及下列附
     加方法:

      -- 成員函式: get_labels ()

          返回邮箱中使用的所有用户定义标签名称的列表。

               備註: 邮箱中存在哪些标签会通过检查实际的消息而非查询
               Babyl 选项部分的标签列表，但 Babyl 选项部分会在邮箱被修改
               时更新。

     *note Babyl: 2a9c. 所实现的某些 *note Mailbox: cb1. 方法使得进行特
     别的说明:

      -- 成員函式: get_file (key)

          在 Babyl 邮箱中，消息的标头并不是与消息体存储在一起的。 要生成
          文件类表示形式，标头和消息体会被一起拷贝到一个 *note
          io.BytesIO: 88a. 实例中，它具有与文件相似的 API。 因此，文件类
          对象实际上独立于下层邮箱，但与字符串表达形式相比并不会更节省内
          存。

      -- 成員函式: lock ()
      -- 成員函式: unlock ()

          使用三种锁机制 — dot 锁，以及可能情况下的 ‘flock()’ 和
          ‘lockf()’ 系统调用。

也參考
......

Format of Version 5 Babyl Files(1)

     Babyl 格式的规格说明。

Reading Mail with Rmail(2)

     Rmail 的帮助手册，包含了有关 Babyl 语义的一些信息。

   ---------- Footnotes ----------

   (1) https://quimby.gnus.org/notes/BABYL

   (2) 
https://www.gnu.org/software/emacs/manual/html_node/emacs/Rmail.html


File: python.info,  Node: MMDF,  Prev: Babyl,  Up: Mailbox 对象

5.19.4.6 ‘MMDF’
...............

 -- 類別: mailbox.MMDF (path, factory=None, create=True)

     *note Mailbox: cb1. 的子类，用于 MMDF 格式的邮箱。 形参 `factory' 是
     一个可调用对象，它接受一个文件类消息表示形式（其行为相当于以二进制
     模式打开）并返回一个自定义的表示形式。 如果 `factory' 为 ‘None’，则
     会使用 *note MMDFMessage: 2aa5. 作为默认的消息表示形式。 如果
     `create' 为 ‘True’，则当邮箱不存在时会创建它。

     MMDF 是一种专用于电子邮件传输代理 Multichannel Memorandum
     Distribution Facility 的单文件邮箱格式。 每条消息使用与 mbox 消息相
     同的形式，但其前后各有包含四个 Control-A (‘'\001'’) 字符的行。 与
     mbox 格式一样，每条消息的开头由一个前五个字符为 "From " 的行来指明
     ，但当存储消息时额外出现的 "From " 不会被转换为 ">From " 因为附加的
     消息分隔符可防止将这些内容误认为是后续消息的开头。

     *note MMDF: 2aa4. 所实现的某些 *note Mailbox: cb1. 方法值得进行特别
     的说明:

      -- 成員函式: get_file (key)

          在 *note MMDF: 2aa4. 实例上调用 ‘flush()’ 或 ‘close()’ 之后再
          使用文件可能产生无法预料的结果或者引发异常。

      -- 成員函式: lock ()
      -- 成員函式: unlock ()

          使用三种锁机制 — dot 锁，以及可能情况下的 ‘flock()’ 和
          ‘lockf()’ 系统调用。

也參考
......

tin 上的 mmdf 指南页面(1)

     MMDF 格式的规格说明，来自新闻阅读器 tin 的文档。

MMDF(2)

     一篇描述 Multichannel Memorandum Distribution Facility 的维基百科文
     章。

   ---------- Footnotes ----------

   (1) http://www.tin.org/bin/man.cgi?section=5&topic=mmdf

   (2) https://en.wikipedia.org/wiki/MMDF


File: python.info,  Node: Message 对象,  Next: 异常<13>,  Prev: Mailbox 对象,  Up: mailbox --- 操作多种格式的邮箱

5.19.4.7 ‘Message’ 对象
.......................

 -- 類別: mailbox.Message (message=None)

     *note email.message: 70. 模块的 *note Message: 63b. 的子类。 *note
     mailbox.Message: cb5. 的子类添加了特定邮箱格式专属的状态和行为。

     如果省略了 `message'，则新实例会以默认的空状态被创建。 如果
     `message' 是一个 *note email.message.Message: 63b. 实例，其内容会被
     拷贝；此外，如果 `message' 是一个 *note Message: cb5. 实例，则任何
     格式专属信息会尽可能地被拷贝。 如果 `message' 是一个字符串、字节串
     或文件，则它应当包含兼容 RFC 2822(1) 的消息，该消息会被读取和解析。
     文档应当以二进制模式打开，但文本模式的文件也会被接受以向下兼容。

     各个子类所提供的格式专属状态和行为各有不同，但总的来说只有那些不仅
     限于特定邮箱的特性才会被支持（虽然这些特性可能专属于特定邮箱格式）
     。 例如，例如，单文件邮箱格式的文件偏移量和基于目录的邮箱格式的文件
     名都不会被保留，因为它们都仅适用于对应的原始邮箱。 但消息是否已被用
     户读取或标记为重要等状态则会被保留，因为它们适用于消息本身。

     不要求用 *note Message: cb5. 实例来表示使用 *note Mailbox: cb1. 实
     例所提取到的消息。 在某些情况下，生成 *note Message: cb5. 表示形式
     所需的时间和内存空间可能是不可接受的。 对于此类情况，*note Mailbox:
     cb1. 实例还提供了字符串和文件类表示形式，并可在初始化 *note
     Mailbox: cb1. 实例时指定自定义的消息工厂函数。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2822.html


File: python.info,  Node: MaildirMessage,  Next: mboxMessage,  Up: Message 对象

5.19.4.8 ‘MaildirMessage’
.........................

 -- 類別: mailbox.MaildirMessage (message=None)

     具有 Maildir 专属行为的消息。 形参 `message' 的含义与 *note
     Message: cb5. 构造器一致。

     通常，邮件用户代理应用程序会在用户第一次打开并关闭邮箱之后将 ‘new’
     子目录中的所有消息移至 ‘cur’ 子目录，将这些消息记录为旧消息，无论它
     们是否真的已被阅读。 ‘cur’ 下的每条消息都有一个 "info" 部分被添加到
     其文件名中以存储有关其状态的信息。 （某些邮件阅读器还会把 "info" 部
     分也添加到 ‘new’ 下的消息中。） "info" 部分可以采用两种形式之一：它
     可能包含 "2," 后面跟一个经标准化的旗标列表（例如 "2,FR"）或者它可能
     包含 "1," 后面跟所谓的实验性信息。 Maildir 消息的标准旗标如下:

     旗标       意义          解释
                              
     --------------------------------------------------------------
                              
     D          草稿          正在撰写中
                              
                              
     F          已标记        已被标记为重要
                              
                              
     P          已检视        转发，重新发送或退回
                              
                              
     R          已回复        回复给
                              
                              
     S          已查看        已阅读
                              
                              
     T          已删除        标记为可被删除
                              

     *note MaildirMessage: 2a72. 实例提供以下方法：

      -- 成員函式: get_subdir ()

          返回 "new" (如果消息应当被存储在 ‘new’ 子目录下) 或者 "cur" (如
          果消息应当被存储在 ‘cur’ 子目录下)。

               備註: 消息通常会在其邮箱被访问后被从 ‘new’ 移至 ‘cur’，无
               论该消息是否已被阅读。 如果 msg.get_flags()‘‘ 中的 ‘"S" 为
               ``True’ 则说明消息 ‘msg’ 已被阅读。

      -- 成員函式: set_subdir (subdir)

          设置消息应当被存储到的子目录。 形参 `subdir' 必须为 "new" 或
          "cur"。

      -- 成員函式: get_flags ()

          返回一个指明当前所设旗标的字符串。 如果消息符合标准的 Maildir
          格式，则结果为零或按字母顺序各自出现一次的 ‘'D'’, ‘'F'’,
          ‘'P'’, ‘'R'’, ‘'S'’ 和 ‘'T'’ 的拼接。 如果未设任何旗标或者如果
          "info" 包含实验性语义则返回空字符串。

      -- 成員函式: set_flags (flags)

          设置由 `flags' 所指定的旗标并重置所有其它旗标。

      -- 成員函式: add_flag (flag)

          设置由 `flag' 所指明的旗标而不改变其他旗标。 要一次性添加一个
          以上的旗标，`flag' 可以为包含一个以上字符的字符串。 当前
          "info" 会被覆盖，无论它是否只包含实验性信息而非旗标。

      -- 成員函式: remove_flag (flag)

          重置由 `flag' 所指明的旗标而不改变其他旗标。 要一次性移除一个
          以上的旗标，`flag' 可以为包含一个以上字符的字符串。 如果
          "info" 包含实验性信息而非旗标，则当前的 "info" 不会被修改。

      -- 成員函式: get_date ()

          以表示 Unix 纪元秒数的浮点数形式返回消息的发送日期。

      -- 成員函式: set_date (date)

          将消息的发送日期设为 `date'，一个表示 Unix 纪元秒数的浮点数。

      -- 成員函式: get_info ()

          返回一个包含消息的 "info" 的字符串。 这适用于访问和修改实验性
          的 "info" (即不是由旗标组成的列表)。

      -- 成員函式: set_info (info)

          将 "info" 设为 `info'，这应当是一个字符串。

当一个 *note MaildirMessage: 2a72. 实例基于 *note mboxMessage: 2929. 或
*note MMDFMessage: 2aa5. 实例被创建时，将会忽略 ‘Status’ 和 ‘X-Status’ 标
头并进行下列转换:

结果状态                 *note mboxMessage: 2929. 或
                         *note MMDFMessage: 2aa5. 状态
                         
----------------------------------------------------------------------------
                         
"cur" 子目录             O 旗标
                         
                         
F 旗标                   F 旗标
                         
                         
R 旗标                   A 旗标
                         
                         
S 旗标                   R 旗标
                         
                         
T 旗标                   D 旗标
                         

当一个 *note MaildirMessage: 2a72. 实例基于 *note MHMessage: 2a8a. 实例
被创建时，将进行下列转换:

结果状态                            *note MHMessage: 2a8a. 状态
                                    
-------------------------------------------------------------------
                                    
"cur" 子目录                        "unseen" 序列
                                    
                                    
"cur" 子目录和 S 旗标               非 "unseen" 序列
                                    
                                    
F 旗标                              "flagged" 序列
                                    
                                    
R 旗标                              "replied" 序列
                                    

当一个 *note MaildirMessage: 2a72. 实例基于 *note BabylMessage: 2a9d. 实
例被创建时，将进行下列转换:

结果状态                            *note BabylMessage: 2a9d. 状态
                                    
------------------------------------------------------------------------
                                    
"cur" 子目录                        "unseen" 标签
                                    
                                    
"cur" 子目录和 S 旗标               非 "unseen" 标签
                                    
                                    
P 旗标                              "forwarded" 或 "resent" 标签
                                    
                                    
R 旗标                              "answered" 标签
                                    
                                    
T 旗标                              "deleted" 标签
                                    


File: python.info,  Node: mboxMessage,  Next: MHMessage,  Prev: MaildirMessage,  Up: Message 对象

5.19.4.9 ‘mboxMessage’
......................

 -- 類別: mailbox.mboxMessage (message=None)

     具有 mbox 专属行为的消息。 形参 `message' 的含义与 *note Message:
     cb5. 构造器一致。

     mbox 邮箱中的消息会一起存储在单个文件中。 发件人的信封地址和发送时
     间通常存储在指明每条消息的起始的以 "From " 打头的行中，不过在 mbox
     的各种实现之间此数据的确切格式具有相当大的差异。 指明消息状态的各种
     旗标，例如是否已读或标记为重要等等通常存储在 ‘Status’ 和 ‘X-Status’
     标头中。

     传统的 mbox 消息旗标如下:

     旗标       意义           解释
                               
     ---------------------------------------------------------------
                               
     R          已阅读         已阅读
                               
                               
     O          旧消息         之前已经过 MUA 检测
                               
                               
     D          已删除         标记为可被删除
                               
                               
     F          已标记         已被标记为重要
                               
                               
     A          已回复         回复给
                               

     "R" 和 "O" 旗标存储在 ‘Status’ 标头中，而 "D", "F" 和 "A" 旗标存储
     在 ‘X-Status’ 标头中。 旗标和标头通常会按上述顺序显示。

     *note mboxMessage: 2929. 实例提供了下列方法:

      -- 成員函式: get_from ()

          返回一个表示在 mbox 邮箱中标记消息起始的 "From " 行的字符串。
          开头的 "From " 和末尾的换行符会被去除。

      -- 成員函式: set_from (from_, time_=None)

          将 "From " 行设为 `from_'，这应当被指定为不带开头的 "From " 或
          末尾的换行符。 为方便起见，可以指定 `time_' 并将经过适当的格式
          化再添加到 `from_'。 如果指定了 `time_'，它应当是一个 *note
          time.struct_time: 690. 实例，适合传入 *note time.strftime():
          c37. 的元组或者 ‘True’ (以使用 *note time.gmtime(): c11.)。

      -- 成員函式: get_flags ()

          返回一个指明当前所设旗标的字符串。 如果消息符合规范格式，则结
          果为零或各自出现一次的 ‘'R'’, ‘'O'’, ‘'D'’, ‘'F'’ 和 ‘'A'’ 按
          上述顺序的拼接。

      -- 成員函式: set_flags (flags)

          设置由 `flags' 所指明的旗标并重启所有其他旗标。 形参 `flags' 应
          当为零或各自出现多次的 ‘'R'’, ‘'O'’, ‘'D'’, ‘'F'’ 和 ‘'A'’ 按
          任意顺序的拼接。

      -- 成員函式: add_flag (flag)

          设置由 `flag' 所指明的旗标而不改变其他旗标。 要一次性添加一个
          以上的旗标，`flag' 可以为包含一个以上字符的字符串。

      -- 成員函式: remove_flag (flag)

          重置由 `flag' 所指明的旗标而不改变其他旗标。 要一次性移除一个
          以上的旗标，`flag' 可以为包含一个以上字符的字符串。

当一个 *note mboxMessage: 2929. 实例基于 *note MaildirMessage: 2a72. 实
例被创建时，"From " 行会基于 *note MaildirMessage: 2a72. 实例的发送时间
被生成，并进行下列转换:

结果状态              *note MaildirMessage: 2a72. 状态
                      
----------------------------------------------------------
                      
R 旗标                S 旗标
                      
                      
O 旗标                "cur" 子目录
                      
                      
D 旗标                T 旗标
                      
                      
F 旗标                F 旗标
                      
                      
A 旗标                R 旗标
                      

当一个 *note mboxMessage: 2929. 实例基于 *note MHMessage: 2a8a. 实例被创
建时，将进行下列转换:

结果状态                *note MHMessage: 2a8a. 状态
                        
-------------------------------------------------------
                        
R 旗标 和 O 旗标        非 "unseen" 序列
                        
                        
O 旗标                  "unseen" 序列
                        
                        
F 旗标                  "flagged" 序列
                        
                        
A 旗标                  "replied" 序列
                        

当一个 *note mboxMessage: 2929. 实例基于 *note BabylMessage: 2a9d. 实例
被创建时，将进行下列转换:

结果状态                *note BabylMessage: 2a9d. 状态
                        
----------------------------------------------------------
                        
R 旗标 和 O 旗标        非 "unseen" 标签
                        
                        
O 旗标                  "unseen" 标签
                        
                        
D 旗标                  "deleted" 标签
                        
                        
A 旗标                  "answered" 标签
                        

当一个 *note Message: cb5. 实例基于 *note MMDFMessage: 2aa5. 实例被创建
时，"From " 行会被拷贝并直接对应所有旗标。

结果状态              *note MMDFMessage: 2aa5. 状态
                      
-------------------------------------------------------
                      
R 旗标                R 旗标
                      
                      
O 旗标                O 旗标
                      
                      
D 旗标                D 旗标
                      
                      
F 旗标                F 旗标
                      
                      
A 旗标                A 旗标
                      


File: python.info,  Node: MHMessage,  Next: BabylMessage,  Prev: mboxMessage,  Up: Message 对象

5.19.4.10 ‘MHMessage’
.....................

 -- 類別: mailbox.MHMessage (message=None)

     具有 MH 专属行为的消息。 形参 `message' 的含义与 *note Message:
     cb5. 构造器一致。

     MH 消息不支持传统意义上的标记或旗标，但它们支持序列，即对任意消息的
     逻辑分组。 某些邮件阅读程序 (但不包括标准 ‘mh’ 和 ‘nmh’) 以与其他格
     式使用旗标类似的方式来使用序列，如下所示:

     序列           解释
                    
     --------------------------------------------------------------
                    
     unseen         未阅读，但之前已经过 MUA 检测
                    
                    
     已回复         回复给
                    
                    
     已标记         已被标记为重要
                    

     *note MHMessage: 2a8a. 实例提供了下列方法:

      -- 成員函式: get_sequences ()

          返回一个包含此消息的序列的名称的列表。

      -- 成員函式: set_sequences (sequences)

          设置包含此消息的序列的列表。

      -- 成員函式: add_sequence (sequence)

          将 `sequence' 添加到包含此消息的序列的列表。

      -- 成員函式: remove_sequence (sequence)

          将 `sequence' 从包含此消息的序列的列表中移除。

当一个 *note MHMessage: 2a8a. 实例基于 *note MaildirMessage: 2a72. 实例
被创建时，将进行下列转换:

结果状态                 *note MaildirMessage: 2a72. 状态
                         
-------------------------------------------------------------
                         
"unseen" 序列            非 S 旗标
                         
                         
"replied" 序列           R 旗标
                         
                         
"flagged" 序列           F 旗标
                         

当一个 *note MHMessage: 2a8a. 实例基于 *note mboxMessage: 2929. 或 *note
MMDFMessage: 2aa5. 实例被创建时，将会忽略 ‘Status’ 和 ‘X-Status’ 标头并
进行下列转换:

结果状态                 *note mboxMessage: 2929. 或
                         *note MMDFMessage: 2aa5. 状态
                         
----------------------------------------------------------------------------
                         
"unseen" 序列            非 R 旗标
                         
                         
"replied" 序列           A 旗标
                         
                         
"flagged" 序列           F 旗标
                         

当一个 *note MHMessage: 2a8a. 实例基于 *note BabylMessage: 2a9d. 实例被
创建时，将进入下列转换:

结果状态                 *note BabylMessage: 2a9d. 状态
                         
-----------------------------------------------------------
                         
"unseen" 序列            "unseen" 标签
                         
                         
"replied" 序列           "answered" 标签
                         


File: python.info,  Node: BabylMessage,  Next: MMDFMessage,  Prev: MHMessage,  Up: Message 对象

5.19.4.11 ‘BabylMessage’
........................

 -- 類別: mailbox.BabylMessage (message=None)

     具有 Babyl 专属行为的消息。 形参 `message' 的含义与 *note Message:
     cb5. 构造器一致。

     某些消息标签被称为 `属性'，根据惯例被定义为具有特殊的含义。 这些属
     性如下所示:

     标签            解释
                     
     ---------------------------------------------------------------
                     
     unseen          未阅读，但之前已经过 MUA 检测
                     
                     
     deleted         标记为可被删除
                     
                     
     filed           复制到另一个文件或邮箱
                     
                     
     answered        回复给
                     
                     
     forwarded       已转发
                     
                     
     edited          已被用户修改
                     
                     
     resent          已重发
                     

     默认情况下，Rmail 只显示可见标头。 不过 *note BabylMessage: 2a9d. 类
     会使用原始标头因为它们更完整。 如果需要可以显式地访问可见标头。

     *note BabylMessage: 2a9d. 实例提供了下列方法:

      -- 成員函式: get_labels ()

          返回邮件上的标签列表。

      -- 成員函式: set_labels (labels)

          将消息上的标签列表设置为 `labels' 。

      -- 成員函式: add_label (label)

          将 `label' 添加到消息上的标签列表中。

      -- 成員函式: remove_label (label)

          从消息上的标签列表中删除 `label' 。

      -- 成員函式: get_visible ()

          返回一个 *note Message: cb5. 实例，其标头为消息的可见标头而其
          消息体为空。

      -- 成員函式: set_visible (visible)

          将消息的可见标头设为与 `message' 中的标头一致。 形参 `visible'
          应当是一个 *note Message: cb5. 实例，*note
          email.message.Message: 63b. 实例，字符串或文件类对象（且应当以
          文本模式打开）。

      -- 成員函式: update_visible ()

          当一个 *note BabylMessage: 2a9d. 实例的原始标头被修改时，可见
          标头不会自动进行对应修改。 此方法将按以下方式更新可见标头：每
          个具有对应原始标头的可见标头会被设为原始标头的值，每个没有对应
          原始标头的可见标头会被移除，而任何存在于原始标头但不存在于可见
          标头中的 ‘Date’, ‘From’, ‘Reply-To’, ‘To’, ‘CC’ 和 ‘Subject’ 会
          被添加至可见标头。

当一个 *note BabylMessage: 2a9d. 实例基于 *note MaildirMessage: 2a72. 实
例被创建时，将进行下列转换:

结果状态                *note MaildirMessage: 2a72. 状态
                        
------------------------------------------------------------
                        
"unseen" 标签           非 S 旗标
                        
                        
"deleted" 标签          T 旗标
                        
                        
"answered" 标签         R 旗标
                        
                        
"forwarded" 标签        P 旗标
                        

当一个 *note BabylMessage: 2a9d. 实例基于 *note mboxMessage: 2929. 或
*note MMDFMessage: 2aa5. 实例被创建时，将会忽略 ‘Status’ 和 ‘X-Status’ 标
头并进入下列转换:

结果状态               *note mboxMessage: 2929. 或
                       *note MMDFMessage: 2aa5. 状态
                       
--------------------------------------------------------------------------
                       
"unseen" 标签          非 R 旗标
                       
                       
"deleted" 标签         D 旗标
                       
                       
"answered" 标签        A 旗标
                       

当一个 *note BabylMessage: 2a9d. 实例基于 *note MHMessage: 2a8a. 实例被
创建时，将进入下列转换:

结果状态               *note MHMessage: 2a8a. 状态
                       
------------------------------------------------------
                       
"unseen" 标签          "unseen" 序列
                       
                       
"answered" 标签        "replied" 序列
                       


File: python.info,  Node: MMDFMessage,  Prev: BabylMessage,  Up: Message 对象

5.19.4.12 ‘MMDFMessage’
.......................

 -- 類別: mailbox.MMDFMessage (message=None)

     具有 MMDF 专属行为的消息。 形参 `message' 的含义与 *note Message:
     cb5. 构造器一致。

     与 mbox 邮箱中的消息类似，MMDF 消息会与将发件人的地址和发送日期作为
     以 "From " 打头的初始行一起存储。 同样地，指明消息状态的旗标通常存
     储在 ‘Status’ 和 ‘X-Status’ 标头中。

     传统的 MMDF 消息旗标与 mbox 消息的类似，如下所示:

     旗标       意义           解释
                               
     ---------------------------------------------------------------
                               
     R          已阅读         已阅读
                               
                               
     O          旧消息         之前已经过 MUA 检测
                               
                               
     D          已删除         标记为可被删除
                               
                               
     F          已标记         已被标记为重要
                               
                               
     A          已回复         回复给
                               

     "R" 和 "O" 旗标存储在 ‘Status’ 标头中，而 "D", "F" 和 "A" 旗标存储
     在 ‘X-Status’ 标头中。 旗标和标头通常会按上述顺序显示。

     *note MMDFMessage: 2aa5. 实例提供了下列方法，与 *note mboxMessage:
     2929. 所提供的类似:

      -- 成員函式: get_from ()

          返回一个表示在 mbox 邮箱中标记消息起始的 "From " 行的字符串。
          开头的 "From " 和末尾的换行符会被去除。

      -- 成員函式: set_from (from_, time_=None)

          将 "From " 行设为 `from_'，这应当被指定为不带开头的 "From " 或
          末尾的换行符。 为方便起见，可以指定 `time_' 并将经过适当的格式
          化再添加到 `from_'。 如果指定了 `time_'，它应当是一个 *note
          time.struct_time: 690. 实例，适合传入 *note time.strftime():
          c37. 的元组或者 ‘True’ (以使用 *note time.gmtime(): c11.)。

      -- 成員函式: get_flags ()

          返回一个指明当前所设旗标的字符串。 如果消息符合规范格式，则结
          果为零或各自出现一次的 ‘'R'’, ‘'O'’, ‘'D'’, ‘'F'’ 和 ‘'A'’ 按
          上述顺序的拼接。

      -- 成員函式: set_flags (flags)

          设置由 `flags' 所指明的旗标并重启所有其他旗标。 形参 `flags' 应
          当为零或各自出现多次的 ‘'R'’, ‘'O'’, ‘'D'’, ‘'F'’ 和 ‘'A'’ 按
          任意顺序的拼接。

      -- 成員函式: add_flag (flag)

          设置由 `flag' 所指明的旗标而不改变其他旗标。 要一次性添加一个
          以上的旗标，`flag' 可以为包含一个以上字符的字符串。

      -- 成員函式: remove_flag (flag)

          重置由 `flag' 所指明的旗标而不改变其他旗标。 要一次性移除一个
          以上的旗标，`flag' 可以为包含一个以上字符的字符串。

当一个 *note MMDFMessage: 2aa5. 实例基于 *note MaildirMessage: 2a72. 实
例被创建时，"From " 行会基于 *note MaildirMessage: 2a72. 实例的发送日期
被生成，并进入下列转换:

结果状态              *note MaildirMessage: 2a72. 状态
                      
----------------------------------------------------------
                      
R 旗标                S 旗标
                      
                      
O 旗标                "cur" 子目录
                      
                      
D 旗标                T 旗标
                      
                      
F 旗标                F 旗标
                      
                      
A 旗标                R 旗标
                      

当一个 *note MMDFMessage: 2aa5. 实例基于 *note MHMessage: 2a8a. 实例被创
建时，将进行下列转换:

结果状态                *note MHMessage: 2a8a. 状态
                        
-------------------------------------------------------
                        
R 旗标 和 O 旗标        非 "unseen" 序列
                        
                        
O 旗标                  "unseen" 序列
                        
                        
F 旗标                  "flagged" 序列
                        
                        
A 旗标                  "replied" 序列
                        

当一个 *note MMDFMessage: 2aa5. 实例基于 *note BabylMessage: 2a9d. 实例
被创建时，将进行下列转换:

结果状态                *note BabylMessage: 2a9d. 状态
                        
----------------------------------------------------------
                        
R 旗标 和 O 旗标        非 "unseen" 标签
                        
                        
O 旗标                  "unseen" 标签
                        
                        
D 旗标                  "deleted" 标签
                        
                        
A 旗标                  "answered" 标签
                        

当一个 *note MMDFMessage: 2aa5. 实例基于 *note mboxMessage: 2929. 实例被
创建时，"From " 行会被拷贝并直接对应所有旗标:

结果状态              *note mboxMessage: 2929. 状态
                      
-------------------------------------------------------
                      
R 旗标                R 旗标
                      
                      
O 旗标                O 旗标
                      
                      
D 旗标                D 旗标
                      
                      
F 旗标                F 旗标
                      
                      
A 旗标                A 旗标
                      


File: python.info,  Node: 异常<13>,  Next: 示例<27>,  Prev: Message 对象,  Up: mailbox --- 操作多种格式的邮箱

5.19.4.13 异常
..............

*note mailbox: ae. 模块中定义了下列异常类:

 -- 例外: mailbox.Error

     所有其他模块专属异常的基类。

 -- 例外: mailbox.NoSuchMailboxError

     在期望获得一个邮箱但未找到时被引发，例如当使用不存在的路径来实例化
     一个 *note Mailbox: cb1. 子类时 (且将 `create' 形参设为 ‘False’)，
     或是当打开一个不存在的路径时。

 -- 例外: mailbox.NotEmptyError

     在期望一个邮箱为空但不为空时被引发，例如当删除一个包含消息的文件夹
     时。

 -- 例外: mailbox.ExternalClashError

     在某些邮箱相关条件超出了程序控制范围导致其无法继续运行时被引发，例
     如当要获取的锁已被另一个程序获取时，或是当要生成的唯一性文件名已存
     在时。

 -- 例外: mailbox.FormatError

     在某个文件中的数据无法被解析时被引发，例如当一个 *note MH: 2a89. 实
     例尝试读取已损坏的 ‘.mh_sequences’ 文件时。


File: python.info,  Node: 示例<27>,  Prev: 异常<13>,  Up: mailbox --- 操作多种格式的邮箱

5.19.4.14 示例
..............

一个打印指定邮箱中所有消息的主题的简单示例:

     import mailbox
     for message in mailbox.mbox('~/mbox'):
         subject = message['subject']       # Could possibly be None.
         if subject and 'python' in subject.lower():
             print(subject)

要将所有邮件从 Babyl 邮箱拷贝到 MH 邮箱，请转换所有可转换的格式专属信息:

     import mailbox
     destination = mailbox.MH('~/Mail')
     destination.lock()
     for message in mailbox.Babyl('~/RMAIL'):
         destination.add(mailbox.MHMessage(message))
     destination.flush()
     destination.unlock()

这个示例将来自多个邮件列表的邮件分类放入不同的邮箱，小心避免由于其他程序
的并发修改导致的邮件损坏，由于程序中断导致的邮件丢失，或是由于邮箱中消息
格式错误导致的意外终止:

     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()


File: python.info,  Node: mimetypes --- 映射文件名到 MIME 类型,  Next: base64 —— Base16、Base32、Base64、Base85 資料編碼,  Prev: mailbox --- 操作多种格式的邮箱,  Up: 互联网数据处理

5.19.5 ‘mimetypes’ — 映射文件名到 MIME 类型
-------------------------------------------

`源代码:' Lib/mimetypes.py(1)

__________________________________________________________________

*note mimetypes: b2. 模块可以在文件名或 URL 和关联到文件扩展名的 MIME 类
型之间执行转换。 所提供的转换包括从文件名到 MIME 类型和从 MIME 类型到文
件扩展名；后一种转换不支持编码格式。

该模块提供了一个类和一些便捷函数。 这些函数是该模块通常的接口，但某些应
用程序可能也会希望使用类。

下列函数提供了此模块的主要接口。 如果此模块尚未被初始化，它们将会调用
*note init(): 10a2.，如果它们依赖于 *note init(): 10a2. 所设置的信息的话
。

 -- 函式: mimetypes.guess_type (url, strict=True)

     根据 `url' 给出的文件名、路径或 URL 来猜测文件的类型，URL 可以为字
     符串或 *note path-like object: 472.。

     返回值是一个元组 ‘(type, encoding)’ 其中 `type' 在无法猜测（后缀不
     存在或者未知）时为 ‘None’，或者为 ‘'type/subtype'’ 形式的字符串，可
     以作为 MIME ‘content-type’ 标头。

     `encoding' 在无编码格式时为 ‘None’，或者为程序所用的编码格式 (例如
     ‘compress’ 或 ‘gzip’)。 它可以作为 ‘Content-Encoding’ 标头，但 `不
     可' 作为 ‘Content-Transfer-Encoding’ 标头。 映射是表格驱动的。 编码
     格式前缀对大小写敏感；类型前缀会先以大小写敏感方式检测再以大小写不
     敏感方式检测。

     可选的 `strict' 参数是一个旗标，指明要将已知 MIME 类型限制在 IANA 已
     注册(2) 的官方类型之内。 当 `strict' 为 ‘True’ 时（默认值），则仅支
     持 IANA 类型；当 `strict' 为 ‘False’ 时，则还支持某些附加的非标准但
     常用的 MIME 类型。

     3.8 版更變: 增加了 *note path-like object: 472. 作为 url 的支持。

 -- 函式: mimetypes.guess_all_extensions (type, strict=True)

     根据由 `type' 给出的文件 MIME 类型猜测其扩展名。 返回值是由所有可能
     的文件扩展名组成的字符串列表，包括开头的点号 (‘'.'’)。 这些扩展名不
     保证能关联到任何特定的数据流，但是将会由 *note guess_type(): 10a1.
     映射到 MIME 类型 `type'。

     可选的 `strict' 参数具有与 *note guess_type(): 10a1. 函数一致的含义
     。

 -- 函式: mimetypes.guess_extension (type, strict=True)

     根据由 `type' 给出的文件 MIME 类型猜测其扩展名。 返回值是一个表示文
     件扩展名的字符串，包括开头的点号 (‘'.'’)。 该扩展名不保证能关联到任
     何特定的数据流，但是将会由 *note guess_type(): 10a1. 映射到 MIME 类
     型 `type'。 如果不能猜测出 `type' 的扩展名，则将返回 ‘None’。

     可选的 `strict' 参数具有与 *note guess_type(): 10a1. 函数一致的含义
     。

有一些附加函数和数据项可被用于控制此模块的行为。

 -- 函式: mimetypes.init (files=None)

     初始化内部数据结构。 `files' 如果给出则必须是一个文件名序列，它应当
     被用于协助默认的类型映射。 如果省略则要使用的文件名会从 *note
     knownfiles: 2ade. 中获取； 在 Windows 上，将会载入当前注册表设置。
     在 `files' 或 *note knownfiles: 2ade. 中指定的每个文件名的优先级将
     高于在它之前的文件名。 *note init(): 10a2. 允许被重复调用。

     为 `files' 指定一个空列表将防止应用系统默认选项：将只保留来自内置列
     表的常用值。

     如果 `files' 为 ‘None’ 则内部数据结构会完全重建为其初始默认值。 这
     是一个稳定操作并将在多次调用时产生相同的结果。

     3.2 版更變: 在之前版本中，Windows 注册表设置会被忽略。

 -- 函式: mimetypes.read_mime_types (filename)

     载入在文件 `filename' 中给定的类型映射，如果文件存在的话。 返回的类
     型映射会是一个字典，其中的键值对为文件扩展名包括开头的点号 (‘'.'’)
     与 ‘'type/subtype'’ 形式的字符串。 如果文件 `filename' 不存在或无法
     被读取，则返回 ‘None’。

 -- 函式: mimetypes.add_type (type, ext, strict=True)

     添加一个从 MIME 类型 `type' 到扩展名 `ext' 的映射。 当扩展名已知时
     ，新类型将替代旧类型。 当类型已知时，扩展名将被添加到已知扩展名列表
     。

     当 `strict' 为 ‘True’ 时（默认值），映射将被添加到官方 MIME 类型，
     否则添加到非标准类型。

 -- Data: mimetypes.inited

     指明全局数据结构是否已被初始化的旗标。 这会由 *note init(): 10a2. 设
     为 ‘True’。

 -- Data: mimetypes.knownfiles

     通常安装的类型映射文件名列表。 这些文件一般被命名为 ‘mime.types’ 并
     会由不同的包安装在不同的位置。

 -- Data: mimetypes.suffix_map

     将后缀映射到其他后缀的字典。 它被用来允许识别已编码的文件，其编码格
     式和类型是由相同的扩展名来指明的。 例如，‘.tgz’ 扩展名被映射到
     ‘.tar.gz’ 以允许编码格式和类型被分别识别。

 -- Data: mimetypes.encodings_map

     映射文件扩展名到编码格式类型的字典。

 -- Data: mimetypes.types_map

     映射文件扩展名到 MIME 类型的字典。

 -- Data: mimetypes.common_types

     映射文件扩展名到非标准但常见的 MIME 类型的字典。

此模块一个使用示例:

     >>> 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'

* Menu:

* MimeTypes 对象::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/mimetypes.py

   (2) https://www.iana.org/assignments/media-types/media-types.xhtml


File: python.info,  Node: MimeTypes 对象,  Up: mimetypes --- 映射文件名到 MIME 类型

5.19.5.1 MimeTypes 对象
.......................

*note MimeTypes: 2ae7. 类可以被用于那些需要多个 MIME 类型数据库的应用程
序；它提供了与 *note mimetypes: b2. 模块所提供的类似接口。

 -- 類別: mimetypes.MimeTypes (filenames=(), strict=True)

     这个类表示 MIME 类型数据库。 默认情况下，它提供了对与此模块其余部分
     一致的数据库的访问权限。 这个初始数据库是此模块所提供数据库的一个副
     本，并可以通过使用 *note read(): 2ae8. 或 *note readfp(): 2ae9. 方
     法将附加的 ‘mime.types’ 样式文载入到数据库中来进行扩展。 如果不需要
     默认数据的话这个映射字典也可以在载入附加数据之前先被清空。

     可选的 `filenames' 形参可被用来让附加文件被载入到默认数据库“之上”。

      -- 屬性: suffix_map

          将后缀映射到其他后缀的字典。 它被用来允许识别已编码的文件，其
          编码格式和类型是由相同的扩展名来指明的。 例如，‘.tgz’ 扩展名被
          映射到 ‘.tar.gz’ 以允许编码格式和类型被分别识别。 这是在模块中
          定义的全局 *note suffix_map: 2ae1. 的一个副本。

      -- 屬性: encodings_map

          映射文件扩展名到编码格式类型的字典。 这是在模块中定义的全局
          *note encodings_map: 2ae2. 的一个副本。

      -- 屬性: types_map

          包含两个字典的元组，将文件扩展名映射到 MIME 类型：第一个字典针
          对非标准类型而第二个字典针对标准类型。 它们会由 *note
          common_types: 2ae4. 和 *note types_map: 2ae3. 来初始化。

      -- 屬性: types_map_inv

          包含两个字典的元组，将 MIME 类型映射到文件扩展名列表：第一个字
          典针对非标准类型而第二个字典针对标准类型。 它们会由 *note
          common_types: 2ae4. 和 *note types_map: 2ae3. 来初始化。

      -- 成員函式: guess_extension (type, strict=True)

          类似于 *note guess_extension(): 2add. 函数，使用存储的表作为对
          象的一部分。

      -- 成員函式: guess_type (url, strict=True)

          类似于 *note guess_type(): 10a1. 函数，使用存储的表作为对象的
          一部分。

      -- 成員函式: guess_all_extensions (type, strict=True)

          类似于 *note guess_all_extensions(): f6f. 函数，使用存储的表作
          为对象的一部分。

      -- 成員函式: read (filename, strict=True)

          从名称为 `filename' 的文件载入 MIME 信息。 此方法使用 *note
          readfp(): 2ae9. 来解析文件。

          如果 `strict' 为 ‘True’，信息将被添加到标准类型列表，否则添加
          到非标准类型列表。

      -- 成員函式: readfp (fp, strict=True)

          从打开的文件 `fp' 载入 MIME 类型信息。 文件必须具有标准
          ‘mime.types’ 文件的格式。

          如果 `strict' 为 ‘True’，信息将被添加到标准类型列表，否则添加
          到非标准类型列表。

      -- 成員函式: read_windows_registry (strict=True)

          从 Windows 注册表载入 MIME 类型信息。

          *note 可用性: 1491.: Windows。

          如果 `strict' 为 ‘True’，信息将被添加到标准类型列表，否则添加
          到非标准类型列表。

          3.2 版新加入.


File: python.info,  Node: base64 —— Base16、Base32、Base64、Base85 資料編碼,  Next: binhex --- 对binhex4文件进行编码和解码,  Prev: mimetypes --- 映射文件名到 MIME 类型,  Up: 互联网数据处理

5.19.6 ‘base64’ —— Base16、Base32、Base64、Base85 資料編碼
----------------------------------------------------------

`源代码：' Lib/base64.py(1)

__________________________________________________________________

這個模組提供將二進位資料編碼成可顯示 ASCII 字元以及解碼回原始資料的功能
，包括了 RFC 3548(2)中的 Base16、Base32、Base64 等編碼方式，以及標準
Ascii85、Base85 編碼等。

RFC 3548(3)標準編碼可以使電子郵件、URL，或是 HTTP POST 內容等傳輸管道安
全地傳遞資料。這些編碼演算法與‘uuencode’ 並不相同。

此模块提供了两个接口。新的接口提供了从 *note 类字节对象: 6df. 到 ASCII 字
节 *note bytes: 172. 的编码，以及将 ASCII 的 *note 类字节对象: 6df. 或字
符串解码到 *note bytes: 172. 的操作。此模块支持定义在 RFC 3548(4) 中的所
有 base-64 字母表 （普通的、URL 安全的和文件系统安全的）。

旧的接口不提供从字符串的解码操作，但提供了操作 *note 文件对象: c14. 的编
码和解码函数。旧接口只支持标准的 Base64 字母表，并且按照 RFC 2045(5) 的
规范每 76 个字符增加一个换行符。注意：如果你需要支持 RFC 2045(6)，那么使
用 *note email: 67. 模块可能更加合适。

3.3 版更變: 新的接口提供的解码函数现在已经支持只包含 ASCII 的 Unicode 字
符串。

3.4 版更變: 所有 *note 类字节对象: 6df. 现在已经被所有编码和解码函数接受
。添加了对 Ascii85/Base85 的支持。

新的接口提供：

 -- 函式: base64.b64encode (s, altchars=None)

     对 *note bytes-like object: 6df. `s' 进行 Base64 编码，并返回编码后
     的 *note bytes: 172.。

     可选项 `altchars' 必须是一个长 2 字节的 *note bytes-like object:
     6df.，它指定了用于替换 ‘+’ 和 ‘/’ 的字符。这允许应用程序生成 URL 或
     文件系统安全的 Base64 字符串。默认值是 ‘None’，使用标准 Base64 字母
     表。

 -- 函式: base64.b64decode (s, altchars=None, validate=False)

     解码 Base64 编码过的 *note bytes-like object: 6df. 或 ASCII 字符串
     `s' 并返回解码过的 *note bytes: 172.。

     可选项 `altchars' 必须是一个长 2 字节的 *note bytes-like object:
     6df.，它指定了用于替换 ‘+’ 和 ‘/’ 的字符。

     如果 `s' 被不正确地填写，一个 *note binascii.Error: a3f. 错误将被抛
     出。

     如果 `validate' 值为 ‘False’ （默认情况），则在填充检查前，将丢弃既
     不在标准 base-64 字母表之中也不在备用字母表中的字符。如果
     `validate' 为 ‘True’，这些非 base64 字符将导致 *note
     binascii.Error: a3f.。

 -- 函式: base64.standard_b64encode (s)

     编码 *note bytes-like object: 6df. `s'，使用标准 Base64 字母表并返
     回编码过的 *note bytes: 172.。

 -- 函式: base64.standard_b64decode (s)

     解码 *note bytes-like object: 6df. 或 ASCII 字符串 `s'，使用标准
     Base64 字母表并返回编码过的 *note bytes: 172.。

 -- 函式: base64.urlsafe_b64encode (s)

     编码 *note bytes-like object: 6df. `s'，使用 URL 与文件系统安全的字
     母表，使用 ‘-’ 以及 ‘_’ 代替标准 Base64 字母表中的 ‘+’ 和 ‘/’。返回
     编码过的 *note bytes: 172.。结果中可能包含 ‘=’。

 -- 函式: base64.urlsafe_b64decode (s)

     解码 *note bytes-like object: 6df. 或 ASCII 字符串 `s'，使用 URL 与
     文件系统安全的字母表，使用 ‘-’ 以及 ‘_’ 代替标准 Base64 字母表中的
     ‘+’ 和 ‘/’。返回解码过的 *note bytes: 172.

 -- 函式: base64.b32encode (s)

     用 Base32 编码 *note bytes-like object: 6df. `s' 并返回编码过的
     *note bytes: 172.

 -- 函式: base64.b32decode (s, casefold=False, map01=None)

     解码 Base32 编码过的 *note bytes-like object: 6df. 或 ASCII 字符串
     `s' 并返回解码过的 *note bytes: 172.。

     可选的 `casefold' 是一个指定小写字幕是否可接受为输入的标志。为了安
     全考虑，默认值为 ‘False’。

     RFC 3548(7) 允许将字母 0(zero) 映射为字母 O(oh)，并可以选择是否将字
     母 1(one) 映射为 I(eye) 或 L(el)。可选参数 `map01' 不是 ‘None’ 时，
     它的值指定 1 的映射目标 (I 或 l)，当 `map01' 非 ‘None’ 时， 0 总是
     被映射为 O。为了安全考虑，默认值被设为 ‘None’，如果是这样， 0 和 1
     不允许被作为输入。

     如果 `s' 被错误地填写或输入中存在字母表之外的字符，将抛出 *note
     binascii.Error: a3f.。

 -- 函式: base64.b16encode (s)

     用 Base16 编码 *note bytes-like object: 6df. `s' 并返回编码过的
     *note bytes: 172.

 -- 函式: base64.b16decode (s, casefold=False)

     解码 Base16 编码过的 *note bytes-like object: 6df. 或 ASCII 字符串
     `s' 并返回解码过的 *note bytes: 172.。

     可选的 `casefold' 是一个指定小写字幕是否可接受为输入的标志。为了安
     全考虑，默认值为 ‘False’。

     如果 `s' 被错误地填写或输入中存在字母表之外的字符，将抛出 *note
     binascii.Error: a3f.。

 -- 函式: base64.a85encode (b, *, foldspaces=False, wrapcol=0,
          pad=False, adobe=False)

     用 Ascii85 编码 *note bytes-like object: 6df. `s' 并返回编码过的
     *note bytes: 172.

     `foldspaces' 是一个可选的标志，使用特殊的短序列 ’y’ 代替 ’btoa’ 提
     供的 4 个连续空格 (ASCII 0x20)。这个特性不被 "标准" Ascii85 编码支
     持。

     `wrapcol' 控制了输出是否包含换行符 (‘b'\n'’). 如果该值非零, 则每一
     行只有该值所限制的字符长度.

     `pad' 控制在编码之前输入是否填充为4的倍数。请注意，‘btoa’ 实现总是
     填充。

     `adobe' 控制编码后的字节序列是否要加上 ‘<~’ 和 ‘~>’，这是 Adobe 实
     现所使用的。

     3.4 版新加入.

 -- 函式: base64.a85decode (b, *, foldspaces=False, adobe=False,
          ignorechars=b' \t\n\r\v')

     解码 Ascii85 编码过的 *note bytes-like object: 6df. 或 ASCII 字符串
     `s' 并返回解码过的 *note bytes: 172.。

     `foldspaces' 旗标指明是否应接受 ’y’ 短序列作为 4 个连续空格 (ASCII
     0x20) 的快捷方式。 此特性不被 "标准" Ascii85 编码格式所支持。

     `adobe' 控制输入序列是否为 Adobe Ascii85 格式 (即附加 <~ 和 ~>)。

     `ignorechars' 应当是一个 *note bytes-like object: 6df. 或 ASCII 字
     符串，其中包含要从输入中忽略的字符。 这应当只包含空白字符，并且默认
     包含 ASCII 中所有的空白字符。

     3.4 版新加入.

 -- 函式: base64.b85encode (b, pad=False)

     用 base85（如 git 风格的二进制 diff 数据所用格式）编码 *note
     bytes-like object: 6df. `b' 并返回编码后的 *note bytes: 172.。

     如果 `pad' 为真值，输入将以 ‘b'\0'’ 填充以使其编码前长度为 4 字节的
     倍数。

     3.4 版新加入.

 -- 函式: base64.b85decode (b)

     解码 base85 编码过的 *note bytes-like object: 6df. 或 ASCII 字符串
     `b' 并返回解码过的 *note bytes: 172.。 如有必要，填充会被隐式地移除
     。

     3.4 版新加入.

旧式接口:

 -- 函式: base64.decode (input, output)

     解码二进制 `input' 文件的内容并将结果二进制数据写入 `output' 文件。
     `input' 和 `output' 必须为 *note 文件对象: c14.  `input' 将被读取直
     至 ‘input.readline()’ 返回空字节串对象。

 -- 函式: base64.decodebytes (s)

     解码 *note bytes-like object: 6df. `s'，该对象必须包含一行或多行
     base64 编码的数据，并返回已解码的 *note bytes: 172.。

     3.1 版新加入.

 -- 函式: base64.encode (input, output)

     编码二进制 `input' 文件的内容并将经 base64 编码的数据写入 `output'
     文件。 `input' 和 `output' 必须为 *note 文件对象: c14.。 `input' 将
     被读取直到 ‘input.read()’ 返回空字节串对象。 *note encode(): 2afc.
     会在每输出 76 个字节之后插入一个换行符 (‘b'\n'’)，并会确保输出总是
     以换行符来结束，如 RFC 2045(8) (MIME) 所规定的那样。

 -- 函式: base64.encodebytes (s)

     编码 *note bytes-like object: 6df. `s'，其中可以包含任意二进制数据
     ，并返回包含经 base64 编码数据的 *note bytes: 172.，每输出 76 个字
     节之后将带一个换行符 (‘b'\n'’)，并会确保在末尾也有一个换行符，如
     RFC 2045(9) (MIME) 所规定的那样。

     3.1 版新加入.

此模块的一个使用示例:

     >>> import base64
     >>> encoded = base64.b64encode(b'data to be encoded')
     >>> encoded
     b'ZGF0YSB0byBiZSBlbmNvZGVk'
     >>> data = base64.b64decode(encoded)
     >>> data
     b'data to be encoded'

也參考
......

模块 *note binascii: f.

     支持模块，包含ASCII到二进制和二进制到ASCII转换。

RFC 1521(10) - MIME (Multipurpose Internet Mail Extensions) 第一部分：规定并描述因特网消息体的格式的机制。

     第 5.2 节，“Base64 内容转换编码格式” 提供了 base64 编码格式的定义。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/base64.py

   (2) https://tools.ietf.org/html/rfc3548.html

   (3) https://tools.ietf.org/html/rfc3548.html

   (4) https://tools.ietf.org/html/rfc3548.html

   (5) https://tools.ietf.org/html/rfc2045.html

   (6) https://tools.ietf.org/html/rfc2045.html

   (7) https://tools.ietf.org/html/rfc3548.html

   (8) https://tools.ietf.org/html/rfc2045.html

   (9) https://tools.ietf.org/html/rfc2045.html

   (10) https://tools.ietf.org/html/rfc1521.html


File: python.info,  Node: binhex --- 对binhex4文件进行编码和解码,  Next: binascii --- 二进制和 ASCII 码互转,  Prev: base64 —— Base16、Base32、Base64、Base85 資料編碼,  Up: 互联网数据处理

5.19.7 ‘binhex’ — 对binhex4文件进行编码和解码
---------------------------------------------

`源代码:' Lib/binhex.py(1)

3.9 版後已棄用.

__________________________________________________________________

此模块以binhe4格式对文件进行编码和解码，该格式允许Macintosh文件以ASCII格
式表示。仅处理数据分支。

*note binhex: 10. 模块定义了以下功能：

 -- 函式: binhex.binhex (input, output)

     将带有文件名 `输入' 的二进制文件转换为binhex文件 `输出' 。输出参数
     可以是文件名或类文件对象（ ‘write()’ 和 ‘close()’ 方法的任何对象）
     。

 -- 函式: binhex.hexbin (input, output)

     解码binhex文件输入。 `输入' 可以是支持 ‘read()’ 和 ‘close()’ 方法的
     文件名或类文件对象。生成的文件将写入名为 `output' 的文件，除非参数
     为 ‘None’ ，在这种情况下，从binhex文件中读取输出文件名。

还定义了以下异常：

 -- 例外: binhex.Error

     当无法使用binhex格式编码某些内容时（例如，文件名太长而无法放入文件
     名字段中），或者输入未正确编码的binhex数据时，会引发异常。

也參考
......

模块 *note binascii: f.

     支持模块，包含ASCII到二进制和二进制到ASCII转换。

* Menu:

* 註解: 註解<2>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/binhex.py


File: python.info,  Node: 註解<2>,  Up: binhex --- 对binhex4文件进行编码和解码

5.19.7.1 註解
.............

还有一个替代的、功能更强大的编码器和解码器接口，详细信息请参见源代码。

如果您在非Macintosh平台上编码或解码文本文件，它们仍将使用旧的Macintosh换
行符约定（回车符作为行尾）。


File: python.info,  Node: binascii --- 二进制和 ASCII 码互转,  Next: quopri --- 编码与解码经过 MIME 转码的可打印数据,  Prev: binhex --- 对binhex4文件进行编码和解码,  Up: 互联网数据处理

5.19.8 ‘binascii’ — 二进制和 ASCII 码互转
-----------------------------------------

__________________________________________________________________

*note binascii: f. 模块包含很多在二进制和二进制表示的各种ASCII码之间转换
的方法。 通常情况不会直接使用这些函数，而是使用像 *note uu: 12c. ，
*note base64: d. ，或 *note binhex: 10. 这样的封装模块。 为了执行效率高
，*note binascii: f. 模块含有许多用 C 写的低级函数，这些底层函数被一些高
级模块所使用。

     備註: ‘a2b_*’ 函数接受只含有 ASCII 码的Unicode 字符串。其他函数只接
     受 *note 字节类对象: 6df. （例如 *note bytes: 172.，*note
     bytearray: 173. 和其他支持缓冲区协议的对象）。

     3.3 版更變: ASCII-only unicode strings are now accepted by the
     ‘a2b_*’ functions.

*note binascii: f. 模块定义了以下函数：

 -- 函式: binascii.a2b_uu (string)

     将单行 uu 编码数据转换成二进制数据并返回。uu 编码每行的数据通常包含
     45 个（二进制）字节，最后一行除外。每行数据后面可能跟有空格。

 -- 函式: binascii.b2a_uu (data, *, backtick=False)

     将二进制数据转换为 ASCII 编码字符，返回值是转换后的行数据，包括换行
     符。 `data' 的长度最多为45。如果 `backtick' 为ture，则零由 ‘'`'’ 而
     不是空格表示。

     3.7 版更變: 增加 `backtick' 形参。

 -- 函式: binascii.a2b_base64 (string)

     将 base64 数据块转换成二进制并以二进制数据形式返回。一次可以传递多
     行数据。

 -- 函式: binascii.b2a_base64 (data, *, newline=True)

     将二进制数据转换为一行用 base64 编码的ASCII字符串。返回值是转换后的
     行数据，如果 `newline' 为true，则返回值包括换行符。该函数的输出符合
     ：rfc：‘3548’。

     3.6 版更變: 增加 `newline' 形参。

 -- 函式: binascii.a2b_qp (data, header=False)

     将一个引号可打印的数据块转换成二进制数据并返回。一次可以转换多行。
     如果可选参数 `header' 存在且为true，则数据中的下划线将被解码成空格
     。

 -- 函式: binascii.b2a_qp (data, quotetabs=False, istext=True,
          header=False)

     将二进制数据转换为一行或多行带引号可打印编码的ASCII字符串。返回值是
     转换后的行数据。如果可选参数 `quotetabs' 存在且为真值，则对所有制表
     符和空格进行编码。如果可选参数 `istext' 存在且为真值，则不对新行进
     行编码，但将对尾随空格进行编码。如果可选参数 `header' 存在且为
     true，则空格将被编码为下划线 RFC 1522(1)。如果可选参数 `header' 存
     在且为假值，则也会对换行符进行编码;不进行换行转换编码可能会破坏二进
     制数据流。

 -- 函式: binascii.a2b_hqx (string)

     将 binhex4 格式的 ASCII 数据不进行 RLE 解压缩直接转换为二进制数据。
     该字符串应包含完整数量的二进制字节，或者（在binhex4 数据最后部分）
     剩余位为零。

     3.9 版後已棄用.

 -- 函式: binascii.rledecode_hqx (data)

     根据 binhex4 标准对数据执行 RLE 解压缩。该算法在一个字节的数据后使
     用 ‘0x90’ 作为重复指示符，然后计数。计数 ‘0’ 指定字节值 ‘0x90’ 。该
     例程返回解压缩的数据，输入数据以孤立的重复指示符结束的情况下，将引
     发 *note Incomplete: 2b09. 异常。

     3.2 版更變: 仅接受 bytestring 或 bytearray 对象作为输入。

     3.9 版後已棄用.

 -- 函式: binascii.rlecode_hqx (data)

     在 `data' 上执行 binhex4 游程编码压缩并返回结果。

     3.9 版後已棄用.

 -- 函式: binascii.b2a_hqx (data)

     执行 hexbin4 类型二进制到 ASCII 码的转换并返回结果字符串。输入数据
     应经过 RLE 编码，且数据长度可被3整除（除了最后一个片段）。

     3.9 版後已棄用.

 -- 函式: binascii.crc_hqx (data, value)

     以 `value' 作为初始 CRC 计算 `data' 的16位 CRC 值，返回其结果。这里
     使用 CRC-CCITT 生成多项式 `x'^16 + `x'^12 + `x'^5 + 1 ，通常表示为
     0x1021。该 CRC 被用于 binhex4 格式。

 -- 函式: binascii.crc32 (data[, value])

     计算 CRC-32 ，从 `value' 的初始 CRC 开始计算 `data' 的32位校验和。
     默认初始 CRC 为零。该算法与 ZIP 文件校验和一致。由于该算法被设计用
     作校验和算法，因此不适合用作通用散列算法。使用方法如下：

          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))

     3.0 版更變: 校验结果始终是无符号类型的。要在所有Python版本和平台上
     生成相同的数值，请使用 ‘crc32(data) & 0xffffffff’ 。

 -- 函式: binascii.b2a_hex (data[, sep[, bytes_per_sep=1]])
 -- 函式: binascii.hexlify (data[, sep[, bytes_per_sep=1]])

     返回二进制数据 `data' 的十六进制表示形式。 `data' 的每个字节都被转
     换为相应的2位十六进制表示形式。因此返回的字节对象的长度是 `data' 的
     两倍。

     使用：*note bytes.hex(): 724. 方法也可以方便地实现相似的功能（但仅
     返回文本字符串）。

     如果指定了 `sep'，它必须为单字符 str 或 bytes 对象。 它将被插入每个
     `bytes_per_sep' 输入字节之后。 分隔符位置默认从输出的右端开始计数，
     如果你希望从左端开始计数，请提供一个负的 `bytes_per_sep' 值。

          >>> 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'

     3.8 版更變: 添加了 `sep' 和 `bytes_per_sep' 形参。

 -- 函式: binascii.a2b_hex (hexstr)
 -- 函式: binascii.unhexlify (hexstr)

     返回由十六进制字符串 `hexstr' 表示的二进制数据。此函数功能与 *note
     b2a_hex(): 19b7. 相反。 `hexstr' 必须包含偶数个十六进制数字（可以是
     大写或小写），否则会引发 *note Error: a3f. 异常。

     使用：*note bytes.fromhex(): 43e. 类方法也实现相似的功能（仅接受文
     本字符串参数，不限制其中的空白字符）。

 -- 例外: binascii.Error

     通常是因为编程错误引发的异常。

 -- 例外: binascii.Incomplete

     数据不完整引发的异常。通常不是编程错误导致的，可以通过读取更多的数
     据并再次尝试来处理该异常。

也參考
......

模块 *note base64: d.

     支持在16，32，64，85进制中进行符合 RFC 协议的 base64 样式编码。

模块 *note binhex: 10.

     支持在 Macintosh 上使用的 binhex 格式。

模块 *note uu: 12c.

     支持在 Unix 上使用的 UU 编码。

模块 *note quopri: db.

     支持在 MIME 版本电子邮件中使用引号可打印编码。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc1522.html


File: python.info,  Node: quopri --- 编码与解码经过 MIME 转码的可打印数据,  Next: uu --- 对 uuencode 文件进行编码与解码,  Prev: binascii --- 二进制和 ASCII 码互转,  Up: 互联网数据处理

5.19.9 ‘quopri’ — 编码与解码经过 MIME 转码的可打印数据
------------------------------------------------------

`源代码:' Lib/quopri.py(1)

__________________________________________________________________

此模块会执行转换后可打印的传输编码与解码，具体定义见 RFC 1521(2): "MIME
(Multipurpose Internet Mail Extensions) Part One: Mechanisms for
Specifying and Describing the Format of Internet Message Bodies"。 转换
后可打印的编码格式被设计用于只包含相对较少的不可打印字符的数据；如果存在
大量这样的字符，通过 *note base64: d. 模块所提供的 base64 编码方案会更为
紧凑，例如当发送图片文件时。

 -- 函式: quopri.decode (input, output, header=False)

     解码 `input' 文件的内容并将已解码二进制数据结果写入 `output' 文件。
     `input' 和 `output' 必须为 *note 二进制文件对象: c14.。 如果提供了
     可选参数 `header' 且为真值，下划线将被解码为空格。 此函数可用于解码
     “Q”编码的头数据，具体描述见 RFC 1522(3): "MIME (Multipurpose
     Internet Mail Extensions) Part Two: Message Header Extensions for
     Non-ASCII Text"。

 -- 函式: quopri.encode (input, output, quotetabs, header=False)

     编码 `input' 文件的内容并将转换后可打印的数据结果写入 `output' 文件
     。 `input' 和 `output' 必须为 *note 二进制文件对象: c14.
     `quotetabs' 是一个非可选的旗标，它控制是否要编码内嵌的空格与制表符
     ；当为真值时将编码此类内嵌空白符，当为假值时则保持原样不进行编码。
     请注意出现在行尾的空格与制表符总是会被编码，具体描述见 RFC 1521(4)。
     `header' 旗标控制空格符是否要编码为下划线，具体描述见 RFC 1522(5)。

 -- 函式: quopri.decodestring (s, header=False)

     类似 *note decode(): 19ba.，区别在于它接受一个源 *note bytes: 172.
     并返回对应的已解码 *note bytes: 172.。

 -- 函式: quopri.encodestring (s, quotetabs=False, header=False)

     类型 *note encode(): 19b9.，区别在于它接受一个源 *note bytes: 172.
     并返回对应的已编码 *note bytes: 172.。 在默认情况下，它会发送
     ‘False’ 值给 *note encode(): 19b9. 函数的 `quotetabs' 形参。

也參考
......

模块 *note base64: d.

     编码与解码 MIME base64 数据

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/quopri.py

   (2) https://tools.ietf.org/html/rfc1521.html

   (3) https://tools.ietf.org/html/rfc1522.html

   (4) https://tools.ietf.org/html/rfc1521.html

   (5) https://tools.ietf.org/html/rfc1522.html


File: python.info,  Node: uu --- 对 uuencode 文件进行编码与解码,  Prev: quopri --- 编码与解码经过 MIME 转码的可打印数据,  Up: 互联网数据处理

5.19.10 ‘uu’ — 对 uuencode 文件进行编码与解码
---------------------------------------------

`源代码:' Lib/uu.py(1)

__________________________________________________________________

此模块使用 uuencode 格式来编码和解码文件，以便任意二进制数据可通过仅限
ASCII 码的连接进行传输。 在任何要求文件参数的地方，这些方法都接受文件类
对象。 为了保持向下兼容，也接受包含路径名称的字符串，并且将打开相应的文
件进行读写；路径名称 ‘'-'’ 被解读为标准输入或输出。 但是，此接口已被弃用
；在 Windows 中调用者最好是自行打开文件，并在需要时确保模式为 ‘'rb'’ or
‘'wb'’。

此代码由 Lance Ellinghouse 贡献，并由 Jack Jansen 修改。

*note uu: 12c. 模块定义了以下函数：

 -- 函式: uu.encode (in_file, out_file, name=None, mode=None, *,
          backtick=False)

     使用 uuencode 将 `in_file' 文件编码为 `out_file' 文件。 经过
     uuencoded 编码的文件将具有指定 `name' 和 `mode' 作为解码该文件默认
     结果的标头。 默认值会相应地从 `in_file' 或 ‘'-'’ 以及 ‘0o666’ 中提
     取。 如果 `backtick' 为真值，零会用 ‘'`'’ 而不是空格来表示。

     3.7 版更變: 增加 `backtick' 参数

 -- 函式: uu.decode (in_file, out_file=None, mode=None, quiet=False)

     调用此函数会解码 uuencod 编码的 `in_file' 文件并将结果放入
     `out_file' 文件。 如果 `out_file' 是一个路径名称，`mode' 会在必须创
     建文件时用于设置权限位。 `out_file' 和 `mode' 的默认值会从 uuencode
     标头中提取。 但是，如果标头中指定的文件已存在，则会引发 *note
     uu.Error: 2b11.。

     如果输入由不正确的 uuencode 编码器生成，*note decode(): 19bb. 可能
     会打印一条警告到标准错误 ，这样 Python 可以从该错误中恢复。 将
     `quiet' 设为真值可以屏蔽此警告。

 -- 例外: uu.Error

     *note Exception: 2dc. 的子类，此异常可由 *note uu.decode(): 19bb. 在
     多种情况下引发，如上文所述，此外还包括格式错误的标头或被截断的输入
     文件等。

也參考
......

模块 *note binascii: f.

     支持模块，包含ASCII到二进制和二进制到ASCII转换。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/uu.py


File: python.info,  Node: 结构化标记处理工具,  Next: 互联网协议和支持,  Prev: 互联网数据处理,  Up: Python 標準函式庫 Standard Library

5.20 结构化标记处理工具
=======================

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 解析


File: python.info,  Node: html --- 超文本标记语言支持,  Next: html parser --- 简单的 HTML 和 XHTML 解析器,  Up: 结构化标记处理工具

5.20.1 ‘html’ — 超文本标记语言支持
----------------------------------

`源码：' Lib/html/__init__.py(1)

__________________________________________________________________

该模块定义了操作HTML的工具。

 -- 函式: html.escape (s, quote=True)

     将字符串 `s' 中的字符‘‘&‘‘ 、 ‘<’ 和 ‘>’ 转换为安全的HTML序列。 如
     果需要在 HTML 中显示可能包含此类字符的文本，请使用此选项。 如果可选
     的标志 `quote' 为真值，则字符 (‘"’) 和 (‘'’) 也被转换；这有助于包含
     在由引号分隔的 HTML 属性中，如 ‘<a href="...">’。

     3.2 版新加入.

 -- 函式: html.unescape (s)

     将字符串 `s' 中的所有命名和数字字符引用 (例如 ‘&gt;’, ‘&#62;’,
     ‘&#x3e;’) 转换为相应的Unicode字符。 此函数使用HTML 5标准为有效和无
     效字符引用定义的规则，以及 *note HTML 5 命名字符引用列表: af3.。

     3.4 版新加入.

__________________________________________________________________

‘html’ 包中的子模块是：

   * *note html.parser: 91. —— 具有宽松解析模式的HTML / XHTML解析器

   * *note html.entities: 90. – HTML 实体定义

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/html/__init__.py


File: python.info,  Node: html parser --- 简单的 HTML 和 XHTML 解析器,  Next: html entities --- HTML 一般实体的定义,  Prev: html --- 超文本标记语言支持,  Up: 结构化标记处理工具

5.20.2 ‘html.parser’ — 简单的 HTML 和 XHTML 解析器
--------------------------------------------------

`源代码：' Lib/html/parser.py(1)

__________________________________________________________________

这个模块定义了一个 *note HTMLParser: 22a. 类，为 HTML（超文本标记语言）
和 XHTML 文本文件解析提供基础。

 -- 類別: html.parser.HTMLParser (*, convert_charrefs=True)

     创建一个能解析无效标记的解析器实例。

     如果 `convert_charrefs' 为 ‘True’ (默认值)，则所有字符引用(
     ‘script’/‘style’ 元素中的除外)都会自动转换为相应的 Unicode 字符。

     一个 *note HTMLParser: 22a. 类的实例用来接受 HTML 数据，并在标记开
     始、标记结束、文本、注释和其他元素标记出现的时候调用对应的方法。要
     实现具体的行为，请使用 *note HTMLParser: 22a. 的子类并重载其方法。

     这个解析器不检查结束标记是否与开始标记匹配，也不会因外层元素完毕而
     隐式关闭了的元素引发结束标记处理。

     3.4 版更變: `convert_charrefs' 关键字参数被添加。

     3.5 版更變: `convert_charrefs' 参数的默认值现在为 ‘True’。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/html/parser.py


File: python.info,  Node: HTML 解析器的示例程序,  Next: HTMLParser 方法,  Up: html parser --- 简单的 HTML 和 XHTML 解析器

5.20.2.1 HTML 解析器的示例程序
..............................

下面是简单的 HTML 解析器的一个基本示例，使用 *note HTMLParser: 22a. 类，
当遇到开始标记、结束标记以及数据的时候将内容打印出来。

     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>')

输出是:

     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


File: python.info,  Node: HTMLParser 方法,  Next: 示例<28>,  Prev: HTML 解析器的示例程序,  Up: html parser --- 简单的 HTML 和 XHTML 解析器

5.20.2.2 ‘HTMLParser’ 方法
..........................

*note HTMLParser: 22a. 实例有下列方法：

 -- 成員函式: HTMLParser.feed (data)

     填充一些文本到解析器中。如果包含完整的元素，则被处理；如果数据不完
     整，将被缓冲直到更多的数据被填充，或者 *note close(): 2b1c. 被调用
     。`data' 必须为 *note str: 205. 类型。

 -- 成員函式: HTMLParser.close ()

     如同后面跟着一个文件结束标记一样，强制处理所有缓冲数据。这个方法能
     被派生类重新定义，用于在输入的末尾定义附加处理，但是重定义的版本应
     当始终调用基类 *note HTMLParser: 22a. 的 *note close(): 2b1c. 方法
     。

 -- 成員函式: HTMLParser.reset ()

     重置实例。丢失所有未处理的数据。在实例化阶段被隐式调用。

 -- 成員函式: HTMLParser.getpos ()

     返回当前行号和偏移值。

 -- 成員函式: HTMLParser.get_starttag_text ()

     返回最近打开的开始标记中的文本。 结构化处理时通常应该不需要这个，但
     在处理“已部署”的 HTML 或是在以最小改变来重新生成输入时可能会有用处
     （例如可以保留属性间的空格等）。

下列方法将在遇到数据或者标记元素的时候被调用。他们需要在子类中重载。基类
的实现中没有任何实际操作（除了 *note handle_startendtag(): 2b20. ）：

 -- 成員函式: HTMLParser.handle_starttag (tag, attrs)

     这个方法在标签开始的时候被调用（例如： ‘<div id="main">’ ）。

     `tag' 参数是小写的标记名。`attrs' 参数是一个 ‘(name, value)’ 形式的
     列表，包含了所有在标记的 ‘<>’ 括号中找到的属性。`name' 转换为小写，
     `value' 的引号被去除，字符和实体引用都会被替换。

     实例中，对于标签 ‘<A HREF="https://www.cwi.nl/">’，这个方法将以下列
     形式被调用 ‘handle_starttag('a', [('href',
     'https://www.cwi.nl/')])’ 。

     *note html.entities: 90. 中的所有实体引用，会被替换为属性值。

 -- 成員函式: HTMLParser.handle_endtag (tag)

     此方法被用来处理元素的结束标记（例如： ‘</div>’ ）。

     `tag' 参数是小写的标签名。

 -- 成員函式: HTMLParser.handle_startendtag (tag, attrs)

     类似于 *note handle_starttag(): 2b21, 只是在解析器遇到 XHTML 样式的
     空标记时被调用（ ‘<img ... />’）。这个方法能被需要这种特殊词法信息
     的子类重载；默认实现仅简单调用 *note handle_starttag(): 2b21. 和
     *note handle_endtag(): 2b22. 。

 -- 成員函式: HTMLParser.handle_data (data)

     这个方法被用来处理任意数据（例如：文本节点和 ‘<script>...</script>’
     以及 ‘<style>...</style>’ 中的内容）。

 -- 成員函式: HTMLParser.handle_entityref (name)

     这个方法被用于处理 ‘&name;’ 形式的命名字符引用（例如 ‘&gt;’），其中
     `name' 是通用的实体引用（例如： ‘'gt'’）。如果 `convert_charrefs' 为
     ‘True’，该方法永远不会被调用。

 -- 成員函式: HTMLParser.handle_charref (name)

     这个方法被用来处理 ‘&#NNN;’ 和 ‘&#xNNN;’ 形式的十进制和十六进制字符
     引用。例如，‘&gt;’ 等效的十进制形式为 ‘&#62;’ ，而十六进制形式为
     ‘&#x3E;’ ；在这种情况下，方法将收到 ‘'62'’ 或 ‘'x3E'’ 。如果
     `convert_charrefs' 为 ‘True’ ，则该方法永远不会被调用。

 -- 成員函式: HTMLParser.handle_comment (data)

     这个方法在遇到注释的时候被调用（例如： ‘<!--comment-->’ ）。

     例如， ‘<!-- comment -->’ 这个注释会用 ‘' comment '’ 作为参数调用此
     方法。

     Internet Explorer 条件注释（condcoms）的内容也被发送到这个方法，因
     此，对于 ‘<!--[if IE 9]>IE9-specific content<![endif]-->’ ，这个方
     法将接收到 ‘'[if IE 9]>IE9-specific content<![endif]'’ 。

 -- 成員函式: HTMLParser.handle_decl (decl)

     这个方法用来处理 HTML doctype 申明（例如 ‘<!DOCTYPE html>’ ）。

     `decl' 形参为 ‘<!...>’ 标记中的所有内容（例如： ‘'DOCTYPE html'’ ）
     。

 -- 成員函式: HTMLParser.handle_pi (data)

     此方法在遇到处理指令的时候被调用。`data' 形参将包含整个处理指令。例
     如，对于处理指令 ‘<?proc color='red'>’ ，这个方法将以
     ‘handle_pi("proc color='red'")’ 形式被调用。它旨在被派生类重载；基
     类实现中无任何实际操作。

          備註: *note HTMLParser: 22a. 类使用 SGML 语法规则处理指令。使
          用 ‘'?'’ 结尾的 XHTML 处理指令将导致 ‘'?'’ 包含在 `data' 中。

 -- 成員函式: HTMLParser.unknown_decl (data)

     当解析器读到无法识别的声明时，此方法被调用。

     `data' 形参为 ‘<![...]>’ 标记中的所有内容。某些时候对派生类的重载很
     有用。基类实现中无任何实际操作。


File: python.info,  Node: 示例<28>,  Prev: HTMLParser 方法,  Up: html parser --- 简单的 HTML 和 XHTML 解析器

5.20.2.3 示例
.............

下面的类实现了一个解析器，用于更多示例的演示:

     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()

解析一个文档类型声明:

     >>> 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"

解析一个具有一些属性和标题的元素:

     >>> 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

‘script’ 和 ‘style’ 元素中的内容原样返回，无需进一步解析:

     >>> 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

解析注释:

     >>> parser.feed('<!-- a comment -->'
     ...             '<!--[if IE 9]>IE-specific content<![endif]-->')
     Comment  :  a comment
     Comment  : [if IE 9]>IE-specific content<![endif]

解析命名或数字形式的字符引用，并把他们转换到正确的字符（注意：这 3 种转
义都是 ‘'>'’ ）:

     >>> parser.feed('&gt;&#62;&#x3E;')
     Named ent: >
     Num ent  : >
     Num ent  : >

填充不完整的块给 *note feed(): 2b1b. 执行，*note handle_data(): 2b23. 可
能会多次调用（除非 `convert_charrefs' 被设置为 ‘True’ ）:

     >>> 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

解析无效的 HTML (例如：未引用的属性）也能正常运行:

     >>> 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


File: python.info,  Node: html entities --- HTML 一般实体的定义,  Next: XML 處理模組,  Prev: html parser --- 简单的 HTML 和 XHTML 解析器,  Up: 结构化标记处理工具

5.20.3 ‘html.entities’ — HTML 一般实体的定义
--------------------------------------------

`源码：' Lib/html/entities.py(1)

__________________________________________________________________

该模块定义了四个词典， *note html5: af3.、 *note name2codepoint: 2b2e.、
*note codepoint2name: 2b2f.、以及 *note entitydefs: 2b30.。

 -- Data: html.entities.html5

     将 HTML5 命名字符引用 (2) 映射到等效的 Unicode 字符的字典，例如
     ‘html5['gt;'] == '>'’。 请注意，尾随的分号包含在名称中（例如
     ‘'gt;'’ ），但是即使没有分号，一些名称也会被标准接受，在这种情况下
     ，名称出现时带有和不带有 ‘';'’。另见 *note html.unescape(): 22b.。

     3.3 版新加入.

 -- Data: html.entities.entitydefs

     将 XHTML 1.0 实体定义映射到 ISO Latin-1 中的替换文本的字典。

 -- Data: html.entities.name2codepoint

     将 HTML 实体名称映射到 Unicode 代码点的字典。

 -- Data: html.entities.codepoint2name

     将 Unicode 代码点映射到 HTML 实体名称的字典。

註解
....

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/html/entities.py

   (2) (1) See
‘https://html.spec.whatwg.org/multipage/syntax.html#named-character-references’


File: python.info,  Node: XML 處理模組,  Next: xml etree ElementTree --- ElementTree XML API,  Prev: html entities --- HTML 一般实体的定义,  Up: 结构化标记处理工具

5.20.4 XML 處理模組
-------------------

`源码：' Lib/xml/(1)

__________________________________________________________________

用于处理XML的Python接口分组在 ‘xml’ 包中。

     警告: XML 模块对于错误或恶意构造的数据是不安全的。 如果你需要解析不
     受信任或未经身份验证的数据，请参阅 *note XML 漏洞: 2b34. 和 *note
     defusedxml 包: 2b35. 部分。

值得注意的是 *note xml: 13c. 包中的模块要求至少有一个 SAX 兼容的 XML 解
析器可用。Expat 解析器包含在 Python 中，因此 *note xml.parsers.expat:
141. 模块将始终可用。

*note xml.dom: 13d. 和 *note xml.sax: 144. 包的文档是 DOM 和 SAX 接口的
Python 绑定的定义。

XML 处理子模块包括:

   * *note xml.etree.ElementTree: 140.： ElementTree API，一个简单而轻量
     级的XML处理器

   * *note xml.dom: 13d.：DOM API 定义

   * *note xml.dom.minidom: 13e.：最小的 DOM 实现

   * *note xml.dom.pulldom: 13f.：支持构建部分 DOM 树

   * *note xml.sax: 144.：SAX2 基类和便利函数

   * *note xml.parsers.expat: 141.：Expat解析器绑定

* Menu:

* XML 漏洞::
* defusedxml 包::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/xml/


File: python.info,  Node: XML 漏洞,  Next: defusedxml 包,  Up: XML 處理模組

5.20.4.1 XML 漏洞
.................

XML 处理模块对于恶意构造的数据是不安全的。 攻击者可能滥用 XML 功能来执行
拒绝服务攻击、访问本地文件、生成与其它计算机的网络连接或绕过防火墙。

下表概述了已知的攻击以及各种模块是否容易受到攻击。

种类                          sax                    etree                  minidom                pulldom                xmlrpc
                                                                                                                          
-------------------------------------------------------------------------------------------------------------------------------------------------
                                                                                                                          
billion laughs                `Vulnerable' (1)       `Vulnerable' (1)       `Vulnerable' (1)       `Vulnerable' (1)       `Vulnerable' (1)
                                                                                                                          
                                                                                                                          
quadratic blowup              `Vulnerable' (1)       `Vulnerable' (1)       `Vulnerable' (1)       `Vulnerable' (1)       `Vulnerable' (1)
                                                                                                                          
                                                                                                                          
external entity expansion     Safe (5)               Safe (2)               Safe (3)               Safe (5)               安全 (4)
                                                                                                                          
                                                                                                                          
DTD(1) retrieval              Safe (5)               安全                   安全                   Safe (5)               安全
                                                                                                                          
                                                                                                                          
decompression bomb            安全                   安全                   安全                   安全                   `易受攻击'
                                                                                                                          

  1. Expat 2.4.1 and newer is not vulnerable to the "billion laughs" and
     "quadratic blowup" vulnerabilities.  Items still listed as
     vulnerable due to potential reliance on system-provided libraries.
     Check ‘pyexpat.EXPAT_VERSION’.

  2. *note xml.etree.ElementTree: 140. 不会扩展外部实体并在实体发生时引
     发 ‘ParserError’。

  3. *note xml.dom.minidom: 13e. 不会扩展外部实体，只是简单地返回未扩展
     的实体。

  4. ‘xmlrpclib’ 不扩展外部实体并省略它们。

  5. 从 Python 3.7.1 开始，默认情况下不再处理外部通用实体。

billion laughs / exponential entity expansion （狂笑/递归实体扩展）

     Billion Laughs(2) 攻击 – 也称为递归实体扩展 – 使用多级嵌套实体。 每
     个实体多次引用另一个实体，最终实体定义包含一个小字符串。 指数级扩展
     导致几千 GB 的文本，并消耗大量内存和 CPU 时间。

quadratic blowup entity expansion（二次爆炸实体扩展）

     二次爆炸攻击类似于 Billion Laughs(3) 攻击，它也滥用实体扩展。 它不
     是嵌套实体，而是一遍又一遍地重复一个具有几千个字符的大型实体。攻击
     不如递归情况有效，但它避免触发禁止深度嵌套实体的解析器对策。

external entity expansion

     实体声明可以包含的不仅仅是替换文本。 它们还可以指向外部资源或本地文
     件。 XML 解析器访问资源并将内容嵌入到 XML 文档中。

DTD(4) retrieval

     Python 的一些 XML 库 *note xml.dom.pulldom: 13f. 从远程或本地位置检
     索文档类型定义。 该功能与外部实体扩展问题具有相似的含义。

decompression bomb

     Decompression bombs（解压炸弹，又名 ZIP bomb(5)）适用于所有可以解析
     压缩 XML 流（例如 gzip 压缩的 HTTP 流或 LZMA 压缩的文件）的 XML 库
     。 对于攻击者来说，它可以将传输的数据量减少三个量级或更多。

PyPI上 defusedxml(6) 的文档包含有关所有已知攻击向量的更多信息以及示例和
参考。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Document_type_definition

   (2) https://en.wikipedia.org/wiki/Billion_laughs

   (3) https://en.wikipedia.org/wiki/Billion_laughs

   (4) https://en.wikipedia.org/wiki/Document_type_definition

   (5) https://en.wikipedia.org/wiki/Zip_bomb

   (6) https://pypi.org/project/defusedxml/


File: python.info,  Node: defusedxml 包,  Prev: XML 漏洞,  Up: XML 處理模組

5.20.4.2 ‘defusedxml’ 包
........................

defusedxml(1) 是一个纯 Python 软件包，它修改了所有标准库 XML 解析器的子
类，可以防止任何潜在的恶意操作。 对于解析不受信任的XML数据的任何服务器代
码，建议使用此程序包。 该软件包还提供了有关更多 XML 漏洞（如 XPath 注入
）的示例漏洞和扩展文档。

   ---------- Footnotes ----------

   (1) https://pypi.org/project/defusedxml/


File: python.info,  Node: xml etree ElementTree --- ElementTree XML API,  Next: xml dom --- 文档对象模型 API,  Prev: XML 處理模組,  Up: 结构化标记处理工具

5.20.5 ‘xml.etree.ElementTree’ — ElementTree XML API
----------------------------------------------------

`源代码：' Lib/xml/etree/ElementTree.py(1)

__________________________________________________________________

*note xml.etree.ElementTree: 140. 模块实现了一个简单高效的API，用于解析
和创建XML数据。

3.3 版更變: 此模块将在可能的情况下使用快速实现。

3.3 版後已棄用: ‘xml.etree.cElementTree’ 模块已被弃用。

     警告: *note xml.etree.ElementTree: 140. 模块对于恶意构建的数据是不
     安全的。如果需要解析不可信或未经身份验证的数据，请参见 *note XML
     漏洞: 2b34. 。

* Menu:

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

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/Lib/xml/etree/ElementTree.py


File: python.info,  Node: 教程,  Next: XPath支持,  Up: xml etree ElementTree --- ElementTree XML API

5.20.5.1 教程
.............

这是一个使用 *note xml.etree.ElementTree: 140. （简称 ‘ET’ ）的简短教程
。目标是演示模块的一些构建块和基本概念。

* Menu:

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


File: python.info,  Node: XML 树和元素,  Next: 解析 XML,  Up: 教程

5.20.5.2 XML 树和元素
.....................

XML 是一种继承性的分层数据格式，最自然的表示方法是使用树。 为此， ‘ET’ 有
两个类 – *note ElementTree: 21c. 将整个XML文档表示为一个树， *note
Element: 21d. 表示该树中的单个节点。 与整个文档的交互（读写文件）通常在
*note ElementTree: 21c. 级别完成。 与单个 XML 元素及其子元素的交互是在
*note Element: 21d. 级别完成的。


File: python.info,  Node: 解析 XML,  Next: 用于非阻塞解析的拉取 API,  Prev: XML 树和元素,  Up: 教程

5.20.5.3 解析 XML
.................

我们将使用以下 XML 文档作为本节的示例数据：

     <?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>

可以通过从文件中读取来导入此数据：

     import xml.etree.ElementTree as ET
     tree = ET.parse('country_data.xml')
     root = tree.getroot()

或直接从字符串中解析：

     root = ET.fromstring(country_data_as_string)

*note fromstring(): 2b3f. 将 XML 从字符串直接解析为 *note Element: 21d.
，该元素是已解析树的根元素。 其他解析函数可能会创建一个 *note
ElementTree: 21c. 。 确切信息请查阅文档。

作为 *note Element: 21d. ， ‘root’ 具有标签和属性字典:

     >>> root.tag
     'data'
     >>> root.attrib
     {}

还有可以迭代的子节点：

     >>> for child in root:
     ...     print(child.tag, child.attrib)
     ...
     country {'name': 'Liechtenstein'}
     country {'name': 'Singapore'}
     country {'name': 'Panama'}

子级是可以嵌套的，我们可以通过索引访问特定的子级节点：

     >>> root[0][1].text
     '2008'

     備註: 并非 XML 输入的所有元素都将作为解析树的元素结束。 目前，此模
     块跳过输入中的任何 XML 注释、处理指令和文档类型声明。 然而，使用这
     个模块的 API 而不是从 XML 文本解析构建的树可以包含注释和处理指令，
     生成 XML 输出时同样包含这些注释和处理指令。 可以通过将自定义 *note
     TreeBuilder: 37d. 实例传递给 *note XMLParser: 37c. 构造器来访问文档
     类型声明。


File: python.info,  Node: 用于非阻塞解析的拉取 API,  Next: 查找感兴趣的元素,  Prev: 解析 XML,  Up: 教程

5.20.5.4 用于非阻塞解析的拉取 API
.................................

此模块所提供了大多数解析函数都要求在返回任何结果之前一次性读取整个文档。
可以使用 *note XMLParser: 37c. 并以增量方式添加数据，但这是在回调目标上
调用方法的推送式 API。 有时用户真正想要的是能够以增量方式解析 XML 而无需
阻塞操作，同时享受完整的已构造 *note Element: 21d. 对象。

针对此需求的最强大工具是 *note XMLPullParser: 9f9.。 它不要求通过阻塞式
读取来获得 XML 数据，而是通过执行 *note XMLPullParser.feed(): 2b41. 调用
来增量式地添加数据。 要获得已解析的 XML 元素，应调用 *note
XMLPullParser.read_events(): 2b42.。 下面是一个示例:

     >>> 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

常见的用例是针对以非阻塞方式进行的应用程序，其中 XML 是从套接字接收或从
某些存储设备增量式读取的。 在这些用例中，阻塞式读取是不可接受的。

因为其非常灵活，*note XMLPullParser: 9f9. 在更简单的用例中使用起来可能并
不方便。 如果你不介意你的应用程序在读取 XML 数据时造成阻塞但仍希望具有增
量解析能力，可以考虑 *note iterparse(): a29.。 它在你读取大型 XML 文档并
且不希望将它完全放去内存时会很适用。


File: python.info,  Node: 查找感兴趣的元素,  Next: 修改XML文件,  Prev: 用于非阻塞解析的拉取 API,  Up: 教程

5.20.5.5 查找感兴趣的元素
.........................

*note Element: 21d. 有一些很有效的方法，可帮助递归遍历其下的所有子树（包
括子级，子级的子级，等等）。例如 *note Element.iter(): daf.:

     >>> 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'}

*note Element.findall(): 2b44. 仅查找当前元素的直接子元素中带有指定标签
的元素。 *note Element.find(): 2b45. 找带有特定标签的 `第一个' 子级，然
后可以用 *note Element.text: 2b46. 访问元素的文本内容。 *note
Element.get: 2b47. 访问元素的属性:

     >>> for country in root.findall('country'):
     ...     rank = country.find('rank').text
     ...     name = country.get('name')
     ...     print(name, rank)
     ...
     Liechtenstein 1
     Singapore 4
     Panama 68

通过使用 *note XPath: 51d. ，可以更精确地指定要查找的元素。


File: python.info,  Node: 修改XML文件,  Next: 构建 XML 文档,  Prev: 查找感兴趣的元素,  Up: 教程

5.20.5.6 修改XML文件
....................

*note ElementTree: 21c. 提供了一种构建XML文档并将其写入文件的简单方法。
调用 *note ElementTree.write(): 9fd. 方法就可以实现。

创建后可以直接操作 *note Element: 21d. 对象。例如：使用 *note
Element.text: 2b46. 修改文本字段，使用 *note Element.set(): 2b49. 方法添
加和修改属性，以及使用 *note Element.append(): 2b4a. 添加新的子元素。

假设我们要为每个国家/地区的中添加一个排名，并在排名元素中添加一个
‘updated’ 属性：

     >>> 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')

生成的XML现在看起来像这样：

     <?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>

可以使用 *note Element.remove(): 2b4b. 删除元素。假设我们要删除排名高于
50的所有国家/地区:

     >>> 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')

请注意在迭代时进行并发修改可能会导致问题，就像在迭代并修改 Python 列表或
字典时那样。 因此，这个示例先通过 ‘root.findall()’ 收集了所有匹配的元素
，在此之后再对匹配项列表进行迭代。

生成的XML现在看起来像这样：

     <?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>


File: python.info,  Node: 构建 XML 文档,  Next: 解析带有命名空间的 XML,  Prev: 修改XML文件,  Up: 教程

5.20.5.7 构建 XML 文档
......................

*note SubElement(): 2b4d. 函数还提供了一种便捷方法来为给定元素创建新的子
元素:

     >>> 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>


File: python.info,  Node: 解析带有命名空间的 XML,  Next: 其他资源,  Prev: 构建 XML 文档,  Up: 教程

5.20.5.8 解析带有命名空间的 XML
...............................

如果 XML 输入带有 命名空间(1)，则具有前缀的 ‘prefix:sometag’ 形式的标记
和属性将被扩展为 ‘{uri}sometag’，其中 `prefix' 会被完整 `URI' 所替换。 并
且，如果存在 默认命名空间(2)，则完整 URI 会被添加到所有未加前缀的标记之
前。

下面的 XML 示例包含两个命名空间，一个具有前缀 "fictional" 而另一个则作为
默认命名空间:

     <?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>

搜索和探查这个 XML 示例的一种方式是手动为 *note find(): 2b45. 或 *note
findall(): 2b44. 的 xpath 中的每个标记或属性添加 URI:

     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)

一种更好的方式是搜索带命名空间的 XML 示例创建一个字典来存放你自己的前缀
并在搜索函数中使用它们:

     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)

这两种方式都会输出:

     John Cleese
      |--> Lancelot
      |--> Archie Leach
     Eric Idle
      |--> Sir Robin
      |--> Gunther
      |--> Commander Clement

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/XML_namespace

   (2) https://www.w3.org/TR/xml-names/#defaulting


File: python.info,  Node: 其他资源,  Prev: 解析带有命名空间的 XML,  Up: 教程

5.20.5.9 其他资源
.................

请访问 ‘http://effbot.org/zone/element-index.htm’ 获取教程和其他文档的链
接。


File: python.info,  Node: XPath支持,  Next: 参考引用,  Prev: 教程,  Up: xml etree ElementTree --- ElementTree XML API

5.20.5.10 XPath支持
...................

此模块提供了对 XPath 表达式(1) 的有限支持用于在树中定位元素。 其目标是支
持一个简化语法的较小子集；完整的 XPath 引擎超出了此模块的适用范围。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://www.w3.org/TR/xpath


File: python.info,  Node: 示例<29>,  Next: 支持的XPath语法,  Up: XPath支持

5.20.5.11 示例
..............

下面是一个演示此模块的部分 XPath 功能的例子。 我们将使用来自 *note 解析
XML: 2b3d. 小节的 ‘countrydata’ XML 文档:

     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]")

对于带有命名空间的 XML，应使用通常的限定 ‘{namespace}tag’ 标记法:

     # All dublin-core "title" tags in the document
     root.findall(".//{http://purl.org/dc/elements/1.1/}title")


File: python.info,  Node: 支持的XPath语法,  Prev: 示例<29>,  Up: XPath支持

5.20.5.12 支持的XPath语法
.........................

语法                        含义
                            
---------------------------------------------------------------------------------------
                            
‘tag’                       选择具有给定标记的所有子元素。 例如，‘spam’ 是选择名为
                            ‘spam’ 的所有子元素，而 ‘spam/egg’ 是在名为 ‘spam’ 的子
                            元素中选择所有名为 ‘egg’ 的孙元素，‘{*}spam’ 是在任意（
                            或无）命名空间中选择名为 ‘spam’ 的标记，而 ‘{}*’ 是只选
                            择不在一个命名空间中的标记。
                            
                            3.8 版更變: 增加了对星号通配符的支持。
                            
                            
‘*’                         选择所有子元素，包括注释和处理说明。例如 ‘*/egg’ 选择所
                            有名为 ‘egg’ 的孙元素。
                            
                            
‘.’                         选择当前节点。这在路径的开头非常有用，用于指示它是相对路
                            径。
                            
                            
‘//’                        选择所有子元素 在当前元素的所有下级中选择所有下级元素。
                            例如，‘.//egg’ 是在整个树中选择所有 ‘egg’ 元素。
                            
                            
‘..’                        选择父元素。 如果路径试图前往起始元素的上级（元素的
                            ‘find’ 被调用）则返回 ‘None’。
                            
                            
‘[@attrib]’                 选择具有给定属性的所有元素。
                            
                            
‘[@attrib='value']’         选择给定属性具有给定值的所有元素。该值不能包含引号。
                            
                            
‘[tag]’                     选择所有包含 ‘tag’ 子元素的元素。只支持直系子元素。
                            
                            
‘[.='text']’                选择完整文本内容等于 ‘text’ 的所有元素（包括后代）。
                            
                            3.7 版新加入.
                            
                            
‘[tag='text']’              选择所有包含名为 ‘tag’ 的子元素的元素，这些子元素（包括
                            后代）的完整文本内容等于给定的 ‘text’ 。
                            
                            
‘[position]’                选择位于给定位置的所有元素。 位置可以是一个整数 (1 表示
                            首位)，表达式 ‘last()’ (表示末位)，或者相对于末位的位置
                            (例如 ‘last()-1’)。
                            

谓词（方括号内的表达式）之前必须带有标签名称，星号或其他谓词。‘position’
谓词前必须有标签名称。


File: python.info,  Node: 参考引用,  Next: XInclude 支持,  Prev: XPath支持,  Up: xml etree ElementTree --- ElementTree XML API

5.20.5.13 参考引用
..................

* Menu:

* 函数: 函数<7>.


File: python.info,  Node: 函数<7>,  Up: 参考引用

5.20.5.14 函数
..............

 -- 函式: xml.etree.ElementTree.canonicalize (xml_data=None, *,
          out=None, from_file=None, **options)

     C14N 2.0(1) 转换功能。.

     规整化是标准化 XML 输出的一种方式，该方式允许按字节比较和数字签名。
     它降低了 XML 序列化器所具有的自由度并改为生成更受约束的 XML 表示形
     式。 主要限制涉及命名空间声明的位置、属性的顺序和可忽略的空白符等。

     此函数接受一个 XML 数字字符串 (`xml_data') 或文件路径或者文件类对象
     (`from_file') 作为输入，将其转换为规整形式，并在提供了 `out' 文件（
     类）对象的情况下将其写到该对象的话，或者如果未提供则将其作为文本字
     符串返回。 输出文件接受文本而非字节数据。 因此它应当以使用 ‘utf-8’
     编码格式的文本模式来打开。

     典型使用:

          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)

     配置选项 `options' 如下:

        - `with_comments': 设为真值以包括注释 (默认为假值)

        - 
          `strip_text': 设为真值以去除文本内容前后的空白符

               （默认值：否）

        - 
          `rewrite_prefixes': 设为真值以替换带有 "n{number}" 前缀的命名空间

               （默认值：否）

        - 
          `qname_aware_tags': 一组可感知限定名称的标记名称，其中的前缀

               应当在文本内容中被替换 (默认为空值)

        - 
          `qname_aware_attrs': 一组可感知限定名称的属性名称，其中的前缀

               应当在文本内容中被替换 (默认为空值)

        - `exclude_attrs': 一组不应当被序列化的属性名称

        - `exclude_tags': 一组不应当被序列化的标记名称

     在上面的选项列表中，"一组" 是指任意多项集或包含字符串的可迭代对象，
     排序是不必要的。

     3.8 版新加入.

 -- 函式: xml.etree.ElementTree.Comment (text=None)

     注释元素工厂函数。 这个工厂函数可创建一个特殊元素，它将被标准序列化
     器当作 XML 注释来进行序列化。 注释字串可以是字节串或是 Unicode 字符
     串。 `text' 是包含注释字串的字符串。 返回一个表示注释的元素实例。

     请注意 *note XMLParser: 37c. 会跳过输入中的注释而不会为其创建注释对
     象。 *note ElementTree: 21c. 将只在当使用某个 *note Element: 21d. 方
     法向树插入了注释节点时才会包含注释节点。

 -- 函式: xml.etree.ElementTree.dump (elem)

     将一个元素树或元素结构体写入到 sys.stdout。 此函数应当只被用于调试
     。

     实际输出格式是依赖于具体实现的。 在这个版本中，它将以普通 XML 文件
     的格式写入。

     `elem' 是一个元素树或单独元素。

     3.8 版更變: *note dump(): 2b58. 函数现在会保留用户指定的属性顺序。

 -- 函式: xml.etree.ElementTree.fromstring (text, parser=None)

     根据一个字符串常量解析 XML 的节。 与 *note XML(): 2b59. 类似。
     `text' 是包含 XML 数据的字符串。 `parser' 是可选的解析器实例。 如果
     未给出，则会使用标准 *note XMLParser: 37c. 解析器。 返回一个 *note
     Element: 21d. 实例。

 -- 函式: xml.etree.ElementTree.fromstringlist (sequence, parser=None)

     根据一个字符串片段序列解析 XML 文档。 `sequence' 是包含 XML 数据片
     段的列表或其他序列对象。 `parser' 是可选的解析器实例。 如果未给出，
     则会使用标准的 *note XMLParser: 37c. 解析器。 返回一个 *note
     Element: 21d. 实例。

     3.2 版新加入.

 -- 函式: xml.etree.ElementTree.indent (tree, space=" ", level=0)

     添加空格到子树来实现树的缩进效果。 这可以被用来生成美化打印的 XML 输
     出。 `tree' 可以为 Element 或 ElementTree。 `space' 是对应将被插入
     的每个缩进层级的空格字符串，默认为两个空格符。 要对已缩进的树的部分
     子树进行缩进，请传入初始缩进层级作为 `level'。

     3.9 版新加入.

 -- 函式: xml.etree.ElementTree.iselement (element)

     检测一个对象是否为有效的元素对象。 `element' 是一个元素实例。 如果
     对象是一个元素对象则返回 ‘True’。

 -- 函式: xml.etree.ElementTree.iterparse (source, events=None,
          parser=None)

     以增量方式将一个 XML 节解析为元素树，并向用户报告执行情况。
     `source' 是包含 XML 数据的文件名或 *note file object: c14.。
     `events' 是要报告的事件序列。 所支持的事件字符串有 ‘"start"’,
     ‘"end"’, ‘"comment"’, ‘"pi"’, ‘"start-ns"’ 和 ‘"end-ns"’ ("ns" 事件
     用于获取详细的命名空间信息)。 如果 `events' 被省略，则只有 ‘"end"’
     事件会被报告。 `parser' 是可选的解析器实例。 如果未给出，则会使用标
     准的 *note XMLParser: 37c. 解析器。 `parser' 必须为 *note
     XMLParser: 37c. 的子类并且只能使用默认的 *note TreeBuilder: 37d. 作
     为目标。 返回一个提供 ‘(event, elem)’ 对的 *note iterator: 1171.。

     请注意虽然 *note iterparse(): a29. 是以增量方式构建树，但它会对
     `source' (或其所指定的文件) 发出阻塞式读取。 因此，它不适用于不可执
     行阻塞式读取的应用。 对于完全非阻塞式的解析，请参看 *note
     XMLPullParser: 9f9.。

          備註: *note iterparse(): a29. 只会确保当发出 "start" 事件时看
          到了开始标记的 ">" 字符，因而在这个点上属性已被定义，但文本容
          和末尾属性还未被定义。 这同样适用于元素的下级；它们可能存在也
          可能不存在。

          如果你需要已完全填充的元素，请改为查找 "end" 事件。

     3.4 版後已棄用: `parser' 参数。

     3.8 版更變: 增加了 ‘comment’ 和 ‘pi’ 事件。

 -- 函式: xml.etree.ElementTree.parse (source, parser=None)

     将一个 XML 的节解析为元素树。 `source' 是包含 XML 数据的文件名或文
     件对象。 `parser' 是可选的解析器实例。 如果未给出，则会使用标准的
     *note XMLParser: 37c. 解析器。 返回一个 *note ElementTree: 21c. 实
     例。

 -- 函式: xml.etree.ElementTree.ProcessingInstruction (target,
          text=None)

     PI 元素工厂函数。 这个工厂函数可创建一个特殊元素，它将被当作 XML 处
     理指令来进行序列化。 `target' 是包含 PI 目标的字符串。 `text' 如果
     给出则是包含 PI 内容的字符串。 返回一个表示处理指令的元素实例。

     请注意 *note XMLParser: 37c. 会跳过输入中的处理指令而不会为其创建注
     释对象。 *note ElementTree: 21c. 将只在当使用某个 *note Element:
     21d. 方法向树插入了处理指令节点时才会包含处理指令节点。

 -- 函式: xml.etree.ElementTree.register_namespace (prefix, uri)

     注册一个命名空间前缀。 这个注册表是全局的，并且任何对应给定前缀或命
     名空间 URI 的现有映射都会被移除。 `prefix' 是命名空间前缀。 `uri' 是
     命名空间 URI。 如果可能的话，这个命名空间中的标记和属性将附带给定的
     前缀来进行序列化。

     3.2 版新加入.

 -- 函式: xml.etree.ElementTree.SubElement (parent, tag, attrib={},
          **extra)

     子元素工厂函数。 这个函数会创建一个元素实例，并将其添加到现有的元素
     。

     元素名、属性名和属性值可以是字节串或 Unicode 字符串。 `parent' 是父
     元素。 `tag' 是子元素名。 `attrib' 是一个可选的字典，其中包含元素属
     性。 `extra' 包含额外的属性，以关键字参数形式给出。 返回一个元素实
     例。

 -- 函式: xml.etree.ElementTree.tostring (element, encoding="us-ascii",
          method="xml", *, xml_declaration=None, default_namespace=None,
          short_empty_elements=True)

     生成一个 XML 元素的字符串表示形式，包括所有子元素。 `element' 是一
     个 *note Element: 21d. 实例。 `encoding' (2) 是输出编码格式（默认为
     US-ASCII）。 请使用 ‘encoding="unicode"’ 来生成 Unicode 字符串（否
     则生成字节串）。 `method' 是 ‘"xml"’, ‘"html"’ 或 ‘"text"’ (默认为
     ‘"xml"’)。 `xml_declaration', `default_namespace' 和
     `short_empty_elements' 具有与 *note ElementTree.write(): 9fd. 中一
     致的含义。 返回一个包含 XML 数据（可选）已编码的字符串。

     3.4 版新加入: `short_empty_elements' 形参。

     3.8 版新加入: `xml_declaration' 和 `default_namespace' 形参。

     3.8 版更變: *note tostring(): 9fb. 函数现在会保留用户指定的属性顺序
     。

 -- 函式: xml.etree.ElementTree.tostringlist (element,
          encoding="us-ascii", method="xml", *, xml_declaration=None,
          default_namespace=None, short_empty_elements=True)

     生成一个 XML 元素的字符串表示形式，包括所有子元素。 `element' 是一
     个 *note Element: 21d. 实例。 `encoding' (3) 是输出编码格式（默认为
     US-ASCII）。 请使用 ‘encoding="unicode"’ 来生成 Unicode 字符串（否
     则生成字节串）。 `method' 是 ‘"xml"’, ‘"html"’ 或 ‘"text"’ (默认为
     ‘"xml"’)。 `xml_declaration', `default_namespace' 和
     `short_empty_elements' 具有与 *note ElementTree.write(): 9fd. 中一
     致的含义。 返回一个包含 XML 数据（可选）已编码字符串的列表。 它并不
     保证任何特定的序列，除了 ‘b"".join(tostringlist(element)) ==
     tostring(element)’。

     3.2 版新加入.

     3.4 版新加入: `short_empty_elements' 形参。

     3.8 版新加入: `xml_declaration' 和 `default_namespace' 形参。

     3.8 版更變: *note tostringlist(): 9fc. 函数现在会保留用户指定的属性
     顺序。

 -- 函式: xml.etree.ElementTree.XML (text, parser=None)

     根据一个字符串常量解析 XML 的节。 此函数可被用于在 Python 代码中嵌
     入“XML 字面值”。 `text' 是包含 XML 数据的字符串。 `parser' 是可选的
     解析器实例。 如果未给出，则会使用标准的 *note XMLParser: 37c. 解析
     器。 返回一个 *note Element: 21d. 实例。

 -- 函式: xml.etree.ElementTree.XMLID (text, parser=None)

     根据一个字符串常量解析 XML 的节，并且还将返回一个将元素的 id:s 映射
     到元素的字典。 `text' 是包含 XML 数据的字符串。 `parser' 是可选的解
     析器实例。 如果未给出，则会使用标准的 *note XMLParser: 37c. 解析器
     。 返回一个包含 *note Element: 21d. 实例和字典的元组。

   ---------- Footnotes ----------

   (1) https://www.w3.org/TR/xml-c14n2/

   (2) (1) 包括在 XML 输出中的编码格式字符串应当符合适当的标准。 例如
"UTF-8" 是有效的，但 "UTF8" 是无效的。 请参阅
‘https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl’ 和
‘https://www.iana.org/assignments/character-sets/character-sets.xhtml’。

   (3) (1) 包括在 XML 输出中的编码格式字符串应当符合适当的标准。 例如
"UTF-8" 是有效的，但 "UTF8" 是无效的。 请参阅
‘https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl’ 和
‘https://www.iana.org/assignments/character-sets/character-sets.xhtml’。


File: python.info,  Node: XInclude 支持,  Next: 参考引用<2>,  Prev: 参考引用,  Up: xml etree ElementTree --- ElementTree XML API

5.20.5.15 XInclude 支持
.......................

此模块通过 ‘xml.etree.ElementInclude’ 辅助模块提供了对 XInclude 指令(1)
的有限支持，这个模块可被用来根据元素树的信息在其中插入子树和文本字符串。

* Menu:

* 示例: 示例<30>.

   ---------- Footnotes ----------

   (1) https://www.w3.org/TR/xinclude/


File: python.info,  Node: 示例<30>,  Up: XInclude 支持

5.20.5.16 示例
..............

以下是一个演示 XInclude 模块用法的例子。 要在当前文本中包括一个 XML 文档
，请使用 ‘{http://www.w3.org/2001/XInclude}include’ 元素并将 `parse' 属
性设为 ‘"xml"’，并使用 `href' 属性来指定要包括的文档。

     <?xml version="1.0"?>
     <document xmlns:xi="http://www.w3.org/2001/XInclude">
       <xi:include href="source.xml" parse="xml" />
     </document>

默认情况下，`href' 属性会被当作文件名来处理。 你可以使用自定义加载器来重
载此行为。 还要注意标准辅助器不支持 XPointer 语法。

要处理这个文件，请正常加载它，并将根元素传给 *note
xml.etree.ElementTree: 140. 模块:

     from xml.etree import ElementTree, ElementInclude

     tree = ElementTree.parse("document.xml")
     root = tree.getroot()

     ElementInclude.include(root)

ElementInclude 模块使用来自 `source.xml' 文档的根元素替代
‘{http://www.w3.org/2001/XInclude}include’ 元素。 结果看起来大概是这样:

     <document xmlns:xi="http://www.w3.org/2001/XInclude">
       <para>This is a paragraph.</para>
     </document>

如果省略了 `parse' 属性，它会取默认的 "xml"。 要求有 href 属性。

要包括文本文档，请使用 ‘{http://www.w3.org/2001/XInclude}include’ 元素，
并将 `parse' 属性设为 "text":

     <?xml version="1.0"?>
     <document xmlns:xi="http://www.w3.org/2001/XInclude">
       Copyright (c) <xi:include href="year.txt" parse="text" />.
     </document>

结果可能如下所示：

     <document xmlns:xi="http://www.w3.org/2001/XInclude">
       Copyright (c) 2003.
     </document>


File: python.info,  Node: 参考引用<2>,  Prev: XInclude 支持,  Up: xml etree ElementTree --- ElementTree XML API

5.20.5.17 参考引用
..................

* Menu:

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


File: python.info,  Node: 函数<8>,  Next: 元素对象,  Up: 参考引用<2>

5.20.5.18 函数
..............

 -- 函式: xml.etree.ElementInclude.default_loader (href, parse,
          encoding=None)

     默认的加载器。 这个默认的加载器会从磁盘读取所包括的资源。 `href' 是
     一个 URL。 `parse' 是 "xml" 或 "text" 表示解析模式。 `encoding' 是
     可选的文本编码格式。 如果未给出，则编码格式为 ‘utf-8’。 返回已扩展
     的资源。 如果解析模式为 ‘"xml"’，则它是一个 ElementTree 实例。 如果
     解析模式为 "text"，则它是一个 Unicode 字符串。 如果加载器失败，它可
     以返回 None 或者引发异常。

 -- 函式: xml.etree.ElementInclude.include (elem, loader=None,
          base_url=None, max_depth=6)

     这个函数会扩展 XInclude 指令。 `elem' 是根元素。 `loader' 是可选的
     资源加载器。 如果省略，则它默认为 *note default_loader(): 2b65.。 如
     果给出，则它应当是一个实现了与 *note default_loader(): 2b65. 相同的
     接口的可调用对象。 `base_url' 是原文件的基准 URL，用于求解相对的包
     括文件引用。 `max_depth' 是递归包括的最大数量。 此限制是为了降低恶
     意内容爆破的风险。 传入一个负值可禁用此限制。

     返回已扩展的资源。 如果解析模式为 ‘"xml"’，则它是一个 ElementTree 实
     例。 如果解析模式为 "text"，则它是一个 Unicode 字符串。 如果加载器
     失败，它可以返回 None 或者引发异常。

     3.9 版新加入: `base_url' 和 `max_depth' 形参。


File: python.info,  Node: 元素对象,  Next: ElementTree 对象,  Prev: 函数<8>,  Up: 参考引用<2>

5.20.5.19 元素对象
..................

 -- 類別: xml.etree.ElementTree.Element (tag, attrib={}, **extra)

     元素类。 这个类定义了 Element 接口，并提供了这个接口的引用实现。

     元素名、属性名和属性值可以是字节串或 Unicode 字符串。 `tag' 是元素
     名。 `attrib' 是一个可选的字典，其中包含元素属性。 `extra' 包含额外
     的属性，以关键字参数形式给出。

      -- 屬性: tag

          一个标识此元素意味着何种数据的字符串(换句话说，元素类型)。

      -- 屬性: text
      -- 屬性: tail

          这些属性可被用于存放与元素相关联的额外数据。 它们的值通常为字
          符串但也可以是任何应用专属的对象。 如果元素是基于 XML 文件创建
          的，`text' 属性会存放元素的开始标记及其第一个子元素或结束标记
          之间的文本，或者为 ‘None’，而 `tail' 属性会存放元素的结束标记
          及下一个标记之间的文本，或者为 ‘None’。 对于 XML 数据

               <a><b>1<c>2<d/>3</c></b>4</a>

          `a' 元素的 `text' 和 `tail' 属性均为 ‘None’，`b' 元素的 `text'
          为 ‘"1"’ 而 `tail' 为 ‘"4"’，`c' 元素的 `text' 为 ‘"2"’ 而
          `tail' 为 ‘None’，`d' 元素的 `text' 为 ‘None’ 而 `tail' 为
          ‘"3"’。

          要获取一个元素的内部文本，请参阅 *note itertext(): c25.，例如
          ‘"".join(element.itertext())’。

          应用程序可以将任意对象存入这些属性。

      -- 屬性: attrib

          一个包含元素属性的字典。 请注意虽然 `attrib' 值总是一个真正可
          变的 Python 字典，但 ElementTree 实现可以选择其他内部表示形式
          ，并只在有需要时才创建字典。 为了发挥这种实现的优势，请在任何
          可能情况下使用下列字典方法。

     以下字典类方法作用于元素属性。

      -- 成員函式: clear ()

          重设一个元素。 此方法会移除所有子元素，清空所有属性，并将 text
          和 tail 属性设为 ‘None’。

      -- 成員函式: get (key, default=None)

          获取名为 `key' 的元素属性。

          返回属性的值，或者如果属性未找到则返回 `default'。

      -- 成員函式: items ()

          将元素属性以 (name, value) 对序列的形式返回。 所返回属性的顺序
          任意。

      -- 成員函式: keys ()

          将元素属性名称以列表的形式返回。 所返回名称的顺序任意。

      -- 成員函式: set (key, value)

          将元素的 `key' 属性设为 `value'。

     以下方法作用于元素的下级（子元素）。

      -- 成員函式: append (subelement)

          将元素 `subelement' 添加到此元素的子元素内部列表。 如果
          `subelement' 不是一个 *note Element: 21d. 则会引发 *note
          TypeError: 1fe.。

      -- 成員函式: extend (subelements)

          使用具有零个或多个元素的序列对象添加 `subelements'。 如果某个
          子元素不是 *note Element: 21d. 则会引发 *note TypeError: 1fe.。

          3.2 版新加入.

      -- 成員函式: find (match, namespaces=None)

          查找第一个匹配 `match' 的子元素。 `match' 可以是一个标记名称或
          者 *note 路径: 51d.。 返回一个元素实例或 ‘None’。 `namespaces'
          是可选的从命名空间前缀到完整名称的映射。 传入 ‘''’ 作为前缀可
          将表达式中所有无前缀的标记名称移动到给定的命名空间。

      -- 成員函式: findall (match, namespaces=None)

          根据标记名称或者 *note 路径: 51d. 查找所有匹配的子元素。 返回
          一个包含所有匹配元素按文档顺序排序的列表。 `namespaces' 是可选
          的从命名空间前缀到完整名称的映射。 传入 ‘''’ 作为前缀可将表达
          式中所有无前缀的标记名称移动到给定的命名空间。

      -- 成員函式: findtext (match, default=None, namespaces=None)

          查找第一个匹配 `match' 的子元素的文本。 `match' 可以是一个标记
          名称或者 *note 路径: 51d.。 反回第一个匹配的元素的文本内容，或
          者如果元素未找到则返回 `default'。 请注意如果匹配的元素没有文
          本内容则会返回一个空字符串。 `namespaces' 是可选的从命名空间前
          缀到完整名称的映射。 传入 ‘''’ 作为前缀可将表达式中所有无前缀
          的标记名称移动到给定的命名空间。

      -- 成員函式: insert (index, subelement)

          将 `subelement' 插入到此元素的给定位置中。 如果 `subelement' 不
          是一个 *note Element: 21d. 则会引发 *note TypeError: 1fe.。

      -- 成員函式: iter (tag=None)

          创建一个以当前元素为根元素的树的 *note iterator: 1171.。 该迭
          代器将以文档（深度优先）顺序迭代此元素及其所有下级元素。 如果
          `tag' 不为 ‘None’ 或 ‘'*'’，则迭代器只返回标记为 `tag' 的元素
          。 如果树结构在迭代期间被修改，则结果是未定义的。

          3.2 版新加入.

      -- 成員函式: iterfind (match, namespaces=None)

          根据标记名称或者 *note 路径: 51d. 查找所有匹配的子元素。 返回
          一个按文档顺序产生所有匹配元素的可迭代对象。 `namespaces' 是可
          选的从命名空间前缀到完整名称的映射。

          3.2 版新加入.

      -- 成員函式: itertext ()

          创建一个文本迭代器。 该迭代器将按文档顺序遍历此元素及其所有子
          元素，并返回所有内部文本。

          3.2 版新加入.

      -- 成員函式: makeelement (tag, attrib)

          创建一个与此元素类型相同的新元素对象。 请不要调用此方法，而应
          改用 *note SubElement(): 2b4d. 工厂函数。

      -- 成員函式: remove (subelement)

          从元素中移除 `subelement'。 与 find* 方法不同的是此方法会基于
          实例的标识来比较元素，而不是基于标记的值或内容。

     *note Element: 21d. 对象还支持下列序列类型方法以配合子元素使用:
     *note __delitem__(): d2b, *note __getitem__(): 3a5, *note
     __setitem__(): d2a, *note __len__(): e90.。

     注意：不带子元素的元素将被检测为 ‘False’。 此行为将在未来的版本中发
     生变化。 请改用 ‘len(elem)’ 或 ‘elem is None’ 进行检测。

          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")

     在 Python 3.8 之前，元素的 XML 属性的序列化顺序会通过按其名称排序来
     强制使其可被预期。 由于现在字典已保证是有序的，这个强制重排序在
     Python 3.8 中已被移除以保留原本由用户代码解析或创建的属性顺序。

     通常，用户代码应当尽量不依赖于特定的属性顺序，因为 XML 信息设定(1)
     明确地排除了用属性顺序转递信息的做法。 代码应当准备好处理任何输入顺
     序。 对于要求确定性的 XML 输出的情况，例如加密签名或检测数据集等，
     可以通过规范化 *note canonicalize(): 2b56. 函数来进行传统的序列化。

     对于规范化输出不可用但仍然要求输出特定属性顺序的情况，代码应当设法
     直接按要求的顺序来创建属性，以避免代码阅读者产生不匹配的感觉。 如果
     这一点是难以做到的，可以在序列化之前应用以下写法来强制实现顺序不依
     赖于元素的创建:

          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)

   ---------- Footnotes ----------

   (1) https://www.w3.org/TR/xml-infoset/


File: python.info,  Node: ElementTree 对象,  Next: QName 对象,  Prev: 元素对象,  Up: 参考引用<2>

5.20.5.20 ElementTree 对象
..........................

 -- 類別: xml.etree.ElementTree.ElementTree (element=None, file=None)

     ElementTree 包装器类。 这个类表示一个完整的元素层级结构，并添加了一
     些对于标准 XML 序列化的额外支持。

     `element' 是根元素。 如果给出 XML `file' 则将使用其内容来初始化树结
     构。

      -- 成員函式: _setroot (element)

          替换该树结构的根元素。 这将丢弃该树结构的当前内容，并将其替换
          为给定的元素。 请小心使用。 `element' 是一个元素实例。

      -- 成員函式: find (match, namespaces=None)

          与 *note Element.find(): 2b45. 类似，从树的根节点开始。

      -- 成員函式: findall (match, namespaces=None)

          与 *note Element.findall(): 2b44. 类似，从树的根节点开始。

      -- 成員函式: findtext (match, default=None, namespaces=None)

          与 *note Element.findtext(): 2b6f. 类似，从树的根节点开始。

      -- 成員函式: getroot ()

          返回这个树的根元素。

      -- 成員函式: iter (tag=None)

          创建并返回根元素的树结构迭代器。 该迭代器会以节顺序遍历这个树
          的所有元素。 `tag' 是要查找的标记（默认返回所有元素）。

      -- 成員函式: iterfind (match, namespaces=None)

          与 *note Element.iterfind(): c24. 类似，从树的根节点开始。

          3.2 版新加入.

      -- 成員函式: parse (source, parser=None)

          将一个外部 XML 节载入到此元素树。 `source' 是一个文件名或
          *note file object: c14.。 `parser' 是可选的解析器实例。 如果未
          给出，则会使用标准的 *note XMLParser: 37c. 解析器。 返回该节的
          根元素。

      -- 成員函式: write (file, encoding="us-ascii",
               xml_declaration=None, default_namespace=None,
               method="xml", *, short_empty_elements=True)

          将元素树以 XML 格式写入到文件。 `file' 为文件名，或是以写入模
          式打开的 *note file object: c14.。 `encoding' (1) 为输出编码格
          式 (默认为 US-ASCII)。 `xml_declaration' 控制是否要将 XML 声明
          添加到文件中。 使用 ‘False’ 表示从不添加，‘True’ 表示总是添加
          ，‘None’ 表示仅在非 US-ASCII 或 UTF-8 或 Unicode 时添加 (默认
          为 ‘None’)。 `default_namespace' 设置默认 XML 命名空间 (用于
          "xmlns")。 `method' 为 ‘"xml"’, ‘"html"’ 或 ‘"text"’ (默认为
          ‘"xml"’)。 仅限关键字形参 `short_empty_elements' 控制不包含内
          容的元素的格式。 如为 ‘True’ (默认值)，它们会被输出为单个自结
          束标记，否则它们会被输出为一对开始/结束标记。

          输出是一个字符串 (*note str: 205.) 或字节串 (*note bytes:
          172.)。 由*encoding* 参数来控制。 如果 `encoding' 为
          ‘"unicode"’，则输出是一个字符串；否则为字节串；请注意这可能与
          `file' 的类型相冲突，如果它是一个打开的 *note file object:
          c14. 的话；请确保你不会试图写入字符串到二进制流或者反向操作。

          3.4 版新加入: `short_empty_elements' 形参。

          3.8 版更變: *note write(): 9fd. 方法现在会保留用户指定的属性顺
          序。

这是将要被操作的 XML 文件:

     <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>

修改第一段中的每个链接的 "target" 属性的示例:

     >>> 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")

   ---------- Footnotes ----------

   (1) (1) 包括在 XML 输出中的编码格式字符串应当符合适当的标准。 例如
"UTF-8" 是有效的，但 "UTF8" 是无效的。 请参阅
‘https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl’ 和
‘https://www.iana.org/assignments/character-sets/character-sets.xhtml’。


File: python.info,  Node: QName 对象,  Next: TreeBuilder 对象,  Prev: ElementTree 对象,  Up: 参考引用<2>

5.20.5.21 QName 对象
....................

 -- 類別: xml.etree.ElementTree.QName (text_or_uri, tag=None)

     QName 包装器。 这可被用来包装 QName 属性值，以便在输出中获得适当的
     命名空间处理。 `text_or_uri' 是一个包含 QName 值的字符串，其形式为
     {uri}local，或者如果给出了 tag 参数，则为 QName 的 URI 部分。 如果
     给出了 `tag'，则第一个参数会被解读为 URI，而这个参数会被解读为本地
     名称。 *note QName: 2b7e. 实例是不透明的。


File: python.info,  Node: TreeBuilder 对象,  Next: XMLParser对象,  Prev: QName 对象,  Up: 参考引用<2>

5.20.5.22 TreeBuilder 对象
..........................

 -- 類別: 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 类格式的解析器来构建元素结构。

     如果给出 `element_factory'，它必须为接受两个位置参数的可调用对象：
     一个标记和一个属性字典。 它预期会返回一个新的元素实例。

     如果给出 `comment_factory' 和 `pi_factory' 函数，它们的行为应当像
     *note Comment(): 2b57. 和 *note ProcessingInstruction(): 2b5d. 函数
     一样创建注释和处理指令。 如果未给出，则将使用默认工厂函数。 当
     `insert_comments' 和/或 `insert_pis' 为真值时，如果 comments/pis 在
     根元素之中（但不在其之外）出现则它们将被插入到树中。

      -- 成員函式: close ()

          刷新构建器缓存，并返回最高层级的文档元素。 返回一个 *note
          Element: 21d. 实例。

      -- 成員函式: data (data)

          将文本添加到当前元素。 `data' 为要添加的文本。 这应当是一个字
          节串或 Unicode 字符串。

      -- 成員函式: end (tag)

          关闭当前元素。 `tag' 是元素名称。 返回已关闭的元素。

      -- 成員函式: start (tag, attrs)

          打开一个新元素。 `tag' 是元素名称。 `attrs' 是包含元素属性的字
          典。 返回打开的元素。

      -- 成員函式: comment (text)

          使用给定的 `text' 创建一条注释。 如果 ‘insert_comments’ 为真值
          ，这还会将其添加到树结构中。

          3.8 版新加入.

      -- 成員函式: pi (target, text)

          使用给定的 `target' 名称和 `text' 创建一条注释。 如果
          ‘insert_pis’ 为真值，这还会将其添加到树结构中。

          3.8 版新加入.

     此外，自定义的 *note TreeBuilder: 37d. 对象还提供了以下方法:

      -- 成員函式: doctype (name, pubid, system)

          处理一条 doctype 声明。 `name' 为 doctype 名称。 `pubid' 为公
          有标识。 `system' 为系统标识。 此方法不存在于默认的 *note
          TreeBuilder: 37d. 类中。

          3.2 版新加入.

      -- 成員函式: start_ns (prefix, uri)

          在定义了 ‘start()’ 回调的打开元素的该回调被调用之前，当解析器
          遇到新的命名空间声明时都会被调用。 `prefix' 对于默认命名空间为
          ‘''’ 或者在其他情况下为被声明的命名空间前缀名称。 `uri' 是命名
          空间 URI。

          3.8 版新加入.

      -- 成員函式: end_ns (prefix)

          在声明了命名空间前缀映射的元素的 ‘end()’ 回调之后被调用，附带
          超出作用域的 `prefix' 的名称。

          3.8 版新加入.

 -- 類別: 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(1) 写入器。 其参数与 *note canonicalize(): 2b56. 函数的相
     同。 这个类并不会构建树结构而是使用 `write' 函数将回调事件直接转换
     为序列化形式。

     3.8 版新加入.

   ---------- Footnotes ----------

   (1) https://www.w3.org/TR/xml-c14n2/


File: python.info,  Node: XMLParser对象,  Next: XMLPullParser对象,  Prev: TreeBuilder 对象,  Up: 参考引用<2>

5.20.5.23 XMLParser对象
.......................

 -- 類別: xml.etree.ElementTree.XMLParser (*, target=None,
          encoding=None)

     这个类是此模块的低层级构建单元。 它使用 *note xml.parsers.expat:
     141. 来实现高效、基于事件的 XML 解析。 它可以通过 *note feed():
     2b8a. 方法增量式地收受 XML 数据，并且解析事件会被转换为推送式 API
     —— 通过在 `target' 对象上发起对回调的调用。 如果省略 `target'，则会
     使用标准的 *note TreeBuilder: 37d.。 如果给出了 `encoding' (1) ，该
     值将覆盖在 XML 文件中指定的编码格式。

     3.8 版更變: 所有形参现在都是 *note 仅限关键字形参: 3ce.。 `html' 参
     数不再受支持。

      -- 成員函式: close ()

          结束向解析器提供数据。 返回调用在构造期间传入的 `target' 的
          ‘close()’ 方法的结果；在默认情况下，这是最高层级的文档元素。

      -- 成員函式: feed (data)

          将数据送入解析器。 `data' 是编码后的数据。

     *note XMLParser.feed(): 2b8a. 会为每个打开的标记调用 `target' 的
     ‘start(tag, attrs_dict)’ 方法，为每个关闭的标记调用它的 ‘end(tag)’
     方法，并通过 ‘data(data)’ 方法来处理数据。 有关更多受支持的回调方法
     ，请参阅 *note TreeBuilder: 37d. 类。 *note XMLParser.close():
     2b8b. 会调用 `target' 的 ‘close()’ 方法。 *note XMLParser: 37c. 不
     仅仅可被用来构建树结构。 下面是一个统计 XML 文件最大深度的示例:

          >>> 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

   ---------- Footnotes ----------

   (1) (1) 包括在 XML 输出中的编码格式字符串应当符合适当的标准。 例如
"UTF-8" 是有效的，但 "UTF8" 是无效的。 请参阅
‘https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl’ 和
‘https://www.iana.org/assignments/character-sets/character-sets.xhtml’。


File: python.info,  Node: XMLPullParser对象,  Next: 异常<14>,  Prev: XMLParser对象,  Up: 参考引用<2>

5.20.5.24 XMLPullParser对象
...........................

 -- 類別: xml.etree.ElementTree.XMLPullParser (events=None)

     适用于非阻塞应用程序的拉取式解析器。 它的输入侧 API 与 *note
     XMLParser: 37c. 的类似，但不是向回调目标推送调用，*note
     XMLPullParser: 9f9. 会收集一个解析事件的内部列表并让用户来读取它。
     `events' 是要报告的事件序列。 受支持的事件字符串有 ‘"start"’,
     ‘"end"’, ‘"comment"’, ‘"pi"’, ‘"start-ns"’ 和 ‘"end-ns"’ ("ns" 事件
     被用于获取详细的命名空间信息)。 如果 `events' 被省略，则只报告
     ‘"end"’ 事件。

      -- 成員函式: feed (data)

          将给定的字节数据送入解析器。

      -- 成員函式: close ()

          通知解析器数据流已终结。 不同于 *note XMLParser.close():
          2b8b.，此方法总是返回 *note None: 203.。 当解析器被关闭时任何
          还未被获取的事件仍可通过 *note read_events(): 2b42. 被读取。

      -- 成員函式: read_events ()

          返回包含在送入解析器的数据中遇到的事件的迭代器。 此迭代器会产
          生 ‘(event, elem)’ 对，其中 `event' 是代表事件类型的字符串 (例
          如 ‘"end"’) 而 `elem' 是遇到的 *note Element: 21d. 对象，或者
          以下的其他上下文值。

             * ‘start’, ‘end’: 当前元素。

             * ‘comment’, ‘pi’: 当前注释 / 处理指令

             * ‘start-ns’: 一个指定所声明命名空间映射的元组 ‘(prefix,
               uri)’。

             * ‘end-ns’: *note None: 203. (这可能在未来版本中改变)

          在之前对 *note read_events(): 2b42. 的调用中提供的事件将不会被
          再次产生。 事件仅当它们从迭代器中被取出时才会在内部队列中被消
          费，因此多个读取方对获取自 *note read_events(): 2b42. 的迭代器
          进行平行迭代将产生无法预料的结果。

          備註: *note XMLPullParser: 9f9. 只会确保当发出 "start" 事件时
          看到了开始标记的 ">" 字符，因而在这个点上属性已被定义，但文本
          内容和末尾属性还未被定义。 这同样适用于元素的下级；它们可能存
          在也可能不存在。

          如果你需要已完全填充的元素，请改为查找 "end" 事件。

     3.4 版新加入.

     3.8 版更變: 增加了 ‘comment’ 和 ‘pi’ 事件。


File: python.info,  Node: 异常<14>,  Prev: XMLPullParser对象,  Up: 参考引用<2>

5.20.5.25 异常
..............

 -- 類別: xml.etree.ElementTree.ParseError

     XML 解析器错误，由此模块中的多个解析方法在解析失败时引发。 此异常的
     实例的字符串表示将包含用户友好的错误消息。 此外，它将具有下列可用属
     性:

      -- 屬性: code

          来自外部解析器的数字错误代码。 请参阅 *note xml.parsers.expat:
          141. 的文档查看错误代码列表及它们的含义。

      -- 屬性: position

          一个包含 `line', `column' 数值的元组，指明错误发生的位置。

註解
....


File: python.info,  Node: xml dom --- 文档对象模型 API,  Next: xml dom minidom --- 最小化的 DOM 实现,  Prev: xml etree ElementTree --- ElementTree XML API,  Up: 结构化标记处理工具

5.20.6 ‘xml.dom’ — 文档对象模型 API
-----------------------------------

`源代码:' Lib/xml/dom/__init__.py(1)

__________________________________________________________________

文档对象模型“DOM”是一个来自万维网联盟（W3C）的跨语言 API，用于访问和修改
XML 文档。 DOM 的实现将 XML 文档以树结构表示，或者允许客户端代码从头构建
这样的结构。 然后它会通过一组提供通用接口的对象赋予对结构的访问权。

DOM 特别适用于进行随机访问的应用。 SAX 仅允许你每次查看文档的一小部分。
如果你正在查看一个 SAX 元素，你将不能访问其他元素。 如果你正在查看一个文
本节点，你将不能访问包含它的元素。 当你编写一个 SAX 应用时，你需要在你自
己的代码的某个地方记住你的程序在文档中的位置。 SAX 不会帮你做这件事。 并
且，如果你想要在 XML 文档中向前查看，你是绝对办不到的。

有些应用程序在不能访问树的事件驱动模型中是根本无法编写的。 当然你可以在
SAX 事件中自行构建某种树，但是 DOM 可以使你避免编写这样的代码。 DOM 是针
对 XML 数据的标准树表示形式。

文档对象模型是由 W3C 分阶段定义的，在其术语中称为“层级”。 Python 中该
API 的映射大致是基于 DOM 第 2 层级的建议。

DOM 应用程序通常从将某些 XML 解析为 DOM 开始。 此操作如何实现完全未被
DOM 第 1 层级所涉及，而第 2 层级也只提供了有限的改进：有一个
‘DOMImplementation’ 对象类，它提供对 ‘Document’ 创建方法的访问，但却没有
办法以不依赖具体实现的方式访问 XML 读取器/解析器/文档创建器。 也没有当不
存在 ‘Document’ 对象的情况下访问这些方法的定义良好的方式。 在 Python 中
，每个 DOM 实现将提供一个函数 *note getDOMImplementation(): 2b94.。 DOM
第 3 层级增加了一个载入/存储规格说明，它定义了与读取器的接口，但这在
Python 标准库中尚不可用。

一旦你得到了 DOM 文档对象，你就可以通过 XML 文档的属性和方法访问它的各个
部分。 这些属性定义在 DOM 规格说明当中；参考指南的这一部分描述了 Python
对此规格说明的解读。

W3C 提供的规格说明定义了适用于 Java, ECMAScript 和 OMG IDL 的 DOM API。
这里定义的 Python 映射很大程度上是基于此规格说明的 IDL 版本，但并不要求
严格映射（但具体实现可以自由地支持对 IDL 的严格映射）。 请参阅 *note
一致性: 2b95. 一节查看有关映射要求的详细讨论。

也參考
......

文档对象模型 (DOM) 第 2 层级规格说明(2)

     被 Python DOM API 作为基础的 W3C 建议。

文档对象模型 (DOM) 第 1 层级规格说明(3)

     被 *note xml.dom.minidom: 13e. 所支持的 W3C 针对 DOM 的建议。

Python 语言映射规格说明(4)

     此文档指明了从 OMG IDL 到 Python 的映射。

* Menu:

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

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/Lib/xml/dom/__init__.py

   (2) https://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/

   (3) https://www.w3.org/TR/REC-DOM-Level-1/

   (4) http://www.omg.org/cgi-bin/doc?formal/02-11-05.pdf


File: python.info,  Node: 模块内容<6>,  Next: DOM 中的对象,  Up: xml dom --- 文档对象模型 API

5.20.6.1 模块内容
.................

*note xml.dom: 13d. 包含下列函数:

 -- 函式: xml.dom.registerDOMImplementation (name, factory)

     注册 `factory' 函数并使用名称 `name'。 该工厂函数应当返回一个实现了
     ‘DOMImplementation’ 接口的对象。 该工厂函数可每次都返回相同对象，或
     每次调用都返回新的对象，视具体实现的要求而定（例如该实现是否支持某
     些定制功能）。

 -- 函式: xml.dom.getDOMImplementation (name=None, features=())

     返回一个适当的 DOM 实现。 `name' 是通用名称、DOM 实现的模块名称或者
     ‘None’。 如果它不为 ‘None’，则会导入相应模块并在导入成功时返回一个
     ‘DOMImplementation’ 对象。 如果没有给出名称，并且如果设置了
     ‘PYTHON_DOM’ 环境变量，此变量会被用来查找相应的实现。

     如果未给出 name，此函数会检查可用的实现来查找具有所需特性集的一个。
     如果找不到任何实现，则会引发 *note ImportError: 16c.。 features 集
     必须是包含 ‘(feature, version)’ 对的序列，它会被传给可用的
     ‘DOMImplementation’ 对象上的 ‘hasFeature()’ 方法。

还提供了一些便捷常量:

 -- Data: xml.dom.EMPTY_NAMESPACE

     该值用于指明没有命名空间被关联到 DOM 中的某个节点。 它通常被作为某
     个节点的 ‘namespaceURI’，或者被用作某个命名空间专属方法的
     `namespaceURI' 参数。

 -- Data: xml.dom.XML_NAMESPACE

     关联到保留前缀 ‘xml’ 的命名空间 URI，如 XML 中的命名空间(1) （第 4
     节） 所定义的。

 -- Data: xml.dom.XMLNS_NAMESPACE

     命名空间声明的命名空间 URI，如 文档对象模型 (DOM) 第 2 层级核心规格
     说明(2) (第 1.1.8节) 所定义的。

 -- Data: xml.dom.XHTML_NAMESPACE

     XHTML 命名空间的 URI，如 XHTML 1.0: 扩展超文本标记语言(3) (第 3.1.1
     节) 所定义的。

此外，*note xml.dom: 13d. 还包含一个基本 ‘Node’ 类和一些 DOM 异常类。 此
模块提供的 ‘Node’ 类未实现 DOM 规格描述所定义的任何方法和属性；实际的
DOM 实现必须提供它们。 提供 ‘Node’ 类作为此模块的一部分并没有提供用于实
际的 ‘Node’ 对象的 ‘nodeType’ 属性的常量；它们是位于类内而不是位于模块层
级以符合 DOM 规格描述。

   ---------- Footnotes ----------

   (1) https://www.w3.org/TR/REC-xml-names/

   (2) https://www.w3.org/TR/DOM-Level-2-Core/core.html

   (3) https://www.w3.org/TR/xhtml1/


File: python.info,  Node: DOM 中的对象,  Next: 一致性,  Prev: 模块内容<6>,  Up: xml dom --- 文档对象模型 API

5.20.6.2 DOM 中的对象
.....................

DOM 的权威文档是来自 W3C 的 DOM 规格描述。

请注意，DOM 属性也可以作为节点而不是简单的字符串进行操作。 然而，必须这
样做的情况相当少见，所以这种用法还没有被写入文档。

接口                                 部件                                    目的
                                                                             
-------------------------------------------------------------------------------------------------------------------
                                                                             
‘DOMImplementation’                  *note DOMImplementation 对象: 2b9e.     底层实现的接口。
                                                                             
                                                                             
‘Node’                               *note 节点对象: 2b9f.                   文档中大多数对象的基本接口。
                                                                             
                                                                             
‘NodeList’                           *note 节点列表对象: 2ba0.               节点序列的接口。
                                                                             
                                                                             
‘DocumentType’                       *note 文档类型对象: 2ba1.               有关处理文档所需声明的信息。
                                                                             
                                                                             
‘Document’                           *note Document 对象: 2ba2.              表示整个文档的对象。
                                                                             
                                                                             
‘Element’                            *note 元素对象: 2ba3.                   文档层次结构中的元素节点。
                                                                             
                                                                             
‘Attr’                               *note Attr 对象: 2ba4.                  元素节点上的属性值节点。
                                                                             
                                                                             
‘Comment’                            *note 注释对象: 2ba5.                   源文档中注释的表示形式。
                                                                             
                                                                             
‘Text’                               *note Text 和 CDATASection 对象: 2ba6.  包含文档中文本内容的节点。
                                                                             
                                                                             
‘ProcessingInstruction’              *note ProcessingInstruction 对象: 2ba7. 处理指令表示形式。
                                                                             

描述在 Python 中使用 DOM 定义的异常的小节。

* Menu:

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


File: python.info,  Node: DOMImplementation 对象,  Next: 节点对象,  Up: DOM 中的对象

5.20.6.3 DOMImplementation 对象
...............................

‘DOMImplementation’ 接口提供了一种让应用程序确定他们所使用的 DOM 中某一
特性可用性的方式。 DOM 第 2 级还添加了使用 ‘DOMImplementation’ 来创建新
的 ‘Document’ 和 ‘DocumentType’ 对象的能力。

 -- 成員函式: DOMImplementation.hasFeature (feature, version)

     如果字符串对 `feature' 和 `version' 所标识的特性已被实现则返回
     ‘True’。

 -- 成員函式: DOMImplementation.createDocument (namespaceUri,
          qualifiedName, doctype)

     返回一个新的 ‘Document’ 对象 (DOM 的根节点)，包含一个具有给定
     `namespaceUri' 和 `qualifiedName' 的下级 ‘Element’ 对象。 `doctype'
     必须为由 *note createDocumentType(): 2bab. 创建的 ‘DocumentType’ 对
     象，或者为 ‘None’。 在 Python DOM API 中，前两个参数也可为 ‘None’ 以
     表示不要创建任何下级 ‘Element’。

 -- 成員函式: DOMImplementation.createDocumentType (qualifiedName,
          publicId, systemId)

     返回一个新的封装了给定 `qualifiedName', `publicId' 和 `systemId' 字
     符串的 ‘DocumentType’ 对象，它表示包含在 XML 文档类型声明中的信息。


File: python.info,  Node: 节点对象,  Next: 节点列表对象,  Prev: DOMImplementation 对象,  Up: DOM 中的对象

5.20.6.4 节点对象
.................

XML 文档的所有组成部分都是 ‘Node’ 的子类。

 -- 屬性: Node.nodeType

     一个代表节点类型的整数。 类型符号常量在 ‘Node’ 对象上:
     ‘ELEMENT_NODE’, ‘ATTRIBUTE_NODE’, ‘TEXT_NODE’,
     ‘CDATA_SECTION_NODE’, ‘ENTITY_NODE’, ‘PROCESSING_INSTRUCTION_NODE’,
     ‘COMMENT_NODE’, ‘DOCUMENT_NODE’, ‘DOCUMENT_TYPE_NODE’,
     ‘NOTATION_NODE’。 这是个只读属性。

 -- 屬性: Node.parentNode

     当前节点的上级，或者对于文档节点则为 ‘None’。 该值总是一个 ‘Node’ 对
     象或者 ‘None’。 对于 ‘Element’ 节点，这将为上级元素，但对于根元素例
     外，在此情况下它将为 ‘Document’ 对象。 对于 ‘Attr’ 节点，它将总是为
     ‘None’。 这是个只读属性。

 -- 屬性: Node.attributes

     属性对象的 ‘NamedNodeMap’。 这仅对元素才有实际值；其它对象会为该属
     性提供 ‘None’ 值。 这是个只读属性。

 -- 屬性: Node.previousSibling

     在此节点之前具有相同上级的相邻节点。 例如结束标记紧接在在 `self' 元
     素的开始标记之前的元素。 当然，XML 文档并非只是由元素组成，因此之前
     相邻节点可以是文本、注释或者其他内容。 如果此节点是上级的第一个子节
     点，则该属性将为 ‘None’。 这是一个只读属性。

 -- 屬性: Node.nextSibling

     在此节点之后具有相同上级的相邻节点。 另请参见 *note
     previousSibling: 2bb0.。 如果此节点是上级的最后一个子节点，则该属性
     将为 ‘None’。 这是一个只读属性。

 -- 屬性: Node.childNodes

     包含在此节点中的节点列表。 这是一个只读属性。

 -- 屬性: Node.firstChild

     节点的第一个下级，如果有的话，否则为 ‘None’。 这是个只读属性。

 -- 屬性: Node.lastChild

     节点的最后一个下级，如果有的话，否则为 ‘None’。 这是个只读属性。

 -- 屬性: Node.localName

     ‘tagName’ 在冒号之后的部分，如果有冒号的话，否则为整个 ‘tagName’。
     该值为一个字符串。

 -- 屬性: Node.prefix

     ‘tagName’ 在冒号之前的部分，如果有冒号的话，否则为空字符串。 该值为
     一个字符串或者为 ‘None’。

 -- 屬性: Node.namespaceURI

     关联到元素名称的命名空间。 这将是一个字符串或为 ‘None’。 这是个只读
     属性。

 -- 屬性: Node.nodeName

     这对于每种节点类型具有不同的含义；请查看 DOM 规格说明来了解详情。 你
     总是可以从其他特征属性例如元素的 ‘tagName’ 特征属性或属性的 ‘name’
     特征属性获取你能从这里获取的信息。 对于所有节点类型，这个属性的值都
     将是一个字符串或为 ‘None’。 这是一个只读属性。

 -- 屬性: Node.nodeValue

     这对于每种节点类型具有不同的含义；请查看 DOM 规格说明来了解详情。 具
     体情况与 *note nodeName: 2bb8. 的类似。 该值是一个字符串或为
     ‘None’。

 -- 成員函式: Node.hasAttributes ()

     如果该节点具有任何属性则返回 ‘True’。

 -- 成員函式: Node.hasChildNodes ()

     如果该节点具有任何子节点则返回 ‘True’。

 -- 成員函式: Node.isSameNode (other)

     如果 `other' 指向的节点就是此节点则返回 ‘True’。 这对于使用了任何代
     理架构的 DOM 实现来说特别有用（因为多个对象可能指向相同节点）。

          備註: 这是基于已提议的 DOM 第 3 等级 API，目前尚处于“起草”阶段
          ，但这个特定接口看来并不存在争议。 来自 W3C 的修改将不会影响
          Python DOM 接口中的这个方法（不过针对它的任何新 W3C API 也将受
          到支持）。

 -- 成員函式: Node.appendChild (newChild)

     在子节点列表末尾添加一个新的子节点，返回 `newChild'。 如果节点已存
     在于树结构中，它将先被移除。

 -- 成員函式: Node.insertBefore (newChild, refChild)

     在现有的子节点之前插入一个新的子节点。 它必须属于 `refChild' 是这个
     节点的子节点的情况；如果不是，则会引发 *note ValueError: 16d.。
     `newChild' 会被返回。 如果 `refChild' 为 ‘None’，它会将 `newChild'
     插入到子节点列表的末尾。

 -- 成員函式: Node.removeChild (oldChild)

     移除一个子节点。 `oldChild' 必须是这个节点的子节点；如果不是，则会
     引发 *note ValueError: 16d.。 成功时 `oldChild' 会被返回。 如果
     `oldChild' 将不再被继续使用，则将调用它的 ‘unlink()’ 方法。

 -- 成員函式: Node.replaceChild (newChild, oldChild)

     将一个现有节点替换为新的节点。 这必须属于 `oldChild' 是该节点的子节
     点的情况；如果不是，则会引发 *note ValueError: 16d.。

 -- 成員函式: Node.normalize ()

     合并相邻的文本节点以便将所有文本段存储为单个 ‘Text’ 实例。 这可以简
     化许多应用程序处理来自 DOM 树文本的操作。

 -- 成員函式: Node.cloneNode (deep)

     克隆此节点。 设置 `deep' 表示也克隆所有子节点。 此方法将返回克隆的
     节点。


File: python.info,  Node: 节点列表对象,  Next: 文档类型对象,  Prev: 节点对象,  Up: DOM 中的对象

5.20.6.5 节点列表对象
.....................

‘NodeList’ 代表一个节点列表。 在 DOM 核心建议中这些对象有两种使用方式: 由
‘Element’ 对象提供作为其子节点列表，以及由 ‘Node’ 的
‘getElementsByTagName()’ 和 ‘getElementsByTagNameNS()’ 方法通过此接口返
回对象来表示查询结果。

DOM 第 2 层级建议为这些对象定义一个方法和一个属性:

 -- 成員函式: NodeList.item (i)

     从序列中返回第 `i' 项，如果序列不为空的话，否则返回 ‘None’。 索引号
     `i' 不允许小于零或大于等于序列的长度。

 -- 屬性: NodeList.length

     序列中的节点数量。

此外，Python DOM 接口还要求提供一些额外支持来允许将 ‘NodeList’ 对象用作
Python 序列。 所有 ‘NodeList’ 实现都必须包括对 *note __len__(): e90. 和
*note __getitem__(): 3a5. 的支持；这样 ‘NodeList’ 就允许使用 *note for:
cfa. 语句进行迭代并能正确地支持 *note len(): 28b. 内置函数。

如果一个 DOM 实现支持文档的修改，则 ‘NodeList’ 实现还必须支持 *note
__setitem__(): d2a. 和 *note __delitem__(): d2b. 方法。


File: python.info,  Node: 文档类型对象,  Next: Document 对象,  Prev: 节点列表对象,  Up: DOM 中的对象

5.20.6.6 文档类型对象
.....................

有关一个文档所声明的标注和实体的信息（包括解析器所使用并能提供信息的外部
子集）可以从 ‘DocumentType’ 对象获取。 文档的 ‘DocumentType’ 可从
‘Document’ 对象的 ‘doctype’ 属性中获取；如果一个文档没有 ‘DOCTYPE’ 声明
，则该文档的 ‘doctype’ 属性将被设为 ‘None’ 而非此接口的一个实例。

‘DocumentType’ 是 ‘Node’ 是专门化，并增加了下列属性:

 -- 屬性: DocumentType.publicId

     文档类型定义的外部子集的公有标识。 这将为一个字符串或者为 ‘None’。

 -- 屬性: DocumentType.systemId

     文档类型定义的外部子集的系统标识。 这将为一个字符串形式的 URI，或者
     为 ‘None’。

 -- 屬性: DocumentType.internalSubset

     一个给出来自文档的完整内部子集的字符串。 这不包括子集外面的圆括号。
     如果文档没有内部子集，则应为 ‘None’。

 -- 屬性: DocumentType.name

     ‘DOCTYPE’ 声明中给出的根元素名称，如果有的话。

 -- 屬性: DocumentType.entities

     这是给出外部实体定义的 ‘NamedNodeMap’。 对于多次定义的实体名称，则
     只提供第一次的定义（其他的会按照 XML 建议被忽略）。 这可能为
     ‘None’，如果解析器未提供此信息，或者如果未定义任何实体的话。

 -- 屬性: DocumentType.notations

     这是给出标注定义的 ‘NamedNodeMap’。 对于多次定义的标注，则只提供第
     一次的定义（其他的会按照 XML 建议被忽略）。 这可能为 ‘None’，如果解
     析器未提供此信息，或者如果未定义任何标注的话。


File: python.info,  Node: Document 对象,  Next: 元素对象<2>,  Prev: 文档类型对象,  Up: DOM 中的对象

5.20.6.7 Document 对象
......................

‘Document’ 代表一个完整的 XML 文档，包括其组成元素、属性、处理指令和注释
等。 请记住它会继承来自 ‘Node’ 的属性。

 -- 屬性: Document.documentElement

     文档唯一的根元素。

 -- 成員函式: Document.createElement (tagName)

     创建并返回一个新的元素节点。 当元素被创建时不会被插入到文档中。 你
     需要通过某个其他方法例如 ‘insertBefore()’ 或 ‘appendChild()’ 来显示
     地插入它。

 -- 成員函式: Document.createElementNS (namespaceURI, tagName)

     创建并返回一个新的带有命名空间的元素。 `tagName' 可以带有前缀。 当
     元素被创建时不会被插入到文档中。 你需要通过某个其他方法例如
     ‘insertBefore()’ 或 ‘appendChild()’ 来显式地插入它。

 -- 成員函式: Document.createTextNode (data)

     创建并返回一个包含作为形参被传入的数据的文本节点。 与其他创建方法一
     样，此方法不会将节点插入到树中。

 -- 成員函式: Document.createComment (data)

     创建并返回一个包含作为形参被传入的数据的注释节点。 与其他创建方法一
     样，此方法不会将节点插入到树中。

 -- 成員函式: Document.createProcessingInstruction (target, data)

     创建并返回一个包含作为形参被传入的 `target' 和 `data' 的处理指令节
     点。 与其他创建方法一样，此方法不会将节点插入到树中。

 -- 成員函式: Document.createAttribute (name)

     创建并返回一个属性节点。 此方法不会将属性节点关联到任何特定的元素。
     你必须在正确的 ‘Element’ 对象上使用 ‘setAttributeNode()’ 来使用新创
     建的属性实例。

 -- 成員函式: Document.createAttributeNS (namespaceURI, qualifiedName)

     创建并返回一个带有命名空间的属性节点。 `tagName' 可以带有前缀。 此
     方法不会将属性节点关联到任何特定的元素。 你必须在正确的 ‘Element’ 对
     象上使用 ‘setAttributeNode()’ 来使用新创建的属性实例。

 -- 成員函式: Document.getElementsByTagName (tagName)

     搜索全部具有特定元素类型名称的后继元素（直接下级、下级的下级等等）
     。

 -- 成員函式: Document.getElementsByTagNameNS (namespaceURI, localName)

     搜索全部具有特定命名空间 URI 和 localname 的后继元素（直接下级、下
     级的下级等等）。 localname 是命名空间在前缀之后的部分。


File: python.info,  Node: 元素对象<2>,  Next: Attr 对象,  Prev: Document 对象,  Up: DOM 中的对象

5.20.6.8 元素对象
.................

‘Element’ 是 ‘Node’ 的子类，因此会继承该类的全部属性。

 -- 屬性: Element.tagName

     元素类型名称。 在使用命名空间的文档中它可能包含冒号。 该值是一个字
     符串。

 -- 成員函式: Element.getElementsByTagName (tagName)

     与 ‘Document’ 类中的对应方法相同。

 -- 成員函式: Element.getElementsByTagNameNS (namespaceURI, localName)

     与 ‘Document’ 类中的对应方法相同。

 -- 成員函式: Element.hasAttribute (name)

     如果元素带有名称为 `name' 的属性则返回 ‘True’。

 -- 成員函式: Element.hasAttributeNS (namespaceURI, localName)

     如果元素带有名称为 `namespaceURI' 加 `localName' 的属性则返回
     ‘True’。

 -- 成員函式: Element.getAttribute (name)

     将名称为 `name' 的属性的值作为字符串返回。 如果指定属性不存在，则返
     回空字符串，就像该属性没有对应的值一样。

 -- 成員函式: Element.getAttributeNode (attrname)

     返回名称为 `attrname' 的属性对应的 ‘Attr’ 节点。

 -- 成員函式: Element.getAttributeNS (namespaceURI, localName)

     将名称为 `namespaceURI' 加 `localName' 的属性的值作为字符串返回。 如
     果指定属性不存在，则返回空字符串，就像该属性没有对应的值一样。

 -- 成員函式: Element.getAttributeNodeNS (namespaceURI, localName)

     将给定 `namespaceURI' 加 `localName' 的属性的值作为节点返回。

 -- 成員函式: Element.removeAttribute (name)

     移除指定名称的节点。 如果没有匹配的属性，则会引发 *note
     NotFoundErr: 2be3.。

 -- 成員函式: Element.removeAttributeNode (oldAttr)

     从属性列表中移除并返回 `oldAttr'，如果该属性存在的话。 如果
     `oldAttr' 不存在，则会引发 *note NotFoundErr: 2be3.。

 -- 成員函式: Element.removeAttributeNS (namespaceURI, localName)

     移除指定名称的属性。 请注意它是使用 localName 而不是 qname。 如果没
     有匹配的属性也不会引发异常。

 -- 成員函式: Element.setAttribute (name, value)

     将属性值设为指定的字符串。

 -- 成員函式: Element.setAttributeNode (newAttr)

     将一个新的属性节点添加到元素，当匹配到 ‘name’ 属性时如有必要会替换
     现有的属性。 如果发生了替换，将返回原有属性节点。 如果 `newAttr' 已
     经被使用，则会引发 *note InuseAttributeErr: 2be8.。

 -- 成員函式: Element.setAttributeNodeNS (newAttr)

     将一个新的属性节点添加到元素，当匹配到 ‘namespaceURI’ 和
     ‘localName’ 属性时如有必要会替换现有的属性。 如果发生了替换，将返回
     原有属性节点。 如果 `newAttr' 已经被使用，则会引发 *note
     InuseAttributeErr: 2be8.。

 -- 成員函式: Element.setAttributeNS (namespaceURI, qname, value)

     将属性值设为 `namespaceURI' 和 `qname' 所给出的字符串。 请注意
     qname 是整个属性名称。 这与上面的方法不同。


File: python.info,  Node: Attr 对象,  Next: NamedNodeMap 对象,  Prev: 元素对象<2>,  Up: DOM 中的对象

5.20.6.9 Attr 对象
..................

‘Attr’ 继承自 ‘Node’，因此会继承其全部属性。

 -- 屬性: Attr.name

     属性名称。 在使用命名空间的文档中可能会包括冒号。

 -- 屬性: Attr.localName

     名称在冒号之后的部分，如果有的话，否则为完整名称。 这是个只读属性。

 -- 屬性: Attr.prefix

     名称在冒号之前的部分，如果有冒号的话，否则为空字符串。

 -- 屬性: Attr.value

     属性的文本值。 这与 ‘nodeValue’ 属性同义。


File: python.info,  Node: NamedNodeMap 对象,  Next: 注释对象,  Prev: Attr 对象,  Up: DOM 中的对象

5.20.6.10 NamedNodeMap 对象
...........................

‘NamedNodeMap’ `不是' 继承自 ‘Node’。

 -- 屬性: NamedNodeMap.length

     属性列表的长度。

 -- 成員函式: NamedNodeMap.item (index)

     返回特定带有索引号的属性。 获取属性的顺序是强制规定的，但在 DOM 的
     生命期内会保持一致。 其中每一项均为属性节点。 可使用 ‘value’ 属性获
     取其值。

还有一些试验性方法给予这个类更多的映射行为。 你可以使用这些方法或者使用
‘Element’ 对象上标准化的 ‘getAttribute*()’ 方法族。


File: python.info,  Node: 注释对象,  Next: Text 和 CDATASection 对象,  Prev: NamedNodeMap 对象,  Up: DOM 中的对象

5.20.6.11 注释对象
..................

‘Comment’ 代表 XML 文档中的注释。 它是 ‘Node’ 的子类，但不能拥有下级节点
。

 -- 屬性: Comment.data

     注释的内容是一个字符串。 该属性包含在开头 ‘<!-’‘-’ 和末尾 ‘-’‘->’ 之
     间的所有字符，但不包括这两个符号。


File: python.info,  Node: Text 和 CDATASection 对象,  Next: ProcessingInstruction 对象,  Prev: 注释对象,  Up: DOM 中的对象

5.20.6.12 Text 和 CDATASection 对象
...................................

‘Text’ 接口代表 XML 文档中的文本。 如果解析器和 DOM 实现支持 DOM 的 XML
扩展，则包裹在 CDATA 标记的节中的部分会被存储到 ‘CDATASection’ 对象中。
这两个接口很相似，但是提供了不同的 ‘nodeType’ 属性值。

这些接口扩展了 ‘Node’ 接口。 它们不能拥有下级节点。

 -- 屬性: Text.data

     字符串形式的文本节点内容。

     備註: ‘CDATASection’ 节点的使用并不表示该节点代表一个完整的 CDATA 标
     记节，只是表示该节点的内容是 CDATA 节的一部分。 单个 CDATA 节可以由
     文档树中的多个节点来表示。 没有什么办法能确定两个相邻的
     ‘CDATASection’ 节点是否代表不同的 CDATA 标记节。


File: python.info,  Node: ProcessingInstruction 对象,  Next: 异常<15>,  Prev: Text 和 CDATASection 对象,  Up: DOM 中的对象

5.20.6.13 ProcessingInstruction 对象
....................................

代表 XML 文档中的处理指令。 它继承自 ‘Node’ 接口并且不能拥有下级节点。

 -- 屬性: ProcessingInstruction.target

     到第一个空格符为止的处理指令内容。 这是个只读属性。

 -- 屬性: ProcessingInstruction.data

     在第一个空格符之后的处理指令内容。


File: python.info,  Node: 异常<15>,  Prev: ProcessingInstruction 对象,  Up: DOM 中的对象

5.20.6.14 异常
..............

DOM 第 2 层级推荐定义一个异常 *note DOMException: 2bfd.，以及多个变量用
来允许应用程序确定发生了何种错误。 *note DOMException: 2bfd. 实例带有
*note code: 1a. 属性用来提供特定异常所对应的值。

Python DOM 接口提供了一些常量，但还扩展了异常集以使 DOM 所定义的每个异常
代码都存在特定的异常。 接口的具体实现必须引发正确的特定异常，它们各自带
有正确的 *note code: 1a. 属性值。

 -- 例外: xml.dom.DOMException

     所有特定 DOM 异常所使用的异常基类。 该异常类不可被直接实例化。

 -- 例外: xml.dom.DomstringSizeErr

     当指定范围的文本不能适配一个字符串时被引发。 此异常在 Python DOM 实
     现中尚不可用，但可从不是以 Python 编写的 DOM 实现中接收。

 -- 例外: xml.dom.HierarchyRequestErr

     当尝试插入一个节点但该节点类型不被允许时被引发。

 -- 例外: xml.dom.IndexSizeErr

     当一个方法的索引或大小参数为负值或超出允许的值范围时被引发。

 -- 例外: xml.dom.InuseAttributeErr

     当尝试插入一个 ‘Attr’ 节点但该节点已存在于文档中的某处时被引发。

 -- 例外: xml.dom.InvalidAccessErr

     当某个参数或操作在底层对象中不受支持时被引发。

 -- 例外: xml.dom.InvalidCharacterErr

     当某个字符串参数包含的字符在使用它的上下文中不被 XML 1.0 标准建议所
     允许时引发。 例如，尝试创建一个元素类型名称中带有空格的 ‘Element’ 节
     点将导致此错误被引发。

 -- 例外: xml.dom.InvalidModificationErr

     当尝试修改某个节点的类型时被引发。

 -- 例外: xml.dom.InvalidStateErr

     当尝试使用未定义或不再可用的的对象时被引发。

 -- 例外: xml.dom.NamespaceErr

     如果试图以 XML 中的命名空间(1) 建议所不允许的方式修改任何对象，则会
     引发此异常。

 -- 例外: xml.dom.NotFoundErr

     当某个节点不存在于被引用的上下文中时引发的异常。 例如，
     ‘NamedNodeMap.removeNamedItem()’ 将在所传入的节点不在于于映射中时引
     发此异常。

 -- 例外: xml.dom.NotSupportedErr

     当具体实现不支持所请求的对象类型或操作时被引发。

 -- 例外: xml.dom.NoDataAllowedErr

     当为某个不支持数据 的节点指定数据时被引发。

 -- 例外: xml.dom.NoModificationAllowedErr

     当尝试修改某个不允许修改的对象（例如只读节点）时被引发。

 -- 例外: xml.dom.SyntaxErr

     当指定了无效或非法的字符串时被引发。

 -- 例外: xml.dom.WrongDocumentErr

     当将某个节点插入非其当前所属的另一个文档，并且具体实现不支持从一个
     文档向一个文档迁移节点时被引发。

DOM 建议映射中针对上述异常而定义的异常代码如下表所示:

常量                                       异常
                                           
---------------------------------------------------------------------------------
                                           
‘DOMSTRING_SIZE_ERR’                       *note DomstringSizeErr: 2bfe.
                                           
                                           
‘HIERARCHY_REQUEST_ERR’                    *note HierarchyRequestErr: 2bff.
                                           
                                           
‘INDEX_SIZE_ERR’                           *note IndexSizeErr: 2c00.
                                           
                                           
‘INUSE_ATTRIBUTE_ERR’                      *note InuseAttributeErr: 2be8.
                                           
                                           
‘INVALID_ACCESS_ERR’                       *note InvalidAccessErr: 2c01.
                                           
                                           
‘INVALID_CHARACTER_ERR’                    *note InvalidCharacterErr: 2c02.
                                           
                                           
‘INVALID_MODIFICATION_ERR’                 *note InvalidModificationErr: 2c03.
                                           
                                           
‘INVALID_STATE_ERR’                        *note InvalidStateErr: 2c04.
                                           
                                           
‘NAMESPACE_ERR’                            *note NamespaceErr: 2c05.
                                           
                                           
‘NOT_FOUND_ERR’                            *note NotFoundErr: 2be3.
                                           
                                           
‘NOT_SUPPORTED_ERR’                        *note NotSupportedErr: 2c06.
                                           
                                           
‘NO_DATA_ALLOWED_ERR’                      *note NoDataAllowedErr: 2c07.
                                           
                                           
‘NO_MODIFICATION_ALLOWED_ERR’              *note NoModificationAllowedErr: 2c08.
                                           
                                           
‘SYNTAX_ERR’                               *note SyntaxErr: 2c09.
                                           
                                           
‘WRONG_DOCUMENT_ERR’                       *note WrongDocumentErr: 2c0a.
                                           

   ---------- Footnotes ----------

   (1) https://www.w3.org/TR/REC-xml-names/


File: python.info,  Node: 一致性,  Prev: DOM 中的对象,  Up: xml dom --- 文档对象模型 API

5.20.6.15 一致性
................

本节描述了 Python DOM API、W3C DOM 建议以及 Python 的 OMG IDL 映射之间的
一致性要求和关系。

* Menu:

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


File: python.info,  Node: 类型映射,  Next: 访问器方法,  Up: 一致性

5.20.6.16 类型映射
..................

将根据下表，将DOM规范中使用的IDL类型映射为Python类型。

IDL 类型               Python Type
                       
-----------------------------------------------------------------------
                       
‘boolean’              ‘bool’ 或 ‘int’
                       
                       
‘int’                  ‘int’
                       
                       
‘long int’             ‘int’
                       
                       
‘unsigned int’         ‘int’
                       
                       
‘DOMString’            ‘str’ 或 ‘bytes’
                       
                       
‘null’                 ‘None’
                       


File: python.info,  Node: 访问器方法,  Prev: 类型映射,  Up: 一致性

5.20.6.17 访问器方法
....................

从 OMG IDL 到 Python 的映射以类似于 Java 映射的方式定义了针对 IDL
‘attribute’ 声明的访问器函数。 映射以下 IDL 声明

     readonly attribute string someValue;
              attribute string anotherValue;

会产生三个访问器函数: ‘someValue’ 的 "get" 方法 (‘_get_someValue()’)，以
及 ‘anotherValue’ 的 "get" 和 "set" 方法 (‘_get_anotherValue()’ 和
‘_set_anotherValue()’)。 特别地，该映射不要求 IDL 属性像普通 Python 属性
那样可访问: ‘object.someValue’ `并非' 必须可用，并可能引发 *note
AttributeError: 4a1.。

但是，Python DOM API 则 `确实' 要求普通属性访问可用。 这意味着由 Python
IDL 解译器生成的典型代理有可能会不可用，如果 DOM 对象是通过 CORBA 来访问
则在客户端可能需要有包装对象。 虽然这确实要求为 CORBA DOM 客户端进行额外
的考虑，但具有从 Python 通过 CORBA 使用 DOM 经验的实现并不会认为这是个问
题。 已经声明了 ‘readonly’ 的属性不必在所有 DOM 实现中限制写入访问。

在 Python DOM API 中，访问器函数不是必须的。 如果提供，则它们应当采用由
Python IDL 映射所定义的形式，但这些方法会被认为不必要，因为这些属性可以
从 Python 直接访问。 永远都不要为 ‘readonly’ 属性提供 "set" 访问器。

IDL 定义没有完全体现 W3C DOM API 的要求，如特定对象的概念，又如
‘getElementsByTagName()’ 的返回值为 "live" 等。 Python DOM API 并不强制
具体实现执行这些要求。


File: python.info,  Node: xml dom minidom --- 最小化的 DOM 实现,  Next: xml dom pulldom --- 支持构建部分 DOM 树,  Prev: xml dom --- 文档对象模型 API,  Up: 结构化标记处理工具

5.20.7 ‘xml.dom.minidom’ — 最小化的 DOM 实现
--------------------------------------------

`源代码:' Lib/xml/dom/minidom.py(1)

__________________________________________________________________

*note xml.dom.minidom: 13e. 是文档对象模型接口的最小化实现，具有与其他语
言类似的 API。 它的目标是比完整 DOM 更简单并且更为小巧。 对于 DOM 还不十
分熟悉的用户则应当考虑改用 *note xml.etree.ElementTree: 140. 模块来进行
XML 处理。

     警告: *note xml.dom.minidom: 13e. 模块对于恶意构建的数据是不安全的
     。 如果你需要解析不受信任或未经身份验证的数据，请参阅 *note XML
     漏洞: 2b34.。

DOM 应用程序通常会从将某个 XML 解析为 DOM 开始。 使用 *note
xml.dom.minidom: 13e. 时，这是通过各种解析函数来完成的:

     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>')

*note parse(): 2c12. 函数可接受一个文件名或者打开的文件对象。

 -- 函式: xml.dom.minidom.parse (filename_or_file, parser=None,
          bufsize=None)

     根据给定的输入返回一个 ‘Document’。 `filename_or_file' 可以是一个文
     件名，或是一个文件类对象。 如果给定 `parser' 则它必须是一个 SAX2 解
     析器对象。 此函数将修改解析器的处理程序并激活命名空间支持；其他解析
     器配置（例如设置一个实体求解器）必须已经提前完成。

如果你将 XML 存放为字符串形式，则可以改用 *note parseString(): 2c13. 函
数:

 -- 函式: xml.dom.minidom.parseString (string, parser=None)

     返回一个代表 `string' 的 ‘Document’。 此方法会为指定字符串创建一个
     *note io.StringIO: 91a. 对象并将其传递给 *note parse(): 2c12.。

两个函数均返回一个代表文档内容的 ‘Document’ 对象。object representing
the content of the document.

*note parse(): 2c12. 和 *note parseString(): 2c13. 函数所做的是将 XML 解
析器连接到一个 "DOM 构建器"，它可以从任意 SAX 解析器接收解析事件并将其转
换为 DOM 树结构。 这两个函数的名称可能有些误导性，但在学习此接口时是很容
易掌握的。 文档解析操作将在这两个函数返回之前完成；简单地说这两个函数本
身并不提供解析器实现。

你也可以通过在一个 "DOM 实现" 对象上调用方法来创建 ‘Document’。 此对象可
通过调用 *note xml.dom: 13d. 包或者 *note xml.dom.minidom: 13e. 模块中的
‘getDOMImplementation()’ 函数来获取。 一旦你获得了一个 ‘Document’，你就
可以向它添加子节点来填充 DOM:

     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)

一旦你得到了 DOM 文档对象，你就可以通过其属性和方法访问对应 XML 文档的各
个部分。 这些属性定义在 DOM 规格说明当中；文档对象的主要特征属性是
‘documentElement’。 它给出了 XML 文档中的主元素：即包含了所有其他元素的
元素。 以下是一个示例程序:

     dom3 = parseString("<myxml>Some data</myxml>")
     assert dom3.documentElement.tagName == "myxml"

当你完成对一个 DOM 树的处理时，你可以选择调用 ‘unlink()’ 方法以鼓励尽早
清除不再需要的对象。 ‘unlink()’ 是 *note xml.dom.minidom: 13e. 针对 DOM
API 的专属扩展，它会将特定节点及其下级标记为不再有用。 在其他情况下，
Python 的垃圾回收器将负责最终处理树结构中的对象。

也參考
......

文档对象模型 (DOM) 第 1 层级规格说明(2)

     被 *note xml.dom.minidom: 13e. 所支持的 W3C 针对 DOM 的建议。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/xml/dom/minidom.py

   (2) https://www.w3.org/TR/REC-DOM-Level-1/


File: python.info,  Node: DOM 对象,  Next: DOM 示例,  Up: xml dom minidom --- 最小化的 DOM 实现

5.20.7.1 DOM 对象
.................

Python 的 DOM API 定义被作为 *note xml.dom: 13d. 模块文档的一部分给出。
这一节列出了该 API 和 *note xml.dom.minidom: 13e. 之间的差异。

 -- 成員函式: Node.unlink ()

     破坏 DOM 的内部引用以便它能在没有循环 GC 的 Python 版本上垃圾回收器
     回收。 即使在循环 GC 可用的时候，使用此方法也可让大量内存更快变为可
     用，因此当 DOM 对象不再被需要时尽早调用它们的这个方法是很好的做法。
     此方法只须在 ‘Document’ 对象上调用，但也可以在下级节点上调用以丢弃
     该节点的下级节点。

     你可以通过使用 *note with: 7da. 语句来避免显式调用此方法。 以下代码
     会在 ‘with’ 代码块退出时自动取消链接 `dom':

          with xml.dom.minidom.parse(datasource) as dom:
              ... # Work with dom.

 -- 成員函式: Node.writexml (writer, indent="", addindent="", newl="",
          encoding=None, standalone=None)

     将 XML 写入到写入器对象。 写入器接受文本而非字节串作为输入，它应当
     具有与文件对象接口相匹配的 ‘write()’ 方法。 `indent' 形参是当前节点
     的缩进层级。 `addindent' 形参是用于当前节点的下级节点的缩进量。
     `newl' 形参指定用于一行结束的字符串。

     对于 ‘Document’ 节点，可以使用附加的关键字参数 `encoding' 来指定
     XML 标头的编码格式字段。

     类似地，显式指明 `standalone' 参数将会使单独的文档声明被添加到 XML
     文档的开头部分。 如果将该值设为 ‘True’，则会添加
     ‘standalone="yes"’，否则将为 ‘"no"’。 未指明该参数将使文档声明被省
     略。

     3.8 版更變: *note writexml(): 2c17. 方法现在会保留用户指定的属性顺
     序。

     3.9 版更變: The `standalone' parameter was added.

 -- 成員函式: Node.toxml (encoding=None, standalone=None)

     返回一个包含 XML DOM 节点所代表的 XML 的字符串或字节串。

     带有显式的 `encoding' (1) 参数时，结果为使用指定编码格式的字节串。
     没有 `encoding' 参数时，结果为 Unicode 字符串，并且结果字符串中的
     XML 声明将不指定编码格式。 使用 UTF-8 以外的编码格式对此字符串进行
     编码通常是不正确的，因为 UTF-8 是 XML 的默认编码格式。

     `standalone' 参数的行为与 *note writexml(): 2c17. 中的完全一致。

     3.8 版更變: *note toxml(): 2c18. 方法现在会保留用户指定的属性顺序。

     3.9 版更變: The `standalone' parameter was added.

 -- 成員函式: Node.toprettyxml (indent="\t", newl="\n", encoding=None,
          standalone=None)

     返回文档的美化打印版本。 `indent' 指定缩进字符串并默认为制表符；
     `newl' 指定标示每行结束的字符串并默认为 ‘\n’。

     `encoding' 参数的行为类似于 *note toxml(): 2c18. 的对应参数。

     `standalone' 参数的行为与 *note writexml(): 2c17. 中的完全一致。

     3.8 版更變: *note toprettyxml(): 2c19. 方法现在会保留用户指定的属性
     顺序。

     3.9 版更變: The `standalone' parameter was added.

   ---------- Footnotes ----------

   (1) (1) 包括在 XML 输出中的编码格式名称应当遵循适当的标准。 例如，
"UTF-8" 是有效的，但 "UTF8" 在 XML 文档的声明中是无效的，即使 Python 接
受其作为编码格式名称。 详情参见
‘https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl’ 和
‘https://www.iana.org/assignments/character-sets/character-sets.xhtml’。


File: python.info,  Node: DOM 示例,  Next: minidom 和 DOM 标准,  Prev: DOM 对象,  Up: xml dom minidom --- 最小化的 DOM 实现

5.20.7.2 DOM 示例
.................

此示例程序是个相当实际的简单程序示例。 在这个特定情况中，我们没有过多地
利用 DOM 的灵活性。

     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 ''.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)


File: python.info,  Node: minidom 和 DOM 标准,  Prev: DOM 示例,  Up: xml dom minidom --- 最小化的 DOM 实现

5.20.7.3 minidom 和 DOM 标准
............................

*note xml.dom.minidom: 13e. 模块实际上是兼容 DOM 1.0 的 DOM 并带有部分
DOM 2 特性（主要是命名空间特性）。

Python 中 DOM 接口的用法十分直观。 会应用下列映射规则:

   * 接口是通过实例对象来访问的。 应用程序不应实例化这些类本身；它们应当
     使用 ‘Document’ 对象提供的创建器函数。 派生的接口支持上级接口的所有
     操作（和属性），并添加了新的操作。

   * 操作以方法的形式使用。 因由 DOM 只使用 *note in: 179. 形参，参数是
     以正常顺序传入的（从左至右）。 不存在可选参数。 ‘void’ 操作返回
     ‘None’。

   * IDL 属性会映射到实例属性。 为了兼容针对 Python 的 OMG IDL 语言映射
     ，属性 ‘foo’ 也可通过访问器方法 ‘_get_foo()’ 和 ‘_set_foo()’ 来访问
     。 ‘readonly’ 属性不可被修改；运行时并不强制要求这一点。

   * ‘short int’, ‘unsigned int’, ‘unsigned long long’ 和 ‘boolean’ 类型
     都会映射为 Python 整数类型。

   * ‘DOMString’ 类型会映射为 Python 字符串。 *note xml.dom.minidom:
     13e. 支持字节串或字符串，但通常是产生字符串。 ‘DOMString’ 类型的值
     也可以为 ‘None’，W3C 的 DOM 规格说明允许其具有 IDL ‘null’ 值。

   * ‘const’ 声明会映射为它们各自的作用域内的变量 (例如
     ‘xml.dom.minidom.Node.PROCESSING_INSTRUCTION_NODE’)；它们不可被修改
     。

   * ‘DOMException’ 目前不被 *note xml.dom.minidom: 13e. 所支持。 *note
     xml.dom.minidom: 13e. 会改为使用标准 Python 异常例如 *note
     TypeError: 1fe. 和 *note AttributeError: 4a1.。

   * ‘NodeList’ 对象是使用 Python 内置列表类型来实现的。 这些对象提供了
     DOM 规格说明中定义的接口，但在较早版本的 Python 中它们不支持官方
     API。 相比在 W3C 建议中定义的接口，它们要更加的 "Pythonic"。

下列接口未在 *note xml.dom.minidom: 13e. 中实现:

   * ‘DOMTimeStamp’

   * ‘EntityReference’

这些接口所反映的 XML 文档信息对于大多数 DOM 用户来说没有什么帮助。

註解
....


File: python.info,  Node: xml dom pulldom --- 支持构建部分 DOM 树,  Next: xml sax --- 支持 SAX2 解析器,  Prev: xml dom minidom --- 最小化的 DOM 实现,  Up: 结构化标记处理工具

5.20.8 ‘xml.dom.pulldom’ — 支持构建部分 DOM 树
----------------------------------------------

`源代码:' Lib/xml/dom/pulldom.py(1)

__________________________________________________________________

*note xml.dom.pulldom: 13f. 模块提供了一个“拉取解析器”，它能在必要时被用
于产生文件的可访问 DOM 的片段。 其基本概念包括从输入的 XML 流拉取“事件
”并处理它们。 与同样地同时应用了事件驱动处理模型加回调函数的 SAX 不同，
拉取解析器的用户要负责显式地从流拉取事件，并循环遍历这些事件直到处理结束
或者发生了错误条件。

     警告: *note xml.dom.pulldom: 13f. 模块对于恶意构建的数据是不安全的
     。 如果你需要解析不受信任或未经身份验证的数据，请参阅 *note XML
     漏洞: 2b34.。

3.7.1 版更變: SAX 解析器默认不再处理一般外部实体以提升在默认情况下的安全
性。 要启用外部实体处理，请传入一个自定义的解析器实例:

     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)

示例:

     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())

‘event’ 是一个常量，可以取下列值之一:

   * ‘START_ELEMENT’

   * ‘END_ELEMENT’

   * ‘COMMENT’

   * ‘START_DOCUMENT’

   * ‘END_DOCUMENT’

   * ‘CHARACTERS’

   * ‘PROCESSING_INSTRUCTION’

   * ‘IGNORABLE_WHITESPACE’

‘node’ 是一个 ‘xml.dom.minidom.Document’, ‘xml.dom.minidom.Element’ 或
‘xml.dom.minidom.Text’ 类型的对象。

由于文档是被当作“展平”的事件流来处理的，文档“树”会被隐式地遍历并且无论所
需元素在树中的深度如何都会被找到。 换句话说，不需要考虑层级问题，例如文
档节点的递归搜索等，但是如果元素的内容很重要，则有必要保留一些上下文相关
的状态（例如记住任意给定点在文档中的位置）或者使用 *note
DOMEventStream.expandNode(): 2c20. 方法并切换到 DOM 相关的处理过程。

 -- 類別: xml.dom.pulldom.PullDom (documentFactory=None)

     *note xml.sax.handler.ContentHandler: 2c22. 的子类。

 -- 類別: xml.dom.pulldom.SAX2DOM (documentFactory=None)

     *note xml.sax.handler.ContentHandler: 2c22. 的子类。

 -- 函式: xml.dom.pulldom.parse (stream_or_string, parser=None,
          bufsize=None)

     基于给定的输入返回一个 *note DOMEventStream: 3a2.。
     `stream_or_string' 可以是一个文件名，或是一个文件类对象。 `parser'
     如果给出，则必须是一个 *note XMLReader: 2c25. 对象。 此函数将改变解
     析器的文档处理程序并激活命名空间支持；其他解析器配置（例如设置实体
     解析器）必须在之前已完成。

如果你将 XML 存放为字符串，则可以改用 *note parseString(): 2c26. 函数:

 -- 函式: xml.dom.pulldom.parseString (string, parser=None)

     返回一个 *note DOMEventStream: 3a2. 来表示 (Unicode) `string'。

 -- Data: xml.dom.pulldom.default_bufsize

     将 `bufsize' 形参的默认值设为 *note parse(): 2c24.。

     此变量的值可在调用 *note parse(): 2c24. 之前修改并使新值生效。

* Menu:

* DOMEventStream 对象::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/xml/dom/pulldom.py


File: python.info,  Node: DOMEventStream 对象,  Up: xml dom pulldom --- 支持构建部分 DOM 树

5.20.8.1 DOMEventStream 对象
............................

 -- 類別: xml.dom.pulldom.DOMEventStream (stream, parser, bufsize)

     3.8 版後已棄用: 对 *note 序列协议: 3a5. 的支持已被弃用。

      -- 成員函式: getEvent ()

          返回一个元组，其中包含 `event' 和 ‘xml.dom.minidom.Document’ 形
          式的当前 `node' 如果 event 等于 ‘START_DOCUMENT’，包含
          ‘xml.dom.minidom.Element’ 如果 event 等于 ‘START_ELEMENT’ 或
          ‘END_ELEMENT’ 或者 ‘xml.dom.minidom.Text’ 如果 event 等于
          ‘CHARACTERS’。 当前 node 不包含有关其子节点的信息，除非 *note
          expandNode(): 2c20. 被调用。

      -- 成員函式: expandNode (node)

          将 `node' 的所有子节点扩展到 `node' 中。 例如:

               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())

      -- 成員函式: reset ()


File: python.info,  Node: xml sax --- 支持 SAX2 解析器,  Next: xml sax handler --- SAX 处理句柄的基类,  Prev: xml dom pulldom --- 支持构建部分 DOM 树,  Up: 结构化标记处理工具

5.20.9 ‘xml.sax’ — 支持 SAX2 解析器
-----------------------------------

`源代码:' Lib/xml/sax/__init__.py(1)

__________________________________________________________________

*note xml.sax: 144. 包提供多个模块，它们在 Python 上实现了用于 XML (SAX)
接口的简单 API。 这个包本身为 SAX API 用户提供了一些最常用的 SAX 异常和
便捷函数。

     警告: *note xml.sax: 144. 模块对于恶意构建的数据是不安全的。 如果你
     需要解析不受信任或未经身份验证的数据，请参阅 *note XML 漏洞: 2b34.。

3.7.1 版更變: SAX 解析器默认不会再处理通用外部实体以便提升安全性。 在此
之前，解析器会创建网络连接来获取远程文件或是从 DTD 和实体文件系统中加载
本地文件。 此特性可通过在解析器对象上调用 *note setFeature(): 2c2e. 对象
并传入参数 *note feature_external_ges: 2c2f. 来重新启用。

可用的便捷函数如下所列:

 -- 函式: xml.sax.make_parser (parser_list=[])

     创建并返回一个 SAX *note XMLReader: 2c25. 对象。 将返回第一个被找到
     的解析器。 如果提供了 `parser_list'，它必须为一个包含字符串的可迭代
     对象，这些字符串指定了具有名为 ‘create_parser()’ 函数的模块。 在
     `parser_list' 中列出的模块将在默认解析器列表中的模块之前被使用。

     3.8 版更變: `parser_list' 参数可以是任意可迭代对象，而不一定是列表
     。

 -- 函式: xml.sax.parse (filename_or_stream, handler,
          error_handler=handler.ErrorHandler())

     创建一个 SAX 解析器并用它来解析文档。 用于传入文档的
     `filename_or_stream' 可以是一个文件名或文件对象。 `handler' 形参必
     须是一个 SAX *note ContentHandler: 2c22. 实例。 如果给出了
     `error_handler'，则它必须是一个 SAX *note ErrorHandler: 2c30. 实例
     ；如果省略，则对于任何错误都将引发 *note SAXParseException: 2c31.。
     此函数没有返回值；所有操作必须由传入的 `handler' 来完成。

 -- 函式: xml.sax.parseString (string, handler,
          error_handler=handler.ErrorHandler())

     类似于 *note parse(): 111c.，但解析对象是作为形参传入的缓冲区
     `string'。 `string' 必须为 *note str: 205. 实例或者 *note
     bytes-like object: 6df.。

     3.5 版更變: 增加了对 *note str: 205. 实例的支持。

典型的 SAX 应用程序会使用三种对象：读取器、处理句柄和输入源。 “读取器”在
此上下文中与解析器同义，即某个从输入源读取字节或字符，并产生事件序列的代
码段。 事件随后将被分发给处理句柄对象，即由读取器发起调用处理句柄上的某
个方法。 因此 SAX 应用程序必须获取一个读取器对象，创建或打开输入源，创建
处理句柄，并一起连接到这些对象。 作为准备工作的最后一步，将调用读取器来
解析输入内容。 在解析过程中，会根据来自输入数据的结构化和语义化事件来调
用处理句柄对象上的方法。

就这些对象而言，只有接口部分是需要关注的；它们通常不是由应用程序本身来实
例化。 由于 Python 没有显式的接口标记法，它们的正式引入形式是类，但应用
程序可能会使用并非从已提供的类继承而来的实现。 *note InputSource: 881,
*note Locator: 2c32, ‘Attributes’, ‘AttributesNS’ 以及 *note XMLReader:
2c25. 接口是在 *note xml.sax.xmlreader: 147. 模块中定义的。 处理句柄接口
是在 *note xml.sax.handler: 145. 中定义的。 为了方便起见，*note
InputSource: 881. (它往往会被直接实例化) 和处理句柄类也可以从 *note
xml.sax: 144. 获得。 这些接口的描述见下文。

除了这些类，*note xml.sax: 144. 还提供了如下异常类。

 -- 例外: xml.sax.SAXException (msg, exception=None)

     封装某个 XML 错误或警告。 这个类可以包含来自 XML 解析器或应用程序的
     基本错误或警告信息：它可以被子类化以提供额外的功能或是添加本地化信
     息。 请注意虽然在 *note ErrorHandler: 2c30. 接口中定义的处理句柄可
     以接收该异常的实例，但是并不要求实际引发该异常 — 它也可以被用作信息
     的容器。

     当实例化时，`msg' 应当是适合人类阅读的错误描述。 如果给出了可选的
     `exception' 形参，它应当为 ‘None’ 或者解析代码所捕获的异常并会被作
     为信息传递出去。

     这是其他 SAX 异常类的基类。

 -- 例外: xml.sax.SAXParseException (msg, exception, locator)

     *note SAXException: 2c33. 的子类，针对解析错误引发。 这个类的实例会
     被传递给 SAX *note ErrorHandler: 2c30. 接口的方法来提供关于解析错误
     的信息。 这个类支持 SAX *note Locator: 2c32. 接口以及 *note
     SAXException: 2c33. 接口。

 -- 例外: xml.sax.SAXNotRecognizedException (msg, exception=None)

     *note SAXException: 2c33. 的子类，当 SAX *note XMLReader: 2c25. 遇
     到不可识别的特性或属性时引发。 SAX 应用程序和扩展可能会出于类似目的
     而使用这个类。

 -- 例外: xml.sax.SAXNotSupportedException (msg, exception=None)

     *note SAXException: 2c33. 的子类，当 SAX *note XMLReader: 2c25. 被
     要求启用某个不受支持的特性，或者将某个属性设为具体实现不支持的值时
     引发。 SAX 应用程序和扩展可能会出于类似目的而使用这个类。

也參考
......

SAX: The Simple API for XML(2)

     这个网站是 SAX API 定义的焦点。 它提供了一个 Java 实现以及在线文档
     。 还包括其他实现的链接和历史信息。

*note xml.sax.handler: 145. 模块

     应用程序所提供对象的接口定义。

*note xml.sax.saxutils: 146. 模块

     可在 SAX 应用程序中使用的便捷函数。

*note xml.sax.xmlreader: 147. 模块

     解析器所提供对象的接口定义。

* Menu:

* SAXException 对象::

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/Lib/xml/sax/__init__.py

   (2) http://www.saxproject.org/


File: python.info,  Node: SAXException 对象,  Up: xml sax --- 支持 SAX2 解析器

5.20.9.1 SAXException 对象
..........................

*note SAXException: 2c33. 异常类支持下列方法:

 -- 成員函式: SAXException.getMessage ()

     返回描述错误条件的适合人类阅读的消息。

 -- 成員函式: SAXException.getException ()

     返回一个封装的异常对象或者 ‘None’。


File: python.info,  Node: xml sax handler --- SAX 处理句柄的基类,  Next: xml sax saxutils --- SAX 工具集,  Prev: xml sax --- 支持 SAX2 解析器,  Up: 结构化标记处理工具

5.20.10 ‘xml.sax.handler’ — SAX 处理句柄的基类
----------------------------------------------

`源代码:' Lib/xml/sax/handler.py(1)

__________________________________________________________________

SAX API 定类了四种处理句柄：内容句柄、DTD 句柄、错误句柄以及实体解析器。
应用程序通常只需要实现他们感兴趣的事件对应的接口；他们可以在单个对象或多
个对象中实现这些接口。 处理句柄的实现应当继承自在 *note xml.sax.handler:
145. 模块中提供的基类，以便所有方法都能获得默认的实现。

 -- 類別: xml.sax.handler.ContentHandler

     这是 SAX 中的主回调接口，也是对应用程序来说最重要的一个接口。 此接
     口中事件的顺序反映了文档中信息的顺序。

 -- 類別: xml.sax.handler.DTDHandler

     处理 DTD 事件。

     这个接口仅指定了基本解析（未解析的实体和属性）所需的那些 DTD 事件。

 -- 類別: xml.sax.handler.EntityResolver

     用于解析实体的基本接口。 如果你创建了实现此接口的对象，然后用你的解
     析器注册该对象，该解析器将调用你的对象中的方法来解析所有外部实体。

 -- 類別: xml.sax.handler.ErrorHandler

     解析器用来向应用程序表示错误和警告的接口。 这个对象的方法控制错误是
     要立即转换为异常还是以某种其他该来来处理。

除了这些类，*note xml.sax.handler: 145. 还提供了表示特性和属性名称的符号
常量。

 -- Data: xml.sax.handler.feature_namespaces

          值: ‘"http://xml.org/sax/features/namespaces"’ 
          true: 执行命名空间处理。 
          false: 可选择不执行命名空间处理 (这意味着 namespace-prefixes; default)。 
          access: (解析) 只读; (不解析) 读/写 

 -- Data: xml.sax.handler.feature_namespace_prefixes

          值: ‘"http://xml.org/sax/features/namespace-prefixes"’ 
          true: 报告原始的带前缀名称和用于命名空间声明的属性。 
          false: 不报告用于命名空间声明的属性，可选择不报告原始的带前缀名称（默认）。 
          access: (解析) 只读; (不解析) 读/写 

 -- Data: xml.sax.handler.feature_string_interning

          值: ‘"http://xml.org/sax/features/string-interning"’ 
          true: 所有元素名称、前缀、属性名称、命名空间 URI 以及本地名称都使用内置的 intern 函数进行内化。 
          false: 名称不要求被内化，但也可以被内化（默认）。 
          access: (解析) 只读; (不解析) 读/写 

 -- Data: xml.sax.handler.feature_validation

          值: ‘"http://xml.org/sax/features/validation"’ 
          true: 报告所有的验证错误（包括 external-general-entities 和 external-parameter-entities）。 
          false: 不报告验证错误。 
          access: (解析) 只读; (不解析) 读/写 

 -- Data: xml.sax.handler.feature_external_ges

          值: ‘"http://xml.org/sax/features/external-general-entities"’ 
          true: 包括所有的外部通用（文本）实体。 
          false: 不包括外部通用实体。 
          access: (解析) 只读; (不解析) 读/写 

 -- Data: xml.sax.handler.feature_external_pes

          值: ‘"http://xml.org/sax/features/external-parameter-entities"’ 
          true: 包括所有的外部参数实体，也包括外部 DTD 子集。 
          false: 不包括任何外部参数实体，也不包括外部 DTD 子集。 
          access: (解析) 只读; (不解析) 读/写 

 -- Data: xml.sax.handler.all_features

     全部特性列表。

 -- Data: xml.sax.handler.property_lexical_handler

          值: ‘"http://xml.org/sax/properties/lexical-handler"’ 
          数据类型: xml.sax.sax2lib.LexicalHandler (在 Python 2 中不受支持) 
          描述: 可选的扩展处理句柄，用于注释等词法事件。 
          访问: 读/写 

 -- Data: xml.sax.handler.property_declaration_handler

          值: ‘"http://xml.org/sax/properties/declaration-handler"’ 
          数据类型: xml.sax.sax2lib.DeclHandler (在 Python 2 中不受支持) 
          描述: 可选的扩展处理句柄，用于标注和未解析实体以外的 DTD 相关事件。 
          访问: 读/写 

 -- Data: xml.sax.handler.property_dom_node

          值: ‘"http://xml.org/sax/properties/dom-node"’ 
          数据类型: org.w3c.dom.Node (在 Python 2 中不受支持) 
          描述: 在解析时，如果这是一个 DOM 迭代器则为当前被访问的 DOM 节点；不在解析时，则将根 DOM 节点用于迭代。 
          access: (解析) 只读; (不解析) 读/写 

 -- Data: xml.sax.handler.property_xml_string

          值: ‘"http://xml.org/sax/properties/xml-string"’ 
          数据类型: String 
          描述: 作为当前事件来源的字符串字面值。 
          访问: 只读 

 -- Data: xml.sax.handler.all_properties

     已知属性名称列表。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/xml/sax/handler.py


File: python.info,  Node: ContentHandler 对象,  Next: DTDHandler 对象,  Up: xml sax handler --- SAX 处理句柄的基类

5.20.10.1 ContentHandler 对象
.............................

用户应当子类化 *note ContentHandler: 2c22. 来支持他们的应用程序。 以下方
法会由解析器在输入文档的适当事件上调用:

 -- 成員函式: ContentHandler.setDocumentLocator (locator)

     由解析器调用来给予应用程序一个定位器以确定文档事件来自何处。

     强烈建议（虽然不是绝对的要求） SAX 解析器提供一个定位器：如果提供的
     话，它必须在发起调用 DocumentHandler 接口的任何其他方法之前通过发起
     调用此方法来提供定位器。

     定位器允许应用程序确定任何文档相关事件的结束位置，即使解析器没有报
     告错误。 通常，应用程序将使用这些信息来报告它自己的错误（例如未匹配
     到应用程序业务规则的字符内容）。 定位器所返回的信息可能不足以与搜索
     引擎配合使用。

     请注意定位器只有在发起调用此接口中的事件时才会返回正确的信息。 应用
     程序不应试图在其他任何时刻使用它。

 -- 成員函式: ContentHandler.startDocument ()

     接收一个文档开始的通知。

     SAX 解析器将只发起调用这个方法一次，并且会在调用这个接口或
     DTDHandler 中的任何其他方法之前 (*note setDocumentLocator(): 2c4b.
     除外)。

 -- 成員函式: ContentHandler.endDocument ()

     接收一个文档结束的通知。

     SAX 解析器将只发起调用这个方法一次，并且它将是在解析过程中最后发起
     调用的方法。 解析器在（因不可恢复的错误）放弃解析或到达输入的终点之
     前不应发起调用这个方法。

 -- 成員函式: ContentHandler.startPrefixMapping (prefix, uri)

     开始一个前缀 URI 命名空间映射的范围。

     来自此事件的信息对于一般命名空间处理来说是不必要的：当
     ‘feature_namespaces’ 特性被启用时（默认）SAX XML 读取器将自动为元素
     和属性名称替换前缀。

     但是也存在一些情况，当应用程序需要在字符数据或属性值中使用前缀，而
     它们无法被安全地自动扩展；*note startPrefixMapping(): 2c4e. 和
     *note endPrefixMapping(): 2c4f. 事件会向应用程序提供信息以便在这些
     上下文内部扩展前缀，如果有必要的话。

     请注意 *note startPrefixMapping(): 2c4e. 和 *note
     endPrefixMapping(): 2c4f. 事件并不保证能够相对彼此被正确地嵌套：所
     有 *note startPrefixMapping(): 2c4e. 事件都将在对应的 *note
     startElement(): 2c50. 事件之前发生，而所有 *note
     endPrefixMapping(): 2c4f. 事件都将在对应的 *note endElement():
     2c51. 事件之后发生，但它们的并不保证一致。

 -- 成員函式: ContentHandler.endPrefixMapping (prefix)

     结束一个前缀 URI 映射的范围。

     请参看 *note startPrefixMapping(): 2c4e. 了解详情。 此事件将总是会
     在对应的 *note endElement(): 2c51. 事件之后发生，但 *note
     endPrefixMapping(): 2c4f. 事件的顺序则并没有保证。

 -- 成員函式: ContentHandler.startElement (name, attrs)

     在非命令空间模式下指示一个元素的开始。

     `name' 形参包含字符串形式的元素类型原始 XML 1.0 名称而 `attrs' 形参
     存放包含元素属性的 ‘Attributes’ 接口对象 (参见 *note Attributes
     接口: 2c52.)。 作为 `attrs' 传入的对象可能被解析器所重用；维持一个
     对它的引用不是保持属性副本的可靠方式。 要保持这些属性的一个副本，请
     使用 `attrs' 对象的 *note copy(): 25. 方法。

 -- 成員函式: ContentHandler.endElement (name)

     在非命名空间模式下指示一个元素的结束。

     `name' 形参包含元素类型的名称，与 *note startElement(): 2c50. 事件
     的一样。

 -- 成員函式: ContentHandler.startElementNS (name, qname, attrs)

     在命名空间模式下指示一个元素的开始。

     `name' 形参包含以 ‘(uri, localname)’ 元组表示的元素类型名称，
     `qname' 形参包含源文档中使用的原始 XML 1.0 名称，而 `attrs' 形参存
     放包含元素属性的 ‘AttributesNS’ 接口实例 (参见 *note AttributesNS
     接口: 2c54.)。 如果没有命名空间被关联到元素，则 `name' 的 `uri' 部
     分将为 ‘None’。 作为 `attrs' 传入的对象可能被解析器所重用；维持一个
     对它的引用不是保持属性副本的可靠方式。 要保持这些属性的一个副本，请
     使用 `attrs' 对象的 *note copy(): 25. 方法。

     解析器可将 `qname' 形参设为 ‘None’，除非
     ‘feature_namespace_prefixes’ 特性已被激活。

 -- 成員函式: ContentHandler.endElementNS (name, qname)

     在命名空间模式下指示一个元素的结束。

     `name' 形参包含元素类型的名称，与 *note startElementNS(): 2c53. 方
     法的一样，`qname' 形参也是类似的。

 -- 成員函式: ContentHandler.characters (content)

     接收字符数据的通知。

     解析器将调用此方法来报告每一个字符数据分块。 SAX 解析器可以将所有连
     续字符数据返回为一个单独分块，或者将其拆成几个分块；但是，在任意单
     个事件中的所有字符都必须来自同一个外部实体以便定位器提供有用的信息
     。

     `content' 可以是一个字符串或字节串实例；‘expat’ 读取器模块总是会产
     生字符串。

          備註: Python XML 特别关注小组所提供的早期 SAX 1 接口针对此方法
          使用了一个更类似于 Java 的接口。 由于 Python 所使用的大多数解
          析器都没有利用老式的接口，因而选择了更简单的签名来替代它。 要
          将旧代码转换为新接口，请使用 `content' 而不要通过旧的 `offset'
          和 `length' 形参来对内容进行切片。

 -- 成員函式: ContentHandler.ignorableWhitespace (whitespace)

     接收元素内容中可忽略空白符的通知。

     验证解析器必须使用此方法来报告每个可忽略的空白符分块（参见 W3C XML
     1.0 建议第 2.10 节）：非验证解析器如果能够解析并使用内容模型的话也
     可以使用此方法。

     SAX 解析器可以将所有连续字符数据返回为一个单独分块，或者将其拆成几
     个分块；但是，在任意单个事件中的所有字符都必须来自同一个外部实体以
     便定位器提供有用的信息。

 -- 成員函式: ContentHandler.processingInstruction (target, data)

     接受一条处理指令的通知。

     解析器将为已找到的每条处理指令发起调用该方法一次：请注意处理指令可
     能出现在主文档元素之前或之后。

     SAX 解析器绝不应当使用此方法来报告 XML 声明（XML 1.0 第 2.8 节）或
     文本声明（XML 1.0 第 4.3.1 节）。

 -- 成員函式: ContentHandler.skippedEntity (name)

     接收一个已跳过实体的通知。

     解析器将为每个已跳过实体发起调用此方法一次。 非验证处理程序可能会跳
     过未看到声明的实体（例如，由于实体是在一个外部because, for example,
     the entity was declared in an external DTD 子集中声明的）。 所有处
     理程序都可以跳过外部实体，具体取决于 ‘feature_external_ges’ 和
     ‘feature_external_pes’ 属性的值。


File: python.info,  Node: DTDHandler 对象,  Next: EntityResolver 对象,  Prev: ContentHandler 对象,  Up: xml sax handler --- SAX 处理句柄的基类

5.20.10.2 DTDHandler 对象
.........................

*note DTDHandler: 2c3c. 实例提供了下列方法:

 -- 成員函式: DTDHandler.notationDecl (name, publicId, systemId)

     处理标注声明事件。

 -- 成員函式: DTDHandler.unparsedEntityDecl (name, publicId, systemId,
          ndata)

     处理未解析的实体声明事件。


File: python.info,  Node: EntityResolver 对象,  Next: ErrorHandler 对象,  Prev: DTDHandler 对象,  Up: xml sax handler --- SAX 处理句柄的基类

5.20.10.3 EntityResolver 对象
.............................

 -- 成員函式: EntityResolver.resolveEntity (publicId, systemId)

     求解一个实体的系统标识符并返回一个字符串形式的系统标识符作为读取源
     ，或是一个 InputSource 作为读取源。 默认的实现会返回 `systemId'。


File: python.info,  Node: ErrorHandler 对象,  Prev: EntityResolver 对象,  Up: xml sax handler --- SAX 处理句柄的基类

5.20.10.4 ErrorHandler 对象
...........................

带有这个接口的对象被用于接收来自 *note XMLReader: 2c25. 的错误和警告信息
。 如果你创建了一个实现这个接口的对象，然后用你的 *note XMLReader: 2c25.
注册这个对象，则解析器将调用你的对象中的这个方法来报告所有的警告和错误。
有三个可用的错误级别：警告、（或许）可恢复的错误和不可恢复的错误。 所有
方法都接受 ‘SAXParseException’ 作为唯一的形参。 错误和警告可以通过引发所
传入的异常对象来转换为异常。

 -- 成員函式: ErrorHandler.error (exception)

     当解析器遇到一个可恢复的错误时调用。 如果此方法没有引发异常，则解析
     可能会继续，但是应用程序不能预期获得更多的文档信息。 允许解析器继续
     可能会允许在输入文档中发现额外的错误。

 -- 成員函式: ErrorHandler.fatalError (exception)

     当解析器遇到一个不可恢复的错误时调用；在此方法返回时解析应当终止。

 -- 成員函式: ErrorHandler.warning (exception)

     当解析器向应用程序提供次要警告信息时调用。 在此方法返回时解析应当继
     续，并且文档信息将继续被传递给应用程序。 在此方法中引发异常将导致解
     析结束。


File: python.info,  Node: xml sax saxutils --- SAX 工具集,  Next: xml sax xmlreader --- 用于 XML 解析器的接口,  Prev: xml sax handler --- SAX 处理句柄的基类,  Up: 结构化标记处理工具

5.20.11 ‘xml.sax.saxutils’ — SAX 工具集
---------------------------------------

`源代码:' Lib/xml/sax/saxutils.py(1)

__________________________________________________________________

*note xml.sax.saxutils: 146. 模块包含一些在创建 SAX 应用程序时十分有用的
类和函数，它们可以被直接使用，或者是作为基类使用。

 -- 函式: xml.sax.saxutils.escape (data, entities={})

     对数据字符串中的 ‘'&'’, ‘'<'’ 和 ‘'>'’ 进行转义。

     你可以通过传入一个字典作为可选的 `entities' 形参来对其他字符串数据
     进行转义。 字典的键和值必须为字符串；每个键将被替换为其所对应的值。
     字符 ‘'&'’, ‘'<'’ 和 ‘'>'’ 总是会被转义，即使提供了 `entities'。

 -- 函式: xml.sax.saxutils.unescape (data, entities={})

     对字符串数据中的 ‘'&amp;'’, ‘'&lt;'’ 和 ‘'&gt;'’ 进行反转义。

     你可以通过传入一个字典作为可选的 `entities' 形参来对其他数据字符串
     进行转义。 字典的键和值必须都为字符串；每个键将被替换为所对应的值。
     ‘'&amp'’, ‘'&lt;'’ 和 ‘'&gt;'’ 将总是保持不被转义，即使提供了
     `entities'。

 -- 函式: xml.sax.saxutils.quoteattr (data, entities={})

     类似于 *note escape(): 2c68.，但还会对 `data' 进行处理以将其用作属
     性值。 返回值是 `data' 加上任何额外要求的替换的带引号版本。*note
     quoteattr(): 2c6a. 将基于 `data' 的内容选择一个引号字符，以尽量避免
     在字符串中编码任何引号字符。 如果单双引号字符在 `data' 中都存在，则
     双引号字符将被编码并且 `data' 将使用双引号来标记。 结果字符串可被直
     接用作属性值:

          >>> print("<element attr=%s>" % quoteattr("ab ' cd \" ef"))
          <element attr="ab ' cd &quot; ef">

     此函数适用于为 HTML 或任何使用引用实体语法的 SGML 生成属性值。

 -- 類別: xml.sax.saxutils.XMLGenerator (out=None,
          encoding='iso-8859-1', short_empty_elements=False)

     这个类通过将 SAX 事件写回到 XML 文档来实现 *note ContentHandler:
     2c22. 接口。 换句话说，使用 *note XMLGenerator: 2c6b. 作为内容处理
     程序将重新产生所解析的原始文档。 `out' 应当为一个文件类对象，它默认
     将为 `sys.stdout'。 `encoding' 为输出流的编码格式，它默认将为
     ‘'iso-8859-1'’。 `short_empty_elements' 控制不包含内容的元素的格式
     化：如为 ‘False’ (默认值) 则它们会以开始/结束标记对的形式被发送，如
     果设为 ‘True’ 则它们会以单个自结束标记的形式被发送。

     3.2 版新加入: `short_empty_elements' 形参。

 -- 類別: xml.sax.saxutils.XMLFilterBase (base)

     这个类被设计用来分隔 *note XMLReader: 2c25. 和客户端应用的事件处理
     程序。 在默认情况下，它除了将请求传送给读取器并将事件传送给处理程序
     之外什么都不做，但其子类可以重载特定的方法以在传送它们的时候修改事
     件流或配置请求。

 -- 函式: xml.sax.saxutils.prepare_input_source (source, base='')

     此函数接受一个输入源和一个可选的基准 URL 并返回一个经过完整解析可供
     读取的 *note InputSource: 881.。 输入源的给出形式可以为字符串、文件
     类对象或 *note InputSource: 881. 对象；解析器将使用此函数来针对它们
     的 ‘parse()’ 方法实现多态 `source' 参数。

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/Lib/xml/sax/saxutils.py


File: python.info,  Node: xml sax xmlreader --- 用于 XML 解析器的接口,  Next: xml parsers expat --- 使用 Expat 的快速 XML 解析,  Prev: xml sax saxutils --- SAX 工具集,  Up: 结构化标记处理工具

5.20.12 ‘xml.sax.xmlreader’ — 用于 XML 解析器的接口
---------------------------------------------------

`源代码:' Lib/xml/sax/xmlreader.py(1)

__________________________________________________________________

SAX 解析器实现了 *note XMLReader: 2c25. 接口。 它们是在一个 Python 模块
中实现的，该模块必须提供一个 ‘create_parser()’ 函数。 该函数由 *note
xml.sax.make_parser(): 115f. 不带参数地发起调用来创建新的解析器对象。

 -- 類別: xml.sax.xmlreader.XMLReader

     可由 SAX 解析器继承的基类。

 -- 類別: xml.sax.xmlreader.IncrementalParser

     在某些情况下，最好不要一次性地解析输入源，而是在可用的时候分块送入
     。 请注意读取器通常不会读取整个文件，它同样也是分块读取的； 并且
     ‘parse()’ 在处理完整个文档之前不会返回。 所以如果不希望 ‘parse()’ 出
     现阻塞行为则应当使用这些接口。

     当解析器被实例化时它已准备好立即开始接受来自 feed 方法的数据。 在通
     过调用 close 方法结束解析时 reset 方法也必须被调用以使解析器准备好
     接受新的数据，无论它是来自于 feed 还是使用 parse 方法。

     请注意这些方法 `不可' 在解析期间被调用，即在 parse 被调用之后及其返
     回之前。

     默认情况下，该类还使用 IncrementalParser 接口的 feed, close 和
     reset 方法来实现 XMLReader 接口的 parse 方法以方便 SAX 2.0 驱动的编
     写者。

 -- 類別: xml.sax.xmlreader.Locator

     用于关联一个 SAX 事件与一个文档位置的接口。 定位器对象只有在调用
     DocumentHandler 的方法期间才会返回有效的结果；在其他任何时候，结果
     都是不可预测的。 如果信息不可用，这些方法可能返回 ‘None’。

 -- 類別: xml.sax.xmlreader.InputSource (system_id=None)

     *note XMLReader: 2c25. 读取实体所需信息的封装。

     这个类可能包括了关于公有标识符、系统标识符、字节流（可能带有字符编
     码格式信息）和/或一个实体的字符流的信息。

     应用程序将创建这个类的对象以便在 *note XMLReader.parse(): 2c71. 方
     法中使用或是用于从 EntityResolver.resolveEntity 返回值。

     *note InputSource: 881. 属于应用程序，*note XMLReader: 2c25. 不能修
     改从应用程序传递给它的 *note InputSource: 881. 对象，但它可以创建副
     本并进行修改。

 -- 類別: xml.sax.xmlreader.AttributesImpl (attrs)

     这是 ‘Attributes’ 接口（参见 *note Attributes 接口: 2c52. 一节）的
     具体实现。 这是一个 ‘startElement()’ 调用中的元素属性的字典类对象。
     除了最有用处的字典操作，它还支持接口所描述的一些其他方法。 该类的对
     象应当由读取器来实例化；`attrs' 必须为包含从属性名到属性值的映射的
     字典类对象。

 -- 類別: xml.sax.xmlreader.AttributesNSImpl (attrs, qnames)

     可感知命名空间的 *note AttributesImpl: 2c72. 变体形式，它将被传递给
     ‘startElementNS()’。 它派生自 *note AttributesImpl: 2c72.，但会将属
     性名称解读为 `namespaceURI' 和 `localname' 二元组。 此外，它还提供
     了一些期望接收在原始文档中出现的限定名称的方法。 这个类实现了
     ‘AttributesNS’ 接口（参见 *note AttributesNS 接口: 2c54. 一节）。

* Menu:

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

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/Lib/xml/sax/xmlreader.py


File: python.info,  Node: XMLReader 对象,  Next: IncrementalParser 对象,  Up: xml sax xmlreader --- 用于 XML 解析器的接口

5.20.12.1 XMLReader 对象
........................

*note XMLReader: 2c25. 接口支持下列方法:

 -- 成員函式: XMLReader.parse (source)

     处理输入源，产生 SAX 事件。 `source' 对象可以是一个系统标识符（标识
     输入源的字符串 – 通常为文件名或 URL）, *note pathlib.Path: 32f. 或
     *note 路径类: 472. 对象，或者是 *note InputSource: 881. 对象。 当
     *note parse(): 2c71. 返回时，输入会被全部处理完成，解析器对象可以被
     丢弃或重置。

     3.5 版更變: 增加了对字符流的支持。

     3.8 版更變: 增加了对路径类对象的支持。

 -- 成員函式: XMLReader.getContentHandler ()

     返回当前的 *note ContentHandler: 2c22.。

 -- 成員函式: XMLReader.setContentHandler (handler)

     设置当前的 *note ContentHandler: 2c22.。 如果没有设置 *note
     ContentHandler: 2c22.，内容事件将被丢弃。

 -- 成員函式: XMLReader.getDTDHandler ()

     返回当前的 *note DTDHandler: 2c3c.。

 -- 成員函式: XMLReader.setDTDHandler (handler)

     设置当前的 *note DTDHandler: 2c3c.。 如果没有设置 *note DTDHandler:
     2c3c.，DTD 事件将被德育。

 -- 成員函式: XMLReader.getEntityResolver ()

     返回当前的 *note EntityResolver: 2c3d.。

 -- 成員函式: XMLReader.setEntityResolver (handler)

     设置当前的 *note EntityResolver: 2c3d.。 如果没有设置 *note
     EntityResolver: 2c3d.，尝试解析一个外部实体将导致打开该实体的系统标
     识符，并且如果它不可用则操作将失败。

 -- 成員函式: XMLReader.getErrorHandler ()

     返回当前的 *note ErrorHandler: 2c30.。

 -- 成員函式: XMLReader.setErrorHandler (handler)

     设置当前的错误处理句柄。 如果没有设置 *note ErrorHandler: 2c30.，错
     误将作为异常被引发，并将打印警告信息。

 -- 成員函式: XMLReader.setLocale (locale)

     允许应用程序为错误和警告设置语言区域。

     SAX 解析器不要求为错误和警告提供本地化信息；但是如果它们无法支持所
     请求的语言区域，则必须引发一个 SAX 异常。 应用程序可以在解析的中途
     请求更改语言区域。

 -- 成員函式: XMLReader.getFeature (featurename)

     返回 `featurename' 特性的当前设置。 如果特性无法被识别，则会引发
     ‘SAXNotRecognizedException’。 在 *note xml.sax.handler: 145. 模块中
     列出了常见的特性名称。

 -- 成員函式: XMLReader.setFeature (featurename, value)

     将 `featurename' 设为 `value'。 如果特性无法被识别，则会引发
     ‘SAXNotRecognizedException’。 如果特性或其设置不被解析器所支持，则
     会引发 `SAXNotSupportedException'。

 -- 成員函式: XMLReader.getProperty (propertyname)

     返回 `propertyname' 属性的当前设置。 如果属性无法被识别，则会引发
     ‘SAXNotRecognizedException’。 在 *note xml.sax.handler: 145. 模块中
     列出了常见的属性名称。

 -- 成員函式: XMLReader.setProperty (propertyname, value)

     将 `propertyname' 设为 `value'。 如果属性无法被识别，则会引发
     ‘SAXNotRecognizedException’。 如果属性或其设置不被解析器所支持，则
     会引发 `SAXNotSupportedException'。


File: python.info,  Node: IncrementalParser 对象,  Next: Locator 对象,  Prev: XMLReader 对象,  Up: xml sax xmlreader --- 用于 XML 解析器的接口

5.20.12.2 IncrementalParser 对象
................................

*note IncrementalParser: 2c70. 的实例额外提供了下列方法:

 -- 成員函式: IncrementalParser.feed (data)

     处理 `data' 的一个分块。

 -- 成員函式: IncrementalParser.close ()

     确定文档的结尾。 这将检查只能在结尾处检查的格式是否良好的条件，发起
     调用处理程序，并可能会清理在解析期间分配的资源。

 -- 成員函式: IncrementalParser.reset ()

     此方法会在调用 close 来重置解析器以便其准备好解析新的文档之后被调用
     。 在 close 之后未调用 reset 即调用 parse 或 feed 的结果是未定义的
     。


File: python.info,  Node: Locator 对象,  Next: InputSource 对象,  Prev: IncrementalParser 对象,  Up: xml sax xmlreader --- 用于 XML 解析器的接口

5.20.12.3 Locator 对象
......................

*note Locator: 2c32. 的实例提供了下列方法:

 -- 成員函式: Locator.getColumnNumber ()

     返回当前事件开始位置的列号。

 -- 成員函式: Locator.getLineNumber ()

     返回当前事件开始位置的行号。

 -- 成員函式: Locator.getPublicId ()

     返回当前事件的公有标识符。

 -- 成員函式: Locator.getSystemId ()

     返回当前事件的系统标识符。


File: python.info,  Node: InputSource 对象,  Next: Attributes 接口,  Prev: Locator 对象,  Up: xml sax xmlreader --- 用于 XML 解析器的接口

5.20.12.4 InputSource 对象
..........................

 -- 成員函式: InputSource.setPublicId (id)

     设置该 *note InputSource: 881. 的公有标识符。

 -- 成員函式: InputSource.getPublicId ()

     返回此 *note InputSource: 881. 的公有标识符。

 -- 成員函式: InputSource.setSystemId (id)

     设置此 *note InputSource: 881. 的系统标识符。

 -- 成員函式: InputSource.getSystemId ()

     返回此 *note InputSource: 881. 的系统标识符。

 -- 成員函式: InputSource.setEncoding (encoding)

     设置此 *note InputSource: 881. 的字符编码格式。

     编码格式必须是 XML 编码声明可接受的字符串（参见 XML 建议规范第
     4.3.3 节）。

     如果 *note InputSource: 881. 还包含一个字符流则 *note InputSource:
     881. 的 encoding 属性会被忽略。

 -- 成員函式: InputSource.getEncoding ()

     获取此 InputSource 的字符编码格式。

 -- 成員函式: InputSource.setByteStream (bytefile)

     设置此输入源的字节流（为 *note binary file: 1e01. 对象）。

     如果还指定了一个字符流被则 SAX 解析器会忽略此设置，但它将优先使用字
     节流而不是自己打开一个 URI 连接。

     如果应用程序知道字节流的字符编码格式，它应当使用 setEncoding 方法来
     设置它。

 -- 成員函式: InputSource.getByteStream ()

     获取此输入源的字节流。

     getEncoding 方法将返回该字节流的字符编码格式，如果未知则返回
     ‘None’。

 -- 成員函式: InputSource.setCharacterStream (charfile)

     设置此输入源的字符流 (为 *note text file: 13d9. 对象)。

     如果指定了一个字符流，SAX 解析器将忽略任何字节流并且不会尝试打开一
     个指向系统标识符的 URI 连接。

 -- 成員函式: InputSource.getCharacterStream ()

     获取此输入源的字符流。


File: python.info,  Node: Attributes 接口,  Next: AttributesNS 接口,  Prev: InputSource 对象,  Up: xml sax xmlreader --- 用于 XML 解析器的接口

5.20.12.5 ‘Attributes’ 接口
...........................

‘Attributes’ 对象实现了一部分 *note 映射协议: c0b.，包括 ‘copy()’,
‘get()’, *note __contains__(): dee, ‘items()’, ‘keys()’ 和 ‘values()’ 等
方法。 还提供了下列方法:

 -- 成員函式: Attributes.getLength ()

     返回属性的数量。

 -- 成員函式: Attributes.getNames ()

     返回属性的名称。

 -- 成員函式: Attributes.getType (name)

     返回属性 `name' 的类型，通常为 ‘'CDATA'’。

 -- 成員函式: Attributes.getValue (name)

     返回属性 `name' 的值。


File: python.info,  Node: AttributesNS 接口,  Prev: Attributes 接口,  Up: xml sax xmlreader --- 用于 XML 解析器的接口

5.20.12.6 ‘AttributesNS’ 接口
.............................

此接口是 ‘Attributes’ 接口（参见 *note Attributes 接口: 2c52. 章节）的一
个子类型。 那个接口所支持的所有方法在 ‘AttributesNS’ 对象上也都可用。

下列方法也是可用的:

 -- 成員函式: AttributesNS.getValueByQName (name)

     返回一个限定名称的值。

 -- 成員函式: AttributesNS.getNameByQName (name)

     返回限定名称 `name' 的 ‘(namespace, localname)’ 对。

 -- 成員函式: AttributesNS.getQNameByName (name)

     返回 ‘(namespace, localname)’ 对的限定名称。

 -- 成員函式: AttributesNS.getQNames ()

     返回所有属性的限定名称。


File: python.info,  Node: xml parsers expat --- 使用 Expat 的快速 XML 解析,  Prev: xml sax xmlreader --- 用于 XML 解析器的接口,  Up: 结构化标记处理工具

5.20.13 ‘xml.parsers.expat’ — 使用 Expat 的快速 XML 解析
--------------------------------------------------------

__________________________________________________________________

     警告: ‘pyexpat’ 模块对于恶意构建的数据是不安全的。 如果你需要解析不
     受信任或未经身份验证的数据，请参阅 *note XML 漏洞: 2b34.。

*note xml.parsers.expat: 141. 模块是针对 Expat 非验证 XML 解析器的
Python 接口。 此模块提供了一个扩展类型 ‘xmlparser’，它代表一个 XML 解析
器的当前状态。 在创建一个 ‘xmlparser’ 对象之后，该对象的各个属性可被设置
为相应的处理句柄函数。 随后当将一个 XML 文档送入解析器时，就会为该 XML 文
档中的字符数据和标记调用处理句柄函数。

此模块使用 ‘pyexpat’ 模块来提供对 Expat 解析器的访问。 直接使用
‘pyexpat’ 模块的方式已被弃用。

此模块提供了一个异常和一个类型对象:

 -- 例外: xml.parsers.expat.ExpatError

     此异常会在 Expat 报错时被引发。 请参阅 *note ExpatError 异常: 2ca5.
     一节了解有关解读 Expat 错误的更多信息。

 -- 例外: xml.parsers.expat.error

     *note ExpatError: cd8. 的别名。

 -- Data: xml.parsers.expat.XMLParserType

     来自 *note ParserCreate(): 2ca8. 函数的返回值的类型。

*note xml.parsers.expat: 141. 模块包含两个函数:

 -- 函式: xml.parsers.expat.ErrorString (errno)

     返回给定错误号 `errno' 的解释性字符串。

 -- 函式: xml.parsers.expat.ParserCreate (encoding=None,
          namespace_separator=None)

     创建并返回一个新的 ‘xmlparser’ 对象。 如果指定了 `encoding'，它必须
     为指定 XML 数据所使用的编码格式名称的字符串。 Expat 支持的编码格式
     没有 Python 那样多，而且它的编码格式库也不能被扩展；它支持 UTF-8,
     UTF-16, ISO-8859-1 (Latin1) 和 ASCII。 如果给出了 `encoding' (1) 则
     它将覆盖隐式或显式指定的文档编码格式。

     可以选择让 Expat 为你做 XML 命名空间处理，这是通过提供
     `namespace_separator' 值来启用的。 该值必须是一个单字符的字符串；如
     果字符串的长度不合法则将引发 *note ValueError: 16d. (‘None’ 被视为
     等同于省略)。 当命名空间处理被启用时，属于特定命名空间的元素类型名
     称和属性名称将被展开。 传递给The element name passed to the 元素处
     理句柄 ‘StartElementHandler’ 和 ‘EndElementHandler’ 的元素名称将为
     命名空间 URI，命名空间分隔符和名称的本地部分的拼接。 如果命名空间分
     隔符是一个零字节 (‘chr(0)’) 则命名空间 URI 和本地部分将被直接拼接而
     不带任何分隔符。

     举例来说，如果 `namespace_separator' 被设为空格符 (‘' '’) 并对以下
     文档进行解析:

          <?xml version="1.0"?>
          <root xmlns    = "http://default-namespace.org/"
                xmlns:py = "http://www.python.org/ns/">
            <py:elem1 />
            <elem2 xmlns="" />
          </root>

     ‘StartElementHandler’ 将为每个元素获取以下字符串:

          http://default-namespace.org/ root
          http://www.python.org/ns/ elem1
          elem2

     由于 ‘pyexpat’ 所使用的 ‘Expat’ 库的限制，被返回的 ‘xmlparser’ 实例
     只能被用来解析单个 XML 文档。 请为每个文档调用 ‘ParserCreate’ 来提
     供单独的解析器实例。

也參考
......

The Expat XML Parser(2)

     Expat 项目的主页。

* Menu:

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

   ---------- Footnotes ----------

   (1) (1) 包括在 XML 输出中的编码格式字符串应当符合适当的标准。 例如
"UTF-8" 是有效的，但 "UTF8" 是无效的。 请参阅
‘https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl’ 和
‘https://www.iana.org/assignments/character-sets/character-sets.xhtml’。

   (2) http://www.libexpat.org/


File: python.info,  Node: XMLParser对象<2>,  Next: ExpatError 异常,  Up: xml parsers expat --- 使用 Expat 的快速 XML 解析

5.20.13.1 XMLParser对象
.......................

‘xmlparser’ 对象具有以下方法:

 -- 成員函式: xmlparser.Parse (data[, isfinal])

     解析字符串 `data' 的内容，调用适当的处理函数来处理解析后的数据。 在
     对此方法的最后一次调用时 `isfinal' 必须为真值；它允许以片段形式解析
     单个文件，而不是提交多个文件。 `data' 在任何时候都可以为空字符串。

 -- 成員函式: xmlparser.ParseFile (file)

     解析从对象 `file' 读取的 XML 数据。 `file' 仅需提供 ‘read(nbytes)’
     方法，当没有更多数据可读时将返回空字符串。

 -- 成員函式: xmlparser.SetBase (base)

     设置要用于解析声明中的系统标识符的相对 URI 的基准。 解析相对标识符
     的任务会留给应用程序进行：这个值将作为 `base' 参数传递给 *note
     ExternalEntityRefHandler(): 2caf, *note NotationDeclHandler():
     2cb0. 和 *note UnparsedEntityDeclHandler(): 2cb1. 函数。

 -- 成員函式: xmlparser.GetBase ()

     返回包含之前调用 *note SetBase(): 2cae. 所设置的基准位置的字符串，
     或者如果未调用 *note SetBase(): 2cae. 则返回 ‘None’。

 -- 成員函式: xmlparser.GetInputContext ()

     将生成当前事件的输入数据以字符串形式返回。 数据为包含文本的实体的编
     码格式。 如果被调用时未激活事件处理句柄，则返回值将为 ‘None’。

 -- 成員函式: xmlparser.ExternalEntityParserCreate (context[, encoding])

     创建一个“子”解析器，可被用来解析由父解析器解析的内容所引用的外部解
     析实体。 `context' 形参应当是传递给 *note
     ExternalEntityRefHandler(): 2caf. 处理函数的字符串，具体如下所述。
     子解析器创建时 *note ordered_attributes: 2cb5. 和 *note
     specified_attributes: 2cb6. 会被设为此解析器的值。

 -- 成員函式: xmlparser.SetParamEntityParsing (flag)

     控制参数实体（包括外部 DTD 子集）的解析。 可能的 `flag' 值有
     ‘XML_PARAM_ENTITY_PARSING_NEVER’,
     ‘XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE’ 和
     ‘XML_PARAM_ENTITY_PARSING_ALWAYS’。 如果该旗标设置成功则返回真值。

 -- 成員函式: xmlparser.UseForeignDTD ([flag])

     调用时将 `flag' 设为真值（默认）将导致 Expat 调用 *note
     ExternalEntityRefHandler: 2caf. 时将所有参数设为 *note None: 203. 以
     允许加载替代的 DTD。 如果文档不包含文档类型声明，*note
     ExternalEntityRefHandler: 2caf. 仍然会被调用，但 *note
     StartDoctypeDeclHandler: 2cb9. 和 *note EndDoctypeDeclHandler:
     2cba. 将不会被调用。

     为 `flag' 传入假值将将撤消之前传入真值的调用，除此之外没有其他影响
     。

     此方法只能在调用 *note Parse(): 2cac. 或 *note ParseFile(): 2cad. 方
     法之前被调用；在已调用过这两个方法之后调用它会导致引发 *note
     ExpatError: cd8. 且 *note code: 1a. 属性被设为
     ‘errors.codes[errors.XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING]’。

‘xmlparser’ 对象具有下列属性:

 -- 屬性: xmlparser.buffer_size

     当 *note buffer_text: 2cbc. 为真值时所使用的缓冲区大小。 可以通过将
     此属性赋一个新的整数值来设置一个新的缓冲区大小。 当大小发生改变时，
     缓冲区将被刷新。

 -- 屬性: xmlparser.buffer_text

     将此属性设为真值会使得 ‘xmlparser’ 对象缓冲 Expat 所返回的文本内容
     以尽可能地避免多次调用 *note CharacterDataHandler(): 2cbd. 回调。 这
     可以显著地提升性能，因为 Expat 通常会将字符数据在每个行结束的位置上
     进行分块。 此属性默认为假值，但可以在任何时候被更改。

 -- 屬性: xmlparser.buffer_used

     当 *note buffer_text: 2cbc. 被启用时，缓冲区中存储的字节数。 这些字
     节数据表示以 UTF-8 编码的文本。 当 *note buffer_text: 2cbc. 为假值
     时此属性没有任何实际意义。

 -- 屬性: xmlparser.ordered_attributes

     将该属性设为非零整数会使得各个属性被报告为列表而非字典。 各个属性会
     按照在文档文本中的出现顺序显示。 对于每个属性，将显示两个列表条目：
     属性名和属性值。 （该模块的较旧版本也使用了此格式。） 默认情况下，
     该属性为假值；它可以在任何时候被更改。

 -- 屬性: xmlparser.specified_attributes

     如果设为非零整数，解析器将只报告在文档实例中指明的属性而不报告来自
     属性声明的属性。 设置此属性的应用程序需要特别小心地使用从声明中获得
     的附加信息以符合 XML 处理程序的行为标准。 默认情况下，该属性为假值
     ；它可以在任何时候被更改。

下列属性包含与 ‘xmlparser’ 对象遇到的最近发生的错误有关联的值，并且一旦
对 ‘Parse()’ 或 ‘ParseFile()’ 的调用引发了 *note
xml.parsers.expat.ExpatError: cd8. 异常就将只包含正确的值。

 -- 屬性: xmlparser.ErrorByteIndex

     错误发生位置的字节索引号。

 -- 屬性: xmlparser.ErrorCode

     指明问题的的数字代码。 该值可被传给 *note ErrorString(): 2ca9. 函数
     ，或是与在 ‘errors’ 对象中定义的常量之一进行比较。

 -- 屬性: xmlparser.ErrorColumnNumber

     错误发生位置的列号。

 -- 屬性: xmlparser.ErrorLineNumber

     错误发生位置的行号。

下列属性包含 ‘xmlparser’ 对象中关联到当前解析位置的值。 在回调报告解析事
件期间它们将指示生成事件的字符序列的第一个字符的位置。 当在回调的外部被
调用时，所指示的位置将恰好位于最后的解析事件之后（无论是否存在关联的回调
）。

 -- 屬性: xmlparser.CurrentByteIndex

     解析器输入的当前字节索引号。

 -- 屬性: xmlparser.CurrentColumnNumber

     解析器输入的当前列号。

 -- 屬性: xmlparser.CurrentLineNumber

     解析器输入的当前行号。

可被设置的处理句柄列表。 要在一个 ‘xmlparser’ 对象 `o' 上设置处理句柄，
请使用 ‘o.handlername = func’。 `handlername' 必须从下面的列表中获取，而
`func' 必须为接受正确数量参数的可调用对象。 所有参数均为字符串，除非另外
指明。

 -- 成員函式: xmlparser.XmlDeclHandler (version, encoding, standalone)

     当解析 XML 声明时被调用。 XML 声明是 XML 建议适用版本、文档文本的编
     码格式，以及可选的“独立”声明的（可选）声明。 `version' 和
     `encoding' 将为字符串，而 `standalone' 在文档被声明为独立时将为
     ‘1’，在文档被声明为非独立时将为 ‘0’，或者在 standalone 短语被省略时
     则为 ‘-1’。 这仅适用于 Expat 的 1.95.0 或更新版本。

 -- 成員函式: xmlparser.StartDoctypeDeclHandler (doctypeName, systemId,
          publicId, has_internal_subset)

     当 Expat 开始解析文档类型声明 (‘<!DOCTYPE ...’) 时被调用。
     `doctypeName' 会完全按所显示的被提供。 `systemId' 和 `publicId' 形
     参给出所指定的系统和公有标识符，如果被省略则为 ‘None’。 如果文档包
     含内部文档声明子集则 `has_internal_subset' 将为真值。 这要求 Expat
     1.2 或更新的版本。

 -- 成員函式: xmlparser.EndDoctypeDeclHandler ()

     当 Expat 完成解析文档类型声明时被调用。 这要求 Expat 1.2 或更新版本
     。

 -- 成員函式: xmlparser.ElementDeclHandler (name, model)

     为每个元素类型声明调用一次。 `name' 为元素类型名称，而 `model' 为内
     容模型的表示形式。

 -- 成員函式: xmlparser.AttlistDeclHandler (elname, attname, type,
          default, required)

     为一个元素类型的每个已声明属性执行调用。 如果一个属性列表声明声明了
     三个属性，这个处理句柄会被调用三次，每个属性一次。 `elname' 是声明
     所适用的元素的名称而 `attname' 是已声明的属性的名称。 属性类型是作
     为 `type' 传入的字符串；可能的值有 ‘'CDATA'’, ‘'ID'’, ‘'IDREF'’,
     ...  `default' 给出了当属性未被文档实例所指明时该属性的默认值，或是
     为 ‘None’，如果没有默认值 (‘#IMPLIED’ 值) 的话。 如果属性必须在文档
     实例中给出，则 `required' 将为真值。 这要求 Expat 1.95.0 或更新的版
     本。

 -- 成員函式: xmlparser.StartElementHandler (name, attributes)

     在每个元素开始时被调用。 `name' 是包含元素名称的字符串，而
     `attributes' 是元素的属性。 如果 *note ordered_attributes: 2cb5. 为
     真值，则属性为列表形式 (完整描述参见 *note ordered_attributes:
     2cb5.)。 否则为将名称映射到值的字典。

 -- 成員函式: xmlparser.EndElementHandler (name)

     在每个元素结束时被调用。

 -- 成員函式: xmlparser.ProcessingInstructionHandler (target, data)

     在每次处理指令时调用。

 -- 成員函式: xmlparser.CharacterDataHandler (data)

     针对字符数据调用。 此方法将被用于普通字符数据、CDATA 标记内容以及可
     忽略的空白符。 需要区分这几种情况的应用程序可以使用 *note
     StartCdataSectionHandler: 2ccc, *note EndCdataSectionHandler: 2ccd.
     和 *note ElementDeclHandler: 2cc7. 回调来收集必要的信息。

 -- 成員函式: xmlparser.UnparsedEntityDeclHandler (entityName, base,
          systemId, publicId, notationName)

     针对未解析（NDATA）实体声明调用。 此方法仅存在于 Expat 库的 1.  2 版
     ；对于更新的版本，请改用 *note EntityDeclHandler: 2cce.。 （下层
     Expat 库中的对应函数已被声明为过时。）

 -- 成員函式: xmlparser.EntityDeclHandler (entityName,
          is_parameter_entity, value, base, systemId, publicId,
          notationName)

     针对所有实体声明被调用。 对于形参和内部实体，`value' 将为给出实体的
     声明内容的字符串；对于外部实体将为 ‘None’。 `notationName' 形参对于
     已解析实体将为 ‘None’，对于未解析实体则为标注的名称。 如果实体为形
     参实体则 `is_parameter_entity' 将为真值而如果为普通实体则为假值（大
     多数应用程序只需要关注普通实体）。 此方法仅从 1.95.0 版 Expat 库开
     始才可用。

 -- 成員函式: xmlparser.NotationDeclHandler (notationName, base,
          systemId, publicId)

     针对标注声明被调用。 `notationName', `base', `systemId' 和
     `publicId' 如果给出则均应为字符串。 如果省略公有标识符，则
     `publicId' 将为 ‘None’。

 -- 成員函式: xmlparser.StartNamespaceDeclHandler (prefix, uri)

     当一个元素包含命名空间声明时被调用。 命名空间声明会在为声明所在的元
     素调用 *note StartElementHandler: 2cc9. 之前被处理。

 -- 成員函式: xmlparser.EndNamespaceDeclHandler (prefix)

     当到达包含命名空间声明的元素的关闭标记时被调用。 此方法会按照调用
     *note StartNamespaceDeclHandler: 2ccf. 以指明每个命名空间作用域的开
     始的逆顺序为元素上的每个命名空间声明调用一次。 对这个处理句柄的调用
     是在相应的 *note EndElementHandler: 2cca. 之后针对元素的结束而进行
     的。

 -- 成員函式: xmlparser.CommentHandler (data)

     针对注释被调用。 `data' 是注释的文本，不包括开头的 ‘'<!-’‘-'’ 和末
     尾的 ‘'-’‘->'’。

 -- 成員函式: xmlparser.StartCdataSectionHandler ()

     在一个 CDATA 节的开头被调用。 需要此方法和 *note
     EndCdataSectionHandler: 2ccd. 以便能够标识 CDATA 节的语法开始和结束
     。

 -- 成員函式: xmlparser.EndCdataSectionHandler ()

     在一个 CDATA 节的末尾被调用。

 -- 成員函式: xmlparser.DefaultHandler (data)

     针对 XML 文档中没有指定适用处理句柄的任何字符被调用。 这包括了所有
     属于可被报告的结构的一部分，但未提供处理句柄的字符。

 -- 成員函式: xmlparser.DefaultHandlerExpand (data)

     这与 *note DefaultHandler(): 2cd2. 相同，但不会抑制内部实体的扩展。
     实体引用将不会被传递给默认处理句柄。

 -- 成員函式: xmlparser.NotStandaloneHandler ()

     当 XML 文档未被声明为独立文档时被调用。 这种情况发生在出现外部子集
     或对参数实体的引用，但 XML 声明没有在 XML 声明中将 standalone 设为
     ‘yes’ 的时候。 如果这个处理句柄返回 ‘0’，那么解析器将引发
     ‘XML_ERROR_NOT_STANDALONE’ 错误。 如果这个处理句柄没有被设置，那么
     解析器就不会为这个条件引发任何异常。

 -- 成員函式: xmlparser.ExternalEntityRefHandler (context, base,
          systemId, publicId)

     为对外部实体的引用执行调用。 `base' 为当前的基准，由之前对 *note
     SetBase(): 2cae. 的调用设置。 公有和系统标识符 `systemId' 和
     `publicId' 如果给出则圴为字符串；如果公有标识符未给出，则
     `publicId' 将为 ‘None’。 `context' 是仅根据以下说明来使用的不透明值
     。

     对于要解析的外部实体，这个处理句柄必须被实现。 它负责使用
     ‘ExternalEntityParserCreate(context)’ 来创建子解析器，通过适当的回
     调将其初始化，并对实体进行解析。 这个处理句柄应当返回一个整数；如果
     它返回 ‘0’，则解析器将引发 ‘XML_ERROR_EXTERNAL_ENTITY_HANDLING’ 错
     误，否则解析将会继续。

     如果未提供这个处理句柄，外部实体会由 *note DefaultHandler: 2cd2. 回
     调来报告，如果提供了该回调的话。


File: python.info,  Node: ExpatError 异常,  Next: 示例<31>,  Prev: XMLParser对象<2>,  Up: xml parsers expat --- 使用 Expat 的快速 XML 解析

5.20.13.2 ExpatError 异常
.........................

*note ExpatError: cd8. 异常包含几个有趣的属性:

 -- 屬性: ExpatError.code

     Expat 对于指定错误的内部错误号。 *note errors.messages: 2cd7. 字典
     会将这些错误号映射到 Expat 的错误消息。 例如:

          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])

     *note errors: 142. 模块也提供了一些错误消息常量和一个将这些消息映射
     回错误码的字典 *note codes: 2cd8.，参见下文。

 -- 屬性: ExpatError.lineno

     检测到错误所在的行号。 首行的行号为 ‘1’。

 -- 屬性: ExpatError.offset

     错误发生在行中的字符偏移量。 首列的列号为 ‘0’。


File: python.info,  Node: 示例<31>,  Next: 内容模型描述,  Prev: ExpatError 异常,  Up: xml parsers expat --- 使用 Expat 的快速 XML 解析

5.20.13.3 示例
..............

以下程序定义了三个处理句柄，会简单地打印出它们的参数。:

     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)

来自这个程序的输出是:

     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


File: python.info,  Node: 内容模型描述,  Next: Expat 错误常量,  Prev: 示例<31>,  Up: xml parsers expat --- 使用 Expat 的快速 XML 解析

5.20.13.4 内容模型描述
......................

内容模型是使用嵌套的元组来描述的。 每个元素包含四个值：类型、限定符、名
称和一个子元组。 子元组就是附加的内容模型描述。

前两个字段的值是在 *note xml.parsers.expat.model: 143. 模块中定义的常量
。 这些常量可分为两组：模型类型组和限定符组。

模型类型组中的常量有:

 -- Data: xml.parsers.expat.model.XML_CTYPE_ANY

     模型名称所指定的元素被声明为具有 ‘ANY’ 内容模型。

 -- Data: xml.parsers.expat.model.XML_CTYPE_CHOICE

     命名元素允许从几个选项中选择；这被用于内容模型例如 ‘(A | B | C)’。

 -- Data: xml.parsers.expat.model.XML_CTYPE_EMPTY

     被声明为 ‘EMPTY’ 的元素具有此模型类型。

 -- Data: xml.parsers.expat.model.XML_CTYPE_MIXED

 -- Data: xml.parsers.expat.model.XML_CTYPE_NAME

 -- Data: xml.parsers.expat.model.XML_CTYPE_SEQ

     代表彼此相连的一系列模型的模型用此模型类型来指明。 这被用于 ‘(A, B,
     C)’ 这样的模型。

限定符组中的常量有:

 -- Data: xml.parsers.expat.model.XML_CQUANT_NONE

     未给出限定符，这样它可以只出现一次，例如 ‘A’。

 -- Data: xml.parsers.expat.model.XML_CQUANT_OPT

     可选的模型：它可以出现一次或完全不出现，例如 ‘A?’。

 -- Data: xml.parsers.expat.model.XML_CQUANT_PLUS

     模型必须出现一次或多次 (例如 ‘A+’)。

 -- Data: xml.parsers.expat.model.XML_CQUANT_REP

     模型必须出现零次或多次，例如 ‘A*’。


File: python.info,  Node: Expat 错误常量,  Prev: 内容模型描述,  Up: xml parsers expat --- 使用 Expat 的快速 XML 解析

5.20.13.5 Expat 错误常量
........................

下列常量是在 *note xml.parsers.expat.errors: 142. 模块中提供的。 这些常
量在有错误发生时解读被引发的 ‘ExpatError’ 异常对象的某些属性时很有用处。
出于保持向下兼容性的理由，这些常量的值是错误 `消息' 而不是数字形式的错误
`代码'，为此你可以将它的 *note code: 1a. 属性和
‘errors.codes[errors.XML_ERROR_`CONSTANT_NAME']’ 进行比较。

‘errors’ 模块具有以下属性:

 -- Data: xml.parsers.expat.errors.codes

     将字符串描述映射到其错误代码的字典。

     3.2 版新加入.

 -- Data: xml.parsers.expat.errors.messages

     将数字形式的错误代码映射到其字符串描述的字典。

     3.2 版新加入.

 -- Data: xml.parsers.expat.errors.XML_ERROR_ASYNC_ENTITY

 -- Data:
          xml.parsers.expat.errors.XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF

     属性值中指向一个外部实体而非内部实体的实体引用。

 -- Data: xml.parsers.expat.errors.XML_ERROR_BAD_CHAR_REF

     指向一个在 XML 不合法的字符的字符引用 (例如，字符 ‘0’ 或 ’‘&#0;’’)。

 -- Data: xml.parsers.expat.errors.XML_ERROR_BINARY_ENTITY_REF

     指向一个使用标注声明，因而无法被解析的实体的实体引用。

 -- Data: xml.parsers.expat.errors.XML_ERROR_DUPLICATE_ATTRIBUTE

     一个属性在一个开始标记中被使用超过一次。

 -- Data: xml.parsers.expat.errors.XML_ERROR_INCORRECT_ENCODING

 -- Data: xml.parsers.expat.errors.XML_ERROR_INVALID_TOKEN

     当一个输入字节无法被正确分配给一个字符时引发；例如，在 UTF-8 输入流
     中的 NUL 字节 (值为 ‘0’).

 -- Data: xml.parsers.expat.errors.XML_ERROR_JUNK_AFTER_DOC_ELEMENT

     在文档元素之后出现空白符以外的内容。

 -- Data: xml.parsers.expat.errors.XML_ERROR_MISPLACED_XML_PI

     在输入数据开始位置以外的地方发现 XML 声明。

 -- Data: xml.parsers.expat.errors.XML_ERROR_NO_ELEMENTS

     文档不包含任何元素（XML 要求所有文档都包含恰好一个最高层级元素）。

 -- Data: xml.parsers.expat.errors.XML_ERROR_NO_MEMORY

     Expat 无法在内部分配内存。

 -- Data: xml.parsers.expat.errors.XML_ERROR_PARAM_ENTITY_REF

     在不被允许的位置发现一个参数实体引用。

 -- Data: xml.parsers.expat.errors.XML_ERROR_PARTIAL_CHAR

     在输入中发出一个不完整的字符。

 -- Data: xml.parsers.expat.errors.XML_ERROR_RECURSIVE_ENTITY_REF

     一个实体引用包含了对同一实体的另一个引用；可能是通过不同的名称，并
     可能是间接的引用。

 -- Data: xml.parsers.expat.errors.XML_ERROR_SYNTAX

     遇到了某个未指明的语法错误。

 -- Data: xml.parsers.expat.errors.XML_ERROR_TAG_MISMATCH

     一个结束标记不能匹配到最内层的未关闭开始标记。

 -- Data: xml.parsers.expat.errors.XML_ERROR_UNCLOSED_TOKEN

     某些记号（例如开始标记）在流结束或遇到下一个记号之前还未关闭。

 -- Data: xml.parsers.expat.errors.XML_ERROR_UNDEFINED_ENTITY

     对一个未定义的实体进行了引用。

 -- Data: xml.parsers.expat.errors.XML_ERROR_UNKNOWN_ENCODING

     文档编码格式不被 Expat 所支持。

 -- Data: xml.parsers.expat.errors.XML_ERROR_UNCLOSED_CDATA_SECTION

     一个 CDATA 标记节还未关闭。

 -- Data: xml.parsers.expat.errors.XML_ERROR_EXTERNAL_ENTITY_HANDLING

 -- Data: xml.parsers.expat.errors.XML_ERROR_NOT_STANDALONE

     解析器确定文档不是“独立的”但它却在 XML 声明中声明自己是独立的，并且
     ‘NotStandaloneHandler’ 被设置为返回 ‘0’。

 -- Data: xml.parsers.expat.errors.XML_ERROR_UNEXPECTED_STATE

 -- Data: xml.parsers.expat.errors.XML_ERROR_ENTITY_DECLARED_IN_PE

 -- Data: xml.parsers.expat.errors.XML_ERROR_FEATURE_REQUIRES_XML_DTD

     请求了一个需要已编译 DTD 支持的操作，但 Expat 被配置为不带 DTD 支持
     。 此错误应当绝对不会被 *note xml.parsers.expat: 141. 模块的标准构
     建版本所报告。

 -- Data:
          xml.parsers.expat.errors.XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING

     在解析开始之后请求一个只能在解析开始之前执行的行为改变。 此错误（目
     前）只能由 ‘UseForeignDTD()’ 所引发。

 -- Data: xml.parsers.expat.errors.XML_ERROR_UNBOUND_PREFIX

     当命名空间处理被启用时发现一个未声明的前缀。

 -- Data: xml.parsers.expat.errors.XML_ERROR_UNDECLARING_PREFIX

     文档试图移除与某个前缀相关联的命名空间声明。

 -- Data: xml.parsers.expat.errors.XML_ERROR_INCOMPLETE_PE

     一个参数实体包含不完整的标记。

 -- Data: xml.parsers.expat.errors.XML_ERROR_XML_DECL

     文档完全未包含任何文档元素。

 -- Data: xml.parsers.expat.errors.XML_ERROR_TEXT_DECL

     解析一个外部实体中的文本声明时出现错误。

 -- Data: xml.parsers.expat.errors.XML_ERROR_PUBLICID

     在公有 id 中发现不被允许的字符。

 -- Data: xml.parsers.expat.errors.XML_ERROR_SUSPENDED

     在挂起的解析器上请求执行操作，但未获得允许。 这包括提供额外输入或停
     止解析器的尝试。

 -- Data: xml.parsers.expat.errors.XML_ERROR_NOT_SUSPENDED

     在解析器未被挂起的时候执行恢复解析器的尝试。

 -- Data: xml.parsers.expat.errors.XML_ERROR_ABORTED

     此错误不应当被报告给 Python 应用程序。

 -- Data: xml.parsers.expat.errors.XML_ERROR_FINISHED

     在一个已经完成解析输入的解析器上请求执行操作，但未获得允许。 这包括
     提供额外输入或停止解析器的尝试。

 -- Data: xml.parsers.expat.errors.XML_ERROR_SUSPEND_PE

註解
....


File: python.info,  Node: 互联网协议和支持,  Next: 多媒体服务,  Prev: 结构化标记处理工具,  Up: Python 標準函式庫 Standard Library

5.21 互联网协议和支持
=====================

本章介绍的模块实现了互联网协议并支持相关技术。 它们都是用 Python 实现的
。 这些模块中的大多数都需要存在依赖于系统的模块 *note socket: ef. ，目前
大多数流行平台都支持它。 这是一个概述：

* Menu:

* webbrowser: webbrowser --- 方便的Web浏览器控制器. 方便的Web浏览器控制器
* cgi: cgi --- 通用网关接口支持. 通用网关接口支持
* cgitb: cgitb --- 用于 CGI 脚本的回溯管理器. 用于 CGI 脚本的回溯管理器
* 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 协议客户端
* nntplib: nntplib --- NNTP 协议客户端. NNTP 协议客户端
* smtplib ---SMTP协议客户端::
* smtpd: smtpd --- SMTP 服务器. SMTP 服务器
* telnetlib: telnetlib -- Telnet 客户端. Telnet 客户端
* 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 操作库


File: python.info,  Node: webbrowser --- 方便的Web浏览器控制器,  Next: cgi --- 通用网关接口支持,  Up: 互联网协议和支持

5.21.1 ‘webbrowser’ — 方便的Web浏览器控制器
-------------------------------------------

`源码：' Lib/webbrowser.py(1)

__________________________________________________________________

*note webbrowser: 132. 模块提供了一个高级接口，允许向用户显示基于Web的文
档。 在大多数情况下，只需从该模块调用 *note open(): 2d0b. 函数就可以了。

在 Unix 下，图形浏览器在 X11 下是首选，但如果图形浏览器不可用或 X11 显示
不可用，则将使用文本模式浏览器。 如果使用文本模式浏览器，则调用进程将阻
塞，直到用户退出浏览器。

如果存在环境变量 ‘BROWSER’ ，则将其解释为 *note os.pathsep: 1486. 分隔的
浏览器列表，以便在平台默认值之前尝试。 当列表部分的值包含字符串 ‘％s’ 时
，它被解释为一个文字浏览器命令行，用于替换 ‘％s’ 的参数 URL ；如果该部分
不包含 ‘％s’，则它只被解释为要启动的浏览器的名称。 (2)

对于非 Unix 平台，或者当 Unix 上有远程浏览器时，控制过程不会等待用户完成
浏览器，而是允许远程浏览器在显示界面上维护自己的窗口。 如果 Unix 上没有
远程浏览器，控制进程将启动一个新的浏览器并等待。

脚本 ‘webbrowser’ 可以用作模块的命令行界面。它接受一个 URL 作为参数。还
接受以下可选参数：‘-n’ 如果可能，在新的浏览器窗口中打开 URL ； ‘-t’ 在新
的浏览器页面（“标签”）中打开 URL。这些选择当然是相互排斥的。用法示例:

     python -m webbrowser -t "https://www.python.org"

定义了以下异常：

 -- 例外: webbrowser.Error

     发生浏览器控件错误时引发异常。

定义了以下函数：

 -- 函式: webbrowser.open (url, new=0, autoraise=True)

     使用默认浏览器显示 `url'。 如果 `new' 为 0，则尽可能在同一浏览器窗
     口中打开 `url'。 如果 `new' 为 1，则尽可能打开新的浏览器窗口。 如果
     `new' 为 2，则尽可能打开新的浏览器页面（“标签”）。 如果 `autoraise'
     为 “True”，则会尽可能置前窗口（请注意，在许多窗口管理器下，无论此变
     量的设置如何，都会置前窗口）。

     请注意，在某些平台上，尝试使用此函数打开文件名，可能会起作用并启动
     操作系统的关联程序。 但是，这种方式不被支持也不可移植。

     使用 ‘url’ 参数会引发 *note auditing event: fa1. ‘webbrowser.open’
     。

 -- 函式: webbrowser.open_new (url)

     如果可能，在默认浏览器的新窗口中打开 `url'，否则，在唯一的浏览器窗
     口中打开 `url'。

 -- 函式: webbrowser.open_new_tab (url)

     如果可能，在默认浏览器的新页面（“标签”）中打开 `url'，否则等效于
     *note open_new(): 2d0d.。

 -- 函式: webbrowser.get (using=None)

     返回浏览器类型为 `using' 指定的控制器对象。 如果 `using' 为 ‘None’，
     则返回适用于调用者环境的默认浏览器的控制器。

 -- 函式: webbrowser.register (name, constructor, instance=None, *,
          preferred=False)

     注册 `name' 浏览器类型。 注册浏览器类型后， *note get(): 2d0f. 函数
     可以返回该浏览器类型的控制器。 如果没有提供 `instance'，或者为
     ‘None’，`constructor' 将在没有参数的情况下被调用，以在需要时创建实
     例。 如果提供了 `instance'，则永远不会调用 `constructor'，并且可能
     是 ‘None’。

     将 `preferred' 设置为 ‘True’ 使得这个浏览器成为 *note get(): 2d0f.
     不带参数调用的首选结果。 否则，只有在您计划设置 ‘BROWSER’ 变量，或
     使用与您声明的处理程序的名称相匹配的非空参数调用 *note get(): 2d0f.
     时，此入口点才有用。

     3.7 版更變: 添加了仅关键字参数 `preferred'。

预定义了许多浏览器类型。 此表给出了可以传递给 *note get(): 2d0f. 函数的
类型名称以及控制器类的相应实例化，这些都在此模块中定义。

类型名                       类名                                          註解
                                                                           
---------------------------------------------------------------------------------------
                                                                           
‘'mozilla'’                  ‘Mozilla('mozilla')’
                             
                                                                           
‘'firefox'’                  ‘Mozilla('mozilla')’
                             
                                                                           
‘'netscape'’                 ‘Mozilla('netscape')’
                             
                                                                           
‘'galeon'’                   ‘Galeon('galeon')’
                             
                                                                           
‘'epiphany'’                 ‘Galeon('epiphany')’
                             
                                                                           
‘'skipstone'’                ‘BackgroundBrowser('skipstone')’
                             
                                                                           
‘'kfmclient'’                ‘Konqueror()’                                 (1)
                                                                           
                                                                           
‘'konqueror'’                ‘Konqueror()’                                 (1)
                                                                           
                                                                           
‘'kfm'’                      ‘Konqueror()’                                 (1)
                                                                           
                                                                           
‘'mosaic'’                   ‘BackgroundBrowser('mosaic')’
                             
                                                                           
‘'opera'’                    ‘Opera()’
                             
                                                                           
‘'grail'’                    ‘Grail()’
                             
                                                                           
‘'links'’                    ‘GenericBrowser('links')’
                             
                                                                           
‘'elinks'’                   ‘Elinks('elinks')’
                             
                                                                           
‘'lynx'’                     ‘GenericBrowser('lynx')’
                             
                                                                           
‘'w3m'’                      ‘GenericBrowser('w3m')’
                             
                                                                           
‘'windows-default'’          ‘WindowsDefault’                              (2)
                                                                           
                                                                           
‘'macosx'’                   ‘MacOSXOSAScript('default')’                  (3)
                                                                           
                                                                           
‘'safari'’                   ‘MacOSXOSAScript('safari')’                   (3)
                                                                           
                                                                           
‘'google-chrome'’            ‘Chrome('google-chrome')’
                             
                                                                           
‘'chrome'’                   ‘Chrome('chrome')’
                             
                                                                           
‘'chromium'’                 ‘Chromium('chromium')’
                             
                                                                           
‘'chromium-browser'’         ‘Chromium('chromium-browser')’
                             

註解：

  1. “Konqueror” 是 Unix 的 KDE 桌面环境的文件管理器，只有在 KDE 运行时
     才有意义。 一些可靠地检测 KDE 的方法会很好；仅检查 ‘KDEDIR’ 变量是
     不够的。 另请注意，KDE 2的 ‘konqueror’ 命令，会使用名称 “kfm”—此实
     现选择运行的 Konqueror 的最佳策略。

  2. 仅限 Windows 平台。

  3. Only on macOS platform.

3.3 版新加入: 添加了对 Chrome/Chromium 的支持。

以下是一些简单的例子:

     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)

* Menu:

* 浏览器控制器对象::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/webbrowser.py

   (2) (1) 这里命名的不带完整路径的可执行文件将在 ‘PATH’ 环境变量给出的
目录中搜索。


File: python.info,  Node: 浏览器控制器对象,  Up: webbrowser --- 方便的Web浏览器控制器

5.21.1.1 浏览器控制器对象
.........................

浏览器控制器提供三个与模块级便捷函数相同的方法：

 -- 成員函式: controller.open (url, new=0, autoraise=True)

     使用此控制器处理的浏览器显示 `url'。 如果 `new' 为 1，则尽可能打开
     新的浏览器窗口。 如果 `new' 为 2，则尽可能打开新的浏览器页面（“标签
     ”）。

 -- 成員函式: controller.open_new (url)

     如果可能，在此控制器处理的浏览器的新窗口中打开 `url' ，否则，在唯一
     的浏览器窗口中打开 `url' 。 别名 *note open_new(): 2d0d.。

 -- 成員函式: controller.open_new_tab (url)

     如果可能，在此控制器处理的浏览器的新页面（“标签”）中打开 `url'，否
     则等效于 *note open_new(): 2d0d.。

註解
....


File: python.info,  Node: cgi --- 通用网关接口支持,  Next: cgitb --- 用于 CGI 脚本的回溯管理器,  Prev: webbrowser --- 方便的Web浏览器控制器,  Up: 互联网协议和支持

5.21.2 ‘cgi’ — 通用网关接口支持
-------------------------------

`源代码：' Lib/cgi.py(1)

__________________________________________________________________

通用网关接口 (CGI) 脚本的支持模块

本模块定义了一些工具供以 Python 编写的 CGI 脚本使用。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/cgi.py


File: python.info,  Node: 簡介<10>,  Next: 使用cgi模块。,  Up: cgi --- 通用网关接口支持

5.21.2.1 簡介
.............

CGI 脚本是由 HTTP 服务器发起调用，通常用来处理通过 HTML ‘<FORM>’ 或
‘<ISINDEX>’ 元素提交的用户输入。

在大多数情况下，CGI 脚本存放在服务器的 ‘cgi-bin’ 特殊目录下。 HTTP 服务
器将有关请求的各种信息（例如客户端的主机名、所请求的 URL、查询字符串以及
许多其他内容）放在脚本的 shell 环境中，然后执行脚本，并将脚本的输出发回
到客户端。

脚本的输入也会被连接到客户端，并且有时表单数据也会以此方式来读取；在其他
时候表单数据会通过 URL 的“查询字符串”部分来传递。 本模块的目标是处理不同
的应用场景并向 Python 脚本提供一个更为简单的接口。 它还提供了一些工具为
脚本调试提供帮助，而最近增加的还有对通过表单上传文件的支持（如果你的浏览
器支持该功能的话）。

CGI 脚本的输出应当由两部分组成，并由一个空行分隔。 前一部分包含一些标头
，它们告诉客户端后面会提供何种数据。 生成一个最小化标头部分的 Python 代
码如下所示:

     print("Content-Type: text/html")    # HTML is following
     print()                             # blank line, end of headers

后一部分通常为 HTML，提供给客户端软件来显示格式良好包含标题的文本、内联
图片等内容。 下面是打印一段简单 HTML 的 Python 代码:

     print("<TITLE>CGI script output</TITLE>")
     print("<H1>This is my first CGI script</H1>")
     print("Hello, world!")


File: python.info,  Node: 使用cgi模块。,  Next: 更高层级的接口,  Prev: 簡介<10>,  Up: cgi --- 通用网关接口支持

5.21.2.2 使用cgi模块。
......................

通过敲下 ‘import cgi’ 来开始。

当你在写一个新脚本时，考虑加上这些语句:

     import cgitb
     cgitb.enable()

这会激活一个特殊的异常处理句柄，它将在发生任何错误时将详细错误报告显示到
Web 浏览器中。 如果你不希望向你的脚本 的用户显示你的程序的内部细节，你可
以改为将报告保存到文件中，使用这样的代码即可:

     import cgitb
     cgitb.enable(display=0, logdir="/path/to/logdir")

在脚本开发期间使用此特性会很有帮助。 *note cgitb: 16. 所产生的报告提供了
在追踪程序问题时能为你节省大量时间的信息。 你可以在完成测试你的脚本并确
信它能正确工作之后再移除 ‘cgitb’ 行。

To get at submitted form data, use the ‘FieldStorage’ class.  If the
form contains non-ASCII characters, use the `encoding' keyword parameter
set to the value of the encoding defined for the document.  It is
usually contained in the META tag in the HEAD section of the HTML
document or by the ‘Content-Type’ header.  This reads the form contents
from the standard input or the environment (depending on the value of
various environment variables set according to the CGI standard).  Since
it may consume standard input, it should be instantiated only once.

‘FieldStorage’ 实例可以像 Python 字典一样来检索。 它允许通过 *note in:
179. 运算符进行成员检测，也支持标准字典方法 *note keys(): cf4. 和内置函
数 *note len(): 28b.。 包含空字符串的表单字段会被忽略而不会出现在字典中
；要保留这样的值，请在创建 ‘FieldStorage’ 实例时为可选的
`keep_blank_values' 关键字形参提供一个真值。

举例来说，下面的代码（假定 ‘Content-Type’ 标头和空行已经被打印）会检查字
段 ‘name’ 和 ‘addr’ 是否均被设为非空字符串:

     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...

在这里的字段通过 ‘form[key]’ 来访问，它们本身就是 ‘FieldStorage’ (或
‘MiniFieldStorage’，取决于表单的编码格式) 的实例。 实例的 ‘value’ 属性会
产生字段的字符串值。 ‘getvalue()’ 方法直接返回这个字符串；它还接受可选的
第二个参数作为当请求的键不存在时要返回的默认值。

如果提交的表单数据包含一个以上的同名字段，由 ‘form[key]’ 所提取的对象将
不是一个 ‘FieldStorage’ 或 ‘MiniFieldStorage’ 实例而是由这种实例组成的列
表。 类似地，在这种情况下，‘form.getvalue(key)’ 将会返回一个字符串列表。
如果你预计到这种可能性（当你的 HTML 表单包含多个同名字段时），请使用
*note getlist(): 2d1c. 方法，它总是返回一个值的列表（这样你就不需要对只
有单个项的情况进行特别处理）。 例如，这段代码拼接了任意数量的 username 字
段，以逗号进行分隔:

     value = form.getlist("username")
     usernames = ",".join(value)

如果一个字段是代表上传的文件，请通过 ‘value’ 属性访问该值或是通过
‘getvalue()’ 方法以字节形式将整个文件读入内存。 这可能不是你想要的结果。
你可以通过测试 ‘filename’ 属性或 ‘file’ 属性来检测上传的文件。 然后你可
以从 ‘file’ 属性读取数据，直到它作为 ‘FieldStorage’ 实例的垃圾回收的一部
分被自动关闭 (*note read(): 7f3. 和 *note readline(): 1849. 方法将返回字
节数据):

     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

‘FieldStorage’ 对象还支持在 *note with: 7da. 语句中使用，该语句结束时将
自动关闭它们。

如果在获取上传文件的内容时遇到错误（例如，当用户点击回退或取消按钮中断表
单提交时）该字段中对象的 ‘done’ 属性值将被设为 -1。

文件上传标准草案考虑到了从一个字段上传多个文件的可能性（使用递归的
‘multipart/*’ 编码格式）。 当这种情况发生时，该条目将是一个类似字典的
‘FieldStorage’ 条目。 这可以通过检测它的 ‘type’ 属性来确定，该属性应当是
‘multipart/form-data’ (或者可能是匹配 ‘multipart/*’ 的其他 MIME 类型)。
在这种情况下，它可以像最高层级的表单对象一样被递归地迭代处理。

当一个表单按“旧”格式提交时（即以查询字符串或是单个
‘application/x-www-form-urlencoded’ 类型的数据部分的形式），这些条目实际
上将是 ‘MiniFieldStorage’ 类的实例。 在这种情况下，‘list’, ‘file’ 和
‘filename’ 属性将总是为 ‘None’。

通过 POST 方式提交并且也带有查询字符串的表单将同时包含 ‘FieldStorage’ 和
‘MiniFieldStorage’ 条目。

3.4 版更變: ‘file’ 属性会在创建 ‘FieldStorage’ 实例的垃圾回收操作中被自
动关闭。

3.5 版更變: 为 ‘FieldStorage’ 类增加了上下文管理协议支持。


File: python.info,  Node: 更高层级的接口,  Next: 函数<9>,  Prev: 使用cgi模块。,  Up: cgi --- 通用网关接口支持

5.21.2.3 更高层级的接口
.......................

前面的部分解释了如何使用 ‘FieldStorage’ 类来读取 CGI 表单数据。 本部分则
会描述一个更高层级的接口，它被添加到此类中以允许人们以更为可读和自然的方
式行事。 这个接口并不会完全取代前面的部分所描述的技巧 — 例如它们在高效处
理文件上传时仍然很有用处。

此接口由两个简单的方法组成。 你可以使用这两个方法以通用的方式处理表单数
据，而无需担心在一个名称下提交的值是只有一个还是有多个。

在前面的部分中，你已学会当你预期用户在一个名称下提交超过一个值的时候编写
以下代码:

     item = form.getvalue("item")
     if isinstance(item, list):
         # The user is requesting more than one item.
     else:
         # The user is requesting only one item.

这种情况很常见，例如当一个表单包含具有相同名称的一组复选框的时候:

     <input type="checkbox" name="item" value="1" />
     <input type="checkbox" name="item" value="2" />

但是在多数情况下，一个表单中的一个特定名称只对应一个表单控件。 因此你可
能会编写包含以下代码的脚本:

     user = form.getvalue("user").upper()

这段代码的问题在于你绝不能预期客户端会向你的脚本提供合法的输入。 举例来
说，如果一个好奇的用户向查询字符串添加了另一个 ‘user=foo’ 对，则该脚本将
会崩溃，因为在这种情况下 ‘getvalue("user")’ 方法调用将返回一个列表而不是
字符串。 在一个列表上调用 *note upper(): 1791. 方法是不合法的（因为列表
并没有这个方法）因而会引发 *note AttributeError: 4a1. 异常。

因此，读取表单数据值的正确方式应当总是使用检查所获取的值是单一值还是值列
表的代码。 这很麻烦并且会使脚本缺乏可读性。

一种更便捷的方式是使用这个更高层级接口所提供的 *note getfirst(): 2d1e. 和
*note getlist(): 2d1c. 方法。

 -- 成員函式: FieldStorage.getfirst (name, default=None)

     此方法总是只返回与表单字段 `name' 相关联的单一值。 此方法在同一名称
     下提交了多个值的情况下将仅返回第一个值。 请注意所接收的值顺序在不同
     浏览器上可能发生变化因而是不确定的。 (1) 如果指定的表单字段或值不存
     在则此方法将返回可选形参 `default' 所指定的值。 如果未指定此形参则
     默认值为 ‘None’。

 -- 成員函式: FieldStorage.getlist (name)

     此方法总是返回与表单字段 `name' 相关联的值列表。 如果 `name' 指定的
     表单字段或值不存在则此方法将返回一个空列表。 如果指定的表单字段只包
     含一个值则它将返回只有一项的列表。

使用这两个方法你将能写出优雅简洁的代码:

     import cgi
     form = cgi.FieldStorage()
     user = form.getfirst("user", "").upper()    # This way it's safe.
     for item in form.getlist("item"):
         do_something(item)

   ---------- Footnotes ----------

   (1) (1) 请注意，新版的 HTML 规范确实注明了请求字段的顺序，但判断请求
是否合法非常繁琐和容易出错，可能来自不符合要求的浏览器，甚至不是来自浏览
器。


File: python.info,  Node: 函数<9>,  Next: 对于安全性的关注,  Prev: 更高层级的接口,  Up: cgi --- 通用网关接口支持

5.21.2.4 函数
.............

这些函数在你想要更多控制，或者如果你想要应用一些此模块中在其他场景下实现
的算法时很有用处。

 -- 函式: cgi.parse (fp=None, environ=os.environ,
          keep_blank_values=False, strict_parsing=False, separator="&")

     在环境中或从某个文件中解析一个查询 (文件默认为 ‘sys.stdin’)。
     `keep_blank_values', `strict_parsing' 和 `separator' 形参会被原样传
     给 *note urllib.parse.parse_qs(): 27f.。

 -- 函式: cgi.parse_multipart (fp, pdict, encoding="utf-8",
          errors="replace", separator="&")

     解析 ‘multipart/form-data’ 类型（用于文件上传）的输入。 参数中 `fp'
     为输入文件，`pdict' 为包含 ‘Content-Type’ 标头中的其他形参的字典，
     `encoding' 为请求的编码格式。

     像 *note urllib.parse.parse_qs(): 27f. 那样返回一个字典：其中的键为
     字段名称，值为对应字段的值列表。 对于非文件字段，其值均为字符串列表
     。

     这很容易使用，但如果你预期要上传巨量字节数据时就不太适合了 — 在这种
     情况下，请改用更为灵活的 ‘FieldStorage’ 类。

     3.7 版更變: 增加了 `encoding' 和 `errors' 形参。 对于非文件字段，其
     值现在为字符串列表而非字节串列表。

     3.9.2 版更變: 增加了 `separator' 形参。

 -- 函式: cgi.parse_header (string)

     将一个 MIME 标头 (例如 ‘Content-Type’) 解析为一个主值和一个参数字典
     。

 -- 函式: cgi.test ()

     对 CGI 执行健壮性检测，适于作为主程序。 写入最小化的 HTTP 标头并以
     HTML 格式来格式化提供给脚本的所有信息。

 -- 函式: cgi.print_environ ()

     以 HTML 格式来格式化 shell 环境。

 -- 函式: cgi.print_form (form)

     以 HTML 格式来格式化表单。

 -- 函式: cgi.print_directory ()

     以 HTML 格式来格式化当前目录。

 -- 函式: cgi.print_environ_usage ()

     以 HTML 格式打印有用的环境变量列表（供 CGI 使用）。


File: python.info,  Node: 对于安全性的关注,  Next: 在 Unix 系统上安装你的 CGI 脚本,  Prev: 函数<9>,  Up: cgi --- 通用网关接口支持

5.21.2.5 对于安全性的关注
.........................

有一条重要的规则：如果你发起调用一个外部程序（通过 *note os.system():
e86, *note os.popen(): 3cb. 或其他具有类似功能的函数），需要非常确定你不
会把从客户端接收的任意字符串直接传给 shell。 这是一个著名的安全漏洞，网
络中聪明的黑客可以通过它来利用容易上当的 CGI 脚本发起调用任何 shell 命令
。 即使 URL 的一部分或字段名称也是不可信任的，因为请求并不一定是来自你的
表单！

为了安全起见，如果你必须将从表单获取的字符串传给 shell 命令，你应当确保
该字符串仅包含字母数字类字符、连字符、下划线和句点。


File: python.info,  Node: 在 Unix 系统上安装你的 CGI 脚本,  Next: 测试你的 CGI 脚本,  Prev: 对于安全性的关注,  Up: cgi --- 通用网关接口支持

5.21.2.6 在 Unix 系统上安装你的 CGI 脚本
........................................

请阅读你的 HTTP 服务器的文档并咨询你所用系统的管理员来找到 CGI 脚本应当
安装到哪个目录；通常是服务器目录树中的 ‘cgi-bin’ 目录。

请确保你的脚本可被“其他人”读取和执行；Unix 文件模式应为八进制数 ‘0o755’
(使用 ‘chmod 0755 filename’)。 请确保脚本的第一行包含 ‘#!’ 且位置是从第
1 列开始，后面带有 Python 解释器的路径名，例如:

     #!/usr/local/bin/python

请确保该 Python 解释器存在并且可被“其他人”执行。

请确保你的脚本需要读取或写入的任何文件都分别是“其他人”可读取或可写入的 —
它们的模式应为可读取 ‘0o644’ 或可写入 ‘0o666’。 这是因为出于安全理由，
HTTP 服务器是作为没有任何特殊权限的 "nobody" 用户来运行脚本的。 它只能读
取（写入、执行）任何人都能读取（写入、执行）的文件。 执行时的当前目录（
通常为服务器的 cgi-bin 目录）和环境变量集合也与你在登录时所得到的不同。
特别地，不可依赖于 shell 的可执行文件搜索路径 ( ‘PATH’) 或 Python 模块搜
索路径 ( *note PYTHONPATH: a34.) 的任何相关设置。

如果你需要从 Python 的默认模块搜索路径之外的目录载入模块，你可以在导入其
他模块之前在你的脚本中改变路径。 例如:

     import sys
     sys.path.insert(0, "/usr/home/joe/lib/python")
     sys.path.insert(0, "/usr/local/lib/python")

（在此方式下，最后插入的目录将最先被搜索！）

针对非 Unix 系统的指导会有所变化；请查看你的 HTTP 服务器的文档（通常会有
关于 CGI 脚本的部分）。


File: python.info,  Node: 测试你的 CGI 脚本,  Next: 调试 CGI 脚本,  Prev: 在 Unix 系统上安装你的 CGI 脚本,  Up: cgi --- 通用网关接口支持

5.21.2.7 测试你的 CGI 脚本
..........................

很不幸，当你在命令行中尝试 CGI 脚本时它通常会无法运行，而能在命令行中完
美运行的脚本则可能会在运行于服务器时神秘地失败。 但有一个理由使你仍然应
当在命令行中测试你的脚本：如果它包含语法错误，Python 解释器将根本不会执
行它，而 HTTP 服务器将很可能向客户端发送令人费解的错误信息。

假定你的脚本没有语法错误，但它仍然无法起作用，你将别无选择，只能继续阅读
下一节。


File: python.info,  Node: 调试 CGI 脚本,  Next: 常见问题和解决方案,  Prev: 测试你的 CGI 脚本,  Up: cgi --- 通用网关接口支持

5.21.2.8 调试 CGI 脚本
......................

首先，请检查是否有安装上的小错误 — 仔细阅读上面关于安装 CGI 脚本的部分可
以使你节省大量时间。 如果你不确定你是否正确理解了安装过程，请尝试将此模
块 (‘cgi.py’) 的副本作为 CGI 脚本安装。 当作为脚本被发起调用时，该文件将
以 HTML 格式转储其环境和表单内容。 请给它赋予正确的模式等，并向它发送一
个请求。 如果它是安装在标准的 ‘cgi-bin’ 目录下，应该可以通过在你的浏览器
中输入表单的 URL 来向它发送请求。

     http://yourhostname/cgi-bin/cgi.py?name=Joe+Blow&addr=At+Home

如果此操作给出类型为 404 的错误，说明服务器找不到此脚本 – 也许你需要将它
安装到不同的目录。 如果它给出另一种错误，说明存在安装问题，你应当解决此
问题才能继续操作。 如果你得到一个格式良好的环境和表单内容清单（在这个例
子中，应当会列出的有字段 "addr" 值为 "At Home" 以及 "name" 值为 "Joe
Blow"），则说明 ‘cgi.py’ 脚本已正确安装。 如果你为自己的脚本执行了同样的
过程，现在你应该能够调试它了。

下一步骤可以是在你的脚本中调用 *note cgi: 15. 模块的 *note test(): 105.
函数：用这一条语句替换它的主代码

     cgi.test()

这将产生从安装 ‘cgi.py’ 文件本身所得到的相同结果。

当某个常规 Python 脚本触发了未处理的异常，（无论出于什么原因：模块名称出
错、文件无法打开等)，Python 解释器就会打印出一条完整的跟踪信息并退出。在
CGI 脚本触发异常时，Python 解释器依然会如此，但最有可能的是，跟踪信息只
会停留在某个 HTTP 服务日志文件中，或者被完全丢弃。

幸运的是，只要执行 `某些' 代码，就可以利用 *note cgitb: 16. 模块将跟踪信
息发送给浏览器。 如果你还没有这样做过，只需添加以下几行代码:

     import cgitb
     cgitb.enable()

然后再运行一下看；发生问题时应能看到详细的报告，或许能让崩溃的原因更清晰
一些。

如果怀疑是 *note cgitb: 16. 模块导入的问题，可以采用一个功能更强的方法（
只用到内置模块）：

     import sys
     sys.stderr = sys.stdout
     print("Content-Type: text/plain")
     print()
     ...your code here...

这得靠 Python 解释器来打印跟踪信息。输出的类型为纯文本，不经过任何 HTML
处理。如果代码正常，则客户端会显示原有的 HTML。如果触发了异常，很可能在
输出前两行后会显示一条跟踪信息。因为不会继续进行 HTML 解析，所以跟踪信息
肯定能被读到。


File: python.info,  Node: 常见问题和解决方案,  Prev: 调试 CGI 脚本,  Up: cgi --- 通用网关接口支持

5.21.2.9 常见问题和解决方案
...........................

   * 大部分 HTTP 服务器会对 CGI 脚本的输出进行缓存，等脚本执行完毕再行输
     出。这意味着在脚本运行时，不可能在客户端屏幕上显示出进度情况。

   * 请查看上述安装说明。

   * 请查看 HTTP 服务器的日志文件。（在另一个单独窗口中执行 ‘tail -f
     logfile’ 可能会很有用！）

   * 一定要先检查脚本是否有语法错误，做法类似：‘python script.py’ 。

   * 如果脚本没有语法错误，试着在脚本的顶部添加 ‘import cgitb;
     cgitb.enable()’。

   * 当调用外部程序时，要确保其可被读取。通常这意味着采用绝对路径名—— 在
     CGI 脚本中， ‘PATH’ 通常不会设为很有用的值。

   * 在读写外部文件时，要确保其能被 CGI 脚本归属的用户读写：通常是运行网
     络服务的用户，或由网络服务的 ‘suexec’ 功能明确指定的一些用户。

   * 不要试图给 CGI 脚本赋予 set-uid 模式。这在大多数系统上这都行不通，
     出于安全考虑也不应如此。

註解
....


File: python.info,  Node: cgitb --- 用于 CGI 脚本的回溯管理器,  Next: wsgiref --- WSGI 工具和引用的实现,  Prev: cgi --- 通用网关接口支持,  Up: 互联网协议和支持

5.21.3 ‘cgitb’ — 用于 CGI 脚本的回溯管理器
------------------------------------------

`源代码:' Lib/cgitb.py(1)

__________________________________________________________________

*note cgitb: 16. 模块提供了用于 Python 脚本的特殊异常处理程序。 （这个名
称有一点误导性。 它最初是设计用来显示 HTML 格式的 CGI 脚本详细回溯信息。
但后来被一般化为也可显示纯文本格式的回溯信息。） 激活这个模块之后，如果
发生了未被捕获的异常，将会显示详细的已格式化的报告。 报告显示内容包括每
个层级的源代码摘录，还有当前正在运行的函数的参数和局部变量值，以帮助你调
试问题。 你也可以选择将此信息保存至文件而不是将其发送至浏览器。

要启用此特性，只需简单地将此代码添加到你的 CGI 脚本的最顶端:

     import cgitb
     cgitb.enable()

*note enable(): 2d2f. 函数的选项可以控制是将报告显示在浏览器中，还是将报
告记录到文件供以后进行分析。

 -- 函式: cgitb.enable (display=1, logdir=None, context=5,
          format="html")

     此函数可通过设置 *note sys.excepthook: f24. 的值以使 *note cgitb:
     16. 模块接管解释器默认的异常处理机制。

     可选参数 `display' 默认为 ‘1’ 并可被设为 ‘0’ 来停止将回溯发送至浏览
     器。 如果给出了参数 `logdir'，则回溯会被写入文件。 `logdir' 的值应
     当是一个用于存放所写入文件的目录。 可选参数 `context' 是要在回溯中
     的当前源代码行前后显示的上下文行数；默认为 ‘5’。 如果可选参数
     `format' 为 ‘"html"’，输出将为 HTML 格式。 任何其它值都会强制启用纯
     文本输出。 默认取值为 ‘"html"’。

 -- 函式: cgitb.text (info, context=5)

     此函数用于处理 `info' (一个包含 *note sys.exc_info(): d27. 返回结果
     的 3 元组) 所描述的异常，将其回溯格式化为文本并将结果作为字符串返回
     。 可选参数 `context' 是要在回溯中的当前源码行前后显示的上下文行数
     ；默认为 ‘5’。

 -- 函式: cgitb.html (info, context=5)

     此函数用于处理 `info' (一个包含 *note sys.exc_info(): d27. 返回结果
     的 3 元组) 所描述的异常，将其回溯格式化为 HTML 并将结果作为字符串返
     回。 可选参数 `context' 是要在回溯中的当前源码行前后显示的上下文行
     数；默认为 ‘5’。

 -- 函式: cgitb.handler (info=None)

     此函数使用默认设置处理异常（即在浏览器中显示报告，但不记录到文件）
     。 当你捕获了一个异常并希望使用 *note cgitb: 16. 来报告它时可以使用
     此函数。 可选的 `info' 参数应为一个包含异常类型，异常值和回溯对象的
     3 元组，与 *note sys.exc_info(): d27. 所返回的元组完全一致。 如果未
     提供 `info' 参数，则会从 *note sys.exc_info(): d27. 获取当前异常。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/cgitb.py


File: python.info,  Node: wsgiref --- WSGI 工具和引用的实现,  Next: urllib --- URL 处理模块,  Prev: cgitb --- 用于 CGI 脚本的回溯管理器,  Up: 互联网协议和支持

5.21.4 ‘wsgiref’ — WSGI 工具和引用的实现
----------------------------------------

__________________________________________________________________

Web 服务器网关接口（WSGI）是 Web 服务器软件和用 Python 编写的 Web 应用程
序之间的标准接口。 具有标准接口能够让支持 WSGI 的应用程序与多种不同的
Web 服务器配合使用。

只有 Web 服务器和编程框架的开发者才需要了解 WSGI 设计的每个细节和边界情
况。 你不需要了解 WSGI 的每个细节而只需要安装一个 WSGI 应用程序或编写使
用现有框架的 Web 应用程序。

*note wsgiref: 135. 是一个 WSGI 规范的参考实现，可被用于将 WSGI 支持添加
到 Web 服务器或框架中。 它提供了操作 WSGI 环境变量和响应标头的工具，实现
WSGI 服务器的基类，一个可部署 WSGI 应用程序的演示性 HTTP 服务器，以及一
个用于检查 WSGI 服务器和应用程序是否符合 WSGI 规范的验证工具 ( PEP
3333(1))。

参看 wsgi.readthedocs.io(2) 获取有关 WSGI 的更多信息，以及教程和其他资源
的链接。

* 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>.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3333

   (2) https://wsgi.readthedocs.io/


File: python.info,  Node: wsgiref util -- WSGI 环境工具,  Next: wsgiref headers -- WSGI 响应标头工具,  Up: wsgiref --- WSGI 工具和引用的实现

5.21.4.1 ‘wsgiref.util’ – WSGI 环境工具
.......................................

本模块提供了多种工具配合 WSGI 环境使用。 WSGI 环境就是一个包含 PEP
3333(1) 所描述的 HTTP 请求变量的目录。 所有接受 `environ' 形参的函数都会
预期被得到一个符合 WSGI 规范的目录；请参阅 PEP 3333(2) 来了解相关规范的
细节。

 -- 函式: wsgiref.util.guess_scheme (environ)

     返回对于 ‘wsgi.url_scheme’ 应为 "http" 还是 "https" 的猜测，具体方
     式是在 `environ' 中检查 ‘HTTPS’ 环境变量。 返回值是一个字符串。

     此函数适用于创建一个包装了 CGI 或 CGI 类协议例如 FastCGI 的网关。 通
     常，提供这种协议的服务器将包括一个 ‘HTTPS’ 变量并会在通过 SSL 接收
     请求时将其值设为 "1", "yes" 或 "on"。 这样，此函数会在找到上述值时
     返回 "https"，否则返回 "http"。

 -- 函式: wsgiref.util.request_uri (environ, include_query=True)

     使用 PEP 3333(3) 的 "URL Reconstruction" 一节中的算法返回完整的请求
     URL，可能包括查询字符串。 如果 `include_query' 为假值，则结果 URI 中
     将不包括查询字符串。

 -- 函式: wsgiref.util.application_uri (environ)

     类似于 *note request_uri(): 2d37.，区别在于 ‘PATH_INFO’ 和
     ‘QUERY_STRING’ 变量会被忽略。 结果为请求所指定的应用程序对象的基准
     URI。

 -- 函式: wsgiref.util.shift_path_info (environ)

     将单个名称从 ‘PATH_INFO’ 变换为 ‘SCRIPT_NAME’ 并返回该名称。
     `environ' 目录将被原地 `修改'；如果你需要保留原始 ‘PATH_INFO’ 或
     ‘SCRIPT_NAME’ 不变请使用一个副本。

     如果 ‘PATH_INFO’ 中没有剩余的路径节，则返回 ‘None’。

     通常，此例程被用来处理请求 URI 路径的每个部分，比如说将路径当作是一
     系列字典键。 此例程会修改传入的环境以使其适合发起调用位于目标 URI 上
     的其他 WSGI 应用程序，如果有一个 WSGI 应用程序位于 ‘/foo’，而请求
     URI 路径为 ‘/foo/bar/baz’，且位于 ‘/foo’ 的 WSGI 应用程序调用了
     *note shift_path_info(): 2d39.，它将获得字符串 "bar"，而环境将被更
     新以适合传递给位于 ‘/foo/bar’ 的 WSGI 应用程序。 也就是说，
     ‘SCRIPT_NAME’ 将由 ‘/foo’ 变为 ‘/foo/bar’，而 ‘PATH_INFO’ 将由
     ‘/bar/baz’ 变为 ‘/baz’。

     当 ‘PATH_INFO’ 只是 "/" 时，此例程会返回一个空字符串并在
     ‘SCRIPT_NAME’ 末尾添加一个斜杠，虽然空的路径节通常会被忽略，并且
     ‘SCRIPT_NAME’ 通常也不以斜杠作为结束。 此行为是有意为之的，用来确保
     应用程序在使用此例程执行对象遍历时能区分以 ‘/x’ 结束的和以 ‘/x/’ 结
     束的 URI。

 -- 函式: wsgiref.util.setup_testing_defaults (environ)

     以简短的默认值更新 `environ' 用于测试目的。

     此全程会添加 WSGI 所需要的各种参数，包括 ‘HTTP_HOST’,
     ‘SERVER_NAME’, ‘SERVER_PORT’, ‘REQUEST_METHOD’, ‘SCRIPT_NAME’,
     ‘PATH_INFO’ 以及 PEP 3333(4) 中定义的所有 ‘wsgi.*’ 变量。 它只提供
     默认值，而不会替换这些变量的现有设置。

     此例程的目的是让 WSGI 服务器的单元测试以及应用程序设置测试环境更为
     容易。 它不应该被实际的 WSGI 服务器或应用程序所使用，因为它用的是假
     数据！

     用法示例：

          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('', 8000, simple_app) as httpd:
              print("Serving on port 8000...")
              httpd.serve_forever()

除了上述的环境函数，*note wsgiref.util: 139. 模块还提供了以下辅助工具:

 -- 函式: wsgiref.util.is_hop_by_hop (header_name)

     如果 ’header_name’ 是 RFC 2616(5) 所定义的 HTTP/1.1 "Hop-by-Hop" 标
     头则返回 ‘True’。

 -- 類別: wsgiref.util.FileWrapper (filelike, blksize=8192)

     一个将文件类对象转换为 *note iterator: 1171. 的包装器。 结果对象同
     时支持 *note __getitem__(): 3a5. 和 *note __iter__(): 608. 迭代形式
     ，以便兼容 Python 2.1 和 Jython。 当对象被迭代时，可选的 `blksize'
     形参将被反复地传给 `文件类对象' 的 ‘read()’ 方法以获取字节串并输出
     。 当 ‘read()’ 返回空字节串时，迭代将结束并不可再恢复。

     如果 `filelike' 具有 ‘close()’ 方法，返回的对象也将具有 ‘close()’ 方
     法，并且它将在被调用时发起调用 `filelike' 对象的 ‘close()’ 方法。

     用法示例：

          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)

     3.8 版後已棄用: 对 *note 序列协议: 3a5. 的支持已被弃用。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3333

   (2) https://www.python.org/dev/peps/pep-3333

   (3) https://www.python.org/dev/peps/pep-3333

   (4) https://www.python.org/dev/peps/pep-3333

   (5) https://tools.ietf.org/html/rfc2616.html


File: python.info,  Node: wsgiref headers -- WSGI 响应标头工具,  Next: wsgiref simple_server -- 一个简单的 WSGI HTTP 服务器,  Prev: wsgiref util -- WSGI 环境工具,  Up: wsgiref --- WSGI 工具和引用的实现

5.21.4.2 ‘wsgiref.headers’ – WSGI 响应标头工具
..............................................

此模块提供了一个单独的类 *note Headers: 87e.，可以方便地使用一个映射类接
口操作 WSGI 响应标头。

 -- 類別: wsgiref.headers.Headers ([headers])

     创建一个包装了 `headers' 的映射类对象，它必须为如 PEP 3333(1) 所描
     述的由标头名称/值元组构成的列表。 `headers' 的默认值为一个空列表。

     *note Headers: 87e. 对象支持典型的映射操作包括 *note __getitem__():
     3a5, ‘get()’, *note __setitem__(): d2a, ‘setdefault()’, *note
     __delitem__(): d2b. 和 *note __contains__(): dee.。 对于以上各个方
     法，映射的键是标头名称（大小写不敏感），而值是关联到该标头名称的第
     一个值。 设置一个标头会移除该标头的任何现有值，再将一个新值添加到所
     包装的标头列表末尾。 标头的现有顺序通常会保持不变，只在所包装的列表
     末尾添加新的标头。

     与字典不同，当你试图获取或删除所包装的标头列表中不存在的键时 *note
     Headers: 87e. 对象不会引发错误。 获取一个不存在的标头只是返回
     ‘None’，而删除一个不存在的标头则没有任何影响。

     *note Headers: 87e. 对象还支持 ‘keys()’, ‘values()’ 以及 ‘items()’
     方法。 如果存在具有多个值的键则 ‘keys()’ 和 ‘items()’ 所返回的列表
     可能包括多个相同的键。 对 *note Headers: 87e. 对象执行 ‘len()’ 的结
     果与 ‘items()’ 的长度相同，也与所包装的标头列表的长度相同。 实际上
     ，‘items()’ 方法只是返回所包装的标头列表的一个副本。

     在 *note Headers: 87e. 对象上调用 ‘bytes()’ 将返回适用于作为 HTTP 响
     应标头来传输的已格式化字节串。 每个标头附带以逗号加空格分隔的值放置
     在一行中。 每一行都以回车符加换行符结束，且该字节串会以一个空行作为
     结束。

     除了映射接口和格式化特性，*note Headers: 87e. 对象还具有下列方法用
     来查询和添加多值标头，以及添加具有 MIME 参数的标头:

      -- 成員函式: get_all (name)

          返回包含指定标头的所有值的列表。

          返回的列表项将按它们在原始标头列表中的出现或被添加到实例中的顺
          序排序，并可能包含重复项。 任何被删除并重新插入的字段总是会被
          添加到标头列表末尾。 如果给定名称的字段不存在，则返回一个空列
          表。

      -- 成員函式: add_header (name, value, **_params)

          添加一个（可能有多个值）标头，带有通过关键字参数指明的可选的
          MIME 参数。

          `name' 是要添加的标头字段。 可以使用关键字参数来为标头字段设置
          MIME 参数。 每个参数必须为字符串或 ‘None’。 参数名中的下划线会
          被转换为连字符，因为连字符不可在 Python 标识符中出现，但许多
          MIME 参数名都包括连字符。 如果参数值为字符串，它会以
          ‘name="value"’ 的形式被添加到标头值参数中。 如果为 ‘None’，则
          只会添加参数名。 （这适用于没有值的 MIME 参数。） 示例用法:

               h.add_header('content-disposition', 'attachment', filename='bud.gif')

          以上代码将添加一个这样的标头:

               Content-Disposition: attachment; filename="bud.gif"

     3.5 版更變: `headers' 形参是可选的。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3333


File: python.info,  Node: wsgiref simple_server -- 一个简单的 WSGI HTTP 服务器,  Next: wsgiref validate --- WSGI 一致性检查器,  Prev: wsgiref headers -- WSGI 响应标头工具,  Up: wsgiref --- WSGI 工具和引用的实现

5.21.4.3 ‘wsgiref.simple_server’ – 一个简单的 WSGI HTTP 服务器
..............................................................

此模块实现了一个简单的 HTTP 服务器 (基于 *note http.server: 96.) 来发布
WSGI 应用程序。 每个服务器实例会在给定的主机名和端口号上发布一个 WSGI 应
用程序。 如果你想在一个主机名和端口号上发布多个应用程序，你应当创建一个
通过解析 ‘PATH_INFO’ 来选择每个请求要发起调用哪个应用程序的 WSGI 应用程
序。 (例如，使用 *note wsgiref.util: 139. 中的 ‘shift_path_info()’ 函数
。)

 -- 函式: wsgiref.simple_server.make_server (host, port, app,
          server_class=WSGIServer, handler_class=WSGIRequestHandler)

     创建一个新的 WSGI 服务器并在 `host' 和 `port' 上进行监听，接受对
     `app' 的连接。 返回值是所提供的 `server_class' 的实例，并将使用指定
     的 `handler_class' 来处理请求。 `app' 必须是一个如 PEP 3333(1) 所定
     义的 WSGI 应用程序对象。

     用法示例：

          from wsgiref.simple_server import make_server, demo_app

          with make_server('', 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()

 -- 函式: wsgiref.simple_server.demo_app (environ, start_response)

     此函数是一个小巧但完整的 WSGI 应用程序，它返回一个包含消息 "Hello
     world!" 以及 `environ' 形参中提供的键/值对的文本页面。 它适用于验证
     WSGI 服务器 (例如 *note wsgiref.simple_server: 138.) 是否能够正确地
     运行一个简单的 WSGI 应用程序。

 -- 類別: wsgiref.simple_server.WSGIServer (server_address,
          RequestHandlerClass)

     创建一个 *note WSGIServer: 2d42. 实例。 `server_address' 应当是一个
     ‘(host,port)’ 元组，而 `RequestHandlerClass' 应当是 *note
     http.server.BaseHTTPRequestHandler: aec. 的子类，它将被用来处理请求
     。

     你通常不需要调用此构造器，因为 *note make_server(): 2d40. 函数能为
     你处理所有的细节。

     *note WSGIServer: 2d42. 是 *note http.server.HTTPServer: 2d43. 的子
     类，因此它所有的方法 (例如 ‘serve_forever()’ 和 ‘handle_request()’)
     都是可用的。 *note WSGIServer: 2d42. 还提供了以下 WSGI 专属的方法:

      -- 成員函式: set_app (application)

          将可调用对象 `application' 设为将要接受请求的 WSGI 应用程序。

      -- 成員函式: get_app ()

          返回当前设置的应用程序可调用对象。

     但是，你通常不需要使用这些附加的方法，因为 *note set_app(): 2d44. 通
     常会由 *note make_server(): 2d40. 来调用，而 *note get_app(): 2d45.
     主要是针对请求处理句柄实例的。

 -- 類別: wsgiref.simple_server.WSGIRequestHandler (request,
          client_address, server)

     为给定的 `request' 创建一个 HTTP 处理句柄 (例如套接字)，
     `client_address' (一个 ‘(host,port)’ 元组)，以及 `server' (*note
     WSGIServer: 2d42. 实例)。

     你不需要直接创建该类的实例；它们会根据 *note WSGIServer: 2d42. 对象
     的需要自动创建。 但是，你可以子类化该类并将其作为 `handler_class' 提
     供给 *note make_server(): 2d40. 函数。 一些可能在子类中重载的相关方
     法:

      -- 成員函式: get_environ ()

          返回包含针对一个请求的 WSGI 环境的字典。 默认实现会拷贝 *note
          WSGIServer: 2d42. 对象的 ‘base_environ’ 字典属性的内容并添加从
          HTTP 请求获取的各种标头。 对此方法的每个调用应当返回一个 PEP
          3333(2) 所指明的包含所有相关 CGI 环境变量的新字典。

      -- 成員函式: get_stderr ()

          返回应被用作 ‘wsgi.errors’ 流的对象。 默认实现将只返回
          ‘sys.stderr’。

      -- 成員函式: handle ()

          处理 HTTP 请求。 默认的实现会使用 *note wsgiref.handlers: 136.
          类创建一个处理句柄实例来实现实际的 WSGI 应用程序接口。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3333

   (2) https://www.python.org/dev/peps/pep-3333


File: python.info,  Node: wsgiref validate --- WSGI 一致性检查器,  Next: wsgiref handlers -- 服务器/网关基类,  Prev: wsgiref simple_server -- 一个简单的 WSGI HTTP 服务器,  Up: wsgiref --- WSGI 工具和引用的实现

5.21.4.4 ‘wsgiref.validate’ — WSGI 一致性检查器
...............................................

当创建新的 WSGI 应用程序对象、框架、服务器或中间件时，使用 *note
wsgiref.validate: 13a. 来验证新代码的一致性是很有用的。 此模块提供了一个
创建 WSGI 应用程序对象的函数来验证 WSGI 服务器或网关与 WSGI 应用程序对象
之间的通信，以便检查双方的协议一致性。

请注意这个工具并不保证完全符合 PEP 3333(1)；此模块没有报告错误并不一定表
示不存在错误。 但是，如果此模块确实报告了错误，那么几乎可以肯定服务器或
应用程序不是 100% 符合要求的。

此模块是基于 Ian Bicking 的 "Python Paste" 库的 ‘paste.lint’ 模块。

 -- 函式: wsgiref.validate.validator (application)

     包装 `application' 并返回一个新的 WSGI 应用程序对象。 返回的应用程
     序将转发所有请求到原始的 `application'，并将检查 `application' 和发
     起调用它的服务器是否都符合 WSGI 规范和 RFC 2616(2)。

     任何被检测到的不一致性都会导致引发 *note AssertionError: 240.；但是
     请注意，如何对待这些错误取决于具体服务器。 例如，*note
     wsgiref.simple_server: 138. 和其他基于 *note wsgiref.handlers: 136.
     的服务器（它们没有重载错误处理方法来做其他操作）将简单地输出一条消
     息报告发生了错误，并将回溯转给 ‘sys.stderr’ 或者其他错误数据流。

     这个包装器也可能会使用 *note warnings: 12f. 模块生成输出来指明存在
     问题但实际上未被 PEP 3333(3) 所禁止的行为。 除非它们被 Python 命令
     行选项或 *note warnings: 12f. API 所屏蔽，否则任何此类警告都将被写
     入到 ‘sys.stderr’ (`不是' ‘wsgi.errors’，除非它们恰好是同一个对象
     )。

     用法示例：

          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('', 8000, validator_app) as httpd:
              print("Listening on port 8000....")
              httpd.serve_forever()

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3333

   (2) https://tools.ietf.org/html/rfc2616.html

   (3) https://www.python.org/dev/peps/pep-3333


File: python.info,  Node: wsgiref handlers -- 服务器/网关基类,  Next: 示例<32>,  Prev: wsgiref validate --- WSGI 一致性检查器,  Up: wsgiref --- WSGI 工具和引用的实现

5.21.4.5 ‘wsgiref.handlers’ – 服务器/网关基类
.............................................

此模块提供了用于实现 WSGI 服务器和网关的处理句柄基类。 这些基类可处理大
部分与 WSGI 应用程序通信的工作，只要给予它们一个带有输入、输出和错误流的
CGI 类环境。

 -- 類別: wsgiref.handlers.CGIHandler

     通过 ‘sys.stdin’, ‘sys.stdout’, ‘sys.stderr’ 和 ‘os.environ’ 发起基
     于 CGI 的调用。 这在当你有一个 WSGI 应用程序并想将其作为 CGI 脚本运
     行时很有用处。 只需发起调用 ‘CGIHandler().run(app)’，其中 ‘app’ 是
     你想要发起调用的 WSGI 应用程序。

     该类是 *note BaseCGIHandler: 2d4e. 的子类，它将设置 ‘wsgi.run_once’
     为真值，‘wsgi.multithread’ 为假值，‘wsgi.multiprocess’ 为真值，并总
     是使用 *note sys: fd. 和 *note os: c4. 来获取所需的 CGI 流和环境。

 -- 類別: wsgiref.handlers.IISCGIHandler

     *note CGIHandler: 2d4d. 的一个专门化替代，用于在 Microsoft 的 IIS
     Web 服务器上部署，无需设置 config allowPathInfo 选项 (IIS>=7) 或
     metabase allowPathInfoForScriptMappings (IIS<7)。

     默认情况下，IIS 给出的 ‘PATH_INFO’ 会与前面的 ‘SCRIPT_NAME’ 重复，
     导致想要实现路由的 WSGI 应用程序出现问题。 这个处理句柄会去除任何这
     样的重复路径。

     IIS 可被配置为传递正确的 ‘PATH_INFO’，但这会导致另一个
     ‘PATH_TRANSLATED’ 出错的问题。 幸运的是这个变量很少被使用并且不被
     WSGI 所保证。 但是在 IIS<7 上，这个设置只能在 vhost 层级上进行，影
     响到所有其他脚本映射，其中许多在受 ‘PATH_TRANSLATED’ 问题影响时都会
     中断运行。 因此 IIS<7 的部署几乎从不附带这样的修正（即使 IIS7 也很
     少使用它，因为它仍然不带 UI）。

     CGI 代码没有办法确定该选项是否已设置，因此提供了一个单独的处理句柄
     类。 它的用法与 *note CGIHandler: 2d4d. 相同，即通过调用
     ‘IISCGIHandler().run(app)’，其中 ‘app’ 是你想要发起调用的 WSGI 应用
     程序。

     3.2 版新加入.

 -- 類別: wsgiref.handlers.BaseCGIHandler (stdin, stdout, stderr,
          environ, multithread=True, multiprocess=False)

     类似于 *note CGIHandler: 2d4d.，但是改用 *note sys: fd. 和 *note
     os: c4. 模块，CGI 环境和 I/O 流会被显式地指定。 `multithread' 和
     `multiprocess' 值被用来为处理句柄实例所运行的任何应用程序设置
     ‘wsgi.multithread’ 和 ‘wsgi.multiprocess’ 旗标。

     该类是 *note SimpleHandler: 2d50. 的子类，旨在用于 HTTP "origin
     servers" 以外的软件。 如果你在编写一个网关协议实现（例如 CGI,
     FastCGI, SCGI 等等），它使用 ‘Status:’ 标头来发布 HTTP 状态，你可能
     会想要子类化该类而不是 *note SimpleHandler: 2d50.。

 -- 類別: wsgiref.handlers.SimpleHandler (stdin, stdout, stderr,
          environ, multithread=True, multiprocess=False)

     类似于 *note BaseCGIHandler: 2d4e.，但被设计用于 HTTP 原始服务器。
     如果你在编写一个 HTTP 服务器实现，你可能会想要子类化该类而不是
     *note BaseCGIHandler: 2d4e.。

     该类是 *note BaseHandler: 1107. 的子类。 它重载了 *note __init__():
     e23, ‘get_stdin()’, ‘get_stderr()’, ‘add_cgi_vars()’, ‘_write()’ 和
     ‘_flush()’ 方法以支持通过构造器显式地设置环境和流。 所提供的环境和
     流存储在 ‘stdin’, ‘stdout’, ‘stderr’ 和 ‘environ’ 属性中。

     `stdout' 的 *note write(): 680. 方法应该完整写入每个数据块，与
     *note io.BufferedIOBase: 67f. 一样。

 -- 類別: wsgiref.handlers.BaseHandler

     这是适用于运行 WSGI 应用程序的抽象基类。 每个实例将处理一个单独的
     HTTP 请求，不过在原则上你也可以创建一个可针对多个请求重用的子类。

     *note BaseHandler: 1107. 实例只有一个方法提供给外部使用:

      -- 成員函式: run (app)

          运行指定的 WSGI 应用程序 `app'。

     所有的 *note BaseHandler: 1107. 其他方法都是在运行应用程序过程中由
     该方法发起调用的，因此主要是为了允许定制运行过程。

     以下方法必须在子类中被重载:

      -- 成員函式: _write (data)

          缓冲字节数据 `data' 以便传输给客户端。 如果此方法真的传输了数
          据也是可以的；*note BaseHandler: 1107. 只有在底层系统真有这样
          的区分时才会区分写入和刷新操作以提高效率。

      -- 成員函式: _flush ()

          强制将缓冲的数据传输给客户端。 如果此方法无任何操作也是可以的
          （例如，*note _write(): 2d52. 实际上已发送了数据）。

      -- 成員函式: get_stdin ()

          返回一个适合被用作当前被处理的请求的 ‘wsgi.input’ 的输入流对象
          。

      -- 成員函式: get_stderr ()

          返回一个适合被用作当前所处理请求的 ‘wsgi.errors’ 的输出流对象
          。

      -- 成員函式: add_cgi_vars ()

          将当前请求的 CGI 变量插入到 ‘environ’ 属性。

     以下是一些你可能会想要重载的其他方法。 但这只是个简略的列表，它不包
     括每个可被重载的方法。 你应当在在尝试创建自定义的 *note
     BaseHandler: 1107. 子类之前参阅文档字符串和源代码来了解更多信息。

     用于自定义 WSGI 环境的属性和方法:

      -- 屬性: wsgi_multithread

          用于 ‘wsgi.multithread’ 环境变量的值。 它在 *note BaseHandler:
          1107. 中默认为真值，但在其他子类中可能有不同的默认值（或是由构
          造器来设置）。

      -- 屬性: wsgi_multiprocess

          用于 ‘wsgi.multiprocess’ 环境变量的值。 它在 *note
          BaseHandler: 1107. 中默认为真值，但在其他子类中可能有不同的默
          认值（或是由构造器来设置）。

      -- 屬性: wsgi_run_once

          用于 ‘wsgi.run_once’ 环境变量的值。 它在 *note BaseHandler:
          1107. 中默认为假值，但在 *note CGIHandler: 2d4d. 中默认为真值
          。

      -- 屬性: os_environ

          要包括在每个请求的 WSGI 环境中的默认环境变量。 在默认情况下，
          这是当 *note wsgiref.handlers: 136. 被导入时的 ‘os.environ’ 的
          一个副本，但也可以在类或实例层级上创建它们自己的子类。 请注意
          该字典应当被当作是只读的，因为默认值会在多个类和实际之间共享。

      -- 屬性: server_software

          如果设置了 *note origin_server: 2d5c. 属性，该属性的值会被用来
          设置默认的 ‘SERVER_SOFTWARE’ WSGI 环境变量，并且还会被用来设置
          HTTP 响应中默认的 ‘Server:’ 标头。 它会被不是 It is ignored
          for handlers (such as *note BaseCGIHandler: 2d4e. and *note
          CGIHandler: 2d4d.) that are not HTTP origin servers.

          3.3 版更變: 名称 "Python" 会被替换为实现专属的名称如
          "CPython", "Jython" 等等。

      -- 成員函式: get_scheme ()

          返回当前请求所使用的 URL 方案。 默认的实现会使用来自 *note
          wsgiref.util: 139. 的 ‘guess_scheme()’ 函数根据当前请求的
          ‘environ’ 变量来猜测方案应该是 "http" 还是 "https"。

      -- 成員函式: setup_environ ()

          将 ‘environ’ 属性设为填充了完整内容的 WSGI 环境。 默认的实现会
          使用上述的所有方法和属性，加上 *note get_stdin(): 2d54, *note
          get_stderr(): 2d55. 和 *note add_cgi_vars(): 2d56. 方法以及
          *note wsgi_file_wrapper: 2d5f. 属性。 它还会插入一个
          ‘SERVER_SOFTWARE’ 键，如果该键还不存在的话，只要 *note
          origin_server: 2d5c. 属性为真值并且设置了 *note
          server_software: 2d5b. 属性。

     用于自定义异常处理的方法和属性:

      -- 成員函式: log_exception (exc_info)

          将 `exc_info' 元素记录到服务器日志。 `exc_info' 是一个 ‘(type,
          value, traceback)’ 元组。 默认的实现会简单地将回溯信息写入请求
          的 ‘wsgi.errors’ 流并刷新它。 子类可以重载此方法来修改格式或重
          设输出目标，通过邮件将回溯信息发给管理员，或执行任何其他符合要
          求的动作。

      -- 屬性: traceback_limit

          要包括在默认 *note log_exception(): 2d60. 方法的回溯信息输出中
          的最大帧数。 如果为 ‘None’，则会包括所有的帧。

      -- 成員函式: error_output (environ, start_response)

          此方法是一个为用户生成错误页面的 WSGI 应用程序。 它仅当将标头
          发送给客户端之前发生错误时会被发起调用。

          此方法可使用 ‘sys.exc_info()’ 来访问当前错误信息，并应当在调用
          `start_response' 时将该信息传递给它（如 PEP 3333(1) 的 "Error
          Handling" 部分所描述的）。

          默认的实现只是使用 *note error_status: 2d63, *note
          error_headers: 2d64, 和 *note error_body: 2d65. 属性来生成一个
          输出页面。 子类可以重载此方法来产生更动态化的错误输出。

          但是请注意，从安全角度看来是不建议将诊断信息暴露给任何用户的；
          理想的做法是你应当通过特别处理来启用诊断输出，因此默认的实现并
          不包括这样的内容。

      -- 屬性: error_status

          用于错误响应的 HTTP 状态。 这应当是一个在 PEP 3333(2) 中定义的
          字符串；它默认为代码 500 以相应的消息。

      -- 屬性: error_headers

          用于错误响应的 HTTP 标头。 这应当是由 WSGI 响应标头 (‘(name,
          value)’ 元组) 构成的列表，如 PEP 3333(3) 所定义的。 默认的列表
          只是将内容类型设为 ‘text/plain’。

      -- 屬性: error_body

          错误响应体。 这应当是一个 HTTP 响应体字节串。 它默认为纯文本
          "A server error occurred.  Please contact the administrator."

     用于 PEP 3333(4) 的 "可选的平台专属文件处理" 特性的方法和属性:

      -- 屬性: wsgi_file_wrapper

          一个 ‘wsgi.file_wrapper’ 工厂对象，或为 ‘None’。 该属性的默认
          值是 *note wsgiref.util.FileWrapper: 3a3. 类。

      -- 成員函式: sendfile ()

          重载以实现平台专属的文件传输。 此方法仅在应用程序的返回值是由
          *note wsgi_file_wrapper: 2d5f. 属性指定的类的实例时会被调用。
          如果它能够成功地传输文件则应当返回真值，以使得默认的传输代码将
          不会被执行。 此方法的默认实现只会返回假值。

     杂项方法和属性:

      -- 屬性: origin_server

          该属性在处理句柄的 *note _write(): 2d52. 和 *note _flush():
          2d53. 被用于同客户端直接通信而不是通过需要 HTTP 状态为某种特殊
          ‘Status:’ 标头的 CGI 类网关协议时应当被设为真值

          该属性在 *note BaseHandler: 1107. 中默认为真值，但在 *note
          BaseCGIHandler: 2d4e. 和 *note CGIHandler: 2d4d. 中则为假值。

      -- 屬性: http_version

          如果 *note origin_server: 2d5c. 为真值，则该字符串属性会被用来
          设置给客户端的响应的 HTTP 版本。 它的默认值为 ‘"1.0"’。

 -- 函式: wsgiref.handlers.read_environ ()

     将来自 ‘os.environ’ 的 CGI 变量转码为 PEP 3333(5) "bytes in
     unicode" 字符串，返回一个新的字典。 此函数被 *note CGIHandler:
     2d4d. 和 *note IISCGIHandler: 2d4f. 用来替代直接使用 ‘os.environ’，
     后者不一定在所有使用 Python 3 的平台和 Web 服务器上都符合 WSGI 标准
     – 特别是当 OS 的实际环境为 Unicode 时 (例如 Windows)，或者当环境为
     字节数据，但被 Python 用来解码它的系统编码格式不是 ISO-8859-1 时 (例
     如使用 UTF-8 的 Unix 系统)。

     如果你要实现自己的基于 CGI 的处理句柄，你可能会想要使用此例程而不是
     简单地从 ‘os.environ’ 直接拷贝值。

     3.2 版新加入.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3333

   (2) https://www.python.org/dev/peps/pep-3333

   (3) https://www.python.org/dev/peps/pep-3333

   (4) https://www.python.org/dev/peps/pep-3333

   (5) https://www.python.org/dev/peps/pep-3333


File: python.info,  Node: 示例<32>,  Prev: wsgiref handlers -- 服务器/网关基类,  Up: wsgiref --- WSGI 工具和引用的实现

5.21.4.6 示例
.............

这是一个可运行的 "Hello World" WSGI 应用程序:

     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('', 8000, hello_world_app) as httpd:
         print("Serving on port 8000...")

         # Serve until process is killed
         httpd.serve_forever()

一个发布当前目录的 WSGI 应用程序示例，接受通过命令行指定可选的目录和端口
号 (默认值: 8000):

     #!/usr/bin/env python3
     '''
     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.
     '''
     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('', 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()


File: python.info,  Node: urllib --- URL 处理模块,  Next: urllib request --- 用于打开 URL 的可扩展库,  Prev: wsgiref --- WSGI 工具和引用的实现,  Up: 互联网协议和支持

5.21.5 ‘urllib’ — URL 处理模块
------------------------------

`源代码:' Lib/urllib/(1)

__________________________________________________________________

‘urllib’ 是一个收集了多个涉及 URL 的模块的包：

   * *note urllib.request: 129. 打开和读取 URL

   * *note urllib.error: 127. 包含 *note urllib.request: 129. 抛出的异常

   * *note urllib.parse: 128. 用于解析 URL

   * *note urllib.robotparser: 12b. 用于解析 ‘robots.txt’ 文件

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/urllib/


File: python.info,  Node: urllib request --- 用于打开 URL 的可扩展库,  Next: urllib response --- urllib 使用的 Response 类,  Prev: urllib --- URL 处理模块,  Up: 互联网协议和支持

5.21.6 ‘urllib.request’ — 用于打开 URL 的可扩展库
-------------------------------------------------

`源码：' Lib/urllib/request.py(1)

__________________________________________________________________

*note urllib.request: 129. 模块定义了适用于在各种复杂情况下打开 URL（主
要为 HTTP）的函数和类 — 例如基本认证、摘要认证、重定向、cookies 及其它。

也參考
......

对于更高级别的 HTTP 客户端接口，建议使用 Requests(2) 。

*note urllib.request: 129. 模块定义了以下函数：

 -- 函式: urllib.request.urlopen (url, data=None[, timeout], *,
          cafile=None, capath=None, cadefault=False, context=None)

     打开统一资源定位符 `url'，可以是一个字符串或一个 *note Request:
     9dc. 对象。

     `data' 必须是一个对象，用于给出要发送到服务器的附加数据，若不需要发
     送数据则为 ‘None’。详情请参阅 *note Request: 9dc. 。

     urllib.request 模块采用 HTTP/1.1 协议，并且在其 HTTP 请求中包含
     ‘Connection:close’ 头部信息。

     `timeout' 为可选参数，用于指定阻塞操作（如连接尝试）的超时时间，单
     位为秒。如未指定，将使用全局默认超时参数）。本参数实际仅对 HTTP、
     HTTPS 和 FTP 连接有效。

     如果给定了 `context' 参数，则必须是一个 *note ssl.SSLContext: 4e9.
     实例，用于描述各种 SSL 参数。更多详情请参阅 *note HTTPSConnection:
     499. 。

     `cafile' 和 `capath' 为可选参数，用于为 HTTPS 请求指定一组受信 CA 证
     书。`cafile' 应指向包含CA 证书的单个文件， `capath' 则应指向哈希证
     书文件的目录。更多信息可参阅 *note
     ssl.SSLContext.load_verify_locations(): 8d8. 。

     参数 `cadefault' 将被忽略。

     本函数总会返回一个对象，该对象可作为 *note context manager: 661. 使
     用，带有 `url'、`headers' 和 `status' 属性。有关这些属性的更多详细
     信息，请参阅 *note urllib.response.addinfourl: 2d6d. 。

     对于 HTTP 和 HTTPS 的 URL 而言，本函数将返回一个稍经修改的 *note
     http.client.HTTPResponse: aef. 对象。除了上述 3 个新的方法之外，还
     有 msg 属性包含了与 *note reason: 2d6e. 属性相同的信息—服务器返回的
     原因描述文字，而不是 *note HTTPResponse: aef. 的文档所述的响应头部
     信息。

     对于 FTP、文件、数据的URL，以及由传统的 *note URLopener: 2d6f.  和
     *note FancyURLopener: 2d70. 类处理的请求，本函数将返回一个 *note
     urllib.response.addinfourl: 2d6d. 对象。

     协议发生错误时，将会引发 *note URLError: 2d71. 。

     请注意，如果没有处理函数对请求进行处理，则有可能会返回 ‘None’ 。尽
     管默认安装的全局 *note OpenerDirector: 2d72. 会用 *note
     UnknownHandler: 2d73. 来确保不会发生这种情况。

     此外，如果检测到设置了代理（比如设置了 ‘http_proxy’ 之类的环境变量
     ），默认会安装 *note ProxyHandler: 10d8. 并确保通过代理处理请求。

     Python 2.6 以下版本中留存的 ‘urllib.urlopen’ 函数已停止使用了；
     *note urllib.request.urlopen(): 87b. 对应于传统的 ‘urllib2.urlopen’
     。对代理服务的处理是通过将字典参数传给 ‘urllib.urlopen’ 来完成的，
     可以用 *note ProxyHandler: 10d8. 对象获取到代理处理函数。

     默认会触发一条 *note 审计事件: fa1. ‘urllib.Request’ ，参数
     ‘fullurl’ 、 ‘data’ 、‘headers’ 、‘method’ 均取自请求对象。

     3.2 版更變: 增加了 `cafile' 与 `capath'。

     3.2 版更變: 只要条件允许（指 *note ssl.HAS_SNI: 2827. 为真），现在
     能够支持 HTTPS 虚拟主机。

     3.2 版新加入: `data' 可以是一个可迭代对象。

     3.3 版更變: 增加了 `cadefault'。

     3.4.3 版更變: 增加了 `context'。

     3.6 版後已棄用: `cafile' 、 `capath' 和 `cadefault' 已废弃，转而推
     荐使用 `context'。请改用 *note ssl.SSLContext.load_cert_chain():
     b69. 或让 *note ssl.create_default_context(): 9a7. 选取系统信任的
     CA 证书。

 -- 函式: urllib.request.install_opener (opener)

     安装一个 *note OpenerDirector: 2d72. 实例，作为默认的全局打开函数。
     仅当 urlopen 用到该打开函数时才需要安装；否则，只需调用 *note
     OpenerDirector.open(): 9e0. 而不是 *note urlopen(): 87b.。代码不会
     检查是否真的属于 *note OpenerDirector: 2d72. 类，所有具备适当接口的
     类都能适用。

 -- 函式: urllib.request.build_opener ([handler, ...])

     返回一个 *note OpenerDirector: 2d72. 实例，以给定顺序把处理函数串联
     起来。处理函数可以是 *note BaseHandler: 2d76. 的实例，也可以是
     *note BaseHandler: 2d76. 的子类（这时构造函数必须允许不带任何参数的
     调用）。以下类的实例将位于 `处理函数' 之前，除非 `处理函数' 已包含
     这些类、其实例或其子类： *note ProxyHandler: 10d8. （如果检测到代理
     设置）、*note UnknownHandler: 2d73. 、*note HTTPHandler: 2d77. 、
     *note HTTPDefaultErrorHandler: 2d78. 、*note HTTPRedirectHandler:
     2d79. 、 *note FTPHandler: 2d7a. 、 *note FileHandler: 2d7b. 、
     *note HTTPErrorProcessor: 2d7c. 。

     若 Python 安装时已带了 SSL 支持（指可以导入 *note ssl: f3. 模块），
     则还会加入 *note HTTPSHandler: c78. 。

     A *note BaseHandler: 2d76. subclass may also change its
     ‘handler_order’ attribute to modify its position in the handlers
     list.

 -- 函式: urllib.request.pathname2url (path)

     将路径名 `path' 从路径本地写法转换为 URL 路径部分所采用的格式。本函
     数不会生成完整的 URL。返回值将会用 *note quote(): 511. 函数加以编码
     。

 -- 函式: urllib.request.url2pathname (path)

     从百分号编码的 URL 中将 `path' 部分转换为本地路径的写法。本函数不接
     受完整的 URL，并利用 *note unquote(): 10db. 函数对 `path' 进行解码
     。

 -- 函式: urllib.request.getproxies ()

     This helper function returns a dictionary of scheme to proxy server
     URL mappings.  It scans the environment for variables named
     ‘<scheme>_proxy’, in a case insensitive approach, for all operating
     systems first, and when it cannot find it, looks for proxy
     information from System Configuration for macOS and Windows Systems
     Registry for Windows.  If both lowercase and uppercase environment
     variables exist (and disagree), lowercase is preferred.

          備註: 如果存在环境变量 ‘REQUEST_METHOD’ ，通常表示脚本运行于
          CGI 环境中，则环境变量 ‘HTTP_PROXY’ （大写的 ‘_PROXY’）将会被
          忽略。这是因其可以由客户端用 HTTP 头部信息 “Proxy:”注入。若要
          在 CGI 环境中使用 HTTP 代理，请显式使用 ‘`ProxyHandler’ ，或确
          保变量名称为小写（或至少是 ‘_proxy’ 后缀）。

提供了以下类：

 -- 類別: urllib.request.Request (url, data=None, headers={},
          origin_req_host=None, unverifiable=False, method=None)

     URL 请求对象的抽象类。

     `url' 应为包含合法 URL 的字符串。

     `data' 必须是一个对象，用于给定发往服务器的附加数据，若无需此类数据
     则为 ‘None’ 。 目前 唯一用到 `data' 的只有 HTTP 请求。支持的对象类
     型包括字节串、类文件对象和可遍历的类字节串对象。如果没有提供
     ‘Content-Length’ 和 ‘Transfer-Encoding’ 头部字段， *note
     HTTPHandler: 2d77. 会根据 `data' 的类型设置这些头部字段。
     ‘Content-Length’ 将用于发送字节对象，而 RFC 7230(3) 第 3.3.1 节中定
     义的 ‘Transfer-Encoding: chunked’ 将用于发送文件和其他可遍历对象。

     对于 HTTP POST 请求方法而言，`data' 应该是标准
     ‘application/x-www-form-urlencoded’ 格式的缓冲区。 *note
     urllib.parse.urlencode(): 87a. 函数的参数为映射对象或二元组序列，并
     返回一个该编码格式的 ASCII 字符串。在用作 `data' 参数之前，应将其编
     码为字节串。

     `headers' 应为字典对象，视同于用每个键和值作为参数去调用 *note
     add_header(): 2d80. 。通常用于 ‘User-Agent’ 头部数据的“伪装” ，浏览
     器用这些头部数据标识自己——某些 HTTP 服务器只允许来自普通浏览器的请
     求，而不接受来自脚本的请求。例如，Mozilla Firefox 可能将自己标识为
     ‘"Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127
     Firefox/2.0.0.11"’ ，而 *note urllib: 126. 的默认 user agent 字符串
     则是 ‘"Python-urllib/2.6"’ （在 Python 2.6 上）。

     如果给出了 `data' 参数，则应当包含合适的 ‘Content-Type’ 头部信息。
     若未提供且 `data' 不是 None，则会把 ‘Content-Type:
     application/x-www-form-urlencoded’ 加入作为默认值。

     接下来的两个参数，只对第三方 HTTP cookie 的处理才有用：

     `origin_req_host' 应为发起初始会话的请求主机，定义参见 RFC 2965(4)
     。默认指为‘‘http.cookiejar.request_host(self)‘‘ 。这是用户发起初始
     请求的主机名或 IP 地址。假设请求是针对 HTML 文档中的图片数据发起的
     ，则本属性应为对包含图像的页面发起请求的主机。

     `unverifiable' 应该标示出请求是否无法验证，定义参见 RFC 2965(5) 。
     默认值为 ‘False’ 。所谓无法验证的请求，是指用户没有机会对请求的 URL
     做验证。例如，如果请求是针对 HTML 文档中的图像，用户没有机会去许可
     能自动读取图像，则本参数应为 True。

     `method' 应为字符串，标示要采用的 HTTP 请求方法（例如 ‘'HEAD'’ ）。
     如果给出本参数，其值会存储在 *note method: 9dd. 属性中，并由 *note
     get_method(): b99. 使用。如果 `data' 为‘‘None‘‘ 则默认值为 ‘'GET'’
     ，否则为 ‘'POST'’。子类可以设置 *note method: 9dd. 属性来标示不同的
     默认请求方法。

          備註: 如果 data 对象无法分多次传递其内容（比如文件或只能生成一
          次内容的可迭代对象）并且由于 HTTP 重定向或身份验证而发生请求重
          试行为，则该请求不会正常工作。 `data' 是紧挨着头部信息发送给
          HTTP 服务器的。现有库不支持 HTTP 100-continue 的征询。

     3.3 版更變: Request 类增加了 *note Request.method: 9dd. 参数。

     3.4 版更變: 默认 *note Request.method: 9dd. 可以在类中标明。

     3.6 版更變: 如果给出了 ‘Content-Length’ ，且 `data' 既不为 ‘None’ 也
     不是字节串对象，则不会触发错误。而会退而求其次采用分块传输的编码格
     式。

 -- 類別: urllib.request.OpenerDirector

     *note OpenerDirector: 2d72. 类通过串接在一起的 *note BaseHandler:
     2d76. 打开 URL，并负责管理 handler 链及从错误中恢复。

 -- 類別: urllib.request.BaseHandler

     这是所有已注册 handler 的基类，只做了简单的注册机制。

 -- 類別: urllib.request.HTTPDefaultErrorHandler

     为 HTTP 错误响应定义的默认 handler，所有出错响应都会转为 *note
     HTTPError: 9e2. 异常。

 -- 類別: urllib.request.HTTPRedirectHandler

     一个用于处理重定向的类。

 -- 類別: urllib.request.HTTPCookieProcessor (cookiejar=None)

     一个用于处理 HTTP Cookies 的类。

 -- 類別: urllib.request.ProxyHandler (proxies=None)

     Cause requests to go through a proxy.  If `proxies' is given, it
     must be a dictionary mapping protocol names to URLs of proxies.
     The default is to read the list of proxies from the environment
     variables ‘<protocol>_proxy’.  If no proxy environment variables
     are set, then in a Windows environment proxy settings are obtained
     from the registry’s Internet Settings section, and in a macOS
     environment proxy information is retrieved from the System
     Configuration Framework.

     若要禁用自动检测出来的代理，请传入空的字典对象。

     环境变量 ‘no_proxy’ 可用于指定不必通过代理访问的主机；应为逗号分隔
     的主机名后缀列表，可加上 ‘:port’ ，例如
     ‘cern.ch,ncsa.uiuc.edu,some.host:8080’ 。

               備註: 如果设置了 ‘REQUEST_METHOD’ 变量，则会忽略
               ‘HTTP_PROXY’ ；参阅 *note getproxies(): 2d7f. 文档。

 -- 類別: urllib.request.HTTPPasswordMgr

     维护 ‘(realm, uri) -> (user, password)’ 映射数据库。

 -- 類別: urllib.request.HTTPPasswordMgrWithDefaultRealm

     维护 ‘(realm, uri) -> (user, password)’ 映射数据库。realm 为 ‘None’
     视作全匹配，若没有其他合适的安全区域就会检索它。

 -- 類別: urllib.request.HTTPPasswordMgrWithPriorAuth

     *note HTTPPasswordMgrWithDefaultRealm: 2d83. 的一个变体，也带有
     ‘uri -> is_authenticated’ 映射数据库。可被 BasicAuth 处理函数用于确
     定立即发送身份认证凭据的时机，而不是先等待 ‘401’ 响应。

     3.5 版新加入.

 -- 類別: urllib.request.AbstractBasicAuthHandler (password_mgr=None)

     这是一个帮助完成 HTTP 身份认证的混合类，对远程主机和代理都适用。参
     数 `password_mgr' 应与 *note HTTPPasswordMgr: 2d82. 兼容；关于必须
     支持哪些接口，请参阅 *note HTTPPasswordMgr 对象: 2d84. 对象的章节。
     如果 `password_mgr' 还提供 ‘is_authenticated’ 和
     ‘update_authenticated’ 方法（请参阅 *note
     HTTPPasswordMgrWithPriorAuth 对象: 2d85. 对象），则 handler 将对给
     定 URI 用到 ‘is_authenticated’ 的结果，来确定是否随请求发送身份认证
     凭据。如果该 URI 的 ‘is_authenticated’ 返回 ‘True’，则发送凭据。如
     果 ‘is_authenticated’ 为 ‘False’ ，则不发送凭据，然后若收到 ‘401’ 响
     应，则使用身份认证凭据重新发送请求。如果身份认证成功，则调用
     ‘update_authenticated’ 设置该 URI 的 ‘is_authenticated’ 为 ‘True’，
     这样后续对该 URI 或其所有父 URI 的请求将自动包含该身份认证凭据。

     3.5 版新加入: 增加了对 ‘is_authenticated’ 的支持。

 -- 類別: urllib.request.HTTPBasicAuthHandler (password_mgr=None)

     处理远程主机的身份认证。 `password_mgr' 应与 *note HTTPPasswordMgr:
     2d82. 兼容；有关哪些接口是必须支持的，请参阅 *note HTTPPasswordMgr
     对象: 2d84. 章节。如果给出错误的身份认证方式， HTTPBasicAuthHandler
     将会触发 *note ValueError: 16d. 。

 -- 類別: urllib.request.ProxyBasicAuthHandler (password_mgr=None)

     处理有代理服务时的身份认证。 `password_mgr' 应与 *note
     HTTPPasswordMgr: 2d82. 兼容；有关哪些接口是必须支持的，请参阅 *note
     HTTPPasswordMgr 对象: 2d84. 章节。

 -- 類別: urllib.request.AbstractDigestAuthHandler (password_mgr=None)

     这是一个帮助完成 HTTP 身份认证的混合类，对远程主机和代理都适用。参
     数 `password_mgr' 应与 *note HTTPPasswordMgr: 2d82. 兼容；关于必须
     支持哪些接口，请参阅 *note HTTPPasswordMgr 对象: 2d84. 的章节。

 -- 類別: urllib.request.HTTPDigestAuthHandler (password_mgr=None)

     处理远程主机的身份认证。 `password_mgr' 应与 *note HTTPPasswordMgr:
     2d82. 兼容；有关哪些接口是必须支持的，请参阅 *note HTTPPasswordMgr
     对象: 2d84. 章节。如果同时添加了 digest 身份认证 handler 和basic 身
     份认证 handler，则会首先尝试 digest 身份认证。如果 digest 身份认证
     再返回 40x 响应，会再发送到 basic 身份验证 handler 进行处理。如果给
     出 Digest 和 Basic 之外的身份认证方式， 本 handler 方法将会触发
     *note ValueError: 16d. 。

     3.3 版更變: 碰到不支持的认证方式时，将会触发 *note ValueError: 16d.
     。

 -- 類別: urllib.request.ProxyDigestAuthHandler (password_mgr=None)

     处理有代理服务时的身份认证。 `password_mgr' 应与 *note
     HTTPPasswordMgr: 2d82. 兼容；有关哪些接口是必须支持的，请参阅 *note
     HTTPPasswordMgr 对象: 2d84. 章节。

 -- 類別: urllib.request.HTTPHandler

     用于打开 HTTP URL 的 handler 类。

 -- 類別: urllib.request.HTTPSHandler (debuglevel=0, context=None,
          check_hostname=None)

     用于打开 HTTPS URL 的 handler 类。`context' 和 `check_hostname' 的
     含义与 *note http.client.HTTPSConnection: 499. 的一样。

     3.2 版更變: 添加 `context' 和 `check_hostname' 参数。

 -- 類別: urllib.request.FileHandler

     打开本地文件。

 -- 類別: urllib.request.DataHandler

     打开数据 URL。

     3.4 版新加入.

 -- 類別: urllib.request.FTPHandler

     打开 FTP URL。

 -- 類別: urllib.request.CacheFTPHandler

     打开 FTP URL，并将打开的 FTP 连接存入缓存，以便最大程度减少延迟。

 -- 類別: urllib.request.UnknownHandler

     处理所有未知类型 URL 的兜底类。

 -- 類別: urllib.request.HTTPErrorProcessor

     处理出错的 HTTP 响应。

* 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 的限制.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/urllib/request.py

   (2) https://requests.readthedocs.io/en/master/

   (3) https://tools.ietf.org/html/rfc7230.html

   (4) https://tools.ietf.org/html/rfc2965.html

   (5) https://tools.ietf.org/html/rfc2965.html


File: python.info,  Node: Request 对象,  Next: OpenerDirector 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.1 Request 对象
.....................

以下方法介绍了 *note Request: 9dc. 的公开接口，因此子类可以覆盖所有这些
方法。这里还定义了几个公开属性，客户端可以利用这些属性了解经过解析的请求
。

 -- 屬性: Request.full_url

     传给构造函数的原始 URL。

     3.4 版更變.

     Request.full_url 是一个带有 setter、getter 和 deleter 的属性。读取
     *note full_url: 9de. 属性将会返回附带片段（fragment）的初始请求
     URL。

 -- 屬性: Request.type

     URI 方式。

 -- 屬性: Request.host

     URI 权限，通常是整个主机，但也有可能带有冒号分隔的端口号。

 -- 屬性: Request.origin_req_host

     请求的原始主机，不含端口。

 -- 屬性: Request.selector

     URI 路径。若 *note Request: 9dc. 使用代理，selector 将会是传给代理
     的完整 URL。

 -- 屬性: Request.data

     请求的数据体，未给出则为 ‘None’ 。

     3.4 版更變: 现在如果修改 *note Request.data: 9df. 的值，则会删除之
     前设置或计算过的“Content-Length”头部信息。

 -- 屬性: Request.unverifiable

     布尔值，标识本请求是否属于 RFC 2965(1) 中定义的无法验证的情况。

 -- 屬性: Request.method

     要采用的 HTTP 请求方法。默认为 *note None: 203.，表示 *note
     get_method(): b99. 将对方法进行正常处理。设置本值可以覆盖 *note
     get_method(): b99. 中的默认处理过程，设置方式可以是在 *note
     Request: 9dc. 的子类中给出默认值，也可以通过 `method' 参数给 *note
     Request: 9dc. 构造函数传入一个值。

     3.3 版新加入.

     3.4 版更變: 现在可以在子类中设置默认值；而之前只能通过构造函数的实
     参进行设置。

 -- 成員函式: Request.get_method ()

     返回表示 HTTP 请求方法的字符串。如果 *note Request.method: 9dd. 不
     为 ‘None’ ，则返回其值。否则若 *note Request.data: 9df. 为 则返回
     ‘'GET'’，不为 ‘None’ 则返回 ‘'POST'’ 。只对 HTTP 请求有效。

     3.3 版更變: 现在 get_method 会兼顾 *note Request.method: 9dd. 的值
     。

 -- 成員函式: Request.add_header (key, val)

     向请求添加一项头部信息。目前只有 HTTP handler 才会处理头部信息，将
     其加入发给服务器的头部信息列表中。请注意，同名的头部信息只能出现一
     次，如果 `键' 发生冲突，后续的调用结果将会覆盖先前的。目前，这并不
     会减少 HTTP 的功能，因为所有多次使用仍有意义的头部信息，都有一种特
     定方式获得与只用一次时相同的功能。

 -- 成員函式: Request.add_unredirected_header (key, header)

     添加一项不会被加入重定向请求的头部信息。

 -- 成員函式: Request.has_header (header)

     返回本实例是否带有命名头部信息（对常规数据和非重定向数据都会检测）
     。

 -- 成員函式: Request.remove_header (header)

     从本请求实例中移除指定命名的头部信息（对常规数据和非重定向数据都会
     检测）。

     3.4 版新加入.

 -- 成員函式: Request.get_full_url ()

     返回构造器中给定的 URL。

     3.4 版更變.

     返回 *note Request.full_url: 9de.

 -- 成員函式: Request.set_proxy (host, type)

     连接代理服务器，为当前请求做准备。 `host' 和 `type' 将会取代本实例
     中的对应值，selector 将会是构造函数中给出的初始 URL。

 -- 成員函式: Request.get_header (header_name, default=None)

     返回给定头部信息的数据。如果该头部信息不存在，返回默认值。

 -- 成員函式: Request.header_items ()

     返回头部信息，形式为（名称, 数据）的元组列表。

3.4 版更變: 自 3.3 起已弃用的下列方法已被删除：add_data、has_data、
get_data、get_type、get_host、get_selector、get_origin_req_host 和
is_unverifiable 。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2965.html


File: python.info,  Node: OpenerDirector 对象,  Next: BaseHandler 对象,  Prev: Request 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.2 OpenerDirector 对象
............................

*note OpenerDirector: 2d72. 实例有以下方法：

 -- 成員函式: OpenerDirector.add_handler (handler)

     `handler' 应为 *note BaseHandler: 2d76. 的实例。将检索以下类型的方
     法，并将其添加到对应的处理链中（注意 HTTP 错误是特殊情况）。请注意
     ，下文中的 `protocol' 应替换为要处理的实际协议，例如
     ‘http_response()’ 将是 HTTP 协议响应处理函数。并且 `type' 也应替换
     为实际的 HTTP 代码，例如 ‘http_error_404()’ 将处理 HTTP 404 错误。

        * ‘<protocol>_open()’ — 表明该 handler 知道如何打开 `protocol' 协
          议的URL。

          更多信息请参阅 *note BaseHandler.<protocol>_open(): 2d9b. 。

        * ‘http_error_<type>()’ — 表明该 handler 知道如何处理代码为
          `type' 的 HTTP 错误。

          更多信息请参阅 *note BaseHandler.http_error_<nnn>(): 2d9c. 。

        * ‘<protocol>_error()’ — 表明该 handler 知道如何处理来自协议为
          `protocol' （非‘http’）的错误。

        * ‘<protocol>_request()’ — 表明该 handler 知道如何预处理协议为
          `protocol' 的请求。

          更多信息请参阅 *note BaseHandler.<protocol>_request(): 2d9d. 。

        * ‘<protocol>_response()’ — 表明该 handler 知道如何后处理协议为
          `protocol' 的响应。

          更多信息请参阅 *note BaseHandler.<protocol>_response(): 2d9e.
          。

 -- 成員函式: OpenerDirector.open (url, data=None[, timeout])

     Open the given `url' (which can be a request object or a string),
     optionally passing the given `data'.  Arguments, return values and
     exceptions raised are the same as those of *note urlopen(): 87b.
     (which simply calls the *note open(): 16f. method on the currently
     installed global *note OpenerDirector: 2d72.).  The optional
     `timeout' parameter specifies a timeout in seconds for blocking
     operations like the connection attempt (if not specified, the
     global default timeout setting will be used).  The timeout feature
     actually works only for HTTP, HTTPS and FTP connections.

 -- 成員函式: OpenerDirector.error (proto, *args)

     处理给定协议的错误。将用给定的参数（协议相关）调用已注册的给定协议
     的错误处理程序。HTTP 协议是特殊情况，采用 HTTP 响应码来确定具体的错
     误处理程序；请参考 handler 类的 ‘http_error_<type>()’ 方法。

     返回值和异常均与 *note urlopen(): 87b. 相同。

OpenerDirector 对象分 3 个阶段打开 URL：

每个阶段中调用这些方法的次序取决于 handler 实例的顺序。

  1. 每个具有 ‘_request()’ 这类方法的 handler 都会调用本方法对请求进行预
     处理。

  2. 调用具有 ‘_open()’ 这类方法的 handler 来处理请求。当 handler 返回非
     *note None: 203. 值（即响应）或引发异常（通常是 *note URLError:
     2d71.）时，本阶段结束。本阶段能够传播异常。

     事实上，以上算法首先会尝试名为 ‘default_open()’ 的。如果这些方法全
     都返回 *note None: 203.，则会对名为 ‘_open()’ 的这类方法重复过程。
     如果又都返回 *note None: 203.，则再对名为 ‘unknown_open()’ 的方法重
     复过程。

     请注意，这些方法的代码可能会调用 *note OpenerDirector: 2d72. 父实例
     的 *note open(): 9e0. 和 *note error(): 2d9f. 方法。

  3. 每个具有 ‘_response()’ 这类方法的 handler 都会调用这些方法，以对响
     应进行后处理。


File: python.info,  Node: BaseHandler 对象,  Next: HTTPRedirectHandler 对象,  Prev: OpenerDirector 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.3 BaseHandler 对象
.........................

*note BaseHandler: 2d76. 对象提供了一些直接可用的方法，以及其他一些可供
派生类使用的方法。以下是可供直接使用的方法：

 -- 成員函式: BaseHandler.add_parent (director)

     将 director 加为父 OpenerDirector。

 -- 成員函式: BaseHandler.close ()

     移除所有父 OpenerDirector。

以下属性和方法仅供 *note BaseHandler: 2d76. 的子类使用：

     備註: 以下约定已被采纳：定义 ‘<protocol>_request()’ 或
     ‘<protocol>_response()’ 方法的子类应命名为 ‘*Processor’；所有其他子
     类都应命名为 ‘*Handler’ 。

 -- 屬性: BaseHandler.parent

     一个可用的 *note OpenerDirector: 2d72.，可用于以其他协议打开 URI，
     或处理错误。

 -- 成員函式: BaseHandler.default_open (req)

     本方法在 *note BaseHandler: 2d76. 中 `未' 予定义，但其子类若要捕获
     所有 URL 则应进行定义。

     若实现了本方法，则会被父类 *note OpenerDirector: 2d72. 调用。应返回
     一个文件类对象，类似于 *note OpenerDirector: 2d72. 的 *note open():
     16f. 的返回值，或返回 ‘None’ 。触发的异常应为 *note URLError:
     2d71.，除非发生真的异常（比如 *note MemoryError: f69. 就不应变为
     ‘URLError’）。

     本方法将会在所有协议的 open 方法之前被调用。

 -- 成員函式: BaseHandler.<protocol>_open(req)

     本方法在 *note BaseHandler: 2d76. 中 `未' 予定义，但其子类若要处理
     给定协议的 URL 则应进行定义。

     若定义了本方法，将会被父 *note OpenerDirector: 2d72. 对象调用。返回
     值和 ‘default_open()’ 的一样。

 -- 成員函式: BaseHandler.unknown_open (req)

     本方法在 *note BaseHandler: 2d76. 中 `未' 予定义，但其子类若要捕获
     并打开所有未注册 handler 的 URL，则应进行定义。

     若实现了本方法，将会被 *note parent: 2da4. 属性指向的父 *note
     OpenerDirector: 2d72. 调用。返回值和 *note default_open(): 2da5. 的
     一样。

 -- 成員函式: BaseHandler.http_error_default (req, fp, code, msg, hdrs)

     本方法在 *note BaseHandler: 2d76. 中 `未' 予定义，但其子类若要为所
     有未定义 handler 的 HTTP 错误提供一个兜底方法，则应进行重写。*note
     OpenerDirector: 2d72. 会自动调用本方法，获取错误信息，而通常在其他
     时候不应去调用。

     `req' 会是一个 *note Request: 9dc. 对象，`fp' 是一个带有 HTTP 错误
     体的文件类对象，`code' 是三位数的错误码，`msg' 是供用户阅读的解释信
     息，`hdrs' 则是一个包含出错头部信息的字典对象。

     返回值和触发的异常应与 *note urlopen(): 87b. 的相同。

 -- 成員函式: BaseHandler.http_error_<nnn>(req, fp, code, msg, hdrs)

     `nnn' 应为三位数的 HTTP 错误码。本方法在 *note BaseHandler: 2d76. 中
     也未予定义，但当子类的实例发生代码为 `nnn' 的 HTTP 错误时，若方法存
     在则会被调用。

     子类应该重写本方法，以便能处理相应的 HTTP 错误。

     参数、返回值和触发的异常应与 ‘http_error_default()’ 相同。

 -- 成員函式: BaseHandler.<protocol>_request(req)

     本方法在 *note BaseHandler: 2d76. 中 `未' 予定义，但其子类若要对给
     定协议的请求进行预处理，则应进行定义。

     若实现了本方法，将会被父 *note OpenerDirector: 2d72. 调用。`req' 将
     为 *note Request: 9dc. 对象。返回值应为 *note Request: 9dc. 对象。

 -- 成員函式: BaseHandler.<protocol>_response(req, response)

     本方法在 *note BaseHandler: 2d76. 中 `未' 予定义，但其子类若要对给
     定协议的请求进行后处理，则应进行定义。

     若实现了本方法，将会被父 *note OpenerDirector: 2d72. 调用。`req' 将
     为 *note Request: 9dc. 对象。`response' 应实现与 *note urlopen():
     87b. 返回值相同的接口。返回值应实现与 *note urlopen(): 87b. 返回值
     相同的接口。


File: python.info,  Node: HTTPRedirectHandler 对象,  Next: HTTPCookieProcessor 对象,  Prev: BaseHandler 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.4 HTTPRedirectHandler 对象
.................................

     備註: 某些 HTTP 重定向操作需要本模块的客户端代码提供的功能。这时会
     触发 *note HTTPError: 9e2.。有关各种重定向代码的确切含义，请参阅
     RFC 2616(1) 。

     如果给到 HTTPRedirectHandler 的重定向 URL 不是 HTTP、HTTPS 或 FTP
     URL，则出于安全考虑将触发 ‘HTTPError’ 异常。

 -- 成員函式: HTTPRedirectHandler.redirect_request (req, fp, code, msg,
          hdrs, newurl)

     返回 *note Request: 9dc. 或 ‘None’ 对象作为重定向行为的响应。当服务
     器接收到重定向请求时， ‘http_error_30*()’ 方法的默认实现代码将会调
     用本方法。如果确实应该发生重定向，则返回一个新的 *note Request:
     9dc. 对象，使得 ‘http_error_30*()’ 能重定向至 `newurl'。否则，若没
     有 handler 会处理此 URL，则会引发 *note HTTPError: 9e2.；或者本方法
     不能处理但或许会有其他 handler 会处理，则返回 ‘None’ 。

          備註: 本方法的默认实现代码并未严格遵循 RFC 2616(2)，即 ‘POST’
          请求的 301 和 302 响应不得在未经用户确认的情况下自动进行重定向
          。现实情况下，浏览器确实允许自动重定向这些响应，将 POST 更改为
          ‘GET’ ，于是默认实现代码就复现了这种处理方式。

 -- 成員函式: HTTPRedirectHandler.http_error_301 (req, fp, code, msg,
          hdrs)

     重定向到 ‘Location:’ 或 ‘URI:’ URL。 这个方法会在得到 HTTP ’moved
     permanently’ 响应时由上级 *note OpenerDirector: 2d72. 来调用。

 -- 成員函式: HTTPRedirectHandler.http_error_302 (req, fp, code, msg,
          hdrs)

     与 *note http_error_301(): 2dab. 相同，不过是发生“found”响应时的调
     用。

 -- 成員函式: HTTPRedirectHandler.http_error_303 (req, fp, code, msg,
          hdrs)

     与 *note http_error_301(): 2dab. 相同，不过是发生“see other”响应时
     的调用。

 -- 成員函式: HTTPRedirectHandler.http_error_307 (req, fp, code, msg,
          hdrs)

     与 *note http_error_301(): 2dab. 相同，不过是发生“temporary
     redirect”响应时的调用。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2616.html

   (2) https://tools.ietf.org/html/rfc2616.html


File: python.info,  Node: HTTPCookieProcessor 对象,  Next: ProxyHandler 对象,  Prev: HTTPRedirectHandler 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.5 HTTPCookieProcessor 对象
.................................

*note HTTPCookieProcessor: 2d81. 的实例具备一个属性：

 -- 屬性: HTTPCookieProcessor.cookiejar

     cookie 存放在 *note http.cookiejar.CookieJar: 2db2. 中。


File: python.info,  Node: ProxyHandler 对象,  Next: HTTPPasswordMgr 对象,  Prev: HTTPCookieProcessor 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.6 ProxyHandler 对象
..........................

 -- 成員函式: ProxyHandler.<protocol>_open(request)

     *note ProxyHandler: 10d8. 将为每种 `protocol' 准备一个 ‘_open()’ 方
     法，在构造函数给出的 `proxies' 字典中包含对应的代理服务器信息。通过
     调用 ‘request.set_proxy()’，本方法将把请求转为通过代理服务器，并会
     调用 handler 链中的下一个 handler 来完成对应的协议处理。


File: python.info,  Node: HTTPPasswordMgr 对象,  Next: HTTPPasswordMgrWithPriorAuth 对象,  Prev: ProxyHandler 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.7 HTTPPasswordMgr 对象
.............................

以下方法 *note HTTPPasswordMgr: 2d82. 和 *note
HTTPPasswordMgrWithDefaultRealm: 2d83. 对象均有提供。

 -- 成員函式: HTTPPasswordMgr.add_password (realm, uri, user, passwd)

     `uri' 可以是单个 URI，也可以是 URI 列表。`realm'、`user' 和
     `passwd' 必须是字符串。这使得在为 `realm' 和超级 URI 进行身份认证时
     ，‘(user, passwd)’ 可用作认证令牌。

 -- 成員函式: HTTPPasswordMgr.find_user_password (realm, authuri)

     为给定 realm 和 URI 获取用户名和密码。如果没有匹配的用户名和密码，
     本方法将会返回 ‘(None, None)’ 。

     对于 *note HTTPPasswordMgrWithDefaultRealm: 2d83. 对象，如果给定
     `realm' 没有匹配的用户名和密码，将搜索 realm ‘None’。


File: python.info,  Node: HTTPPasswordMgrWithPriorAuth 对象,  Next: AbstractBasicAuthHandler 对象,  Prev: HTTPPasswordMgr 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.8 HTTPPasswordMgrWithPriorAuth 对象
..........................................

这是 *note HTTPPasswordMgrWithDefaultRealm: 2d83. 的扩展，以便对那些需要
一直发送认证凭证的 URI 进行跟踪。

 -- 成員函式: HTTPPasswordMgrWithPriorAuth.add_password (realm, uri,
          user, passwd, is_authenticated=False)

     `realm'、`uri'、`user'、`passwd' 的含义与 *note
     HTTPPasswordMgr.add_password(): 2db6. 的相同。`is_authenticated' 为
     给定 URI 或 URI 列表设置 ‘is_authenticated’ 标志的初始值。如果
     `is_authenticated' 设为 ‘True’ ，则会忽略 `realm'。

 -- 成員函式: HTTPPasswordMgrWithPriorAuth.find_user_password (realm,
          authuri)

     与 *note HTTPPasswordMgrWithDefaultRealm: 2d83. 对象的相同。

 -- 成員函式: HTTPPasswordMgrWithPriorAuth.update_authenticated (self,
          uri, is_authenticated=False)

     更新给定 `uri' 或 URI 列表的 ‘is_authenticated’ 标志。

 -- 成員函式: HTTPPasswordMgrWithPriorAuth.is_authenticated (self,
          authuri)

     返回给定 URI ‘is_authenticated’ 标志的当前状态。


File: python.info,  Node: AbstractBasicAuthHandler 对象,  Next: HTTPBasicAuthHandler 对象,  Prev: HTTPPasswordMgrWithPriorAuth 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.9 AbstractBasicAuthHandler 对象
......................................

 -- 成員函式: AbstractBasicAuthHandler.http_error_auth_reqed (authreq,
          host, req, headers)

     通过获取用户名和密码并重新尝试请求，以处理身份认证请求。 `authreq'
     应该是请求中包含 realm 的头部信息名称，`host' 指定了需要进行身份认
     证的 URL 和路径，`req' 应为 (已失败的) *note Request: 9dc. 对象 ,
     `headers' 应该是出错的头部信息。

     `host' 要么是一个认证信息（例如 ‘"python.org"’ ），要么是一个包含认
     证信息的 URL（如‘‘"‘http://python.org/’"‘‘ ）。 不论是哪种格式，认
     证信息中都不能包含用户信息（因此，‘"python.org"’ 和
     ‘"python.org:80"’ 没问题，而 ‘"joe:password@python.org"’ 则不行）。


File: python.info,  Node: HTTPBasicAuthHandler 对象,  Next: ProxyBasicAuthHandler 对象,  Prev: AbstractBasicAuthHandler 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.10 HTTPBasicAuthHandler 对象
...................................

 -- 成員函式: HTTPBasicAuthHandler.http_error_401 (req, fp, code, msg,
          hdrs)

     如果可用的话，请用身份认证信息重试请求。


File: python.info,  Node: ProxyBasicAuthHandler 对象,  Next: AbstractDigestAuthHandler 对象,  Prev: HTTPBasicAuthHandler 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.11 ProxyBasicAuthHandler 对象
....................................

 -- 成員函式: ProxyBasicAuthHandler.http_error_407 (req, fp, code, msg,
          hdrs)

     如果可用的话，请用身份认证信息重试请求。


File: python.info,  Node: AbstractDigestAuthHandler 对象,  Next: HTTPDigestAuthHandler 对象,  Prev: ProxyBasicAuthHandler 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.12 AbstractDigestAuthHandler 对象
........................................

 -- 成員函式: AbstractDigestAuthHandler.http_error_auth_reqed (authreq,
          host, req, headers)

     `authreq' 应为请求中有关 realm 的头部信息名称，`host' 应为需要进行
     身份认证的主机，`req' 应为（已失败的） *note Request: 9dc. 对象，
     `headers' 则应为出错的头部信息。


File: python.info,  Node: HTTPDigestAuthHandler 对象,  Next: ProxyDigestAuthHandler 对象,  Prev: AbstractDigestAuthHandler 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.13 HTTPDigestAuthHandler 对象
....................................

 -- 成員函式: HTTPDigestAuthHandler.http_error_401 (req, fp, code, msg,
          hdrs)

     如果可用的话，请用身份认证信息重试请求。


File: python.info,  Node: ProxyDigestAuthHandler 对象,  Next: HTTPHandler 对象,  Prev: HTTPDigestAuthHandler 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.14 ProxyDigestAuthHandler 对象
.....................................

 -- 成員函式: ProxyDigestAuthHandler.http_error_407 (req, fp, code, msg,
          hdrs)

     如果可用的话，请用身份认证信息重试请求。


File: python.info,  Node: HTTPHandler 对象,  Next: HTTPSHandler 对象,  Prev: ProxyDigestAuthHandler 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.15 HTTPHandler 对象
..........................

 -- 成員函式: HTTPHandler.http_open (req)

     发送 HTTP 请求，根据 ‘req.has_data()’ 的结果，可能是 GET 或 POST 格
     式。


File: python.info,  Node: HTTPSHandler 对象,  Next: FileHandler 对象,  Prev: HTTPHandler 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.16 HTTPSHandler 对象
...........................

 -- 成員函式: HTTPSHandler.https_open (req)

     发送 HTTPS 请求，根据 ‘req.has_data()’ 的结果，可能是 GET 或 POST 格
     式。


File: python.info,  Node: FileHandler 对象,  Next: DataHandler 对象,  Prev: HTTPSHandler 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.17 FileHandler 对象
..........................

 -- 成員函式: FileHandler.file_open (req)

     若无主机名或主机名为 ‘'localhost'’ ，则打开本地文件。

     3.2 版更變: 本方法仅适用于本地主机名。如果给出的是远程主机名，将会
     触发 *note URLError: 2d71. 。


File: python.info,  Node: DataHandler 对象,  Next: FTPHandler 对象,  Prev: FileHandler 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.18 DataHandler 对象
..........................

 -- 成員函式: DataHandler.data_open (req)

     读取内含数据的 URL。这种 URL 本身包含了经过编码的数据。 RFC 2397(1)
     中给出了数据 URL 的语法定义。目前的代码库将忽略经过 base64 编码的数
     据 URL 中的空白符，因此 URL 可以放入任何源码文件中。如果数据 URL 的
     base64 编码尾部缺少填充，即使某些浏览器不介意，但目前的代码库仍会引
     发 *note ValueError: 16d.。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2397.html


File: python.info,  Node: FTPHandler 对象,  Next: CacheFTPHandler 对象,  Prev: DataHandler 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.19 FTPHandler 对象
.........................

 -- 成員函式: FTPHandler.ftp_open (req)

     打开由 `req' 给出的 FTP 文件。登录时的用户名和密码总是为空。


File: python.info,  Node: CacheFTPHandler 对象,  Next: UnknownHandler 对象,  Prev: FTPHandler 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.20 CacheFTPHandler 对象
..............................

*note CacheFTPHandler: 2d8a. 对象即为加入以下方法的 *note FTPHandler:
2d7a. 对象：

 -- 成員函式: CacheFTPHandler.setTimeout (t)

     设置连接超时为 `t' 秒。

 -- 成員函式: CacheFTPHandler.setMaxConns (m)

     设置已缓存的最大连接数为 `m' 。


File: python.info,  Node: UnknownHandler 对象,  Next: HTTPErrorProcessor 对象,  Prev: CacheFTPHandler 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.21 UnknownHandler 对象
.............................

 -- 成員函式: UnknownHandler.unknown_open ()

     触发 *note URLError: 2d71. 异常。


File: python.info,  Node: HTTPErrorProcessor 对象,  Next: 示例<33>,  Prev: UnknownHandler 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.22 HTTPErrorProcessor 对象
.................................

 -- 成員函式: HTTPErrorProcessor.http_response (request, response)

     处理出错的 HTTP 响应。

     对于 200 错误码，响应对象将立即返回。

     对于 200 以外的错误码，只通过 *note OpenerDirector.error(): 2d9f. 将
     任务传给 handler 的 ‘http_error_<type>()’ 方法。如果最终没有
     handler 处理错误， *note HTTPDefaultErrorHandler: 2d78. 将触发
     *note HTTPError: 9e2.。

 -- 成員函式: HTTPErrorProcessor.https_response (request, response)

     HTTPS 出错响应的处理。

     与 *note http_response(): 2de7. 方法相同。


File: python.info,  Node: 示例<33>,  Next: 沿袭的接口,  Prev: HTTPErrorProcessor 对象,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.23 示例
..............

*note 如何使用urllib套件取得網路資源: 2deb. 中给出了更多的示例。

以下示例将读取 python.org 主页并显示前 300 个字节的内容：

     >>> 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 '

请注意，urlopen 将返回字节串对象。这是因为 urlopen 无法自动确定由 HTTP 服
务器收到的字节流的编码。通常，只要能确定或猜出编码格式，就应将返回的字节
串解码为字符串。

下述 W3C 文档 ‘https://www.w3.org/International/O-charset’列出了可用于指
明（X）HTML 或 XML 文档编码信息的多种方案。

python.org 网站已在 meta 标签中指明，采用的是 `utf-8' 编码，因此这里将用
同样的格式对字节串进行解码。

     >>> 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

不用 *note context manager: 661. 方法也能获得同样的结果：

     >>> 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

以下示例将会把数据流发送给某 CGI 的 stdin，并读取返回数据。请注意，该示
例只能工作于 Python 装有 SSL 支持的环境。

     >>> 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"

上述示例中的 CGI 代码如下所示：

     #!/usr/bin/env python
     import sys
     data = sys.stdin.read()
     print('Content-type: text/plain\n\nGot Data: "%s"' % data)

下面是利用 *note Request: 9dc. 发送‘‘PUT‘‘ 请求的示例：

     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)

基本 HTTP 认证示例：

     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')

*note build_opener(): 2d75. 默认提供了很多现成的 handler，包括 *note
ProxyHandler: 10d8.。 默认情况下，*note ProxyHandler: 10d8. 会使用名为
‘<scheme>_proxy’ 的环境变量，其中的 ‘<scheme>’ 是相关的 URL 协议。 例如
，可以读取 ‘http_proxy’ 环境变量来获取 HTTP 代理的 URL。

以下示例将默认的 *note ProxyHandler: 10d8. 替换为自己的 handler，由程序
提供代理 URL，并利用 *note ProxyBasicAuthHandler: 2d87. 加入代理认证的支
持：

     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')

添加 HTTP 头部信息：

可利用 *note Request: 9dc. 构造函数的 `headers' 参数，或者是：

     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)

*note OpenerDirector: 2d72. 自动会在每个 *note Request: 9dc. 中加入一项
‘User-Agent’ 头部信息。若要修改，请参见以下语句：

     import urllib.request
     opener = urllib.request.build_opener()
     opener.addheaders = [('User-agent', 'Mozilla/5.0')]
     opener.open('http://www.example.com/')

另请记得，当 *note Request: 9dc. 传给 *note urlopen(): 87b. （或 *note
OpenerDirector.open(): 9e0.）时，会加入一些标准的头部信息（
‘Content-Length’ 、 ‘Content-Type’ 和 ‘Host’）。 以下会话示例用 ‘GET’ 方
法读取包含参数的 URL。

     >>> 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'))
     ...

以下示例换用 ‘POST’ 方法。请注意 urlencode 输出结果先被编码为字节串
data，再送入 urlopen。

     >>> 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'))
     ...

以下示例显式指定了 HTTP 代理，以覆盖环境变量中的设置：

     >>> 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')
     ...

以下示例根本不用代理，也覆盖了环境变量中的设置：

     >>> import urllib.request
     >>> opener = urllib.request.FancyURLopener({})
     >>> with opener.open("http://www.python.org/") as f:
     ...     f.read().decode('utf-8')
     ...


File: python.info,  Node: 沿袭的接口,  Next: urllib request 的限制,  Prev: 示例<33>,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.24 沿袭的接口
....................

以下函数和类是由 Python 2 模块 ‘urllib``（相对早于 ``urllib2’ ）移植过来
的。将来某个时候可能会停用。

 -- 函式: urllib.request.urlretrieve (url, filename=None,
          reporthook=None, data=None)

     将 URL 形式的网络对象复制为本地文件。如果 URL 指向本地文件，则必须
     提供文件名才会执行复制。返回值为元组 ‘(filename, headers)’ ，其中
     `filename' 是保存网络对象的本地文件名， `headers' 是由 *note
     urlopen(): 87b. 返回的远程对象 ‘info()’ 方法的调用结果。可能触发的
     异常与 *note urlopen(): 87b. 相同。

     第二个参数指定文件的保存位置（若未给出，则会是名称随机生成的临时文
     件）。第三个参数是个可调用对象，在建立网络连接时将会调用一次，之后
     每次读完数据块后会调用一次。该可调用对象将会传入 3 个参数：已传输的
     块数、块的大小（以字节为单位）和文件总的大小。如果面对的是老旧 FTP
     服务器，文件大小参数可能会是 ‘-1’ ，这些服务器响应读取请求时不会返
     回文件大小。

     以下例子演示了大部分常用场景：

          >>> import urllib.request
          >>> local_filename, headers = urllib.request.urlretrieve('http://python.org/')
          >>> html = open(local_filename)
          >>> html.close()

     如果 `url' 使用 ‘http:’ 方式的标识符，则可能给出可选的 `data' 参数
     来指定一个 ‘POST’ 请求 (通常的请求类型为 ‘GET’)。 `data' 参数必须是
     标准 ‘application/x-www-form-urlencoded’ 格式的字节串对象；参见
     *note urllib.parse.urlencode(): 87a. 函数。

     *note urlretrieve(): 2dee. 在检测到可用数据少于预期的大小（即由
     `Content-Length' 标头所报告的大小）时将引发 ‘ContentTooShortError’。
     例如，这可能会在下载中断时发生。

     `Content-Length' 会被视为大小的下限：如果存在更多的可用数据，
     urlretrieve 会读取更多的数据，但是如果可用数据少于该值，则会引发异
     常。

     在这种情况下你仍然能够获取已下载的数据，它会存放在异常实例的
     ‘content’ 属性中。

     如果未提供 `Content-Length' 标头，urlretrieve 就无法检查它所下载的
     数据大小，只是简单地返回它。 在这种情况下你只能假定下载是成功的。

 -- 函式: urllib.request.urlcleanup ()

     清理之前调用 *note urlretrieve(): 2dee. 时可能留下的临时文件。

 -- 類別: urllib.request.URLopener (proxies=None, **x509)

     3.3 版後已棄用.

     用于打开和读取 URL 的基类。 除非你需要支持使用 ‘http:’, ‘ftp:’ 或
     ‘file:’ 以外的方式来打开对象，那你也许可以使用 *note
     FancyURLopener: 2d70.。

     在默认情况下，*note URLopener: 2d6f. 类会发送一个内容为
     ‘urllib/VVV’ 的 ‘User-Agent’ 标头，其中 `VVV' 是 *note urllib: 126.
     的版本号。 应用程序可以通过子类化 *note URLopener: 2d6f. 或 *note
     FancyURLopener: 2d70. 并在子类定义中将类属性 *note version: 2def. 设
     为适当的字符串值来定义自己的 ‘User-Agent’ 标头。

     可选的 `proxies' 形参应当是一个将方式名称映射到代理 URL 的字典，如
     为空字典则会完全关闭代理。 它的默认值为 ‘None’，在这种情况下如果存
     在环境代理设置则将使用它，正如上文 *note urlopen(): 87b. 的定义中所
     描述的。

     一些归属于 `x509' 的额外关键字形参可在使用 ‘https:’ 方式时被用于客
     户端的验证。 支持通过关键字 `key_file' 和 `cert_file' 来提供 SSL 密
     钥和证书；对客户端验证的支持需要提供这两个形参。

     如果服务器返回错误代码则 *note URLopener: 2d6f. 对象将引发 *note
     OSError: 304. 异常。

      -- 成員函式: open (fullurl, data=None)

          使用适当的协议打开 `fullurl'。 此方法会设置缓存和代理信息，然
          后调用适当的打开方法并附带其输入参数。 如果方式无法被识别，则
          会调用 *note open_unknown(): 2df1.。 `data' 参数的含义与 *note
          urlopen(): 87b. 中的 `data' 参数相同。

          此方法总是会使用 *note quote(): 511. 来对 `fullurl' 进行转码。

      -- 成員函式: open_unknown (fullurl, data=None)

          用于打开未知 URL 类型的可重载接口。

      -- 成員函式: retrieve (url, filename=None, reporthook=None,
               data=None)

          提取 `url' 的内容并将其存放到 `filename' 中。 返回值为元组，由
          一个本地文件名和一个包含响应标头 (对于远程 URL) 的 *note
          email.message.Message: 63b. 对象或者 ‘None’ (对于本地 URL)。 之
          后调用方必须打开并读取 `filename' 的内容。 如果 `filename' 未
          给出并且 URL 指向一个本地文件，则会返回输入文件名。 如果 URL 非
          本地并且 `filename' 未给出，则文件名为带有与输入 URL 的路径末
          尾部分后缀相匹配的后缀的 *note tempfile.mktemp(): f7d. 的输出
          。 如果给出了 `reporthook'，它必须为接受三个数字形参的函数：数
          据分块编号、读入分块的最大数据量和下载的总数据量 (未知则为
          -1)。 它将在开始时和从网络读取每个数据分块之后被调用。 对于本
          地 URL `reporthook' 会被忽略。

          如果 `url' 使用 ‘http:’ 方式的标识符，则可能给出可选的 `data'
          参数来指定一个 ‘POST’ 请求 (通常的请求类型为 ‘GET’)。 `data' 参
          数必须为标准的 ‘application/x-www-form-urlencoded’ 格式 ；参见
          *note urllib.parse.urlencode(): 87a. 函数。

      -- 屬性: version

          指明打开器对象的用户代理名称的变量。 以便让 *note urllib: 126.
          告诉服务器它是某个特定的用户代理，请在子类中将其作为类变量来设
          置或是在调用基类构造器之前在构造器中设置。

 -- 類別: urllib.request.FancyURLopener (...)

     3.3 版後已棄用.

     *note FancyURLopener: 2d70. 子类化了 *note URLopener: 2d6f. 以提供
     对以下 HTTP 响应代码的默认处理: 301, 302, 303, 307 和 401。 对于上
     述的 30x 响应代码，会使用 ‘Location’ 标头来获取实际 URL。 对于 401
     响应代码 (authentication required)，则会执行基本 HTTP 验证。 对于
     30x 响应代码，递归层数会受 `maxtries' 属性值的限制，该值默认为 10。

     对于所有其他响应代码，会调用 ‘http_error_default()’ 方法，你可以在
     子类中重载此方法来正确地处理错误。

          備註: 根据 RFC 2616(1) 的说明，对 POST 请求的 301 和 302 响应
          不可在未经用户确认的情况下自动进行重定向。 在现实情况下，浏览
          器确实允许自动重定义这些响应，将 POST 更改为 GET，于是 *note
          urllib: 126. 就会复现这种行为。

     传给此构造器的形参与 *note URLopener: 2d6f. 的相同。

          備註: 当执行基本验证时，*note FancyURLopener: 2d70. 实例会调用
          其 *note prompt_user_passwd(): 2df2. 方法。 默认的实现将向用户
          询问控制终端所要求的信息。 如有必要子类可以重载此方法来支持更
          适当的行为。

     *note FancyURLopener: 2d70. 类附带了一个额外方法，它应当被重载以提
     供适当的行为:

      -- 成員函式: prompt_user_passwd (host, realm)

          返回指定的安全体系下在给定的主机上验证用户所需的信息。 返回的
          值应当是一个元组 ‘(user, password)’，它可被用于基本验证。

          该实现会在终端上提示此信息；应用程序应当重载此方法以使用本地环
          境下适当的交互模型。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2616.html


File: python.info,  Node: urllib request 的限制,  Prev: 沿袭的接口,  Up: urllib request --- 用于打开 URL 的可扩展库

5.21.6.25 ‘urllib.request’ 的限制
.................................

   * 目前，仅支持下列协议: HTTP (0.9 和 1.0 版), FTP, 本地文件, 以及数据
     URL。

     3.4 版更變: 增加了对数据URL 的支持。

   * *note urlretrieve(): 2dee. 的缓存特性已被禁用，等待有人有时间去正确
     地解决过期时间标头的处理问题。

   * 应当有一个函数来查询特定 URL 是否在缓存中。

   * 为了保持向下兼容性，如果某个 URL 看起来是指向本地文件但该文件无法被
     打开，则该 URL 会使用 FTP 协议来重新解读。 这有时可能会导致令人迷惑
     的错误消息。

   * *note urlopen(): 87b. 和 *note urlretrieve(): 2dee. 方法在等待网络
     连接建立时会导致任意长的延迟。这意味着在不使用线程的情况下，搭建一
     个可交互的网络客户端是非常困难的。

   * 由 *note urlopen(): 87b. 或 *note urlretrieve(): 2dee. 返回的数据就
     是服务器所返回的原始数据。 这可以是二进制数据（如图片）、纯文本或
     HTML 代码等。 HTTP 协议在响应标头中提供了类型信息，这可以通过读取
     ‘Content-Type’ 标头来查看。 如果返回的数据是 HTML，你可以使用 *note
     html.parser: 91. 模块来解析它。

   * 处理 FTP 协议的代码无法区分文件和目录。 这在尝试读取指向不可访问的
     URL 时可能导致意外的行为。 如果 URL 以一个 ‘/’ 结束，它会被认为指向
     一个目录并将作相应的处理。 但是如果读取一个文件的尝试导致了 550 错
     误（表示 URL 无法找到或不可访问，这常常是由于权限原因），则该路径会
     被视为一个目录以便处理 URL 是指定一个目录但略去了末尾 ‘/’ 的情况。
     这在你尝试获取一个因其设置了读取权限因而无法访问的文件时会造成误导
     性的结果；FTP 代码将尝试读取它，因 550 错误而失败，然后又为这个不可
     读取的文件执行目录列表操作。 如果需要细粒度的控制，请考虑使用 *note
     ftplib: 82. 模块，子类化 *note FancyURLopener: 2d70.，或是修改
     `_urlopener' 来满足你的需求。


File: python.info,  Node: urllib response --- urllib 使用的 Response 类,  Next: urllib parse 用于解析 URL,  Prev: urllib request --- 用于打开 URL 的可扩展库,  Up: 互联网协议和支持

5.21.7 ‘urllib.response’ — urllib 使用的 Response 类
----------------------------------------------------

*note urllib.response: 12a. 模块定义了一些函数和提供最小化文件类接口包括
‘read()’ 和 ‘readline()’ 等的类。 此模块定义的函数会由 *note
urllib.request: 129. 模块在内部使用。 典型的响应对象是一个 *note
urllib.response.addinfourl: 2d6d. 实例:

 -- 類別: urllib.response.addinfourl

      -- 屬性: url

          已读取资源的 URL，通常用于确定是否进行了重定向。

      -- 屬性: headers

          以 *note EmailMessage: 63c. 实例的形式返回响应的标头。

      -- 屬性: status

          3.9 版新加入.

          由服务器返回的状态码。

      -- 成員函式: geturl ()

          3.9 版後已棄用: 已弃用，建议改用 *note url: 2df5.。

      -- 成員函式: info ()

          3.9 版後已棄用: 已弃用，建议改用 *note headers: 2df6.。

      -- 屬性: code

          3.9 版後已棄用: 已弃用，建议改用 *note status: 2df7.。

      -- 成員函式: getstatus ()

          3.9 版後已棄用: 已弃用，建议改用 *note status: 2df7.。


File: python.info,  Node: urllib parse 用于解析 URL,  Next: urllib error --- urllib request 引发的异常类,  Prev: urllib response --- urllib 使用的 Response 类,  Up: 互联网协议和支持

5.21.8 ‘urllib.parse’ 用于解析 URL
----------------------------------

`源代码:' Lib/urllib/parse.py(1)

__________________________________________________________________

该模块定义了一个标准接口，用于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:
‘file’, ‘ftp’, ‘gopher’, ‘hdl’, ‘http’, ‘https’, ‘imap’, ‘mailto’,
‘mms’, ‘news’, ‘nntp’, ‘prospero’, ‘rsync’, ‘rtsp’, ‘rtspu’, ‘sftp’,
‘shttp’, ‘sip’, ‘sips’, ‘snews’, ‘svn’, ‘svn+ssh’, ‘telnet’, ‘wais’,
‘ws’, ‘wss’.

*note urllib.parse: 128. 模块定义的函数可分为两个主要门类: URL 解析和
URL 转码。 这些函数将在以下各节中详细说明。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/urllib/parse.py


File: python.info,  Node: URL 解析,  Next: 解析ASCII编码字节,  Up: urllib parse 用于解析 URL

5.21.8.1 URL 解析
.................

URL解析功能可以将一个URL字符串分割成其组件，或者将URL组件组合成一个URL字
符串。

 -- 函式: urllib.parse.urlparse (urlstring, scheme='',
          allow_fragments=True)

     将一个 URL 解析为六个部分，返回一个包含 6 项的 *note named tuple:
     b7b.。 这对应于 URL 的主要结构:
     ‘scheme://netloc/path;parameters?query#fragment’。 每个元组项均为字
     符串，可能为空字符串。 这些部分不会再被拆分为更小的部分（例如，
     netloc 将为单个字符串），并且 % 转义不会被扩展。 上面显示的分隔符不
     会出现在结果中，只有 `path' 部分的开头斜杠例外，它如果存在则会被保
     留。 例如:

          >>> from urllib.parse import urlparse
          >>> urlparse("scheme://netloc/path;parameters?query#fragment")
          ParseResult(scheme='scheme', netloc='netloc', path='/path;parameters', params='',
                      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='',
                      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'

     根据 RFC 1808(1) 中的语法规范，urlparse 仅在 netloc 前面正确地附带
     了 ’//’ 的情况下才会识别它。 否则输入会被当作是一个相对 URL 因而以
     路径的组成部分开头。

          >>> from urllib.parse import urlparse
          >>> urlparse('//www.cwi.nl:80/%7Eguido/Python.html')
          ParseResult(scheme='', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
                      params='', query='', fragment='')
          >>> urlparse('www.cwi.nl/%7Eguido/Python.html')
          ParseResult(scheme='', netloc='', path='www.cwi.nl/%7Eguido/Python.html',
                      params='', query='', fragment='')
          >>> urlparse('help/Python.html')
          ParseResult(scheme='', netloc='', path='help/Python.html', params='',
                      query='', fragment='')

     `scheme' 参数给出了默认的协议，只有在 URL 未指定协议的情况下才会被
     使用。 它应该是与 `urlstring' 相同的类型（文本或字节串），除此之外
     默认值 ‘''’ 也总是被允许，并会在适当情况下自动转换为 ‘b''’。

     如果 `allow_fragments' 参数为假值，则片段标识符不会被识别。 它们会
     被解析为路径、参数或查询部分，在返回值中 ‘fragment’ 会被设为空字符
     串。

     返回值是一个 *note named tuple: b7b.，这意味着它的条目可以通过索引
     或作为命名属性来访问，这些属性是：

     属性                   索引        值                            值（如果不存在）
                                                                      
     ----------------------------------------------------------------------------------------------
                                                                      
     ‘scheme’               0           URL协议                       `scheme' 参数
                                                                      
                                                                      
     ‘netloc’               1           网络位置部分                  空字符串
                                                                      
                                                                      
     ‘path’                 2           分层路径                      空字符串
                                                                      
                                                                      
     ‘params’               3           No longer used                always an empty string
                                                                      
                                                                      
     ‘query’                4           查询组件                      空字符串
                                                                      
                                                                      
     ‘fragment’             5           片段识别                      空字符串
                                                                      
                                                                      
     ‘username’                         用户名                        *note None: 203.
                                                                      
                                                                      
     ‘password’                         密码                          *note None: 203.
                                                                      
                                                                      
     ‘hostname’                         主机名（小写）                *note None: 203.
                                                                      
                                                                      
     ‘port’                             端口号为整数（如果存在）      *note None: 203.
                                                                      

     如果在 URL 中指定了无效的端口，读取 ‘port’ 属性将引发 *note
     ValueError: 16d.。 有关结果对象的更多信息请参阅 *note
     结构化解析结果: 2dff. 一节。

     在 ‘netloc’ 属性中不匹配的方括号将引发 *note ValueError: 16d.。

     如果 ‘netloc’ 属性中的字符在 NFKC 规范化下（如 IDNA 编码格式所使用
     的）被分解成 ‘/’, ‘?’, ‘#’, ‘@’ 或 ‘:’ 则将引发 *note ValueError:
     16d.。 如果在解析之前 URL 就被分解，则不会引发错误。

     与所有具名元组的情况一样，该子类还有一些特别有用的附加方法和属性。
     其中一个方法是 ‘_replace()’。 ‘_replace()’ 方法将返回一个新的
     ParseResult 对象来将指定字段替换为新的值。

          >>> from urllib.parse import urlparse
          >>> u = urlparse('//www.cwi.nl:80/%7Eguido/Python.html')
          >>> u
          ParseResult(scheme='', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
                      params='', query='', fragment='')
          >>> u._replace(scheme='http')
          ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
                      params='', query='', fragment='')

     3.2 版更變: 添加了IPv6 URL解析功能。

     3.3 版更變: The fragment is now parsed for all URL schemes (unless
     `allow_fragment' is false), in accordance with RFC 3986(2).
     Previously, a whitelist of schemes that support fragments existed.

     3.6 版更變: 超范围的端口号现在会引发 *note ValueError: 16d.，而不是
     返回 *note None: 203.。

     3.8 版更變: 在 NFKC 规范化下会影响 netloc 解析的字符现在将引发
     *note ValueError: 16d.。

 -- 函式: urllib.parse.parse_qs (qs, keep_blank_values=False,
          strict_parsing=False, encoding='utf-8', errors='replace',
          max_num_fields=None, separator='&')

     解析以字符串参数形式（类型为 ‘application/x-www-form-urlencoded’ 的
     数据）给出的查询字符串。 返回字典形式的数据。 结果字典的键为唯一的
     查询变量名而值为每个变量名对应的值列表。

     可选参数 `keep_blank_values' 是一个旗标，指明是否要将以百分号转码的
     空值作为空字符串处理。 真值表示空值应当被保留作为空字符串。 默认的
     假值表示空值会被忽略并将其视作未包括的值。

     可选参数 `strict_parsing' 是一个旗标，指明要如何处理解析错误。 如为
     假值（默认），错误会被静默地忽略。 如为真值，错误会引发 *note
     ValueError: 16d. 异常。

     可选的 `encoding' 和 `errors' 形参指定如何将以百分号编码的序列解码
     为 Unicode 字符，即作为 *note bytes.decode(): 171. 方法所接受的数据
     。

     可选参数 `max_num_fields' 是要读取的最大字段数量的。 如果设置，则如
     果读取的字段超过 `max_num_fields' 会引发 *note ValueError: 16d.。

     可选参数 `separator' 是用来分隔查询参数的符号。 默认为 ‘&’。

     使用 *note urllib.parse.urlencode(): 87a. 函数 (并将 ‘doseq’ 形参设
     为 ‘True’) 将这样的字典转换为查询字符串。.

     3.2 版更變: 增加了 `encoding' 和 `errors' 形参。

     3.8 版更變: 增加了 `max_num_fields' 形参。

     3.9.2 版更變: Added `separator' parameter with the default value of
     ‘&’.  Python versions earlier than Python 3.9.2 allowed using both
     ‘;’ and ‘&’ as query parameter separator.  This has been changed to
     allow only a single separator key, with ‘&’ as the default
     separator.

 -- 函式: urllib.parse.parse_qsl (qs, keep_blank_values=False,
          strict_parsing=False, encoding='utf-8', errors='replace',
          max_num_fields=None, separator='&')

     解析以字符串参数形式（类型为 ‘application/x-www-form-urlencoded’ 的
     数据）给出的查询字符串。 数据以字段名和字段值对列表的形式返回。

     可选参数 `keep_blank_values' 是一个旗标，指明是否要将以百分号转码的
     空值作为空字符串处理。 真值表示空值应当被保留作为空字符串。 默认的
     假值表示空值会被忽略并将其视作未包括的值。

     可选参数 `strict_parsing' 是一个旗标，指明要如何处理解析错误。 如为
     假值（默认），错误会被静默地忽略。 如为真值，错误会引发 *note
     ValueError: 16d. 异常。

     可选的 `encoding' 和 `errors' 形参指定如何将以百分号编码的序列解码
     为 Unicode 字符，即作为 *note bytes.decode(): 171. 方法所接受的数据
     。

     可选参数 `max_num_fields' 是要读取的最大字段数量的。 如果设置，则如
     果读取的字段超过 `max_num_fields' 会引发 *note ValueError: 16d.。

     可选参数 `separator' 是用来分隔查询参数的符号。 默认为 ‘&’。

     使用 *note urllib.parse.urlencode(): 87a. 函数将这样的名值对列表转
     换为查询字符串。

     3.2 版更變: 增加了 `encoding' 和 `errors' 形参。

     3.8 版更變: 增加了 `max_num_fields' 形参。

     3.9.2 版更變: Added `separator' parameter with the default value of
     ‘&’.  Python versions earlier than Python 3.9.2 allowed using both
     ‘;’ and ‘&’ as query parameter separator.  This has been changed to
     allow only a single separator key, with ‘&’ as the default
     separator.

 -- 函式: urllib.parse.urlunparse (parts)

     根据 ‘urlparse()’ 所返回的元组来构造一个 URL。 `parts' 参数可以是任
     何包含六个条目的可迭代对象。 构造的结果可能是略有不同但保持等价的
     URL，如果被解析的 URL 原本包含不必要的分隔符（例如，带有空查询的
     ‘?’；RFC 已声明这是等价的）。

 -- 函式: urllib.parse.urlsplit (urlstring, scheme='',
          allow_fragments=True)

     此函数类似于 *note urlparse(): 6f1.，但不会拆分来自 URL 的参数。 此
     函数通常应当在需要允许将参数应用到 URL 的 `path' 部分的每个分节的较
     新的 URL 语法的情况下 (参见 RFC 2396(3)) 被用来代替 *note
     urlparse(): 6f1.。 需要使用一个拆分函数来拆分路径分节和参数。 此函
     数将返回包含 5 个条目的 *note named tuple: b7b.:

          (addressing scheme, network location, path, query, fragment identifier).

     返回值是一个 *note named tuple: b7b.，它的条目可以通过索引或作为命
     名属性来访问:

     属性                   索引        值                            值（如果不存在）
                                                                      
     --------------------------------------------------------------------------------------------
                                                                      
     ‘scheme’               0           URL协议                       `scheme' 参数
                                                                      
                                                                      
     ‘netloc’               1           网络位置部分                  空字符串
                                                                      
                                                                      
     ‘path’                 2           分层路径                      空字符串
                                                                      
                                                                      
     ‘query’                3           查询组件                      空字符串
                                                                      
                                                                      
     ‘fragment’             4           片段识别                      空字符串
                                                                      
                                                                      
     ‘username’                         用户名                        *note None: 203.
                                                                      
                                                                      
     ‘password’                         密码                          *note None: 203.
                                                                      
                                                                      
     ‘hostname’                         主机名（小写）                *note None: 203.
                                                                      
                                                                      
     ‘port’                             端口号为整数（如果存在）      *note None: 203.
                                                                      

     如果在 URL 中指定了无效的端口，读取 ‘port’ 属性将引发 *note
     ValueError: 16d.。 有关结果对象的更多信息请参阅 *note
     结构化解析结果: 2dff. 一节。

     在 ‘netloc’ 属性中不匹配的方括号将引发 *note ValueError: 16d.。

     如果 ‘netloc’ 属性中的字符在 NFKC 规范化下（如 IDNA 编码格式所使用
     的）被分解成 ‘/’, ‘?’, ‘#’, ‘@’ 或 ‘:’ 则将引发 *note ValueError:
     16d.。 如果在解析之前 URL 就被分解，则不会引发错误。

     依据更新 RFC 3986 的 WHATWG spec(4)，ASCII 换行符 ‘\n’, ‘\r’ 和制表
     符 ‘\t’ 等字符会从 URL 中被去除。

     3.6 版更變: 超范围的端口号现在会引发 *note ValueError: 16d.，而不是
     返回 *note None: 203.。

     3.8 版更變: 在 NFKC 规范化下会影响 netloc 解析的字符现在将引发
     *note ValueError: 16d.。

     3.9.5 版更變: ASCII 换行符和制表符会从 URL 中被去除。

 -- 函式: urllib.parse.urlunsplit (parts)

     将 *note urlsplit(): 6f0. 所返回的元组中的元素合并为一个字符串形式
     的完整 URL。 `parts' 参数可以是任何包含五个条目的可迭代对象。 其结
     果可能是略有不同但保持等价的 URL，如果被解析的 URL 原本包含不必要的
     分隔符（例如，带有空查询的 ?；RFC 已声明这是等价的）。

 -- 函式: urllib.parse.urljoin (base, url, allow_fragments=True)

     通过合并一个 "基准 URL" (`base') 和另一个 URL (`url') 来构造一个完
     整 ("absolute") URL。 在非正式情况下，这将使用基准 URL 的各部分，特
     别是地址协议、网络位置和 (一部分) 路径来提供相对 URL 中缺失的部分。
     例如:

          >>> from urllib.parse import urljoin
          >>> urljoin('http://www.cwi.nl/%7Eguido/Python.html', 'FAQ.html')
          'http://www.cwi.nl/%7Eguido/FAQ.html'

     `allow_fragments' 参数具有与 *note urlparse(): 6f1. 中的对应参数一
     致的含义与默认值。

          備註: 如果 `url' 为绝对 URL (即以 ‘//’ 或 ‘scheme://’ 打头)，
          则 `url' 的主机名和/或协议将出现在结果中。 例如:

               >>> urljoin('http://www.cwi.nl/%7Eguido/Python.html',
               ...         '//www.python.org/%7Eguido')
               'http://www.python.org/%7Eguido'

          如果你不想要那样的行为，请使用 *note urlsplit(): 6f0. 和 *note
          urlunsplit(): 2e01. 对 `url' 进行预处理，移除可能存在的
          `scheme' 和 `netloc' 部分。

     3.5 版更變: 更新行为以匹配 RFC 3986(5) 中定义的语义。

 -- 函式: urllib.parse.urldefrag (url)

     如果 `url' 包含片段标识符，则返回不带片段标识符的 `url' 修改版本。
     如果 `url' 中没有片段标识符，则返回未经修改的 `url' 和一个空字符串
     。

     返回值是一个 *note named tuple: b7b.，它的条目可以通过索引或作为命
     名属性来访问:

     属性                   索引        值                            值（如果不存在）
                                                                      
     --------------------------------------------------------------------------------------------
                                                                      
     ‘url’                  0           不带片段的 URL                空字符串
                                                                      
                                                                      
     ‘fragment’             1           片段识别                      空字符串
                                                                      

     请参阅 *note 结构化解析结果: 2dff. 一节了解有关结果对象的更多信息。

     3.2 版更變: 结果为已构造好的对象而不是一个简单的 2 元组。-tuple.

 -- 函式: urllib.parse.unwrap (url)

     从已包装的 URL (即被格式化为 ‘<URL:scheme://host/path>’,
     ‘<scheme://host/path>’, ‘URL:scheme://host/path’ 或
     ‘scheme://host/path’ 的字符串) 中提取 URL。 如果 `url' 不是一个已包
     装的 URL，它将被原样返回。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc1808.html

   (2) https://tools.ietf.org/html/rfc3986.html

   (3) https://tools.ietf.org/html/rfc2396.html

   (4) https://url.spec.whatwg.org/#concept-basic-url-parser

   (5) https://tools.ietf.org/html/rfc3986.html


File: python.info,  Node: 解析ASCII编码字节,  Next: 结构化解析结果,  Prev: URL 解析,  Up: urllib parse 用于解析 URL

5.21.8.2 解析ASCII编码字节
..........................

这些 URL 解析函数最初设计只用于操作字符串。 但在实践中，它也能够操作经过
正确转码和编码的 ASCII 字节序列形式的 URL。 相应地，此模块中的 URL 解析
函数既可以操作 *note str: 205. 对象也可以操作 *note bytes: 172. 和 *note
bytearray: 173. 对象。

如果传入 *note str: 205. 数据，结果将只包含 *note str: 205. 数据。 如果
传入 *note bytes: 172. 或 *note bytearray: 173. 数据，则结果也将只包含
*note bytes: 172. 数据。

试图在单个函数调用中混用 *note str: 205. 数据和 *note bytes: 172. 或
*note bytearray: 173. 数据将导致引发 *note TypeError: 1fe.，而试图传入非
ASCII 字节值则将引发 *note UnicodeDecodeError: 32b.。

为了支持结果对象在 *note str: 205. 和 *note bytes: 172. 之间方便地转换，
所有来自 URL 解析函数的返回值都会提供 ‘encode()’ 方法 (当结果包含 *note
str: 205. 数据) 或 ‘decode()’ 方法 (当结果包含 *note bytes: 172. 数据)。
这些方法的签名与 *note str: 205. 和 *note bytes: 172. 的对应方法相匹配
(不同之处在于其默认编码格式是 ‘'ascii'’ 而非 ‘'utf-8'’)。 每个方法会输出
包含相应类型的 *note bytes: 172. 数据 (对于 ‘encode()’ 方法) 或 *note
str: 205. 数据 (对于 ‘decode()’ 方法) 的值。

对于某些需要在有可能不正确地转码的包含非 ASCII 数据的 URL 上进行操作的应
用程序来说，在发起调用 URL 解析方法之前必须自行将字节串解码为字符。

在本节中描述的行为仅适用于 URL 解析函数。 URL 转码函数在产生和消耗字节序
列时使用它们自己的规则，详情参见单独 URL 转码函数的文档。

3.2 版更變: URL 解析函数现在接受 ASCII 编码的字节序列


File: python.info,  Node: 结构化解析结果,  Next: URL 转码,  Prev: 解析ASCII编码字节,  Up: urllib parse 用于解析 URL

5.21.8.3 结构化解析结果
.......................

*note urlparse(): 6f1, *note urlsplit(): 6f0. 和 *note urldefrag(): cac.
函数的结果对象是 *note tuple: 1a2. 类型的子类。 这些子类中增加了在那些函
数的文档中列出的属性，之前小节中描述的编码和解码支持，以及一个附加方法:

 -- 成員函式: urllib.parse.SplitResult.geturl ()

     以字符串形式返回原始 URL 的重合并版本。 这可能与原始 URL 有所不同，
     例如协议的名称可能被正规化为小写字母、空的组成部分可能被丢弃。 特别
     地，空的参数、查询和片段标识符将会被移除。

     对于 *note urldefrag(): cac. 的结果，只有空的片段标识符会被移除。 对
     于 *note urlsplit(): 6f0. 和 *note urlparse(): 6f1. 的结果，所有被
     记录的改变都会被应用到此方法所返回的 URL 上。

     如果是通过原始的解析方法传回则此方法的结果会保持不变:

          >>> 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/'

下面的类提供了当在 *note str: 205. 对象上操作时对结构化解析结果的实现:

 -- 類別: urllib.parse.DefragResult (url, fragment)

     用于 *note urldefrag(): cac. 结果的实体类，包含有 *note str: 205. 数
     据。 ‘encode()’ 方法会返回一个 *note DefragResultBytes: 2e07. 实例
     。

     3.2 版新加入.

 -- 類別: urllib.parse.ParseResult (scheme, netloc, path, params, query,
          fragment)

     用于 *note urlparse(): 6f1. 结果的实体类，包含有 *note str: 205. 数
     据。 ‘encode()’ 方法会返回一个 *note ParseResultBytes: 2e09. 实例。

 -- 類別: urllib.parse.SplitResult (scheme, netloc, path, query,
          fragment)

     用于 *note urlsplit(): 6f0. 结果的实体类，包含有 *note str: 205. 数
     据。 ‘encode()’ 方法会返回一个 *note SplitResultBytes: 2e0b. 实例。

下面的类提供了当在 *note bytes: 172. 或 *note bytearray: 173. 对象上操作
时对解析结果的实现:

 -- 類別: urllib.parse.DefragResultBytes (url, fragment)

     用于 *note urldefrag(): cac. 结果的实体类，包含有 *note bytes: 172.
     数据。 ‘decode()’ 方法会返回一个 *note DefragResult: 2e06. 实例。

     3.2 版新加入.

 -- 類別: urllib.parse.ParseResultBytes (scheme, netloc, path, params,
          query, fragment)

     用于 *note urlparse(): 6f1. 结果的实体类，包含有 *note bytes: 172.
     数据。 ‘decode()’ 方法会返回一个 *note ParseResult: 2e08. 实例。

     3.2 版新加入.

 -- 類別: urllib.parse.SplitResultBytes (scheme, netloc, path, query,
          fragment)

     用于 *note urlsplit(): 6f0. 结果的实体类，包含有 *note bytes: 172.
     数据。 ‘decode()’ 方法会返回一个 *note SplitResult: 2e0a. 实例。

     3.2 版新加入.


File: python.info,  Node: URL 转码,  Prev: 结构化解析结果,  Up: urllib parse 用于解析 URL

5.21.8.4 URL 转码
.................

URL 转码函数的功能是接收程序数据并通过对特殊字符进行转码并正确编码非
ASCII 文本来将其转为可以安全地用作 URL 组成部分的形式。 它们还支持逆转此
操作以便从作为 URL 组成部分的内容中重建原始数据，如果上述的 URL 解析函数
还未覆盖此功能的话。

 -- 函式: urllib.parse.quote (string, safe='/', encoding=None,
          errors=None)

     使用 ‘%xx’ 转义符替换 `string' 中的特殊字符。 字母、数字和 ‘'_.-~'’
     等字符一定不会被转码。 在默认情况下，此函数只对 URL 的路径部分进行
     转码。 可选的 `safe' 形参额外指定不应被转码的 ASCII 字符 — 其默认值
     为 ‘'/'’。

     `string' 可以是 *note str: 205. 或 *note bytes: 172. 对象。

     3.7 版更變: 从 RFC 2396(1) 迁移到 RFC 3986(2) 以转码 URL 字符串。
     "~" 现在已被包括在非保留字符集中。

     可选的 `encoding' 和 `errors' 形参指明如何处理非 ASCII 字符，与
     *note str.encode(): 170. 方法所接受的值一样。 `encoding' 默认为
     ‘'utf-8'’。 `errors' 默认为 ‘'strict'’，表示不受支持的字符将引发
     *note UnicodeEncodeError: 32a.。 如果 `string' 为 *note bytes: 172.
     则不可提供 `encoding' 和 `errors'，否则将引发 *note TypeError:
     1fe.。

     请注意 ‘quote(string, safe, encoding, errors)’ 等价于
     ‘quote_from_bytes(string.encode(encoding, errors), safe)’。

     例如: ‘quote('/El Niño/')’ 将产生 ‘'/El%20Ni%C3%B1o/'’.

 -- 函式: urllib.parse.quote_plus (string, safe='', encoding=None,
          errors=None)

     类似于 *note quote(): 511.，但还会使用加号来替换空格，如在构建放入
     URL 的查询字符串时对于转码 HTML 表单值时所要求的那样。 原始字符串中
     的加号会被转义，除非它们已包括在 `safe' 中。 它也不会将 `safe' 的默
     认值设为 ‘'/'’。

     例如: ‘quote_plus('/El Niño/')’ 将产生 ‘'%2FEl+Ni%C3%B1o%2F'’。

 -- 函式: urllib.parse.quote_from_bytes (bytes, safe='/')

     类似于 *note quote(): 511.，但是接受 *note bytes: 172. 对象而非
     *note str: 205.，并且不执行从字符串到字节串的编码。

     例如: ‘quote_from_bytes(b'a&\xef')’ 产生 ‘'a%26%EF'’。

 -- 函式: urllib.parse.unquote (string, encoding='utf-8',
          errors='replace')

     将 ‘%xx’ 转义符替换为其单字符等价物。 可选的 `encoding' 和 `errors'
     形参指定如何将以百分号编码的序列解码为 Unicode 字符，即 *note
     bytes.decode(): 171. 方法所接受的数据。

     `string' 可以是 *note str: 205. 或 *note bytes: 172. 对象。

     `encoding' 默认为 ‘'utf-8'’。 `errors' 默认为 ‘'replace'’，表示无效
     的序列将被替换为占位字符。

     例如: ‘unquote('/El%20Ni%C3%B1o/')’ 将产生 ‘'/El Niño/'’。

     3.9 版更變: `string' 形参支持 bytes 和 str 对象（之前仅支持 str）。

 -- 函式: urllib.parse.unquote_plus (string, encoding='utf-8',
          errors='replace')

     类似于 *note unquote(): 10db.，但还会将加号替换为空格，如反转码表单
     值所要求的。

     `string' 必须为 *note str: 205.。

     例如: ‘unquote_plus('/El+Ni%C3%B1o/')’ 将产生 ‘'/El Niño/'’。

 -- 函式: urllib.parse.unquote_to_bytes (string)

     将 ‘%xx’ 转义符替换为其单八位等价物，并返回一个 *note bytes: 172. 对
     象。

     `string' 可以是 *note str: 205. 或 *note bytes: 172. 对象。

     如果它是 *note str: 205.，则 `string' 中未转义的非 ASCII 字符会被编
     码为 UTF-8 字节串。

     例如: ‘unquote_to_bytes('a%26%EF')’ y将产生 ‘b'a&\xef'’。

 -- 函式: urllib.parse.urlencode (query, doseq=False, safe='',
          encoding=None, errors=None, quote_via=quote_plus)

     将一个包含有 *note str: 205. 或 *note bytes: 172. 对象的映射对象或
     二元组序列转换为以百分号编码的 ASCII 文本字符串。 如果所产生的字符
     串要被用作 *note urlopen(): 87b. 函数的 POST 操作的 `data'，则它应
     当被编码为字节串，否则它将导致 *note TypeError: 1fe.。

     结果字符串是一系列 ‘key=value’ 对，由 ‘'&'’ 字符进行分隔，其中
     `key' 和 `value' 都已使用 `quote_via' 函数转码。 在默认情况下，会使
     用 *note quote_plus(): cad. 来转码值，这意味着空格会被转码为 ‘'+'’
     字符而 ’/’ 字符会被转码为 ‘%2F’，即遵循 GET 请求的标准
     (‘application/x-www-form-urlencoded’)。 另一个可以作为 `quote_via'
     传入的替代函数是 *note quote(): 511.，它将把空格转码为 ‘%20’ 并且不
     编码 ’/’ 字符。 为了最大程序地控制要转码的内容，请使用 ‘quote’ 并指
     定 `safe' 的值。

     当使用二元组序列作为 `query' 参数时，每个元组的第一个元素为键而第二
     个元素为值。 值元素本身也可以为一个序列，在那种情况下，如果可选的形
     参 `doseq' 的值为 ‘True’，则每个键的值序列元素生成单个 ‘key=value’
     对（以 ‘'&'’ 分隔）。 被编码的字符串中的参数顺序将与序列中的形参元
     素顺序相匹配。

     `safe', `encoding' 和 `errors' 形参会被传递给 `quote_via'
     (`encoding' 和 `errors' 形参仅在查询元素为 *note str: 205. 时会被传
     递)。

     为了反向执行这个编码过程，此模块提供了 *note parse_qs(): 27f. 和
     *note parse_qsl(): 280. 来将查询字符串解析为 Python 数据结构。

     请参考 *note urllib 示例: 2dec. 来了解如何使用 *note
     urllib.parse.urlencode(): 87a. 方法来生成 URL 的查询字符串或 POST 请
     求的数据。

     3.2 版更變: 查询支持字节和字符串对象。

     3.5 版新加入: `quote_via' 参数.

也參考
......

WHATWG(3) - URL 现有标准

     定义 URL、域名、IP 地址、application/x-www-form-urlencoded 格式及其
     API 的工作组。

RFC 3986(4) - 统一资源标识符

     这是当前的标准 (STD66)。 任何对于 urllib.parse 模块的修改都必须遵循
     该标准。 某些偏离也可能会出现，这大都是出于向下兼容的目的以及特定的
     经常存在于各主要浏览器上的实际解析需求。

RFC 2732(5) - URL 中的 IPv6 Addresses 地址显示格式。

     这指明了 IPv6 URL 的解析要求。

RFC 2396(6) - 统一资源标识符（URI）：通用语法

     描述统一资源名称 (URN) 和统一资源定位符 (URL) 通用语义要求的文档。

RFC 2368(7) - mailto URL 模式。

     mailto URL 模式的解析要求。

RFC 1808(8) - 相对统一资源定位符

     这个请求注释包括联结绝对和相对 URL 的规则，其中包括大量控制边界情况
     处理的 "异常示例"。

RFC 1738(9) - 统一资源定位符 (URL)

     这指明了绝对 URL 的正式语义和句法。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2396.html

   (2) https://tools.ietf.org/html/rfc3986.html

   (3) https://url.spec.whatwg.org/

   (4) https://tools.ietf.org/html/rfc3986.html

   (5) https://tools.ietf.org/html/rfc2732.html

   (6) https://tools.ietf.org/html/rfc2396.html

   (7) https://tools.ietf.org/html/rfc2368.html

   (8) https://tools.ietf.org/html/rfc1808.html

   (9) https://tools.ietf.org/html/rfc1738.html


File: python.info,  Node: urllib error --- urllib request 引发的异常类,  Next: urllib robotparser --- robots txt 语法分析程序,  Prev: urllib parse 用于解析 URL,  Up: 互联网协议和支持

5.21.9 ‘urllib.error’ — urllib.request 引发的异常类
---------------------------------------------------

`源代码：' Lib/urllib/error.py(1)

__________________________________________________________________

*note urllib.error: 127. 模块为 *note urllib.request: 129. 所引发的异常
定义了异常类。 基础异常类是 *note URLError: 2d71.。

下列异常会被 *note urllib.error: 127. 按需引发：

 -- 例外: urllib.error.URLError

     处理程序在遇到问题时会引发此异常（或其派生的异常）。 它是 *note
     OSError: 304. 的一个子类。

      -- 屬性: reason

          此错误的原因。 它可以是一个消息字符串或另一个异常实例。

     3.3 版更變: *note URLError: 2d71. 已被设为 *note OSError: 304. 而不
     是 *note IOError: a73. 的子类。

 -- 例外: urllib.error.HTTPError

     虽然是一个异常（*note URLError: 2d71. 的一个子类），*note
     HTTPError: 9e2. 也可以作为一个非异常的文件类返回值（与 *note
     urlopen(): 87b. 返所回的对象相同）。 这适用于处理特殊 HTTP 错误例如
     作为认证请求的时候。

      -- 屬性: code

          一个 HTTP 状态码，具体定义见 RFC 2616(2)。 这个数字的值对应于
          存放在 *note http.server.BaseHTTPRequestHandler.responses:
          2e15. 代码字典中的某个值。

      -- 屬性: reason

          这通常是一个解释本次错误原因的字符串。

      -- 屬性: headers

          导致 *note HTTPError: 9e2. 的特定 HTTP 请求的 HTTP 响应头。

          3.4 版新加入.

 -- 例外: urllib.error.ContentTooShortError (msg, content)

     此异常会在 *note urlretrieve(): 2dee. 函数检测到已下载的数据量小于
     期待的数据量（由 `Content-Length' 头给定）时被引发。 ‘content’ 属性
     中将存放已下载（可能被截断）的数据。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/urllib/error.py

   (2) https://tools.ietf.org/html/rfc2616.html


File: python.info,  Node: urllib robotparser --- robots txt 语法分析程序,  Next: http --- HTTP 模块,  Prev: urllib error --- urllib request 引发的异常类,  Up: 互联网协议和支持

5.21.10 ‘urllib.robotparser’ — robots.txt 语法分析程序
------------------------------------------------------

`源代码：' Lib/urllib/robotparser.py(1)

__________________________________________________________________

此模块提供了一个单独的类 *note RobotFileParser: 6a4.，它可以回答关于某个
特定用户代理是否能在 Web 站点获取发布 ‘robots.txt’ 文件的 URL 的问题。 有
关 ‘robots.txt’ 文件结构的更多细节请参阅
‘http://www.robotstxt.org/orig.html’。

 -- 類別: urllib.robotparser.RobotFileParser (url='')

     这个类提供了一些可以读取、解析和回答关于 `url' 上的 ‘robots.txt’ 文
     件的问题的方法。

      -- 成員函式: set_url (url)

          设置指向 ‘robots.txt’ 文件的 URL。

      -- 成員函式: read ()

          读取 ‘robots.txt’ URL 并将其输入解析器。

      -- 成員函式: parse (lines)

          解析行参数。

      -- 成員函式: can_fetch (useragent, url)

          如果允许 `useragent' 按照被解析 ‘robots.txt’ 文件中的规则来获
          取 `url' 则返回 ‘True’。

      -- 成員函式: mtime ()

          返回最近一次获取 ‘robots.txt’ 文件的时间。 这适用于需要定期检
          查 ‘robots.txt’ 文件更新情况的长时间运行的网页爬虫。

      -- 成員函式: modified ()

          将最近一次获取 ‘robots.txt’ 文件的时间设置为当前时间。

      -- 成員函式: crawl_delay (useragent)

          为指定的 `useragent' 从 ‘robots.txt’ 返回 ‘Crawl-delay’ 形参。
          如果此形参不存在或不适用于指定的 `useragent' 或者此形参的
          ‘robots.txt’ 条目存在语法错误，则返回 ‘None’。

          3.6 版新加入.

      -- 成員函式: request_rate (useragent)

          以 *note named tuple: b7b. ‘RequestRate(requests, seconds)’ 的
          形式从 ‘robots.txt’ 返回 ‘Request-rate’ 形参的内容。 如果此形
          参不存在或不适用于指定的 `useragent' 或者此形参的 ‘robots.txt’
          条目存在语法错误，则返回 ‘None’。

          3.6 版新加入.

      -- 成員函式: site_maps ()

          以 *note list(): 1f8. 的形式从 ‘robots.txt’ 返回 ‘Sitemap’ 形
          参的内容。 如果此形参不存在或者此形参的 ‘robots.txt’ 条目存在
          语法错误，则返回 ‘None’。

          3.8 版新加入.

下面的例子演示了 *note RobotFileParser: 6a4. 类的基本用法:

     >>> 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

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/Lib/urllib/robotparser.py


File: python.info,  Node: http --- HTTP 模块,  Next: http client --- HTTP 协议客户端,  Prev: urllib robotparser --- robots txt 语法分析程序,  Up: 互联网协议和支持

5.21.11 ‘http’ — HTTP 模块
--------------------------

`源代码:' Lib/http/__init__.py(1)

__________________________________________________________________

*note http: 92. 是一个包，它收集了多个用于处理超文本传输协议的模块:

   * *note http.client: 93. 是一个低层级的 HTTP 协议客户端；对于高层级的
     URL 访问请使用 *note urllib.request: 129.

   * *note http.server: 96. 包含基于 *note socketserver: f0. 的基本 HTTP
     服务类

   * *note http.cookies: 95. 包含一些有用来实现通过 cookies 进行状态管理
     的工具

   * *note http.cookiejar: 94. 提供了 cookies 的持久化

*note http: 92. 也是一个通过 *note http.HTTPStatus: 1ac. 枚举定义了一些
HTTP 状态码以及相关联消息的模块

 -- 類別: http.HTTPStatus

     3.5 版新加入.

     *note enum.IntEnum: 684. 的子类，它定义了组 HTTP 状态码，原理短语以
     及用英语书写的长描述文本。

     用法:

          >>> 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>, ...]

* Menu:

* HTTP 状态码::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/http/__init__.py


File: python.info,  Node: HTTP 状态码,  Up: http --- HTTP 模块

5.21.11.1 HTTP 状态码
.....................

已支持并且已在 *note http.HTTPStatus: 1ac. IANA 注册(1) 的状态码有：

状态码      映射名                                  详情
                                                    
----------------------------------------------------------------------------------------------------------------------------------------
                                                    
‘100’       ‘CONTINUE’                              HTTP/1.1 RFC 7231(2), 6.2.1 节
                                                    
                                                    
‘101’       ‘SWITCHING_PROTOCOLS’                   HTTP/1.1 RFC 7231, 6.2.2 节
                                                    
                                                    
‘102’       ‘PROCESSING’                            WebDAV RFC 2518, 10.1 节
                                                    
                                                    
‘103’       ‘EARLY_HINTS’                           用于指定提示 RFC 8297(3) 的 HTTP 状态码
                                                    
                                                    
‘200’       ‘OK’                                    HTTP/1.1 RFC 7231, 6.3.1 节
                                                    
                                                    
‘201’       ‘CREATED’                               HTTP/1.1 RFC 7231, 6.3.2 节
                                                    
                                                    
‘202’       ‘ACCEPTED’                              HTTP/1.1 RFC 7231, 6.3.3 节
                                                    
                                                    
‘203’       ‘NON_AUTHORITATIVE_INFORMATION’         HTTP/1.1 RFC 7231, 6.3.4 节
                                                    
                                                    
‘204’       ‘NO_CONTENT’                            HTTP/1.1 RFC 7231, 6.3.5 节
                                                    
                                                    
‘205’       ‘RESET_CONTENT’                         HTTP/1.1 RFC 7231, 6.3.6 节
                                                    
                                                    
‘206’       ‘PARTIAL_CONTENT’                       HTTP/1.1 RFC 7233, 4.1 节
                                                    
                                                    
‘207’       ‘MULTI_STATUS’                          WebDAV RFC 4918, 11.1 节
                                                    
                                                    
‘208’       ‘ALREADY_REPORTED’                      WebDAV Binding Extensions RFC 5842, 7.1 节（实验性）
                                                    
                                                    
‘226’       ‘IM_USED’                               Delta Encoding in HTTP RFC 3229, 10.4.1 节
                                                    
                                                    
‘300’       ‘MULTIPLE_CHOICES’：有多种资源可选择    HTTP/1.1 RFC 7231, 6.4.1 节
                                                    
                                                    
‘301’       ‘MOVED_PERMANENTLY’：永久移动           HTTP/1.1 RFC 7231, 6.4.2 节
                                                    
                                                    
‘302’       ‘FOUND’：临时移动                       HTTP/1.1 RFC 7231, 6.4.3 节
                                                    
                                                    
‘303’       ‘SEE_OTHER’：已经移动                   HTTP/1.1 RFC 7231, 6.4.4 节
                                                    
                                                    
‘304’       ‘NOT_MODIFIED’：没有修改                HTTP/1.1 RFC 7232, 4.1 节
                                                    
                                                    
‘305’       ‘USE_PROXY’：使用代理                   HTTP/1.1 RFC 7231, 6.4.5 节
                                                    
                                                    
‘307’       ‘TEMPORARY_REDIRECT’：临时重定向        HTTP/1.1 RFC 7231(4), 6.4.7 节
                                                    
                                                    
‘308’       ‘PERMANENT_REDIRECT’：永久重定向        Permanent Redirect RFC 7238(5), Section 3 (Experimental)
                                                    
                                                    
‘400’       ‘BAD_REQUEST’：错误请求                 HTTP/1.1 RFC 7231, 6.5.1 节
                                                    
                                                    
‘401’       ‘UNAUTHORIZED’：未授权                  HTTP/1.1 Authentication RFC 7235, 3.1 节
                                                    
                                                    
‘402’       ‘PAYMENT_REQUIRED’：保留，将来使用      HTTP/1.1 RFC 7231, 6.5.2 节
                                                    
                                                    
‘403’       ‘FORBIDDEN’：禁止                       HTTP/1.1 RFC 7231, 6.5.3 节
                                                    
                                                    
‘404’       ‘NOT_FOUND’：没有找到                   HTTP/1.1 RFC 7231, 6.5.4 节
                                                    
                                                    
‘405’       ‘METHOD_NOT_ALLOWED’：该请求方法不允    HTTP/1.1 RFC 7231, 6.5.5 节
            许                                      
            
                                                    
‘406’       ‘NOT_ACCEPTABLE’：不可接受              HTTP/1.1 RFC 7231, 6.5.6 节
                                                    
                                                    
‘407’       ‘PROXY_AUTHENTICATION_REQUIRED’：要求   HTTP/1.1 Authentication RFC 7235, 3.1 节
            使用代理验证身份                        
            
                                                    
‘408’       ‘REQUEST_TIMEOUT’：请求超时             HTTP/1.1 RFC 7231(6), 6.5.7 节
                                                    
                                                    
‘409’       ‘CONFLICT’：冲突                        HTTP/1.1 RFC 7231, 6.5.8 节
                                                    
                                                    
‘410’       ‘GONE’：已经不在了                      HTTP/1.1 RFC 7231, 6.5.9 节
                                                    
                                                    
‘411’       ‘LENGTH_REQUIRED’：长度要求             HTTP/1.1 RFC 7231, 6.5.10 节
                                                    
                                                    
‘412’       ‘PRECONDITION_FAILED’：前提条件错误     HTTP/1.1 RFC 7232, 4.2 节
                                                    
                                                    
‘413’       ‘REQUEST_ENTITY_TOO_LARGE’：请求体太    HTTP/1.1 RFC 7231, 6.5.11 节
            大了                                    
            
                                                    
‘414’       ‘REQUEST_URI_TOO_LONG’：请求URI太长了   HTTP/1.1 RFC 7231, 6.5.12 节
                                                    
                                                    
‘415’       ‘UNSUPPORTED_MEDIA_TYPE’：不支持的媒    HTTP/1.1 RFC 7231, 6.5.13 节
            体格式                                  
            
                                                    
‘416’       ‘REQUESTED_RANGE_NOT_SATISFIABLE’       HTTP/1.1 Range Requests RFC 7233, 4.4 节
                                                    
                                                    
‘417’       ‘EXPECTATION_FAILED’：期望失败          HTTP/1.1 RFC 7231, 6.5.14 节
                                                    
                                                    
‘418’       ‘IM_A_TEAPOT’                           HTCPCP/1.0 RFC 2324(7), Section 2.3.2
                                                    
                                                    
‘421’       ‘MISDIRECTED_REQUEST’                   HTTP/2 RFC 7540(8), 9.1.2 节
                                                    
                                                    
‘422’       ‘UNPROCESSABLE_ENTITY’：可加工实体      WebDAV RFC 4918, 11.2 节
                                                    
                                                    
‘423’       ‘LOCKED’：锁着                          WebDAV RFC 4918, 11.3 节
                                                    
                                                    
‘424’       ‘FAILED_DEPENDENCY’：失败的依赖         WebDAV RFC 4918, 11.4 节
                                                    
                                                    
‘425’       ‘TOO_EARLY’                             使用 HTTP RFC 8470(9) 中的早期数据
                                                    
                                                    
‘426’       ‘UPGRADE_REQUIRED’：升级需要            HTTP/1.1 RFC 7231, 6.5.15 节
                                                    
                                                    
‘428’       ‘PRECONDITION_REQUIRED’：先决条件要求   Additional HTTP Status Codes RFC 6585
                                                    
                                                    
‘429’       ‘TOO_MANY_REQUESTS’：太多的请求         Additional HTTP Status Codes RFC 6585
                                                    
                                                    
‘431’       ‘REQUEST_HEADER_FIELDS_TOO_LARGE’：请   Additional HTTP Status Codes RFC 6585
            求头太大                                
            
                                                    
‘451’       ‘UNAVAILABLE_FOR_LEGAL_REASONS’         HTTP 状态码用于报告法律障碍 RFC 7725(10)
                                                    
                                                    
‘500’       ‘INTERNAL_SERVER_ERROR’：内部服务错误   HTTP/1.1 RFC 7231, 6.6.1 节
                                                    
                                                    
‘501’       ‘NOT_IMPLEMENTED’：不可执行             HTTP/1.1 RFC 7231, 6.6.2 节
                                                    
                                                    
‘502’       ‘BAD_GATEWAY’：无效网关                 HTTP/1.1 RFC 7231, 6.6.3 节
                                                    
                                                    
‘503’       ‘SERVICE_UNAVAILABLE’：服务不可用       HTTP/1.1 RFC 7231, 6.6.4 节
                                                    
                                                    
‘504’       ‘GATEWAY_TIMEOUT’：网关超时             HTTP/1.1 RFC 7231, 6.6.5 节
                                                    
                                                    
‘505’       ‘HTTP_VERSION_NOT_SUPPORTED’：HTTP版    HTTP/1.1 RFC 7231, 6.6.6 节
            本不支持                                
            
                                                    
‘506’       ‘VARIANT_ALSO_NEGOTIATES’：服务器存在   透明内容协商在： HTTP RFC 2295(11), 8.1 节（实验性）
            内部配置错误                            
            
                                                    
‘507’       ‘INSUFFICIENT_STORAGE’：存储不足        WebDAV RFC 4918, 11.5 节
                                                    
                                                    
‘508’       ‘LOOP_DETECTED’：循环检测               WebDAV Binding Extensions RFC 5842, 7.2 节（实验性）
                                                    
                                                    
‘510’       ‘NOT_EXTENDED’：不扩展                  WebDAV Binding Extensions RFC 5842, 7.2 节（实验性）
                                                    
                                                    
‘511’       ‘NETWORK_AUTHENTICATION_REQUIRED’：要   Additional HTTP Status Codes RFC 6585(12), 6 节
            求网络身份验证                          
            

为了保持向后兼容性，枚举值也以常量形式出现在 *note http.client: 93. 模块
中，。 枚举名等于常量名 (例如 ‘http.HTTPStatus.OK’ 也可以是
‘http.client.OK’)。

3.7 版更變: 添加了 ‘421 MISDIRECTED_REQUEST’ 状态码。

3.8 版新加入: 添加了 ‘451 UNAVAILABLE_FOR_LEGAL_REASONS’ 状态码。

3.9 版新加入: 增加了 ‘103 EARLY_HINTS’, ‘418 IM_A_TEAPOT’ 和 ‘425
TOO_EARLY’ 状态码

   ---------- Footnotes ----------

   (1) 
https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml

   (2) https://tools.ietf.org/html/rfc7231.html

   (3) https://tools.ietf.org/html/rfc8297.html

   (4) https://tools.ietf.org/html/rfc7231.html

   (5) https://tools.ietf.org/html/rfc7238.html

   (6) https://tools.ietf.org/html/rfc7231.html

   (7) https://tools.ietf.org/html/rfc2324.html

   (8) https://tools.ietf.org/html/rfc7540.html

   (9) https://tools.ietf.org/html/rfc8470.html

   (10) https://tools.ietf.org/html/rfc7725.html

   (11) https://tools.ietf.org/html/rfc2295.html

   (12) https://tools.ietf.org/html/rfc6585.html


File: python.info,  Node: http client --- HTTP 协议客户端,  Next: ftplib --- FTP 协议客户端,  Prev: http --- HTTP 模块,  Up: 互联网协议和支持

5.21.12 ‘http.client’ — HTTP 协议客户端
---------------------------------------

`源代码：' Lib/http/client.py(1)

__________________________________________________________________

这个模块定义了实现 HTTP 和 HTTPS 协议客户端的类。 它通常不直接使用 — 模
块 *note urllib.request: 129. 用它来处理使用 HTTP 和 HTTPS 的 URL。

也參考
......

对于更高级别的 HTTP 客户端接口，建议使用 Requests(2) 。

     備註: HTTPS 支持仅在编译 Python 时启用了 SSL 支持的情况下（通过
     *note ssl: f3. 模块）可用。

该模块支持以下类：

 -- 類別: http.client.HTTPConnection (host, port=None[, timeout],
          source_address=None, blocksize=8192)

     *note HTTPConnection: 498. 的实例代表与 HTTP 的一个连接事务。 它的
     实例化应当传入一个主机和可选的端口号。 如果没有传入端口号，如果主机
     字符串的形式为 ‘主机:端口’ 则会从中提取端口，否则将使用默认的 HTTP
     端口（80）。 如果给出了可选的 `timeout' 参数，则阻塞操作（例如连接
     尝试）将在指定的秒数之后超时（如果未给出，则使用全局默认超时设置）
     。 可选的 `source_address' 参数可以为一个 (主机, 端口) 元组，用作进
     行 HTTP 连接的源地址。 可选的 `blocksize' 参数可以字节为单位设置缓
     冲区的大小，用来发送文件类消息体。

     举个例子，以下调用都是创建连接到同一主机和端口的服务器的实例：

          >>> 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)

     3.2 版更變: 添加了 `source_address'。

     3.4 版更變: 删除了 `strict' 参数，不再支持 HTTP 0.9 风格的“简单响应
     ”。

     3.7 版更變: 添加了 `blocksize' 参数。

 -- 類別: http.client.HTTPSConnection (host, port=None, key_file=None,
          cert_file=None[, timeout], source_address=None, *,
          context=None, check_hostname=None, blocksize=8192)

     *note HTTPConnection: 498. 的子类，使用 SSL 与安全服务器进行通信。
     默认端口为 ‘443’。 如果指定了 `context'，它必须为一个描述 SSL 各选
     项的 *note ssl.SSLContext: 4e9. 实例。

     请参阅 *note 安全考量: 26fd. 了解有关最佳实践的更多信息。

     3.2 版更變: 添加了 `source_address', `context' 和 `check_hostname'。

     3.2 版更變: 这个类目前会在可能的情况下（即如果 *note ssl.HAS_SNI:
     2827. 为真值）支持 HTTPS 虚拟主机。

     3.4 版更變: 删除了 `strict' 参数，不再支持 HTTP 0.9 风格的“简单响应
     ”。

     3.4.3 版更變: 目前这个类在默认情况下会执行所有必要的证书和主机检查
     。 要回复到先前的非验证行为，可以将
     ‘ssl._create_unverified_context()’ 传递给 `context' 参数。

     3.8 版更變: 该类现在对于默认的 `context' 或在传入 `cert_file' 并附
     带自定义 `context' 时会启用 TLS 1.3 *note
     ssl.SSLContext.post_handshake_auth: 351.。

     3.6 版後已棄用: `key_file' 和 `cert_file' 已弃用并转而推荐
     `context'。 请改用 *note ssl.SSLContext.load_cert_chain(): b69. 或
     让 *note ssl.create_default_context(): 9a7. 为你选择系统所信任的 CA
     证书。

     `check_hostname' 参数也已弃用；应当改用 `context' 的 *note
     ssl.SSLContext.check_hostname: 2812. 属性。

 -- 類別: http.client.HTTPResponse (sock, debuglevel=0, method=None,
          url=None)

     在成功连接后返回类的实例，而不是由用户直接实例化。

     3.4 版更變: 删除了 `strict' 参数，不再支持HTTP 0.9 风格的“简单响应
     ”。

这个模块定义了以下函数：

 -- 函式: http.client.parse_headers (fp)

     从文件指针 `fp' 中解析头部信息，该文件代表 HTTP 请求/响应。该文件必
     须是 ‘BufferedIOBase’ reader 对象（即不是文本），并且必须提供符合
     RFC 2822(3) 格式的头部。

     该函数返回 ‘http.client.HTTPMessage’ 的实例，带有头部各个字段，但不
     带正文数据（与 *note HTTPResponse.msg: 2e27. 和 *note
     http.server.BaseHTTPRequestHandler.headers: 2e28. 一样）。返回之后
     ，文件指针 `fp' 已为读取 HTTP 正文做好准备了。

          備註: *note parse_headers(): 1176. 不会解析 HTTP 消息的开始行
          ；只会解析各 ‘Name: value’ 行。文件必须为读取这些字段做好准备
          ，所以在调用该函数之前，第一行应该已经被读取过了。

下列异常可以适当地被引发:

 -- 例外: http.client.HTTPException

     此模块中其他异常的基类。 它是 *note Exception: 2dc. 的一个子类。

 -- 例外: http.client.NotConnected

     *note HTTPException: 2e29. 的一个子类。

 -- 例外: http.client.InvalidURL

     *note HTTPException: 2e29. 的一个子类，如果给出了一个非数字或为空值
     的端口就会被引发。

 -- 例外: http.client.UnknownProtocol

     *note HTTPException: 2e29. 的一个子类。

 -- 例外: http.client.UnknownTransferEncoding

     *note HTTPException: 2e29. 的一个子类。

 -- 例外: http.client.UnimplementedFileMode

     *note HTTPException: 2e29. 的一个子类。

 -- 例外: http.client.IncompleteRead

     *note HTTPException: 2e29. 的一个子类。

 -- 例外: http.client.ImproperConnectionState

     *note HTTPException: 2e29. 的一个子类。

 -- 例外: http.client.CannotSendRequest

     *note ImproperConnectionState: 2e30. 的一个子类。

 -- 例外: http.client.CannotSendHeader

     *note ImproperConnectionState: 2e30. 的一个子类。

 -- 例外: http.client.ResponseNotReady

     *note ImproperConnectionState: 2e30. 的一个子类。

 -- 例外: http.client.BadStatusLine

     *note HTTPException: 2e29. 的一个子类。 如果服务器反馈了一个我们不
     理解的 HTTP 状态码就会被引发。

 -- 例外: http.client.LineTooLong

     *note HTTPException: 2e29. 的一个子类。 如果在 HTTP 协议中从服务器
     接收到过长的行就会被引发。

 -- 例外: http.client.RemoteDisconnected

     *note ConnectionResetError: a81. 和 *note BadStatusLine: 2e34. 的一
     个子类。 当尝试读取响应时的结果是未从连接读取到数据时由 *note
     HTTPConnection.getresponse(): 7d5. 引发，表明远端已关闭连接。

     3.5 版新加入: 在此之前引发的异常为 *note BadStatusLine:
     2e34.‘('')’。

此模块中定义的常量为：

 -- Data: http.client.HTTP_PORT

     HTTP 协议默认的端口号 (总是 ‘80’)。

 -- Data: http.client.HTTPS_PORT

     HTTPS 协议默认的端口号 (总是 ‘443’)。

 -- Data: http.client.responses

     这个字典把 HTTP 1.1 状态码映射到 W3C 名称。

     例如：‘http.client.responses[http.client.NOT_FOUND]’ 是 ‘'NOT
     FOUND’ （未发现）。

本模块中可用的 HTTP 状态码常量可以参见 *note HTTP 状态码: 2e23. 。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/http/client.py

   (2) https://requests.readthedocs.io/en/master/

   (3) https://tools.ietf.org/html/rfc2822.html


File: python.info,  Node: HTTPConnection 对象,  Next: HTTPResponse 对象,  Up: http client --- HTTP 协议客户端

5.21.12.1 HTTPConnection 对象
.............................

*note HTTPConnection: 498. 实例拥有以下方法：

 -- 成員函式: HTTPConnection.request (method, url, body=None,
          headers={}, *, encode_chunked=False)

     这会使用 HTTP 请求方法 `method' 和选择器 `url' 向服务器发送请求。

     如果给定 `body'，那么给定的数据会在信息头完成之后发送。它可能是一个
     *note str: 205. 、一个 *note bytes-like object: 6df. 、一个打开的
     *note file object: c14.，或者 *note bytes: 172. 迭代器。如果 `body'
     是字符串，它会按 HTTP 默认的 ISO-8859-1 编码；如果是一个字节类对象
     ，它会按原样发送；如果是 *note file object: c14. ，文件的内容会被发
     送，这个文件对象应该支持 ‘read()’ 方法。如果这个文件对象是一个
     *note io.TextIOBase: d01. 实例， ‘read()’ 方法返回的数据会按
     ISO-8859-1 编码，否则 ‘read()’ 方法返回的数据会按原样发送；如果
     `body' 是一个迭代器，迭代器中的元素会被发送，直到迭代器耗尽。

     `headers' 参数应是额外的随请求发送的 HTTP 信息头的字典。

     如果 `headers' 既不包含 Content-Length 也没有 Transfer-Encoding，但
     存在请求正文，那么这些头字段中的一个会自动设定。如果 `body' 是
     ‘None’，那么对于要求正文的方法 (‘PUT’，‘POST’，和 ‘PATCH’)，
     Content-Length 头会被设为 ‘0’。如果 `body' 是字符串或者类似字节的对
     象，并且也不是 *note 文件: c14.，Content-Length 头会设为正文的长度
     。任何其他类型的 `body' （一般是文件或迭代器）会按块编码，这时会自
     动设定 Transfer-Encoding 头以代替 Content-Length。

     在 `headers' 中指定 Transfer-Encoding 时， `encode_chunked' 是唯一
     相关的参数。如果 `encode_chunked' 为 ‘False’，HTTPConnection 对象会
     假定所有的编码都由调用代码处理。如果为 ‘True’，正文会按块编码。

          備註: HTTP 协议在 1.1 版中添加了块传输编码。除非明确知道 HTTP
          服务器可以处理 HTTP 1.1，调用者要么必须指定 Content-Length，要
          么必须传入 *note str: 205. 或字节类对象，注意该对象不能是表达
          body 的文件。

     3.2 版新加入: `body' 现在可以是可迭代对象了。

     3.6 版更變: 如果 Content-Length 和 Transfer-Encoding 都没有在
     `headers' 中设置，文件和可迭代的 `body' 对象现在会按块编码。添加了
     `encode_chunked' 参数。不会尝试去确定文件对象的 Content-Length。

 -- 成員函式: HTTPConnection.getresponse ()

     应当在发送一个请求从服务器获取响应时被调用。 返回一个 *note
     HTTPResponse: aef. 的实例。

          備註: 请注意你必须在读取了整个响应之后才能向服务器发送新的请求
          。

     3.5 版更變: 如果引发了 *note ConnectionError: 7d7. 或其子类， *note
     HTTPConnection: 498. 对象将在发送新的请求时准备好重新连接。

 -- 成員函式: HTTPConnection.set_debuglevel (level)

     设置调试等级。 默认的调试等级为 ‘0’，意味着不会打印调试输出。 任何
     大于 ‘0’ 的值将使得所有当前定义的调试输出被打印到 stdout。
     ‘debuglevel’ 会被传给任何新创建的 *note HTTPResponse: aef. 对象。

     3.1 版新加入.

 -- 成員函式: HTTPConnection.set_tunnel (host, port=None, headers=None)

     为 HTTP 连接隧道设置主机和端口。 这将允许通过代理服务器运行连接。

     host 和 port 参数指明隧道连接的位置（即 CONNECT 请求所包含的地址，
     而 `不是' 代理服务器的地址）。

     headers 参数应为一个随 CONNECT 请求发送的额外 HTTP 标头的映射。

     例如，要通过一个运行于本机 8080 端口的 HTTPS 代理服务器隧道，我们应
     当向 *note HTTPSConnection: 499. 构造器传入代理的地址，并将我们最终
     想要访问的主机地址传给 *note set_tunnel(): c7d. 方法:

          >>> import http.client
          >>> conn = http.client.HTTPSConnection("localhost", 8080)
          >>> conn.set_tunnel("www.python.org")
          >>> conn.request("HEAD","/index.html")

     3.2 版新加入.

 -- 成員函式: HTTPConnection.connect ()

     当对象被创建后连接到指定的服务器。 默认情况下，如果客户端还未建立连
     接，此函数会在发送请求时自动被调用。

 -- 成員函式: HTTPConnection.close ()

     关闭到服务器的连接。

 -- 屬性: HTTPConnection.blocksize

     用于发送文件类消息体的缓冲区大小。

     3.7 版新加入.

作为对使用上述 ‘request()’ 方法的替代同，你也可以通过使用下面的四个函数
，分步骤发送请的请求。

 -- 成員函式: HTTPConnection.putrequest (method, url, skip_host=False,
          skip_accept_encoding=False)

     应为连接服务器之后首先调用的函数。将向服务器发送一行数据，包含
     `method' 字符串、`url' 字符串和 HTTP 版本（‘HTTP/1.1’）。若要禁止自
     动发送 ‘Host:’ 或 ‘Accept-Encoding:’ 头部信息（比如需要接受其他编码
     格式的内容），请将 `skip_host' 或 `skip_accept_encoding' 设为非
     False 值。

 -- 成員函式: HTTPConnection.putheader (header, argument[, ...])

     向服务器发送一个 RFC 822(1) 格式的头部。将向服务器发送一行由头、冒
     号和空格以及第一个参数组成的数据。 如果还给出了其他参数，将在后续行
     中发送，每行由一个制表符和一个参数组成。

 -- 成員函式: HTTPConnection.endheaders (message_body=None, *,
          encode_chunked=False)

     向服务器发送一个空行，表示头部文件结束。可选的 `message_body' 参数
     可用于传入一个与请求相关的消息体。

     如果 `encode_chunked' 为 ‘True’，则对 `message_body' 的每次迭代结果
     将依照 RFC 7230(2) 3.3.1 节的规范进行分块编码。数据如何编码取决于
     `message_body' 的类型。 如果 `message_body' 实现了 *note buffer
     接口: 171c.，编码将生成一个数据块。如果 `message_body' 是 *note
     collections.abc.Iterable: 1818.，则 `message_body' 的每次迭代都会产
     生一个块。 如果 `message_body' 为 *note file object: c14.，那么每次
     调用 ‘.read()’ 都会产生一个数据块。在 `message_body' 结束后，本方法
     立即会自动标记块编码数据的结束。

          備註: 由于分块编码的规范要求，迭代器本身产生的空块将被分块编码
          器忽略。这是为了避免目标服务器因错误编码而过早终止对请求的读取
          。

     3.6 版新加入: 支持分块编码。加入了 `encode_chunked' 参数。

 -- 成員函式: HTTPConnection.send (data)

     发送数据到服务器。本函数只应在调用 *note endheaders(): 64a. 方法之
     后且调用 *note getresponse(): 7d5. 之前直接调用。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc822.html

   (2) https://tools.ietf.org/html/rfc7230.html


File: python.info,  Node: HTTPResponse 对象,  Next: 示例<34>,  Prev: HTTPConnection 对象,  Up: http client --- HTTP 协议客户端

5.21.12.2 HTTPResponse 对象
...........................

*note HTTPResponse: aef. 实例封装了来自服务器的 HTTP 响应。通过它可以访
问请求头和响应体。响应是可迭代对象，可在 with 语句中使用。

3.5 版更變: 现在已实现了 *note io.BufferedIOBase: 67f. 接口，并且支持所
有的读取操作。

 -- 成員函式: HTTPResponse.read ([amt])

     读取并返回响应体，或后续 `amt' 个字节。

 -- 成員函式: HTTPResponse.readinto (b)

     读取响应体的后续 len(b) 个字节到缓冲区 `b'。返回读取的字节数。

     3.3 版新加入.

 -- 成員函式: HTTPResponse.getheader (name, default=None)

     返回头部信息中的 `name' 值，如果没有与 `name' 匹配的字段，则返回
     *default*。如果名为 `name' 的字段不止一个，则返回所有字段，中间用
     ’, ’ 连接。 如果 ’default’ 不是单个字符串，而是其他可迭代对象，则其
     元素同样以逗号连接并返回。

 -- 成員函式: HTTPResponse.getheaders ()

     返回 (header, value) 元组构成的列表。

 -- 成員函式: HTTPResponse.fileno ()

     返回底层套接字的 ‘fileno’。

 -- 屬性: HTTPResponse.msg

     包含响应头的 ‘http.client.HTTPMessage’ 实例。
     ‘http.client.HTTPMessage’ 是 *note email.message: 70. 的子类。

 -- 屬性: HTTPResponse.version

     服务器使用的 HTTP 协议版本。10 代表 HTTP/1.0，11 代表 HTTP/1.1。

 -- 屬性: HTTPResponse.url

     已读取资源的 URL，通常用于确定是否进行了重定向。

 -- 屬性: HTTPResponse.headers

     响应的头部信息，形式为 *note email.message.EmailMessage: 63c. 的实
     例。

 -- 屬性: HTTPResponse.status

     由服务器返回的状态码。

 -- 屬性: HTTPResponse.reason

     服务器返回的原因短语。

 -- 屬性: HTTPResponse.debuglevel

     一个调试钩子。如果 *note debuglevel: 2e4c. 大于零，状态信息将在读取
     和解析响应数据时打印输出到 stdout。

 -- 屬性: HTTPResponse.closed

     如果流被关闭，则为‘‘True‘‘。

 -- 成員函式: HTTPResponse.geturl ()

     3.9 版後已棄用: 已弃用，建议用 *note url: 2e49.。

 -- 成員函式: HTTPResponse.info ()

     3.9 版後已棄用: 已弃用，建议用 *note headers: 2e4a.。

 -- 成員函式: HTTPResponse.getstatus ()

     3.9 版後已棄用: 已弃用，建议用 *note status: 2e4b. 。


File: python.info,  Node: 示例<34>,  Next: HTTPMessage 对象,  Prev: HTTPResponse 对象,  Up: http client --- HTTP 协议客户端

5.21.12.3 示例
..............

下面是使用 ‘GET’ 方法的会话示例：

     >>> 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()

以下是使用 ‘HEAD’ 方法的会话示例。 请注意，‘HEAD’ 方法从不返回任何数据。

     >>> 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''
     True

下面是用 ‘POST’ 发送请求的会话示例：

     >>> 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()

在客户端， ‘HTTP PUT’ 请求与 ‘POST’ 请求非常相似。区别只在于服务器端，
HTTP 服务器将允许通过 ‘PUT’ 请求创建资源。应该注意的是，自定义的 HTTP 方
法也可以在 *note urllib.request.Request: 9dc. 中通过设置适当的方法属性来
进行处理。下面是一个会话示例，演示了如何利用 http.client 发送 ‘PUT’ 请求
。

     >>> # 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


File: python.info,  Node: HTTPMessage 对象,  Prev: 示例<34>,  Up: http client --- HTTP 协议客户端

5.21.12.4 HTTPMessage 对象
..........................

‘http.client.HTTPMessage’ 的实例存有 HTTP 响应的头部信息。利用 *note
email.message.Message: 63b. 类实现。


File: python.info,  Node: ftplib --- FTP 协议客户端,  Next: poplib --- POP3 协议客户端,  Prev: http client --- HTTP 协议客户端,  Up: 互联网协议和支持

5.21.13 ‘ftplib’ — FTP 协议客户端
---------------------------------

`源代码：' Lib/ftplib.py(1)

__________________________________________________________________

本模块定义了 *note FTP: 1a6. 类和一些相关项目。*note FTP: 1a6. 类实现了
FTP 协议的客户端。可以用该类编写 Python 程序，执行各种自动化的 FTP 任务
，如镜像其他 FTP 服务器。*note urllib.request: 129. 模块也用它来处理使用
了 FTP 的 URL。关于 FTP（文件传输协议）的详情请参阅 Internet RFC 959(2)。

默认编码为 UTF-8，遵循 RFC 2640(3)。

以下是使用 *note ftplib: 82. 模块的会话示例:

     >>> 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.'

这个模块定义了以下内容：

 -- 類別: ftplib.FTP (host='', user='', passwd='', acct='',
          timeout=None, source_address=None, *, encoding='utf-8')

     返回一个 *note FTP: 1a6. 类的新实例。当传入 `host' 时，将调用
     ‘connect(host)’ 方法。当传入 `user' 时，将额外调用 ‘login(user,
     passwd, acct)’ 方法（其中 `passwd' 和 `acct' 若没有传入则默认为空字
     符串）。可选参数 `timeout' 指定阻塞操作（如连接尝试）的超时（以秒为
     单位，如果未指定超时，将使用全局默认超时设置）。`source_address' 是
     一个 2 元组 ‘(host, port)’，套接字在连接前绑定它，作为其源地址。
     `encoding' 参数指定目录和文件名的编码。

     *note FTP: 1a6. 类支持 *note with: 7da. 语句，例如：

          >>> 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
          >>>

     3.2 版更變: 支持了 *note with: 7da. 语句。

     3.3 版更變: 添加了 `source_address' 参数。

     3.9 版更變: 如果 `timeout' 参数设置为 0，创建非阻塞套接字时，它将引
     发 *note ValueError: 16d. 来阻止该操作。添加了 `encoding' 参数，且
     为了遵循 RFC 2640(4)，该参数默认值从 Latin-1 改为了 UTF-8。

 -- 類別: ftplib.FTP_TLS (host='', user='', passwd='', acct='',
          keyfile=None, certfile=None, context=None, timeout=None,
          source_address=None, *, encoding='utf-8')

     一个 *note FTP: 1a6. 的子类，它为 FTP 添加了 TLS 支持，如 RFC
     4217(5) 所述。它将像通常一样连接到 21 端口，暗中保护在身份验证前的
     FTP 控制连接。而保护数据连接需要用户明确调用 *note prot_p(): 2e56.
     方法。`context' 是一个 *note ssl.SSLContext: 4e9. 对象，该对象可以
     将 SSL 配置选项、证书和私钥打包放入一个单独的（可以长久存在的）结构
     中。请阅读 *note 安全考量: 26fd. 以获取最佳实践。

     `keyfile' 和 `certfile' 是可以代替 `context' 的传统方案，它们可以分
     别指向 PEM 格式的私钥和证书链文件，用于进行 SSL 连接。

     3.2 版新加入.

     3.3 版更變: 添加了 `source_address' 参数。

     3.4 版更變: 本类现在支持通过 *note ssl.SSLContext.check_hostname:
     2812. 和 `服务器名称提示' （参阅 *note ssl.HAS_SNI: 2827.）进行主机
     名检查。

     3.6 版後已棄用: `keyfile' 和 `certfile' 已弃用并转而推荐 `context'。
     请改用 *note ssl.SSLContext.load_cert_chain(): b69. 或让 *note
     ssl.create_default_context(): 9a7. 为你选择系统所信任的 CA 证书。

     3.9 版更變: 如果 `timeout' 参数设置为 0，创建非阻塞套接字时，它将引
     发 *note ValueError: 16d. 来阻止该操作。添加了 `encoding' 参数，且
     为了遵循 RFC 2640(6)，该参数默认值从 Latin-1 改为了 UTF-8。

     以下是使用 *note FTP_TLS: 1a7. 类的会话示例:

          >>> 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']

 -- 例外: ftplib.error_reply

     从服务器收到意外答复时，将引发本异常。

 -- 例外: ftplib.error_temp

     收到表示临时错误的错误代码（响应代码在 400–499 范围内）时，将引发本
     异常。

 -- 例外: ftplib.error_perm

     收到表示永久性错误的错误代码（响应代码在 500–599 范围内）时，将引发
     本异常。

 -- 例外: ftplib.error_proto

     从服务器收到不符合 FTP 响应规范的答复，比如以数字 1–5 开头时，将引
     发本异常。

 -- Data: ftplib.all_errors

     所有异常的集合（一个元组），由于 FTP 连接出现问题（并非调用者的编码
     错误），*note FTP: 1a6. 实例的方法可能会引发这些异常。该集合包括上
     面列出的四个异常以及 *note OSError: 304. 和 *note EOFError: d34.。

也參考
......

*note netrc: be. 模块

     ‘.netrc’ 文件格式解析器。FTP 客户端在响应用户之前，通常使用
     ‘.netrc’ 文件来加载用户认证信息。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/ftplib.py

   (2) https://tools.ietf.org/html/rfc959.html

   (3) https://tools.ietf.org/html/rfc2640.html

   (4) https://tools.ietf.org/html/rfc2640.html

   (5) https://tools.ietf.org/html/rfc4217.html

   (6) https://tools.ietf.org/html/rfc2640.html


File: python.info,  Node: FTP 对象,  Next: FTP_TLS 对象,  Up: ftplib --- FTP 协议客户端

5.21.13.1 FTP 对象
..................

一些方法可以按照两种方式来使用：一种处理文本文件，另一种处理二进制文件。
方法名称与相应的命令相同，文本版中命令后面跟着 ‘lines’，二进制版中命令后
面跟着 ‘binary’。

*note FTP: 1a6. 实例具有下列方法:

 -- 成員函式: FTP.set_debuglevel (level)

     设置实例的调试级别，它控制着调试信息的数量。默认值 ‘0’ 不产生调试信
     息。值 ‘1’ 产生中等数量的调试信息，通常每个请求产生一行。大于或等于
     ‘2’ 的值产生的调试信息最多，FTP 控制连接上发送和接收的每一行都将被
     记录下来。

 -- 成員函式: FTP.connect (host='', port=0, timeout=None,
          source_address=None)

     连接到给定的主机和端口。默认端口号由 FTP 协议规范规定，为 ‘21’。偶
     尔才需要指定其他端口号。每个实例只应调用一次本函数，如果在创建实例
     时就传入了 host，则根本不应调用它。所有其他方法只能在建立连接后使用
     。可选参数 `timeout' 指定连接尝试的超时（以秒为单位）。如果没有传入
     `timeout'，将使用全局默认超时设置。`source_address' 是一个 2 元组
     ‘(host, port)’，套接字在连接前绑定它，作为其源地址。

     引发一个 *note 审计事件: fa1. ‘ftplib.connect’，附带参数 ‘self’,
     ‘host’, ‘port’。

     3.3 版更變: 添加了 `source_address' 参数。

 -- 成員函式: FTP.getwelcome ()

     返回服务器发送的欢迎消息，作为连接开始的回复。（该消息有时包含与用
     户有关的免责声明或帮助信息。）

 -- 成員函式: FTP.login (user='anonymous', passwd='', acct='')

     以 `user' 的身份登录。`passwd' 和 `acct' 是可选参数，默认为空字符串
     。如果没有指定 `user'，则默认为 ‘'anonymous'’。如果 `user' 为
     ‘'anonymous'’，那么默认的 `passwd' 是 ‘'anonymous@'’。连接建立后，
     每个实例只应调用一次本函数；如果在创建实例时传入了 host 和 user，则
     完全不应该调用本函数。在客户端登录后，才允许执行大多数 FTP 命令。
     `acct' 参数提供记账信息 ("accounting information")；仅少数系统实现
     了该特性。

 -- 成員函式: FTP.abort ()

     中止正在进行的文件传输。本方法并不总是有效，但值得一试。

 -- 成員函式: FTP.sendcmd (cmd)

     将一条简单的命令字符串发送到服务器，返回响应的字符串。

     引发一个 *note 审计事件: fa1. ‘ftplib.sendcmd’，附带参数 ‘self’,
     ‘cmd’。

 -- 成員函式: FTP.voidcmd (cmd)

     将一条简单的命令字符串发送到服务器，并处理响应内容。如果收到的响应
     代码表示的是成功（代码范围 200–299），则不返回任何内容。否则将引发
     *note error_reply: 2e57.。

     引发一个 *note 审计事件: fa1. ‘ftplib.sendcmd’，附带参数 ‘self’,
     ‘cmd’。

 -- 成員函式: FTP.retrbinary (cmd, callback, blocksize=8192, rest=None)

     以二进制传输模式下载文件。`cmd' 应为恰当的 ‘RETR’ 命令：‘'RETR 文件
     名'’。`callback' 函数会在收到每个数据块时调用，传入的参数是表示数据
     块的一个字节。为执行实际传输，创建了底层套接字对象，可选参数
     `blocksize' 指定了读取该对象时的最大块大小（这也是传入 `callback' 的
     数据块的最大大小）。已经选择了合理的默认值。`rest' 的含义与 *note
     transfercmd(): 2e66. 方法中的含义相同。

 -- 成員函式: FTP.retrlines (cmd, callback=None)

     按照初始化时的 `encoding' 参数指定的编码，获取文件或目录列表。`cmd'
     应是恰当的 ‘RETR’ 命令（参阅 *note retrbinary(): 2e65.），也可以是
     诸如 ‘LIST’ 或 ‘NLST’ 之类的命令（通常就只是字符串 ‘'LIST'’）。
     ‘LIST’ 获取文件列表以及那些文件的信息。‘NLST’ 获取文件名称列表。
     `callback' 函数会在每一行都调用，参数就是包含一行的字符串，删除了尾
     部的 CRLF。默认的 `callback' 会把行打印到 ‘sys.stdout’。

 -- 成員函式: FTP.set_pasv (val)

     如果 `val' 为 true，则打开“被动”模式，否则禁用被动模式。默认下被动
     模式是打开的。

 -- 成員函式: FTP.storbinary (cmd, fp, blocksize=8192, callback=None,
          rest=None)

     以二进制传输模式存储文件。 `cmd' 应为恰当的 ‘STOR’ 命令: ‘"STOR
     filename"’。`fp' 是一个 *note 文件对象: c14. (以二进制模式打开)，将
     使用它的 ‘read()’ 方法读取它，用于提供要存储的数据，直到遇到 EOF，
     读取时的块大小为 `blocksize'。 参数 `blocksize' 的默认值为 8192。 可
     选参数 `callback' 是单参数函数，在每个数据块发送后都会以该数据块作
     为参数来调用它。`rest' 的含义与 *note transfercmd(): 2e66. 方法中的
     含义相同。

     3.2 版更變: 添加了 `rest' 参数。

 -- 成員函式: FTP.storlines (cmd, fp, callback=None)

     以文本行模式存储文件。`cmd' 应为恰当的 ‘STOR’ 命令 (请参阅 *note
     storbinary(): d67.)。 `fp' 是一个 *note 文件对象: c14. (以二进制模
     式打开)，将使用它的 *note readline(): 1849. 方法读取它的每一行，用
     于提供要存储的数据，直到遇到 EOF。 可选参数 `callback' 是单参数函数
     ，在每行发送后都会以该行作为参数来调用它。

 -- 成員函式: FTP.transfercmd (cmd, rest=None)

     在 FTP 数据连接上开始传输数据。如果传输处于活动状态，传输命令由
     `cmd' 指定，需发送 ‘EPRT’ 或 ‘PORT’ 命令，然后接受连接 (accept)。如
     果服务器是被动服务器，需发送 ‘EPSV’ 或 ‘PASV’ 命令，连接到服务器
     (connect)，然后启动传输命令。两种方式都将返回用于连接的套接字。

     如果传入了可选参数 `rest'，则一条 ‘REST’ 命令会被发送到服务器，并以
     `rest' 作为参数。`rest' 通常表示请求文件中的字节偏移量，它告诉服务
     器重新开始发送文件的字节，从请求的偏移量处开始，跳过起始字节。但是
     请注意，*note transfercmd(): 2e66. 方法会将 `rest' 转换为字符串，但
     是不检查字符串的内容，转换用的编码是在初始化时指定的 `encoding' 参
     数。如果服务器无法识别 ‘REST’ 命令，将引发 *note error_reply: 2e57.
     异常。如果发生这种情况，只需不带 `rest' 参数调用 *note
     transfercmd(): 2e66.。

 -- 成員函式: FTP.ntransfercmd (cmd, rest=None)

     类似于 *note transfercmd(): 2e66.，但返回一个元组，包括数据连接和数
     据的预计大小。如果预计大小无法计算，则返回的预计大小为 ‘None’。
     `cmd' 和 `rest' 的含义与 *note transfercmd(): 2e66. 中的相同。

 -- 成員函式: FTP.mlsd (path="", facts=[])

     使用 ‘MLSD’ 命令以标准格式列出目录内容 ( RFC 3659(1))。如果省略
     `path' 则使用当前目录。`facts' 是字符串列表，表示所需的信息类型（如
     ‘["type", "size", "perm"]’）。返回一个生成器对象，每个在 path 中找
     到的文件都将在该对象中生成两个元素的元组。第一个元素是文件名，第二
     个元素是该文件的 facts 的字典。该字典的内容受 `facts' 参数限制，但
     不能保证服务器会返回所有请求的 facts。

     3.3 版新加入.

 -- 成員函式: FTP.nlst (argument[, ...])

     返回一个文件名列表，文件名由 ‘NLST’ 命令返回。可选参数 `argument' 是
     待列出的目录（默认为当前服务器目录）。可以使用多个参数，将非标准选
     项传递给 ‘NLST’ 命令。

          備註: 如果目标服务器支持相关命令，那么 *note mlsd(): ae3. 提供
          的 API 更好。

 -- 成員函式: FTP.dir (argument[, ...])

     生成目录列表，即 ‘LIST’ 命令所返回的结果，并将其打印到标准输出。可
     选参数 `argument' 是待列出的目录（默认为当前服务器目录）。可以使用
     多个参数，将非标准选项传递给 ‘LIST’ 命令。如果最后一个参数是一个函
     数，它将被用作 `callback' 函数，与 *note retrlines(): 2e67. 中的相
     同，默认将打印到 ‘sys.stdout’。本方法返回 ‘None’。

          備註: 如果目标服务器支持相关命令，那么 *note mlsd(): ae3. 提供
          的 API 更好。

 -- 成員函式: FTP.rename (fromname, toname)

     将服务器上的文件 `fromname' 重命名为 `toname'。

 -- 成員函式: FTP.delete (filename)

     将服务器上名为 `filename' 的文件删除。如果删除成功，返回响应文本，
     如果删除失败，在权限错误时引发 *note error_perm: 2e59.，在其他错误
     时引发 *note error_reply: 2e57.。

 -- 成員函式: FTP.cwd (pathname)

     设置服务器端的当前目录。

 -- 成員函式: FTP.mkd (pathname)

     在服务器上创建一个新目录。

 -- 成員函式: FTP.pwd ()

     返回服务器上当前目录的路径。

 -- 成員函式: FTP.rmd (dirname)

     将服务器上名为 `dirname' 的目录删除。

 -- 成員函式: FTP.size (filename)

     请求服务器上名为 `filename' 的文件大小。成功后以整数返回文件大小，
     未成功则返回 ‘None’。注意，‘SIZE’ 不是标准命令，但通常许多服务器的
     实现都支持该命令。

 -- 成員函式: FTP.quit ()

     向服务器发送 ‘QUIT’ 命令并关闭连接。 这是关闭一个连接的“礼貌”方式，
     但是如果服务器对 ‘QUIT’ 命令的响应带有错误消息则这会引发一个异常。
     这意味着对 *note close(): 2e73. 方法的调用，它将使得 *note FTP:
     1a6. 实例对后继调用无效（见下文）。

 -- 成員函式: FTP.close ()

     单方面关闭连接。 这不该被应用于已经关闭的连接，例如成功调用 *note
     quit(): 2e72. 之后的连接。 在此调用之后 *note FTP: 1a6. 实例不应被
     继续使用（在调用 *note close(): 2e73. 或 *note quit(): 2e72. 之后你
     不能通过再次发起调用 *note login(): 2e61. 方法重新打开连接）。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc3659.html


File: python.info,  Node: FTP_TLS 对象,  Prev: FTP 对象,  Up: ftplib --- FTP 协议客户端

5.21.13.2 FTP_TLS 对象
......................

*note FTP_TLS: 1a7. 类继承自 *note FTP: 1a6.，它定义了下述其他对象：

 -- 屬性: FTP_TLS.ssl_version

     欲采用的 SSL 版本（默认为 *note ssl.PROTOCOL_SSLv23: 2817.）。

 -- 成員函式: FTP_TLS.auth ()

     通过使用 TLS 或 SSL 来设置一个安全控制连接，具体取决于 *note
     ssl_version: 2e75. 属性是如何设置的。

     3.4 版更變: 此方法现在支持使用 *note ssl.SSLContext.check_hostname:
     2812. 和 `服务器名称指示' (参见 *note ssl.HAS_SNI: 2827.) 进行主机
     名检查。

 -- 成員函式: FTP_TLS.ccc ()

     将控制通道回复为纯文本。 这适用于发挥知道如何使用非安全 FTP 处理
     NAT 而无需打开固定端口的防火墙的优势。

     3.3 版新加入.

 -- 成員函式: FTP_TLS.prot_p ()

     设置加密数据连接。

 -- 成員函式: FTP_TLS.prot_c ()

     设置明文数据连接。


File: python.info,  Node: poplib --- POP3 协议客户端,  Next: imaplib --- IMAP4 协议客户端,  Prev: ftplib --- FTP 协议客户端,  Up: 互联网协议和支持

5.21.14 ‘poplib’ — POP3 协议客户端
----------------------------------

`源代码：' Lib/poplib.py(1)

__________________________________________________________________

本模块定义了一个 *note POP3: 1d5. 类，该类封装了到 POP3 服务器的连接过程
，并实现了 RFC 1939(2) 中定义的协议。*note POP3: 1d5. 类同时支持 RFC
1939(3) 中最小的和可选的命令集。*note POP3: 1d5. 类还支持在 RFC 2595(4)
中引入的 ‘STLS’ 命令，用于在已建立的连接上启用加密通信。

本模块额外提供一个 *note POP3_SSL: 1d6. 类，在连接到 POP3 服务器时，该类
为使用 SSL 作为底层协议层提供了支持。

注意，尽管 POP3 具有广泛的支持，但它已经过时。POP3 服务器的实现质量差异
很大，而且大多很糟糕。如果邮件服务器支持 IMAP，则最好使用 *note
imaplib.IMAP4: 1af. 类，因为 IMAP 服务器一般实现得更好。

*note poplib: d0. 模块提供了两个类：

 -- 類別: poplib.POP3 (host, port=POP3_PORT[, timeout])

     本类实现实际的 POP3 协议。实例初始化时，连接就会建立。如果省略
     `port'，则使用标准 POP3 端口（110）。可选参数 `timeout' 指定连接尝
     试的超时时间（以秒为单位，如果未指定超时，将使用全局默认超时设置）
     。

     引发一个 *note 审计事件: fa1. ‘poplib.connect’，附带参数 ‘self’,
     ‘host’, ‘port’。

     引发一个 *note 审计事件: fa1. ‘poplib.putline’，附带参数 ‘self’,
     ‘line’。

     3.9 版更變: 如果 `timeout' 参数设置为 0，创建非阻塞套接字时，它将引
     发 *note ValueError: 16d. 来阻止该操作。

 -- 類別: poplib.POP3_SSL (host, port=POP3_SSL_PORT, keyfile=None,
          certfile=None, timeout=None, context=None)

     一个 *note POP3: 1d5. 的子类，它使用经 SSL 加密的套接字连接到服务器
     。如果端口 `port' 未指定，则使用 995，它是标准的 POP3-over-SSL 端口
     。`timeout' 的作用与 *note POP3: 1d5. 构造函数中的相同。`context' 是
     一个可选的 *note ssl.SSLContext: 4e9. 对象，该对象可以将 SSL 配置选
     项、证书和私钥打包放入一个单独的（可以长久存在的）结构中。请阅读
     *note 安全考量: 26fd. 以获取最佳实践。

     `keyfile' 和 `certfile' 是可以代替 `context' 的传统方案，它们可以分
     别指向 PEM 格式的私钥和证书链文件，用于进行 SSL 连接。

     引发一个 *note 审计事件: fa1. ‘poplib.connect’，附带参数 ‘self’,
     ‘host’, ‘port’。

     引发一个 *note 审计事件: fa1. ‘poplib.putline’，附带参数 ‘self’,
     ‘line’。

     3.2 版更變: 添加了 `context' 参数。

     3.4 版更變: 本类现在支持使用 *note ssl.SSLContext.check_hostname:
     2812. 和 `服务器名称指示' （参阅 *note ssl.HAS_SNI: 2827.）进行主机
     名检查。

     3.6 版後已棄用: `keyfile' 和 `certfile' 已弃用并转而推荐 `context'。
     请改用 *note ssl.SSLContext.load_cert_chain(): b69. 或让 *note
     ssl.create_default_context(): 9a7. 为你选择系统所信任的 CA 证书。

     3.9 版更變: 如果 `timeout' 参数设置为 0，创建非阻塞套接字时，它将引
     发 *note ValueError: 16d. 来阻止该操作。

定义了一个异常，它是作为 *note poplib: d0. 模块的属性定义的：

 -- 例外: poplib.error_proto

     此模块的所有错误都将引发本异常（来自 *note socket: ef. 模块的错误不
     会被捕获）。异常的原因将以字符串的形式传递给构造函数。

也參考
......

*note imaplib: 97. 模块

     标准的 Python IMAP 模块。

有关 Fetchmail 的常见问题(5)

     ‘fetchmail’ POP/IMAP 客户端的“常见问题”收集了 POP3 服务器之间的差异
     和 RFC 不兼容的信息，如果要编写基于 POP 协议的应用程序，这可能会很
     有用。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/poplib.py

   (2) https://tools.ietf.org/html/rfc1939.html

   (3) https://tools.ietf.org/html/rfc1939.html

   (4) https://tools.ietf.org/html/rfc2595.html

   (5) http://www.catb.org/~esr/fetchmail/fetchmail-FAQ.html


File: python.info,  Node: POP3 对象,  Next: POP3 示例,  Up: poplib --- POP3 协议客户端

5.21.14.1 POP3 对象
...................

所有 POP3 命令均以同名的方法表示，小写，大多数方法返回的是服务器发送的响
应文本。

*note POP3: 1d5. 实例具有下列方法：

 -- 成員函式: POP3.set_debuglevel (level)

     设置实例的调试级别，它控制着调试信息的数量。默认值 ‘0’ 不产生调试信
     息。值 ‘1’ 产生中等数量的调试信息，通常每个请求产生一行。大于或等于
     ‘2’ 的值产生的调试信息最多，FTP 控制连接上发送和接收的每一行都将被
     记录下来。

 -- 成員函式: POP3.getwelcome ()

     返回 POP3 服务器发送的问候语字符串。

 -- 成員函式: POP3.capa ()

     查询服务器支持的功能，这些功能在 RFC 2449(1) 中有说明。返回一个
     ‘{'name': ['param'...]}’ 形式的字典。

     3.4 版新加入.

 -- 成員函式: POP3.user (username)

     发送 user 命令，返回的响应应该指示需要一个密码。

 -- 成員函式: POP3.pass_ (password)

     发送密码，响应包括邮件数和邮箱大小。注意：在调用 ‘quit()’ 前，服务
     器上的邮箱都是锁定的。

 -- 成員函式: POP3.apop (user, secret)

     使用更安全的 APOP 身份验证登录到 POP3 服务器。

 -- 成員函式: POP3.rpop (user)

     使用 RPOP 身份验证（类似于 Unix r-命令）登录到 POP3 服务器。

 -- 成員函式: POP3.stat ()

     获取邮箱状态。结果为 2 个整数组成的元组：‘(message count, mailbox
     size)’。

 -- 成員函式: POP3.list ([which])

     请求消息列表，结果的形式为 ‘(response, ['mesg_num octets', ...],
     octets)’。如果设置了 `which'，它表示需要列出的消息。

 -- 成員函式: POP3.retr (which)

     检索编号为 `which' 的整条消息，并设置其已读标志位。结果的形式为
     ‘(response, ['line', ...], octets)’。

 -- 成員函式: POP3.dele (which)

     将编号为 `which' 的消息标记为待删除。在多数服务器上，删除操作直到
     QUIT 才会实际执行（主要例外是 Eudora QPOP，它在断开连接时执行删除，
     故意违反了 RFC）。

 -- 成員函式: POP3.rset ()

     移除邮箱中的所有待删除标记。

 -- 成員函式: POP3.noop ()

     什么都不做。可以用于保持活动状态。

 -- 成員函式: POP3.quit ()

     登出：提交更改，解除邮箱锁定，断开连接。

 -- 成員函式: POP3.top (which, howmuch)

     检索编号为 `which' 的消息，范围是消息头加上消息头往后数 `howmuch' 行
     。结果的形式为 ‘(response, ['line', ...], octets)’。

     本方法使用 POP3 TOP 命令，不同于 RETR 命令，它不设置邮件的已读标志
     位。不幸的是，TOP 在 RFC 中说明不清晰，且在小众的服务器软件中往往不
     可用。信任并使用它之前，请先手动对目标 POP3 服务器测试本方法。

 -- 成員函式: POP3.uidl (which=None)

     返回消息摘要（唯一 ID）列表。如果指定了 `which'，那么结果将包含那条
     消息的唯一 ID，形式为 ‘'response mesgnum uid’，如果未指定，那么结果
     为列表 ‘(response, ['mesgnum uid', ...], octets)’。

 -- 成員函式: POP3.utf8 ()

     尝试切换至 UTF-8 模式。成功则返回服务器的响应，失败则引发 *note
     error_proto: bea. 异常。在 RFC 6856(2) 中有说明。

     3.5 版新加入.

 -- 成員函式: POP3.stls (context=None)

     在活动连接上开启 TLS 会话，在 RFC 2595(3) 中有说明。仅在用户身份验
     证前允许这样做。

     `context' 参数是一个 *note ssl.SSLContext: 4e9. 对象，该对象可以将
     SSL 配置选项、证书和私钥打包放入一个单独的（可以长久存在的）结构中
     。请阅读 *note 安全考量: 26fd. 以获取最佳实践。

     此方法支持通过 *note ssl.SSLContext.check_hostname: 2812. 和 `服务
     器名称指示' (参见 *note ssl.HAS_SNI: 2827.) 进行主机名检查。

     3.4 版新加入.

*note POP3_SSL: 1d6. 实例没有额外方法。该子类的接口与其父类的相同。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2449.html

   (2) https://tools.ietf.org/html/rfc6856.html

   (3) https://tools.ietf.org/html/rfc2595.html


File: python.info,  Node: POP3 示例,  Prev: POP3 对象,  Up: poplib --- POP3 协议客户端

5.21.14.2 POP3 示例
...................

以下是一个最短示例（不带错误检查），该示例将打开邮箱，检索并打印所有消息
:

     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)

模块的最后有一段测试，其中包含的用法示例更加广泛。


File: python.info,  Node: imaplib --- IMAP4 协议客户端,  Next: nntplib --- NNTP 协议客户端,  Prev: poplib --- POP3 协议客户端,  Up: 互联网协议和支持

5.21.15 ‘imaplib’ — IMAP4 协议客户端
------------------------------------

`源代码：' Lib/imaplib.py(1)

__________________________________________________________________

本模块定义了三个类： *note IMAP4: 1af. 、 *note IMAP4_SSL: 1b0. 和 *note
IMAP4_stream: 1b2. 。这三个类封装了与IMAP4服务器的连接并实现了 RFC
2060(2) 当中定义的大多数IMAP4rev1客户端协议。其与IMAP4（ RFC 1730(3) ）
服务器后向兼容，但是 ‘STATUS’ 指令在IMAP4中不支持。

*note imaplib: 97. 模块提供了三个类，其中 *note IMAP4: 1af. 是基类：

 -- 類別: imaplib.IMAP4 (host='', port=IMAP4_PORT, timeout=None)

     这个类实现了实际的 IMAP4 协议。 当其实例被实例化时会创建连接并确定
     协议版本 (IMAP4 或 IMAP4rev1)。 如果未指明 `host'，则会使用 ‘''’ (本
     地主机)。 如果省略 `port'，则会使用标准 IMAP4 端口 (143)。 可选的
     `timeout' 形参指定连接尝试的超时秒数。 如果未指定超时或为 None，则
     会使用全局默认的套接字超时。

     *note IMAP4: 1af. 类支持 *note with: 7da. 语句。 当这样使用时，
     IMAP4 ‘LOGOUT’ 命令会在 ‘with’ 语句退出时自动发出。 例如:

          >>> from imaplib import IMAP4
          >>> with IMAP4("domain.org") as M:
          ...     M.noop()
          ...
          ('OK', [b'Nothing Accomplished. d25if65hy903weo.87'])

     3.5 版更變: 支持了 *note with: 7da. 语句。

     3.9 版更變: 添加了可选的 `timeout' 形参。

有三个异常被定义为 *note IMAP4: 1af. 类的属性:

 -- 例外: IMAP4.error

     任何错误都将引发该异常。 异常的原因会以字符串的形式传递给构造器。

 -- 例外: IMAP4.abort

     IMAP4 服务器错误会导致引发该异常。 这是 *note IMAP4.error: 2e8e. 的
     子类。 请注意关闭此实例并实例化一个新实例通常将会允许从该异常中恢复
     。

 -- 例外: IMAP4.readonly

     当一个可写邮箱的状态被服务器修改时会引发此异常。 此异常是 *note
     IMAP4.error: 2e8e. 的子类。 某个其他客户端现在会具有写入权限，将需
     要重新打开该邮箱以重新获得写入权限。

另外还有一个针对安全连接的子类:

 -- 類別: imaplib.IMAP4_SSL (host='', port=IMAP4_SSL_PORT, keyfile=None,
          certfile=None, ssl_context=None, timeout=None)

     这是一个派生自 *note IMAP4: 1af. 的子类，它使用经 SSL 加密的套接字
     进行连接 (为了使用这个类你需要编译时附带 SSL 支持的 socket 模块)。
     如果未指定 `host'，则会使用 ‘''’ (本地主机)。 如果省略了 `port'，则
     会使用标准的 IMAP4-over-SSL 端口 (993)。 `ssl_context' 是一个 *note
     ssl.SSLContext: 4e9. 对象，它允许将 SSL 配置选项、证书和私钥打包放
     入一个单独的 (可以长久存在的) 结构体中。 请阅读 *note 安全考量:
     26fd. 以获取最佳实践。

     `keyfile' 和 `certfile' 是 `ssl_context' 的旧式替代品 —— 它们可以指
     向 PEM 格式的私钥和证书链文件用于 SSL 连接。 请注意
     `keyfile'/`certfile' 形参不能与 `ssl_context' 共存，如果
     `keyfile'/`certfile' 与 `ssl_context' 一同被提供则会引发 *note
     ValueError: 16d.。

     可选的 `timeout' 形参指明连接尝试的超时秒数。 如果参数未给出或为
     None，则会使用全局默认的套接字超时设置。

     3.3 版更變: 增加了 `ssl_context' 形参。

     3.4 版更變: 本类现在支持通过 *note ssl.SSLContext.check_hostname:
     2812. 和 `服务器名称提示' （参阅 *note ssl.HAS_SNI: 2827.）进行主机
     名检查。

     3.6 版後已棄用: `keyfile' 和 `certfile' 已弃用并转而推荐
     `ssl_context'。 请改用 *note ssl.SSLContext.load_cert_chain():
     b69.，或让 *note ssl.create_default_context(): 9a7. 为你选择系统所
     信任的 CA 证书。

     3.9 版更變: 添加了可选的 `timeout' 形参。

第二个子类允许由子进程所创建的连接:

 -- 類別: imaplib.IMAP4_stream (command)

     这是一个派生自 *note IMAP4: 1af. 的子类，它可以连接 ‘stdin/stdout’
     文件描述符，此种文件是通过向 ‘subprocess.Popen()’ 传入 `command' 来
     创建的。

定义了下列工具函数:

 -- 函式: imaplib.Internaldate2tuple (datestr)

     解析一个 IMAP4 ‘INTERNALDATE’ 字符串并返回对应的本地时间。 返回值是
     一个 *note time.struct_time: 690. 元组或者如果字符串格式错误则为
     ‘None’。

 -- 函式: imaplib.Int2AP (num)

     将一个整数转换为使用字符集 [‘A’ ..  ‘P’] 的字节串表示形式。

 -- 函式: imaplib.ParseFlags (flagstr)

     将一个 IMAP4 ‘FLAGS’ 响应转换为包含单独旗标的元组。

 -- 函式: imaplib.Time2Internaldate (date_time)

     将 `date_time' 转换为 IMAP4 ‘INTERNALDATE’ 表示形式。 返回值是以下
     形式的字符串: ‘"DD-Mmm-YYYY HH:MM:SS +HHMM"’ (包括双引号)。
     `date_time' 参数可以是一个代表距离纪元起始的秒数 (如 *note
     time.time(): 42d. 的返回值) 的数字 (整数或浮点数)，一个代表本地时间
     的 9 元组，一个 *note time.struct_time: 690. 实例 (如 *note
     time.localtime(): 1080. 的返回值)，一个感知型的 *note
     datetime.datetime: 19f. 实例，或一个双引号字符串。 在最后一种情况下
     ，它会被假定已经具有正确的格式。

请注意 IMAP4 消息编号会随邮箱的改变而改变；特别是在使用 ‘EXPUNGE’ 命令执
行删除后剩余的消息会被重新编号。 因此高度建议通过 UID 命令来改用 UID。

模块的最后有一段测试，其中包含的用法示例更加广泛。

也參考
......

描述该协议的文档，实现该协议的服务器源代码，由华盛顿大学 IMAP 信息中心提
供 (`源代码') ‘https://github.com/uw-imap/imap’ (`不再维护')。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/imaplib.py

   (2) https://tools.ietf.org/html/rfc2060.html

   (3) https://tools.ietf.org/html/rfc1730.html


File: python.info,  Node: IMAP4 对象,  Next: IMAP4 示例,  Up: imaplib --- IMAP4 协议客户端

5.21.15.1 IMAP4 对象
....................

所有 IMAP4rev1 命令都表示为同名的方法，可以为大写或小写形式。

命令的所有参数都会被转换为字符串，只有 ‘AUTHENTICATE’ 例外，而, and the
last argument to ‘APPEND’ 的最后一个参数会被作为 IMAP4 字面值传入。 如有
必要 (字符串包含 IMAP4 协议中的敏感字符并且未加圆括号或双引号) 每个字符
串都会被转码。 但是，‘LOGIN’ 命令的 `password' 参数总是会被转码。 如果你
想让某个参数字符串免于被转码 (例如: ‘STORE’ 的 `flags' 参数) 则要为该字
符串加上圆括号 (例如: ‘r'(\Deleted)'’)。

每条命令均返回一个元组: ‘(type, [data, ...])’ 其中 `type' 通常为 ‘'OK'’
或 ‘'NO'’，而 `data' 为来自命令响应的文本，或为来自命令的规定结果。 每个
`data' 均为 ‘bytes’ 或者元组。 如果为元组，则其第一部分是响应的标头，而
第二部分将包含数据 (例如: ’literal’ 值)。

以下命令的 `message_set' 选项为指定要操作的一条或多条消息的字符串。 它可
以是一个简单的消息编号 (‘'1'’)，一段消息编号区间 (‘'2:4'’)，或者一组以逗
号分隔的非连续区间 (‘'1:3,6:9'’)。 区间可以包含一个星号来表示无限的上界
(‘'3:*'’)。

*note IMAP4: 1af. 实例具有下列方法:

 -- 成員函式: IMAP4.append (mailbox, flags, date_time, message)

     将 `message' 添加到指定的邮箱。

 -- 成員函式: IMAP4.authenticate (mechanism, authobject)

     认证命令 — 要求对响应进行处理。

     `mechanism' 指明要使用哪种认证机制 —— 它应当在实例变量
     ‘capabilities’ 中以 ‘AUTH=mechanism’ 的形式出现。

     `authobject' 必须是一个可调用对象:

          data = authobject(response)

     它将被调用以便处理服务器连续响应；传给它的 `response' 参数将为
     ‘bytes’ 类型。 它应当返回 base64 编码的 ‘bytes’ `数据' 并发送给服务
     器。 或者在客户端中止响应时返回 ‘None’ 并应改为发送 ‘*’。

     3.5 版更變: 字符串形式的用户名和密码现在会被执行 ‘utf-8’ 编码而不限
     于 ASCII 字符。

 -- 成員函式: IMAP4.check ()

     为服务器上的邮箱设置检查点。

 -- 成員函式: IMAP4.close ()

     关闭当前选定的邮箱。 已删除的消息会从可写邮箱中被移除。 在 ‘LOGOUT’
     之前建议执行此命令。

 -- 成員函式: IMAP4.copy (message_set, new_mailbox)

     将 `message_set' 消息拷贝到 `new_mailbox' 的末尾。

 -- 成員函式: IMAP4.create (mailbox)

     新建名为 `mailbox' 新邮箱。

 -- 成員函式: IMAP4.delete (mailbox)

     删除名为 `mailbox' 的旧邮箱。

 -- 成員函式: IMAP4.deleteacl (mailbox, who)

     删除邮箱上某人的 ACL (移除任何权限)。

 -- 成員函式: IMAP4.enable (capability)

     启用 `capability' (参见 RFC 5161(1))。 大多数功能都不需要被启用。 目
     前只有 ‘UTF8=ACCEPT’ 功能受到支持 (参见 RFC 6855(2))。

     3.5 版新加入: *note enable(): 7db. 方法本身，以及 RFC 6855(3) 支持
     。

 -- 成員函式: IMAP4.expunge ()

     从选定的邮箱中永久移除被删除的条目。 为每条被删除的消息各生成一个
     ‘EXPUNGE’ 响应。 返回包含按接收时间排序的 ‘EXPUNGE’ 消息编号的列表
     。

 -- 成員函式: IMAP4.fetch (message_set, message_parts)

     获取消息（的各个部分）。 `message_parts' 应为加圆标号的消息部分名称
     字符串，例如: ‘"(UID BODY[TEXT])"’。 返回的数据是由消息部分封包和数
     据组成的元组。

 -- 成員函式: IMAP4.getacl (mailbox)

     获取 `mailbox' 的 ‘ACL’。 此方法是非标准的，但是被 ‘Cyrus’ 服务器所
     支持。

 -- 成員函式: IMAP4.getannotation (mailbox, entry, attribute)

     提取 `mailbox' 的特定 ‘ANNOTATION’。 此方法是非标准的，但是被
     ‘Cyrus’ 服务器所支持。

 -- 成員函式: IMAP4.getquota (root)

     获取 ‘quota’ `root' 的资源使用和限制。 此方法是 rfc2087 定义的
     IMAP4 QUOTA 扩展的组成部分。

 -- 成員函式: IMAP4.getquotaroot (mailbox)

     获取指定 `mailbox' 的 ‘quota’ ‘roots’ 列表。 此方法是 rfc2087 定义
     的 IMAP4 QUOTA 扩展的组成部分。

 -- 成員函式: IMAP4.list ([directory[, pattern]])

     列出 `directory' 中与 `pattern' 相匹配的邮箱名称。 `directory' 默认
     为最高层级的电邮文件夹，而 `pattern' 默认为匹配任何文本。 返回的数
     据包含 ‘LIST’ 响应列表。

 -- 成員函式: IMAP4.login (user, password)

     使用纯文本密码标识客户。 `password' 将被转码。

 -- 成員函式: IMAP4.login_cram_md5 (user, password)

     在标识用户以保护密码时强制使用 ‘CRAM-MD5’ 认证。 将只在服务器
     ‘CAPABILITY’ 响应包含 ‘AUTH=CRAM-MD5’ 阶段时才有效。

 -- 成員函式: IMAP4.logout ()

     关闭对服务器的连接。 返回服务器 ‘BYE’ 响应。

     3.8 版更變: 此方法不会再忽略静默的任意异常。

 -- 成員函式: IMAP4.lsub (directory='""', pattern='*')

     列出 directory 中抽取的与 pattern 相匹配的邮箱。 `directory' 默认为
     最高层级目录而 `pattern' 默认为匹配任何邮箱。 返回的数据为消息部分
     封包和数据的元组。

 -- 成員函式: IMAP4.myrights (mailbox)

     显示某个邮箱的本人 ACL (即本人在邮箱中的权限)。

 -- 成員函式: IMAP4.namespace ()

     返回 RFC 2342(4) 中定义的 IMAP 命名空间。

 -- 成員函式: IMAP4.noop ()

     将 ‘NOOP’ 发送给服务器。

 -- 成員函式: IMAP4.open (host, port, timeout=None)

     打开连接 `host' 上 `port' 的套接字。 可选的 `timeout' 形参指定连接
     尝试的超时秒数。 如果 timeout 未给出或为 None，则会使用全局默认的套
     接字超时。 另外请注意如果 `timeout' 形参被设为零，它将引发 *note
     ValueError: 16d. 以拒绝创建非阻塞套接字。 此方法会由 *note IMAP4:
     1af. 构造器隐式地调用。 此方法所建立的连接对象将在 *note
     IMAP4.read(): 2eac, *note IMAP4.readline(): 2ead, *note
     IMAP4.send(): 2eae. 和 *note IMAP4.shutdown(): 2eaf. 等方法中被使用
     。 你可以重载此方法。

     引发一个 *note 审计事件: fa1. ‘imaplib.open’，附带参数 ‘self’,
     ‘host’, ‘port’。

     3.9 版更變: 加入 `timeout' 参数。

 -- 成員函式: IMAP4.partial (message_num, message_part, start, length)

     获取消息被截断的部分。 返回的数据是由消息部分封包和数据组成的元组。

 -- 成員函式: IMAP4.proxyauth (user)

     作为 `user' 进行认证。 允许经权限的管理员通过代理进入任意用户的邮箱
     。

 -- 成員函式: IMAP4.read (size)

     从远程服务器读取 `size' 字节。 你可以重载此方法。

 -- 成員函式: IMAP4.readline ()

     从远程服务器读取一行。 你可以重载此方法。

 -- 成員函式: IMAP4.recent ()

     提示服务器进行更新。 如果没有新消息则返回的数据为 ‘None’，否则为
     ‘RECENT’ 响应的值。

 -- 成員函式: IMAP4.rename (oldmailbox, newmailbox)

     将名为 `oldmailbox' 的邮箱重命名为 `newmailbox'。

 -- 成員函式: IMAP4.response (code)

     如果收到响应 `code' 则返回其数据，否则返回 ‘None’。 返回给定的代码
     ，而不是普通的类型。

 -- 成員函式: IMAP4.search (charset, criterion[, ...])

     在邮箱中搜索匹配的消息。 `charset' 可以为 ‘None’，在这种情况下在发
     给服务器的请求中将不指定 ‘CHARSET’。 IMAP 协议要求至少指定一个标准
     ；当服务器返回错误时将会引发异常。 `charset' 为 ‘None’ 对应使用
     *note enable(): 7db. 命令启用了 ‘UTF8=ACCEPT’ 功能的情况。

     示例:

          # M is a connected IMAP4 instance...
          typ, msgnums = M.search(None, 'FROM', '"LDJ"')

          # or:
          typ, msgnums = M.search(None, '(FROM "LDJ")')

 -- 成員函式: IMAP4.select (mailbox='INBOX', readonly=False)

     选择一个邮箱。 返回的数据是 `mailbox' 中消息的数量 (‘EXISTS’ 响应
     )。 默认的 `mailbox' 为 ‘'INBOX'’。 如果设置了 `readonly' 旗标，则
     不允许修改该邮箱。

 -- 成員函式: IMAP4.send (data)

     将 ‘data’ 发送给远程服务器。 请可以重载此方法。

     引发一个 *note 审计事件: fa1. ‘imaplib.send’，附带参数 ‘self’,
     ‘data’。

 -- 成員函式: IMAP4.setacl (mailbox, who, what)

     发送 `mailbox' 的 ‘ACL’。 此方法是非标准的，但是被 ‘Cyrus’ 服务器所
     支持。

 -- 成員函式: IMAP4.setannotation (mailbox, entry, attribute[, ...])

     设置 `mailbox' 的 ‘ANNOTATION’。 此方法是非标准的，但是被 ‘Cyrus’ 服
     务器所支持。

 -- 成員函式: IMAP4.setquota (root, limits)

     设置 ‘quota’ `root' 的资源限制为 `limits'。 此方法是 rfc2087 定义的
     IMAP4 QUOTA 扩展的组成部分。

 -- 成員函式: IMAP4.shutdown ()

     关闭在 ‘open’ 中建立的连接。 此方法会由 *note IMAP4.logout(): 2ea7.
     隐式地调用。 你可以重载此方法。

 -- 成員函式: IMAP4.socket ()

     返回用于连接服务器的套接字实例。

 -- 成員函式: IMAP4.sort (sort_criteria, charset, search_criterion[,
          ...])

     ‘sort’ 命令是 ‘search’ 的变化形式，带有结果排序语句。 返回的数据包
     含以空格分隔的匹配消息编号列表。

     排序命令在 `search_criterion' 参数之前还有两个参数；一个带圆括号的
     `sort_criteria' 列表，和搜索的 `charset'。 请注意不同于 ‘search’，
     搜索的 `charset' 参数是强制性的。 还有一个 ‘uid sort’ 命令与 ‘sort’
     对应，如同 ‘uid search’ 与 ‘search’ 对应一样。 ‘sort’ 命令首先在邮
     箱中搜索匹配给定搜索条件的消息，使用 charset 参数来解读搜索条件中的
     字符串。 然后它将返回所匹配消息的编号。

     这是一个 ‘IMAP4rev1’ 扩展命令。

 -- 成員函式: IMAP4.starttls (ssl_context=None)

     发送一个 ‘STARTTLS’ 命令。 `ssl_context' 参数是可选的并且应为一个
     *note ssl.SSLContext: 4e9. 对象。 这将在 IMAP 连接上启用加密。 请阅
     读 *note 安全考量: 26fd. 来了解最佳实践。

     3.2 版新加入.

     3.4 版更變: 此方法现在支持使用 *note ssl.SSLContext.check_hostname:
     2812. 和 `服务器名称指示' (参见 *note ssl.HAS_SNI: 2827.) 进行主机
     名检查。

 -- 成員函式: IMAP4.status (mailbox, names)

     针对 `mailbox' 请求指定的状态条件。

 -- 成員函式: IMAP4.store (message_set, command, flag_list)

     改变邮箱中消息的旗标处理。 `command' 由 RFC 2060(5) 的 6.4.6 小节指
     明，应为 "FLAGS", "+FLAGS" 或 "-FLAGS" 之一，并可选择附带 ".SILENT"
     后缀。

     例如，要在所有消息上设置删除旗标:

          typ, data = M.search(None, 'ALL')
          for num in data[0].split():
             M.store(num, '+FLAGS', '\\Deleted')
          M.expunge()

          備註: 创建包含 ’]’ 的旗标 (例如: "[test]") 会违反 RFC 3501(6)
          (IMAP 协议)。 但是，imaplib 在历史上曾经允许创建这样的标签，并
          且流行的 IMAP 服务器如 Gmail 都会接受并生成这样的旗标。 有些非
          Python 程序也会创建这样的旗标。 虽然它违反 RFC 并且 IMAP 客户
          端和服务器应当严格遵守规范，但是 imaplib 出于向下兼容的理由仍
          然继续允许创建这样的标签，并且在 Python 3.6 中会在其被服务器所
          发送时处理它们，因为这能提升实际的兼容性。

 -- 成員函式: IMAP4.subscribe (mailbox)

     订阅新邮箱。

 -- 成員函式: IMAP4.thread (threading_algorithm, charset,
          search_criterion[, ...])

     ‘thread’ 命令是 ‘search’ 的变化形式，带有针对结果的消息串句法。 返
     回的数据包含以空格分隔的消息串成员列表。

     消息串成员由零个或多个消息编号组成，以空格分隔，标示了连续的上下级
     关系。

     thread 命令在 `search_criterion' 参数之前还有两个参数；一个
     `threading_algorithm'，以及搜索使用的 `charset'。 请注意不同于
     ‘search’，搜索使用的 `charset' 参数是强制性的。 还有一个 ‘uid
     thread’ 命令与 ‘thread’ 对应，如同 ‘uid search’ 与 ‘search’ 对应一
     个。 ‘thread’ 命令首先在邮箱中搜索匹配给定搜索条件的消息，使用
     charset 参数来解读搜索条件中的字符串。 然后它将按照指定的消息串算法
     返回所匹配的消息串。

     这是一个 ‘IMAP4rev1’ 扩展命令。

 -- 成員函式: IMAP4.uid (command, arg[, ...])

     执行 command arg 并附带用 UID 所标识的消息，而不是用消息编号。 返回
     与命令对应的响应。 必须至少提供一个参数；如果不提供任何参数，服务器
     将返回错误并引发异常。

 -- 成員函式: IMAP4.unsubscribe (mailbox)

     取消订阅原有邮箱。

 -- 成員函式: IMAP4.unselect ()

     *note imaplib.IMAP4.unselect(): 1b3. 会释放关联到选定邮箱的服务器资
     源并将服务器返回到已认证状态。 此命令会执行与 *note
     imaplib.IMAP4.close(): 1b4. 相同的动作，区别在于它不会从当前选定邮
     箱中永久性地移除消息。

     3.9 版新加入.

 -- 成員函式: IMAP4.xatom (name[, ...])

     允许服务器在 ‘CAPABILITY’ 响应中通知简单的扩展命令。

在 *note IMAP4: 1af. 的实例上定义了下列属性:

 -- 屬性: IMAP4.PROTOCOL_VERSION

     在服务器的 ‘CAPABILITY’ 响应中最新的受支持协议。

 -- 屬性: IMAP4.debug

     控制调试输出的整数值。 初始值会从模块变量 ‘Debug’ 中获取。 大于三的
     值表示将追踪每一条命令。

 -- 屬性: IMAP4.utf8_enabled

     通常为 ‘False’ 的布尔值，但也可以被设为 ‘True’，如果成功地为
     ‘UTF8=ACCEPT’ 功能发送了 *note enable(): 7db. 命令的话。

     3.5 版新加入.

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc5161.html

   (2) https://tools.ietf.org/html/rfc6855.html

   (3) https://tools.ietf.org/html/rfc6855.html

   (4) https://tools.ietf.org/html/rfc2342.html

   (5) https://tools.ietf.org/html/rfc2060.html

   (6) https://tools.ietf.org/html/rfc3501.html


File: python.info,  Node: IMAP4 示例,  Prev: IMAP4 对象,  Up: imaplib --- IMAP4 协议客户端

5.21.15.2 IMAP4 示例
....................

以下是一个最短示例（不带错误检查），该示例将打开邮箱，检索并打印所有消息
:

     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()


File: python.info,  Node: nntplib --- NNTP 协议客户端,  Next: smtplib ---SMTP协议客户端,  Prev: imaplib --- IMAP4 协议客户端,  Up: 互联网协议和支持

5.21.16 ‘nntplib’ — NNTP 协议客户端
-----------------------------------

`源代码:' Lib/nntplib.py(1)

__________________________________________________________________

此模块定义了 *note NNTP: 1c6. 类来实现网络新闻传输协议的客户端。 它可被
用于实现一个新闻阅读或发布器，或是新闻自动处理程序。 它兼容了 RFC
3977(2) 以及较旧的 RFC 977(3) 和 RFC 2980(4)。

下面是此模块的两个简单用法示例。 列出某个新闻组的一些统计数据并打印最近
10 篇文章的主题:

     >>> 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!'

要基于一个二进制文件发布文章 (假定文章包含有效的标头，并且你有在特定新闻
组上发布内容的权限):

     >>> s = nntplib.NNTP('news.gmane.io')
     >>> f = open('article.txt', 'rb')
     >>> s.post(f)
     '240 Article posted successfully.'
     >>> s.quit()
     '205 Bye!'

此模块本身定义了以下的类:

 -- 類別: nntplib.NNTP (host, port=119, user=None, password=None,
          readermode=None, usenetrc=False[, timeout])

     返回一个新的 *note NNTP: 1c6. 对象，代表一个对运行于主机 `host'，在
     端口 `port' 上监听的 NNTP 服务器的连接。 可以为套接字连接指定可选的
     `timeout'。 如果提供了可选的 `user' 和 `password'，或者如果在
     ‘/.netrc’ 中存在适合的凭证并且可选的旗标 `usenetrc' 为真值，则会使
     用 ‘AUTHINFO USER’ 和 ‘AUTHINFO PASS’ 命令在服务器上标识和认证用户
     。 如果可选的旗标 `readermode' 为真值，则会在执行认证之前发送 ‘mode
     reader’ 命令。 在某些时候如果你是连接本地机器上的 NNTP 服务器并且想
     要调用读取者专属命令如 ‘group’ 那么还必须使用读取者模式。 如果你收
     到预料之外的 *note NNTPPermanentError: 2ec9.，你可能需要设置
     `readermode'。 *note NNTP: 1c6. 类支持使用 *note with: 7da. 语句来
     无条件地消费 *note OSError: 304. 异常并在结束时关闭 NNTP 连接，例如
     :

          >>> 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')
          >>>

     引发一个 *note 审计事件: fa1. ‘nntplib.connect’ 附带参数 ‘self’,
     ‘host’, ‘port’。

     引发一个 *note 审计事件: fa1. ‘nntplib.putline’，附带参数 ‘self’,
     ‘line’。

     3.2 版更變: `usenetrc' 现在默认为 ‘False’。

     3.3 版更變: 支持了 *note with: 7da. 语句。

     3.9 版更變: 如果 `timeout' 参数设置为 0，创建非阻塞套接字时，它将引
     发 *note ValueError: 16d. 来阻止该操作。

 -- 類別: nntplib.NNTP_SSL (host, port=563, user=None, password=None,
          ssl_context=None, readermode=None, usenetrc=False[, timeout])

     返回一个新的 *note NNTP_SSL: 1c7. 对象，代表一个对运行于主机
     `host'，在端口 `port' 上监听的 NNTP 服务器的连接。 *note NNTP_SSL:
     1c7. 对象具有与 *note NNTP: 1c6. 对象相同的方法。 如果 `port' 被省
     略，则会使用端口 563 (NNTPS)。 `ssl_context' 也是可选的，且为一个
     *note SSLContext: 4e9. 对象。 请阅读 *note 安全考量: 26fd. 来了解最
     佳实践。 所有其他形参的行为都与 *note NNTP: 1c6. 的相同。

     请注意 RFC 4642(5) 不再推荐使用 563 端口的 SSL，建议改用下文描述的
     STARTTLS。 但是，某些服务器只支持前者。

     引发一个 *note 审计事件: fa1. ‘nntplib.connect’ 附带参数 ‘self’,
     ‘host’, ‘port’。

     引发一个 *note 审计事件: fa1. ‘nntplib.putline’，附带参数 ‘self’,
     ‘line’。

     3.2 版新加入.

     3.4 版更變: 本类现在支持通过 *note ssl.SSLContext.check_hostname:
     2812. 和 `服务器名称提示' （参阅 *note ssl.HAS_SNI: 2827.）进行主机
     名检查。

     3.9 版更變: 如果 `timeout' 参数设置为 0，创建非阻塞套接字时，它将引
     发 *note ValueError: 16d. 来阻止该操作。

 -- 例外: nntplib.NNTPError

     派生自标准异常 *note Exception: 2dc.，这是 *note nntplib: c0. 模块
     中引发的所有异常的基类。 该类的实例具有以下属性:

      -- 屬性: response

          可用的服务器响应，为一 *note str: 205. 对象。

 -- 例外: nntplib.NNTPReplyError

     从服务器收到意外答复时，将引发本异常。

 -- 例外: nntplib.NNTPTemporaryError

     收到 400–499 范围内的响应代码时所引发的异常。

 -- 例外: nntplib.NNTPPermanentError

     收到 500–599 范围内的响应代码时所引发的异常。

 -- 例外: nntplib.NNTPProtocolError

     当从服务器收到不是以数字 1–5 开头的答复时所引发的异常。

 -- 例外: nntplib.NNTPDataError

     当响应数据中存在错误时所引发的异常。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/nntplib.py

   (2) https://tools.ietf.org/html/rfc3977.html

   (3) https://tools.ietf.org/html/rfc977.html

   (4) https://tools.ietf.org/html/rfc2980.html

   (5) https://tools.ietf.org/html/rfc4642.html


File: python.info,  Node: NNTP 对象,  Next: 工具函数<2>,  Up: nntplib --- NNTP 协议客户端

5.21.16.1 NNTP 对象
...................

当连接时，*note NNTP: 1c6. 和 *note NNTP_SSL: 1c7. 对象支持以下方法和属
性。

* Menu:

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


File: python.info,  Node: 属性,  Next: 方法<3>,  Up: NNTP 对象

5.21.16.2 属性
..............

 -- 屬性: NNTP.nntp_version

     代表服务器所支持的 NNTP 协议版本的整数。 在实践中，这对声明遵循 RFC
     3977(1) 的服务器应为 ‘2’ 而对其他服务器则为 ‘1’。

     3.2 版新加入.

 -- 屬性: NNTP.nntp_implementation

     描述 NNTP 服务器软件名称和版本的字符串，如果服务器未声明此信息则为
     *note None: 203.。

     3.2 版新加入.

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc3977.html


File: python.info,  Node: 方法<3>,  Prev: 属性,  Up: NNTP 对象

5.21.16.3 方法
..............

作为几乎全部方法所返回元组的第一项返回的 `response' 是服务器的响应：以三
位数字代码打头的字符串。 如果服务器的响应是提示错误，则方法将引发上述异
常之一。

以下方法中许多都接受一个可选的仅限关键字参数 `file'。 当提供了 `file' 参
数时，它必须为打开用于二进制写入的 *note file object: c14.，或要写入的磁
盘文件名称。 此类方法随后将把服务器返回的任意数据（除了响应行和表示结束
的点号）写入到文件中；此类方法通常返回的任何行列表、元组或对象都将为空值
。

3.2 版更變: 以下方法中许多都已被重写和修正，这使得它们不再与 3.1 中的同
名方法相兼容。

 -- 成員函式: NNTP.quit ()

     发送 ‘QUIT’ 命令并关闭连接。 一旦此方法被调用，NNTP 对象的其他方法
     都不应再被调用。

 -- 成員函式: NNTP.getwelcome ()

     返回服务器发送的欢迎消息，作为连接开始的回复。（该消息有时包含与用
     户有关的免责声明或帮助信息。）

 -- 成員函式: NNTP.getcapabilities ()

     返回服务器所声明的 RFC 3977(1) 功能，其形式为将功能名称映射到（可能
     为空的）值列表的 *note dict: 164. 实例。 在不能识别 ‘CAPABILITIES’
     命令的旧式服务器上，会返回一个空字典。

          >>> s = NNTP('news.gmane.io')
          >>> 'POST' in s.getcapabilities()
          True

     3.2 版新加入.

 -- 成員函式: NNTP.login (user=None, password=None, usenetrc=True)

     发送 ‘AUTHINFO’ 命令并附带用户名和密码。 如果 `user' 和 `password'
     为 ‘None’ 且 `usenetrc' 为真值，则会在可能的情况下使用来自
     ‘~/.netrc’ 的凭证。

     除非被有意延迟，登录操作通常会在 *note NNTP: 1c6. 对象初始化期间被
     执行因而没有必要单独调用此函数。 要强制延迟验证，你在创建该对象时不
     能设置 `user' 或 `password'，并必须将 `usenetrc' 设为 False。

     3.2 版新加入.

 -- 成員函式: NNTP.starttls (context=None)

     发送 ‘STARTTLS’ 命令。 这将在 NNTP 连接上启用加密。 `context' 参数
     是可选的且应为 *note ssl.SSLContext: 4e9. 对象。 请阅读 *note
     安全考量: 26fd. 了解最佳实践。

     请注意此操作可能不会在传输验证信息之后立即完成，只要有可能验证默认
     会在 *note NNTP: 1c6. 对象初始化期间发生。 请参阅 *note
     NNTP.login(): 2ed9. 了解有关如何屏蔽此行为的信息。

     3.2 版新加入.

     3.4 版更變: 此方法现在支持使用 *note ssl.SSLContext.check_hostname:
     2812. 和 `服务器名称指示' (参见 *note ssl.HAS_SNI: 2827.) 进行主机
     名检查。

 -- 成員函式: NNTP.newgroups (date, *, file=None)

     发送 ‘NEWGROUPS’ 命令。 `date' 参数应为 *note datetime.date: 19d. 或
     *note datetime.datetime: 19f. 对象。 返回一个 ‘(response, groups)’
     对，其中 `groups' 是代表给定i `date' 以来所新建的分组。 但是如果提
     供了 `file'，则 `groups' 将为空值。

          >>> 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')

 -- 成員函式: NNTP.newnews (group, date, *, file=None)

     发送 ‘NEWNEWS’ 命令。 这里，`group' 是新闻组名称或为 ‘'*'’，而
     `date' 与 *note newgroups(): 2eda. 中的含义相同。 返回一个
     ‘(response, articles)’ 对，其中 `articles' 为消息 ID 列表。

     此命令经常会被 NNTP 服务器管理员禁用。

 -- 成員函式: NNTP.list (group_pattern=None, *, file=None)

     发送 ‘LIST’ 或 ‘LIST ACTIVE’ 命令。 返回一个 ‘(response, list)’ 对
     ，其中 `list' 是代表此 NNTP 服务器上所有可用新闻组的元组列表，并可
     选择匹配模式字符串 `group_pattern'。 每个元组的形式为 ‘(group,
     last, first, flag)’，其中 `group' 为新闻组名称，`last' 和 `first' 是
     最后一个和第一个文章的编号，而 `flag' 通常为下列值之一:

        * ‘y’: 允许来自对等方的本地发帖和文章。

        * ‘m’: 新闻组受到管制因而所有发帖必须经过审核。

        * ‘n’: 不允许本地发帖，只允许来自组员的文章。

        * ‘j’: 来自组员的文章会被转入垃圾分组。

        * ‘x’: 不允许本地发帖，而来自组员的文章会被忽略。

        * ‘=foo.bar’: 文章会被转入 ‘foo.bar’ 分组。

     如果 `flag' 具有其他值，则新闻组的状态应当被视为未知。

     此命令可能返回非常庞大的结果，特别是当未指明 `group_pattern' 的时候
     。 最好是离线缓存其结果，除非你确实需要刷新它们。

     3.2 版更變: 增加了 `group_pattern'。

 -- 成員函式: NNTP.descriptions (grouppattern)

     发送 ‘LIST NEWSGROUPS’ 命令，其中 `grouppattern' 为 RFC 3977(2) 中
     规定的 wildmat 字符串（它实际上与 DOS 或 UNIX shell 通配字符串相同
     ）。 返回一个 ‘(response, descriptions)’ 对，其中 `descriptions' 是
     将新闻组名称映射到文本描述的字典。

          >>> resp, descs = s.descriptions('gmane.comp.python.*')
          >>> len(descs)
          295
          >>> descs.popitem()
          ('gmane.comp.python.bio.general', 'BioPython discussion list (Moderated)')

 -- 成員函式: NNTP.description (group)

     获取单个新闻组 `group' 的描述。 如果匹配到一个以上的新闻组（如果
     ’group’ 是一个真实的 wildmat 字符串），则返回第一个匹配结果。 如果
     未匹配到任何新闻组，则返回空字符串。

     此方法略去了来自服务器的响应代码。 如果需要响应代码，请使用 *note
     descriptions(): 214.。

 -- 成員函式: NNTP.group (name)

     发送 ‘GROUP’ 命令，其中 `name' 为新闻组名称。 该新闻组如果存在，则
     会被选定为当前新闻组。 返回一个元组 ‘(response, count, first, last,
     name)’，其中 `count' 是该新闻组中（估计的）文章数量，`first' 是新闻
     组中第一篇文章的编号，`last' 是新闻组中最后一篇文章的编号，而
     `name' 是新闻组名称。

 -- 成員函式: NNTP.over (message_spec, *, file=None)

     发送 ‘OVER’ 命令，或是旧式服务器上的 ‘XOVER’ 命令。 `message_spec'
     可以是表示消息 ID 的字符串，或是指明当前新闻组内文章范围的数字元组
     ‘(first, last)’，或是指明当前新闻组内从 ‘(first, None)’ `first' 到
     最后一篇文章的元组，或者为 *note None: 203. 表示选定当前新闻组内的
     当前文章。

     返回一个 ‘(response, overviews)’ 对。 其中 `overviews' 是一个包含
     ‘(article_number, overview)’ 元组的列表，每个元组对应
     `message_spec' 所选定的一篇文章。 每个 `overview' 则是包含同样数量
     条目的字典，但具体数量取决于服务器。 这些条目或是为消息标头（对应键
     为小写的标头名称）或是为 metadata 项（对应键为以 ‘":"’ 打头的
     metadata 名称）。 以下条目会由 NNTP 规范描述来确保提供:

        * ‘subject’, ‘from’, ‘date’, ‘message-id’ 和 ‘references’ 标头

        * ‘:bytes’ metadata: 整个原始文章数据的字节数（包括标头和消息体
          ）

        * ‘:lines’ metadata: 文章消息体的行数

     每个条目的值或者为字符串，或者在没有值时为 *note None: 203.。

     建议在标头值可能包含非 ASCII 字符的时候对其使用 *note
     decode_header(): 2edf. 函数:

          >>> _, _, 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>'

     3.2 版新加入.

 -- 成員函式: NNTP.help (*, file=None)

     发送 ‘HELP’ 命令。 返回一个 ‘(response, list)’ 对，其中 `list' 为帮
     助字符串列表。

 -- 成員函式: NNTP.stat (message_spec=None)

     发送 ‘STAT’ 命令，其中 `message_spec' 为消息 ID (包裹在 ‘'<'’ 和
     ‘'>'’ 中) 或者当前新闻组中的文章编号。 如果 `message_spec' 被省略或
     为 *note None: 203.，则会选择当前新闻组中的当前文章。 反回一个三元
     组 ‘(response, number, id)’，其中 `number' 为文章编号而 `id' 为消息
     ID。

          >>> _, _, first, last, _ = s.group('gmane.comp.python.devel')
          >>> resp, number, message_id = s.stat(first)
          >>> number, message_id
          (9099, '<20030112190404.GE29873@epoch.metaslash.com>')

 -- 成員函式: NNTP.next ()

     发送 ‘NEXT’ 命令。 返回与 *note stat(): 2ee1. 类似的结果。

 -- 成員函式: NNTP.last ()

     发送 ‘LAST’ 命令。 返回与 *note stat(): 2ee1. 类似的结果。

 -- 成員函式: NNTP.article (message_spec=None, *, file=None)

     发送 ‘ARTICLE’ 命令，其中 `message_spec' 的含义与 *note stat():
     2ee1. 中的相同。 返回一个元组 ‘(response, info)’，其中 `info' 是一
     个 *note namedtuple: 1a1.，包含三个属性 `number', `message_id' 和
     `lines' (按此顺序)。 `number' 是新闻组中的文章数量 (或者如果该信息
     不可用则为 0)，`message_id' 为字符串形式的消息 ID，而 `lines' 为由
     包括标头和消息体的原始消息的行组成的列表 (不带末尾换行符)。

          >>> 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'', b'Neal']

 -- 成員函式: NNTP.head (message_spec=None, *, file=None)

     与 *note article(): 2ee4. 类似，但会发送 ‘HEAD’ 命令。 返回的
     `lines' (或写入到 `file') 将只包含消息标头，不包含消息体。

 -- 成員函式: NNTP.body (message_spec=None, *, file=None)

     与 *note article(): 2ee4. 类似，但会发送 ‘BODY’ 命令。 返回的
     `lines' (或写入到 `file') 将只包含消息体，不包含标头。

 -- 成員函式: NNTP.post (data)

     使用 ‘POST’ 命令发布文章。 `data' 参数是以二进制读取模式打开的
     *note file object: c14.，或是任意包含字节串对象的可迭代对象 (表示要
     发布的文章的原始行数据)。 它应当代表一篇适当格式的新闻组文章，包含
     所需的标头。 *note post(): 2ee7. 方法会自动对以 ‘.’ 打头的行数据进
     行转义并添加结束行。

     如果此方法执行成功，将返回服务器的响应。 如果服务器拒绝响应，则会引
     发 *note NNTPReplyError: 2ecc.。

 -- 成員函式: NNTP.ihave (message_id, data)

     发送 ‘IHAVE’ 命令。 `message_id' 为要发给服务器的消息 ID (包裹在
     ‘'<'’ 和 ‘'>'’ 中)。 `data' 形参和返回值与 *note post(): 2ee7. 的一
     致。

 -- 成員函式: NNTP.date ()

     返回一个 ‘(response, date)’ 对。 `date' 是包含服务器当前日期与时间
     的 *note datetime: 19f. 对象。

 -- 成員函式: NNTP.slave ()

     发送 ‘SLAVE’ 命令。 返回服务器的 `响应'。

 -- 成員函式: NNTP.set_debuglevel (level)

     设置实例的调试级别。 它控制着打印调试输出信息的数量。 默认值 ‘0’ 不
     产生调试输出。 值 ‘1’ 产生中等数量的调试输出，通常每个请求或响应各
     产生一行。 大于等于 ‘2’ 的值产生最多的调试输出，在连接上发送和接收
     的每一行信息都会被记录下来（包括消息文本）。

以下是在 RFC 2980(3) 中定义的可选 NNTP 扩展。 其中一些已被 RFC 3977(4) 中
的新命令所取代。

 -- 成員函式: NNTP.xhdr (hdr, str, *, file=None)

     发送 ‘XHDR’ 命令。 `hdr' 参数是标头关键字，例如 ‘'subject'’。 `str'
     参数的形式应为 ‘'first-last'’，其中 `first' 和 `last' 是要搜索的首
     篇和末篇文章编号。 返回一个 ‘(response, list)’ 对，其中 `list' 是
     ‘(id, text)’ 对的列表，其中 `id' 是文章编号（字符串类型）而 `text'
     是该文章的请求标头。 如果提供了 `file' 形参，则 ‘XHDR’ 命令的输出会
     保存到文件中。 如果 `file' 为字符串，则此方法将打开指定名称的文件，
     向其写入内容并将其关闭。 如果 `file' 为 *note file object: c14.，则
     将在该文件对象上调用 ‘write()’ 方法来保存命令所输出的行信息。 如果
     提供了 `file'，则返回的 `list' 将为空列表。

 -- 成員函式: NNTP.xover (start, end, *, file=None)

     发送 ‘XOVER’ 命令。 `start' 和 `end' 是限制所选取文章范围的文章编号
     。 返回值与 *note over(): 2ede. 的相同。 推荐改用 *note over():
     2ede.，因为它将在可能的情况下自动使用更新的 ‘OVER’ 命令。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc3977.html

   (2) https://tools.ietf.org/html/rfc3977.html

   (3) https://tools.ietf.org/html/rfc2980.html

   (4) https://tools.ietf.org/html/rfc3977.html


File: python.info,  Node: 工具函数<2>,  Prev: NNTP 对象,  Up: nntplib --- NNTP 协议客户端

5.21.16.4 工具函数
..................

这个模块还定义了下列工具函数:

 -- 函式: nntplib.decode_header (header_str)

     解码标头值，恢复任何被转义的非 ASCII 字符。 `header_str' 必须为
     *note str: 205. 对象。 将返回被恢复的值。 推荐使用此函数来以人类可
     读的形式显示某些标头:

          >>> 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'


File: python.info,  Node: smtplib ---SMTP协议客户端,  Next: smtpd --- SMTP 服务器,  Prev: nntplib --- NNTP 协议客户端,  Up: 互联网协议和支持

5.21.17 ‘smtplib’ —SMTP协议客户端
---------------------------------

`源代码：' Lib/smtplib.py(1)

__________________________________________________________________

*note smtplib: ed. 模块定义了一个 SMTP 客户端会话对象，该对象可将邮件发
送到 Internet 上带有 SMTP 或 ESMTP 接收程序的计算机。 关于 SMTP 和 ESMTP
操作的详情请参阅 RFC 821(2) (简单邮件传输协议) 和 RFC 1869(3) (SMTP 服务
扩展)。

 -- 類別: smtplib.SMTP (host='', port=0, local_hostname=None[, timeout],
          source_address=None)

     一个 *note SMTP: 1de. 实例就是一个封装好的 SMTP 连接。该实例具有的
     方法支持所有 SMTP 和 ESMTP 操作。如果传入了可选参数 host 和 port，
     那么将在初始化时使用这些参数调用 SMTP *note connect(): 10cd. 方法。
     如果传入了 `local_hostname'，它将在 HELO/EHLO 命令中被用作本地主机
     的 FQDN。否则将使用 *note socket.getfqdn(): 27d9. 找到本地主机名。
     如果 *note connect(): 10cd. 返回了成功码以外的内容，则引发 *note
     SMTPConnectError: 2ef1. 异常。可选参数 `timeout' 指定阻塞操作（如连
     接尝试）的超时（以秒为单位，如果未指定超时，将使用全局默认超时设置
     ）。到达超时时长后会引发 *note socket.timeout: cd9. 异常。可选参数
     source_address 允许在有多张网卡的计算机中绑定到某些特定的源地址，和
     /或绑定到某些特定的源 TCP 端口。在连接前，套接字需要绑定一个 2 元组
     (host, port) 作为其源地址。如果省略，或者是主机为 ‘''’ 和/或端口为
     0，则将使用操作系统默认行为。

     正常使用时，只需要初始化或 connect 方法，*note sendmail(): 833. 方
     法，再加上 *note SMTP.quit(): 2ef2. 方法即可。下文包括了一个示例。

     *note SMTP: 1de. 类支持 *note with: 7da. 语句。当这样使用时，‘with’
     语句一退出就会自动发出 SMTP ‘QUIT’ 命令。例如:

          >>> from smtplib import SMTP
          >>> with SMTP("domain.org") as smtp:
          ...     smtp.noop()
          ...
          (250, b'Ok')
          >>>

     引发一个 *note 审计事件: fa1. ‘smtplib.send’，附带参数 ‘self’,
     ‘data’。

     3.3 版更變: 支持了 *note with: 7da. 语句。

     3.3 版更變: 添加了 source_address 参数。

     3.5 版新加入: 现在已支持 SMTPUTF8 扩展 ( RFC 6531(4))。

     3.9 版更變: 如果 `timeout' 形参被设为零，则它将引发 *note
     ValueError: 16d. 来阻止创建非阻塞的套接字

 -- 類別: smtplib.SMTP_SSL (host='', port=0, local_hostname=None,
          keyfile=None, certfile=None[, timeout], context=None,
          source_address=None)

     *note SMTP_SSL: 1df. 实例与 *note SMTP: 1de. 实例的行为完全相同。在
     开始连接就需要 SSL，且 ‘starttls()’ 不适合的情况下，应该使用 *note
     SMTP_SSL: 1df.。如果未指定 `host'，则使用 localhost。如果 `port' 为
     0，则使用标准 SMTP-over-SSL 端口（465）。可选参数 `local_hostname'、
     `timeout' 和 `source_address' 的含义与 *note SMTP: 1de. 类中的相同
     。可选参数 `context' 是一个 *note SSLContext: 4e9. 对象，可以从多个
     方面配置安全连接。请阅读 *note 安全考量: 26fd. 以获取最佳实践。

     `keyfile' 和 `certfile' 是 `context' 的传统替代物，它们可以指向 PEM
     格式的私钥和证书链文件用于 SSL 连接。

     3.3 版更變: 增加了 `context'。

     3.3 版更變: 添加了 source_address 参数。

     3.4 版更變: 本类现在支持通过 *note ssl.SSLContext.check_hostname:
     2812. 和 `服务器名称提示' （参阅 *note ssl.HAS_SNI: 2827.）进行主机
     名检查。

     3.6 版後已棄用: `keyfile' 和 `certfile' 已弃用并转而推荐 `context'。
     请改用 *note ssl.SSLContext.load_cert_chain(): b69. 或让 *note
     ssl.create_default_context(): 9a7. 为你选择系统所信任的 CA 证书。

     3.9 版更變: 如果 `timeout' 形参被设为零，则它将引发 *note
     ValueError: 16d. 来阻止创建非阻塞的套接字

 -- 類別: smtplib.LMTP (host='', port=LMTP_PORT, local_hostname=None,
          source_address=None[, timeout])

     LMTP 协议与 ESMTP 非常相似，它很大程度上基于标准的 SMTP 客户端。将
     Unix 套接字用于 LMTP 是很常见的，因此 ‘connect()’ 方法支持 Unix 套
     接字，也支持常规的 host:port 服务器。可选参数 local_hostname 和
     source_address 的含义与 *note SMTP: 1de. 类中的相同。要指定 Unix 套
     接字，`host' 必须使用绝对路径，以 ’/’ 开头。

     支持使用常规的 SMTP 机制来进行认证。 当使用 Unix 套接字时，LMTP 通
     常不支持或要求任何认证，但你的情况可能会有所不同。

     3.9 版更變: 添加了可选的 `timeout' 形参。

同样地定义了一组精心选择的异常:

 -- 例外: smtplib.SMTPException

     *note OSError: 304. 的子类，它是本模块提供的所有其他异常的基类。

     3.4 版更變: SMTPException 已成为 *note OSError: 304. 的子类

 -- 例外: smtplib.SMTPServerDisconnected

     当服务器意外断开连接，或在 *note SMTP: 1de. 实例连接到服务器之前尝
     试使用它时将引发此异常。

 -- 例外: smtplib.SMTPResponseException

     包括 SMTP 错误代码的所有异常的基类。 这些异常会在 SMTP 服务器返回错
     误代码时在实例中生成。 错误代码存放在错误的 ‘smtp_code’ 属性中，并
     且 ‘smtp_error’ 属性会被设为错误消息。

 -- 例外: smtplib.SMTPSenderRefused

     发送方地址被拒绝。 除了在所有 *note SMTPResponseException: 2ef4. 异
     常上设置的属性，还会将 ’sender’ 设为代表拒绝方 SMTP 服务器的字符串
     。

 -- 例外: smtplib.SMTPRecipientsRefused

     所有接收方地址被拒绝。 每个接收方的错误可通过属性 ‘recipients’ 来访
     问，该属性是一个字典，其元素顺序与 *note SMTP.sendmail(): 833. 所返
     回的一致。

 -- 例外: smtplib.SMTPDataError

     SMTP 服务器拒绝接收消息数据。

 -- 例外: smtplib.SMTPConnectError

     在建立与服务器的连接期间发生了错误。

 -- 例外: smtplib.SMTPHeloError

     服务器拒绝了我们的 ‘HELO’ 消息。

 -- 例外: smtplib.SMTPNotSupportedError

     尝试的命令或选项不被服务器所支持。

     3.5 版新加入.

 -- 例外: smtplib.SMTPAuthenticationError

     SMTP 认证出现问题。 最大的可能是服务器不接受所提供的用户名/密码组合
     。

也參考
......

RFC 821(5) - 简单邮件传输协议

     SMTP 的协议定义。 该文件涵盖了 SMTP 的模型、操作程序和协议细节。

RFC 1869(6) - SMTP 服务扩展

     定义了 SMTP 的 ESMTP 扩展。 这描述了一个用新命令扩展 SMTP 的框架，
     支持动态发现服务器所提供的命令，并定义了一些额外的命令。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/smtplib.py

   (2) https://tools.ietf.org/html/rfc821.html

   (3) https://tools.ietf.org/html/rfc1869.html

   (4) https://tools.ietf.org/html/rfc6531.html

   (5) https://tools.ietf.org/html/rfc821.html

   (6) https://tools.ietf.org/html/rfc1869.html


File: python.info,  Node: SMTP 对象,  Next: SMTP 示例,  Up: smtplib ---SMTP协议客户端

5.21.17.1 SMTP 对象
...................

一个 *note SMTP: 1de. 实例拥有以下方法：

 -- 成員函式: SMTP.set_debuglevel (level)

     设置调试输出级别。 如果 `level' 的值为 1 或 ‘True’ ，就会产生连接的
     调试信息，以及所有发送和接收服务器的信息。 如果 `level' 的值为 2 ，
     则这些信息会被加上时间戳。

     3.5 版更變: 添调试级别 2 。

 -- 成員函式: SMTP.docmd (cmd, args='')

     向服务器发送一条命令 `cmd' 。 可选的参数 `args' 被简单地串联到命令
     中，用一个空格隔开。

     这将返回一个由数字响应代码和实际响应行组成的2元组（多行响应被连接成
     一个长行）。

     在正常操作中，应该没有必要明确地调用这个方法。它被用来实现其他方法
     ，对于测试私有扩展可能很有用。

     如果在等待回复的过程中，与服务器的连接丢失， *note
     SMTPServerDisconnected: 2ef3. 将被触发。

 -- 成員函式: SMTP.connect (host='localhost', port=0)

     连接到某个主机的某个端口。默认是连接到 localhost 的标准 SMTP 端口（
     25）上。如果主机名以冒号 (‘':'’) 结尾，后跟数字，则该后缀将被删除，
     且数字将视作要使用的端口号。如果在实例化时指定了 host，则构造函数会
     自动调用本方法。返回包含响应码和响应消息的 2 元组，它们由服务器在其
     连接响应中发送。

     触发一个 *note auditing event: fa1. ‘smtplib.connect’，其参数为
     ‘self’ ， ‘host’ ， ‘port’ 。

 -- 成員函式: SMTP.helo (name='')

     使用 ‘HELO’ 向 SMTP 服务器表明自己的身份。 hostname 参数默认为本地
     主机的完全合格域名。服务器返回的消息被存储为对象的 ‘helo_resp’ 属性
     。

     在正常操作中，应该没有必要明确调用这个方法。它将在必要时被 *note
     sendmail(): 833. 隐式调用。

 -- 成員函式: SMTP.ehlo (name='')

     使用 ‘EHLO’ 向 ESMTP 服务器标识自身。hostname 参数默认为 localhost
     的标准域名。使用 *note has_extn(): 2eff. 来检查响应中的 ESMTP 选项
     ，并将它们保存起来。还给一些信息性的属性赋值：服务器返回的消息存储
     为 ‘ehlo_resp’ 属性；根据服务器是否支持 ESMTP，将 ‘does_esmtp’ 设置
     为 true 或 false；而 ‘esmtp_features’ 是一个字典，包含该服务器支持
     的 SMTP 服务扩展的名称及参数（如果有参数）。

     除非你想在发送邮件前使用 *note has_extn(): 2eff. ，否则应该没有必要
     明确调用这个方法。 它将在必要时被 *note sendmail(): 833. 隐式调用。

 -- 成員函式: SMTP.ehlo_or_helo_if_needed ()

     如果这个会话中没有先前的 ‘EHLO’ 或 ‘HELO’ 命令，该方法会调用 *note
     ehlo(): 2efe. 和/或 *note helo(): 2efd. 。它首先尝试 ESMTP ‘EHLO’ 。

     *note SMTPHeloError: 2ef8.

          服务器没有正确回复 ‘HELO’ 问候。

 -- 成員函式: SMTP.has_extn (name)

     如果 `name' 在服务器返回的 SMTP 服务扩展集合中，返回 *note True:
     593. ，否则为 *note False: 48e. 。大小写被忽略。

 -- 成員函式: SMTP.verify (address)

     使用 SMTP ‘VRFY’ 检查此服务器上的某个地址是否有效。 如果用户地址有
     效则返回一个由代码 250 和完整 RFC 822(1) 地址（包括人名）组成的元组
     。 否则返回 400 或更大的 SMTP 错误代码以及一个错误字符串。

          備註: 许多网站都禁用 SMTP ‘VRFY’ 以阻止垃圾邮件。

 -- 成員函式: SMTP.login (user, password, *, initial_response_ok=True)

     登录到一个需要认证的 SMTP 服务器。 参数是用于认证的用户名和密码。 如
     果会话在之前没有执行过 ‘EHLO’ 或 ‘HELO’ 命令，此方法会先尝试 ESMTP
     ‘EHLO’。 如果认证成功则此方法将正常返回，否则可能引发以下异常:

     *note SMTPHeloError: 2ef8.

          服务器没有正确回复 ‘HELO’ 问候。

     *note SMTPAuthenticationError: 2ef9.

          服务器不接受所提供的用户名/密码组合。

     *note SMTPNotSupportedError: 10cb.

          服务器不支持 ‘AUTH’ 命令。

     *note SMTPException: 99e.

          未找到适当的认证方法。

     *note smtplib: ed. 所支持的每种认证方法只要被服务器声明支持就会被依
     次尝试。 请参阅 *note auth(): 831. 获取受支持的认证方法列表。
     `initial_response_ok' 会被传递给 *note auth(): 831.。

     可选的关键字参数 `initial_response_ok' 对于支持它的认证方法，是否可
     以与 ‘AUTH’ 命令一起发送 RFC 4954(2) 中所规定的“初始响应”，而不是要
     求回复/响应。

     3.5 版更變: 可能会引发 *note SMTPNotSupportedError: 10cb.，并添加
     `initial_response_ok' 形参。

 -- 成員函式: SMTP.auth (mechanism, authobject, *,
          initial_response_ok=True)

     为指定的认证机制 `mechanism' 发送 ‘SMTP’ ‘AUTH’ 命令，并通过
     `authobject' 处理回复响应。

     `mechanism' 指定要使用何种认证机制作为 ‘AUTH’ 命令的参数；可用的值
     是在 ‘esmtp_features’ 的 ‘auth’ 元素中列出的内容。

     `authobject' 必须是接受一个可选的单独参数的可调用对象:

          data = authobject(challenge=None)

     如果可选的关键字参数 `initial_response_ok' 为真值，则将先不带参数地
     调用 ‘authobject()’。 它可以返回 RFC 4954(3) "初始响应" ASCII
     ‘str’，其内容将被编码并使用下述的 ‘AUTH’ 命令来发送。 如果
     ‘authobject()’ 不支持初始响应（例如由于要求一个回复），它应当将
     ‘None’ 作为附带 ‘challenge=None’ 调用的返回值。 如果
     `initial_response_ok' 为假值，则 ‘authobject()’ 将不会附带 ‘None’ 被
     首先调用。

     如果初始响应检测返回了 ‘None’，或者如果 `initial_response_ok' 为假
     值，则将调用 ‘authobject()’ 来处理服务器的回复响应；它所传递的
     `challenge' 参数将为一个 ‘bytes’。 它应当返回用 base64 进行编码的
     ASCII ‘str’ `data' 并发送给服务器。

     ‘SMTP’ 类提供的 ‘authobjects’ 针对 ‘CRAM-MD5’, ‘PLAIN’ 和 ‘LOGIN’ 等
     机制；它们的名称分别是 ‘SMTP.auth_cram_md5’, ‘SMTP.auth_plain’ 和
     ‘SMTP.auth_login’。 它们都要求将 ‘user’ 和 ‘password’ 这两个 ‘SMTP’
     实例属性设为适当的值。

     用户代码通常不需要直接调用 ‘auth’，而是调用 *note login(): 2f02. 方
     法，它将按上述顺序依次尝试上述每一种机制。 ‘auth’ 被公开以便辅助实
     现 *note smtplib: ed. 没有（或尚未）直接支持的认证方法。

     3.5 版新加入.

 -- 成員函式: SMTP.starttls (keyfile=None, certfile=None, context=None)

     将 SMTP 连接设为 TLS (传输层安全) 模式。 后续的所有 SMTP 命令都将被
     加密。 你应当随即再次调用 *note ehlo(): 2efe.。

     如果提供了 `keyfile' 和 `certfile'，它们会被用来创建 *note
     ssl.SSLContext: 4e9.。

     可选的 `context' 形参是一个 *note ssl.SSLContext: 4e9. 对象；它是使
     用密钥文件和证书的替代方式，如果指定了该形参则 `keyfile' 和
     `certfile' 都应为 ‘None’。

     如果这个会话中没有先前的 ‘EHLO’ or ‘HELO’ 命令，该方法会首先尝试
     ESMTP ‘EHLO’。

     3.6 版後已棄用: `keyfile' 和 `certfile' 已弃用并转而推荐 `context'。
     请改用 *note ssl.SSLContext.load_cert_chain(): b69. 或让 *note
     ssl.create_default_context(): 9a7. 为你选择系统所信任的 CA 证书。

     *note SMTPHeloError: 2ef8.

          服务器没有正确回复 ‘HELO’ 问候。

     *note SMTPNotSupportedError: 10cb.

          服务器不支持 STARTTLS 扩展。

     *note RuntimeError: 3dc.

          SSL/TLS 支持在你的 Python 解释器上不可用。

     3.3 版更變: 增加了 `context'。

     3.4 版更變: 此方法现在支持使用 ‘SSLContext.check_hostname’ 和 `服务
     器名称指示符' (参见 *note HAS_SNI: 2827.) 进行主机名检查。

     3.5 版更變: 因缺少 STARTTLS 支持而引发的错误现在是 *note
     SMTPNotSupportedError: 10cb. 子类而不是 *note SMTPException: 99e. 基
     类。

 -- 成員函式: SMTP.sendmail (from_addr, to_addrs, msg, mail_options=(),
          rcpt_options=())

     发送邮件。必要参数是一个 RFC 822(4) 发件地址字符串，一个 RFC 822(5)
     收件地址字符串列表（裸字符串将被视为含有 1 个地址的列表），以及一个
     消息字符串。调用者可以将 ESMTP 选项列表（如 ‘8bitmime’）作为
     `mail_options' 传入，用于 ‘MAIL FROM’ 命令。需要与所有 ‘RCPT’ 命令
     一起使用的 ESMTP 选项（如 ‘DSN’ 命令）可以作为 `rcpt_options' 传入
     。（如果需要对不同的收件人使用不同的 ESMTP 选项，则必须使用底层的方
     法来发送消息，如 ‘mail()’, ‘rcpt()’ 和 ‘data()’。）

          備註: `from_addr' 和 `to_addrs' 形参被用来构造传输代理所使用的
          消息封包。 ‘sendmail’ 不会以任何方式修改消息标头。

     `msg' 可以是一个包含 ASCII 范围内字符的字符串，或是一个字节串。 字
     符串会使用 ascii 编解码器编码为字节串，并且单独的 ‘\r’ 和 ‘\n’ 字符
     会被转换为 ‘\r\n’ 字符序列。 字节串则不会被修改。

     如果在此之前本会话没有执行过 ‘EHLO’ 或 ‘HELO’ 命令，此方法会先尝试
     ESMTP ‘EHLO’。 如果服务器执行了 ESMTP，消息大小和每个指定的选项将被
     传递给它（如果指定的选项属于服务器声明的特性集）。 如果 ‘EHLO’ 失败
     ，则将尝试 ‘HELO’ 并屏蔽 ESMTP 选项。

     如果邮件被至少一个接收方接受则此方法将正常返回。 在其他情况下它将引
     发异常。 也就是说，如果此方法没有引发异常，则应当会有人收到你的邮件
     。 如果此方法没有引发异常，它将返回一个字典，其中的条目对应每个拒绝
     的接收方。 每个条目均包含由服务器发送的 SMTP 错误代码和相应错误消息
     所组成的元组。

     如果 ‘SMTPUTF8’ 包括在 `mail_options' 中，并且被服务器所支持，则
     `from_addr' 和 `to_addrs' 可能包含非 ASCII 字符。

     此方法可能引发以下异常:

     *note SMTPRecipientsRefused: 2ef6.

          所有收件人都被拒绝。 无人收到邮件。 该异常的 ‘recipients’ 属性
          是一个字典，其中有被拒绝收件人的信息（类似于至少有一个收件人接
          受邮件时所返回的信息）。

     *note SMTPHeloError: 2ef8.

          服务器没有正确回复 ‘HELO’ 问候。

     *note SMTPSenderRefused: 2ef5.

          服务器不接受 `from_addr'。

     *note SMTPDataError: 2ef7.

          服务器回复了一个意外的错误代码（而不是拒绝收件人）。

     *note SMTPNotSupportedError: 10cb.

          在 `mail_options' 中给出了 ‘SMTPUTF8’ 但是不被服务器所支持。

     除非另有说明，即使在引发异常之后连接仍将被打开。

     3.2 版更變: `msg' 可以为字节串。

     3.5 版更變: 增加了 ‘SMTPUTF8’ 支持，并且如果指定了 ‘SMTPUTF8’ 但是
     不被服务器所支持则可能会引发 *note SMTPNotSupportedError: 10cb.。

 -- 成員函式: SMTP.send_message (msg, from_addr=None, to_addrs=None,
          mail_options=(), rcpt_options=())

     本方法是一种快捷方法，用于带着消息调用 *note sendmail(): 833.，消息
     由 *note email.message.Message: 63b. 对象表示。参数的含义与 *note
     sendmail(): 833. 中的相同，除了 `msg'，它是一个 ‘Message’ 对象。

     如果 `from_addr' 为 ‘None’ 或 `to_addrs' 为 ‘None’，那么
     ‘‘send_message‘‘将根据 RFC 5322(6)，从 `msg' 头部提取地址填充下列参
     数：如果头部存在 ‘Sender’ 字段，则用它填充 `from_addr'，不存在则用
     ‘From’ 字段填充 `from_addr'。`to_addrs' 组合了 `msg' 中的 ‘To’,
     ‘Cc’ 和 ‘Bcc’ 字段的值（字段存在的情况下）。如果一组 ‘Resent-*’ 头
     部恰好出现在 message 中，那么就忽略常规的头部，改用 ‘Resent-*’ 头部
     。如果 message 包含多组 ‘Resent-*’ 头部，则引发 *note ValueError:
     16d.，因为无法明确检测出哪一组 ‘Resent-’ 头部是最新的。

     ‘send_message’ 使用 *note BytesGenerator: c1f. 来序列化 `msg'，且将
     ‘\r\n’ 作为 `linesep'，并调用 *note sendmail(): 833. 来传输序列化后
     的结果。无论 `from_addr' 和 `to_addrs' 的值为何，‘send_message’ 都
     不会传输 `msg' 中可能出现的 ‘Bcc’ 或 ‘Resent-Bcc’ 头部。如果
     `from_addr' 和 `to_addrs' 中的某个地址包含非 ASCII 字符，且服务器没
     有声明支持 ‘SMTPUTF8’，则引发 ‘SMTPNotSupported’ 错误。如果服务器支
     持，则 ‘Message’ 将按新克隆的 *note policy: 73. 进行序列化，其中的
     *note utf8: 7c5. 属性被设置为 ‘True’，且 ‘SMTPUTF8’ 和
     ‘BODY=8BITMIME’ 被添加到 `mail_options' 中。

     3.2 版新加入.

     3.5 版新加入: 支持国际化地址 (‘SMTPUTF8’)。

 -- 成員函式: SMTP.quit ()

     终结 SMTP 会话并关闭连接。 返回 SMTP ‘QUIT’ 命令的结果。

与标准 SMTP/ESMTP 命令 ‘HELP’, ‘RSET’, ‘NOOP’, ‘MAIL’, ‘RCPT’ 和 ‘DATA’
对应的低层级方法也是受支持的。 通常不需要直接调用这些方法，因此它们没有
被写入本文档。 相关细节请参看模块代码。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc822.html

   (2) https://tools.ietf.org/html/rfc4954.html

   (3) https://tools.ietf.org/html/rfc4954.html

   (4) https://tools.ietf.org/html/rfc822.html

   (5) https://tools.ietf.org/html/rfc822.html

   (6) https://tools.ietf.org/html/rfc5322.html


File: python.info,  Node: SMTP 示例,  Prev: SMTP 对象,  Up: smtplib ---SMTP协议客户端

5.21.17.2 SMTP 示例
...................

这个例子提示用户输入消息封包所需的地址 (’To’ 和 ’From’ 地址)，以及所要封
包的消息。 请注意包括在消息中的标头必须包括在输入的消息中；这个例子不对
RFC 822(1) 标头进行任何处理。 特别地，’To’ 和 ’From’ 地址必须显式地包括
在消息标头中。

     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()

     備註: 通常，你将需要使用 *note email: 67. 包的特性来构造电子邮件消
     息，然后你可以通过 *note send_message(): 834. 来发送它，参见 *note
     email; 示例: 932.。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc822.html


File: python.info,  Node: smtpd --- SMTP 服务器,  Next: telnetlib -- Telnet 客户端,  Prev: smtplib ---SMTP协议客户端,  Up: 互联网协议和支持

5.21.18 ‘smtpd’ — SMTP 服务器
-----------------------------

`源代码:' Lib/smtpd.py(1)

__________________________________________________________________

该模块提供了几个类来实现 SMTP （电子邮件）服务器。

也參考
......

The aiosmtpd(2) package is a recommended replacement for this module.
It is based on *note asyncio: 9. and provides a more straightforward
API. *note smtpd: ec. should be considered deprecated.

有几个服务器的实现；一个是通用的无为实现，可以被重写，而另外两个则提供特
定的邮件发送策略。

此外， SMTPChannel 可以被扩展以实现与 SMTP 客户端非常具体的交互行为。

该代码支持 RFC 5321(3) ，加上 RFC 1870(4) SIZE和 RFC 6531(5) SMTPUTF8 扩
展。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/smtpd.py

   (2) http://aiosmtpd.readthedocs.io/

   (3) https://tools.ietf.org/html/rfc5321.html

   (4) https://tools.ietf.org/html/rfc1870.html

   (5) https://tools.ietf.org/html/rfc6531.html


File: python.info,  Node: SMTPServer 对象,  Next: DebuggingServer 对象,  Up: smtpd --- SMTP 服务器

5.21.18.1 SMTPServer 对象
.........................

 -- 類別: smtpd.SMTPServer (localaddr, remoteaddr,
          data_size_limit=33554432, map=None, enable_SMTPUTF8=False,
          decode_data=False)

     新建一个 *note SMTPServer: 6f9. 对象，它会绑定到本机地址
     `localaddr'。 它将把 `remoteaddr' 当作上游 SMTP 中继器。
     `localaddr' 和 `remoteaddr' 都应当是 *note (host, port): 27b4. 元组
     。 该对象继承自 *note asyncore.dispatcher: c91.，因而会在实例化时将
     自己插入到 *note asyncore: a. 的事件循环。

     `data_size_limit' 指定将在 ‘DATA’ 命令中被接受的最大字节数。 值为
     ‘None’ 或 ‘0’ 表示无限制。

     `map' 是用于连接的套接字映射（初始为空的字典是适当的值）。 如果未指
     定则会使用 *note asyncore: a. 全局套接字映射。

     `enable_SMTPUTF8' 决定是否应当启用 ‘SMTPUTF8’ 扩展（如 RFC 6531(1)
     所定义的。 默认值为 ‘False’。 当设为 ‘True’ 时，会接受 ‘SMTPUTF8’ 作
     为 ‘MAIL’ 命令的形参并在被提供时将其传给 ‘kwargs['mail_options']’ 列
     表中的 *note process_message(): 6fa.。 `decode_data' 和
     `enable_SMTPUTF8' 不可同时被设为 ‘True’。

     `decode_data' 指明 SMTP 事务的数据部分是否应当使用 UTF-8 来解码。 当
     `decode_data' 为 ‘False’ 时（默认值），服务器会声明 ‘8BITMIME’ 扩展
     ( RFC 6152(2))，接受来自 ‘MAIL’ 命令的 ‘BODY=8BITMIME’ 形参，并在该
     形参存在时将其传给 ‘kwargs['mail_options']’ 列表中的 *note
     process_message(): 6fa. 方法。 `decode_data' 和 `enable_SMTPUTF8' 不
     可同时被设为 ‘True’。

      -- 成員函式: process_message (peer, mailfrom, rcpttos, data,
               **kwargs)

          引发 *note NotImplementedError: 704. 异常。 请在子类中重载此方
          法以实际运用此消息。 在构造器中作为 `remoteaddr' 传入的任何东
          西都可以 ‘_remoteaddr’ 属性的形式来访问。 `peer' 是远程主机的
          地址，`mailfrom' 是封包的发送方，`rcpttos' 是封包的接收方而
          `data' 是包含电子邮件内容的字符串（应该为 RFC 5321(3) 格式）。

          如果构造器关键字参数 `decode_data' 被设为 ‘True’，则 `data' 参
          数将为 Unicode 字符串。 如果被设为 ‘False’，则将为字节串对象。

          `kwargs' 是包含附加信息的字典。 如果给出 ‘decode_data=True’ 作
          为初始参数则该字典为空，否则它会包含以下的键:

               `mail_options':

                    由 ‘MAIL’ 命令所接收的所有参数组成的列表 (其元素为大
                    写形式的字符串；例如: ‘['BODY=8BITMIME',
                    'SMTPUTF8']’)。

               `rcpt_options':

                    与 `mail_options' 类似但是针对 ‘RCPT’ 命令。 目前不
                    支持任何 ‘RCPT TO’ 选项，因此其值将总是为空列表。

          ‘process_message’ 的实现应当使用 ‘**kwargs’ 签名来接收任意关键
          字参数，因为未来的增强特性可能会向 kwargs 字典添加新键。

          返回 ‘None’ 以请求一个正常的 ‘250 Ok’ 响应；在其他情况下则以
          RFC 5321(4) 格式返回所需的响应字符串。

      -- 屬性: channel_class

          重载这个子类以使用自定义的 *note SMTPChannel: 6f8. 来管理 SMTP
          客户端。

     3.4 版新加入: `map' 构造器参数。

     3.5 版更變: `localaddr' 和 `remoteaddr' 现在可以包含 IPv6 地址。

     3.5 版新加入: `decode_data' 和 `enable_SMTPUTF8' 构造器形参，以及当
     `decode_data' 为 ‘False’ 时传给 *note process_message(): 6fa. 的
     `kwargs' 形参。

     3.6 版更變: `decode_data' 现在默认为 ‘False’。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc6531.html

   (2) https://tools.ietf.org/html/rfc6152.html

   (3) https://tools.ietf.org/html/rfc5321.html

   (4) https://tools.ietf.org/html/rfc5321.html


File: python.info,  Node: DebuggingServer 对象,  Next: PureProxy对象,  Prev: SMTPServer 对象,  Up: smtpd --- SMTP 服务器

5.21.18.2 DebuggingServer 对象
..............................

 -- 類別: smtpd.DebuggingServer (localaddr, remoteaddr)

     创建一个新的调试服务器。 参数是针对每个 *note SMTPServer: 6f9.。 消
     息将被丢弃，并在 stdout 上打印出来。


File: python.info,  Node: PureProxy对象,  Next: MailmanProxy 对象,  Prev: DebuggingServer 对象,  Up: smtpd --- SMTP 服务器

5.21.18.3 PureProxy对象
.......................

 -- 類別: smtpd.PureProxy (localaddr, remoteaddr)

     创建一个新的纯代理服务器。 参数是针对每个 *note SMTPServer: 6f9.。
     一切都将被转发到 `remoteaddr'。 请注意运行此对象有很大的机会令你成
     为一个开放的中继站，所以需要小心。


File: python.info,  Node: MailmanProxy 对象,  Next: SMTPChannel 对象,  Prev: PureProxy对象,  Up: smtpd --- SMTP 服务器

5.21.18.4 MailmanProxy 对象
...........................

 -- 類別: smtpd.MailmanProxy (localaddr, remoteaddr)

     Deprecated since version 3.9, will be removed in version 3.11:
     *note MailmanProxy: 211. 已被弃用，它依赖于一个已不存在的 ‘Mailman’
     模块因而本来就不再可用了。

     创建一个新的纯代理服务器。 参数是针对每个 *note SMTPServer: 6f9.。
     一切都将被转发到 `remoteaddr'，除非本地 mailman 配置知道另一个地址
     ，在那种情况下它将由 mailman 来处理。 请注意运行此对象有很大的机会
     令你成为一个开放的中继站，所以需要小心。


File: python.info,  Node: SMTPChannel 对象,  Prev: MailmanProxy 对象,  Up: smtpd --- SMTP 服务器

5.21.18.5 SMTPChannel 对象
..........................

 -- 類別: smtpd.SMTPChannel (server, conn, addr,
          data_size_limit=33554432, map=None, enable_SMTPUTF8=False,
          decode_data=False)

     创建一个新的 *note SMTPChannel: 6f8. 对象，该对象会管理服务器和单个
     SMTP 客户端之间的通信。

     `conn' 和 `addr' 是针对下述的每个实例变量。

     `data_size_limit' 指定将在 ‘DATA’ 命令中被接受的最大字节数。 值为
     ‘None’ 或 ‘0’ 表示无限制。

     `enable_SMTPUTF8' 确定 ‘SMTPUTF8’ 扩展 (如 RFC 6531(1) 所定义的) 是
     否应当被启用。 默认值为 ‘False’。 `decode_data' 和
     `enable_SMTPUTF8' 不能被同时设为 ‘True’。

     可以在 `map' 中指定一个字典以避免使用全局套接字映射。

     `decode_data' 指明 SMTP 事务的数据部分是否应当使用 UTF-8 来解码。 默
     认值为 ‘False’。 `decode_data' 和 `enable_SMTPUTF8' 不能被同时设为
     ‘True’。

     要使用自定义的 SMTPChannel 实现你必须重载你的 *note SMTPServer:
     6f9. 的 *note SMTPServer.channel_class: 2f08.。

     3.5 版更變: 添加了 `decode_data' 和 `enable_SMTPUTF8' 形参。

     3.6 版更變: `decode_data' 现在默认为 ‘False’。

     *note SMTPChannel: 6f8. 具有下列实例变量:

      -- 屬性: smtp_server

          存放生成此通道的 *note SMTPServer: 6f9.。

      -- 屬性: conn

          存放连接到客户端的套接字对象。

      -- 屬性: addr

          存放客户端的地址，*note socket.accept: 768. 所返回的第二个值。

      -- 屬性: received_lines

          存放从客户端接收的行字符串列表 (使用 UTF-8 解码)。 所有行的
          ‘"\r\n"’ 行结束符都会被转写为 ‘"\n"’。

      -- 屬性: smtp_state

          存放通道的当前状态。 其初始值将为 ‘COMMAND’ 而在客户端发送
          "DATA" 行后将为 ‘DATA’。

      -- 屬性: seen_greeting

          存放包含客户端在其 "HELO" 中发送的问候信息的字符串。

      -- 屬性: mailfrom

          存放包含客户端在 "MAIL FROM:" 中标识的地址的字符串。

      -- 屬性: rcpttos

          存放包含客户端在 "RCPT TO:" 行中标识的地址的字符串。

      -- 屬性: received_data

          存放客户端在 DATA 状态期间发送的所有数据的字符串，直至但不包括
          末尾的 ‘"\r\n.\r\n"’。

      -- 屬性: fqdn

          存放由 *note socket.getfqdn(): 27d9. 所返回的服务器完整限定域
          名。

      -- 屬性: peer

          存放由 ‘conn.getpeername()’ 所返回的客户端对等方名称，其中
          ‘conn’ 为 *note conn: 2f10.。

     *note SMTPChannel: 6f8. 在接收到来自客户端的命令行时会通过发起调用
     名为 ‘smtp_<command>’ 的方法来进行操作。 在基类 *note SMTPChannel:
     6f8. 中具有用于处理下列命令（并对他们作出适当反应）的方法:

     命令         所采取的行动
                  
     -------------------------------------------------------------------------------------
                  
     HELO         接受来自客户端的问候语，并将其存储在 *note seen_greeting: 2f14. 中。
                  将服务器设置为基本命令模式。
                  
                  
     EHLO         接受来自客户的问候并将其存储在 *note seen_greeting: 2f14. 中。将服务
                  器设置为扩展命令模式。
                  
                  
     NOOP         不采取任何措施。
                  
                  
     QUIT         干净地关闭连接。
                  
                  
     MAIL         接受 "MAIL FROM:" 句法并将所提供的地址保存为 *note mailfrom: 2f15.。
                  在扩展命令模式下，还接受 RFC 1870(2) SIZE 属性并根据
                  `data_size_limit' 的值作出适当返回。
                  
                  
     RCPT         接受 "RCPT TO:" 句法并将所提供的地址保存在 *note rcpttos: 2f16. 列表
                  中。
                  
                  
     RSET         重置 *note mailfrom: 2f15, *note rcpttos: 2f16, 和
                  *note received_data: 2f17. ，但不重置问候语。
                  
                  
     DATA         将内部状态设为 ‘DATA’ 并将来自客户端的剩余行保存在
                  *note received_data: 2f17. 中直至接收到终止符 ‘"\r\n.\r\n"’。
                  
                  
     HELP         返回有关命令语法的最少信息
                  
                  
     VRFY         返回代码252（服务器不知道该地址是否有效）
                  
                  
     EXPN         报告该命令未实现。
                  

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc6531.html

   (2) https://tools.ietf.org/html/rfc1870.html


File: python.info,  Node: telnetlib -- Telnet 客户端,  Next: uuid --- RFC 4122 定义的UUID对象,  Prev: smtpd --- SMTP 服务器,  Up: 互联网协议和支持

5.21.19 ‘telnetlib’ – Telnet 客户端
-----------------------------------

`源代码：' Lib/telnetlib.py(1)

__________________________________________________________________

*note telnetlib: 102. 模块提供一个实现Telnet协议的类 *note Telnet: 68e.。
关于此协议的细节请参见 RFC 854(2) 。此外，它还为协议字符（见下文）和
telnet 选项提供了对应的符号常量。telnet选项对应的符号名遵循
‘arpa/telnet.h’ 中的定义，但删除了前缀 ‘TELOPT_’。对于不在
‘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).

 -- 類別: telnetlib.Telnet (host=None, port=0[, timeout])

     *note Telnet: 68e. 表示到 Telnet 服务器的连接. 实例初始化后默认不连
     接；必须使用 *note open(): 2f1c. 方法来建立连接。或者， 可选参数
     host 和 port 也可以传递给构造函数，在这种情况下，到服务器的连接将在
     构造函数返回前建立。可选参数 `timeout' 为阻塞操作（如连接尝试）指定
     一个以秒为单位的超时时间（如果没有指定，将使用全局默认设置） 。

     不要重新打开一个已经连接的实例。

     这个类有很多 ‘read_*()’ 方法。 请注意，其中一些方法在读取结束时会触
     发 *note EOFError: d34. 异常，这是由于连接对象可能出于其它原因返回
     一个空字符串。 请参阅下面的个别描述。

     *note Telnet: 68e. 对象一个上下文管理器，可以在 *note with: 7da. 语
     句中使用。当 ‘with’ 块结束，*note close(): 2f1d. 方法会被调用:

          >>> from telnetlib import Telnet
          >>> with Telnet('localhost', 23) as tn:
          ...     tn.interact()
          ...

     3.6 版更變: 添加了上下文管理器的支持

也參考
......

RFC 854(3) - Telnet 协议规范

     Telnet 协议的定义。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/telnetlib.py

   (2) https://tools.ietf.org/html/rfc854.html

   (3) https://tools.ietf.org/html/rfc854.html


File: python.info,  Node: Telnet 对象,  Next: Telnet 示例,  Up: telnetlib -- Telnet 客户端

5.21.19.1 Telnet 对象
.....................

*note Telnet: 68e. 实例有以下几种方法：

 -- 成員函式: Telnet.read_until (expected, timeout=None)

     读取直到遇到给定字节串 `expected' 或 `timeout' 秒已经过去。

     当没有找到匹配时，返回可用的内容，也可能返回空字节。如果连接已关闭
     且没有可用的熟数据，将触发 *note EOFError: d34.。

 -- 成員函式: Telnet.read_all ()

     读取数据，直到遇到 EOF；连接关闭前都会保持阻塞。

 -- 成員函式: Telnet.read_some ()

     在达到 EOF 前，读取至少一个字节的熟数据。如果命中 EOF，返回 ‘b''’。
     如果没有立即可用的数据，则阻塞。

 -- 成員函式: Telnet.read_very_eager ()

     在不阻塞 I/O 的情况下读取所有的内容（eager）。

     如果连接已关闭并且没有可用的熟数据，将会触发 *note EOFError: d34. 。
     如果没有熟数据可用返回 ‘b''’ 。除非在一个 IAC 序列的中间，否则不要
     进行阻塞。

 -- 成員函式: Telnet.read_eager ()

     读取现成的数据。

     如果连接已关闭并且没有可用的熟数据，将会触发 *note EOFError: d34. 。
     如果没有熟数据可用返回 ‘b''’ 。除非在一个 IAC 序列的中间，否则不要
     进行阻塞。

 -- 成員函式: Telnet.read_lazy ()

     处理并返回已经在队列中的数据（lazy）。

     如果连接已关闭并且没有可用的数据，将会触发 *note EOFError: d34. 。
     如果没有熟数据可用则返回 ‘b''’ 。除非在一个 IAC 序列的中间，否则不
     要进行阻塞。

 -- 成員函式: Telnet.read_very_lazy ()

     返回熟数据队列任何可用的数据（very lazy）。

     如果连接已关闭并且没有可用的数据，将会触发 *note EOFError: d34. 。
     如果没有熟数据可用则返回 ‘b''’ 。该方法永远不会阻塞。

 -- 成員函式: Telnet.read_sb_data ()

     返回在 SB/SE 对之间收集的数据（子选项 begin/end）。当使用 ‘SE’ 命令
     调用回调函数时，该回调函数应该访问这些数据。该方法永远不会阻塞。

 -- 成員函式: Telnet.open (host, port=0[, timeout])

     连接主机。第二个可选参数是端口号，默认为标准 Telnet 端口（23）。可
     选参数 `timeout' 指定一个以秒为单位的超时时间用于像连接尝试这样的阻
     塞操作（如果没有指定，将使用全局默认超时设置）。

     不要尝试重新打开一个已经连接的实例。

     触发 *note auditing event: fa1. ‘telnetlib.Telnet.open’ ，参数为
     ‘self’，‘host’，‘port’。

 -- 成員函式: Telnet.msg (msg, *args)

     当调试级别 ‘>’ 0 时打印一条调试信息。如果存在额外参数，则它们会被替
     换在使用标准字符串格式化操作符的信息中。

 -- 成員函式: Telnet.set_debuglevel (debuglevel)

     设置调试级别。`debuglevel' 的值越高，得到的调试输出越多（在
     ‘sys.stdout’ ）。

 -- 成員函式: Telnet.close ()

     关闭连接对象。

 -- 成員函式: Telnet.get_socket ()

     返回内部使用的套接字对象。

 -- 成員函式: Telnet.fileno ()

     返回内部使用的套接字对象的文件描述符。

 -- 成員函式: Telnet.write (buffer)

     向套接字写入一个字节字符串，将所有 IAC 字符加倍。如果连接被阻塞，这
     可能也会阻塞。如果连接关闭可能触发 *note OSError: 304.。

     触发 *note auditing event: fa1. ‘telnetlib.Telnet.write’ ，参数为
     ‘self’，‘buffer’。

     3.3 版更變: 曾经该函数抛出 *note socket.error: a76.，现在这是 *note
     OSError: 304. 的别名。

 -- 成員函式: Telnet.interact ()

     交互函数，模拟一个非常笨拙的 Telnet 客户端。

 -- 成員函式: Telnet.mt_interact ()

     多线程版的 *note interact(): 2f2d.

 -- 成員函式: Telnet.expect (list, timeout=None)

     一直读取，直到匹配列表中的某个正则表达式。

     第一个参数是一个正则表达式列表，可以是已编译的 (*note
     正则表达式对象: 983.)，也可以是未编译的 (字节串)。 第二个可选参数是
     超时，单位是秒；默认一直阻塞。

     返回一个包含三个元素的元组：列表中的第一个匹配的正则表达式的索引；
     返回的匹配对象；包括匹配在内的读取过的字节。

     如果找到了文件的结尾且没有字节被读取，触发 *note EOFError: d34.。否
     则，当没有匹配时,返回 ‘(-1, None, data)’，其中 `data' 是到目前为止
     接受到的字节（如果发生超时，则可能是空字节）。

     如果一个正则表达式以贪婪匹配结束（例如 ‘.*’），或者多个表达式可以匹
     配同一个输出，则结果是不确定的，可能取决于 I/O 计时。

 -- 成員函式: Telnet.set_option_negotiation_callback (callback)

     每次在输入流上读取 telnet 选项时，这个带有如下参数的 `callback' （
     如果设置了）会被调用： callback(telnet socket, command
     (DO/DONT/WILL/WONT), option)。telnetlib 之后不会再执行其它操作。


File: python.info,  Node: Telnet 示例,  Prev: Telnet 对象,  Up: telnetlib -- Telnet 客户端

5.21.19.2 Telnet 示例
.....................

一个简单的说明性典型用法例子:

     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'))


File: python.info,  Node: uuid --- RFC 4122 定义的UUID对象,  Next: socketserver --- 用于网络服务器的框架,  Prev: telnetlib -- Telnet 客户端,  Up: 互联网协议和支持

5.21.20 ‘uuid’ — `RFC 4122' 定义的UUID对象
------------------------------------------

`Source code:' Lib/uuid.py(1)

__________________________________________________________________

这个模块提供了不可变的 *note UUID: 38a. 对象 (*note UUID: 38a. 类) 和
*note uuid1(): 517, *note uuid3(): 2f35, *note uuid4(): 2f36, *note
uuid5(): 2f37. 等函数用于生成 RFC 4122(2) 所定义的第 1, 3, 4 和 5 版
UUID。

如果你想要的只是一个唯一的ID，你可能应该调用 *note uuid1(): 517. 或
*note uuid4(): 2f36.。 注意 *note uuid1(): 517. 可能会损害隐私，因为它创
建了一个包含计算机网络地址的UUID。 *note uuid4(): 2f36. 可以创建一个随机
UUID。

根据底层平台的支持，*note uuid1(): 517. 可能会也可能不会返回一个 "安全的
" UUID。 安全的 UUID 是使用同步方法生成的，确保没有两个进程可以获得相同
的 UUID。 所有 *note UUID: 38a. 的实例都有一个 ‘is_safe’ 属性，使用这个
枚举来传递关于 UUID 安全的任何信息:

 -- 類別: uuid.SafeUUID

     3.7 版新加入.

      -- 屬性: safe

          该UUID是由平台以多进程安全的方式生成的。

      -- 屬性: unsafe

          UUID不是以多进程安全的方式生成的。

      -- 屬性: unknown

          该平台不提供UUID是否安全生成的信息。

 -- 類別: 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:

          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)

     必须给出 `hex'、`bytes'、`bytes_le'、`fields' 或 `int' 中的唯一一个
     。 `version' 参数是可选的；如果给定，产生的UUID将根据 RFC 4122(3) 设
     置其变体和版本号，覆盖给定的 `hex'、`bytes'、`bytes_le'、`fields' 或
     `int' 中的位。

     UUID 对象的比较是通过比较它们的 *note UUID.int: 2f3c. 属性进行的。
     与非 UUID 对象的比较会引发 *note TypeError: 1fe.。

     ‘str(uuid)’ 返回一个 ‘12345678-1234-5678-1234-567812345678’ 形式的
     字符串，其中 32 位十六进制数字代表 UUID。

*note UUID: 38a. 实例有这些只读的属性:

 -- 屬性: UUID.bytes

     UUID 是一个 16 字节的字符串（包含 6 个整数字段，大端字节顺序）。

 -- 屬性: UUID.bytes_le

     UUID 是一个 16 字节的字符串（其中 `time_low'、`time_mid' 和
     `time_hi_version' 为小端字节顺序）。

 -- 屬性: UUID.fields

     以元组形式存放的UUID的6个整数域，有六个单独的属性和两个派生属性：

     域                                 意义
                                        
     -----------------------------------------------------------------------
                                        
     ‘time_low’                         UUID的前32位
                                        
                                        
     ‘time_mid’                         接前一域的16位
                                        
                                        
     ‘time_hi_version’                  接前一域的16位
                                        
                                        
     ‘clock_seq_hi_variant’             接前一域的8位
                                        
                                        
     ‘clock_seq_low’                    接前一域的8位
                                        
                                        
     ‘node’                             UUID的最后48位
                                        
                                        
     *note time: 10c.                   UUID的总长60位的时间戳
                                        
                                        
     ‘clock_seq’                        14位的序列号
                                        

 -- 屬性: UUID.hex

     UUID是一个32个字符的十六进制字符串。

 -- 屬性: UUID.int

     UUID是一个128位的整数。

 -- 屬性: UUID.urn

     在 RFC 4122(4) 中定义的 URN 形式的 UUID。

 -- 屬性: UUID.variant

     UUID 的变体，它决定了 UUID 的内部布局。 这将是 *note RESERVED_NCS:
     2f43, *note RFC_4122: 2f44, *note RESERVED_MICROSOFT: 2f45. 或
     *note RESERVED_FUTURE: 2f46. 中的一个。

 -- 屬性: UUID.version

     UUID 版本号（1 到 5，只有当变体为 *note RFC_4122: 2f44. 时才有意义
     ）。

 -- 屬性: UUID.is_safe

     一个 *note SafeUUID: 2f38. 的枚举，表示平台是否以多进程安全的方式生
     成 UUID。

     3.7 版新加入.

*note uuid: 12d. 模块定义了以下函数：

 -- 函式: uuid.getnode ()

     获取 48 位正整数形式的硬件地址。 第一次运行时，它可能会启动一个单独
     的程序，这可能会相当慢。 如果所有获取硬件地址的尝试都失败了，我们会
     按照 RFC 4122(5) 中的建议，选择一个随机的 48 位数字，其多播位 (第一
     个八进制数的最小有效位) 设置为 1。 “硬件地址”是指一个网络接口的 MAC
     地址。 在一台有多个网络接口的机器上，普遍管理的 MAC 地址 (即第一个
     八位数的第二个最小有效位是 `未设置的') 将比本地管理的 MAC 地址优先
     ，但没有其他排序保证。

     3.7 版更變: 普遍管理的MAC地址优于本地管理的MAC地址，因为前者保证是
     全球唯一的，而后者则不是。

 -- 函式: uuid.uuid1 (node=None, clock_seq=None)

     根据主机 ID、序列号和当前时间生成一个 UUID。 如果没有给出 `node'，
     则使用 *note getnode(): 516. 来获取硬件地址。 如果给出了
     `clock_seq'，它将被用作序列号；否则将选择一个随机的 14 比特位序列号
     。

 -- 函式: uuid.uuid3 (namespace, name)

     根据命名空间标识符（这是一个UUID）和名称（这是一个字符串）的MD5哈希
     值，生成一个UUID。

 -- 函式: uuid.uuid4 ()

     生成一个随机的UUID。

 -- 函式: uuid.uuid5 (namespace, name)

     根据命名空间标识符（这是一个UUID）和名称（这是一个字符串）的SHA-1哈
     希值生成一个UUID。

*note uuid: 12d. 模块定义了以下命名空间标识符，供 *note uuid3(): 2f35. 或
*note uuid5(): 2f37. 使用。

 -- Data: uuid.NAMESPACE_DNS

     当指定这个命名空间时，`name' 字符串是一个完全限定的域名。

 -- Data: uuid.NAMESPACE_URL

     当指定这个命名空间时，`name' 字符串是一个 URL。

 -- Data: uuid.NAMESPACE_OID

     当指定这个命名空间时，`name' 字符串是一个 ISO OID。

 -- Data: uuid.NAMESPACE_X500

     当指定这个命名空间时，`name' 字符串是 DER 或文本输出格式的 X.500
     DN。

*note uuid: 12d. 模块为 ‘variant’ 属性的可能值定义了以下常量:

 -- Data: uuid.RESERVED_NCS

     为NCS兼容性保留。

 -- Data: uuid.RFC_4122

     指定 RFC 4122(6) 中给出的 UUID 布局。

 -- Data: uuid.RESERVED_MICROSOFT

     为微软的兼容性保留。

 -- Data: uuid.RESERVED_FUTURE

     保留给未来的定义。

也參考
......

RFC 4122(7) - 通用唯一标识符（UUID）URN命名空间

     本规范定义了UUID的统一资源名称空间，UUID的内部格式，以及生成UUID的
     方法。

* Menu:

* 示例: 示例<35>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/uuid.py

   (2) https://tools.ietf.org/html/rfc4122.html

   (3) https://tools.ietf.org/html/rfc4122.html

   (4) https://tools.ietf.org/html/rfc4122.html

   (5) https://tools.ietf.org/html/rfc4122.html

   (6) https://tools.ietf.org/html/rfc4122.html

   (7) https://tools.ietf.org/html/rfc4122.html


File: python.info,  Node: 示例<35>,  Up: uuid --- RFC 4122 定义的UUID对象

5.21.20.1 示例
..............

下面是一些 *note uuid: 12d. 模块的典型使用例子:

     >>> 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')


File: python.info,  Node: socketserver --- 用于网络服务器的框架,  Next: http server --- HTTP 服务器,  Prev: uuid --- RFC 4122 定义的UUID对象,  Up: 互联网协议和支持

5.21.21 ‘socketserver’ — 用于网络服务器的框架
---------------------------------------------

`源代码:' Lib/socketserver.py(1)

__________________________________________________________________

*note socketserver: f0. 模块简化了编写网络服务器的任务。

该模块具有四个基础实体服务器类:

 -- 類別: 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
     `bind_and_activate' is true, the constructor automatically attempts
     to invoke *note server_bind(): 2f51. and *note server_activate():
     2f52.  The other parameters are passed to the *note BaseServer:
     b61. base class.

 -- 類別: socketserver.UDPServer (server_address, RequestHandlerClass,
          bind_and_activate=True)

     该类使用数据包，即一系列离散的信息分包，它们可能会无序地到达或在传
     输中丢失。 该类的形参与 *note TCPServer: 2f50. 的相同。

 -- 類別: socketserver.UnixStreamServer (server_address,
          RequestHandlerClass, bind_and_activate=True)
 -- 類別: socketserver.UnixDatagramServer (server_address,
          RequestHandlerClass, bind_and_activate=True)

     这两个更常用的类与 TCP 和 UDP 类相似，但使用 Unix 域套接字；它们在
     非 Unix 系统平台上不可用。 它们的形参与 *note TCPServer: 2f50. 的相
     同。

这四个类会 `同步地' 处理请求；每个请求必须完成才能开始下一个请求。 这就
不适用于每个请求要耗费很长时间来完成的情况，或者因为它需要大量的计算，又
或者它返回了大量的数据而客户端处理起来很缓慢。 解决方案是创建单独的进程
或线程来处理每个请求；*note ForkingMixIn: 4db. 和 *note ThreadingMixIn:
4dc. 混合类可以被用于支持异步行为。

创建一个服务器需要分几个步骤进行。 首先，你必须通过子类化 *note
BaseRequestHandler: 2f56. 类并重载其 *note handle(): 2f57. 方法来创建一
个请求处理句柄类；这个方法将处理传入的请求。 其次，你必须实例化某个服务
器类，将服务器地址和请求处理句柄类传给它。 建议在 *note with: 7da. 语句
中使用该服务器。 然后再调用服务器对象的 *note handle_request(): 2f58. 或
*note serve_forever(): b63. 方法来处理一个或多个请求。 最后，调用 *note
server_close(): 2f59. 来关闭套接字（除非你使用了 ‘with’ 语句）。

当从 *note ThreadingMixIn: 4dc. 继承线程连接行为时，你应当显式地声明你希
望在突然关机时你的线程采取何种行为。 *note ThreadingMixIn: 4dc. 类定义了
一个属性 `daemon_threads'，它指明服务器是否应当等待线程终止。 如果你希望
线程能自主行动你应当显式地设置这个旗标；默认值为 *note False: 48e.，表示
Python 将不会在 *note ThreadingMixIn: 4dc. 所创建的所有线程都退出之前退
出。

服务器类具有同样的外部方法和属性，无论它们使用哪种网络协议。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/socketserver.py


File: python.info,  Node: 服务器创建的说明,  Next: Server 对象<2>,  Up: socketserver --- 用于网络服务器的框架

5.21.21.1 服务器创建的说明
..........................

在继承图中有五个类，其中四个代表四种类型的同步服务器:

     +------------+
     | BaseServer |
     +------------+
           |
           v
     +-----------+        +------------------+
     | TCPServer |------->| UnixStreamServer |
     +-----------+        +------------------+
           |
           v
     +-----------+        +--------------------+
     | UDPServer |------->| UnixDatagramServer |
     +-----------+        +--------------------+

请注意 *note UnixDatagramServer: 2f55. 派生自 *note UDPServer: 2f53.，而
不是 *note UnixStreamServer: 2f54. — IP 和 Unix 流服务器的唯一区别是地址
族，它会在两种 Unix 服务器类中简单地重复。

 -- 類別: socketserver.ForkingMixIn
 -- 類別: socketserver.ThreadingMixIn

     每种服务器类型的分叉和线程版本都可以使用这些混合类来创建。 例如，
     *note ThreadingUDPServer: 2f5b. 的创建方式如下:

          class ThreadingUDPServer(ThreadingMixIn, UDPServer):
              pass

     混合类先出现，因为它重载了 *note UDPServer: 2f53. 中定义的一个方法
     。 设置各种属性也会改变下层服务器机制的行为。

     *note ForkingMixIn: 4db. 和下文提及的分叉类仅在支持 *note fork():
     a42. 的 POSIX 系统平台上可用。

     ‘socketserver.ForkingMixIn.server_close()’ 会等待直到所有子进程完成
     ，除非 ‘socketserver.ForkingMixIn.block_on_close’ 属性为假值。

     ‘socketserver.ThreadingMixIn.server_close()’ 会等待直到所有非守护类
     线程完成，除非 ‘socketserver.ThreadingMixIn.block_on_close’ 属性为
     假值。 请将 ‘ThreadingMixIn.daemon_threads’ 设为 ‘True’ 来使用守护
     类线程以便不等待线完成。

     3.7 版更變: ‘socketserver.ForkingMixIn.server_close()’ 和
     ‘socketserver.ThreadingMixIn.server_close()’ 现在会等待直到所有子进
     程和非守护类线程完成。 请新增一个
     ‘socketserver.ForkingMixIn.block_on_close’ 类属性来选择 3.7 版之前
     的行为。

 -- 類別: socketserver.ForkingTCPServer
 -- 類別: socketserver.ForkingUDPServer
 -- 類別: socketserver.ThreadingTCPServer
 -- 類別: socketserver.ThreadingUDPServer

     这些类都是使用混合类来预定义的。

要实现一个服务，你必须从 *note BaseRequestHandler: 2f56. 派生一个类并重
定义其 *note handle(): 2f57. 方法。 然后你可以通过组合某种服务器类型与你
的请求处理句柄类来运行各种版本的服务。 请求处理句柄类对于数据报和流服务
必须是不相同的。 这可以通过使用处理句柄子类 *note StreamRequestHandler:
67e. 或 *note DatagramRequestHandler: 2f5f. 来隐藏。

当然，你仍然需要动点脑筋！ 举例来说，如果服务包含可能被不同请求所修改的
内存状态则使用分叉服务器是没有意义的，因为在子进程中的修改将永远不会触及
保存在父进程中的初始状态并传递到各个子进程。 在这种情况下，你可以使用线
程服务器，但你可能必须使用锁来保护共享数据的一致性。

另一方面，如果你是在编写一个所有数据保存在外部（例如文件系统）的 HTTP 服
务器，同步类实际上将在正在处理某个请求的时候“失聪” – 如果某个客户端在接
收它所请求的所有数据时很缓慢这可能会是非常长的时间。 这时线程或分叉服务
器会更为适用。

在某些情况下，合适的做法是同步地处理请求的一部分，但根据请求数据在分叉的
子进程中完成处理。 这可以通过使用一个同步服务器并在请求处理句柄类 *note
handle(): 2f57. 中进行显式分叉来实现。

还有一种可以在既不支持线程也不支持 *note fork(): a42. 的环境（或者对于本
服务来说这两者开销过大或是不适用）中处理多个同时请求的方式是维护一个显式
的部分完成的请求表并使用 *note selectors: e6. 来决定接下来要处理哪个请求
（或者是否要处理一个新传入的请求）。 这对于流服务来说特别重要，因为每个
客户端可能会连接很长的时间（如果不能使用线程或子进程）。 请参阅 *note
asyncore: a. 来了解另一种管理方式。


File: python.info,  Node: Server 对象<2>,  Next: 请求处理句柄对象,  Prev: 服务器创建的说明,  Up: socketserver --- 用于网络服务器的框架

5.21.21.2 Server 对象
.....................

 -- 類別: socketserver.BaseServer (server_address, RequestHandlerClass)

     这是本模块中所有 Server 对象的超类。 它定义了下文给出的接口，但没有
     实现大部分的方法，它们应在子类中实现。 两个形参存储在对应的 *note
     server_address: 2f61. 和 *note RequestHandlerClass: 2f62. 属性中。

      -- 成員函式: fileno ()

          返回服务器正在监听的套接字的以整数表示的文件描述符。 此函数最
          常被传递给 *note selectors: e6.，以允许在同一进程中监控多个服
          务器。

      -- 成員函式: handle_request ()

          处理单个请求。 此函数会依次调用下列方法: *note get_request():
          2f64, *note verify_request(): 2f65. 和 *note
          process_request(): 2f66.。 如果用户提供的处理句柄类的 *note
          handle(): 2f57. 方法引发了异常，则将调用服务器的 *note
          handle_error(): 6f4. 方法。 如果在 *note timeout: 2f67. 秒内未
          接收到请求，将会调用 *note handle_timeout(): 2f68. 并将返回
          *note handle_request(): 2f58.。

      -- 成員函式: serve_forever (poll_interval=0.5)

          对请求进行处理直至收到显式的 *note shutdown(): 1155. 请求。 每
          隔 `poll_interval' 秒对 shutdown 进行轮询。 忽略 *note
          timeout: 2f67. 属性。 它还会调用 *note service_actions():
          b62.，这可被子类或混合类用来提供某个给定服务的专属操作。 例如
          ，*note ForkingMixIn: 4db. 类使用 *note service_actions():
          b62. 来清理僵尸子进程。

          3.3 版更變: 将 ‘service_actions’ 调用添加到 ‘serve_forever’ 方
          法。

      -- 成員函式: service_actions ()

          此方法会在 the *note serve_forever(): b63. 循环中被调用。 此方
          法可被子类或混合类所重载以执行某个给定服务的专属操作，例如清理
          操作。

          3.3 版新加入.

      -- 成員函式: shutdown ()

          通知 *note serve_forever(): b63. 循环停止并等待它完成。 *note
          shutdown(): 1155. 必须在 *note serve_forever(): b63. 运行于不
          同线程时被调用否则它将发生死锁。

      -- 成員函式: server_close ()

          清理服务器。 可以被重载。

      -- 屬性: address_family

          服务器套接字所属的协议族。 常见的例子有 *note socket.AF_INET:
          26f8. 和 *note socket.AF_UNIX: 26fe.。

      -- 屬性: RequestHandlerClass

          用户提供的请求处理句柄类；将为每个请求创建该类的实例。

      -- 屬性: 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 *note socket: ef. module for details.
          For Internet protocols, this is a tuple containing a string
          giving the address, and an integer port number: ‘('127.0.0.1',
          80)’, for example.

      -- 屬性: socket

          将由服务器用于监听入站请求的套接字对象。

     服务器类支持下列类变量:

      -- 屬性: allow_reuse_address

          服务器是否要允许地址的重用。 默认值为 *note False: 48e.，并可
          在子类中设置以改变策略。

      -- 屬性: request_queue_size

          请求队列的长度。 如果处理单个请求要花费很长的时间，则当服务器
          正忙时到达的任何请求都会被加入队列，最多加入 *note
          request_queue_size: 2f6c. 个请求。 一旦队列被加满，来自客户端
          的更多请求将收到 "Connection denied" 错误。 默认值为 5，但可在
          子类中重载。

      -- 屬性: socket_type

          服务器使用的套接字类型；常见的有 *note socket.SOCK_STREAM:
          d52. 和 *note socket.SOCK_DGRAM: d51. 这两个值。

      -- 屬性: timeout

          超时限制，以秒数表示，或者如果不限制超时则为 *note None: 203.。
          如果在超时限制期间没有收到 *note handle_request(): 2f58.，则会
          调用 *note handle_timeout(): 2f68. 方法。

     有多个服务器方法可被服务器基类的子类例如 *note TCPServer: 2f50. 所
     重载；这些方法对服务器对象的外部用户来说并无用处。

      -- 成員函式: finish_request (request, client_address)

          通过实例化 *note RequestHandlerClass: 2f62. 并调用其 *note
          handle(): 2f57. 方法来实际处理请求。

      -- 成員函式: get_request ()

          必须接受来自套接字的请求，并返回一个 2 元组，其中包含用来与客
          户端通信的 `new' 套接字对象，以及客户端的地址。

      -- 成員函式: handle_error (request, client_address)

          此函数会在 *note RequestHandlerClass: 2f62. 实例的 *note
          handle(): 2f57. 方法引发异常时被调用。 默认行为是将回溯信息打
          印到标准错误并继续处理其他请求。

          3.6 版更變: 现在只针对派生自 *note Exception: 2dc. 类的异常调
          用此方法。

      -- 成員函式: handle_timeout ()

          此函数会在 *note timeout: 2f67. 属性被设为 *note None: 203. 以
          外的值并且在超出时限之后仍未收到请求时被调用。 分叉服务器的默
          认行为是收集任何已退出的子进程状态，而在线程服务器中此方法则不
          做任何操作。

      -- 成員函式: process_request (request, client_address)

          调用 *note finish_request(): 2f6e. 来创建 *note
          RequestHandlerClass: 2f62. 的实例。 如果需要，此函数可创建一个
          新的进程或线程来处理请求；*note ForkingMixIn: 4db. 和 *note
          ThreadingMixIn: 4dc. 类能完成此任务。

      -- 成員函式: server_activate ()

          由服务器的构造器调用以激活服务器。 TCP 服务器的默认行为只是在
          服务器的套接字上发起调用 *note listen(): 83a.。 可以被重载。

      -- 成員函式: server_bind ()

          由服务器的构造器调用以将套接字绑定到所需的地址。 可以被重载。

      -- 成員函式: verify_request (request, client_address)

          必须返回一个布尔值；如果值为 *note True: 593.，请求将被处理。
          而如果值为 *note False: 48e.，请求将被拒绝。 此函数可被重载以
          实现服务器的访问控制。 默认实现总是返回 *note True: 593.。

     3.6 版更變: 添加了对 *note context manager: 661. 协议的支持。 退出
     上下文管理器与调用 *note server_close(): 2f59. 等效。


File: python.info,  Node: 请求处理句柄对象,  Next: 示例<36>,  Prev: Server 对象<2>,  Up: socketserver --- 用于网络服务器的框架

5.21.21.3 请求处理句柄对象
..........................

 -- 類別: socketserver.BaseRequestHandler

     这是所有请求处理句柄对象的超类。 它定义了下文列出的接口。 一个实体
     请求处理句柄子类必须定义新的 *note handle(): 2f57. 方法，并可重载任
     何其他方法。 对于每个请求都会创建一个新的子类的实例。

      -- 成員函式: setup ()

          会在 *note handle(): 2f57. 方法之前被调用以执行任何必要的初始
          化操作。 默认实现不执行任何操作。

      -- 成員函式: handle ()

          此函数必须执行为请求提供服务所需的全部操作。 默认实现不执行任
          何操作。 它有几个可用的实例属性；请求为 ‘self.request’；客户端
          地址为 ‘self.client_address’；服务器实例为 ‘self.server’，如果
          它需要访问特定服务器信息的话。

          针对数据报或流服务的 ‘self.request’ 类型是不同的。 对于流服务
          ，‘self.request’ 是一个套接字对象；对于数据报服务，
          ‘self.request’ 是一对字符串与套接字。

      -- 成員函式: finish ()

          在 *note handle(): 2f57. 方法之后调用以执行任何需要的清理操作
          。 默认实现不执行任何操作。 如果 *note setup(): 2f70. 引发了异
          常，此函数将不会被调用。

 -- 類別: socketserver.StreamRequestHandler
 -- 類別: socketserver.DatagramRequestHandler

     *note BaseRequestHandler: 2f56. 子类重载了 *note setup(): 2f70. 和
     *note finish(): 2f71. 方法，并提供了 ‘self.rfile’ 和 ‘self.wfile’ 属
     性。 ‘self.rfile’ 和 ‘self.wfile’ 属性可以被分别读取或写入，以获取
     请求数据或将数据返回给客户端。

     这两个类的 ‘rfile’ 属性都支持 *note io.BufferedIOBase: 67f. 可读接
     口，并且 ‘DatagramRequestHandler.wfile’ 还支持 *note
     io.BufferedIOBase: 67f. 可写接口。

     3.6 版更變: ‘StreamRequestHandler.wfile’ 也支持 *note
     io.BufferedIOBase: 67f. 可写接口。


File: python.info,  Node: 示例<36>,  Prev: 请求处理句柄对象,  Up: socketserver --- 用于网络服务器的框架

5.21.21.4 示例
..............

* Menu:

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


File: python.info,  Node: socketserver TCPServer 示例,  Next: socketserver UDPServer 示例,  Up: 示例<36>

5.21.21.5 ‘socketserver.TCPServer’ 示例
.......................................

以下是服务端:

     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()

一个使用流（通过提供标准文件接口来简化通信的文件类对象）的替代请求处理句
柄类:

     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())

区别在于第二个处理句柄的 ‘readline()’ 调用将多次调用 ‘recv()’ 直至遇到一
个换行符，而第一个处理句柄的单次 ‘recv()’ 调用只是返回在一次 ‘sendall()’
调用中由客户端发送的内容。

以下是客户端:

     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))

这个示例程序的输出应该是像这样的:

服务器:

     $ python TCPServer.py
     127.0.0.1 wrote:
     b'hello world with TCP'
     127.0.0.1 wrote:
     b'python is nice'

客户端:

     $ 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


File: python.info,  Node: socketserver UDPServer 示例,  Next: 异步混合类,  Prev: socketserver TCPServer 示例,  Up: 示例<36>

5.21.21.6 ‘socketserver.UDPServer’ 示例
.......................................

以下是服务端:

     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()

以下是客户端:

     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))

这个示例程序的输出应该是与 TCP 服务器示例相一致的。


File: python.info,  Node: 异步混合类,  Prev: socketserver UDPServer 示例,  Up: 示例<36>

5.21.21.7 异步混合类
....................

要构建异步处理句柄，请使用 *note ThreadingMixIn: 4dc. 和 *note
ForkingMixIn: 4db. 类。

*note ThreadingMixIn: 4dc. 类的示例:

     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()

这个示例程序的输出应该是像这样的:

     $ 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

*note ForkingMixIn: 4db. 类的使用方式是相同的，区别在于服务器将为每个请
求产生一个新的进程。 仅在支持 *note fork(): a42. 的 POSIX 系统平台上可用
。


File: python.info,  Node: http server --- HTTP 服务器,  Next: http cookies --- HTTP状态管理,  Prev: socketserver --- 用于网络服务器的框架,  Up: 互联网协议和支持

5.21.22 ‘http.server’ — HTTP 服务器
-----------------------------------

`源代码：' Lib/http/server.py(1)

__________________________________________________________________

这个模块定义了实现 HTTP 服务器（ Web 服务器）的类。

     警告: 不推荐在生产环境中使用 *note http.server: 96. 。它只实现了基
     本的安全检查功能。

*note HTTPServer: 2d43. 是 *note socketserver.TCPServer: 2f50. 的一个子
类。它会创建和侦听 HTTP 套接字，并将请求调度给处理程序。用于创建和运行服
务器的代码看起来像这样：

     def run(server_class=HTTPServer, handler_class=BaseHTTPRequestHandler):
         server_address = ('', 8000)
         httpd = server_class(server_address, handler_class)
         httpd.serve_forever()

 -- 類別: http.server.HTTPServer (server_address, RequestHandlerClass)

     该类基于 *note TCPServer: 2f50. 类，并会将服务器地址存入名为
     ‘server_name’ 和 ‘server_port’ 的实例变量中。服务器可被处理程序通过
     ‘server’ 实例变量访问。

 -- 類別: http.server.ThreadingHTTPServer (server_address,
          RequestHandlerClass)

     这个类与 HTTPServer 相似，但会通过使用 *note ThreadingMixIn: 4dc. 来
     以线程处理请求。 这适用于处理 Web 浏览器预开启套接字，以便 *note
     HTTPServer: 2d43. 无限期地执行等待。

     3.7 版新加入.

*note HTTPServer: 2d43. 和 *note ThreadingHTTPServer: 49c. 必须在实例化
时给定一个 `RequestHandlerClass'，此模块提供了该对象的三种不同形式:

 -- 類別: http.server.BaseHTTPRequestHandler (request, client_address,
          server)

     这个类用于处理到达服务器的 HTTP 请求。 它本身无法响应任何实际的
     HTTP 请求；它必须被子类化以处理每个请求方法（例如 GET 或 POST）。
     *note BaseHTTPRequestHandler: aec. 提供了许多供子类使用的类和实例变
     量以及方法。

     这个处理程序将解析请求和标头，然后调用特定请求类型对应的方法。 方法
     名称将根据请求来构造。 例如，对于请求方法 ‘SPAM’，将不带参数地调用
     ‘do_SPAM()’ 方法。 所有相关信息会被保存在该处理程序的实际变量中。 子
     类不需要重载或扩展 *note __init__(): e23. 方法。

     *note BaseHTTPRequestHandler: aec. 具有下列实例变量:

      -- 屬性: client_address

          包含 ‘(host, port)’ 形式的指向客户端地址的元组。

      -- 屬性: server

          包含服务器实例。

      -- 屬性: close_connection

          应当在 *note handle_one_request(): 2f7b. 返回之前设定的布尔值
          ，指明是否要期待另一个请求，还是应当关闭连接。

      -- 屬性: requestline

          包含 HTTP 请求行的字符串表示。 末尾的 CRLF 会被去除。 该属性应
          当由 *note handle_one_request(): 2f7b. 来设定。 如果无有效请求
          行被处理，则它应当被设为空字符串。

      -- 屬性: command

          包含具体的命令（请求类型）。 例如 ‘'GET'’。

      -- 屬性: path

          包含请求路径。如果URL的查询部分存在， ‘path’ 会包含这个查询部
          分。使用 RFC 3986(2) 的术语来说，在这里， ‘path’ 包含
          ‘hier-part’ 和 ‘query’ 。

      -- 屬性: request_version

          包含请求的版本字符串。 例如 ‘'HTTP/1.0'’。

      -- 屬性: headers

          存放由 *note MessageClass: 2f80. 类变量所指定的类的实例。 该实
          例会解析并管理 HTTP 请求中的标头。 *note http.client: 93. 中的
          *note parse_headers(): 1176. 函数将被用来解析标头并且它需要
          HTTP 请求提供一个有效的 RFC 2822(3) 风格的标头。

      -- 屬性: rfile

          一个 *note io.BufferedIOBase: 67f. 输入流，准备从可选的输入数
          据的开头进行读取。

      -- 屬性: wfile

          包含用于写入响应并发回给客户端的输出流。 在写入流时必须正确遵
          守 HTTP 协议以便成功地实现与 HTTP 客户端的互操作。

          3.6 版更變: 这是一个 *note io.BufferedIOBase: 67f. 流。

     *note BaseHTTPRequestHandler: aec. 具有下列属性：

      -- 屬性: server_version

          指定服务器软件版本。 你可能会想要重载该属性。 该属性的格式为多
          个以空格分隔的字符串，其中每个字符串的形式为 name[/version]。
          例如 ‘'BaseHTTP/0.2'’。

      -- 屬性: sys_version

          包含 Python 系统版本，采用 *note version_string: 2f85. 方法和
          *note server_version: 2f83. 类变量所支持的形式。 例如
          ‘'Python/1.4'’。

      -- 屬性: error_message_format

          指定应当被 *note send_error(): 947. 方法用来构建发给客户端的错
          误响应的格式字符串。 该字符串应使用来自 *note responses: 2e15.
          的变量根据传给 *note send_error(): 947. 的状态码来填充默认值。

      -- 屬性: error_content_type

          指定发送给客户端的错误响应的 Content-Type HTTP 标头。 默认值为
          ‘'text/html'’。

      -- 屬性: protocol_version

          该属性指定在响应中使用的 HTTP 协议版本。 如果设为
          ‘'HTTP/1.1'’，服务器将允许 HTTP 永久连接；但是，这样你的服务器
          `必须' 在发给客户端的所有响应中包括一个准确的 ‘Content-Length’
          标头 (使用 *note send_header(): 2f89.)。 为了向下兼容，该设置
          默认为 ‘'HTTP/1.0'’。

      -- 屬性: MessageClass

          指定一个 *note email.message.Message: 63b. 这样的类来解析 HTTP
          标头。 通常该属性不会被重载，其默认值为
          ‘http.client.HTTPMessage’。

      -- 屬性: responses

          该属性包含一个整数错误代码与由短消息和长消息组成的二元组的映射
          。 例如，‘{code: (shortmessage, longmessage)}’。
          `shortmessage' 通常是作为消息响应中的 `message' 键，而
          `longmessage' 则是作为 `explain' 键。 该属性会被 *note
          send_response_only(): 2f8a. 和 *note send_error(): 947. 方法所
          使用。

     *note BaseHTTPRequestHandler: aec. 实例具有下列方法:

      -- 成員函式: handle ()

          调用 *note handle_one_request(): 2f7b. 一次（或者如果启用了永
          久连接则为多次）来处理传入的 HTTP 请求。 你应该完全不需要重载
          它；而是要实现适当的 ‘do_*()’ 方法。

      -- 成員函式: handle_one_request ()

          此方法将解析并将请求分配给适当的 ‘do_*()’ 方法。 你应该完全不
          需要重载它。

      -- 成員函式: handle_expect_100 ()

          当一个符合 HTTP/1.1 标准的服务器收到 ‘Expect: 100-continue’ 请
          求标头时它会以 ‘100 Continue’ 加 ‘200 OK’ 的标头作为响应。 如
          果服务器不希望客户端继续则可以重载此方法引发一个错误。 例如服
          务器可以选择发送 ‘417 Expectation Failed’ 作为响应标头并
          ‘return False’。

          3.2 版新加入.

      -- 成員函式: send_error (code, message=None, explain=None)

          发送并记录回复给客户端的完整错误信息。 数字形式的 `code' 指明
          HTTP 错误代码，可选的 `message' 为简短的易于人类阅读的错误描述
          。 `explain' 参数可被用于提供更详细的错误信息；它将使用 *note
          error_message_format: 2f86. 属性来进行格式化并在一组完整的标头
          之后作为响应体被发送。 *note responses: 2e15. 属性存放了
          `message' 和 `explain' 的默认值，它们将在未提供时被使用；对于
          未知代码两者的默认值均为字符串 ‘???’。 如果方法为 HEAD 或响应
          代码是下列值之一则响应体将为空: ‘1xx’, ‘204 No Content’, ‘205
          Reset Content’, ‘304 Not Modified’。

          3.4 版更變: 错误响应包括一个 Content-Length 标头。 增加了
          `explain' 参数。

      -- 成員函式: send_response (code, message=None)

          将一个响应标头添加到标头缓冲区并记录被接受的请求。 HTTP 响应行
          会被写入到内部缓冲区，后面是 `Server' 和 `Date' 标头。 这两个
          标头的值将分别通过 *note version_string(): 2f85. 和 *note
          date_time_string(): 2f8e. 方法获取。 如果服务器不打算使用
          *note send_header(): 2f89. 方法发送任何其他标头，则 *note
          send_response(): 2f8d. 后面应该跟一个 *note end_headers():
          aed. 调用。

          3.3 版更變: 标头会被存储到内部缓冲区并且需要显式地调用 *note
          end_headers(): aed.。

      -- 成員函式: send_header (keyword, value)

          将 HTTP 标头添加到内部缓冲区，它将在 *note end_headers(): aed.
          或 *note flush_headers(): aee. 被发起调用时写入输出流。
          `keyword' 应当指定标头关键字，并以 `value' 指定其值。 请注意，
          在 send_header 调用结束之后，必须调用 *note end_headers():
          aed. 以便完成操作。

          3.2 版更變: 标头将被存入内部缓冲区。

      -- 成員函式: send_response_only (code, message=None)

          只发送响应标头，用于当 ‘100 Continue’ 响应被服务器发送给客户端
          的场合。 标头不会被缓冲而是直接发送到输出流。 如果未指定
          `message'，则会发送与响应 `code' 相对应的 HTTP 消息。

          3.2 版新加入.

      -- 成員函式: end_headers ()

          将一个空行（指明响应中 HTTP 标头的结束）添加到标头缓冲区并调用
          *note flush_headers(): aee.。

          3.2 版更變: 已缓冲的标头会被写入到输出流。

      -- 成員函式: flush_headers ()

          最终将标头发送到输出流并清空内部标头缓冲区。

          3.3 版新加入.

      -- 成員函式: log_request (code='-', size='-')

          记录一次被接受（成功）的请求。 `code' 应当指定与请求相关联的
          HTTP 代码。 如果请求的大小可用，则它应当作为 `size' 形参传入。

      -- 成員函式: log_error (...)

          当请求无法完成时记录一次错误。 默认情况下，它会将消息传给
          *note log_message(): 2f91.，因此它接受同样的参数 (`format' 和
          一些额外的值)。

      -- 成員函式: log_message (format, ...)

          将任意一条消息记录到 ‘sys.stderr’。 此方法通常会被重载以创建自
          定义的错误日志记录机制。 `format' 参数是标准 printf 风格的格式
          字符串，其中会将传给 *note log_message(): 2f91. 的额外参数用作
          格式化操作的输入。 每条消息日志记录的开头都会加上客户端 IP 地
          址和当前日期时间。

      -- 成員函式: version_string ()

          返回服务器软件的版本字符串。 该值为 *note server_version:
          2f83. 与 *note sys_version: 2f84. 属性的组合。

      -- 成員函式: date_time_string (timestamp=None)

          返回由 `timestamp' 所给定的日期和时间（参数应为 ‘None’ 或为
          *note time.time(): 42d. 所返回的格式），格式化为一个消息标头。
          如果省略 `timestamp'，则会使用当前日期和时间。

          结果看起来像 ‘'Sun, 06 Nov 1994 08:49:37 GMT'’。

      -- 成員函式: log_date_time_string ()

          返回当前的日期和时间，为日志格式化

      -- 成員函式: address_string ()

          返回客户端的地址

          3.3 版更變: 在之前版本中，会执行一次名称查找。 为了避免名称解
          析的时延，现在将总是返回 IP 地址。

 -- 類別: http.server.SimpleHTTPRequestHandler (request, client_address,
          server, directory=None)

     这个类会为目录 `directory' 及以下的文件提供发布服务，或者如果未提供
     `directory' 则为当前目录，直接将目录结构映射到 HTTP 请求。

     3.7 版新加入: `directory' 形参。

     3.9 版更變: `directory' 形参接受一个 *note path-like object: 472.。

     诸如解析请求之类的大量工作都是由基类 *note BaseHTTPRequestHandler:
     aec. 完成的。本类实现了 *note do_GET(): 2f94. 和 *note do_HEAD():
     2f95. 函数。

     以下是 *note SimpleHTTPRequestHandler: 49b. 的类属性。

      -- 屬性: server_version

          这会是 ‘"SimpleHTTP/" + __version__’，其中 ‘__version__’ 定义
          于模块级别。

      -- 屬性: extensions_map

          将后缀映射为 MIME 类型的字典，其中包含了覆盖系统默认值的自定义
          映射关系。不区分大小写，因此字典键只应为小写值。

          3.9 版更變: 此字典不再填充默认的系统映射，而只包含覆盖值。

     *note SimpleHTTPRequestHandler: 49b. 类定义了以下方法：

      -- 成員函式: do_HEAD ()

          本方法为 ‘'HEAD'’ 请求提供服务：它将发送等同于 ‘GET’ 请求的头
          文件。关于合法头部信息的更完整解释，请参阅 *note do_GET():
          2f94. 方法。

      -- 成員函式: do_GET ()

          这一请求通过把其解释为当前工作目录的相对路径来映射到本地文件

          如果请求被映射到目录，则会依次检查该目录是否存在 ‘index.html’
          或 ‘index.htm’ 文件。若存在则返回文件内容；否则会调用
          ‘list_directory()’ 方法生成目录列表。本方法将利用 *note
          os.listdir(): b1c. 扫描目录，如果 *note listdir(): b1c. 失败，
          则返回 ‘404’ 出错应答。

          如果请求被映射到文件，则会打开该文件。 打开文件时的任何 *note
          OSError: 304. 异常都会被映射为 ‘404’, ‘'File not found'’ 错误
          。 如果请求中带有 ‘'If-Modified-Since'’ 标头，而在此时间点之后
          文件未作修改，则会发送 ‘304’, ‘'Not Modified'’ 的响应。 否则会
          调用 ‘guess_type()’ 方法猜测内容的类型，该方法会反过来用到
          `extensions_map' 变量，并返回文件内容。

          将会输出 ‘'Content-type:'’ 头部信息，带上猜出的内容类型，然后
          是 ‘'Content-Length:'’ 头部信息，带有文件的大小，以及
          ‘'Last-Modified:'’ 头部信息，带有文件的修改时间。

          后面是一个空行，标志着头部信息的结束，然后输出文件的内容。如果
          文件的 MIME 类型以 ‘text/’ 开头，文件将以文本模式打开；否则将
          使用二进制模式。

          用法示例请参阅 *note http.server: 96. 模块中的 *note test():
          105. 函数的实现。

          3.7 版更變: 为 ‘'If-Modified-Since'’ 头部信息提供支持。

*note SimpleHTTPRequestHandler: 49b. 类的用法可如下所示，以便创建一个非
常简单的 Web 服务，为相对于当前目录的文件提供服务：

     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()
*note http.server: 96. 也可使用解释器的 *note -m: 443. 开关加上 ‘port
number’ 参数直接发起调用。 与前面的例子类似，可支持相对于当前目录的文件:

     python -m http.server 8000

默认情况下，HTTP 服务器将绑定所有的网络接口。参数 ‘-b/--bind’ 可指定需绑
定的地址。IPv4 和 IPv6 均可。比如以下命令可让 HTTP 服务器只与 localhost
绑定：

     python -m http.server 8000 --bind 127.0.0.1

3.4 版新加入: 引入了 ‘--bind’ 参数。

3.8 版新加入: 为了支持 IPv6 改进了 ‘--bind’ 参数。

HTTP 服务器默认使用当前目录。参数 ‘-d/--directory’ 可指定文件所在的目录
。比如以下命令就指定了一个目录：

     python -m http.server --directory /tmp/

3.7 版新加入: ‘--directory’ 指定备用目录

 -- 類別: http.server.CGIHTTPRequestHandler (request, client_address,
          server)

     该类可为当前及以下目录中的文件或输出 CGI 脚本提供服务。注意，把
     HTTP 分层结构映射到本地目录结构，这与 *note
     SimpleHTTPRequestHandler: 49b. 完全一样。

          備註: 由 *note CGIHTTPRequestHandler: 2f98. 类运行的 CGI 脚本
          不能进行重定向操作（HTTP 代码302），因为在执行 CGI 脚本之前会
          发送代码 200（接下来就输出脚本）。这样状态码就冲突了。

     然而，如果这个类猜测它是一个 CGI 脚本，那么就会运行该 CGI 脚本，而
     不是作为文件提供出去。 只会识别基于目录的 CGI —— 另有一种常用的服务
     器设置，即标识 CGI 脚本是通过特殊的扩展名。

     如果请求指向 ‘cgi_directories’ 以下的路径，‘do_GET()’ 和
     ‘do_HEAD()’ 函数已作修改，不是给出文件，而是运行 CGI 脚本并输出结果
     。

     *note CGIHTTPRequestHandler: 2f98. 定义了以下数据成员：

      -- 屬性: cgi_directories

          默认为 ‘['/cgi-bin', '/htbin']’，视作 CGI 脚本所在目录。

     *note CGIHTTPRequestHandler: 2f98. 定义了以下方法：

      -- 成員函式: do_POST ()

          本方法服务于 ‘'POST'’ 请求，仅用于 CGI 脚本。如果试图向非 CGI
          网址发送 POST 请求，则会输出错误 501：Can only POST to CGI
          scripts"。

     请注意，为了保证安全性，CGI 脚本将以用户 nobody 的 UID 运行。CGI 脚
     本运行错误将被转换为错误 403。

通过在命令行传入 ‘--cgi’ 参数，可以启用 *note CGIHTTPRequestHandler:
2f98. ：

     python -m http.server --cgi 8000

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/http/server.py

   (2) https://tools.ietf.org/html/rfc3986.html

   (3) https://tools.ietf.org/html/rfc2822.html


File: python.info,  Node: http cookies --- HTTP状态管理,  Next: http cookiejar —— HTTP 客户端的 Cookie 处理,  Prev: http server --- HTTP 服务器,  Up: 互联网协议和支持

5.21.23 ‘http.cookies’ — HTTP状态管理
-------------------------------------

`源代码:' Lib/http/cookies.py(1)

__________________________________________________________________

*note http.cookies: 95. 模块定义的类将 cookie 的概念抽象了出来，这是一种
HTTP 状态的管理机制。它既支持简单的纯字符串形式的 cookie，也为任何可序列
化数据类型的 cookie 提供抽象。

以前，该模块严格套用 RFC 2109(2) 和 RFC 2068(3) 规范中描述的解析规则。后
来人们发现，MSIE 3.0 并不遵循这些规范中的字符规则，而且目前许多浏览器和
服务器在处理 cookie 时也放宽了解析规则。 因此，这里用到的解析规则没有那
么严格。

字符集 *note string.ascii_letters: d24. 、 *note string.digits: 186b. 和
‘!#$%&'*+-.^_`|~:’ 给出了本模块允许出现在 cookie 名称中的有效字符集（如
*note key: 588.）。

3.3 版更變: “:”字符可用于有效的 cookie 名称。

     備註: 当遇到无效 cookie 时会触发 *note CookieError: 2f9d.，所以若
     cookie 数据来自浏览器，一定要做好应对无效数据的准备，并在解析时捕获
     *note CookieError: 2f9d.。

 -- 例外: http.cookies.CookieError

     出现异常的原因，可能是不符合 RFC 2109(4) ：属性不正确、‘Set-Cookie’
     头部信息不正确等等。

 -- 類別: http.cookies.BaseCookie ([input])

     类似字典的对象，字典键为字符串，字典值是 *note Morsel: 587. 实例。
     请注意，在将键值关联时，首先会把值转换为包含键和值的 *note Morsel:
     587. 对象。

     若给出 `input' ，将会传给 *note load(): 2f9f. 方法。

 -- 類別: http.cookies.SimpleCookie ([input])

     该类派生于 *note BaseCookie: 2f9e.，并覆盖了 ‘value_decode()’ 和
     ‘value_encode()’ 方法。SimpleCookie 允许用字符串作为 cookie 值。在
     设置值时，SimpleCookie 将调用内置的 *note str(): 205. 将其转换为字
     符串。从 HTTP 接收到的值将作为字符串保存。

也參考
......

*note http.cookiejar: 94. 模块

     处理网络 `客户端' 的 HTTP cookie。 *note http.cookiejar: 94. 和
     *note http.cookies: 95. 模块相互没有依赖关系。

RFC 2109(5) - HTTP状态管理机制

     这是本模块实现的状态管理规范。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/http/cookies.py

   (2) https://tools.ietf.org/html/rfc2109.html

   (3) https://tools.ietf.org/html/rfc2068.html

   (4) https://tools.ietf.org/html/rfc2109.html

   (5) https://tools.ietf.org/html/rfc2109.html


File: python.info,  Node: Cookie 对象,  Next: Morsel 对象,  Up: http cookies --- HTTP状态管理

5.21.23.1 Cookie 对象
.....................

 -- 成員函式: BaseCookie.value_decode (val)

     由字符串返回元组 ‘(real_value, coded_value)’。‘real_value’ 可为任意
     类型。*note BaseCookie: 2f9e. 中的此方法未实现任何解码工作——只为能
     被子类重写。

 -- 成員函式: BaseCookie.value_encode (val)

     返回元组 ‘(real_value, coded_value)’。`val' 可为任意类型，
     ‘coded_value’ 则会转换为字符串。 *note BaseCookie: 2f9e. 中的此方法
     未实现任何编码工作——只为能被子类重写。

     通常在 `value_decode' 的取值范围内，*note value_encode(): 2fa3. 和
     *note value_decode(): 2fa2. 应为可互逆操作。

 -- 成員函式: BaseCookie.output (attrs=None, header='Set-Cookie:',
          sep='\r\n')

     返回可作为 HTTP 标头信息发送的字符串表示。 `attrs' 和 `header' 会传
     给每个 *note Morsel: 587. 的 *note output(): 2fa4. 方法。 `sep' 用
     来将标头连接在一起，默认为 ‘'\r\n'’ (CRLF) 组合。

 -- 成員函式: BaseCookie.js_output (attrs=None)

     返回一段可供嵌入的 JavaScript 代码，若在支持 JavaScript 的浏览器上
     运行，其作用如同发送 HTTP 头部信息一样。

     `attrs' 的含义与 *note output(): 2fa4. 的相同。

 -- 成員函式: BaseCookie.load (rawdata)

     若 `rawdata' 为字符串，则会作为 ‘HTTP_COOKIE’ 进行解析，并将找到的
     值添加为 *note Morsel: 587.。 如果是字典值，则等价于:

          for k, v in rawdata.items():
              cookie[k] = v


File: python.info,  Node: Morsel 对象,  Next: 示例<37>,  Prev: Cookie 对象,  Up: http cookies --- HTTP状态管理

5.21.23.2 Morsel 对象
.....................

 -- 類別: http.cookies.Morsel

     对键/值对的抽象，带有 RFC 2109(1) 的部分属性。

     morsel 对象类似于字典，键的组成是常量——均为有效的 RFC 2109(2) 属性
     ，包括：

        * ‘expires’

        * ‘path’

        * ‘comment’

        * ‘domain’

        * ‘max-age’

        * ‘secure’

        * ‘version’

        * ‘httponly’

        * ‘samesite’

     ‘httponly’ 属性指明了该 cookie 仅在 HTTP 请求中传输，且不能通过
     JavaScript 访问。这是为了减轻某些跨站脚本攻击的危害。

     ‘samesite’ 属性指明了浏览器不得与跨站请求一起发送该 cookie。这有助
     于减轻 CSRF 攻击的危害。此属性的有效值为 “Strict”和“Lax”。

     键不区分大小写，默认值为 ‘''’。

     3.5 版更變: 现在，‘__eq__()’ 会同时考虑 *note key: 588. 和 *note
     value: 589. 。

     3.7 版更變: Attributes *note key: 588, *note value: 589. and *note
     coded_value: 58a. are read-only.  Use *note set(): 58b. for setting
     them.

     3.8 版更變: 增加对 ‘samesite’ 属性的支持。

 -- 屬性: Morsel.value

     Cookie的值。

 -- 屬性: Morsel.coded_value

     编码后的 cookie 值——也即要发送的内容。

 -- 屬性: Morsel.key

     cookie 名称

 -- 成員函式: Morsel.set (key, value, coded_value)

     设置 `key'、`value' 和 `coded_value' 属性。

 -- 成員函式: Morsel.isReservedKey (K)

     `K' 是否属于 *note Morsel: 587. 的键。

 -- 成員函式: Morsel.output (attrs=None, header='Set-Cookie:')

     返回 morsel 的字符串形式，适用于作为 HTTP 头部信息进行发送。默认包
     含所有属性，除非给出 `attrs' 属性列表。`header' 默认为
     ‘"Set-Cookie:"’。

 -- 成員函式: Morsel.js_output (attrs=None)

     返回一段可供嵌入的 JavaScript 代码，若在支持 JavaScript 的浏览器上
     运行，其作用如同发送 HTTP 头部信息一样。

     `attrs' 的含义与 *note output(): 2fa9. 的相同。

 -- 成員函式: Morsel.OutputString (attrs=None)

     返回 morsel 的字符串形式，不含 HTTP 或 JavaScript 数据。

     `attrs' 的含义与 *note output(): 2fa9. 的相同。

 -- 成員函式: Morsel.update (values)

     用字典 `values' 中的值更新 morsel 字典中的值。若有 `values' 字典中
     的键不是有效的 RFC 2109(3) 属性，则会触发错误。

     3.5 版更變: 无效键会触发错误。

 -- 成員函式: Morsel.copy (value)

     返回 morsel 对象的浅表复制副本。

     3.5 版更變: 返回一个 morsel 对象，而非字典。

 -- 成員函式: Morsel.setdefault (key, value=None)

     若 key 不是有效的 RFC 2109(4) 属性则触发错误，否则与 *note
     dict.setdefault(): a9e. 相同。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2109.html

   (2) https://tools.ietf.org/html/rfc2109.html

   (3) https://tools.ietf.org/html/rfc2109.html

   (4) https://tools.ietf.org/html/rfc2109.html


File: python.info,  Node: 示例<37>,  Prev: Morsel 对象,  Up: http cookies --- HTTP状态管理

5.21.23.3 示例
..............

以下例子演示了 *note http.cookies: 95. 模块的用法。

     >>> 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


File: python.info,  Node: http cookiejar —— HTTP 客户端的 Cookie 处理,  Next: xmlrpc --- XMLRPC 服务端与客户端模块,  Prev: http cookies --- HTTP状态管理,  Up: 互联网协议和支持

5.21.24 ‘http.cookiejar’ —— HTTP 客户端的 Cookie 处理
-----------------------------------------------------

`源代码：' Lib/http/cookiejar.py(1)

__________________________________________________________________

*note http.cookiejar: 94. 模块定义了用于自动处理 HTTP cookie 的类。这对
访问需要小段数据 —— `cookies' 的网站很有用，这些数据由 Web 服务器的 HTTP
响应在客户端计算机上设置，然后在以后的 HTTP 请求中返回给服务器。

常规的 Netscape Cookie 协议和 RFC 2965(2) 定义的协议都可以处理。RFC 2965
处理默认情况下处于关闭状态。 RFC 2109(3) cookie 被解析为 Netscape
cookie，随后根据有效的 ’policy’ 被视为 Netscape 或 RFC 2965 cookie。 请
注意，Internet 上的大多数 cookie 是 Netscape cookie。 *note
http.cookiejar: 94. 尝试遵循事实上的 Netscape cookie 协议（与原始
Netscape 规范中所设定的协议大不相同），包括注意 ‘max-age’ 和 ‘port’ RFC
2965 引入的 cookie 属性。

     備註: 在 ‘Set-Cookie’ 和 ‘Set-Cookie2’ 头中找到的各种命名参数通常指
     `attributes'。为了不与 Python 属性相混淆，模块文档使用
     `cookie-attribute' 代替。

此模块定义了以下异常：

 -- 例外: http.cookiejar.LoadError

     *note FileCookieJar: 2fb2. 实例在从文件加载 cookies 出错时抛出这个
     异常。 *note LoadError: 2fb1. 是 *note OSError: 304. 的一个子类。

     3.3 版更變: LoadError 成为 *note OSError: 304. 的子类而不是 *note
     IOError: a73.。

提供了以下类：

 -- 類別: http.cookiejar.CookieJar (policy=None)

     `policy' 是实现了 *note CookiePolicy: 2fb3. 接口的一个对象。

     *note CookieJar: 2db2. 类储存 HTTP cookies。它从 HTTP 请求提取
     cookies，并在 HTTP 响应中返回它们。 *note CookieJar: 2db2. 实例在必
     要时自动处理包含 cookie 的到期情况。子类还负责储存和从文件或数据库
     中查找 cookies。

 -- 類別: http.cookiejar.FileCookieJar (filename, delayload=None,
          policy=None)

     `policy' 是实现了 *note CookiePolicy: 2fb3. 接口的一个对象。对于其
     他参数，参考相应属性的文档。

     一个可以从硬盘中文件加载或保存 cookie 的 *note CookieJar: 2db2.。
     Cookies `不' 会在 *note load(): 2fb4. 或 *note revert(): 2fb5. 方法
     调用前从命名的文件中加载。子类的文档位于段落 *note FileCookieJar
     的子类及其与 Web 浏览器的协同: 2fb6.。

     3.8 版更變: 文件名形参支持 *note path-like object: 472.。

 -- 類別: http.cookiejar.CookiePolicy

     此类负责确定是否应从服务器接受每个 cookie 或将其返回给服务器。

 -- 類別: 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"))

     构造参数只能以关键字参数传递，`blocked_domains' 是一个我们既不会接
     受也不会返回 cookie 的域名序列。`allowed_domains' 如果不是 *note
     None: 203.，则是仅有的我们会接受或返回的域名序列。
     `secure_protocols' 是可以添加安全 cookies 的协议序列。默认将
     `https' 和 `wss' （安全 WebSocket）考虑为安全协议。对于其他参数，参
     考 *note CookiePolicy: 2fb3. 和 *note DefaultCookiePolicy: 1129. 对
     象的文档。

     *note DefaultCookiePolicy: 1129. 实现了 Netscape 和 RFC 2965(4)
     cookies 的标准接受 / 拒绝规则。 默认情况下， RFC 2109(5) cookies（
     即在 ‘Set-Cookie’ 头中收到的 cookie-attribute 版本为 1 的 cookies ）
     将按照 RFC 2965 规则处理。 然而，如果 RFC 2965 的处理被关闭，或者
     *note rfc2109_as_netscape: 2fb7. 为 ‘True’，*note Cookie: 2fb8. 实
     例的 ‘version’ 属性设置将被为 0， RFC 2109 cookies *note CookieJar:
     2db2. 实例将 "降级" 为 Netscape cookies。 *note
     DefaultCookiePolicy: 1129. 也提供一些参数以允许一些策略微调。

 -- 類別: http.cookiejar.Cookie

     这个类代表 Netscape、 RFC 2109(6) 和 RFC 2965(7) 的 cookie 。 我们
     不希望 *note http.cookiejar: 94. 的用户构建他们自己的 *note Cookie:
     2fb8. 实例。 相反，如果有必要，请在一个 *note CookieJar: 2db2. 实例
     上调用 ‘make_cookies()’ 。

也參考
......

模块 *note urllib.request: 129.

     URL 打开带有自动的 cookie 处理。

模块 *note http.cookies: 95.

     HTTP cookie类，主要是对服务端代码有用。 *note http.cookiejar: 94. 和
     *note http.cookies: 95. 模块不相互依赖。

‘https://curl.se/rfc/cookie_spec.html’

     原始 Netscape cookie 协议的规范。 虽然这仍然是主流协议，但所有主要
     浏览器（以及 *note http.cookiejar: 94. ）实现的 "Netscape cookie协
     议" 与‘‘cookie_spec.html‘‘中描述的协议仅有几分相似之处。

RFC 2109(8) - HTTP状态管理机制

     被 RFC 2965(9) 所取代。使用 ‘Set-Cookie’ version=1 。

RFC 2965(10) - HTTP状态管理机制

     修正了错误的 Netscape 协议。 使用 ‘Set-Cookie2’ 来代替 ‘Set-Cookie’
     。 没有广泛被使用。

‘http://kristol.org/cookie/errata.html’

     未完成的:rfc:‘2965’ 勘误表。

HTTP状态管理使用方法

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/http/cookiejar.py

   (2) https://tools.ietf.org/html/rfc2965.html

   (3) https://tools.ietf.org/html/rfc2109.html

   (4) https://tools.ietf.org/html/rfc2965.html

   (5) https://tools.ietf.org/html/rfc2109.html

   (6) https://tools.ietf.org/html/rfc2109.html

   (7) https://tools.ietf.org/html/rfc2965.html

   (8) https://tools.ietf.org/html/rfc2109.html

   (9) https://tools.ietf.org/html/rfc2965.html

   (10) https://tools.ietf.org/html/rfc2965.html


File: python.info,  Node: CookieJar 和 FileCookieJar 对象,  Next: FileCookieJar 的子类及其与 Web 浏览器的协同,  Up: http cookiejar —— HTTP 客户端的 Cookie 处理

5.21.24.1 CookieJar 和 FileCookieJar 对象
.........................................

*note CookieJar: 2db2. 对象支持 *note iterator: 1171. 协议，用于迭代包含
的 *note Cookie: 2fb8. 对象。

*note CookieJar: 2db2. 有以下方法：

 -- 成員函式: CookieJar.add_cookie_header (request)

     在 `request' 中添加正确的 ‘Cookie’ 头。

     如果策略允许（即 ‘rfc2965’ 和 ‘hide_cookie2’ 属性在 *note
     CookieJar: 2db2. 的 *note CookiePolicy: 2fb3. 实例中分别为 True 和
     False ）， ‘Cookie2’ 标头也会在适当时候添加。

     如 *note urllib.request: 129. 所记载的， `request' 对象（通常是一个
     *note urllib.request.Request: 9dc. 实例）必须支持 ‘get_full_url()’
     , ‘get_host()’, ‘get_type()’, ‘unverifiable()’, ‘has_header()’,
     ‘get_header()’, ‘header_items()’, ‘add_unredirected_header()’ 和
     ‘origin_req_host’ 属性。

     3.3 版更變: `request' 对象需要 ‘origin_req_host’ 属性。对已废弃的方
     法 ‘get_origin_req_host()’ 的依赖已被移除。

 -- 成員函式: CookieJar.extract_cookies (response, request)

     从HTTP `response' 中提取 cookie，并在政策允许的情况下，将它们存储在
     *note CookieJar: 2db2. 中。

     *note CookieJar: 2db2. 将 在*response* 参数中寻找允许的
     ‘Set-Cookie’ 和 ‘Set-Cookie2’ 头信息，并适当地存储cookies（须经
     *note CookiePolicy.set_ok(): 2fbd. 方法批准）。

     `response' 对象（通常是调用 *note urllib.request.urlopen(): 87b. 或
     类似方法的结果）应该支持 ‘info()’ 方法，它返回 *note
     email.message.Message: 63b. 实例。

     如 *note urllib.request: 129. 的文档所说，`request' 对象（通常是一
     个 *note urllib.request.Request: 9dc. 实例）必须支持
     ‘get_full_url()’, ‘get_host()’, ‘unverifiable()’ 和
     ‘origin_req_host’ 属性。 该请求用于设置 cookie-attributes 的默认值
     ，以及检查 cookie 是否允许被设置。

     3.3 版更變: `request' 对象需要 ‘origin_req_host’ 属性。对已废弃的方
     法 ‘get_origin_req_host()’ 的依赖已被移除。

 -- 成員函式: CookieJar.set_policy (policy)

     设置要使用的 *note CookiePolicy: 2fb3. 实例。

 -- 成員函式: CookieJar.make_cookies (response, request)

     返回从 `response' 对象中提取的 *note Cookie: 2fb8. 对象的序列。

     关于 `response' 和 `request' 参数所需的接口，请参见 *note
     extract_cookies(): 2fbc. 的文档。

 -- 成員函式: CookieJar.set_cookie_if_ok (cookie, request)

     如果策略规定可以这样做，就设置一个 *note Cookie: 2fb8. 。

 -- 成員函式: CookieJar.set_cookie (cookie)

     设置一个 *note Cookie: 2fb8.，不需要检查策略是否应该被设置。

 -- 成員函式: CookieJar.clear ([domain[, path[, name]]])

     清除一些cookie。

     如果调用时没有参数，则清除所有的cookie。 如果给定一个参数，只有属于
     该 `domain' 的cookies将被删除。如果给定两个参数，那么属于指定的
     `domain' 和 URL `path' 的cookie将被删除。 如果给定三个参数，那么属
     于指定的 `domain' 、`path' 和 `name' 的cookie将被删除

     如果不存在匹配的 cookie，则会引发 *note KeyError: 3e9.。

 -- 成員函式: CookieJar.clear_session_cookies ()

     丢弃所有session cookie。

     丢弃所有 ‘discard’ 属性为真值的已包含 cookie（通常是因为它们没有
     ‘max-age’ 或 ‘expires’ cookie 属性，或者显式的 ‘discard’ cookie 属
     性）。 对于交互式浏览器，会话的结束通常对应于关闭浏览器窗口。

     请注意 ‘save()’ 方法并不会保存会话的 cookie，除非你通过传入一个真值
     给 `ignore_discard' 参数来提出明确的要求。

*note FileCookieJar: 2fb2. 实现了下列附加方法:

 -- 成員函式: FileCookieJar.save (filename=None, ignore_discard=False,
          ignore_expires=False)

     将 cookie 保存到文件。

     基类会引发 *note NotImplementedError: 704.。 子类可以继续不实现该方
     法。

     `filename' 为要用来保存 cookie 的文件名称。 如果未指定 `filename'，
     则会使用 ‘self.filename’ (该属性默认为传给构造器的值，如果有传入的
     话)；如果 ‘self.filename’ 为 *note None: 203.，则会引发 *note
     ValueError: 16d.。

     `ignore_discard': 即使设定了丢弃 cookie 仍然保存它们。
     `ignore_expires': 即使 cookie 已超期仍然保存它们

     文件如果已存在则会被覆盖，这将清除其所包含的全部 cookie。 已保存的
     cookie 可以使用 *note load(): 2fb4. 或 *note revert(): 2fb5. 方法来
     恢复。

 -- 成員函式: FileCookieJar.load (filename=None, ignore_discard=False,
          ignore_expires=False)

     从文件加载 cookie。

     旧的 cookie 将被保留，除非是被新加载的 cookie 所覆盖。

     其参数与 *note save(): 2fc4. 的相同。

     指定的文件必须为该类所能理解的格式，否则将引发 *note LoadError:
     2fb1.。 也可能会引发 *note OSError: 304.，例如当文件不存在的时候。

     3.3 版更變: 过去触发的 *note IOError: a73.，现在是 *note OSError:
     304. 的别名。

 -- 成員函式: FileCookieJar.revert (filename=None, ignore_discard=False,
          ignore_expires=False)

     清除所有 cookie 并从保存的文件重新加载 cookie。

     *note revert(): 2fb5. 可以引发与 *note load(): 2fb4. 相同的异常。 如
     果执行失败，对象的状态将不会被改变。

*note FileCookieJar: 2fb2. 实例具有下列公有属性:

 -- 屬性: FileCookieJar.filename

     默认的保存 cookie 的文件的文件名。 该属性可以被赋值。

 -- 屬性: FileCookieJar.delayload

     如为真值，则惰性地从磁盘加载 cookie。 该属性不应当被赋值。 这只是一
     个提示，因为它只会影响性能，而不会影响行为（除非磁盘中的 cookie 被
     改变了）。 *note CookieJar: 2db2. 对象可能会忽略它。 任何包括在标准
     库中的 *note FileCookieJar: 2fb2. 类都不会惰性地加载 cookie。


File: python.info,  Node: FileCookieJar 的子类及其与 Web 浏览器的协同,  Next: CookiePolicy 对象,  Prev: CookieJar 和 FileCookieJar 对象,  Up: http cookiejar —— HTTP 客户端的 Cookie 处理

5.21.24.2 FileCookieJar 的子类及其与 Web 浏览器的协同
.....................................................

提供了以下 *note CookieJar: 2db2. 子类用于读取和写入。

 -- 類別: http.cookiejar.MozillaCookieJar (filename, delayload=None,
          policy=None)

     一个能够以 Mozilla ‘cookies.txt’ 文件格式（该格式也被 Lynx 和
     Netscape 浏览器所使用）从磁盘加载和存储 cookie 的 *note
     FileCookieJar: 2fb2.。

          備註: 这会丢失有关 RFC 2965(1) cookie 的信息，以及有关较新或非
          标准的 cookie 属性例如 ‘port’。

          警告: 在存储之前备份你的 cookie，如果你的 cookie 丢失/损坏会造
          成麻烦的话（有一些微妙的因素可能导致文件在加载/保存的往返过程
          中发生细微的变化）。

     还要注意在 Mozilla 运行期间保存的 cookie 将可能被 Mozilla 清除。

 -- 類別: http.cookiejar.LWPCookieJar (filename, delayload=None,
          policy=None)

     一个能够以 libwww-perl 库的 ‘Set-Cookie3’ 文件格式从磁盘加载和存储
     cookie 的 *note FileCookieJar: 2fb2.。 这适用于当你想以人类可读的文
     件来保存 cookie 的情况。

     3.8 版更變: 文件名形参支持 *note path-like object: 472.。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2965.html


File: python.info,  Node: CookiePolicy 对象,  Next: DefaultCookiePolicy 对象,  Prev: FileCookieJar 的子类及其与 Web 浏览器的协同,  Up: http cookiejar —— HTTP 客户端的 Cookie 处理

5.21.24.3 CookiePolicy 对象
...........................

实现了 *note CookiePolicy: 2fb3. 接口的对象具有下列方法:

 -- 成員函式: CookiePolicy.set_ok (cookie, request)

     返回指明是否应当从服务器接受 cookie 的布尔值。

     `cookie' 是一个 *note Cookie: 2fb8. 实例。 `request' 是一个实现了由
     *note CookieJar.extract_cookies(): 2fbc. 的文档所定义的接口的对象。

 -- 成員函式: CookiePolicy.return_ok (cookie, request)

     返回指明是否应当将 cookie 返回给服务器的布尔值。

     `cookie' 是一个 *note Cookie: 2fb8. 实例。 `request' 是一个实现了
     *note CookieJar.add_cookie_header(): 2fbb. 的文档所定义的接口的对象
     。

 -- 成員函式: CookiePolicy.domain_return_ok (domain, request)

     对于给定的 cookie 域如果不应当返回 cookie 则返回 ‘False’。

     此方法是一种优化操作。 它消除了检查每个具有特定域的 cookie 的必要性
     （这可能会涉及读取许多文件）。 从 *note domain_return_ok(): 2fcd. 和
     *note path_return_ok(): 2fce. 返回真值并将所有工作留给 *note
     return_ok(): 2fcc.。

     如果 *note domain_return_ok(): 2fcd. 为 cookie 域返回真值，则会为
     cookie 路径调用 *note path_return_ok(): 2fce.。 在其他情况下，则不
     会为该 cookie 域调用 *note path_return_ok(): 2fce. 和 *note
     return_ok(): 2fcc.。 如果 *note path_return_ok(): 2fce. 返回真值，
     则会调用 *note return_ok(): 2fcc. 并附带 *note Cookie: 2fb8. 对象本
     身以进行全面检查。 在其他情况下，都永远不会为该 cookie 路径调用
     *note return_ok(): 2fcc.。

     请注意 *note domain_return_ok(): 2fcd. 会针对每个 `cookie' 域被调用
     ，而非只针对 `request' 域。 例如，该函数会针对 ‘".example.com"’ 和
     ‘"www.example.com"’ 被调用，如果 request 域为 ‘"www.example.com"’ 的
     话。 对于 *note path_return_ok(): 2fce. 也是如此。

     `request' 参数与 *note return_ok(): 2fcc. 的文档所说明的一致。

 -- 成員函式: CookiePolicy.path_return_ok (path, request)

     对于给定的 cookie 路径如果不应当返回 cookie 返回 ‘False’。

     请参阅 *note domain_return_ok(): 2fcd. 的文档。

除了实现上述方法，*note CookiePolicy: 2fb3. 接口的实现还必须提供下列属性
，指明应当使用哪种协议以及如何使用。 所有这些属性都可以被赋值。

 -- 屬性: CookiePolicy.netscape

     实现 Netscape 协议。

 -- 屬性: CookiePolicy.rfc2965

     实现 RFC 2965(1) 协议。

 -- 屬性: CookiePolicy.hide_cookie2

     不要向请求添加 ‘Cookie2’ 标头（此标头是提示服务器请求方能识别 RFC
     2965(2) cookie）。

定义 *note CookiePolicy: 2fb3. 类的最适用方式是通过子类化 *note
DefaultCookiePolicy: 1129. 并重载部分或全部上述的方法。 *note
CookiePolicy: 2fb3. 本身可被用作 ’空策略’ 以允许设置和接收所有的 cookie（
但这没有什么用处）。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2965.html

   (2) https://tools.ietf.org/html/rfc2965.html


File: python.info,  Node: DefaultCookiePolicy 对象,  Next: Cookie 对象<2>,  Prev: CookiePolicy 对象,  Up: http cookiejar —— HTTP 客户端的 Cookie 处理

5.21.24.4 DefaultCookiePolicy 对象
..................................

实现接收和返回 cookie 的标准规则。

RFC 2965(1) 和 Netscape cookie 均被涵盖。 RFC 2965 处理默认关闭。

提供自定义策略的最容易方式是重载此类并在你重载的实现中添加你自己的额外检
查之前调用其方法:

     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

在实现 *note CookiePolicy: 2fb3. 接口所要求的特性之外，该类还允许你阻止
和允许特定的域设置和接收 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 `blocked_domains' constructor argument, and ‘blocked_domains()’ and
‘set_blocked_domains()’ methods (and the corresponding argument and
methods for `allowed_domains').  If you set a whitelist, you can turn it
off again by setting it to *note None: 203.

Domains in block or allow lists that do not start with a dot must equal
the cookie domain to be matched.  For example, ‘"example.com"’ matches a
blacklist entry of ‘"example.com"’, but ‘"www.example.com"’ does not.
Domains that do start with a dot are matched by more specific domains
too.  For example, both ‘"www.example.com"’ and
‘"www.coyote.example.com"’ match ‘".example.com"’ (but ‘"example.com"’
itself does not).  IP addresses are an exception, and must match
exactly.  For example, if blocked_domains contains ‘"192.168.1.2"’ and
‘".168.1.2"’, 192.168.1.2 is blocked, but 193.168.1.2 is not.

*note DefaultCookiePolicy: 1129. 实现了下列附加方法:

 -- 成員函式: DefaultCookiePolicy.blocked_domains ()

     返回被阻止域的序列（元组类型）。

 -- 成員函式: DefaultCookiePolicy.set_blocked_domains (blocked_domains)

     设置被阻止域的序列。

 -- 成員函式: DefaultCookiePolicy.is_blocked (domain)

     Return whether `domain' is on the blacklist for setting or
     receiving cookies.

 -- 成員函式: DefaultCookiePolicy.allowed_domains ()

     返回 *note None: 203.，或者被允许域的序列（元组类型）。

 -- 成員函式: DefaultCookiePolicy.set_allowed_domains (allowed_domains)

     设置被允许域的序列，或者为 *note None: 203.。

 -- 成員函式: DefaultCookiePolicy.is_not_allowed (domain)

     Return whether `domain' is not on the whitelist for setting or
     receiving cookies.

*note DefaultCookiePolicy: 1129. 实例具有下列属性，它们都是基于同名的构
造器参数来初始化的，并且都可以被赋值。

 -- 屬性: DefaultCookiePolicy.rfc2109_as_netscape

     如为真值，则请求 *note CookieJar: 2db2. 实例将 RFC 2109(2) cookie
     (即在带有 version 值为 1 的 cookie 属性的 ‘Set-Cookie’ 标头中接收到
     的 cookie) 降级为 Netscape cookie: 即将 *note Cookie: 2fb8. 实例的
     version 属性设为 0。 默认值为 *note None: 203.，在此情况下 RFC 2109
     cookie 仅在s are downgraded if and only if RFC 2965(3) 处理被关闭时
     才会被降级。 因此，RFC 2109 cookie 默认会被降级。

通用严格性开关:

 -- 屬性: DefaultCookiePolicy.strict_domain

     不允许网站设置带国家码顶级域的包含两部分的域名例如 ‘.co.uk’,
     ‘.gov.uk’, ‘.co.nz’ 等。 此开关尚未十分完善，并不保证有效！

RFC 2965(4) 协议严格性开关:

 -- 屬性: DefaultCookiePolicy.strict_rfc2965_unverifiable

     遵循针对不可验证事务的 RFC 2965(5) 规则（不可验证事务通常是由重定向
     或请求发布在其它网站的图片导致的）。 如果该属性为假值，则 `永远不会
     ' 基于可验证性而阻止 cookie。

Netscape 协议严格性开关:

 -- 屬性: DefaultCookiePolicy.strict_ns_unverifiable

     即便是对 Netscape cookie 也要应用 RFC 2965(6) 规则。

 -- 屬性: DefaultCookiePolicy.strict_ns_domain

     指明针对 Netscape cookie 的域匹配规则的严格程度。 可接受的值见下文
     。

 -- 屬性: DefaultCookiePolicy.strict_ns_set_initial_dollar

     忽略 Set-Cookie 中的 cookie: 即名称前缀为 ‘'{TX-PL-LABEL}#x27;’ 的
     标头。

 -- 屬性: DefaultCookiePolicy.strict_ns_set_path

     不允许设置路径与请求 URL 路径不匹配的 cookie。

‘strict_ns_domain’ 是一组旗标。 其值是通过或运算来构造的（例如，
‘DomainStrictNoDots|DomainStrictNonDomain’ 表示同时设置两个旗标）。

 -- 屬性: DefaultCookiePolicy.DomainStrictNoDots

     当设置 cookie 是，’host prefix’ 不可包含点号（例如
     ‘www.foo.bar.com’ 不能为 ‘.bar.com’ 设置 cookie，因为 ‘www.foo’ 包
     含了一个点号）。

 -- 屬性: DefaultCookiePolicy.DomainStrictNonDomain

     没有显式指明Cookies that did not explicitly specify a ‘domain’
     cookie 属性的 cookie 只能被返回给与设置 cookie 的域相同的域（例如
     ‘spam.example.com’ 不会是来自 ‘example.com’ 的返回 cookie，如果该域
     名没有 ‘domain’ cookie 属性的话）。

 -- 屬性: DefaultCookiePolicy.DomainRFC2965Match

     当设置 cookie 时，要求完整的 RFC 2965(7) 域匹配。

下列属性是为方便使用而提供的，是上述旗标的几种最常用组合:

 -- 屬性: DefaultCookiePolicy.DomainLiberal

     等价于 0 (即所有上述 Netscape 域严格性旗标均停用)。

 -- 屬性: DefaultCookiePolicy.DomainStrict

     等价于 ‘DomainStrictNoDots|DomainStrictNonDomain’。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2965.html

   (2) https://tools.ietf.org/html/rfc2109.html

   (3) https://tools.ietf.org/html/rfc2965.html

   (4) https://tools.ietf.org/html/rfc2965.html

   (5) https://tools.ietf.org/html/rfc2965.html

   (6) https://tools.ietf.org/html/rfc2965.html

   (7) https://tools.ietf.org/html/rfc2965.html


File: python.info,  Node: Cookie 对象<2>,  Next: 示例<38>,  Prev: DefaultCookiePolicy 对象,  Up: http cookiejar —— HTTP 客户端的 Cookie 处理

5.21.24.5 Cookie 对象
.....................

*note Cookie: 2fb8. 实例具有与各种 cookie 标准中定义的标准 cookie 属性大
致对应的 Python 属性。 这并非一一对应，因为存在复杂的赋默认值的规则，因
为 ‘max-age’ 和 ‘expires’ cookie 属性包含相同信息，也因为 RFC 2109(1)
cookie 可以被 *note http.cookiejar: 94. 从第 1 版 ’降级为’ 第 0 版
(Netscape) cookie。

对这些属性的赋值在 *note CookiePolicy: 2fb3. 方法的极少数情况以外应该都
是不必要的。 该类不会强制内部一致性，因此如果这样做则你应当清楚自己在做
什么。

 -- 屬性: Cookie.version

     整数或 *note None: 203.。 Netscape cookie 的 *note version: 2fe6. 值
     为 0。 RFC 2965(2) 和 RFC 2109(3) cookie 的 ‘version’ cookie 属性值
     为 1。 但是，请注意 *note http.cookiejar: 94. 可以将 RFC 2109
     cookie ’降级’ 为 Netscape cookie，在此情况下 *note version: 2fe6. 值
     也为 0。

 -- 屬性: Cookie.name

     Cookie 名称（一个字符串）。

 -- 屬性: Cookie.value

     Cookie 值（一个字符串），或为 *note None: 203.。

 -- 屬性: Cookie.port

     代表一个端口或一组端口（例如 ’80’ 或 ’80,8080’）的字符串，或为
     *note None: 203.。

 -- 屬性: Cookie.path

     Cookie 路径 (字符串类型，例如 ‘'/acme/rocket_launchers'’)。

 -- 屬性: Cookie.secure

     如果 cookie 应当只能通过安全连接返回则为 ‘True’。

 -- 屬性: Cookie.expires

     整数类型的过期时间，以距离 Unix 纪元的秒数表示，或者为 *note None:
     203.。 另请参阅 *note is_expired(): 2fed. 方法。

 -- 屬性: Cookie.discard

     如果是会话 cookie 则为 ‘True’。

 -- 屬性: Cookie.comment

     来自服务器的解释此 cookie 功能的字符串形式的注释，或者为 *note
     None: 203.。

 -- 屬性: Cookie.comment_url

     链接到来自服务器的解释此 cookie 功能的注释的 URL，或者为 *note
     None: 203.。

 -- 屬性: Cookie.rfc2109

     如果 cookie 是作为 RFC 2109(4) cookie 被接收（即该 cookie 是在
     ‘Set-Cookie’ 标头中送达，且该标头的 Version cookie 属性的值为 1）则
     为 ‘True’。 之所以要提供该属性是因为 *note http.cookiejar: 94. 可能
     会从 RFC 2109 cookies ’降级’ 为 Netscape cookie，在此情况下 *note
     version: 2fe6. 值为 0。

 -- 屬性: Cookie.port_specified

     如果服务器显式地指定了一个端口或一组端口（在 ‘Set-Cookie’ /
     ‘Set-Cookie2’ 标头中）则为 ‘True’。

 -- 屬性: Cookie.domain_specified

     如果服务器显式地指定了一个域则为 ‘True’。

 -- 屬性: Cookie.domain_initial_dot

     该属性为 ‘True’ 表示服务器显式地指定了以一个点号 (‘'.'’) 打头的域。

Cookie 可能还有额外的非标准 cookie 属性。 这些属性可以通过下列方法来访问
:

 -- 成員函式: Cookie.has_nonstandard_attr (name)

     如果 cookie 具有相应名称的 cookie 属性则返回 ‘True’。

 -- 成員函式: Cookie.get_nonstandard_attr (name, default=None)

     如果 cookie 具有相应名称的 cookie 属性，则返回其值。 否则，返回
     `default'。

 -- 成員函式: Cookie.set_nonstandard_attr (name, value)

     设置指定名称的 cookie 属性的值。

*note Cookie: 2fb8. 类还定义了下列方法:

 -- 成員函式: Cookie.is_expired (now=None)

     如果 cookie 传入了服务器请求其所应过期的时间则为 ‘True’。 如果给出
     `now' 值（距离 Unix 纪元的秒数），则返回在指定的时间 cookie 是否已
     过期。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2109.html

   (2) https://tools.ietf.org/html/rfc2965.html

   (3) https://tools.ietf.org/html/rfc2109.html

   (4) https://tools.ietf.org/html/rfc2109.html


File: python.info,  Node: 示例<38>,  Prev: Cookie 对象<2>,  Up: http cookiejar —— HTTP 客户端的 Cookie 处理

5.21.24.6 示例
..............

第一个例子显示了 *note http.cookiejar: 94. 的最常见用法:

     import http.cookiejar, urllib.request
     cj = http.cookiejar.CookieJar()
     opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
     r = opener.open("http://example.com/")

这个例子演示了如何使用你的 Netscape, Mozilla 或 Lynx cookie 打开一个 URL
(假定 cookie 文件位置采用 Unix/Netscape 惯例):

     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/")

下一个例子演示了 *note DefaultCookiePolicy: 1129. 的使用。 启用 RFC
2965(1) cookie，在设置和返回 Netscape cookie 时更严格地限制域，以及阻止
某些域设置 cookie 或返回它们:

     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/")

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2965.html


File: python.info,  Node: xmlrpc --- XMLRPC 服务端与客户端模块,  Next: xmlrpc client --- XML-RPC 客户端访问,  Prev: http cookiejar —— HTTP 客户端的 Cookie 处理,  Up: 互联网协议和支持

5.21.25 ‘xmlrpc’ — XMLRPC 服务端与客户端模块
--------------------------------------------

XML-RPC 是一种远程过程调用方法，它使用通过 HTTP 传递的 XML 作为载体。 有
了它，客户端可以在远程服务器上调用带参数的方法（服务器以 URI 命名）并获
取结构化的数据。

‘xmlrpc’ 是一个集合了 XML-RPC 服务端与客户端实现模块的包。 这些模块是:

   * *note xmlrpc.client: 148.

   * *note xmlrpc.server: 149.


File: python.info,  Node: xmlrpc client --- XML-RPC 客户端访问,  Next: xmlrpc server --- 基本 XML-RPC 服务器,  Prev: xmlrpc --- XMLRPC 服务端与客户端模块,  Up: 互联网协议和支持

5.21.26 ‘xmlrpc.client’ — XML-RPC 客户端访问
--------------------------------------------

`源代码:' Lib/xmlrpc/client.py(1)

__________________________________________________________________

XML-RPC 是一种远程过程调用方法，它以使用 HTTP(S) 传递的 XML 作为载体。 通
过它，客户端可以在远程服务器（服务器以 URI 指明）上调用带参数的方法并获
取结构化的数据。 本模块支持编写 XML-RPC 客户端代码；它会处理在通用
Python 对象和 XML 之间进行在线翻译的所有细节。

     警告: *note xmlrpc.client: 148. 模块对于恶意构建的数据是不安全的。
     如果你需要解析不受信任或未经身份验证的数据，请参阅 *note XML 漏洞:
     2b34.。

3.5 版更變: 对于 HTTPS URI，现在 *note xmlrpc.client: 148. 默认会执行所
有必要的证书和主机名检查。

 -- 類別: xmlrpc.client.ServerProxy (uri, transport=None, encoding=None,
          verbose=False, allow_none=False, use_datetime=False,
          use_builtin_types=False, *, headers=(), context=None)

     *note ServerProxy: 37f. 实例是管理与远程 XML-RPC 服务器通信的对象。
     要求的第一个参数为 URI (统一资源定位符)，通常就是服务器的 URL。 可
     选的第二个参数为传输工厂实例；在默认情况下对于 https: URL 是一个内
     部 ‘SafeTransport’ 实例，在其他情况下则是一个内部 HTTP ‘Transport’
     实例。 可选的第三个参数为编码格式，默认为 UTF-8。 可选的第四个参数
     为调试旗标。

     下列形参控制所返回代理实例的使用。 如果 `allow_none' 为真值，则
     Python 常量 ‘None’ 将被转写为 XML；默认行为是针对 ‘None’ 引发 *note
     TypeError: 1fe.。 这是对 XML-RPC 规格的一个常用扩展，但并不被所有客
     户端和服务器所支持；请参阅
     http://ontosys.com/xml-rpc/extensions.php(2) 了解详情。
     `use_builtin_types' 旗标可被用来将日期/时间值表示为 *note
     datetime.datetime: 19f. 对象而将二进制数据表示为 *note bytes: 172.
     对象；此旗标默认为假值。 *note datetime.datetime: 19f, *note bytes:
     172. 和 *note bytearray: 173. 对象可以被传给调用操作。 `headers' 形
     参为可选的随每次请求发送的 HTTP 标头序列，其形式为包含代表标头名称
     和值的 2 元组的序列 (例如 ‘[(’Header-Name’, ’value’)]’)。 已不再适
     用的 `use_datetime' 旗标与 `use_builtin_types' 类似但它只针对日期
     /时间值。

3.3 版更變: 增加了 `use_builtin_types' 旗标。

3.8 版更變: 增加了 `headers' 形参。

HTTP 和 HTTPS 传输均支持用于 HTTP 基本身份验证的 URL 语法扩展:
‘http://user:pass@host:port/path’。 ‘user:pass’ 部分将以 base64 编码为
HTTP ’Authorization’ 标头，并在发起调用 XML-RPC 方法时作为连接过程的一部
分发送给远程服务器。 你只需要在远程服务器要求基本身份验证账号和密码时使
用此语法。 如果提供了 HTTPS URL，`context' 可以为 *note ssl.SSLContext:
4e9. 并配置有下层 HTTPS 连接的 SSL 设置。

返回的实例是一个代理对象，具有可被用来在远程服务器上发起相应 RPC 调用的
方法。 如果远程服务器支持内省 API，则也可使用该代理对象在远程服务器上查
询它所支持的方法（服务发现）并获取其他服务器相关的元数据

适用的类型（即可通过 XML 生成 marshall 对象），包括如下类型（除了已说明
的例外，它们会被反 marshall 为同样的 Python 类型）:

XML-RPC类型                Python数据类型
                           
---------------------------------------------------------------------------------------
                           
‘boolean’                  *note bool: 2bd.
                           
                           
‘int’, ‘i1’, ‘i2’, ‘i4’,   *note int: 204. 的范围从 -2147483648 到 2147483647。值将
‘i8’ 或者 ‘biginteger’     获得 ‘<int>’ 标志。
                           
                           
‘double’ 或 ‘float’        *note float: 1fd.。值将获得 ‘<double>’ 标志。
                           
                           
‘string’                   *note str: 205.
                           
                           
‘array’                    *note list: 1f8. 或 *note tuple: 1a2. 包含整合元素。数组
                           以 *note lists: 1f8. 形式返回。
                           
                           
‘struct’                   *note dict: 164.。 键必须为字符串，值可以为任何适用的类型
                           。 可以传入用户自定义类的对象；只有其
                           *note __dict__: 5f5. 属性会被传输。
                           
                           
‘dateTime.iso8601’         *note DateTime: 2ffd. 或 *note datetime.datetime: 19f.。
                           返回的类型取决于 `use_builtin_types' 和 `use_datetime' 标
                           志的值。
                           
                           
‘base64’                   *note Binary: 2ffe, *note bytes: 172. 或
                           *note bytearray: 173.。返回的类型取决于
                           `use_builtin_types' 标志的值。
                           
                           
‘nil’                      ‘None’ 常量。仅当 `allow_none' 为true时才允许传递。
                           
                           
‘bigdecimal’               *note decimal.Decimal: 2c0.  仅返回类型。
                           

这是This is the full set of data types supported by XML-RPC 所支持数据类
型的完整集合。 方法调用也可能引发一个特殊的 *note Fault: 2fff. 实例，用
来提示 XML-RPC 服务器错误，或是用 *note ProtocolError: 3000. 来提示
HTTP/HTTPS 传输层中的错误。 *note Fault: 2fff. 和 *note ProtocolError:
3000. 都派生自名为 ‘Error’ 的基类。 请注意 xmlrpc client 模块目前不可
marshal 内置类型的子类的实例。

当传入字符串时，XML 中的特殊字符如 ‘<’, ‘>’ 和 ‘&’ 将被自动转义。 但是，
调用方有责任确保字符串中没有 XML 中不允许的字符，例如 ASCII 值在 0 和 31
之间的控制字符（当然，制表、换行和回车除外）；不这样做将导致 XML-RPC 请
求的 XML 格式不正确。 如果你必须通过 XML-RPC 传入任意字节数据，请使用
*note bytes: 172. 或 *note bytearray: 173. 类或者下文描述的 *note
Binary: 2ffe. 包装器类。

‘Server’ 被保留作为 *note ServerProxy: 37f. 的别名用于向下兼容。 新的代
码应当使用 *note ServerProxy: 37f.。

3.5 版更變: 增加了 `context' 参数。

3.6 版更變: 增加了对带有前缀的类型标签的支持 (例如 ‘ex:nil’)。 增加了对
反 marshall 被 Apache XML-RPC 实现用于表示数值的附加类型的支持: ‘i1’,
‘i2’, ‘i8’, ‘biginteger’, ‘float’ 和 ‘bigdecimal’。 请参阅
‘http://ws.apache.org/xmlrpc/types.html’ 了解详情。

也參考
......

XML-RPC HOWTO(3)

     以多种语言对 XML-RPC 操作和客户端软件进行了很好的说明。 包含
     XML-RPC 客户端开发者所需知道的几乎任何事情。

XML-RPC Introspection(4)

     描述了用于内省的 XML-RPC 协议扩展。

XML-RPC Specification(5)

     官方规范说明。

Unofficial XML-RPC Errata(6)

     Fredrik Lundh 的 "非官方勘误表，旨在澄清 XML-RPC 规范说明的某些细节
     ，以及关于在设计你自己的 XML-RPC 实现时的 ’最佳实践’ 的提示。"

* Menu:

* ServerProxy 对象::
* 日期時間物件::
* Binary 对象::
* Fault 对象::
* ProtocolError 对象::
* MultiCall 对象::
* 便捷函数::
* 客户端用法的示例::
* 客户端与服务器用法的示例::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/xmlrpc/client.py

   (2) 
https://web.archive.org/web/20130120074804/http://ontosys.com/xml-rpc/extensions.php

   (3) http://www.tldp.org/HOWTO/XML-RPC-HOWTO/index.html

   (4) http://xmlrpc-c.sourceforge.net/introspection.html

   (5) http://xmlrpc.scripting.com/spec.html

   (6) http://effbot.org/zone/xmlrpc-errata.htm


File: python.info,  Node: ServerProxy 对象,  Next: 日期時間物件,  Up: xmlrpc client --- XML-RPC 客户端访问

5.21.26.1 ServerProxy 对象
..........................

*note ServerProxy: 37f. 实例有一个方法与 XML-RPC 服务器所接受的每个远程
过程调用相对应。 调用该方法会执行一个 RPC，通过名称和参数签名来调度（例
如同一个方法名可通过多个参数签名来重载）。 RPC 结束时返回一个值，它可以
是适用类型的返回数据或是表示错误的 *note Fault: 2fff. 或 *note
ProtocolError: 3000. 对象。

支持 XML 内省 API 的服务器还支持一些以保留的 ‘system’ 属性分组的通用方法
:

 -- 成員函式: ServerProxy.system.listMethods ()

     此方法返回一个字符串列表，每个字符串都各自对应 XML-RPC 服务器所支持
     的（非系统）方法。

 -- 成員函式: ServerProxy.system.methodSignature (name)

     此方法接受一个形参，即某个由 XML-RPC 服务器所实现的方法名称。 它返
     回一个由此方法可能的签名组成的数组。 一个签名就是一个类型数组。 这
     些类型中的第一个是方法的的返回类型，其余的均为形参。

     由于允许多个签名（即重载），此方法是返回一个签名列表而非一个单例。

     签名本身被限制为一个方法所期望的最高层级形参。 举例来说如果一个方法
     期望有一个结构体数组作为形参，并返回一个字符串，则其签名就是
     "string, array"。 如果它期望有三个整数并返回一个字符串，则其签名是
     "string, int, int, int"。

     如果方法没有定义任何签名，则将返回一个非数组值。 在 Python 中这意味
     着返回值的类型为列表以外的类型。

 -- 成員函式: ServerProxy.system.methodHelp (name)

     此方法接受一个形参，即 XML-RPC 服务器所实现的某个方法的名称。 它返
     回描述相应方法用法的文档字符串。 如果没有可用的文档字符串，则返回空
     字符串。 文档字符串可以包含 HTML 标记。

3.5 版更變: *note ServerProxy: 37f. 的实例支持 *note context manager:
661. 协议用于关闭下层传输。

以下是一个可运行的示例。 服务器端代码:

     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()

前述服务器的客户端代码:

     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)))


File: python.info,  Node: 日期時間物件,  Next: Binary 对象,  Prev: ServerProxy 对象,  Up: xmlrpc client --- XML-RPC 客户端访问

5.21.26.2 日期時間物件
......................

 -- 類別: xmlrpc.client.DateTime

     该类的初始化可以使用距离 Unix 纪元的秒数、时间元组、ISO 8601 时间
     /日期字符串或 *note datetime.datetime: 19f. 实例。 它具有下列方法，
     主要是为 marshall 和反 marshall 代码的内部使用提供支持:

      -- 成員函式: decode (string)

          接受一个字符串作为实例的新时间值。

      -- 成員函式: encode (out)

          将此 *note DateTime: 2ffd. 条目的 XML-RPC 编码格式写入到 `out'
          流对象。

     它还通过富比较和 *note __repr__(): 44a. 方法来支持某些 Python 内置
     操作。

以下是一个可运行的示例。 服务器端代码:

     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()

前述服务器的客户端代码:

     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"))


File: python.info,  Node: Binary 对象,  Next: Fault 对象,  Prev: 日期時間物件,  Up: xmlrpc client --- XML-RPC 客户端访问

5.21.26.3 Binary 对象
.....................

 -- 類別: xmlrpc.client.Binary

     该类的初始化可以使用字节数据（可包括 NUL）。 对 *note Binary: 2ffe.
     对象的初始访问是由一个属性来提供的:

      -- 屬性: data

          被 *note Binary: 2ffe. 实例封装的二进制数据。 该数据以 *note
          bytes: 172. 对象的形式提供。

     *note Binary: 2ffe. 对象具有下列方法，支持这些方法主要是供 marshall
     和反 marshall 代码在内部使用:

      -- 成員函式: decode (bytes)

          接受一个 base64 *note bytes: 172. 对象并将其解码为实例的新数据
          。

      -- 成員函式: encode (out)

          将此二进制条目的 XML-RPC base 64 编码格式写入到 `out' 流对象。

          被编码数据将依据 RFC 2045 第 6.8 节(1) 每 76 个字符换行一次，
          这是撰写 XML-RPC 规范说明时 base64 规范的事实标准。

     它还通过 *note __eq__(): 44b. 和 *note __ne__(): f18. 方法来支持某
     些 Python 内置运算符。

该二进制对象的示例用法。 我们将通过 XMLRPC 来传输一张图片:

     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()

客户端会获取图片并将其保存为一个文件:

     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)

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2045.html#section-6.8


File: python.info,  Node: Fault 对象,  Next: ProtocolError 对象,  Prev: Binary 对象,  Up: xmlrpc client --- XML-RPC 客户端访问

5.21.26.4 Fault 对象
....................

 -- 類別: xmlrpc.client.Fault

     *note Fault: 2fff. 对象封装了 XML-RPC fault 标签的内容。 Fault 对象
     具有下列属性:

      -- 屬性: faultCode

          A string indicating the fault type.

      -- 屬性: faultString

          一个包含与 fault 相关联的诊断消息的字符串。

在接下来的示例中我们将通过返回一个复数类型的值来故意引发一个 *note
Fault: 2fff.。 服务器端代码:

     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()

前述服务器的客户端代码:

     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)


File: python.info,  Node: ProtocolError 对象,  Next: MultiCall 对象,  Prev: Fault 对象,  Up: xmlrpc client --- XML-RPC 客户端访问

5.21.26.5 ProtocolError 对象
............................

 -- 類別: xmlrpc.client.ProtocolError

     *note ProtocolError: 3000. 对象描述了下层传输层中的协议错误（例如当
     URI 所指定的服务器不存在时的 404 ’not found’ 错误）。 它具有下列属
     性:

      -- 屬性: url

          触发错误的 URI 或 URL。

      -- 屬性: errcode

          错误代码。

      -- 屬性: errmsg

          错误消息或诊断字符串。

      -- 屬性: headers

          一个包含触发错误的 HTTP/HTTPS 请求的标头的字典。

在接下来的示例中我们将通过提供一个无效的 URI 来故意引发一个 *note
ProtocolError: 3000.:

     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)


File: python.info,  Node: MultiCall 对象,  Next: 便捷函数,  Prev: ProtocolError 对象,  Up: xmlrpc client --- XML-RPC 客户端访问

5.21.26.6 MultiCall 对象
........................

*note MultiCall: 301a. 对象提供了一种将对远程服务器的多个调用封装为一个
单独请求的方式 (1)。

 -- 類別: xmlrpc.client.MultiCall (server)

     创建一个用于盒式方法调用的对象。 `server' 是调用的最终目标。 可以对
     结果对象发起调用，但它们将立即返回 ‘None’，并只在 *note MultiCall:
     301a. 对象中存储调用名称和形参。 调用该对象本身会导致所有已存储的调
     用作为一个单独的 ‘system.multicall’ 请求被发送。 此调用的结果是一个
     *note generator: a83.；迭代这个生成器会产生各个结果。

以下是该类的用法示例。 服务器端代码:

     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()

前述服务器的客户端代码:

     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))

   ---------- Footnotes ----------

   (1) (1) 此做法被首次提及是在 a discussion on xmlrpc.com
(https://web.archive.org/web/20060624230303/http://www.xmlrpc.com/discuss/msgReader$1208?mode=topic)。


File: python.info,  Node: 便捷函数,  Next: 客户端用法的示例,  Prev: MultiCall 对象,  Up: xmlrpc client --- XML-RPC 客户端访问

5.21.26.7 便捷函数
..................

 -- 函式: xmlrpc.client.dumps (params, methodname=None,
          methodresponse=None, encoding=None, allow_none=False)

     请 `params' 转换为一个 XML-RPC 请求。 或者当 `methodresponse' 为真
     值时则转换为一个请求。 `params' 可以是一个参数元组或是一个 *note
     Fault: 2fff. 异常类的实例。 如果 `methodresponse' 为真值，只有单独
     的值可以被返回，这意味着 `params' 的长度必须为 1。 如果提供了
     `encoding'，则在生成的 XML 会使用该编码格式；默认的编码格式为
     UTF-8。 Python 的 *note None: 203. 值不可在标准 XML-RPC 中使用；要
     通过扩展来允许使用它，请为 `allow_none' 提供一个真值。

 -- 函式: xmlrpc.client.loads (data, use_datetime=False,
          use_builtin_types=False)

     将一个 XML-RPC 请求或响应转换为 Python 对象 ‘(params, methodname)’。
     `params' 是一个参数元组；`methodname' 是一个字符串，或者如果数据包
     没有提供方法名则为 ‘None’。 如果 XML-RPC 数据包是代表一个故障条件，
     则此函数将引发一个 *note Fault: 2fff. 异常。 `use_builtin_types' 旗
     标可被用于将日期/时间值表示为 *note datetime.datetime: 19f. 对象并
     将二进制数据表示为 *note bytes: 172. 对象；此旗标默认为假值。

     已过时的 `use_datetime' 旗标与 `use_builtin_types' 类似但只作用于日
     期/时间值。

     3.3 版更變: 增加了 `use_builtin_types' 旗标。


File: python.info,  Node: 客户端用法的示例,  Next: 客户端与服务器用法的示例,  Prev: 便捷函数,  Up: xmlrpc client --- XML-RPC 客户端访问

5.21.26.8 客户端用法的示例
..........................

     # 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)

要通过 HTTP 代理访问一个 XML-RPC 服务器，你必须自行定义一个传输。 下面的
例子演示了具体做法:

     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))


File: python.info,  Node: 客户端与服务器用法的示例,  Prev: 客户端用法的示例,  Up: xmlrpc client --- XML-RPC 客户端访问

5.21.26.9 客户端与服务器用法的示例
..................................

参见 *note SimpleXMLRPCServer 示例: 3021.。

註解
....


File: python.info,  Node: xmlrpc server --- 基本 XML-RPC 服务器,  Next: ipaddress --- IPv4/IPv6 操作库,  Prev: xmlrpc client --- XML-RPC 客户端访问,  Up: 互联网协议和支持

5.21.27 ‘xmlrpc.server’ — 基本 XML-RPC 服务器
---------------------------------------------

`源代码:' Lib/xmlrpc/server.py(1)

__________________________________________________________________

*note xmlrpc.server: 149. 模块为以 Python 编写 XML-RPC 服务器提供了一个
基本服务器框架。 服务器可以是独立的，使用 *note SimpleXMLRPCServer:
3024.，或是嵌入某个 CGI 环境中，使用 *note CGIXMLRPCRequestHandler:
3025.。

     警告: *note xmlrpc.server: 149. 模块对于恶意构建的数据是不安全的。
     如果你需要解析不受信任或未经身份验证的数据，请参阅 *note XML 漏洞:
     2b34.。

 -- 類別: xmlrpc.server.SimpleXMLRPCServer (addr,
          requestHandler=SimpleXMLRPCRequestHandler, logRequests=True,
          allow_none=False, encoding=None, bind_and_activate=True,
          use_builtin_types=False)

     创建一个新的服务器实例。 这个类提供了一些用来注册可以被 XML-RPC 协
     议所调用的函数的方法。 `requestHandler' 形参应该是一个用于请求处理
     句柄实例的工厂函数；它默认为 *note SimpleXMLRPCRequestHandler:
     3026.。 `addr' 和 `requestHandler' 形参会被传给 *note
     socketserver.TCPServer: 2f50. 构造器。 如果 `logRequests' 为真值（
     默认），请求将被记录到日志；将此形参设为假值将关闭日志记录。
     `allow_none' 和 `encoding' 形参会被传给 *note xmlrpc.client: 148. 并
     控制将从服务器返回的 XML-RPC 响应。 `bind_and_activate' 形参控制
     ‘server_bind()’ 和 ‘server_activate()’ 是否会被构造器立即调用；它默
     认为真值。 将其设为假值将允许代码在地址被绑定之前操作
     `allow_reuse_address' 类变量。 `use_builtin_types' 形参会被传给
     *note loads(): 301d. 函数并控制当收到日期/时间值或二进制数据时将处
     理哪些类型；它默认为假值。

     3.3 版更變: 增加了 `use_builtin_types' 旗标。

 -- 類別: xmlrpc.server.CGIXMLRPCRequestHandler (allow_none=False,
          encoding=None, use_builtin_types=False)

     创建一个新的实例来处理 CGI 环境中的 XML-RPC 请求。 `allow_none' 和
     `encoding' 形参会被传递给 *note xmlrpc.client: 148. 并控制将要从服
     务器返回的 XML-RPC 响应。 `use_builtin_types' 形参会被传递给 *note
     loads(): 301d. 函数并控制当接收到日期/时间值或二进制数据时要处理哪
     种类型；该形参默认为假值。

     3.3 版更變: 增加了 `use_builtin_types' 旗标。

 -- 類別: xmlrpc.server.SimpleXMLRPCRequestHandler

     创建一个新的请求处理句柄实例。 该请求处理句柄支持 ‘POST’ 请求并会修
     改日志记录操作以便使用传递给 *note SimpleXMLRPCServer: 3024. 形参的
     `logRequests' 形参。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/xmlrpc/server.py


File: python.info,  Node: SimpleXMLRPCServer 对象,  Next: CGIXMLRPCRequestHandler,  Up: xmlrpc server --- 基本 XML-RPC 服务器

5.21.27.1 SimpleXMLRPCServer 对象
.................................

*note SimpleXMLRPCServer: 3024. 类是基于 *note socketserver.TCPServer:
2f50. 并提供了一个创建简单、独立的 XML-RPC 服务器的方式。

 -- 成員函式: SimpleXMLRPCServer.register_function (function=None,
          name=None)

     注册一个可以响应 XML-RPC 请求的函数。 如果给出了 `name'，则它将成为
     与 `function' 相关联的方法名，否则将使用 ‘function.__name__’。
     `name' 是一个字符串，并可能包含不可在 Python 标识符中出现的字符，包
     括句点符。

     此方法也可被用作装饰器。 当被用作装饰器时，`name' 只能被指定为以
     `name' 注册的 `function' 的一个关键字参数。 如果没有指定 `name'，则
     将使用 ‘function.__name__’。

     3.7 版更變: *note register_function(): 3029. 可被用作装饰器。

 -- 成員函式: SimpleXMLRPCServer.register_instance (instance,
          allow_dotted_names=False)

     注册一个被用来公开未使用 *note register_function(): 3029. 注册的方
     法名的对象。 如果 `instance' 包含 ‘_dispatch()’ 方法，它将被调用并
     附带被请求的方法名和来自请求的形参。 它的 API 是 ‘def
     _dispatch(self, method, params)’ (请注意 `params' 并不表示变量参数
     列表)。 如果它调用了一个下层函数来执行任务，该函数将以
     ‘func(*params)’ 的形式被调用，即扩展了形参列表。 来自 ‘_dispatch()’
     的返回值将作为结果被返回给客户端。 如果 `instance' 不包含
     ‘_dispatch()’ 方法，则会在其中搜索与被请求的方法名相匹配的属性。

     如果可选的 `allow_dotted_names' 参数为真值且该实例没有
     ‘_dispatch()’ 方法，则如果被请求的方法名包含句点符，会单独搜索该方
     法名的每个组成部分，其效果就是执行了简单的分层级搜索。 通过搜索找到
     的值将随即附带来自请求的形参被调用，并且返回值会被回传给客户端。

          警告: 启用 `allow_dotted_names' 选项将允许入侵者访问你的模块的
          全局变量并可能允许入侵者在你的机器上执行任意代码。 仅可在安全
          、封闭的网络中使用此选项。

 -- 成員函式: SimpleXMLRPCServer.register_introspection_functions ()

     注册 XML-RPC 内省函数 ‘system.listMethods’, ‘system.methodHelp’ 和
     ‘system.methodSignature’。

 -- 成員函式: SimpleXMLRPCServer.register_multicall_functions ()

     注册 XML-RPC 多调用函数 system.multicall。

 -- 屬性: SimpleXMLRPCRequestHandler.rpc_paths

     一个必须为元组类型的属性值，其中列出所接收 XML-RPC 请求的有效路径部
     分。 发送到其他路径的请求将导致 404 "no such page" HTTP 错误。 如果
     此元组为空，则所有路径都将被视为有效。 默认值为 ‘('/', '/RPC2')’。

* Menu:

* SimpleXMLRPCServer 示例::


File: python.info,  Node: SimpleXMLRPCServer 示例,  Up: SimpleXMLRPCServer 对象

5.21.27.2 SimpleXMLRPCServer 示例
.................................

服务器端代码:

     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()

以下客户端代码将调用上述服务器所提供的方法:

     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())

‘register_function()’ 也可被用作装饰器。 上述服务器端示例可以通过装饰器
方式来注册函数:

     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()

以下包括在 ‘Lib/xmlrpc/server.py’ 模块中的例子演示了一个允许带点号名称并
注册有多调用函数的服务器。

     警告: 启用 `allow_dotted_names' 选项将允许入侵者访问你的模块的全局
     变量并可能允许入侵者在你的机器上执行任意代码。 仅可在安全、封闭的网
     络中使用此示例。

     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)

这个 ExampleService 演示程序可通过命令行发起调用:

     python -m xmlrpc.server

可与上述服务器进行交互的客户端包括在 ‘Lib/xmlrpc/client.py’ 中:

     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)

这个可与示例 XMLRPC 服务器进行交互的客户端的启动方式如下:

     python -m xmlrpc.client


File: python.info,  Node: CGIXMLRPCRequestHandler,  Next: XMLRPC 服务器文档,  Prev: SimpleXMLRPCServer 对象,  Up: xmlrpc server --- 基本 XML-RPC 服务器

5.21.27.3 CGIXMLRPCRequestHandler
.................................

*note CGIXMLRPCRequestHandler: 3025. 类可被用来处理发送给 Python CGI 脚
本的 XML-RPC 请求。

 -- 成員函式: CGIXMLRPCRequestHandler.register_function (function=None,
          name=None)

     注册一个可以响应 XML-RPC 请求的函数。 如果给出了 `name'，则它将成为
     与 `function' 相关联的方法名，否则将使用 ‘function.__name__’。
     `name' 是一个字符串，并可能包含不可在 Python 标识符中出现的字符，包
     括句点符。

     此方法也可被用作装饰器。 当被用作装饰器时，`name' 只能被指定为以
     `name' 注册的 `function' 的一个关键字参数。 如果没有指定 `name'，则
     将使用 ‘function.__name__’。

     3.7 版更變: *note register_function(): 3030. 可被用作装饰器。

 -- 成員函式: CGIXMLRPCRequestHandler.register_instance (instance)

     注册一个对象用来公开未使用 *note register_function(): 3030. 进行注
     册的方法名。 如果实例包含 ‘_dispatch()’ 方法，它会附带所请求的方法
     名和来自请求的形参被调用；返回值会作为结果被返回给客户端。 如果实例
     不包含 ‘_dispatch()’ 方法，则在其中搜索与所请求方法名相匹配的属性；
     如果所请求方法名包含句点，则会分别搜索方法名的每个部分，其效果就是
     执行了简单的层级搜索。 搜索找到的值将附带来自请求的形参被调用，其返
     回值会被返回给客户端。

 -- 成員函式: CGIXMLRPCRequestHandler.register_introspection_functions
          ()

     注册 XML-RPC 内海函数 ‘system.listMethods’, ‘system.methodHelp’ 和
     ‘system.methodSignature’。

 -- 成員函式: CGIXMLRPCRequestHandler.register_multicall_functions ()

     注册 XML-RPC 多调用函数 ‘system.multicall’。

 -- 成員函式: CGIXMLRPCRequestHandler.handle_request (request_text=None)

     处理一个 XML-RPC 请求。 如果给出了 `request_text'，它应当是 HTTP 服
     务器所提供的 POST 数据，否则将使用 stdin 的内容。

示例:

     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()


File: python.info,  Node: XMLRPC 服务器文档,  Next: DocXMLRPCServer 对象,  Prev: CGIXMLRPCRequestHandler,  Up: xmlrpc server --- 基本 XML-RPC 服务器

5.21.27.4 XMLRPC 服务器文档
...........................

这些类扩展了上面的类以发布响应 HTTP GET 请求的 HTML 文档。 服务器可以是
独立的，使用 *note DocXMLRPCServer: 10bc.，或是嵌入某个 CGI 环境中，使用
*note DocCGIXMLRPCRequestHandler: 3036.。

 -- 類別: xmlrpc.server.DocXMLRPCServer (addr,
          requestHandler=DocXMLRPCRequestHandler, logRequests=True,
          allow_none=False, encoding=None, bind_and_activate=True,
          use_builtin_types=True)

     创建一个新的服务器实例。 所有形参的含义与 *note SimpleXMLRPCServer:
     3024. 的相同；`requestHandler' 默认为 *note
     DocXMLRPCRequestHandler: 3037.。

     3.3 版更變: 增加了 `use_builtin_types' 旗标。

 -- 類別: xmlrpc.server.DocCGIXMLRPCRequestHandler

     创建一个新的实例来处理 CGI 环境中的 XML-RPC 请求。

 -- 類別: xmlrpc.server.DocXMLRPCRequestHandler

     创建一个新的请求处理句柄实例。 该请求处理句柄支持 XML-RPC POST 请求
     、文档 GET 请求并会修改日志记录操作以便使用传递给 *note
     DocXMLRPCServer: 10bc. 构造器形参的 `logRequests' 形参。


File: python.info,  Node: DocXMLRPCServer 对象,  Next: DocCGIXMLRPCRequestHandler,  Prev: XMLRPC 服务器文档,  Up: xmlrpc server --- 基本 XML-RPC 服务器

5.21.27.5 DocXMLRPCServer 对象
..............................

*note DocXMLRPCServer: 10bc. 类派生自 *note SimpleXMLRPCServer: 3024. 并
提供了一种创建自动记录文档的、独立的 XML-RPC 服务器的方式。 HTTP POST 请
求将作为 XML-RPC 方法调用来处理。 HTTP GET 请求将通过生成 pydoc 风格的
HTML 文档来处理。 这将允许服务器自己提供基于 Web 的文档。

 -- 成員函式: DocXMLRPCServer.set_server_title (server_title)

     设置所生成 HTML 文档要使用的标题。 此标题将在 HTML "title" 元素中使
     用。

 -- 成員函式: DocXMLRPCServer.set_server_name (server_name)

     设置所生成 HTML 文档要使用的名称。 此名称将出现在所生成文档顶部的
     "h1" 元素中。

 -- 成員函式: DocXMLRPCServer.set_server_documentation
          (server_documentation)

     设置所生成Set the description used in the generated HTML 文档要使用
     的描述。 此描述将显示为文档中的一个段落，位于服务器名称之下。


File: python.info,  Node: DocCGIXMLRPCRequestHandler,  Prev: DocXMLRPCServer 对象,  Up: xmlrpc server --- 基本 XML-RPC 服务器

5.21.27.6 DocCGIXMLRPCRequestHandler
....................................

*note DocCGIXMLRPCRequestHandler: 3036. 类派生自 *note
CGIXMLRPCRequestHandler: 3025. 并提供了一种创建自动记录文档的 XML-RPC
CGI 脚本的方式。 HTTP POST 请求将作为 XML-RPC 方法调用来处理。 HTTP GET
请求将通过生成 pydoc 风格的 HTML 文档来处理。 这将允许服务器自己提供基于
Web 的文档。

 -- 成員函式: DocCGIXMLRPCRequestHandler.set_server_title (server_title)

     设置所生成 HTML 文档要使用的标题。 此标题将在 HTML "title" 元素中使
     用。

 -- 成員函式: DocCGIXMLRPCRequestHandler.set_server_name (server_name)

     设置所生成 HTML 文档要使用的名称。 此名称将出现在所生成文档顶部的
     "h1" 元素中。

 -- 成員函式: DocCGIXMLRPCRequestHandler.set_server_documentation
          (server_documentation)

     设置所生成Set the description used in the generated HTML 文档要使用
     的描述。 此描述将显示为文档中的一个段落，位于服务器名称之下。


File: python.info,  Node: ipaddress --- IPv4/IPv6 操作库,  Prev: xmlrpc server --- 基本 XML-RPC 服务器,  Up: 互联网协议和支持

5.21.28 ‘ipaddress’ — IPv4/IPv6 操作库
--------------------------------------

`源代码：' Lib/ipaddress.py(1)

__________________________________________________________________

*note ipaddress: a2. 提供了创建、处理和操作 IPv4 和 IPv6 地址和网络的功
能。

该模块中的函数和类可以直接处理与IP地址相关的各种任务，包括检查两个主机是
否在同一个子网中，遍历某个子网中的所有主机，检查一个字符串是否是一个有效
的IP地址或网络定义等等。

这是完整的模块 API 参考—若要查看概述，请见 *note ipaddress模組介紹:
3043.

3.3 版新加入.

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/ipaddress.py


File: python.info,  Node: 方便的工厂函数,  Next: IP 地址,  Up: ipaddress --- IPv4/IPv6 操作库

5.21.28.1 方便的工厂函数
........................

*note ipaddress: a2. 模块提供来工厂函数来方便地创建 IP 地址，网络和接口
：

 -- 函式: ipaddress.ip_address (address)

     Return an *note IPv4Address: 3046. or *note IPv6Address: 1bb.
     object depending on the IP address passed as argument.  Either IPv4
     or IPv6 addresses may be supplied; integers less than ‘2**32’ will
     be considered to be IPv4 by default.  A *note ValueError: 16d. is
     raised if `address' does not represent a valid IPv4 or IPv6
     address.

          >>> ipaddress.ip_address('192.168.0.1')
          IPv4Address('192.168.0.1')
          >>> ipaddress.ip_address('2001:db8::')
          IPv6Address('2001:db8::')

 -- 函式: ipaddress.ip_network (address, strict=True)

     Return an *note IPv4Network: 4a6. or *note IPv6Network: 4a5. object
     depending on the IP address passed as argument.  `address' is a
     string or integer representing the IP network.  Either IPv4 or IPv6
     networks may be supplied; integers less than ‘2**32’ will be
     considered to be IPv4 by default.  `strict' is passed to *note
     IPv4Network: 4a6. or *note IPv6Network: 4a5. constructor.  A *note
     ValueError: 16d. is raised if `address' does not represent a valid
     IPv4 or IPv6 address, or if the network has host bits set.

          >>> ipaddress.ip_network('192.168.0.0/28')
          IPv4Network('192.168.0.0/28')

 -- 函式: ipaddress.ip_interface (address)

     Return an *note IPv4Interface: 3049. or *note IPv6Interface: 304a.
     object depending on the IP address passed as argument.  `address'
     is a string or integer representing the IP address.  Either IPv4 or
     IPv6 addresses may be supplied; integers less than ‘2**32’ will be
     considered to be IPv4 by default.  A *note ValueError: 16d. is
     raised if `address' does not represent a valid IPv4 or IPv6
     address.

这些方便的函数的一个缺点是需要同时处理IPv4和IPv6格式，这意味着提供的错误
信息并不精准，因为函数不知道是打算采用IPv4还是IPv6格式。更详细的错误报告
可以通过直接调用相应版本的类构造函数来获得。


File: python.info,  Node: IP 地址,  Next: IP网络的定义,  Prev: 方便的工厂函数,  Up: ipaddress --- IPv4/IPv6 操作库

5.21.28.2 IP 地址
.................

* Menu:

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


File: python.info,  Node: 地址对象,  Next: 转换字符串和整数,  Up: IP 地址

5.21.28.3 地址对象
..................

*note IPv4Address: 3046. 和 *note IPv6Address: 1bb. 对象有很多共同的属性
。一些只对IPv6 地址有意义的属性也在 *note IPv4Address: 3046. 对象实现，
以便更容易编写正确处理两种 IP 版本的代码。地址对象是可哈希的 *note
hashable: 276.，所以它们可以作为字典中的键来使用。

 -- 類別: ipaddress.IPv4Address (address)

     构造一个 IPv4 地址。 如果 `address' 不是一个有效的 IPv4 地址，会抛
     出 *note AddressValueError: 304d. 。

     以下是有效的 IPv4 地址：

       1. 以十进制小数点表示的字符串，由四个十进制整数组成，范围为
          0–255，用点隔开(例如 ‘192.168.0.1’ )。每个整数代表地址中的八位
          （一个字节）。不允许使用前导零，以免与八进制表示产生歧义。

       2. 一个32位可容纳的整数。

       3. 一个长度为 4 的封装在 *note bytes: 172. 对象中的整数(高位优先
          )。

          >>> 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')

     3.8 版更變: 前导零可被接受，即使是在可能与八进制表示混淆的情况下也
     会被接受。

     3.10 版更變: 前导零不再被接受，并且会被视作错误。IPv4地址字符串现在
     严格按照glibc的 *note inet_pton(): 237. 函数进行解析。

     3.9.5 版更變: 上述变更也在自3.9.5版本起的Python 3.9当中被包含。

     3.8.12 版更變: The above change was also included in Python 3.8
     starting with version 3.8.12.

      -- 屬性: version

          合适的版本号：IPv4为 ‘4’ ，IPv6为 ‘6’ 。

      -- 屬性: max_prefixlen

          在该版本的地址表示中，比特数的总数：IPv4为 ‘32’ ；IPv6为 ‘128’
          。

          前缀定义了地址中的前导位数量，通过比较来确定一个地址是否是网络
          的一部分。

      -- 屬性: compressed

      -- 屬性: exploded

          以点符号分割十进制表示的字符串。表示中不包括前导零。

          由于IPv4没有为八位数设为零的地址定义速记符号，这两个属性始终与
          IPv4地址的‘‘str(addr)‘‘相同。暴露这些属性使得编写能够处理
          IPv4和IPv6地址的显示代码变得更加容易。

      -- 屬性: packed

          这个地址的二进制表示——一个适当长度的 *note bytes: 172. 对象（
          最高的八位在最前）。 对于 IPv4 来说是 4 字节，对于 IPv6 来说是
          16 字节。

      -- 屬性: reverse_pointer

          IP地址的反向DNS PTR记录的名称，例如:

               >>> 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'

          这是可用于执行PTR查询的名称，而不是已解析的主机名本身。

          3.5 版新加入.

      -- 屬性: is_multicast

          如果该地址被保留用作多播用途，返回 ‘True’ 。关于多播地址，请参
          见 RFC 3171(1) （IPv4）和 RFC 2373(2) （IPv6）。

      -- 屬性: is_private

          如果该地址被分配至私有网络，返回 ‘True’ 。关于公共网络，请参见
          iana-ipv4-special-registry(3) （针对IPv4）和
          iana-ipv6-special-registry(4) （针对IPv6）。

      -- 屬性: is_global

          如果该地址被分配至公共网络，返回 ‘True’ 。关于公共网络，请参见
          iana-ipv4-special-registry(5) （针对IPv4）和
          iana-ipv6-special-registry(6) （针对IPv6）。

          3.4 版新加入.

      -- 屬性: is_unspecified

          当地址未指定时为‘‘True‘‘ 。 参见 RFC 5735(7) (IPv4) 或 RFC
          2373(8) (IPv6).

      -- 屬性: is_reserved

          如果该地址属于互联网工程任务组（IETF）所规定的其他保留地址，返
          回 ‘True’ 。

      -- 屬性: is_loopback

          如果该地址为一个回环地址，返回 ‘True’ 。关于回环地址，请见 RFC
          3330(9) （IPv4）和 RFC 2373(10) （IPv6）。

      -- 屬性: is_link_local

          如果该地址被保留用于本地链接则为 ‘True’。 参见 RFC 3927(11)。

 -- 成員函式: IPv4Address.__format__ (fmt)

     返回一个IP地址的字符串表示，由一个明确的格式字符串控制。`fmt' 可以
     是以下之一: ‘'s'’，默认选项，相当于 *note str(): 205.，‘'b'’ 用于零
     填充的二进制字符串，‘'X'’ 或者 ‘'x'’ 用于大写或小写的十六进制表示，
     或者 ‘'n'’ 相当于 ‘'b'’ 用于 IPv4 地址和 ‘'x'’ 用于 IPv6 地址。 对
     于二进制和十六进制表示法，可以使用形式指定器 ‘'#'’ 和分组选项
     ‘'_'’。 ‘__format__’ 被 ‘format’、 ‘str.format’ 和 f 字符串使用。

          >>> 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'

     3.9 版新加入.

 -- 類別: ipaddress.IPv6Address (address)

     构造一个 IPv6 地址。 如果 `address' 不是一个有效的 IPv6 地址，会抛
     出 *note AddressValueError: 304d. 。

     以下是有效的 IPv6 地址：

       1. 一个由八组四个16进制数字组成的字符串, 每组展示为16位. 以冒号分
          隔. 这可以描述为 `分解' (普通书写).  此字符可以被 `压缩' (速记
          书写) .  详见:RFC:‘4291’ .  例如,
          ‘"0000:0000:0000:0000:0000:0abc:0007:0def"’ 可以被精简为
          ‘"::abc:7:def"’.

          可选择的是，该字符串也可以有一个范围区ID，用后缀
          ‘‘%scope_id‘‘表示。如果存在，范围ID必须是非空的，并且不能包含
          ‘‘%‘‘。详见:RFC:‘4007’。例如，‘fe80::1234%1``可以识别节点第一
          条链路上的地址``fe80::1234’

       2. 适合 128 位的整数.

       3. 一个打包在长度为 16 字节的大端序 *note bytes: 172. 对象中的整
          数。

          >>> ipaddress.IPv6Address('2001:db8::1000')
          IPv6Address('2001:db8::1000')
          >>> ipaddress.IPv6Address('ff02::5678%1')
          IPv6Address('ff02::5678%1')

      -- 屬性: compressed

     地址表示的简短形式，省略了组中的前导零，完全由零组成的最长的组序列
     被折叠成一个空组。

     这也是‘‘str(addr)‘‘对IPv6地址返回的值。

      -- 屬性: exploded

     地址的长形式表示，包括所有前导零和完全由零组成的组。

     关于以下属性和方法，请参见 *note IPv4Address: 3046. 类的相应文档。

      -- 屬性: packed

      -- 屬性: reverse_pointer

      -- 屬性: version

      -- 屬性: max_prefixlen

      -- 屬性: is_multicast

      -- 屬性: is_private

      -- 屬性: is_global

      -- 屬性: is_unspecified

      -- 屬性: is_reserved

      -- 屬性: is_loopback

      -- 屬性: is_link_local

          3.4 版新加入: is_global

      -- 屬性: is_site_local

          如果地址被保留用于本地站点则为 ‘True’。 请注意本地站点地址空间
          已被 RFC 3879(12) 弃用。 请使用 *note is_private: 3055. 来检测
          此地址是否位于 RFC 4193(13) 所定义的本地唯一地址空间中。

      -- 屬性: ipv4_mapped

          映射IPv4的地址 (起始为 ‘::FFFF/96’), 这一属性记录为嵌入IPv4地
          址. 其他的任何地址, 这一属性为 ‘None’.

      -- 屬性: scope_id

          对于:RFC:‘4007‘定义的作用域地址，此属性以字符串的形式确定地址
          所属的作用域的特定区域。当没有指定作用域时，该属性将是
          ‘‘None‘’。

      -- 屬性: sixtofour

          对于看起来是6to4的地址（以‘‘2002::/16‘‘开头），如 RFC 3056(14)
          所定义的，此属性将返回嵌入的IPv4地址。 对于任何其他地址，该属
          性将是‘‘None‘‘。

      -- 屬性: teredo

          对于看起来是:RFC:‘4380‘定义的Teredo地址（以‘‘2001::/32‘‘开头）
          的地址，此属性将返回嵌入式IP地址对‘‘(server, client)‘’。 对于
          任何其他地址，该属性将是‘‘None‘‘。

 -- 成員函式: IPv6Address.__format__ (fmt)

     请参考 *note IPv4Address: 3046. 中对应的方法文档。

     3.9 版新加入.

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc3171.html

   (2) https://tools.ietf.org/html/rfc2373.html

   (3) 
https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml

   (4) 
https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml

   (5) 
https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml

   (6) 
https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml

   (7) https://tools.ietf.org/html/rfc5735.html

   (8) https://tools.ietf.org/html/rfc2373.html

   (9) https://tools.ietf.org/html/rfc3330.html

   (10) https://tools.ietf.org/html/rfc2373.html

   (11) https://tools.ietf.org/html/rfc3927.html

   (12) https://tools.ietf.org/html/rfc3879.html

   (13) https://tools.ietf.org/html/rfc4193.html

   (14) https://tools.ietf.org/html/rfc3056.html


File: python.info,  Node: 转换字符串和整数,  Next: 运算符<3>,  Prev: 地址对象,  Up: IP 地址

5.21.28.4 转换字符串和整数
..........................

与网络模块互操作像套接字模块, 地址必须转换为字符串或整数. 这是使用 *note
str(): 205. 和 *note int(): 204. 内置函数:

     >>> 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

请注意，IPv6范围内的地址被转换为没有范围区域ID的整数。


File: python.info,  Node: 运算符<3>,  Prev: 转换字符串和整数,  Up: IP 地址

5.21.28.5 运算符
................

地址对象支持一些运算符。 除非另有说明，运算符只能在兼容对象之间应用（即
IPv4与IPv4，IPv6与IPv6）。

* Menu:

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


File: python.info,  Node: 比较运算符,  Next: 算术运算符,  Up: 运算符<3>

5.21.28.6 比较运算符
....................

地址对象可以用通常的一组比较运算符进行比较。具有不同范围区域ID的相同
IPv6地址是不平等的。一些例子:

     >>> 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


File: python.info,  Node: 算术运算符,  Prev: 比较运算符,  Up: 运算符<3>

5.21.28.7 算术运算符
....................

整数可以被添加到地址对象或从地址对象中减去。 一些例子:

     >>> 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


File: python.info,  Node: IP网络的定义,  Next: 接口对象,  Prev: IP 地址,  Up: ipaddress --- IPv4/IPv6 操作库

5.21.28.8 IP网络的定义
......................

*note IPv4Network: 4a6. 和 *note IPv6Network: 4a5. 对象提供了一个定义和
检查IP网络定义的机制。一个网络定义由一个 `掩码' 和一个 `网络地址' 组成，
因此定义了一个IP地址的范围，当用掩码屏蔽（二进制AND）时，等于网络地址。
例如，一个带有掩码‘‘255.255.255.0‘‘和网络地址‘‘192.168.1.0‘‘的网络定义由
包括‘‘192.168.1.0‘‘到‘‘192.168.1.255‘‘的IP地址组成。

* Menu:

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


File: python.info,  Node: 前缀、网络掩码和主机掩码,  Next: 网络对象,  Up: IP网络的定义

5.21.28.9 前缀、网络掩码和主机掩码
..................................

有几种相等的方法来指定IP网络掩码。 `前缀' ‘/<nbits>``是一个符号，表示在
网络掩码中设置了多少个高阶位。 一个 *网络掩码* 是一个设置了一定数量高阶
位的IP地址。 因此，前缀’/24‘‘等同于IPv4中的网络掩码‘‘255.255.255.0‘‘或
IPv6中的网络掩码‘‘ffff:ff00::‘。 此外，*主机掩码* 是 *网络掩码* 的逻辑取
反，有时被用来表示网络掩码（例如在Cisco访问控制列表中）。 在IPv4中，相当
于主机掩码``0.0.0.255``的是’/24‘‘ 。


File: python.info,  Node: 网络对象,  Next: 运算符<4>,  Prev: 前缀、网络掩码和主机掩码,  Up: IP网络的定义

5.21.28.10 网络对象
...................

所有由地址对象实现的属性也由网络对象实现。 此外，网络对象还实现了额外的
属性。所有这些在 *note IPv4Network: 4a6. 和 *note IPv6Network: 4a5. 之间
是共同的，所以为了避免重复，它们只在 *note IPv4Network: 4a6. 中记录。网
络对象是 *note hashable: 276.，所以它们可以作为字典中的键使用。

 -- 類別: ipaddress.IPv4Network (address, strict=True)

     构建一个 IPv4 网络定义。 `address' 可以是以下之一：

       1. 一个由 IP 地址和可选掩码组成的字符串，用斜线 (‘/’) 分开。 IP 地
          址是网络地址，掩码可以是一个单一的数字，这意味着它是一个 `前缀
          '，或者是一个 IPv4 地址的字符串表示。 如果是后者，如果掩码以非
          零字段开始，则被解释为 `网络掩码'，如果以零字段开始，则被解释
          为 `主机掩码'，唯一的例外是全零的掩码被视为 `网络掩码'。 如果
          没有提供掩码，它就被认为是 ‘/32’。

          例如，以下的*地址*描述是等同的：‘192.168.1.0/24’，
          ‘192.168.1.0/255.255.255.0``和``192.168.1.0/0.0.0.255’

       2. 一个可转化为32位的整数。 这相当于一个单地址的网络，网络地址是
          *address*，掩码是‘‘/32‘‘。

       3. 一个整数被打包成一个长度为 4 的大端序 *note bytes: 172. 对象。
          其解释类似于一个整数 `address'。

       4. 一个地址描述和一个网络掩码的双元组，其中地址描述是一个字符串，
          一个 32 位的整数，一个 4 字节的打包整数，或一个现有的
          IPv4Address 对象；而网络掩码是一个代表前缀长度的整数 (例如
          ‘24’) 或一个代表前缀掩码的字符串 (例如 ‘255.255.255.0’)。

     如果 `address' 不是一个有效的 IPv4 地址则会引发 *note
     AddressValueError: 304d.。 如果掩码不是有效的 IPv4 地址则会引发
     *note NetmaskValueError: 3074.。

     如果 `strict' 是 ‘True’，并且在提供的地址中设置了主机位，那么 *note
     ValueError: 16d. 将被触发。 否则，主机位将被屏蔽掉，以确定适当的网
     络地址。

     除非另有说明，如果参数的 IP 版本与 ‘self’ 不兼容，所有接受其他网络
     /地址对象的网络方法都将引发 *note TypeError: 1fe.。

     3.5 版更變: 为*address*构造函数参数添加了双元组形式。

      -- 屬性: version

      -- 屬性: max_prefixlen

          请参考 *note IPv4Address: 3046. 中的相应属性文档。

      -- 屬性: is_multicast

      -- 屬性: is_private

      -- 屬性: is_unspecified

      -- 屬性: is_reserved

      -- 屬性: is_loopback

      -- 屬性: is_link_local

          如果这些属性对网络地址和广播地址都是真实的，那么它们对整个网络
          来说就是真实的。

      -- 屬性: network_address

          网络的网络地址。网络地址和前缀长度一起唯一地定义了一个网络。

      -- 屬性: broadcast_address

          网络的广播地址。发送到广播地址的数据包应该被网络上的每台主机所
          接收。

      -- 屬性: hostmask

          主机掩码，作为一个 *note IPv4Address: 3046. 对象。

      -- 屬性: netmask

          网络掩码，作为一个 *note IPv4Address: 3046. 对象。

      -- 屬性: with_prefixlen

      -- 屬性: compressed

      -- 屬性: exploded

          网络的字符串表示，其中掩码为前缀符号。

          ‘with_prefixlen’ 和 ‘compressed’ 总是与 ‘str(network)’ 相同，
          ‘exploded’ 使用分解形式的网络地址。

      -- 屬性: with_netmask

          网络的字符串表示，掩码用net mask符号表示。

      -- 屬性: with_hostmask

          网络的字符串表示，其中的掩码为主机掩码符号。

      -- 屬性: num_addresses

          网络中的地址总数。

      -- 屬性: prefixlen

          网络前缀的长度，以比特为单位。

      -- 成員函式: hosts ()

          返回一个网络中可用主机的迭代器。 可用的主机是属于该网络的所有
          IP地址，除了网络地址本身和网络广播地址。 对于掩码长度为31的网
          络，网络地址和网络广播地址也包括在结果中。掩码为32的网络将返回
          一个包含单一主机地址的列表。

               >>> 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')]

      -- 成員函式: overlaps (other)

          如果这个网络部分或全部包含在*other*中，或者*other*全部包含在这
          个网络中，则为‘‘True‘‘。

      -- 成員函式: address_exclude (network)

          计算从这个网络中移除给定的 `network' 后产生的网络定义。 返回一
          个网络对象的迭代器。 如果 `network' 不完全包含在这个网络中则会
          引发 *note ValueError: 16d.。

               >>> 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')]

      -- 成員函式: subnets (prefixlen_diff=1, new_prefix=None)

          根据参数值，加入的子网构成当前的网络定义。 `prefixlen_diff' 是
          我们的前缀长度应该增加的数量。 `new_prefix' 是所需的子网的新前
          缀；它必须大于我们的前缀。 必须设置 `prefixlen_diff' 和
          `new_prefix' 中的一个，且只有一个。 返回一个网络对象的迭代器。

               >>> 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')]

      -- 成員函式: supernet (prefixlen_diff=1, new_prefix=None)

          包含这个网络定义的超级网，取决于参数值。 `prefixlen_diff' 是我
          们的前缀长度应该减少的数量。 `new_prefix' 是超级网的新前缀；它
          必须比我们的前缀小。 必须设置 `prefixlen_diff' 和 `new_prefix'
          中的一个，而且只有一个。 返回一个单一的网络对象。

               >>> 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')

      -- 成員函式: subnet_of (other)

          如果这个网络是*other*的子网，则返回‘‘True‘‘。

               >>> a = ip_network('192.168.1.0/24')
               >>> b = ip_network('192.168.1.128/30')
               >>> b.subnet_of(a)
               True

          3.7 版新加入.

      -- 成員函式: supernet_of (other)

          如果这个网络是*other*的超网，则返回‘‘True‘‘。

               >>> a = ip_network('192.168.1.0/24')
               >>> b = ip_network('192.168.1.128/30')
               >>> a.supernet_of(b)
               True

          3.7 版新加入.

      -- 成員函式: compare_networks (other)

          将这个网络与*ohter*网络进行比较。 在这个比较中，只考虑网络地址
          ；不考虑主机位。 返回是‘‘-1‘‘ 、 ‘0``或``1’。

               >>> 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

          3.7 版後已棄用: 它使用与"<"、"=="和">"相同的排序和比较算法。

 -- 類別: ipaddress.IPv6Network (address, strict=True)

     构建一个 IPv6 网络定义。 `address' 可以是以下之一：

       1. 一个由IP地址和可选前缀长度组成的字符串，用斜线（‘/’）分开。
          IP地址是网络地址，前缀长度必须是一个数字，即*prefix*。 如果没
          有提供前缀长度，就认为是‘‘/128‘‘。

          Note that currently expanded netmasks are not supported.  That
          means ‘2001:db00::0/24’ is a valid argument while
          ‘2001:db00::0/ffff:ff00::’ is not.

       2. 一个适合128位的整数。 这相当于一个单地址网络，网络地址是
          *address*，掩码是‘‘/128‘‘。

       3. 一个整数被打包成一个长度为 16 的大端序 *note bytes: 172. 对象
          。 其解释类似于一个整数的 `address'。

       4. 一个地址描述和一个网络掩码的双元组，其中地址描述是一个字符串，
          一个 128 位的整数，一个 16 字节的打包整数，或者一个现有的
          IPv6Address 对象；而网络掩码是一个代表前缀长度的整数。

     如果 `address' 不是一个有效的 IPv6 地址则会引发 *note
     AddressValueError: 304d.。 如果掩码对 IPv6 地址无效则会引发 *note
     NetmaskValueError: 3074.。

     如果 `strict' 是 ‘True’，并且在提供的地址中设置了主机位，那么 *note
     ValueError: 16d. 将被触发。 否则，主机位将被屏蔽掉，以确定适当的网
     络地址。

     3.5 版更變: 为*address*构造函数参数添加了双元组形式。

      -- 屬性: version

      -- 屬性: max_prefixlen

      -- 屬性: is_multicast

      -- 屬性: is_private

      -- 屬性: is_unspecified

      -- 屬性: is_reserved

      -- 屬性: is_loopback

      -- 屬性: is_link_local

      -- 屬性: network_address

      -- 屬性: broadcast_address

      -- 屬性: hostmask

      -- 屬性: netmask

      -- 屬性: with_prefixlen

      -- 屬性: compressed

      -- 屬性: exploded

      -- 屬性: with_netmask

      -- 屬性: with_hostmask

      -- 屬性: num_addresses

      -- 屬性: prefixlen

      -- 成員函式: hosts ()

          返回一个网络中可用主机的迭代器。 可用的主机是属于该网络的所有
          IP地址，除了Subnet-Router任播的地址。 对于掩码长度为127的网络
          ，子网-路由器任播地址也包括在结果中。掩码为128的网络将返回一个
          包含单一主机地址的列表。

      -- 成員函式: overlaps (other)

      -- 成員函式: address_exclude (network)

      -- 成員函式: subnets (prefixlen_diff=1, new_prefix=None)

      -- 成員函式: supernet (prefixlen_diff=1, new_prefix=None)

      -- 成員函式: subnet_of (other)

      -- 成員函式: supernet_of (other)

      -- 成員函式: compare_networks (other)

          请参考 *note IPv4Network: 4a6. 中的相应属性文档。

      -- 屬性: is_site_local

          如果这些属性对网络地址和广播地址都是真的，那么对整个网络来说就
          是真的。


File: python.info,  Node: 运算符<4>,  Prev: 网络对象,  Up: IP网络的定义

5.21.28.11 运算符
.................

网络对象支持一些操作符。 除非另有说明，操作符只能在兼容的对象之间应用（
例如，IPv4与IPv4，IPv6与IPv6）。

* Menu:

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


File: python.info,  Node: 逻辑操作符,  Next: 迭代<2>,  Up: 运算符<4>

5.21.28.12 逻辑操作符
.....................

网络对象可以用常规的逻辑运算符集进行比较。网络对象首先按网络地址排序，然
后按网络掩码排序。


File: python.info,  Node: 迭代<2>,  Next: 作为地址容器的网络,  Prev: 逻辑操作符,  Up: 运算符<4>

5.21.28.13 迭代
...............

网络对象可以被迭代，以列出属于该网络的所有地址。 对于迭代，`所有' 主机都
会被返回，包括不可用的主机（对于可用的主机，使用 *note hosts(): 3088. 方
法）。 一个例子:

     >>> 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')


File: python.info,  Node: 作为地址容器的网络,  Prev: 迭代<2>,  Up: 运算符<4>

5.21.28.14 作为地址容器的网络
.............................

网络对象可以作为地址的容器。 一些例子:

     >>> 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


File: python.info,  Node: 接口对象,  Next: 其他模块级别函数,  Prev: IP网络的定义,  Up: ipaddress --- IPv4/IPv6 操作库

5.21.28.15 接口对象
...................

接口对象是 *note hashable: 276. 的，所以它们可以作为字典中的键使用。

 -- 類別: ipaddress.IPv4Interface (address)

     构建一个 IPv4 接口。 `address' 的含义与 *note IPv4Network: 4a6. 构
     造器中的一样，不同之处在于任意主机地址总是会被接受。

     *note IPv4Interface: 3049. 是 *note IPv4Address: 3046. 的一个子类，
     所以它继承了该类的所有属性。 此外，还有以下属性可用：

      -- 屬性: ip

          地址（*note IPv4Address: 3046.）没有网络信息。

               >>> interface = IPv4Interface('192.0.2.5/24')
               >>> interface.ip
               IPv4Address('192.0.2.5')

      -- 屬性: network

          该接口所属的网络（*note IPv4Network: 4a6.）。

               >>> interface = IPv4Interface('192.0.2.5/24')
               >>> interface.network
               IPv4Network('192.0.2.0/24')

      -- 屬性: with_prefixlen

          用前缀符号表示的接口与掩码的字符串。

               >>> interface = IPv4Interface('192.0.2.5/24')
               >>> interface.with_prefixlen
               '192.0.2.5/24'

      -- 屬性: with_netmask

          以网络为掩码的接口的字符串表示。

               >>> interface = IPv4Interface('192.0.2.5/24')
               >>> interface.with_netmask
               '192.0.2.5/255.255.255.0'

      -- 屬性: with_hostmask

          以主机为掩码的接口的字符串表示。

               >>> interface = IPv4Interface('192.0.2.5/24')
               >>> interface.with_hostmask
               '192.0.2.5/0.0.0.255'

 -- 類別: ipaddress.IPv6Interface (address)

     构建一个 IPv6 接口。 `address' 的含义与 *note IPv6Network: 4a5. 构
     造器中的一样，不同之处在于任意主机地址总是会被接受。

     *note IPv6Interface: 304a. 是 *note IPv6Address: 1bb. 的一个子类，
     所以它继承了该类的所有属性。 此外，还有以下属性可用：

      -- 屬性: ip

      -- 屬性: network

      -- 屬性: with_prefixlen

      -- 屬性: with_netmask

      -- 屬性: with_hostmask

          请参考 *note IPv4Interface: 3049. 中的相应属性文档。

* Menu:

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


File: python.info,  Node: 运算符<5>,  Up: 接口对象

5.21.28.16 运算符
.................

接口对象支持一些运算符。 除非另有说明，运算符只能在兼容的对象之间应用（
即IPv4与IPv4，IPv6与IPv6）。

* Menu:

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


File: python.info,  Node: 逻辑操作符<2>,  Up: 运算符<5>

5.21.28.17 逻辑操作符
.....................

接口对象可以用通常的逻辑运算符集进行比较。

对于相等比较（‘==``和’!=‘‘），IP地址和网络都必须是相同的对象才会相等。 一
个接口不会与任何地址或网络对象相等。

对于排序 (‘<’、‘>’ 等)，规则是不同的。 具有相同 IP 版本的接口和地址对象
可以被比较，而地址对象总是在接口对象之前排序。 两个接口对象首先通过它们
的网络进行比较，如果它们是相同的，则通过它们的 IP 地址进行比较。


File: python.info,  Node: 其他模块级别函数,  Next: 自定义异常,  Prev: 接口对象,  Up: ipaddress --- IPv4/IPv6 操作库

5.21.28.18 其他模块级别函数
...........................

该模块还提供以下模块级函数：

 -- 函式: ipaddress.v4_int_to_packed (address)

     以网络（大端序）顺序将一个地址表示为 4 个打包的字节。`address' 是一
     个 IPv4 IP 地址的整数表示。 如果整数是负数或太大而不满足 IPv4 IP 地
     址要求，会触发一个 *note ValueError: 16d.。

          >>> ipaddress.ip_address(3221225985)
          IPv4Address('192.0.2.1')
          >>> ipaddress.v4_int_to_packed(3221225985)
          b'\xc0\x00\x02\x01'

 -- 函式: ipaddress.v6_int_to_packed (address)

     以网络（大端序）顺序将一个地址表示为 4 个打包的字节。`address' 是一
     个IPv6 IP地址的整数表示。 如果整数是负数或太大而不满足 IPv6 IP 地址
     要求，会触发一个 *note ValueError: 16d.。

 -- 函式: ipaddress.summarize_address_range (first, last)

     给出第一个和最后一个 IP 地址，返回总结的网络范围的迭代器。 `first'
     是范围内的第一个 *note IPv4Address: 3046. 或 *note IPv6Address:
     1bb.，`last' 是范围内的最后一个 *note IPv4Address: 3046. 或 *note
     IPv6Address: 1bb.。 如果 `first' 或 `last' 不是IP地址或不是同一版本
     则会引发 *note TypeError: 1fe.。 如果 `last' 不大于 `first'，或者
     `first' 的地址版本不是 4 或 6 则会引发 *note ValueError: 16d.。

          >>> [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')]

 -- 函式: ipaddress.collapse_addresses (addresses)

     返回一个 *note IPv4Network: 4a6. 或 *note IPv6Network: 4a5. 对象的
     迭代器。 `addresses' 是一个 *note IPv4Network: 4a6. 或 *note
     IPv6Network: 4a5. 对象的迭代器。 如果 `addresses' 包含混合版本的对
     象则会引发 *note TypeError: 1fe.。

          >>> [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')]

 -- 函式: ipaddress.get_mixed_type_key (obj)

     返回一个适合在网络和地址之间进行排序的键。 地址和网络对象在默认情况
     下是不可排序的；它们在本质上是不同的，所以表达式:

          IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24')

     是没有意义的。 然而，有些时候，你可能希望让 *note ipaddress: a2. 对
     这些进行排序。 如果你需要这样做，你可以使用这个函数作为 *note
     sorted(): 546. 的 `key' 参数。

     `obj' 是一个网络或地址对象。


File: python.info,  Node: 自定义异常,  Prev: 其他模块级别函数,  Up: ipaddress --- IPv4/IPv6 操作库

5.21.28.19 自定义异常
.....................

为了支持来自类构造函数的更具体的错误报告，模块定义了以下异常：

 -- 例外: ipaddress.AddressValueError (ValueError)

     与地址有关的任何数值错误。

 -- 例外: ipaddress.NetmaskValueError (ValueError)

     与网络掩码有关的任何数值错误


File: python.info,  Node: 多媒体服务,  Next: 國際化,  Prev: 互联网协议和支持,  Up: Python 標準函式庫 Standard Library

5.22 多媒体服务
===============

本章描述的模块实现了主要用于多媒体应用的各种算法或接口。 它们可在安装时
自行决定。 这是一个概述：

* Menu:

* audioop: audioop --- 处理原始音频数据. 处理原始音频数据
* aifc: aifc --- 读写 AIFF 和 AIFC 文件. 读写 AIFF 和 AIFC 文件
* sunau: sunau --- 读写 Sun AU 文件. 读写 Sun AU 文件
* wave: wave --- 读写WAV格式文件. 读写WAV格式文件
* chunk: chunk --- 读取 IFF 分块数据. 读取 IFF 分块数据
* colorsys: colorsys --- 颜色系统间的转换. 颜色系统间的转换
* imghdr: imghdr --- 推测图像类型. 推测图像类型
* sndhdr: sndhdr --- 推测声音文件的类型. 推测声音文件的类型
* ossaudiodev: ossaudiodev --- 访问兼容OSS的音频设备. 访问兼容OSS的音频设备


File: python.info,  Node: audioop --- 处理原始音频数据,  Next: aifc --- 读写 AIFF 和 AIFC 文件,  Up: 多媒体服务

5.22.1 ‘audioop’ — 处理原始音频数据
-----------------------------------

__________________________________________________________________

*note audioop: c. 模块包含针对声音片段的一些有用操作。它操作的声音片段由
8、16、24 或 32 位宽的有符号整型采样值组成，存储在 *note 类字节串对象:
6df. 中。除非特别说明，否则所有标量项目均为整数。

3.4 版更變: 增加了对 24 位采样的支持。现在，所有函数都接受任何 *note
类字节串对象: 6df.。而传入字符串会立即导致错误。

本模块提供对 a-LAW、u-LAW 和 Intel/DVI ADPCM 编码的支持。

部分更复杂的操作仅接受 16 位采样，而其他操作始终需要采样大小（以字节为单
位）作为该操作的参数。

此模块定义了下列变量和函数：

 -- 例外: audioop.error

     所有错误都会抛出此异常，比如采样值的字节数未知等等。

 -- 函式: audioop.add (fragment1, fragment2, width)

     两个采样作为参数传入，返回一个片段，该片段是两个采样的和。`width' 是
     采样位宽（以字节为单位），可以取 ‘1’, ‘2’, ‘3’ 或 ‘4’。两个片段的长
     度应相同。如果发生溢出，较长的采样将被截断。

 -- 函式: audioop.adpcm2lin (adpcmfragment, width, state)

     将 Intel/DVI ADPCM 编码的片段解码为线性片段。关于 ADPCM 编码的详情
     请参阅 *note lin2adpcm(): 30c8. 的描述。返回一个元组 ‘(sample,
     newstate)’，其中 sample 的位宽由 `width' 指定。

 -- 函式: audioop.alaw2lin (fragment, width)

     将 a-LAW 编码的声音片段转换为线性编码声音片段。由于 a-LAW 编码采样
     值始终为 8 位，因此这里的 `width' 仅指输出片段的采样位宽。

 -- 函式: audioop.avg (fragment, width)

     返回片段中所有采样值的平均值。

 -- 函式: audioop.avgpp (fragment, width)

     返回片段中所有采样值的平均峰峰值。由于没有进行过滤，因此该例程的实
     用性尚存疑。

 -- 函式: audioop.bias (fragment, width, bias)

     返回一个片段，该片段由原始片段中的每个采样值加上偏差组成。在溢出时
     采样值会回卷 (wrap around)。

 -- 函式: audioop.byteswap (fragment, width)

     “按字节交换”片段中的所有采样值，返回修改后的片段。将大端序采样转换
     为小端序采样，反之亦然。

     3.4 版新加入.

 -- 函式: audioop.cross (fragment, width)

     将片段作为参数传入，返回其中过零点的数量。

 -- 函式: audioop.findfactor (fragment, reference)

     返回一个系数 `F' 使得 ‘rms(add(fragment, mul(reference, -F)))’ 最小
     ，即返回的系数乘以 `reference' 后与 `fragment' 最匹配。两个片段都应
     包含 2 字节宽的采样。

     本例程所需的时间与 ‘len(fragment)’ 成正比。

 -- 函式: audioop.findfit (fragment, reference)

     尽可能尝试让 `reference' 匹配 `fragment' 的一部分（`fragment' 应较
     长）。从概念上讲，完成这些靠从 `fragment' 中取出切片，使用 *note
     findfactor(): 30ce. 计算最佳匹配，并最小化结果。两个片段都应包含 2
     字节宽的采样。返回一个元组 ‘(offset, factor)’，其中 `offset' 是在
     `fragment' 中的偏移量（整数），表示从此处开始最佳匹配，而 `factor'
     是由 *note findfactor(): 30ce. 定义的因数（浮点数）。

 -- 函式: audioop.findmax (fragment, length)

     在 `fragment' 中搜索所有长度为 `length' 的采样切片（不是字节！）中
     ，能量最大的那一个切片，即返回 `i' 使得
     ‘rms(fragment[i*2:(i+length)*2])’ 最大。两个片段都应包含 2 字节宽的
     采样。

     本例程所需的时间与 ‘len(fragment)’ 成正比。

 -- 函式: audioop.getsample (fragment, width, index)

     返回片段中采样值索引 `index' 的值。

 -- 函式: audioop.lin2adpcm (fragment, width, state)

     将采样转换为 4 位 Intel/DVI ADPCM 编码。ADPCM 编码是一种自适应编码
     方案，其中每个 4 比特数字是一个采样值与下一个采样值之间的差除以（不
     定的）步长。IMA 已选择使用 Intel/DVI ADPCM 算法，因此它很可能成为标
     准。

     `state' 是一个表示编码器状态的元组。编码器返回一个元组 ‘(adpcmfrag,
     newstate)’，而 `newstate' 要在下一次调用 *note lin2adpcm(): 30c8. 时
     传入。在初始调用中，可以将 ‘None’ 作为 state 传递。`adpcmfrag' 是
     ADPCM 编码的片段，每个字节打包了 2 个 4 比特值。

 -- 函式: audioop.lin2alaw (fragment, width)

     将音频片段中的采样值转换为 a-LAW 编码，并将其作为字节对象返回。
     a-LAW 是一种音频编码格式，仅使用 8 位采样即可获得大约 13 位的动态范
     围。Sun 音频硬件等使用该编码。

 -- 函式: audioop.lin2lin (fragment, width, newwidth)

     将采样在 1、2、3 和 4 字节格式之间转换。

          備註: 在某些音频格式（如 .WAV 文件）中，16、24 和 32 位采样是
          有符号的，但 8 位采样是无符号的。因此，当将这些格式转换为 8 位
          宽采样时，还需使结果加上 128:

               new_frames = audioop.lin2lin(frames, old_width, 1)
               new_frames = audioop.bias(new_frames, 1, 128)

          反之，将 8 位宽的采样转换为 16、24 或 32 位时，必须采用相同的
          处理。

 -- 函式: audioop.lin2ulaw (fragment, width)

     将音频片段中的采样值转换为 u-LAW 编码，并将其作为字节对象返回。
     u-LAW 是一种音频编码格式，仅使用 8 位采样即可获得大约 14 位的动态范
     围。Sun 音频硬件等使用该编码。

 -- 函式: audioop.max (fragment, width)

     返回片段中所有采样值的最大 `绝对值'。

 -- 函式: audioop.maxpp (fragment, width)

     返回声音片段中的最大峰峰值。

 -- 函式: audioop.minmax (fragment, width)

     返回声音片段中所有采样值的最小值和最大值组成的元组。

 -- 函式: audioop.mul (fragment, width, factor)

     返回一个片段，该片段由原始片段中的每个采样值乘以浮点值 `factor' 组
     成。如果发生溢出，采样将被截断。

 -- 函式: audioop.ratecv (fragment, width, nchannels, inrate, outrate,
          state[, weightA[, weightB]])

     转换输入片段的帧速率。

     `state' 是一个表示转换器状态的元组。转换器返回一个元组
     ‘(newfragment, newstate)’，而 `newstate' 要在下一次调用 *note
     ratecv(): 30d9. 时传入。初始调用应传入 ‘None’ 作为 state。

     参数 `weightA' 和 `weightB' 是简单数字滤波器的参数，默认分别为 ‘1’
     和 ‘0’。

 -- 函式: audioop.reverse (fragment, width)

     将片段中的采样值反转，返回修改后的片段。

 -- 函式: audioop.rms (fragment, width)

     返回片段的均方根值，即 ‘sqrt(sum(S_i^2)/n)’。

     测量音频信号的能量。

 -- 函式: audioop.tomono (fragment, width, lfactor, rfactor)

     将立体声片段转换为单声道片段。左通道乘以 `lfactor'，右通道乘以
     `rfactor'，然后两个通道相加得到单声道信号。

 -- 函式: audioop.tostereo (fragment, width, lfactor, rfactor)

     由单声道片段生成立体声片段。立体声片段中的两对采样都是从单声道计算
     而来的，即左声道是乘以 `lfactor'，右声道是乘以 `rfactor'。

 -- 函式: audioop.ulaw2lin (fragment, width)

     将 u-LAW 编码的声音片段转换为线性编码声音片段。由于 u-LAW 编码采样
     值始终为 8 位，因此这里的 `width' 仅指输出片段的采样位宽。

请注意，诸如 *note mul(): 30d8. 或 *note max(): 30d5. 之类的操作在单声道
和立体声间没有区别，即所有采样都作相同处理。如果出现问题，应先将立体声片
段拆分为两个单声道片段，之后再重组。以下是如何进行该操作的示例:

     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)

如果使用 ADPCM 编码器构造网络数据包，并且希望协议是无状态的（即能够容忍
数据包丢失），则不仅需要传输数据，还应该传输状态。请注意，必须将*初始*状
态（传入 *note lin2adpcm(): 30c8. 的状态）发送给解码器，不能发送最终状态
（编码器返回的状态）。如果要使用 *note struct.Struct: 1950. 以二进制保存
状态，可以将第一个元素（预测值）用 16 位编码，将第二个元素（增量索引）用
8 位编码。

本 ADPCM 编码器从不与其他 ADPCM 编码器对立，仅针对自身。本开发者可能会误
读标准，这种情况下它们将无法与相应标准互操作。

乍看之下 ‘find*()’ 例程可能有些可笑。它们主要是用于回声消除，一种快速有
效的方法是选取输出样本中能量最高的片段，在输入样本中定位该片段，然后从输
入样本中减去整个输出样本:

     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)


File: python.info,  Node: aifc --- 读写 AIFF 和 AIFC 文件,  Next: sunau --- 读写 Sun AU 文件,  Prev: audioop --- 处理原始音频数据,  Up: 多媒体服务

5.22.2 ‘aifc’ — 读写 AIFF 和 AIFC 文件
--------------------------------------

`源代码：' Lib/aifc.py(1)

__________________________________________________________________

本模块提供读写 AIFF 和 AIFF-C 文件的支持。AIFF 是音频交换文件格式 (Audio
Interchange File Format)，一种用于在文件中存储数字音频采样的格式。AIFF-C
是该格式的更新版本，其中包括压缩音频数据的功能。

音频文件内有许多参数，用于描述音频数据。采样率或帧率是每秒对声音采样的次
数。通道数表示音频是单声道，双声道还是四声道。每个通道的每个帧包含一次采
样。采样大小是以字节表示的每次采样的大小。因此，一帧由 ‘nchannels *
samplesize’ （通道数*采样大小）字节组成，而一秒钟的音频包含 ‘nchannels *
samplesize * framerate’ （通道数*采样大小*帧率）字节。

例如，CD 质量的音频采样大小为 2 字节（16位），使用 2 个声道（立体声），
且帧速率为 44,100 帧/秒。这表示帧大小为 4 字节 (2*2)，一秒钟占用
2*2*44100 字节（176,400 字节）。

*note aifc: 4. 模块定义了以下函数：

 -- 函式: aifc.open (file, mode=None)

     打开一个 AIFF 或 AIFF-C 文件并返回一个对象实例，该实例具有下方描述
     的方法。参数 `file' 是文件名称字符串或 *note 文件对象: c14.。当打开
     文件用于读取时，`mode' 必须为 ‘'r'’ 或 ‘'rb'’，当打开文件用于写入时
     ，`mode' 必须为 ‘'w'’ 或 ‘'wb'’。如果该参数省略，则使用 ‘file.mode’
     的值（如果有），否则使用 ‘'rb'’。当文件用于写入时，文件对象应该支持
     seek 操作，除非提前获知写入的采样总数，并使用 ‘writeframesraw()’ 和
     ‘setnframes()’。*note open(): 55c. 函数可以在 *note with: 7da. 语句
     中使用。当 ‘with’ 块执行完毕，将调用 *note close(): 909. 方法。

     3.4 版更變: 支持了 *note with: 7da. 语句。

当打开文件用于读取时，由 *note open(): 55c. 返回的对象具有以下几种方法：

 -- 成員函式: aifc.getnchannels ()

     返回音频的通道数（单声道为 1，立体声为 2）。

 -- 成員函式: aifc.getsampwidth ()

     返回以字节表示的单个采样的大小。

 -- 成員函式: aifc.getframerate ()

     返回采样率（每秒的音频帧数）。

 -- 成員函式: aifc.getnframes ()

     返回文件中的音频帧总数。

 -- 成員函式: aifc.getcomptype ()

     返回一个长度为 4 的字节数组，描述了音频文件中使用的压缩类型。对于
     AIFF 文件，返回值为 ‘b'NONE'’。

 -- 成員函式: aifc.getcompname ()

     返回一个字节数组，可转换为人类可读的描述，描述的是音频文件中使用的
     压缩类型。对于 AIFF 文件，返回值为 ‘b'not compressed'’。

 -- 成員函式: aifc.getparams ()

     返回一个 *note namedtuple(): 1a1. ‘(nchannels, sampwidth,
     framerate, nframes, comptype, compname)’，与 ‘get*()’ 方法的输出相
     同。

 -- 成員函式: aifc.getmarkers ()

     返回一个列表，包含音频文件中的所有标记。标记由一个 3 元素的元组组成
     。第一个元素是标记 ID（整数），第二个是标记位置，从数据开头算起的帧
     数（整数），第三个是标记的名称（字符串）。

 -- 成員函式: aifc.getmark (id)

     根据传入的标记 `id' 返回元组，元组与 *note getmarkers(): 30e7. 中描
     述的一致。

 -- 成員函式: aifc.readframes (nframes)

     从音频文件读取并返回后续 `nframes' 个帧。返回的数据是一个字符串，包
     含每个帧所有通道的未压缩采样值。

 -- 成員函式: aifc.rewind ()

     倒回读取指针。下一次 *note readframes(): 30e9. 将从头开始。

 -- 成員函式: aifc.setpos (pos)

     移动读取指针到指定的帧上。

 -- 成員函式: aifc.tell ()

     返回当前的帧号。

 -- 成員函式: aifc.close ()

     关闭 AIFF 文件。调用此方法后，对象将无法再使用。

打开文件用于写入时，*note open(): 55c. 返回的对象具有上述所有方法，但
‘readframes()’ 和 ‘setpos()’ 除外，并额外具备了以下方法。只有调用了
‘set*()’ 方法之后，才能调用相应的 ‘get*()’ 方法。在首次调用
‘writeframes()’ 或 ‘writeframesraw()’ 之前，必须填写除帧数以外的所有参数
。

 -- 成員函式: aifc.aiff ()

     创建一个 AIFF 文件，默认创建 AIFF-C 文件，除非文件名以 ‘'.aiff'’ 为
     后缀，在此情况下默认创建 AIFF 文件。

 -- 成員函式: aifc.aifc ()

     创建一个 AIFF-C 文件。 默认创建 AIFF-C 文件，除非文件名以 ‘'.aiff'’
     为后缀，在此情况下默认创建 AIFF 文件。

 -- 成員函式: aifc.setnchannels (nchannels)

     指明音频文件中的通道数。

 -- 成員函式: aifc.setsampwidth (width)

     指明以字节为单位的音频采样大小。

 -- 成員函式: aifc.setframerate (rate)

     指明以每秒帧数表示的采样频率。

 -- 成員函式: aifc.setnframes (nframes)

     指明要写入到音频文件的帧数。 如果未设定此形参或者未正确设定，则文件
     需要支持位置查找。

 -- 成員函式: aifc.setcomptype (type, name)

     指明压缩类型。 如果未指明，则音频数据将不会被压缩。 在 AIFF 文件中
     ，压缩是无法实现的。 name 形参应当为以字节数组表示的人类可读的压缩
     类型描述，type 形参应当为长度为 4 的字节数组。 目前支持的压缩类型如
     下: ‘b'NONE'’, ‘b'ULAW'’, ‘b'ALAW'’, ‘b'G722'’。

 -- 成員函式: aifc.setparams (nchannels, sampwidth, framerate, comptype,
          compname)

     一次性设置上述所有参数。 该参数是由多个形参组成的元组。 这意味着可
     以使用 *note getparams(): 908. 调用的结果作为 *note setparams():
     30f4. 的参数。

 -- 成員函式: aifc.setmark (id, pos, name)

     添加具有给定 id (大于 0)，以及在给定位置上给定名称的标记。 此方法可
     在 *note close(): 909. 之前的任何时候被调用。

 -- 成員函式: aifc.tell ()

     返回输出文件中的当前写入位置。 适用于与 *note setmark(): 30f5. 进行
     协同配合。

 -- 成員函式: aifc.writeframes (data)

     将数据写入到输出文件。 此方法只能在设置了音频文件形参之后被调用。

     3.4 版更變: 现在可接受任意 *note bytes-like object: 6df.。

 -- 成員函式: aifc.writeframesraw (data)

     类似于 *note writeframes(): 90b.，不同之处在于音频文件的标头不会被
     更新。

     3.4 版更變: 现在可接受任意 *note bytes-like object: 6df.。

 -- 成員函式: aifc.close ()

     关闭 AIFF 文件。 文件的标头会被更新以反映音频数据的实际大小。 在调
     用此方法之后，对象将无法再被使用。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/aifc.py


File: python.info,  Node: sunau --- 读写 Sun AU 文件,  Next: wave --- 读写WAV格式文件,  Prev: aifc --- 读写 AIFF 和 AIFC 文件,  Up: 多媒体服务

5.22.3 ‘sunau’ — 读写 Sun AU 文件
---------------------------------

`源代码:' Lib/sunau.py(1)

__________________________________________________________________

*note sunau: fa. 模拟提供了一个处理 Sun AU 声音格式的便利接口。请注意此
模块与 *note aifc: 4. 和 *note wave: 130. 是兼容接口的。

音频文件由标头和数据组成。标头的字段为：

域                  内容
                    
------------------------------------------------------------------------
                    
magic word          四个字节 ‘.snd’
                    
                    
header size         标头的大小，包括信息，以字节为单位。
                    
                    
data size           数据的物理大小，以字节为单位。
                    
                    
编码                指示音频样本的编码方式。
                    
                    
sample rate         采样率
                    
                    
# of channels       采样中的通道数。
                    
                    
info                提供音频文件描述的ASCII字符串（用空字节填充）。
                    

除了 info 字段，所有标头字段的大小都是 4 字节。 它们都是采用大端字节序编
码的 32 位无符号整数。

*note sunau: fa. 模块定义了以下函数:

 -- 函式: sunau.open (file, mode)

     如果 `file' 是一个字符串，打开相应名称的文件，否则就把它作为可定位
     的文件类对象来处理。 `mode' 可以是

     ‘'r'’

          只读模式。

     ‘'w'’

          只写模式。

     注意它不支持同时读/写文件。

     `mode' 为 ‘'r'’ 时返回一个 ‘AU_read’ 对象，而 `mode' 为 ‘'w'’ 或
     ‘'wb'’ 时返回一个 ‘AU_write’ 对象。

*note sunau: fa. 模块定义了以下异常:

 -- 例外: sunau.Error

     当 Sun AU 规范或实现的低效导致无法操作时引发的错误。

*note sunau: fa. 模块定义了以下数据条目:

 -- Data: sunau.AUDIO_FILE_MAGIC

     位于每个有效的 Sun AU 文件开头的整数，以大端序形式存储。 这是一个被
     当作整数来解读的字符串 ‘.snd’。

 -- Data: sunau.AUDIO_FILE_ENCODING_MULAW_8
 -- Data: sunau.AUDIO_FILE_ENCODING_LINEAR_8
 -- Data: sunau.AUDIO_FILE_ENCODING_LINEAR_16
 -- Data: sunau.AUDIO_FILE_ENCODING_LINEAR_24
 -- Data: sunau.AUDIO_FILE_ENCODING_LINEAR_32
 -- Data: sunau.AUDIO_FILE_ENCODING_ALAW_8

     AU 标头中被此模块所支持的 encoding 字段值。

 -- Data: sunau.AUDIO_FILE_ENCODING_FLOAT
 -- Data: sunau.AUDIO_FILE_ENCODING_DOUBLE
 -- Data: sunau.AUDIO_FILE_ENCODING_ADPCM_G721
 -- Data: sunau.AUDIO_FILE_ENCODING_ADPCM_G722
 -- Data: sunau.AUDIO_FILE_ENCODING_ADPCM_G723_3
 -- Data: sunau.AUDIO_FILE_ENCODING_ADPCM_G723_5

     AU 标头中附加的已知但不被此模块所支持的 encoding 字段值。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/sunau.py


File: python.info,  Node: AU_read 对象,  Next: AU_write 对象,  Up: sunau --- 读写 Sun AU 文件

5.22.3.1 AU_read 对象
.....................

由上面的 *note open(): 572. 所返回的 AU_read 对象具有以下几种方法:

 -- 成員函式: AU_read.close ()

     关闭流，并使实例不可用。 （此方法会在删除对象时自动调用。）

 -- 成員函式: AU_read.getnchannels ()

     返回音频的通道数（单声道为 1，立体声为 2）。

 -- 成員函式: AU_read.getsampwidth ()

     返回采样字节长度。

 -- 成員函式: AU_read.getframerate ()

     返回采样频率。

 -- 成員函式: AU_read.getnframes ()

     返回音频总帧数。

 -- 成員函式: AU_read.getcomptype ()

     返回压缩类型。 受支持的压缩类型有 ‘'ULAW'’, ‘'ALAW'’ 和 ‘'NONE'’。

 -- 成員函式: AU_read.getcompname ()

     *note getcomptype(): 310d. 的人类可读的版本。 受支持的类型将为相应
     的名称 ‘'CCITT G.711 u-law'’, ‘'CCITT G.711 A-law'’ 和 ‘'not
     compressed'’。

 -- 成員函式: AU_read.getparams ()

     返回一个 *note namedtuple(): 1a1. ‘(nchannels, sampwidth,
     framerate, nframes, comptype, compname)’，与 ‘get*()’ 方法的输出相
     同。

 -- 成員函式: AU_read.readframes (n)

     读取至多 `n' 帧音频并作为 *note bytes: 172. 对象返回。 数据将以线性
     格式返回。 如果原始数据为 u-LAW 格式，则它将被转换。

 -- 成員函式: AU_read.rewind ()

     设置当前文件指针位置。

以下两个方法都使用指针，具体实现由其底层决定。

 -- 成員函式: AU_read.setpos (pos)

     设置文件指针到特定位置。 只有从 *note tell(): 3113. 返回的值才可被
     用作 `pos'。

 -- 成員函式: AU_read.tell ()

     返回当前文件指针的位置。 请注意该返回值与文件中的实例位置无关。

以下两个函数是为了与 *note aifc: 4. 保持兼容而定义的，实际不做任何事件。

 -- 成員函式: AU_read.getmarkers ()

     返回 ‘None’。

 -- 成員函式: AU_read.getmark (id)

     引发错误异常。


File: python.info,  Node: AU_write 对象,  Prev: AU_read 对象,  Up: sunau --- 读写 Sun AU 文件

5.22.3.2 AU_write 对象
......................

由上面的 *note open(): 572. 所返回的 AU_write 对象具有以下几种方法:

 -- 成員函式: AU_write.setnchannels (n)

     设置声道数。

 -- 成員函式: AU_write.setsampwidth (n)

     设置采样宽度（字节长度。）

     3.4 版更變: 增加了对 24 位采样的支持。

 -- 成員函式: AU_write.setframerate (n)

     设置帧速率。

 -- 成員函式: AU_write.setnframes (n)

     设置总帧数。 如果写入了更多的帧，此值将会被更改。

 -- 成員函式: AU_write.setcomptype (type, name)

     设置压缩类型和描述。 对于输出只支持 ‘'NONE'’ 和 ‘'ULAW'’。

 -- 成員函式: AU_write.setparams (tuple)

     `tuple' 应该是 ‘(nchannels, sampwidth, framerate, nframes,
     comptype, compname)’，每项的值可用于 ‘set*()’ 方法。 设置所有形参。

 -- 成員函式: AU_write.tell ()

     返回文件中的当前位置，其含义与 *note AU_read.tell(): 3113. 和 *note
     AU_read.setpos(): 3112. 方法的一致。

 -- 成員函式: AU_write.writeframesraw (data)

     写入音频数据但不更新 `nframes'。

     3.4 版更變: 现在可接受任意 *note bytes-like object: 6df.。

 -- 成員函式: AU_write.writeframes (data)

     写入音频数据并更新 `nframes'。

     3.4 版更變: 现在可接受任意 *note bytes-like object: 6df.。

 -- 成員函式: AU_write.close ()

     确保 `nframes' 正确，并关闭文件。

     此方法会在删除时被调用。

请注意在调用 ‘writeframes()’ 和 ‘writeframesraw()’ 之后再设置任何形参都
是无效的。


File: python.info,  Node: wave --- 读写WAV格式文件,  Next: chunk --- 读取 IFF 分块数据,  Prev: sunau --- 读写 Sun AU 文件,  Up: 多媒体服务

5.22.4 ‘wave’ — 读写WAV格式文件
-------------------------------

`源代码:' Lib/wave.py(1)

__________________________________________________________________

*note wave: 130. 模块提供了一个处理 WAV 声音格式的便利接口。它不支持压缩
/解压，但是支持单声道/立体声。

*note wave: 130. 模块定义了以下函数和异常:

 -- 函式: wave.open (file, mode=None)

     如果 `file' 是一个字符串，打开对应文件名的文件。否则就把它作为文件
     类对象来处理。`mode' 可以为以下值：

     ‘'rb'’

          只读模式。

     ‘'wb'’

          只写模式。

     注意不支持同时读写WAV文件。

     `mode' 设为 ‘'rb'’ 时返回一个 ‘Wave_read’ 对象，而 `mode' 设为
     ‘'wb'’ 时返回一个 ‘Wave_write’ 对象。如果省略 `mode' 并指定 `file'
     来传入一个文件类对象，则 ‘file.mode’ 会被用作 `mode' 的默认值。

     如果操作的是文件对象，当使用 wave 对象的 ‘close()’ 方法时，并不会真
     正关闭文件对象，这需要调用者负责来关闭文件对象。

     *note open(): 219. 函数可以在 *note with: 7da. 语句中使用。 当
     ‘with’ 阻塞结束时，*note Wave_read.close(): 3121. 或 *note
     Wave_write.close(): 3122. 方法会被调用。

     3.4 版更變: 添加了对不可搜索文件的支持。

 -- 例外: wave.Error

     当不符合WAV格式或无法操作时引发的错误。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/wave.py


File: python.info,  Node: Wave_read对象,  Next: Wave_write 对象,  Up: wave --- 读写WAV格式文件

5.22.4.1 Wave_read对象
......................

由 *note open(): 219. 返回的 Wave_read 对象，有以下几种方法:

 -- 成員函式: Wave_read.close ()

     关闭 *note wave: 130. 打开的数据流并使对象不可用。当对象销毁时会自
     动调用。

 -- 成員函式: Wave_read.getnchannels ()

     返回声道数量（‘1’ 为单声道，‘2’ 为立体声）

 -- 成員函式: Wave_read.getsampwidth ()

     返回采样字节长度。

 -- 成員函式: Wave_read.getframerate ()

     返回采样频率。

 -- 成員函式: Wave_read.getnframes ()

     返回音频总帧数。

 -- 成員函式: Wave_read.getcomptype ()

     返回压缩类型（只支持 ‘'NONE'’ 类型）

 -- 成員函式: Wave_read.getcompname ()

     *note getcomptype(): 312a. 的通俗版本。使用 ‘'not compressed'’ 代替
     ‘'NONE'’。

 -- 成員函式: Wave_read.getparams ()

     返回一个 *note namedtuple(): 1a1. ‘(nchannels, sampwidth,
     framerate, nframes, comptype, compname)’，与 ‘get*()’ 方法的输出相
     同。

 -- 成員函式: Wave_read.readframes (n)

     读取并返回以 *note bytes: 172. 对象表示的最多 `n' 帧音频。

 -- 成員函式: Wave_read.rewind ()

     设置当前文件指针位置。

后面两个方法是为了和 *note aifc: 4. 保持兼容，实际不做任何事情。

 -- 成員函式: Wave_read.getmarkers ()

     返回 ‘None’。

 -- 成員函式: Wave_read.getmark (id)

     引发错误异常。

以下两个方法都使用指针，具体实现由其底层决定。

 -- 成員函式: Wave_read.setpos (pos)

     设置文件指针到指定位置。

 -- 成員函式: Wave_read.tell ()

     返回当前文件指针位置。


File: python.info,  Node: Wave_write 对象,  Prev: Wave_read对象,  Up: wave --- 读写WAV格式文件

5.22.4.2 Wave_write 对象
........................

对于可查找的输出流，‘wave’ 头将自动更新以反映实际写入的帧数。 对于不可查
找的流，当写入第一帧时 `nframes' 值必须准确。 获取准确的 `nframes' 值可
以通过调用 *note setnframes(): 3134. 或 *note setparams(): 3135. 并附带
*note close(): 3122. 被调用之前将要写入的帧数，然后使用 *note
writeframesraw(): 9f2. 来写入帧数据，或者通过调用 *note writeframes():
9f3. 并附带所有要写入的帧。 在后一种情况下 *note writeframes(): 9f3. 将
计算数据中的帧数并在写入帧数据之前相应地设置 `nframes'。

由 *note open(): 219. 返回的 Wave_write 对象，有以下几种方法:

3.4 版更變: 添加了对不可搜索文件的支持。

 -- 成員函式: Wave_write.close ()

     确保 `nframes' 是正确的，并在文件被 *note wave: 130. 打开时关闭它。
     此方法会在对象收集时被调用。 如果输出流不可查找且 `nframes' 与实际
     写入的帧数不匹配时引发异常。

 -- 成員函式: Wave_write.setnchannels (n)

     设置声道数。

 -- 成員函式: Wave_write.setsampwidth (n)

     设置采样字节长度为 `n'。

 -- 成員函式: Wave_write.setframerate (n)

     设置采样频率为 `n'。

     3.2 版更變: 对此方法的非整数输入会被舍入到最接近的整数。

 -- 成員函式: Wave_write.setnframes (n)

     设置总帧数为 `n'。 如果与之后实际写入的帧数不一致此值将会被更改（ 如
     果输出流不可查找则此更改尝试将引发错误）。

 -- 成員函式: Wave_write.setcomptype (type, name)

     设置压缩格式。目前只支持 ‘NONE’ 即无压缩格式。

 -- 成員函式: Wave_write.setparams (tuple)

     `tuple' 应该是 ‘(nchannels, sampwidth, framerate, nframes,
     comptype, compname)’，每项的值应可用于 ‘set*()’ 方法。设置所有形参
     。

 -- 成員函式: Wave_write.tell ()

     返回当前文件指针，其指针含义和 *note Wave_read.tell(): 3132. 以及
     *note Wave_read.setpos(): 3131. 是一致的。

 -- 成員函式: Wave_write.writeframesraw (data)

     写入音频数据但不更新 `nframes'。

     3.4 版更變: 现在可接受任意 *note bytes-like object: 6df.。

 -- 成員函式: Wave_write.writeframes (data)

     写入音频帧并确保 `nframes' 是正确的。 如果输出流不可查找且在 `data'
     被写入之后写入的总帧数与之前设定的has been written does not match
     the previously set value for `nframes' 值不匹配将会引发错误。

     3.4 版更變: 现在可接受任意 *note bytes-like object: 6df.。

注意在调用 ‘writeframes()’ 或 ‘writeframesraw()’ 之后再设置任何格式参数
是无效的，而且任何这样的尝试将引发 *note wave.Error: 3123.。


File: python.info,  Node: chunk --- 读取 IFF 分块数据,  Next: colorsys --- 颜色系统间的转换,  Prev: wave --- 读写WAV格式文件,  Up: 多媒体服务

5.22.5 ‘chunk’ — 读取 IFF 分块数据
----------------------------------

`源代码:' Lib/chunk.py(1)

__________________________________________________________________

本模块提供了一个读取使用 EA IFF 85 分块的数据的接口chunks.  (2) 这种格式
使用的场合有 Audio Interchange File Format (AIFF/AIFF-C) 和 Real Media
File Format (RMFF) 等。 与它们密切相关的 WAVE 音频文件也可使用此模块来读
取。

一个分块具有以下结构:

偏移          长度         内容
                           
---------------------------------------------------------------
                           
0             4            区块ID
                           
                           
4             4            大端字节顺序的块大小，不包括头
                           
                           
8             `n'          数据字节，其中 `n' 是前一字段中给
                           出的大小
                           
                           
8 + `n'       0 或 1       如果 `n' 为奇数且使用块对齐，则需
                           要填充字节
                           

ID是一个4字节的字符串，用于标识块的类型。

大小字段（32 位的值，使用大端字节序编码）给出分块数据的大小，不包括 8 字
节的标头。

使用由一个或更多分块组成的 IFF 类型文件。 此处定义的 *note Chunk: 313d.
类的建议使用方式是在每个分块开始时实例化一个实例并从实例读取直到其末尾，
在那之后可以再实例化新的实例。 到达文件末尾时，创建新实例将会失败并引发
*note EOFError: d34. 异常。

 -- 類別: chunk.Chunk (file, align=True, bigendian=True,
          inclheader=False)

     代表一个分块的类。 `file' 参数预期为一个文件类对象。 特别地也允许该
     类的实例。 唯一必需的方法是 ‘read()’。 如果存在 *note seek(): 1efb.
     和 *note tell(): 1efc. 方法并且没有引发异常，它们也会被使用。 如果
     存在这些方法并且引发了异常，则它们不应改变目标对象。 如果可选参数
     `align' 为真值，则分块应当以 2 字节边界对齐。 如果 `align' 为假值，
     则不使用对齐。 此参数默认为真值。 如果可选参数 `bigendian' 为假值，
     分块大小应当为小端序。 这对于 WAVE 音频文件是必须的。 此参数默认为
     真值。 如果可选参数 `inclheader' 为真值，则分块标头中给出的大小将包
     括标头的大小。 此参数默认为假值。

     *note Chunk: 313d. 对象支持下列方法：

      -- 成員函式: getname ()

          返回分块的名称（ID）。 这是分块的头 4 个字节。

      -- 成員函式: getsize ()

          返回分块的大小。

      -- 成員函式: close ()

          关闭并跳转到分块的末尾。 这不会关闭下层的文件。

     在 *note close(): 3140. 方法已被调用后其余方法将会引发 *note
     OSError: 304.。 在 Python 3.3 之前，它们曾会引发 *note IOError:
     a73.，现在这是 *note OSError: 304. 的一个别名。

      -- 成員函式: isatty ()

          返回 ‘False’。

      -- 成員函式: seek (pos, whence=0)

          设置分块的当前位置。 `whence' 参数为可选项并且默认为 ‘0’ (绝对
          文件定位)；其他值还有 ‘1’ (相对当前位置查找) 和 ‘2’ (相对文件
          末尾查找)。 没有返回值。 如果下层文件不支持查找，则只允许向前
          查找。

      -- 成員函式: tell ()

          将当前位置返回到分块。

      -- 成員函式: read (size=-1)

          从分块读取至多 `size' 个字节（如果在获得 `size' 个字节之前已到
          达分块末尾则读取的字节会少于此数量）。 如果 `size' 参数为负值
          或被省略，则读取所有字节直到分块末尾。 当立即遇到分块末尾则返
          回空字节串对象。

      -- 成員函式: skip ()

          跳到分块末尾。此后对分块再次调用 *note read(): 3144. 将返回
          ‘b''’。 如果你对分块的内容不感兴趣，则应当调用此方法以使文件指
          向下一分块的开头。

註解
....

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/chunk.py

   (2) (1) "EA IFF 85" 交换格式文件标准, Jerry Morrison, Electronic
Arts, 1985 年 1 月。


File: python.info,  Node: colorsys --- 颜色系统间的转换,  Next: imghdr --- 推测图像类型,  Prev: chunk --- 读取 IFF 分块数据,  Up: 多媒体服务

5.22.6 ‘colorsys’ — 颜色系统间的转换
------------------------------------

`源代码：' Lib/colorsys.py(1)

__________________________________________________________________

*note colorsys: 1f. 模块定义了计算机显示器所用的 RGB (Red Green Blue) 色
彩空间与三种其他色彩坐标系统 YIQ, HLS (Hue Lightness Saturation) 和 HSV
(Hue Saturation Value) 表示的颜色值之间的双向转换。 所有这些色彩空间的坐
标都使用浮点数值来表示。 在 YIQ 空间中，Y 坐标取值为 0 和 1 之间，而 I 和
Q 坐标均可以为正数或负数。 在所有其他空间中，坐标取值均为 0 和 1 之间。

也參考
......

有关色彩空间的更多信息可访问 ‘https://poynton.ca/ColorFAQ.html’ 和
‘https://www.cambridgeincolour.com/tutorials/color-spaces.htm’。

*note colorsys: 1f. 模块定义了如下函数：

 -- 函式: colorsys.rgb_to_yiq (r, g, b)

     把颜色从RGB值转为YIQ值。

 -- 函式: colorsys.yiq_to_rgb (y, i, q)

     把颜色从YIQ值转为RGB值。

 -- 函式: colorsys.rgb_to_hls (r, g, b)

     把颜色从RGB值转为HLS值。

 -- 函式: colorsys.hls_to_rgb (h, l, s)

     把颜色从HLS值转为RGB值。

 -- 函式: colorsys.rgb_to_hsv (r, g, b)

     把颜色从RGB值转为HSV值。

 -- 函式: colorsys.hsv_to_rgb (h, s, v)

     把颜色从HSV值转为RGB值。

示例:

     >>> 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)

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/colorsys.py


File: python.info,  Node: imghdr --- 推测图像类型,  Next: sndhdr --- 推测声音文件的类型,  Prev: colorsys --- 颜色系统间的转换,  Up: 多媒体服务

5.22.7 ‘imghdr’ — 推测图像类型
------------------------------

`源代码' Lib/imghdr.py(1)

__________________________________________________________________

*note imghdr: 98. 模块推测文件或字节流中的图像的类型。

*note imghdr: 98. 模块定义了以下类型：

 -- 函式: imghdr.what (filename, h=None)

     测试包含在命名为 `filename' 的文件中的图像数据，并且返回描述此类图
     片的字符串。如果可选的 `h' 被提供， `filename' 将被忽略并且 `h' 包
     含将被测试的二进制流。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

接下来的图像类型是可识别的，返回值来自 *note what(): 7de.：

值               图像格式
                 
---------------------------------------------------------
                 
‘'rgb'’          SGI 图像库文件
                 
                 
‘'gif'’          GIF 87a 和 89a 文件
                 
                 
‘'pbm'’          便携式位图文件
                 
                 
‘'pgm'’          便携式灰度图文件
                 
                 
‘'ppm'’          便携式像素表文件
                 
                 
‘'tiff'’         TIFF 文件
                 
                 
‘'rast'’         Sun 光栅文件
                 
                 
‘'xbm'’          X 位图文件
                 
                 
‘'jpeg'’         JFIF 或 Exif 格式的 JPEG 数据
                 
                 
‘'bmp'’          BMP 文件
                 
                 
‘'png'’          便携式网络图像
                 
                 
‘'webp'’         WebP 文件
                 
                 
‘'exr'’          OpenEXR 文件
                 

3.5 版新加入: `exr' 和 `webp' 格式被添加。

你可以扩展此 *note imghdr: 98. 可以被追加的这个变量识别的文件格式的列表
：

 -- Data: imghdr.tests

     执行单个测试的函数列表。每个函数都有两个参数：字节流和类似开放文件
     的对象。当 *note what(): 7de. 用字节流调用时，类文件对象将是
     ‘None’。

     如果测试成功，这个测试函数应当返回一个描述图像类型的字符串，否则返
     回 ‘None’。

示例:

     >>> import imghdr
     >>> imghdr.what('bass.gif')
     'gif'

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/imghdr.py


File: python.info,  Node: sndhdr --- 推测声音文件的类型,  Next: ossaudiodev --- 访问兼容OSS的音频设备,  Prev: imghdr --- 推测图像类型,  Up: 多媒体服务

5.22.8 ‘sndhdr’ — 推测声音文件的类型
------------------------------------

`源代码' Lib/sndhdr.py(1)

__________________________________________________________________

*note sndhdr: ee. 提供了企图猜测文件中的声音数据类型的功能函数。当这些函
数可以推测出存储在文件中的声音数据的类型是，它们返回一个 *note
collections.namedtuple(): 1a1.，包含了五种属性：（‘filetype’,
‘framerate’, ‘nchannels’, ‘nframes’, ‘sampwidth’）。这些 `type' 的值表示
数据的类型，会是以下字符串之一： ‘'aifc'’, ‘'aiff'’, ‘'au'’, ‘'hcom'’,
‘'sndr'’, ‘'sndt'’, ‘'voc'’, ‘'wav'’, ‘'8svx'’, ‘'sb'’, ‘'ub'’, or
‘'ul'’ 。 `sampling_rate' 可能是实际值或者当未知或者难以解码时的 ‘0’。类
似的， `channels' 也会返回实际值或者在无法推测或者难以解码时返回 ‘0’。
`frames' 则是实际值或 ‘-1’。 元组的最后一项， `bits_per_sample' 将会为比
特表示的 sample 大小或者 A-LAW 时为 ‘'A'’， u-LAW 时为 ‘'U'’。

 -- 函式: sndhdr.what (filename)

     使用 *note whathdr(): 837. 推测存储在 `filename' 文件中的声音数据的
     类型。如果成功，返回上述的命名元组，否则返回 ‘None’。

     3.5 版更變: 将结果从元组改为命名元组。

 -- 函式: sndhdr.whathdr (filename)

     基于文件头推测存储在文件中的声音数据类型。文件名由 `filename' 给出
     。这个函数在成功时返回上述命名元组，或者在失败时返回 ‘None’。

     3.5 版更變: 将结果从元组改为命名元组。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/sndhdr.py


File: python.info,  Node: ossaudiodev --- 访问兼容OSS的音频设备,  Prev: sndhdr --- 推测声音文件的类型,  Up: 多媒体服务

5.22.9 ‘ossaudiodev’ — 访问兼容OSS的音频设备
--------------------------------------------

__________________________________________________________________

该模块允许您访问 OSS（开放式音响系统）音频接口。 OSS 可用于广泛的开源和
商业 Unices，并且是 Linux 和最新版本的 FreeBSD 的标准音频接口。

3.3 版更變: 此模块中过去会引发 *note IOError: a73. 的操作现在将引发
*note OSError: 304.。

也參考
......

开放之声系统程序员手册(1)

     OSS C API 的官方文档

该模块定义了大量由OSS设备驱动提供的常量； 请参阅‘‘<sys/soundcard.h>‘‘
Linux 或 FreeBSD 上的列表。

*note ossaudiodev: c6. 定义了下列变量和函数:

 -- 例外: ossaudiodev.OSSAudioError

     此异常会针对特定错误被引发。 其参数为一个描述错误信息的字符串。

     （如果 *note ossaudiodev: c6. 从系统调用例如 ‘open()’, ‘write()’ 或
     ‘ioctl()’ 接收到错误，它将引发 *note OSError: 304.。 由 *note
     ossaudiodev: c6. 直接检测到的错误将引发 *note OSSAudioError: 3155.。
     ）

     （为了向下兼容，此异常类也可通过 ‘ossaudiodev.error’ 访问。）

 -- 函式: ossaudiodev.open (mode)

 -- 函式: ossaudiodev.open (device, mode)

     打开一个音频设备并返回 OSS 音频设备对象。 此对象支持许多文件类方法
     ，例如 ‘read()’, ‘write()’ 和 ‘fileno()’ (不过传统的 Unix 读/写语义
     与 OSS 音频设备的存在一些细微的差异)。 它还支持一些音频专属的方法；
     完整的方法列表见下文。

     `device' 是要使用的音频设备文件名。 如果未指定，则此模块会先在环境
     变量 ‘AUDIODEV’ 中查找要使用的设备。 如果未找到，它将回退为
     ‘/dev/dsp’。

     `mode' 可以为 ‘'r'’ 表示只读（录音）访问，‘'w'’ 表示只写（回放）访
     问以及 ‘'rw'’ 表示同时读写。 由于许多声卡在同一时间只允许单个进程打
     开录音机或播放器，因此好的做法是只根据活动的需要打开设备。 并且，有
     些声卡是半双工的：它们可以被打开用于读取或写入，但不能同时读写。

     请注意这里特殊的调用语法: `first' 参数是可选的，而第二个参数则是必
     需的。 这是出于历史原因要与 *note ossaudiodev: c6. 所替代的
     ‘linuxaudiodev’ 模块保持兼容。

 -- 函式: ossaudiodev.openmixer ([device])

     打开一个混音设备并返回 OSS 混音设备对象。 `device' 是要使用的混音设
     备文件名。 如果未指定，则此模块会先在环境变量 ‘MIXERDEV’ 中查找要使
     用的设备。 如果未找到，它将回退为 ‘/dev/mixer’。

* Menu:

* 音频设备对象::
* Mixer Device Objects::

   ---------- Footnotes ----------

   (1) http://www.opensound.com/pguide/oss.pdf


File: python.info,  Node: 音频设备对象,  Next: Mixer Device Objects,  Up: ossaudiodev --- 访问兼容OSS的音频设备

5.22.9.1 音频设备对象
.....................

在你写入或读取音频设备之前，你必须按照正确的顺序调用三个方法:

  1. ‘setfmt()’ 设置输出格式

  2. ‘channels()’ 设置声道数量

  3. ‘speed()’ 设置采样率

或者，你也可以使用 ‘setparameters()’ 方法一次性地设置全部三个音频参数。
这更为便捷，但可能不会在所有场景下都一样灵活。

*note open(): 3156. 所返回的音频设备对象定义了下列方法和（只读）属性:

 -- 成員函式: oss_audio_device.close ()

     显式地关闭音频设备。 当你完成写入或读取音频设备后，你应当显式地关闭
     它。 已关闭的设备不可被再次使用。

 -- 成員函式: oss_audio_device.fileno ()

     返回与设备相关联的文件描述符。

 -- 成員函式: oss_audio_device.read (size)

     从音频输入设备读取 `size' 个字节并返回为 Python 字符串。 与大多数
     Unix 设备驱动不同，处于阻塞模式（默认）的 OSS 音频设备将阻塞 *note
     read(): 315c. 直到所请求大小的数据全部可用。

 -- 成員函式: oss_audio_device.write (data)

     将一个 *note bytes-like object: 6df. `data' 写入音频设备并返回写入
     的字节数。 如果音频设备处于阻塞模式（默认），则总是会写入完整数据（
     这还是不同于通常的 Unix 设备语义）。 如果设备处于非阻塞模式，则可能
     会有部分数据未被写入 — 参见 *note writeall(): 315e.。

     3.5 版更變: 现在支持可写的 *note 字节类对象: 6df.。

 -- 成員函式: oss_audio_device.writeall (data)

     将一个 *note bytes-like object: 6df. `data' 写入音频设备：等待直到
     音频设备能够接收数据，将根据其所能接收的数据量尽可能多地写入，并重
     复操作直至 `data' 被完全写入。 如果设备处于阻塞模式（默认），则其效
     果与 *note write(): 315d. 相同；*note writeall(): 315e. 仅适用于非
     阻塞模式。 它没有返回值，因为写入的数据量总是等于所提供的数据量。

     3.5 版更變: 现在支持可写的 *note 字节类对象: 6df.。

3.2 版更變: 音频设备对象还支持上下文管理协议，就是说它们可以在 *note
with: 7da. 语句中使用。

下列方法各自映射一个 ‘ioctl()’ 系统调用。 对应关系很明显：例如，
‘setfmt()’ 对应 ‘SNDCTL_DSP_SETFMT’ ioctl，而 ‘sync()’ 对应
‘SNDCTL_DSP_SYNC’ (这在查阅 OSS 文档时很有用)。 如果下层的 ‘ioctl()’ 失
败，它们将引发 *note OSError: 304.。

 -- 成員函式: oss_audio_device.nonblock ()

     将设备转为非阻塞模式。 一旦处于非阻塞模式，将无法将其转回阻塞模式。

 -- 成員函式: oss_audio_device.getfmts ()

     返回声卡所支持的音频输出格式的位掩码。 OSS 支持的一部分格式如下:

     文件格式                      描述
                                   
     --------------------------------------------------------------------------------
                                   
     ‘AFMT_MU_LAW’                 一种对数编码格式（被 Sun ‘.au’ 文件和
                                   ‘/dev/audio’ 所使用）
                                   
                                   
     ‘AFMT_A_LAW’                  一种对数编码格式
                                   
                                   
     ‘AFMT_IMA_ADPCM’              一种 4:1 压缩格式，由 Interactive Multimedia
                                   Association 定义
                                   
                                   
     ‘AFMT_U8’                     无符号的 8 位音频
                                   
                                   
     ‘AFMT_S16_LE’                 Signed, 16-bit audio, little-endian byte order
                                   (as used by Intel processors)
                                   
                                   
     ‘AFMT_S16_BE’                 Signed, 16-bit audio, big-endian byte order (as
                                   used by 68k, PowerPC, Sparc)
                                   
                                   
     ‘AFMT_S8’                     Signed, 8 bit audio
                                   
                                   
     ‘AFMT_U16_LE’                 Unsigned, 16-bit little-endian audio
                                   
                                   
     ‘AFMT_U16_BE’                 Unsigned, 16-bit big-endian audio
                                   

     Consult the OSS documentation for a full list of audio formats, and
     note that most devices support only a subset of these formats.
     Some older devices only support ‘AFMT_U8’; the most common format
     used today is ‘AFMT_S16_LE’.

 -- 成員函式: oss_audio_device.setfmt (format)

     Try to set the current audio format to `format'—see *note
     getfmts(): 3160. for a list.  Returns the audio format that the
     device was set to, which may not be the requested format.  May also
     be used to return the current audio format—do this by passing an
     "audio format" of ‘AFMT_QUERY’.

 -- 成員函式: oss_audio_device.channels (nchannels)

     Set the number of output channels to `nchannels'.  A value of 1
     indicates monophonic sound, 2 stereophonic.  Some devices may have
     more than 2 channels, and some high-end devices may not support
     mono.  Returns the number of channels the device was set to.

 -- 成員函式: oss_audio_device.speed (samplerate)

     Try to set the audio sampling rate to `samplerate' samples per
     second.  Returns the rate actually set.  Most sound devices don’t
     support arbitrary sampling rates.  Common rates are:

     采样率      描述
                 
     ------------------------------------------------------------
                 
     8000        ‘/dev/audio’ 的默认采样率
                 
                 
     11025       语音录音
                 
                 
     22050

     44100       CD品质的音频（16位采样和2通道）
                 
                 
     96000       DVD品质的音频（24位采样）
                 

 -- 成員函式: oss_audio_device.sync ()

     Wait until the sound device has played every byte in its buffer.
     (This happens implicitly when the device is closed.)  The OSS
     documentation recommends closing and re-opening the device rather
     than using *note sync(): 3164.

 -- 成員函式: oss_audio_device.reset ()

     Immediately stop playing or recording and return the device to a
     state where it can accept commands.  The OSS documentation
     recommends closing and re-opening the device after calling *note
     reset(): 3165.

 -- 成員函式: oss_audio_device.post ()

     Tell the driver that there is likely to be a pause in the output,
     making it possible for the device to handle the pause more
     intelligently.  You might use this after playing a spot sound
     effect, before waiting for user input, or before doing disk I/O.

The following convenience methods combine several ioctls, or one ioctl
and some simple calculations.

 -- 成員函式: oss_audio_device.setparameters (format, nchannels,
          samplerate[, strict=False])

     Set the key audio sampling parameters—sample format, number of
     channels, and sampling rate—in one method call.  `format',
     `nchannels', and `samplerate' should be as specified in the *note
     setfmt(): 3161, *note channels(): 3162, and *note speed(): 3163.
     methods.  If `strict' is true, *note setparameters(): 3167. checks
     to see if each parameter was actually set to the requested value,
     and raises *note OSSAudioError: 3155. if not.  Returns a tuple
     (`format', `nchannels', `samplerate') indicating the parameter
     values that were actually set by the device driver (i.e., the same
     as the return values of *note setfmt(): 3161, *note channels():
     3162, and *note speed(): 3163.).

     For example,

          (fmt, channels, rate) = dsp.setparameters(fmt, channels, rate)

     is equivalent to

          fmt = dsp.setfmt(fmt)
          channels = dsp.channels(channels)
          rate = dsp.rate(rate)

 -- 成員函式: oss_audio_device.bufsize ()

     Returns the size of the hardware buffer, in samples.

 -- 成員函式: oss_audio_device.obufcount ()

     Returns the number of samples that are in the hardware buffer yet
     to be played.

 -- 成員函式: oss_audio_device.obuffree ()

     Returns the number of samples that could be queued into the
     hardware buffer to be played without blocking.

Audio device objects also support several read-only attributes:

 -- 屬性: oss_audio_device.closed

     Boolean indicating whether the device has been closed.

 -- 屬性: oss_audio_device.name

     String containing the name of the device file.

 -- 屬性: oss_audio_device.mode

     The I/O mode for the file, either ‘"r"’, ‘"rw"’, or ‘"w"’.


File: python.info,  Node: Mixer Device Objects,  Prev: 音频设备对象,  Up: ossaudiodev --- 访问兼容OSS的音频设备

5.22.9.2 Mixer Device Objects
.............................

The mixer object provides two file-like methods:

 -- 成員函式: oss_mixer_device.close ()

     This method closes the open mixer device file.  Any further
     attempts to use the mixer after this file is closed will raise an
     *note OSError: 304.

 -- 成員函式: oss_mixer_device.fileno ()

     Returns the file handle number of the open mixer device file.

3.2 版更變: Mixer objects also support the context management protocol.

The remaining methods are specific to audio mixing:

 -- 成員函式: oss_mixer_device.controls ()

     This method returns a bitmask specifying the available mixer
     controls ("Control" being a specific mixable "channel", such as
     ‘SOUND_MIXER_PCM’ or ‘SOUND_MIXER_SYNTH’).  This bitmask indicates
     a subset of all available mixer controls—the ‘SOUND_MIXER_*’
     constants defined at module level.  To determine if, for example,
     the current mixer object supports a PCM mixer, use the following
     Python code:

          mixer=ossaudiodev.openmixer()
          if mixer.controls() & (1 << ossaudiodev.SOUND_MIXER_PCM):
              # PCM is supported
              ... code ...

     For most purposes, the ‘SOUND_MIXER_VOLUME’ (master volume) and
     ‘SOUND_MIXER_PCM’ controls should suffice—but code that uses the
     mixer should be flexible when it comes to choosing mixer controls.
     On the Gravis Ultrasound, for example, ‘SOUND_MIXER_VOLUME’ does
     not exist.

 -- 成員函式: oss_mixer_device.stereocontrols ()

     Returns a bitmask indicating stereo mixer controls.  If a bit is
     set, the corresponding control is stereo; if it is unset, the
     control is either monophonic or not supported by the mixer (use in
     combination with *note controls(): 3172. to determine which).

     See the code example for the *note controls(): 3172. function for
     an example of getting data from a bitmask.

 -- 成員函式: oss_mixer_device.reccontrols ()

     Returns a bitmask specifying the mixer controls that may be used to
     record.  See the code example for *note controls(): 3172. for an
     example of reading from a bitmask.

 -- 成員函式: oss_mixer_device.get (control)

     Returns the volume of a given mixer control.  The returned volume
     is a 2-tuple ‘(left_volume,right_volume)’.  Volumes are specified
     as numbers from 0 (silent) to 100 (full volume).  If the control is
     monophonic, a 2-tuple is still returned, but both volumes are the
     same.

     Raises *note OSSAudioError: 3155. if an invalid control is
     specified, or *note OSError: 304. if an unsupported control is
     specified.

 -- 成員函式: oss_mixer_device.set (control, (left, right))

     Sets the volume for a given mixer control to ‘(left,right)’.
     ‘left’ and ‘right’ must be ints and between 0 (silent) and 100
     (full volume).  On success, the new volume is returned as a
     2-tuple.  Note that this may not be exactly the same as the volume
     specified, because of the limited resolution of some soundcard’s
     mixers.

     Raises *note OSSAudioError: 3155. if an invalid mixer control was
     specified, or if the specified volumes were out-of-range.

 -- 成員函式: oss_mixer_device.get_recsrc ()

     This method returns a bitmask indicating which control(s) are
     currently being used as a recording source.

 -- 成員函式: oss_mixer_device.set_recsrc (bitmask)

     Call this function to specify a recording source.  Returns a
     bitmask indicating the new recording source (or sources) if
     successful; raises *note OSError: 304. if an invalid source was
     specified.  To set the current recording source to the microphone
     input:

          mixer.setrecsrc (1 << ossaudiodev.SOUND_MIXER_MIC)


File: python.info,  Node: 國際化,  Next: 程式框架,  Prev: 多媒体服务,  Up: Python 標準函式庫 Standard Library

5.23 國際化
===========

本章中介绍的模块通过提供选择要在程序信息中使用的语言的机制或通过定制输出
以匹配本地约定来帮助你编写不依赖于语言和区域设置的软件。

本章中描述的模块列表是：

* Menu:

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


File: python.info,  Node: gettext --- 多语种国际化服务,  Next: locale --- 国际化服务,  Up: 國際化

5.23.1 ‘gettext’ — 多语种国际化服务
-----------------------------------

`源代码：' Lib/gettext.py(1)

__________________________________________________________________

*note gettext: 87. 模块为 Python 模块和应用程序提供国际化
(Internationalization, I18N) 和本地化 (Localization, L10N) 服务。它同时
支持 GNU ‘gettext’ 消息编目 API 和更高级的、基于类的 API，后者可能更适合
于 Python 文件。下方描述的接口允许用户使用一种自然语言编写模块和应用程序
消息，并提供翻译后的消息编目，以便在不同的自然语言下运行。

同时还给出一些本地化 Python 模块及应用程序的小技巧。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/gettext.py


File: python.info,  Node: GNU gettext API,  Next: 基于类的 API,  Up: gettext --- 多语种国际化服务

5.23.1.1 GNU ‘gettext’ API
..........................

模块 *note gettext: 87. 定义了下列 API，这与 ‘gettext’ API 类似。如果你
使用该 API，将会对整个应用程序产生全局的影响。如果你的应用程序支持多语种
，而语言选择取决于用户的语言环境设置，这通常正是你所想要的。而如果你正在
本地化某个 Python 模块，或者你的应用程序需要在运行时切换语言，相反你或许
想用基于类的API。

 -- 函式: gettext.bindtextdomain (domain, localedir=None)

     将 `domain' 绑定到本地目录 `localedir'。 更具体地来说，模块 *note
     gettext: 87. 将使用路径 (在 Unix 系统中):
     ‘`localedir'/`language'/LC_MESSAGES/`domain'.mo’ 查找二进制 ‘.mo’ 文
     件，此处对应地查找 `language' 的位置是环境变量 ‘LANGUAGE’,
     ‘LC_ALL’, ‘LC_MESSAGES’ 和 ‘LANG’ 中。

     如果遗漏了 `localedir' 或者设置为 ‘None’，那么将返回当前 `domain' 所
     绑定的值 (1)

 -- 函式: gettext.bind_textdomain_codeset (domain, codeset=None)

     将 `domain' 绑定到 `codeset'，修改 *note lgettext(): 3b6, *note
     ldgettext(): 3b7, *note lngettext(): 3b8. 和 *note ldngettext():
     3b9. 函数返回的字节串的字符编码。如果省略了 `codeset'，则返回当前绑
     定的编码集。

     Deprecated since version 3.8, will be removed in version 3.10.

 -- 函式: gettext.textdomain (domain=None)

     修改或查询当前的全局域。如果 `domain' 为 ‘None’，则返回当前的全局域
     ，不为 ‘None’ 则将全局域设置为 `domain'，并返回它。

 -- 函式: gettext.gettext (message)

     返回 `message' 的本地化翻译，依据包括当前的全局域、语言和语言环境目
     录。本函数在本地命名空间中通常有别名 ‘_()’ （参考下面的示例）。

 -- 函式: gettext.dgettext (domain, message)

     与 *note gettext(): e92. 类似，但在指定的 `domain' 中查找 message。

 -- 函式: gettext.ngettext (singular, plural, n)

     与 *note gettext(): e92. 类似，但考虑了复数形式。如果找到了翻译，则
     将 `n' 代入复数公式，然后返回得出的消息（某些语言具有两种以上的复数
     形式）。如果未找到翻译，则 `n' 为 1 时返回 `singular'，为其他数时返
     回 `plural'。

     复数公式取自编目头文件。它是 C 或 Python 表达式，有一个自变量 `n'，
     该表达式计算的是所需复数形式在编目中的索引号。关于在 ‘.po’ 文件中使
     用的确切语法和各种语言的公式，请参阅 GNU gettext 文档(2) 。

 -- 函式: gettext.dngettext (domain, singular, plural, n)

     与 *note ngettext(): 3183. 类似，但在指定的 `domain' 中查找
     message。

 -- 函式: gettext.pgettext (context, message)

 -- 函式: gettext.dpgettext (domain, context, message)

 -- 函式: gettext.npgettext (context, singular, plural, n)

 -- 函式: gettext.dnpgettext (domain, context, singular, plural, n)

     与前缀中没有 ‘p’ 的相应函数类似（即 *note gettext(): 87, *note
     dgettext(): 3182, *note ngettext(): 3183, *note dngettext(): 3184.
     ），但是仅翻译给定的 message `context'。

     3.8 版新加入.

 -- 函式: gettext.lgettext (message)

 -- 函式: gettext.ldgettext (domain, message)

 -- 函式: gettext.lngettext (singular, plural, n)

 -- 函式: gettext.ldngettext (domain, singular, plural, n)

     与前缀中没有 ‘l’ 的相应函数等效（ *note gettext(): e92, *note
     dgettext(): 3182, *note ngettext(): 3183. 和 *note dngettext():
     3184. ），但是如果没有用 *note bind_textdomain_codeset(): 3ba. 显式
     设置其他编码，则返回的翻译将以首选系统编码来编码字节串。

          警告: 在 Python 3 中应避免使用这些函数，因为它们返回的是编码后
          的字节串。最好使用返回 Unicode 字符串的其他方法，因为大多数
          Python 应用程序都希望将人类可读的文本作为字符串而不是字节来处
          理。此外，如果翻译后的字符串存在编码问题，则可能会意外出现与
          Unicode 相关的异常。

     Deprecated since version 3.8, will be removed in version 3.10.

注意，GNU ‘gettext’ 还定义了 ‘dcgettext()’ 方法，但它被认为不实用，因此
目前没有实现它。

这是该 API 的典型用法示例:

     import gettext
     gettext.bindtextdomain('myapplication', '/path/to/my/language/directory')
     gettext.textdomain('myapplication')
     _ = gettext.gettext
     # ...
     print(_('This is a translatable string.'))

   ---------- Footnotes ----------

   (1) (1) 不同系统的默认语言环境目录是不同的；比如在 RedHat Linux 上是
‘/usr/share/locale’，在 Solaris 上是 ‘/usr/lib/locale’。*note gettext:
87. 模块不会支持这些基于不同系统的默认值；而它的默认值为
‘`sys.base_prefix'/share/locale’ （请参阅 *note sys.base_prefix: 3180.）
。基于上述原因，最好每次都在应用程序的开头使用明确的绝对路径来调用 *note
bindtextdomain(): 317f.。

   (2) https://www.gnu.org/software/gettext/manual/gettext.html


File: python.info,  Node: 基于类的 API,  Next: 国际化 I18N 你的程序和模块,  Prev: GNU gettext API,  Up: gettext --- 多语种国际化服务

5.23.1.2 基于类的 API
.....................

与 GNU ‘gettext’ API 相比，*note gettext: 87. 模块的基于类的 API 提供了
更多的灵活性和更强的便利性。这是本地化 Python 应用程序和模块的推荐方法。
‘gettext’ 定义了一个 *note GNUTranslations: 3189. 类，该类实现了 GNU
‘.mo’ 格式文件的解析，并且具有用于返回字符串的方法。本类的实例也可以将自
身作为函数 ‘_()’ 安装到内建命名空间中。

 -- 函式: gettext.find (domain, localedir=None, languages=None,
          all=False)

     本函数实现了标准的 ‘.mo’ 文件搜索算法。它接受一个 `domain'，它与
     *note textdomain(): 3181. 接受的域相同。可选参数 `localedir' 与
     *note bindtextdomain(): 317f. 中的相同。可选参数 `languages' 是多条
     字符串的列表，其中每条字符串都是一种语言代码。

     如果没有传入 `localedir'，则使用默认的系统语言环境目录。 (1) 如果没
     有传入 `languages'，则搜索以下环境变量： ‘LANGUAGE’、 ‘LC_ALL’、
     ‘LC_MESSAGES’ 和 ‘LANG’。从这些变量返回的第一个非空值将用作
     `languages' 变量。环境变量应包含一个语言列表，由冒号分隔，该列表会
     被按冒号拆分，以产生所需的语言代码字符串列表。

     *note find(): 318a. 将扩展并规范化 language，然后遍历它们，搜索由这
     些组件构建的现有文件:

     ‘`localedir'/`language'/LC_MESSAGES/`domain'.mo’

     *note find(): 318a. 返回找到类似的第一个文件名。如果找不到这样的文
     件，则返回 ‘None’。如果传入了 `all'，它将返回一个列表，包含所有文件
     名，并按它们在语言列表或环境变量中出现的顺序排列。

 -- 函式: gettext.translation (domain, localedir=None, languages=None,
          class_=None, fallback=False, codeset=None)

     根据 `domain'、`localedir' 和 `languages'，返回 ‘*Translations’ 实
     例，首先应将前述参数传入 *note find(): 318a. 以获取关联的 ‘.mo’ 文
     件路径的列表。名字与 ‘.mo’ 文件名相同的实例将被缓存。如果传入
     `class_'，它将是实际被实例化的类，否则实例化 *note GNUTranslations:
     3189.。类的构造函数必须只接受一个 *note 文件对象: c14. 参数。如果传
     入 `codeset'，那么在 *note lgettext(): 318b. 和 *note lngettext():
     318c. 方法中，对翻译后的字符串进行编码的字符集将被改变。

     如果找到多个文件，后找到的文件将用作先前文件的替补。为了设置替补，
     将使用 *note copy.copy(): 4d1. 从缓存中克隆每个 translation 对象。
     实际的实例数据仍在缓存中共享。

     如果 ‘.mo’ 文件未找到，且 `fallback' 为 false（默认值），则本函数引
     发 *note OSError: 304. 异常，如果 `fallback' 为 true，则返回一个
     *note NullTranslations: 318d. 实例。

     3.3 版更變: *note IOError: a73. 代替 *note OSError: 304. 被引发。

     Deprecated since version 3.8, will be removed in version 3.10:
     `codeset' 参数。

 -- 函式: gettext.install (domain, localedir=None, codeset=None,
          names=None)

     根据传入 *note translation(): 3bd. 函数的 `domain'、`localedir' 和
     `codeset'，在 Python 内建命名空间中安装 ‘_()’ 函数。

     `names' 参数的信息请参阅 translation 对象的 *note install(): 318e.
     方法的描述。

     如下所示，通常将字符串包括在 ‘_()’ 函数的调用中，以标记应用程序中待
     翻译的字符串，就像这样:

          print(_('This string will be translated.'))

     为了方便，一般将 ‘_()’ 函数安装在 Python 内建命名空间中，以便在应用
     程序的所有模块中轻松访问它。

     Deprecated since version 3.8, will be removed in version 3.10:
     `codeset' 参数。

* Menu:

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

   ---------- Footnotes ----------

   (1) (2) 参阅上方 *note bindtextdomain(): 317f. 的脚注。


File: python.info,  Node: NullTranslations 类,  Next: GNUTranslations 类,  Up: 基于类的 API

5.23.1.3 ‘NullTranslations’ 类
..............................

translation 类实际实现的是，将原始源文件消息字符串转换为已翻译的消息字符
串。所有 translation 类使用的基类为 *note NullTranslations: 318d.，它提
供了基本的接口，可用于编写自己定制的 translation 类。以下是
‘NullTranslations’ 的方法：

 -- 類別: gettext.NullTranslations (fp=None)

     接受一个可选参数 *note 文件对象: c14. `fp'，该参数会被基类忽略。初
     始化由派生类设置的 "protected" （受保护的）实例变量 `_info' 和
     `_charset'，与 `_fallback' 类似，但它是通过 *note add_fallback():
     3190. 来设置的。如果 `fp' 不为 ‘None’，就会调用 ‘self._parse(fp)’。

      -- 成員函式: _parse (fp)

          在基类中没有操作，本方法接受文件对象 `fp'，从该文件读取数据，
          用来初始化消息编目。如果你手头的消息编目文件的格式不受支持，则
          应重写本方法来解析你的格式。

      -- 成員函式: add_fallback (fallback)

          添加 `fallback' 为当前 translation 对象的替补对象。如果
          translation 对象无法为指定消息提供翻译，则应向替补查询。

      -- 成員函式: gettext (message)

          如果设置了替补，则转发 ‘gettext()’ 给替补。否则返回 `message'。
          在派生类中被重写。

      -- 成員函式: ngettext (singular, plural, n)

          如果设置了替补，则转发 ‘ngettext()’ 给替补。否则，`n' 为 1 时
          返回 `singular'，为其他时返回 `plural'。在派生类中被重写。

      -- 成員函式: pgettext (context, message)

          如果设置了替补，则转发 *note pgettext(): 300. 给替补。否则返回
          已翻译的消息。在派生类中被重写。

          3.8 版新加入.

      -- 成員函式: npgettext (context, singular, plural, n)

          如果设置了替补，则转发 *note npgettext(): 3186. 给替补。否则返
          回已翻译的消息。在派生类中被重写。

          3.8 版新加入.

      -- 成員函式: lgettext (message)

      -- 成員函式: lngettext (singular, plural, n)

          与 *note gettext(): 3192. 和 *note ngettext(): 3193. 等效，但
          是如果没有用 *note set_output_charset(): 3bc. 显式设置编码，则
          返回的翻译将以首选系统编码来编码字节串。在派生类中被重写。

               警告: 应避免在 Python 3 中使用这些方法。请参阅 *note
               lgettext(): 3b6. 函数的警告。

          Deprecated since version 3.8, will be removed in version 3.10.

      -- 成員函式: info ()

          返回 "protected"（受保护的） ‘_info’ 变量，它是一个字典，包含
          在消息编目文件中找到的元数据。

      -- 成員函式: charset ()

          返回消息编目文件的编码。

      -- 成員函式: output_charset ()

          返回由 *note lgettext(): 318b. 和 *note lngettext(): 318c. 翻
          译出的消息的编码。

          Deprecated since version 3.8, will be removed in version 3.10.

      -- 成員函式: set_output_charset (charset)

          更改翻译出的消息的编码。

          Deprecated since version 3.8, will be removed in version 3.10.

      -- 成員函式: install (names=None)

          本方法将 *note gettext(): 3192. 安装至内建命名空间，并绑定为
          ‘_’。

          如果传入 `names' 参数，该参数必须是一个序列，包含除 ‘_()’ 外其
          他要安装在内建命名空间中的函数的名称。支持的名称有
          ‘'gettext'’, ‘'ngettext'’, ‘'pgettext'’, ‘'npgettext'’,
          ‘'lgettext'’ 和 ‘'lngettext'’。

          注意，这仅仅是使 ‘_()’ 函数在应用程序中生效的一种方法，尽管也
          是最方便的方法。由于它会影响整个应用程序全局，特别是内建命名空
          间，因此已经本地化的模块不应该安装 ‘_()’，而是应该用下列代码使
          ‘_()’ 在各自模块中生效:

               import gettext
               t = gettext.translation('mymodule', ...)
               _ = t.gettext

          这只将 ‘_()’ 放在其模块的全局命名空间中，所以只影响其模块内的
          调用。

          3.8 版更變: 添加了 ‘'pgettext'’ 和 ‘'npgettext'’。


File: python.info,  Node: GNUTranslations 类,  Next: Solaris 消息编目支持,  Prev: NullTranslations 类,  Up: 基于类的 API

5.23.1.4 ‘GNUTranslations’ 类
.............................

*note gettext: 87. 模块提供了一个派生自 *note NullTranslations: 318d. 的
其他类：*note GNUTranslations: 3189.。该类重写了 ‘_parse()’，同时能以大
端序和小端序格式读取 GNU ‘gettext’ 格式的 ‘.mo’ 文件。

*note GNUTranslations: 3189. 从翻译编目中解析出可选的元数据。GNU
‘gettext’ 约定，将元数据包括在空字符串的翻译中。该元数据采用 RFC 822(1)
样式的 ‘key: value’ 键值对，且应该包含 ‘Project-Id-Version’ 键。如果找到
‘Content-Type’ 键，那么将用 ‘charset’ 属性去初始化 "protected"（受保护的
） ‘_charset’ 实例变量，而该变量在未找到键的情况下默认为 ‘None’。如果指
定了字符编码，那么从编目中读取的所有消息 ID 和消息字符串都将使用此编码转
换为 Unicode，若未指定编码，则假定编码为 ASCII。

由于消息 ID 也是作为 Unicode 字符串读取的，因此所有 ‘*gettext()’ 方法都
假定消息 ID 为 Unicode 字符串，而不是字节串。

整个键/值对集合将被放入一个字典，并设置为 "protected"（受保护的）
‘_info’ 实例变量。

如果 ‘.mo’ 文件的魔法值 (magic number) 无效，或遇到意外的主版本号，或在
读取文件时发生其他问题，则实例化 *note GNUTranslations: 3189. 类会引发
*note OSError: 304.。

 -- 類別: gettext.GNUTranslations

     下列方法是根据基类实现重写的：

      -- 成員函式: gettext (message)

          在编目中查找 `message' ID，并以 Unicode 字符串形式返回相应的消
          息字符串。如果在编目中没有 `message' ID 条目，且配置了替补，则
          查找请求将被转发到替补的 *note gettext(): 3192. 方法。否则，返
          回 `message' ID。

      -- 成員函式: ngettext (singular, plural, n)

          查找消息 ID 的复数形式。`singular' 用作消息 ID，用于在编目中查
          找，同时 `n' 用于确定使用哪种复数形式。返回的消息字符串是
          Unicode 字符串。

          如果在编目中没有找到消息 ID，且配置了替补，则查找请求将被转发
          到替补的 *note ngettext(): 3193. 方法。否则，当 `n' 为 1 时返
          回 `singular'，其他情况返回 `plural'。

          例如：

               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}

      -- 成員函式: pgettext (context, message)

          在编目中查找 `context' 和 `message' ID，并以 Unicode 字符串形
          式返回相应的消息字符串。如果在编目中没有 `message' ID 和
          `context' 条目，且配置了替补，则查找请求将被转发到替补的 *note
          pgettext(): 300. 方法。否则，返回 `message' ID。

          3.8 版新加入.

      -- 成員函式: npgettext (context, singular, plural, n)

          查找消息 ID 的复数形式。`singular' 用作消息 ID，用于在编目中查
          找，同时 `n' 用于确定使用哪种复数形式。

          如果在编目中没有找到 `context' 对应的消息 ID，且配置了替补，则
          查找请求将被转发到替补的 *note npgettext(): 3186. 方法。否则，
          当 `n' 为 1 时返回 `singular'，其他情况返回 `plural'。

          3.8 版新加入.

      -- 成員函式: lgettext (message)

      -- 成員函式: lngettext (singular, plural, n)

          与 *note gettext(): 3199. 和 *note ngettext(): 319a. 等效，但
          是如果没有用 *note set_output_charset(): 3bc. 显式设置编码，则
          返回的翻译将以首选系统编码来编码字节串。

               警告: 应避免在 Python 3 中使用这些方法。请参阅 *note
               lgettext(): 3b6. 函数的警告。

          Deprecated since version 3.8, will be removed in version 3.10.

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc822.html


File: python.info,  Node: Solaris 消息编目支持,  Next: 编目构造器,  Prev: GNUTranslations 类,  Up: 基于类的 API

5.23.1.5 Solaris 消息编目支持
.............................

Solaris 操作系统定义了自己的二进制 ‘.mo’ 文件格式，但由于找不到该格式的
文档，因此目前不支持该格式。


File: python.info,  Node: 编目构造器,  Prev: Solaris 消息编目支持,  Up: 基于类的 API

5.23.1.6 编目构造器
...................

GNOME 用的 *note gettext: 87. 模块是 James Henstridge 写的版本，但该版本
的 API 略有不同。它文档中的用法是:

     import gettext
     cat = gettext.Catalog(domain, localedir)
     _ = cat.gettext
     print(_('hello world'))

为了与本模块的旧版本兼容，‘Catalog()’ 函数是上述 *note translation():
3bd. 函数的别名。

本模块与 Henstridge 的模块有一个区别：他的编目对象支持通过映射 API 进行
访问，但是该特性似乎从未使用过，因此目前不支持该特性。


File: python.info,  Node: 国际化 I18N 你的程序和模块,  Next: 致谢<9>,  Prev: 基于类的 API,  Up: gettext --- 多语种国际化服务

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

国际化 (I18N) 是指使程序可切换多种语言的操作。本地化 (L10N) 是指程序的适
配能力，一旦程序被国际化，就能适配当地的语言和文化习惯。为了向 Python 程
序提供不同语言的消息，需要执行以下步骤：

  1. 准备程序或模块，将可翻译的字符串特别标记起来

  2. 在已标记的文件上运行一套工具，用来生成原始消息编目

  3. 创建消息编目的不同语言的翻译

  4. 使用 *note gettext: 87. 模块，以便正确翻译消息字符串

为了准备代码以达成 I18N，需要巡视文件中的所有字符串。所有要翻译的字符串
都应包括在 ‘_('...')’ 内，以此打上标记——也就是调用 ‘_()’ 函数。例如:

     filename = 'mylog.txt'
     message = _('writing a log message')
     with open(filename, 'w') as fp:
         fp.write(message)

在这个例子中，字符串 ‘'writing a log message'’ 被标记为待翻译，而字符串
‘'mylog.txt'’ 和 ‘'w'’ 没有被标记。

有一些工具可以将待翻译的字符串提取出来。原版的 GNU ‘gettext’ 仅支持 C 或
C++ 源代码，但其扩展版 ‘xgettext’ 可以扫描多种语言的代码（包括 Python）
，来找出标记为可翻译的字符串。Babel(1) 是一个 Python 国际化库，其中包含
一个 ‘pybabel’ 脚本，用于提取并编译消息编目。François Pinard 写的称为
‘xpot’ 的程序也能完成类似的工作，可从他的 po-utils 软件包(2) 中获取。

（Python 还包括了这些程序的纯 Python 版本，称为 ‘pygettext.py’ 和
‘msgfmt.py’，某些 Python 发行版已经安装了它们。‘pygettext.py’ 类似于
‘xgettext’，但只能理解 Python 源代码，无法处理诸如 C 或 C++ 的其他编程语
言。‘pygettext.py’ 支持的命令行界面类似于 ‘xgettext’，查看其详细用法请运
行 ‘pygettext.py --help’。‘msgfmt.py’ 与 GNU ‘msgfmt’ 是二进制兼容的。有
了这两个程序，可以不需要 GNU ‘gettext’ 包来国际化 Python 应用程序。）

‘xgettext’、‘pygettext’ 或类似工具生成的 ‘.po’ 文件就是消息编目。它们是
结构化的人类可读文件，包含源代码中所有被标记的字符串，以及这些字符串的翻
译的占位符。

然后把这些 ‘.po’ 文件的副本交给各个人工译者，他们为所支持的每种自然语言
编写翻译。译者以 ‘<语言名称>.po’ 文件的形式发送回翻译完的某个语言的版本
，将该文件用 ‘msgfmt’ 程序编译为机器可读的 ‘.mo’ 二进制编目文件。*note
gettext: 87. 模块使用 ‘.mo’ 文件在运行时进行实际的翻译处理。

如何在代码中使用 *note gettext: 87. 模块取决于国际化单个模块还是整个应用
程序。接下来的两节将讨论每种情况。

* Menu:

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

   ---------- Footnotes ----------

   (1) http://babel.pocoo.org/

   (2) https://github.com/pinard/po-utils


File: python.info,  Node: 本地化你的模块,  Next: 本地化你的应用程序,  Up: 国际化 I18N 你的程序和模块

5.23.1.8 本地化你的模块
.......................

如果要本地化模块，则切忌进行全局性的更改，如更改内建命名空间。不应使用
GNU ‘gettext’ API，而应使用基于类的 API。

假设你的模块叫做 "spam"，并且该模块的各种自然语言翻译 ‘.mo’ 文件存放于
‘/usr/share/locale’，为 GNU ‘gettext’ 格式。以下内容应放在模块顶部:

     import gettext
     t = gettext.translation('spam', '/usr/share/locale')
     _ = t.gettext


File: python.info,  Node: 本地化你的应用程序,  Next: 即时更改语言,  Prev: 本地化你的模块,  Up: 国际化 I18N 你的程序和模块

5.23.1.9 本地化你的应用程序
...........................

如果正在本地化应用程序，可以将 ‘_()’ 函数全局安装到内建命名空间中，通常
在应用程序的主文件中安装。这将使某个应用程序的所有文件都能使用
‘_('...')’，而不必在每个文件中显式安装它。

最简单的情况，就只需将以下代码添加到应用程序的主程序文件中:

     import gettext
     gettext.install('myapplication')

如果需要设置语言环境目录，可以将其传递给 *note install(): 3be. 函数:

     import gettext
     gettext.install('myapplication', '/usr/share/locale')


File: python.info,  Node: 即时更改语言,  Next: 延迟翻译,  Prev: 本地化你的应用程序,  Up: 国际化 I18N 你的程序和模块

5.23.1.10 即时更改语言
......................

如果程序需要同时支持多种语言，则可能需要创建多个翻译实例，然后在它们之间
进行显式切换，如下所示:

     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()


File: python.info,  Node: 延迟翻译,  Prev: 即时更改语言,  Up: 国际化 I18N 你的程序和模块

5.23.1.11 延迟翻译
..................

在大多数代码中，字符串会在编写位置进行翻译。但偶尔需要将字符串标记为待翻
译，实际翻译却推迟到后面。一个典型的例子是:

     animals = ['mollusk',
                'albatross',
                'rat',
                'penguin',
                'python', ]
     # ...
     for a in animals:
         print(a)

此处希望将 ‘animals’ 列表中的字符串标记为可翻译，但不希望在打印之前对它
们进行翻译。

这是处理该情况的一种方式:

     def _(message): return message

     animals = [_('mollusk'),
                _('albatross'),
                _('rat'),
                _('penguin'),
                _('python'), ]

     del _

     # ...
     for a in animals:
         print(_(a))

该方法之所以可行，是因为 ‘_()’ 的虚定义只是简单地返回了原本的字符串。并
且该虚定义将临时覆盖内建命名空间中 ‘_()’ 的定义（直到 *note del: 13a2. 命
令）。即使先前在本地命名空间中已经有了 ‘_()’ 的定义也请注意。

注意，第二次使用 ‘_()’ 不会认为 "a" 可以传递给 ‘gettext’ 程序去翻译，因
为该参数不是字符串文字。

解决该问题的另一种方法是下面这个例子:

     def N_(message): return message

     animals = [N_('mollusk'),
                N_('albatross'),
                N_('rat'),
                N_('penguin'),
                N_('python'), ]

     # ...
     for a in animals:
         print(_(a))

这种情况下标记可翻译的字符串使用的是函数 ‘N_()’，该函数不会与 ‘_()’ 的任
何定义冲突。但是，需要教会消息提取程序去寻找用 ‘N_()’ 标记的可翻译字符串
。‘xgettext’, ‘pygettext’, ‘pybabel extract’ 和 ‘xpot’ 都支持此功能，使
用 ‘-k’ 命令行开关即可。这里选择 ‘N_()’ 为名称完全是任意的，它也能轻易改
为 ‘MarkThisStringForTranslation()’。


File: python.info,  Node: 致谢<9>,  Prev: 国际化 I18N 你的程序和模块,  Up: gettext --- 多语种国际化服务

5.23.1.12 致谢
..............

以下人员为创建此模块贡献了代码、反馈、设计建议、早期实现和宝贵的经验：

   * Peter Funk

   * James Henstridge

   * Juan David Ibáñez Palomar

   * Marc-André Lemburg

   * Martin von Löwis

   * François Pinard

   * Barry Warsaw

   * Gustavo Niemeyer

註解
....


File: python.info,  Node: locale --- 国际化服务,  Prev: gettext --- 多语种国际化服务,  Up: 國際化

5.23.2 ‘locale’ — 国际化服务
----------------------------

`源代码：' Lib/locale.py(1)

__________________________________________________________________

*note locale: a9. 模块开通了 POSIX 本地化数据库和功能的访问。POSIX 本地
化机制让程序员能够为应用程序处理某些本地化的问题，而不需要去了解运行软件
的每个国家的全部文化特点。

*note locale: a9. 模块是在 ‘_locale’ 模块的基础上实现的，而 _locale 则又
用到了 ANSI C 语言实现的本地化功能。

*note locale: a9. 模块定义了以下异常和函数：

 -- 例外: locale.Error

     当传给 *note setlocale(): 2166. 的 locale 无法识别时，会触发异常。

 -- 函式: locale.setlocale (category, locale=None)

     如果给定了 `locale' 而不是 ‘None’，*note setlocale(): 2166. 会修改
     `category' 的 locale 设置。可用的类别会在下面的数据描述中列出。
     `locale' 可以是一个字符串，也可以是两个字符串（语言代码和编码）组成
     的可迭代对象。若为可迭代对象，则会用地区别名引擎转换为一个地区名称
     。若为空字符串则指明采用用户的默认设置。如果 locale 设置修改失败，
     会触发 *note Error: 31a9. 异常。如果成功则返回新的 locale 设置。

     如果省略 `locale' 或为 ‘None’，将返回 `category' 但当前设置。

     *note setlocale(): 2166. 在大多数系统上都不是线程安全的。应用程序通
     常会如下调用：

          import locale
          locale.setlocale(locale.LC_ALL, '')

     这会把所有类别的 locale 都设为用户的默认设置（通常在 ‘LANG’ 环境变
     量中指定）。如果后续 locale 没有改动，则使用多线程应该不会产生问题
     。

 -- 函式: locale.localeconv ()

     以字典的形式返回本地约定的数据库。此字典具有以下字符串作为键：

     类别                       键                                        含义
                                                                          
     ----------------------------------------------------------------------------------------------------------
                                                                          
     *note LC_NUMERIC: 31aa.    ‘'decimal_point'’                         小数点字符。
                                                                          
                                                                          
                                ‘'grouping'’                              数字列表，指定 ‘'thousands_sep'’ 应
                                                                          该出现的位置。 如果列表以
                                                                          *note CHAR_MAX: 31ab. 结束，则不会
                                                                          作分组。如果列表以 ‘0’ 结束，则重
                                                                          复使用最后的分组大小。
                                                                          
                                                                          
                                ‘'thousands_sep'’                         组之间使用的字符。
                                                                          
                                                                          
     *note LC_MONETARY: 31ac.   ‘'int_curr_symbol'’                       国际货币符号。
                                                                          
                                                                          
                                ‘'currency_symbol'’                       当地货币符号。
                                                                          
                                                                          
                                ‘'p_cs_precedes/n_cs_precedes'’           货币符号是否在值之前（对于正值或负
                                                                          值）。
                                                                          
                                                                          
                                ‘'p_sep_by_space/n_sep_by_space'’         货币符号是否通过空格与值分隔（对于
                                                                          正值或负值）。
                                                                          
                                                                          
                                ‘'mon_decimal_point'’                     用于货币金额的小数点。
                                                                          
                                                                          
                                ‘'frac_digits'’                           货币值的本地格式中使用的小数位数。
                                                                          
                                                                          
                                ‘'int_frac_digits'’                       货币价值的国际格式中使用的小数位数
                                                                          。
                                                                          
                                                                          
                                ‘'mon_thousands_sep'’                     用于货币值的组分隔符。
                                                                          
                                                                          
                                ‘'mon_grouping'’                          相当于 ‘'grouping'’ ，用于货币价值
                                                                          。
                                                                          
                                                                          
                                ‘'positive_sign'’                         用于标注正货币价值的符号。
                                                                          
                                                                          
                                ‘'negative_sign'’                         用于注释负货币价值的符号。
                                                                          
                                                                          
                                ‘'p_sign_posn/n_sign_posn'’               符号的位置（对于正值或负值），见下
                                                                          文。
                                                                          

     可以将所有数值设置为 *note CHAR_MAX: 31ab. ，以指示此语言环境中未指
     定任何值。

     下面给出了 ‘'p_sign_posn'’ 和 ‘'n_sign_posn'’ 的可能值。

     值                 解释
                        
     -----------------------------------------------------------------
                        
     ‘0’                被括号括起来的货币和金额。
                        
                        
     ‘1’                该标志应位于值和货币符号之前。
                        
                        
     ‘2’                该标志应位于值和货币符号之后。
                        
                        
     ‘3’                标志应该紧跟在值之前。
                        
                        
     ‘4’                标志应该紧跟值项。
                        
                        
     ‘CHAR_MAX’         此语言环境中未指定任何内容。
                        

     该函数将 ‘LC_CTYPE’ 地区设为 ‘LC_NUMERIC’ 地区，若地区不同且数字或
     货币字符为非 ASCII，则设置为 ‘LC_MONETARY’ 地区。这个临时的改变会影
     响到其他线程。

     3.7 版更變: 现在在某些情况下，该函数会将 ‘LC_CTYPE’ 地区设为
     ‘LC_NUMERIC’ 地区。

 -- 函式: locale.nl_langinfo (option)

     以字符串形式返回一些地区相关的信息。本函数并非在所有系统都可用，而
     且可用的 option 在不同平台上也可能不同。可填的参数值为数值，在
     locale 模块中提供了对应的符号常量。

     *note nl_langinfo(): 31ad. 函数可接受以下值。大部分含义都取自 GNU C
     库。

      -- Data: locale.CODESET

          获取一个字符串，代表所选地区采用的字符编码名称。

      -- Data: locale.D_T_FMT

          获取一个字符串，可用作 *note time.strftime(): c37. 的格式串，
          以便以地区特定格式表示日期和时间。

      -- Data: locale.D_FMT

          获取一个字符串，可用作 *note time.strftime(): c37. 的格式串，
          以便以地区特定格式表示日期。

      -- Data: locale.T_FMT

          获取一个字符串，可用作 *note time.strftime(): c37. 的格式串，
          以便以地区特定格式表示时间。

      -- Data: locale.T_FMT_AMPM

          获取一个字符串，可用作 *note time.strftime(): c37. 的格式串，
          以便以 am/pm 的格式表示时间。

      -- Data: DAY_1 ... DAY_7

          获取一周中第 n 天的名称。

               備註: 这里遵循美国惯例，即 ‘DAY_1’ 是星期天，而不是国际惯
               例（ISO 8601），即星期一是一周的第一天。

      -- Data: ABDAY_1 ... ABDAY_7

          获取一周中第 n 天的缩写名称。

      -- Data: MON_1 ... MON_12

          获取第 n 个月的名称。

      -- Data: ABMON_1 ... ABMON_12

          获取第 n 个月的缩写名称。

      -- Data: locale.RADIXCHAR

          获取小数点字符（小数点、小数逗号等）。

      -- Data: locale.THOUSEP

          获取千位数（三位数一组）的分隔符。

      -- Data: locale.YESEXPR

          获取一个可供 regex 函数使用的正则表达式，用于识别需要回答是或
          否的问题的肯定回答。

               備註: 该表达式的语法适用于 C 库的 ‘regex()’ 函数，可能与
               *note re: dd. 中的语法不一样。

      -- Data: locale.NOEXPR

          获取一个可供 regex(3) 函数使用的正则表达式，用于识别需要回答是
          或否的问题的否定回答。

      -- Data: locale.CRNCYSTR

          获取货币符号，如果符号应位于数字之前，则在其前面加上“-”；如果
          符号应位于数字之后，则前面加“+”；如果符号应取代小数点字符，则
          前面加“.”。

      -- Data: locale.ERA

          获取一个字符串，代表当前地区使用的纪元。

          大多数地区都没有定义该值。定义了该值的一个案例日本。日本传统的
          日期表示方法中，包含了当时天皇统治朝代的名称。

          通常没有必要直接使用该值。在格式串中指定 ‘E’ 符号，会让 *note
          time.strftime(): c37. 函数启用此信息。返回字符串的格式并没有定
          义，因此不得假定各个系统都能理解。

      -- Data: locale.ERA_D_T_FMT

          获取一个字符串，可用作 *note time.strftime(): c37. 的格式串，
          以便以地区特定格式表示带纪元的日期和时间。

      -- Data: locale.ERA_D_FMT

          获取一个字符串，可用作 *note time.strftime(): c37. 的格式串，
          以便以地区特定格式表示带纪元的日期。

      -- Data: locale.ERA_T_FMT

          获取一个字符串，可用作 *note time.strftime(): c37. 的格式串，
          以便以地区特定格式表示带纪元的时间。

      -- Data: locale.ALT_DIGITS

          获取 0 到 99 的表示法，最多不超过 100 个值。

 -- 函式: locale.getdefaultlocale ([envvars])

     尝试确定默认的地区设置，并以 ‘(language code, encoding)’ 元组的形式
     返回。

     根据 POSIX 的规范，未调用 ‘setlocale(LC_ALL, '')’ 的程序采用可移植
     的 ‘'C'’ 区域设置运行。 调用 ‘setlocale(LC_ALL, '')’ 则可采用
     ‘LANG’ 变量定义的默认区域。 由于不想干扰当前的区域设置，因此就以上
     述方式进行了模拟。

     为了维持与其他平台的兼容性，不仅需要检测 ‘LANG’ 变量，还需要检测
     envvars 参数给出的变量列表。首先发现的定义将被采用。 `envvars' 默认
     为 GNU gettext 采用的搜索路径；必须包含 ‘'LANG'’ 变量。 GNU gettext
     的搜索路径依次包含了 ‘'LC_ALL'’、‘'LC_CTYPE'’、‘'LANG'’ 和
     ‘'LANGUAGE'’。

     除了 ‘'C'’ 之外，语言代码对应 RFC 1766(2) 标准。如果 `语言代码' 和
     `编码' 不能确定，可为 ‘None’。

 -- 函式: locale.getlocale (category=LC_CTYPE)

     以列表的形式返回指定地区类别的当前设置，结果包括 `语言代码' 、`编码
     '。`category' 可以是 ‘LC_*’ 之一， *note LC_ALL: 31bd. 除外。默认为
     *note LC_CTYPE: 31be.。

     除了 ‘'C'’ 之外，语言代码对应 RFC 1766(3) 标准。如果 `语言代码' 和
     `编码' 不能确定，可为 ‘None’。

 -- 函式: 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.

     某些系统必须调用 *note setlocale(): 2166. 才能获取用户偏好，所以本
     函数不是线程安全的。如果不需要或不希望调用 setlocale，
     `do_setlocale' 应设为 ‘False’。

     On Android or in the UTF-8 mode (*note -X: 290. ‘utf8’ option),
     always return ‘'UTF-8'’, the locale and the `do_setlocale' argument
     are ignored.

     3.7 版更變: The function now always returns ‘UTF-8’ on Android or
     if the UTF-8 mode is enabled.

 -- 函式: locale.normalize (localename)

     为给定的区域名称返回标准代码。返回的区域代码已经格式化，可供 *note
     setlocale(): 2166. 使用。 如果标准化操作失败，则返回原名称。

     如果给出的编码无法识别，则本函数默认采用区域代码的默认编码，这正类
     似于 *note setlocale(): 2166.。

 -- 函式: locale.resetlocale (category=LC_ALL)

     将 `category' 的区域设为默认值。

     默认设置通过调用 *note getdefaultlocale(): 1492. 确定。`category' 默
     认为 *note LC_ALL: 31bd.。

 -- 函式: locale.strcoll (string1, string2)

     根据当前的 *note LC_COLLATE: 31c2. 设置，对两个字符串进行比较。与其
     他比较函数一样，根据 `string1' 位于 `string2' 之前、之后或是相同，
     返回负值、、正值或者 ‘0’。

 -- 函式: locale.strxfrm (string)

     将字符串转换为可用于本地化比较的字符串。例如 ‘strxfrm(s1) <
     strxfrm(s2)’ 相当于 ‘strcoll(s1, s2) < 0’。在重复比较同一个字符串时
     ，可能会用到本函数，比如整理字符串列表时。

 -- 函式: locale.format_string (format, val, grouping=False,
          monetary=False)

     根据当前的 *note LC_NUMERIC: 31aa. 设置，对数字 `val' 进行格式化。
     格式将遵循 ‘%’ 运算符的约定。浮点值的小数点会按需修改。若
     `grouping' 为 True，则还会考虑分组。

     若 `monetary' 为 True，则会用到货币千位分隔符和分组字符串。

     格式化符的处理类似 ‘format % val’ ，但会考虑到当前的区域设置。

     3.7 版更變: 增加了关键字参数 `monetary' 。

 -- 函式: locale.format (format, val, grouping=False, monetary=False)

     请注意，本函数的工作原理与 *note format_string(): 4aa. 类似，但只对
     ‘%char’ 格式符起作用。 比如 ‘'%f'’ 和 ‘'%.0f'’ 都是有效的格式符，但
     ‘'%f KiB'’ 则不是。

     若想用到全部的格式化串，请采用 *note format_string(): 4aa.。

     3.7 版後已棄用: 请改用 *note format_string(): 4aa. 。

 -- 函式: locale.currency (val, symbol=True, grouping=False,
          international=False)

     根据当前的 *note LC_MONETARY: 31ac. 设置，对数字 `val' 进行格式化。

     如果 `symbol' 为 True（默认值），则返回的字符串将包含货币符号。如果
     `grouping' 为 True（非默认值），则会进行分组。如果 `international'
     为 True（非默认值），将采用国际货币符号。

     请注意，本函数对区域 “C” 无效，所以必须先通过 *note setlocale():
     2166. 设置一个区域。

 -- 函式: locale.str (float)

     对浮点数进行格式化，格式要求与内置函数 ‘str(float)’ 相同，但会考虑
     小数点。

 -- 函式: locale.delocalize (string)

     根据 *note LC_NUMERIC: 31aa. 的设置，将字符串转换为格式化后的数字字
     符串。

     3.5 版新加入.

 -- 函式: locale.atof (string)

     根据 *note LC_NUMERIC: 31aa. 的设置，将字符串转换为浮点数。

 -- 函式: locale.atoi (string)

     按照 *note LC_NUMERIC: 31aa. 的约定，将字符串转换为整数。

 -- Data: locale.LC_CTYPE

     字符型函数的区域类别。根据该类别的设置，模块 *note string: f6. 中处
     理大小写的函数会改变操作方式。

 -- Data: locale.LC_COLLATE

     字符串排序会用到的区域类别。 将会影响 *note locale: a9. 模块的
     *note strcoll(): 31c1. 和 *note strxfrm(): 31c3. 函数。

 -- Data: locale.LC_TIME

     格式化时间时会用到的区域类别。 *note time.strftime(): c37. 函数会参
     考这些约定。

 -- Data: locale.LC_MONETARY

     格式化货币值时会用到的区域类别。可用值可由 *note localeconv(): 584.
     函数获取。

 -- Data: locale.LC_MESSAGES

     显示消息时用到的区域类别。目前 Python 不支持应用定制的本地化消息。
     由操作系统显示的消息，比如由 *note os.strerror(): 2062. 返回的消息
     可能会受到该类别的影响。

 -- Data: locale.LC_NUMERIC

     格式化数字时用到的区域类别。 *note locale: a9. 模块的 *note
     format(): 569. 、 *note atoi(): 31c7. 、 *note atof(): 31c6. 和
     *note str(): 31c5. 函数会受到该类别的影响。其他所有数字格式化操作不
     受影响。

 -- Data: locale.LC_ALL

     混合所有的区域设置。如果在区域改动时使用该标志，将尝试设置所有类别
     的区域参数。只要有任何一个类别设置失败，就不会修改任何类别。在使用
     此标志获取区域设置时，会返回一个代表所有类别设置的字符串。之后可用
     此字符串恢复设置。

 -- Data: locale.CHAR_MAX

     一个符号常量， *note localeconv(): 584. 返回多个值时将会用到。

示例:

     >>> 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, '')   # use user's preferred locale
     >>> locale.setlocale(locale.LC_ALL, 'C')  # use default (C) locale
     >>> locale.setlocale(locale.LC_ALL, loc)  # restore saved locale

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/locale.py

   (2) https://tools.ietf.org/html/rfc1766.html

   (3) https://tools.ietf.org/html/rfc1766.html


File: python.info,  Node: 背景、细节、提示、技巧和注意事项,  Next: 针对扩展程序编写人员和嵌入Python 运行的程序,  Up: locale --- 国际化服务

5.23.2.1 背景、细节、提示、技巧和注意事项
.........................................

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.

当程序第一次启动时，无论用户偏好定义成什么，区域值都是 ‘C’。不过有一个例
外，就是在启动时修改 *note LC_CTYPE: 31be. 类别，设置当前区域编码为用户
偏好编码。程序必须调用 ‘setlocale(LC_ALL, '')’ 明确表示用户偏好区域将设
为其他类别。

若要从库程序中调用 *note setlocale(): 2166. ，通常这不是个好主意，因为副
作用是会影响整个程序。保存和恢复区域设置也几乎一样糟糕：不仅代价高昂，而
且会影响到恢复之前运行的其他线程。

如果是要编写通用模块，需要有一种不受区域设置影响的操作方式（比如某些用到
*note time.strftime(): c37. 的格式），将不得不寻找一种不用标准库的方案。
更好的办法是说服自己，可以采纳区域设置。只有在万不得已的情况下，才能用文
档标注出模块与非 ‘C’ 区域设置不兼容。

根据区域设置进行数字运算的唯一方法，就是采用本模块定义的函数：*note
atof(): 31c6. 、 *note atoi(): 31c7. 、 *note format(): 569. 、 *note
str(): 31c5.。

无法根据区域设置进行大小写转换和字符分类。对于（Unicode）文本字符串来说
，这些操作都是根据字符值进行的；而对于字节符串来说，转换和分类则是根据字
节的 ASCII 值进行的，高位被置位的字节（即非 ASCII 字节）永远不会被转换或
被视作字母或空白符之类。


File: python.info,  Node: 针对扩展程序编写人员和嵌入Python 运行的程序,  Next: 访问信息目录,  Prev: 背景、细节、提示、技巧和注意事项,  Up: locale --- 国际化服务

5.23.2.2 针对扩展程序编写人员和嵌入Python 运行的程序
....................................................

除了要查询当前区域，扩展模块不应去调用 *note setlocale(): 2166.。但由于
返回值只能用于恢复设置，所以也没什么用（也许只能用于确认是否为 ‘C’）。

当 Python 代码利用 *note locale: a9. 模块修改区域设置时，也会影响到嵌入
Python 运行的应用程序。如果嵌入运行的程序不希望发生这种情况，则应从
‘config.c’ 文件的内置模块表中删除 ‘_locale’ 扩展模块（所有操作均是由它完
成的），并确保 ‘_locale’ 模块不能成为一个共享库。


File: python.info,  Node: 访问信息目录,  Prev: 针对扩展程序编写人员和嵌入Python 运行的程序,  Up: locale --- 国际化服务

5.23.2.3 访问信息目录
.....................

 -- 函式: locale.gettext (msg)

 -- 函式: locale.dgettext (domain, msg)

 -- 函式: locale.dcgettext (domain, msg, category)

 -- 函式: locale.textdomain (domain)

 -- 函式: locale.bindtextdomain (domain, dir)

在提供 gettext 接口的系统中，locale 模块暴露出了 C 库的接口。它由
‘gettext()’ 、‘dgettext()’ 、‘dcgettext()’ 、 ‘textdomain()’ 、
‘bindtextdomain()’ 和 ‘bind_textdomain_codeset()’ 等函数组成。 他们与
*note gettext: 87. 模块中的同名函数类似，但采用了 C 库二进制格式的消息目
录，以及 C 库的搜索算法来查找消息目录。

Python 应用程序通常不需要调用这些函数，而应改用 *note gettext: 87.。这条
规则的一个已知例外，是与附加 C 库链接的应用程序，他们在内部调用了
‘gettext()’ 或 ‘dcgettext()’。对于这些应用程序，可能有必要绑定文本域，以
便库可以准确找到他们的信息目录。


File: python.info,  Node: 程式框架,  Next: 以 Tk 打造 GUI,  Prev: 國際化,  Up: Python 標準函式庫 Standard Library

5.24 程式框架
=============

本章中描述的模块是很大程度上决定程序结构的框架。 目前，这里描述的模块都
面向编写命令行接口。

本章描述的完整模块列表如下：

* Menu:

* turtle: turtle --- 龜圖學. 龜圖學
* cmd: cmd --- 支持面向行的命令解释器. 支持面向行的命令解释器
* shlex —— 简单的词义分析::


File: python.info,  Node: turtle --- 龜圖學,  Next: cmd --- 支持面向行的命令解释器,  Up: 程式框架

5.24.1 ‘turtle’ — 龜圖學
------------------------

`源码：' Lib/turtle.py(1)

__________________________________________________________________

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/turtle.py


File: python.info,  Node: 介紹,  Next: 可用的 Turtle 和 Screen 方法概览,  Up: turtle --- 龜圖學

5.24.1.1 介紹
.............

海龟绘图很适合用来引导孩子学习编程。 最初来自于 Wally Feurzeig, Seymour
Papert 和 Cynthia Solomon 于 1967 年所创造的 Logo 编程语言。

想像一下，一隻機器龜在 x-y 平面上從 (0, 0) 出發。在 ‘import turtle’ 之後
，給它命令 ‘turtle.forward(15)’ ，然後它就會移動 (在螢幕上！) 15 個單位
像素，方向是朝著其正面對的方向。給它命令 ‘turtle.right(25)’ ，它就會在原
地順時針旋轉 25 度。

Turtle star
...........

龜可以使用重複簡單動作之程式來畫出複雜的形狀。

[python-figures/turtle-star]
     from turtle import *
     color('red', 'yellow')
     begin_fill()
     while True:
         forward(200)
         left(170)
         if abs(pos()) < 1:
             break
     end_fill()
     done()

藉由結合這些類似的命令，複雜的形狀和圖形可以輕易被畫出來。

*note turtle: 11f. 模块是基于 Python 标准发行版 2.5 以来的同名模块重新编
写并进行了功能扩展。

新模块尽量保持了原模块的特点，并且(几乎)100%与其兼容。这就意味着初学编程
者能够以交互方式使用模块的所有命令、类和方法——运行 IDLE 时注意加 ‘-n’ 参
数。

turtle 模块提供面向对象和面向过程两种形式的海龟绘图基本组件。由于它使用
*note tkinter: 10e. 实现基本图形界面，因此需要安装了 Tk 支持的 Python 版
本。

面向对象的接口主要使用“2+2”个类：

  1. *note TurtleScreen: 31da. 类定义图形窗口作为绘图海龟的运动场。它的
     构造器需要一个 ‘tkinter.Canvas’ 或 *note ScrolledCanvas: 31db. 作为
     参数。应在 *note turtle: 11f. 作为某个程序的一部分的时候使用。

     *note Screen(): 31dc. 函数返回一个 *note TurtleScreen: 31da. 子类的
     单例对象。此函数应在 *note turtle: 11f. 作为独立绘图工具时使用。作
     为一个单例对象，其所属的类是不可被继承的。

     TurtleScreen/Screen 的所有方法还存在对应的函数，即作为面向过程的接
     口组成部分。

  2. *note RawTurtle: 31dd. (别名: *note RawPen: 31de.) 类定义海龟对象在
     *note TurtleScreen: 31da. 上绘图。它的构造器需要一个 Canvas,
     ScrolledCanvas 或 TurtleScreen 作为参数，以指定 RawTurtle 对象在哪
     里绘图。

     从 RawTurtle 派生出子类 *note Turtle: 31df. (别名: ‘Pen’)，该类对象
     在 *note Screen: 31dc. 实例上绘图，如果实例不存在则会自动创建。

     RawTurtle/Turtle 的所有方法也存在对应的函数，即作为面向过程的接口组
     成部分。

过程式接口提供与 *note Screen: 31dc. 和 *note Turtle: 31df. 类的方法相对
应的函数。函数名与对应的方法名相同。当 Screen 类的方法对应函数被调用时会
自动创建一个 Screen 对象。当 Turtle 类的方法对应函数被调用时会自动创建一
个 (匿名的) Turtle 对象。

如果屏幕上需要有多个海龟，就必须使用面向对象的接口。

     備註: 以下文档给出了函数的参数列表。对于方法来说当然还有额外的第一
     个参数 `self'，这里省略了。


File: python.info,  Node: 可用的 Turtle 和 Screen 方法概览,  Next: RawTurtle/Turtle 方法和对应函数,  Prev: 介紹,  Up: turtle --- 龜圖學

5.24.1.2 可用的 Turtle 和 Screen 方法概览
.........................................

* Menu:

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


File: python.info,  Node: Turtle 方法,  Next: TurtleScreen/Screen 方法,  Up: 可用的 Turtle 和 Screen 方法概览

5.24.1.3 Turtle 方法
....................

海龟动作

     移动和绘制

               *note forward(): 31e2. | *note fd(): 31e3. 前进 
               *note backward(): 31e4. | *note bk(): 31e5. | *note back(): 31e6. 后退 
               *note right(): 31e7. | *note rt(): 31e8. 右转 
               *note left(): 31e9. | *note lt(): 31ea. 左转 
               *note goto(): 31eb. | *note setpos(): 31ec. | *note setposition(): 31ed. 前往/定位 
               *note setx(): 31ee. 设置x坐标 
               *note sety(): 31ef. 设置y坐标 
               *note setheading(): 31f0. | *note seth(): 31f1. 设置朝向 
               *note home(): 31f2. 返回原点 
               *note circle(): 31f3. 画圆 
               *note dot(): 31f4. 画点 
               *note stamp(): 31f5. 印章 
               *note clearstamp(): 31f6. 清除印章 
               *note clearstamps(): 31f7. 清除多个印章 
               *note undo(): 31f8. 撤消 
               *note speed(): 31f9. 速度 

     获取海龟的状态

               *note position(): 31fa. | *note pos(): 31fb. 位置 
               *note towards(): 31fc. 目标方向 
               *note xcor(): 31fd. x坐标 
               *note ycor(): 31fe. y坐标 
               *note heading(): 31ff. 朝向 
               *note distance(): 3200. 距离 

     设置与度量单位

               *note degrees(): 3201. 角度 
               *note radians(): 3202. 弧度 

画笔控制

     绘图状态

               *note pendown(): 3203. | *note pd(): 3204. | *note down(): 3205. 画笔落下 
               *note penup(): 3206. | *note pu(): 3207. | *note up(): 3208. 画笔抬起 
               *note pensize(): 3209. | *note width(): 320a. 画笔粗细 
               *note pen(): 320b. 画笔 
               *note isdown(): 320c. 画笔是否落下 

     颜色控制

               *note color(): 320d. 颜色 
               *note pencolor(): 320e. 画笔颜色 
               *note fillcolor(): 320f. 填充颜色 

     填充

               *note filling(): 3210. 是否填充 
               *note begin_fill(): 3211. 开始填充 
               *note end_fill(): 3212. 结束填充 

     更多绘图控制

               *note reset(): 3213. 重置 
               *note clear(): 3214. 清空 
               *note write(): 3215. 书写 

海龟状态

     可见性

               *note showturtle(): 3216. | *note st(): 3217. 显示海龟 
               *note hideturtle(): 3218. | *note ht(): 3219. 隐藏海龟 
               *note isvisible(): 321a. 是否可见 

     外观

               *note shape(): 321b. 形状 
               *note resizemode(): 321c. 大小调整模式 
               *note shapesize(): 321d. | *note turtlesize(): 321e. 形状大小 
               *note shearfactor(): 321f. 剪切因子 
               *note settiltangle(): 3220. 设置倾角 
               *note tiltangle(): 3221. 倾角 
               *note tilt(): 3222. 倾斜 
               *note shapetransform(): 3223. 变形 
               *note get_shapepoly(): 3224. 获取形状多边形 

使用事件

          *note onclick(): 3225. 当鼠标点击 
          *note onrelease(): 3226. 当鼠标释放 
          *note ondrag(): 3227. 当鼠标拖动 

特殊海龟方法

          *note begin_poly(): 3228. 开始记录多边形 
          *note end_poly(): 3229. 结束记录多边形 
          *note get_poly(): 322a. 获取多边形 
          *note clone(): 322b. 克隆 
          *note getturtle(): 322c. | *note getpen(): 322d. 获取海龟画笔 
          *note getscreen(): 322e. 获取屏幕 
          *note setundobuffer(): 322f. 设置撤消缓冲区 
          *note undobufferentries(): 3230. 撤消缓冲区条目数 


File: python.info,  Node: TurtleScreen/Screen 方法,  Prev: Turtle 方法,  Up: 可用的 Turtle 和 Screen 方法概览

5.24.1.4 TurtleScreen/Screen 方法
.................................

窗口控制

          *note bgcolor(): 3232. 背景颜色 
          *note bgpic(): 3233. 背景图片 
          *note clearscreen(): 3234. 
          *note resetscreen(): 3235. 
          *note screensize(): 3236. 屏幕大小 
          *note setworldcoordinates(): 3237. 设置世界坐标系 

动画控制

          *note delay(): 3238. 延迟 
          *note tracer(): 3239. 追踪 
          *note update(): 323a. 更新 

使用屏幕事件

          *note listen(): 323b. 监听 
          *note onkey(): 323c. | *note onkeyrelease(): 323d. 当键盘按下并释放 
          *note onkeypress(): 323e. 当键盘按下 
          *note onclick(): 3225. | *note onscreenclick(): 323f. 当点击屏幕 
          *note ontimer(): 3240. 当达到定时 
          *note mainloop(): 3241. | *note done(): 3242. 主循环 

设置与特殊方法

          *note mode(): 3243. 模式 
          *note colormode(): 3244. 颜色模式 
          *note getcanvas(): 3245. 获取画布 
          *note getshapes(): 3246. 获取形状 
          *note register_shape(): 3247. | *note addshape(): 3248. 添加形状 
          *note turtles(): 3249. 所有海龟 
          *note window_height(): 324a. 窗口高度 
          *note window_width(): 324b. 窗口宽度 

输入方法

          *note textinput(): fa6. 文本输入 
          *note numinput(): fa7. 数字输入 

Screen 专有方法

          *note bye(): 324c. 退出 
          *note exitonclick(): 324d. 当点击时退出 
          *note setup(): 324e. 设置 
          *note title(): 324f. 标题 


File: python.info,  Node: RawTurtle/Turtle 方法和对应函数,  Next: TurtleScreen/Screen 方法及对应函数,  Prev: 可用的 Turtle 和 Screen 方法概览,  Up: turtle --- 龜圖學

5.24.1.5 RawTurtle/Turtle 方法和对应函数
........................................

本节中的大部分示例都使用 Turtle 类的一个实例，命名为 ‘turtle’。

* Menu:

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


File: python.info,  Node: 海龟动作,  Next: 获取海龟的状态,  Up: RawTurtle/Turtle 方法和对应函数

5.24.1.6 海龟动作
.................

 -- 函式: turtle.forward (distance)
 -- 函式: turtle.fd (distance)


     參數: ‘distance’ – 一个数值 (整型或浮点型)

     海龟前进 `distance' 指定的距离，方向为海龟的朝向。

          >>> turtle.position()
          (0.00,0.00)
          >>> turtle.forward(25)
          >>> turtle.position()
          (25.00,0.00)
          >>> turtle.forward(-75)
          >>> turtle.position()
          (-50.00,0.00)

 -- 函式: turtle.back (distance)
 -- 函式: turtle.bk (distance)
 -- 函式: turtle.backward (distance)


     參數: ‘distance’ – 一个数值

     海龟后退 `distance' 指定的距离，方向与海龟的朝向相反。不改变海龟的
     朝向。

          >>> turtle.position()
          (0.00,0.00)
          >>> turtle.backward(30)
          >>> turtle.position()
          (-30.00,0.00)

 -- 函式: turtle.right (angle)
 -- 函式: turtle.rt (angle)


     參數: ‘angle’ – 一个数值 (整型或浮点型)

     海龟右转 `angle' 个单位。(单位默认为角度，但可通过 *note degrees():
     3201. 和 *note radians(): 3202. 函数改变设置。) 角度的正负由海龟模
     式确定，参见 *note mode(): 3243.。

          >>> turtle.heading()
          22.0
          >>> turtle.right(45)
          >>> turtle.heading()
          337.0

 -- 函式: turtle.left (angle)
 -- 函式: turtle.lt (angle)


     參數: ‘angle’ – 一个数值 (整型或浮点型)

     海龟左转 `angle' 个单位。(单位默认为角度，但可通过 *note degrees():
     3201. 和 *note radians(): 3202. 函数改变设置。) 角度的正负由海龟模
     式确定，参见 *note mode(): 3243.。

          >>> turtle.heading()
          22.0
          >>> turtle.left(45)
          >>> turtle.heading()
          67.0

 -- 函式: turtle.goto (x, y=None)
 -- 函式: turtle.setpos (x, y=None)
 -- 函式: turtle.setposition (x, y=None)


     參數:

        * ‘x’ – 一个数值或数值对/向量

        * ‘y’ – 一个数值或 ‘None’

     如果 `y' 为 ‘None’，`x' 应为一个表示坐标的数值对或 *note Vec2D:
     3252. 类对象 (例如 *note pos(): 31fb. 返回的对象).

     海龟移动到一个绝对坐标。如果画笔已落下将会画线。不改变海龟的朝向。

           >>> 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)

 -- 函式: turtle.setx (x)


     參數: ‘x’ – 一个数值 (整型或浮点型)

     设置海龟的横坐标为 `x'，纵坐标保持不变。

          >>> turtle.position()
          (0.00,240.00)
          >>> turtle.setx(10)
          >>> turtle.position()
          (10.00,240.00)

 -- 函式: turtle.sety (y)


     參數: ‘y’ – 一个数值 (整型或浮点型)

     设置海龟的纵坐标为 `y'，横坐标保持不变。

          >>> turtle.position()
          (0.00,40.00)
          >>> turtle.sety(-10)
          >>> turtle.position()
          (0.00,-10.00)

 -- 函式: turtle.setheading (to_angle)
 -- 函式: turtle.seth (to_angle)


     參數: ‘to_angle’ – 一个数值 (整型或浮点型)

     设置海龟的朝向为 `to_angle'。以下是以角度表示的几个常用方向：

     标准模式                logo 模式
                             
     -------------------------------------------------
                             
     0 - 东                  0 - 北
                             
                             
     90 - 北                 90 - 东
                             
                             
     180 - 西                180 - 南
                             
                             
     270 - 南                270 - 西
                             

          >>> turtle.setheading(90)
          >>> turtle.heading()
          90.0

 -- 函式: turtle.home ()

     海龟移至初始坐标 (0,0)，并设置朝向为初始方向 (由海龟模式确定，参见
     *note mode(): 3243.)。

          >>> turtle.heading()
          90.0
          >>> turtle.position()
          (0.00,-10.00)
          >>> turtle.home()
          >>> turtle.position()
          (0.00,0.00)
          >>> turtle.heading()
          0.0

 -- 函式: turtle.circle (radius, extent=None, steps=None)


     參數:

        * ‘radius’ – 一个数值

        * ‘extent’ – 一个数值 (或 ‘None’)

        * ‘steps’ – 一个整型数 (或 ‘None’)

     绘制一个 `radius' 指定半径的圆。圆心在海龟左边 `radius' 个单位；
     `extent' 为一个夹角，用来决定绘制圆的一部分。如未指定 `extent*则绘
     制整个圆。如果 *extent' 不是完整圆周，则以当前画笔位置为一个端点绘
     制圆弧。如果 `radius' 为正值则朝逆时针方向绘制圆弧，否则朝顺时针方
     向。最终海龟的朝向会依据 `extent' 的值而改变。

     圆实际是以其内切正多边形来近似表示的，其边的数量由 `steps' 指定。如
     果未指定边数则会自动确定。此方法也可用来绘制正多边形。

          >>> 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

 -- 函式: turtle.dot (size=None, *color)


     參數:

        * ‘size’ – 一个整型数 >= 1 (如果指定)

        * ‘color’ – 一个颜色字符串或颜色数值元组

     绘制一个直径为 `size'，颜色为 `color' 的圆点。如果 `size' 未指定，
     则直径取 pensize+4 和 2*pensize 中的较大值。

          >>> turtle.home()
          >>> turtle.dot()
          >>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50)
          >>> turtle.position()
          (100.00,-0.00)
          >>> turtle.heading()
          0.0

 -- 函式: turtle.stamp ()

     在海龟当前位置印制一个海龟形状。返回该印章的 stamp_id，印章可以通过
     调用 ‘clearstamp(stamp_id)’ 来删除。

          >>> turtle.color("blue")
          >>> turtle.stamp()
          11
          >>> turtle.fd(50)

 -- 函式: turtle.clearstamp (stampid)


     參數: ‘stampid’ – 一个整型数，必须是之前 *note stamp(): 31f5. 调用
     的返回值

     删除 `stampid' 指定的印章。

          >>> 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)

 -- 函式: turtle.clearstamps (n=None)


     參數: ‘n’ – 一个整型数 (或 ‘None’)

     删除全部或前/后 `n' 个海龟印章。如果 `n' 为 ‘None’ 则删除全部印章，
     如果 `n' > 0 则删除前 `n' 个印章，否则如果 `n' < 0 则删除后 `n' 个
     印章。

          >>> 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()

 -- 函式: turtle.undo ()

     撤消 (或连续撤消) 最近的一个 (或多个) 海龟动作。可撤消的次数由撤消
     缓冲区的大小决定。

          >>> for i in range(4):
          ...     turtle.fd(50); turtle.lt(80)
          ...
          >>> for i in range(8):
          ...     turtle.undo()

 -- 函式: turtle.speed (speed=None)


     參數: ‘speed’ – 一个 0..10 范围内的整型数或速度字符串 (见下)

     设置海龟移动的速度为 0..10 表示的整型数值。如未指定参数则返回当前速
     度。

     如果输入数值大于 10 或小于 0.5 则速度设为 0。速度字符串与速度值的对
     应关系如下:

        * "fastest": 0 最快

        * "fast": 10 快

        * "normal": 6 正常

        * "slow": 3 慢

        * "slowest": 1 最慢

     速度值从 1 到 10，画线和海龟转向的动画效果逐级加快。

     注意: `speed' = 0 表示 `没有' 动画效果。forward/back 将使海龟向前
     /向后跳跃，同样的 left/right 将使海龟立即改变朝向。

          >>> turtle.speed()
          3
          >>> turtle.speed('normal')
          >>> turtle.speed()
          6
          >>> turtle.speed(9)
          >>> turtle.speed()
          9


File: python.info,  Node: 获取海龟的状态,  Next: 度量单位设置,  Prev: 海龟动作,  Up: RawTurtle/Turtle 方法和对应函数

5.24.1.7 获取海龟的状态
.......................

 -- 函式: turtle.position ()
 -- 函式: turtle.pos ()

     返回海龟当前的坐标 (x,y) (为 *note Vec2D: 3252. 矢量类对象)。

          >>> turtle.pos()
          (440.00,-0.00)

 -- 函式: turtle.towards (x, y=None)


     參數:

        * ‘x’ – 一个数值或数值对/矢量，或一个海龟实例

        * ‘y’ – 一个数值——如果 `x' 是一个数值，否则为 ‘None’

     返回从海龟位置到由 (x,y)、矢量或另一海龟所确定位置的连线的夹角。 此
     数值依赖于海龟的初始朝向，这又取决于 "standard"/"world" 或 "logo" 模
     式设置。

          >>> turtle.goto(10, 10)
          >>> turtle.towards(0,0)
          225.0

 -- 函式: turtle.xcor ()

     返回海龟的 x 坐标。

          >>> turtle.home()
          >>> turtle.left(50)
          >>> turtle.forward(100)
          >>> turtle.pos()
          (64.28,76.60)
          >>> print(round(turtle.xcor(), 5))
          64.27876

 -- 函式: turtle.ycor ()

     返回海龟的 y 坐标。

          >>> turtle.home()
          >>> turtle.left(60)
          >>> turtle.forward(100)
          >>> print(turtle.pos())
          (50.00,86.60)
          >>> print(round(turtle.ycor(), 5))
          86.60254

 -- 函式: turtle.heading ()

     返回海龟当前的朝向 (数值依赖于海龟模式参见 *note mode(): 3243.)。

          >>> turtle.home()
          >>> turtle.left(67)
          >>> turtle.heading()
          67.0

 -- 函式: turtle.distance (x, y=None)


     參數:

        * ‘x’ – 一个数值或数值对/矢量，或一个海龟实例

        * ‘y’ – 一个数值——如果 `x' 是一个数值，否则为 ‘None’

     返回从海龟位置到由 (x,y)，适量或另一海龟对应位置的单位距离。

          >>> turtle.home()
          >>> turtle.distance(30,40)
          50.0
          >>> turtle.distance((30,40))
          50.0
          >>> joe = Turtle()
          >>> joe.forward(77)
          >>> turtle.distance(joe)
          77.0


File: python.info,  Node: 度量单位设置,  Next: 画笔控制,  Prev: 获取海龟的状态,  Up: RawTurtle/Turtle 方法和对应函数

5.24.1.8 度量单位设置
.....................

 -- 函式: turtle.degrees (fullcircle=360.0)


     參數: ‘fullcircle’ – 一个数值

     设置角度的度量单位，即设置一个圆周为多少 "度"。默认值为 360 度。

          >>> 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

 -- 函式: turtle.radians ()

     设置角度的度量单位为弧度。其值等于 ‘degrees(2*math.pi)’。

          >>> turtle.home()
          >>> turtle.left(90)
          >>> turtle.heading()
          90.0
          >>> turtle.radians()
          >>> turtle.heading()
          1.5707963267948966


File: python.info,  Node: 画笔控制,  Next: 海龟状态,  Prev: 度量单位设置,  Up: RawTurtle/Turtle 方法和对应函数

5.24.1.9 画笔控制
.................

* Menu:

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


File: python.info,  Node: 绘图状态,  Next: 颜色控制,  Up: 画笔控制

5.24.1.10 绘图状态
..................

 -- 函式: turtle.pendown ()
 -- 函式: turtle.pd ()
 -- 函式: turtle.down ()

     画笔落下 – 移动时将画线。

 -- 函式: turtle.penup ()
 -- 函式: turtle.pu ()
 -- 函式: turtle.up ()

     画笔抬起 – 移动时不画线。

 -- 函式: turtle.pensize (width=None)
 -- 函式: turtle.width (width=None)


     參數: ‘width’ – 一个正数值

     设置线条的粗细为 `width' 或返回该值。如果 resizemode 设为 "auto" 并
     且 turtleshape 为多边形，该多边形也以同样组细的线条绘制。如未指定参
     数，则返回当前的 pensize。

          >>> turtle.pensize()
          1
          >>> turtle.pensize(10)   # from here on lines of width 10 are drawn

 -- 函式: turtle.pen (pen=None, **pendict)


     參數:

        * ‘pen’ – 一个包含部分或全部下列键的字典

        * ‘pendict’ – 一个或多个以下列键为关键字的关键字参数

     返回或设置画笔的属性，以一个包含以下键值对的 "画笔字典" 表示:

        * "shown": True/False

        * "pendown": True/False

        * "pencolor": 颜色字符串或颜色元组

        * "fillcolor": 颜色字符串或颜色元组

        * "pensize": 正数值

        * "speed": 0..10 范围内的数值

        * "resizemode": "auto" 或 "user" 或 "noresize"

        * "stretchfactor": (正数值, 正数值)

        * "outline": 正数值

        * "tilt": 数值

     此字典可作为后续调用 *note pen(): 320b. 时的参数，以恢复之前的画笔
     状态。另外还可将这些属性作为关键词参数提交。使用此方式可以用一条语
     句设置画笔的多个属性。

          >>> 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', ''), ('outline', 1), ('pencolor', 'yellow')]
          >>> turtle.pen(penstate, fillcolor="green")
          >>> sorted(turtle.pen().items())[:3]
          [('fillcolor', 'green'), ('outline', 1), ('pencolor', 'red')]

 -- 函式: turtle.isdown ()

     如果画笔落下返回 ‘True’，如果画笔抬起返回 ‘False’。

          >>> turtle.penup()
          >>> turtle.isdown()
          False
          >>> turtle.pendown()
          >>> turtle.isdown()
          True


File: python.info,  Node: 颜色控制,  Next: 填充,  Prev: 绘图状态,  Up: 画笔控制

5.24.1.11 颜色控制
..................

 -- 函式: turtle.pencolor (*args)

     返回或设置画笔颜色。

     允许以下四种输入格式:

     ‘pencolor()’

          返回以颜色描述字符串或元组 (见示例) 表示的当前画笔颜色。可用作
          其他 color/pencolor/fillcolor 调用的输入。

     ‘pencolor(colorstring)’

          设置画笔颜色为 `colorstring' 指定的 Tk 颜色描述字符串，例如
          ‘"red"’、‘"yellow"’ 或 ‘"#33cc8c"’。

     ‘pencolor((r, g, b))’

          设置画笔颜色为以 `r', `g', `b' 元组表示的 RGB 颜色。`r', `g',
          `b' 的取值范围应为 0..colormode，colormode 的值为 1.0 或 255
          (参见 *note colormode(): 3244.)。

     ‘pencolor(r, g, b)’

          设置画笔颜色为以 `r', `g', `b' 表示的 RGB 颜色。`r', `g', `b'
          的取值范围应为 0..colormode。

     如果 turtleshape 为多边形，该多边形轮廓也以新设置的画笔颜色绘制。

           >>> 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)

 -- 函式: turtle.fillcolor (*args)

     返回或设置填充颜色。

     允许以下四种输入格式:

     ‘fillcolor()’

          返回以颜色描述字符串或元组 (见示例) 表示的当前填充颜色。可用作
          其他 color/pencolor/fillcolor 调用的输入。

     ‘fillcolor(colorstring)’

          设置填充颜色为 `colorstring' 指定的 Tk 颜色描述字符串，例如
          ‘"red"’、‘"yellow"’ 或 ‘"#33cc8c"’。

     ‘fillcolor((r, g, b))’

          设置填充颜色为以 `r', `g', `b' 元组表示的 RGB 颜色。`r', `g',
          `b' 的取值范围应为 0..colormode，colormode 的值为 1.0 或 255
          (参见 *note colormode(): 3244.)。

     ‘fillcolor(r, g, b)’

          设置填充颜色为 `r', `g', `b' 表示的 RGB 颜色。`r', `g', `b' 的
          取值范围应为 0..colormode。

     如果 turtleshape 为多边形，该多边形内部也以新设置的填充颜色填充。

           >>> 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)

 -- 函式: turtle.color (*args)

     返回或设置画笔颜色和填充颜色。

     允许多种输入格式。使用如下 0 至 3 个参数:

     ‘color()’

          返回以一对颜色描述字符串或元组表示的当前画笔颜色和填充颜色，两
          者可分别由 *note pencolor(): 320e. 和 *note fillcolor(): 320f.
          返回。

     ‘color(colorstring)’, ‘color((r,g,b))’, ‘color(r,g,b)’

          输入格式与 *note pencolor(): 320e. 相同，同时设置填充颜色和画
          笔颜色为指定的值。

     ‘color(colorstring1, colorstring2)’, ‘color((r1,g1,b1), (r2,g2,b2))’

          相当于 ‘pencolor(colorstring1)’ 加 ‘fillcolor(colorstring2)’，
          使用其他输入格式的方法也与之类似。

     如果 turtleshape 为多边形，该多边形轮廓与填充也使用新设置的颜色。

           >>> turtle.color("red", "green")
           >>> turtle.color()
           ('red', 'green')
           >>> color("#285078", "#a0c8f0")
           >>> color()
           ((40.0, 80.0, 120.0), (160.0, 200.0, 240.0))

另参见: Screen 方法 *note colormode(): 3244.。


File: python.info,  Node: 填充,  Next: 更多绘图控制,  Prev: 颜色控制,  Up: 画笔控制

5.24.1.12 填充
..............

 -- 函式: turtle.filling ()

     返回填充状态 (填充为 ‘True’，否则为 ‘False’)。

           >>> turtle.begin_fill()
           >>> if turtle.filling():
           ...    turtle.pensize(5)
           ... else:
           ...    turtle.pensize(3)

 -- 函式: turtle.begin_fill ()

     在绘制要填充的形状之前调用。

 -- 函式: turtle.end_fill ()

     填充上次调用 *note begin_fill(): 3211. 之后绘制的形状。

     自相交多边形或多个形状间的重叠区域是否填充取决于操作系统的图形引擎
     、重叠的类型以及重叠的层数。 例如上面的 Turtle 多芒星可能会全部填充
     为黄色，也可能会有一些白色区域。

          >>> turtle.color("black", "red")
          >>> turtle.begin_fill()
          >>> turtle.circle(80)
          >>> turtle.end_fill()


File: python.info,  Node: 更多绘图控制,  Prev: 填充,  Up: 画笔控制

5.24.1.13 更多绘图控制
......................

 -- 函式: turtle.reset ()

     从屏幕中删除海龟的绘图，海龟回到原点并设置所有变量为默认值。

          >>> 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

 -- 函式: turtle.clear ()

     从屏幕中删除指定海龟的绘图。不移动海龟。海龟的状态和位置以及其他海
     龟的绘图不受影响。

 -- 函式: turtle.write (arg, move=False, align="left", font=("Arial", 8,
          "normal"))


     參數:

        * ‘arg’ – 要书写到 TurtleScreen 的对象

        * ‘move’ – True/False

        * ‘align’ – 字符串 "left", "center" 或 "right"

        * ‘font’ – 一个三元组 (fontname, fontsize, fonttype)

     基于 `align' ("left", "center" 或 "right") 并使用给定的字体将文本
     —— `arg' 的字符串表示形式 —— 写到当前海龟位置。 如果 `move' 为真值
     ，画笔会移至文本的右下角。 默认情况下 `move' 为 ‘False’。

          >>> turtle.write("Home = ", True, align="center")
          >>> turtle.write((0,0), True)


File: python.info,  Node: 海龟状态,  Next: 使用事件,  Prev: 画笔控制,  Up: RawTurtle/Turtle 方法和对应函数

5.24.1.14 海龟状态
..................

* Menu:

* 可见性::
* 外观::


File: python.info,  Node: 可见性,  Next: 外观,  Up: 海龟状态

5.24.1.15 可见性
................

 -- 函式: turtle.hideturtle ()
 -- 函式: turtle.ht ()

     使海龟不可见。当你绘制复杂图形时这是个好主意，因为隐藏海龟可显著加
     快绘制速度。

          >>> turtle.hideturtle()

 -- 函式: turtle.showturtle ()
 -- 函式: turtle.st ()

     使海龟可见。

          >>> turtle.showturtle()

 -- 函式: turtle.isvisible ()

     如果海龟显示返回 ‘True’，如果海龟隐藏返回 ‘False’。

          >>> turtle.hideturtle()
          >>> turtle.isvisible()
          False
          >>> turtle.showturtle()
          >>> turtle.isvisible()
          True


File: python.info,  Node: 外观,  Prev: 可见性,  Up: 海龟状态

5.24.1.16 外观
..............

 -- 函式: turtle.shape (name=None)


     參數: ‘name’ – 一个有效的形状名字符串

     设置海龟形状为 `name' 指定的形状名，如未指定形状名则返回当前的形状
     名。`name' 指定的形状名应存在于 TurtleScreen 的 shape 字典中。多边
     形的形状初始时有以下几种: "arrow", "turtle", "circle", "square",
     "triangle", "classic"。要了解如何处理形状请参看 Screen 方法 *note
     register_shape(): 3247.。

          >>> turtle.shape()
          'classic'
          >>> turtle.shape("turtle")
          >>> turtle.shape()
          'turtle'

 -- 函式: turtle.resizemode (rmode=None)


     參數: ‘rmode’ – 字符串 "auto", "user", "noresize" 其中之一

     设置大小调整模式为以下值之一: "auto", "user", "noresize"。如未指定
     `rmode' 则返回当前的大小调整模式。不同的大小调整模式的效果如下:

        - "auto": 根据画笔粗细值调整海龟的外观。

        - "user": 根据拉伸因子和轮廓宽度 (outline) 值调整海龟的外观，两
          者是由 *note shapesize(): 321d. 设置的。

        - "noresize": 不调整海龟的外观大小。

     ‘resizemode("user")’ 会由 *note shapesize(): 321d. 带参数使用时被调
     用。

          >>> turtle.resizemode()
          'noresize'
          >>> turtle.resizemode("auto")
          >>> turtle.resizemode()
          'auto'

 -- 函式: turtle.shapesize (stretch_wid=None, stretch_len=None,
          outline=None)
 -- 函式: turtle.turtlesize (stretch_wid=None, stretch_len=None,
          outline=None)


     參數:

        * ‘stretch_wid’ – 正数值

        * ‘stretch_len’ – 正数值

        * ‘outline’ – 正数值

     返回或设置画笔的属性 x/y-拉伸因子和/或轮廓。设置大小调整模式为
     "user"。当且仅当大小调整模式设为 "user" 时海龟会基于其拉伸因子调整
     外观: `stretch_wid' 为垂直于其朝向的宽度拉伸因子，`stretch_len' 为
     平等于其朝向的长度拉伸因子，决定形状轮廓线的粗细。

          >>> 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)

 -- 函式: turtle.shearfactor (shear=None)


     參數: ‘shear’ – 数值 (可选)

     设置或返回当前的剪切因子。根据 share 指定的剪切因子即剪切角度的切线
     来剪切海龟形状。`不' 改变海龟的朝向 (移动方向)。如未指定 shear 参数
     : 返回当前的剪切因子即剪切角度的切线，与海龟朝向平行的线条将被剪切
     。

           >>> turtle.shape("circle")
           >>> turtle.shapesize(5,2)
           >>> turtle.shearfactor(0.5)
           >>> turtle.shearfactor()
           0.5

 -- 函式: turtle.tilt (angle)


     參數: ‘angle’ – 一个数值

     海龟形状自其当前的倾角转动 `angle' 指定的角度，但 `不' 改变海龟的朝
     向 (移动方向)。

          >>> turtle.reset()
          >>> turtle.shape("circle")
          >>> turtle.shapesize(5,2)
          >>> turtle.tilt(30)
          >>> turtle.fd(50)
          >>> turtle.tilt(30)
          >>> turtle.fd(50)

 -- 函式: turtle.settiltangle (angle)


     參數: ‘angle’ – 一个数值

     旋转海龟形状使其指向 `angle' 指定的方向，忽略其当前的倾角，`不' 改
     变海龟的朝向 (移动方向)。

          >>> turtle.reset()
          >>> turtle.shape("circle")
          >>> turtle.shapesize(5,2)
          >>> turtle.settiltangle(45)
          >>> turtle.fd(50)
          >>> turtle.settiltangle(-45)
          >>> turtle.fd(50)

     3.1 版後已棄用.

 -- 函式: turtle.tiltangle (angle=None)


     參數: ‘angle’ – 一个数值 (可选)

     设置或返回当前的倾角。如果指定 angle 则旋转海龟形状使其指向 angle 指
     定的方向，忽略其当前的倾角。`不' 改变海龟的朝向 (移动方向)。如果未
     指定 angle: 返回当前的倾角，即海龟形状的方向和海龟朝向 (移动方向) 之
     间的夹角。

          >>> turtle.reset()
          >>> turtle.shape("circle")
          >>> turtle.shapesize(5,2)
          >>> turtle.tilt(45)
          >>> turtle.tiltangle()
          45.0

 -- 函式: turtle.shapetransform (t11=None, t12=None, t21=None, t22=None)


     參數:

        * ‘t11’ – 一个数值 (可选)

        * ‘t12’ – 一个数值 (可选)

        * ‘t21’ – 一个数值 (可选)

        * ‘t12’ – 一个数值 (可选)

     设置或返回海龟形状的当前变形矩阵。

     如未指定任何矩阵元素，则返回以 4 元素元组表示的变形矩阵。 否则就根
     据设置指定元素的矩阵来改变海龟形状，矩阵第一排的值为 t11, t12 而第
     二排的值为 t21, t22。 行列式 t11 * t22 - t12 * t21 必须不为零，否则
     会引发错误。 根据指定矩阵修改拉伸因子 stretchfactor, 剪切因子
     shearfactor 和倾角 tiltangle。

          >>> turtle = Turtle()
          >>> turtle.shape("square")
          >>> turtle.shapesize(4,2)
          >>> turtle.shearfactor(-0.5)
          >>> turtle.shapetransform()
          (4.0, -1.0, -0.0, 2.0)

 -- 函式: turtle.get_shapepoly ()

     返回以坐标值对元组表示的当前形状多边形。这可以用于定义一个新形状或
     一个复合形状的多个组成部分。

          >>> turtle.shape("square")
          >>> turtle.shapetransform(4, -1, 0, 2)
          >>> turtle.get_shapepoly()
          ((50, -20), (30, 20), (-50, 20), (-30, -20))


File: python.info,  Node: 使用事件,  Next: 特殊海龟方法,  Prev: 海龟状态,  Up: RawTurtle/Turtle 方法和对应函数

5.24.1.17 使用事件
..................

 -- 函式: turtle.onclick (fun, btn=1, add=None)


     參數:

        * ‘fun’ – 一个函数，调用时将传入两个参数表示在画布上点击的坐标。

        * ‘btn’ – 鼠标按钮编号，默认值为 1 (鼠标左键)

        * ‘add’ – ‘True’ 或 ‘False’ – 如为 ‘True’ 则将添加一个新绑定，否
          则将取代先前的绑定

     将 `fun' 指定的函数绑定到鼠标点击此海龟事件。如果 `fun' 值为
     ‘None’，则移除现有的绑定。以下为使用匿名海龟即过程式的示例:

          >>> def turn(x, y):
          ...     left(180)
          ...
          >>> onclick(turn)  # Now clicking into the turtle will turn it.
          >>> onclick(None)  # event-binding will be removed

 -- 函式: turtle.onrelease (fun, btn=1, add=None)


     參數:

        * ‘fun’ – 一个函数，调用时将传入两个参数表示在画布上点击的坐标。

        * ‘btn’ – 鼠标按钮编号，默认值为 1 (鼠标左键)

        * ‘add’ – ‘True’ 或 ‘False’ – 如为 ‘True’ 则将添加一个新绑定，否
          则将取代先前的绑定

     将 `fun' 指定的函数绑定到在此海龟上释放鼠标按键事件。如果 `fun' 值
     为 ‘None’，则移除现有的绑定。

          >>> 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.

 -- 函式: turtle.ondrag (fun, btn=1, add=None)


     參數:

        * ‘fun’ – 一个函数，调用时将传入两个参数表示在画布上点击的坐标。

        * ‘btn’ – 鼠标按钮编号，默认值为 1 (鼠标左键)

        * ‘add’ – ‘True’ 或 ‘False’ – 如为 ‘True’ 则将添加一个新绑定，否
          则将取代先前的绑定

     将 `fun' 指定的函数绑定到在此海龟上移动鼠标事件。如果 `fun' 值为
     ‘None’，则移除现有的绑定。

     注: 在海龟上移动鼠标事件之前应先发生在此海龟上点击鼠标事件。

          >>> turtle.ondrag(turtle.goto)

     在此之后点击并拖动海龟可在屏幕上手绘线条 (如果画笔为落下)。


File: python.info,  Node: 特殊海龟方法,  Next: 复合形状,  Prev: 使用事件,  Up: RawTurtle/Turtle 方法和对应函数

5.24.1.18 特殊海龟方法
......................

 -- 函式: turtle.begin_poly ()

     开始记录多边形的顶点。当前海龟位置为多边形的第一个顶点。

 -- 函式: turtle.end_poly ()

     停止记录多边形的顶点。当前海龟位置为多边形的最后一个顶点。它将连线
     到第一个顶点。

 -- 函式: turtle.get_poly ()

     返回最新记录的多边形。

          >>> 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)

 -- 函式: turtle.clone ()

     创建并返回海龟的克隆体，具有相同的位置、朝向和海龟属性。

          >>> mick = Turtle()
          >>> joe = mick.clone()

 -- 函式: turtle.getturtle ()
 -- 函式: turtle.getpen ()

     返回海龟对象自身。唯一合理的用法: 作为一个函数来返回 "匿名海龟":

          >>> pet = getturtle()
          >>> pet.fd(50)
          >>> pet
          <turtle.Turtle object at 0x...>

 -- 函式: turtle.getscreen ()

     返回作为海龟绘图场所的 *note TurtleScreen: 31da. 类对象。该对象将可
     调用 TurtleScreen 方法。

          >>> ts = turtle.getscreen()
          >>> ts
          <turtle._Screen object at 0x...>
          >>> ts.bgcolor("pink")

 -- 函式: turtle.setundobuffer (size)


     參數: ‘size’ – 一个整型数值或 ‘None’

     设置或禁用撤销缓冲区。 如果 `size' 为整数，则开辟一个给定大小的空撤
     销缓冲区。 `size' 给出了可以通过 *note undo(): 31f8. 方法/函数撤销
     海龟动作的最大次数。 如果 `size' 为 ‘None’，则禁用撤销缓冲区。

          >>> turtle.setundobuffer(42)

 -- 函式: turtle.undobufferentries ()

     返回撤销缓冲区里的条目数。

          >>> while undobufferentries():
          ...     undo()


File: python.info,  Node: 复合形状,  Prev: 特殊海龟方法,  Up: RawTurtle/Turtle 方法和对应函数

5.24.1.19 复合形状
..................

要使用由多个不同颜色多边形构成的复合海龟形状，你必须明确地使用辅助类
*note Shape: 3261.，具体步骤如下:

  1. 创建一个空 Shape 对象，类型为 "compound"。

  2. 按照需要使用 ‘addcomponent()’ 方法向此对象添加多个部件。

     例如:

          >>> 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")

  3. 接下来将 Shape 对象添加到 Screen 对象的形状列表并使用它:

          >>> register_shape("myshape", s)
          >>> shape("myshape")

     備註: *note Shape: 3261. 类在 *note register_shape(): 3247. 方法的
     内部以多种方式使用。应用程序编写者 `只有' 在使用上述的复合形状时才
     需要处理 Shape 类。


File: python.info,  Node: TurtleScreen/Screen 方法及对应函数,  Next: 公共类,  Prev: RawTurtle/Turtle 方法和对应函数,  Up: turtle --- 龜圖學

5.24.1.20 TurtleScreen/Screen 方法及对应函数
............................................

本节中的大部分示例都使用 TurtleScreen 类的一个实例，命名为 ‘screen’。

* Menu:

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


File: python.info,  Node: 窗口控制,  Next: 动画控制,  Up: TurtleScreen/Screen 方法及对应函数

5.24.1.21 窗口控制
..................

 -- 函式: turtle.bgcolor (*args)


     參數: ‘args’ – 一个颜色字符串或三个取值范围 0..colormode 内的数值或
     一个取值范围相同的数值3元组

     设置或返回 TurtleScreen 的背景颜色。

          >>> screen.bgcolor("orange")
          >>> screen.bgcolor()
          'orange'
          >>> screen.bgcolor("#800080")
          >>> screen.bgcolor()
          (128.0, 0.0, 128.0)

 -- 函式: turtle.bgpic (picname=None)


     參數: ‘picname’ – 一个字符串, gif-文件名, ‘"nopic"’, 或 ‘None’

     设置背景图片或返回当前背景图片名称。如果 `picname' 为一个文件名，则
     将相应图片设为背景。如果 `picname' 为 ‘"nopic"’，则删除当前背景图片
     。如果 `picname' 为 ‘None’，则返回当前背景图片文件名。:

          >>> screen.bgpic()
          'nopic'
          >>> screen.bgpic("landscape.gif")
          >>> screen.bgpic()
          "landscape.gif"

 -- 函式: turtle.clear ()

          備註: 此 TurtleScreen 方法作为全局函数时只有一个名字
          ‘clearscreen’。全局函数 ‘clear’ 所对应的是 Turtle 方法
          ‘clear’。

 -- 函式: turtle.clearscreen ()

     从中删除所有海龟的全部绘图。将已清空的 TurtleScreen 重置为初始状态:
     白色背景，无背景片，无事件绑定并启用追踪。

 -- 函式: turtle.reset ()

          備註: 此 TurtleScreen 方法作为全局函数时只有一个名字
          ‘resetscreen’。全局函数 ‘reset’ 所对应的是 Turtle 方法
          ‘reset’。

 -- 函式: turtle.resetscreen ()

     重置屏幕上的所有海龟为其初始状态。

 -- 函式: turtle.screensize (canvwidth=None, canvheight=None, bg=None)


     參數:

        * ‘canvwidth’ – 正整型数，以像素表示画布的新宽度值

        * ‘canvheight’ – 正整型数，以像素表示画面的新高度值

        * ‘bg’ – 颜色字符串或颜色元组，新的背景颜色

     如未指定任何参数，则返回当前的 (canvaswidth, canvasheight)。否则改
     变作为海龟绘图场所的画布大小。不改变绘图窗口。要观察画布的隐藏区域
     ，可以使用滚动条。通过此方法可以令之前绘制于画布之外的图形变为可见
     。

          >>> screen.screensize()
          (400, 300)
          >>> screen.screensize(2000,1500)
          >>> screen.screensize()
          (2000, 1500)

     也可以用来寻找意外逃走的海龟 ;-)

 -- 函式: turtle.setworldcoordinates (llx, lly, urx, ury)


     參數:

        * ‘llx’ – 一个数值, 画布左下角的 x-坐标

        * ‘lly’ – 一个数值, 画布左下角的 y-坐标

        * ‘urx’ – 一个数值, 画面右上角的 x-坐标

        * ‘ury’ – 一个数值, 画布右上角的 y-坐标

     设置用户自定义坐标系并在必要时切换模式为 "world"。这会执行一次
     ‘screen.reset()’。如果 "world" 模式已激活，则所有图形将根据新的坐标
     系重绘。

     `注意': 在用户自定义坐标系中，角度可能显得扭曲。

          >>> 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


File: python.info,  Node: 动画控制,  Next: 使用屏幕事件,  Prev: 窗口控制,  Up: TurtleScreen/Screen 方法及对应函数

5.24.1.22 动画控制
..................

 -- 函式: turtle.delay (delay=None)


     參數: ‘delay’ – 正整型数

     设置或返回以毫秒数表示的延迟值 `delay'。(这约等于连续两次画布刷新的
     间隔时间。) 绘图延迟越长，动画速度越慢。

     可选参数:

          >>> screen.delay()
          10
          >>> screen.delay(5)
          >>> screen.delay()
          5

 -- 函式: turtle.tracer (n=None, delay=None)


     參數:

        * ‘n’ – 非负整型数

        * ‘delay’ – 非负整型数

     启用/禁用海龟动画并设置刷新图形的延迟时间。如果指定 `n' 值，则只有
     每第 n 次屏幕刷新会实际执行。(可被用来加速复杂图形的绘制。) 如果调
     用时不带参数，则返回当前保存的 n 值。第二个参数设置延迟值 (参见
     *note delay(): 3238.)。

          >>> screen.tracer(8, 25)
          >>> dist = 2
          >>> for i in range(200):
          ...     fd(dist)
          ...     rt(90)
          ...     dist += 2

 -- 函式: turtle.update ()

     执行一次 TurtleScreen 刷新。在禁用追踪时使用。

另参见 RawTurtle/Turtle 方法 *note speed(): 31f9.。


File: python.info,  Node: 使用屏幕事件,  Next: 输入方法,  Prev: 动画控制,  Up: TurtleScreen/Screen 方法及对应函数

5.24.1.23 使用屏幕事件
......................

 -- 函式: turtle.listen (xdummy=None, ydummy=None)

     设置焦点到 TurtleScreen (以便接收按键事件)。使用两个 Dummy 参数以便
     能够传递 *note listen(): 323b. 给 onclick 方法。

 -- 函式: turtle.onkey (fun, key)
 -- 函式: turtle.onkeyrelease (fun, key)


     參數:

        * ‘fun’ – 一个无参数的函数或 ‘None’

        * ‘key’ – 一个字符串: 键 (例如 "a") 或键标 (例如 "space")

     绑定 `fun' 指定的函数到按键释放事件。如果 `fun' 值为 ‘None’，则移除
     事件绑定。注: 为了能够注册按键事件，TurtleScreen 必须得到焦点。(参
     见 method *note listen(): 323b. 方法。)

          >>> def f():
          ...     fd(50)
          ...     lt(60)
          ...
          >>> screen.onkey(f, "Up")
          >>> screen.listen()

 -- 函式: turtle.onkeypress (fun, key=None)


     參數:

        * ‘fun’ – 一个无参数的函数或 ‘None’

        * ‘key’ – 一个字符串: 键 (例如 "a") 或键标 (例如 "space")

     绑定 `fun' 指定的函数到指定键的按下事件。如未指定键则绑定到任意键的
     按下事件。注: 为了能够注册按键事件，必须得到焦点。(参见 *note
     listen(): 323b. 方法。)

          >>> def f():
          ...     fd(50)
          ...
          >>> screen.onkey(f, "Up")
          >>> screen.listen()

 -- 函式: turtle.onclick (fun, btn=1, add=None)
 -- 函式: turtle.onscreenclick (fun, btn=1, add=None)


     參數:

        * ‘fun’ – 一个函数，调用时将传入两个参数表示在画布上点击的坐标。

        * ‘btn’ – 鼠标按钮编号，默认值为 1 (鼠标左键)

        * ‘add’ – ‘True’ 或 ‘False’ – 如为 ‘True’ 则将添加一个新绑定，否
          则将取代先前的绑定

     绑定 `fun' 指定的函数到鼠标点击屏幕事件。如果 `fun' 值为 ‘None’，则
     移除现有的绑定。

     以下示例使用一个 TurtleScreen 实例 ‘screen’ 和一个 Turtle 实例
     ‘turtle’:

          >>> 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

          備註: 此 TurtleScreen 方法作为全局函数时只有一个名字
          ‘onscreenclick’。全局函数 ‘onclick’ 所对应的是 Turtle 方法
          ‘onclick’。

 -- 函式: turtle.ontimer (fun, t=0)


     參數:

        * ‘fun’ – 一个无参数的函数

        * ‘t’ – 一个数值 >= 0

     安装一个计时器，在 `t' 毫秒后调用 `fun' 函数。

          >>> running = True
          >>> def f():
          ...     if running:
          ...         fd(50)
          ...         lt(60)
          ...         screen.ontimer(f, 250)
          >>> f()   ### makes the turtle march around
          >>> running = False

 -- 函式: turtle.mainloop ()
 -- 函式: turtle.done ()

     开始事件循环 - 调用 Tkinter 的 mainloop 函数。必须作为一个海龟绘图
     程序的结束语句。如果一个脚本是在以 -n 模式 (无子进程) 启动的 IDLE 中
     运行时 `不可' 使用 - 用于实现海龟绘图的交互功能。:

          >>> screen.mainloop()


File: python.info,  Node: 输入方法,  Next: 设置与特殊方法,  Prev: 使用屏幕事件,  Up: TurtleScreen/Screen 方法及对应函数

5.24.1.24 输入方法
..................

 -- 函式: turtle.textinput (title, prompt)


     參數:

        * ‘title’ – 字符串

        * ‘prompt’ – 字符串

     弹出一个对话框窗口用来输入一个字符串。形参 title 为对话框窗口的标题
     ，prompt 为一条文本，通常用来提示要输入什么信息。返回输入的字符串。
     如果对话框被取消则返回 ‘None’。:

          >>> screen.textinput("NIM", "Name of first player:")

 -- 函式: turtle.numinput (title, prompt, default=None, minval=None,
          maxval=None)


     參數:

        * ‘title’ – 字符串

        * ‘prompt’ – 字符串

        * ‘default’ – 数值 (可选)

        * ‘minval’ – 数值 (可选)

        * ‘maxval’ – 数值 (可选)

     弹出一个对话框窗口用来输入一个数值。title 为对话框窗口的标题，
     prompt 为一条文本，通常用来描述要输入的数值信息。default: 默认值,
     minval: 可输入的最小值, maxval: 可输入的最大值。输入数值的必须在指
     定的 minval ..  maxval 范围之内，否则将给出一条提示，对话框保持打开
     等待修改。返回输入的数值。如果对话框被取消则返回 ‘None’。:

          >>> screen.numinput("Poker", "Your stakes:", 1000, minval=10, maxval=10000)


File: python.info,  Node: 设置与特殊方法,  Next: Screen 专有方法 而非继承自 TurtleScreen,  Prev: 输入方法,  Up: TurtleScreen/Screen 方法及对应函数

5.24.1.25 设置与特殊方法
........................

 -- 函式: turtle.mode (mode=None)


     參數: ‘mode’ – 字符串 "standard", "logo" 或 "world" 其中之一

     设置海龟模式 ("standard", "logo" 或 "world") 并执行重置。如未指定模
     式则返回当前的模式。

     "standard" 模式与旧的 *note turtle: 11f. 兼容。"logo" 模式与大部分
     Logo 海龟绘图兼容。"world" 模式使用用户自定义的 "世界坐标系"。`注意
     ': 在此模式下，如果 ‘x/y’ 单位比率不等于 1 则角度会显得扭曲。

     模式             初始海龟朝向                  正数角度
                                                    
     -----------------------------------------------------------------------
                                                    
     "standard"       朝右 (东)                     逆时针
                                                    
                                                    
     "logo"           朝上 (北)                     顺时针
                                                    

          >>> mode("logo")   # resets turtle heading to north
          >>> mode()
          'logo'

 -- 函式: turtle.colormode (cmode=None)


     參數: ‘cmode’ – 数值 1.0 或 255 其中之一

     返回颜色模式或将其设为 1.0 或 255。构成颜色三元组的 `r', `g', `b' 数
     值必须在 0..`cmode' 范围之内。

          >>> 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)

 -- 函式: turtle.getcanvas ()

     返回此 TurtleScreen 的 Canvas 对象。供了解 Tkinter 的 Canvas 对象内
     部机理的人士使用。

          >>> cv = screen.getcanvas()
          >>> cv
          <turtle.ScrolledCanvas object ...>

 -- 函式: turtle.getshapes ()

     返回所有当前可用海龟形状的列表。

          >>> screen.getshapes()
          ['arrow', 'blank', 'circle', ..., 'turtle']

 -- 函式: turtle.register_shape (name, shape=None)
 -- 函式: turtle.addshape (name, shape=None)

     调用此函数有三种不同方式:

       1. `name' 为一个 gif 文件的文件名， `shape' 为 ‘None’: 安装相应的
          图像形状。:

               >>> screen.register_shape("turtle.gif")

               備註: 当海龟转向时图像形状 `不会' 转动，因此无法显示海龟
               的朝向!

       2. `name' 为指定的字符串，`shape' 为由坐标值对构成的元组: 安装相
          应的多边形形状。

               >>> screen.register_shape("triangle", ((5,-3), (0,5), (-5,-3)))

       3. `name' 为指定的字符串， 为一个 (复合) *note Shape: 3261. 类对
          象: 安装相应的复合形状。

     将一个海龟形状加入 TurtleScreen 的形状列表。只有这样注册过的形状才
     能通过执行 ‘shape(shapename)’ 命令来使用。

 -- 函式: turtle.turtles ()

     返回屏幕上的海龟列表。

          >>> for turtle in screen.turtles():
          ...     turtle.color("red")

 -- 函式: turtle.window_height ()

     返回海龟窗口的高度。:

          >>> screen.window_height()
          480

 -- 函式: turtle.window_width ()

     返回海龟窗口的宽度。:

          >>> screen.window_width()
          640


File: python.info,  Node: Screen 专有方法 而非继承自 TurtleScreen,  Prev: 设置与特殊方法,  Up: TurtleScreen/Screen 方法及对应函数

5.24.1.26 Screen 专有方法, 而非继承自 TurtleScreen
..................................................

 -- 函式: turtle.bye ()

     关闭海龟绘图窗口。

 -- 函式: turtle.exitonclick ()

     将 ‘bye()’ 方法绑定到 Screen 上的鼠标点击事件。

     如果配置字典中 "using_IDLE" 的值为 ‘False’ (默认值) 则同时进入主事
     件循环。注: 如果启动 IDLE 时使用了 ‘-n’ 开关 (无子进程)，
     ‘turtle.cfg’ 中此数值应设为 ‘True’。在此情况下 IDLE 本身的主事件循
     环同样会作用于客户脚本。

 -- 函式: turtle.setup (width=_CFG["width"], height=_CFG["height"],
          startx=_CFG["leftright"], starty=_CFG["topbottom"])

     设置主窗口的大小和位置。默认参数值保存在配置字典中，可通过
     ‘turtle.cfg’ 文件进行修改。


     參數:

        * ‘width’ – 如为一个整型数值，表示大小为多少像素，如为一个浮点数
          值，则表示屏幕的占比；默认为屏幕的 50%

        * ‘height’ – 如为一个整型数值，表示高度为多少像素，如为一个浮点
          数值，则表示屏幕的占比；默认为屏幕的 75%

        * ‘startx’ – 如为正值，表示初始位置距离屏幕左边缘多少像素，负值
          表示距离右边缘，‘None’ 表示窗口水平居中

        * ‘starty’ – 如为正值，表示初始位置距离屏幕上边缘多少像素，负值
          表示距离下边缘，‘None’ 表示窗口垂直居中

          >>> 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

 -- 函式: turtle.title (titlestring)


     參數: ‘titlestring’ – 一个字符串，显示为海龟绘图窗口的标题栏文本

     设置海龟窗口标题为 `titlestring' 指定的文本。

          >>> screen.title("Welcome to the turtle zoo!")


File: python.info,  Node: 公共类,  Next: 帮助与配置,  Prev: TurtleScreen/Screen 方法及对应函数,  Up: turtle --- 龜圖學

5.24.1.27 公共类
................

 -- 類別: turtle.RawTurtle (canvas)
 -- 類別: turtle.RawPen (canvas)


     參數: ‘canvas’ – 一个 ‘tkinter.Canvas’ , *note ScrolledCanvas:
     31db. 或 *note TurtleScreen: 31da. 类对象

     创建一个海龟。海龟对象具有 "Turtle/RawTurtle 方法" 一节所述的全部方
     法。

 -- 類別: turtle.Turtle

     RawTurtle 的子类，具有相同的接口，但其绘图场所为默认的 *note
     Screen: 31dc. 类对象，在首次使用时自动创建。

 -- 類別: turtle.TurtleScreen (cv)


     參數: ‘cv’ – 一个 ‘tkinter.Canvas’ 类对象

     提供面向屏幕的方法例如 ‘setbg()’ 等。说明见上文。

 -- 類別: turtle.Screen

     TurtleScreen 的子类，*note 增加了四个方法: 3269.

 -- 類別: turtle.ScrolledCanvas (master)


     參數: ‘master’ – 可容纳 ScrolledCanvas 的 Tkinter 部件，即添加了滚
     动条的 Tkinter-canvas

     由 Screen 类使用，使其能够自动提供一个 ScrolledCanvas 作为海龟的绘
     图场所。

 -- 類別: turtle.Shape (type_, data)


     參數: ‘type_’ – 字符串 "polygon", "image", "compound" 其中之一

     实现形状的数据结构。‘(type_, data)’ 必须遵循以下定义:

     `type_'         `data'
                     
     -------------------------------------------------------------------------------
                     
     "polygon"       一个多边形元组，即由坐标值对构成的元组
                     
                     
     "image"         一个图片 (此形式仅限内部使用!)
                     
                     
     "compound"      ‘None’ (复合形状必须使用 *note addcomponent(): 326b. 方法来
                     构建)
                     

      -- 成員函式: addcomponent (poly, fill, outline=None)


          參數:

             * ‘poly’ – 一个多边形，即由数值对构成的元组

             * ‘fill’ – 一种颜色，将用来填充 `poly' 指定的多边形

             * ‘outline’ – 一种颜色，用于多边形的轮廓 (如有指定)

          示例:

               >>> 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()

          参见 *note 复合形状: 3260.。

 -- 類別: turtle.Vec2D (x, y)

     一个二维矢量类，用来作为实现海龟绘图的辅助类。也可能在海龟绘图程序
     中使用。派生自元组，因此矢量也属于元组!

     提供的运算 (`a', `b' 为矢量, `k' 为数值):

        * ‘a + b’ 矢量加法

        * ‘a - b’ 矢量减法

        * ‘a * b’ 内积

        * ‘k * a’ 和 ‘a * k’ 与标量相乘

        * ‘abs(a)’ a 的绝对值

        * ‘a.rotate(angle)’ 旋转


File: python.info,  Node: 帮助与配置,  Next: turtledemo --- 演示脚本集,  Prev: 公共类,  Up: turtle --- 龜圖學

5.24.1.28 帮助与配置
....................

* Menu:

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


File: python.info,  Node: 如何使用帮助,  Next: 文档字符串翻译为不同的语言,  Up: 帮助与配置

5.24.1.29 如何使用帮助
......................

Screen 和 Turtle 类的公用方法以文档字符串提供了详细的文档。因此可以利用
Python 帮助工具获取这些在线帮助信息:

   - 当使用 IDLE 时，输入函数/方法调用将弹出工具提示显示其签名和文档字符
     串的头几行。

   - 对文法或函数调用 *note help(): 175. 将显示其文档字符串:

          >>> 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()

   - 方法对应函数的文档字符串的形式会有一些修改:

          >>> 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()

这些修改版文档字符串是在导入时与方法对应函数的定义一起自动生成的。


File: python.info,  Node: 文档字符串翻译为不同的语言,  Next: 如何配置 Screen 和 Turtle,  Prev: 如何使用帮助,  Up: 帮助与配置

5.24.1.30 文档字符串翻译为不同的语言
....................................

可使用工具创建一个字典，键为方法名，值为 Screen 和 Turtle 类公共方法的文
档字符串。

 -- 函式: turtle.write_docstringdict (filename="turtle_docstringdict")


     參數: ‘filename’ – 一个字符串，表示文件名

     创建文档字符串字典并将其写入 filename 指定的 Python 脚本文件。此函
     数必须显示地调用 (海龟绘图类并不使用此函数)。文档字符串字典将被写入
     到 Python 脚本文件 ‘`filename'.py’。该文件可作为模板用来将文档字符
     串翻译为不同语言。

如果你 (或你的学生) 想使用本国语言版本的 *note turtle: 11f. 在线帮助，你
必须翻译文档字符串并保存结果文件，例如 ‘turtle_docstringdict_german.py’.

如果你在 ‘turtle.cfg’ 文件中加入了相应的条目，此字典将在导入模块时被读取
并替代原有的英文版文档字符串。

在撰写本文档时已经有了德语和意大利语版的文档字符串字典。(更多需求请联系
<glingl@aon.at>)


File: python.info,  Node: 如何配置 Screen 和 Turtle,  Prev: 文档字符串翻译为不同的语言,  Up: 帮助与配置

5.24.1.31 如何配置 Screen 和 Turtle
...................................

内置的默认配置是模仿旧 turtle 模块的外观和行为，以便尽可能地与其保持兼容
。

如果你想使用不同的配置，以便更好地反映此模块的特性或是更适合你的需求，例
如在课堂中使用，你可以准备一个配置文件 ‘turtle.cfg’，该文件将在导入模块
时被读取并根据其中的设定修改模块配置。

内置的配置对应以下的 turtle.cfg:

     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

选定条目的简短说明:

   - 开头的四行对应 ‘Screen.setup()’ 方法的参数。

   - 第 5 和 6 行对应 ‘Screen.screensize()’ 方法的参数。

   - `shape' 可以是任何内置形状，即: arrow, turtle 等。更多信息可用
     ‘help(shape)’ 查看。

   - 如果你想使用无填充色 (即令海龟变透明)，你必须写 ‘fillcolor = ""’ (但
     cfg 文件中所有非空字符串都不可加引号)。

   - 如果你想令海龟反映其状态，你必须使用 ‘resizemode = auto’。

   - 如果你设置语言例如 ‘language = italian’ 则文档字符串字典
     ‘turtle_docstringdict_italian.py’ 将在导入模块时被加载 (如果导入路
     径即 *note turtle: 11f. 的目录中存在此文件。

   - `exampleturtle' 和 `examplescreen' 条目定义了相应对象在文档字符串中
     显示的名称。方法文档字符串转换为函数文档字符串时将从文档字符串中删
     去这些名称。

   - `using_IDLE': 如果你经常使用 IDLE 并启用其 -n 开关 ("无子进程") 则
     应将此项设为 ‘True’，这将阻止 *note exitonclick(): 324d. 进入主事件
     循环。

‘turtle.cfg’ 文件可以保存于 *note turtle: 11f. 所在目录，当前工作目录也
可以有一个同名文件。后者会重载覆盖前者的设置。

‘Lib/turtledemo’ 目录中也有一个 ‘turtle.cfg’ 文件。你可以将其作为示例进
行研究，并在运行演示时查看其作用效果 (但最好不要在演示查看器中运行)。


File: python.info,  Node: turtledemo --- 演示脚本集,  Next: Python 2 6 之后的变化,  Prev: 帮助与配置,  Up: turtle --- 龜圖學

5.24.1.32 ‘turtledemo’ — 演示脚本集
...................................

*note turtledemo: 120. 包汇集了一组演示脚本。这些脚本可以通过以下命令打
开所提供的演示查看器运行和查看:

     python -m turtledemo

此外，你也可以单独运行其中的演示脚本。例如，:

     python -m turtledemo.bytedesign

*note turtledemo: 120. 包目录中的内容:

   - 一个演示查看器 ‘__main__.py’，可用来查看脚本的源码并即时运行。

   - 多个脚本文件，演示 *note turtle: 11f. 模块的不同特性。所有示例可通
     过 Examples 菜单打开。也可以单独运行每个脚本。

   - 一个 ‘turtle.cfg’ 文件，作为说明如何编写并使用模块配置文件的示例模
     板。

演示脚本清单如下:

名称                 描述                               相关特性
                                                        
------------------------------------------------------------------------------------
                                                        
bytedesign           复杂的传统海龟绘图模式             ‘tracer()’, delay,
                                                        ‘update()’
                                                        
                                                        
chaos                绘制 Verhulst 动态模型，演示通过   世界坐标系
                     计算机的运算可能会生成令人惊叹的   
                     结果
                     
                                                        
clock                绘制模拟时钟显示本机的当前时间     海龟作为表针, ontimer
                                                        
                                                        
colormixer           试验 r, g, b 颜色模式              ‘ondrag()’ 当鼠标拖动
                                                        
                                                        
forest               绘制 3 棵广度优先树                随机化
                                                        
                                                        
fractalcurves        绘制 Hilbert & Koch 曲线           递归
                                                        
                                                        
lindenmayer          文化数学 (印度装饰艺术)            L-系统
                                                        
                                                        
minimal_hanoi        汉诺塔                             矩形海龟作为汉诺盘
                                                        (shape, shapesize)
                                                        
                                                        
nim                  玩经典的“尼姆”游戏，开始时有三堆   海龟作为小棒，事件驱动 (鼠
                     小棒，与电脑对战。                 标, 键盘)
                                                        
                                                        
paint                超极简主义绘画程序                 ‘onclick()’ 当鼠标点击
                                                        
                                                        
peace                初级技巧                           海龟: 外观与动画
                                                        
                                                        
penrose              非周期性地使用风筝和飞镖形状铺满   ‘stamp()’ 印章
                     平面                               
                     
                                                        
planet_and_moon      模拟引力系统                       复合开关, ‘Vec2D’ 类
                                                        
                                                        
round_dance          两两相对并不断旋转舞蹈的海龟       复合形状, clone
                                                        shapesize, tilt,
                                                        get_shapepoly, update
                                                        
                                                        
sorting_animate      动态演示不同的排序方法             简单对齐, 随机化
                                                        
                                                        
tree                 一棵 (图形化的) 广度优先树 (使用   ‘clone()’ 克隆
                     生成器)                            
                     
                                                        
two_canvases         简单设计                           两块画布上的海龟
                                                        
                                                        
wikipedia            一个来自介绍海龟绘图的维基百科文   ‘clone()’, ‘undo()’
                     章的图案                           
                     
                                                        
yinyang              另一个初级示例                     ‘circle()’ 画圆
                                                        

祝你玩得开心！


File: python.info,  Node: Python 2 6 之后的变化,  Next: Python 3 0 之后的变化,  Prev: turtledemo --- 演示脚本集,  Up: turtle --- 龜圖學

5.24.1.33 Python 2.6 之后的变化
...............................

   - ‘Turtle.tracer()’, ‘Turtle.window_width()’ 和
     ‘Turtle.window_height()’ 方法已被去除。具有这些名称和功能的方法现在
     只限于 ‘Screen’ 类的方法。但其对应的函数仍然可用。(实际上在 Python
     2.6 中这些方法就已经只是从对应的 ‘TurtleScreen’/‘Screen’ 类的方法复
     制而来。)

   - ‘Turtle.fill()’ 方法已被去除。‘begin_fill()’ 和 ‘end_fill()’ 的行为
     则有细微改变: 现在每个填充过程必须以一个 ‘end_fill()’ 调用来结束。

   - 新增了一个 ‘Turtle.filling()’ 方法。该方法返回一个布尔值: 如果填充
     过程正在进行为 ‘True’，否则为 ‘False’。此行为相当于 Python 2.6 中不
     带参数的 ‘fill()’ 调用。


File: python.info,  Node: Python 3 0 之后的变化,  Prev: Python 2 6 之后的变化,  Up: turtle --- 龜圖學

5.24.1.34 Python 3.0 之后的变化
...............................

   - 新增了 ‘Turtle.shearfactor()’, ‘Turtle.shapetransform()’ 和
     ‘Turtle.get_shapepoly()’ 方法。这样就可以使用所有标准线性变换来调整
     海龟形状。‘Turtle.tiltangle()’ 的功能已被加强: 现在可被用来获取或设
     置倾角。‘Turtle.settiltangle()’ 已弃用。

   - 新增了 ‘Screen.onkeypress()’ 方法作为对 ‘Screen.onkey()’ 的补充，实
     际就是将行为绑定到 keyrelease 事件。后者相应增加了一个别名:
     ‘Screen.onkeyrelease()’。

   - 新增了 ‘Screen.mainloop()’ 方法。这样当仅需使用 Screen 和 Turtle 对
     象时不需要再额外导入 ‘mainloop()’。

   - 新增了两个方法 ‘Screen.textinput()’ 和 ‘Screen.numinput()’。用来弹
     出对话框接受输入并分别返回字符串和数值。

   - 两个新的示例脚本 ‘tdemo_nim.py’ 和 ‘tdemo_round_dance.py’ 被加入到
     ‘Lib/turtledemo’ 目录中。


File: python.info,  Node: cmd --- 支持面向行的命令解释器,  Next: shlex —— 简单的词义分析,  Prev: turtle --- 龜圖學,  Up: 程式框架

5.24.2 ‘cmd’ — 支持面向行的命令解释器
-------------------------------------

`源代码:' Lib/cmd.py(1)

__________________________________________________________________

*note Cmd: 3276. 类提供简单框架用于编写面向行的命令解释器。 这些通常对测
试工具，管理工具和原型有用，这些工具随后将被包含在更复杂的接口中。

 -- 類別: cmd.Cmd (completekey='tab', stdin=None, stdout=None)

     一个 *note Cmd: 3276. 实例或子类实例是面向行的解释器框架结构。 实例
     化 *note Cmd: 3276. 本身是没有充分理由的， 它作为自定义解释器类的超
     类是非常有用的为了继承 *note Cmd: 3276. 的方法并且封装动作方法。

     可选参数 `completekey' 是完成键的 *note readline: de. 名称；默认是
     ‘Tab’ 。如果 `completekey' 不是 *note None: 203. 并且 *note
     readline: de. 是可用的， 命令完成会自动完成。

     可选参数 `stdin' 和 `stdout' 指定了Cmd实例或子类实例将用于输入和输
     出的输入和输出文件对象。如果没有指定，他们将默认为 *note sys.stdin:
     41e. 和 *note sys.stdout: 41f. 。

     如果你想要使用一个给定的 `stdin' ，确保将实例的 *note use_rawinput:
     3277. 属性设置为 ‘False’ ，否则 `stdin' 将被忽略。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/cmd.py


File: python.info,  Node: Cmd 对象,  Next: Cmd 例子,  Up: cmd --- 支持面向行的命令解释器

5.24.2.1 Cmd 对象
.................

*note Cmd: 3276. 实例有下列方法：

 -- 成員函式: Cmd.cmdloop (intro=None)

     反复发出提示，接受输入，从收到的输入中解析出一个初始前缀，并分派给
     操作方法，将其余的行作为参数传递给它们。

     可选参数是在第一个提示之前发布的横幅或介绍字符串（这将覆盖 *note
     intro: 327b. 类属性）。

     如果 *note readline: de. 继承模块被加载，输入将自动继承类似 ‘bash’的
     历史列表编辑（例如， ‘Control-P’ 滚动回到最后一个命令， ‘Control-N’
     转到下一个命令，以 ‘Control-F’ 非破坏性的方式向右 ‘Control-B’ 移动
     光标，破坏性地等）。

     输入的文件结束符被作为字符串传回 ‘'EOF'’ 。

     解释器实例将会识别命令名称 ‘foo’ 当且仅当它有方法 ‘do_foo()’ 。有一
     个特殊情况，分派始于字符 ‘'?'’ 的行到方法 ‘do_help()’ 。另一种特殊
     情况，分派始于字符 ‘'!'’ 的行到方法 ‘do_shell()’ （如果定义了这个方
     法）

     这个方法将返回当 *note postcmd(): 327c. 方法返回一个真值 。参数
     `stop' 到 *note postcmd(): 327c. 是命令对应的返回值 ‘do_*()’ 的方法
     。

     如果激活了完成，全部命令将会自动完成，并且通过调用 ‘complete_foo()’
     参数 `text' , `line', `begidx' ,和 `endidx' 完成全部命令参数。
     `text' 是我们试图匹配的字符串前缀，所有返回的匹配项必须以它为开头。
     `line' 是删除了前导空格的当前的输入行， `begidx' 和 `endidx' 是前缀
     文本的开始和结束索引。，可以用于根据参数位置提供不同的完成。

     所有 *note Cmd: 3276. 的子类继承一个预定义 ‘do_help()’ 。 这个方法
     使用参数 ‘'bar'’ 调用， 调用对应的方法 ‘help_bar()’ ，如果不存在，
     打印 ‘do_bar()’ 的文档字符串，如果可用。没有参数的情况下，
     ‘do_help()’ 方法会列出所有可用的帮助主题 （即所有具有相应的
     ‘help_*()’ 方法或命令的 文档字符串），也会列举所有未被记录的命令。

 -- 成員函式: Cmd.onecmd (str)

     解释该参数，就好像它是为响应提示而键入的一样。 这可能会被覆盖，但通
     常不应该被覆盖; 请参阅： *note precmd(): 327e. 和 *note postcmd():
     327c. 方法，用于执行有用的挂钩。 返回值是一个标志，指示解释器对命令
     的解释是否应该停止。 如果命令 `str' 有一个 ‘do_*()’ 方法，则返回该
     方法的返回值，否则返回 *note default(): 327f. 方法的返回值。

 -- 成員函式: Cmd.emptyline ()

     在响应提示输入空行时调用的方法。如果此方法未被覆盖，则重复输入的最
     后一个非空命令。

 -- 成員函式: Cmd.default (line)

     当命令前缀不能被识别的时候在输入行调用的方法。如果此方法未被覆盖，
     它将输出一个错误信息并返回。

 -- 成員函式: Cmd.completedefault (text, line, begidx, endidx)

     当没有特定于命令的 ‘complete_*()’ 方法可用时，调用此方法完成输入行
     。默认情况下，它返回一个空列表。

 -- 成員函式: Cmd.precmd (line)

     钩方法在命令行 `line' 被解释之前执行，但是在输入提示被生成和发出后
     。这个方法是一个在 *note Cmd: 3276. 中的存根；它的存在是为了被子类
     覆盖。返回值被用作 *note onecmd(): 327d. 方法执行的命令； *note
     precmd(): 327e. 的实现或许会重写命令或者简单的返回 `line' 不变。

 -- 成員函式: Cmd.postcmd (stop, line)

     钩方法只在命令调度完成后执行。这个方法是一个在 *note Cmd: 3276. 中
     的存根；它的存在是为了子类被覆盖。 `line' 是被执行的命令行， `stop'
     是一个表示在调用 *note postcmd(): 327c. 之后是否终止执行的标志；这
     将作为 *note onecmd(): 327d. 方法的返回值。这个方法的返回值被用作与
     `stop' 相关联的内部标志的新值；返回 false 将导致解释继续。

 -- 成員函式: Cmd.preloop ()

     钩方法当 *note cmdloop(): 327a. 被调用时执行一次。方法是一个在
     *note Cmd: 3276. 中的存根；它的存在是为了被子类覆盖。

 -- 成員函式: Cmd.postloop ()

     钩方法在 *note cmdloop(): 327a. 即将返回时执行一次。这个方法是一个
     在 *note Cmd: 3276. 中的存根；它的存在是为了被子类覆盖。

Instances of *note Cmd: 3276. subclasses have some public instance
variables:

 -- 屬性: Cmd.prompt

     发出提示以请求输入。

 -- 屬性: Cmd.identchars

     接受命令前缀的字符串。

 -- 屬性: Cmd.lastcmd

     看到最后一个非空命令前缀。

 -- 屬性: Cmd.cmdqueue

     排队的输入行列表。当需要新的输入时，在 *note cmdloop(): 327a. 中检
     查 cmdqueue 列表；如果它不是空的，它的元素将被按顺序处理，就像在提
     示符处输入一样。

 -- 屬性: Cmd.intro

     要作为简介或横幅发出的字符串。 可以通过给 *note cmdloop(): 327a. 方
     法一个参数来覆盖它。

 -- 屬性: Cmd.doc_header

     如果帮助输出具有记录命令的段落，则发出头文件。

 -- 屬性: Cmd.misc_header

     如果帮助输出其他帮助主题的部分（即与 ‘do_*()’ 方法没有关联的
     ‘help_*()’ 方法），则发出头文件。

 -- 屬性: Cmd.undoc_header

     如果帮助输出未被记录命令的部分（即与 ‘help_*()’ 方法没有关联的
     ‘do_*()’ 方法），则发出头文件。

 -- 屬性: Cmd.ruler

     用于在帮助信息标题的下方绘制分隔符的字符，如果为空，则不绘制标尺线
     。 这个字符默认是 ‘'='’ 。

 -- 屬性: Cmd.use_rawinput

     这是一个标志，默认为 true 。如果为 true ，, *note cmdloop(): 327a.
     使用 *note input(): d33. 先是提示并且阅读下一个命令；如果为 false ，
     ‘sys.stdout.write()’ 和 ‘sys.stdin.readline()’ 被使用。（这意味着解
     释器将会自动支持类似于 ‘Emacs’的行编辑和命令历史记录按键操作，通过
     导入 *note readline: de. 在支持它的系统上。）


File: python.info,  Node: Cmd 例子,  Prev: Cmd 对象,  Up: cmd --- 支持面向行的命令解释器

5.24.2.2 Cmd 例子
.................

The *note cmd: 19. module is mainly useful for building custom shells
that let a user work with a program interactively.

这部分提供了一个简单的例子来介绍如何使用一部分在 *note turtle: 11f. 模块
中的命令构建一个 shell 。

基础的 turtle 命令比如 *note forward(): 31e2. 被添加进一个 *note Cmd:
3276. 子类，方法名为 ‘do_forward()’ 。参数被转换成数字并且分发至 turtle
模组中。 docstring 是 shell 提供的帮助实用程序。

例子也包含使用 *note precmd(): 327e. 方法实现基础的记录和回放的功能，这
个方法负责将输入转换为小写并且将命令写入文件。 ‘do_playback()’ 方法读取
文件并添加记录命令至 ‘cmdqueue’ 用于即时回放:

     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()

这是一个示例会话，其中 turtle shell 显示帮助功能，使用空行重复命令，以及
简单的记录和回放功能：

     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


File: python.info,  Node: shlex —— 简单的词义分析,  Prev: cmd --- 支持面向行的命令解释器,  Up: 程式框架

5.24.3 ‘shlex’ —— 简单的词义分析
--------------------------------

`源代码：' Lib/shlex.py(1)

__________________________________________________________________

*note shlex: 671. 类可用于编写类似 Unix shell 的简单词义分析程序。通常可
用于编写“迷你语言”（如 Python 应用程序的运行控制文件）或解析带引号的字符
串。

*note shlex: e8. 模块中定义了以下函数：

 -- 函式: shlex.split (s, comments=False, posix=True)

     用类似 shell 的语法拆分字符串 `s'。如果 `comments' 为 *note False:
     48e. (默认值)，则不会解析给定字符串中的注释 (*note commenters:
     3290. 属性的 *note shlex: 671. 实例设为空字符串)。 本函数默认工作于
     POSIX 模式下，但若 `posix' 参数为 False，则采用非 POSIX 模式。

          備註: Since the *note split(): 210. function instantiates a
          *note shlex: 671. instance, passing ‘None’ for `s' will read
          the string to split from standard input.

     3.9 版後已棄用: 在以后的 Python 版本中，给 `s' 传入 ‘None’ 将触发异
     常。

 -- 函式: shlex.join (split_command)

     将列表 `split_command' 中的单词串联起来，返回一个字符串。本函数是
     *note split(): 210. 的逆运算。

          >>> from shlex import join
          >>> print(join(['echo', '-n', 'Multiple words']))
          echo -n 'Multiple words'

     为防止注入漏洞，返回值是经过 shell 转义的（参见 *note quote(): b4e.
     ）。

     3.8 版新加入.

 -- 函式: shlex.quote (s)

     返回经过 shell 转义的字符串 `s' 。返回值为字符串，可以安全地作为
     shell 命令行中的单词使用，可用于不能使用列表的场合。

     以下用法是不安全的：

          >>> filename = 'somefile; rm -rf ~'
          >>> command = 'ls -l {}'.format(filename)
          >>> print(command)  # executed by a shell: boom!
          ls -l somefile; rm -rf ~

     用 *note quote(): b4e. 可以堵住这种安全漏洞：

          >>> 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 ~'"'"''

     这种包装方式兼容于 UNIX shell 和 *note split(): 210. 。

          >>> 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 ~']

     3.3 版新加入.

*note shlex: e8. 模块中定义了以下类：

 -- 類別: shlex.shlex (instream=None, infile=None, posix=False,
          punctuation_chars=False)

     *note shlex: 671. 及其子类的实例是一种词义分析器对象。 利用初始化参
     数可指定从哪里读取字符。 初始化参数必须是具备 *note read(): 2162. 和
     *note readline(): 1d5b. 方法的文件/流对象，或者是一个字符串。 如果
     没有给出初始化参数，则会从 ‘sys.stdin’ 获取输入。 第二个可选参数是
     个文件名字符串，用于设置 *note infile: 3291. 属性的初始值。 如果
     `instream' 参数被省略或等于 ‘sys.stdin’，则第二个参数默认为
     "stdin"。 `posix' 参数定义了操作的模式：若 `posix' 不为真值（默认）
     ，则 *note shlex: 671. 实例将工作于兼容模式。 若运行于 POSIX 模式下
     ，则 *note shlex: 671. 会尽可能地应用 POSIX shell 解析规则。
     `punctuation_chars' 参数提供了一种使行为更接近于真正的 shell 解析的
     方式。 该参数可接受多种值：默认值、‘False’、保持 Python 3.5 及更早
     版本的行为。 如果设为 ‘True’，则会改变对字符 ‘();<>|&’ 的解析方式：
     这些字符将作为独立的形符被返回（视作标点符号）。 如果设为非空字符串
     ，则这些字符将被用作标点符号。 出现在 `punctuation_chars' 中的
     *note wordchars: 3292. 属性中的任何字符都会从 *note wordchars:
     3292. 中被删除。 请参阅 *note 改进的 shell 兼容性: 672. 了解详情。
     `punctuation_chars' 只能在创建 *note shlex: 671. 实例时设置，以后不
     能再作修改。

     3.6 版更變: 加入 `punctuation_chars' 参数。

也參考
......

*note configparser: 22. 模块

     配置文件解析器，类似于 Windows 的 ‘.ini’ 文件。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/shlex.py


File: python.info,  Node: shlex 对象,  Next: 解析规则,  Up: shlex —— 简单的词义分析

5.24.3.1 shlex 对象
...................

*note shlex: 671. 实例具备以下方法：

 -- 成員函式: shlex.get_token ()

     返回一个单词。如果所有单词已用 *note push_token(): 3296. 堆叠在一起
     了，则从堆中弹出一个单词。否则就从输入流中读取一个。如果读取时遇到
     文件结束符，则会返回 ‘eof`（在非 POSIX 模式下为空字符串 `’’’‘，在
     POSIX 模式下为 ``None’）。

 -- 成員函式: shlex.push_token (str)

     将参数值压入单词堆栈。

 -- 成員函式: shlex.read_token ()

     读取一个原单词。忽略堆栈，且不解释源请求。（通常没什么用，只是为了
     完整起见。）

 -- 成員函式: shlex.sourcehook (filename)

     当 *note shlex: 671. 检测到源请求（见下面的 *note source: 3299.），
     本方法被赋予以下单词作为参数，并应返回一个由文件名和打开的文件对象
     组成的元组。

     通常本方法会先移除参数中的引号。如果结果为绝对路径名，或者之前没有
     有效的源请求，或者之前的源请求是一个流对象（比如 ‘sys.stdin’），那
     么结果将不做处理。否则，如果结果是相对路径名，那么前面将会加上目录
     部分，目录名来自于源堆栈中前一个文件名（类似于 C 预处理器对
     ‘#include "file.h"’ 的处理方式）。

     结果被视为一个文件名，并作为元组的第一部分返回，元组的第二部分以此
     为基础调用 *note open(): 16f. 获得。（注意：这与实例初始化中的参数
     顺序相反！)

     此钩子函数是公开的，可用于实现路径搜索、添加文件扩展名或黑入其他命
     名空间。没有对应的“关闭”钩子函数，但 shlex 实例在返回 EOF 时会调用
     源输入流的 *note close(): 1147. 方法。

     若要更明确地控制源堆栈，请采用 *note push_source(): 329a. 和 *note
     pop_source(): 329b. 方法。

 -- 成員函式: shlex.push_source (newstream, newfile=None)

     将输入源流压入输入堆栈。如果指定了文件名参数，以后错误信息中将会用
     到。这与 *note sourcehook(): 3298. 内部使用的方法相同。

 -- 成員函式: shlex.pop_source ()

     从输入堆栈中弹出最后一条输入源。当遇到输入流的 EOF 时，内部也使用同
     一方法。

 -- 成員函式: shlex.error_leader (infile=None, lineno=None)

     本方法生成一条错误信息的首部，以 Unix C 编译器错误标签的形式；格式
     为‘‘’"%s", line %d: ’‘，其中 ``%s’ 被替换为当前源文件的名称，‘%d’ 被
     替换为当前输入行号（可用可选参数覆盖）。

     这是个快捷函数，旨在鼓励 *note shlex: e8. 用户以标准的、可解析的格
     式生成错误信息，以便 Emacs 和其他 Unix 工具理解。

*note shlex: 671. 子类的实例有一些公共实例变量，这些变量可以控制词义分析
，也可用于调试。

 -- 屬性: shlex.commenters

     将被视为注释起始字符串。从注释起始字符串到行尾的所有字符都将被忽略
     。默认情况下只包括 ‘'#'’。

 -- 屬性: shlex.wordchars

     可连成多字符单词的字符串。默认包含所有 ASCII 字母数字和下划线。在
     POSIX 模式下，Latin-1 字符集的重音字符也被包括在内。如果 *note
     punctuation_chars: 10d9. 不为空，则可出现在文件名规范和命令行参数中
     的 ‘~-./*?=’ 字符也将包含在内，任何 ‘punctuation_chars’ 中的字符将
     从 ‘wordchars’ 中移除。如果 *note whitespace_split: 329d. 设为
     ‘True’，则本规则无效。

 -- 屬性: shlex.whitespace

     将被视为空白符并跳过的字符。空白符是单词的边界。默认包含空格、制表
     符、换行符和回车符。

 -- 屬性: shlex.escape

     将视为转义字符。仅适用于 POSIX 模式，默认只包含 ‘'\'’。

 -- 屬性: shlex.quotes

     将视为引号的字符。单词中的字符将会累至再次遇到同样的引号（因此，不
     同的引号会像在 shell 中一样相互包含。）默认包含 ASCII 单引号和双引
     号。

 -- 屬性: shlex.escapedquotes

     *note quotes: 32a0. 中的字符将会解析 *note escape: 329f. 定义的转义
     字符。这只在 POSIX 模式下使用，默认只包含 ‘'"'’。

 -- 屬性: shlex.whitespace_split

     若为 ‘True’，则只根据空白符拆分单词。这很有用，比如用 *note shlex:
     671. 解析命令行，用类似 shell 参数的方式读取各个单词。当与 *note
     punctuation_chars: 10d9. 一起使用时，将根据空白符和这些字符拆分单词
     。

     3.8 版更變: *note punctuation_chars: 10d9. 属性已与 *note
     whitespace_split: 329d. 属性兼容。

 -- 屬性: shlex.infile

     当前输入的文件名，可能是在类实例化时设置的，或者是由后来的源请求堆
     栈生成的。在构建错误信息时可能会用到本属性。

 -- 屬性: shlex.instream

     *note shlex: 671. 实例正从中读取字符的输入流。

 -- 屬性: shlex.source

     本属性默认值为 ‘None’。 如果给定一个字符串，则会识别为包含请求，类
     似于各种 shell 中的 ‘source’ 关键字。 也就是说，紧随其后的单词将作
     为文件名打开，作为输入流，直至遇到 EOF 后调用流的 *note close():
     1147. 方法，然后原输入流仍变回输入源。Source 请求可以在词义堆栈中嵌
     套任意深度。

 -- 屬性: shlex.debug

     如果本属性为大于 ‘1’ 的数字，则 *note shlex: 671. 实例会把动作进度
     详细地输出出来。若需用到本属性，可阅读源代码来了解细节。

 -- 屬性: shlex.lineno

     源的行数（到目前为止读到的换行符数量加 1）。

 -- 屬性: shlex.token

     单词缓冲区。在捕获异常时可能会用到。

 -- 屬性: shlex.eof

     用于确定文件结束的单词。在非 POSIX 模式下，将设为空字符串 ‘''’，在
     POSIX 模式下被设为 ‘None’。

 -- 屬性: shlex.punctuation_chars

     只读属性。表示应视作标点符号的字符。标点符号将作为单个单词返回。然
     而，请注意不会进行语义有效性检查：比如 “>>>” 可能会作为一个单词返回
     ，虽然 shell 可能无法识别。

     3.6 版新加入.


File: python.info,  Node: 解析规则,  Next: 改进的 shell 兼容性,  Prev: shlex 对象,  Up: shlex —— 简单的词义分析

5.24.3.2 解析规则
.................

在非 POSIX 模式下时，*note shlex: 671. 会试图遵守以下规则：

   * 不识别单词中的引号（‘Do"Not"Separate’ 解析为一个单词
     ‘Do"Not"Separate’）。

   * 不识别转义字符；

   * 引号包裹的字符保留字面意思。

   * 成对的引号会将单词分离（‘"Do"Separate’ 解析为 ‘"Do"’ 和 ‘Separate’）
     。

   * 如果 *note whitespace_split: 329d. 为 ‘False’，则未声明为单词字符、
     空白或引号的字符将作为单字符标记返回。若为 ‘True’， 则 *note shlex:
     671. 只根据空白符拆分单词。

   * EOF 用空字符串（‘''’）表示；

   * 空字符串无法解析，即便是加了引号。

在 POSIX 模式时，*note shlex: 671. 将尝试遵守以下解析规则：

   * 引号会被剔除，且不会拆分单词（ ‘"Do"Not"Separate"’ 将解析为单个单词
     ‘DoNotSeparate’）。

   * 未加引号包裹的转义字符（如 ‘'\'’ ）保留后一个字符的字面意思；

   * 引号中的字符不属于 *note escapedquotes: 32a1. （例如，‘"'"’），则保
     留引号中所有字符的字面值。

   * 若引号包裹的字符属于 *note escapedquotes: 32a1. （例如 ‘'"'’），则
     保留引号中所有字符的字面意思，属于 *note escape: 329f. 中的字符除外
     。仅当后跟后半个引号或转义字符本身时，转义字符才保留其特殊含义。否
     则，转义字符将视作普通字符。

   * EOF 用 *note None: 203. 表示。

   * 允许出现引号包裹的空字符串（‘''’）。


File: python.info,  Node: 改进的 shell 兼容性,  Prev: 解析规则,  Up: shlex —— 简单的词义分析

5.24.3.3 改进的 shell 兼容性
............................

3.6 版新加入.

*note shlex: e8. 类提供了与常见 Unix shell（如 ‘bash’、‘dash’ 和‘‘sh‘‘）
的解析兼容性。为了充分利用这种兼容性，请在构造函数中设定
‘punctuation_chars’ 参数。该参数默认为 ‘False’，维持 3.6 以下版本的行为
。如果设为 ‘True’，则会改变对 ‘();<>|&’ 字符的解析方式：这些字符都将视为
单个标记返回。虽然不算是完整的 shell 解析程序（考虑到 shell 的多样性，超
出了标准库的范围），但确实能比其他方式更容易进行命令行的处理。以下代码段
演示了两者的差异：

      >>> 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', ')']

当然，返回的词法单元对 shell 无效，需要对返回的词法单元自行进行错误检查
。

punctuation_chars 参数可以不传入 ‘True’ ，而是传入包含特定字符的字符串，
用于确定由哪些字符构成标点符号。例如：

     >>> import shlex
     >>> s = shlex.shlex("a && b || c", punctuation_chars="|")
     >>> list(s)
     ['a', '&', '&', 'b', '||', 'c']

     備註: 如果指定了 ‘punctuation_chars’，则 *note wordchars: 3292. 属
     性的参数会是 ‘~-./*?=’。因为这些字符可以出现在文件名（包括通配符）
     和命令行参数中（如 ‘--color=auto’）。因此：

          >>> import shlex
          >>> s = shlex.shlex('~/a && b-c --color=auto || d *.py?',
          ...                 punctuation_chars=True)
          >>> list(s)
          ['~/a', '&&', 'b-c', '--color=auto', '||', 'd', '*.py?']

     不过为了尽可能接近于 shell ，建议在使用 *note punctuation_chars:
     10d9. 时始终使用 ‘posix’ 和 *note whitespace_split: 329d. ，这将完
     全否定 *note wordchars: 3292. 。

为了达到最佳效果，‘punctuation_chars’ 应与 ‘posix=True’ 一起设置。（注意
‘posix=False’ 是 *note shlex: 671. 的默认设置)。


File: python.info,  Node: 以 Tk 打造 GUI,  Next: 開發工具,  Prev: 程式框架,  Up: Python 標準函式庫 Standard Library

5.25 以 Tk 打造 GUI
===================

Tcl/Tk集成到Python中已经有一些年头了。Python程序员可以通过 *note
tkinter: 10e. 包和它的扩展， *note tkinter.tix: 117. 模块和 *note
tkinter.ttk: 118. 模块，来使用这套鲁棒的、平台无关的窗口工具集。

*note tkinter: 10e. 包是使用面向对象方式对 Tcl/Tk 进行的一层薄包装。 使
用 *note tkinter: 10e.，你不需要写 Tcl 代码，但你将需要参阅 Tk 文档，有
时还需要参阅 Tcl 文档。 *note tkinter: 10e. 是一组包装器，它将 Tk 的可视
化部件实现为相应的 Python 类。

*note tkinter: 10e. 的主要特点是速度很快，并且通常直接附带在 Python 中。
虽然它的官方文档做得不好，但还是有许多可用的资源，包括：在线参考、教程、
入门书等等。 *note tkinter: 10e. 还有众所周知的较过时的外观界面，这在 Tk
8.5 中已得到很大改进。 无论如何，你还可以考虑许多其他的 GUI 库。 Python
wiki 例出了一些替代性的 GUI 框架和工具(1)。

* 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<51>.

   ---------- Footnotes ----------

   (1) https://wiki.python.org/moin/GuiProgramming


File: python.info,  Node: tkinter --- Tcl/Tk的Python接口,  Next: tkinter colorchooser --- 颜色选择对话框,  Up: 以 Tk 打造 GUI

5.25.1 ‘tkinter’ — Tcl/Tk的Python接口
-------------------------------------

`源代码:' Lib/tkinter/__init__.py(1)

__________________________________________________________________

The *note tkinter: 10e. package ("Tk interface") is the standard Python
interface to the Tcl/Tk GUI toolkit.  Both Tk and *note tkinter: 10e.
are available on most Unix platforms, including macOS, as well as on
Windows systems.

在命令行中运行 ‘python -m tkinter’，应该会弹出一个Tk界面的窗口，表明
*note tkinter: 10e. 包已经正确安装，而且告诉你 Tcl/Tk 的版本号，通过这个
版本号，你就可以参考对应的 Tcl/Tk 文档了。

也參考
......

   * 
     TkDocs(2)

          Extensive tutorial on creating user interfaces with Tkinter.
          Explains key concepts, and illustrates recommended approaches
          using the modern API.

   * 
     Tkinter 8.5 参考：一个Python图形用户界面(3)

          Reference documentation for Tkinter 8.5 detailing available
          classes, methods, and options.

Tcl/Tk Resources:

   * 
     Tk 命令(4)

          Comprehensive reference to each of the underlying Tcl/Tk
          commands used by Tkinter.

   * 
     Tcl/Tk Home Page(5)

          Additional documentation, and links to Tcl/Tk core
          development.

Books:

   * 
     Modern Tkinter for Busy Python Developers(6)

          By Mark Roseman.  (ISBN 978-1999149567)

   * 
     Python and Tkinter Programming(7)

          By Alan Moore.  (ISBN 978-1788835886)

   * 
     使用 Python 编程(8)

          By Mark Lutz; has excellent coverage of Tkinter.  (ISBN
          978-0596158101)

   * 
     Tcl and the Tk Toolkit (2nd edition)(9)

          By John Ousterhout, inventor of Tcl/Tk, and Ken Jones; does
          not cover Tkinter.  (ISBN 978-0321336330)

* Menu:

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

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/Lib/tkinter/__init__.py

   (2) http://tkdocs.com/

   (3) https://www.tkdocs.com/shipman/

   (4) https://www.tcl.tk/man/tcl8.6/TkCmd/contents.htm

   (5) https://www.tcl.tk

   (6) https://tkdocs.com/book.html

   (7) 
https://www.packtpub.com/product/python-gui-programming-with-tkinter/9781788835886

   (8) http://learning-python.com/about-pp4e.html

   (9) https://www.amazon.com/exec/obidos/ASIN/032133633X


File: python.info,  Node: Tkinter 模块,  Next: Tkinter 拾遗,  Up: tkinter --- Tcl/Tk的Python接口

5.25.1.1 Tkinter 模块
.....................

Support for Tkinter is spread across several modules.  Most applications
will need the main *note tkinter: 10e. module, as well as the *note
tkinter.ttk: 118. module, which provides the modern themed widget set
and API:

     from tkinter import *
     from tkinter import ttk

 -- 類別: tkinter.Tk (screenName=None, baseName=None, className='Tk',
          useTk=1)

     *note Tk: 32b0. 类被初始化时无参数。此时会创建一个 Tk 顶级控件，通
     常是应用程序的主窗口。每个实例都有自己关联的 Tcl 解释器。

 -- 函式: tkinter.Tcl (screenName=None, baseName=None, className='Tk',
          useTk=0)

     *note Tcl(): 32b1. 函数是一个工厂函数，它创建的对象与 *note Tk:
     32b0. 类创建的对象非常相似，只是它不初始化 Tk 子系统。 在不想创建或
     无法创建（如没有 X Server 的 Unix/Linux 系统）额外的顶层窗口的环境
     中驱动 Tcl 解释器时，这一点非常有用。 由 *note Tcl(): 32b1. 对象创
     建的对象可以通过调用其 ‘loadtk()’ 方法来创建顶层窗口（并初始化 Tk 子
     系统）。

The modules that provide Tk support include:

*note tkinter: 10e.

     Main Tkinter module.

*note tkinter.colorchooser: 10f.

     让用户选择颜色的对话框。

*note tkinter.commondialog: 110.

     在此处列出的其他模块中定义的对话框的基类。

*note tkinter.filedialog: 112.

     允许用户指定文件的通用对话框，用于打开或保存文件。

*note tkinter.font: 113.

     帮助操作字体的工具。

*note tkinter.messagebox: 114.

     访问标准的 Tk 对话框。

*note tkinter.scrolledtext: 115.

     内置纵向滚动条的文本组件。

*note tkinter.simpledialog: 116.

     基础对话框和便捷功能。

*note tkinter.ttk: 118.

     Themed widget set introduced in Tk 8.5, providing modern
     alternatives for many of the classic widgets in the main *note
     tkinter: 10e. module.

Additional modules:

‘_tkinter’

     A binary module that contains the low-level interface to Tcl/Tk.
     It is automatically imported by the main *note tkinter: 10e.
     module, and should never be used directly by application
     programmers.  It is usually a shared library (or DLL), but might in
     some cases be statically linked with the Python interpreter.

‘idlelib’

     Python’s Integrated Development and Learning Environment (IDLE).
     Based on *note tkinter: 10e.

‘tkinter.constants’

     Symbolic constants that can be used in place of strings when
     passing various parameters to Tkinter calls.  Automatically
     imported by the main *note tkinter: 10e. module.

*note tkinter.dnd: 111.

     (experimental) Drag-and-drop support for *note tkinter: 10e.  This
     will become deprecated when it is replaced with the Tk DND.

*note tkinter.tix: 117.

     (deprecated) An older third-party Tcl/Tk package that adds several
     new widgets.  Better alternatives for most can be found in *note
     tkinter.ttk: 118.

*note turtle: 11f.

     Tk 窗口中的海龟绘图库。


File: python.info,  Node: Tkinter 拾遗,  Next: Tcl/Tk 速览,  Prev: Tkinter 模块,  Up: tkinter --- Tcl/Tk的Python接口

5.25.1.2 Tkinter 拾遗
.....................

本节不应作为 Tk 或 Tkinter 的详尽教程。而只是一个补充，提供一些系统指南
。

Credits:

   * Tk 是 John Ousterhout 在伯克利大学时写的。

   * Tkinter 是由 Steen Lumholt 和 Guido van Rossum 编写的。

   * 本拾遗由弗吉尼亚大学的 Matt Conway 撰写。

   * HTML 渲染和一些自由编辑功能，是由 Ken Manheimer 根据 FrameMaker 创
     建的。

   * Fredrik Lundh 认真研究并修改了类的接口描述，使其与 Tk 4.2 保持一致
     。

   * Mike Clarkson 将文档转换为 LaTeX 格式，并编写了参考手册的用户界面章
     节。

* Menu:

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


File: python.info,  Node: 本节内容的用法,  Next: 简单的 Hello World 程序,  Up: Tkinter 拾遗

5.25.1.3 本节内容的用法
.......................

本节分为两部分：前半部分（大致）涵盖了背景材料，后半部分可以作为手头的参
考手册。

当试图回答“如何才能怎么怎么”这种问题时，通常最好是弄清楚如何直接在 Tk 中
实现，然后转换回相应的 *note tkinter: 10e. 调用。Python 程序员通常可查看
Tk 文档来猜测正确的 Python 命令。这意味着要用好 Tkinter，必须对 Tk 有一
定的了解。本文无法完成这个任务，所以最好的做法就是给出目前最好的文档。下
面给出一些小提示：

   * 作者强烈建议用户先拿到一份 Tk 手册。具体来说，‘manN’ 目录下的 man 文
     档是最有用的。‘man3’ 的 man 文档描述了 Tk 库的 C 接口，因此对脚本编
     写人员没有什么特别的帮助。

   * Addison-Wesley 出版了一本名为《Tcl 和 Tk 工具包》的书，作者是 John
     Ousterhout（ISBN 0-201-63337-X），对于新手来说，这是一本很好的 Tcl
     和Tk 介绍书籍。该书不算详尽，很多细节还是要看 man 手册。

   * 对大多数人而言，‘tkinter/__init__.py’ 是最后一招，但其他手段都无效
     时也不失为一个好去处。


File: python.info,  Node: 简单的 Hello World 程序,  Prev: 本节内容的用法,  Up: Tkinter 拾遗

5.25.1.4 简单的 Hello World 程序
................................

     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()


File: python.info,  Node: Tcl/Tk 速览,  Next: 将简单的 Tk 映射到 Tkinter,  Prev: Tkinter 拾遗,  Up: tkinter --- Tcl/Tk的Python接口

5.25.1.5 Tcl/Tk 速览
....................

类的层次结构看起来很复杂，但在实际操作中，应用程序编写人员几乎总是查看最
底层的类。

註解：

   * 提供这些类，是为了能在同一个命名空间下将某些功能组织在一起。并不意
     味着可以独立对其进行实例化。

   * *note Tk: 32b0. 类在同一个应用程序中仅需作一次实例化。应用程序编程
     人员不需要显式进行实例化，只要有其他任何类被实例化，系统就会创建一
     个。

   * ‘Widget’ 类不是用来实例化的，它仅用于继承以便生成“真正”的部件（ C++
     中称为“抽象类”）。

若要充分利用这些参考资料，有时需要知道如何阅读 Tk 的短文，以及如何识别
Tk 命令的各个部分。（参见 *note 将简单的 Tk 映射到 Tkinter: 32b6. 一节，
了解以下内容在 *note tkinter: 10e. 中的对应部分）。

Tk 脚本就是 Tcl 程序。像所有其他的 Tcl 程序一样，Tk 脚本只是由空格分隔的
单词列表。一个Tk 部件只是它的 `class'，`options' 用于进行配置，`actions'
让它执行有用的动作。

要在 Tk 中制作一个部件，总是采用如下格式的命令：

     classCommand newPathname options

`classCommand'

     表示要制作何种部件（按钮、标签、菜单......）。

`newPathname'

     该组件的新名字。Tk 中的所有名字都必须唯一。为了帮助实现这一点，Tk 中
     的部件都用 `路径' 命名，就像文件系统中的文件一样。顶层的部件，即 `根
     '，名为 ‘.``（句点），而子部件则由更多的句点分隔。比如部件名可能会
     是 ``.myApp.controlPanel.okButton’ 。

`options'

     配置部件的外观，有时也能配置行为。这些选项以标志和值的列表形式出现
     。标志前带一个“-”，就像 Unix shell 命令的标志一样，如果值超过一个单
     词，就用引号括起来。

例如:

     button   .fred   -fg red -text "hi there"
        ^       ^     \______________________/
        |       |                |
      class    new            options
     command  widget  (-opt val -opt val ...)

一旦创建成功，部件的路径名就成了一条新的命令。这个新的 `部件命令' 是程序
员让新部件执行某些 `action' 的句柄。在 C 语言中可表示为someAction(fred,
someOptions)，在 C++ 中可表示为fred.someAction(someOptions)，而在 Tk 中
写作：

     .fred someAction someOptions

请注意，对象名 ‘.fred’ 是以句点开头的。

如您所料，`someAction' 的可用值取决于部件的类别。如果 fred 为按钮，则
‘.fred disable’ 有效（fred 会变灰），而当 fred 为标签时则无效（Tk 不支持
标签的禁用）。

`someOptions' 的合法值取决于动作。有些动作不需要参数，比如 ‘disable’，其
他动作如文本输入框的 ‘delete’ 命令则需用参数指定要删除的文本范围。


File: python.info,  Node: 将简单的 Tk 映射到 Tkinter,  Next: Tk 和 Tkinter 如何关联,  Prev: Tcl/Tk 速览,  Up: tkinter --- Tcl/Tk的Python接口

5.25.1.6 将简单的 Tk 映射到 Tkinter
...................................

Tk 中的类命令对应于 Tkinter 中的类构造函数：

     button .fred                =====>  fred = Button()

父对象是隐含在创建时给定的新名字中的。在 Tkinter 中，父对象是显式指定的
：

     button .panel.fred          =====>  fred = Button(panel)

Tk 中的配置项是以连字符标签列表的形式给出的，后跟着参数值。在 Tkinter 中
，选项指定为实例构造函数中的关键字参数，在配置调用时指定为关键字 args，
或在已有实例中指定为实例索引，以字典的形式。参见 *note 可选配置项: 32b8.
一节的选项设置部分。

     button .fred -fg red        =====>  fred = Button(panel, fg="red")
     .fred configure -fg red     =====>  fred["fg"] = red
                                 OR ==>  fred.config(fg="red")

在 Tk 中, 要在某个部件上执行动作, 要用部件名作为命令, 并后面附上动作名称
, 可能还会带有参数（option）。在 Tkinter 中，则调用类实例的方法来执行部
件的动作。部件能够执行的动作（方法）列在 ‘tkinter/__init__.py’ 中。

     .fred invoke                =====>  fred.invoke()

若要将部件交给打包器（geometry manager），需带上可选参数去调用 pack。在
Tkinter 中，Pack 类拥有全部这些功能，pack 命令的各种形式都以方法的形式实
现。 *note tkinter: 10e. 中的所有部件都是从 Packer 继承而来的，因此继承
了所有打包方法。关于Form geometry manager 的更多信息，请参见 *note
tkinter.tix: 117. 模块的文档。

     pack .fred -side left       =====>  fred.pack(side="left")


File: python.info,  Node: Tk 和 Tkinter 如何关联,  Next: 快速参考,  Prev: 将简单的 Tk 映射到 Tkinter,  Up: tkinter --- Tcl/Tk的Python接口

5.25.1.7 Tk 和 Tkinter 如何关联
...............................

自上而下：

（Python）应用程序位于这里

     Python 应用程序进行了 *note tkinter: 10e. 调用。

tkinter （Python 包）

     此调用（比如创建一个按钮部件）在 *note tkinter: 10e. 包中实现，它是
     用 Python 编写的。该 Python 函数将解析命令和参数，并转换为貌似 Tk 脚
     本的格式，而不像是 Python 脚本。

_tkinter（C 语言）

     这些命令及参数将被传给 ‘_tkinter’ 扩展模块中的 C 函数——注意下划线。

Tk 部件（C 和 Tcl）

     该 C 函数能调用其他的 C 模块，包括构成 Tk 库的 C 函数。Tk 是用 C 和
     一些 Tcl 实现的。Tk 部件的 Tcl 部分用于将某些默认行为绑定到部件上，
     并在导入 Python *note tkinter: 10e. 包时执行一次。（该阶段对用户而
     言永不可见）。

Tk（C 语言）

     Tk 部件的 Tk 语言部分实现了最终的映射

Xlib（C 语言）

     Xlib 库在屏幕上绘制图形。


File: python.info,  Node: 快速参考,  Next: File Handlers,  Prev: Tk 和 Tkinter 如何关联,  Up: tkinter --- Tcl/Tk的Python接口

5.25.1.8 快速参考
.................

* Menu:

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


File: python.info,  Node: 可选配置项,  Next: The Packer,  Up: 快速参考

5.25.1.9 可选配置项
...................

配置参数可以控制组件颜色和边框宽度等。可通过三种方式进行设置：

在对象创建时，使用关键字参数

          fred = Button(self, fg="red", bg="blue")

在对象创建后，将参数名用作字典索引

          fred["fg"] = "red"
          fred["bg"] = "blue"

利用 config() 方法修改对象的属性

          fred.config(fg="red", bg="blue")

关于这些参数及其表现的完整解释，请参阅 Tk 手册中有关组件的 man 帮助页。

请注意，man 手册页列出了每个部件的“标准选项”和“组件特有选项”。前者是很多
组件通用的选项列表，后者是该组件特有的选项。标准选项在 ‘options(3)’ man
手册中有文档。

本文没有区分标准选项和部件特有选项。有些选项不适用于某类组件。组件是否对
某选项做出响应，取决于组件的类别；按钮组件有一个 ‘command’ 选项，而标签
组件就没有。

组件支持的选项在其手册中有列出，也可在运行时调用 ‘config()’ 方法（不带参
数）查看，或者通过调用组件的 ‘keys()’ 方法进行查询。这些调用的返回值为字
典，字典的键是字符串格式的选项名（比如 ‘'relief'’），字典的值为五元组。

有些选项，比如 ‘bg’ 是全名通用选项的同义词（‘bg’ 是 “background”的简写）
。向 ‘config()’ 方法传入选项的简称将返回一个二元组，而不是五元组。传回的
二元组将包含同义词的全名和“真正的”选项（比如 ‘('bg', 'background')’）。

索引        意义                                  示例
                                                  
---------------------------------------------------------------------
                                                  
0           选项名称                              ‘'relief'’
                                                  
                                                  
1           数据库查找的选项名称                  ‘'relief'’
                                                  
                                                  
2           数据库查找的选项类                    ‘'Relief'’
                                                  
                                                  
3           默认值                                ‘'raised'’
                                                  
                                                  
4           当前值                                ‘'groove'’
                                                  

示例:

     >>> print(fred.config())
     {'relief': ('relief', 'relief', 'Relief', 'raised', 'groove')}

当然，输出的字典将包含所有可用选项及其值。这里只是举个例子。


File: python.info,  Node: The Packer,  Next: 包装器的参数,  Prev: 可选配置项,  Up: 快速参考

5.25.1.10 The Packer
....................

包装器是 Tk 的形状管理机制之一。 形状管理器用于指定部件在容器内的相对位
置——彼此的 `宿主' 关系。与更为麻烦的 `定位器' 相比（不太常用，这里不做介
绍），包装器可接受定性的相对关系—— `上面' 、`左边' 、`填充' 等，并确定精
确的放置坐标。

`主' 部件的大小都由其内部的 “从属部件” 的大小决定。包装器用于控制从属部
件在主部件中出现的位置。可以把部件包入框架，再把框架包入其他框架中，搭建
出所需的布局。此外，只要完成了包装，组件的布局就会进行动态调整，以适应布
局参数的变化。

请注意，只有用形状管理器指定几何形状后，部件才会显示出来。忘记设置形状参
数是新手常犯的错误，惊讶于创建完部件却啥都没出现。部件只有在应用了类似于
打包器的 ‘pack()’ 方法之后才会显示在屏幕上。

调用 pack() 方法时可以给出由关键字/参数值组成的键值对，以便控制组件在其
容器中出现的位置，以及主程序窗口大小变动时的行为。下面是一些例子：

     fred.pack()                     # defaults to side = "top"
     fred.pack(side="left")
     fred.pack(expand=1)


File: python.info,  Node: 包装器的参数,  Next: 部件与变量的关联,  Prev: The Packer,  Up: 快速参考

5.25.1.11 包装器的参数
......................

关于包装器及其可接受的参数，更多信息请参阅 man 手册和 John Ousterhout 书
中的第 183 页。

anchor

     锚点类型。 表示包装器要放置的每个从属组件的位置。

expand

     布尔型，‘0’ 或 ‘1’ 。

fill

     合法值为：‘'x'’ 、‘'y'’ 、‘'both'’ 、‘'none'’。

ipadx 和 ipady

     距离值，指定从属部件每一侧的内边距。

padx 和 pady

     距离值，指定从属部件的外边距。

side

     合法值为：‘'left'’、 ‘'right'’ 、 ‘'top'’、 ‘'bottom'’。


File: python.info,  Node: 部件与变量的关联,  Next: 窗口管理器,  Prev: 包装器的参数,  Up: 快速参考

5.25.1.12 部件与变量的关联
..........................

通过一些特定参数，某些组件（如文本输入组件）的当前设置可直接与应用程序的
变量关联。这些参数包括 ‘variable’ 、 ‘textvariable’ 、 ‘onvalue’ 、
‘offvalue’ 、 ‘value’。这种关联是双向的：只要这些变量因任何原因发生变化
，其关联的部件就会更新以反映新的参数值。

不幸的是，在目前 *note tkinter: 10e. 的实现代码中，不可能通过 ‘variable’
或 ‘textvariable’ 参数将任意 Python 变量移交给组件。变量只有是 *note
tkinter: 10e. 中定义的 Variable 类的子类，才能生效。

已经定义了很多有用的 Variable 子类： ‘StringVar’ 、 ‘IntVar’ 、
‘DoubleVar’ 和 ‘BooleanVar’。调用 ‘get()’ 方法可以读取这些变量的当前值；
调用 ‘set()’ 方法则可改变变量值。只要遵循这种用法，组件就会保持跟踪变量
的值，而不需要更多的干预。

例如:

     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()


File: python.info,  Node: 窗口管理器,  Next: Tk 参数的数据类型,  Prev: 部件与变量的关联,  Up: 快速参考

5.25.1.13 窗口管理器
....................

Tk 有个实用命令 ‘wm’，用于与窗口管理器进行交互。‘wm’ 命令的参数可用于控
制标题、位置、图标之类的东西。在 *note tkinter: 10e. 中，这些命令已被实
现为 ‘Wm’ 类的方法。顶层部件是 ‘Wm’ 类的子类，所以可以直接调用 ‘Wm’ 的这
些方法。

要获得指定部件所在的顶层窗口，通常只要引用该部件的主窗口即可。当然，如果
该部件是包装在框架内的，那么主窗口不代表就是顶层窗口。为了获得任意组件所
在的顶层窗口，可以调用 ‘_root()’ 方法。该方法以下划线开头，表明其为
Python 实现的代码，而非 Tk 提供的某个接口。

以下是一些典型用法：

     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()


File: python.info,  Node: Tk 参数的数据类型,  Next: 绑定和事件,  Prev: 窗口管理器,  Up: 快速参考

5.25.1.14 Tk 参数的数据类型
...........................

anchor

     合法值是罗盘的方位点：‘"n"’ 、‘"ne"’ 、‘"e"’ 、‘"se"’ 、‘"s"’ 、
     ‘"sw"’ 、‘"w"’ 、‘"nw"’ 和 ‘"center"’

位图

     内置已命名的位图有八个：‘'error'’、 ‘'gray25'’ 、‘'gray50'’ 、
     ‘'hourglass'’、 ‘'info'’ 、‘'questhead'’ 、‘'question'’ 、
     ‘'warning'’ 。若要指定位图的文件名，请给出完整路径，前面加一个 ‘@’，
     比如 ‘"@/usr/contrib/bitmap/gumby.bit"’。

布尔值

     可以传入整数 0 或 1，或是字符串 ‘"yes"’ 或 ‘"no"’。

callback – 回调

     指任何无需调用参数的 Python 函数。 例如：

          def print_it():
              print("hi there")
          fred["command"] = print_it

color

     可在 rgb.txt 文件中以颜色名的形式给出，或是 RGB 字符串的形式，4 位
     ：‘"#RGB"’ ，8 位 ：‘"#RRGGBB"’，12 位：‘"#RRRGGGBBB"’，16 位：
     ‘"#RRRRGGGGBBBB"’，其中R、G、B 为合法的十六进制数值。 详见
     Ousterhout 书中的第 160 页。

cursor

     可采用 ‘cursorfont.h’ 中的标准光标名称，去掉 ‘XC_’ 前缀。 比如要获
     取一个手形光标（‘XC_hand2’），可以用字符串 ‘"hand2"’。也可以指定自
     己的位图和掩码文件作为光标。参见 Ousterhout 书中的第 179 页。

distance

     屏幕距离可以用像素或绝对距离来指定。像素是数字，绝对距离是字符串，
     后面的字符表示单位：‘c’ 是厘米，‘i’ 是英寸，‘m’ 是毫米，‘p’ 则表示
     打印机的点数。例如，3.5 英寸可表示为 ‘"3.5i"’。

font

     Tk 采用一串名称的格式表示字体，例如 ‘{courier 10 bold}’。正数的字体
     大小以点为单位，负数的大小以像素为单位。

geometry

     这是一个 ‘widthxheight’ 形式的字符串，其中宽度和高度对于大多数部件
     来说是以像素为单位的（对于显示文本的部件来说是以字符为单位的）。例
     如：fred["geometry"] = "200x100"。

justify

     合法的值为字符串： ‘"left"’ 、 ‘"center"’ 、 ‘"right"’ 和 ‘"fill"’
     。

region

     这是包含四个元素的字符串，以空格分隔，每个元素是表示一个合法的距离
     值（见上文）。例如：‘"2 3 4 5"’ 、 ‘"3i 2i 4.5i 2i"’ 和 ‘"3c 2c 4c
     10.43c"’ 都是合法的区域值。

relief

     决定了组件的边框样式。 合法值包括：‘"raised"’、 ‘"sunken"’ 、
     ‘"flat"’ 、‘"groove"’ 和 ‘"ridge"’ 。

scrollcommand

     这几乎就是带滚动条部件的 ‘set()’ 方法，但也可是任一只有一个参数的部
     件方法。

wrap

     只能是以下值之一：‘"none"’ 、 ‘"char"’ 、 ‘"word"’。


File: python.info,  Node: 绑定和事件,  Next: The index Parameter,  Prev: Tk 参数的数据类型,  Up: 快速参考

5.25.1.15 绑定和事件
....................

部件命令中的 bind 方法可觉察某些事件，并在事件发生时触发一个回调函数。
bind 方法的形式是：

     def bind(self, sequence, func, add=''):

这里：

序列

     是一个表示事件的目标种类的字符串。（详情请看 bind 的手册页和 John
     Outsterhout 的书的第 201 页。）

func

     is a Python function, taking one argument, to be invoked when the
     event occurs.  An Event instance will be passed as the argument.
     (Functions deployed this way are commonly known as `callbacks'.)

add

     is optional, either ‘''’ or ‘'+'’.  Passing an empty string denotes
     that this binding is to replace any other bindings that this event
     is associated with.  Passing a ‘'+'’ means that this function is to
     be added to the list of functions bound to this event type.

例如:

     def turn_red(self, event):
         event.widget["activeforeground"] = "red"

     self.button.bind("<Enter>", self.turn_red)

Notice how the widget field of the event is being accessed in the
‘turn_red()’ callback.  This field contains the widget that caught the X
event.  The following table lists the other event fields you can access,
and how they are denoted in Tk, which can be useful when referring to
the Tk man pages.

Tk       Tkinter Event Field       Tk       Tkinter Event Field
                                            
----------------------------------------------------------------------
                                            
%f       焦点                      %A       char
                                            
                                            
%h       height                    %E       send_event
                                            
                                            
%k       keycode                   %K       keysym
                                            
                                            
%s       状况                      %N       keysym_num
                                            
                                            
%t       time                      %T       类型
                                            
                                            
%w       宽度                      %W       widget
                                            
                                            
%x       x                         %X       x_root
                                            
                                            
%y       y                         %Y       y_root
                                            


File: python.info,  Node: The index Parameter,  Next: Images,  Prev: 绑定和事件,  Up: 快速参考

5.25.1.16 The index Parameter
.............................

A number of widgets require "index" parameters to be passed.  These are
used to point at a specific place in a Text widget, or to particular
characters in an Entry widget, or to particular menu items in a Menu
widget.

Entry widget indexes (index, view index, etc.)

     Entry widgets have options that refer to character positions in the
     text being displayed.  You can use these *note tkinter: 10e.
     functions to access these special points in text widgets:

Text widget indexes

     The index notation for Text widgets is very rich and is best
     described in the Tk man pages.

Menu indexes (menu.invoke(), menu.entryconfig(), etc.)

     Some options and methods for menus manipulate specific menu
     entries.  Anytime a menu index is needed for an option or a
     parameter, you may pass in:

        * an integer which refers to the numeric position of the entry
          in the widget, counted from the top, starting with 0;

        * the string ‘"active"’, which refers to the menu position that
          is currently under the cursor;

        * the string ‘"last"’ which refers to the last menu item;

        * An integer preceded by ‘@’, as in ‘@6’, where the integer is
          interpreted as a y pixel coordinate in the menu’s coordinate
          system;

        * the string ‘"none"’, which indicates no menu entry at all,
          most often used with menu.activate() to deactivate all
          entries, and finally,

        * a text string that is pattern matched against the label of the
          menu entry, as scanned from the top of the menu to the bottom.
          Note that this index type is considered after all the others,
          which means that matches for menu items labelled ‘last’,
          ‘active’, or ‘none’ may be interpreted as the above literals,
          instead.


File: python.info,  Node: Images,  Prev: The index Parameter,  Up: 快速参考

5.25.1.17 Images
................

Images of different formats can be created through the corresponding
subclass of ‘tkinter.Image’:

   * ‘BitmapImage’ for images in XBM format.

   * ‘PhotoImage’ for images in PGM, PPM, GIF and PNG formats.  The
     latter is supported starting with Tk 8.6.

Either type of image is created through either the ‘file’ or the ‘data’
option (other options are available as well).

The image object can then be used wherever an ‘image’ option is
supported by some widget (e.g.  labels, buttons, menus).  In these
cases, Tk will not keep a reference to the image.  When the last Python
reference to the image object is deleted, the image data is deleted as
well, and Tk will display an empty box wherever the image was used.

也參考
......

The Pillow(1) package adds support for formats such as BMP, JPEG, TIFF,
and WebP, among others.

   ---------- Footnotes ----------

   (1) http://python-pillow.org/


File: python.info,  Node: File Handlers,  Prev: 快速参考,  Up: tkinter --- Tcl/Tk的Python接口

5.25.1.18 File Handlers
.......................

Tk allows you to register and unregister a callback function which will
be called from the Tk mainloop when I/O is possible on a file
descriptor.  Only one handler may be registered per file descriptor.
Example code:

     import tkinter
     widget = tkinter.Tk()
     mask = tkinter.READABLE | tkinter.WRITABLE
     widget.tk.createfilehandler(file, mask, callback)
     ...
     widget.tk.deletefilehandler(file)

This feature is not available on Windows.

Since you don’t know how many bytes are available for reading, you may
not want to use the *note BufferedIOBase: 67f. or *note TextIOBase: d01.
*note read(): 1ebb. or *note readline(): 1849. methods, since these will
insist on reading a predefined number of bytes.  For sockets, the *note
recv(): 76a. or *note recvfrom(): 76b. methods will work fine; for other
files, use raw reads or ‘os.read(file.fileno(), maxbytecount)’.

 -- 成員函式: Widget.tk.createfilehandler (file, mask, func)

     Registers the file handler callback function `func'.  The `file'
     argument may either be an object with a *note fileno(): 2069.
     method (such as a file or socket object), or an integer file
     descriptor.  The `mask' argument is an ORed combination of any of
     the three constants below.  The callback is called as follows:

          callback(file, mask)

 -- 成員函式: Widget.tk.deletefilehandler (file)

     Unregisters a file handler.

 -- Data: tkinter.READABLE
 -- Data: tkinter.WRITABLE
 -- Data: tkinter.EXCEPTION

     Constants used in the `mask' arguments.


File: python.info,  Node: tkinter colorchooser --- 颜色选择对话框,  Next: tkinter font --- Tkinter 字体封装,  Prev: tkinter --- Tcl/Tk的Python接口,  Up: 以 Tk 打造 GUI

5.25.2 ‘tkinter.colorchooser’ — 颜色选择对话框
----------------------------------------------

`源代码:' Lib/tkinter/colorchooser.py(1)

__________________________________________________________________

*note tkinter.colorchooser: 10f. 模块提供了 *note Chooser: 32ce. 类作为
原生颜色选择对话框的接口。 ‘Chooser’ 实现了一个模式颜色选择对话框窗口。
‘Chooser’ 类继承自 *note Dialog: 32cf. 类。

 -- 類別: tkinter.colorchooser.Chooser (master=None, **options)

 -- 函式: tkinter.colorchooser.askcolor (color=None, **options)

     创建一个颜色选择对话框。 调用此方法将显示相应窗口，等待用户进行选择
     ，并将选择的颜色 (或 ‘None’) 返回给调用者。

也參考
......

模块 *note tkinter.commondialog: 110.

     Tkinter 标准对话框模块

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/Lib/tkinter/colorchooser.py


File: python.info,  Node: tkinter font --- Tkinter 字体封装,  Next: Tkinter 对话框,  Prev: tkinter colorchooser --- 颜色选择对话框,  Up: 以 Tk 打造 GUI

5.25.3 ‘tkinter.font’ — Tkinter 字体封装
----------------------------------------

`源代码:' Lib/tkinter/font.py(1)

__________________________________________________________________

*note tkinter.font: 113. 模块提供用于创建和使用命名字体的 *note Font:
fcb. 类。

不同的字体粗细和倾斜是：

 -- Data: tkinter.font.NORMAL
 -- Data: tkinter.font.BOLD
 -- Data: tkinter.font.ITALIC
 -- Data: tkinter.font.ROMAN

 -- 類別: tkinter.font.Font (root=None, font=None, name=None,
          exists=False, **options)

     *note Font: fcb. 类表示命名字体。`Font' 实例具有唯一的名称，可以通
     过其族、大小和样式配置进行指定。命名字体是 Tk 将字体创建和标识为单
     个对象的方法，而不是通过每次出现时的属性来指定字体。

          参数：

                    `font' - 字体指示符元组 (family, size, options) 
                    `name' - 唯一的字体名 
                    `exists' - 指向现有命名字体（如果有） 

          其他关键字选项（如果指定了 `font'，则忽略）：

                    `family' - 字体系列，例如 Courier，Times 
                    `size' - 字体大小 
                         如果 `size' 为正数，则解释为以磅为单位的大小。 
                         如果 `size' 是负数，则将其绝对值 
                         解释为以像素为单位的大小。 
                    `weight' - 字体强调 (NORMAL, BOLD)（普通，加粗） 
                    `slant' - ROMAN, ITALIC（正体，斜体） 
                    `underline' - 字体下划线（0 - 无下划线，1 - 有下划线） 
                    `overstrike' - 字体删除线（0 - 无删除线，1 - 有删除线） 

      -- 成員函式: actual (option=None, displayof=None)

          返回字体的属性。

      -- 成員函式: cget (option)

          检索字体的某一个属性值。

      -- 成員函式: config (**options)

          修改字体的某一个属性值。

      -- 成員函式: copy ()

          返回当前字体的新实例。

      -- 成員函式: measure (text, displayof=None)

          返回以当前字体格式化时文本将在指定显示上占用的空间量。如果未指
          定显示，则假定为主应用程序窗口。

      -- 成員函式: metrics (*options, **kw)

          返回特定字体的数据。选项包括：

          `ascent' - 基线和最高点之间的距离

               （在该字体中的一个字符可以占用的空间中）

          `descent' - 基线和最低点之间的距离

               （在该字体中的一个字符可以占用的空间中）

          `linespace' - 所需最小垂直间距（在两个

               该字体的字符间，使得这两个字符在垂直方向上不重叠）。

          `fixed' - 如果该字体宽度被固定则为1，否则为0。

 -- 函式: tkinter.font.families (root=None, displayof=None)

     返回不同的字体系列。

 -- 函式: tkinter.font.names (root=None)

     返回定义字体的名字。

 -- 函式: tkinter.font.nametofont (name)

     返回一个 *note Font: fcb. 类，代表一个 tk 命名的字体。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/tkinter/font.py


File: python.info,  Node: Tkinter 对话框,  Next: tkinter messagebox --- Tkinter 消息提示,  Prev: tkinter font --- Tkinter 字体封装,  Up: 以 Tk 打造 GUI

5.25.4 Tkinter 对话框
---------------------

* Menu:

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


File: python.info,  Node: tkinter simpledialog --- 标准 Tkinter 输入对话框,  Next: tkinter filedialog --- 文件选择对话框,  Up: Tkinter 对话框

5.25.4.1 ‘tkinter.simpledialog’ — 标准 Tkinter 输入对话框
.........................................................

`源码:' Lib/tkinter/simpledialog.py(1)

__________________________________________________________________

*note tkinter.simpledialog: 116. 模块包含了一些便捷类和函数，用于创建简
单的模态对话框，从用户那里读取一个值。

 -- 函式: tkinter.simpledialog.askfloat (title, prompt, **kw)
 -- 函式: tkinter.simpledialog.askinteger (title, prompt, **kw)
 -- 函式: tkinter.simpledialog.askstring (title, prompt, **kw)

     以上三个函数提供给用户输入期望值的类型的对话框.

 -- 類別: tkinter.simpledialog.Dialog (parent, title=None)

     自定义对话框的基类.

           -- 成員函式: body (master)

               可以覆盖，用于构建对话框的界面，并返回初始焦点所在的部件
               。

           -- 成員函式: buttonbox ()

               加入 OK 和 Cancel 按钮的默认行为. 重写自定义按钮布局.

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/Lib/tkinter/simpledialog.py


File: python.info,  Node: tkinter filedialog --- 文件选择对话框,  Next: tkinter commondialog --- 对话窗口模板,  Prev: tkinter simpledialog --- 标准 Tkinter 输入对话框,  Up: Tkinter 对话框

5.25.4.2 ‘tkinter.filedialog’ — 文件选择对话框.
...............................................

`源码:' Lib/tkinter/filedialog.py(1)

__________________________________________________________________

*note tkinter.filedialog: 112. 模块提供了用于创建文件/目录选择窗口的类和
工厂函数。

* Menu:

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

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/Lib/tkinter/filedialog.py


File: python.info,  Node: 原生 加载/保存 对话框,  Up: tkinter filedialog --- 文件选择对话框

5.25.4.3 原生 加载/保存 对话框.
...............................

以下类和函数提供了文件对话窗口，这些窗口带有原生外观，具备可定制行为的配
置项。这些关键字参数适用于以下类和函数：

          `parent' —— 对话框下方的窗口 

          `title' —— 窗口的标题 

          `initialdir' —— 对话框的启动目录 

          `initialfile' —— 打开对话框时选中的文件 

          `filetypes' —— （标签，匹配模式）元组构成的列表，允许使用 “*” 通配符 

          `defaultextension' —— 默认的扩展名，用于加到文件名后面（保存对话框）。 

          `multiple' —— 为 True 则允许多选 

** 静态工厂函数 **

调用以下函数时，会创建一个模态的、原生外观的对话框，等待用户选取，然后将
选中值或 ‘None’ 返回给调用者。

 -- 函式: tkinter.filedialog.askopenfile (mode="r", **options)
 -- 函式: tkinter.filedialog.askopenfiles (mode="r", **options)

     上述两个函数创建了 *note Open: 32ed. 对话框，并以只读模式返回打开的
     文件对象。

 -- 函式: tkinter.filedialog.asksaveasfile (mode="w", **options)

     创建 *note SaveAs: 32ef. 对话框并返回一个写入模式打开的文件对象。

 -- 函式: tkinter.filedialog.askopenfilename (**options)
 -- 函式: tkinter.filedialog.askopenfilenames (**options)

     以上两个函数创建了 *note Open: 32ed. 对话框，并返回选中的文件名，对
     应着已存在的文件。

 -- 函式: tkinter.filedialog.asksaveasfilename (**options)

     创建 *note SaveAs: 32ef. 对话框，并返回选中的文件名。

 -- 函式: tkinter.filedialog.askdirectory (**options)

          提示用户选择一个目录. 
          其他关键字参数： 
               `mustexist' —— 确定是否必须为已存在的目录。 

 -- 類別: tkinter.filedialog.Open (master=None, **options)
 -- 類別: tkinter.filedialog.SaveAs (master=None, **options)

     上述两个类提供了用于保存和加载文件的原生对话窗口。

** 便捷类 **

以下类用于从头开始创建文件/目录窗口。不会模仿当前系统的原生外观。

 -- 類別: tkinter.filedialog.Directory (master=None, **options)

     创建对话框，提示用户选择一个目录。

     備註: 为了实现自定义的事件处理和行为，应继承 `FileDialog' 类。

 -- 類別: tkinter.filedialog.FileDialog (master, title=None)

     创建一个简单的文件选择对话框。

      -- 成員函式: cancel_command (event=None)

          触发对话窗口的终止。

      -- 成員函式: dirs_double_event (event)

          目录双击事件的处理程序。

      -- 成員函式: dirs_select_event (event)

          目录单击事件的处理程序。

      -- 成員函式: files_double_event (event)

          文件双击事件的处理程序。

      -- 成員函式: files_select_event (event)

          文件单击事件的处理程序。

      -- 成員函式: filter_command (event=None)

          以目录过滤文件.

      -- 成員函式: get_filter ()

          获取当前使用的文件过滤器.

      -- 成員函式: get_selection ()

          获取当前选择的项目.

      -- 成員函式: go (dir_or_file=os.curdir, pattern="*", default="",
               key=None)

          渲染对话和启动事件循环,

      -- 成員函式: ok_event (event)

          退出对话回到当前选择.

      -- 成員函式: quit (how=None)

          退出对话回到文件名, 如果有的话.

      -- 成員函式: set_filter (dir, pat)

          设置文件过滤器.

      -- 成員函式: set_selection (file)

          将当前选中文件更新为 `file'。

 -- 類別: tkinter.filedialog.LoadFileDialog (master, title=None)

     FileDialog 的一个子类，为选择已有文件创建对话窗口。

      -- 成員函式: ok_command ()

          检测有否给出文件，以及选中的文件是否存在。

 -- 類別: tkinter.filedialog.SaveFileDialog (master, title=None)

     FileDialog 的一个子类，创建用于选择目标文件的对话窗口。

      -- 成員函式: ok_command ()

          检测选中文件是否为目录。如果选中已存在文件，则需要进行确认。


File: python.info,  Node: tkinter commondialog --- 对话窗口模板,  Prev: tkinter filedialog --- 文件选择对话框,  Up: Tkinter 对话框

5.25.4.4 ‘tkinter.commondialog’ — 对话窗口模板
..............................................

`源码:' Lib/tkinter/commondialog.py(1)

__________________________________________________________________

*note tkinter.commondialog: 110. 模块提供了 *note Dialog: 32cf. 类，是其
他模块定义的对话框的基类。

 -- 類別: tkinter.commondialog.Dialog (master=None, **options)

      -- 成員函式: show (color=None, **options)

          渲染对话窗口.

也參考
......

模块 *note tkinter.messagebox: 114, *note 讀寫檔案: 13d4.

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/Lib/tkinter/commondialog.py


File: python.info,  Node: tkinter messagebox --- Tkinter 消息提示,  Next: tkinter scrolledtext --- 滚动文字控件,  Prev: Tkinter 对话框,  Up: 以 Tk 打造 GUI

5.25.5 ‘tkinter.messagebox’ — Tkinter 消息提示
----------------------------------------------

`源代码:' Lib/tkinter/messagebox.py(1)

__________________________________________________________________

*note tkinter.messagebox: 114. 模块提供了一个模板基类以及多个常用配置的
便捷方法。 消息框为模式窗口并将基于用户的选择返回 (True, False, OK,
None, Yes, No) 的一个子集。 常用消息框风格和布局包括但不限于:

[python-figures/tk_msg]
Figure

 -- 類別: tkinter.messagebox.Message (master=None, **options)

     创建一个默认信息消息框。

`信息消息框'

 -- 成員函式: tkinter.messagebox.showinfo (title=None, message=None,
          **options)

`警告消息框'

 -- 成員函式: tkinter.messagebox.showwarning (title=None, message=None,
          **options)
 -- 成員函式: tkinter.messagebox.showerror (title=None, message=None,
          **options)

`疑问消息框'

 -- 成員函式: tkinter.messagebox.askquestion (title=None, message=None,
          **options)
 -- 成員函式: tkinter.messagebox.askokcancel (title=None, message=None,
          **options)
 -- 成員函式: tkinter.messagebox.askretrycancel (title=None,
          message=None, **options)
 -- 成員函式: tkinter.messagebox.askyesno (title=None, message=None,
          **options)
 -- 成員函式: tkinter.messagebox.askyesnocancel (title=None,
          message=None, **options)

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/Lib/tkinter/messagebox.py


File: python.info,  Node: tkinter scrolledtext --- 滚动文字控件,  Next: tkinter dnd --- 拖放操作支持,  Prev: tkinter messagebox --- Tkinter 消息提示,  Up: 以 Tk 打造 GUI

5.25.6 ‘tkinter.scrolledtext’ — 滚动文字控件
--------------------------------------------

`源代码：' Lib/tkinter/scrolledtext.py(1)

__________________________________________________________________

*note tkinter.scrolledtext: 115. 模块提供了一个同名的类，实现了带有垂直
滚动条并被配置为可以“正常运作”的文本控件 。 使用 *note ScrolledText:
3316. 类会比直接配置一个文本控件附加滚动条要简单得多。

文本控件与滚动条打包在一个 ‘Frame’ 中， ‘Grid’ 方法和 ‘Pack’ 方法的布局
管理器从 ‘Frame’ 对象中获得。这允许 *note ScrolledText: 3316. 控件可以直
接用于实现大多数正常的布局管理行为。

如果需要更具体的控制，可以使用以下属性：

 -- 類別: tkinter.scrolledtext.ScrolledText (master=None, **kw)

      -- 屬性: frame

          围绕文本和滚动条控件的框架。

      -- 屬性: vbar

          滚动条控件。

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/Lib/tkinter/scrolledtext.py


File: python.info,  Node: tkinter dnd --- 拖放操作支持,  Next: tkinter ttk --- Tk主题部件,  Prev: tkinter scrolledtext --- 滚动文字控件,  Up: 以 Tk 打造 GUI

5.25.7 ‘tkinter.dnd’ — 拖放操作支持
-----------------------------------

`源代码:' Lib/tkinter/dnd.py(1)

__________________________________________________________________

     備註: 此模块是实验性的且在为 Tk DND 所替代后将被弃用。

*note tkinter.dnd: 111. 模块为单个应用内部的对象提供了在同一窗口中或多个
窗口间的拖放操作支持。 要将对象设为可拖放，你必须为其创建启动拖放进程的
事件绑定。 通常，你要将 ButtonPress 事件绑定到你所编写的回调函数 (参见
*note 绑定和事件: 32c1.)。 该函数应当调用 *note dnd_start(): 331b.，其中
’source’ 为要拖动的对象，而 ’event’ 为发起调用的事件（你的回调函数的参数
）。

目标对象的选择方式如下:

  1. 从顶至底地在鼠标之下的区域中搜索目标控件

        * 目标控件应当具有一个指向可调用对象的 `dnd_accept' 属性

        * 如果 `dnd_accept' 不存在或是返回 None，则将转至父控件中搜索

        * 如果目标控件未找到，则目标对象为 None

  2. 调用 `<old_target>.dnd_leave(source, event)'

  3. 调用 `<new_target>.dnd_enter(source, event)'

  4. 调用 `<target>.dnd_commit(source, event)' 来通知释放

  5. 调用 `<source>.dnd_end(target, event)' 来表明拖放的结束

 -- 類別: tkinter.dnd.DndHandler (source, event)

     `DndHandler' 类处理拖放事件，在事件控件的根对象上跟踪 Motion 和
     ButtonRelease 事件。

      -- 成員函式: cancel (event=None)

          取消拖放进程。

      -- 成員函式: finish (event, commit=0)

          执行结束播放函数。

      -- 成員函式: on_motion (event)

          在执行拖动期间为目标对象检查鼠标之下的区域。

      -- 成員函式: on_release (event)

          当释放模式被触发时表明拖动的结束。

 -- 函式: tkinter.dnd.dnd_start (source, event)

     用于拖放进程的工厂函数。

也參考
......

*note 绑定和事件: 32c1.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/tkinter/dnd.py


File: python.info,  Node: tkinter ttk --- Tk主题部件,  Next: tkinter tix --- TK扩展包,  Prev: tkinter dnd --- 拖放操作支持,  Up: 以 Tk 打造 GUI

5.25.8 ‘tkinter.ttk’ — Tk主题部件
---------------------------------

`源代码:' Lib/tkinter/ttk.py(1)

__________________________________________________________________

*note tkinter.ttk: 118. 模块自 Tk 8.5 开始引入，可用于访问 Tk 风格的控件
包。如果 Python 未基于 Tk 8.5 编译，只要安装了 `Tile' 仍可访问本模块。前
一种采用 Tk 8.5 的方式带有更多好处，比如在 X11 系统下支持反锯齿字体渲染
和透明窗口（需要 X11 中的窗口组管理器）。

*note tkinter.ttk: 118. 的基本设计思路，就是尽可能地把控件的行为代码与实
现其外观的代码分离开来。

也參考
......

Tk 控件风格(2)

     一份文档介绍Tk支持的主题

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/tkinter/ttk.py

   (2) https://core.tcl.tk/tips/doc/trunk/tip/48.md


File: python.info,  Node: 使用 Ttk,  Next: Ttk 控件,  Up: tkinter ttk --- Tk主题部件

5.25.8.1 使用 Ttk
.................

开始使用 Ttk, 导入模块:

     from tkinter import ttk

重写基础Tk控件,导入应跟随Tk导入:

     from tkinter import *
     from tkinter.ttk import *

这段代码会让以下几个 ‘tkinter. ttk’ 控件（‘Button’, ‘Checkbutton’,
‘Entry’, ‘Frame’, ‘Label’, ‘LabelFrame’, ‘Menubutton’, ‘PanedWindow’,
‘Radiobutton’, ‘Scale’ 和 ‘Scrollbar’）自动替换掉 Tk 的对应控件。

使用新控件的直接好处，是拥有更好的跨平台的外观，但新旧控件并不完全兼容。
主要区别在于，Ttk 组件不再包含“fg”、“bg”等与样式相关的参数 。而是用
‘ttk.Style’ 类来定义更美观的样式效果。

也參考
......

将现有的应用程序转换为 Tile 控件，可参考 Converting existing applications to use Tile widgets(1) 。

     此文介绍使用新控件时的常见差别（使用 Tcl ）。

   ---------- Footnotes ----------

   (1) http://tktable.sourceforge.net/tile/doc/converting.txt


File: python.info,  Node: Ttk 控件,  Next: 控件,  Prev: 使用 Ttk,  Up: tkinter ttk --- Tk主题部件

5.25.8.2 Ttk 控件
.................

ttk 中有 18 种部件 ，其中十二种已存在于 tkinter 中: ‘Button’,
‘Checkbutton’, ‘Entry’, ‘Frame’, ‘Label’, ‘LabelFrame’, ‘Menubutton’,
‘PanedWindow’, ‘Radiobutton’, ‘Scale’, ‘Scrollbar’ 以及 *note Spinbox:
501.。 另外六种是新增的: *note Combobox: 3325, *note Notebook: 3326,
*note Progressbar: 3327, ‘Separator’, ‘Sizegrip’ 以及 *note Treeview:
3de.。 它们全都是 *note Widget: 3328. 的子类。

ttk 控件可以改善应用程序的外观。如上所述，修改样式的代码与 tk 控件存在差
异。

Tk 代码:

     l1 = tkinter.Label(text="Test", fg="black", bg="white")
     l2 = tkinter.Label(text="Test", fg="black", bg="white")

Ttk 代码:

     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")

有关 *note TtkStyling: 3329. 的更多信息，请参阅 *note Style: 332a. 类文
档。


File: python.info,  Node: 控件,  Next: 组合框,  Prev: Ttk 控件,  Up: tkinter ttk --- Tk主题部件

5.25.8.3 控件
.............

‘ttk.Widget’ 定义了由 Tk 带主题部件所支持的标准选项和方法，它们不应该被
直接实例化。

* Menu:

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


File: python.info,  Node: 标准选项,  Next: 可滚动控件选项,  Up: 控件

5.25.8.4 标准选项
.................

所有 ‘ttk’ 小部件接受以下选项：

     选项            描述
                     
     -----------------------------------------------------------------------------------
                     
     类              指定窗口类。在查询选项数据库中窗口的其他选项时，使用该类，确定窗
                     口的默认绑定标签，以及选择控件的默认布局和样式。此选项仅为只读，
                     并且只能在创建窗口时指定。
                     
                     
     光标            指定要用于控件的鼠标光标。如果设置为空字符串（默认值），则为父控
                     件继承光标.
                     
                     
     takefocus       确定窗口是否在键盘遍历期间接受焦点。返回0或1，返回空字符串。如果
                     返回0，则表示在键盘遍历期间应该跳过该窗口。如果为1，则表示只要可
                     以查看窗口就应该接收输入焦点。并且空字符串意味着遍历脚本决定是否
                     关注窗口。
                     
                     
     风格            可用于指定自定义控件样式。
                     


File: python.info,  Node: 可滚动控件选项,  Next: 标签选项,  Prev: 标准选项,  Up: 控件

5.25.8.5 可滚动控件选项
.......................

控件支持以下选项使用滚动条控制.

     选项                 描述
                          
     -----------------------------------------------------------------------------------
                          
     xscroll命令          用于与水平滚动条通讯.
                          
                          当视图在控件的窗口改变,控件将会基于scroll命令生成Tcl命令.
                          
                          通常该参数由滚动条的 ‘Scrollbar.set()’ 方法组成。当窗口中的
                          可见内容发生变化时，将会刷新滚动条的状态。
                          
                          
     yscroll命令          用于与垂直滚动条通讯.更多信息请参考上面的信息.
                          


File: python.info,  Node: 标签选项,  Next: 兼容性选项,  Prev: 可滚动控件选项,  Up: 控件

5.25.8.6 标签选项
.................

以下选项支持标签,按钮已及其他类按钮的控件.

     选项               描述
                        
     -----------------------------------------------------------------------------------
                        
     文本               指定显示在控件内的文本。
                        
                        
     文本变量           指定一个变量名，其值将用于设置 text 参数。
                        
                        
     下划线             设置文本字符串中带下划线字符的索引（基于0）。下划线字符用于激
                        活快捷键。
                        
                        
     图片               指定一个用于显示的图像。这是一个由1个或多个元素组成的列表。第
                        一个元素是默认的图像名称。列表的其余部分是由
                        *note Style.map(): fe4. 定义的“状态/值对”的序列，指定控件在某
                        状态或状态组合时要采用的图像。列表中的所有图像应具备相同的尺
                        寸。
                        
                        
     compound           指定同时存在 text 和 image 参数时，应如何显示文本和对应的图片
                        。合法的值包括：
                        
                           * text: 只显示文本
                        
                           * image: 只显示图片
                        
                           * top, bottom, left, right: 分别显示图片的上,下,左,右的文
                             本.
                        
                           * none: 默认. 如果设置显示图片, 否则文本.
                        
                        
     宽度               如果值大于零，指定文本标签留下多少空间，单位是字符数；如果值
                        小于零，则指定最小宽度。如果等于零或未指定，则使用文本标签本
                        身的宽度。
                        


File: python.info,  Node: 兼容性选项,  Next: 控件状态,  Prev: 标签选项,  Up: 控件

5.25.8.7 兼容性选项
...................

     选项         描述
                  
     ----------------------------------------------------------------------------------
                  
     状况         可以设为“normal”或“disabled”，以便控制“禁用”状态标志位。本参数只允
                  许写入：用以改变控件的状态，但 *note Widget.state(): 3330. 方法不
                  影响本参数。
                  


File: python.info,  Node: 控件状态,  Next: ttk Widget,  Prev: 兼容性选项,  Up: 控件

5.25.8.8 控件状态
.................

控件状态是无关状态标志的位图.

     标志             描述
                      
     -----------------------------------------------------------------------------------
                      
     活动             鼠标光标经过控件并按下鼠标按钮，将引发动作。
                      
                      
     禁用             在程序控制下控件是禁用的
                      
                      
     焦点             控件有键盘焦点
                      
                      
     按压             控件已被按下。
                      
                      
     选择             勾选或单选框之类的控件，表示启用、选中状态。
                      
                      
     背景             Windows 和 Mac 系统的窗口具有“激活”或后台的概念。后台窗口的控件
                      会设置 `foreground' 参数，而前台窗口的控件则会清除此状态。
                      
                      
     只读             控件不允许用户修改。
                      
                      
     alternate        控件的备选显式格式。
                      
                      
     无效的           控件的值是无效的
                      

所谓的控件状态，就是一串状态名称的组合，可在某个名称前加上感叹号，表示该
状态位是关闭的。


File: python.info,  Node: ttk Widget,  Prev: 控件状态,  Up: 控件

5.25.8.9 ttk.Widget
...................

除了以下方法之外，‘ttk.Widget’ 还支持 ‘tkinter.Widget.cget()’ 和
‘tkinter.Widget.configure()’ 方法。

 -- 類別: tkinter.ttk.Widget

      -- 成員函式: identify (x, y)

          返回位于 `x' `y' 的控件名称，如果该坐标点不属于任何控件，则返
          回空字符串。

          `x' 和 `y' 是控件内的相对坐标，单位是像素。

      -- 成員函式: instate (statespec, callback=None, *args, **kw)

          检测控件的状态。如果没有设置回调函数，那么当控件状态符合
          `statespec' 时返回 ‘True’，否则返回 ‘False’。如果指定了回调函
          数，那么当控件状态匹配 `statespec' 时将会调用回调函数，且带上
          参数 args。

      -- 成員函式: state (statespec=None)

          修改或查询控件的状态。如果给出了 `statespec'，则会设置控件的状
          态，并返回一个新的*statespec*，表明哪些标志做过改动。如果未给
          出 `statespec'，则返回当前启用的状态标志。

     `statespec' 通常是列表或元组类型。


File: python.info,  Node: 组合框,  Next: Spinbox,  Prev: 控件,  Up: tkinter ttk --- Tk主题部件

5.25.8.10 组合框
................

‘ttk.Combobox’ 控件是文本框和下拉列表的组合体。该控件是 ‘Entry’ 的子类。

除了从 *note Widget: 3328. 继承的 ‘Widget.cget()’ 、
‘Widget.configure()’ 、*note Widget.identify(): 3333. 、*note
Widget.instate(): 3334. 和 *note Widget.state(): 3330. 方法，以及从
‘Entry’ 继承的 ‘Entry.bbox()’ 、 ‘Entry.delete()’ 、 ‘Entry.icursor()’ 、
‘Entry.index()’ 、 ‘Entry.insert()’ 、 ‘Entry.selection()’ 、
‘Entry.xview()’ 方法，‘ttk.Combobox’ 还自带了其他几个方法。

* Menu:

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


File: python.info,  Node: 选项,  Next: 虚拟事件,  Up: 组合框

5.25.8.11 选项
..............

控件可设置以下参数：

     选项                  描述
                           
     -----------------------------------------------------------------------------------
                           
     exportselection       布尔值，如果设为 True，则控件的选中文字将关联为窗口管理器
                           的选中文字（可由 Misc.selection_get 返回）。
                           
                           
     justify               指定文本在控件中的对齐方式。可为 left、center、right 之一
                           。
                           
                           
     height                设置下拉列表框的高度。
                           
                           
     postcommand           一条代码，（可用 Misc.register 进行注册），在显示之前将被
                           调用。可用于选取要显示的值。
                           
                           
     状况                  normal 、readonly 或 disabled。在 readonly 状态下，数据不
                           能直接编辑，用户只能从下拉列表中选取。在 normal 状态下，可
                           直接编辑文本框。在 disabled 状态下，无法做任何交互。
                           
                           
     文本变量              设置一个变量名，其值与控件的值关联。每当该变量对应的值发生
                           变动时，控件值就会更新，反之亦然。参见 ‘tkinter.StringVar’
                           。
                           
                           
     值                    设置显示于下拉列表中的值。
                           
                           
     宽度                  设置为整数值，表示输入窗口的应有宽度，单位是字符单位（控件
                           字体的平均字符宽度）。
                           


File: python.info,  Node: 虚拟事件,  Next: ttk Combobox,  Prev: 选项,  Up: 组合框

5.25.8.12 虚拟事件
..................

当用户从下拉列表中选择某个元素时，控件会生成一条 `<<ComboboxSelected>>'
虚拟事件。


File: python.info,  Node: ttk Combobox,  Prev: 虚拟事件,  Up: 组合框

5.25.8.13 ttk.Combobox
......................

 -- 類別: tkinter.ttk.Combobox

      -- 成員函式: current (newindex=None)

          如果给出了 `newindex'，则把控件值设为 `newindex' 位置的元素值
          。否则，返回当前值的索引，当前值未在列表中则返回 -1。

      -- 成員函式: get ()

          返回控件的当前值。

      -- 成員函式: set (value)

          设置控件的值为 `value' 。


File: python.info,  Node: Spinbox,  Next: 笔记本,  Prev: 组合框,  Up: tkinter ttk --- Tk主题部件

5.25.8.14 Spinbox
.................

‘ttk.Spinbox’ 控件是 ‘ttk.Entry’ 的扩展，带有增减箭头。可用于数字或字符
串列表。这是 ‘Entry’ 的子类。

除了从 *note Widget: 3328. 继承的 ‘Widget.cget()’ 、
‘Widget.configure()’ 、‘Widget.identified()’ 、 *note Widget.instate():
3334. 和 *note Widget.state(): 3330. 方法，以及从 ‘Entry’ 继承的 ‘Entry.
bbox()’ 、 ‘Entry.delete()’ 、 ‘Entry.icursor()’ 、‘Entry.index()’ 、
‘Entry.insert()’ 、 ‘Entry.xview()’ 方法，控件还自带了其他一些方法，在
‘ttk.Spinbox’ 中都有介绍。

* Menu:

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


File: python.info,  Node: 选项<2>,  Next: 虚拟事件<2>,  Up: Spinbox

5.25.8.15 选项
..............

控件可设置以下参数：

选项                       描述
                           
--------------------------------------------------------------------------------------
                           
从                         浮点值。即递减按钮要递减的最小值。作为参数使用时必须写成
                           ‘from_’，因为 ‘from’ 是 Python 关键字。
                           
                           
到                         浮点值。即递增按钮能够到达的最大值。
                           
                           
增加                       浮点值。指定递增/递减按钮每次的修改量。默认值为 1.0。
                           
                           
值                         字符串或浮点值构成的序列。如若给出，则递增/递减会在此序
                           列元素间循环，而不是增减数值。
                           
                           
wrap                       布尔值。若为 ‘True’ ，则递增和递减按钮会由 ‘to’ 值循环至
                           ‘from’ 值，或由 ‘from’ 值循环至 ‘to’ 值。
                           
                           
格式                       字符串。指定递增/递减按钮的数字格式。必须以“%W.Pf”的格式
                           给出，W 是填充的宽度，P 是小数精度，% 和 f 就是本身的含
                           义。
                           
                           
命令                       Python 回调函数。只要递增或递减按钮按下之后，就会进行不
                           带参数的调用。
                           


File: python.info,  Node: 虚拟事件<2>,  Next: ttk Spinbox,  Prev: 选项<2>,  Up: Spinbox

5.25.8.16 虚拟事件
..................

用户若按下 <Up> ，则控件会生成 `<<Increment>>' 虚拟事件，若按下 <Down> 则
会生成 `<<Decrement>>' 事件。


File: python.info,  Node: ttk Spinbox,  Prev: 虚拟事件<2>,  Up: Spinbox

5.25.8.17 ttk.Spinbox
.....................

 -- 類別: tkinter.ttk.Spinbox

      -- 成員函式: get ()

          返回spinbox当前值

      -- 成員函式: set (value)

          设置spinbox的值为*值*.


File: python.info,  Node: 笔记本,  Next: Progressbar,  Prev: Spinbox,  Up: tkinter ttk --- Tk主题部件

5.25.8.18 笔记本
................

Ttk Notebook 控件管理着多个窗口的集合，每次显示其中的一个。每个子窗口都
与某个 tab 关联，可供用户选中以改变当前显示的窗口。

* Menu:

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


File: python.info,  Node: 选项<3>,  Next: Tab 选项,  Up: 笔记本

5.25.8.19 选项
..............

控件可设置以下参数：

     选项          描述
                   
     -----------------------------------------------------------------------------------
                   
     height        如若给出且大于 0，则指定子窗口面板的应有高度（不含内部缩进）。否则
                   会采用所有子窗口面板的最大高度。
                   
                   
     padding       指定在控件外部添加的留白。padding 是最多包含四个值的列表，指定左顶
                   右底的空间。如果给出的元素少于四个，底部值默认为顶部值，右侧值默认
                   为左侧值，顶部值默认为左侧值。
                   
                   
     宽度          若给出且大于 0，则设置面板的应有宽度（不含内部 padding）。否则将采
                   用所有子窗口面板的最大宽度。
                   


File: python.info,  Node: Tab 选项,  Next: Tab 标识,  Prev: 选项<3>,  Up: 笔记本

5.25.8.20 Tab 选项
..................

Tab 特有属性如下：

     选项            描述
                     
     -----------------------------------------------------------------------------------
                     
     状况            可为 normal、disabled 或 disabled 之一。若为 disabled 则不能选中
                     。若为 hidden 则不会显示。
                     
                     
     sticky          指定子窗口在面板内的定位方式。应为包含零个或多个 n、s、e 、w 字
                     符的字符串。每个字母表示子窗口应紧靠的方向（北、南、东或西），正
                     如 ‘grid()’ 位置管理器所述。
                     
                     
     padding         指定控件和面板之间的留白空间。格式与本控件的 padding 属性相同。
                     
                     
     文本            指定显示在 tab 上的文本。
                     
                     
     图片            指定显示在 tab 上的图片。参见 *note Widget: 3328. 的 image 属性
                     。
                     
                     
     compound        当文本和图片同时存在时，指定图片相对于文本的显示位置。合法的属性
                     值参见 *note Label Options: 332e. 。
                     
                     
     下划线          指定下划线在文本字符串中的索引（基于0）。如果调用过了
                     *note Notebook.enable_traversal(): 3345.，带下划线的字符将用于激
                     活快捷键。
                     


File: python.info,  Node: Tab 标识,  Next: 虚拟事件<3>,  Prev: Tab 选项,  Up: 笔记本

5.25.8.21 Tab 标识
..................

The tab_id present in several methods of ‘ttk.Notebook’ may take any of
the following forms:

   * 位于 0 和 tab 总数之间的整数值。

   * 子窗口的名称

   * 以“@x,y”形式给出的位置，唯一标识了 tab 页。

   * 字符串“current”，标识当前选中的 Tab。

   * 字符串字面值 "end"，它返回标签页的数量 (仅适用于 *note
     Notebook.index(): 3347.)


File: python.info,  Node: 虚拟事件<3>,  Next: ttk Notebook,  Prev: Tab 标识,  Up: 笔记本

5.25.8.22 虚拟事件
..................

当选中一个新 tab 页之后，控件会生成一条 `<<NotebookTabChanged>>' 虚拟事
件。


File: python.info,  Node: ttk Notebook,  Prev: 虚拟事件<3>,  Up: 笔记本

5.25.8.23 ttk.Notebook
......................

 -- 類別: tkinter.ttk.Notebook

      -- 成員函式: add (child, **kw)

          添加一个新 tab 页。

          如果窗口是由 Notebook 管理但处于隐藏状态，则会恢复到之前的位置
          。

          可用属性请参见 *note Tab Options: 3344. 。

      -- 成員函式: forget (tab_id)

          删除 `tab_id' 指定的 tab 页，移除与其窗口的关联。

      -- 成員函式: hide (tab_id)

          隐藏 `tab_id' 指定的 tab 页。

          tab 页不会显示出来，但关联的窗口仍接受 Notebook 的管理，其配置
          属性会继续保留。隐藏的 tab 页可由 *note add(): 334a. 恢复。

      -- 成員函式: identify (x, y)

          返回 tab 页内位置为 `x'、`y' 的控件名称，若不存在则返回空字符
          串。

      -- 成員函式: index (tab_id)

          返回 `tab_id' 指定 tab 页的索引值，如果 `tab_id' 为 end 则返回
          tab 页的总数。

      -- 成員函式: insert (pos, child, **kw)

          在指定位置插入一个面板控件。

          `pos' 可为字符串“end” 、整数索引值或子窗口名称。如果 `child' 已
          由 Notebook 管理，则移至指定位置。

          可用属性请参见 *note Tab Options: 3344. 。

      -- 成員函式: select (tab_id=None)

          选中 `tab_id' 指定 tab。

          显示关联的子窗口，之前选中的窗口将取消映射关系。如果省略
          `tab_id' ，则返回当前选中面板的控件名称。

      -- 成員函式: tab (tab_id, option=None, **kw)

          查询或修改 `tab_id' 指定 tab 的属性。

          如果未给出 `kw' ，则返回由 tab 属性组成的字典。如果指定了
          `option'，则返回其值。否则，设置属性值。

      -- 成員函式: tabs ()

          返回 Notebook 管理的窗口列表。

      -- 成員函式: enable_traversal ()

          为包含 Notebook 的顶层窗口启用键盘遍历。

          这将为包含 Notebook 的顶层窗口增加如下键盘绑定关系：

             * ‘Control-Tab’ ：将当前 tab 加入选中列表。

             * ‘Shift-Control-Tab’ ：选中当前 tab 之前的页。

             * ‘Alt-K’ ：这里 `K' 是任意 tab 页的快捷键（带下划线）字符
               ，将会直接选中该 tab。

          一个顶层窗口中可为多个 Notebook 启用键盘遍历，包括嵌套的
          Notebook 。但仅当所有面板都将所在 Notebook 作为父控件时，键盘
          遍历才会生效。


File: python.info,  Node: Progressbar,  Next: Separator,  Prev: 笔记本,  Up: tkinter ttk --- Tk主题部件

5.25.8.24 Progressbar
.....................

‘ttk.Progressbar’ 控件可为长时间操作显示状态。可工作于两种模式：1）确定
模式，显示相对完成进度；2）不确定模式，显示动画让用户知道工作正在进行中
。

* Menu:

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


File: python.info,  Node: 选项<4>,  Next: ttk Progressbar,  Up: Progressbar

5.25.8.25 选项
..............

控件可设置以下参数：

     选项           描述
                    
     -----------------------------------------------------------------------------------
                    
     orient         horizontal 或 vertical。指定进度条的显示方向。
                    
                    
     length         指定进度条长轴的长度（横向为宽度，纵向则为高度）。
                    
                    
     模式           determinate 或 indeterminate。
                    
                    
     maximum        设定最大值。默认为 100。
                    
                    
     值             进度条的当前值。在 determinate 模式下代表已完成的工作量。在
                    indeterminate 模式下，解释为 `maximum' 的模；也就是说，当本值增至
                    `maximum' 时，进度条完成了一个“周期”。
                    
                    
     variable       与属性值关联的变量名。若给出，则当变量值变化时会自动设为进度条的
                    值。
                    
                    
     phase          只读属性。只要值大于 0 且在 determinate 模式下小于最大值，控件就
                    会定期增大该属性值。当前主题可利用本属性提供额外的动画效果。
                    


File: python.info,  Node: ttk Progressbar,  Prev: 选项<4>,  Up: Progressbar

5.25.8.26 ttk.Progressbar
.........................

 -- 類別: tkinter.ttk.Progressbar

      -- 成員函式: start (interval=None)

          启动自动递增模式：安排一个循环的定时器事件，每隔 `interval' 毫
          秒调用一次 *note Progressbar.step(): 3356.。`interval' 可省略
          ，默认为 50毫秒。

      -- 成員函式: step (amount=None)

          将进度条的值增加 `amount'。

          `amount' 可省略，默认为 1.0。

      -- 成員函式: stop ()

          停止自增模式：取消所有由 *note Progressbar.start(): 3355. 启动
          的循环定时器事件。


File: python.info,  Node: Separator,  Next: Sizegrip,  Prev: Progressbar,  Up: tkinter ttk --- Tk主题部件

5.25.8.27 Separator
...................

The ‘ttk.Separator’ widget displays a horizontal or vertical separator
bar.

除由 ‘ttk.Widget’ 继承而来的方法外，没有定义其他方法。

* Menu:

* 选项: 选项<5>.


File: python.info,  Node: 选项<5>,  Up: Separator

5.25.8.28 选项
..............

属性如下：

     选项         描述
                  
     ----------------------------------------------------------------------------------
                  
     orient       horizontal 或 vertical。指定分隔条的方向。
                  


File: python.info,  Node: Sizegrip,  Next: Treeview,  Prev: Separator,  Up: tkinter ttk --- Tk主题部件

5.25.8.29 Sizegrip
..................

‘ttk.Sizegrip’ 控件允许用户通过按下并拖动控制柄来调整内部顶层窗口的大小
。

除由 ‘ttk.Widget’ 继承的之外，没有其他属性和方法。

* Menu:

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


File: python.info,  Node: 与平台相关的注意事项,  Next: Bug,  Up: Sizegrip

5.25.8.30 与平台相关的注意事项
..............................

   * On macOS, toplevel windows automatically include a built-in size
     grip by default.  Adding a ‘Sizegrip’ is harmless, since the
     built-in grip will just mask the widget.


File: python.info,  Node: Bug,  Prev: 与平台相关的注意事项,  Up: Sizegrip

5.25.8.31 Bug
.............

   * 假如内部的顶层窗口位置是相对于屏幕的右侧或底部进行设置的，那么
     ‘Sizegrip’ 控件将不会改变窗口的大小。

   * 仅支持东南方向的缩放。


File: python.info,  Node: Treeview,  Next: Ttk 风格,  Prev: Sizegrip,  Up: tkinter ttk --- Tk主题部件

5.25.8.32 Treeview
..................

‘ttk.Treeview’ 控件可将多项内容分层级显示。每个数据项抖带有一个文本标签
、一张图片（可选）和一个数据列表（可选）。这些数据值将在树标签后面分列显
示。

数据值的显示顺序可用属性 ‘displaycolumns’ 进行控制。树控件还可以显示列标
题。数据列可通过数字或名称进行访问，各列的名称在属性 columns 中列出。参
阅 *note Column Identifiers: 335e.。

每个数据项都由唯一名称进行标识。如果调用者未提供数据项的 ID，树控件会自
动生成。根有且只有一个，名为 ‘{}’。根本身不会显示出来；其子项将显示在顶
层。

每个数据项均带有 tag 列表，可用于绑定事件及控制外观。

Treeview 组件支持水平和垂直滚动，滚动时会依据 *note Scrollable Widget
Options: 332d. 描述的属性和 *note Treeview.xview(): 335f. 和 *note
Treeview.yview(): 3360. 方法。

* Menu:

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


File: python.info,  Node: 选项<6>,  Next: 数据项的属性,  Up: Treeview

5.25.8.33 选项
..............

控件可设置以下参数：

     选项                 描述
                          
     ----------------------------------------------------------------------------------
                          
     columns              列标识的列表，指定列的数量和名称。
                          
                          
     displaycolumns       列标识的列表（索引可为符号或整数），指定要显示的数据列及显
                          示顺序，或者字符串 “#all”。
                          
                          
     height               指定可见的行数。注意：所需宽度由各列宽度之和决定。
                          
                          
     padding              指定控件内部的留白。为不超过四个元素的长度列表。
                          
                          
     selectmode           控制内部类如何进行选中项的管理。可为 extended、browse 或
                          none。若设为 extended（默认），则可选中多个项。若为 browse
                          ，则每次只能选中一项。若为 none，则无法修改选中项。
                          
                          请注意，代码和 tag 绑定可自由进行选中操作，不受本属性的限
                          制。
                          
                          
     show                 由0个或下列值组成的列表，指定要显示树的哪些元素。
                          
                             * tree ：在 #0 列显示树的文本标签。
                          
                             * headings ：显示标题行。
                          
                          默认为“tree headings”，显示所有元素。
                          
                          ** 注意** ：第 #0 列一定是指 tree 列，即便未设置
                          show="tree" 也一样。
                          


File: python.info,  Node: 数据项的属性,  Next: tag 属性,  Prev: 选项<6>,  Up: Treeview

5.25.8.34 数据项的属性
......................

可在插入和数据项操作时设置以下属性。

     选项         描述
                  
     ---------------------------------------------------------------------------------
                  
     文本         用于显示的文本标签。
                  
                  
     图片         Tk 图片对象，显示在文本标签左侧。
                  
                  
     值           关联的数据值列表。
                  
                  每个数据项关联的数据数量应与 columns 属性相同。如果比 columns 属
                  性的少，剩下的值将视为空。如果多于 columns 属性的，多余数据将被忽
                  略。
                  
                  
     open         ‘True’ 或 ‘False’，表明是否显示数据项的子树。
                  
                  
     tags         与该数据项关联的 tag 列表。
                  


File: python.info,  Node: tag 属性,  Next: 列标识,  Prev: 数据项的属性,  Up: Treeview

5.25.8.35 tag 属性
..................

tag 可定义以下属性：

     选项             描述
                      
     ---------------------------------------------------------------------------------
                      
     foreground       定义文本前景色。
                      
                      
     背景             定义单元格或数据项的背景色。
                      
                      
     font             定义文本的字体。
                      
                      
     图片             定义数据项的图片，当 image 属性为空时使用。
                      


File: python.info,  Node: 列标识,  Next: 虚拟事件<4>,  Prev: tag 属性,  Up: Treeview

5.25.8.36 列标识
................

列标识可用以下格式给出：

   * 由 columns 属性给出的符号名。

   * 整数值 n，指定第 n 列。

   * #n 的字符串格式，n 是整数，指定第 n 个显示列。

註解：

   * 数据项属性的显示顺序可能与存储顺序不一样。

   * #0 列一定是指 tree 列，即便未指定 show="tree" 也是一样。

数据列号是指属性值列表中的索引值，显示列号是指显示在树控件中的列号。树的
文本标签将显示在 #0 列。如果未设置 displaycolumns 属性，则数据列 n 将显
示在第 #n+1 列。再次强调一下，`#0 列一定是指 tree 列' 。


File: python.info,  Node: 虚拟事件<4>,  Next: ttk Treeview,  Prev: 列标识,  Up: Treeview

5.25.8.37 虚拟事件
..................

Treeview 控件会生成以下虚拟事件。

     Event                    描述
                              
     --------------------------------------------------------------------------------
                              
     <<TreeviewSelect>>       当选中项发生变化时生成。
                              
                              
     <<TreeviewOpen>>         当焦点所在项的 open= True 时立即生成。
                              
                              
     <<TreeviewClose>>        当焦点所在项的 open= True 之后立即生成。
                              

*note Treeview.focus(): 3365. 和 *note Treeview.selection(): 3df. 方法可
用于确认涉及的数据项。


File: python.info,  Node: ttk Treeview,  Prev: 虚拟事件<4>,  Up: Treeview

5.25.8.38 ttk.Treeview
......................

 -- 類別: tkinter.ttk.Treeview

      -- 成員函式: bbox (item, column=None)

          返回某 `数据项' 的边界（相对于控件窗口的坐标），形式为 (x, y,
          width, height) 。

          若给出了 `column'，则返回该单元格的边界。若该 `数据项' 不可见
          （即从属于已关闭项或滚动至屏幕外），则返回空字符串。

      -- 成員函式: get_children (item=None)

          返回从属于 `item' 的下级数据项列表。

          若未给出 `item' ，则返回根的下级。

      -- 成員函式: set_children (item, *newchildren)

          用 `newchildren' 替换 `item' 的下级数据。

          对于 `item' 中存在而 `newchildren' 中不存在的数据项，会从树中
          移除。`newchildren' 中的数据不能是 `item' 的上级。注意，未给出
          `newchildren' 会导致 `item' 的子项被移除。

      -- 成員函式: column (column, option=None, **kw)

          查询或修改 `column' 的属性。

          如果未给出 `kw'，则返回属性值的字典。若指定了 `option'，则会返
          回该属性值。否则将设置属性值。

          合法的 属性/值 可为：

             * 
               id

                    返回列名。这是只读属性。

             * 
               anchor：标准的 Tk 锚点值。

                    指定该列的文本在单元格内的对齐方式。

             * 
               minwidth：宽度。

                    列的最小宽度，单位是像素。在缩放控件或用户拖动某一列
                    时，Treeview 会保证列宽不小于此值。

             * 
               stretch: ‘True’/‘False’

                    指明列宽度是否应该在部件大小被改变时进行相应的调整。

             * 
               width: width

                    以像素表示的列宽度。

          要配置树的列，则调用此方法并附带参数 column = "#0"

      -- 成員函式: delete (*items)

          删除所有 `items' 及其下属。

          根不能删除。

      -- 成員函式: detach (*items)

          将所有 `items' 与树解除关联。

          数据项及其下属依然存在，后续可以重新插入，目前只是不显示出来。

          根不能解除关联。

      -- 成員函式: exists (item)

          如果给出的 `item' 位于树中，则返回 ‘True’。

      -- 成員函式: focus (item=None)

          如果给出 `item' 则设为当前焦点。否则返回当前焦点所在数据项，若
          无则返回 ’’。

      -- 成員函式: heading (column, option=None, **kw)

          查询或修改某 `column' 的标题。

          若未给出 `kw'，则返回列标题组成的列表。若给出了 `option' 则返
          回对应属性值。否则，设置属性值。

          合法的 属性/值 可为：

             * 
               text：文本。

                    显示为列标题的文本。

             * 
               image：图片名称

                    指定显示在列标题右侧的图片。

             * 
               anchor：锚点

                    指定列标题文本的对齐方式。应为标准的 Tk 锚点值。

             * 
               command：回调函数

                    点击列标题时执行的回调函数。

          若要对 tree 列进行设置，请带上 column = "#0" 进行调用。

      -- 成員函式: identify (component, x, y)

          返回 `x'、`y' 位置上 `component' 控件的描述信息，如果此处没有
          这种控件，则返回空字符串。

      -- 成員函式: identify_row (y)

          返回 `y' 位置上的数据项 ID。

      -- 成員函式: identify_column (x)

          返回 `x' 位置上的单元格所在的数据列 ID。

          tree 列的 ID 为 #0 。

      -- 成員函式: identify_region (x, y)

          返回以下值之一：

          region          区域
                          
          -----------------------------------------------------------
                          
          标题栏          树的标题栏区域。
                          
                          
          heading         两个列标题之间的间隔区域。
                          
                          
          tree            树区域。
                          
                          
          cell            数据单元格。
                          

          可用性：Tk 8.6。

      -- 成員函式: identify_element (x, y)

          返回位于 `x' 、`y' 的数据项。

          可用性：Tk 8.6。

      -- 成員函式: index (item)

          返回 `item' 在其数据项列表中的整数索引。

      -- 成員函式: insert (parent, index, iid=None, **kw)

          新建一个数据项并返回其 ID。

          `parent' 是父项的 ID，若要新建顶级项则为空字符串。 `index' 是
          整数或“end”，指明在父项的子项列表中的插入位置。如果 `index' 小
          于等于0，则在开头插入新节点；如果 `index' 大于或等于当前子节点
          数，则将其插入末尾。如果给出了 `iid'，则将其用作数据项 ID；
          `iid' 不得存在于树中。否则会新生成一个唯一 ID。

          此处可设置的属性请参阅 *note Item Options: 3362. 。

      -- 成員函式: item (item, option=None, **kw)

          查询或修改某 `item' 的属性。

          如果未给出 option，则返回属性/值构成的字典。如果给出了
          `option'，则返回该属性的值。否则，将属性设为 `kw' 给出的值。

      -- 成員函式: move (item, parent, index)

          将 `item' 移至指定位置，父项为 `parent' ，子项列表索引为
          `index' 。

          将数据项移入其子项之下是非法的。如果 `index' 小于等于0，`item'
          将被移到开头；如果大于等于子项的总数，则被移至最后。如果
          `item' 已解除关联，则会被重新连接。

      -- 成員函式: next (item)

          返回 `item' 的下一个相邻项，如果 `item' 是父项的最后一个子项，
          则返回 ’’。

      -- 成員函式: parent (item)

          返回 `item' 的父项 ID，如果 `item' 为顶级节点，则返回 ’’。

      -- 成員函式: prev (item)

          返回 `item' 的前一个相邻项，若 `item' 为父项的第一个子项，则返
          回 ’’。

      -- 成員函式: reattach (item, parent, index)

          *note Treeview.move(): 3377. 的别名。

      -- 成員函式: see (item)

          确保 `item' 可见。

          将 `item' 所有上级的 open 属性设为 ‘True’，必要时会滚动控件，
          让 `item' 处于树的可见部分。

      -- 成員函式: selection ()

          返回由选中项构成的元组。

          3.8 版更變: ‘selection()’ 不再接受参数了。若要改变选中的状态，
          请使用以下方法。

      -- 成員函式: selection_set (*items)

          让 `items' 成为新的选中项。

          3.6 版更變: `items' 可作为多个单独的参数传递，而不是作为一个元
          组。

      -- 成員函式: selection_add (*items)

          将 `items' 加入选中项。

          3.6 版更變: `items' 可作为多个单独的参数传递，而不是作为一个元
          组。

      -- 成員函式: selection_remove (*items)

          从选中项中移除 `items' 。

          3.6 版更變: `items' 可作为多个单独的参数传递，而不是作为一个元
          组。

      -- 成員函式: selection_toggle (*items)

          切换 `items' 中各项的选中状态。

          3.6 版更變: `items' 可作为多个单独的参数传递，而不是作为一个元
          组。

      -- 成員函式: set (item, column=None, value=None)

          若带一个参数，则返回指定 `item' 的列/值字典。若带两个参数，则
          返回 `column' 的当前值。若带三个参数，则将 `item' 的 `column'
          设为 `value'。

      -- 成員函式: tag_bind (tagname, sequence=None, callback=None)

          为 tag 为 `tagname' 的数据项绑定事件 `sequence' 的回调函数。当
          事件分发给该数据项时，tag 参数为 `tagname' 的全部数据项的回调
          都会被调用到。

      -- 成員函式: tag_configure (tagname, option=None, **kw)

          查询或修改 `tagname' 指定项的参数。

          如果给出了 `kw'，则返回 `tagname' 项的属性字典。如果给出了
          `option'，则返回 `tagname' 项的 `option' 属性值。否则，设置
          `tagname' 项的属性值。

      -- 成員函式: tag_has (tagname, item=None)

          如果给出了 `item' ，则依据 `item' 是否具备 `tagname' 而返回 1
          或 0。否则，返回 tag 为 `tagname' 的所有数据项构成的列表。

          可用性：Tk 8.6。

      -- 成員函式: xview (*args)

          查询或修改 Treeview 的横向位置。

      -- 成員函式: yview (*args)

          查询或修改 Treeview 的纵向位置。


File: python.info,  Node: Ttk 风格,  Prev: Treeview,  Up: tkinter ttk --- Tk主题部件

5.25.8.39 Ttk 风格
..................

‘ttk’ 的每种控件都赋有一个样式，指定了控件内的元素及其排列方式，以及元素
属性的动态和默认设置。默认情况下，样式名与控件的类名相同，但可能会被控件
的 style 属性覆盖。如果不知道控件的类名，可用 ‘Misc.winfo_class()’ 方法
获取（somewidget.winfo_class()）。

也參考
......

Tcl’2004 会议报告(1)

     文章解释了主题引擎的工作原理。

 -- 類別: tkinter.ttk.Style

     用于操控风格数据库的类。

      -- 成員函式: configure (style, query_opt=None, **kw)

          查询或设置 `style' 的默认参数。

          Each key in `kw' is an option and each value is a string
          identifying the value for that option.

          例如，要将默认按钮改为扁平样式，并带有留白和各种背景色：

               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()

      -- 成員函式: map (style, query_opt=None, **kw)

          查询或设置 `style' 的指定属性的动态值。

          Each key in `kw' is an option and each value should be a list
          or a tuple (usually) containing statespecs grouped in tuples,
          lists, or some other preference.  A statespec is a compound of
          one or more states and then a value.

          An example may make it more understandable:

               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()

          Note that the order of the (states, value) sequences for an
          option does matter, if the order is changed to ‘[('active',
          'blue'), ('pressed', 'red')]’ in the foreground option, for
          example, the result would be a blue foreground when the widget
          were in active or pressed states.

      -- 成員函式: lookup (style, option, state=None, default=None)

          Returns the value specified for `option' in `style'.

          If `state' is specified, it is expected to be a sequence of
          one or more states.  If the `default' argument is set, it is
          used as a fallback value in case no specification for option
          is found.

          To check what font a Button uses by default:

               from tkinter import ttk

               print(ttk.Style().lookup("TButton", "font"))

      -- 成員函式: layout (style, layoutspec=None)

          Define the widget layout for given `style'.  If `layoutspec'
          is omitted, return the layout specification for given style.

          `layoutspec', if specified, is expected to be a list or some
          other sequence type (excluding strings), where each item
          should be a tuple and the first item is the layout name and
          the second item should have the format described in *note
          Layouts: 3388.

          To understand the format, see the following example (it is not
          intended to do anything useful):

               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()

      -- 成員函式: element_create (elementname, etype, *args, **kw)

          Create a new element in the current theme, of the given
          `etype' which is expected to be either "image", "from" or
          "vsapi".  The latter is only available in Tk 8.6a for Windows
          XP and Vista and is not described here.

          If "image" is used, `args' should contain the default image
          name followed by statespec/value pairs (this is the
          imagespec), and `kw' may have the following options:

                  * 
                    border=padding

                         padding is a list of up to four integers,
                         specifying the left, top, right, and bottom
                         borders, respectively.

                  * 
                    height=height

                         Specifies a minimum height for the element.  If
                         less than zero, the base image’s height is used
                         as a default.

                  * 
                    padding=padding

                         Specifies the element’s interior padding.
                         Defaults to border’s value if not specified.

                  * 
                    sticky=spec

                         Specifies how the image is placed within the
                         final parcel.  spec contains zero or more
                         characters "n", "s", "w", or "e".

                  * 
                    width=width

                         Specifies a minimum width for the element.  If
                         less than zero, the base image’s width is used
                         as a default.

          If "from" is used as the value of `etype', *note
          element_create(): 3389. will clone an existing element.
          `args' is expected to contain a themename, from which the
          element will be cloned, and optionally an element to clone
          from.  If this element to clone from is not specified, an
          empty element will be used.  `kw' is discarded.

      -- 成員函式: element_names ()

          Returns the list of elements defined in the current theme.

      -- 成員函式: element_options (elementname)

          Returns the list of `elementname'’s options.

      -- 成員函式: theme_create (themename, parent=None, settings=None)

          Create a new theme.

          It is an error if `themename' already exists.  If `parent' is
          specified, the new theme will inherit styles, elements and
          layouts from the parent theme.  If `settings' are present they
          are expected to have the same syntax used for *note
          theme_settings(): 338d.

      -- 成員函式: theme_settings (themename, settings)

          Temporarily sets the current theme to `themename', apply
          specified `settings' and then restore the previous theme.

          Each key in `settings' is a style and each value may contain
          the keys ’configure’, ’map’, ’layout’ and ’element create’ and
          they are expected to have the same format as specified by the
          methods *note Style.configure(): 3385, *note Style.map(): fe4,
          *note Style.layout(): 3387. and *note Style.element_create():
          3389. respectively.

          As an example, let’s change the Combobox for the default theme
          a bit:

               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()

      -- 成員函式: theme_names ()

          Returns a list of all known themes.

      -- 成員函式: theme_use (themename=None)

          If `themename' is not given, returns the theme in use.
          Otherwise, sets the current theme to `themename', refreshes
          all widgets and emits a <<ThemeChanged>> event.

* Menu:

* Layouts::

   ---------- Footnotes ----------

   (1) http://tktable.sourceforge.net/tile/tile-tcl2004.pdf


File: python.info,  Node: Layouts,  Up: Ttk 风格

5.25.8.40 Layouts
.................

A layout can be just ‘None’, if it takes no options, or a dict of
options specifying how to arrange the element.  The layout mechanism
uses a simplified version of the pack geometry manager: given an initial
cavity, each element is allocated a parcel.  Valid options/values are:

        * 
          side: whichside

               Specifies which side of the cavity to place the element;
               one of top, right, bottom or left.  If omitted, the
               element occupies the entire cavity.

        * 
          sticky: nswe

               Specifies where the element is placed inside its
               allocated parcel.

        * 
          unit: 0 or 1

               If set to 1, causes the element and all of its
               descendants to be treated as a single element for the
               purposes of *note Widget.identify(): 3333. et al.  It’s
               used for things like scrollbar thumbs with grips.

        * 
          children: [sublayout... ]

               Specifies a list of elements to place inside the element.
               Each element is a tuple (or other sequence type) where
               the first item is the layout name, and the other is a
               *note Layout: 3388.


File: python.info,  Node: tkinter tix --- TK扩展包,  Next: IDLE<51>,  Prev: tkinter ttk --- Tk主题部件,  Up: 以 Tk 打造 GUI

5.25.9 ‘tkinter.tix’ — TK扩展包
-------------------------------

`源代码:' Lib/tkinter/tix.py(1)

3.6 版後已棄用: 这个 TK 扩展已无人维护所以请不要在新代码中使用。 请改用
*note tkinter.ttk: 118.。

__________________________________________________________________

The *note tkinter.tix: 117. (Tk Interface Extension) module provides an
additional rich set of widgets.  Although the standard Tk library has
many useful widgets, they are far from complete.  The *note tkinter.tix:
117. library provides most of the commonly needed widgets that are
missing from standard Tk: *note HList: 3394, *note ComboBox: 3395, *note
Control: 3396. (a.k.a.  SpinBox) and an assortment of scrollable
widgets.  *note tkinter.tix: 117. also includes many more widgets that
are generally useful in a wide range of applications: *note NoteBook:
3397, *note FileEntry: 3398, *note PanedWindow: 3399, etc; there are
more than 40 of them.

With all these new widgets, you can introduce new interaction techniques
into applications, creating more useful and more intuitive user
interfaces.  You can design your application by choosing the most
appropriate widgets to match the special needs of your application and
users.

也參考
......

Tix Homepage(2)

     The home page for ‘Tix’.  This includes links to additional
     documentation and downloads.

Tix Man Pages(3)

     On-line version of the man pages and reference material.

Tix Programming Guide(4)

     On-line version of the programmer’s reference material.

Tix Development Applications(5)

     Tix applications for development of Tix and Tkinter programs.  Tide
     applications work under Tk or Tkinter, and include ‘TixInspect’, an
     inspector to remotely modify and debug Tix/Tk/Tkinter applications.

* Menu:

* Using Tix::
* Tix Widgets::
* Tix Commands::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/tkinter/tix.py

   (2) http://tix.sourceforge.net/

   (3) http://tix.sourceforge.net/dist/current/man/

   (4) 
http://tix.sourceforge.net/dist/current/docs/tix-book/tix.book.html

   (5) http://tix.sourceforge.net/Tixapps/src/Tide.html


File: python.info,  Node: Using Tix,  Next: Tix Widgets,  Up: tkinter tix --- TK扩展包

5.25.9.1 Using Tix
..................

 -- 類別: tkinter.tix.Tk (screenName=None, baseName=None,
          className='Tix')

     Toplevel widget of Tix which represents mostly the main window of
     an application.  It has an associated Tcl interpreter.

     Classes in the *note tkinter.tix: 117. module subclasses the
     classes in the *note tkinter: 10e.  The former imports the latter,
     so to use *note tkinter.tix: 117. with Tkinter, all you need to do
     is to import one module.  In general, you can just import *note
     tkinter.tix: 117, and replace the toplevel call to *note
     tkinter.Tk: 32b0. with ‘tix.Tk’:

          from tkinter import tix
          from tkinter.constants import *
          root = tix.Tk()

To use *note tkinter.tix: 117, you must have the Tix widgets installed,
usually alongside your installation of the Tk widgets.  To test your
installation, try the following:

     from tkinter import tix
     root = tix.Tk()
     root.tk.eval('package require Tix')


File: python.info,  Node: Tix Widgets,  Next: Tix Commands,  Prev: Using Tix,  Up: tkinter tix --- TK扩展包

5.25.9.2 Tix Widgets
....................

Tix(1) introduces over 40 widget classes to the *note tkinter: 10e.
repertoire.

* Menu:

* Basic Widgets::
* File Selectors::
* Hierarchical ListBox::
* Tabular ListBox::
* Manager Widgets::
* Image Types::
* Miscellaneous Widgets::
* Form Geometry Manager::

   ---------- Footnotes ----------

   (1) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/TixIntro.htm


File: python.info,  Node: Basic Widgets,  Next: File Selectors,  Up: Tix Widgets

5.25.9.3 Basic Widgets
......................

 -- 類別: tkinter.tix.Balloon

     A Balloon(1) that pops up over a widget to provide help.  When the
     user moves the cursor inside a widget to which a Balloon widget has
     been bound, a small pop-up window with a descriptive message will
     be shown on the screen.

 -- 類別: tkinter.tix.ButtonBox

     The ButtonBox(2) widget creates a box of buttons, such as is
     commonly used for ‘Ok Cancel’.

 -- 類別: tkinter.tix.ComboBox

     The ComboBox(3) widget is similar to the combo box control in MS
     Windows.  The user can select a choice by either typing in the
     entry subwidget or selecting from the listbox subwidget.

 -- 類別: tkinter.tix.Control

     The Control(4) 控件又名 ‘SpinBox’ 控件。 用户可通过点按两个方向键或
     直接输入内容来调整数值。 更新的数值将被检查是否在用户定义的上下限之
     内。

 -- 類別: tkinter.tix.LabelEntry

     The LabelEntry(5) widget packages an entry widget and a label into
     one mega widget.  It can be used to simplify the creation of
     "entry-form" type of interface.

 -- 類別: tkinter.tix.LabelFrame

     The LabelFrame(6) widget packages a frame widget and a label into
     one mega widget.  To create widgets inside a LabelFrame widget, one
     creates the new widgets relative to the ‘frame’ subwidget and
     manage them inside the ‘frame’ subwidget.

 -- 類別: tkinter.tix.Meter

     The Meter(7) widget can be used to show the progress of a
     background job which may take a long time to execute.

 -- 類別: tkinter.tix.OptionMenu

     The OptionMenu(8) creates a menu button of options.

 -- 類別: tkinter.tix.PopupMenu

     The PopupMenu(9) widget can be used as a replacement of the
     ‘tk_popup’ command.  The advantage of the ‘Tix’ *note PopupMenu:
     33a4. widget is it requires less application code to manipulate.

 -- 類別: tkinter.tix.Select

     The Select(10) widget is a container of button subwidgets.  It can
     be used to provide radio-box or check-box style of selection
     options for the user.

 -- 類別: tkinter.tix.StdButtonBox

     The StdButtonBox(11) widget is a group of standard buttons for
     Motif-like dialog boxes.

   ---------- Footnotes ----------

   (1) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixBalloon.htm

   (2) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixButtonBox.htm

   (3) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixComboBox.htm

   (4) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixControl.htm

   (5) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixLabelEntry.htm

   (6) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixLabelFrame.htm

   (7) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixMeter.htm

   (8) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixOptionMenu.htm

   (9) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixPopupMenu.htm

   (10) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixSelect.htm

   (11) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixStdButtonBox.htm


File: python.info,  Node: File Selectors,  Next: Hierarchical ListBox,  Prev: Basic Widgets,  Up: Tix Widgets

5.25.9.4 File Selectors
.......................

 -- 類別: tkinter.tix.DirList

     The DirList(1) widget displays a list view of a directory, its
     previous directories and its sub-directories.  The user can choose
     one of the directories displayed in the list or change to another
     directory.

 -- 類別: tkinter.tix.DirTree

     The DirTree(2) widget displays a tree view of a directory, its
     previous directories and its sub-directories.  The user can choose
     one of the directories displayed in the list or change to another
     directory.

 -- 類別: tkinter.tix.DirSelectDialog

     The DirSelectDialog(3) widget presents the directories in the file
     system in a dialog window.  The user can use this dialog window to
     navigate through the file system to select the desired directory.

 -- 類別: tkinter.tix.DirSelectBox

     The *note DirSelectBox: 33ab. is similar to the standard Motif(TM)
     directory-selection box.  It is generally used for the user to
     choose a directory.  DirSelectBox stores the directories mostly
     recently selected into a ComboBox widget so that they can be
     quickly selected again.

 -- 類別: tkinter.tix.ExFileSelectBox

     The ExFileSelectBox(4) widget is usually embedded in a
     tixExFileSelectDialog widget.  It provides a convenient method for
     the user to select files.  The style of the *note ExFileSelectBox:
     33ac. widget is very similar to the standard file dialog on MS
     Windows 3.1.

 -- 類別: tkinter.tix.FileSelectBox

     The FileSelectBox(5) is similar to the standard Motif(TM)
     file-selection box.  It is generally used for the user to choose a
     file.  FileSelectBox stores the files mostly recently selected into
     a *note ComboBox: 3395. widget so that they can be quickly selected
     again.

 -- 類別: tkinter.tix.FileEntry

     The FileEntry(6) widget can be used to input a filename.  The user
     can type in the filename manually.  Alternatively, the user can
     press the button widget that sits next to the entry, which will
     bring up a file selection dialog.

   ---------- Footnotes ----------

   (1) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixDirList.htm

   (2) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixDirTree.htm

   (3) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixDirSelectDialog.htm

   (4) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixExFileSelectBox.htm

   (5) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixFileSelectBox.htm

   (6) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixFileEntry.htm


File: python.info,  Node: Hierarchical ListBox,  Next: Tabular ListBox,  Prev: File Selectors,  Up: Tix Widgets

5.25.9.5 Hierarchical ListBox
.............................

 -- 類別: tkinter.tix.HList

     The HList(1) widget can be used to display any data that have a
     hierarchical structure, for example, file system directory trees.
     The list entries are indented and connected by branch lines
     according to their places in the hierarchy.

 -- 類別: tkinter.tix.CheckList

     The CheckList(2) widget displays a list of items to be selected by
     the user.  CheckList acts similarly to the Tk checkbutton or
     radiobutton widgets, except it is capable of handling many more
     items than checkbuttons or radiobuttons.

 -- 類別: tkinter.tix.Tree

     The Tree(3) widget can be used to display hierarchical data in a
     tree form.  The user can adjust the view of the tree by opening or
     closing parts of the tree.

   ---------- Footnotes ----------

   (1) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixHList.htm

   (2) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixCheckList.htm

   (3) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixTree.htm


File: python.info,  Node: Tabular ListBox,  Next: Manager Widgets,  Prev: Hierarchical ListBox,  Up: Tix Widgets

5.25.9.6 Tabular ListBox
........................

 -- 類別: tkinter.tix.TList

     The TList(1) widget can be used to display data in a tabular
     format.  The list entries of a *note TList: 33b2. widget are
     similar to the entries in the Tk listbox widget.  The main
     differences are (1) the *note TList: 33b2. widget can display the
     list entries in a two dimensional format and (2) you can use
     graphical images as well as multiple colors and fonts for the list
     entries.

   ---------- Footnotes ----------

   (1) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixTList.htm


File: python.info,  Node: Manager Widgets,  Next: Image Types,  Prev: Tabular ListBox,  Up: Tix Widgets

5.25.9.7 Manager Widgets
........................

 -- 類別: tkinter.tix.PanedWindow

     The PanedWindow(1) widget allows the user to interactively
     manipulate the sizes of several panes.  The panes can be arranged
     either vertically or horizontally.  The user changes the sizes of
     the panes by dragging the resize handle between two panes.

 -- 類別: tkinter.tix.ListNoteBook

     The ListNoteBook(2) widget is very similar to the ‘TixNoteBook’
     widget: it can be used to display many windows in a limited space
     using a notebook metaphor.  The notebook is divided into a stack of
     pages (windows).  At one time only one of these pages can be shown.
     The user can navigate through these pages by choosing the name of
     the desired page in the ‘hlist’ subwidget.

 -- 類別: tkinter.tix.NoteBook

     The NoteBook(3) widget can be used to display many windows in a
     limited space using a notebook metaphor.  The notebook is divided
     into a stack of pages.  At one time only one of these pages can be
     shown.  The user can navigate through these pages by choosing the
     visual "tabs" at the top of the NoteBook widget.

   ---------- Footnotes ----------

   (1) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixPanedWindow.htm

   (2) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixListNoteBook.htm

   (3) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixNoteBook.htm


File: python.info,  Node: Image Types,  Next: Miscellaneous Widgets,  Prev: Manager Widgets,  Up: Tix Widgets

5.25.9.8 Image Types
....................

The *note tkinter.tix: 117. module adds:

   * pixmap(1) capabilities to all *note tkinter.tix: 117. and *note
     tkinter: 10e. widgets to create color images from XPM files.

   * Compound(2) image types can be used to create images that consists
     of multiple horizontal lines; each line is composed of a series of
     items (texts, bitmaps, images or spaces) arranged from left to
     right.  For example, a compound image can be used to display a
     bitmap and a text string simultaneously in a Tk ‘Button’ widget.

   ---------- Footnotes ----------

   (1) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/pixmap.htm

   (2) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/compound.htm


File: python.info,  Node: Miscellaneous Widgets,  Next: Form Geometry Manager,  Prev: Image Types,  Up: Tix Widgets

5.25.9.9 Miscellaneous Widgets
..............................

 -- 類別: tkinter.tix.InputOnly

     The InputOnly(1) widgets are to accept inputs from the user, which
     can be done with the ‘bind’ command (Unix only).

   ---------- Footnotes ----------

   (1) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixInputOnly.htm


File: python.info,  Node: Form Geometry Manager,  Prev: Miscellaneous Widgets,  Up: Tix Widgets

5.25.9.10 Form Geometry Manager
...............................

In addition, *note tkinter.tix: 117. augments *note tkinter: 10e. by
providing:

 -- 類別: tkinter.tix.Form

     The Form(1) geometry manager based on attachment rules for all Tk
     widgets.

   ---------- Footnotes ----------

   (1) 
http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixForm.htm


File: python.info,  Node: Tix Commands,  Prev: Tix Widgets,  Up: tkinter tix --- TK扩展包

5.25.9.11 Tix Commands
......................

 -- 類別: tkinter.tix.tixCommand

     The tix commands(1) provide access to miscellaneous elements of
     ‘Tix’’s internal state and the ‘Tix’ application context.  Most of
     the information manipulated by these methods pertains to the
     application as a whole, or to a screen or display, rather than to a
     particular window.

     To view the current settings, the common usage is:

          from tkinter import tix
          root = tix.Tk()
          print(root.tix_configure())

 -- 成員函式: tixCommand.tix_configure (cnf=None, **kw)

     Query or modify the configuration options of the Tix application
     context.  If no option is specified, returns a dictionary all of
     the available options.  If option is specified with no value, then
     the method returns a list describing the one named option (this
     list will be identical to the corresponding sublist of the value
     returned if no option is specified).  If one or more option-value
     pairs are specified, then the method modifies the given option(s)
     to have the given value(s); in this case the method returns an
     empty string.  Option may be any of the configuration options.

 -- 成員函式: tixCommand.tix_cget (option)

     Returns the current value of the configuration option given by
     `option'.  Option may be any of the configuration options.

 -- 成員函式: tixCommand.tix_getbitmap (name)

     Locates a bitmap file of the name ‘name.xpm’ or ‘name’ in one of
     the bitmap directories (see the *note tix_addbitmapdir(): 33bf.
     method).  By using *note tix_getbitmap(): 33be, you can avoid hard
     coding the pathnames of the bitmap files in your application.  When
     successful, it returns the complete pathname of the bitmap file,
     prefixed with the character ‘@’.  The returned value can be used to
     configure the ‘bitmap’ option of the Tk and Tix widgets.

 -- 成員函式: tixCommand.tix_addbitmapdir (directory)

     Tix maintains a list of directories under which the *note
     tix_getimage(): 33c0. and *note tix_getbitmap(): 33be. methods will
     search for image files.  The standard bitmap directory is
     ‘$TIX_LIBRARY/bitmaps’.  The *note tix_addbitmapdir(): 33bf. method
     adds `directory' into this list.  By using this method, the image
     files of an applications can also be located using the *note
     tix_getimage(): 33c0. or *note tix_getbitmap(): 33be. method.

 -- 成員函式: tixCommand.tix_filedialog ([dlgclass])

     Returns the file selection dialog that may be shared among
     different calls from this application.  This method will create a
     file selection dialog widget when it is called the first time.
     This dialog will be returned by all subsequent calls to *note
     tix_filedialog(): 33c1.  An optional dlgclass parameter can be
     passed as a string to specified what type of file selection dialog
     widget is desired.  Possible options are ‘tix’, ‘FileSelectDialog’
     or ‘tixExFileSelectDialog’.

 -- 成員函式: tixCommand.tix_getimage (self, name)

     Locates an image file of the name ‘name.xpm’, ‘name.xbm’ or
     ‘name.ppm’ in one of the bitmap directories (see the *note
     tix_addbitmapdir(): 33bf. method above).  If more than one file
     with the same name (but different extensions) exist, then the image
     type is chosen according to the depth of the X display: xbm images
     are chosen on monochrome displays and color images are chosen on
     color displays.  By using *note tix_getimage(): 33c0, you can avoid
     hard coding the pathnames of the image files in your application.
     When successful, this method returns the name of the newly created
     image, which can be used to configure the ‘image’ option of the Tk
     and Tix widgets.

 -- 成員函式: tixCommand.tix_option_get (name)

     Gets the options maintained by the Tix scheme mechanism.

 -- 成員函式: tixCommand.tix_resetoptions (newScheme, newFontSet[,
          newScmPrio])

     Resets the scheme and fontset of the Tix application to `newScheme'
     and `newFontSet', respectively.  This affects only those widgets
     created after this call.  Therefore, it is best to call the
     resetoptions method before the creation of any widgets in a Tix
     application.

     The optional parameter `newScmPrio' can be given to reset the
     priority level of the Tk options set by the Tix schemes.

     Because of the way Tk handles the X option database, after Tix has
     been has imported and inited, it is not possible to reset the color
     schemes and font sets using the ‘tix_config()’ method.  Instead,
     the *note tix_resetoptions(): 33c3. method must be used.

   ---------- Footnotes ----------

   (1) http://tix.sourceforge.net/dist/current/man/html/TixCmd/tix.htm


File: python.info,  Node: IDLE<51>,  Prev: tkinter tix --- TK扩展包,  Up: 以 Tk 打造 GUI

5.25.10 IDLE
------------

`源代码：' Lib/idlelib/(1)

__________________________________________________________________

IDLE 是 Python 所内置的开发与学习环境。

IDLE 具有以下特性：

   * 编码于 100% 纯正的 Python，使用名为 *note tkinter: 10e. 的图形用户
     界面工具

   * 跨平台：在 Windows、Unix 和 macOS 上工作近似。

   * 提供输入输出高亮和错误信息的 Python 命令行窗口 （交互解释器）

   * 提供多次撤销操作、Python 语法高亮、智能缩进、函数调用提示、自动补全
     等功能的多窗口文本编辑器

   * 在多个窗口中检索，在编辑器中替换文本，以及在多个文件中检索（通过
     grep）

   * 提供持久保存的断点调试、单步调试、查看本地和全局命名空间功能的调试
     器

   * 配置、浏览以及其它对话框

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/idlelib/


File: python.info,  Node: 目录,  Next: 编辑和导航,  Up: IDLE<51>

5.25.10.1 目录
..............

IDEL 有两种主要的窗口类型：Shell窗口和编辑器窗口。其中编辑器窗口可以同时
打开多个。并且对于 Windows 和 Linux 平台，窗口顶部主菜单各不相同。以下每
个菜单说明项，都标识了与之关联的平台类型。

导出窗口，例如使用 编辑=>在文件中查找 是编辑器窗口的的一个子类型。它们目
前有着相同的主菜单，但是默认标题和上下文菜单不同。

在macOS上，只有一个应用程序菜单。它会根据当前选择的窗口动态变化。它具有
一个IDLE菜单，并且下面描述的某些条目已移动到符合Apple准则的位置。

* Menu:

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


File: python.info,  Node: 文件菜单 （命令行和编辑器）,  Next: 编辑菜单（命令行和编辑器）,  Up: 目录

5.25.10.2 文件菜单 （命令行和编辑器）
.....................................

新建文件

     创建一个文件编辑器窗口。

打开...

     使用打开窗口以打开一个已存在的文件。

近期文件

     打开一个近期文件列表，选取一个以打开它。

打开模块...

     打开一个已存在的模块 （搜索 sys.path）

类浏览器

     于当前所编辑的文件中使用树形结构展示函数、类以及方法。在命令行中，
     首先打开一个模块。

路径浏览

     在树状结构中展示 sys.path 目录、模块、函数、类和方法。

保存

     如果文件已经存在，则将当前窗口保存至对应的文件。自打开或上次保存之
     后经过修改的文件的窗口标题栏首尾将出现星号 * 。如果没有对应的文件，
     则使用“另存为”代替。

保存为...

     使用“保存为”对话框保存当前窗口。被保存的文件将作为当前窗口新的对应
     文件。

另存为副本...

     保存当前窗口至另一个文件，而不修改当前对应文件。

打印窗口

     通过默认打印机打印当前窗口。

关闭

     关闭当前窗口（如果未保存则询问）。

退出

     关闭所有窗口并退出 IDLE（如果未保存则询问）


File: python.info,  Node: 编辑菜单（命令行和编辑器）,  Next: 格式菜单（仅 window 编辑器）,  Prev: 文件菜单 （命令行和编辑器）,  Up: 目录

5.25.10.3 编辑菜单（命令行和编辑器）
....................................

撤销操作

     撤销当前窗口的最近一次操作。最高可以撤回 1000 条操作记录。

重做

     重做当前窗口最近一次所撤销的操作。

剪切

     复制选区至系统剪贴板，然后删除选区。

复制

     复制选区至系统剪贴板。

粘贴

     插入系统剪贴板的内容至当前窗口。

剪贴板功能也可用于上下文目录。

全选

     选择当前窗口的全部内容。

查找...

     打开一个提供多选项的查找窗口。

再次查找

     重复上一次搜索（如果有的话）。

查找选区

     查找当前选中的字符串，如果存在

在文件中查找...

     打开文件查找对话框。将结果输出至新的输出窗口。

替换...

     打开 查找并替换 对话框。

前往行

     Move the cursor to the beginning of the line requested and make
     that line visible.  A request past the end of the file goes to the
     end.  Clear any selection and update the line and column status.

提示完成

     Open a scrollable list allowing selection of existing names.  See
     *note Completions: 33c9. in the Editing and navigation section
     below.

展开文本

     展开键入的前缀以匹配同一窗口中的完整单词；重复以获得不同的扩展。

显示调用贴士

     在函数的右括号后，打开一个带有函数参数提示的小窗口。请参阅下面的“编
     辑和导航”部分中的 *note Calltips: 33ca. 。

显示周围括号

     突出显示周围的括号。


File: python.info,  Node: 格式菜单（仅 window 编辑器）,  Next: 运行菜单（仅 window 编辑器）,  Prev: 编辑菜单（命令行和编辑器）,  Up: 目录

5.25.10.4 格式菜单（仅 window 编辑器）
......................................

增加缩进

     将选定的行右缩进（默认为4个空格）。

减少缩进

     将选定的行左缩进（默认为4个空格）。

注释

     在所选行的前面插入 ##。

取消注释

     从所选行中删除开头的 ＃ 或 ##。

制表符化

     将 `前导' 空格变成制表符。 （注意：我们建议使用4个空格来缩进
     Python代码。）

取消制表符化

     将 `所有' 制表符转换为正确的空格数。

缩进方式切换

     打开一个对话框，以在制表符和空格之间切换。

缩进宽度调整

     打开一个对话框以更改缩进宽度。 Python社区接受的默认值为4个空格。

格式段落

     在注释块或多行字符串或字符串中的选定行中，重新格式化当前以空行分隔
     的段落。段落中的所有行的格式都将少于N列，其中N默认为72。

删除尾随空格

     通过将 str.rstrip 应用于每行（包括多行字符串中的行），删除行尾非空
     白字符之后的尾随空格和其他空白字符。除Shell窗口外，在文件末尾删除多
     余的换行符。


File: python.info,  Node: 运行菜单（仅 window 编辑器）,  Next: Shell 菜单（仅 window 编辑器）,  Prev: 格式菜单（仅 window 编辑器）,  Up: 目录

5.25.10.5 运行菜单（仅 window 编辑器）
......................................

运行模块

     执行 *note 检查模块: 33cf. 。如果没有错误，重新启动 shell 以清理环
     境，然后执行模块。输出显示在 shell 窗口中。请注意，输出需要使用 “打
     印” 或 “写入”。执行完成后，Shell 将保留焦点并显示提示。此时，可以交
     互地探索执行的结果。这类似于在命令行执行带有 ‘python -i file’ 的文
     件。

运行... 定制

     与 *note 运行模块: 33ce. 相同，但使用自定义设置运行该模块。`命令行
     参数' 扩展 *note sys.argv: cc6. ，就像在命令行上传递一样。该模块可
     以在命令行管理程序中运行，而无需重新启动。

检查模块

     检查 “编辑器” 窗口中当前打开的模块的语法。如果尚未保存该模块，则
     IDLE会提示用户保存或自动保存，如在 “空闲设置” 对话框的 “常规” 选项
     卡中所选择的那样。如果存在语法错误，则会在 “编辑器” 窗口中指示大概
     位置。

Python Shell

     打开或唤醒Python Shell窗口。


File: python.info,  Node: Shell 菜单（仅 window 编辑器）,  Next: 调试菜单（仅 window 编辑器）,  Prev: 运行菜单（仅 window 编辑器）,  Up: 目录

5.25.10.6 Shell 菜单（仅 window 编辑器）
........................................

查看最近重启

     将Shell窗口滚动到上一次Shell重启。

重启Shell

     重启 shell 以清理环境，重置显示和异常处理。

上一条历史记录

     循环浏览历史记录中与当前条目匹配的早期命令。

下一条历史记录

     循环浏览历史记录中与当前条目匹配的后续命令。

中断执行

     停止正在运行的程序。


File: python.info,  Node: 调试菜单（仅 window 编辑器）,  Next: 选项菜单（命令行和编辑器）,  Prev: Shell 菜单（仅 window 编辑器）,  Up: 目录

5.25.10.7 调试菜单（仅 window 编辑器）
......................................

跳转到文件/行

     Look on the current line.  with the cursor, and the line above for
     a filename and line number.  If found, open the file if not already
     open, and show the line.  Use this to view source lines referenced
     in an exception traceback and lines found by Find in Files.  Also
     available in the context menu of the Shell window and Output
     windows.

调试器（切换）

     激活后，在Shell中输入的代码或从编辑器中运行的代码将在调试器下运行。
     在编辑器中，可以使用上下文菜单设置断点。此功能不完整，具有实验性。

堆栈查看器

     在树状目录中显示最后一个异常的堆栈回溯，可以访问本地和全局。

自动打开堆栈查看器

     在未处理的异常上切换自动打开堆栈查看器。


File: python.info,  Node: 选项菜单（命令行和编辑器）,  Next: Window 菜单（命令行和编辑器）,  Prev: 调试菜单（仅 window 编辑器）,  Up: 目录

5.25.10.8 选项菜单（命令行和编辑器）
....................................

配置 IDLE

     打开配置对话框并更改以下各项的首选项：字体、缩进、键绑定、文本颜色
     主题、启动窗口和大小、其他帮助源和扩展名。在MacOS上，通过在应用程序
     菜单中选择首选项来打开配置对话框。有关详细信息，请参阅：帮助和首选
     项下的 *note 首选项设置: 33d5.。

大多数配置选项适用于所有窗口或将来的所有窗口。以下选项仅适用于活动窗口。

显示/隐藏代码上下文（仅 window 编辑器）

     Open a pane at the top of the edit window which shows the block
     context of the code which has scrolled above the top of the window.
     See *note Code Context: 33d6. in the Editing and Navigation section
     below.

显示/隐藏行号（仅 window 编辑器）

     Open a column to the left of the edit window which shows the number
     of each line of text.  The default is off, which may be changed in
     the preferences (see *note Setting preferences: 33d5.).

缩放/还原高度

     Toggles the window between normal size and maximum height.  The
     initial size defaults to 40 lines by 80 chars unless changed on the
     General tab of the Configure IDLE dialog.  The maximum height for a
     screen is determined by momentarily maximizing a window the first
     time one is zoomed on the screen.  Changing screen settings may
     invalidate the saved height.  This toggle has no effect when a
     window is maximized.


File: python.info,  Node: Window 菜单（命令行和编辑器）,  Next: 帮助菜单（命令行和编辑器）,  Prev: 选项菜单（命令行和编辑器）,  Up: 目录

5.25.10.9 Window 菜单（命令行和编辑器）
.......................................

列出所有打开的窗口的名称；选择一个将其带到前台（必要时对其进行去符号化）
。


File: python.info,  Node: 帮助菜单（命令行和编辑器）,  Next: 上下文菜单,  Prev: Window 菜单（命令行和编辑器）,  Up: 目录

5.25.10.10 帮助菜单（命令行和编辑器）
.....................................

关于 IDLE

     显示版本，版权，许可证，荣誉等。

IDLE 帮助

     显示此 IDLE 文档，详细介绍菜单选项，基本编辑和导航以及其他技巧。

Python 文档

     访问本地Python文档（如果已安装），或启动Web浏览器并打开
     docs.python.org显示最新的Python文档。

海龟演示

     使用示例 Python 代码运行 turtledemo 模块和海龟绘图

可以在 “常规” 选项卡下的 “配置IDLE” 对话框中添加其他帮助源。有关“帮助”菜
单选项的更多信息，请参见下面的 *note 帮助源: 33d9. 小节。


File: python.info,  Node: 上下文菜单,  Prev: 帮助菜单（命令行和编辑器）,  Up: 目录

5.25.10.11 上下文菜单
.....................

Open a context menu by right-clicking in a window (Control-click on
macOS). Context menus have the standard clipboard functions also on the
Edit menu.

剪切

     复制选区至系统剪贴板，然后删除选区。

复制

     复制选区至系统剪贴板。

粘贴

     插入系统剪贴板的内容至当前窗口。

Editor windows also have breakpoint functions.  Lines with a breakpoint
set are specially marked.  Breakpoints only have an effect when running
under the debugger.  Breakpoints for a file are saved in the user’s
‘.idlerc’ directory.

设置断点

     在当前行设置断点

清除断点

     清除当前行断点

shell 和输出窗口还具有以下内容。

跳转到文件/行

     与调试菜单相同。

The Shell window also has an output squeezing facility explained in the
`Python Shell window' subsection below.

压缩

     If the cursor is over an output line, squeeze all the output
     between the code above and the prompt below down to a ’Squeezed
     text’ label.


File: python.info,  Node: 编辑和导航,  Next: 启动和代码执行,  Prev: 目录,  Up: IDLE<51>

5.25.10.12 编辑和导航
.....................

* Menu:

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


File: python.info,  Node: 编辑窗口,  Next: 按键绑定,  Up: 编辑和导航

5.25.10.13 编辑窗口
...................

IDLE may open editor windows when it starts, depending on settings and
how you start IDLE. Thereafter, use the File menu.  There can be only
one open editor window for a given file.

The title bar contains the name of the file, the full path, and the
version of Python and IDLE running the window.  The status bar contains
the line number (’Ln’) and column number (’Col’).  Line numbers start
with 1; column numbers with 0.

IDLE assumes that files with a known .py* extension contain Python code
and that other files do not.  Run Python code with the Run menu.


File: python.info,  Node: 按键绑定,  Next: 自动缩进,  Prev: 编辑窗口,  Up: 编辑和导航

5.25.10.14 按键绑定
...................

在本节中，’C’ 是指 Windows 和 Unix 上的 ‘Control’ 键，以及 macOS 上的
‘Command’ 键。

   * ‘Backspace’ 向左删除; ‘Del’ 向右删除

   * ‘C-Backspace’ 向左删除单词; ‘C-Del’ 向右删除单词

   * 方向键和 ‘Page Up’/‘Page Down’ 移动

   * ‘C-LeftArrow’ 和 ‘C-RightArrow’ 按单词移动

   * ‘Home’/‘End’ 跳转到行首/尾

   * ‘C-Home’/‘C-End’ 跳转到文档首/尾

   * 一些有用的Emacs绑定是从Tcl / Tk继承的：

             * ‘C-a’ 行首

             * ‘C-e’ 行尾

             * ‘C-k’ 删除行（但未将其放入剪贴板）

             * ‘C-l’ center window around the insertion point

             * ‘C-b’ go backward one character without deleting (usually
               you can also use the cursor key for this)

             * ‘C-f’ go forward one character without deleting (usually
               you can also use the cursor key for this)

             * ‘C-p’ go up one line (usually you can also use the cursor
               key for this)

             * ‘C-d’ 删除下一个字符

Standard keybindings (like ‘C-c’ to copy and ‘C-v’ to paste) may work.
Keybindings are selected in the Configure IDLE dialog.


File: python.info,  Node: 自动缩进,  Next: 完成,  Prev: 按键绑定,  Up: 编辑和导航

5.25.10.15 自动缩进
...................

After a block-opening statement, the next line is indented by 4 spaces
(in the Python Shell window by one tab).  After certain keywords (break,
return etc.)  the next line is dedented.  In leading indentation,
‘Backspace’ deletes up to 4 spaces if they are there.  ‘Tab’ inserts
spaces (in the Python Shell window one tab), number depends on Indent
width.  Currently, tabs are restricted to four spaces due to Tcl/Tk
limitations.

See also the indent/dedent region commands on the *note Format menu:
33cb.


File: python.info,  Node: 完成,  Next: 提示,  Prev: 自动缩进,  Up: 编辑和导航

5.25.10.16 完成
...............

Completions are supplied, when requested and available, for module
names, attributes of classes or functions, or filenames.  Each request
method displays a completion box with existing names.  (See tab
completions below for an exception.)  For any box, change the name being
completed and the item highlighted in the box by typing and deleting
characters; by hitting ‘Up’, ‘Down’, ‘PageUp’, ‘PageDown’, ‘Home’, and
‘End’ keys; and by a single click within the box.  Close the box with
‘Escape’, ‘Enter’, and double ‘Tab’ keys or clicks outside the box.  A
double click within the box selects and closes.

One way to open a box is to type a key character and wait for a
predefined interval.  This defaults to 2 seconds; customize it in the
settings dialog.  (To prevent auto popups, set the delay to a large
number of milliseconds, such as 100000000.)  For imported module names
or class or function attributes, type ’.’.  For filenames in the root
directory, type *note os.sep: 1dd4. or *note os.altsep: 1dd5.
immediately after an opening quote.  (On Windows, one can specify a
drive first.)  Move into subdirectories by typing a directory name and a
separator.

Instead of waiting, or after a box is closed, open a completion box
immediately with Show Completions on the Edit menu.  The default hot key
is ‘C-space’.  If one types a prefix for the desired name before opening
the box, the first match or near miss is made visible.  The result is
the same as if one enters a prefix after the box is displayed.  Show
Completions after a quote completes filenames in the current directory
instead of a root directory.

Hitting ‘Tab’ after a prefix usually has the same effect as Show
Completions.  (With no prefix, it indents.)  However, if there is only
one match to the prefix, that match is immediately added to the editor
text without opening a box.

Invoking ’Show Completions’, or hitting ‘Tab’ after a prefix, outside of
a string and without a preceding ’.’ opens a box with keywords, builtin
names, and available module-level names.

When editing code in an editor (as oppose to Shell), increase the
available module-level names by running your code and not restarting the
Shell thereafter.  This is especially useful after adding imports at the
top of a file.  This also increases possible attribute completions.

Completion boxes initially exclude names beginning with ’_’ or, for
modules, not included in ’__all__’.  The hidden names can be accessed by
typing ’_’ after ’.’, either before or after the box is opened.


File: python.info,  Node: 提示,  Next: 代码上下文,  Prev: 完成,  Up: 编辑和导航

5.25.10.17 提示
...............

A calltip is shown automatically when one types ‘(’ after the name of an
`accessible' function.  A function name expression may include dots and
subscripts.  A calltip remains until it is clicked, the cursor is moved
out of the argument area, or ‘)’ is typed.  Whenever the cursor is in
the argument part of a definition, select Edit and "Show Call Tip" on
the menu or enter its shortcut to display a calltip.

The calltip consists of the function’s signature and docstring up to the
latter’s first blank line or the fifth non-blank line.  (Some builtin
functions lack an accessible signature.)  A ’/’ or ’*’ in the signature
indicates that the preceding or following arguments are passed by
position or name (keyword) only.  Details are subject to change.

In Shell, the accessible functions depends on what modules have been
imported into the user process, including those imported by Idle itself,
and which definitions have been run, all since the last restart.

For example, restart the Shell and enter ‘itertools.count(’.  A calltip
appears because Idle imports itertools into the user process for its own
use.  (This could change.)  Enter ‘turtle.write(’ and nothing appears.
Idle does not itself import turtle.  The menu entry and shortcut also do
nothing.  Enter ‘import turtle’.  Thereafter, ‘turtle.write(’ will
display a calltip.

In an editor, import statements have no effect until one runs the file.
One might want to run a file after writing import statements, after
adding function definitions, or after opening an existing file.


File: python.info,  Node: 代码上下文,  Next: Python Shell 窗口,  Prev: 提示,  Up: 编辑和导航

5.25.10.18 代码上下文
.....................

Within an editor window containing Python code, code context can be
toggled in order to show or hide a pane at the top of the window.  When
shown, this pane freezes the opening lines for block code, such as those
beginning with ‘class’, ‘def’, or ‘if’ keywords, that would have
otherwise scrolled out of view.  The size of the pane will be expanded
and contracted as needed to show the all current levels of context, up
to the maximum number of lines defined in the Configure IDLE dialog
(which defaults to 15).  If there are no current context lines and the
feature is toggled on, a single blank line will display.  Clicking on a
line in the context pane will move that line to the top of the editor.

The text and background colors for the context pane can be configured
under the Highlights tab in the Configure IDLE dialog.


File: python.info,  Node: Python Shell 窗口,  Next: 文本颜色,  Prev: 代码上下文,  Up: 编辑和导航

5.25.10.19 Python Shell 窗口
............................

With IDLE’s Shell, one enters, edits, and recalls complete statements.
Most consoles and terminals only work with a single physical line at a
time.

When one pastes code into Shell, it is not compiled and possibly
executed until one hits ‘Return’.  One may edit pasted code first.  If
one pastes more that one statement into Shell, the result will be a
*note SyntaxError: 559. when multiple statements are compiled as if they
were one.

The editing features described in previous subsections work when
entering code interactively.  IDLE’s Shell window also responds to the
following keys.

   * ‘C-c’ 中断执行命令

   * ‘C-d’ sends end-of-file; closes window if typed at a ‘>>>’ prompt

   * ‘Alt-/’ (Expand word) is also useful to reduce typing

     历史命令

        * ‘Alt-p’ retrieves previous command matching what you have
          typed.  On macOS use ‘C-p’.

        * ‘Alt-n’ retrieves next.  On macOS use ‘C-n’.

        * ‘Return’ while on any previous command retrieves that command


File: python.info,  Node: 文本颜色,  Prev: Python Shell 窗口,  Up: 编辑和导航

5.25.10.20 文本颜色
...................

Idle defaults to black on white text, but colors text with special
meanings.  For the shell, these are shell output, shell error, user
output, and user error.  For Python code, at the shell prompt or in an
editor, these are keywords, builtin class and function names, names
following ‘class’ and ‘def’, strings, and comments.  For any text
window, these are the cursor (when present), found text (when possible),
and selected text.

Text coloring is done in the background, so uncolorized text is
occasionally visible.  To change the color scheme, use the Configure
IDLE dialog Highlighting tab.  The marking of debugger breakpoint lines
in the editor and text in popups and dialogs is not user-configurable.


File: python.info,  Node: 启动和代码执行,  Next: 帮助和偏好,  Prev: 编辑和导航,  Up: IDLE<51>

5.25.10.21 启动和代码执行
.........................

Upon startup with the ‘-s’ option, IDLE will execute the file referenced
by the environment variables ‘IDLESTARTUP’ or *note PYTHONSTARTUP: 9cb.
IDLE first checks for ‘IDLESTARTUP’; if ‘IDLESTARTUP’ is present the
file referenced is run.  If ‘IDLESTARTUP’ is not present, IDLE checks
for ‘PYTHONSTARTUP’.  Files referenced by these environment variables
are convenient places to store functions that are used frequently from
the IDLE shell, or for executing import statements to import common
modules.

In addition, ‘Tk’ also loads a startup file if it is present.  Note that
the Tk file is loaded unconditionally.  This additional file is
‘.Idle.py’ and is looked for in the user’s home directory.  Statements
in this file will be executed in the Tk namespace, so this file is not
useful for importing functions to be used from IDLE’s Python shell.

* Menu:

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


File: python.info,  Node: 命令行语法,  Next: 启动失败,  Up: 启动和代码执行

5.25.10.22 命令行语法
.....................

     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)

如果有参数：

   * If ‘-’, ‘-c’, or ‘r’ is used, all arguments are placed in
     ‘sys.argv[1:...]’ and ‘sys.argv[0]’ is set to ‘''’, ‘'-c'’, or
     ‘'-r'’.  No editor window is opened, even if that is the default
     set in the Options dialog.

   * Otherwise, arguments are files opened for editing and ‘sys.argv’
     reflects the arguments passed to IDLE itself.


File: python.info,  Node: 启动失败,  Next: 运行用户代码,  Prev: 命令行语法,  Up: 启动和代码执行

5.25.10.23 启动失败
...................

IDLE uses a socket to communicate between the IDLE GUI process and the
user code execution process.  A connection must be established whenever
the Shell starts or restarts.  (The latter is indicated by a divider
line that says ’RESTART’).  If the user process fails to connect to the
GUI process, it usually displays a ‘Tk’ error box with a ’cannot
connect’ message that directs the user here.  It then exits.

One specific connection failure on Unix systems results from
misconfigured masquerading rules somewhere in a system’s network setup.
When IDLE is started from a terminal, one will see a message starting
with ‘** Invalid host:’.  The valid value is ‘127.0.0.1
(idlelib.rpc.LOCALHOST)’.  One can diagnose with ‘tcpconnect -irv
127.0.0.1 6543’ in one terminal window and ‘tcplisten <same args>’ in
another.

A common cause of failure is a user-written file with the same name as a
standard library module, such as `random.py' and `tkinter.py'.  When
such a file is located in the same directory as a file that is about to
be run, IDLE cannot import the stdlib file.  The current fix is to
rename the user file.

Though less common than in the past, an antivirus or firewall program
may stop the connection.  If the program cannot be taught to allow the
connection, then it must be turned off for IDLE to work.  It is safe to
allow this internal connection because no data is visible on external
ports.  A similar problem is a network mis-configuration that blocks
connections.

Python installation issues occasionally stop IDLE: multiple versions can
clash, or a single installation might need admin access.  If one undo
the clash, or cannot or does not want to run as admin, it might be
easiest to completely remove Python and start over.

A zombie pythonw.exe process could be a problem.  On Windows, use Task
Manager to check for one and stop it if there is.  Sometimes a restart
initiated by a program crash or Keyboard Interrupt (control-C) may fail
to connect.  Dismissing the error box or using Restart Shell on the
Shell menu may fix a temporary problem.

When IDLE first starts, it attempts to read user configuration files in
‘~/.idlerc/’ (~ is one’s home directory).  If there is a problem, an
error message should be displayed.  Leaving aside random disk glitches,
this can be prevented by never editing the files by hand.  Instead, use
the configuration dialog, under Options.  Once there is an error in a
user configuration file, the best solution may be to delete it and start
over with the settings dialog.

If IDLE quits with no message, and it was not started from a console,
try starting it from a console or terminal (‘python -m idlelib’) and see
if this results in an error message.

On Unix-based systems with tcl/tk older than ‘8.6.11’ (see ‘About IDLE’)
certain characters of certain fonts can cause a tk failure with a
message to the terminal.  This can happen either if one starts IDLE to
edit a file with such a character or later when entering such a
character.  If one cannot upgrade tcl/tk, then re-configure IDLE to use
a font that works better.


File: python.info,  Node: 运行用户代码,  Next: Shell中的用户输出,  Prev: 启动失败,  Up: 启动和代码执行

5.25.10.24 运行用户代码
.......................

With rare exceptions, the result of executing Python code with IDLE is
intended to be the same as executing the same code by the default
method, directly with Python in a text-mode system console or terminal
window.  However, the different interface and operation occasionally
affect visible results.  For instance, ‘sys.modules’ starts with more
entries, and ‘threading.active_count()’ returns 2 instead of 1.

By default, IDLE runs user code in a separate OS process rather than in
the user interface process that runs the shell and editor.  In the
execution process, it replaces ‘sys.stdin’, ‘sys.stdout’, and
‘sys.stderr’ with objects that get input from and send output to the
Shell window.  The original values stored in ‘sys.__stdin__’,
‘sys.__stdout__’, and ‘sys.__stderr__’ are not touched, but may be
‘None’.

Sending print output from one process to a text widget in another is
slower than printing to a system terminal in the same process.  This has
the most effect when printing multiple arguments, as the string for each
argument, each separator, the newline are sent separately.  For
development, this is usually not a problem, but if one wants to print
faster in IDLE, format and join together everything one wants displayed
together and then print a single string.  Both format strings and *note
str.join(): 1766. can help combine fields and lines.

IDLE’s standard stream replacements are not inherited by subprocesses
created in the execution process, whether directly by user code or by
modules such as multiprocessing.  If such subprocess use ‘input’ from
sys.stdin or ‘print’ or ‘write’ to sys.stdout or sys.stderr, IDLE should
be started in a command line window.  The secondary subprocess will then
be attached to that window for input and output.

If ‘sys’ is reset by user code, such as with ‘importlib.reload(sys)’,
IDLE’s changes are lost and input from the keyboard and output to the
screen will not work correctly.

When Shell has the focus, it controls the keyboard and screen.  This is
normally transparent, but functions that directly access the keyboard
and screen will not work.  These include system-specific functions that
determine whether a key has been pressed and if so, which.

The IDLE code running in the execution process adds frames to the call
stack that would not be there otherwise.  IDLE wraps
‘sys.getrecursionlimit’ and ‘sys.setrecursionlimit’ to reduce the effect
of the additional stack frames.

When user code raises SystemExit either directly or by calling sys.exit,
IDLE returns to a Shell prompt instead of exiting.


File: python.info,  Node: Shell中的用户输出,  Next: 开发 tkinter 应用程序,  Prev: 运行用户代码,  Up: 启动和代码执行

5.25.10.25 Shell中的用户输出
............................

When a program outputs text, the result is determined by the
corresponding output device.  When IDLE executes user code, ‘sys.stdout’
and ‘sys.stderr’ are connected to the display area of IDLE’s Shell.
Some of its features are inherited from the underlying Tk Text widget.
Others are programmed additions.  Where it matters, Shell is designed
for development rather than production runs.

For instance, Shell never throws away output.  A program that sends
unlimited output to Shell will eventually fill memory, resulting in a
memory error.  In contrast, some system text windows only keep the last
n lines of output.  A Windows console, for instance, keeps a
user-settable 1 to 9999 lines, with 300 the default.

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.)

     >>> 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='')  # Display s as is.
     # Result varies by OS and font.  Try it.

The ‘repr’ function is used for interactive echo of expression values.
It returns an altered version of the input string in which control
codes, some BMP codepoints, and all non-BMP codepoints are replaced with
escape codes.  As demonstrated above, it allows one to identify the
characters in a string, regardless of how they are displayed.

Normal and error output are generally kept separate (on separate lines)
from code input and each other.  They each get different highlight
colors.

For SyntaxError tracebacks, the normal ’^’ marking where the error was
detected is replaced by coloring the text with an error highlight.  When
code run from a file causes other exceptions, one may right click on a
traceback line to jump to the corresponding line in an IDLE editor.  The
file will be opened if necessary.

Shell has a special facility for squeezing output lines down to a
’Squeezed text’ label.  This is done automatically for output over N
lines (N = 50 by default).  N can be changed in the PyShell section of
the General page of the Settings dialog.  Output with fewer lines can be
squeezed by right clicking on the output.  This can be useful lines long
enough to slow down scrolling.

Squeezed output is expanded in place by double-clicking the label.  It
can also be sent to the clipboard or a separate view window by
right-clicking the label.


File: python.info,  Node: 开发 tkinter 应用程序,  Next: 在没有子进程的情况下运行,  Prev: Shell中的用户输出,  Up: 启动和代码执行

5.25.10.26 开发 tkinter 应用程序
................................

IDLE is intentionally different from standard Python in order to
facilitate development of tkinter programs.  Enter ‘import tkinter as
tk; root = tk.Tk()’ in standard Python and nothing appears.  Enter the
same in IDLE and a tk window appears.  In standard Python, one must also
enter ‘root.update()’ to see the window.  IDLE does the equivalent in
the background, about 20 times a second, which is about every 50
milliseconds.  Next enter ‘b = tk.Button(root, text='button');
b.pack()’.  Again, nothing visibly changes in standard Python until one
enters ‘root.update()’.

Most tkinter programs run ‘root.mainloop()’, which usually does not
return until the tk app is destroyed.  If the program is run with
‘python -i’ or from an IDLE editor, a ‘>>>’ shell prompt does not appear
until ‘mainloop()’ returns, at which time there is nothing left to
interact with.

When running a tkinter program from an IDLE editor, one can comment out
the mainloop call.  One then gets a shell prompt immediately and can
interact with the live application.  One just has to remember to
re-enable the mainloop call when running in standard Python.


File: python.info,  Node: 在没有子进程的情况下运行,  Prev: 开发 tkinter 应用程序,  Up: 启动和代码执行

5.25.10.27 在没有子进程的情况下运行
...................................

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.

If the attempt to make the socket connection fails, Idle will notify
you.  Such failures are sometimes transient, but if persistent, the
problem may be either a firewall blocking the connection or
misconfiguration of a particular system.  Until the problem is fixed,
one can run Idle with the -n command line switch.

If IDLE is started with the -n command line switch it will run in a
single process and will not create the subprocess which runs the RPC
Python execution server.  This can be useful if Python cannot create the
subprocess or the RPC socket interface on your platform.  However, in
this mode user code is not isolated from IDLE itself.  Also, the
environment is not restarted when Run/Run Module (F5) is selected.  If
your code has been modified, you must reload() the affected modules and
re-import any specific items (e.g.  from foo import baz) if the changes
are to take effect.  For these reasons, it is preferable to run IDLE
with the default subprocess if at all possible.

3.4 版後已棄用.


File: python.info,  Node: 帮助和偏好,  Prev: 启动和代码执行,  Up: IDLE<51>

5.25.10.28 帮助和偏好
.....................

* Menu:

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


File: python.info,  Node: 帮助源,  Next: 首选项设置,  Up: 帮助和偏好

5.25.10.29 帮助源
.................

Help menu entry "IDLE Help" displays a formatted html version of the
IDLE chapter of the Library Reference.  The result, in a read-only
tkinter text window, is close to what one sees in a web browser.
Navigate through the text with a mousewheel, the scrollbar, or up and
down arrow keys held down.  Or click the TOC (Table of Contents) button
and select a section header in the opened box.

Help menu entry "Python Docs" opens the extensive sources of help,
including tutorials, available at ‘docs.python.org/x.y’, where ’x.y’ is
the currently running Python version.  If your system has an off-line
copy of the docs (this may be an installation option), that will be
opened instead.

Selected URLs can be added or removed from the help menu at any time
using the General tab of the Configure IDLE dialog.


File: python.info,  Node: 首选项设置,  Next: macOS 上的IDLE,  Prev: 帮助源,  Up: 帮助和偏好

5.25.10.30 首选项设置
.....................

The font preferences, highlighting, keys, and general preferences can be
changed via Configure IDLE on the Option menu.  Non-default user
settings are saved in a ‘.idlerc’ directory in the user’s home
directory.  Problems caused by bad user configuration files are solved
by editing or deleting one or more of the files in ‘.idlerc’.

On the Font tab, see the text sample for the effect of font face and
size on multiple characters in multiple languages.  Edit the sample to
add other characters of personal interest.  Use the sample to select
monospaced fonts.  If particular characters have problems in Shell or an
editor, add them to the top of the sample and try changing first size
and then font.

On the Highlights and Keys tab, select a built-in or custom color theme
and key set.  To use a newer built-in color theme or key set with older
IDLEs, save it as a new custom theme or key set and it well be
accessible to older IDLEs.


File: python.info,  Node: macOS 上的IDLE,  Next: 扩展,  Prev: 首选项设置,  Up: 帮助和偏好

5.25.10.31 macOS 上的IDLE
.........................

Under System Preferences: Dock, one can set "Prefer tabs when opening
documents" to "Always".  This setting is not compatible with the
tk/tkinter GUI framework used by IDLE, and it breaks a few IDLE
features.


File: python.info,  Node: 扩展,  Prev: macOS 上的IDLE,  Up: 帮助和偏好

5.25.10.32 扩展
...............

IDLE contains an extension facility.  Preferences for extensions can be
changed with the Extensions tab of the preferences dialog.  See the
beginning of config-extensions.def in the idlelib directory for further
information.  The only current default extension is zzdummy, an example
also used for testing.


File: python.info,  Node: 開發工具,  Next: 调试和分析,  Prev: 以 Tk 打造 GUI,  Up: Python 標準函式庫 Standard Library

5.26 開發工具
=============

本章中描述的各模块可帮你编写 Python 程序。例如，*note pydoc: d9. 模块接
受一个模块并根据该模块的内容来生成文档。*note doctest: 66. 和 *note
unittest: 124. 这两个模块包含了用于编写单元测试的框架，并可用于自动测试
所编写的代码，验证预期的输出是否产生。‘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 --- Utilities for the Python test suite. Utilities for the Python test suite
* test.support.socket_helper: test support socket_helper --- Utilities for socket tests. Utilities for socket tests
* test.support.script_helper: test support script_helper --- Utilities for the Python execution tests. Utilities for the Python execution tests
* test.support.bytecode_helper: test support bytecode_helper --- Support tools for testing correct bytecode generation. Support tools for testing correct bytecode
                                generation


File: python.info,  Node: typing --- 类型提示支持,  Next: pydoc --- 文档生成器和在线帮助系统,  Up: 開發工具

5.26.1 ‘typing’ — 类型提示支持
------------------------------

3.5 版新加入.

`源码：' Lib/typing.py(1)

     備註: Python 运行时不强制执行函数和变量类型注解，但这些注解可用于类
     型检查器、IDE、静态检查器等第三方工具。

__________________________________________________________________

This module provides runtime support for type hints.  The most
fundamental support consists of the types *note Any: 745, *note Union:
116a, *note Callable: 27b, *note TypeVar: 104e, and *note Generic: 100b.
For a full specification, please see PEP 484(2).  For a simplified
introduction to type hints, see PEP 483(3).

下面的函数接收与返回的都是字符串，注解方式如下：

     def greeting(name: str) -> str:
         return 'Hello ' + name

‘greeting’ 函数中，参数 ‘name’ 的类型是 *note str: 205.，返回类型也是
*note str: 205.。子类型也可以当作参数。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/typing.py

   (2) https://www.python.org/dev/peps/pep-0484

   (3) https://www.python.org/dev/peps/pep-0483


File: python.info,  Node: Relevant PEPs,  Next: 类型别名,  Up: typing --- 类型提示支持

5.26.1.1 Relevant PEPs
......................

Since the initial introduction of type hints in PEP 484(1) and PEP
483(2), a number of PEPs have modified and enhanced Python’s framework
for type annotations.  These include:

   * 
     PEP 526(3): Syntax for Variable Annotations

          `Introducing' syntax for annotating variables outside of
          function definitions, and *note ClassVar: 69a.

   * 
     PEP 544(4): Protocols: Structural subtyping (static duck typing)

          `Introducing' *note Protocol: 36a. and the *note
          @runtime_checkable: 36b. decorator

   * 
     PEP 585(5): Type Hinting Generics In Standard Collections

          `Introducing' *note types.GenericAlias: 27c. and the ability
          to use standard library classes as *note generic types: fe5.

   * 
     PEP 586(6): Literal Types

          `Introducing' *note Literal: 275.

   * 
     PEP 589(7): TypedDict: Type Hints for Dictionaries with a Fixed Set of Keys

          `Introducing' *note TypedDict: 367.

   * 
     PEP 591(8): Adding a final qualifier to typing

          `Introducing' *note Final: 368. and the *note @final: 369.
          decorator

   * 
     PEP 593(9): Flexible function and variable annotations

          `Introducing' *note Annotated: 1ee.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0484

   (2) https://www.python.org/dev/peps/pep-0483

   (3) https://www.python.org/dev/peps/pep-0526

   (4) https://www.python.org/dev/peps/pep-0544

   (5) https://www.python.org/dev/peps/pep-0585

   (6) https://www.python.org/dev/peps/pep-0586

   (7) https://www.python.org/dev/peps/pep-0589

   (8) https://www.python.org/dev/peps/pep-0591

   (9) https://www.python.org/dev/peps/pep-0593


File: python.info,  Node: 类型别名,  Next: NewType,  Prev: Relevant PEPs,  Up: typing --- 类型提示支持

5.26.1.2 类型别名
.................

把类型赋给别名，就可以定义类型别名。本例中，‘Vector’ 和 ‘list[float]’ 相
同，可互换：

     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])

类型别名适用于简化复杂的类型签名。例如：

     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:
         ...

注意，‘None’ 是一种类型提示特例，已被 ‘type(None)’ 取代。


File: python.info,  Node: NewType,  Next: 可调对象（Callable）,  Prev: 类型别名,  Up: typing --- 类型提示支持

5.26.1.3 NewType
................

*note NewType(): 69c. 辅助函数可创建不同的新类型：

     from typing import NewType

     UserId = NewType('UserId', int)
     some_id = UserId(524313)

静态类型检查器把新类型当作原始类型的子类，这种方式适用于捕捉逻辑错误：

     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)

‘UserId’ 类型的变量可执行所有 ‘int’ 操作，但返回结果都是 ‘int’ 类型。这
种方式允许在预期 ‘int’ 时传入 ‘UserId’，还能防止意外创建无效的 ‘UserId’：

     # 'output' is of type 'int', not 'UserId'
     output = UserId(23413) + UserId(54341)

注意，这些检查只由静态类型检查器强制执行。 在运行时，语句 ‘Derived =
NewType('Derived', Base)’ 将产生一个 ‘Derived’ 函数，该函数立即返回你传
递给它的任何参数。 这意味着表达式 ‘Derived(some_value)’ 不会创建一个新的
类，也不会引入超出常规函数调用的很多开销。

更确切地说，在运行时，‘some_value is Derived(some_value)’ 表达式总为
True。

也就是说，不能创建 ‘Derived’ 的子类型，因为，在运行时，它是标识函数，不
是真正的类型：

     from typing import NewType

     UserId = NewType('UserId', int)

     # Fails at runtime and does not typecheck
     class AdminUserId(UserId): pass

然而，我们可以在 "派生的" ‘NewType’ 的基础上创建一个 *note NewType:
69c.。

     from typing import NewType

     UserId = NewType('UserId', int)

     ProUserId = NewType('ProUserId', UserId)

同时，‘ProUserId’ 的类型检查也可以按预期执行。

详见 PEP 484(1)。

     備註: 回顾上文，类型别名声明了两种彼此 `等价' 的类型。 ‘Alias =
     Original’ 时，静态类型检查器认为 ‘Alias’ 与 ‘Original’ `完全等价'。
     这种方式适用于简化复杂类型签名。

     反之，‘NewType’ 声明把一种类型当作另一种类型的 `子类型'。‘Derived =
     NewType('Derived', Original)’ 时，静态类型检查器把 ‘Derived’ 当作
     ‘Original’ 的 `子类' ，即，‘Original’ 类型的值不能用在预期
     ‘Derived’ 类型的位置。这种方式适用于以最小运行时成本防止逻辑错误。

3.5.2 版新加入.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0484


File: python.info,  Node: 可调对象（Callable）,  Next: 泛型（Generic）,  Prev: NewType,  Up: typing --- 类型提示支持

5.26.1.4 可调对象（Callable）
.............................

预期特定签名回调函数的框架可以用 ‘Callable[[Arg1Type, Arg2Type],
ReturnType]’ 实现类型提示。

例如：

     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

无需指定调用签名，用省略号字面量替换类型提示里的参数列表：
‘Callable[..., ReturnType]’，就可以声明可调对象的返回类型。


File: python.info,  Node: 泛型（Generic）,  Next: 用户定义的泛型类型,  Prev: 可调对象（Callable）,  Up: typing --- 类型提示支持

5.26.1.5 泛型（Generic）
........................

容器中，对象的类型信息不能以泛型方式静态推断，因此，抽象基类扩展支持下标
，用于表示容器元素的预期类型。

     from collections.abc import Mapping, Sequence

     def notify_by_email(employees: Sequence[Employee],
                         overrides: Mapping[str, str]) -> None: ...

typing 模块中新推出的 *note TypeVar: 104e. 工厂函数实现泛型参数化。

     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]


File: python.info,  Node: 用户定义的泛型类型,  Next: Any 类型,  Prev: 泛型（Generic）,  Up: typing --- 类型提示支持

5.26.1.6 用户定义的泛型类型
...........................

用户定义的类可以定义为泛型类。

     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)

‘Generic[T]’ 是定义类 ‘LoggedVar’ 的基类，该类使用单类型参数 ‘T’。在该类
体内，‘T’ 是有效的类型。

The *note Generic: 100b. base class defines *note __class_getitem__():
437. so that ‘LoggedVar[t]’ is valid as a type:

     from collections.abc import Iterable

     def zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None:
         for var in vars:
             var.set(0)

泛型类型支持多个类型变量，不过，类型变量可能会受到限制：

     from typing import TypeVar, Generic
     ...

     T = TypeVar('T')
     S = TypeVar('S', int, str)

     class StrangePair(Generic[T, S]):
         ...

*note Generic: 100b. 类型变量的参数应各不相同。下列代码就是无效的：

     from typing import TypeVar, Generic
     ...

     T = TypeVar('T')

     class Pair(Generic[T, T]):   # INVALID
         ...

*note Generic: 100b. 支持多重继承：

     from collections.abc import Sized
     from typing import TypeVar, Generic

     T = TypeVar('T')

     class LinkedList(Sized, Generic[T]):
         ...

继承自泛型类时，可以修正某些类型变量：

     from collections.abc import Mapping
     from typing import TypeVar

     T = TypeVar('T')

     class MyDict(Mapping[str, T]):
         ...

比如，本例中 ‘MyDict’ 调用的单参数，‘T’。

未指定泛型类的类型参数时，每个位置的类型都预设为 *note Any: 745.。下例中
，‘MyIterable’ 不是泛型，但却隐式继承了 ‘Iterable[Any]’：

     from collections.abc import Iterable

     class MyIterable(Iterable): # Same as Iterable[Any]

还支持用户定义的泛型类型别名。例如：

     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)

3.7 版更變: *note Generic: 100b. 不再支持自定义元类。

抽象基类可作为用户定义的泛型类的基类，且不会与元类冲突。现已不再支持泛型
元类。参数化泛型的输出结果会被缓存，typing 模块的大多数类型都可哈希、可
进行等价对比。


File: python.info,  Node: Any 类型,  Next: 名义子类型 vs 结构子类型,  Prev: 用户定义的泛型类型,  Up: typing --- 类型提示支持

5.26.1.7 ‘Any’ 类型
...................

*note Any: 745. 是一种特殊的类型。静态类型检查器认为所有类型均与 *note
Any: 745. 兼容，同样，*note Any: 745. 也与所有类型兼容。

也就是说，可对 *note Any: 745. 类型的值执行任何操作或方法调用，并赋值给
任意变量：

     from typing import Any

     a: Any = None
     a = []          # OK
     a = 2           # OK

     s: str = ''
     s = a           # OK

     def foo(item: Any) -> int:
         # Typechecks; 'item' could be any type,
         # and that type might have a 'bar' method
         item.bar()
         ...

注意，*note Any: 745. 类型的值赋给更精确的类型时，不执行类型检查。例如，
把 ‘a’ 赋给 ‘s’，在运行时，即便 ‘s’ 已声明为 *note str: 205. 类型，但接
收 *note int: 204. 值时，静态类型检查器也不会报错。

此外，未指定返回值与参数类型的函数，都隐式地默认使用 *note Any: 745.：

     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

需要混用动态与静态类型代码时，此操作把 *note Any: 745. 当作 `应急出口'。

*note Any: 745. 和 *note object: 3d2. 的区别。与 *note Any: 745. 相似，
所有类型都是 *note object: 3d2. 的子类型。然而，与 *note Any: 745. 不同
，object 不可逆：*note object: 3d2. `不是' 其它类型的子类型。

就是说，值的类型是 *note object: 3d2. 时，类型检查器几乎会拒绝所有对它的
操作，并且，把它赋给更精确的类型变量（或返回值）属于类型错误。例如：

     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")

使用 *note object: 3d2.，说明值能以类型安全的方式转为任何类型。使用
*note Any: 745.，说明值是动态类型。


File: python.info,  Node: 名义子类型 vs 结构子类型,  Next: 模块内容<7>,  Prev: Any 类型,  Up: typing --- 类型提示支持

5.26.1.8 名义子类型 vs 结构子类型
.................................

PEP 484(1) 最初只是把 Python 静态类型系统定义为应用 `名义子类型'。即，当
且仅当 ‘A’ 是 ‘B’ 的子类时，才能在预期 ‘B’ 类时应用 ‘A’ 类。

此项要求以前也适用于抽象基类，例如，*note Iterable: 1818. 。这种方式的问
题在于，定义类时必须显式说明，既不 Pythonic，也不是动态类型式 Python 代
码的惯用写法。例如，下列代码就遵从了 PEP 484(2) 的规范：

     from collections.abc import Sized, Iterable, Iterator

     class Bucket(Sized, Iterable[int]):
         ...
         def __len__(self) -> int: ...
         def __iter__(self) -> Iterator[int]: ...

PEP 544(3) 允许用户在类定义时不显式说明基类，从而解决了这一问题，静态类
型检查器隐式认为 ‘Bucket’ 既是 ‘Sized’ 的子类型，又是 ‘Iterable[int]’ 的
子类型。这就是 `结构子类型' （又称为静态鸭子类型）：

     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

此外，结构子类型的优势在于，通过继承特殊类 *note Protocol: 36a. ，用户可
以定义新的自定义协议（见下文中的例子）。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0484

   (2) https://www.python.org/dev/peps/pep-0484

   (3) https://www.python.org/dev/peps/pep-0544


File: python.info,  Node: 模块内容<7>,  Prev: 名义子类型 vs 结构子类型,  Up: typing --- 类型提示支持

5.26.1.9 模块内容
.................

本模块定义了下列类、函数和修饰器。

     備註: 本模块定义了一些类型，作为标准库中已有的类的子类，从而可以让
     *note Generic: 100b. 支持 ‘[]’ 中的类型变量。Python 3.9 中，这些标
     准库的类已支持 ‘[]’ ，因此，这些类型就变得冗余了。

     Python 3.9 弃用了这些冗余类型，但解释器并未提供相应的弃用警告。标记
     弃用类型的工作留待支持 Python 3.9 及以上版本的类型检查器实现。

     Python 3.9.0 发布五年后的首个 Python 发行版将从 *note typing: 122.
     模块中移除这些弃用类型。详见 PEP 585(1) 《`标准集合的类型提示泛型
     '》。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0585


File: python.info,  Node: 特殊类型原语,  Next: 泛型具象容器,  Up: 模块内容<7>

5.26.1.10 特殊类型原语
......................

* Menu:

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


File: python.info,  Node: 特殊类型,  Next: 特殊形式,  Up: 特殊类型原语

5.26.1.11 特殊类型
..................

这些类型可用于类型注解，但不支持 ‘[]’。

 -- Data: typing.Any

     不受限的特殊类型。

        * 所有类型都与 *note Any: 745. 兼容。

        * *note Any: 745. 与所有类型都兼容。

 -- Data: typing.NoReturn

     标记没有返回值的函数的特殊类型。例如：

          from typing import NoReturn

          def stop() -> NoReturn:
              raise RuntimeError('no way')

     3.5.4 版新加入.

     3.6.2 版新加入.


File: python.info,  Node: 特殊形式,  Next: 构建泛型类型,  Prev: 特殊类型,  Up: 特殊类型原语

5.26.1.12 特殊形式
..................

可用于类型注解，且支持 ‘[]’ ，每种形式都有其独特的句法。

 -- Data: typing.Tuple

     元组类型； ‘Tuple[X, Y]’ 是二项元组类型，第一个元素的类型是 X，第二
     个元素的类型是 Y。空元组的类型可写为 ‘Tuple[()]’。

     例：‘Tuple[T1, T2]’ 是二项元组，类型变量分别为 T1 和 T2。
     ‘Tuple[int, float, str]’ 是由整数、浮点数、字符串组成的三项元组。

     可用省略号字面量指定同质变长元组，例如，‘Tuple[int, ...]’ 。*note
     Tuple: 3405. 与 ‘Tuple[Any, ...]’ 等价，也与 *note tuple: 1a2. 等价
     。

     3.9 版後已棄用: *note builtins.tuple: 1a2. 现已支持 ‘[]’。详见 PEP
     585(1) 与 *note GenericAlias 类型: fe5.。

 -- Data: typing.Union

     联合类型；‘Union[X, Y]’ 的意思是，非 X 即 Y。

     可用 ‘Union[int, str]’ 等形式定义联合类型。 具体如下：

        * 参数必须是某种类型，且至少有一个。

        * 联合类型之联合类型会被展平，例如：

               Union[Union[int, str], float] == Union[int, str, float]

        * 单参数之联合类型就是该参数自身，例如：

               Union[int] == int  # The constructor actually returns int

        * 冗余的参数会被跳过，例如：

               Union[int, str, int] == Union[int, str]

        * 比较联合类型，不涉及参数顺序，例如：

               Union[int, str] == Union[str, int]

        * 联合类型不能作为子类，也不能实例化。

        * 不支持 ‘Union[X][Y]’ 这种写法。

        * ‘Optional[X]’ 是 ‘Union[X, None]’ 的缩写。

     3.7 版更變: 在运行时，不要移除联合类型中的显式子类。

 -- Data: typing.Optional

     可选类型。

     ‘Optional[X]’ 等价于 ‘Union[X, None]’ 。

     注意，可选类型与含默认值的可选参数不同。含默认值的可选参数不需要在
     类型注解上添加 ‘Optional’ 限定符，因为它仅是可选的。例如：

          def foo(arg: int = 0) -> None:
              ...

     另一方面，显式应用 ‘None’ 值时，不管该参数是否可选， ‘Optional’ 都
     适用。例如：

          def foo(arg: Optional[int] = None) -> None:
              ...

 -- Data: typing.Callable

     可调类型； ‘Callable[[int], str]’ 是把（int）转为 str 的函数。

     下标句法必须与参数列表和返回类型这两个值一起使用。参数列表只能是类
     型列表或省略号；返回类型只能是单一类型。

     没有说明可选参数或关键字参数的句法；这类函数类型很少用作回调类型。
     ‘Callable[..., ReturnType]’ （省略号字面量）可用于为接受任意数量参
     数，并返回 ‘ReturnType’ 的可调对象提供类型提示。纯 *note Callable:
     27b. 等价于 ‘Callable[..., Any]’，进而等价于 *note
     collections.abc.Callable: 27a. 。

     3.9 版後已棄用: *note collections.abc.Callable: 27a. 现已支持 ‘[]’。
     详见 PEP 585(2) 与 *note GenericAlias 类型: fe5.。

 -- 類別: typing.Type (Generic[CT_co])

     用 ‘C’ 注解的变量可以接受类型 ‘C’ 的值。反之，用 ‘Type[C]’ 注解的变
     量可以接受类自身的值 — 准确地说，是接受 ‘C’ 的 `类对象'，例如：

          a = 3         # Has type 'int'
          b = int       # Has type 'Type[int]'
          c = type(a)   # Also has type 'Type[int]'

     注意，‘Type[C]’ 为协变量：

          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()

     ‘Type[C]’ 为协变量的意思是指， ‘C’ 的所有子类都应使用与 ‘C’ 相同的
     构造器签名及类方法签名。类型检查器应标记违反此项规定的内容，但也应
     允许符合指定基类构造器调用的子类进行构造器调用。 PEP 484(3) 修订版
     将来可能会调整类型检查器对这种特例的处理方式。

     *note Type: 3407. 合法的参数仅有类、*note Any: 745. 、*note
     类型变量: 1588. 以及上述类型的联合类型。例如：

          def new_non_team_user(user_class: Type[Union[BasicUser, ProUser]]): ...

     ‘Type[Any]’ 等价于 ‘Type’，进而等价于 Python 元类架构的根基，
     ‘type’。

     3.5.2 版新加入.

     3.9 版後已棄用: *note builtins.type: 6ff. 现已支持 ‘[]’。详见 PEP
     585(4) 与 *note GenericAlias 类型: fe5.。

 -- Data: typing.Literal

     表示类型检查器对应变量或函数参数的值等价于给定字面量（或多个字面量
     之一）的类型。例如：

          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

     ‘Literal[...]’ 不能创建子类。在运行时，任意值均可作为
     ‘Literal[...]’ 的类型参数，但类型检查器可以对此加以限制。字面量类型
     详见 PEP 586(5) 。

     3.8 版新加入.

     3.9.1 版更變: ‘Literal’ 现在能去除形参的重复。 ‘Literal’ 对象的相等
     性比较不再依赖顺序。 现在如果有某个参数不为 *note hashable: 276.，
     ‘Literal’ 对象在相等性比较期间将引发 *note TypeError: 1fe.。

 -- Data: typing.ClassVar

     标记类变量的特殊类型构造器。

     如 PEP 526(6) 所述，打包在 ClassVar 内的变量注解是指，给定属性应当
     用作类变量，而不应设置在类实例上。用法如下：

          class Starship:
              stats: ClassVar[dict[str, int]] = {} # class variable
              damage: int = 10                     # instance variable

     *note ClassVar: 69a. 仅接受类型，也不能使用下标。

     *note ClassVar: 69a. 本身不是类，不应用于 *note isinstance(): 551.
     或 *note issubclass(): 552.。*note ClassVar: 69a. 不改变 Python 运
     行时行为，但可以用于第三方类型检查器。例如，类型检查器会认为以下代
     码有错：

          enterprise_d = Starship(3000)
          enterprise_d.stats = {} # Error, setting class variable on instance
          Starship.stats = {}     # This is OK

     3.5.3 版新加入.

 -- Data: typing.Final

     告知类型检查器某名称不能再次赋值或在子类中重写的特殊类型构造器。例
     如：

          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

     这些属性没有运行时检查。详见 PEP 591(7)。

     3.8 版新加入.

 -- Data: typing.Annotated

     PEP 593(8) （‘灵活函数和变量注解’）里引入的类型，可以用上下文特定元
     数据（‘Annotated’ 的参数可变，也可能用它的多个组成部分）装饰现有的
     类型。具体来说，就是类型提示 ‘Annotated[T, x]’ 用元数据 ‘x’ 注解类
     型 ‘T’。静态分析或运行时都能使用该元数据。库（或工具）处理类型提示
     ‘Annotated[T, x]’ 时，在元数据 ‘x’ 不涉及特殊逻辑的情况下，可忽略该
     类型提示，仅把它当作类型 ‘T’。与 ‘typing’ 模块中现有的
     ‘no_type_check’ 功能不同，该功能完全禁用了函数或类的类型检查注解，
     而 ‘Annotated’ 类型则允许对 ‘T’ 进行静态类型检查（例如，通过 mypy 或
     Pyre，可安全地忽略 ‘x’），也可以在特定应用程序中实现 ‘x’ 的运行时访
     问。

     毕竟，如何解释注解（如有）由处理 ‘Annotated’ 类型的工具/库负责。工
     具/库处理 ‘Annotated’ 类型时，扫描所有注解以确定是否需要进行处理（
     例如，使用 ‘isinstance()’）。

     工具/库不支持注解，或遇到未知注解时，应忽略注解，并把注解类型当作底
     层类型。

     是否允许客户端在一个类型上使用多个注解，以及如何合并这些注解，由处
     理注解的工具决定。

     ‘Annotated’ 类型支持把多个相同（或不同）的单个（或多个）类型注解置
     于任意节点。因此，使用这些注解的工具/库要负责处理潜在的重复项。例如
     ，执行值范围分析时，应允许以下操作：

          T1 = Annotated[int, ValueRange(-10, 5)]
          T2 = Annotated[T1, ValueRange(-20, 3)]

     传递 ‘include_extras=True’ 至 *note get_type_hints(): 1ef. ，即可在
     运行时访问额外的注解。

     语义详情：

        * ‘Annotated’ 的第一个参数必须是有效类型。

        * 支持多个类型标注（‘Annotated’ 支持可变参数）：

               Annotated[int, ValueRange(3, 10), ctype("char")]

        * 调用 ‘Annotated’ 至少要有两个参数（‘Annotated[int]’ 是无效的）

        * 注解的顺序会被保留，且影响等价检查：

               Annotated[int, ValueRange(3, 10), ctype("char")] != Annotated[
                   int, ctype("char"), ValueRange(3, 10)
               ]

        * 嵌套 ‘Annotated’ 类型会被展平，元数据从最内层注解依序展开：

               Annotated[Annotated[int, ValueRange(3, 10)], ctype("char")] == Annotated[
                   int, ValueRange(3, 10), ctype("char")
               ]

        * 不移除注解重复项：

               Annotated[int, ValueRange(3, 10)] != Annotated[
                   int, ValueRange(3, 10), ValueRange(3, 10)
               ]

        * ‘Annotated’ 可用于嵌套或泛型别名：

               T = TypeVar('T')
               Vec = Annotated[list[tuple[T, T]], MaxLen(10)]
               V = Vec[int]

               V == Annotated[list[tuple[int, int]], MaxLen(10)]

     3.9 版新加入.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0585

   (2) https://www.python.org/dev/peps/pep-0585

   (3) https://www.python.org/dev/peps/pep-0484

   (4) https://www.python.org/dev/peps/pep-0585

   (5) https://www.python.org/dev/peps/pep-0586

   (6) https://www.python.org/dev/peps/pep-0526

   (7) https://www.python.org/dev/peps/pep-0591

   (8) https://www.python.org/dev/peps/pep-0593


File: python.info,  Node: 构建泛型类型,  Next: 其他特殊指令,  Prev: 特殊形式,  Up: 特殊类型原语

5.26.1.13 构建泛型类型
......................

以下内容是创建泛型类型的基石，但不在注解内使用。

 -- 類別: typing.Generic

     用于泛型类型的抽象基类。

     泛型类型一般通过继承含一个或多个类型变量的类实例进行声明。例如，泛
     型映射类型定义如下：

          class Mapping(Generic[KT, VT]):
              def __getitem__(self, key: KT) -> VT:
                  ...
                  # Etc.

     该类的用法如下：

          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

 -- 類別: typing.TypeVar

     类型变量。

     用法：

          T = TypeVar('T')  # Can be anything
          A = TypeVar('A', str, bytes)  # Must be str or bytes

     类型变量主要是为静态类型检查器提供支持，用于泛型类型与泛型函数定义
     的参数。有关泛型类型，详见 *note Generic: 100b.。泛型函数的写法如下
     ：

          def repeat(x: T, n: int) -> Sequence[T]:
              """Return a list containing n references to x."""
              return [x]*n

          def longest(x: A, y: A) -> A:
              """Return the longest of two strings."""
              return x if len(x) >= len(y) else y

     本质上，后例的签名重载了 ‘(str, str) -> str’ 与 ‘(bytes, bytes) ->
     bytes’。注意，参数是 *note str: 205. 子类的实例时，返回类型仍是纯
     *note str: 205.。

     在运行时，‘isinstance(x, T)’ 会触发 *note TypeError: 1fe. 异常。一
     般而言，*note isinstance(): 551. 和 *note issubclass(): 552. 不应与
     类型搭配使用。

     通过 ‘covariant=True’ 或 ‘contravariant=True’ 可以把类型变量标记为
     协变量或逆变量。详见 PEP 484(1)。默认情况下，类型变量是不变量。类型
     变量还可以用 ‘bound=<type>’ 指定上限。这里的意思是，（显式或隐式地
     ）取代类型变量的实际类型必须是限定类型的子类，详见 PEP 484(2)。

 -- Data: typing.AnyStr

     ‘AnyStr’ 类型变量的定义为 ‘AnyStr = TypeVar('AnyStr', str, bytes)’。

     这里指的是，它可以接受任意同类字符串，但不支持混用不同类别的字符串
     。例如：

          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

 -- 類別: typing.Protocol (Generic)

     Protocol 类的基类。Protocol 类的定义如下：

          class Proto(Protocol):
              def meth(self) -> int:
                  ...

     这些类主要与静态类型检查器搭配使用，用来识别结构子类型（静态鸭子类
     型），例如：

          class C:
              def meth(self) -> int:
                  return 0

          def func(x: Proto) -> int:
              return x.meth()

          func(C())  # Passes static type check

     详见 PEP 544(3)。Protocol 类用 *note runtime_checkable(): 36b. （见
     下文）装饰，忽略类型签名，仅检查给定属性是否存在，充当简要的运行时
     协议。

     Protocol 类可以是泛型，例如：

          class GenProto(Protocol[T]):
              def meth(self) -> T:
                  ...

     3.8 版新加入.

 -- 函式: @typing.runtime_checkable

     用于把 Protocol 类标记为运行时协议。

     该协议可以与 *note isinstance(): 551. 和 *note issubclass(): 552. 一
     起使用。应用于非协议的类时，会触发 *note TypeError: 1fe.。该指令支
     持简易结构检查，与 *note collections.abc: 1e. 的 *note Iterable:
     1818. 非常类似，只擅长做一件事。 例如：

          @runtime_checkable
          class Closable(Protocol):
              def close(self): ...

          assert isinstance(open('/some/file'), Closable)

          備註: *note runtime_checkable(): 36b. 只检查所需方法是否存在，
          但却不检查类型签名！ 例如，*note builtins.complex: 2c1. 支持
          *note __float__(): 2c4.，因此，它能通过 *note SupportsFloat:
          340a. 的 *note issubclass(): 552. 检查。 然而，
          ‘complex.__float__’ 方法其实只是为了触发含更多信息的 *note
          TypeError: 1fe.。

     3.8 版新加入.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0484

   (2) https://www.python.org/dev/peps/pep-0484

   (3) https://www.python.org/dev/peps/pep-0544


File: python.info,  Node: 其他特殊指令,  Prev: 构建泛型类型,  Up: 特殊类型原语

5.26.1.14 其他特殊指令
......................

这些特殊指令是声明类型的基石，但不在注解内使用。

 -- 類別: typing.NamedTuple

     *note collections.namedtuple(): 1a1. 的类型版本。

     用法：

          class Employee(NamedTuple):
              name: str
              id: int

     相当于：

          Employee = collections.namedtuple('Employee', ['name', 'id'])

     为字段提供默认值，要在类体内赋值：

          class Employee(NamedTuple):
              name: str
              id: int = 3

          employee = Employee('Guido')
          assert employee.id == 3

     带默认值的字段必须在不带默认值的字段后面。

     生成的类具有 ‘__annotations__’ 这个附加属性，提供了映射字段名与字段
     类型的字典。（字段名在 ‘_fields’ 属性内，默认值在 ‘_field_defaults’
     属性内，这两项都是命名元组 API 的组成部分。）

     ‘NamedTuple’ 子类也支持文档字符串与方法：

          class Employee(NamedTuple):
              """Represents an employee."""
              name: str
              id: int = 3

              def __repr__(self) -> str:
                  return f'<Employee {self.name}, id={self.id}>'

     反向兼容用法：

          Employee = NamedTuple('Employee', [('name', str), ('id', int)])

     3.6 版更變: 添加了对 PEP 526(1) 中变量注解句法的支持。

     3.6.1 版更變: 添加了对默认值、方法、文档字符串的支持。

     3.8 版更變: ‘_field_types’ 和 ‘__annotations__’ 属性现已使用常规字
     典，不再使用 ‘OrderedDict’ 实例。

     3.9 版更變: 移除了 ‘_field_types’ 属性， 改用具有相同信息，但更标准
     的 ‘__annotations__’ 属性。

 -- 函式: typing.NewType (name, tp)

     用于为类型检查器标明不同类型的辅助函数，详见 *note NewType: 33f9.。
     在运行时，它返回一个返回其参数的函数。用法如下：

          UserId = NewType('UserId', int)
          first_user = UserId(1)

     3.5.2 版新加入.

 -- 類別: typing.TypedDict (dict)

     把类型提示添加至字典的特殊构造器。在运行时，它是纯 *note dict:
     164.。

     ‘TypedDict’ 声明一个字典类型，该类型预期所有实例都具有一组键集，其
     中，每个键都与对应类型的值关联。运行时不检查此预期，而是由类型检查
     器强制执行。用法如下：

          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')

     用于内省的类型信息可通过 ‘Point2D.__annotations__’ 和
     ‘Point2D.__total__’ 访问。为了让不支持 PEP 526(2) 的老版 Python 也
     能使用此功能，‘TypedDict’ 支持两个附加的等价句法形式：

          Point2D = TypedDict('Point2D', x=int, y=int, label=str)
          Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})

     默认情况下，所有键都必须列在 TypedDict 里。不过，也可以通过指定
     total 参数进行重写。用法如下：

          class point2D(TypedDict, total=False):
              x: int
              y: int

     这段代码的意思是，可以省略 point2D 这个 TypedDict 中的任意键。类型
     检查器只支持字面量 False 或 True 作为 total 参数的值。True 是默认值
     ，表明在类体中，必须定义所有项目。

     更多示例与 ‘TypedDict’ 的详细规则，详见 PEP 589(3)。

     3.8 版新加入.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0526

   (2) https://www.python.org/dev/peps/pep-0526

   (3) https://www.python.org/dev/peps/pep-0589


File: python.info,  Node: 泛型具象容器,  Next: 抽象基类,  Prev: 特殊类型原语,  Up: 模块内容<7>

5.26.1.15 泛型具象容器
......................

* Menu:

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


File: python.info,  Node: 对应的内置类型,  Next: collections 对应类型,  Up: 泛型具象容器

5.26.1.16 对应的内置类型
........................

 -- 類別: typing.Dict (dict, MutableMapping[KT, VT])

     *note dict: 164. 的泛型版本。适用于注解返回类型。注解参数时，最好使
     用 *note Mapping: 340f. 等抽象容器类型。

     该类型用法如下：

          def count_words(text: str) -> Dict[str, int]:
              ...

     3.9 版後已棄用: *note builtins.dict: 164. 现已支持 ‘[]’。详见 PEP
     585(1) 和 *note GenericAlias 类型: fe5.。

 -- 類別: typing.List (list, MutableSequence[T])

     *note list: 1f8. 的泛型版本。适用于注解返回类型。注解参数时，最好使
     用 *note Sequence: 3411. 或 *note Iterable: 3412. 等抽象容器类型。

     该类型用法如下：

          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]

     3.9 版後已棄用: *note builtins.list: 1f8. 现已支持 ‘[]’。详见 PEP
     585(2) 与 *note GenericAlias 类型: fe5.。

 -- 類別: typing.Set (set, MutableSet[T])

     *note builtins.set: 1f6. 的泛型版本。适用于注解返回类型。注解参数时
     ，最好使用 *note AbstractSet: 3414. 等抽象容器类型。

     3.9 版後已棄用: *note builtins.set: 1f6. 现已支持 ‘[]’。详见 PEP
     585(3) 和 *note GenericAlias 类型: fe5.。

 -- 類別: typing.FrozenSet (frozenset, AbstractSet[T_co])

     *note builtins.frozenset: 1f7. 的泛型版本。

     3.9 版後已棄用: *note builtins.frozenset: 1f7. 现已支持 ‘[]’。详见
     PEP 585(4) 和 *note GenericAlias 类型: fe5.。

     備註: *note Tuple: 3405. 是一种特殊形式。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0585

   (2) https://www.python.org/dev/peps/pep-0585

   (3) https://www.python.org/dev/peps/pep-0585

   (4) https://www.python.org/dev/peps/pep-0585


File: python.info,  Node: collections 对应类型,  Next: 其他具象类型,  Prev: 对应的内置类型,  Up: 泛型具象容器

5.26.1.17 ‘collections’ 对应类型
................................

 -- 類別: typing.DefaultDict (collections.defaultdict,
          MutableMapping[KT, VT])

     *note collections.defaultdict: c0c. 的泛型版本。

     3.5.2 版新加入.

     3.9 版後已棄用: *note collections.defaultdict: c0c. 现已支持 ‘[]’。
     详见 PEP 585(1) 与 *note GenericAlias 类型: fe5.。

 -- 類別: typing.OrderedDict (collections.OrderedDict,
          MutableMapping[KT, VT])

     *note collections.OrderedDict: 2ea. 的泛型版本。

     3.7.2 版新加入.

     3.9 版後已棄用: *note collections.OrderedDict: 2ea. 现已支持 ‘[]’。
     详见 PEP 585(2) 与 *note GenericAlias 类型: fe5.。

 -- 類別: typing.ChainMap (collections.ChainMap, MutableMapping[KT, VT])

     *note collections.ChainMap: 5a3. 的泛型版本。

     3.5.4 版新加入.

     3.6.1 版新加入.

     3.9 版後已棄用: *note collections.ChainMap: 5a3. 现已支持 ‘[]’。详
     见 PEP 585(3) 和 *note GenericAlias 类型: fe5.。

 -- 類別: typing.Counter (collections.Counter, Dict[T, int])

     *note collections.Counter: ab9. 的泛型版本。

     3.5.4 版新加入.

     3.6.1 版新加入.

     3.9 版後已棄用: *note collections.Counter: ab9. 现已支持 ‘[]’。详见
     PEP 585(4) 和 *note GenericAlias 类型: fe5.。

 -- 類別: typing.Deque (deque, MutableSequence[T])

     *note collections.deque: 62a. 的泛型版本。

     3.5.4 版新加入.

     3.6.1 版新加入.

     3.9 版後已棄用: *note collections.deque: 62a. 现已支持 ‘[]’。详见
     PEP 585(5) 和 *note GenericAlias 类型: fe5.。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0585

   (2) https://www.python.org/dev/peps/pep-0585

   (3) https://www.python.org/dev/peps/pep-0585

   (4) https://www.python.org/dev/peps/pep-0585

   (5) https://www.python.org/dev/peps/pep-0585


File: python.info,  Node: 其他具象类型,  Prev: collections 对应类型,  Up: 泛型具象容器

5.26.1.18 其他具象类型
......................

 -- 類別: typing.IO
 -- 類別: typing.TextIO
 -- 類別: typing.BinaryIO

     泛型类型 ‘IO[AnyStr]’ 及其子类 ‘TextIO(IO[str])’ 与
     ‘BinaryIO(IO[bytes])’ 表示 I/O 流的类型，例如 *note open(): 16f. 所
     返回的对象。

     Deprecated since version 3.8, will be removed in version 3.12: 这些
     类型也在 ‘typing.io’ 命名空间中，它从未得到类型检查器的支持并将被移
     除。

 -- 類別: typing.Pattern
 -- 類別: typing.Match

     这些类型对应的是从 *note re.compile(): 54c. 和 *note re.match():
     c83. 返回的类型。 这些类型（及相应的函数）是 ‘AnyStr’ 中的泛型并可
     通过编写 ‘Pattern[str]’, ‘Pattern[bytes]’, ‘Match[str]’ 或
     ‘Match[bytes]’ 来具体指定。

     Deprecated since version 3.8, will be removed in version 3.12: 这些
     类型也在 ‘typing.re’ 命名空间中，它从未得到类型检查器的支持并将被移
     除。

     3.9 版後已棄用: *note re: dd. 模块中的 ‘Pattern’ 与 ‘Match’ 类现已
     支持 ‘[]’。详见 PEP 585(1) 与 *note GenericAlias 类型: fe5.。

 -- 類別: typing.Text

     ‘Text’ 是 ‘str’ 的别名。提供了对 Python 2 代码的向下兼容：Python 2
     中，‘Text’ 是 ‘unicode’ 的别名。

     使用 ‘Text’ 时，值中必须包含 unicode 字符串，以兼容 Python 2 和
     Python 3：

          def add_unicode_checkmark(text: Text) -> Text:
              return text + u' \u2713'

     3.5.2 版新加入.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0585


File: python.info,  Node: 抽象基类,  Next: 协议<3>,  Prev: 泛型具象容器,  Up: 模块内容<7>

5.26.1.19 抽象基类
..................

* Menu:

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


File: python.info,  Node: collections abc 对应的容器,  Next: collections abc 对应的其他类型,  Up: 抽象基类

5.26.1.20 ‘collections.abc’ 对应的容器
......................................

 -- 類別: typing.AbstractSet (Sized, Collection[T_co])

     *note collections.abc.Set: 1810. 的泛型版本。

     3.9 版後已棄用: *note collections.abc.Set: 1810. 现已支持 ‘[]’。详
     见 PEP 585(1) 与 *note GenericAlias 类型: fe5.。

 -- 類別: typing.ByteString (Sequence[int])

     *note collections.abc.ByteString: 181c. 的泛型版本。

     该类型代表了 *note bytes: 172.、*note bytearray: 173.、*note
     memoryview: 386. 等字节序列类型。

     作为该类型的简称，*note bytes: 172. 可用于标注上述任意类型的参数。

     3.9 版後已棄用: *note collections.abc.ByteString: 181c. 现已支持
     ‘[]’。详见 PEP 585(2) 与 *note GenericAlias 类型: fe5.。

 -- 類別: typing.Collection (Sized, Iterable[T_co], Container[T_co])

     *note collections.abc.Collection: 626. 的泛型版本。

     3.6.0 版新加入.

     3.9 版後已棄用: *note collections.abc.Collection: 626. 现已支持
     ‘[]’。详见 PEP 585(3) 与 *note GenericAlias 类型: fe5.。

 -- 類別: typing.Container (Generic[T_co])

     *note collections.abc.Container: 181a. 的泛型版本。

     3.9 版後已棄用: *note collections.abc.Container: 181a. 现已支持
     ‘[]’。详见 PEP 585(4) 和 *note GenericAlias 类型: fe5.。

 -- 類別: typing.ItemsView (MappingView, Generic[KT_co, VT_co])

     *note collections.abc.ItemsView: 181f. 的泛型版本。

     3.9 版後已棄用: *note collections.abc.ItemsView: 181f. 现已支持
     ‘[]’。详见 PEP 585(5) 和 *note GenericAlias 类型: fe5.。

 -- 類別: typing.KeysView (MappingView[KT_co], AbstractSet[KT_co])

     *note collections.abc.KeysView: 181e. 的泛型版本。

     3.9 版後已棄用: *note collections.abc.KeysView: 181e. 现已支持
     ‘[]’。详见 PEP 585(6) 和 *note GenericAlias 类型: fe5.。

 -- 類別: typing.Mapping (Sized, Collection[KT], Generic[VT_co])

     *note collections.abc.Mapping: 15f. 的泛型版本。用法如下：

          def get_position_in_index(word_list: Mapping[str, int], word: str) -> int:
              return word_list[word]

     3.9 版後已棄用: *note collections.abc.Mapping: 15f. 现已支持 ‘[]’。
     详见 PEP 585(7) 和 *note GenericAlias 类型: fe5.。

 -- 類別: typing.MappingView (Sized, Iterable[T_co])

     *note collections.abc.MappingView: 181d. 的泛型版本。

     3.9 版後已棄用: *note collections.abc.MappingView: 181d. 现已支持
     ‘[]’。详见 PEP 585(8) 和 *note GenericAlias 类型: fe5.。

 -- 類別: typing.MutableMapping (Mapping[KT, VT])

     *note collections.abc.MutableMapping: ace. 的泛型版本。

     3.9 版後已棄用: *note collections.abc.MutableMapping: ace. 现已支持
     ‘[]’。详见 PEP 585(9) 和 *note GenericAlias 类型: fe5.。

 -- 類別: typing.MutableSequence (Sequence[T])

     *note collections.abc.MutableSequence: 79f. 的泛型版本。

     3.9 版後已棄用: *note collections.abc.MutableSequence: 79f. 现已支
     持 ‘[]’。详见 PEP 585(10) 和 *note GenericAlias 类型: fe5.。

 -- 類別: typing.MutableSet (AbstractSet[T])

     *note collections.abc.MutableSet: 181b. 的泛型版本。

     3.9 版後已棄用: *note collections.abc.MutableSet: 181b. 现已支持
     ‘[]’。详见 PEP 585(11) 和 *note GenericAlias 类型: fe5.。

 -- 類別: typing.Sequence (Reversible[T_co], Collection[T_co])

     *note collections.abc.Sequence: 1764. 的泛型版本。

     3.9 版後已棄用: *note collections.abc.Sequence: 1764. 现已支持
     ‘[]’。详见 PEP 585(12) 和 *note GenericAlias 类型: fe5.。

 -- 類別: typing.ValuesView (MappingView[VT_co])

     *note collections.abc.ValuesView: 1820. 的泛型版本。

     3.9 版後已棄用: *note collections.abc.ValuesView: 1820. 现已支持
     ‘[]’。详见 PEP 585(13) 和 *note GenericAlias 类型: fe5.。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0585

   (2) https://www.python.org/dev/peps/pep-0585

   (3) https://www.python.org/dev/peps/pep-0585

   (4) https://www.python.org/dev/peps/pep-0585

   (5) https://www.python.org/dev/peps/pep-0585

   (6) https://www.python.org/dev/peps/pep-0585

   (7) https://www.python.org/dev/peps/pep-0585

   (8) https://www.python.org/dev/peps/pep-0585

   (9) https://www.python.org/dev/peps/pep-0585

   (10) https://www.python.org/dev/peps/pep-0585

   (11) https://www.python.org/dev/peps/pep-0585

   (12) https://www.python.org/dev/peps/pep-0585

   (13) https://www.python.org/dev/peps/pep-0585


File: python.info,  Node: collections abc 对应的其他类型,  Next: 异步编程,  Prev: collections abc 对应的容器,  Up: 抽象基类

5.26.1.21 ‘collections.abc’ 对应的其他类型
..........................................

 -- 類別: typing.Iterable (Generic[T_co])

     *note collections.abc.Iterable: 1818. 的泛型版本。

     3.9 版後已棄用: *note collections.abc.Iterable: 1818. 现已支持
     ‘[]’。详见 PEP 585(1) 和 *note GenericAlias 类型: fe5.。

 -- 類別: typing.Iterator (Iterable[T_co])

     *note collections.abc.Iterator: 1819. 的泛型版本。

     3.9 版後已棄用: *note collections.abc.Iterator: 1819. 现已支持
     ‘[]’。详见 PEP 585(2) 和 *note GenericAlias 类型: fe5.。

 -- 類別: typing.Generator (Iterator[T_co], Generic[T_co, T_contra,
          V_co])

     生成器可以由泛型类型 ‘Generator[YieldType, SendType, ReturnType]’ 注
     解。例如：

          def echo_round() -> Generator[int, float, str]:
              sent = yield 0
              while sent >= 0:
                  sent = yield round(sent)
              return 'Done'

     注意，与 typing 模块里的其他泛型不同， *note Generator: 3430. 的
     ‘SendType’ 属于逆变行为，不是协变行为，也是不变行为。

     如果生成器只产生值，可将 ‘SendType’ 与 ‘ReturnType’ 设为 ‘None’：

          def infinite_stream(start: int) -> Generator[int, None, None]:
              while True:
                  yield start
                  start += 1

     此外，还可以把生成器的返回类型注解为 ‘Iterable[YieldType]’ 或
     ‘Iterator[YieldType]’：

          def infinite_stream(start: int) -> Iterator[int]:
              while True:
                  yield start
                  start += 1

     3.9 版後已棄用: *note collections.abc.Generator: 7a8. 现已支持
     ‘[]’。详见 PEP 585(3) 和 *note GenericAlias 类型: fe5.。

 -- 類別: typing.Hashable

     *note collections.abc.Hashable: 1aa9. 的别名。

 -- 類別: typing.Reversible (Iterable[T_co])

     *note collections.abc.Reversible: 627. 的泛型版本。

     3.9 版後已棄用: *note collections.abc.Reversible: 627. 现已支持
     ‘[]’。详见 PEP 585(4) 和 *note GenericAlias 类型: fe5.。

 -- 類別: typing.Sized

     *note collections.abc.Sized: 1aaa. 的别名。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0585

   (2) https://www.python.org/dev/peps/pep-0585

   (3) https://www.python.org/dev/peps/pep-0585

   (4) https://www.python.org/dev/peps/pep-0585


File: python.info,  Node: 异步编程,  Next: 上下文管理器类型<2>,  Prev: collections abc 对应的其他类型,  Up: 抽象基类

5.26.1.22 异步编程
..................

 -- 類別: typing.Coroutine (Awaitable[V_co], Generic[T_co, T_contra,
          V_co])

     *note collections.abc.Coroutine: 7aa. 的泛型版本。类型变量的差异和
     顺序与 *note Generator: 3430. 的内容相对应，例如：

          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

     3.5.3 版新加入.

     3.9 版後已棄用: *note collections.abc.Coroutine: 7aa. 现已支持
     ‘[]’。详见 PEP 585(1) 和 *note GenericAlias 类型: fe5.。

 -- 類別: typing.AsyncGenerator (AsyncIterator[T_co], Generic[T_co,
          T_contra])

     异步生成器可由泛型类型 ‘AsyncGenerator[YieldType, SendType]’ 注解。
     例如：

          async def echo_round() -> AsyncGenerator[int, float]:
              sent = yield 0
              while sent >= 0.0:
                  rounded = await round(sent)
                  sent = yield rounded

     与常规生成器不同，异步生成器不能返回值，因此没有 ‘ReturnType’ 类型
     参数。 与 *note Generator: 3430. 类似，‘SendType’ 也属于逆变行为。

     如果生成器只产生值，可将 ‘SendType’ 设置为 ‘None’：

          async def infinite_stream(start: int) -> AsyncGenerator[int, None]:
              while True:
                  yield start
                  start = await increment(start)

     此外，可用 ‘AsyncIterable[YieldType]’ 或 ‘AsyncIterator[YieldType]’
     注解生成器的返回类型：

          async def infinite_stream(start: int) -> AsyncIterator[int]:
              while True:
                  yield start
                  start = await increment(start)

     3.6.1 版新加入.

     3.9 版後已棄用: *note collections.abc.AsyncGenerator: 629. 现已支持
     ‘[]’。详见 PEP 585(2) 和 *note GenericAlias 类型: fe5.。

 -- 類別: typing.AsyncIterable (Generic[T_co])

     *note collections.abc.AsyncIterable: 7ac. 的泛型版本。

     3.5.2 版新加入.

     3.9 版後已棄用: *note collections.abc.AsyncIterable: 7ac. 现已支持
     ‘[]’。详见 PEP 585(3) 和 *note GenericAlias 类型: fe5.。

 -- 類別: typing.AsyncIterator (AsyncIterable[T_co])

     *note collections.abc.AsyncIterator: 7ab. 的泛型版本。

     3.5.2 版新加入.

     3.9 版後已棄用: *note collections.abc.AsyncIterator: 7ab. 现已支持
     ‘[]’。详见 PEP 585(4) 和 *note GenericAlias 类型: fe5.。

 -- 類別: typing.Awaitable (Generic[T_co])

     *note collections.abc.Awaitable: 7a9. 的泛型版本。

     3.5.2 版新加入.

     3.9 版後已棄用: *note collections.abc.Awaitable: 7a9. 现已支持
     ‘[]’。详见 PEP 585(5) 和 *note GenericAlias 类型: fe5.。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0585

   (2) https://www.python.org/dev/peps/pep-0585

   (3) https://www.python.org/dev/peps/pep-0585

   (4) https://www.python.org/dev/peps/pep-0585

   (5) https://www.python.org/dev/peps/pep-0585


File: python.info,  Node: 上下文管理器类型<2>,  Prev: 异步编程,  Up: 抽象基类

5.26.1.23 上下文管理器类型
..........................

 -- 類別: typing.ContextManager (Generic[T_co])

     *note contextlib.AbstractContextManager: 62d. 的泛型版本。

     3.5.4 版新加入.

     3.6.0 版新加入.

     3.9 版後已棄用: *note contextlib.AbstractContextManager: 62d. 现已
     支持 ‘[]’。详见 PEP 585(1) 和 *note GenericAlias 类型: fe5.。

 -- 類別: typing.AsyncContextManager (Generic[T_co])

     *note contextlib.AbstractAsyncContextManager: 480. 的泛型版本。

     3.5.4 版新加入.

     3.6.2 版新加入.

     3.9 版後已棄用: *note contextlib.AbstractAsyncContextManager: 480.
     现已支持 ‘[]’。详见 PEP 585(2) 和 *note GenericAlias 类型: fe5.。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0585

   (2) https://www.python.org/dev/peps/pep-0585


File: python.info,  Node: 协议<3>,  Next: 函数与装饰器,  Prev: 抽象基类,  Up: 模块内容<7>

5.26.1.24 协议
..............

这些协议由 *note runtime_checkable(): 36b. 装饰。

 -- 類別: typing.SupportsAbs

     含抽象方法 ‘__abs__’ 的抽象基类，是其返回类型里的协变量。

 -- 類別: typing.SupportsBytes

     含抽象方法 ‘__bytes__’ 的抽象基类。

 -- 類別: typing.SupportsComplex

     含抽象方法 ‘__complex__’ 的抽象基类。

 -- 類別: typing.SupportsFloat

     含抽象方法 ‘__float__’ 的抽象基类。

 -- 類別: typing.SupportsIndex

     含抽象方法 ‘__index__’ 的抽象基类。

     3.8 版新加入.

 -- 類別: typing.SupportsInt

     含抽象方法 ‘__int__’ 的抽象基类。

 -- 類別: typing.SupportsRound

     含抽象方法 ‘__round__’ 的抽象基类，是其返回类型的协变量。


File: python.info,  Node: 函数与装饰器,  Next: 内省辅助器,  Prev: 协议<3>,  Up: 模块内容<7>

5.26.1.25 函数与装饰器
......................

 -- 函式: typing.cast (typ, val)

     把值强制转换为类型。

     不变更返回值。对类型检查器而言，代表了返回值具有指定的类型，但运行
     时故意不做任何检查（以便让检查速度尽量快）。

 -- 函式: @typing.overload

     ‘@overload’ 装饰器可以修饰支持多个不同参数类型组合的函数或方法。
     ‘@overload’ - 装饰定义的系列必须紧跟一个非 ‘@overload’-装饰定义（用
     于同一个函数/方法）。‘@overload’-装饰定义仅是为了协助类型检查器， 因
     为该装饰器会被非 ‘@overload’-装饰定义覆盖，后者用于运行时，而且会被
     类型检查器忽略。在运行时直接调用 ‘@overload’ 装饰的函数会触发 *note
     NotImplementedError: 704.。下面的重载示例给出了比联合类型或类型变量
     更精准的类型：

          @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>

     详见 PEP 484(1)，与其他类型语义进行对比。

 -- 函式: @typing.final

     告知类型检查器被装饰的方法不能被覆盖，且被装饰的类不能作为子类的装
     饰器，例如：

          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
              ...

     这些属性没有运行时检查。详见 PEP 591(2)。

     3.8 版新加入.

 -- 函式: @typing.no_type_check

     标明注解不是类型提示的装饰器。

     用作类或函数的 *note decorator: 174.。用于类时，递归地应用于该类中
     定义的所有方法，（但不影响超类或子类中定义的方法）。

     本方法可直接修改函数。

 -- 函式: @typing.no_type_check_decorator

     让其他装饰器具有 *note no_type_check(): 3443. 效果的装饰器。

     本装饰器用 *note no_type_check(): 3443. 里的装饰函数打包其他装饰器
     。

 -- 函式: @typing.type_check_only

     标记类或函数内不可用于运行时的装饰器。

     在运行时，该装饰器本身不可用。实现返回的是私有类实例时，它主要是用
     于标记在类型存根文件中定义的类。

          @type_check_only
          class Response:  # private or not available at runtime
              code: int
              def get_header(self, name: str) -> str: ...

          def fetch_response() -> Response: ...

     注意，建议不要返回私有类实例，最好将之设为公共类。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0484

   (2) https://www.python.org/dev/peps/pep-0591


File: python.info,  Node: 内省辅助器,  Next: 常量<4>,  Prev: 函数与装饰器,  Up: 模块内容<7>

5.26.1.26 内省辅助器
....................

 -- 函式: typing.get_type_hints (obj, globalns=None, localns=None,
          include_extras=False)

     返回函数、方法、模块、类对象的类型提示的字典。

     一般情况下，与 ‘obj.__annotations__’ 相同。此外，可通过在 ‘globals’
     与 ‘locals’ 命名空间里进行评估，以此来处理编码为字符串字面量的前向
     引用。如有需要，在默认值设置为 ‘None’ 时，可为函数或方法注解添加
     ‘Optional[t]’。对于类 ‘C’，则返回由所有 ‘__annotations__’ 与
     ‘C.__mro__’ 逆序合并而成的字典。

     本函数以递归地方式用 ‘T’ 替换所有 ‘Annotated[T, ...]’， 除非将
     ‘include_extras’ 的值设置为 ‘True’ （详见 *note Annotated: 1ee.）。
     例如：

          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']
          }

     3.9 版更變: PEP 593(1) 的组成部分，添加了 ‘include_extras’ 参数。

 -- 函式: typing.get_args (tp)

 -- 函式: typing.get_origin (tp)

     为泛型类型与特殊类型形式提供了基本的内省功能。

     对于 ‘X[Y, Z, ...]’ 形式的类型对象，这些函数返回 ‘X’ 与 ‘(Y, Z,
     ...)’。如果 ‘X’ 是内置对象或 *note collections: 1d. class 的泛型别
     名， 会将其标准化为原始类。如果 ‘X’ 是包含在其他泛型类型中的 *note
     Union: 116a. 或 *note Literal: 275.，‘(Y, Z, ...)’ 的顺序会因类型缓
     存，而与原始参数 ‘[Y, Z, ...]’ 的顺序不同。对于不支持的对象会相应地
     返回 ‘None’ 或 ‘()’。例如：

          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)

     3.8 版新加入.

 -- 類別: typing.ForwardRef

     用于字符串前向引用的内部类型表示的类。 例如，‘List["SomeClass"]’ 会
     被隐式转换为 ‘List[ForwardRef("SomeClass")]’。 这个类不应由用户来实
     例化，但可以由内省工具使用。

          備註: PEP 585(2) 泛型类型例如 ‘list["SomeClass"]’ 将不会被隐式
          地转换为 ‘list[ForwardRef("SomeClass")]’ 因而将不会自动解析为
          ‘list[SomeClass]’。

     3.7.4 版新加入.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0593

   (2) https://www.python.org/dev/peps/pep-0585


File: python.info,  Node: 常量<4>,  Prev: 内省辅助器,  Up: 模块内容<7>

5.26.1.27 常量
..............

 -- Data: typing.TYPE_CHECKING

     被第三方静态类型检查器假定为 ‘True’ 的特殊常量。在运行时为 ‘False’。
     用法如下：

          if TYPE_CHECKING:
              import expensive_mod

          def fun(arg: 'expensive_mod.SomeType') -> None:
              local_var: expensive_mod.AnotherType = other_fun()

     第一个类型注解必须用引号标注，才能把它当作“前向引用”，从而在解释器
     运行时中隐藏 ‘expensive_mod’ 引用。局部变量的类型注释不会被评估，因
     此，第二个注解不需要用引号引起来。

          備註: Python 3.7 或更高版本中使用 ‘from __future__ import’ 时
          ，函数定义时不处理注解， 而是把注解当作字符串存在
          ‘__annotations__’ 里，这样就不必为注解使用引号。（详见 PEP
          563(1)）。

     3.5.2 版新加入.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0563


File: python.info,  Node: pydoc --- 文档生成器和在线帮助系统,  Next: Python 开发模式,  Prev: typing --- 类型提示支持,  Up: 開發工具

5.26.2 ‘pydoc’ — 文档生成器和在线帮助系统
-----------------------------------------

`源代码:' Lib/pydoc.py(1)

__________________________________________________________________

*note pydoc: d9. 模块自动利用 Python 模块生成文档。生成的文档可在控制台
中显示为文本页面，还可在 Web 浏览器中查阅，或保存为 HTML 文件。

对于模块、类、函数和方法，显示的文档内容取自文档字符串（即 ‘__doc__’ 属
性），并会递归地从其带文档的成员中获取。 如果没有文档字符串，*note
pydoc: d9. 会尝试从类、函数或方法定义上方，或是模块顶部的注释行段落获取
(参见 *note inspect.getcomments(): 344a.).

内置函数 *note help(): 175. 会发起调用交互式解释器的在线帮助系统，该系统
使用 *note pydoc: d9. 在终端上生成文本形式的文档内容。 同样的文本文档也
可以在 Python 解释器以外通过在操作系统的命令提示符下以脚本方式运行
‘pydoc’ 来查看。 例如，运行

     pydoc sys

在终端提示符下将通过 *note sys: fd. 模块显示文档内容，其样式类似于 Unix
‘man’ 命令所显示的指南页面。 ‘pydoc’ 的参数可以为函数、模块、包，或带点
号的对模块中的类、方法或函数以及包中的模块的引用。 如果传给 ‘pydoc’ 的参
数像是一个路径（即包含所在操作系统的路径分隔符，例如 Unix 的正斜杠），并
且其指向一个现有的 Python 源文件，则会为该文件生成文档内容。

     備註: 为了找到对象及其文档内容，*note pydoc: d9. 会导入文档所在的模
     块。 因此，任何模块层级的代码都将被执行。 请使用 ‘if __name__ ==
     '__main__':’ 语句来确保一个文件的特定代码仅在作为脚本被发起调用时执
     行而不是在被导入时执行。

当打印输出到控制台时，‘pydoc’ 会尝试对输出进行分页以方便阅读。 如果设置
了 ‘PAGER’ 环境变量，‘pydoc’ 将使用该变量值作为分页程序。

在参数前指定 ‘-w’ 旗标将把 HTML 文档写入到当前目录下的一个文件中，而不是
在控制台中显示文本。

在参数前指定 ‘-k’ 旗标将在全部可用模块的提要行中搜索参数所给定的关键字，
具体方式同样类似于 Unix ‘man’ 命令。 模块的提要行就是其文档字符串的第一
行。

你还可以使用 ‘pydoc’ 在本机上启动一个 HTTP 服务，这将向来访的 Web 浏览器
提供文档服务。 ‘pydoc -p 1234’ 将在 1234 端口上启动 HTTP 服务，允许你在
你喜欢的 Web 服务器中通过 ‘http://localhost:1234/’ 浏览文档内容。 指定
‘0’ 作为端口号将会任意选择一个未使用的端口。

‘pydoc -n <hostname>’ 将启动在给定主机名上执行监听的服务。 默认主机名为
’localhost’ 但如果你希望能从其他机器搜索该服务器，你可能会想要改变服务器
所响应的主机名。 在开发阶段此特性会特别有用，因为这样你将能在一个容器中
运行 pydoc。

‘pydoc -b’ 将启动服务并额外打开一个 Web 浏览器访问模块索引页。 所发布的
每个页面顶端都带有导航栏，你可以点击 `Get' 获取特定条目的帮助，点击
`Search' 在所有模块的提要行中搜索特定关键词，或是点击 `Module index',
`Topics' 和 `Keywords' 前往相应的页面。

当 ‘pydoc’ 生成文档内容时，它会使用当前环境和路径来定位模块。 因此，发起
调用 ‘pydoc spam’ 得到的文档版本会与你启动 Python 解释器并输入 ‘import
spam’ 时得到的模块版本完全相同。

核心模块的模块文档位置对应于 ‘https://docs.python.org/X.Y/library/’ 其中
‘X’ 和 ‘Y’ 是 Python 解释器的主要版本号和小版本号。 这可通过设置
‘PYTHONDOCS’ 环境变量来重载为指向不同的 URL 或包含 Library Reference
Manual 页面的本地目录。

3.2 版更變: 添加 ‘-b’ 选项。

3.3 版更變: 命令行选项 ‘-g’ 已经移除。

3.4 版更變: *note pydoc: d9. 现在会使用 *note inspect.signature(): 655.
而非 *note inspect.getfullargspec(): 657. 来从可调用对象中提取签名信息。

3.7 版更變: 添加 ‘-n’ 选项。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/pydoc.py


File: python.info,  Node: Python 开发模式,  Next: Python 开发模式的效果,  Prev: pydoc --- 文档生成器和在线帮助系统,  Up: 開發工具

5.26.3 Python 开发模式
----------------------

3.7 版新加入.

Python 开发模式引入了额外的运行时检查，由于成本太高，所以默认情况下是不
启用的。如果代码是正确的，它不应该比默认情况的更加详细；只有在检测到问题
的时候才会发出新的警告。

它可以通过 *note -X dev: 290. 命令行选项或通过设置 *note PYTHONDEVMODE:
43c. 环境变量为 ‘1’ 来启用。


File: python.info,  Node: Python 开发模式的效果,  Next: ResourceWarning 示例,  Prev: Python 开发模式,  Up: 開發工具

5.26.4 Python 开发模式的效果
----------------------------

启用 Python 开发模式后的效果，与以下命令类似，不过还有下面的额外效果：

     PYTHONMALLOC=debug PYTHONASYNCIODEBUG=1 python3 -W default -X faulthandler

Python 开发模式的效果：

   * 加入 ‘default’ *note warning filter: 147e. 。下述警告信息将会显示出
     来：

        * *note DeprecationWarning: 15a.

        * *note ImportWarning: 6cf.

        * *note PendingDeprecationWarning: 15c.

        * *note ResourceWarning: 5ca.

     通常上述警告是由默认的 *note warning filters: 147e. 负责处理的。

     其行为相当于使用了 *note -W default: 15b. 命令行选项。

     使用命令行参数 *note -W error: 15b. 或将环境变量 *note
     PYTHONWARNINGS: 51b. 设为 ‘error’，可将警告视为错误。

   * 在内存分配程序中安装调试钩子，用以查看：

        * 缓冲区下溢

        * 缓冲区上溢

        * 内存分配 API 冲突

        * 不安全的 GIL 调用

     参见 C 函数 *note PyMem_SetupDebugHooks(): 603. 。

     效果类似于将环境变量 *note PYTHONMALLOC: 5fc. 设为 ‘debug’。

     若要启用 Python 开发模式，却又不要在内存分配程序中安装调试钩子，请
     将 环境变量 *note PYTHONMALLOC: 5fc. 设为 ‘default’。

   * 在启动 Python 时调用 *note faulthandler.enable(): 642. ，会安装
     ‘SIGSEGV’ 、 ‘SIGFPE’ 、 ‘SIGABRT’ 、 ‘SIGBUS’ 和 ‘SIGILL’ 信号的处
     理程序，以便在程序崩溃时将 Python 跟踪信息转储下来。

     其行为如同使用了 *note -X faulthandler: 290. 命令行选项或将 *note
     PYTHONFAULTHANDLER: aa7. 环境变量设为 ‘1’。

   * 启用 *note asyncio debug mode: 148e.。比如 *note asyncio: 9. 会检查
     没有等待的协程并记录下来。

     效果如同将环境变量 *note PYTHONASYNCIODEBUG: 148d. 设为 ‘1’。

   * 检查字符串编码和解码函数的 `encoding' 和 `errors' 参数。例如：
     *note open(): 16f. 、 *note str.encode(): 170. 和 *note
     bytes.decode(): 171.。

     为了获得最佳性能，默认只会在第一次编码/解码错误时才会检查 `errors'
     参数，有时 `encoding' 参数为空字符串时还会被忽略。

   * *note io.IOBase: 30c. 的析构函数会记录 ‘close()’ 触发的异常。

   * 将 *note sys.flags: c0e. 的 ‘dev_mode’ 属性设为 ‘True’。

Python 开发模式下，默认不会启用 *note tracemalloc: 11d. 模块，因为其性能
和内存开销太大。启用 *note tracemalloc: 11d. 模块后，能够提供有关错误来
源的一些额外信息。例如，*note ResourceWarning: 5ca. 记录了资源分配的跟踪
信息，而缓冲区溢出错误记录了内存块分配的跟踪信息。

Python 开发模式不会阻止命令行参数 *note -O: 77e. 删除 *note assert: 23f.
语句，也不会阻止将 *note __debug__: 1137. 设为 ‘False’。

3.8 版更變: 现在， *note io.IOBase: 30c. 的析构函数会记录 ‘close()’ 触发
的异常。

3.9 版更變: 现在，字符串编码和解码操作时会检查 `encoding' 和 `errors' 参
数。


File: python.info,  Node: ResourceWarning 示例,  Next: 文件描述符错误示例,  Prev: Python 开发模式的效果,  Up: 開發工具

5.26.5 ResourceWarning 示例
---------------------------

以下示例将统计由命令行指定的文本文件的行数：

     import sys

     def main():
         fp = open(sys.argv[1])
         nlines = len(fp.readlines())
         print(nlines)
         # The file is closed implicitly

     if __name__ == "__main__":
         main()

上述代码没有显式关闭文件。默认情况下，Python 不会触发任何警告。下面用
README.txt 文件测试下，有 269 行。

     $ python3 script.py README.txt
     269

启用 Python 开发模式后，则会显示一条 *note ResourceWarning: 5ca. 警告。

     $ 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

启用 *note tracemalloc: 11d. 后，则还会显示打开文件的那行代码：

     $ 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])

修正方案就是显式关闭文件。下面用上下文管理器作为示例：

     def main():
         # Close the file explicitly when exiting the with block
         with open(sys.argv[1]) as fp:
             nlines = len(fp.readlines())
         print(nlines)

未能显式关闭资源，会让资源打开时长远超预期；在退出 Python 时可能会导致严
重问题。这在 CPython 中比较糟糕，但在 PyPy 中会更糟。显式关闭资源能让应
用程序更加稳定可靠。


File: python.info,  Node: 文件描述符错误示例,  Next: doctest --- 测试交互性的Python示例,  Prev: ResourceWarning 示例,  Up: 開發工具

5.26.6 文件描述符错误示例
-------------------------

显示自身的第一行代码：

     import os

     def main():
         fp = open(__file__)
         firstline = fp.readline()
         print(firstline.rstrip())
         os.close(fp.fileno())
         # The file is closed implicitly

     main()

默认情况下，Python 不会触发任何警告：

     $ python3 script.py
     import os

在 Python 开发模式下，会在析构文件对象时显示 *note ResourceWarning: 5ca.
并记录 “Bad file descriptor” 错误。

     $ 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

‘os.close(fp.fileno())’ 会关闭文件描述符。当文件对象析构函数试图再次关闭
文件描述符时会失败，并触发 ‘Bad file descriptor’ 错误。每个文件描述符只
允许关闭一次。在最坏的情况下，关闭两次会导致程序崩溃（示例可参见
bpo-18748(1) ）。

修正方案是删除 ‘os.close(fp.fileno())’ 这一行，或者打开文件时带上
‘closefd=False’ 参数。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue18748


File: python.info,  Node: doctest --- 测试交互性的Python示例,  Next: unittest --- 單元測試框架,  Prev: 文件描述符错误示例,  Up: 開發工具

5.26.7 ‘doctest’ — 测试交互性的Python示例
-----------------------------------------

** 源代码 ** Lib/doctest.py(1)

__________________________________________________________________

*note doctest: 66. 模块寻找像Python交互式代码的文本，然后执行这些代码来
确保它们的确就像展示的那样正确运行，有许多方法来使用doctest：

   * 通过验证所有交互式示例仍然按照记录的方式工作，以此来检查模块的文档
     字符串是否是最新的。

   * 通过验证来自一个测试文件或一个测试对象的交互式示例按预期工作，来进
     行回归测试。

   * 为一个包写指导性的文档，用输入输出的例子来说明。 取决于是强调例子还
     是说明性的文字，这有一种 "文本测试 "或 "可执行文档 "的风格。

下面是一个小却完整的示例模块:

     """
     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()

如果你直接在命令行里运行 ‘example.py’ ， *note doctest: 66. 将发挥他的作
用。

     $ python example.py
     $

没有输出！ 这很正常，这意味着所有的例子都成功了。 把 ‘-v’ 传给脚本，
*note doctest: 66. 会打印出它所尝试的详细日志，并在最后打印出一个总结。

     $ 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

以此类推，最终以：

     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.
     $

这就是对于高效地使用 *note doctest: 66. 你所需要知道的一切！开始上手吧。
下面的章节提供了完整的细节。 请注意，在标准的 Python 测试套件和库中有许
多 doctest 的例子。特别有用的例子可以在标准测试文件
‘Lib/test/test_doctest.py’ 中找到。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/doctest.py


File: python.info,  Node: 简单用法：检查Docstrings中的示例,  Next: 简单的用法：检查文本文件中的例子,  Up: doctest --- 测试交互性的Python示例

5.26.7.1 简单用法：检查Docstrings中的示例
.........................................

开始使用doctest的最简单方法（但不一定是你将继续这样做的方式）是结束每个
模块 ‘M’ 使用:

     if __name__ == "__main__":
         import doctest
         doctest.testmod()

*note doctest: 66. 会随后检查模块 ‘M’ 中的文档字符串。

以脚本形式运行该模块会使文档中的例子得到执行和验证:

     python M.py

这不会显示任何东西，除非一个例子失败了，在这种情况下，失败的例子和失败的
原因会被打印到stdout，最后一行的输出是‘‘***Test Failed*** N failures.‘‘，
其中*N*是失败的例子的数量。

用‘‘-v‘‘来运行它来切换，而不是:

     python M.py -v

并将所有尝试过的例子的详细报告打印到标准输出，最后还有各种总结。

你可以通过向 *note testmod(): e95. 传递 ‘verbose=True’ 来强制执行
verbose 模式，或者通过传递 ‘verbose=False’ 来禁止它。 在这两种情况下，
‘sys.argv’ 都不会被 *note testmod(): e95. 检查（所以传递 ‘-v’ 或不传递都
没有影响）。

还有一个命令行快捷方式用于运行 *note testmod(): e95.。 你可以指示
Python解释器直接从标准库中运行doctest模块，并在命令行中传递模块名称:

     python -m doctest -v example.py

这将导入 ‘example.py’ 作为一个独立的模块，并对其运行 *note testmod():
e95.。 注意，如果该文件是一个包的一部分，并且从该包中导入了其他子模块，
这可能无法正确工作。

关于 *note testmod(): e95. 的更多信息，请参见 *note 基本API: 3454. 部分
。


File: python.info,  Node: 简单的用法：检查文本文件中的例子,  Next: 它是如何工作的,  Prev: 简单用法：检查Docstrings中的示例,  Up: doctest --- 测试交互性的Python示例

5.26.7.2 简单的用法：检查文本文件中的例子
.........................................

doctest 的另一个简单应用是测试文本文件中的交互式例子。 这可以用 *note
testfile(): 3457. 函数来完成;:

     import doctest
     doctest.testfile("example.txt")

这个简短的脚本执行并验证文件 ‘example.txt’ 中包含的任何交互式 Python 示
例。该文件的内容被当作一个巨大的文档串来处理；该文件不需要包含一个
Python程序！例如，也许 ‘example.txt’ 包含以下内容:

     The ``example`` module
     ======================

     Using ``factorial``
     -------------------

     This is an example text file in reStructuredText format.  First import
     ``factorial`` from the ``example`` module:

         >>> from example import factorial

     Now use it:

         >>> factorial(6)
         120

运行‘‘doctest.testfile("example.txt")‘‘，然后发现这个文档中的错误:

     File "./example.txt", line 14, in example.txt
     Failed example:
         factorial(6)
     Expected:
         120
     Got:
         720

与 *note testmod(): e95. 一样， *note testfile(): 3457. 不会显示任何东西
，除非一个例子失败。 如果一个例子失败了，那么失败的例子和失败的原因将被
打印到stdout，使用的格式与 *note testmod(): e95. 相同。

默认情况下，*note testfile(): 3457. 在调用模块的目录中寻找文件。参见章节
*note 基本API: 3454.，了解可用于告诉它在其他位置寻找文件的可选参数的描述
。

像 *note testmod(): e95. 一样，*note testfile(): 3457. 的详细程度可以通
过命令行 ‘-v’ 切换或可选的关键字参数 `verbose' 来设置。

还有一个命令行快捷方式用于运行 *note testfile(): 3457.。 你可以指示
Python解释器直接从标准库中运行doctest模块，并在命令行中传递文件名:

     python -m doctest -v example.txt

因为文件名没有以 ‘.py’ 结尾，*note doctest: 66. 推断它必须用 *note
testfile(): 3457. 运行，而不是 *note testmod(): e95.。

关于 *note testfile(): 3457. 的更多信息，请参见 *note 基本API: 3454. 一
节。


File: python.info,  Node: 它是如何工作的,  Next: 基本API,  Prev: 简单的用法：检查文本文件中的例子,  Up: doctest --- 测试交互性的Python示例

5.26.7.3 它是如何工作的
.......................

这一节详细研究了doctest的工作原理：它查看哪些文档串，它如何找到交互式的
用例，它使用什么执行环境，它如何处理异常，以及如何用选项标志来控制其行为
。这是你写doctest例子所需要知道的信息；关于在这些例子上实际运行doctest的
信息，请看下面的章节。

* Menu:

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


File: python.info,  Node: 哪些文件串被检查了？,  Next: 文档串的例子是如何被识别的？,  Up: 它是如何工作的

5.26.7.4 哪些文件串被检查了？
.............................

模块的文档串以及所有函数、类和方法的文档串都将被搜索。 导入模块的对象不
被搜索。

此外，如果 ‘M.__test__’ 存在并且 "为真值"，则它必须是一个字典，其中每个
条目都将一个（字符串）名称映射到一个函数对象、类对象或字符串。 从
‘M.__test__’ 找到的函数和类对象的文档字符串会被搜索，而字符串会被当作文
档字符串来处理。 在输出时，每个键 ‘K’ 在 ‘M.__test__’ 中都显示为其名称

     <name of M>.__test__.K

任何发现的类都会以类似的方式进行递归搜索，以测试其包含的方法和嵌套类中的
文档串。

`CPython implementation detail:' Prior to version 3.4, extension modules
written in C were not fully searched by doctest.


File: python.info,  Node: 文档串的例子是如何被识别的？,  Next: 什么是执行上下文,  Prev: 哪些文件串被检查了？,  Up: 它是如何工作的

5.26.7.5 文档串的例子是如何被识别的？
.....................................

在大多数情况下，对交互式控制台会话的复制和粘贴功能工作得很好，但是
doctest 并不试图对任何特定的 Python shell 进行精确的模拟。

     >>> # comments are ignored
     >>> x = 12
     >>> x
     12
     >>> if x == 13:
     ...     print("yes")
     ... else:
     ...     print("no")
     ...     print("NO")
     ...     print("NO!!!")
     ...
     no
     NO
     NO!!!
     >>>

任何预期的输出必须紧随包含代码的最后 ‘'>>> '’ 或 ‘'... '’ 行，预期的输出
（如果有的话）延伸到下一 ‘'>>> '’ 行或全空白行。

fine输出：

   * 预期输出不能包含一个全白的行，因为这样的行被认为是预期输出的结束信
     号。 如果预期的输出包含一个空行，在你的测试例子中，在每一个预期有空
     行的地方加上‘‘<BLANKLINE>‘‘。

   * 所有硬制表符都被扩展为空格，使用 8 列的制表符。由测试代码生成的输出
     中的制表符不会被修改。 因为样本输出中的任何硬制表符都会被扩展，这意
     味着如果代码输出包括硬制表符，文档测试通过的唯一方法是 *note
     NORMALIZE_WHITESPACE: 345e. 选项或者 *note 指令: 345f. 是有效的。 另
     外，测试可以被重写，以捕获输出并将其与预期值进行比较，作为测试的一
     部分。这种对源码中标签的处理是通过试错得出的，并被证明是最不容易出
     错的处理方式。通过编写一个自定义的 *note DocTestParser: 3460. 类，
     可以使用一个不同的算法来处理标签。

   * 向stdout的输出被捕获，但不向stderr输出（异常回溯通过不同的方式被捕
     获）。

   * 如果你在交互式会话中通过反斜线续行，或出于任何其他原因使用反斜线，
     你应该使用原始文件串，它将完全保留你输入的反斜线:

          >>> def f(x):
          ...     r'''Backslashes in a raw docstring: m\n'''
          >>> print(f.__doc__)
          Backslashes in a raw docstring: m\n

     否则，反斜杠将被解释为字符串的一部分。例如，上面的‘‘n‘‘会被解释为一
     个换行符。 另外，你可以在doctest版本中把每个反斜杠加倍（而不使用原
     始字符串）:

          >>> def f(x):
          ...     '''Backslashes in a raw docstring: m\\n'''
          >>> print(f.__doc__)
          Backslashes in a raw docstring: m\n

   * 起始列并不重要:

          >>> assert "Easy!"
                >>> import math
                    >>> math.floor(1.9)
                    1

     并从预期的输出中剥离出与开始该例子的初始 ‘'>>> '’ 行中出现的同样多
     的前导空白字符。


File: python.info,  Node: 什么是执行上下文,  Next: 异常如何处理？,  Prev: 文档串的例子是如何被识别的？,  Up: 它是如何工作的

5.26.7.6 什么是执行上下文
.........................

默认情况下，每次 *note doctest: 66. 找到要测试的文档串时，它都会使用 ‘M’
的*浅层副本*，这样运行测试就不会改变模块的真正全局变量，而且 ‘M’ 的一个
测试也不会留下临时变量，从而意外地让另一个测试通过。这意味着例子可以自由
地使用 ‘M’ 中的任何顶级定义的名字，以及正在运行的文档串中早期定义的名字
。用例不能看到其他文档串中定义的名字。

你可以通过将‘‘globs=your_dict‘‘传递给 *note testmod(): e95. 或 *note
testfile(): 3457. 来强制使用你自己的dict作为执行环境。


File: python.info,  Node: 异常如何处理？,  Next: 选项标记,  Prev: 什么是执行上下文,  Up: 它是如何工作的

5.26.7.7 异常如何处理？
.......................

没问题，只要回溯是这个例子产生的唯一输出：只要粘贴回溯即可。(1) 由于回溯
所包含的细节可能会迅速变化（例如，确切的文件路径和行号），这是doctest努
力使其接受的内容具有灵活性的一种情况。

简单实例:

     >>> [1, 2, 3].remove(42)
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     ValueError: list.remove(x): x not in list

如果 *note ValueError: 16d. 被触发，该测试就会成功，‘list.remove(x): x
not in list’ 的细节如图所示。

异常的预期输出必须以回溯头开始，可以是以下两行中的任何一行，缩进程度与例
子中的第一行相同:

     Traceback (most recent call last):
     Traceback (innermost last):

回溯头的后面是一个可选的回溯堆栈，其内容被doctest忽略。 回溯堆栈通常是省
略的，或者从交互式会话中逐字复制的。

回溯堆栈的后面是最有趣的部分：包含异常类型和细节的一行（几行）。 这通常
是回溯的最后一行，但如果异常有多行细节，则可以延伸到多行:

     >>> raise ValueError('multi\n    line\ndetail')
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     ValueError: multi
         line
     detail

最后三行（以 *note ValueError: 16d. 开头）将与异常的类型和细节进行比较，
其余的被忽略。

最佳实践是省略回溯栈，除非它为这个例子增加了重要的文档价值。 因此，最后
一个例子可能更好，因为:

     >>> raise ValueError('multi\n    line\ndetail')
     Traceback (most recent call last):
         ...
     ValueError: multi
         line
     detail

请注意，回溯的处理方式非常特别。 特别是，在重写的例子中，‘...’ 的使用与
doctest 的 *note ELLIPSIS: e96. 选项无关。 该例子中的省略号可以不写，也
可以是三个（或三百个）逗号或数字，或者是一个缩进的 Monty Python 短剧的剧
本。

有些细节你应该读一遍，但不需要记住：

   * Doctest 不能猜测你的预期输出是来自异常回溯还是来自普通打印。 因此，
     例如，一个期望 ‘ValueError: 42 is prime’ 的用例将通过测试，无论
     *note ValueError: 16d. 是真的被触发，或者该用例只是打印了该回溯文本
     。 在实践中，普通输出很少以回溯标题行开始，所以这不会产生真正的问题
     。

   * 回溯堆栈的每一行（如果有的话）必须比例子的第一行缩进， `或者' 以一
     个非字母数字的字符开始。 回溯头之后的第一行缩进程度相同，并且以字母
     数字开始，被认为是异常细节的开始。 当然，这对真正的回溯来说是正确的
     事情。

   * 当 *note IGNORE_EXCEPTION_DETAIL: 3465. doctest 选项被指定时，最左
     边的冒号后面的所有内容以及异常名称中的任何模块信息都被忽略。

   * 交互式 shell 省略了一些 *note SyntaxError: 559. 的回溯头行。但
     doctest 使用回溯头行来区分异常和非异常。所以在罕见的情况下，如果你
     需要测试一个省略了回溯头的 *note SyntaxError: 559.，你将需要手动添
     加回溯头行到你的测试用例中。

   * 对于一些 *note SyntaxError: 559.，Python 使用 ‘^’ 标记显示语法错误
     的字符位置:

          >>> 1 1
            File "<stdin>", line 1
              1 1
                ^
          SyntaxError: invalid syntax

     由于显示错误位置的行在异常类型和细节之前，它们不被doctest检查。 例
     如，下面的测试会通过，尽管它把‘‘^‘‘标记放在了错误的位置:

          >>> 1 1
          Traceback (most recent call last):
            File "<stdin>", line 1
              1 1
              ^
          SyntaxError: invalid syntax

   ---------- Footnotes ----------

   (1) (1) 不支持同时包含预期输出和异常的用例。试图猜测一个在哪里结束，
另一个在哪里开始，太容易出错了，而且这也会使测试变得混乱。


File: python.info,  Node: 选项标记,  Next: 指令,  Prev: 异常如何处理？,  Up: 它是如何工作的

5.26.7.8 选项标记
.................

一系列选项旗标控制着 doctest 的各方面行为。 旗标的符号名称以模块常量的形
式提供，可以一起 *note 按位或: 1676. 并传递给各种函数。 这些名称也可以在
*note doctest 指令: 345f. 中使用，并且可以通过 ‘-o’ 选项传递给 doctest 命
令行接口。

3.4 版新加入: 命令行选项 ‘-o’ 。

第一组选项定义了测试语义，控制doctest如何决定实际输出是否与用例的预期输
出相匹配方面的问题。

 -- Data: doctest.DONT_ACCEPT_TRUE_FOR_1

     默认情况下，如果一个预期的输出块只包含 ‘1’，那么实际的输出块只包含
     ‘1’ 或只包含 ‘True’ 就被认为是匹配的，同样，‘0’ 与 ‘False’ 也是如此
     。 当 *note DONT_ACCEPT_TRUE_FOR_1: 3468. 被指定时，两种替换都不允
     许。 默认行为是为了适应 Python 将许多函数的返回类型从整数改为布尔值
     ；期望 "小整数" 输出的测试在这些情况下仍然有效。 这个选项可能会消失
     ，但不会在几年内消失。

 -- Data: doctest.DONT_ACCEPT_BLANKLINE

     默认情况下，如果一个预期输出块包含一个只包含字符串 ‘<BLANKLINE>’ 的
     行，那么该行将与实际输出中的一个空行相匹配。 因为一个真正的空行是对
     预期输出的限定，这是传达预期空行的唯一方法。 当 *note
     DONT_ACCEPT_BLANKLINE: 3469. 被指定时，这种替换是不允许的。

 -- Data: doctest.NORMALIZE_WHITESPACE

     当指定时，所有的空白序列（空白和换行）都被视为相等。预期输出中的任
     何空白序列将与实际输出中的任何空白序列匹配。默认情况下，空白必须完
     全匹配。 *note NORMALIZE_WHITESPACE: 345e. 在预期输出非常长的一行，
     而你想把它包在源代码的多行中时特别有用。

 -- Data: doctest.ELLIPSIS

     当指定时，预期输出中的省略号（‘...’）可以匹配实际输出中的任何子串。
     这包括跨行的子串和空子串，所以最好保持简单的用法。复杂的用法会导致
     与‘‘.*‘‘在正则表达式中容易出现的 "oops, it matched too much!"相同的
     意外情况。

 -- Data: doctest.IGNORE_EXCEPTION_DETAIL

     当被指定时，如果一个预期的异常类型被触发，即使异常细节不匹配，期望
     异常的用例也会通过。 例如，如果实际引发的异常是 ‘ValueError: 42’，
     期待 ‘ValueError: 3*14’ 的用例将通过，但例如，如果 *note TypeError:
     1fe. 触发将导致失败。

     它也会忽略Python 3 doctest报告中使用的模块名称。因此，无论测试是在
     Python 2.7还是Python 3.2 (或更高版本)下运行，这两种变化都会在指定的
     标志下工作:

          >>> raise CustomError('message')
          Traceback (most recent call last):
          CustomError: message

          >>> raise CustomError('message')
          Traceback (most recent call last):
          my_module.CustomError: message

     注意 *note ELLIPSIS: e96. 也可以用来忽略异常信息的细节，但这样的测
     试仍然可能失败，因为模块的细节可能被打印为异常名称的一部分。使用
     *note IGNORE_EXCEPTION_DETAIL: 3465. 和 Python 2.3 的细节也是唯一明
     确的方法，可以编写一个不关心异常细节但在 Python 2.3 或更早的版本中
     继续通过的 doctest (这些版本不支持 *note doctest directives: 345f.
     并将其作为无关的注释忽略)。例如:

          >>> (1, 2)[3] = 'moo'
          Traceback (most recent call last):
            File "<stdin>", line 1, in <module>
          TypeError: object doesn't support item assignment

     在Python 2.3及以后的Python版本中，在指定了标志的情况下通过，尽管这
     个细节在Python 2.4中改变为 "does not" 而不是 "doesn’t"。

     3.2 版更變: *note IGNORE_EXCEPTION_DETAIL: 3465. 现在也忽略了与包含
     被测异常的模块有关的任何信息。

 -- Data: doctest.SKIP

     当指定时，完全不运行这个用例。 这在doctest用例既是文档又是测试案例
     的情况下很有用，一个例子应该包括在文档中，但不应该被检查。例如，这
     个例子的输出可能是随机的；或者这个例子可能依赖于测试驱动程序所不能
     使用的资源。

     SKIP标志也可用于临时 "注释" 用例。

 -- Data: doctest.COMPARISON_FLAGS

     一个比特或运算将上述所有的比较标志放在一起。

第二组选项控制测试失败的报告方式：

 -- Data: doctest.REPORT_UDIFF

     当指定时，涉及多行预期和实际输出的故障将使用统一的差异来显示。

 -- Data: doctest.REPORT_CDIFF

     当指定时，涉及多行预期和实际输出的故障将使用上下文差异来显示。

 -- Data: doctest.REPORT_NDIFF

     当指定时，差异由‘‘difflib.Differ‘‘来计算，使用与流行的
     :file:‘ndiff.py‘工具相同的算法。这是唯一一种标记行内和行间差异的方
     法。 例如，如果一行预期输出包含数字‘‘1‘’，而实际输出包含字母‘‘l‘‘，
     那么就会插入一行，用圆点标记不匹配的列位置。

 -- Data: doctest.REPORT_ONLY_FIRST_FAILURE

     当指定时，在每个 doctest 中显示第一个失败的用例，但隐藏所有其余用例
     的输出。 这将防止 doctest 报告由于先前的失败而中断的正确用例；但也
     可能隐藏独立于第一个失败的不正确用例。 当 *note
     REPORT_ONLY_FIRST_FAILURE: 346c. 被指定时，其余的用例仍然被运行，并
     且仍然计入报告的失败总数；只是输出被隐藏了。

 -- Data: doctest.FAIL_FAST

     当指定时，在第一个失败的用例后退出，不尝试运行其余的用例。因此，报
     告的失败次数最多为1。这个标志在调试时可能很有用，因为第一个失败后的
     用例甚至不会产生调试输出。

     doctest命令行接受选项‘‘-f‘‘作为‘‘-o FAIL_FAST‘‘的简洁形式。

     3.4 版新加入.

 -- Data: doctest.REPORTING_FLAGS

     一个比特或操作将上述所有的报告标志组合在一起。

还有一种方法可以注册新的选项标志名称，不过这并不有用，除非你打算通过子类
来扩展 *note doctest: 66. 内部。

 -- 函式: doctest.register_optionflag (name)

     用给定的名称创建一个新的选项标志，并返回新标志的整数值。 *note
     register_optionflag(): 346e. 可以在继承 *note OutputChecker: 346f.
     或 *note DocTestRunner: 3470. 时使用，以创建子类支持的新选项。
     *note register_optionflag(): 346e. 应始终使用以下方式调用:

          MY_FLAG = register_optionflag('MY_FLAG')


File: python.info,  Node: 指令,  Next: 警告<2>,  Prev: 选项标记,  Up: 它是如何工作的

5.26.7.9 指令
.............

Doctest指令可以用来修改单个例子的 *note option flags: 929. 。 Doctest指
令是在一个用例的源代码后面的特殊Python注释。

     directive             ::= "#" "doctest:" directive_options
     directive_options     ::= directive_option ("," directive_option)\*
     directive_option      ::= on_or_off directive_option_name
     on_or_off             ::= "+" \| "-"
     directive_option_name ::= "DONT_ACCEPT_BLANKLINE" \| "NORMALIZE_WHITESPACE" \| ...

‘+’ 或 ‘-’ 与指令选项名称之间不允许有空格。 指令选项名称可以是上面解释的
任何一个选项标志名称。

一个用例的 doctest 指令可以修改 doctest 对该用例的行为。 使用 ‘+’ 来启用
指定的行为，或者使用 ‘-’ 来禁用它。

例如，这个测试将会通过:

     >>> print(list(range(20)))
     [0,   1,  2,  3,  4,  5,  6,  7,  8,  9,
     10,  11, 12, 13, 14, 15, 16, 17, 18, 19]

如果没有这个指令，它就会失败，这是因为实际的输出在个位数的列表元素前没有
两个空格，也因为实际的输出是在单行上。 这个测试也通过了，而且也需要一个
指令来完成:

     >>> print(list(range(20)))
     [0, 1, ..., 18, 19]

在一个物理行上可以使用多个指令，用逗号分隔:

     >>> print(list(range(20)))
     [0,    1, ...,   18,    19]

如果在一个用例中使用了多个指令注释，那么它们将被合并:

     >>> print(list(range(20)))
     ...
     [0,    1, ...,   18,    19]

正如前面的例子所示，你可以在你的用例中添加只包含指令的行。 当一个用例太
长，指令不能舒适地放在同一行时，这可能很有用:

     >>> print(list(range(5)) + list(range(10, 20)) + list(range(30, 40)))
     ...
     [0, ..., 4, 10, ..., 19, 30, ..., 39]

请注意，由于所有的选项都是默认禁用的，而指令只适用于它们出现的用例，所以
启用选项 (通过指令中的 ‘+’) 通常是唯一有意义的选择。 然而，选项标志也可
以被传递给运行测试的函数，建立不同的默认值。 在这种情况下，通过指令中的
‘-’ 来禁用一个选项可能是有用的。


File: python.info,  Node: 警告<2>,  Prev: 指令,  Up: 它是如何工作的

5.26.7.10 警告
..............

*note doctest: 66. 是严格地要求在预期输出中完全匹配。 如果哪怕只有一个字
符不匹配，测试就会失败。 这可能会让你吃惊几次，在你确切地了解到 Python 对
输出的保证和不保证之前。 例如，当打印一个集合时，Python 不保证元素以任何
特定的顺序被打印出来，所以像:

     >>> foo()
     {"Hermione", "Harry"}

是不可靠的！一个变通方法是做:

     >>> foo() == {"Hermione", "Harry"}
     True

来取代。另一个是使用

     >>> d = sorted(foo())
     >>> d
     ['Harry', 'Hermione']

     備註: 在 Python 3.6 之前，当打印一个 dict 时，Python 并不保证键值对
     以任何特定的顺序被打印。

还有其他的问题，但你会明白的。

另一个不好的做法是打印嵌入了对象地址的变量，如:

     >>> 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>

*note ELLIPSIS: e96. 指令为最后一个例子提供了一个不错的方法:

     >>> C()
     <__main__.C instance at 0x...>

浮点数在不同的平台上也会有小的输出变化，因为Python在浮点数的格式化上依赖
于平台的C库，而C库在这个问题上的质量差异很大。:

     >>> 1./7  # risky
     0.14285714285714285
     >>> print(1./7) # safer
     0.142857142857
     >>> print(round(1./7, 6)) # much safer
     0.142857

形式‘‘I/2.**J‘‘的数字在所有的平台上都是安全的，我经常设计一些测试的用例
来产生该形式的数:

     >>> 3./4  # utterly safe
     0.75

简单的分数也更容易让人理解，这也使得文件更加完善。


File: python.info,  Node: 基本API,  Next: Unittest API,  Prev: 它是如何工作的,  Up: doctest --- 测试交互性的Python示例

5.26.7.11 基本API
.................

函数 *note testmod(): e95. 和 *note testfile(): 3457. 为 doctest 提供了
一个简单的接口，应该足以满足大多数基本用途。关于这两个函数的不太正式的介
绍，请参见 *note 简单用法：检查Docstrings中的示例: 3452. 和 *note
简单的用法：检查文本文件中的例子: 3455. 部分。

 -- 函式: 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*，所有的参数都是可选的，而且应该以关键字的形式指定。

     测试名为 `filename' 的文件中的用例。 返回‘‘(failure_count,
     test_count)‘‘。

     可选参数 `module_relative' 指定了文件名的解释方式。

        * 如果 `module_relative' 是 ‘True’ (默认)，那么 `filename' 指定
          一个独立于操作系统的模块相对路径。 默认情况下，这个路径是相对
          于调用模块的目录的；但是如果指定了 `package' 参数，那么它就是
          相对于该包的。 为了保证操作系统的独立性，`filename' 应该使用字
          符来分隔路径段，并且不能是一个绝对路径 (即不能以 ‘/’ 开始)。

        * 如果 `module_relative' 是 ‘False’，那么 `filename' 指定了一个
          操作系统特定的路径。路径可以是绝对的，也可以是相对的；相对路径
          是相对于当前工作目录而言的。

     可选参数 `name' 给出了测试的名称；默认情况下，或者如果是‘‘None‘‘，
     那么使用‘‘os.path.basename(filename)‘‘。

     可选参数 `package' 是一个 Python 包或一个 Python 包的名字，其目录应
     被用作模块相关文件名的基础目录。 如果没有指定包，那么调用模块的目录
     将作为模块相关文件名的基础目录。如果 `module_relative' 是
     ‘‘False‘‘，那么指定 `package' 是错误的。

     可选参数 `globs' 给出了一个在执行示例时用作全局变量的dict。 这个
     dict的一个新的浅层副本将为doctest创建，因此它的用例将从一个干净的地
     方开始。默认情况下，或者如果为‘‘None‘‘，使用一个新的空dict。

     可选参数 `extraglobs' 给出了一个合并到用于执行用例全局变量中的
     dict。 这就像 *note dict.update(): e8e. 一样：如果 `globs' 和
     `extraglobs' 有一个共同的键，那么 `extraglobs' 中的相关值会出现在合
     并的dict中。 默认情况下，或者为‘‘None‘‘ ，则不使用额外的全局变量。
     这是一个高级功能，允许对 doctest 进行参数化。例如，可以为一个基类写
     一个测试，使用该类的通用名称，然后通过传递一个 `extraglobs' dict，
     将通用名称映射到要测试的子类，从而重复用于测试任何数量的子类。

     可选的参数 `verbose' 如果为真值会打印很多东西，如果为假值则只打印失
     败信息；默认情况下，或者为 ‘None’，只有当 ‘'-v'’ 在 ‘sys.argv’ 中时
     才为真值。

     可选参数 `report' 为True时，在结尾处打印一个总结，否则在结尾处什么
     都不打印。 在verbose模式下，总结是详细的，否则总结是非常简短的（事
     实上，如果所有的测试都通过了，总结就是空的）。

     可选参数 `optionflags' （默认值为0）是选项标志的 *note bitwise OR:
     1676. 。参见章节 *note 选项标记: 929. 。

     可选参数 `raise_on_error' 默认为False。 如果是True，在一个用例中第
     一次出现失败或意外的异常时，会触发一个异常。这允许对失败进行事后调
     试。默认行为是继续运行例子。

     可选参数 `parser' 指定一个 *note DocTestParser: 3460. （或子类），
     它应该被用来从文件中提取测试。它默认为一个普通的解析器（即
     ‘‘DocTestParser()‘‘）。

     可选参数 `encoding' 指定了一个编码，应该用来将文件转换为unicode。

 -- 函式: doctest.testmod (m=None, name=None, globs=None, verbose=None,
          report=True, optionflags=0, extraglobs=None,
          raise_on_error=False, exclude_empty=False)

     所有的参数都是可选的，除了 `m' 之外，都应该以关键字的形式指定。

     测试从模块 `m' （或模块 *note __main__: 1. ，如果 `m' 没有被提供或
     为‘‘None‘‘）可达到的函数和类的文档串中的用例，从‘‘m.__doc__‘‘开始。

     也测试从dict ‘m.__test__’ 可达到的用例，如果它存在并且不是 ‘None’ 。
     ‘m.__test__’ 将名字（字符串）映射到函数、类和字符串；函数和类的文档
     串被搜索到的用例；字符串被直接搜索到，就像它们是文档串一样。

     只搜索附属于模块 `m' 中的对象的文档串。

     返回 ‘(failure_count, test_count)’ 。

     可选参数 `name' 给出了模块的名称；默认情况下，或者如果为 ‘None’ ，
     则为 ‘m.__name__’ 。

     可选参数 `exclude_empty' 默认为假值。 如果为真值，没有找到任何
     doctest 的对象将被排除在考虑范围之外。 默认情况下是向后兼容，所以仍
     然使用 ‘doctest.master.summarize()’ 和 *note testmod(): e95. 的代码
     会继续得到没有测试的对象的输出。 较新的 *note DocTestFinder: 347a.
     构造器的 `exclude_empty' 参数默认为真值。

     可选参数 `extraglobs' 、 `verbose' 、 `report' 、 `optionflags' 、
     `raise_on_error' 和 `globs' 与上述函数 *note testfile(): 3457. 的参
     数相同，只是 `globs' 默认为 ‘m.__dict__’ 。

 -- 函式: doctest.run_docstring_examples (f, globs, verbose=False,
          name="NoName", compileflags=None, optionflags=0)

     与对象 `f' 相关的测试用例；例如， `f' 可以是一个字符串、一个模块、
     一个函数或一个类对象。

     dict 参数 `globs' 的浅层拷贝被用于执行环境。

     可选参数*name*在失败信息中使用，默认为 ‘"NoName"’ 。

     如果可选参数 `verbose' 为真，即使没有失败也会产生输出。 默认情况下
     ，只有在用例失败的情况下才会产生输出。

     可选参数 `compileflags' 给出了Python编译器在运行例子时应该使用的标
     志集。默认情况下，或者如果为 ‘None’ ，标志是根据 `globs' 中发现的未
     来特征集推导出来的。

     可选参数 `optionflags' 的作用与上述 *note testfile(): 3457. 函数中
     的相同。


File: python.info,  Node: Unittest API,  Next: 高级 API,  Prev: 基本API,  Up: doctest --- 测试交互性的Python示例

5.26.7.12 Unittest API
......................

*note doctest: 66. 提供了两个函数，可以用来从模块和包含测试的文本文件中
创建 *note unittest: 124. 测试套件。 要与 *note unittest: 124. 测试发现
集成，请在你的测试模块中包含一个 ‘load_tests()’ 函数：:

     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

有两个主要函数用于从文本文件和带doctest的模块中创建 *note
unittest.TestSuite: 7c1. 实例。

 -- 函式: doctest.DocFileSuite (*paths, module_relative=True,
          package=None, setUp=None, tearDown=None, globs=None,
          optionflags=0, parser=DocTestParser(), encoding=None)

     将一个或多个文本文件中的doctest测试转换为一个 *note
     unittest.TestSuite: 7c1. 。

     返回的 *note unittest.TestSuite: 7c1. 将由 unittest 框架运行，并运
     行每个文件中的交互式示例。如果任何文件中的用例失败了，那么合成的单
     元测试就会失败，并触发一个 ‘failureException’ 异常，显示包含该测试
     的文件名和一个（有时是近似的）行号。

     传递一个或多个要检查的文本文件的路径（作为字符串）。

     选项可以作为关键字参数提供：

     可选参数 `module_relative' 指定了 `paths' 中的文件名应该如何解释。

        * 如果*module_relative*是 ‘True’ （默认值），那么 `paths' 中的每
          个文件名都指定了一个独立于操作系统的模块相对路径。 默认情况下
          ，这个路径是相对于调用模块的目录的；但是如果指定了 `package' 参
          数，那么它就是相对于该包的。 为了保证操作系统的独立性，每个文
          件名都应该使用字符来分隔路径段，并且不能是绝对路径（即不能以
          ‘/’ 开始）。

        * 如果 `module_relative' 是 ‘False’ ，那么 `paths' 中的每个文件
          名都指定了一个操作系统特定的路径。 路径可以是绝对的，也可以是
          相对的；相对路径是关于当前工作目录的解析。

     可选参数 `package' 是一个Python包或一个Python包的名字，其目录应该被
     用作 `paths' 中模块相关文件名的基本目录。 如果没有指定包，那么调用
     模块的目录将作为模块相关文件名的基础目录。 如果 `module_relative' 是
     ‘False’ ，那么指定 `package' 是错误的。

     可选的参数 `setUp' 为测试套件指定了一个设置函数。在运行每个文件中的
     测试之前，它被调用。 `setUp' 函数将被传递给一个 *note DocTest:
     347f. 对象。 setUp函数可以通过测试的 `globs' 属性访问测试的全局变量
     。

     可选的参数 `tearDown' 指定了测试套件的卸载函数。 在运行每个文件中的
     测试后，它会被调用。 `tearDown' 函数将被传递一个 *note DocTest:
     347f. 对象。 setUp函数可以通过测试的 `globs' 属性访问测试的全局变量
     。

     可选参数 `globs' 是一个包含测试的初始全局变量的字典。 这个字典的一
     个新副本为每个测试创建。 默认情况下， `globs' 是一个新的空字典。

     可选参数 `optionflags' 为测试指定默认的doctest选项，通过将各个选项
     的标志连接在一起创建。 参见章节 *note 选项标记: 929. 。参见下面的函
     数 *note set_unittest_reportflags(): 3480. ，以了解设置报告选项的更
     好方法。

     可选参数 `parser' 指定一个 *note DocTestParser: 3460. （或子类），
     它应该被用来从文件中提取测试。它默认为一个普通的解析器（即
     ‘‘DocTestParser()‘‘）。

     可选参数 `encoding' 指定了一个编码，应该用来将文件转换为unicode。

     该全局 ‘__file__’ 被添加到提供给用 *note DocFileSuite(): 347e. 从文
     本文件加载的doctest的全局变量中。

 -- 函式: doctest.DocTestSuite (module=None, globs=None,
          extraglobs=None, test_finder=None, setUp=None, tearDown=None,
          checker=None)

     将一个模块的doctest测试转换为 *note unittest.TestSuite: 7c1. 。

     返回的 *note unittest.TestSuite: 7c1. 将由 unittest 框架运行，并运
     行模块中的每个 doctest。 如果任何一个测试失败，那么合成的单元测试就
     会失败，并触发一个 ‘failureException’ 异常，显示包含该测试的文件名
     和一个（有时是近似的）行号。

     可选参数 `module' 提供了要测试的模块。 它可以是一个模块对象或一个（
     可能是带点的）模块名称。 如果没有指定，则使用调用此函数的模块。

     可选参数 `globs' 是一个包含测试的初始全局变量的字典。 这个字典的一
     个新副本为每个测试创建。 默认情况下， `globs' 是一个新的空字典。

     可选参数 `extraglobs' 指定了一组额外的全局变量，这些变量被合并到
     `globs' 中。 默认情况下，不使用额外的全局变量。

     可选参数 `test_finder' 是 *note DocTestFinder: 347a. 对象（或一个可
     替换的对象），用于从模块中提取测试。

     可选参数 `setUp' 、 `tearDown' 和 `optionflags' 与上述函数 *note
     DocFileSuite(): 347e. 相同。

     这个函数使用与 *note testmod(): e95. 相同的搜索技术。

     3.5 版更變: 如果 `module' 不包含任何文件串，则 *note
     DocTestSuite(): 7c0. 返回一个空的 *note unittest.TestSuite: 7c1.，
     而不是触发 *note ValueError: 16d.。

*note DocTestSuite(): 7c0. 从 ‘doctest.DocTestCase’ 实例中创建一个 *note
unittest.TestSuite: 7c1. ，而 ‘DocTestCase’ 是 *note unittest.TestCase:
9e5. 的子类。 ‘DocTestCase’ 在这里没有记录（这是一个内部细节），但研究其
代码可以回答关于 *note unittest: 124. 集成的实际细节问题。

同样， *note DocFileSuite(): 347e. 从 ‘doctest.DocFileCase’ 实例中创建一
个 *note unittest.TestSuite: 7c1. ，并且 ‘DocFileCase’ 是 ‘DocTestCase’
的一个子类。

所以这两种创建 *note unittest.TestSuite: 7c1. 的方式都是运行
‘DocTestCase’ 的实例。这一点很重要，因为有一个微妙的原因：当你自己运行
*note doctest: 66. 函数时，你可以直接控制使用中的 *note doctest: 66. 选
项，通过传递选项标志给 *note doctest: 66. 函数。 然而，如果你正在编写一
个 *note unittest: 124. 框架， *note unittest: 124. 最终会控制测试的运行
时间和方式。 框架作者通常希望控制 *note doctest: 66. 的报告选项（也许，
例如，由命令行选项指定），但没有办法通过 *note unittest: 124. 向 *note
doctest: 66. 测试运行者传递选项。

出于这个原因， *note doctest: 66. 也支持一个概念，即 *note doctest: 66.
报告特定于 *note unittest: 124. 支持的标志，通过这个函数：

 -- 函式: doctest.set_unittest_reportflags (flags)

     设置要使用的 *note doctest: 66. 报告标志。

     参数 `flags' 是选项标志的 *note bitwise OR: 1676. 。 参见章节 *note
     选项标记: 929. 。 只有 "报告标志" 可以被使用。

     这是一个模块的全局设置，并影响所有未来由模块 *note unittest: 124. 运
     行的测试： ‘DocTestCase’ 的 ‘runTest()’ 方法会查看 ‘DocTestCase’ 实
     例构建时为测试用例指定的选项标志。 如果没有指定报告标志（这是典型的
     和预期的情况）， *note doctest: 66. 的 *note unittest: 124. 报告标
     志被 *note bitwise ORed: 1676. 到选项标志中，这样增加的选项标志被传
     递给 *note DocTestRunner: 3470. 实例来运行doctest。 如果在构建
     ‘DocTestCase’ 实例时指定了任何报告标志，那么 *note doctest: 66. 的
     *note unittest: 124. 报告标志会被忽略。

     *note unittest: 124. 报告标志的值在调用该函数之前是有效的，由该函数
     返回。


File: python.info,  Node: 高级 API,  Next: 调试,  Prev: Unittest API,  Up: doctest --- 测试交互性的Python示例

5.26.7.13 高级 API
..................

基本 API 是一个简单的封装，旨在使 doctest 易于使用。它相当灵活，应该能满
足大多数用户的需求；但是，如果你需要对测试进行更精细的控制，或者希望扩展
doctest 的功能，那么你应该使用高级 API 。

高级API围绕着两个容器类，用于存储从 doctest 案例中提取的交互式用例:

   * *note Example: 3483.: 一个单一的 Python *note statement: 1cef. ，与
     它的预期输出配对。

   * *note DocTest: 347f.: 一组 *note Example: 3483.s 的集合，通常从一个
     文档字符串或文本文件中提取。

定义了额外的处理类来寻找、解析和运行，并检查 doctest 的用例。

   * *note DocTestFinder: 347a. : 查找给定模块中的所有文档串，并使用
     *note DocTestParser: 3460. 从每个包含交互式用例的文档串中创建一个
     *note DocTest: 347f. 。

   * *note DocTestParser: 3460. : 从一个字符串（如一个对象的文档串）创建
     一个 *note DocTest: 347f. 对象。

   * *note DocTestRunner: 3470. : 执行 *note DocTest: 347f. 中的用例，并
     使用 *note OutputChecker: 346f. 来验证其输出。

   * *note OutputChecker: 346f. : 将一个测试用例的实际输出与预期输出进行
     比较，并决定它们是否匹配。

这些处理类之间的关系总结在下图中:

                                 list of:
     +------+                   +---------+
     |module| --DocTestFinder-> | DocTest | --DocTestRunner-> results
     +------+    |        ^     +---------+     |       ^    (printed)
                 |        |     | Example |     |       |
                 v        |     |   ...   |     v       |
                DocTestParser   | Example |   OutputChecker
                                +---------+

* Menu:

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


File: python.info,  Node: DocTest 对象,  Next: Example 对象,  Up: 高级 API

5.26.7.14 DocTest 对象
......................

 -- 類別: doctest.DocTest (examples, globs, name, filename, lineno,
          docstring)

     应该在单一命名空间中运行的doctest用例的集合。构造函数参数被用来初始
     化相同名称的属性。

     *note DocTest: 347f. 定义了以下属性。 它们由构造函数初始化，不应该
     被直接修改。

      -- 屬性: examples

          一个 *note Example: 3483. 对象的列表，它编码了应该由该测试运行
          的单个交互式 Python 用例。

      -- 屬性: globs

          例子应该运行的命名空间（又称 globals ）。这是一个将名字映射到
          数值的字典。例子对名字空间的任何改变（比如绑定新的变量）将在测
          试运行后反映在 *note globs: 3487. 中。

      -- 屬性: name

          识别 *note DocTest: 347f. 的字符串名称。 通常情况下，这是从测
          试中提取的对象或文件的名称。

      -- 屬性: filename

          这个 *note DocTest: 347f. 被提取的文件名；或者为‘‘None‘‘，如果
          文件名未知，或者 *note DocTest: 347f. 没有从文件中提取。

      -- 屬性: lineno

          *note filename: 3489. 中的行号，这个 *note DocTest: 347f. 开始
          的地方，或者行号不可用时为‘‘None‘‘。 这个行号相对于文件的开头
          来说是零的。

      -- 屬性: docstring

          从测试中提取的字符串，或者如果字符串不可用，或者为 ‘None’ ，如
          果测试没有从字符串中提取。


File: python.info,  Node: Example 对象,  Next: DocTestFinder 对象,  Prev: DocTest 对象,  Up: 高级 API

5.26.7.15 Example 对象
......................

 -- 類別: doctest.Example (source, want, exc_msg=None, lineno=0,
          indent=0, options=None)

     单个交互式用例，由一个 Python 语句及其预期输出组成。 构造函数参数被
     用来初始化相同名称的属性。

     *note Example: 3483. 定义了以下属性。 它们由构造函数初始化，不应该
     被直接修改。

      -- 屬性: source

          一个包含该用例源码的字符串。 源码由一个 Python 语句组成，并且
          总是以换行结束；构造函数在必要时添加一个换行。

      -- 屬性: want

          运行这个用例的源码的预期输出（可以是 stdout ，也可以是异常情况
          下的回溯）。 *note want: 348f. 以一个换行符结束，除非没有预期
          的输出，在这种情况下它是一个空字符串。 构造函数在必要时添加一
          个换行。

      -- 屬性: exc_msg

          用例产生的异常信息，如果这个例子被期望产生一个异常；或者为
          ‘None’ ，如果它不被期望产生一个异常。 这个异常信息与 *note
          traceback.format_exception_only(): 3491. 的返回值进行比较。
          *note exc_msg: 3490. 以换行结束，除非是 ‘None’ 。

      -- 屬性: lineno

          包含本例的字符串中的行号，即本例的开始。 这个行号相对于包含字
          符串的开头来说是以零开始的。

      -- 屬性: indent

          用例在包含字符串中的缩进，即在用例的第一个提示前有多少个空格字
          符。

      -- 屬性: options

          一个从选项标志到 ‘True’ 或 ‘False’ 的字典映射，用于覆盖这个例
          子的默认选项。 任何不包含在这个字典中的选项标志都被保留为默认
          值（由 *note DocTestRunner: 3470. 的 ‘optionflags’ 指定）。默
          认情况下，没有选项被设置。


File: python.info,  Node: DocTestFinder 对象,  Next: DocTestParser 对象,  Prev: Example 对象,  Up: 高级 API

5.26.7.16 DocTestFinder 对象
............................

 -- 類別: doctest.DocTestFinder (verbose=False, parser=DocTestParser(),
          recurse=True, exclude_empty=True)

     一个处理类，用于从一个给定的对象的 docstring 和其包含的对象的
     docstring 中提取与之相关的 *note DocTest: 347f. 。 *note DocTest:
     347f. 可以从模块、类、函数、方法、静态方法、类方法和属性中提取。

     可选的参数 `verbose' 可以用来显示查找器搜索到的对象。 它的默认值是
     ‘False’ （无输出）。

     可选的参数 `parser' 指定了 *note DocTestParser: 3460. 对象（或一个
     可替换的对象），用于从文档串中提取 doctest 。

     如果可选的参数 `recurse' 是 False ，那么 *note
     DocTestFinder.find(): 3497. 将只检查给定的对象，而不是任何包含的对
     象。

     如果可选参数 `exclude_empty' 为 False ，那么 *note
     DocTestFinder.find(): 3497. 将包括对文档字符串为空的对象的测试。

     *note DocTestFinder: 347a. 定义了以下方法：

      -- 成員函式: find (obj[, name][, module][, globs][, extraglobs])

          返回 *note DocTest: 347f. 的列表，该列表由 `obj' 的文档串或其
          包含的任何对象的文档串定义。

          可选参数 `name' 指定了对象的名称；这个名称将被用来为返回的
          *note DocTest: 347f. 构建名称。 如果没有指定*name*，则使用
          ‘obj.__name__’ 。

          可选参数 `module' 是包含给定对象的模块。如果没有指定模块或者是
          ‘None’ ，那么测试查找器将试图自动确定正确的模块。 该对象被使用
          的模块：

             * 作为一个默认的命名空间，如果没有指定 `globs' 。

             * 为了防止 DocTestFinder 从其他模块导入的对象中提取 DocTest
               。 (包含有除 `module' 以外的模块的对象会被忽略)。

             * 找到包含该对象的文件名。

             * 找到该对象在其文件中的行号。

          如果 `module' 是 ‘False’ ，将不会试图找到这个模块。 这是不明确
          的，主要用于测试 doctest 本身：如果 `module' 是 ‘False’ ，或者
          是 ‘None’ 但不能自动找到，那么所有对象都被认为属于（不存在的）
          模块，所以所有包含的对象将（递归地）被搜索到 doctest 。

          每个 *note DocTest: 347f. 的 globals 是由 `globs' 和
          `extraglobs' 组合而成的（ `extraglobs' 的绑定覆盖 `globs' 的绑
          定）。 为每个 *note DocTest: 347f. 创建一个新的 globals 字典的
          浅层拷贝。如果没有指定 `globs' ，那么它默认为模块的 `__dict__'
          ，如果指定了或者为 ‘{}’ ，则除外。 如果没有指定 `extraglobs' ，
          那么它默认为 ‘{}’ 。


File: python.info,  Node: DocTestParser 对象,  Next: DocTestRunner 对象,  Prev: DocTestFinder 对象,  Up: 高级 API

5.26.7.17 DocTestParser 对象
............................

 -- 類別: doctest.DocTestParser

     一个处理类，用于从一个字符串中提取交互式的用例，并使用它们来创建一
     个 *note DocTest: 347f. 对象。

     *note DocTestParser: 3460. 定义了以下方法：

      -- 成員函式: get_doctest (string, globs, name, filename, lineno)

          从给定的字符串中提取所有的测试用例，并将它们收集到一个 *note
          DocTest: 347f. 对象中。

          `globs' 、 `name' 、 `filename' 和 `lineno' 是新的 *note
          DocTest: 347f. 对象的属性。 更多信息请参见 *note DocTest:
          347f. 的文档。

      -- 成員函式: get_examples (string, name='<string>')

          ä»ç»å®çå­ç¬¦ä¸²ä¸­æåææçæµè¯ç¨ä¾ï¼å¹¶ä»¥ *note Example: 3483.
          å¯¹è±¡åè¡¨çå½¢å¼è¿åã è¡æ°ä»¥ 0 ä¸ºåºç¡ã å¯éåæ° `name'
          æ¯è¯å«è¿ä¸ªå­ç¬¦ä¸²çåç§°ï¼åªç¨äºéè¯¯ä¿¡æ¯ã

      -- 成員函式: parse (string, name='<string>')

          å°ç»å®çå­ç¬¦ä¸²åæç¨ä¾åä¸­é´ææ¬ï¼å¹¶ä»¥ *note Example: 3483.
          åå­ç¬¦ä¸²äº¤æ¿çåè¡¨å½¢å¼è¿åã *note Example: 3483. çè¡å·ä»¥ 0
          ä¸ºåºç¡ã å¯éåæ° `name'
          æ¯è¯å«è¿ä¸ªå­ç¬¦ä¸²çåç§°ï¼åªç¨äºéè¯¯ä¿¡æ¯ã


File: python.info,  Node: DocTestRunner 对象,  Next: OutputChecker 对象,  Prev: DocTestParser 对象,  Up: 高级 API

5.26.7.18 DocTestRunner 对象
............................

 -- 類別: doctest.DocTestRunner (checker=None, verbose=None,
          optionflags=0)

     ä¸ä¸ªå¤çç±»ï¼ç¨äºæ§è¡åéªè¯ *note DocTest: 347f. ä¸­çäº¤äºå¼ç¨ä¾ã

     é¢æè¾åºåå®é è¾åºä¹é´çæ¯è¾æ¯ç±ä¸ä¸ª *note OutputChecker: 346f. å®æçã
     è¿ç§æ¯è¾å¯ä»¥ç¨ä¸äºéé¡¹æ å¿æ¥å®å¶ï¼æ´å¤ä¿¡æ¯è¯·ç *note 选项标记:
     929. é¨åã å¦æéé¡¹æ å¿ä¸å¤ï¼é£ä¹ä¹å¯ä»¥éè¿åæé å½æ°ä¼ é *note
     OutputChecker: 346f. çå­ç±»æ¥å®å¶æ¯è¾ã

     æµè¯è¿è¡å¨çæ¾ç¤ºè¾åºå¯ä»¥éè¿ä¸¤ç§æ¹å¼æ§å¶ãé¦å
     ï¼ä¸ä¸ªè¾åºå½æ°å¯ä»¥è¢«ä¼ éç» ‘TestRunner.run()’
     ï¼è¿ä¸ªå½æ°å°è¢«è°ç¨ï¼å¹¶æ¾ç¤ºåºåºè¯¥æ¾ç¤ºçå­ç¬¦ä¸²ã å®çé»è®¤å¼æ¯
     ‘sys.stdout.write’ ã å¦æåªæè·è¾åºæ¯ä¸å¤çï¼é£ä¹ä¹å¯ä»¥éè¿å­ç±»å
     DocTestRunner ï¼å¹¶éå *note report_start(): 349f. , *note
     report_success(): 34a0. , *note report_unexpected_exception():
     34a1. , å *note report_failure(): 34a2. æ¹æ³æ¥å®å¶æ¾ç¤ºè¾åºã

     å¯éçå ³é®å­åæ° `checker' æå®äº *note OutputChecker: 346f.
     å¯¹è±¡ï¼ææ¿æ¢ï¼ï¼å®åºè¯¥è¢«ç¨æ¥æ¯è¾é¢æè¾åºå doctest ç¨ä¾çå®é è¾åºã

     å¯éçå ³é®å­åæ° `verbose' æ§å¶ *note DocTestRunner: 3470.
     çè¯¦ç»ç¨åº¦ã å¦æ `verbose' æ¯ ‘True’
     ï¼é£ä¹æ¯ä¸ªç¨ä¾çä¿¡æ¯é½ä¼è¢«æå°åºæ¥ï¼å½å®æ­£å¨è¿è¡æ¶ã å¦æ
     `verbose*æ¯ ‘‘False‘‘ ï¼ååªæå°å¤±è´¥çä¿¡æ¯ã å¦æ *verbose'
     æ²¡ææå®ï¼æè ä¸º ‘None’ ï¼å¦æå½ä½¿ç¨äºå½ä»¤è¡å¼å ³ ‘-v’
     ï¼åä½¿ç¨verboseè¾åºã

     å¯éçå ³é®å­åæ° `optionflags'
     å¯ä»¥ç¨æ¥æ§å¶æµè¯è¿è¡å¨å¦ä½æ¯è¾é¢æè¾åºåå®é
     è¾åºï¼ä»¥åå¦ä½æ¾ç¤ºå¤±è´¥ãæ´å¤ä¿¡æ¯ï¼è¯·åè§ç« è *note 选项标记:
     929. ã

     *note DocTestParser: 3460. 定义了以下方法：

      -- 成員函式: report_start (out, test, example)

          报告测试运行器即将处理给定的用例。提供这个方法是为了让 *note
          DocTestRunner: 3470. 的子类能够定制他们的输出；它不应该被直接
          调用。

          `example' 是即将被处理的用。 `test' 是 `包含用例' 的测试。
          `out' 是传递给 *note DocTestRunner.run(): 34a3. 的输出函数。

      -- 成員函式: report_success (out, test, example, got)

          报告给定的例子运行成功。 提供这个方法是为了让 *note
          DocTestRunner: 3470. 的子类能够定制他们的输出；它不应该被直接
          调用。

          `example' 是即将被处理的用例。 `got' 是这个例子的实际输出。
          `test' 是包含 `example' 的测试。 `out' 是传递给 *note
          DocTestRunner.run(): 34a3. 的输出函数。

      -- 成員函式: report_failure (out, test, example, got)

          报告给定的用例运行失败。 提供这个方法是为了让 *note
          DocTestRunner: 3470. 的子类能够定制他们的输出；它不应该被直接
          调用。

          `example' 是即将被处理的用例。 `got' 是这个例子的实际输出。
          `test' 是包含 `example' 的测试。 `out' 是传递给 *note
          DocTestRunner.run(): 34a3. 的输出函数。

      -- 成員函式: report_unexpected_exception (out, test, example,
               exc_info)

          报告给定的用例触发了一个异常。 提供这个方法是为了让 *note
          DocTestRunner: 3470. 的子类能够定制他们的输出；它不应该被直接
          调用。

          `example' 是将要被处理的用例。 `exc_info' 是一个元组，包含关于
          异常的信息（如由 *note sys.exc_info(): d27. 返回）。 `test' 是
          包含 `example' 的测试。 `out' 是传递给 *note
          DocTestRunner.run(): 34a3. 的输出函数。

      -- 成員函式: run (test, compileflags=None, out=None,
               clear_globs=True)

          在 `test' （一个 *note DocTest: 347f. 对象）中运行这些用例，并
          使用写入函数 `out' 显示结果。

          这些用例都是在命名空间 ‘test.globs’ 中运行的。 如果
          `clear_globs' 为 True （默认），那么这个命名空间将在测试运行后
          被清除，以帮助进行垃圾回收。如果你想在测试完成后检查命名空间，
          那么使用 `clear_globs=False' 。

          `compileflags' 给出了 Python 编译器在运行例子时应该使用的标志
          集。如果没有指定，那么它将默认为适用于 `globs' 的
          future-import 标志集。

          每个用例的输出都使用 *note DocTestRunner: 3470. 的输出检查器进
          行检查，结果由 ‘DocTestRunner.report_*()’ 方法进行格式化。

      -- 成員函式: summarize (verbose=None)

          打印这个 DocTestRunner 运行过的所有测试用例的摘要，并返回一个
          *note named tuple: b7b. ‘TestResults(failed, attempted)’ 。

          可选的 `verbose' 参数控制摘要的详细程度。 如果没有指定 verbose
          ，那么将使用 *note DocTestRunner: 3470. 的 verbose 。


File: python.info,  Node: OutputChecker 对象,  Prev: DocTestRunner 对象,  Up: 高级 API

5.26.7.19 OutputChecker 对象
............................

 -- 類別: doctest.OutputChecker

     一个用于检查测试用例的实际输出是否与预期输出相匹配的类。 *note
     OutputChecker: 346f. 定义了两个方法： *note check_output(): 34a7. ，
     比较给定的一对输出，如果它们匹配则返回 ‘True’ ； *note
     output_difference(): 34a8. ，返回一个描述两个输出之间差异的字符串。

     *note OutputChecker: 346f. 定义了以下方法：

      -- 成員函式: check_output (want, got, optionflags)

          如果一个用例的实际输出（ `got' ）与预期输出（ `want' ）匹配，
          则返回 ‘True’ 。 如果这些字符串是相同的，总是被认为是匹配的；
          但是根据测试运行器使用的选项标志，也可能有几种非精确的匹配类型
          。 参见章节 *note 选项标记: 929. 了解更多关于选项标志的信息。

      -- 成員函式: output_difference (example, got, optionflags)

          返回一个字符串，描述给定用例（ `example' ）的预期输出和实际输
          出（ `got' ）之间的差异。 `optionflags' 是用于比较 `want' 和
          `got' 的选项标志集。


File: python.info,  Node: 调试,  Next: 肥皂盒,  Prev: 高级 API,  Up: doctest --- 测试交互性的Python示例

5.26.7.20 调试
..............

Doctest 提供了几种调试 doctest 用例的机制：

   * 有几个函数将测试转换为可执行的 Python 程序，这些程序可以在 Python 调
     试器， *note pdb: c9. 下运行。

   * *note DebugRunner: 34ab. 类是 *note DocTestRunner: 3470. 的一个子类
     ，它为第一个失败的用例触发一个异常，包含关于这个用例的信息。这些信
     息可以用来对这个用例进行事后调试。

   * 由 *note DocTestSuite(): 7c0. 生成的 *note unittest: 124. 用例支持
     由 *note unittest.TestCase: 9e5. 定义的 *note debug(): 34ac. 方法，
     。

   * 你可以在 doctest 的用例中加入对 *note pdb.set_trace(): 4c8. 的调用
     ，当这一行被执行时，你会进入 Python 调试器。 然后你可以检查变量的当
     前值，等等。 例如，假设 ‘a.py’ 只包含这个模块 docstring

          """
          >>> def f(x):
          ...     g(x*2)
          >>> def g(x):
          ...     print(x+3)
          ...     import pdb; pdb.set_trace()
          >>> f(3)
          9
          """

     那么一个交互式Python会话可能是这样的:

          >>> 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)
          >>>

将测试转换为 Python 代码的函数，并可能在调试器下运行合成的代码:

 -- 函式: doctest.script_from_examples (s)

     将带有用例的文本转换为脚本。

     参数 `s' 是一个包含测试用例的字符串。 该字符串被转换为 Python 脚本
     ，其中 `s' 中的 doctest 用例被转换为常规代码，其他的都被转换为
     Python 注释。 生成的脚本将以字符串的形式返回。例如，

          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
          """))

     显示:

          # Set x and y to 1 and 2.
          x, y = 1, 2
          #
          # Print their sum:
          print(x+y)
          # Expected:
          ## 3

     这个函数在内部被其他函数使用（见下文），但当你想把一个交互式 Python
     会话转化为 Python 脚本时，也会很有用。

 -- 函式: doctest.testsource (module, name)

     将一个对象的 doctest 转换为一个脚本。

     参数 `module' 是一个模块对象，或者一个模块带点的名称，包含对其
     doctest 感兴趣的对象。 参数 `name' 是具有感兴趣的测试的对象的名称（
     在模块中）。 结果是一个字符串，包含该对象的文本串转换为 Python 脚本
     ，如上面 *note script_from_examples(): 34ad. 所述。 例如，如果模块
     ‘a.py’ 包含一个顶级函数 ‘f()’ ，那么

          import a, doctest
          print(doctest.testsource(a, "a.f"))

     打印函数 ‘f()’ 的文档串的脚本版本，将测试转换为代码，其余部分放在注
     释中。

 -- 函式: doctest.debug (module, name, pm=False)

     对一个对象的 doctest 进行调试。

     `module' 和 `name' 参数与上面函数 *note testsource(): 34ae. 的参数
     相同。 被命名对象的文本串的合成 Python 脚本被写入一个临时文件，然后
     该文件在 Python 调试器 *note pdb: c9. 的控制下运行。

     ‘module.__dict__’ 的一个浅层拷贝被用于本地和全局的执行环境。

     可选参数 `pm' 控制是否使用事后调试。 如果 `pm' 为 True ，则直接运行
     脚本文件，只有当脚本通过引发一个未处理的异常而终止时，调试器才会介
     入。如果是这样，就会通过 *note pdb.post_mortem(): e0a. 调用事后调试
     ，并传递未处理异常的跟踪对象。如果没有指定 `pm' ，或者是 False ，脚
     本将从一开始就在调试器下运行，通过传递一个适当的 *note exec(): d0c.
     调用给 *note pdb.run(): 34af. 。

 -- 函式: doctest.debug_src (src, pm=False, globs=None)

     在一个字符串中调试 doctest 。

     这就像上面的函数 *note debug(): 34ac. ，只是通过 `src' 参数，直接指
     定一个包含测试用例的字符串。

     可选参数 `pm' 的含义与上述函数 *note debug(): 34ac. 的含义相同。

     可选的参数 `globs' 给出了一个字典，作为本地和全局的执行环境。 如果
     没有指定，或者为 ‘None’ ，则使用一个空的字典。如果指定，则使用字典
     的浅层拷贝。

*note DebugRunner: 34ab. 类，以及它可能触发的特殊异常，是测试框架作者最
感兴趣的，在此仅作简要介绍。请看源代码，特别是 *note DebugRunner: 34ab.
的文档串（这是一个测试！）以了解更多细节。

 -- 類別: doctest.DebugRunner (checker=None, verbose=None,
          optionflags=0)

     *note DocTestRunner: 3470. 的一个子类，一旦遇到失败，就会触发一个异
     常。 如果一个意外的异常发生，就会引发一个 *note
     UnexpectedException: 34b1. 异常，包含测试、用例和原始异常。 如果输
     出不匹配，那么就会引发一个 *note DocTestFailure: 34b2. 异常，包含测
     试、用例和实际输出。

     关于构造函数参数和方法的信息，请参见 *note DocTestRunner: 3470. 部
     分的文档 *note 高级 API: 3482. 。

*note DebugRunner: 34ab. 实例可能会触发两种异常。

 -- 例外: doctest.DocTestFailure (test, example, got)

     *note DocTestRunner: 3470. 触发的异常，表示一个 doctest 用例的实际
     输出与预期输出不一致。构造函数参数被用来初始化相同名称的属性。

*note DocTestFailure: 34b2. 定义了以下属性:

 -- 屬性: DocTestFailure.test

     当该用例失败时正在运行的 *note DocTest: 347f. 对象。

 -- 屬性: DocTestFailure.example

     失败的 *note Example: 3483. 。

 -- 屬性: DocTestFailure.got

     用例的实际输出。

 -- 例外: doctest.UnexpectedException (test, example, exc_info)

     一个由 *note DocTestRunner: 3470. 触发的异常，以提示一个 doctest 用
     例引发了一个意外的异常。 构造函数参数被用来初始化相同名称的属性。

*note UnexpectedException: 34b1. 定义了以下属性:

 -- 屬性: UnexpectedException.test

     当该用例失败时正在运行的 *note DocTest: 347f. 对象。

 -- 屬性: UnexpectedException.example

     失败的 *note Example: 3483. 。

 -- 屬性: UnexpectedException.exc_info

     一个包含意外异常信息的元组，由 ‘sys.ex_info()’ 返回。


File: python.info,  Node: 肥皂盒,  Prev: 调试,  Up: doctest --- 测试交互性的Python示例

5.26.7.21 肥皂盒
................

正如介绍中提到的， *note doctest: 66. 已经发展到有三个主要用途:

  1. 检查 docstring 中的用例。

  2. 回归测试

  3. 可执行的文档/文字测试。

这些用途有不同的要求，区分它们是很重要的。特别是，用晦涩难懂的测试用例来
填充你的文档字符串会使文档变得很糟糕。

在编写文档串时，要谨慎地选择文档串的用例。这是一门需要学习的艺术——一开始
可能并不自然。用例应该为文档增加真正的价值。 一个好的用例往往可以抵得上
许多文字。如果用心去做，这些用例对你的用户来说是非常有价值的，而且随着时
间的推移和事情的变化，收集这些用例所花费的时间也会得到很多倍的回报。 我
仍然惊讶于我的 *note doctest: 66. 用例在一个“无害”的变化后停止工作。

Doctest 也是回归测试的一个很好的工具，特别是如果你不吝啬解释的文字。 通
过交错的文本和用例，可以更容易地跟踪真正的测试，以及为什么。当测试失败时
，好的文本可以使你更容易弄清问题所在，以及如何解决。 的确，你可以在基于
代码的测试中写大量的注释，但很少有程序员这样做。许多人发现，使用 doctest
方法反而能使测试更加清晰。 也许这只是因为 doctest 使写散文比写代码容易一
些，而在代码中写注释则有点困难。 我认为它比这更深入：当写一个基于
doctest 的测试时，自然的态度是你想解释你的软件的细微之处，并用例子来说明
它们。这反过来又自然地导致了测试文件从最简单的功能开始，然后逻辑地发展到
复杂和边缘案例。 一个连贯的叙述是结果，而不是一个孤立的函数集合，似乎是
随机的测试孤立的功能位。 这是一种不同的态度，产生不同的结果，模糊了测试
和解释之间的区别。

回归测试最好限制在专用对象或文件中。 有几种组织测试的选择：

   * 编写包含测试案例的文本文件作为交互式例子，并使用 *note testfile():
     3457. 或 *note DocFileSuite(): 347e. 来测试这些文件。 建议这样做，
     尽管对于新的项目来说是最容易做到的，从一开始就设计成使用 doctest 。

   * 定义命名为 ‘_regrtest_topic’ 的函数，由单个文档串组成，包含命名主题
     的测试用例。 这些函数可以包含在与模块相同的文件中，或分离出来成为一
     个单独的测试文件。

   * 定义一个从回归测试主题到包含测试用例的文档串的 ‘__test__’ 字典映射
     。

当你把你的测试放在一个模块中时，这个模块本身就可以成为测试运行器。 当一
个测试失败时，你可以安排你的测试运行器只重新运行失败的测试，同时调试问题
。 下面是这样一个测试运行器的最小例子:

     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))

註解
....


File: python.info,  Node: unittest --- 單元測試框架,  Next: unittest mock --- mock对象库,  Prev: doctest --- 测试交互性的Python示例,  Up: 開發工具

5.26.8 ‘unittest’ — 單元測試框架
--------------------------------

`源代码：' Lib/unittest/__init__.py(1)

__________________________________________________________________

（假如你已經熟悉相關基礎的測試概念，你可能會希望跳過以下段落，直接參考
*note assert 方法清單: 34bd.。）

*note unittest: 124. 原生的單元測試框架最初由 JUnit 開發，和其他程式語言
相似有主要的單元測試框架。支援自動化測試，對測試分享安裝與關閉程式碼，集
合所有匯總的測試，並且獨立各個測試報告框架。

*note unittest: 124. 用來作為實現支援一些重要的物件導向方法的概念。

test fixture

     `test fixture' 表示为了开展一项或多项测试所需要进行的准备工作，以及
     所有相关的清理操作。举个例子，这可能包含创建临时或代理的数据库、目
     录，再或者启动一个服务器进程。

test case（測試用例）

     一個 `test case' 是一個獨立的單元測試。這是用來確認一個特定設定的輸
     入的特殊回饋。 *note unittest: 124. 提供一個基礎類別，類別 *note
     TestCase: 9e5.，可以用來建立一個新的測試條例。

test suite（測試套件）

     `test suite' 是一個搜集測試條例，測試套件，或是兩者皆有。它需要一起
     被執行並用來匯總測試。

test runner（測試執行器）

     `test runner' 是一個編排測試執行與提供結果給使用者的一個元件。執行
     器可以使用圖形化介面，文字介面或是回傳一個特別值用來標示出執行測試
     的結果。

也參考
......

*note doctest: 66. 模組

     另一個執行測試的模組，但使用不一樣的測試方法與規範。

Simple Smalltalk Testing: With Patterns(2)

     Kent Beck 的原始論文討論使用 *note unittest: 124. 這樣模式的測試框
     架。

pytest(3)

     第三方单元测试框架，提供轻量化的语法来编写测试，例如：‘assert
     func(10) == 42’。

The Python Testing Tools Taxonomy(4)

     一份詳細的 Python 測試工具列表，包含 functional testing 框架和mock
     object 函式庫。

Testing in Python Mailing List(5)

     一個專門興趣的群組用來討論 Python 中的測試方式與測試工具。

随 Python 源代码分发的脚本 ‘Tools/unittestgui/unittestgui.py’ 是一个一个
用于发现和执行测试的用户图形界面工具。这主要是为了方便新手使用单元测试制
作的。在生产环境中，测试应由一个持续集成（CI）系统运行，如 Buildbot(6),
Jenkins(7) ，Travis-CI(8), 或 AppVeyor(9)。

* Menu:

* 簡單範例::
* 命令執行列介面 (Command-Line Interface): 命令執行列介面 Command-Line Interface.
* Test Discovery（測試探索）::
* 组织你的测试代码::
* 复用已有的测试代码::
* 跳过测试与预计的失败::
* Distinguishing test iterations using subtests::
* 类与函数::
* Class and Module Fixtures::
* 信号处理::

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/Lib/unittest/__init__.py

   (2) 
https://web.archive.org/web/20150315073817/http://www.xprogramming.com/testfram.htm

   (3) https://docs.pytest.org/

   (4) https://wiki.python.org/moin/PythonTestingToolsTaxonomy

   (5) http://lists.idyll.org/listinfo/testing-in-python

   (6) https://buildbot.net/

   (7) https://jenkins.io/

   (8) https://travis-ci.com

   (9) https://www.appveyor.com/


File: python.info,  Node: 簡單範例,  Next: 命令執行列介面 Command-Line Interface,  Up: unittest --- 單元測試框架

5.26.8.1 簡單範例
.................

*note unittest: 124. 模組提供一系列豐富的工具用來建構與執行測試。本節將
展示這一系列工具中一部份，它們已能滿足大部份使用者需求。

這是一段簡短的腳本用來測試 3 個字串方法：

     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()

測試用例 (testcase) 可以透過繼承 *note unittest.TestCase: 9e5. 類別來建
立。這裡定義了三個獨立的物件方法，名稱皆以 ‘test’ 開頭。這樣的命名方式能
告知 test runner 哪些物件方法為定義的測試。

每個測試的關鍵為呼叫 *note assertEqual(): c85. 來確認是否為期望的結果；
*note assertTrue(): c84. 或是 *note assertFalse(): d8f. 用來驗證一個條件
式； *note assertRaises(): b92. 用來驗證是否觸發一個特定的 exception。使
用這些物件方法來取代 *note assert: 23f. 陳述句，將能使 test runner 收集
所有的測試結果並產生一個報表。

通过 *note setUp(): d93. 和 *note tearDown(): d94. 方法，可以设置测试开
始前与完成后需要执行的指令。 在 *note 组织你的测试代码: 34c0. 中，对此有
更为详细的描述。

最後將顯示一個簡單的方法去執行測試 *note unittest.main(): 9e8. 提供一個
命令執行列介面測試腳本。當透過命令執行列執行，輸出結果將會像是：

     ...
     ----------------------------------------------------------------------
     Ran 3 tests in 0.000s

     OK

在測試時加入 ‘-v’ 選項將指示 *note unittest.main(): 9e8. 提高 verbosity
層級，產生以下的輸出：

     test_isupper (__main__.TestStringMethods) ... ok
     test_split (__main__.TestStringMethods) ... ok
     test_upper (__main__.TestStringMethods) ... ok

     ----------------------------------------------------------------------
     Ran 3 tests in 0.001s

     OK

以上的例子顯示大多數使用 *note unittest: 124. 特徵足以滿足大多數日常測試
的需求。接下來第一部分文件的剩餘部分將繼續探索完整特徵設定。


File: python.info,  Node: 命令執行列介面 Command-Line Interface,  Next: Test Discovery（測試探索）,  Prev: 簡單範例,  Up: unittest --- 單元測試框架

5.26.8.2 命令執行列介面 (Command-Line Interface)
................................................

單元測試模組可以透過命令執行列執行測試模組，物件甚至個別的測試方法：

     python -m unittest test_module1 test_module2
     python -m unittest test_module.TestClass
     python -m unittest test_module.TestClass.test_method

你可以通過一個串列與任何模組名稱的組合，完全符合類別與方法的名稱。

測試模組可以根據檔案路徑指定：

     python -m unittest tests/test_something.py

這允許你使用 shell 檔案名稱補完功能 (filename completion) 來指定測試模組
。給定的檔案路徑必須亦能被當作模組 import。此路徑轉換為模組名稱的方式為
移除 ’.py’ 並將路徑分隔符 (path separator) 轉換成 ’.’。 假如你的測試檔案
無法被 import 成模組，你應該直接執行該測試檔案。

通過增加 -v 的旗標數，可以在你執行測試時得到更多細節（更高的 verbosity）
：

     python -m unittest -v test_module

若執行時不代任何引數，將執行 *note Test Discovery（測試探索）: 34c3.：

     python -m unittest

列出所有命令列選項：

     python -m unittest -h

3.2 版更變: 在早期的版本可以個別執行測試方法和不需要模組或是類別。

* Menu:

* 命令列模式選項::


File: python.info,  Node: 命令列模式選項,  Up: 命令執行列介面 Command-Line Interface

5.26.8.3 命令列模式選項
.......................

‘unittest’ supports these command-line options:

 -- 程式選項: -b, --buffer

     Standard output 與 standard error stream 將在測試執行被緩衝
     (buffer)。這些輸出在測試通過時被丟棄。若是測試錯誤或失則，這些輸出
     將會正常地被印出，並且被加入至錯誤訊息中。

 -- 程式選項: -c, --catch

     ‘Control-C’ 測試執行過程中等待正確的測試結果並回報目前為止所有的測
     試結果。第二個 ‘Control-C’ 拋出一般例外 *note KeyboardInterrupt:
     2cc.。

     參照 *note Signal Handling: 34c5. 針對函式提供的功能。

 -- 程式選項: -f, --failfast

     在第一次錯誤或是失敗停止執行測試。

 -- 程式選項: -k

     Only run test methods and classes that match the pattern or
     substring.  This option may be used multiple times, in which case
     all test cases that match any of the given patterns are included.

     包含通配符（*）的模式使用 *note fnmatch.fnmatchcase(): 1dd9. 对测试
     名称进行匹配。另外，该匹配是大小写敏感的。

     模式对测试加载器导入的测试方法全名进行匹配。

     例如，‘-k foo’ 可以匹配到 ‘foo_tests.SomeTest.test_something’ 和
     ‘bar_tests.SomeTest.test_foo’ ，但是不能匹配到
     ‘bar_tests.FooTest.test_something’ 。

 -- 程式選項: --locals

     透過 traceback 顯示本地變數。

3.2 版新加入: 增加命令列模式選項 ‘-b’ 、 ‘-c’ 與 ‘-f’。

3.5 版新加入: 命令列選項 ‘--locals’。

3.7 版新加入: 命令行选项 ‘-k’ 。

對執行所有的專案或是一個子集合測試，命令列模式可以可以被用來做測試探索。


File: python.info,  Node: Test Discovery（測試探索）,  Next: 组织你的测试代码,  Prev: 命令執行列介面 Command-Line Interface,  Up: unittest --- 單元測試框架

5.26.8.4 Test Discovery（測試探索）
...................................

3.2 版新加入.

單元測試支援簡單的 test discovery（測試探索）。為了相容於測試探索，所有
的測試檔案都要是*note 模組: 13b1.或是*note 套件: 13be.（包含 *note
namespace packages: 15ee.），並能從專案的最上層目錄中 import（代表它們的
檔案名稱必須是有效的 *note identifiers: 1505.）。

Test discovery（測試探索）實作在 *note TestLoader.discover(): 9ea.，但也
可以被用於命令列模式。基本的命令列模式用法如下：

     cd project_directory
     python -m unittest discover

     備註: ‘python -m unittest’ 作為捷徑，其功能相當於 ‘python -m
     unittest discover’。假如你想傳遞引數至探索測試的話，一定要明確地加
     入 ‘discover’ 子指令。

‘discover’ 子指令有以下幾個選項：

 -- 程式選項: -v, --verbose

     詳細（verbose）輸出

 -- 程式選項: -s, --start-directory directory

     開始尋找的資料夾（預設為 ‘.’）

 -- 程式選項: -p, --pattern pattern

     匹配測試檔案的模式（預設為 ‘test*.py’）

 -- 程式選項: -t, --top-level-directory directory

     專案的最高階層目錄 (defaults to start directory)

*note -s: 34ca, *note -p: 34cb, 和 *note -t: 34cc. 選項依照傳遞位置作為
引數排序順序。以下兩個命令列被視為等價:

     python -m unittest discover -s project_directory -p "*_test.py"
     python -m unittest discover project_directory "*_test.py"

正如可以传入路径那样，传入一个包名作为起始目录也是可行的，如
‘myproject.subpackage.test’ 。你提供的包名会被导入，它在文件系统中的位置
会被作为起始目录。

     警示: 探索性测试通过导入测试对测试进行加载。在找到所有你指定的开始
     目录下的所有测试文件后，它把路径转换为包名并进行导入。如
     ‘foo/bar/baz.py’ 会被导入为 ‘foo.bar.baz’ 。

     如果你有一个全局安装的包，并尝试对这个包的副本进行探索性测试，可能
     会从错误的地方开始导入。如果出现这种情况，测试会输出警告并退出。

     如果你使用包名而不是路径作为开始目录，搜索时会假定它导入的是你想要
     的目录，所以你不会收到警告。

测试模块和包可以通过 *note load_tests protocol: 34cd. 自定义测试的加载和
搜索。

3.4 版更變: 测试发现支持初始目录下的 *note 命名空间包: 15ee.。注意你也需
要指定顶层目录（例如：‘python -m unittest discover -s root/namespace -t
root’）。


File: python.info,  Node: 组织你的测试代码,  Next: 复用已有的测试代码,  Prev: Test Discovery（測試探索）,  Up: unittest --- 單元測試框架

5.26.8.5 组织你的测试代码
.........................

单元测试的构建单位是 `test cases' ：独立的、包含执行条件与正确性检查的方
案。在 *note unittest: 124. 中，测试用例表示为 *note unittest.TestCase:
9e5. 的实例。通过编写 *note TestCase: 9e5. 的子类或使用 *note
FunctionTestCase: 34cf. 编写你自己的测试用例。

一个 *note TestCase: 9e5. 实例的测试代码必须是完全自含的，因此它可以独立
运行，或与其它任意组合任意数量的测试用例一起运行。

*note TestCase: 9e5. 的最简单的子类需要实现一个测试方法（例如一个命名以
‘test’ 开头的方法）以执行特定的测试代码：

     import unittest

     class DefaultWidgetSizeTestCase(unittest.TestCase):
         def test_default_widget_size(self):
             widget = Widget('The widget')
             self.assertEqual(widget.size(), (50, 50))

可以看到，为了进行测试，我们使用了基类 *note TestCase: 9e5. 提供的其中一
个 ‘assert*()’ 方法。若测试不通过，将会引发一个带有说明信息的异常，并且
*note unittest: 124. 会将这个测试用例标记为测试不通过。任何其它类型的异
常将会被当做错误处理。

可能同时存在多个前置操作相同的测试，我们可以把测试的前置操作从测试代码中
拆解出来，并实现测试前置方法 *note setUp(): d93. 。在运行测试时，测试框
架会自动地为每个单独测试调用前置方法。

     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')

     備註: 多个测试运行的顺序由内置字符串排序方法对测试名进行排序的结果
     决定。

在测试运行时，若 *note setUp(): d93. 方法引发异常，测试框架会认为测试发
生了错误，因此测试方法不会被运行。

相似的，我们提供了一个 *note tearDown(): d94. 方法在测试方法运行后进行清
理工作。

     import unittest

     class WidgetTestCase(unittest.TestCase):
         def setUp(self):
             self.widget = Widget('The widget')

         def tearDown(self):
             self.widget.dispose()

若 *note setUp(): d93. 成功运行，无论测试方法是否成功，都会运行 *note
tearDown(): d94. 。

这样的一个测试代码运行的环境被称为 `test fixture' 。一个新的 TestCase 实
例作为一个测试脚手架，用于运行各个独立的测试方法。在运行每个测试时，
*note setUp(): d93. 、*note tearDown(): d94. 和 ‘__init__()’ 会被调用一
次。

推荐你根据用例所测试的功能将测试用 TestCase 分组。*note unittest: 124. 为
此提供了 `test suite'：*note unittest: 124. 的 *note TestSuite: 7c1. 类
是一个代表。通常情况下，调用 *note unittest.main(): 9e8. 就能正确地找到
并执行这个模块下所有用 TestCase 分组的测试。

然而，如果你需要自定义你的测试套件的话，你可以参考以下方法组织你的测试：

     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())

你可以把测试用例和测试套件放在与被测试代码相同的模块中（比如
‘widget.py’），但将测试代码放在单独的模块中（比如 ‘test_widget.py’）有几
个优势。

   * 测试模块可以从命令行被独立调用。

   * 更容易在分发的代码中剥离测试代码。

   * 降低没有好理由的情况下修改测试代码以通过测试的诱惑。

   * 测试代码应比被测试代码更少地被修改。

   * 被测试代码可以更容易地被重构。

   * 对用 C 语言写成的模块无论如何都得单独写成一个模块，为什么不保持一致
     呢？

   * 如果测试策略发生了改变，没有必要修改源代码。


File: python.info,  Node: 复用已有的测试代码,  Next: 跳过测试与预计的失败,  Prev: 组织你的测试代码,  Up: unittest --- 單元測試框架

5.26.8.6 复用已有的测试代码
...........................

一些用户希望直接使用 *note unittest: 124. 运行已有的测试代码，而不需要把
已有的每个测试函数转化为一个 *note TestCase: 9e5. 的子类。

因此， *note unittest: 124. 提供 *note FunctionTestCase: 34cf. 类。这个
*note TestCase: 9e5. 的子类可用于打包已有的测试函数，并支持设置前置与后
置函数。

假定有一个测试函数：

     def testSomething():
         something = makeSomething()
         assert something.name is not None
         # ...

可以创建等价的测试用例如下，其中前置和后置方法是可选的。

     testcase = unittest.FunctionTestCase(testSomething,
                                          setUp=makeSomethingDB,
                                          tearDown=deleteSomethingDB)

     備註: 用 *note FunctionTestCase: 34cf. 可以快速将现有的测试转换成基
     于 *note unittest: 124. 的测试，但不推荐你这样做。花点时间继承
     *note TestCase: 9e5. 会让以后重构测试无比轻松。

在某些情况下，现有的测试可能是用 *note doctest: 66. 模块编写的。 如果是
这样， *note doctest: 66. 提供了一个 ‘DocTestSuite’ 类，可以从现有基于
*note doctest: 66. 的测试中自动构建 *note unittest.TestSuite: 7c1. 用例
。


File: python.info,  Node: 跳过测试与预计的失败,  Next: Distinguishing test iterations using subtests,  Prev: 复用已有的测试代码,  Up: unittest --- 單元測試框架

5.26.8.7 跳过测试与预计的失败
.............................

3.1 版新加入.

Unittest 支持跳过单个或整组的测试用例。它还支持把测试标注成“预期失败”的
测试，这些坏测试会失败，但不会算进 *note TestResult: b97. 的失败里。

Skipping a test is simply a matter of using the *note skip(): 10e5.
*note decorator: 174. or one of its conditional variants, calling *note
TestCase.skipTest(): 34d4. within a *note setUp(): d93. or test method,
or raising *note SkipTest: 9e9. directly.

跳过测试的基本用法如下:

     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

在啰嗦模式下运行以上测试例子时，程序输出如下：

     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)

跳过测试类的写法跟跳过测试方法的写法相似:

     @unittest.skip("showing class skipping")
     class MySkippedTestCase(unittest.TestCase):
         def test_not_run(self):
             pass

*note TestCase.setUp(): d93. 也可以跳过测试。可以用于所需资源不可用的情
况下跳过接下来的测试。

使用 *note expectedFailure(): 34d5. 装饰器表明这个测试预计失败。:

     class ExpectedFailureTestCase(unittest.TestCase):
         @unittest.expectedFailure
         def test_fail(self):
             self.assertEqual(1, 0, "broken")

It’s easy to roll your own skipping decorators by making a decorator
that calls *note skip(): 10e5. on the test when it wants it to be
skipped.  This decorator skips the test unless the passed object has a
certain attribute:

     def skipUnlessHasattr(obj, attr):
         if hasattr(obj, attr):
             return lambda func: func
         return unittest.skip("{!r} doesn't have {!r}".format(obj, attr))

以下的装饰器和异常实现了跳过测试和预期失败两种功能：

 -- 函式: @unittest.skip (reason)

     跳过被此装饰器装饰的测试。 `reason' 为测试被跳过的原因。

 -- 函式: @unittest.skipIf (condition, reason)

     当 `condition' 为真时，跳过被装饰的测试。

 -- 函式: @unittest.skipUnless (condition, reason)

     跳过被装饰的测试，除非 `condition' 为真。

 -- 函式: @unittest.expectedFailure

     Mark the test as an expected failure or error.  If the test fails
     or errors in the test function itself (rather than in one of the
     `test fixture' methods) then it will be considered a success.  If
     the test passes, it will be considered a failure.

 -- 例外: unittest.SkipTest (reason)

     引发此异常以跳过一个测试。

     通常来说，你可以使用 *note TestCase.skipTest(): 34d4. 或其中一个跳
     过测试的装饰器实现跳过测试的功能，而不是直接引发此异常。

被跳过的测试的 *note setUp(): d93. 和 *note tearDown(): d94. 不会被运行
。被跳过的类的 *note setUpClass(): 376. 和 *note tearDownClass(): d91. 不
会被运行。被跳过的模组的 ‘setUpModule()’ 和 ‘tearDownModule()’ 不会被运
行。


File: python.info,  Node: Distinguishing test iterations using subtests,  Next: 类与函数,  Prev: 跳过测试与预计的失败,  Up: unittest --- 單元測試框架

5.26.8.8 Distinguishing test iterations using subtests
......................................................

3.4 版新加入.

When there are very small differences among your tests, for instance
some parameters, unittest allows you to distinguish them inside the body
of a test method using the *note subTest(): 9e6. context manager.

例如，以下测试:

     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)

可以得到以下输出:

     ======================================================================
     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

如果不使用子测试，程序遇到第一次错误之后就会停止。而且因为‘‘i‘‘的值不显
示，错误也更难找。

     ======================================================================
     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


File: python.info,  Node: 类与函数,  Next: Class and Module Fixtures,  Prev: Distinguishing test iterations using subtests,  Up: unittest --- 單元測試框架

5.26.8.9 类与函数
.................

本节深入介绍了 *note unittest: 124. 的 API。

* Menu:

* 测试用例::
* Grouping tests::
* Loading and running tests::


File: python.info,  Node: 测试用例,  Next: Grouping tests,  Up: 类与函数

5.26.8.10 测试用例
..................

 -- 類別: unittest.TestCase (methodName='runTest')

     Instances of the *note TestCase: 9e5. class represent the logical
     test units in the *note unittest: 124. universe.  This class is
     intended to be used as a base class, with specific tests being
     implemented by concrete subclasses.  This class implements the
     interface needed by the test runner to allow it to drive the tests,
     and methods that the test code can use to check for and report
     various kinds of failure.

     Each instance of *note TestCase: 9e5. will run a single base
     method: the method named `methodName'.  In most uses of *note
     TestCase: 9e5, you will neither change the `methodName' nor
     reimplement the default ‘runTest()’ method.

     3.2 版更變: *note TestCase: 9e5. can be instantiated successfully
     without providing a `methodName'.  This makes it easier to
     experiment with *note TestCase: 9e5. from the interactive
     interpreter.

     *note TestCase: 9e5. instances provide three groups of methods: one
     group used to run the test, another used by the test implementation
     to check conditions and report failures, and some inquiry methods
     allowing information about the test itself to be gathered.

     第一组（用于运行测试的）方法是：

      -- 成員函式: setUp ()

          Method called to prepare the test fixture.  This is called
          immediately before calling the test method; other than *note
          AssertionError: 240. or *note SkipTest: 9e9, any exception
          raised by this method will be considered an error rather than
          a test failure.  The default implementation does nothing.

      -- 成員函式: tearDown ()

          Method called immediately after the test method has been
          called and the result recorded.  This is called even if the
          test method raised an exception, so the implementation in
          subclasses may need to be particularly careful about checking
          internal state.  Any exception, other than *note
          AssertionError: 240. or *note SkipTest: 9e9, raised by this
          method will be considered an additional error rather than a
          test failure (thus increasing the total number of reported
          errors).  This method will only be called if the *note
          setUp(): d93. succeeds, regardless of the outcome of the test
          method.  The default implementation does nothing.

      -- 成員函式: setUpClass ()

          A class method called before tests in an individual class are
          run.  ‘setUpClass’ is called with the class as the only
          argument and must be decorated as a *note classmethod(): 309.:

               @classmethod
               def setUpClass(cls):
                   ...

          查看 *note Class and Module Fixtures: 34dd. 获取更详细的说明。

          3.2 版新加入.

      -- 成員函式: tearDownClass ()

          A class method called after tests in an individual class have
          run.  ‘tearDownClass’ is called with the class as the only
          argument and must be decorated as a *note classmethod(): 309.:

               @classmethod
               def tearDownClass(cls):
                   ...

          查看 *note Class and Module Fixtures: 34dd. 获取更详细的说明。

          3.2 版新加入.

      -- 成員函式: run (result=None)

          Run the test, collecting the result into the *note TestResult:
          b97. object passed as `result'.  If `result' is omitted or
          ‘None’, a temporary result object is created (by calling the
          *note defaultTestResult(): 34de. method) and used.  The result
          object is returned to *note run(): b96.’s caller.

          The same effect may be had by simply calling the *note
          TestCase: 9e5. instance.

          3.3 版更變: Previous versions of ‘run’ did not return the
          result.  Neither did calling an instance.

      -- 成員函式: skipTest (reason)

          Calling this during a test method or *note setUp(): d93. skips
          the current test.  See *note 跳过测试与预计的失败: 34d3. for
          more information.

          3.1 版新加入.

      -- 成員函式: subTest (msg=None, **params)

          Return a context manager which executes the enclosed code
          block as a subtest.  `msg' and `params' are optional,
          arbitrary values which are displayed whenever a subtest fails,
          allowing you to identify them clearly.

          A test case can contain any number of subtest declarations,
          and they can be arbitrarily nested.

          查看 *note Distinguishing test iterations using subtests: 9e7.
          获取更详细的信息。

          3.4 版新加入.

      -- 成員函式: debug ()

          Run the test without collecting the result.  This allows
          exceptions raised by the test to be propagated to the caller,
          and can be used to support running tests under a debugger.
     The *note TestCase: 9e5. class provides several assert methods to
     check for and report failures.  The following table lists the most
     commonly used methods (see the tables below for more assert
     methods):

     Method                                        Checks that                       New in
                                                                                     
     ----------------------------------------------------------------------------------------------------
                                                                                     
     *note assertEqual(a, b): c85.                 ‘a == b’
                                                   
                                                                                     
     *note assertNotEqual(a, b): c86.              ‘a != b’
                                                   
                                                                                     
     *note assertTrue(x): c84.                     ‘bool(x) is True’
                                                   
                                                                                     
     *note assertFalse(x): d8f.                    ‘bool(x) is False’
                                                   
                                                                                     
     *note assertIs(a, b): d97.                    ‘a is b’                          3.1
                                                                                     
                                                                                     
     *note assertIsNot(a, b): d98.                 ‘a is not b’                      3.1
                                                                                     
                                                                                     
     *note assertIsNone(x): d95.                   ‘x is None’                       3.1
                                                                                     
                                                                                     
     *note assertIsNotNone(x): d96.                ‘x is not None’                   3.1
                                                                                     
                                                                                     
     *note assertIn(a, b): da0.                    ‘a in b’                          3.1
                                                                                     
                                                                                     
     *note assertNotIn(a, b): da1.                 ‘a not in b’                      3.1
                                                                                     
                                                                                     
     *note assertIsInstance(a, b): d99.            ‘isinstance(a, b)’                3.2
                                                                                     
                                                                                     
     *note assertNotIsInstance(a, b): d9a.         ‘not isinstance(a, b)’            3.2
                                                                                     

     All the assert methods accept a `msg' argument that, if specified,
     is used as the error message on failure (see also *note
     longMessage: d90.).  Note that the `msg' keyword argument can be
     passed to *note assertRaises(): b92, *note assertRaisesRegex():
     b93, *note assertWarns(): b94, *note assertWarnsRegex(): b95. only
     when they are used as a context manager.

      -- 成員函式: assertEqual (first, second, msg=None)

          Test that `first' and `second' are equal.  If the values do
          not compare equal, the test will fail.

          In addition, if `first' and `second' are the exact same type
          and one of list, tuple, dict, set, frozenset or str or any
          type that a subclass registers with *note
          addTypeEqualityFunc(): da9. the type-specific equality
          function will be called in order to generate a more useful
          default error message (see also the *note list of
          type-specific methods: 34df.).

          3.1 版更變: Added the automatic calling of type-specific
          equality function.

          3.2 版更變: *note assertMultiLineEqual(): d9f. added as the
          default type equality function for comparing strings.

      -- 成員函式: assertNotEqual (first, second, msg=None)

          Test that `first' and `second' are not equal.  If the values
          do compare equal, the test will fail.

      -- 成員函式: assertTrue (expr, msg=None)
      -- 成員函式: assertFalse (expr, msg=None)

          Test that `expr' is true (or false).

          Note that this is equivalent to ‘bool(expr) is True’ and not
          to ‘expr is True’ (use ‘assertIs(expr, True)’ for the latter).
          This method should also be avoided when more specific methods
          are available (e.g.  ‘assertEqual(a, b)’ instead of
          ‘assertTrue(a == b)’), because they provide a better error
          message in case of failure.

      -- 成員函式: assertIs (first, second, msg=None)
      -- 成員函式: assertIsNot (first, second, msg=None)

          Test that `first' and `second' are (or are not) the same
          object.

          3.1 版新加入.

      -- 成員函式: assertIsNone (expr, msg=None)
      -- 成員函式: assertIsNotNone (expr, msg=None)

          Test that `expr' is (or is not) ‘None’.

          3.1 版新加入.

      -- 成員函式: assertIn (member, container, msg=None)
      -- 成員函式: assertNotIn (member, container, msg=None)

          Test that `member' is (or is not) in `container'.

          3.1 版新加入.

      -- 成員函式: assertIsInstance (obj, cls, msg=None)
      -- 成員函式: assertNotIsInstance (obj, cls, msg=None)

          Test that `obj' is (or is not) an instance of `cls' (which can
          be a class or a tuple of classes, as supported by *note
          isinstance(): 551.).  To check for the exact type, use *note
          assertIs(type(obj), cls): d97.

          3.2 版新加入.

     It is also possible to check the production of exceptions,
     warnings, and log messages using the following methods:

     Method                                                        Checks that                                New in
                                                                                                              
     --------------------------------------------------------------------------------------------------------------------------
                                                                                                              
     *note assertRaises(exc, fun, *args, **kwds): b92.             ‘fun(*args, **kwds)’ raises `exc'
                                                                   
                                                                                                              
     *note assertRaisesRegex(exc, r, fun, *args, **kwds): b93.     ‘fun(*args, **kwds)’ raises `exc' and      3.1
                                                                   the message matches regex `r'              
                                                                   
                                                                                                              
     *note assertWarns(warn, fun, *args, **kwds): b94.             ‘fun(*args, **kwds)’ raises `warn'         3.2
                                                                                                              
                                                                                                              
     *note assertWarnsRegex(warn, r, fun, *args, **kwds): b95.     ‘fun(*args, **kwds)’ raises `warn' and     3.2
                                                                   the message matches regex `r'              
                                                                   
                                                                                                              
     *note assertLogs(logger, level): 9eb.                         The ‘with’ block logs on `logger' with     3.4
                                                                   minimum `level'                            
                                                                   

      -- 成員函式: assertRaises (exception, callable, *args, **kwds)

      -- 成員函式: assertRaises (exception, *, msg=None)

          Test that an exception is raised when `callable' is called
          with any positional or keyword arguments that are also passed
          to *note assertRaises(): b92.  The test passes if `exception'
          is raised, is an error if another exception is raised, or
          fails if no exception is raised.  To catch any of a group of
          exceptions, a tuple containing the exception classes may be
          passed as `exception'.

          If only the `exception' and possibly the `msg' arguments are
          given, return a context manager so that the code under test
          can be written inline rather than as a function:

               with self.assertRaises(SomeException):
                   do_something()

          When used as a context manager, *note assertRaises(): b92.
          accepts the additional keyword argument `msg'.

          The context manager will store the caught exception object in
          its ‘exception’ attribute.  This can be useful if the
          intention is to perform additional checks on the exception
          raised:

               with self.assertRaises(SomeException) as cm:
                   do_something()

               the_exception = cm.exception
               self.assertEqual(the_exception.error_code, 3)

          3.1 版更變: Added the ability to use *note assertRaises():
          b92. as a context manager.

          3.2 版更變: Added the ‘exception’ attribute.

          3.3 版更變: Added the `msg' keyword argument when used as a
          context manager.

      -- 成員函式: assertRaisesRegex (exception, regex, callable, *args,
               **kwds)

      -- 成員函式: assertRaisesRegex (exception, regex, *, msg=None)

          Like *note assertRaises(): b92. but also tests that `regex'
          matches on the string representation of the raised exception.
          `regex' may be a regular expression object or a string
          containing a regular expression suitable for use by *note
          re.search(): c82.  Examples:

               self.assertRaisesRegex(ValueError, "invalid literal for.*XYZ'$",
                                      int, 'XYZ')

          或是：

               with self.assertRaisesRegex(ValueError, 'literal'):
                  int('XYZ')

          3.1 版新加入: 以方法名‘‘assertRaisesRegexp‘‘添加。

          3.2 版更變: Renamed to *note assertRaisesRegex(): b93.

          3.3 版更變: Added the `msg' keyword argument when used as a
          context manager.

      -- 成員函式: assertWarns (warning, callable, *args, **kwds)

      -- 成員函式: assertWarns (warning, *, msg=None)

          Test that a warning is triggered when `callable' is called
          with any positional or keyword arguments that are also passed
          to *note assertWarns(): b94.  The test passes if `warning' is
          triggered and fails if it isn’t.  Any exception is an error.
          To catch any of a group of warnings, a tuple containing the
          warning classes may be passed as `warnings'.

          If only the `warning' and possibly the `msg' arguments are
          given, return a context manager so that the code under test
          can be written inline rather than as a function:

               with self.assertWarns(SomeWarning):
                   do_something()

          When used as a context manager, *note assertWarns(): b94.
          accepts the additional keyword argument `msg'.

          The context manager will store the caught warning object in
          its ‘warning’ attribute, and the source line which triggered
          the warnings in the ‘filename’ and ‘lineno’ attributes.  This
          can be useful if the intention is to perform additional checks
          on the warning caught:

               with self.assertWarns(SomeWarning) as cm:
                   do_something()

               self.assertIn('myfile.py', cm.filename)
               self.assertEqual(320, cm.lineno)

          This method works regardless of the warning filters in place
          when it is called.

          3.2 版新加入.

          3.3 版更變: Added the `msg' keyword argument when used as a
          context manager.

      -- 成員函式: assertWarnsRegex (warning, regex, callable, *args,
               **kwds)

      -- 成員函式: assertWarnsRegex (warning, regex, *, msg=None)

          Like *note assertWarns(): b94. but also tests that `regex'
          matches on the message of the triggered warning.  `regex' may
          be a regular expression object or a string containing a
          regular expression suitable for use by *note re.search(): c82.
          Example:

               self.assertWarnsRegex(DeprecationWarning,
                                     r'legacy_function\(\) is deprecated',
                                     legacy_function, 'XYZ')

          或是：

               with self.assertWarnsRegex(RuntimeWarning, 'unsafe frobnicating'):
                   frobnicate('/etc/passwd')

          3.2 版新加入.

          3.3 版更變: Added the `msg' keyword argument when used as a
          context manager.

      -- 成員函式: assertLogs (logger=None, level=None)

          A context manager to test that at least one message is logged
          on the `logger' or one of its children, with at least the
          given `level'.

          If given, `logger' should be a *note logging.Logger: 4ad.
          object or a *note str: 205. giving the name of a logger.  The
          default is the root logger, which will catch all messages that
          were not blocked by a non-propagating descendent logger.

          If given, `level' should be either a numeric logging level or
          its string equivalent (for example either ‘"ERROR"’ or
          ‘logging.ERROR’).  The default is ‘logging.INFO’.

          The test passes if at least one message emitted inside the
          ‘with’ block matches the `logger' and `level' conditions,
          otherwise it fails.

          The object returned by the context manager is a recording
          helper which keeps tracks of the matching log messages.  It
          has two attributes:

           -- 屬性: records

               A list of *note logging.LogRecord: 9ec. objects of the
               matching log messages.

           -- 屬性: output

               A list of *note str: 205. objects with the formatted
               output of matching messages.

          示例:

               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'])

          3.4 版新加入.

     There are also other methods used to perform more specific checks,
     such as:

     Method                                      Checks that                          New in
                                                                                      
     ----------------------------------------------------------------------------------------------------
                                                                                      
     *note assertAlmostEqual(a, b): c87.         ‘round(a-b, 7) == 0’
                                                 
                                                                                      
     *note assertNotAlmostEqual(a, b): c88.      ‘round(a-b, 7) != 0’
                                                 
                                                                                      
     *note assertGreater(a, b): d9b.             ‘a > b’                              3.1
                                                                                      
                                                                                      
     *note assertGreaterEqual(a, b): d9c.        ‘a >= b’                             3.1
                                                                                      
                                                                                      
     *note assertLess(a, b): d9d.                ‘a < b’                              3.1
                                                                                      
                                                                                      
     *note assertLessEqual(a, b): d9e.           ‘a <= b’                             3.1
                                                                                      
                                                                                      
     *note assertRegex(s, r): c81.               ‘r.search(s)’                        3.1
                                                                                      
                                                                                      
     *note assertNotRegex(s, r): 34e2.           ‘not r.search(s)’                    3.2
                                                                                      
                                                                                      
     *note assertCountEqual(a, b): c7f.          `a' and `b' have the same elements   3.2
                                                 in the same number, regardless of    
                                                 their order.
                                                 

      -- 成員函式: assertAlmostEqual (first, second, places=7, msg=None,
               delta=None)
      -- 成員函式: assertNotAlmostEqual (first, second, places=7,
               msg=None, delta=None)

          Test that `first' and `second' are approximately (or not
          approximately) equal by computing the difference, rounding to
          the given number of decimal `places' (default 7), and
          comparing to zero.  Note that these methods round the values
          to the given number of `decimal places' (i.e.  like the *note
          round(): d35. function) and not `significant digits'.

          If `delta' is supplied instead of `places' then the difference
          between `first' and `second' must be less or equal to (or
          greater than) `delta'.

          Supplying both `delta' and `places' raises a *note TypeError:
          1fe.

          3.2 版更變: *note assertAlmostEqual(): c87. automatically
          considers almost equal objects that compare equal.  *note
          assertNotAlmostEqual(): c88. automatically fails if the
          objects compare equal.  Added the `delta' keyword argument.

      -- 成員函式: assertGreater (first, second, msg=None)
      -- 成員函式: assertGreaterEqual (first, second, msg=None)
      -- 成員函式: assertLess (first, second, msg=None)
      -- 成員函式: assertLessEqual (first, second, msg=None)

          Test that `first' is respectively >, >=, < or <= than `second'
          depending on the method name.  If not, the test will fail:

               >>> self.assertGreaterEqual(3, 4)
               AssertionError: "3" unexpectedly not greater than or equal to "4"

          3.1 版新加入.

      -- 成員函式: assertRegex (text, regex, msg=None)
      -- 成員函式: assertNotRegex (text, regex, msg=None)

          测试一个 `regex' 是否匹配 `文本'。如果不匹配，错误信息中将包含
          匹配模式和 `文本*（或部分匹配失败的 *文本'）。`regex' 可以是正
          则表达式对象或能够用于 *note re.search(): c82. 的包含正则表达
          式的字符串。

          3.1 版新加入: 以方法名‘‘assertRegexpMatches‘‘添加。

          3.2 版更變: 方法 ‘assertRegexpMatches()’ 已被改名为 *note
          assertRegex(): c81.。

          3.2 版新加入: *note assertNotRegex(): 34e2.

          3.5 版新加入: ‘assertNotRegexpMatches’ 这个名字是 *note
          assertNotRegex(): 34e2. 的已被弃用的别名。

      -- 成員函式: assertCountEqual (first, second, msg=None)

          Test that sequence `first' contains the same elements as
          `second', regardless of their order.  When they don’t, an
          error message listing the differences between the sequences
          will be generated.

          Duplicate elements are `not' ignored when comparing `first'
          and `second'.  It verifies whether each element has the same
          count in both sequences.  Equivalent to:
          ‘assertEqual(Counter(list(first)), Counter(list(second)))’ but
          works with sequences of unhashable objects as well.

          3.2 版新加入.

     The *note assertEqual(): c85. method dispatches the equality check
     for objects of the same type to different type-specific methods.
     These methods are already implemented for most of the built-in
     types, but it’s also possible to register new methods using *note
     addTypeEqualityFunc(): da9.:

      -- 成員函式: addTypeEqualityFunc (typeobj, function)

          Registers a type-specific method called by *note
          assertEqual(): c85. to check if two objects of exactly the
          same `typeobj' (not subclasses) compare equal.  `function'
          must take two positional arguments and a third msg=None
          keyword argument just as *note assertEqual(): c85. does.  It
          must raise *note self.failureException(msg): 34e3. when
          inequality between the first two parameters is detected –
          possibly providing useful information and explaining the
          inequalities in details in the error message.

          3.1 版新加入.

     以下是 *note assertEqual(): c85. 自动选用的不同类型的比较方法。一般
     情况下不需要直接在测试中调用这些方法。

     Method                                        用作比较                          New in
                                                                                     
     ---------------------------------------------------------------------------------------------------
                                                                                     
     *note assertMultiLineEqual(a, b): d9f.        字符串                            3.1
                                                                                     
                                                                                     
     *note assertSequenceEqual(a, b): da5.         序列                              3.1
                                                                                     
                                                                                     
     *note assertListEqual(a, b): da3.             列表                              3.1
                                                                                     
                                                                                     
     *note assertTupleEqual(a, b): da4.            元组                              3.1
                                                                                     
                                                                                     
     *note assertSetEqual(a, b): da2.              集合                              3.1
                                                                                     
                                                                                     
     *note assertDictEqual(a, b): da6.             字典                              3.1
                                                                                     

      -- 成員函式: assertMultiLineEqual (first, second, msg=None)

          Test that the multiline string `first' is equal to the string
          `second'.  When not equal a diff of the two strings
          highlighting the differences will be included in the error
          message.  This method is used by default when comparing
          strings with *note assertEqual(): c85.

          3.1 版新加入.

      -- 成員函式: assertSequenceEqual (first, second, msg=None,
               seq_type=None)

          Tests that two sequences are equal.  If a `seq_type' is
          supplied, both `first' and `second' must be instances of
          `seq_type' or a failure will be raised.  If the sequences are
          different an error message is constructed that shows the
          difference between the two.

          This method is not called directly by *note assertEqual():
          c85, but it’s used to implement *note assertListEqual(): da3.
          and *note assertTupleEqual(): da4.

          3.1 版新加入.

      -- 成員函式: assertListEqual (first, second, msg=None)
      -- 成員函式: assertTupleEqual (first, second, msg=None)

          Tests that two lists or tuples are equal.  If not, an error
          message is constructed that shows only the differences between
          the two.  An error is also raised if either of the parameters
          are of the wrong type.  These methods are used by default when
          comparing lists or tuples with *note assertEqual(): c85.

          3.1 版新加入.

      -- 成員函式: assertSetEqual (first, second, msg=None)

          Tests that two sets are equal.  If not, an error message is
          constructed that lists the differences between the sets.  This
          method is used by default when comparing sets or frozensets
          with *note assertEqual(): c85.

          Fails if either of `first' or `second' does not have a
          ‘set.difference()’ method.

          3.1 版新加入.

      -- 成員函式: assertDictEqual (first, second, msg=None)

          Test that two dictionaries are equal.  If not, an error
          message is constructed that shows the differences in the
          dictionaries.  This method will be used by default to compare
          dictionaries in calls to *note assertEqual(): c85.

          3.1 版新加入.

     Finally the *note TestCase: 9e5. provides the following methods and
     attributes:

      -- 成員函式: fail (msg=None)

          Signals a test failure unconditionally, with `msg' or ‘None’
          for the error message.

      -- 屬性: failureException

          This class attribute gives the exception raised by the test
          method.  If a test framework needs to use a specialized
          exception, possibly to carry additional information, it must
          subclass this exception in order to "play fair" with the
          framework.  The initial value of this attribute is *note
          AssertionError: 240.

      -- 屬性: longMessage

          This class attribute determines what happens when a custom
          failure message is passed as the msg argument to an assertXYY
          call that fails.  ‘True’ is the default value.  In this case,
          the custom message is appended to the end of the standard
          failure message.  When set to ‘False’, the custom message
          replaces the standard message.

          The class setting can be overridden in individual test methods
          by assigning an instance attribute, self.longMessage, to
          ‘True’ or ‘False’ before calling the assert methods.

          The class setting gets reset before each test call.

          3.1 版新加入.

      -- 屬性: maxDiff

          This attribute controls the maximum length of diffs output by
          assert methods that report diffs on failure.  It defaults to
          80*8 characters.  Assert methods affected by this attribute
          are *note assertSequenceEqual(): da5. (including all the
          sequence comparison methods that delegate to it), *note
          assertDictEqual(): da6. and *note assertMultiLineEqual(): d9f.

          Setting ‘maxDiff’ to ‘None’ means that there is no maximum
          length of diffs.

          3.2 版新加入.

     Testing frameworks can use the following methods to collect
     information on the test:

      -- 成員函式: countTestCases ()

          Return the number of tests represented by this test object.
          For *note TestCase: 9e5. instances, this will always be ‘1’.

      -- 成員函式: defaultTestResult ()

          Return an instance of the test result class that should be
          used for this test case class (if no other result instance is
          provided to the *note run(): b96. method).

          For *note TestCase: 9e5. instances, this will always be an
          instance of *note TestResult: b97.; subclasses of *note
          TestCase: 9e5. should override this as necessary.

      -- 成員函式: id ()

          Return a string identifying the specific test case.  This is
          usually the full name of the test method, including the module
          and class name.

      -- 成員函式: shortDescription ()

          Returns a description of the test, or ‘None’ if no description
          has been provided.  The default implementation of this method
          returns the first line of the test method’s docstring, if
          available, or ‘None’.

          3.1 版更變: In 3.1 this was changed to add the test name to
          the short description even in the presence of a docstring.
          This caused compatibility issues with unittest extensions and
          adding the test name was moved to the *note TextTestResult:
          f51. in Python 3.2.

      -- 成員函式: addCleanup (function, /, *args, **kwargs)

          Add a function to be called after *note tearDown(): d94. to
          cleanup resources used during the test.  Functions will be
          called in reverse order to the order they are added (LIFO).
          They are called with any arguments and keyword arguments
          passed into *note addCleanup(): 3c5. when they are added.

          If *note setUp(): d93. fails, meaning that *note tearDown():
          d94. is not called, then any cleanup functions added will
          still be called.

          3.1 版新加入.

      -- 成員函式: doCleanups ()

          This method is called unconditionally after *note tearDown():
          d94, or after *note setUp(): d93. if *note setUp(): d93.
          raises an exception.

          It is responsible for calling all the cleanup functions added
          by *note addCleanup(): 3c5.  If you need cleanup functions to
          be called `prior' to *note tearDown(): d94. then you can call
          *note doCleanups(): d92. yourself.

          *note doCleanups(): d92. pops methods off the stack of cleanup
          functions one at a time, so it can be called at any time.

          3.1 版新加入.

      -- 成員函式: classmethod addClassCleanup (function, /, *args,
               **kwargs)

          Add a function to be called after *note tearDownClass(): d91.
          to cleanup resources used during the test class.  Functions
          will be called in reverse order to the order they are added
          (LIFO).  They are called with any arguments and keyword
          arguments passed into *note addClassCleanup(): 375. when they
          are added.

          If *note setUpClass(): 376. fails, meaning that *note
          tearDownClass(): d91. is not called, then any cleanup
          functions added will still be called.

          3.8 版新加入.

      -- 成員函式: classmethod doClassCleanups ()

          This method is called unconditionally after *note
          tearDownClass(): d91, or after *note setUpClass(): 376. if
          *note setUpClass(): 376. raises an exception.

          It is responsible for calling all the cleanup functions added
          by *note addClassCleanup(): 375.  If you need cleanup
          functions to be called `prior' to *note tearDownClass(): d91.
          then you can call *note doClassCleanups(): 34e9. yourself.

          *note doClassCleanups(): 34e9. pops methods off the stack of
          cleanup functions one at a time, so it can be called at any
          time.

          3.8 版新加入.

 -- 類別: unittest.IsolatedAsyncioTestCase (methodName='runTest')

     This class provides an API similar to *note TestCase: 9e5. and also
     accepts coroutines as test functions.

     3.8 版新加入.

      -- 成員函式: coroutine asyncSetUp ()

          Method called to prepare the test fixture.  This is called
          after ‘setUp()’.  This is called immediately before calling
          the test method; other than *note AssertionError: 240. or
          *note SkipTest: 9e9, any exception raised by this method will
          be considered an error rather than a test failure.  The
          default implementation does nothing.

      -- 成員函式: coroutine asyncTearDown ()

          Method called immediately after the test method has been
          called and the result recorded.  This is called before
          ‘tearDown()’.  This is called even if the test method raised
          an exception, so the implementation in subclasses may need to
          be particularly careful about checking internal state.  Any
          exception, other than *note AssertionError: 240. or *note
          SkipTest: 9e9, raised by this method will be considered an
          additional error rather than a test failure (thus increasing
          the total number of reported errors).  This method will only
          be called if the *note asyncSetUp(): 34ea. succeeds,
          regardless of the outcome of the test method.  The default
          implementation does nothing.

      -- 成員函式: addAsyncCleanup (function, /, *args, **kwargs)

          This method accepts a coroutine that can be used as a cleanup
          function.

      -- 成員函式: run (result=None)

          Sets up a new event loop to run the test, collecting the
          result into the *note TestResult: b97. object passed as
          `result'.  If `result' is omitted or ‘None’, a temporary
          result object is created (by calling the ‘defaultTestResult()’
          method) and used.  The result object is returned to *note
          run(): 34ed.’s caller.  At the end of the test all the tasks
          in the event loop are cancelled.

     An example illustrating the order:

          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()

     After running the test, ‘events’ would contain ‘["setUp",
     "asyncSetUp", "test_response", "asyncTearDown", "tearDown",
     "cleanup"]’.

 -- 類別: unittest.FunctionTestCase (testFunc, setUp=None,
          tearDown=None, description=None)

     This class implements the portion of the *note TestCase: 9e5.
     interface which allows the test runner to drive the test, but does
     not provide the methods which test code can use to check and report
     errors.  This is used to create test cases using legacy test code,
     allowing it to be integrated into a *note unittest: 124.-based test
     framework.

* Menu:

* Deprecated aliases::


File: python.info,  Node: Deprecated aliases,  Up: 测试用例

5.26.8.11 Deprecated aliases
............................

For historical reasons, some of the *note TestCase: 9e5. methods had one
or more aliases that are now deprecated.  The following table lists the
correct names along with their deprecated aliases:

     方法名                             Deprecated alias           Deprecated alias
                                                                   
     ------------------------------------------------------------------------------------------
                                                                   
     *note assertEqual(): c85.          failUnlessEqual            assertEquals
                                                                   
                                                                   
     *note assertNotEqual(): c86.       failIfEqual                assertNotEquals
                                                                   
                                                                   
     *note assertTrue(): c84.           failUnless                 assert_
                                                                   
                                                                   
     *note assertFalse(): d8f.          failIf
                                        
                                                                   
     *note assertRaises(): b92.         failUnlessRaises
                                        
                                                                   
     *note assertAlmostEqual(): c87.    failUnlessAlmostEqual      assertAlmostEquals
                                                                   
                                                                   
     *note assertNotAlmostEqual(): c88. failIfAlmostEqual          assertNotAlmostEquals
                                                                   
                                                                   
     *note assertRegex(): c81.                                     assertRegexpMatches
                                                                   
                                                                   
     *note assertNotRegex(): 34e2.                                 assertNotRegexpMatches
                                                                   
                                                                   
     *note assertRaisesRegex(): b93.                               assertRaisesRegexp
                                                                   

     3.1 版後已棄用: The fail* aliases listed in the second column have
     been deprecated.

     3.2 版後已棄用: The assert* aliases listed in the third column have
     been deprecated.

     3.2 版後已棄用: ‘assertRegexpMatches’ and ‘assertRaisesRegexp’ have
     been renamed to *note assertRegex(): c81. and *note
     assertRaisesRegex(): b93.

     3.5 版後已棄用: The ‘assertNotRegexpMatches’ name is deprecated in
     favor of *note assertNotRegex(): 34e2.


File: python.info,  Node: Grouping tests,  Next: Loading and running tests,  Prev: 测试用例,  Up: 类与函数

5.26.8.12 Grouping tests
........................

 -- 類別: unittest.TestSuite (tests=())

     This class represents an aggregation of individual test cases and
     test suites.  The class presents the interface needed by the test
     runner to allow it to be run as any other test case.  Running a
     *note TestSuite: 7c1. instance is the same as iterating over the
     suite, running each test individually.

     If `tests' is given, it must be an iterable of individual test
     cases or other test suites that will be used to build the suite
     initially.  Additional methods are provided to add test cases and
     suites to the collection later on.

     *note TestSuite: 7c1. objects behave much like *note TestCase: 9e5.
     objects, except they do not actually implement a test.  Instead,
     they are used to aggregate tests into groups of tests that should
     be run together.  Some additional methods are available to add
     tests to *note TestSuite: 7c1. instances:

      -- 成員函式: addTest (test)

          Add a *note TestCase: 9e5. or *note TestSuite: 7c1. to the
          suite.

      -- 成員函式: addTests (tests)

          Add all the tests from an iterable of *note TestCase: 9e5. and
          *note TestSuite: 7c1. instances to this test suite.

          This is equivalent to iterating over `tests', calling *note
          addTest(): 34f1. for each element.

     *note TestSuite: 7c1. shares the following methods with *note
     TestCase: 9e5.:

      -- 成員函式: run (result)

          Run the tests associated with this suite, collecting the
          result into the test result object passed as `result'.  Note
          that unlike *note TestCase.run(): b96, *note TestSuite.run():
          34f3. requires the result object to be passed in.

      -- 成員函式: debug ()

          Run the tests associated with this suite without collecting
          the result.  This allows exceptions raised by the test to be
          propagated to the caller and can be used to support running
          tests under a debugger.

      -- 成員函式: countTestCases ()

          Return the number of tests represented by this test object,
          including all individual tests and sub-suites.

      -- 成員函式: __iter__ ()

          Tests grouped by a *note TestSuite: 7c1. are always accessed
          by iteration.  Subclasses can lazily provide tests by
          overriding *note __iter__(): a43.  Note that this method may
          be called several times on a single suite (for example when
          counting tests or comparing for equality) so the tests
          returned by repeated iterations before *note TestSuite.run():
          34f3. must be the same for each call iteration.  After *note
          TestSuite.run(): 34f3, callers should not rely on the tests
          returned by this method unless the caller uses a subclass that
          overrides ‘TestSuite._removeTestAtIndex()’ to preserve test
          references.

          3.2 版更變: In earlier versions the *note TestSuite: 7c1.
          accessed tests directly rather than through iteration, so
          overriding *note __iter__(): a43. wasn’t sufficient for
          providing tests.

          3.4 版更變: In earlier versions the *note TestSuite: 7c1. held
          references to each *note TestCase: 9e5. after *note
          TestSuite.run(): 34f3.  Subclasses can restore that behavior
          by overriding ‘TestSuite._removeTestAtIndex()’.

     In the typical usage of a *note TestSuite: 7c1. object, the *note
     run(): 34f3. method is invoked by a ‘TestRunner’ rather than by the
     end-user test harness.


File: python.info,  Node: Loading and running tests,  Prev: Grouping tests,  Up: 类与函数

5.26.8.13 Loading and running tests
...................................

 -- 類別: unittest.TestLoader

     The *note TestLoader: 871. class is used to create test suites from
     classes and modules.  Normally, there is no need to create an
     instance of this class; the *note unittest: 124. module provides an
     instance that can be shared as *note unittest.defaultTestLoader:
     34f7.  Using a subclass or instance, however, allows customization
     of some configurable properties.

     *note TestLoader: 871. objects have the following attributes:

      -- 屬性: errors

          A list of the non-fatal errors encountered while loading
          tests.  Not reset by the loader at any point.  Fatal errors
          are signalled by the relevant a method raising an exception to
          the caller.  Non-fatal errors are also indicated by a
          synthetic test that will raise the original error when run.

          3.5 版新加入.

     *note TestLoader: 871. objects have the following methods:

      -- 成員函式: loadTestsFromTestCase (testCaseClass)

          Return a suite of all test cases contained in the *note
          TestCase: 9e5.-derived ‘testCaseClass’.

          A test case instance is created for each method named by *note
          getTestCaseNames(): 34f9.  By default these are the method
          names beginning with ‘test’.  If *note getTestCaseNames():
          34f9. returns no methods, but the ‘runTest()’ method is
          implemented, a single test case is created for that method
          instead.

      -- 成員函式: loadTestsFromModule (module, pattern=None)

          Return a suite of all test cases contained in the given
          module.  This method searches `module' for classes derived
          from *note TestCase: 9e5. and creates an instance of the class
          for each test method defined for the class.

               備註: While using a hierarchy of *note TestCase:
               9e5.-derived classes can be convenient in sharing
               fixtures and helper functions, defining test methods on
               base classes that are not intended to be instantiated
               directly does not play well with this method.  Doing so,
               however, can be useful when the fixtures are different
               and defined in subclasses.

          If a module provides a ‘load_tests’ function it will be called
          to load the tests.  This allows modules to customize test
          loading.  This is the *note load_tests protocol: 34cd.  The
          `pattern' argument is passed as the third argument to
          ‘load_tests’.

          3.2 版更變: Support for ‘load_tests’ added.

          3.5 版更變: The undocumented and unofficial `use_load_tests'
          default argument is deprecated and ignored, although it is
          still accepted for backward compatibility.  The method also
          now accepts a keyword-only argument `pattern' which is passed
          to ‘load_tests’ as the third argument.

      -- 成員函式: loadTestsFromName (name, module=None)

          Return a suite of all test cases given a string specifier.

          The specifier `name' is a "dotted name" that may resolve
          either to a module, a test case class, a test method within a
          test case class, a *note TestSuite: 7c1. instance, or a
          callable object which returns a *note TestCase: 9e5. or *note
          TestSuite: 7c1. instance.  These checks are applied in the
          order listed here; that is, a method on a possible test case
          class will be picked up as "a test method within a test case
          class", rather than "a callable object".

          For example, if you have a module ‘SampleTests’ containing a
          *note TestCase: 9e5.-derived class ‘SampleTestCase’ with three
          test methods (‘test_one()’, ‘test_two()’, and ‘test_three()’),
          the specifier ‘'SampleTests.SampleTestCase'’ would cause this
          method to return a suite which will run all three test
          methods.  Using the specifier
          ‘'SampleTests.SampleTestCase.test_two'’ would cause it to
          return a test suite which will run only the ‘test_two()’ test
          method.  The specifier can refer to modules and packages which
          have not been imported; they will be imported as a
          side-effect.

          The method optionally resolves `name' relative to the given
          `module'.

          3.5 版更變: If an *note ImportError: 16c. or *note
          AttributeError: 4a1. occurs while traversing `name' then a
          synthetic test that raises that error when run will be
          returned.  These errors are included in the errors accumulated
          by self.errors.

      -- 成員函式: loadTestsFromNames (names, module=None)

          Similar to *note loadTestsFromName(): da7, but takes a
          sequence of names rather than a single name.  The return value
          is a test suite which supports all the tests defined for each
          name.

      -- 成員函式: getTestCaseNames (testCaseClass)

          Return a sorted sequence of method names found within
          `testCaseClass'; this should be a subclass of *note TestCase:
          9e5.

      -- 成員函式: discover (start_dir, pattern='test*.py',
               top_level_dir=None)

          Find all the test modules by recursing into subdirectories
          from the specified start directory, and return a TestSuite
          object containing them.  Only test files that match `pattern'
          will be loaded.  (Using shell style pattern matching.)  Only
          module names that are importable (i.e.  are valid Python
          identifiers) will be loaded.

          All test modules must be importable from the top level of the
          project.  If the start directory is not the top level
          directory then the top level directory must be specified
          separately.

          If importing a module fails, for example due to a syntax
          error, then this will be recorded as a single error and
          discovery will continue.  If the import failure is due to
          *note SkipTest: 9e9. being raised, it will be recorded as a
          skip instead of an error.

          If a package (a directory containing a file named
          ‘__init__.py’) is found, the package will be checked for a
          ‘load_tests’ function.  If this exists then it will be called
          ‘package.load_tests(loader, tests, pattern)’.  Test discovery
          takes care to ensure that a package is only checked for tests
          once during an invocation, even if the load_tests function
          itself calls ‘loader.discover’.

          If ‘load_tests’ exists then discovery does `not' recurse into
          the package, ‘load_tests’ is responsible for loading all tests
          in the package.

          The pattern is deliberately not stored as a loader attribute
          so that packages can continue discovery themselves.
          `top_level_dir' is stored so ‘load_tests’ does not need to
          pass this argument in to ‘loader.discover()’.

          `start_dir' can be a dotted module name as well as a
          directory.

          3.2 版新加入.

          3.4 版更變: Modules that raise *note SkipTest: 9e9. on import
          are recorded as skips, not errors.

          3.4 版更變: `start_dir' can be a *note namespace packages:
          15ee.

          3.4 版更變: Paths are sorted before being imported so that
          execution order is the same even if the underlying file
          system’s ordering is not dependent on file name.

          3.5 版更變: Found packages are now checked for ‘load_tests’
          regardless of whether their path matches `pattern', because it
          is impossible for a package name to match the default pattern.

     The following attributes of a *note TestLoader: 871. can be
     configured either by subclassing or assignment on an instance:

      -- 屬性: testMethodPrefix

          String giving the prefix of method names which will be
          interpreted as test methods.  The default value is ‘'test'’.

          This affects *note getTestCaseNames(): 34f9. and all the
          ‘loadTestsFrom*()’ methods.

      -- 屬性: sortTestMethodsUsing

          Function to be used to compare method names when sorting them
          in *note getTestCaseNames(): 34f9. and all the
          ‘loadTestsFrom*()’ methods.

      -- 屬性: suiteClass

          Callable object that constructs a test suite from a list of
          tests.  No methods on the resulting object are needed.  The
          default value is the *note TestSuite: 7c1. class.

          This affects all the ‘loadTestsFrom*()’ methods.

      -- 屬性: testNamePatterns

          List of Unix shell-style wildcard test name patterns that test
          methods have to match to be included in test suites (see ‘-v’
          option).

          If this attribute is not ‘None’ (the default), all test
          methods to be included in test suites must match one of the
          patterns in this list.  Note that matches are always performed
          using *note fnmatch.fnmatchcase(): 1dd9, so unlike patterns
          passed to the ‘-v’ option, simple substring patterns will have
          to be converted using ‘*’ wildcards.

          This affects all the ‘loadTestsFrom*()’ methods.

          3.7 版新加入.

 -- 類別: unittest.TestResult

     This class is used to compile information about which tests have
     succeeded and which have failed.

     A *note TestResult: b97. object stores the results of a set of
     tests.  The *note TestCase: 9e5. and *note TestSuite: 7c1. classes
     ensure that results are properly recorded; test authors do not need
     to worry about recording the outcome of tests.

     Testing frameworks built on top of *note unittest: 124. may want
     access to the *note TestResult: b97. object generated by running a
     set of tests for reporting purposes; a *note TestResult: b97.
     instance is returned by the ‘TestRunner.run()’ method for this
     purpose.

     *note TestResult: b97. instances have the following attributes that
     will be of interest when inspecting the results of running a set of
     tests:

      -- 屬性: errors

          A list containing 2-tuples of *note TestCase: 9e5. instances
          and strings holding formatted tracebacks.  Each tuple
          represents a test which raised an unexpected exception.

      -- 屬性: failures

          A list containing 2-tuples of *note TestCase: 9e5. instances
          and strings holding formatted tracebacks.  Each tuple
          represents a test where a failure was explicitly signalled
          using the ‘TestCase.assert*()’ methods.

      -- 屬性: skipped

          A list containing 2-tuples of *note TestCase: 9e5. instances
          and strings holding the reason for skipping the test.

          3.1 版新加入.

      -- 屬性: expectedFailures

          A list containing 2-tuples of *note TestCase: 9e5. instances
          and strings holding formatted tracebacks.  Each tuple
          represents an expected failure or error of the test case.

      -- 屬性: unexpectedSuccesses

          A list containing *note TestCase: 9e5. instances that were
          marked as expected failures, but succeeded.

      -- 屬性: shouldStop

          Set to ‘True’ when the execution of tests should stop by *note
          stop(): 3504.

      -- 屬性: testsRun

          The total number of tests run so far.

      -- 屬性: buffer

          If set to true, ‘sys.stdout’ and ‘sys.stderr’ will be buffered
          in between *note startTest(): 3507. and *note stopTest():
          3508. being called.  Collected output will only be echoed onto
          the real ‘sys.stdout’ and ‘sys.stderr’ if the test fails or
          errors.  Any output is also attached to the failure / error
          message.

          3.2 版新加入.

      -- 屬性: failfast

          If set to true *note stop(): 3504. will be called on the first
          failure or error, halting the test run.

          3.2 版新加入.

      -- 屬性: tb_locals

          If set to true then local variables will be shown in
          tracebacks.

          3.5 版新加入.

      -- 成員函式: wasSuccessful ()

          Return ‘True’ if all tests run so far have passed, otherwise
          returns ‘False’.

          3.4 版更變: Returns ‘False’ if there were any *note
          unexpectedSuccesses: 3502. from tests marked with the *note
          expectedFailure(): 34d5. decorator.

      -- 成員函式: stop ()

          This method can be called to signal that the set of tests
          being run should be aborted by setting the *note shouldStop:
          3503. attribute to ‘True’.  ‘TestRunner’ objects should
          respect this flag and return without running any additional
          tests.

          For example, this feature is used by the *note TextTestRunner:
          f52. class to stop the test framework when the user signals an
          interrupt from the keyboard.  Interactive tools which provide
          ‘TestRunner’ implementations can use this in a similar manner.

     The following methods of the *note TestResult: b97. class are used
     to maintain the internal data structures, and may be extended in
     subclasses to support additional reporting requirements.  This is
     particularly useful in building tools which support interactive
     reporting while tests are being run.

      -- 成員函式: startTest (test)

          Called when the test case `test' is about to be run.

      -- 成員函式: stopTest (test)

          Called after the test case `test' has been executed,
          regardless of the outcome.

      -- 成員函式: startTestRun ()

          Called once before any tests are executed.

          3.1 版新加入.

      -- 成員函式: stopTestRun ()

          Called once after all tests are executed.

          3.1 版新加入.

      -- 成員函式: addError (test, err)

          Called when the test case `test' raises an unexpected
          exception.  `err' is a tuple of the form returned by *note
          sys.exc_info(): d27.: ‘(type, value, traceback)’.

          The default implementation appends a tuple ‘(test,
          formatted_err)’ to the instance’s *note errors: 34fe.
          attribute, where `formatted_err' is a formatted traceback
          derived from `err'.

      -- 成員函式: addFailure (test, err)

          Called when the test case `test' signals a failure.  `err' is
          a tuple of the form returned by *note sys.exc_info(): d27.:
          ‘(type, value, traceback)’.

          The default implementation appends a tuple ‘(test,
          formatted_err)’ to the instance’s *note failures: 34ff.
          attribute, where `formatted_err' is a formatted traceback
          derived from `err'.

      -- 成員函式: addSuccess (test)

          Called when the test case `test' succeeds.

          The default implementation does nothing.

      -- 成員函式: addSkip (test, reason)

          Called when the test case `test' is skipped.  `reason' is the
          reason the test gave for skipping.

          The default implementation appends a tuple ‘(test, reason)’ to
          the instance’s *note skipped: 3500. attribute.

      -- 成員函式: addExpectedFailure (test, err)

          Called when the test case `test' fails or errors, but was
          marked with the *note expectedFailure(): 34d5. decorator.

          The default implementation appends a tuple ‘(test,
          formatted_err)’ to the instance’s *note expectedFailures:
          3501. attribute, where `formatted_err' is a formatted
          traceback derived from `err'.

      -- 成員函式: addUnexpectedSuccess (test)

          Called when the test case `test' was marked with the *note
          expectedFailure(): 34d5. decorator, but succeeded.

          The default implementation appends the test to the instance’s
          *note unexpectedSuccesses: 3502. attribute.

      -- 成員函式: addSubTest (test, subtest, outcome)

          Called when a subtest finishes.  `test' is the test case
          corresponding to the test method.  `subtest' is a custom *note
          TestCase: 9e5. instance describing the subtest.

          If `outcome' is *note None: 203, the subtest succeeded.
          Otherwise, it failed with an exception where `outcome' is a
          tuple of the form returned by *note sys.exc_info(): d27.:
          ‘(type, value, traceback)’.

          The default implementation does nothing when the outcome is a
          success, and records subtest failures as normal failures.

          3.4 版新加入.

 -- 類別: unittest.TextTestResult (stream, descriptions, verbosity)

     A concrete implementation of *note TestResult: b97. used by the
     *note TextTestRunner: f52.

     3.2 版新加入: This class was previously named ‘_TextTestResult’.
     The old name still exists as an alias but is deprecated.

 -- Data: unittest.defaultTestLoader

     Instance of the *note TestLoader: 871. class intended to be shared.
     If no customization of the *note TestLoader: 871. is needed, this
     instance can be used instead of repeatedly creating new instances.

 -- 類別: unittest.TextTestRunner (stream=None, descriptions=True,
          verbosity=1, failfast=False, buffer=False, resultclass=None,
          warnings=None, *, tb_locals=False)

     A basic test runner implementation that outputs results to a
     stream.  If `stream' is ‘None’, the default, *note sys.stderr: 1ea.
     is used as the output stream.  This class has a few configurable
     parameters, but is essentially very simple.  Graphical applications
     which run test suites should provide alternate implementations.
     Such implementations should accept ‘**kwargs’ as the interface to
     construct runners changes when features are added to unittest.

     By default this runner shows *note DeprecationWarning: 15a, *note
     PendingDeprecationWarning: 15c, *note ResourceWarning: 5ca. and
     *note ImportWarning: 6cf. even if they are *note ignored by
     default: 3513.  Deprecation warnings caused by *note deprecated
     unittest methods: c89. are also special-cased and, when the warning
     filters are ‘'default'’ or ‘'always'’, they will appear only once
     per-module, in order to avoid too many warning messages.  This
     behavior can be overridden using Python’s ‘-Wd’ or ‘-Wa’ options
     (see *note Warning control: 147d.) and leaving `warnings' to
     ‘None’.

     3.2 版更變: Added the ‘warnings’ argument.

     3.2 版更變: The default stream is set to *note sys.stderr: 1ea. at
     instantiation time rather than import time.

     3.5 版更變: Added the tb_locals parameter.

      -- 成員函式: _makeResult ()

          This method returns the instance of ‘TestResult’ used by *note
          run(): 3515.  It is not intended to be called directly, but
          can be overridden in subclasses to provide a custom
          ‘TestResult’.

          ‘_makeResult()’ instantiates the class or callable passed in
          the ‘TextTestRunner’ constructor as the ‘resultclass’
          argument.  It defaults to *note TextTestResult: f51. if no
          ‘resultclass’ is provided.  The result class is instantiated
          with the following arguments:

               stream, descriptions, verbosity

      -- 成員函式: run (test)

          This method is the main public interface to the
          ‘TextTestRunner’.  This method takes a *note TestSuite: 7c1.
          or *note TestCase: 9e5. instance.  A *note TestResult: b97. is
          created by calling *note _makeResult(): 3514. and the test(s)
          are run and the results printed to stdout.

 -- 函式: 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)

     A command-line program that loads a set of tests from `module' and
     runs them; this is primarily for making test modules conveniently
     executable.  The simplest use for this function is to include the
     following line at the end of a test script:

          if __name__ == '__main__':
              unittest.main()

     You can run tests with more detailed information by passing in the
     verbosity argument:

          if __name__ == '__main__':
              unittest.main(verbosity=2)

     The `defaultTest' argument is either the name of a single test or
     an iterable of test names to run if no test names are specified via
     `argv'.  If not specified or ‘None’ and no test names are provided
     via `argv', all tests found in `module' are run.

     The `argv' argument can be a list of options passed to the program,
     with the first element being the program name.  If not specified or
     ‘None’, the values of *note sys.argv: cc6. are used.

     The `testRunner' argument can either be a test runner class or an
     already created instance of it.  By default ‘main’ calls *note
     sys.exit(): daa. with an exit code indicating success or failure of
     the tests run.

     The `testLoader' argument has to be a *note TestLoader: 871.
     instance, and defaults to *note defaultTestLoader: 34f7.

     ‘main’ supports being used from the interactive interpreter by
     passing in the argument ‘exit=False’.  This displays the result on
     standard output without calling *note sys.exit(): daa.:

          >>> from unittest import main
          >>> main(module='test_module', exit=False)

     The `failfast', `catchbreak' and `buffer' parameters have the same
     effect as the same-name *note command-line options: 34c4.

     The `warnings' argument specifies the *note warning filter: 15d.
     that should be used while running the tests.  If it’s not
     specified, it will remain ‘None’ if a ‘-W’ option is passed to
     ‘python’ (see *note Warning control: 147d.), otherwise it will be
     set to ‘'default'’.

     Calling ‘main’ actually returns an instance of the ‘TestProgram’
     class.  This stores the result of the tests run as the ‘result’
     attribute.

     3.1 版更變: The `exit' parameter was added.

     3.2 版更變: The `verbosity', `failfast', `catchbreak', `buffer' and
     `warnings' parameters were added.

     3.4 版更變: The `defaultTest' parameter was changed to also accept
     an iterable of test names.

* Menu:

* load_tests Protocol::


File: python.info,  Node: load_tests Protocol,  Up: Loading and running tests

5.26.8.14 load_tests Protocol
.............................

3.2 版新加入.

Modules or packages can customize how tests are loaded from them during
normal test runs or test discovery by implementing a function called
‘load_tests’.

If a test module defines ‘load_tests’ it will be called by *note
TestLoader.loadTestsFromModule(): 86f. with the following arguments:

     load_tests(loader, standard_tests, pattern)

where `pattern' is passed straight through from ‘loadTestsFromModule’.
It defaults to ‘None’.

It should return a *note TestSuite: 7c1.

`loader' is the instance of *note TestLoader: 871. doing the loading.
`standard_tests' are the tests that would be loaded by default from the
module.  It is common for test modules to only want to add or remove
tests from the standard set of tests.  The third argument is used when
loading packages as part of test discovery.

A typical ‘load_tests’ function that loads tests from a specific set of
*note TestCase: 9e5. classes may look like:

     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

If discovery is started in a directory containing a package, either from
the command line or by calling *note TestLoader.discover(): 9ea, then
the package ‘__init__.py’ will be checked for ‘load_tests’.  If that
function does not exist, discovery will recurse into the package as
though it were just another directory.  Otherwise, discovery of the
package’s tests will be left up to ‘load_tests’ which is called with the
following arguments:

     load_tests(loader, standard_tests, pattern)

This should return a *note TestSuite: 7c1. representing all the tests
from the package.  (‘standard_tests’ will only contain tests collected
from ‘__init__.py’.)

Because the pattern is passed into ‘load_tests’ the package is free to
continue (and potentially modify) test discovery.  A ’do nothing’
‘load_tests’ function for a test package would look like:

     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

3.5 版更變: Discovery no longer checks package names for matching
`pattern' due to the impossibility of package names matching the default
pattern.


File: python.info,  Node: Class and Module Fixtures,  Next: 信号处理,  Prev: 类与函数,  Up: unittest --- 單元測試框架

5.26.8.15 Class and Module Fixtures
...................................

Class and module level fixtures are implemented in *note TestSuite: 7c1.
When the test suite encounters a test from a new class then
‘tearDownClass()’ from the previous class (if there is one) is called,
followed by ‘setUpClass()’ from the new class.

Similarly if a test is from a different module from the previous test
then ‘tearDownModule’ from the previous module is run, followed by
‘setUpModule’ from the new module.

After all the tests have run the final ‘tearDownClass’ and
‘tearDownModule’ are run.

Note that shared fixtures do not play well with [potential] features
like test parallelization and they break test isolation.  They should be
used with care.

The default ordering of tests created by the unittest test loaders is to
group all tests from the same modules and classes together.  This will
lead to ‘setUpClass’ / ‘setUpModule’ (etc) being called exactly once per
class and module.  If you randomize the order, so that tests from
different modules and classes are adjacent to each other, then these
shared fixture functions may be called multiple times in a single test
run.

Shared fixtures are not intended to work with suites with non-standard
ordering.  A ‘BaseTestSuite’ still exists for frameworks that don’t want
to support shared fixtures.

If there are any exceptions raised during one of the shared fixture
functions the test is reported as an error.  Because there is no
corresponding test instance an ‘_ErrorHolder’ object (that has the same
interface as a *note TestCase: 9e5.) is created to represent the error.
If you are just using the standard unittest test runner then this detail
doesn’t matter, but if you are a framework author it may be relevant.

* Menu:

* setUpClass and tearDownClass::
* setUpModule and tearDownModule::


File: python.info,  Node: setUpClass and tearDownClass,  Next: setUpModule and tearDownModule,  Up: Class and Module Fixtures

5.26.8.16 setUpClass and tearDownClass
......................................

These must be implemented as class methods:

     import unittest

     class Test(unittest.TestCase):
         @classmethod
         def setUpClass(cls):
             cls._connection = createExpensiveConnectionObject()

         @classmethod
         def tearDownClass(cls):
             cls._connection.destroy()

If you want the ‘setUpClass’ and ‘tearDownClass’ on base classes called
then you must call up to them yourself.  The implementations in *note
TestCase: 9e5. are empty.

If an exception is raised during a ‘setUpClass’ then the tests in the
class are not run and the ‘tearDownClass’ is not run.  Skipped classes
will not have ‘setUpClass’ or ‘tearDownClass’ run.  If the exception is
a *note SkipTest: 9e9. exception then the class will be reported as
having been skipped instead of as an error.


File: python.info,  Node: setUpModule and tearDownModule,  Prev: setUpClass and tearDownClass,  Up: Class and Module Fixtures

5.26.8.17 setUpModule and tearDownModule
........................................

These should be implemented as functions:

     def setUpModule():
         createConnection()

     def tearDownModule():
         closeConnection()

If an exception is raised in a ‘setUpModule’ then none of the tests in
the module will be run and the ‘tearDownModule’ will not be run.  If the
exception is a *note SkipTest: 9e9. exception then the module will be
reported as having been skipped instead of as an error.

To add cleanup code that must be run even in the case of an exception,
use ‘addModuleCleanup’:

 -- 函式: unittest.addModuleCleanup (function, /, *args, **kwargs)

     Add a function to be called after ‘tearDownModule()’ to cleanup
     resources used during the test class.  Functions will be called in
     reverse order to the order they are added (LIFO).  They are called
     with any arguments and keyword arguments passed into *note
     addModuleCleanup(): 374. when they are added.

     If ‘setUpModule()’ fails, meaning that ‘tearDownModule()’ is not
     called, then any cleanup functions added will still be called.

     3.8 版新加入.

 -- 函式: unittest.doModuleCleanups ()

     This function is called unconditionally after ‘tearDownModule()’,
     or after ‘setUpModule()’ if ‘setUpModule()’ raises an exception.

     It is responsible for calling all the cleanup functions added by
     ‘addCleanupModule()’.  If you need cleanup functions to be called
     `prior' to ‘tearDownModule()’ then you can call *note
     doModuleCleanups(): 3518. yourself.

     *note doModuleCleanups(): 3518. pops methods off the stack of
     cleanup functions one at a time, so it can be called at any time.

     3.8 版新加入.


File: python.info,  Node: 信号处理,  Prev: Class and Module Fixtures,  Up: unittest --- 單元測試框架

5.26.8.18 信号处理
..................

3.2 版新加入.

The *note -c/–catch: d8c. command-line option to unittest, along with
the ‘catchbreak’ parameter to *note unittest.main(): 9e8, provide more
friendly handling of control-C during a test run.  With catch break
behavior enabled control-C will allow the currently running test to
complete, and the test run will then end and report all the results so
far.  A second control-c will raise a *note KeyboardInterrupt: 2cc. in
the usual way.

The control-c handling signal handler attempts to remain compatible with
code or tests that install their own *note signal.SIGINT: 2626. handler.
If the ‘unittest’ handler is called but `isn’t' the installed *note
signal.SIGINT: 2626. handler, i.e.  it has been replaced by the system
under test and delegated to, then it calls the default handler.  This
will normally be the expected behavior by code that replaces an
installed handler and delegates to it.  For individual tests that need
‘unittest’ control-c handling disabled the *note removeHandler(): d8d.
decorator can be used.

There are a few utility functions for framework authors to enable
control-c handling functionality within test frameworks.

 -- 函式: unittest.installHandler ()

     Install the control-c handler.  When a *note signal.SIGINT: 2626.
     is received (usually in response to the user pressing control-c)
     all registered results have *note stop(): 3504. called.

 -- 函式: unittest.registerResult (result)

     Register a *note TestResult: b97. object for control-c handling.
     Registering a result stores a weak reference to it, so it doesn’t
     prevent the result from being garbage collected.

     Registering a *note TestResult: b97. object has no side-effects if
     control-c handling is not enabled, so test frameworks can
     unconditionally register all results they create independently of
     whether or not handling is enabled.

 -- 函式: unittest.removeResult (result)

     Remove a registered result.  Once a result has been removed then
     *note stop(): 3504. will no longer be called on that result object
     in response to a control-c.

 -- 函式: unittest.removeHandler (function=None)

     When called without arguments this function removes the control-c
     handler if it has been installed.  This function can also be used
     as a test decorator to temporarily remove the handler while the
     test is being executed:

          @unittest.removeHandler
          def test_signal_handling(self):
              ...


File: python.info,  Node: unittest mock --- mock对象库,  Next: unittest mock 上手指南,  Prev: unittest --- 單元測試框架,  Up: 開發工具

5.26.9 ‘unittest.mock’ — mock对象库
-----------------------------------

3.3 版新加入.

`源代码：' Lib/unittest/mock.py(1)

__________________________________________________________________

*note unittest.mock: 125. 是一个用于测试的Python库。它允许使用mock对象替
换受测试系统的部分，并对它们如何已经被使用进行断言。

*note unittest.mock: 125. 提供的 *note Mock: 373. 类，能在整个测试套件中
模拟大量的方法。创建后，就可以断言调用了哪些方法/属性及其参数。还可以以
常规方式指定返回值并设置所需的属性。

此外，mock 提供了用于修补测试范围内模块和类级别属性的 *note patch():
877. 装饰器，和用于创建独特对象的 *note sentinel: 50e. 。 阅读 *note
quick guide: 351e. 中的案例了解如何使用 *note Mock: 373. ，*note
MagicMock: 874. 和 *note patch(): 877. 。

Mock is designed for use with *note unittest: 124. and is based on the
’action -> assertion’ pattern instead of ’record -> replay’ used by many
mocking frameworks.

在 Python 的早期版本要单独使用 *note unittest.mock: 125. ，在 PyPI 获取
mock(2) 。

* Menu:

* 快速上手::
* Mock 类::
* The patchers::
* MagicMock and magic method support::
* Helpers::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/unittest/mock.py

   (2) https://pypi.org/project/mock


File: python.info,  Node: 快速上手,  Next: Mock 类,  Up: unittest mock --- mock对象库

5.26.9.1 快速上手
.................

当您访问对象时， *note Mock: 373. 和 *note MagicMock: 874. 将创建所有属
性和方法，并保存他们在使用时的细节。你可以通过配置，指定返回值或者限制可
访问属性，然后断言他们如何被调用：

     >>> 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')

通过 ‘side_effect’ 设置副作用(side effects) ，可以是一个 mock 被调用是抛
出的异常：

     >>> mock = Mock(side_effect=KeyError('foo'))
     >>> mock()
     Traceback (most recent call last):
      ...
     KeyError: 'foo'

     >>> 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)

Mock 还可以通过其他方法配置和控制其行为。例如 mock 可以通过设置 `spec' 参
数来从一个对象中获取其规格(specification)。如果访问 mock 的属性或方法不
在 spec 中，会报 *note AttributeError: 4a1. 错误。

使用 *note patch(): 877. 装饰去/上下文管理器，可以更方便地测试一个模块下
的类或对象。你指定的对象会在测试过程中替换成 mock （或者其他对象），测试
结束后恢复。

     >>> 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()

     備註: 当你嵌套 patch 装饰器时，mock 将以执行顺序传递给装饰器函数（
     `Python' 装饰器正常顺序）。由于从下至上，因此在上面的示例中，首先
     mock 传入的 ‘module.ClassName1’ 。

     在查找对象的名称空间中修补对象使用 *note patch(): 877. 。使用起来很
     简单，阅读 *note 在哪里打补丁: 351f. 来快速上手。

*note patch(): 877. 也可以 with 语句中使用上下文管理。

     >>> 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)

还有一个 *note patch.dict(): 110a. 用于在一定范围内设置字典中的值，并在
测试结束时将字典恢复为其原始状态：

     >>> foo = {'key': 'value'}
     >>> original = foo.copy()
     >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True):
     ...     assert foo == {'newkey': 'newvalue'}
     ...
     >>> assert foo == original

Mock支持 Python *note 魔术方法: 3520. 。使用模式方法最简单的方式是使用
*note MagicMock: 874. class. 。它可以做如下事情：

     >>> mock = MagicMock()
     >>> mock.__str__.return_value = 'foobarbaz'
     >>> str(mock)
     'foobarbaz'
     >>> mock.__str__.assert_called_with()

Mock 能指定函数（或其他 Mock 实例）为魔术方法，它们将被适当地调用。
*note MagicMock: 874. 是预先创建了所有魔术方法（所有有用的方法） 的 Mock
。

下面是一个使用了普通 Mock 类的魔术方法的例子

     >>> mock = Mock()
     >>> mock.__str__ = Mock(return_value='wheeeeee')
     >>> str(mock)
     'wheeeeee'

使用 *note auto-speccing: 3521. 可以保证测试中的模拟对象与要替换的对象具
有相同的api 。在 patch 中可以通过 `autospec' 参数实现自动推断，或者使用
*note create_autospec(): 1087. 函数。自动推断会创建一个与要替换对象相同
的属相和方法的模拟对象，并且任何函数和方法（包括构造函数）都具有与真实对
象相同的调用签名。

这么做是为了因确保不当地使用 mock 导致与生产代码相同的失败：

     >>> 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)

在类中使用 *note create_autospec(): 1087. 时，会复制 ‘__init__’ 方法的签
名，另外在可调用对象上使用时，会复制 ‘__call__’ 方法的签名。


File: python.info,  Node: Mock 类,  Next: The patchers,  Prev: 快速上手,  Up: unittest mock --- mock对象库

5.26.9.2 Mock 类
................

*note Mock: 373. 是一个可以灵活的替换存根 (stubs) 的对象，可以测试所有代
码。 Mock 是可调用的，在访问其属性时创建一个新的 mock (1) 。访问相同的属
性只会返回相同的 mock 。 Mock 会保存调用记录，可以通过断言获悉代码的调用
。

*note MagicMock: 874. 是 *note Mock: 373. 的子类，它有所有预创建且可使用
的魔术方法。在需要模拟不可调用对象时，可以使用 *note NonCallableMock:
3523.  和 *note NonCallableMagicMock: 3524.

*note patch(): 877. 装饰器便于 *note Mock: 373. 对象临时替换特定模块中的
类。 *note patch(): 877. 默认创建 *note MagicMock: 874. 。可以使用 *note
patch(): 877. 方法的 `new_callable' 参数指定 *note Mock: 373. 的替代类。

 -- 類別: unittest.mock.Mock (spec=None, side_effect=None,
          return_value=DEFAULT, wraps=None, name=None, spec_set=None,
          unsafe=False, **kwargs)

     创建一个新的 *note Mock: 373. 对象。通过可选参数指定 *note Mock:
     373. 对象的行为：

        * `spec': 可以是要给字符串列表，也可以是充当模拟对象规范的现有对
          象（类或实例）。如果传入一个对象，则通过在该对象上调用 dir 来
          生成字符串列表（不支持的魔法属性和方法除外）。访问不在此列表中
          的任何属性都将触发 *note AttributeError: 4a1. 。

          如果 `spec' 是一个对象（而不是字符串列表），则 *note
          __class__: ecc. 返回 `spec' 对象的类。 这允许模拟程序通过
          *note isinstance(): 551. 测试。

        * `spec_set' ：`spec' 的更严格的变体。如果使用了该属性，尝试模拟
          `set' 或 `get' 的属性不在 `spec_set' 所包含的对象中时，会抛出
          *note AttributeError: 4a1. 。

        * `side_effect' ：每当调用 Mock 时都会调用的函数。 参见 *note
          side_effect: 3525. 属性。 对于引发异常或动态更改返回值很有用。
          该函数使用与 mock 函数相同的参数调用，并且除非返回 *note
          DEFAULT: 3526. ，否则该函数的返回值将用作返回值。

          另外， `side_effect' 可以是异常类或实例。 此时，调用模拟程序时
          将引发异常。

          如果 `side_effect' 是可迭代对象，则每次调用 mock 都将返回可迭
          代对象的下一个值。

          设置 `side_effect' 为 ‘None’ 即可清空。

        * `return_value' ：调用 mock 的返回值。 默认情况下，是一个新的
          Mock（在首次访问时创建）。 参见 *note return_value: 3527. 属性
          。

        * `unsafe' ：默认情况下，如果任何以 `assert' 或 `assret' 开头的
          属性都将引发 *note AttributeError: 4a1. 。 当 ‘unsafe=True’ 时
          可以访问。

          3.5 版新加入.

        * `wraps' ：要包装的 mock 对象。 如果 `wraps' 不是 ‘None’ ，那么
          调用 Mock 会将调用传递给 `wraps' 的对象（返回实际结果）。 对模
          拟的属性访问将返回一个 Mock 对象，该对象包装了 `wraps' 对象的
          相应属性（因此，尝试访问不存在的属性将引发 *note
          AttributeError: 4a1. ）。

          如果明确指定 `return_value' ，调用是，不会返回包装对象，而是返
          回 `return_value' 。

        * `name' ：mock 的名称。 在调试时很有用。 名称会传递到子 mock 。

     还可以使用任意关键字参数来调用 mock 。 创建模拟后，将使用这些属性来
     设置 mock 的属性。 有关详细信息，请参见 *note configure_mock():
     3528. 方法。

      -- 成員函式: assert_called ()

          断言至少被调用过一次。

               >>> mock = Mock()
               >>> mock.method()
               <Mock name='mock.method()' id='...'>
               >>> mock.method.assert_called()

          3.6 版新加入.

      -- 成員函式: assert_called_once ()

          断言仅被调用一次。

               >>> 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.

          3.6 版新加入.

      -- 成員函式: assert_called_with (*args, **kwargs)

          此方法是断言上次调用已以特定方式进行的一种便捷方法：

               >>> mock = Mock()
               >>> mock.method(1, 2, 3, test='wow')
               <Mock name='mock.method()' id='...'>
               >>> mock.method.assert_called_with(1, 2, 3, test='wow')

      -- 成員函式: assert_called_once_with (*args, **kwargs)

          Assert that the mock was called exactly once and that call was
          with the specified arguments.

               >>> 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.

      -- 成員函式: assert_any_call (*args, **kwargs)

          断言使用指定的参数调用。

          The assert passes if the mock has `ever' been called, unlike
          *note assert_called_with(): 113a. and *note
          assert_called_once_with(): 3529. that only pass if the call is
          the most recent one, and in the case of *note
          assert_called_once_with(): 3529. it must also be the only
          call.

               >>> mock = Mock(return_value=None)
               >>> mock(1, 2, arg='thing')
               >>> mock('some', 'thing', 'else')
               >>> mock.assert_any_call(1, 2, arg='thing')

      -- 成員函式: assert_has_calls (calls, any_order=False)

          assert the mock has been called with the specified calls.  The
          *note mock_calls: 352c. list is checked for the calls.

          If `any_order' is false then the calls must be sequential.
          There can be extra calls before or after the specified calls.

          If `any_order' is true then the calls can be in any order, but
          they must all appear in *note mock_calls: 352c.

               >>> 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)

      -- 成員函式: assert_not_called ()

          Assert the mock was never called.

               >>> 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.

          3.5 版新加入.

      -- 成員函式: reset_mock (*, return_value=False, side_effect=False)

          The reset_mock method resets all the call attributes on a mock
          object:

               >>> mock = Mock(return_value=None)
               >>> mock('hello')
               >>> mock.called
               True
               >>> mock.reset_mock()
               >>> mock.called
               False

          3.6 版更變: Added two keyword only argument to the reset_mock
          function.

          This can be useful where you want to make a series of
          assertions that reuse the same object.  Note that *note
          reset_mock(): 6a1. `doesn’t' clear the return value, *note
          side_effect: 3525. or any child attributes you have set using
          normal assignment by default.  In case you want to reset
          `return_value' or *note side_effect: 3525, then pass the
          corresponding parameter as ‘True’.  Child mocks and the return
          value mock (if any) are reset as well.

               備註: `return_value', and *note side_effect: 3525. are
               keyword only argument.

      -- 成員函式: mock_add_spec (spec, spec_set=False)

          Add a spec to a mock.  `spec' can either be an object or a
          list of strings.  Only attributes on the `spec' can be fetched
          as attributes from the mock.

          If `spec_set' is true then only attributes on the spec can be
          set.

      -- 成員函式: attach_mock (mock, attribute)

          Attach a mock as an attribute of this one, replacing its name
          and parent.  Calls to the attached mock will be recorded in
          the *note method_calls: 352f. and *note mock_calls: 352c.
          attributes of this one.

      -- 成員函式: configure_mock (**kwargs)

          Set attributes on the mock through keyword arguments.

          Attributes plus return values and side effects can be set on
          child mocks using standard dot notation and unpacking a
          dictionary in the method call:

               >>> 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

          The same thing can be achieved in the constructor call to
          mocks:

               >>> 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

          *note configure_mock(): 3528. exists to make it easier to do
          configuration after the mock has been created.

      -- 成員函式: __dir__ ()

          *note Mock: 373. objects limit the results of ‘dir(some_mock)’
          to useful results.  For mocks with a `spec' this includes all
          the permitted attributes for the mock.

          See *note FILTER_DIR: 3531. for what this filtering does, and
          how to switch it off.

      -- 成員函式: _get_child_mock (**kw)

          Create the child mocks for attributes and return value.  By
          default child mocks will be the same type as the parent.
          Subclasses of Mock may want to override this to customize the
          way child mocks are made.

          For non-callable mocks the callable variant will be used
          (rather than any custom subclass).

      -- 屬性: called

          A boolean representing whether or not the mock object has been
          called:

               >>> mock = Mock(return_value=None)
               >>> mock.called
               False
               >>> mock()
               >>> mock.called
               True

      -- 屬性: call_count

          An integer telling you how many times the mock object has been
          called:

               >>> mock = Mock(return_value=None)
               >>> mock.call_count
               0
               >>> mock()
               >>> mock()
               >>> mock.call_count
               2

      -- 屬性: return_value

          Set this to configure the value returned by calling the mock:

               >>> mock = Mock()
               >>> mock.return_value = 'fish'
               >>> mock()
               'fish'

          The default return value is a mock object and you can
          configure it in the normal way:

               >>> mock = Mock()
               >>> mock.return_value.attribute = sentinel.Attribute
               >>> mock.return_value()
               <Mock name='mock()()' id='...'>
               >>> mock.return_value.assert_called_with()

          *note return_value: 3527. can also be set in the constructor:

               >>> mock = Mock(return_value=3)
               >>> mock.return_value
               3
               >>> mock()
               3

      -- 屬性: side_effect

          This can either be a function to be called when the mock is
          called, an iterable or an exception (class or instance) to be
          raised.

          If you pass in a function it will be called with same
          arguments as the mock and unless the function returns the
          *note DEFAULT: 3526. singleton the call to the mock will then
          return whatever the function returns.  If the function returns
          *note DEFAULT: 3526. then the mock will return its normal
          value (from the *note return_value: 3527.).

          If you pass in an iterable, it is used to retrieve an iterator
          which must yield a value on every call.  This value can either
          be an exception instance to be raised, or a value to be
          returned from the call to the mock (*note DEFAULT: 3526.
          handling is identical to the function case).

          An example of a mock that raises an exception (to test
          exception handling of an API):

               >>> mock = Mock()
               >>> mock.side_effect = Exception('Boom!')
               >>> mock()
               Traceback (most recent call last):
                 ...
               Exception: Boom!

          Using *note side_effect: 3525. to return a sequence of values:

               >>> mock = Mock()
               >>> mock.side_effect = [3, 2, 1]
               >>> mock(), mock(), mock()
               (3, 2, 1)

          Using a callable:

               >>> mock = Mock(return_value=3)
               >>> def side_effect(*args, **kwargs):
               ...     return DEFAULT
               ...
               >>> mock.side_effect = side_effect
               >>> mock()
               3

          *note side_effect: 3525. can be set in the constructor.
          Here’s an example that adds one to the value the mock is
          called with and returns it:

               >>> side_effect = lambda value: value + 1
               >>> mock = Mock(side_effect=side_effect)
               >>> mock(3)
               4
               >>> mock(-8)
               -7

          Setting *note side_effect: 3525. to ‘None’ clears it:

               >>> m = Mock(side_effect=KeyError, return_value=3)
               >>> m()
               Traceback (most recent call last):
                ...
               KeyError
               >>> m.side_effect = None
               >>> m()
               3

      -- 屬性: call_args

          This is either ‘None’ (if the mock hasn’t been called), or the
          arguments that the mock was last called with.  This will be in
          the form of a tuple: the first member, which can also be
          accessed through the ‘args’ property, is any ordered arguments
          the mock was called with (or an empty tuple) and the second
          member, which can also be accessed through the ‘kwargs’
          property, is any keyword arguments (or an empty dictionary).

               >>> 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!'}

          *note call_args: 106a, along with members of the lists *note
          call_args_list: 3535, *note method_calls: 352f. and *note
          mock_calls: 352c. are *note call: 10cc. objects.  These are
          tuples, so they can be unpacked to get at the individual
          arguments and make more complex assertions.  See *note calls
          as tuples: 3536.

          3.8 版更變: Added ‘args’ and ‘kwargs’ properties.

      -- 屬性: call_args_list

          This is a list of all the calls made to the mock object in
          sequence (so the length of the list is the number of times it
          has been called).  Before any calls have been made it is an
          empty list.  The *note call: 10cc. object can be used for
          conveniently constructing lists of calls to compare with *note
          call_args_list: 3535.

               >>> 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

          Members of *note call_args_list: 3535. are *note call: 10cc.
          objects.  These can be unpacked as tuples to get at the
          individual arguments.  See *note calls as tuples: 3536.

      -- 屬性: method_calls

          As well as tracking calls to themselves, mocks also track
          calls to methods and attributes, and `their' methods and
          attributes:

               >>> 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()]

          Members of *note method_calls: 352f. are *note call: 10cc.
          objects.  These can be unpacked as tuples to get at the
          individual arguments.  See *note calls as tuples: 3536.

      -- 屬性: mock_calls

          *note mock_calls: 352c. records `all' calls to the mock
          object, its methods, magic methods `and' return value mocks.

               >>> 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

          Members of *note mock_calls: 352c. are *note call: 10cc.
          objects.  These can be unpacked as tuples to get at the
          individual arguments.  See *note calls as tuples: 3536.

               備註: The way *note mock_calls: 352c. are recorded means
               that where nested calls are made, the parameters of
               ancestor calls are not recorded and so will always
               compare equal:

                    >>> 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

      -- 屬性: __class__

          Normally the *note __class__: 3537. attribute of an object
          will return its type.  For a mock object with a ‘spec’,
          ‘__class__’ returns the spec class instead.  This allows mock
          objects to pass *note isinstance(): 551. tests for the object
          they are replacing / masquerading as:

               >>> mock = Mock(spec=3)
               >>> isinstance(mock, int)
               True

          *note __class__: 3537. is assignable to, this allows a mock to
          pass an *note isinstance(): 551. check without forcing you to
          use a spec:

               >>> mock = Mock()
               >>> mock.__class__ = dict
               >>> isinstance(mock, dict)
               True

 -- 類別: unittest.mock.NonCallableMock (spec=None, wraps=None,
          name=None, spec_set=None, **kwargs)

     A non-callable version of *note Mock: 373.  The constructor
     parameters have the same meaning of *note Mock: 373, with the
     exception of `return_value' and `side_effect' which have no meaning
     on a non-callable mock.

Mock objects that use a class or an instance as a ‘spec’ or ‘spec_set’
are able to pass *note isinstance(): 551. tests:

     >>> mock = Mock(spec=SomeClass)
     >>> isinstance(mock, SomeClass)
     True
     >>> mock = Mock(spec_set=SomeClass())
     >>> isinstance(mock, SomeClass)
     True

The *note Mock: 373. classes have support for mocking magic methods.
See *note magic methods: 3520. for the full details.

The mock classes and the *note patch(): 877. decorators all take
arbitrary keyword arguments for configuration.  For the *note patch():
877. decorators the keywords are passed to the constructor of the mock
being created.  The keyword arguments are for configuring attributes of
the mock:

     >>> m = MagicMock(attribute=3, other='fish')
     >>> m.attribute
     3
     >>> m.other
     'fish'

The return value and side effect of child mocks can be set in the same
way, using dotted notation.  As you can’t use dotted names directly in a
call you have to create a dictionary and unpack it using ‘**’:

     >>> 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

A callable mock which was created with a `spec' (or a `spec_set') will
introspect the specification object’s signature when matching calls to
the mock.  Therefore, it can match the actual call’s arguments
regardless of whether they were passed positionally or by name:

     >>> 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)

This applies to *note assert_called_with(): 113a, *note
assert_called_once_with(): 3529, *note assert_has_calls(): 352b. and
*note assert_any_call(): 352a.  When *note Autospeccing: 3521, it will
also apply to method calls on the mock object.

     3.4 版更變: Added signature introspection on specced and
     autospecced mock objects.

 -- 類別: unittest.mock.PropertyMock (*args, **kwargs)

     A mock intended to be used as a property, or other descriptor, on a
     class.  *note PropertyMock: 3538. provides *note __get__(): 156e.
     and *note __set__(): 1572. methods so you can specify a return
     value when it is fetched.

     Fetching a *note PropertyMock: 3538. instance from an object calls
     the mock, with no args.  Setting it calls the mock with the value
     being set.

          >>> 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)]

Because of the way mock attributes are stored you can’t directly attach
a *note PropertyMock: 3538. to a mock object.  Instead you can attach it
to the mock type object:

     >>> m = MagicMock()
     >>> p = PropertyMock(return_value=3)
     >>> type(m).foo = p
     >>> m.foo
     3
     >>> p.assert_called_once_with()

 -- 類別: unittest.mock.AsyncMock (spec=None, side_effect=None,
          return_value=DEFAULT, wraps=None, name=None, spec_set=None,
          unsafe=False, **kwargs)

     An asynchronous version of *note MagicMock: 874.  The *note
     AsyncMock: 372. object will behave so the object is recognized as
     an async function, and the result of a call is an awaitable.

          >>> mock = AsyncMock()
          >>> asyncio.iscoroutinefunction(mock)
          True
          >>> inspect.isawaitable(mock())
          True

     The result of ‘mock()’ is an async function which will have the
     outcome of ‘side_effect’ or ‘return_value’ after it has been
     awaited:

        - if ‘side_effect’ is a function, the async function will return
          the result of that function,

        - if ‘side_effect’ is an exception, the async function will
          raise the exception,

        - if ‘side_effect’ is an iterable, the async function will
          return the next value of the iterable, however, if the
          sequence of result is exhausted, ‘StopAsyncIteration’ is
          raised immediately,

        - if ‘side_effect’ is not defined, the async function will
          return the value defined by ‘return_value’, hence, by default,
          the async function returns a new *note AsyncMock: 372. object.

     Setting the `spec' of a *note Mock: 373. or *note MagicMock: 874.
     to an async function will result in a coroutine object being
     returned after calling.

          >>> async def async_func(): pass
          ...
          >>> mock = MagicMock(async_func)
          >>> mock
          <MagicMock spec='function' id='...'>
          >>> mock()
          <coroutine object AsyncMockMixin._mock_call at ...>

     Setting the `spec' of a *note Mock: 373, *note MagicMock: 874, or
     *note AsyncMock: 372. to a class with asynchronous and synchronous
     functions will automatically detect the synchronous functions and
     set them as *note MagicMock: 874. (if the parent mock is *note
     AsyncMock: 372. or *note MagicMock: 874.) or *note Mock: 373. (if
     the parent mock is *note Mock: 373.).  All asynchronous functions
     will be *note AsyncMock: 372.

          >>> 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='...'>

     3.8 版新加入.

      -- 成員函式: assert_awaited ()

          Assert that the mock was awaited at least once.  Note that
          this is separate from the object having been called, the
          ‘await’ keyword must be used:

               >>> 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()

      -- 成員函式: assert_awaited_once ()

          Assert that the mock was awaited exactly once.

               >>> 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.

      -- 成員函式: assert_awaited_with (*args, **kwargs)

          Assert that the last await was with the specified arguments.

               >>> 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')

      -- 成員函式: assert_awaited_once_with (*args, **kwargs)

          Assert that the mock was awaited exactly once and with the
          specified arguments.

               >>> 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.

      -- 成員函式: assert_any_await (*args, **kwargs)

          Assert the mock has ever been awaited with the specified
          arguments.

               >>> 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

      -- 成員函式: assert_has_awaits (calls, any_order=False)

          Assert the mock has been awaited with the specified calls.
          The *note await_args_list: 1069. list is checked for the
          awaits.

          If `any_order' is false then the awaits must be sequential.
          There can be extra calls before or after the specified awaits.

          If `any_order' is true then the awaits can be in any order,
          but they must all appear in *note await_args_list: 1069.

               >>> 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)

      -- 成員函式: assert_not_awaited ()

          Assert that the mock was never awaited.

               >>> mock = AsyncMock()
               >>> mock.assert_not_awaited()

      -- 成員函式: reset_mock (*args, **kwargs)

          See *note Mock.reset_mock(): 6a1.  Also sets *note
          await_count: 3541. to 0, *note await_args: 3542. to None, and
          clears the *note await_args_list: 1069.

      -- 屬性: await_count

          An integer keeping track of how many times the mock object has
          been awaited.

               >>> mock = AsyncMock()
               >>> async def main():
               ...     await mock()
               ...
               >>> asyncio.run(main())
               >>> mock.await_count
               1
               >>> asyncio.run(main())
               >>> mock.await_count
               2

      -- 屬性: await_args

          This is either ‘None’ (if the mock hasn’t been awaited), or
          the arguments that the mock was last awaited with.  Functions
          the same as *note Mock.call_args: 106a.

               >>> 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')

      -- 屬性: await_args_list

          This is a list of all the awaits made to the mock object in
          sequence (so the length of the list is the number of times it
          has been awaited).  Before any awaits have been made it is an
          empty list.

               >>> 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')]

* Menu:

* Calling::
* Deleting Attributes::
* Mock names and the name attribute::
* Attaching Mocks as Attributes::

   ---------- Footnotes ----------

   (1) (1) The only exceptions are magic methods and attributes (those
that have leading and trailing double underscores).  Mock doesn’t create
these but instead raises an *note AttributeError: 4a1.  This is because
the interpreter will often implicitly request these methods, and gets
`very' confused to get a new Mock object when it expects a magic method.
If you need magic method support see *note magic methods: 3520.


File: python.info,  Node: Calling,  Next: Deleting Attributes,  Up: Mock 类

5.26.9.3 Calling
................

Mock objects are callable.  The call will return the value set as the
*note return_value: 3527. attribute.  The default return value is a new
Mock object; it is created the first time the return value is accessed
(either explicitly or by calling the Mock) - but it is stored and the
same one returned each time.

Calls made to the object will be recorded in the attributes like *note
call_args: 106a. and *note call_args_list: 3535.

If *note side_effect: 3525. is set then it will be called after the call
has been recorded, so if ‘side_effect’ raises an exception the call is
still recorded.

The simplest way to make a mock raise an exception when called is to
make *note side_effect: 3525. an exception class or instance:

     >>> 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')]

If ‘side_effect’ is a function then whatever that function returns is
what calls to the mock return.  The ‘side_effect’ function is called
with the same arguments as the mock.  This allows you to vary the return
value of the call dynamically, based on the input:

     >>> 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)]

If you want the mock to still return the default return value (a new
mock), or any set return value, then there are two ways of doing this.
Either return ‘mock.return_value’ from inside ‘side_effect’, or return
*note DEFAULT: 3526.:

     >>> 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

To remove a ‘side_effect’, and return to the default behaviour, set the
‘side_effect’ to ‘None’:

     >>> 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

The ‘side_effect’ can also be any iterable object.  Repeated calls to
the mock will return values from the iterable (until the iterable is
exhausted and a *note StopIteration: 581. is raised):

     >>> m = MagicMock(side_effect=[1, 2, 3])
     >>> m()
     1
     >>> m()
     2
     >>> m()
     3
     >>> m()
     Traceback (most recent call last):
       ...
     StopIteration

If any members of the iterable are exceptions they will be raised
instead of returned:

     >>> iterable = (33, ValueError, 66)
     >>> m = MagicMock(side_effect=iterable)
     >>> m()
     33
     >>> m()
     Traceback (most recent call last):
      ...
     ValueError
     >>> m()
     66


File: python.info,  Node: Deleting Attributes,  Next: Mock names and the name attribute,  Prev: Calling,  Up: Mock 类

5.26.9.4 Deleting Attributes
............................

Mock objects create attributes on demand.  This allows them to pretend
to be objects of any type.

You may want a mock object to return ‘False’ to a *note hasattr(): 54a.
call, or raise an *note AttributeError: 4a1. when an attribute is
fetched.  You can do this by providing an object as a ‘spec’ for a mock,
but that isn’t always convenient.

You "block" attributes by deleting them.  Once deleted, accessing an
attribute will raise an *note AttributeError: 4a1.

     >>> 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


File: python.info,  Node: Mock names and the name attribute,  Next: Attaching Mocks as Attributes,  Prev: Deleting Attributes,  Up: Mock 类

5.26.9.5 Mock names and the name attribute
..........................................

Since "name" is an argument to the *note Mock: 373. constructor, if you
want your mock object to have a "name" attribute you can’t just pass it
in at creation time.  There are two alternatives.  One option is to use
*note configure_mock(): 3528.:

     >>> mock = MagicMock()
     >>> mock.configure_mock(name='my_name')
     >>> mock.name
     'my_name'

A simpler option is to simply set the "name" attribute after mock
creation:

     >>> mock = MagicMock()
     >>> mock.name = "foo"


File: python.info,  Node: Attaching Mocks as Attributes,  Prev: Mock names and the name attribute,  Up: Mock 类

5.26.9.6 Attaching Mocks as Attributes
......................................

When you attach a mock as an attribute of another mock (or as the return
value) it becomes a "child" of that mock.  Calls to the child are
recorded in the *note method_calls: 352f. and *note mock_calls: 352c.
attributes of the parent.  This is useful for configuring child mocks
and then attaching them to the parent, or for attaching mocks to a
parent that records all calls to the children and allows you to make
assertions about the order of calls between mocks:

     >>> 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)]

The exception to this is if the mock has a name.  This allows you to
prevent the "parenting" if for some reason you don’t want it to happen.

     >>> 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
     []

Mocks created for you by *note patch(): 877. are automatically given
names.  To attach mocks that have names to a parent you use the *note
attach_mock(): 352e. method:

     >>> 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')]


File: python.info,  Node: The patchers,  Next: MagicMock and magic method support,  Prev: Mock 类,  Up: unittest mock --- mock对象库

5.26.9.7 The patchers
.....................

The patch decorators are used for patching objects only within the scope
of the function they decorate.  They automatically handle the unpatching
for you, even if exceptions are raised.  All of these functions can also
be used in with statements or as class decorators.

* Menu:

* patch::
* patch.object: patch object.
* patch.dict: patch dict.
* patch.multiple: patch multiple.
* patch methods; start and stop: patch methods start and stop.
* patch builtins::
* TEST_PREFIX::
* Nesting Patch Decorators::
* Where to patch::
* Patching Descriptors and Proxy Objects::


File: python.info,  Node: patch,  Next: patch object,  Up: The patchers

5.26.9.8 patch
..............

     備註: The key is to do the patching in the right namespace.  See
     the section *note where to patch: 354a.

 -- 函式: unittest.mock.patch (target, new=DEFAULT, spec=None,
          create=False, spec_set=None, autospec=None, new_callable=None,
          **kwargs)

     *note patch(): 877. acts as a function decorator, class decorator
     or a context manager.  Inside the body of the function or with
     statement, the `target' is patched with a `new' object.  When the
     function/with statement exits the patch is undone.

     If `new' is omitted, then the target is replaced with an *note
     AsyncMock: 372. if the patched object is an async function or a
     *note MagicMock: 874. otherwise.  If *note patch(): 877. is used as
     a decorator and `new' is omitted, the created mock is passed in as
     an extra argument to the decorated function.  If *note patch():
     877. is used as a context manager the created mock is returned by
     the context manager.

     `target' should be a string in the form
     ‘'package.module.ClassName'’.  The `target' is imported and the
     specified object replaced with the `new' object, so the `target'
     must be importable from the environment you are calling *note
     patch(): 877. from.  The target is imported when the decorated
     function is executed, not at decoration time.

     The `spec' and `spec_set' keyword arguments are passed to the *note
     MagicMock: 874. if patch is creating one for you.

     In addition you can pass ‘spec=True’ or ‘spec_set=True’, which
     causes patch to pass in the object being mocked as the
     spec/spec_set object.

     `new_callable' allows you to specify a different class, or callable
     object, that will be called to create the `new' object.  By default
     *note AsyncMock: 372. is used for async functions and *note
     MagicMock: 874. for the rest.

     A more powerful form of `spec' is `autospec'.  If you set
     ‘autospec=True’ then the mock will be created with a spec from the
     object being replaced.  All attributes of the mock will also have
     the spec of the corresponding attribute of the object being
     replaced.  Methods and functions being mocked will have their
     arguments checked and will raise a *note TypeError: 1fe. if they
     are called with the wrong signature.  For mocks replacing a class,
     their return value (the ’instance’) will have the same spec as the
     class.  See the *note create_autospec(): 1087. function and *note
     Autospeccing: 3521.

     Instead of ‘autospec=True’ you can pass ‘autospec=some_object’ to
     use an arbitrary object as the spec instead of the one being
     replaced.

     By default *note patch(): 877. will fail to replace attributes that
     don’t exist.  If you pass in ‘create=True’, and the attribute
     doesn’t exist, patch will create the attribute for you when the
     patched function is called, and delete it again after the patched
     function has exited.  This is useful for writing tests against
     attributes that your production code creates at runtime.  It is off
     by default because it can be dangerous.  With it switched on you
     can write passing tests against APIs that don’t actually exist!

          備註: 
          3.5 版更變: If you are patching builtins in a module then you
          don’t need to pass ‘create=True’, it will be added by default.

     Patch can be used as a ‘TestCase’ class decorator.  It works by
     decorating each test method in the class.  This reduces the
     boilerplate code when your test methods share a common patchings
     set.  *note patch(): 877. finds tests by looking for method names
     that start with ‘patch.TEST_PREFIX’.  By default this is ‘'test'’,
     which matches the way *note unittest: 124. finds tests.  You can
     specify an alternative prefix by setting ‘patch.TEST_PREFIX’.

     Patch can be used as a context manager, with the with statement.
     Here the patching applies to the indented block after the with
     statement.  If you use "as" then the patched object will be bound
     to the name after the "as"; very useful if *note patch(): 877. is
     creating a mock object for you.

     *note patch(): 877. takes arbitrary keyword arguments.  These will
     be passed to *note AsyncMock: 372. if the patched object is
     asynchronous, to *note MagicMock: 874. otherwise or to
     `new_callable' if specified.

     ‘patch.dict(...)’, ‘patch.multiple(...)’ and ‘patch.object(...)’
     are available for alternate use-cases.

*note patch(): 877. as function decorator, creating the mock for you and
passing it into the decorated function:

     >>> @patch('__main__.SomeClass')
     ... def function(normal_argument, mock_class):
     ...     print(mock_class is SomeClass)
     ...
     >>> function(None)
     True

Patching a class replaces the class with a *note MagicMock: 874.
`instance'.  If the class is instantiated in the code under test then it
will be the *note return_value: 3527. of the mock that will be used.

If the class is instantiated multiple times you could use *note
side_effect: 3525. to return a new mock each time.  Alternatively you
can set the `return_value' to be anything you want.

To configure return values on methods of `instances' on the patched
class you must do this on the ‘return_value’.  For 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'
     ...

If you use `spec' or `spec_set' and *note patch(): 877. is replacing a
`class', then the return value of the created mock will have the same
spec.

     >>> Original = Class
     >>> patcher = patch('__main__.Class', spec=True)
     >>> MockClass = patcher.start()
     >>> instance = MockClass()
     >>> assert isinstance(instance, Original)
     >>> patcher.stop()

The `new_callable' argument is useful where you want to use an
alternative class to the default *note MagicMock: 874. for the created
mock.  For example, if you wanted a *note NonCallableMock: 3523. to be
used:

     >>> 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

Another use case might be to replace an object with an *note
io.StringIO: 91a. instance:

     >>> 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()

When *note patch(): 877. is creating a mock for you, it is common that
the first thing you need to do is to configure the mock.  Some of that
configuration can be done in the call to patch.  Any arbitrary keywords
you pass into the call will be used to set attributes on the created
mock:

     >>> patcher = patch('__main__.thing', first='one', second='two')
     >>> mock_thing = patcher.start()
     >>> mock_thing.first
     'one'
     >>> mock_thing.second
     'two'

As well as attributes on the created mock attributes, like the *note
return_value: 3527. and *note side_effect: 3525, of child mocks can also
be configured.  These aren’t syntactically valid to pass in directly as
keyword arguments, but a dictionary with these as keys can still be
expanded into a *note patch(): 877. call using ‘**’:

     >>> 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

By default, attempting to patch a function in a module (or a method or
an attribute in a class) that does not exist will fail with *note
AttributeError: 4a1.:

     >>> @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'

but adding ‘create=True’ in the call to *note patch(): 877. will make
the previous example work as expected:

     >>> @patch('sys.non_existing_attribute', 42, create=True)
     ... def test(mock_stdout):
     ...     assert sys.non_existing_attribute == 42
     ...
     >>> test()

3.8 版更變: *note patch(): 877. now returns an *note AsyncMock: 372. if
the target is an async function.


File: python.info,  Node: patch object,  Next: patch dict,  Prev: patch,  Up: The patchers

5.26.9.9 patch.object
.....................

 -- 函式: patch.object (target, attribute, new=DEFAULT, spec=None,
          create=False, spec_set=None, autospec=None, new_callable=None,
          **kwargs)

     patch the named member (`attribute') on an object (`target') with a
     mock object.

     *note patch.object(): 10b4. can be used as a decorator, class
     decorator or a context manager.  Arguments `new', `spec', `create',
     `spec_set', `autospec' and `new_callable' have the same meaning as
     for *note patch(): 877.  Like *note patch(): 877, *note
     patch.object(): 10b4. takes arbitrary keyword arguments for
     configuring the mock object it creates.

     When used as a class decorator *note patch.object(): 10b4. honours
     ‘patch.TEST_PREFIX’ for choosing which methods to wrap.

You can either call *note patch.object(): 10b4. with three arguments or
two arguments.  The three argument form takes the object to be patched,
the attribute name and the object to replace the attribute with.

When calling with the two argument form you omit the replacement object,
and a mock is created for you and passed in as an extra argument to the
decorated function:

     >>> @patch.object(SomeClass, 'class_method')
     ... def test(mock_method):
     ...     SomeClass.class_method(3)
     ...     mock_method.assert_called_with(3)
     ...
     >>> test()

`spec', `create' and the other arguments to *note patch.object(): 10b4.
have the same meaning as they do for *note patch(): 877.


File: python.info,  Node: patch dict,  Next: patch multiple,  Prev: patch object,  Up: The patchers

5.26.9.10 patch.dict
....................

 -- 函式: patch.dict (in_dict, values=(), clear=False, **kwargs)

     Patch a dictionary, or dictionary like object, and restore the
     dictionary to its original state after the test.

     `in_dict' can be a dictionary or a mapping like container.  If it
     is a mapping then it must at least support getting, setting and
     deleting items plus iterating over keys.

     `in_dict' can also be a string specifying the name of the
     dictionary, which will then be fetched by importing it.

     `values' can be a dictionary of values to set in the dictionary.
     `values' can also be an iterable of ‘(key, value)’ pairs.

     If `clear' is true then the dictionary will be cleared before the
     new values are set.

     *note patch.dict(): 110a. can also be called with arbitrary keyword
     arguments to set values in the dictionary.

     3.8 版更變: *note patch.dict(): 110a. now returns the patched
     dictionary when used as a context manager.

*note patch.dict(): 110a. can be used as a context manager, decorator or
class decorator:

     >>> foo = {}
     >>> @patch.dict(foo, {'newkey': 'newvalue'})
     ... def test():
     ...     assert foo == {'newkey': 'newvalue'}
     >>> test()
     >>> assert foo == {}

When used as a class decorator *note patch.dict(): 110a. honours
‘patch.TEST_PREFIX’ (default to ‘'test'’) for choosing which methods to
wrap:

     >>> 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')

If you want to use a different prefix for your test, you can inform the
patchers of the different prefix by setting ‘patch.TEST_PREFIX’.  For
more details about how to change the value of see *note TEST_PREFIX:
354d.

*note patch.dict(): 110a. can be used to add members to a dictionary, or
simply let a test change a dictionary, and ensure the dictionary is
restored when the test ends.

     >>> 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 == {}

     >>> import os
     >>> with patch.dict('os.environ', {'newkey': 'newvalue'}):
     ...     print(os.environ['newkey'])
     ...
     newvalue
     >>> assert 'newkey' not in os.environ

Keywords can be used in the *note patch.dict(): 110a. call to set values
in the dictionary:

     >>> mymodule = MagicMock()
     >>> mymodule.function.return_value = 'fish'
     >>> with patch.dict('sys.modules', mymodule=mymodule):
     ...     import mymodule
     ...     mymodule.function('some', 'args')
     ...
     'fish'

*note patch.dict(): 110a. can be used with dictionary like objects that
aren’t actually dictionaries.  At the very minimum they must support
item getting, setting, deleting and either iteration or membership test.
This corresponds to the magic methods *note __getitem__(): 3a5, *note
__setitem__(): d2a, *note __delitem__(): d2b. and either *note
__iter__(): 608. or *note __contains__(): dee.

     >>> 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']


File: python.info,  Node: patch multiple,  Next: patch methods start and stop,  Prev: patch dict,  Up: The patchers

5.26.9.11 patch.multiple
........................

 -- 函式: patch.multiple (target, spec=None, create=False,
          spec_set=None, autospec=None, new_callable=None, **kwargs)

     Perform multiple patches in a single call.  It takes the object to
     be patched (either as an object or a string to fetch the object by
     importing) and keyword arguments for the patches:

          with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
              ...

     Use *note DEFAULT: 3526. as the value if you want *note
     patch.multiple(): 354f. to create mocks for you.  In this case the
     created mocks are passed into a decorated function by keyword, and
     a dictionary is returned when *note patch.multiple(): 354f. is used
     as a context manager.

     *note patch.multiple(): 354f. can be used as a decorator, class
     decorator or a context manager.  The arguments `spec', `spec_set',
     `create', `autospec' and `new_callable' have the same meaning as
     for *note patch(): 877.  These arguments will be applied to `all'
     patches done by *note patch.multiple(): 354f.

     When used as a class decorator *note patch.multiple(): 354f.
     honours ‘patch.TEST_PREFIX’ for choosing which methods to wrap.

If you want *note patch.multiple(): 354f. to create mocks for you, then
you can use *note DEFAULT: 3526. as the value.  If you use *note
patch.multiple(): 354f. as a decorator then the created mocks are passed
into the decorated function by keyword.

     >>> 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()

*note patch.multiple(): 354f. can be nested with other ‘patch’
decorators, but put arguments passed by keyword `after' any of the
standard arguments created by *note patch(): 877.:

     >>> @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()

If *note patch.multiple(): 354f. is used as a context manager, the value
returned by the context manager is a dictionary where created mocks are
keyed by name:

     >>> 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
     ...


File: python.info,  Node: patch methods start and stop,  Next: patch builtins,  Prev: patch multiple,  Up: The patchers

5.26.9.12 patch methods: start and stop
.......................................

All the patchers have ‘start()’ and ‘stop()’ methods.  These make it
simpler to do patching in ‘setUp’ methods or where you want to do
multiple patches without nesting decorators or with statements.

To use them call *note patch(): 877, *note patch.object(): 10b4. or
*note patch.dict(): 110a. as normal and keep a reference to the returned
‘patcher’ object.  You can then call ‘start()’ to put the patch in place
and ‘stop()’ to undo it.

If you are using *note patch(): 877. to create a mock for you then it
will be returned by the call to ‘patcher.start’.

     >>> 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

A typical use case for this might be for doing multiple patches in the
‘setUp’ method of a ‘TestCase’:

     >>> 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()

     警示: If you use this technique you must ensure that the patching
     is "undone" by calling ‘stop’.  This can be fiddlier than you might
     think, because if an exception is raised in the ‘setUp’ then
     ‘tearDown’ is not called.  *note unittest.TestCase.addCleanup():
     3c5. makes this easier:

          >>> 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
          ...

     As an added bonus you no longer need to keep a reference to the
     ‘patcher’ object.

It is also possible to stop all patches which have been started by using
*note patch.stopall(): 3552.

 -- 函式: patch.stopall ()

     Stop all active patches.  Only stops patches started with ‘start’.


File: python.info,  Node: patch builtins,  Next: TEST_PREFIX,  Prev: patch methods start and stop,  Up: The patchers

5.26.9.13 patch builtins
........................

You can patch any builtins within a module.  The following example
patches builtin *note ord(): 1559.:

     >>> @patch('__main__.ord')
     ... def test(mock_ord):
     ...     mock_ord.return_value = 101
     ...     print(ord('c'))
     ...
     >>> test()
     101


File: python.info,  Node: TEST_PREFIX,  Next: Nesting Patch Decorators,  Prev: patch builtins,  Up: The patchers

5.26.9.14 TEST_PREFIX
.....................

All of the patchers can be used as class decorators.  When used in this
way they wrap every test method on the class.  The patchers recognise
methods that start with ‘'test'’ as being test methods.  This is the
same way that the *note unittest.TestLoader: 871. finds test methods by
default.

It is possible that you want to use a different prefix for your tests.
You can inform the patchers of the different prefix by setting
‘patch.TEST_PREFIX’:

     >>> 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


File: python.info,  Node: Nesting Patch Decorators,  Next: Where to patch,  Prev: TEST_PREFIX,  Up: The patchers

5.26.9.15 Nesting Patch Decorators
..................................

If you want to perform multiple patches then you can simply stack up the
decorators.

You can stack up multiple patch decorators using this pattern:

     >>> @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')

Note that the decorators are applied from the bottom upwards.  This is
the standard way that Python applies decorators.  The order of the
created mocks passed into your test function matches this order.


File: python.info,  Node: Where to patch,  Next: Patching Descriptors and Proxy Objects,  Prev: Nesting Patch Decorators,  Up: The patchers

5.26.9.16 Where to patch
........................

*note patch(): 877. works by (temporarily) changing the object that a
`name' points to with another one.  There can be many names pointing to
any individual object, so for patching to work you must ensure that you
patch the name used by the system under test.

The basic principle is that you patch where an object is `looked up',
which is not necessarily the same place as where it is defined.  A
couple of examples will help to clarify this.

Imagine we have a project that we want to test with the following
structure:

     a.py
         -> Defines SomeClass

     b.py
         -> from a import SomeClass
         -> some_function instantiates SomeClass

Now we want to test ‘some_function’ but we want to mock out ‘SomeClass’
using *note patch(): 877.  The problem is that when we import module b,
which we will have to do then it imports ‘SomeClass’ from module a.  If
we use *note patch(): 877. to mock out ‘a.SomeClass’ then it will have
no effect on our test; module b already has a reference to the `real'
‘SomeClass’ and it looks like our patching had no effect.

The key is to patch out ‘SomeClass’ where it is used (or where it is
looked up).  In this case ‘some_function’ will actually look up
‘SomeClass’ in module b, where we have imported it.  The patching should
look like:

     @patch('b.SomeClass')

However, consider the alternative scenario where instead of ‘from a
import SomeClass’ module b does ‘import a’ and ‘some_function’ uses
‘a.SomeClass’.  Both of these import forms are common.  In this case the
class we want to patch is being looked up in the module and so we have
to patch ‘a.SomeClass’ instead:

     @patch('a.SomeClass')


File: python.info,  Node: Patching Descriptors and Proxy Objects,  Prev: Where to patch,  Up: The patchers

5.26.9.17 Patching Descriptors and Proxy Objects
................................................

Both *note patch: 3549. and *note patch.object: 354b. correctly patch
and restore descriptors: class methods, static methods and properties.
You should patch these on the `class' rather than an instance.  They
also work with `some' objects that proxy attribute access, like the
django settings object(1).

   ---------- Footnotes ----------

   (1) 
http://www.voidspace.org.uk/python/weblog/arch_d7_2010_12_04.shtml#e1198


File: python.info,  Node: MagicMock and magic method support,  Next: Helpers,  Prev: The patchers,  Up: unittest mock --- mock对象库

5.26.9.18 MagicMock and magic method support
............................................

* Menu:

* Mocking Magic Methods::
* Magic Mock::


File: python.info,  Node: Mocking Magic Methods,  Next: Magic Mock,  Up: MagicMock and magic method support

5.26.9.19 Mocking Magic Methods
...............................

*note Mock: 373. supports mocking the Python protocol methods, also
known as "magic methods".  This allows mock objects to replace
containers or other objects that implement Python protocols.

Because magic methods are looked up differently from normal methods (1),
this support has been specially implemented.  This means that only
specific magic methods are supported.  The supported list includes
`almost' all of them.  If there are any missing that you need please let
us know.

You mock magic methods by setting the method you are interested in to a
function or a mock instance.  If you are using a function then it `must'
take ‘self’ as the first argument (2).

     >>> def __str__(self):
     ...     return 'fooble'
     ...
     >>> mock = Mock()
     >>> mock.__str__ = __str__
     >>> str(mock)
     'fooble'

     >>> mock = Mock()
     >>> mock.__str__ = Mock()
     >>> mock.__str__.return_value = 'fooble'
     >>> str(mock)
     'fooble'

     >>> mock = Mock()
     >>> mock.__iter__ = Mock(return_value=iter([]))
     >>> list(mock)
     []

One use case for this is for mocking objects used as context managers in
a *note with: 7da. statement:

     >>> 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)

Calls to magic methods do not appear in *note method_calls: 352f, but
they are recorded in *note mock_calls: 352c.

     備註: If you use the `spec' keyword argument to create a mock then
     attempting to set a magic method that isn’t in the spec will raise
     an *note AttributeError: 4a1.

The full list of supported magic methods is:

   * ‘__hash__’, ‘__sizeof__’, ‘__repr__’ and ‘__str__’

   * ‘__dir__’, ‘__format__’ and ‘__subclasses__’

   * ‘__round__’, ‘__floor__’, ‘__trunc__’ and ‘__ceil__’

   * Comparisons: ‘__lt__’, ‘__gt__’, ‘__le__’, ‘__ge__’, ‘__eq__’ and
     ‘__ne__’

   * Container methods: ‘__getitem__’, ‘__setitem__’, ‘__delitem__’,
     ‘__contains__’, ‘__len__’, ‘__iter__’, ‘__reversed__’ and
     ‘__missing__’

   * Context manager: ‘__enter__’, ‘__exit__’, ‘__aenter__’ and
     ‘__aexit__’

   * Unary numeric methods: ‘__neg__’, ‘__pos__’ and ‘__invert__’

   * The numeric methods (including right hand and in-place variants):
     ‘__add__’, ‘__sub__’, ‘__mul__’, ‘__matmul__’, ‘__div__’,
     ‘__truediv__’, ‘__floordiv__’, ‘__mod__’, ‘__divmod__’,
     ‘__lshift__’, ‘__rshift__’, ‘__and__’, ‘__xor__’, ‘__or__’, and
     ‘__pow__’

   * Numeric conversion methods: ‘__complex__’, ‘__int__’, ‘__float__’
     and ‘__index__’

   * Descriptor methods: ‘__get__’, ‘__set__’ and ‘__delete__’

   * Pickling: ‘__reduce__’, ‘__reduce_ex__’, ‘__getinitargs__’,
     ‘__getnewargs__’, ‘__getstate__’ and ‘__setstate__’

   * File system path representation: ‘__fspath__’

   * Asynchronous iteration methods: ‘__aiter__’ and ‘__anext__’

3.8 版更變: Added support for *note os.PathLike.__fspath__(): 5e6.

3.8 版更變: Added support for ‘__aenter__’, ‘__aexit__’, ‘__aiter__’ and
‘__anext__’.

The following methods exist but are `not' supported as they are either
in use by mock, can’t be set dynamically, or can cause problems:

   * ‘__getattr__’, ‘__setattr__’, ‘__init__’ and ‘__new__’

   * ‘__prepare__’, ‘__instancecheck__’, ‘__subclasscheck__’, ‘__del__’

   ---------- Footnotes ----------

   (1) (2) Magic methods `should' be looked up on the class rather than
the instance.  Different versions of Python are inconsistent about
applying this rule.  The supported protocol methods should work with all
supported versions of Python.

   (2) (3) The function is basically hooked up to the class, but each
‘Mock’ instance is kept isolated from the others.


File: python.info,  Node: Magic Mock,  Prev: Mocking Magic Methods,  Up: MagicMock and magic method support

5.26.9.20 Magic Mock
....................

There are two ‘MagicMock’ variants: *note MagicMock: 874. and *note
NonCallableMagicMock: 3524.

 -- 類別: unittest.mock.MagicMock (*args, **kw)

     ‘MagicMock’ is a subclass of *note Mock: 373. with default
     implementations of most of the magic methods.  You can use
     ‘MagicMock’ without having to configure the magic methods yourself.

     The constructor parameters have the same meaning as for *note Mock:
     373.

     If you use the `spec' or `spec_set' arguments then `only' magic
     methods that exist in the spec will be created.

 -- 類別: unittest.mock.NonCallableMagicMock (*args, **kw)

     A non-callable version of *note MagicMock: 874.

     The constructor parameters have the same meaning as for *note
     MagicMock: 874, with the exception of `return_value' and
     `side_effect' which have no meaning on a non-callable mock.

The magic methods are setup with *note MagicMock: 874. objects, so you
can configure them and use them in the usual way:

     >>> mock = MagicMock()
     >>> mock[3] = 'fish'
     >>> mock.__setitem__.assert_called_with(3, 'fish')
     >>> mock.__getitem__.return_value = 'result'
     >>> mock[2]
     'result'

By default many of the protocol methods are required to return objects
of a specific type.  These methods are preconfigured with a default
return value, so that they can be used without you having to do anything
if you aren’t interested in the return value.  You can still `set' the
return value manually if you want to change the default.

Methods and their defaults:

   * ‘__lt__’: ‘NotImplemented’

   * ‘__gt__’: ‘NotImplemented’

   * ‘__le__’: ‘NotImplemented’

   * ‘__ge__’: ‘NotImplemented’

   * ‘__int__’: ‘1’

   * ‘__contains__’: ‘False’

   * ‘__len__’: ‘0’

   * ‘__iter__’: ‘iter([])’

   * ‘__exit__’: ‘False’

   * ‘__aexit__’: ‘False’

   * ‘__complex__’: ‘1j’

   * ‘__float__’: ‘1.0’

   * ‘__bool__’: ‘True’

   * ‘__index__’: ‘1’

   * ‘__hash__’: default hash for the mock

   * ‘__str__’: default str for the mock

   * ‘__sizeof__’: default sizeof for the mock

例如:

     >>> mock = MagicMock()
     >>> int(mock)
     1
     >>> len(mock)
     0
     >>> list(mock)
     []
     >>> object() in mock
     False

The two equality methods, *note __eq__(): 44b. and *note __ne__(): f18,
are special.  They do the default equality comparison on identity, using
the *note side_effect: 3525. attribute, unless you change their return
value to return something else:

     >>> MagicMock() == 3
     False
     >>> MagicMock() != 3
     True
     >>> mock = MagicMock()
     >>> mock.__eq__.return_value = True
     >>> mock == 3
     True

The return value of ‘MagicMock.__iter__()’ can be any iterable object
and isn’t required to be an iterator:

     >>> mock = MagicMock()
     >>> mock.__iter__.return_value = ['a', 'b', 'c']
     >>> list(mock)
     ['a', 'b', 'c']
     >>> list(mock)
     ['a', 'b', 'c']

If the return value `is' an iterator, then iterating over it once will
consume it and subsequent iterations will result in an empty list:

     >>> mock.__iter__.return_value = iter(['a', 'b', 'c'])
     >>> list(mock)
     ['a', 'b', 'c']
     >>> list(mock)
     []

‘MagicMock’ has all of the supported magic methods configured except for
some of the obscure and obsolete ones.  You can still set these up if
you want.

Magic methods that are supported but not setup by default in ‘MagicMock’
are:

   * ‘__subclasses__’

   * ‘__dir__’

   * ‘__format__’

   * ‘__get__’, ‘__set__’ and ‘__delete__’

   * ‘__reversed__’ and ‘__missing__’

   * ‘__reduce__’, ‘__reduce_ex__’, ‘__getinitargs__’, ‘__getnewargs__’,
     ‘__getstate__’ and ‘__setstate__’

   * ‘__getformat__’ and ‘__setformat__’


File: python.info,  Node: Helpers,  Prev: MagicMock and magic method support,  Up: unittest mock --- mock对象库

5.26.9.21 Helpers
.................

* Menu:

* sentinel::
* DEFAULT::
* call::
* create_autospec::
* ANY::
* FILTER_DIR::
* mock_open::
* Autospeccing::
* Sealing mocks::


File: python.info,  Node: sentinel,  Next: DEFAULT,  Up: Helpers

5.26.9.22 sentinel
..................

 -- Data: unittest.mock.sentinel

     The ‘sentinel’ object provides a convenient way of providing unique
     objects for your tests.

     Attributes are created on demand when you access them by name.
     Accessing the same attribute will always return the same object.
     The objects returned have a sensible repr so that test failure
     messages are readable.

     3.7 版更變: The ‘sentinel’ attributes now preserve their identity
     when they are *note copied: 25. or *note pickled: ca.

Sometimes when testing you need to test that a specific object is passed
as an argument to another method, or returned.  It can be common to
create named sentinel objects to test this.  *note sentinel: 50e.
provides a convenient way of creating and testing the identity of
objects like this.

In this example we monkey patch ‘method’ to return
‘sentinel.some_object’:

     >>> 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


File: python.info,  Node: DEFAULT,  Next: call,  Prev: sentinel,  Up: Helpers

5.26.9.23 DEFAULT
.................

 -- Data: unittest.mock.DEFAULT

     The *note DEFAULT: 3526. object is a pre-created sentinel (actually
     ‘sentinel.DEFAULT’).  It can be used by *note side_effect: 3525.
     functions to indicate that the normal return value should be used.


File: python.info,  Node: call,  Next: create_autospec,  Prev: DEFAULT,  Up: Helpers

5.26.9.24 call
..............

 -- 函式: unittest.mock.call (*args, **kwargs)

     *note call(): 10cc. is a helper object for making simpler
     assertions, for comparing with *note call_args: 106a, *note
     call_args_list: 3535, *note mock_calls: 352c. and *note
     method_calls: 352f.  *note call(): 10cc. can also be used with
     *note assert_has_calls(): 352b.

          >>> 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

 -- 成員函式: call.call_list ()

     For a call object that represents multiple calls, *note
     call_list(): 355f. returns a list of all the intermediate calls as
     well as the final call.

‘call_list’ is particularly useful for making assertions on "chained
calls".  A chained call is multiple calls on a single line of code.
This results in multiple entries in *note mock_calls: 352c. on a mock.
Manually constructing the sequence of calls can be tedious.

*note call_list(): 355f. can construct the sequence of calls from the
same chained call:

     >>> 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
A ‘call’ object is either a tuple of (positional args, keyword args) or
(name, positional args, keyword args) depending on how it was
constructed.  When you construct them yourself this isn’t particularly
interesting, but the ‘call’ objects that are in the *note
Mock.call_args: 106a, *note Mock.call_args_list: 3535. and *note
Mock.mock_calls: 352c. attributes can be introspected to get at the
individual arguments they contain.

The ‘call’ objects in *note Mock.call_args: 106a. and *note
Mock.call_args_list: 3535. are two-tuples of (positional args, keyword
args) whereas the ‘call’ objects in *note Mock.mock_calls: 352c, along
with ones you construct yourself, are three-tuples of (name, positional
args, keyword args).

You can use their "tupleness" to pull out the individual arguments for
more complex introspection and assertions.  The positional arguments are
a tuple (an empty tuple if there are no positional arguments) and the
keyword arguments are a dictionary:

     >>> 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

     >>> 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


File: python.info,  Node: create_autospec,  Next: ANY,  Prev: call,  Up: Helpers

5.26.9.25 create_autospec
.........................

 -- 函式: unittest.mock.create_autospec (spec, spec_set=False,
          instance=False, **kwargs)

     Create a mock object using another object as a spec.  Attributes on
     the mock will use the corresponding attribute on the `spec' object
     as their spec.

     Functions or methods being mocked will have their arguments checked
     to ensure that they are called with the correct signature.

     If `spec_set' is ‘True’ then attempting to set attributes that
     don’t exist on the spec object will raise an *note AttributeError:
     4a1.

     If a class is used as a spec then the return value of the mock (the
     instance of the class) will have the same spec.  You can use a
     class as the spec for an instance object by passing
     ‘instance=True’.  The returned mock will only be callable if
     instances of the mock are callable.

     *note create_autospec(): 1087. also takes arbitrary keyword
     arguments that are passed to the constructor of the created mock.

See *note Autospeccing: 3521. for examples of how to use auto-speccing
with *note create_autospec(): 1087. and the `autospec' argument to *note
patch(): 877.

3.8 版更變: *note create_autospec(): 1087. now returns an *note
AsyncMock: 372. if the target is an async function.


File: python.info,  Node: ANY,  Next: FILTER_DIR,  Prev: create_autospec,  Up: Helpers

5.26.9.26 ANY
.............

 -- Data: unittest.mock.ANY

Sometimes you may need to make assertions about `some' of the arguments
in a call to mock, but either not care about some of the arguments or
want to pull them individually out of *note call_args: 106a. and make
more complex assertions on them.

To ignore certain arguments you can pass in objects that compare equal
to `everything'.  Calls to *note assert_called_with(): 113a. and *note
assert_called_once_with(): 3529. will then succeed no matter what was
passed in.

     >>> mock = Mock(return_value=None)
     >>> mock('foo', bar=object())
     >>> mock.assert_called_once_with('foo', bar=ANY)

*note ANY: 10d1. can also be used in comparisons with call lists like
*note mock_calls: 352c.:

     >>> m = MagicMock(return_value=None)
     >>> m(1)
     >>> m(1, 2)
     >>> m(object())
     >>> m.mock_calls == [call(1), call(1, 2), ANY]
     True


File: python.info,  Node: FILTER_DIR,  Next: mock_open,  Prev: ANY,  Up: Helpers

5.26.9.27 FILTER_DIR
....................

 -- Data: unittest.mock.FILTER_DIR

*note FILTER_DIR: 3531. is a module level variable that controls the way
mock objects respond to *note dir(): df9. (only for Python 2.6 or more
recent).  The default is ‘True’, which uses the filtering described
below, to only show useful members.  If you dislike this filtering, or
need to switch it off for diagnostic purposes, then set ‘mock.FILTER_DIR
= False’.

With filtering on, ‘dir(some_mock)’ shows only useful attributes and
will include any dynamically created attributes that wouldn’t normally
be shown.  If the mock was created with a `spec' (or `autospec' of
course) then all the attributes from the original are shown, even if
they haven’t been accessed yet:

     >>> 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',
      ...

Many of the not-very-useful (private to *note Mock: 373. rather than the
thing being mocked) underscore and double underscore prefixed attributes
have been filtered from the result of calling *note dir(): df9. on a
*note Mock: 373.  If you dislike this behaviour you can switch it off by
setting the module level switch *note FILTER_DIR: 3531.:

     >>> 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__',
      ...

Alternatively you can just use ‘vars(my_mock)’ (instance members) and
‘dir(type(my_mock))’ (type members) to bypass the filtering irrespective
of ‘mock.FILTER_DIR’.


File: python.info,  Node: mock_open,  Next: Autospeccing,  Prev: FILTER_DIR,  Up: Helpers

5.26.9.28 mock_open
...................

 -- 函式: unittest.mock.mock_open (mock=None, read_data=None)

     A helper function to create a mock to replace the use of *note
     open(): 16f.  It works for *note open(): 16f. called directly or
     used as a context manager.

     The `mock' argument is the mock object to configure.  If ‘None’
     (the default) then a *note MagicMock: 874. will be created for you,
     with the API limited to methods or attributes available on standard
     file handles.

     `read_data' is a string for the ‘read()’, *note readline(): 1849,
     and *note readlines(): 18d6. methods of the file handle to return.
     Calls to those methods will take data from `read_data' until it is
     depleted.  The mock of these methods is pretty simplistic: every
     time the `mock' is called, the `read_data' is rewound to the start.
     If you need more control over the data that you are feeding to the
     tested code you will need to customize this mock for yourself.
     When that is insufficient, one of the in-memory filesystem packages
     on PyPI(1) can offer a realistic filesystem for testing.

     3.4 版更變: Added *note readline(): 1849. and *note readlines():
     18d6. support.  The mock of ‘read()’ changed to consume `read_data'
     rather than returning it on each call.

     3.5 版更變: `read_data' is now reset on each call to the `mock'.

     3.8 版更變: Added *note __iter__(): 608. to implementation so that
     iteration (such as in for loops) correctly consumes `read_data'.

Using *note open(): 16f. as a context manager is a great way to ensure
your file handles are closed properly and is becoming common:

     with open('/some/path', 'w') as f:
         f.write('something')

The issue is that even if you mock out the call to *note open(): 16f. it
is the `returned object' that is used as a context manager (and has
*note __enter__(): d5d. and *note __exit__(): d5e. called).

Mocking context managers with a *note MagicMock: 874. is common enough
and fiddly enough that a helper function is useful.

     >>> 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')

And for reading files:

     >>> 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'

   ---------- Footnotes ----------

   (1) https://pypi.org


File: python.info,  Node: Autospeccing,  Next: Sealing mocks,  Prev: mock_open,  Up: Helpers

5.26.9.29 Autospeccing
......................

Autospeccing is based on the existing ‘spec’ feature of mock.  It limits
the api of mocks to the api of an original object (the spec), but it is
recursive (implemented lazily) so that attributes of mocks only have the
same api as the attributes of the spec.  In addition mocked functions /
methods have the same call signature as the original so they raise a
*note TypeError: 1fe. if they are called incorrectly.

Before I explain how auto-speccing works, here’s why it is needed.

*note Mock: 373. is a very powerful and flexible object, but it suffers
from two flaws when used to mock out objects from a system under test.
One of these flaws is specific to the *note Mock: 373. api and the other
is a more general problem with using mock objects.

First the problem specific to *note Mock: 373.  *note Mock: 373. has two
assert methods that are extremely handy: *note assert_called_with():
113a. and *note assert_called_once_with(): 3529.

     >>> 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.

Because mocks auto-create attributes on demand, and allow you to call
them with arbitrary arguments, if you misspell one of these assert
methods then your assertion is gone:

     >>> mock = Mock(name='Thing', return_value=None)
     >>> mock(1, 2, 3)
     >>> mock.assret_called_once_with(4, 5, 6)

Your tests can pass silently and incorrectly because of the typo.

The second issue is more general to mocking.  If you refactor some of
your code, rename members and so on, any tests for code that is still
using the `old api' but uses mocks instead of the real objects will
still pass.  This means your tests can all pass even though your code is
broken.

Note that this is another reason why you need integration tests as well
as unit tests.  Testing everything in isolation is all fine and dandy,
but if you don’t test how your units are "wired together" there is still
lots of room for bugs that tests might have caught.

‘mock’ already provides a feature to help with this, called speccing.
If you use a class or instance as the ‘spec’ for a mock then you can
only access attributes on the mock that exist on the real class:

     >>> from urllib import request
     >>> mock = Mock(spec=request.Request)
     >>> mock.assret_called_with
     Traceback (most recent call last):
      ...
     AttributeError: Mock object has no attribute 'assret_called_with'

The spec only applies to the mock itself, so we still have the same
issue with any methods on the mock:

     >>> mock.has_data()
     <mock.Mock object at 0x...>
     >>> mock.has_data.assret_called_with()

Auto-speccing solves this problem.  You can either pass ‘autospec=True’
to *note patch(): 877. / *note patch.object(): 10b4. or use the *note
create_autospec(): 1087. function to create a mock with a spec.  If you
use the ‘autospec=True’ argument to *note patch(): 877. then the object
that is being replaced will be used as the spec object.  Because the
speccing is done "lazily" (the spec is created as attributes on the mock
are accessed) you can use it with very complex or deeply nested objects
(like modules that import modules that import modules) without a big
performance hit.

Here’s an example of it in use:

     >>> 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='...'>

You can see that ‘request.Request’ has a spec.  ‘request.Request’ takes
two arguments in the constructor (one of which is `self').  Here’s what
happens if we try to call it incorrectly:

     >>> req = request.Request()
     Traceback (most recent call last):
      ...
     TypeError: <lambda>() takes at least 2 arguments (1 given)

The spec also applies to instantiated classes (i.e.  the return value of
specced mocks):

     >>> req = request.Request('foo')
     >>> req
     <NonCallableMagicMock name='request.Request()' spec='Request' id='...'>

‘Request’ objects are not callable, so the return value of instantiating
our mocked out ‘request.Request’ is a non-callable mock.  With the spec
in place any typos in our asserts will raise the correct error:

     >>> req.add_header('spam', 'eggs')
     <MagicMock name='request.Request().add_header()' id='...'>
     >>> req.add_header.assret_called_with
     Traceback (most recent call last):
      ...
     AttributeError: Mock object has no attribute 'assret_called_with'
     >>> req.add_header.assert_called_with('spam', 'eggs')

In many cases you will just be able to add ‘autospec=True’ to your
existing *note patch(): 877. calls and then be protected against bugs
due to typos and api changes.

As well as using `autospec' through *note patch(): 877. there is a *note
create_autospec(): 1087. for creating autospecced mocks directly:

     >>> from urllib import request
     >>> mock_request = create_autospec(request)
     >>> mock_request.Request('foo', 'bar')
     <NonCallableMagicMock name='mock.Request()' spec='Request' id='...'>

This isn’t without caveats and limitations however, which is why it is
not the default behaviour.  In order to know what attributes are
available on the spec object, autospec has to introspect (access
attributes) the spec.  As you traverse attributes on the mock a
corresponding traversal of the original object is happening under the
hood.  If any of your specced objects have properties or descriptors
that can trigger code execution then you may not be able to use
autospec.  On the other hand it is much better to design your objects so
that introspection is safe (1).

A more serious problem is that it is common for instance attributes to
be created in the *note __init__(): e23. method and not to exist on the
class at all.  `autospec' can’t know about any dynamically created
attributes and restricts the api to visible attributes.

     >>> 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'

There are a few different ways of resolving this problem.  The easiest,
but not necessarily the least annoying, way is to simply set the
required attributes on the mock after creation.  Just because `autospec'
doesn’t allow you to fetch attributes that don’t exist on the spec it
doesn’t prevent you setting them:

     >>> with patch('__main__.Something', autospec=True):
     ...   thing = Something()
     ...   thing.a = 33
     ...

There is a more aggressive version of both `spec' and `autospec' that
`does' prevent you setting non-existent attributes.  This is useful if
you want to ensure your code only `sets' valid attributes too, but
obviously it prevents this particular scenario:

     >>> 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'

Probably the best way of solving the problem is to add class attributes
as default values for instance members initialised in *note __init__():
e23.  Note that if you are only setting default attributes in *note
__init__(): e23. then providing them via class attributes (shared
between instances of course) is faster too.  e.g.

     class Something:
         a = 33

This brings up another issue.  It is relatively common to provide a
default value of ‘None’ for members that will later be an object of a
different type.  ‘None’ would be useless as a spec because it wouldn’t
let you access `any' attributes or methods on it.  As ‘None’ is `never'
going to be useful as a spec, and probably indicates a member that will
normally of some other type, autospec doesn’t use a spec for members
that are set to ‘None’.  These will just be ordinary mocks (well -
MagicMocks):

     >>> class Something:
     ...     member = None
     ...
     >>> mock = create_autospec(Something)
     >>> mock.member.foo.bar.baz()
     <MagicMock name='mock.member.foo.bar.baz()' id='...'>

If modifying your production classes to add defaults isn’t to your
liking then there are more options.  One of these is simply to use an
instance as the spec rather than the class.  The other is to create a
subclass of the production class and add the defaults to the subclass
without affecting the production class.  Both of these require you to
use an alternative object as the spec.  Thankfully *note patch(): 877.
supports this - you can simply pass the alternative object as the
`autospec' argument:

     >>> 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='...'>

   ---------- Footnotes ----------

   (1) (4) This only applies to classes or already instantiated objects.
Calling a mocked class to create a mock instance `does not' create a
real instance.  It is only attribute lookups - along with calls to *note
dir(): df9. - that are done.


File: python.info,  Node: Sealing mocks,  Prev: Autospeccing,  Up: Helpers

5.26.9.30 Sealing mocks
.......................

 -- 函式: unittest.mock.seal (mock)

     Seal will disable the automatic creation of mocks when accessing an
     attribute of the mock being sealed or any of its attributes that
     are already mocks recursively.

     If a mock instance with a name or a spec is assigned to an
     attribute it won’t be considered in the sealing chain.  This allows
     one to prevent seal from fixing part of the mock object.

          >>> 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.

     3.7 版新加入.


File: python.info,  Node: unittest mock 上手指南,  Next: 2to3 - 自動將 Python 2的程式碼轉成 Python 3,  Prev: unittest mock --- mock对象库,  Up: 開發工具

5.26.10 ‘unittest.mock’ 上手指南
--------------------------------

3.3 版新加入.

* Menu:

* 使用 mock::
* Patch Decorators::
* Further Examples::


File: python.info,  Node: 使用 mock,  Next: Patch Decorators,  Up: unittest mock 上手指南

5.26.10.1 使用 mock
...................

* Menu:

* 模拟方法调用::
* 对象上的方法调用的 mock::
* Mocking Classes::
* Naming your mocks::
* Tracking all Calls::
* Setting Return Values and Attributes::
* Raising exceptions with mocks::
* Side effect functions and iterables::
* Mocking asynchronous iterators::
* Mocking asynchronous context manager::
* Creating a Mock from an Existing Object::


File: python.info,  Node: 模拟方法调用,  Next: 对象上的方法调用的 mock,  Up: 使用 mock

5.26.10.2 模拟方法调用
......................

使用 *note Mock: 373. 的常见场景：

   * 模拟函数调用

   * 记录“对象上的方法调用”

你可能需要替换一个对象上的方法，用于确认此方法被系统中的其他部分调用过，
并且调用时使用了正确的参数。

     >>> real = SomeClass()
     >>> real.method = MagicMock(name='method')
     >>> real.method(3, 4, 5, key='value')
     <MagicMock name='method()' id='...'>

使用了 mock（本例中的 ‘real.method’）之后，它有方法和属性可以让你针对它
是被如何使用的下断言。

     備註: 在多数示例中，*note Mock: 373. 与 *note MagicMock: 874. 两个
     类可以相互替换，而 ‘MagicMock’ 是一个更适用的类，通常情况下，使用它
     就可以了。

如果 mock 被调用，它的 *note called: 3533. 属性就会变成 ‘True’，更重要的
是，我们可以使用 *note assert_called_with(): 113a. 或者 *note
assert_called_once_with(): 3529. 方法来确认它在被调用时使用了正确的参数
。

在如下的测试示例中，验证对于 ‘ProductionClass().method’ 的调用会导致
‘something’ 的调用。

     >>> 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)


File: python.info,  Node: 对象上的方法调用的 mock,  Next: Mocking Classes,  Prev: 模拟方法调用,  Up: 使用 mock

5.26.10.3 对象上的方法调用的 mock
.................................

In the last example we patched a method directly on an object to check
that it was called correctly.  Another common use case is to pass an
object into a method (or some part of the system under test) and then
check that it is used in the correct way.

The simple ‘ProductionClass’ below has a ‘closer’ method.  If it is
called with an object then it calls ‘close’ on it.

     >>> class ProductionClass:
     ...     def closer(self, something):
     ...         something.close()
     ...

So to test it we need to pass in an object with a ‘close’ method and
check that it was called correctly.

     >>> real = ProductionClass()
     >>> mock = Mock()
     >>> real.closer(mock)
     >>> mock.close.assert_called_with()

We don’t have to do any work to provide the ’close’ method on our mock.
Accessing close creates it.  So, if ’close’ hasn’t already been called
then accessing it in the test will create it, but *note
assert_called_with(): 113a. will raise a failure exception.


File: python.info,  Node: Mocking Classes,  Next: Naming your mocks,  Prev: 对象上的方法调用的 mock,  Up: 使用 mock

5.26.10.4 Mocking Classes
.........................

A common use case is to mock out classes instantiated by your code under
test.  When you patch a class, then that class is replaced with a mock.
Instances are created by `calling the class'.  This means you access the
"mock instance" by looking at the return value of the mocked class.

In the example below we have a function ‘some_function’ that
instantiates ‘Foo’ and calls a method on it.  The call to *note patch():
877. replaces the class ‘Foo’ with a mock.  The ‘Foo’ instance is the
result of calling the mock, so it is configured by modifying the mock
*note return_value: 3527.

     >>> 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'


File: python.info,  Node: Naming your mocks,  Next: Tracking all Calls,  Prev: Mocking Classes,  Up: 使用 mock

5.26.10.5 Naming your mocks
...........................

It can be useful to give your mocks a name.  The name is shown in the
repr of the mock and can be helpful when the mock appears in test
failure messages.  The name is also propagated to attributes or methods
of the mock:

     >>> mock = MagicMock(name='foo')
     >>> mock
     <MagicMock name='foo' id='...'>
     >>> mock.method
     <MagicMock name='foo.method' id='...'>


File: python.info,  Node: Tracking all Calls,  Next: Setting Return Values and Attributes,  Prev: Naming your mocks,  Up: 使用 mock

5.26.10.6 Tracking all Calls
............................

Often you want to track more than a single call to a method.  The *note
mock_calls: 352c. attribute records all calls to child attributes of the
mock - and also to their children.

     >>> 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)]

If you make an assertion about ‘mock_calls’ and any unexpected methods
have been called, then the assertion will fail.  This is useful because
as well as asserting that the calls you expected have been made, you are
also checking that they were made in the right order and with no
additional calls:

You use the *note call: 10cc. object to construct lists for comparing
with ‘mock_calls’:

     >>> expected = [call.method(), call.attribute.method(10, x=53)]
     >>> mock.mock_calls == expected
     True

However, parameters to calls that return mocks are not recorded, which
means it is not possible to track nested calls where the parameters used
to create ancestors are important:

     >>> m = Mock()
     >>> m.factory(important=True).deliver()
     <Mock name='mock.factory().deliver()' id='...'>
     >>> m.mock_calls[-1] == call.factory(important=False).deliver()
     True


File: python.info,  Node: Setting Return Values and Attributes,  Next: Raising exceptions with mocks,  Prev: Tracking all Calls,  Up: 使用 mock

5.26.10.7 Setting Return Values and Attributes
..............................................

Setting the return values on a mock object is trivially easy:

     >>> mock = Mock()
     >>> mock.return_value = 3
     >>> mock()
     3

Of course you can do the same for methods on the mock:

     >>> mock = Mock()
     >>> mock.method.return_value = 3
     >>> mock.method()
     3

The return value can also be set in the constructor:

     >>> mock = Mock(return_value=3)
     >>> mock()
     3

If you need an attribute setting on your mock, just do it:

     >>> mock = Mock()
     >>> mock.x = 3
     >>> mock.x
     3

Sometimes you want to mock up a more complex situation, like for example
‘mock.connection.cursor().execute("SELECT 1")’.  If we wanted this call
to return a list, then we have to configure the result of the nested
call.

We can use *note call: 10cc. to construct the set of calls in a "chained
call" like this for easy assertion afterwards:

     >>> 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

It is the call to ‘.call_list()’ that turns our call object into a list
of calls representing the chained calls.


File: python.info,  Node: Raising exceptions with mocks,  Next: Side effect functions and iterables,  Prev: Setting Return Values and Attributes,  Up: 使用 mock

5.26.10.8 Raising exceptions with mocks
.......................................

A useful attribute is *note side_effect: 3525.  If you set this to an
exception class or instance then the exception will be raised when the
mock is called.

     >>> mock = Mock(side_effect=Exception('Boom!'))
     >>> mock()
     Traceback (most recent call last):
       ...
     Exception: Boom!


File: python.info,  Node: Side effect functions and iterables,  Next: Mocking asynchronous iterators,  Prev: Raising exceptions with mocks,  Up: 使用 mock

5.26.10.9 Side effect functions and iterables
.............................................

‘side_effect’ can also be set to a function or an iterable.  The use
case for ‘side_effect’ as an iterable is where your mock is going to be
called several times, and you want each call to return a different
value.  When you set ‘side_effect’ to an iterable every call to the mock
returns the next value from the iterable:

     >>> mock = MagicMock(side_effect=[4, 5, 6])
     >>> mock()
     4
     >>> mock()
     5
     >>> mock()
     6

For more advanced use cases, like dynamically varying the return values
depending on what the mock is called with, ‘side_effect’ can be a
function.  The function will be called with the same arguments as the
mock.  Whatever the function returns is what the call returns:

     >>> 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


File: python.info,  Node: Mocking asynchronous iterators,  Next: Mocking asynchronous context manager,  Prev: Side effect functions and iterables,  Up: 使用 mock

5.26.10.10 Mocking asynchronous iterators
.........................................

Since Python 3.8, ‘AsyncMock’ and ‘MagicMock’ have support to mock *note
异步迭代器: 739. through ‘__aiter__’.  The *note return_value: 3527.
attribute of ‘__aiter__’ can be used to set the return values to be used
for iteration.

     >>> 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]


File: python.info,  Node: Mocking asynchronous context manager,  Next: Creating a Mock from an Existing Object,  Prev: Mocking asynchronous iterators,  Up: 使用 mock

5.26.10.11 Mocking asynchronous context manager
...............................................

Since Python 3.8, ‘AsyncMock’ and ‘MagicMock’ have support to mock *note
异步上下文管理器: 15d2. through ‘__aenter__’ and ‘__aexit__’.  By
default, ‘__aenter__’ and ‘__aexit__’ are ‘AsyncMock’ instances that
return an async function.

     >>> 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()


File: python.info,  Node: Creating a Mock from an Existing Object,  Prev: Mocking asynchronous context manager,  Up: 使用 mock

5.26.10.12 Creating a Mock from an Existing Object
..................................................

One problem with over use of mocking is that it couples your tests to
the implementation of your mocks rather than your real code.  Suppose
you have a class that implements ‘some_method’.  In a test for another
class, you provide a mock of this object that `also' provides
‘some_method’.  If later you refactor the first class, so that it no
longer has ‘some_method’ - then your tests will continue to pass even
though your code is now broken!

*note Mock: 373. allows you to provide an object as a specification for
the mock, using the `spec' keyword argument.  Accessing methods /
attributes on the mock that don’t exist on your specification object
will immediately raise an attribute error.  If you change the
implementation of your specification, then tests that use that class
will start failing immediately without you having to instantiate the
class in those tests.

     >>> mock = Mock(spec=SomeClass)
     >>> mock.old_method()
     Traceback (most recent call last):
        ...
     AttributeError: object has no attribute 'old_method'

Using a specification also enables a smarter matching of calls made to
the mock, regardless of whether some parameters were passed as
positional or named arguments:

     >>> 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)

If you want this smarter matching to also work with method calls on the
mock, you can use *note auto-speccing: 3521.

If you want a stronger form of specification that prevents the setting
of arbitrary attributes as well as the getting of them then you can use
`spec_set' instead of `spec'.


File: python.info,  Node: Patch Decorators,  Next: Further Examples,  Prev: 使用 mock,  Up: unittest mock 上手指南

5.26.10.13 Patch Decorators
...........................

     備註: 在查找对象的名称空间中修补对象使用 *note patch(): 877. 。使用
     起来很简单，阅读 *note 在哪里打补丁: 351f. 来快速上手。

A common need in tests is to patch a class attribute or a module
attribute, for example patching a builtin or patching a class in a
module to test that it is instantiated.  Modules and classes are
effectively global, so patching on them has to be undone after the test
or the patch will persist into other tests and cause hard to diagnose
problems.

mock provides three convenient decorators for this: *note patch(): 877,
*note patch.object(): 10b4. and *note patch.dict(): 110a.  ‘patch’ takes
a single string, of the form ‘package.module.Class.attribute’ to specify
the attribute you are patching.  It also optionally takes a value that
you want the attribute (or class or whatever) to be replaced with.
’patch.object’ takes an object and the name of the attribute you would
like patched, plus optionally the value to patch it with.

‘patch.object’:

     >>> 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()

If you are patching a module (including *note builtins: 12.) then use
*note patch(): 877. instead of *note patch.object(): 10b4.:

     >>> 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"

The module name can be ’dotted’, in the form ‘package.module’ if needed:

     >>> @patch('package.module.ClassName.attribute', sentinel.attribute)
     ... def test():
     ...     from package.module import ClassName
     ...     assert ClassName.attribute == sentinel.attribute
     ...
     >>> test()

A nice pattern is to actually decorate test methods themselves:

     >>> 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

If you want to patch with a Mock, you can use *note patch(): 877. with
only one argument (or *note patch.object(): 10b4. with two arguments).
The mock will be created for you and passed into the test function /
method:

     >>> 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()

You can stack up multiple patch decorators using this pattern:

     >>> 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()

When you nest patch decorators the mocks are passed in to the decorated
function in the same order they applied (the normal `Python' order that
decorators are applied).  This means from the bottom up, so in the
example above the mock for ‘test_module.ClassName2’ is passed in first.

还有一个 *note patch.dict(): 110a. 用于在一定范围内设置字典中的值，并在
测试结束时将字典恢复为其原始状态：

     >>> foo = {'key': 'value'}
     >>> original = foo.copy()
     >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True):
     ...     assert foo == {'newkey': 'newvalue'}
     ...
     >>> assert foo == original

‘patch’, ‘patch.object’ and ‘patch.dict’ can all be used as context
managers.

Where you use *note patch(): 877. to create a mock for you, you can get
a reference to the mock using the "as" form of the with statement:

     >>> 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)

As an alternative ‘patch’, ‘patch.object’ and ‘patch.dict’ can be used
as class decorators.  When used in this way it is the same as applying
the decorator individually to every method whose name starts with
"test".


File: python.info,  Node: Further Examples,  Prev: Patch Decorators,  Up: unittest mock 上手指南

5.26.10.14 Further Examples
...........................

Here are some more examples for some slightly more advanced scenarios.

* Menu:

* Mocking chained calls::
* Partial mocking::
* Mocking a Generator Method::
* Applying the same patch to every test method::
* Mocking Unbound Methods::
* Checking multiple calls with mock::
* Coping with mutable arguments::
* Nesting Patches::
* Mocking a dictionary with MagicMock::
* Mock subclasses and their attributes::
* Mocking imports with patch.dict: Mocking imports with patch dict.
* Tracking order of calls and less verbose call assertions::
* More complex argument matching::


File: python.info,  Node: Mocking chained calls,  Next: Partial mocking,  Up: Further Examples

5.26.10.15 Mocking chained calls
................................

Mocking chained calls is actually straightforward with mock once you
understand the *note return_value: 3527. attribute.  When a mock is
called for the first time, or you fetch its ‘return_value’ before it has
been called, a new *note Mock: 373. is created.

This means that you can see how the object returned from a call to a
mocked object has been used by interrogating the ‘return_value’ mock:

     >>> mock = Mock()
     >>> mock().foo(a=2, b=3)
     <Mock name='mock().foo()' id='...'>
     >>> mock.return_value.foo.assert_called_with(a=2, b=3)

From here it is a simple step to configure and then make assertions
about chained calls.  Of course another alternative is writing your code
in a more testable way in the first place...

So, suppose we have some code that looks a little bit like this:

     >>> 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

Assuming that ‘BackendProvider’ is already well tested, how do we test
‘method()’?  Specifically, we want to test that the code section ‘# more
code’ uses the response object in the correct way.

As this chain of calls is made from an instance attribute we can monkey
patch the ‘backend’ attribute on a ‘Something’ instance.  In this
particular case we are only interested in the return value from the
final call to ‘start_call’ so we don’t have much configuration to do.
Let’s assume the object it returns is ’file-like’, so we’ll ensure that
our response object uses the builtin *note open(): 16f. as its ‘spec’.

To do this we create a mock instance as our mock backend and create a
mock response object for it.  To set the response as the return value
for that final ‘start_call’ we could do this:

     mock_backend.get_endpoint.return_value.create_call.return_value.start_call.return_value = mock_response

We can do that in a slightly nicer way using the *note configure_mock():
3528. method to directly set the return value for us:

     >>> 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)

With these we monkey patch the "mock backend" in place and can make the
real call:

     >>> something.backend = mock_backend
     >>> something.method()

Using *note mock_calls: 352c. we can check the chained call with a
single assert.  A chained call is several calls in one line of code, so
there will be several entries in ‘mock_calls’.  We can use *note
call.call_list(): 355f. to create this list of calls for us:

     >>> chained = call.get_endpoint('foobar').create_call('spam', 'eggs').start_call()
     >>> call_list = chained.call_list()
     >>> assert mock_backend.mock_calls == call_list


File: python.info,  Node: Partial mocking,  Next: Mocking a Generator Method,  Prev: Mocking chained calls,  Up: Further Examples

5.26.10.16 Partial mocking
..........................

In some tests I wanted to mock out a call to *note
datetime.date.today(): 19e8. to return a known date, but I didn’t want
to prevent the code under test from creating new date objects.
Unfortunately *note datetime.date: 19d. is written in C, and so I
couldn’t just monkey-patch out the static ‘date.today()’ method.

I found a simple way of doing this that involved effectively wrapping
the date class with a mock, but passing through calls to the constructor
to the real class (and returning real instances).

The *note patch decorator: 877. is used here to mock out the ‘date’
class in the module under test.  The ‘side_effect’ attribute on the mock
date class is then set to a lambda function that returns a real date.
When the mock date class is called a real date will be constructed and
returned by ‘side_effect’.

     >>> 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)

Note that we don’t patch *note datetime.date: 19d. globally, we patch
‘date’ in the module that `uses' it.  See *note where to patch: 351f.

When ‘date.today()’ is called a known date is returned, but calls to the
‘date(...)’ constructor still return normal dates.  Without this you can
find yourself having to calculate an expected result using exactly the
same algorithm as the code under test, which is a classic testing
anti-pattern.

Calls to the date constructor are recorded in the ‘mock_date’ attributes
(‘call_count’ and friends) which may also be useful for your tests.

An alternative way of dealing with mocking dates, or other builtin
classes, is discussed in this blog entry(1).

   ---------- Footnotes ----------

   (1) 
https://williambert.online/2011/07/how-to-unit-testing-in-django-with-mocking-and-patching/


File: python.info,  Node: Mocking a Generator Method,  Next: Applying the same patch to every test method,  Prev: Partial mocking,  Up: Further Examples

5.26.10.17 Mocking a Generator Method
.....................................

A Python generator is a function or method that uses the *note yield:
2c7. statement to return a series of values when iterated over (1).

A generator method / function is called to return the generator object.
It is the generator object that is then iterated over.  The protocol
method for iteration is *note __iter__(): 175d, so we can mock this
using a *note MagicMock: 874.

Here’s an example class with an "iter" method implemented as a
generator:

     >>> class Foo:
     ...     def iter(self):
     ...         for i in [1, 2, 3]:
     ...             yield i
     ...
     >>> foo = Foo()
     >>> list(foo.iter())
     [1, 2, 3]

How would we mock this class, and in particular its "iter" method?

To configure the values returned from the iteration (implicit in the
call to *note list: 1f8.), we need to configure the object returned by
the call to ‘foo.iter()’.

     >>> mock_foo = MagicMock()
     >>> mock_foo.iter.return_value = iter([1, 2, 3])
     >>> list(mock_foo.iter())
     [1, 2, 3]

   ---------- Footnotes ----------

   (1) (1) There are also generator expressions and more advanced uses
(http://www.dabeaz.com/coroutines/index.html) of generators, but we
aren’t concerned about them here.  A very good introduction to
generators and how powerful they are is: Generator Tricks for Systems
Programmers (http://www.dabeaz.com/generators/).


File: python.info,  Node: Applying the same patch to every test method,  Next: Mocking Unbound Methods,  Prev: Mocking a Generator Method,  Up: Further Examples

5.26.10.18 Applying the same patch to every test method
.......................................................

If you want several patches in place for multiple test methods the
obvious way is to apply the patch decorators to every method.  This can
feel like unnecessary repetition.  For Python 2.6 or more recent you can
use *note patch(): 877. (in all its various forms) as a class decorator.
This applies the patches to all test methods on the class.  A test
method is identified by methods whose names start with ‘test’:

     >>> @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'

An alternative way of managing patches is to use the *note patch
methods; start and stop: 3551.  These allow you to move the patching
into your ‘setUp’ and ‘tearDown’ methods.

     >>> 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()

If you use this technique you must ensure that the patching is "undone"
by calling ‘stop’.  This can be fiddlier than you might think, because
if an exception is raised in the setUp then tearDown is not called.
*note unittest.TestCase.addCleanup(): 3c5. makes this easier:

     >>> 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()


File: python.info,  Node: Mocking Unbound Methods,  Next: Checking multiple calls with mock,  Prev: Applying the same patch to every test method,  Up: Further Examples

5.26.10.19 Mocking Unbound Methods
..................................

Whilst writing tests today I needed to patch an `unbound method'
(patching the method on the class rather than on the instance).  I
needed self to be passed in as the first argument because I want to make
asserts about which objects were calling this particular method.  The
issue is that you can’t patch with a mock for this, because if you
replace an unbound method with a mock it doesn’t become a bound method
when fetched from the instance, and so it doesn’t get self passed in.
The workaround is to patch the unbound method with a real function
instead.  The *note patch(): 877. decorator makes it so simple to patch
out methods with a mock that having to create a real function becomes a
nuisance.

If you pass ‘autospec=True’ to patch then it does the patching with a
`real' function object.  This function object has the same signature as
the one it is replacing, but delegates to a mock under the hood.  You
still get your mock auto-created in exactly the same way as before.
What it means though, is that if you use it to patch out an unbound
method on a class the mocked function will be turned into a bound method
if it is fetched from an instance.  It will have ‘self’ passed in as the
first argument, which is exactly what I wanted:

     >>> 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)

If we don’t use ‘autospec=True’ then the unbound method is patched out
with a Mock instance instead, and isn’t called with ‘self’.


File: python.info,  Node: Checking multiple calls with mock,  Next: Coping with mutable arguments,  Prev: Mocking Unbound Methods,  Up: Further Examples

5.26.10.20 Checking multiple calls with mock
............................................

mock has a nice API for making assertions about how your mock objects
are used.

     >>> mock = Mock()
     >>> mock.foo_bar.return_value = None
     >>> mock.foo_bar('baz', spam='eggs')
     >>> mock.foo_bar.assert_called_with('baz', spam='eggs')

If your mock is only being called once you can use the
‘assert_called_once_with()’ method that also asserts that the
‘call_count’ is one.

     >>> 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.

Both ‘assert_called_with’ and ‘assert_called_once_with’ make assertions
about the `most recent' call.  If your mock is going to be called
several times, and you want to make assertions about `all' those calls
you can use *note call_args_list: 3535.:

     >>> 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()]

The *note call: 10cc. helper makes it easy to make assertions about
these calls.  You can build up a list of expected calls and compare it
to ‘call_args_list’.  This looks remarkably similar to the repr of the
‘call_args_list’:

     >>> expected = [call(1, 2, 3), call(4, 5, 6), call()]
     >>> mock.call_args_list == expected
     True


File: python.info,  Node: Coping with mutable arguments,  Next: Nesting Patches,  Prev: Checking multiple calls with mock,  Up: Further Examples

5.26.10.21 Coping with mutable arguments
........................................

Another situation is rare, but can bite you, is when your mock is called
with mutable arguments.  ‘call_args’ and ‘call_args_list’ store
`references' to the arguments.  If the arguments are mutated by the code
under test then you can no longer make assertions about what the values
were when the mock was called.

Here’s some example code that shows the problem.  Imagine the following
functions defined in ’mymodule’:

     def frob(val):
         pass

     def grob(val):
         "First frob and then clear val"
         frob(val)
         val.clear()

When we try to test that ‘grob’ calls ‘frob’ with the correct argument
look what happens:

     >>> 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(),), {})

One possibility would be for mock to copy the arguments you pass in.
This could then cause problems if you do assertions that rely on object
identity for equality.

Here’s one solution that uses the ‘side_effect’ functionality.  If you
provide a ‘side_effect’ function for a mock then ‘side_effect’ will be
called with the same args as the mock.  This gives us an opportunity to
copy the arguments and store them for later assertions.  In this example
I’m using `another' mock to store the arguments so that I can use the
mock methods for doing the assertion.  Again a helper function sets this
up for me.

     >>> 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})

‘copy_call_args’ is called with the mock that will be called.  It
returns a new mock that we do the assertion on.  The ‘side_effect’
function makes a copy of the args and calls our ‘new_mock’ with the
copy.

     備註: If your mock is only going to be used once there is an easier
     way of checking arguments at the point they are called.  You can
     simply do the checking inside a ‘side_effect’ function.

          >>> def side_effect(arg):
          ...     assert arg == {6}
          ...
          >>> mock = Mock(side_effect=side_effect)
          >>> mock({6})
          >>> mock(set())
          Traceback (most recent call last):
              ...
          AssertionError

An alternative approach is to create a subclass of *note Mock: 373. or
*note MagicMock: 874. that copies (using *note copy.deepcopy(): 4d2.)
the arguments.  Here’s an example implementation:

     >>> 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='...'>

When you subclass ‘Mock’ or ‘MagicMock’ all dynamically created
attributes, and the ‘return_value’ will use your subclass automatically.
That means all children of a ‘CopyingMock’ will also have the type
‘CopyingMock’.


File: python.info,  Node: Nesting Patches,  Next: Mocking a dictionary with MagicMock,  Prev: Coping with mutable arguments,  Up: Further Examples

5.26.10.22 Nesting Patches
..........................

Using patch as a context manager is nice, but if you do multiple patches
you can end up with nested with statements indenting further and further
to the right:

     >>> 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

With unittest ‘cleanup’ functions and the *note patch methods; start and
stop: 3551. we can achieve the same effect without the nested
indentation.  A simple helper method, ‘create_patch’, puts the patch in
place and returns the created mock for us:

     >>> 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


File: python.info,  Node: Mocking a dictionary with MagicMock,  Next: Mock subclasses and their attributes,  Prev: Nesting Patches,  Up: Further Examples

5.26.10.23 Mocking a dictionary with MagicMock
..............................................

You may want to mock a dictionary, or other container object, recording
all access to it whilst having it still behave like a dictionary.

We can do this with *note MagicMock: 874, which will behave like a
dictionary, and using *note side_effect: 3525. to delegate dictionary
access to a real underlying dictionary that is under our control.

When the *note __getitem__(): 3a5. and *note __setitem__(): d2a. methods
of our ‘MagicMock’ are called (normal dictionary access) then
‘side_effect’ is called with the key (and in the case of ‘__setitem__’
the value too).  We can also control what is returned.

After the ‘MagicMock’ has been used we can use attributes like *note
call_args_list: 3535. to assert about how the dictionary was used:

     >>> 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

     備註: An alternative to using ‘MagicMock’ is to use ‘Mock’ and
     `only' provide the magic methods you specifically want:

          >>> mock = Mock()
          >>> mock.__getitem__ = Mock(side_effect=getitem)
          >>> mock.__setitem__ = Mock(side_effect=setitem)

     A `third' option is to use ‘MagicMock’ but passing in ‘dict’ as the
     `spec' (or `spec_set') argument so that the ‘MagicMock’ created
     only has dictionary magic methods available:

          >>> mock = MagicMock(spec_set=dict)
          >>> mock.__getitem__.side_effect = getitem
          >>> mock.__setitem__.side_effect = setitem

With these side effect functions in place, the ‘mock’ will behave like a
normal dictionary but recording the access.  It even raises a *note
KeyError: 3e9. if you try to access a key that doesn’t exist.

     >>> 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'

After it has been used you can make assertions about the access using
the normal mock methods and attributes:

     >>> 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'}


File: python.info,  Node: Mock subclasses and their attributes,  Next: Mocking imports with patch dict,  Prev: Mocking a dictionary with MagicMock,  Up: Further Examples

5.26.10.24 Mock subclasses and their attributes
...............................................

There are various reasons why you might want to subclass *note Mock:
373.  One reason might be to add helper methods.  Here’s a silly
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

The standard behaviour for ‘Mock’ instances is that attributes and the
return value mocks are of the same type as the mock they are accessed
on.  This ensures that ‘Mock’ attributes are ‘Mocks’ and ‘MagicMock’
attributes are ‘MagicMocks’ (1).  So if you’re subclassing to add helper
methods then they’ll also be available on the attributes and return
value mock of instances of your subclass.

     >>> 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

Sometimes this is inconvenient.  For example, one user(2) is subclassing
mock to created a Twisted adaptor(3).  Having this applied to attributes
too actually causes errors.

‘Mock’ (in all its flavours) uses a method called ‘_get_child_mock’ to
create these "sub-mocks" for attributes and return values.  You can
prevent your subclass being used for attributes by overriding this
method.  The signature is that it takes arbitrary keyword arguments
(‘**kwargs’) which are then passed onto the mock constructor:

     >>> 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)

   ---------- Footnotes ----------

   (1) (2) An exception to this rule are the non-callable mocks.
Attributes use the callable variant because otherwise non-callable mocks
couldn’t have callable methods.

   (2) https://code.google.com/archive/p/mock/issues/105

   (3) 
https://twistedmatrix.com/documents/11.0.0/api/twisted.python.components.html


File: python.info,  Node: Mocking imports with patch dict,  Next: Tracking order of calls and less verbose call assertions,  Prev: Mock subclasses and their attributes,  Up: Further Examples

5.26.10.25 Mocking imports with patch.dict
..........................................

One situation where mocking can be hard is where you have a local import
inside a function.  These are harder to mock because they aren’t using
an object from the module namespace that we can patch out.

Generally local imports are to be avoided.  They are sometimes done to
prevent circular dependencies, for which there is `usually' a much
better way to solve the problem (refactor the code) or to prevent "up
front costs" by delaying the import.  This can also be solved in better
ways than an unconditional local import (store the module as a class or
module attribute and only do the import on first use).

That aside there is a way to use ‘mock’ to affect the results of an
import.  Importing fetches an `object' from the *note sys.modules: 1051.
dictionary.  Note that it fetches an `object', which need not be a
module.  Importing a module for the first time results in a module
object being put in ‘sys.modules’, so usually when you import something
you get a module back.  This need not be the case however.

This means you can use *note patch.dict(): 110a. to `temporarily' put a
mock in place in *note sys.modules: 1051.  Any imports whilst this patch
is active will fetch the mock.  When the patch is complete (the
decorated function exits, the with statement body is complete or
‘patcher.stop()’ is called) then whatever was there previously will be
restored safely.

Here’s an example that mocks out the ’fooble’ module.

     >>> 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()

As you can see the ‘import fooble’ succeeds, but on exit there is no
’fooble’ left in *note sys.modules: 1051.

This also works for the ‘from module import name’ form:

     >>> 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()

With slightly more work you can also mock package imports:

     >>> 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()


File: python.info,  Node: Tracking order of calls and less verbose call assertions,  Next: More complex argument matching,  Prev: Mocking imports with patch dict,  Up: Further Examples

5.26.10.26 Tracking order of calls and less verbose call assertions
...................................................................

The *note Mock: 373. class allows you to track the `order' of method
calls on your mock objects through the *note method_calls: 352f.
attribute.  This doesn’t allow you to track the order of calls between
separate mock objects, however we can use *note mock_calls: 352c. to
achieve the same effect.

Because mocks track calls to child mocks in ‘mock_calls’, and accessing
an arbitrary attribute of a mock creates a child mock, we can create our
separate mocks from a parent one.  Calls to those child mock will then
all be recorded, in order, in the ‘mock_calls’ of the parent:

     >>> manager = Mock()
     >>> mock_foo = manager.foo
     >>> mock_bar = manager.bar

     >>> mock_foo.something()
     <Mock name='mock.foo.something()' id='...'>
     >>> mock_bar.other.thing()
     <Mock name='mock.bar.other.thing()' id='...'>

     >>> manager.mock_calls
     [call.foo.something(), call.bar.other.thing()]

We can then assert about the calls, including the order, by comparing
with the ‘mock_calls’ attribute on the manager mock:

     >>> expected_calls = [call.foo.something(), call.bar.other.thing()]
     >>> manager.mock_calls == expected_calls
     True

If ‘patch’ is creating, and putting in place, your mocks then you can
attach them to a manager mock using the *note attach_mock(): 352e.
method.  After attaching calls will be recorded in ‘mock_calls’ of the
manager.

     >>> 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()]

If many calls have been made, but you’re only interested in a particular
sequence of them then an alternative is to use the *note
assert_has_calls(): 352b. method.  This takes a list of calls
(constructed with the *note call: 10cc. object).  If that sequence of
calls are in *note mock_calls: 352c. then the assert succeeds.

     >>> 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)

Even though the chained call ‘m.one().two().three()’ aren’t the only
calls that have been made to the mock, the assert still succeeds.

Sometimes a mock may have several calls made to it, and you are only
interested in asserting about `some' of those calls.  You may not even
care about the order.  In this case you can pass ‘any_order=True’ to
‘assert_has_calls’:

     >>> 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)


File: python.info,  Node: More complex argument matching,  Prev: Tracking order of calls and less verbose call assertions,  Up: Further Examples

5.26.10.27 More complex argument matching
.........................................

Using the same basic concept as *note ANY: 10d1. we can implement
matchers to do more complex assertions on objects used as arguments to
mocks.

Suppose we expect some object to be passed to a mock that by default
compares equal based on object identity (which is the Python default for
user defined classes).  To use *note assert_called_with(): 113a. we
would need to pass in the exact same object.  If we are only interested
in some of the attributes of this object then we can create a matcher
that will check these attributes for us.

You can see in this example how a ’standard’ call to
‘assert_called_with’ isn’t sufficient:

     >>> 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...>)

A comparison function for our ‘Foo’ class might look something like
this:

     >>> 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
     ...

And a matcher object that can use comparison functions like this for its
equality operation would look something like this:

     >>> 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)
     ...

Putting all this together:

     >>> match_foo = Matcher(compare, Foo(1, 2))
     >>> mock.assert_called_with(match_foo)

The ‘Matcher’ is instantiated with our compare function and the ‘Foo’
object we want to compare against.  In ‘assert_called_with’ the
‘Matcher’ equality method will be called, which compares the object the
mock was called with against the one we created our matcher with.  If
they match then ‘assert_called_with’ passes, and if they don’t an *note
AssertionError: 240. is raised:

     >>> 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...>,), {})

With a bit of tweaking you could have the comparison function raise the
*note AssertionError: 240. directly and provide a more useful failure
message.

As of version 1.5, the Python testing library PyHamcrest(1) provides
similar functionality, that may be useful here, in the form of its
equality matcher (hamcrest.library.integration.match_equality(2)).

   ---------- Footnotes ----------

   (1) https://pyhamcrest.readthedocs.io/

   (2) 
https://pyhamcrest.readthedocs.io/en/release-1.8/integration/#module-hamcrest.library.integration.match_equality


File: python.info,  Node: 2to3 - 自動將 Python 2的程式碼轉成 Python 3,  Next: test --- Python回归测试包,  Prev: unittest mock 上手指南,  Up: 開發工具

5.26.11 2to3 - 自動將 Python 2的程式碼轉成 Python 3
---------------------------------------------------

2to3 是一个 Python 程序，它可以读取 Python 2.x 的源代码并使用一系列的 `修
复器' 来将其转换为合法的 Python 3.x 代码。 标准库已包含了丰富的修复器，
这足以处理几乎所有代码。 不过 2to3 的支持库 *note lib2to3: a7. 是一个很
灵活通用的库，所以还可以编写你自己的 2to3 修复器。

* Menu:

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


File: python.info,  Node: 使用 2to3,  Next: 修复器,  Up: 2to3 - 自動將 Python 2的程式碼轉成 Python 3

5.26.11.1 使用 2to3
...................

2to3 通常会作为脚本和 Python 解释器一起安装，你可以在 Python 根目录的
‘Tools/scripts’ 文件夹下找到它。

2to3 的基本调用参数是一个需要转换的文件或目录列表。对于目录，会递归地寻
找其中的 Python 源码。

這邊有簡單的 Python 2的原始檔案 ‘example.py’:

     def greet(name):
         print "Hello, {0}!".format(name)
     print "What's your name?"
     name = raw_input()
     greet(name)

它可以在命令行中使用 2to3 转换成 Python 3.x 版本的代码：

     $ 2to3 example.py

这个命令会打印出和源文件的区别。通过传入 ‘-w’ 参数，2to3 也可以把需要的
修改写回到原文件中（除非传入了 ‘-n’ 参数，否则会为原始文件创建一个副本）
：

     $ 2to3 -w example.py

在转换完成后，‘example.py’ 看起来像是这样：

     def greet(name):
         print("Hello, {0}!".format(name))
     print("What's your name?")
     name = input()
     greet(name)

注释和缩进都会在转换过程中保持不变。

默认情况下，2to3 会执行 *note 预定义修复器: 3589. 的集合。使用 ‘-l’ 参数
可以列出所有可用的修复器。使用 ‘-f’ 参数可以明确指定需要使用的修复器集合
。而使用 ‘-x’ 参数则可以明确指定不使用的修复器。下面的例子会只使用
‘imports’ 和 ‘has_key’ 修复器运行：

     $ 2to3 -f imports -f has_key example.py

这个命令会执行除了 ‘apply’ 之外的所有修复器：

     $ 2to3 -x apply example.py

有一些修复器是需要 `显式指定' 的，它们默认不会执行，必须在命令行中列出才
会执行。比如下面的例子，除了默认的修复器以外，还会执行 ‘idioms’ 修复器：

     $ 2to3 -f all -f idioms example.py

注意这里使用 ‘all’ 来启用所有默认的修复器。

有些情况下 2to3 会找到源码中有一些需要修改，但是无法自动处理的代码。在这
种情况下，2to3 会在差异处下面打印一个警告信息。你应该定位到相应的代码并
对其进行修改，以使其兼容 Python 3.x。

2to3 也可以重构 doctests。使用 ‘-d’ 开启这个模式。需要注意*只有*
doctests 会被重构。这种模式下不需要文件是合法的 Python 代码。举例来说，
reST 文档中类似 doctests 的示例也可以使用这个选项进行重构。

‘-v’ 选项可以输出更多转换程序的详细信息。

由于某些 print 语句可被解读为函数调用或是语句，2to3 并不总能读取包含
print 函数的文件。 当 2to3 检测到存在 ‘from __future__ import
print_function’ 编译器指令时，会修改其内部语法将 *note print(): 971. 解
读为函数。 这一变动也可以使用 ‘-p’ 旗标手动开启。 使用 ‘-p’ 来为已转换过
print 语句的代码运行修复器。 也可以使用 ‘-e’ 将 *note exec(): d0c. 解读
为函数。

‘-o’ 或 ‘--output-dir’ 选项可以指定将转换后的文件写入其他目录中。由于这
种情况下不会覆写原始文件，所以创建副本文件毫无意义，因此也需要使用 ‘-n’
选项来禁用创建副本。

3.2.3 版新加入: 增加了 ‘-o’ 选项。

‘-W’ 或 ‘--write-unchanged-files’ 选项用来告诉 2to3 始终需要输出文件，即
使没有任何改动。这在使用 ‘-o’ 参数时十分有用，这样就可以将整个 Python 源
码包完整地转换到另一个目录。这个选项隐含了 ‘-w’ 选项，否则等于没有作用。

3.2.3 版新加入: 增加了 ‘-W’ 选项。

‘--add-suffix’ 选项接受一个字符串，用来作为后缀附加在输出文件名后面的后
面。由于写入的文件名与原始文件不同，所以没有必要创建副本，因此 ‘-n’ 选项
也是必要的。举个例子：

     $ 2to3 -n -W --add-suffix=3 example.py

这样会把转换后的文件写入 ‘example.py3’ 文件。

3.2.3 版新加入: 增加了 ‘--add-suffix’ 选项。

将整个项目从一个目录转换到另一个目录可以用这样的命令：

     $ 2to3 --output-dir=python3-version/mycode -W -n python2-version/mycode


File: python.info,  Node: 修复器,  Next: lib2to3 —— 2to3 支持库,  Prev: 使用 2to3,  Up: 2to3 - 自動將 Python 2的程式碼轉成 Python 3

5.26.11.2 修复器
................

转换代码的每一个步骤都封装在修复器中。可以使用 ‘2to3 -l’ 来列出可用的修
复器。*note 之前已经提到: 3587.，每个修复器都可以独立地打开或是关闭。下
面会对各个修复器做更详细的描述。

 -- 2to3fixer: apply

     移除对 ‘apply()’ 的使用，举例来说，‘apply(function, *args,
     **kwargs)’ 会被转换成 ‘function(*args, **kwargs)’。

 -- 2to3fixer: asserts

     将已弃用的 *note unittest: 124. 方法替换为正确的。

     從                                   到
                                          
     ------------------------------------------------------------------------------------
                                          
     ‘failUnlessEqual(a, b)’              *note assertEqual(a, b): c85.
                                          
                                          
     ‘assertEquals(a, b)’                 *note assertEqual(a, b): c85.
                                          
                                          
     ‘failIfEqual(a, b)’                  *note assertNotEqual(a, b): c86.
                                          
                                          
     ‘assertNotEquals(a, b)’              *note assertNotEqual(a, b): c86.
                                          
                                          
     ‘failUnless(a)’                      *note assertTrue(a): c84.
                                          
                                          
     ‘assert_(a)’                         *note assertTrue(a): c84.
                                          
                                          
     ‘failIf(a)’                          *note assertFalse(a): d8f.
                                          
                                          
     ‘failUnlessRaises(exc, cal)’         *note assertRaises(exc, cal): b92.
                                          
                                          
     ‘failUnlessAlmostEqual(a, b)’        *note assertAlmostEqual(a, b): c87.
                                          
                                          
     ‘assertAlmostEquals(a, b)’           *note assertAlmostEqual(a, b): c87.
                                          
                                          
     ‘failIfAlmostEqual(a, b)’            *note assertNotAlmostEqual(a, b): c88.
                                          
                                          
     ‘assertNotAlmostEquals(a, b)’        *note assertNotAlmostEqual(a, b): c88.
                                          

 -- 2to3fixer: basestring

     将 ‘basestring’ 转换为 *note str: 205.。

 -- 2to3fixer: buffer

     将 ‘buffer’ 转换为 *note memoryview: 386.。这个修复器是可选的，因为
     *note memoryview: 386. API 和 ‘buffer’ 很相似，但不完全一样。

 -- 2to3fixer: dict

     修复字典迭代方法。‘dict.iteritems()’ 会转换成 *note dict.items():
     cf5.，‘dict.iterkeys()’ 会转换成 *note dict.keys(): cf4.，
     ‘dict.itervalues()’ 会转换成 *note dict.values(): cf6.。类似的，
     ‘dict.viewitems()’，‘dict.viewkeys()’ 和 ‘dict.viewvalues()’ 会分别
     转换成 *note dict.items(): cf5.，*note dict.keys(): cf4. 和 *note
     dict.values(): cf6.。另外也会将原有的 *note dict.items(): cf5.，
     *note dict.keys(): cf4. 和 *note dict.values(): cf6. 方法调用用
     *note list: 1f8. 包装一层。

 -- 2to3fixer: except

     将 ‘except X, T’ 转换为 ‘except X as T’。

 -- 2to3fixer: exec

     将 ‘exec’ 语句转换为 *note exec(): d0c. 函数调用。

 -- 2to3fixer: execfile

     移除 ‘execfile()’ 的使用。‘execfile()’ 的实参会使用 *note open():
     16f.，*note compile(): 2e7. 和 *note exec(): d0c. 包装。

 -- 2to3fixer: exitfunc

     将对 ‘sys.exitfunc’ 的赋值改为使用 *note atexit: b. 模块代替。

 -- 2to3fixer: filter

     将 *note filter(): cf8. 函数用 *note list: 1f8. 包装一层。

 -- 2to3fixer: funcattrs

     修复已经重命名的函数属性。比如 ‘my_function.func_closure’ 会被转换
     为 ‘my_function.__closure__’。

 -- 2to3fixer: future

     移除 ‘from __future__ import new_feature’ 语句。

 -- 2to3fixer: getcwdu

     将 ‘os.getcwdu()’ 重命名为 *note os.getcwd(): 1119.。

 -- 2to3fixer: has_key

     将 ‘dict.has_key(key)’ 转换为 ‘key in dict’。

 -- 2to3fixer: idioms

     这是一个可选的修复器，会进行多种转换，将 Python 代码变成更加常见的
     写法。类似 ‘type(x) is SomeClass’ 和 ‘type(x) == SomeClass’ 的类型
     对比会被转换成 ‘isinstance(x, SomeClass)’。‘while 1’ 转换成 ‘while
     True’。这个修复器还会在合适的地方使用 *note sorted(): 546. 函数。举
     个例子，这样的代码块：

          L = list(some_iterable)
          L.sort()

     会被转换为：

          L = sorted(some_iterable)

 -- 2to3fixer: import

     检测 sibling imports，并将其转换成相对 import。

 -- 2to3fixer: imports

     处理标准库模块的重命名。

 -- 2to3fixer: imports2

     处理标准库中其他模块的重命名。这个修复器由于一些技术上的限制，因此
     和 *note imports: 359a. 拆分开了。

 -- 2to3fixer: input

     将 ‘input(prompt)’ 转换为 ‘eval(input(prompt))’。

 -- 2to3fixer: intern

     将 ‘intern()’ 转换为 *note sys.intern(): d36.。

 -- 2to3fixer: isinstance

     修复 *note isinstance(): 551. 函数第二个实参中重复的类型。举例来说
     ，‘isinstance(x, (int, int))’ 会转换为 ‘isinstance(x, int)’,
     ‘isinstance(x, (int, float, int))’ 会转换为 ‘isinstance(x, (int,
     float))’。

 -- 2to3fixer: itertools_imports

     移除 ‘itertools.ifilter()’，‘itertools.izip()’ 以及
     ‘itertools.imap()’ 的 import。对 ‘itertools.ifilterfalse()’ 的
     import 也会替换成 *note itertools.filterfalse(): 1722.。

 -- 2to3fixer: itertools

     修改 ‘itertools.ifilter()’，‘itertools.izip()’ 和
     ‘itertools.imap()’ 的调用为对应的内建实现。
     ‘itertools.ifilterfalse()’ 会替换成 *note itertools.filterfalse():
     1722.。

 -- 2to3fixer: long

     将 ‘long’ 重命名为 *note int: 204.。

 -- 2to3fixer: map

     用 *note list: 1f8. 包装 *note map(): cf7.。同时也会将 ‘map(None,
     x)’ 替换为 ‘list(x)’。使用 ‘from future_builtins import map’ 禁用这
     个修复器。

 -- 2to3fixer: metaclass

     将老的元类语法（类体中的 ‘__metaclass__ = Meta’）替换为新的（‘class
     X(metaclass=Meta)’）。

 -- 2to3fixer: methodattrs

     修复老的方法属性名。例如 ‘meth.im_func’ 会被转换为 ‘meth.__func__’。

 -- 2to3fixer: ne

     转换老的不等语法，将 ‘<>’ 转为 ‘!=’。

 -- 2to3fixer: next

     将迭代器的 ‘next()’ 方法调用转为 *note next(): 775. 函数。也会将
     *note next(): 775. 方法重命名为 *note __next__(): d2c.。

 -- 2to3fixer: nonzero

     Renames definitions of methods called ‘__nonzero__()’ to *note
     __bool__(): d30.

 -- 2to3fixer: numliterals

     将八进制字面量转为新的语法。

 -- 2to3fixer: operator

     将 *note operator: c2. 模块中的许多方法调用转为其他的等效函数调用。
     如果有需要，会添加适当的 ‘import’ 语句，比如 ‘import
     collections.abc’。有以下转换映射：

     從                                     到
                                            
     -----------------------------------------------------------------------------------------
                                            
     ‘operator.isCallable(obj)’             ‘callable(obj)’
                                            
                                            
     ‘operator.sequenceIncludes(obj)’       ‘operator.contains(obj)’
                                            
                                            
     ‘operator.isSequenceType(obj)’         ‘isinstance(obj, collections.abc.Sequence)’
                                            
                                            
     ‘operator.isMappingType(obj)’          ‘isinstance(obj, collections.abc.Mapping)’
                                            
                                            
     ‘operator.isNumberType(obj)’           ‘isinstance(obj, numbers.Number)’
                                            
                                            
     ‘operator.repeat(obj, n)’              ‘operator.mul(obj, n)’
                                            
                                            
     ‘operator.irepeat(obj, n)’             ‘operator.imul(obj, n)’
                                            

 -- 2to3fixer: paren

     在列表生成式中增加必须的括号。例如将 ‘[x for x in 1, 2]’ 转换为 ‘[x
     for x in (1, 2)]’。

 -- 2to3fixer: print

     将 ‘print’ 语句转换为 *note print(): 971. 函数。

 -- 2to3fixer: raise

     将 ‘raise E, V’ 转换为 ‘raise E(V)’，将 ‘raise E, V, T’ 转换为
     ‘raise E(V).with_traceback(T)’。如果 ‘E’ 是元组，这样的转换是不正确
     的，因为用元组代替异常的做法在 3.0 中已经移除了。

 -- 2to3fixer: raw_input

     将 ‘raw_input()’ 转换为 *note input(): d33.。

 -- 2to3fixer: reduce

     将 ‘reduce()’ 转换为 *note functools.reduce(): d37.。

 -- 2to3fixer: reload

     将 ‘reload()’ 转换为 *note importlib.reload(): 49f.。

 -- 2to3fixer: renames

     将 ‘sys.maxint’ 转换为 *note sys.maxsize: c15.。

 -- 2to3fixer: repr

     将反引号 repr 表达式替换为 *note repr(): 8b9. 函数。

 -- 2to3fixer: set_literal

     将 *note set: 1f6. 构造函数替换为 set literals 写法。这个修复器是可
     选的。

 -- 2to3fixer: standarderror

     将 ‘StandardError’ 重命名为 *note Exception: 2dc.。

 -- 2to3fixer: sys_exc

     将弃用的 ‘sys.exc_value’，‘sys.exc_type’，‘sys.exc_traceback’ 替换
     为 *note sys.exc_info(): d27. 的用法。

 -- 2to3fixer: throw

     修复生成器的 ‘throw()’ 方法的 API 变更。

 -- 2to3fixer: tuple_params

     移除隐式的元组参数解包。这个修复器会插入临时变量。

 -- 2to3fixer: types

     修复 *note type: 6ff. 模块中一些成员的移除引起的代码问题。

 -- 2to3fixer: unicode

     将 ‘unicode’ 重命名为 *note str: 205.。

 -- 2to3fixer: urllib

     将 *note urllib: 126. 和 ‘urllib2’ 重命名为 *note urllib: 126. 包。

 -- 2to3fixer: ws_comma

     移除逗号分隔的元素之间多余的空白。这个修复器是可选的。

 -- 2to3fixer: xrange

     将 ‘xrange()’ 重命名为 *note range(): 1f5.，并用 *note list: 1f8. 包
     装原有的 *note range(): 1f5.。

 -- 2to3fixer: xreadlines

     将 ‘for x in file.xreadlines()’ 转换为 ‘for x in file’。

 -- 2to3fixer: zip

     用 *note list: 1f8. 包装 *note zip(): cfc.。如果使用了 ‘from
     future_builtins import zip’ 的话会禁用。


File: python.info,  Node: lib2to3 —— 2to3 支持库,  Prev: 修复器,  Up: 2to3 - 自動將 Python 2的程式碼轉成 Python 3

5.26.11.3 ‘lib2to3’ —— 2to3 支持库
..................................

`源代码：' Lib/lib2to3/(1)

__________________________________________________________________

3.10 版後已棄用: Python 3.9 将切换到 PEG 解析器 (参见 PEP 617(2))，
Python 3.10 可能会包含 lib2to3 的 LL(1) 解析器所不能解析的新语法。
‘lib2to3’ 模块可能会在未来的 Python 版本中被移出标准库。 请考虑使用第三
方替代例如 LibCST(3) 或 parso(4)。

     備註: *note lib2to3: a7. API 并不稳定，并可能在未来大幅修改。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/lib2to3/

   (2) https://www.python.org/dev/peps/pep-0617

   (3) https://libcst.readthedocs.io/

   (4) https://parso.readthedocs.io/


File: python.info,  Node: test --- Python回归测试包,  Next: test support --- Utilities for the Python test suite,  Prev: 2to3 - 自動將 Python 2的程式碼轉成 Python 3,  Up: 開發工具

5.26.12 ‘test’ — Python回归测试包
---------------------------------

     備註: *note test: 105. 包只供 Python 内部使用。它的记录是为了让
     Python 的核心开发者受益。我们不鼓励在 Python 标准库之外使用这个包，
     因为这里提到的代码在 Python 的不同版本之间可能会改变或被删除而不另
     行通知。

__________________________________________________________________

*note test: 105. 包包含了 Python 的所有回归测试，以及 *note
test.support: 106. 和 ‘test.regrtest’ 模块。 *note test.support: 106. 用
于增强你的测试，而 ‘test.regrtest’ 驱动测试套件。

‘test`包中每个名字以 ``test_`’ 开头的模块都是一个特定模块或功能的测试套
件。所有新的测试应该使用 *note unittest: 124. 或 *note doctest: 66. 模块
编写。一些旧的测试是使用“传统”的测试风格编写的，即比较打印出来的输出到
‘‘sys.stdout‘‘；这种测试风格被认为是过时的。

也參考
......

模块 *note unittest: 124.

     编写 PyUnit 回归测试.

模組 *note doctest: 66.

     Tests embedded in documentation strings.

* Menu:

* Writing Unit Tests for the test package::
* Running tests using the command-line interface::


File: python.info,  Node: Writing Unit Tests for the test package,  Next: Running tests using the command-line interface,  Up: test --- Python回归测试包

5.26.12.1 Writing Unit Tests for the ‘test’ package
...................................................

It is preferred that tests that use the *note unittest: 124. module
follow a few guidelines.  One is to name the test module by starting it
with ‘test_’ and end it with the name of the module being tested.  The
test methods in the test module should start with ‘test_’ and end with a
description of what the method is testing.  This is needed so that the
methods are recognized by the test driver as test methods.  Also, no
documentation string for the method should be included.  A comment (such
as ‘# Tests function returns only True or False’) should be used to
provide documentation for test methods.  This is done because
documentation strings get printed out if they exist and thus what test
is being run is not stated.

A basic boilerplate is often used:

     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()

This code pattern allows the testing suite to be run by ‘test.regrtest’,
on its own as a script that supports the *note unittest: 124. CLI, or
via the ‘python -m unittest’ CLI.

The goal for regression testing is to try to break code.  This leads to
a few guidelines to be followed:

   * The testing suite should exercise all classes, functions, and
     constants.  This includes not just the external API that is to be
     presented to the outside world but also "private" code.

   * Whitebox testing (examining the code being tested when the tests
     are being written) is preferred.  Blackbox testing (testing only
     the published user interface) is not complete enough to make sure
     all boundary and edge cases are tested.

   * Make sure all possible values are tested including invalid ones.
     This makes sure that not only all valid values are acceptable but
     also that improper values are handled correctly.

   * Exhaust as many code paths as possible.  Test where branching
     occurs and thus tailor input to make sure as many different paths
     through the code are taken.

   * Add an explicit test for any bugs discovered for the tested code.
     This will make sure that the error does not crop up again if the
     code is changed in the future.

   * Make sure to clean up after your tests (such as close and remove
     all temporary files).

   * If a test is dependent on a specific condition of the operating
     system then verify the condition already exists before attempting
     the test.

   * Import as few modules as possible and do it as soon as possible.
     This minimizes external dependencies of tests and also minimizes
     possible anomalous behavior from side-effects of importing a
     module.

   * Try to maximize code reuse.  On occasion, tests will vary by
     something as small as what type of input is used.  Minimize code
     duplication by subclassing a basic test class with a class that
     specifies the input:

          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)

     When using this pattern, remember that all classes that inherit
     from *note unittest.TestCase: 9e5. are run as tests.  The ‘Mixin’
     class in the example above does not have any data and so can’t be
     run by itself, thus it does not inherit from *note
     unittest.TestCase: 9e5.

也參考
......

Test Driven Development

     A book by Kent Beck on writing tests before code.


File: python.info,  Node: Running tests using the command-line interface,  Prev: Writing Unit Tests for the test package,  Up: test --- Python回归测试包

5.26.12.2 Running tests using the command-line interface
........................................................

The *note test: 105. package can be run as a script to drive Python’s
regression test suite, thanks to the *note -m: 443. option: ‘python -m
test’.  Under the hood, it uses ‘test.regrtest’; the call ‘python -m
test.regrtest’ used in previous Python versions still works.  Running
the script by itself automatically starts running all regression tests
in the *note test: 105. package.  It does this by finding all modules in
the package whose name starts with ‘test_’, importing them, and
executing the function ‘test_main()’ if present or loading the tests via
unittest.TestLoader.loadTestsFromModule if ‘test_main’ does not exist.
The names of tests to execute may also be passed to the script.
Specifying a single regression test (‘python -m test test_spam’) will
minimize output and only print whether the test passed or failed.

Running *note test: 105. directly allows what resources are available
for tests to use to be set.  You do this by using the ‘-u’ command-line
option.  Specifying ‘all’ as the value for the ‘-u’ option enables all
possible resources: ‘python -m test -uall’.  If all but one resource is
desired (a more common case), a comma-separated list of resources that
are not desired may be listed after ‘all’.  The command ‘python -m test
-uall,-audio,-largefile’ will run *note test: 105. with all resources
except the ‘audio’ and ‘largefile’ resources.  For a list of all
resources and more command-line options, run ‘python -m test -h’.

Some other ways to execute the regression tests depend on what platform
the tests are being executed on.  On Unix, you can run ‘make test’ at
the top-level directory where Python was built.  On Windows, executing
‘rt.bat’ from your ‘PCbuild’ directory will run all regression tests.


File: python.info,  Node: test support --- Utilities for the Python test suite,  Next: test support socket_helper --- Utilities for socket tests,  Prev: test --- Python回归测试包,  Up: 開發工具

5.26.13 ‘test.support’ — Utilities for the Python test suite
------------------------------------------------------------

The *note test.support: 106. module provides support for Python’s
regression test suite.

     備註: *note test.support: 106. is not a public module.  It is
     documented here to help Python developers write tests.  The API of
     this module is subject to change without backwards compatibility
     concerns between releases.

This module defines the following exceptions:

 -- 例外: test.support.TestFailed

     Exception to be raised when a test fails.  This is deprecated in
     favor of *note unittest: 124.-based tests and *note
     unittest.TestCase: 9e5.’s assertion methods.

 -- 例外: test.support.ResourceDenied

     Subclass of *note unittest.SkipTest: 9e9.  Raised when a resource
     (such as a network connection) is not available.  Raised by the
     *note requires(): 35c7. function.

The *note test.support: 106. module defines the following constants:

 -- Data: test.support.verbose

     ‘True’ when verbose output is enabled.  Should be checked when more
     detailed information is desired about a running test.  `verbose' is
     set by ‘test.regrtest’.

 -- Data: test.support.is_jython

     ‘True’ if the running interpreter is Jython.

 -- Data: test.support.is_android

     ‘True’ if the system is Android.

 -- Data: test.support.unix_shell

     Path for shell if not on Windows; otherwise ‘None’.

 -- Data: test.support.FS_NONASCII

     A non-ASCII character encodable by *note os.fsencode(): 5e9.

 -- Data: test.support.TESTFN

     Set to a name that is safe to use as the name of a temporary file.
     Any temporary file that is created should be closed and unlinked
     (removed).

 -- Data: test.support.TESTFN_UNICODE

     Set to a non-ASCII name for a temporary file.

 -- Data: test.support.TESTFN_ENCODING

     Set to *note sys.getfilesystemencoding(): 5ef.

 -- Data: test.support.TESTFN_UNENCODABLE

     Set to a filename (str type) that should not be able to be encoded
     by file system encoding in strict mode.  It may be ‘None’ if it’s
     not possible to generate such a filename.

 -- Data: test.support.TESTFN_UNDECODABLE

     Set to a filename (bytes type) that should not be able to be
     decoded by file system encoding in strict mode.  It may be ‘None’
     if it’s not possible to generate such a filename.

 -- Data: test.support.TESTFN_NONASCII

     Set to a filename containing the *note FS_NONASCII: 35cc.
     character.

 -- Data: test.support.LOOPBACK_TIMEOUT

     Timeout in seconds for tests using a network server listening on
     the network local loopback interface like ‘127.0.0.1’.

     The timeout is long enough to prevent test failure: it takes into
     account that the client and the server can run in different threads
     or even different processes.

     The timeout should be long enough for *note connect(): 769, *note
     recv(): 76a. and *note send(): 76d. methods of *note socket.socket:
     767.

     其默认值为5秒。

     参见 *note INTERNET_TIMEOUT: 10b2.。

 -- Data: 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.

     Usually, a timeout using *note INTERNET_TIMEOUT: 10b2. should not
     mark a test as failed, but skip the test instead: see *note
     transient_internet(): 35d2.

     其默认值是1分钟。

     参见 *note LOOPBACK_TIMEOUT: 10b1.。

 -- Data: test.support.SHORT_TIMEOUT

     Timeout in seconds to mark a test as failed if the test takes "too
     long".

     The timeout value depends on the regrtest ‘--timeout’ command line
     option.

     If a test using *note SHORT_TIMEOUT: f94. starts to fail randomly
     on slow buildbots, use *note LONG_TIMEOUT: 10b3. instead.

     其默认值为30秒。

 -- Data: test.support.LONG_TIMEOUT

     Timeout in seconds to detect when a test hangs.

     It is long enough to reduce the risk of test failure on the slowest
     Python buildbots.  It should not be used to mark a test as failed
     if the test takes "too long".  The timeout value depends on the
     regrtest ‘--timeout’ command line option.

     其默认值为5分钟。

     See also *note LOOPBACK_TIMEOUT: 10b1, *note INTERNET_TIMEOUT:
     10b2. and *note SHORT_TIMEOUT: f94.

 -- Data: test.support.SAVEDCWD

     Set to *note os.getcwd(): 1119.

 -- Data: test.support.PGO

     Set when tests can be skipped when they are not useful for PGO.

 -- Data: test.support.PIPE_MAX_SIZE

     A constant that is likely larger than the underlying OS pipe buffer
     size, to make writes blocking.

 -- Data: test.support.SOCK_MAX_SIZE

     A constant that is likely larger than the underlying OS socket
     buffer size, to make writes blocking.

 -- Data: test.support.TEST_SUPPORT_DIR

     Set to the top level directory that contains *note test.support:
     106.

 -- Data: test.support.TEST_HOME_DIR

     Set to the top level directory for the test package.

 -- Data: test.support.TEST_DATA_DIR

     Set to the ‘data’ directory within the test package.

 -- Data: test.support.MAX_Py_ssize_t

     Set to *note sys.maxsize: c15. for big memory tests.

 -- Data: test.support.max_memuse

     Set by *note set_memlimit(): 35dc. as the memory limit for big
     memory tests.  Limited by *note MAX_Py_ssize_t: 35da.

 -- Data: test.support.real_max_memuse

     Set by *note set_memlimit(): 35dc. as the memory limit for big
     memory tests.  Not limited by *note MAX_Py_ssize_t: 35da.

 -- Data: test.support.MISSING_C_DOCSTRINGS

     Return ‘True’ if running on CPython, not on Windows, and
     configuration not set with ‘WITH_DOC_STRINGS’.

 -- Data: test.support.HAVE_DOCSTRINGS

     Check for presence of docstrings.

 -- Data: test.support.TEST_HTTP_URL

     Define the URL of a dedicated HTTP server for the network tests.

 -- Data: test.support.ALWAYS_EQ

     Object that is equal to anything.  Used to test mixed type
     comparison.

 -- Data: test.support.NEVER_EQ

     Object that is not equal to anything (even to *note ALWAYS_EQ:
     35e1.).  Used to test mixed type comparison.

 -- Data: test.support.LARGEST

     Object that is greater than anything (except itself).  Used to test
     mixed type comparison.

 -- Data: test.support.SMALLEST

     Object that is less than anything (except itself).  Used to test
     mixed type comparison.

The *note test.support: 106. module defines the following functions:

 -- 函式: test.support.forget (module_name)

     Remove the module named `module_name' from ‘sys.modules’ and delete
     any byte-compiled files of the module.

 -- 函式: test.support.unload (name)

     Delete `name' from ‘sys.modules’.

 -- 函式: test.support.unlink (filename)

     Call *note os.unlink(): b18. on `filename'.  On Windows platforms,
     this is wrapped with a wait loop that checks for the existence of
     the file.

 -- 函式: test.support.rmdir (filename)

     Call *note os.rmdir(): b16. on `filename'.  On Windows platforms,
     this is wrapped with a wait loop that checks for the existence of
     the file.

 -- 函式: test.support.rmtree (path)

     Call *note shutil.rmtree(): 349. on `path' or call *note
     os.lstat(): 322. and *note os.rmdir(): b16. 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.

 -- 函式: test.support.make_legacy_pyc (source)

     Move a PEP 3147(1)/ PEP 488(2) pyc file to its legacy pyc location
     and return the file system path to the legacy pyc file.  The
     `source' value is the file system path to the source file.  It does
     not need to exist, however the PEP 3147/488 pyc file must exist.

 -- 函式: test.support.is_resource_enabled (resource)

     Return ‘True’ if `resource' is enabled and available.  The list of
     available resources is only set when ‘test.regrtest’ is executing
     the tests.

 -- 函式: test.support.python_is_optimized ()

     Return ‘True’ if Python was not built with ‘-O0’ or ‘-Og’.

 -- 函式: test.support.with_pymalloc ()

     Return ‘_testcapi.WITH_PYMALLOC’.

 -- 函式: test.support.requires (resource, msg=None)

     Raise *note ResourceDenied: 35c6. if `resource' is not available.
     `msg' is the argument to *note ResourceDenied: 35c6. if it is
     raised.  Always returns ‘True’ if called by a function whose
     ‘__name__’ is ‘'__main__'’.  Used when tests are executed by
     ‘test.regrtest’.

 -- 函式: test.support.system_must_validate_cert (f)

     Raise *note unittest.SkipTest: 9e9. on TLS certification validation
     failures.

 -- 函式: test.support.sortdict (dict)

     Return a repr of `dict' with keys sorted.

 -- 函式: test.support.findfile (filename, subdir=None)

     Return the path to the file named `filename'.  If no match is found
     `filename' is returned.  This does not equal a failure since it
     could be the path to the file.

     Setting `subdir' indicates a relative path to use to find the file
     rather than looking directly in the path directories.

 -- 函式: test.support.create_empty_file (filename)

     Create an empty file with `filename'.  If it already exists,
     truncate it.

 -- 函式: test.support.fd_count ()

     Count the number of open file descriptors.

 -- 函式: test.support.match_test (test)

     Match `test' to patterns set in *note set_match_tests(): 35f4.

 -- 函式: test.support.set_match_tests (patterns)

     Define match test with regular expression `patterns'.

 -- 函式: test.support.run_unittest (*classes)

     Execute *note unittest.TestCase: 9e5. subclasses passed to the
     function.  The function scans the classes for methods starting with
     the prefix ‘test_’ and executes the tests individually.

     It is also legal to pass strings as parameters; these should be
     keys in ‘sys.modules’.  Each associated module will be scanned by
     ‘unittest.TestLoader.loadTestsFromModule()’.  This is usually seen
     in the following ‘test_main()’ function:

          def test_main():
              support.run_unittest(__name__)

     This will run all tests defined in the named module.

 -- 函式: test.support.run_doctest (module, verbosity=None,
          optionflags=0)

     Run *note doctest.testmod(): e95. on the given `module'.  Return
     ‘(failure_count, test_count)’.

     If `verbosity' is ‘None’, *note doctest.testmod(): e95. is run with
     verbosity set to *note verbose: 35c8.  Otherwise, it is run with
     verbosity set to ‘None’.  `optionflags' is passed as ‘optionflags’
     to *note doctest.testmod(): e95.

 -- 函式: test.support.setswitchinterval (interval)

     Set the *note sys.setswitchinterval(): 218. to the given
     `interval'.  Defines a minimum interval for Android systems to
     prevent the system from hanging.

 -- 函式: 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:

          check_impl_detail()               # Only on CPython (default).
          check_impl_detail(jython=True)    # Only on Jython.
          check_impl_detail(cpython=False)  # Everywhere except CPython.

 -- 函式: test.support.check_warnings (*filters, quiet=True)

     A convenience wrapper for *note warnings.catch_warnings(): 35f9.
     that makes it easier to test that a warning was correctly raised.
     It is approximately equivalent to calling
     ‘warnings.catch_warnings(record=True)’ with *note
     warnings.simplefilter(): 35fa. set to ‘always’ and with the option
     to automatically validate the results that are recorded.

     ‘check_warnings’ accepts 2-tuples of the form ‘("message regexp",
     WarningCategory)’ as positional arguments.  If one or more
     `filters' are provided, or if the optional keyword argument `quiet'
     is ‘False’, it checks to make sure the warnings are as expected:
     each specified filter must match at least one of the warnings
     raised by the enclosed code or the test fails, and if any warnings
     are raised that do not match any of the specified filters the test
     fails.  To disable the first of these checks, set `quiet' to
     ‘True’.

     If no arguments are specified, it defaults to:

          check_warnings(("", Warning), quiet=True)

     In this case all warnings are caught and no errors are raised.

     On entry to the context manager, a ‘WarningRecorder’ instance is
     returned.  The underlying warnings list from *note
     catch_warnings(): 35f9. is available via the recorder object’s
     *note warnings: 12f. attribute.  As a convenience, the attributes
     of the object representing the most recent warning can also be
     accessed directly through the recorder object (see example below).
     If no warning has been raised, then any of the attributes that
     would otherwise be expected on an object representing a warning
     will return ‘None’.

     The recorder object also has a ‘reset()’ method, which clears the
     warnings list.

     The context manager is designed to be used like this:

          with check_warnings(("assertion is always true", SyntaxWarning),
                              ("", UserWarning)):
              exec('assert(False, "Hey!")')
              warnings.warn(UserWarning("Hide me!"))

     In this case if either warning was not raised, or some other
     warning was raised, *note check_warnings(): 35f8. would raise an
     error.

     When a test needs to look more deeply into the warnings, rather
     than just checking whether or not they occurred, code like this can
     be used:

          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

     Here all warnings will be caught, and the test code tests the
     captured warnings directly.

     3.2 版更變: New optional arguments `filters' and `quiet'.

 -- 函式: test.support.check_no_resource_warning (testcase)

     Context manager to check that no *note ResourceWarning: 5ca. was
     raised.  You must remove the object which may emit *note
     ResourceWarning: 5ca. before the end of the context manager.

 -- 函式: test.support.set_memlimit (limit)

     Set the values for *note max_memuse: 35db. and *note
     real_max_memuse: 35dd. for big memory tests.

 -- 函式: test.support.record_original_stdout (stdout)

     Store the value from `stdout'.  It is meant to hold the stdout at
     the time the regrtest began.

 -- 函式: test.support.get_original_stdout ()

     Return the original stdout set by *note record_original_stdout():
     35fc. or ‘sys.stdout’ if it’s not set.

 -- 函式: test.support.args_from_interpreter_flags ()

     Return a list of command line arguments reproducing the current
     settings in ‘sys.flags’ and ‘sys.warnoptions’.

 -- 函式: test.support.optim_args_from_interpreter_flags ()

     Return a list of command line arguments reproducing the current
     optimization settings in ‘sys.flags’.

 -- 函式: test.support.captured_stdin ()
 -- 函式: test.support.captured_stdout ()
 -- 函式: test.support.captured_stderr ()

     A context managers that temporarily replaces the named stream with
     *note io.StringIO: 91a. object.

     Example use with output streams:

          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"

     Example use with input stream:

          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")

 -- 函式: test.support.temp_dir (path=None, quiet=False)

     A context manager that creates a temporary directory at `path' and
     yields the directory.

     If `path' is ‘None’, the temporary directory is created using *note
     tempfile.mkdtemp(): 1dc5.  If `quiet' is ‘False’, the context
     manager raises an exception on error.  Otherwise, if `path' is
     specified and cannot be created, only a warning is issued.

 -- 函式: test.support.change_cwd (path, quiet=False)

     A context manager that temporarily changes the current working
     directory to `path' and yields the directory.

     If `quiet' is ‘False’, the context manager raises an exception on
     error.  Otherwise, it issues only a warning and keeps the current
     working directory the same.

 -- 函式: test.support.temp_cwd (name='tempcwd', quiet=False)

     A context manager that temporarily creates a new directory and
     changes the current working directory (CWD).

     The context manager creates a temporary directory in the current
     directory with name `name' before temporarily changing the current
     working directory.  If `name' is ‘None’, the temporary directory is
     created using *note tempfile.mkdtemp(): 1dc5.

     If `quiet' is ‘False’ and it is not possible to create or change
     the CWD, an error is raised.  Otherwise, only a warning is raised
     and the original CWD is used.

 -- 函式: test.support.temp_umask (umask)

     A context manager that temporarily sets the process umask.

 -- 函式: test.support.disable_faulthandler ()

     A context manager that replaces ‘sys.stderr’ with ‘sys.__stderr__’.

 -- 函式: test.support.gc_collect ()

     Force as many objects as possible to be collected.  This is needed
     because timely deallocation is not guaranteed by the garbage
     collector.  This means that ‘__del__’ methods may be called later
     than expected and weakrefs may remain alive for longer than
     expected.

 -- 函式: test.support.disable_gc ()

     A context manager that disables the garbage collector upon entry
     and reenables it upon exit.

 -- 函式: test.support.swap_attr (obj, attr, new_val)

     Context manager to swap out an attribute with a new object.

     用法:

          with swap_attr(obj, "attr", 5):
              ...

     This will set ‘obj.attr’ to 5 for the duration of the ‘with’ block,
     restoring the old value at the end of the block.  If ‘attr’ doesn’t
     exist on ‘obj’, it will be created and then deleted at the end of
     the block.

     The old value (or ‘None’ if it doesn’t exist) will be assigned to
     the target of the "as" clause, if there is one.

 -- 函式: test.support.swap_item (obj, attr, new_val)

     Context manager to swap out an item with a new object.

     用法:

          with swap_item(obj, "item", 5):
              ...

     This will set ‘obj["item"]’ to 5 for the duration of the ‘with’
     block, restoring the old value at the end of the block.  If ‘item’
     doesn’t exist on ‘obj’, it will be created and then deleted at the
     end of the block.

     The old value (or ‘None’ if it doesn’t exist) will be assigned to
     the target of the "as" clause, if there is one.

 -- 函式: test.support.print_warning (msg)

     Print a warning into *note sys.__stderr__: 360c.  Format the
     message as: ‘f"Warning -- {msg}"’.  If `msg' is made of multiple
     lines, add ‘"Warning -- "’ prefix to each line.

     3.9 版新加入.

 -- 函式: test.support.wait_process (pid, *, exitcode, timeout=None)

     Wait until process `pid' completes and check that the process exit
     code is `exitcode'.

     Raise an *note AssertionError: 240. if the process exit code is not
     equal to `exitcode'.

     If the process runs longer than `timeout' seconds (*note
     SHORT_TIMEOUT: f94. by default), kill the process and raise an
     *note AssertionError: 240.  The timeout feature is not available on
     Windows.

     3.9 版新加入.

 -- 函式: test.support.wait_threads_exit (timeout=60.0)

     Context manager to wait until all threads created in the ‘with’
     statement exit.

 -- 函式: test.support.start_threads (threads, unlock=None)

     Context manager to start `threads'.  It attempts to join the
     threads upon exit.

 -- 函式: test.support.calcobjsize (fmt)

     Return *note struct.calcsize(): 10c5. for ‘nP{fmt}0n’ or, if
     ‘gettotalrefcount’ exists, ‘2PnP{fmt}0P’.

 -- 函式: test.support.calcvobjsize (fmt)

     Return *note struct.calcsize(): 10c5. for ‘nPn{fmt}0n’ or, if
     ‘gettotalrefcount’ exists, ‘2PnPn{fmt}0P’.

 -- 函式: test.support.checksizeof (test, o, size)

     For testcase `test', assert that the ‘sys.getsizeof’ for `o' plus
     the GC header size equals `size'.

 -- 函式: test.support.can_symlink ()

     Return ‘True’ if the OS supports symbolic links, ‘False’ otherwise.

 -- 函式: test.support.can_xattr ()

     Return ‘True’ if the OS supports xattr, ‘False’ otherwise.

 -- 函式: @test.support.skip_unless_symlink

     A decorator for running tests that require support for symbolic
     links.

 -- 函式: @test.support.skip_unless_xattr

     A decorator for running tests that require support for xattr.

 -- 函式: @test.support.anticipate_failure (condition)

     A decorator to conditionally mark tests with *note
     unittest.expectedFailure(): 34d5.  Any use of this decorator should
     have an associated comment identifying the relevant tracker issue.

 -- 函式: @test.support.run_with_locale (catstr, *locales)

     A decorator for running a function in a different locale, correctly
     resetting it after it has finished.  `catstr' is the locale
     category as a string (for example ‘"LC_ALL"’).  The `locales'
     passed will be tried sequentially, and the first valid locale will
     be used.

 -- 函式: @test.support.run_with_tz (tz)

     A decorator for running a function in a specific timezone,
     correctly resetting it after it has finished.

 -- 函式: @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 *note
     unittest.SkipTest: 9e9.

 -- 函式: @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 *note
     unittest.SkipTest: 9e9.

 -- 函式: @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 *note
     unittest.SkipTest: 9e9.

 -- 函式: @test.support.requires_IEEE_754

     Decorator for skipping tests on non-IEEE 754 platforms.

 -- 函式: @test.support.requires_zlib

     Decorator for skipping tests if *note zlib: 14d. doesn’t exist.

 -- 函式: @test.support.requires_gzip

     Decorator for skipping tests if *note gzip: 8b. doesn’t exist.

 -- 函式: @test.support.requires_bz2

     Decorator for skipping tests if *note bz2: 13. doesn’t exist.

 -- 函式: @test.support.requires_lzma

     Decorator for skipping tests if *note lzma: ad. doesn’t exist.

 -- 函式: @test.support.requires_resource (resource)

     Decorator for skipping tests if `resource' is not available.

 -- 函式: @test.support.requires_docstrings

     Decorator for only running the test if *note HAVE_DOCSTRINGS: 35df.

 -- 函式: @test.support.cpython_only (test)

     Decorator for tests only applicable to CPython.

 -- 函式: @test.support.impl_detail (msg=None, **guards)

     Decorator for invoking *note check_impl_detail(): 35f7. on
     `guards'.  If that returns ‘False’, then uses `msg' as the reason
     for skipping the test.

 -- 函式: @test.support.no_tracing (func)

     Decorator to temporarily turn off tracing for the duration of the
     test.

 -- 函式: @test.support.refcount_test (test)

     Decorator for tests which involve reference counting.  The
     decorator does not run the test if it is not run by CPython.  Any
     trace function is unset for the duration of the test to prevent
     unexpected refcounts caused by the trace function.

 -- 函式: @test.support.reap_threads (func)

     Decorator to ensure the threads are cleaned up even if the test
     fails.

 -- 函式: @test.support.bigmemtest (size, memuse, dry_run=True)

     Decorator for bigmem tests.

     `size' is a requested size for the test (in arbitrary,
     test-interpreted units.)  `memuse' is the number of bytes per unit
     for the test, or a good estimate of it.  For example, a test that
     needs two byte buffers, of 4 GiB each, could be decorated with
     ‘@bigmemtest(size=_4G, memuse=2)’.

     The `size' argument is normally passed to the decorated test method
     as an extra argument.  If `dry_run' is ‘True’, the value passed to
     the test method may be less than the requested value.  If `dry_run'
     is ‘False’, it means the test doesn’t support dummy runs when ‘-M’
     is not specified.

 -- 函式: @test.support.bigaddrspacetest (f)

     Decorator for tests that fill the address space.  `f' is the
     function to wrap.

 -- 函式: test.support.make_bad_fd ()

     Create an invalid file descriptor by opening and closing a
     temporary file, and returning its descriptor.

 -- 函式: test.support.check_syntax_error (testcase, statement,
          errtext='', *, lineno=None, offset=None)

     Test for syntax errors in `statement' by attempting to compile
     `statement'.  `testcase' is the *note unittest: 124. instance for
     the test.  `errtext' is the regular expression which should match
     the string representation of the raised *note SyntaxError: 559.  If
     `lineno' is not ‘None’, compares to the line of the exception.  If
     `offset' is not ‘None’, compares to the offset of the exception.

 -- 函式: test.support.check_syntax_warning (testcase, statement,
          errtext='', *, lineno=1, offset=None)

     Test for syntax warning in `statement' by attempting to compile
     `statement'.  Test also that the *note SyntaxWarning: 2c9. is
     emitted only once, and that it will be converted to a *note
     SyntaxError: 559. when turned into error.  `testcase' is the *note
     unittest: 124. instance for the test.  `errtext' is the regular
     expression which should match the string representation of the
     emitted *note SyntaxWarning: 2c9. and raised *note SyntaxError:
     559.  If `lineno' is not ‘None’, compares to the line of the
     warning and exception.  If `offset' is not ‘None’, compares to the
     offset of the exception.

     3.8 版新加入.

 -- 函式: test.support.open_urlresource (url, *args, **kw)

     Open `url'.  If open fails, raises *note TestFailed: 35c5.

 -- 函式: test.support.import_module (name, deprecated=False, *,
          required_on())

     This function imports and returns the named module.  Unlike a
     normal import, this function raises *note unittest.SkipTest: 9e9.
     if the module cannot be imported.

     Module and package deprecation messages are suppressed during this
     import if `deprecated' is ‘True’.  If a module is required on a
     platform but optional for others, set `required_on' to an iterable
     of platform prefixes which will be compared against *note
     sys.platform: 3d3.

     3.1 版新加入.

 -- 函式: test.support.import_fresh_module (name, fresh=(), blocked=(),
          deprecated=False)

     This function imports and returns a fresh copy of the named Python
     module by removing the named module from ‘sys.modules’ before doing
     the import.  Note that unlike ‘reload()’, the original module is
     not affected by this operation.

     `fresh' is an iterable of additional module names that are also
     removed from the ‘sys.modules’ cache before doing the import.

     `blocked' is an iterable of module names that are replaced with
     ‘None’ in the module cache during the import to ensure that
     attempts to import them raise *note ImportError: 16c.

     The named module and any modules named in the `fresh' and `blocked'
     parameters are saved before starting the import and then reinserted
     into ‘sys.modules’ when the fresh import is complete.

     Module and package deprecation messages are suppressed during this
     import if `deprecated' is ‘True’.

     This function will raise *note ImportError: 16c. if the named
     module cannot be imported.

     Example use:

          # 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'])

     3.1 版新加入.

 -- 函式: test.support.modules_setup ()

     Return a copy of *note sys.modules: 1051.

 -- 函式: test.support.modules_cleanup (oldmodules)

     Remove modules except for `oldmodules' and ‘encodings’ in order to
     preserve internal cache.

 -- 函式: test.support.threading_setup ()

     Return current thread count and copy of dangling threads.

 -- 函式: test.support.threading_cleanup (*original_values)

     Cleanup up threads not specified in `original_values'.  Designed to
     emit a warning if a test leaves running threads in the background.

 -- 函式: test.support.join_thread (thread, timeout=30.0)

     Join a `thread' within `timeout'.  Raise an *note AssertionError:
     240. if thread is still alive after `timeout' seconds.

 -- 函式: test.support.reap_children ()

     Use this at the end of ‘test_main’ whenever sub-processes are
     started.  This will help ensure that no extra children (zombies)
     stick around to hog resources and create problems when looking for
     refleaks.

 -- 函式: test.support.get_attribute (obj, name)

     Get an attribute, raising *note unittest.SkipTest: 9e9. if *note
     AttributeError: 4a1. is raised.

 -- 函式: test.support.catch_threading_exception ()

     Context manager catching *note threading.Thread: 21a. exception
     using *note threading.excepthook(): 35e.

     Attributes set when an exception is caught:

        * ‘exc_type’

        * ‘exc_value’

        * ‘exc_traceback’

        * ‘thread’

     See *note threading.excepthook(): 35e. documentation.

     These attributes are deleted at the context manager exit.

     用法:

          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)

     3.8 版新加入.

 -- 函式: test.support.catch_unraisable_exception ()

     Context manager catching unraisable exception using *note
     sys.unraisablehook(): 35a.

     Storing the exception value (‘cm.unraisable.exc_value’) creates a
     reference cycle.  The reference cycle is broken explicitly when the
     context manager exits.

     Storing the object (‘cm.unraisable.object’) can resurrect it if it
     is set to an object which is being finalized.  Exiting the context
     manager clears the stored object.

     用法:

          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)

     3.8 版新加入.

 -- 函式: test.support.load_package_tests (pkg_dir, loader,
          standard_tests, pattern)

     Generic implementation of the *note unittest: 124. ‘load_tests’
     protocol for use in test packages.  `pkg_dir' is the root directory
     of the package; `loader', `standard_tests', and `pattern' are the
     arguments expected by ‘load_tests’.  In simple cases, the test
     package’s ‘__init__.py’ can be the following:

          import os
          from test.support import load_package_tests

          def load_tests(*args):
              return load_package_tests(os.path.dirname(__file__), *args)

 -- 函式: test.support.fs_is_case_insensitive (directory)

     Return ‘True’ if the file system for `directory' is
     case-insensitive.

 -- 函式: test.support.detect_api_mismatch (ref_api, other_api, *,
          ignore=())

     Returns the set of attributes, functions or methods of `ref_api'
     not found on `other_api', except for a defined list of items to be
     ignored in this check specified in `ignore'.

     By default this skips private attributes beginning with ’_’ but
     includes all magic methods, i.e.  those starting and ending in
     ’__’.

     3.5 版新加入.

 -- 函式: test.support.patch (test_instance, object_to_patch, attr_name,
          new_value)

     Override `object_to_patch.attr_name' with `new_value'.  Also add
     cleanup procedure to `test_instance' to restore `object_to_patch'
     for `attr_name'.  The `attr_name' should be a valid attribute for
     `object_to_patch'.

 -- 函式: test.support.run_in_subinterp (code)

     Run `code' in subinterpreter.  Raise *note unittest.SkipTest: 9e9.
     if *note tracemalloc: 11d. is enabled.

 -- 函式: test.support.check_free_after_iterating (test, iter, cls,
          args=())

     Assert that `iter' is deallocated after iterating.

 -- 函式: test.support.missing_compiler_executable (cmd_names=[])

     Check for the existence of the compiler executables whose names are
     listed in `cmd_names' or all the compiler executables when
     `cmd_names' is empty and return the first missing executable or
     ‘None’ when none is found missing.

 -- 函式: test.support.check__all__ (test_case, module,
          name_of_module=None, extra=(), blacklist=())

     Assert that the ‘__all__’ variable of `module' contains all public
     names.

     The module’s public names (its API) are detected automatically
     based on whether they match the public name convention and were
     defined in `module'.

     The `name_of_module' argument can specify (as a string or tuple
     thereof) what module(s) an API could be defined in order to be
     detected as a public API. One case for this is when `module'
     imports part of its public API from other modules, possibly a C
     backend (like ‘csv’ and its ‘_csv’).

     The `extra' argument can be a set of names that wouldn’t otherwise
     be automatically detected as "public", like objects without a
     proper ‘__module__’ attribute.  If provided, it will be added to
     the automatically detected ones.

     The `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 use:

          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)

     3.6 版新加入.

The *note test.support: 106. module defines the following classes:

 -- 類別: test.support.TransientResource (exc, **kwargs)

     Instances are a context manager that raises *note ResourceDenied:
     35c6. 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 *note with: 7da. statement.
     Only if all pairs match properly against attributes on the
     exception is *note ResourceDenied: 35c6. raised.

 -- 類別: test.support.EnvironmentVarGuard

     Class used to temporarily set or unset environment variables.
     Instances can be used as a context manager and have a complete
     dictionary interface for querying/modifying the underlying
     ‘os.environ’.  After exit from the context manager all changes to
     environment variables done through this instance will be rolled
     back.

     3.1 版更變: Added dictionary interface.

 -- 成員函式: EnvironmentVarGuard.set (envvar, value)

     Temporarily set the environment variable ‘envvar’ to the value of
     ‘value’.

 -- 成員函式: EnvironmentVarGuard.unset (envvar)

     Temporarily unset the environment variable ‘envvar’.

 -- 類別: test.support.SuppressCrashReport

     A context manager used to try to prevent crash dialog popups on
     tests that are expected to crash a subprocess.

     On Windows, it disables Windows Error Reporting dialogs using
     SetErrorMode(3).

     On UNIX, *note resource.setrlimit(): 3643. is used to set *note
     resource.RLIMIT_CORE: 3644.’s soft limit to 0 to prevent coredump
     file creation.

     On both platforms, the old value is restored by *note __exit__():
     d5e.

 -- 類別: 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:

          with CleanImport('foo'):
              importlib.import_module('foo')  # New reference.

 -- 類別: test.support.DirsOnSysPath (*paths)

     A context manager to temporarily add directories to sys.path.

     This makes a copy of *note sys.path: 261, appends any directories
     given as positional arguments, then reverts *note sys.path: 261. to
     the copied settings when the context ends.

     Note that `all' *note sys.path: 261. modifications in the body of
     the context manager, including replacement of the object, will be
     reverted at the end of the block.

 -- 類別: test.support.SaveSignals

     Class to save and restore signal handlers registered by the Python
     signal handler.

 -- 類別: test.support.Matcher

      -- 成員函式: matches (self, d, **kwargs)

          Try to match a single dict with the supplied arguments.

      -- 成員函式: match_value (self, k, dv, v)

          Try to match a single stored value (`dv') with a supplied
          value (`v').

 -- 類別: test.support.WarningsRecorder

     Class used to record warnings for unit tests.  See documentation of
     *note check_warnings(): 35f8. above for more details.

 -- 類別: test.support.BasicTestRunner

      -- 成員函式: run (test)

          Run `test' and return the result.

 -- 類別: test.support.FakePath (path)

     Simple *note path-like object: 472.  It implements the
     ‘__fspath__()’ method which just returns the `path' argument.  If
     `path' is an exception, it will be raised in ‘__fspath__()’.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3147

   (2) https://www.python.org/dev/peps/pep-0488

   (3) 
https://msdn.microsoft.com/en-us/library/windows/desktop/ms680621.aspx


File: python.info,  Node: test support socket_helper --- Utilities for socket tests,  Next: test support script_helper --- Utilities for the Python execution tests,  Prev: test support --- Utilities for the Python test suite,  Up: 開發工具

5.26.14 ‘test.support.socket_helper’ — Utilities for socket tests
-----------------------------------------------------------------

The *note test.support.socket_helper: 109. module provides support for
socket tests.

3.9 版新加入.

 -- Data: test.support.socket_helper.IPV6_ENABLED

     设置为 ‘True’ 如果主机打开IPv6, 否则 ‘False’ .

 -- 函式: test.support.socket_helper.find_unused_port
          (family=socket.AF_INET, socktype=socket.SOCK_STREAM)

     Returns an unused port that should be suitable for binding.  This
     is achieved by creating a temporary socket with the same family and
     type as the ‘sock’ parameter (default is *note AF_INET: 26f8, *note
     SOCK_STREAM: d52.), and binding it to the specified host address
     (defaults to ‘0.0.0.0’) with the port set to 0, eliciting an unused
     ephemeral port from the OS. The temporary socket is then closed and
     deleted, and the ephemeral port is returned.

     Either this method or *note bind_port(): 3652. should be used for
     any tests where a server socket needs to be bound to a particular
     port for the duration of the test.  Which one to use depends on
     whether the calling code is creating a Python socket, or if an
     unused port needs to be provided in a constructor or passed to an
     external program (i.e.  the ‘-accept’ argument to openssl’s
     s_server mode).  Always prefer *note bind_port(): 3652. over *note
     find_unused_port(): 3651. where possible.  Using a hard coded port
     is discouraged since it can make multiple instances of the test
     impossible to run simultaneously, which is a problem for buildbots.

 -- 函式: test.support.socket_helper.bind_port (sock, host=HOST)

     Bind the socket to a free port and return the port number.  Relies
     on ephemeral ports in order to ensure we are using an unbound port.
     This is important as many tests may be running simultaneously,
     especially in a buildbot environment.  This method raises an
     exception if the ‘sock.family’ is *note AF_INET: 26f8. and
     ‘sock.type’ is *note SOCK_STREAM: d52, and the socket has
     ‘SO_REUSEADDR’ or ‘SO_REUSEPORT’ set on it.  Tests should never set
     these socket options for TCP/IP sockets.  The only case for setting
     these options is testing multicasting via multiple UDP sockets.

     Additionally, if the ‘SO_EXCLUSIVEADDRUSE’ socket option is
     available (i.e.  on Windows), it will be set on the socket.  This
     will prevent anyone else from binding to our host/port for the
     duration of the test.

 -- 函式: test.support.socket_helper.bind_unix_socket (sock, addr)

     Bind a unix socket, raising *note unittest.SkipTest: 9e9. if *note
     PermissionError: 6f6. is raised.

 -- 函式: @test.support.socket_helper.skip_unless_bind_unix_socket

     A decorator for running tests that require a functional ‘bind()’
     for Unix sockets.

 -- 函式: test.support.socket_helper.transient_internet (resource_name,
          *, timeout=30.0, errnos=())

     A context manager that raises *note ResourceDenied: 35c6. when
     various issues with the internet connection manifest themselves as
     exceptions.


File: python.info,  Node: test support script_helper --- Utilities for the Python execution tests,  Next: test support bytecode_helper --- Support tools for testing correct bytecode generation,  Prev: test support socket_helper --- Utilities for socket tests,  Up: 開發工具

5.26.15 ‘test.support.script_helper’ — Utilities for the Python execution tests
-------------------------------------------------------------------------------

The *note test.support.script_helper: 108. module provides support for
Python’s script execution tests.

 -- 函式: test.support.script_helper.interpreter_requires_environment ()

     Return ‘True’ if ‘sys.executable interpreter’ requires environment
     variables in order to be able to run at all.

     This is designed to be used with ‘@unittest.skipIf()’ to annotate
     tests that need to use an ‘assert_python*()’ function to launch an
     isolated mode (‘-I’) or no environment mode (‘-E’) sub-interpreter
     process.

     A normal build & test does not run into this situation but it can
     happen when trying to run the standard library test suite from an
     interpreter that doesn’t have an obvious home with Python’s current
     home finding logic.

     Setting *note PYTHONHOME: 5d0. is one way to get most of the
     testsuite to run in that situation.  *note PYTHONPATH: a34. or
     ‘PYTHONUSERSITE’ are other common environment variables that might
     impact whether or not the interpreter can start.

 -- 函式: test.support.script_helper.run_python_until_end (*args,
          **env_vars)

     Set up the environment based on `env_vars' for running the
     interpreter in a subprocess.  The values can include ‘__isolated’,
     ‘__cleanenv’, ‘__cwd’, and ‘TERM’.

     3.9 版更變: The function no longer strips whitespaces from
     `stderr'.

 -- 函式: test.support.script_helper.assert_python_ok (*args,
          **env_vars)

     Assert that running the interpreter with `args' and optional
     environment variables `env_vars' succeeds (‘rc == 0’) and return a
     ‘(return code, stdout, stderr)’ tuple.

     If the ‘__cleanenv’ keyword is set, `env_vars' is used as a fresh
     environment.

     Python is started in isolated mode (command line option ‘-I’),
     except if the ‘__isolated’ keyword is set to ‘False’.

     3.9 版更變: The function no longer strips whitespaces from
     `stderr'.

 -- 函式: test.support.script_helper.assert_python_failure (*args,
          **env_vars)

     Assert that running the interpreter with `args' and optional
     environment variables `env_vars' fails (‘rc != 0’) and return a
     ‘(return code, stdout, stderr)’ tuple.

     See *note assert_python_ok(): 3658. for more options.

     3.9 版更變: The function no longer strips whitespaces from
     `stderr'.

 -- 函式: test.support.script_helper.spawn_python (*args,
          stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kw)

     Run a Python subprocess with the given arguments.

     `kw' is extra keyword args to pass to *note subprocess.Popen():
     3db.  Returns a *note subprocess.Popen: 3db. object.

 -- 函式: test.support.script_helper.kill_python (p)

     Run the given *note subprocess.Popen: 3db. process until completion
     and return stdout.

 -- 函式: test.support.script_helper.make_script (script_dir,
          script_basename, source, omit_suffix=False)

     Create script containing `source' in path `script_dir' and
     `script_basename'.  If `omit_suffix' is ‘False’, append ‘.py’ to
     the name.  Return the full script path.

 -- 函式: test.support.script_helper.make_zip_script (zip_dir,
          zip_basename, script_name, name_in_zip=None)

     Create zip file at `zip_dir' and `zip_basename' with extension
     ‘zip’ which contains the files in `script_name'.  `name_in_zip' is
     the archive name.  Return a tuple containing ‘(full path, full path
     of archive name)’.

 -- 函式: test.support.script_helper.make_pkg (pkg_dir, init_source='')

     Create a directory named `pkg_dir' containing an ‘__init__’ file
     with `init_source' as its contents.

 -- 函式: test.support.script_helper.make_zip_pkg (zip_dir,
          zip_basename, pkg_name, script_basename, source, depth=1,
          compiled=False)

     Create a zip package directory with a path of `zip_dir' and
     `zip_basename' containing an empty ‘__init__’ file and a file
     `script_basename' containing the `source'.  If `compiled' is
     ‘True’, both source files will be compiled and added to the zip
     package.  Return a tuple of the full zip path and the archive name
     for the zip file.


File: python.info,  Node: test support bytecode_helper --- Support tools for testing correct bytecode generation,  Prev: test support script_helper --- Utilities for the Python execution tests,  Up: 開發工具

5.26.16 ‘test.support.bytecode_helper’ — Support tools for testing correct bytecode generation
----------------------------------------------------------------------------------------------

The *note test.support.bytecode_helper: 107. module provides support for
testing and inspecting bytecode generation.

3.9 版新加入.

The module defines the following class:

 -- 類別: test.support.bytecode_helper.BytecodeTestCase
          (unittest.TestCase)

     This class has custom assertion methods for inspecting bytecode.

 -- 成員函式: BytecodeTestCase.get_disassembly_as_string (co)

     Return the disassembly of `co' as string.

 -- 成員函式: BytecodeTestCase.assertInBytecode (x, opname,
          argval=_UNSPECIFIED)

     Return instr if `opname' is found, otherwise throws *note
     AssertionError: 240.

 -- 成員函式: BytecodeTestCase.assertNotInBytecode (x, opname,
          argval=_UNSPECIFIED)

     Throws *note AssertionError: 240. if `opname' is found.


File: python.info,  Node: 调试和分析,  Next: 軟體封裝與發布,  Prev: 開發工具,  Up: Python 標準函式庫 Standard Library

5.27 调试和分析
===============

这些库可以帮助你进行 Python 开发：调试器使你能够逐步执行代码，分析堆栈帧
并设置中断点等等，性能分析器可以运行代码并为你提供执行时间的详细数据，使
你能够找出你的程序中的瓶颈。 审计事件提供运行时行为的可见性，如果没有此
工具则需要进行侵入式调试或修补。

* Menu:

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


File: python.info,  Node: 审计事件表,  Next: bdb --- Debugger framework,  Up: 调试和分析

5.27.1 审计事件表
-----------------

下表包含了在整个 CPython 运行时和标准库中由 *note sys.audit(): 1056. 或
*note PySys_Audit(): 1068. 调用所引发的全部事件。 这些调用是在 3.8.0 或
更高版本中添加了 (参见 PEP 578(1))。

请参阅 *note sys.addaudithook(): 366a. 和 *note PySys_AddAuditHook():
366b. 了解有关处理这些事件的详细信息。

`CPython implementation detail:' 此表是根据 CPython 文档生成的，可能无法
表示其他实现所引发的事件。 请参阅你的运行时专属的文档了解实际引发的事件
。

Audit event                        Arguments                                                   References
                                                                                               
-------------------------------------------------------------------------------------------------------------------
                                                                                               
array.__new__                      ‘typecode’, ‘initializer’                                   *note [1]: 216.
                                                                                               
                                                                                               
builtins.breakpoint                ‘breakpointhook’                                            *note [1]: 40b.
                                                                                               
                                                                                               
builtins.id                        ‘id’                                                        *note [1]: e4b.
                                                                                               
                                                                                               
builtins.input                     ‘prompt’                                                    *note [1]: d33.
                                                                                               
                                                                                               
builtins.input/result              ‘result’                                                    *note [1]: d33.
                                                                                               
                                                                                               
code.__new__                       ‘code’, ‘filename’, ‘name’, ‘argcount’,                     *note [1]: 2cd.
                                   ‘posonlyargcount’, ‘kwonlyargcount’, ‘nlocals’,             
                                   ‘stacksize’, ‘flags’
                                   
                                                                                               
compile                            ‘source’, ‘filename’                                        *note [1]: 2e7.
                                                                                               
                                                                                               
cpython.PyInterpreterState_Clear                                                               *note [1]: 366c.
                                                                                               
                                                                                               
cpython.PyInterpreterState_New                                                                 *note [1]: 366d.
                                                                                               
                                                                                               
cpython._PySys_ClearAuditHooks                                                                 *note [1]: 6c0.
                                                                                               
                                                                                               
cpython.run_command                ‘command’                                                   *note [1]: 1340.
                                                                                               
                                                                                               
cpython.run_file                   ‘filename’                                                  *note [1]: 366e.
                                                                                               
                                                                                               
cpython.run_interactivehook        ‘hook’                                                      *note [1]: 9ca.
                                                                                               
                                                                                               
cpython.run_module                 ‘module-name’                                               *note [1]: 443.
                                                                                               
                                                                                               
cpython.run_startup                ‘filename’                                                  *note [1]: 9cb.
                                                                                               
                                                                                               
cpython.run_stdin                                                                              *note [1]: 366f.
                                                                                               
                                                                                               
ctypes.addressof                   ‘obj’                                                       *note [1]: 2476.
                                                                                               
                                                                                               
ctypes.call_function               ‘func_pointer’, ‘arguments’                                 *note [1]: 246b.
                                                                                               
                                                                                               
ctypes.cdata                       ‘address’                                                   *note [1]: 2487.
                                                                                               
                                                                                               
ctypes.cdata/buffer                ‘pointer’, ‘size’, ‘offset’                                 *note [1]: 2485.*note [2]: 2486.
                                                                                               
                                                                                               
ctypes.create_string_buffer        ‘init’, ‘size’                                              *note [1]: 2428.
                                                                                               
                                                                                               
ctypes.create_unicode_buffer       ‘init’, ‘size’                                              *note [1]: 10d7.
                                                                                               
                                                                                               
ctypes.dlopen                      ‘name’                                                      *note [1]: 2468.
                                                                                               
                                                                                               
ctypes.dlsym                       ‘library’, ‘name’                                           *note [1]: 2468.
                                                                                               
                                                                                               
ctypes.dlsym/handle                ‘handle’, ‘name’                                            *note [1]: 2468.
                                                                                               
                                                                                               
ctypes.get_errno                                                                               *note [1]: 2462.
                                                                                               
                                                                                               
ctypes.get_last_error                                                                          *note [1]: 2464.
                                                                                               
                                                                                               
ctypes.seh_exception               ‘code’                                                      *note [1]: 246b.
                                                                                               
                                                                                               
ctypes.set_errno                   ‘errno’                                                     *note [1]: 2463.
                                                                                               
                                                                                               
ctypes.set_last_error              ‘error’                                                     *note [1]: 2465.
                                                                                               
                                                                                               
ctypes.string_at                   ‘address’, ‘size’                                           *note [1]: 247f.
                                                                                               
                                                                                               
ctypes.wstring_at                  ‘address’, ‘size’                                           *note [1]: 2481.
                                                                                               
                                                                                               
ensurepip.bootstrap                ‘root’                                                      *note [1]: 3670.
                                                                                               
                                                                                               
exec                               ‘code_object’                                               *note [1]: c61.*note [2]: d0c.
                                                                                               
                                                                                               
fcntl.fcntl                        ‘fd’, ‘cmd’, ‘arg’                                          *note [1]: 27e8.
                                                                                               
                                                                                               
fcntl.flock                        ‘fd’, ‘operation’                                           *note [1]: 3671.
                                                                                               
                                                                                               
fcntl.ioctl                        ‘fd’, ‘request’, ‘arg’                                      *note [1]: ea2.
                                                                                               
                                                                                               
fcntl.lockf                        ‘fd’, ‘cmd’, ‘len’, ‘start’, ‘whence’                       *note [1]: e17.
                                                                                               
                                                                                               
ftplib.connect                     ‘self’, ‘host’, ‘port’                                      *note [1]: 2e5f.
                                                                                               
                                                                                               
ftplib.sendcmd                     ‘self’, ‘cmd’                                               *note [1]: 2e63.*note [2]: 2e64.
                                                                                               
                                                                                               
function.__new__                   ‘code’                                                      *note [1]: 1af3.
                                                                                               
                                                                                               
gc.get_objects                     ‘generation’                                                *note [1]: 2fe.
                                                                                               
                                                                                               
gc.get_referents                   ‘objs’                                                      *note [1]: fb7.
                                                                                               
                                                                                               
gc.get_referrers                   ‘objs’                                                      *note [1]: fb6.
                                                                                               
                                                                                               
glob.glob                          ‘pathname’, ‘recursive’                                     *note [1]: 6bd.*note [2]: 6be.
                                                                                               
                                                                                               
imaplib.open                       ‘self’, ‘host’, ‘port’                                      *note [1]: 1b1.
                                                                                               
                                                                                               
imaplib.send                       ‘self’, ‘data’                                              *note [1]: 2eae.
                                                                                               
                                                                                               
import                             ‘module’, ‘filename’, ‘sys.path’, ‘sys.meta_path’,          *note [1]: ce7.
                                   ‘sys.path_hooks’                                            
                                   
                                                                                               
marshal.dumps                      ‘value’, ‘version’                                          *note [1]: 1e42.
                                                                                               
                                                                                               
marshal.load                                                                                   *note [1]: 112b.
                                                                                               
                                                                                               
marshal.loads                      ‘bytes’                                                     *note [1]: 112b.
                                                                                               
                                                                                               
mmap.__new__                       ‘fileno’, ‘length’, ‘access’, ‘offset’                      *note [1]: 31c.
                                                                                               
                                                                                               
msvcrt.get_osfhandle               ‘fd’                                                        *note [1]: 3672.
                                                                                               
                                                                                               
msvcrt.locking                     ‘fd’, ‘mode’, ‘nbytes’                                      *note [1]: 3673.
                                                                                               
                                                                                               
msvcrt.open_osfhandle              ‘handle’, ‘flags’                                           *note [1]: 3674.
                                                                                               
                                                                                               
nntplib.connect                    ‘self’, ‘host’, ‘port’                                      *note [1]: 1c6.*note [2]: 1c7.
                                                                                               
                                                                                               
nntplib.putline                    ‘self’, ‘line’                                              *note [1]: 1c6.*note [2]: 1c7.
                                                                                               
                                                                                               
object.__delattr__                 ‘obj’, ‘name’                                               *note [1]: 1563.
                                                                                               
                                                                                               
object.__getattr__                 ‘obj’, ‘name’                                               *note [1]: 549.
                                                                                               
                                                                                               
object.__setattr__                 ‘obj’, ‘name’, ‘value’                                      *note [1]: eee.
                                                                                               
                                                                                               
open                               ‘file’, ‘mode’, ‘flags’                                     *note [1]: 16f.*note [2]: 74d.*note [3]: 758.
                                                                                               
                                                                                               
os.add_dll_directory               ‘path’                                                      *note [1]: 2f3.
                                                                                               
                                                                                               
os.chdir                           ‘path’                                                      *note [1]: 16e.*note [2]: 74e.
                                                                                               
                                                                                               
os.chflags                         ‘path’, ‘flags’                                             *note [1]: b0e.*note [2]: 20aa.
                                                                                               
                                                                                               
os.chmod                           ‘path’, ‘mode’, ‘dir_fd’                                    *note [1]: b0f.*note [2]: 74f.*note [3]: 1160.
                                                                                               
                                                                                               
os.chown                           ‘path’, ‘uid’, ‘gid’, ‘dir_fd’                              *note [1]: b10.*note [2]: 750.*note [3]: 20ab.
                                                                                               
                                                                                               
os.exec                            ‘path’, ‘args’, ‘env’                                       *note [1]: 20e7.
                                                                                               
                                                                                               
os.fork                                                                                        *note [1]: a42.
                                                                                               
                                                                                               
os.forkpty                                                                                     *note [1]: 20ff.
                                                                                               
                                                                                               
os.fwalk                           ‘top’, ‘topdown’, ‘onerror’, ‘follow_symlinks’, ‘dir_fd’    *note [1]: 4ba.
                                                                                               
                                                                                               
os.getxattr                        ‘path’, ‘attribute’                                         *note [1]: b26.
                                                                                               
                                                                                               
os.kill                            ‘pid’, ‘sig’                                                *note [1]: db9.
                                                                                               
                                                                                               
os.killpg                          ‘pgid’, ‘sig’                                               *note [1]: 10e1.
                                                                                               
                                                                                               
os.link                            ‘src’, ‘dst’, ‘src_dir_fd’, ‘dst_dir_fd’                    *note [1]: b11.
                                                                                               
                                                                                               
os.listdir                         ‘path’                                                      *note [1]: b1c.
                                                                                               
                                                                                               
os.listxattr                       ‘path’                                                      *note [1]: b27.
                                                                                               
                                                                                               
os.lockf                           ‘fd’, ‘cmd’, ‘len’                                          *note [1]: b35.
                                                                                               
                                                                                               
os.mkdir                           ‘path’, ‘mode’, ‘dir_fd’                                    *note [1]: 4c3.*note [2]: b12.
                                                                                               
                                                                                               
os.posix_spawn                     ‘path’, ‘argv’, ‘env’                                       *note [1]: 381.*note [2]: 114d.
                                                                                               
                                                                                               
os.putenv                          ‘key’, ‘value’                                              *note [1]: 1cd.
                                                                                               
                                                                                               
os.remove                          ‘path’, ‘dir_fd’                                            *note [1]: b13.*note [2]: 20b2.*note [3]: b18.
                                                                                               
                                                                                               
os.removexattr                     ‘path’, ‘attribute’                                         *note [1]: b28.
                                                                                               
                                                                                               
os.rename                          ‘src’, ‘dst’, ‘src_dir_fd’, ‘dst_dir_fd’                    *note [1]: b14.*note [2]: 20b3.*note [3]: b15.
                                                                                               
                                                                                               
os.rmdir                           ‘path’, ‘dir_fd’                                            *note [1]: b16.
                                                                                               
                                                                                               
os.scandir                         ‘path’                                                      *note [1]: 389.
                                                                                               
                                                                                               
os.setxattr                        ‘path’, ‘attribute’, ‘value’, ‘flags’                       *note [1]: b29.
                                                                                               
                                                                                               
os.spawn                           ‘mode’, ‘path’, ‘args’, ‘env’                               *note [1]: 20a3.
                                                                                               
                                                                                               
os.startfile                       ‘path’, ‘operation’                                         *note [1]: 2113.
                                                                                               
                                                                                               
os.symlink                         ‘src’, ‘dst’, ‘dir_fd’                                      *note [1]: b17.
                                                                                               
                                                                                               
os.system                          ‘command’                                                   *note [1]: e86.
                                                                                               
                                                                                               
os.truncate                        ‘fd’, ‘length’                                              *note [1]: 755.*note [2]: 813.
                                                                                               
                                                                                               
os.unsetenv                        ‘key’                                                       *note [1]: 1cc.
                                                                                               
                                                                                               
os.utime                           ‘path’, ‘times’, ‘ns’, ‘dir_fd’                             *note [1]: b19.
                                                                                               
                                                                                               
os.walk                            ‘top’, ‘topdown’, ‘onerror’, ‘followlinks’                  *note [1]: 747.
                                                                                               
                                                                                               
pathlib.Path.glob                  ‘self’, ‘pattern’                                           *note [1]: 1084.
                                                                                               
                                                                                               
pathlib.Path.rglob                 ‘self’, ‘pattern’                                           *note [1]: 1085.
                                                                                               
                                                                                               
pdb.Pdb                                                                                        *note [1]: 1d3.
                                                                                               
                                                                                               
pickle.find_class                  ‘module’, ‘name’                                            *note [1]: 1e1d.
                                                                                               
                                                                                               
poplib.connect                     ‘self’, ‘host’, ‘port’                                      *note [1]: 1d5.*note [2]: 1d6.
                                                                                               
                                                                                               
poplib.putline                     ‘self’, ‘line’                                              *note [1]: 1d5.*note [2]: 1d6.
                                                                                               
                                                                                               
pty.spawn                          ‘argv’                                                      *note [1]: 97f.
                                                                                               
                                                                                               
resource.prlimit                   ‘pid’, ‘resource’, ‘limits’                                 *note [1]: 986.
                                                                                               
                                                                                               
resource.setrlimit                 ‘resource’, ‘limits’                                        *note [1]: 3643.
                                                                                               
                                                                                               
setopencodehook                                                                                *note [1]: 2144.
                                                                                               
                                                                                               
shutil.chown                       ‘path’, ‘user’, ‘group’                                     *note [1]: b51.
                                                                                               
                                                                                               
shutil.copyfile                    ‘src’, ‘dst’                                                *note [1]: 383.*note [2]: 384.*note [3]: 382.
                                                                                               
                                                                                               
shutil.copymode                    ‘src’, ‘dst’                                                *note [1]: 383.*note [2]: 1de4.
                                                                                               
                                                                                               
shutil.copystat                    ‘src’, ‘dst’                                                *note [1]: 384.*note [2]: b52.
                                                                                               
                                                                                               
shutil.copytree                    ‘src’, ‘dst’                                                *note [1]: 347.
                                                                                               
                                                                                               
shutil.make_archive                ‘base_name’, ‘format’, ‘root_dir’, ‘base_dir’               *note [1]: 348.
                                                                                               
                                                                                               
shutil.move                        ‘src’, ‘dst’                                                *note [1]: 385.
                                                                                               
                                                                                               
shutil.rmtree                      ‘path’                                                      *note [1]: 349.
                                                                                               
                                                                                               
shutil.unpack_archive              ‘filename’, ‘extract_dir’, ‘format’                         *note [1]: c68.
                                                                                               
                                                                                               
signal.pthread_kill                ‘thread_id’, ‘signalnum’                                    *note [1]: b55.
                                                                                               
                                                                                               
smtplib.connect                    ‘self’, ‘host’, ‘port’                                      *note [1]: 10cd.
                                                                                               
                                                                                               
smtplib.send                       ‘self’, ‘data’                                              *note [1]: 1de.
                                                                                               
                                                                                               
socket.__new__                     ‘self’, ‘family’, ‘type’, ‘protocol’                        *note [1]: 767.
                                                                                               
                                                                                               
socket.bind                        ‘self’, ‘address’                                           *note [1]: 27e2.
                                                                                               
                                                                                               
socket.connect                     ‘self’, ‘address’                                           *note [1]: 769.*note [2]: 27e4.
                                                                                               
                                                                                               
socket.getaddrinfo                 ‘host’, ‘port’, ‘family’, ‘type’, ‘protocol’                *note [1]: 270c.
                                                                                               
                                                                                               
socket.gethostbyaddr               ‘ip_address’                                                *note [1]: fad.
                                                                                               
                                                                                               
socket.gethostbyname               ‘hostname’                                                  *note [1]: 27da.*note [2]: fae.
                                                                                               
                                                                                               
socket.gethostname                                                                             *note [1]: 2064.
                                                                                               
                                                                                               
socket.getnameinfo                 ‘sockaddr’                                                  *note [1]: 270d.
                                                                                               
                                                                                               
socket.getservbyname               ‘servicename’, ‘protocolname’                               *note [1]: 27dc.
                                                                                               
                                                                                               
socket.getservbyport               ‘port’, ‘protocolname’                                      *note [1]: 27dd.
                                                                                               
                                                                                               
socket.sendmsg                     ‘self’, ‘address’                                           *note [1]: 76f.
                                                                                               
                                                                                               
socket.sendto                      ‘self’, ‘address’                                           *note [1]: 770.
                                                                                               
                                                                                               
socket.sethostname                 ‘name’                                                      *note [1]: b5f.
                                                                                               
                                                                                               
sqlite3.connect                    ‘database’                                                  *note [1]: 4e0.
                                                                                               
                                                                                               
subprocess.Popen                   ‘executable’, ‘args’, ‘cwd’, ‘env’                          *note [1]: 3db.
                                                                                               
                                                                                               
sys._current_frames                                                                            *note [1]: e60.
                                                                                               
                                                                                               
sys._getframe                                                                                  *note [1]: f25.
                                                                                               
                                                                                               
sys.addaudithook                                                                               *note [1]: 366b.*note [2]: 366a.
                                                                                               
                                                                                               
sys.excepthook                     ‘hook’, ‘type’, ‘value’, ‘traceback’                        *note [1]: f24.
                                                                                               
                                                                                               
sys.set_asyncgen_hooks_finalizer                                                               *note [1]: 1057.
                                                                                               
                                                                                               
sys.set_asyncgen_hooks_firstiter                                                               *note [1]: 1057.
                                                                                               
                                                                                               
sys.setprofile                                                                                 *note [1]: eff.
                                                                                               
                                                                                               
sys.settrace                                                                                   *note [1]: f00.
                                                                                               
                                                                                               
sys.unraisablehook                 ‘hook’, ‘unraisable’                                        *note [1]: 35a.
                                                                                               
                                                                                               
syslog.closelog                                                                                *note [1]: 3675.
                                                                                               
                                                                                               
syslog.openlog                     ‘ident’, ‘logoption’, ‘facility’                            *note [1]: 10a6.
                                                                                               
                                                                                               
syslog.setlogmask                  ‘maskpri’                                                   *note [1]: 3676.
                                                                                               
                                                                                               
syslog.syslog                      ‘priority’, ‘message’                                       *note [1]: 3677.
                                                                                               
                                                                                               
telnetlib.Telnet.open              ‘self’, ‘host’, ‘port’                                      *note [1]: 2f1c.
                                                                                               
                                                                                               
telnetlib.Telnet.write             ‘self’, ‘buffer’                                            *note [1]: 2f2c.
                                                                                               
                                                                                               
tempfile.mkdtemp                   ‘fullpath’                                                  *note [1]: c96.*note [2]: 1dc5.
                                                                                               
                                                                                               
tempfile.mkstemp                   ‘fullpath’                                                  *note [1]: e0e.*note [2]: 1dc3.*note [3]: 1dc4.
                                                                                               
                                                                                               
urllib.Request                     ‘fullurl’, ‘data’, ‘headers’, ‘method’                      *note [1]: 87b.
                                                                                               
                                                                                               
webbrowser.open                    ‘url’                                                       *note [1]: 2d0b.
                                                                                               
                                                                                               
winreg.ConnectRegistry             ‘computer_name’, ‘key’                                      *note [1]: 3678.
                                                                                               
                                                                                               
winreg.CreateKey                   ‘key’, ‘sub_key’, ‘access’                                  *note [1]: 3679.*note [2]: 367a.
                                                                                               
                                                                                               
winreg.DeleteKey                   ‘key’, ‘sub_key’, ‘access’                                  *note [1]: 367b.*note [2]: 367c.
                                                                                               
                                                                                               
winreg.DeleteValue                 ‘key’, ‘value’                                              *note [1]: 367d.
                                                                                               
                                                                                               
winreg.DisableReflectionKey        ‘key’                                                       *note [1]: 367e.
                                                                                               
                                                                                               
winreg.EnableReflectionKey         ‘key’                                                       *note [1]: 367f.
                                                                                               
                                                                                               
winreg.EnumKey                     ‘key’, ‘index’                                              *note [1]: 3680.
                                                                                               
                                                                                               
winreg.EnumValue                   ‘key’, ‘index’                                              *note [1]: 3681.
                                                                                               
                                                                                               
winreg.ExpandEnvironmentStrings    ‘str’                                                       *note [1]: 3682.
                                                                                               
                                                                                               
winreg.LoadKey                     ‘key’, ‘sub_key’, ‘file_name’                               *note [1]: 3683.
                                                                                               
                                                                                               
winreg.OpenKey                     ‘key’, ‘sub_key’, ‘access’                                  *note [1]: 3684.
                                                                                               
                                                                                               
winreg.OpenKey/result              ‘key’                                                       *note [1]: 3679.*note [2]: 367a.*note [3]: 3684.
                                                                                               
                                                                                               
winreg.PyHKEY.Detach               ‘key’                                                       *note [1]: 3685.
                                                                                               
                                                                                               
winreg.QueryInfoKey                ‘key’                                                       *note [1]: 3686.
                                                                                               
                                                                                               
winreg.QueryReflectionKey          ‘key’                                                       *note [1]: 3687.
                                                                                               
                                                                                               
winreg.QueryValue                  ‘key’, ‘sub_key’, ‘value_name’                              *note [1]: 3688.*note [2]: 3689.
                                                                                               
                                                                                               
winreg.SaveKey                     ‘key’, ‘file_name’                                          *note [1]: 368a.
                                                                                               
                                                                                               
winreg.SetValue                    ‘key’, ‘sub_key’, ‘type’, ‘value’                           *note [1]: 368b.*note [2]: 368c.
                                                                                               

下列事件只在内部被引发，而不会回应任何 CPython 公共 API:

审计事件                       实参
                               
-------------------------------------------------------------------------------
                               
_winapi.CreateFile             ‘file_name’, ‘desired_access’, ‘share_mode’,
                               ‘creation_disposition’,
                               ‘flags_and_attributes’
                               
                               
_winapi.CreateJunction         ‘src_path’, ‘dst_path’
                               
                               
_winapi.CreateNamedPipe        ‘name’, ‘open_mode’, ‘pipe_mode’
                               
                               
_winapi.CreatePipe

_winapi.CreateProcess          ‘application_name’, ‘command_line’,
                               ‘current_directory’
                               
                               
_winapi.OpenProcess            ‘process_id’, ‘desired_access’
                               
                               
_winapi.TerminateProcess       ‘handle’, ‘exit_code’
                               
                               
ctypes.PyObj_FromPtr           ‘obj’
                               

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0578


File: python.info,  Node: bdb --- Debugger framework,  Next: faulthandler —— 转储 Python 的跟踪信息,  Prev: 审计事件表,  Up: 调试和分析

5.27.2 ‘bdb’ — Debugger framework
---------------------------------

`Source code:' Lib/bdb.py(1)

__________________________________________________________________

The *note bdb: e. module handles basic debugger functions, like setting
breakpoints or managing execution via the debugger.

定义了以下异常：

 -- 例外: bdb.BdbQuit

     Exception raised by the *note Bdb: d60. class for quitting the
     debugger.

The *note bdb: e. module also defines two classes:

 -- 類別: bdb.Breakpoint (self, file, line, temporary=0, cond=None,
          funcname=None)

     This class implements temporary breakpoints, ignore counts,
     disabling and (re-)enabling, and conditionals.

     Breakpoints are indexed by number through a list called
     ‘bpbynumber’ and by ‘(file, line)’ pairs through ‘bplist’.  The
     former points to a single instance of class *note Breakpoint: 3690.
     The latter points to a list of such instances since there may be
     more than one breakpoint per line.

     When creating a breakpoint, its associated filename should be in
     canonical form.  If a `funcname' is defined, a breakpoint hit will
     be counted when the first line of that function is executed.  A
     conditional breakpoint always counts a hit.

     *note Breakpoint: 3690. instances have the following methods:

      -- 成員函式: deleteMe ()

          Delete the breakpoint from the list associated to a file/line.
          If it is the last breakpoint in that position, it also deletes
          the entry for the file/line.

      -- 成員函式: enable ()

          Mark the breakpoint as enabled.

      -- 成員函式: disable ()

          Mark the breakpoint as disabled.

      -- 成員函式: bpformat ()

          Return a string with all the information about the breakpoint,
          nicely formatted:

             * The breakpoint number.

             * If it is temporary or not.

             * Its file,line position.

             * The condition that causes a break.

             * If it must be ignored the next N times.

             * The breakpoint hit count.

          3.2 版新加入.

      -- 成員函式: bpprint (out=None)

          Print the output of *note bpformat(): 3694. to the file `out',
          or if it is ‘None’, to standard output.

 -- 類別: bdb.Bdb (skip=None)

     The *note Bdb: d60. class acts as a generic Python debugger base
     class.

     This class takes care of the details of the trace facility; a
     derived class should implement user interaction.  The standard
     debugger class (*note pdb.Pdb: 1d3.) is an example.

     The `skip' argument, if given, must be an iterable of glob-style
     module name patterns.  The debugger will not step into frames that
     originate in a module that matches one of these patterns.  Whether
     a frame is considered to originate in a certain module is
     determined by the ‘__name__’ in the frame globals.

     3.1 版新加入: `skip' 参数。

     The following methods of *note Bdb: d60. normally don’t need to be
     overridden.

      -- 成員函式: canonic (filename)

          Auxiliary method for getting a filename in a canonical form,
          that is, as a case-normalized (on case-insensitive
          filesystems) absolute path, stripped of surrounding angle
          brackets.

      -- 成員函式: reset ()

          Set the ‘botframe’, ‘stopframe’, ‘returnframe’ and ‘quitting’
          attributes with values ready to start debugging.

      -- 成員函式: trace_dispatch (frame, event, arg)

          This function is installed as the trace function of debugged
          frames.  Its return value is the new trace function (in most
          cases, that is, itself).

          The default implementation decides how to dispatch a frame,
          depending on the type of event (passed as a string) that is
          about to be executed.  `event' can be one of the following:

             * ‘"line"’: A new line of code is going to be executed.

             * ‘"call"’: A function is about to be called, or another
               code block entered.

             * ‘"return"’: A function or other code block is about to
               return.

             * ‘"exception"’: An exception has occurred.

             * ‘"c_call"’: A C function is about to be called.

             * ‘"c_return"’: A C function has returned.

             * ‘"c_exception"’: A C function has raised an exception.

          For the Python events, specialized functions (see below) are
          called.  For the C events, no action is taken.

          The `arg' parameter depends on the previous event.

          See the documentation for *note sys.settrace(): f00. for more
          information on the trace function.  For more information on
          code and frame objects, refer to *note 标准类型层级结构: 1553.

      -- 成員函式: dispatch_line (frame)

          If the debugger should stop on the current line, invoke the
          *note user_line(): 369a. method (which should be overridden in
          subclasses).  Raise a *note BdbQuit: 368f. exception if the
          ‘Bdb.quitting’ flag is set (which can be set from *note
          user_line(): 369a.).  Return a reference to the *note
          trace_dispatch(): 3698. method for further tracing in that
          scope.

      -- 成員函式: dispatch_call (frame, arg)

          If the debugger should stop on this function call, invoke the
          *note user_call(): 369c. method (which should be overridden in
          subclasses).  Raise a *note BdbQuit: 368f. exception if the
          ‘Bdb.quitting’ flag is set (which can be set from *note
          user_call(): 369c.).  Return a reference to the *note
          trace_dispatch(): 3698. method for further tracing in that
          scope.

      -- 成員函式: dispatch_return (frame, arg)

          If the debugger should stop on this function return, invoke
          the *note user_return(): 369e. method (which should be
          overridden in subclasses).  Raise a *note BdbQuit: 368f.
          exception if the ‘Bdb.quitting’ flag is set (which can be set
          from *note user_return(): 369e.).  Return a reference to the
          *note trace_dispatch(): 3698. method for further tracing in
          that scope.

      -- 成員函式: dispatch_exception (frame, arg)

          If the debugger should stop at this exception, invokes the
          *note user_exception(): 36a0. method (which should be
          overridden in subclasses).  Raise a *note BdbQuit: 368f.
          exception if the ‘Bdb.quitting’ flag is set (which can be set
          from *note user_exception(): 36a0.).  Return a reference to
          the *note trace_dispatch(): 3698. method for further tracing
          in that scope.

     Normally derived classes don’t override the following methods, but
     they may if they want to redefine the definition of stopping and
     breakpoints.

      -- 成員函式: stop_here (frame)

          This method checks if the `frame' is somewhere below
          ‘botframe’ in the call stack.  ‘botframe’ is the frame in
          which debugging started.

      -- 成員函式: break_here (frame)

          This method checks if there is a breakpoint in the filename
          and line belonging to `frame' or, at least, in the current
          function.  If the breakpoint is a temporary one, this method
          deletes it.

      -- 成員函式: break_anywhere (frame)

          This method checks if there is a breakpoint in the filename of
          the current frame.

     Derived classes should override these methods to gain control over
     debugger operation.

      -- 成員函式: user_call (frame, argument_list)

          This method is called from *note dispatch_call(): 369b. when
          there is the possibility that a break might be necessary
          anywhere inside the called function.

      -- 成員函式: user_line (frame)

          This method is called from *note dispatch_line(): 3699. when
          either *note stop_here(): 36a1. or *note break_here(): 36a2.
          yields ‘True’.

      -- 成員函式: user_return (frame, return_value)

          This method is called from *note dispatch_return(): 369d. when
          *note stop_here(): 36a1. yields ‘True’.

      -- 成員函式: user_exception (frame, exc_info)

          This method is called from *note dispatch_exception(): 369f.
          when *note stop_here(): 36a1. yields ‘True’.

      -- 成員函式: do_clear (arg)

          Handle how a breakpoint must be removed when it is a temporary
          one.

          This method must be implemented by derived classes.

     Derived classes and clients can call the following methods to
     affect the stepping state.

      -- 成員函式: set_step ()

          Stop after one line of code.

      -- 成員函式: set_next (frame)

          Stop on the next line in or below the given frame.

      -- 成員函式: set_return (frame)

          Stop when returning from the given frame.

      -- 成員函式: set_until (frame)

          Stop when the line with the line no greater than the current
          one is reached or when returning from current frame.

      -- 成員函式: set_trace ([frame])

          Start debugging from `frame'.  If `frame' is not specified,
          debugging starts from caller’s frame.

      -- 成員函式: set_continue ()

          Stop only at breakpoints or when finished.  If there are no
          breakpoints, set the system trace function to ‘None’.

      -- 成員函式: set_quit ()

          Set the ‘quitting’ attribute to ‘True’.  This raises *note
          BdbQuit: 368f. in the next call to one of the ‘dispatch_*()’
          methods.

     Derived classes and clients can call the following methods to
     manipulate breakpoints.  These methods return a string containing
     an error message if something went wrong, or ‘None’ if all is well.

      -- 成員函式: set_break (filename, lineno, temporary=0, cond,
               funcname)

          Set a new breakpoint.  If the `lineno' line doesn’t exist for
          the `filename' passed as argument, return an error message.
          The `filename' should be in canonical form, as described in
          the *note canonic(): 3696. method.

      -- 成員函式: clear_break (filename, lineno)

          Delete the breakpoints in `filename' and `lineno'.  If none
          were set, an error message is returned.

      -- 成員函式: clear_bpbynumber (arg)

          Delete the breakpoint which has the index `arg' in the
          ‘Breakpoint.bpbynumber’.  If `arg' is not numeric or out of
          range, return an error message.

      -- 成員函式: clear_all_file_breaks (filename)

          Delete all breakpoints in `filename'.  If none were set, an
          error message is returned.

      -- 成員函式: clear_all_breaks ()

          Delete all existing breakpoints.

      -- 成員函式: get_bpbynumber (arg)

          Return a breakpoint specified by the given number.  If `arg'
          is a string, it will be converted to a number.  If `arg' is a
          non-numeric string, if the given breakpoint never existed or
          has been deleted, a *note ValueError: 16d. is raised.

          3.2 版新加入.

      -- 成員函式: get_break (filename, lineno)

          Check if there is a breakpoint for `lineno' of `filename'.

      -- 成員函式: get_breaks (filename, lineno)

          Return all breakpoints for `lineno' in `filename', or an empty
          list if none are set.

      -- 成員函式: get_file_breaks (filename)

          Return all breakpoints in `filename', or an empty list if none
          are set.

      -- 成員函式: get_all_breaks ()

          Return all breakpoints that are set.

     Derived classes and clients can call the following methods to get a
     data structure representing a stack trace.

      -- 成員函式: get_stack (f, t)

          Get a list of records for a frame and all higher (calling) and
          lower frames, and the size of the higher part.

      -- 成員函式: format_stack_entry (frame_lineno, lprefix=': ')

          Return a string with information about a stack entry,
          identified by a ‘(frame, lineno)’ tuple:

             * The canonical form of the filename which contains the
               frame.

             * The function name, or ‘"<lambda>"’.

             * The input arguments.

             * The return value.

             * The line of code (if it exists).

     The following two methods can be called by clients to use a
     debugger to debug a *note statement: 1cef, given as a string.

      -- 成員函式: run (cmd, globals=None, locals=None)

          Debug a statement executed via the *note exec(): d0c.
          function.  `globals' defaults to ‘__main__.__dict__’, `locals'
          defaults to `globals'.

      -- 成員函式: runeval (expr, globals=None, locals=None)

          Debug an expression executed via the *note eval(): c61.
          function.  `globals' and `locals' have the same meaning as in
          *note run(): 36b8.

      -- 成員函式: runctx (cmd, globals, locals)

          For backwards compatibility.  Calls the *note run(): 36b8.
          method.

      -- 成員函式: runcall (func, /, *args, **kwds)

          Debug a single function call, and return its result.

Finally, the module defines the following functions:

 -- 函式: bdb.checkfuncname (b, frame)

     Check whether we should break here, depending on the way the
     breakpoint `b' was set.

     If it was set via line number, it checks if ‘b.line’ is the same as
     the one in the frame also passed as argument.  If the breakpoint
     was set via function name, we have to check we are in the right
     frame (the right function) and if we are in its first executable
     line.

 -- 函式: bdb.effective (file, line, frame)

     Determine if there is an effective (active) breakpoint at this line
     of code.  Return a tuple of the breakpoint and a boolean that
     indicates if it is ok to delete a temporary breakpoint.  Return
     ‘(None, None)’ if there is no matching breakpoint.

 -- 函式: bdb.set_trace ()

     Start debugging with a *note Bdb: d60. instance from caller’s
     frame.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/bdb.py


File: python.info,  Node: faulthandler —— 转储 Python 的跟踪信息,  Next: pdb --- Python 的调试器,  Prev: bdb --- Debugger framework,  Up: 调试和分析

5.27.3 ‘faulthandler’ —— 转储 Python 的跟踪信息
-----------------------------------------------

3.3 版新加入.

__________________________________________________________________

当故障、超时或收到用户信号时，利用本模块内的函数可转储 Python 跟踪信息。
调用 *note faulthandler.enable(): 642. 可安装 ‘SIGSEGV’ 、 ‘SIGFPE’ 、
‘SIGABRT’ 、 ‘SIGBUS’ 和 ‘SIGILL’ 信号的故障处理程序。通过设置 *note
PYTHONFAULTHANDLER: aa7. 环境变量或 *note -X: 290. ‘faulthandler’ 命令行
参数，还可以在启动时开启这些设置。

故障处理程序与操作系统的故障处理程序兼容，比如 Apport 或 Windows 故障处
理程序等。如果 ‘sigaltstack()’ 函数可用，本模块将为信号处理程序使用备用
堆栈。这样即便堆栈溢出也能转储跟踪信息。

故障处理程序将在灾难性场合调用，因此只能使用信号安全的函数（比如不能在堆
上分配内存）。由于这一限制，与正常的 Python 跟踪相比，转储量是最小的。

   * 只支持 ASCII 码。编码时会用到 ‘backslashreplace’ 错误处理程序。

   * 每个字符串限制在 500 个字符以内。

   * 只会显式文件名、函数名和行号。（不显示源代码）

   * 上限是 100 页内存帧和 100 个线程。

   * 反序排列：最近的调用最先显示。

默认情况下，Python 的跟踪信息会写入 *note sys.stderr: 1ea.。为了能看到跟
踪信息，应用程序必须运行于终端中。日志文件也可以传给 *note
faulthandler.enable(): 642.。

本模块是用 C 语言实现的，所以才能在崩溃或 Python 死锁时转储跟踪信息。

在 Python 启动时， *note Python 开发模式: 160. 会调用 *note
faulthandler.enable(): 642.。

* Menu:

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


File: python.info,  Node: 转储跟踪信息,  Next: 错误处理程序的状态,  Up: faulthandler —— 转储 Python 的跟踪信息

5.27.3.1 转储跟踪信息
.....................

 -- 函式: faulthandler.dump_traceback (file=sys.stderr,
          all_threads=True)

     将所有线程的跟踪数据转储到 `file' 中。如果 `all_threads' 为
     ‘False’，则只转储当前线程。

     3.5 版更變: 增加了向本函数传入文件描述符的支持。


File: python.info,  Node: 错误处理程序的状态,  Next: 一定时间后转储跟踪数据。,  Prev: 转储跟踪信息,  Up: faulthandler —— 转储 Python 的跟踪信息

5.27.3.2 错误处理程序的状态
...........................

 -- 函式: faulthandler.enable (file=sys.stderr, all_threads=True)

     启用故障处理程序：为 ‘SIGSEGV’ 、 ‘SIGFPE’ 、 ‘SIGABRT’ 、 ‘SIGBUS’
     和 ‘SIGILL’ 信号安装处理程序，以转储 Python 跟踪信息。如果
     `all_threads' 为 ‘True’，则会为每个运行中的线程生成跟踪信息。否则只
     转储当前线程。

     该 `文件' 必须保持打开状态，直至禁用故障处理程序为止：参见 *note
     文件描述符相关话题: 36c2.。

     3.5 版更變: 增加了向本函数传入文件描述符的支持。

     3.6 版更變: 在 Windows 系统中，同时会安装一个 Windows 异常处理程序
     。

 -- 函式: faulthandler.disable ()

     停用故障处理程序：卸载由 *note enable(): 642. 安装的信号处理程序。

 -- 函式: faulthandler.is_enabled ()

     检查故障处理程序是否被启用。


File: python.info,  Node: 一定时间后转储跟踪数据。,  Next: 转储用户信号的跟踪信息。,  Prev: 错误处理程序的状态,  Up: faulthandler —— 转储 Python 的跟踪信息

5.27.3.3 一定时间后转储跟踪数据。
.................................

 -- 函式: faulthandler.dump_traceback_later (timeout, repeat=False,
          file=sys.stderr, exit=False)

     在 `timeout' 秒超时后，转储所有线程的跟踪信息，如果 `repeat' 为
     ‘True’，则每隔 `timeout' 秒转储一次。如果 `exit' 为 ‘True’，则在转
     储跟踪信息后调用 ‘_exit()’，参数 status=1。请注意， ‘_exit()’ 会立
     即关闭进程，这意味着不做任何清理工作，如刷新文件缓冲区等。如果调用
     两次函数，则新的调用将取代之前的参数，超时时间也会重置。计时器的精
     度为亚秒级。

     `file' 必须保持打开状态，直至跟踪信息转储完毕，或调用了 *note
     cancel_dump_traceback_later(): 36c6. ：参见 *note
     文件描述符相关话题: 36c2.。

     本函数用一个看门狗线程实现。

     3.7 版更變: 该函数现在总是可用。

     3.5 版更變: 增加了向本函数传入文件描述符的支持。

 -- 函式: faulthandler.cancel_dump_traceback_later ()

     取消 *note dump_traceback_later(): 7cc. 的最后一次调用。


File: python.info,  Node: 转储用户信号的跟踪信息。,  Next: 文件描述符相关话题,  Prev: 一定时间后转储跟踪数据。,  Up: faulthandler —— 转储 Python 的跟踪信息

5.27.3.4 转储用户信号的跟踪信息。
.................................

 -- 函式: faulthandler.register (signum, file=sys.stderr,
          all_threads=True, chain=False)

     注册一个用户信号：为 `signum' 信号安装一个处理程序，将所有线程或当
     前线程（`all_threads' 为 ‘False’ 时）的跟踪信息转储到 `file' 中。如
     果 chain 为 ‘True’，则调用前一个处理程序。

     `file' 必须保持打开状态，直至信号被 *note unregister(): 36c8. 注销
     ：参见 *note 文件描述符相关话题: 36c2.。

     Windows 中不可用。

     3.5 版更變: 增加了向本函数传入文件描述符的支持。

 -- 函式: faulthandler.unregister (signum)

     注销一个用户信号：卸载由 *note register(): 7ca. 安装的 `signum' 信
     号处理程序。如果信号已注册，返回 ‘True’，否则返回 ‘False’。

     Windows 中不可用。


File: python.info,  Node: 文件描述符相关话题,  Next: 示例<39>,  Prev: 转储用户信号的跟踪信息。,  Up: faulthandler —— 转储 Python 的跟踪信息

5.27.3.5 文件描述符相关话题
...........................

*note enable(): 642. 、 *note dump_traceback_later(): 7cc. 和 *note
register(): 7ca. 保留其 `file' 参数给出的文件描述符。 如果文件关闭，文件
描述符将被一个新文件重新使用；或者用 *note os.dup2(): 4c4. 替换了文件描
述符，则跟踪信息将被写入另一个文件。 每次文件被替换时，都会再次调用这些
函数。


File: python.info,  Node: 示例<39>,  Prev: 文件描述符相关话题,  Up: faulthandler —— 转储 Python 的跟踪信息

5.27.3.6 示例
.............

在 Linux 中启用和停用内存段故障的默认处理程序：

     $ 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


File: python.info,  Node: pdb --- Python 的调试器,  Next: Python Profilers 分析器,  Prev: faulthandler —— 转储 Python 的跟踪信息,  Up: 调试和分析

5.27.4 ‘pdb’ — Python 的调试器
------------------------------

`源代码：' Lib/pdb.py(1)

__________________________________________________________________

*note pdb: c9. 模块定义了一个交互式源代码调试器，用于 Python 程序。它支
持在源码行间设置（有条件的）断点和单步执行，检视堆栈帧，列出源码列表，以
及在任何堆栈帧的上下文中运行任意 Python 代码。它还支持事后调试，可以在程
序控制下调用。

调试器是可扩展的——调试器实际被定义为 *note Pdb: 1d3. 类。该类目前没有文
档，但通过阅读源码很容易理解它。扩展接口使用了 *note bdb: e. 和 *note
cmd: 19. 模块。

调试器的提示符是 ‘(Pdb)’。在调试器的控制下运行程序的典型用法是:

     >>> import pdb
     >>> import mymodule
     >>> pdb.run('mymodule.test()')
     > <string>(0)?()
     (Pdb) continue
     > <string>(1)?()
     (Pdb) continue
     NameError: 'spam'
     > <string>(1)?()
     (Pdb)

3.3 版更變: 由 *note readline: de. 模块实现的 Tab 补全可用于补全本模块的
命令和命令的参数，例如，Tab 补全会提供当前的全局变量和局部变量，用作 ‘p’
命令的参数。

也可以将 ‘pdb.py’ 作为脚本调用，来调试其他脚本。例如:

     python3 -m pdb myscript.py

当作为脚本调用时，如果要调试的程序异常退出，pdb 调试将自动进入事后调试。
事后调试之后（或程序正常退出之后），pdb 将重新启动程序。自动重启会保留
pdb 的状态（如断点），在大多数情况下，这比在退出程序的同时退出调试器更加
实用。

3.2 版新加入: ‘pdb.py’ 现在接受 ‘-c’ 选项，可以执行命令，这与将该命令写
入 ‘.pdbrc’ 文件相同，请参阅 *note 调试器命令: 36ce.。

3.7 版新加入: ‘pdb.py’ 现在接受 ‘-m’ 选项，该选项用于执行一个模块，类似
于 ‘python3 -m’。与脚本相同，调试器将暂停在待执行模块第一行前。

The typical usage to break into the debugger is to insert:

     import pdb; pdb.set_trace()

at the location you want to break into the debugger, and then run the
program.  You can then step through the code following this statement,
and continue running without the debugger using the *note continue:
36cf. command.

3.7 版新加入: 内置函数 *note breakpoint(): 40b.，当以默认参数调用它时，
可以用来代替 ‘import pdb; pdb.set_trace()’。

检查已崩溃程序的典型用法是:

     >>> 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)

本模块定义了下列函数，每个函数进入调试器的方式略有不同：

 -- 函式: pdb.run (statement, globals=None, locals=None)

     在调试器控制范围内执行 `statement' （以字符串或代码对象的形式提供）
     。调试器提示符会在执行代码前出现，你可以设置断点并键入 *note
     continue: 36cf.，也可以使用 *note step: 36d0. 或 *note next: 36d1.
     逐步执行语句（上述所有命令在后文有说明）。可选参数 `globals' 和
     `locals' 指定代码执行环境，默认时使用 *note __main__: 1. 模块的字典
     。（请参阅内置函数 *note exec(): d0c. 或 *note eval(): c61. 的说明
     。）

 -- 函式: pdb.runeval (expression, globals=None, locals=None)

     在调试器控制范围内执行 `expression' （以字符串或代码对象的形式提供
     ）。*note runeval(): 36d2. 返回时将返回表达式的值。本函数在其他方面
     与 *note run(): 34af. 类似。

 -- 函式: pdb.runcall (function, *args, **kwds)

     使用给定的参数调用 `function' （以函数或方法对象的形式提供，不能是
     字符串）。*note runcall(): 36d3. 返回的是所调用函数的返回值。调试器
     提示符将在进入函数后立即出现。

 -- 函式: pdb.set_trace (*, header=None)

     在调用本函数的堆栈帧处进入调试器。用于硬编码一个断点到程序中的固定
     点处，即使该代码不在调试状态（如断言失败时）。如果传入 `header'，它
     将在调试开始前被打印到控制台。

     3.7 版更變: 仅关键字参数 `header'。

 -- 函式: pdb.post_mortem (traceback=None)

     进入 `traceback' 对象的事后调试。如果没有给定 `traceback'，默认使用
     当前正在处理的异常之一（默认时，必须存在正在处理的异常）。

 -- 函式: pdb.pm ()

     在 *note sys.last_traceback: 36d5. 中查找 traceback，并进入其事后调
     试。

‘run*’ 函数和 *note set_trace(): 4c8. 都是别名，用于实例化 *note Pdb:
1d3. 类和调用同名方法。如果要使用其他功能，则必须自己执行以下操作：

 -- 類別: pdb.Pdb (completekey='tab', stdin=None, stdout=None,
          skip=None, nosigint=False, readrc=True)

     *note Pdb: 1d3. 是调试器类。

     `completekey'、`stdin' 和 `stdout' 参数都会传递给底层的 *note
     cmd.Cmd: 3276. 类，请参考相应的描述。

     如果给出 `skip' 参数，则它必须是一个迭代器，可以迭代出 glob-style 样
     式的模块名称。如果遇到匹配上述样式的模块，调试器将不会进入来自该模
     块的堆栈帧。 (2)

     默认情况下，当发出 ‘continue’ 命令时，Pdb 将为 SIGINT 信号设置一个
     处理程序（SIGINT 信号是用户在控制台按 ‘Ctrl-C’ 时发出的）。这使用户
     可以按 ‘Ctrl-C’ 再次进入调试器。如果希望 Pdb 不要修改 SIGINT 处理程
     序，请将 `nosigint' 设置为 true。

     `readrc' 参数默认为 true，它控制 Pdb 是否从文件系统加载 .pdbrc 文件
     。

     启用跟踪且带有 `skip' 参数的调用示范:

          import pdb; pdb.Pdb(skip=['django.*']).set_trace()

     引发一个 *note 审计事件: fa1. ‘pdb.Pdb’，没有附带参数。

     3.1 版新加入: `skip' 参数。

     3.2 版新加入: `nosigint' 参数。在这之前，Pdb 不为 SIGINT 设置处理程
     序。

     3.6 版更變: `readrc' 参数。

      -- 成員函式: run (statement, globals=None, locals=None)
      -- 成員函式: runeval (expression, globals=None, locals=None)
      -- 成員函式: runcall (function, *args, **kwds)
      -- 成員函式: set_trace ()

          请参阅上文解释同名函数的文档。

* Menu:

* 调试器命令::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/pdb.py

   (2) (1) 一个帧是否会被认为源自特定模块是由帧全局变量 ‘__name__’ 来决
定的。


File: python.info,  Node: 调试器命令,  Up: pdb --- Python 的调试器

5.27.4.1 调试器命令
...................

下方列出的是调试器可接受的命令。如下所示，大多数命令可以缩写为一个或两个
字母。如 ‘h(elp)’ 表示可以输入 ‘h’ 或 ‘help’ 来输入帮助命令（但不能输入
‘he’ 或 ‘hel’，也不能是 ‘H’ 或 ‘Help’ 或 ‘HELP’）。命令的参数必须用空格
（空格符或制表符）分隔。在命令语法中，可选参数括在方括号 (‘[]’) 中，使用
时请勿输入方括号。命令语法中的选择项由竖线 (‘|’) 分隔。

输入一个空白行将重复最后输入的命令。例外：如果最后一个命令是 *note list:
36db. 命令，则会列出接下来的 11 行。

调试器无法识别的命令将被认为是 Python 语句，并在正在调试的程序的上下文中
执行。Python 语句也可以用感叹号 (‘!’) 作为前缀。这是检查正在调试的程序的
强大方法，甚至可以修改变量或调用函数。当此类语句发生异常，将打印异常名称
，但调试器的状态不会改变。

调试器支持 *note 别名: 36dc.。别名可以有参数，使得调试器对被检查的上下文
有一定程度的适应性。

在一行中可以输入多个命令，以 ‘;;’ 分隔。（不能使用单个 ‘;’，因为它用于分
隔传递给 Python 解释器的一行中的多条语句。）切分命令很无脑，总是在第一个
‘;;’ 对处将输入切分开，即使它位于带引号的字符串之中。

如果文件 ‘.pdbrc’ 存在于用户主目录或当前目录中，则将其读入并执行，等同于
在调试器提示符下键入该文件。这对于别名很有用。若两个文件都存在则首先读取
主目录中的文件，且本地文件可以覆盖其中定义的别名。

3.2 版更變: ‘.pdbrc’ 现在可以包含继续调试的命令，如 *note continue:
36cf. 或 *note next: 36d1.。文件中的这些命令以前是无效的。

 -- Pdbcommand: h(elp) [command]

     不带参数时，显示可用的命令列表。参数为 `command' 时，打印有关该命令
     的帮助。‘help pdb’ 显示完整文档（即 *note pdb: c9. 模块的文档字符串
     ）。由于 `command' 参数必须是标识符，因此要获取 ‘!’ 的帮助必须输入
     ‘help exec’。

 -- Pdbcommand: w(here)

     打印堆栈回溯，最新一帧在底部。有一个箭头指向当前帧，该帧决定了大多
     数命令的上下文。

 -- Pdbcommand: d(own) [count]

     在堆栈回溯中，将当前帧向下移动 `count' 级（默认为 1 级，移向更新的
     帧）。

 -- Pdbcommand: u(p) [count]

     在堆栈回溯中，将当前帧向上移动 `count' 级（默认为 1 级，移向更老的
     帧）。

 -- Pdbcommand: b(reak) [([filename:]lineno | function) [, condition]]

     如果带有 `lineno' 参数，则在当前文件相应行处设置一个断点。如果带有
     `function' 参数，则在该函数的第一条可执行语句处设置一个断点。行号可
     以加上文件名和冒号作为前缀，以在另一个文件（可能是尚未加载的文件）
     中设置一个断点。另一个文件将在 *note sys.path: 261. 范围内搜索。请
     注意，每个断点都分配有一个编号，其他所有断点命令都引用该编号。

     如果第二个参数存在，它应该是一个表达式，且它的计算值为 true 时断点
     才起作用。

     如果不带参数执行，将列出所有中断，包括每个断点、命中该断点的次数、
     当前的忽略次数以及关联的条件（如果有）。

 -- Pdbcommand: tbreak [([filename:]lineno | function) [, condition]]

     临时断点，在第一次命中时会自动删除。它的参数与 *note break: 36e1. 相
     同。

 -- Pdbcommand: cl(ear) [filename:lineno | bpnumber ...]

     如果参数是 `filename:lineno'，则清除此行上的所有断点。如果参数是空
     格分隔的断点编号列表，则清除这些断点。如果不带参数，则清除所有断点
     （但会先提示确认）。

 -- Pdbcommand: disable [bpnumber ...]

     禁用断点，断点以空格分隔的断点编号列表给出。禁用断点表示它不会导致
     程序停止执行，但是与清除断点不同，禁用的断点将保留在断点列表中并且
     可以（重新）启用。

 -- Pdbcommand: enable [bpnumber ...]

     启用指定的断点。

 -- Pdbcommand: ignore bpnumber [count]

     为指定的断点编号设置忽略次数。如果省略 count，则忽略次数将设置为 0。
     忽略次数为 0 时断点将变为活动状态。如果为非零值，在每次达到断点，且
     断点未禁用，且关联条件计算值为 true 的情况下，该忽略次数会递减。

 -- Pdbcommand: condition bpnumber [condition]

     为断点设置一个新 `condition'，它是一个表达式，且它的计算值为 true 时
     断点才起作用。如果没有给出 `condition'，则删除现有条件，也就是将断
     点设为无条件。

 -- Pdbcommand: commands [bpnumber]

     为编号是 `bpnumber' 的断点指定一系列命令。命令内容将显示在后续的几
     行中。输入仅包含 ‘end’ 的行来结束命令列表。举个例子:

          (Pdb) commands 1
          (com) p some_variable
          (com) end
          (Pdb)

     要删除断点上的所有命令，请输入 ‘commands’ 并立即以 ‘end’ 结尾，也就
     是不指定任何命令。

     如果不带 `bpnumber' 参数，‘commands’ 作用于最后一个被设置的断点。

     可以为断点指定命令来重新启动程序。只需使用 *note continue: 36cf. 或
     *note step: 36d0. 命令或其他可以继续运行程序的命令。

     如果指定了某个继续运行程序的命令（目前包括 *note continue: 36cf,
     *note step: 36d0, *note next: 36d1, *note return: 36e9, *note jump:
     36ea, *note quit: 36eb. 及它们的缩写）将终止命令列表（就像该命令后
     紧跟着 end）。因为在任何时候继续运行下去（即使是简单的 next 或
     step），都可能会遇到另一个断点，该断点可能具有自己的命令列表，这导
     致要执行的列表含糊不清。

     如果在命令列表中加入 ’silent’ 命令，那么在该断点处停下时就不会打印
     常规信息。如果希望断点打印特定信息后继续运行，这可能是理想的。如果
     没有其他命令来打印一些信息，则看不到已达到断点的迹象。

 -- Pdbcommand: s(tep)

     运行当前行，在第一个可以停止的位置（在被调用的函数内部或在当前函数
     的下一行）停下。

 -- Pdbcommand: n(ext)

     继续运行，直到运行到当前函数的下一行，或当前函数返回为止。（ *note
     next: 36d1. 和 *note step: 36d0. 之间的区别在于，*note step: 36d0.
     进入被调用函数内部并停止，而 *note next: 36d1. （几乎）全速运行被调
     用函数，仅在当前函数的下一行停止。）

 -- Pdbcommand: unt(il) [lineno]

     如果不带参数，则继续运行，直到行号比当前行大时停止。

     如果带有行号，则继续运行，直到行号大于或等于该行号时停止。在这两种
     情况下，当前帧返回时也将停止。

     3.2 版更變: 允许明确给定行号。

 -- Pdbcommand: r(eturn)

     继续运行，直到当前函数返回。

 -- Pdbcommand: c(ont(inue))

     继续运行，仅在遇到断点时停止。

 -- Pdbcommand: j(ump) lineno

     设置即将运行的下一行。仅可用于堆栈最底部的帧。它可以往回跳来再次运
     行代码，也可以往前跳来跳过不想运行的代码。

     需要注意的是，不是所有的跳转都是允许的 – 例如，不能跳转到 *note
     for: cfa. 循环的中间或跳出 *note finally: 2bc. 子句。

 -- Pdbcommand: l(ist) [first[, last]]

     列出当前文件的源代码。如果不带参数，则列出当前行周围的 11 行，或继
     续前一个列表。如果用 ‘.’ 作为参数，则列出当前行周围的 11 行。如果带
     有一个参数，则列出那一行周围的 11 行。如果带有两个参数，则列出所给
     的范围中的代码；如果第二个参数小于第一个参数，则将其解释为列出行数
     的计数。

     当前帧中的当前行用 ‘->’ 标记。如果正在调试异常，且最早抛出或传递该
     异常的行不是当前行，则那一行用 ‘>>’ 标记。

     3.2 版新加入: ‘>>’ 标记。

 -- Pdbcommand: ll | longlist

     列出当前函数或帧的所有源代码。相关行的标记与 *note list: 36db. 相同
     。

     3.2 版新加入.

 -- Pdbcommand: a(rgs)

     打印当前函数的参数列表。

 -- Pdbcommand: p expression

     在当前上下文中运行 `expression' 并打印它的值。

          備註: ‘print()’ 也可以使用，但它不是一个调试器命令 — 它执行
          Python *note print(): 971. 函数。

 -- Pdbcommand: pp expression

     与 *note p: 972. 命令类似，但表达式的值使用 *note pprint: d2. 模块
     美观地打印。

 -- Pdbcommand: whatis expression

     打印 `expression' 的类型。

 -- Pdbcommand: source expression

     尝试获取给定对象的源代码并显示出来。

     3.2 版新加入.

 -- Pdbcommand: display [expression]

     如果表达式的值发生改变则显示它的值，每次将停止执行当前帧。

     不带表达式则列出当前帧的所有显示表达式。

     3.2 版新加入.

 -- Pdbcommand: undisplay [expression]

     不再显示当前帧中的表达式。 不带表达式则清除当前帧的所有显示表达式。

     3.2 版新加入.

 -- Pdbcommand: interact

     启动一个交互式解释器（使用 *note code: 1a. 模块），它的全局命名空间
     将包含当前作用域中的所有（全局和局部）名称。

     3.2 版新加入.

 -- Pdbcommand: alias [name [command]]

     创建一个标识为 `name' 的别名来执行 `command'。 执行的命令 `不可' 加
     上引号。 可替换形参可通过 ‘%1’, ‘%2’ 等来标示，而 ‘%*’ 会被所有形参
     所替换。 如果没有给出命令，则会显示 `name' 的当前别名。 如果没有给
     出参数，则会列出所有别名。

     别名允许嵌套并可包含能在 pdb 提示符下合法输入的任何内容。 请注意内
     部 pdb 命令 `可以' 被别名所覆盖。 这样的命令将被隐藏直到别名被移除
     。 别名会递归地应用到命令行的第一个单词；行内的其他单词不会受影响。

     作为示例，这里列出了两个有用的别名（特别适合放在 ‘.pdbrc’ 文件中）:

          # 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

 -- Pdbcommand: unalias name

     删除指定的别名。

 -- Pdbcommand: ! statement

     在当前堆栈帧的上下文中执行 (单行) `statement'。 感叹号可以被省略，
     除非语句的第一个单词与调试器命令重名。 要设置全局变量，你可以在同一
     行上为赋值命令添加前缀的 *note global: 1378. 语句，例如:

          (Pdb) global list_options; list_options = ['-l']
          (Pdb)

 -- Pdbcommand: run [args ...]
 -- Pdbcommand: restart [args ...]

     重启被调试的 Python 程序。 如果提供了参数，它会用 *note shlex: e8.
     来拆分且拆分结果将被用作新的 *note sys.argv: cc6.。 历史、中断点、
     动作和调试器选项将被保留。 *note restart: 36f9. 是 *note run: 36f8.
     的一个别名。

 -- Pdbcommand: q(uit)

     退出调试器。 被执行的程序将被中止。

 -- Pdbcommand: debug code

     进入一个对代码参数执行步进的递归调试器（该参数是在当前环境中执行的
     任意表达式或语句）。

 -- Pdbcommand: retval

     打印函数最后一次返回的返回值。

註解
....


File: python.info,  Node: Python Profilers 分析器,  Next: timeit --- 测量小代码片段的执行时间,  Prev: pdb --- Python 的调试器,  Up: 调试和分析

5.27.5 Python Profilers 分析器
------------------------------

`源代码：' Lib/profile.py(1) 和 Lib/pstats.py(2)

__________________________________________________________________

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/profile.py

   (2) https://github.com/python/cpython/tree/3.9/Lib/pstats.py


File: python.info,  Node: profile分析器简介,  Next: 实时用户手册,  Up: Python Profilers 分析器

5.27.5.1 profile分析器简介
..........................

*note cProfile: 27. 和 *note profile: d3. 提供了 Python 程序的 `确定性性
能分析' 。 `profile' 是一组统计数据，描述程序的各个部分执行的频率和时间
。这些统计数据可以通过 *note pstats: d4. 模块格式化为报表。

Python 标准库提供了同一分析接口的两种不同实现：

  1. 对于大多数用户，建议使用 *note cProfile: 27. ；这是一个 C 扩展插件
     ，因为其合理的运行开销，所以适合于分析长时间运行的程序。该插件基于
     ‘lsprof’ ，由 Brett Rosen 和 Ted Chaotter 贡献。

  2. *note profile: d3. 是一个纯 Python 模块（*note cProfile: 27. 就是模
     拟其接口的 C 语言实现），但它会显著增加配置程序的开销。如果你正在尝
     试以某种方式扩展分析器，则使用此模块可能会更容易完成任务。该模块最
     初由 Jim Roskind 设计和编写。

     備註: profiler 分析器模块被设计为给指定的程序提供执行概要文件，而不
     是用于基准测试目的（ *note timeit: 10d. 才是用于此目标的，它能获得
     合理准确的结果）。这特别适用于将 Python 代码与 C 代码进行基准测试：
     分析器为Python 代码引入开销，但不会为 C级别的函数引入开销，因此 C 代
     码似乎比任何Python 代码都更快。


File: python.info,  Node: 实时用户手册,  Next: profile 和 cProfile 模块参考,  Prev: profile分析器简介,  Up: Python Profilers 分析器

5.27.5.2 实时用户手册
.....................

本节是为 “不想阅读手册” 的用户提供的。它提供了非常简短的概述，并允许用户
快速对现有应用程序执行评测。

要分析采用单个参数的函数，可以执行以下操作：

     import cProfile
     import re
     cProfile.run('re.compile("foo|bar")')

（如果 *note cProfile: 27. 在您的系统上不可用，请使用 *note profile: d3.
。）

上述操作将运行 *note re.compile(): 54c. 并打印分析结果，如下所示：

           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)

第一行显示监听了197个调用。在这些调用中，有192个是 `原始的' ，这意味着调
用不是通过递归引发的。下一行: ‘Ordered by: standard name’ ，表示最右边列
中的文本字符串用于对输出进行排序。列标题包括：

ncalls

     调用次数

tottime

     在指定函数中消耗的总时间（不包括调用子函数的时间）

percall

     是 ‘tottime’ 除以 ‘ncalls’ 的商

cumtime

     指定的函数及其所有子函数（从调用到退出）消耗的累积时间。这个数字对
     于递归函数来说是准确的。

percall

     是 ‘cumtime’ 除以原始调用（次数）的商（即：函数运行一次的平均时间）

filename:lineno(function)

     提供相应数据的每个函数

如果第一列中有两个数字（例如3/1），则表示函数递归。第二个值是原始调用次
数，第一个是调用的总次数。请注意，当函数不递归时，这两个值是相同的，并且
只打印单个数字。

profile 运行结束时，打印输出不是必须的。也可以通过为 ‘run()’ 函数指定文
件名，将结果保存到文件中：

     import cProfile
     import re
     cProfile.run('re.compile("foo|bar")', 'restats')

*note pstats.Stats: 3703. 类从文件中读取 profile 结果，并以各种方式对其
进行格式化。

*note cProfile: 27. 和 *note profile: d3. 文件也可以作为脚本调用，以分析
另一个脚本。例如：

     python -m cProfile [-o output_file] [-s sort_order] (-m module | myscript.py)

‘-o’ 将profile 结果写入文件而不是标准输出

‘-s’ 指定 *note sort_stats(): 3704. 排序值之一以对输出进行排序。这仅适用
于未提供 ‘-o’ 的情况

‘-m’ 指定要分析的是模块而不是脚本。

     3.7 版新加入: *note cProfile: 27. 添加 ‘-m’ 选项

     3.8 版新加入: *note profile: d3. 添加 ‘-m’ 选项

The *note pstats: d4. module’s *note Stats: 3703. class has a variety of
methods for manipulating and printing the data saved into a profile
results file:

     import pstats
     from pstats import SortKey
     p = pstats.Stats('restats')
     p.strip_dirs().sort_stats(-1).print_stats()

The *note strip_dirs(): 3705. method removed the extraneous path from
all the module names.  The *note sort_stats(): 3704. method sorted all
the entries according to the standard module/line/name string that is
printed.  The *note print_stats(): 3706. method printed out all the
statistics.  You might try the following sort calls:

     p.sort_stats(SortKey.NAME)
     p.print_stats()

The first call will actually sort the list by function name, and the
second call will print out the statistics.  The following are some
interesting calls to experiment with:

     p.sort_stats(SortKey.CUMULATIVE).print_stats(10)

This sorts the profile by cumulative time in a function, and then only
prints the ten most significant lines.  If you want to understand what
algorithms are taking time, the above line is what you would use.

If you were looking to see what functions were looping a lot, and taking
a lot of time, you would do:

     p.sort_stats(SortKey.TIME).print_stats(10)

to sort according to time spent within each function, and then print the
statistics for the top ten functions.

你也可以尝试：

     p.sort_stats(SortKey.FILENAME).print_stats('__init__')

This will sort all the statistics by file name, and then print out
statistics for only the class init methods (since they are spelled with
‘__init__’ in them).  As one final example, you could try:

     p.sort_stats(SortKey.TIME, SortKey.CUMULATIVE).print_stats(.5, 'init')

This line sorts statistics with a primary key of time, and a secondary
key of cumulative time, and then prints out some of the statistics.  To
be specific, the list is first culled down to 50% (re: ‘.5’) of its
original size, then only lines containing ‘init’ are maintained, and
that sub-sub-list is printed.

If you wondered what functions called the above functions, you could now
(‘p’ is still sorted according to the last criteria) do:

     p.print_callers(.5, 'init')

and you would get a list of callers for each of the listed functions.

If you want more functionality, you’re going to have to read the manual,
or guess what the following functions do:

     p.print_callees()
     p.add('restats')

Invoked as a script, the *note pstats: d4. module is a statistics
browser for reading and examining profile dumps.  It has a simple
line-oriented interface (implemented using *note cmd: 19.) and
interactive help.


File: python.info,  Node: profile 和 cProfile 模块参考,  Next: Stats 类,  Prev: 实时用户手册,  Up: Python Profilers 分析器

5.27.5.3 ‘profile’ 和 ‘cProfile’ 模块参考
.........................................

*note profile: d3. 和 *note cProfile: 27. 模块都提供下列函数：

 -- 函式: profile.run (command, filename=None, sort=-1)

     This function takes a single argument that can be passed to the
     *note exec(): d0c. function, and an optional file name.  In all
     cases this routine executes:

          exec(command, __main__.__dict__, __main__.__dict__)

     and gathers profiling statistics from the execution.  If no file
     name is present, then this function automatically creates a *note
     Stats: 3703. instance and prints a simple profiling report.  If the
     sort value is specified, it is passed to this *note Stats: 3703.
     instance to control how the results are sorted.

 -- 函式: profile.runctx (command, globals, locals, filename=None,
          sort=-1)

     This function is similar to *note run(): 3708, with added arguments
     to supply the globals and locals dictionaries for the `command'
     string.  This routine executes:

          exec(command, globals, locals)

     and gathers profiling statistics as in the *note run(): 3708.
     function above.

 -- 類別: profile.Profile (timer=None, timeunit=0.0, subcalls=True,
          builtins=True)

     This class is normally only used if more precise control over
     profiling is needed than what the ‘cProfile.run()’ function
     provides.

     A custom timer can be supplied for measuring how long code takes to
     run via the `timer' argument.  This must be a function that returns
     a single number representing the current time.  If the number is an
     integer, the `timeunit' specifies a multiplier that specifies the
     duration of each unit of time.  For example, if the timer returns
     times measured in thousands of seconds, the time unit would be
     ‘.001’.

     Directly using the *note Profile: 2ec. class allows formatting
     profile results without writing the profile data to a file:

          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())

     The *note Profile: 2ec. class can also be used as a context manager
     (supported only in *note cProfile: 27. module.  see *note
     上下文管理器类型: 15c6.):

          import cProfile

          with cProfile.Profile() as pr:
              # ... do something ...

          pr.print_stats()

     3.8 版更變: 添加了上下文管理器支持。

      -- 成員函式: enable ()

          开始收集分析数据。仅在 *note cProfile: 27. 可用。

      -- 成員函式: disable ()

          停止收集分析数据。仅在 *note cProfile: 27. 可用。

      -- 成員函式: create_stats ()

          停止收集分析数据，并在内部将结果记录为当前 profile。

      -- 成員函式: print_stats (sort=-1)

          Create a *note Stats: 3703. object based on the current
          profile and print the results to stdout.

      -- 成員函式: dump_stats (filename)

          将当前profile 的结果写入 `filename' 。

      -- 成員函式: run (cmd)

          Profile the cmd via *note exec(): d0c.

      -- 成員函式: runctx (cmd, globals, locals)

          Profile the cmd via *note exec(): d0c. with the specified
          global and local environment.

      -- 成員函式: runcall (func, /, *args, **kwargs)

          Profile ‘func(*args, **kwargs)’

Note that profiling will only work if the called command/function
actually returns.  If the interpreter is terminated (e.g.  via a *note
sys.exit(): daa. call during the called command/function execution) no
profiling results will be printed.


File: python.info,  Node: Stats 类,  Next: 什么是确定性性能分析？,  Prev: profile 和 cProfile 模块参考,  Up: Python Profilers 分析器

5.27.5.4 ‘Stats’ 类
...................

Analysis of the profiler data is done using the *note Stats: 3703.
class.

 -- 類別: pstats.Stats (*filenames or profile, stream=sys.stdout)

     This class constructor creates an instance of a "statistics object"
     from a `filename' (or list of filenames) or from a ‘Profile’
     instance.  Output will be printed to the stream specified by
     `stream'.

     The file selected by the above constructor must have been created
     by the corresponding version of *note profile: d3. or *note
     cProfile: 27.  To be specific, there is `no' file compatibility
     guaranteed with future versions of this profiler, and there is no
     compatibility with files produced by other profilers, or the same
     profiler run on a different operating system.  If several files are
     provided, all the statistics for identical functions will be
     coalesced, so that an overall view of several processes can be
     considered in a single report.  If additional files need to be
     combined with data in an existing *note Stats: 3703. object, the
     *note add(): 3713. method can be used.

     Instead of reading the profile data from a file, a
     ‘cProfile.Profile’ or *note profile.Profile: 2ec. object can be
     used as the profile data source.

     *note Stats: 3703. 对象有以下方法:

      -- 成員函式: strip_dirs ()

          This method for the *note Stats: 3703. class removes all
          leading path information from file names.  It is very useful
          in reducing the size of the printout to fit within (close to)
          80 columns.  This method modifies the object, and the stripped
          information is lost.  After performing a strip operation, the
          object is considered to have its entries in a "random" order,
          as it was just after object initialization and loading.  If
          *note strip_dirs(): 3705. causes two function names to be
          indistinguishable (they are on the same line of the same
          filename, and have the same function name), then the
          statistics for these two entries are accumulated into a single
          entry.

      -- 成員函式: add (*filenames)

          This method of the *note Stats: 3703. class accumulates
          additional profiling information into the current profiling
          object.  Its arguments should refer to filenames created by
          the corresponding version of *note profile.run(): 3708. or
          ‘cProfile.run()’.  Statistics for identically named (re: file,
          line, name) functions are automatically accumulated into
          single function statistics.

      -- 成員函式: dump_stats (filename)

          Save the data loaded into the *note Stats: 3703. object to a
          file named `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 *note
          profile.Profile: 2ec. and ‘cProfile.Profile’ classes.

      -- 成員函式: sort_stats (*keys)

          This method modifies the *note Stats: 3703. 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: ‘'time'’, ‘'name'’, ‘SortKey.TIME’ or
          ‘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, ‘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:

          有效字符串参数         有效枚举参数              含义
                                                           
          ----------------------------------------------------------------------------
                                                           
          ‘'calls'’              SortKey.CALLS             调用次数
                                                           
                                                           
          ‘'cumulative'’         SortKey.CUMULATIVE        累积时间
                                                           
                                                           
          ‘'cumtime'’            N/A                       累积时间
                                                           
                                                           
          ‘'file'’               N/A                       文件名
                                                           
                                                           
          ‘'filename'’           SortKey.FILENAME          文件名
                                                           
                                                           
          ‘'module'’             N/A                       文件名
                                                           
                                                           
          ‘'ncalls'’             N/A                       调用次数
                                                           
                                                           
          ‘'pcalls'’             SortKey.PCALLS            原始调用计数
                                                           
                                                           
          ‘'line'’               SortKey.LINE              行号
                                                           
                                                           
          ‘'name'’               SortKey.NAME              函数名称
                                                           
                                                           
          ‘'nfl'’                SortKey.NFL               名称/文件/行
                                                           
                                                           
          ‘'stdname'’            SortKey.STDNAME           标准名称
                                                           
                                                           
          ‘'time'’               SortKey.TIME              内部时间
                                                           
                                                           
          ‘'tottime'’            N/A                       内部时间
                                                           

          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 ‘SortKey.NFL’
          and ‘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, ‘SortKey.NFL’ does a
          numeric compare of the line numbers.  In fact,
          ‘sort_stats(SortKey.NFL)’ is the same as
          ‘sort_stats(SortKey.NAME, SortKey.FILENAME, SortKey.LINE)’.

          For backward-compatibility reasons, the numeric arguments
          ‘-1’, ‘0’, ‘1’, and ‘2’ are permitted.  They are interpreted
          as ‘'stdname'’, ‘'calls'’, ‘'time'’, and ‘'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.

          3.7 版新加入: Added the SortKey enum.

      -- 成員函式: reverse_order ()

          This method for the *note Stats: 3703. 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.

      -- 成員函式: print_stats (*restrictions)

          This method for the *note Stats: 3703. class prints out a
          report as described in the *note profile.run(): 3708.
          definition.

          The order of the printing is based on the last *note
          sort_stats(): 3704. operation done on the object (subject to
          caveats in *note add(): 3713. and *note strip_dirs(): 3705.).

          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:

               print_stats(.1, 'foo:')

          would first limit the printing to first 10% of list, and then
          only print functions that were part of filename ‘.*foo:’.  In
          contrast, the command:

               print_stats('foo:', .1)

          would limit the list to all functions having file names
          ‘.*foo:’, and then proceed to only print the first 10% of
          them.

      -- 成員函式: print_callers (*restrictions)

          This method for the *note Stats: 3703. class prints a list of
          all functions that called each function in the profiled
          database.  The ordering is identical to that provided by *note
          print_stats(): 3706, 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:

             * With *note profile: d3, 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.

             * With *note cProfile: 27, 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.

      -- 成員函式: print_callees (*restrictions)

          This method for the *note Stats: 3703. 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 *note print_callers(): 3716. method.

      -- 成員函式: 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.


File: python.info,  Node: 什么是确定性性能分析？,  Next: 局限性,  Prev: Stats 类,  Up: Python Profilers 分析器

5.27.5.5 什么是确定性性能分析？
...............................

`确定性性能分析' 旨在反映这样一个事实：即所有 `函数调用' 、 `函数返回' 和
`异常' 事件都被监控，并且对这些事件之间的间隔（在此期间用户的代码正在执
行）进行精确计时。相反，统计分析（不是由该模块完成）随机采样有效指令指针
，并推断时间花费在哪里。后一种技术传统上涉及较少的开销（因为代码不需要检
测），但只提供了时间花在哪里的相对指示。

在Python中，由于在执行过程中总有一个活动的解释器，因此执行确定性评测不需
要插入指令的代码。Python 自动为每个事件提供一个:dfn:‘钩子’ （可选回调）
。此外，Python 的解释特性往往会给执行增加太多开销，以至于在典型的应用程
序中，确定性分析往往只会增加很小的处理开销。结果是，确定性分析并没有那么
代价高昂，但是它提供了有关 Python 程序执行的大量运行时统计信息。

调用计数统计信息可用于识别代码中的错误（意外计数），并识别可能的内联扩展
点（高频调用）。内部时间统计可用于识别应仔细优化的 "热循环" 。累积时间统
计可用于识别算法选择上的高级别错误。请注意，该分析器中对累积时间的异常处
理，允许直接比较算法的递归实现与迭代实现的统计信息。


File: python.info,  Node: 局限性,  Next: 准确估量,  Prev: 什么是确定性性能分析？,  Up: Python Profilers 分析器

5.27.5.6 局限性
...............

一个限制是关于时间信息的准确性。确定性性能分析存在一个涉及精度的基本问题
。最明显的限制是，底层的 "时钟" 周期大约为0.001秒（通常）。因此，没有什
么测量会比底层时钟更精确。如果进行了足够的测量，那么 "误差" 将趋于平均。
不幸的是，删除第一个错误会导致第二个错误来源。

第二个问题是，从调度事件到分析器调用获取时间函数实际 `获取' 时钟状态，这
需要 "一段时间" 。类似地，从获取时钟值（然后保存）开始，直到再次执行用户
代码为止，退出分析器事件句柄时也存在一定的延迟。因此，多次调用单个函数或
调用多个函数通常会累积此错误。尽管这种方式的误差通常小于时钟的精度（小于
一个时钟周期），但它 `可以' 累积并变得非常可观。

与开销较低的 *note cProfile: 27. 相比， *note profile: d3. 的问题更为严
重。出于这个原因， *note profile: d3. 提供了一种针对指定平台的自我校准方
法，以便可以在很大程度上（平均地）消除此误差。 校准后，结果将更准确（在
最小二乘意义上），但它有时会产生负数（当调用计数异常低，且概率之神对您不
利时：-）。因此 `不要' 对产生的负数感到惊慌。它们应该只在你手工校准分析
器的情况下才会出现，实际上结果比没有校准的情况要好。


File: python.info,  Node: 准确估量,  Next: 使用自定义计时器,  Prev: 局限性,  Up: Python Profilers 分析器

5.27.5.7 准确估量
.................

*note profile: d3. 模块的 profiler 会从每个事件处理时间中减去一个常量，
以补偿调用 time 函数和存储结果的开销。默认情况下，常数为0。对于特定的平
台，可用以下程序获得更好修正常数（ *note 局限性: 371c. ）。

     import profile
     pr = profile.Profile()
     for i in range(5):
         print(pr.calibrate(10000))

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 `very' fast, or your timer function has poor
resolution, you might have to pass 100000, or even 1000000, to get
consistent results.

当你有一个一致的答案时，有三种方法可以使用：

     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)

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.


File: python.info,  Node: 使用自定义计时器,  Prev: 准确估量,  Up: Python Profilers 分析器

5.27.5.8 使用自定义计时器
.........................

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 ‘Profile’ class constructor:

     pr = profile.Profile(your_time_func)

The resulting profiler will then call ‘your_time_func’.  Depending on
whether you are using *note profile.Profile: 2ec. or ‘cProfile.Profile’,
‘your_time_func’’s return value will be interpreted differently:

*note profile.Profile: 2ec.

     ‘your_time_func’ should return a single number, or a list of
     numbers whose sum is the current time (like what *note os.times():
     b37. 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 *note 准确估量: 371e.).  For
     most machines, a timer that returns a lone integer value will
     provide the best results in terms of low overhead during profiling.
     (*note os.times(): b37. is `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.

‘cProfile.Profile’

     ‘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 ‘your_integer_time_func’ returns times measured in
     thousands of seconds, you would construct the ‘Profile’ instance as
     follows:

          pr = cProfile.Profile(your_integer_time_func, 0.001)

     As the ‘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 ‘_lsprof’
     module.

Python 3.3 adds several new functions in *note time: 10c. that can be
used to make precise measurements of process or wall-clock time.  For
example, see *note time.perf_counter(): 3cc.


File: python.info,  Node: timeit --- 测量小代码片段的执行时间,  Next: trace --- 跟踪Python语句执行,  Prev: Python Profilers 分析器,  Up: 调试和分析

5.27.6 ‘timeit’ — 测量小代码片段的执行时间
------------------------------------------

`源码：' Lib/timeit.py(1)

__________________________________________________________________

此模块提供了一种简单的方法来计算一小段 Python 代码的耗时。 它有 *note
命令執行列介面: 3723. 以及一个 *note 可调用: 3724. 方法。 它避免了许多测
量时间的常见陷阱。 另见 Tim Peter 在 O’Reilly 出版的 `Python Cookbook' 第
二版中“算法”章节的概述。

* Menu:

* 基礎範例: 基礎範例<2>.
* Python 接口::
* 命令執行列介面::
* 示例: 示例<40>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/timeit.py


File: python.info,  Node: 基礎範例<2>,  Next: Python 接口,  Up: timeit --- 测量小代码片段的执行时间

5.27.6.1 基礎範例
.................

以下示例显示了如何使用 *note 命令執行列介面: 3723. 来比较三个不同的表达
式：

     $ 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

这可以通过 *note Python 接口: 3724. 实现

     >>> 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

从 *note Python 接口: 3724. 还可以传出一个可调用对象:

     >>> timeit.timeit(lambda: "-".join(map(str, range(100))), number=10000)
     0.19665591977536678

但请注意 *note timeit(): 860. 仅在使用命令行界面时会自动确定重复次数。 在
*note 示例: 3726. 一节你可以找到更多的进阶示例。


File: python.info,  Node: Python 接口,  Next: 命令執行列介面,  Prev: 基礎範例<2>,  Up: timeit --- 测量小代码片段的执行时间

5.27.6.2 Python 接口
....................

该模块定义了三个便利函数和一个公共类：

 -- 函式: timeit.timeit (stmt='pass', setup='pass', timer=<default
          timer>, number=1000000, globals=None)

     使用给定语句、 `setup' 代码和 `timer' 函数创建一个 *note Timer:
     3728. 实例，并执行 `number' 次其 *note timeit(): 693. 方法。可选的
     `globals' 参数指定用于执行代码的命名空间。

     3.5 版更變: 添加可选参数 `globals' 。

 -- 函式: timeit.repeat (stmt='pass', setup='pass', timer=<default
          timer>, repeat=5, number=1000000, globals=None)

     使用给定语句、 `setup' 代码和 `timer' 函数创建一个 *note Timer:
     3728. 实例，并使用给定的 `repeat' 计数和 `number' 执行运行其 *note
     repeat(): 372a. 方法。可选的 `globals' 参数指定用于执行代码的命名空
     间。

     3.5 版更變: 添加可选参数 `globals' 。

     3.7 版更變: `repeat' 的默认值由 3 更改为 5 。

 -- 函式: timeit.default_timer ()

     默认的计时器，总是 *note time.perf_counter(): 3cc. 。

     3.3 版更變: *note time.perf_counter(): 3cc. 现在是默认计时器。

 -- 類別: timeit.Timer (stmt='pass', setup='pass', timer=<timer
          function>, globals=None)

     用于小代码片段的计数执行速度的类。

     构造函数接受一个将计时的语句、一个用于设置的附加语句和一个定时器函
     数。两个语句都默认为 ‘'pass'’ ；计时器函数与平台有关（请参阅模块文
     档字符串）。 `stmt' 和 `setup' 也可能包含多个以 ‘;’ 或换行符分隔的
     语句，只要它们不包含多行字符串文字即可。该语句默认在 timeit 的命名
     空间内执行；可以通过将命名空间传递给 `globals' 来控制此行为。

     要测量第一个语句的执行时间，请使用 *note timeit(): 693. 方法。
     *note repeat(): 372a. 和 *note autorange(): 692. 方法是方便的方法来
     调用 *note timeit(): 693. 多次。

     `setup' 的执行时间从总体计时执行中排除。

     `stmt' 和 `setup' 参数也可以使用不带参数的可调用对象。这将在一个计
     时器函数中嵌入对它们的调用，然后由 *note timeit(): 693. 执行。请注
     意，由于额外的函数调用，在这种情况下，计时开销会略大一些。

     3.5 版更變: 添加可选参数 `globals' 。

      -- 成員函式: timeit (number=1000000)

          执行 `number' 次主要语句。这将执行一次 setup 语句，然后返回执
          行主语句多次所需的时间，以秒为单位测量为浮点数。参数是通过循环
          的次数，默认为一百万。要使用的主语句、 setup 语句和 timer 函数
          将传递给构造函数。

               備註: 默认情况下， *note timeit(): 693. 暂时关闭 *note
               garbage collection: fc8. 。这种方法的优点在于它使独立时序
               更具可比性。缺点是GC可能是所测量功能性能的重要组成部分。
               如果是这样，可以在 `setup' 字符串中的第一个语句重新启用
               GC。例如:

                    timeit.Timer('for i in range(10): oct(i)', 'gc.enable()').timeit()

      -- 成員函式: autorange (callback=None)

          自动决定调用多少次 *note timeit(): 693. 。

          这是一个便利函数，它反复调用 *note timeit(): 693. ，以便总时间
          >= 0.2 秒，返回最终（循环次数，循环所用的时间）。它调用 *note
          timeit(): 693. 的次数以序列 1, 2, 5, 10, 20, 50, ... 递增，直
          到所用的时间至少为0.2秒。

          如果给出 `callback' 并且不是 ‘None’ ，则在每次试验后将使用两个
          参数调用它： ‘callback(number, time_taken)’ 。

          3.6 版新加入.

      -- 成員函式: repeat (repeat=5, number=1000000)

          调用 *note timeit(): 693. 几次。

          这是一个方便的函数，它反复调用 *note timeit(): 693. ，返回结果
          列表。第一个参数指定调用 *note timeit(): 693. 的次数。第二个参
          数指定 *note timeit(): 693. 的 `number' 参数。

               備註: 从结果向量计算并报告平均值和标准差这些是很诱人的。
               但是，这不是很有用。在典型情况下，最低值给出了机器运行给
               定代码段的速度的下限；结果向量中较高的值通常不是由
               Python的速度变化引起的，而是由于其他过程干扰你的计时准确
               性。所以结果的 *note min(): 8f6. 可能是你应该感兴趣的唯一
               数字。之后，你应该看看整个向量并应用常识而不是统计。

          3.7 版更變: `repeat' 的默认值由 3 更改为 5 。

      -- 成員函式: print_exc (file=None)

          帮助程序从计时代码中打印回溯。

          典型使用:

               t = Timer(...)       # outside the try/except
               try:
                   t.timeit(...)    # or t.repeat(...)
               except Exception:
                   t.print_exc()

          与标准回溯相比，优势在于将显示已编译模板中的源行。可选的
          `file' 参数指向发送回溯的位置；它默认为 *note sys.stderr: 1ea.
          。


File: python.info,  Node: 命令執行列介面,  Next: 示例<40>,  Prev: Python 接口,  Up: timeit --- 测量小代码片段的执行时间

5.27.6.3 命令執行列介面
.......................

从命令行调用程序时，使用以下表单:

     python -m timeit [-n N] [-r N] [-u U] [-s S] [-h] [statement ...]

如果了解以下选项：

 -- 程式選項: -n N, --number=N

     执行 ’语句’ 多少次

 -- 程式選項: -r N, --repeat=N

     重复计时器的次数（默认为5）

 -- 程式選項: -s S, --setup=S

     最初要执行一次的语句（默认为 ‘pass’ ）

 -- 程式選項: -p, --process

     测量进程时间，而不是 wallclock 时间，使用 *note
     time.process_time(): 3cd. 而不是 *note time.perf_counter(): 3cc. ，
     这是默认值

     3.3 版新加入.

 -- 程式選項: -u, --unit=U

     指定定时器输出的时间单位；可以选择 nsec，usec，msec或sec

     3.5 版新加入.

 -- 程式選項: -v, --verbose

     打印原始计时结果；重复更多位数精度

 -- 程式選項: -h, --help

     打印一条简短的使用信息并退出

可以通过将每一行指定为单独的语句参数来给出多行语句；通过在引号中包含参数
并使用前导空格可以缩进行。多个 *note -s: 3730. 选项的处理方式相似。

如果未给出 *note -n: 372e.，则会通过尝试按序列 1, 2, 5, 10, 20, 50, ...
递增的数值来计算合适的循环次数，直到总计时间至少为 0.2 秒。

*note default_timer(): 372b. 测量可能受到在同一台机器上运行的其他程序的
影响，因此在需要精确计时时最好的做法是重复几次计时并使用最佳时间。 *note
-r: 372f. 选项对此有利；在大多数情况下，默认的 5 次重复可能就足够了。 你
可以使用 *note time.process_time(): 3cd. 来测量CPU时间。

     備註: 执行 pass 语句会产生一定的基线开销。这里的代码不会试图隐藏它
     ，但你应该知道它。可以通过不带参数调用程序来测量基线开销，并且
     Python版本之间可能会有所不同。


File: python.info,  Node: 示例<40>,  Prev: 命令執行列介面,  Up: timeit --- 测量小代码片段的执行时间

5.27.6.4 示例
.............

可以提供一个在开头只执行一次的 setup 语句：

     $ 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

     >>> 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

使用 *note Timer: 3728. 类及其方法可以完成同样的操作:

     >>> 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]

以下示例显示如何计算包含多行的表达式。 在这里我们对比使用 *note
hasattr(): 54a. 与 *note try: e37./*note except: c10. 的开销来测试缺失与
提供对象属性:

     $ 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

     >>> 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

要让 *note timeit: 10d. 模块访问你定义的函数，你可以传递一个包含 import
语句的 `setup' 参数:

     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"))

另一种选择是将 *note globals(): f55. 传递给 `globals' 参数，这将导致代码
在当前的全局命名空间中执行。这比单独指定 import 更方便

     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()))


File: python.info,  Node: trace --- 跟踪Python语句执行,  Next: tracemalloc --- 跟踪内存分配,  Prev: timeit --- 测量小代码片段的执行时间,  Up: 调试和分析

5.27.7 ‘trace’ — 跟踪Python语句执行
-----------------------------------

`源代码:' Lib/trace.py(1)

__________________________________________________________________

模块 *note trace: 11b. module 允许你跟踪程序的执行过程，生成带注释的语句
覆盖率列表，打印调用/被调用关系以及列出在程序运行期间执行过的函数。可以
在其他程序或者命令行中使用它

也參考
......

Coverage.py(2)

     流行的第三方代码覆盖工具，可输出 HTML ，并提供分支覆盖等高级功能。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/trace.py

   (2) https://coverage.readthedocs.io/


File: python.info,  Node: 命令行用法,  Next: 编程接口,  Up: trace --- 跟踪Python语句执行

5.27.7.1 命令行用法
...................

*note trace: 11b. 模块可由命令行调用。用法如此简单：

     python -m trace --count -C . somefile.py ...

上述命令将执行 ‘somefile.py’ ，并在当前目录生成执行期间所有已导入 Python
模块的带注释列表。

 -- 程式選項: --help

     显示用法并退出。

 -- 程式選項: --version

     显示模块版本并退出。

3.8 版新加入: 加入了 ‘--module’ 选项，允许运行可执行模块。

* Menu:

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


File: python.info,  Node: 主要的可选参数,  Next: 修饰器,  Up: 命令行用法

5.27.7.2 主要的可选参数
.......................

在调用 *note trace: 11b. 时，至少须指定以下可选参数之一。 *note
-listfuncs: 373d. 与 *note -trace: 373e. 、 *note -count: 373f. 相互排斥
。如果给出 *note –listfuncs: 373d.，就再不会接受 *note –count: 373f. 和
*note –trace: 373e. ，反之亦然。

 -- 程式選項: -c, --count

     在程序完成时生成一组带有注解的列表文件，显示每个语句被执行的次数。
     参见下面的 *note -coverdir: 3740. 、*note -file: 3741. 和 *note
     -no-report: 3742.。

 -- 程式選項: -t, --trace

     执行时显示行。

 -- 程式選項: -l, --listfuncs

     显示程序运行时执行到的函数。

 -- 程式選項: -r, --report

     由之前用了 *note –count: 373f. 和 *note –file: 3741. 运行的程序产生
     一个带有注解的报表。 不会执行代码。

 -- 程式選項: -T, --trackcalls

     显示程序运行时暴露出来的调用关系。


File: python.info,  Node: 修饰器,  Next: 过滤器,  Prev: 主要的可选参数,  Up: 命令行用法

5.27.7.3 修饰器
...............

 -- 程式選項: -f, --file=<file>

     用于累计多次跟踪运行计数的文件名。应与 *note –count: 373f. 一起使用
     。

 -- 程式選項: -C, --coverdir=<dir>

     报表文件的所在目录。‘package.module’ 的覆盖率报表将被写入文件
     ‘`dir'/`package'/`module'.cover’。

 -- 程式選項: -m, --missing

     生成带注解的报表时，用 ‘>>>>>>’ 标记未执行的行。

 -- 程式選項: -s, --summary

     在用到 *note –count: 373f. 或 *note –report: 3743. 时，将每个文件的
     简短摘要写到 stdout。

 -- 程式選項: -R, --no-report

     不生成带注解的报表。如果打算用 *note –count: 373f. 执行多次运行，然
     后在最后产生一组带注解的报表，该选项就很有用。

 -- 程式選項: -g, --timing

     在每一行前面加上时间，自程序运行算起。只在跟踪时有用。


File: python.info,  Node: 过滤器,  Prev: 修饰器,  Up: 命令行用法

5.27.7.4 过滤器
...............

以下参数可重复多次。

 -- 程式選項: --ignore-module=<mod>

     忽略给出的模块名及其子模块（若为包）。参数可为逗号分隔的名称列表。

 -- 程式選項: --ignore-dir=<dir>

     忽略指定目录及其子目录下的所有模块和包。参数可为 *note os.pathsep:
     1486. 分隔的目录列表。


File: python.info,  Node: 编程接口,  Prev: 命令行用法,  Up: trace --- 跟踪Python语句执行

5.27.7.5 编程接口
.................

 -- 類別: trace.Trace (count=1, trace=1, countfuncs=0, countcallers=0,
          ignoremods=(), ignoredirs=(), infile=None, outfile=None,
          timing=False)

     创建一个对象来跟踪单个语句或表达式的执行。所有参数均为选填。
     `count' 可对行号计数。 `trace' 启用单行执行跟踪。 `countfuncs' 可列
     出运行过程中调用的函数。 `countcallers' 可跟踪调用关系。
     `ignoremods' 是要忽略的模块或包的列表。`ignoredirs' 是要忽略的模块
     或包的目录列表。 `infile' 是个文件名，从该文件中读取存储的计数信息
     。 `outfile' 是用来写入最新计数信息的文件名。 `timing' 可以显示相对
     于跟踪开始时间的时间戳。

      -- 成員函式: run (cmd)

          执行命令，并根据当前跟踪参数从执行过程中收集统计数据。 `cmd' 必
          须为字符串或 code 对象，可供传入 *note exec(): d0c.。

      -- 成員函式: runctx (cmd, globals=None, locals=None)

          在定义的全局和局部环境中，执行命令并收集当前跟踪参数下的执行统
          计数据。若没有定义 `globals' 和 `locals' ，则默认为空字典。

      -- 成員函式: runfunc (func, /, *args, **kwds)

          在 *note Trace: 374e. 对象的控制下，用给定的参数调用 `func'，
          并采用当前的跟踪参数。

      -- 成員函式: results ()

          返回一个 *note CoverageResults: 3752. 对象，包含之前对指定
          *note Trace: 374e. 实例调用 ‘run’、‘runctx’ 和 ‘runfunc’ 的累
          积结果。 累积的跟踪结果不会重置。

 -- 類別: trace.CoverageResults

     用于覆盖跟踪结果的容器，由 *note Trace.results(): 3751. 创建。用户
     不应直接去创建。

      -- 成員函式: update (other)

          从另一个 *note CoverageResults: 3752. 对象中合并跟踪数据。

      -- 成員函式: write_results (show_missing=True, summary=False,
               coverdir=None)

          写入代码覆盖结果。设置 `show_missing' 可显示未命中的行。设置
          *summary* 可在输出中包含每个模块的覆盖率摘要信息。 `coverdir'
          可指定覆盖率结果文件的输出目录，为 ‘None’ 则结果将置于源文件所
          在目录中。

以下例子简单演示了编程接口的用法：

     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=".")


File: python.info,  Node: tracemalloc --- 跟踪内存分配,  Prev: trace --- 跟踪Python语句执行,  Up: 调试和分析

5.27.8 ‘tracemalloc’ — 跟踪内存分配
-----------------------------------

3.4 版新加入.

`源代码：' Lib/tracemalloc.py(1)

__________________________________________________________________

The tracemalloc module is a debug tool to trace memory blocks allocated
by Python.  It provides the following information:

   * Traceback where an object was allocated

   * Statistics on allocated memory blocks per filename and per line
     number: total size, number and average size of allocated memory
     blocks

   * Compute the differences between two snapshots to detect memory
     leaks

To trace most memory blocks allocated by Python, the module should be
started as early as possible by setting the *note PYTHONTRACEMALLOC:
148c. environment variable to ‘1’, or by using *note -X: 290.
‘tracemalloc’ command line option.  The *note tracemalloc.start(): 1481.
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 *note
PYTHONTRACEMALLOC: 148c. environment variable to ‘25’, or use the *note
-X: 290. ‘tracemalloc=25’ command line option.

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/tracemalloc.py


File: python.info,  Node: 示例<41>,  Next: API,  Up: tracemalloc --- 跟踪内存分配

5.27.8.1 示例
.............

* Menu:

* 显示前10项::
* 计算差异::
* Get the traceback of a memory block::
* Pretty top::


File: python.info,  Node: 显示前10项,  Next: 计算差异,  Up: 示例<41>

5.27.8.2 显示前10项
...................

显示内存分配最多的10个文件：

     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)

Python测试套件的输出示例：

     [ 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

We can see that Python loaded ‘4855 KiB’ data (bytecode and constants)
from modules and that the *note collections: 1d. module allocated ‘244
KiB’ to build *note namedtuple: 1a1. types.

See *note Snapshot.statistics(): 3759. for more options.


File: python.info,  Node: 计算差异,  Next: Get the traceback of a memory block,  Prev: 显示前10项,  Up: 示例<41>

5.27.8.3 计算差异
.................

获取两个快照并显示差异：

     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)

Example of output before/after running some tests of the Python test
suite:

     [ 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

We can see that Python has loaded ‘8173 KiB’ of module data (bytecode
and constants), and that this is ‘4428 KiB’ more than had been loaded
before the tests, when the previous snapshot was taken.  Similarly, the
*note linecache: a8. module has cached ‘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 *note Snapshot.dump(): 375b. method to analyze the snapshot
offline.  Then use the *note Snapshot.load(): 375c. method reload the
snapshot.


File: python.info,  Node: Get the traceback of a memory block,  Next: Pretty top,  Prev: 计算差异,  Up: 示例<41>

5.27.8.4 Get the traceback of a memory block
............................................

Code to display the traceback of the biggest memory block:

     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)

Example of output of the Python test suite (traceback limited to 25
frames):

     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)

We can see that the most memory was allocated in the *note importlib:
9a. module to load data (bytecode and constants) from modules: ‘870.1
KiB’.  The traceback is where the *note importlib: 9a. loaded data most
recently: on the ‘import pdb’ line of the *note doctest: 66. module.
The traceback may change if a new module is loaded.


File: python.info,  Node: Pretty top,  Prev: Get the traceback of a memory block,  Up: 示例<41>

5.27.8.5 Pretty top
...................

Code to display the 10 lines allocating the most memory with a pretty
output, ignoring ‘<frozen importlib._bootstrap>’ and ‘<unknown>’ files:

     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)

Python测试套件的输出示例：

     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

See *note Snapshot.statistics(): 3759. for more options.

* Menu:

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


File: python.info,  Node: Record the current and peak size of all traced memory blocks,  Up: Pretty top

5.27.8.6 Record the current and peak size of all traced memory blocks
.....................................................................

The following code computes two sums like ‘0 + 1 + 2 + ...’
inefficiently, by creating a list of those numbers.  This list consumes
a lot of memory temporarily.  We can use *note get_traced_memory():
3760. and *note reset_peak(): 1ec. to observe the small memory usage
after the sum is computed as well as the peak memory usage during the
computations:

     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=}")

输出:

     first_size=664, first_peak=3592984
     second_size=804, second_peak=29704

Using *note reset_peak(): 1ec. ensured we could accurately record the
peak during the computation of ‘small_sum’, even though it is much
smaller than the overall peak size of memory blocks since the *note
start(): 1481. call.  Without the call to *note reset_peak(): 1ec,
‘second_peak’ would still be the peak from the computation ‘large_sum’
(that is, equal to ‘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 *note list: 1f8, and writing
‘sum(range(...))’).


File: python.info,  Node: API,  Prev: 示例<41>,  Up: tracemalloc --- 跟踪内存分配

5.27.8.7 API
............

* Menu:

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


File: python.info,  Node: 函数<10>,  Next: 域过滤器,  Up: API

5.27.8.8 函数
.............

 -- 函式: tracemalloc.clear_traces ()

     Clear traces of memory blocks allocated by Python.

     See also *note stop(): 3764.

 -- 函式: tracemalloc.get_object_traceback (obj)

     Get the traceback where the Python object `obj' was allocated.
     Return a *note Traceback: 503. instance, or ‘None’ if the *note
     tracemalloc: 11d. module is not tracing memory allocations or did
     not trace the allocation of the object.

     See also *note gc.get_referrers(): fb6. and *note sys.getsizeof():
     3765. functions.

 -- 函式: tracemalloc.get_traceback_limit ()

     Get the maximum number of frames stored in the traceback of a
     trace.

     The *note tracemalloc: 11d. module must be tracing memory
     allocations to get the limit, otherwise an exception is raised.

     The limit is set by the *note start(): 1481. function.

 -- 函式: tracemalloc.get_traced_memory ()

     Get the current size and peak size of memory blocks traced by the
     *note tracemalloc: 11d. module as a tuple: ‘(current: int, peak:
     int)’.

 -- 函式: tracemalloc.reset_peak ()

     Set the peak size of memory blocks traced by the *note tracemalloc:
     11d. module to the current size.

     Do nothing if the *note tracemalloc: 11d. module is not tracing
     memory allocations.

     This function only modifies the recorded peak size, and does not
     modify or clear any traces, unlike *note clear_traces(): 3763.
     Snapshots taken with *note take_snapshot(): 3767. before a call to
     *note reset_peak(): 1ec. can be meaningfully compared to snapshots
     taken after the call.

     See also *note get_traced_memory(): 3760.

     3.9 版新加入.

 -- 函式: tracemalloc.get_tracemalloc_memory ()

     Get the memory usage in bytes of the *note tracemalloc: 11d. module
     used to store traces of memory blocks.  Return an *note int: 204.

 -- 函式: tracemalloc.is_tracing ()

     ‘True’ if the *note tracemalloc: 11d. module is tracing Python
     memory allocations, ‘False’ otherwise.

     See also *note start(): 1481. and *note stop(): 3764. functions.

 -- 函式: tracemalloc.start (nframe: int=1)

     Start tracing Python memory allocations: install hooks on Python
     memory allocators.  Collected tracebacks of traces will be limited
     to `nframe' frames.  By default, a trace of a memory block only
     stores the most recent frame: the limit is ‘1’.  `nframe' must be
     greater or equal to ‘1’.

     You can still read the original number of total frames that
     composed the traceback by looking at the *note
     Traceback.total_nframe: 376a. attribute.

     Storing more than ‘1’ frame is only useful to compute statistics
     grouped by ‘'traceback'’ or to compute cumulative statistics: see
     the *note Snapshot.compare_to(): 376b. and *note
     Snapshot.statistics(): 3759. methods.

     Storing more frames increases the memory and CPU overhead of the
     *note tracemalloc: 11d. module.  Use the *note
     get_tracemalloc_memory(): 3768. function to measure how much memory
     is used by the *note tracemalloc: 11d. module.

     The *note PYTHONTRACEMALLOC: 148c. environment variable
     (‘PYTHONTRACEMALLOC=NFRAME’) and the *note -X: 290.
     ‘tracemalloc=NFRAME’ command line option can be used to start
     tracing at startup.

     See also *note stop(): 3764, *note is_tracing(): 3769. and *note
     get_traceback_limit(): 3766. functions.

 -- 函式: 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 *note take_snapshot(): 3767. function to take a snapshot of
     traces before clearing them.

     See also *note start(): 1481, *note is_tracing(): 3769. and *note
     clear_traces(): 3763. functions.

 -- 函式: tracemalloc.take_snapshot ()

     Take a snapshot of traces of memory blocks allocated by Python.
     Return a new *note Snapshot: 376c. instance.

     The snapshot does not include memory blocks allocated before the
     *note tracemalloc: 11d. module started to trace memory allocations.

     Tracebacks of traces are limited to *note get_traceback_limit():
     3766. frames.  Use the `nframe' parameter of the *note start():
     1481. function to store more frames.

     The *note tracemalloc: 11d. module must be tracing memory
     allocations to take a snapshot, see the *note start(): 1481.
     function.

     See also the *note get_object_traceback(): 129b. function.


File: python.info,  Node: 域过滤器,  Next: 过滤器<2>,  Prev: 函数<10>,  Up: API

5.27.8.9 域过滤器
.................

 -- 類別: tracemalloc.DomainFilter (inclusive: bool, domain: int)

     Filter traces of memory blocks by their address space (domain).

     3.6 版新加入.

      -- 屬性: inclusive

          If `inclusive' is ‘True’ (include), match memory blocks
          allocated in the address space *note domain: 376f.

          If `inclusive' is ‘False’ (exclude), match memory blocks not
          allocated in the address space *note domain: 376f.

      -- 屬性: domain

          Address space of a memory block (‘int’).  Read-only property.


File: python.info,  Node: 过滤器<2>,  Next: Frame,  Prev: 域过滤器,  Up: API

5.27.8.10 过滤器
................

 -- 類別: tracemalloc.Filter (inclusive: bool, filename_pattern: str,
          lineno: int=None, all_frames: bool=False, domain: int=None)

     对内存块的跟踪进行筛选。

     See the *note fnmatch.fnmatch(): 1dd3. function for the syntax of
     `filename_pattern'.  The ‘'.pyc'’ file extension is replaced with
     ‘'.py'’.

     示例：

        * ‘Filter(True, subprocess.__file__)’ only includes traces of
          the *note subprocess: f9. module

        * ‘Filter(False, tracemalloc.__file__)’ excludes traces of the
          *note tracemalloc: 11d. module

        * ‘Filter(False, "<unknown>")’ excludes empty tracebacks

     3.5 版更變: The ‘'.pyo'’ file extension is no longer replaced with
     ‘'.py'’.

     3.6 版更變: Added the *note domain: 3772. attribute.

      -- 屬性: domain

          Address space of a memory block (‘int’ or ‘None’).

          tracemalloc uses the domain ‘0’ to trace memory allocations
          made by Python.  C extensions can use other domains to trace
          other resources.

      -- 屬性: inclusive

          If `inclusive' is ‘True’ (include), only match memory blocks
          allocated in a file with a name matching *note
          filename_pattern: 3774. at line number *note lineno: 3775.

          If `inclusive' is ‘False’ (exclude), ignore memory blocks
          allocated in a file with a name matching *note
          filename_pattern: 3774. at line number *note lineno: 3775.

      -- 屬性: lineno

          Line number (‘int’) of the filter.  If `lineno' is ‘None’, the
          filter matches any line number.

      -- 屬性: filename_pattern

          Filename pattern of the filter (‘str’).  Read-only property.

      -- 屬性: all_frames

          If `all_frames' is ‘True’, all frames of the traceback are
          checked.  If `all_frames' is ‘False’, only the most recent
          frame is checked.

          This attribute has no effect if the traceback limit is ‘1’.
          See the *note get_traceback_limit(): 3766. function and *note
          Snapshot.traceback_limit: 3777. attribute.


File: python.info,  Node: Frame,  Next: 快照,  Prev: 过滤器<2>,  Up: API

5.27.8.11 Frame
...............

 -- 類別: tracemalloc.Frame

     Frame of a traceback.

     The *note Traceback: 503. class is a sequence of *note Frame: 3779.
     instances.

      -- 屬性: filename

          文件名（‘字符串’）

      -- 屬性: lineno

          行号（‘整形’）


File: python.info,  Node: 快照,  Next: 统计,  Prev: Frame,  Up: API

5.27.8.12 快照
..............

 -- 類別: tracemalloc.Snapshot

     Snapshot of traces of memory blocks allocated by Python.

     The *note take_snapshot(): 3767. function creates a snapshot
     instance.

      -- 成員函式: 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 *note StatisticDiff: 377d. instances
          grouped by `key_type'.

          See the *note Snapshot.statistics(): 3759. method for
          `key_type' and `cumulative' parameters.

          The result is sorted from the biggest to the smallest by:
          absolute value of *note StatisticDiff.size_diff: 377e, *note
          StatisticDiff.size: 377f, absolute value of *note
          StatisticDiff.count_diff: 3780, *note Statistic.count: 3781.
          and then by *note StatisticDiff.traceback: 3782.

      -- 成員函式: dump (filename)

          将快照写入文件

          使用 *note load(): 375c. 重载快照。

      -- 成員函式: filter_traces (filters)

          Create a new *note Snapshot: 376c. instance with a filtered
          *note traces: 3784. sequence, `filters' is a list of *note
          DomainFilter: 697. and *note Filter: 3771. instances.  If
          `filters' is an empty list, return a new *note Snapshot: 376c.
          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 版更變: *note DomainFilter: 697. instances are now also
          accepted in `filters'.

      -- 成員函式: classmethod load (filename)

          从文件载入快照。

          另见 *note dump(): 375b.

      -- 成員函式: statistics (key_type: str, cumulative: bool=False)

          获取 *note Statistic: 3785. 信息列表，按 `key_type' 分组排序：

          key_type                  描述
                                    
          -------------------------------------------------------
                                    
          ‘'filename'’              文件名
                                    
                                    
          ‘'lineno'’                文件名和行号
                                    
                                    
          ‘'traceback'’             回溯
                                    

          If `cumulative' is ‘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
          `key_type' equals to ‘'filename'’ and ‘'lineno'’.

          The result is sorted from the biggest to the smallest by:
          *note Statistic.size: 3786, *note Statistic.count: 3781. and
          then by *note Statistic.traceback: 3787.

      -- 屬性: traceback_limit

          Maximum number of frames stored in the traceback of *note
          traces: 3784.: result of the *note get_traceback_limit():
          3766. when the snapshot was taken.

      -- 屬性: traces

          Traces of all memory blocks allocated by Python: sequence of
          *note Trace: 3788. instances.

          The sequence has an undefined order.  Use the *note
          Snapshot.statistics(): 3759. method to get a sorted list of
          statistics.


File: python.info,  Node: 统计,  Next: StatisticDiff,  Prev: 快照,  Up: API

5.27.8.13 统计
..............

 -- 類別: tracemalloc.Statistic

     统计内存分配

     *note Snapshot.statistics(): 3759. 返回 *note Statistic: 3785. 实例
     的列表。.

     参见 *note StatisticDiff: 377d. 类。

      -- 屬性: count

          内存块数（‘整形’）。

      -- 屬性: size

          Total size of memory blocks in bytes (‘int’).

      -- 屬性: traceback

          Traceback where the memory block was allocated, *note
          Traceback: 503. instance.


File: python.info,  Node: StatisticDiff,  Next: 跟踪,  Prev: 统计,  Up: API

5.27.8.14 StatisticDiff
.......................

 -- 類別: tracemalloc.StatisticDiff

     Statistic difference on memory allocations between an old and a new
     *note Snapshot: 376c. instance.

     *note Snapshot.compare_to(): 376b. returns a list of *note
     StatisticDiff: 377d. instances.  See also the *note Statistic:
     3785. class.

      -- 屬性: count

          Number of memory blocks in the new snapshot (‘int’): ‘0’ if
          the memory blocks have been released in the new snapshot.

      -- 屬性: count_diff

          Difference of number of memory blocks between the old and the
          new snapshots (‘int’): ‘0’ if the memory blocks have been
          allocated in the new snapshot.

      -- 屬性: size

          Total size of memory blocks in bytes in the new snapshot
          (‘int’): ‘0’ if the memory blocks have been released in the
          new snapshot.

      -- 屬性: size_diff

          Difference of total size of memory blocks in bytes between the
          old and the new snapshots (‘int’): ‘0’ if the memory blocks
          have been allocated in the new snapshot.

      -- 屬性: traceback

          Traceback where the memory blocks were allocated, *note
          Traceback: 503. instance.


File: python.info,  Node: 跟踪,  Next: 回溯,  Prev: StatisticDiff,  Up: API

5.27.8.15 跟踪
..............

 -- 類別: tracemalloc.Trace

     Trace of a memory block.

     The *note Snapshot.traces: 3784. attribute is a sequence of *note
     Trace: 3788. instances.

     3.6 版更變: Added the *note domain: 378d. attribute.

      -- 屬性: domain

          Address space of a memory block (‘int’).  Read-only property.

          tracemalloc uses the domain ‘0’ to trace memory allocations
          made by Python.  C extensions can use other domains to trace
          other resources.

      -- 屬性: size

          Size of the memory block in bytes (‘int’).

      -- 屬性: traceback

          Traceback where the memory block was allocated, *note
          Traceback: 503. instance.


File: python.info,  Node: 回溯,  Prev: 跟踪,  Up: API

5.27.8.16 回溯
..............

 -- 類別: tracemalloc.Traceback

     Sequence of *note Frame: 3779. instances sorted from the oldest
     frame to the most recent frame.

     A traceback contains at least ‘1’ frame.  If the ‘tracemalloc’
     module failed to get a frame, the filename ‘"<unknown>"’ at line
     number ‘0’ is used.

     When a snapshot is taken, tracebacks of traces are limited to *note
     get_traceback_limit(): 3766. frames.  See the *note
     take_snapshot(): 3767. function.  The original number of frames of
     the traceback is stored in the *note Traceback.total_nframe: 376a.
     attribute.  That allows to know if a traceback has been truncated
     by the traceback limit.

     The *note Trace.traceback: 378f. attribute is an instance of *note
     Traceback: 503. instance.

     3.7 版更變: Frames are now sorted from the oldest to the most
     recent, instead of most recent to oldest.

      -- 屬性: total_nframe

          Total number of frames that composed the traceback before
          truncation.  This attribute can be set to ‘None’ if the
          information is not available.

     3.9 版更變: The *note Traceback.total_nframe: 376a. attribute was
     added.

      -- 成員函式: format (limit=None, most_recent_first=False)

          Format the traceback as a list of lines.  Use the *note
          linecache: a8. module to retrieve lines from the source code.
          If `limit' is set, format the `limit' most recent frames if
          `limit' is positive.  Otherwise, format the ‘abs(limit)’
          oldest frames.  If `most_recent_first' is ‘True’, the order of
          the formatted frames is reversed, returning the most recent
          frame first instead of last.

          Similar to the *note traceback.format_tb(): 3791. function,
          except that *note format(): 504. does not include newlines.

          示例:

               print("Traceback (most recent call first):")
               for line in traceback:
                   print(line)

          输出:

               Traceback (most recent call first):
                 File "test.py", line 9
                   obj = Object()
                 File "test.py", line 12
                   tb = tracemalloc.get_object_traceback(f())


File: python.info,  Node: 軟體封裝與發布,  Next: Python运行时服务,  Prev: 调试和分析,  Up: Python 標準函式庫 Standard Library

5.28 軟體封裝與發布
===================

这些库可帮助你发布和安装 Python 软件。 虽然这些模块设计为与‘Python 包索
引 <‘https://pypi.org’>‘__结合使用，但它们也可以与本地索引服务器一起使用
，或者根本不使用任何索引服务器。

* Menu:

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


File: python.info,  Node: distutils --- 构建和安装 Python 模块,  Next: ensurepip --- Bootstrapping the pip installer,  Up: 軟體封裝與發布

5.28.1 ‘distutils’ — 构建和安装 Python 模块
-------------------------------------------

__________________________________________________________________

*note distutils: 38. 包为将待构建和安装的额外的模块，打包成 Python 安装
包提供支持。新模块既可以是百分百的纯 Python，也可以是用 C 写的扩展模块，
或者可以是一组包含了同时用 Python 和 C 编码的 Python 包。

大多数 Python 用户 `不会' 想要直接使用这个包，而是使用 Python 包官方维护
的跨版本工具。特别地， setuptools(1) 是一个对于 *note distutils: 38. 的
增强选项，它能提供：

   * 对声明项目依赖的支持

   * 额外的用于配置哪些文件包含在源代码发布中的机制（包括与版本控制系统
     集成需要的插件）

   * 生成项目“进入点”的能力，进入点可用作应用插件系统的基础

   * 自动在安装时间生成 Windows 命令行可执行文件的能力，而不是需要预编译
     它们

   * 跨所有受支持的 Python 版本上的一致的表现

推荐的 pip(2) 安装器用 ‘setuptools’ 运行所有的 ‘setup.py’ 脚本，即使脚本
本身只引了 ‘distutils’ 包。参考 Python Packaging User Guide(3)  获得更多
信息。

为了打包工具的作者和用户能更好理解当前的打包和分发系统，遗留的基于 *note
distutils: 38. 的用户文档和 API 参考保持可用：

   * *note 安裝 Python 模組（舊版）: 8e4.

   * *note 發布 Python 模組（舊版）: 8e5.

   ---------- Footnotes ----------

   (1) https://setuptools.readthedocs.io/en/latest/

   (2) https://pip.pypa.io/

   (3) https://packaging.python.org


File: python.info,  Node: ensurepip --- Bootstrapping the pip installer,  Next: venv --- 创建虚拟环境,  Prev: distutils --- 构建和安装 Python 模块,  Up: 軟體封裝與發布

5.28.2 ‘ensurepip’ — Bootstrapping the ‘pip’ installer
------------------------------------------------------

3.4 版新加入.

__________________________________________________________________

The *note ensurepip: 78. package provides support for bootstrapping the
‘pip’ installer into an existing Python installation or virtual
environment.  This bootstrapping approach reflects the fact that ‘pip’
is an independent project with its own release cycle, and the latest
available stable version is bundled with maintenance and feature
releases of the CPython reference interpreter.

In most cases, end users of Python shouldn’t need to invoke this module
directly (as ‘pip’ should be bootstrapped by default), but it may be
needed if installing ‘pip’ was skipped when installing Python (or when
creating a virtual environment) or after explicitly uninstalling ‘pip’.

     備註: This module `does not' access the internet.  All of the
     components needed to bootstrap ‘pip’ are included as internal parts
     of the package.

也參考
......

*note 安裝 Python 模組: 8e2.

     The end user guide for installing Python packages

PEP 453(1): Explicit bootstrapping of pip in Python installations

     The original rationale and specification for this module.

* Menu:

* Command line interface::
* Module API::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0453


File: python.info,  Node: Command line interface,  Next: Module API,  Up: ensurepip --- Bootstrapping the pip installer

5.28.2.1 Command line interface
...............................

The command line interface is invoked using the interpreter’s ‘-m’
switch.

The simplest possible invocation is:

     python -m ensurepip

This invocation will install ‘pip’ if it is not already installed, but
otherwise does nothing.  To ensure the installed version of ‘pip’ is at
least as recent as the one bundled with ‘ensurepip’, pass the
‘--upgrade’ option:

     python -m ensurepip --upgrade

By default, ‘pip’ is installed into the current virtual environment (if
one is active) or into the system site packages (if there is no active
virtual environment).  The installation location can be controlled
through two additional command line options:

   * ‘--root <dir>’: Installs ‘pip’ relative to the given root directory
     rather than the root of the currently active virtual environment
     (if any) or the default root for the current Python installation.

   * ‘--user’: Installs ‘pip’ into the user site packages directory
     rather than globally for the current Python installation (this
     option is not permitted inside an active virtual environment).

By default, the scripts ‘pipX’ and ‘pipX.Y’ will be installed (where X.Y
stands for the version of Python used to invoke ‘ensurepip’).  The
scripts installed can be controlled through two additional command line
options:

   * ‘--altinstall’: if an alternate installation is requested, the
     ‘pipX’ script will `not' be installed.

   * ‘--default-pip’: if a "default pip" installation is requested, the
     ‘pip’ script will be installed in addition to the two regular
     scripts.

Providing both of the script selection options will trigger an
exception.


File: python.info,  Node: Module API,  Prev: Command line interface,  Up: ensurepip --- Bootstrapping the pip installer

5.28.2.2 Module API
...................

*note ensurepip: 78. exposes two functions for programmatic use:

 -- 函式: ensurepip.version ()

     Returns a string specifying the bundled version of pip that will be
     installed when bootstrapping an environment.

 -- 函式: ensurepip.bootstrap (root=None, upgrade=False, user=False,
          altinstall=False, default_pip=False, verbosity=0)

     Bootstraps ‘pip’ into the current or designated environment.

     `root' specifies an alternative root directory to install relative
     to.  If `root' is ‘None’, then installation uses the default
     install location for the current environment.

     `upgrade' indicates whether or not to upgrade an existing
     installation of an earlier version of ‘pip’ to the bundled version.

     `user' indicates whether to use the user scheme rather than
     installing globally.

     By default, the scripts ‘pipX’ and ‘pipX.Y’ will be installed
     (where X.Y stands for the current version of Python).

     If `altinstall' is set, then ‘pipX’ will `not' be installed.

     If `default_pip' is set, then ‘pip’ will be installed in addition
     to the two regular scripts.

     Setting both `altinstall' and `default_pip' will trigger *note
     ValueError: 16d.

     `verbosity' controls the level of output to *note sys.stdout: 41f.
     from the bootstrapping operation.

     Raises an *note auditing event: fa1. ‘ensurepip.bootstrap’ with
     argument ‘root’.

          備註: The bootstrapping process has side effects on both
          ‘sys.path’ and ‘os.environ’.  Invoking the command line
          interface in a subprocess instead allows these side effects to
          be avoided.

          備註: The bootstrapping process may install additional modules
          required by ‘pip’, but other software should not assume those
          dependencies will always be present by default (as the
          dependencies may be removed in a future version of ‘pip’).


File: python.info,  Node: venv --- 创建虚拟环境,  Next: zipapp —— 管理可执行的 Python zip 打包文件,  Prev: ensurepip --- Bootstrapping the pip installer,  Up: 軟體封裝與發布

5.28.3 ‘venv’ — 创建虚拟环境
----------------------------

3.3 版新加入.

`源码：' Lib/venv/(1)

__________________________________________________________________

*note venv: 12e. 模块支持使用自己的站点目录创建轻量级“虚拟环境”，可选择
与系统站点目录隔离。每个虚拟环境都有自己的 Python 二进制文件（与用于创建
此环境的二进制文件的版本相匹配），并且可以在其站点目录中拥有自己独立的已
安装 Python 软件包集。

有关 Python 虚拟环境的更多信息，请参阅 PEP 405(2) 。

也參考
......

Python 打包用户指南：创建和使用虚拟环境(3)

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/venv/

   (2) https://www.python.org/dev/peps/pep-0405

   (3) 
https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/#creating-a-virtual-environment


File: python.info,  Node: 创建虚拟环境,  Next: API<2>,  Up: venv --- 创建虚拟环境

5.28.3.1 创建虚拟环境
.....................

通过执行 ‘venv’ 指令来创建一个 *note 虚拟环境: 379e.:

     python3 -m venv /path/to/new/virtual/environment

运行此命令将创建目标目录（父目录若不存在也将创建），并放置一个
‘pyvenv.cfg’ 文件在其中，文件中有一个 ‘home’ 键，它的值指向运行此命令的
Python 安装（目标目录的常用名称是 ‘.venv’）。它还会创建一个 ‘bin’ 子目录
（在 Windows 上是 ‘Scripts’），其中包含 Python 二进制文件的副本或符号链
接（视创建环境时使用的平台或参数而定）。它还会创建一个（初始为空的）
‘lib/pythonX.Y/site-packages’ 子目录（在 Windows 上是
‘Lib\site-packages’）。如果指定了一个现有的目录，这个目录就将被重新使用
。

3.6 版後已棄用: ‘pyvenv’ 是 Python 3.3 和 3.4 中创建虚拟环境的推荐工具，
不过 在 Python 3.6 中已弃用(1)。

3.5 版更變: 现在推荐使用 ‘venv’ 来创建虚拟环境。

在 Windows 上，调用 ‘venv’ 命令如下:

     c:\>c:\Python35\python -m venv c:\path\to\myenv

或者，如果已经为 *note Python 安装: 3f8. 配置好 ‘PATH’ 和 ‘PATHEXT’ 变量
:

     c:\>python -m venv c:\path\to\myenv

本命令如果以 ‘-h’ 参数运行，将显示可用的选项:

     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.

3.9 版更變: 添加 ‘--upgrade-deps’ 选项，用于将 pip + setuptools 升级到
PyPI 上的最新版本

3.4 版更變: 默认安装 pip，并添加 ‘--without-pip’ 和 ‘--copies’ 选项

3.4 版更變: 在早期版本中，如果目标目录已存在，将引发错误，除非使用了
‘--clear’ 或 ‘--upgrade’ 选项。

     備註: 虽然 Windows 支持符号链接，但不推荐使用它们。特别注意，在文件
     资源管理器中双击 ‘python.exe’ 将立即解析符号链接，并忽略虚拟环境。

     備註: 在 Microsoft Windows 上，为了启用 ‘Activate.ps1’ 脚本，可能需
     要修改用户的执行策略。可以运行以下 PowerShell 命令来执行此操作：

     PS C:> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope
     CurrentUser

     参阅 About Execution Policies(2) 以获取更多信息。

生成的 ‘pyvenv.cfg’ 文件还包括 ‘include-system-site-packages’ 键，如果运
行 ‘venv’ 时带有 ‘--system-site-packages’ 选项，则键值为 ‘true’，否则为
‘false’。

除非采用 ‘--without-pip’ 选项，否则将会调用 *note ensurepip: 78. 将
‘pip’ 引导到虚拟环境中。

可以向 ‘venv’ 传入多个路径，此时将根据给定的选项，在所给的每个路径上创建
相同的虚拟环境。

创建虚拟环境后，可以使用虚拟环境的二进制目录中的脚本来“激活”该环境。不同
平台调用的脚本是不同的（须将 ‘<venv>’ 替换为包含虚拟环境的目录路径）：

平台              Shell                 用于激活虚拟环境的命令
                                        
--------------------------------------------------------------------------------------
                                        
POSIX             bash/zsh              $ source <venv>/bin/activate
                                        
                                        
                  fish                  $ source <venv>/bin/activate.fish
                                        
                                        
                  csh/tcsh              $ source <venv>/bin/activate.csh
                                        
                                        
                  PowerShell Core       $ <venv>/bin/Activate.ps1
                                        
                                        
Windows           cmd.exe               C:\> <venv>\Scripts\activate.bat
                                        
                                        
                  PowerShell            PS C:\> <venv>\Scripts\Activate.ps1
                                        

当一个虚拟环境被激活时， ‘VIRTUAL_ENV’ 环境变量会被设为该虚拟环境的路径
。 这可被用来检测程序是否运行在虚拟环境中。

激活环境不是 `必须' 的，激活只是将虚拟环境的二进制目录添加到搜索路径中，
这样 "python" 命令将调用虚拟环境的 Python 解释器，可以运行其中已安装的脚
本，而不必输入其完整路径。但是，安装在虚拟环境中的所有脚本都应在不激活的
情况下可运行，并自动与虚拟环境的 Python 一起运行。

在 shell 中输入 "deactivate" 可以退出虚拟环境。具体机制取决于不同平台，
并且是内部实现（通常使用脚本或 shell 函数）。

3.4 版新加入: ‘fish’ 和 ‘csh’ 激活脚本。

3.8 版新加入: 在 POSIX 上安装 PowerShell 激活脚本，以支持 PowerShell
Core。

     備註: 虚拟环境是一个 Python 环境，安装到其中的 Python 解释器、库和
     脚本与其他虚拟环境中的内容是隔离的，且（默认）与“系统级” Python（操
     作系统的一部分）中安装的库是隔离的。

     虚拟环境是一个目录树，其中包含 Python 可执行文件和其他文件，其他文
     件指示了这是一个是虚拟环境。

     常用安装工具如 setuptools(3) 和 pip(4) 可以在虚拟环境中按预期工作。
     换句话说，当虚拟环境被激活，它们就会将 Python 软件包安装到虚拟环境
     中，无需明确指示。

     当虚拟环境被激活（即虚拟环境的 Python 解释器正在运行），属性 *note
     sys.prefix: 379f. 和 *note sys.exec_prefix: 37a0. 指向的是虚拟环境
     的基础目录，而 *note sys.base_prefix: 3180. 和 *note
     sys.base_exec_prefix: 37a1. 指向非虚拟环境的 Python 安装，即曾用于
     创建虚拟环境的那个 Python 安装。如果虚拟环境没有被激活，则 *note
     sys.prefix: 379f. 与 *note sys.base_prefix: 3180. 相同，且 *note
     sys.exec_prefix: 37a0. 与 *note sys.base_exec_prefix: 37a1. 相同（
     它们均指向非虚拟环境的 Python 安装）。

     当虚拟环境被激活，所有 *note distutils: 38. 配置文件中更改安装路径
     的选项都会被忽略，以防止无意中将项目安装在虚拟环境之外。

     在命令行 shell 中工作时，用户可以运行虚拟环境可执行文件目录中的
     ‘activate’ 脚本来激活虚拟环境（调用该文件的确切文件名和命令取决于
     shell），这会将虚拟环境的可执行文件目录添加到当前 shell 的 ‘PATH’ 环
     境变量。在其他情况下，无需激活虚拟环境。安装到虚拟环境中的脚本有
     "shebang" 行，指向虚拟环境的 Python 解释器。这意味着无论 ‘PATH’ 的
     值如何，脚本都将与该解释器一起运行。在 Windows 上，如果已安装
     Python Launcher for Windows，则支持处理 "shebang" 行（此功能在
     Python 3.3 中添加，详情请参阅 PEP 397(5)）。这样，在 Windows 资源管
     理器中双击已安装的脚本，应该会使用正确的解释器运行该脚本，而在
     ‘PATH’ 中无需指向其虚拟环境。

   ---------- Footnotes ----------

   (1) https://docs.python.org/dev/whatsnew/3.6.html#deprecated-features

   (2) https://go.microsoft.com/fwlink/?LinkID=135170

   (3) https://pypi.org/project/setuptools/

   (4) https://pypi.org/project/pip/

   (5) https://www.python.org/dev/peps/pep-0397


File: python.info,  Node: API<2>,  Next: 一个扩展 EnvBuilder 的例子,  Prev: 创建虚拟环境,  Up: venv --- 创建虚拟环境

5.28.3.2 API
............

上述的高级方法使用了一个简单的 API，该 API 提供了一种机制，第三方虚拟环
境创建者可以根据其需求自定义环境创建过程，该 API 为 *note EnvBuilder:
9ee. 类。

 -- 類別: venv.EnvBuilder (system_site_packages=False, clear=False,
          symlinks=False, upgrade=False, with_pip=False, prompt=None,
          upgrade_deps=False)

     *note EnvBuilder: 9ee. 类在实例化时接受以下关键字参数：

        * ‘system_site_packages’ – 一个布尔值，要求系统 Python 的
          site-packages 对环境可用（默认为 ‘False’）。

        * ‘clear’ – 一个布尔值，如果为 true，则在创建环境前将删除目标目
          录的现有内容。

        * ‘symlinks’ – 一个布尔值，指示是否尝试符号链接 Python 二进制文
          件，而不是进行复制。

        * ‘upgrade’ – 一个布尔值，如果为 true，则将使用当前运行的 Python
          去升级一个现有的环境，这主要在原位置的 Python 更新后使用（默认
          为 ‘False’）。

        * ‘with_pip’ – 一个布尔值，如果为 true，则确保在虚拟环境中已安装
          pip。这使用的是带有 ‘--default-pip’ 选项的 *note ensurepip:
          78.。

        * ‘prompt’ – 激活虚拟环境后显示的提示符（默认为 ‘None’，表示使用
          环境所在的目录名称）。如果使用了 ‘"."’ 这一特殊字符串，则使用
          当前目录的基本名称作为提示符。

        * ‘upgrade_deps’ – 将基本 venv 模块更新为 PyPI 上的最新版本。

     3.4 版更變: 添加 ‘with_pip’ 参数

     3.6 版新加入: 添加 ‘prompt’ 参数

     3.9 版新加入: 添加 ‘upgrade_deps’ 参数

     第三方虚拟环境工具的创建者可以自由地将此处提供的 *note EnvBuilder:
     9ee. 类作为基类。

     返回的 env-builder 是一个对象，包含一个 ‘create’ 方法：

      -- 成員函式: create (env_dir)

          指定要建立虚拟环境的目标目录（绝对路径或相对于当前路径）来创建
          虚拟环境。‘create’ 方法将在指定目录中创建环境，或者引发对应的
          异常。

          *note EnvBuilder: 9ee. 类的 ‘create’ 方法定义了可用于定制子类
          的钩子:

               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)

          每个方法 *note ensure_directories(): 37a4, *note
          create_configuration(): 37a5, *note setup_python(): 37a6,
          *note setup_scripts(): 37a7. 和 *note post_setup(): 37a8. 都可
          以被重写。

      -- 成員函式: ensure_directories (env_dir)

          创建环境目录和所有必需的目录，并返回一个上下文对象。该对象只是
          一个容器，保存属性（如路径），供其他方法使用。允许目录已经存在
          ，如果指定了 ‘clear’ 或 ‘upgrade’ 就允许在现有环境目录上进行操
          作。

      -- 成員函式: create_configuration (context)

          在环境中创建 ‘pyvenv.cfg’ 配置文件。

      -- 成員函式: setup_python (context)

          在环境中创建 Python 可执行文件的拷贝或符号链接。在 POSIX 系统
          上，如果给定了可执行文件 ‘python3.x’，将创建指向该可执行文件的
          ‘python’ 和 ‘python3’ 符号链接，除非相同名称的文件已经存在。

      -- 成員函式: setup_scripts (context)

          将适用于平台的激活脚本安装到虚拟环境中。

      -- 成員函式: upgrade_dependencies (context)

          升级环境中 venv 依赖的核心软件包（当前为 ‘pip’ 和
          ‘setuptools’）。通过在环境中使用 ‘pip’ 可执行文件来完成。

          3.9 版新加入.

      -- 成員函式: post_setup (context)

          占位方法，可以在第三方实现中重写，用于在虚拟环境中预安装软件包
          ，或是其他创建后要执行的步骤。

     3.7.2 版更變: Windows 现在为 ‘python[w].exe’ 使用重定向脚本，而不是
     复制实际的二进制文件。仅在 3.7.2 中，除非运行的是源码树中的构建，否
     则 *note setup_python(): 37a6. 不会执行任何操作。

     3.7.3 版更變: Windows 将重定向脚本复制为 *note setup_python():
     37a6. 的一部分而非 *note setup_scripts(): 37a7.。在 3.7.2 中不是这
     种情况。使用符号链接时，将链接至原始可执行文件。

     此外，*note EnvBuilder: 9ee. 提供了如下实用方法，可以从子类的 *note
     setup_scripts(): 37a7. 或 *note post_setup(): 37a8. 调用，用来将自
     定义脚本安装到虚拟环境中。

      -- 成員函式: install_scripts (context, path)

          `path' 是一个目录的路径，该目录应包含子目录 "common", "posix",
          "nt"，每个子目录存有发往对应环境中 bin 目录的脚本。在下列占位
          符替换完毕后，将复制 "common" 的内容和与 *note os.name: 2040.
          对应的子目录：

             * ‘__VENV_DIR__’ 会被替换为环境目录的绝对路径。

             * ‘__VENV_NAME__’ 会被替换为环境名称（环境目录的最后一个字
               段）。

             * ‘__VENV_PROMPT__’ 会被替换为提示符（用括号括起来的环境名
               称紧跟着一个空格）。

             * ‘__VENV_BIN_NAME__’ 会被替换为 bin 目录的名称（ ‘bin’ 或
               ‘Scripts’ ）。

             * ‘__VENV_PYTHON__’ 会被替换为环境可执行文件的绝对路径。

          允许目录已存在（用于升级现有环境时）。

有一个方便实用的模块级别的函数:

 -- 函式: venv.create (env_dir, system_site_packages=False, clear=False,
          symlinks=False, with_pip=False, prompt=None)

     通过关键词参数来创建一个 *note EnvBuilder: 9ee.，并且使用 `env_dir'
     参数来调用它的 *note create(): 37a3. 方法。

     3.3 版新加入.

     3.4 版更變: 添加 ‘with_pip’ 参数

     3.6 版更變: 添加 ‘prompt’ 参数


File: python.info,  Node: 一个扩展 EnvBuilder 的例子,  Prev: API<2>,  Up: venv --- 创建虚拟环境

5.28.3.3 一个扩展 ‘EnvBuilder’ 的例子
.....................................

下面的脚本展示了如何通过实现一个子类来扩展 *note EnvBuilder: 9ee.。这个
子类会安装 setuptotols 和 pip 的到被创建的虚拟环境中。

     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 = ''
             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)

这个脚本同样可以 在线下载(1)。

   ---------- Footnotes ----------

   (1) https://gist.github.com/vsajip/4673395


File: python.info,  Node: zipapp —— 管理可执行的 Python zip 打包文件,  Prev: venv --- 创建虚拟环境,  Up: 軟體封裝與發布

5.28.4 ‘zipapp’ —— 管理可执行的 Python zip 打包文件
---------------------------------------------------

3.5 版新加入.

`源代码：' Lib/zipapp.py(1)

__________________________________________________________________

本模块提供了一套管理工具，用于创建包含 Python 代码的压缩文件，这些文件可
以 *note 直接由 Python 解释器执行: 146e.。 本模块提供 *note
命令執行列介面: 37af. 和 *note Python API: 37b0.。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/zipapp.py


File: python.info,  Node: 简单示例,  Next: 命令執行列介面<2>,  Up: zipapp —— 管理可执行的 Python zip 打包文件

5.28.4.1 简单示例
.................

下述例子展示了用 *note 命令執行列介面: 37af. 根据含有 Python 代码的目录
创建一个可执行的打包文件。 运行后该打包文件时，将会执行 ‘myapp’ 模块中的
‘main’ 函数。

     $ python -m zipapp myapp -m "myapp:main"
     $ python myapp.pyz
     <output from myapp>


File: python.info,  Node: 命令執行列介面<2>,  Next: Python API,  Prev: 简单示例,  Up: zipapp —— 管理可执行的 Python zip 打包文件

5.28.4.2 命令執行列介面
.......................

若要从命令行调用，则采用以下形式：

     $ python -m zipapp source [options]

如果 `source' 是个目录，将根据 `source' 的内容创建一个打包文件。如果
`source' 是个文件，则应为一个打包文件，将会复制到目标打包文件中（如果指
定了 -info 选项，将会显示 shebang 行的内容）。

可以接受以下参数：

 -- 程式選項: -o <output>, --output=<output>

     将程序的输出写入名为 `output' 的文件中。若未指定此参数，输出的文件
     名将与输入的 `source' 相同，并添加扩展名 ‘.pyz’。如果显式给出了文件
     名，将会原样使用（因此必要时应包含扩展名 ‘.pyz’）。

     如果 `source' 是个打包文件，必须指定一个输出文件名（这时 `output' 必
     须与 `source' 不同）。

 -- 程式選項: -p <interpreter>, --python=<interpreter>

     给打包文件加入 ‘#!’ 行，以便指定 `解释器' 作为运行的命令行。另外，
     还让打包文件在 POSIX 平台上可执行。默认不会写入 ‘#!’ 行，也不让文件
     可执行。

 -- 程式選項: -m <mainfn>, --main=<mainfn>

     在打包文件中写入一个 ‘__main__.py’ 文件，用于执行 `mainfn'。
     `mainfn' 参数的形式应为 “pkg.mod:fn”，其中 “pkg.mod”是打包文件中的
     某个包/模块，“fn”是该模块中的一个可调用对象。‘__main__.py’ 文件将会
     执行该可调用对象。

     在复制打包文件时，不能设置 *note –main: 37b5. 参数。

 -- 程式選項: -c, --compress

     利用 deflate 方法压缩文件，减少输出文件的大小。默认情况下，打包文件
     中的文件是不压缩的。

     在复制打包文件时，*note –compress: 37b6. 无效。

     3.7 版新加入.

 -- 程式選項: --info

     显示嵌入在打包文件中的解释器程序，以便诊断问题。这时会忽略其他所有
     参数，SOURCE 必须是个打包文件，而不是目录。

 -- 程式選項: -h, --help

     打印简短的用法信息并退出。


File: python.info,  Node: Python API,  Next: 示例<42>,  Prev: 命令執行列介面<2>,  Up: zipapp —— 管理可执行的 Python zip 打包文件

5.28.4.3 Python API
...................

该模块定义了两个快捷函数：

 -- 函式: zipapp.create_archive (source, target=None, interpreter=None,
          main=None, filter=None, compressed=False)

     由 `source' 创建一个应用程序打包文件。source 可以是以下形式之一：

        * 一个目录名，或指向目录的 *note path-like object: 472. ，这时将
          根据目录内容新建一个应用程序打包文件。

        * 一个已存在的应用程序打包文件名，或指向这类文件的 *note
          path-like object: 472.，这时会将该文件复制为目标文件（会稍作修
          改以反映出 `interpreter' 参数的值）。必要时文件名中应包括
          ‘.pyz’ 扩展名。

        * 一个以字节串模式打开的文件对象。该文件的内容应为应用程序打包文
          件，且假定文件对象定位于打包文件的初始位置。

     `target' 参数定义了打包文件的写入位置：

        * 若是个文件名，或是 *note path-like object: 472.，打包文件将写
          入该文件中。

        * 若是个打开的文件对象，打包文件将写入该对象，该文件对象必须在字
          节串写入模式下打开。

        * 如果省略了 target （或为 ‘None’），则 source 必须为一个目录，
          target 将是与 source 同名的文件，并加上 ‘.pyz’ 扩展名。

     参数 `interpreter' 指定了 Python 解释器程序名，用于执行打包文件。这
     将以 “释伴（shebang）”行的形式写入打包文件的头部。在 POSIX 平台上，
     操作系统会进行解释，而在 Windows 平台则会由 Python 启动器进行处理。
     省略 `interpreter' 参数则不会写入释伴行。如果指定了解释器，且目标为
     文件名，则会设置目标文件的可执行属性位。

     参数 `main' 指定某个可调用程序的名称，用作打包文件的主程序。仅当
     source 为目录且不含 ‘__main__.py’ 文件时，才能指定该参数。`main' 参
     数应采用 “pkg.module:callable”的形式，通过导入“pkg.module”并不带参
     数地执行给出的可调用对象，即可执行打包文件。如果 source 是目录且不
     含‘‘__main__.py‘‘ 文件，省略 `main' 将会出错，生成的打包文件将无法
     执行。

     可选参数 `filter' 指定了回调函数，将传给代表被添加文件路径的 Path 对
     象（相对于源目录）。在文件添加完成后，应返回 ‘True’。

     可选参数 `compressed' 指定是否要压缩打包文件。若设为 ‘True’，则打包
     中的文件将用 deflate 方法进行压缩；否则就不会压缩。本参数在复制现有
     打包文件时无效。

     若 `source' 或 `target' 指定的是文件对象，则调用者有责任在调用
     create_archive 之后关闭文件。

     当复制已有的打包文件时，提供的文件对象只需 ‘read’ 和 ‘readline’ 方
     法，或 ‘write’ 方法。当由目录创建打包文件时，若目标为文件对象，将会
     将其传给 类，且必须提供 ‘zipfile.ZipFile’ 类所需的方法。

     3.7 版新加入: 加入了 `filter' 和 `compressed' 参数。

 -- 函式: zipapp.get_interpreter (archive)

     返回打包文件开头的 行指定的解释器程序。如果没有 ‘#!’ 行，则返回
     *note None: 203.。参数 `archive' 可为文件名或在字节串模式下打开以供
     读取的文件类对象。‘#!’ 行假定是在打包文件的开头。


File: python.info,  Node: 示例<42>,  Next: 指定解释器程序,  Prev: Python API,  Up: zipapp —— 管理可执行的 Python zip 打包文件

5.28.4.4 示例
.............

将目录打包成一个文件并运行它。

     $ python -m zipapp myapp
     $ python myapp.pyz
     <output from myapp>

同样还可用 *note create_archive(): 520. 函数完成：

     >>> import zipapp
     >>> zipapp.create_archive('myapp', 'myapp.pyz')

要让应用程序能在 POSIX 平台上直接执行，需要指定所用的解释器。

     $ python -m zipapp myapp -p "/usr/bin/env python"
     $ ./myapp.pyz
     <output from myapp>

若要替换已有打包文件中的释伴行，请用 *note create_archive(): 520. 函数另
建一个修改好的打包文件：

     >>> import zipapp
     >>> zipapp.create_archive('old_archive.pyz', 'new_archive.pyz', '/usr/bin/python3')

若要原地更新打包文件，可用 ‘BytesIO’ 对象在内存中进行替换，然后再覆盖源
文件。注意，原地覆盖文件会有风险，出错时会丢失原文件。这里没有考虑出错情
况，但生产代码则应进行处理。另外，这种方案仅当内存足以容纳打包文件时才有
意义：

     >>> 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())


File: python.info,  Node: 指定解释器程序,  Next: 用 zipapp 创建独立运行的应用程序,  Prev: 示例<42>,  Up: zipapp —— 管理可执行的 Python zip 打包文件

5.28.4.5 指定解释器程序
.......................

注意，如果指定了解释器程序再发布应用程序打包文件，需要确保所用到的解释器
是可移植的。Windows 的 Python 启动器支持大多数常见的 POSIX ‘#!’ 行，但还
需要考虑一些其他问题。

   * 如果采用“/usr/bin/env python”（或其他格式的 python 调用命令，比如
     “/usr/bin/python”)，需要考虑默认版本既可能是 Python 2 又可能是
     Python 3，应让代码在两个版本下均能正常运行。

   * 如果用到的 Python 版本明确，如“/usr/bin/env python3”，则没有该版本
     的用户将无法运行应用程序。（如果代码不兼容 Python 2，可能正该如此）
     。

   * 因为无法指定“python X.Y以上版本”，所以应小心“/usr/bin/env
     python3.4”这种精确版本的指定方式，因为对于 Python 3.5 的用户就得修
     改释伴行，比如：

通常应该用“/usr/bin/env python2”或“/usr/bin/env python3”的格式，具体根据
代码适用于 Python 2 还是 3 而定。


File: python.info,  Node: 用 zipapp 创建独立运行的应用程序,  Next: Python 打包应用程序的格式,  Prev: 指定解释器程序,  Up: zipapp —— 管理可执行的 Python zip 打包文件

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

利用 *note zipapp: 14a. 模块可以创建独立运行的 Python 程序，以便向最终用
户发布，仅需在系统中装有合适版本的 Python 即可运行。操作的关键就是把应用
程序代码和所有依赖项一起放入打包文件中。

创建独立运行打包文件的步骤如下：

  1. 照常在某个目录中创建应用程序，于是会有一个 ‘myapp’ 目录，里面有个
     ‘‘__main__.py‘‘ 文件，以及所有支持性代码。

  2. 用 pip 将应用程序的所有依赖项装入 ‘myapp’ 目录。

          $ python -m pip install -r requirements.txt --target myapp

     （这里假定在 ‘requirements.txt’ 文件中列出了项目所需的依赖项，也可
     以在 pip 命令行中列出依赖项）。

  3. pip 在 ‘myapp’ 中创建的 ‘.dist-info’ 目录，是可以删除的。这些目录保
     存了 pip 用于管理包的元数据，由于接下来不会再用到 pip，所以不是必须
     存在，当然留下来也不会有什么坏处。

  4. 用以下命令打包：

          $ python -m zipapp -p "interpreter" myapp

这会生成一个独立的可执行文件，可在任何装有合适解释器的机器上运行。详情参
见 *note 指定解释器程序: 37be.。可以单个文件的形式分发给用户。

在 Unix 系统中，‘myapp.pyz’ 文件将以原有文件名执行。如果喜欢 “普通”的命
令名，可以重命名该文件，去掉扩展名 ‘.pyz’ 。在 Windows 系统中，
‘myapp.pyz[w]’ 是可执行文件，因为 Python 解释器在安装时注册了扩展名
‘‘.pyz‘‘ 和 ‘.pyzw’ 。

* Menu:

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


File: python.info,  Node: 制作 Windows 可执行文件,  Next: 注意事项,  Up: 用 zipapp 创建独立运行的应用程序

5.28.4.7 制作 Windows 可执行文件
................................

在 Windows 系统中，可能没有注册扩展名 ‘.pyz’，另外有些场合无法“透明”地识
别已注册的扩展（最简单的例子是，‘subprocess.run(['myapp'])’ 就找不到——需
要明确指定扩展名）。

因此，在 Windows 系统中，通常最好 由zipapp 创建一个可执行文件。虽然需要
用到 C 编译器，但还是相对容易做到的。基本做法有赖于以下事实，即 zip 文件
内可预置任意数据，Windows 的 exe 文件也可以附带任意数据。因此，创建一个
合适的启动程序并将 ‘.pyz’ 文件附在后面，最后就能得到一个单文件的可执行文
件，可运行 Python 应用程序。

合适的启动程序可以简单如下：

     #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);
     }

若已定义了预处理器符号 ‘WINDOWS’，上述代码将会生成一个 GUI 可执行文件。
若未定义则生成一个可执行的控制台文件。

直接使用标准的 MSVC 命令行工具，或利用 distutils 知道如何编译 Python 源
代码，即可编译可执行文件：

     >>> 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")

生成的启动程序用到了 “受限 ABI”，所以可在任意版本的 Python 3.x 中运行。
只要用户的 ‘PATH’ 中包含了 Python（‘python3.dll’）路径即可。

若要得到完全独立运行的发行版程序，可将附有应用程序的启动程序，与“内嵌版”
Python 打包在一起即可。这样在架构匹配（32位或64位）的任一 PC 上都能运行
。


File: python.info,  Node: 注意事项,  Prev: 制作 Windows 可执行文件,  Up: 用 zipapp 创建独立运行的应用程序

5.28.4.8 注意事项
.................

要将应用程序打包为单个文件，存在一些限制。大多数情况下，无需对应用程序进
行重大修改即可解决。

  1. 如果应用程序依赖某个带有 C 扩展的包，则此程序包无法由打包文件运行（
     这是操作系统的限制，因为可执行代码必须存在于文件系统中，操作系统才
     能加载）。这时可去除打包文件中的依赖关系，然后要求用户事先安装好该
     程序包，或者与打包文件一起发布并在 ‘__main__.py’ 中增加代码，将未打
     包模块的目录加入 ‘sys.path’ 中。采用增加代码方式时，一定要为目标架
     构提供合适的二进制文件（可能还需在运行时根据用户的机器选择正确的版
     本加入 ‘sys.path’）。

  2. 若要如上所述发布一个 Windows 可执行文件，就得确保用户在 PATH 中包含
     ‘‘python3.dll‘‘ 的路径（安装程序默认不会如此），或者应把应用程序与
     内嵌版 Python 一起打包。

  3. 上述给出的启动程序采用了 Python 嵌入 API。 这意味着应用程序将会是
     ‘sys.executable’ ，而*不是*传统的 Python 解释器。代码及依赖项需做好
     准备。例如，如果应用程序用到了 *note multiprocessing: b7. 模块，就
     需要调用 *note multiprocessing.set_executable(): 2520. 来让模块知道
     标准 Python 解释器的位置。


File: python.info,  Node: Python 打包应用程序的格式,  Prev: 用 zipapp 创建独立运行的应用程序,  Up: zipapp —— 管理可执行的 Python zip 打包文件

5.28.4.9 Python 打包应用程序的格式
..................................

自 2.6 版开始，Python 即能够执行包含 文件的打包文件了。为了能被 Python 执
行，应用程序的打包文件必须为包含 ‘__main__.py’ 文件的标准 zip 文件，
‘__main__.py’ 文件将作为应用程序的入口运行。类似于常规的 Python 脚本，父
级（这里指打包文件）将放入 *note sys.path: 261. ，因此可从打包文件中导入
更多的模块。

zip 文件格式允许在文件中预置任意数据。利用这种能力，zip 应用程序格式在文
件中预置了一个标准的 POSIX “释伴”行（‘#!/path/to/interpreter’）。

因此，Python zip 应用程序的格式会如下所示：

  1. 可选的释伴行，包含字符 ‘b'#!'’，后面是解释器名，然后是换行符 （
     ‘b'\n'’）。 解释器名可为操作系统 “释伴”处理所能接受的任意值，或为
     Windows 系统中的 Python 启动程序。解释器名在 Windows 中应用 UTF-8 编
     码，在 POSIX 中则用 *note sys.getfilesystemencoding(): 5ef.。

  2. 标准的打包文件由 *note zipfile: 14b. 模块生成。其中 `必须' 包含一个
     名为‘‘__main__.py‘‘ 的文件（必须位于打包文件的“根”目录——不能位于某
     个子目录中）。打包文件中的数据可以是压缩或未压缩的。

如果应用程序的打包文件带有释伴行，则在 POSIX 系统中可能需要启用可执行属
性，以允许直接执行。

不一定非要用本模块中的工具创建应用程序打包文件，本模块只是提供了便捷方案
，上述格式的打包文件可用任何方式创建，均可被 Python 接受。


File: python.info,  Node: Python运行时服务,  Next: 自定义 Python 解释器,  Prev: 軟體封裝與發布,  Up: Python 標準函式庫 Standard Library

5.29 Python运行时服务
=====================

本章里描述的模块提供了和Python解释器及其环境交互相关的广泛服务。以下是综
述：

* Menu:

* sys: sys --- 系统相关的参数和函数. 系统相关的参数和函数
* sysconfig: sysconfig --- Provide access to Python's configuration information. Provide access to Python’s configuration information
* 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 —— 指定域的配置钩子::


File: python.info,  Node: sys --- 系统相关的参数和函数,  Next: sysconfig --- Provide access to Python's configuration information,  Up: Python运行时服务

5.29.1 ‘sys’ — 系统相关的参数和函数
-----------------------------------

__________________________________________________________________

该模块提供了一些变量和函数。这些变量可能被解释器使用，也可能由解释器提供
。这些函数会影响解释器。本模块总是可用的。

 -- Data: sys.abiflags

     在POSIX系统上，以标准的 ‘configure’ 脚本构建的 Python 中，这个变量
     会包含 PEP 3149(1) 中定义的ABI标签。

     3.8 版更變: 默认的 flags 变为了空字符串（用于 pymalloc 的 ‘m’ 旗标
     已经移除）

     3.2 版新加入.

 -- 函式: sys.addaudithook (hook)

     将可调用对象 `hook' 附加到当前（子）解释器的活动的审计钩子列表中。

     当通过 *note sys.audit(): 1056. 函数引发审计事件时，每个钩子将按照
     其被加入的先后顺序被调用，调用时会传入事件名称和参数元组。 由 *note
     PySys_AddAuditHook(): 366b. 添加的原生钩子会先被调用，然后是当前（
     子）解释器中添加的钩子。 接下来这些钩子会记录事件，引发异常来中止操
     作，或是完全终止进程。

     调用 *note sys.addaudithook(): 366a. 时它自身将引发一个名为
     ‘sys.addaudithook’ 的审计事件且不附带参数。 如果任何现有的钩子引发
     了派生自 *note RuntimeError: 3dc. 的异常，则新的钩子不会被添加并且
     该异常会被抑制。 其结果就是，调用者无法确保他们的钩子已经被添加，除
     非他们控制了全部现有的钩子。

     请参阅 *note 审计事件表: 3667. 以获取由 CPython 引发的所有事件，并
     参阅 PEP 578(2) 了解最初的设计讨论。

     3.8 版新加入.

     3.8.1 版更變: 派生自 *note Exception: 2dc. （而非 *note
     RuntimeError: 3dc. ）的异常不会被抑制。

     `CPython implementation detail:' 启用跟踪时（参阅 *note settrace():
     f00. ），仅当可调用对象（钩子）的 ‘__cantrace__’ 成员设置为 true 时
     ，才会跟踪该钩子。否则，跟踪功能将跳过该钩子。

 -- Data: sys.argv

     一个列表，其中包含了被传递给 Python 脚本的命令行参数。 ‘argv[0]’ 为
     脚本的名称（是否是完整的路径名取决于操作系统）。如果是通过 Python 解
     释器的命令行参数 *note -c: 1340. 来执行的， ‘argv[0]’ 会被设置成字
     符串 ‘'-c'’ 。如果没有脚本名被传递给 Python 解释器， ‘argv[0]’ 为空
     字符串。

     为了遍历标准输入，或者通过命令行传递的文件列表，参照 *note
     fileinput: 7e. 模块

          備註: 在 Unix 上，系统传递的命令行参数是字节类型的。Python 使
          用文件系统编码和 "surrogateescape" 错误处理方案对它们进行解码
          。当需要原始字节时，可以通过 ‘[os.fsencode(arg) for arg in
          sys.argv]’ 来获取。
 -- 函式: sys.audit (event, *args)

     引发一个审计事件并触发任何激活的审计钩子。 `event' 是一个用于标识事
     件的字符串，`args' 会包含有关事件的更多信息的可选参数。 特定事件的
     参数的数量和类型会被视为是公有的稳定 API 且不应当在版本之间进行修改
     。

     例如，有一个审计事件的名称为 ‘os.chdir’。 此事件具有一个名为 `path'
     的参数，该参数将包含所请求的新工作目录。

     *note sys.audit(): 1056. 将调用现有的审计钩子，传入事件名称和参数，
     并将重新引发来自任何钩子的第一个异常。 通常来说，如果有一个异常被引
     发，则它不应当被处理且其进程应当被尽可能快地终止。 这将允许钩子实现
     来决定对特定事件要如何反应：它们可以只是将事件写入日志或是通过引发
     异常来中止操作。

     钩子程序由 *note sys.addaudithook(): 366a. 或 *note
     PySys_AddAuditHook(): 366b. 函数添加。

     与本函数相等效的原生函数是 *note PySys_Audit(): 1068.，应尽量使用原
     生函数。

     参阅 *note 审计事件表: 3667. 以获取 CPython 定义的所有审计事件。

     3.8 版新加入.

 -- Data: sys.base_exec_prefix

     在 ‘site.py’ 运行之前， Python 启动的时候被设置为跟 *note
     exec_prefix: 37a0. 同样的值。如果不是运行在 *note 虚拟环境: 379e. 中
     ，两个值会保持相同；如果 ‘site.py’ 发现处于一个虚拟环境中， *note
     prefix: 379f. 和 *note exec_prefix: 37a0. 将会指向虚拟环境。然而
     *note base_prefix: 3180. 和 *note base_exec_prefix: 37a1. 将仍然会
     指向基础的 Python 环境（用来创建虚拟环境的 Python 环境）

     3.3 版新加入.

 -- Data: sys.base_prefix

     在 ‘site.py’ 运行之前， Python 启动的时候被设置为跟 *note prefix:
     379f. 同样的值。如果不是运行在 *note 虚拟环境: 379e. 中, 两个值会保
     持相同；如果 ‘site.py’ 发现处于一个虚拟环境中， *note prefix: 379f.
     和 *note exec_prefix: 37a0. 将会指向虚拟环境。然而 *note
     base_prefix: 3180. 和 *note base_exec_prefix: 37a1. 将仍然会指向基
     础的 Python 环境（用来创建虚拟环境的 Python 环境）

     3.3 版新加入.

 -- Data: sys.byteorder

     本地字节顺序的指示符。在大端序（最高有效位优先）操作系统上值为
     ‘'big'’ ，在小端序（最低有效位优先）操作系统上为 ‘'little'’ 。

 -- Data: sys.builtin_module_names

     一个元素为字符串的元组。包含了所有的被编译进 Python 解释器的模块。
     （这个信息无法通过其他的办法获取， ‘modules.keys()’ 只包括被导入过
     的模块。）

 -- 函式: sys.call_tracing (func, args)

     在启用跟踪时调用 ‘func(*args)’ 来保存跟踪状态，然后恢复跟踪状态。这
     将从检查点的调试器调用，以便递归地调试其他的一些代码。

 -- Data: sys.copyright

     一个字符串，包含了 Python 解释器有关的版权信息

 -- 函式: sys._clear_type_cache ()

     清除内部的类型缓存。类型缓存是为了加速查找方法和属性的。在调试引用
     泄漏的时候调用这个函数 `只会' 清除不必要的引用。

     这个函数应该只在内部为了一些特定的目的使用。

 -- 函式: sys._current_frames ()

     返回一个字典，存放着每个线程的标识符与（调用本函数时）该线程栈顶的
     帧（当前活动的帧）之间的映射。注意 *note traceback: 11c. 模块中的函
     数可以在给定某一帧的情况下构建调用堆栈。

     这对于调试死锁最有用：本函数不需要死锁线程的配合，并且只要这些线程
     的调用栈保持死锁，它们就是冻结的。在调用本代码来检查栈顶的帧的那一
     刻，非死锁线程返回的帧可能与该线程当前活动的帧没有任何关系。

     这个函数应该只在内部为了一些特定的目的使用。

     引发一个 *note 审计事件: fa1. ‘sys._current_frames’，没有附带参数。

 -- 函式: sys.breakpointhook ()

     本钩子函数由内建函数 *note breakpoint(): 40b. 调用。默认情况下，它
     将进入 *note pdb: c9. 调试器，但可以将其改为任何其他函数，以选择使
     用哪个调试器。

     该函数的特征取决于其调用的函数。例如，默认绑定（即
     ‘pdb.set_trace()’ ）不要求提供参数，但可以将绑定换成要求提供附加参
     数（位置参数/关键字参数）的函数。内建函数 ‘breakpoint()’ 直接将其
     ‘*args’ 和 ‘**kws’ 传入。‘breakpointhooks()’ 返回的所有内容都会从
     ‘breakpoint()’ 返回。

     默认的实现首先会查询环境变量 *note PYTHONBREAKPOINT: 424.。如果将该
     变量设置为 ‘"0"’，则本函数立即返回，表示在断点处无操作。如果未设置
     该环境变量或将其设置为空字符串，则调用 ‘pdb.set_trace()’。否则，此
     变量应指定要运行的函数，指定函数时应使用 Python 的点导入命名法，如
     ‘package.subpackage.module.function’。这种情况下将导入
     ‘package.subpackage.module’，且导入的模块必须有一个名为
     ‘function()’ 的可调用对象。该可调用对象会运行，‘*args’ 和 ‘**kws’ 会
     传入，且无论 ‘function()’ 返回什么，‘sys.breakpointhook()’ 都将返回
     到內建函数 *note breakpoint(): 40b.。

     请注意，如果在导入 *note PYTHONBREAKPOINT: 424. 指定的可调用对象时
     出错，则将报告一个 *note RuntimeWarning: 3e2. 并忽略断点。

     另请注意，如果以编程方式覆盖 ‘sys.breakpointhook()’，则 `不会' 查询
     *note PYTHONBREAKPOINT: 424.。

     3.7 版新加入.

 -- 函式: sys._debugmallocstats ()

     将有关 CPython 内存分配器状态的底层的信息打印至 stderr。

     如果 Python 被配置为 –with-pydebug，本方法还将执行一些开销较大的内
     部一致性检查。

     3.3 版新加入.

     `CPython implementation detail:' 本函数仅限 CPython。此处没有定义确
     切的输出格式，且可能会更改。

 -- Data: sys.dllhandle

     指向 Python DLL 句柄的整数。

     *note 可用性: 1491.: Windows。

 -- 函式: sys.displayhook (value)

     如果 `value' 不是 ‘None’，则本函数会将 ‘repr(value)’ 打印至
     ‘sys.stdout’，并将 `value' 保存在 ‘builtins._’ 中。如果
     ‘repr(value)’ 无法用 ‘sys.stdout.errors’ 错误处理方案（可能为
     ‘'strict'’ ）编码为 ‘sys.stdout.encoding’，则用
     ‘'backslashreplace'’ 错误处理方案将其编码为 ‘sys.stdout.encoding’。

     在交互式 Python 会话中运行 *note expression: 158f. 产生结果后，将在
     结果上调用 ‘sys.displayhook’。若要自定义这些 value 的显示，可以将
     ‘sys.displayhook’ 指定为另一个单参数函数。

     伪代码:

          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

     3.2 版更變: 在发生 *note UnicodeEncodeError: 32a. 时使用
     ‘'backslashreplace'’ 错误处理方案。

 -- Data: sys.dont_write_bytecode

     如果该值为 true，则 Python 在导入源码模块时将不会尝试写入 ‘.pyc’ 文
     件。该值会被初始化为 ‘True’ 或 ‘False’，依据是 *note -B: dfe. 命令
     行选项和 *note PYTHONDONTWRITEBYTECODE: dff. 环境变量，可以自行设置
     该值，来控制是否生成字节码文件。

 -- Data: sys.pycache_prefix

     如果将该值设为某个目录（不是 ‘None’ ），Python 会将字节码缓存文件
     ‘.pyc’ 写入到以该目录为根的并行目录树中（并从中读取），而不是在源码
     树中的 ‘__pycache__’ 目录下读写。源码树中所有的 ‘__pycache__’ 目录
     都将被忽略，并将在 pycache prefix 内写入新的 ‘.pyc’ 文件。因此，如
     果使用 *note compileall: 20. 作为预构建步骤，则必须确保预构建时使用
     的 pycache prefix （如果有）与将来运行的时候相同。

     相对路径将解释为相对于当前工作目录。

     该值的初值设置，依据 *note -X: 290. ‘pycache_prefix=PATH’ 命令行选
     项或 *note PYTHONPYCACHEPREFIX: 28f. 环境变量的值（命令行优先）。如
     果两者均未设置，则为 ‘None’。

     3.8 版新加入.

 -- 函式: sys.excepthook (type, value, traceback)

     本函数会将所给的回溯和异常输出到 ‘sys.stderr’ 中。

     当抛出一个异常，且未被捕获时，解释器将调用 ‘sys.excepthook’ 并带有
     三个参数：异常类、异常实例和一个回溯对象。在交互式会话中，这会在控
     制权返回到提示符之前发生。在 Python 程序中，这会在程序退出之前发生
     。如果要自定义此类顶级异常的处理过程，可以将另一个 3 个参数的函数赋
     给 ‘sys.excepthook’。

     引发一个 *note 审计事件: fa1. ‘sys.excepthook’，附带参数 ‘hook’,
     ‘type’, ‘value’, ‘traceback’。

     也參考
     ......

     *note sys.unraisablehook(): 35a. 函数处理无法抛出的异常，*note
     threading.excepthook(): 35e. 函数处理 *note threading.Thread.run():
     35f. 抛出的异常。

 -- Data: sys.__breakpointhook__
 -- Data: sys.__displayhook__
 -- Data: sys.__excepthook__
 -- Data: sys.__unraisablehook__

     程序开始时，这些对象存有 ‘breakpointhook’、‘displayhook’、
     ‘excepthook’ 和 ‘unraisablehook’ 的初始值。保存它们是为了可以在
     ‘breakpointhook’、‘displayhook’ 和 ‘excepthook’、‘unraisablehook’ 被
     破坏或被替换时恢复它们。

     3.7 版新加入: __breakpointhook__

     3.8 版新加入: __unraisablehook__

 -- 函式: sys.exc_info ()

     本函数返回的元组包含三个值，它们给出当前正在处理的异常的信息。返回
     的信息仅限于当前线程和当前堆栈帧。如果当前堆栈帧没有正在处理的异常
     ，则信息将从下级被调用的堆栈帧或上级调用者等位置获取，依此类推，直
     到找到正在处理异常的堆栈帧为止。此处的“处理异常”指的是“执行 except
     子句”。任何堆栈帧都只能访问当前正在处理的异常的信息。

     如果整个堆栈都没有正在处理的异常，则返回包含三个 ‘None’ 值的元组。
     否则返回值为 ‘(type, value, traceback)’。它们的含义是：`type' 是正
     在处理的异常类型（它是 *note BaseException: 2db. 的子类）；`value'
     是异常实例（异常类型的实例）；`traceback' 是一个 *note 回溯对象:
     442.，该对象封装了最初发生异常时的调用堆栈。

 -- Data: sys.exec_prefix

     一个字符串，提供特定域的目录前缀，该目录中安装了与平台相关的 Python
     文件，默认也是 ‘'/usr/local'’。该目录前缀可以在构建时使用
     ‘configure’ 脚本的 ‘--exec-prefix’ 参数进行设置。具体而言，所有配置
     文件（如 ‘pyconfig.h’ 头文件）都安装在目录
     ‘`exec_prefix'/lib/python`X.Y'/config’ 中，共享库模块安装在
     ‘`exec_prefix'/lib/python`X.Y'/lib-dynload’ 中，其中 `X.Y' 是
     Python 的版本号，如 ‘3.2’。

          備註: 如果在一个 *note 虚拟环境: 379e. 中，那么该值将在
          ‘site.py’ 中被修改，指向虚拟环境。Python 安装位置仍然可以用
          *note base_exec_prefix: 37a1. 来获取。

 -- Data: sys.executable

     一个字符串，提供 Python 解释器的可执行二进制文件的绝对路径，仅在部
     分系统中此值有意义。如果 Python 无法获取其可执行文件的真实路径，则
     *note sys.executable: 39d. 将为空字符串或 ‘None’。

 -- 函式: sys.exit ([arg])

     从 Python 中退出。实现方式是抛出一个 *note SystemExit: 6f3. 异常，
     因此异常抛出后 *note try: e37. 语句的 finally 分支的清除动作将被触
     发，这样可能会打断外层的退出尝试。

     可选参数 `arg' 可以是表示退出状态的整数（默认为 0），也可以是其他类
     型的对象。如果它是整数，则 shell 等将 0 视为“成功终止”，非零值视为
     “异常终止”。大多数系统要求该值的范围是 0–127，否则会产生不确定的结
     果。某些系统为退出代码约定了特定的含义，但通常尚不完善；Unix 程序通
     常用 2 表示命令行语法错误，用 1 表示所有其他类型的错误。传入其他类
     型的对象，如果传入 ‘None’ 等同于传入 0，如果传入其他对象则将其打印
     至 *note stderr: 1ea.，且退出代码为 1。特别地，‘sys.exit("some
     error message")’ 可以在发生错误时快速退出程序。

     由于 *note exit(): 1743. 最终“只是”抛出一个异常，因此当从主线程调用
     时，只会从进程退出；而异常不会因此被打断。

     3.6 版更變: 在 Python 解释器捕获 *note SystemExit: 6f3. 后，如果在
     清理中发生错误（如清除标准流中的缓冲数据时出错），则退出状态码将变
     为 120。

 -- Data: sys.flags

     *note 具名元组: b7b. `flags' 含有命令行标志的状态。这些属性是只读的
     。

     属性                              标志
                                       
     -------------------------------------------------------------------------------------------------------
                                       
     ‘debug’                           *note -d: 1476.
                                       
                                       
     *note inspect: a0.                *note -i: ee1.
                                       
                                       
     ‘interactive’                     *note -i: ee1.
                                       
                                       
     ‘isolated’                        *note -I: 231.
                                       
                                       
     ‘optimize’                        *note -O: 77e. 或 *note -OO: 77f.
                                       
                                       
     *note dont_write_bytecode: 37ce.  *note -B: dfe.
                                       
                                       
     ‘no_user_site’                    *note -s: ddb.
                                       
                                       
     ‘no_site’                         *note -S: bf7.
                                       
                                       
     ‘ignore_environment’              *note -E: 230.
                                       
                                       
     ‘verbose’                         *note -v: e4d.
                                       
                                       
     ‘bytes_warning’                   *note -b: 519.
                                       
                                       
     ‘quiet’                           *note -q: 1479.
                                       
                                       
     ‘hash_randomization’              *note -R: 11c9.
                                       
                                       
     ‘dev_mode’                        *note -X dev: 290. (*note Python 开发模式: 160.)
                                       
                                       
     ‘utf8_mode’                       *note -X utf8: 290.
                                       

     3.2 版更變: 为新的 *note -q: 1479. 标志添加了 ‘quiet’ 属性

     3.2.3 版新加入: ‘hash_randomization’ 属性

     3.3 版更變: 删除了过时的 ‘division_warning’ 属性

     3.4 版更變: 为 *note -I: 231. ‘isolated’ 标志添加了 ‘isolated’ 属性
     。

     3.7 版更變: 为新的 *note Python 开发模式: 160. 添加了 ‘dev_mode’ 属
     性，为新的 *note -X: 290. ‘utf8’ 标志添加了 ‘utf8_mode’ 属性。

 -- Data: sys.float_info

     一个 *note 具名元组: b7b.，存有浮点型的相关信息。它包含的是关于精度
     和内部表示的底层信息。这些值与标准头文件 ‘float.h’ 中为 C 语言定义
     的各种浮点常量对应，详情请参阅 1999 ISO/IEC C 标准 *note [C99]:
     37d3. 的 5.2.4.2.2 节，’Characteristics of floating types（浮点型的
     特性）’。

     属性                      float.h 宏           说明
                                                    
     ------------------------------------------------------------------------------------------------------
                                                    
     ‘epsilon’                 DBL_EPSILON          大于 1.0 的最小值和 1.0 之间的差，表示为浮点数
                                                    
                                                    另请参阅 *note math.ulp(): 1c1.。
                                                    
                                                    
     ‘dig’                     DBL_DIG              浮点数可以真实表示的最大十进制数字；见下文
                                                    
                                                    
     ‘mant_dig’                DBL_MANT_DIG         浮点数精度：‘radix’ 基数下的浮点数有效位数
                                                    
                                                    
     *note max: 8f7.           DBL_MAX              可表示的最大正浮点数（非无穷）
                                                    
                                                    
     ‘max_exp’                 DBL_MAX_EXP          使得 ‘radix**(e-1)’ 是可表示的浮点数（非无穷）的最大
                                                    整数 `e'
                                                    
                                                    
     ‘max_10_exp’              DBL_MAX_10_EXP       使得 ‘10**e’ 在可表示的浮点数（非无穷）范围内的最大
                                                    整数 `e'
                                                    
                                                    
     *note min: 8f6.           DBL_MIN              可表示的最小正 `规格化' 浮点数
                                                    
                                                    使用 *note math.ulp(0.0): 1c1. 获取可表示的最小正 `非
                                                    规格化' 浮点数
                                                    
                                                    
     ‘min_exp’                 DBL_MIN_EXP          使得 ‘radix**(e-1)’ 是规格化浮点数的最小整数 `e'
                                                    
                                                    
     ‘min_10_exp’              DBL_MIN_10_EXP       使得 ‘10**e’ 是规格化浮点数的最小整数 `e'
                                                    
                                                    
     ‘radix’                   FLT_RADIX            指数表示法中采用的基数
                                                    
                                                    
     ‘rounds’                  FLT_ROUNDS           整数常数，表示算术运算中的舍入方式。它反映了解释器启
                                                    动时系统的 FLT_ROUNDS 宏的值。关于可能的值及其含义的
                                                    说明，请参阅 C99 标准 5.2.4.2.2 节。
                                                    

     关于 ‘sys.float_info.dig’ 属性的进一步说明。如果 ‘s’ 是表示十进制数
     的字符串，而该数最多有 ‘sys.float_info.dig’ 位有效数字，则将 ‘s’ 转
     换为 float 再转回去将恢复原先相同十进制值的字符串:

          >>> 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'

     但是对于超过 ‘sys.float_info.dig’ 位有效数字的字符串，转换前后并非
     总是相同:

          >>> s = '9876543211234567'    # 16 significant digits is too many!
          >>> format(float(s), '.16g')  # conversion changes value
          '9876543211234568'

 -- Data: sys.float_repr_style

     一个字符串，反映 *note repr(): 8b9. 函数在浮点数上的行为。如果该字
     符串是 ‘'short'’，那么对于（非无穷的）浮点数 ‘x’，‘repr(x)’ 将会生
     成一个短字符串，满足 ‘float(repr(x)) == x’ 的特性。这是 Python 3.1
     及更高版本中的常见行为。否则 ‘float_repr_style’ 的值将是
     ‘'legacy'’，此时 ‘repr(x)’ 的行为方式将与 Python 3.1 之前的版本相同
     。

     3.1 版新加入.

 -- 函式: sys.getallocatedblocks ()

     返回解释器当前已分配的内存块数，无论它们大小如何。本函数主要用于跟
     踪和调试内存泄漏。因为解释器有内部缓存，所以不同调用之间结果会变化
     。可能需要调用 *note _clear_type_cache(): 37cb. 和 *note
     gc.collect(): 35b. 使结果更容易预测。

     如果当前 Python 构建或实现无法合理地计算此信息，允许 *note
     getallocatedblocks(): 9c8. 返回 0。

     3.4 版新加入.

 -- 函式: sys.getandroidapilevel ()

     返回一个整数，表示 Android 构建时 API 版本。

     *note 可用性: 1491.：Android。

     3.7 版新加入.

 -- 函式: sys.getdefaultencoding ()

     返回当前 Unicode 实现所使用的默认字符串编码名称。

 -- 函式: sys.getdlopenflags ()

     返回当前 ‘dlopen()’ 调用所使用的标志位的值。标志值对应的符号名称可
     以在 *note os: c4. 模块中找到（形如 ‘RTLD_xxx’ 的常量，如 *note
     os.RTLD_LAZY: b3a. ）。

     *note 可用性: 1491.: Unix。

 -- 函式: sys.getfilesystemencoding ()

     返回编码名称，该编码用于在 Unicode 文件名和 bytes 文件名之间转换。
     为获得最佳兼容性，任何时候都应使用 str 表示文件名，尽管用字节来表示
     文件名也是支持的。函数如果需要接受或返回文件名，它应支持 str 或
     bytes，并在内部将其转换为系统首选的表示形式。

     该编码始终是 ASCII 兼容的。

     应使用 *note os.fsencode(): 5e9. 和 *note os.fsdecode(): 5e8. 来保
     证所采用的编码和错误处理方案都是正确的。

        * 在 UTF-8 模式下，任何平台上的编码均为 ‘utf-8’。

        * 在 macOS 上，编码为 ‘'utf-8'’。

        * 在 Unix 上，编码是语言环境编码。

        * 在 Windows 上取决于用户配置，编码可能是 ‘'utf-8'’ 或 ‘'mbcs'’。

        * 在 Android 上，编码为 ‘'utf-8'’。

        * 在 VxWorks 上，编码为 ‘'utf-8'’。

     3.2 版更變: *note getfilesystemencoding(): 5ef. 的结果将不再有可能
     是 ‘None’。

     3.6 版更變: Windows 不再保证会返回 ‘'mbcs'’。详情请参阅 PEP 529(3)
     和 *note _enablelegacywindowsfsencoding(): 5f1.。

     3.7 版更變: 在 UTF-8 模式下返回 ’utf-8’ 。

 -- 函式: sys.getfilesystemencodeerrors ()

     返回错误处理方案的名称，该错误处理方案将在 Unicode 文件名和 bytes 文
     件名转换时生效。编码的名称是由 *note getfilesystemencoding(): 5ef.
     返回的。

     应使用 *note os.fsencode(): 5e9. 和 *note os.fsdecode(): 5e8. 来保
     证所采用的编码和错误处理方案都是正确的。

     3.6 版新加入.

 -- 函式: sys.getrefcount (object)

     返回 `object' 的引用计数。返回的计数通常比预期的多一，因为它包括了
     作为 *note getrefcount(): 37d5. 参数的这一次（临时）引用。

 -- 函式: sys.getrecursionlimit ()

     返回当前的递归限制值，即 Python 解释器堆栈的最大深度。此限制可防止
     无限递归导致的 C 堆栈溢出和 Python 崩溃。该值可以通过 *note
     setrecursionlimit(): f3c. 设置。

 -- 函式: sys.getsizeof (object[, default])

     返回对象的大小（以字节为单位）。该对象可以是任何类型。所有内建对象
     返回的结果都是正确的，但对于第三方扩展不一定正确，因为这与具体实现
     有关。

     只计算直接分配给对象的内存消耗，不计算它所引用的对象的内存消耗。

     对象不提供计算大小的方法时，如果传入过 `default' 则返回它，否则抛出
     *note TypeError: 1fe. 异常。

     如果对象由垃圾回收器管理，则 *note getsizeof(): 3765. 将调用对象的
     ‘__sizeof__’ 方法，并在上层添加额外的垃圾回收器。

     可以参考 recursive sizeof recipe(4) 中的示例，关于递归调用 *note
     getsizeof(): 3765. 来得到各个容器及其所有内容物的大小。

 -- 函式: sys.getswitchinterval ()

     返回解释器的“线程切换间隔时间”，请参阅 *note setswitchinterval():
     218.。

     3.2 版新加入.

 -- 函式: sys._getframe ([depth])

     返回来自调用栈的一个帧对象。如果传入可选整数 `depth'，则返回从栈顶
     往下相应调用层数的帧对象。如果该数比调用栈更深，则抛出 *note
     ValueError: 16d.。`depth' 的默认值是 0，返回调用栈顶部的帧。

     引发一个 *note 审计事件: fa1. ‘sys._getframe’，没有附带参数。

     `CPython implementation detail:' 这个函数应该只在内部为了一些特定的
     目的使用。不保证它在所有 Python 实现中都存在。

 -- 函式: sys.getprofile ()

     返回由 *note setprofile(): eff. 设置的性能分析函数。

 -- 函式: sys.gettrace ()

     返回由 *note settrace(): f00. 设置的跟踪函数。

     `CPython implementation detail:' *note gettrace(): e0d. 函数仅用于
     实现调试器，性能分析器，打包工具等。它的行为是实现平台的一部分，而
     不是语言定义的一部分，因此并非在所有 Python 实现中都可用。

 -- 函式: sys.getwindowsversion ()

     返回一个具名元组，描述当前正在运行的 Windows 版本。元素名称包括
     `major', `minor', `build', `platform', `service_pack',
     `service_pack_minor', `service_pack_major', `suite_mask',
     `product_type' 和 `platform_version'。`service_pack' 包含一个字符串
     ，`platform_version' 包含一个三元组，其他所有值都是整数。元素也可以
     通过名称来访问，所以 ‘sys.getwindowsversion()[0]’ 与
     ‘sys.getwindowsversion().major’ 是等效的。为保持与旧版本的兼容性，
     只有前 5 个元素可以用索引检索。

     `platform' 将会是 ‘2 (VER_PLATFORM_WIN32_NT)’。

     `product_type' 可能是以下值之一：

     常数                                        含义
                                                 
     ----------------------------------------------------------------------------------
                                                 
     ‘1 (VER_NT_WORKSTATION)’                    系统是工作站。
                                                 
                                                 
     ‘2 (VER_NT_DOMAIN_CONTROLLER)’              系统是域控制器。
                                                 
                                                 
     ‘3 (VER_NT_SERVER)’                         系统是服务器，但不是域控制器。
                                                 

     本函数包装了 Win32 ‘GetVersionEx()’ 函数，参阅 Microsoft 文档有关
     ‘OSVERSIONINFOEX()’ 的内容可获取这些字段的更多信息。

     `platform_version' 返回当前操作系统的主要版本、次要版本和编译版本号
     ，而不是为该进程所模拟的版本。 它旨在用于日志记录而非特性检测。

          備註: `platform_version' 会从 kernel32.dll 获取版本号，这个版
          本可能与 OS 版本不同。 请使用 *note platform: ce. 模块来获取准
          确的 OS 版本号。

     *note 可用性: 1491.: Windows。

     3.2 版更變: 更改为具名元组，添加 `service_pack_minor',
     `service_pack_major', `suite_mask' 和 `product_type'。

     3.6 版更變: 添加了 `platform_version'

 -- 函式: sys.get_asyncgen_hooks ()

     返回一个 `asyncgen_hooks' 对象，该对象类似于 *note namedtuple:
     1a1.，形式为 ‘(firstiter, finalizer)’，其中 `firstiter' 和
     `finalizer' 为 ‘None’ 或函数，函数以 *note 异步生成器迭代器: 37d7.
     作为参数，并用于在事件循环中干预异步生成器的终结。

     3.6 版新加入: 详情请参阅 PEP 525(5)。

          備註: 本函数已添加至暂定软件包（详情请参阅 PEP 411(6) ）。

 -- 函式: sys.get_coroutine_origin_tracking_depth ()

     获取由 *note set_coroutine_origin_tracking_depth(): 4f8. 设置的协程
     来源的追踪深度。

     3.7 版新加入.

          備註: 本函数已添加至暂定软件包（详情请参阅 PEP 411(7) ）。仅将
          其用于调试目的。

 -- Data: sys.hash_info

     一个 *note 具名元组: b7b.，给出数字类型的哈希的实现参数。关于数字类
     型的哈希的详情请参阅 *note 数字类型的哈希运算: 175b.。

     属性                      说明
                               
     ---------------------------------------------------------------------------------
                               
     ‘width’                   用于哈希值的位宽度
                               
                               
     ‘modulus’                 用于数字散列方案的素数模数P。
                               
                               
     ‘inf’                     为正无穷大返回的哈希值
                               
                               
     ‘nan’                     为nan返回的哈希值
                               
                               
     ‘imag’                    用于复数虚部的乘数
                               
                               
     ‘algorithm’               字符串、字节和内存视图的哈希算法的名称
                               
                               
     ‘hash_bits’               哈希算法的内部输出大小。
                               
                               
     ‘seed_bits’               散列算法的种子密钥的大小
                               

     3.2 版新加入.

     3.4 版更變: 添加了 `algorithm', `hash_bits' 和 `seed_bits'

 -- Data: sys.hexversion

     编码为单个整数的版本号。该整数会确保每个版本都自增，其中适当包括了
     未发布版本。举例来说，要测试 Python 解释器的版本不低于 1.5.2，请使
     用:

          if sys.hexversion >= 0x010502F0:
              # use some advanced feature
              ...
          else:
              # use an alternative implementation or warn the user
              ...

     之所以称它为 ‘hexversion’，是因为只有将它传入内置函数 *note hex():
     d2e. 后，其结果才看起来有意义。也可以使用 *note 具名元组: b7b.
     *note sys.version_info: bed.，它对相同信息有着更人性化的编码。

     关于 ‘hexversion’ 的更多信息可以在 *note API 和 ABI 版本管理: 37d9.
     中找到。

 -- Data: sys.implementation

     一个对象，该对象包含当前运行的 Python 解释器的实现信息。所有 Python
     实现中都必须存在下列属性。

     `name' 是当前实现的标识符，如 ‘'cpython'’。实际的字符串由 Python 实
     现定义，但保证是小写字母。

     `version' 是一个具名元组，格式与 *note sys.version_info: bed. 相同
     。它表示 Python `实现' 的版本。 另一个（由 ‘sys.version_info’ 表示
     ）是当前解释器遵循的相应 Python `语言' 的版本，两者具有不同的含义。
     例如，对于 PyPy 1.8，‘sys.implementation.version’ 可能是
     ‘sys.version_info(1, 8, 0, 'final', 0)’，而 ‘sys.version_info’ 则是
     ‘sys.version_info(2, 7, 2, 'final', 0)’。对于 CPython 而言两个值是
     相同的，因为它是参考实现。

     `hexversion' 是十六进制的实现版本，类似于 *note sys.hexversion:
     37d8.。

     `cache_tag' 是导入机制使用的标记，用于已缓存模块的文件名。按照惯例
     ，它将由实现的名称和版本组成，如 ‘'cpython-33'’。但如果合适，Python
     实现可以使用其他值。如果 ‘cache_tag’ 被置为 ‘None’，表示模块缓存已
     禁用。

     *note sys.implementation: a8b. 可能包含相应 Python 实现的其他属性。
     这些非标准属性必须以下划线开头，此处不详细阐述。无论其内容如何，
     *note sys.implementation: a8b. 在解释器运行期间或不同实现版本之间都
     不会更改。（但是不同 Python 语言版本间可能会不同。）详情请参阅 PEP
     421(8)。

     3.3 版新加入.

          備註: 新的必要属性的添加必须经过常规的 PEP 过程。详情请参阅
          PEP 421(9)。

 -- Data: sys.int_info

     一个 *note 具名元组: b7b.，包含 Python 内部整数表示形式的信息。这些
     属性是只读的。

     属性                          说明
                                   
     ---------------------------------------------------------------------------------
                                   
     ‘bits_per_digit’              每个数字占有的位数。Python 内部将整数存储在基底
                                   ‘2**int_info.bits_per_digit’
                                   
                                   
     ‘sizeof_digit’                用于表示数字的C类型的字节大小
                                   

     3.1 版新加入.

 -- Data: sys.__interactivehook__

     当本属性存在，则以 *note 交互模式: 9c9. 启动解释器时，将自动（不带
     参数地）调用本属性的值。该过程是在读取 *note PYTHONSTARTUP: 9cb. 文
     件之后完成的，所以可以在该文件中设置这一钩子。*note site: eb. 模块
     *note 设置了这一属性: 9cc.。

     引发一个 *note 审计事件: fa1. ‘cpython.run_interactivehook’，附带参
     数 ‘hook’。

     3.4 版新加入.

 -- 函式: sys.intern (string)

     将 `string' 插入 "interned" （驻留）字符串表，返回被插入的字符串 –
     它是 `string' 本身或副本。驻留字符串对提高字典查找的性能很有用 – 如
     果字典中的键已驻留，且所查找的键也已驻留，则键（取散列后）的比较可
     以用指针代替字符串来比较。通常，Python 程序使用到的名称会被自动驻留
     ，且用于保存模块、类或实例属性的字典的键也已驻留。

     驻留字符串不是永久存在的，对 *note intern(): d36. 返回值的引用必须
     保留下来，才能发挥驻留字符串的优势。

 -- 函式: sys.is_finalizing ()

     如果 Python 解释器 *note 正在关闭: 852. 则返回 *note True: 593.，否
     则返回 *note False: 48e.。

     3.5 版新加入.

 -- Data: sys.last_type
 -- Data: sys.last_value
 -- Data: sys.last_traceback

     这三个变量并非总是有定义，仅当有异常未处理，且解释器打印了错误消息
     和堆栈回溯时，才会给它们赋值。它们的预期用途，是允许交互中的用户导
     入调试器模块，进行事后调试，而不必重新运行导致错误的命令。（通常使
     用 ‘import pdb; pdb.pm()’ 进入事后调试器，详情请参阅 *note pdb: c9.
     模块。）

     这些变量的含义与上述 *note exc_info(): d27. 返回值的含义相同。

 -- Data: sys.maxsize

     一个整数，表示 ‘Py_ssize_t’ 类型的变量可以取到的最大值。在 32 位平
     台上通常为 ‘2**31 - 1’，在 64 位平台上通常为 ‘2**63 - 1’。

 -- Data: sys.maxunicode

     一个整数，表示最大的 Unicode 码点值，如 ‘1114111’ （十六进制为
     ‘0x10FFFF’ ）。

     3.3 版更變: 在 PEP 393(10) 之前，‘sys.maxunicode’ 曾是 ‘0xFFFF’ 或
     ‘0x10FFFF’，具体取决于配置选项，该选项指定将 Unicode 字符存储为
     UCS-2 还是 UCS-4。

 -- Data: sys.meta_path

     一个由 *note 元路径查找器: a91. 对象组成的列表，当查找需要导入的模
     块时，会调用这些对象的 *note find_spec(): 564. 方法，观察这些对象是
     否能找到所需模块。调用 *note find_spec(): 564. 方法最少需要传入待导
     入模块的绝对名称。如果待导入模块包含在一个包中，则父包的 *note
     __path__: 13c3. 属性将作为第二个参数被传入。该方法返回 *note
     模块规格: 37db.，找不到模块则返回 ‘None’。

     也參考
     ......

     *note importlib.abc.MetaPathFinder: a93.

          抽象基类，定义了 *note meta_path: 6dd. 内的查找器对象的接口。

     *note importlib.machinery.ModuleSpec: 1601.

          *note find_spec(): 564. 返回的实例所对应的具体类。

     3.4 版更變: 在 Python 3.4 中通过 PEP 451(11) 引入了 *note 模块规格:
     37db.。早期版本的 Python 会寻找一个称为 *note find_module(): 563. 的
     方法。如果某个 *note meta_path: 6dd. 条目没有 *note find_spec():
     564. 方法，就会回退去调用前一种方法。

 -- Data: sys.modules

     一个字典，将模块名称映射到已加载的模块。可以操作该字典来强制重新加
     载模块，或是实现其他技巧。但是，替换的字典不一定会按预期工作，并且
     从字典中删除必要的项目可能会导致 Python 崩溃。

 -- Data: sys.path

     一个由字符串组成的列表，用于指定模块的搜索路径。初始化自环境变量
     *note PYTHONPATH: a34.，再加上一条与安装有关的默认路径。

     程序启动时将初始化本列表，列表的第一项 ‘path[0]’ 目录含有调用
     Python 解释器的脚本。如果脚本目录不可用（比如以交互方式调用了解释器
     ，或脚本是从标准输入中读取的），则 ‘path[0]’ 为空字符串，这将导致
     Python 优先搜索当前目录中的模块。注意，脚本目录将插入在 *note
     PYTHONPATH: a34. 的条目*之前*。

     程序可以随意修改本列表用于自己的目的。只能向 *note sys.path: 261. 中
     添加 string 和 bytes 类型，其他数据类型将在导入期间被忽略。

     也參考
     ......

     *note site: eb. 模块，该模块描述了如何使用 .pth 文件来扩展 *note
     sys.path: 261.。

 -- Data: sys.path_hooks

     一个由可调用对象组成的列表，这些对象接受一个路径作为参数，并尝试为
     该路径创建一个 *note 查找器: 15f5.。如果成功创建查找器，则可调用对
     象将返回它，否则将引发 *note ImportError: 16c. 异常。

     本特性最早在 PEP 302(12) 中被提及。

 -- Data: sys.path_importer_cache

     一个字典，作为 *note 查找器: 15f5. 对象的缓存。key 是传入 *note
     sys.path_hooks: a3d. 的路径，value 是相应已找到的查找器。如果路径是
     有效的文件系统路径，但在 *note sys.path_hooks: a3d. 中未找到查找器
     ，则存入 ‘None’。

     本特性最早在 PEP 302(13) 中被提及。

     3.3 版更變: 未找到查找器时，改为存储 ‘None’，而不是 *note
     imp.NullImporter: a9b.。

 -- Data: sys.platform

     本字符串是一个平台标识符，举例而言，该标识符可用于将特定平台的组件
     追加到 *note sys.path: 261. 中。

     对于 Unix 系统（除 Linux 和 AIX 外），该字符串是 `Python 构建时的'
     ‘uname -s’ 返回的小写操作系统名称，并附加了 ‘uname -r’ 返回的系统版
     本的第一部分，如 ‘'sunos5'’ 或 ‘'freebsd8'’。除非需要检测特定版本的
     系统，否则建议使用以下习惯用法:

          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...

     对于其他系统，值是：

     系统                 ‘平台’ 值
                          
     -----------------------------------------------------
                          
     AIX                  ‘'aix'’
                          
                          
     Linux                ‘'linux'’
                          
                          
     Windows              ‘'win32'’
                          
                          
     Windows/Cygwin       ‘'cygwin'’
                          
                          
     macOS                ‘'darwin'’
                          

     3.3 版更變: 在 Linux 上，*note sys.platform: 3d3. 将不再包含副版本
     号。它将总是 ‘'linux'’ 而不是 ‘'linux2'’ 或 ‘'linux3'’。由于旧版本
     的 Python 会包含该版本号，因此推荐总是使用上述 ‘startswith’ 习惯用
     法。

     3.8 版更變: 在 AIX 上，*note sys.platform: 3d3. 将不再包含副版本号
     。它将总是 ‘'aix'’ 而不是 ‘'aix5'’ 或 ‘'aix7'’。由于旧版本的 Python
     会包含该版本号，因此推荐总是使用上述 ‘startswith’ 习惯用法。

     也參考
     ......

     *note os.name: 2040. 更加简略。*note os.uname(): b38. 提供系统的版
     本信息。

     *note platform: ce. 模块提供了对系统标识更详细的检查。

 -- Data: sys.platlibdir

     平台专用库目录。用于构建标准库的路径和已安装扩展模块的路径。

     在大多数平台上，它等同于 ‘"lib"’ 。在 Fedora 和 SuSE 上，它等同于给
     出了以下 ‘sys.path’ 路径的 64 位平台上的 ‘"lib64"’ （其中 ‘X.Y’ 是
     Python 的 ‘major.minor’ 版本）。

        * ‘/usr/lib64/pythonX.Y/’：标准库（如 *note os: c4. 模块的
          ‘os.py’ ）

        * ‘/usr/lib64/pythonX.Y/lib-dynload/’：标准库的 C 扩展模块（如
          *note errno: 7a. 模块，确切的文件名取决于平台）

        * ‘/usr/lib/pythonX.Y/site-packages/’ (请使用 ‘lib’, 而非 *note
          sys.platlibdir: 1e9.): 第三方模块

        * ‘/usr/lib64/pythonX.Y/site-packages/’: 第三方包的 C 扩展模块

     3.9 版新加入.

 -- Data: sys.prefix

     A string giving the site-specific directory prefix where the
     platform independent Python files are installed; on Unix, the
     default is ‘'/usr/local'’.  This can be set at build time with the
     ‘--prefix’ argument to the ‘configure’ script.  See *note 安装路径:
     37dc. for derived paths.

          備註: 如果在一个 *note 虚拟环境: 379e. 中，那么该值将在
          ‘site.py’ 中被修改，指向虚拟环境。Python 安装位置仍然可以用
          *note base_prefix: 3180. 来获取。

 -- Data: sys.ps1
 -- Data: sys.ps2

     字符串，指定解释器的首要和次要提示符。仅当解释器处于交互模式时，它
     们才有定义。这种情况下，它们的初值为 ‘'>>> '’ 和 ‘'... '’。如果赋给
     其中某个变量的是非字符串对象，则每次解释器准备读取新的交互式命令时
     ，都会重新运行该对象的 *note str(): 205.，这可以用来实现动态的提示
     符。

 -- 函式: sys.setdlopenflags (n)

     设置解释器在调用 ‘dlopen()’ 时用到的标志，例如解释器在加载扩展模块
     时。首先，调用 ‘sys.setdlopenflags(0)’ 将在导入模块时对符号启用惰性
     解析。要在扩展模块之间共享符号，请调用
     ‘sys.setdlopenflags(os.RTLD_GLOBAL)’。标志值的符号名称可以在 *note
     os: c4. 模块中找到（即 ‘RTLD_xxx’ 常量，如 *note os.RTLD_LAZY: b3a.
     ）。

     *note 可用性: 1491.: Unix。

 -- 函式: sys.setprofile (profilefunc)

     设置系统的性能分析函数，该函数使得在 Py​​thon 中能够实现一个 Python 源
     代码性能分析器。关于 Python Profiler 的更多信息请参阅 *note Python
     Profilers 分析器: 36fd. 章节。性能分析函数的调用方式类似于系统的跟
     踪函数（参阅 *note settrace(): f00. ），但它是通过不同的事件调用的
     ，例如，不是每执行一行代码就调用它一次（仅在调用某函数和从某函数返
     回时才会调用性能分析函数，但即使某函数发生异常也会算作返回事件）。
     该函数是特定于单个线程的，但是性能分析器无法得知线程之间的上下文切
     换，因此在存在多个线程的情况下使用它是没有意义的。另外，因为它的返
     回值不会被用到，所以可以简单地返回 ‘None’。性能分析函数中的错误将导
     致其自身被解除设置。

     性能分析函数应接收三个参数：`frame'、`event' 和 `arg'。`frame' 是当
     前的堆栈帧。`event' 是一个字符串：‘'call'’、‘'return'’、
     ‘'c_call'’、‘'c_return'’ 或 ‘'c_exception'’。`arg' 取决于事件类型。

     引发一个 *note 审计事件: fa1. ‘sys.setprofile’，不附带任何参数。

     这些事件具有以下含义：

     ‘'call'’

          表示调用了某个函数（或进入了其他的代码块）。性能分析函数将被调
          用，`arg' 为 ‘None’。

     ‘'return'’

          表示某个函数（或别的代码块）即将返回。性能分析函数将被调用，
          `arg' 是即将返回的值，如果此次返回事件是由于抛出异常，`arg' 为
          ‘None’。

     ‘'c_call'’

          表示即将调用某个 C 函数。它可能是扩展函数或是内建函数。`arg' 是
          C 函数对象。

     ‘'c_return'’

          表示返回了某个 C 函数。`arg' 是 C 函数对象。

     ‘'c_exception'’

          表示某个 C 函数抛出了异常。`arg' 是 C 函数对象。

 -- 函式: sys.setrecursionlimit (limit)

     将 Python 解释器堆栈的最大深度设置为 `limit'。此限制可防止无限递归
     导致的 C 堆栈溢出和 Python 崩溃。

     不同平台所允许的最高限值不同。当用户有需要深度递归的程序且平台支持
     更高的限值，可能就需要调高限值。进行该操作需要谨慎，因为过高的限值
     可能会导致崩溃。

     如果新的限值低于当前的递归深度，将抛出 *note RecursionError: 727. 异
     常。

     3.5.1 版更變: 如果新的限值低于当前的递归深度，现在将抛出 *note
     RecursionError: 727. 异常。

 -- 函式: sys.setswitchinterval (interval)

     设置解释器的线程切换间隔时间（单位为秒）。该浮点数决定了“时间片”的
     理想持续时间，时间片将分配给同时运行的 Python 线程。请注意，实际值
     可能更高，尤其是使用了运行时间长的内部函数或方法时。同时，在时间间
     隔末尾调度哪个线程是操作系统的决定。解释器没有自己的调度程序。

     3.2 版新加入.

 -- 函式: sys.settrace (tracefunc)

     设置系统的跟踪函数，使得用户在 Python 中就可以实现 Python 源代码调
     试器。该函数是特定于单个线程的，所以要让调试器支持多线程，必须为正
     在调试的每个线程都用 *note settrace(): f00. 注册一个跟踪函数，或使
     用 *note threading.settrace(): 24ab.。

     跟踪函数应接收三个参数：`frame'、`event' 和 `arg'。`frame' 是当前的
     堆栈帧。`event' 是一个字符串：‘'call'’、‘'line'’、‘'return'’、
     ‘'exception'’ 或 ‘'opcode'’。`arg' 取决于事件类型。

     每次进入 trace 函数的新的局部作用范围，都会调用 trace 函数（
     `event' 会被设置为 ‘'call'’ ），它应该返回一个引用，指向即将用在新
     作用范围上的局部跟踪函数；如果不需要跟踪当前的作用范围，则返回
     ‘None’。

     局部跟踪函数应返回对自身的引用（或对另一个函数的引用，用来在其作用
     范围内进行进一步的跟踪），或者返回 ‘None’ 来停止跟踪其作用范围。

     如果跟踪函数出错，则该跟踪函数将被取消设置，类似于调用
     ‘settrace(None)’。

     这些事件具有以下含义：

     ‘'call'’

          表示调用了某个函数（或进入了其他的代码块）。全局跟踪函数将被调
          用，`arg' 为 ‘None’。返回值将指定局部跟踪函数。

     ‘'line'’

          表示解释器即将执行新一行代码或重新执行循环条件。局部跟踪函数将
          被调用，`arg' 为 ‘None’，其返回值将指定新的局部跟踪函数。关于
          其工作原理的详细说明，请参见 ‘Objects/lnotab_notes.txt’。要在
          该堆栈帧禁用每行触发事件，可以在堆栈帧上将 ‘f_trace_lines’ 设
          置为 *note False: 48e.。

     ‘'return'’

          表示某个函数（或别的代码块）即将返回。局部跟踪函数将被调用，
          `arg' 是即将返回的值，如果此次返回事件是由于抛出异常，`arg' 为
          ‘None’。跟踪函数的返回值将被忽略。

     ‘'exception'’

          表示发生了某个异常。局部跟踪函数将被调用，`arg' 是一个
          ‘(exception, value, traceback)’ 元组，返回值将指定新的局部跟踪
          函数。

     ‘'opcode'’

          表示解释器即将执行一个新的操作码（操作码的详情请参阅 *note
          dis: 37. ）。局部跟踪函数将被调用，`arg' 为 ‘None’，其返回值将
          指定新的局部跟踪函数。每操作码触发事件默认情况下都不发出：必须
          在堆栈帧上将 ‘f_trace_opcodes’ 显式地设置为 *note True: 593. 来
          请求这些事件。

     注意，由于异常是在链式调用中传播的，所以每一级都会产生一个
     ‘'exception'’ 事件。

     更细微的用法是，可以显式地通过赋值 ‘frame.f_trace = tracefunc’ 来设
     置跟踪函数，而不是用现有跟踪函数的返回值去间接设置它。当前帧上的跟
     踪函数必须激活，而 *note settrace(): f00. 还没有做这件事。注意，为
     了使上述设置起效，必须使用 *note settrace(): f00. 来安装全局跟踪函
     数才能启用运行时跟踪机制，但是它不必与上述是同一个跟踪函数（它可以
     是一个开销很低的跟踪函数，只返回 ‘None’，即在各个帧上立即将其自身禁
     用）。

     关于代码对象和帧对象的更多信息请参考 *note 标准类型层级结构: 1553.。

     引发一个 *note 审计事件: fa1. ‘sys.settrace’，不附带任何参数。

     `CPython implementation detail:' *note settrace(): f00. 函数仅用于
     实现调试器，性能分析器，打包工具等。它的行为是实现平台的一部分，而
     不是语言定义的一部分，因此并非在所有 Python 实现中都可用。

     3.7 版更變: 添加了 ‘'opcode'’ 事件类型；为帧对象添加了
     ‘f_trace_lines’ 和 ‘f_trace_opcodes’ 属性

 -- 函式: sys.set_asyncgen_hooks (firstiter, finalizer)

     接受两个可选的关键字参数，要求它们是可调用对象，且接受一个 *note
     异步生成器迭代器: 37d7. 作为参数。`firstiter' 对象将在异步生成器第
     一次迭代时调用。`finalizer' 将在异步生成器即将被销毁时调用。

     引发一个 *note 审计事件: fa1. ‘sys.set_asyncgen_hooks_firstiter’，
     不附带任何参数。

     引发一个 *note 审计事件: fa1. ‘sys.set_asyncgen_hooks_finalizer’，
     不附带任何参数。

     之所以会引发两个审计事件，是因为底层的 API 由两个调用组成，每个调用
     都须要引发自己的事件。

     3.6 版新加入: 更多详情请参阅 PEP 525(14)，`finalizer' 方法的参考示
     例可参阅 Lib/asyncio/base_events.py(15) 中
     ‘asyncio.Loop.shutdown_asyncgens’ 的实现。

          備註: 本函数已添加至暂定软件包（详情请参阅 PEP 411(16) ）。

 -- 函式: sys.set_coroutine_origin_tracking_depth (depth)

     用于启用或禁用协程溯源。启用后，协程对象上的 ‘cr_origin’ 属性将包含
     一个元组，它由多个（文件名 filename，行号 line number，函数名
     function name）元组组成，整个元组描述出了协程对象创建过程的回溯，元
     组首端是最近一次的调用。禁用后，‘cr_origin’ 将为 None。

     要启用，请向 `depth' 传递一个大于零的值，它指定了有多少帧将被捕获信
     息。要禁用，请将 `depth' 置为零。

     该设置是特定于单个线程的。

     3.7 版新加入.

          備註: 本函数已添加至暂定软件包（详情请参阅 PEP 411(17) ）。仅
          将其用于调试目的。

 -- 函式: sys._enablelegacywindowsfsencoding ()

     将默认文件系统编码和错误处理方案分别更改为 ’mbcs’ 和 ’replace’，这
     是为了与 Python 3.6 前的版本保持一致。

     这等同于在启动 Python 前先定义好 *note
     PYTHONLEGACYWINDOWSFSENCODING: 5f0. 环境变量。

     *note 可用性: 1491.: Windows。

     3.6 版新加入: 更多详情请参阅 PEP 529(18)。

 -- Data: sys.stdin
 -- Data: sys.stdout
 -- Data: sys.stderr

     解释器用于标准输入、标准输出和标准错误的 *note 文件对象: c14.：

        * ‘stdin’ 用于所有交互式输入（包括对 *note input(): d33. 的调用
          ）；

        * ‘stdout’ 用于 *note print(): 971. 和 *note expression: 158f. 语
          句的输出，以及用于 *note input(): d33. 的提示符；

        * 解释器自身的提示符和它的错误消息都发往 ‘stderr’。

     这些流都是常规 *note 文本文件: 13d9.，与 *note open(): 16f. 函数返
     回的对象一致。它们的参数选择如下：

        * 字符编码取决于各个平台。在非 Windows 平台上使用的是语言环境
          (locale) 编码（可参阅 *note locale.getpreferredencoding():
          4ab. ）。

          在 Windows 上，控制台设备使用 UTF-8 编码。非字符设备（如磁盘文
          件和管道）使用系统语言环境编码（即 ANSI 代码页）。非控制台字符
          设备（即 ‘isatty()’ 返回的是 ‘True’，如 NUL）在启动时，会把控
          制台输入代码页和输出代码页的值分别用于 stdin 和 stdout/stderr。
          如果进程原本没有附加到控制台，则默认为系统语言环境编码。

          要重写控制台的特殊行为，可以在启动 Python 前设置
          PYTHONLEGACYWINDOWSSTDIO 环境变量。此时，控制台代码页将用于其
          他字符设备。

          在所有平台上，都可以通过在 Python 启动前设置 *note
          PYTHONIOENCODING: a14. 环境变量来重写字符编码，或通过新的
          *note -X: 290. ‘utf8’ 命令行选项和 *note PYTHONUTF8: 421. 环境
          变量来设置。但是，对 Windows 控制台来说，上述方法仅在设置了
          *note PYTHONLEGACYWINDOWSSTDIO: 5f3. 后才起效。

        * 交互模式下，‘stdout’ 流是行缓冲的。其他情况下，它像常规文本文
          件一样是块缓冲的。两种情况下的 ‘stderr’ 流都是行缓冲的。要使得
          两个流都变成无缓冲，可以传入 *note -u: 109d. 命令行选项或设置
          *note PYTHONUNBUFFERED: 109e. 环境变量。

     3.9 版更變: 非交互模式下，‘stderr’ 现在是行缓冲的，而不是全缓冲的。

          備註: 要从标准流写入或读取二进制数据，请使用底层二进制 *note
          buffer: d02. 对象。例如，要将字节写入 *note stdout: 41f.，请使
          用 ‘sys.stdout.buffer.write(b'abc')’。

          但是，如果你在写一个库（并且不限制执行库代码时的上下文），那么
          请注意，标准流可能会被替换为文件类对象，如 *note io.StringIO:
          91a.，它们是不支持 ‘buffer’ 属性的。

 -- Data: sys.__stdin__
 -- Data: sys.__stdout__
 -- Data: sys.__stderr__

     程序开始时，这些对象存有 ‘stdin’、‘stderr’ 和 ‘stdout’ 的初始值。它
     们在程序结束前都可以使用，且在需要向实际的标准流打印内容时很有用，
     无论 ‘sys.std*’ 对象是否已重定向。

     如果实际文件已经被覆盖成一个损坏的对象了，那它也可用于将实际文件还
     原成能正常工作的文件对象。但是，本过程的最佳方法应该是，在原来的流
     被替换之前就显式地保存它，并使用这一保存的对象来还原。

          備註: 某些情况下的 ‘stdin’、‘stdout’ 和 ‘stderr’ 以及初始值
          ‘__stdin__’、‘__stdout__’ 和 ‘__stderr__’ 可以是 ‘None’。通常
          发生在未连接到控制台的 Windows GUI app 中，以及在用 ‘pythonw’
          启动的 Python app 中。

 -- Data: sys.thread_info

     一个 *note 具名元组: b7b.，包含线程实现的信息。

     属性                   说明
                            
     -------------------------------------------------------------------------------------
                            
     ‘name’                 线程实现的名称：
                            
                                    * ‘'nt'’: Windows 线程
                            
                                    * ‘'pthread'’: POSIX 线程
                            
                                    * ‘'solaris'’: Solaris 线程
                            
                            
     ‘lock’                 锁实现的名称：
                            
                                    * ‘'semaphore'’: 锁使用信号量
                            
                                    * ‘'mutex+cond'’: 锁使用互斥和条件变量
                            
                                    * ‘None’ 如果此信息未知
                            
                            
     *note version: 6ca.    线程库的名称和版本。它是一个字符串，如果此信息未知，则为
                            ‘None’ 。
                            

     3.3 版新加入.

 -- Data: sys.tracebacklimit

     当该变量值设置为整数，在发生未处理的异常时，它将决定打印的回溯信息
     的最大层级数。默认为 ‘1000’。当将其设置为 ‘0’ 或小于 0，将关闭所有
     回溯信息，并且只打印异常类型和异常值。

 -- 函式: sys.unraisablehook (unraisable, /)

     处理一个无法抛出的异常。

     它会在发生了一个异常但 Python 没有办法处理时被调用。例如，当一个析
     构器引发了异常，或在垃圾回收 (*note gc.collect(): 35b.) 期间引发了
     异常。

     `unraisable' 参数具有以下属性:

        * `exc_type': 异常类型

        * `exc_value': 异常值，可以是 ‘None’.

        * `exc_traceback': 异常回溯，可以是 ‘None’.

        * `err_msg': 错误信息，可以是 ‘None’.

        * `object': 导致异常的对象，可以为 ‘None’.

     默认的钩子程序会将 `err_msg' 和 `object' 格式化为： ‘f'{err_msg}:
     {object!r}'’；如果 `err_msg' 为 ‘None’ 则采用 "Exception ignored
     in" 错误信息。

     要改变无法抛出的异常的处理过程，可以重写 *note
     sys.unraisablehook(): 35a.。

     使用定制钩子存放 `exc_value' 可能会创建引用循环。 它应当在不再需要
     异常时被显式地清空以打破引用循环。

     如果一个 `object' 正在被销毁，那么使用自定义的钩子储存该对象可能会
     将其复活。请在自定义钩子生效后避免储存 `object'，以避免对象的复活。

     另请参阅 *note excepthook(): f24.，它处理未捕获的异常。

     引发一个审计事件 ‘sys.unraisablehook’ 并附带参数 ‘hook’,
     ‘unraisable’。

     3.8 版新加入.

 -- Data: sys.version

     一个包含 Python 解释器版本号加编译版本号以及所用编译器等额外信息的
     字符串。 此字符串会在交互式解释器启动时显示。 请不要从中提取版本信
     息，而应当使用 *note version_info: bed. 以及 *note platform: ce. 模
     块所提供的函数。

 -- Data: sys.api_version

     这个解释器的 C API 版本。当你在调试 Python及期扩展模板的版本冲突这
     个功能非常有用。

 -- Data: sys.version_info

     一个包含版本号五部分的元组: `major', `minor', `micro',
     `releaselevel' 和 `serial'。 除 `releaselevel' 外的所有值均为整数；
     发布级别值则为 ‘'alpha'’, ‘'beta'’, ‘'candidate'’ 或 ‘'final'’。 对
     应于 Python 版本 2.0 的 ‘version_info’ 值为 ‘(2, 0, 0, 'final',
     0)’。 这些部分也可按名称访问，因此 ‘sys.version_info[0]’ 就等价于
     ‘sys.version_info.major’，依此类推。

     3.1 版更變: 增加了以名称表示的各部分属性。

 -- Data: sys.warnoptions

     这是警告框架的一个实现细节；请不要修改此值。 有关警告框架的更多信息
     请参阅 *note warnings: 12f. 模块。

 -- Data: sys.winver

     用于在 Windows 平台上组成注册表键的版本号。 这在 Python DLL 中存储
     为 1000 号字符串资源。 其值通常是 *note version: 6ca. 的头三个字符
     。 它在 *note sys: fd. 模块中提供是为了信息展示目的；修改此值不会影
     响 Python 所使用的注册表键。

     *note 可用性: 1491.: Windows。

 -- Data: sys._xoptions

     一个字典，包含通过 *note -X: 290. 命令行选项传递的旗标，这些旗标专
     属于各种具体实现。选项名称将会映射到对应的值（如果显式指定）或者
     *note True: 593.。例如:

          $ ./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}

     `CPython implementation detail:' 这是 CPython 专属的访问通过 *note
     -X: 290. 传递的选项的方式。 其他实现可能会通过其他方式导出它们，或
     者完全不导出。

     3.2 版新加入.

引用
....

(C99) ISO/IEC 9899:1999.  "Programming languages – C." 该标准的公开草案
可从 ‘http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf’获得。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3149

   (2) https://www.python.org/dev/peps/pep-0578

   (3) https://www.python.org/dev/peps/pep-0529

   (4) https://code.activestate.com/recipes/577504

   (5) https://www.python.org/dev/peps/pep-0525

   (6) https://www.python.org/dev/peps/pep-0411

   (7) https://www.python.org/dev/peps/pep-0411

   (8) https://www.python.org/dev/peps/pep-0421

   (9) https://www.python.org/dev/peps/pep-0421

   (10) https://www.python.org/dev/peps/pep-0393

   (11) https://www.python.org/dev/peps/pep-0451

   (12) https://www.python.org/dev/peps/pep-0302

   (13) https://www.python.org/dev/peps/pep-0302

   (14) https://www.python.org/dev/peps/pep-0525

   (15) 
https://github.com/python/cpython/tree/3.9/Lib/asyncio/base_events.py

   (16) https://www.python.org/dev/peps/pep-0411

   (17) https://www.python.org/dev/peps/pep-0411

   (18) https://www.python.org/dev/peps/pep-0529


File: python.info,  Node: sysconfig --- Provide access to Python's configuration information,  Next: builtins --- 内建对象,  Prev: sys --- 系统相关的参数和函数,  Up: Python运行时服务

5.29.2 ‘sysconfig’ — Provide access to Python’s configuration information
-------------------------------------------------------------------------

3.2 版新加入.

`源代码：' Lib/sysconfig.py(1)

__________________________________________________________________

The *note sysconfig: fe. module provides access to Python’s
configuration information like the list of installation paths and the
configuration variables relevant for the current platform.

* Menu:

* 配置变量::
* 安装路径::
* 其他功能: 其他功能<2>.
* Using sysconfig as a script::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/sysconfig.py


File: python.info,  Node: 配置变量,  Next: 安装路径,  Up: sysconfig --- Provide access to Python's configuration information

5.29.2.1 配置变量
.................

A Python distribution contains a ‘Makefile’ and a ‘pyconfig.h’ header
file that are necessary to build both the Python binary itself and
third-party C extensions compiled using *note distutils: 38.

*note sysconfig: fe. puts all variables found in these files in a
dictionary that can be accessed using *note get_config_vars(): a46. or
*note get_config_var(): a45.

Notice that on Windows, it’s a much smaller set.

 -- 函式: sysconfig.get_config_vars (*args)

     With no arguments, return a dictionary of all configuration
     variables relevant for the current platform.

     With arguments, return a list of values that result from looking up
     each argument in the configuration variable dictionary.

     For each argument, if the value is not found, return ‘None’.

 -- 函式: sysconfig.get_config_var (name)

     Return the value of a single variable `name'.  Equivalent to
     ‘get_config_vars().get(name)’.

     If `name' is not found, return ‘None’.

用法示例:

     >>> 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++']


File: python.info,  Node: 安装路径,  Next: 其他功能<2>,  Prev: 配置变量,  Up: sysconfig --- Provide access to Python's configuration information

5.29.2.2 安装路径
.................

Python uses an installation scheme that differs depending on the
platform and on the installation options.  These schemes are stored in
*note sysconfig: fe. under unique identifiers based on the value
returned by *note os.name: 2040.

Every new component that is installed using *note distutils: 38. or a
Distutils-based system will follow the same scheme to copy its file in
the right places.

Python currently supports six schemes:

   - `posix_prefix': scheme for POSIX platforms like Linux or macOS.
     This is the default scheme used when Python or a component is
     installed.

   - `posix_home': scheme for POSIX platforms used when a `home' option
     is used upon installation.  This scheme is used when a component is
     installed through Distutils with a specific home prefix.

   - `posix_user': scheme for POSIX platforms used when a component is
     installed through Distutils and the `user' option is used.  This
     scheme defines paths located under the user home directory.

   - `nt': scheme for NT platforms like Windows.

   - `nt_user': scheme for NT platforms, when the `user' option is used.

   - `osx_framework_user': scheme for macOS, when the `user' option is
     used.

Each scheme is itself composed of a series of paths and each path has a
unique identifier.  Python currently uses eight paths:

   - `stdlib': directory containing the standard Python library files
     that are not platform-specific.

   - `platstdlib': directory containing the standard Python library
     files that are platform-specific.

   - `platlib': directory for site-specific, platform-specific files.

   - `purelib': directory for site-specific, non-platform-specific
     files.

   - `include': directory for non-platform-specific header files.

   - `platinclude': directory for platform-specific header files.

   - `scripts': directory for script files.

   - `data': directory for data files.

*note sysconfig: fe. provides some functions to determine these paths.

 -- 函式: sysconfig.get_scheme_names ()

     Return a tuple containing all schemes currently supported in *note
     sysconfig: fe.

 -- 函式: sysconfig.get_path_names ()

     Return a tuple containing all path names currently supported in
     *note sysconfig: fe.

 -- 函式: sysconfig.get_path (name[, scheme[, vars[, expand]]])

     Return an installation path corresponding to the path `name', from
     the install scheme named `scheme'.

     `name' has to be a value from the list returned by *note
     get_path_names(): 37e6.

     *note sysconfig: fe. stores installation paths corresponding to
     each path name, for each platform, with variables to be expanded.
     For instance the `stdlib' path for the `nt' scheme is:
     ‘{base}/Lib’.

     *note get_path(): d86. will use the variables returned by *note
     get_config_vars(): a46. to expand the path.  All variables have
     default values for each platform so one may call this function and
     get the default value.

     If `scheme' is provided, it must be a value from the list returned
     by *note get_scheme_names(): 37e5.  Otherwise, the default scheme
     for the current platform is used.

     If `vars' is provided, it must be a dictionary of variables that
     will update the dictionary return by *note get_config_vars(): a46.

     If `expand' is set to ‘False’, the path will not be expanded using
     the variables.

     If `name' is not found, raise a *note KeyError: 3e9.

 -- 函式: sysconfig.get_paths ([scheme[, vars[, expand]]])

     Return a dictionary containing all installation paths corresponding
     to an installation scheme.  See *note get_path(): d86. for more
     information.

     If `scheme' is not provided, will use the default scheme for the
     current platform.

     If `vars' is provided, it must be a dictionary of variables that
     will update the dictionary used to expand the paths.

     If `expand' is set to false, the paths will not be expanded.

     If `scheme' is not an existing scheme, *note get_paths(): ca7. will
     raise a *note KeyError: 3e9.


File: python.info,  Node: 其他功能<2>,  Next: Using sysconfig as a script,  Prev: 安装路径,  Up: sysconfig --- Provide access to Python's configuration information

5.29.2.3 其他功能
.................

 -- 函式: sysconfig.get_python_version ()

     Return the ‘MAJOR.MINOR’ Python version number as a string.
     Similar to ‘'%d.%d' % sys.version_info[:2]’.

 -- 函式: sysconfig.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.

     返回值的示例：

        - linux-i586

        - linux-alpha (?)

        - solaris-2.6-sun4u

     Windows将返回以下之一：

        - win-amd64 (在 AMD64, aka x86_64, Intel64, 和 EM64T上的64位
          Windows )

        - win32 (all others - specifically, sys.platform is returned)

     macOS can return:

        - macosx-10.6-ppc

        - macosx-10.4-ppc64

        - macosx-10.3-i386

        - macosx-10.4-fat

     对于其他非-POSIX 平台， 目前只是返回 *note sys.platform: 3d3. 。

 -- 函式: sysconfig.is_python_build ()

     Return ‘True’ if the running Python interpreter was built from
     source and is being run from its built location, and not from a
     location resulting from e.g.  running ‘make install’ or installing
     via a binary installer.

 -- 函式: sysconfig.parse_config_h (fp[, vars])

     Parse a ‘config.h’-style file.

     `fp' is a file-like object pointing to the ‘config.h’-like file.

     A dictionary containing name/value pairs is returned.  If an
     optional dictionary is passed in as the second argument, it is used
     instead of a new dictionary, and updated with the values read in
     the file.

 -- 函式: sysconfig.get_config_h_filename ()

     返回 ‘pyconfig.h’ 的目录

 -- 函式: sysconfig.get_makefile_filename ()

     返回 ‘Makefile’ 的目录


File: python.info,  Node: Using sysconfig as a script,  Prev: 其他功能<2>,  Up: sysconfig --- Provide access to Python's configuration information

5.29.2.4 Using ‘sysconfig’ as a script
......................................

You can use *note sysconfig: fe. as a script with Python’s `-m' option:

     $ 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"
             ...

This call will print in the standard output the information returned by
*note get_platform(): ca5, *note get_python_version(): ca6, *note
get_path(): d86. and *note get_config_vars(): a46.


File: python.info,  Node: builtins --- 内建对象,  Next: __main__ --- 顶层脚本环境,  Prev: sysconfig --- Provide access to Python's configuration information,  Up: Python运行时服务

5.29.3 ‘builtins’ — 内建对象
----------------------------

__________________________________________________________________

该模块提供对Python的所有“内置”标识符的直接访问；例如，‘builtins.open’ 是
内置函数的全名 *note open(): 16f. 。请参阅 *note 內建函式: cbe. 和 *note
內建常數: 173f. 的文档。

大多数应用程序通常不会显式访问此模块，但在提供与内置值同名的对象的模块中
可能很有用，但其中还需要内置该名称。例如，在一个想要实现 *note open():
16f. 函数的模块中，它包装了内置的 *note open(): 16f. ，这个模块可以直接
使用:

     import builtins

     def open(path):
         f = builtins.open(path, 'r')
         return UpperCaser(f)

     class UpperCaser:
         '''Wrapper around a file that converts output to upper-case.'''

         def __init__(self, f):
             self._f = f

         def read(self, count=-1):
             return self._f.read(count).upper()

         # ...

作为一个实现细节，大多数模块都将名称 ‘__builtins__’ 作为其全局变量的一部
分提供。 ‘__builtins__’ 的值通常是这个模块或者这个模块的值 *note
__dict__: 5f5. 属性。由于这是一个实现细节，因此 Python 的替代实现可能不
会使用它。


File: python.info,  Node: __main__ --- 顶层脚本环境,  Next: warnings —— 警告信息的控制,  Prev: builtins --- 内建对象,  Up: Python运行时服务

5.29.4 ‘__main__’ — 顶层脚本环境
--------------------------------

__________________________________________________________________

‘'__main__'’ 是顶层代码执行的作用域的名称。模块的 __name__ 在通过标准输
入、脚本文件或是交互式命令读入的时候会等于 ‘'__main__'’。

模块可以通过检查自己的 ‘__name__’ 来得知是否运行在 main 作用域中，这使得
模块可以在作为脚本或是通过 ‘python -m’ 运行时条件性地执行一些代码，而在
被 import 时不会执行。

     if __name__ == "__main__":
         # execute only if run as a script
         main()

对软件包来说，通过加入 ‘__main__.py’ 模块可以达到同样的效果，当使用 ‘-m’
运行模块时，其中的代码会被执行。


File: python.info,  Node: warnings —— 警告信息的控制,  Next: dataclasses --- 数据类,  Prev: __main__ --- 顶层脚本环境,  Up: Python运行时服务

5.29.5 ‘warnings’ —— 警告信息的控制
-----------------------------------

`源代码：' Lib/warnings.py(1)

__________________________________________________________________

通常以下情况会引发警告：提醒用户注意程序中的某些情况，而这些情况（通常）
还不值得触发异常并终止程序。例如，当程序用到了某个过时的模块时，就可能需
要发出一条警告。

Python 程序员可调用本模块中定义的 *note warn(): f1a. 函数来发布警告。（C
语言程序员则用 *note PyErr_WarnEx(): e76. ； 详见 *note 例外處理: 37f2.
）。

警告信息通常会写入 *note sys.stderr: 1ea. ，但可以灵活改变，从忽略所有警
告到变成异常都可以。警告的处理方式可以依据 *note 警告类型: 185f. 、警告
信息的文本和发出警告的源位置而进行变化。同一源位置重复出现的警告通常会被
抑制。

控制警告信息有两个阶段：首先，每次引发警告时，决定信息是否要发出；然后，
如果要发出信息，就用可由用户设置的钩子进行格式化并打印输出。

*note 警告过滤器: 15d. 控制着是否发出警告信息，也即一系列的匹配规则和动
作。调用 *note filterwarnings(): eca. 可将规则加入过滤器，调用 *note
resetwarnings(): 37f3. 则可重置为默认状态。

警告信息的打印输出是通过调用 *note showwarning(): 37f4. 完成的，该函数可
被重写；默认的实现代码是调用 *note formatwarning(): 112d. 进行格式化，自
己编写的代码也可以调用此格式化函数。

也參考
......

利用 *note logging.captureWarnings(): 2228. 可以采用标准的日志部件处理所
有警告。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/warnings.py


File: python.info,  Node: 警告类别,  Next: 警告过滤器,  Up: warnings —— 警告信息的控制

5.29.5.1 警告类别
.................

警告的类别由一些内置的异常表示。这种分类有助于对警告信息进行分组过滤。

虽然在技术上警告类别属于 *note 内置异常: 185d.，但也只是在此记录一下而已
，因为在概念上他们属于警告机制的一部分。

通过对某个标准的警告类别进行派生，用户代码可以定义其他的警告类别。 警告
类别必须是 *note Warning: 1860. 类的子类。

目前已定义了以下警告类别的类：

类                                     描述
                                       
-------------------------------------------------------------------------------------------
                                       
*note Warning: 1860.                   这是所有警告类别的基类。它是
                                       *note Exception: 2dc. 的子类。
                                       
                                       
*note UserWarning: 1861.               The default category for *note warn(): f1a.
                                       
                                       
*note DeprecationWarning: 15a.         已废弃特性警告的基类，这些警告是为其他 Python 开
                                       发者准备的（默认会忽略，除非在 ‘__main__’ 中用代
                                       码触发）。
                                       
                                       
*note SyntaxWarning: 2c9.              用于警告可疑语法的基类。
                                       
                                       
*note RuntimeWarning: 3e2.             用于警告可疑运行时特性的基类
                                       
                                       
*note FutureWarning: 435.              用于警告已废弃特性的基类，这些警告是为 Python 应
                                       用程序的最终用户准备的。
                                       
                                       
*note PendingDeprecationWarning: 15c.  用于警告即将废弃功能的基类（默认忽略）。
                                       
                                       
*note ImportWarning: 6cf.              导入模块时触发的警告的基类（默认忽略）。
                                       
                                       
*note UnicodeWarning: e4c.             用于 Unicode 相关警告的基类。
                                       
                                       
*note BytesWarning: 5af.               *note bytes: 172. 和 *note bytearray: 173. 相关警
                                       告的基类
                                       
                                       
*note ResourceWarning: 5ca.            Base category for warnings related to resource
                                       usage (ignored by default).
                                       

3.7 版更變: 以前 *note DeprecationWarning: 15a. 和 *note FutureWarning:
435. 是根据某个功能是否完全删除或改变其行为来区分的。现在是根据受众和默
认警告过滤器的处理方式来区分的。


File: python.info,  Node: 警告过滤器,  Next: 暂时禁止警告,  Prev: 警告类别,  Up: warnings —— 警告信息的控制

5.29.5.2 警告过滤器
...................

警告过滤器控制着警告是否被忽略、显示或转为错误（触发异常）。

从概念上讲，警告过滤器维护着一个经过排序的过滤器类别列表；任何具体的警告
都会依次与列表中的每种过滤器进行匹配，直到找到一个匹配项；过滤器决定了匹
配项的处理方式。每个列表项均为 ( `action' , `message' , `category' ,
`module' , `lineno' ) 格式的元组，其中：

   * `action' 是以下字符串之一：

     值                  处置
                         
     -----------------------------------------------------------------------
                         
     ‘"default"’         为发出警告的每个位置（模块+行号）打印第一个匹配
                         警告
                         
                         
     ‘"error"’           将匹配警告转换为异常
                         
                         
     ‘"ignore"’          从不打印匹配的警告
                         
                         
     ‘"always"’          总是打印匹配的警告
                         
                         
     ‘"module"’          为发出警告的每个模块打印第一次匹配警告（无论行号
                         如何）
                         
                         
     ‘"once"’            无论位置如何，仅打印第一次出现的匹配警告
                         

   * `message' 是包含正则表达式的字符串，警告信息的开头必须与之匹配。该
     表达式编译时不区分大小写。

   * `category' 是警告类别的类（*note Warning: 1860. 的子类），警告类别
     必须是其子类，才能匹配。

   * `module' 是个字符串，包含了模块名称必须匹配的正则表达式。该表达式编
     译时大小写敏感。

   * `lineno' 是个整数，发生警告的行号必须与之匹配，或与所有行号匹配。

由于 *note Warning: 1860. 类是由内置类 *note Exception: 2dc. 派生出来的
，要把某个警告变成错误，只要触发‘‘category(message)‘‘ 即可。

如果警告不匹配所有已注册的过滤器，那就会应用 “default” 动作（正如其名）
。

* Menu:

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


File: python.info,  Node: 警告过滤器的介绍,  Next: 默认警告过滤器,  Up: 警告过滤器

5.29.5.3 警告过滤器的介绍
.........................

警告过滤器由传给 Python 解释器的命令行 *note -W: 15b. 选项和 *note
PYTHONWARNINGS: 51b. 环境变量初始化。解释器在 ‘sys.warningoptions’ 中保
存了所有给出的参数，但不作解释；*note warnings: 12f. 模块在第一次导入时
会解析这些参数（无效的选项被忽略，并会先向 *note sys.stderr: 1ea. 打印一
条信息）。

每个警告过滤器的设定格式为冒号分隔的字段序列：

     action:message:category:module:line

这些字段的含义在 *note 警告过滤器: 15d. 中描述。当一行中列出多个过滤器时
（如 *note PYTHONWARNINGS: 51b.），过滤器间用逗号隔开，后面的优先于前面
的（因为是从左到右应用的，最近应用的过滤器优先于前面的）。

常用的警告过滤器适用于所有的警告、特定类别的警告、由特定模块和包引发的警
告。下面是一些例子：

     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"


File: python.info,  Node: 默认警告过滤器,  Next: 重写默认的过滤器,  Prev: 警告过滤器的介绍,  Up: 警告过滤器

5.29.5.4 默认警告过滤器
.......................

Python 默认安装了几个警告过滤器，可以通过 *note -W: 15b. 命令行参数、
*note PYTHONWARNINGS: 51b. 环境变量及调用 *note filterwarnings(): eca. 进
行覆盖。

在常规发布的版本中，默认的警告过滤器包括（按优先顺序排列）：

     default::DeprecationWarning:__main__
     ignore::DeprecationWarning
     ignore::PendingDeprecationWarning
     ignore::ImportWarning
     ignore::ResourceWarning

在调试版本中，默认警告过滤器的列表是空的。

3.2 版更變: 除了 *note PendingDeprecationWarning: 15c. 之外，*note
DeprecationWarning: 15a. 现在默认会被忽略。

3.7 版更變: *note DeprecationWarning: 15a. 在被 ‘__main__’ 中的代码直接
触发时，默认会再次显示。

3.7 版更變: 如果指定两次 *note -b: 519.，则 *note BytesWarning: 5af. 不
再出现在默认的过滤器列表中，而是通过 ‘sys.warningoptions’ 进行配置。


File: python.info,  Node: 重写默认的过滤器,  Prev: 默认警告过滤器,  Up: 警告过滤器

5.29.5.5 重写默认的过滤器
.........................

Python 应用程序的开发人员可能希望在默认情况下向用户隐藏 `所有' Python级
别的警告，而只在运行测试或其他调试时显示这些警告。用于向解释器传递过滤器
配置的 ‘sys.warningoptions’ 属性可以作为一个标记，表示是否应该禁用警告：

     import sys

     if not sys.warnoptions:
         import warnings
         warnings.simplefilter("ignore")

建议 Python 代码测试的开发者使用如下代码，以确保被测代码默认显示 `所有'
警告：

     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

最后，建议在 ‘__main__’ 以外的命名空间运行用户代码的交互式开发者，请确保
*note DeprecationWarning: 15a. 在默认情况下是可见的，可采用如下代码（这
里 ‘user_ns’ 是用于执行交互式输入代码的模块）：

     import warnings
     warnings.filterwarnings("default", category=DeprecationWarning,
                                        module=user_ns.get("__name__"))


File: python.info,  Node: 暂时禁止警告,  Next: 测试警告,  Prev: 警告过滤器,  Up: warnings —— 警告信息的控制

5.29.5.6 暂时禁止警告
.....................

如果明知正在使用会引起警告的代码，比如某个废弃函数，但不想看到警告（即便
警告已经通过命令行作了显式配置），那么可以使用 *note catch_warnings:
35f9. 上下文管理器来抑制警告。

     import warnings

     def fxn():
         warnings.warn("deprecated", DeprecationWarning)

     with warnings.catch_warnings():
         warnings.simplefilter("ignore")
         fxn()

在上下文管理器中，所有的警告将被简单地忽略。这样就能使用已知的过时代码而
又不必看到警告，同时也不会限制警告其他可能不知过时的代码。注意：只能保证
在单线程应用程序中生效。如果两个以上的线程同时使用 *note catch_warnings:
35f9. 上下文管理器，行为不可预知。


File: python.info,  Node: 测试警告,  Next: 为新版本的依赖关系更新代码,  Prev: 暂时禁止警告,  Up: warnings —— 警告信息的控制

5.29.5.7 测试警告
.................

要测试由代码引发的警告，请采用 *note catch_warnings: 35f9. 上下文管理器
。有了它，就可以临时改变警告过滤器以方便测试。例如，以下代码可捕获所有的
警告以便查看：

     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)

也可以用 ‘error’ 取代 ‘always’ ，让所有的警告都成为异常。需要注意的是，
如果某条警告已经因为 ‘once’ / ‘default’ 规则而被引发，那么无论设置什么过
滤器，该条警告都不会再出现，除非该警告有关的注册数据被清除。

一旦上下文管理器退出，警告过滤器将恢复到刚进此上下文时的状态。这样在多次
测试时可防止意外改变警告过滤器，从而导致不确定的测试结果。模块中的 *note
showwarning(): 37f4. 函数也被恢复到初始值。注意：这只能在单线程应用程序
中得到保证。如果两个以上的线程同时使用 *note catch_warnings: 35f9. 上下
文管理器，行为未定义。

当测试多项操作会引发同类警告时，重点是要确保每次操作都会触发新的警告（比
如，将警告设置为异常并检查操作是否触发异常，检查每次操作后警告列表的长度
是否有增加，否则就在每次新操作前将以前的警告列表项删除）。


File: python.info,  Node: 为新版本的依赖关系更新代码,  Next: 可用的函数,  Prev: 测试警告,  Up: warnings —— 警告信息的控制

5.29.5.8 为新版本的依赖关系更新代码
...................................

在默认情况下，主要针对 Python 开发者（而不是 Python 应用程序的最终用户）
的警告类别，会被忽略。

值得注意的是，这个“默认忽略”的列表包含 *note DeprecationWarning: 15a. （
适用于每个模块，除了 ‘__main__’），这意味着开发人员应该确保在测试代码时
应将通常忽略的警告显示出来，以便未来破坏性 API 变化时及时收到通知（无论
是在标准库还是第三方包）。

理想情况下，代码会有一个合适的测试套件，在运行测试时会隐含地启用所有警告
（由 *note unittest: 124. 模块提供的测试运行程序就是如此）。

在不太理想的情况下，可以通过向 Python 解释器传入 *note -Wd: 15b. (这是
‘-W default’ 的简写) 或设置环境变量 ‘PYTHONWARNINGS=default’ 来检查应用
程序是否用到了已弃用的接口。 这样可以启用对所有警告的默认处理操作，包括
那些默认忽略的警告。 要改变遇到警告后执行的动作，可以改变传给 *note -W:
15b. 的参数 (例如 ‘-W error’)。 请参阅 *note -W: 15b. 旗标来了解更多的细
节。


File: python.info,  Node: 可用的函数,  Next: 可用的上下文管理器,  Prev: 为新版本的依赖关系更新代码,  Up: warnings —— 警告信息的控制

5.29.5.9 可用的函数
...................

 -- 函式: warnings.warn (message, category=None, stacklevel=1,
          source=None)

     引发警告、忽略或者触发异常。 如果给出 `category' 参数，则必须是
     *note 警告类别类: 185f. ；默认为 *note UserWarning: 1861.。 或者
     `message' 可为 *note Warning: 1860. 的实例，这时 `category' 将被忽
     略，转而采用 ‘message.__class__’。 在这种情况下，错误信息文本将是
     ‘str(message)’。 如果某条警告被 *note 警告过滤器: 15d. 改成了错误，
     本函数将触发一条异常。 参数 `stacklevel' 可供 Python 包装函数使用，
     比如:

          def deprecation(message):
              warnings.warn(message, DeprecationWarning, stacklevel=2)

     这会让警告指向 ‘deprecation()’ 的调用者，而不是 ‘deprecation()’ 本
     身的来源（因为后者会破坏引发警告的目的）。

     `source' 是发出 *note ResourceWarning: 5ca. 的被销毁对象。

     3.6 版更變: 加入 `source'  参数。

 -- 函式: warnings.warn_explicit (message, category, filename, lineno,
          module=None, registry=None, module_globals=None, source=None)

     这是 *note warn(): f1a. 函数的底层接口，显式传入消息、类别、文件名
     和行号，以及可选的模块名和注册表（应为模块的 ‘__warningregistry__’
     字典）。 模块名称默认为去除了 ‘.py’ 的文件名；如果未传递注册表，警
     告就不会被抑制。 `message' 必须是个字符串，`category' 是 *note
     Warning: 1860. 的子类；或者*message* 可为 *note Warning: 1860. 的实
     例，且 `category' 将被忽略。

     `module_globals' 应为发出警告的代码所用的全局命名空间。（该参数用于
     从 zip 文件或其他非文件系统导入模块时显式源码）。

     `source' 是发出 *note ResourceWarning: 5ca. 的被销毁对象。

     3.6 版更變: 加入 `source' 参数。

 -- 函式: warnings.showwarning (message, category, filename, lineno,
          file=None, line=None)

     将警告信息写入文件。默认的实现代码是调用‘‘formatwarning(message,
     category, filename, lineno, line)‘‘ 并将结果字符串写入 `file' ，默
     认文件为 *note sys.stderr: 1ea.。通过将任何可调用对象赋给
     ‘warnings.showwarning’ 可替换掉该函数。`line' 是要包含在警告信息中
     的一行源代码；如果未提供 `line'，*note showwarning(): 37f4. 将尝试
     读取由*filename* 和 `lineno' 指定的行。

 -- 函式: warnings.formatwarning (message, category, filename, lineno,
          line=None)

     以标准方式格式化一条警告信息。将返回一个字符串，可能包含内嵌的换行
     符，并以换行符结束。如果未提供 `line'，*note formatwarning(): 112d.
     将尝试读取由 `filename' 和 `lineno' 指定的行。

 -- 函式: warnings.filterwarnings (action, message='', category=Warning,
          module='', lineno=0, append=False)

     在 *note 警告过滤器种类: 15d. 列表中插入一条数据项。默认情况下，该
     数据项将被插到前面；如果 `append' 为 True，则会插到后面。这里会检查
     参数的类型，编译 `message' 和 `module' 正则表达式，并将他们作为一个
     元组插入警告过滤器的列表中。如果两者都与某种警告匹配，那么靠近列表
     前面的数据项就会覆盖后面的项。省略的参数默认匹配任意值。

 -- 函式: warnings.simplefilter (action, category=Warning, lineno=0,
          append=False)

     在 *note 警告过滤器种类: 15d. 列表中插入一条简单数据项。函数参数的
     含义与 *note filterwarnings(): eca. 相同，但不需要正则表达式，因为
     插入的过滤器总是匹配任何模块中的任何信息，只要类别和行号匹配即可。

 -- 函式: warnings.resetwarnings ()

     重置警告过滤器。这将丢弃之前对 *note filterwarnings(): eca. 的所有
     调用，包括 *note -W: 15b. 命令行选项和对 *note simplefilter():
     35fa. 的调用效果。


File: python.info,  Node: 可用的上下文管理器,  Prev: 可用的函数,  Up: warnings —— 警告信息的控制

5.29.5.10 可用的上下文管理器
............................

 -- 類別: warnings.catch_warnings (*, record=False, module=None)

     该上下文管理器会复制警告过滤器和 *note showwarning(): 37f4. 函数，
     并在退出时恢复。 如果 `record' 参数是 *note False: 48e. (默认)，则
     在进入时会返回 *note None: 203.。 如果 `record' 为 *note True:
     593.，则返回一个列表，列表由自定义 *note showwarning(): 37f4. 函数
     所用对象逐步填充（该函数还会抑制 ‘sys.stdout’ 的输出）。 列表中每个
     对象的属性与 *note showwarning(): 37f4. 的参数名称相同。

     `module' 参数代表一个模块，当导入 *note warnings: 12f. 时，将被用于
     代替返回的模块，其过滤器将被保护。该参数主要是为了测试 *note
     warnings: 12f. 模块自身。

          備註: *note catch_warnings: 35f9. 管理器的工作方式，是替换并随
          后恢复模块的 *note showwarning(): 37f4. 函数和内部的过滤器种类
          列表。这意味着上下文管理器将会修改全局状态，因此不是线程安全的
          。


File: python.info,  Node: dataclasses --- 数据类,  Next: contextlib --- 为 with语句上下文提供的工具,  Prev: warnings —— 警告信息的控制,  Up: Python运行时服务

5.29.6 ‘dataclasses’ — 数据类
-----------------------------

`源码：' Lib/dataclasses.py(1)

__________________________________________________________________

这个模块提供了一个装饰器和一些函数，用于自动添加生成的 *note special
method: 3806.，例如 *note __init__(): e23. 和 *note __repr__(): 44a. 到
用户定义的类。 它最初描述于 PEP 557(2) 。

在这些生成的方法中使用的成员变量是使用 PEP 526(3) 类型标注来定义的。 例
如以下代码:

     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

将在添加的内容中包括如下所示的 *note __init__(): e23.:

     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

请注意，此方法会自动添加到类中：它不会在上面显示的 ‘InventoryItem’ 定义
中直接指定。

3.7 版新加入.

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/dataclasses.py

   (2) https://www.python.org/dev/peps/pep-0557

   (3) https://www.python.org/dev/peps/pep-0526


File: python.info,  Node: 模块级装饰器、类和函数,  Next: 初始化后处理,  Up: dataclasses --- 数据类

5.29.6.1 模块级装饰器、类和函数
...............................

 -- 函式: @dataclasses.dataclass (*, init=True, repr=True, eq=True,
          order=False, unsafe_hash=False, frozen=False)

     这个函数是 *note decorator: 174. ，用于将生成的 *note special
     method: 3806. 添加到类中，如下所述。

     *note dataclass(): 449. 装饰器会检查类以查找 ‘field’。 ‘field’ 被定
     义为具有 *note 类型标注: 712. 的类变量。 除了下面描述的两个例外，在
     *note dataclass(): 449. 中没有什么东西会去检查在变量标注中所指定的
     类型。

     所有生成的方法中的字段顺序是它们在类定义中出现的顺序。

     *note dataclass(): 449. 装饰器将向类中添加各种“dunder”方法，如下所
     述。 如果所添加的方法已存在于类中，则行为将取决于下面所列出的参数。
     装饰器会返回调用它的类本身；不会创建新的类。

     如果 *note dataclass(): 449. 仅用作没有参数的简单装饰器，它就像它具
     有此签名中记录的默认值一样。也就是说，这三种 *note dataclass():
     449. 用法是等价的:

          @dataclass
          class C:
              ...

          @dataclass()
          class C:
              ...

          @dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
          class C:
             ...

     *note dataclass(): 449. 的参数有：

        - ‘init’: 如果为真值（默认），将生成一个 *note __init__(): e23.
          方法。

          如果类已定义 *note __init__(): e23. ，则忽略此参数。

        - ‘repr’ ：如果为真值（默认），将生成一个 *note __repr__(): 44a.
          方法。 生成的 repr 字符串将具有类名以及每个字段的名称和 repr ，
          按照它们在类中定义的顺序。不包括标记为从 repr 中排除的字段。 例
          如：‘InventoryItem(name='widget', unit_price=3.0,
          quantity_on_hand=10)’。

          如果类已定义 *note __repr__(): 44a. ，则忽略此参数。

        - ‘eq’ ：如果为true（默认值），将生成 *note __eq__(): 44b. 方法
          。此方法将类作为其字段的元组按顺序比较。比较中的两个实例必须是
          相同的类型。

          如果类已定义 *note __eq__(): 44b. ，则忽略此参数。

        - ‘order’ ：如果为真值（默认为 ‘False’ ），则 *note __lt__():
          cfe. 、 *note __le__(): d68. 、 *note __gt__(): d69. 和 *note
          __ge__(): d6a. 方法将生成。 这将类作为其字段的元组按顺序比较。
          比较中的两个实例必须是相同的类型。如果 ‘order’ 为真值并且 ‘eq’
          为假值 ，则引发 *note ValueError: 16d. 。

          如果类已经定义了 *note __lt__(): cfe. 、 *note __le__(): d68.
          、 *note __gt__(): d69. 或者 *note __ge__(): d6a. 中的任意一个
          ，将引发 *note TypeError: 1fe. 。

        - ‘unsafe_hash’ ：如果为 ‘False’ （默认值），则根据 ‘eq’ 和
          ‘frozen’ 的设置方式生成 *note __hash__(): 44c. 方法。

          *note __hash__(): 44c. 由内置的 *note hash(): aa3. 使用，当对
          象被添加到散列集合（如字典和集合）时。有一个 *note __hash__():
          44c. 意味着类的实例是不可变的。可变性是一个复杂的属性，取决于
          程序员的意图， *note __eq__(): 44b. 的存在性和行为，以及 *note
          dataclass(): 449. 装饰器中 ‘eq’ 和 ‘frozen’ 标志的值。

          默认情况下， *note dataclass(): 449. 不会隐式添加 *note
          __hash__(): 44c. 方法，除非这样做是安全的。 它也不会添加或更改
          现有的明确定义的 *note __hash__(): 44c. 方法。 设置类属性
          ‘__hash__ = None’ 对 Python 具有特定含义，如 *note __hash__():
          44c. 文档中所述。

          如果 *note __hash__(): 44c. 没有显式定义，或者它被设为 ‘None’，
          则 *note dataclass(): 449. `可能' 会添加一个隐式 *note
          __hash__(): 44c. 方法。 虽然并不推荐，但你可以用
          ‘unsafe_hash=True’ 来强制 *note dataclass(): 449. 创建一个
          *note __hash__(): 44c. 方法。 如果你的类在逻辑上不可变但却仍然
          可被修改那么可能就是这种情况。 这是一个特殊用例并且应当被仔细
          地考虑。

          以下是隐式创建 *note __hash__(): 44c. 方法的规则。请注意，你不
          能在数据类中都使用显式的 *note __hash__(): 44c. 方法并设置
          ‘unsafe_hash=True’ ；这将导致 *note TypeError: 1fe. 。

          如果 ‘eq’ 和 ‘frozen’ 都是 true，默认情况下 *note dataclass():
          449. 将为你生成一个 *note __hash__(): 44c. 方法。如果 ‘eq’ 为
          true 且 ‘frozen’ 为 false ，则 *note __hash__(): 44c. 将被设置
          为 ‘None’ ，标记它不可用（因为它是可变的）。如果 ‘eq’ 为 false
          ，则 *note __hash__(): 44c. 将保持不变，这意味着将使用超类的
          *note __hash__(): 44c. 方法（如果超类是 *note object: 3d2. ，
          这意味着它将回到基于id的hash）。

        - ‘frozen’: 如为真值 (默认值为 ‘False’)，则对字段赋值将会产生异
          常。 这模拟了只读的冻结实例。 如果在类中定义了 *note
          __setattr__(): eee. 或 *note __delattr__(): 1563. 则将会引发
          *note TypeError: 1fe.。 参见下文的讨论。

     ‘field’s 可以选择使用普通的 Python 语法指定默认值:

          @dataclass
          class C:
              a: int       # 'a' has no default value
              b: int = 0   # assign a default value for 'b'

     在这个例子中， ‘a’ 和 ‘b’ 都将包含在添加的 *note __init__(): e23. 方
     法中，它们将被定义为:

          def __init__(self, a: int, b: int = 0):

     如果具有默认值的字段之后存在没有默认值的字段，将会引发 *note
     TypeError: 1fe.。 无论此情况是发生在单个类中还是作为类继承的结果，
     都是如此。

 -- 函式: dataclasses.field (*, default=MISSING,
          default_factory=MISSING, repr=True, hash=None, init=True,
          compare=True, metadata=None)

     对于常见和简单的用例，不需要其他功能。但是，有些数据类功能需要额外
     的每字段信息。为了满足这种对附加信息的需求，你可以通过调用提供的
     *note field(): 1139. 函数来替换默认字段值。例如:

          @dataclass
          class C:
              mylist: list[int] = field(default_factory=list)

          c = C()
          c.mylist += [1, 2, 3]

     如上所示， ‘MISSING’ 值是一个 sentinel 对象，用于检测是否提供了
     ‘default’ 和 ‘default_factory’ 参数。 使用此 sentinel 是因为 ‘None’
     是 ‘default’ 的有效值。没有代码应该直接使用 ‘MISSING’ 值。

     *note field(): 1139. 参数有：

        - ‘default’ ：如果提供，这将是该字段的默认值。这是必需的，因为
          *note field(): 1139. 调用本身会替换一般的默认值。

        - ‘default_factory’ ：如果提供，它必须是一个零参数可调用对象，当
          该字段需要一个默认值时，它将被调用。除了其他目的之外，这可以用
          于指定具有可变默认值的字段，如下所述。 同时指定 ‘default’ 和
          ‘default_factory’ 将产生错误。

        - ‘init’ ：如果为true（默认值），则该字段作为参数包含在生成的
          *note __init__(): e23. 方法中。

        - ‘repr’ ：如果为true（默认值），则该字段包含在生成的 *note
          __repr__(): 44a. 方法返回的字符串中。

        - ‘compare’ ：如果为true（默认值），则该字段包含在生成的相等性和
          比较方法中（ *note __eq__(): 44b. ， *note __gt__(): d69. 等等
          ）。

        - ‘hash’ ：这可以是布尔值或 ‘None’ 。如果为true，则此字段包含在
          生成的 *note __hash__(): 44c. 方法中。如果为 ‘None’ （默认值）
          ，请使用 ‘compare’ 的值，这通常是预期的行为。如果字段用于比较
          ，则应在 hash 中考虑该字段。不鼓励将此值设置为 ‘None’ 以外的任
          何值。

          设置 ‘hash=False’ 但 ‘compare=True’ 的一个可能原因是，如果一个
          计算 hash 的代价很高的字段是检验等价性需要的，但还有其他字段可
          以计算类型的 hash 。 即使从 hash 中排除某个字段，它仍将用于比
          较。

        - ‘metadata’ ：这可以是映射或 None 。 None 被视为一个空的字典。
          这个值包含在 ‘MappingProxyType()’ 中，使其成为只读，并暴露在
          *note Field: 3808. 对象上。数据类根本不使用它，它是作为第三方
          扩展机制提供的。多个第三方可以各自拥有自己的键值，以用作元数据
          中的命名空间。

     如果通过调用 *note field(): 1139. 指定字段的默认值，则该字段的类属
     性将替换为指定的 ‘default’ 值。如果没有提供 ‘default’ ，那么将删除
     类属性。目的是在 *note dataclass(): 449. 装饰器运行之后，类属性将包
     含字段的默认值，就像指定了默认值一样。例如，之后:

          @dataclass
          class C:
              x: int
              y: int = field(repr=False)
              z: int = field(repr=False, default=10)
              t: int = 20

     类属性 ‘C.z’ 将是 ‘10’ ，类属性 ‘C.t’ 将是 ‘20’，类属性 ‘C.x’ 和
     ‘C.y’ 将不设置。

 -- 類別: dataclasses.Field

     *note Field: 3808. 对象描述每个定义的字段。这些对象在内部创建，并由
     *note fields(): 3809. 模块级方法返回（见下文）。用户永远不应该直接
     实例化 *note Field: 3808. 对象。 其有文档的属性是：

             - ‘name’ ：字段的名字。

             - ‘type’ ：字段的类型。

             - ‘default’ 、 ‘default_factory’ 、 ‘init’ 、 ‘repr’ 、
               ‘hash’ 、 ‘compare’ 以及 ‘metadata’ 与具有和 *note
               field(): 1139. 声明中相同的意义和值。

     可能存在其他属性，但它们是私有的，不能被审查或依赖。

 -- 函式: dataclasses.fields (class_or_instance)

     返回 *note Field: 3808. 对象的元组，用于定义此数据类的字段。 接受数
     据类或数据类的实例。如果没有传递一个数据类或实例将引发 *note
     TypeError: 1fe. 。 不返回 ‘ClassVar’ 或 ‘InitVar’ 的伪字段。

 -- 函式: dataclasses.asdict (obj, *, dict_factory=dict)

     Converts the dataclass ‘obj’ to a dict (by using the factory
     function ‘dict_factory’).  Each dataclass is converted to a dict of
     its fields, as ‘name: value’ pairs.  dataclasses, dicts, lists, and
     tuples are recursed into.  Other objects are copied with *note
     copy.deepcopy(): 4d2.

     Example of using *note asdict(): f57. on nested dataclasses:

          @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}]}

     To create a shallow copy, the following workaround may be used:

          dict((field.name, getattr(obj, field.name)) for field in fields(obj))

     *note asdict(): f57. raises *note TypeError: 1fe. if ‘obj’ is not a
     dataclass instance.

 -- 函式: dataclasses.astuple (obj, *, tuple_factory=tuple)

     Converts the dataclass ‘obj’ to a tuple (by using the factory
     function ‘tuple_factory’).  Each dataclass is converted to a tuple
     of its field values.  dataclasses, dicts, lists, and tuples are
     recursed into.  Other objects are copied with *note
     copy.deepcopy(): 4d2.

     继续前一个例子:

          assert astuple(p) == (10, 20)
          assert astuple(c) == ([(0, 0), (10, 4)],)

     To create a shallow copy, the following workaround may be used:

          tuple(getattr(obj, field.name) for field in dataclasses.fields(obj))

     *note astuple(): f56. raises *note TypeError: 1fe. if ‘obj’ is not
     a dataclass instance.

 -- 函式: dataclasses.make_dataclass (cls_name, fields, *, bases=(),
          namespace=None, init=True, repr=True, eq=True, order=False,
          unsafe_hash=False, frozen=False)

     创建一个名为 ‘cls_name’ 的新数据类，字段为 ‘fields’ 中定义的字段，
     基类为 ‘bases’ 中给出的基类，并使用 ‘namespace’ 中给出的命名空间进
     行初始化。 ‘fields’ 是一个可迭代的元素，每个元素都是 ‘name’ 、
     ‘(name, type)’ 或 ‘(name, type, Field)’ 。 如果只提供‘‘name‘‘ ，
     ‘type’ 为 ‘typing.Any’ 。 ‘init’ 、 ‘repr’ 、 ‘eq’ 、 ‘order’ 、
     ‘unsafe_hash’ 和 ‘frozen’ 的值与它们在 *note dataclass(): 449. 中的
     含义相同。

     此函数不是严格要求的，因为用于任何创建带有 ‘__annotations__’ 的新类
     的 Python 机制都可以应用 *note dataclass(): 449. 函数将该类转换为数
     据类。提供此功能是为了方便。例如:

          C = make_dataclass('C',
                             [('x', int),
                               'y',
                              ('z', int, field(default=5))],
                             namespace={'add_one': lambda self: self.x + 1})

     等价于

          @dataclass
          class C:
              x: int
              y: 'typing.Any'
              z: int = 5

              def add_one(self):
                  return self.x + 1

 -- 函式: dataclasses.replace (obj, /, **changes)

     Creates a new object of the same type as ‘obj’, replacing fields
     with values from ‘changes’.  If ‘obj’ is not a Data Class, raises
     *note TypeError: 1fe.  If values in ‘changes’ do not specify
     fields, raises *note TypeError: 1fe.

     新返回的对象通过调用数据类的 *note __init__(): e23. 方法创建。这确
     保了如果存在 ‘__post_init__()’ ，其也被调用。

     如果存在没有默认值的仅初始化变量，必须在调用 *note replace(): fa8.
     时指定，以便它们可以传递给 *note __init__(): e23. 和
     ‘__post_init__()’ 。

     ‘changes’ 包含任何定义为 ‘init=False’ 的字段是错误的。在这种情况下
     会引发 *note ValueError: 16d. 。

     提前提醒 ‘init=False’ 字段在调用 *note replace(): fa8. 时的工作方式
     。如果它们完全被初始化的话，它们不是从源对象复制的，而是在
     ‘__post_init__()’ 中初始化。估计 ‘init=False’ 字段很少能被正确地使
     用。如果使用它们，那么使用备用类构造函数或者可能是处理实例复制的自
     定义 ‘replace()’ （或类似命名的）方法可能是明智的。

 -- 函式: dataclasses.is_dataclass (obj)

     如果其形参为 dataclass 或其实例则返回 ‘True’，否则返回 ‘False’。

     如果你需要知道一个类是否是一个数据类的实例（而不是一个数据类本身）
     ，那么再添加一个 ‘not isinstance(obj, type)’ 检查:

          def is_dataclass_instance(obj):
              return is_dataclass(obj) and not isinstance(obj, type)


File: python.info,  Node: 初始化后处理,  Next: 类变量,  Prev: 模块级装饰器、类和函数,  Up: dataclasses --- 数据类

5.29.6.2 初始化后处理
.....................

生成的 *note __init__(): e23. 代码将调用一个名为 ‘__post_init__()’ 的方
法，如果在类上已经定义了 ‘__post_init__()’ 。它通常被称为
‘self.__post_init__()’ 。但是，如果定义了任何 ‘InitVar’ 字段，它们也将按
照它们在类中定义的顺序传递给 ‘__post_init__()’ 。 如果没有 ‘__ init__()’
方法生成，那么 ‘__post_init__()’ 将不会被自动调用。

在其他用途中，这允许初始化依赖于一个或多个其他字段的字段值。例如:

     @dataclass
     class C:
         a: float
         b: float
         c: float = field(init=False)

         def __post_init__(self):
             self.c = self.a + self.b

由 *note dataclass(): 449. 所生成的 *note __init__(): e23. 方法不会调用
基类的 *note __init__(): e23. 方法。 如果基类有需要被调用的 *note
__init__(): e23. 方法，通常是在 ‘__post_init__()’ 方法中调用此方法:

     @dataclass
     class Rectangle:
         height: float
         width: float

     @dataclass
     class Square(Rectangle):
         side: float

         def __post_init__(self):
             super().__init__(self.side, self.side)

但是请注意，一般来说 dataclass 生成的 *note __init__(): e23. 方法不需要
被调用，因为派生的 dataclass 将负责初始化任何自身为 dataclass 的基类的所
有字段。

有关将参数传递给 ‘__post_init__()’ 的方法，请参阅下面有关仅初始化变量的
段落。另请参阅关于 *note replace(): fa8. 处理 ‘init=False’ 字段的警告。


File: python.info,  Node: 类变量,  Next: 仅初始化变量,  Prev: 初始化后处理,  Up: dataclasses --- 数据类

5.29.6.3 类变量
...............

两个地方 *note dataclass(): 449. 实际检查字段类型的之一是确定字段是否是
如 PEP 526(1) 所定义的类变量。它通过检查字段的类型是否为
‘typing.ClassVar’ 来完成此操作。如果一个字段是一个 ‘ClassVar’ ，它将被排
除在考虑范围之外，并被数据类机制忽略。这样的 ‘ClassVar’ 伪字段不会由模块
级的 *note fields(): 3809. 函数返回。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0526


File: python.info,  Node: 仅初始化变量,  Next: 冻结的实例,  Prev: 类变量,  Up: dataclasses --- 数据类

5.29.6.4 仅初始化变量
.....................

另一个 *note dataclass(): 449. 检查类型注解地方是为了确定一个字段是否是
一个仅初始化变量。它通过查看字段的类型是否为 ‘dataclasses.InitVar’ 类型
来实现。如果一个字段是一个 ‘InitVar’ ，它被认为是一个称为仅初始化字段的
伪字段。因为它不是一个真正的字段，所以它不会被模块级的 *note fields():
3809. 函数返回。仅初始化字段作为参数添加到生成的 *note __init__(): e23.
方法中，并传递给可选的 ‘__post_init__()’ 方法。数据类不会使用它们。

例如，假设一个字段将从数据库初始化，如果在创建类时未提供其值:

     @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)

在这种情况下， *note fields(): 3809. 将返回 ‘i’ 和 ‘j’ 的 *note Field:
3808. 对象，但不包括 ‘database’ 。


File: python.info,  Node: 冻结的实例,  Next: 继承,  Prev: 仅初始化变量,  Up: dataclasses --- 数据类

5.29.6.5 冻结的实例
...................

无法创建真正不可变的 Python 对象。但是，通过将 ‘frozen=True’ 传递给
*note dataclass(): 449. 装饰器，你可以模拟不变性。在这种情况下，数据类将
向类添加 *note __setattr__(): eee. 和 *note __delattr__(): 1563. 方法。
些方法在调用时会引发 *note FrozenInstanceError: 380f. 。

使用 ‘frozen=True’ 时会有很小的性能损失： ‘__ init__()’ 不能使用简单的赋
值来初始化字段，并必须使用 *note object.__setattr__(): eee. 。


File: python.info,  Node: 继承,  Next: 默认工厂函数,  Prev: 冻结的实例,  Up: dataclasses --- 数据类

5.29.6.6 继承
.............

当数组由 *note dataclass(): 449. 装饰器创建时，它会查看反向 MRO 中的所有
类的基类（即从 *note object: 3d2. 开始 ），并且对于它找到的每个数据类，
将该基类中的字段添加到字段的有序映射中。添加完所有基类字段后，它会将自己
的字段添加到有序映射中。所有生成的方法都将使用这种组合的，计算的有序字段
映射。由于字段是按插入顺序排列的，因此派生类会重载基类。一个例子:

     @dataclass
     class Base:
         x: Any = 15.0
         y: int = 0

     @dataclass
     class C(Base):
         z: int = 10
         x: int = 15

最后的字段列表依次是 ‘x’ 、 ‘y’ 、 ‘z’ 。 ‘x’ 的最终类型是 ‘int’ ，如类
‘C’ 中所指定的那样。

为 ‘C’ 生成的 *note __init__(): e23. 方法看起来像:

     def __init__(self, x: int = 15, y: int = 0, z: int = 10):


File: python.info,  Node: 默认工厂函数,  Next: 可变的默认值,  Prev: 继承,  Up: dataclasses --- 数据类

5.29.6.7 默认工厂函数
.....................

     如果一个 *note field(): 1139. 指定了一个 ‘default_factory’ ，当需要
     该字段的默认值时，将使用零参数调用它。例如，要创建列表的新实例，请
     使用:

          mylist: list = field(default_factory=list)

     如果一个字段被排除在 *note __init__(): e23. 之外（使用 ‘init=False’
     ）并且字段也指定 ‘default_factory’ ，则默认的工厂函数将始终从生成的
     *note __init__(): e23. 函数调用。发生这种情况是因为没有其他方法可以
     为字段提供初始值。


File: python.info,  Node: 可变的默认值,  Next: 异常<16>,  Prev: 默认工厂函数,  Up: dataclasses --- 数据类

5.29.6.8 可变的默认值
.....................

     Python 在类属性中存储默认成员变量值。思考这个例子，不使用数据类:

          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

     请注意，类 ‘C’ 的两个实例共享相同的类变量 ‘x’ ，如预期的那样。

     使用数据类， `如果' 此代码有效:

          @dataclass
          class D:
              x: List = []
              def add(self, element):
                  self.x += element

     它生成的代码类似于:

          class D:
              x = []
              def __init__(self, x=x):
                  self.x = x
              def add(self, element):
                  self.x += element

          assert D().x is D().x

     这与使用类 ‘C’ 的原始示例具有相同的问题。也就是说，在创建类实例时没
     有为 ‘x’ 指定值的类 ‘D’ 的两个实例将共享相同的 ‘x’ 副本。由于数据类
     只使用普通的 Python 类创建，因此它们也会共享此行为。数据类没有通用
     的方法来检测这种情况。相反，如果数据类检测到类型为 ‘list’ 、 ‘dict’
     或 ‘set’ 的默认参数，则会引发 *note TypeError: 1fe. 。这是一个部分
     解决方案，但它可以防止许多常见错误。

     使用默认工厂函数是一种创建可变类型新实例的方法，并将其作为字段的默
     认值:

          @dataclass
          class D:
              x: list = field(default_factory=list)

          assert D().x is not D().x


File: python.info,  Node: 异常<16>,  Prev: 可变的默认值,  Up: dataclasses --- 数据类

5.29.6.9 异常
.............

 -- 例外: dataclasses.FrozenInstanceError

     在使用 ‘frozen=True’ 定义的数据类上调用隐式定义的 *note
     __setattr__(): eee. 或 *note __delattr__(): 1563. 时引发。 这是
     *note AttributeError: 4a1. 的一个子类。


File: python.info,  Node: contextlib --- 为 with语句上下文提供的工具,  Next: abc --- 抽象基类,  Prev: dataclasses --- 数据类,  Up: Python运行时服务

5.29.7 ‘contextlib’ — 为 ‘with’语句上下文提供的工具
---------------------------------------------------

`源代码' Lib/contextlib.py(1)

__________________________________________________________________

此模块为涉及 *note with: 7da. 语句的常见任务提供了实用的工具。更多信息请
参见 *note 上下文管理器类型: 15c6. 和 *note with 语句上下文管理器:
15c4.。

* Menu:

* 工具::
* 例子和配方::
* Single use, reusable and reentrant context managers: Single use reusable and reentrant context managers.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/contextlib.py


File: python.info,  Node: 工具,  Next: 例子和配方,  Up: contextlib --- 为 with语句上下文提供的工具

5.29.7.1 工具
.............

提供的函数和类：

 -- 類別: contextlib.AbstractContextManager

     一个为实现了 *note object.__enter__(): d5d. 与 *note
     object.__exit__(): d5e. 的类提供的 *note abstract base class: c05.。
     为 *note object.__enter__(): d5d. 提供的一个默认实现是返回 ‘self’ 而
     *note object.__exit__(): d5e. 是一个默认返回 ‘None’ 的抽象方法。 参
     见 *note 上下文管理器类型: 15c6. 的定义。

     3.6 版新加入.

 -- 類別: contextlib.AbstractAsyncContextManager

     一个为实现了 *note object.__aenter__(): 109a. 与 *note
     object.__aexit__(): 109b. 的类提供的 *note abstract base class:
     c05.。 为 *note object.__aenter__(): 109a. 提供的一个默认实现是返回
     ‘self’ 而 *note object.__aexit__(): 109b. 是一个默认返回 ‘None’ 的
     抽象方法。 参见 *note 异步上下文管理器: 15d2. 的定义。

     3.7 版新加入.

 -- 函式: @contextlib.contextmanager

     这个函数是一个 *note decorator: 174. ，它可以定义一个支持 *note
     with: 7da. 语句上下文管理器的工厂函数， 而不需要创建一个类或区
     *note __enter__(): d5d. 与 *note __exit__(): d5e. 方法。

     尽管许多对象原生支持使用 with 语句，但有些需要被管理的资源并不是上
     下文管理器，并且没有实现 ‘close()’ 方法而不能使用
     ‘contextlib.closing’ 。

     下面是一个抽象的示例，展示如何确保正确的资源管理:

          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

     被装饰的函数在被调用时，必须返回一个 *note generator: a83. 迭代器。
     这个迭代器必须只 yield 一个值出来，这个值会被用在 *note with: 7da.
     语句中，绑定到 ‘as’ 后面的变量，如果给定了的话。

     当生成器发生 yield 时，嵌套在 *note with: 7da. 语句中的语句体会被执
     行。 语句体执行完毕离开之后，该生成器将被恢复执行。 如果在该语句体
     中发生了未处理的异常，则该异常会在生成器发生 yield 时重新被引发。 因
     此，你可以使用 *note try: e37...*note except: c10...*note finally:
     2bc. 语句来捕获该异常（如果有的话），或确保进行了一些清理。 如果仅
     出于记录日志或执行某些操作（而非完全抑制异常）的目的捕获了异常，生
     成器必须重新引发该异常。 否则生成器的上下文管理器将向 ‘with’ 语句指
     示该异常已经被处理，程序将立即在 ‘with’ 语句之后恢复并继续执行。

     *note contextmanager(): c4f. 使用 *note ContextDecorator: c4e. 因此
     它创建的上下文管理器不仅可以用在 *note with: 7da. 语句中，还可以用
     作一个装饰器。当它用作一个装饰器时，每一次函数调用时都会隐式创建一
     个新的生成器实例（这使得 *note contextmanager(): c4f. 创建的上下文
     管理器满足了支持多次调用以用作装饰器的需求，而非“一次性”的上下文管
     理器）。

     3.2 版更變: *note ContextDecorator: c4e. 的使用。

 -- 函式: @contextlib.asynccontextmanager

     与 *note contextmanager(): c4f. 类似，但创建的是 *note asynchronous
     context manager: 15d2. 。

     这个函数是一个 *note decorator: 174. ，它可以定义一个支持 *note
     async with: 736. 语句的异步上下文管理器的工厂函数， 而不需要创建一
     个类或区分 *note __aenter__(): 109a. 与 *note __aexit__(): 109b. 方
     法。它必须被作用在一个 *note asynchronous generator: 1640. 函数上

     一个简单的示例：

          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 ...')

     3.7 版新加入.

 -- 函式: contextlib.closing (thing)

     返回一个在语句块执行完成时关闭 `things' 的上下文管理器。这基本上等
     价于：

          from contextlib import contextmanager

          @contextmanager
          def closing(thing):
              try:
                  yield thing
              finally:
                  thing.close()

     并允许你编写这样的代码：

          from contextlib import closing
          from urllib.request import urlopen

          with closing(urlopen('https://www.python.org')) as page:
              for line in page:
                  print(line)

     而无需显式地关闭 ‘page’ 。 即使发生错误，在退出 *note with: 7da. 语
     句块时， ‘page.close()’ 也同样会被调用。
 -- 函式: contextlib.nullcontext (enter_result=None)

     返回一个从 ‘__enter__’ 返回 `enter_result' 的上下文管理器，除此之外
     不执行任何操作。它旨在用于可选上下文管理器的一种替代，例如：

          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

     一个使用 `enter_result' 的例子：

          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

     3.7 版新加入.

 -- 函式: contextlib.suppress (*exceptions)

     Return a context manager that suppresses any of the specified
     exceptions if they occur in the body of a ‘with’ statement and then
     resumes execution with the first statement following the end of the
     ‘with’ statement.

     与完全抑制异常的任何其他机制一样，该上下文管理器应当只用来抑制非常
     具体的错误，并确保该场景下静默地继续执行程序是通用的正确做法。

     例如:

          from contextlib import suppress

          with suppress(FileNotFoundError):
              os.remove('somefile.tmp')

          with suppress(FileNotFoundError):
              os.remove('someotherfile.tmp')

     这段代码等价于：

          try:
              os.remove('somefile.tmp')
          except FileNotFoundError:
              pass

          try:
              os.remove('someotherfile.tmp')
          except FileNotFoundError:
              pass

     该上下文管理器是 *note reentrant: 3819. 。

     3.4 版新加入.

 -- 函式: contextlib.redirect_stdout (new_target)

     用于将 *note sys.stdout: 41f. 临时重定向到一个文件或类文件对象的上
     下文管理器。

     该工具给已有的将输出硬编码写到 stdout 的函数或类提供了额外的灵活性
     。

     For example, the output of *note help(): 175. normally is sent to
     `sys.stdout'.  You can capture that output in a string by
     redirecting the output to an *note io.StringIO: 91a. object.  The
     replacement stream is returned from the ‘__enter__’ method and so
     is available as the target of the *note with: 7da. statement:

          with redirect_stdout(io.StringIO()) as f:
              help(pow)
          s = f.getvalue()

     如果要把 *note help(): 175. 的输出写到磁盘上的一个文件，重定向该输
     出到一个常规文件：

          with open('help.txt', 'w') as f:
              with redirect_stdout(f):
                  help(pow)

     如果要把 *note help(): 175. 的输出写到 `sys.stderr' ：

          with redirect_stdout(sys.stderr):
              help(pow)

     需要注意的点在于， *note sys.stdout: 41f. 的全局副作用意味着此上下
     文管理器不适合在库代码和大多数多线程应用程序中使用。它对子进程的输
     出没有影响。不过对于许多工具脚本而言，它仍然是一个有用的方法。

     该上下文管理器是 *note reentrant: 3819. 。

     3.4 版新加入.

 -- 函式: contextlib.redirect_stderr (new_target)

     与 *note redirect_stdout(): 7b5. 类似，不过是将 *note sys.stderr:
     1ea. 重定向到一个文件或类文件对象。

     该上下文管理器是 *note reentrant: 3819. 。

     3.5 版新加入.

 -- 類別: contextlib.ContextDecorator

     一个使上下文管理器能用作装饰器的基类。

     与往常一样，继承自 ‘ContextDecorator’  的上下文管理器必须实现
     ‘__enter__’ 与 ‘__exit__’ 。即使用作装饰器， ‘__exit__’ 依旧会保持
     可能的异常处理。

     ‘ContextDecorator’ 被用在 *note contextmanager(): c4f. 中，因此你自
     然获得了这项功能。

     ‘ContextDecorator’ 的示例:

          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

     这个改动只是针对如下形式的一个语法糖：

          def f():
              with cm():
                  # Do stuff

     ‘ContextDecorator’ 使得你可以这样改写：

          @cm()
          def f():
              # Do stuff

     这能清楚地表明， ‘cm’ 作用于整个函数，而不仅仅是函数的一部分（同时
     也能保持不错的缩进层级）。

     现有的上下文管理器即使已经有基类，也可以使用 ‘ContextDecorator’ 作
     为混合类进行扩展：

          from contextlib import ContextDecorator

          class mycontext(ContextBaseClass, ContextDecorator):
              def __enter__(self):
                  return self

              def __exit__(self, *exc):
                  return False

          備註: 由于被装饰的函数必须能够被多次调用，因此对应的上下文管理
          器必须支持在多个 *note with: 7da. 语句中使用。如果不是这样，则
          应当使用原来的具有显式 ‘with’ 语句的形式使用该上下文管理器。

     3.2 版新加入.

 -- 類別: contextlib.ExitStack

     该上下文管理器的设计目标是使得在编码中组合其他上下文管理器和清理函
     数更加容易，尤其是那些可选的或由输入数据驱动的上下文管理器。

     例如，通过一个如下的 with 语句可以很容易处理一组文件：

          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

     每个实例维护一个注册了一组回调的栈，这些回调在实例关闭时以相反的顺
     序被调用（显式或隐式地在 *note with: 7da. 语句的末尾）。请注意，当
     一个栈实例被垃圾回收时，这些回调将 `不会' 被隐式调用。

     通过使用这个基于栈的模型，那些通过 ‘__init__’ 方法获取资源的上下文
     管理器（如文件对象）能够被正确处理。

     由于注册的回调函数是按照与注册相反的顺序调用的，因此最终的行为就像
     多个嵌套的 *note with: 7da. 语句用在这些注册的回调函数上。这个行为
     甚至扩展到了异常处理：如果内部的回调函数抑制或替换了异常，则外部回
     调收到的参数是基于该更新后的状态得到的。

     这是一个相对底层的 API，它负责正确处理栈里回调退出时依次展开的细节
     。它为相对高层的上下文管理器提供了一个合适的基础，使得它能根据应用
     程序的需求使用特定方式操作栈。

     3.3 版新加入.

      -- 成員函式: enter_context (cm)

          Enters a new context manager and adds its *note __exit__():
          d5e. method to the callback stack.  The return value is the
          result of the context manager’s own *note __enter__(): d5d.
          method.

          These context managers may suppress exceptions just as they
          normally would if used directly as part of a *note with: 7da.
          statement.

      -- 成員函式: push (exit)

          Adds a context manager’s *note __exit__(): d5e. method to the
          callback stack.

          As ‘__enter__’ is `not' invoked, this method can be used to
          cover part of an *note __enter__(): d5d. implementation with a
          context manager’s own *note __exit__(): d5e. method.

          If passed an object that is not a context manager, this method
          assumes it is a callback with the same signature as a context
          manager’s *note __exit__(): d5e. method and adds it directly
          to the callback stack.

          By returning true values, these callbacks can suppress
          exceptions the same way context manager *note __exit__(): d5e.
          methods can.

          The passed in object is returned from the function, allowing
          this method to be used as a function decorator.

      -- 成員函式: callback (callback, /, *args, **kwds)

          Accepts an arbitrary callback function and arguments and adds
          it to the callback stack.

          Unlike the other methods, callbacks added this way cannot
          suppress exceptions (as they are never passed the exception
          details).

          The passed in callback is returned from the function, allowing
          this method to be used as a function decorator.

      -- 成員函式: pop_all ()

          Transfers the callback stack to a fresh *note ExitStack: 47e.
          instance and returns it.  No callbacks are invoked by this
          operation - instead, they will now be invoked when the new
          stack is closed (either explicitly or implicitly at the end of
          a *note with: 7da. statement).

          For example, a group of files can be opened as an "all or
          nothing" operation as follows:

               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.

      -- 成員函式: close ()

          Immediately unwinds the callback stack, invoking callbacks in
          the reverse order of registration.  For any context managers
          and exit callbacks registered, the arguments passed in will
          indicate that no exception occurred.

 -- 類別: contextlib.AsyncExitStack

     An *note asynchronous context manager: 15d2, similar to *note
     ExitStack: 47e, that supports combining both synchronous and
     asynchronous context managers, as well as having coroutines for
     cleanup logic.

     The ‘close()’ method is not implemented, *note aclose(): 381e. must
     be used instead.

      -- 成員函式: coroutine enter_async_context (cm)

          Similar to ‘enter_context()’ but expects an asynchronous
          context manager.

      -- 成員函式: push_async_exit (exit)

          Similar to ‘push()’ but expects either an asynchronous context
          manager or a coroutine function.

      -- 成員函式: push_async_callback (callback, /, *args, **kwds)

          Similar to ‘callback()’ but expects a coroutine function.

      -- 成員函式: coroutine aclose ()

          Similar to ‘close()’ but properly handles awaitables.

     Continuing the example for *note asynccontextmanager(): 47f.:

          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.

     3.7 版新加入.


File: python.info,  Node: 例子和配方,  Next: Single use reusable and reentrant context managers,  Prev: 工具,  Up: contextlib --- 为 with语句上下文提供的工具

5.29.7.2 例子和配方
...................

This section describes some examples and recipes for making effective
use of the tools provided by *note contextlib: 23.

* Menu:

* Supporting a variable number of context managers::
* Catching exceptions from __enter__ methods::
* Cleaning up in an __enter__ implementation::
* Replacing any use of try-finally and flag variables::
* Using a context manager as a function decorator::


File: python.info,  Node: Supporting a variable number of context managers,  Next: Catching exceptions from __enter__ methods,  Up: 例子和配方

5.29.7.3 Supporting a variable number of context managers
.........................................................

The primary use case for *note ExitStack: 47e. is the one given in the
class documentation: supporting a variable number of context managers
and other cleanup operations in a single *note with: 7da. statement.
The variability may come from the number of context managers needed
being driven by user input (such as opening a user specified collection
of files), or from some of the context managers being optional:

     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

As shown, *note ExitStack: 47e. also makes it quite easy to use *note
with: 7da. statements to manage arbitrary resources that don’t natively
support the context management protocol.


File: python.info,  Node: Catching exceptions from __enter__ methods,  Next: Cleaning up in an __enter__ implementation,  Prev: Supporting a variable number of context managers,  Up: 例子和配方

5.29.7.4 Catching exceptions from ‘__enter__’ methods
.....................................................

It is occasionally desirable to catch exceptions from an ‘__enter__’
method implementation, `without' inadvertently catching exceptions from
the *note with: 7da. statement body or the context manager’s ‘__exit__’
method.  By using *note ExitStack: 47e. the steps in the context
management protocol can be separated slightly in order to allow this:

     stack = ExitStack()
     try:
         x = stack.enter_context(cm)
     except Exception:
         # handle __enter__ exception
     else:
         with stack:
             # Handle normal case

Actually needing to do this is likely to indicate that the underlying
API should be providing a direct resource management interface for use
with *note try: e37./*note except: c10./*note finally: 2bc. statements,
but not all APIs are well designed in that regard.  When a context
manager is the only resource management API provided, then *note
ExitStack: 47e. can make it easier to handle various situations that
can’t be handled directly in a *note with: 7da. statement.


File: python.info,  Node: Cleaning up in an __enter__ implementation,  Next: Replacing any use of try-finally and flag variables,  Prev: Catching exceptions from __enter__ methods,  Up: 例子和配方

5.29.7.5 Cleaning up in an ‘__enter__’ implementation
.....................................................

As noted in the documentation of *note ExitStack.push(): 381b, this
method can be useful in cleaning up an already allocated resource if
later steps in the *note __enter__(): d5d. implementation fail.

Here’s an example of doing this for a context manager that accepts
resource acquisition and release functions, along with an optional
validation function, and maps them to the context management protocol:

     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()


File: python.info,  Node: Replacing any use of try-finally and flag variables,  Next: Using a context manager as a function decorator,  Prev: Cleaning up in an __enter__ implementation,  Up: 例子和配方

5.29.7.6 Replacing any use of ‘try-finally’ and flag variables
..............................................................

A pattern you will sometimes see is a ‘try-finally’ statement with a
flag variable to indicate whether or not the body of the ‘finally’
clause should be executed.  In its simplest form (that can’t already be
handled just by using an ‘except’ clause instead), it looks something
like this:

     cleanup_needed = True
     try:
         result = perform_operation()
         if result:
             cleanup_needed = False
     finally:
         if cleanup_needed:
             cleanup_resources()

As with any ‘try’ statement based code, this can cause problems for
development and review, because the setup code and the cleanup code can
end up being separated by arbitrarily long sections of code.

*note ExitStack: 47e. makes it possible to instead register a callback
for execution at the end of a ‘with’ statement, and then later decide to
skip executing that callback:

     from contextlib import ExitStack

     with ExitStack() as stack:
         stack.callback(cleanup_resources)
         result = perform_operation()
         if result:
             stack.pop_all()

This allows the intended cleanup up behaviour to be made explicit up
front, rather than requiring a separate flag variable.

If a particular application uses this pattern a lot, it can be
simplified even further by means of a small helper class:

     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()

If the resource cleanup isn’t already neatly bundled into a standalone
function, then it is still possible to use the decorator form of *note
ExitStack.callback(): 3c7. to declare the resource cleanup in advance:

     from contextlib import ExitStack

     with ExitStack() as stack:
         @stack.callback
         def cleanup_resources():
             ...
         result = perform_operation()
         if result:
             stack.pop_all()

Due to the way the decorator protocol works, a callback function
declared this way cannot take any parameters.  Instead, any resources to
be released must be accessed as closure variables.


File: python.info,  Node: Using a context manager as a function decorator,  Prev: Replacing any use of try-finally and flag variables,  Up: 例子和配方

5.29.7.7 Using a context manager as a function decorator
........................................................

*note ContextDecorator: c4e. makes it possible to use a context manager
in both an ordinary ‘with’ statement and also as a function decorator.

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, inheriting from *note ContextDecorator: c4e.
provides both capabilities in a single definition:

     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)

Instances of this class can be used as both a context manager:

     with track_entry_and_exit('widget loader'):
         print('Some time consuming activity goes here')
         load_widget()

And also as a function decorator:

     @track_entry_and_exit('widget loader')
     def activity():
         print('Some time consuming activity goes here')
         load_widget()

Note that there is one additional limitation when using context managers
as function decorators: there’s no way to access the return value of
*note __enter__(): d5d.  If that value is needed, then it is still
necessary to use an explicit ‘with’ statement.

也參考
......

PEP 343(1) - "with" 语句

     Python *note with: 7da. 语句的规范描述、背景和示例。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0343


File: python.info,  Node: Single use reusable and reentrant context managers,  Prev: 例子和配方,  Up: contextlib --- 为 with语句上下文提供的工具

5.29.7.8 Single use, reusable and reentrant context managers
............................................................

Most context managers are written in a way that means they can only be
used effectively in a *note with: 7da. statement once.  These single use
context managers must be created afresh each time they’re used -
attempting to use them a second time will trigger an exception or
otherwise not work correctly.

This common limitation means that it is generally advisable to create
context managers directly in the header of the *note with: 7da.
statement where they are used (as shown in all of the usage examples
above).

Files are an example of effectively single use context managers, since
the first *note with: 7da. statement will close the file, preventing any
further IO operations using that file object.

Context managers created using *note contextmanager(): c4f. are also
single use context managers, and will complain about the underlying
generator failing to yield if an attempt is made to use them a second
time:

     >>> 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

* Menu:

* Reentrant context managers::
* Reusable context managers::


File: python.info,  Node: Reentrant context managers,  Next: Reusable context managers,  Up: Single use reusable and reentrant context managers

5.29.7.9 Reentrant context managers
...................................

More sophisticated context managers may be "reentrant".  These context
managers can not only be used in multiple *note with: 7da. statements,
but may also be used `inside' a ‘with’ statement that is already using
the same context manager.

*note threading.RLock: cba. is an example of a reentrant context
manager, as are *note suppress(): 919. and *note redirect_stdout(): 7b5.
Here’s a very simple example of reentrant use:

     >>> 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

Real world examples of reentrancy are more likely to involve multiple
functions calling each other and hence be far more complicated than this
example.

Note also that being reentrant is `not' the same thing as being thread
safe.  *note redirect_stdout(): 7b5, for example, is definitely not
thread safe, as it makes a global modification to the system state by
binding *note sys.stdout: 41f. to a different stream.


File: python.info,  Node: Reusable context managers,  Prev: Reentrant context managers,  Up: Single use reusable and reentrant context managers

5.29.7.10 Reusable context managers
...................................

Distinct from both single use and reentrant context managers are
"reusable" context managers (or, to be completely explicit, "reusable,
but not reentrant" context managers, since reentrant context managers
are also reusable).  These context managers support being used multiple
times, but will fail (or otherwise not work correctly) if the specific
context manager instance has already been used in a containing with
statement.

*note threading.Lock: 24bc. is an example of a reusable, but not
reentrant, context manager (for a reentrant lock, it is necessary to use
*note threading.RLock: cba. instead).

Another example of a reusable, but not reentrant, context manager is
*note ExitStack: 47e, as it invokes `all' currently registered callbacks
when leaving any with statement, regardless of where those callbacks
were added:

     >>> 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

As the output from the example shows, reusing a single stack object
across multiple with statements works correctly, but attempting to nest
them will cause the stack to be cleared at the end of the innermost with
statement, which is unlikely to be desirable behaviour.

Using separate *note ExitStack: 47e. instances instead of reusing a
single instance avoids that problem:

     >>> 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


File: python.info,  Node: abc --- 抽象基类,  Next: atexit --- 退出处理器,  Prev: contextlib --- 为 with语句上下文提供的工具,  Up: Python运行时服务

5.29.8 ‘abc’ — 抽象基类
-----------------------

`源代码：' Lib/abc.py(1)

__________________________________________________________________

该模块提供了在 Python 中定义 *note 抽象基类: c05. (ABC) 的组件，在 PEP
3119(2) 中已有概述。查看 PEP 文档了解为什么需要在 Python 中增加这个模块
。（也可查看 PEP 3141(3) 以及 *note numbers: c1. 模块了解基于 ABC 的数字
类型继承关系。）

*note collections: 1d. 模块中有一些派生自 ABC 的具体类；当然这些类还可以
进一步被派生。此外，*note collections.abc: 1e. 子模块中有一些 ABC 可被用
于测试一个类或实例是否提供特定的接口，例如它是否可哈希或它是否为映射等。

该模块提供了一个元类 *note ABCMeta: 906.，可以用来定义抽象类，另外还提供
一个工具类 *note ABC: 905.，可以用它以继承的方式定义抽象基类。

 -- 類別: abc.ABC

     一个使用 *note ABCMeta: 906. 作为元类的工具类。抽象基类可以通过从
     *note ABC: 905. 派生来简单地创建，这就避免了在某些情况下会令人混淆
     的元类用法，例如：

          from abc import ABC

          class MyABC(ABC):
              pass

     注意 *note ABC: 905. 的类型仍然是 *note ABCMeta: 906.，因此继承
     *note ABC: 905. 仍然需要关注元类使用中的注意事项，比如可能会导致元
     类冲突的多重继承。当然你也可以直接使用 *note ABCMeta: 906. 作为元类
     来定义抽象基类，例如：

          from abc import ABCMeta

          class MyABC(metaclass=ABCMeta):
              pass

     3.4 版新加入.

 -- 類別: abc.ABCMeta

     用于定义抽象基类（ABC）的元类。

     使用该元类以创建抽象基类。抽象基类可以像 mix-in 类一样直接被子类继
     承。你也可以将不相关的具体类（包括内建类）和抽象基类注册为“抽象子类
     ” —— 这些类以及它们的子类会被内建函数 *note issubclass(): 552. 识别
     为对应的抽象基类的子类，但是该抽象基类不会出现在其 MRO（Method
     Resolution Order，方法解析顺序）中，抽象基类中实现的方法也不可调用
     （即使通过 *note super(): 5dd. 调用也不行）。(4)

     使用 *note ABCMeta: 906. 作为元类创建的类含有如下方法：

      -- 成員函式: register (subclass)

          将“子类”注册为该抽象基类的“抽象子类”，例如：

               from abc import ABC

               class MyABC(ABC):
                   pass

               MyABC.register(tuple)

               assert issubclass(tuple, MyABC)
               assert isinstance((), MyABC)

          3.3 版更變: 返回注册的子类，使其能够作为类装饰器。

          3.4 版更變: 你可以使用 *note get_cache_token(): 904. 函数来检
          测对 *note register(): ab0. 的调用。

     你也可以在虚基类中重载这个方法。

      -- 成員函式: __subclasshook__ (subclass)

          （必须定义为类方法。）

          检查 `subclass' 是否是该抽象基类的子类。也就是说对于那些你希望
          定义为该抽象基类的子类的类，你不用对每个类都调用 *note
          register(): ab0. 方法了，而是可以直接自定义 ‘issubclass’ 的行
          为。（这个类方法是在抽象基类的 ‘__subclasscheck__()’ 方法中调
          用的。）

          该方法必须返回 ‘True’, ‘False’ 或是 ‘NotImplemented’。如果返回
          ‘True’，`subclass' 就会被认为是这个抽象基类的子类。如果返回
          ‘False’，无论正常情况是否应该认为是其子类，统一视为不是。如果
          返回 ‘NotImplemented’，子类检查会按照正常机制继续执行。

     为了对这些概念做一演示，请看以下定义 ABC 的示例：

          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)

     ABC ‘MyIterable’ 定义了标准的迭代方法 *note __iter__(): 175e. 作为
     一个抽象方法。这里给出的实现仍可在子类中被调用。‘get_iterator()’ 方
     法也是 ‘MyIterable’ 抽象基类的一部分，但它并非必须被非抽象派生类所
     重载。

     这里定义的 *note __subclasshook__(): 382d. 类方法指明了任何在其
     *note __dict__: 5f5. (或在其通过 *note __mro__: 173a. 列表访问的基
     类) 中具有 *note __iter__(): 175e. 方法的类也都会被视为
     ‘MyIterable’。

     最后，末尾行使得 ‘Foo’ 成为 ‘MyIterable’ 的一个虚子类，即使它没有定
     义 *note __iter__(): 175e. 方法（它使用了以 *note __len__(): e90. 和
     *note __getitem__(): 3a5. 术语定义的旧式可迭代对象协议）。 请注意这
     将不会使 ‘get_iterator’ 成为 ‘Foo’ 的一个可用方法，它是被另外提供的
     。

此外，*note abc: 3. 模块还提供了这些装饰器：

 -- 函式: @abc.abstractmethod

     用于声明抽象方法的装饰器。

     使用此装饰器要求类的元类是 *note ABCMeta: 906. 或是从该类派生。一个
     具有派生自 *note ABCMeta: 906. 的元类的类不可以被实例化，除非它全部
     的抽象方法和特征属性均已被重载。抽象方法可通过任何普通的“super”调用
     机制来调用。 *note abstractmethod(): aad. 可被用于声明特性属性和描
     述器的抽象方法。

     不支持动态添加抽象方法到一个类，或试图在方法或类被创建后修改其抽象
     状态等操作。 *note abstractmethod(): aad. 只会影响使用常规继承所派
     生的子类；通过 ABC 的 ‘register()’ 方法注册的“虚子类”不会受到影响。

     当 *note abstractmethod(): aad. 与其他方法描述符配合应用时，它应当
     被应用为最内层的装饰器，如以下用法示例所示:

          class C(ABC):
              @abstractmethod
              def my_abstract_method(self, ...):
                  ...
              @classmethod
              @abstractmethod
              def my_abstract_classmethod(cls, ...):
                  ...
              @staticmethod
              @abstractmethod
              def my_abstract_staticmethod(...):
                  ...

              @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)

     为了能正确地与抽象基类机制实现互操作，描述符必须使用
     ‘__isabstractmethod__’ 将自身标识为抽象的。 通常，如果被用于组成描
     述符的任何方法都是抽象的则此属性应当为 ‘True’。 例如，Python 的内置
     *note property: 308. 所做的就等价于:

          class Descriptor:
              ...
              @property
              def __isabstractmethod__(self):
                  return any(getattr(f, '__isabstractmethod__', False) for
                             f in (self._fget, self._fset, self._fdel))

          備註: 不同于 Java 抽象方法，这些抽象方法可能具有一个实现。 这
          个实现可在重载它的类上通过 *note super(): 5dd. 机制来调用。 这
          在使用协作多重继承的框架中可以被用作超调用的一个端点。

*note abc: 3. 模块还支持下列旧式装饰器:

 -- 函式: @abc.abstractclassmethod

     3.2 版新加入.

     3.3 版後已棄用: 现在可以让 *note classmethod: 309. 配合 *note
     abstractmethod(): aad. 使用，使得此装饰器变得冗余。

     内置 *note classmethod(): 309. 的子类，指明一个抽象类方法。 在其他
     方面它都类似于 *note abstractmethod(): aad.。

     这个特例已被弃用，因为现在当 *note classmethod(): 309. 装饰器应用于
     抽象方法时它会被正确地标识为抽象的:

          class C(ABC):
              @classmethod
              @abstractmethod
              def my_abstract_classmethod(cls, ...):
                  ...

 -- 函式: @abc.abstractstaticmethod

     3.2 版新加入.

     3.3 版後已棄用: 现在可以让 *note staticmethod: 30a. 配合 *note
     abstractmethod(): aad. 使用，使得此装饰器变得冗余。

     内置 *note staticmethod(): 30a. 的子类，指明一个抽象静态方法。 在其
     他方面它都类似于 *note abstractmethod(): aad.。

     这个特例已被弃用，因为现在当 *note staticmethod(): 30a. 装饰器应用
     于抽象方法时它会被正确地标识为抽象的:

          class C(ABC):
              @staticmethod
              @abstractmethod
              def my_abstract_staticmethod(...):
                  ...

 -- 函式: @abc.abstractproperty

     3.3 版後已棄用: 现在可以让 *note property: 308,
     ‘property.getter()’, ‘property.setter()’ 和 ‘property.deleter()’ 配
     合 *note abstractmethod(): aad. 使用，使得此装饰器变得冗余。

     内置 *note property(): 308. 的子类，指明一个抽象特性属性。

     这个特例已被弃用，因为现在当 *note property(): 308. 装饰器应用于抽
     象方法时它会被正确地标识为抽象的:

          class C(ABC):
              @property
              @abstractmethod
              def my_abstract_property(self):
                  ...

     上面的例子定义了一个只读特征属性；你也可以通过适当地将一个或多个下
     层方法标记为抽象的来定义可读写的抽象特征属性:

          class C(ABC):
              @property
              def x(self):
                  ...

              @x.setter
              @abstractmethod
              def x(self, val):
                  ...

     如果只有某些组件是抽象的，则只需更新那些组件即可在子类中创建具体的
     特征属性:

          class D(C):
              @C.x.setter
              def x(self, val):
                  ...

*note abc: 3. 模块还提供了这些函数：

 -- 函式: abc.get_cache_token ()

     返回当前抽象基类的缓存令牌

     此令牌是一个不透明对象（支持相等性测试），用于为虚子类标识抽象基类
     缓存的当前版本。 此令牌会在任何 ABC 上每次调用 *note
     ABCMeta.register(): ab0. 时发生更改。

     3.4 版新加入.

註解
....

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/abc.py

   (2) https://www.python.org/dev/peps/pep-3119

   (3) https://www.python.org/dev/peps/pep-3141

   (4) (1) C++ 程序员需要注意：Python 中虚基类的概念和 C++ 中的并不相同
。


File: python.info,  Node: atexit --- 退出处理器,  Next: traceback --- 打印或检索堆栈回溯,  Prev: abc --- 抽象基类,  Up: Python运行时服务

5.29.9 ‘atexit’ — 退出处理器
----------------------------

__________________________________________________________________

*note atexit: b. 模块定义了清理函数的注册和反注册函数. 被注册的函数会在
解释器正常终止时执行.  *note atexit: b. 会按照注册顺序的*逆序*执行; 如果
你注册了 ‘A’, ‘B’ 和 ‘C’, 那么在解释器终止时会依序执行 ‘C’, ‘B’, ‘A’.

`注意:' 通过该模块注册的函数, 在程序被未被 Python 捕获的信号杀死时并不会
执行, 在检测到 Python 内部致命错误以及调用了 *note os._exit(): 1854. 时
也不会执行.

3.7 版更變: 当配合 C-API 子解释器使用时，已注册函数是它们所注册解释器中
的局部对象。

 -- 函式: atexit.register (func, *args, **kwargs)

     将 `func' 注册为终止时执行的函数.  任何传给 `func' 的可选的参数都应
     当作为参数传给 *note register(): f46.  可以多次注册同样的函数及参数
     .

     在正常的程序终止时 (举例来说, 当调用了 *note sys.exit(): daa. 或是
     主模块的执行完成时), 所有注册过的函数都会以后进先出的顺序执行. 这样
     做是假定更底层的模块通常会比高层模块更早引入, 因此需要更晚清理.

     如果在 exit 处理句柄执行期间引发了异常，将会打印回溯信息 (除非引发
     的是 *note SystemExit: 6f3.) 并且异常信息会被保存。 在所有 exit 处
     理句柄都获得运行机会之后，所引发的最后一个异常会被重新引发。

     这个函数返回 `func' 对象，可以把它当作装饰器使用。

 -- 函式: atexit.unregister (func)

     将 `func' 移出当解释器关闭时要运行的函数列表。 如果 `func' 之前未被
     注册则 *note unregister(): 3830. 将静默地不做任何事。 如果 `func' 已
     被注册一次以上，则该函数每次在 *note atexit: b. 调用栈中的出现都将
     被移除。 当取消注册时会在内部使用相等性比较 (‘==’)，因而函数引用不
     需要具有匹配的标识号。

也參考
......

模块 *note readline: de.

     使用 *note atexit: b. 读写 *note readline: de. 历史文件的有用的例子
     。

* Menu:

* atexit 示例::


File: python.info,  Node: atexit 示例,  Up: atexit --- 退出处理器

5.29.9.1 ‘atexit’ 示例
......................

以下简单例子演示了一个模块在被导入时如何从文件初始化一个计数器，并在程序
终结时自动保存计数器的更新值，此操作不依赖于应用在终结时对此模块进行显式
调用。:

     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)

位置和关键字参数也可传入 *note register(): f46. 以便传递给被调用的已注册
函数:

     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')

作为 *note decorator: 174.: 使用:

     import atexit

     @atexit.register
     def goodbye():
         print('You are now leaving the Python sector.')

只有在函数不需要任何参数调用时才能工作.


File: python.info,  Node: traceback --- 打印或检索堆栈回溯,  Next: __future__ --- Future 语句定义,  Prev: atexit --- 退出处理器,  Up: Python运行时服务

5.29.10 ‘traceback’ — 打印或检索堆栈回溯
----------------------------------------

`源代码：' Lib/traceback.py(1)

__________________________________________________________________

该模块提供了一个标准接口来提取、格式化和打印 Python 程序的堆栈跟踪结果。
它完全模仿Python 解释器在打印堆栈跟踪结果时的行为。当您想要在程序控制下
打印堆栈跟踪结果时，例如在“封装”解释器时，这是非常有用的。

这个模块使用 traceback 对象 —— 这是存储在 *note sys.last_traceback:
36d5. 中的对象类型变量，并作为 *note sys.exc_info(): d27. 的第三项被返回
。

这个模块定义了以下函数：

 -- 函式: traceback.print_tb (tb, limit=None, file=None)

     如果*limit*是正整数，那么从 traceback 对象 "tb" 输出最高 `limit' 个
     （从调用函数开始的）栈的堆栈回溯‎条目‎；如果 `limit' 是负数就输出
     ‘abs(limit)’ 个回溯条目；又如果 `limit' 被省略或者为 ‘None’，那么就
     会输出所有回溯条目。如果 `file' 被省略或为 ‘None’ 那么就会输出至标
     准输出‘‘sys.stderr‘‘否则它应该是一个打开的文件或者文件类对象来接收
     输出

     3.5 版更變: 添加了对负数值 `limit' 的支持

 -- 函式: traceback.print_exception (etype, value, tb, limit=None,
          file=None, chain=True)

     打印回溯对象 `tb' 到 `file' 的异常信息和整个堆栈回溯。这和 *note
     print_tb(): 868. 比有以下方面不同：

        * 如果 `tb' 不为 ‘None’，它将打印头部 ‘Traceback (most recent
          call last):’

        * 它将在输出完堆栈回溯后，输出异常中的 `etype' 和 `value' 信息

        * if `type(value)' is *note SyntaxError: 559. and `value' has
          the appropriate format, it prints the line where the syntax
          error occurred with a caret indicating the approximate
          position of the error.

     The optional `limit' argument has the same meaning as for *note
     print_tb(): 868.  If `chain' is true (the default), then chained
     exceptions (the ‘__cause__’ or ‘__context__’ attributes of the
     exception) will be printed as well, like the interpreter itself
     does when printing an unhandled exception.

     3.5 版更變: The `etype' argument is ignored and inferred from the
     type of `value'.

 -- 函式: traceback.print_exc (limit=None, file=None, chain=True)

     This is a shorthand for ‘print_exception(*sys.exc_info(), limit,
     file, chain)’.

 -- 函式: traceback.print_last (limit=None, file=None, chain=True)

     This is a shorthand for ‘print_exception(sys.last_type,
     sys.last_value, sys.last_traceback, limit, file, chain)’.  In
     general it will work only after an exception has reached an
     interactive prompt (see *note sys.last_type: d22.).

 -- 函式: traceback.print_stack (f=None, limit=None, file=None)

     Print up to `limit' stack trace entries (starting from the
     invocation point) if `limit' is positive.  Otherwise, print the
     last ‘abs(limit)’ entries.  If `limit' is omitted or ‘None’, all
     entries are printed.  The optional `f' argument can be used to
     specify an alternate stack frame to start.  The optional `file'
     argument has the same meaning as for *note print_tb(): 868.

     3.5 版更變: 添加了对负数值 `limit' 的支持

 -- 函式: traceback.extract_tb (tb, limit=None)

     Return a *note StackSummary: 866. object representing a list of
     "pre-processed" stack trace entries extracted from the traceback
     object `tb'.  It is useful for alternate formatting of stack
     traces.  The optional `limit' argument has the same meaning as for
     *note print_tb(): 868.  A "pre-processed" stack trace entry is a
     *note FrameSummary: 867. object containing attributes ‘filename’,
     ‘lineno’, ‘name’, and ‘line’ representing the information that is
     usually printed for a stack trace.  The ‘line’ is a string with
     leading and trailing whitespace stripped; if the source is not
     available it is ‘None’.

 -- 函式: traceback.extract_stack (f=None, limit=None)

     Extract the raw traceback from the current stack frame.  The return
     value has the same format as for *note extract_tb(): 3837.  The
     optional `f' and `limit' arguments have the same meaning as for
     *note print_stack(): 869.

 -- 函式: traceback.format_list (extracted_list)

     Given a list of tuples or *note FrameSummary: 867. objects as
     returned by *note extract_tb(): 3837. or *note extract_stack():
     3838, return a list of strings ready for printing.  Each string in
     the resulting list corresponds to the item with the same index in
     the argument list.  Each string ends in a newline; the strings may
     contain internal newlines as well, for those items whose source
     text line is not ‘None’.

 -- 函式: 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 ‘sys.last_type’ and
     ‘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 *note SyntaxError: 559. 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.

 -- 函式: traceback.format_exception (etype, value, tb, limit=None,
          chain=True)

     Format a stack trace and the exception information.  The arguments
     have the same meaning as the corresponding arguments to *note
     print_exception(): 2208.  The return value is a list of strings,
     each ending in a newline and some containing internal newlines.
     When these lines are concatenated and printed, exactly the same
     text is printed as does *note print_exception(): 2208.

     3.5 版更變: The `etype' argument is ignored and inferred from the
     type of `value'.

 -- 函式: traceback.format_exc (limit=None, chain=True)

     This is like ‘print_exc(limit)’ but returns a string instead of
     printing to a file.

 -- 函式: traceback.format_tb (tb, limit=None)

     A shorthand for ‘format_list(extract_tb(tb, limit))’.

 -- 函式: traceback.format_stack (f=None, limit=None)

     A shorthand for ‘format_list(extract_stack(f, limit))’.

 -- 函式: traceback.clear_frames (tb)

     Clears the local variables of all the stack frames in a traceback
     `tb' by calling the ‘clear()’ method of each frame object.

     3.4 版新加入.

 -- 函式: traceback.walk_stack (f)

     Walk a stack following ‘f.f_back’ from the given frame, yielding
     the frame and line number for each frame.  If `f' is ‘None’, the
     current stack is used.  This helper is used with *note
     StackSummary.extract(): 383d.

     3.5 版新加入.

 -- 函式: traceback.walk_tb (tb)

     Walk a traceback following ‘tb_next’ yielding the frame and line
     number for each frame.  This helper is used with *note
     StackSummary.extract(): 383d.

     3.5 版新加入.

The module also defines the following classes:

* Menu:

* TracebackException Objects::
* StackSummary Objects::
* FrameSummary Objects::
* Traceback Examples::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/traceback.py


File: python.info,  Node: TracebackException Objects,  Next: StackSummary Objects,  Up: traceback --- 打印或检索堆栈回溯

5.29.10.1 ‘TracebackException’ Objects
......................................

3.5 版新加入.

*note TracebackException: 865. objects are created from actual
exceptions to capture data for later printing in a lightweight fashion.

 -- 類別: traceback.TracebackException (exc_type, exc_value,
          exc_traceback, *, limit=None, lookup_lines=True,
          capture_locals=False)

     Capture an exception for later rendering.  `limit', `lookup_lines'
     and `capture_locals' are as for the *note StackSummary: 866. class.

     Note that when locals are captured, they are also shown in the
     traceback.

      -- 屬性: __cause__

          A *note TracebackException: 865. of the original ‘__cause__’.

      -- 屬性: __context__

          A *note TracebackException: 865. of the original
          ‘__context__’.

      -- 屬性: __suppress_context__

          The ‘__suppress_context__’ value from the original exception.

      -- 屬性: stack

          A *note StackSummary: 866. representing the traceback.

      -- 屬性: exc_type

          The class of the original traceback.

      -- 屬性: filename

          For syntax errors - the file name where the error occurred.

      -- 屬性: lineno

          For syntax errors - the line number where the error occurred.

      -- 屬性: text

          For syntax errors - the text where the error occurred.

      -- 屬性: offset

          For syntax errors - the offset into the text where the error
          occurred.

      -- 屬性: msg

          For syntax errors - the compiler error message.

      -- 成員函式: classmethod from_exception (exc, *, limit=None,
               lookup_lines=True, capture_locals=False)

          Capture an exception for later rendering.  `limit',
          `lookup_lines' and `capture_locals' are as for the *note
          StackSummary: 866. class.

          Note that when locals are captured, they are also shown in the
          traceback.

      -- 成員函式: format (*, chain=True)

          Format the exception.

          If `chain' is not ‘True’, ‘__cause__’ and ‘__context__’ will
          not be formatted.

          The return value is a generator of strings, each ending in a
          newline and some containing internal newlines.  *note
          print_exception(): 2208. is a wrapper around this method which
          just prints the lines to a file.

          The message indicating which exception occurred is always the
          last string in the output.

      -- 成員函式: format_exception_only ()

          Format the exception part of the traceback.

          The return value is a generator of strings, each ending in a
          newline.

          Normally, the generator emits a single string; however, for
          *note SyntaxError: 559. exceptions, it emits several lines
          that (when printed) display detailed information about where
          the syntax error occurred.

          The message indicating which exception occurred is always the
          last string in the output.


File: python.info,  Node: StackSummary Objects,  Next: FrameSummary Objects,  Prev: TracebackException Objects,  Up: traceback --- 打印或检索堆栈回溯

5.29.10.2 ‘StackSummary’ Objects
................................

3.5 版新加入.

*note StackSummary: 866. objects represent a call stack ready for
formatting.

 -- 類別: traceback.StackSummary

      -- 成員函式: classmethod extract (frame_gen, *, limit=None,
               lookup_lines=True, capture_locals=False)

          Construct a *note StackSummary: 866. object from a frame
          generator (such as is returned by *note walk_stack(): 863. or
          *note walk_tb(): 864.).

          If `limit' is supplied, only this many frames are taken from
          `frame_gen'.  If `lookup_lines' is ‘False’, the returned *note
          FrameSummary: 867. objects will not have read their lines in
          yet, making the cost of creating the *note StackSummary: 866.
          cheaper (which may be valuable if it may not actually get
          formatted).  If `capture_locals' is ‘True’ the local variables
          in each *note FrameSummary: 867. are captured as object
          representations.

      -- 成員函式: classmethod from_list (a_list)

          Construct a *note StackSummary: 866. object from a supplied
          list of *note FrameSummary: 867. objects or old-style list of
          tuples.  Each tuple should be a 4-tuple with filename, lineno,
          name, line as the elements.

      -- 成員函式: format ()

          Returns a list of strings ready for printing.  Each string in
          the resulting list corresponds to a single frame from the
          stack.  Each string ends in a newline; the strings may contain
          internal newlines as well, for those items with source text
          lines.

          For long sequences of the same frame and line, the first few
          repetitions are shown, followed by a summary line stating the
          exact number of further repetitions.

          3.6 版更變: Long sequences of repeated frames are now
          abbreviated.


File: python.info,  Node: FrameSummary Objects,  Next: Traceback Examples,  Prev: StackSummary Objects,  Up: traceback --- 打印或检索堆栈回溯

5.29.10.3 ‘FrameSummary’ Objects
................................

3.5 版新加入.

*note FrameSummary: 867. objects represent a single frame in a
traceback.

 -- 類別: traceback.FrameSummary (filename, lineno, name,
          lookup_line=True, locals=None, line=None)

     Represent a single frame in the traceback or stack that is being
     formatted or printed.  It may optionally have a stringified version
     of the frames locals included in it.  If `lookup_line' is ‘False’,
     the source code is not looked up until the *note FrameSummary: 867.
     has the ‘line’ attribute accessed (which also happens when casting
     it to a tuple).  ‘line’ may be directly provided, and will prevent
     line lookups happening at all.  `locals' is an optional local
     variable dictionary, and if supplied the variable representations
     are stored in the summary for later display.


File: python.info,  Node: Traceback Examples,  Prev: FrameSummary Objects,  Up: traceback --- 打印或检索堆栈回溯

5.29.10.4 Traceback Examples
............................

This simple example implements a basic read-eval-print loop, similar to
(but less useful than) the standard Python interactive interpreter loop.
For a more complete implementation of the interpreter loop, refer to the
*note code: 1a. module.

     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)

The following example demonstrates the different ways to print and
format the exception and traceback:

     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)

The output for the example would look similar to this:

     *** 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

The following example shows the different ways to print and format the
stack:

     >>> 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']

This last example demonstrates the final few formatting functions:

     >>> 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']


File: python.info,  Node: __future__ --- Future 语句定义,  Next: gc --- 垃圾回收器接口,  Prev: traceback --- 打印或检索堆栈回溯,  Up: Python运行时服务

5.29.11 ‘__future__’ — Future 语句定义
--------------------------------------

`源代码：' Lib/__future__.py(1)

__________________________________________________________________

*note __future__: 0. 是一个真正的模块，这主要有 3 个原因：

   * 避免混淆已有的分析 import 语句并查找 import 的模块的工具。

   * 确保 *note future 语句: 16c4. 在 2.1 之前的版本运行时至少能抛出
     runtime 异常（import *note __future__: 0. 会失败，因为 2.1 版本之前
     没有这个模块）。

   * 当引入不兼容的修改时，可以记录其引入的时间以及强制使用的时间。这是
     一种可执行的文档，并且可以通过 import *note __future__: 0. 来做程序
     性的检查。

‘__future__.py’ 中的每一条语句都是以下格式的：

     FeatureName = _Feature(OptionalRelease, MandatoryRelease,
                            CompilerFlag)

通常 `OptionalRelease' 要比 `MandatoryRelease' 小，并且都是和 *note
sys.version_info: bed. 格式一致的 5 元素元组。

     (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
     )

`OptionalRelease' 记录了一个特性首次发布时的 Python 版本。

在 `MandatoryRelases' 还没有发布时，`MandatoryRelease' 表示该特性会变成
语言的一部分的预测时间。

其他情况下，`MandatoryRelease' 用来记录这个特性是何时成为语言的一部分的
。从该版本往后，使用该特性将不需要 future 语句，不过很多人还是会加上对应
的 import。

`MandatoryRelease' 也可能是 ‘None’, 表示这个特性已经被撤销。

‘_Feature’ 类的实例有两个对应的方法，‘getOptionalRelease()’ 和
‘getMandatoryRelease()’。

`CompilerFlag' 是一个（位）标记，对于动态编译的代码，需要将这个标记作为
第四个参数传入内建函数 *note compile(): 2e7. 中以开启对应的特性。这个标
记存储在 ‘_Feature’ 类实例的 ‘compiler_flag’ 属性中。

*note __future__: 0. 中不会删除特性的描述。从 Python 2.1 中首次加入以来
，通过这种方式引入了以下特性：

特性                   可选版本          强制加入版本       效果
                                                            
--------------------------------------------------------------------------------------------------------------
                                                            
nested_scopes          2.1.0b1           2.2                PEP 227(2): `Statically Nested Scopes'
                                                            
                                                            
generators             2.2.0a1           2.3                PEP 255(3): `Simple Generators'
                                                            
                                                            
division               2.2.0a2           3.0                PEP 238(4): `Changing the Division Operator'
                                                            
                                                            
absolute_import        2.5.0a1           3.0                PEP 328(5): `Imports: Multi-Line and
                                                            Absolute/Relative'
                                                            
                                                            
with_statement         2.5.0a1           2.6                PEP 343(6): `The "with" Statement'
                                                            
                                                            
print_function         2.6.0a2           3.0                PEP 3105(7): `Make print a function'
                                                            
                                                            
unicode_literals       2.6.0a2           3.0                PEP 3112(8): `Bytes literals in Python 3000'
                                                            
                                                            
generator_stop         3.5.0b1           3.7                PEP 479(9): `StopIteration handling inside
                                                            generators'
                                                            
                                                            
annotations            3.7.0b1           3.10               PEP 563(10): `Postponed evaluation of
                                                            annotations'
                                                            

也參考
......

*note future 语句: 16c4.

     编译器怎样处理 future import。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/__future__.py

   (2) https://www.python.org/dev/peps/pep-0227

   (3) https://www.python.org/dev/peps/pep-0255

   (4) https://www.python.org/dev/peps/pep-0238

   (5) https://www.python.org/dev/peps/pep-0328

   (6) https://www.python.org/dev/peps/pep-0343

   (7) https://www.python.org/dev/peps/pep-3105

   (8) https://www.python.org/dev/peps/pep-3112

   (9) https://www.python.org/dev/peps/pep-0479

   (10) https://www.python.org/dev/peps/pep-0563


File: python.info,  Node: gc --- 垃圾回收器接口,  Next: inspect --- 检查对象,  Prev: __future__ --- Future 语句定义,  Up: Python运行时服务

5.29.12 ‘gc’ — 垃圾回收器接口
-----------------------------

__________________________________________________________________

此模块提供可选的垃圾回收器的接口，提供的功能包括：关闭收集器、调整收集频
率、设置调试选项。它同时提供对回收器找到但是无法释放的不可达对象的访问。
由于 Python 使用了带有引用计数的回收器，如果你确定你的程序不会产生循环引
用，你可以关闭回收器。可以通过调用 ‘gc.disable()’ 关闭自动垃圾回收。若要
调试一个存在内存泄漏的程序，调用 ‘gc.set_debug(gc.DEBUG_LEAK)’ ；需要注
意的是，它包含 ‘gc.DEBUG_SAVEALL’ ，使得被垃圾回收的对象会被存放在
gc.garbage 中以待检查。

*note gc: 84. 模块提供下列函数：

 -- 函式: gc.enable ()

     启用自动垃圾回收

 -- 函式: gc.disable ()

     停用自动垃圾回收

 -- 函式: gc.isenabled ()

     如果启用了自动回收则返回 ‘True’。

 -- 函式: gc.collect (generation=2)

     若被调用时不包含参数，则启动完全的垃圾回收。可选的参数 `generation'
     可以是一个整数，指明需要回收哪一代（从 0 到 2 ）的垃圾。当参数
     `generation' 无效时，会引发 *note ValueError: 16d. 异常。返回发现的
     不可达对象的数目。

     每当运行完整收集或最高代 (2) 收集时，为多个内置类型所维护的空闲列表
     会被清空。 由于特定类型特别是 *note float: 1fd. 的实现，在某些空闲
     列表中并非所有项都会被释放。

 -- 函式: gc.set_debug (flags)

     设置垃圾回收器的调试标识位。调试信息会被写入 ‘sys.stderr’ 。此文档
     末尾列出了各个标志位及其含义；可以使用位操作对多个标志位进行设置以
     控制调试器。

 -- 函式: gc.get_debug ()

     返回当前调试标识位。

 -- 函式: gc.get_objects (generation=None)

     返回一个收集器所跟踪的所有对象的列表，所返回的列表除外。 如果
     `generation' 不为 None，则只返回收集器所跟踪的属于该生成的对象。

     3.8 版更變: 新的 `generation' 形参。

     引发一个 *note 审计事件: fa1. ‘gc.get_objects’，附带参数
     ‘generation’。

 -- 函式: gc.get_stats ()

     返回一个包含三个字典对象的列表，每个字典分别包含对应代的从解释器开
     始运行的垃圾回收统计数据。字典的键的数目在将来可能发生改变，目前每
     个字典包含以下内容：

        * ‘collections’ 是该代被回收的次数；

        * ‘collected’ 是该代中被回收的对象总数；

        * ‘uncollectable’ 是在这一代中被发现无法收集的对象总数 （因此被
          移动到 *note garbage: c12. 列表中）。

     3.4 版新加入.

 -- 函式: gc.set_threshold (threshold0[, threshold1[, threshold2]])

     设置垃圾回收阈值（收集频率）。 将 `threshold0' 设为零会禁用回收。

     垃圾回收器把所有对象分类为三代，其依据是对象在多少次垃圾回收后幸存
     。 新建对象会被放在最年轻代（第 ‘0’ 代）。 如果一个对象在一次垃圾回
     收后幸存，它会被移入下一个较老代。 由于第 ‘2’ 代是最老代，这一代的
     对象在一次垃圾回收后仍会保留原样。 为了确定何时要运行，垃圾回收器会
     跟踪自上一次回收后对象分配和释放的数量。 当分配数量减去释放数量的结
     果值大于 `threshold0' 时，垃圾回收就会开始。 初始时只有第 ‘0’ 代会
     被检查。 如果自第 ‘1’ 代被检查后第 ‘0’ 代已被检查超过 `threshold1'
     次，则第 ‘1’ 也会被检查。 对于第三代来说情况还会更复杂，请参阅
     Collecting the oldest generation(1) 来了解详情。

 -- 函式: gc.get_count ()

     将当前回收计数以形为 ‘(count0, count1, count2)’ 的元组返回。

 -- 函式: gc.get_threshold ()

     将当前回收阈值以形为 ‘(threshold0, threshold1, threshold2)’ 的元组
     返回。

 -- 函式: gc.get_referrers (*objs)

     返回直接引用任意一个 `ojbs' 的对象列表。这个函数只定位支持垃圾回收
     的容器；引用了其它对象但不支持垃圾回收的扩展类型不会被找到。

     需要注意的是，已经解除对 `objs' 引用的对象，但仍存在于循环引用中未
     被回收时，仍然会被作为引用者出现在返回的列表当中。若要获取当前正在
     引用 `objs' 的对象，需要调用 *note collect(): 35b. 然后再调用 *note
     get_referrers(): fb6. 。

          警告: 在使用 *note get_referrers(): fb6. 返回的对象时必须要小
          心，因为其中一些对象可能仍在构造中因此处于暂时的无效状态。不要
          把 *note get_referrers(): fb6. 用于调试以外的其它目的。

     引发一个 *note 审计事件: fa1. ‘gc.get_referrers’，附带参数 ‘objs’。

 -- 函式: gc.get_referents (*objs)

     返回被任意一个参数中的对象直接引用的对象的列表。返回的被引用对象是
     被参数中的对象的C语言级别方法（若存在） *note tp_traverse: 23b. 访
     问到的对象，可能不是所有的实际直接可达对象。只有支持垃圾回收的对象
     支持 *note tp_traverse: 23b.  方法，并且此方法只会在需要访问涉及循
     环引用的对象时使用。因此，可以有以下例子：一个整数对其中一个参数是
     直接可达的，这个整数有可能出现或不出现在返回的结果列表当中。

     引发一个 *note 审计事件: fa1. ‘gc.get_referents’，附带参数 ‘objs’。

 -- 函式: gc.is_tracked (obj)

     当对象正在被垃圾回收器监控时返回 ‘True’ ，否则返回 ‘False’ 。一般来
     说，原子类的实例不会被监控，而非原子类（如容器、用户自定义的对象）
     会被监控。然而，会有一些特定类型的优化以便减少垃圾回收器在简单实例
     （如只含有原子性的键和值的字典）上的消耗。

          >>> 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

     3.1 版新加入.

 -- 函式: gc.is_finalized (obj)

     如果给定对象已被垃圾回收器终结则返回 ‘True’，否则返回 ‘False’。

          >>> 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

     3.9 版新加入.

 -- 函式: gc.freeze ()

     冻结 gc 所跟踪的所有对象 —— 将它们移至永久代并忽略所有未来的集合。
     这可以在 POSIX fork() 调用之前使用以便令对写入复制保持友好或加速收
     集。 并且在 POSIX fork() 调用之前的收集也可以释放页面以供未来分配，
     这也可能导致写入时复制，因此建议在主进程中禁用 gc 并在 fork 之前冻
     结，而在子进程中启用 gc。

     3.7 版新加入.

 -- 函式: gc.unfreeze ()

     解冻永久代中的对象，并将它们放回到年老代中。

     3.7 版新加入.

 -- 函式: gc.get_freeze_count ()

     返回永久代中的对象数量。

     3.7 版新加入.

提供以下变量仅供只读访问（你可以修改但不应该重绑定它们）：

 -- Data: gc.garbage

     一个回收器发现不可达而又无法被释放的对象（不可回收对象）列表。 从
     Python 3.4 开始，该列表在大多数时候都应该是空的，除非使用了含有非
     ‘NULL’ ‘tp_del’ 空位的 C 扩展类型的实例。

     如果设置了 *note DEBUG_SAVEALL: 385e. ，则所有不可访问对象将被添加
     至该列表而不会被释放。

     3.2 版更變: 当 *note interpreter shutdown: 852. 即解释器关闭时，若
     此列表非空，会产生 *note ResourceWarning: 5ca. ，即资源警告，在默认
     情况下此警告不会被提醒。如果设置了 *note DEBUG_UNCOLLECTABLE:
     c13. ，所有无法被回收的对象会被打印。

     3.4 版更變: 根据 PEP 442(2) ，带有 *note __del__(): a04. 方法的对象
     最终不再会进入 *note gc.garbage: c12. 。

 -- Data: gc.callbacks

     在垃圾回收器开始前和完成后会被调用的一系列回调函数。这些回调函数在
     被调用时使用两个参数： `phase' 和 `info' 。

     `phase' 可为以下两值之一：

          "start": 垃圾回收即将开始。

          "stop": 垃圾回收已结束。

     `info' is a dict providing more information for the callback.  The
     following keys are currently defined:

          "generation"（代） ：正在被回收的最久远的一代。

          "collected"（已回收的 ）: 当*phase* 为 "stop" 时，被成功回收的
          对象的数目。

          "uncollectable"（不可回收的）: 当 `phase' 为 "stop" 时，不能被
          回收并被放入 *note garbage: c12. 的对象的数目。

     应用程序可以把他们自己的回调函数加入此列表。主要的使用场景有：

          统计垃圾回收的数据，如：不同代的回收频率、回收所花费的时间。

          使应用程序可以识别和清理他们自己的在 *note garbage: c12. 中的
          不可回收类型的对象。

     3.3 版新加入.

以下常量被用于 *note set_debug(): 3859. ：

 -- Data: gc.DEBUG_STATS

     在回收完成后打印统计信息。当回收频率设置较高时，这些信息会比较有用
     。

 -- Data: gc.DEBUG_COLLECTABLE

     当发现可回收对象时打印信息。

 -- Data: gc.DEBUG_UNCOLLECTABLE

     打印找到的不可回收对象的信息（指不能被回收器回收的不可达对象）。这
     些对象会被添加到 ‘garbage’ 列表中。

     3.2 版更變: 当 *note interpreter shutdown: 852. 时，即解释器关闭时
     ，若 *note garbage: c12. 列表中存在对象，这些对象也会被打印输出。

 -- Data: gc.DEBUG_SAVEALL

     设置后，所有回收器找到的不可达对象会被添加进 `garbage' 而不是直接被
     释放。这在调试一个内存泄漏的程序时会很有用。

 -- Data: gc.DEBUG_LEAK

     调试内存泄漏的程序时，使回收器打印信息的调试标识位。（等价于
     ‘DEBUG_COLLECTABLE | DEBUG_UNCOLLECTABLE | DEBUG_SAVEALL’ ）。

   ---------- Footnotes ----------

   (1) 
https://devguide.python.org/garbage_collector/#collecting-the-oldest-generation

   (2) https://www.python.org/dev/peps/pep-0442


File: python.info,  Node: inspect --- 检查对象,  Next: site —— 指定域的配置钩子,  Prev: gc --- 垃圾回收器接口,  Up: Python运行时服务

5.29.13 ‘inspect’ — 检查对象
----------------------------

`源代码:' Lib/inspect.py(1)

__________________________________________________________________

*note inspect: a0. 模块提供了一些有用的函数帮助获取对象的信息，例如模块
、类、方法、函数、回溯、帧对象以及代码对象。例如它可以帮助你检查类的内容
，获取某个方法的源代码，取得并格式化某个函数的参数列表，或者获取你需要显
示的回溯的详细信息。

该模块提供了4种主要的功能：类型检查、获取源代码、检查类与函数、检查解释
器的调用堆栈。

* Menu:

* 类型和成员::
* Retrieving source code::
* Introspecting callables with the Signature object::
* 类与函数: 类与函数<2>.
* The interpreter stack::
* Fetching attributes statically::
* Current State of Generators and Coroutines::
* Code Objects Bit Flags::
* 命令行界面: 命令行界面<5>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/inspect.py


File: python.info,  Node: 类型和成员,  Next: Retrieving source code,  Up: inspect --- 检查对象

5.29.13.1 类型和成员
....................

*note getmembers(): 3866. 函数获取对象的成员，例如类或模块。函数名以
"is"开始的函数主要作为 *note getmembers(): 3866. 的第2个参数使用。它们也
可用于判定某对象是否有如下的特殊属性:

类型            属性                    描述
                                        
------------------------------------------------------------------------
                                        
module 模块     __doc__                 文档字符串
                                        
                                        
                __file__                文件名(内置模块没有文件名)
                                        
                                        
class 类        __doc__                 文档字符串
                                        
                                        
                __name__                类定义时所使用的名称
                                        
                                        
                __qualname__            qualified name – 限定名称
                                        
                                        
                __module__              该类型被定义时所在的模块的名
                                        称
                                        
                                        
method 方法     __doc__                 文档字符串
                                        
                                        
                __name__                该方法定义时所使用的名称
                                        
                                        
                __qualname__            qualified name – 限定名称
                                        
                                        
                __func__                实现该方法的函数对象
                                        
                                        
                __self__                该方法被绑定的实例，若没有绑
                                        定则为 ‘None’
                                        
                                        
                __module__              定义此方法的模块的名称
                                        
                                        
函数            __doc__                 文档字符串
                                        
                                        
                __name__                用于定义此函数的名称
                                        
                                        
                __qualname__            qualified name – 限定名称
                                        
                                        
                __code__                包含已编译函数的代码对象
                                        *note bytecode: 709.
                                        
                                        
                __defaults__            所有位置或关键字参数的默认值
                                        的元组
                                        
                                        
                __kwdefaults__          mapping of any default values
                                        for keyword-only parameters
                                        
                                        
                __globals__             global namespace in which
                                        this function was defined
                                        
                                        
                __annotations__         mapping of parameters names
                                        to annotations; ‘"return"’
                                        key is reserved for return
                                        annotations.
                                        
                                        
                __module__              name of module in which this
                                        function was defined
                                        
                                        
回溯            tb_frame                此级别的框架对象
                                        
                                        
                tb_lasti                index of last attempted
                                        instruction in bytecode
                                        
                                        
                tb_lineno               current line number in Python
                                        source code
                                        
                                        
                tb_next                 next inner traceback object
                                        (called by this level)
                                        
                                        
框架            f_back                  next outer frame object (this
                                        frame’s caller)
                                        
                                        
                f_builtins              builtins namespace seen by
                                        this frame
                                        
                                        
                f_code                  code object being executed in
                                        this frame
                                        
                                        
                f_globals               global namespace seen by this
                                        frame
                                        
                                        
                f_lasti                 index of last attempted
                                        instruction in bytecode
                                        
                                        
                f_lineno                current line number in Python
                                        source code
                                        
                                        
                f_locals                local namespace seen by this
                                        frame
                                        
                                        
                f_trace                 tracing function for this
                                        frame, or ‘None’
                                        
                                        
code            co_argcount             number of arguments (not
                                        including keyword only
                                        arguments, * or ** args)
                                        
                                        
                co_code                 原始编译字节码的字符串
                                        
                                        
                co_cellvars             单元变量名称的元组(通过包含作
                                        用域引用)
                                        
                                        
                co_consts               字节码中使用的常量元组
                                        
                                        
                co_filename             创建此代码对象的文件的名称
                                        
                                        
                co_firstlineno          number of first line in
                                        Python source code
                                        
                                        
                co_flags                bitmap of ‘CO_*’ flags, read
                                        more *note here: 3867.
                                        
                                        
                co_lnotab               编码的行号到字节码索引的映射
                                        
                                        
                co_freevars             tuple of names of free
                                        variables (referenced via a
                                        function’s closure)
                                        
                                        
                co_posonlyargcount      number of positional only
                                        arguments
                                        
                                        
                co_kwonlyargcount       number of keyword only
                                        arguments (not including **
                                        arg)
                                        
                                        
                co_name                 定义此代码对象的名称
                                        
                                        
                co_names                局部变量名称的元组
                                        
                                        
                co_nlocals              局部变量的数量
                                        
                                        
                co_stacksize            需要虚拟机堆栈空间
                                        
                                        
                co_varnames             参数名和局部变量的元组
                                        
                                        
生成器          __name__                名称
                                        
                                        
                __qualname__            qualified name – 限定名称
                                        
                                        
                gi_frame                框架
                                        
                                        
                gi_running              生成器在运行吗？
                                        
                                        
                gi_code                 code
                                        
                                        
                gi_yieldfrom            object being iterated by
                                        ‘yield from’, or ‘None’
                                        
                                        
协程            __name__                名称
                                        
                                        
                __qualname__            qualified name – 限定名称
                                        
                                        
                cr_await                object being awaited on, or
                                        ‘None’
                                        
                                        
                cr_frame                框架
                                        
                                        
                cr_running              is the coroutine running?
                                        
                                        
                cr_code                 code
                                        
                                        
                cr_origin               where coroutine was created,
                                        or ‘None’.  See
                                        *note sys.set_coroutine_origin_tracking_depth(): 4f8.
                                        
                                        
builtin         __doc__                 文档字符串
                                        
                                        
                __name__                此函数或方法的原始名称
                                        
                                        
                __qualname__            qualified name – 限定名称
                                        
                                        
                __self__                instance to which a method is
                                        bound, or ‘None’
                                        

3.5 版更變: Add ‘__qualname__’ and ‘gi_yieldfrom’ attributes to
generators.

The ‘__name__’ attribute of generators is now set from the function
name, instead of the code name, and it can now be modified.

3.7 版更變: Add ‘cr_origin’ attribute to coroutines.

 -- 函式: inspect.getmembers (object[, predicate])

     Return all the members of an object in a list of ‘(name, value)’
     pairs sorted by name.  If the optional `predicate' argument—which
     will be called with the ‘value’ object of each member—is supplied,
     only members for which the predicate returns a true value are
     included.

          備註: *note getmembers(): 3866. will only return class
          attributes defined in the metaclass when the argument is a
          class and those attributes have been listed in the metaclass’
          custom *note __dir__(): 42b.

 -- 函式: inspect.getmodulename (path)

     Return the name of the module named by the file `path', without
     including the names of enclosing packages.  The file extension is
     checked against all of the entries in *note
     importlib.machinery.all_suffixes(): 3868.  If it matches, the final
     path component is returned with the extension removed.  Otherwise,
     ‘None’ is returned.

     Note that this function `only' returns a meaningful name for actual
     Python modules - paths that potentially refer to Python packages
     will still return ‘None’.

     3.3 版更變: The function is based directly on *note importlib: 9a.

 -- 函式: inspect.ismodule (object)

     Return ‘True’ if the object is a module.

 -- 函式: inspect.isclass (object)

     Return ‘True’ if the object is a class, whether built-in or created
     in Python code.

 -- 函式: inspect.ismethod (object)

     Return ‘True’ if the object is a bound method written in Python.

 -- 函式: inspect.isfunction (object)

     Return ‘True’ if the object is a Python function, which includes
     functions created by a *note lambda: 1ca8. expression.

 -- 函式: inspect.isgeneratorfunction (object)

     Return ‘True’ if the object is a Python generator function.

     3.8 版更變: Functions wrapped in *note functools.partial(): 8b5.
     now return ‘True’ if the wrapped function is a Python generator
     function.

 -- 函式: inspect.isgenerator (object)

     Return ‘True’ if the object is a generator.

 -- 函式: inspect.iscoroutinefunction (object)

     Return ‘True’ if the object is a *note coroutine function: 732. (a
     function defined with an *note async def: 3a9. syntax).

     3.5 版新加入.

     3.8 版更變: Functions wrapped in *note functools.partial(): 8b5.
     now return ‘True’ if the wrapped function is a *note coroutine
     function: 732.

 -- 函式: inspect.iscoroutine (object)

     Return ‘True’ if the object is a *note coroutine: 18a. created by
     an *note async def: 3a9. function.

     3.5 版新加入.

 -- 函式: inspect.isawaitable (object)

     Return ‘True’ if the object can be used in *note await: 2d8.
     expression.

     Can also be used to distinguish generator-based coroutines from
     regular generators:

          def gen():
              yield
          @types.coroutine
          def gen_coro():
              yield

          assert not isawaitable(gen())
          assert isawaitable(gen_coro())

     3.5 版新加入.

 -- 函式: inspect.isasyncgenfunction (object)

     Return ‘True’ if the object is an *note asynchronous generator:
     1640. function, for example:

          >>> async def agen():
          ...     yield 1
          ...
          >>> inspect.isasyncgenfunction(agen)
          True

     3.6 版新加入.

     3.8 版更變: Functions wrapped in *note functools.partial(): 8b5.
     now return ‘True’ if the wrapped function is a *note asynchronous
     generator: 1640. function.

 -- 函式: inspect.isasyncgen (object)

     Return ‘True’ if the object is an *note asynchronous generator
     iterator: 37d7. created by an *note asynchronous generator: 1640.
     function.

     3.6 版新加入.

 -- 函式: inspect.istraceback (object)

     Return ‘True’ if the object is a traceback.

 -- 函式: inspect.isframe (object)

     Return ‘True’ if the object is a frame.

 -- 函式: inspect.iscode (object)

     Return ‘True’ if the object is a code.

 -- 函式: inspect.isbuiltin (object)

     Return ‘True’ if the object is a built-in function or a bound
     built-in method.

 -- 函式: inspect.isroutine (object)

     Return ‘True’ if the object is a user-defined or built-in function
     or method.

 -- 函式: inspect.isabstract (object)

     Return ‘True’ if the object is an abstract base class.

 -- 函式: inspect.ismethoddescriptor (object)

     Return ‘True’ if the object is a method descriptor, but not if
     *note ismethod(): 386b, *note isclass(): 386a, *note isfunction():
     386c. or *note isbuiltin(): 3872. are true.

     This, for example, is true of ‘int.__add__’.  An object passing
     this test has a *note __get__(): 156e. method but not a *note
     __set__(): 1572. method, but beyond that the set of attributes
     varies.  A *note __name__: d2f. attribute is usually sensible, and
     ‘__doc__’ often is.

     Methods implemented via descriptors that also pass one of the other
     tests return ‘False’ from the *note ismethoddescriptor(): 3875.
     test, simply because the other tests promise more – you can, e.g.,
     count on having the ‘__func__’ attribute (etc) when an object
     passes *note ismethod(): 386b.

 -- 函式: inspect.isdatadescriptor (object)

     Return ‘True’ if the object is a data descriptor.

     Data descriptors have a *note __set__: 1572. or a *note __delete__:
     1573. method.  Examples are properties (defined in Python),
     getsets, and members.  The latter two are defined in C and there
     are more specific tests available for those types, which is robust
     across Python implementations.  Typically, data descriptors will
     also have *note __name__: d2f. and ‘__doc__’ attributes
     (properties, getsets, and members have both of these attributes),
     but this is not guaranteed.

 -- 函式: inspect.isgetsetdescriptor (object)

     Return ‘True’ if the object is a getset descriptor.

     `CPython implementation detail:' getsets are attributes defined in
     extension modules via *note PyGetSetDef: 52a. structures.  For
     Python implementations without such types, this method will always
     return ‘False’.

 -- 函式: inspect.ismemberdescriptor (object)

     Return ‘True’ if the object is a member descriptor.

     `CPython implementation detail:' Member descriptors are attributes
     defined in extension modules via *note PyMemberDef: 529.
     structures.  For Python implementations without such types, this
     method will always return ‘False’.


File: python.info,  Node: Retrieving source code,  Next: Introspecting callables with the Signature object,  Prev: 类型和成员,  Up: inspect --- 检查对象

5.29.13.2 Retrieving source code
................................

 -- 函式: inspect.getdoc (object)

     Get the documentation string for an object, cleaned up with *note
     cleandoc(): 387b.  If the documentation string for an object is not
     provided and the object is a class, a method, a property or a
     descriptor, retrieve the documentation string from the inheritance
     hierarchy.

     3.5 版更變: Documentation strings are now inherited if not
     overridden.

 -- 函式: inspect.getcomments (object)

     Return in a single string any lines of comments immediately
     preceding the object’s source code (for a class, function, or
     method), or at the top of the Python source file (if the object is
     a module).  If the object’s source code is unavailable, return
     ‘None’.  This could happen if the object has been defined in C or
     the interactive shell.

 -- 函式: inspect.getfile (object)

     Return the name of the (text or binary) file in which an object was
     defined.  This will fail with a *note TypeError: 1fe. if the object
     is a built-in module, class, or function.

 -- 函式: inspect.getmodule (object)

     Try to guess which module an object was defined in.

 -- 函式: inspect.getsourcefile (object)

     Return the name of the Python source file in which an object was
     defined.  This will fail with a *note TypeError: 1fe. if the object
     is a built-in module, class, or function.

 -- 函式: inspect.getsourcelines (object)

     Return a list of source lines and starting line number for an
     object.  The argument may be a module, class, method, function,
     traceback, frame, or code object.  The source code is returned as a
     list of the lines corresponding to the object and the line number
     indicates where in the original source file the first line of code
     was found.  An *note OSError: 304. is raised if the source code
     cannot be retrieved.

     3.3 版更變: *note OSError: 304. is raised instead of *note IOError:
     a73, now an alias of the former.

 -- 函式: inspect.getsource (object)

     Return the text of the source code for an object.  The argument may
     be a module, class, method, function, traceback, frame, or code
     object.  The source code is returned as a single string.  An *note
     OSError: 304. is raised if the source code cannot be retrieved.

     3.3 版更變: *note OSError: 304. is raised instead of *note IOError:
     a73, now an alias of the former.

 -- 函式: inspect.cleandoc (doc)

     Clean up indentation from docstrings that are indented to line up
     with blocks of code.

     All leading whitespace is removed from the first line.  Any leading
     whitespace that can be uniformly removed from the second line
     onwards is removed.  Empty lines at the beginning and end are
     subsequently removed.  Also, all tabs are expanded to spaces.


File: python.info,  Node: Introspecting callables with the Signature object,  Next: 类与函数<2>,  Prev: Retrieving source code,  Up: inspect --- 检查对象

5.29.13.3 Introspecting callables with the Signature object
...........................................................

3.3 版新加入.

The Signature object represents the call signature of a callable object
and its return annotation.  To retrieve a Signature object, use the
*note signature(): 655. function.

 -- 函式: inspect.signature (callable, *, follow_wrapped=True)

     Return a *note Signature: 7e4. object for the given ‘callable’:

          >>> 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'>

     Accepts a wide range of Python callables, from plain functions and
     classes to *note functools.partial(): 8b5. objects.

     Raises *note ValueError: 16d. if no signature can be provided, and
     *note TypeError: 1fe. if that type of object is not supported.

     A slash(/) in the signature of a function denotes that the
     parameters prior to it are positional-only.  For more info, see
     *note the FAQ entry on positional-only parameters: 1729.

     3.5 版新加入: ‘follow_wrapped’ parameter.  Pass ‘False’ to get a
     signature of ‘callable’ specifically (‘callable.__wrapped__’ will
     not be used to unwrap decorated callables.)

          備註: Some callables may not be introspectable in certain
          implementations of Python.  For example, in CPython, some
          built-in functions defined in C provide no metadata about
          their arguments.

 -- 類別: inspect.Signature (parameters=None, *,
          return_annotation=Signature.empty)

     A Signature object represents the call signature of a function and
     its return annotation.  For each parameter accepted by the function
     it stores a *note Parameter: 7e5. object in its *note parameters:
     1088. collection.

     The optional `parameters' argument is a sequence of *note
     Parameter: 7e5. objects, which is validated to check that there are
     no parameters with duplicate names, and that the parameters are in
     the right order, i.e.  positional-only first, then
     positional-or-keyword, and that parameters with defaults follow
     parameters without defaults.

     The optional `return_annotation' argument, can be an arbitrary
     Python object, is the "return" annotation of the callable.

     Signature objects are `immutable'.  Use *note Signature.replace():
     3880. to make a modified copy.

     3.5 版更變: Signature objects are picklable and hashable.

      -- 屬性: empty

          A special class-level marker to specify absence of a return
          annotation.

      -- 屬性: parameters

          An ordered mapping of parameters’ names to the corresponding
          *note Parameter: 7e5. objects.  Parameters appear in strict
          definition order, including keyword-only parameters.

          3.7 版更變: Python only explicitly guaranteed that it
          preserved the declaration order of keyword-only parameters as
          of version 3.7, although in practice this order had always
          been preserved in Python 3.

      -- 屬性: return_annotation

          The "return" annotation for the callable.  If the callable has
          no "return" annotation, this attribute is set to *note
          Signature.empty: 3881.

      -- 成員函式: bind (*args, **kwargs)

          Create a mapping from positional and keyword arguments to
          parameters.  Returns *note BoundArguments: a89. if ‘*args’ and
          ‘**kwargs’ match the signature, or raises a *note TypeError:
          1fe.

      -- 成員函式: bind_partial (*args, **kwargs)

          Works the same way as *note Signature.bind(): 3883, but allows
          the omission of some required arguments (mimics *note
          functools.partial(): 8b5. behavior.)  Returns *note
          BoundArguments: a89, or raises a *note TypeError: 1fe. if the
          passed arguments do not match the signature.

      -- 成員函式: replace (*[, parameters][, return_annotation])

          Create a new Signature instance based on the instance replace
          was invoked on.  It is possible to pass different ‘parameters’
          and/or ‘return_annotation’ to override the corresponding
          properties of the base signature.  To remove return_annotation
          from the copied Signature, pass in *note Signature.empty:
          3881.

               >>> 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'"

      -- 成員函式: classmethod from_callable (obj, *,
               follow_wrapped=True)

          Return a *note Signature: 7e4. (or its subclass) object for a
          given callable ‘obj’.  Pass ‘follow_wrapped=False’ to get a
          signature of ‘obj’ without unwrapping its ‘__wrapped__’ chain.

          This method simplifies subclassing of *note Signature: 7e4.:

               class MySignature(Signature):
                   pass
               sig = MySignature.from_callable(min)
               assert isinstance(sig, MySignature)

          3.5 版新加入.

 -- 類別: inspect.Parameter (name, kind, *, default=Parameter.empty,
          annotation=Parameter.empty)

     Parameter objects are `immutable'.  Instead of modifying a
     Parameter object, you can use *note Parameter.replace(): 3885. to
     create a modified copy.

     3.5 版更變: Parameter objects are picklable and hashable.

      -- 屬性: empty

          A special class-level marker to specify absence of default
          values and annotations.

      -- 屬性: name

          The name of the parameter as a string.  The name must be a
          valid Python identifier.

          `CPython implementation detail:' CPython generates implicit
          parameter names of the form ‘.0’ on the code objects used to
          implement comprehensions and generator expressions.

          3.6 版更變: These parameter names are exposed by this module
          as names like ‘implicit0’.

      -- 屬性: default

          The default value for the parameter.  If the parameter has no
          default value, this attribute is set to *note Parameter.empty:
          3886.

      -- 屬性: annotation

          The annotation for the parameter.  If the parameter has no
          annotation, this attribute is set to *note Parameter.empty:
          3886.

      -- 屬性: kind

          Describes how argument values are bound to the parameter.
          Possible values (accessible via *note Parameter: 7e5, like
          ‘Parameter.KEYWORD_ONLY’):

          名称                         意义
                                       
          --------------------------------------------------------------------------------
                                       
          `POSITIONAL_ONLY'            Value must be supplied as a positional argument.
                                       Positional only parameters are those which
                                       appear before a ‘/’ entry (if present) in a
                                       Python function definition.
                                       
                                       
          `POSITIONAL_OR_KEYWORD'      Value may be supplied as either a keyword or
                                       positional argument (this is the standard
                                       binding behaviour for functions implemented in
                                       Python.)
                                       
                                       
          `VAR_POSITIONAL'             A tuple of positional arguments that aren’t
                                       bound to any other parameter.  This corresponds
                                       to a ‘*args’ parameter in a Python function
                                       definition.
                                       
                                       
          `KEYWORD_ONLY'               Value must be supplied as a keyword argument.
                                       Keyword only parameters are those which appear
                                       after a ‘*’ or ‘*args’ entry in a Python
                                       function definition.
                                       
                                       
          `VAR_KEYWORD'                A dict of keyword arguments that aren’t bound to
                                       any other parameter.  This corresponds to a
                                       ‘**kwargs’ parameter in a Python function
                                       definition.
                                       

          Example: print all keyword-only arguments without default
          values:

               >>> 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

      -- 屬性: kind.description

          Describes a enum value of Parameter.kind.

          3.8 版新加入.

          Example: print all descriptions of arguments:

               >>> 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

      -- 成員函式: replace (*[, name][, kind][, default][, annotation])

          Create a new Parameter instance based on the instance replaced
          was invoked on.  To override a *note Parameter: 7e5.
          attribute, pass the corresponding argument.  To remove a
          default value or/and an annotation from a Parameter, pass
          *note Parameter.empty: 3886.

               >>> 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'"

     3.4 版更變: In Python 3.3 Parameter objects were allowed to have
     ‘name’ set to ‘None’ if their ‘kind’ was set to ‘POSITIONAL_ONLY’.
     This is no longer permitted.

 -- 類別: inspect.BoundArguments

     Result of a *note Signature.bind(): 3883. or *note
     Signature.bind_partial(): 3884. call.  Holds the mapping of
     arguments to the function’s parameters.

      -- 屬性: arguments

          A mutable mapping of parameters’ names to arguments’ values.
          Contains only explicitly bound arguments.  Changes in *note
          arguments: 1b9. will reflect in *note args: 388c. and *note
          kwargs: 388d.

          Should be used in conjunction with *note Signature.parameters:
          1088. for any argument processing purposes.

               備註: Arguments for which *note Signature.bind(): 3883.
               or *note Signature.bind_partial(): 3884. relied on a
               default value are skipped.  However, if needed, use *note
               BoundArguments.apply_defaults(): 7e6. to add them.

          3.9 版更變: *note arguments: 1b9. is now of type *note dict:
          164.  Formerly, it was of type *note collections.OrderedDict:
          2ea.

      -- 屬性: args

          A tuple of positional arguments values.  Dynamically computed
          from the *note arguments: 1b9. attribute.

      -- 屬性: kwargs

          A dict of keyword arguments values.  Dynamically computed from
          the *note arguments: 1b9. attribute.

      -- 屬性: signature

          A reference to the parent *note Signature: 7e4. object.

      -- 成員函式: apply_defaults ()

          Set default values for missing arguments.

          For variable-positional arguments (‘*args’) the default is an
          empty tuple.

          For variable-keyword arguments (‘**kwargs’) the default is an
          empty dict.

               >>> def foo(a, b='ham', *args): pass
               >>> ba = inspect.signature(foo).bind('spam')
               >>> ba.apply_defaults()
               >>> ba.arguments
               {'a': 'spam', 'b': 'ham', 'args': ()}

          3.5 版新加入.

     The *note args: 388c. and *note kwargs: 388d. properties can be
     used to invoke functions:

          def test(a, *, b):
              ...

          sig = signature(test)
          ba = sig.bind(10, b=20)
          test(*ba.args, **ba.kwargs)

也參考
......

PEP 362(1) - Function Signature Object.

     The detailed specification, implementation details and examples.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0362


File: python.info,  Node: 类与函数<2>,  Next: The interpreter stack,  Prev: Introspecting callables with the Signature object,  Up: inspect --- 检查对象

5.29.13.4 类与函数
..................

 -- 函式: inspect.getclasstree (classes, unique=False)

     Arrange the given list of classes into a hierarchy of nested lists.
     Where a nested list appears, it contains classes derived from the
     class whose entry immediately precedes the list.  Each entry is a
     2-tuple containing a class and a tuple of its base classes.  If the
     `unique' argument is true, exactly one entry appears in the
     returned structure for each class in the given list.  Otherwise,
     classes using multiple inheritance and their descendants will
     appear multiple times.

 -- 函式: inspect.getargspec (func)

     Get the names and default values of a Python function’s parameters.
     A *note named tuple: b7b. ‘ArgSpec(args, varargs, keywords,
     defaults)’ is returned.  `args' is a list of the parameter names.
     `varargs' and `keywords' are the names of the ‘*’ and ‘**’
     parameters or ‘None’.  `defaults' is a tuple of default argument
     values or ‘None’ if there are no default arguments; if this tuple
     has `n' elements, they correspond to the last `n' elements listed
     in `args'.

     3.0 版後已棄用: Use *note getfullargspec(): 657. for an updated API
     that is usually a drop-in replacement, but also correctly handles
     function annotations and keyword-only parameters.

     Alternatively, use *note signature(): 655. and *note Signature
     Object: 387e, which provide a more structured introspection API for
     callables.

 -- 函式: inspect.getfullargspec (func)

     Get the names and default values of a Python function’s parameters.
     A *note named tuple: b7b. is returned:

     ‘FullArgSpec(args, varargs, varkw, defaults, kwonlyargs,
     kwonlydefaults, annotations)’

     `args' is a list of the positional parameter names.  `varargs' is
     the name of the ‘*’ parameter or ‘None’ if arbitrary positional
     arguments are not accepted.  `varkw' is the name of the ‘**’
     parameter or ‘None’ if arbitrary keyword arguments are not
     accepted.  `defaults' is an `n'-tuple of default argument values
     corresponding to the last `n' positional parameters, or ‘None’ if
     there are no such defaults defined.  `kwonlyargs' is a list of
     keyword-only parameter names in declaration order.
     `kwonlydefaults' is a dictionary mapping parameter names from
     `kwonlyargs' to the default values used if no argument is supplied.
     `annotations' is a dictionary mapping parameter names to
     annotations.  The special key ‘"return"’ is used to report the
     function return value annotation (if any).

     Note that *note signature(): 655. and *note Signature Object: 387e.
     provide the recommended API for callable introspection, and support
     additional behaviours (like positional-only arguments) that are
     sometimes encountered in extension module APIs.  This function is
     retained primarily for use in code that needs to maintain
     compatibility with the Python 2 ‘inspect’ module API.

     3.4 版更變: This function is now based on *note signature(): 655,
     but still ignores ‘__wrapped__’ attributes and includes the already
     bound first parameter in the signature output for bound methods.

     3.6 版更變: This method was previously documented as deprecated in
     favour of *note signature(): 655. in Python 3.5, but that decision
     has been reversed in order to restore a clearly supported standard
     interface for single-source Python 2/3 code migrating away from the
     legacy *note getargspec(): 656. API.

     3.7 版更變: Python only explicitly guaranteed that it preserved the
     declaration order of keyword-only parameters as of version 3.7,
     although in practice this order had always been preserved in Python
     3.

 -- 函式: inspect.getargvalues (frame)

     Get information about arguments passed into a particular frame.  A
     *note named tuple: b7b. ‘ArgInfo(args, varargs, keywords, locals)’
     is returned.  `args' is a list of the argument names.  `varargs'
     and `keywords' are the names of the ‘*’ and ‘**’ arguments or
     ‘None’.  `locals' is the locals dictionary of the given frame.

          備註: This function was inadvertently marked as deprecated in
          Python 3.5.

 -- 函式: inspect.formatargspec (args[, varargs, varkw, defaults,
          kwonlyargs, kwonlydefaults, annotations[, formatarg,
          formatvarargs, formatvarkw, formatvalue, formatreturns,
          formatannotations]])

     Format a pretty argument spec from the values returned by *note
     getfullargspec(): 657.

     The first seven arguments are (‘args’, ‘varargs’, ‘varkw’,
     ‘defaults’, ‘kwonlyargs’, ‘kwonlydefaults’, ‘annotations’).

     The other six arguments are functions that are called to turn
     argument names, ‘*’ argument name, ‘**’ argument name, default
     values, return annotation and individual annotations into strings,
     respectively.

     例如:

          >>> from inspect import formatargspec, getfullargspec
          >>> def f(a: int, b: float):
          ...     pass
          ...
          >>> formatargspec(*getfullargspec(f))
          '(a: int, b: float)'

     3.5 版後已棄用: Use *note signature(): 655. and *note Signature
     Object: 387e, which provide a better introspecting API for
     callables.

 -- 函式: inspect.formatargvalues (args[, varargs, varkw, locals,
          formatarg, formatvarargs, formatvarkw, formatvalue])

     Format a pretty argument spec from the four values returned by
     *note getargvalues(): 8a6.  The format* arguments are the
     corresponding optional formatting functions that are called to turn
     names and values into strings.

          備註: This function was inadvertently marked as deprecated in
          Python 3.5.

 -- 函式: inspect.getmro (cls)

     Return a tuple of class cls’s base classes, including cls, in
     method resolution order.  No class appears more than once in this
     tuple.  Note that the method resolution order depends on cls’s
     type.  Unless a very peculiar user-defined metatype is in use, cls
     will be the first element of the tuple.

 -- 函式: inspect.getcallargs (func, /, *args, **kwds)

     Bind the `args' and `kwds' to the argument names of the Python
     function or method `func', as if it was called with them.  For
     bound methods, bind also the first argument (typically named
     ‘self’) to the associated instance.  A dict is returned, mapping
     the argument names (including the names of the ‘*’ and ‘**’
     arguments, if any) to their values from `args' and `kwds'.  In case
     of invoking `func' incorrectly, i.e.  whenever ‘func(*args,
     **kwds)’ would raise an exception because of incompatible
     signature, an exception of the same type and the same or similar
     message is raised.  For 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'

     3.2 版新加入.

     3.5 版後已棄用: Use *note Signature.bind(): 3883. and *note
     Signature.bind_partial(): 3884. instead.

 -- 函式: inspect.getclosurevars (func)

     Get the mapping of external name references in a Python function or
     method `func' to their current values.  A *note named tuple: b7b.
     ‘ClosureVars(nonlocals, globals, builtins, unbound)’ is returned.
     `nonlocals' maps referenced names to lexical closure variables,
     `globals' to the function’s module globals and `builtins' to the
     builtins visible from the function body.  `unbound' is the set of
     names referenced in the function that could not be resolved at all
     given the current module globals and builtins.

     *note TypeError: 1fe. is raised if `func' is not a Python function
     or method.

     3.3 版新加入.

 -- 函式: inspect.unwrap (func, *, stop=None)

     Get the object wrapped by `func'.  It follows the chain of
     ‘__wrapped__’ attributes returning the last object in the chain.

     `stop' is an optional callback accepting an object in the wrapper
     chain as its sole argument that allows the unwrapping to be
     terminated early if the callback returns a true value.  If the
     callback never returns a true value, the last object in the chain
     is returned as usual.  For example, *note signature(): 655. uses
     this to stop unwrapping if any object in the chain has a
     ‘__signature__’ attribute defined.

     *note ValueError: 16d. is raised if a cycle is encountered.

     3.4 版新加入.


File: python.info,  Node: The interpreter stack,  Next: Fetching attributes statically,  Prev: 类与函数<2>,  Up: inspect --- 检查对象

5.29.13.5 The interpreter stack
...............................

When the following functions return "frame records," each record is a
*note named tuple: b7b. ‘FrameInfo(frame, filename, lineno, function,
code_context, index)’.  The tuple contains the frame object, the
filename, the line number of the current line, the function name, a list
of lines of context from the source code, and the index of the current
line within that list.

3.5 版更變: Return a named tuple instead of a tuple.

     備註: Keeping references to frame objects, as found in the first
     element of the frame records these functions return, can cause your
     program to create reference cycles.  Once a reference cycle has
     been created, the lifespan of all objects which can be accessed
     from the objects which form the cycle can become much longer even
     if Python’s optional cycle detector is enabled.  If such cycles
     must be created, it is important to ensure they are explicitly
     broken to avoid the delayed destruction of objects and increased
     memory consumption which occurs.

     Though the cycle detector will catch these, destruction of the
     frames (and local variables) can be made deterministic by removing
     the cycle in a *note finally: 2bc. clause.  This is also important
     if the cycle detector was disabled when Python was compiled or
     using *note gc.disable(): 3857.  For example:

          def handle_stackframe_without_leak():
              frame = inspect.currentframe()
              try:
                  # do something with the frame
              finally:
                  del frame

     If you want to keep the frame around (for example to print a
     traceback later), you can also break reference cycles by using the
     *note frame.clear(): 8f8. method.

The optional `context' argument supported by most of these functions
specifies the number of lines of context to return, which are centered
around the current line.

 -- 函式: inspect.getframeinfo (frame, context=1)

     Get information about a frame or traceback object.  A *note named
     tuple: b7b. ‘Traceback(filename, lineno, function, code_context,
     index)’ is returned.

 -- 函式: inspect.getouterframes (frame, context=1)

     Get a list of frame records for a frame and all outer frames.
     These frames represent the calls that lead to the creation of
     `frame'.  The first entry in the returned list represents `frame';
     the last entry represents the outermost call on `frame'’s stack.

     3.5 版更變: A list of *note named tuples: b7b. ‘FrameInfo(frame,
     filename, lineno, function, code_context, index)’ is returned.

 -- 函式: inspect.getinnerframes (traceback, context=1)

     Get a list of frame records for a traceback’s frame and all inner
     frames.  These frames represent calls made as a consequence of
     `frame'.  The first entry in the list represents `traceback'; the
     last entry represents where the exception was raised.

     3.5 版更變: A list of *note named tuples: b7b. ‘FrameInfo(frame,
     filename, lineno, function, code_context, index)’ is returned.

 -- 函式: inspect.currentframe ()

     Return the frame object for the caller’s stack frame.

     `CPython implementation detail:' This function relies on Python
     stack frame support in the interpreter, which isn’t guaranteed to
     exist in all implementations of Python.  If running in an
     implementation without Python stack frame support this function
     returns ‘None’.

 -- 函式: inspect.stack (context=1)

     Return a list of frame records for the caller’s stack.  The first
     entry in the returned list represents the caller; the last entry
     represents the outermost call on the stack.

     3.5 版更變: A list of *note named tuples: b7b. ‘FrameInfo(frame,
     filename, lineno, function, code_context, index)’ is returned.

 -- 函式: inspect.trace (context=1)

     Return a list of frame records for the stack between the current
     frame and the frame in which an exception currently being handled
     was raised in.  The first entry in the list represents the caller;
     the last entry represents where the exception was raised.

     3.5 版更變: A list of *note named tuples: b7b. ‘FrameInfo(frame,
     filename, lineno, function, code_context, index)’ is returned.


File: python.info,  Node: Fetching attributes statically,  Next: Current State of Generators and Coroutines,  Prev: The interpreter stack,  Up: inspect --- 检查对象

5.29.13.6 Fetching attributes statically
........................................

Both *note getattr(): 54b. and *note hasattr(): 54a. can trigger code
execution when fetching or checking for the existence of attributes.
Descriptors, like properties, will be invoked and *note __getattr__():
42a. and *note __getattribute__(): 549. may be called.

For cases where you want passive introspection, like documentation
tools, this can be inconvenient.  *note getattr_static(): c99. has the
same signature as *note getattr(): 54b. but avoids executing code when
it fetches attributes.

 -- 函式: inspect.getattr_static (obj, attr, default=None)

     Retrieve attributes without triggering dynamic lookup via the
     descriptor protocol, *note __getattr__(): 42a. or *note
     __getattribute__(): 549.

     Note: this function may not be able to retrieve all attributes that
     getattr can fetch (like dynamically created attributes) and may
     find attributes that getattr can’t (like descriptors that raise
     AttributeError).  It can also return descriptors objects instead of
     instance members.

     If the instance *note __dict__: 5f5. is shadowed by another member
     (for example a property) then this function will be unable to find
     instance members.

     3.2 版新加入.

*note getattr_static(): c99. does not resolve descriptors, for example
slot descriptors or getset descriptors on objects implemented in C. The
descriptor object is returned instead of the underlying attribute.

You can handle these with code like the following.  Note that for
arbitrary getset descriptors invoking these may trigger code execution:

     # 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


File: python.info,  Node: Current State of Generators and Coroutines,  Next: Code Objects Bit Flags,  Prev: Fetching attributes statically,  Up: inspect --- 检查对象

5.29.13.7 Current State of Generators and Coroutines
....................................................

When implementing coroutine schedulers and for other advanced uses of
generators, it is useful to determine whether a generator is currently
executing, is waiting to start or resume or execution, or has already
terminated.  *note getgeneratorstate(): c98. allows the current state of
a generator to be determined easily.

 -- 函式: inspect.getgeneratorstate (generator)

     Get current state of a generator-iterator.

     Possible states are:

             * GEN_CREATED: Waiting to start execution.

             * GEN_RUNNING: Currently being executed by the interpreter.

             * GEN_SUSPENDED: Currently suspended at a yield expression.

             * GEN_CLOSED: Execution has completed.

     3.2 版新加入.

 -- 函式: inspect.getcoroutinestate (coroutine)

     Get current state of a coroutine object.  The function is intended
     to be used with coroutine objects created by *note async def: 3a9.
     functions, but will accept any coroutine-like object that has
     ‘cr_running’ and ‘cr_frame’ attributes.

     Possible states are:

             * CORO_CREATED: Waiting to start execution.

             * CORO_RUNNING: Currently being executed by the
               interpreter.

             * CORO_SUSPENDED: Currently suspended at an await
               expression.

             * CORO_CLOSED: Execution has completed.

     3.5 版新加入.

The current internal state of the generator can also be queried.  This
is mostly useful for testing purposes, to ensure that internal state is
being updated as expected:

 -- 函式: inspect.getgeneratorlocals (generator)

     Get the mapping of live local variables in `generator' to their
     current values.  A dictionary is returned that maps from variable
     names to values.  This is the equivalent of calling *note locals():
     556. in the body of the generator, and all the same caveats apply.

     If `generator' is a *note generator: a83. with no currently
     associated frame, then an empty dictionary is returned.  *note
     TypeError: 1fe. is raised if `generator' is not a Python generator
     object.

     `CPython implementation detail:' This function relies on the
     generator exposing a Python stack frame for introspection, which
     isn’t guaranteed to be the case in all implementations of Python.
     In such cases, this function will always return an empty
     dictionary.

     3.3 版新加入.

 -- 函式: inspect.getcoroutinelocals (coroutine)

     This function is analogous to *note getgeneratorlocals(): af7, but
     works for coroutine objects created by *note async def: 3a9.
     functions.

     3.5 版新加入.


File: python.info,  Node: Code Objects Bit Flags,  Next: 命令行界面<5>,  Prev: Current State of Generators and Coroutines,  Up: inspect --- 检查对象

5.29.13.8 Code Objects Bit Flags
................................

Python code objects have a ‘co_flags’ attribute, which is a bitmap of
the following flags:

 -- Data: inspect.CO_OPTIMIZED

     The code object is optimized, using fast locals.

 -- Data: inspect.CO_NEWLOCALS

     If set, a new dict will be created for the frame’s ‘f_locals’ when
     the code object is executed.

 -- Data: inspect.CO_VARARGS

     The code object has a variable positional parameter (‘*args’-like).

 -- Data: inspect.CO_VARKEYWORDS

     The code object has a variable keyword parameter (‘**kwargs’-like).

 -- Data: inspect.CO_NESTED

     The flag is set when the code object is a nested function.

 -- Data: inspect.CO_GENERATOR

     The flag is set when the code object is a generator function, i.e.
     a generator object is returned when the code object is executed.

 -- Data: inspect.CO_NOFREE

     The flag is set if there are no free or cell variables.

 -- Data: inspect.CO_COROUTINE

     The flag is set when the code object is a coroutine function.  When
     the code object is executed it returns a coroutine object.  See PEP
     492(1) for more details.

     3.5 版新加入.

 -- Data: inspect.CO_ITERABLE_COROUTINE

     The flag is used to transform generators into generator-based
     coroutines.  Generator objects with this flag can be used in
     ‘await’ expression, and can ‘yield from’ coroutine objects.  See
     PEP 492(2) for more details.

     3.5 版新加入.

 -- Data: inspect.CO_ASYNC_GENERATOR

     The flag is set when the code object is an asynchronous generator
     function.  When the code object is executed it returns an
     asynchronous generator object.  See PEP 525(3) for more details.

     3.6 版新加入.

     備註: The flags are specific to CPython, and may not be defined in
     other Python implementations.  Furthermore, the flags are an
     implementation detail, and can be removed or deprecated in future
     Python releases.  It’s recommended to use public APIs from the
     *note inspect: a0. module for any introspection needs.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0492

   (2) https://www.python.org/dev/peps/pep-0492

   (3) https://www.python.org/dev/peps/pep-0525


File: python.info,  Node: 命令行界面<5>,  Prev: Code Objects Bit Flags,  Up: inspect --- 检查对象

5.29.13.9 命令行界面
....................

The *note inspect: a0. module also provides a basic introspection
capability from the command line.

By default, accepts the name of a module and prints the source of that
module.  A class or function within the module can be printed instead by
appended a colon and the qualified name of the target object.

 -- 程式選項: --details

     Print information about the specified object rather than the source
     code


File: python.info,  Node: site —— 指定域的配置钩子,  Prev: inspect --- 检查对象,  Up: Python运行时服务

5.29.14 ‘site’ —— 指定域的配置钩子
----------------------------------

`源代码:' Lib/site.py(1)

__________________________________________________________________

`这个模块将在初始化时被自动导入。' 此自动导入可以通过使用解释器的 *note
-S: bf7. 选项来屏蔽。

导入此模块将会附加域特定的路径到模块搜索路径并且添加一些内建对象，除非使
用了 *note -S: bf7. 选项。 那样的话，模块可以被安全地导入，而不会对模块
搜索路径和内建对象有自动的修改或添加。要明确地触发通常域特定的添加，调用
函数 *note site.main(): 147b.。

3.3 版更變: 在之前即便使用了 *note -S: bf7.，导入此模块仍然会触发路径操
纵。

It starts by constructing up to four directories from a head and a tail
part.  For the head part, it uses ‘sys.prefix’ and ‘sys.exec_prefix’;
empty heads are skipped.  For the tail part, it uses the empty string
and then ‘lib/site-packages’ (on Windows) or
‘lib/python`X.Y'/site-packages’ (on Unix and macOS). For each of the
distinct head-tail combinations, it sees if it refers to an existing
directory, and if so, adds it to ‘sys.path’ and also inspects the newly
added path for configuration files.

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；反之则会。

一个路径配置文件是具有 ‘`name'.pth’ 命名格式的文件，并且存在上面提到的四
个目录之一中；它的内容是要添加到 ‘sys.path’ 中的额外项目（每行一个）。不
存在的项目不会添加到 ‘sys.path’，并且不会检查项目指向的是目录还是文件。
项目不会被添加到 ‘sys.path’ 超过一次。空行和由 ‘#’ 起始的行会被跳过。以
‘import’ 开始的行（跟着空格或 TAB）会被执行。

     備註: 每次启动 Python，在 ‘.pth’ 文件中的可执行行都将会被运行，而不
     管特定的模块实际上是否需要被使用。 因此，其影响应降至最低。可执行行
     的主要预期目的是使相关模块可导入（加载第三方导入钩子，调整 ‘PATH’ 等
     ）。如果它发生了，任何其他的初始化都应当在模块实际导入之前完成。将
     代码块限制为一行是一种有意采取的措施，不鼓励在此处放置更复杂的内容
     。

例如，假设 ‘sys.prefix’ 和 ‘sys.exec_prefix’ 已经被设置为 ‘/usr/local’。
Python X.Y 的库之后被安装为 ‘/usr/local/lib/python`X.Y'’。假设有一个拥有
三个孙目录 ‘foo’, ‘bar’ 和 ‘spam’ 的子目录
‘/usr/local/lib/python`X.Y'/site-packages’，并且有两个路径配置文件
‘foot.pth’ 和 ‘bar.pth’。假定 ‘foo.pth’ 内容如下:

     # foo package configuration

     foo
     bar
     bletch

并且 ‘bar.pth’ 包含:

     # bar package configuration

     bar

则下面特定版目录将以如下顺序被添加到 ‘sys.path’。

     /usr/local/lib/pythonX.Y/site-packages/bar
     /usr/local/lib/pythonX.Y/site-packages/foo

请注意 ‘bletch’ 已被省略因为它并不存在；‘bar’ 目前在 ‘foo’ 目录之前因为
‘bar.pth’ 按字母顺序排在 ‘foo.pth’ 之前；而 ‘spam’ 已被省略因为它在两个
路径配置文件中都未被提及。

在这些路径操作之后，会尝试导入一个名为 ‘sitecustomize’ 的模块，它可以执
行任意站点专属的定制。 它通常是由系统管理员在 site-packages 目录下创建的
。 如果此导入失败并引发 *note ImportError: 16c. 或其子类异常，并且异常的
‘name’ 属性等于 ‘'sitecustomize'’，则它会被静默地忽略。 如果 Python 是在
没有可用输出流的情况下启动的，例如在 Windows 上使用 ‘pythonw.exe’ (它默
认被用于启动 start IDLE)，则来自 ‘sitecustomize’ 的输出尝试会被忽略。 任
何其他异常都会导致静默且可能令人迷惑不解的进程失败。

在此之后，会尝试导入一个名为 ‘usercustomize’ 的模块，它可以执行任意用户
专属的定制，如果 *note ENABLE_USER_SITE: 38a8. 为真值的话。 这个文件应该
在用户的 site-packages 目录中创建（见下文），该目录是 ‘sys.path’ 的组成
部分，除非被 *note -s: ddb. 所禁用。 如果此导入失败并引发 *note
ImportError: 16c. 或者其子类异常，并且异常的 ‘name’ 属性等于
‘'usercustomize'’，它会被静默地忽略。

请注意对于某些非 Unix 系统来说，‘sys.prefix’ 和 ‘sys.exec_prefix’ 均为空
值，并且路径操作会被跳过；但是仍然会尝试导入 ‘sitecustomize’ 和
‘usercustomize’。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/site.py


File: python.info,  Node: Readline 配置,  Next: 模块内容<8>,  Up: site —— 指定域的配置钩子

5.29.14.1 Readline 配置
.......................

在支持 *note readline: de. 的系统上，这个模块也将导入并配置 *note
rlcompleter: e1. 模块，如果 Python 是以 *note 交互模式: 9c9. 启动并且不
带 *note -S: bf7. 选项的话。 默认的行为是启用 tab 键补全并使用
‘~/.python_history’ 作为历史存档文件。 要禁用它，请删除（或重载）你的
‘sitecustomize’ 或 ‘usercustomize’ 模块或 *note PYTHONSTARTUP: 9cb. 文件
中的 *note sys.__interactivehook__: 9ca. 属性。

3.4 版更變: rlcompleter 和 history 会被自动激活。


File: python.info,  Node: 模块内容<8>,  Next: 命令行界面<6>,  Prev: Readline 配置,  Up: site —— 指定域的配置钩子

5.29.14.2 模块内容
..................

 -- Data: site.PREFIXES

     site-packages 目录的前缀列表。

 -- Data: site.ENABLE_USER_SITE

     显示用户 site-packages 目录状态的旗标。 ‘True’ 意味着它被启用并被添
     加到 ‘sys.path’。 ‘False’ 意味着它按照用户请求被禁用 (通过 *note
     -s: ddb. 或 *note PYTHONNOUSERSITE: ddc.)。 ‘None’ 意味着它因安全理
     由（user 或 group id 和 effective id 之间不匹配）或是被管理员所禁用
     。

 -- Data: site.USER_SITE

     Path to the user site-packages for the running Python.  Can be
     ‘None’ if *note getusersitepackages(): ca3. hasn’t been called yet.
     Default value is ‘~/.local/lib/python`X.Y'/site-packages’ for UNIX
     and non-framework macOS builds,
     ‘~/Library/Python/`X.Y'/lib/python/site-packages’ for macOS
     framework builds, and ‘`%APPDATA%'\Python\Python`XY'\site-packages’
     on Windows.  This directory is a site directory, which means that
     ‘.pth’ files in it will be processed.

 -- Data: site.USER_BASE

     Path to the base directory for the user site-packages.  Can be
     ‘None’ if *note getuserbase(): ca2. hasn’t been called yet.
     Default value is ‘~/.local’ for UNIX and macOS non-framework
     builds, ‘~/Library/Python/`X.Y'’ for macOS framework builds, and
     ‘`%APPDATA%'\Python’ for Windows.  This value is used by Distutils
     to compute the installation directories for scripts, data files,
     Python modules, etc.  for the *note user installation scheme: 148a.
     See also *note PYTHONUSERBASE: dda.

 -- 函式: site.main ()

     将所有的标准站点专属目录添加到模块搜索路径。 这个函数会在导入此模块
     时被自动调用，除非 Python 解释器启动时附带了 *note -S: bf7. 旗标。

     3.3 版更變: 这个函数使用无条件调用。

 -- 函式: site.addsitedir (sitedir, known_paths=None)

     将一个目录添加到 sys.path 并处理其 ‘.pth’ 文件。 通常被用于
     ‘sitecustomize’ 或 ‘usercustomize’ (见下文)。

 -- 函式: site.getsitepackages ()

     返回包含所有全局 site-packages 目录的列表。

     3.2 版新加入.

 -- 函式: site.getuserbase ()

     返回用户基准目录的路径 *note USER_BASE: 1489.。 如果它尚未被初始化
     ，则此函数还将参照 *note PYTHONUSERBASE: dda. 来设置它。

     3.2 版新加入.

 -- 函式: site.getusersitepackages ()

     返回用户专属 site-packages 目录的路径 *note USER_SITE: 147a.。 如果
     它尚未被初始化，则此函数还将参照 *note USER_BASE: 1489. 来设置它。
     要确定用户专属 site-packages 是否已被添加到 ‘sys.path’ 则应当使用
     *note ENABLE_USER_SITE: 38a8.。

     3.2 版新加入.


File: python.info,  Node: 命令行界面<6>,  Prev: 模块内容<8>,  Up: site —— 指定域的配置钩子

5.29.14.3 命令行界面
....................

*note site: eb. 模块还提供了一个从命令行获取用户目录的方式:

     $ python3 -m site --user-site
     /home/user/.local/lib/python3.3/site-packages

如果它被不带参数地调用，它将在标准输出打印 *note sys.path: 261. 的内容，
再打印 *note USER_BASE: 1489. 的值以及该目录是否存在，然后打印 *note
USER_SITE: 147a. 的相应信息，最后打印 *note ENABLE_USER_SITE: 38a8. 的值
。

 -- 程式選項: --user-base

     输出用户基本的路径。

 -- 程式選項: --user-site

     输出用户site-packages目录的路径。

如果同时给出了两个选项，则将打印用户基准目录和用户站点信息（总是按此顺序
），并以 *note os.pathsep: 1486. 分隔。

如果给出了其中一个选项，脚本将退出并返回以下值中的一个：如果用户级
site-packages 目录被启用则为 ‘0’，如果它被用户禁用则为 ‘1’，如果它因安全
理由或被管理员禁用则为 ‘2’，如果发生错误则为大于 2 的值。

也參考
......

PEP 370(1) – 分用户的 site-packages 目录

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0370


File: python.info,  Node: 自定义 Python 解释器,  Next: 匯入模組,  Prev: Python运行时服务,  Up: Python 標準函式庫 Standard Library

5.30 自定义 Python 解释器
=========================

本章中描述的模块允许编写类似于 Python 的交互式解释器的接口。 如果你想要
一个支持附加一些特殊功能到 Python 语言的 Python 解释器，你应该看看 *note
code: 1a. 模块。 （ *note codeop: 1c. 模块是低层级的，用于支持编译可能不
完整的 Python 代码块。）

本章描述的完整模块列表如下：

* Menu:

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


File: python.info,  Node: code --- 解释器基类,  Next: codeop --- 编译Python代码,  Up: 自定义 Python 解释器

5.30.1 ‘code’ — 解释器基类
--------------------------

`源代码：' Lib/code.py(1)

__________________________________________________________________

‘code’ 模块提供了在 Python 中实现 read-eval-print 循环的功能。它包含两个
类和一些快捷功能，可用于构建提供交互式解释器的应用程序。

 -- 類別: code.InteractiveInterpreter (locals=None)

     这个类处理解析器和解释器状态（用户命名空间的）；它不处理缓冲器、终
     端提示区或着输入文件名（文件名总是显示地传递）。可选的 `locals' 参
     数指定一个字典，字典里面包含将在此类执行的代码；它默认创建新的字典
     ，其键 ‘'__name__'’ 设置为 ‘'__console__'’ ，键 ‘'__doc__'’ 设置为
     ‘None’ 。

 -- 類別: code.InteractiveConsole (locals=None, filename="<console>")

     尽可能模拟交互式 Python 解释器的行为。此类建立在 *note
     InteractiveInterpreter: 38b6. 的基础上，使用熟悉的 ‘sys.ps1’ 和
     ‘sys.ps2’ 作为输入提示符，并有输入缓冲。

 -- 函式: code.interact (banner=None, readfunc=None, local=None,
          exitmsg=None)

     运行一个 read-eval-print 循环的便捷函数。这会创建一个新的 *note
     InteractiveConsole: 1944. 实例。如果提供了 `readfunc' ，会设置为
     *note InteractiveConsole.raw_input(): 38b8. 方法。如果提供了
     `local' ，则将其传递给 *note InteractiveConsole: 1944. 的构造函数，
     以用作解释器循环的默认命名空间。然后，如果提供了 `banner' 和
     `exitmsg' ，实例的 *note interact(): 38b7. 方法会以此为标题和退出消
     息。控制台对象在使用后将被丢弃。

     3.6 版更變: 加入 `exitmsg' 参数。

 -- 函式: code.compile_command (source, filename="<input>",
          symbol="single")

     这个函数主要用来模拟 Python 解释器的主循环（即 read-eval-print 循环
     ）。难点的部分是当用户输入不完整命令时，判断能否通过之后的输入来完
     成（要么成为完整的命令，要么语法错误）。该函数 `几乎' 和实际的解释
     器主循环的判断是相同的。

     `source' 是源字符串；`filename' 是可选的用作读取源的文件名，默认为
     ‘'<input>'’；`symbol' 是可选的语法开启符号，应为 ‘'single'’ (默认),
     ‘'eval'’ 或 ‘'exec'’。

     如果命令完整且有效则返回一个代码对象 (等价于 ‘compile(source,
     filename, symbol)’)；如果命令不完整则返回 ‘None’；如果命令完整但包
     含语法错误则会引发 *note SyntaxError: 559. 或 *note OverflowError:
     a41. 而如果命令包含无效字面值则将引发 *note ValueError: 16d.。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/code.py


File: python.info,  Node: 交互解释器对象,  Next: 交互式控制台对象,  Up: code --- 解释器基类

5.30.1.1 交互解释器对象
.......................

 -- 成員函式: InteractiveInterpreter.runsource (source,
          filename="<input>", symbol="single")

     在解释器中编译并运行一段源码。 所用参数与 *note compile_command():
     38b9. 一样；`filename' 的默认值为 ‘'<input>'’，`symbol' 则为
     ‘'single'’。 可能发生以下情况之一：

        * 输入不正确；*note compile_command(): 38b9. 引发了一个异常
          (*note SyntaxError: 559. 或 *note OverflowError: a41.)。 将通
          过调用 *note showsyntaxerror(): 38bd. 方法打印语法回溯信息。
          *note runsource(): 38bc. 返回 ‘False’。

        * 输入不完整，需要更多输入；函数 *note compile_command(): 38b9.
          返回 ‘None’ 。方法 *note runsource(): 38bc. 返回 ‘True’ 。

        * 输入完整；*note compile_command(): 38b9. 返回了一个代码对象。
          将通过调用 *note runcode(): 38be. 执行代码（该方法也会处理运行
          时异常，*note SystemExit: 6f3. 除外）。 *note runsource():
          38bc. 返回 ‘False’。

     该返回值用于决定使用 ‘sys.ps1’ 还是 ‘sys.ps2’ 来作为下一行的输入提
     示符。

 -- 成員函式: InteractiveInterpreter.runcode (code)

     执行一个代码对象。当发生异常时，调用 *note showtraceback(): 79a. 来
     显示回溯。除 *note SystemExit: 6f3. （允许传播）以外的所有异常都会
     被捕获。

     有关 *note KeyboardInterrupt: 2cc. 的说明，该异常可能发生于此代码的
     其他位置，并且并不总能被捕获。 调用者应当准备好处理它。

 -- 成員函式: InteractiveInterpreter.showsyntaxerror (filename=None)

     显示刚发生的语法错误。 这不会显示堆栈回溯因为语法错误并无此种信息。
     如果给出了 `filename'，它会被放入异常来替代 Python 解析器所提供的默
     认文件名，因为它在从一个字符串读取时总是会使用 ‘'<string>'’。 输出
     将由 *note write(): 38bf. 方法来写入。

 -- 成員函式: InteractiveInterpreter.showtraceback ()

     显示刚发生的异常。 我们移除了第一个堆栈条目因为它从属于解释器对象的
     实现。 输出将由 *note write(): 38bf. 方法来写入。

     3.5 版更變: 将显示完整的链式回溯，而不只是主回溯。

 -- 成員函式: InteractiveInterpreter.write (data)

     将一个字符串写入到标准错误流 (‘sys.stderr’)。 所有派生类都应重载此
     方法以提供必要的正确输出处理。


File: python.info,  Node: 交互式控制台对象,  Prev: 交互解释器对象,  Up: code --- 解释器基类

5.30.1.2 交互式控制台对象
.........................

*note InteractiveConsole: 1944. 类是 *note InteractiveInterpreter: 38b6.
的子类，因此它提供了解释器对象的所有方法，还有以下的额外方法。

 -- 成員函式: InteractiveConsole.interact (banner=None, exitmsg=None)

     近似地模拟交互式 Python 终端。 可选的 `banner' 参数指定要在第一次交
     互前打印的条幅；默认情况下会类似于标准 Python 解释器所打印的内容，
     并附上外加圆括号的终端对象类名（这样就不会与真正的解释器混淆 —— 因
     为确实太像了！）

     可选的 `exitmsg' 参数指定要在退出时打印的退出消息。 传入空字符串可
     以屏蔽退出消息。 如果 `exitmsg' 未给出或为 ‘None’，则将打印默认消息
     。

     3.4 版更變: 要禁止打印任何条幅消息，请传递一个空字符串。

     3.6 版更變: 退出时打印退出消息。

 -- 成員函式: InteractiveConsole.push (line)

     将一行源文本推入解释器。 行内容不应带有末尾换行符；它可以有内部换行
     符。 行内容会被添加到一个缓冲区并且会调用解释器的 ‘runsource()’ 方
     法，附带缓冲区内容的拼接结果作为源文本。 如果显示命令已执行或不合法
     ，缓冲区将被重置；否则，则命令尚未结束，缓冲区将在添加行后保持原样
     。 如果要求更多输入则返回值为 ‘True’，如果行已按某种方式被处理则返
     回值为 ‘False’ (这与 ‘runsource()’ 相同)。

 -- 成員函式: InteractiveConsole.resetbuffer ()

     从输入缓冲区中删除所有未处理的内容。

 -- 成員函式: InteractiveConsole.raw_input (prompt="")

     输出提示并读取一行。返回的行不包含末尾的换行符。当用户输入 EOF 键序
     列时，会引发 *note EOFError: d34. 异常。默认实现是从 ‘sys.stdin’ 读
     取；子类可以用其他实现代替。


File: python.info,  Node: codeop --- 编译Python代码,  Prev: code --- 解释器基类,  Up: 自定义 Python 解释器

5.30.2 ‘codeop’ — 编译Python代码
--------------------------------

`源代码：' Lib/codeop.py(1)

__________________________________________________________________

*note codeop: 1c. 模块提供了可以模拟Python读取-执行-打印循环的实用程序，
就像在 *note code: 1a. 模块中一样。因此，您可能不希望直接使用该模块；如
果你想在程序中包含这样一个循环，你可能需要使用 *note code: 1a. 模块。

这个任务有两个部分:

  1. 能够判断一行输入是否完成了一个Python语句：简而言之，告诉我们是否要
     打印’">>>"’或’"..."’。

  2. 记住用户已输入了哪些 future 语句，这样后续的输入可以在这些语句被启
     用的状态下被编译。

*note codeop: 1c. 模块提供了分别以及同时执行这两个部分的方式。

只执行前一部分：

 -- 函式: codeop.compile_command (source, filename="<input>",
          symbol="single")

     尝试编译 `source'，这应当是一个 Python 代码字符串，并且在 `source'
     是有效的 Python 代码时返回一个代码对象。 在此情况下，代码对象的
     filename 属性将为 `filename'，其默认值为 ‘'<input>'’。 如果
     `source' `不是' 有效的 Python 代码而是有效的 Python 代码的一个前缀
     时将返回 ‘None’。

     如果 `source' 存在问题，将引发异常。 如果存在无效的 Python 语法将引
     发 *note SyntaxError: 559.，而如果存在无效的字面值则将引发 *note
     OverflowError: a41. 或 *note ValueError: 16d.。

     `symbol' 参数确定 `source' 是作为一条语句 (对应默认值 ‘'single'’)，
     作为一系列语句 (‘'exec'’) 还是作为一个 *note expression: 158f.
     (‘'eval'’) 进行编译。 任何其他值都将导致引发 *note ValueError:
     16d.。

          備註: 解析器有可能（但很不常见）会在到达源码结尾之前停止解析并
          成功输出结果；在这种情况下，末尾的符号可能会被忽略而不是引发错
          误。 例如，一个反斜杠加两个换行符之后可以跟随任何无意义的符号
          。 一旦解析器 API 得到改进将修正这个问题。

 -- 類別: codeop.Compile

     这个类的实例具有 *note __call__(): 1560. 方法，其签名与内置函数
     *note compile(): 2e7. 相似，区别在于如果该实例编译了包含 *note
     __future__: 0. 语句的程序文本，则实例会‘记住’并使用已生效的语句编译
     所有后续程序文本。

 -- 類別: codeop.CommandCompiler

     这个类的实例具有 *note __call__(): 1560. 方法，其签名与 *note
     compile_command(): 103c. 相似；区别在于如果该实例编译了包含
     ‘__future__’ 语句的程序文本，则实例会‘记住’并使用已生效的语句编译编
     译所有后续程序文本。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/codeop.py


File: python.info,  Node: 匯入模組,  Next: Python 语言服务,  Prev: 自定义 Python 解释器,  Up: Python 標準函式庫 Standard Library

5.31 匯入模組
=============

本章中介绍的模块提供了导入其他Python模块和挂钩以自定义导入过程的新方法。

本章描述的完整模块列表如下：

* Menu:

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


File: python.info,  Node: zipimport --- 从 Zip 存档中导入模块,  Next: pkgutil --- 包扩展工具,  Up: 匯入模組

5.31.1 ‘zipimport’ — 从 Zip 存档中导入模块
------------------------------------------

`源代码：' Lib/zipimport.py(1)

__________________________________________________________________

此模块添加了从 ZIP 格式档案中导入 Python 模块（ ‘*.py’ ， ‘*.pyc’ ）和包
的能力。通常不需要明确地使用 *note zipimport: 14c. 模块，内置的 *note
import: ce7. 机制会自动将此模块用于 ZIP 档案路径的 *note sys.path: 261.
项目上。

通常， *note sys.path: 261. 是字符串的目录名称列表。此模块同样允许 *note
sys.path: 261. 的一项成为命名 ZIP 文件档案的字符串。 ZIP 档案可以容纳子
目录结构去支持包的导入，并且可以将归档文件中的路径指定为仅从子目录导入。
比如说，路径 ‘example.zip/lib/’ 将只会从档案中的 ‘lib/’ 子目录导入。

Any files may be present in the ZIP archive, but importers are only
invoked for ‘.py’ and ‘.pyc’ files.  ZIP import of dynamic modules
(‘.pyd’, ‘.so’) is disallowed.  Note that if an archive only contains
‘.py’ files, Python will not attempt to modify the archive by adding the
corresponding ‘.pyc’ file, meaning that if a ZIP archive doesn’t contain
‘.pyc’ files, importing may be rather slow.

3.8 版更變: 以前，不支持带有档案注释的 ZIP 档案。

也參考
......

PKZIP Application Note(2)

     Phil Katz 编写的 ZIP 文件格式文档，此格式和使用的算法的创建者。

PEP 273(3) -  从ZIP压缩包导入模块

     由 James C. Ahlstrom 编写，他也提供了实现。 Python 2.3 遵循 PEP
     273(4) 的规范，但是使用 Just van Rossum 编写的使用了 PEP 302(5) 中
     描述的导入钩的实现。

PEP 302(6) - 新导入钩

     PEP 添加导入钩来有助于模块运作。

此模块定义了一个异常：

 -- 例外: zipimport.ZipImportError

     异常由 zipimporter 对象引发。这是 *note ImportError: 16c. 的子类，
     因此，也可以捕获为 *note ImportError: 16c. 。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/zipimport.py

   (2) https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT

   (3) https://www.python.org/dev/peps/pep-0273

   (4) https://www.python.org/dev/peps/pep-0273

   (5) https://www.python.org/dev/peps/pep-0302

   (6) https://www.python.org/dev/peps/pep-0302


File: python.info,  Node: zipimporter 对象,  Next: 示例<43>,  Up: zipimport --- 从 Zip 存档中导入模块

5.31.1.1 zipimporter 对象
.........................

*note zipimporter: 38d1. 是用于导入 ZIP 文件的类。

 -- 類別: zipimport.zipimporter (archivepath)

     创建新的 zipimporter 实例。 `archivepath' 必须是指向 ZIP 文件的路径
     ，或者 ZIP 文件中的特定路径。例如， ‘foo/bar.zip/lib’ 的
     `archivepath' 将在 ZIP 文件 ‘foo/bar.zip’ 中的 ‘lib’ 目录中查找模块
     （只要它存在）。

     如果 `archivepath' 没有指向一个有效的 ZIP 档案，引发 *note
     ZipImportError: 38ce. 。

      -- 成員函式: find_module (fullname[, path])

          搜索由 `fullname' 指定的模块。 `fullname' 必须是完全合格的（点
          分的）模块名。它返回 zipimporter 实例本身如果模块被找到，或者
          返回 *note None: 203. 如果没找到指定模块。可选的 `path' 被忽略
          ，这是为了与导入器协议兼容。

      -- 成員函式: get_code (fullname)

          返回指定模块的代码对象。如果不能找到模块会引发 *note
          ZipImportError: 38ce. 错误。

      -- 成員函式: get_data (pathname)

          返回与 `pathname' 相关联的数据。如果不能找到文件则引发 *note
          OSError: 304. 错误。

          3.3 版更變: 曾经是 *note IOError: a73. 被引发而不是 *note
          OSError: 304. 。

      -- 成員函式: get_filename (fullname)

          如果导入了指定的模块 ‘__file__’ ，则返回为该模块设置的值。如果
          未找到模块则引发 *note ZipImportError: 38ce. 错误。

          3.1 版新加入.

      -- 成員函式: get_source (fullname)

          返回指定模块的源代码。如果没有找到模块则引发 *note
          ZipImportError: 38ce. ，如果档案包含模块但是没有源代码，返回
          *note None: 203. 。

      -- 成員函式: is_package (fullname)

          如果由 `fullname' 指定的模块是一个包则返回 ‘True’ 。如果不能找
          到模块则引发 *note ZipImportError: 38ce. 错误。

      -- 成員函式: load_module (fullname)

          加载由 `fullname' 指定的模块。 `fullname' 必须是完全限定的（点
          分的）模块名。它返回已加载模块，或者当找不到模块时引发 *note
          ZipImportError: 38ce. 错误。

      -- 屬性: archive

          导入器关联的 ZIP 文件的文件名，没有可能的子路径。

      -- 屬性: prefix

          ZIP 文件中搜索的模块的子路径。这是一个指向 ZIP 文件根目录的
          zipimporter 对象的空字符串。

     当与斜杠结合使用时， *note archive: 38d8. 和 *note prefix: 38d9. 属
     性等价于赋予 *note zipimporter: 38d1. 构造器的原始 `archivepath' 参
     数。


File: python.info,  Node: 示例<43>,  Prev: zipimporter 对象,  Up: zipimport --- 从 Zip 存档中导入模块

5.31.1.2 示例
.............

这是一个从 ZIP 档案中导入模块的例子 - 请注意 *note zipimport: 14c. 模块
不需要明确地使用。

     $ 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'


File: python.info,  Node: pkgutil --- 包扩展工具,  Next: modulefinder --- 查找脚本使用的模块,  Prev: zipimport --- 从 Zip 存档中导入模块,  Up: 匯入模組

5.31.2 ‘pkgutil’ — 包扩展工具
-----------------------------

`源代码:' Lib/pkgutil.py(1)

__________________________________________________________________

该模块为导入系统提供了工具，尤其是在包支持方面。

 -- 類別: pkgutil.ModuleInfo (module_finder, name, ispkg)

     一个包含模块信息的简短摘要的命名元组。

     3.6 版新加入.

 -- 函式: pkgutil.extend_path (path, name)

     Extend the search path for the modules which comprise a package.
     Intended use is to place the following code in a package’s
     ‘__init__.py’:

          from pkgutil import extend_path
          __path__ = extend_path(__path__, __name__)

     This will add to the package’s ‘__path__’ all subdirectories of
     directories on ‘sys.path’ named after the package.  This is useful
     if one wants to distribute different parts of a single logical
     package as multiple directories.

     It also looks for ‘*.pkg’ files beginning where ‘*’ matches the
     `name' argument.  This feature is similar to ‘*.pth’ files (see the
     *note site: eb. module for more information), except that it
     doesn’t special-case lines starting with ‘import’.  A ‘*.pkg’ file
     is trusted at face value: apart from checking for duplicates, all
     entries found in a ‘*.pkg’ file are added to the path, regardless
     of whether they exist on the filesystem.  (This is a feature.)

     If the input path is not a list (as is the case for frozen
     packages) it is returned unchanged.  The input path is not
     modified; an extended copy is returned.  Items are only appended to
     the copy at the end.

     It is assumed that *note sys.path: 261. is a sequence.  Items of
     *note sys.path: 261. that are not strings referring to existing
     directories are ignored.  Unicode items on *note sys.path: 261.
     that cause errors when used as filenames may cause this function to
     raise an exception (in line with *note os.path.isdir(): 327.
     behavior).

 -- 類別: pkgutil.ImpImporter (dirname=None)

     PEP 302(2) Finder that wraps Python’s "classic" import algorithm.

     If `dirname' is a string, a PEP 302(3) finder is created that
     searches that directory.  If `dirname' is ‘None’, a PEP 302(4)
     finder is created that searches the current *note sys.path: 261,
     plus any modules that are frozen or built-in.

     Note that *note ImpImporter: 38df. does not currently support being
     used by placement on *note sys.meta_path: 6dd.

     3.3 版後已棄用: This emulation is no longer needed, as the standard
     import mechanism is now fully PEP 302(5) compliant and available in
     *note importlib: 9a.

 -- 類別: pkgutil.ImpLoader (fullname, file, filename, etc)

     *note Loader: 15f6. that wraps Python’s "classic" import algorithm.

     3.3 版後已棄用: This emulation is no longer needed, as the standard
     import mechanism is now fully PEP 302(6) compliant and available in
     *note importlib: 9a.

 -- 函式: pkgutil.find_loader (fullname)

     Retrieve a module *note loader: 15f6. for the given `fullname'.

     This is a backwards compatibility wrapper around *note
     importlib.util.find_spec(): a1c. that converts most failures to
     *note ImportError: 16c. and only returns the loader rather than the
     full ‘ModuleSpec’.

     3.3 版更變: Updated to be based directly on *note importlib: 9a.
     rather than relying on the package internal PEP 302(7) import
     emulation.

     3.4 版更變: Updated to be based on PEP 451(8)

 -- 函式: pkgutil.get_importer (path_item)

     Retrieve a *note finder: 15f5. for the given `path_item'.

     The returned finder is cached in *note sys.path_importer_cache:
     597. if it was newly created by a path hook.

     The cache (or part of it) can be cleared manually if a rescan of
     *note sys.path_hooks: a3d. is necessary.

     3.3 版更變: Updated to be based directly on *note importlib: 9a.
     rather than relying on the package internal PEP 302(9) import
     emulation.

 -- 函式: pkgutil.get_loader (module_or_name)

     Get a *note loader: 15f6. object for `module_or_name'.

     If the module or package is accessible via the normal import
     mechanism, a wrapper around the relevant part of that machinery is
     returned.  Returns ‘None’ if the module cannot be found or
     imported.  If the named module is not already imported, its
     containing package (if any) is imported, in order to establish the
     package ‘__path__’.

     3.3 版更變: Updated to be based directly on *note importlib: 9a.
     rather than relying on the package internal PEP 302(10) import
     emulation.

     3.4 版更變: Updated to be based on PEP 451(11)

 -- 函式: pkgutil.iter_importers (fullname='')

     Yield *note finder: 15f5. objects for the given module name.

     If fullname contains a ’.’, the finders will be for the package
     containing fullname, otherwise they will be all registered top
     level finders (i.e.  those on both sys.meta_path and
     sys.path_hooks).

     If the named module is in a package, that package is imported as a
     side effect of invoking this function.

     If no module name is specified, all top level finders are produced.

     3.3 版更變: Updated to be based directly on *note importlib: 9a.
     rather than relying on the package internal PEP 302(12) import
     emulation.

 -- 函式: pkgutil.iter_modules (path=None, prefix='')

     Yields *note ModuleInfo: 703. for all submodules on `path', or, if
     `path' is ‘None’, all top-level modules on ‘sys.path’.

     `path' should be either ‘None’ or a list of paths to look for
     modules in.

     `prefix' is a string to output on the front of every module name on
     output.

          備註: Only works for a *note finder: 15f5. which defines an
          ‘iter_modules()’ method.  This interface is non-standard, so
          the module also provides implementations for *note
          importlib.machinery.FileFinder: a96. and *note
          zipimport.zipimporter: 38d1.

     3.3 版更變: Updated to be based directly on *note importlib: 9a.
     rather than relying on the package internal PEP 302(13) import
     emulation.

 -- 函式: pkgutil.walk_packages (path=None, prefix='', onerror=None)

     Yields *note ModuleInfo: 703. for all modules recursively on
     `path', or, if `path' is ‘None’, all accessible modules.

     `path' should be either ‘None’ or a list of paths to look for
     modules in.

     `prefix' is a string to output on the front of every module name on
     output.

     Note that this function must import all `packages' (`not' all
     modules!)  on the given `path', in order to access the ‘__path__’
     attribute to find submodules.

     `onerror' is a function which gets called with one argument (the
     name of the package which was being imported) if any exception
     occurs while trying to import a package.  If no `onerror' function
     is supplied, *note ImportError: 16c.s are caught and ignored, while
     all other exceptions are propagated, terminating the search.

     例如:

          # list all modules python can access
          walk_packages()

          # list all submodules of ctypes
          walk_packages(ctypes.__path__, ctypes.__name__ + '.')

          備註: Only works for a *note finder: 15f5. which defines an
          ‘iter_modules()’ method.  This interface is non-standard, so
          the module also provides implementations for *note
          importlib.machinery.FileFinder: a96. and *note
          zipimport.zipimporter: 38d1.

     3.3 版更變: Updated to be based directly on *note importlib: 9a.
     rather than relying on the package internal PEP 302(14) import
     emulation.

 -- 函式: pkgutil.get_data (package, resource)

     从包中获取一个资源。

     This is a wrapper for the *note loader: 15f6. *note get_data: 38e4.
     API. The `package' argument should be the name of a package, in
     standard module format (‘foo.bar’).  The `resource' argument should
     be in the form of a relative filename, using ‘/’ as the path
     separator.  The parent directory name ‘..’ is not allowed, and nor
     is a rooted name (starting with a ‘/’).

     The function returns a binary string that is the contents of the
     specified resource.

     For packages located in the filesystem, which have already been
     imported, this is the rough equivalent of:

          d = os.path.dirname(sys.modules[package].__file__)
          data = open(os.path.join(d, resource), 'rb').read()

     If the package cannot be located or loaded, or it uses a *note
     loader: 15f6. which does not support *note get_data: 38e4, then
     ‘None’ is returned.  In particular, the *note loader: 15f6. for
     *note namespace packages: 15ee. does not support *note get_data:
     38e4.

 -- 函式: pkgutil.resolve_name (name)

     Resolve a name to an object.

     This functionality is used in numerous places in the standard
     library (see bpo-12915(15)) - and equivalent functionality is also
     in widely used third-party packages such as setuptools, Django and
     Pyramid.

     It is expected that `name' will be a string in one of the following
     formats, where W is shorthand for a valid Python identifier and dot
     stands for a literal period in these pseudo-regexes:

        * ‘W(.W)*’

        * ‘W(.W)*:(W(.W)*)?’

     The first form is intended for backward compatibility only.  It
     assumes that some part of the dotted name is a package, and the
     rest is an object somewhere within that package, possibly nested
     inside other objects.  Because the place where the package stops
     and the object hierarchy starts can’t be inferred by inspection,
     repeated attempts to import must be done with this form.

     In the second form, the caller makes the division point clear
     through the provision of a single colon: the dotted name to the
     left of the colon is a package to be imported, and the dotted name
     to the right is the object hierarchy within that package.  Only one
     import is needed in this form.  If it ends with the colon, then a
     module object is returned.

     The function will return an object (which might be a module), or
     raise one of the following exceptions:

     *note ValueError: 16d. – if `name' isn’t in a recognised format.

     *note ImportError: 16c. – if an import failed when it shouldn’t
     have.

     *note AttributeError: 4a1. – If a failure occurred when traversing
     the object hierarchy within the imported package to get to the
     desired object.

     3.9 版新加入.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/pkgutil.py

   (2) https://www.python.org/dev/peps/pep-0302

   (3) https://www.python.org/dev/peps/pep-0302

   (4) https://www.python.org/dev/peps/pep-0302

   (5) https://www.python.org/dev/peps/pep-0302

   (6) https://www.python.org/dev/peps/pep-0302

   (7) https://www.python.org/dev/peps/pep-0302

   (8) https://www.python.org/dev/peps/pep-0451

   (9) https://www.python.org/dev/peps/pep-0302

   (10) https://www.python.org/dev/peps/pep-0302

   (11) https://www.python.org/dev/peps/pep-0451

   (12) https://www.python.org/dev/peps/pep-0302

   (13) https://www.python.org/dev/peps/pep-0302

   (14) https://www.python.org/dev/peps/pep-0302

   (15) https://bugs.python.org/issue12915


File: python.info,  Node: modulefinder --- 查找脚本使用的模块,  Next: runpy ——查找并执行 Python 模块,  Prev: pkgutil --- 包扩展工具,  Up: 匯入模組

5.31.3 ‘modulefinder’ — 查找脚本使用的模块
------------------------------------------

`源码：' Lib/modulefinder.py(1)

__________________________________________________________________

该模块提供了一个 *note ModuleFinder: 111b. 类，可用于确定脚本导入的模块
集。 ‘modulefinder.py’ 也可以作为脚本运行，给出 Python 脚本的文件名作为
参数，之后将打印导入模块的报告。

 -- 函式: modulefinder.AddPackagePath (pkg_name, path)

     记录名为 `pkg_name' 的包可以在指定的 `path' 中找到。

 -- 函式: modulefinder.ReplacePackage (oldname, newname)

     允许指定名为 `oldname' 的模块实际上是名为 `newname' 的包。

 -- 類別: modulefinder.ModuleFinder (path=None, debug=0, excludes=[],
          replace_paths=[])

     该类提供 *note run_script(): 38ea. 和 *note report(): 38eb. 方法，
     用于确定脚本导入的模块集。 `path' 可以是搜索模块的目录列表；如果没
     有指定，则使用 ‘sys.path’ 。 `debug' 设置调试级别；更高的值使类打印
     调试消息，关于它正在做什么。 `excludes' 是要从分析中排除的模块名称
     列表。 `replace_paths' 是将在模块路径中替换的 ‘(oldpath, newpath)’
     元组的列表。

      -- 成員函式: report ()

          将报告打印到标准输出，列出脚本导入的模块及其路径，以及缺少或似
          乎缺失的模块。

      -- 成員函式: run_script (pathname)

          分析 `pathname' 文件的内容，该文件必须包含 Python 代码。

      -- 屬性: modules

          一个将模块名称映射到模块的字典。 请参阅 *note ModuleFinder
          的示例用法: 38ed.。

* Menu:

* ModuleFinder 的示例用法::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/modulefinder.py


File: python.info,  Node: ModuleFinder 的示例用法,  Up: modulefinder --- 查找脚本使用的模块

5.31.3.1 ‘ModuleFinder’ 的示例用法
..................................

稍后将分析的脚本（bacon.py）:

     import re, itertools

     try:
         import baconhameggs
     except ImportError:
         pass

     try:
         import guido.python.ham
     except ImportError:
         pass

将输出 bacon.py 报告的脚本:

     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='')
         print(','.join(list(mod.globalnames.keys())[:3]))

     print('-'*50)
     print('Modules not imported:')
     print('\n'.join(finder.badmodules.keys()))

输出样例（可能因架构而异）:

     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


File: python.info,  Node: runpy ——查找并执行 Python 模块,  Next: importlib --- import 的实现,  Prev: modulefinder --- 查找脚本使用的模块,  Up: 匯入模組

5.31.4 ‘runpy’ ——查找并执行 Python 模块
---------------------------------------

`源代码：' Lib/runpy.py(1)

__________________________________________________________________

*note runpy: e2. 模块用于找到并运行 Python 的模块，而无需首先导入。主要
用于实现 *note -m: 443. 命令行开关，以允许用 Python 模块命名空间而不是文
件系统来定位脚本。

请注意，这 `并非' 一个沙盒模块——所有代码都在当前进程中运行，所有副作用（
如其他模块对导入操作进行了缓存）在函数返回后都会留存。

此外，在 *note runpy: e2. 函数返回后，任何由已执行代码定义的函数和类都不
能保证正确工作。如果某使用场景不能接收此限制，那么选用 *note importlib:
9a. 可能更合适些。

*note runpy: e2. 模块提供两个函数：

 -- 函式: runpy.run_module (mod_name, init_globals=None, run_name=None,
          alter_sys=False)

     执行给定模块的代码，并返回结果模块的 globals 字典。 该模块的代码首
     先会用标准的导入机制去查找定位 (详情请参阅 PEP 302(2))，然后在全新
     的模块命名空间中运行。

     参数 `mod_name' 应该是一个绝对模块名。如果模块名指向一个包，而不是
     普通的模块，那么该包会被导入，然后执行包中的 ‘__main__’ 子模块，并
     返回结果模块的 globals 字典。

     可选的字典参数 `init_globals' 可用来在代码执行前预填充模块的
     globals 字典。给出的字典参数不会被修改。如果字典中定义了以下任意一
     个特殊全局变量，这些定义都会被 *note run_module(): 146f. 覆盖。

     The special global variables ‘__name__’, ‘__spec__’, ‘__file__’,
     ‘__cached__’, ‘__loader__’ and ‘__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).

     若可选参数 ‘__name__’ 不为 *note None: 203. 则设为 `run_name'，若此
     名称的模块是一个包则设为 ‘mod_name + '.__main__'’，否则设为
     `mod_name' 参数。

     ‘__spec__’ 将设为合适的 `实际' 导入模块（也就是说，‘__spec__.name’
     一定是 `mod_name' 或 ‘mod_name + '.__main__’，而不是 `run_name'）。

     ‘__file__’ 、‘__cached__’、 ‘__loader__’ 和 ‘__package__’ 根据模块
     规范进行 *note 正常设置: 15fd.

     如果给出了参数 `alter_sys' 并且值为 *note True: 593.，那么
     ‘sys.argv[0]’ 将被更新为 ‘__file__’ 的值，‘sys.modules[__name__]’ 将
     被更新为临时模块对象。在函数返回前， ‘sys.argv[0]’ 和
     ‘sys.modules[__name__]’ 将会复原。

     注意，这种对 *note sys: fd. 的操作不是线程安全的。其他线程可能会看
     到初始化不完整的模块，以及变动后的参数列表。如果从线程中的代码调用
     此函数，建议单实例运行 *note sys: fd. 模块。

     也參考
     ......

     *note -m: 443. 选项由命令行提供相同功能。

     3.1 版更變: 加入了 查找 ‘__main__’ 子模块并执行软件包的能力。

     3.2 版更變: 加入了 ‘__cached__’ 全局变量（参见 PEP 3147(3) ）。

     3.4 版更變: 充分利用 PEP 451(4) 加入的模块规格功能。使得以这种方式
     运行的模块能够正确设置 ‘__cached__’，并确保真正的模块名称总是可以通
     过 ‘__spec__.name’ 的形式访问。

 -- 函式: runpy.run_path (file_path, init_globals=None, run_name=None)

     执行指定位置的代码，并返回结果模块的 globals 字典。与提供给 CPython
     命令行的脚本名称一样，给出的路径可以指向 Python 源文件、编译过的字
     节码文件或包含‘‘__main__‘‘ 模块的有效 sys.path 项（例如一个包含顶级
     ‘‘__main__.py‘‘ 文件的 zip 文件）。

     对于直接的脚本而言，指定代码将直接在一个新的模块命名空间中运行。对
     于一个有效的 sys.path 项（通常是一个 zip 文件或目录），其首先会被添
     加到 ‘sys.path’ 的开头。然后，本函数用更新后的路径查找并执行 *note
     __main__: 1. 模块。请注意，即便在指定位置不存在主模块，也没有特别的
     保护措施来防止调用存在于 ‘sys.path’ 其他地方的 *note __main__: 1.。

     利用可选的字典参数 `init_globals' ，可在代码执行前预填模块的
     globals 字典。给出的字典参数不会被修改。如果给出的字典中定义了下列
     特殊全局变量，这些定义均会被 *note run_module(): 146f. 覆盖。

     The special global variables ‘__name__’, ‘__spec__’, ‘__file__’,
     ‘__cached__’, ‘__loader__’ and ‘__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).

     如果该可选参数不为 *note None: 203.，则 ‘__name__’ 被设为
     `run_name'，否则为 ‘'<run_path>'’。

     如果提供的路径直接引用了一个脚本文件（无论是源码文件还是预编译的字
     节码），那么 ‘__file__’ 将设为给出的路径，而 ‘__spec__’、
     ‘__cached__’、‘__loader__’ 和 ‘__package__’ 都将设为 *note None:
     203.。

     如果给出的路径是对有效 sys.path 项的引用，那么 ‘__spec__’ 将为导入
     的 ‘__main__’ 模块进行正确设置 (也就是说，‘__spec__.name’ 将一定是
     ‘__main__’)。 ‘__file__’, ‘__cached__’, ‘__loader__’ 和
     ‘__package__’ 将依据模块规格 *note 进行常规设置: 15fd.。

     *note sys: fd. 模块也做了一些改动。 首先，如上所述，‘sys.path’ 可能
     会被修改。 ‘sys.argv[0]’ 被更新为 ‘file_path’ 的值，
     ‘sys.modules[__name__]’ 被更新为正在被执行的模块的临时模块对象。 在
     函数返回之前，对 *note sys: fd. 中条目的所有修改都会被复原。

     注意，与 *note run_module(): 146f. 不同的是，本函数对 *note sys:
     fd. 的修改不是可有可无的，因为这些调整对于 sys.path 项能够顺利执行
     至关重要。由于依然存在线程安全的限制，在线程代码中使用本函数时应采
     用导入锁进行序列运行，或者委托给一个单独的进程。

     也參考
     ......

     *note 接口选项: 146e. 用于在命令行上实现同等功能（‘python
     path/to/script’）。

     3.2 版新加入.

     3.4 版更變: 已作更新，以便充分利用 PEP 451(5) 加入的模块规格功能。
     使得从有效 sys.path 项导入‘‘__main__‘‘ 而不是直接执行的情况下，能够
     正确设置 ‘__cached__’。

也參考
......

PEP 338(6) – 将模块作为脚本执行

     PEP 由 Nick Coghlan 撰写并实现。

PEP 366(7) ——主模块的显式相对导入

     PEP 由 Nick Coghlan 撰写并实现。

PEP 451(8) —— 导入系统采用的 ModuleSpec 类型

     PEP 由 Eric Snow 撰写并实现。

*note 命令行与环境: 10bd. —— CPython 命令行详解

*note importlib.import_module(): be6. 函数

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/runpy.py

   (2) https://www.python.org/dev/peps/pep-0302

   (3) https://www.python.org/dev/peps/pep-3147

   (4) https://www.python.org/dev/peps/pep-0451

   (5) https://www.python.org/dev/peps/pep-0451

   (6) https://www.python.org/dev/peps/pep-0338

   (7) https://www.python.org/dev/peps/pep-0366

   (8) https://www.python.org/dev/peps/pep-0451


File: python.info,  Node: importlib --- import 的实现,  Next: Using importlib metadata,  Prev: runpy ——查找并执行 Python 模块,  Up: 匯入模組

5.31.5 ‘importlib’ — ‘import’ 的实现
------------------------------------

3.1 版新加入.

`源代码' Lib/importlib/__init__.py(1)

__________________________________________________________________

* Menu:

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

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/Lib/importlib/__init__.py


File: python.info,  Node: 簡介<11>,  Next: 函数<11>,  Up: importlib --- import 的实现

5.31.5.1 簡介
.............

*note importlib: 9a. 包的目的有两个。 第一个目的是在 Python 源代码中提供
*note import: ce7. 语句的实现（并且因此而扩展 *note __import__(): 16b. 函
数）。 这提供了一个可移植到任何 Python 解释器的 ‘import’ 实现。 相比使用
Python 以外的编程语言实现方式，这一实现更加易于理解。

第二个目的是实现 *note import: ce7. 的部分被公开在这个包中，使得用户更容
易创建他们自己的自定义对象 (通常被称为 *note importer: 15f7.) 来参与到导
入过程中。

也參考
......

*note import 语句: ce7.

     *note import: ce7. 语句的语言参考

包规格说明(1)

     包的初始规范。自从编写这个文档开始，一些语义已经发生改变了（比如基
     于 *note sys.modules: 1051. 中 ‘None’ 的重定向）。

*note __import__(): a8e. 函数

     *note import: ce7. 语句是这个函数的语法糖。

PEP 235(2)

     在忽略大小写的平台上进行导入

PEP 263(3)

     定义 Python 源代码编码

PEP 302(4)

     新导入钩子

PEP 328(5)

     导入：多行和绝对/相对

PEP 366(6)

     主模块显式相对导入

PEP 420(7)

     隐式命名空间包

PEP 451(8)

     导入系统的一个模块规范类型

PEP 488(9)

     消除PYO文件

PEP 489(10)

     多阶段扩展模块初始化

PEP 552(11)

     确定性的 pyc 文件

PEP 3120(12)

     使用 UTF-8 作为默认的源编码

PEP 3147(13)

     PYC 仓库目录

   ---------- Footnotes ----------

   (1) https://www.python.org/doc/essays/packages/

   (2) https://www.python.org/dev/peps/pep-0235

   (3) https://www.python.org/dev/peps/pep-0263

   (4) https://www.python.org/dev/peps/pep-0302

   (5) https://www.python.org/dev/peps/pep-0328

   (6) https://www.python.org/dev/peps/pep-0366

   (7) https://www.python.org/dev/peps/pep-0420

   (8) https://www.python.org/dev/peps/pep-0451

   (9) https://www.python.org/dev/peps/pep-0488

   (10) https://www.python.org/dev/peps/pep-0489

   (11) https://www.python.org/dev/peps/pep-0552

   (12) https://www.python.org/dev/peps/pep-3120

   (13) https://www.python.org/dev/peps/pep-3147


File: python.info,  Node: 函数<11>,  Next: importlib abc —— 关于导入的抽象基类,  Prev: 簡介<11>,  Up: importlib --- import 的实现

5.31.5.2 函数
.............

 -- 函式: importlib.__import__ (name, globals=None, locals=None,
          fromlist=(), level=0)

     内置 *note __import__(): 16b. 函数的实现。

          備註: 程序式地导入模块应该使用 *note import_module(): be6. 而
          不是这个函数。

 -- 函式: importlib.import_module (name, package=None)

     导入一个模块。参数 `name' 指定了以绝对或相对导入方式导入什么模块 (比
     如要么像这样 ‘pkg.mod’ 或者这样 ‘..mod’)。如果参数 name 使用相对导
     入的方式来指定，那么那个参数 `packages' 必须设置为那个包名，这个包
     名作为解析这个包名的锚点 (比如 ‘import_module('..mod',
     'pkg.subpkg')’ 将会导入 ‘pkg.mod’)。

     *note import_module(): be6. 函数是一个对 *note
     importlib.__import__(): a8e. 进行简化的包装器。 这意味着该函数的所
     有主义都来自于 *note importlib.__import__(): a8e.。 这两个函数之间
     最重要的不同点在于 *note import_module(): be6. 返回指定的包或模块
     (例如 ‘pkg.mod’)，而 *note __import__(): 16b. 返回最高层级的包或模
     块 (例如 ‘pkg’)。

     如果动态导入一个自从解释器开始执行以来被创建的模块（即创建了一个
     Python 源代码文件），为了让导入系统知道这个新模块，可能需要调用
     *note invalidate_caches(): 596.。

     3.3 版更變: 父包会被自动导入。

 -- 函式: importlib.find_loader (name, path=None)

     查找一个模块的加载器，可选择地在指定的 `path' 里面。如果这个模块是
     在 *note sys.modules: 1051.，那么返回
     ‘sys.modules[name].__loader__’ (除非这个加载器是 ‘None’ 或者是没有
     被设置， 在这样的情况下，会引起 *note ValueError: 16d. 异常）。 否
     则使用 *note sys.meta_path: 6dd. 的一次搜索就结束。如果未发现加载器
     ，则返回 ‘None’。

     点状的名称没有使得它父包或模块隐式地导入，因为它需要加载它们并且可
     能不需要。为了适当地导入一个子模块，需要导入子模块的所有父包并且使
     用正确的参数提供给 `path'。

     3.3 版新加入.

     3.4 版更變: 如果没有设置 ‘__loader__’，会引起 *note ValueError:
     16d. 异常，就像属性设置为 ‘None’ 的时候一样。

     3.4 版後已棄用: 使用 *note importlib.util.find_spec(): a1c. 来代替
     。

 -- 函式: importlib.invalidate_caches ()

     使查找器存储在 *note sys.meta_path: 6dd. 中的内部缓存无效。如果一个
     查找器实现了 ‘invalidate_caches()’，那么它会被调用来执行那个无效过
     程。 如果创建/安装任何模块，同时正在运行的程序是为了保证所有的查找
     器知道新模块的存在，那么应该调用这个函数。

     3.3 版新加入.

 -- 函式: importlib.reload (module)

     重新加载之前导入的 `module'。那个参数必须是一个模块对象，所以它之前
     必须已经成功导入了。这样做是有用的，如果使用外部编辑器编已经辑过了
     那个模块的源代码文件并且想在退出 Python 解释器之前试验这个新版本的
     模块。函数的返回值是那个模块对象（如果重新导入导致一个不同的对象放
     置在 *note sys.modules: 1051. 中，那么那个模块对象是有可能会不同）
     。

     当执行 *note reload(): 49f. 的时候：

        * Python 模块的代码会被重新编译并且那个模块级的代码被重新执行，
          通过重新使用一开始加载那个模块的 *note loader: 15f6.，定义一个
          新的绑定在那个模块字典中的名称的对象集合。扩展模块的‘‘init‘‘函
          数不会被调用第二次。

        * 与Python中的所有的其它对象一样，旧的对象只有在它们的引用计数为
          0之后才会被回收。

        * 模块命名空间中的名称重新指向任何新的或更改后的对象。

        * 其他旧对象的引用（例如那个模块的外部名称）不会被重新绑定到引用
          的新对象的，并且如果有需要，必须在出现的每个命名空间中进行更新
          。

     有一些其他注意事项：

     当一个模块被重新加载的时候，它的字典（包含了那个模块的全区变量）会
     被保留。名称的重新定义会覆盖旧的定义，所以通常来说这不是问题。如果
     一个新模块没有定义在旧版本模块中定义的名称，则将保留旧版本中的定义
     。这一特性可用于作为那个模块的优点，如果它维护一个全局表或者对象的
     缓存 —— 使用 *note try: e37. 语句，就可以测试表的存在并且跳过它的初
     始化，如果有需要的话:

          try:
              cache
          except NameError:
              cache = {}

     重新加载内置的或者动态加载模块，通常来说不是很有用处。不推荐重新加
     载"*note sys: fd.，*note __main__: 1.，*note builtins: 12. 和其它关
     键模块。在很多例子中，扩展模块并不是设计为不止一次的初始化，并且当
     重新加载时，可能会以任意方式失败。

     如果一个模块使用 *note from: d0d. ...  *note import: ce7. ... 导入
     的对象来自另外一个模块，给其它模块调用 *note reload(): 49f. 不会重
     新定义来自这个模块的对象 —— 解决这个问题的一种方式是重新执行 ‘from’
     语句，另一种方式是使用 ‘import’ 和限定名称(`module.name')来代替。

     如果一个模块创建一个类的实例，重新加载定义那个类的模块不影响那些实
     例的方法定义———它们继续使用旧类中的定义。对于子类来说同样是正确的。

     3.4 版新加入.

     3.7 版更變: 当重新加载的那个模块缺少 ‘ModuleSpec’ 的时候，会引起
     *note ModuleNotFoundError: 4a0. 异常。


File: python.info,  Node: importlib abc —— 关于导入的抽象基类,  Next: importlib resources -- 资源,  Prev: 函数<11>,  Up: importlib --- import 的实现

5.31.5.3 ‘importlib.abc’ —— 关于导入的抽象基类
..............................................

`源代码：' Lib/importlib/abc.py(1)

__________________________________________________________________

The *note importlib.abc: 9b. module contains all of the core abstract
base classes used by *note import: ce7.  Some subclasses of the core
abstract base classes are also provided to help in implementing the core
ABCs.

ABC 类的层次结构：

     object
      +-- Finder (deprecated)
      |    +-- MetaPathFinder
      |    +-- PathEntryFinder
      +-- Loader
           +-- ResourceLoader --------+
           +-- InspectLoader          |
                +-- ExecutionLoader --+
                                      +-- FileLoader
                                      +-- SourceLoader

 -- 類別: importlib.abc.Finder

     代表 *note finder: 15f5. 的一个抽象基类

     3.3 版後已棄用: 使用 *note MetaPathFinder: a93. 或 *note
     PathEntryFinder: a94. 来代替。

      -- 成員函式: abstractmethod find_module (fullname, path=None)

          为指定的模块查找 *note loader: 15f6. 定义的抽象方法。本来是在
          PEP 302(2) 指定的，这个方法是在 *note sys.meta_path: 6dd. 和基
          于路径的导入子系统中使用。

          3.4 版更變: 当被调用的时候，返回 ‘None’ 而不是引发 *note
          NotImplementedError: 704.。

 -- 類別: importlib.abc.MetaPathFinder

     代表 *note meta path finder: a91. 的一个抽象基类。 为了保持兼容性，
     这是 *note Finder: a95. 的一个子类。

     3.3 版新加入.

      -- 成員函式: find_spec (fullname, path, target=None)

          一个抽象方法，用于查找指定模块的 *note spec: 37db. 。若是顶层
          导入，`path' 将为 ‘None’。 否则就是查找子包或模块，`path' 将是
          父级包的 *note __path__: 13c3. 值。找不到则会返回 ‘None’。传入
          的 ‘target’ 是一个模块对象，查找器可以用来对返回的规格进行更有
          依据的猜测。在实现具体的 ‘MetaPathFinders’ 代码时，可能会用到
          *note importlib.util.spec_from_loader(): 38f7. 。

          3.4 版新加入.

      -- 成員函式: find_module (fullname, path)

          一个用于查找指定的模块中 *note loader: 15f6. 的遗留方法。如果
          这是最高层级的导入，`path' 的值将会是 ‘None’。否则，这是一个查
          找子包或者模块的方法，并且 `path' 的值将会是来自父包的 *note
          __path__: 13c3. 的值。如果未发现加载器，返回 ‘None’。

          如果定义了 *note find_spec(): 564. 方法，则提供了向后兼容的功
          能。

          3.4 版更變: 当调用这个方法的时候返回 ‘None’ 而不是引发 *note
          NotImplementedError: 704.。 可以使用 *note find_spec(): 564. 来
          提供功能。

          3.4 版後已棄用: 使用 *note find_spec(): 564. 来代替。

      -- 成員函式: invalidate_caches ()

          当被调用的时候，一个可选的方法应该将查找器使用的任何内部缓存进
          行无效。将在 *note sys.meta_path: 6dd. 上的所有查找器的缓存进
          行无效的时候，这个函数被 *note importlib.invalidate_caches():
          596. 所使用。

          3.4 版更變: 当方法被调用的时候，方法返回是 ‘None’ 而不是
          ‘NotImplemented’ 。

 -- 類別: importlib.abc.PathEntryFinder

     *note path entry finder: a92. 的一个抽象基类。尽管这个基类和 *note
     MetaPathFinder: a93. 有一些相似之处，但是 ‘PathEntryFinder’ 只在由
     ‘PathFinder’ 提供的基于路径导入子系统中使用。这个抽象类是 *note
     Finder: 15f5. 的一个子类，仅仅是因为兼容性的原因。

     3.3 版新加入.

      -- 成員函式: find_spec (fullname, target=None)

          一个抽象方法，用于查找指定模块的 *note spec: 37db.。搜索器将只
          在指定的 *note path entry: 160b. 内搜索该模块。找不到则会返回
          ‘None’。在实现具体的 ‘PathEntryFinders’ 代码时，可能会用到
          *note importlib.util.spec_from_loader(): 38f7. 。

          3.4 版新加入.

      -- 成員函式: find_loader (fullname)

          一个用于在模块中查找一个 *note loader: 15f6. 的遗留方法。 返回
          一个 ‘(loader, portion)’ 的2元组，‘portion’ 是一个贡献给命名空
          间包部分的文件系统位置的序列。 加载器可能是 ‘None’，同时正在指
          定的 ‘portion’ 表示的是贡献给命名空间包的文件系统位置。
          ‘portion’ 可以使用一个空列表来表示加载器不是命名空间包的一部分
          。 如果 ‘loader’ 是 ‘None’ 并且 ‘portion’ 是一个空列表，那么命
          名空间包中无加载器或者文件系统位置可查找到（即在那个模块中未能
          找到任何东西）。

          如果定义了 *note find_spec(): 566. ，则提供了向后兼容的功能。

          3.4 版更變: 返回 ‘(None, [])’ 而不是引发 *note
          NotImplementedError: 704.。 当可于提供相应的功能的时候，使用
          *note find_spec(): 566.。

          3.4 版後已棄用: 使用 *note find_spec(): 566. 来代替。

      -- 成員函式: find_module (fullname)

          ‘Finder.find_module`的具体实现，该方法等价于
          ``self.find_loader(fullname)[0]`()’。

          3.4 版後已棄用: 使用 *note find_spec(): 566. 来代替。

      -- 成員函式: invalidate_caches ()

          当被调用的时候，一个可选的方法应该将查找器使用的任何内部缓存进
          行无效。当将所有缓存的查找器的缓存进行无效的时候，该函数被
          ‘PathFinder.invalidate_caches()’ 使用。

 -- 類別: importlib.abc.Loader

     *note loader: 15f6. 的抽象基类。 关于一个加载器的实际定义请查看 PEP
     302(3)。

     加载器想要支持资源读取应该实现一个由 *note
     importlib.abc.ResourceReader: 44e. 指定的
     ‘‘get_resource_reader(fullname)‘‘ 方法。

     3.7 版更變: 引入了可选的 ‘get_resource_reader()’ 方法。

      -- 成員函式: create_module (spec)

          当导入一个模块的时候，一个返回将要使用的那个模块对象的方法。这
          个方法可能返回 ‘None’ ，这暗示着应该发生默认的模块创建语义。"

          3.4 版新加入.

          3.5 版更變: 从 Python 3.6 开始，当定义了 *note exec_module():
          6db. 的时候，这个方法将不会是可选的。

      -- 成員函式: exec_module (module)

          当一个模块被导入或重新加载时，一个抽象方法在它自己的命名空间中
          执行那个模块。当调用 ‘exec_module()’ 的时候，那个模块应该已经
          被初始化 了。当这个方法存在时，必须定义 *note create_module():
          64e. 。

          3.4 版新加入.

          3.6 版更變: *note create_module(): 64e. 也必须被定义。

      -- 成員函式: load_module (fullname)

          用于加载一个模块的传统方法。如果这个模块不能被导入，将引起
          *note ImportError: 16c. 异常，否则返回那个被加载的模块。

          如果请求的模块已经存在 *note sys.modules: 1051.，应该使用并且
          重新加载那个模块。 否则加载器应该是创建一个新的模块并且在任何
          家过程开始之前将这个新模块插入到 *note sys.modules: 1051. 中，
          来阻止递归导入。 如果加载器插入了一个模块并且加载失败了，加载
          器必须从 *note sys.modules: 1051. 中将这个模块移除。在加载器开
          始执行之前，已经在 *note sys.modules: 1051. 中的模块应该被忽略
          (查看 *note importlib.util.module_for_loader(): a26.)。

          加载器应该在模块上面设置几个属性。（要知道当重新加载一个模块的
          时候，那些属性某部分可以改变）：

             - 
               *note __name__: dd8.

                    模块的名字

             - 
               *note __file__: 1562.

                    模块数据存储的路径(不是为了内置的模块而设置)

             - 
               *note __cached__: c04.

                    被存储或应该被存储的模块的编译版本的路径（当这个属性
                    不恰当的时候不设置）。

             - 
               *note __path__: 13c3.

                    指定在一个包中搜索路径的一个字符串列表。这个属性不在
                    模块上面进行设置。

             - 
               *note __package__: a36.

                    当模块作为子模块加载时，其所在包的完全限定名称（顶层
                    模块则为空字符串）。对于包而言，与 *note __name__:
                    dd8. 相同。 *note
                    importlib.util.module_for_loader(): a26. 装饰器能够
                    处理 *note __package__: a36. 的细节。

             - 
               *note __loader__: a37.

                    用来加载那个模块的加载器。 *note
                    importlib.util.module_for_loader(): a26. 装饰器可以
                    处理 *note __package__: a36. 的细节。

          当 *note exec_module(): 6db. 可用的时候，那么则提供了向后兼容
          的功能。

          3.4 版更變: 当这个方法被调用的时候，触发 *note ImportError:
          16c. 异常而不是 *note NotImplementedError: 704.。当 *note
          exec_module(): 6db. 可用的时候，使用它的功能。

          3.4 版後已棄用: 加载模块推荐的使用的 API 是 *note
          exec_module(): 6db. (和 *note create_module(): 64e.)。 加载器
          应该实现它而不是 load_module()。 当 exec_module() 被实现的时候
          ，导入机制关心的是 load_module() 所有其他的责任。

      -- 成員函式: module_repr (module)

          一个遗留方法，在实现时计算并返回给定模块的 repr，作为字符串。
          模块类型的默认 repr() 将根据需要使用此方法的结果。

          3.3 版新加入.

          3.4 版更變: 是可选的方法而不是一个抽象方法。

          3.4 版後已棄用: 现在导入机制会自动地关注这个方法。

 -- 類別: importlib.abc.ResourceReader

     `被 TraversableResources' 取代

     提供读取 `resources' 能力的一个 *note abstract base class: c05. 。

     从这个 ABC 的视角出发，`resource' 指一个包附带的二进制文件。常见的
     如在包的 ‘__init__.py’ 文件旁的数据文件。这个类存在的目的是为了将对
     数据文件的访问进行抽象，这样包就和其数据文件的存储方式无关了。不论
     这些文件是存放在一个 zip 文件里还是直接在文件系统内。

     对于该类中的任一方法，`resource' 参数的值都需要是一个在概念上表示文
     件名称的 *note path-like object: 472.。 这意味着任何子目录的路径都
     不该出现在 `resouce' 参数值内。 因为对于阅读器而言，包的位置就代表
     着「目录」。 因此目录和文件名就分别对应于包和资源。 这也是该类的实
     例都需要和一个包直接关联（而不是潜在指代很多包或者一整个模块）的原
     因。

     想支持资源读取的加载器需要提供一个返回实现了此 ABC 的接口的
     ‘get_resource_reader(fullname)’ 方法。如果通过全名指定的模块不是一
     个包，这个方法应该返回 *note None: 203.。 当指定的模块是一个包时，
     应该只返回一个与这个抽象类ABC兼容的对象。

     3.7 版新加入.

      -- 成員函式: abstractmethod open_resource (resource)

          返回一个打开的 *note file-like object: 1dc6. 用于 `resource' 的
          二进制读取。

          如果无法找到资源，将会引发 *note FileNotFoundError: 8ad.。

      -- 成員函式: abstractmethod resource_path (resource)

          返回 `resource' 的文件系统路径。

          如果资源并不实际存在于文件系统中，将会引发 *note
          FileNotFoundError: 8ad.。

      -- 成員函式: abstractmethod is_resource (name)

          如果*name* 被视作资源，则返回True。如果*name*不存在，则引发
          *note FileNotFoundError: 8ad. 异常。

      -- 成員函式: abstractmethod contents ()

          反回由字符串组成的 *note iterable: c7c.，表示这个包的所有内容
          。 请注意并不要求迭代器返回的所有名称都是实际的资源，例如返回
          *note is_resource(): 38fc. 为假值的名称也是可接受的。

          允许非资源名字被返回是为了允许存储的一个包和它的资源的方式是已
          知先验的并且非资源名字会有用的情况。比如，允许返回子目录名字，
          目的是当得知包和资源存储在文件系统上面的时候，能够直接使用子目
          录的名字。

          这个抽象方法返回了一个不包含任何内容的可迭代对象。

 -- 類別: importlib.abc.ResourceLoader

     一个 *note loader: 15f6. 的抽象基类，它实现了可选的 PEP 302(4) 协议
     用于从存储后端加载任意资源。

     3.7 版後已棄用: 由于要支持使用 *note importlib.abc.ResourceReader:
     44e. 类来加载资源，这个 ABC 已经被弃用了。

      -- 成員函式: abstractmethod get_data (path)

          一个用于返回位于 `path' 的字节数据的抽象方法。有一个允许存储任
          意数据的类文件存储后端的加载器能够实现这个抽象方法来直接访问这
          些被存储的数据。如果不能够找到 `path'，则会引发 *note OSError:
          304. 异常。`path' 被希望使用一个模块的 ‘__file’ 属性或来自一个
          包的 *note __path__: 13c3. 来构建。

          3.4 版更變: 引发 *note OSError: 304. 异常而不是 *note
          NotImplementedError: 704. 异常。

 -- 類別: importlib.abc.InspectLoader

     一个实现加载器检查模块可选的 PEP 302(5) 协议的 *note loader: 15f6.
     的抽象基类。

      -- 成員函式: get_code (fullname)

          返回一个模块的代码对象，或如果模块没有一个代码对象（例如，对于
          内置的模块来说，这会是这种情况），则为 ‘None’。 如果加载器不能
          找到请求的模块，则引发 *note ImportError: 16c. 异常。

               備註: 当这个方法有一个默认的实现的时候，出于性能方面的考
               虑，如果有可能的话，建议覆盖它。

          3.4 版更變: 不再抽象并且提供一个具体的实现。

      -- 成員函式: abstractmethod get_source (fullname)

          一个返回模块源的抽象方法。使用 *note universal newlines: 6eb.
          作为文本字符串被返回，将所有可识别行分割符翻译成 ‘'\n'’ 字符。
          如果没有可用的源（例如，一个内置模块），则返回 ‘None’。 如果加
          载器不能找到指定的模块，则引发 *note ImportError: 16c. 异常。

          3.4 版更變: 引发 *note ImportError: 16c. 而不是 *note
          NotImplementedError: 704.。

      -- 成員函式: is_package (fullname)

          可选方法，如果模块为包，则返回 True，否则返回 False。 如果
          *note loader: 15f6. 找不到模块，则会触发 *note ImportError:
          16c.。

          3.4 版更變: 引发 *note ImportError: 16c. 而不是 *note
          NotImplementedError: 704.。

      -- 成員函式: static source_to_code (data, path='<string>')

          创建一个来自Python源码的代码对象。

          参数 `data' 可以是任意 *note compile(): 2e7. 函数支持的类型（
          例如字符串或字节串）。 参数 `path' 应该是源代码来源的路径，这
          可能是一个抽象概念（例如位于一个 zip 文件中）。

          在有后续代码对象的情况下，可以在一个模块中通过运行‘‘exec(code,
          module.__dict__)‘‘来执行它。

          3.4 版新加入.

          3.5 版更變: 使得这个方法变成静态的。

      -- 成員函式: exec_module (module)

          *note Loader.exec_module(): 6db. 的实现。

          3.4 版新加入.

      -- 成員函式: load_module (fullname)

          *note Loader.load_module(): 6da. 的实现。

          3.4 版後已棄用: 使用 *note exec_module(): a23. 来代替。

 -- 類別: importlib.abc.ExecutionLoader

     一个继承自 *note InspectLoader: 94b. 的抽象基类，当被实现时，帮助一
     个模块作为脚本来执行。 这个抽象基类表示可选的 PEP 302(6) 协议。

      -- 成員函式: abstractmethod get_filename (fullname)

          一个用来为指定模块返回 *note __file__: 1562. 的值的抽象方法。
          如果无路径可用，则引发 *note ImportError: 16c.。

          如果源代码可用，那么这个方法返回源文件的路径，不管是否是用来加
          载模块的字节码。

          3.4 版更變: 引发 *note ImportError: 16c. 而不是 *note
          NotImplementedError: 704.。

 -- 類別: importlib.abc.FileLoader (fullname, path)

     一个继承自 *note ResourceLoader: 567. 和 *note ExecutionLoader:
     38fe.，提供 *note ResourceLoader.get_data(): 38e4. 和 *note
     ExecutionLoader.get_filename(): 38ff. 具体实现的抽象基类。

     参数*fullname*是加载器要处理的模块的完全解析的名字。参数*path*是模
     块文件的路径。

     3.3 版新加入.

      -- 屬性: name

          加载器可以处理的模块的名字。

      -- 屬性: path

          模块的文件路径

      -- 成員函式: load_module (fullname)

          调用super的‘‘load_module()‘‘。

          3.4 版後已棄用: 使用 *note Loader.exec_module(): 6db. 来代替。

      -- 成員函式: abstractmethod get_filename (fullname)

          返回 *note path: 3901.。

      -- 成員函式: abstractmethod get_data (path)

          读取 `path' 作为二进制文件并且返回来自它的字节数据。

 -- 類別: importlib.abc.SourceLoader

     一个用于实现源文件（和可选地字节码）加载的抽象基类。这个类继承自
     *note ResourceLoader: 567. 和 *note ExecutionLoader: 38fe.，需要实
     现：

        * *note ResourceLoader.get_data(): 38e4.

        * 
          *note ExecutionLoader.get_filename(): 38ff.

               应该是只返回源文件的路径；不支持无源加载。

     由这个类定义的抽象方法用来添加可选的字节码文件支持。不实现这些可选
     的方法（或导致它们引发 *note NotImplementedError: 704. 异常）导致这
     个加载器只能与源代码一起工作。 实现这些方法允许加载器能与源 `和' 字
     节码文件一起工作。不允许只提供字节码的 `无源式' 加载。字节码文件是
     通过移除 Python 编译器的解析步骤来加速加载的优化，并且因此没有开放
     出字节码专用的 API。

      -- 成員函式: path_stats (path)

          返回一个包含关于指定路径的元数据的 *note dict: 164. 的可选的抽
          象方法。 支持的字典键有：

             - ‘'mtime'’ (必选项): 一个表示源码修改时间的整数或浮点数；

             - ‘'size'’ (可选项)：源码的字节大小。

          字典中任何其他键会被忽略，以允许将来的扩展。 如果不能处理该路
          径，则会引发 *note OSError: 304.。

          3.3 版新加入.

          3.4 版更變: 引发 *note OSError: 304. 而不是 *note
          NotImplemented: 202.。

      -- 成員函式: path_mtime (path)

          返回指定文件路径修改时间的可选的抽象方法。

          3.3 版後已棄用: 在有了 *note path_stats(): bc3. 的情况下，这个
          方法被弃用了。 没必要去实现它了，但是为了兼容性，它依然处于可
          用状态。 如果文件路径不能被处理，则引发 *note OSError: 304. 异
          常。

          3.4 版更變: 引发 *note OSError: 304. 而不是 *note
          NotImplemented: 202.。

      -- 成員函式: set_data (path, data)

          往一个文件路径写入指定字节的的可选的抽象方法。任何中间不存在的
          目录不会被自动创建。

          由于路径是只读的，当写入的路径产生错误时（*note errno.EACCES:
          23a0./*note PermissionError: 6f6.），不会传播异常。

          3.4 版更變: 当被调用时，不再引起 *note NotImplementedError:
          704. 异常。

      -- 成員函式: get_code (fullname)

          *note InspectLoader.get_code(): 94c. 的具体实现。

      -- 成員函式: exec_module (module)

          *note Loader.exec_module(): 6db. 的具体实现。

          3.4 版新加入.

      -- 成員函式: load_module (fullname)

          Concrete implementation of *note Loader.load_module(): 6da.

          3.4 版後已棄用: 使用 *note exec_module(): a24. 来代替。

      -- 成員函式: get_source (fullname)

          *note InspectLoader.get_source(): 950. 的具体实现。

      -- 成員函式: is_package (fullname)

          *note InspectLoader.is_package(): 38fd. 的具体实现。一个模块被
          确定为一个包的条件是：它的文件路径（由 *note
          ExecutionLoader.get_filename(): 38ff. 提供）当文件扩展名被移除
          时是一个命名为 ‘__init__’ 的文件，`并且' 这个模块名字本身不是
          以‘‘__init__‘‘结束。

 -- 類別: importlib.abc.Traversable

     拥有部分 pathlib.Path 方法的对象，适用于遍历目录和打开文件。

     3.9 版新加入.

      -- 成員函式: abstractmethod name ()

          The base name of this object without any parent references.

      -- 成員函式: abstractmethod iterdir ()

          Yield Traversable objects in self.

      -- 成員函式: abstractmethod is_dir ()

          Return True if self is a directory.

      -- 成員函式: abstractmethod is_file ()

          Return True if self is a file.

      -- 成員函式: abstractmethod joinpath (child)

          Return Traversable child in self.

      -- 成員函式: abstractmethod __truediv__ (child)

          Return Traversable child in self.

      -- 成員函式: abstractmethod open (mode='r', *args, **kwargs)

          `mode' may be ’r’ or ’rb’ to open as text or binary.  Return a
          handle suitable for reading (same as *note pathlib.Path.open:
          1d3a.).

          When opening as text, accepts encoding parameters such as
          those accepted by *note io.TextIOWrapper: 6ea.

      -- 成員函式: read_bytes ()

          Read contents of self as bytes.

      -- 成員函式: read_text (encoding=None)

          Read contents of self as text.

 -- 類別: importlib.abc.TraversableResources

     用作资源读取器的抽象基类，能够为 ‘files’ 接口提供服务。其为
     ResourceReader 的子类，并具体实现了 ResourceReader 的抽象方法。因此
     ，任何提供 TraversableReader 的加载器也提供 ResourceReader。

     3.9 版新加入.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/importlib/abc.py

   (2) https://www.python.org/dev/peps/pep-0302

   (3) https://www.python.org/dev/peps/pep-0302

   (4) https://www.python.org/dev/peps/pep-0302

   (5) https://www.python.org/dev/peps/pep-0302

   (6) https://www.python.org/dev/peps/pep-0302


File: python.info,  Node: importlib resources -- 资源,  Next: importlib machinery —— 导入器和路径钩子函数。,  Prev: importlib abc —— 关于导入的抽象基类,  Up: importlib --- import 的实现

5.31.5.4 ‘importlib.resources’ – 资源
.....................................

`源码：' Lib/importlib/resources.py(1)

__________________________________________________________________

3.7 版新加入.

这个模块使得Python的导入系统提供了访问*包*内的*资源*的功能。如果能够导入
一个包，那么就能够访问那个包里面的资源。资源可以以二进制或文本模式方式被
打开或读取。

资源非常类似于目录内部的文件，要牢记的是这仅仅是一个比喻。资源和包不是与
文件系统上的物理文件和目录一样存在着。

     備註: 本模块提供了类似于 pkg_resources(2) Basic Resource Access(3)
     的功能，但没有该包的性能开销。这样读取包中的资源就更为容易，语义也
     更稳定一致。

     该模块有独立的向下移植版本， using importlib.resources(4) 和
     migrating from pkg_resources to importlib.resources(5) 提供了更多信
     息。

加载器想要支持资源读取应该实现一个由 *note importlib.abc.ResourceReader:
44e. 指定的‘‘get_resource_reader(fullname)‘‘ 方法。

定义了以下类型。

 -- Data: importlib.resources.Package

     ‘Package’ 类型定义为 ‘Union[str, ModuleType]’ 。这意味着只要函数说
     明接受 ‘Package’ 的地方，就可以传入字符串或模块。模块对象必须拥有一
     个可解析的 ‘__spec__.submodule_search_locations’，不能是 ‘None’。

 -- Data: importlib.resources.Resource

     此类型描述了传入本包各函数的资源名称。定义为 ‘Union[str,
     os.PathLike]’。

有以下函数可用：

 -- 函式: importlib.resources.files (package)

     返回一个 ‘importlib.resources.abc.Traversable’ 对象，代表包的资源容
     器（可视为目录）及其资源（可视为文件）。Traversable 可以包含其他容
     器（可视为子目录）。

     `package' 是包名或符合 ‘Package’ 要求的模块对象。

     3.9 版新加入.

 -- 函式: importlib.resources.as_file (traversable)

     给出代表某个文件的 ‘importlib.resources.abc.Traversable’ 对象，通常
     是来自 *note importlib.resources.files(): 1b7.，返回上下文管理器以
     供 *note with: 7da. 语句使用。上下文管理器提供一个 *note
     pathlib.Path: 32f. 对象。

     退出上下文管理程序时，可以清理所有临时文件，比如从压缩文件中提取资
     源时创建的那些文件。

     如果 Traversable 方法（‘read_text’ 等）不够用，需要文件系统中的实际
     文件时，请使用 ‘as_file’。

     3.9 版新加入.

 -- 函式: importlib.resources.open_binary (package, resource)

     以二进制读方式打开 `package' 内的 `resource'。

     `package' 是包名或符合 ‘Package’ 要求的模块对象。 `resource' 是要在
     *package* 内打开的资源名；不能包含路径分隔符，也不能有子资源（即不
     能为目录）。本函数将返回一个‘‘typing.BinaryIO‘‘ 实例，即一个供读取
     的已打开的二进制 I/O 流。

 -- 函式: importlib.resources.open_text (package, resource,
          encoding='utf-8', errors='strict')

     以文本读方式打开 `package' 内的 `resource'。默认情况下，资源将以
     UTF-8 格式打开以供读取。

     `package' 是包名或符合 ‘Package’ 要求的模块对象。 `resource' 是要在
     `package' 内打开的资源名；不能包含路径分隔符，也不能有子资源（即不
     能是目录）。`encoding' 和 `errors' 的含义与内置 *note open(): 16f.
     的一样。

     本函数返回一个 ‘typing.TextIO’ 实例，即一个打开的文本 I/O 流对象以
     供读取。

 -- 函式: importlib.resources.read_binary (package, resource)

     读取并返回 `package' 中的 `resource' 内容，格式为 ‘bytes’。

     `package' 是包名或符合 ‘Package’ 要求的模块对象。 `resource' 是要在
     `package' 内打开的资源名；不能包含路径分隔符，也不能有子资源（即不
     能是目录）。资源内容以 *note bytes: 172. 的形式返回。

 -- 函式: importlib.resources.read_text (package, resource,
          encoding='utf-8', errors='strict')

     读取并返回 `package' 中 `resource' 的内容，格式为 ‘str’。默认情况下
     ，资源内容将以严格的 UTF-8 格式读取。

     `package' 是包名或符合 ‘Package’ 要求的模块对象。 `resource' 是要在
     `package' 内打开的资源名；不能包含路径分隔符，也不能有子资源（即不
     能是目录）。`encoding' 和 `errors' 的含义与内置 *note open(): 16f.
     的一样。资源内容将以 *note str: 205. 的形式返回。

 -- 函式: importlib.resources.path (package, resource)

     返回 `resource' 实际的文件系统路径。本函数返回一个上下文管理器，以
     供 *note with: 7da. 语句中使用。上下文管理器提供一个 *note
     pathlib.Path: 32f. 对象。

     退出上下文管理程序时，可以清理所有临时文件，比如从压缩文件中提取资
     源时创建的那些文件。

     `package' 是包名或符合 ‘Package’ 要求的模块对象。 `resource' 是要在
     `package' 内打开的资源名；不能包含路径分隔符，也不能有子资源（即不
     能是目录）。

 -- 函式: importlib.resources.is_resource (package, name)

     如果包中存在名为 `name' 的资源，则返回 ‘True’，否则返回 ‘False’。 请
     记住，目录 `不是' 资源！ `package' 为包名或一个符合 ‘Package’ 要求
     的模块对象。

 -- 函式: importlib.resources.contents (package)

     返回一个用于遍历包内各命名项的可迭代对象。该可迭代对象将返回 *note
     str: 205. 资源（如文件）及非资源（如目录）。该迭代器不会递归进入子
     目录。

     `package' 是包名或符合 ‘Package’ 要求的模块对象。

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/Lib/importlib/resources.py

   (2) https://setuptools.readthedocs.io/en/latest/pkg_resources.html

   (3) 
http://setuptools.readthedocs.io/en/latest/pkg_resources.html#basic-resource-access

   (4) http://importlib-resources.readthedocs.io/en/latest/using.html

   (5) 
http://importlib-resources.readthedocs.io/en/latest/migration.html


File: python.info,  Node: importlib machinery —— 导入器和路径钩子函数。,  Next: importlib util —— 导入器的工具程序代码,  Prev: importlib resources -- 资源,  Up: importlib --- import 的实现

5.31.5.5 ‘importlib.machinery’ —— 导入器和路径钩子函数。
........................................................

`源代码：' Lib/importlib/machinery.py(1)

__________________________________________________________________

本模块包含多个对象，以帮助 *note import: ce7. 查找并加载模块。

 -- 屬性: importlib.machinery.SOURCE_SUFFIXES

     一个字符串列表，表示源模块的可识别的文件后缀。

     3.3 版新加入.

 -- 屬性: importlib.machinery.DEBUG_BYTECODE_SUFFIXES

     一个字符串列表，表示未经优化字节码模块的文件后缀。

     3.3 版新加入.

     3.5 版後已棄用: 改用 *note BYTECODE_SUFFIXES: 391e. 。

 -- 屬性: importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES

     一个字符串列表，表示已优化字节码模块的文件后缀。

     3.3 版新加入.

     3.5 版後已棄用: 改用 *note BYTECODE_SUFFIXES: 391e. 。

 -- 屬性: importlib.machinery.BYTECODE_SUFFIXES

     一个字符串列表，表示字节码模块的可识别的文件后缀（包含前导的句点符
     号）。

     3.3 版新加入.

     3.5 版更變: 该值不再依赖于 ‘__debug__’ 。

 -- 屬性: importlib.machinery.EXTENSION_SUFFIXES

     一个字符串列表，表示扩展模块的可识别的文件后缀。

     3.3 版新加入.

 -- 函式: importlib.machinery.all_suffixes ()

     返回字符串的组合列表，代表标准导入机制可识别模块的所有文件后缀。这
     是个助手函数，只需知道某个文件系统路径是否会指向模块，而不需要任何
     关于模块种类的细节（例如 *note inspect.getmodulename(): 6e9.）。

     3.3 版新加入.

 -- 類別: importlib.machinery.BuiltinImporter

     用于导入内置模块的 *note importer: 15f7.。 所有已知的内置模块都已列
     入 *note sys.builtin_module_names: 37c8.。 此类实现了 *note
     importlib.abc.MetaPathFinder: a93. 和 *note
     importlib.abc.InspectLoader: 94b. 抽象基类。

     此类只定义类的方法，以减轻实例化的开销。

     3.5 版更變: 作为 PEP 489(2) 的一部分，现在内置模块导入器实现了
     ‘Loader.create_module()’ 和 ‘Loader.exec_module()’。

 -- 類別: importlib.machinery.FrozenImporter

     用于已冻结模块的 *note importer: 15f7.。 此类实现了 *note
     importlib.abc.MetaPathFinder: a93. 和 *note
     importlib.abc.InspectLoader: 94b. 抽象基类。

     此类只定义类的方法，以减轻实例化的开销。

     3.4 版更變: 有了 ‘create_module()’ 和 ‘exec_module()’ 方法。

 -- 類別: importlib.machinery.WindowsRegistryFinder

     *note Finder: 15f5. 用于查找在 Windows 注册表中声明的模块。该类实现
     了基础的 *note importlib.abc.MetaPathFinder: a93. 。

     此类只定义类的方法，以减轻实例化的开销。

     3.3 版新加入.

     3.6 版後已棄用: 改用 *note site: eb. 配置。未来版本的 Python 可能不
     会默认启用该查找器。

 -- 類別: importlib.machinery.PathFinder

     用于 *note sys.path: 261. 和包的 ‘__path__’ 属性的 *note Finder:
     15f5. 。该类实现了基础的 *note importlib.abc.MetaPathFinder: a93.。

     此类只定义类的方法，以减轻实例化的开销。

      -- 成員函式: classmethod find_spec (fullname, path=None,
               target=None)

          类方法试图在 *note sys.path: 261. 或 `path' 上为 `fullname' 指
          定的模块查找 *note spec: 37db.。对于每个路径条目，都会查看
          *note sys.path_importer_cache: 597. 。如果找到非 False 的对象
          ，则将其用作 *note path entry finder: a92. 来查找要搜索的模块
          。如果在 *note sys.path_importer_cache: 597. 中没有找到条目，
          那会在 *note sys.path_hooks: a3d. 检索该路径条目的查找器，找到
          了则和查到的模块信息一起存入 *note sys.path_importer_cache:
          597. 。如果查找器没有找到，则缓存中的查找器和模块信息都存为
          ‘None’ ，并返回。

          3.4 版新加入.

          3.5 版更變: 如果当前工作目录不再有效（用空字符串表示），则返回
          ‘None’，但在 *note sys.path_importer_cache: 597. 中不会有缓存
          值。

      -- 成員函式: classmethod find_module (fullname, path=None)

          一个过时的 *note find_spec(): a1e. 封装对象。

          3.4 版後已棄用: 使用 *note find_spec(): a1e. 来代替。

      -- 成員函式: classmethod invalidate_caches ()

          为所有存于 *note sys.path_importer_cache: 597. 中的查找器，调
          用其 *note importlib.abc.PathEntryFinder.invalidate_caches():
          38f9. 方法。 *note sys.path_importer_cache: 597. 中为 ‘None’ 的
          条目将被删除。

          3.7 版更變: *note sys.path_importer_cache: 597. 中的 ‘None’ 条
          目将被删除。

     3.4 版更變: 调用 *note sys.path_hooks: a3d. 中的对象，当前工作目录
     为 ‘''’ (即空字符串)。

 -- 類別: importlib.machinery.FileFinder (path, *loader_details)

     *note importlib.abc.PathEntryFinder: a94. 的一个具体实现，它会缓存
     来自文件系统的结果。

     参数 `path' 是查找器负责搜索的目录。

     `loader_details' 参数是数量不定的二元组，每个元组包含加载器及其可识
     别的文件后缀列表。加载器应为可调用对象，可接受两个参数，即模块的名
     称和已找到文件的路径。

     查找器将按需对目录内容进行缓存，通过对每个模块的检索进行状态统计，
     验证缓存是否过期。因为缓存的滞后性依赖于操作系统文件系统状态信息的
     粒度，所以搜索模块、新建文件、然后搜索新文件代表的模块，这会存在竞
     争状态。如果这些操作的频率太快，甚至小于状态统计的粒度，那么模块搜
     索将会失败。为了防止这种情况发生，在动态创建模块时，请确保调用
     *note importlib.invalidate_caches(): 596.。

     3.3 版新加入.

      -- 屬性: path

          查找器将要搜索的路径。

      -- 成員函式: find_spec (fullname, target=None)

          尝试在 *note path: 3921. 中找到处理 `fullname' 的规格。

          3.4 版新加入.

      -- 成員函式: find_loader (fullname)

          试图在 *note path: 3921. 内找到处理 `fullname' 的加载器。

      -- 成員函式: invalidate_caches ()

          清理内部缓存。

      -- 成員函式: classmethod path_hook (*loader_details)

          一个类方法，返回供 *note sys.path_hooks: a3d. 使用的闭包。根据
          直接给出的路径参数和间接给出的 `loader_details'，闭包会返回一
          个 *note FileFinder: a96. 的实例。

          如果给闭包的参数不是已存在的目录，将会触发 *note ImportError:
          16c.。

 -- 類別: importlib.machinery.SourceFileLoader (fullname, path)

     *note importlib.abc.SourceLoader: 3904. 的一个具体实现，该实现子类
     化了 *note importlib.abc.FileLoader: a97. 并提供了其他一些方法的具
     体实现。

     3.3 版新加入.

      -- 屬性: name

          该加载器将要处理的模块名称。

      -- 屬性: path

          源文件的路径

      -- 成員函式: is_package (fullname)

          如果 *note path: 3926. 看似包的路径，则返回 ‘True’。

      -- 成員函式: path_stats (path)

          *note importlib.abc.SourceLoader.path_stats(): bc3. 的具体代码
          实现。

      -- 成員函式: set_data (path, data)

          *note importlib.abc.SourceLoader.set_data(): 3905. 的具体代码
          实现。

      -- 成員函式: load_module (name=None)

          *note importlib.abc.Loader.load_module(): 6da. 的具体代码实现
          ，这里要加载的模块名是可选的。

          3.6 版後已棄用: 改用 *note importlib.abc.Loader.exec_module():
          6db. 。

 -- 類別: importlib.machinery.SourcelessFileLoader (fullname, path)

     *note importlib.abc.FileLoader: a97. 的具体代码实现，可导入字节码文
     件（也即源代码文件不存在）。

     请注意，直接用字节码文件（而不是源代码文件），会让模块无法应用于所
     有的 Python 版本或字节码格式有所改动的新版本 Python。

     3.3 版新加入.

      -- 屬性: name

          加载器将要处理的模块名。

      -- 屬性: path

          二进制码文件的路径。

      -- 成員函式: is_package (fullname)

          根据 *note path: 392b. 确定该模块是否为包。

      -- 成員函式: get_code (fullname)

          返回由 *note path: 392b. 创建的 *note name: 392a. 的代码对象。

      -- 成員函式: get_source (fullname)

          因为用此加载器时字节码文件没有源码文件，所以返回 ‘None’。

      -- 成員函式: load_module (name=None)

     *note importlib.abc.Loader.load_module(): 6da. 的具体代码实现，这里
     要加载的模块名是可选的。

     3.6 版後已棄用: 改用 *note importlib.abc.Loader.exec_module(): 6db.
     。

 -- 類別: importlib.machinery.ExtensionFileLoader (fullname, path)

     *note importlib.abc.ExecutionLoader: 38fe. 的具体代码实现，用于扩展
     模块。

     参数 `fullname' 指定了加载器要支持的模块名。参数 `path' 是指向扩展
     模块文件的路径。

     3.3 版新加入.

      -- 屬性: name

          装载器支持的模块名。

      -- 屬性: path

          扩展模块的路径。

      -- 成員函式: create_module (spec)

          根据 PEP 489(3) ，由给定规范创建模块对象。

          3.5 版新加入.

      -- 成員函式: exec_module (module)

          根据 PEP 489(4)，初始化给定的模块对象。

          3.5 版新加入.

      -- 成員函式: is_package (fullname)

          根据 *note EXTENSION_SUFFIXES: 3920. ，如果文件路径指向某个包
          的 ‘__init__’ 模块，则返回 ‘True’。

      -- 成員函式: get_code (fullname)

          返回 ‘None’，因为扩展模块缺少代码对象。

      -- 成員函式: get_source (fullname)

          返回 ‘None’，因为扩展模块没有源代码。

      -- 成員函式: get_filename (fullname)

          返回 *note path: 3930.。

          3.4 版新加入.

 -- 類別: importlib.machinery.ModuleSpec (name, loader, *, origin=None,
          loader_state=None, is_package=None)

     关于模块导入系统相关状态的规范。通常这是作为模块的 ‘__spec__’ 属性
     暴露出来。 在以下描述中，括号里的名字给出了模块对象中直接可用的属性
     。比如 ‘module.__spec__.origin == module.__file__’。 但是请注意，虽
     然 `值' 通常是相等的，但它们可以不同，因为两个对象之间没有进行同步
     。因此 ‘__path__’ 有可能在运行时做过更新，而这不会自动反映在
     ‘__spec__.submodule_search_locations’ 中。

     3.4 版新加入.

      -- 屬性: name

     （‘__name__’）

     一个字符串，表示模块的完全限定名称。

      -- 屬性: loader

     （‘__loader__’）

     模块加载时应采用的 *note Loader: 15f6. 。 *note Finders: 15f5. 应确
     保设置本属性。

      -- 屬性: origin

     （‘__file__’）

     装载模块所在位置的名称，如内置模块为 “buildin”，从源代码加载的模块
     为文件名。通常应设置 “origin” ，但它可能为 ‘None’ (默认值)，表示未
     指定 (如命名空间包)。

      -- 屬性: submodule_search_locations

     （‘__path__’）

     如果是包（否则为 ），子模块所在位置的字符串列表（否则为 ‘None’）。

      -- 屬性: loader_state

     依模块不同的额外数据的容器，以供加载过程中使用（或 ‘None’）。

      -- 屬性: cached

     （‘__cached__’）

     字符串，表示编译后的模块所在位置（或 ‘None’）。

      -- 屬性: parent

     （‘__package__’）

     包的完全限定名称（只读），模块应作为其子模块进行加载（对于顶层模块
     则为空字符串）。对于包而言，其值与 *note __name__: dd8. 相同。

      -- 屬性: has_location

     布尔值，表示模块的“origin”属性是否指向可加载的位置。

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/Lib/importlib/machinery.py

   (2) https://www.python.org/dev/peps/pep-0489

   (3) https://www.python.org/dev/peps/pep-0489

   (4) https://www.python.org/dev/peps/pep-0489


File: python.info,  Node: importlib util —— 导入器的工具程序代码,  Next: 示例<44>,  Prev: importlib machinery —— 导入器和路径钩子函数。,  Up: importlib --- import 的实现

5.31.5.6 ‘importlib.util’ —— 导入器的工具程序代码
.................................................

`源代码：' Lib/importlib/util.py(1)

__________________________________________________________________

本模块包含了帮助构建 *note importer: 15f7. 的多个对象。

 -- 屬性: importlib.util.MAGIC_NUMBER

     代表字节码版本号的字节串。若要有助于加载/写入字节码，可考虑采用
     *note importlib.abc.SourceLoader: 3904.。

     3.4 版新加入.

 -- 函式: importlib.util.cache_from_source (path, debug_override=None,
          *, optimization=None)

     返回 PEP 3147(2)/ PEP 488(3) 定义的，与源 `path' 相关联的已编译字节
     码文件的路径。 例如，如果 `path' 为 ‘/foo/bar/baz.py’ 则 Python 3.2
     中的返回值将是 ‘/foo/bar/__pycache__/baz.cpython-32.pyc’。 字符串
     ‘cpython-32’ 来自于当前的魔法标签 (参见 ‘get_tag()’; 如果
     ‘sys.implementation.cache_tag’ 未定义则将会引发 *note
     NotImplementedError: 704.)。

     参数 `optimization' 用于指定字节码文件的优化级别。空字符串代表没有
     优化，所以 `optimization' 为 的 ‘/foo/bar/baz.py’，将会得到字节码路
     径为 ‘/foo/bar/__pycache__/baz.cpython-32.pyc’。‘None’ 会导致采用解
     释器的优化。任何其他字符串都会被采用，所以 `optimization' 为 ‘''’ 的
     ‘/foo/bar/baz.py’ 会导致字节码路径为
     ‘/foo/bar/__pycache__/baz.cpython-32.opt-2.pyc’。`optimization' 字
     符串只能是字母数字，否则会触发 *note ValueError: 16d.。

     `debug_override' 参数已废弃，可用于覆盖系统的 ‘__debug__’ 值。
     ‘True’ 值相当于将 `optimization' 设为空字符串。‘False’ 则相当于
     *optimization* 设为 ‘1’。如果 `debug_override' 和 `optimization' 都
     不为 ‘None’，则会触发 *note TypeError: 1fe.。

     3.4 版新加入.

     3.5 版更變: 增加了 `optimization' 参数，废弃了 `debug_override' 参
     数。

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: importlib.util.source_from_cache (path)

     根据指向一个 PEP 3147(4) 文件名的 `path'，返回相关联的源代码文件路
     径。 举例来说，如果 `path' 为
     ‘/foo/bar/__pycache__/baz.cpython-32.pyc’ 则返回的路径将是
     ‘/foo/bar/baz.py’。 `path' 不需要已存在，但如果它未遵循 PEP 3147(5)
     或 PEP 488(6) 的格式，则会引发 *note ValueError: 16d.。 如果未定义
     ‘sys.implementation.cache_tag’，则会引发 *note NotImplementedError:
     704.。

     3.4 版新加入.

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: importlib.util.decode_source (source_bytes)

     对代表源代码的字节串进行解码，并将其作为带有通用换行符的字符串返回
     （符合 *note importlib.abc.InspectLoader.get_source(): 950. 要求）
     。

     3.4 版新加入.

 -- 函式: importlib.util.resolve_name (name, package)

     将模块的相对名称解析为绝对名称。

     如果 `name' 前面没有句点，那就简单地返回 `name'。这样就能采用
     ‘‘importlib.util.resolve_name(’sys’, __spec__.parent)‘‘ 之类的写法
     ，而无需检查是否需要 `package' 参数。

     如果 `name' 是相对模块名称，但 `package' 为 False 值（如 ‘None’ 或
     空字符串），则会触发 *note ImportError: 16c.。 如果相对名称会离开所
     在的包（如从 ‘spam’ 包中请求 ‘..bacon’），则还会触发 *note
     ImportError: 16c.。

     3.3 版新加入.

     3.9 版更變: 为了改善与 import 语句的一致性，对于无效的相对导入尝试
     会引发 *note ImportError: 16c. 而不是 *note ValueError: 16d.。

 -- 函式: importlib.util.find_spec (name, package=None)

     查找模块的 *note spec: 37db.，可选相对指定的 `包' 名。如果该模块位
     于 *note sys.modules: 1051. 中，则会返回
     ‘sys.modules[name].__spec__’ （除非 spec为 ‘None’ 或未作设置，这时
     会触发 *note ValueError: 16d.)。否则将用 *note sys.meta_path: 6dd.
     进行搜索。若找不到则返回 ‘None’。

     如果 `name' 为一个子模块（带有一个句点），则会自动导入父级模块。

     `name' 和 `package' 的用法与 ‘import_module()’ 相同。

     3.4 版新加入.

     3.7 版更變: 如果 `package' 实际上不是一个包（即缺少 *note __path__:
     13c3. 属性）则会引发 *note ModuleNotFoundError: 4a0. 而不是 *note
     AttributeError: 4a1.。

 -- 函式: importlib.util.module_from_spec (spec)

     基于 `spec' 和 *note spec.loader.create_module: 64e. 创建一个新模块
     。

     如果 *note spec.loader.create_module: 64e. 未返回 ‘None’，那么先前
     已存在的属性不会被重置。另外，如果 *note AttributeError: 4a1. 是在
     访问 `spec' 或设置模块属性时触发的，则不会触发 。

     本函数比 *note types.ModuleType: 7e2. 创建新模块要好，因为用到
     `spec' 模块设置了尽可能多的导入控制属性。

     3.5 版新加入.

 -- 函式: @importlib.util.module_for_loader

     *note importlib.abc.Loader.load_module(): 6da. 的一个 *note
     decorator: 174.，用来选取合适的模块对象以供加载。被装饰方法的签名应
     带有两个位置参数（如：‘load_module(self, module)’），其中第二个参数
     将是加载器用到的模块 `对象'。请注意，由于假定有两个参数，所以装饰器
     对静态方法不起作用。

     装饰的方法将接受要加载的模块的 `name'，正如 *note loader: 15f6. 一
     样。如果在 *note sys.modules: 1051. 中没有找到该模块，那么将构造一
     个新模块。不管模块来自哪里， *note __loader__: a37. 设置为 `self' ，
     并且 *note __package__: a36. 是根据 *note
     importlib.abc.InspectLoader.is_package(): 38fd. 的返回值设置的。这
     些属性会无条件进行设置以便支持重载。

     如果被装饰的方法触发异常，并且已有模块加入 *note sys.modules: 1051.
     中，那么该模块将被移除，以防 *note sys.modules: 1051. 中残留一个部
     分初始化的模块。如果该模块原先已在 *note sys.modules: 1051. 中，则
     会保留。

     3.3 版更變: 有可能时自动设置 *note __loader__: a37. 和 *note
     __package__: a36. 。

     3.4 版更變: 无条件设置 *note __name__: dd8. 、 *note __loader__:
     a37. 、 *note __package__: a36. 以支持再次加载。

     3.4 版後已棄用: 现在，导入机制直接执行本函数提供的所有功能。

 -- 函式: @importlib.util.set_loader

     一个 *note decorator: 174.，用于 *note
     importlib.abc.Loader.load_module(): 6da. 在返回的模块上设置 *note
     __loader__: a37. 属性。如果该属性已被设置，装饰器就什么都不做。这里
     假定被封装方法的第一个位置参数（即 ‘self’）就是 *note __loader__:
     a37. 要设置的。

     3.4 版更變: 如果设为 ‘None’ ，则会去设置 ‘__loader__’ ，就像该属性
     不存在一样。

     3.4 版後已棄用: 现在导入机制会自动用到本方法。

 -- 函式: @importlib.util.set_package

     一个用于 *note importlib.abc.Loader.load_module(): 6da. 的 *note
     decorator: 174. ，以便设置返回模块的 *note __package__: a36. 属性。
     如果 *note __package__: a36. 已设置且不为 ‘None’，则不会做改动。

     3.4 版後已棄用: 现在导入机制会自动用到本方法。

 -- 函式: importlib.util.spec_from_loader (name, loader, *, origin=None,
          is_package=None)

     一个工厂函数，用于创建基于加载器的 ‘ModuleSpec’ 实例。 形参的含义与
     ModuleSpec 的相同。 该函数会利用当前可用的 *note loader: 15f6. API，
     比如 ‘InspectLoader.is_package()’，以填充所有缺失的规格信息。

     3.4 版新加入.

 -- 函式: importlib.util.spec_from_file_location (name, location, *,
          loader=None, submodule_search_locations=None)

     一个工厂函数，用于创建基于文件路径的 ‘ModuleSpec’ 实例。 缺失的信息
     将通过利用加载器 API 以及模块将基于文件的隐含条件在 spec 上进行填充
     。

     3.4 版新加入.

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- 函式: importlib.util.source_hash (source_bytes)

     以字节串的形式返回 `source_bytes' 的哈希值。基于哈希值的 ‘.pyc’ 文
     件在头部嵌入了对应源文件内容的 *note source_hash(): 393c.。

     3.7 版新加入.

 -- 類別: importlib.util.LazyLoader (loader)

     此类会延迟执行模块加载器，直至该模块有一个属性被访问到。

     此类 `只' 适用于定义了 *note exec_module(): 6db. 的加载器，因为需要
     控制模块的类型。 同理，加载器的 *note create_module(): 64e. 方法必
     须返回 ‘None’ 或 ‘__class__’ 属性可被改变且不用 *note slots: 393d.
     的类型。 最后，用于替换 *note sys.modules: 1051. 内容的模块将无法工
     作，因为无法在整个解释器中安全地替换模块的引用；如果检测到这种替换
     ，将触发 *note ValueError: 16d.。

          備註: 如果项目对启动时间要求很高，只要模块未被用过，此类能够最
          小化加载模块的开销。对于启动时间并不重要的项目来说，由于加载过
          程中产生的错误信息会被暂时搁置，因此强烈不建议使用此类。

     3.5 版新加入.

     3.6 版更變: 开始调用 *note create_module(): 64e.，移除 *note
     importlib.machinery.BuiltinImporter: 64f. 和 *note
     importlib.machinery.ExtensionFileLoader: 650. 的兼容性警告。

      -- 成員函式: classmethod factory (loader)

          静态方法，返回创建延迟加载器的可调用对象。就是说用在加载器用类
          而不是实例传递的场合。

               suffixes = importlib.machinery.SOURCE_SUFFIXES
               loader = importlib.machinery.SourceFileLoader
               lazy_loader = importlib.util.LazyLoader.factory(loader)
               finder = importlib.machinery.FileFinder(path, (lazy_loader, suffixes))

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/importlib/util.py

   (2) https://www.python.org/dev/peps/pep-3147

   (3) https://www.python.org/dev/peps/pep-0488

   (4) https://www.python.org/dev/peps/pep-3147

   (5) https://www.python.org/dev/peps/pep-3147

   (6) https://www.python.org/dev/peps/pep-0488


File: python.info,  Node: 示例<44>,  Prev: importlib util —— 导入器的工具程序代码,  Up: importlib --- import 的实现

5.31.5.7 示例
.............

* Menu:

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


File: python.info,  Node: 用编程方式导入,  Next: 检查某模块可否导入。,  Up: 示例<44>

5.31.5.8 用编程方式导入
.......................

要以编程方式导入一个模块，请使用 *note importlib.import_module(): be6. ：

     import importlib

     itertools = importlib.import_module('itertools')


File: python.info,  Node: 检查某模块可否导入。,  Next: 直接导入源文件。,  Prev: 用编程方式导入,  Up: 示例<44>

5.31.5.9 检查某模块可否导入。
.............................

若要查看某个模块是否可导入，但不需要实际执行导入，则应使用 *note
importlib.util.find_spec(): a1c. ：

     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")


File: python.info,  Node: 直接导入源文件。,  Next: 设置导入器,  Prev: 检查某模块可否导入。,  Up: 示例<44>

5.31.5.10 直接导入源文件。
..........................

若要直接导入 Python 源码文件，请使用一下方案（仅 Python 3.5 以上版本有效
）：

     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)


File: python.info,  Node: 设置导入器,  Next: importlib import_module 的近似实现,  Prev: 直接导入源文件。,  Up: 示例<44>

5.31.5.11 设置导入器
....................

对于深度定制的导入，通常需要实现一个 *note importer: 15f7.。 这意味着得
同时管理 *note finder: 15f5. 和 *note loader: 15f6.。 根据不同的需求，有
两种类型的查找器可供选择： *note meta path finder: a91. 或 *note path
entry finder: a92.。 前者应位于 *note sys.meta_path: 6dd. 之上，而后者是
用 *note path entry hook: 160d. 在 *note sys.path_hooks: a3d. 上创建但与
*note sys.path: 261. 一起工作，可能会创建一个查找器。以下例子将演示如何
注册自己的导入器，以供导入使用（关于自建导入器请阅读本包内定义的类文档）
：

     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))


File: python.info,  Node: importlib import_module 的近似实现,  Prev: 设置导入器,  Up: 示例<44>

5.31.5.12 ‘importlib.import_module()’ 的近似实现
................................................

导入过程本身是用 Python 代码实现的，这样就能通过 importlib 将大多数导入
机制暴露出来。以下代码近似实现了 *note importlib.import_module(): be6. ，
以帮助说明 importlib 暴露出来的各种 API （importlib 的用法适用于 Python
3.4 以上版本 ，其他代码适用于 Python 3.6 以上版本）。

     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


File: python.info,  Node: Using importlib metadata,  Prev: importlib --- import 的实现,  Up: 匯入模組

5.31.6 Using ‘importlib.metadata’
---------------------------------

`Source code:' Lib/importlib/metadata.py(1)

3.8 版新加入.

     備註: This functionality is provisional and may deviate from the
     usual version semantics of the standard library.

‘importlib.metadata’ is a library that provides for access to installed
package metadata.  Built in part on Python’s import system, this library
intends to replace similar functionality in the entry point API(2) and
metadata API(3) of ‘pkg_resources’.  Along with *note
importlib.resources: 9e. in Python 3.7 and newer (backported as
importlib_resources(4) for older versions of Python), this can eliminate
the need to use the older and less efficient ‘pkg_resources’ package.

By "installed package" we generally mean a third-party package installed
into Python’s ‘site-packages’ directory via tools such as pip(5).
Specifically, it means a package with either a discoverable ‘dist-info’
or ‘egg-info’ directory, and metadata defined by PEP 566(6) or its older
specifications.  By default, package metadata can live on the file
system or in zip archives on *note sys.path: 261.  Through an extension
mechanism, the metadata can live almost anywhere.

* Menu:

* 概述::
* 可用 API::
* Distributions::
* Extending the search algorithm::

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/Lib/importlib/metadata.py

   (2) 
https://setuptools.readthedocs.io/en/latest/pkg_resources.html#entry-points

   (3) 
https://setuptools.readthedocs.io/en/latest/pkg_resources.html#metadata-api

   (4) https://importlib-resources.readthedocs.io/en/latest/index.html

   (5) https://pypi.org/project/pip/

   (6) https://www.python.org/dev/peps/pep-0566


File: python.info,  Node: 概述,  Next: 可用 API,  Up: Using importlib metadata

5.31.6.1 概述
.............

Let’s say you wanted to get the version string for a package you’ve
installed using ‘pip’.  We start by creating a virtual environment and
installing something into it:

     $ python3 -m venv example
     $ source example/bin/activate
     (example) $ pip install wheel

You can get the version string for ‘wheel’ by running the following:

     (example) $ python
     >>> from importlib.metadata import version
     >>> version('wheel')
     '0.32.3'

You can also get the set of entry points keyed by group, such as
‘console_scripts’, ‘distutils.commands’ and others.  Each group contains
a sequence of *note EntryPoint: 394a. objects.

You can get the *note metadata for a distribution: 394b.:

     >>> 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']

You can also get a *note distribution’s version number: 394c, list its
*note constituent files: 394d, and get a list of the distribution’s
*note Distribution requirements: 394e.


File: python.info,  Node: 可用 API,  Next: Distributions,  Prev: 概述,  Up: Using importlib metadata

5.31.6.2 可用 API
.................

This package provides the following functionality via its public API.

* Menu:

* Entry points::
* Distribution metadata::
* Distribution versions::
* Distribution files::
* Distribution requirements::


File: python.info,  Node: Entry points,  Next: Distribution metadata,  Up: 可用 API

5.31.6.3 Entry points
.....................

The ‘entry_points()’ function returns a dictionary of all entry points,
keyed by group.  Entry points are represented by ‘EntryPoint’ instances;
each ‘EntryPoint’ has a ‘.name’, ‘.group’, and ‘.value’ attributes and a
‘.load()’ method to resolve the value.  There are also ‘.module’,
‘.attr’, and ‘.extras’ attributes for getting the components of the
‘.value’ attribute:

     >>> 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>

The ‘group’ and ‘name’ are arbitrary values defined by the package
author and usually a client will wish to resolve all entry points for a
particular group.  Read the setuptools docs(1) for more information on
entry points, their definition, and usage.

   ---------- Footnotes ----------

   (1) 
https://setuptools.readthedocs.io/en/latest/setuptools.html#dynamic-discovery-of-services-and-plugins


File: python.info,  Node: Distribution metadata,  Next: Distribution versions,  Prev: Entry points,  Up: 可用 API

5.31.6.4 Distribution metadata
..............................

Every distribution includes some metadata, which you can extract using
the ‘metadata()’ function:

     >>> wheel_metadata = metadata('wheel')

The keys of the returned data structure (1) name the metadata keywords,
and their values are returned unparsed from the distribution metadata:

     >>> wheel_metadata['Requires-Python']
     '>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*'

   ---------- Footnotes ----------

   (1) (1) Technically, the returned distribution metadata object is an
*note email.message.EmailMessage: 63c. 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.


File: python.info,  Node: Distribution versions,  Next: Distribution files,  Prev: Distribution metadata,  Up: 可用 API

5.31.6.5 Distribution versions
..............................

The ‘version()’ function is the quickest way to get a distribution’s
version number, as a string:

     >>> version('wheel')
     '0.32.3'


File: python.info,  Node: Distribution files,  Next: Distribution requirements,  Prev: Distribution versions,  Up: 可用 API

5.31.6.6 Distribution files
...........................

You can also get the full set of files contained within a distribution.
The ‘files()’ function takes a distribution package name and returns all
of the files installed by this distribution.  Each file object returned
is a ‘PackagePath’, a *note pathlib.PurePath: 235. derived object with
additional ‘dist’, ‘size’, and ‘hash’ properties as indicated by the
metadata.  For 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>

Once you have the file, you can also read its contents:

     >>> print(util.read_text())
     import base64
     import sys
     ...
     def as_bytes(s):
         if isinstance(s, text_type):
             return s.encode('utf-8')
         return s

You can also use the ‘locate’ method to get a the absolute path to the
file:

     >>> util.locate()
     PosixPath('/home/gustav/example/lib/site-packages/wheel/util.py')

In the case where the metadata file listing files (RECORD or
SOURCES.txt) is missing, ‘files()’ will return ‘None’.  The caller may
wish to wrap calls to ‘files()’ in always_iterable(1) or otherwise guard
against this condition if the target distribution is not known to have
the metadata present.

   ---------- Footnotes ----------

   (1) 
https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.always_iterable


File: python.info,  Node: Distribution requirements,  Prev: Distribution files,  Up: 可用 API

5.31.6.7 Distribution requirements
..................................

To get the full set of requirements for a distribution, use the
‘requires()’ function:

     >>> requires('wheel')
     ["pytest (>=3.0.0) ; extra == 'test'", "pytest-cov ; extra == 'test'"]


File: python.info,  Node: Distributions,  Next: Extending the search algorithm,  Prev: 可用 API,  Up: Using importlib metadata

5.31.6.8 Distributions
......................

While the above API is the most common and convenient usage, you can get
all of that information from the ‘Distribution’ class.  A ‘Distribution’
is an abstract object that represents the metadata for a Python package.
You can get the ‘Distribution’ instance:

     >>> from importlib.metadata import distribution
     >>> dist = distribution('wheel')

Thus, an alternative way to get the version number is through the
‘Distribution’ instance:

     >>> dist.version
     '0.32.3'

There are all kinds of additional metadata available on the
‘Distribution’ instance:

     >>> dist.metadata['Requires-Python']
     '>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*'
     >>> dist.metadata['License']
     'MIT'

The full set of available metadata is not described here.  See PEP
566(1) for additional details.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0566


File: python.info,  Node: Extending the search algorithm,  Prev: Distributions,  Up: Using importlib metadata

5.31.6.9 Extending the search algorithm
.......................................

Because package metadata is not available through *note sys.path: 261.
searches, or package loaders directly, the metadata for a package is
found through import system *note finders: 15f3.  To find a distribution
package’s metadata, ‘importlib.metadata’ queries the list of *note meta
path finders: a91. on *note sys.meta_path: 6dd.

The default ‘PathFinder’ for Python includes a hook that calls into
‘importlib.metadata.MetadataPathFinder’ for finding distributions loaded
from typical file-system-based paths.

The abstract class *note importlib.abc.MetaPathFinder: a93. defines the
interface expected of finders by Python’s import system.
‘importlib.metadata’ extends this protocol by looking for an optional
‘find_distributions’ callable on the finders from *note sys.meta_path:
6dd. and presents this extended interface as the ‘DistributionFinder’
abstract base class, which defines this abstract method:

     @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 ``context``.
         """

The ‘DistributionFinder.Context’ object provides ‘.path’ and ‘.name’
properties indicating the path to search and name to match and may
supply other relevant context.

What this means in practice is that to support finding distribution
package metadata in locations other than the file system, subclass
‘Distribution’ and implement the abstract methods.  Then from a custom
finder, return instances of this derived ‘Distribution’ in the
‘find_distributions()’ method.

备注
....


File: python.info,  Node: Python 语言服务,  Next: 杂项服务,  Prev: 匯入模組,  Up: Python 標準函式庫 Standard Library

5.32 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 --- Byte-compile Python libraries. Byte-compile Python libraries
* dis: dis --- Python bytecode的反組譯器. Python bytecode的反組譯器
* pickletools: pickletools --- pickle 开发者工具集. pickle 开发者工具集


File: python.info,  Node: parser --- 访问 Python 解析树,  Next: ast --- 抽象语法树,  Up: Python 语言服务

5.32.1 ‘parser’ — 访问 Python 解析树
------------------------------------

__________________________________________________________________

The *note parser: c7. 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.

     警告: parser 模块已被弃用并将在未来的 Python 版本中移除。 对于大多
     数用例你都可以使用 *note ast: 7. 模块来控制抽象语法树（AST）的生成
     和编译阶段。

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
*note parser: c7. 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 *note Python 語言參考手冊: 1331.  The parser
itself is created from a grammar specification defined in the file
‘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 *note expr(): 395c. or
*note suite(): 395d. functions, described below.  The ST objects created
by *note sequence2st(): 395e. 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 *note st2list(): 395f. or
*note st2tuple(): 3960. 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 ‘Include/graminit.h’ and the Python module *note symbol: fb.  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 *note if: eab. in an ‘if_stmt’,
are included in the node tree without any special treatment.  For
example, the ‘if’ keyword is represented by the tuple ‘(1, 'if')’, where
‘1’ is the numeric value associated with all ‘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 ‘(1, 'if', 12)’, where the ‘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 *note if: eab. keyword above is representative.  The
various types of terminal symbols are defined in the C header file
‘Include/token.h’ and the Python module *note token: 119.

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 *note parser: c7. 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.

也參考
......

模块 *note symbol: fb.

     代表解析树内部节点的有用常量。

模块 *note token: 119.

     代表解析树叶子节点和测试节点值的函数的有用常量。

* Menu:

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


File: python.info,  Node: 创建 ST 对象,  Next: 转换 ST 对象,  Up: parser --- 访问 Python 解析树

5.32.1.1 创建 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 ‘'eval'’ and ‘'exec'’ forms.

 -- 函式: parser.expr (source)

     The *note expr(): 395c. function parses the parameter `source' as
     if it were an input to ‘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.

 -- 函式: parser.suite (source)

     The *note suite(): 395d. function parses the parameter `source' as
     if it were an input to ‘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.

 -- 函式: 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 *note
     ParserError: 3963. 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 *note compilest(): 3964.  This may indicate problems not
     related to syntax (such as a *note MemoryError: f69. exception),
     but may also be due to constructs such as the result of parsing
     ‘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 ‘(1, 'name')’ or as three-element
     lists of the form ‘(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.

 -- 函式: parser.tuple2st (sequence)

     This is the same function as *note sequence2st(): 395e.  This entry
     point is maintained for backward compatibility.


File: python.info,  Node: 转换 ST 对象,  Next: Queries on ST Objects,  Prev: 创建 ST 对象,  Up: parser --- 访问 Python 解析树

5.32.1.2 转换 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.

 -- 函式: parser.st2list (st, line_info=False, col_info=False)

     This function accepts an ST object from the caller in `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, *note st2tuple(): 3960. 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 `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 `ends'.  This information is omitted if the flag
     is false or omitted.

 -- 函式: parser.st2tuple (st, line_info=False, col_info=False)

     This function accepts an ST object from the caller in `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 *note st2list(): 395f.

     If `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.

 -- 函式: parser.compilest (st, filename='<syntax-tree>')

     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
     *note exec(): d0c. or *note eval(): c61. functions.  This function
     provides the interface to the compiler, passing the internal parse
     tree from `st' to the parser, using the source file name specified
     by the `filename' parameter.  The default value supplied for
     `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 *note SyntaxError: 559. caused
     by the parse tree for ‘del f(0)’: this statement is considered
     legal within the formal grammar for Python but is not a legal
     language construct.  The *note SyntaxError: 559. 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 *note
     parser: c7. module.  Most causes of compilation failure can be
     diagnosed programmatically by inspection of the parse tree.


File: python.info,  Node: Queries on ST Objects,  Next: 异常和错误处理,  Prev: 转换 ST 对象,  Up: parser --- 访问 Python 解析树

5.32.1.3 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 *note
expr(): 395c. or *note suite(): 395d. or from a parse tree via *note
sequence2st(): 395e.

 -- 函式: parser.isexpr (st)

     When `st' represents an ‘'eval'’ form, this function returns
     ‘True’, otherwise it returns ‘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
     *note compilest(): 3964. cannot be queried like this either, and
     are identical to those created by the built-in *note compile():
     2e7. function.

 -- 函式: parser.issuite (st)

     This function mirrors *note isexpr(): 396a. in that it reports
     whether an ST object represents an ‘'exec'’ form, commonly known as
     a "suite."  It is not safe to assume that this function is
     equivalent to ‘not isexpr(st)’, as additional syntactic fragments
     may be supported in the future.


File: python.info,  Node: 异常和错误处理,  Next: ST 对象,  Prev: Queries on ST Objects,  Up: parser --- 访问 Python 解析树

5.32.1.4 异常和错误处理
.......................

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.

 -- 例外: parser.ParserError

     Exception raised when a failure occurs within the parser module.
     This is generally produced for validation failures rather than the
     built-in *note SyntaxError: 559. 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 *note sequence2st(): 395e. and an explanatory
     string.  Calls to *note sequence2st(): 395e. 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.

Note that the functions *note compilest(): 3964, *note expr(): 395c, and
*note suite(): 395d. may raise exceptions which are normally raised by
the parsing and compilation process.  These include the built in
exceptions *note MemoryError: f69, *note OverflowError: a41, *note
SyntaxError: 559, and *note SystemError: 6f2.  In these cases, these
exceptions carry all the meaning normally associated with them.  Refer
to the descriptions of each function for detailed information.


File: python.info,  Node: ST 对象,  Next: 示例 compile 的模拟,  Prev: 异常和错误处理,  Up: parser --- 访问 Python 解析树

5.32.1.5 ST 对象
................

Ordered and equality comparisons are supported between ST objects.
Pickling of ST objects (using the *note pickle: ca. module) is also
supported.

 -- Data: parser.STType

     The type of the objects returned by *note expr(): 395c, *note
     suite(): 395d. and *note sequence2st(): 395e.

ST 对象具有以下方法：

 -- 成員函式: ST.compile (filename='<syntax-tree>')

     和 ‘compilest(st, filename)’ 相同.

 -- 成員函式: ST.isexpr ()

     和 ‘isexpr(st)’ 相同。

 -- 成員函式: ST.issuite ()

     和 ‘issuite(st)’ 相同。

 -- 成員函式: ST.tolist (line_info=False, col_info=False)

     和 ‘st2list(st, line_info, col_info)’ 相同。

 -- 成員函式: ST.totuple (line_info=False, col_info=False)

     和 ‘st2tuple(st, line_info, col_info)’ 相同。


File: python.info,  Node: 示例 compile 的模拟,  Prev: ST 对象,  Up: parser --- 访问 Python 解析树

5.32.1.6 示例: ‘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 *note parser: c7. module to produce an intermediate data
structure is equivalent to the code

     >>> code = compile('a + 5', 'file.py', 'eval')
     >>> a = 5
     >>> eval(code)
     10

The equivalent operation using the *note parser: c7. module is somewhat
longer, and allows the intermediate internal parse tree to be retained
as an ST object:

     >>> import parser
     >>> st = parser.expr('a + 5')
     >>> code = st.compile('file.py')
     >>> a = 5
     >>> eval(code)
     10

An application which needs both ST and code objects can package this
code into readily available functions:

     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()


File: python.info,  Node: ast --- 抽象语法树,  Next: symtable ——访问编译器的符号表,  Prev: parser --- 访问 Python 解析树,  Up: Python 语言服务

5.32.2 ‘ast’ — 抽象语法树
-------------------------

`源代码：' Lib/ast.py(1)

__________________________________________________________________

*note ast: 7. 模块帮助 Python 程序处理 Python 语法的抽象语法树。抽象语法
或许会随着 Python 的更新发布而改变；该模块能够帮助理解当前语法在编程层面
的样貌。

抽象语法树可通过将 *note ast.PyCF_ONLY_AST: 3979. 作为旗标传递给 *note
compile(): 2e7. 内置函数来生成，或是使用此模块中提供的 *note parse():
2d6. 辅助函数。返回结果将是一个对象树，，其中的类都继承自 *note ast.AST:
187.。抽象语法树可被内置的 *note compile(): 2e7. 函数编译为一个 Python 代
码对象。

* Menu:

* 抽象文法::
* 节点类::
* ast 中的辅助函数::
* Compiler Flags::
* 命令行用法: 命令行用法<2>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/ast.py


File: python.info,  Node: 抽象文法,  Next: 节点类,  Up: ast --- 抽象语法树

5.32.2.1 抽象文法
.................

抽象文法目前定义如下

     -- 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)
     }


File: python.info,  Node: 节点类,  Next: ast 中的辅助函数,  Prev: 抽象文法,  Up: ast --- 抽象语法树

5.32.2.2 节点类
...............

 -- 類別: ast.AST

     这是所有 AST 节点类的基类。实际上，这些节点类派生自
     ‘Parser/Python.asdl’ 文件，其中定义的语法树示例 *note 如下: 397a.。
     它们在 C 语言模块 ‘_ast’ 中定义，并被导出至 *note ast: 7. 模块。

     抽象语法定义的每个左侧符号(比方说， ‘ast.stmt’ 或者 ‘ast.expr’)定义
     了一个类。另外，在抽象语法定义的右侧，对每一个构造器也定义了一个类
     ；这些类继承自树左侧的类。比如，*note ast.BinOp: 10d2. 继承自
     ‘ast.expr’。对于多分支产生式(也就是"和规则")，树右侧的类是抽象的；
     只有特定构造器结点的实例能被构造。

      -- 屬性: _fields

          每个具体类都有个属性 *note _fields: 397d, 用来给出所有子节点的
          名字。

          每个具体类的实例对它每个子节点都有一个属性，对应类型如文法中所
          定义。比如，*note ast.BinOp: 10d2. 的实例有个属性 ‘left’，类型
          是 ‘ast.expr’.

          如果这些属性在文法中标记为可选（使用问号），对应值可能会是
          ‘None’。如果这些属性有零或多个（用星号标记），对应值会用
          Python的列表来表示。所有可能的属性必须在用 *note compile():
          2e7. 编译得到AST时给出，且是有效的值。

      -- 屬性: lineno
      -- 屬性: col_offset
      -- 屬性: end_lineno
      -- 屬性: end_col_offset

          Instances of ‘ast.expr’ and ‘ast.stmt’ subclasses have *note
          lineno: 397e, *note col_offset: 397f, *note end_lineno: 3980,
          and *note end_col_offset: 3981. attributes.  The *note lineno:
          397e. and *note end_lineno: 3980. are the first and last line
          numbers of the source text span (1-indexed so the first line
          is line 1), and the *note col_offset: 397f. and *note
          end_col_offset: 3981. 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.

          Note that the end positions are not required by the compiler
          and are therefore optional.  The end offset is `after' the
          last symbol, for example one can get the source segment of a
          one-line expression node using ‘source_line[node.col_offset :
          node.end_col_offset]’.

     一个类的构造器 ‘ast.T’ 像下面这样parse它的参数。

        * 如果有位置参数，它们必须和 ‘T._fields’ 中的元素一样多；他们会
          像这些名字的属性一样被赋值。

        * 如果有关键字参数，它们必须被设为和给定值同名的属性。

     比方说，要创建和填充节点 *note ast.UnaryOp: 3982.，你得用

          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

     或者更紧凑点

          node = ast.UnaryOp(ast.USub(), ast.Constant(5, lineno=0, col_offset=0),
                             lineno=0, col_offset=0)

3.8 版更變: Class *note ast.Constant: 3a6. is now used for all
constants.

3.9 版更變: Simple indices are represented by their value, extended
slices are represented as tuples.

3.8 版後已棄用: Old classes ‘ast.Num’, ‘ast.Str’, ‘ast.Bytes’,
‘ast.NameConstant’ and ‘ast.Ellipsis’ are still available, but they will
be removed in future Python releases.  In the meantime, instantiating
them will return an instance of a different class.

3.9 版後已棄用: Old classes ‘ast.Index’ and ‘ast.ExtSlice’ are still
available, but they will be removed in future Python releases.  In the
meantime, instantiating them will return an instance of a different
class.

     備註: The descriptions of the specific node classes displayed here
     were initially adapted from the fantastic Green Tree Snakes(1)
     project and all its contributors.

* Menu:

* 字面值: 字面值<3>.
* Variables::
* 表达式: 表达式<2>.
* Statements::
* Control flow::
* Function and class definitions::
* Async and await::

   ---------- Footnotes ----------

   (1) https://greentreesnakes.readthedocs.io/en/latest/


File: python.info,  Node: 字面值<3>,  Next: Variables,  Up: 节点类

5.32.2.3 字面值
...............

 -- 類別: ast.Constant (value)

     A constant value.  The ‘value’ attribute of the ‘Constant’ literal
     contains the Python object it represents.  The values represented
     can be simple types such as a number, string or ‘None’, but also
     immutable container types (tuples and frozensets) if all of their
     elements are constant.

          >>> print(ast.dump(ast.parse('123', mode='eval'), indent=4))
          Expression(
              body=Constant(value=123))

 -- 類別: ast.FormattedValue (value, conversion, format_spec)

     Node representing a single formatting field in an f-string.  If the
     string contains a single formatting field and nothing else the node
     can be isolated otherwise it appears in *note JoinedStr: 3985.

        * ‘value’ is any expression node (such as a literal, a variable,
          or a function call).

        * ‘conversion’ is an integer:

             * -1: no formatting

             * 115: ‘!s’ string formatting

             * 114: ‘!r’ repr formatting

             * 97: ‘!a’ ascii formatting

        * ‘format_spec’ is a *note JoinedStr: 3985. node representing
          the formatting of the value, or ‘None’ if no format was
          specified.  Both ‘conversion’ and ‘format_spec’ can be set at
          the same time.

 -- 類別: ast.JoinedStr (values)

     An f-string, comprising a series of *note FormattedValue: 3984. and
     *note Constant: 3a6. nodes.

          >>> 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')]))]))

 -- 類別: ast.List (elts, ctx)
 -- 類別: ast.Tuple (elts, ctx)

     A list or tuple.  ‘elts’ holds a list of nodes representing the
     elements.  ‘ctx’ is *note Store: 3988. if the container is an
     assignment target (i.e.  ‘(x,y)=something’), and *note Load: 3989.
     otherwise.

          >>> 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()))

 -- 類別: ast.Set (elts)

     A set.  ‘elts’ holds a list of nodes representing the set’s
     elements.

          >>> 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)]))

 -- 類別: ast.Dict (keys, values)

     A dictionary.  ‘keys’ and ‘values’ hold lists of nodes representing
     the keys and the values respectively, in matching order (what would
     be returned when calling ‘dictionary.keys()’ and
     ‘dictionary.values()’).

     When doing dictionary unpacking using dictionary literals the
     expression to be expanded goes in the ‘values’ list, with a ‘None’
     at the corresponding position in ‘keys’.

          >>> 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())]))


File: python.info,  Node: Variables,  Next: 表达式<2>,  Prev: 字面值<3>,  Up: 节点类

5.32.2.4 Variables
..................

 -- 類別: ast.Name (id, ctx)

     A variable name.  ‘id’ holds the name as a string, and ‘ctx’ is one
     of the following types.

 -- 類別: ast.Load
 -- 類別: ast.Store
 -- 類別: ast.Del

     Variable references can be used to load the value of a variable, to
     assign a new value to it, or to delete it.  Variable references are
     given a context to distinguish these cases.

          >>> 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=[])

 -- 類別: ast.Starred (value, ctx)

     A ‘*var’ variable reference.  ‘value’ holds the variable, typically
     a *note Name: 102b. node.  This type must be used when building a
     *note Call: 398e. node with ‘*args’.

          >>> 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=[])


File: python.info,  Node: 表达式<2>,  Next: Statements,  Prev: Variables,  Up: 节点类

5.32.2.5 表达式
...............

 -- 類別: ast.Expr (value)

     When an expression, such as a function call, appears as a statement
     by itself with its return value not used or stored, it is wrapped
     in this container.  ‘value’ holds one of the other nodes in this
     section, a *note Constant: 3a6, a *note Name: 102b, a *note Lambda:
     3991, a *note Yield: 3992. or *note YieldFrom: 3993. node.

          >>> print(ast.dump(ast.parse('-a'), indent=4))
          Module(
              body=[
                  Expr(
                      value=UnaryOp(
                          op=USub(),
                          operand=Name(id='a', ctx=Load())))],
              type_ignores=[])

 -- 類別: ast.UnaryOp (op, operand)

     A unary operation.  ‘op’ is the operator, and ‘operand’ any
     expression node.

 -- 類別: ast.UAdd
 -- 類別: ast.USub
 -- 類別: ast.Not
 -- 類別: ast.Invert

     Unary operator tokens.  *note Not: 3996. is the ‘not’ keyword,
     *note Invert: 3997. is the ‘~’ operator.

          >>> print(ast.dump(ast.parse('not x', mode='eval'), indent=4))
          Expression(
              body=UnaryOp(
                  op=Not(),
                  operand=Name(id='x', ctx=Load())))

 -- 類別: ast.BinOp (left, op, right)

     A binary operation (like addition or division).  ‘op’ is the
     operator, and ‘left’ and ‘right’ are any expression nodes.

          >>> 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())))

 -- 類別: ast.Add
 -- 類別: ast.Sub
 -- 類別: ast.Mult
 -- 類別: ast.Div
 -- 類別: ast.FloorDiv
 -- 類別: ast.Mod
 -- 類別: ast.Pow
 -- 類別: ast.LShift
 -- 類別: ast.RShift
 -- 類別: ast.BitOr
 -- 類別: ast.BitXor
 -- 類別: ast.BitAnd
 -- 類別: ast.MatMult

     Binary operator tokens.

 -- 類別: ast.BoolOp (op, values)

     A boolean operation, ’or’ or ’and’.  ‘op’ is *note Or: 39a6. or
     *note And: 39a7.  ‘values’ are the values involved.  Consecutive
     operations with the same operator, such as ‘a or b or c’, are
     collapsed into one node with several values.

     This doesn’t include ‘not’, which is a *note UnaryOp: 3982.

          >>> 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())]))

 -- 類別: ast.And
 -- 類別: ast.Or

     Boolean operator tokens.

 -- 類別: ast.Compare (left, ops, comparators)

     A comparison of two or more values.  ‘left’ is the first value in
     the comparison, ‘ops’ the list of operators, and ‘comparators’ the
     list of values after the first element in the comparison.

          >>> 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)]))

 -- 類別: ast.Eq
 -- 類別: ast.NotEq
 -- 類別: ast.Lt
 -- 類別: ast.LtE
 -- 類別: ast.Gt
 -- 類別: ast.GtE
 -- 類別: ast.Is
 -- 類別: ast.IsNot
 -- 類別: ast.In
 -- 類別: ast.NotIn

     Comparison operator tokens.

 -- 類別: ast.Call (func, args, keywords, starargs, kwargs)

     A function call.  ‘func’ is the function, which will often be a
     *note Name: 102b. or *note Attribute: 39b3. object.  Of the
     arguments:

        * ‘args’ holds a list of the arguments passed by position.

        * ‘keywords’ holds a list of *note keyword: a6. objects
          representing arguments passed by keyword.

     When creating a ‘Call’ node, ‘args’ and ‘keywords’ are required,
     but they can be empty lists.  ‘starargs’ and ‘kwargs’ are optional.

          >>> 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()))]))

 -- 類別: ast.keyword (arg, value)

     A keyword argument to a function call or class definition.  ‘arg’
     is a raw string of the parameter name, ‘value’ is a node to pass
     in.

 -- 類別: ast.IfExp (test, body, orelse)

     An expression such as ‘a if b else c’.  Each field holds a single
     node, so in the following example, all three are *note Name: 102b.
     nodes.

          >>> 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())))

 -- 類別: ast.Attribute (value, attr, ctx)

     Attribute access, e.g.  ‘d.keys’.  ‘value’ is a node, typically a
     *note Name: 102b.  ‘attr’ is a bare string giving the name of the
     attribute, and ‘ctx’ is *note Load: 3989, *note Store: 3988. or
     *note Del: 398c. according to how the attribute is acted on.

          >>> print(ast.dump(ast.parse('snake.colour', mode='eval'), indent=4))
          Expression(
              body=Attribute(
                  value=Name(id='snake', ctx=Load()),
                  attr='colour',
                  ctx=Load()))

 -- 類別: ast.NamedExpr (target, value)

          A named expression.  This AST node is produced by the
          assignment expressions operator (also known as the walrus
          operator).  As opposed to the *note Assign: 39b7. node in
          which the first argument can be multiple nodes, in this case
          both ‘target’ and ‘value’ must be single nodes.

          >>> print(ast.dump(ast.parse('(x := 4)', mode='eval'), indent=4))
          Expression(
              body=NamedExpr(
                  target=Name(id='x', ctx=Store()),
                  value=Constant(value=4)))

* Menu:

* Subscripting::
* Comprehensions::


File: python.info,  Node: Subscripting,  Next: Comprehensions,  Up: 表达式<2>

5.32.2.6 Subscripting
.....................

 -- 類別: ast.Subscript (value, slice, ctx)

     A subscript, such as ‘l[1]’.  ‘value’ is the subscripted object
     (usually sequence or mapping).  ‘slice’ is an index, slice or key.
     It can be a *note Tuple: 3987. and contain a *note Slice: 39ba.
     ‘ctx’ is *note Load: 3989, *note Store: 3988. or *note Del: 398c.
     according to the action performed with the subscript.

          >>> 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()))

 -- 類別: ast.Slice (lower, upper, step)

     Regular slicing (on the form ‘lower:upper’ or ‘lower:upper:step’).
     Can occur only inside the `slice' field of *note Subscript: 39b9,
     either directly or as an element of *note Tuple: 3987.

          >>> 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()))


File: python.info,  Node: Comprehensions,  Prev: Subscripting,  Up: 表达式<2>

5.32.2.7 Comprehensions
.......................

 -- 類別: ast.ListComp (elt, generators)
 -- 類別: ast.SetComp (elt, generators)
 -- 類別: ast.GeneratorExp (elt, generators)
 -- 類別: ast.DictComp (key, value, generators)

     List and set comprehensions, generator expressions, and dictionary
     comprehensions.  ‘elt’ (or ‘key’ and ‘value’) is a single node
     representing the part that will be evaluated for each item.

     ‘generators’ is a list of *note comprehension: 39c0. nodes.

          >>> 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)]))

 -- 類別: ast.comprehension (target, iter, ifs, is_async)

     One ‘for’ clause in a comprehension.  ‘target’ is the reference to
     use for each element - typically a *note Name: 102b. or *note
     Tuple: 3987. node.  ‘iter’ is the object to iterate over.  ‘ifs’ is
     a list of test expressions: each ‘for’ clause can have multiple
     ‘ifs’.

     ‘is_async’ indicates a comprehension is asynchronous (using an
     ‘async for’ instead of ‘for’).  The value is an integer (0 or 1).

          >>> 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)]))


File: python.info,  Node: Statements,  Next: Control flow,  Prev: 表达式<2>,  Up: 节点类

5.32.2.8 Statements
...................

 -- 類別: ast.Assign (targets, value, type_comment)

     An assignment.  ‘targets’ is a list of nodes, and ‘value’ is a
     single node.

     Multiple nodes in ‘targets’ represents assigning the same value to
     each.  Unpacking is represented by putting a *note Tuple: 3987. or
     *note List: 3986. within ‘targets’.

      -- 屬性: type_comment

          ‘type_comment’ is an optional string with the type annotation
          as a comment.

          >>> 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=[])

 -- 類別: ast.AnnAssign (target, annotation, value, simple)

     An assignment with a type annotation.  ‘target’ is a single node
     and can be a *note Name: 102b, a *note Attribute: 39b3. or a *note
     Subscript: 39b9.  ‘annotation’ is the annotation, such as a *note
     Constant: 3a6. or *note Name: 102b. node.  ‘value’ is a single
     optional node.  ‘simple’ is a boolean integer set to True for a
     *note Name: 102b. node in ‘target’ that do not appear in between
     parenthesis and are hence pure names and not expressions.

          >>> 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=[])

 -- 類別: ast.AugAssign (target, op, value)

     Augmented assignment, such as ‘a += 1’.  In the following example,
     ‘target’ is a *note Name: 102b. node for ‘x’ (with the *note Store:
     3988. context), ‘op’ is *note Add: 3998, and ‘value’ is a *note
     Constant: 3a6. with value for 1.

     The ‘target’ attribute connot be of class *note Tuple: 3987. or
     *note List: 3986, unlike the targets of *note Assign: 39b7.

          >>> 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=[])

 -- 類別: ast.Raise (exc, cause)

     A ‘raise’ statement.  ‘exc’ is the exception object to be raised,
     normally a *note Call: 398e. or *note Name: 102b, or ‘None’ for a
     standalone ‘raise’.  ‘cause’ is the optional part for ‘y’ in ‘raise
     x from y’.

          >>> 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=[])

 -- 類別: ast.Assert (test, msg)

     An assertion.  ‘test’ holds the condition, such as a *note Compare:
     39a8. node.  ‘msg’ holds the failure message.

          >>> 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=[])

 -- 類別: ast.Delete (targets)

     Represents a ‘del’ statement.  ‘targets’ is a list of nodes, such
     as *note Name: 102b, *note Attribute: 39b3. or *note Subscript:
     39b9. nodes.

          >>> 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=[])

 -- 類別: ast.Pass

     A ‘pass’ statement.

          >>> print(ast.dump(ast.parse('pass'), indent=4))
          Module(
              body=[
                  Pass()],
              type_ignores=[])

Other statements which are only applicable inside functions or loops are
described in other sections.

* Menu:

* Imports::


File: python.info,  Node: Imports,  Up: Statements

5.32.2.9 Imports
................

 -- 類別: ast.Import (names)

     An import statement.  ‘names’ is a list of *note alias: 39cb.
     nodes.

          >>> 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=[])

 -- 類別: ast.ImportFrom (module, names, level)

     Represents ‘from x import y’.  ‘module’ is a raw string of the
     ’from’ name, without any leading dots, or ‘None’ for statements
     such as ‘from . import foo’.  ‘level’ is an integer holding the
     level of the relative import (0 means absolute import).

          >>> 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=[])

 -- 類別: ast.alias (name, asname)

     Both parameters are raw strings of the names.  ‘asname’ can be
     ‘None’ if the regular name is to be used.

          >>> 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=[])


File: python.info,  Node: Control flow,  Next: Function and class definitions,  Prev: Statements,  Up: 节点类

5.32.2.10 Control flow
......................

     備註: Optional clauses such as ‘else’ are stored as an empty list
     if they’re not present.

 -- 類別: ast.If (test, body, orelse)

     An ‘if’ statement.  ‘test’ holds a single node, such as a *note
     Compare: 39a8. node.  ‘body’ and ‘orelse’ each hold a list of
     nodes.

     ‘elif’ clauses don’t have a special representation in the AST, but
     rather appear as extra *note If: 39ce. nodes within the ‘orelse’
     section of the previous one.

          >>> 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=[])

 -- 類別: ast.For (target, iter, body, orelse, type_comment)

     A ‘for’ loop.  ‘target’ holds the variable(s) the loop assigns to,
     as a single *note Name: 102b, *note Tuple: 3987. or *note List:
     3986. node.  ‘iter’ holds the item to be looped over, again as a
     single node.  ‘body’ and ‘orelse’ contain lists of nodes to
     execute.  Those in ‘orelse’ are executed if the loop finishes
     normally, rather than via a ‘break’ statement.

      -- 屬性: type_comment

          ‘type_comment’ is an optional string with the type annotation
          as a comment.

          >>> 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=[])

 -- 類別: ast.While (test, body, orelse)

     A ‘while’ loop.  ‘test’ holds the condition, such as a *note
     Compare: 39a8. node.

          >> 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=[])

 -- 類別: ast.Break
 -- 類別: ast.Continue

     The ‘break’ and ‘continue’ statements.

          >>> 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=[])

 -- 類別: ast.Try (body, handlers, orelse, finalbody)

     ‘try’ blocks.  All attributes are list of nodes to execute, except
     for ‘handlers’, which is a list of *note ExceptHandler: 39d5.
     nodes.

          >>> 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=[])

 -- 類別: ast.ExceptHandler (type, name, body)

     A single ‘except’ clause.  ‘type’ is the exception type it will
     match, typically a *note Name: 102b. node (or ‘None’ for a
     catch-all ‘except:’ clause).  ‘name’ is a raw string for the name
     to hold the exception, or ‘None’ if the clause doesn’t have ‘as
     foo’.  ‘body’ is a list of nodes.

          >>> 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=[])

 -- 類別: ast.With (items, body, type_comment)

     A ‘with’ block.  ‘items’ is a list of *note withitem: 39d7. nodes
     representing the context managers, and ‘body’ is the indented block
     inside the context.

      -- 屬性: type_comment

          ‘type_comment’ is an optional string with the type annotation
          as a comment.

 -- 類別: ast.withitem (context_expr, optional_vars)

     A single context manager in a ‘with’ block.  ‘context_expr’ is the
     context manager, often a *note Call: 398e. node.  ‘optional_vars’
     is a *note Name: 102b, *note Tuple: 3987. or *note List: 3986. for
     the ‘as foo’ part, or ‘None’ if that isn’t used.

          >>> 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=[])


File: python.info,  Node: Function and class definitions,  Next: Async and await,  Prev: Control flow,  Up: 节点类

5.32.2.11 Function and class definitions
........................................

 -- 類別: ast.FunctionDef (name, args, body, decorator_list, returns,
          type_comment)

     A function definition.

        * ‘name’ is a raw string of the function name.

        * ‘args’ is an *note arguments: 39db. node.

        * ‘body’ is the list of nodes inside the function.

        * ‘decorator_list’ is the list of decorators to be applied,
          stored outermost first (i.e.  the first in the list will be
          applied last).

        * ‘returns’ is the return annotation.

      -- 屬性: type_comment

          ‘type_comment’ is an optional string with the type annotation
          as a comment.

 -- 類別: ast.Lambda (args, body)

     ‘lambda’ is a minimal function definition that can be used inside
     an expression.  Unlike *note FunctionDef: 39da, ‘body’ holds a
     single node.

          >>> 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=[])

 -- 類別: ast.arguments (posonlyargs, args, vararg, kwonlyargs,
          kw_defaults, kwarg, defaults)

     The arguments for a function.

        * ‘posonlyargs’, ‘args’ and ‘kwonlyargs’ are lists of *note arg:
          39dd. nodes.

        * ‘vararg’ and ‘kwarg’ are single *note arg: 39dd. nodes,
          referring to the ‘*args, **kwargs’ parameters.

        * ‘kw_defaults’ is a list of default values for keyword-only
          arguments.  If one is ‘None’, the corresponding argument is
          required.

        * ‘defaults’ is a list of default values for arguments that can
          be passed positionally.  If there are fewer defaults, they
          correspond to the last n arguments.

 -- 類別: ast.arg (arg, annotation, type_comment)

     A single argument in a list.  ‘arg’ is a raw string of the argument
     name, ‘annotation’ is its annotation, such as a ‘Str’ or *note
     Name: 102b. node.

      -- 屬性: type_comment

          ‘type_comment’ is an optional string with the type annotation
          as a comment

          >>> 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=[])

 -- 類別: ast.Return (value)

     A ‘return’ statement.

          >>> print(ast.dump(ast.parse('return 4'), indent=4))
          Module(
              body=[
                  Return(
                      value=Constant(value=4))],
              type_ignores=[])

 -- 類別: ast.Yield (value)
 -- 類別: ast.YieldFrom (value)

     A ‘yield’ or ‘yield from’ expression.  Because these are
     expressions, they must be wrapped in a *note Expr: 3990. node if
     the value sent back is not used.

          >>> 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=[])

 -- 類別: ast.Global (names)
 -- 類別: ast.Nonlocal (names)

     ‘global’ and ‘nonlocal’ statements.  ‘names’ is a list of raw
     strings.

          >>> 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=[])

 -- 類別: ast.ClassDef (name, bases, keywords, starargs, kwargs, body,
          decorator_list)

     A class definition.

        * ‘name’ is a raw string for the class name

        * ‘bases’ is a list of nodes for explicitly specified base
          classes.

        * ‘keywords’ is a list of *note keyword: a6. nodes, principally
          for ’metaclass’.  Other keywords will be passed to the
          metaclass, as per PEP-3115(1).

        * ‘starargs’ and ‘kwargs’ are each a single node, as in a
          function call.  starargs will be expanded to join the list of
          base classes, and kwargs will be passed to the metaclass.

        * ‘body’ is a list of nodes representing the code within the
          class definition.

        * ‘decorator_list’ is a list of nodes, as in *note FunctionDef:
          39da.

          >>> 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=[])

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3115/


File: python.info,  Node: Async and await,  Prev: Function and class definitions,  Up: 节点类

5.32.2.12 Async and await
.........................

 -- 類別: ast.AsyncFunctionDef (name, args, body, decorator_list,
          returns, type_comment)

     An ‘async def’ function definition.  Has the same fields as *note
     FunctionDef: 39da.

 -- 類別: ast.Await (value)

     An ‘await’ expression.  ‘value’ is what it waits for.  Only valid
     in the body of an *note AsyncFunctionDef: 39e4.

     >>> 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=[])

 -- 類別: ast.AsyncFor (target, iter, body, orelse, type_comment)
 -- 類別: ast.AsyncWith (items, body, type_comment)

     ‘async for’ loops and ‘async with’ context managers.  They have the
     same fields as *note For: 39cf. and *note With: 39d6, respectively.
     Only valid in the body of an *note AsyncFunctionDef: 39e4.

     備註: When a string is parsed by *note ast.parse(): 2d6, operator
     nodes (subclasses of ‘ast.operator’, ‘ast.unaryop’, ‘ast.cmpop’,
     ‘ast.boolop’ and ‘ast.expr_context’) on the returned tree will be
     singletons.  Changes to one will be reflected in all other
     occurrences of the same value (e.g.  *note ast.Add: 3998.).


File: python.info,  Node: ast 中的辅助函数,  Next: Compiler Flags,  Prev: 节点类,  Up: ast --- 抽象语法树

5.32.2.13 ‘ast’ 中的辅助函数
............................

除了节点类， *note ast: 7. 模块里为遍历抽象语法树定义了这些工具函数和类:

 -- 函式: ast.parse (source, filename='<unknown>', mode='exec', *,
          type_comments=False, feature_version=None)

     把源码解析为AST节点。和 ‘compile(source, filename,
     mode,ast.PyCF_ONLY_AST)’ 等价。

     If ‘type_comments=True’ is given, the parser is modified to check
     and return type comments as specified by PEP 484(1) and PEP 526(2).
     This is equivalent to adding *note ast.PyCF_TYPE_COMMENTS: 39e9. to
     the flags passed to *note compile(): 2e7.  This will report syntax
     errors for misplaced type comments.  Without this flag, type
     comments will be ignored, and the ‘type_comment’ field on selected
     AST nodes will always be ‘None’.  In addition, the locations of ‘#
     type: ignore’ comments will be returned as the ‘type_ignores’
     attribute of ‘Module’ (otherwise it is always an empty list).

     In addition, if ‘mode’ is ‘'func_type'’, the input syntax is
     modified to correspond to PEP 484(3) "signature type comments",
     e.g.  ‘(str, int) -> List[str]’.

     Also, setting ‘feature_version’ to a tuple ‘(major, minor)’ will
     attempt to parse using that Python version’s grammar.  Currently
     ‘major’ must equal to ‘3’.  For example, setting
     ‘feature_version=(3, 4)’ will allow the use of ‘async’ and ‘await’
     as variable names.  The lowest supported version is ‘(3, 4)’; the
     highest is ‘sys.version_info[0:2]’.

     If source contains a null character (’0’), *note ValueError: 16d.
     is raised.

               警告: Note that successfully parsing source code into an
               AST object doesn’t guarantee that the source code
               provided is valid Python code that can be executed as the
               compilation step can raise further *note SyntaxError:
               559. exceptions.  For instance, the source ‘return 42’
               generates a valid AST node for a return statement, but it
               cannot be compiled alone (it needs to be inside a
               function node).

               In particular, *note ast.parse(): 2d6. won’t do any
               scoping checks, which the compilation step does.

          警告: 足够复杂或是巨大的字符串可能导致Python解释器的崩溃，因为
          Python的AST编译器是有栈深限制的。

     3.8 版更變: Added ‘type_comments’, ‘mode='func_type'’ and
     ‘feature_version’.

 -- 函式: ast.unparse (ast_obj)

     Unparse an *note ast.AST: 187. object and generate a string with
     code that would produce an equivalent *note ast.AST: 187. object if
     parsed back with *note ast.parse(): 2d6.

          警告: The produced code string will not necessarily be equal
          to the original code that generated the *note ast.AST: 187.
          object (without any compiler optimizations, such as constant
          tuples/frozensets).

          警告: Trying to unparse a highly complex expression would
          result with *note RecursionError: 727.

     3.9 版新加入.

 -- 函式: ast.literal_eval (node_or_string)

     对表达式节点以及包含Python字面量或容器的字符串进行安全的求值。传入
     的字符串或者节点里可能只包含下列的Python字面量结构: 字符串，字节对
     象(bytes)，数值，元组，列表，字典，集合，布尔值和 ‘None’。

     This can be used for safely evaluating strings containing Python
     values from untrusted sources without the need to parse the values
     oneself.  It is not capable of evaluating arbitrarily complex
     expressions, for example involving operators or indexing.

          警告: 足够复杂或是巨大的字符串可能导致Python解释器的崩溃，因为
          Python的AST编译器是有栈深限制的。

     3.2 版更變: 目前支持字节和集合。

     3.9 版更變: Now supports creating empty sets with ‘'set()'’.

 -- 函式: ast.get_docstring (node, clean=True)

     Return the docstring of the given `node' (which must be a *note
     FunctionDef: 39da, *note AsyncFunctionDef: 39e4, *note ClassDef:
     39e2, or ‘Module’ node), or ‘None’ if it has no docstring.  If
     `clean' is true, clean up the docstring’s indentation with *note
     inspect.cleandoc(): 387b.

     3.5 版更變: 目前支持 *note AsyncFunctionDef: 39e4.

 -- 函式: ast.get_source_segment (source, node, *, padded=False)

     Get source code segment of the `source' that generated `node'.  If
     some location information (‘lineno’, ‘end_lineno’, ‘col_offset’, or
     ‘end_col_offset’) is missing, return ‘None’.

     If `padded' is ‘True’, the first line of a multi-line statement
     will be padded with spaces to match its original position.

     3.8 版新加入.

 -- 函式: ast.fix_missing_locations (node)

     When you compile a node tree with *note compile(): 2e7, the
     compiler expects ‘lineno’ and ‘col_offset’ attributes for every
     node that supports them.  This is rather tedious to fill in for
     generated nodes, so this helper adds these attributes recursively
     where not already set, by setting them to the values of the parent
     node.  It works recursively starting at `node'.

 -- 函式: ast.increment_lineno (node, n=1)

     Increment the line number and end line number of each node in the
     tree starting at `node' by `n'.  This is useful to "move code" to a
     different location in a file.

 -- 函式: ast.copy_location (new_node, old_node)

     Copy source location (‘lineno’, ‘col_offset’, ‘end_lineno’, and
     ‘end_col_offset’) from `old_node' to `new_node' if possible, and
     return `new_node'.

 -- 函式: ast.iter_fields (node)

     Yield a tuple of ‘(fieldname, value)’ for each field in
     ‘node._fields’ that is present on `node'.

 -- 函式: ast.iter_child_nodes (node)

     Yield all direct child nodes of `node', that is, all fields that
     are nodes and all items of fields that are lists of nodes.

 -- 函式: ast.walk (node)

     Recursively yield all descendant nodes in the tree starting at
     `node' (including `node' itself), in no specified order.  This is
     useful if you only want to modify nodes in place and don’t care
     about the context.

 -- 類別: ast.NodeVisitor

     A node visitor base class that walks the abstract syntax tree and
     calls a visitor function for every node found.  This function may
     return a value which is forwarded by the *note visit(): 39ef.
     method.

     This class is meant to be subclassed, with the subclass adding
     visitor methods.

      -- 成員函式: visit (node)

          Visit a node.  The default implementation calls the method
          called ‘self.visit_`classname'’ where `classname' is the name
          of the node class, or *note generic_visit(): 39f0. if that
          method doesn’t exist.

      -- 成員函式: generic_visit (node)

          This visitor calls *note visit(): 39ef. on all children of the
          node.

          Note that child nodes of nodes that have a custom visitor
          method won’t be visited unless the visitor calls *note
          generic_visit(): 39f0. or visits them itself.

     Don’t use the *note NodeVisitor: 3a7. if you want to apply changes
     to nodes during traversal.  For this a special visitor exists
     (*note NodeTransformer: 39f1.) that allows modifications.

     3.8 版後已棄用: Methods ‘visit_Num()’, ‘visit_Str()’,
     ‘visit_Bytes()’, ‘visit_NameConstant()’ and ‘visit_Ellipsis()’ are
     deprecated now and will not be called in future Python versions.
     Add the ‘visit_Constant()’ method to handle all constant nodes.

 -- 類別: ast.NodeTransformer

     子类 *note NodeVisitor: 3a7. 用于遍历抽象语法树，并允许修改节点。

     *note NodeTransformer: 39f1. 将遍历抽象语法树并使用visitor方法的返
     回值去替换或移除旧节点。如果visitor方法的返回值为 ‘None’ , 则该节点
     将从其位置移除，否则将替换为返回值。当返回值是原始节点时，无需替换
     。

     如下是一个转换器示例，它将所有出现的名称 (‘foo’) 重写为
     ‘data['foo']’:

          class RewriteName(NodeTransformer):

              def visit_Name(self, node):
                  return Subscript(
                      value=Name(id='data', ctx=Load()),
                      slice=Constant(value=node.id),
                      ctx=node.ctx
                  )

     请记住，如果您正在操作的节点具有子节点，则必须先转换其子节点或为该
     节点调用 ‘generic_visit()’ 方法。

     对于属于语句集合（适用于所有语句节点）的节点，访问者还可以返回节点
     列表而不仅仅是单个节点。

     If *note NodeTransformer: 39f1. introduces new nodes (that weren’t
     part of original tree) without giving them location information
     (such as ‘lineno’), *note fix_missing_locations(): 39ea. should be
     called with the new sub-tree to recalculate the location
     information:

          tree = ast.parse('foo', mode='eval')
          new_tree = fix_missing_locations(RewriteName().visit(tree))

     通常你可以像这样使用转换器:

          node = YourTransformer().visit(node)

 -- 函式: ast.dump (node, annotate_fields=True,
          include_attributes=False, *, indent=None)

     Return a formatted dump of the tree in `node'.  This is mainly
     useful for debugging purposes.  If `annotate_fields' is true (by
     default), the returned string will show the names and the values
     for fields.  If `annotate_fields' is false, the result string will
     be more compact by omitting unambiguous field names.  Attributes
     such as line numbers and column offsets are not dumped by default.
     If this is wanted, `include_attributes' can be set to true.

     If `indent' is a non-negative integer or string, then the tree will
     be pretty-printed with that indent level.  An indent level of 0,
     negative, or ‘""’ will only insert newlines.  ‘None’ (the default)
     selects the single line representation.  Using a positive integer
     indent indents that many spaces per level.  If `indent' is a string
     (such as ‘"\t"’), that string is used to indent each level.

     3.9 版更變: Added the `indent' option.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0484

   (2) https://www.python.org/dev/peps/pep-0526

   (3) https://www.python.org/dev/peps/pep-0484


File: python.info,  Node: Compiler Flags,  Next: 命令行用法<2>,  Prev: ast 中的辅助函数,  Up: ast --- 抽象语法树

5.32.2.14 Compiler Flags
........................

The following flags may be passed to *note compile(): 2e7. in order to
change effects on the compilation of a program:

 -- Data: ast.PyCF_ALLOW_TOP_LEVEL_AWAIT

     Enables support for top-level ‘await’, ‘async for’, ‘async with’
     and async comprehensions.

     3.8 版新加入.

 -- Data: ast.PyCF_ONLY_AST

     Generates and returns an abstract syntax tree instead of returning
     a compiled code object.

 -- Data: ast.PyCF_TYPE_COMMENTS

     Enables support for PEP 484(1) and PEP 526(2) style type comments
     (‘# type: <type>’, ‘# type: ignore <stuff>’).

     3.8 版新加入.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0484

   (2) https://www.python.org/dev/peps/pep-0526


File: python.info,  Node: 命令行用法<2>,  Prev: Compiler Flags,  Up: ast --- 抽象语法树

5.32.2.15 命令行用法
....................

3.9 版新加入.

The *note ast: 7. module can be executed as a script from the command
line.  It is as simple as:

     python -m ast [-m <mode>] [-a] [infile]

可以接受以下选项：

 -- 程式選項: -h, --help

     Show the help message and exit.

 -- 程式選項: -m <mode>
 -- 程式選項: --mode <mode>

     Specify what kind of code must be compiled, like the `mode'
     argument in *note parse(): 2d6.

 -- 程式選項: --no-type-comments

     Don’t parse type comments.

 -- 程式選項: -a, --include-attributes

     Include attributes such as line numbers and column offsets.

 -- 程式選項: -i <indent>
 -- 程式選項: --indent <indent>

     Indentation of nodes in AST (number of spaces).

If ‘infile’ is specified its contents are parsed to AST and dumped to
stdout.  Otherwise, the content is read from stdin.

也參考
......

Green Tree Snakes(1), an external documentation resource, has good
details on working with Python ASTs.

ASTTokens(2) annotates Python ASTs with the positions of tokens and text
in the source code that generated them.  This is helpful for tools that
make source code transformations.

leoAst.py(3) unifies the token-based and parse-tree-based views of
python programs by inserting two-way links between tokens and ast nodes.

LibCST(4) parses code as a Concrete Syntax Tree that looks like an ast
tree and keeps all formatting details.  It’s useful for building
automated refactoring (codemod) applications and linters.

Parso(5) is a Python parser that supports error recovery and round-trip
parsing for different Python versions (in multiple Python versions).
Parso is also able to list multiple syntax errors in your python file.

   ---------- Footnotes ----------

   (1) https://greentreesnakes.readthedocs.io/

   (2) https://asttokens.readthedocs.io/en/latest/user-guide.html

   (3) http://leoeditor.com/appendices.html#leoast-py

   (4) https://libcst.readthedocs.io/

   (5) https://parso.readthedocs.io


File: python.info,  Node: symtable ——访问编译器的符号表,  Next: symbol --- 与 Python 解析树一起使用的常量,  Prev: ast --- 抽象语法树,  Up: Python 语言服务

5.32.3 ‘symtable’ ——访问编译器的符号表
--------------------------------------

`Source code：' Lib/symtable.py(1)

__________________________________________________________________

符号表由编译器在生成字节码之前根据 AST 生成。符号表负责计算代码中每个标
识符的作用域。 *note symtable: fc. 提供了一个查看这些表的接口。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/symtable.py


File: python.info,  Node: 符号表的生成,  Next: 符号表的查看,  Up: symtable ——访问编译器的符号表

5.32.3.1 符号表的生成
.....................

 -- 函式: symtable.symtable (code, filename, compile_type)

     返回 Python 源 `代码' 顶层的 *note SymbolTable: 3a00.。`filename' 是
     代码文件名。 `compile_type' 的含义类似 *note compile(): 2e7. 的
     `mode' 参数。


File: python.info,  Node: 符号表的查看,  Prev: 符号表的生成,  Up: symtable ——访问编译器的符号表

5.32.3.2 符号表的查看
.....................

 -- 類別: symtable.SymbolTable

     某个代码块的命名空间表。构造函数不公开。

      -- 成員函式: get_type ()

          返回符号表的类型。可能是 ‘'class'’ 、‘'module'’ 或
          ‘'function'’。

      -- 成員函式: get_id ()

          返回符号表的标识符

      -- 成員函式: get_name ()

          返回符号表的名称。 若为类的符号表则返回类名；若为函数的符号表
          则为函数名；若是全局符号表则为 ‘'top'’ (*note get_type():
          3a02. 返回 ‘'module'’)。

      -- 成員函式: get_lineno ()

          返回符号表所代表的代码块中第一行的编号。

      -- 成員函式: is_optimized ()

          如果符号表中的局部变量可能被优化过，则返回 ‘True’。

      -- 成員函式: is_nested ()

          如果代码块是嵌套类或函数，则返回 ‘True’。

      -- 成員函式: has_children ()

          如果代码块中有嵌套的命名空间，则返回 ‘True’。可通过 *note
          get_children(): 3a09. 读取。

      -- 成員函式: get_identifiers ()

          返回符号表中的符号名列表。

      -- 成員函式: lookup (name)

          在符号表中查找 `name' 并返回一个 *note Symbol: 3a0c. 实例。

      -- 成員函式: get_symbols ()

          返回符号表中所有符号的 *note Symbol: 3a0c. 实例的列表。

      -- 成員函式: get_children ()

          返回嵌套符号表的列表。

 -- 類別: symtable.Function

     函数或方法的命名空间。该类继承自 *note SymbolTable: 3a00.。

      -- 成員函式: get_parameters ()

          返回由函数的参数名组成的元组。

      -- 成員函式: get_locals ()

          返回函数中局部变量名组成的元组。

      -- 成員函式: get_globals ()

          返回函数中全局变量名组成的元组。

      -- 成員函式: get_nonlocals ()

          返回函数中非局部变量名组成的元组。

      -- 成員函式: get_frees ()

          返回函数中自由变量名组成的元组。

 -- 類別: symtable.Class

     类的命名空间。继承自 *note SymbolTable: 3a00.。

      -- 成員函式: get_methods ()

          返回类中声明的方法名组成的元组。

 -- 類別: symtable.Symbol

     *note SymbolTable: 3a00. 中的数据项，对应于源码中的某个标识符。构造
     函数不公开。

      -- 成員函式: get_name ()

          返回符号名

      -- 成員函式: is_referenced ()

          如果符号在代码块中被引用了，则返回 ‘True’。

      -- 成員函式: is_imported ()

          如果符号是由导入语句创建的，则返回 ‘True’。

      -- 成員函式: is_parameter ()

          如果符号是参数，返回 ‘True’。

      -- 成員函式: is_global ()

          如果符号是全局变量，则返回 ‘True’。

      -- 成員函式: is_nonlocal ()

          如果符号为非局部变量，则返回 ‘True’。

      -- 成員函式: is_declared_global ()

          如果符号用 global 声明为全局变量，则返回 ‘True’。

      -- 成員函式: is_local ()

          如果符号在代码块内是局部变量，则返回 ‘True’。

      -- 成員函式: is_annotated ()

          如果符号带有注解，则返回 ‘True’。

          3.6 版新加入.

      -- 成員函式: is_free ()

          如果符号在代码块中被引用，但未赋值，则返回 ‘True’。

      -- 成員函式: is_assigned ()

          如果符号在代码块中赋值，则返回 ‘True’。

      -- 成員函式: is_namespace ()

          如果符号名绑定引入了新的命名空间，则返回 ‘True’。

          如果符号名用于 function 或 class 语句，则为 True。

          例如:

               >>> table = symtable.symtable("def some_func(): pass", "string", "exec")
               >>> table.lookup("some_func").is_namespace()
               True

          注意，一个符号名可以与多个对象绑定。如果结果为 ‘True’，则该符
          号名还可以绑定到其他对象上，比如 int 或 list ，且不会引入新的
          命名空间。

      -- 成員函式: get_namespaces ()

          返回与符号名绑定的命名空间的列表。

      -- 成員函式: get_namespace ()

          返回与符号名绑定的命名空间。如果绑定的命名空间超过一个，则会触
          发 *note ValueError: 16d.。


File: python.info,  Node: symbol --- 与 Python 解析树一起使用的常量,  Next: token --- 与Python解析树一起使用的常量,  Prev: symtable ——访问编译器的符号表,  Up: Python 语言服务

5.32.4 ‘symbol’ — 与 Python 解析树一起使用的常量
------------------------------------------------

`源代码:' Lib/symbol.py(1)

__________________________________________________________________

此模块提供用于表示解析树内部节点数值的常量。 与大多数 Python 不同，这些
常量使用小写字符名称。 请参阅 Python 发行版中的 ‘Grammar/Grammar’ 文件来
获取该语言语法上下文中对这些名称的定义。 这些名称所映射的特定数字值可能
会在 Python 版本之间更改。

     警告: symbol 模块已弃用并将在未来的 Python 版本中被移除。

此模块还提供了一个额外的数据对象:

 -- Data: symbol.sym_name

     将此模块中定义的常量的数值映射回名称字符串的字典，允许生成更加人类
     可读的解析树表示。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/symbol.py


File: python.info,  Node: token --- 与Python解析树一起使用的常量,  Next: keyword --- 检验Python关键字,  Prev: symbol --- 与 Python 解析树一起使用的常量,  Up: Python 语言服务

5.32.5 ‘token’ — 与Python解析树一起使用的常量
---------------------------------------------

`源码：' Lib/token.py(1)

__________________________________________________________________

此模块提供表示解析树（终端令牌）的叶节点的数值的常量。 请参阅 Python 发
行版中的文件 ‘Grammar/Grammar’ ，以获取语言语法上下文中名称的定义。 名称
映射到的特定数值可能会在 Python 版本之间更改。

该模块还提供从数字代码到名称和一些函数的映射。 这些函数镜像了 Python C 头
文件中的定义。

 -- Data: token.tok_name

     将此模块中定义的常量的数值映射回名称字符串的字典，允许生成更加人类
     可读的解析树表示。

 -- 函式: token.ISTERMINAL (x)

     对终端标记值返回 ‘True’。

 -- 函式: token.ISNONTERMINAL (x)

     对非终端标记值返回 ‘True’。

 -- 函式: token.ISEOF (x)

     如果 `x' 是表示输入结束的标记则返回 ‘True’。

标记常量是：

 -- Data: token.ENDMARKER

 -- Data: token.NAME

 -- Data: token.NUMBER

 -- Data: token.STRING

 -- Data: token.NEWLINE

 -- Data: token.INDENT

 -- Data: token.DEDENT

 -- Data: token.LPAR

     ‘"("’ 的权标值。

 -- Data: token.RPAR

     ‘")"’ 的权标值。

 -- Data: token.LSQB

     ‘"["’ 的权标值。

 -- Data: token.RSQB

     ‘"]"’ 的权标值。

 -- Data: token.COLON

     ‘":"’ 的权标值。

 -- Data: token.COMMA

     ‘","’ 的权标值。

 -- Data: token.SEMI

     ‘";"’ 的权标值。

 -- Data: token.PLUS

     ‘"+"’ 的权标值。

 -- Data: token.MINUS

     ‘"-"’ 的权标值。

 -- Data: token.STAR

     ‘"*"’ 的权标值。

 -- Data: token.SLASH

     ‘"/"’ 的权标值。

 -- Data: token.VBAR

     ‘"|"’ 的权标值。

 -- Data: token.AMPER

     ‘"&"’ 的权标值。

 -- Data: token.LESS

     ‘"<"’ 的权标值。

 -- Data: token.GREATER

     ‘">"’ 的权标值。

 -- Data: token.EQUAL

     Token value for ‘"="’.

 -- Data: token.DOT

     Token value for ‘"."’.

 -- Data: token.PERCENT

     Token value for ‘"%"’.

 -- Data: token.LBRACE

     Token value for ‘"{"’.

 -- Data: token.RBRACE

     Token value for ‘"}"’.

 -- Data: token.EQEQUAL

     Token value for ‘"=="’.

 -- Data: token.NOTEQUAL

     Token value for ‘"!="’.

 -- Data: token.LESSEQUAL

     Token value for ‘"<="’.

 -- Data: token.GREATEREQUAL

     Token value for ‘">="’.

 -- Data: token.TILDE

     Token value for ‘"~"’.

 -- Data: token.CIRCUMFLEX

     Token value for ‘"^"’.

 -- Data: token.LEFTSHIFT

     Token value for ‘"<<"’.

 -- Data: token.RIGHTSHIFT

     Token value for ‘">>"’.

 -- Data: token.DOUBLESTAR

     Token value for ‘"**"’.

 -- Data: token.PLUSEQUAL

     Token value for ‘"+="’.

 -- Data: token.MINEQUAL

     Token value for ‘"-="’.

 -- Data: token.STAREQUAL

     Token value for ‘"*="’.

 -- Data: token.SLASHEQUAL

     Token value for ‘"/="’.

 -- Data: token.PERCENTEQUAL

     Token value for ‘"%="’.

 -- Data: token.AMPEREQUAL

     Token value for ‘"&="’.

 -- Data: token.VBAREQUAL

     Token value for ‘"|="’.

 -- Data: token.CIRCUMFLEXEQUAL

     Token value for ‘"^="’.

 -- Data: token.LEFTSHIFTEQUAL

     Token value for ‘"<<="’.

 -- Data: token.RIGHTSHIFTEQUAL

     Token value for ‘">>="’.

 -- Data: token.DOUBLESTAREQUAL

     Token value for ‘"**="’.

 -- Data: token.DOUBLESLASH

     Token value for ‘"//"’.

 -- Data: token.DOUBLESLASHEQUAL

     Token value for ‘"//="’.

 -- Data: token.AT

     Token value for ‘"@"’.

 -- Data: token.ATEQUAL

     Token value for ‘"@="’.

 -- Data: token.RARROW

     Token value for ‘"->"’.

 -- Data: token.ELLIPSIS

     Token value for ‘"..."’.

 -- Data: token.COLONEQUAL

     Token value for ‘":="’.

 -- Data: token.OP

 -- Data: token.AWAIT

 -- Data: token.ASYNC

 -- Data: token.TYPE_IGNORE

 -- Data: token.TYPE_COMMENT

 -- Data: token.ERRORTOKEN

 -- Data: token.N_TOKENS

 -- Data: token.NT_OFFSET

C 标记生成器不使用以下标记类型值，但 *note tokenize: 11a. 模块需要这些标
记类型值。

 -- Data: token.COMMENT

     标记值用于表示注释。

 -- Data: token.NL

     标记值用于表示非终止换行符。 *note NEWLINE: 3a2f. 标记表示 Python 代
     码逻辑行的结束；当在多条物理线路上继续执行逻辑代码行时，会生成 ‘NL’
     标记。

 -- Data: token.ENCODING

     指示用于将源字节解码为文本的编码的标记值。 *note
     tokenize.tokenize(): d23. 返回的第一个标记将始终是一个 ‘ENCODING’ 标
     记。

 -- Data: token.TYPE_COMMENT

     Token value indicating that a type comment was recognized.  Such
     tokens are only produced when *note ast.parse(): 2d6. is invoked
     with ‘type_comments=True’.

3.5 版更變: 补充 *note AWAIT: 3a62. 和 *note ASYNC: 3a63. 标记。

3.7 版更變: 补充 *note COMMENT: 3a69. 、 *note NL: 3a6a. 和 *note
ENCODING: 3a6b. 标记。

3.7 版更變: 移除 *note AWAIT: 3a62. 和 *note ASYNC: 3a63. 标记。 "async"
和 "await" 现在被标记为 *note NAME: 3a2c. 标记。

3.8 版更變: Added *note TYPE_COMMENT: 3a65, *note TYPE_IGNORE: 3a64,
*note COLONEQUAL: 3a60.  Added *note AWAIT: 3a62. and *note ASYNC: 3a63.
tokens back (they’re needed to support parsing older Python versions for
*note ast.parse(): 2d6. with ‘feature_version’ set to 6 or lower).

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/token.py


File: python.info,  Node: keyword --- 检验Python关键字,  Next: tokenize --- 对 Python 代码使用的标记解析器,  Prev: token --- 与Python解析树一起使用的常量,  Up: Python 语言服务

5.32.6 ‘keyword’ — 检验Python关键字
-----------------------------------

`源码：' Lib/keyword.py(1)

__________________________________________________________________

此模块允许 Python 程序确定某个字符串是否为 *note 关键字: 150d.。

 -- 函式: keyword.iskeyword (s)

     如果 `s' 是一个 Python *note 关键字: 150d. 则返回 ‘True’。

 -- Data: keyword.kwlist

     包含解释器定义的所有 *note 关键字: 150d. 的序列。 如果所定义的任何
     关键字仅在特定 *note __future__: 0. 语句生效时被激活，它们也将被包
     含在内。

 -- 函式: keyword.issoftkeyword (s)

     如果 `s' 是一个 Python 的软 *note 关键字: 150d. 则返回 ‘True’。

     3.9 版新加入.

 -- Data: keyword.softkwlist

     包含解释器定义的所有软 *note 关键字: 150d. 的序列。 如果所定义的任
     何软关键字仅在特定 *note __future__: 0. 语句生效时被激活，它们也将
     被包含在内。

     3.9 版新加入.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/keyword.py


File: python.info,  Node: tokenize --- 对 Python 代码使用的标记解析器,  Next: tabnanny --- 模糊缩进检测,  Prev: keyword --- 检验Python关键字,  Up: Python 语言服务

5.32.7 ‘tokenize’ — 对 Python 代码使用的标记解析器
--------------------------------------------------

`源码：' Lib/tokenize.py(1)

__________________________________________________________________

*note tokenize: 11a. 模块为 Python 源代码提供了一个词法扫描器，用 Python
实现。该模块中的扫描器也将注释作为标记返回，这使得它对于实现“漂亮的输出
器”非常有用，包括用于屏幕显示的着色器。

为了简化标记流的处理，所有的 *note 运算符: 154a. 和 *note 定界符: 154b.
以及 *note Ellipsis: 1740. 返回时都会打上通用的 *note OP: 3a61. 标记。 可
以通过 *note tokenize.tokenize(): d23. 返回的 *note named tuple: b7b. 对
象的 ‘exact_type’ 属性来获得确切的标记类型。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/tokenize.py


File: python.info,  Node: 对输入进行解析标记,  Next: 命令行用法<3>,  Up: tokenize --- 对 Python 代码使用的标记解析器

5.32.7.1 对输入进行解析标记
...........................

主要的入口是一个生成器 *note generator: a83.:

 -- 函式: tokenize.tokenize (readline)

     生成器 *note tokenize(): d23. 需要一个 `readline' 参数，这个参数必
     须是一个可调用对象，且能提供与文件对象的 *note
     io.IOBase.readline(): 1849. 方法相同的接口。每次调用这个函数都要 返
     回字节类型输入的一行数据。

     生成器产生 5 个具有这些成员的元组：令牌类型；令牌字符串；指定令牌在
     源中开始的行和列的 2 元组 ‘(srow, scol)’ ；指定令牌在源中结束的行和
     列的 2 元组 ‘(erow, ecol)’ ；以及发现令牌的行。所传递的行（最后一个
     元组项）是 `实际的' 行。 5 个元组以 *note named tuple: b7b. 的形式
     返回，字段名是： ‘type string start end line’ 。

     返回的 *note named tuple: b7b. 有一个额外的属性，名为 ‘exact_type’
     ，包含了 *note OP: 3a61. 标记的确切操作符类型。 对于所有其他标记类
     型， ‘exact_type’ 等于命名元组的 ‘type’ 字段。

     3.1 版更變: 增加了对 named tuple 的支持。

     3.3 版更變: 添加了对 ‘exact_type’ 的支持。

     根据:pep:‘263’ ， *note tokenize(): d23. 通过寻找 UTF-8 BOM 或编码
     cookie 来确定文件的源编码。

 -- 函式: tokenize.generate_tokens (readline)

     对读取 unicode 字符串而不是字节的源进行标记。

     和 *note tokenize(): d23. 一样， `readline' 参数是一个返回单行输入
     的可调用参数。然而， *note generate_tokens(): 116b. 希望 `readline'
     返回一个 str 对象而不是字节。

     其结果是一个产生具名元组的的迭代器，与 *note tokenize(): d23. 完全
     一样。 它不会产生 *note ENCODING: 3a6b. 标记。

所有来自 *note token: 119. 模块的常量也可从 *note tokenize: 11a. 导出。

提供了另一个函数来逆转标记化过程。这对于创建对脚本进行标记、修改标记流并
写回修改后脚本的工具很有用。

 -- 函式: tokenize.untokenize (iterable)

     将令牌转换为 Python 源代码。 `iterable' 必须返回至少有两个元素的序
     列，即令牌类型和令牌字符串。任何额外的序列元素都会被忽略。

     重构的脚本以单个字符串的形式返回。 结果被保证为标记回与输入相匹配，
     因此转换是无损的，并保证来回操作。 该保证只适用于标记类型和标记字符
     串，因为标记之间的间距（列位置）可能会改变。

     它返回字节，使用 *note ENCODING: 3a6b. 标记进行编码，这是由 *note
     tokenize(): d23. 输出的第一个标记序列。如果输入中没有编码令牌，它将
     返回一个字符串。

*note tokenize(): d23. 需要检测它所标记源文件的编码。它用来做这件事的函
数是可用的：

 -- 函式: tokenize.detect_encoding (readline)

     *note detect_encoding(): 1ddd. 函数用于检测解码 Python 源文件时应使
     用的编码。它需要一个参数， readline ，与 *note tokenize(): d23. 生
     成器的使用方式相同。

     它最多调用 readline 两次，并返回所使用的编码（作为一个字符串）和它
     所读入的任何行（不是从字节解码的）的 list 。

     它从 UTF-8 BOM 或编码 cookie 的存在中检测编码格式，如 PEP 263(1) 所
     指明的。 如果 BOM 和 cookie 都存在，但不一致，将会引发 *note
     SyntaxError: 559.。 请注意，如果找到 BOM ，将返回 ‘'utf-8-sig'’ 作
     为编码格式。

     如果没有指定编码，那么将返回默认的 ‘'utf-8'’ 编码.

     使用 *note open(): 1ddc. 来打开 Python 源文件：它使用 *note
     detect_encoding(): 1ddd. 来检测文件编码。

 -- 函式: tokenize.open (filename)

     使用由 *note detect_encoding(): 1ddd. 检测到的编码，以只读模式打开
     一个文件。

     3.2 版新加入.

 -- 例外: tokenize.TokenError

     当文件中任何地方没有完成 docstring 或可能被分割成几行的表达式时触发
     ，例如:

          """Beginning of
          docstring

     或是：

          [1,
           2,
           3

注意，未封闭的单引号字符串不会导致错误发生。它们被标记为 *note
ERRORTOKEN: 3a66. ，然后是其内容的标记化。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0263


File: python.info,  Node: 命令行用法<3>,  Next: 示例<45>,  Prev: 对输入进行解析标记,  Up: tokenize --- 对 Python 代码使用的标记解析器

5.32.7.2 命令行用法
...................

3.3 版新加入.

*note tokenize: 11a. 模块可以作为一个脚本从命令行执行。这很简单。

     python -m tokenize [-e] [filename.py]

可以接受以下选项：

 -- 程式選項: -h, --help

     显示此帮助信息并退出

 -- 程式選項: -e, --exact

     使用确切的类型显示令牌名称

如果 ‘filename.py’ 被指定，其内容会被标记到 stdout 。否则，标记化将在
stdin 上执行。


File: python.info,  Node: 示例<45>,  Prev: 命令行用法<3>,  Up: tokenize --- 对 Python 代码使用的标记解析器

5.32.7.3 示例
.............

脚本改写器的例子，它将 float 文本转换为 Decimal 对象：。

     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')

从命令行进行标记化的例子。 脚本:

     def say_hello():
         print("Hello, World!")

     say_hello()

将被标记为以下输出，其中第一列是发现标记的行 / 列坐标范围，第二列是标记
的名称，最后一列是标记的值（如果有）。

     $ 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         ''
     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      ''

可以使用 *note -e: 3a79. 选项来显示确切的标记类型名称。

     $ 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         ''
     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      ''

以编程方式对文件进行标记的例子，用 *note generate_tokens(): 116b. 读取
unicode 字符串而不是字节:

     import tokenize

     with tokenize.open('hello.py') as f:
         tokens = tokenize.generate_tokens(f.readline)
         for token in tokens:
             print(token)

或者通过 *note tokenize(): d23. 直接读取字节数据:

     import tokenize

     with open('hello.py', 'rb') as f:
         tokens = tokenize.tokenize(f.readline)
         for token in tokens:
             print(token)


File: python.info,  Node: tabnanny --- 模糊缩进检测,  Next: pyclbr --- Python 模块浏览器支持,  Prev: tokenize --- 对 Python 代码使用的标记解析器,  Up: Python 语言服务

5.32.8 ‘tabnanny’ — 模糊缩进检测
--------------------------------

`源代码:' Lib/tabnanny.py(1)

__________________________________________________________________

目前，该模块旨在作为脚本调用。但是可以使用下面描述的 *note check():
3a7d. 函数将其导入IDE。

     備註: 此模块提供的API可能会在将来的版本中更改；此类更改可能无法向后
     兼容。

 -- 函式: tabnanny.check (file_or_dir)

     如果 `file_or_dir' 是目录而非符号链接，则递归地在名为 `file_or_dir'
     的目录树中下行，沿途检查所有 ‘.py’ 文件。 如果 `file_or_dir' 是一个
     普通 Python 源文件，将检查其中的空格相关问题。 诊断消息将使用 *note
     print(): 971. 函数写入到标准输出。

 -- Data: tabnanny.verbose

     此旗标指明是否打印详细消息。 如果作为脚本调用则是通过 ‘-v’ 选项来增
     加。

 -- Data: tabnanny.filename_only

     此旗标指明是否只打印包含空格相关问题文件的文件名。 如果作为脚本调用
     则是通过 ‘-q’ 选项来设为真值。

 -- 例外: tabnanny.NannyNag

     如果检测到模糊缩进则由 *note process_tokens(): 3a81. 引发。 在
     *note check(): 3a7d. 中捕获并处理。

 -- 函式: tabnanny.process_tokens (tokens)

     此函数由 *note check(): 3a7d. 用来处理由 *note tokenize: 11a. 模块
     所生成的标记。

也參考
......

模块 *note tokenize: 11a.

     用于Python源代码的词法扫描程序。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/tabnanny.py


File: python.info,  Node: pyclbr --- Python 模块浏览器支持,  Next: py_compile --- 编译 Python 源文件,  Prev: tabnanny --- 模糊缩进检测,  Up: Python 语言服务

5.32.9 ‘pyclbr’ — Python 模块浏览器支持
---------------------------------------

`源代码:' Lib/pyclbr.py(1)

__________________________________________________________________

*note pyclbr: d8. 模块提供了对于以 Python 编写的模块中定义的函数、类和方
法的受限信息。 这种信息足够用来实现一个模块浏览器。 这种信息是从 Python
源代码中直接提取而非通过导入模块，因此该模块可以安全地用于不受信任的代码
。 此限制使得非 Python 实现的模块无法使用此模块，包括所有标准和可选的扩
展模块。

 -- 函式: pyclbr.readmodule (module, path=None)

     返回一个将模块层级的类名映射到类描述器的字典。 如果可能，将会包括已
     导入基类的描述器。 形参 `module' 为要读取模块名称的字符串；它可能是
     某个包内部的模块名称。 `path' 如果给出则为添加到 ‘sys.path’ 开头的
     目录路径序列，它会被用于定位模块的源代码。

     此函数为原始接口，仅保留用于向下兼容。 它会返回以下内容的过滤版本。

 -- 函式: pyclbr.readmodule_ex (module, path=None)

     返回一个基于字典的树，其中包含与模块中每个用 ‘def’ 或 ‘class’ 语句
     定义的函数和类相对应的函数和类描述器。 被返回的字典会将模块层级的函
     数和类名映射到它们的描述器。 嵌套的对象会被输入到它们的上级子目录中
     。 与 readmodule 一样，`module' 指明要读取的模块而 `path' 会被添加
     到 sys.path。 如果被读取的模块是一个包，则返回的字典将具有
     ‘'__path__'’ 键，其值是一个包含包搜索路径的列表。

3.7 版新加入: 嵌套定义的描述器。 它们通过新的子属性来访问。 每个定义都会
有一个新的上级属性。

这些函数所返回的描述器是 Function 和 Class 类的实例。 用户不应自行创建这
些类的实例。

* Menu:

* 函式物件::
* Class 对象::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/pyclbr.py


File: python.info,  Node: 函式物件,  Next: Class 对象,  Up: pyclbr --- Python 模块浏览器支持

5.32.9.1 函式物件
.................

‘Function’ 类的实例描述了由 def 语句所定义的函数。 它们具有下列属性:

 -- 屬性: Function.file

     函数定义所在的文件名称。

 -- 屬性: Function.module

     定义了所描述函数的模块名称。

 -- 屬性: Function.name

     函数名称。

 -- 屬性: Function.lineno

     定义在文件中起始位置的行号。

 -- 屬性: Function.parent

     对于最高层级函数为 None。 对于嵌套函数则为上级函数。

     3.7 版新加入.

 -- 屬性: Function.children

     将名称映射到嵌套函数和类描述器的字典。

     3.7 版新加入.


File: python.info,  Node: Class 对象,  Prev: 函式物件,  Up: pyclbr --- Python 模块浏览器支持

5.32.9.2 Class 对象
...................

‘Class’ 类的实例描述了由 class 语句所定义的类。 它们具有与 Function 对象
相同的属性以及两个额外属性。

 -- 屬性: Class.file

     类定义所在的文件名称。

 -- 屬性: Class.module

     定义了所描述类的模块名称。

 -- 屬性: Class.name

     类名称。

 -- 屬性: Class.lineno

     定义在文件中起始位置的行号。

 -- 屬性: Class.parent

     对于最高层级类为 None。 对于嵌套类则为上级类。

     3.7 版新加入.

 -- 屬性: Class.children

     将名称映射到嵌套函数和类描述器的字典。

     3.7 版新加入.

 -- 屬性: Class.super

     一个 ‘Class’ 对象的列表，它们描述了所描述类的直接基类。 被命名为超
     类但无法被 *note readmodule_ex(): 129f. 发现的类会作为类名字符串而
     非 ‘Class’ 对象列出。

 -- 屬性: Class.methods

     一个将方法名映射到行号的字典。 此属性可从更新的子目录中获取，仅保留
     用于向下兼容。


File: python.info,  Node: py_compile --- 编译 Python 源文件,  Next: compileall --- Byte-compile Python libraries,  Prev: pyclbr --- Python 模块浏览器支持,  Up: Python 语言服务

5.32.10 ‘py_compile’ — 编译 Python 源文件
-----------------------------------------

`源代码:' Lib/py_compile.py(1)

__________________________________________________________________

*note py_compile: d7. 模块提供了用来从源文件生成字节码的函数和另一个用于
当模块源文件作为脚本被调用时的函数。

虽然不太常用，但这个函数在安装共享模块时还是很有用的，特别是当一些用户可
能没有权限在包含源代码的目录中写字节码缓存文件时。

 -- 例外: py_compile.PyCompileError

     当编译文件过程中发生错误时，抛出的异常。

 -- 函式: py_compile.compile (file, cfile=None, dfile=None,
          doraise=False, optimize=-1,
          invalidation_mode=PycInvalidationMode.TIMESTAMP, quiet=0)

     将源文件编译成字节码并写出字节码缓存文件。 源代码从名为 `file' 的文
     件中加载。 字节码会写入到 `cfile'，默认为 PEP 3147(2)/ PEP 488(3) 路
     径，以 ‘.pyc’ 结尾。 例如，如果 `file' 是 ‘/foo/bar/baz.py’ 则对于
     Python 3.2 `cfile' 将默认为
     ‘/foo/bar/__pycache__/baz.cpython-32.pyc’。 如果指定了 `dfile'，则
     在错误信息中它将代替 `file' 作为源文件的名称。 如果 `doraise' 为真
     值，则当编译 `file' 遇到错误时将会引发 *note PyCompileError: 3a98.。
     如果 `doraise' 为假值（默认），则将错误信息写入到 ‘sys.stderr’，但
     不会引发异常。 此函数返回编译后字节码文件的路径，即 `cfile' 所使用
     的值。

     `doraise' 和 `quiet' 参数确定在编译文件时如何处理错误。 如果
     `quiet' 为 0 或 1，并且 `doraise' 为假值，则会启用默认行为：写入错
     误信息到 ‘sys.stderr’，并且函数将返回 ‘None’ 而非一个路径。 如果
     `doraise' 为真值，则将改为引发 *note PyCompileError: 3a98.。 但是如
     果 `quiet' 为 2，则不会写入消息，并且 `doraise' 也不会有效果。

     如果 `cfile' 所表示（显式指定或计算得出）的路径为符号链接或非常规文
     件，则将引发 *note FileExistsError: a39.。 此行为是用来警告如果允许
     写入编译后字节码文件到这些路径则导入操作将会把它们转为常规文件。 这
     是使用文件重命名来将最终编译后字节码文件放置到位以防止并发文件写入
     问题的导入操作的附带效果。

     `optimize' 控制优化级别并会被传给内置的 *note compile(): 2e7. 函数
     。 默认值 ‘-1’ 表示选择当前解释器的优化级别。

     `invalidation_mode' 应当是 *note PycInvalidationMode: 3a99. 枚举的
     成员，它控制在运行时如何让已生成的字节码缓存失效。 如果设置了
     ‘SOURCE_DATE_EPOCH’ 环境变量则默认值为 *note
     PycInvalidationMode.CHECKED_HASH: 3a9a.，否则默认值为 *note
     PycInvalidationMode.TIMESTAMP: 3a9b.。

     3.2 版更變: 将 `cfile' 的默认值改成与 PEP 3147(4) 兼容。 之前的默认
     值是 `file' + ‘'c'’ (如果启用优化则为 ‘'o'’)。 同时也添加了
     `optimize' 形参。

     3.4 版更變: 将代码更改为使用 *note importlib: 9a. 执行字节码缓存文
     件写入。 这意味着文件创建/写入的语义现在与 *note importlib: 9a. 所
     做的相匹配，例如权限、写入和移动语义等等。 同时也添加了当 `cfile' 为
     符号链接或非常规文件时引发 *note FileExistsError: a39. 的预警设置。

     3.7 版更變: `invalidation_mode' 形参是根据 PEP 552(5) 的描述添加的
     。 如果设置了 ‘SOURCE_DATE_EPOCH’ 环境变量，`invalidation_mode' 将
     被强制设为 *note PycInvalidationMode.CHECKED_HASH: 3a9a.。

     3.7.2 版更變: ‘SOURCE_DATE_EPOCH’ 环境变量不会再覆盖
     `invalidation_mode' 参数的值，而改为确定其默认值。

     3.8 版更變: 增加了 `quiet' 形参。

 -- 類別: py_compile.PycInvalidationMode

     一个由可用方法组成的枚举，解释器可以用来确定字节码文件是否与源文件
     保持一致。 ‘.pyc’ 文件在其标头中指明了所需的失效模式。 请参阅 *note
     已缓存字节码的失效: 439. 了解有关 Python 在运行时如何让 ‘.pyc’ 文件
     失效的更多信息。

     3.7 版新加入.

      -- 屬性: TIMESTAMP

          ‘.pyc’ 文件包括时间戳和源文件的大小，Python 将在运行时将其与源
          文件的元数据进行比较以确定 ‘.pyc’ 文件是否需要重新生成。

      -- 屬性: CHECKED_HASH

          ‘.pyc’ 文件包括源文件内容的哈希值，Python 将在运行时将其与源文
          件内容进行比较以确定 ‘.pyc’ 文件是否需要重新生成。

      -- 屬性: UNCHECKED_HASH

          类似于 *note CHECKED_HASH: 3a9a.，‘.pyc’ 文件包括源文件内容的
          哈希值。 但是，Python 将在运行时假定 ‘.pyc’ 文件是最新的而完全
          不会将 ‘.pyc’ 与源文件进行验证。

          此选项适用于 ‘.pycs’ 由 Python 以外的某个系统例如构建系统来确
          保最新的情况。

 -- 函式: py_compile.main (args=None)

     编译多个源文件。 在 `args' 中（或者当 `args' 为 ‘None’ 时则是在命令
     行中）指定的文件会被编译并将结果字节码以正常方式来缓存。 此函数不会
     搜索目录结构来定位源文件；它只编译显式指定的文件。 如果 ‘'-'’ 是
     args 中唯一的值，则会从标准输入获取文件列表。

     3.2 版更變: 添加了对 ‘'-'’ 的支持。

当此模块作为脚本运行时，会使用 *note main(): 3a9d. 来编译命令行中指定的
所有文件。 如果某个文件无法被编译则退出状态将为非零值。

也參考
......

模块 *note compileall: 20.

     编译一个目录树中所有 Python 源文件的工具。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/py_compile.py

   (2) https://www.python.org/dev/peps/pep-3147

   (3) https://www.python.org/dev/peps/pep-0488

   (4) https://www.python.org/dev/peps/pep-3147

   (5) https://www.python.org/dev/peps/pep-0552


File: python.info,  Node: compileall --- Byte-compile Python libraries,  Next: dis --- Python bytecode的反組譯器,  Prev: py_compile --- 编译 Python 源文件,  Up: Python 语言服务

5.32.11 ‘compileall’ — Byte-compile Python libraries
----------------------------------------------------

`Source code:' Lib/compileall.py(1)

__________________________________________________________________

This module provides some utility functions to support installing Python
libraries.  These functions compile Python source files in a directory
tree.  This module can be used to create the cached byte-code files at
library installation time, which makes them available for use even by
users who don’t have write permission to the library directories.

* Menu:

* Command-line use::
* Public functions::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/compileall.py


File: python.info,  Node: Command-line use,  Next: Public functions,  Up: compileall --- Byte-compile Python libraries

5.32.11.1 Command-line use
..........................

This module can work as a script (using ‘python -m compileall’) to
compile Python sources.

 -- 程式選項: directory ...
 -- 程式選項: file ...

     Positional arguments are files to compile or directories that
     contain source files, traversed recursively.  If no argument is
     given, behave as if the command line was ‘-l <directories from
     sys.path>’.

 -- 程式選項: -l

     Do not recurse into subdirectories, only compile source code files
     directly contained in the named or implied directories.

 -- 程式選項: -f

     Force rebuild even if timestamps are up-to-date.

 -- 程式選項: -q

     Do not print the list of files compiled.  If passed once, error
     messages will still be printed.  If passed twice (‘-qq’), all
     output is suppressed.

 -- 程式選項: -d destdir

     Directory prepended to the path to each file being compiled.  This
     will appear in compilation time tracebacks, and is also compiled in
     to the byte-code file, where it will be used in tracebacks and
     other messages in cases where the source file does not exist at the
     time the byte-code file is executed.

 -- 程式選項: -s strip_prefix

 -- 程式選項: -p prepend_prefix

     Remove (‘-s’) or append (‘-p’) the given prefix of paths recorded
     in the ‘.pyc’ files.  Cannot be combined with ‘-d’.

 -- 程式選項: -x regex

     regex is used to search the full path to each file considered for
     compilation, and if the regex produces a match, the file is
     skipped.

 -- 程式選項: -i list

     Read the file ‘list’ and add each line that it contains to the list
     of files and directories to compile.  If ‘list’ is ‘-’, read lines
     from ‘stdin’.

 -- 程式選項: -b

     Write the byte-code files to their legacy locations and names,
     which may overwrite byte-code files created by another version of
     Python.  The default is to write files to their PEP 3147(1)
     locations and names, which allows byte-code files from multiple
     versions of Python to coexist.

 -- 程式選項: -r

     Control the maximum recursion level for subdirectories.  If this is
     given, then ‘-l’ option will not be taken into account.  ‘python -m
     compileall <directory> -r 0’ is equivalent to ‘python -m compileall
     <directory> -l’.

 -- 程式選項: -j N

     Use `N' workers to compile the files within the given directory.
     If ‘0’ is used, then the result of *note os.cpu_count(): 96a. will
     be used.

 -- 程式選項: --invalidation-mode
          [timestamp|checked-hash|unchecked-hash]

     Control how the generated byte-code files are invalidated at
     runtime.  The ‘timestamp’ value, means that ‘.pyc’ files with the
     source timestamp and size embedded will be generated.  The
     ‘checked-hash’ and ‘unchecked-hash’ values cause hash-based pycs to
     be generated.  Hash-based pycs embed a hash of the source file
     contents rather than a timestamp.  See *note 已缓存字节码的失效:
     439. for more information on how Python validates bytecode cache
     files at runtime.  The default is ‘timestamp’ if the
     ‘SOURCE_DATE_EPOCH’ environment variable is not set, and
     ‘checked-hash’ if the ‘SOURCE_DATE_EPOCH’ environment variable is
     set.

 -- 程式選項: -o level

     Compile with the given optimization level.  May be used multiple
     times to compile for multiple levels at a time (for example,
     ‘compileall -o 1 -o 2’).

 -- 程式選項: -e dir

     Ignore symlinks pointing outside the given directory.

 -- 程式選項: --hardlink-dupes

     If two ‘.pyc’ files with different optimization level have the same
     content, use hard links to consolidate duplicate files.

3.2 版更變: Added the ‘-i’, ‘-b’ and ‘-h’ options.

3.5 版更變: Added the ‘-j’, ‘-r’, and ‘-qq’ options.  ‘-q’ option was
changed to a multilevel value.  ‘-b’ will always produce a byte-code
file ending in ‘.pyc’, never ‘.pyo’.

3.7 版更變: Added the ‘--invalidation-mode’ option.

3.9 版更變: Added the ‘-s’, ‘-p’, ‘-e’ and ‘--hardlink-dupes’ options.
Raised the default recursion limit from 10 to *note
sys.getrecursionlimit(): f3b.  Added the possibility to specify the ‘-o’
option multiple times.

There is no command-line option to control the optimization level used
by the *note compile(): 2e7. function, because the Python interpreter
itself already provides the option: ‘python -O -m compileall’.

Similarly, the *note compile(): 2e7. function respects the *note
sys.pycache_prefix: 291. setting.  The generated bytecode cache will
only be useful if *note compile(): 2e7. is run with the same *note
sys.pycache_prefix: 291. (if any) that will be used at runtime.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3147


File: python.info,  Node: Public functions,  Prev: Command-line use,  Up: compileall --- Byte-compile Python libraries

5.32.11.2 Public functions
..........................

 -- 函式: 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)

     Recursively descend the directory tree named by `dir', compiling
     all ‘.py’ files along the way.  Return a true value if all the
     files compiled successfully, and a false value otherwise.

     The `maxlevels' parameter is used to limit the depth of the
     recursion; it defaults to ‘sys.getrecursionlimit()’.

     If `ddir' is given, it is prepended to the path to each file being
     compiled for use in compilation time tracebacks, and is also
     compiled in to the byte-code file, where it will be used in
     tracebacks and other messages in cases where the source file does
     not exist at the time the byte-code file is executed.

     If `force' is true, modules are re-compiled even if the timestamps
     are up to date.

     If `rx' is given, its ‘search’ method is called on the complete
     path to each file considered for compilation, and if it returns a
     true value, the file is skipped.  This can be used to exclude files
     matching a regular expression, given as a *note re.Pattern: 983.
     object.

     If `quiet' is ‘False’ or ‘0’ (the default), the filenames and other
     information are printed to standard out.  Set to ‘1’, only errors
     are printed.  Set to ‘2’, all output is suppressed.

     If `legacy' is true, byte-code files are written to their legacy
     locations and names, which may overwrite byte-code files created by
     another version of Python.  The default is to write files to their
     PEP 3147(1) locations and names, which allows byte-code files from
     multiple versions of Python to coexist.

     `optimize' specifies the optimization level for the compiler.  It
     is passed to the built-in *note compile(): 2e7. function.  Accepts
     also a sequence of optimization levels which lead to multiple
     compilations of one ‘.py’ file in one call.

     The argument `workers' specifies how many workers are used to
     compile files in parallel.  The default is to not use multiple
     workers.  If the platform can’t use multiple workers and `workers'
     argument is given, then sequential compilation will be used as a
     fallback.  If `workers' is 0, the number of cores in the system is
     used.  If `workers' is lower than ‘0’, a *note ValueError: 16d.
     will be raised.

     `invalidation_mode' should be a member of the *note
     py_compile.PycInvalidationMode: 3a99. enum and controls how the
     generated pycs are invalidated at runtime.

     The `stripdir', `prependdir' and `limit_sl_dest' arguments
     correspond to the ‘-s’, ‘-p’ and ‘-e’ options described above.
     They may be specified as ‘str’, ‘bytes’ or *note os.PathLike: 5e5.

     If `hardlink_dupes' is true and two ‘.pyc’ files with different
     optimization level have the same content, use hard links to
     consolidate duplicate files.

     3.2 版更變: Added the `legacy' and `optimize' parameter.

     3.5 版更變: Added the `workers' parameter.

     3.5 版更變: `quiet' parameter was changed to a multilevel value.

     3.5 版更變: The `legacy' parameter only writes out ‘.pyc’ files,
     not ‘.pyo’ files no matter what the value of `optimize' is.

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

     3.7 版更變: The `invalidation_mode' parameter was added.

     3.7.2 版更變: The `invalidation_mode' parameter’s default value is
     updated to None.

     3.8 版更變: Setting `workers' to 0 now chooses the optimal number
     of cores.

     3.9 版更變: Added `stripdir', `prependdir', `limit_sl_dest' and
     `hardlink_dupes' arguments.  Default value of `maxlevels' was
     changed from ‘10’ to ‘sys.getrecursionlimit()’

 -- 函式: 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)

     Compile the file with path `fullname'.  Return a true value if the
     file compiled successfully, and a false value otherwise.

     If `ddir' is given, it is prepended to the path to the file being
     compiled for use in compilation time tracebacks, and is also
     compiled in to the byte-code file, where it will be used in
     tracebacks and other messages in cases where the source file does
     not exist at the time the byte-code file is executed.

     If `rx' is given, its ‘search’ method is passed the full path name
     to the file being compiled, and if it returns a true value, the
     file is not compiled and ‘True’ is returned.  This can be used to
     exclude files matching a regular expression, given as a *note
     re.Pattern: 983. object.

     If `quiet' is ‘False’ or ‘0’ (the default), the filenames and other
     information are printed to standard out.  Set to ‘1’, only errors
     are printed.  Set to ‘2’, all output is suppressed.

     If `legacy' is true, byte-code files are written to their legacy
     locations and names, which may overwrite byte-code files created by
     another version of Python.  The default is to write files to their
     PEP 3147(2) locations and names, which allows byte-code files from
     multiple versions of Python to coexist.

     `optimize' specifies the optimization level for the compiler.  It
     is passed to the built-in *note compile(): 2e7. function.  Accepts
     also a sequence of optimization levels which lead to multiple
     compilations of one ‘.py’ file in one call.

     `invalidation_mode' should be a member of the *note
     py_compile.PycInvalidationMode: 3a99. enum and controls how the
     generated pycs are invalidated at runtime.

     The `stripdir', `prependdir' and `limit_sl_dest' arguments
     correspond to the ‘-s’, ‘-p’ and ‘-e’ options described above.
     They may be specified as ‘str’, ‘bytes’ or *note os.PathLike: 5e5.

     If `hardlink_dupes' is true and two ‘.pyc’ files with different
     optimization level have the same content, use hard links to
     consolidate duplicate files.

     3.2 版新加入.

     3.5 版更變: `quiet' parameter was changed to a multilevel value.

     3.5 版更變: The `legacy' parameter only writes out ‘.pyc’ files,
     not ‘.pyo’ files no matter what the value of `optimize' is.

     3.7 版更變: The `invalidation_mode' parameter was added.

     3.7.2 版更變: The `invalidation_mode' parameter’s default value is
     updated to None.

     3.9 版更變: Added `stripdir', `prependdir', `limit_sl_dest' and
     `hardlink_dupes' arguments.

 -- 函式: compileall.compile_path (skip_curdir=True, maxlevels=0,
          force=False, quiet=0, legacy=False, optimize=-1,
          invalidation_mode=None)

     Byte-compile all the ‘.py’ files found along ‘sys.path’.  Return a
     true value if all the files compiled successfully, and a false
     value otherwise.

     If `skip_curdir' is true (the default), the current directory is
     not included in the search.  All other parameters are passed to the
     *note compile_dir(): 47a. function.  Note that unlike the other
     compile functions, ‘maxlevels’ defaults to ‘0’.

     3.2 版更變: Added the `legacy' and `optimize' parameter.

     3.5 版更變: `quiet' parameter was changed to a multilevel value.

     3.5 版更變: The `legacy' parameter only writes out ‘.pyc’ files,
     not ‘.pyo’ files no matter what the value of `optimize' is.

     3.7 版更變: The `invalidation_mode' parameter was added.

     3.7.2 版更變: The `invalidation_mode' parameter’s default value is
     updated to None.

To force a recompile of all the ‘.py’ files in the ‘Lib/’ subdirectory
and all its subdirectories:

     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)

也參考
......

模块 *note py_compile: d7.

     Byte-compile a single source file.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3147

   (2) https://www.python.org/dev/peps/pep-3147


File: python.info,  Node: dis --- Python bytecode的反組譯器,  Next: pickletools --- pickle 开发者工具集,  Prev: compileall --- Byte-compile Python libraries,  Up: Python 语言服务

5.32.12 ‘dis’ — Python bytecode的反組譯器
-----------------------------------------

`原始碼：'Lib/dis.py(1)

__________________________________________________________________

*note dis: 37. 模組支援反組譯分析 CPython *note bytecode: 709.。CPython
bytecode 作為輸入的模組被定義於 ‘Include/opcode.h’ 並且被編譯器和直譯器
所使用。

`CPython implementation detail:' 字节码是 CPython 解释器的实现细节。不保
证不会在Python版本之间添加、删除或更改字节码。不应考虑将此模块的跨
Python VM 或 Python 版本的使用。

3.6 版更變: 每条指令使用2个字节。以前字节数因指令而异。

示例：给出函数 ‘myfunc()’:

     def myfunc(alist):
         return len(alist)

可以使用以下命令显示 ‘myfunc()’ 的反汇编

     >>> dis.dis(myfunc)
       2           0 LOAD_GLOBAL              0 (len)
                   2 LOAD_FAST                0 (alist)
                   4 CALL_FUNCTION            1
                   6 RETURN_VALUE

("2" 是行号)。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/dis.py


File: python.info,  Node: 字节码分析,  Next: 分析函数,  Up: dis --- Python bytecode的反組譯器

5.32.12.1 字节码分析
....................

3.4 版新加入.

字节码分析 API 允许将 Python 代码片段包装在 *note Bytecode: 924. 对象中
，以便轻松访问已编译代码的详细信息。

 -- 類別: dis.Bytecode (x, *, first_line=None, current_offset=None)

     分析的字节码对应于函数、生成器、异步生成器、协程、方法、源代码字符
     串或代码对象（由 *note compile(): 2e7. 返回）。

     这是下面列出的许多函数的便利包装，最值得注意的是 *note
     get_instructions(): 923. ，迭代于 *note Bytecode: 924. 的实例产生字
     节码操作 *note Instruction: 922. 的实例。

     如果 `first_line' 不是 ‘None’ ，则表示应该为反汇编代码中的第一个源
     代码行报告的行号。否则，源行信息（如果有的话）直接来自反汇编的代码
     对象。

     如果 `current_offset' 不是 ‘None’ ，则它指的是反汇编代码中的指令偏
     移量。设置它意味着 *note dis(): 925. 将针对指定的操作码显示“当前指
     令”标记。

      -- 成員函式: classmethod from_traceback (tb)

          从给定回溯构造一个 *note Bytecode: 924. 实例，将设置
          `current_offset' 为异常负责的指令。

      -- Data: codeobj

          已编译的代码对象。

      -- Data: first_line

          代码对象的第一个源代码行（如果可用）

      -- 成員函式: dis ()

          返回字节码操作的格式化视图（与 *note dis.dis(): 48a. 打印相同
          ，但作为多行字符串返回）。

      -- 成員函式: info ()

          返回带有关于代码对象的详细信息的格式化多行字符串，如 *note
          code_info(): c9c. 。

     3.7 版更變: 现在可以处理协程和异步生成器对象。

示例:

     >>> bytecode = dis.Bytecode(myfunc)
     >>> for instr in bytecode:
     ...     print(instr.opname)
     ...
     LOAD_GLOBAL
     LOAD_FAST
     CALL_FUNCTION
     RETURN_VALUE


File: python.info,  Node: 分析函数,  Next: Python字节码说明,  Prev: 字节码分析,  Up: dis --- Python bytecode的反組譯器

5.32.12.2 分析函数
..................

*note dis: 37. 模块还定义了以下分析函数，它们将输入直接转换为所需的输出
。如果只执行单个操作，它们可能很有用，因此中间分析对象没用：

 -- 函式: dis.code_info (x)

     返回格式化的多行字符串，其包含详细代码对象信息的用于被提供的函数、
     生成器、异步生成器、协程、方法、源代码字符串或代码对象。

     请注意，代码信息字符串的确切内容是高度依赖于实现的，它们可能会在
     Python VM或Python版本中任意更改。

     3.2 版新加入.

     3.7 版更變: 现在可以处理协程和异步生成器对象。

 -- 函式: dis.show_code (x, *, file=None)

     将提供的函数、方法。源代码字符串或代码对象的详细代码对象信息打印到
     `file' （如果未指定 `file' ，则为 ‘sys.stdout’ ）。

     这是 ‘print(code_info(x), file=file)’ 的便捷简写，用于在解释器提示
     符下进行交互式探索。

     3.2 版新加入.

     3.4 版更變: 添加 `file' 形参。

 -- 函式: dis.dis (x=None, *, file=None, depth=None)

     反汇编 `x' 对象。 `x' 可以表示模块、类、方法、函数、生成器、异步生
     成器、协程、代码对象、源代码字符串或原始字节码的字节序列。对于模块
     ，它会反汇编所有功能。对于一个类，它反汇编所有方法（包括类和静态方
     法）。对于代码对象或原始字节码序列，它每字节码指令打印一行。它还递
     归地反汇编嵌套代码对象（推导式代码，生成器表达式和嵌套函数，以及用
     于构建嵌套类的代码）。在被反汇编之前，首先使用 *note compile():
     2e7. 内置函数将字符串编译为代码对象。如果未提供任何对象，则此函数会
     反汇编最后一次回溯。

     如果提供的话，反汇编将作为文本写入提供的 `file' 参数，否则写入
     ‘sys.stdout’ 。

     递归的最大深度受 `depth' 限制，除非它是 ‘None’ 。 ‘depth=0’ 表示没
     有递归。

     3.4 版更變: 添加 `file' 形参。

     3.7 版更變: 实现了递归反汇编并添加了 `depth' 参数。

     3.7 版更變: 现在可以处理协程和异步生成器对象。

 -- 函式: dis.distb (tb=None, *, file=None)

     如果没有传递，则使用最后一个回溯来反汇编回溯的堆栈顶部函数。 指示了
     导致异常的指令。

     如果提供的话，反汇编将作为文本写入提供的 `file' 参数，否则写入
     ‘sys.stdout’ 。

     3.4 版更變: 添加 `file' 形参。

 -- 函式: dis.disassemble (code, lasti=-1, *, file=None)
 -- 函式: dis.disco (code, lasti=-1, *, file=None)

     反汇编代码对象，如果提供了 `lasti' ，则指示最后一条指令。输出分为以
     下几列：

       1. 行号，用于每行的第一条指令

       2. 当前指令，表示为 ‘-->’ ，

       3. 一个标记的指令，用 ‘>>’ 表示，

       4. 指令的地址，

       5. 操作码名称，

       6. 操作参数，和

       7. 括号中参数的解释。

     参数解释识别本地和全局变量名称、常量值、分支目标和比较运算符。

     如果提供的话，反汇编将作为文本写入提供的 `file' 参数，否则写入
     ‘sys.stdout’ 。

     3.4 版更變: 添加 `file' 形参。

 -- 函式: dis.get_instructions (x, *, first_line=None)

     在所提供的函数、方法、源代码字符串或代码对象中的指令上返回一个迭代
     器。

     迭代器生成一系列 *note Instruction: 922. ，命名为元组，提供所提供代
     码中每个操作的详细信息。

     如果 `first_line' 不是 ‘None’ ，则表示应该为反汇编代码中的第一个源
     代码行报告的行号。否则，源行信息（如果有的话）直接来自反汇编的代码
     对象。

     3.4 版新加入.

 -- 函式: dis.findlinestarts (code)

     此生成器函数使用代码对象 `code' 的 ‘co_firstlineno’ 和 ‘co_lnotab’
     属性来查找源代码中行开头的偏移量。它们生成为 ‘(offset, lineno)’ 对
     。请参阅 objects/lnotab_notes.txt(1) ，了解 ‘co_lnotab’ 格式以及如
     何解码它。

     3.6 版更變: 行号可能会减少。 以前，他们总是在增加。

 -- 函式: dis.findlabels (code)

     检测作为跳转目标的原始编译后字节码字符串 `code' 中的所有偏移量，并
     返回这些偏移量的列表。

 -- 函式: dis.stack_effect (opcode, oparg=None, *, jump=None)

     使用参数 `oparg' 计算 `opcode' 的堆栈效果。

     如果代码有一个跳转目标并且 `jump' 是 ‘True’ ，则 ‘drag_effect()’ 将
     返回跳转的堆栈效果。如果 `jump' 是 ‘False’ ，它将返回不跳跃的堆栈效
     果。如果 `jump' 是 ‘None’ （默认值），它将返回两种情况的最大堆栈效
     果。

     3.4 版新加入.

     3.8 版更變: 添加 `jump' 参数。

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/objects/lnotab_notes.txt


File: python.info,  Node: Python字节码说明,  Next: 操作码集合,  Prev: 分析函数,  Up: dis --- Python bytecode的反組譯器

5.32.12.3 Python字节码说明
..........................

*note get_instructions(): 923. 函数和 *note Bytecode: 924. 类提供字节码
指令的详细信息的 *note Instruction: 922. 实例：

 -- 類別: dis.Instruction

     字节码操作的详细信息

      -- Data: opcode

          操作的数字代码，对应于下面列出的操作码值和 *note 操作码集合:
          3ac0. 中的字节码值。

      -- Data: opname

          人类可读的操作名称

      -- Data: arg

          操作的数字参数（如果有的话），否则为 ‘None’

      -- Data: argval

          已解析的 arg 值（如果已知），否则与 arg 相同

      -- Data: argrepr

          人类可读的操作参数描述

      -- Data: offset

          在字节码序列中启动操作索引

      -- Data: starts_line

          行由此操作码（如果有）启动，否则为 ‘None’

      -- Data: is_jump_target

          如果其他代码跳到这里，则为 ‘True’ ，否则为 ‘False’

     3.4 版新加入.

Python编译器当前生成以下字节码指令。

`一般指令'

 -- Opcode: NOP

     什么都不做。 用作字节码优化器的占位符。

 -- Opcode: POP_TOP

     删除堆栈顶部（TOS）项。

 -- Opcode: ROT_TWO

     交换两个最顶层的堆栈项。

 -- Opcode: ROT_THREE

     将第二个和第三个堆栈项向上提升一个位置，顶项移动到位置三。

 -- Opcode: ROT_FOUR

     将第二个、第三个和第四个堆栈项向上提升一个位置，将顶项移动到第四个
     位置。

     3.8 版新加入.

 -- Opcode: DUP_TOP

     复制堆栈顶部的引用。

     3.2 版新加入.

 -- Opcode: DUP_TOP_TWO

     复制堆栈顶部的两个引用，使它们保持相同的顺序。

     3.2 版新加入.

`一元操作'

一元操作获取堆栈顶部元素，应用操作，并将结果推回堆栈。

 -- Opcode: UNARY_POSITIVE

     实现 ‘TOS = +TOS’ 。

 -- Opcode: UNARY_NEGATIVE

     实现 ‘TOS = -TOS’ 。

 -- Opcode: UNARY_NOT

     实现 ‘TOS = not TOS’ 。

 -- Opcode: UNARY_INVERT

     实现 ‘TOS = ~TOS’ 。

 -- Opcode: GET_ITER

     实现 ‘TOS = iter(TOS)’ 。

 -- Opcode: GET_YIELD_FROM_ITER

     如果 ‘TOS’ 是一个 *note generator iterator: 558. 或 *note
     coroutine: 18a. 对象则保持原样。否则实现 ‘TOS = iter(TOS)’ 。

     3.5 版新加入.

`二元操作'

二元操作从堆栈中删除堆栈顶部（TOS）和第二个最顶层堆栈项（TOS1）。 它们执
行操作，并将结果放回堆栈。

 -- Opcode: BINARY_POWER

     实现 ‘TOS = TOS1 ** TOS’ 。

 -- Opcode: BINARY_MULTIPLY

     实现 ‘TOS = TOS1 * TOS’ 。

 -- Opcode: BINARY_MATRIX_MULTIPLY

     实现 ‘TOS = TOS1 @ TOS’ 。

     3.5 版新加入.

 -- Opcode: BINARY_FLOOR_DIVIDE

     实现 ‘TOS = TOS1 // TOS’。

 -- Opcode: BINARY_TRUE_DIVIDE

     实现 ‘TOS = TOS1 / TOS’ 。

 -- Opcode: BINARY_MODULO

     实现 ‘TOS = TOS1 % TOS’ 。

 -- Opcode: BINARY_ADD

     实现 ‘TOS = TOS1 + TOS’ 。

 -- Opcode: BINARY_SUBTRACT

     实现 ‘TOS = TOS1 - TOS’ 。

 -- Opcode: BINARY_SUBSCR

     实现 ‘TOS = TOS1[TOS]’ 。

 -- Opcode: BINARY_LSHIFT

     实现 ‘TOS = TOS1 << TOS’ 。

 -- Opcode: BINARY_RSHIFT

     实现 ‘TOS = TOS1 >> TOS’ 。

 -- Opcode: BINARY_AND

     实现 ‘TOS = TOS1 & TOS’ 。

 -- Opcode: BINARY_XOR

     实现 ‘TOS = TOS1 ^ TOS’ 。

 -- Opcode: BINARY_OR

     实现 ‘TOS = TOS1 | TOS’ 。

`就地操作'

就地操作就像二元操作，因为它们删除了TOS和TOS1，并将结果推回到堆栈上，但
是当TOS1支持它时，操作就地完成，并且产生的TOS可能是（但不一定） 原来的
TOS1。

 -- Opcode: INPLACE_POWER

     就地实现 ‘TOS = TOS1 ** TOS’ 。

 -- Opcode: INPLACE_MULTIPLY

     就地实现 ‘TOS = TOS1 * TOS’ 。

 -- Opcode: INPLACE_MATRIX_MULTIPLY

     就地实现 ‘TOS = TOS1 @ TOS’ 。

     3.5 版新加入.

 -- Opcode: INPLACE_FLOOR_DIVIDE

     就地实现 ‘TOS = TOS1 // TOS’ 。

 -- Opcode: INPLACE_TRUE_DIVIDE

     就地实现 ‘TOS = TOS1 / TOS’ 。

 -- Opcode: INPLACE_MODULO

     就地实现 ‘TOS = TOS1 % TOS’ 。

 -- Opcode: INPLACE_ADD

     就地实现 ‘TOS = TOS1 + TOS’ 。

 -- Opcode: INPLACE_SUBTRACT

     就地实现 ‘TOS = TOS1 - TOS’ 。

 -- Opcode: INPLACE_LSHIFT

     就地实现 ‘TOS = TOS1 << TOS’ 。

 -- Opcode: INPLACE_RSHIFT

     就地实现 ‘TOS = TOS1 >> TOS’ 。

 -- Opcode: INPLACE_AND

     就地实现 ‘TOS = TOS1 & TOS’ 。

 -- Opcode: INPLACE_XOR

     就地实现 ‘TOS = TOS1 ^ TOS’ 。

 -- Opcode: INPLACE_OR

     就地实现 ‘TOS = TOS1 | TOS’ 。

 -- Opcode: STORE_SUBSCR

     实现 ‘TOS1[TOS] = TOS2’ 。

 -- Opcode: DELETE_SUBSCR

     实现 ‘del TOS1[TOS]’ 。

`协程操作码'

 -- Opcode: GET_AWAITABLE

     实现 ‘TOS = get_awaitable(TOS)’ ，其中 ‘get_awaitable(o)’ 返回 ‘o’
     如果 ‘o’ 是一个有 CO_ITERABLE_COROUTINE 标志的协程对象或生成器对象
     ，否则解析 ‘o.__await__’ 。

     3.5 版新加入.

 -- Opcode: GET_AITER

     实现 ‘TOS = TOS.__aiter__()’ 。

     3.5 版新加入.

     3.7 版更變: 已经不再支持从 ‘__aiter__’ 返回可等待对象。

 -- Opcode: GET_ANEXT

     实现 ‘PUSH(get_awaitable(TOS.__anext__()))’ 。参见 ‘GET_AWAITABLE’
     获取更多 ‘get_awaitable’ 的细节

     3.5 版新加入.

 -- Opcode: END_ASYNC_FOR

     终止一个 *note async for: 3fd. 循环。处理等待下一个项目时引发的异常
     。如果 TOS 是 *note StopAsyncIteration: 114a.， 从堆栈弹出7个值，并
     使用后三个恢复异常状态。否则，使用堆栈中的三个值重新引发异常。从块
     堆栈中删除异常处理程序块。

     3.8 版新加入.

 -- Opcode: BEFORE_ASYNC_WITH

     从栈顶对象解析 ‘__aenter__’ 和 ‘__aexit__’ 。将 ‘__aexit__’ 和
     ‘__aenter__()’ 的结果推入堆栈。

     3.5 版新加入.

 -- Opcode: SETUP_ASYNC_WITH

     创建一个新的帧对象。

     3.5 版新加入.

`其他操作码'

 -- Opcode: PRINT_EXPR

     实现交互模式的表达式语句。TOS从堆栈中被移除并打印。在非交互模式下，
     表达式语句以 *note POP_TOP: 3ac9. 终止。

 -- Opcode: SET_ADD (i)

     调用 ‘set.add(TOS1[-i], TOS)’ 。 用于实现集合推导。

 -- Opcode: LIST_APPEND (i)

     调用 ‘list.append(TOS1[-i], TOS)’。 用于实现列表推导式。

 -- Opcode: MAP_ADD (i)

     调用 ‘dict.__setitem__(TOS1[-i], TOS1, TOS)’ 。 用于实现字典推导。

     3.1 版新加入.

     3.8 版更變: 映射值为 TOS ，映射键为 TOS1 。之前，它们被颠倒了。

对于所有 *note SET_ADD: 3af7. 、 *note LIST_APPEND: 3af8. 和 *note
MAP_ADD: 3fe. 指令，当弹出添加的值或键值对时，容器对象保留在堆栈上，以便
它可用于循环的进一步迭代。

 -- Opcode: RETURN_VALUE

     返回 TOS 到函数的调用者。

 -- Opcode: YIELD_VALUE

     弹出 TOS 并从一个 *note generator: a83. 生成它。

 -- Opcode: YIELD_FROM

     弹出 TOS 并将其委托给它作为 *note generator: a83. 的子迭代器。

     3.3 版新加入.

 -- Opcode: SETUP_ANNOTATIONS

     检查 ‘__annotations__’ 是否在 ‘locals()’ 中定义，如果没有，它被设置
     为空 ‘dict’ 。只有在类或模块体静态地包含 *note variable
     annotations: 712. 时才会发出此操作码。

     3.6 版新加入.

 -- Opcode: IMPORT_STAR

     将所有不以 ‘'_'’ 开头的符号直接从模块 TOS 加载到局部命名空间。加载
     所有名称后弹出该模块。这个操作码实现了 ‘from module import *’ 。

 -- Opcode: POP_BLOCK

     从块堆栈中删除一个块。有一块堆栈，每帧用于表示 *note try: e37. 语句
     等。

 -- Opcode: POP_EXCEPT

     从块堆栈中删除一个块。 弹出的块必须是异常处理程序块，在进入 except
     处理程序时隐式创建。除了从帧堆栈弹出无关值之外，最后三个弹出值还用
     于恢复异常状态。

 -- Opcode: RERAISE

     重新引发当前位于栈顶的异常。

     3.9 版新加入.

 -- Opcode: WITH_EXCEPT_START

     调用堆栈中 7 号位置上的函数并附带栈顶位置的三项作为参数。 用来在
     *note with: 7da. 语句内发生异常时实现调用
     ‘context_manager.__exit__(*exc_info())’。

     3.9 版新加入.

 -- Opcode: LOAD_ASSERTION_ERROR

     将 *note AssertionError: 240. 推入栈顶。 由 *note assert: 23f. 语句
     使用。

     3.9 版新加入.

 -- Opcode: LOAD_BUILD_CLASS

     将 ‘builtins .__ build_class__()’ 推到堆栈上。它之后被 *note
     CALL_FUNCTION: 70e. 调用来构造一个类。

 -- Opcode: SETUP_WITH (delta)

     此操作码会在 with 代码块开始之前执行多个操作。 首先，它从上下文管理
     器加载 *note __exit__(): d5e. 并将其推入栈顶以供 *note
     WITH_EXCEPT_START: 3b00. 后续使用。 然后，调用 *note __enter__():
     d5d.，并推入一个指向 `delta' 的 finally 代码块。 最后，将调用
     ‘__enter__()’ 方法的结果推入栈顶。 下一个操作码将忽略它 (*note
     POP_TOP: 3ac9.)，或将其存储在一个或多个变量 (*note STORE_FAST:
     3b03, *note STORE_NAME: 3b04. 或 *note UNPACK_SEQUENCE: 3b05.) 中。

     3.2 版新加入.

以下所有操作码均使用其参数。

 -- Opcode: STORE_NAME (namei)

     实现 ‘name = TOS’。 `namei' 是 `name' 在代码对象的 ‘co_names’ 属性
     中的索引。 在可能的情况下，编译器会尝试使用 *note STORE_FAST: 3b03.
     或 *note STORE_GLOBAL: 3b06.。

 -- Opcode: DELETE_NAME (namei)

     实现 ‘del name’ ，其中 `namei' 是代码对象的 ‘co_names’ 属性的索引。

 -- Opcode: UNPACK_SEQUENCE (count)

     将 TOS 解包为 `count' 个单独的值，它们将按从右至左的顺序被放入堆栈
     。

 -- Opcode: UNPACK_EX (counts)

     实现使用带星号的目标进行赋值：将 TOS 中的可迭代对象解包为单独的值，
     其中值的总数可以小于可迭代对象中的项数：新值之一将是由所有剩余项构
     成的列表。

     `counts' 的低字节是列表值之前的值的数量，`counts' 中的高字节则是之
     后的值的数量。 结果值会按从右至左的顺序入栈。

 -- Opcode: STORE_ATTR (namei)

     实现 ‘TOS.name = TOS1’，其中 `namei' 是 name 在 ‘co_names’ 中的索引
     号。

 -- Opcode: DELETE_ATTR (namei)

     实现 ‘del TOS.name’，使用 `namei' 作为 ‘co_names’ 中的索引号。

 -- Opcode: STORE_GLOBAL (namei)

     类似于 *note STORE_NAME: 3b04. 但会将 name 存储为全局变量。

 -- Opcode: DELETE_GLOBAL (namei)

     类似于 *note DELETE_NAME: 3b07. 但会删除一个全局变量。

 -- Opcode: LOAD_CONST (consti)

     将 ‘co_consts[consti]’ 推入栈顶。

 -- Opcode: LOAD_NAME (namei)

     将与 ‘co_names[namei]’ 相关联的值推入栈顶。

 -- Opcode: BUILD_TUPLE (count)

     创建一个使用了来自栈的 `count' 个项的元组，并将结果元组推入栈顶。

 -- Opcode: BUILD_LIST (count)

     类似于 *note BUILD_TUPLE: 3b0e. 但会创建一个列表。

 -- Opcode: BUILD_SET (count)

     类似于 *note BUILD_TUPLE: 3b0e. 但会创建一个集合。

 -- Opcode: BUILD_MAP (count)

     将一个新字典对象推入栈顶。 弹出 ‘2 * count’ 项使得字典包含 `count'
     个条目: ‘{..., TOS3: TOS2, TOS1: TOS}’。

     3.5 版更變: 字典是根据栈中的项创建而不是创建一个预设大小包含
     `count' 项的空字典。

 -- Opcode: BUILD_CONST_KEY_MAP (count)

     *note BUILD_MAP: 3b11. 版本专用于常量键。 弹出的栈顶元素包含一个由
     键构成的元组，然后从 ‘TOS1’ 开始从构建字典的值中弹出 `count' 个值。

     3.6 版新加入.

 -- Opcode: BUILD_STRING (count)

     拼接 `count' 个来自栈的字符串并将结果字符串推入栈顶。

     3.6 版新加入.

 -- Opcode: LIST_TO_TUPLE

     从堆栈中弹出一个列表并推入一个包含相同值的元组。

     3.9 版新加入.

 -- Opcode: LIST_EXTEND (i)

     调用 ‘list.extend(TOS1[-i], TOS)’。 用于构建列表。

     3.9 版新加入.

 -- Opcode: SET_UPDATE (i)

     调用 ‘set.update(TOS1[-i], TOS)’。 用于构建集合。

     3.9 版新加入.

 -- Opcode: DICT_UPDATE (i)

     调用 ‘dict.update(TOS1[-i], TOS)’。 用于构建字典。

     3.9 版新加入.

 -- Opcode: DICT_MERGE

     类似于 *note DICT_UPDATE: 3b15. 但对于重复的键会引发异常。

     3.9 版新加入.

 -- Opcode: LOAD_ATTR (namei)

     将 TOS 替换为 ‘getattr(TOS, co_names[namei])’。

 -- Opcode: COMPARE_OP (opname)

     执行布尔运算操作。 操作名称可在 ‘cmp_op[opname]’ 中找到。

 -- Opcode: IS_OP (invert)

     执行 ‘is’ 比较，或者如果 ‘invert’ 为 1 则执行 ‘is not’。

     3.9 版新加入.

 -- Opcode: CONTAINS_OP (invert)

     执行 ‘in’ 比较，或者如果 ‘invert’ 为 1 则执行 ‘not in’。

     3.9 版新加入.

 -- Opcode: IMPORT_NAME (namei)

     导入模块 ‘co_names[namei]’。 会弹出 TOS 和 TOS1 以提供 `fromlist' 和
     `level' 参数给 *note __import__(): 16b.。 模块对象会被推入栈顶。 当
     前命名空间不受影响：对于一条标准 import 语句，会执行后续的 *note
     STORE_FAST: 3b03. 指令来修改命名空间。

 -- Opcode: IMPORT_FROM (namei)

     从在 TOS 内找到的模块中加载属性 ‘co_names[namei]’。 结果对象会被推
     入栈顶，以便由后续的 *note STORE_FAST: 3b03. 指令来保存。

 -- Opcode: JUMP_FORWARD (delta)

     将字节码计数器的值增加 `delta'。

 -- Opcode: POP_JUMP_IF_TRUE (target)

     如果 TOS 为真值，则将字节码计数器的值设为 `target'。 TOS 会被弹出。

     3.1 版新加入.

 -- Opcode: POP_JUMP_IF_FALSE (target)

     如果 TOS 为假值，则将字节码计数器的值设为 `target'。 TOS 会被弹出。

     3.1 版新加入.

 -- Opcode: JUMP_IF_NOT_EXC_MATCH (target)

     检测堆栈中的第二个值是否为匹配 TOS 的异常，如果不是则会跳转。 从堆
     栈中弹出两个值。

     3.9 版新加入.

 -- Opcode: JUMP_IF_TRUE_OR_POP (target)

     如果 TOS 为真值，则将字节码计数器的值设为 `target' 并将 TOS 留在栈
     顶。 否则（如 TOS 为假值），TOS 会被弹出。

     3.1 版新加入.

 -- Opcode: JUMP_IF_FALSE_OR_POP (target)

     如果 TOS 为假值，则将字节码计数器的值设为 `target' 并将 TOS 留在栈
     顶。 否则（如 TOS 为真值），TOS 会被弹出。

     3.1 版新加入.

 -- Opcode: JUMP_ABSOLUTE (target)

     将字节码计数器的值设为 `target'。

 -- Opcode: FOR_ITER (delta)

     TOS 是一个 *note iterator: 1171.。 请调用其 *note __next__(): d2c.
     方法。 如果此操作产生了一个新值，则将其推入栈顶（将迭代器留在其下方
     ）。 如果迭代器提示已耗尽，TOS 会被弹出，并且字节码计数器将增加
     `delta'。

 -- Opcode: LOAD_GLOBAL (namei)

     加载名称为 ‘co_names[namei]’ 的全局对象推入栈顶。

 -- Opcode: SETUP_FINALLY (delta)

     将一个来自 try-finally 或 try-except 子句的 try 代码块推入代码块栈
     顶。 相对 finally 代码块或第一个 except 代码块 `delta' 个点数。

 -- Opcode: LOAD_FAST (var_num)

     将指向局部对象 ‘co_varnames[var_num]’ 的引用推入栈顶。

 -- Opcode: STORE_FAST (var_num)

     将 TOS 存放到局部对象 ‘co_varnames[var_num]’。

 -- Opcode: DELETE_FAST (var_num)

     移除局部对象 ‘co_varnames[var_num]’。

 -- Opcode: LOAD_CLOSURE (i)

     将一个包含在单元的第 `i' 个空位中的对单元的引用推入栈顶并释放可用的
     存储空间。 如果 `i' 小于 `co_cellvars' 的长度则变量的名称为
     ‘co_cellvars[i]’。 否则为 ‘co_freevars[i - len(co_cellvars)]’。

 -- Opcode: LOAD_DEREF (i)

     加载包含在单元的第 `i' 个空位中的单元并释放可用的存储空间。 将一个
     对单元所包含对象的引用推入栈顶。

 -- Opcode: LOAD_CLASSDEREF (i)

     类似于 *note LOAD_DEREF: 3b29. 但在查询单元之前会首先检查局部对象字
     典。 这被用于加载类语句体中的自由变量。

     3.4 版新加入.

 -- Opcode: STORE_DEREF (i)

     将 TOS 存放到包含在单元的第 `i' 个空位中的单元内并释放可用存储空间
     。

 -- Opcode: DELETE_DEREF (i)

     清空包含在单元的第 `i' 个空位中的单元并释放可用存储空间。 被用于
     *note del: 13a2. 语句。

     3.2 版新加入.

 -- Opcode: RAISE_VARARGS (argc)

     使用 ‘raise’ 语句的 3 种形式之一引发异常，具体形式取决于 `argc' 的
     值：

        * 0: ‘raise’ (重新引发之前的异常)

        * 1: ‘raise TOS’ (在 ‘TOS’ 上引发异常实例或类型)

        * 2: ‘raise TOS1 from TOS’ (在 ‘TOS1’ 上引发异常实例或类型并将
          ‘__cause__’ 设为 ‘TOS’)

 -- Opcode: CALL_FUNCTION (argc)

     调用一个可调用对象并传入位置参数。 `argc' 指明位置参数的数量。 栈顶
     包含位置参数，其中最右边的参数在最顶端。 在参数之下是一个待调用的可
     调用对象。 ‘CALL_FUNCTION’ 会从栈中弹出所有参数以及可调用对象，附带
     这些参数调用该可调用对象，并将可调用对象所返回的返回值推入栈顶。

     3.6 版更變: 此操作码仅用于附带位置参数的调用。

 -- Opcode: CALL_FUNCTION_KW (argc)

     调用一个可调用对象并传入位置参数（如果有的话）和关键字参数。 `argc'
     指明位置参数和关键字参数的总数量。 栈顶元素包含一个关键字参数名称的
     元组，名称必须为字符串。 在元组之下是与元组顺序相对应的关键字参数值
     。 在它之下则是位置参数，其中最右边的参数在最顶端。 在参数之下是要
     调用的可调用对象。 ‘CALL_FUNCTION_KW’ 会从栈中弹出所有参数及可调用
     对象，附带这些参数调用该可调用对象，并将可调用对象所返回的返回值推
     入栈顶。

     3.6 版更變: 关键字参数会被打包为一个元组而非字典，`argc' 指明参数的
     总数量。

 -- Opcode: CALL_FUNCTION_EX (flags)

     调用一个可调用对象并附带位置参数和关键字参数变量集合。 如果设置了
     `flags' 的最低位，则栈顶包含一个由额外关键字参数组成的映射对象。 在
     调用该可调用对象之前，映射对象和可迭代对象会被分别“解包”并将它们的
     内容分别作为关键字参数和位置参数传入。 ‘CALL_FUNCTION_EX’ 会中栈中
     弹出所有参数及可调用对象，附带这些参数调用该可调用对象，并将可调用
     对象所返回的返回值推入栈顶。

     3.6 版新加入.

 -- Opcode: LOAD_METHOD (namei)

     从 TOS 对象加载一个名为 ‘co_names[namei]’ 的方法。 TOS 将被弹出。 此
     字节码可区分两种情况：如果 TOS 有一个名称正确的方法，字节码会将未绑
     定方法和 TOS 推入栈顶。 TOS 将在调用未绑定方法时被用作 *note
     CALL_METHOD: 5a8. 的第一个参数 (‘self’)。 否则会将 ‘NULL’ 和属性查
     找所返回的对象推入栈顶。

     3.7 版新加入.

 -- Opcode: CALL_METHOD (argc)

     调用一个方法。 `argc' 是位置参数的数量。 关键字参数不受支持。 此操
     作码被设计用于配合 *note LOAD_METHOD: 5a7. 使用。 位置参数放在栈顶
     。 在它们之下放在栈中的是由 *note LOAD_METHOD: 5a7. 所描述的两个条
     目（或者是 ‘self’ 和一个未绑定方法对象，或者是 ‘NULL’ 和一个任意可
     调用对象）。 它们会被全部弹出并将返回值推入栈顶。

     3.7 版新加入.

 -- Opcode: MAKE_FUNCTION (flags)

     将一个新函数对象推入栈顶。 从底端到顶端，如果参数带有指定的旗标值则
     所使用的栈必须由这些值组成。

        * ‘0x01’ 一个默认值的元组，用于按位置排序的仅限位置形参以及位置
          或关键字形参

        * ‘0x02’ 一个仅限关键字形参的默认值的字典

        * ‘0x04’ 是一个标注字典

        * ‘0x08’ 一个包含用于自由变量的单元的元组，生成一个闭包

        * 与函数相关联的代码 (在 TOS1)

        * 函数的 *note qualified name: 155c. (在 TOS)

 -- Opcode: BUILD_SLICE (argc)

     将一个切片对象推入栈顶。 `argc' 必须为 2 或 3。 如果为 2，则推入
     ‘slice(TOS1, TOS)’；如果为 3，则推入 ‘slice(TOS2, TOS1, TOS)’。 请
     参阅 *note slice(): ec8. 内置函数了解详细信息。

 -- Opcode: EXTENDED_ARG (ext)

     为任意带有大到无法放入默认的单字节的参数的操作码添加前缀。 `ext' 存
     放一个附加字节作为参数中的高比特位。 对于每个操作码，最多允许三个
     ‘EXTENDED_ARG’ 前缀，构成两字节到三字节的参数。

 -- Opcode: FORMAT_VALUE (flags)

     用于实现格式化字面值字符串（f-字符串）。 从栈中弹出一个可选的
     `fmt_spec'，然后是一个必须的 `value'。 `flags' 的解读方式如下：

        * ‘(flags & 0x03) == 0x00’: `value' 按原样格式化。

        * ‘(flags & 0x03) == 0x01’: 在格式化 `value' 之前调用其 *note
          str(): 205.。

        * ‘(flags & 0x03) == 0x02’: 在格式化 `value' 之前调用其 *note
          repr(): 8b9.。

        * ‘(flags & 0x03) == 0x03’: 在格式化 `value' 之前调用其 *note
          ascii(): e11.。

        * ‘(flags & 0x04) == 0x04’: 从栈中弹出 `fmt_spec' 并使用它，否则
          使用空的 `fmt_spec'。

     使用 ‘PyObject_Format()’ 执行格式化。 结果会被推入栈顶。

     3.6 版新加入.

 -- Opcode: HAVE_ARGUMENT

     这不是一个真正的操作码。 它用于标明使用参数和不使用参数的操作码 (分
     别为 ‘< HAVE_ARGUMENT’ 和 ‘>= HAVE_ARGUMENT’) 之间的分隔线。

     3.6 版更變: 现在每条指令都带有参数，但操作码 ‘< HAVE_ARGUMENT’ 会忽
     略它。 之前仅限操作码 ‘>= HAVE_ARGUMENT’ 带有参数。


File: python.info,  Node: 操作码集合,  Prev: Python字节码说明,  Up: dis --- Python bytecode的反組譯器

5.32.12.4 操作码集合
....................

提供这些集合用于字节码指令的自动内省：

 -- Data: dis.opname

     操作名称的序列，可使用字节码来索引。

 -- Data: dis.opmap

     映射操作名称到字节码的字典

 -- Data: dis.cmp_op

     所有比较操作名称的序列。

 -- Data: dis.hasconst

     访问常量的字节码序列。

 -- Data: dis.hasfree

     访问自由变量的字节码序列（请注意这里所说的‘自由’是指在当前作用域中
     被内部作用域所引用的名称，或在外部作用域中被此作用域所引用的名称。
     它 `并不' 包括对全局或内置作用域的引用）。

 -- Data: dis.hasname

     按名称访问属性的字节码序列。

 -- Data: dis.hasjrel

     具有相对跳转目标的字节码序列。

 -- Data: dis.hasjabs

     具有绝对跳转目标的字节码序列。

 -- Data: dis.haslocal

     访问局部变量的字节码序列。

 -- Data: dis.hascompare

     布尔运算的字节码序列。


File: python.info,  Node: pickletools --- pickle 开发者工具集,  Prev: dis --- Python bytecode的反組譯器,  Up: Python 语言服务

5.32.13 ‘pickletools’ — pickle 开发者工具集
-------------------------------------------

`源代码:' Lib/pickletools.py(1)

__________________________________________________________________

此模块包含与 *note pickle: ca. 模块内部细节有关的多个常量，一些关于具体
实现的详细注释，以及一些能够分析封存数据的有用函数。 此模块的内容对需要
操作 *note pickle: ca. 的 Python 核心开发者来说很有用处；*note pickle:
ca. 的一般用户则可能会感觉 *note pickletools: cb. 模块与他们无关。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/pickletools.py


File: python.info,  Node: 命令行语法<2>,  Next: 编程接口<2>,  Up: pickletools --- pickle 开发者工具集

5.32.13.1 命令行语法
....................

3.2 版新加入.

当从命令行发起调用时，‘python -m pickletools’ 将对一个或更多 pickle 文件
的内容进行拆解。 请注意如果你查看 pickle 中保存的 Python 对象而非 pickle
格式的细节，你可能需要改用 ‘-m pickle’。 但是，当你想检查的 pickle 文件
来自某个不受信任的源时，‘-m pickletools’ 是更安全的选择，因为它不会执行
pickle 字节码。

例如，对于一个封存在文件 ‘x.pickle’ 中的元组 ‘(1, 2)’:

     $ 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

* Menu:

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


File: python.info,  Node: 命令行选项<5>,  Up: 命令行语法<2>

5.32.13.2 命令行选项
....................

 -- 程式選項: -a, --annotate

     使用简短的操作码描述来标注每一行。

 -- 程式選項: -o, --output=<file>

     输出应当写入到的文件名称。

 -- 程式選項: -l, --indentlevel=<num>

     一个新的 MARK 层级所需缩进的空格数。

 -- 程式選項: -m, --memo

     当反汇编多个对象时，保留各个反汇编的备忘记录。

 -- 程式選項: -p, --preamble=<preamble>

     当指定一个以上的 pickle 文件时，在每次反汇编之前打印给定的前言。


File: python.info,  Node: 编程接口<2>,  Prev: 命令行语法<2>,  Up: pickletools --- pickle 开发者工具集

5.32.13.3 编程接口
..................

 -- 函式: pickletools.dis (pickle, out=None, memo=None, indentlevel=4,
          annotate=0)

     将 pickle 的符号化反汇编数据输出到文件类对象 `out'，默认为
     ‘sys.stdout’。 `pickle' 可以是一个字符串或一个文件类对象。 `memo' 可
     以是一个将被用作 pickle 的备忘记录的 Python 字典；它可被用来对由同
     一封存器创建的多个封存对象执行反汇编。 由 ‘MARK’ 操作码指明的每个连
     续级别将会缩进 `indentlevel' 个空格。 如果为 `annotate' 指定了一个
     非零值，则输出中的每个操作码将以一个简短描述来标注。 `annotate' 的
     值会被用作标注所应开始的列的提示。

     3.2 版新加入: `annotate' 参数。

 -- 函式: pickletools.genops (pickle)

     提供包含 pickle 中所有操作码的 *note iterator: 1171.，返回一个
     ‘(opcode, arg, pos)’ 三元组的序列。 `opcode' 是 ‘OpcodeInfo’ 类的一
     个实例；`arg' 是 Python 对象形式的 opcode 参数的已解码值；`pos' 是
     opcode 所在的位置。 `pickle' 可以是一个字符串或一个文件类对象。

 -- 函式: pickletools.optimize (picklestring)

     在消除未使用的 ‘PUT’ 操作码之后返回一个新的等效 pickle 字符串。 优
     化后的 pickle 将更为简短，耗费更为的传输时间，要求更少的存储空间并
     能更高效地解封。


File: python.info,  Node: 杂项服务,  Next: Windows系统相关模块,  Prev: Python 语言服务,  Up: Python 標準函式庫 Standard Library

5.33 杂项服务
=============

本章中介绍的模块提供了所有 Python 版本中提供的各种杂项服务。 这是一个概
述：

* Menu:

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


File: python.info,  Node: formatter --- 通用格式化输出,  Up: 杂项服务

5.33.1 ‘formatter’ — 通用格式化输出
-----------------------------------

3.4 版後已棄用: 因为被使用的次数很少，此格式化模块已经被弃用了。

__________________________________________________________________

This module supports two interface definitions, each with multiple
implementations: The `formatter' interface, and the `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::


File: python.info,  Node: The Formatter Interface,  Next: Formatter Implementations,  Up: formatter --- 通用格式化输出

5.33.1.1 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:

 -- Data: formatter.AS_IS

     Value which can be used in the font specification passed to the
     ‘push_font()’ method described below, or as the new value to any
     other ‘push_property()’ method.  Pushing the ‘AS_IS’ value allows
     the corresponding ‘pop_property()’ method to be called without
     having to track whether the property was changed.

The following attributes are defined for formatter instance objects:

 -- 屬性: formatter.writer

     The writer instance with which the formatter interacts.

 -- 成員函式: formatter.end_paragraph (blanklines)

     Close any open paragraphs and insert at least `blanklines' before
     the next paragraph.

 -- 成員函式: formatter.add_line_break ()

     Add a hard line break if one does not already exist.  This does not
     break the logical paragraph.

 -- 成員函式: 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 ‘send_line_break()’ method.

 -- 成員函式: formatter.add_flowing_data (data)

     Provide data which should be formatted with collapsed whitespace.
     Whitespace from preceding and successive calls to *note
     add_flowing_data(): 3b52. 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.

 -- 成員函式: 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 `data'.

 -- 成員函式: 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 `format' value is a string, it is
     interpreted as a format specification for `counter', which should
     be an integer.  The result of this formatting becomes the value of
     the label; if `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 ‘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 ‘'1'’ represents the counter value
     formatter as an Arabic number, the characters ‘'A'’ and ‘'a'’
     represent alphabetic representations of the counter value in upper
     and lower case, respectively, and ‘'I'’ and ‘'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.

 -- 成員函式: formatter.flush_softspace ()

     Send any pending whitespace buffered from a previous call to *note
     add_flowing_data(): 3b52. to the associated writer object.  This
     should be called before any direct manipulation of the writer
     object.

 -- 成員函式: formatter.push_alignment (align)

     Push a new alignment setting onto the alignment stack.  This may be
     *note AS_IS: 3b4d. if no change is desired.  If the alignment value
     is changed from the previous setting, the writer’s
     ‘new_alignment()’ method is called with the `align' value.

 -- 成員函式: formatter.pop_alignment ()

     Restore the previous alignment.

 -- 成員函式: formatter.push_font ((size, italic, bold, teletype))

     Change some or all font properties of the writer object.
     Properties which are not set to *note AS_IS: 3b4d. are set to the
     values passed in while others are maintained at their current
     settings.  The writer’s ‘new_font()’ method is called with the
     fully resolved font specification.

 -- 成員函式: formatter.pop_font ()

     Restore the previous font.

 -- 成員函式: formatter.push_margin (margin)

     Increase the number of left margin indentations by one, associating
     the logical tag `margin' with the new indentation.  The initial
     margin level is ‘0’.  Changed values of the logical tag must be
     true values; false values other than *note AS_IS: 3b4d. are not
     sufficient to change the margin.

 -- 成員函式: formatter.pop_margin ()

     Restore the previous margin.

 -- 成員函式: 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 *note AS_IS: 3b4d. values, is passed to the
     writer’s ‘new_styles()’ method.

 -- 成員函式: formatter.pop_style (n=1)

     Pop the last `n' style specifications passed to *note push_style():
     3b5c.  A tuple representing the revised stack, including *note
     AS_IS: 3b4d. values, is passed to the writer’s ‘new_styles()’
     method.

 -- 成員函式: formatter.set_spacing (spacing)

     Set the spacing style for the writer.

 -- 成員函式: 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 `flag' argument can be set
     to false if the writer manipulations produced a hard line break at
     the end of the output.


File: python.info,  Node: Formatter Implementations,  Next: The Writer Interface,  Prev: The Formatter Interface,  Up: formatter --- 通用格式化输出

5.33.1.2 Formatter Implementations
..................................

Two implementations of formatter objects are provided by this module.
Most applications may use one of these classes without modification or
subclassing.

 -- 類別: formatter.NullFormatter (writer=None)

     A formatter which does nothing.  If `writer' is omitted, a *note
     NullWriter: 3b63. instance is created.  No methods of the writer
     are called by *note NullFormatter: 3b62. instances.
     Implementations should inherit from this class if implementing a
     writer interface but don’t need to inherit any implementation.

 -- 類別: 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.


File: python.info,  Node: The Writer Interface,  Next: Writer Implementations,  Prev: Formatter Implementations,  Up: formatter --- 通用格式化输出

5.33.1.3 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 *note AbstractFormatter: 3b64. class
as a formatter, the writer must typically be provided by the
application.

 -- 成員函式: writer.flush ()

     Flush any buffered output or device control events.

 -- 成員函式: writer.new_alignment (align)

     Set the alignment style.  The `align' value can be any object, but
     by convention is a string or ‘None’, where ‘None’ indicates that
     the writer’s "preferred" alignment should be used.  Conventional
     `align' values are ‘'left'’, ‘'center'’, ‘'right'’, and
     ‘'justify'’.

 -- 成員函式: writer.new_font (font)

     Set the font style.  The value of `font' will be ‘None’, indicating
     that the device’s default font should be used, or a tuple of the
     form ‘(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
     `italic', `bold', and `teletype' values are Boolean values
     specifying which of those font attributes should be used.

 -- 成員函式: writer.new_margin (margin, level)

     Set the margin level to the integer `level' and the logical tag to
     `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 `level'.

 -- 成員函式: writer.new_spacing (spacing)

     Set the spacing style to `spacing'.

 -- 成員函式: writer.new_styles (styles)

     Set additional styles.  The `styles' value is a tuple of arbitrary
     values; the value *note AS_IS: 3b4d. should be ignored.  The
     `styles' tuple may be interpreted either as a set or as a stack
     depending on the requirements of the application and writer
     implementation.

 -- 成員函式: writer.send_line_break ()

     Break the current line.

 -- 成員函式: writer.send_paragraph (blankline)

     Produce a paragraph separation of at least `blankline' blank lines,
     or the equivalent.  The `blankline' value will be an integer.  Note
     that the implementation will receive a call to *note
     send_line_break(): 3b6d. 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.

 -- 成員函式: 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 *note
     send_line_break(): 3b6d.

 -- 成員函式: 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.

 -- 成員函式: 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
     ‘send_formatted_data()’ interface.

 -- 成員函式: writer.send_label_data (data)

     Set `data' to the left of the current left margin, if possible.
     The value of `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.


File: python.info,  Node: Writer Implementations,  Prev: The Writer Interface,  Up: formatter --- 通用格式化输出

5.33.1.4 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 *note NullWriter: 3b63. class.

 -- 類別: 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.

 -- 類別: 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.

 -- 類別: formatter.DumbWriter (file=None, maxcol=72)

     Simple writer class which writes output on the *note file object:
     c14. passed in as `file' or, if `file' is omitted, on standard
     output.  The output is simply word-wrapped to the number of columns
     specified by `maxcol'.  This class is suitable for reflowing a
     sequence of paragraphs.


File: python.info,  Node: Windows系统相关模块,  Next: Unix 专有服务,  Prev: 杂项服务,  Up: Python 標準函式庫 Standard Library

5.34 Windows系统相关模块
========================

本章节叙述的模块只在 Windows 平台上可用。

* Menu:

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


File: python.info,  Node: msilib --- Read and write Microsoft Installer files,  Next: msvcrt --- 来自 MS VC++ 运行时的有用例程,  Up: Windows系统相关模块

5.34.1 ‘msilib’ — Read and write Microsoft Installer files
----------------------------------------------------------

`Source code:' Lib/msilib/__init__.py(1)

__________________________________________________________________

The *note msilib: b5. supports the creation of Microsoft Installer
(‘.msi’) files.  Because these files often contain an embedded "cabinet"
file (‘.cab’), it also exposes an API to create CAB files.  Support for
reading ‘.cab’ files is currently not implemented; read support for the
‘.msi’ database is possible.

This package aims to provide complete access to all tables in an ‘.msi’
file, therefore, it is a fairly low-level API. Two primary applications
of this package are the *note distutils: 38. command ‘bdist_msi’, and
the creation of Python installer package itself (although that currently
uses a different version of ‘msilib’).

The package contents can be roughly split into four parts: low-level CAB
routines, low-level MSI routines, higher-level MSI routines, and
standard table structures.

 -- 函式: msilib.FCICreate (cabname, files)

     Create a new CAB file named `cabname'.  `files' must be a list of
     tuples, each containing the name of the file on disk, and the name
     of the file inside the CAB file.

     The files are added to the CAB file in the order they appear in the
     list.  All files are added into a single CAB file, using the MSZIP
     compression algorithm.

     Callbacks to Python for the various steps of MSI creation are
     currently not exposed.

 -- 函式: msilib.UuidCreate ()

     Return the string representation of a new unique identifier.  This
     wraps the Windows API functions ‘UuidCreate()’ and
     ‘UuidToString()’.

 -- 函式: msilib.OpenDatabase (path, persist)

     Return a new database object by calling MsiOpenDatabase.  `path' is
     the file name of the MSI file; `persist' can be one of the
     constants ‘MSIDBOPEN_CREATEDIRECT’, ‘MSIDBOPEN_CREATE’,
     ‘MSIDBOPEN_DIRECT’, ‘MSIDBOPEN_READONLY’, or ‘MSIDBOPEN_TRANSACT’,
     and may include the flag ‘MSIDBOPEN_PATCHFILE’.  See the Microsoft
     documentation for the meaning of these flags; depending on the
     flags, an existing database is opened, or a new one created.

 -- 函式: msilib.CreateRecord (count)

     Return a new record object by calling ‘MSICreateRecord()’.  `count'
     is the number of fields of the record.

 -- 函式: msilib.init_database (name, schema, ProductName, ProductCode,
          ProductVersion, Manufacturer)

     Create and return a new database `name', initialize it with
     `schema', and set the properties `ProductName', `ProductCode',
     `ProductVersion', and `Manufacturer'.

     `schema' must be a module object containing ‘tables’ and
     ‘_Validation_records’ attributes; typically, *note msilib.schema:
     3b7e. should be used.

     The database will contain just the schema and the validation
     records when this function returns.

 -- 函式: msilib.add_data (database, table, records)

     Add all `records' to the table named `table' in `database'.

     The `table' argument must be one of the predefined tables in the
     MSI schema, e.g.  ‘'Feature'’, ‘'File'’, ‘'Component'’, ‘'Dialog'’,
     ‘'Control'’, etc.

     `records' should be a list of tuples, each one containing all
     fields of a record according to the schema of the table.  For
     optional fields, ‘None’ can be passed.

     Field values can be ints, strings, or instances of the Binary
     class.

 -- 類別: msilib.Binary (filename)

     Represents entries in the Binary table; inserting such an object
     using *note add_data(): 3b7f. reads the file named `filename' into
     the table.

 -- 函式: msilib.add_tables (database, module)

     Add all table content from `module' to `database'.  `module' must
     contain an attribute `tables' listing all tables for which content
     should be added, and one attribute per table that has the actual
     content.

     This is typically used to install the sequence tables.

 -- 函式: msilib.add_stream (database, name, path)

     Add the file `path' into the ‘_Stream’ table of `database', with
     the stream name `name'.

 -- 函式: 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).

也參考
......

FCICreate(2) UuidCreate(3) UuidToString(4)

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/msilib/__init__.py

   (2) https://msdn.microsoft.com/en-us/library/bb432265.aspx

   (3) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa379205.aspx

   (4) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa379352.aspx


File: python.info,  Node: Database Objects,  Next: View Objects,  Up: msilib --- Read and write Microsoft Installer files

5.34.1.1 Database Objects
.........................

 -- 成員函式: Database.OpenView (sql)

     Return a view object, by calling ‘MSIDatabaseOpenView()’.  `sql' is
     the SQL statement to execute.

 -- 成員函式: Database.Commit ()

     Commit the changes pending in the current transaction, by calling
     ‘MSIDatabaseCommit()’.

 -- 成員函式: Database.GetSummaryInformation (count)

     Return a new summary information object, by calling
     ‘MsiGetSummaryInformation()’.  `count' is the maximum number of
     updated values.

 -- 成員函式: Database.Close ()

     Close the database object, through ‘MsiCloseHandle()’.

     3.7 版新加入.

也參考
......

MSIDatabaseOpenView(1) MSIDatabaseCommit(2) MSIGetSummaryInformation(3)
MsiCloseHandle(4)

   ---------- Footnotes ----------

   (1) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370082.aspx

   (2) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370075.aspx

   (3) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370301.aspx

   (4) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370067.aspx


File: python.info,  Node: View Objects,  Next: Summary Information Objects,  Prev: Database Objects,  Up: msilib --- Read and write Microsoft Installer files

5.34.1.2 View Objects
.....................

 -- 成員函式: View.Execute (params)

     Execute the SQL query of the view, through ‘MSIViewExecute()’.  If
     `params' is not ‘None’, it is a record describing actual values of
     the parameter tokens in the query.

 -- 成員函式: View.GetColumnInfo (kind)

     Return a record describing the columns of the view, through calling
     ‘MsiViewGetColumnInfo()’.  `kind' can be either ‘MSICOLINFO_NAMES’
     or ‘MSICOLINFO_TYPES’.

 -- 成員函式: View.Fetch ()

     Return a result record of the query, through calling
     ‘MsiViewFetch()’.

 -- 成員函式: View.Modify (kind, data)

     Modify the view, by calling ‘MsiViewModify()’.  `kind' can be one
     of ‘MSIMODIFY_SEEK’, ‘MSIMODIFY_REFRESH’, ‘MSIMODIFY_INSERT’,
     ‘MSIMODIFY_UPDATE’, ‘MSIMODIFY_ASSIGN’, ‘MSIMODIFY_REPLACE’,
     ‘MSIMODIFY_MERGE’, ‘MSIMODIFY_DELETE’,
     ‘MSIMODIFY_INSERT_TEMPORARY’, ‘MSIMODIFY_VALIDATE’,
     ‘MSIMODIFY_VALIDATE_NEW’, ‘MSIMODIFY_VALIDATE_FIELD’, or
     ‘MSIMODIFY_VALIDATE_DELETE’.

     `data' must be a record describing the new data.

 -- 成員函式: View.Close ()

     Close the view, through ‘MsiViewClose()’.

也參考
......

MsiViewExecute(1) MSIViewGetColumnInfo(2) MsiViewFetch(3)
MsiViewModify(4) MsiViewClose(5)

   ---------- Footnotes ----------

   (1) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370513.aspx

   (2) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370516.aspx

   (3) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370514.aspx

   (4) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370519.aspx

   (5) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370510.aspx


File: python.info,  Node: Summary Information Objects,  Next: Record Objects,  Prev: View Objects,  Up: msilib --- Read and write Microsoft Installer files

5.34.1.3 Summary Information Objects
....................................

 -- 成員函式: SummaryInformation.GetProperty (field)

     Return a property of the summary, through
     ‘MsiSummaryInfoGetProperty()’.  `field' is the name of the
     property, and can be one of the constants ‘PID_CODEPAGE’,
     ‘PID_TITLE’, ‘PID_SUBJECT’, ‘PID_AUTHOR’, ‘PID_KEYWORDS’,
     ‘PID_COMMENTS’, ‘PID_TEMPLATE’, ‘PID_LASTAUTHOR’, ‘PID_REVNUMBER’,
     ‘PID_LASTPRINTED’, ‘PID_CREATE_DTM’, ‘PID_LASTSAVE_DTM’,
     ‘PID_PAGECOUNT’, ‘PID_WORDCOUNT’, ‘PID_CHARCOUNT’, ‘PID_APPNAME’,
     or ‘PID_SECURITY’.

 -- 成員函式: SummaryInformation.GetPropertyCount ()

     Return the number of summary properties, through
     ‘MsiSummaryInfoGetPropertyCount()’.

 -- 成員函式: SummaryInformation.SetProperty (field, value)

     Set a property through ‘MsiSummaryInfoSetProperty()’.  `field' can
     have the same values as in *note GetProperty(): 10fe, `value' is
     the new value of the property.  Possible value types are integer
     and string.

 -- 成員函式: SummaryInformation.Persist ()

     Write the modified properties to the summary information stream,
     using ‘MsiSummaryInfoPersist()’.

也參考
......

MsiSummaryInfoGetProperty(1) MsiSummaryInfoGetPropertyCount(2)
MsiSummaryInfoSetProperty(3) MsiSummaryInfoPersist(4)

   ---------- Footnotes ----------

   (1) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370409.aspx

   (2) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370488.aspx

   (3) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370491.aspx

   (4) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370490.aspx


File: python.info,  Node: Record Objects,  Next: Errors,  Prev: Summary Information Objects,  Up: msilib --- Read and write Microsoft Installer files

5.34.1.4 Record Objects
.......................

 -- 成員函式: Record.GetFieldCount ()

     Return the number of fields of the record, through
     ‘MsiRecordGetFieldCount()’.

 -- 成員函式: Record.GetInteger (field)

     Return the value of `field' as an integer where possible.  `field'
     must be an integer.

 -- 成員函式: Record.GetString (field)

     Return the value of `field' as a string where possible.  `field'
     must be an integer.

 -- 成員函式: Record.SetString (field, value)

     Set `field' to `value' through ‘MsiRecordSetString()’.  `field'
     must be an integer; `value' a string.

 -- 成員函式: Record.SetStream (field, value)

     Set `field' to the contents of the file named `value', through
     ‘MsiRecordSetStream()’.  `field' must be an integer; `value' a
     string.

 -- 成員函式: Record.SetInteger (field, value)

     Set `field' to `value' through ‘MsiRecordSetInteger()’.  Both
     `field' and `value' must be an integer.

 -- 成員函式: Record.ClearData ()

     Set all fields of the record to 0, through ‘MsiRecordClearData()’.

也參考
......

MsiRecordGetFieldCount(1) MsiRecordSetString(2) MsiRecordSetStream(3)
MsiRecordSetInteger(4) MsiRecordClearData(5)

   ---------- Footnotes ----------

   (1) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370366.aspx

   (2) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370373.aspx

   (3) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370372.aspx

   (4) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370371.aspx

   (5) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370364.aspx


File: python.info,  Node: Errors,  Next: CAB Objects,  Prev: Record Objects,  Up: msilib --- Read and write Microsoft Installer files

5.34.1.5 Errors
...............

All wrappers around MSI functions raise ‘MSIError’; the string inside
the exception will contain more detail.


File: python.info,  Node: CAB Objects,  Next: Directory Objects,  Prev: Errors,  Up: msilib --- Read and write Microsoft Installer files

5.34.1.6 CAB Objects
....................

 -- 類別: msilib.CAB (name)

     The class *note CAB: 3ba1. represents a CAB file.  During MSI
     construction, files will be added simultaneously to the ‘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.

     `name' is the name of the CAB file in the MSI file.

      -- 成員函式: append (full, file, logical)

          Add the file with the pathname `full' to the CAB file, under
          the name `logical'.  If there is already a file named
          `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.

      -- 成員函式: commit (database)

          Generate a CAB file, add it as a stream to the MSI file, put
          it into the ‘Media’ table, and remove the generated file from
          the disk.


File: python.info,  Node: Directory Objects,  Next: 相关特性<3>,  Prev: CAB Objects,  Up: msilib --- Read and write Microsoft Installer files

5.34.1.7 Directory Objects
..........................

 -- 類別: 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 *note start_component(): 10ff, 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
     ‘None’), the path to the physical directory, and a logical
     directory name.  `default' specifies the DefaultDir slot in the
     directory table.  `componentflags' specifies the default flags that
     new components get.

      -- 成員函式: 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 `feature' is
          given, the current feature is used.  If no `flags' are given,
          the directory’s default flags are used.  If no `keyfile' is
          given, the KeyPath is left null in the Component table.

      -- 成員函式: 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 `src' file is specified, it is interpreted relative to
          the current directory.  Optionally, a `version' and a
          `language' can be specified for the entry in the File table.

      -- 成員函式: 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
          `exclude' list.

      -- 成員函式: remove_pyc ()

          Remove ‘.pyc’ files on uninstall.

也參考
......

Directory Table(1) File Table(2) Component Table(3) FeatureComponents
Table(4)

   ---------- Footnotes ----------

   (1) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa368295.aspx

   (2) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa368596.aspx

   (3) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa368007.aspx

   (4) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa368579.aspx


File: python.info,  Node: 相关特性<3>,  Next: GUI classes,  Prev: Directory Objects,  Up: msilib --- Read and write Microsoft Installer files

5.34.1.8 相关特性
.................

 -- 類別: msilib.Feature (db, id, title, desc, display, level=1,
          parent=None, directory=None, attributes=0)

     Add a new record to the ‘Feature’ table, using the values `id',
     `parent.id', `title', `desc', `display', `level', `directory', and
     `attributes'.  The resulting feature object can be passed to the
     ‘start_component()’ method of *note Directory: 3ba6.

      -- 成員函式: set_current ()

          Make this feature the current feature of *note msilib: b5.
          New components are automatically added to the default feature,
          unless a feature is explicitly specified.

也參考
......

Feature Table(1)

   ---------- Footnotes ----------

   (1) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa368585.aspx


File: python.info,  Node: GUI classes,  Next: Precomputed tables,  Prev: 相关特性<3>,  Up: msilib --- Read and write Microsoft Installer files

5.34.1.9 GUI classes
....................

*note msilib: b5. provides several classes that wrap the GUI tables in
an MSI database.  However, no standard user interface is provided; use
*note bdist_msi: 40. to create MSI files with a user-interface for
installing Python packages.

 -- 類別: msilib.Control (dlg, name)

     Base class of the dialog controls.  `dlg' is the dialog object the
     control belongs to, and `name' is the control’s name.

      -- 成員函式: event (event, argument, condition=1, ordering=None)

          Make an entry into the ‘ControlEvent’ table for this control.

      -- 成員函式: mapping (event, attribute)

          Make an entry into the ‘EventMapping’ table for this control.

      -- 成員函式: condition (action, condition)

          Make an entry into the ‘ControlCondition’ table for this
          control.

 -- 類別: msilib.RadioButtonGroup (dlg, name, property)

     Create a radio button control named `name'.  `property' is the
     installer property that gets set when a radio button is selected.

      -- 成員函式: add (name, x, y, width, height, text, value=None)

          Add a radio button named `name' to the group, at the
          coordinates `x', `y', `width', `height', and with the label
          `text'.  If `value' is ‘None’, it defaults to `name'.

 -- 類別: msilib.Dialog (db, name, x, y, w, h, attr, title, first,
          default, cancel)

     Return a new *note Dialog: 3bb6. object.  An entry in the ‘Dialog’
     table is made, with the specified coordinates, dialog attributes,
     title, name of the first, default, and cancel controls.

      -- 成員函式: control (name, type, x, y, width, height, attributes,
               property, text, control_next, help)

          Return a new *note Control: 3bb0. object.  An entry in the
          ‘Control’ table is made with the specified parameters.

          This is a generic method; for specific types, specialized
          methods are provided.

      -- 成員函式: text (name, x, y, width, height, attributes, text)

          Add and return a ‘Text’ control.

      -- 成員函式: bitmap (name, x, y, width, height, text)

          Add and return a ‘Bitmap’ control.

      -- 成員函式: line (name, x, y, width, height)

          Add and return a ‘Line’ control.

      -- 成員函式: pushbutton (name, x, y, width, height, attributes,
               text, next_control)

          Add and return a ‘PushButton’ control.

      -- 成員函式: radiogroup (name, x, y, width, height, attributes,
               property, text, next_control)

          Add and return a ‘RadioButtonGroup’ control.

      -- 成員函式: checkbox (name, x, y, width, height, attributes,
               property, text, next_control)

          Add and return a ‘CheckBox’ control.

也參考
......

Dialog Table(1) Control Table(2) Control Types(3) ControlCondition
Table(4) ControlEvent Table(5) EventMapping Table(6) RadioButton
Table(7)

   ---------- Footnotes ----------

   (1) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa368286.aspx

   (2) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa368044.aspx

   (3) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa368039.aspx

   (4) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa368035.aspx

   (5) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa368037.aspx

   (6) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa368559.aspx

   (7) 
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370962.aspx


File: python.info,  Node: Precomputed tables,  Prev: GUI classes,  Up: msilib --- Read and write Microsoft Installer files

5.34.1.10 Precomputed tables
............................

*note msilib: b5. provides a few subpackages that contain only schema
and table definitions.  Currently, these definitions are based on MSI
version 2.0.

 -- Data: msilib.schema

     This is the standard MSI schema for MSI 2.0, with the `tables'
     variable providing a list of table definitions, and
     `_Validation_records' providing the data for MSI validation.

 -- Data: msilib.sequence

     This module contains table contents for the standard sequence
     tables: `AdminExecuteSequence', `AdminUISequence',
     `AdvtExecuteSequence', `InstallExecuteSequence', and
     `InstallUISequence'.

 -- Data: msilib.text

     This module contains definitions for the UIText and ActionText
     tables, for the standard installer actions.


File: python.info,  Node: msvcrt --- 来自 MS VC++ 运行时的有用例程,  Next: winreg --- Windows 注册表访问,  Prev: msilib --- Read and write Microsoft Installer files,  Up: Windows系统相关模块

5.34.2 ‘msvcrt’ — 来自 MS VC++ 运行时的有用例程
-----------------------------------------------

__________________________________________________________________

这些函数提供了对 Windows 平台上一些有用功能的访问。一些更高级别的模块使
用这些函数来构建其服务的 Windows 实现。 例如， *note getpass: 86. 模块在
实现 *note getpass(): 86. 函数时使用了这些函数。

关于这些函数的更多信息可以在平台 API 文档中找到。

该模块实现了控制台 I/O API 的普通和宽字符变体。普通的 API 只处理ASCII字
符，国际化应用受限。应该尽可能地使用宽字符 API 。

3.3 版更變: 此模块中过去会引发 *note IOError: a73. 的操作现在将引发
*note OSError: 304.。

* Menu:

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


File: python.info,  Node: 文件操作,  Next: 控制台 I/O,  Up: msvcrt --- 来自 MS VC++ 运行时的有用例程

5.34.2.1 文件操作
.................

 -- 函式: msvcrt.locking (fd, mode, nbytes)

     基于文件描述符 `fd' 从 C 运行时锁定文件的某一部分。 失败时引发
     *note OSError: 304.。 锁定的文件区域从当前文件位置开始扩展 `nbytes'
     个字节，并可能持续到超出文件末尾。 `mode' 必须为下面列出的 ‘LK_*’ 之
     一。 一个文件中的多个区域可以被同时锁定，但是不能重叠。 相邻区域不
     会被合并；它们必须单独被解锁。

     引发一个 *note 审计事件: fa1. ‘msvcrt.locking’，附带参数 ‘fd’,
     ‘mode’, ‘nbytes’。

 -- Data: msvcrt.LK_LOCK
 -- Data: msvcrt.LK_RLCK

     锁定指定的字节数据。 如果字节数据无法被锁定，程序会在 1 秒之后立即
     重试。 如果在 10 次尝试后字节数据仍无法被锁定，则会引发 *note
     OSError: 304.。

 -- Data: msvcrt.LK_NBLCK
 -- Data: msvcrt.LK_NBRLCK

     锁定指定的字节数据。 如果字节数据无法被锁定，则会引发 *note
     OSError: 304.。

 -- Data: msvcrt.LK_UNLCK

     解锁指定的字节数据，该对象必须在之前被锁定。

 -- 函式: msvcrt.setmode (fd, flags)

     设置文件描述符 `fd' 的行结束符转写模式。 要将其设为文本模式，则
     `flags' 应当为 *note os.O_TEXT: 2085.；设为二进制模式，则应当为
     *note os.O_BINARY: 2076.。

 -- 函式: msvcrt.open_osfhandle (handle, flags)

     基于文件句柄 `handle' 创建一个 C 运行时文件描述符。 `flags' 形参应
     当 *note os.O_APPEND: 2078, *note os.O_RDONLY: 2074. 和 *note
     os.O_TEXT: 2085. 按位 OR 的结果。 返回的文件描述符可以被用作 *note
     os.fdopen(): 1564. 的形参以创建一个文件对象。

     引发一个 *note 审计事件: fa1. ‘msvcrt.open_osfhandle’，附带参数
     ‘handle’, ‘flags’。

 -- 函式: msvcrt.get_osfhandle (fd)

     返回文件描述符 `fd' 的文件句柄。 如果 `fd' 不能被识别则会引发 *note
     OSError: 304.。

     引发一个 *note 审计事件: fa1. ‘msvcrt.get_osfhandle’，附带参数
     ‘fd’。


File: python.info,  Node: 控制台 I/O,  Next: 其他函数,  Prev: 文件操作,  Up: msvcrt --- 来自 MS VC++ 运行时的有用例程

5.34.2.2 控制台 I/O
...................

 -- 函式: msvcrt.kbhit ()

     如果有某个按键正在等待被读取则返回 ‘True’。

 -- 函式: msvcrt.getch ()

     读取一个按键并将结果字符返回为一个字节串。 不会有内容回显到缝制台。
     如果还没有任何键被按下此调用将会阻塞，但它将不会等待 ‘Enter’ 被按下
     。 如果按下的键是一个特殊功能键，此函数将返回 ‘'\000'’ 或 ‘'\xe0'’；
     下一次调用将返回键代码。 ‘Control-C’ 按钮无法使用此函数来读取。

 -- 函式: msvcrt.getwch ()

     *note getch(): 3bcf. 的宽字符版本，返回一个 Unicode 值。

 -- 函式: msvcrt.getche ()

     类似于 *note getch(): 3bcf.，但按键如果表示一个可打印字符则它将被回
     显。

 -- 函式: msvcrt.getwche ()

     *note getche(): 3bd1. 的宽字符版本，返回一个 Unicode 值。

 -- 函式: msvcrt.putch (char)

     将字符串 `char' 打印到终端，不使用缓冲区。

 -- 函式: msvcrt.putwch (unicode_char)

     *note putch(): 3bd3. 的宽字符版本，接受一个 Unicode 值。

 -- 函式: msvcrt.ungetch (char)

     使得字节串 `char' 被“推回”终端缓冲区；它将是被 *note getch(): 3bcf.
     或 *note getche(): 3bd1. 读取的下一个字符。

 -- 函式: msvcrt.ungetwch (unicode_char)

     *note ungetch(): 3bd5. 的宽字符版本，接受一个 Unicode 值。


File: python.info,  Node: 其他函数,  Prev: 控制台 I/O,  Up: msvcrt --- 来自 MS VC++ 运行时的有用例程

5.34.2.3 其他函数
.................

 -- 函式: msvcrt.heapmin ()

     强制 ‘malloc()’ 堆清空自身并将未使用的块返回给操作系统。 失败时，这
     将引发 *note OSError: 304.。


File: python.info,  Node: winreg --- Windows 注册表访问,  Next: winsound —— Windows 系统的声音播放接口,  Prev: msvcrt --- 来自 MS VC++ 运行时的有用例程,  Up: Windows系统相关模块

5.34.3 ‘winreg’ — Windows 注册表访问
------------------------------------

__________________________________________________________________

这些函数将 Windows 注册表 API 暴露给 Python。为了确保即便程序员忽略了显
式关闭句柄，该句柄依然能够正确关闭，它使用了一个 *note handle 对象:
3bdc. 而不是整数来作为注册表句柄。

3.3 版更變: 该模块中的几个函数被用于引发 *note WindowsError: a75.，该异
常现在是 *note OSError: 304. 的别名。

* Menu:

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


File: python.info,  Node: 函数<12>,  Next: 常数<7>,  Up: winreg --- Windows 注册表访问

5.34.3.1 函数
.............

该模块提供了下列函数：

 -- 函式: winreg.CloseKey (hkey)

     关闭之前打开的注册表键。参数 `hkey' 指之前打开的键。

          備註: 如果没有使用该方法关闭 `hkey' (或者通过 *note
          hkey.Close(): 3be1.)，在对象 `hkey' 被 Python 销毁时会将其关闭
          。

 -- 函式: winreg.ConnectRegistry (computer_name, key)

     建立到另一台计算上上的预定义注册表句柄的连接，并返回一个 *note
     handle 对象: 3bdc.

     `computer_name' 是远程计算机的名称，以 ‘r"\\computername"’ 的形式。
     如果是 ‘None’ ，将会使用本地计算机。

     `key' 是所连接到的预定义句柄。

     返回值是所开打键的句柄。如果函数失败，则引发一个 *note OSError:
     304. 异常。

     引发一个 *note 审计事件: fa1. ‘winreg.ConnectRegistry’，附带参数
     ‘computer_name’, ‘key’。

     3.3 版更變: 参考 *note 上文: 3bdd.。

 -- 函式: winreg.CreateKey (key, sub_key)

     创建或打开特定的键，返回一个 *note handle 对象: 3bdc.。

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 3be2. 之
     一。

     `sub_key' 是用于命名该方法所打开或创建的键的字符串。

     如果 `key' 是预定义键之一，`sub_key' 可能会是 ‘None’。该情况下，返
     回的句柄就是传入函数的句柄。

     如果键已经存在，则该函数打开已经存在的该键。

     返回值是所开打键的句柄。如果函数失败，则引发一个 *note OSError:
     304. 异常。

     引发一个 *note 审计事件: fa1. ‘winreg.CreateKey’，附带参数 ‘key’,
     ‘sub_key’, ‘access’。

     引发一个 *note 审计事件: fa1. ‘winreg.OpenKey/result’，附带参数
     ‘key’。

     3.3 版更變: 参考 *note 上文: 3bdd.。

 -- 函式: winreg.CreateKeyEx (key, sub_key, reserved=0,
          access=KEY_WRITE)

     创建或打开特定的键，返回一个 *note handle 对象: 3bdc.。

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 3be2. 之
     一。

     `sub_key' 是用于命名该方法所打开或创建的键的字符串。

     `reserved' 是一个保留的证书，必须是零。默认值为零。

     `access' 为一个整数，用于给键的预期安全访问指定访问掩码。默认值为
     *note KEY_WRITE: 3be3.。 参阅 *note Access Rights: 3be4. 了解其它允
     许值。

     如果 `key' 是预定义键之一，`sub_key' 可能会是 ‘None’。该情况下，返
     回的句柄就是传入函数的句柄。

     如果键已经存在，则该函数打开已经存在的该键。

     返回值是所开打键的句柄。如果函数失败，则引发一个 *note OSError:
     304. 异常。

     引发一个 *note 审计事件: fa1. ‘winreg.CreateKey’，附带参数 ‘key’,
     ‘sub_key’, ‘access’。

     引发一个 *note 审计事件: fa1. ‘winreg.OpenKey/result’，附带参数
     ‘key’。

     3.2 版新加入.

     3.3 版更變: 参考 *note 上文: 3bdd.。

 -- 函式: winreg.DeleteKey (key, sub_key)

     删除指定的键。

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 3be2. 之
     一。

     `sub_key' 这个字符串必须是由 `key' 参数所指定键的一个子项。该值项不
     可以是 ‘None’，同时键也不可以有子项。

     `该方法不能删除带有子项的键。'

     如果方法成功，则整个键，包括其所有值项都会被移除。如果方法失败，则
     引发一个 *note OSError: 304. 异常。

     引发一个 *note 审计事件: fa1. ‘winreg.DeleteKey’，附带参数 ‘key’,
     ‘sub_key’, ‘access’。

     3.3 版更變: 参考 *note 上文: 3bdd.。

 -- 函式: winreg.DeleteKeyEx (key, sub_key, access=KEY_WOW64_64KEY,
          reserved=0)

     删除指定的键。

          備註: 函数 *note DeleteKeyEx(): 367c. 通过 RegDeleteKeyEx 这个
          Windows API 函数实现，该函数为 Windows 的64位版本专属。 参阅
          RegDeleteKeyEx 文档(1)。

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 3be2. 之
     一。

     `sub_key' 这个字符串必须是由 `key' 参数所指定键的一个子项。该值项不
     可以是 ‘None’，同时键也不可以有子项。

     `reserved' 是一个保留的证书，必须是零。默认值为零。

     `access' 为一个整数，用于给键的预期安全访问指定访问掩码。默认值为常
     量 ‘_WOW64_64KEY’ 。参阅 *note Access Rights: 3be4. 了解其它允许值
     。

     `该方法不能删除带有子项的键。'

     如果方法成功，则整个键，包括其所有值项都会被移除。如果方法失败，则
     引发一个 *note OSError: 304. 异常。

     在不支持的 Windows 版本之上，将会引发 *note NotImplementedError:
     704. 异常。

     引发一个 *note 审计事件: fa1. ‘winreg.DeleteKey’，附带参数 ‘key’,
     ‘sub_key’, ‘access’。

     3.2 版新加入.

     3.3 版更變: 参考 *note 上文: 3bdd.。

 -- 函式: winreg.DeleteValue (key, value)

     从某个注册键中删除一个命名值项。

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 3be2. 之
     一。

     `value' 为标识所要删除值项的字符串。

     引发一个 *note 审计事件: fa1. ‘winreg.DeleteValue’，附带参数 ‘key’,
     ‘value’。

 -- 函式: winreg.EnumKey (key, index)

     列举某个已经打开注册表键的子项，并返回一个字符串。

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 3be2. 之
     一。

     `index' 为一个整数，用于标识所获取键的索引。

     每次调用该函数都会获取一个子项的名字。通常它会被反复调用，直到引发
     *note OSError: 304. 异常，这说明已经没有更多的可用值了。

     引发一个 *note 审计事件: fa1. ‘winreg.EnumKey’，附带参数 ‘key’,
     ‘index’。

     3.3 版更變: 参考 *note 上文: 3bdd.。

 -- 函式: winreg.EnumValue (key, index)

     列举某个已经打开注册表键的值项，并返回一个元组。

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 3be2. 之
     一。

     `index' 为一个整数，用于标识要获取值项的索引。

     每次调用该函数都会获取一个子项的名字。通常它会被反复调用，直到引发
     *note OSError: 304. 异常，这说明已经没有更多的可用值了。

     结果为3元素的元组。

     索引        意义
                 
     -------------------------------------------------------------
                 
     ‘0’         用于标识值项名称的字符串。
                 
                 
     ‘1’         保存值项数据的对象，其类型取决于背后的注册表类
                 型。
                 
                 
     ‘2’         标识值项数据类型的整数。（请查阅
                 *note SetValueEx(): 368c. 文档中的表格）
                 

     引发一个 *note 审计事件: fa1. ‘winreg.EnumValue’，附带参数 ‘key’,
     ‘index’。

     3.3 版更變: 参考 *note 上文: 3bdd.。

 -- 函式: winreg.ExpandEnvironmentStrings (str)

     Expands environment variable placeholders ‘%NAME%’ in strings like
     *note REG_EXPAND_SZ: 3be5.:

          >>> ExpandEnvironmentStrings('%windir%')
          'C:\\Windows'

     引发一个 *note 审计事件: fa1. ‘winreg.ExpandEnvironmentStrings’，附
     带参数 ‘str’。

 -- 函式: winreg.FlushKey (key)

     将某个键的所有属性写入注册表。

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 3be2. 之
     一。

     没有必要调用 *note FlushKey(): 3be6. 去改动注册表键。注册表的变动是
     由其延迟刷新机制更新到磁盘的。在系统关机时，也会将注册表的变动写入
     磁盘。与 *note CloseKey(): 3be0. 不同， *note FlushKey(): 3be6. 方
     法只有等到所有数据都写入注册表后才会返回。只有需要绝对确认注册表变
     动已写入磁盘时，应用程序才应去调用 *note FlushKey(): 3be6.。

          備註: 如果不知道是否要调用 *note FlushKey(): 3be6. ，可能就是
          不需要。

 -- 函式: winreg.LoadKey (key, sub_key, file_name)

     在指定键之下创建一个子键，并将指定文件中的注册表信息存入该子键中。

     `key' 是由 *note ConnectRegistry(): 3678. 返回的句柄，或者是常量
     *note HKEY_USERS: 3be7. 或 *note HKEY_LOCAL_MACHINE: 3be8. 之一。

     `sub_key' 是个字符串，用于标识需要载入的子键。

     `file_name' 是要加载注册表数据的文件名。该文件必须是用 *note
     SaveKey(): 368a. 函数创建的。在文件分配表（FAT）文件系统中，文件名
     可能不带扩展名。

     如果调用 *note LoadKey(): 3683. 的进程没有 ‘SE_RESTORE_PRIVILEGE’ 权
     限，则调用会失败。请注意，特权与权限不同 —— 更多细节请参阅
     RegLoadKey 文档(2)。

     如果 `key' 是由 *note ConnectRegistry(): 3678. 返回的句柄，那么
     `file_name' 指定的路径是相对于远程计算机而言的。

     引发一个 *note 审计事件: fa1. ‘winreg.LoadKey’，附带参数 ‘key’,
     ‘sub_key’, ‘file_name’。

 -- 函式: winreg.OpenKey (key, sub_key, reserved=0, access=KEY_READ)
 -- 函式: winreg.OpenKeyEx (key, sub_key, reserved=0, access=KEY_READ)

     打开指定的注册表键，返回 *note handle对象: 3bdc.。

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 3be2. 之
     一。

     `sub_key' 是个字符串，标识了需要打开的子键。

     `reserved' 是个保留整数，必须为零。默认值为零。

     `access' 是个指定访问掩码的整数，掩码描述了注册表键所需的安全权限。
     默认值为 *note KEY_READ: 3bea.。 其他合法值参见 *note 访问权限:
     3be4.。

     返回结果为一个新句柄，指向指定的注册表键。

     如果调用失败，则会触发 *note OSError: 304. 。

     引发一个 *note 审计事件: fa1. ‘winreg.OpenKey’，附带参数 ‘key’,
     ‘sub_key’, ‘access’。

     引发一个 *note 审计事件: fa1. ‘winreg.OpenKey/result’，附带参数
     ‘key’。

     3.2 版更變: 允许使用命名参数。

     3.3 版更變: 参考 *note 上文: 3bdd.。

 -- 函式: winreg.QueryInfoKey (key)

     以元组形式返回某注册表键的信息。

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 3be2. 之
     一。

     结果为3元素的元组。

     索引        意义
                 
     --------------------------------------------------------------
                 
     ‘0’         表示此注册表键有多少个子键的整数值。
                 
                 
     ‘1’         整数值，给出了此注册表键的值的数量。
                 
                 
     ‘2’         整数值，给出了此注册表键的最后修改时间，单位为
                 自 1601 年 1 月 1 日以来的 100 纳秒。
                 

     引发一个 *note 审计事件: fa1. ‘winreg.QueryInfoKey’，附带参数
     ‘key’。

 -- 函式: winreg.QueryValue (key, sub_key)

     读取某键的未命名值，形式为字符串。

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 3be2. 之
     一。

     `sub_key' 是个字符串，用于保存与某个值相关的子键名称。如果本参数为
     ‘None’ 或空，函数将读取由 *note SetValue(): 368b. 方法为 `key' 键设
     置的值。

     注册表中的值包含名称、类型和数据。本方法将读取注册表键值的第一个名
     称为 ‘NULL’ 的数据。可是底层的 API 调用不会返回类型，所以如果可能的
     话，请一定使用 *note QueryValueEx(): 3689.。

     引发一个 *note 审计事件: fa1. ‘winreg.QueryValue’，附带参数 ‘key’,
     ‘sub_key’, ‘value_name’。

 -- 函式: winreg.QueryValueEx (key, value_name)

     读取已打开注册表键指定值名称的类型和数据。

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 3be2. 之
     一。

     `value_name' 是字符串，表示要查询的值。

     结果为二元组：

     索引        意义
                 
     ----------------------------------------------------------
                 
     ‘0’         注册表项的值。
                 
                 
     ‘1’         整数值，给出该值的注册表类型（请查看文档中
                 的表格了解 *note SetValueEx(): 368c. ）。
                 

     引发一个 *note 审计事件: fa1. ‘winreg.QueryValue’，附带参数 ‘key’,
     ‘sub_key’, ‘value_name’。

 -- 函式: winreg.SaveKey (key, file_name)

     将指定注册表键及其所有子键存入指定的文件。

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 3be2. 之
     一。

     `file_name' 是要保存注册表数据的文件名。该文件不能已存在。如果文件
     名包括扩展名，也不能在文件分配表（FAT）文件系统中用于 *note
     LoadKey(): 3683. 方法。

     如果 `key' 代表远程计算机的注册表键，那么 `file_name' 所描述的路径
     是相对于远程计算机的。本方法的调用者必须拥有 ‘SeBackupPrivilege’ 特
     权。请注意，特权与权限是不同的 —— 更多细节请参见 用户权利和权限之间
     的冲突文档(3)。

     本函数将 ‘NULL’ 传给 API 的 `security_attributes'。

     引发一个 *note 审计事件: fa1. ‘winreg.SaveKey’，附带参数 ‘key’,
     ‘file_name’。

 -- 函式: winreg.SetValue (key, sub_key, type, value)

     将值与指定的注册表键关联。

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 3be2. 之
     一。

     `sub_key' 是个字符串，用于命名与该值相关的子键。

     `type' 是个整数，用于指定数据的类型。目前这必须是 *note REG_SZ:
     3beb. ，意味着只支持字符串。请用 *note SetValueEx(): 368c. 函数支持
     其他的数据类型。

     `value' 是设置新值的字符串。

     如果 `sub_key' 参数指定的注册表键不存在，SetValue 函数会创建一个。

     值的长度受到可用内存的限制。较长的值（超过 2048 字节）应存为文件，
     并将文件名存入配置注册表。这有助于提高注册表的使用效率。

     由 `key' 参数标识的注册表键，必须已用 *note KEY_SET_VALUE: 3bec. 方
     式打开。

     引发一个 *note 审计事件: fa1. ‘winreg.SetValue’，附带参数 ‘key’,
     ‘sub_key’, ‘type’, ‘value’。

 -- 函式: winreg.SetValueEx (key, value_name, reserved, type, value)

     将数据存入已打开的注册表键的值中。

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 3be2. 之
     一。

     `value_name' 是个字符串，用于命名与值相关的子键。

     `reserved' 可以是任意数据 —— 传给 API 的总是 0。

     `type' 是个整数，用于指定数据的类型。请参阅 *note Value Types:
     3bed. 了解可用的类型。

     `value' 是设置新值的字符串。

     本方法也可为指定的注册表键设置额外的值和类型信息。注册表键必须已用
     *note KEY_SET_VALUE: 3bec. 方式打开。

     请用 *note CreateKey(): 3679. 或 *note OpenKey(): 3684. 方法打开注
     册表键。

     值的长度受到可用内存的限制。较长的值（超过 2048 字节）应存为文件，
     并将文件名存入配置注册表。这有助于提高注册表的使用效率。

     引发一个 *note 审计事件: fa1. ‘winreg.SetValue’，附带参数 ‘key’,
     ‘sub_key’, ‘type’, ‘value’。

 -- 函式: winreg.DisableReflectionKey (key)

     禁用运行于 64 位操作系统的 32 位进程的注册表重定向。

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 3be2. 之
     一。

     如果在 32 位操作系统上执行，一般会触发 *note NotImplementedError:
     704.。

     如果注册表键不在重定向列表中，函数会调用成功，但没有实际效果。禁用
     注册表键的重定向不会影响任何子键的重定向。

     引发一个 *note 审计事件: fa1. ‘winreg.DisableReflectionKey’，附带参
     数 ‘key’。

 -- 函式: winreg.EnableReflectionKey (key)

     恢复已禁用注册表键的重定向。

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 3be2. 之
     一。

     如果在 32 位操作系统上执行，一般会触发 *note NotImplementedError:
     704.。

     恢复注册表键的重定向不会影响任何子键的重定向。

     引发一个 *note 审计事件: fa1. ‘winreg.EnableReflectionKey’，附带参
     数 ‘key’。

 -- 函式: winreg.QueryReflectionKey (key)

     确定给定注册表键的重定向状况。

     `key' 为某个已经打开的键，或者预定义的 *note HKEY_* 常量: 3be2. 之
     一。

     如果重定向已禁用则返回 ‘True’。

     如果在 32 位操作系统上执行，一般会触发 *note NotImplementedError:
     704.。

     引发一个 *note 审计事件: fa1. ‘winreg.QueryReflectionKey’，附带参数
     ‘key’。

   ---------- Footnotes ----------

   (1) https://msdn.microsoft.com/en-us/library/ms724847%28VS.85%29.aspx

   (2) 
https://msdn.microsoft.com/en-us/library/ms724889%28v=VS.85%29.aspx

   (3) 
https://msdn.microsoft.com/en-us/library/ms724878%28v=VS.85%29.aspx


File: python.info,  Node: 常数<7>,  Next: 注册表句柄对象,  Prev: 函数<12>,  Up: winreg --- Windows 注册表访问

5.34.3.2 常数
.............

以下常量定义成可供很多 ‘_winreg’ 函数使用。

* Menu:

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


File: python.info,  Node: HKEY_* 常量,  Next: 访问权限,  Up: 常数<7>

5.34.3.3 HKEY_* 常量
....................

 -- Data: winreg.HKEY_CLASSES_ROOT

     本注册表键下的注册表项定义了文件的类型（或类别）及相关属性。Shell 和
     COM 应用程序将使用该注册表键下保存的信息。

 -- Data: winreg.HKEY_CURRENT_USER

     属于该注册表键的表项定义了当前用户的偏好。这些偏好值包括环境变量设
     置、程序组数据、颜色、打印机、网络连接和应用程序参数。

 -- Data: winreg.HKEY_LOCAL_MACHINE

     属于该注册表键的表项定义了计算机的物理状态，包括总线类型、系统内存
     和已安装软硬件等数据。

 -- Data: winreg.HKEY_USERS

     属于该注册表键的表项定义了当前计算机中新用户的默认配置和当前用户配
     置。

 -- Data: winreg.HKEY_PERFORMANCE_DATA

     属于该注册表键的表项可用于读取性能数据。这些数据其实并不存放于注册
     表中；注册表提供功能让系统收集数据。

 -- Data: winreg.HKEY_CURRENT_CONFIG

     包含有关本地计算机系统当前硬件配置的信息。

 -- Data: winreg.HKEY_DYN_DATA

     Windows 98 以上版本不使用该注册表键。


File: python.info,  Node: 访问权限,  Next: 注册表值的类型,  Prev: HKEY_* 常量,  Up: 常数<7>

5.34.3.4 访问权限
.................

更多信息，请参阅 注册表密钥安全和访问(1)。

 -- Data: winreg.KEY_ALL_ACCESS

     组合了 STANDARD_RIGHTS_REQUIRED 、*note KEY_QUERY_VALUE: 3bf8. 、
     *note KEY_SET_VALUE: 3bec. 、 *note KEY_CREATE_SUB_KEY: 3bf9. 、
     *note KEY_ENUMERATE_SUB_KEYS: 3bfa. 、 *note KEY_NOTIFY: 3bfb. 和
     *note KEY_CREATE_LINK: 3bfc. 访问权限。

 -- Data: winreg.KEY_WRITE

     组合了 STANDARD_RIGHTS_WRITE 、 *note KEY_SET_VALUE: 3bec. 和 *note
     KEY_CREATE_SUB_KEY: 3bf9. 访问权限。

 -- Data: winreg.KEY_READ

     组合了 STANDARD_RIGHTS_READ 、 *note KEY_QUERY_VALUE: 3bf8. 、
     *note KEY_ENUMERATE_SUB_KEYS: 3bfa. 和 *note KEY_NOTIFY: 3bfb. 。

 -- Data: winreg.KEY_EXECUTE

     等价于 *note KEY_READ: 3bea.。

 -- Data: winreg.KEY_QUERY_VALUE

     查询注册表键值时需要用到。

 -- Data: winreg.KEY_SET_VALUE

     创建、删除或设置注册表值时需要用到。

 -- Data: winreg.KEY_CREATE_SUB_KEY

     创建注册表键的子键时需要用到。

 -- Data: winreg.KEY_ENUMERATE_SUB_KEYS

     枚举注册表键的子键时需要用到。

 -- Data: winreg.KEY_NOTIFY

     为注册表键或子键请求修改通知时需要用到。

 -- Data: winreg.KEY_CREATE_LINK

     保留给系统使用。

* Menu:

* 64 位系统特有::

   ---------- Footnotes ----------

   (1) 
https://msdn.microsoft.com/en-us/library/ms724878%28v=VS.85%29.aspx


File: python.info,  Node: 64 位系统特有,  Up: 访问权限

5.34.3.5 64 位系统特有
......................

详情请参阅 Accessing an Alternate Registry View(1)。

 -- Data: winreg.KEY_WOW64_64KEY

     表示 64 位 Windows 中的应用程序应在 64 位注册表视图上操作。

 -- Data: winreg.KEY_WOW64_32KEY

     表示 64 位 Windows 中的应用程序应在 32 位注册表视图上操作。

   ---------- Footnotes ----------

   (1) https://msdn.microsoft.com/en-us/library/aa384129(v=VS.85).aspx


File: python.info,  Node: 注册表值的类型,  Prev: 访问权限,  Up: 常数<7>

5.34.3.6 注册表值的类型
.......................

详情请参阅 Registry Value Types(1)。

 -- Data: winreg.REG_BINARY

     任意格式的二进制数据。

 -- Data: winreg.REG_DWORD

     32 位数值。

 -- Data: winreg.REG_DWORD_LITTLE_ENDIAN

     32 位低字节序格式的数字。相当于 *note REG_DWORD: 3c04.。

 -- Data: winreg.REG_DWORD_BIG_ENDIAN

     32 位高字节序格式的数字。

 -- Data: winreg.REG_EXPAND_SZ

     包含环境变量（‘%PATH%’）的字符串，以空字符结尾。

 -- Data: winreg.REG_LINK

     Unicode 符号链接。

 -- Data: winreg.REG_MULTI_SZ

     一串以空字符结尾的字符串，最后以两个空字符结尾。Python 会自动处理这
     种结尾形式。

 -- Data: winreg.REG_NONE

     未定义的类型。

 -- Data: winreg.REG_QWORD

     64 位数字。

     3.6 版新加入.

 -- Data: winreg.REG_QWORD_LITTLE_ENDIAN

     64 位低字节序格式的数字。相当于 *note REG_QWORD: 6a9.。

     3.6 版新加入.

 -- Data: winreg.REG_RESOURCE_LIST

     设备驱动程序资源列表。

 -- Data: winreg.REG_FULL_RESOURCE_DESCRIPTOR

     硬件设置。

 -- Data: winreg.REG_RESOURCE_REQUIREMENTS_LIST

     硬件资源列表。

 -- Data: winreg.REG_SZ

     空字符结尾的字符串。

   ---------- Footnotes ----------

   (1) 
https://msdn.microsoft.com/en-us/library/ms724884%28v=VS.85%29.aspx


File: python.info,  Node: 注册表句柄对象,  Prev: 常数<7>,  Up: winreg --- Windows 注册表访问

5.34.3.7 注册表句柄对象
.......................

该对象封装了 Windows HKEY 对象，对象销毁时会自动关闭。为确保资源得以清理
，可调用 *note Close(): 3be1. 方法或 *note CloseKey(): 3be0. 函数。

本模块中的所有注册表函数都会返回注册表句柄对象。

本模块中所有接受注册表句柄对象的注册表函数，也能接受一个整数，但鼓励大家
使用句柄对象。

注册表句柄对象支持 *note __bool__(): d30. 语义 —— 因此：

     if handle:
         print("Yes")

将会打印出 ‘Yes’ 。

句柄对象还支持比较语义，因此若多个句柄对象都引用了同一底层 Windows 句柄
值，那么比较操作结果将为 True。

句柄对象可转换为整数（如利用内置函数 *note int(): 204.），这时会返回底层
的 Windows 句柄值。用 *note Detach(): 3685. 方法也可返回整数句柄，同时会
断开与 Windows 句柄的连接。

 -- 成員函式: PyHKEY.Close ()

     关闭底层的 Windows 句柄。

     如果句柄已关闭，不会引发错误。

 -- 成員函式: PyHKEY.Detach ()

     断开与 Windows 句柄的连接。

     结果为一个整数，存有被断开连接之前的句柄值。如果该句柄已断开连接或
     关闭，则返回 0。

     调用本函数后，注册表句柄将被迅速禁用，但并没有关闭。当需要底层的
     Win32 句柄在句柄对象的生命周期之后仍然存在时，可以调用这个函数。

     引发一个 *note 审计事件: fa1. ‘winreg.PyHKEY.Detach’，附带参数
     ‘key’。

 -- 成員函式: PyHKEY.__enter__ ()
 -- 成員函式: PyHKEY.__exit__ (*exc_info)

     HKEY 对象实现了 *note __enter__(): d5d. 和 *note __exit__(): d5e. 方
     法，因此支持 *note with: 7da. 语句的上下文协议：

          with OpenKey(HKEY_LOCAL_MACHINE, "foo") as key:
              ...  # work with key

     在离开 *note with: 7da. 语句块时，`key' 会自动关闭。


File: python.info,  Node: winsound —— Windows 系统的声音播放接口,  Prev: winreg --- Windows 注册表访问,  Up: Windows系统相关模块

5.34.4 ‘winsound’ —— Windows 系统的声音播放接口
-----------------------------------------------

__________________________________________________________________

通过 *note winsound: 134. 模块可访问 Windows 平台的基础音频播放机制。包
括一些函数和几个常量。

 -- 函式: winsound.Beep (frequency, duration)

     让 PC 的扬声器发出提示音。`frequency' 参数可指定声音的频率，单位是
     赫兹，必须位于 37 到 32,767 之间。`duration' 参数则指定了声音应持续
     的毫秒数。若系统无法让扬声器发声，则会触发 *note RuntimeError:
     3dc.。

 -- 函式: winsound.PlaySound (sound, flags)

     由平台 API 调用底层的 ‘PlaySound()’ 函数。 参数 `sound' 可以是文件
     名、系统音频的别名、*note bytes-like object: 6df. 的音频数据或
     ‘‘None‘‘。 如何解释取决于 `flags' 的值，可为以下常数的二进制 OR 组
     合。 如果 `sound' 参数为 ‘None’，则当前播放的波形音频会全部停止。如
     果系统报错， 则会触发 *note RuntimeError: 3dc.。

 -- 函式: winsound.MessageBeep (type=MB_OK)

     由平台 API 调用底层的 ‘MessageBeep()’ 函数。用于播放注册表中指定的
     音频。 `type' 参数指定播放的音频；可能的值是 ‘-1’、
     ‘MB_ICONASTERISK’、‘MB_ICONEXCLAMATION’、‘MB_ICONHAND’、
     ‘MB_ICONQUESTION’ 和 ‘MB_OK’，下面会介绍。值 ‘-1’ 会生成一个 "简单
     的嘀声"；若其他的音频无法播放，这是最后的退路。如果系统报错，则会触
     发 *note RuntimeError: 3dc. 。

 -- Data: winsound.SND_FILENAME

     参数 `sound' 指明 WAV 文件名。不要与 *note SND_ALIAS: 3c13. 一起使
     用。

 -- Data: winsound.SND_ALIAS

     参数 `sound' 是注册表内关联的音频名称。 如果注册表中无此名称，则播
     放系统默认的声音，除非同时设定了 *note SND_NODEFAULT: 3c14. 。 如果
     没有注册默认声音，则会触发 *note RuntimeError: 3dc.。 请勿与 *note
     SND_FILENAME: 3c12. 一起使用。

     所有的 Win32 系统至少支持以下音频名称；大多数系统支持的音频都多于这
     些：

     *note PlaySound(): 6ad.        对应的控制面板音频名
     `name'                         

     ----------------------------------------------------------------------------
                                    
     ‘'SystemAsterisk'’             星号
                                    
                                    
     ‘'SystemExclamation'’          叹息声
                                    
                                    
     ‘'SystemExit'’                 退出 Windows
                                    
                                    
     ‘'SystemHand'’                 关键性停止音
                                    
                                    
     ‘'SystemQuestion'’             问题
                                    

     例如:

          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)

 -- Data: winsound.SND_LOOP

     循环播放音频。为避免阻塞，必须同时使用 *note SND_ASYNC: 3c16. 标志
     。不能与 *note SND_MEMORY: 3c17. 一起使用。

 -- Data: winsound.SND_MEMORY

     *note PlaySound(): 6ad. 的 `sound' 形参是一个 WAV 文件的内存镜像，
     作为一个 *note bytes-like object: 6df.。

          備註: 本模块不支持异步播放音频的内存镜像，所以该标志和 *note
          SND_ASYNC: 3c16. 的组合将触发 *note RuntimeError: 3dc.。

 -- Data: winsound.SND_PURGE

     停止播放指定声音的所有实例。

          備註: 新版 Windows 平台不支持本标志。

 -- Data: winsound.SND_ASYNC

     立即返回，允许异步播放音频。

 -- Data: winsound.SND_NODEFAULT

     即便找不到指定的音频，也不播放系统默认音频。

 -- Data: winsound.SND_NOSTOP

     不打断正在播放的音频。

 -- Data: winsound.SND_NOWAIT

     如果音频驱动程序忙，则立即返回。

          備註: 新版 Windows 平台不支持本标志。

 -- Data: winsound.MB_ICONASTERISK

     播放 ‘SystemDefault’ 音频。

 -- Data: winsound.MB_ICONEXCLAMATION

     播放 ‘SystemExclamation’ 音频。

 -- Data: winsound.MB_ICONHAND

     播放 ‘SystemHand’ 音频。

 -- Data: winsound.MB_ICONQUESTION

     播放 ‘SystemQuestion’ 音频。

 -- Data: winsound.MB_OK

     播放 ‘SystemDefault’ 音频。


File: python.info,  Node: Unix 专有服务,  Next: 被取代的模块,  Prev: Windows系统相关模块,  Up: Python 標準函式庫 Standard Library

5.35 Unix 专有服务
==================

本章描述的模块提供了 Unix 操作系统独有特性的接口，在某些情况下也适用于它
的某些或许多衍生版。 以下为模块概览：

* Menu:

* posix: posix --- 最常见的 POSIX 系统调用. 最常见的 POSIX 系统调用
* pwd: pwd --- 用户密码数据库. 用户密码数据库
* spwd —— shadow 密码库::
* grp: grp --- 组数据库. 组数据库
* crypt —— 检查 Unix 口令的函数::
* termios: termios --- POSIX 风格的 tty 控制. POSIX 风格的 tty 控制
* tty: tty --- 终端控制功能. 终端控制功能
* pty: pty --- 伪终端工具. 伪终端工具
* fcntl —— 系统调用 fcntl 和 ioctl::
* pipes: pipes --- 终端管道接口. 终端管道接口
* resource: resource --- 资源使用信息. 资源使用信息
* nis: nis --- Sun 的 NIS 黄页 接口. Sun 的 NIS (黄页) 接口
* Unix syslog 库例程::


File: python.info,  Node: posix --- 最常见的 POSIX 系统调用,  Next: pwd --- 用户密码数据库,  Up: Unix 专有服务

5.35.1 ‘posix’ — 最常见的 POSIX 系统调用
----------------------------------------

__________________________________________________________________

此模块提供了对基于 C 标准和 POSIX 标准（一种稍加修改的 Unix 接口）进行标
准化的系统功能的访问。

`请勿直接导入此模块。' 而应导入 *note os: c4. 模块，它提供了此接口的 `可
移植' 版本。 在 Unix 上，*note os: c4. 模块提供了 *note posix: d1. 接口
的一个超集。 在非 Unix 操作系统上 *note posix: d1. 模块将不可用，但会通
过 *note os: c4. 接口提供它的一个可用子集。 一旦导入了 *note os: c4.，用
它替代 *note posix: d1. 时就 `没有' 性能惩罚。 此外，*note os: c4. 还提
供了一些附加功能，例如在 ‘os.environ’ 中的某个条目被修改时会自动调用
*note putenv(): 1cd.。

错误将作为异常被报告；对于类型错误会给出普通异常，而系统调用所报告的异常
则会引发 *note OSError: 304.。

* Menu:

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


File: python.info,  Node: 大文件支持,  Next: 重要的模块内容,  Up: posix --- 最常见的 POSIX 系统调用

5.35.1.1 大文件支持
...................

某些操作系统（包括 AIX, HP-UX, Irix 和 Solaris）可对 ‘int’ 和 ‘long’ 为
32 位值的 C 编程模型提供大于 2 GiB 的文件的支持。 这在通常情况下是以将相
关数据长度和偏移类型定义为 64 位值的方式来实现的。 这样的文件有时被称为
`大文件'。

Python 中的大文件支持会在 ‘off_t’ 的大小超过 ‘long’ 且 ‘long long’ 至少
与 ‘off_t’ 一样大时被启用。 要启用此模式可能必须在启用特定编译旗标的情况
下执行 Python 配置和编译。 例如，在最近几个版本的 Irix 中默认启用了大文
件支持，但在 Solaris 2.6 和 2.7 中你还需要执行这样的操作:

     CFLAGS="`getconf LFS_CFLAGS`" OPT="-g -O2 $CFLAGS" \
             ./configure

在支持大文件的 Linux 系统中，可以这样做:

     CFLAGS='-D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64' OPT="-g -O2 $CFLAGS" \
             ./configure


File: python.info,  Node: 重要的模块内容,  Prev: 大文件支持,  Up: posix --- 最常见的 POSIX 系统调用

5.35.1.2 重要的模块内容
.......................

除了 *note os: c4. 模块文档已说明的许多函数，*note posix: d1. 还定义了下
列数据项:

 -- Data: posix.environ

     一个表示解释器启动时间点的字符串环境的字典。 键和值的类型在Unix 上
     为 bytes 而在 Windows 上为 str。 例如，‘environ[b'HOME']’ (Windows
     上的 ‘environ['HOME']’) 是你的家目录的路径名，等价于 C 中的
     ‘getenv("HOME")’。

     修改此字典不会影响由 *note execv(): 2058, *note popen(): 3cb. 或
     *note system(): e86. 所传入的字符串环境；如果你需要修改环境，请将
     ‘environ’ 传给 *note execve(): b1b. 或者为 *note system(): e86. 或
     *note popen(): 3cb. 的命令字符串添加变量赋值和 export 语句。

     3.2 版更變: 在 Unix 上，键和值为 bytes 类型。

          備註: *note os: c4. 模块提供了对 ‘environ’ 的替代实现，它会在
          被修改时更新环境。 还要注意更新 *note os.environ: c09. 将导致
          此字典失效。 推荐使用这个 *note os: c4. 模块版本而不是直接访问
          *note posix: d1. 模块。


File: python.info,  Node: pwd --- 用户密码数据库,  Next: spwd —— shadow 密码库,  Prev: posix --- 最常见的 POSIX 系统调用,  Up: Unix 专有服务

5.35.2 ‘pwd’ — 用户密码数据库
-----------------------------

__________________________________________________________________

此模块可以访问 Unix 用户账户名及密码数据库，在所有 Unix 版本上均可使用。

密码数据库中的条目以元组对象返回，属性对应 ‘passwd’ 中的结构（属性如下所
示，可参考 ‘<pwd.h>’）：

索引        属性                意义
                                
------------------------------------------------------------------
                                
0           ‘pw_name’           登录名
                                
                                
1           ‘pw_passwd’         密码，可能已经加密
                                
                                
2           ‘pw_uid’            用户 ID 数值
                                
                                
3           ‘pw_gid’            组 ID 数值
                                
                                
4           ‘pw_gecos’          用户名或备注
                                
                                
5           ‘pw_dir’            用户主目录
                                
                                
6           ‘pw_shell’          用户的命令解释器
                                

其中 uid 和 gid 是整数，其他是字符串，如果找不到对应的项目，抛出 *note
KeyError: 3e9. 异常。

     備註: 
     传统的 Unix 系统中，‘pw_passwd’ 的值通常使用 DES 导出的算法加密（参
     阅 *note crypt: 28. 模块）。不过现在的 unix 系统使用 `影子密码' 系
     统。在这些 unix 上，`pw_passwd' 只包含星号（‘'*'’）或字母（‘'x'’）
     ，而加密的密码存储在文件 ‘/etc/shadow’ 中，此文件不是全局可读的。在
     `pw_passwd' 中是否包含有用信息是系统相关的。如果可以访问到加密的密
     码，就需要使用 *note spwd: f1. 模块了。

本模块定义如下内容：

 -- 函式: pwd.getpwuid (uid)

     给定用户的数值 ID，返回密码数据库的对应项目。

 -- 函式: pwd.getpwnam (name)

     给定用户名，返回密码数据库的对应项目。

 -- 函式: pwd.getpwall ()

     返回密码数据库中所有项目的列表，顺序不是固定的。

也參考
......

模块 *note grp: 8a.

     针对用户组数据库的接口，与本模块类似。

模块 *note spwd: f1.

     针对影子密码数据库的接口，与本模块类似。


File: python.info,  Node: spwd —— shadow 密码库,  Next: grp --- 组数据库,  Prev: pwd --- 用户密码数据库,  Up: Unix 专有服务

5.35.3 ‘spwd’ —— shadow 密码库
------------------------------

__________________________________________________________________

该模块提供对 Unix shadow 密码库的访问能力。可用于各种 Unix 版本。

访问 shadow 密码数据库须拥有足够的权限（通常意味着必须采用 root 账户）。

shadow 密码库的每条数据均表示为一个类似元组的对象，其属性对应着‘‘spwd‘‘
结构的成员（下面列出了各属性字段，参见 ‘ ‘<shadow.h>’）。

索引        属性                意义
                                
----------------------------------------------------------------------
                                
0           ‘sp_namp’           登录名
                                
                                
1           ‘sp_pwdp’           加密后的密码
                                
                                
2           ‘sp_lstchg’         最后修改日期
                                
                                
3           ‘sp_min’            两次修改间隔的最小天数
                                
                                
4           ‘sp_max’            两次修改间隔的最大天数
                                
                                
5           ‘sp_warn’           提前警告用户密码过期的天数
                                
                                
6           ‘sp_inact’          密码过期至账户禁用之间的天数
                                
                                
7           ‘sp_expire’         账户过期的天数，自 1970-01-01 算起
                                
                                
8           ‘sp_flag’           保留字段
                                

sp_namp 和 sp_pwdp 条目是字符串，其他的均为整数。 如果未找到所需条目则会
触发 *note KeyError: 3e9.。

定义了以下函数：

 -- 函式: spwd.getspnam (name)

     返回指定用户名的 shadow 密码库记录。

     3.6 版更變: 如果当前用户权限不足，会触发 *note PermissionError:
     6f6.，而非 *note KeyError: 3e9.。

 -- 函式: spwd.getspall ()

     返回所有可用的 shadow 密码库记录列表，顺序随机。

也參考
......

模块 *note grp: 8a.

     针对用户组数据库的接口，与本模块类似。

模块 *note pwd: d6.

     访问普通密码库的接口，与本模块类似。


File: python.info,  Node: grp --- 组数据库,  Next: crypt —— 检查 Unix 口令的函数,  Prev: spwd —— shadow 密码库,  Up: Unix 专有服务

5.35.4 ‘grp’ — 组数据库
-----------------------

__________________________________________________________________

该模块提供对Unix组数据库的访问。 它在所有Unix版本上都可用。

组数据库条目被报告为类似元组的对象，其属性对应于 ‘group’ 结构的成员（下
面的属性字段，请参见 ‘<pwd.h>’ ）：

索引        属性            意义
                            
------------------------------------------------------------------
                            
0           gr_name         组名
                            
                            
1           gr_passwd       （加密的）组密码； 通常为空
                            
                            
2           gr_gid          数字组ID
                            
                            
3           gr_mem          组内所有成员的用户名
                            

gid是整数，名称和密码是字符串，成员列表是字符串列表。 （注意，大多数用户
未根据密码数据库显式列为所属组的成员。请检查两个数据库以获取完整的成员资
格信息。还要注意，以 ‘+’ 或 ‘-’ 开头的 ‘gr_name’ 可能是 YP/NIS 引用，可
能无法通过 *note getgrnam(): 1162. 或 *note getgrgid(): 6d6. 访问。）

本模块定义如下内容：

 -- 函式: grp.getgrgid (gid)

     返回给定数字组ID的组数据库条目。 如果找不到要求的条目，则会引发
     *note KeyError: 3e9. 错误。

     3.6 版後已棄用: 从 Python 3.6 开始，弃用对 *note getgrgid(): 6d6. 中
     的 float 或 string 等非 integer 参数的支持。

 -- 函式: grp.getgrnam (name)

     返回给定组名的组数据库条目。 如果找不到要求的条目，则会引发 *note
     KeyError: 3e9. 错误。

 -- 函式: grp.getgrall ()

     以任意顺序返回所有可用组条目的列表。

也參考
......

模块 *note pwd: d6.

     用户数据库的接口，与此类似。

模块 *note spwd: f1.

     针对影子密码数据库的接口，与本模块类似。


File: python.info,  Node: crypt —— 检查 Unix 口令的函数,  Next: termios --- POSIX 风格的 tty 控制,  Prev: grp --- 组数据库,  Up: Unix 专有服务

5.35.5 ‘crypt’ —— 检查 Unix 口令的函数
--------------------------------------

`源代码：' Lib/struct.py(1)

__________________________________________________________________

本模块实现了连接 ‘crypt(3)’ 的接口，是一个基于改进 DES 算法的单向散列函
数；更多细节请参阅 Unix man 手册。可能的用途包括保存经过哈希的口令，这样
就可以在不存储实际口令的情况下对其进行验证，或者尝试用字典来破解 Unix 口
令。

请注意，本模块的执行取决于当前系统中 ‘crypt(3)’ 的实际实现。 因此，当前
实现版本可用的扩展均可在本模块使用。

*note 可用性: 1491.: Unix。 在 VxWorks 上不可用。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/struct.py


File: python.info,  Node: 哈希方法,  Next: 模块属性,  Up: crypt —— 检查 Unix 口令的函数

5.35.5.1 哈希方法
.................

3.3 版新加入.

*note crypt: 28. 模块定义了哈希方法的列表（不是所有的方法在所有平台上都
可用）。

 -- Data: crypt.METHOD_SHA512

     基于 SHA-512 哈希函数的模块化加密格式方法，具备 16 个字符的 salt 和
     86个字符的哈希算法。这是最强的哈希算法。

 -- Data: crypt.METHOD_SHA256

     另一种基于 SHA-256 哈希函数的模块化加密格式方法，具备 16 个字符的
     salt 和 43 个字符的哈希算法。

 -- Data: crypt.METHOD_BLOWFISH

     另一种基于 Blowfish 的模块化加密格式方法，有 22 个字符的 salt 和 31
     个字符的哈希算法。

     3.7 版新加入.

 -- Data: crypt.METHOD_MD5

     另一种基于 MD5 哈希函数的模块化加密格式方法，具备 8 个字符的 salt 和
     22 个字符的哈希算法。

 -- Data: crypt.METHOD_CRYPT

     传统的方法，具备 2 个字符的 salt 和 13 个字符的哈希算法。这是最弱的
     方法。


File: python.info,  Node: 模块属性,  Next: 模块函数<2>,  Prev: 哈希方法,  Up: crypt —— 检查 Unix 口令的函数

5.35.5.2 模块属性
.................

3.3 版新加入.

 -- 屬性: crypt.methods

     可用口令哈希算法的列表，形式为 ‘crypt.METHOD_*’ 对象。该列表从最强
     到最弱进行排序。


File: python.info,  Node: 模块函数<2>,  Next: 示例<46>,  Prev: 模块属性,  Up: crypt —— 检查 Unix 口令的函数

5.35.5.3 模块函数
.................

*note crypt: 28. 模块定义了以下函数：

 -- 函式: crypt.crypt (word, salt=None)

     `word' 通常是用户在提示符或图形界面上输入的口令。可选参数 `salt' 要
     么是 *note mksalt(): 484. 返回的字符串，即 ‘crypt.METHOD_*’ 之一（
     尽管不是所有平台都可用），要么就是一个完全加密的包含 salt 值的口令
     ，正如本函数的返回值。如果未给出 `salt'，将使用最强的哈希方法（
     *note methods(): 3c3b. 返回）。

     查验口令通常是传入纯文本密码 `word' ，和之前 *note crypt(): 28. 调
     用的结果进行比较，应该与本次调用的结果相同。

     `salt' (随机的 2 或 16 个字符的字符串，可能带有
     ‘$digit{TX-PL-LABEL}#x60;’ 前缀以提示相关方法) 将被用来扰乱加密算法
     。 `salt' 中的字符必须在 ‘[./a-zA-Z0-9]’ 集合中，但 Modular Crypt
     Format 除外，它会带有 ‘$digit{TX-PL-LABEL}#x60;’ 前缀。

     返回哈希后的口令字符串，将由 salt 所在字母表中的字符组成。

     由于有些 ‘crypt(3)’ 扩展允许不同的值， `salt' 大小也可不同，建议在
     查验口令时采用完整的加密后口令作为 salt。

     3.3 版更變: 除了字符串之外， `salt' 还可接受 ‘crypt.METHOD_*’ 值。

 -- 函式: crypt.mksalt (method=None, *, rounds=None)

     返回用指定方法随机生成的 salt。如果没有给出 `method'，则使用 *note
     methods(): 3c3b. 返回的最强方法。

     返回一个字符串，可用作传入 *note crypt(): 28. 的 `salt' 参数。

     `rounds' 指定了 ‘METHOD_SHA256’, ‘METHOD_SHA512’ 和
     ‘METHOD_BLOWFISH’ 的循环次数。 对于 ‘METHOD_SHA256’ 和
     ‘METHOD_SHA512’ 而言，必须为介于 ‘1000’ 和 ‘999_999_999’ 之间的整数
     ，默认值为 ‘5000’。 而对于 ‘METHOD_BLOWFISH’，则必须为 ‘16’ (2^4) 和
     ‘2_147_483_648’ (2^31) 之间的二的幂，默认值为 ‘4096’ (2^12)。

     3.3 版新加入.

     3.7 版更變: 加入 `rounds' 参数。


File: python.info,  Node: 示例<46>,  Prev: 模块函数<2>,  Up: crypt —— 检查 Unix 口令的函数

5.35.5.4 示例
.............

以下简单示例演示了典型用法（需要一个时间固定的比较操作来限制留给计时攻击
的暴露面。 *note hmac.compare_digest(): aea. 即很适用）：

     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

采用当前强度最高的方法生成哈希值，并与原口令进行核对：

     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")


File: python.info,  Node: termios --- POSIX 风格的 tty 控制,  Next: tty --- 终端控制功能,  Prev: crypt —— 检查 Unix 口令的函数,  Up: Unix 专有服务

5.35.6 ‘termios’ — POSIX 风格的 tty 控制
----------------------------------------

__________________________________________________________________

此模块提供了针对tty I/O 控制的 POSIX 调用的接口。 有关此类调用的完整描述
，请参阅 ‘termios(3)’ Unix 指南页。 它仅在当安装时配置了支持 POSIX
`termios' 风格的 tty I/O 控制的 Unix 版本上可用。

此模块中的所有函数均接受一个文件描述符 `fd' 作为第一个参数。 这可以是一
个整数形式的文件描述符，例如 ‘sys.stdin.fileno()’ 所返回的对象，或是一个
*note file object: c14.，例如 ‘sys.stdin’ 本身。

这个模块还定义了与此处所提供的函数一起使用的所有必要的常量；这些常量与它
们在 C 中的对应常量同名。 请参考你的系统文档了解有关如何使用这些终端控制
接口的更多信息。

这个模块定义了以下函数：

 -- 函式: termios.tcgetattr (fd)

     对于文件描述符 `fd' 返回一个包含 tty 属性的列表，形式如下: ‘[iflag,
     oflag, cflag, lflag, ispeed, ospeed, cc]’，其中 `cc' 为一个包含 tty
     特殊字符的列表（每一项都是长度为 1 的字符串，索引号为 ‘VMIN’ 和
     ‘VTIME’ 的项除外，这些字段如有定义则应为整数）。 对旗标和速度以及
     `cc' 数组中索引的解读必须使用在 *note termios: 104. 模块中定义的符
     号常量来完成。

 -- 函式: termios.tcsetattr (fd, when, attributes)

     根据 `attributes' 列表设置文件描述符 `fd' 的 tty 属性，该列表即
     *note tcgetattr(): 3c41. 所返回的对象。 `when' 参数确定何时改变属性
     : ‘TCSANOW’ 表示立即改变，‘TCSADRAIN’ 表示在传输所有队列输出后再改
     变，或 ‘TCSAFLUSH’ 表示在传输所有队列输出并丢失所有队列输入后再改变
     。

 -- 函式: termios.tcsendbreak (fd, duration)

     在文件描述符 `fd' 上发送一个中断。 `duration' 为零表示发送时长为
     0.25–0.5 秒的中断；`duration' 非零值的含义取决于具体系统。

 -- 函式: termios.tcdrain (fd)

     进入等待状态直到写入文件描述符 `fd' 的所有输出都传送完毕。

 -- 函式: termios.tcflush (fd, queue)

     在文件描述符 `fd' 上丢弃队列数据。 `queue' 选择器指定哪个队列:
     ‘TCIFLUSH’ 表示输入队列，‘TCOFLUSH’ 表示输出队列，或 ‘TCIOFLUSH’ 表
     示两个队列同时。

 -- 函式: termios.tcflow (fd, action)

     在文件描述符 `fd' 上挂起一战恢复输入或输出。 `action' 参数可以为
     ‘TCOOFF’ 表示挂起输出，‘TCOON’ 表示重启输出，‘TCIOFF’ 表示挂起输入
     ，或 ‘TCION’ 表示重启输入。

也參考
......

模块 *note tty: 11e.

     针对常用终端控制操作的便捷函数。

* Menu:

* 示例: 示例<47>.


File: python.info,  Node: 示例<47>,  Up: termios --- POSIX 风格的 tty 控制

5.35.6.1 示例
.............

这个函数可提示输入密码并且关闭回显。 请注意其采取的技巧是使用一个单独的
*note tcgetattr(): 3c41. 调用和一个 *note try: e37. ...  *note finally:
2bc. 语句来确保旧的 tty 属性无论在何种情况下都会被原样保存:

     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


File: python.info,  Node: tty --- 终端控制功能,  Next: pty --- 伪终端工具,  Prev: termios --- POSIX 风格的 tty 控制,  Up: Unix 专有服务

5.35.7 ‘tty’ — 终端控制功能
---------------------------

`Source code:' Lib/tty.py(1)

__________________________________________________________________

*note tty: 11e. 模块定义了将 tty 放入 cbreak 和 raw 模式的函数。

因为它需要 *note termios: 104. 模块，所以只能在 Unix 上运行。

*note tty: 11e. 模块定义了以下函数：

 -- 函式: tty.setraw (fd, when=termios.TCSAFLUSH)

     将文件描述符 `fd' 的模式更改为 raw 。如果 `when' 被省略，则默认为
     ‘termios.TCSAFLUSH’ ，并传递给 *note termios.tcsetattr(): 3c42. 。

 -- 函式: tty.setcbreak (fd, when=termios.TCSAFLUSH)

     将文件描述符 `fd' 的模式更改为 cbreak 。如果 `when' 被省略，则默认
     为 ‘termios.TCSAFLUSH’ ，并传递给 *note termios.tcsetattr(): 3c42.
     。

也參考
......

模块 *note termios: 104.

     低级终端控制接口。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/tty.py


File: python.info,  Node: pty --- 伪终端工具,  Next: fcntl —— 系统调用 fcntl 和 ioctl,  Prev: tty --- 终端控制功能,  Up: Unix 专有服务

5.35.8 ‘pty’ — 伪终端工具
-------------------------

`源代码:' Lib/pty.py(1)

__________________________________________________________________

*note pty: d5. 模块定义了一些处理“伪终端”概念的操作：启动另一个进程并能
以程序方式在其控制终端中进行读写。

由于伪终端处理高度依赖于具体平台，因此此功能只有针对 Linux 的代码。 （
Linux 代码也可在其他平台上工作，但是未经测试。）

*note pty: d5. 模块定义了下列函数:

 -- 函式: pty.fork ()

     分叉。 将子进程的控制终端连接到一个伪终端。 返回值为 ‘(pid, fd)’。
     请注意子进程获得 `pid' 0 而 `fd' 为 `invalid'。 父进程返回值为子进
     程的 `pid' 而 `fd' 为一个连接到子进程的控制终端（并同时连接到子进程
     的标准输入和输出）的文件描述符。

 -- 函式: pty.openpty ()

     打开一个新的伪终端对，如果可能将使用 *note os.openpty(): 208b.，或
     是针对通用 Unix 系统的模拟代码。 返回一个文件描述符对 ‘(master,
     slave)’，分别表示主从两端。

 -- 函式: pty.spawn (argv[, master_read[, stdin_read]])

     生成一个进程，并将其控制终端连接到当前进程的标准 io。 这常被用来应
     对坚持要从控制终端读取数据的程序。 在 pty 背后生成的进程预期最后将
     被终止，而且当它被终止时 `spawn' 将会返回。

     会向 `master_read' 和 `stdin_read' 函数传入一个文件描述符供它们读取
     ，并且它们总是应当返回一个字节串。 为了强制 spawn 在子进程退出之前
     返回所以应当抛出 *note OSError: 304.。

     两个函数的默认实现在每次函数被调用时将读取并返回至多 1024 个字节。
     会向 `master_read' 回调传入伪终端的主文件描述符以从子进程读取输出，
     而向 `stdin_read' 传入文件描述符 0 以从父进程的标准输入读取数据。

     从两个回调返回空字节串会被解读为文件结束 (EOF) 条件，在此之后回调将
     不再被调用。 如果 `stdin_read' 发出 EOF 信号则控制终端就不能再与父
     进程或子进程进行通信。 除非子进程将不带任何输入就退出，否则随后
     `spawn' 将一直循环下去。 如果 `master_read' 发出 EOF 信号则会有相同
     的行为结果（至少是在 Linux 上）。

     如果两个回调都发出 EOF 信号则 `spawn' 可能将永不返回，除非在你的平
     台上当传入三个空列表时 `select' 会抛出一个错误。 这是一个程序缺陷，
     相关文档见 问题 26228(2)。

     从子进程中的 *note os.waitpid(): 760. 返回退出状态值。

     可以使用 ‘waitstatus_to_exitcode()’ 来将退出状态转换为退出码。

     引发一个 *note 审计事件: fa1. ‘pty.spawn’，附带参数 ‘argv’。

     3.4 版更變: *note spawn(): 97f. 现在会从子进程的 *note
     os.waitpid(): 760. 返回状态值。

* Menu:

* 示例: 示例<48>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/pty.py

   (2) https://bugs.python.org/issue26228


File: python.info,  Node: 示例<48>,  Up: pty --- 伪终端工具

5.35.8.1 示例
.............

以下程序的作用类似于 Unix 命令 ‘script(1)’，它使用一个伪终端来记录一个
"typescript" 里终端进程的所有输入和输出:

     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)


File: python.info,  Node: fcntl —— 系统调用 fcntl 和 ioctl,  Next: pipes --- 终端管道接口,  Prev: pty --- 伪终端工具,  Up: Unix 专有服务

5.35.9 ‘fcntl’ —— 系统调用 ‘fcntl’ 和 ‘ioctl’
---------------------------------------------

__________________________________________________________________

本模块基于文件描述符来进行文件控制和 I/O 控制。它是 Unix 系统调用
‘fcntl()’ 和 ‘ioctl()’ 的接口。关于这些调用的完整描述，请参阅 Unix 手册
的 ‘fcntl(2)’ 和 ‘ioctl(2)’ 页面。

本模块的所有函数都接受文件描述符 `fd' 作为第一个参数。可以是一个整数形式
的文件描述符，比如 ‘sys.stdin.fileno()’ 的返回结果，或为 *note
io.IOBase: 30c. 对象，比如 ‘sys.stdin’ 提供一个 *note fileno(): 2069.，
可返回一个真正的文件描述符。

3.3 版更變: 本模块的操作以前触发的是 *note IOError: a73.，现在则会触发
*note OSError: 304.。

3.8 版更變: fcntl 模块现在有了 ‘F_ADD_SEALS’ 、‘F_GET_SEALS’ 和
‘F_SEAL_*’ 常量，用于文件描述符 *note os.memfd_create(): 320. 的封装。

3.9 版更變: 在 macOS 上，fcntl 模块提供 ‘F_GETPATH’ 常量，由文件描述符中
获取文件路径。在 Linux（>=3.15）上，fcntl 模块提供
‘F_OFD_GETLK````F_OFD_SETLK’ 和 ‘F_OFD_SETLKW’ 常量，用于处理打开文件描
述符锁。

这个模块定义了以下函数：

 -- 函式: fcntl.fcntl (fd, cmd, arg=0)

     对文件描述符 `fd' 执行 `cmd' 操作（能够提供 *note fileno(): 2069. 方
     法的文件对象也可以接受）。 `cmd' 可用的值与操作系统有关，在 *note
     fcntl: 7c. 模块中可作为常量使用，名称与相关 C 语言头文件中的一样。
     参数 `arg' 可以是整数或 *note bytes: 172. 对象。若为整数值，则本函
     数的返回值是 C 语言 ‘fcntl()’ 调用的整数返回值。若为字节串，则其代
     表一个二进制结构，比如由 *note struct.pack(): cd6. 创建的数据。该二
     进制数据将被复制到一个缓冲区，缓冲区地址传给 C 调用 ‘fcntl()’。调用
     成功后的返回值位于缓冲区内，转换为一个 *note bytes: 172. 对象。返回
     的对象长度将与 `arg' 参数的长度相同。上限为 1024 字节。如果操作系统
     在缓冲区中返回的信息大于 1024 字节，很可能导致内存段冲突，或更为不
     易察觉的数据错误。

     如果 ‘fcntl()’ 调用失败，会触发 *note OSError: 304.。

     引发一条 *note auditing 事件: fa1. ‘fcntl.fcntl’，参数为 ‘fd’ 、
     ‘cmd’、‘arg’。

 -- 函式: fcntl.ioctl (fd, request, arg=0, mutate_flag=True)

     本函数与 *note fcntl(): 27e8. 函数相同，只是参数的处理更加复杂。

     `request' 参数的上限是 32位。*note termios: 104. 模块中包含了可用作
     `request' 参数其他常量，名称与相关 C 头文件中定义的相同。

     参数 `arg' 可为整数、支持只读缓冲区接口的对象（如 *note bytes: 172.
     ）或支持读写缓冲区接口的对象（如 *note bytearray: 173. ）。

     除了最后一种情况，其他情况下的行为都与 *note fcntl(): 27e8. 函数一
     样。

     如果传入的是个可变缓冲区，那么行为就由 `mutate_flag' 参数决定。

     如果为 False，缓冲区的可变性将被忽略，行为与只读缓冲区一样，只是没
     有了上述 1024 字节的上限——只要传入的缓冲区能容纳操作系统放入的数据
     即可。

     如果 `mutate_flag' 为 True（默认值），那么缓冲区（实际上）会传给底
     层的 系统调用 *note ioctl(): ea2. ，其返回代码则会回传给调用它的
     Python，而缓冲区的新数据则反映了 *note ioctl(): ea2. 的运行结果。这
     里做了一点简化，因为若是给出的缓冲区少于 1024 字节，首先会被复制到
     一个 1024 字节长的静态缓冲区再传给 *note ioctl(): ea2. ，然后把结果
     复制回给出的缓冲区去。

     如果 ‘ioctl()’ 调用失败，则会触发 *note OSError: 304. 异常。

     例子:

          >>> 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])

     触发一条 *note auditing 事件: fa1. ‘fcntl.ioctl’，参数为 ‘fd’ 、
     ‘request’ 、‘arg’。

 -- 函式: fcntl.flock (fd, operation)

     在文件描述符 `fd' 上执行加锁操作 `operation' (也接受能提供 *note
     fileno(): 2069. 方法的文件对象)。 详见 Unix 手册 ‘flock(2)’。 (在某
     些系统中，此函数是用 ‘fcntl()’ 模拟出来的。)

     如果 ‘flock()’ 调用失败，就会触发 *note OSError: 304. 异常。

     触发一条 *note 审计事件: fa1. ‘fcntl.flock’，参数为 ‘fd’ 、
     ‘operation’。

 -- 函式: fcntl.lockf (fd, cmd, len=0, start=0, whence=0)

     本质上是对 *note fcntl(): 27e8. 加锁调用的封装。`fd' 是要加解锁的文
     件描述符（也接受能提供 *note fileno(): 2069. 方法的文件对象），
     `cmd' 是以下值之一：

        * ‘LOCK_UN’ ——解锁

        * ‘LOCK_SH’ —— 获取一个共享锁

        * ‘LOCK_EX’ —— 获取一个独占锁

     如果 `cmd' 为 ‘LOCK_SH’ 或 ‘LOCK_EX’，则还可以与 ‘LOCK_NB’ 进行按位
     或运算，以避免在获取锁时出现阻塞。 如果用了 ‘LOCK_NB’，无法获取锁时
     将触发 *note OSError: 304.，此异常的 `errno' 属性将被设为 ‘EACCES’
     或 ‘EAGAIN’ (视操作系统而定；为了保证可移植性，请检查这两个值)。 至
     少在某些系统上，只有当文件描述符指向需要写入而打开的文件时，才可以
     使用 ‘LOCK_EX’。

     `len' 是要锁定的字节数，`start' 是自 `whence' 开始锁定的字节偏移量
     ，`whence' 与 *note io.IOBase.seek(): 1efb. 的定义一样。

        * ‘0’ —— 自文件起始位置（*note os.SEEK_SET: e59.）。

        * ‘1’ —— 自缓冲区当前位置（ *note os.SEEK_CUR: e5a. ）

        * ‘2’—— 自文件末尾（*note os.SEEK_END: e5b.)

     `start' 的默认值为 0，表示从文件起始位置开始。`len' 的默认值是 0，
     表示加锁至文件末尾。 `whence' 的默认值也是 0。

     触发一条 *note 审计事件: fa1. ‘fcntl.lockf’，参数为 ‘fd’ 、 ‘cmd’、
     ‘len’、 ‘start’、 ‘whence’。

示例（都是运行于符合 SVR4 的系统）：

     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)

注意，在第一个例子中，返回值变量 `rv' 将存有整数；在第二个例子中，该变量
中将存有一个 *note bytes: 172. 对象。`lockdata' 变量的结构布局视系统而定
——因此可能采用 *note flock(): 3671. 调用会更好。

也參考
......

模块 *note os: c4.

     如果 *note os: c4. 模块中存在加锁标志 *note O_SHLOCK: e5c. 和 *note
     O_EXLOCK: e5d. （仅在BSD上），那么 *note os.open(): 758. 函数提供了
     *note lockf(): e17. 和 *note flock(): 3671. 函数的替代方案。


File: python.info,  Node: pipes --- 终端管道接口,  Next: resource --- 资源使用信息,  Prev: fcntl —— 系统调用 fcntl 和 ioctl,  Up: Unix 专有服务

5.35.10 ‘pipes’ — 终端管道接口
------------------------------

`源代码：' Lib/pipes.py(1)

__________________________________________________________________

*note pipes: cc. 定义了一个类用来抽象 `pipeline' 的概念 — 将数据从一个文
件转到另一文件的转换器序列。

由于模块使用了 ‘/bin/sh’ 命令行，因此要求有 POSIX 或兼容 *note
os.system(): e86. 和 *note os.popen(): 3cb. 的终端程序。

*note pipes: cc. 模块定义了以下的类:

 -- 類別: pipes.Template

     对管道的抽象。

示例:

     >>> 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'

* Menu:

* 模板对象::

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/pipes.py


File: python.info,  Node: 模板对象,  Up: pipes --- 终端管道接口

5.35.10.1 模板对象
..................

模板对象有以下方法:

 -- 成員函式: Template.reset ()

     将一个管道模板恢复为初始状态。

 -- 成員函式: Template.clone ()

     返回一个新的等价的管道模板。

 -- 成員函式: Template.debug (flag)

     如果 `flag' 为真值，则启用调试。 否则禁用调试。 当启用调试时，要执
     行的命令会被打印出来，并且会给予终端 ‘set -x’ 命令以输出更详细的信
     息。

 -- 成員函式: Template.append (cmd, kind)

     在末尾添加一个新的动作。 `cmd' 变量必须为一个有效的 bourne 终端命令
     。 `kind' 变量由两个字母组成。

     第一个字母可以为 ‘'-'’ (这表示命令将读取其标准输入), ‘'f'’ (这表示
     命令将读取在命令行中给定的文件) 或 ‘'.'’ (这表示命令将不读取输入，
     因而必须放在前面。)

     类似地，第二个字母可以为 ‘'-'’ (这表示命令将写入到标准输出), ‘'f'’
     (这表示命令将写入在命令行中给定的文件) 或 ‘'.'’ (这表示命令将不执行
     写入，因而必须放在末尾。)

 -- 成員函式: Template.prepend (cmd, kind)

     在开头添加一个新的动作。 请参阅 *note append(): 3c5c. 获取相应参数
     的说明。

 -- 成員函式: Template.open (file, mode)

     返回一个文件类对象，打开到 `file'，但是将从管道读取或写入。 请注意
     只能给出 ‘'r'’, ‘'w'’ 中的一个。

 -- 成員函式: Template.copy (infile, outfile)

     通过管道将 `infile' 拷贝到 `outfile'。


File: python.info,  Node: resource --- 资源使用信息,  Next: nis --- Sun 的 NIS 黄页 接口,  Prev: pipes --- 终端管道接口,  Up: Unix 专有服务

5.35.11 ‘resource’ — 资源使用信息
---------------------------------

__________________________________________________________________

该模块提供了测量和控制程序所利用的系统资源的基本机制。

符号常量被用来指定特定的系统资源，并要求获得关于当前进程或其子进程的使用
信息。

当系统调用失败时，会触发一个 *note OSError: 304. 。

 -- 例外: resource.error

     一个被弃用的 *note OSError: 304. 的别名。

     3.3 版更變: 根据 PEP 3151(1)，这个类是 *note OSError: 304. 的别名。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3151


File: python.info,  Node: 资源限制<2>,  Next: 资源用量,  Up: resource --- 资源使用信息

5.35.11.1 资源限制
..................

资源的使用可以通过下面描述的 *note setrlimit(): 3643. 函数来限制。每个资
源都被一对限制所控制：一个软限制和一个硬限制。软限制是当前的限制，并且可
以由一个进程随着时间的推移而降低或提高。软限制永远不能超过硬限制。硬限制
可以降低到大于软限制的任何数值，但不能提高。（只有拥有超级用户有效UID的
进程才能提高硬限制。)

可以被限制的具体资源取决于系统。它们在 man ‘getrlimit(2)’ 中描述。 下面
列出的资源在底层操作系统支持的情况下被支持；那些不能被操作系统检查或控制
的资源在本模块中没有为这些平台定义。

 -- Data: resource.RLIM_INFINITY

     用来表示无限资源的极限的常数。

 -- 函式: resource.getrlimit (resource)

     返回一个包含 `resource' 当前软限制和硬限制的元组。如果指定了一个无
     效的资源，则触发 *note ValueError: 16d. ，如果底层系统调用意外失败
     ，则引发 *note error: 3c62. 。

 -- 函式: resource.setrlimit (resource, limits)

     设置 `resource' 的新的消耗极限。参数 `limits' 必须是一个由两个整数
     组成的元组 ‘(soft, hard)’ ，描述了新的限制。 *note RLIM_INFINITY:
     3c64. 的值可以用来请求一个无限的限制。

     如果指定了一个无效的资源，如果新的软限制超过了硬限制，或者如果一个
     进程试图提高它的硬限制，将触发 *note ValueError: 16d. 。当资源的硬
     限制或系统限制不是无限时，指定一个 *note RLIM_INFINITY: 3c64. 的限
     制将导致 *note ValueError: 16d. 。 一个有效 UID 为超级用户的进程可
     以请求任何有效的限制值，包括无限，但如果请求的限制超过了系统规定的
     限制，则仍然会产生 *note ValueError: 16d. 。

     如果底层系统调用失败， ‘setrlimit’ 也可能触发 *note error: 3c62. 。

     VxWorks只支持设置 *note RLIMIT_NOFILE: 3c66. 。

     触发一个 *note auditing event: fa1. ‘resource.setrlimit``使用参数
     ``resource’ ， ‘limits’ 。

 -- 函式: resource.prlimit (pid, resource[, limits])

     将 *note setrlimit(): 3643. 和 *note getrlimit(): 3c65. 合并为一个
     函数，支持获取和设置任意进程的资源限制。如果 `pid' 为0，那么该调用
     适用于当前进程。 `resource' 和 `limits' 的含义与 *note setrlimit():
     3643. 相同，只是 `limits' 是可选的。

     当 `limits' 没有给出时，该函数返回进程 `pid' 的 `resource' 限制。当
     `limits' 被给定时，进程的 `resource' 限制被设置，并返回以前的资源限
     制。

     当 `pid' 找不到时，触发 *note ProcessLookupError: a7c. ；当用户没有
     进程的权限时，触发 *note PermissionError: 6f6. 。

     触发一个 *note auditing event: fa1. ‘resource.prlimit’ 带有参数
     ‘pid’ ， ‘resource’ ， ‘limits’ 。

     *note Availability: 1491.: Linux 2.6.36 或更新版本带有 glibc 2.13 或
     更新版本

     3.4 版新加入.

这些符号定义了资源的消耗可以通过下面描述的 *note setrlimit(): 3643. 和
*note getrlimit(): 3c65. 函数来控制。这些符号的值正是 C 程序所使用的常数
。

Unix man 页面 ‘getrlimit(2)’ 列出了可用的资源。注意，并非所有系统都使用
相同的符号或相同的值来表示相同的资源。本模块并不试图掩盖平台的差异——没有
为某一平台定义的符号在该平台上将无法从本模块中获得。

 -- Data: resource.RLIMIT_CORE

     当前进程可以创建的核心文件的最大大小（以字节为单位）。如果需要更大
     的核心文件来包含整个进程的镜像，这可能会导致创建一个部分核心文件。

 -- Data: resource.RLIMIT_CPU

     一个进程可以使用的最大处理器时间（以秒为单位）。如果超过了这个限制
     ，一个 ‘SIGXCPU’ 信号将被发送给进程。（）参见 *note signal: ea. 模
     块文档，了解如何捕捉这个信号并做一些有用的事情，例如，将打开的文件
     刷新到磁盘上）。

 -- Data: resource.RLIMIT_FSIZE

     进程可能创建的文件的最大大小。

 -- Data: resource.RLIMIT_DATA

     进程的堆的最大大小（以字节为单位）。

 -- Data: resource.RLIMIT_STACK

     当前进程的调用堆栈的最大大小（字节）。 这只影响到多线程进程中主线程
     的堆栈。

 -- Data: resource.RLIMIT_RSS

     应该提供给进程的最大常驻内存大小。

 -- Data: resource.RLIMIT_NPROC

     当前进程可能创建的最大进程数。

 -- Data: resource.RLIMIT_NOFILE

     当前进程打开的文件描述符的最大数量。

 -- Data: resource.RLIMIT_OFILE

     BSD 对 *note RLIMIT_NOFILE: 3c66. 的命名。

 -- Data: resource.RLIMIT_MEMLOCK

     可能被锁定在内存中的最大地址空间。

 -- Data: resource.RLIMIT_VMEM

     进程可能占用的最大映射内存区域。

 -- Data: resource.RLIMIT_AS

     进程可能占用的地址空间的最大区域（以字节为单位）。

 -- Data: resource.RLIMIT_MSGQUEUE

     可分配给 POSIX 消息队列的字节数。

     *note Availability: 1491.: Linux 2.6.8 或更新版本。

     3.4 版新加入.

 -- Data: resource.RLIMIT_NICE

     进程的 Nice 级别的上限（计算为 20 - rlim_cur ）。

     *note Availability: 1491.: Linux 2.6.12 或更新版本

     3.4 版新加入.

 -- Data: resource.RLIMIT_RTPRIO

     实时优先级的上限。

     *note Availability: 1491.: Linux 2.6.12 或更新版本

     3.4 版新加入.

 -- Data: resource.RLIMIT_RTTIME

     在实时调度下，一个进程在不进行阻塞性系统调用的情况下，可以花费的
     CPU 时间限制（以微秒计）。

     *note Availability: 1491.: Linux 2.6.25 或更新版本

     3.4 版新加入.

 -- Data: resource.RLIMIT_SIGPENDING

     进程可能排队的信号数量。

     *note Availability: 1491.: Linux 2.6.8 或更新版本。

     3.4 版新加入.

 -- Data: resource.RLIMIT_SBSIZE

     这个用户使用的套接字缓冲区的最大大小（字节数）。这限制了这个用户在
     任何时候都可以持有的网络内存数量，因此也限制了 mbufs 的数量。

     *note Availability: 1491.: FreeBSD 9 或更新版本

     3.4 版新加入.

 -- Data: resource.RLIMIT_SWAP

     这个用户 ID 的所有进程可能保留或使用的交换空间的最大大小（字节数）
     。这个限制只有在 vm.overcommit sysctl的第 1 位被置 1 时才会被强制执
     行。请参阅 tuning(7)(1) 以获得关于这个系统检测器的完整介绍。

     *note Availability: 1491.: FreeBSD 9 或更新版本

     3.4 版新加入.

 -- Data: resource.RLIMIT_NPTS

     该用户 ID 创建的伪终端的最大数量。

     *note Availability: 1491.: FreeBSD 9 或更新版本

     3.4 版新加入.

   ---------- Footnotes ----------

   (1) https://www.freebsd.org/cgi/man.cgi?query=tuning&sektion=7


File: python.info,  Node: 资源用量,  Prev: 资源限制<2>,  Up: resource --- 资源使用信息

5.35.11.2 资源用量
..................

这些函数被用来检索资源使用信息。

 -- 函式: resource.getrusage (who)

     这个函数返回一个对象，描述当前进程或其子进程所消耗的资源，由 `who'
     参数指定。 `who' 参数应该使用下面描述的 ‘RUSAGE_*’ 常数之一来指定。

     一个简单的示例：

          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))

     返回值的字段分别描述了某一特定系统资源的使用情况，例如，在用户模式
     下运行的时间或进程从主内存中换出的次数。有些值取决于内部的时钟周期
     ，例如进程使用的内存量。

     为了向后兼容，返回值也可以作为一个 16 个元素的元组来访问。

     返回值中的 ‘ru_utime’ 和 ‘ru_stime’ 字段是浮点值，分别代表在用户模
     式下执行的时间和在系统模式下执行的时间。其余的值是整数。关于这些值
     的详细信息，请查阅 ‘getrusage(2)’ man page 。这里介绍一个简短的摘要
     。

     索引         域                        资源
                                            
     -----------------------------------------------------------------------------------
                                            
     ‘0’          ‘ru_utime’                用户模式下的时间（浮点数秒）
                                            
                                            
     ‘1’          ‘ru_stime’                系统模式下的时间（浮点数秒）
                                            
                                            
     ‘2’          ‘ru_maxrss’               最大的常驻内存大小
                                            
                                            
     ‘3’          ‘ru_ixrss’                共享内存大小
                                            
                                            
     ‘4’          ‘ru_idrss’                未共享的内存大小
                                            
                                            
     ‘5’          ‘ru_isrss’                未共享的堆栈大小
                                            
                                            
     ‘6’          ‘ru_minflt’               不需要 I/O 的页面故障
                                            
                                            
     ‘7’          ‘ru_majflt’               需要 I/O 的页面故障数
                                            
                                            
     ‘8’          ‘ru_nswap’                swap out 的数量
                                            
                                            
     ‘9’          ‘ru_inblock’              块写入操作数
                                            
                                            
     ‘10’         ‘ru_oublock’              块输出操作数
                                            
                                            
     ‘11’         ‘ru_msgsnd’               发送消息数
                                            
                                            
     ‘12’         ‘ru_msgrcv’               收到消息数
                                            
                                            
     ‘13’         ‘ru_nsignals’             收到信号数
                                            
                                            
     ‘14’         ‘ru_nvcsw’                主动上下文切换
                                            
                                            
     ‘15’         ‘ru_nivcsw’               被动上下文切换
                                            

     如果指定了一个无效的 `who' 参数，这个函数将触发一个 *note
     ValueError: 16d. 。在特殊情况下，它也可能触发 *note error: 3c62. 异
     常。

 -- 函式: resource.getpagesize ()

     返回一个系统页面的字节数。（这不需要和硬件页的大小相同）。

下面的 ‘RUSAGE_*’ 符号被传递给 *note getrusage(): e5e. 函数，以指定应该
为哪些进程提供信息。

 -- Data: resource.RUSAGE_SELF

     传递给 *note getrusage(): e5e. 以请求调用进程消耗的资源，这是进程中
     所有线程使用的资源总和。

 -- Data: resource.RUSAGE_CHILDREN

     传递给 *note getrusage(): e5e. 以请求被终止和等待的调用进程的子进程
     所消耗的资源。

 -- Data: resource.RUSAGE_BOTH

     传递给 *note getrusage(): e5e. 以请求当前进程和子进程所消耗的资源。
     并非所有系统都能使用。

 -- Data: resource.RUSAGE_THREAD

     传递给 *note getrusage(): e5e. 以请求当前线程所消耗的资源。 并非所
     有系统都能使用。

     3.2 版新加入.


File: python.info,  Node: nis --- Sun 的 NIS 黄页 接口,  Next: Unix syslog 库例程,  Prev: resource --- 资源使用信息,  Up: Unix 专有服务

5.35.12 ‘nis’ — Sun 的 NIS (黄页) 接口
--------------------------------------

__________________________________________________________________

*note nis: bf. 模块提供了对 NIS 库的轻量级包装，适用于多个主机的集中管理
。

因为 NIS 仅存在于 Unix 系统，此模块仅在 Unix 上可用。

*note nis: bf. 模块定义了以下函数：

 -- 函式: nis.match (key, mapname, domain=default_domain)

     返回 `key' 在映射 `mapname' 中的匹配结果，如无结果则会引发错误
     (*note nis.error: 3c79.)。 两个参数都应为字符串，`key' 定长 8 个比
     特。 返回值为任意字节数组（可包含 ‘NULL’ 和其他特殊值）。

     请注意如果 `mapname' 是另一名称的别名则会先检查别名。

     `domain' 参数可允许重载用于查找的 NIS 域。 如果未指定，则会在默认
     NIS 域中查找。

 -- 函式: nis.cat (mapname, domain=default_domain)

     返回一个字典，其元素为 `key' 到 `value' 的映射使得 ‘match(key,
     mapname)==value’。 请注意字典的键和值均为任意字节数组。

     请注意如果 `mapname' 是另一名称的别名则会先检查别名。

     `domain' 参数可允许重载用于查找的 NIS 域。 如果未指定，则会在默认
     NIS 域中查找。

 -- 函式: nis.maps (domain=default_domain)

     返回全部可用映射的列表。

     `domain' 参数可允许重载用于查找的 NIS 域。 如果未指定，则会在默认
     NIS 域中查找。

 -- 函式: nis.get_default_domain ()

     返回系统默认的 NIS 域。

*note nis: bf. 模块定义了以下异常：

 -- 例外: nis.error

     当 NIS 函数返回一个错误码时引发的异常。


File: python.info,  Node: Unix syslog 库例程,  Prev: nis --- Sun 的 NIS 黄页 接口,  Up: Unix 专有服务

5.35.13 Unix syslog 库例程
--------------------------

__________________________________________________________________

此模块提供一个接口到Unix ‘syslog’ 日常库. 参考 Unix 手册页关于 ‘syslog’
设施的详细描述.

此模块包装了系统的 ‘syslog’ 例程族。 一个能与 syslog 服务器对话的纯
Python 库则以 *note logging.handlers: ac. 模块中 ‘SysLogHandler’ 类的形
式提供。

这个模块定义了以下函数：

 -- 函式: syslog.syslog (message)

 -- 函式: syslog.syslog (priority, message)

     将字符串 `message' 发送到系统日志记录器。 如有必要会添加末尾换行符
     。 每条消息都带有一个由 `facility' 和 `level' 组成的优先级标价签。
     可选的 `priority' 参数默认值为 ‘LOG_INFO’，它确定消息的优先级。 如
     果未在 `priority' 中使用逻辑或 (‘LOG_INFO | LOG_USER’) 对 facility
     进行编码，则会使用在 *note openlog(): 10a6. 调用中所给定的值。

     如果 *note openlog(): 10a6. 未在对 *note syslog(): ff. 的调用之前被
     调用，则将不带参数地调用 ‘openlog()’。

     引发 *note 审计事件: fa1. ‘syslog.syslog’ 使用参数 ‘priority’,
     ‘message’.

 -- 函式: syslog.openlog ([ident[, logoption[, facility]]])

     后续 *note syslog(): ff. 调用的日志选项可以通过调用 *note
     openlog(): 10a6. 来设置。 如果日志当前未打开则 *note syslog(): ff.
     将不带参数地调用 *note openlog(): 10a6.。

     可选的 `ident' 关键字参数是在每条消息前添加的字符串，默认为
     ‘sys.argv[0]’ 去除打头的路径部分。 可选的 `logoption' 关键字参数（
     默认为 0）是一个位字段 – 请参见下文了解可能的组合值。 可选的
     `facility' 关键字参数 (默认为 ‘LOG_USER’) 为没有显式编码 facility 的
     消息设置默认的 facility。

     引发 *note 审计事件: fa1. ‘syslog.openlog’ 使用参数 ‘ident’,
     ‘logoption’, ‘facility’.

     3.2 版更變: 在之前的版本中，不允许关键字参数，并且要求必须有
     `ident'。 `ident' 的默认值依赖于系统库，它往往为 ‘python’ 而不是
     Python 程序文件的实际名称。

 -- 函式: syslog.closelog ()

     重置日志模块值并且调用系统库 ‘closelog()’.

     这使得此模块在初始导入时行为固定。 例如，*note openlog(): 10a6. 将
     在首次调用 *note syslog(): ff. 时被调用（如果 *note openlog():
     10a6. 还未被调用过），并且 `ident' 和其他 *note openlog(): 10a6. 形
     参会被重置为默认值。

     引发一个 *note 审计事件: fa1. ‘syslog.closelog’ 不附带任何参数。

 -- 函式: syslog.setlogmask (maskpri)

     将优先级掩码设为 `maskpri' 并返回之前的掩码值。 调用 *note
     syslog(): ff. 并附带未在 `maskpri' 中设置的优先级将会被忽略。 默认
     设置为记录所有优先级。 函数 ‘LOG_MASK(pri)’ 可计算单个优先级 `pri'
     的掩码。 函数 ‘LOG_UPTO(pri)’ 可计算包括 `pri' 在内的所有优先级的掩
     码。

     引发一个 *note 审计事件: fa1. ‘syslog.setlogmask’ 附带参数
     ‘maskpri’。

此模块定义了一下常量:

优先级级别 (高到低):

     ‘LOG_EMERG’, ‘LOG_ALERT’, ‘LOG_CRIT’, ‘LOG_ERR’, ‘LOG_WARNING’,
     ‘LOG_NOTICE’, ‘LOG_INFO’, ‘LOG_DEBUG’.

设施:

     ‘LOG_KERN’, ‘LOG_USER’, ‘LOG_MAIL’, ‘LOG_DAEMON’, ‘LOG_AUTH’,
     ‘LOG_LPR’, ‘LOG_NEWS’, ‘LOG_UUCP’, ‘LOG_CRON’, ‘LOG_SYSLOG’,
     ‘LOG_LOCAL0’ to ‘LOG_LOCAL7’，如果 ‘<syslog.h>’ 中有定义则还有
     ‘LOG_AUTHPRIV’。

日志选项:

     ‘LOG_PID’, ‘LOG_CONS’, ‘LOG_NDELAY’，如果 ‘<syslog.h>’ 中有定义则还
     有 ‘LOG_ODELAY’, ‘LOG_NOWAIT’ 以及 ‘LOG_PERROR’。

* Menu:

* 示例: 示例<49>.


File: python.info,  Node: 示例<49>,  Up: Unix syslog 库例程

5.35.13.1 示例
..............

* Menu:

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


File: python.info,  Node: 简单示例<2>,  Up: 示例<49>

5.35.13.2 简单示例
..................

一个简单的示例集:

     import syslog

     syslog.syslog('Processing started')
     if error:
         syslog.syslog(syslog.LOG_ERR, 'Processing started')

一个设置多种日志选项的示例，其中有在日志消息中包含进程 ID，以及将消息写
入用于邮件日志记录的目标设施等:

     syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_MAIL)
     syslog.syslog('E-mail processing initiated...')


File: python.info,  Node: 被取代的模块,  Next: 未创建文档的模块,  Prev: Unix 专有服务,  Up: Python 標準函式庫 Standard Library

5.36 被取代的模块
=================

本章中描述的模块均已弃用，仅保留用于向后兼容。 它们已经被其他模块所取代
。

* Menu:

* optparse: optparse --- 解析器的命令行选项. 解析器的命令行选项
* imp —— 由代码内部访问 import 。::


File: python.info,  Node: optparse --- 解析器的命令行选项,  Next: imp —— 由代码内部访问 import 。,  Up: 被取代的模块

5.36.1 ‘optparse’ — 解析器的命令行选项
--------------------------------------

`源代码：' Lib/optparse.py(1)

3.2 版後已棄用: *note optparse: c3. 模块已被弃用并且将不再继续开发；开发
将转至 *note argparse: 5. 模块进行。

__________________________________________________________________

*note optparse: c3. 是一个相比原有 *note getopt: 85. 模块更为方便、灵活
和强大的命令行选项解析库。 *note optparse: c3. 使用更为显明的命令行解析
风格：创建一个 *note OptionParser: 3c85. 的实例，向其中填充选项，然后解
析命令行。 *note optparse: c3. 允许用户以传统的 GNU/POSIX 语法来指定选项
，并为你生成额外的用法和帮助消息。

下面是在一个简单脚本中使用 *note optparse: c3. 的示例:

     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()

With these few lines of code, users of your script can now do the "usual
thing" on the command-line, for example:

     <yourscript> --file=outfile -q

As it parses the command line, *note optparse: c3. sets attributes of
the ‘options’ object returned by ‘parse_args()’ based on user-supplied
command-line values.  When ‘parse_args()’ returns from parsing this
command line, ‘options.filename’ will be ‘"outfile"’ and
‘options.verbose’ will be ‘False’.  *note optparse: c3. supports both
long and short options, allows short options to be merged together, and
allows options to be associated with their arguments in a variety of
ways.  Thus, the following command lines are all equivalent to the above
example:

     <yourscript> -f outfile --quiet
     <yourscript> --quiet --file outfile
     <yourscript> -q -foutfile
     <yourscript> -qfoutfile

Additionally, users can run one of the following

     <yourscript> -h
     <yourscript> --help

and *note optparse: c3. will print out a brief summary of your script’s
options:

     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

where the value of `yourscript' is determined at runtime (normally from
‘sys.argv[0]’).

* Menu:

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

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/optparse.py


File: python.info,  Node: 背景,  Next: 教程<2>,  Up: optparse --- 解析器的命令行选项

5.36.1.1 背景
.............

*note optparse: c3. was explicitly designed to encourage the creation of
programs with straightforward, conventional command-line interfaces.  To
that end, it supports only the most common command-line syntax and
semantics conventionally used under Unix.  If you are unfamiliar with
these conventions, read this section to acquaint yourself with them.

* Menu:

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


File: python.info,  Node: 术语,  Next: What are options for?,  Up: 背景

5.36.1.2 术语
.............

参数

     a string entered on the command-line, and passed by the shell to
     ‘execl()’ or ‘execv()’.  In Python, arguments are elements of
     ‘sys.argv[1:]’ (‘sys.argv[0]’ is the name of the program being
     executed).  Unix shells also use the term "word".

     It is occasionally desirable to substitute an argument list other
     than ‘sys.argv[1:]’, so you should read "argument" as "an element
     of ‘sys.argv[1:]’, or of some other list provided as a substitute
     for ‘sys.argv[1:]’".

选项

     an argument used to supply extra information to guide or customize
     the execution of a program.  There are many different syntaxes for
     options; the traditional Unix syntax is a hyphen ("-") followed by
     a single letter, e.g.  ‘-x’ or ‘-F’.  Also, traditional Unix syntax
     allows multiple options to be merged into a single argument, e.g.
     ‘-x -F’ is equivalent to ‘-xF’.  The GNU project introduced ‘--’
     followed by a series of hyphen-separated words, e.g.  ‘--file’ or
     ‘--dry-run’.  These are the only two option syntaxes provided by
     *note optparse: c3.

     Some other option syntaxes that the world has seen include:

        * a hyphen followed by a few letters, e.g.  ‘-pf’ (this is `not'
          the same as multiple options merged into a single argument)

        * a hyphen followed by a whole word, e.g.  ‘-file’ (this is
          technically equivalent to the previous syntax, but they aren’t
          usually seen in the same program)

        * a plus sign followed by a single letter, or a few letters, or
          a word, e.g.  ‘+f’, ‘+rgb’

        * a slash followed by a letter, or a few letters, or a word,
          e.g.  ‘/f’, ‘/file’

     These option syntaxes are not supported by *note optparse: c3, and
     they never will be.  This is deliberate: the first three are
     non-standard on any environment, and the last only makes sense if
     you’re exclusively targeting VMS, MS-DOS, and/or Windows.

可选参数:

     an argument that follows an option, is closely associated with that
     option, and is consumed from the argument list when that option is.
     With *note optparse: c3, option arguments may either be in a
     separate argument from their option:

          -f foo
          --file foo

     or included in the same argument:

          -ffoo
          --file=foo

     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 ‘-a’ takes an optional argument and ‘-b’ is
     another option entirely, how do we interpret ‘-ab’?  Because of
     this ambiguity, *note optparse: c3. does not support this feature.

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.

必选选项

     an option that must be supplied on the command-line; note that the
     phrase "required option" is self-contradictory in English.  *note
     optparse: c3. doesn’t prevent you from implementing required
     options, but doesn’t give you much help at it either.

For example, consider this hypothetical command-line:

     prog -v --report report.txt foo bar

‘-v’ and ‘--report’ are both options.  Assuming that ‘--report’ takes
one argument, ‘report.txt’ is an option argument.  ‘foo’ and ‘bar’ are
positional arguments.


File: python.info,  Node: What are options for?,  Next: 位置位置,  Prev: 术语,  Up: 背景

5.36.1.3 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
`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 ‘find’, ‘tar’, and ‘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 `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
‘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, ‘cp’ fails if you run it with no arguments.  However, it has a
flexible, useful syntax that does not require any options at all:

     cp SOURCE DEST
     cp SOURCE ... DEST-DIR

You can get pretty far with just that.  Most ‘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 ‘cp’, which is to copy either one file to
another, or several files to another directory.


File: python.info,  Node: 位置位置,  Prev: What are options for?,  Up: 背景

5.36.1.4 位置位置
.................

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 `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.


File: python.info,  Node: 教程<2>,  Next: 参考指南,  Prev: 背景,  Up: optparse --- 解析器的命令行选项

5.36.1.5 教程
.............

While *note optparse: c3. 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 *note optparse: c3.-based program.

First, you need to import the OptionParser class; then, early in the
main program, create an OptionParser instance:

     from optparse import OptionParser
     ...
     parser = OptionParser()

Then you can start defining options.  The basic syntax is:

     parser.add_option(opt_str, ...,
                       attr=value, ...)

Each option has one or more option strings, such as ‘-f’ or ‘--file’,
and several option attributes that tell *note optparse: c3. 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.:

     parser.add_option("-f", "--file", ...)

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 *note OptionParser.add_option(): 21cd. are
effectively labels for the option defined by that call.  For brevity, we
will frequently refer to `encountering an option' on the command line;
in reality, *note optparse: c3. encounters `option strings' and looks up
options from them.

Once all of your options are defined, instruct *note optparse: c3. to
parse your program’s command line:

     (options, args) = parser.parse_args()

(If you like, you can pass a custom argument list to ‘parse_args()’, but
that’s rarely necessary: by default it uses ‘sys.argv[1:]’.)

‘parse_args()’ 返回两个值：

   * ‘options’, an object containing values for all of your options—e.g.
     if ‘--file’ takes a single string argument, then ‘options.file’
     will be the filename supplied by the user, or ‘None’ if the user
     did not supply that option

   * ‘args’, the list of positional arguments leftover after parsing
     options

This tutorial section only covers the four most important option
attributes: *note action: 3c90, *note type: 3c91, *note dest: 3c92.
(destination), and *note help: 3c93.  Of these, *note action: 3c90. 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::


File: python.info,  Node: Understanding option actions,  Next: The store action,  Up: 教程<2>

5.36.1.6 Understanding option actions
.....................................

Actions tell *note optparse: c3. what to do when it encounters an option
on the command line.  There is a fixed set of actions hard-coded into
*note optparse: c3.; adding new actions is an advanced topic covered in
section *note Extending optparse: 3c96.  Most actions tell *note
optparse: c3. to store a value in some variable—for example, take a
string from the command line and store it in an attribute of ‘options’.

If you don’t specify an option action, *note optparse: c3. defaults to
‘store’.


File: python.info,  Node: The store action,  Next: Handling boolean flag options,  Prev: Understanding option actions,  Up: 教程<2>

5.36.1.7 The store action
.........................

The most common option action is ‘store’, which tells *note optparse:
c3. 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.

例如:

     parser.add_option("-f", "--file",
                       action="store", type="string", dest="filename")

Now let’s make up a fake command line and ask *note optparse: c3. to
parse it:

     args = ["-f", "foo.txt"]
     (options, args) = parser.parse_args(args)

When *note optparse: c3. sees the option string ‘-f’, it consumes the
next argument, ‘foo.txt’, and stores it in ‘options.filename’.  So,
after this call to ‘parse_args()’, ‘options.filename’ is ‘"foo.txt"’.

Some other option types supported by *note optparse: c3. are ‘int’ and
‘float’.  Here’s an option that expects an integer argument:

     parser.add_option("-n", type="int", dest="num")

Note that this option has no long option string, which is perfectly
acceptable.  Also, there’s no explicit action, since the default is
‘store’.

Let’s parse another fake command-line.  This time, we’ll jam the option
argument right up against the option: since ‘-n42’ (one argument) is
equivalent to ‘-n 42’ (two arguments), the code

     (options, args) = parser.parse_args(["-n42"])
     print(options.num)

will print ‘42’.

If you don’t specify a type, *note optparse: c3. assumes ‘string’.
Combined with the fact that the default action is ‘store’, that means
our first example can be a lot shorter:

     parser.add_option("-f", "--file", dest="filename")

If you don’t supply a destination, *note optparse: c3. figures out a
sensible default from the option strings: if the first long option
string is ‘--foo-bar’, then the default destination is ‘foo_bar’.  If
there are no long option strings, *note optparse: c3. looks at the first
short option string: the default destination for ‘-f’ is ‘f’.

*note optparse: c3. also includes the built-in ‘complex’ type.  Adding
types is covered in section *note Extending optparse: 3c96.


File: python.info,  Node: Handling boolean flag options,  Next: Other actions,  Prev: The store action,  Up: 教程<2>

5.36.1.8 Handling boolean (flag) options
........................................

Flag options—set a variable to true or false when a particular option is
seen—are quite common.  *note optparse: c3. supports them with two
separate actions, ‘store_true’ and ‘store_false’.  For example, you
might have a ‘verbose’ flag that is turned on with ‘-v’ and off with
‘-q’:

     parser.add_option("-v", action="store_true", dest="verbose")
     parser.add_option("-q", action="store_false", dest="verbose")

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 *note optparse: c3. encounters ‘-v’ on the command line, it sets
‘options.verbose’ to ‘True’; when it encounters ‘-q’, ‘options.verbose’
is set to ‘False’.


File: python.info,  Node: Other actions,  Next: 默认值,  Prev: Handling boolean flag options,  Up: 教程<2>

5.36.1.9 Other actions
......................

Some other actions supported by *note optparse: c3. are:

‘"store_const"’

     store a constant value

‘"append"’

     append this option’s argument to a list

‘"count"’

     increment a counter by one

‘"callback"’

     调用指定函数

These are covered in section *note 参考指南: 3c9d, and section *note
Option Callbacks: 3c9e.


File: python.info,  Node: 默认值,  Next: Generating help,  Prev: Other actions,  Up: 教程<2>

5.36.1.10 默认值
................

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 ‘None’.  This is usually fine, but sometimes you
want more control.  *note optparse: c3. 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 *note optparse:
c3. to set ‘verbose’ to ‘True’ unless ‘-q’ is seen, then we can do this:

     parser.add_option("-v", action="store_true", dest="verbose", default=True)
     parser.add_option("-q", action="store_false", dest="verbose")

Since default values apply to the `destination' rather than to any
particular option, and these two options happen to have the same
destination, this is exactly equivalent:

     parser.add_option("-v", action="store_true", dest="verbose")
     parser.add_option("-q", action="store_false", dest="verbose", default=True)

考虑一下：

     parser.add_option("-v", action="store_true", dest="verbose", default=False)
     parser.add_option("-q", action="store_false", dest="verbose", default=True)

Again, the default value for ‘verbose’ will be ‘True’: the last default
value supplied for any particular destination is the one that counts.

A clearer way to specify default values is the ‘set_defaults()’ method
of OptionParser, which you can call at any time before calling
‘parse_args()’:

     parser.set_defaults(verbose=True)
     parser.add_option(...)
     (options, args) = parser.parse_args()

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.


File: python.info,  Node: Generating help,  Next: Printing a version string,  Prev: 默认值,  Up: 教程<2>

5.36.1.11 Generating help
.........................

*note optparse: c3.’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 *note help: 3c93. value for
each option, and optionally a short usage message for your whole
program.  Here’s an OptionParser populated with user-friendly
(documented) options:

     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]")

If *note optparse: c3. encounters either ‘-h’ or ‘--help’ on the
command-line, or if you just call ‘parser.print_help()’, it prints the
following to standard output:

     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]

(If the help output is triggered by a help option, *note optparse: c3.
exits after printing the help text.)

There’s a lot going on here to help *note optparse: c3. generate the
best possible help message:

   * the script defines its own usage message:

          usage = "usage: %prog [options] arg1 arg2"

     *note optparse: c3. expands ‘%prog’ in the usage string to the name
     of the current program, i.e.  ‘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, *note optparse: c3. uses a
     bland but sensible default: ‘"Usage: %prog [options]"’, which is
     fine if your script doesn’t take any positional arguments.

   * every option defines a help string, and doesn’t worry about
     line-wrapping—*note optparse: c3. takes care of wrapping lines and
     making the help output look good.

   * options that take a value indicate this fact in their
     automatically-generated help message, e.g.  for the "mode" option:

          -m MODE, --mode=MODE

     Here, "MODE" is called the meta-variable: it stands for the
     argument that the user is expected to supply to ‘-m’/‘--mode’.  By
     default, *note optparse: c3. converts the destination variable name
     to uppercase and uses that for the meta-variable.  Sometimes,
     that’s not what you want—for example, the ‘--filename’ option
     explicitly sets ‘metavar="FILE"’, resulting in this
     automatically-generated option description:

          -f FILE, --filename=FILE

     This is important for more than just saving space, though: the
     manually written help text uses the meta-variable ‘FILE’ to clue
     the user in that there’s a connection between the semi-formal
     syntax ‘-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.

   * options that have a default value can include ‘%default’ in the
     help string—*note optparse: c3. will replace it with *note str():
     205. of the option’s default value.  If an option has no default
     value (or the default value is ‘None’), ‘%default’ expands to
     ‘none’.

* Menu:

* Grouping Options::


File: python.info,  Node: Grouping Options,  Up: Generating help

5.36.1.12 Grouping Options
..........................

When dealing with many options, it is convenient to group these options
for better help output.  An *note OptionParser: 3c85. can contain
several option groups, each of which can contain several options.

An option group is obtained using the class *note OptionGroup: 3ca4.:

 -- 類別: optparse.OptionGroup (parser, title, description=None)

     where

        * parser is the *note OptionParser: 3c85. instance the group
          will be inserted in to

        * title is the group title

        * description, optional, is a long description of the group

*note OptionGroup: 3ca4. inherits from ‘OptionContainer’ (like *note
OptionParser: 3c85.) and so the ‘add_option()’ method can be used to add
an option to the group.

Once all the options are declared, using the *note OptionParser: 3c85.
method ‘add_option_group()’ the group is added to the previously defined
parser.

Continuing with the parser defined in the previous section, adding an
*note OptionGroup: 3ca4. to a parser is easy:

     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)

This would result in the following help output:

     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.

A bit more complete example might involve using more than one group:
still extending the previous 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)

that results in the following output:

     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

Another interesting method, in particular when working programmatically
with option groups is:

 -- 成員函式: OptionParser.get_option_group (opt_str)

     Return the *note OptionGroup: 3ca4. to which the short or long
     option string `opt_str' (e.g.  ‘'-o'’ or ‘'--option'’) belongs.  If
     there’s no such *note OptionGroup: 3ca4, return ‘None’.


File: python.info,  Node: Printing a version string,  Next: How optparse handles errors,  Prev: Generating help,  Up: 教程<2>

5.36.1.13 Printing a version string
...................................

Similar to the brief usage string, *note optparse: c3. can also print a
version string for your program.  You have to supply the string as the
‘version’ argument to OptionParser:

     parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")

‘%prog’ is expanded just like it is in ‘usage’.  Apart from that,
‘version’ can contain anything you like.  When you supply it, *note
optparse: c3. automatically adds a ‘--version’ option to your parser.
If it encounters this option on the command line, it expands your
‘version’ string (by replacing ‘%prog’), prints it to stdout, and exits.

For example, if your script is called ‘/usr/bin/foo’:

     $ /usr/bin/foo --version
     foo 1.0

The following two methods can be used to print and get the ‘version’
string:

 -- 成員函式: OptionParser.print_version (file=None)

     Print the version message for the current program (‘self.version’)
     to `file' (default stdout).  As with *note print_usage(): 3ca9, any
     occurrence of ‘%prog’ in ‘self.version’ is replaced with the name
     of the current program.  Does nothing if ‘self.version’ is empty or
     undefined.

 -- 成員函式: OptionParser.get_version ()

     Same as *note print_version(): 3ca8. but returns the version string
     instead of printing it.


File: python.info,  Node: How optparse handles errors,  Next: Putting it all together,  Prev: Printing a version string,  Up: 教程<2>

5.36.1.14 How ‘optparse’ handles errors
.......................................

There are two broad classes of errors that *note optparse: c3. has to
worry about: programmer errors and user errors.  Programmer errors are
usually erroneous calls to *note OptionParser.add_option(): 21cd, e.g.
invalid option strings, unknown option attributes, missing option
attributes, etc.  These are dealt with in the usual way: raise an
exception (either ‘optparse.OptionError’ or *note TypeError: 1fe.) 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.  *note optparse: c3. can
automatically detect some user errors, such as bad option arguments
(passing ‘-n 4x’ where ‘-n’ takes an integer argument), missing
arguments (‘-n’ at the end of the command line, where ‘-n’ takes an
argument of any type).  Also, you can call ‘OptionParser.error()’ to
signal an application-defined error condition:

     (options, args) = parser.parse_args()
     ...
     if options.a and options.b:
         parser.error("options -a and -b are mutually exclusive")

In either case, *note optparse: c3. 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 ‘4x’ to an
option that takes an integer:

     $ /usr/bin/foo -n 4x
     Usage: foo [options]

     foo: error: option -n: invalid integer value: '4x'

Or, where the user fails to pass a value at all:

     $ /usr/bin/foo -n
     Usage: foo [options]

     foo: error: -n option requires an argument

*note optparse: c3.-generated error messages take care always to mention
the option involved in the error; be sure to do the same when calling
‘OptionParser.error()’ from your application code.

If *note optparse: c3.’s default error-handling behaviour does not suit
your needs, you’ll need to subclass OptionParser and override its
‘exit()’ and/or ‘error()’ methods.


File: python.info,  Node: Putting it all together,  Prev: How optparse handles errors,  Up: 教程<2>

5.36.1.15 Putting it all together
.................................

Here’s what *note optparse: c3.-based scripts usually look like:

     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()


File: python.info,  Node: 参考指南,  Next: Option Callbacks,  Prev: 教程<2>,  Up: optparse --- 解析器的命令行选项

5.36.1.16 参考指南
..................

* Menu:

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


File: python.info,  Node: 创建解析器,  Next: 填充解析器,  Up: 参考指南

5.36.1.17 创建解析器
....................

The first step in using *note optparse: c3. is to create an OptionParser
instance.

 -- 類別: 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.

     ‘usage’ (默认: ‘"%prog [options]"’)

          The usage summary to print when your program is run
          incorrectly or with a help option.  When *note optparse: c3.
          prints the usage string, it expands ‘%prog’ to
          ‘os.path.basename(sys.argv[0])’ (or to ‘prog’ if you passed
          that keyword argument).  To suppress a usage message, pass the
          special value ‘optparse.SUPPRESS_USAGE’.

     ‘option_list’ (默认: ‘[]’)

          A list of Option objects to populate the parser with.  The
          options in ‘option_list’ are added after any options in
          ‘standard_option_list’ (a class attribute that may be set by
          OptionParser subclasses), but before any version or help
          options.  Deprecated; use *note add_option(): 21cd. after
          creating the parser instead.

     ‘option_class’ (默认: optparse.Option)

          Class to use when adding options to the parser in *note
          add_option(): 21cd.

     ‘version’ (默认: ‘None’)

          A version string to print when the user supplies a version
          option.  If you supply a true value for ‘version’, *note
          optparse: c3. automatically adds a version option with the
          single option string ‘--version’.  The substring ‘%prog’ is
          expanded the same as for ‘usage’.

     ‘conflict_handler’ (默认: ‘"error"’)

          Specifies what to do when options with conflicting option
          strings are added to the parser; see section *note Conflicts
          between options: 3cb2.

     ‘description’ (默认: ‘None’)

          A paragraph of text giving a brief overview of your program.
          *note optparse: c3. reformats this paragraph to fit the
          current terminal width and prints it when the user requests
          help (after ‘usage’, but before the list of options).

     ‘formatter’ (default: a new ‘IndentedHelpFormatter’)

          An instance of optparse.HelpFormatter that will be used for
          printing help text.  *note optparse: c3. provides two concrete
          classes for this purpose: IndentedHelpFormatter and
          TitledHelpFormatter.

     ‘add_help_option’ (默认: ‘True’)

          If true, *note optparse: c3. will add a help option (with
          option strings ‘-h’ and ‘--help’) to the parser.

     ‘prog’

          The string to use when expanding ‘%prog’ in ‘usage’ and
          ‘version’ instead of ‘os.path.basename(sys.argv[0])’.

     ‘epilog’ (默认: ‘None’)

          A paragraph of help text to print after the option help.


File: python.info,  Node: 填充解析器,  Next: 定义选项,  Prev: 创建解析器,  Up: 参考指南

5.36.1.18 填充解析器
....................

There are several ways to populate the parser with options.  The
preferred way is by using *note OptionParser.add_option(): 21cd, as
shown in section *note 教程: 3c8e.  ‘add_option()’ can be called in one
of two ways:

   * pass it an Option instance (as returned by ‘make_option()’)

   * pass it any combination of positional and keyword arguments that
     are acceptable to ‘make_option()’ (i.e., to the Option
     constructor), and it will create the Option instance for you

The other alternative is to pass a list of pre-constructed Option
instances to the OptionParser constructor, as in:

     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)

(‘make_option()’ is a factory function for creating Option instances;
currently it is an alias for the Option constructor.  A future version
of *note optparse: c3. may split Option into several classes, and
‘make_option()’ will pick the right class to instantiate.  Do not
instantiate Option directly.)


File: python.info,  Node: 定义选项,  Next: Option attributes,  Prev: 填充解析器,  Up: 参考指南

5.36.1.19 定义选项
..................

Each Option instance represents a set of synonymous command-line option
strings, e.g.  ‘-f’ and ‘--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 ‘Option’ instance is with the
‘add_option()’ method of *note OptionParser: 3c85.

 -- 成員函式: OptionParser.add_option (option)

 -- 成員函式: OptionParser.add_option (*opt_str, attr=value, ...)

     To define an option with only a short option string:

          parser.add_option("-f", attr=value, ...)

     And to define an option with only a long option string:

          parser.add_option("--foo", attr=value, ...)

     The keyword arguments define attributes of the new Option object.
     The most important option attribute is *note action: 3c90, and it
     largely determines which other attributes are relevant or required.
     If you pass irrelevant option attributes, or fail to pass required
     ones, *note optparse: c3. raises an ‘OptionError’ exception
     explaining your mistake.

     An option’s `action' determines what *note optparse: c3. does when
     it encounters this option on the command-line.  The standard option
     actions hard-coded into *note optparse: c3. are:

     ‘"store"’

          存储此选项的参数（默认）

     ‘"store_const"’

          store a constant value

     ‘"store_true"’

          store ‘True’

     ‘"store_false"’

          store ‘False’

     ‘"append"’

          append this option’s argument to a list

     ‘"append_const"’

          将常量值附加到列表

     ‘"count"’

          increment a counter by one

     ‘"callback"’

          调用指定函数

     ‘"help"’

          打印用法消息，包括所有选项和文档

     (If you don’t supply an action, the default is ‘"store"’.  For this
     action, you may also supply *note type: 3c91. and *note dest: 3c92.
     option attributes; see *note Standard option actions: 3cb7.)

As you can see, most actions involve storing or updating a value
somewhere.  *note optparse: c3. always creates a special object for
this, conventionally called ‘options’ (it happens to be an instance of
‘optparse.Values’).  Option arguments (and various other values) are
stored as attributes of this object, according to the *note dest: 3c92.
(destination) option attribute.

For example, when you call

     parser.parse_args()

one of the first things *note optparse: c3. does is create the ‘options’
object:

     options = Values()

If one of the options in this parser is defined with

     parser.add_option("-f", "--file", action="store", type="string", dest="filename")

and the command-line being parsed includes any of the following:

     -ffoo
     -f foo
     --file=foo
     --file foo

then *note optparse: c3, on seeing this option, will do the equivalent
of

     options.filename = "foo"

The *note type: 3c91. and *note dest: 3c92. option attributes are almost
as important as *note action: 3c90, but *note action: 3c90. is the only
one that makes sense for `all' options.


File: python.info,  Node: Option attributes,  Next: Standard option actions,  Prev: 定义选项,  Up: 参考指南

5.36.1.20 Option attributes
...........................

The following option attributes may be passed as keyword arguments to
*note OptionParser.add_option(): 21cd.  If you pass an option attribute
that is not relevant to a particular option, or fail to pass a required
option attribute, *note optparse: c3. raises ‘OptionError’.

 -- 屬性: Option.action

     (默认: ‘"store"’)

     Determines *note optparse: c3.’s behaviour when this option is seen
     on the command line; the available options are documented *note
     here: 3cb7.

 -- 屬性: Option.type

     (默认: ‘"string"’)

     The argument type expected by this option (e.g., ‘"string"’ or
     ‘"int"’); the available option types are documented *note here:
     3cba.

 -- 屬性: Option.dest

     (default: derived from option strings)

     If the option’s action implies writing or modifying a value
     somewhere, this tells *note optparse: c3. where to write it: *note
     dest: 3c92. names an attribute of the ‘options’ object that *note
     optparse: c3. builds as it parses the command line.

 -- 屬性: Option.default

     The value to use for this option’s destination if the option is not
     seen on the command line.  See also *note
     OptionParser.set_defaults(): 3cbc.

 -- 屬性: Option.nargs

     (默认: 1)

     How many arguments of type *note type: 3c91. should be consumed
     when this option is seen.  If > 1, *note optparse: c3. will store a
     tuple of values to *note dest: 3c92.

 -- 屬性: Option.const

     For actions that store a constant value, the constant value to
     store.

 -- 屬性: Option.choices

     For options of type ‘"choice"’, the list of strings the user may
     choose from.

 -- 屬性: Option.callback

     For options with action ‘"callback"’, the callable to call when
     this option is seen.  See section *note Option Callbacks: 3c9e. for
     detail on the arguments passed to the callable.

 -- 屬性: Option.callback_args
 -- 屬性: Option.callback_kwargs

     Additional positional and keyword arguments to pass to ‘callback’
     after the four standard callback arguments.

 -- 屬性: Option.help

     Help text to print for this option when listing all available
     options after the user supplies a *note help: 3c93. option (such as
     ‘--help’).  If no help text is supplied, the option will be listed
     without help text.  To hide this option, use the special value
     ‘optparse.SUPPRESS_HELP’.

 -- 屬性: Option.metavar

     (default: derived from option strings)

     Stand-in for the option argument(s) to use when printing help text.
     See section *note 教程: 3c8e. for an example.


File: python.info,  Node: Standard option actions,  Next: Standard option types,  Prev: Option attributes,  Up: 参考指南

5.36.1.21 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 *note optparse: c3.’s behaviour; a few have
required attributes, which you must specify for any option using that
action.

   * ‘"store"’ [relevant: *note type: 3c91, *note dest: 3c92, *note
     nargs: 3cbd, *note choices: 3cbf.]

     The option must be followed by an argument, which is converted to a
     value according to *note type: 3c91. and stored in *note dest:
     3c92.  If *note nargs: 3cbd. > 1, multiple arguments will be
     consumed from the command line; all will be converted according to
     *note type: 3c91. and stored to *note dest: 3c92. as a tuple.  See
     the *note Standard option types: 3cba. section.

     If *note choices: 3cbf. is supplied (a list or tuple of strings),
     the type defaults to ‘"choice"’.

     If *note type: 3c91. is not supplied, it defaults to ‘"string"’.

     If *note dest: 3c92. is not supplied, *note optparse: c3. derives a
     destination from the first long option string (e.g., ‘--foo-bar’
     implies ‘foo_bar’).  If there are no long option strings, *note
     optparse: c3. derives a destination from the first short option
     string (e.g., ‘-f’ implies ‘f’).

     示例:

          parser.add_option("-f")
          parser.add_option("-p", type="float", nargs=3, dest="point")

     As it parses the command line

          -f foo.txt -p 1 -3.5 4 -fbar.txt

     *note optparse: c3. will set

          options.f = "foo.txt"
          options.point = (1.0, -3.5, 4.0)
          options.f = "bar.txt"

   * ‘"store_const"’ [required: *note const: 3cbe.; relevant: *note
     dest: 3c92.]

     The value *note const: 3cbe. is stored in *note dest: 3c92.

     示例:

          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")

     If ‘--noisy’ is seen, *note optparse: c3. will set

          options.verbose = 2

   * ‘"store_true"’ [relevant: *note dest: 3c92.]

     A special case of ‘"store_const"’ that stores ‘True’ to *note dest:
     3c92.

   * ‘"store_false"’ [relevant: *note dest: 3c92.]

     Like ‘"store_true"’, but stores ‘False’.

     示例:

          parser.add_option("--clobber", action="store_true", dest="clobber")
          parser.add_option("--no-clobber", action="store_false", dest="clobber")

   * ‘"append"’ [relevant: *note type: 3c91, *note dest: 3c92, *note
     nargs: 3cbd, *note choices: 3cbf.]

     The option must be followed by an argument, which is appended to
     the list in *note dest: 3c92.  If no default value for *note dest:
     3c92. is supplied, an empty list is automatically created when
     *note optparse: c3. first encounters this option on the
     command-line.  If *note nargs: 3cbd. > 1, multiple arguments are
     consumed, and a tuple of length *note nargs: 3cbd. is appended to
     *note dest: 3c92.

     The defaults for *note type: 3c91. and *note dest: 3c92. are the
     same as for the ‘"store"’ action.

     示例:

          parser.add_option("-t", "--tracks", action="append", type="int")

     If ‘-t3’ is seen on the command-line, *note optparse: c3. does the
     equivalent of:

          options.tracks = []
          options.tracks.append(int("3"))

     If, a little later on, ‘--tracks=4’ is seen, it does:

          options.tracks.append(int("4"))

     The ‘append’ action calls the ‘append’ method on the current value
     of the option.  This means that any default value specified must
     have an ‘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:

          >>> parser.add_option("--files", action="append", default=['~/.mypkg/defaults'])
          >>> opts, args = parser.parse_args(['--files', 'overrides.mypkg'])
          >>> opts.files
          ['~/.mypkg/defaults', 'overrides.mypkg']

   * ‘"append_const"’ [required: *note const: 3cbe.; relevant: *note
     dest: 3c92.]

     Like ‘"store_const"’, but the value *note const: 3cbe. is appended
     to *note dest: 3c92.; as with ‘"append"’, *note dest: 3c92.
     defaults to ‘None’, and an empty list is automatically created the
     first time the option is encountered.

   * ‘"count"’ [relevant: *note dest: 3c92.]

     Increment the integer stored at *note dest: 3c92.  If no default
     value is supplied, *note dest: 3c92. is set to zero before being
     incremented the first time.

     示例:

          parser.add_option("-v", action="count", dest="verbosity")

     The first time ‘-v’ is seen on the command line, *note optparse:
     c3. does the equivalent of:

          options.verbosity = 0
          options.verbosity += 1

     Every subsequent occurrence of ‘-v’ results in

          options.verbosity += 1

   * ‘"callback"’ [required: *note callback: 3cc0.; relevant: *note
     type: 3c91, *note nargs: 3cbd, *note callback_args: 3cc1, *note
     callback_kwargs: 3cc2.]

     Call the function specified by *note callback: 3cc0, which is
     called as

          func(option, opt_str, value, parser, *args, **kwargs)

     See section *note Option Callbacks: 3c9e. for more detail.

   * ‘"help"’

     Prints a complete help message for all the options in the current
     option parser.  The help message is constructed from the ‘usage’
     string passed to OptionParser’s constructor and the *note help:
     3c93. string passed to every option.

     If no *note help: 3c93. string is supplied for an option, it will
     still be listed in the help message.  To omit an option entirely,
     use the special value ‘optparse.SUPPRESS_HELP’.

     *note optparse: c3. automatically adds a *note help: 3c93. option
     to all OptionParsers, so you do not normally need to create one.

     示例:

          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)

     If *note optparse: c3. sees either ‘-h’ or ‘--help’ on the command
     line, it will print something like the following help message to
     stdout (assuming ‘sys.argv[0]’ is ‘"foo.py"’):

          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

     After printing the help message, *note optparse: c3. terminates
     your process with ‘sys.exit(0)’.

   * ‘"version"’

     Prints the version number supplied to the OptionParser to stdout
     and exits.  The version number is actually formatted and printed by
     the ‘print_version()’ method of OptionParser.  Generally only
     relevant if the ‘version’ argument is supplied to the OptionParser
     constructor.  As with *note help: 3c93. options, you will rarely
     create ‘version’ options, since *note optparse: c3. automatically
     adds them when needed.


File: python.info,  Node: Standard option types,  Next: 解析参数<2>,  Prev: Standard option actions,  Up: 参考指南

5.36.1.22 Standard option types
...............................

*note optparse: c3. has five built-in option types: ‘"string"’, ‘"int"’,
‘"choice"’, ‘"float"’ and ‘"complex"’.  If you need to add new option
types, see section *note Extending optparse: 3c96.

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 ‘"int"’) are parsed as follows:

   * if the number starts with ‘0x’, it is parsed as a hexadecimal
     number

   * if the number starts with ‘0’, it is parsed as an octal number

   * if the number starts with ‘0b’, it is parsed as a binary number

   * otherwise, the number is parsed as a decimal number

The conversion is done by calling *note int(): 204. with the appropriate
base (2, 8, 10, or 16).  If this fails, so will *note optparse: c3,
although with a more useful error message.

‘"float"’ and ‘"complex"’ option arguments are converted directly with
*note float(): 1fd. and *note complex(): 2c1, with similar
error-handling.

‘"choice"’ options are a subtype of ‘"string"’ options.  The *note
choices: 3cbf. option attribute (a sequence of strings) defines the set
of allowed option arguments.  ‘optparse.check_choice()’ compares
user-supplied option arguments against this master list and raises
‘OptionValueError’ if an invalid string is given.


File: python.info,  Node: 解析参数<2>,  Next: Querying and manipulating your option parser,  Prev: Standard option types,  Up: 参考指南

5.36.1.23 解析参数
..................

The whole point of creating and populating an OptionParser is to call
its ‘parse_args()’ method:

     (options, args) = parser.parse_args(args=None, values=None)

输入参数的位置

‘args’

     the list of arguments to process (default: ‘sys.argv[1:]’)

‘values’

     an ‘optparse.Values’ object to store option arguments in (default:
     a new instance of ‘Values’) – if you give an existing object, the
     option defaults will not be initialized on it

and the return values are

‘options’

     the same object that was passed in as ‘values’, or the
     optparse.Values instance created by *note optparse: c3.

‘args’

     the leftover positional arguments after all options have been
     processed

The most common usage is to supply neither keyword argument.  If you
supply ‘values’, it will be modified with repeated *note setattr():
1712. calls (roughly one for every option argument stored to an option
destination) and returned by ‘parse_args()’.

If ‘parse_args()’ encounters any errors in the argument list, it calls
the OptionParser’s ‘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).


File: python.info,  Node: Querying and manipulating your option parser,  Next: Conflicts between options,  Prev: 解析参数<2>,  Up: 参考指南

5.36.1.24 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:

 -- 成員函式: OptionParser.disable_interspersed_args ()

     Set parsing to stop on the first non-option.  For example, if ‘-a’
     and ‘-b’ are both simple options that take no arguments, *note
     optparse: c3. normally accepts this syntax:

          prog -a arg1 -b arg2

     and treats it as equivalent to

          prog -a -b arg1 arg2

     To disable this feature, call *note disable_interspersed_args():
     21ce.  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.

 -- 成員函式: 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.

 -- 成員函式: OptionParser.get_option (opt_str)

     Returns the Option instance with the option string `opt_str', or
     ‘None’ if no options have that option string.

 -- 成員函式: OptionParser.has_option (opt_str)

     Return ‘True’ if the OptionParser has an option with option string
     `opt_str' (e.g., ‘-q’ or ‘--verbose’).

 -- 成員函式: OptionParser.remove_option (opt_str)

     If the *note OptionParser: 3c85. has an option corresponding to
     `opt_str', that option is removed.  If that option provided any
     other option strings, all of those option strings become invalid.
     If `opt_str' does not occur in any option belonging to this *note
     OptionParser: 3c85, raises *note ValueError: 16d.


File: python.info,  Node: Conflicts between options,  Next: 清理<2>,  Prev: Querying and manipulating your option parser,  Up: 参考指南

5.36.1.25 Conflicts between options
...................................

If you’re not careful, it’s easy to define options with conflicting
option strings:

     parser.add_option("-n", "--dry-run", ...)
     ...
     parser.add_option("-n", "--noisy", ...)

(This is particularly true if you’ve defined your own OptionParser
subclass with some standard options.)

Every time you add an option, *note optparse: c3. 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:

     parser = OptionParser(..., conflict_handler=handler)

or with a separate call:

     parser.set_conflict_handler(handler)

The available conflict handlers are:

     ‘"error"’ (默认)

          assume option conflicts are a programming error and raise
          ‘OptionConflictError’

     ‘"resolve"’

          resolve option conflicts intelligently (see below)

As an example, let’s define an *note OptionParser: 3c85. that resolves
conflicts intelligently and add conflicting options to it:

     parser = OptionParser(conflict_handler="resolve")
     parser.add_option("-n", "--dry-run", ..., help="do no harm")
     parser.add_option("-n", "--noisy", ..., help="be noisy")

At this point, *note optparse: c3. detects that a previously-added
option is already using the ‘-n’ option string.  Since
‘conflict_handler’ is ‘"resolve"’, it resolves the situation by removing
‘-n’ from the earlier option’s list of option strings.  Now ‘--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:

     Options:
       --dry-run     do no harm
       ...
       -n, --noisy   be noisy

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, *note optparse: c3.
removes that option completely, so it doesn’t show up in help text or
anywhere else.  Carrying on with our existing OptionParser:

     parser.add_option("--dry-run", ..., help="new dry-run option")

At this point, the original ‘-n’/‘--dry-run’ option is no longer
accessible, so *note optparse: c3. removes it, leaving this help text:

     Options:
       ...
       -n, --noisy   be noisy
       --dry-run     new dry-run option


File: python.info,  Node: 清理<2>,  Next: Other methods,  Prev: Conflicts between options,  Up: 参考指南

5.36.1.26 清理
..............

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 ‘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.


File: python.info,  Node: Other methods,  Prev: 清理<2>,  Up: 参考指南

5.36.1.27 Other methods
.......................

OptionParser supports several other public methods:

 -- 成員函式: OptionParser.set_usage (usage)

     Set the usage string according to the rules described above for the
     ‘usage’ constructor keyword argument.  Passing ‘None’ sets the
     default usage string; use ‘optparse.SUPPRESS_USAGE’ to suppress a
     usage message.

 -- 成員函式: OptionParser.print_usage (file=None)

     Print the usage message for the current program (‘self.usage’) to
     `file' (default stdout).  Any occurrence of the string ‘%prog’ in
     ‘self.usage’ is replaced with the name of the current program.
     Does nothing if ‘self.usage’ is empty or not defined.

 -- 成員函式: OptionParser.get_usage ()

     Same as *note print_usage(): 3ca9. but returns the usage string
     instead of printing it.

 -- 成員函式: OptionParser.set_defaults (dest=value, ...)

     Set default values for several option destinations at once.  Using
     *note set_defaults(): 3cbc. 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:

          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

     To avoid this confusion, use *note set_defaults(): 3cbc.:

          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")


File: python.info,  Node: Option Callbacks,  Next: Extending optparse,  Prev: 参考指南,  Up: optparse --- 解析器的命令行选项

5.36.1.28 Option Callbacks
..........................

When *note optparse: c3.’s built-in actions and types aren’t quite
enough for your needs, you have two choices: extend *note optparse: c3.
or define a callback option.  Extending *note optparse: c3. 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:

   * define the option itself using the ‘"callback"’ action

   * write the callback; this is a function (or method) that takes at
     least four arguments, as described below

* 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.


File: python.info,  Node: Defining a callback option,  Next: How callbacks are called,  Up: Option Callbacks

5.36.1.29 Defining a callback option
....................................

As always, the easiest way to define a callback option is by using the
*note OptionParser.add_option(): 21cd. method.  Apart from *note action:
3c90, the only option attribute you must specify is ‘callback’, the
function to call:

     parser.add_option("-c", action="callback", callback=my_callback)

‘callback’ is a function (or other callable object), so you must have
already defined ‘my_callback()’ when you create this callback option.
In this simple case, *note optparse: c3. doesn’t even know if ‘-c’ takes
any arguments, which usually means that the option takes no
arguments—the mere presence of ‘-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.

*note optparse: c3. always passes four particular arguments to your
callback, and it will only pass additional arguments if you specify them
via *note callback_args: 3cc1. and *note callback_kwargs: 3cc2.  Thus,
the minimal callback function signature is:

     def my_callback(option, opt, value, parser):

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:

*note type: 3c91.

     has its usual meaning: as with the ‘"store"’ or ‘"append"’ actions,
     it instructs *note optparse: c3. to consume one argument and
     convert it to *note type: 3c91.  Rather than storing the converted
     value(s) anywhere, though, *note optparse: c3. passes it to your
     callback function.

*note nargs: 3cbd.

     also has its usual meaning: if it is supplied and > 1, *note
     optparse: c3. will consume *note nargs: 3cbd. arguments, each of
     which must be convertible to *note type: 3c91.  It then passes a
     tuple of converted values to your callback.

*note callback_args: 3cc1.

     a tuple of extra positional arguments to pass to the callback

*note callback_kwargs: 3cc2.

     a dictionary of extra keyword arguments to pass to the callback


File: python.info,  Node: How callbacks are called,  Next: Raising errors in a callback,  Prev: Defining a callback option,  Up: Option Callbacks

5.36.1.30 How callbacks are called
..................................

All callbacks are called as follows:

     func(option, opt_str, value, parser, *args, **kwargs)

where

‘option’

     is the Option instance that’s calling the callback

‘opt_str’

     is the option string seen on the command-line that’s triggering the
     callback.  (If an abbreviated long option was used, ‘opt_str’ will
     be the full, canonical option string—e.g.  if the user puts ‘--foo’
     on the command-line as an abbreviation for ‘--foobar’, then
     ‘opt_str’ will be ‘"--foobar"’.)

‘value’

     is the argument to this option seen on the command-line.  *note
     optparse: c3. will only expect an argument if *note type: 3c91. is
     set; the type of ‘value’ will be the type implied by the option’s
     type.  If *note type: 3c91. for this option is ‘None’ (no argument
     expected), then ‘value’ will be ‘None’.  If *note nargs: 3cbd. > 1,
     ‘value’ will be a tuple of values of the appropriate type.

‘parser’

     is the OptionParser instance driving the whole thing, mainly useful
     because you can access some other interesting data through its
     instance attributes:

     ‘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 ‘parser.largs’, e.g.  by
          adding more arguments to it.  (This list will become ‘args’,
          the second return value of ‘parse_args()’.)

     ‘parser.rargs’

          the current list of remaining arguments, ie.  with ‘opt_str’
          and ‘value’ (if applicable) removed, and only the arguments
          following them still there.  Feel free to modify
          ‘parser.rargs’, e.g.  by consuming more arguments.

     ‘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 *note optparse: c3. 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.

‘args’

     is a tuple of arbitrary positional arguments supplied via the *note
     callback_args: 3cc1. option attribute.

‘kwargs’

     is a dictionary of arbitrary keyword arguments supplied via *note
     callback_kwargs: 3cc2.


File: python.info,  Node: Raising errors in a callback,  Next: Callback example 1 trivial callback,  Prev: How callbacks are called,  Up: Option Callbacks

5.36.1.31 Raising errors in a callback
......................................

The callback function should raise ‘OptionValueError’ if there are any
problems with the option or its argument(s).  *note optparse: c3.
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.


File: python.info,  Node: Callback example 1 trivial callback,  Next: Callback example 2 check option order,  Prev: Raising errors in a callback,  Up: Option Callbacks

5.36.1.32 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:

     def record_foo_seen(option, opt_str, value, parser):
         parser.values.saw_foo = True

     parser.add_option("--foo", action="callback", callback=record_foo_seen)

Of course, you could do that with the ‘"store_true"’ action.


File: python.info,  Node: Callback example 2 check option order,  Next: Callback example 3 check option order generalized,  Prev: Callback example 1 trivial callback,  Up: Option Callbacks

5.36.1.33 Callback example 2: check option order
................................................

Here’s a slightly more interesting example: record the fact that ‘-a’ is
seen, but blow up if it comes after ‘-b’ in the command-line.

     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")


File: python.info,  Node: Callback example 3 check option order generalized,  Next: Callback example 4 check arbitrary condition,  Prev: Callback example 2 check option order,  Up: Option Callbacks

5.36.1.34 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 ‘-b’ has already been seen), it needs a bit of
work: the error message and the flag that it sets must be generalized.

     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')


File: python.info,  Node: Callback example 4 check arbitrary condition,  Next: Callback example 5 fixed arguments,  Prev: Callback example 3 check option order generalized,  Up: Option Callbacks

5.36.1.35 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:

     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")

(The definition of ‘is_moon_full()’ is left as an exercise for the
reader.)


File: python.info,  Node: Callback example 5 fixed arguments,  Next: Callback example 6 variable arguments,  Prev: Callback example 4 check arbitrary condition,  Up: Option Callbacks

5.36.1.36 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 ‘"store"’ or ‘"append"’
option: if you define *note type: 3c91, then the option takes one
argument that must be convertible to that type; if you further define
*note nargs: 3cbd, then the option takes *note nargs: 3cbd. arguments.

Here’s an example that just emulates the standard ‘"store"’ action:

     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")

Note that *note optparse: c3. 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.)


File: python.info,  Node: Callback example 6 variable arguments,  Prev: Callback example 5 fixed arguments,  Up: Option Callbacks

5.36.1.37 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 *note optparse:
c3. doesn’t provide any built-in capabilities for it.  And you have to
deal with certain intricacies of conventional Unix command-line parsing
that *note optparse: c3. normally handles for you.  In particular,
callbacks should implement the conventional rules for bare ‘--’ and ‘-’
arguments:

   * either ‘--’ or ‘-’ can be option arguments

   * bare ‘--’ (if not the argument to some option): halt command-line
     processing and discard the ‘--’

   * bare ‘-’ (if not the argument to some option): halt command-line
     processing but keep the ‘-’ (append it to ‘parser.largs’)

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 *note optparse: c3.
doesn’t support this sort of thing directly).

Nevertheless, here’s a stab at a callback for an option with variable
arguments:

     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)


File: python.info,  Node: Extending optparse,  Prev: Option Callbacks,  Up: optparse --- 解析器的命令行选项

5.36.1.38 Extending ‘optparse’
..............................

Since the two major controlling factors in how *note optparse: c3.
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::


File: python.info,  Node: Adding new types,  Next: Adding new actions,  Up: Extending optparse

5.36.1.39 Adding new types
..........................

To add new types, you need to define your own subclass of *note
optparse: c3.’s ‘Option’ class.  This class has a couple of attributes
that define *note optparse: c3.’s types: *note TYPES: 3ceb. and *note
TYPE_CHECKER: 3cec.

 -- 屬性: Option.TYPES

     A tuple of type names; in your subclass, simply define a new tuple
     *note TYPES: 3ceb. that builds on the standard one.

 -- 屬性: Option.TYPE_CHECKER

     A dictionary mapping type names to type-checking functions.  A
     type-checking function has the following signature:

          def check_mytype(option, opt, value)

     where ‘option’ is an ‘Option’ instance, ‘opt’ is an option string
     (e.g., ‘-f’), and ‘value’ is the string from the command line that
     must be checked and converted to your desired type.
     ‘check_mytype()’ should return an object of the hypothetical type
     ‘mytype’.  The value returned by a type-checking function will wind
     up in the OptionValues instance returned by
     ‘OptionParser.parse_args()’, or be passed to a callback as the
     ‘value’ parameter.

     Your type-checking function should raise ‘OptionValueError’ if it
     encounters any problems.  ‘OptionValueError’ takes a single string
     argument, which is passed as-is to *note OptionParser: 3c85.’s
     ‘error()’ method, which in turn prepends the program name and the
     string ‘"error:"’ and prints everything to stderr before
     terminating the process.

Here’s a silly example that demonstrates adding a ‘"complex"’ option
type to parse Python-style complex numbers on the command line.  (This
is even sillier than it used to be, because *note optparse: c3. 1.3
added built-in support for complex numbers, but never mind.)

First, the necessary imports:

     from copy import copy
     from optparse import Option, OptionValueError

You need to define your type-checker first, since it’s referred to later
(in the *note TYPE_CHECKER: 3cec. class attribute of your Option
subclass):

     def check_complex(option, opt, value):
         try:
             return complex(value)
         except ValueError:
             raise OptionValueError(
                 "option %s: invalid complex value: %r" % (opt, value))

Finally, the Option subclass:

     class MyOption (Option):
         TYPES = Option.TYPES + ("complex",)
         TYPE_CHECKER = copy(Option.TYPE_CHECKER)
         TYPE_CHECKER["complex"] = check_complex

(If we didn’t make a *note copy(): 25. of *note Option.TYPE_CHECKER:
3cec, we would end up modifying the *note TYPE_CHECKER: 3cec. attribute
of *note optparse: c3.’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 *note optparse: c3.-based script, except you have to
instruct your OptionParser to use MyOption instead of Option:

     parser = OptionParser(option_class=MyOption)
     parser.add_option("-c", type="complex")

Alternately, you can build your own option list and pass it to
OptionParser; if you don’t use ‘add_option()’ in the above way, you
don’t need to tell OptionParser which option class to use:

     option_list = [MyOption("-c", action="store", type="complex", dest="c")]
     parser = OptionParser(option_list=option_list)


File: python.info,  Node: Adding new actions,  Prev: Adding new types,  Up: Extending optparse

5.36.1.40 Adding new actions
............................

Adding new actions is a bit trickier, because you have to understand
that *note optparse: c3. has a couple of classifications for actions:

"store" actions

     actions that result in *note optparse: c3. storing a value to an
     attribute of the current OptionValues instance; these options
     require a *note dest: 3c92. attribute to be supplied to the Option
     constructor.

"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 *note type: 3c91. attribute
     to the Option constructor.

These are overlapping sets: some default "store" actions are ‘"store"’,
‘"store_const"’, ‘"append"’, and ‘"count"’, while the default "typed"
actions are ‘"store"’, ‘"append"’, and ‘"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):

 -- 屬性: Option.ACTIONS

     All actions must be listed in ACTIONS.

 -- 屬性: Option.STORE_ACTIONS

     "store" actions are additionally listed here.

 -- 屬性: Option.TYPED_ACTIONS

     "typed" actions are additionally listed here.

 -- 屬性: 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 *note optparse: c3. assigns the default type, ‘"string"’, to
     options with no explicit type whose action is listed in *note
     ALWAYS_TYPED_ACTIONS: 3cf2.

In order to actually implement your new action, you must override
Option’s ‘take_action()’ method and add a case that recognizes your
action.

For example, let’s add an ‘"extend"’ action.  This is similar to the
standard ‘"append"’ action, but instead of taking a single value from
the command-line and appending it to an existing list, ‘"extend"’ will
take multiple values in a single comma-delimited string, and extend an
existing list with them.  That is, if ‘--names’ is an ‘"extend"’ option
of type ‘"string"’, the command line

     --names=foo,bar --names blah --names ding,dong

would result in a list

     ["foo", "bar", "blah", "ding", "dong"]

Again we define a subclass of Option:

     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)

Features of note:

   * ‘"extend"’ both expects a value on the command-line and stores that
     value somewhere, so it goes in both *note STORE_ACTIONS: 3cf0. and
     *note TYPED_ACTIONS: 3cf1.

   * to ensure that *note optparse: c3. assigns the default type of
     ‘"string"’ to ‘"extend"’ actions, we put the ‘"extend"’ action in
     *note ALWAYS_TYPED_ACTIONS: 3cf2. as well.

   * ‘MyOption.take_action()’ implements just this one new action, and
     passes control back to ‘Option.take_action()’ for the standard
     *note optparse: c3. actions.

   * ‘values’ is an instance of the optparse_parser.Values class, which
     provides the very useful ‘ensure_value()’ method.  ‘ensure_value()’
     is essentially *note getattr(): 54b. with a safety valve; it is
     called as

          values.ensure_value(attr, value)

     If the ‘attr’ attribute of ‘values’ doesn’t exist or is ‘None’,
     then ensure_value() first sets it to ‘value’, and then returns
     ’value.  This is very handy for actions like ‘"extend"’,
     ‘"append"’, and ‘"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
     ‘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 ‘None’ and
     ‘ensure_value()’ will take care of getting it right when it’s
     needed.


File: python.info,  Node: imp —— 由代码内部访问 import 。,  Prev: optparse --- 解析器的命令行选项,  Up: 被取代的模块

5.36.2 ‘imp’ —— 由代码内部访问 import 。
----------------------------------------

`源代码：' Lib/imp.py(1)

3.4 版後已棄用: *note imp: 99. 模块已被废弃，请改用 *note importlib:
9a.。

__________________________________________________________________

本模块提供了一个接口，用于实现 *note import: ce7. 语句的机制。这里定义了
以下常量和函数：

 -- 函式: imp.get_magic ()

     Return the magic string value used to recognize byte-compiled code
     files (‘.pyc’ files).  (This value may be different for each Python
     version.)

     3.4 版後已棄用: Use *note importlib.util.MAGIC_NUMBER: 94d.
     instead.

 -- 函式: imp.get_suffixes ()

     Return a list of 3-element tuples, each describing a particular
     type of module.  Each triple has the form ‘(suffix, mode, type)’,
     where `suffix' is a string to be appended to the module name to
     form the filename to search for, `mode' is the mode string to pass
     to the built-in *note open(): 16f. function to open the file (this
     can be ‘'r'’ for text files or ‘'rb'’ for binary files), and `type'
     is the file type, which has one of the values *note PY_SOURCE:
     3cf6, *note PY_COMPILED: 3cf7, or *note C_EXTENSION: 3cf8,
     described below.

     3.3 版後已棄用: Use the constants defined on *note
     importlib.machinery: 9c. instead.

 -- 函式: imp.find_module (name[, path])

     Try to find the module `name'.  If `path' is omitted or ‘None’, the
     list of directory names given by ‘sys.path’ is searched, but first
     a few special places are searched: the function tries to find a
     built-in module with the given name (*note C_BUILTIN: 3cfa.), then
     a frozen module (*note PY_FROZEN: 3cfb.), and on some systems some
     other places are looked in as well (on Windows, it looks in the
     registry which may point to a specific file).

     Otherwise, `path' must be a list of directory names; each directory
     is searched for files with any of the suffixes returned by *note
     get_suffixes(): 3cf5. above.  Invalid names in the list are
     silently ignored (but all list items must be strings).

     If search is successful, the return value is a 3-element tuple
     ‘(file, pathname, description)’:

     `file' is an open *note file object: c14. positioned at the
     beginning, `pathname' is the pathname of the file found, and
     `description' is a 3-element tuple as contained in the list
     returned by *note get_suffixes(): 3cf5. describing the kind of
     module found.

     If the module is built-in or frozen then `file' and `pathname' are
     both ‘None’ and the `description' tuple contains empty strings for
     its suffix and mode; the module type is indicated as given in
     parentheses above.  If the search is unsuccessful, *note
     ImportError: 16c. is raised.  Other exceptions indicate problems
     with the arguments or environment.

     If the module is a package, `file' is ‘None’, `pathname' is the
     package path and the last item in the `description' tuple is *note
     PKG_DIRECTORY: 3cfc.

     This function does not handle hierarchical module names (names
     containing dots).  In order to find `P.M', that is, submodule `M'
     of package `P', use *note find_module(): 3cf9. and *note
     load_module(): 3cfd. to find and load package `P', and then use
     *note find_module(): 3cf9. with the `path' argument set to
     ‘P.__path__’.  When `P' itself has a dotted name, apply this recipe
     recursively.

     3.3 版後已棄用: Use *note importlib.util.find_spec(): a1c. instead
     unless Python 3.3 compatibility is required, in which case use
     *note importlib.find_loader(): a1b.  For example usage of the
     former case, see the *note 示例: 3940. section of the *note
     importlib: 9a. documentation.

 -- 函式: imp.load_module (name, file, pathname, description)

     Load a module that was previously found by *note find_module():
     3cf9. (or by an otherwise conducted search yielding compatible
     results).  This function does more than importing the module: if
     the module was already imported, it will reload the module!  The
     `name' argument indicates the full module name (including the
     package name, if this is a submodule of a package).  The `file'
     argument is an open file, and `pathname' is the corresponding file
     name; these can be ‘None’ and ‘''’, respectively, when the module
     is a package or not being loaded from a file.  The `description'
     argument is a tuple, as would be returned by *note get_suffixes():
     3cf5, describing what kind of module must be loaded.

     If the load is successful, the return value is the module object;
     otherwise, an exception (usually *note ImportError: 16c.) is
     raised.

     `Important:' the caller is responsible for closing the `file'
     argument, if it was not ‘None’, even when an exception is raised.
     This is best done using a *note try: e37. ...  *note finally: 2bc.
     statement.

     3.3 版後已棄用: If previously used in conjunction with *note
     imp.find_module(): 3cf9. then consider using *note
     importlib.import_module(): be6, otherwise use the loader returned
     by the replacement you chose for *note imp.find_module(): 3cf9.  If
     you called *note imp.load_module(): 3cfd. and related functions
     directly with file path arguments then use a combination of *note
     importlib.util.spec_from_file_location(): 653. and *note
     importlib.util.module_from_spec(): 7e1.  See the *note 示例: 3940.
     section of the *note importlib: 9a. documentation for details of
     the various approaches.

 -- 函式: imp.new_module (name)

     Return a new empty module object called `name'.  This object is
     `not' inserted in ‘sys.modules’.

     3.4 版後已棄用: Use *note importlib.util.module_from_spec(): 7e1.
     instead.

 -- 函式: imp.reload (module)

     Reload a previously imported `module'.  The argument must be a
     module object, so it must have been successfully imported before.
     This is useful if you have edited the module source file using an
     external editor and want to try out the new version without leaving
     the Python interpreter.  The return value is the module object (the
     same as the `module' argument).

     When ‘reload(module)’ is executed:

        * Python modules’ code is recompiled and the module-level code
          reexecuted, defining a new set of objects which are bound to
          names in the module’s dictionary.  The ‘init’ function of
          extension modules is not called a second time.

        * 与Python中的所有的其它对象一样，旧的对象只有在引用计数为0之后
          才会被回收。

        * 模块命名空间中的名称重新指向任何新的或更改后的对象。

        * 其他旧对象的引用（例如那个模块的外部名称）不会被重新绑定到引用
          的新对象的，并且如果有需要，必须在出现的每个命名空间中进行更新
          。

     有一些其他注意事项：

     当一个模块被重新加载的时候，它的字典（包含了那个模块的全区变量）会
     被保留。名称的重新定义会覆盖旧的定义，所以通常来说这不是问题。如果
     一个新模块没有定义在旧版本模块中定义的名称，则将保留旧版本中的定义
     。这一特性可用于作为那个模块的优点，如果它维护一个全局表或者对象的
     缓存 —— 使用 *note try: e37. 语句，就可以测试表的存在并且跳过它的初
     始化，如果有需要的话:

          try:
              cache
          except NameError:
              cache = {}

     It is legal though generally not very useful to reload built-in or
     dynamically loaded modules, except for *note sys: fd, *note
     __main__: 1. and *note builtins: 12.  In many cases, however,
     extension modules are not designed to be initialized more than
     once, and may fail in arbitrary ways when reloaded.

     If a module imports objects from another module using *note from:
     d0d. ...  *note import: ce7. ..., calling *note reload(): d38. for
     the other module does not redefine the objects imported from it —
     one way around this is to re-execute the ‘from’ statement, another
     is to use ‘import’ and qualified names (`module'.*name*) instead.

     如果一个模块创建一个类的实例，重新加载定义那个类的模块不影响这个实
     例的方法定义———它们继续使用旧类的定义。对于子类，也是一样的。

     3.3 版更變: Relies on both ‘__name__’ and ‘__loader__’ being
     defined on the module being reloaded instead of just ‘__name__’.

     3.4 版後已棄用: Use *note importlib.reload(): 49f. instead.

The following functions are conveniences for handling PEP 3147(2)
byte-compiled file paths.

3.2 版新加入.

 -- 函式: imp.cache_from_source (path, debug_override=None)

     Return the PEP 3147(3) path to the byte-compiled file associated
     with the source `path'.  For example, if `path' is
     ‘/foo/bar/baz.py’ the return value would be
     ‘/foo/bar/__pycache__/baz.cpython-32.pyc’ for Python 3.2.  The
     ‘cpython-32’ string comes from the current magic tag (see *note
     get_tag(): 3d00.; if ‘sys.implementation.cache_tag’ is not defined
     then *note NotImplementedError: 704. will be raised).  By passing
     in ‘True’ or ‘False’ for `debug_override' you can override the
     system’s value for ‘__debug__’, leading to optimized bytecode.

     `path' need not exist.

     3.3 版更變: If ‘sys.implementation.cache_tag’ is ‘None’, then *note
     NotImplementedError: 704. is raised.

     3.4 版後已棄用: Use *note importlib.util.cache_from_source(): 651.
     instead.

     3.5 版更變: The `debug_override' parameter no longer creates a
     ‘.pyo’ file.

 -- 函式: imp.source_from_cache (path)

     Given the `path' to a PEP 3147(4) file name, return the associated
     source code file path.  For example, if `path' is
     ‘/foo/bar/__pycache__/baz.cpython-32.pyc’ the returned path would
     be ‘/foo/bar/baz.py’.  `path' need not exist, however if it does
     not conform to PEP 3147(5) format, a *note ValueError: 16d. is
     raised.  If ‘sys.implementation.cache_tag’ is not defined, *note
     NotImplementedError: 704. is raised.

     3.3 版更變: Raise *note NotImplementedError: 704. when
     ‘sys.implementation.cache_tag’ is not defined.

     3.4 版後已棄用: Use *note importlib.util.source_from_cache(): 652.
     instead.

 -- 函式: imp.get_tag ()

     Return the PEP 3147(6) magic tag string matching this version of
     Python’s magic number, as returned by *note get_magic(): 94e.

     3.4 版後已棄用: Use ‘sys.implementation.cache_tag’ directly
     starting in Python 3.3.

The following functions help interact with the import system’s internal
locking mechanism.  Locking semantics of imports are an implementation
detail which may vary from release to release.  However, Python ensures
that circular imports work without any deadlocks.

 -- 函式: imp.lock_held ()

     Return ‘True’ if the global import lock is currently held, else
     ‘False’.  On platforms without threads, always return ‘False’.

     On platforms with threads, a thread executing an import first holds
     a global import lock, then sets up a per-module lock for the rest
     of the import.  This blocks other threads from importing the same
     module until the original import completes, preventing other
     threads from seeing incomplete module objects constructed by the
     original thread.  An exception is made for circular imports, which
     by construction have to expose an incomplete module object at some
     point.

     3.3 版更變: The locking scheme has changed to per-module locks for
     the most part.  A global import lock is kept for some critical
     tasks, such as initializing the per-module locks.

     3.4 版後已棄用.

 -- 函式: imp.acquire_lock ()

     Acquire the interpreter’s global import lock for the current
     thread.  This lock should be used by import hooks to ensure
     thread-safety when importing modules.

     Once a thread has acquired the import lock, the same thread may
     acquire it again without blocking; the thread must release it once
     for each time it has acquired it.

     On platforms without threads, this function does nothing.

     3.3 版更變: The locking scheme has changed to per-module locks for
     the most part.  A global import lock is kept for some critical
     tasks, such as initializing the per-module locks.

     3.4 版後已棄用.

 -- 函式: imp.release_lock ()

     Release the interpreter’s global import lock.  On platforms without
     threads, this function does nothing.

     3.3 版更變: The locking scheme has changed to per-module locks for
     the most part.  A global import lock is kept for some critical
     tasks, such as initializing the per-module locks.

     3.4 版後已棄用.

The following constants with integer values, defined in this module, are
used to indicate the search result of *note find_module(): 3cf9.

 -- Data: imp.PY_SOURCE

     The module was found as a source file.

     3.3 版後已棄用.

 -- Data: imp.PY_COMPILED

     The module was found as a compiled code object file.

     3.3 版後已棄用.

 -- Data: imp.C_EXTENSION

     The module was found as dynamically loadable shared library.

     3.3 版後已棄用.

 -- Data: imp.PKG_DIRECTORY

     The module was found as a package directory.

     3.3 版後已棄用.

 -- Data: imp.C_BUILTIN

     The module was found as a built-in module.

     3.3 版後已棄用.

 -- Data: imp.PY_FROZEN

     The module was found as a frozen module.

     3.3 版後已棄用.

 -- 類別: imp.NullImporter (path_string)

     The *note NullImporter: a9b. type is a PEP 302(7) import hook that
     handles non-directory path strings by failing to find any modules.
     Calling this type with an existing directory or empty string raises
     *note ImportError: 16c.  Otherwise, a *note NullImporter: a9b.
     instance is returned.

     Instances have only one method:

      -- 成員函式: find_module (fullname[, path])

          This method always returns ‘None’, indicating that the
          requested module could not be found.

     3.3 版更變: ‘None’ is inserted into ‘sys.path_importer_cache’
     instead of an instance of *note NullImporter: a9b.

     3.4 版後已棄用: Insert ‘None’ into ‘sys.path_importer_cache’
     instead.

* Menu:

* 示例: 示例<50>.

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Lib/imp.py

   (2) https://www.python.org/dev/peps/pep-3147

   (3) https://www.python.org/dev/peps/pep-3147

   (4) https://www.python.org/dev/peps/pep-3147

   (5) https://www.python.org/dev/peps/pep-3147

   (6) https://www.python.org/dev/peps/pep-3147

   (7) https://www.python.org/dev/peps/pep-0302


File: python.info,  Node: 示例<50>,  Up: imp —— 由代码内部访问 import 。

5.36.2.1 示例
.............

The following function emulates what was the standard import statement
up to Python 1.4 (no hierarchical module names).  (This `implementation'
wouldn’t work in that version, since *note find_module(): 3cf9. has been
extended and *note load_module(): 3cfd. has been added in 1.4.)

     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()


File: python.info,  Node: 未创建文档的模块,  Next: Security Considerations,  Prev: 被取代的模块,  Up: Python 標準函式庫 Standard Library

5.37 未创建文档的模块
=====================

以下是应当记入文档但是目前尚无文档的模块速览列表。 欢迎大家为它们贡献文
档！ （发送电子邮件到 <docs@python.org> ）

本章的想法和原内容取自 Fredrik Lundh 的帖子；本章的具体内容已经大幅修改
。

* Menu:

* 平台特定模块::


File: python.info,  Node: 平台特定模块,  Up: 未创建文档的模块

5.37.1 平台特定模块
-------------------

这些模块用于实现 *note os.path: c5. 模块，除此之外没有文档。几乎没有必要
创建这些文档。

‘ntpath’

     — 在 Win32 和 Win64 平台上实现 *note os.path: c5. 。

‘posixpath’

     — 在 POSIX 上实现 *note os.path: c5. 。


File: python.info,  Node: Security Considerations,  Prev: 未创建文档的模块,  Up: Python 標準函式庫 Standard Library

5.38 Security Considerations
============================

The following modules have specific security considerations:

   * *note cgi: 15.: *note CGI security considerations: 2d28.

   * *note hashlib: 8c.: *note all constructors take a "usedforsecurity"
     keyword-only argument disabling known insecure and blocked
     algorithms: 200b.

   * *note http.server: 96. is not suitable for production use, only
     implementing basic security checks

   * *note logging: aa.: *note Logging configuration uses eval(): 2230.

   * *note multiprocessing: b7.: *note Connection.recv() uses pickle:
     252b.

   * *note pickle: ca.: *note Restricting globals in pickle: 1e1e.

   * *note random: dc. shouldn’t be used for security purposes, use
     *note secrets: e4. instead

   * *note shelve: e7.: *note shelve is based on pickle and thus
     unsuitable for dealing with untrusted sources: 1e3b.

   * *note ssl: f3.: *note SSL/TLS security considerations: 26fd.

   * *note subprocess: f9.: *note Subprocess security considerations:
     25d0.

   * *note tempfile: 103.: *note mktemp is deprecated due to
     vulnerability to race conditions: 1dd0.

   * *note xml: 13c.: *note XML vulnerabilities: 2b34.

   * *note zipfile: 14b.: *note maliciously prepared .zip files can
     cause disk volume exhaustion: 1f31.


File: python.info,  Node: 擴充和嵌入 Python 直譯器,  Next: Python/C API 參考手冊,  Prev: Python 標準函式庫 Standard Library,  Up: Top

6 擴充和嵌入 Python 直譯器
**************************

這份說明文件描述如何在 C 或 C++ 中編寫模組，並使用新模組來擴充 Python 直
譯器功能。那些模組不僅可以定義新的函式，也可以定義新的物件型別及其方法
(method)。文件內容也會描述如何將 Python 直譯器嵌入另一個應用程式中，做為
一種擴充語言 (extension language) 使用。最後，它會展示如何編譯及連結擴充
模組，使那些模組可以動態地（在運行時）被載入到直譯器中，前提是底層作業系
統有支援這個功能。

這份說明文件假設您具備 Python 的基礎知識。關於此語言的非正式介紹，請參閱
*note Python 教學: 132f.。*note Python 語言參考手冊: 1331.給予此語言更為
正式的定義。*note Python 標準函式庫 (Standard Library): 1330. 記錄了賦予
此語言廣泛應用範圍的物件型別、函式與（內建的和以 Python 編寫的）模組。

關於完整的 Python/C API 詳細介紹，請參閱另外一份 *note Python/C API
參考手冊: 1333.。

* Menu:

* 推薦的第三方工具::
* 不使用第三方工具建立擴充::
* 在更大的應用程式中嵌入 CPython 運行環境 (runtime): 在更大的應用程式中嵌入 CPython 運行環境 runtime.


File: python.info,  Node: 推薦的第三方工具,  Next: 不使用第三方工具建立擴充,  Up: 擴充和嵌入 Python 直譯器

6.1 推薦的第三方工具
====================

這份指南僅涵蓋了此 CPython 版本所提供的、用以建立擴充的基本工具。第三方
工具，例如 Cython(1)、cffi(2)、SWIG(3) 和 Numba(4)，提供了更為簡單及更為
複雜的多種方法，來為 Python 建立 C 和 C ++ 擴充。

也參考
......

Python 封裝使用者指南：二進制擴充(5)

     Python 封裝使用者指南 (Python Packaging User Guide) 不僅涵蓋了數個
     可以用來簡化二進制擴充建立過程的工具，也會討論為何建立一個擴充模組
     可能會是您的優先考量。

   ---------- Footnotes ----------

   (1) http://cython.org/

   (2) https://cffi.readthedocs.io

   (3) http://www.swig.org

   (4) https://numba.pydata.org/

   (5) https://packaging.python.org/guides/packaging-binary-extensions/


File: python.info,  Node: 不使用第三方工具建立擴充,  Next: 在更大的應用程式中嵌入 CPython 運行環境 runtime,  Prev: 推薦的第三方工具,  Up: 擴充和嵌入 Python 直譯器

6.2 不使用第三方工具建立擴充
============================

本指南中的這一節將說明，在沒有第三方工具的協助下，如何建立 C 和 C ++ 擴
充。它主要是寫給使用那些工具的創作者們，而不是讓你建立自己的 C 擴充的推
薦方法。

* Menu:

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


File: python.info,  Node: 以 C 或 C++ 擴充 Python,  Next: 自定义扩展类型：教程,  Up: 不使用第三方工具建立擴充

6.2.1 以 C 或 C++ 擴充 Python
-----------------------------

如果你会用 C，添加新的 Python 内置模块会很简单。以下两件不能用 Python 直
接做的事，可以通过 `extension modules' 来实现：实现新的内置对象类型；调
用 C 的库函数和系统调用。

为了支持扩展，Python API（应用程序编程接口）定义了一系列函数、宏和变量，
可以访问 Python 运行时系统的大部分内容。Python 的 API 可以通过在一个 C 源
文件中引用 ‘"Python.h"’ 头文件来使用。

扩展模块的编写方式取决与你的目的以及系统设置；下面章节会详细介绍。

     備註: C扩展接口特指CPython，扩展模块无法在其他Python实现上工作。在
     大多数情况下，应该避免写C扩展，来保持可移植性。举个例子，如果你的用
     例调用了C库或系统调用，你应该考虑使用 *note ctypes: 2a. 模块或
     cffi(1) 库，而不是自己写C代码。这些模块允许你写Python代码来接口C代
     码，而且可移植性更好。不知为何编译失败了。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://cffi.readthedocs.io/


File: python.info,  Node: 一个简单的例子,  Next: 关于错误和异常,  Up: 以 C 或 C++ 擴充 Python

6.2.1.1 一个简单的例子
......................

让我们创建一个扩展模块 ‘spam’ (Monty Python 粉丝最喜欢的食物...) 并且想
要创建对应 C 库函数 ‘system()’ (1) 的 Python 接口。 这个函数接受一个以
null 结尾的字符串参数并返回一个整数。 我们希望可以在 Python 中以如下方式
调用此函数:

     >>> import spam
     >>> status = spam.system("ls -l")

首先创建一个 ‘spammodule.c’ 文件。（传统上，如果一个模块叫 ‘spam’，则对
应实现它的 C 文件叫 ‘spammodule.c’；如果这个模块名字非常长，比如
‘spammify’，则这个模块的文件可以直接叫 ‘spammify.c’。）

文件中开始的两行是：

     #define PY_SSIZE_T_CLEAN
     #include <Python.h>

这会导入 Python API（如果你喜欢，你可以在这里添加描述模块目标和版权信息
的注释)。

     備註: 由于Python可能会定义一些影响某些系统上标准头文件的预处理器定
     义，因此在包含任何标准头文件之前，您*必须* include 这个文件：
     ‘Python.h’。

     推荐总是在 ‘Python.h’ 前定义 ‘PY_SSIZE_T_CLEAN’ 。查看 *note
     提取扩展函数的参数: 3d18. 来了解这个宏的更多内容。

所有在 ‘Python.h’ 中定义的用户可见的符号都具有 ‘Py’ 或 ‘PY’ 前缀，已在标
准头文件中定义的那些除外。 考虑到便利性，也由于其在 Python 解释器中被广
泛使用，‘"Python.h"’ 还包含了一些标准头文件: ‘<stdio.h>’，‘<string.h>’，
‘<errno.h>’ 和 ‘<stdlib.h>’。 如果后面的头文件在你的系统上不存在，它还会
直接声明函数 ‘malloc()’，‘free()’ 和 ‘realloc()’。

下面要做的事是将 C 函数添加到我们的扩展模块，当 Python 表达式
‘spam.system(string)’ 被求值时函数将被调用（我们很快就会看到它最终是如何
被调用的）:

     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);
     }

有个直接翻译参数列表的方法(例如单独的 ‘“ls-l"’)到要传递给C函数的参数。
C函数总是有两个参数，通常名字是 `self' 和 `args' 。

对模块级函数， `self' 参数指向模块对象；对于方法则指向对象实例。

`args' 参数是指向一个 Python 的 tuple 对象的指针，其中包含参数。 每个
tuple 项对应一个调用参数。 这些参数也全都是 Python 对象 — 要在我们的 C 函
数中使用它们就需要先将其转换为 C 值。 Python API 中的函数 *note
PyArg_ParseTuple(): 393. 会检查参数类型并将其转换为 C 值。 它使用模板字
符串确定需要的参数类型以及存储被转换的值的 C 变量类型。 细节将稍后说明。

*note PyArg_ParseTuple(): 393. 在所有参数都有正确类型且组成部分按顺序放
在传递进来的地址里时，返回真(非零)。其在传入无效参数时返回假(零)。在后续
例子里，还会抛出特定异常，使得调用的函数可以理解返回 ‘NULL’ (也就是例子
里所见)。

   ---------- Footnotes ----------

   (1) (1) 这个函数的接口已经在标准模块 *note os: c4. 里了，这里作为一个
简单而直接的例子。


File: python.info,  Node: 关于错误和异常,  Next: 回到例子,  Prev: 一个简单的例子,  Up: 以 C 或 C++ 擴充 Python

6.2.1.2 关于错误和异常
......................

An important convention throughout the Python interpreter is the
following: when a function fails, it should set an exception condition
and return an error value (usually ‘-1’ or a ‘NULL’ pointer).  Exception
information is stored in three members of the interpreter’s thread
state.  These are ‘NULL’ if there is no exception.  Otherwise they are
the C equivalents of the members of the Python tuple returned by *note
sys.exc_info(): d27.  These are the exception type, exception instance,
and a traceback object.  It is important to know about them to
understand how errors are passed around.

Python API中定义了一些函数来设置这些变量。

最常用的就是 *note PyErr_SetString(): 3d1b.。 其参数是异常对象和 C 字符
串。 异常对象一般是像 ‘PyExc_ZeroDivisionError’ 这样的预定义对象。 C 字
符串指明异常原因，并被转换为一个 Python 字符串对象存储为异常的“关联值”。

另一个有用的函数是 *note PyErr_SetFromErrno(): 3d1c. ，仅接受一个异常对
象，异常描述包含在全局变量 ‘errno’ 中。最通用的函数还是 *note
PyErr_SetObject(): 3d1d. ，包含两个参数，分别为异常对象和异常描述。你不
需要使用 *note Py_INCREF(): 38e. 来增加传递到其他函数的参数对象的引用计
数。

你可以通过 *note PyErr_Occurred(): 3d1e. 在不造成破坏的情况下检测是否设
置了异常。 这将返回当前异常对象，或者如果未发生异常则返回 ‘NULL’。 你通
常不需要调用 *note PyErr_Occurred(): 3d1e. 来查看函数调用中是否发生了错
误，因为你应该能从返回值中看出来。

当一个函数 `f' 调用另一个函数 `g' 时检测到后者出错了，`f' 应当自己返回一
个错误值 (通常为 ‘NULL’ 或 ‘-1’)。 它 `不应该' 调用某个 ‘PyErr_*()’ 函数
— 这类函数已经被 `g' 调用过了。 `f' 的调用者随后也应当返回一个错误来提示
`它的' 调用者，同样 `不应该' 调用 ‘PyErr_*()’，依此类推 — 错误的最详细原
因已经由首先检测到它的函数报告了。 一旦这个错误到达 Python 解释器的主循
环，它会中止当前执行的 Python 代码并尝试找出由 Python 程序员所指定的异常
处理程序。

（在某些情况下，当模块确实能够通过调用其它 ‘PyErr_*()’ 函数给出更加详细
的错误消息，并且在这些情况是可以这样做的。 但是按照一般规则，这是不必要
的，并可能导致有关错误原因的信息丢失：大多数操作会由于种种原因而失败。）

想要忽略由一个失败的函数调用所设置的异常，异常条件必须通过调用 *note
PyErr_Clear(): a4c. 显式地被清除。 C 代码应当调用 *note PyErr_Clear():
a4c. 的唯一情况是如果它不想将错误传给解释器而是想完全由自己来处理它（可
能是尝试其他方法，或是假装没有出错）。

每次失败的 ‘malloc()’ 调用必须转换为一个异常。 ‘malloc()’ (或
‘realloc()’ )的直接调用者必须调用 *note PyErr_NoMemory(): 3d1f. 来返回错
误来提示。所有对象创建函数(例如 *note PyLong_FromLong(): 3d20. )已经这么
做了，所以这个提示仅用于直接调用 ‘malloc()’ 的情况。

还要注意的是，除了 *note PyArg_ParseTuple(): 393. 等重要的例外，返回整数
状态码的函数通常都是返回正值或零来表示成功，而以 ‘-1’ 表示失败，如同
Unix 系统调用一样。

最后，当你返回一个错误指示器时要注意清理垃圾（通过为你已经创建的对象执行
*note Py_XDECREF(): 391. 或 *note Py_DECREF(): 38f. 调用）！

选择引发哪个异常完全取决于你的喜好。 所有内置的 Python 异常都有对应的预
声明 C 对象，例如 ‘PyExc_ZeroDivisionError’，你可以直接使用它们。 当然，
你应当明智地选择异常 — 不要使用 ‘PyExc_TypeError’ 来表示一个文件无法被打
开 (那大概应该用 ‘PyExc_IOError’)。 如果参数列表有问题，*note
PyArg_ParseTuple(): 393. 函数通常会引发 ‘PyExc_TypeError’。 如果你想要一
个参数的值必须处于特定范围之内或必须满足其他条件，则适宜使用
‘PyExc_ValueError’。

你也可以为你的模块定义一个唯一的新异常。需要在文件前部声明一个静态对象变
量，如:

     static PyObject *SpamError;

并且在你的模块的初始化函数 (‘PyInit_spam()’) 中使用一个异常对象来初始化:

     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;
     }

注意异常对象的Python名字是 ‘spam.error’ 。而 *note PyErr_NewException():
ccb. 函数可以创建一个类，其基类为 *note Exception: 2dc. (除非是另一个类
传入以替换 ‘NULL’ )， 细节参见 *note 內建的例外: f73. 。

同样注意的是创建类保存了 ‘SpamError’ 的一个引用，这是有意的。为了防止被
垃圾回收掉，否则 ‘SpamError’ 随时会成为野指针。

一会讨论 ‘PyMODINIT_FUNC’ 作为函数返回类型的用法。

‘spam.error’ 异常可以在扩展模块中抛出，通过 *note PyErr_SetString():
3d1b. 函数调用，如下：

     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);
     }


File: python.info,  Node: 回到例子,  Next: 模块方法表和初始化函数,  Prev: 关于错误和异常,  Up: 以 C 或 C++ 擴充 Python

6.2.1.3 回到例子
................

回到前面的例子，你应该明白下面的代码:

     if (!PyArg_ParseTuple(args, "s", &command))
         return NULL;

如果在参数列表中检测到错误，它将返回 ‘NULL’ (该值是返回对象指针的函数所
使用的错误提示)，这取决于 *note PyArg_ParseTuple(): 393. 设置的异常。 在
其他情况下参数的字符串值会被拷贝到局部变量 ‘command’。 这是一个指针赋值
并且你不应该修改它所指向的字符串 (因此在标准 C 中，变量 ‘command’ 应当被
正确地声明为 ‘const char *command’)。

下一个语句使用UNIX系统函数 ‘system()’ ，传递给他的参数是刚才从 *note
PyArg_ParseTuple(): 393. 取出的:

     sts = system(command);

我们的 ‘spam.system()’ 函数必须返回 ‘sts’ 的值作为Python对象。这通过使用
函数 *note PyLong_FromLong(): 3d20. 来实现。

     return PyLong_FromLong(sts);

在这种情况下，会返回一个整数对象，(这个对象会在Python堆里面管理)。

如果你的 C 函数没有有用的返回值 (返回 ‘void’ 的函数)，则对应的 Python 函
数必须返回 ‘None’。 你必须使用这种写法（可以通过 *note Py_RETURN_NONE:
e9b. 宏来实现）:

     Py_INCREF(Py_None);
     return Py_None;

*note Py_None: 3d23. 是特殊 Python 对象 ‘None’ 所对应的 C 名称。 它是一
个真正的 Python 对象而不是 ‘NULL’ 指针，如我们所见，后者在大多数上下文中
都意味着“错误”。


File: python.info,  Node: 模块方法表和初始化函数,  Next: 编译和链接,  Prev: 回到例子,  Up: 以 C 或 C++ 擴充 Python

6.2.1.4 模块方法表和初始化函数
..............................

为了展示 ‘spam_system()’ 如何被Python程序调用。把函数声明为可以被
Python调用，需要先定义一个方法表 "method table" 。

     static PyMethodDef SpamMethods[] = {
         ...
         {"system",  spam_system, METH_VARARGS,
          "Execute a shell command."},
         ...
         {NULL, NULL, 0, NULL}        /* Sentinel */
     };

注意第三个参数 ( ‘METH_VARARGS’ ) ，这个标志指定会使用C的调用惯例。可选
值有 ‘METH_VARARGS’ 、 ‘METH_VARARGS | METH_KEYWORDS’ 。值 ‘0’ 代表使用
*note PyArg_ParseTuple(): 393. 的陈旧变量。

如果单独使用 ‘METH_VARARGS’ ，函数会等待Python传来tuple格式的参数，并最
终使用 *note PyArg_ParseTuple(): 393. 进行解析。

‘METH_KEYWORDS’ 值表示接受关键字参数。这种情况下C函数需要接受第三个
‘PyObject *’ 对象，表示字典参数，使用 *note
PyArg_ParseTupleAndKeywords(): 6c1. 来解析出参数。

这个方法表必须被模块定义结构所引用。

     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
     };

这个结构体必须传递给解释器的模块初始化函数。初始化函数必须命名为
‘PyInit_name()’ ，其中 `name' 是模块的名字，并应该定义为非 ‘static’ ，且
在模块文件里：

     PyMODINIT_FUNC
     PyInit_spam(void)
     {
         return PyModule_Create(&spammodule);
     }

注意 PyMODINIT_FUNC 将函数声明为 ‘PyObject *’ 返回类型，声明了任何平台所
要求的特殊链接声明，并针对 C++ 将函数声明为 ‘extern "C"’。

当 Python 程序首次导入 ‘spam’ 模块时， ‘PyInit_spam()’ 会被调用。 （有关
嵌入 Python 的注释参见下文。） 它将调用 *note PyModule_Create(): 3d26.，
该函数会返回一个模块对象，并基于在模块定义中找到的表将内置函数对象插入到
新创建的模块中（该表是一个 *note PyMethodDef: edd. 结构体的数组）。
*note PyModule_Create(): 3d26. 返回一个指向它所创建的模块对象的指针。 它
可能会因程度严重的特定错误而中止，或者在模块无法成功初始化时返回 ‘NULL’。
初始化函数必须返回模块对象给其调用者，这样它就可以被插入到 ‘sys.modules’
中。

当嵌入Python时， ‘PyInit_spam()’ 函数不会被自动调用，除非放在
‘PyImport_Inittab’ 表里。要添加模块到初始化表，使用 *note
PyImport_AppendInittab(): f9c. ，可选的跟着一个模块的导入。

     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;
     }

     備註: 要从 ‘sys.modules’ 删除实体或导入已编译模块到一个进程里的多个
     解释器(或使用 ‘fork()’ 而没用 ‘exec()’ )会在一些扩展模块上产生错误
     。扩展模块作者可以在初始化内部数据结构时给出警告。

更多关于模块的现实的例子包含在Python源码包的 ‘Modules/xxmodule.c’ 中。这
些文件可以用作你的代码模板，或者学习。脚本 modulator.py 包含在源码发行版
或Windows安装中，提供了一个简单的GUI，用来声明需要实现的函数和对象，并且
可以生成供填入的模板。脚本在 Tools/modulator/ 目录。查看README以了解用法
。

     備註: 不像我们的 ‘spam’ 例子， ‘xxmodule’ 使用了 `多阶段初始化'
     (Python3.5开始引入)， ‘PyInit_spam’ 会返回一个 PyModuleDef 结构体，
     然后创建的模块放到导入机制。细节参考 PEP 489(1) 的多阶段初始化。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0489


File: python.info,  Node: 编译和链接,  Next: 在C中调用Python函数,  Prev: 模块方法表和初始化函数,  Up: 以 C 或 C++ 擴充 Python

6.2.1.5 编译和链接
..................

在你能使用你的新写的扩展之前，你还需要做两件事情：使用 Python 系统来编译
和链接。如果你使用动态加载，这取决于你使用的操作系统的动态加载机制；更多
信息请参考编译扩展模块的章节（ *note 构建C/C++扩展: 3d29. 章节），以及在
Windows 上编译需要的额外信息（ *note 在 Windows 上构建 C 和 C++ 扩展:
14cd. 章节）。

如果你不使用动态加载，或者想要让模块永久性的作为Python解释器的一部分，就
必须修改配置设置，并重新构建解释器。幸运的是在Unix上很简单，只需要把你的
文件 ( ‘spammodule.c’ 为例) 放在解压缩源码发行包的 ‘Modules/’ 目录下，添
加一行到 ‘Modules/Setup.local’ 来描述你的文件：

     spam spammodule.o

然后在顶层目录运行 ‘make’ 来重新构建解释器。你也可以在 ‘Modules/’ 子目录
使用 ‘make’，但是你必须先重建 ‘Makefile’ 文件，然后运行 ’‘make’
Makefile’ 命令。（你每次修改 ‘Setup’ 文件都需要这样操作。）

如果你的模块需要额外的链接，这些内容可以列出在配置文件里，举个实例：

     spam spammodule.o -lX11


File: python.info,  Node: 在C中调用Python函数,  Next: 提取扩展函数的参数,  Prev: 编译和链接,  Up: 以 C 或 C++ 擴充 Python

6.2.1.6 在C中调用Python函数
...........................

迄今为止，我们一直把注意力集中于让Python调用C函数，其实反过来也很有用，
就是用C调用Python函数。这在回调函数中尤其有用。如果一个C接口使用回调，那
么就要实现这个回调机制。

幸运的是，Python解释器是比较方便回调的，并给标准Python函数提供了标准接口
。(这里就不再详述解析Python代码作为输入的方式，如果有兴趣可以参考
‘Python/pythonmain.c’ 中的 *note -c: 1340. 命令代码。)

调用Python函数，首先Python程序要传递Python函数对象。应该提供个函数(或其
他接口)来实现。当调用这个函数时，用全局变量保存Python函数对象的指针，还
要调用 (*note Py_INCREF(): 38e.) 来增加引用计数，当然不用全局变量也没什
么关系。例如如下:

     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;
     }

这个函数必须使用 *note METH_VARARGS: f0a. 标志注册到解释器，这在 *note
模块方法表和初始化函数: 3d24. 章节会描述。 *note PyArg_ParseTuple():
393. 函数及其参数的文档在 *note 提取扩展函数的参数: 3d18. 。

*note Py_XINCREF(): 390. 和 *note Py_XDECREF(): 391. 这两个宏可增加/减少
一个对象的引用计数，并且当存在 ‘NULL’ 指针时仍可保证安全 (但请注意在这个
上下文中 `temp' 将不为 ‘NULL’)。 更多相关信息请参考 *note 引用计数:
3d2c. 章节。

随后，当要调用此函数时，你将调用 C 函数 *note PyObject_CallObject():
3d2d.。 该函数有两个参数，它们都属于指针，指向任意 Python 对象：即
Python 函数，及其参数列表。 参数列表必须总是一个元组对象，其长度即参数的
个数量。 要不带参数地调用 Python 函数，则传入 ‘NULL’ 或一个空元组；要带
一个参数调用它，则传入一个单元组。 *note Py_BuildValue(): 3f0. 会在其格
式字符串包含一对圆括号内的零个或多个格式代码时返回一个元组。 例如:

     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);

*note PyObject_CallObject(): 3d2d. 返回Python对象指针，这也是Python函数
的返回值。 *note PyObject_CallObject(): 3d2d. 是一个对其参数 "引用计数无
关" 的函数。例子中新的元组创建用于参数列表，并且在 *note
PyObject_CallObject(): 3d2d. 之后立即使用了 *note Py_DECREF(): 38f. 。

‘PyEval_CallObject()’ 的返回值总是“新”的：要么是一个新建的对象；要么是已
有对象，但增加了引用计数。所以除非你想把结果保存在全局变量中，你需要对这
个值使用 *note Py_DECREF(): 38f.，即使你对里面的内容（特别！）不感兴趣。

但是在你这么做之前，很重要的一点是检查返回值不是 ‘NULL’。 如果是的话，
Python 函数会终止并引发异常。 如果调用 *note PyObject_CallObject():
3d2d. 的 C 代码是在 Python 中发起调用的，它应当立即返回一个错误来告知其
Python 调用者，以便解释器能打印栈回溯信息，或者让调用方 Python 代码能处
理该异常。 如果这无法做到或不合本意，则应当通过调用 *note PyErr_Clear():
a4c. 来清除异常。 例如:

     if (result == NULL)
         return NULL; /* Pass error back */
     ...use result...
     Py_DECREF(result);

依赖于具体的回调函数，你还要提供一个参数列表到 ‘PyEval_CallObject()’ 。
在某些情况下参数列表是由Python程序提供的，通过接口再传到回调函数。这样就
可以不改变形式直接传递。另外一些时候你要构造一个新的tuple来传递参数。最
简单的方法就是 *note Py_BuildValue(): 3f0. 函数构造tuple。例如，你要传递
一个事件对象时可以用:

     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);

注意 ‘Py_DECREF(arglist)’ 所在处会立即调用，在错误检查之前。当然还要注意
一些常规的错误，比如 *note Py_BuildValue(): 3f0. 可能会遭遇内存不足等等
。

你还需要注意，用关键字参数调用 *note PyObject_Call(): 23c. ，需要支持普
通参数和关键字参数。有如如上例子中，我们使用 *note Py_BuildValue(): 3f0.
来构造字典。

     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);


File: python.info,  Node: 提取扩展函数的参数,  Next: 给扩展函数的关键字参数,  Prev: 在C中调用Python函数,  Up: 以 C 或 C++ 擴充 Python

6.2.1.7 提取扩展函数的参数
..........................

函数 *note PyArg_ParseTuple(): 393. 的声明如下：

     int PyArg_ParseTuple(PyObject *arg, const char *format, ...);

参数 `arg' 必须是一个元组对象，包含从 Python 传递给 C 函数的参数列表。
`format' 参数必须是一个格式字符串，语法请参考 Python C/API 手册中的
*note 语句解释及变量编译: 3f2.。剩余参数是各个变量的地址，类型要与格式字
符串对应。

注意 *note PyArg_ParseTuple(): 393. 会检测他需要的Python参数类型，却无法
检测传递给他的C变量地址，如果这里出错了，可能会在内存中随机写入东西，小
心。

注意任何由调用者提供的Python对象引用是 `借来的' 引用；不要递减它们的引用
计数！

一些调用的例子：

     #define PY_SSIZE_T_CLEAN  /* Make "s#" use Py_ssize_t rather than int. */
     #include <Python.h>

     int ok;
     int i, j;
     long k, l;
     const char *s;
     Py_ssize_t size;

     ok = PyArg_ParseTuple(args, ""); /* No arguments */
         /* Python call: f() */

     ok = PyArg_ParseTuple(args, "s", &s); /* A string */
         /* Possible Python call: f('whoops!') */

     ok = PyArg_ParseTuple(args, "lls", &k, &l, &s); /* Two longs and a string */
         /* Possible Python call: f(1, 2, 'three') */

     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') */

     {
         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) */
     }

     {
         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)) */
     }

     {
         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) */
     }


File: python.info,  Node: 给扩展函数的关键字参数,  Next: 构造任意值,  Prev: 提取扩展函数的参数,  Up: 以 C 或 C++ 擴充 Python

6.2.1.8 给扩展函数的关键字参数
..............................

函数 *note PyArg_ParseTupleAndKeywords(): 6c1. 声明如下：

     int PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict,
                                     const char *format, char *kwlist[], ...);

`arg' 与 `format' 形参与 *note PyArg_ParseTuple(): 393. 函数所定义的一致
。 `kwdict' 形参是作为第三个参数从 Python 运行时接收的关键字字典。
`kwlist' 形参是以 ‘NULL’ 结尾的字符串列表，它被用来标识形参；名称从左至
右与来自 `format' 的类型信息相匹配。 如果执行成功，*note
PyArg_ParseTupleAndKeywords(): 6c1. 会返回真值，否则返回假值并引发一个适
当的异常。

     備註: 嵌套的元组在使用关键字参数时无法生效，不在 `kwlist' 中的关键
     字参数会导致 *note TypeError: 1fe. 异常。

如下是使用关键字参数的例子模块，作者是 Geoff Philbrick
(<phibrick@hks.com>):

     #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);
     }


File: python.info,  Node: 构造任意值,  Next: 引用计数,  Prev: 给扩展函数的关键字参数,  Up: 以 C 或 C++ 擴充 Python

6.2.1.9 构造任意值
..................

这个函数与 *note PyArg_ParseTuple(): 393. 很相似，声明如下：

     PyObject *Py_BuildValue(const char *format, ...);

接受一个格式字符串，与 *note PyArg_ParseTuple(): 393. 相同，但是参数必须
是原变量的地址指针(输入给函数，而非输出)。最终返回一个Python对象适合于返
回C函数调用给Python代码。

一个与 *note PyArg_ParseTuple(): 393. 的不同是，后面可能需要的要求返回一
个元组(Python参数里诶包总是在内部描述为元组)，比如用于传递给其他Python函
数以参数。 *note Py_BuildValue(): 3f0. 并不总是生成元组，在多于1个参数时
会生成元组，而如果没有参数则返回 ‘None’ ，一个参数则直接返回该参数的对象
。如果要求强制生成一个长度为空的元组，或包含一个元素的元组，需要在格式字
符串中加上括号。

例子(左侧是调用，右侧是Python值结果)：

     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))


File: python.info,  Node: 引用计数,  Next: 在C++中编写扩展,  Prev: 构造任意值,  Up: 以 C 或 C++ 擴充 Python

6.2.1.10 引用计数
.................

在C/C++语言中，程序员负责动态分配和回收堆(heap)当中的内存。在C里，通过函
数 ‘malloc()’ 和 ‘free()’ 来完成。在C++里是操作 ‘new’ 和 ‘delete’ 来实现
相同的功能。

每个由 ‘malloc()’ 分配的内存块，最终都要由 ‘free()’ 退回到可用内存池里面
去。而调用 ‘free()’ 的时机非常重要，如果一个内存块忘了 ‘free()’ 则会导致
内存泄漏，这块内存在程序结束前将无法重新使用。这叫做 `内存泄漏' 。而如果
对同一内存块 ‘free()’ 了以后，另外一个指针再次访问，则再次使用
‘malloc()’ 复用这块内存会导致冲突。这叫做 `野指针' 。等同于使用未初始化
的数据，core dump，错误结果，神秘的崩溃等。

内存泄露往往发生在一些并不常见的代码流程上面。比如一个函数申请了内存以后
，做了些计算，然后释放内存块。现在一些对函数的修改可能增加对计算的测试并
检测错误条件，然后过早的从函数返回了。这很容易忘记在退出前释放内存，特别
是后期修改的代码。这种内存泄漏，一旦引入，通常很长时间都难以检测到，错误
退出被调用的频度较低，而现代电脑又有非常巨大的虚拟内存，所以泄漏仅在长期
运行或频繁调用泄漏函数时才会变得明显。因此，有必要避免内存泄漏，通过代码
规范会策略来最小化此类错误。

Python通过 ‘malloc()’ 和 ‘free()’ 包含大量的内存分配和释放，同样需要避免
内存泄漏和野指针。他选择的方法就是 `引用计数' 。其原理比较简单：每个对象
都包含一个计数器，计数器的增减与对象引用的增减直接相关，当引用计数为0时
，表示对象已经没有存在的意义了，对象就可以删除了。

另一个叫法是 `自动垃圾回收' 。(有时引用计数也被看作是垃圾回收策略，于是
这里的"自动"用以区分两者)。自动垃圾回收的优点是用户不需要明确的调用
‘free()’ 。(另一个优点是改善速度或内存使用，然而这并不难)。缺点是对C，没
有可移植的自动垃圾回收器，而引用计数则可以可移植的实现(只要 ‘malloc()’ 和
‘free()’ 函数是可用的，这也是C标准担保的)。也许以后有一天会出现可移植的
自动垃圾回收器，但在此前我们必须与引用计数一起工作。

Python使用传统的引用计数实现，也提供了循环监测器，用以检测引用循环。这使
得应用无需担心直接或间接的创建了循环引用，这是引用计数垃圾收集的一个弱点
。引用循环是对象(可能直接)的引用了本身，所以循环中的每个对象的引用计数都
不是0。典型的引用计数实现无法回收处于引用循环中的对象，或者被循环所引用
的对象，哪怕没有循环以外的引用了。

循环探测器可以检测垃圾循环并回收。 *note gc: 84. 模块提供了方法运行探测
器 ( *note collect(): 35b. 函数) ，而且可以在运行时配置禁用探测器。循环
探测器被当作可选组件，默认是包含的，也可以在构建时禁用，在Unix平台(包括
Mac OS X)使用 ‘--without-cycle-gc’ 选项到 ‘configure’ 脚本。如果循环探测
器被禁用， *note gc: 84. 模块就不可用了。

* Menu:

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


File: python.info,  Node: Python中的引用计数,  Next: 拥有规则,  Up: 引用计数

6.2.1.11 Python中的引用计数
...........................

有两个宏 ‘Py_INCREF(x)’ 和 ‘Py_DECREF(x)’ ，会处理引用计数的增减。 *note
Py_DECREF(): 38f. 也会在引用计数到达0时释放对象。为了灵活，并不会直接调
用 ‘free()’ ，而是通过对象的 `类型对象' 的函数指针来调用。为了这个目的
(或其他的)，每个对象同时包含一个指向自身类型对象的指针。

最大的问题依旧：何时使用 ‘Py_INCREF(x)’ 和 ‘Py_DECREF(x)’ ？我们首先引入
一些概念。没有人"拥有"一个对象，你可以 `拥有一个引用' 到一个对象。一个对
象的引用计数定义为拥有引用的数量。引用的拥有者有责任调用 *note
Py_DECREF(): 38f. ，在引用不再需要时。引用的拥有关系可以被传递。有三种办
法来处置拥有的引用：传递、存储、调用 *note Py_DECREF(): 38f. 。忘记处置
一个拥有的引用会导致内存泄漏。

还可以 `借用' (1) 一个对象的引用。借用的引用不应该调用 *note
Py_DECREF(): 38f. 。借用者必须确保不能持有对象超过拥有者借出的时间。在拥
有者处置对象后使用借用的引用是有风险的，应该完全避免 (2) 。

借用相对于引用的优点是你无需担心整条路径上代码的引用，或者说，通过借用你
无需担心内存泄漏的风险。借用的缺点是一些看起来正确代码上的借用可能会在拥
有者处置后使用对象。

借用可以变为拥有引用，通过调用 *note Py_INCREF(): 38e. 。这不会影响已经
借出的拥有者的状态。这回创建一个新的拥有引用，并给予完全的拥有者责任(新
的拥有者必须恰当的处置引用，就像之前的拥有者那样)。

   ---------- Footnotes ----------

   (1) (2) 术语"借用"一个引用是不完全正确的：拥有者仍然有引用的拷贝。

   (2) (3) 检查引用计数至少为1 `没有用' ，引用计数本身可以在已经释放的内
存里，并有可能被其他对象所用。


File: python.info,  Node: 拥有规则,  Next: 危险的薄冰,  Prev: Python中的引用计数,  Up: 引用计数

6.2.1.12 拥有规则
.................

当一个对象引用传递进出一个函数时，函数的接口应该指定拥有关系的传递是否包
含引用。

大多数函数返回一个对象的引用，并传递引用拥有关系。通常，所有创建对象的函
数，例如 *note PyLong_FromLong(): 3d20. 和 *note Py_BuildValue(): 3f0. ，
会传递拥有关系给接收者。即便是对象不是真正新的，你仍然可以获得对象的新引
用。一个实例是 *note PyLong_FromLong(): 3d20. 维护了一个流行值的缓存，并
可以返回已缓存项目的新引用。

很多另一个对象提取对象的函数，也会传递引用关系，例如 *note
PyObject_GetAttrString(): 3d38. 。这里的情况不够清晰，一些不太常用的例程
是例外的 *note PyTuple_GetItem(): 3d39. ， *note PyList_GetItem(): 3d3a.
， *note PyDict_GetItem(): 3d3b. ， *note PyDict_GetItemString(): 3d3c.
都是返回从元组、列表、字典里借用的引用。

函数 *note PyImport_AddModule(): 3d3d. 也会返回借用的引用，哪怕可能会返
回创建的对象：这个可能因为一个拥有的引用对象是存储在 ‘sys.modules’ 里。

当你传递一个对象引用到另一个函数时，通常函数是借用出去的。如果需要存储，
就使用 *note Py_INCREF(): 38e. 来变成独立的拥有者。这个规则有两个重要的
例外： *note PyTuple_SetItem(): 3d3e. 和 *note PyList_SetItem(): 3d3f. 。
这些函数接受传递来的引用关系，哪怕会失败！(注意 *note PyDict_SetItem():
3d40. 及其同类不会接受引用关系，他们是"正常的")。

当一个C函数被Python调用时，会从调用方传来的参数借用引用。调用者拥有对象
的引用，所以借用的引用生命周期可以保证到函数返回。只要当借用的引用需要存
储或传递时，就必须转换为拥有的引用，通过调用 *note Py_INCREF(): 38e. 。

Python调用从C函数返回的对象引用时必须是拥有的引用—拥有关系被从函数传递给
调用者。


File: python.info,  Node: 危险的薄冰,  Next: NULL指针,  Prev: 拥有规则,  Up: 引用计数

6.2.1.13 危险的薄冰
...................

有少数情况下，借用的引用看起来无害，但却可能导致问题。这通常是因为解释器
的隐式调用，并可能导致引用拥有者处置这个引用。

首先需要特别注意的情况是使用 *note Py_DECREF(): 38f. 到一个无关对象，而
这个对象的引用是借用自一个列表的元素。举个实例：

     void
     bug(PyObject *list)
     {
         PyObject *item = PyList_GetItem(list, 0);

         PyList_SetItem(list, 1, PyLong_FromLong(0L));
         PyObject_Print(item, stdout, 0); /* BUG! */
     }

这个函数首先借用一个引用 ‘list[0]’ ，然后替换 ‘list[1]’ 为值 ‘0’ ，最后
打印借用的引用。看起来无害是吧，但却不是。

我们跟着控制流进入 *note PyList_SetItem(): 3d3f. 。列表拥有者引用了其所
有成员，所以当成员1被替换时，就必须处置原来的成员1。现在假设原来的成员
1是用户定义类的实例，且假设这个类定义了 *note __del__(): a04. 方法。如果
这个类实例的引用计数是1，那么处置动作就会调用 *note __del__(): a04. 方法
。

既然是Python写的， *note __del__(): a04. 方法可以执行任意Python代码。是
否可能在 ‘bug()’ 的 ‘item’ 废止引用呢，是的。假设列表传递到 ‘bug()’ 会被
*note __del__(): a04. 方法所访问，就可以执行一个语句来实现 ‘del list[0]’
，然后假设这是最后一个对对象的引用，就需要释放内存，从而使得 ‘item’ 无效
化。

解决方法是，当你知道了问题的根源，就容易了：临时增加引用计数。正确版本的
函数代码如下：

     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);
     }

这是个真实的故事。一个旧版本的Python包含了这个bug的变种，而一些人花费了
大量时间在C调试器上去寻找为什么 *note __del__(): a04. 方法会失败。

这个问题的第二种情况是借用的引用涉及线程的变种。通常，Python解释器里多个
线程无法进入对方的路径，因为有个全局锁保护着Python整个对象空间。但可以使
用宏 *note Py_BEGIN_ALLOW_THREADS: 3d43. 来临时释放这个锁，重新获取锁用
*note Py_END_ALLOW_THREADS: 3d7. 。这通常围绕在阻塞I/O调用外，使得其他线
程可以在等待I/O期间使用处理器。显然，如下函数会跟之前那个有一样的问题：

     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! */
     }


File: python.info,  Node: NULL指针,  Prev: 危险的薄冰,  Up: 引用计数

6.2.1.14 NULL指针
.................

通常，接受对象引用作为参数的函数不希望你传给它们 ‘NULL’ 指针，并且当你这
样做时将会转储核心（或在以后导致核心转储）。 返回对象引用的函数通常只在
要指明发生了异常时才返回 ‘NULL’。 不检测 ‘NULL’ 参数的原因在于这些函数经
常要将它们所接收的对象传给其他函数 — 如果每个函数都检测 ‘NULL’，将会导致
大量的冗余检测而使代码运行得更缓慢。

更好的做法是仅在“源头”上检测 ‘NULL’，即在接收到一个可能为 ‘NULL’ 的指针
，例如来自 ‘malloc()’ 或是一个可能引发异常的函数的时候。

*note Py_INCREF(): 38e. 和 *note Py_DECREF(): 38f. 等宏不会检测 ‘NULL’ 指
针 — 但是，它们的变种 *note Py_XINCREF(): 390. 和 *note Py_XDECREF():
391. 则会检测。

用于检测特定对象类型的宏 (‘Pytype_Check()’) 不会检测 ‘NULL’ 指针 — 同样
地，有大量代码会连续调用这些宏来测试一个对象是否为几种不同预期类型之一，
这将会生成冗余的测试。 不存在带有 ‘NULL’ 检测的变体。

C 函数调用机制会保证传给 C 函数的参数列表 (本示例中为 ‘args’) 绝不会为
‘NULL’ — 实际上它会保证其总是为一个元组 (1)。

任何时候将 ‘NULL’ 指针“泄露”给 Python 用户都会是个严重的错误。

   ---------- Footnotes ----------

   (1) (4) 当你使用 "旧式" 风格调用约定时，这些保证不成立，尽管这依旧存
在于很多旧代码中。


File: python.info,  Node: 在C++中编写扩展,  Next: 给扩展模块提供C API,  Prev: 引用计数,  Up: 以 C 或 C++ 擴充 Python

6.2.1.15 在C++中编写扩展
........................

还可以在C++中编写扩展模块，只是有些限制。如果主程序(Python解释器)是使用
C编译器来编译和链接的，全局或静态对象的构造器就不能使用。而如果是C++编译
器来链接的就没有这个问题。函数会被Python解释器调用(通常就是模块初始化函
数)必须声明为 ‘extern "C"’ 。而是否在 ‘extern "C" {...}’ 里包含Python头
文件则不是那么重要，因为如果定义了符号 ‘__cplusplus’ 则已经是这么声明的
了(所有现代C++编译器都会定义这个符号)。


File: python.info,  Node: 给扩展模块提供C API,  Prev: 在C++中编写扩展,  Up: 以 C 或 C++ 擴充 Python

6.2.1.16 给扩展模块提供C API
............................

很多扩展模块提供了新的函数和类型供Python使用，但有时扩展模块里的代码也可
以被其他扩展模块使用。例如，一个扩展模块可以实现一个类型 "collection" 看
起来是没有顺序的。就像是Python列表类型，拥有C API允许扩展模块来创建和维
护列表，这个新的集合类型可以有一堆C函数用于给其他扩展模块直接使用。

开始看起来很简单：只需要编写函数(无需声明为 ‘static’ )，提供恰当的头文件
，以及C API的文档。实际上在所有扩展模块都是静态链接到Python解释器时也是
可以正常工作的。当模块以共享库链接时，一个模块中的符号定义对另一个模块不
可见。可见的细节依赖于操作系统，一些系统的Python解释器使用全局命名空间
(例如Windows)，有些则在链接时需要一个严格的已导入符号列表(一个例子是
AIX)，或者提供可选的不同策略(如Unix系列)。即便是符号是全局可见的，你要调
用的模块也可能尚未加载。

可移植性需要不能对符号可见性做任何假设。这意味着扩展模块里的所有符号都应
该声明为 ‘static’ ，除了模块的初始化函数，来避免与其他扩展模块的命名冲突
(在段落 *note 模块方法表和初始化函数: 3d24. 中讨论) 。这意味着符号应该
`必须' 通过其他导出方式来供其他扩展模块访问。

Python提供了一个特别的机制来传递C级别信息(指针)，从一个扩展模块到另一个
：Capsules。一个Capsule是一个Python数据类型，会保存指针( ‘void *’ )。
Capsule只能通过其C API来创建和访问，但可以像其他Python对象一样的传递。通
常，我们可以指定一个扩展模块命名空间的名字。其他扩展模块可以导入这个模块
，获取这个名字的值，然后从Capsule获取指针。

Capsule可以用多种方式导出C API给扩展模块。每个函数可以用自己的Capsule，
或者所有C API指针可以存储在一个数组里，数组地址再发布给Capsule。存储和获
取指针也可以用多种方式，供客户端模块使用。

无论你选择哪个方法，正确地为你的 Capsule 命名都很重要。 函数 *note
PyCapsule_New(): 3d49. 接受一个名称形参 (‘const char *’)；允许你传入一个
‘NULL’ 作为名称，但我们强烈建议你指定一个名称。 正确地命名的 Capsule 提
供了一定程序的运行时类型安全；没有可行的方式能区分两个未命名的 Capsule。

通常来说，Capsule用于暴露C API，其名字应该遵循如下规范：

     modulename.attributename

便利函数 *note PyCapsule_Import(): 3d4a. 可以方便的载入通过Capsule提供的
C API，仅在Capsule的名字匹配时。这个行为为C API用户提供了高度的确定性来
载入正确的C API。

如下例子展示了将大部分负担交由导出模块作者的方法，适用于常用的库模块。其
会存储所有C API指针(例子里只有一个)在 ‘void’ 指针的数组里，并使其值变为
Capsule。对应的模块头文件提供了宏来管理导入模块和获取C API指针；客户端模
块只需要在访问C API前调用这个宏即可。

导出的模块修改自 ‘spam’ 模块，来自 *note 一个简单的例子: 3d17. 段落。函
数 ‘spam.system()’ 不会直接调用C库函数 ‘system()’ ，但一个函数
‘PySpam_System()’ 会负责调用，当然现实中会更复杂些(例如添加 "spam" 到每
个命令)。函数 ‘PySpam_System()’ 也会导出给其他扩展模块。

函数 ‘PySpam_System()’ 是个纯C函数，声明 ‘static’ 就像其他地方那样:

     static int
     PySpam_System(const char *command)
     {
         return system(command);
     }

函数 ‘spam_system()’ 按照如下方式修改:

     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);
     }

在模块开头，在此行后:

     #include <Python.h>

添加另外两行:

     #define SPAM_MODULE
     #include "spammodule.h"

‘#define’ 用于告知头文件需要包含给导出的模块，而不是客户端模块。最终，模
块的初始化函数必须负责初始化C API指针数组:

     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;
     }

注意 ‘PySpam_API’ 声明为 ‘static’ ；此外指针数组会在 ‘PyInit_spam()’ 结
束后消失!

头文件 ‘spammodule.h’ 里的一堆工作，看起来如下所示:

     #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) */

客户端模块必须在其初始化函数里按顺序调用函数 ‘import_spam()’ (或其他宏
)才能访问函数 ‘PySpam_System()’ 。

     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;
     }

这种方法的主要缺点是，文件 ‘spammodule.h’ 过于复杂。当然，对每个要导出的
函数，基本结构是相似的，所以只需要学习一次。

最后需要提醒的是Capsule提供了额外的功能，用于存储在Capsule里的指针的内存
分配和释放。细节参考 Python/C API参考手册的章节 *note Capsule 对象:
3d4b. 和Capsule的实现(在Python源码发行包的 ‘Include/pycapsule.h’ 和
‘Objects/pycapsule.c’ )。

註解
....


File: python.info,  Node: 自定义扩展类型：教程,  Next: 定义扩展类型：已分类主题,  Prev: 以 C 或 C++ 擴充 Python,  Up: 不使用第三方工具建立擴充

6.2.2 自定义扩展类型：教程
--------------------------

Python 允许编写 C 扩展模块定义可以从 Python 代码中操纵的新类型，这很像内
置的 *note str: 205. 和 *note list: 1f8. 类型。所有扩展类型的代码都遵循
一个模式，但是在您开始之前，您需要了解一些细节。这份文件是对这个主题介绍
。

* Menu:

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


File: python.info,  Node: 基础,  Next: Adding data and methods to the Basic example,  Up: 自定义扩展类型：教程

6.2.2.1 基础
............

*note CPython: 1569. 运行时将所有 Python 对象都视为类型 *note PyObject*:
5b4. 的变量，即所有 Python 对象的"基础类型"。 *note PyObject: 5b4. 结构
体本身包含了对象的 *note reference count: 3d51. 和对象的"类型对象"。 类
型对象确定解释器需要调用哪些 (C) 函数，例如一个属性查询一个对象，一个方
法调用，或者与另一个对象相乘。 这些 C 函数被称为“类型方法”。

所以，如果你想要定义新的扩展类型，需要创建新的类型对象。

这类事情只能用例子解释，这里用一个最小化但完整的的模块，定义了新的类型叫
做 ‘Custom’ 在C扩展模块 ‘custom’ 里。

     備註: 这里展示的方法是定义 `static' 扩展类型的传统方法。可以适合大
     部分用途。C API也可以定义在堆上分配的扩展类型，使用 *note
     PyType_FromSpec(): 23a. 函数，但不在本入门里讨论。

     #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 = "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;
     }

这部分很容易理解，这是为了跟上一章能对接上。这个文件定义了三件事：

  1. ‘Custom’ 类的对象 `object' 包含了： ‘CustomObject’ 结构，这会为每个
     ‘Custom’ 实例分配一次。

  2. ‘Custom’ `type' 的行为：这是 ‘CustomType’ 结构体，其定义了一堆标识
     和函数指针，会指向解释器里请求的操作。

  3. 初始化 ‘custom’ 模块： ‘PyInit_custom’ 函数和对应的 ‘custommodule’
     结构体。

结构的第一块是

     typedef struct {
         PyObject_HEAD
     } CustomObject;

这就是一个自定义对象所包含的。 ‘PyObject_HEAD’ 是强制要求必须在每个对象
结构体之前，用以定义一个类型为 *note PyObject: 5b4. 的字段叫 ‘ob_base’ ，
包含了一个指针指向类型对象和一个引用计数(这可以用宏 *note Py_REFCNT:
3d52. 和 *note Py_TYPE: 3d53. 来区分)。用宏来抽象，使得附加字段可以用调
试构建。

     備註: 注意在宏 *note PyObject_HEAD: d3a. 后没有分号。意外添加分号会
     导致编译器提示出错。

当然，对象除了在 ‘PyObject_HEAD’ 存储数据外，还有额外数据；例如，如下定
义了标准的Python浮点数:

     typedef struct {
         PyObject_HEAD
         double ob_fval;
     } PyFloatObject;

第二个位是类型对象的定义:

     static PyTypeObject CustomType = {
         PyVarObject_HEAD_INIT(NULL, 0)
         .tp_name = "custom.Custom",
         .tp_doc = "Custom objects",
         .tp_basicsize = sizeof(CustomObject),
         .tp_itemsize = 0,
         .tp_flags = Py_TPFLAGS_DEFAULT,
         .tp_new = PyType_GenericNew,
     };

     備註: 推荐使用如上C99风格的初始化，以避免列出所有的 *note
     PyTypeObject: 3f5. 字段，其中很多是你不需要关心的，这样也可以避免关
     注字段的定义顺序。

在 ‘object.h’ 中实际定义的 *note PyTypeObject: 3f5. 具有比如上定义更多的
*note 字段: 271.。 剩余的字段会由 C 编译器用零来填充，通常的做法是不显式
地指定它们，除非你确实需要它们。

我们先挑选一部分，每次一个字段:

     PyVarObject_HEAD_INIT(NULL, 0)

这一行是强制的样板，用以初始化如上提到的 ‘ob_base’ 字段:

     .tp_name = "custom.Custom",

我们的类型的名称。 这将出现在我们的对象的默认文本表示形式和某些错误消息
中，例如:

     >>> "" + custom.Custom()
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     TypeError: can only concatenate str (not "custom.Custom") to str

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
‘custom’ and the type is ‘Custom’, so we set the type name to
‘custom.Custom’.  Using the real dotted import path is important to make
your type compatible with the *note pydoc: d9. and *note pickle: ca.
modules.

     .tp_basicsize = sizeof(CustomObject),
     .tp_itemsize = 0,

This is so that Python knows how much memory to allocate when creating
new ‘Custom’ instances.  *note tp_itemsize: 3d54. is only used for
variable-sized objects and should otherwise be zero.

     備註: If you want your type to be subclassable from Python, and
     your type has the same *note tp_basicsize: 26a. 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 *note
     __bases__: ecb, or else it will not be able to call your type’s
     *note __new__(): 974. method without getting an error.  You can
     avoid this problem by ensuring that your type has a larger value
     for *note tp_basicsize: 26a. than its base type does.  Most of the
     time, this will be true anyway, because either your base type will
     be *note object: 3d2, or else you will be adding data members to
     your base type, and therefore increasing its size.

We set the class flags to *note Py_TPFLAGS_DEFAULT: 3d55.

     .tp_flags = Py_TPFLAGS_DEFAULT,

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 *note tp_doc: 3d56.

     .tp_doc = "Custom objects",

To enable object creation, we have to provide a *note tp_new: 3d57.
handler.  This is the equivalent of the Python method *note __new__():
974, but has to be specified explicitly.  In this case, we can just use
the default implementation provided by the API function *note
PyType_GenericNew(): 3d58.

     .tp_new = PyType_GenericNew,

Everything else in the file should be familiar, except for some code in
‘PyInit_custom()’:

     if (PyType_Ready(&CustomType) < 0)
         return;

This initializes the ‘Custom’ type, filling in a number of members to
the appropriate default values, including ‘ob_type’ that we initially
set to ‘NULL’.

     Py_INCREF(&CustomType);
     if (PyModule_AddObject(m, "Custom", (PyObject *) &CustomType) < 0) {
         Py_DECREF(&CustomType);
         Py_DECREF(m);
         return NULL;
     }

This adds the type to the module dictionary.  This allows us to create
‘Custom’ instances by calling the ‘Custom’ class:

     >>> import custom
     >>> mycustom = custom.Custom()

That’s it!  All that remains is to build it; put the above code in a
file called ‘custom.c’ and:

     from distutils.core import setup, Extension
     setup(name="custom", version="1.0",
           ext_modules=[Extension("custom", ["custom.c"])])

in a file called ‘setup.py’; then typing

     $ python setup.py build

at a shell should produce a file ‘custom.so’ in a subdirectory; move to
that directory and fire up Python — you should be able to ‘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.

     備註: While this documentation showcases the standard *note
     distutils: 38. module for building C extensions, it is recommended
     in real-world use cases to use the newer and better-maintained
     ‘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(1).

   ---------- Footnotes ----------

   (1) https://packaging.python.org/tutorials/distributing-packages/


File: python.info,  Node: Adding data and methods to the Basic example,  Next: Providing finer control over data attributes,  Prev: 基础,  Up: 自定义扩展类型：教程

6.2.2.2 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,
‘custom2’ that adds these capabilities:

     #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 = "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;
     }

This version of the module has a number of changes.

We’ve added an extra include:

     #include <structmember.h>

This include provides declarations that we use to handle attributes, as
described a bit later.

The ‘Custom’ type now has three data attributes in its C struct,
`first', `last', and `number'.  The `first' and `last' variables are
Python strings containing first and last names.  The `number' attribute
is a C integer.

The object structure is updated accordingly:

     typedef struct {
         PyObject_HEAD
         PyObject *first; /* first name */
         PyObject *last;  /* last name */
         int number;
     } CustomObject;

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:

     static void
     Custom_dealloc(CustomObject *self)
     {
         Py_XDECREF(self->first);
         Py_XDECREF(self->last);
         Py_TYPE(self)->tp_free((PyObject *) self);
     }

which is assigned to the *note tp_dealloc: 3d5a. member:

     .tp_dealloc = (destructor) Custom_dealloc,

This method first clears the reference counts of the two Python
attributes.  *note Py_XDECREF(): 391. correctly handles the case where
its argument is ‘NULL’ (which might happen here if ‘tp_new’ failed
midway).  It then calls the *note tp_free: 3d5b. member of the object’s
type (computed by ‘Py_TYPE(self)’) to free the object’s memory.  Note
that the object’s type might not be ‘CustomType’, because the object may
be an instance of a subclass.

     備註: The explicit cast to ‘destructor’ above is needed because we
     defined ‘Custom_dealloc’ to take a ‘CustomObject *’ argument, but
     the ‘tp_dealloc’ function pointer expects to receive a ‘PyObject *’
     argument.  Otherwise, the compiler will emit a warning.  This is
     object-oriented polymorphism, in C!

We want to make sure that the first and last names are initialized to
empty strings, so we provide a ‘tp_new’ implementation:

     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;
     }

and install it in the *note tp_new: 3d57. member:

     .tp_new = Custom_new,

The ‘tp_new’ handler is responsible for creating (as opposed to
initializing) objects of the type.  It is exposed in Python as the *note
__new__(): 974. method.  It is not required to define a ‘tp_new’ member,
and indeed many extension types will simply reuse *note
PyType_GenericNew(): 3d58. as done in the first version of the ‘Custom’
type above.  In this case, we use the ‘tp_new’ handler to initialize the
‘first’ and ‘last’ attributes to non-‘NULL’ default values.

‘tp_new’ is passed the type being instantiated (not necessarily
‘CustomType’, if a subclass is instantiated) and any arguments passed
when the type was called, and is expected to return the instance
created.  ‘tp_new’ handlers always accept positional and keyword
arguments, but they often ignore the arguments, leaving the argument
handling to initializer (a.k.a.  ‘tp_init’ in C or ‘__init__’ in Python)
methods.

     備註: ‘tp_new’ shouldn’t call ‘tp_init’ explicitly, as the
     interpreter will do it itself.

The ‘tp_new’ implementation calls the *note tp_alloc: 3d5c. slot to
allocate memory:

     self = (CustomObject *) type->tp_alloc(type, 0);

Since memory allocation may fail, we must check the *note tp_alloc:
3d5c. result against ‘NULL’ before proceeding.

     備註: We didn’t fill the *note tp_alloc: 3d5c. slot ourselves.
     Rather *note PyType_Ready(): 3d5d. fills it for us by inheriting it
     from our base class, which is *note object: 3d2. by default.  Most
     types use the default allocation strategy.

     備註: If you are creating a co-operative *note tp_new: 3d57. (one
     that calls a base type’s *note tp_new: 3d57. or *note __new__():
     974.), you must `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 *note tp_new: 3d57.
     directly, or via ‘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 *note TypeError: 1fe.)

We also define an initialization function which accepts arguments to
provide initial values for our instance:

     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;
     }

by filling the *note tp_init: 3d5e. slot.

     .tp_init = (initproc) Custom_init,

The *note tp_init: 3d5e. slot is exposed in Python as the *note
__init__(): e23. method.  It is used to initialize an object after it’s
created.  Initializers always accept positional and keyword arguments,
and they should return either ‘0’ on success or ‘-1’ on error.

Unlike the ‘tp_new’ handler, there is no guarantee that ‘tp_init’ is
called at all (for example, the *note pickle: ca. module by default
doesn’t call *note __init__(): e23. on unpickled instances).  It can
also be called multiple times.  Anyone can call the *note __init__():
e23. 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 ‘first’ member like this:

     if (first) {
         Py_XDECREF(self->first);
         Py_INCREF(first);
         self->first = first;
     }

But this would be risky.  Our type doesn’t restrict the type of the
‘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
‘first’ member; or that destructor could release the *note Global
interpreter Lock: 20e. 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?

   * when we absolutely know that the reference count is greater than 1;

   * when we know that deallocation of the object (1) will neither
     release the *note GIL: 20e. nor cause any calls back into our
     type’s code;

   * when decrementing a reference count in a *note tp_dealloc: 3d5a.
     handler on a type which doesn’t support cyclic garbage collection
     (2).

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:

     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 */
     };

and put the definitions in the *note tp_members: 3d5f. slot:

     .tp_members = Custom_members,

Each member definition has a member name, type, offset, access flags and
documentation string.  See the *note 泛型属性管理: 3d60. 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 ‘NULL’.  Even though we can make sure the
members are initialized to non-‘NULL’ values, the members can be set to
‘NULL’ if the attributes are deleted.

We define a single method, ‘Custom.name()’, that outputs the objects
name as the concatenation of the first and last names.

     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);
     }

The method is implemented as a C function that takes a ‘Custom’ (or
‘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:

     def name(self):
         return "%s %s" % (self.first, self.last)

Note that we have to check for the possibility that our ‘first’ and
‘last’ members are ‘NULL’.  This is because they can be deleted, in
which case they are set to ‘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:

     static PyMethodDef Custom_methods[] = {
         {"name", (PyCFunction) Custom_name, METH_NOARGS,
          "Return the name, combining the first and last name"
         },
         {NULL}  /* Sentinel */
     };

(note that we used the *note METH_NOARGS: eda. flag to indicate that the
method is expecting no arguments other than `self')

and assign it to the *note tp_methods: 3d61. slot:

     .tp_methods = Custom_methods,

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 *note Py_TPFLAGS_BASETYPE: 3d62. to our
class flag definition:

     .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,

We rename ‘PyInit_custom()’ to ‘PyInit_custom2()’, update the module
name in the *note PyModuleDef: 258. struct, and update the full class
name in the *note PyTypeObject: 3f5. struct.

Finally, we update our ‘setup.py’ file to build the new module:

     from distutils.core import setup, Extension
     setup(name="custom", version="1.0",
           ext_modules=[
              Extension("custom", ["custom.c"]),
              Extension("custom2", ["custom2.c"]),
              ])

   ---------- Footnotes ----------

   (1) (1) This is true when we know that the object is a basic type,
like a string or a float.

   (2) (2) We relied on this in the *note tp_dealloc: 3d5a. handler in
this example, because our type doesn’t support garbage collection.


File: python.info,  Node: Providing finer control over data attributes,  Next: Supporting cyclic garbage collection,  Prev: Adding data and methods to the Basic example,  Up: 自定义扩展类型：教程

6.2.2.3 Providing finer control over data attributes
....................................................

In this section, we’ll provide finer control over how the ‘first’ and
‘last’ attributes are set in the ‘Custom’ example.  In the previous
version of our module, the instance variables ‘first’ and ‘last’ could
be set to non-string values or even deleted.  We want to make sure that
these attributes always contain strings.

     #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 = "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;
     }

To provide greater control, over the ‘first’ and ‘last’ attributes,
we’ll use custom getter and setter functions.  Here are the functions
for getting and setting the ‘first’ attribute:

     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;
     }

The getter function is passed a ‘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 ‘Custom’ object, the new value, and
the closure.  The new value may be ‘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 *note PyGetSetDef: 52a. structures:

     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 */
     };

and register it in the *note tp_getset: 3d64. slot:

     .tp_getset = Custom_getsetters,

The last item in a *note PyGetSetDef: 52a. structure is the "closure"
mentioned above.  In this case, we aren’t using a closure, so we just
pass ‘NULL’.

We also remove the member definitions for these attributes:

     static PyMemberDef Custom_members[] = {
         {"number", T_INT, offsetof(CustomObject, number), 0,
          "custom number"},
         {NULL}  /* Sentinel */
     };

We also need to update the *note tp_init: 3d5e. handler to only allow
strings (1) to be passed:

     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;
     }

With these changes, we can assure that the ‘first’ and ‘last’ members
are never ‘NULL’ so we can remove checks for ‘NULL’ values in almost all
cases.  This means that most of the *note Py_XDECREF(): 391. calls can
be converted to *note Py_DECREF(): 38f. calls.  The only place we can’t
change these calls is in the ‘tp_dealloc’ implementation, where there is
the possibility that the initialization of these members failed in
‘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 ‘setup.py’ file.

   ---------- Footnotes ----------

   (1) (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.


File: python.info,  Node: Supporting cyclic garbage collection,  Next: Subclassing other types,  Prev: Providing finer control over data attributes,  Up: 自定义扩展类型：教程

6.2.2.4 Supporting cyclic garbage collection
............................................

Python has a *note cyclic garbage collector (GC): fc8. 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:

     >>> l = []
     >>> l.append(l)
     >>> del l

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 ‘Custom’ example, we allowed any kind of
object to be stored in the ‘first’ or ‘last’ attributes (1).  Besides,
in the second and third versions, we allowed subclassing ‘Custom’, and
subclasses may add arbitrary attributes.  For any of those two reasons,
‘Custom’ objects can participate in cycles:

     >>> import custom3
     >>> class Derived(custom3.Custom): pass
     ...
     >>> n = Derived()
     >>> n.some_attribute = n

To allow a ‘Custom’ instance participating in a reference cycle to be
properly detected and collected by the cyclic GC, our ‘Custom’ type
needs to fill two additional slots and to enable a flag that enables
these slots:

     #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 = "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;
     }

First, the traversal method lets the cyclic GC know about subobjects
that could participate in cycles:

     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;
     }

For each subobject that can participate in cycles, we need to call the
‘visit()’ function, which is passed to the traversal method.  The
‘visit()’ function takes as arguments the subobject and the extra
argument `arg' passed to the traversal method.  It returns an integer
value that must be returned if it is non-zero.

Python provides a *note Py_VISIT(): 3d66. macro that automates calling
visit functions.  With *note Py_VISIT(): 3d66, we can minimize the
amount of boilerplate in ‘Custom_traverse’:

     static int
     Custom_traverse(CustomObject *self, visitproc visit, void *arg)
     {
         Py_VISIT(self->first);
         Py_VISIT(self->last);
         return 0;
     }

     備註: The *note tp_traverse: 23b. implementation must name its
     arguments exactly `visit' and `arg' in order to use *note
     Py_VISIT(): 3d66.

Second, we need to provide a method for clearing any subobjects that can
participate in cycles:

     static int
     Custom_clear(CustomObject *self)
     {
         Py_CLEAR(self->first);
         Py_CLEAR(self->last);
         return 0;
     }

Notice the use of the *note Py_CLEAR(): 3d67. 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 *note
Py_XDECREF(): 391. instead on the attribute before setting it to ‘NULL’,
there is a possibility that the attribute’s destructor would call back
into code that reads the attribute again (`especially' if there is a
reference cycle).

     備註: You could emulate *note Py_CLEAR(): 3d67. by writing:

          PyObject *tmp;
          tmp = self->first;
          self->first = NULL;
          Py_XDECREF(tmp);

     Nevertheless, it is much easier and less error-prone to always use
     *note Py_CLEAR(): 3d67. when deleting an attribute.  Don’t try to
     micro-optimize at the expense of robustness!

The deallocator ‘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 *note PyObject_GC_UnTrack():
f07. before clearing members.  Here is our reimplemented deallocator
using *note PyObject_GC_UnTrack(): f07. and ‘Custom_clear’:

     static void
     Custom_dealloc(CustomObject *self)
     {
         PyObject_GC_UnTrack(self);
         Custom_clear(self);
         Py_TYPE(self)->tp_free((PyObject *) self);
     }

Finally, we add the *note Py_TPFLAGS_HAVE_GC: 3d68. flag to the class
flags:

     .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,

That’s pretty much it.  If we had written custom *note tp_alloc: 3d5c.
or *note tp_free: 3d5b. handlers, we’d need to modify them for cyclic
garbage collection.  Most extensions will use the versions automatically
provided.

   ---------- Footnotes ----------

   (1) (4) Also, even with our attributes restricted to strings
instances, the user could pass arbitrary *note str: 205. subclasses and
therefore still create reference cycles.


File: python.info,  Node: Subclassing other types,  Prev: Supporting cyclic garbage collection,  Up: 自定义扩展类型：教程

6.2.2.5 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 *note PyTypeObject: 3f5. it needs.  It
can be difficult to share these *note PyTypeObject: 3f5. structures
between extension modules.

In this example we will create a ‘SubList’ type that inherits from the
built-in *note list: 1f8. type.  The new type will be completely
compatible with regular lists, but will have an additional ‘increment()’
method that increases an internal counter:

     >>> import sublist
     >>> s = sublist.SubList(range(3))
     >>> s.extend(s)
     >>> print(len(s))
     6
     >>> print(s.increment())
     1
     >>> print(s.increment())
     2

     #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 = "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;
     }

As you can see, the source code closely resembles the ‘Custom’ examples
in previous sections.  We will break down the main differences between
them.

     typedef struct {
         PyListObject list;
         int state;
     } SubListObject;

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 *note PyObject_HEAD(): d3a. at the beginning of its
structure.

When a Python object is a ‘SubList’ instance, its ‘PyObject *’ pointer
can be safely cast to both ‘PyListObject *’ and ‘SubListObject *’:

     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;
     }

We see above how to call through to the *note __init__: e23. method of
the base type.

This pattern is important when writing a type with custom *note tp_new:
3d57. and *note tp_dealloc: 3d5a. members.  The *note tp_new: 3d57.
handler should not actually create the memory for the object with its
*note tp_alloc: 3d5c, but let the base class handle it by calling its
own *note tp_new: 3d57.

The *note PyTypeObject: 3f5. struct supports a *note tp_base: 3d6a.
specifying the type’s concrete base class.  Due to cross-platform
compiler issues, you can’t fill that field directly with a reference to
*note PyList_Type: 3d6b.; it should be done later in the module
initialization function:

     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;
     }

Before calling *note PyType_Ready(): 3d5d, the type structure must have
the *note tp_base: 3d6a. slot filled in.  When we are deriving an
existing type, it is not necessary to fill out the *note tp_alloc: 3d5c.
slot with *note PyType_GenericNew(): 3d58. – the allocation function
from the base type will be inherited.

After that, calling *note PyType_Ready(): 3d5d. and adding the type
object to the module is the same as with the basic ‘Custom’ examples.

脚注
....


File: python.info,  Node: 定义扩展类型：已分类主题,  Next: 构建C/C++扩展,  Prev: 自定义扩展类型：教程,  Up: 不使用第三方工具建立擴充

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

本章节目标是提供一个各种你可以实现的类型方法及其功能的简短介绍。

这是C类型 *note PyTypeObject: 3f5. 的定义，省略了只用于调试构建的字段:

     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;

这里有 `很多' 方法。但是不要太担心，如果你要定义一个类型，通常只需要实现
少量的方法。

正如你猜到的一样，我们正要一步一步详细介绍各种处理程序。因为有大量的历史
包袱影响字段的排序，所以我们不会根据它们在结构体里定义的顺序讲解。通常非
常容易找到一个包含你需要的字段的例子，然后改变值去适应你新的类型。

     const char *tp_name; /* For printing */

类型的名字 - 上一章提到过的，会出现在很多地方，几乎全部都是为了诊断目的
。尝试选择一个好名字，对于诊断很有帮助。

     Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */

这些字段告诉运行时在创造这个类型的新对象时需要分配多少内存。Python为了可
变长度的结构（想下：字符串，元组）有些内置支持，这是 *note tp_itemsize:
3d54. 字段存在的原由。这部分稍后解释。

     const char *tp_doc;

这里你可以放置一段字符串（或者它的地址），当你想在Python脚本引用
‘obj.__doc__’ 时返回这段文档字符串。

现在我们来看一下基本类型方法 - 大多数扩展类型将实现的方法。

* Menu:

* 终结和内存释放::
* 对象展示::
* 属性管理::
* Object Comparison::
* Abstract Protocol Support::
* Weak Reference Support::
* 更多建议::


File: python.info,  Node: 终结和内存释放,  Next: 对象展示,  Up: 定义扩展类型：已分类主题

6.2.3.1 终结和内存释放
......................

     destructor tp_dealloc;

当您的类型实例的引用计数减少为零并且Python解释器想要回收它时，将调用此函
数。如果你的类型有内存可供释放或执行其他清理，你可以把它放在这里。 对象
本身也需要在这里释放。 以下是此函数的示例：

     static void
     newdatatype_dealloc(newdatatypeobject *obj)
     {
         free(obj->obj_UnderlyingDatatypePtr);
         Py_TYPE(obj)->tp_free((PyObject *)obj);
     }

If your type supports garbage collection, the destructor should call
*note PyObject_GC_UnTrack(): f07. before clearing any member fields:

     static void
     newdatatype_dealloc(newdatatypeobject *obj)
     {
         PyObject_GC_UnTrack(obj);
         Py_CLEAR(obj->other_obj);
         ...
         Py_TYPE(obj)->tp_free((PyObject *)obj);
     }

一个重要的释放器函数实现要求是把所有未决异常放着不动。这很重要是因为释放
器会被解释器频繁的调用，当栈异常退出时(而非正常返回)，不会有任何办法保护
释放器看到一个异常尚未被设置。此事释放器的任何行为都会导致额外增加的
Python代码来检查异常是否被设置。这可能导致解释器的误导性错误。正确的保护
方法是，在任何不安全的操作前，保存未决异常，然后在其完成后恢复。者可以通
过 *note PyErr_Fetch(): a4b. 和 *note PyErr_Restore(): 3d71. 函数来实现:

     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);
     }

     備註: There are limitations to what you can safely do in a
     deallocator function.  First, if your type supports garbage
     collection (using *note tp_traverse: 23b. and/or *note tp_clear:
     3d72.), some of the object’s members can have been cleared or
     finalized by the time *note tp_dealloc: 3d5a. is called.  Second,
     in *note tp_dealloc: 3d5a, your object is in an unstable state: its
     reference count is equal to zero.  Any call to a non-trivial object
     or API (as in the example above) might end up calling *note
     tp_dealloc: 3d5a. again, causing a double free and a crash.

     从 Python 3.4 开始，推荐不要在 *note tp_dealloc: 3d5a. 放复杂的终结
     代码，而是使用新的 *note tp_finalize: 3f6. 类型方法。

     也參考
     ......

     PEP 442(1) 解释了新的终结方案。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0442


File: python.info,  Node: 对象展示,  Next: 属性管理,  Prev: 终结和内存释放,  Up: 定义扩展类型：已分类主题

6.2.3.2 对象展示
................

在 Python 中，有两种方式可以生成对象的文本表示: *note repr(): 8b9. 函数
和 *note str(): 205. 函数。 (*note print(): 971. 函数会直接调用 *note
str(): 205.。) 这些处理程序都是可选的。

     reprfunc tp_repr;
     reprfunc tp_str;

*note tp_repr: 3d74. 处理程序应该返回一个字符串对象，其中包含调用它的实
例的表示形式。 下面是一个简单的例子:

     static PyObject *
     newdatatype_repr(newdatatypeobject * obj)
     {
         return PyUnicode_FromFormat("Repr-ified_newdatatype{{size:%d}}",
                                     obj->obj_UnderlyingDatatypePtr->size);
     }

如果没有指定 *note tp_repr: 3d74. 处理程序，解释器将提供一个使用 *note
tp_name: 3d75. 的表示形式以及对象的惟一标识值。

The *note tp_str: 3d76. handler is to *note str(): 205. what the *note
tp_repr: 3d74. handler described above is to *note repr(): 8b9.; that
is, it is called when Python code calls *note str(): 205. on an instance
of your object.  Its implementation is very similar to the *note
tp_repr: 3d74. function, but the resulting string is intended for human
consumption.  If *note tp_str: 3d76. is not specified, the *note
tp_repr: 3d74. handler is used instead.

下面是一个简单的例子:

     static PyObject *
     newdatatype_str(newdatatypeobject * obj)
     {
         return PyUnicode_FromFormat("Stringified_newdatatype{{size:%d}}",
                                     obj->obj_UnderlyingDatatypePtr->size);
     }


File: python.info,  Node: 属性管理,  Next: Object Comparison,  Prev: 对象展示,  Up: 定义扩展类型：已分类主题

6.2.3.3 属性管理
................

For every object which can support attributes, the corresponding type
must provide the functions that control how the attributes are resolved.
There needs to be a function which can retrieve attributes (if any are
defined), and another to set attributes (if setting attributes is
allowed).  Removing an attribute is a special case, for which the new
value passed to the handler is ‘NULL’.

Python supports two pairs of attribute handlers; a type that supports
attributes only needs to implement the functions for one pair.  The
difference is that one pair takes the name of the attribute as a
‘char*’, while the other accepts a *note PyObject*: 5b4.  Each type can
use whichever pair makes more sense for the implementation’s
convenience.

     getattrfunc  tp_getattr;        /* char * version */
     setattrfunc  tp_setattr;
     /* ... */
     getattrofunc tp_getattro;       /* PyObject * version */
     setattrofunc tp_setattro;

If accessing attributes of an object is always a simple operation (this
will be explained shortly), there are generic implementations which can
be used to provide the *note PyObject*: 5b4. version of the attribute
management functions.  The actual need for type-specific attribute
handlers almost completely disappeared starting with Python 2.2, though
there are many examples which have not been updated to use some of the
new generic mechanism that is available.

* Menu:

* 泛型属性管理::
* Type-specific Attribute Management::


File: python.info,  Node: 泛型属性管理,  Next: Type-specific Attribute Management,  Up: 属性管理

6.2.3.4 泛型属性管理
....................

大多数扩展类型只使用 `简单' 属性，那么，是什么让属性变得“简单”呢？只需要
满足下面几个条件：

  1. 当调用 *note PyType_Ready(): 3d5d. 时，必须知道属性的名称。

  2. 不需要特殊的处理来记录属性是否被查找或设置，也不需要根据值采取操作
     。

请注意，此列表不对属性的值、值的计算时间或相关数据的存储方式施加任何限制
。

When *note PyType_Ready(): 3d5d. is called, it uses three tables
referenced by the type object to create *note descriptor: 1579.s which
are placed in the dictionary of the type object.  Each descriptor
controls access to one attribute of the instance object.  Each of the
tables is optional; if all three are ‘NULL’, instances of the type will
only have attributes that are inherited from their base type, and should
leave the *note tp_getattro: 3d79. and *note tp_setattro: 3d7a. fields
‘NULL’ as well, allowing the base type to handle attributes.

表被声明为object::类型的三个字段:

     struct PyMethodDef *tp_methods;
     struct PyMemberDef *tp_members;
     struct PyGetSetDef *tp_getset;

If *note tp_methods: 3d61. is not ‘NULL’, it must refer to an array of
*note PyMethodDef: edd. structures.  Each entry in the table is an
instance of this structure:

     typedef struct PyMethodDef {
         const char  *ml_name;       /* method name */
         PyCFunction  ml_meth;       /* implementation function */
         int          ml_flags;      /* flags */
         const char  *ml_doc;        /* docstring */
     } PyMethodDef;

One entry should be defined for each method provided by the type; no
entries are needed for methods inherited from a base type.  One
additional entry is needed at the end; it is a sentinel that marks the
end of the array.  The ‘ml_name’ field of the sentinel must be ‘NULL’.

The second table is used to define attributes which map directly to data
stored in the instance.  A variety of primitive C types are supported,
and access may be read-only or read-write.  The structures in the table
are defined as:

     typedef struct PyMemberDef {
         const char *name;
         int         type;
         int         offset;
         int         flags;
         const char *doc;
     } PyMemberDef;

For each entry in the table, a *note descriptor: 1579. will be
constructed and added to the type which will be able to extract a value
from the instance structure.  The *note type: 6ff. field should contain
one of the type codes defined in the ‘structmember.h’ header; the value
will be used to determine how to convert Python values to and from C
values.  The ‘flags’ field is used to store flags which control how the
attribute can be accessed.

以下标志常量定义在:file: ’ structmember.h ’;它们可以使用bitwise-OR组合。

常数                            意义
                                
-----------------------------------------------------------------------------------
                                
‘READONLY’                      没有可写的
                                
                                
‘READ_RESTRICTED’               Not readable in restricted mode.
                                
                                
‘WRITE_RESTRICTED’              Not writable in restricted mode.
                                
                                
‘RESTRICTED’                    在受限模式下不可读，也不可写。
                                

An interesting advantage of using the *note tp_members: 3d5f. table to
build descriptors that are used at runtime is that any attribute defined
this way can have an associated doc string simply by providing the text
in the table.  An application can use the introspection API to retrieve
the descriptor from the class object, and get the doc string using its
‘__doc__’ attribute.

As with the *note tp_methods: 3d61. table, a sentinel entry with a
‘name’ value of ‘NULL’ is required.


File: python.info,  Node: Type-specific Attribute Management,  Prev: 泛型属性管理,  Up: 属性管理

6.2.3.5 Type-specific Attribute Management
..........................................

For simplicity, only the ‘char*’ version will be demonstrated here; the
type of the name parameter is the only difference between the ‘char*’
and *note PyObject*: 5b4. flavors of the interface.  This example
effectively does the same thing as the generic example above, but does
not use the generic support added in Python 2.2.  It explains how the
handler functions are called, so that if you do need to extend their
functionality, you’ll understand what needs to be done.

The *note tp_getattr: 3d7c. handler is called when the object requires
an attribute look-up.  It is called in the same situations where the
*note __getattr__(): 42a. method of a class would be called.

例如：

     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;
     }

The *note tp_setattr: 3d7d. handler is called when the *note
__setattr__(): eee. or *note __delattr__(): 1563. method of a class
instance would be called.  When an attribute should be deleted, the
third parameter will be ‘NULL’.  Here is an example that simply raises
an exception; if this were really all you wanted, the *note tp_setattr:
3d7d. handler should be set to ‘NULL’.

     static int
     newdatatype_setattr(newdatatypeobject *obj, char *name, PyObject *v)
     {
         PyErr_Format(PyExc_RuntimeError, "Read-only attribute: %s", name);
         return -1;
     }


File: python.info,  Node: Object Comparison,  Next: Abstract Protocol Support,  Prev: 属性管理,  Up: 定义扩展类型：已分类主题

6.2.3.6 Object Comparison
.........................

     richcmpfunc tp_richcompare;

The *note tp_richcompare: 3d7f. handler is called when comparisons are
needed.  It is analogous to the *note rich comparison methods: 156b,
like *note __lt__(): cfe, and also called by *note
PyObject_RichCompare(): 3d80. and *note PyObject_RichCompareBool():
109c.

This function is called with two Python objects and the operator as
arguments, where the operator is one of ‘Py_EQ’, ‘Py_NE’, ‘Py_LE’,
‘Py_GE’, ‘Py_LT’ or ‘Py_GT’.  It should compare the two objects with
respect to the specified operator and return ‘Py_True’ or ‘Py_False’ if
the comparison is successful, ‘Py_NotImplemented’ to indicate that
comparison is not implemented and the other object’s comparison method
should be tried, or ‘NULL’ if an exception was set.

Here is a sample implementation, for a datatype that is considered equal
if the size of an internal pointer is equal:

     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;
      }


File: python.info,  Node: Abstract Protocol Support,  Next: Weak Reference Support,  Prev: Object Comparison,  Up: 定义扩展类型：已分类主题

6.2.3.7 Abstract Protocol Support
.................................

Python supports a variety of `abstract' ’protocols;’ the specific
interfaces provided to use these interfaces are documented in *note
抽象物件層: 3d82.

A number of these abstract interfaces were defined early in the
development of the Python implementation.  In particular, the number,
mapping, and sequence protocols have been part of Python since the
beginning.  Other protocols have been added over time.  For protocols
which depend on several handler routines from the type implementation,
the older protocols have been defined as optional blocks of handlers
referenced by the type object.  For newer protocols there are additional
slots in the main type object, with a flag bit being set to indicate
that the slots are present and should be checked by the interpreter.
(The flag bit does not indicate that the slot values are non-‘NULL’.
The flag may be set to indicate the presence of a slot, but a slot may
still be unfilled.)

     PyNumberMethods   *tp_as_number;
     PySequenceMethods *tp_as_sequence;
     PyMappingMethods  *tp_as_mapping;

If you wish your object to be able to act like a number, a sequence, or
a mapping object, then you place the address of a structure that
implements the C type *note PyNumberMethods: e46, *note
PySequenceMethods: 3d83, or *note PyMappingMethods: 3d84, respectively.
It is up to you to fill in this structure with appropriate values.  You
can find examples of the use of each of these in the ‘Objects’ directory
of the Python source distribution.

     hashfunc tp_hash;

This function, if you choose to provide it, should return a hash number
for an instance of your data type.  Here is a simple 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;
     }

‘Py_hash_t’ is a signed integer type with a platform-varying width.
Returning ‘-1’ from *note tp_hash: 3d85. indicates an error, which is
why you should be careful to avoid returning it when hash computation is
successful, as seen above.

     ternaryfunc tp_call;

This function is called when an instance of your data type is "called",
for example, if ‘obj1’ is an instance of your data type and the Python
script contains ‘obj1('hello')’, the *note tp_call: 3d86. handler is
invoked.

This function takes three arguments:

  1. `self' is the instance of the data type which is the subject of the
     call.  If the call is ‘obj1('hello')’, then `self' is ‘obj1’.

  2. `args' is a tuple containing the arguments to the call.  You can
     use *note PyArg_ParseTuple(): 393. to extract the arguments.

  3. `kwds' is a dictionary of keyword arguments that were passed.  If
     this is non-‘NULL’ and you support keyword arguments, use *note
     PyArg_ParseTupleAndKeywords(): 6c1. to extract the arguments.  If
     you do not want to support keyword arguments and this is
     non-‘NULL’, raise a *note TypeError: 1fe. with a message saying
     that keyword arguments are not supported.

Here is a toy ‘tp_call’ implementation:

     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;
     }

     /* Iterators */
     getiterfunc tp_iter;
     iternextfunc tp_iternext;

These functions provide support for the iterator protocol.  Both
handlers take exactly one parameter, the instance for which they are
being called, and return a new reference.  In the case of an error, they
should set an exception and return ‘NULL’.  *note tp_iter: ef2.
corresponds to the Python *note __iter__(): 608. method, while *note
tp_iternext: ef3. corresponds to the Python *note __next__(): d2c.
method.

Any *note iterable: c7c. object must implement the *note tp_iter: ef2.
handler, which must return an *note iterator: 1171. object.  Here the
same guidelines apply as for Python classes:

   * For collections (such as lists and tuples) which can support
     multiple independent iterators, a new iterator should be created
     and returned by each call to *note tp_iter: ef2.

   * Objects which can only be iterated over once (usually due to side
     effects of iteration, such as file objects) can implement *note
     tp_iter: ef2. by returning a new reference to themselves – and
     should also therefore implement the *note tp_iternext: ef3.
     handler.

Any *note iterator: 1171. object should implement both *note tp_iter:
ef2. and *note tp_iternext: ef3.  An iterator’s *note tp_iter: ef2.
handler should return a new reference to the iterator.  Its *note
tp_iternext: ef3. handler should return a new reference to the next
object in the iteration, if there is one.  If the iteration has reached
the end, *note tp_iternext: ef3. may return ‘NULL’ without setting an
exception, or it may set *note StopIteration: 581. `in addition' to
returning ‘NULL’; avoiding the exception can yield slightly better
performance.  If an actual error occurs, *note tp_iternext: ef3. should
always set an exception and return ‘NULL’.


File: python.info,  Node: Weak Reference Support,  Next: 更多建议,  Prev: Abstract Protocol Support,  Up: 定义扩展类型：已分类主题

6.2.3.8 Weak Reference Support
..............................

One of the goals of Python’s weak reference implementation is to allow
any type to participate in the weak reference mechanism without
incurring the overhead on performance-critical objects (such as
numbers).

也參考
......

Documentation for the *note weakref: 131. module.

For an object to be weakly referencable, the extension type must do two
things:

  1. Include a *note PyObject*: 5b4. field in the C object structure
     dedicated to the weak reference mechanism.  The object’s
     constructor should leave it ‘NULL’ (which is automatic when using
     the default *note tp_alloc: 3d5c.).

  2. Set the *note tp_weaklistoffset: 26b. type member to the offset of
     the aforementioned field in the C object structure, so that the
     interpreter knows how to access and modify that field.

Concretely, here is how a trivial object structure would be augmented
with the required field:

     typedef struct {
         PyObject_HEAD
         PyObject *weakreflist;  /* List of weak references */
     } TrivialObject;

And the corresponding member in the statically-declared type object:

     static PyTypeObject TrivialType = {
         PyVarObject_HEAD_INIT(NULL, 0)
         /* ... other members omitted for brevity ... */
         .tp_weaklistoffset = offsetof(TrivialObject, weakreflist),
     };

The only further addition is that ‘tp_dealloc’ needs to clear any weak
references (by calling ‘PyObject_ClearWeakRefs()’) if the field is
non-‘NULL’:

     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);
     }


File: python.info,  Node: 更多建议,  Prev: Weak Reference Support,  Up: 定义扩展类型：已分类主题

6.2.3.9 更多建议
................

In order to learn how to implement any specific method for your new data
type, get the *note CPython: 1569. source code.  Go to the ‘Objects’
directory, then search the C source files for ‘tp_’ plus the function
you want (for example, ‘tp_richcompare’).  You will find examples of the
function you want to implement.

When you need to verify that an object is a concrete instance of the
type you are implementing, use the *note PyObject_TypeCheck(): 3d89.
function.  A sample of its use might be something like the following:

     if (!PyObject_TypeCheck(some_object, &MyType)) {
         PyErr_SetString(PyExc_TypeError, "arg #1 not a mything");
         return NULL;
     }

也參考
......

下载CPython源代码版本。

     ‘https://www.python.org/downloads/source/’

GitHub上开发CPython源代码的CPython项目。

     ‘https://github.com/python/cpython’


File: python.info,  Node: 构建C/C++扩展,  Next: 在 Windows 上构建 C 和 C++ 扩展,  Prev: 定义扩展类型：已分类主题,  Up: 不使用第三方工具建立擴充

6.2.4 构建C/C++扩展
-------------------

一个CPython的C扩展是一个共享库(例如一个Linux上的 ‘.so’ ，或者Windows上的
‘.pyd’ )，其会导出一个 `初始化函数' 。

为了可导入，共享库必须在 *note PYTHONPATH: a34. 中有效，且必须命名遵循模
块名字，通过适当的扩展。当使用distutils时，会自动生成正确的文件名。

初始化函数的声明如下：

 -- C 函式: PyObject* PyInit_modulename (void)

该函数返回完整初始化过的模块，或一个 *note PyModuleDef: 258. 实例。查看
*note Initializing C modules: 3d8d. 了解更多细节。

对于仅有ASCII编码的模块名，函数必须是 ‘PyInit_<modulename>’ ，将
‘<modulename>’ 替换为模块的名字。当使用 *note Multi-phase
initialization: 3d8e. 时，允许使用非ASCII编码的模块名。此时初始化函数的
名字是 ‘PyInitU_<modulename>’ ，而 ‘<modulename>’ 需要用Python的
`punycode' 编码，连字号需替换为下划线。在Python里:

     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

可以在一个动态库里导出多个模块，通过定义多个初始化函数。而导入他们需要符
号链接或自定义导入器，因为缺省时只有对应了文件名的函数才会被发现。查看
`"一个库里的多模块"' 章节，在 PEP 489(1) 了解更多细节。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0489


File: python.info,  Node: 使用distutils构建C和C++扩展,  Next: 发布你的扩展模块,  Up: 构建C/C++扩展

6.2.4.1 使用distutils构建C和C++扩展
...................................

扩展模块可以用distutils来构建，这是Python自带的。distutils也支持创建二进
制包，用户无需编译器而distutils就能安装扩展。

一个distutils包包含了一个驱动脚本 ‘setup.py’ 。这是个纯Python文件，大多
数时候也很简单，看起来如下：

     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])

通过文件 ‘setup.py’ ，和文件 ‘demo.c’ ，运行如下

     python setup.py build

这会编译 ‘demo.c’ ，然后产生一个扩展模块叫做 ‘demo’ 在目录 ‘build’ 里。
依赖于系统，模块文件会放在某个子目录形如 ‘build/lib.system’ ，名字可能是
‘demo.so’ 或 ‘demo.pyd’ 。

在文件 ‘setup.py’ 里，所有动作的入口通过 ‘setup’ 函数。该函数可以接受可
变数量个关键字参数，上面的例子只使用了一个子集。特别需要注意的例子指定了
构建包的元信息，以及指定了包内容。通常一个包会包括多个模块，就像Python的
源码模块、文档、子包等。请参数distutils的文档，在 *note 發布 Python
模組（舊版）: 8e5. 来了解更多distutils的特性；本章节只解释构建扩展模块的
部分。

通常预计算参数给 ‘setup()’ ，想要更好的结构化驱动脚本。有如如上例子函数
*note setup(): 3d90. 的 ‘ext_modules’ 参数是一列扩展模块，每个是一个
‘Extension’ 类的实例。例子中的实例定义了扩展命名为 ‘demo’ ，从单一源码文
件构建 ‘demo.c’ 。

更多时候，构建一个扩展会复杂的多，需要额外的预处理器定义和库。如下例子展
示了这些。

     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 = '''
     This is really just a demo package.
     ''',
            ext_modules = [module1])

例子中函数 *note setup(): 3d90. 在调用时额外传递了元信息，是推荐发布包构
建时的内容。对于这个扩展，其指定了预处理器定义，include目录，库目录，库
。依赖于编译器，distutils还会用其他方式传递信息给编译器。例如在Unix上，
结果是如下编译命令

     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

这些行代码仅用于展示目的；distutils用户应该相信distutils能正确调用。


File: python.info,  Node: 发布你的扩展模块,  Prev: 使用distutils构建C和C++扩展,  Up: 构建C/C++扩展

6.2.4.2 发布你的扩展模块
........................

当一个扩展已经成功地被构建时，有三种方式来使用它。

最终用户通常想要安装模块，可以这么运行

     python setup.py install

模块维护者应该制作源码包；要实现可以运行

     python setup.py sdist

有些情况下，需要在源码发布包里包含额外的文件；这通过 ‘MANIFEST.in’ 文件
实现，查看 *note Specifying the files to distribute: 3d93. 了解细节。

如果源码发行包被成功地构建，维护者还可以创建二进制发行包。 取决于具体平
台，以下命令中的一个可以用来完成此任务

     python setup.py bdist_wininst
     python setup.py bdist_rpm
     python setup.py bdist_dumb


File: python.info,  Node: 在 Windows 上构建 C 和 C++ 扩展,  Prev: 构建C/C++扩展,  Up: 不使用第三方工具建立擴充

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

这一章简要介绍了如何使用 Microsoft Visual C++ 创建 Python 的 Windows 扩
展模块，然后再提供有关其工作机理的详细背景信息。 这些说明材料同时适用于
Windows 程序员学习构建 Python 扩展以及 Unix 程序员学习如何生成在 Unix 和
Windows 上均能成功构建的软件。

鼓励模块作者使用 distutils 方式来构建扩展模块，而不使用本节所描述的方式
。 你仍将需要使用 C 编译器来构建 Python；通常为 Microsoft Visual C++。

     備註: 这一章提及了多个包括已编码 Python 版本号的文件名。 这些文件名
     以显示为 ‘XY’ 的版本号来代表；在实践中，‘'X'’ 将为你所使用的 Python
     发布版的主版本号而 ‘'Y'’ 将为次版本号。 例如，如果你所使用的是
     Python 2.2.1，‘XY’ 将为 ‘22’。

* Menu:

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


File: python.info,  Node: 菜谱式说明,  Next: Unix 和 Windows 之间的差异,  Up: 在 Windows 上构建 C 和 C++ 扩展

6.2.5.1 菜谱式说明
..................

在 Windows 和 Unix 上构建扩展模块都有两种方式：使用 *note distutils: 38.
包来控制构建过程，或者全手动操作。 distutils 方式适用于大多数扩展；使用
*note distutils: 38. 构建和打包扩展模块的文档见 *note 發布 Python
模組（舊版）: 8e5.。 如果你发现你确实需要手动操作，那么研究一下
winsound(1) 标准库模块的项目文件可能会很有帮助。

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/PCbuild/winsound.vcxproj


File: python.info,  Node: Unix 和 Windows 之间的差异,  Next: DLL 的实际使用,  Prev: 菜谱式说明,  Up: 在 Windows 上构建 C 和 C++ 扩展

6.2.5.2 Unix 和 Windows 之间的差异
..................................

Unix 和 Windows 对于代码的运行时加载使用了完全不同的范式。 在你尝试构建
可动态加载的模块之前，要先了解你所用系统是如何工作的。

在 Unix 中，一个共享对象 (‘.so’) 文件中包含将由程序来使用的代码，也包含
在程序中可被找到的函数名称和数据。 当文件被合并到程序中时，对在文件代码
中这些函数和数据的全部引用都会被改为指向程序中函数和数据在内存中所放置的
实际位置。 这基本上是一个链接操作。

在 Windows 中，一个动态链接库 (‘.dll’) 文件中没有悬挂的引用。 而是通过一
个查找表执行对函数或数据的访问。 因此在运行时 DLL 代码不必在运行时进行修
改；相反地，代码已经使用了 DLL 的查找表，并且在运行时查找表会被修改以指
向特定的函数和数据。

在 Unix 中，只存在一种库文件 (‘.a’)，它包含来自多个对象文件 (‘.o’) 的代
码。 在创建共享对象文件 (‘.so’) 的链接阶段，链接器可能会发现它不知道某个
标识符是在哪里定义的。 链接器将在各个库的对象文件中查找它；如果找到了它
，链接器将会包括来自该对象文件的所有代码。

在 Windows 中，存在两种库类型，静态库和导入库 (扩展名都是 ‘.lib’)。 静态
库类似于 Unix 的 ‘.a’ 文件；它包含在必要时可被包括的代码。 导入库基本上
仅用于让链接器能确保特定标识符是合法的，并且将在 DLL 被加载时出现于程序
中。 这样链接器可使用来自导入库的信息构建查找表以便使用未包括在 DLL 中的
标识符。 当一个应用程序或 DLL 被链接时，可能会生成一个导入库，它将需要被
用于应用程序或 DLL 中未来所有依赖于这些符号的 DLL。

假设你正在编译两个动态加载模块 B 和 C，它们应当共享另一个代码块 A。 在
Unix 上，你 `不应' 将 ‘A.a’ 传给链接器作为 ‘B.so’ 和 ‘C.so’；那会导致它
被包括两次，这样 B 和 C 将分别拥有它们自己的副本。 在 Windows 上，编译
‘A.dll’ 将同时编译 ‘A.lib’。 你 `应当' 将 ‘A.lib’ 传给链接器用于 B 和 C。
‘A.lib’ 并不包含代码；它只包含将在运行时被用于访问 A 的代码的信息。

在 Windows 上，使用导入库有点像是使用 ‘import spam’；它让你可以访问 spam
中的名称，但并不会创建一个单独副本。 在 Unix 上，链接到一个库更像是
‘from spam import *’；它会创建一个单独副本。


File: python.info,  Node: DLL 的实际使用,  Prev: Unix 和 Windows 之间的差异,  Up: 在 Windows 上构建 C 和 C++ 扩展

6.2.5.3 DLL 的实际使用
......................

Windows 版 Python 是用 Microsoft Visual C++ 编译的；使用其他编译器可能行
也可能不行（但 Borland 看来是可以的）。 这一节的剩余部分只适用于 MSVC++。

当在 Windows 中创建 DLL 时，你必须将 ‘pythonXY.lib’ 传给链接器。 要编译
两个 DLL，spam 和 ni (会使用 spam 中找到的 C 函数)，你应当使用以下命令:

     cl /LD /I/python/include spam.c ../libs/pythonXY.lib
     cl /LD /I/python/include ni.c spam.lib ../libs/pythonXY.lib

第一条命令创建了三个文件: ‘spam.obj’, ‘spam.dll’ 和 ‘spam.lib’。
‘Spam.dll’ 不包含任何 Python 函数 (例如 *note PyArg_ParseTuple(): 393.)，
但它通过 ‘pythonXY.lib’ 可以知道如何找到所需的 Python 代码。

第二条命令创建了 ‘ni.dll’ (以及 ‘.obj’ 和 ‘.lib’)，它知道如何从 spam 以
及 Python 可执行文件中找到所需的函数。

不是每个标识符都会被导出到查找表。 如果你想要任何其他模块（包括 Python）
都能看到你的标识符，你必须写上 ‘_declspec(dllexport)’，就如在 ‘void
_declspec(dllexport) initspam(void)’ 或 ‘PyObject _declspec(dllexport)
*NiGetSpamData(void)’ 中一样。

Developer Studio 将加入大量你并不真正需要的导入库，使你的可执行文件大小
增加 100K。 要摆脱它们，请使用项目设置对话框的链接选项卡指定 `忽略默认库
'。 将正确的 ‘msvcrtxx.lib’ 添加到库列表中。


File: python.info,  Node: 在更大的應用程式中嵌入 CPython 運行環境 runtime,  Prev: 不使用第三方工具建立擴充,  Up: 擴充和嵌入 Python 直譯器

6.3 在更大的應用程式中嵌入 CPython 運行環境 (runtime)
=====================================================

有時候，相較於建立一個擴充，使其在 Python 直譯器中可作為主應用程式運行，
還不如將 CPython 運行環境嵌入至一個更大的應用程式中更可取。本節將涵蓋一
些要成功完成此任務所涉及的細節。

* Menu:

* 在其它 App 內嵌入 Python::


File: python.info,  Node: 在其它 App 內嵌入 Python,  Up: 在更大的應用程式中嵌入 CPython 運行環境 runtime

6.3.1 在其它 App 內嵌入 Python
------------------------------

前几章讨论了如何对 Python 进行扩展，也就是如何用 C 函数库 扩展 Python 的
功能。反过来也是可以的：将 Python 嵌入到 C/C++ 应用程序中丰富其功能。这
种嵌入可以让应用程序用 Python 来实现某些功能，而不是用 C 或 C++ 。用途会
有很多；比如允许用户用 Python 编写一些脚本，以便定制应用程序满足需求。如
果某些功能用 Python 编写起来更为容易，那么开发人员自己也能这么干。

Python 的嵌入类似于扩展，但不完全相同。不同之处在于，扩展 Python 时应用
程序的主程序仍然是 Python 解释器，而嵌入 Python 时的主程序可能与 Python
完全无关——而是应用程序的某些部分偶尔会调用 Python 解释器来运行一些
Python 代码。

因此，若要嵌入 Python，就要提供自己的主程序。此主程序要做的事情之一就是
初始化 Python 解释器。至少得调用函数 *note Py_Initialize(): 20f.。还有些
可选的调用可向 Python 传递命令行参数。之后即可从应用程序的任何地方调用解
释器了。

调用解释器的方式有好几种：可向 *note PyRun_SimpleString(): 3da0. 传入一
个包含 Python 语句的字符串，也可向 *note PyRun_SimpleFile(): 3da1. 传入
一个 stdio 文件指针和一个文件名（仅在错误信息中起到识别作用）。还可以调
用前面介绍过的底层操作来构造并使用 Python 对象。

也參考
......

*note Python/C API 參考手冊: 1333.

     本文详细介绍了 Python 的 C 接口。这里有大量必要的信息。

* Menu:

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


File: python.info,  Node: 高层次的嵌入,  Next: 突破高层次嵌入的限制：概述,  Up: 在其它 App 內嵌入 Python

6.3.1.1 高层次的嵌入
....................

最简单的 Python 嵌入形式就是采用非常高层的接口。该接口的目标是只执行一段
Python 脚本，而无需与应用程序直接交互。比如以下代码可以用来对某个文件进
行一些操作。

     #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;
     }

在 *note Py_Initialize(): 20f. 之前，应该先调用 *note
Py_SetProgramName(): 10f2. 函数，以便向解释器告知 Python运行库的路径。接
下来，*note Py_Initialize(): 20f. 会初始化 Python 解释器，然后执行硬编码
的 Python 脚本，打印出日期和时间。之后，调用 *note Py_FinalizeEx(): 6c0.
关闭解释器，程序结束。在真实的程序中，可能需要从其他来源获取 Python 脚本
，或许是从文本编辑器例程、文件，或者某个数据库。利用 *note
PyRun_SimpleFile(): 3da1. 函数可以更好地从文件中获取 Python 代码，可省去
分配内存空间和加载文件内容的麻烦。


File: python.info,  Node: 突破高层次嵌入的限制：概述,  Next: 纯嵌入,  Prev: 高层次的嵌入,  Up: 在其它 App 內嵌入 Python

6.3.1.2 突破高层次嵌入的限制：概述
..................................

高级接口能从应用程序中执行任何 Python 代码，但至少交换数据可说是相当麻烦
的。如若需要交换数据，应使用较低级别的调用。几乎可以实现任何功能，代价是
得写更多的 C 代码。

应该注意，尽管意图不同，但扩展 Python 和嵌入 Python 的过程相当类似。前几
章中讨论的大多数主题依然有效。为了说明这一点，不妨来看一下从 Python 到 C
的扩展代码到底做了什么：

  1. 转换 Python 的数据值到 C,

  2. 用转换后的数据执行 C 程序的函数调用，以及

  3. 将调用返回的数据从 C 转换为 Python 格式。

嵌入 Python 时，接口代码会这样做：

  1. 转换 C 的数据值到 Python,

  2. 用转换后的数据执行对 Python 接口的函数调用，

  3. 将调用返回的数据从 Python 转换为 C 格式。

可见只是数据转换的步骤交换了一下顺序，以顺应跨语言的传输方向。唯一的区别
是在两次数据转换之间调用的函数不同。在执行扩展时，调用一个 C 函数，而执
行嵌入时调用的是个 Python 函数。

本文不会讨论如何将数据从 Python 转换到 C 去，反之亦然。另外还假定读者能
够正确使用引用并处理错误。由于这些地方与解释器的扩展没有区别，请参考前面
的章节以获得所需的信息。


File: python.info,  Node: 纯嵌入,  Next: 对嵌入 Python 功能进行扩展,  Prev: 突破高层次嵌入的限制：概述,  Up: 在其它 App 內嵌入 Python

6.3.1.3 纯嵌入
..............

第一个程序的目标是执行 Python 脚本中的某个函数。就像高层次接口那样，
Python 解释器并不会直接与应用程序进行交互（但下一节将改变这一点）。

要运行 Python 脚本中定义的函数，代码如下：

     #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;
     }

上述代码先利用 ‘argv[1]’ 加载 Python 脚本，再调用 ‘argv[2]’ 指定的函数。
函数的整数参数是 ‘argv’ 数组中的其余值。如果 *note 编译并链接: 3da8. 该
程序（此处将最终的可执行程序称作 ‘call’）, 并用它执行一个 Python 脚本，
例如：

     def multiply(a,b):
         print("Will compute", a, "times", b)
         c = 0
         for i in range(0, a):
             c = c + b
         return c

然后结果应该是:

     $ call multiply multiply 3 2
     Will compute 3 times 2
     Result of call: 6

尽管相对其功能而言，该程序体积相当庞大，但大部分代码是用于 Python 和 C 之
间的数据转换，以及报告错误。嵌入 Python 的有趣部分从此开始：

     Py_Initialize();
     pName = PyUnicode_DecodeFSDefault(argv[1]);
     /* Error checking of pName left out */
     pModule = PyImport_Import(pName);

初始化解释器之后，则用 *note PyImport_Import(): e24. 加载脚本。此函数的
参数需是个 Python 字符串，一个用 *note PyUnicode_FromString(): 3da9. 数
据转换函数构建的字符串。

     pFunc = PyObject_GetAttrString(pModule, argv[2]);
     /* pFunc is a new reference */

     if (pFunc && PyCallable_Check(pFunc)) {
         ...
     }
     Py_XDECREF(pFunc);

脚本一旦加载完毕，就会用 *note PyObject_GetAttrString(): 3d38. 查找属性
名称。如果名称存在，并且返回的是可调用对象，即可安全地视其为函数。然后程
序继续执行，照常构建由参数组成的元组。然后用以下方式调用 Python 函数：

     pValue = PyObject_CallObject(pFunc, pArgs);

当函数返回时，‘pValue’ 要么为 ‘NULL’，要么包含对函数返回值的引用。请确保
用完后释放该引用。


File: python.info,  Node: 对嵌入 Python 功能进行扩展,  Next: 在 C++ 中嵌入 Python,  Prev: 纯嵌入,  Up: 在其它 App 內嵌入 Python

6.3.1.4 对嵌入 Python 功能进行扩展
..................................

到目前为止，嵌入的 Python 解释器还不能访问应用程序本身的功能。Python API
通过扩展嵌入解释器实现了这一点。 也就是说，用应用程序提供的函数对嵌入的
解释器进行扩展。虽然听起来有些复杂，但也没那么糟糕。只要暂时忘记是应用程
序启动了 Python 解释器。而把应用程序看作是一堆子程序，然后写一些胶水代码
让 Python 访问这些子程序，就像编写普通的 Python 扩展程序一样。 例如：

     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);
     }

在 ‘main()’ 函数之前插入上述代码。并在调用 *note Py_Initialize(): 20f. 之
前插入以下两条语句：

     numargs = argc;
     PyImport_AppendInittab("emb", &PyInit_emb);

这两行代码初始化了 ‘numargs’ 变量，并让 ‘emb.numargs()’ 函数能被嵌入的
Python 解释器访问到。有了这些扩展，Python 脚本可以执行类似以下功能：

     import emb
     print("Number of arguments", emb.numargs())

在真实的应用程序中，这种方法将把应用的 API 暴露给 Python 使用。


File: python.info,  Node: 在 C++ 中嵌入 Python,  Next: 在类 Unix 系统中编译和链接,  Prev: 对嵌入 Python 功能进行扩展,  Up: 在其它 App 內嵌入 Python

6.3.1.5 在 C++ 中嵌入 Python
............................

还可以将 Python 嵌入到 C++ 程序中去；确切地说，实现方式将取决于 C++ 系统
的实现细节；一般需用 C++ 编写主程序，并用 C++ 编译器来编译和链接 程序。
不需要用 C++ 重新编译 Python 本身。


File: python.info,  Node: 在类 Unix 系统中编译和链接,  Prev: 在 C++ 中嵌入 Python,  Up: 在其它 App 內嵌入 Python

6.3.1.6 在类 Unix 系统中编译和链接
..................................

为了将 Python 解释器嵌入应用程序，找到正确的编译参数传给编译器 (和链接器
) 并非易事，特别是因为 Python 加载的库模块是以 C 动态扩展（‘.so’ 文件）
的形式实现的。

为了得到所需的编译器和链接器参数，可执行 ‘python`X.Y'-config’ 脚本，它是
在安装 Python 时生成的（也可能存在 ‘python3-config’ 脚本）。该脚本有几个
参数，其中以下几个参数会直接有用：

   * ‘pythonX.Y-config --cflags’ 将给出建议的编译参数。

          $ /opt/bin/python3.4-config --cflags
          -I/opt/include/python3.4m -I/opt/include/python3.4m -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes

   * ‘pythonX.Y-config --ldflags’ 将给出建议的链接参数。

          $ /opt/bin/python3.4-config --ldflags
          -L/opt/lib/python3.4/config-3.4m -lpthread -ldl -lutil -lm -lpython3.4m -Xlinker -export-dynamic

     備註: 为了避免多个 Python 安装版本引发混乱（特别是在系统安装版本和
     自己编译版本之间），建议用 ‘python`X.Y'-config’ 指定绝对路径，如上
     例所述。

如果上述方案不起作用（不能保证对所有 Unix 类平台都生效；欢迎提出 *note
bug 报告: 3daf.），就得阅读系统关于动态链接的文档，并检查 Python 的
‘Makefile’ （用 *note sysconfig.get_makefile_filename(): 37ea. 找到所在
位置）和编译参数。这时 *note sysconfig: fe. 模块会是个有用的工具，可用编
程方式提取需组合在一起的配置值。比如：

     >>> import sysconfig
     >>> sysconfig.get_config_var('LIBS')
     '-lpthread -ldl  -lutil'
     >>> sysconfig.get_config_var('LINKFORSHARED')
     '-Xlinker -export-dynamic'


File: python.info,  Node: Python/C API 參考手冊,  Next: 發布 Python 模組,  Prev: 擴充和嵌入 Python 直譯器,  Up: Top

7 Python/C API 參考手冊
***********************

對於想要編寫擴充模組或是嵌入 Python 的 C 和 C++ 程式設計師們，這份手冊記
錄了可使用的 API（應用程式介面）。在*note 擴充和嵌入 Python 直譯器:
1332.中也有相關的內容，它描述了編寫擴充的一般原則，但並沒有詳細說明 API
函式。

* Menu:

* 簡介: 簡介<12>.
* 稳定的应用程序二进制接口::
* The Very High Level Layer::
* 參照計數::
* 例外處理::
* 工具: 工具<2>.
* 抽象物件層::
* 具体的对象层::
* 初始化，终结和线程::
* Python初始化配置::
* 記憶體管理::
* 对象实现支持::
* API 和 ABI 版本管理::


File: python.info,  Node: 簡介<12>,  Next: 稳定的应用程序二进制接口,  Up: Python/C API 參考手冊

7.1 簡介
========

Python 的应用编程接口（API）使得 C 和 C++ 程序员可以在多个层级上访问
Python 解释器。该 API 在 C++ 中同样可用，但为简化描述，通常将其称为
Python/C API。使用 Python/C API 有两个基本的理由。第一个理由是为了特定目
的而编写 `扩展模块'；它们是扩展 Python 解释器功能的 C 模块。这可能是最常
见的使用场景。第二个理由是将 Python 用作更大规模应用的组件；这种技巧通常
被称为在一个应用中 `embedding' Python。

编写扩展模块的过程相对来说更易于理解，可以通过“菜谱”的形式分步骤介绍。使
用某些工具可在一定程度上自动化这一过程。虽然人们在其他应用中嵌入 Python
的做法早已有之，但嵌入 Python 的过程没有编写扩展模块那样方便直观。

许多 API 函数在你嵌入或是扩展 Python 这两种场景下都能发挥作用；此外，大
多数嵌入 Python 的应用程序也需要提供自定义扩展，因此在尝试在实际应用中嵌
入 Python 之前先熟悉编写扩展应该会是个好主意。

* Menu:

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


File: python.info,  Node: 代码标准,  Next: 包含文件,  Up: 簡介<12>

7.1.1 代码标准
--------------

如果你想要编写可包含于 CPython 的 C 代码，你 `必须' 遵循在 PEP 7(1) 中定
义的指导原则和标准。这些指导原则适用于任何你所要扩展的 Python 版本。在编
写你自己的第三方扩展模块时可以不必遵循这些规范，除非你准备在日后向
Python 贡献这些模块。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0007


File: python.info,  Node: 包含文件,  Next: 有用的宏,  Prev: 代码标准,  Up: 簡介<12>

7.1.2 包含文件
--------------

使用 Python/C API 所需要的全部函数、类型和宏定义可通过下面这行语句包含到
你的代码之中：

     #define PY_SSIZE_T_CLEAN
     #include <Python.h>

这意味着包含以下标准头文件：‘<stdio.h>’，‘<string.h>’，‘<errno.h>’，
‘<limits.h>’，‘<assert.h>’ 和 ‘<stdlib.h>’（如果可用）。

     備註: 由于 Python 可能会定义一些能在某些系统上影响标准头文件的预处
     理器定义，因此在包含任何标准头文件之前，你 `必须' 先包含
     ‘Python.h’。

     推荐总是在 ‘Python.h’ 前定义 ‘PY_SSIZE_T_CLEAN’ 。查看 *note
     语句解释及变量编译: 3f2. 来了解这个宏的更多内容。

Python.h 所定义的全部用户可见名称（由包含的标准头文件所定义的除外）都带
有前缀 ‘Py’ 或者 ‘_Py’。以 ‘_Py’ 打头的名称是供 Python 实现内部使用的，
不应被扩展编写者使用。结构成员名称没有保留前缀。

     備註: 用户代码永远不应该定义以 ‘Py’ 或 ‘_Py’ 开头的名称。这会使读者
     感到困惑，并危及用户代码对未来Python版本的可移植性，这些版本可能会
     定义以这些前缀之一开头的其他名称。

头文件通常会与 Python 一起安装。在 Unix 上，它们位于以下目录：
‘`prefix'/include/pythonversion/’ 和
‘`exec_prefix'/include/pythonversion/’，其中 ‘prefix’ 和 ‘exec_prefix’ 是
由向 Python 的 ‘configure’ 脚本传入的对应形参所定义，而 `version' 则为
‘'%d.%d' % sys.version_info[:2]’。在 Windows 上，头文件安装于
‘`prefix'/include’，其中 ‘prefix’ 是向安装程序指定的安装目录。

要包含头文件，请将两个目录（如果不同）都放到你所用编译器的包含搜索路径中
。请 `不要' 将父目录放入搜索路径然后使用 ‘#include
<pythonX.Y/Python.h>’；这将使得多平台编译不可用，因为 ‘prefix’ 下平台无
关的头文件需要包含来自 ‘exec_prefix’ 下特定平台的头文件。

C++ 用户应该注意，尽管 API 是完全使用 C 来定义的，但头文件正确地将入口点
声明为 ‘extern "C"’，因此 API 在 C++ 中使用此 API 不必再做任何特殊处理。


File: python.info,  Node: 有用的宏,  Next: 对象、类型和引用计数,  Prev: 包含文件,  Up: 簡介<12>

7.1.3 有用的宏
--------------

Python 头文件中定义了一些有用的宏。许多是在靠近它们被使用的地方定义的（
例如 *note Py_RETURN_NONE: e9b.）。其他更为通用的则定义在这里。这里所显
示的并不是一个完整的列表。

 -- C 巨集: Py_UNREACHABLE ()

     这个可以在你有一个设计上无法到达的代码路径时使用。例如，当一个
     ‘switch’ 语句中所有可能的值都已被 ‘case’ 子句覆盖了，就可将其用在
     ‘default:’ 子句中。当你非常想在某个位置放一个 ‘assert(0)’ 或
     ‘abort()’ 调用时也可以用这个。

     在 release 模式下，该宏帮助编译器优化代码，并避免发出不可到达代码的
     警告。例如，在 GCC 的 release 模式下，该宏使用
     ‘__builtin_unreachable()’ 实现。

     ‘Py_UNREACHABLE()’ 的一个用法是调用一个不会返回，但却没有声明
     ‘_Py_NO_RETURN’ 的函数之后。

     如果一个代码路径不太可能是正常代码，但在特殊情况下可以到达，就不能
     使用该宏。例如，在低内存条件下，或者一个系统调用返回超出预期范围值
     ，诸如此类，最好将错误报告给调用者。如果无法将错误报告给调用者，可
     以使用 *note Py_FatalError(): 266. 。

     3.7 版新加入.

 -- C 巨集: Py_ABS (x)

     返回 ‘x’ 的绝对值。

     3.3 版新加入.

 -- C 巨集: Py_MIN (x, y)

     返回 ‘x’ 和 ‘y’ 当中的最小值。

     3.3 版新加入.

 -- C 巨集: Py_MAX (x, y)

     返回 ‘x’ 和 ‘y’ 当中的最大值。

     3.3 版新加入.

 -- C 巨集: Py_STRINGIFY (x)

     将 ‘x’ 转换为 C 字符串。例如 ‘Py_STRINGIFY(123)’ 返回 ‘"123"’。

     3.4 版新加入.

 -- C 巨集: Py_MEMBER_SIZE (type, member)

     返回结构 (‘type’) ‘member’ 的大小，以字节表示。

     3.6 版新加入.

 -- C 巨集: Py_CHARMASK (c)

     参数必须为 [-128, 127] 或 [0, 255] 范围内的字符或整数类型。这个宏将
     ‘c’ 强制转换为 ‘unsigned char’ 返回。

 -- C 巨集: Py_GETENV (s)

     与 ‘getenv(s)’ 类似，但是如果命令行上传递了 *note -E: 230. ，则返回
     ‘NULL’ （即如果设置了 ‘Py_IgnoreEnvironmentFlag’ ）。

 -- C 巨集: Py_UNUSED (arg)

     用于函数定义中未使用的参数，从而消除编译器警告。例如： ‘int
     func(int a, int Py_UNUSED(b)) { return a; }’ 。

     3.4 版新加入.

 -- C 巨集: Py_DEPRECATED (version)

     弃用声明。该宏必须放置在符号名称前。

     示例:

          Py_DEPRECATED(3.8) PyAPI_FUNC(int) Py_OldFunction(void);

     3.8 版更變: 添加了 MSVC 支持。

 -- C 巨集: PyDoc_STRVAR (name, str)

     创建一个可以在文档字符串中使用的，名字为 ‘name’ 的变量。如果不和文
     档字符串一起构建 Python，该值将为空。

     如 PEP 7(1) 所述，使用 *note PyDoc_STRVAR: 105a. 作为文档字符串，以
     支持不和文档字符串一起构建 Python 的情况。

     示例:

          PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");

          static PyMethodDef deque_methods[] = {
              // ...
              {"pop", (PyCFunction)deque_pop, METH_NOARGS, pop_doc},
              // ...
          }

 -- C 巨集: PyDoc_STR (str)

     为给定的字符串输入创建一个文档字符串，或者当文档字符串被禁用时，创
     建一个空字符串。

     如 PEP 7(2) 所述，使用 *note PyDoc_STR: 3dc2. 指定文档字符串，以支
     持不和文档字符串一起构建 Python 的情况。

     示例:

          static PyMethodDef pysqlite_row_methods[] = {
              {"keys", (PyCFunction)pysqlite_row_keys, METH_NOARGS,
                  PyDoc_STR("Returns the keys of the row.")},
              {NULL, NULL}
          };

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0007

   (2) https://www.python.org/dev/peps/pep-0007


File: python.info,  Node: 对象、类型和引用计数,  Next: 异常<17>,  Prev: 有用的宏,  Up: 簡介<12>

7.1.4 对象、类型和引用计数
--------------------------

多数 Python/C API 有一个或多个参数，以及一个 *note PyObject*: 5b4. 类型
的返回值。这种类型是指向任意 Python 对象的不透明数据类型的指针。所有
Python 对象类型在大多数情况下都被 Python 语言由相同的方式处理（例如，赋
值，作用域规则，和参数传递），因此将它们由单个 C 类型表示才合适。几乎所
有 Python 对象存放在堆中：你不能声明一个类型为 *note PyObject: 5b4. 的自
动或静态的变量，只能声明类型为 *note PyObject*: 5b4. 的指针。type 对象是
唯一的例外，因为它们永远不能被释放，所以它们通常是静态的 *note
PyTypeObject: 3f5. 对象。

所有 Python 对象（甚至 Python 整数）都有一个 `type' 和一个 `reference
count'。对象的类型确定它是什么类型的对象（例如整数、列表或用户定义函数；
还有更多，如 *note 标准类型层级结构: 1553. 中所述）。对于每个众所周知的
类型，都有一个宏来检查对象是否属于该类型；例如，当（且仅当） `a' 所指的
对象是 Python 列表时 ‘PyList_Check(a)’ 为真。

* Menu:

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


File: python.info,  Node: 引用计数<2>,  Next: 类型,  Up: 对象、类型和引用计数

7.1.4.1 引用计数
................

引用计数非常重要，因为现代计算机内存（通常十分）有限；它计算有多少不同的
地方引用同一个对象。这样的地方可以是某个对象，或者是某个全局（或静态）C
变量，亦或是某个 C 函数的局部变量。当一个对象的引用计数变为 0，释放该对
象。如果这个已释放的对象包含其它对象的引用计数，则递减这些对象的引用计数
。如果这些对象的引用计数减少为零，则可以依次释放这些对象，依此类推。（这
里有一个很明显的问题——对象之间相互引用；目前，解决方案是“不要那样做”。）

总是显式操作引用计数。通常的方法是使用宏 *note Py_INCREF(): 38e. 来增加
一个对象的引用计数，使用宏 *note Py_DECREF(): 38f. 来减少一个对象的引用
计数。宏 *note Py_DECREF(): 38f. 必须检查引用计数是否为零，然后调用对象
的释放器， 因此它比 incref 宏复杂得多。释放器是一个包含在对象类型结构中
的函数指针。如果对象是复合对象类型（例如列表），则类型特定的释放器负责递
减包含在对象中的其他对象的引用计数，并执行所需的终结。引用计数不会溢出，
至少用与虚拟内存中不同内存位置一样多的位用于保存引用计数（即
‘sizeof(Py_ssize_t) >= sizeof(void*)’ ）。因此，引用计数递增是一个简单的
操作。

没有必要为每个包含指向对象的指针的局部变量增加对象的引用计数。理论上，当
变量指向对象时，对象的引用计数增加 1 ，当变量超出范围时，对象的引用计数
减少 1 。但是，这两者相互抵消，所以最后引用计数没有改变。使用引用计数的
唯一真正原因是只要我们的变量指向它，就可以防止对象被释放。如果知道至少有
一个对该对象的其他引用存活时间至少和我们的变量一样长，则没必要临时增加引
用计数。一个典型的情形是，对象作为参数从 Python 中传递给被调用的扩展模块
中的 C 函数时，调用机制会保证在调用期间持有对所有参数的引用。

但是，有一个常见的陷阱是从列表中提取一个对象，并将其持有一段时间，而不增
加其引用计数。某些操作可能会从列表中删除某个对象，减少其引用计数，并有可
能重新分配这个对象。真正的危险是，这个看似无害的操作可能会调用任意
Python 代码——也许有一个代码路径允许控制流从 *note Py_DECREF(): 38f. 回到
用户，因此在复合对象上的操作都存在潜在的风险。

一个安全的方式是始终使用泛型操作（名称以 ‘PyObject_’ ， ‘PyNumber_’ ，
‘PySequence_’ 或 ‘PyMapping_’ 开头的函数）。这些操作总是增加它们返回的对
象的引用计数。这让调用者有责任在获得结果后调用 *note Py_DECREF(): 38f. 。
习惯这种方式很简单。

* Menu:

* 引用计数细节::


File: python.info,  Node: 引用计数细节,  Up: 引用计数<2>

7.1.4.2 引用计数细节
....................

The reference count behavior of functions in the Python/C API is best
explained in terms of `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 *note Py_DECREF(): 38f. or *note Py_XDECREF(): 391. 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 `new' reference.  When no ownership is
transferred, the caller is said to `borrow' the reference.  Nothing
needs to be done for a borrowed reference.

Conversely, when a calling function passes in a reference to an object,
there are two possibilities: the function `steals' a reference to the
object, or it does not.  `Stealing a reference' means that when you pass
a reference to a function, that function assumes that it now owns that
reference, and you are not responsible for it any longer.

Few functions steal references; the two notable exceptions are *note
PyList_SetItem(): 3d3f. and *note PyTuple_SetItem(): 3d3e, which steal a
reference to the item (but not to the tuple or list into which the item
is put!).  These functions were designed to steal a reference because of
a common idiom for populating a tuple or list with newly created
objects; for example, the code to create the tuple ‘(1, 2, "three")’
could look like this (forgetting about error handling for the moment; a
better way to code this is shown below):

     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"));

Here, *note PyLong_FromLong(): 3d20. returns a new reference which is
immediately stolen by *note PyTuple_SetItem(): 3d3e.  When you want to
keep using an object although the reference to it will be stolen, use
*note Py_INCREF(): 38e. to grab another reference before calling the
reference-stealing function.

Incidentally, *note PyTuple_SetItem(): 3d3e. is the `only' way to set
tuple items; *note PySequence_SetItem(): 1184. and *note
PyObject_SetItem(): 3dc9. refuse to do this since tuples are an
immutable data type.  You should only use *note PyTuple_SetItem(): 3d3e.
for tuples that you are creating yourself.

Equivalent code for populating a list can be written using *note
PyList_New(): 3dca. and *note PyList_SetItem(): 3d3f.

However, in practice, you will rarely use these ways of creating and
populating a tuple or list.  There’s a generic function, *note
Py_BuildValue(): 3f0, that can create most common objects from C values,
directed by a `format string'.  For example, the above two blocks of
code could be replaced by the following (which also takes care of the
error checking):

     PyObject *tuple, *list;

     tuple = Py_BuildValue("(iis)", 1, 2, "three");
     list = Py_BuildValue("[iis]", 1, 2, "three");

It is much more common to use *note PyObject_SetItem(): 3dc9. and
friends with items whose references you are only borrowing, like
arguments that were passed in to the function you are writing.  In that
case, their behaviour regarding reference counts is much saner, since
you don’t have to increment a reference count so you can give a
reference away ("have it be stolen").  For example, this function sets
all items of a list (actually, any mutable sequence) to a given item:

     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;
     }

The situation is slightly different for function return values.  While
passing a reference to most functions does not change your ownership
responsibilities for that reference, many functions that return a
reference to an object give you ownership of the reference.  The reason
is simple: in many cases, the returned object is created on the fly, and
the reference you get is the only reference to the object.  Therefore,
the generic functions that return object references, like *note
PyObject_GetItem(): 3dcb. and *note PySequence_GetItem(): 1183, always
return a new reference (the caller becomes the owner of the reference).

It is important to realize that whether you own a reference returned by
a function depends on which function you call only — `the plumage' (the
type of the object passed as an argument to the function) `doesn’t enter
into it!'  Thus, if you extract an item from a list using *note
PyList_GetItem(): 3d3a, you don’t own the reference — but if you obtain
the same item from the same list using *note PySequence_GetItem(): 1183.
(which happens to take exactly the same arguments), you do own a
reference to the returned object.

Here is an example of how you could write a function that computes the
sum of the items in a list of integers; once using *note
PyList_GetItem(): 3d3a, and once using *note PySequence_GetItem(): 1183.

     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;
     }

     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;
     }


File: python.info,  Node: 类型,  Prev: 引用计数<2>,  Up: 对象、类型和引用计数

7.1.4.3 类型
............

There are few other data types that play a significant role in the
Python/C API; most are simple C types such as ‘int’, ‘long’, ‘double’
and ‘char*’.  A few structure types are used to describe static tables
used to list the functions exported by a module or the data attributes
of a new object type, and another is used to describe the value of a
complex number.  These will be discussed together with the functions
that use them.


File: python.info,  Node: 异常<17>,  Next: 嵌入式Python,  Prev: 对象、类型和引用计数,  Up: 簡介<12>

7.1.5 异常
----------

Python程序员只需要处理特定需要处理的错误异常；未处理的异常会自动传递给调
用者，然后传递给调用者的调用者，依此类推，直到他们到达顶级解释器，在那里
将它们报告给用户并伴随堆栈回溯。

For C programmers, however, error checking always has to be explicit.
All functions in the Python/C API can raise exceptions, unless an
explicit claim is made otherwise in a function’s documentation.  In
general, when a function encounters an error, it sets an exception,
discards any object references that it owns, and returns an error
indicator.  If not documented otherwise, this indicator is either ‘NULL’
or ‘-1’, depending on the function’s return type.  A few functions
return a Boolean true/false result, with false indicating an error.
Very few functions return no explicit error indicator or have an
ambiguous return value, and require explicit testing for errors with
*note PyErr_Occurred(): 3d1e.  These exceptions are always explicitly
documented.

Exception state is maintained in per-thread storage (this is equivalent
to using global storage in an unthreaded application).  A thread can be
in one of two states: an exception has occurred, or not.  The function
*note PyErr_Occurred(): 3d1e. can be used to check for this: it returns
a borrowed reference to the exception type object when an exception has
occurred, and ‘NULL’ otherwise.  There are a number of functions to set
the exception state: *note PyErr_SetString(): 3d1b. is the most common
(though not the most general) function to set the exception state, and
*note PyErr_Clear(): a4c. clears the exception state.

The full exception state consists of three objects (all of which can be
‘NULL’): the exception type, the corresponding exception value, and the
traceback.  These have the same meanings as the Python result of
‘sys.exc_info()’; however, they are not the same: the Python objects
represent the last exception being handled by a Python *note try: e37.
...  *note except: c10. statement, while the C level exception state
only exists while an exception is being passed on between C functions
until it reaches the Python bytecode interpreter’s main loop, which
takes care of transferring it to ‘sys.exc_info()’ and friends.

Note that starting with Python 1.5, the preferred, thread-safe way to
access the exception state from Python code is to call the function
*note sys.exc_info(): d27, which returns the per-thread exception state
for Python code.  Also, the semantics of both ways to access the
exception state have changed so that a function which catches an
exception will save and restore its thread’s exception state so as to
preserve the exception state of its caller.  This prevents common bugs
in exception handling code caused by an innocent-looking function
overwriting the exception being handled; it also reduces the often
unwanted lifetime extension for objects that are referenced by the stack
frames in the traceback.

As a general principle, a function that calls another function to
perform some task should check whether the called function raised an
exception, and if so, pass the exception state on to its caller.  It
should discard any object references that it owns, and return an error
indicator, but it should `not' set another exception — that would
overwrite the exception that was just raised, and lose important
information about the exact cause of the error.

A simple example of detecting exceptions and passing them on is shown in
the ‘sum_sequence()’ example above.  It so happens that this example
doesn’t need to clean up any owned references when it detects an error.
The following example function shows some error cleanup.  First, to
remind you why you like Python, we show the equivalent Python code:

     def incr_item(dict, key):
         try:
             item = dict[key]
         except KeyError:
             item = 0
         dict[key] = item + 1

下面是对应的闪耀荣光的 C 代码：

     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 */
     }

This example represents an endorsed use of the ‘goto’ statement in C! It
illustrates the use of *note PyErr_ExceptionMatches(): 3dd0. and *note
PyErr_Clear(): a4c. to handle specific exceptions, and the use of *note
Py_XDECREF(): 391. to dispose of owned references that may be ‘NULL’
(note the ‘'X'’ in the name; *note Py_DECREF(): 38f. would crash when
confronted with a ‘NULL’ reference).  It is important that the variables
used to hold owned references are initialized to ‘NULL’ for this to
work; likewise, the proposed return value is initialized to ‘-1’
(failure) and only set to success after the final call made is
successful.


File: python.info,  Node: 嵌入式Python,  Next: 调试构建,  Prev: 异常<17>,  Up: 簡介<12>

7.1.6 嵌入式Python
------------------

The one important task that only embedders (as opposed to extension
writers) of the Python interpreter have to worry about is the
initialization, and possibly the finalization, of the Python
interpreter.  Most functionality of the interpreter can only be used
after the interpreter has been initialized.

The basic initialization function is *note Py_Initialize(): 20f.  This
initializes the table of loaded modules, and creates the fundamental
modules *note builtins: 12, *note __main__: 1, and *note sys: fd.  It
also initializes the module search path (‘sys.path’).

*note Py_Initialize(): 20f. does not set the "script argument list"
(‘sys.argv’).  If this variable is needed by Python code that will be
executed later, it must be set explicitly with a call to
‘PySys_SetArgvEx(argc, argv, updatepath)’ after the call to *note
Py_Initialize(): 20f.

On most systems (in particular, on Unix and Windows, although the
details are slightly different), *note Py_Initialize(): 20f. calculates
the module search path based upon its best guess for the location of the
standard Python interpreter executable, assuming that the Python library
is found in a fixed location relative to the Python interpreter
executable.  In particular, it looks for a directory named
‘lib/python`X.Y'’ relative to the parent directory where the executable
named ‘python’ is found on the shell command search path (the
environment variable ‘PATH’).

For instance, if the Python executable is found in
‘/usr/local/bin/python’, it will assume that the libraries are in
‘/usr/local/lib/python`X.Y'’.  (In fact, this particular path is also
the "fallback" location, used when no executable file named ‘python’ is
found along ‘PATH’.)  The user can override this behavior by setting the
environment variable *note PYTHONHOME: 5d0, or insert additional
directories in front of the standard path by setting *note PYTHONPATH:
a34.

The embedding application can steer the search by calling
‘Py_SetProgramName(file)’ `before' calling *note Py_Initialize(): 20f.
Note that *note PYTHONHOME: 5d0. still overrides this and *note
PYTHONPATH: a34. is still inserted in front of the standard path.  An
application that requires total control has to provide its own
implementation of *note Py_GetPath(): 3dd3, *note Py_GetPrefix(): 3dd4,
*note Py_GetExecPrefix(): 3dd5, and *note Py_GetProgramFullPath(): 39e.
(all defined in ‘Modules/getpath.c’).

Sometimes, it is desirable to "uninitialize" Python.  For instance, the
application may want to start over (make another call to *note
Py_Initialize(): 20f.) or the application is simply done with its use of
Python and wants to free memory allocated by Python.  This can be
accomplished by calling *note Py_FinalizeEx(): 6c0.  The function *note
Py_IsInitialized(): 3dd6. returns true if Python is currently in the
initialized state.  More information about these functions is given in a
later chapter.  Notice that *note Py_FinalizeEx(): 6c0. does `not' free
all memory allocated by the Python interpreter, e.g.  memory allocated
by extension modules currently cannot be released.


File: python.info,  Node: 调试构建,  Prev: 嵌入式Python,  Up: 簡介<12>

7.1.7 调试构建
--------------

Python can be built with several macros to enable extra checks of the
interpreter and extension modules.  These checks tend to add a large
amount of overhead to the runtime so they are not enabled by default.

A full list of the various types of debugging builds is in the file
‘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 ‘Py_DEBUG’ macro defined produces
what is generally meant by "a debug build" of Python.  ‘Py_DEBUG’ is
enabled in the Unix build by adding ‘--with-pydebug’ to the
‘./configure’ command.  It is also implied by the presence of the
not-Python-specific ‘_DEBUG’ macro.  When ‘Py_DEBUG’ is enabled in the
Unix build, compiler optimization is disabled.

除了前面描述的引用计数调试之外，还执行以下额外检查：

   * 额外检查将添加到对象分配器。

   * 额外的检查将添加到解析器和编译器中。

   * 检查从宽类型向窄类型的向下强转是否损失了信息。

   * 许多断言被添加到字典和集合实现中。另外，集合对象需要 ‘test_c_api()’
     方法。

   * 输入参数的完整性检查被添加到框架创建中。

   * 使用已知的无效模式初始化整型的存储，以捕获对未初始化数字的引用。

   * 添加底层跟踪和额外的异常检查到虚拟机的运行时中。

   * 添加额外的检查到 arena 内存实现。

   * 添加额外调试到线程模块。

这里可能没有提到的额外的检查。

Defining ‘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 *note PyObject: 5b4.  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 ‘Py_DEBUG’.

有关更多详细信息，请参阅Python源代码中的 ‘Misc/SpecialBuilds.txt’ 。


File: python.info,  Node: 稳定的应用程序二进制接口,  Next: The Very High Level Layer,  Prev: 簡介<12>,  Up: Python/C API 參考手冊

7.2 稳定的应用程序二进制接口
============================

传统上，Python的C API将随每个版本而变化。大多数更改都与源代码兼容，通常
只添加API，而不是更改现有API或删除API（尽管某些接口会首先弃用然后再删除
）。

不幸的是，API兼容性没有扩展到二进制兼容性（ABI）。原因主要是结构定义的演
变，在这里添加新字段或更改字段类型可能不会破坏API，但可能会破坏ABI。因此
，每个Python版本都需要重新编译扩展模块（即使在未使用任何受影响的接口的情
况下，Unix上也可能会出现异常）。此外，在Windows上，扩展模块与特定的
pythonXY.dll链接，需要重新编译才能与新的pythonXY.dll链接。

从Python3.2起，已经声明了一个API的子集，以确保稳定的ABI。如果使用此API（
也被称为“受限API”）的扩展模块需要定义‘‘Py_LIMITED_API‘‘。许多解释器细节
将从扩展模块中隐藏; 反过来，在任何3.x版本（x>=2）上构建的模块都不需要重
新编译

在某些情况下，需要添加新函数来扩展稳定版 ABI。希望使用这些新 API 的扩展
模块需要将 ‘Py_LIMITED_API’ 设置为他们想要支持的最低 Python 版本的
‘PY_VERSION_HEX’ 值（例如： Python 3.3 为 ‘0x03030000’）（参见 *note API
和 ABI 版本管理: 37d9.）。此类模块将适用于所有后续 Python版本，但无法在
旧版本上加载（因为缺少符号）。

从Python 3.2开始，受限API可用的函数集记录在 PEP 384(1) 。在C API文档中，
不属于受限API的API元素标记为 “不属于受限API” 。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0384


File: python.info,  Node: The Very High Level Layer,  Next: 參照計數,  Prev: 稳定的应用程序二进制接口,  Up: Python/C API 參考手冊

7.3 The Very High Level Layer
=============================

The functions in this chapter will let you execute Python source code
given in a file or a buffer, but they will not let you interact in a
more detailed way with the interpreter.

Several of these functions accept a start symbol from the grammar as a
parameter.  The available start symbols are ‘Py_eval_input’,
‘Py_file_input’, and ‘Py_single_input’.  These are described following
the functions which accept them as parameters.

Note also that several of these functions take ‘FILE*’ parameters.  One
particular issue which needs to be handled carefully is that the ‘FILE’
structure for different C libraries can be different and incompatible.
Under Windows (at least), it is possible for dynamically linked
extensions to actually use different libraries, so care should be taken
that ‘FILE*’ parameters are only passed to these functions if it is
certain that they were created by the same library that the Python
runtime is using.

 -- C 函式: int Py_Main (int argc, wchar_t **argv)

     The main program for the standard interpreter.  This is made
     available for programs which embed Python.  The `argc' and `argv'
     parameters should be prepared exactly as those which are passed to
     a C program’s ‘main()’ function (converted to wchar_t according to
     the user’s locale).  It is important to note that the argument list
     may be modified (but the contents of the strings pointed to by the
     argument list are not).  The return value will be ‘0’ if the
     interpreter exits normally (i.e., without an exception), ‘1’ if the
     interpreter exits due to an exception, or ‘2’ if the parameter list
     does not represent a valid Python command line.

     Note that if an otherwise unhandled *note SystemExit: 6f3. is
     raised, this function will not return ‘1’, but exit the process, as
     long as ‘Py_InspectFlag’ is not set.

 -- C 函式: int Py_BytesMain (int argc, char **argv)

     Similar to *note Py_Main(): 5b1. but `argv' is an array of bytes
     strings.

     3.8 版新加入.

 -- C 函式: int PyRun_AnyFile (FILE *fp, const char *filename)

     This is a simplified interface to *note PyRun_AnyFileExFlags():
     3de0. below, leaving `closeit' set to ‘0’ and `flags' set to
     ‘NULL’.

 -- C 函式: int PyRun_AnyFileFlags (FILE *fp, const char *filename,
          PyCompilerFlags *flags)

     This is a simplified interface to *note PyRun_AnyFileExFlags():
     3de0. below, leaving the `closeit' argument set to ‘0’.

 -- C 函式: int PyRun_AnyFileEx (FILE *fp, const char *filename,
          int closeit)

     This is a simplified interface to *note PyRun_AnyFileExFlags():
     3de0. below, leaving the `flags' argument set to ‘NULL’.

 -- C 函式: int PyRun_AnyFileExFlags (FILE *fp, const char *filename,
          int closeit, PyCompilerFlags *flags)

     If `fp' refers to a file associated with an interactive device
     (console or terminal input or Unix pseudo-terminal), return the
     value of *note PyRun_InteractiveLoop(): 3de3, otherwise return the
     result of *note PyRun_SimpleFile(): 3da1.  `filename' is decoded
     from the filesystem encoding (*note sys.getfilesystemencoding():
     5ef.).  If `filename' is ‘NULL’, this function uses ‘"???"’ as the
     filename.

 -- C 函式: int PyRun_SimpleString (const char *command)

     This is a simplified interface to *note PyRun_SimpleStringFlags():
     3de4. below, leaving the *note PyCompilerFlags: 3ee.* argument set
     to ‘NULL’.

 -- C 函式: int PyRun_SimpleStringFlags (const char *command,
          PyCompilerFlags *flags)

     Executes the Python source code from `command' in the *note
     __main__: 1. module according to the `flags' argument.  If *note
     __main__: 1. does not already exist, it is created.  Returns ‘0’ on
     success or ‘-1’ if an exception was raised.  If there was an error,
     there is no way to get the exception information.  For the meaning
     of `flags', see below.

     Note that if an otherwise unhandled *note SystemExit: 6f3. is
     raised, this function will not return ‘-1’, but exit the process,
     as long as ‘Py_InspectFlag’ is not set.

 -- C 函式: int PyRun_SimpleFile (FILE *fp, const char *filename)

     This is a simplified interface to *note PyRun_SimpleFileExFlags():
     fc7. below, leaving `closeit' set to ‘0’ and `flags' set to ‘NULL’.

 -- C 函式: int PyRun_SimpleFileEx (FILE *fp, const char *filename,
          int closeit)

     This is a simplified interface to *note PyRun_SimpleFileExFlags():
     fc7. below, leaving `flags' set to ‘NULL’.

 -- C 函式: int PyRun_SimpleFileExFlags (FILE *fp, const char *filename,
          int closeit, PyCompilerFlags *flags)

     Similar to *note PyRun_SimpleStringFlags(): 3de4, but the Python
     source code is read from `fp' instead of an in-memory string.
     `filename' should be the name of the file, it is decoded from the
     filesystem encoding (*note sys.getfilesystemencoding(): 5ef.).  If
     `closeit' is true, the file is closed before
     PyRun_SimpleFileExFlags returns.

          備註: On Windows, `fp' should be opened as binary mode (e.g.
          ‘fopen(filename, "rb")’).  Otherwise, Python may not handle
          script file with LF line ending correctly.

 -- C 函式: int PyRun_InteractiveOne (FILE *fp, const char *filename)

     This is a simplified interface to *note
     PyRun_InteractiveOneFlags(): 3de7. below, leaving `flags' set to
     ‘NULL’.

 -- C 函式: int PyRun_InteractiveOneFlags (FILE *fp, const
          char *filename, PyCompilerFlags *flags)

     Read and execute a single statement from a file associated with an
     interactive device according to the `flags' argument.  The user
     will be prompted using ‘sys.ps1’ and ‘sys.ps2’.  `filename' is
     decoded from the filesystem encoding (*note
     sys.getfilesystemencoding(): 5ef.).

     Returns ‘0’ when the input was executed successfully, ‘-1’ if there
     was an exception, or an error code from the ‘errcode.h’ include
     file distributed as part of Python if there was a parse error.
     (Note that ‘errcode.h’ is not included by ‘Python.h’, so must be
     included specifically if needed.)

 -- C 函式: int PyRun_InteractiveLoop (FILE *fp, const char *filename)

     This is a simplified interface to *note
     PyRun_InteractiveLoopFlags(): 3de8. below, leaving `flags' set to
     ‘NULL’.

 -- C 函式: int PyRun_InteractiveLoopFlags (FILE *fp, const
          char *filename, PyCompilerFlags *flags)

     Read and execute statements from a file associated with an
     interactive device until EOF is reached.  The user will be prompted
     using ‘sys.ps1’ and ‘sys.ps2’.  `filename' is decoded from the
     filesystem encoding (*note sys.getfilesystemencoding(): 5ef.).
     Returns ‘0’ at EOF or a negative number upon failure.

 -- C 變數: int (*PyOS_InputHook) (void)

     Can be set to point to a function with the prototype ‘int
     func(void)’.  The function will be called when Python’s interpreter
     prompt is about to become idle and wait for user input from the
     terminal.  The return value is ignored.  Overriding this hook can
     be used to integrate the interpreter’s prompt with other event
     loops, as done in the ‘Modules/_tkinter.c’ in the Python source
     code.

 -- C 變數: char* (*PyOS_ReadlineFunctionPointer) (FILE *, FILE *, const
          char *)

     Can be set to point to a function with the prototype ‘char
     *func(FILE *stdin, FILE *stdout, char *prompt)’, overriding the
     default function used to read a single line of input at the
     interpreter’s prompt.  The function is expected to output the
     string `prompt' if it’s not ‘NULL’, and then read a line of input
     from the provided standard input file, returning the resulting
     string.  For example, The *note readline: de. module sets this hook
     to provide line-editing and tab-completion features.

     The result must be a string allocated by *note PyMem_RawMalloc():
     a4e. or *note PyMem_RawRealloc(): a4f, or ‘NULL’ if an error
     occurred.

     3.4 版更變: The result must be allocated by *note
     PyMem_RawMalloc(): a4e. or *note PyMem_RawRealloc(): a4f, instead
     of being allocated by *note PyMem_Malloc(): 5fe. or *note
     PyMem_Realloc(): a50.

 -- C 函式: struct _node* PyParser_SimpleParseString (const char *str,
          int start)

     This is a simplified interface to *note
     PyParser_SimpleParseStringFlagsFilename(): 200. below, leaving
     `filename' set to ‘NULL’ and `flags' set to ‘0’.

     Deprecated since version 3.9, will be removed in version 3.10.

 -- C 函式: struct _node* PyParser_SimpleParseStringFlags (const
          char *str, int start, int flags)

     This is a simplified interface to *note
     PyParser_SimpleParseStringFlagsFilename(): 200. below, leaving
     `filename' set to ‘NULL’.

     Deprecated since version 3.9, will be removed in version 3.10.

 -- C 函式: struct _node* PyParser_SimpleParseStringFlagsFilename (const
          char *str, const char *filename, int start, int flags)

     Parse Python source code from `str' using the start token `start'
     according to the `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.  `filename'
     is decoded from the filesystem encoding (*note
     sys.getfilesystemencoding(): 5ef.).

     Deprecated since version 3.9, will be removed in version 3.10.

 -- C 函式: struct _node* PyParser_SimpleParseFile (FILE *fp, const
          char *filename, int start)

     This is a simplified interface to *note
     PyParser_SimpleParseFileFlags(): 201. below, leaving `flags' set to
     ‘0’.

     Deprecated since version 3.9, will be removed in version 3.10.

 -- C 函式: struct _node* PyParser_SimpleParseFileFlags (FILE *fp, const
          char *filename, int start, int flags)

     Similar to *note PyParser_SimpleParseStringFlagsFilename(): 200,
     but the Python source code is read from `fp' instead of an
     in-memory string.

     Deprecated since version 3.9, will be removed in version 3.10.

 -- C 函式: PyObject* PyRun_String (const char *str, int start,
          PyObject *globals, PyObject *locals)
     `Return value: New reference.'  This is a simplified interface to
     *note PyRun_StringFlags(): 3dec. below, leaving `flags' set to
     ‘NULL’.

 -- C 函式: PyObject* PyRun_StringFlags (const char *str, int start,
          PyObject *globals, PyObject *locals, PyCompilerFlags *flags)
     `Return value: New reference.'  Execute Python source code from
     `str' in the context specified by the objects `globals' and
     `locals' with the compiler flags specified by `flags'.  `globals'
     must be a dictionary; `locals' can be any object that implements
     the mapping protocol.  The parameter `start' specifies the start
     token that should be used to parse the source code.

     Returns the result of executing the code as a Python object, or
     ‘NULL’ if an exception was raised.

 -- C 函式: PyObject* PyRun_File (FILE *fp, const char *filename,
          int start, PyObject *globals, PyObject *locals)
     `Return value: New reference.'  This is a simplified interface to
     *note PyRun_FileExFlags(): 3dee. below, leaving `closeit' set to
     ‘0’ and `flags' set to ‘NULL’.

 -- C 函式: PyObject* PyRun_FileEx (FILE *fp, const char *filename,
          int start, PyObject *globals, PyObject *locals, int closeit)
     `Return value: New reference.'  This is a simplified interface to
     *note PyRun_FileExFlags(): 3dee. below, leaving `flags' set to
     ‘NULL’.

 -- C 函式: PyObject* PyRun_FileFlags (FILE *fp, const char *filename,
          int start, PyObject *globals, PyObject *locals,
          PyCompilerFlags *flags)
     `Return value: New reference.'  This is a simplified interface to
     *note PyRun_FileExFlags(): 3dee. below, leaving `closeit' set to
     ‘0’.

 -- C 函式: PyObject* PyRun_FileExFlags (FILE *fp, const char *filename,
          int start, PyObject *globals, PyObject *locals, int closeit,
          PyCompilerFlags *flags)
     `Return value: New reference.'  Similar to *note
     PyRun_StringFlags(): 3dec, but the Python source code is read from
     `fp' instead of an in-memory string.  `filename' should be the name
     of the file, it is decoded from the filesystem encoding (*note
     sys.getfilesystemencoding(): 5ef.).  If `closeit' is true, the file
     is closed before *note PyRun_FileExFlags(): 3dee. returns.

 -- C 函式: PyObject* Py_CompileString (const char *str, const
          char *filename, int start)
     `Return value: New reference.'  This is a simplified interface to
     *note Py_CompileStringFlags(): 3df2. below, leaving `flags' set to
     ‘NULL’.

 -- C 函式: PyObject* Py_CompileStringFlags (const char *str, const
          char *filename, int start, PyCompilerFlags *flags)
     `Return value: New reference.'  This is a simplified interface to
     *note Py_CompileStringExFlags(): 3df3. below, with `optimize' set
     to ‘-1’.

 -- C 函式: PyObject* Py_CompileStringObject (const char *str,
          PyObject *filename, int start, PyCompilerFlags *flags,
          int optimize)
     `Return value: New reference.'  Parse and compile the Python source
     code in `str', returning the resulting code object.  The start
     token is given by `start'; this can be used to constrain the code
     which can be compiled and should be ‘Py_eval_input’,
     ‘Py_file_input’, or ‘Py_single_input’.  The filename specified by
     `filename' is used to construct the code object and may appear in
     tracebacks or *note SyntaxError: 559. exception messages.  This
     returns ‘NULL’ if the code cannot be parsed or compiled.

     The integer `optimize' specifies the optimization level of the
     compiler; a value of ‘-1’ selects the optimization level of the
     interpreter as given by *note -O: 77e. options.  Explicit levels
     are ‘0’ (no optimization; ‘__debug__’ is true), ‘1’ (asserts are
     removed, ‘__debug__’ is false) or ‘2’ (docstrings are removed too).

     3.4 版新加入.

 -- C 函式: PyObject* Py_CompileStringExFlags (const char *str, const
          char *filename, int start, PyCompilerFlags *flags,
          int optimize)
     `Return value: New reference.'  Like *note
     Py_CompileStringObject(): 3df4, but `filename' is a byte string
     decoded from the filesystem encoding (*note os.fsdecode(): 5e8.).

     3.2 版新加入.

 -- C 函式: PyObject* PyEval_EvalCode (PyObject *co, PyObject *globals,
          PyObject *locals)
     `Return value: New reference.'  This is a simplified interface to
     *note PyEval_EvalCodeEx(): 3df6, with just the code object, and
     global and local variables.  The other arguments are set to ‘NULL’.

 -- C 函式: PyObject* PyEval_EvalCodeEx (PyObject *co,
          PyObject *globals, PyObject *locals, PyObject *const *args,
          int argcount, PyObject *const *kws, int kwcount, PyObject
          *const *defs, int defcount, PyObject *kwdefs,
          PyObject *closure)
     `Return value: New reference.'  Evaluate a precompiled code object,
     given a particular environment for its evaluation.  This
     environment consists of a dictionary of global variables, a mapping
     object of local variables, arrays of arguments, keywords and
     defaults, a dictionary of default values for *note keyword-only:
     3ce. arguments and a closure tuple of cells.

 -- C 類型: PyFrameObject

     The C structure of the objects used to describe frame objects.  The
     fields of this type are subject to change at any time.

 -- C 函式: PyObject* PyEval_EvalFrame (PyFrameObject *f)
     `Return value: New reference.'  Evaluate an execution frame.  This
     is a simplified interface to *note PyEval_EvalFrameEx(): a48, for
     backward compatibility.

 -- C 函式: PyObject* PyEval_EvalFrameEx (PyFrameObject *f,
          int throwflag)
     `Return value: New reference.'  This is the main, unvarnished
     function of Python interpretation.  The code object associated with
     the execution frame `f' is executed, interpreting bytecode and
     executing calls as needed.  The additional `throwflag' parameter
     can mostly be ignored - if true, then it causes an exception to
     immediately be thrown; this is used for the *note throw(): ff8.
     methods of generator objects.

     3.4 版更變: 该函数现在包含一个调试断言，用以确保不会静默地丢弃活动
     的异常。

 -- C 函式: int PyEval_MergeCompilerFlags (PyCompilerFlags *cf)

     This function changes the flags of the current evaluation frame,
     and returns true on success, false on failure.

 -- C 變數: int Py_eval_input

     The start symbol from the Python grammar for isolated expressions;
     for use with *note Py_CompileString(): 3df1.

 -- C 變數: int Py_file_input

     The start symbol from the Python grammar for sequences of
     statements as read from a file or other source; for use with *note
     Py_CompileString(): 3df1.  This is the symbol to use when compiling
     arbitrarily long Python source code.

 -- C 變數: int Py_single_input

     The start symbol from the Python grammar for a single statement;
     for use with *note Py_CompileString(): 3df1.  This is the symbol
     used for the interactive interpreter loop.

 -- C 類型: struct PyCompilerFlags

     This is the structure used to hold compiler flags.  In cases where
     code is only being compiled, it is passed as ‘int flags’, and in
     cases where code is being executed, it is passed as
     ‘PyCompilerFlags *flags’.  In this case, ‘from __future__ import’
     can modify `flags'.

     Whenever ‘PyCompilerFlags *flags’ is ‘NULL’, ‘cf_flags’ is treated
     as equal to ‘0’, and any modification due to ‘from __future__
     import’ is discarded.

      -- C 成員函數: int cf_flags

          Compiler flags.

      -- C 成員函數: int cf_feature_version

          `cf_feature_version' is the minor Python version.  It should
          be initialized to ‘PY_MINOR_VERSION’.

          The field is ignored by default, it is used if and only if
          ‘PyCF_ONLY_AST’ flag is set in `cf_flags'.

     3.8 版更變: Added `cf_feature_version' field.

 -- C 變數: int CO_FUTURE_DIVISION

     This bit can be set in `flags' to cause division operator ‘/’ to be
     interpreted as "true division" according to PEP 238(1).

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0238


File: python.info,  Node: 參照計數,  Next: 例外處理,  Prev: The Very High Level Layer,  Up: Python/C API 參考手冊

7.4 參照計數
============

本节介绍的宏被用于管理 Python 对象的引用计数。

 -- C 函式: void Py_INCREF (PyObject *o)

     增加对象 `o' 的引用计数。 对象必须不为 ‘NULL’；如果你不确定它不为
     ‘NULL’，可使用 *note Py_XINCREF(): 390.。

 -- C 函式: void Py_XINCREF (PyObject *o)

     增加对象 `o' 的引用计数。 对象可以为 ‘NULL’，在此情况下该宏不产生任
     何效果。

 -- C 函式: void Py_DECREF (PyObject *o)

     减少对象 `o' 的引用计数。 对象必须不为 ‘NULL’；如果你不确定它不为
     ‘NULL’，可使用 *note Py_XDECREF(): 391.。 如果引用计数降为零，将发
     起调用对象所属类型的释放函数 (它必须不为 ‘NULL’)。

          警告: 释放函数可导致任意 Python 代码被发起调用（例如当一个带有
          *note __del__(): a04. 方法的类实例被释放时就是如此）。 虽然此
          类代码中的异常不会被传播，但被执行的代码能够自由访问所有
          Python 全局变量。 这意味着任何可通过全局变量获取的对象在 *note
          Py_DECREF(): 38f. 被发起调用之前都应当处于完好状态。 例如，从
          一个列表中删除对象的代码应当将被删除对象的引用拷贝到一个临时变
          量中，更新列表数据结构，然后再为临时变量调用 *note
          Py_DECREF(): 38f.。

 -- C 函式: void Py_XDECREF (PyObject *o)

     减少对象 `o' 的引用计数。 对象可以为 ‘NULL’，在此情况下该宏不产生任
     何效果；在其他情况下其效果与 *note Py_DECREF(): 38f. 相同，并会应用
     同样的警告。

 -- C 函式: void Py_CLEAR (PyObject *o)

     减少对象 `o' 的引用计数。 对象可以为 ‘NULL’，在此情况下该宏不产生任
     何效果；在其他情况下其效果与 *note Py_DECREF(): 38f. 相同，区别在于
     其参数也会被设为 ‘NULL’。 针对 *note Py_DECREF(): 38f. 的警告不适用
     于所传递的对象，因为该宏会细心地使用一个临时变量并在减少其引用计数
     之前将参数设为 ‘NULL’。

     每当要减少在垃圾回收期间可能会被遍历的对象的引用计数时，使用该宏是
     一个好主意。

以下函数适用于 Python 的运行时动态嵌入: ‘Py_IncRef(PyObject *o)’,
‘Py_DecRef(PyObject *o)’。 它们分别只是 *note Py_XINCREF(): 390. 和
*note Py_XDECREF(): 391. 的简单导出函数版本。

以下函数或宏仅可在解释器核心内部使用: ‘_Py_Dealloc()’,
‘_Py_ForgetReference()’, ‘_Py_NewReference()’ 以及全局变量
‘_Py_RefTotal’。


File: python.info,  Node: 例外處理,  Next: 工具<2>,  Prev: 參照計數,  Up: Python/C API 參考手冊

7.5 例外處理
============

本章描述的函数将让你处理和触发 Python 异常。了解一些 Python 异常处理的基
本知识是很重要的。 它的工作原理有点像 POSIX 的 ‘errno’ 变量：（每个线程
）有一个全局指示器显示最近发生的错误。 大多数 C API 函数不会在成功时理会
它，但会在失败时设置它来指示错误的原因。 多数 C API 函数也返回一个错误指
示器，如果它们应该返回一个指针，通常返回 ‘NULL’，如果返回一个整数，则返
回 ‘-1’ (例外: ‘PyArg_*()’ 函数成功时返回 ‘1’ 而失败时返回 ‘0’)。

具体地说，错误指示器由三个对象指针组成：异常的类型，异常的值，和回溯对象
。如果没有错误被设置，这些指针都可以是 ‘NULL’ （尽管一些组合使禁止的，例
如，如果异常类型是 ‘NULL’ ，你不能有一个非 ‘NULL’ 的回溯）。

当一个函数由于它调用的某个函数失败而必须失败时，通常不会设置错误指示器；
它调用的那个函数已经设置了它。而它负责处理错误和清理异常，或在清除其拥有
的所有资源后返回（如对象应用或内存分配）。如果不准备处理异常，则 `不' 应
该正常地继续。如果是由于一个错误返回，那么一定要向调用者表明已经设置了错
误。如果错误没有得到处理或小心传播，对 Python/C API的其它调用可能不会有
预期的行为，并且可能会以某种神秘的方式失败。

     備註: 错误指示器 `不是' *note sys.exc_info(): d27. 的执行结果。前者
     对应尚未捕获的异常（异常还在传播），而后者在捕获异常后返回这个异常
     （异常已经停止传播）。

* Menu:

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


File: python.info,  Node: 打印和清理,  Next: 抛出异常,  Up: 例外處理

7.5.1 打印和清理
----------------

 -- C 函式: void PyErr_Clear ()

     清除错误指示器。如果没有设置错误指示器，则不会有作用。

 -- C 函式: void PyErr_PrintEx (int set_sys_last_vars)

     将标准回溯打印到 ‘sys.stderr’ 并清除错误指示器。`除非' 错误是
     ‘SystemExit’，这种情况下不会打印回溯进程，且会退出 Python 进程，并
     显示 ‘SystemExit’ 实例指定的错误代码。

     只有在错误指示器被设置时才需要调用这个函数，否则这会导致错误！

     如果 `set_sys_last_vars' 非零，则变量 *note sys.last_type: d22.，
     *note sys.last_value: 37da. 和 *note sys.last_traceback: 36d5. 将分
     别设置为打印异常的类型，值和回溯。

 -- C 函式: void PyErr_Print ()

     ‘PyErr_PrintEx(1)’ 的别名。

 -- C 函式: void PyErr_WriteUnraisable (PyObject *obj)

     使用当前异常和 `obj' 参数调用 *note sys.unraisablehook(): 35a.。

     当设置了异常，但解释器不可能实际地触发异常时，这个实用函数向
     ‘sys.stderr’ 打印一个警告信息。例如，当 *note __del__(): a04. 方法
     中发生异常时使用这个函数。

     该函数使用单个参数 `obj' 进行调用，该参数标识发生不可触发异常的上下
     文。如果可能，`obj' 的报告将打印在警告消息中。

     调用此函数时必须设置一个异常。


File: python.info,  Node: 抛出异常,  Next: 发出警告,  Prev: 打印和清理,  Up: 例外處理

7.5.2 抛出异常
--------------

这些函数可帮助你设置当前线程的错误指示器。为了方便起见，一些函数将始终返
回 ‘NULL’ 指针，以便用于 ‘return’ 语句。

 -- C 函式: void PyErr_SetString (PyObject *type, const char *message)

     This is the most common way to set the error indicator.  The first
     argument specifies the exception type; it is normally one of the
     standard exceptions, e.g.  ‘PyExc_RuntimeError’.  You need not
     increment its reference count.  The second argument is an error
     message; it is decoded from ‘'utf-8'’.

 -- C 函式: void PyErr_SetObject (PyObject *type, PyObject *value)

     此函数类似于 *note PyErr_SetString(): 3d1b.，但是允许你为异常的“值
     ”指定任意一个 Python 对象。

 -- C 函式: PyObject* PyErr_Format (PyObject *exception, const
          char *format, ...)
     `Return value: Always NULL.' 这个函数设置了一个错误指示器并且返回了
     ‘NULL’，`exception' 应当是一个 Python 中的异常类。`format' 和随后的
     形参会帮助格式化这个错误的信息；它们与 *note
     PyUnicode_FromFormat(): 8b8. 有着相同的含义和值。`format' 是一个
     ASCII编码的字符串。

 -- C 函式: PyObject* PyErr_FormatV (PyObject *exception, const
          char *format, va_list vargs)
     `Return value: Always NULL.' 和 *note PyErr_Format(): 898. 相同，但
     它接受一个 ‘va_list’ 类型的参数而不是可变数量的参数集。

     3.5 版新加入.

 -- C 函式: void PyErr_SetNone (PyObject *type)

     这是 ‘PyErr_SetObject(type, Py_None)’ 的简写。

 -- C 函式: int PyErr_BadArgument ()

     这是 ‘PyErr_SetString(PyExc_TypeError, message)’ 的简写，其中
     `message' 指出使用了非法参数调用内置操作。它主要用于内部使用。

 -- C 函式: PyObject* PyErr_NoMemory ()
     `Return value: Always NULL.' 这是
     ‘PyErr_SetNone(PyExc_MemoryError)’ 的简写；它返回 ‘NULL’ ，以便当内
     存耗尽时，对象分配函数可以写 ‘return PyErr_NoMemory();’ 。

 -- C 函式: PyObject* PyErr_SetFromErrno (PyObject *type)
     `Return value: Always NULL.'

     这是个便捷函数，当 C 库函数返回错误并设置 ‘errno’ 时，这个函数会触
     发异常。它构造一个元组对象，其第一项是整数值 ‘errno’，第二项是相应
     的错误消息（从 ‘strerror()’ 获取），然后调用 ‘PyErr_SetObject(type,
     object)’。在 Unix 上，当 ‘errno’ 值是 ‘EINTR’ ，即中断的系统调用时
     ，这个函数会调用 *note PyErr_CheckSignals(): 3e09. ，如果设置了错误
     指示器，则将其设置为该值。该函数永远返回 ‘NULL’ ，因此当系统调用返
     回错误时，围绕系统调用的包装函数可以写成 ‘return
     PyErr_SetFromErrno(type);’。

 -- C 函式: PyObject* PyErr_SetFromErrnoWithFilenameObject
          (PyObject *type, PyObject *filenameObject)
     `Return value: Always NULL.' 类似于 *note PyErr_SetFromErrno():
     3d1c. ，附加的行为是如果 `filenameObject' 不为 ‘NULL’ ，它将作为第
     三个参数传递给 `type' 的构造函数。举个例子，在 *note OSError: 304.
     异常中，`filenameObject' 将用来定义异常实例的 ‘filename’ 属性。

 -- C 函式: PyObject* PyErr_SetFromErrnoWithFilenameObjects
          (PyObject *type, PyObject *filenameObject,
          PyObject *filenameObject2)
     `Return value: Always NULL.' 类似于 *note
     PyErr_SetFromErrnoWithFilenameObject(): 3e0a. ，但接受第二个
     filename 对象，用于当一个接受两个 filename 的函数失败时触发错误。

     3.4 版新加入.

 -- C 函式: PyObject* PyErr_SetFromErrnoWithFilename (PyObject *type,
          const char *filename)
     `Return value: Always NULL.' 类似于 *note
     PyErr_SetFromErrnoWithFilenameObject(): 3e0a. ，但文件名以 C 字符串
     形式给出。 `filename' 是从文件系统编码（*note os.fsdecode(): 5e8.）
     解码出来的。

 -- C 函式: PyObject* PyErr_SetFromWindowsErr (int ierr)
     `Return value: Always NULL.' 这是触发 *note WindowsError: a75. 的便
     捷函数。如果 `lerr' 为 ‘0’ ，则改用调用 ‘GetLastError()’ 返回的错误
     代码。它调用 Win32 函数 ‘FormatMessage()’ 来检索 `ierr' 或
     ‘GetLastError()’ 给定的错误代码的 Windows 描述，然后构造一个元组对
     象，其第一项是 `ierr' 值，第二项是相应的错误信息（从
     ‘FormatMessage()’ 获取），然后调用
     ‘PyErr_SetObject(PyExc_WindowsError, object)’ 。该函数永远返回
     ‘NULL’ 。

     *note 可用性: 1491.: Windows。

 -- C 函式: PyObject* PyErr_SetExcFromWindowsErr (PyObject *type,
          int ierr)
     `Return value: Always NULL.' 类似于 *note
     PyErr_SetFromWindowsErr(): 3e0d. ，额外的参数指定要触发的异常类型。

     *note 可用性: 1491.: Windows。

 -- C 函式: PyObject* PyErr_SetFromWindowsErrWithFilename (int ierr,
          const char *filename)
     `Return value: Always NULL.' 类似于
     ‘PyErr_SetFromWindowsErrWithFilenameObject()’ ，但是 filename 是以
     C 字符串形式给出的。 `filename' 是从文件系统编码（*note
     os.fsdecode(): 5e8.）解码出来的。

     *note 可用性: 1491.: Windows。

 -- C 函式: PyObject* PyErr_SetExcFromWindowsErrWithFilenameObject
          (PyObject *type, int ierr, PyObject *filename)
     `Return value: Always NULL.' 类似于
     ‘PyErr_SetFromWindowsErrWithFilenameObject()’ ，额外参数指定要触发
     的异常类型。

     *note 可用性: 1491.: Windows。

 -- C 函式: PyObject* PyErr_SetExcFromWindowsErrWithFilenameObjects
          (PyObject *type, int ierr, PyObject *filename,
          PyObject *filename2)
     `Return value: Always NULL.' 类似于 *note
     PyErr_SetExcFromWindowsErrWithFilenameObject(): 3e10. ，但是接受第
     二个 filename 对象。

     *note 可用性: 1491.: Windows。

     3.4 版新加入.

 -- C 函式: PyObject* PyErr_SetExcFromWindowsErrWithFilename
          (PyObject *type, int ierr, const char *filename)
     `Return value: Always NULL.' 类似于 *note
     PyErr_SetFromWindowsErrWithFilename(): 3e0f. ，额外参数指定要触发的
     异常类型。

     *note 可用性: 1491.: Windows。

 -- C 函式: PyObject* PyErr_SetImportError (PyObject *msg,
          PyObject *name, PyObject *path)
     `Return value: Always NULL.' 这是触发 *note ImportError: 16c. 的便
     捷函数。 `msg' 将被设为异常的消息字符串。 `name' 和 `path' ，（都可
     以为 ‘NULL’ ），将用来被设置 *note ImportError: 16c. 对应的属性
     ‘name’ 和 ‘path’。

     3.3 版新加入.

 -- C 函式: void PyErr_SyntaxLocationObject (PyObject *filename,
          int lineno, int col_offset)

     设置当前异常的文件，行和偏移信息。如果当前异常不是 *note
     SyntaxError: 559. ，则它设置额外的属性，使异常打印子系统认为异常是
     *note SyntaxError: 559.。

     3.4 版新加入.

 -- C 函式: void PyErr_SyntaxLocationEx (const char *filename,
          int lineno, int col_offset)

     与 *note PyErr_SyntaxLocationObject(): 3e13. 类似，只是 `filename'
     是从文件系统编码（ *note os.fsdecode(): 5e8. ）解码出的一个字节字符
     串。

     3.2 版新加入.

 -- C 函式: void PyErr_SyntaxLocation (const char *filename, int lineno)

     与 *note PyErr_SyntaxLocationEx(): 3e14. 类似，但省略了参数
     col_offset。

 -- C 函式: void PyErr_BadInternalCall ()

     这是 ‘PyErr_SetString(PyExc_SystemError, message)’ 的缩写，其中
     `message' 表示使用了非法参数调用内部操作（例如，Python/C API 函数）
     。它主要用于内部使用。


File: python.info,  Node: 发出警告,  Next: 查询错误指示器,  Prev: 抛出异常,  Up: 例外處理

7.5.3 发出警告
--------------

这些函数可以从 C 代码中发出警告。它们仿照了由 Python 模块 *note
warnings: 12f. 导出的那些函数。它们通常向 `sys.stderr' 打印一条警告信息
；当然，用户也有可能已经指定将警告转换为错误，在这种情况下，它们将触发异
常。也有可能由于警告机制出现问题，使得函数触发异常。如果没有触发异常，返
回值为 ‘0’ ；如果触发异常，返回值为 ‘-1’。（无法确定是否实际打印了警告信
息，也无法确定异常触发的原因。这是故意为之）。如果触发了异常，调用者应该
进行正常的异常处理（例如，*note Py_DECREF(): 38f. 持有引用并返回一个错误
值）。

 -- C 函式: int PyErr_WarnEx (PyObject *category, const char *message,
          Py_ssize_t stack_level)

     发出一个警告信息。参数 `category' 是一个警告类别（见下面）或 ‘NULL’
     ； `message' 是一个 UTF-8 编码的字符串。 `stack_level' 是一个给出栈
     帧数量的正数；警告将从该栈帧中当前正在执行的代码行发出。
     `stack_level' 为 1 的是调用 *note PyErr_WarnEx(): e76. 的函数，2 是
     在此之上的函数，以此类推。

     警告类别必须是 ‘PyExc_Warning’ 的子类， ‘PyExc_Warning’ 是
     ‘PyExc_Exception’ 的子类；默认警告类别是 ‘PyExc_RuntimeWarning’ 。
     标准 Python 警告类别作为全局变量可用，所有其名称见 *note
     标准警告类别: 3e18. 。

     有关警告控制的信息，参见模块文档 *note warnings: 12f. 和命令行文档
     中的 *note -W: 15b. 选项。没有用于警告控制的 C API。

 -- C 函式: PyObject* PyErr_SetImportErrorSubclass (PyObject *exception,
          PyObject *msg, PyObject *name, PyObject *path)
     `Return value: Always NULL.' 和 *note PyErr_SetImportError(): 6ef.
     很类似，但这个函数允许指定一个 *note ImportError: 16c. 的子类来触发
     。

     3.6 版新加入.

 -- C 函式: int PyErr_WarnExplicitObject (PyObject *category,
          PyObject *message, PyObject *filename, int lineno,
          PyObject *module, PyObject *registry)

     Issue a warning message with explicit control over all warning
     attributes.  This is a straightforward wrapper around the Python
     function *note warnings.warn_explicit(): 6a7, see there for more
     information.  The `module' and `registry' arguments may be set to
     ‘NULL’ to get the default effect described there.

     3.4 版新加入.

 -- C 函式: int PyErr_WarnExplicit (PyObject *category, const
          char *message, const char *filename, int lineno, const
          char *module, PyObject *registry)

     Similar to *note PyErr_WarnExplicitObject(): 3e19. except that
     `message' and `module' are UTF-8 encoded strings, and `filename' is
     decoded from the filesystem encoding (*note os.fsdecode(): 5e8.).

 -- C 函式: int PyErr_WarnFormat (PyObject *category,
          Py_ssize_t stack_level, const char *format, ...)

     Function similar to *note PyErr_WarnEx(): e76, but use *note
     PyUnicode_FromFormat(): 8b8. to format the warning message.
     `format' is an ASCII-encoded string.

     3.2 版新加入.

 -- C 函式: int PyErr_ResourceWarning (PyObject *source,
          Py_ssize_t stack_level, const char *format, ...)

     Function similar to *note PyErr_WarnFormat(): 3e1b, but `category'
     is *note ResourceWarning: 5ca. and it passes `source' to
     ‘warnings.WarningMessage()’.

     3.6 版新加入.


File: python.info,  Node: 查询错误指示器,  Next: 信号处理<2>,  Prev: 发出警告,  Up: 例外處理

7.5.4 查询错误指示器
--------------------

 -- C 函式: PyObject* PyErr_Occurred ()
     `Return value: Borrowed reference.'  Test whether the error
     indicator is set.  If set, return the exception `type' (the first
     argument to the last call to one of the ‘PyErr_Set*()’ functions or
     to *note PyErr_Restore(): 3d71.).  If not set, return ‘NULL’.  You
     do not own a reference to the return value, so you do not need to
     *note Py_DECREF(): 38f. it.

     呼叫者必须持有GIL。

          備註: Do not compare the return value to a specific exception;
          use *note PyErr_ExceptionMatches(): 3dd0. instead, shown
          below.  (The comparison could easily fail since the exception
          may be an instance instead of a class, in the case of a class
          exception, or it may be a subclass of the expected exception.)

 -- C 函式: int PyErr_ExceptionMatches (PyObject *exc)

     Equivalent to ‘PyErr_GivenExceptionMatches(PyErr_Occurred(), exc)’.
     This should only be called when an exception is actually set; a
     memory access violation will occur if no exception has been raised.

 -- C 函式: int PyErr_GivenExceptionMatches (PyObject *given,
          PyObject *exc)

     Return true if the `given' exception matches the exception type in
     `exc'.  If `exc' is a class object, this also returns true when
     `given' is an instance of a subclass.  If `exc' is a tuple, all
     exception types in the tuple (and recursively in subtuples) are
     searched for a match.

 -- C 函式: void PyErr_Fetch (PyObject **ptype, PyObject **pvalue,
          PyObject **ptraceback)

     Retrieve the error indicator into three variables whose addresses
     are passed.  If the error indicator is not set, set all three
     variables to ‘NULL’.  If it is set, it will be cleared and you own
     a reference to each object retrieved.  The value and traceback
     object may be ‘NULL’ even when the type object is not.

          備註: This function is normally only used by code that needs
          to catch exceptions or by code that needs to save and restore
          the error indicator temporarily, e.g.:

               {
                  PyObject *type, *value, *traceback;
                  PyErr_Fetch(&type, &value, &traceback);

                  /* ... code that might produce other errors ... */

                  PyErr_Restore(type, value, traceback);
               }

 -- C 函式: void PyErr_Restore (PyObject *type, PyObject *value,
          PyObject *traceback)

     Set the error indicator from the three objects.  If the error
     indicator is already set, it is cleared first.  If the objects are
     ‘NULL’, the error indicator is cleared.  Do not pass a ‘NULL’ type
     and non-‘NULL’ value or traceback.  The exception type should be a
     class.  Do not pass an invalid exception type or value.  (Violating
     these rules will cause subtle problems later.)  This call takes
     away a reference to each object: you must own a reference to each
     object before the call and after the call you no longer own these
     references.  (If you don’t understand this, don’t use this
     function.  I warned you.)

          備註: This function is normally only used by code that needs
          to save and restore the error indicator temporarily.  Use
          *note PyErr_Fetch(): a4b. to save the current error indicator.

 -- C 函式: void PyErr_NormalizeException (PyObject**exc, PyObject**val,
          PyObject**tb)

     Under certain circumstances, the values returned by *note
     PyErr_Fetch(): a4b. below can be "unnormalized", meaning that
     ‘*exc’ is a class object but ‘*val’ is not an instance of the same
     class.  This function can be used to instantiate the class in that
     case.  If the values are already normalized, nothing happens.  The
     delayed normalization is implemented to improve performance.

          備註: This function `does not' implicitly set the
          ‘__traceback__’ attribute on the exception value.  If setting
          the traceback appropriately is desired, the following
          additional snippet is needed:

               if (tb != NULL) {
                 PyException_SetTraceback(val, tb);
               }

 -- C 函式: void PyErr_GetExcInfo (PyObject **ptype, PyObject **pvalue,
          PyObject **ptraceback)

     Retrieve the exception info, as known from ‘sys.exc_info()’.  This
     refers to an exception that was `already caught', not to an
     exception that was freshly raised.  Returns new references for the
     three objects, any of which may be ‘NULL’.  Does not modify the
     exception info state.

          備註: This function is not normally used by code that wants to
          handle exceptions.  Rather, it can be used when code needs to
          save and restore the exception state temporarily.  Use *note
          PyErr_SetExcInfo(): 3e1f. to restore or clear the exception
          state.

     3.3 版新加入.

 -- C 函式: void PyErr_SetExcInfo (PyObject *type, PyObject *value,
          PyObject *traceback)

     Set the exception info, as known from ‘sys.exc_info()’.  This
     refers to an exception that was `already caught', not to an
     exception that was freshly raised.  This function steals the
     references of the arguments.  To clear the exception state, pass
     ‘NULL’ for all three arguments.  For general rules about the three
     arguments, see *note PyErr_Restore(): 3d71.

          備註: This function is not normally used by code that wants to
          handle exceptions.  Rather, it can be used when code needs to
          save and restore the exception state temporarily.  Use *note
          PyErr_GetExcInfo(): 3e1e. to read the exception state.

     3.3 版新加入.


File: python.info,  Node: 信号处理<2>,  Next: Exception 类<2>,  Prev: 查询错误指示器,  Up: 例外處理

7.5.5 信号处理
--------------

 -- C 函式: int PyErr_CheckSignals ()

     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 *note signal: ea. module
     is supported, this can invoke a signal handler written in Python.
     In all cases, the default effect for ‘SIGINT’ is to raise the *note
     KeyboardInterrupt: 2cc. exception.  If an exception is raised the
     error indicator is set and the function returns ‘-1’; otherwise the
     function returns ‘0’.  The error indicator may or may not be
     cleared if it was previously set.

 -- C 函式: void PyErr_SetInterrupt ()

     Simulate the effect of a ‘SIGINT’ signal arriving.  The next time
     *note PyErr_CheckSignals(): 3e09. is called, the Python signal
     handler for ‘SIGINT’ will be called.

     如果 Python 没有处理 *note signal.SIGINT: 2626. (将它设为 *note
     signal.SIG_DFL: 2627. 或 *note signal.SIG_IGN: 2628.)，此函数将不做
     任何事。

 -- C 函式: int PySignal_SetWakeupFd (int fd)

     This utility function specifies a file descriptor to which the
     signal number is written as a single byte whenever a signal is
     received.  `fd' must be non-blocking.  It returns the previous such
     file descriptor.

     The value ‘-1’ disables the feature; this is the initial state.
     This is equivalent to *note signal.set_wakeup_fd(): 4d4. in Python,
     but without any error checking.  `fd' should be a valid file
     descriptor.  The function should only be called from the main
     thread.

     3.5 版更變: 在 Windows 上，此函数现在也支持套接字处理。


File: python.info,  Node: Exception 类<2>,  Next: 异常对象,  Prev: 信号处理<2>,  Up: 例外處理

7.5.6 Exception 类
------------------

 -- C 函式: PyObject* PyErr_NewException (const char *name,
          PyObject *base, PyObject *dict)
     `Return value: New reference.'  This utility function creates and
     returns a new exception class.  The `name' argument must be the
     name of the new exception, a C string of the form
     ‘module.classname’.  The `base' and `dict' arguments are normally
     ‘NULL’.  This creates a class object derived from *note Exception:
     2dc. (accessible in C as ‘PyExc_Exception’).

     The ‘__module__’ attribute of the new class is set to the first
     part (up to the last dot) of the `name' argument, and the class
     name is set to the last part (after the last dot).  The `base'
     argument can be used to specify alternate base classes; it can
     either be only one class or a tuple of classes.  The `dict'
     argument can be used to specify a dictionary of class variables and
     methods.

 -- C 函式: PyObject* PyErr_NewExceptionWithDoc (const char *name, const
          char *doc, PyObject *base, PyObject *dict)
     `Return value: New reference.' 和 *note PyErr_NewException(): ccb.
     一样，除了可以轻松地给新的异常类一个文档字符串：如果 `doc' 属性非空
     ，它将用作异常类的文档字符串。

     3.2 版新加入.


File: python.info,  Node: 异常对象,  Next: Unicode 异常对象,  Prev: Exception 类<2>,  Up: 例外處理

7.5.7 异常对象
--------------

 -- C 函式: PyObject* PyException_GetTraceback (PyObject *ex)
     `Return value: New reference.'  Return the traceback associated
     with the exception as a new reference, as accessible from Python
     through ‘__traceback__’.  If there is no traceback associated, this
     returns ‘NULL’.

 -- C 函式: int PyException_SetTraceback (PyObject *ex, PyObject *tb)

     将异常关联的回溯设置为 `tb' 。使用‘‘Py_None‘‘清除它。

 -- C 函式: PyObject* PyException_GetContext (PyObject *ex)
     `Return value: New reference.'  Return the context (another
     exception instance during whose handling `ex' was raised)
     associated with the exception as a new reference, as accessible
     from Python through ‘__context__’.  If there is no context
     associated, this returns ‘NULL’.

 -- C 函式: void PyException_SetContext (PyObject *ex, PyObject *ctx)

     Set the context associated with the exception to `ctx'.  Use ‘NULL’
     to clear it.  There is no type check to make sure that `ctx' is an
     exception instance.  This steals a reference to `ctx'.

 -- C 函式: PyObject* PyException_GetCause (PyObject *ex)
     `Return value: New reference.'  Return the cause (either an
     exception instance, or *note None: 203, set by ‘raise ... from
     ...’) associated with the exception as a new reference, as
     accessible from Python through ‘__cause__’.

 -- C 函式: void PyException_SetCause (PyObject *ex, PyObject *cause)

     Set the cause associated with the exception to `cause'.  Use ‘NULL’
     to clear it.  There is no type check to make sure that `cause' is
     either an exception instance or *note None: 203.  This steals a
     reference to `cause'.

     ‘__suppress_context__’ is implicitly set to ‘True’ by this
     function.


File: python.info,  Node: Unicode 异常对象,  Next: 递归控制,  Prev: 异常对象,  Up: 例外處理

7.5.8 Unicode 异常对象
----------------------

The following functions are used to create and modify Unicode exceptions
from C.

 -- C 函式: PyObject* PyUnicodeDecodeError_Create (const char *encoding,
          const char *object, Py_ssize_t length, Py_ssize_t start,
          Py_ssize_t end, const char *reason)
     `Return value: New reference.'  Create a *note UnicodeDecodeError:
     32b. object with the attributes `encoding', `object', `length',
     `start', `end' and `reason'.  `encoding' and `reason' are UTF-8
     encoded strings.

 -- C 函式: PyObject* PyUnicodeEncodeError_Create (const char *encoding,
          const Py_UNICODE *object, Py_ssize_t length, Py_ssize_t start,
          Py_ssize_t end, const char *reason)
     `Return value: New reference.'  Create a *note UnicodeEncodeError:
     32a. object with the attributes `encoding', `object', `length',
     `start', `end' and `reason'.  `encoding' and `reason' are UTF-8
     encoded strings.

     3.3 版後已棄用: 3.11

     ‘Py_UNICODE’ is deprecated since Python 3.3.  Please migrate to
     ‘PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnns", ...)’.

 -- C 函式: PyObject* PyUnicodeTranslateError_Create (const
          Py_UNICODE *object, Py_ssize_t length, Py_ssize_t start,
          Py_ssize_t end, const char *reason)
     `Return value: New reference.'  Create a *note
     UnicodeTranslateError: 185b. object with the attributes `object',
     `length', `start', `end' and `reason'.  `reason' is a UTF-8 encoded
     string.

     3.3 版後已棄用: 3.11

     ‘Py_UNICODE’ is deprecated since Python 3.3.  Please migrate to
     ‘PyObject_CallFunction(PyExc_UnicodeTranslateError, "Onns", ...)’.

 -- C 函式: PyObject* PyUnicodeDecodeError_GetEncoding (PyObject *exc)
 -- C 函式: PyObject* PyUnicodeEncodeError_GetEncoding (PyObject *exc)
     `Return value: New reference.' 返回给定异常对象的 `encoding' 属性

 -- C 函式: PyObject* PyUnicodeDecodeError_GetObject (PyObject *exc)
 -- C 函式: PyObject* PyUnicodeEncodeError_GetObject (PyObject *exc)
 -- C 函式: PyObject* PyUnicodeTranslateError_GetObject (PyObject *exc)
     `Return value: New reference.' 返回给定异常对象的 `object' 属性

 -- C 函式: int PyUnicodeDecodeError_GetStart (PyObject *exc,
          Py_ssize_t *start)
 -- C 函式: int PyUnicodeEncodeError_GetStart (PyObject *exc,
          Py_ssize_t *start)
 -- C 函式: int PyUnicodeTranslateError_GetStart (PyObject *exc,
          Py_ssize_t *start)

     Get the `start' attribute of the given exception object and place
     it into `*start'.  `start' must not be ‘NULL’.  Return ‘0’ on
     success, ‘-1’ on failure.

 -- C 函式: int PyUnicodeDecodeError_SetStart (PyObject *exc,
          Py_ssize_t start)
 -- C 函式: int PyUnicodeEncodeError_SetStart (PyObject *exc,
          Py_ssize_t start)
 -- C 函式: int PyUnicodeTranslateError_SetStart (PyObject *exc,
          Py_ssize_t start)

     Set the `start' attribute of the given exception object to `start'.
     Return ‘0’ on success, ‘-1’ on failure.

 -- C 函式: int PyUnicodeDecodeError_GetEnd (PyObject *exc,
          Py_ssize_t *end)
 -- C 函式: int PyUnicodeEncodeError_GetEnd (PyObject *exc,
          Py_ssize_t *end)
 -- C 函式: int PyUnicodeTranslateError_GetEnd (PyObject *exc,
          Py_ssize_t *end)

     Get the `end' attribute of the given exception object and place it
     into `*end'.  `end' must not be ‘NULL’.  Return ‘0’ on success,
     ‘-1’ on failure.

 -- C 函式: int PyUnicodeDecodeError_SetEnd (PyObject *exc,
          Py_ssize_t end)
 -- C 函式: int PyUnicodeEncodeError_SetEnd (PyObject *exc,
          Py_ssize_t end)
 -- C 函式: int PyUnicodeTranslateError_SetEnd (PyObject *exc,
          Py_ssize_t end)

     Set the `end' attribute of the given exception object to `end'.
     Return ‘0’ on success, ‘-1’ on failure.

 -- C 函式: PyObject* PyUnicodeDecodeError_GetReason (PyObject *exc)
 -- C 函式: PyObject* PyUnicodeEncodeError_GetReason (PyObject *exc)
 -- C 函式: PyObject* PyUnicodeTranslateError_GetReason (PyObject *exc)
     `Return value: New reference.' 返回给定异常对象的 `reason' 属性

 -- C 函式: int PyUnicodeDecodeError_SetReason (PyObject *exc, const
          char *reason)
 -- C 函式: int PyUnicodeEncodeError_SetReason (PyObject *exc, const
          char *reason)
 -- C 函式: int PyUnicodeTranslateError_SetReason (PyObject *exc, const
          char *reason)

     Set the `reason' attribute of the given exception object to
     `reason'.  Return ‘0’ on success, ‘-1’ on failure.


File: python.info,  Node: 递归控制,  Next: 标准异常,  Prev: Unicode 异常对象,  Up: 例外處理

7.5.9 递归控制
--------------

These two functions provide a way to perform safe recursive calls at the
C level, both in the core and in extension modules.  They are needed if
the recursive code does not necessarily invoke Python code (which tracks
its recursion depth automatically).  They are also not needed for
`tp_call' implementations because the *note call protocol: 3e47. takes
care of recursion handling.

 -- C 函式: int Py_EnterRecursiveCall (const char *where)

     Marks a point where a recursive C-level call is about to be
     performed.

     如果定义了 ‘USE_STACKCHECK’，此函数会使用 *note PyOS_CheckStack():
     3e48. 来检查操作系统堆栈是否溢出。 在这种情况下，它将设置一个 *note
     MemoryError: f69. 并返回非零值。

     The function then checks if the recursion limit is reached.  If
     this is the case, a *note RecursionError: 727. is set and a nonzero
     value is returned.  Otherwise, zero is returned.

     `where' should be a UTF-8 encoded string such as ‘" in instance
     check"’ to be concatenated to the *note RecursionError: 727.
     message caused by the recursion depth limit.

     3.9 版更變: This function is now also available in the limited API.

 -- C 函式: void Py_LeaveRecursiveCall (void)

     Ends a *note Py_EnterRecursiveCall(): 251.  Must be called once for
     each `successful' invocation of *note Py_EnterRecursiveCall(): 251.

     3.9 版更變: This function is now also available in the limited API.

Properly implementing *note tp_repr: 3d74. for container types requires
special recursion handling.  In addition to protecting the stack, *note
tp_repr: 3d74. also needs to track objects to prevent cycles.  The
following two functions facilitate this functionality.  Effectively,
these are the C equivalent to *note reprlib.recursive_repr(): c41.

 -- C 函式: int Py_ReprEnter (PyObject *object)

     Called at the beginning of the *note tp_repr: 3d74. implementation
     to detect cycles.

     If the object has already been processed, the function returns a
     positive integer.  In that case the *note tp_repr: 3d74.
     implementation should return a string object indicating a cycle.
     As examples, *note dict: 164. objects return ‘{...}’ and *note
     list: 1f8. objects return ‘[...]’.

     The function will return a negative integer if the recursion limit
     is reached.  In that case the *note tp_repr: 3d74. implementation
     should typically return ‘NULL’.

     Otherwise, the function returns zero and the *note tp_repr: 3d74.
     implementation can continue normally.

 -- C 函式: void Py_ReprLeave (PyObject *object)

     Ends a *note Py_ReprEnter(): 3e49.  Must be called once for each
     invocation of *note Py_ReprEnter(): 3e49. that returns zero.


File: python.info,  Node: 标准异常,  Next: 标准警告类别,  Prev: 递归控制,  Up: 例外處理

7.5.10 标准异常
---------------

All standard Python exceptions are available as global variables whose
names are ‘PyExc_’ followed by the Python exception name.  These have
the type *note PyObject*: 5b4.; they are all class objects.  For
completeness, here are all the variables:

C 名称                                        Python 名称                           註解
                                                                                    
---------------------------------------------------------------------------------------------------
                                                                                    
‘PyExc_BaseException’                         *note BaseException: 2db.             (1)
                                                                                    
                                                                                    
‘PyExc_Exception’                             *note Exception: 2dc.                 (1)
                                                                                    
                                                                                    
‘PyExc_ArithmeticError’                       *note ArithmeticError: 1845.          (1)
                                                                                    
                                                                                    
‘PyExc_AssertionError’                        *note AssertionError: 240.
                                              
                                                                                    
‘PyExc_AttributeError’                        *note AttributeError: 4a1.
                                              
                                                                                    
‘PyExc_BlockingIOError’                       *note BlockingIOError: a78.
                                              
                                                                                    
‘PyExc_BrokenPipeError’                       *note BrokenPipeError: a7e.
                                              
                                                                                    
‘PyExc_BufferError’                           *note BufferError: 1847.
                                              
                                                                                    
‘PyExc_ChildProcessError’                     *note ChildProcessError: a79.
                                              
                                                                                    
‘PyExc_ConnectionAbortedError’                *note ConnectionAbortedError: a7f.
                                              
                                                                                    
‘PyExc_ConnectionError’                       *note ConnectionError: 7d7.
                                              
                                                                                    
‘PyExc_ConnectionRefusedError’                *note ConnectionRefusedError: a80.
                                              
                                                                                    
‘PyExc_ConnectionResetError’                  *note ConnectionResetError: a81.
                                              
                                                                                    
‘PyExc_EOFError’                              *note EOFError: d34.
                                              
                                                                                    
‘PyExc_FileExistsError’                       *note FileExistsError: a39.
                                              
                                                                                    
‘PyExc_FileNotFoundError’                     *note FileNotFoundError: 8ad.
                                              
                                                                                    
‘PyExc_FloatingPointError’                    *note FloatingPointError: 1846.
                                              
                                                                                    
‘PyExc_GeneratorExit’                         *note GeneratorExit: df8.
                                              
                                                                                    
‘PyExc_ImportError’                           *note ImportError: 16c.
                                              
                                                                                    
‘PyExc_IndentationError’                      *note IndentationError: f39.
                                              
                                                                                    
‘PyExc_IndexError’                            *note IndexError: f36.
                                              
                                                                                    
‘PyExc_InterruptedError’                      *note InterruptedError: 74c.
                                              
                                                                                    
‘PyExc_IsADirectoryError’                     *note IsADirectoryError: a7a.
                                              
                                                                                    
‘PyExc_KeyError’                              *note KeyError: 3e9.
                                              
                                                                                    
‘PyExc_KeyboardInterrupt’                     *note KeyboardInterrupt: 2cc.
                                              
                                                                                    
‘PyExc_LookupError’                           *note LookupError: 1790.              (1)
                                                                                    
                                                                                    
‘PyExc_MemoryError’                           *note MemoryError: f69.
                                              
                                                                                    
‘PyExc_ModuleNotFoundError’                   *note ModuleNotFoundError: 4a0.
                                              
                                                                                    
‘PyExc_NameError’                             *note NameError: e40.
                                              
                                                                                    
‘PyExc_NotADirectoryError’                    *note NotADirectoryError: a7b.
                                              
                                                                                    
‘PyExc_NotImplementedError’                   *note NotImplementedError: 704.
                                              
                                                                                    
‘PyExc_OSError’                               *note OSError: 304.                   (1)
                                                                                    
                                                                                    
‘PyExc_OverflowError’                         *note OverflowError: a41.
                                              
                                                                                    
‘PyExc_PermissionError’                       *note PermissionError: 6f6.
                                              
                                                                                    
‘PyExc_ProcessLookupError’                    *note ProcessLookupError: a7c.
                                              
                                                                                    
‘PyExc_RecursionError’                        *note RecursionError: 727.
                                              
                                                                                    
‘PyExc_ReferenceError’                        *note ReferenceError: f0f.            (2)
                                                                                    
                                                                                    
‘PyExc_RuntimeError’                          *note RuntimeError: 3dc.
                                              
                                                                                    
‘PyExc_StopAsyncIteration’                    *note StopAsyncIteration: 114a.
                                              
                                                                                    
‘PyExc_StopIteration’                         *note StopIteration: 581.
                                              
                                                                                    
‘PyExc_SyntaxError’                           *note SyntaxError: 559.
                                              
                                                                                    
‘PyExc_SystemError’                           *note SystemError: 6f2.
                                              
                                                                                    
‘PyExc_SystemExit’                            *note SystemExit: 6f3.
                                              
                                                                                    
‘PyExc_TabError’                              *note TabError: f38.
                                              
                                                                                    
‘PyExc_TimeoutError’                          *note TimeoutError: a7d.
                                              
                                                                                    
‘PyExc_TypeError’                             *note TypeError: 1fe.
                                              
                                                                                    
‘PyExc_UnboundLocalError’                     *note UnboundLocalError: f37.
                                              
                                                                                    
‘PyExc_UnicodeDecodeError’                    *note UnicodeDecodeError: 32b.
                                              
                                                                                    
‘PyExc_UnicodeEncodeError’                    *note UnicodeEncodeError: 32a.
                                              
                                                                                    
‘PyExc_UnicodeError’                          *note UnicodeError: d03.
                                              
                                                                                    
‘PyExc_UnicodeTranslateError’                 *note UnicodeTranslateError: 185b.
                                              
                                                                                    
‘PyExc_ValueError’                            *note ValueError: 16d.
                                              
                                                                                    
‘PyExc_ZeroDivisionError’                     *note ZeroDivisionError: 1fa.
                                              

3.3 版新加入: ‘PyExc_BlockingIOError’, ‘PyExc_BrokenPipeError’,
‘PyExc_ChildProcessError’, ‘PyExc_ConnectionError’,
‘PyExc_ConnectionAbortedError’, ‘PyExc_ConnectionRefusedError’,
‘PyExc_ConnectionResetError’, ‘PyExc_FileExistsError’,
‘PyExc_FileNotFoundError’, ‘PyExc_InterruptedError’,
‘PyExc_IsADirectoryError’, ‘PyExc_NotADirectoryError’,
‘PyExc_PermissionError’, ‘PyExc_ProcessLookupError’ and
‘PyExc_TimeoutError’ 介绍如下 PEP 3151(1).

3.5 版新加入: ‘PyExc_StopAsyncIteration’ 和 ‘PyExc_RecursionError’.

3.6 版新加入: ‘PyExc_ModuleNotFoundError’.

这些是兼容性别名 ‘PyExc_OSError’:

C 名称                                    註解
                                          
---------------------------------------------------------
                                          
‘PyExc_EnvironmentError’

‘PyExc_IOError’

‘PyExc_WindowsError’                      (3)
                                          

3.3 版更變: 这些别名曾经是单独的异常类型。

註解：

  1. 这是其他标准异常的基类。

  2. Only defined on Windows; protect code that uses this by testing
     that the preprocessor macro ‘MS_WINDOWS’ is defined.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3151


File: python.info,  Node: 标准警告类别,  Prev: 标准异常,  Up: 例外處理

7.5.11 标准警告类别
-------------------

All standard Python warning categories are available as global variables
whose names are ‘PyExc_’ followed by the Python exception name.  These
have the type *note PyObject*: 5b4.; they are all class objects.  For
completeness, here are all the variables:

C 名称                                         Python 名称                           註解
                                                                                     
----------------------------------------------------------------------------------------------------
                                                                                     
‘PyExc_Warning’                                *note Warning: 1860.                  (1)
                                                                                     
                                                                                     
‘PyExc_BytesWarning’                           *note BytesWarning: 5af.
                                               
                                                                                     
‘PyExc_DeprecationWarning’                     *note DeprecationWarning: 15a.
                                               
                                                                                     
‘PyExc_FutureWarning’                          *note FutureWarning: 435.
                                               
                                                                                     
‘PyExc_ImportWarning’                          *note ImportWarning: 6cf.
                                               
                                                                                     
‘PyExc_PendingDeprecationWarning’              *note PendingDeprecationWarning: 15c.
                                               
                                                                                     
‘PyExc_ResourceWarning’                        *note ResourceWarning: 5ca.
                                               
                                                                                     
‘PyExc_RuntimeWarning’                         *note RuntimeWarning: 3e2.
                                               
                                                                                     
‘PyExc_SyntaxWarning’                          *note SyntaxWarning: 2c9.
                                               
                                                                                     
‘PyExc_UnicodeWarning’                         *note UnicodeWarning: e4c.
                                               
                                                                                     
‘PyExc_UserWarning’                            *note UserWarning: 1861.
                                               

3.2 版新加入: ‘PyExc_ResourceWarning’.

註解：

  1. 这是其他标准警告类别的基类。


File: python.info,  Node: 工具<2>,  Next: 抽象物件層,  Prev: 例外處理,  Up: Python/C API 參考手冊

7.6 工具
========

本章中的函数执行各种实用工具任务，包括帮助 C 代码提升跨平台可移植性，在
C 中使用 Python 模块，以及解析函数参数并根据 C 中的值构建 Python 中的值
等等。

* Menu:

* 作業系統工具::
* 系統函式::
* 行程（Process）控制::
* 匯入模組: 匯入模組<2>.
* 数据 marshal 操作支持::
* 语句解释及变量编译::
* 字串轉換與格式化::
* 反射::
* 编解码器注册与支持功能::


File: python.info,  Node: 作業系統工具,  Next: 系統函式,  Up: 工具<2>

7.6.1 作業系統工具
------------------

 -- C 函式: PyObject* PyOS_FSPath (PyObject *path)
     `Return value: New reference.'  Return the file system
     representation for `path'.  If the object is a *note str: 205. or
     *note bytes: 172. object, then its reference count is incremented.
     If the object implements the *note os.PathLike: 5e5. interface,
     then *note __fspath__(): 5e6. is returned as long as it is a *note
     str: 205. or *note bytes: 172. object.  Otherwise *note TypeError:
     1fe. is raised and ‘NULL’ is returned.

     3.6 版新加入.

 -- C 函式: int Py_FdIsInteractive (FILE *fp, const char *filename)

     Return true (nonzero) if the standard I/O file `fp' with name
     `filename' is deemed interactive.  This is the case for files for
     which ‘isatty(fileno(fp))’ is true.  If the global flag *note
     Py_InteractiveFlag: 3e55. is true, this function also returns true
     if the `filename' pointer is ‘NULL’ or if the name is equal to one
     of the strings ‘'<stdin>'’ or ‘'???'’.

 -- C 函式: void PyOS_BeforeFork ()

     Function to prepare some internal state before a process fork.
     This should be called before calling ‘fork()’ or any similar
     function that clones the current process.  Only available on
     systems where ‘fork()’ is defined.

          警告: The C ‘fork()’ call should only be made from the *note
          "main" thread: 3e56. (of the *note "main" interpreter: 3e57.).
          The same is true for ‘PyOS_BeforeFork()’.

     3.7 版新加入.

 -- C 函式: void PyOS_AfterFork_Parent ()

     Function to update some internal state after a process fork.  This
     should be called from the parent process after calling ‘fork()’ or
     any similar function that clones the current process, regardless of
     whether process cloning was successful.  Only available on systems
     where ‘fork()’ is defined.

          警告: The C ‘fork()’ call should only be made from the *note
          "main" thread: 3e56. (of the *note "main" interpreter: 3e57.).
          The same is true for ‘PyOS_AfterFork_Parent()’.

     3.7 版新加入.

 -- C 函式: void PyOS_AfterFork_Child ()

     Function to update internal interpreter state after a process fork.
     This must be called from the child process after calling ‘fork()’,
     or any similar function that clones the current process, if there
     is any chance the process will call back into the Python
     interpreter.  Only available on systems where ‘fork()’ is defined.

          警告: The C ‘fork()’ call should only be made from the *note
          "main" thread: 3e56. (of the *note "main" interpreter: 3e57.).
          The same is true for ‘PyOS_AfterFork_Child()’.

     3.7 版新加入.

     也參考
     ......

     *note os.register_at_fork(): 4bc. allows registering custom Python
     functions to be called by *note PyOS_BeforeFork(): 535, *note
     PyOS_AfterFork_Parent(): 536. and *note PyOS_AfterFork_Child():
     3ef.

 -- C 函式: void PyOS_AfterFork ()

     Function to update some internal state after a process fork; this
     should be called in the new process if the Python interpreter will
     continue to be used.  If a new executable is loaded into the new
     process, this function does not need to be called.

     3.7 版後已棄用: This function is superseded by *note
     PyOS_AfterFork_Child(): 3ef.

 -- C 函式: int PyOS_CheckStack ()

     Return true when the interpreter runs out of stack space.  This is
     a reliable check, but is only available when ‘USE_STACKCHECK’ is
     defined (currently on Windows using the Microsoft Visual C++
     compiler).  ‘USE_STACKCHECK’ will be defined automatically; you
     should never change the definition in your own code.

 -- C 函式: PyOS_sighandler_t PyOS_getsig (int i)

     Return the current signal handler for signal `i'.  This is a thin
     wrapper around either ‘sigaction()’ or ‘signal()’.  Do not call
     those functions directly!  ‘PyOS_sighandler_t’ is a typedef alias
     for ‘void (*)(int)’.

 -- C 函式: PyOS_sighandler_t PyOS_setsig (int i, PyOS_sighandler_t h)

     Set the signal handler for signal `i' to be `h'; return the old
     signal handler.  This is a thin wrapper around either ‘sigaction()’
     or ‘signal()’.  Do not call those functions directly!
     ‘PyOS_sighandler_t’ is a typedef alias for ‘void (*)(int)’.

 -- C 函式: wchar_t* Py_DecodeLocale (const char* arg, size_t *size)

     Decode a byte string from the locale encoding with the *note
     surrogateescape error handler: 198a.: 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:

        * ‘UTF-8’ on macOS, Android, and VxWorks;

        * ‘UTF-8’ on Windows if *note Py_LegacyWindowsFSEncodingFlag:
          3e5a. is zero;

        * ‘UTF-8’ if the Python UTF-8 mode is enabled;

        * ‘ASCII’ if the ‘LC_CTYPE’ locale is ‘"C"’,
          ‘nl_langinfo(CODESET)’ returns the ‘ASCII’ encoding (or an
          alias), and ‘mbstowcs()’ and ‘wcstombs()’ functions uses the
          ‘ISO-8859-1’ encoding.

        * the current locale encoding.

     Return a pointer to a newly allocated wide character string, use
     *note PyMem_RawFree(): 3e5b. to free the memory.  If size is not
     ‘NULL’, write the number of wide characters excluding the null
     character into ‘*size’

     Return ‘NULL’ on decoding error or memory allocation error.  If
     `size' is not ‘NULL’, ‘*size’ is set to ‘(size_t)-1’ on memory
     error or set to ‘(size_t)-2’ on decoding error.

     Decoding errors should never happen, unless there is a bug in the C
     library.

     Use the *note Py_EncodeLocale(): 53f. function to encode the
     character string back to a byte string.

     也參考
     ......

     The *note PyUnicode_DecodeFSDefaultAndSize(): 3e5c. and *note
     PyUnicode_DecodeLocaleAndSize(): 540. functions.

     3.5 版新加入.

     3.7 版更變: The function now uses the UTF-8 encoding in the UTF-8
     mode.

     3.8 版更變: The function now uses the UTF-8 encoding on Windows if
     *note Py_LegacyWindowsFSEncodingFlag: 3e5a. is zero;

 -- C 函式: char* Py_EncodeLocale (const wchar_t *text,
          size_t *error_pos)

     Encode a wide character string to the locale encoding with the
     *note surrogateescape error handler: 198a.: surrogate characters in
     the range U+DC80..U+DCFF are converted to bytes 0x80..0xFF.

     Encoding, highest priority to lowest priority:

        * ‘UTF-8’ on macOS, Android, and VxWorks;

        * ‘UTF-8’ on Windows if *note Py_LegacyWindowsFSEncodingFlag:
          3e5a. is zero;

        * ‘UTF-8’ if the Python UTF-8 mode is enabled;

        * ‘ASCII’ if the ‘LC_CTYPE’ locale is ‘"C"’,
          ‘nl_langinfo(CODESET)’ returns the ‘ASCII’ encoding (or an
          alias), and ‘mbstowcs()’ and ‘wcstombs()’ functions uses the
          ‘ISO-8859-1’ encoding.

        * the current locale encoding.

     The function uses the UTF-8 encoding in the Python UTF-8 mode.

     Return a pointer to a newly allocated byte string, use *note
     PyMem_Free(): e6e. to free the memory.  Return ‘NULL’ on encoding
     error or memory allocation error

     If error_pos is not ‘NULL’, ‘*error_pos’ is set to ‘(size_t)-1’ on
     success, or set to the index of the invalid character on encoding
     error.

     Use the *note Py_DecodeLocale(): 53e. function to decode the bytes
     string back to a wide character string.

     也參考
     ......

     The *note PyUnicode_EncodeFSDefault(): 1180. and *note
     PyUnicode_EncodeLocale(): 541. functions.

     3.5 版新加入.

     3.7 版更變: The function now uses the UTF-8 encoding in the UTF-8
     mode.

     3.8 版更變: The function now uses the UTF-8 encoding on Windows if
     *note Py_LegacyWindowsFSEncodingFlag: 3e5a. is zero;


File: python.info,  Node: 系統函式,  Next: 行程（Process）控制,  Prev: 作業系統工具,  Up: 工具<2>

7.6.2 系統函式
--------------

These are utility functions that make functionality from the *note sys:
fd. module accessible to C code.  They all work with the current
interpreter thread’s *note sys: fd. module’s dict, which is contained in
the internal thread state structure.

 -- C 函式: PyObject *PySys_GetObject (const char *name)
     `Return value: Borrowed reference.'  Return the object `name' from
     the *note sys: fd. module or ‘NULL’ if it does not exist, without
     setting an exception.

 -- C 函式: int PySys_SetObject (const char *name, PyObject *v)

     Set `name' in the *note sys: fd. module to `v' unless `v' is
     ‘NULL’, in which case `name' is deleted from the sys module.
     Returns ‘0’ on success, ‘-1’ on error.

 -- C 函式: void PySys_ResetWarnOptions ()

     Reset *note sys.warnoptions: 51a. to an empty list.  This function
     may be called prior to *note Py_Initialize(): 20f.

 -- C 函式: void PySys_AddWarnOption (const wchar_t *s)

     Append `s' to *note sys.warnoptions: 51a.  This function must be
     called prior to *note Py_Initialize(): 20f. in order to affect the
     warnings filter list.

 -- C 函式: void PySys_AddWarnOptionUnicode (PyObject *unicode)

     Append `unicode' to *note sys.warnoptions: 51a.

     Note: this function is not currently usable from outside the
     CPython implementation, as it must be called prior to the implicit
     import of *note warnings: 12f. in *note Py_Initialize(): 20f. to be
     effective, but can’t be called until enough of the runtime has been
     initialized to permit the creation of Unicode objects.

 -- C 函式: void PySys_SetPath (const wchar_t *path)

     Set *note sys.path: 261. to a list object of paths found in `path'
     which should be a list of paths separated with the platform’s
     search path delimiter (‘:’ on Unix, ‘;’ on Windows).

 -- C 函式: void PySys_WriteStdout (const char *format, ...)

     Write the output string described by `format' to *note sys.stdout:
     41f.  No exceptions are raised, even if truncation occurs (see
     below).

     `format' should limit the total size of the formatted output string
     to 1000 bytes or less – after 1000 bytes, the output string is
     truncated.  In particular, this means that no unrestricted "%s"
     formats should occur; these should be limited using "%.<N>s" where
     <N> is a decimal number calculated so that <N> plus the maximum
     size of other formatted text does not exceed 1000 bytes.  Also
     watch out for "%f", which can print hundreds of digits for very
     large numbers.

     If a problem occurs, or *note sys.stdout: 41f. is unset, the
     formatted message is written to the real (C level) `stdout'.

 -- C 函式: void PySys_WriteStderr (const char *format, ...)

     As *note PySys_WriteStdout(): 3e63, but write to *note sys.stderr:
     1ea. or `stderr' instead.

 -- C 函式: void PySys_FormatStdout (const char *format, ...)

     Function similar to PySys_WriteStdout() but format the message
     using *note PyUnicode_FromFormatV(): 3e66. and don’t truncate the
     message to an arbitrary length.

     3.2 版新加入.

 -- C 函式: void PySys_FormatStderr (const char *format, ...)

     As *note PySys_FormatStdout(): 3e65, but write to *note sys.stderr:
     1ea. or `stderr' instead.

     3.2 版新加入.

 -- C 函式: void PySys_AddXOption (const wchar_t *s)

     Parse `s' as a set of *note -X: 290. options and add them to the
     current options mapping as returned by *note PySys_GetXOptions():
     3e69.  This function may be called prior to *note Py_Initialize():
     20f.

     3.2 版新加入.

 -- C 函式: PyObject *PySys_GetXOptions ()
     `Return value: Borrowed reference.'  Return the current dictionary
     of *note -X: 290. options, similarly to *note sys._xoptions: 1482.
     On error, ‘NULL’ is returned and an exception is set.

     3.2 版新加入.

 -- C 函式: int PySys_Audit (const char *event, const char *format, ...)

     Raise an auditing event with any active hooks.  Return zero for
     success and non-zero with an exception set on failure.

     If any hooks have been added, `format' and other arguments will be
     used to construct a tuple to pass.  Apart from ‘N’, the same format
     characters as used in *note Py_BuildValue(): 3f0. are available.
     If the built value is not a tuple, it will be added into a
     single-element tuple.  (The ‘N’ format option consumes a reference,
     but since there is no way to know whether arguments to this
     function will be consumed, using it may cause reference leaks.)

     Note that ‘#’ format characters should always be treated as
     ‘Py_ssize_t’, regardless of whether ‘PY_SSIZE_T_CLEAN’ was defined.

     *note sys.audit(): 1056. performs the same function from Python
     code.

     3.8 版新加入.

     3.8.2 版更變: Require ‘Py_ssize_t’ for ‘#’ format characters.
     Previously, an unavoidable deprecation warning was raised.

 -- C 函式: int PySys_AddAuditHook (Py_AuditHookFunction hook,
          void *userData)

     Append the callable `hook' to the list of active auditing hooks.
     Return zero for success and non-zero on failure.  If the runtime
     has been initialized, also set an error on failure.  Hooks added
     through this API are called for all interpreters created by the
     runtime.

     `userData' 指针会被传入钩子函数。 因于钩子函数可能由不同的运行时调
     用，该指针不应直接指向 Python 状态。

     This function is safe to call before *note Py_Initialize(): 20f.
     When called after runtime initialization, existing audit hooks are
     notified and may silently abort the operation by raising an error
     subclassed from *note Exception: 2dc. (other errors will not be
     silenced).

     The hook function is of type ‘int (*)(const char *event, PyObject
     *args, void *userData)’, where `args' is guaranteed to be a *note
     PyTupleObject: 3e6a.  The hook function is always called with the
     GIL held by the Python interpreter that raised the event.

     See PEP 578(1) for a detailed description of auditing.  Functions
     in the runtime and standard library that raise events are listed in
     the *note audit events table: 3667.  Details are in each function’s
     documentation.

     引发一个 *note 审计事件: fa1. ‘sys.addaudithook’，没有附带参数。

     3.8 版新加入.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0578


File: python.info,  Node: 行程（Process）控制,  Next: 匯入模組<2>,  Prev: 系統函式,  Up: 工具<2>

7.6.3 行程（Process）控制
-------------------------

 -- C 函式: void Py_FatalError (const char *message)

     Print a fatal error message and kill the process.  No cleanup is
     performed.  This function should only be invoked when a condition
     is detected that would make it dangerous to continue using the
     Python interpreter; e.g., when the object administration appears to
     be corrupted.  On Unix, the standard C library function ‘abort()’
     is called which will attempt to produce a ‘core’ file.

     The ‘Py_FatalError()’ function is replaced with a macro which logs
     automatically the name of the current function, unless the
     ‘Py_LIMITED_API’ macro is defined.

     3.9 版更變: Log the function name automatically.

 -- C 函式: void Py_Exit (int status)

     Exit the current process.  This calls *note Py_FinalizeEx(): 6c0.
     and then calls the standard C library function ‘exit(status)’.  If
     *note Py_FinalizeEx(): 6c0. indicates an error, the exit status is
     set to 120.

     3.6 版更變: Errors from finalization no longer ignored.

 -- C 函式: int Py_AtExit (void (*func)())

     Register a cleanup function to be called by *note Py_FinalizeEx():
     6c0.  The cleanup function will be called with no arguments and
     should return no value.  At most 32 cleanup functions can be
     registered.  When the registration is successful, *note
     Py_AtExit(): 3e6d. returns ‘0’; on failure, it returns ‘-1’.  The
     cleanup function registered last is called first.  Each cleanup
     function will be called at most once.  Since Python’s internal
     finalization will have completed before the cleanup function, no
     Python APIs should be called by `func'.


File: python.info,  Node: 匯入模組<2>,  Next: 数据 marshal 操作支持,  Prev: 行程（Process）控制,  Up: 工具<2>

7.6.4 匯入模組
--------------

 -- C 函式: PyObject* PyImport_ImportModule (const char *name)
     `Return value: New reference.'

     This is a simplified interface to *note PyImport_ImportModuleEx():
     bf4. below, leaving the `globals' and `locals' arguments set to
     ‘NULL’ and `level' set to 0.  When the `name' argument contains a
     dot (when it specifies a submodule of a package), the `fromlist'
     argument is set to the list ‘['*']’ so that the return value is the
     named module rather than the top-level package containing it as
     would otherwise be the case.  (Unfortunately, this has an
     additional side effect when `name' in fact specifies a subpackage
     instead of a submodule: the submodules specified in the package’s
     ‘__all__’ variable are loaded.)  Return a new reference to the
     imported module, or ‘NULL’ with an exception set on failure.  A
     failing import of a module doesn’t leave the module in *note
     sys.modules: 1051.

     该函数总是使用绝对路径导入。

 -- C 函式: PyObject* PyImport_ImportModuleNoBlock (const char *name)
     `Return value: New reference.' 该函数是 *note
     PyImport_ImportModule(): d3b. 的一个被弃用的别名。

     3.3 版更變: This function used to fail immediately when the import
     lock was held by another thread.  In Python 3.3 though, the locking
     scheme switched to per-module locks for most purposes, so this
     function’s special behaviour isn’t needed anymore.

 -- C 函式: PyObject* PyImport_ImportModuleEx (const char *name,
          PyObject *globals, PyObject *locals, PyObject *fromlist)
     `Return value: New reference.'

     Import a module.  This is best described by referring to the
     built-in Python function *note __import__(): 16b.

     The return value is a new reference to the imported module or
     top-level package, or ‘NULL’ with an exception set on failure.
     Like for *note __import__(): 16b, the return value when a submodule
     of a package was requested is normally the top-level package,
     unless a non-empty `fromlist' was given.

     Failing imports remove incomplete module objects, like with *note
     PyImport_ImportModule(): d3b.

 -- C 函式: PyObject* PyImport_ImportModuleLevelObject (PyObject *name,
          PyObject *globals, PyObject *locals, PyObject *fromlist,
          int level)
     `Return value: New reference.'  Import a module.  This is best
     described by referring to the built-in Python function *note
     __import__(): 16b, as the standard *note __import__(): 16b.
     function calls this function directly.

     The return value is a new reference to the imported module or
     top-level package, or ‘NULL’ with an exception set on failure.
     Like for *note __import__(): 16b, the return value when a submodule
     of a package was requested is normally the top-level package,
     unless a non-empty `fromlist' was given.

     3.3 版新加入.

 -- C 函式: PyObject* PyImport_ImportModuleLevel (const char *name,
          PyObject *globals, PyObject *locals, PyObject *fromlist,
          int level)
     `Return value: New reference.'  Similar to *note
     PyImport_ImportModuleLevelObject(): 3e71, but the name is a UTF-8
     encoded string instead of a Unicode object.

     3.3 版更變: Negative values for `level' are no longer accepted.

 -- C 函式: PyObject* PyImport_Import (PyObject *name)
     `Return value: New reference.'  This is a higher-level interface
     that calls the current "import hook function" (with an explicit
     `level' of 0, meaning absolute import).  It invokes the *note
     __import__(): 16b. function from the ‘__builtins__’ of the current
     globals.  This means that the import is done using whatever import
     hooks are installed in the current environment.

     该函数总是使用绝对路径导入。

 -- C 函式: PyObject* PyImport_ReloadModule (PyObject *m)
     `Return value: New reference.'  Reload a module.  Return a new
     reference to the reloaded module, or ‘NULL’ with an exception set
     on failure (the module still exists in this case).

 -- C 函式: PyObject* PyImport_AddModuleObject (PyObject *name)
     `Return value: Borrowed reference.'  Return the module object
     corresponding to a module name.  The `name' argument may be of the
     form ‘package.module’.  First check the modules dictionary if
     there’s one there, and if not, create a new one and insert it in
     the modules dictionary.  Return ‘NULL’ with an exception set on
     failure.

          備註: This function does not load or import the module; if the
          module wasn’t already loaded, you will get an empty module
          object.  Use *note PyImport_ImportModule(): d3b. or one of its
          variants to import a module.  Package structures implied by a
          dotted name for `name' are not created if not already present.

     3.3 版新加入.

 -- C 函式: PyObject* PyImport_AddModule (const char *name)
     `Return value: Borrowed reference.'  Similar to *note
     PyImport_AddModuleObject(): 3e73, but the name is a UTF-8 encoded
     string instead of a Unicode object.

 -- C 函式: PyObject* PyImport_ExecCodeModule (const char *name,
          PyObject *co)
     `Return value: New reference.'

     Given a module name (possibly of the form ‘package.module’) and a
     code object read from a Python bytecode file or obtained from the
     built-in function *note compile(): 2e7, load the module.  Return a
     new reference to the module object, or ‘NULL’ with an exception set
     if an error occurred.  `name' is removed from *note sys.modules:
     1051. in error cases, even if `name' was already in *note
     sys.modules: 1051. on entry to *note PyImport_ExecCodeModule():
     3e74.  Leaving incompletely initialized modules in *note
     sys.modules: 1051. is dangerous, as imports of such modules have no
     way to know that the module object is an unknown (and probably
     damaged with respect to the module author’s intents) state.

     The module’s *note __spec__: 1603. and *note __loader__: a37. will
     be set, if not set already, with the appropriate values.  The
     spec’s loader will be set to the module’s ‘__loader__’ (if set) and
     to an instance of ‘SourceFileLoader’ otherwise.

     The module’s *note __file__: 1562. attribute will be set to the
     code object’s ‘co_filename’.  If applicable, *note __cached__: c04.
     will also be set.

     This function will reload the module if it was already imported.
     See *note PyImport_ReloadModule(): 3e72. for the intended way to
     reload a module.

     If `name' points to a dotted name of the form ‘package.module’, any
     package structures not already created will still not be created.

     See also *note PyImport_ExecCodeModuleEx(): 3e75. and *note
     PyImport_ExecCodeModuleWithPathnames(): 3e76.

 -- C 函式: PyObject* PyImport_ExecCodeModuleEx (const char *name,
          PyObject *co, const char *pathname)
     `Return value: New reference.'  Like *note
     PyImport_ExecCodeModule(): 3e74, but the *note __file__: 1562.
     attribute of the module object is set to `pathname' if it is
     non-‘NULL’.

     参见 *note PyImport_ExecCodeModuleWithPathnames(): 3e76.。

 -- C 函式: PyObject* PyImport_ExecCodeModuleObject (PyObject *name,
          PyObject *co, PyObject *pathname, PyObject *cpathname)
     `Return value: New reference.'  Like *note
     PyImport_ExecCodeModuleEx(): 3e75, but the *note __cached__: c04.
     attribute of the module object is set to `cpathname' if it is
     non-‘NULL’.  Of the three functions, this is the preferred one to
     use.

     3.3 版新加入.

 -- C 函式: PyObject* PyImport_ExecCodeModuleWithPathnames (const
          char *name, PyObject *co, const char *pathname, const
          char *cpathname)
     `Return value: New reference.'  Like *note
     PyImport_ExecCodeModuleObject(): 3e77, but `name', `pathname' and
     `cpathname' are UTF-8 encoded strings.  Attempts are also made to
     figure out what the value for `pathname' should be from `cpathname'
     if the former is set to ‘NULL’.

     3.2 版新加入.

     3.3 版更變: Uses *note imp.source_from_cache(): 3d01. in
     calculating the source path if only the bytecode path is provided.

 -- C 函式: long PyImport_GetMagicNumber ()

     Return the magic number for Python bytecode files (a.k.a.  ‘.pyc’
     file).  The magic number should be present in the first four bytes
     of the bytecode file, in little-endian byte order.  Returns ‘-1’ on
     error.

     3.3 版更變: 失败时返回值 ‘-1’。

 -- C 函式: const char * PyImport_GetMagicTag ()

     Return the magic tag string for PEP 3147(1) format Python bytecode
     file names.  Keep in mind that the value at
     ‘sys.implementation.cache_tag’ is authoritative and should be used
     instead of this function.

     3.2 版新加入.

 -- C 函式: PyObject* PyImport_GetModuleDict ()
     `Return value: Borrowed reference.'  Return the dictionary used for
     the module administration (a.k.a.  ‘sys.modules’).  Note that this
     is a per-interpreter variable.

 -- C 函式: PyObject* PyImport_GetModule (PyObject *name)
     `Return value: New reference.'  Return the already imported module
     with the given name.  If the module has not been imported yet then
     returns ‘NULL’ but does not set an error.  Returns ‘NULL’ and sets
     an error if the lookup failed.

     3.7 版新加入.

 -- C 函式: PyObject* PyImport_GetImporter (PyObject *path)
     `Return value: New reference.'  Return a finder object for a *note
     sys.path: 261./‘pkg.__path__’ item `path', possibly by fetching it
     from the *note sys.path_importer_cache: 597. dict.  If it wasn’t
     yet cached, traverse *note sys.path_hooks: a3d. until a hook is
     found that can handle the path item.  Return ‘None’ if no hook
     could; this tells our caller that the *note path based finder:
     15fb. could not find a finder for this path item.  Cache the result
     in *note sys.path_importer_cache: 597.  Return a new reference to
     the finder object.

 -- C 函式: int PyImport_ImportFrozenModuleObject (PyObject *name)
     `Return value: New reference.'  Load a frozen module named `name'.
     Return ‘1’ for success, ‘0’ if the module is not found, and ‘-1’
     with an exception set if the initialization failed.  To access the
     imported module on a successful load, use *note
     PyImport_ImportModule(): d3b.  (Note the misnomer — this function
     would reload the module if it was already imported.)

     3.3 版新加入.

     3.4 版更變: The ‘__file__’ attribute is no longer set on the
     module.

 -- C 函式: int PyImport_ImportFrozenModule (const char *name)

     Similar to *note PyImport_ImportFrozenModuleObject(): 3e7b, but the
     name is a UTF-8 encoded string instead of a Unicode object.

 -- C 類型: struct _frozen

     This is the structure type definition for frozen module
     descriptors, as generated by the ‘freeze’ utility (see
     ‘Tools/freeze/’ in the Python source distribution).  Its
     definition, found in ‘Include/import.h’, is:

          struct _frozen {
              const char *name;
              const unsigned char *code;
              int size;
          };

 -- C 變數: const struct _frozen* PyImport_FrozenModules

     该指针被初始化为指向 ‘struct _frozen’ 数组，以 ‘NULL’ 或者 0 作为结
     束标记。当一个冻结模块被导入，首先要在这个表中搜索。第三方库可以以
     此来提供动态创建的冻结模块集合。

 -- C 函式: int PyImport_AppendInittab (const char *name, PyObject*
          (*initfunc)(void))

     Add a single module to the existing table of built-in modules.
     This is a convenience wrapper around *note
     PyImport_ExtendInittab(): f9d, returning ‘-1’ if the table could
     not be extended.  The new module can be imported by the name
     `name', and uses the function `initfunc' as the initialization
     function called on the first attempted import.  This should be
     called before *note Py_Initialize(): 20f.

 -- C 類型: struct _inittab

     Structure describing a single entry in the list of built-in
     modules.  Each of these structures gives the name and
     initialization function for a module built into the interpreter.
     The name is an ASCII encoded string.  Programs which embed Python
     may use an array of these structures in conjunction with *note
     PyImport_ExtendInittab(): f9d. to provide additional built-in
     modules.  The structure is defined in ‘Include/import.h’ as:

          struct _inittab {
              const char *name;           /* ASCII encoded string */
              PyObject* (*initfunc)(void);
          };

 -- C 函式: int PyImport_ExtendInittab (struct _inittab *newtab)

     Add a collection of modules to the table of built-in modules.  The
     `newtab' array must end with a sentinel entry which contains ‘NULL’
     for the ‘name’ field; failure to provide the sentinel value can
     result in a memory fault.  Returns ‘0’ on success or ‘-1’ if
     insufficient memory could be allocated to extend the internal
     table.  In the event of failure, no modules are added to the
     internal table.  This must be called before *note Py_Initialize():
     20f.

     If Python is initialized multiple times, *note
     PyImport_AppendInittab(): f9c. or *note PyImport_ExtendInittab():
     f9d. must be called before each Python initialization.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3147


File: python.info,  Node: 数据 marshal 操作支持,  Next: 语句解释及变量编译,  Prev: 匯入模組<2>,  Up: 工具<2>

7.6.5 数据 marshal 操作支持
---------------------------

这些例程允许 C 代码处理与 *note marshal: b0. 模块所用相同数据格式的序列
化对象。 其中有些函数可用来将数据写入这种序列化格式，另一些函数则可用来
读取并恢复数据。 用于存储 marshal 数据的文件必须以二进制模式打开。

数字值在存储时会将最低位字节放在开头。

此模块支持两种数据格式版本：第 0 版为历史版本，第 1 版本会在文件和
marshal 反序列化中共享固化的字符串。 第 2 版本会对浮点数使用二进制格式。
‘Py_MARSHAL_VERSION’ 指明了当前文件的格式（当前取值为 2）。

 -- C 函式: void PyMarshal_WriteLongToFile (long value, FILE *file,
          int version)

     将一个 ‘long’ 整数 `value' 以 marshal 格式写入 `file'。 这将只写入
     `value' 最低的 32 位；无论本机 ‘long’ 类型的长度如何。 `version' 指
     明文件格式的版本。

 -- C 函式: void PyMarshal_WriteObjectToFile (PyObject *value,
          FILE *file, int version)

     将一个 Python 对象 `value' 以 marshal 格式写入 `file'。 `version' 指
     明文件格式的版本。

 -- C 函式: PyObject* PyMarshal_WriteObjectToString (PyObject *value,
          int version)
     `Return value: New reference.' 返回一个包含 `value' 的 marshal 表示
     形式的字节串对象。 `version' 指明文件格式的版本。

以下函数允许读取并恢复存储为 marshal 格式的值。

 -- C 函式: long PyMarshal_ReadLongFromFile (FILE *file)

     从打开用于读取的 ‘FILE*’ 的对应数据流返回一个 C ‘long’。 使用只函数
     只能读取 32 位的值，无论本机 ‘long’ 类型的长度为何。

     发生错误时，将设置适当的异常 (*note EOFError: d34.) 并返回 ‘-1’。

 -- C 函式: int PyMarshal_ReadShortFromFile (FILE *file)

     从打开用于读取的 ‘FILE*’ 的对应数据流返回一个 C ‘short’。 使用此函
     数只能读取 16 位的值，无论本机 ‘short’ 类型的长度为何。

     发生错误时，将设置适当的异常 (*note EOFError: d34.) 并返回 ‘-1’。

 -- C 函式: PyObject* PyMarshal_ReadObjectFromFile (FILE *file)
     `Return value: New reference.' 从打开用于读取的 ‘FILE*’ 的对应数据
     流返回一个 Python 对象。

     发生错误时，将设置适当的异常 (*note EOFError: d34, *note
     ValueError: 16d. 或 *note TypeError: 1fe.) 并返回 ‘NULL’。

 -- C 函式: PyObject* PyMarshal_ReadLastObjectFromFile (FILE *file)
     `Return value: New reference.' 从打开用于读取的 ‘FILE*’ 的对应数据
     流返回一个 Python 对象。 不同于 *note
     PyMarshal_ReadObjectFromFile(): 3e87.，此函数假定将不再从该文件读取
     更多的对象，允许其将文件数据积极地载入内存，以便反序列化过程可以在
     内存中的数据上操作而不是每次从文件读取一个字节。 只有当你确定不会再
     从文件读取任何内容时方可使用此形式。

     发生错误时，将设置适当的异常 (*note EOFError: d34, *note
     ValueError: 16d. 或 *note TypeError: 1fe.) 并返回 ‘NULL’。

 -- C 函式: PyObject* PyMarshal_ReadObjectFromString (const char *data,
          Py_ssize_t len)
     `Return value: New reference.' 从包含指向 `data' 的 `len' 个字节的
     字节缓冲区对应的数据流返回一个 Python 对象。

     发生错误时，将设置适当的异常 (*note EOFError: d34, *note
     ValueError: 16d. 或 *note TypeError: 1fe.) 并返回 ‘NULL’。


File: python.info,  Node: 语句解释及变量编译,  Next: 字串轉換與格式化,  Prev: 数据 marshal 操作支持,  Up: 工具<2>

7.6.6 语句解释及变量编译
------------------------

这些函数在创建你自己的函数时帮助很大。更多说明以及实例可参考说明文档中的
*note 擴充和嵌入 Python 直譯器: 1332. 小节。

这些函数描述的前三个，*note PyArg_ParseTuple(): 393.，*note
PyArg_ParseTupleAndKeywords(): 6c1.，以及 *note PyArg_Parse(): 10f0.，它
们都使用 `格式化字符串' 来将函数期待的参数告知函数。这些函数都使用相同语
法规则的格式化字符串。

* Menu:

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


File: python.info,  Node: 解析参数<3>,  Next: 创建变量,  Up: 语句解释及变量编译

7.6.6.1 解析参数
................

一个格式化字符串包含 0 或者更多的格式单元。一个格式单元用来描述一个
Python 对象；它通常是一个字符或者由括号括起来的格式单元序列。除了少数例
外，一个非括号序列的格式单元通常对应这些函数的具有单一地址的参数。在接下
来的描述中，双引号内的表达式是格式单元；圆括号 () 内的是对应这个格式单元
的 Python 对象类型；方括号 [] 内的是传递的 C 变量(变量集)类型。

* Menu:

* 字符串和缓存区::
* 數字::
* 其他对象::
* API 函数::


File: python.info,  Node: 字符串和缓存区,  Next: 數字,  Up: 解析参数<3>

7.6.6.2 字符串和缓存区
......................

这些格式允许将对象按照连续的内存块形式进行访问。你没必要提供返回的
unicode 字符或者字节区的原始数据存储。

一般的，当一个表达式设置一个指针指向一个缓冲区，这个缓冲区可以被相应的
Python 对象管理，并且这个缓冲区共享这个对象的生存周期。你不需要人为的释
放任何内存空间。除了这些 ‘es’, ‘es#’, ‘et’ and ‘et#’.

然而，当一个 *note Py_buffer: bee. 结构被赋值，其包含的缓冲区被锁住，所
以调用者在随后使用这个缓冲区，即使在 *note Py_BEGIN_ALLOW_THREADS: 3d43.
块中，可以避免可变数据因为调整大小或者被销毁所带来的风险。因此，`你不得
不调用' *note PyBuffer_Release(): e19. 在你结束数据的处理时(或者在之前任
何中断事件中)

除非另有说明，缓冲区是不会以空终止的。

某些格式需要只读的 *note bytes-like object: 6df.，并设置指针而不是缓冲区
结构。 他们通过检查对象的 *note PyBufferProcs.bf_releasebuffer: 3e8e. 字
段是否为 ‘NULL’ 来发挥作用，该字段不允许为 *note bytearray: 173. 这样的
可变对象。

     備註: 所有 ‘#’ 表达式的变式(‘s#’，‘y#’，等等)，长度参数的类型(整型
     或者 ‘Py_ssize_t’)在包含 ‘Python.h’ 头文件之前由 ‘PY_SSIZE_T_CLEAN’
     宏的定义控制。如果这个宏被定义，长度是一个 ‘Py_ssize_t’ Python 元大
     小类型而不是一个 ‘int’ 整型。在未来的 Python 版本中将会改变，只支持
     ‘Py_ssize_t’ 而放弃支持 ‘int’ 整型。最好一直定义 ‘PY_SSIZE_T_CLEAN’
     这个宏。

‘s’ (*note str: 205.) [const char *]

     将一个 Unicode 对象转换成一个指向字符串的 C 指针。一个指针指向一个
     已经存在的字符串，这个字符串存储的是传如的字符指针变量。C 字符串是
     已空结束的。Python 字符串不能包含嵌入的无效的代码点；如果由，一个
     *note ValueError: 16d. 异常会被引发。Unicode 对象被转化成 ‘'utf-8'’
     编码的 C 字符串。如果转换失败，一个 *note UnicodeError: d03. 异常被
     引发。

          備註: 这个表达式不接受 *note bytes-like objects: 6df.。如果你
          想接受文件系统路径并将它们转化成 C 字符串，建议使用 ‘O&’ 表达
          式配合 *note PyUnicode_FSConverter(): 6c5. 作为 `转化函数'。

     3.5 版更變: 以前，当 Python 字符串中遇到了嵌入的 null 代码点会引发
     *note TypeError: 1fe. 。

‘s*’ (*note str: 205. or *note bytes-like object: 6df.) [Py_buffer]

     这个表达式既接受 Unicode 对象也接受类字节类型对象。它为由调用者提供
     的 *note Py_buffer: bee. 结构赋值。这里结果的 C 字符串可能包含嵌入
     的 NUL 字节。Unicode 对象通过 ‘'utf-8'’ 编码转化成 C 字符串。

‘s#’ (*note str: 205, 只读 *note bytes-like object: 6df.) [const char *, int or ‘Py_ssize_t’]

     像 ‘s*’，除了它不接受易变的对象。结果存储在两个 C 变量中，第一个是
     指向 C 字符串的指针，第二个是它的长度。字符串可能包含嵌入的 null 字
     节。Unicode 对象都被通过 ‘'utf-8'’ 编码转化成 C 字符串。

‘z’ (*note str: 205. or ‘None’) [const char *]

     与 ‘s’ 类似，但 Python 对象也可能为 ‘None’，在这种情况下，C 指针设
     置为 ‘NULL’。

‘z*’ (*note str: 205, *note bytes-like object: 6df. or ‘None’) [Py_buffer]

     与 ‘s*’ 类似，但 Python 对象也可能为 ‘None’，在这种情况下，*note
     Py_buffer: bee. 结构的 ‘buf’ 成员设置为 ‘NULL’。

‘z#’ (*note str: 205, 只读 *note bytes-like object: 6df. 或 ‘None’) [const char *, int 或 ‘Py_ssize_t’]

     与 ‘s#’ 类似，但 Python 对象也可能为 ‘None’，在这种情况下，C 指针设
     置为 ‘NULL’。

‘y’ (read-only *note bytes-like object: 6df.) [const char *]

     这个表达式将一个类字节类型对象转化成一个指向字符串的 C 指针；它不接
     受 Unicode 对象。字节缓存区必须不包含嵌入的 null 字节；如果包含了
     null 字节，会引发一个 *note ValueError: 16d. 异常。

     3.5 版更變: 以前，当字节缓冲区中遇到了嵌入的 null 字节会引发 *note
     TypeError: 1fe. 。

‘y*’ (*note bytes-like object: 6df.) [Py_buffer]

     ‘s*’ 的变式，不接受 Unicode 对象，只接受类字节类型变量。`这是接受二
     进制数据的推荐方法。'

‘y#’ (只读 *note bytes-like object: 6df.) [const char *, int 或 ‘Py_ssize_t’]

     ‘s#’ 的变式，不接受 Unicode 对象，只接受类字节类型变量。

‘S’ (*note bytes: 172.) [PyBytesObject *]

     要求 Python 对象为 *note bytes: 172. 对象，不尝试进行任何转换。 如
     果该对象不为 bytes 对象则会引发 *note TypeError: 1fe.。 C 变量也可
     被声明为 *note PyObject*: 5b4. 类型。

‘Y’ (*note bytearray: 173.) [PyByteArrayObject *]

     要求 Python 对象为 *note bytearray: 173. 对象，不尝试进行任何转换。
     如果该对象不为 *note bytearray: 173. 对象则会引发 *note TypeError:
     1fe.。 C 变量也可被声明为 *note PyObject*: 5b4. 类型。

‘u’ (*note str: 205.) [const Py_UNICODE *]

     将一个 Python Unicode 对象转化成指向一个以空终止的 Unicode 字符缓冲
     区的指针。你必须传入一个 *note Py_UNICODE: bc5. 指针变量的地址，存
     储了一个指向已经存在的 Unicode 缓冲区的指针。请注意一个 *note
     Py_UNICODE: bc5. 类型的字符宽度取决于编译选项(16 位或者 32 位)。
     Python 字符串必须不能包含嵌入的 null 代码点；如果有，引发一个 *note
     ValueError: 16d. 异常。

     3.5 版更變: 以前，当 Python 字符串中遇到了嵌入的 null 代码点会引发
     *note TypeError: 1fe. 。

     Deprecated since version 3.3, will be removed in version 3.12: 这是
     旧版样式 *note Py_UNICODE: bc5. API; 请迁移至 *note
     PyUnicode_AsWideCharString(): 53b.

‘u#’ (*note str: 205.) [const Py_UNICODE *, int 或 ‘Py_ssize_t’]

     ‘u’ 的变式，存储两个 C 变量，第一个指针指向一个 Unicode 数据缓存区
     ，第二个是它的长度。它允许 null 代码点。

     Deprecated since version 3.3, will be removed in version 3.12: 这是
     旧版样式 *note Py_UNICODE: bc5. API; 请迁移至 *note
     PyUnicode_AsWideCharString(): 53b.

‘Z’ (*note str: 205. 或 ‘None’) [const Py_UNICODE *]

     与 ‘u’ 类似，但 Python 对象也可能为 ‘None’，在这种情况下 *note
     Py_UNICODE: bc5. 指针设置为 ‘NULL’。

     Deprecated since version 3.3, will be removed in version 3.12: 这是
     旧版样式 *note Py_UNICODE: bc5. API; 请迁移至 *note
     PyUnicode_AsWideCharString(): 53b.

‘Z#’ (*note str: 205. 或 ‘None’) [const Py_UNICODE *, int 或 ‘Py_ssize_t’]

     与 ‘u#’ 类似，但 Python 对象也可能为 ‘None’，在这种情况下 *note
     Py_UNICODE: bc5. 指针设置为 ‘NULL’。

     Deprecated since version 3.3, will be removed in version 3.12: 这是
     旧版样式 *note Py_UNICODE: bc5. API; 请迁移至 *note
     PyUnicode_AsWideCharString(): 53b.

‘U’ (*note str: 205.) [PyObject *]

     要求 Python 对象为 Unicode 对象，不尝试进行任何转换。 如果该对象不
     为 Unicode 对象则会引发 *note TypeError: 1fe.。 C 变量也可被声明为
     *note PyObject*: 5b4.。

‘w*’ (可读写 *note bytes-like object: 6df.) [Py_buffer]

     这个表达式接受任何实现可读写缓存区接口的对象。它为调用者提供的
     *note Py_buffer: bee. 结构赋值。缓冲区可能存在嵌入的 null 字节。当
     缓冲区使用完后调用者需要调用 *note PyBuffer_Release(): e19.。

‘es’ (*note str: 205.) [const char *encoding, char **buffer]

     ‘s’ 的变式，它将编码后的 Unicode 字符存入字符缓冲区。它只处理没有嵌
     NUL 字节的已编码数据。

     此格式需要两个参数。 第一个仅用作输入，并且必须为 ‘const char*’，它
     指向一个以 NUL 结束的字符串表示的编码格式名称，或者为 ‘NULL’，这表
     示使用 ‘'utf-8'’ 编码格式。 如果为 Python 无法识别的编码格式名称则
     会引发异常。 第二个参数必须为 ‘char**’；它所引用的指针值将被设为带
     有参数文本内容的缓冲区。 文本将以第一个参数所指定的编码格式进行编码
     。

     *note PyArg_ParseTuple(): 393. 会分配一个足够大小的缓冲区，将编码后
     的数据拷贝进这个缓冲区并且设置 `*buffer' 引用这个新分配的内存空间。
     调用者有责任在使用后调用 *note PyMem_Free(): e6e. 去释放已经分配的
     缓冲区。

‘et’ (*note str: 205, *note bytes: 172. or *note bytearray: 173.) [const char *encoding, char **buffer]

     和 ‘es’ 相同，除了不用重编码传入的字符串对象。相反，它假设传入的参
     数是编码后的字符串类型。

‘es#’ (*note str: 205.) [const char *encoding, char **buffer, int 或 ‘Py_ssize_t’ *buffer_length]

     ‘s#’ 的变式，它将已编码的 Unicode 字符存入字符缓冲区。不像 ‘es’ 表
     达式，它允许传入的数据包含 NUL 字符。

     它需要三个参数。 第一个仅用作输入，并且必须为 ‘const char*’，它指向
     一个编码格式名称，形式为以 NUL 结束的字符串或 ‘NULL’，在后一种情况
     下将使用 ‘'utf-8'’ 编码格式。 如果编码格式名称无法被 Python 识别则
     会引发异常。 第二个参数必须为 ‘char**’；它所引用的指针值将被设为带
     有参数文本内容的缓冲区。 文本将以第一个参数所指定的编码格式进行编码
     。 第三个参数必须为指向一个整数的指针；被引用的整数将被设为输出缓冲
     区中的字节数。

     有两种操作方式：

     如果 `*buffer' 指向 ‘NULL’ 指针，则函数将分配所需大小的缓冲区，将编
     码的数据复制到此缓冲区，并设置 `*buffer' 以引用新分配的存储。 呼叫
     者负责调用 *note PyMem_Free(): e6e. 以在使用后释放分配的缓冲区。

     如果 `*buffer' 指向非 ‘NULL’ 指针（已分配的缓冲区），则 *note
     PyArg_ParseTuple(): 393. 将使用此位置作为缓冲区，并将
     `*buffer_length' 的初始值解释为缓冲区大小。 然后，它将将编码的数据
     复制到缓冲区，并终止它。 如果缓冲区不够大，将设置一个 *note
     ValueError: 16d.。

     在这两个例子中，`*buffer_length' 被设置为编码后结尾不为 NUL 的数据
     的长度。

‘et#’ (*note str: 205, *note bytes: 172. 或 *note bytearray: 173.) [const char *encoding, char **buffer, int 或 ‘Py_ssize_t’ *buffer_length]

     和 ‘es#’ 相同，除了不用重编码传入的字符串对象。相反，它假设传入的参
     数是编码后的字符串类型。


File: python.info,  Node: 數字,  Next: 其他对象,  Prev: 字符串和缓存区,  Up: 解析参数<3>

7.6.6.3 數字
............

‘b’ (*note int: 204.) [unsigned char]

     将一个非负的 Python 整型转化成一个无符号的微整型，存储在一个 C
     ‘unsigned char’ 类型中。

‘B’ (*note int: 204.) [unsigned char]

     将一个 Python 整型转化成一个微整型并不检查溢出问题，存储在一个 C
     ‘unsigned char’ 类型中。

‘h’ (*note int: 204.) [short int]

     将一个 Python 整型转化成一个 C ‘short int’ 短整型。

‘H’ (*note int: 204.) [unsigned short int]

     将一个 Python 整型转化成一个 C ‘unsigned short int’ 无符号短整型，
     并不检查溢出问题。

‘i’ (*note int: 204.) [int]

     将一个 Python 整型转化成一个 C ‘int’ 整型。

‘I’ (*note int: 204.) [unsigned int]

     将一个 Python 整型转化成一个 C ‘unsigned int’ 无符号整型，并不检查
     溢出问题。

‘l’ (*note int: 204.) [long int]

     将一个 Python 整型转化成一个 C ‘long int’ 长整型。

‘k’ (*note int: 204.) [unsigned long]

     将一个Python整型转化成一个C ‘unsigned long int’ 无符号长整型，并不
     检查溢出问题。

‘L’ (*note int: 204.) [long long]

     将一个 Python 整型转化成一个 C ‘long long’ 长长整型。

‘K’ (*note int: 204.) [unsigned long long]

     将一个 Python 整型转化成一个 C ‘unsigned long long’ 无符号长长整型
     ，并不检查溢出问题。

‘n’ (*note int: 204.) [Py_ssize_t]

     将一个 Python 整型转化成一个 C ‘Py_ssize_t’ Python 元大小类型。

‘c’ (*note bytes: 172. 或者 *note bytearray: 173. 长度为 1) [char]

     将一个 Python 字节类型，如一个长度为 1 的 *note bytes: 172. 或者
     *note bytearray: 173. 对象，转化成一个 C ‘char’ 字符类型。

     3.3 版更變: 允许 *note bytearray: 173. 类型的对象。

‘C’ (*note str: 205. 长度为 1) [int]

     将一个 Python 字符，如一个长度为 1 的 *note str: 205. 字符串对象，
     转化成一个 C ‘int’ 整型类型。

‘f’ (*note float: 1fd.) [float]

     将一个 Python 浮点数转化成一个 C ‘float’ 浮点数。

‘d’ (*note float: 1fd.) [double]

     将一个Python浮点数转化成一个C ‘double’ 双精度浮点数。

‘D’ (*note complex: 2c1.) [Py_complex]

     将一个 Python 复数类型转化成一个 C *note Py_complex: 3e90. Python 复
     数类型。


File: python.info,  Node: 其他对象,  Next: API 函数,  Prev: 數字,  Up: 解析参数<3>

7.6.6.4 其他对象
................

‘O’ (object) [PyObject *]

     将 Python 对象（不进行任何转换）存储在 C 对象指针中。 因此，C 程序
     接收已传递的实际对象。 对象的引用计数不会增加。 存储的指针不是
     ‘NULL’。

‘O!’ (object) [`typeobject', PyObject *]

     将一个 Python 对象存入一个 C 对象指针。 这类似于 ‘O’，但是接受两个
     C 参数：第一个是 Python 类型对象的地址，第二个是存储对象指针的 C 变
     量 (类型为 *note PyObject*: 5b4.) 的地址。 如果 Python 对象不具有所
     要求的类型，则会引发 *note TypeError: 1fe.。

‘O&’ (object) [`converter', `anything']

     通过一个 `converter' 函数将一个 Python 对象转换为一个 C 变量。 此函
     数接受两个参数：第一个是函数，第二个是 C 变量 (类型任意) 的地址，转
     换为 ‘void *’ 类型。 `converter' 函数将以如下方式被调用:

          status = converter(object, address);

     其中 `object' 是待转换的 Python 对象而 `address' 为传给 *note
     PyArg_Parse*(): 10f0. 函数的 ‘void*’ 参数。 返回的 `status' 应当以
     ‘1’ 代表转换成功而以 ‘0’ 代表转换失败。 当转换失败时，`converter' 函
     数应当引发异常并且会让 `address' 的内容保持未修改状态。

     如果 `converter' 返回 ‘Py_CLEANUP_SUPPORTED’，则如果参数解析最终失
     败，它可能会再次调用该函数，从而使转换器有机会释放已分配的任何内存
     。在第二个调用中，`object' 参数将为 ‘NULL’;因此，该参数将为
     ‘NULL’;因此，该参数将为 ‘NULL’，因此，该参数将为 ‘NULL``（如果值）
     为 ``NULL’ `address' 的值与原始呼叫中的值相同。

     3.1 版更變: ‘Py_CLEANUP_SUPPORTED’ 被添加。

‘p’ (*note bool: 2bd.) [int]

     测试传入的值是否为真(一个布尔判断)并且将结果转化为相对应的 C
     true/false 整型值。如果表达式为真置 ‘1’，假则置 ‘0’。它接受任何合法
     的 Python 值。参见 *note 逻辑值检测: 1718. 获取更多关于 Python 如何
     测试值为真的信息。

     3.3 版新加入.

‘(items)’ (*note tuple: 1a2.) [`matching-items']

     对象必须是 Python 序列，它的长度是 `items' 中格式单元的数量。C 参数
     必须对应 `items' 中每一个独立的格式单元。序列中的格式单元可能有嵌套
     。

传递 "long" 整型(整型的值超过了平台的 ‘LONG_MAX’ 限制)是可能的，然而没有
进行适当的范围检测——当接收字段太小而接收不到值时，最重要的位被静默地截断
(实际上，C 语言会在语义继承的基础上强制类型转换——期望的值可能会发生变化
)。

格式化字符串中还有一些其他的字符具有特殊的涵义。这些可能并不嵌套在圆括号
中。它们是：

‘|’

     表明在 Python 参数列表中剩下的参数都是可选的。C 变量对应的可选参数
     需要初始化为默认值——当一个可选参数没有指定时， *note
     PyArg_ParseTuple(): 393. 不能访问相应的 C 变量(变量集)的内容。

‘$’

     *note PyArg_ParseTupleAndKeywords(): 6c1. only：表明在 Python 参数
     列表中剩下的参数都是强制关键字参数。当前，所有强制关键字参数都必须
     也是可选参数，所以格式化字符串中 ‘|’ 必须一直在 ‘$’ 前面。

     3.3 版新加入.

‘:’

     格式单元的列表结束标志；冒号后的字符串被用来作为错误消息中的函数名
     (*note PyArg_ParseTuple(): 393. 函数引发的“关联值”异常)。

‘;’

     格式单元的列表结束标志；分号后的字符串被用来作为错误消息取代默认的
     错误消息。 ‘:’ 和 ‘;’ 相互排斥。

注意任何由调用者提供的 Python 对象引用是 `借来的' 引用；不要递减它们的引
用计数！

传递给这些函数的附加参数必须是由格式化字符串确定的变量的地址；这些都是用
来存储输入元组的值。有一些情况，如上面的格式单元列表中所描述的，这些参数
作为输入值使用；在这种情况下，它们应该匹配指定的相应的格式单元。

为了转换成功，`arg' 对象必须匹配格式并且格式必须用尽。成功的话，*note
PyArg_Parse*(): 10f0. 函数返回 true，反之它们返回 false 并且引发一个合适
的异常。当 *note PyArg_Parse*(): 10f0. 函数因为某一个格式单元转化失败而
失败时，对应的以及后续的格式单元地址内的变量都不会被使用。


File: python.info,  Node: API 函数,  Prev: 其他对象,  Up: 解析参数<3>

7.6.6.5 API 函数
................

 -- C 函式: int PyArg_ParseTuple (PyObject *args, const char *format,
          ...)

     解析一个函数的参数，表达式中的参数按参数位置顺序存入局部变量中。成
     功返回 true；失败返回 false 并且引发相应的异常。

 -- C 函式: int PyArg_VaParse (PyObject *args, const char *format,
          va_list vargs)

     和 *note PyArg_ParseTuple(): 393. 相同，然而它接受一个 va_list 类型
     的参数而不是可变数量的参数集。

 -- C 函式: int PyArg_ParseTupleAndKeywords (PyObject *args,
          PyObject *kw, const char *format, char *keywords[], ...)

     分析将位置参数和关键字参数同时转换为局部变量的函数的参数。
     `keywords' 参数是关键字参数名称的 ‘NULL’ 终止数组。 空名称表示
     *note positional-only parameters: 3c9.。成功时返回 true;发生故障时
     ，它将返回 false 并引发相应的异常。

     3.6 版更變: 添加了 *note positional-only parameters: 3c9. 的支持。

 -- C 函式: int PyArg_VaParseTupleAndKeywords (PyObject *args,
          PyObject *kw, const char *format, char *keywords[],
          va_list vargs)

     和 *note PyArg_ParseTupleAndKeywords(): 6c1. 相同，然而它接受一个
     va_list类型的参数而不是可变数量的参数集。

 -- C 函式: int PyArg_ValidateKeywordArguments (PyObject *)

     确保字典中的关键字参数都是字符串。这个函数只被使用于 *note
     PyArg_ParseTupleAndKeywords(): 6c1. 不被使用的情况下，后者已经不再
     做这样的检查。

     3.2 版新加入.

 -- C 函式: int PyArg_Parse (PyObject *args, const char *format, ...)

     函数被用来析构“旧类型”函数的参数列表——这些函数使用的 ‘METH_OLDARGS’
     参数解析方法已从 Python 3 中移除。这不被推荐用于新代码的参数解析，
     并且在标准解释器中的大多数代码已被修改，已不再用于该目的。它仍然方
     便于分解其他元组，然而可能因为这个目的被继续使用。

 -- C 函式: int PyArg_UnpackTuple (PyObject *args, const char *name,
          Py_ssize_t min, Py_ssize_t max, ...)

     一个更简单的参数提取方式，它不使用格式字符串来指定参数类型。 使用这
     种方法来提取参数的函数应当在函数或方法表中被声明为 *note
     METH_VARARGS: f0a.。 包含实际参数的元组应当作为 `args' 传入；它必须
     确实是一个元组。 元组的长度必须至少为 `min' 并且不超过 `max'；`min'
     和 `max' 可能相等。 额外的参数必须被传入函数，每个参数必须是一个指
     向 *note PyObject*: 5b4. 变量的指针；它们将以来自 `args' 的值填充；
     它们将包含暂借的引用。 对应于可选参数的变量不会由 `args' 给出的值填
     充；它们将由调用者来初始化。 此函数执行成功时返回真值，如果 `args'
     不是元组或者包含错误数量的元素则返回假值；如果执行失败则将设置一个
     异常。

     这是一个使用此函数的示例，取自 ‘_weakref’ 帮助模块用来弱化引用的源
     代码：

          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;
          }

     这个例子中调用 *note PyArg_UnpackTuple(): f08. 完全等价于调用 *note
     PyArg_ParseTuple(): 393.:

          PyArg_ParseTuple(args, "O|O:ref", &object, &callback)


File: python.info,  Node: 创建变量,  Prev: 解析参数<3>,  Up: 语句解释及变量编译

7.6.6.6 创建变量
................

 -- C 函式: PyObject* Py_BuildValue (const char *format, ...)
     `Return value: New reference.' 基于类似于 *note PyArg_Parse*():
     10f0. 函数系列和一系列值的格式字符串创建新值。 在出现错误时返回值或
     ‘NULL’;如果返回 ‘NULL’，将引发异常。

     *note Py_BuildValue(): 3f0. 并不一直创建一个元组。只有当它的格式化
     字符串包含两个或更多的格式单元才会创建一个元组。如果格式化字符串是
     空，它返回 ‘None’；如果它包含一个格式单元，它返回由格式单元描述的的
     任一对象。用圆括号包裹格式化字符串可以强制它返回一个大小为 0 或者 1
     的元组。

     当内存缓存区的数据以参数形式传递用来构建对象时，如 ‘s’ 和 ‘s#’ 格式
     单元，会拷贝需要的数据。调用者提供的缓冲区从来都不会被由 *note
     Py_BuildValue(): 3f0. 创建的对象来引用。换句话说，如果你的代码调用
     ‘malloc()’ 并且将分配的内存空间传递给 *note Py_BuildValue(): 3f0.，
     你的代码就有责任在 *note Py_BuildValue(): 3f0. 返回时调用 ‘free()’
     。

     在下面的描述中，双引号的表达式使格式单元；圆括号 () 内的是格式单元
     将要返回的 Python 对象类型；方括号 [] 内的是传递的 C 变量(变量集)的
     类型。

     字符例如空格，制表符，冒号和逗号在格式化字符串中会被忽略(但是不包括
     格式单元，如 ‘s#’)。这可以使很长的格式化字符串具有更好的可读性。

     ‘s’ (*note str: 205. 或 ‘None’) [const char *]

          使用 ‘'utf-8'’ 编码将空终止的 C 字符串转换为 Python *note str:
          205. 对象。如果 C 字符串指针为 ‘NULL’，则使用 ‘None’。

     ‘s#’ (*note str: 205. 或 ‘None’) [const char *, int 或 ‘Py_ssize_t’]

          使用 ‘'utf-8'’ 编码将 C 字符串及其长度转换为 Python *note str:
          205. 对象。如果 C 字符串指针为 ‘NULL’，则长度将被忽略，并返回
          ‘None’。

     ‘y’ (*note bytes: 172.) [const char *]

          这将 C 字符串转换为 Python *note bytes: 172. 对象。 如果 C 字
          符串指针为 ‘NULL’，则返回 ‘None’。

     ‘y#’ (*note bytes: 172.) [const char *, int 或 ‘Py_ssize_t’]

          这会将 C 字符串及其长度转换为一个 Python 对象。 如果该 C 字符
          串指针为 ‘NULL’，则返回 ‘None’。

     ‘z’ (*note str: 205. or ‘None’) [const char *]

          和 ‘s’ 一样。

     ‘z#’ (*note str: 205. 或 ‘None’) [const char *, int 或 ‘Py_ssize_t’]

          和 ‘s#’ 一样。

     ‘u’ (*note str: 205.) [const wchar_t *]

          将空终止的 ‘wchar_t’ 的 Unicode （UTF-16 或 UCS-4） 数据缓冲区
          转换为 Python Unicode 对象。 如果 Unicode 缓冲区指针为 ‘NULL’，
          则返回 ‘None’。

     ‘u#’ (*note str: 205.) [const wchar_t *, int 或 ‘Py_ssize_t’]

          将 Unicode （UTF-16 或 UCS-4） 数据缓冲区及其长度转换为 Python
          Unicode 对象。 如果 Unicode 缓冲区指针为 ‘NULL’，则长度将被忽
          略，并返回 ‘None’。

     ‘U’ (*note str: 205. 或 ‘None’) [const char *]

          和 ‘s’ 一样。

     ‘U#’ (*note str: 205. 或 ‘None’) [const char *, int 或 ‘Py_ssize_t’]

          和 ‘s#’ 一样。

     ‘i’ (*note int: 204.) [int]

          将一个 C ‘int’ 整型转化成 Python 整型对象。

     ‘b’ (*note int: 204.) [char]

          将一个 C ‘char’ 字符型转化成 Python 整型对象。

     ‘h’ (*note int: 204.) [short int]

          将一个 C ‘short int’ 短整型转化成 Python 整型对象。

     ‘l’ (*note int: 204.) [long int]

          将一个 C ‘long int’ 长整型转化成 Python 整型对象。

     ‘B’ (*note int: 204.) [unsigned char]

          将一个 C ‘unsigned char’ 无符号字符型转化成 Python 整型对象。

     ‘H’ (*note int: 204.) [unsigned short int]

          将一个 C ‘unsigned long’ 无符号短整型转化成 Python 整型对象。

     ‘I’ (*note int: 204.) [unsigned int]

          将一个 C ‘unsigned long’ 无符号整型转化成 Python 整型对象。

     ‘k’ (*note int: 204.) [unsigned long]

          将一个 C ‘unsigned long’ 无符号长整型转化成 Python 整型对象。

     ‘L’ (*note int: 204.) [long long]

          将一个 C ‘long long’ 长长整形转化成 Python 整形对象。

     ‘K’ (*note int: 204.) [unsigned long long]

          将一个 C ‘unsigned long long’ 无符号长长整型转化成 Python 整型
          对象。

     ‘n’ (*note int: 204.) [Py_ssize_t]

          将一个 C ‘Py_ssize_t’ 类型转化为 Python 整型。

     ‘c’ (*note bytes: 172. 长度为1 ) [char]

          将一个 C ‘int’ 整型代表的字符转化为 Python *note bytes: 172. 长
          度为 1 的字节对象。

     ‘C’ (*note str: 205. 长度为 1) [int]

          将一个 C ‘int’ 整型代表的字符转化为 Python *note str: 205. 长
          度为 1 的字符串对象。

     ‘d’ (*note float: 1fd.) [double]

          将一个 C ‘double’ 双精度浮点数转化为 Python 浮点数类型数字。

     ‘f’ (*note float: 1fd.) [float]

          将一个 C ‘float’ 单精度浮点数转化为 Python 浮点数类型数字。

     ‘D’ (*note complex: 2c1.) [Py_complex *]

          将一个 C *note Py_complex: 3e90. 类型的结构转化为 Python 复数
          类型。

     ‘O’ (object) [PyObject *]

          将 Python 对象传递不变（其引用计数除外，该计数由 1 递增）。 如
          果传入的对象是 ‘NULL’ 指针，则假定这是由于生成参数的调用发现错
          误并设置异常而引起的。因此，*note Py_BuildValue(): 3f0. 将返回
          ‘NULL’，但不会引发异常。 如果尚未引发异常，则设置 *note
          SystemError: 6f2.。

     ‘S’ (object) [PyObject *]

          和 ‘O’ 相同。

     ‘N’ (object) [PyObject *]

          和 ‘O’ 相同，然而它并不增加对象的引用计数。当通过调用参数列表
          中的对象构造器创建对象时很实用。

     ‘O&’ (object) [`converter', `anything']

          通过 `converter' 函数将 `anything' 转换为 Python 对象。 该函数
          调用时会传入 `anything' (应与 ‘void*’ 兼容) 作为参数并且应当返
          回一个“新的”Python 对象，或者当发生错误时返回 ‘NULL’。

     ‘(items)’ (*note tuple: 1a2.) [`matching-items']

          将一个 C 变量序列转换成 Python 元组并保持相同的元素数量。

     ‘[items]’ (*note list: 1f8.) [`相关的元素']

          将一个 C 变量序列转换成 Python 列表并保持相同的元素数量。

     ‘{items}’ (*note dict: 164.) [`相关的元素']

          将一个C变量序列转换成 Python 字典。每一对连续的 C 变量对作为一
          个元素插入字典中，分别作为关键字和值。

     如果格式字符串中出现错误，则设置 *note SystemError: 6f2. 异常并返回
     ‘NULL’。

 -- C 函式: PyObject* Py_VaBuildValue (const char *format,
          va_list vargs)
     `Return value: New reference.' 和 *note Py_BuildValue(): 3f0. 相同
     ，然而它接受一个 va_list 类型的参数而不是可变数量的参数集。


File: python.info,  Node: 字串轉換與格式化,  Next: 反射,  Prev: 语句解释及变量编译,  Up: 工具<2>

7.6.7 字串轉換與格式化
----------------------

數字轉換函數和被格式化的字串輸出。

 -- C 函式: int PyOS_snprintf (char *str, size_t size, const
          char *format, ...)

     根据格式字符串 `format' 和额外参数，输出不超过 `size' 个字节到
     `str'。 参见 Unix 手册页面 ‘snprintf(3)’。

 -- C 函式: int PyOS_vsnprintf (char *str, size_t size, const
          char *format, va_list va)

     根据格式字符串 `format' 和变量参数列表 `va'，输出不超过 `size' 个字
     节到 `str'。 参见 Unix 手册页面 ‘vsnprintf(3)’。

*note PyOS_snprintf(): f0b. 和 *note PyOS_vsnprintf(): f0c. 包装 C 标准
库函数 ‘snprintf()’ 和 ‘vsnprintf()’ 。它们的目的是保证在极端情况下的一
致行为，而标准 C 的函数则不然。

包装器会确保 ‘str[size-1]’ 在返回时始终为 ‘'\0'’。 它们从不写入超过
`size' 个字节 (包括末尾的 ‘'\0'’) 到字符串。 两个函数都要求 ‘str !=
NULL’, ‘size > 0’ 和 ‘format != NULL’。

如果平台没有 ‘vsnprintf()’ 而且缓冲区大小需要避免截断超出 `size' 512 字
节以上，Python 会以一个 *note Py_FatalError(): 266. 来中止。

當回傳值 (`rv') 給這些函數應該被編譯如下：

   * 当 ‘0 <= rv < size’ 时，输出转换即成功并将 `rv' 个字符写入到 `str'
     (不包括末尾 ‘str[rv]’ 位置的 ‘'\0'’ 字节)。

   * 当 ‘rv >= size’ 时，输出转换会被截断并且需要一个具有 ‘rv + 1’ 字节
     的缓冲区才能成功执行。 在此情况下 ‘str[size-1]’ 为 ‘'\0'’。

   * 当 ‘rv < 0’ 时，"会发生不好的事情。" 在此情况下 ‘str[size-1]’ 也为
     ‘'\0'’，但 `str' 的其余部分是未定义的。 错误的确切原因取决于底层平
     台。

以下函数提供与语言环境无关的字符串到数字转换。

 -- C 函式: double PyOS_string_to_double (const char *s, char **endptr,
          PyObject *overflow_exception)

     将字符串 ‘s’ 转换为 ‘double’ 类型，失败时引发Python异常。接受的字符
     串的集合对应于被 Python 的 *note float(): 1fd. 构造函数接受的字符串
     的集合，除了 ‘s’ 必须没有前导或尾随空格。转换必须独立于当前的区域。

     如果 ‘endptr’ 是 ‘NULL’ ，转换整个字符串。引发 *note ValueError:
     16d. 并且 返回 ‘-1.0’ 如果字符串不是浮点数的有效的表达方式。

     如果 ‘endptr’ 不是 ‘NULL’ ，尽可能多的转换字符串并将 ‘*endptr’ 设置
     为指向第一个未转换的字符。如果字符串的初始段不是浮点数的有效的表达
     方式，将 ‘*endptr’ 设置为指向字符串的开头，引发 ValueError 异常，并
     且返回 ‘-1.0’ 。

     如果 ‘s’ 表示一个太大而不能存储在一个浮点数中的值（比方说，
     ‘"1e500"’ 在许多平台上是一个字符串）然后如果 ‘overflow_exception’ 是
     ‘NULL’ 返回 ‘Py_HUGE_VAL’ （用适当的符号）并且不设置任何异常。 在其
     他方面， ‘overflow_exception’ 必须指向一个 Python 异常对象；引发异
     常并返回 ‘-1.0’ 。在这两种情况下，设置 ‘*endptr’ 指向转换值之后的第
     一个字符。

     如果在转换期间发生任何其他错误（比如一个内存不足的错误），设置适当
     的 Python 异常并且返回 ‘-1.0’ 。

     3.1 版新加入.

 -- C 函式: char* PyOS_double_to_string (double val, char format_code,
          int precision, int flags, int *ptype)

     转换 ‘double’ `val' 为一个使用 `format_code'， `precision' 和
     `flags' 的字符串

     `格式码' 必须是以下其中之一, ‘'e'’, ‘'E'’, ‘'f'’, ‘'F'’, ‘'g'’,
     ‘'G'’ 或者 ‘'r'’。对于 ‘'r'’ , 提供的 `精度' 必须是0。‘'r'’ 格式码
     指定了标准函数 *note repr(): 8b9. 格式。

     `flags' 可以为零或者其他值 ‘Py_DTSF_SIGN’, ‘Py_DTSF_ADD_DOT_0’ 或
     ‘Py_DTSF_ALT’ 或其组合：

        * ‘Py_DTSF_SIGN’ 表示总是在返回的字符串前附加一个符号字符，即使
          `val' 为非负数。

        * ‘Py_DTSF_ADD_DOT_0’ 表示确保返回的字符串看起来不像是一个整数。

        * ‘Py_DTSF_ALT’ 表示应用 "替代的" 格式化规则。 相关细节请参阅
          *note PyOS_snprintf(): f0b. ‘'#'’ 定义文档。

     如果 `ptype' 不为 ‘NULL’，则它指向的值将被设为 ‘Py_DTST_FINITE’,
     ‘Py_DTST_INFINITE’ 或 ‘Py_DTST_NAN’ 中的一个，分别表示 `val' 是一个
     有限数字、无限数字或非数字。

     返回值是一个指向包含转换后字符串的 `buffer' 的指针，如果转换失败则
     为 ‘NULL’。 调用方要负责调用 *note PyMem_Free(): e6e. 来释放返回的
     字符串。

     3.1 版新加入.

 -- C 函式: int PyOS_stricmp (const char *s1, const char *s2)

     字符串不区分大小写。该函数几乎与 ‘strcmp()’ 的工作方式相同，只是它
     忽略了大小写。

 -- C 函式: int PyOS_strnicmp (const char *s1, const char *s2,
          Py_ssize_t  size)

     字符串不区分大小写。该函数几乎与 ‘strncmp()’ 的工作方式相同，只是它
     忽略了大小写。


File: python.info,  Node: 反射,  Next: 编解码器注册与支持功能,  Prev: 字串轉換與格式化,  Up: 工具<2>

7.6.8 反射
----------

 -- C 函式: PyObject* PyEval_GetBuiltins (void)
     `Return value: Borrowed reference.' 返回当前执行帧中内置函数的字典
     ，如果当前没有帧正在执行，则返回线程状态的解释器。

 -- C 函式: PyObject* PyEval_GetLocals (void)
     `Return value: Borrowed reference.' 返回当前执行帧中局部变量的字典
     ，如果没有当前执行的帧则返回 ‘NULL’。

 -- C 函式: PyObject* PyEval_GetGlobals (void)
     `Return value: Borrowed reference.' 返回当前执行帧中全局变量的字典
     ，如果没有当前执行的帧则返回 ‘NULL’。

 -- C 函式: PyFrameObject* PyEval_GetFrame (void)
     `Return value: Borrowed reference.' 返回当前线程状态的帧，如果没有
     当前执行的帧则返回 ‘NULL’。

     另请参阅 *note PyThreadState_GetFrame(): 24e.。

 -- C 函式: int PyFrame_GetBack (PyFrameObject *frame)

     获取 `frame' 为下一个外部帧。

     返回一个强引用，如果 `frame' 没有外部帧则返回 ‘NULL’。

     `frame' 必须不为 ‘NULL’。

     3.9 版新加入.

 -- C 函式: int PyFrame_GetCode (PyFrameObject *frame)

     获取 `frame' 的代码。

     返回一个强引用。

     `frame' 必须不为 ‘NULL’。 结果（帧的代码）不能为 ‘NULL’。

     3.9 版新加入.

 -- C 函式: int PyFrame_GetLineNumber (PyFrameObject *frame)

     返回 `frame' 当前正在执行的行号。

     `frame' 必须不为 ‘NULL’。

 -- C 函式: const char* PyEval_GetFuncName (PyObject *func)

     如果 `func' 是函数、类或实例对象，则返回它的名称，否则返回 `func' 的
     类型的名称。

 -- C 函式: const char* PyEval_GetFuncDesc (PyObject *func)

     根据 `func' 的类型返回描述字符串。 返回值包括函数和方法的 "()", "
     constructor", " instance" 和 " object"。 与 *note
     PyEval_GetFuncName(): 3ea5. 的结果连接，结果将是 `func' 的描述。


File: python.info,  Node: 编解码器注册与支持功能,  Prev: 反射,  Up: 工具<2>

7.6.9 编解码器注册与支持功能
----------------------------

 -- C 函式: int PyCodec_Register (PyObject *search_function)

     注册一个新的编解码器搜索函数。

     作为副作用，其尝试加载 ‘encodings’ 包，如果尚未完成，请确保它始终位
     于搜索函数列表的第一位。

 -- C 函式: int PyCodec_KnownEncoding (const char *encoding)

     根据注册的给定 `encoding' 的编解码器是否已存在而返回 ‘1’ 或 ‘0’。此
     函数总能成功。

 -- C 函式: PyObject* PyCodec_Encode (PyObject *object, const
          char *encoding, const char *errors)
     `Return value: New reference.' 泛型编解码器基本编码 API。

     `object' 使用由 `errors' 所定义的错误处理方法传递给定 `encoding' 的
     编码器函数。 `errors' 可以为 ‘NULL’ 表示使用为编码器所定义的默认方
     法。 如果找不到编码器则会引发 *note LookupError: 1790.。

 -- C 函式: PyObject* PyCodec_Decode (PyObject *object, const
          char *encoding, const char *errors)
     `Return value: New reference.' 泛型编解码器基本解码 API。

     `object' 使用由 `errors' 所定义的错误处理方法传递给定 `encoding' 的
     解码器函数。 `errors' 可以为 ‘NULL’ 表示使用为编解码器所定义的默认
     方法。 如果找不到编解码器则会引发 *note LookupError: 1790.。

* Menu:

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


File: python.info,  Node: Codec 查找API,  Next: 用于Unicode编码错误处理程序的注册表API,  Up: 编解码器注册与支持功能

7.6.9.1 Codec 查找API
.....................

在下列函数中，`encoding' 字符串会被查找并转换为小写字母形式，这使得通过
此机制查找编码格式实际上对大小写不敏感。 如果未找到任何编解码器，则将设
置 *note KeyError: 3e9. 并返回 ‘NULL’。

 -- C 函式: PyObject* PyCodec_Encoder (const char *encoding)
     `Return value: New reference.' 为给定的 `encoding' 获取一个编码器函
     数。

 -- C 函式: PyObject* PyCodec_Decoder (const char *encoding)
     `Return value: New reference.' 为给定的 `encoding' 获取一个解码器函
     数。

 -- C 函式: PyObject* PyCodec_IncrementalEncoder (const char *encoding,
          const char *errors)
     `Return value: New reference.' 为给定的 `encoding' 获取一个 *note
     IncrementalEncoder: 196e. 对象。

 -- C 函式: PyObject* PyCodec_IncrementalDecoder (const char *encoding,
          const char *errors)
     `Return value: New reference.' 为给定的 `encoding' 获取一个 *note
     IncrementalDecoder: 196f. 对象。

 -- C 函式: PyObject* PyCodec_StreamReader (const char *encoding,
          PyObject *stream, const char *errors)
     `Return value: New reference.' 为给定的 `encoding' 获取一个 *note
     StreamReader: 1973. 工厂函数。

 -- C 函式: PyObject* PyCodec_StreamWriter (const char *encoding,
          PyObject *stream, const char *errors)
     `Return value: New reference.' 为给定的 `encoding' 获取一个 *note
     StreamWriter: 1972. 工厂函数。


File: python.info,  Node: 用于Unicode编码错误处理程序的注册表API,  Prev: Codec 查找API,  Up: 编解码器注册与支持功能

7.6.9.2 用于Unicode编码错误处理程序的注册表API
..............................................

 -- C 函式: int PyCodec_RegisterError (const char *name,
          PyObject *error)

     在给定的 `name' 之下注册错误处理回调函数 `error'。 该回调函数将在一
     个编解码器遇到无法编码的字符/无法解码的字节数据并且 `name' 被指定为
     encode/decode 函数调用的 error 形参时由该编解码器来调用。

     该回调函数会接受一个 *note UnicodeEncodeError: 32a, *note
     UnicodeDecodeError: 32b. 或 *note UnicodeTranslateError: 185b. 的实
     例作为单独参数，其中包含关于有问题字符或字节序列及其在原始序列的偏
     移量信息（请参阅 *note Unicode 异常对象: 3e2a. 了解提取此信息的函数
     详情）。 该回调函数必须引发给定的异常，或者返回一个包含有问题序列及
     相应替换序列的二元组，以及一个表示偏移量的整数，该整数指明应在什么
     位置上恢复编码/解码操作。

     成功则返回‘‘0‘‘ ，失败则返回‘‘-1‘‘

 -- C 函式: PyObject* PyCodec_LookupError (const char *name)
     `Return value: New reference.' 查找在 `name' 之下注册的错误处理回调
     函数。 作为特例还可以传入 ‘NULL’，在此情况下将返回针对 "strict" 的
     错误处理回调函数。

 -- C 函式: PyObject* PyCodec_StrictErrors (PyObject *exc)
     `Return value: Always NULL.' 引发 `exc' 作为异常。

 -- C 函式: PyObject* PyCodec_IgnoreErrors (PyObject *exc)
     `Return value: New reference.' 忽略 unicode 错误，跳过错误的输入。

 -- C 函式: PyObject* PyCodec_ReplaceErrors (PyObject *exc)
     `Return value: New reference.' 使用 ‘?’ 或 ‘U+FFFD’ 替换 unicode 编
     码错误。

 -- C 函式: PyObject* PyCodec_XMLCharRefReplaceErrors (PyObject *exc)
     `Return value: New reference.' 使用 XML 字符引用替换 unicode 编码错
     误。

 -- C 函式: PyObject* PyCodec_BackslashReplaceErrors (PyObject *exc)
     `Return value: New reference.' 使用反斜杠转义符 (‘\x’, ‘\u’ 和
     ‘\U’) 替换 unicode 编码错误。

 -- C 函式: PyObject* PyCodec_NameReplaceErrors (PyObject *exc)
     `Return value: New reference.' 使用 ‘\N{...}’ 转义符替换 unicode 编
     码错误。

     3.5 版新加入.


File: python.info,  Node: 抽象物件層,  Next: 具体的对象层,  Prev: 工具<2>,  Up: Python/C API 參考手冊

7.7 抽象物件層
==============

本章中的函数与 Python对象交互，无论其类型，或具有广泛类的对象类型（例如
，所有数值类型，或所有序列类型）。当使用对象类型并不适用时，他们会产生一
个 Python 异常。

这些函数是不可能用于未正确初始化的对象的，如一个列表对象被 *note
PyList_New(): 3dca. 创建，但其中的项目没有被设置为一些非‘‘NULL‘‘的值。

* Menu:

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


File: python.info,  Node: 对象协议,  Next: 调用协议,  Up: 抽象物件層

7.7.1 对象协议
--------------

 -- C 變數: PyObject* Py_NotImplemented

     ‘NotImplemented’ 单例，用于标记某个操作没有针对给定类型组合的实现。

 -- C 巨集: Py_RETURN_NOTIMPLEMENTED

     C 函数内部应正确处理 *note Py_NotImplemented: 3ec1. 的返回过程（即
     增加 NotImplemented 的引用计数并返回之）。

 -- C 函式: int PyObject_Print (PyObject *o, FILE *fp, int flags)

     将对象 `o' 写入到文件 `fp'。 出错时返回 ‘-1’ 。 旗标参数被用于启用
     特定的输出选项。 目前唯一支持的选项是 ‘Py_PRINT_RAW’；如果给出该选
     项，则将写入对象的 *note str(): 205. 而不是 *note repr(): 8b9.。

 -- C 函式: int PyObject_HasAttr (PyObject *o, PyObject *attr_name)

     如果 `o' 带有属性 `attr_name'，则返回 ‘1’，否则返回 ‘0’。这相当于
     Python 表达式 ‘hasattr(o, attr_name)’。 此函数总是成功。

     注意，在调用 *note __getattr__(): 42a. 和 *note __getattribute__():
     549. 方法时发生的异常将被抑制。若要获得错误报告，请换用 *note
     PyObject_GetAttr(): 3ec4. 。

 -- C 函式: int PyObject_HasAttrString (PyObject *o, const
          char *attr_name)

     如果 `o' 带有属性 `attr_name'，则返回 ‘1’，否则返回 ‘0’。这相当于
     Python 表达式 ‘hasattr(o, attr_name)’。 此函数总是成功。

     注意，在调用 *note __getattr__(): 42a. 和 *note __getattribute__():
     549. 方法并创建一个临时字符串对象时，异常将被抑制。若要获得错误报告
     ，请换用 *note PyObject_GetAttrString(): 3d38. 。

 -- C 函式: PyObject* PyObject_GetAttr (PyObject *o,
          PyObject *attr_name)
     `Return value: New reference.' 从对象 `o' 中读取名为 `attr_name' 的
     属性。成功返回属性值，失败则返回 ‘NULL’。 这相当于 Python 表达式
     ‘o.attr_name’。

 -- C 函式: PyObject* PyObject_GetAttrString (PyObject *o, const
          char *attr_name)
     `Return value: New reference.' 从对象 `o' 中读取一个名为
     `attr_name' 的属性。成功时返回属性值，失败则返回 ‘NULL’。这相当于
     Python 表达式 ‘o.attr_name’。

 -- C 函式: PyObject* PyObject_GenericGetAttr (PyObject *o,
          PyObject *name)
     `Return value: New reference.' 通用的属性获取函数，用于放入类型对象
     的 ‘tp_getattro’ 槽中。它在类的字典中（位于对象的 MRO 中）查找某个
     描述符，并在对象的 *note __dict__: 5f5. 中查找某个属性。正如 *note
     实现描述器: 5e3. 所述，数据描述符优先于实例属性，而非数据描述符则不
     优先。失败则会触发 *note AttributeError: 4a1. 。

 -- C 函式: int PyObject_SetAttr (PyObject *o, PyObject *attr_name,
          PyObject *v)

     将对象 `o' 中名为 `attr_name' 的属性值设为 `v' 。失败时引发异常并返
     回 ‘-1’；成功时返 回‘‘0‘‘ 。这相当于 Python 语句 ‘o.attr_name = v’。

     如果 `v' 为 ‘NULL’，属性将被删除，但是此功能已被弃用，应改用 *note
     PySequence_DelItem(): 1185. 。

 -- C 函式: int PyObject_SetAttrString (PyObject *o, const
          char *attr_name, PyObject *v)

     将对象 `o' 中名为 `attr_name' 的属性值设为 `v' 。失败时引发异常并返
     回 ‘-1’；成功时返 回‘‘0‘‘ 。这相当于 Python 语句 ‘o.attr_name = v’。

     如果 `v' 为 ‘NULL’，该属性将被删除，但是此功能已被弃用，应改用
     *note PySequence_DelItem(): 1185. 。

 -- C 函式: int PyObject_GenericSetAttr (PyObject *o, PyObject *name,
          PyObject *value)

     通用的属性设置和删除函数，用于放入类型对象的 *note tp_setattro:
     3d7a. 槽。它在类的字典中（位于对象的MRO中）查找数据描述器，如果找到
     ，则将比在实例字典中设置或删除属性优先执行。否则，该属性将在对象的
     *note __dict__: 5f5. 中设置或删除。如果成功将返回 ‘0’，否则将引发
     *note AttributeError: 4a1. 并返回 ‘-1’。

 -- C 函式: int PyObject_DelAttr (PyObject *o, PyObject *attr_name)

     删除对象 `o' 中名为 `attr_name' 的属性。失败时返回 ‘-1’。这相当于
     Python 语句 ‘del o.attr_name’。

 -- C 函式: int PyObject_DelAttrString (PyObject *o, const
          char *attr_name)

     删除对象 `o' 中名为 `attr_name' 的属性。失败时返回 ‘-1’。这相当于
     Python 语句 ‘del o.attr_name’。

 -- C 函式: PyObject* PyObject_GenericGetDict (PyObject *o,
          void *context)
     `Return value: New reference.'  ‘__dict__’ 描述符的获取函数的一种通
     用实现。必要时会创建字典。

     3.3 版新加入.

 -- C 函式: int PyObject_GenericSetDict (PyObject *o, PyObject *value,
          void *context)

     ‘__dict__’ 描述符设置函数的一种通用实现。这里不允许删除字典。

     3.3 版新加入.

 -- C 函式: PyObject* PyObject_RichCompare (PyObject *o1, PyObject *o2,
          int opid)
     `Return value: New reference.' 用 `opid' 指定的操作比较 `o1' 和
     `o2' 的值，必须是 ‘Py_LT’ 、 ‘Py_LE’ 、 ‘Py_EQ’ 、 ‘Py_NE’ 、
     ‘Py_GT’ 或 ‘Py_GE’ 之一，分别对应于‘‘<=‘‘ 、‘==’ 、 ‘!=’ 、‘>’ 或
     ‘>=’。这相当于 Python 表达式 ‘o1 op o2’，其中 ‘op’ 是对应于 `opid'
     的操作符。成功时返回比较值，失败时返回 ‘NULL’。

 -- C 函式: int PyObject_RichCompareBool (PyObject *o1, PyObject *o2,
          int opid)

     用 `opid' 指定的操作比较 `o1' 和 `o2' 的值，必须是 ‘Py_LT’ 、
     ‘Py_LE’ 、 ‘Py_EQ’ 、 ‘Py_NE’ 、 ‘Py_GT’ 或 ‘Py_GE’ 之一，分别对应
     于 ‘<’ 、‘<=’、 ‘==’ 、‘!=’ 、‘>’ 或 ‘>=’。错误时返回 ‘-1’，若结果
     为 false 则返回 ‘0’，否则返回 ‘1’。这相当于 Python 表达式 ‘o1 op
     o2’，其中 ‘op’ 是对应于 `opid' 的操作符。

     備註: 如果 `o1' 和 `o2' 是同一个对象，*note
     PyObject_RichCompareBool(): 109c. 为 ‘Py_EQ’ 则返回 ‘1’ ，为
     ‘Py_NE’ 则返回 ‘0’。

 -- C 函式: PyObject* PyObject_Repr (PyObject *o)
     `Return value: New reference.'

     计算对象 `o' 的字符串形式。 成功时返回字符串，失败时返回 ‘NULL’。 这
     相当于 Python 表达式 ‘repr(o)’。 由内置函数 *note repr(): 8b9. 调用
     。

     3.4 版更變: 该函数现在包含一个调试断言，用以确保不会静默地丢弃活动
     的异常。

 -- C 函式: PyObject* PyObject_ASCII (PyObject *o)
     `Return value: New reference.'

     与 *note PyObject_Repr(): a49. 一样，计算对象 `o' 的字符串形式，但
     在 *note PyObject_Repr(): a49. 返回的字符串中用 ‘\x’、‘\u’ 或 ‘\U’
     转义非 ASCII 字符。这将生成一个类似于 Python 2 中由 *note
     PyObject_Repr(): a49. 返回的字符串。由内置函数 *note ascii(): e11.
     调用。

 -- C 函式: PyObject* PyObject_Str (PyObject *o)
     `Return value: New reference.' 计算对象 `o' 的字符串形式。 成功时返
     回字符串，失败时返回 ‘NULL’。 这相当于 Python 表达式 ‘str(o)’。由内
     置函数 *note str(): 205. 调用，因此也由 *note print(): 971. 函数调
     用。

     3.4 版更變: 该函数现在包含一个调试断言，用以确保不会静默地丢弃活动
     的异常。

 -- C 函式: PyObject* PyObject_Bytes (PyObject *o)
     `Return value: New reference.'

     计算对象 `o' 的字节形式。失败时返回 ‘NULL’，成功时返回一个字节串对
     象。这相当于 `o' 不是整数时的 Python 表达式 ‘bytes(o)’ 。与
     ‘bytes(o)’ 不同的是，当 `o' 是整数而不是初始为 0 的字节串对象时，会
     触发 TypeError。

 -- C 函式: int PyObject_IsSubclass (PyObject *derived, PyObject *cls)

     如果 `derived' 类与 `cls' 类相同或为其派生类，则返回 ‘1’，否则返回
     ‘0’。 如果出错则返回 ‘-1’。

     如果 `cls' 是元组，则会对 `cls' 进行逐项检测。如果至少有一次检测返
     回 ‘1’，结果将为 ‘1’，否则将是 ‘0’。

     正如 PEP 3119(1) 所述，如果 `cls' 带有 *note __subclasscheck__():
     1585. 方法，将会被调用以确定子类的状态。 否则，如果 `derived' 是个
     直接或间接子类，即包含在 ‘cls.__mro__’ 中，那么它就是 `cls' 的一个
     子类。

     通常只有类对象才会被视为类，即 *note type: 6ff. 或派生类的实例。然
     而，对象可以通过拥有 ‘__bases__’ 属性（必须是基类的元组）来覆盖这一
     点。

 -- C 函式: int PyObject_IsInstance (PyObject *inst, PyObject *cls)

     如果 `inst' 是 `cls' 类或其子类的实例，则返回 ‘1’，如果不是则返回
     ‘‘0‘‘。 如果出错则返回 ‘-1’ 并设置一个异常。

     如果 `cls' 是元组，则会对 `cls' 进行逐项检测。如果至少有一次检测返
     回 ‘1’，结果将为 ‘1’，否则将是 ‘0’。

     正如 PEP 3119(2) 所述，如果 `cls' 带有 *note __subclasscheck__():
     1585. 方法，将会被调用以确定子类的状态。 否则，如果 `derived' 是
     `cls' 的子类，那么它就是 `cls' 的一个实例。

     实例 `inst' 可以通过 ‘__class__’ 属性来覆盖其所属类。

     对象 `cls' 可以通过 ‘__bases__’ 属性（必须是基类的元组）来覆盖它是
     否被认作类的状态，及其基类。

 -- C 函式: Py_hash_t PyObject_Hash (PyObject *o)

     计算并返回对象的哈希值 `o'。 失败时返回 ‘-1’。这相当于 Python 表达
     式 ‘hash(o)’。

     3.2 版更變: 现在的返回类型是 Py_hash_t。 这是一个带符号整数，与
     Py_ssize_t 大小相同。

 -- C 函式: Py_hash_t PyObject_HashNotImplemented (PyObject *o)

     设置一个 *note TypeError: 1fe. 表示 ‘type(o)’ 是不可哈希的，并返回
     ‘-1’ 。该函数保存在 ‘tp_hash’ 槽中时会受到特别对待，允许某个类型向
     解释器显式表明它不可散列。

 -- C 函式: int PyObject_IsTrue (PyObject *o)

     如果对象 `o' 被认为是 true，则返回 ‘1’，否则返回 ‘0’。这相当于
     Python 表达式 ‘not not o’。 失败则返回 ‘-1’。

 -- C 函式: int PyObject_Not (PyObject *o)

     如果对象 `o' 被认为是 true，则返回 ‘1’，否则返回 ‘0’。这相当于
     Python 表达式 ‘not not o’。 失败则返回 ‘-1’。

 -- C 函式: PyObject* PyObject_Type (PyObject *o)
     `Return value: New reference.'

     当 `o' 非 ‘NULL’ 时，返回一个与对象 `o' 的类型相对应的类型对象。失
     败时，引发 *note SystemError: 6f2. 并返回 ‘NULL’。这等同于 Python 表
     达式 ‘type(o)’。该函数会增加返回值的引用计数。实际上没有理由不去用
     普通的表达式 ‘o->ob_type’ 而使用该函数，表达式会返回一个类型指针
     *note PyTypeObject*: 3f5. ，除非需要增加引用计数。

 -- C 函式: int PyObject_TypeCheck (PyObject *o, PyTypeObject *type)

     如果对象 `o' 为 `type' 类型或 `type' 的子类型则返回真值。 两个参数
     都必须非 ‘NULL’。

 -- C 函式: Py_ssize_t PyObject_Size (PyObject *o)
 -- C 函式: Py_ssize_t PyObject_Length (PyObject *o)

     返回对象 `o' 的长度。 如果对象 `o' 支持序列和映射协议，则返回序列长
     度。 出错时返回 ‘-1’。这等同于 Python 表达式 ‘len(o)’。

 -- C 函式: Py_ssize_t PyObject_LengthHint (PyObject *o,
          Py_ssize_t defaultvalue)

     返回对象 `o' 的估计长度。首先尝试返回实际长度，然后用 *note
     __length_hint__(): 8f9. 进行估计，最后返回默认值。出错时返回
     ‘‘-1‘‘。这等同于 Python 表达式 ‘operator.length_hint(o,
     defaultvalue)’。

     3.4 版新加入.

 -- C 函式: PyObject* PyObject_GetItem (PyObject *o, PyObject *key)
     `Return value: New reference.' 返回对象 `key' 对应的 `o' 元素，或在
     失败时返回 ‘NULL’。这等同于 Python 表达式 ‘o[key]’。

 -- C 函式: int PyObject_SetItem (PyObject *o, PyObject *key,
          PyObject *v)

     将对象 `key' 映射到值 `v'。 失败时引发异常并返回 ‘-1’；成功时返回
     ‘0’。 这相当于 Python 语句 ‘o[key] = v’。该函数 `不会' 偷取 `v' 的
     引用。

 -- C 函式: int PyObject_DelItem (PyObject *o, PyObject *key)

     从对象 `o' 中移除对象 `key' 的映射。失败时返回 ‘-1’。 这相当于
     Python 语句 ‘del o[key]’。

 -- C 函式: PyObject* PyObject_Dir (PyObject *o)
     `Return value: New reference.' 相当于 Python 表达式 ‘dir(o)’，返回
     一个（可能为空）适合对象参数的字符串列表，如果出错则返回 ‘NULL’。 如
     果参数为 ‘NULL’，类似 Python 的 ‘dir()’，则返回当前 locals 的名字；
     这时如果没有活动的执行框架，则返回 ‘NULL’，但 *note
     PyErr_Occurred(): 3d1e. 将返回 false。

 -- C 函式: PyObject* PyObject_GetIter (PyObject *o)
     `Return value: New reference.' 等同于 Python 表达式 ‘iter(o)’。为对
     象参数返回一个新的迭代器，如果该对象已经是一个迭代器，则返回对象本
     身。如果对象不能被迭代，会引发 *note TypeError: 1fe. ，并返回
     ‘NULL’。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3119

   (2) https://www.python.org/dev/peps/pep-3119


File: python.info,  Node: 调用协议,  Next: 数字协议,  Prev: 对象协议,  Up: 抽象物件層

7.7.2 调用协议
--------------

CPython 支持两种不同的调用协议：`tp_call' 和矢量调用。

* Menu:

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


File: python.info,  Node: tp_call 协议,  Next: Vectorcall 协议,  Up: 调用协议

7.7.2.1 `tp_call' 协议
......................

设置 *note tp_call: 3d86. 的类的实例都是可调用的。 槽位的签名为:

     PyObject *tp_call(PyObject *callable, PyObject *args, PyObject *kwargs);

一个调用是用一个元组表示位置参数，用一个dict表示关键字参数，类似于
Python代码中的‘‘callable(`args, **kwargs)‘‘。*args*必须是非空的（如果没
有参数，会使用一个空元组），但如果没有关键字参数，*kwargs*可以是*NULL'。

这个约定不仅被*tp_call*使用： *note tp_new: 3d57. 和 *note tp_init:
3d5e. 也这样传递参数。

使用 *note PyObject_Call(): 23c. 或其他 *note 调用 API: 3edc. 来调用一个
对象。


File: python.info,  Node: Vectorcall 协议,  Next: 调用对象的 API,  Prev: tp_call 协议,  Up: 调用协议

7.7.2.2 Vectorcall 协议
.......................

3.9 版新加入.

vectorcall 协议是在 PEP 590(1) 被引入的，它是使调用函数更加有效的附加协
议。

作为经验法则，如果可调用程序支持 vectorcall，CPython 会更倾向于内联调用
。 然而，这并不是一个硬性规定。 此外，一些第三方扩展直接使用 `tp_call'
(而不是使用 *note PyObject_Call(): 23c.)。 因此，一个支持 vectorcall 的
类也必须实现 *note tp_call: 3d86.。 此外，无论使用哪种协议，可调对象的行
为都必须是相同的。 推荐的方法是将 *note tp_call: 3d86. 设置为 *note
PyVectorcall_Call(): 3ede.。值得一提的是:

     警告: 一个支持 Vectorcall 的类 `必须' 也实现具有相同语义的 *note
     tp_call: 3d86.。

如果一个类的vectorcall比*tp_call*慢，就不应该实现vectorcall。例如，如果
被调用者需要将参数转换为args 元组和kwargs dict，那么实现vectorcall就没有
意义。

类可以通过启用 *note Py_TPFLAGS_HAVE_VECTORCALL: 3edf. 标志并将 *note
tp_vectorcall_offset: 3ee0. 设置为对象结构中的 `vectorcallfunc' 的
offset 来实现 vectorcall 协议。这是一个指向具有以下签名的函数的指针:

 -- C 類型: PyObject *(*vectorcallfunc) (PyObject *callable, PyObject
          *const *args, size_t nargsf, PyObject *kwnames)

   - `callable' 是指被调用的对象。

   - 
     `args' 是一个C语言数组，由位置参数和后面的

          关键字参数的值。如果没有参数，这个值可以是 `NULL' 。

   - 
     `nargsf' 是位置参数的数量加上可能的

          ‘PY_VECTORCALL_ARGUMENTS_OFFSET’ 标志。 要从 `nargsf' 获得实际
          的位置参数数，请使用 *note PyVectorcall_NARGS(): 3ee2.。

   - 
     `kwnames' 是一包含所有关键字名称的元组。

          换句话说，就是 kwargs 字典的键。 这些名字必须是字符串 (‘str’ 或
          其子类的实例)，并且它们必须是唯一的。 如果没有关键字参数，那么
          `kwnames' 可以用 `NULL' 代替。

 -- C 巨集: PY_VECTORCALL_ARGUMENTS_OFFSET

     如果在 vectorcall 的 `nargsf' 参数中设置了此标志，则允许被调用者临
     时更改 ‘args[-1]’ 的值。换句话说， `args' 指向分配向量中的参数 1（
     不是 0 ）。被调用方必须在返回之前还原 ‘args[-1]’ 的值。

     对于 *note PyObject_VectorcallMethod(): 3ee4. ，这个标志的改变意味
     着‘‘args[0]‘‘ 可能改变了。

     当调用方可以以几乎无代价的方式（无额外的内存申请），那么调用者被推
     荐适用： ‘PY_VECTORCALL_ARGUMENTS_OFFSET’。这样做将允许诸如绑定方法
     之类的可调用函数非常有效地进行向前调用（其中包括一个带前缀的 `self'
     参数）。

要调用一个实现了 vectorcall 的对象，请使用某个 *note call API: 3edc. 函
数，就像其他可调对象一样。 *note PyObject_Vectorcall(): 3ee5. 通常是最有
效的。

     備註: 在 CPython 3.8 中，vectorcall API 和相关的函数暂定以带开头下
     划线的名称提供: ‘_PyObject_Vectorcall’,
     ‘_Py_TPFLAGS_HAVE_VECTORCALL’, ‘_PyObject_VectorcallMethod’,
     ‘_PyVectorcall_Function’, ‘_PyObject_CallOneArg’,
     ‘_PyObject_CallMethodNoArgs’, ‘_PyObject_CallMethodOneArg’。 此外，
     ‘PyObject_VectorcallDict’ 以 ‘_PyObject_FastCallDict’ 的名称提供。
     旧名称仍然被定义为不带下划线的新名称的别名。

* Menu:

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

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0590


File: python.info,  Node: 递归控制<2>,  Next: Vectorcall 支持 API,  Up: Vectorcall 协议

7.7.2.3 递归控制
................

在使用 `tp_call' 时，被调用者不必担心 *note 递归: 3e45.: CPython 对于使
用 `tp_call' 进行的调用会使用 *note Py_EnterRecursiveCall(): 251. 和
*note Py_LeaveRecursiveCall(): 252.。

为保证效率，这不适用于使用 vectorcall 的调用：被调用方在需要时应当使用
`Py_EnterRecursiveCall' 和 `Py_LeaveRecursiveCall'。


File: python.info,  Node: Vectorcall 支持 API,  Prev: 递归控制<2>,  Up: Vectorcall 协议

7.7.2.4 Vectorcall 支持 API
...........................

 -- C 函式: Py_ssize_t PyVectorcall_NARGS (size_t nargsf)

     给定一个 vectorcall `nargsf' 实参，返回参数的实际数量。 目前等同于:

          (Py_ssize_t)(nargsf & ~PY_VECTORCALL_ARGUMENTS_OFFSET)

     然而，应使用 ‘PyVectorcall_NARGS’ 函数以便将来扩展。

     这个函数不是 *note limited API: 3dda. 的一部分。

     3.8 版新加入.

 -- C 函式: vectorcallfunc PyVectorcall_Function (PyObject *op)

     如果*op*不支持vectorcall协议（要么是因为类型不支持，要么是因为具体
     实例不支持），返回*NULL*。否则，返回存储在*op*中的vectorcall函数指
     针。这个函数从不触发异常。

     这在检查 `op' 是否支持 vectorcall 时最有用处，可以通过检查
     ‘PyVectorcall_Function(op) != NULL’ 来实现。

     这个函数不是 *note limited API: 3dda. 的一部分。

     3.8 版新加入.

 -- C 函式: PyObject* PyVectorcall_Call (PyObject *callable,
          PyObject *tuple, PyObject *dict)

     调用*可调对象*的 *note vectorcallfunc: 3ee1.，其位置参数和关键字参
     数分别以元组和dict形式给出。

     这是一个专门函数，其目的是被放入 *note tp_call: 3d86. 槽位或是用于
     ‘tp_call’ 的实现。 它不会检查 *note Py_TPFLAGS_HAVE_VECTORCALL:
     3edf. 旗标并且它不会回退到 ‘tp_call’。

     这个函数不是 *note limited API: 3dda. 的一部分。

     3.8 版新加入.


File: python.info,  Node: 调用对象的 API,  Next: 调用支持 API,  Prev: Vectorcall 协议,  Up: 调用协议

7.7.2.5 调用对象的 API
......................

Various functions are available for calling a Python object.  Each
converts its arguments to a convention supported by the called object –
either `tp_call' or vectorcall.  In order to do as little conversion as
possible, pick one that best fits the format of data you have available.

下表总结了可用的功能； 请参阅各个文档以了解详细信息。

函数                                           可调用对象（           args                     kwargs
                                               Callable）                                      
                                               
-------------------------------------------------------------------------------------------------------------------
                                                                                               
*note PyObject_Call(): 23c.                    ‘PyObject *’           元组                     dict/‘NULL’
                                                                                               
                                                                                               
*note PyObject_CallNoArgs(): 250.              ‘PyObject *’           —                        —
                                                                                               
                                                                                               
*note PyObject_CallOneArg(): 256.              ‘PyObject *’           1个对象                  —
                                                                                               
                                                                                               
*note PyObject_CallObject(): 3d2d.             ‘PyObject *’           元组/‘NULL’              —
                                                                                               
                                                                                               
*note PyObject_CallFunction(): 3f1.            ‘PyObject *’           format                   —
                                                                                               
                                                                                               
*note PyObject_CallMethod(): 3eea.             对象 + ‘char*’         format                   —
                                                                                               
                                                                                               
*note PyObject_CallFunctionObjArgs(): 3eeb.    ‘PyObject *’           可变参数                 —
                                                                                               
                                                                                               
*note PyObject_CallMethodObjArgs(): 1114.      对象 + 名称            可变参数                 —
                                                                                               
                                                                                               
*note PyObject_CallMethodNoArgs(): 3eec.       对象 + 名称            —                        —
                                                                                               
                                                                                               
*note PyObject_CallMethodOneArg(): 3eed.       对象 + 名称            1个对象                  —
                                                                                               
                                                                                               
*note PyObject_Vectorcall(): 3ee5.             ‘PyObject *’           vectorcall               vectorcall
                                                                                               
                                                                                               
*note PyObject_VectorcallDict(): 3eee.         ‘PyObject *’           vectorcall               dict/‘NULL’
                                                                                               
                                                                                               
*note PyObject_VectorcallMethod(): 3ee4.       参数 + 名称            vectorcall               vectorcall
                                                                                               

 -- C 函式: PyObject* PyObject_Call (PyObject *callable, PyObject *args,
          PyObject *kwargs)
     `Return value: New reference.' 调用一个可调用的 Python 对象
     `callable'，附带由元组 `args' 所给出的参数，以及由字典 `kwargs' 所
     给出的关键字参数。

     `args' 必须不为 `NULL'；如果不想要参数请使用一个空元组。 如果不想要
     关键字参数，则 `kwargs' 可以为 `NULL'。

     成功时返回结果，在失败时抛出一个异常并返回 `NULL'。

     这等价于 Python 表达式 ‘callable(*args, **kwargs)’。

 -- C 函式: PyObject* PyObject_CallNoArgs (PyObject *callable)

     调用一个可调用的 Python 对象 `callable' 并不附带任何参数。 这是不带
     参数调用 Python 可调用对象的最有效方式。

     成功时返回结果，在失败时抛出一个异常并返回 `NULL'。

     3.9 版新加入.

 -- C 函式: PyObject* PyObject_CallOneArg (PyObject *callable,
          PyObject *arg)

     调用一个可调用的 Python 对象 `callable' 并附带恰好 1 个位置参数
     `arg' 而没有关键字参数。

     成功时返回结果，在失败时抛出一个异常并返回 `NULL'。

     这个函数不是 *note limited API: 3dda. 的一部分。

     3.9 版新加入.

 -- C 函式: PyObject* PyObject_CallObject (PyObject *callable,
          PyObject *args)
     `Return value: New reference.' 调用一个可调用的 Python 对象
     `callable'，附带由元组 `args' 所给出的参数。 如果不想要传入参数，则
     `args' 可以为 `NULL'。

     成功时返回结果，在失败时抛出一个异常并返回 `NULL'。

     这等价于 Python 表达式 ‘callable(*args)’。

 -- C 函式: PyObject* PyObject_CallFunction (PyObject *callable, const
          char *format, ...)
     `Return value: New reference.' 调用一个可调用的 Python 对象
     `callable'，附带可变数量的 C 参数。 这些 C 参数使用 *note
     Py_BuildValue(): 3f0. 风格的格式化字符串来描述。 format 可以为
     `NULL'，表示没有提供任何参数。

     成功时返回结果，在失败时抛出一个异常并返回 `NULL'。

     这等价于 Python 表达式 ‘callable(*args)’。

     请注意如果你只传入 *note PyObject *: 5b4. 参数，则 *note
     PyObject_CallFunctionObjArgs(): 3eeb. 是更快速的选择。

     3.4 版更變: 这个 `format' 类型已从 ‘char *’ 更改。

 -- C 函式: PyObject* PyObject_CallMethod (PyObject *obj, const
          char *name, const char *format, ...)
     `Return value: New reference.' 调用 `obj' 对象中名为 `name' 的方法
     并附带可变数量的 C 参数。 这些 C 参数由 *note Py_BuildValue(): 3f0.
     格式字符串来描述并应当生成一个元组。

     格式可以为 `NULL' ，表示未提供任何参数。

     成功时返回结果，在失败时抛出一个异常并返回 `NULL'。

     这和Python表达式‘‘obj.name(arg1, arg2, ...)‘‘是一样的。

     请注意如果你只传入 *note PyObject *: 5b4. 参数，则 *note
     PyObject_CallMethodObjArgs(): 1114. 是更快速的选择。

     3.4 版更變: The types of `name' and `format' were changed from
     ‘char *’.

 -- C 函式: PyObject* PyObject_CallFunctionObjArgs (PyObject *callable,
          ...)
     `Return value: New reference.' 调用一个可调用的 Python 对象
     `callable'，附带可变数量的 *note PyObject *: 5b4. 参数。 这些参数是
     以 `NULL' 之后可变数量的形参的形式提供的。

     成功时返回结果，在失败时抛出一个异常并返回 `NULL'。

     这和Python表达式‘‘callable(arg1, arg2, ...)‘‘是一样的。

 -- C 函式: PyObject* PyObject_CallMethodObjArgs (PyObject *obj,
          PyObject *name, ...)
     `Return value: New reference.' 调用 Python 对象 `obj' 中的一个方法
     ，其中方法名称由 `name' 中的 Python 字符串对象给出。 它将附带可变数
     量的 *note PyObject *: 5b4. 参数被调用。 这些参数是以 `NULL' 之后可
     变数量的形参的形式提供的。

     成功时返回结果，在失败时抛出一个异常并返回 `NULL'。

 -- C 函式: PyObject* PyObject_CallMethodNoArgs (PyObject *obj,
          PyObject *name)

     调用 Python 对象 `obj' 中的一个方法并不附带任何参数，其中方法名称由
     `name' 中的 Python 字符串对象给出。

     成功时返回结果，在失败时抛出一个异常并返回 `NULL'。

     这个函数不是 *note limited API: 3dda. 的一部分。

     3.9 版新加入.

 -- C 函式: PyObject* PyObject_CallMethodOneArg (PyObject *obj,
          PyObject *name, PyObject *arg)

     调用Call a method of the Python 对象 `obj' 中的一个方法并附带单个位
     置参数 `arg'，其中方法名称由 `name' 中的 Python 字符串对象给出。

     成功时返回结果，在失败时抛出一个异常并返回 `NULL'。

     这个函数不是 *note limited API: 3dda. 的一部分。

     3.9 版新加入.

 -- C 函式: PyObject* PyObject_Vectorcall (PyObject *callable, PyObject
          *const *args, size_t nargsf, PyObject *kwnames)

     调用一个可调用的 Python 对象 `callable'。 附带的参数与 *note
     vectorcallfunc: 3ee1. 相同。 如果 `callable' 支持 *note vectorcall:
     2b8.，则它会直接调用存放在 `callable' 中的 vectorcall 函数。

     成功时返回结果，在失败时抛出一个异常并返回 `NULL'。

     这个函数不是 *note limited API: 3dda. 的一部分。

     3.9 版新加入.

 -- C 函式: PyObject* PyObject_VectorcallDict (PyObject *callable,
          PyObject *const *args, size_t nargsf, PyObject *kwdict)

     调用 `callable' 并附带与在 *note vectorcall: 2b8. 协议中传入的完全
     相同的位置参数，但会加上以字典 `kwdict' 形式传入的关键字参数。
     `args' 数组将只包含位置参数。

     无论在内部使用哪种协议，都需要进行参数的转换。 因此，此函数应当仅在
     调用方已经拥有作为关键字参数的字典，但没有作为位置参数的元组时才被
     使用。

     这个函数不是 *note limited API: 3dda. 的一部分。

     3.9 版新加入.

 -- C 函式: PyObject* PyObject_VectorcallMethod (PyObject *name,
          PyObject *const *args, size_t nargsf, PyObject *kwnames)

     使用 vectorcall 调用惯例来调用一个方法。 方法的名称以 Python 字符串
     `name' 的形式给出。 调用方法的对象为 `args[0]'，而 `args' 数组从
     `args[1]' 开始的部分则代表调用的参数。 必须传入至少一个位置参数。
     `nargsf' 为包括 `args[0]' 在内的位置参数的数量，如果 ‘args[0]’ 的值
     可能被临时改变则要再加上 ‘PY_VECTORCALL_ARGUMENTS_OFFSET’。 关键字
     参数可以像在 *note PyObject_Vectorcall(): 3ee5. 中一样被传入。

     如果对象具有 *note Py_TPFLAGS_METHOD_DESCRIPTOR: 3eef. 特性，此函数
     将调用调用未绑定的方法对象并附带完整的 `args' vector 作为参数。

     成功时返回结果，在失败时抛出一个异常并返回 `NULL'。

     这个函数不是 *note limited API: 3dda. 的一部分。

     3.9 版新加入.


File: python.info,  Node: 调用支持 API,  Prev: 调用对象的 API,  Up: 调用协议

7.7.2.6 调用支持 API
....................

 -- C 函式: int PyCallable_Check (PyObject *o)

     确定对象 `o' 是可调对象。如果对象是可调对象则返回 ‘1’ ，其他情况返
     回 ‘0’ 。这个函数不会调用失败。


File: python.info,  Node: 数字协议,  Next: 序列协议,  Prev: 调用协议,  Up: 抽象物件層

7.7.3 数字协议
--------------

 -- C 函式: int PyNumber_Check (PyObject *o)

     如果对象 `o' 提供数字的协议，返回真 ‘1’，否则返回假。这个函数不会调
     用失败。

     3.8 版更變: 如果 `o' 是一个索引整数则返回 ‘1’。

 -- C 函式: PyObject* PyNumber_Add (PyObject *o1, PyObject *o2)
     `Return value: New reference.' 返回 `o1' 、`o2' 相加的结果，如果失
     败，返回 ‘NULL’。等价于 Python 表达式 ‘o1 + o2’。

 -- C 函式: PyObject* PyNumber_Subtract (PyObject *o1, PyObject *o2)
     `Return value: New reference.' 返回 `o1' 减去 `o2' 的结果，如果失败
     ，返回 ‘NULL’。等价于 Python 表达式 ‘o1 - o2’。

 -- C 函式: PyObject* PyNumber_Multiply (PyObject *o1, PyObject *o2)
     `Return value: New reference.' 返回 `o1' 、 `o2' 相乘的结果，如果失
     败，返回 ‘NULL’。等价于 Python 表达式 ‘o1 * o2’。

 -- C 函式: PyObject* PyNumber_MatrixMultiply (PyObject *o1,
          PyObject *o2)
     `Return value: New reference.' 返回 `o1' 、`o2' 做矩阵乘法的结果，
     如果失败，返回 ‘NULL’。等价于 Python 表达式 ‘o1 @ o2’。

     3.5 版新加入.

 -- C 函式: PyObject* PyNumber_FloorDivide (PyObject *o1, PyObject *o2)
     `Return value: New reference.' 返回 `o1' 除以 `o2' 的向下取整后的结
     果，如果失败，返回 ‘NULL’。等价于“传统”的整数除法。

 -- C 函式: PyObject* PyNumber_TrueDivide (PyObject *o1, PyObject *o2)
     `Return value: New reference.' 返回 `o1' 除以 `o2' 的一个合理的近似
     值，如果失败，返回 ‘NULL’。结果是近似的，因为二进制浮点数是一个近似
     值，不可能以2为基数来表示出所有实数。这个函数返回两个整数相除得到的
     浮点数。

 -- C 函式: PyObject* PyNumber_Remainder (PyObject *o1, PyObject *o2)
     `Return value: New reference.' 返回 `o1' 除以 `o2' 得到的余数，如果
     失败，返回 ‘NULL’。等价于 Python 表达式 ‘o1 % o2’。

 -- C 函式: PyObject* PyNumber_Divmod (PyObject *o1, PyObject *o2)
     `Return value: New reference.'

     参考内置函数 *note divmod(): 28d.。如果失败，返回 ‘NULL’。等价于
     Python 表达式 ‘divmod(o1, o2)’。

 -- C 函式: PyObject* PyNumber_Power (PyObject *o1, PyObject *o2,
          PyObject *o3)
     `Return value: New reference.'

     请参阅内置函数 *note pow(): 2cf.。 如果失败，返回 ‘NULL’。 等价于
     Python 中的表达式 ‘pow(o1, o2, o3)’，其中 `o3' 是可选的。如果要忽略
     `o3'，则需传入 *note Py_None: 3d23. 作为代替（如果传入 ‘NULL’ 会导
     致非法内存访问）。

 -- C 函式: PyObject* PyNumber_Negative (PyObject *o)
     `Return value: New reference.' 返回 `o' 的负值，如果失败，返回
     ‘NULL’ 。等价于 Python 表达式 ‘-o’。

 -- C 函式: PyObject* PyNumber_Positive (PyObject *o)
     `Return value: New reference.' 返回 `o'，如果失败，返回 ‘NULL’ 。等
     价于 Python 表达式 ‘+o’。

 -- C 函式: PyObject* PyNumber_Absolute (PyObject *o)
     `Return value: New reference.'

     返回 `o' 的绝对值，如果失败，返回 ‘NULL’。等价于 Python 表达式
     ‘abs(o)’。

 -- C 函式: PyObject* PyNumber_Invert (PyObject *o)
     `Return value: New reference.' 返回 `o' 的按位取反后的结果，如果失
     败，返回 ‘NULL’。等价于 Python 表达式 ‘~o’。

 -- C 函式: PyObject* PyNumber_Lshift (PyObject *o1, PyObject *o2)
     `Return value: New reference.' 返回 `o1' 左移 `o2' 个比特后的结果，
     如果失败，返回 ‘NULL’。等价于 Python 表达式 ‘o1 << o2’。

 -- C 函式: PyObject* PyNumber_Rshift (PyObject *o1, PyObject *o2)
     `Return value: New reference.' 返回 `o1' 右移 `o2' 个比特后的结果，
     如果失败，返回 ‘NULL’ 。等价于 Python 表达式 ‘o1 >> o2’。

 -- C 函式: PyObject* PyNumber_And (PyObject *o1, PyObject *o2)
     `Return value: New reference.' 返回 `o1' 和 `o2' “按位与”的结果，如
     果失败，返回 ‘NULL’ 。等价于 Python 表达式 ‘o1 & o2’。

 -- C 函式: PyObject* PyNumber_Xor (PyObject *o1, PyObject *o2)
     `Return value: New reference.' 返回 `o1' 和 `o2' “按位异或”的结果，
     如果失败，返回 ‘NULL’ 。等价于 Python 表达式 ‘o1 ^ o2’。

 -- C 函式: PyObject* PyNumber_Or (PyObject *o1, PyObject *o2)
     `Return value: New reference.' 返回 `o1' 和 `o2' “按位或”的结果，如
     果失败，返回 ‘NULL’ 。等价于 Python 表达式 ‘o1 | o2’。

 -- C 函式: PyObject* PyNumber_InPlaceAdd (PyObject *o1, PyObject *o2)
     `Return value: New reference.' 返回 `o1' 、`o2' 相加的结果，如果失
     败，返回 ‘NULL’。当 `o1' 支持时，这个运算直接使用它储存结果。 等价
     于 Python 语句 ‘o1 += o2’。

 -- C 函式: PyObject* PyNumber_InPlaceSubtract (PyObject *o1,
          PyObject *o2)
     `Return value: New reference.' 返回 `o1' 、`o2' 相减的结果，如果失
     败，返回 ‘NULL’ 。当 `o1' 支持时，这个运算直接使用它储存结果。 等价
     于 Python 语句 ‘o1 -= o2’。

 -- C 函式: PyObject* PyNumber_InPlaceMultiply (PyObject *o1,
          PyObject *o2)
     `Return value: New reference.' 返回 `o1' 、`o2*相乘的结果，如果失败
     ，返回 ‘‘NULL‘‘ 。当 *o1' 支持时，这个运算直接使用它储存结果。 等价
     于 Python 语句 ‘o1 *= o2’。

 -- C 函式: PyObject* PyNumber_InPlaceMatrixMultiply (PyObject *o1,
          PyObject *o2)
     `Return value: New reference.' 返回 `o1' 、`o2' 做矩阵乘法后的结果
     ，如果失败，返回 ‘NULL’ 。当 `o1' 支持时，这个运算直接使用它储存结
     果。 等价于 Python 语句 ‘o1 @= o2’。

     3.5 版新加入.

 -- C 函式: PyObject* PyNumber_InPlaceFloorDivide (PyObject *o1,
          PyObject *o2)
     `Return value: New reference.' 返回 `o1' 除以 `o2' 后向下取整的结果
     ，如果失败，返回 ‘NULL’。当 `o1' 支持时，这个运算直接使用它储存结果
     。 等价于 Python 语句 ‘o1 //= o2’。

 -- C 函式: PyObject* PyNumber_InPlaceTrueDivide (PyObject *o1,
          PyObject *o2)
     `Return value: New reference.' 返回 `o1' 除以 `o2' 的一个合理的近似
     值，如果失败，返回 ‘NULL’。结果是近似的，因为二进制浮点数是一个近似
     值，不可能以2为基数来表示出所有实数。这个函数返回两个整数相除得到的
     浮点数。当 `o1' 支持时，这个运算直接使用它储存结果。

 -- C 函式: PyObject* PyNumber_InPlaceRemainder (PyObject *o1,
          PyObject *o2)
     `Return value: New reference.' 返回 `o1' 除以 `o2' 得到的余数，如果
     失败，返回 ‘NULL’。当 `o1' 支持时，这个运算直接使用它储存结果。 等
     价于 Python 语句 ‘o1 %= o2’。

 -- C 函式: PyObject* PyNumber_InPlacePower (PyObject *o1, PyObject *o2,
          PyObject *o3)
     `Return value: New reference.'

     请参阅内置函数 *note pow(): 2cf.。 如果失败，返回 ‘NULL’。当 `o1' 支
     持时，这个运算直接使用它储存结果。当 `o3' 是 *note Py_None: 3d23. 时
     ，等价于 Python 语句 ‘o1 **= o2’；否则等价于在原来位置储存结果的
     ‘pow(o1, o2, o3)’ 。如果要忽略 `o3'，则需传入 *note Py_None: 3d23.
     （传入 ‘NULL’ 会导致非法内存访问）。

 -- C 函式: PyObject* PyNumber_InPlaceLshift (PyObject *o1,
          PyObject *o2)
     `Return value: New reference.' 返回 `o1' 左移 `o2' 个比特后的结果，
     如果失败，返回 ‘NULL’。当 `o1' 支持时，这个运算直接使用它储存结果。
     等价于 Python 语句 ‘o1 <<= o2’。

 -- C 函式: PyObject* PyNumber_InPlaceRshift (PyObject *o1,
          PyObject *o2)
     `Return value: New reference.' 返回 `o1' 右移 `o2' 个比特后的结果，
     如果失败，返回 ‘NULL’。当 `o1' 支持时，这个运算直接使用它储存结果。
     等价于 Python 语句 ‘o1 >>= o2’。

 -- C 函式: PyObject* PyNumber_InPlaceAnd (PyObject *o1, PyObject *o2)
     `Return value: New reference.' 成功时返回 `o1' 和 `o2' "按位与" 的
     结果，失败时返回 ‘NULL’。 在 `o1' 支持的前提下该操作将 `原地' 执行
     。 等价与 Python 语句 ‘o1 &= o2’。

 -- C 函式: PyObject* PyNumber_InPlaceXor (PyObject *o1, PyObject *o2)
     `Return value: New reference.' 成功时返回 `o1' 和 `o2' "按位异或的
     结果，失败时返回 ‘NULL’。 在 `o1' 支持的前提下该操作将 `原地' 执行
     。 等价与 Python 语句 ‘o1 ^= o2’。

 -- C 函式: PyObject* PyNumber_InPlaceOr (PyObject *o1, PyObject *o2)
     `Return value: New reference.' 成功时返回 `o1' 和 `o2' "按位或" 的
     结果，失败时返回 ‘NULL’。 在 `o1' 支持的前提下该操作将 `原地' 执行
     。 等价于 Python 语句 ‘o1 |= o2’。

 -- C 函式: PyObject* PyNumber_Long (PyObject *o)
     `Return value: New reference.'

     成功时返回 `o' 转换为整数对象后的结果，失败时返回 ‘NULL’。 等价于
     Python 表达式 ‘int(o)’。

 -- C 函式: PyObject* PyNumber_Float (PyObject *o)
     `Return value: New reference.'

     成功时返回 `o' 转换为浮点对象后的结果，失败时返回 ‘NULL’。 等价于
     Python 表达式 ‘float(o)’。

 -- C 函式: PyObject* PyNumber_Index (PyObject *o)
     `Return value: New reference.' 成功时返回 `o' 转换为 Python int 类
     型后的结果，失败时返回 ‘NULL’ 并引发 *note TypeError: 1fe. 异常。

 -- C 函式: PyObject* PyNumber_ToBase (PyObject *n, int base)
     `Return value: New reference.' 返回整数 `n' 转换成以 `base' 为基数
     的字符串后的结果。这个 `base' 参数必须是 2，8，10 或者 16 。对于基
     数 2，8，或 16 ，返回的字符串将分别加上基数标识 ‘'0b'’, ‘'0o'’, or
     ‘'0x'’。如果 `n' 不是 Python 中的整数 `int' 类型，就先通过 *note
     PyNumber_Index(): 3f12. 将它转换成整数类型。

 -- C 函式: Py_ssize_t PyNumber_AsSsize_t (PyObject *o, PyObject *exc)

     如果 `o' 是一个整数类型的解释型，返回 `o' 转换成一个 Py_ssize_t 值
     项后的结果。如果调用失败，返回 ‘-1’ 并引发异常。

     如果 `o' 可以被转换为 Python int 类型但尝试转换为 Py_ssize_t 值则会
     引发 *note OverflowError: a41.，这时 `exc' 参数为将被引发的异常类型
     (通常是 *note IndexError: f36. 或 *note OverflowError: a41.)。 如果
     `exc' 为 ‘NULL’，则异常会被清除并且值会被裁剪为负整数
     ‘PY_SSIZE_T_MIN’ 或正整数 ‘PY_SSIZE_T_MAX’。

 -- C 函式: int PyIndex_Check (PyObject *o)

     如果 `o' 是一个索引整数（存有 nb_index 位置并有 tp_as_number 填入其
     中）则返回 ‘1’，否则返回 ‘0’ 。这个函数不会调用失败。


File: python.info,  Node: 序列协议,  Next: 映射协议,  Prev: 数字协议,  Up: 抽象物件層

7.7.4 序列协议
--------------

 -- C 函式: int PySequence_Check (PyObject *o)

     如果对象提供序列协议，函数返回 ‘1’，否则返回 ‘0’。 请注意它将为具有
     *note __getitem__(): 3a5. 方法的 Python 类返回 ‘1’，除非它们是
     *note dict: 164. 的子类，因为在一般情况下无法确定它所支持键类型。 此
     函数总是会成功执行。

 -- C 函式: Py_ssize_t PySequence_Size (PyObject *o)
 -- C 函式: Py_ssize_t PySequence_Length (PyObject *o)

     到哪里积分返回序列 `o' 中对象的数量，失败时返回 ‘-1’。 这相当于
     Python 表达式 ‘len(o)’。

 -- C 函式: PyObject* PySequence_Concat (PyObject *o1, PyObject *o2)
     `Return value: New reference.' 成功时返回 `o1' 和 `o2' 的拼接，失败
     时返回 ‘NULL’。 这等价于 Python 表达式 ‘o1 + o2’。

 -- C 函式: PyObject* PySequence_Repeat (PyObject *o, Py_ssize_t count)
     `Return value: New reference.' 返回序列对象 `o' 重复 `count' 次的结
     果，失败时返回 ‘NULL’。 这等价于 Python 表达式 ‘o * count’。

 -- C 函式: PyObject* PySequence_InPlaceConcat (PyObject *o1,
          PyObject *o2)
     `Return value: New reference.' 成功时返回 `o1' 和 `o2' 的拼接，失败
     时返回 ‘NULL’。 在 `o1' 支持的情况下操作将 `原地' 完成。 这等价于
     Python 表达式 ‘o1 += o2’。

 -- C 函式: PyObject* PySequence_InPlaceRepeat (PyObject *o,
          Py_ssize_t count)
     `Return value: New reference.'  Return the result of repeating
     sequence object返回序列对象 `o' 重复 `count' 次的结果，失败时返回
     ‘NULL’。 在 `o' 支持的情况下该操作会 `原地' 完成。 这等价于 Python
     表达式 ‘o *= count’。

 -- C 函式: PyObject* PySequence_GetItem (PyObject *o, Py_ssize_t i)
     `Return value: New reference.' 返回 `o' 中的第 `i' 号元素，失败时返
     回 ‘NULL’。 这等价于 Python 表达式 ‘o[i]’。

 -- C 函式: PyObject* PySequence_GetSlice (PyObject *o, Py_ssize_t i1,
          Py_ssize_t i2)
     `Return value: New reference.' 返回序列对象 `o' 的 `i1' 到 `i2' 的
     切片，失败时返回 ‘NULL’。 这等价于 Python 表达式 ‘o[i1:i2]’。

 -- C 函式: int PySequence_SetItem (PyObject *o, Py_ssize_t i,
          PyObject *v)

     将对象 `v' 赋值给 `o' 的第 `i' 号元素。 失败时会引发异常并返回
     ‘-1’；成功时返回 ‘0’。 这相当于 Python 语句 ‘o[i] = v’。 此函数 `不
     会' 改变对 `v' 的引用。

     如果 `v' 为 ‘NULL’，元素将被删除，但是此特性已被弃用，应当改用
     *note PySequence_DelItem(): 1185.。

 -- C 函式: int PySequence_DelItem (PyObject *o, Py_ssize_t i)

     删除对象 `o' 的第 `i' 号元素。 失败时返回 ‘-1’。 这相当于 Python 语
     句 ‘del o[i]’。

 -- C 函式: int PySequence_SetSlice (PyObject *o, Py_ssize_t i1,
          Py_ssize_t i2, PyObject *v)

     将序列对象 `v' 赋值给序列对象 `o' 的从 `i1' 到 `i2' 切片。 这相当于
     Python 语句 ‘o[i1:i2] = v’。

 -- C 函式: int PySequence_DelSlice (PyObject *o, Py_ssize_t i1,
          Py_ssize_t i2)

     删除序列对象 `o' 的从 `i1' 到 `i2' 的切片。 失败时返回 ‘-1’。 这相
     当于 Python 语句 ‘del o[i1:i2]’。

 -- C 函式: Py_ssize_t PySequence_Count (PyObject *o, PyObject *value)

     返回 `value' 在 `o' 中出现的次数，即返回使得 ‘o[key] == value’ 的键
     的数量。 失败时返回 ‘-1’。 这相当于 Python 表达式 ‘o.count(value)’。

 -- C 函式: int PySequence_Contains (PyObject *o, PyObject *value)

     确定 `o' 是否包含 `value'。 如果 `o' 中的某一项等于 `value'，则返回
     ‘1’，否则返回 ‘0’。 出错时，返回 ‘-1’。 这相当于 Python 表达式
     ‘value in o’。

 -- C 函式: Py_ssize_t PySequence_Index (PyObject *o, PyObject *value)

     返回第一个索引*i*,其中 ‘o[i] == value’.出错时,返回“-1”.相当于
     Python的‘‘o.index(value)‘‘表达式.

 -- C 函式: PyObject* PySequence_List (PyObject *o)
     `Return value: New reference.' 返回一个列表对象，其内容与序列或可迭
     代对象 `o' 相同，失败时返回 ‘NULL’。 返回的列表保证是一个新对象。 这
     等价于 Python 表达式 ‘list(o)’。

 -- C 函式: PyObject* PySequence_Tuple (PyObject *o)
     `Return value: New reference.'

     返回一个元组对象，其内容与序列或可迭代对象 `o' 相同，失败时返回
     ‘NULL’。 如果 `o' 为元组，则将返回一个新的引用，在其他情况下将使用
     适当的内容构造一个元组。 这等价于 Python 表达式 ‘tuple(o)’。

 -- C 函式: PyObject* PySequence_Fast (PyObject *o, const char *m)
     `Return value: New reference.' 将序列或可迭代对象 `o' 作为其他
     ‘PySequence_Fast*’ 函数族可用的对象返回。 如果该对象不是序列或可迭
     代对象，则会引发 *note TypeError: 1fe. 并将 `m' 作为消息文本。 失败
     时返回 ‘NULL’。

     ‘PySequence_Fast*’ 函数之所以这样命名，是因为它们会假定 `o' 是一个
     *note PyTupleObject: 3e6a. 或 *note PyListObject: 3f26. 并直接访问
     `o' 的数据字段。

     作为 CPython 的实现细节，如果 `o' 已经是一个序列或列表，它将被直接
     返回。

 -- C 函式: Py_ssize_t PySequence_Fast_GET_SIZE (PyObject *o)

     在 `o' 由 *note PySequence_Fast(): 3f25. 返回且 `o' 不为 ‘NULL’ 的
     情况下返回 `o' 的长度。 也可以通过在 `o' 上调用 *note
     PySequence_Size(): 1182. 来获取大小，但是 *note
     PySequence_Fast_GET_SIZE(): 3f27. 速度更快，因为它可以假定 `o' 为列
     表或元组。

 -- C 函式: PyObject* PySequence_Fast_GET_ITEM (PyObject *o,
          Py_ssize_t i)
     `Return value: Borrowed reference.' 在 `o' 由 *note
     PySequence_Fast(): 3f25. 返回且 `o' 不 ‘NULL’，并且 `i' d在索引范围
     内的情况下返回 `o' 的第 `i' 号元素。

 -- C 函式: PyObject** PySequence_Fast_ITEMS (PyObject *o)

     返回 PyObject 指针的底层数组。 假设 `o' 由 *note PySequence_Fast():
     3f25. 返回且 `o' 不为 ‘NULL’。

     请注意,如果列表调整大小,重新分配可能会重新定位items数组.因此,仅在序
     列无法更改的上下文中使用基础数组指针.

 -- C 函式: PyObject* PySequence_ITEM (PyObject *o, Py_ssize_t i)
     `Return value: New reference.' 返回 `o' 的第 `i' 个元素或在失败时返
     回 ‘NULL’。 此形式比 *note PySequence_GetItem(): 1183. 理馔，但不会
     检查 `o' 上的 *note PySequence_Check(): 3f17. 是否为真值，也不会对
     负序号进行调整。


File: python.info,  Node: 映射协议,  Next: 迭代器协议,  Prev: 序列协议,  Up: 抽象物件層

7.7.5 映射协议
--------------

参见 *note PyObject_GetItem(): 3dcb.、*note PyObject_SetItem(): 3dc9. 与
*note PyObject_DelItem(): 3ed6.。

 -- C 函式: int PyMapping_Check (PyObject *o)

     如果对象提供映射协议或支持切片则返回 ‘1’，否则返回 ‘0’。 请注意它将
     为具有 *note __getitem__(): 3a5. 方法的 Python 类返回 ‘1’，因为在一
     般情况下无法确定它所支持的键类型。 此函数总是会成功执行。

 -- C 函式: Py_ssize_t PyMapping_Size (PyObject *o)
 -- C 函式: Py_ssize_t PyMapping_Length (PyObject *o)

     成功时返回对象 `o' 中键的数量，失败时返回 ‘-1’。 这相当于 Python 表
     达式 ‘len(o)’。

 -- C 函式: PyObject* PyMapping_GetItemString (PyObject *o, const
          char *key)
     `Return value: New reference.' 返回 `o' 中对应于字符串 `key' 的元素
     ，或者失败时返回 ‘NULL’。 这相当于 Python 表达式 ‘o[key]’。 另请参
     见 also *note PyObject_GetItem(): 3dcb.。

 -- C 函式: int PyMapping_SetItemString (PyObject *o, const char *key,
          PyObject *v)

     在对象 `o' 中将字符串 `key' 映射到值 `v'。 失败时返回 ‘-1’。 这相当
     于 Python 语句 ‘o[key] = v’。 另请参见 *note PyObject_SetItem():
     3dc9.。 此函数 `不会' 增加对 `v' 的引用。

 -- C 函式: int PyMapping_DelItem (PyObject *o, PyObject *key)

     从对象 `o' 中移除对象 `key' 的映射。 失败时返回 ‘-1’。 这相当于
     Python 语句 ‘del o[key]’。 这是 *note PyObject_DelItem(): 3ed6. 的
     一个别名。

 -- C 函式: int PyMapping_DelItemString (PyObject *o, const char *key)

     从对象 `o' 中移除字符串 `key' 的映射。 失败时返回 ‘-1’。 这相当于
     Python 语句 ‘del o[key]’。

 -- C 函式: int PyMapping_HasKey (PyObject *o, PyObject *key)

     如果映射对象具有键 `key' 则返回 ‘1’，否则返回 ‘0’。 这相当于 Python
     表达式 ‘key in o’。 此函数总是会成功执行。

     请注意在调用 *note __getitem__(): 3a5. 方法期间发生的异常将会被屏蔽
     。 要获取错误报告请改用 *note PyObject_GetItem(): 3dcb.。

 -- C 函式: int PyMapping_HasKeyString (PyObject *o, const char *key)

     如果映射对象具有键 `key' 则返回 ‘1’，否则返回 ‘0’。 这相当于 Python
     表达式 ‘key in o’。 此函数总是会成功执行。

     请注意在调用 *note __getitem__(): 3a5. 方法期间发生的异常将会被屏蔽
     。 要获取错误报告请改用 *note PyMapping_GetItemString(): 3f30.。

 -- C 函式: PyObject* PyMapping_Keys (PyObject *o)
     `Return value: New reference.' 成功时，返回对象 `o' 中的键的列表。
     失败时，返回 ‘NULL’。

     3.7 版更變: 在之前版本中，此函数返回一个列表或元组。

 -- C 函式: PyObject* PyMapping_Values (PyObject *o)
     `Return value: New reference.' 成功时，返回对象 `o' 中的值的列表。
     失败时，返回 ‘NULL’。

     3.7 版更變: 在之前版本中，此函数返回一个列表或元组。

 -- C 函式: PyObject* PyMapping_Items (PyObject *o)
     `Return value: New reference.' 成功时，返回对象 `o' 中条目的列表，
     其中每个条目是一个包含键值对的元组。 失败时，返回 ‘NULL’。

     3.7 版更變: 在之前版本中，此函数返回一个列表或元组。


File: python.info,  Node: 迭代器协议,  Next: 缓冲协议,  Prev: 映射协议,  Up: 抽象物件層

7.7.6 迭代器协议
----------------

迭代器有两个函数。

 -- C 函式: int PyIter_Check (PyObject *o)

     如果对象 `o' 支持迭代器协议则返回真值。 此函数总是会成功执行。

 -- C 函式: PyObject* PyIter_Next (PyObject *o)
     `Return value: New reference.' 返回迭代 `o' 的下一个值。 对象必须是
     一个迭代器（这应由调用者来判断）。 如果没有余下的值，则返回 ‘NULL’
     并且不设置异常。 如果在获取条目时发生了错误，则返回 ‘NULL’ 并且传递
     异常。

要为迭代器编写一个一个循环，C代码应该看起来像这样

     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 */
     }


File: python.info,  Node: 缓冲协议,  Next: 旧缓冲协议,  Prev: 迭代器协议,  Up: 抽象物件層

7.7.7 缓冲协议
--------------

在 Python 中可使用一些对象来包装对底层内存数组或称 `缓冲' 的访问。此类对
象包括内置的 *note bytes: 172. 和 *note bytearray: 173. 以及一些如 *note
array.array: 216. 这样的扩展类型。第三方库也可能会为了特殊的目的而定义它
们自己的类型，例如用于图像处理和数值分析等。

虽然这些类型中的每一种都有自己的语义，但它们具有由可能较大的内存缓冲区支
持的共同特征。 在某些情况下，希望直接访问该缓冲区而无需中间复制。

Python 以 *note 缓冲协议: 171c. 的形式在 C 层级上提供这样的功能。 此协议
包括两个方面:

   - 在生产者这一方面，该类型的协议可以导出一个“缓冲区接口”，允许公开它
     的底层缓冲区信息。该接口的描述信息在 *note Buffer Object
     Structures: 3f3c. 一节中；

   - 在消费者一侧，有几种方法可用于获得指向对象的原始底层数据的指针（例
     如一个方法的形参）。

一些简单的对象例如 *note bytes: 172. 和 *note bytearray: 173. 会以面向字
节的形式公开它们的底层缓冲区。 也可能会用其他形式；例如 *note
array.array: 216. 所公开的元素可以是多字节值。

缓冲区接口的消费者的一个例子是文件对象的 *note write(): 680. 方法：任何
可以输出为一系列字节流的对象可以被写入文件。然而 ‘write()’ 方法只需要对
于传入对象的只读权限，其他的方法，如 *note readinto(): 2150. 需要参数内
容的写入权限。缓冲区接口使得对象可以选择性地允许或拒绝读写或只读缓冲区的
导出。

对于缓冲接口的消费者而言，有两种方式来获取一个目的对象的缓冲：

   * 使用正确的参数来调用 *note PyObject_GetBuffer(): deb. 函数；

   * 调用 *note PyArg_ParseTuple(): 393. (或其同级对象之一) 并传入 ‘y*’,
     ‘w*’ or ‘s*’ *note 格式代码: 3f2. 中的一个。

在这两种情况下，当不再需要缓冲区时必须调用 *note PyBuffer_Release():
e19. 。如果此操作失败，可能会导致各种问题，例如资源泄漏。

* Menu:

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


File: python.info,  Node: 缓冲区结构,  Next: 缓冲区请求的类型,  Up: 缓冲协议

7.7.7.1 缓冲区结构
..................

缓冲区结构(或者简单地称为“buffers”)对于将二进制数据从另一个对象公开给
Python 程序员非常有用。它们还可以用作零拷贝切片机制。使用它们引用内存块
的能力，可以很容易地将任何数据公开给 Python 程序员。内存可以是 C 扩展中
的一个大的常量数组，也可以是在传递到操作系统库之前用于操作的原始内存块，
或者可以用来传递本机内存格式的结构化数据。

与 Python 解释器公开的大多部数据类型不同，缓冲区不是 *note PyObject:
5b4. 指针而是简单的 C 结构。 这使得它们可以非常简单地创建和复制。 当需要
为缓冲区加上泛型包装器时，可以创建一个 *note 内存视图: 3f3f. 对象。

有关如何编写并导出对象的简短说明，请参阅 *note 缓冲区对象结构: 3f3c.。 要
获取缓冲区对象，请参阅 *note PyObject_GetBuffer(): deb.。

 -- C 類型: Py_buffer

      -- C 成員函數: void *buf

          指向由缓冲区字段描述的逻辑结构开始的指针。 这可以是导出程序底
          层物理内存块中的任何位置。 例如，使用负的 *note strides: 3f41.
          值可能指向内存块的末尾。

          对于 *note contiguous: 17ec. ，‘邻接’数组，值指向内存块的开头
          。

      -- C 成員函數: void *obj

          对导出对象的新引用。 该引用归使用者所有，并由 *note
          PyBuffer_Release(): e19. 自动递减并设置为 ‘NULL’。 该字段等于
          任何标准 C-API 函数的返回值。

          作为一种特殊情况，对于由 *note PyMemoryView_FromBuffer():
          3f43. 或 *note PyBuffer_FillInfo(): 3f44. 包装的 `temporary' 缓
          冲区，此字段为 ‘NULL’。 通常，导出对象不得使用此方案。

      -- C 成員函數: Py_ssize_t len

          ‘product(shape) * itemsize’。对于连续数组，这是基础内存块的长
          度。对于非连续数组，如果逻辑结构复制到连续表示形式，则该长度将
          具有该长度。

          仅当缓冲区是通过保证连续性的请求获取时，才访问 ‘((char
          *)buf)[0] up to ((char *)buf)[len-1]’ 时才有效。在大多数情况下
          ，此类请求将为 *note PyBUF_SIMPLE: 3f46. 或 *note
          PyBUF_WRITABLE: 3f47.。

      -- C 成員函數: int readonly

          缓冲区是否为只读的指示器。此字段由 *note PyBUF_WRITABLE: 3f47.
          标志控制。

      -- C 成員函數: Py_ssize_t itemsize

          单个元素的项大小（以字节为单位）。与 *note struct.calcsize():
          10c5. 调用非 ‘NULL’ *note format: 3f4a. 的值相同。

          重要例外：如果使用者请求的缓冲区没有 *note PyBUF_FORMAT: 3f4b.
          标志，*note format: 3f4a. 将设置为 ‘NULL’，但 *note itemsize:
          3f49. 仍具有原始格式的值。

          如果 *note shape: 3f4c. 存在，则相等的 ‘product(shape) *
          itemsize == len’ 仍然存在，使用者可以使用 *note itemsize:
          3f49. 来导航缓冲区。

          如果 *note shape: 3f4c. 是 ‘NULL’，因为结果为 *note
          PyBUF_SIMPLE: 3f46. 或 *note PyBUF_WRITABLE: 3f47. 请求，则使
          用者必须忽略 *note itemsize: 3f49.，并假设 ‘itemsize == 1’。

      -- C 成員函數: const char *format

          在 *note struct: f8. 模块样式语法中 `NUL' 字符串，描述单个项的
          内容。如果这是 ‘NULL’，则假定为‘‘"B"‘‘ (无符号字节) 。

          此字段由 *note PyBUF_FORMAT: 3f4b. 标志控制。

      -- C 成員函數: int ndim

          内存表示为 n 维数组的维数。 如果是‘‘0‘‘， *note buf: 3f40. 指
          向表示标量的单个项目。 在这种情况下，*note shape: 3f4c.、*note
          strides: 3f41. 和 *note suboffsets: 3f4e. 必须是‘‘NULL‘‘ 。

          宏 ‘PyBUF_MAX_NDIM’ 将最大维度数限制为 64。 导出程序必须遵守这
          个限制，多维缓冲区的使用者应该能够处理最多 ‘PyBUF_MAX_NDIM’ 维
          度。

      -- C 成員函數: Py_ssize_t *shape

          一个长度为 ‘Py_ssize_t’ 的数组 *note ndim: 3f4d. 表示作为 n 维
          数组的内存形状。 请注意，‘shape[0] * ... * shape[ndim-1] *
          itemsize’ 必须等于 *note len: 3f45.。

          Shape 形状数组中的值被限定在 ‘shape[n] >= 0’ 。 ‘shape[n] ==
          0’ 这一情形需要特别注意。更多信息请参阅 *note complex arrays:
          3f4f. 。

          shape 数组对于使用者来说是只读的。

      -- C 成員函數: Py_ssize_t *strides

          一个长度为 ‘Py_ssize_t’ 的数组 *note ndim: 3f4d. 给出要跳过的
          字节数以获取每个尺寸中的新元素。

          Stride 步幅数组中的值可以为任何整数。对于常规数组，步幅通常为
          正数，但是使用者必须能够处理 ‘strides[n] <= 0’ 的情况。更多信
          息请参阅 *note complex arrays: 3f4f. 。

          strides数组对用户来说是只读的。

      -- C 成員函數: Py_ssize_t *suboffsets

          一个长度为 *note ndim: 3f4d. 类型为 ‘Py_ssize_t’ 的数组 。如果
          ‘suboffsets[n] >= 0’，则第 n 维存储的是指针，suboffset 值决定
          了解除引用时要给指针增加多少字节的偏移。suboffset 为负值，则表
          示不应解除引用（在连续内存块中移动）。

          如果所有子偏移均为负（即无需取消引用），则此字段必须为 ‘NULL’
          （默认值）。

          Python Imaging Library (PIL) 中使用了这种类型的数组表达方式。
          请参阅 *note complex arrays: 3f4f. 来了解如何从这样一个数组中
          访问元素。

          suboffsets 数组对于使用者来说是只读的。

      -- C 成員函數: void *internal

          供输出对象内部使用。比如可能被导出器重组为一个整数，用于存储一
          个标志，标明在缓冲区释放时是否必须释放 shape、strides 和
          suboffsets 数组。缓冲区用户 `不得' 修改该值。


File: python.info,  Node: 缓冲区请求的类型,  Next: 复杂数组,  Prev: 缓冲区结构,  Up: 缓冲协议

7.7.7.2 缓冲区请求的类型
........................

通常，通过 *note PyObject_GetBuffer(): deb. 向输出对象发送缓冲区请求，即
可获得缓冲区。由于内存的逻辑结构复杂，可能会有很大差异，缓冲区使用者可用
`flags' 参数指定其能够处理的缓冲区具体类型。

所有 *note Py_buffer: bee. 字段均由请求类型明确定义。

* Menu:

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


File: python.info,  Node: 与请求无关的字段,  Next: 只读，格式,  Up: 缓冲区请求的类型

7.7.7.3 与请求无关的字段
........................

以下字段不会被 `flags' 影响，并且必须总是用正确的值填充：*note obj:
3f42, *note buf: 3f40.，*note len: 3f45.，*note itemsize: 3f49.，*note
ndim: 3f4d.。


File: python.info,  Node: 只读，格式,  Next: 形状，步幅，子偏移量,  Prev: 与请求无关的字段,  Up: 缓冲区请求的类型

7.7.7.4 只读，格式
..................

      -- C 巨集: PyBUF_WRITABLE

          控制 *note readonly: 3f48. 字段。如果设置了，输出程序 `必须' 提
          供一个可写的缓冲区，否则报告失败。若未设置，输出程序 `可以' 提
          供只读或可写的缓冲区，但对所有消费者程序 `必须' 保持一致。

      -- C 巨集: PyBUF_FORMAT

          控制 *note format: 3f4a. 字段。 如果设置，则必须正确填写此字段
          。其他情况下，此字段必须为‘‘NULL‘‘。

*note PyBUF_WRITABLE: 3f47. 可以和下一节的所有标志联用。由于 *note
PyBUF_SIMPLE: 3f46. 定义为 0，所以 *note PyBUF_WRITABLE: 3f47. 可以作为
一个独立的标志，用于请求一个简单的可写缓冲区。

*note PyBUF_FORMAT: 3f4b. 可以被设为除了 *note PyBUF_SIMPLE: 3f46. 之外
的任何标志。 后者已经按暗示了‘‘B‘‘(无符号字节串)格式。


File: python.info,  Node: 形状，步幅，子偏移量,  Next: 连续性的请求,  Prev: 只读，格式,  Up: 缓冲区请求的类型

7.7.7.5 形状，步幅，子偏移量
............................

控制内存逻辑结构的标志按照复杂度的递减顺序列出。注意，每个标志包含它下面
的所有标志。

请求                              形状        步幅          子偏移量
                                                            
-----------------------------------------------------------------------------
                                                            
 -- C 巨集: PyBUF_INDIRECT        是          是            如果需要的话
                                                            
                                                            
 -- C 巨集: PyBUF_STRIDES         是          是            NULL
                                                            
                                                            
 -- C 巨集: PyBUF_ND              是          NULL          NULL
                                                            
                                                            
 -- C 巨集: PyBUF_SIMPLE          NULL        NULL          NULL
                                                            


File: python.info,  Node: 连续性的请求,  Next: 复合请求,  Prev: 形状，步幅，子偏移量,  Up: 缓冲区请求的类型

7.7.7.6 连续性的请求
....................

可以显式地请求C 或 Fortran *note 连续: 17ec. ，不管有没有步幅信息。若没
有步幅信息，则缓冲区必须是 C-连续的。

请求                                    形状        步幅          子偏移量         邻接
                                                                                   
------------------------------------------------------------------------------------------------
                                                                                   
 -- C 巨集: PyBUF_C_CONTIGUOUS          是          是            NULL             C
                                                                                   
                                                                                   
 -- C 巨集: PyBUF_F_CONTIGUOUS          是          是            NULL             F
                                                                                   
                                                                                   
 -- C 巨集: PyBUF_ANY_CONTIGUOUS        是          是            NULL             C 或 F
                                                                                   
                                                                                   
*note PyBUF_ND: 3f58.                   是          NULL          NULL             C
                                                                                   


File: python.info,  Node: 复合请求,  Prev: 连续性的请求,  Up: 缓冲区请求的类型

7.7.7.7 复合请求
................

所有可能的请求都由上一节中某些标志的组合完全定义。为方便起见，缓冲区协议
提供常用的组合作为单个标志。

在下表中，`U' 代表连续性未定义。消费者程序必须调用 *note
PyBuffer_IsContiguous(): 3f5e. 以确定连续性。

请求                                形状        步幅          子偏移量         邻接         只读           格式
                                                                                                           
------------------------------------------------------------------------------------------------------------------------
                                                                                                           
 -- C 巨集: PyBUF_FULL              是          是            如果需要的话     U            0              是
                                                                                                           
                                                                                                           
 -- C 巨集: PyBUF_FULL_RO           是          是            如果需要的话     U            1 或 0         是
                                                                                                           
                                                                                                           
 -- C 巨集: PyBUF_RECORDS           是          是            NULL             U            0              是
                                                                                                           
                                                                                                           
 -- C 巨集: PyBUF_RECORDS_RO        是          是            NULL             U            1 或 0         是
                                                                                                           
                                                                                                           
 -- C 巨集: PyBUF_STRIDED           是          是            NULL             U            0              NULL
                                                                                                           
                                                                                                           
 -- C 巨集: PyBUF_STRIDED_RO        是          是            NULL             U            1 或 0         NULL
                                                                                                           
                                                                                                           
 -- C 巨集: PyBUF_CONTIG            是          NULL          NULL             C            0              NULL
                                                                                                           
                                                                                                           
 -- C 巨集: PyBUF_CONTIG_RO         是          NULL          NULL             C            1 或 0         NULL
                                                                                                           


File: python.info,  Node: 复杂数组,  Next: 缓冲区相关函数,  Prev: 缓冲区请求的类型,  Up: 缓冲协议

7.7.7.8 复杂数组
................

* Menu:

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


File: python.info,  Node: NumPy-风格：形状和步幅,  Next: PIL-风格：形状，步幅和子偏移量,  Up: 复杂数组

7.7.7.9 NumPy-风格：形状和步幅
..............................

NumPy 风格数组的逻辑结构由 *note itemsize: 3f49. 、 *note ndim: 3f4d. 、
*note shape: 3f4c. 和 *note strides: 3f41. 定义。

如果 ‘ndim == 0’ ， *note buf: 3f40. 指向的内存位置被解释为大小为 *note
itemsize: 3f49. 的标量。这时， *note shape: 3f4c. 和 *note strides:
3f41. 都为 ‘NULL’。

如果 *note strides: 3f41. 为 ‘NULL’，则数组将被解释为一个标准的 n 维 C 语
言数组。否则，消费者程序必须按如下方式访问 n 维数组：

     ptr = (char *)buf + indices[0] * strides[0] + ... + indices[n-1] * strides[n-1];
     item = *((typeof(item) *)ptr);

如上所述，*note buf: 3f40. 可以指向实际内存块中的任意位置。输出者程序可
以用该函数检查缓冲区的有效性。

     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


File: python.info,  Node: PIL-风格：形状，步幅和子偏移量,  Prev: NumPy-风格：形状和步幅,  Up: 复杂数组

7.7.7.10 PIL-风格：形状，步幅和子偏移量
.......................................

除了常规项之外， PIL 风格的数组还可以包含指针，必须跟随这些指针才能到达
维度的下一个元素。例如，常规的三维 C 语言数组 ‘char v[2][2][3]’ 可以看作
是一个指向 2 个二维数组的 2 个指针：‘char (*v[2])[2][3]’。在子偏移表示中
，这两个指针可以嵌入在 *note buf: 3f40. 的开头，指向两个可以位于内存任何
位置的 ‘char x[2][3]’ 数组。

这是一个函数，当n维索引所指向的N-D数组中有‘‘NULL‘‘步长和子偏移量时，它返
回一个指针

     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;
     }


File: python.info,  Node: 缓冲区相关函数,  Prev: 复杂数组,  Up: 缓冲协议

7.7.7.11 缓冲区相关函数
.......................

 -- C 函式: int PyObject_CheckBuffer (PyObject *obj)

     如果 `obj' 支持缓冲区接口，则返回 ‘1’，否则返回 ‘0’。 返回 ‘1’ 时不
     保证 *note PyObject_GetBuffer(): deb. 一定成功。本函数一定调用成功
     。

 -- C 函式: int PyObject_GetBuffer (PyObject *exporter, Py_buffer *view,
          int flags)

     向 `输出器程序' 发送请求，按照 `flags' 指定的内容填充 `view'。如果
     输出器程序不能提供准确类型的缓冲区，`必须' 触发
     ‘PyExc_BufferError’，设置 ‘view->obj’ 为 ‘NULL’ 并返回 ‘-1’。

     成功时，填充 `view'，将 ‘view->obj’ 设为对 `exporter' 的新引用，并
     返回 0。 当链式缓冲区提供程序将请求重定向到一个对象时，‘view->obj’
     可以引用该对象而不是 `exporter' (参见 *note 缓冲区对象结构: 3f3c.)。

     *note PyObject_GetBuffer(): deb. 必须与 *note PyBuffer_Release():
     e19. 同时调用成功，类似于 ‘malloc()’ 和 ‘free()’。因此，消费者程序
     用完缓冲区后， *note PyBuffer_Release(): e19. 必须保证被调用一次。

 -- C 函式: void PyBuffer_Release (Py_buffer *view)

     释放缓冲区 `view' 并递减 ‘view->obj’ 的引用计数。该函数必须在缓冲区
     不再使用时才能调用，否则可能会发生引用泄漏。

     若该函数针对的缓冲区不是通过 *note PyObject_GetBuffer(): deb. 获得
     的，将会出错。

 -- C 函式: Py_ssize_t PyBuffer_SizeFromFormat (const char *format)

     返回 *note itemsize: 3f49. 中隐含的 *note format: 3f4a. 。如果出错
     ，会触发异常并返回 -1。

     3.9 版新加入.

 -- C 函式: int PyBuffer_IsContiguous (Py_buffer *view, char order)

     如果 `view' 定义的内存是 C 风格（`order' 为 ‘'C'’）或 Fortran 风格
     （`order' 为 ‘'F'’） *note contiguous: 17ec. 或其中之一（`order' 是
     ‘'A'’），则返回 ‘1’。否则返回 ‘0’。该函数总会成功。

 -- C 函式: void* PyBuffer_GetPointer (Py_buffer *view,
          Py_ssize_t *indices)

     获取给定 `view' 内的 `indices' 所指向的内存区域。`indices' 必须指向
     一个 ‘view->ndim’ 索引的数组。

 -- C 函式: int PyBuffer_FromContiguous (Py_buffer *view, void *buf,
          Py_ssize_t len, char fort)

     从 `buf' 复制连续的 `len' 字节到 `view' 。`fort' 可以是 ‘'C'’ 或
     ‘'F'``（对应于 C 风格或 Fortran 风格的顺序）。成功时返回 ``0’，错误
     时返回 ‘-1’。

 -- C 函式: int PyBuffer_ToContiguous (void *buf, Py_buffer *src,
          Py_ssize_t len, char order)

     从 `src' 复制 `len' 字节到 `buf' ，成为连续字节串的形式。`order' 可
     以是 ‘'C'’ 或 ‘'F'’ 或 ‘'A'``（对应于 C 风格、Fortran 风格的顺序或
     其中任意一种）。成功时返回 ``0’，出错时返回 ‘-1’。

     如果 `len' != `src->len' 则此函数将报错。

 -- C 函式: void PyBuffer_FillContiguousStrides (int ndims,
          Py_ssize_t *shape, Py_ssize_t *strides, int itemsize,
          char order)

     用给定形状的 *note contiguous: 17ec. 字节串数组 (如果 `order' 为
     ‘'C'’ 则为 C 风格，如果 `order' 为 ‘'F'’ 则为 Fortran 风格) 来填充
     `strides' 数组，每个元素具有给定的字节数。

 -- C 函式: int PyBuffer_FillInfo (Py_buffer *view, PyObject *exporter,
          void *buf, Py_ssize_t len, int readonly, int flags)

     处理导出程序的缓冲区请求，该导出程序要公开大小为 `len' 的 `buf' ，
     并根据 `readonly' 设置可写性。`bug' 被解释为一个无符号字节序列。

     参数 `flags' 表示请求的类型。该函数总是按照 flag 指定的内容填入
     `view'，除非 `buf' 设为只读，并且 `flag' 中设置了 *note
     PyBUF_WRITABLE: 3f47. 标志。

     成功时，将 ‘view->obj’ 设为 `exporter' 的新引用，并返回 0。否则，引
     发 ‘PyExc_BufferError’ ，将 ‘view->obj’ 设为 ‘NULL’，并返回 ‘-1’。

     如果此函数用作 *note getbufferproc: 3f3c. 的一部分，则 `exporter' 必
     须设置为导出对象，并且必须在未修改的情况下传递 `flags'。否则，
     `exporter' 必须是 ‘NULL’。


File: python.info,  Node: 旧缓冲协议,  Prev: 缓冲协议,  Up: 抽象物件層

7.7.8 旧缓冲协议
----------------

3.0 版後已棄用.

这些函数是 Python 2 中“旧缓冲协议”API 的组成部分。 在 Python 3 中，此协
议已不复存在，但这些函数仍然被公开以便移植 2.x 的代码。 它们被用作 *note
新缓冲协议: 171c. 的兼容性包装器，但它们并不会在缓冲被导出时向你提供对所
获资源的生命周期控制。

因此，推荐你调用 *note PyObject_GetBuffer(): deb. (或者配合 *note
PyArg_ParseTuple(): 393. 函数族使用 ‘y*’ 或 ‘w*’ *note 格式码: 3f2.) 来
获取一个对象的缓冲视图，并在缓冲视图可被释放时调用 *note
PyBuffer_Release(): e19.。

 -- C 函式: int PyObject_AsCharBuffer (PyObject *obj, const
          char **buffer, Py_ssize_t *buffer_len)

     返回一个指向可用作基于字符的输入的只读内存地址的指针。 `obj' 参数必
     须支持单段字符缓冲接口。 成功时返回 ‘0’，将 `buffer' 设为内存地址并
     将 `buffer_len' 设为缓冲区长度。 出错时返回 ‘-1’ 并设置一个 *note
     TypeError: 1fe.。

 -- C 函式: int PyObject_AsReadBuffer (PyObject *obj, const
          void **buffer, Py_ssize_t *buffer_len)

     返回一个指向包含任意数据的只读内存地址的指针。 `obj' 参数必须支持单
     段可读缓冲接口。 成功时返回 ‘0’，将 `buffer' 设为内存地址并将
     `buffer_len' 设为缓冲区长度。 出错时返回 ‘-1’ 并设置一个 *note
     TypeError: 1fe.。

 -- C 函式: int PyObject_CheckReadBuffer (PyObject *o)

     如果 `o' 支持单段可读缓冲接口则返回 ‘1’。 否则返回 ‘0’。 此函数总是
     会成功执行。

     请注意此函数会尝试获取并释放一个缓冲区，并且在调用对应函数期间发生
     的异常会被屏蔽。 要获取错误报告则应改用 *note PyObject_GetBuffer():
     deb.。

 -- C 函式: int PyObject_AsWriteBuffer (PyObject *obj, void **buffer,
          Py_ssize_t *buffer_len)

     返回一个指向可写内存地址的指针。 `obj' 必须支持单段字符缓冲接口。 成
     功时返回 ‘0’，将 `buffer' 设为内存地址并将 `buffer_len' 设为缓冲区
     长度。 出错时返回 ‘-1’ 并设置一个 *note TypeError: 1fe.。


File: python.info,  Node: 具体的对象层,  Next: 初始化，终结和线程,  Prev: 抽象物件層,  Up: Python/C API 參考手冊

7.8 具体的对象层
================

本章中的函数特定于某些 Python 对象类型。 将错误类型的对象传递给它们并不
是一个好主意；如果您从 Python 程序接收到一个对象，但不确定它是否具有正确
的类型，则必须首先执行类型检查；例如，要检查对象是否为字典，请使用 *note
PyDict_Check(): 3f77.。 本章的结构类似于 Python 对象类型的“家族树”。

     警告: 虽然本章所描述的函数会仔细检查传入对象的类型，但是其中许多函
     数不会检查传入的对象是否为 ‘NULL’。 允许传入 ‘NULL’ 可能导致内存访
     问冲突和解释器的立即终止。

* Menu:

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


File: python.info,  Node: 基本对象,  Next: 数值对象,  Up: 具体的对象层

7.8.1 基本对象
--------------

本节描述Python类型对象和单一实例对象 象None。

* Menu:

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


File: python.info,  Node: Type 对象,  Next: None 对象,  Up: 基本对象

7.8.1.1 Type 对象
.................

 -- C 類型: PyTypeObject

     对象的 C 结构用于描述 built-in 类型。

 -- C 變數: PyTypeObject PyType_Type

     这是属于 type 对象的 type object，它在 Python 层面和 *note type:
     6ff. 是相同的对象。

 -- C 函式: int PyType_Check (PyObject *o)

     Return non-zero if the object `o' is a type object, including
     instances of types derived from the standard type object.  Return 0
     in all other cases.  This function always succeeds.

 -- C 函式: int PyType_CheckExact (PyObject *o)

     Return non-zero if the object `o' is a type object, but not a
     subtype of the standard type object.  Return 0 in all other cases.
     This function always succeeds.

 -- C 函式: unsigned int PyType_ClearCache ()

     Clear the internal lookup cache.  Return the current version tag.

 -- C 函式: unsigned long PyType_GetFlags (PyTypeObject* type)

     Return the *note tp_flags: 1011. member of `type'.  This function
     is primarily meant for use with ‘Py_LIMITED_API’; the individual
     flag bits are guaranteed to be stable across Python releases, but
     access to *note tp_flags: 1011. itself is not part of the limited
     API.

     3.2 版新加入.

     3.4 版更變: The return type is now ‘unsigned long’ rather than
     ‘long’.

 -- C 函式: void PyType_Modified (PyTypeObject *type)

     Invalidate the internal lookup cache for the type and all of its
     subtypes.  This function must be called after any manual
     modification of the attributes or base classes of the type.

 -- C 函式: int PyType_HasFeature (PyTypeObject *o, int feature)

     Return non-zero if the type object `o' sets the feature `feature'.
     Type features are denoted by single bit flags.

 -- C 函式: int PyType_IS_GC (PyTypeObject *o)

     Return true if the type object includes support for the cycle
     detector; this tests the type flag *note Py_TPFLAGS_HAVE_GC: 3d68.

 -- C 函式: int PyType_IsSubtype (PyTypeObject *a, PyTypeObject *b)

     Return true if `a' is a subtype of `b'.

     This function only checks for actual subtypes, which means that
     *note __subclasscheck__(): 1585. is not called on `b'.  Call *note
     PyObject_IsSubclass(): 88d. to do the same check that *note
     issubclass(): 552. would do.

 -- C 函式: PyObject* PyType_GenericAlloc (PyTypeObject *type,
          Py_ssize_t nitems)
     `Return value: New reference.'  Generic handler for the *note
     tp_alloc: 3d5c. slot of a type object.  Use Python’s default memory
     allocation mechanism to allocate a new instance and initialize all
     its contents to ‘NULL’.

 -- C 函式: PyObject* PyType_GenericNew (PyTypeObject *type,
          PyObject *args, PyObject *kwds)
     `Return value: New reference.'  Generic handler for the *note
     tp_new: 3d57. slot of a type object.  Create a new instance using
     the type’s *note tp_alloc: 3d5c. slot.

 -- C 函式: int PyType_Ready (PyTypeObject *type)

     Finalize a type object.  This should be called on all type objects
     to finish their initialization.  This function is responsible for
     adding inherited slots from a type’s base class.  Return ‘0’ on
     success, or return ‘-1’ and sets an exception on error.

          備註: If some of the base classes implements the GC protocol
          and the provided type does not include the *note
          Py_TPFLAGS_HAVE_GC: 3d68. in its flags, then the GC protocol
          will be automatically implemented from its parents.  On the
          contrary, if the type being created does include *note
          Py_TPFLAGS_HAVE_GC: 3d68. in its flags then it `must'
          implement the GC protocol itself by at least implementing the
          *note tp_traverse: 23b. handle.

 -- C 函式: void* PyType_GetSlot (PyTypeObject *type, int slot)

     Return the function pointer stored in the given slot.  If the
     result is ‘NULL’, this indicates that either the slot is ‘NULL’, or
     that the function was called with invalid parameters.  Callers will
     typically cast the result pointer into the appropriate function
     type.

     See ‘PyType_Slot.slot’ for possible values of the `slot' argument.

     An exception is raised if `type' is not a heap type.

     3.4 版新加入.

 -- C 函式: PyObject* PyType_GetModule (PyTypeObject *type)

     Return the module object associated with the given type when the
     type was created using *note PyType_FromModuleAndSpec(): 245.

     If no module is associated with the given type, sets *note
     TypeError: 1fe. and returns ‘NULL’.

     This function is usually used to get the module in which a method
     is defined.  Note that in such a method,
     ‘PyType_GetModule(Py_TYPE(self))’ may not return the intended
     result.  ‘Py_TYPE(self)’ may be a `subclass' of the intended class,
     and subclasses are not necessarily defined in the same module as
     their superclass.  See *note PyCMethod: 248. to get the class that
     defines the method.

     3.9 版新加入.

 -- C 函式: void* PyType_GetModuleState (PyTypeObject *type)

     Return the state of the module object associated with the given
     type.  This is a shortcut for calling *note PyModule_GetState():
     25e. on the result of *note PyType_GetModule(): 246.

     If no module is associated with the given type, sets *note
     TypeError: 1fe. and returns ‘NULL’.

     If the `type' has an associated module but its state is ‘NULL’,
     returns ‘NULL’ without setting an exception.

     3.9 版新加入.

* Menu:

* Creating Heap-Allocated Types::


File: python.info,  Node: Creating Heap-Allocated Types,  Up: Type 对象

7.8.1.2 Creating Heap-Allocated Types
.....................................

The following functions and structs are used to create *note heap types:
3f83.

 -- C 函式: PyObject* PyType_FromModuleAndSpec (PyObject *module,
          PyType_Spec *spec, PyObject *bases)
     `Return value: New reference.'  Creates and returns a heap type
     object from the `spec' (*note Py_TPFLAGS_HEAPTYPE: 3f84.).

     If `bases' is a tuple, the created heap type contains all types
     contained in it as base types.

     If `bases' is ‘NULL’, the `Py_tp_bases' slot is used instead.  If
     that also is ‘NULL’, the `Py_tp_base' slot is used instead.  If
     that also is ‘NULL’, the new type derives from *note object: 3d2.

     The `module' argument can be used to record the module in which the
     new class is defined.  It must be a module object or ‘NULL’.  If
     not ‘NULL’, the module is associated with the new type and can
     later be retrieved with *note PyType_GetModule(): 246.  The
     associated module is not inherited by subclasses; it must be
     specified for each class individually.

     This function calls *note PyType_Ready(): 3d5d. on the new type.

     3.9 版新加入.

 -- C 函式: PyObject* PyType_FromSpecWithBases (PyType_Spec *spec,
          PyObject *bases)
     `Return value: New reference.'  Equivalent to
     ‘PyType_FromModuleAndSpec(NULL, spec, bases)’.

     3.3 版新加入.

 -- C 函式: PyObject* PyType_FromSpec (PyType_Spec *spec)
     `Return value: New reference.'  Equivalent to
     ‘PyType_FromSpecWithBases(spec, NULL)’.

 -- C 類型: PyType_Spec

     Structure defining a type’s behavior.

      -- C 成員函數: const char* PyType_Spec.name

          Name of the type, used to set *note PyTypeObject.tp_name:
          3d75.

      -- C 成員函數: int PyType_Spec.basicsize

      -- C 成員函數: int PyType_Spec.itemsize

          Size of the instance in bytes, used to set *note
          PyTypeObject.tp_basicsize: 26a. and *note
          PyTypeObject.tp_itemsize: 3d54.

      -- C 成員函數: int PyType_Spec.flags

          Type flags, used to set *note PyTypeObject.tp_flags: 1011.

          If the ‘Py_TPFLAGS_HEAPTYPE’ flag is not set, *note
          PyType_FromSpecWithBases(): 102d. sets it automatically.

      -- C 成員函數: PyType_Slot *PyType_Spec.slots

          Array of *note PyType_Slot: 3f8b. structures.  Terminated by
          the special slot value ‘{0, NULL}’.

 -- C 類型: PyType_Slot

     Structure defining optional functionality of a type, containing a
     slot ID and a value pointer.

      -- C 成員函數: int PyType_Slot.slot

               A slot ID.

               Slot IDs are named like the field names of the structures
               *note PyTypeObject: 3f5, *note PyNumberMethods: e46,
               *note PySequenceMethods: 3d83, *note PyMappingMethods:
               3d84. and *note PyAsyncMethods: 3f8d. with an added ‘Py_’
               prefix.  For example, use:

                  * ‘Py_tp_dealloc’ to set *note
                    PyTypeObject.tp_dealloc: 3d5a.

                  * ‘Py_nb_add’ to set *note PyNumberMethods.nb_add:
                    3f8e.

                  * ‘Py_sq_length’ to set *note
                    PySequenceMethods.sq_length: 3f8f.

               The following fields cannot be set at all using *note
               PyType_Spec: 3f85. and *note PyType_Slot: 3f8b.:

                  * *note tp_dict: 3f90.

                  * *note tp_mro: 3f91.

                  * *note tp_cache: 3f92.

                  * *note tp_subclasses: 3f93.

                  * *note tp_weaklist: 3f94.

                  * *note tp_vectorcall: 3f95.

                  * *note tp_weaklistoffset: 26b. (see *note
                    PyMemberDef: 3f96.)

                  * *note tp_dictoffset: 3f97. (see *note PyMemberDef:
                    3f96.)

                  * *note tp_vectorcall_offset: 3ee0. (see *note
                    PyMemberDef: 3f96.)

               The following fields cannot be set using *note
               PyType_Spec: 3f85. and *note PyType_Slot: 3f8b. under the
               limited API:

                  * *note bf_getbuffer: 3f98.

                  * *note bf_releasebuffer: 3e8e.

               Setting ‘Py_tp_bases’ or ‘Py_tp_base’ may be problematic
               on some platforms.  To avoid issues, use the `bases'
               argument of ‘PyType_FromSpecWithBases()’ instead.

          3.9 版更變: Slots in *note PyBufferProcs: 3f99. in may be set
          in the unlimited API.

      -- C 成員函數: void *PyType_Slot.pfunc

          The desired value of the slot.  In most cases, this is a
          pointer to a function.

          May not be ‘NULL’.


File: python.info,  Node: None 对象,  Prev: Type 对象,  Up: 基本对象

7.8.1.3 ‘None’ 对象
...................

请注意， ‘None’ 的 *note PyTypeObject: 3f5. 不会直接在 Python / C API 中
公开。 由于 ‘None’ 是单例，测试对象标识（在C中使用 ‘==’ ）就足够了。 由
于同样的原因，没有 ‘PyNone_Check()’ 函数。

 -- C 變數: PyObject* Py_None

     Python ‘None’ 对象，表示缺乏值。 这个对象没有方法。 它需要像引用计
     数一样处理任何其他对象。

 -- C 巨集: Py_RETURN_NONE

     正确处理来自C函数内的 *note Py_None: 3d23. 返回（也就是说，增加
     ‘None’ 的引用计数并返回它。）


File: python.info,  Node: 数值对象,  Next: 序列对象,  Prev: 基本对象,  Up: 具体的对象层

7.8.2 数值对象
--------------

* Menu:

* 整數物件::
* 布林物件::
* 浮點數（Floating Point）物件::
* 复数对象::


File: python.info,  Node: 整數物件,  Next: 布林物件,  Up: 数值对象

7.8.2.1 整數物件
................

所有整数都使用以任意大小的长整数对象表示。

在出错时，大多数 ‘PyLong_As*’ API返回 ‘(返回类型)-1’ ，无法与一般的数字
区分开来。请使用 *note PyErr_Occurred(): 3d1e. 来区分。

 -- C 類型: PyLongObject

     表示 Python 整数对象的 *note PyObject: 5b4. 子类型。

 -- C 變數: PyTypeObject PyLong_Type

     这个 *note PyTypeObject: 3f5. 的实例表示 Python 的整数类型。与
     Python层中的 *note int: 204. 相同。

 -- C 函式: int PyLong_Check (PyObject *p)

     如果它的参数是 *note PyLongObject: 3fa3. 或 *note PyLongObject:
     3fa3. 的子类型则返回真值。 此函数总是会成功执行。

 -- C 函式: int PyLong_CheckExact (PyObject *p)

     如果它的参数是 *note PyLongObject: 3fa3.，但不是 *note
     PyLongObject: 3fa3. 的子类型则返回真值。 此函数总是会成功执行。

 -- C 函式: PyObject* PyLong_FromLong (long v)
     `Return value: New reference.' 由 `v' 返回一个新的 *note
     PyLongObject: 3fa3. 对象，失败时返回 ‘NULL’ 。

     当前的实现维护了一个整数对象数组，包含 ‘-5’ 和 ‘256’ 之间的所有整数
     对象。当你在这个范围内创建一个 int 时，实际上得到的是一个对已有对象
     的引用。

 -- C 函式: PyObject* PyLong_FromUnsignedLong (unsigned long v)
     `Return value: New reference.' 由 C ‘unsigned long’ 类型返回一个新
     的 *note PyLongObject: 3fa3. 对象，失败时返回 ‘NULL’ 。

 -- C 函式: PyObject* PyLong_FromSsize_t (Py_ssize_t v)
     `Return value: New reference.' 从 C ‘Py_ssize_t’ 类型返回一个新的
     *note PyLongObject: 3fa3. 对象，如果失败则返回 ‘NULL’ 。

 -- C 函式: PyObject* PyLong_FromSize_t (size_t v)
     `Return value: New reference.' 从 C ‘size_t’ 返回一个新的 *note
     PyLongObject: 3fa3. 对象，如果失败则返回 ‘NULL’ 。

 -- C 函式: PyObject* PyLong_FromLongLong (long long v)
     `Return value: New reference.' 从 C ‘long long’ 返回一个新的 *note
     PyLongObject: 3fa3. 对象，失败时返回 ‘NULL’ 。

 -- C 函式: PyObject* PyLong_FromUnsignedLongLong (unsigned long long v)
     `Return value: New reference.' 从 C ‘unsigned long long’ 返回一个新
     的 *note PyLongObject: 3fa3. 对象，失败时返回 ‘NULL’ 。

 -- C 函式: PyObject* PyLong_FromDouble (double v)
     `Return value: New reference.' 从 `v' 的整数部分返回一个新的 *note
     PyLongObject: 3fa3. 对象，如果失败则返回 ‘NULL’ 。

 -- C 函式: PyObject* PyLong_FromString (const char *str, char **pend,
          int base)
     `Return value: New reference.' 根据 `str' 字符串值返回一个新的
     *note PyLongObject: 3fa3. ，`base' 指定基数。如果 `pend' 不是
     ‘NULL’ ， `/*pend' 将指向 `str' 中表示这个数字部分的后面的第一个字
     符。如果 `base' 是 ‘0’ ， `str' 将使用 *note 整数字面值: 1533. 定义
     来解释；在这种情况下，一个非零的十进制数中的前导零会引发一个 *note
     ValueError: 16d. 。如果 `base' 不是 ‘0’ ，它必须在 ‘2’ 和 ‘36’ 之间
     ，包括2和36。基数说明符后以及数字之间的前导空格、单下划线将被忽略。
     如果没有数字，将引发 *note ValueError: 16d.。

 -- C 函式: PyObject* PyLong_FromUnicode (Py_UNICODE *u,
          Py_ssize_t length, int base)
     `Return value: New reference.' 将 Unicode 数字序列转换为 Python 整
     数值。

     Deprecated since version 3.3, will be removed in version 3.10: 旧的
     *note Py_UNICODE: bc5. API的一部分;请迁移到使用 *note
     PyLong_FromUnicodeObject(): 3fab. 。

 -- C 函式: PyObject* PyLong_FromUnicodeObject (PyObject *u, int base)
     `Return value: New reference.' 将字符串 `u' 中的 Unicode 数字序列转
     换为 Python 整数值。

     3.3 版新加入.

 -- C 函式: PyObject* PyLong_FromVoidPtr (void *p)
     `Return value: New reference.' 从指针 `p' 创建一个 Python 整数。可
     以使用 *note PyLong_AsVoidPtr(): 3fad. 返回的指针值。

 -- C 函式: long PyLong_AsLong (PyObject *obj)

     返回 `obj' 的 C ‘long’ 表达方式。 如果 `obj' 不是 *note
     PyLongObject: 3fa3. 的实例，先调用它的 *note __index__(): 2c2. 或
     *note __int__(): 2c3. 方法(如果有)将其转换为 *note PyLongObject:
     3fa3. 。

     如果 `obj' 的值溢出了 ‘long’ 的范围，会引发 *note OverflowError:
     a41.。

     发生错误时返回 ‘-1’ 。使用 *note PyErr_Occurred(): 3d1e. 来消歧义。

     3.8 版更變: 如果可用将使用 *note __index__(): 2c2.。

     3.8 版後已棄用: *note __int__(): 2c3. 已被弃用。

 -- C 函式: long PyLong_AsLongAndOverflow (PyObject *obj, int *overflow)

     返回 `obj' 的 C ‘long’ 表达方式。 如果 `obj' 不是 *note
     PyLongObject: 3fa3. 的实例，先调用它的 *note __index__(): 2c2. 或
     *note __int__(): 2c3. 方法(如果有)将其转换为 *note PyLongObject:
     3fa3. 。

     If the value of `obj' is greater than ‘LONG_MAX’ or less than
     ‘LONG_MIN’, set `*overflow' to ‘1’ or ‘-1’, respectively, and
     return ‘-1’; otherwise, set `*overflow' to ‘0’.  If any other
     exception occurs set `*overflow' to ‘0’ and return ‘-1’ as usual.

     发生错误时返回 ‘-1’ 。使用 *note PyErr_Occurred(): 3d1e. 来消歧义。

     3.8 版更變: 如果可用将使用 *note __index__(): 2c2.。

     3.8 版後已棄用: *note __int__(): 2c3. 已被弃用。

 -- C 函式: long long PyLong_AsLongLong (PyObject *obj)

     Return a C ‘long long’ representation of `obj'.  If `obj' is not an
     instance of *note PyLongObject: 3fa3, first call its *note
     __index__(): 2c2. or *note __int__(): 2c3. method (if present) to
     convert it to a *note PyLongObject: 3fa3.

     如果 `obj' 值超出 ‘long long’ ，触发 *note OverflowError: a41.

     发生错误时返回 ‘-1’ 。使用 *note PyErr_Occurred(): 3d1e. 来消歧义。

     3.8 版更變: 如果可用将使用 *note __index__(): 2c2.。

     3.8 版後已棄用: *note __int__(): 2c3. 已被弃用。

 -- C 函式: long long PyLong_AsLongLongAndOverflow (PyObject *obj,
          int *overflow)

     Return a C ‘long long’ representation of `obj'.  If `obj' is not an
     instance of *note PyLongObject: 3fa3, first call its *note
     __index__(): 2c2. or *note __int__(): 2c3. method (if present) to
     convert it to a *note PyLongObject: 3fa3.

     If the value of `obj' is greater than ‘LLONG_MAX’ or less than
     ‘LLONG_MIN’, set `*overflow' to ‘1’ or ‘-1’, respectively, and
     return ‘-1’; otherwise, set `*overflow' to ‘0’.  If any other
     exception occurs set `*overflow' to ‘0’ and return ‘-1’ as usual.

     发生错误时返回 ‘-1’ 。使用 *note PyErr_Occurred(): 3d1e. 来消歧义。

     3.2 版新加入.

     3.8 版更變: 如果可用将使用 *note __index__(): 2c2.。

     3.8 版後已棄用: *note __int__(): 2c3. 已被弃用。

 -- C 函式: Py_ssize_t PyLong_AsSsize_t (PyObject *pylong)

     Return a C ‘Py_ssize_t’ representation of `pylong'.  `pylong' must
     be an instance of *note PyLongObject: 3fa3.

     Raise *note OverflowError: a41. if the value of `pylong' is out of
     range for a ‘Py_ssize_t’.

     发生错误时返回 ‘-1’ 。使用 *note PyErr_Occurred(): 3d1e. 来消歧义。

 -- C 函式: unsigned long PyLong_AsUnsignedLong (PyObject *pylong)

     Return a C ‘unsigned long’ representation of `pylong'.  `pylong'
     must be an instance of *note PyLongObject: 3fa3.

     Raise *note OverflowError: a41. if the value of `pylong' is out of
     range for a ‘unsigned long’.

     Returns ‘(unsigned long)-1’ on error.  Use *note PyErr_Occurred():
     3d1e. to disambiguate.

 -- C 函式: size_t PyLong_AsSize_t (PyObject *pylong)

     Return a C ‘size_t’ representation of `pylong'.  `pylong' must be
     an instance of *note PyLongObject: 3fa3.

     Raise *note OverflowError: a41. if the value of `pylong' is out of
     range for a ‘size_t’.

     Returns ‘(size_t)-1’ on error.  Use *note PyErr_Occurred(): 3d1e.
     to disambiguate.

 -- C 函式: unsigned long long PyLong_AsUnsignedLongLong
          (PyObject *pylong)

     Return a C ‘unsigned long long’ representation of `pylong'.
     `pylong' must be an instance of *note PyLongObject: 3fa3.

     Raise *note OverflowError: a41. if the value of `pylong' is out of
     range for an ‘unsigned long long’.

     Returns ‘(unsigned long long)-1’ on error.  Use *note
     PyErr_Occurred(): 3d1e. to disambiguate.

     3.1 版更變: A negative `pylong' now raises *note OverflowError:
     a41, not *note TypeError: 1fe.

 -- C 函式: unsigned long PyLong_AsUnsignedLongMask (PyObject *obj)

     Return a C ‘unsigned long’ representation of `obj'.  If `obj' is
     not an instance of *note PyLongObject: 3fa3, first call its *note
     __index__(): 2c2. or *note __int__(): 2c3. method (if present) to
     convert it to a *note PyLongObject: 3fa3.

     If the value of `obj' is out of range for an ‘unsigned long’,
     return the reduction of that value modulo ‘ULONG_MAX + 1’.

     Returns ‘(unsigned long)-1’ on error.  Use *note PyErr_Occurred():
     3d1e. to disambiguate.

     3.8 版更變: 如果可用将使用 *note __index__(): 2c2.。

     3.8 版後已棄用: *note __int__(): 2c3. 已被弃用。

 -- C 函式: unsigned long long PyLong_AsUnsignedLongLongMask
          (PyObject *obj)

     Return a C ‘unsigned long long’ representation of `obj'.  If `obj'
     is not an instance of *note PyLongObject: 3fa3, first call its
     *note __index__(): 2c2. or *note __int__(): 2c3. method (if
     present) to convert it to a *note PyLongObject: 3fa3.

     If the value of `obj' is out of range for an ‘unsigned long long’,
     return the reduction of that value modulo ‘ULLONG_MAX + 1’.

     Returns ‘(unsigned long long)-1’ on error.  Use *note
     PyErr_Occurred(): 3d1e. to disambiguate.

     3.8 版更變: 如果可用将使用 *note __index__(): 2c2.。

     3.8 版後已棄用: *note __int__(): 2c3. 已被弃用。

 -- C 函式: double PyLong_AsDouble (PyObject *pylong)

     Return a C ‘double’ representation of `pylong'.  `pylong' must be
     an instance of *note PyLongObject: 3fa3.

     Raise *note OverflowError: a41. if the value of `pylong' is out of
     range for a ‘double’.

     Returns ‘-1.0’ on error.  Use *note PyErr_Occurred(): 3d1e. to
     disambiguate.

 -- C 函式: void* PyLong_AsVoidPtr (PyObject *pylong)

     Convert a Python integer `pylong' to a C ‘void’ pointer.  If
     `pylong' cannot be converted, an *note OverflowError: a41. will be
     raised.  This is only assured to produce a usable ‘void’ pointer
     for values created with *note PyLong_FromVoidPtr(): 3fac.

     Returns ‘NULL’ on error.  Use *note PyErr_Occurred(): 3d1e. to
     disambiguate.


File: python.info,  Node: 布林物件,  Next: 浮點數（Floating Point）物件,  Prev: 整數物件,  Up: 数值对象

7.8.2.2 布林物件
................

Python 中的布尔值是作为整数的子类实现的。只有 ‘Py_False’ 和 ‘Py_True’ 两
个布尔值。因此，正常的创建和删除功能不适用于布尔值。但是，下列宏可用。

 -- C 函式: int PyBool_Check (PyObject *o)

     如果 `o' 的类型为 ‘PyBool_Type’ 则返回真值。 此函数总是会成功执行。

 -- C 變數: PyObject* Py_False

     Python 的 ‘False’ 对象没有任何方法，它需要和其他对象一样遵循引用计
     数。

 -- C 變數: PyObject* Py_True

     Python 的 ‘True’ 对象没有任何方法，它需要和其他对象一样遵循引用计数
     。

 -- C 巨集: Py_RETURN_FALSE

     从函数返回 ‘Py_False’ 时，需要增加它的引用计数。

 -- C 巨集: Py_RETURN_TRUE

     从函数返回 ‘Py_True’ 时，需要增加它的引用计数。

 -- C 函式: PyObject* PyBool_FromLong (long v)
     `Return value: New reference.' 根据 `v' 的实际值，返回一个
     ‘Py_True’ 或者 ‘Py_False’ 的新引用。


File: python.info,  Node: 浮點數（Floating Point）物件,  Next: 复数对象,  Prev: 布林物件,  Up: 数值对象

7.8.2.3 浮點數（Floating Point）物件
....................................

 -- C 類型: PyFloatObject

     这个C类型 *note PyObject: 5b4. 的子类型代表一个Python浮点数对象。

 -- C 變數: PyTypeObject PyFloat_Type

     这是个属于C类型 *note PyTypeObject: 3f5. 的代表Python浮点类型的实例
     。在Python层面的类型 *note float: 1fd. 是同一个对象。

 -- C 函式: int PyFloat_Check (PyObject *p)

     如果它的参数是一个 *note PyFloatObject: 3fbe. 或者 *note
     PyFloatObject: 3fbe. 的子类型则返回真值。 此函数总是会成功执行。

 -- C 函式: int PyFloat_CheckExact (PyObject *p)

     如果它的参数是一个 *note PyFloatObject: 3fbe. 但不是 *note
     PyFloatObject: 3fbe. 的子类型则返回真值。 此函数总是会成功执行。

 -- C 函式: PyObject* PyFloat_FromString (PyObject *str)
     `Return value: New reference.' 根据字符串 `str' 的值创建一个 *note
     PyFloatObject: 3fbe.，失败时返回 ‘NULL’。

 -- C 函式: PyObject* PyFloat_FromDouble (double v)
     `Return value: New reference.' 根据 `v' 创建一个 *note
     PyFloatObject: 3fbe. 对象，失败时返回 ‘NULL’。

 -- C 函式: double PyFloat_AsDouble (PyObject *pyfloat)

     返回一个 C ‘double’ 代表 `pyfloat' 的内容。 如果 `pyfloat' 不是一个
     Python 浮点数对象但是具有 *note __float__(): 2c4. 方法，此方法将首
     先被调用，将 `pyfloat' 转换成一个数点数。 如果 ‘__float__()’ 未定义
     则将回退至 *note __index__(): 2c2.。 如果失败，此方法将返回 ‘-1.0’，
     因此开发者应当调用 *note PyErr_Occurred(): 3d1e. 来检查错误。

     3.8 版更變: 如果可用将使用 *note __index__(): 2c2.。

 -- C 函式: double PyFloat_AS_DOUBLE (PyObject *pyfloat)

     返回一个 `pyfloat' 内容的 C ‘double’ 表示，但没有错误检查。

 -- C 函式: PyObject* PyFloat_GetInfo (void)
     `Return value: New reference.' 返回一个 structseq 实例，其中包含有
     关 float 的精度、最小值和最大值的信息。 它是头文件 ‘float.h’ 的一个
     简单包装。

 -- C 函式: double PyFloat_GetMax ()

     返回最大可表示的有限浮点数 `DBL_MAX' 为 C ‘double’ 。

 -- C 函式: double PyFloat_GetMin ()

     返回最小可表示归一化正浮点数 `DBL_MIN' 为 C ‘double’ 。


File: python.info,  Node: 复数对象,  Prev: 浮點數（Floating Point）物件,  Up: 数值对象

7.8.2.4 复数对象
................

从C API看，Python的复数对象由两个不同的部分实现：一个是在Python程序使用
的Python对象，另外的是一个代表真正复数值的C结构体。API提供了函数共同操作
两者。

* Menu:

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


File: python.info,  Node: 表示复数的C结构体,  Next: 表示复数的Python对象,  Up: 复数对象

7.8.2.5 表示复数的C结构体
.........................

需要注意的是接受这些结构体的作为参数并当做结果返回的函数，都是传递“值”而
不是引用指针。此规则适用于整个API。

 -- C 類型: Py_complex

     这是一个对应Python复数对象的值部分的C结构体。绝大部分处理复数对象的
     函数都用这类型的结构体作为输入或者输出值，它可近似地定义为：

          typedef struct {
             double real;
             double imag;
          } Py_complex;

 -- C 函式: Py_complex _Py_c_sum (Py_complex left, Py_complex right)

     返回两个复数的和，用 C 类型 *note Py_complex: 3e90. 表示。

 -- C 函式: Py_complex _Py_c_diff (Py_complex left, Py_complex right)

     返回两个复数的差，用 C 类型 *note Py_complex: 3e90. 表示。

 -- C 函式: Py_complex _Py_c_neg (Py_complex num)

     返回复数 `num' 的负值，用 C *note Py_complex: 3e90. 表示。

 -- C 函式: Py_complex _Py_c_prod (Py_complex left, Py_complex right)

     返回两个复数的乘积，用 C 类型 *note Py_complex: 3e90. 表示。

 -- C 函式: Py_complex _Py_c_quot (Py_complex dividend,
          Py_complex divisor)

     返回两个复数的商，用 C 类型 *note Py_complex: 3e90. 表示。

     如果 `divisor' 为空，这个方法返回零并设置 ‘errno’ 为 ‘EDOM’。

 -- C 函式: Py_complex _Py_c_pow (Py_complex num, Py_complex exp)

     返回 `num' 的 `exp' 次幂，用 C 类型 *note Py_complex: 3e90. 表示。

     如果 `num' 为空且 `exp' 不是正实数，这个方法返回零并设置 ‘errno’ 为
     ‘EDOM’。


File: python.info,  Node: 表示复数的Python对象,  Prev: 表示复数的C结构体,  Up: 复数对象

7.8.2.6 表示复数的Python对象
............................

 -- C 類型: PyComplexObject

     这个C类型 *note PyObject: 5b4. 的子类型代表一个 Python 复数对象。

 -- C 變數: PyTypeObject PyComplex_Type

     这是个属于C类型 *note PyTypeObject: 3f5. 的代表 Python 复数类型的实
     例。 和 Python 层面的类 *note complex: 2c1. 是同一个对象。

 -- C 函式: int PyComplex_Check (PyObject *p)

     如果它的参数是一个 *note PyComplexObject: 3fd0. 或者 *note
     PyComplexObject: 3fd0. 的子类型则返回真值。 此函数总是会成功执行。

 -- C 函式: int PyComplex_CheckExact (PyObject *p)

     如果它的参数是一个 *note PyComplexObject: 3fd0. 但不是 *note
     PyComplexObject: 3fd0. 的子类型则返回真值。 此函数总是会成功执行。

 -- C 函式: PyObject* PyComplex_FromCComplex (Py_complex v)
     `Return value: New reference.' 根据C类型 *note Py_complex: 3e90. 的
     值生成一个新的Python复数对象。

 -- C 函式: PyObject* PyComplex_FromDoubles (double real, double imag)
     `Return value: New reference.' 根据 `real' 和 `imag' 返回一个新的
     C类型 *note PyComplexObject: 3fd0. 对象。

 -- C 函式: double PyComplex_RealAsDouble (PyObject *op)

     以C类型 ‘double’ 返回 `op' 的实部。

 -- C 函式: double PyComplex_ImagAsDouble (PyObject *op)

     以C类型 ‘double’ 返回 `op' 的虚部。

 -- C 函式: Py_complex PyComplex_AsCComplex (PyObject *op)

     返回复数 `op' 的C类型 *note Py_complex: 3e90. 值。

     如果 `op' 不是一个 Python 复数对象，但是具有 *note __complex__():
     2c5. 方法，此方法将首先被调用，将 `op' 转换为一个 Python 复数对象。
     如果 ‘__complex__()’ 未定义则将回退至 *note __float__(): 2c4.，如果
     ‘__float__()’ 未定义则将回退至 *note __index__(): 2c2.。 如果失败，
     此方法将返回 ‘-1.0’ 作为实数值。

     3.8 版更變: 如果可用将使用 *note __index__(): 2c2.。


File: python.info,  Node: 序列对象,  Next: 容器对象,  Prev: 数值对象,  Up: 具体的对象层

7.8.3 序列对象
--------------

序列对象的一般操作在前一章中讨论过;本节介绍Python语言固有的特定类型的序
列对象。

* Menu:

* 字节对象::
* 字节数组对象::
* Unicode物件與編碼::
* 元組（Tuple）物件::
* 结构序列对象::
* List（串列）物件::


File: python.info,  Node: 字节对象,  Next: 字节数组对象,  Up: 序列对象

7.8.3.1 字节对象
................

当期望带一个字节串形参但却带一个非字节串形参被调用时，这些函数会引发
*note TypeError: 1fe.。

 -- C 類型: PyBytesObject

     这种 *note PyObject: 5b4. 的子类型表示一个 Python 字节对象。

 -- C 變數: PyTypeObject PyBytes_Type

     *note PyTypeObject: 3f5. 的实例代表一个 Python 字节类型，在 Python
     层面它与 *note bytes: 172. 是相同的对象。

 -- C 函式: int PyBytes_Check (PyObject *o)

     如果对象 `o' 是一个 bytes 对象或者 bytes 类型的子类型的实例则返回真
     值。 此函数总是会成功执行。

 -- C 函式: int PyBytes_CheckExact (PyObject *o)

     如果对象 `o' 是一个 bytes 对象但不是 bytes 类型的子类型的实例则返回
     真值。 此函数总是会成功执行。

 -- C 函式: PyObject* PyBytes_FromString (const char *v)
     `Return value: New reference.' 成功时返回一个以字符串 `v' 的副本为
     值的新字节串对象，失败时返回 ‘NULL’。 形参 `v' 不可为 ‘NULL’；它不
     会被检查。

 -- C 函式: PyObject* PyBytes_FromStringAndSize (const char *v,
          Py_ssize_t len)
     `Return value: New reference.' 成功时返回一个以字符串 `v' 的副本为
     值且长度为 `len' 的新字节串对象，失败时返回 ‘NULL’。 如果 `v' 为
     ‘NULL’，则不初始化字节串对象的内容。

 -- C 函式: PyObject* PyBytes_FromFormat (const char *format, ...)
     `Return value: New reference.' 接受一个 C ‘printf()’ 风格的
     `format' 字符串和可变数量的参数，计算结果 Python 字节串对象的大小并
     返回参数值经格式化后的字节串对象。 可变数量的参数必须均为 C 类型并
     且必须恰好与 `format' 字符串中的格式字符相对应。 允许使用下列格式字
     符串:

     格式字符                类型                注释
                                                 
     ---------------------------------------------------------------------------------
                                                 
     ‘%%’                    `不适用'            文字%字符。
                                                 
                                                 
     ‘%c’                    int                 一个字节，被表示为一个 C 语言的整
                                                 型
                                                 
                                                 
     ‘%d’                    int                 相当于 ‘printf("%d")’.  (1)
                                                 
                                                 
     ‘%u’                    unsigned int        相当于 ‘printf("%u")’.  (2)
                                                 
                                                 
     ‘%ld’                   长整型              相当于 ‘printf("%ld")’.  (3)
                                                 
                                                 
     ‘%lu’                   unsigned long       相当于 ‘printf("%lu")’.  (4)
                                                 
                                                 
     ‘%zd’                   Py_ssize_t          相当于 ‘printf("%zd")’.  (5)
                                                 
                                                 
     ‘%zu’                   size_t              相当于 ‘printf("%zu")’.  (6)
                                                 
                                                 
     ‘%i’                    int                 相当于 ‘printf("%i")’.  (7)
                                                 
                                                 
     ‘%x’                    int                 相当于 ‘printf("%x")’.  (8)
                                                 
                                                 
     ‘%s’                    const char*         以 null 为终止符的 C 字符数组。
                                                 
                                                 
     ‘%p’                    const void*         一个 C 指针的十六进制表示形式。 基
                                                 本等价于 ‘printf("%p")’ 但它会确保
                                                 以字面值 ‘0x’ 开头，不论系统平台上
                                                 ‘printf’ 的输出是什么。
                                                 

     无法识别的格式字符会导致将格式字符串的其余所有内容原样复制到结果对
     象，并丢弃所有多余的参数。

 -- C 函式: PyObject* PyBytes_FromFormatV (const char *format,
          va_list vargs)
     `Return value: New reference.' 与 *note PyBytes_FromFormat(): 1144.
     完全相同，除了它需要两个参数。

 -- C 函式: PyObject* PyBytes_FromObject (PyObject *o)
     `Return value: New reference.' 返回字节表示实现缓冲区协议的对象
     *o*。

 -- C 函式: Py_ssize_t PyBytes_Size (PyObject *o)

     返回字节对象*o*中字节的长度。

 -- C 函式: Py_ssize_t PyBytes_GET_SIZE (PyObject *o)

     宏版本的 *note PyBytes_Size(): 3fe2. 但是不带错误检测。

 -- C 函式: char* PyBytes_AsString (PyObject *o)

     返回对应 `o' 的内容的指针。 该指针指向 `o' 的内部缓冲区，其中包含
     ‘len(o) + 1’ 个字节。 缓冲区的最后一个字节总是为空，不论是否存在其
     他空字节。 该数据不可通过任何形式来修改，除非是刚使用
     ‘PyBytes_FromStringAndSize(NULL, size)’ 创建该对象。 它不可被撤销分
     配。 如果 `o' 根本不是一个字节串对象，则 *note PyBytes_AsString():
     3fe4. 将返回 ‘NULL’ 并引发 *note TypeError: 1fe.。

 -- C 函式: char* PyBytes_AS_STRING (PyObject *string)

     宏版本的 *note PyBytes_AsString(): 3fe4. 但是不带错误检测。

 -- C 函式: int PyBytes_AsStringAndSize (PyObject *obj, char **buffer,
          Py_ssize_t *length)

     通过输出变量 `buffer' 和 `length' 返回以 null 为终止符的对象 `obj'
     的内容。

     如果 `length' 为 ‘NULL’，字节串对象就不包含嵌入的空字节；如果包含，
     则该函数将返回 ‘-1’ 并引发 *note ValueError: 16d.。

     该缓冲区指向 `obj' 的内部缓冲，它的末尾包含一个额外的空字节（不算在
     `length' 当中）。 该数据不可通过任何方式来修改，除非是刚使用
     ‘PyBytes_FromStringAndSize(NULL, size)’ 创建该对象。 它不可被撤销分
     配。 如果 `obj' 根本不是一个字节串对象，则 *note
     PyBytes_AsStringAndSize(): 3fe6. 将返回 ‘-1’ 并引发 *note
     TypeError: 1fe.。

     3.5 版更變: 以前，当字节串对象中出现嵌入的空字节时将引发 *note
     TypeError: 1fe.。

 -- C 函式: void PyBytes_Concat (PyObject **bytes, PyObject *newpart)

     在 `*bytes' 中创建新的字节串对象，其中包含添加到 `bytes' 的
     `newpart' 的内容；调用者将获得新的引用。 对 `bytes' 原值的引用将被
     收回。 如果无法创建新对象，对 `bytes' 的旧引用仍将被丢弃且 `*bytes'
     的值将被设为 ‘NULL’；并将设置适当的异常。

 -- C 函式: void PyBytes_ConcatAndDel (PyObject **bytes,
          PyObject *newpart)

     在 `*bytes' 中创建新的字节串对象，其中包含添加到 `bytes' 的
     `newpart' 的内容。 此版本会减少 `newpart' 的引用计数。

 -- C 函式: int _PyBytes_Resize (PyObject **bytes, Py_ssize_t newsize)

     改变字节串大小的一种方式，即使其为“不可变对象”。 此方式仅用于创建全
     新的字节串对象；如果字节串在代码的其他部分已知则不可使用此方式。 如
     果输入字节串对象的引用计数不为一则调用此函数将报错。 传入一个现有字
     节串对象的地址作为 lvalue（它可能会被写入），并传入希望的新大小。 当
     成功时，`*bytes' 将存放改变大小后的字节串对象并返回 ‘0’；`*bytes' 中
     的地址可能与其输入值不同。 如果重新分配失败，则 `*bytes' 上的原字节
     串对象将被撤销分配，`*bytes' 会被设为 ‘NULL’，同时设置 *note
     MemoryError: f69. 并返回 ‘-1’。

   ---------- Footnotes ----------

   (1) (1) 对于整数说明符（d，u，ld，lu，zd，zu，i，x）：当给出精度时，0
转换标志是有效的。

   (2) (1) 对于整数说明符（d，u，ld，lu，zd，zu，i，x）：当给出精度时，0
转换标志是有效的。

   (3) (1) 对于整数说明符（d，u，ld，lu，zd，zu，i，x）：当给出精度时，0
转换标志是有效的。

   (4) (1) 对于整数说明符（d，u，ld，lu，zd，zu，i，x）：当给出精度时，0
转换标志是有效的。

   (5) (1) 对于整数说明符（d，u，ld，lu，zd，zu，i，x）：当给出精度时，0
转换标志是有效的。

   (6) (1) 对于整数说明符（d，u，ld，lu，zd，zu，i，x）：当给出精度时，0
转换标志是有效的。

   (7) (1) 对于整数说明符（d，u，ld，lu，zd，zu，i，x）：当给出精度时，0
转换标志是有效的。

   (8) (1) 对于整数说明符（d，u，ld，lu，zd，zu，i，x）：当给出精度时，0
转换标志是有效的。


File: python.info,  Node: 字节数组对象,  Next: Unicode物件與編碼,  Prev: 字节对象,  Up: 序列对象

7.8.3.2 字节数组对象
....................

 -- C 類型: PyByteArrayObject

     这个 *note PyObject: 5b4. 的子类型表示一个 Python 字节数组对象。

 -- C 變數: PyTypeObject PyByteArray_Type

     Python bytearray 类型表示为 *note PyTypeObject: 3f5. 的实例；这与
     Python层面的 *note bytearray: 173. 是相同的对象。

* Menu:

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


File: python.info,  Node: 类型检查宏,  Next: 直接 API 函数,  Up: 字节数组对象

7.8.3.3 类型检查宏
..................

 -- C 函式: int PyByteArray_Check (PyObject *o)

     如果对象 `o' 是一个 bytearray 对象或者 bytearray 类型的子类型的实例
     则返回真值。 此函数总是会成功执行。

 -- C 函式: int PyByteArray_CheckExact (PyObject *o)

     如果对象 `o' 是一个 bytearray 对象但不是 bytearray 类型的子类型的实
     例则返回真值。 此函数总是会成功执行。


File: python.info,  Node: 直接 API 函数,  Next: 宏,  Prev: 类型检查宏,  Up: 字节数组对象

7.8.3.4 直接 API 函数
.....................

 -- C 函式: PyObject* PyByteArray_FromObject (PyObject *o)
     `Return value: New reference.' 根据任何实现了 *note 缓冲区协议:
     171c. 的对象 `o'，返回一个新的字节数组对象。

 -- C 函式: PyObject* PyByteArray_FromStringAndSize (const char *string,
          Py_ssize_t len)
     `Return value: New reference.' 根据 `string' 及其长度 `len' 创建一
     个新的 bytearray 对象。 当失败时返回 ‘NULL’。

 -- C 函式: PyObject* PyByteArray_Concat (PyObject *a, PyObject *b)
     `Return value: New reference.' 连接字节数组 `a' 和 `b' 并返回一个带
     有结果的新的字节数组。

 -- C 函式: Py_ssize_t PyByteArray_Size (PyObject *bytearray)

     在检查 ‘NULL’ 指针后返回 `bytearray' 的大小。

 -- C 函式: char* PyByteArray_AsString (PyObject *bytearray)

     在检查 ‘NULL’ 指针后返回将 `bytearray' 返回为一个字符数组。 返回的
     数组总是会附加一个额外的空字节。

 -- C 函式: int PyByteArray_Resize (PyObject *bytearray, Py_ssize_t len)

     将 `bytearray' 的内部缓冲区的大小调整为 `len'。


File: python.info,  Node: 宏,  Prev: 直接 API 函数,  Up: 字节数组对象

7.8.3.5 宏
..........

这些宏减低安全性以换取性能，它们不检查指针。

 -- C 函式: char* PyByteArray_AS_STRING (PyObject *bytearray)

     C函数 *note PyByteArray_AsString(): 3ff4. 的宏版本。

 -- C 函式: Py_ssize_t PyByteArray_GET_SIZE (PyObject *bytearray)

     C函数 *note PyByteArray_Size(): 3ff3. 的宏版本。


File: python.info,  Node: Unicode物件與編碼,  Next: 元組（Tuple）物件,  Prev: 字节数组对象,  Up: 序列对象

7.8.3.6 Unicode物件與編碼
.........................

* Menu:

* Unicode对象::
* Built-in Codecs::
* Methods and Slot Functions::


File: python.info,  Node: Unicode对象,  Next: Built-in Codecs,  Up: Unicode物件與編碼

7.8.3.7 Unicode对象
...................

自从python3.3中实现了 PEP 393(1) 以来，Unicode对象在内部使用各种表示形式
，以便在保持内存效率的同时处理完整范围的Unicode字符。对于所有代码点都低
于128、256或65536的字符串，有一些特殊情况；否则，代码点必须低于1114112（
这是完整的Unicode范围）。

*note Py_UNICODE*: bc5. and UTF-8 representations are created on demand
and cached in the Unicode object.  The *note Py_UNICODE*: bc5.
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:

   * "canonical" Unicode objects are all objects created by a
     non-deprecated Unicode API. They use the most efficient
     representation allowed by the implementation.

   * "legacy" Unicode objects have been created through one of the
     deprecated APIs (typically *note PyUnicode_FromUnicode(): 263.) and
     only bear the *note Py_UNICODE*: bc5. representation; you will have
     to call *note PyUnicode_READY(): bad. on them before calling any
     other API.

     備註: The "legacy" Unicode object will be removed in Python 3.12
     with deprecated APIs.  All Unicode objects will be "canonical"
     since then.  See PEP 623(2) for more information.

* Menu:

* Unicode类型::
* Unicode字符属性::
* Creating and accessing Unicode strings::
* Deprecated Py_UNICODE APIs::
* Locale Encoding::
* File System Encoding::
* wchar_t Support::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0393

   (2) https://www.python.org/dev/peps/pep-0623


File: python.info,  Node: Unicode类型,  Next: Unicode字符属性,  Up: Unicode对象

7.8.3.8 Unicode类型
...................

These are the basic Unicode object types used for the Unicode
implementation in Python:

 -- C 類型: Py_UCS4
 -- C 類型: Py_UCS2
 -- 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 *note Py_UCS4:
     baa.

     3.3 版新加入.

 -- C 類型: Py_UNICODE

     This is a typedef of ‘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.

 -- C 類型: PyASCIIObject
 -- C 類型: PyCompactUnicodeObject
 -- C 類型: PyUnicodeObject

     These subtypes of *note PyObject: 5b4. 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 *note PyObject: 5b4. pointers.

     3.3 版新加入.

 -- C 變數: PyTypeObject PyUnicode_Type

     This instance of *note PyTypeObject: 3f5. represents the Python
     Unicode type.  It is exposed to Python code as ‘str’.

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:

 -- C 函式: int PyUnicode_Check (PyObject *o)

     Return true if the object `o' is a Unicode object or an instance of
     a Unicode subtype.  This function always succeeds.

 -- C 函式: int PyUnicode_CheckExact (PyObject *o)

     Return true if the object `o' is a Unicode object, but not an
     instance of a subtype.  This function always succeeds.

 -- C 函式: int PyUnicode_READY (PyObject *o)

     Ensure the string object `o' is in the "canonical" representation.
     This is required before using any of the access macros described
     below.

     Returns ‘0’ on success and ‘-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 *note PyUnicode_FromUnicode(): 263.

 -- C 函式: Py_ssize_t PyUnicode_GET_LENGTH (PyObject *o)

     Return the length of the Unicode string, in code points.  `o' has
     to be a Unicode object in the "canonical" representation (not
     checked).

     3.3 版新加入.

 -- C 函式: Py_UCS1* PyUnicode_1BYTE_DATA (PyObject *o)
 -- C 函式: Py_UCS2* PyUnicode_2BYTE_DATA (PyObject *o)
 -- C 函式: Py_UCS4* PyUnicode_4BYTE_DATA (PyObject *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 *note PyUnicode_KIND(): bb5. to select the right macro.
     Make sure *note PyUnicode_READY(): bad. has been called before
     accessing this.

     3.3 版新加入.

 -- C 巨集: PyUnicode_WCHAR_KIND
 -- C 巨集: PyUnicode_1BYTE_KIND
 -- C 巨集: PyUnicode_2BYTE_KIND
 -- C 巨集: PyUnicode_4BYTE_KIND

     Return values of the *note PyUnicode_KIND(): bb5. macro.

     3.3 版新加入.

     Deprecated since version 3.10, will be removed in version 3.12:
     ‘PyUnicode_WCHAR_KIND’ is deprecated.

 -- C 函式: unsigned int PyUnicode_KIND (PyObject *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.  `o' has to be a Unicode object in the "canonical"
     representation (not checked).

     3.3 版新加入.

 -- C 函式: void* PyUnicode_DATA (PyObject *o)

     Return a void pointer to the raw Unicode buffer.  `o' has to be a
     Unicode object in the "canonical" representation (not checked).

     3.3 版新加入.

 -- C 函式: void PyUnicode_WRITE (int kind, void *data,
          Py_ssize_t index, Py_UCS4 value)

     Write into a canonical representation `data' (as obtained with
     *note PyUnicode_DATA(): bb1.).  This macro does not do any sanity
     checks and is intended for usage in loops.  The caller should cache
     the `kind' value and `data' pointer as obtained from other macro
     calls.  `index' is the index in the string (starts at 0) and
     `value' is the new code point value which should be written to that
     location.

     3.3 版新加入.

 -- C 函式: Py_UCS4 PyUnicode_READ (int kind, void *data,
          Py_ssize_t index)

     Read a code point from a canonical representation `data' (as
     obtained with *note PyUnicode_DATA(): bb1.).  No checks or ready
     calls are performed.

     3.3 版新加入.

 -- C 函式: Py_UCS4 PyUnicode_READ_CHAR (PyObject *o, Py_ssize_t index)

     Read a character from a Unicode object `o', which must be in the
     "canonical" representation.  This is less efficient than *note
     PyUnicode_READ(): bba. if you do multiple consecutive reads.

     3.3 版新加入.

 -- C 巨集: PyUnicode_MAX_CHAR_VALUE (o)

     Return the maximum code point that is suitable for creating another
     string based on `o', which must be in the "canonical"
     representation.  This is always an approximation but more efficient
     than iterating over the string.

     3.3 版新加入.

 -- C 函式: Py_ssize_t PyUnicode_GET_SIZE (PyObject *o)

     Return the size of the deprecated *note Py_UNICODE: bc5.
     representation, in code units (this includes surrogate pairs as 2
     units).  `o' has to be a Unicode object (not checked).

     Deprecated since version 3.3, will be removed in version 3.12: Part
     of the old-style Unicode API, please migrate to using *note
     PyUnicode_GET_LENGTH(): ba3.

 -- C 函式: Py_ssize_t PyUnicode_GET_DATA_SIZE (PyObject *o)

     Return the size of the deprecated *note Py_UNICODE: bc5.
     representation in bytes.  `o' has to be a Unicode object (not
     checked).

     Deprecated since version 3.3, will be removed in version 3.12: Part
     of the old-style Unicode API, please migrate to using *note
     PyUnicode_GET_LENGTH(): ba3.

 -- C 函式: Py_UNICODE* PyUnicode_AS_UNICODE (PyObject *o)
 -- C 函式: const char* PyUnicode_AS_DATA (PyObject *o)

     Return a pointer to a *note Py_UNICODE: bc5. 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 ‘AS_DATA’ form casts the pointer to ‘const char *’.
     The `o' argument has to be a Unicode object (not checked).

     3.3 版更變: This macro is now inefficient – because in many cases
     the *note Py_UNICODE: bc5. representation does not exist and needs
     to be created – and can fail (return ‘NULL’ with an exception set).
     Try to port the code to use the new ‘PyUnicode_nBYTE_DATA()’ macros
     or use *note PyUnicode_WRITE(): bbc. or *note PyUnicode_READ():
     bba.

     Deprecated since version 3.3, will be removed in version 3.12: Part
     of the old-style Unicode API, please migrate to using the
     ‘PyUnicode_nBYTE_DATA()’ family of macros.

 -- C 函式: int PyUnicode_IsIdentifier (PyObject *o)

     Return ‘1’ if the string is a valid identifier according to the
     language definition, section *note 标识符和关键字: 1505.  Return
     ‘0’ otherwise.

     3.9 版更變: The function does not call *note Py_FatalError(): 266.
     anymore if the string is not ready.


File: python.info,  Node: Unicode字符属性,  Next: Creating and accessing Unicode strings,  Prev: Unicode类型,  Up: Unicode对象

7.8.3.9 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.

 -- C 函式: int Py_UNICODE_ISSPACE (Py_UCS4 ch)

     Return ‘1’ or ‘0’ depending on whether `ch' is a whitespace
     character.

 -- C 函式: int Py_UNICODE_ISLOWER (Py_UCS4 ch)

     Return ‘1’ or ‘0’ depending on whether `ch' is a lowercase
     character.

 -- C 函式: int Py_UNICODE_ISUPPER (Py_UCS4 ch)

     Return ‘1’ or ‘0’ depending on whether `ch' is an uppercase
     character.

 -- C 函式: int Py_UNICODE_ISTITLE (Py_UCS4 ch)

     Return ‘1’ or ‘0’ depending on whether `ch' is a titlecase
     character.

 -- C 函式: int Py_UNICODE_ISLINEBREAK (Py_UCS4 ch)

     Return ‘1’ or ‘0’ depending on whether `ch' is a linebreak
     character.

 -- C 函式: int Py_UNICODE_ISDECIMAL (Py_UCS4 ch)

     Return ‘1’ or ‘0’ depending on whether `ch' is a decimal character.

 -- C 函式: int Py_UNICODE_ISDIGIT (Py_UCS4 ch)

     Return ‘1’ or ‘0’ depending on whether `ch' is a digit character.

 -- C 函式: int Py_UNICODE_ISNUMERIC (Py_UCS4 ch)

     Return ‘1’ or ‘0’ depending on whether `ch' is a numeric character.

 -- C 函式: int Py_UNICODE_ISALPHA (Py_UCS4 ch)

     Return ‘1’ or ‘0’ depending on whether `ch' is an alphabetic
     character.

 -- C 函式: int Py_UNICODE_ISALNUM (Py_UCS4 ch)

     Return ‘1’ or ‘0’ depending on whether `ch' is an alphanumeric
     character.

 -- C 函式: int Py_UNICODE_ISPRINTABLE (Py_UCS4 ch)

     Return ‘1’ or ‘0’ depending on whether `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 *note repr(): 8b9. is invoked on a string.  It has no
     bearing on the handling of strings written to *note sys.stdout:
     41f. or *note sys.stderr: 1ea.)

These APIs can be used for fast direct character conversions:

 -- C 函式: Py_UCS4 Py_UNICODE_TOLOWER (Py_UCS4 ch)

     Return the character `ch' converted to lower case.

     3.3 版後已棄用: This function uses simple case mappings.

 -- C 函式: Py_UCS4 Py_UNICODE_TOUPPER (Py_UCS4 ch)

     Return the character `ch' converted to upper case.

     3.3 版後已棄用: This function uses simple case mappings.

 -- C 函式: Py_UCS4 Py_UNICODE_TOTITLE (Py_UCS4 ch)

     Return the character `ch' converted to title case.

     3.3 版後已棄用: This function uses simple case mappings.

 -- C 函式: int Py_UNICODE_TODECIMAL (Py_UCS4 ch)

     Return the character `ch' converted to a decimal positive integer.
     Return ‘-1’ if this is not possible.  This macro does not raise
     exceptions.

 -- C 函式: int Py_UNICODE_TODIGIT (Py_UCS4 ch)

     Return the character `ch' converted to a single digit integer.
     Return ‘-1’ if this is not possible.  This macro does not raise
     exceptions.

 -- C 函式: double Py_UNICODE_TONUMERIC (Py_UCS4 ch)

     Return the character `ch' converted to a double.  Return ‘-1.0’ if
     this is not possible.  This macro does not raise exceptions.

These APIs can be used to work with surrogates:

 -- C 巨集: Py_UNICODE_IS_SURROGATE (ch)

     Check if `ch' is a surrogate (‘0xD800 <= ch <= 0xDFFF’).

 -- C 巨集: Py_UNICODE_IS_HIGH_SURROGATE (ch)

     Check if `ch' is a high surrogate (‘0xD800 <= ch <= 0xDBFF’).

 -- C 巨集: Py_UNICODE_IS_LOW_SURROGATE (ch)

     Check if `ch' is a low surrogate (‘0xDC00 <= ch <= 0xDFFF’).

 -- C 巨集: Py_UNICODE_JOIN_SURROGATES (high, low)

     Join two surrogate characters and return a single Py_UCS4 value.
     `high' and `low' are respectively the leading and trailing
     surrogates in a surrogate pair.


File: python.info,  Node: Creating and accessing Unicode strings,  Next: Deprecated Py_UNICODE APIs,  Prev: Unicode字符属性,  Up: Unicode对象

7.8.3.10 Creating and accessing Unicode strings
...............................................

To create Unicode objects and access their basic sequence properties,
use these APIs:

 -- C 函式: PyObject* PyUnicode_New (Py_ssize_t size, Py_UCS4 maxchar)
     `Return value: New reference.'  Create a new Unicode object.
     `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 版新加入.

 -- C 函式: PyObject* PyUnicode_FromKindAndData (int kind, const
          void *buffer, Py_ssize_t size)
     `Return value: New reference.'  Create a new Unicode object with
     the given `kind' (possible values are *note PyUnicode_1BYTE_KIND:
     bb7. etc., as returned by *note PyUnicode_KIND(): bb5.).  The
     `buffer' must point to an array of `size' units of 1, 2 or 4 bytes
     per character, as given by the kind.

     3.3 版新加入.

 -- C 函式: PyObject* PyUnicode_FromStringAndSize (const char *u,
          Py_ssize_t size)
     `Return value: New reference.'  Create a Unicode object from the
     char buffer `u'.  The bytes will be interpreted as being UTF-8
     encoded.  The buffer is copied into the new object.  If the buffer
     is not ‘NULL’, the return value might be a shared object, i.e.
     modification of the data is not allowed.

     If `u' is ‘NULL’, this function behaves like *note
     PyUnicode_FromUnicode(): 263. with the buffer set to ‘NULL’.  This
     usage is deprecated in favor of *note PyUnicode_New(): ba4, and
     will be removed in Python 3.12.

 -- C 函式: PyObject *PyUnicode_FromString (const char *u)
     `Return value: New reference.'  Create a Unicode object from a
     UTF-8 encoded null-terminated char buffer `u'.

 -- C 函式: PyObject* PyUnicode_FromFormat (const char *format, ...)
     `Return value: New reference.'  Take a C ‘printf()’-style `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
     `format' ASCII-encoded string.  The following format characters are
     allowed:

     格式字符                类型                      注释
                                                       
     -----------------------------------------------------------------------------------------
                                                       
     ‘%%’                    `不适用'                  文字%字符。
                                                       
                                                       
     ‘%c’                    int                       单个字符，表示为C 语言的整型。
                                                       
                                                       
     ‘%d’                    int                       相当于 ‘printf("%d")’.  (1)
                                                       
                                                       
     ‘%u’                    unsigned int              相当于 ‘printf("%u")’.  (2)
                                                       
                                                       
     ‘%ld’                   长整型                    相当于 ‘printf("%ld")’.  (3)
                                                       
                                                       
     ‘%li’                   长整型                    相当于 ‘printf("%li")’.  (4)
                                                       
                                                       
     ‘%lu’                   unsigned long             相当于 ‘printf("%lu")’.  (5)
                                                       
                                                       
     ‘%lld’                  long long                 相当于 ‘printf("%lld")’.  (6)
                                                       
                                                       
     ‘%lli’                  long long                 相当于 ‘printf("%lli")’.  (7)
                                                       
                                                       
     ‘%llu’                  unsigned long long        相当于 ‘printf("%llu")’.  (8)
                                                       
                                                       
     ‘%zd’                   Py_ssize_t                相当于 ‘printf("%zd")’.  (9)
                                                       
                                                       
     ‘%zi’                   Py_ssize_t                相当于 ‘printf("%zi")’.  (10)
                                                       
                                                       
     ‘%zu’                   size_t                    相当于 ‘printf("%zu")’.  (11)
                                                       
                                                       
     ‘%i’                    int                       相当于 ‘printf("%i")’.  (12)
                                                       
                                                       
     ‘%x’                    int                       相当于 ‘printf("%x")’.  (13)
                                                       
                                                       
     ‘%s’                    const char*               以 null 为终止符的 C 字符数组。
                                                       
                                                       
     ‘%p’                    const void*               一个 C 指针的十六进制表示形式。 基本
                                                       等价于 ‘printf("%p")’ 但它会确保以字
                                                       面值 ‘0x’ 开头，不论系统平台上
                                                       ‘printf’ 的输出是什么。
                                                       
                                                       
     ‘%A’                    PyObject*                 *note ascii(): e11. 调用的结果。
                                                       
                                                       
     ‘%U’                    PyObject*                 A Unicode object.
                                                       
                                                       
     ‘%V’                    PyObject*, const char*    A Unicode object (which may be
                                                       ‘NULL’) and a null-terminated C
                                                       character array as a second
                                                       parameter (which will be used, if
                                                       the first parameter is ‘NULL’).
                                                       
                                                       
     ‘%S’                    PyObject*                 The result of calling
                                                       *note PyObject_Str(): a4a.
                                                       
                                                       
     ‘%R’                    PyObject*                 The result of calling
                                                       *note PyObject_Repr(): a49.
                                                       

     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.

          備註: The width formatter unit is number of characters rather
          than bytes.  The precision formatter unit is number of bytes
          for ‘"%s"’ and ‘"%V"’ (if the ‘PyObject*’ argument is ‘NULL’),
          and a number of characters for ‘"%A"’, ‘"%U"’, ‘"%S"’, ‘"%R"’
          and ‘"%V"’ (if the ‘PyObject*’ argument is not ‘NULL’).

     3.2 版更變: Support for ‘"%lld"’ and ‘"%llu"’ added.

     3.3 版更變: Support for ‘"%li"’, ‘"%lli"’ and ‘"%zi"’ added.

     3.4 版更變: Support width and precision formatter for ‘"%s"’,
     ‘"%A"’, ‘"%U"’, ‘"%V"’, ‘"%S"’, ‘"%R"’ added.

 -- C 函式: PyObject* PyUnicode_FromFormatV (const char *format,
          va_list vargs)
     `Return value: New reference.'  Identical to *note
     PyUnicode_FromFormat(): 8b8. except that it takes exactly two
     arguments.

 -- C 函式: PyObject* PyUnicode_FromEncodedObject (PyObject *obj, const
          char *encoding, const char *errors)
     `Return value: New reference.'  Decode an encoded object `obj' to a
     Unicode object.

     *note bytes: 172, *note bytearray: 173. and other *note bytes-like
     objects: 6df. are decoded according to the given `encoding' and
     using the error handling defined by `errors'.  Both can be ‘NULL’
     to have the interface use the default values (see *note Built-in
     Codecs: 4019. for details).

     All other objects, including Unicode objects, cause a *note
     TypeError: 1fe. to be set.

     The API returns ‘NULL’ if there was an error.  The caller is
     responsible for decref’ing the returned objects.

 -- C 函式: Py_ssize_t PyUnicode_GetLength (PyObject *unicode)

     Return the length of the Unicode object, in code points.

     3.3 版新加入.

 -- C 函式: Py_ssize_t PyUnicode_CopyCharacters (PyObject *to,
          Py_ssize_t to_start, PyObject *from, Py_ssize_t from_start,
          Py_ssize_t how_many)

     Copy characters from one Unicode object into another.  This
     function performs character conversion when necessary and falls
     back to ‘memcpy()’ if possible.  Returns ‘-1’ and sets an exception
     on error, otherwise returns the number of copied characters.

     3.3 版新加入.

 -- C 函式: Py_ssize_t PyUnicode_Fill (PyObject *unicode,
          Py_ssize_t start, Py_ssize_t length, Py_UCS4 fill_char)

     Fill a string with a character: write `fill_char' into
     ‘unicode[start:start+length]’.

     Fail if `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 ‘-1’ and raise an
     exception on error.

     3.3 版新加入.

 -- C 函式: int PyUnicode_WriteChar (PyObject *unicode,
          Py_ssize_t index, Py_UCS4 character)

     Write a character to a string.  The string must have been created
     through *note PyUnicode_New(): ba4.  Since Unicode strings are
     supposed to be immutable, the string must not be shared, or have
     been hashed yet.

     This function checks that `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 版新加入.

 -- C 函式: Py_UCS4 PyUnicode_ReadChar (PyObject *unicode,
          Py_ssize_t index)

     Read a character from a string.  This function checks that
     `unicode' is a Unicode object and the index is not out of bounds,
     in contrast to the macro version *note PyUnicode_READ_CHAR(): bbb.

     3.3 版新加入.

 -- C 函式: PyObject* PyUnicode_Substring (PyObject *str,
          Py_ssize_t start, Py_ssize_t end)
     `Return value: New reference.'  Return a substring of `str', from
     character index `start' (included) to character index `end'
     (excluded).  Negative indices are not supported.

     3.3 版新加入.

 -- C 函式: Py_UCS4* PyUnicode_AsUCS4 (PyObject *u, Py_UCS4 *buffer,
          Py_ssize_t buflen, int copy_null)

     Copy the string `u' into a UCS4 buffer, including a null character,
     if `copy_null' is set.  Returns ‘NULL’ and sets an exception on
     error (in particular, a *note SystemError: 6f2. if `buflen' is
     smaller than the length of `u').  `buffer' is returned on success.

     3.3 版新加入.

 -- C 函式: Py_UCS4* PyUnicode_AsUCS4Copy (PyObject *u)

     Copy the string `u' into a new UCS4 buffer that is allocated using
     *note PyMem_Malloc(): 5fe.  If this fails, ‘NULL’ is returned with
     a *note MemoryError: f69. set.  The returned buffer always has an
     extra null code point appended.

     3.3 版新加入.

   ---------- Footnotes ----------

   (1) (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.

   (2) (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.

   (3) (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.

   (4) (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.

   (5) (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.

   (6) (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.

   (7) (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.

   (8) (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.

   (9) (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.

   (10) (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.

   (11) (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.

   (12) (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.

   (13) (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.


File: python.info,  Node: Deprecated Py_UNICODE APIs,  Next: Locale Encoding,  Prev: Creating and accessing Unicode strings,  Up: Unicode对象

7.8.3.11 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 PEP
393(1).  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.

 -- C 函式: PyObject* PyUnicode_FromUnicode (const Py_UNICODE *u,
          Py_ssize_t size)
     `Return value: New reference.'  Create a Unicode object from the
     Py_UNICODE buffer `u' of the given size.  `u' may be ‘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 ‘NULL’, the return value might be a shared
     object.  Therefore, modification of the resulting Unicode object is
     only allowed when `u' is ‘NULL’.

     If the buffer is ‘NULL’, *note PyUnicode_READY(): bad. must be
     called once the string content has been filled before using any of
     the access macros such as *note PyUnicode_KIND(): bb5.

     Deprecated since version 3.3, will be removed in version 3.12: Part
     of the old-style Unicode API, please migrate to using *note
     PyUnicode_FromKindAndData(): bae, *note PyUnicode_FromWideChar():
     bc6, or *note PyUnicode_New(): ba4.

 -- C 函式: Py_UNICODE* PyUnicode_AsUnicode (PyObject *unicode)

     Return a read-only pointer to the Unicode object’s internal *note
     Py_UNICODE: bc5. buffer, or ‘NULL’ on error.  This will create the
     *note Py_UNICODE*: bc5. 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 *note Py_UNICODE: bc5. 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 *note
     PyUnicode_AsUCS4(): baf, *note PyUnicode_AsWideChar(): 1187, *note
     PyUnicode_ReadChar(): ba6. or similar new APIs.

     Deprecated since version 3.3, will be removed in version 3.10.

 -- C 函式: PyObject* PyUnicode_TransformDecimalToASCII (Py_UNICODE *s,
          Py_ssize_t size)
     `Return value: New reference.'  Create a Unicode object by
     replacing all decimal digits in *note Py_UNICODE: bc5. buffer of
     the given `size' by ASCII digits 0–9 according to their decimal
     value.  Return ‘NULL’ if an exception occurs.

     Deprecated since version 3.3, will be removed in version 3.11: Part
     of the old-style *note Py_UNICODE: bc5. API; please migrate to
     using *note Py_UNICODE_TODECIMAL(): 400f.

 -- C 函式: Py_UNICODE* PyUnicode_AsUnicodeAndSize (PyObject *unicode,
          Py_ssize_t *size)

     Like *note PyUnicode_AsUnicode(): 264, but also saves the *note
     Py_UNICODE(): bc5. array length (excluding the extra null
     terminator) in `size'.  Note that the resulting *note Py_UNICODE*:
     bc5. 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 *note
     PyUnicode_AsUCS4(): baf, *note PyUnicode_AsWideChar(): 1187, *note
     PyUnicode_ReadChar(): ba6. or similar new APIs.

 -- C 函式: Py_UNICODE* PyUnicode_AsUnicodeCopy (PyObject *unicode)

     Create a copy of a Unicode string ending with a null code point.
     Return ‘NULL’ and raise a *note MemoryError: f69. exception on
     memory allocation failure, otherwise return a new allocated buffer
     (use *note PyMem_Free(): e6e. to free the buffer).  Note that the
     resulting *note Py_UNICODE*: bc5. 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 *note PyUnicode_AsUCS4Copy(): bb0. or
     similar new APIs.

 -- C 函式: Py_ssize_t PyUnicode_GetSize (PyObject *unicode)

     Return the size of the deprecated *note Py_UNICODE: bc5.
     representation, in code units (this includes surrogate pairs as 2
     units).

     Deprecated since version 3.3, will be removed in version 3.12: Part
     of the old-style Unicode API, please migrate to using *note
     PyUnicode_GET_LENGTH(): ba3.

 -- C 函式: PyObject* PyUnicode_FromObject (PyObject *obj)
     `Return value: New reference.'  Copy an instance of a Unicode
     subtype to a new true Unicode object if necessary.  If `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 *note
     TypeError: 1fe.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0393


File: python.info,  Node: Locale Encoding,  Next: File System Encoding,  Prev: Deprecated Py_UNICODE APIs,  Up: Unicode对象

7.8.3.12 Locale Encoding
........................

The current locale encoding can be used to decode text from the
operating system.

 -- C 函式: PyObject* PyUnicode_DecodeLocaleAndSize (const char *str,
          Py_ssize_t len, const char *errors)
     `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 ‘"strict"’ and
     ‘"surrogateescape"’ ( PEP 383(1)).  The decoder uses ‘"strict"’
     error handler if `errors' is ‘NULL’.  `str' must end with a null
     character but cannot contain embedded null characters.

     Use *note PyUnicode_DecodeFSDefaultAndSize(): 3e5c. to decode a
     string from ‘Py_FileSystemDefaultEncoding’ (the locale encoding
     read at Python startup).

     This function ignores the Python UTF-8 mode.

     也參考
     ......

     The *note Py_DecodeLocale(): 53e. function.

     3.3 版新加入.

     3.7 版更變: The function now also uses the current locale encoding
     for the ‘surrogateescape’ error handler, except on Android.
     Previously, *note Py_DecodeLocale(): 53e. was used for the
     ‘surrogateescape’, and the current locale encoding was used for
     ‘strict’.

 -- C 函式: PyObject* PyUnicode_DecodeLocale (const char *str, const
          char *errors)
     `Return value: New reference.'  Similar to *note
     PyUnicode_DecodeLocaleAndSize(): 540, but compute the string length
     using ‘strlen()’.

     3.3 版新加入.

 -- C 函式: PyObject* PyUnicode_EncodeLocale (PyObject *unicode, const
          char *errors)
     `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 ‘"strict"’ and
     ‘"surrogateescape"’ ( PEP 383(2)).  The encoder uses ‘"strict"’
     error handler if `errors' is ‘NULL’.  Return a *note bytes: 172.
     object.  `unicode' cannot contain embedded null characters.

     Use *note PyUnicode_EncodeFSDefault(): 1180. to encode a string to
     ‘Py_FileSystemDefaultEncoding’ (the locale encoding read at Python
     startup).

     This function ignores the Python UTF-8 mode.

     也參考
     ......

     The *note Py_EncodeLocale(): 53f. function.

     3.3 版新加入.

     3.7 版更變: The function now also uses the current locale encoding
     for the ‘surrogateescape’ error handler, except on Android.
     Previously, *note Py_EncodeLocale(): 53f. was used for the
     ‘surrogateescape’, and the current locale encoding was used for
     ‘strict’.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0383

   (2) https://www.python.org/dev/peps/pep-0383


File: python.info,  Node: File System Encoding,  Next: wchar_t Support,  Prev: Locale Encoding,  Up: Unicode对象

7.8.3.13 File System Encoding
.............................

To encode and decode file names and other environment strings,
‘Py_FileSystemDefaultEncoding’ should be used as the encoding, and
‘Py_FileSystemDefaultEncodeErrors’ should be used as the error handler (
PEP 383(1) and PEP 529(2)).  To encode file names to *note bytes: 172.
during argument parsing, the ‘"O&"’ converter should be used, passing
*note PyUnicode_FSConverter(): 6c5. as the conversion function:

 -- C 函式: int PyUnicode_FSConverter (PyObject* obj, void* result)

     ParseTuple converter: encode *note str: 205. objects – obtained
     directly or through the *note os.PathLike: 5e5. interface – to
     *note bytes: 172. using *note PyUnicode_EncodeFSDefault(): 1180.;
     *note bytes: 172. objects are output as-is.  `result' must be a
     *note PyBytesObject*: de4. which must be released when it is no
     longer used.

     3.1 版新加入.

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

To decode file names to *note str: 205. during argument parsing, the
‘"O&"’ converter should be used, passing *note PyUnicode_FSDecoder():
6c6. as the conversion function:

 -- C 函式: int PyUnicode_FSDecoder (PyObject* obj, void* result)

     ParseTuple converter: decode *note bytes: 172. objects – obtained
     either directly or indirectly through the *note os.PathLike: 5e5.
     interface – to *note str: 205. using *note
     PyUnicode_DecodeFSDefaultAndSize(): 3e5c.; *note str: 205. objects
     are output as-is.  `result' must be a *note PyUnicodeObject*: 3ffd.
     which must be released when it is no longer used.

     3.2 版新加入.

     3.6 版更變: 接受一个 *note 类路径对象: 472.。

 -- C 函式: PyObject* PyUnicode_DecodeFSDefaultAndSize (const char *s,
          Py_ssize_t size)
     `Return value: New reference.'  Decode a string using
     ‘Py_FileSystemDefaultEncoding’ and the
     ‘Py_FileSystemDefaultEncodeErrors’ error handler.

     If ‘Py_FileSystemDefaultEncoding’ is not set, fall back to the
     locale encoding.

     ‘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 *note
     PyUnicode_DecodeLocaleAndSize(): 540.

     也參考
     ......

     The *note Py_DecodeLocale(): 53e. function.

     3.6 版更變: Use ‘Py_FileSystemDefaultEncodeErrors’ error handler.

 -- C 函式: PyObject* PyUnicode_DecodeFSDefault (const char *s)
     `Return value: New reference.'  Decode a null-terminated string
     using ‘Py_FileSystemDefaultEncoding’ and the
     ‘Py_FileSystemDefaultEncodeErrors’ error handler.

     If ‘Py_FileSystemDefaultEncoding’ is not set, fall back to the
     locale encoding.

     Use *note PyUnicode_DecodeFSDefaultAndSize(): 3e5c. if you know the
     string length.

     3.6 版更變: Use ‘Py_FileSystemDefaultEncodeErrors’ error handler.

 -- C 函式: PyObject* PyUnicode_EncodeFSDefault (PyObject *unicode)
     `Return value: New reference.'  Encode a Unicode object to
     ‘Py_FileSystemDefaultEncoding’ with the
     ‘Py_FileSystemDefaultEncodeErrors’ error handler, and return *note
     bytes: 172.  Note that the resulting *note bytes: 172. object may
     contain null bytes.

     If ‘Py_FileSystemDefaultEncoding’ is not set, fall back to the
     locale encoding.

     ‘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 *note
     PyUnicode_EncodeLocale(): 541.

     也參考
     ......

     The *note Py_EncodeLocale(): 53f. function.

     3.2 版新加入.

     3.6 版更變: Use ‘Py_FileSystemDefaultEncodeErrors’ error handler.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0383

   (2) https://www.python.org/dev/peps/pep-0529


File: python.info,  Node: wchar_t Support,  Prev: File System Encoding,  Up: Unicode对象

7.8.3.14 wchar_t Support
........................

‘wchar_t’ support for platforms which support it:

 -- C 函式: PyObject* PyUnicode_FromWideChar (const wchar_t *w,
          Py_ssize_t size)
     `Return value: New reference.'  Create a Unicode object from the
     ‘wchar_t’ buffer `w' of the given `size'.  Passing ‘-1’ as the
     `size' indicates that the function must itself compute the length,
     using wcslen.  Return ‘NULL’ on failure.

 -- C 函式: Py_ssize_t PyUnicode_AsWideChar (PyObject *unicode,
          wchar_t *w, Py_ssize_t size)

     Copy the Unicode object contents into the ‘wchar_t’ buffer `w'.  At
     most `size' ‘wchar_t’ characters are copied (excluding a possibly
     trailing null termination character).  Return the number of
     ‘wchar_t’ characters copied or ‘-1’ in case of an error.  Note that
     the resulting ‘wchar_t*’ string may or may not be null-terminated.
     It is the responsibility of the caller to make sure that the
     ‘wchar_t*’ string is null-terminated in case this is required by
     the application.  Also, note that the ‘wchar_t*’ string might
     contain null characters, which would cause the string to be
     truncated when used with most C functions.

 -- C 函式: wchar_t* PyUnicode_AsWideCharString (PyObject *unicode,
          Py_ssize_t *size)

     Convert the Unicode object to a wide character string.  The output
     string always ends with a null character.  If `size' is not ‘NULL’,
     write the number of wide characters (excluding the trailing null
     termination character) into `*size'.  Note that the resulting
     ‘wchar_t’ string might contain null characters, which would cause
     the string to be truncated when used with most C functions.  If
     `size' is ‘NULL’ and the ‘wchar_t*’ string contains null characters
     a *note ValueError: 16d. is raised.

     Returns a buffer allocated by ‘PyMem_Alloc()’ (use *note
     PyMem_Free(): e6e. to free it) on success.  On error, returns
     ‘NULL’ and `*size' is undefined.  Raises a *note MemoryError: f69.
     if memory allocation is failed.

     3.2 版新加入.

     3.7 版更變: Raises a *note ValueError: 16d. if `size' is ‘NULL’ and
     the ‘wchar_t*’ string contains null characters.


File: python.info,  Node: Built-in Codecs,  Next: Methods and Slot Functions,  Prev: Unicode对象,  Up: Unicode物件與編碼

7.8.3.15 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 *note str():
205. string object constructor.

Setting encoding to ‘NULL’ causes the default encoding to be used which
is UTF-8.  The file system calls should use *note
PyUnicode_FSConverter(): 6c5. for encoding file names.  This uses the
variable ‘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 ‘NULL’ meaning
to use the default handling defined for the codec.  Default error
handling for all built-in codecs is "strict" (*note ValueError: 16d. is
raised).

The codecs all use a similar interface.  Only deviation from the
following generic ones are documented for simplicity.

* Menu:

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


File: python.info,  Node: Generic Codecs,  Next: UTF-8 Codecs,  Up: Built-in Codecs

7.8.3.16 Generic Codecs
.......................

These are the generic codec APIs:

 -- C 函式: PyObject* PyUnicode_Decode (const char *s, Py_ssize_t size,
          const char *encoding, const char *errors)
     `Return value: New reference.'  Create a Unicode object by decoding
     `size' bytes of the encoded string `s'.  `encoding' and `errors'
     have the same meaning as the parameters of the same name in the
     *note str(): 205. built-in function.  The codec to be used is
     looked up using the Python codec registry.  Return ‘NULL’ if an
     exception was raised by the codec.

 -- C 函式: PyObject* PyUnicode_AsEncodedString (PyObject *unicode,
          const char *encoding, const char *errors)
     `Return value: New reference.'  Encode a Unicode object and return
     the result as Python bytes object.  `encoding' and `errors' have
     the same meaning as the parameters of the same name in the Unicode
     *note encode(): 170. method.  The codec to be used is looked up
     using the Python codec registry.  Return ‘NULL’ if an exception was
     raised by the codec.

 -- C 函式: PyObject* PyUnicode_Encode (const Py_UNICODE *s,
          Py_ssize_t size, const char *encoding, const char *errors)
     `Return value: New reference.'  Encode the *note Py_UNICODE: bc5.
     buffer `s' of the given `size' and return a Python bytes object.
     `encoding' and `errors' have the same meaning as the parameters of
     the same name in the Unicode *note encode(): 170. method.  The
     codec to be used is looked up using the Python codec registry.
     Return ‘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 *note Py_UNICODE: bc5. API; please migrate to
     using *note PyUnicode_AsEncodedString(): 4023.


File: python.info,  Node: UTF-8 Codecs,  Next: UTF-32 Codecs,  Prev: Generic Codecs,  Up: Built-in Codecs

7.8.3.17 UTF-8 Codecs
.....................

These are the UTF-8 codec APIs:

 -- C 函式: PyObject* PyUnicode_DecodeUTF8 (const char *s,
          Py_ssize_t size, const char *errors)
     `Return value: New reference.'  Create a Unicode object by decoding
     `size' bytes of the UTF-8 encoded string `s'.  Return ‘NULL’ if an
     exception was raised by the codec.

 -- C 函式: PyObject* PyUnicode_DecodeUTF8Stateful (const char *s,
          Py_ssize_t size, const char *errors, Py_ssize_t *consumed)
     `Return value: New reference.'  If `consumed' is ‘NULL’, behave
     like *note PyUnicode_DecodeUTF8(): 4025.  If `consumed' is not
     ‘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
     `consumed'.

 -- C 函式: PyObject* PyUnicode_AsUTF8String (PyObject *unicode)
     `Return value: New reference.'  Encode a Unicode object using UTF-8
     and return the result as Python bytes object.  Error handling is
     "strict".  Return ‘NULL’ if an exception was raised by the codec.

 -- C 函式: const char* PyUnicode_AsUTF8AndSize (PyObject *unicode,
          Py_ssize_t *size)

     Return a pointer to the UTF-8 encoding of the Unicode object, and
     store the size of the encoded representation (in bytes) in `size'.
     The `size' argument can be ‘NULL’; in this case no size will be
     stored.  The returned buffer always has an extra null byte appended
     (not included in `size'), regardless of whether there are any other
     null code points.

     In the case of an error, ‘NULL’ is returned with an exception set
     and no `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.

     3.3 版新加入.

     3.7 版更變: The return type is now ‘const char *’ rather of ‘char
     *’.

 -- C 函式: const char* PyUnicode_AsUTF8 (PyObject *unicode)

     As *note PyUnicode_AsUTF8AndSize(): 52d, but does not store the
     size.

     3.3 版新加入.

     3.7 版更變: The return type is now ‘const char *’ rather of ‘char
     *’.

 -- C 函式: PyObject* PyUnicode_EncodeUTF8 (const Py_UNICODE *s,
          Py_ssize_t size, const char *errors)
     `Return value: New reference.'  Encode the *note Py_UNICODE: bc5.
     buffer `s' of the given `size' using UTF-8 and return a Python
     bytes object.  Return ‘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 *note Py_UNICODE: bc5. API; please migrate to
     using *note PyUnicode_AsUTF8String(): bd2, *note
     PyUnicode_AsUTF8AndSize(): 52d. or *note
     PyUnicode_AsEncodedString(): 4023.


File: python.info,  Node: UTF-32 Codecs,  Next: UTF-16 Codecs,  Prev: UTF-8 Codecs,  Up: Built-in Codecs

7.8.3.18 UTF-32 Codecs
......................

These are the UTF-32 codec APIs:

 -- C 函式: PyObject* PyUnicode_DecodeUTF32 (const char *s,
          Py_ssize_t size, const char *errors, int *byteorder)
     `Return value: New reference.'  Decode `size' bytes from a UTF-32
     encoded buffer string and return the corresponding Unicode object.
     `errors' (if non-‘NULL’) defines the error handling.  It defaults
     to "strict".

     If `byteorder' is non-‘NULL’, the decoder starts decoding using the
     given byte order:

          *byteorder == -1: little endian
          *byteorder == 0:  native order
          *byteorder == 1:  big endian

     If ‘*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 ‘*byteorder’ is ‘-1’ or ‘1’, any byte order mark is copied to
     the output.

     After completion, `*byteorder' is set to the current byte order at
     the end of input data.

     If `byteorder' is ‘NULL’, the codec starts in native order mode.

     Return ‘NULL’ if an exception was raised by the codec.

 -- C 函式: PyObject* PyUnicode_DecodeUTF32Stateful (const char *s,
          Py_ssize_t size, const char *errors, int *byteorder,
          Py_ssize_t *consumed)
     `Return value: New reference.'  If `consumed' is ‘NULL’, behave
     like *note PyUnicode_DecodeUTF32(): 4028.  If `consumed' is not
     ‘NULL’, *note PyUnicode_DecodeUTF32Stateful(): 4029. 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 `consumed'.

 -- C 函式: PyObject* PyUnicode_AsUTF32String (PyObject *unicode)
     `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 ‘NULL’ if an
     exception was raised by the codec.

 -- C 函式: PyObject* PyUnicode_EncodeUTF32 (const Py_UNICODE *s,
          Py_ssize_t size, const char *errors, int byteorder)
     `Return value: New reference.'  Return a Python bytes object
     holding the UTF-32 encoded value of the Unicode data in `s'.
     Output is written according to the following byte order:

          byteorder == -1: little endian
          byteorder == 0:  native byte order (writes a BOM mark)
          byteorder == 1:  big endian

     If byteorder is ‘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 ‘Py_UNICODE_WIDE’ is not defined, surrogate pairs will be output
     as a single code point.

     Return ‘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 *note Py_UNICODE: bc5. API; please migrate to
     using *note PyUnicode_AsUTF32String(): 402a. or *note
     PyUnicode_AsEncodedString(): 4023.


File: python.info,  Node: UTF-16 Codecs,  Next: UTF-7 Codecs,  Prev: UTF-32 Codecs,  Up: Built-in Codecs

7.8.3.19 UTF-16 Codecs
......................

These are the UTF-16 codec APIs:

 -- C 函式: PyObject* PyUnicode_DecodeUTF16 (const char *s,
          Py_ssize_t size, const char *errors, int *byteorder)
     `Return value: New reference.'  Decode `size' bytes from a UTF-16
     encoded buffer string and return the corresponding Unicode object.
     `errors' (if non-‘NULL’) defines the error handling.  It defaults
     to "strict".

     If `byteorder' is non-‘NULL’, the decoder starts decoding using the
     given byte order:

          *byteorder == -1: little endian
          *byteorder == 0:  native order
          *byteorder == 1:  big endian

     If ‘*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 ‘*byteorder’ is ‘-1’ or ‘1’, any byte order mark is copied to
     the output (where it will result in either a ‘\ufeff’ or a ‘\ufffe’
     character).

     After completion, `*byteorder' is set to the current byte order at
     the end of input data.

     If `byteorder' is ‘NULL’, the codec starts in native order mode.

     Return ‘NULL’ if an exception was raised by the codec.

 -- C 函式: PyObject* PyUnicode_DecodeUTF16Stateful (const char *s,
          Py_ssize_t size, const char *errors, int *byteorder,
          Py_ssize_t *consumed)
     `Return value: New reference.'  If `consumed' is ‘NULL’, behave
     like *note PyUnicode_DecodeUTF16(): 402c.  If `consumed' is not
     ‘NULL’, *note PyUnicode_DecodeUTF16Stateful(): 402d. 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 `consumed'.

 -- C 函式: PyObject* PyUnicode_AsUTF16String (PyObject *unicode)
     `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 ‘NULL’ if an
     exception was raised by the codec.

 -- C 函式: PyObject* PyUnicode_EncodeUTF16 (const Py_UNICODE *s,
          Py_ssize_t size, const char *errors, int byteorder)
     `Return value: New reference.'  Return a Python bytes object
     holding the UTF-16 encoded value of the Unicode data in `s'.
     Output is written according to the following byte order:

          byteorder == -1: little endian
          byteorder == 0:  native byte order (writes a BOM mark)
          byteorder == 1:  big endian

     If byteorder is ‘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 ‘Py_UNICODE_WIDE’ is defined, a single *note Py_UNICODE: bc5.
     value may get represented as a surrogate pair.  If it is not
     defined, each *note Py_UNICODE: bc5. values is interpreted as a
     UCS-2 character.

     Return ‘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 *note Py_UNICODE: bc5. API; please migrate to
     using *note PyUnicode_AsUTF16String(): 402e. or *note
     PyUnicode_AsEncodedString(): 4023.


File: python.info,  Node: UTF-7 Codecs,  Next: Unicode-Escape Codecs,  Prev: UTF-16 Codecs,  Up: Built-in Codecs

7.8.3.20 UTF-7 Codecs
.....................

These are the UTF-7 codec APIs:

 -- C 函式: PyObject* PyUnicode_DecodeUTF7 (const char *s,
          Py_ssize_t size, const char *errors)
     `Return value: New reference.'  Create a Unicode object by decoding
     `size' bytes of the UTF-7 encoded string `s'.  Return ‘NULL’ if an
     exception was raised by the codec.

 -- C 函式: PyObject* PyUnicode_DecodeUTF7Stateful (const char *s,
          Py_ssize_t size, const char *errors, Py_ssize_t *consumed)
     `Return value: New reference.'  If `consumed' is ‘NULL’, behave
     like *note PyUnicode_DecodeUTF7(): 4030.  If `consumed' is not
     ‘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
     `consumed'.

 -- C 函式: PyObject* PyUnicode_EncodeUTF7 (const Py_UNICODE *s,
          Py_ssize_t size, int base64SetO, int base64WhiteSpace, const
          char *errors)
     `Return value: New reference.'  Encode the *note Py_UNICODE: bc5.
     buffer of the given size using UTF-7 and return a Python bytes
     object.  Return ‘NULL’ if an exception was raised by the codec.

     If `base64SetO' is nonzero, "Set O" (punctuation that has no
     otherwise special meaning) will be encoded in base-64.  If
     `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 *note Py_UNICODE: bc5. API; please migrate to
     using *note PyUnicode_AsEncodedString(): 4023.


File: python.info,  Node: Unicode-Escape Codecs,  Next: Raw-Unicode-Escape Codecs,  Prev: UTF-7 Codecs,  Up: Built-in Codecs

7.8.3.21 Unicode-Escape Codecs
..............................

These are the "Unicode Escape" codec APIs:

 -- C 函式: PyObject* PyUnicode_DecodeUnicodeEscape (const char *s,
          Py_ssize_t size, const char *errors)
     `Return value: New reference.'  Create a Unicode object by decoding
     `size' bytes of the Unicode-Escape encoded string `s'.  Return
     ‘NULL’ if an exception was raised by the codec.

 -- C 函式: PyObject* PyUnicode_AsUnicodeEscapeString
          (PyObject *unicode)
     `Return value: New reference.'  Encode a Unicode object using
     Unicode-Escape and return the result as a bytes object.  Error
     handling is "strict".  Return ‘NULL’ if an exception was raised by
     the codec.

 -- C 函式: PyObject* PyUnicode_EncodeUnicodeEscape (const
          Py_UNICODE *s, Py_ssize_t size)
     `Return value: New reference.'  Encode the *note Py_UNICODE: bc5.
     buffer of the given `size' using Unicode-Escape and return a bytes
     object.  Return ‘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 *note Py_UNICODE: bc5. API; please migrate to
     using *note PyUnicode_AsUnicodeEscapeString(): bd6.


File: python.info,  Node: Raw-Unicode-Escape Codecs,  Next: Latin-1 Codecs,  Prev: Unicode-Escape Codecs,  Up: Built-in Codecs

7.8.3.22 Raw-Unicode-Escape Codecs
..................................

These are the "Raw Unicode Escape" codec APIs:

 -- C 函式: PyObject* PyUnicode_DecodeRawUnicodeEscape (const char *s,
          Py_ssize_t size, const char *errors)
     `Return value: New reference.'  Create a Unicode object by decoding
     `size' bytes of the Raw-Unicode-Escape encoded string `s'.  Return
     ‘NULL’ if an exception was raised by the codec.

 -- C 函式: PyObject* PyUnicode_AsRawUnicodeEscapeString
          (PyObject *unicode)
     `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 ‘NULL’ if an exception was raised by
     the codec.

 -- C 函式: PyObject* PyUnicode_EncodeRawUnicodeEscape (const
          Py_UNICODE *s, Py_ssize_t size)
     `Return value: New reference.'  Encode the *note Py_UNICODE: bc5.
     buffer of the given `size' using Raw-Unicode-Escape and return a
     bytes object.  Return ‘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 *note Py_UNICODE: bc5. API; please migrate to
     using *note PyUnicode_AsRawUnicodeEscapeString(): bd8. or *note
     PyUnicode_AsEncodedString(): 4023.


File: python.info,  Node: Latin-1 Codecs,  Next: ASCII Codecs,  Prev: Raw-Unicode-Escape Codecs,  Up: Built-in Codecs

7.8.3.23 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.

 -- C 函式: PyObject* PyUnicode_DecodeLatin1 (const char *s,
          Py_ssize_t size, const char *errors)
     `Return value: New reference.'  Create a Unicode object by decoding
     `size' bytes of the Latin-1 encoded string `s'.  Return ‘NULL’ if
     an exception was raised by the codec.

 -- C 函式: PyObject* PyUnicode_AsLatin1String (PyObject *unicode)
     `Return value: New reference.'  Encode a Unicode object using
     Latin-1 and return the result as Python bytes object.  Error
     handling is "strict".  Return ‘NULL’ if an exception was raised by
     the codec.

 -- C 函式: PyObject* PyUnicode_EncodeLatin1 (const Py_UNICODE *s,
          Py_ssize_t size, const char *errors)
     `Return value: New reference.'  Encode the *note Py_UNICODE: bc5.
     buffer of the given `size' using Latin-1 and return a Python bytes
     object.  Return ‘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 *note Py_UNICODE: bc5. API; please migrate to
     using *note PyUnicode_AsLatin1String(): bda. or *note
     PyUnicode_AsEncodedString(): 4023.


File: python.info,  Node: ASCII Codecs,  Next: Character Map Codecs,  Prev: Latin-1 Codecs,  Up: Built-in Codecs

7.8.3.24 ASCII Codecs
.....................

These are the ASCII codec APIs.  Only 7-bit ASCII data is accepted.  All
other codes generate errors.

 -- C 函式: PyObject* PyUnicode_DecodeASCII (const char *s,
          Py_ssize_t size, const char *errors)
     `Return value: New reference.'  Create a Unicode object by decoding
     `size' bytes of the ASCII encoded string `s'.  Return ‘NULL’ if an
     exception was raised by the codec.

 -- C 函式: PyObject* PyUnicode_AsASCIIString (PyObject *unicode)
     `Return value: New reference.'  Encode a Unicode object using ASCII
     and return the result as Python bytes object.  Error handling is
     "strict".  Return ‘NULL’ if an exception was raised by the codec.

 -- C 函式: PyObject* PyUnicode_EncodeASCII (const Py_UNICODE *s,
          Py_ssize_t size, const char *errors)
     `Return value: New reference.'  Encode the *note Py_UNICODE: bc5.
     buffer of the given `size' using ASCII and return a Python bytes
     object.  Return ‘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 *note Py_UNICODE: bc5. API; please migrate to
     using *note PyUnicode_AsASCIIString(): bdc. or *note
     PyUnicode_AsEncodedString(): 4023.


File: python.info,  Node: Character Map Codecs,  Next: MBCS codecs for Windows,  Prev: ASCII Codecs,  Up: Built-in Codecs

7.8.3.25 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 ‘encodings’ package).  The codec uses mapping to
encode and decode characters.  The mapping objects provided must support
the *note __getitem__(): 3a5. mapping interface; dictionaries and
sequences work well.

These are the mapping codec APIs:

 -- C 函式: PyObject* PyUnicode_DecodeCharmap (const char *data,
          Py_ssize_t size, PyObject *mapping, const char *errors)
     `Return value: New reference.'  Create a Unicode object by decoding
     `size' bytes of the encoded string `s' using the given `mapping'
     object.  Return ‘NULL’ if an exception was raised by the codec.

     If `mapping' is ‘NULL’, Latin-1 decoding will be applied.  Else
     `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 ‘None’.  Unmapped data bytes – ones which
     cause a *note LookupError: 1790, as well as ones which get mapped
     to ‘None’, ‘0xFFFE’ or ‘'\ufffe'’, are treated as undefined
     mappings and cause an error.

 -- C 函式: PyObject* PyUnicode_AsCharmapString (PyObject *unicode,
          PyObject *mapping)
     `Return value: New reference.'  Encode a Unicode object using the
     given `mapping' object and return the result as a bytes object.
     Error handling is "strict".  Return ‘NULL’ if an exception was
     raised by the codec.

     The `mapping' object must map Unicode ordinal integers to bytes
     objects, integers in the range from 0 to 255 or ‘None’.  Unmapped
     character ordinals (ones which cause a *note LookupError: 1790.) as
     well as mapped to ‘None’ are treated as "undefined mapping" and
     cause an error.

 -- C 函式: PyObject* PyUnicode_EncodeCharmap (const Py_UNICODE *s,
          Py_ssize_t size, PyObject *mapping, const char *errors)
     `Return value: New reference.'  Encode the *note Py_UNICODE: bc5.
     buffer of the given `size' using the given `mapping' object and
     return the result as a bytes object.  Return ‘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 *note Py_UNICODE: bc5. API; please migrate to
     using *note PyUnicode_AsCharmapString(): 403c. or *note
     PyUnicode_AsEncodedString(): 4023.

The following codec API is special in that maps Unicode to Unicode.

 -- C 函式: PyObject* PyUnicode_Translate (PyObject *str,
          PyObject *table, const char *errors)
     `Return value: New reference.'  Translate a string by applying a
     character mapping table to it and return the resulting Unicode
     object.  Return ‘NULL’ if an exception was raised by the codec.

     The mapping table must map Unicode ordinal integers to Unicode
     ordinal integers or ‘None’ (causing deletion of the character).

     Mapping tables need only provide the *note __getitem__(): 3a5.
     interface; dictionaries and sequences work well.  Unmapped
     character ordinals (ones which cause a *note LookupError: 1790.)
     are left untouched and are copied as-is.

     `errors' has the usual meaning for codecs.  It may be ‘NULL’ which
     indicates to use the default error handling.

 -- C 函式: PyObject* PyUnicode_TranslateCharmap (const Py_UNICODE *s,
          Py_ssize_t size, PyObject *mapping, const char *errors)
     `Return value: New reference.'  Translate a *note Py_UNICODE: bc5.
     buffer of the given `size' by applying a character `mapping' table
     to it and return the resulting Unicode object.  Return ‘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 *note Py_UNICODE: bc5. API; please migrate to
     using *note PyUnicode_Translate(): 403d.  or *note generic codec
     based API: 6e5.


File: python.info,  Node: MBCS codecs for Windows,  Next: Methods & Slots,  Prev: Character Map Codecs,  Up: Built-in Codecs

7.8.3.26 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.

 -- C 函式: PyObject* PyUnicode_DecodeMBCS (const char *s,
          Py_ssize_t size, const char *errors)
     `Return value: New reference.'  Create a Unicode object by decoding
     `size' bytes of the MBCS encoded string `s'.  Return ‘NULL’ if an
     exception was raised by the codec.

 -- C 函式: PyObject* PyUnicode_DecodeMBCSStateful (const char *s,
          Py_ssize_t size, const char *errors, Py_ssize_t *consumed)
     `Return value: New reference.'  If `consumed' is ‘NULL’, behave
     like *note PyUnicode_DecodeMBCS(): 403f.  If `consumed' is not
     ‘NULL’, *note PyUnicode_DecodeMBCSStateful(): 4040. will not decode
     trailing lead byte and the number of bytes that have been decoded
     will be stored in `consumed'.

 -- C 函式: PyObject* PyUnicode_AsMBCSString (PyObject *unicode)
     `Return value: New reference.'  Encode a Unicode object using MBCS
     and return the result as Python bytes object.  Error handling is
     "strict".  Return ‘NULL’ if an exception was raised by the codec.

 -- C 函式: PyObject* PyUnicode_EncodeCodePage (int code_page,
          PyObject *unicode, const char *errors)
     `Return value: New reference.'  Encode the Unicode object using the
     specified code page and return a Python bytes object.  Return
     ‘NULL’ if an exception was raised by the codec.  Use ‘CP_ACP’ code
     page to get the MBCS encoder.

     3.3 版新加入.

 -- C 函式: PyObject* PyUnicode_EncodeMBCS (const Py_UNICODE *s,
          Py_ssize_t size, const char *errors)
     `Return value: New reference.'  Encode the *note Py_UNICODE: bc5.
     buffer of the given `size' using MBCS and return a Python bytes
     object.  Return ‘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 *note Py_UNICODE: bc5. API; please migrate to
     using *note PyUnicode_AsMBCSString(): be0, *note
     PyUnicode_EncodeCodePage(): be1. or *note
     PyUnicode_AsEncodedString(): 4023.


File: python.info,  Node: Methods & Slots,  Prev: MBCS codecs for Windows,  Up: Built-in Codecs

7.8.3.27 Methods & Slots
........................


File: python.info,  Node: Methods and Slot Functions,  Prev: Built-in Codecs,  Up: Unicode物件與編碼

7.8.3.28 Methods and Slot Functions
...................................

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 ‘NULL’ or ‘-1’ if an exception occurs.

 -- C 函式: PyObject* PyUnicode_Concat (PyObject *left, PyObject *right)
     `Return value: New reference.'  Concat two strings giving a new
     Unicode string.

 -- C 函式: PyObject* PyUnicode_Split (PyObject *s, PyObject *sep,
          Py_ssize_t maxsplit)
     `Return value: New reference.'  Split a string giving a list of
     Unicode strings.  If `sep' is ‘NULL’, splitting will be done at all
     whitespace substrings.  Otherwise, splits occur at the given
     separator.  At most `maxsplit' splits will be done.  If negative,
     no limit is set.  Separators are not included in the resulting
     list.

 -- C 函式: PyObject* PyUnicode_Splitlines (PyObject *s, int keepend)
     `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 `keepend' is ‘0’, the Line break characters
     are not included in the resulting strings.

 -- C 函式: PyObject* PyUnicode_Join (PyObject *separator,
          PyObject *seq)
     `Return value: New reference.'  Join a sequence of strings using
     the given `separator' and return the resulting Unicode string.

 -- C 函式: Py_ssize_t PyUnicode_Tailmatch (PyObject *str,
          PyObject *substr, Py_ssize_t start, Py_ssize_t end,
          int direction)

     Return ‘1’ if `substr' matches ‘str[start:end]’ at the given tail
     end (`direction' == ‘-1’ means to do a prefix match, `direction' ==
     ‘1’ a suffix match), ‘0’ otherwise.  Return ‘-1’ if an error
     occurred.

 -- C 函式: Py_ssize_t PyUnicode_Find (PyObject *str, PyObject *substr,
          Py_ssize_t start, Py_ssize_t end, int direction)

     Return the first position of `substr' in ‘str[start:end]’ using the
     given `direction' (`direction' == ‘1’ means to do a forward search,
     `direction' == ‘-1’ a backward search).  The return value is the
     index of the first match; a value of ‘-1’ indicates that no match
     was found, and ‘-2’ indicates that an error occurred and an
     exception has been set.

 -- C 函式: Py_ssize_t PyUnicode_FindChar (PyObject *str, Py_UCS4 ch,
          Py_ssize_t start, Py_ssize_t end, int direction)

     Return the first position of the character `ch' in ‘str[start:end]’
     using the given `direction' (`direction' == ‘1’ means to do a
     forward search, `direction' == ‘-1’ a backward search).  The return
     value is the index of the first match; a value of ‘-1’ indicates
     that no match was found, and ‘-2’ indicates that an error occurred
     and an exception has been set.

     3.3 版新加入.

     3.7 版更變: `start' and `end' are now adjusted to behave like
     ‘str[start:end]’.

 -- C 函式: Py_ssize_t PyUnicode_Count (PyObject *str, PyObject *substr,
          Py_ssize_t start, Py_ssize_t end)

     Return the number of non-overlapping occurrences of `substr' in
     ‘str[start:end]’.  Return ‘-1’ if an error occurred.

 -- C 函式: PyObject* PyUnicode_Replace (PyObject *str,
          PyObject *substr, PyObject *replstr, Py_ssize_t maxcount)
     `Return value: New reference.'  Replace at most `maxcount'
     occurrences of `substr' in `str' with `replstr' and return the
     resulting Unicode object.  `maxcount' == ‘-1’ means replace all
     occurrences.

 -- C 函式: int PyUnicode_Compare (PyObject *left, PyObject *right)

     Compare two strings and return ‘-1’, ‘0’, ‘1’ for less than, equal,
     and greater than, respectively.

     This function returns ‘-1’ upon failure, so one should call *note
     PyErr_Occurred(): 3d1e. to check for errors.

 -- C 函式: int PyUnicode_CompareWithASCIIString (PyObject *uni, const
          char *string)

     Compare a Unicode object, `uni', with `string' and return ‘-1’,
     ‘0’, ‘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.

 -- C 函式: PyObject* PyUnicode_RichCompare (PyObject *left,
          PyObject *right, int op)
     `Return value: New reference.'  Rich compare two Unicode strings
     and return one of the following:

        * ‘NULL’ in case an exception was raised

        * ‘Py_True’ or ‘Py_False’ for successful comparisons

        * ‘Py_NotImplemented’ in case the type combination is unknown

     Possible values for `op' are ‘Py_GT’, ‘Py_GE’, ‘Py_EQ’, ‘Py_NE’,
     ‘Py_LT’, and ‘Py_LE’.

 -- C 函式: PyObject* PyUnicode_Format (PyObject *format,
          PyObject *args)
     `Return value: New reference.'  Return a new string object from
     `format' and `args'; this is analogous to ‘format % args’.

 -- C 函式: int PyUnicode_Contains (PyObject *container,
          PyObject *element)

     Check whether `element' is contained in `container' and return true
     or false accordingly.

     `element' has to coerce to a one element Unicode string.  ‘-1’ is
     returned if there was an error.

 -- C 函式: void PyUnicode_InternInPlace (PyObject **string)

     Intern the argument `*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 `*string', it sets `*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 `*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.)

 -- C 函式: PyObject* PyUnicode_InternFromString (const char *v)
     `Return value: New reference.'  A combination of *note
     PyUnicode_FromString(): 3da9. and *note PyUnicode_InternInPlace():
     404c, 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.


File: python.info,  Node: 元組（Tuple）物件,  Next: 结构序列对象,  Prev: Unicode物件與編碼,  Up: 序列对象

7.8.3.29 元組（Tuple）物件
..........................

 -- C 類型: PyTupleObject

     这个 *note PyObject: 5b4. 的子类型代表一个 Python 的元组对象。

 -- C 變數: PyTypeObject PyTuple_Type

     *note PyTypeObject: 3f5. 的实例代表一个 Python 元组类型，这与
     Python 层面的 *note tuple: 1a2. 是相同的对象。

 -- C 函式: int PyTuple_Check (PyObject *p)

     如果 `p' 是一个 tuple 对象或者 tuple 类型的子类型的实例则返回真值。
     此函数总是会成功执行。

 -- C 函式: int PyTuple_CheckExact (PyObject *p)

     如果 `p' 是一个 tuple 对象但不是 tuple 类型的子类型的实例则返回真值
     。 此函数总是会成功执行。

 -- C 函式: PyObject* PyTuple_New (Py_ssize_t len)
     `Return value: New reference.' 成功时返回一个新的元组对象，长度为
     `len'，失败时返回‘‘NULL‘‘。

 -- C 函式: PyObject* PyTuple_Pack (Py_ssize_t n, ...)
     `Return value: New reference.' 成功时返回一个新的元组对象，大小为
     `n' ，失败时返回 ‘NULL’。 元组值初始化为指向 Python 对象的后续 `n'
     个 C 参数。 ‘PyTuple_Pack(2, a, b)’ 和 ‘Py_BuildValue("(OO)", a,
     b)’ 相等。

 -- C 函式: Py_ssize_t PyTuple_Size (PyObject *p)

     获取指向元组对象的指针，并返回该元组的大小。

 -- C 函式: Py_ssize_t PyTuple_GET_SIZE (PyObject *p)

     返回元组 `p' 的大小，它必须为非 ‘NULL’ 并且指向一个元组；不执行错误
     检查。

 -- C 函式: PyObject* PyTuple_GetItem (PyObject *p, Py_ssize_t pos)
     `Return value: Borrowed reference.' 返回 `p' 所指向的元组中，位于
     `pos' 处的对象。 如果 `pos' 超出界限，返回 ‘NULL’，并抛出一个 *note
     IndexError: f36. 异常。

 -- C 函式: PyObject* PyTuple_GET_ITEM (PyObject *p, Py_ssize_t pos)
     `Return value: Borrowed reference.' 类似于 *note PyTuple_GetItem():
     3d39.，但不检查其参数。

 -- C 函式: PyObject* PyTuple_GetSlice (PyObject *p, Py_ssize_t low,
          Py_ssize_t high)
     `Return value: New reference.' 返回 `p' 所指向的元组的切片，在
     `low' 和 `high' 之间，或者在失败时返回 ‘NULL’。 这等同于 Python 表
     达式 ‘p[low:high]’。 不支持从列表末尾索引。

 -- C 函式: int PyTuple_SetItem (PyObject *p, Py_ssize_t pos,
          PyObject *o)

     在 `p' 指向的元组的 `pos' 位置插入对对象 `o' 的引用。 成功时返回
     ‘0’；如果 `pos' 越界，则返回 ‘-1’，并抛出一个 *note IndexError:
     f36. 异常。

          備註: 此函数会“窃取”对 `o' 的引用，并丢弃对元组中已在受影响位
          置的条目的引用。

 -- C 函式: void PyTuple_SET_ITEM (PyObject *p, Py_ssize_t pos,
          PyObject *o)

     类似于 *note PyTuple_SetItem(): 3d3e.，但不进行错误检查，并且应该
     `只是' 被用来填充全新的元组。

          備註: 这个宏会“偷走”一个对 `o' 的引用，但与 *note
          PyTuple_SetItem(): 3d3e. 不同，它 `不会' 丢弃对任何被替换项的
          引用；元组中位于 `pos' 位置的任何引用都将被泄漏。

 -- C 函式: int _PyTuple_Resize (PyObject **p, Py_ssize_t newsize)

     可以用于调整元组的大小。 `newsize' 将是元组的新长度。 因为元组 `被
     认为' 是不可变的，所以只有在对象仅有一个引用时，才应该使用它。 如果
     元组已经被代码的其他部分所引用，请不要使用此项。 元组在最后总是会增
     长或缩小。 把它看作是销毁旧元组并创建一个新元组，只会更有效。 成功
     时返回 ‘0’ 。 客户端代码不应假定 ‘*p’ 的结果值将与调用此函数之前的
     值相同。 如果替换了 ‘*p’ 引用的对象，则原始的 ‘*p’ 将被销毁。 失败
     时，返回‘‘-1‘‘，将 ‘*p’ 设置为 ‘NULL’，并引发 *note MemoryError:
     f69. 或者 *note SystemError: 6f2.。


File: python.info,  Node: 结构序列对象,  Next: List（串列）物件,  Prev: 元組（Tuple）物件,  Up: 序列对象

7.8.3.30 结构序列对象
.....................

结构序列对象是等价于 *note namedtuple(): 1a1. 的 C 对象，即一个序列，其
中的条目也可以通过属性访问。 要创建结构序列，你首先必须创建特定的结构序
列类型。

 -- C 函式: PyTypeObject* PyStructSequence_NewType
          (PyStructSequence_Desc *desc)
     `Return value: New reference.' 根据 `desc' 中的数据创建一个新的结构
     序列类型，如下所述。 可以使用 *note PyStructSequence_New(): 405c. 创
     建结果类型的实例。

 -- C 函式: void PyStructSequence_InitType (PyTypeObject *type,
          PyStructSequence_Desc *desc)

     从 `desc' 就地初始化结构序列类型 `type'。

 -- C 函式: int PyStructSequence_InitType2 (PyTypeObject *type,
          PyStructSequence_Desc *desc)

     与 ‘PyStructSequence_InitType’ 相同，但成功时返回 ‘0’ ，失败时返回
     ‘-1’ 。

     3.4 版新加入.

 -- C 類型: PyStructSequence_Desc

     包含要创建的结构序列类型的元信息。

     域                      C Type                             意义
                                                                
     ------------------------------------------------------------------------------------------------------
                                                                
     ‘name’                  ‘const char *’                     结构序列类型的名称
                                                                
                                                                
     ‘doc’                   ‘const char *’                     指向要忽略类型的文档字符串或 ‘NULL’ 的指
                                                                针
                                                                
                                                                
     ‘fields’                ‘PyStructSequence_Field *’         指向以 ‘NULL’ 结尾的数组的指针，其字段名
                                                                称为新类型
                                                                
                                                                
     ‘n_in_sequence’         ‘int’                              Python侧可见的字段数（如果用作元组）
                                                                

 -- C 類型: PyStructSequence_Field

     描述结构序列的一个字段。 当结构序列被建模为元组时，所有字段的类型都
     是 *note PyObject*: 5b4.。 在 *note PyStructSequence_Desc: 52c. 的
     ‘fields’ 数组中的索引确定了结构序列描述的是哪个字段。

     域              C Type                 意义
                                            
     -------------------------------------------------------------------------------------
                                            
     ‘name’          ‘const char *’         字段的名称或 ‘NULL’ ，若要结束命名字段的列
                                            表，请设置为
                                            *note PyStructSequence_UnnamedField: 262. 以
                                            保留未命名字段
                                            
                                            
     ‘doc’           ‘const char *’         要忽略的字段文档字符串或 ‘NULL’
                                            

 -- C 變數: const char * const PyStructSequence_UnnamedField

     字段名的特殊值将保持未命名状态。

     3.9 版更變: 这个类型已从 ‘char *’ 更改。

 -- C 函式: PyObject* PyStructSequence_New (PyTypeObject *type)
     `Return value: New reference.' 创建 `type' 的实例，该实例必须使用
     *note PyStructSequence_NewType(): f9e. 创建。

 -- C 函式: PyObject* PyStructSequence_GetItem (PyObject *p,
          Py_ssize_t pos)
     `Return value: Borrowed reference.' 返回 `p' 所指向的结构序列中，位
     于 `pos' 处的对象。不需要进行边界检查。

 -- C 函式: PyObject* PyStructSequence_GET_ITEM (PyObject *p,
          Py_ssize_t pos)
     `Return value: Borrowed reference.'  *note
     PyStructSequence_GetItem(): 405d. 的宏版本。

 -- C 函式: void PyStructSequence_SetItem (PyObject *p, Py_ssize_t pos,
          PyObject *o)

     将结构序列 `p' 的索引 `pos' 处的字段设置为值 `o'。 与 *note
     PyTuple_SET_ITEM(): 405a. 一样，它应该只用于填充全新的实例。

          備註: 这个函数“窃取”了指向 `o' 的一个引用。

 -- C 函式: void PyStructSequence_SET_ITEM (PyObject *p,
          Py_ssize_t *pos, PyObject *o)

     *note PyStructSequence_SetItem(): 405f. 的宏版本。

          備註: 这个函数“窃取”了指向 `o' 的一个引用。


File: python.info,  Node: List（串列）物件,  Prev: 结构序列对象,  Up: 序列对象

7.8.3.31 List（串列）物件
.........................

 -- C 類型: PyListObject

     这个C类型 *note PyObject: 5b4. 的子类型代表一个Python列表对象。

 -- C 變數: PyTypeObject PyList_Type

     这是个属于 *note PyTypeObject: 3f5. 的代表Python列表类型的实例。在
     Python层面和类型 *note list: 1f8. 是同一个对象。

 -- C 函式: int PyList_Check (PyObject *p)

     如果 `p' 是一个 list 对象或者 list 类型的子类型的实例则返回真值。 此
     函数总是会成功执行。

 -- C 函式: int PyList_CheckExact (PyObject *p)

     如果 `p' 是一个 list 对象但不是 list 类型的子类型的实例则返回真值。
     此函数总是会成功执行。

 -- C 函式: PyObject* PyList_New (Py_ssize_t len)
     `Return value: New reference.' 成功时返回一个长度为 `len' 的新列表
     ，失败时返回 ‘NULL’。

          備註: 当 `len' 大于零时，被返回的列表对象项目被设成 ‘NULL’。因
          此你不能用类似C函数 *note PySequence_SetItem(): 1184. 的抽象
          API或者用C函数 *note PyList_SetItem(): 3d3f. 将所有项目设置成
          真实对象前对Python代码公开这个对象。

 -- C 函式: Py_ssize_t PyList_Size (PyObject *list)

     返回 `list' 中列表对象的长度；这等于在列表对象调用 ‘len(list)’ 。

 -- C 函式: Py_ssize_t PyList_GET_SIZE (PyObject *list)

     宏版本的C函数 *note PyList_Size(): e43. ，没有错误检测。

 -- C 函式: PyObject* PyList_GetItem (PyObject *list, Py_ssize_t index)
     `Return value: Borrowed reference.' 返回 `list' 所指向列表中
     `index' 位置上的对象。 位置值必须为非负数；不支持从列表末尾进行索引
     。 如果 `index' 超出边界 (<0 or >=len(list))，则返回 ‘NULL’ 并设置
     *note IndexError: f36. 异常。

 -- C 函式: PyObject* PyList_GET_ITEM (PyObject *list, Py_ssize_t i)
     `Return value: Borrowed reference.' 宏版本的C函数 *note
     PyList_GetItem(): 3d3a. ，没有错误检测。

 -- C 函式: int PyList_SetItem (PyObject *list, Py_ssize_t index,
          PyObject *item)

     将列表中索引为 `index' 的项设为 `item'。 成功时返回 ‘0’。 如果
     `index' 超出范围则返回 ‘-1’ 并设定 *note IndexError: f36. 异常。

          備註: 此函数会“偷走”一个对 `item' 的引用并丢弃一个对列表中受影
          响位置上的已有条目的引用。

 -- C 函式: void PyList_SET_ITEM (PyObject *list, Py_ssize_t i,
          PyObject *o)

     不带错误检测的宏版本 *note PyList_SetItem(): 3d3f.。 这通常只被用于
     新列表中之前没有内容的位置进行填充。

          備註: 该宏会“偷走”一个对 `item' 的引用，但与 *note
          PyList_SetItem(): 3d3f. 不同的是它 `不会' 丢弃对任何被替换条目
          的引用；在 `list' 的 `i' 位置上的任何引用都将被泄露。

 -- C 函式: int PyList_Insert (PyObject *list, Py_ssize_t index,
          PyObject *item)

     将条目 `item' 插入到列表 `list' 索引号 `index' 之前的位置。 如果成
     功将返回 ‘0’；如果不成功则返回 ‘-1’ 并设置一个异常。 相当于
     ‘list.insert(index, item)’。

 -- C 函式: int PyList_Append (PyObject *list, PyObject *item)

     将对象 `item' 添加到列表 `list' 的末尾。 如果成功将返回 ‘0’；如果不
     成功则返回 ‘-1’ 并设置一个异常。 相当于 ‘list.append(item)’。

 -- C 函式: PyObject* PyList_GetSlice (PyObject *list, Py_ssize_t low,
          Py_ssize_t high)
     `Return value: New reference.' 返回一个对象列表，包含 `list' 当中位
     于 `low' 和 `high' `之间' 的对象。 如果不成功则返回 ‘NULL’ 并设置异
     常。 相当于 ‘list[low:high]’。 不支持从列表末尾进行索引。

 -- C 函式: int PyList_SetSlice (PyObject *list, Py_ssize_t low,
          Py_ssize_t high, PyObject *itemlist)

     将 `list' 当中 `low' 与 `high' 之间的切片设为 `itemlist' 的内容。 相
     当于 ‘list[low:high] = itemlist’。 `itemlist' 可以为 ‘NULL’，表示赋
     值为一个空列表（删除切片）。 成功时返回 ‘0’，失败时返回 ‘-1’。 这里
     不支持从列表末尾进行索引。

 -- C 函式: int PyList_Sort (PyObject *list)

     对 `list' 中的条目进行原地排序。 成功时返回 ‘0’，失败时返回 ‘-1’。
     这等价于 ‘list.sort()’。

 -- C 函式: int PyList_Reverse (PyObject *list)

     对 `list' 中的条目进行原地反转。 成功时返回 ‘0’，失败时返回 ‘-1’。
     这等价于 ‘list.reverse()’。

 -- C 函式: PyObject* PyList_AsTuple (PyObject *list)
     `Return value: New reference.'

     返回一个新的元组对象，其中包含 `list' 的内容；等价于 ‘tuple(list)’。


File: python.info,  Node: 容器对象,  Next: 函式物件<2>,  Prev: 序列对象,  Up: 具体的对象层

7.8.4 容器对象
--------------

* Menu:

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


File: python.info,  Node: 字典物件,  Next: 集合对象,  Up: 容器对象

7.8.4.1 字典物件
................

 -- C 類型: PyDictObject

     *note PyObject: 5b4. 子型態代表一個 Python 字典物件。

 -- C 變數: PyTypeObject PyDict_Type

     *note PyTypeObject: 3f5. 實例代表一個 Python 字典型態。此與 Python
     層中的 *note dict: 164. 為同一個物件。

 -- C 函式: int PyDict_Check (PyObject *p)

     若 `p' 是一個字典物件或字典的子型態實例則會回傳 true。此函式每次都
     會執行成功。

 -- C 函式: int PyDict_CheckExact (PyObject *p)

     若 `p' 是一個字典物件但並不是一個字典子型態的實例，則回傳 true。此
     函式每次都會執行成功。

 -- C 函式: PyObject* PyDict_New ()
     `Return value: New reference.' 返回一个新的空字典，失败时返回
     ‘NULL’。

 -- C 函式: PyObject* PyDictProxy_New (PyObject *mapping)
     `Return value: New reference.' 返回 *note types.MappingProxyType:
     b8e. 对象，用于强制执行只读行为的映射。这通常用于创建视图以防止修改
     非动态类类型的字典。

 -- C 函式: void PyDict_Clear (PyObject *p)

     清空现有字典的所有键值对。

 -- C 函式: int PyDict_Contains (PyObject *p, PyObject *key)

     确定 `key' 是否包含在字典 `p' 中。如果 `key' 匹配上 `p' 的某一项，
     则返回 ‘1’ ，否则返回 ‘0’ 。返回 ‘-1’ 表示出错。这等同于Python表达
     式 ‘key in p’ 。

 -- C 函式: PyObject* PyDict_Copy (PyObject *p)
     `Return value: New reference.' 返回与 `p' 包含相同键值对的新字典。

 -- C 函式: int PyDict_SetItem (PyObject *p, PyObject *key,
          PyObject *val)

     使用 `key' 作为键将 `val' 插入字典 `p'。 `key' 必须为 *note
     hashable: 276.；如果不是，则将引发 *note TypeError: 1fe.。 成功时返
     回 ‘0’，失败时返回 ‘-1’。 此函数 `不会' 附带对 `val' 的引用。

 -- C 函式: int PyDict_SetItemString (PyObject *p, const char *key,
          PyObject *val)

     使用 `key' 作为键将 `val' 插入到字典 `p'。 `key' 应当为 ‘const
     char*’。 键对象是使用 ‘PyUnicode_FromString(key)’ 创建的。 成功时返
     回 ‘0’，失败时返回 ‘-1’。 此函数 `不会' 附带对 `val' 的引用。

 -- C 函式: int PyDict_DelItem (PyObject *p, PyObject *key)

     移除字典 `p' 中键为 `key' 的条目。 `key' 必须是可哈希的；如果不是，
     则会引发 *note TypeError: 1fe.。 如果字典中没有 `key'，则会引发
     *note KeyError: 3e9.。 成功时返回 ‘0’，失败时返回 ‘-1’。

 -- C 函式: int PyDict_DelItemString (PyObject *p, const char *key)

     移除字典 `p' 中由字符串 `key' 指定的键的条目。 如果字典中没有
     `key'，则会引发 *note KeyError: 3e9.。 成功时返回 ‘0’，失败时返回
     ‘-1’。

 -- C 函式: PyObject* PyDict_GetItem (PyObject *p, PyObject *key)
     `Return value: Borrowed reference.' 从字典 `p' 中返回以 `key' 为键
     的对象。 如果键名 `key' 不存在但 `没有' 设置一个异常则返回 ‘NULL’。

     需要注意的是，调用 *note __hash__(): 44c. 和 *note __eq__(): 44b. 方
     法产生的异常不会被抛出。改用 *note PyDict_GetItemWithError(): 4080.
     获得错误报告。

 -- C 函式: PyObject* PyDict_GetItemWithError (PyObject *p,
          PyObject *key)
     `Return value: Borrowed reference.'  *note PyDict_GetItem(): 3d3b.
     的变种，它不会屏蔽异常。 当异常发生时将返回 ‘NULL’ `并且' 设置一个
     异常。 如果键不存在则返回 ‘NULL’ `并且不会' 设置一个异常。

 -- C 函式: PyObject* PyDict_GetItemString (PyObject *p, const
          char *key)
     `Return value: Borrowed reference.' 这与 *note PyDict_GetItem():
     3d3b. 一样，但是 `key' 被指定为 ‘const char*’，而不是 *note
     PyObject*: 5b4.。

     需要注意的是，调用 *note __hash__(): 44c. 、 *note __eq__(): 44b. 方
     法和创建一个临时的字符串对象时产生的异常不会被抛出。改用 *note
     PyDict_GetItemWithError(): 4080. 获得错误报告。

 -- C 函式: PyObject* PyDict_SetDefault (PyObject *p, PyObject *key,
          PyObject *defaultobj)
     `Return value: Borrowed reference.' 这跟Python层面的 *note
     dict.setdefault(): a9e. 一样。如果键 `key' 存在，它返回在字典 `p' 里
     面对应的值。如果键不存在，它会和值 `defaultobj' 一起插入并返回
     `defaultobj' 。这个函数只计算 `key' 的哈希函数一次，而不是在查找和
     插入时分别计算它。

     3.4 版新加入.

 -- C 函式: PyObject* PyDict_Items (PyObject *p)
     `Return value: New reference.' 返回一个包含字典中所有键值项的 *note
     PyListObject: 3f26.。

 -- C 函式: PyObject* PyDict_Keys (PyObject *p)
     `Return value: New reference.' 返回一个包含字典中所有键(keys)的
     *note PyListObject: 3f26.。

 -- C 函式: PyObject* PyDict_Values (PyObject *p)
     `Return value: New reference.' 返回一个包含字典中所有值(values)的
     *note PyListObject: 3f26.。

 -- C 函式: Py_ssize_t PyDict_Size (PyObject *p)

     返回字典中项目数，等价于对字典 `p' 使用 ‘len(p)’。

 -- C 函式: int PyDict_Next (PyObject *p, Py_ssize_t *ppos,
          PyObject **pkey, PyObject **pvalue)

     迭代字典 `p' 中的所有键值对。 在第一次调用此函数开始迭代之前，由
     `ppos' 所引用的 ‘Py_ssize_t’ 必须被初始化为 ‘0’；该函数将为字典中的
     每个键值对返回真值，一旦所有键值对都报告完毕则返回假值。 形参
     `pkey' 和 `pvalue' 应当指向 *note PyObject*: 5b4. 变量，它们将分别
     使用每个键和值来填充，或者也可以为 ‘NULL’。 通过它们返回的任何引用
     都是暂借的。 `ppos' 在迭代期间不应被更改。 它的值表示内部字典结构中
     的偏移量，并且由于结构是稀疏的，因此偏移量并不连续。

     例如:

          PyObject *key, *value;
          Py_ssize_t pos = 0;

          while (PyDict_Next(self->dict, &pos, &key, &value)) {
              /* do something interesting with the values... */
              ...
          }

     字典 `p' 不应该在遍历期间发生改变。在遍历字典时，改变键中的值是安全
     的，但仅限于键的集合不发生改变。例如:

          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);
          }

 -- C 函式: int PyDict_Merge (PyObject *a, PyObject *b, int override)

     对映射对象 `b' 进行迭代，将键值对添加到字典 `a'。 `b' 可以是一个字
     典，或任何支持 *note PyMapping_Keys(): 52f. 和 *note
     PyObject_GetItem(): 3dcb. 的对象。 如果 `override' 为真值，则如果在
     `b' 中找到相同的键则 `a' 中已存在的相应键值对将被替换，否则如果在
     `a' 中没有相同的键则只是添加键值对。 当成功时返回 ‘0’ 或者当引发异
     常时返回 ‘-1’。

 -- C 函式: int PyDict_Update (PyObject *a, PyObject *b)

     这与 C 中的 ‘PyDict_Merge(a, b, 1)’ 一样，也类似于 Python 中的
     ‘a.update(b)’，差别在于 *note PyDict_Update(): 4088. 在第二个参数没
     有 "keys" 属性时不会回退到迭代键值对的序列。 当成功时返回 ‘0’ 或者
     当引发异常时返回 ‘-1’。

 -- C 函式: int PyDict_MergeFromSeq2 (PyObject *a, PyObject *seq2,
          int override)

     将 `seq2' 中的键值对更新或合并到字典 `a'。 `seq2' 必须为产生长度为
     2 的用作键值对的元素的可迭代对象。 当存在重复的键时，如果
     `override' 真值则最后出现的键胜出。 当成功时返回 ‘0’ 或者当引发异常
     时返回 ‘-1’。 等价的 Python 代码（返回值除外）:

          def PyDict_MergeFromSeq2(a, seq2, override):
              for key, value in seq2:
                  if override or key not in a:
                      a[key] = value


File: python.info,  Node: 集合对象,  Prev: 字典物件,  Up: 容器对象

7.8.4.2 集合对象
................

这一章节详细介绍了 *note set: 1f6. 和 *note frozenset: 1f7. 对象的公共
API。 任何未在下面列出的功能最好是使用抽象对象协议 (包括 *note
PyObject_CallMethod(): 3eea, *note PyObject_RichCompareBool(): 109c,
*note PyObject_Hash(): 3ed0, *note PyObject_Repr(): a49, *note
PyObject_IsTrue(): 3ed1, *note PyObject_Print(): 1181. 以及 *note
PyObject_GetIter(): 3ed8.) 或者抽象数字协议 (包括 *note PyNumber_And():
3f03, *note PyNumber_Subtract(): 3ef6, *note PyNumber_Or(): 3f05, *note
PyNumber_Xor(): 3f04, *note PyNumber_InPlaceAnd(): 3f0f, *note
PyNumber_InPlaceSubtract(): 3f07, *note PyNumber_InPlaceOr(): 3f11. 以及
*note PyNumber_InPlaceXor(): 3f10.) 来访问。

 -- C 類型: PySetObject

     这个 *note PyObject: 5b4. 的子类型被用来保存 *note set: 1f6. 和
     *note frozenset: 1f7. 对象的内部数据。 它类似于 *note PyDictObject:
     4075.，因为对于小尺寸集合来说它是固定大小的（很像元组的存储方式），
     并且对于中等和大尺寸集合来说它将指向单独的可变大小的内存块（很像列
     表的存储方式）。 此结构体的字段不应被视为公有并且可能发生改变。 所
     有访问应当通过已写入文档的 API 来进行，而不可通过操纵结构体中的值。

 -- C 變數: PyTypeObject PySet_Type

     这是一个 *note PyTypeObject: 3f5. 实例，表示 Python *note set: 1f6.
     类型。

 -- C 變數: PyTypeObject PyFrozenSet_Type

     这是一个 *note PyTypeObject: 3f5. 实例，表示 Python *note
     frozenset: 1f7. 类型。

下列类型检查宏适用于指向任意 Python 对象的指针。 类似地，这些构造函数也
适用于任意可迭代的 Python 对象。

 -- C 函式: int PySet_Check (PyObject *p)

     如果 `p' 是一个 *note set: 1f6. 对象或者是其子类型的实例则返回真值
     。 此函数总是会成功执行。

 -- C 函式: int PyFrozenSet_Check (PyObject *p)

     如果 `p' 是一个 *note frozenset: 1f7. 对象或者是其子类型的实例则返
     回真值。 此函数总是会成功执行。

 -- C 函式: int PyAnySet_Check (PyObject *p)

     如果 `p' 是一个 *note set: 1f6. 对象、*note frozenset: 1f7. 对象或
     者是其子类型的实例则返回真值。 此函数总是会成功执行。

 -- C 函式: int PyAnySet_CheckExact (PyObject *p)

     如果 `p' 是一个 *note set: 1f6. 或 *note frozenset: 1f7. 对象但不是
     其子类型的实例则返回真值。 此函数总是会成功执行。

 -- C 函式: int PyFrozenSet_CheckExact (PyObject *p)

     如果 `p' 是一个 *note frozenset: 1f7. 对象但不是其子类型的实例则返
     回真值。 此函数总是会成功执行。

 -- C 函式: PyObject* PySet_New (PyObject *iterable)
     `Return value: New reference.' 返回一个新的 *note set: 1f6.，其中包
     含 `iterable' 所返回的对象。 `iterable' 可以为 ‘NULL’ 表示创建一个
     新的空集合。 成功时返回新的集合，失败时返回 ‘NULL’。 如果
     `iterable' 实际上不是可迭代对象则引发 *note TypeError: 1fe.。 该构
     造器也适用于拷贝集合 (‘c=set(s)’)。

 -- C 函式: PyObject* PyFrozenSet_New (PyObject *iterable)
     `Return value: New reference.' 返回一个新的 *note frozenset: 1f7.，
     其中包含 `iterable' 所返回的对象。 `iterable' 可以为 ‘NULL’ 表示创
     建一个新的空冻结集合。 成功时返回新的冻结集合，失败时返回 ‘NULL’。
     如果 `iterable' 实际上不是可迭代对象则引发 *note TypeError: 1fe.。

下列函数和宏适用于 *note set: 1f6. 或 *note frozenset: 1f7. 的实例或是其
子类型的实例。

 -- C 函式: Py_ssize_t PySet_Size (PyObject *anyset)

     返回 *note set: 1f6. 或 *note frozenset: 1f7. 对象的长度。 等价于
     ‘len(anyset)’。 如果 `anyset' 不是 *note set: 1f6, *note frozenset:
     1f7. 或其子类型的实例则会引发 ‘PyExc_SystemError’。

 -- C 函式: Py_ssize_t PySet_GET_SIZE (PyObject *anyset)

     宏版本的 *note PySet_Size(): e75.，不带错误检测。

 -- C 函式: int PySet_Contains (PyObject *anyset, PyObject *key)

     如果找到返回 ‘1’，如果未找到返回 ‘0’，如果遇到错误则返回 ‘-1’。 不
     同于 Python *note __contains__(): dee. 方法，此函数不会自动将不可哈
     希的集合转换为临时的冻结集合。 如果 `key' 为不可哈希对象则会引发
     *note TypeError: 1fe.。 如果 `anyset' 不是 *note set: 1f6, *note
     frozenset: 1f7. 或其子类型的实例则会引发 ‘PyExc_SystemError’。

 -- C 函式: int PySet_Add (PyObject *set, PyObject *key)

     添加 `key' 到一个 *note set: 1f6. 实例。 也可用于 *note frozenset:
     1f7. 实例（类似于 *note PyTuple_SetItem(): 3d3e.，它可被用来为全新
     冻结集合在公开给其他代码之前填充全新的值）。 成功时返回 ‘0’，失败时
     返回 ‘-1’。 如果 `key' 为不可哈希对象则会引发 *note TypeError:
     1fe.。 如果没有增长空间则会引发 *note MemoryError: f69.。 如果
     `set' 不是 *note set: 1f6. 或其子类型的实例则会引发 *note
     SystemError: 6f2.。

下列函数适用于 *note set: 1f6. 或其子类型的实例，但不可用于 *note
frozenset: 1f7. 或其子类型的实例。

 -- C 函式: int PySet_Discard (PyObject *set, PyObject *key)

     如果找到并移除返回 ‘1’，如果未找到（无操作）返回 ‘0’，如果遇到错误
     则返回 ‘-1’。 对于不存在的键不会引发 *note KeyError: 3e9.。 如果
     `key' 为不可哈希对象则会引发 *note TypeError: 1fe.。 不同于 Python
     ‘discard()’ 方法，此函数不会自动将不可哈希的集合转换为临时的冻结集
     合。 如果 `set' 不是 *note set: 1f6. 或其子类型的实例则会引发
     ‘PyExc_SystemError’。

 -- C 函式: PyObject* PySet_Pop (PyObject *set)
     `Return value: New reference.' 返回 `set' 中任意对象的新引用，并从
     `set' 中移除该对象。 失败时返回 ‘NULL’。 如果集合为空则会引发 *note
     KeyError: 3e9.。 如果 `set' 不是 *note set: 1f6. 或其子类型的实例则
     会引发 *note SystemError: 6f2.。

 -- C 函式: int PySet_Clear (PyObject *set)

     清空现有字典的所有键值对。


File: python.info,  Node: 函式物件<2>,  Next: 其他对象<2>,  Prev: 容器对象,  Up: 具体的对象层

7.8.5 函式物件
--------------

* Menu:

* 函式（Function）物件::
* 實體方法物件::
* 方法对象::
* Cell 物件::
* 代码对象: 代码对象<2>.


File: python.info,  Node: 函式（Function）物件,  Next: 實體方法物件,  Up: 函式物件<2>

7.8.5.1 函式（Function）物件
............................

這有一些少數Python函數的於具體說明。

 -- C 類型: PyFunctionObject

     用于函数的 C 结构体。

 -- C 變數: PyTypeObject PyFunction_Type

     这是一个 *note PyTypeObject: 3f5. 实例并表示 Python 函数类型。 它作
     为 ‘types.FunctionType’ 向 Python 程序员公开。

 -- C 函式: int PyFunction_Check (PyObject *o)

     如果 `o' 是一个函数对象 (类型为 *note PyFunction_Type: 409e.) 则返
     回真值。 形参必须不为 ‘NULL’。 此函数总是会成功执行。

 -- C 函式: PyObject* PyFunction_New (PyObject *code, PyObject *globals)
     `Return value: New reference.' 返回与代码对象 `code' 关联的新函数对
     象。 `globals' 必须是一个字典，该函数可以访问全局变量。

     从代码对象中提取函数的文档字符串和名称。 `__module__' 会从
     `globals' 中提取。 参数 defaults, annotations 和 closure 设为
     ‘NULL’。 `__qualname__' 设为与函数名称相同的值。

 -- C 函式: PyObject* PyFunction_NewWithQualName (PyObject *code,
          PyObject *globals, PyObject *qualname)
     `Return value: New reference.' 类似 *note PyFunction_New(): 40a0.，
     但还允许设置函数对象的 ‘__qualname__’ 属性。 `qualname' 应当是
     unicode 对象或 ‘NULL’；如果是 ‘NULL’ 则 ‘__qualname__’ 属性设为与其
     ‘__name__’ 属性相同的值。

     3.3 版新加入.

 -- C 函式: PyObject* PyFunction_GetCode (PyObject *op)
     `Return value: Borrowed reference.' 回傳與程式碼物件相關的函數物件
     `op'。

 -- C 函式: PyObject* PyFunction_GetGlobals (PyObject *op)
     `Return value: Borrowed reference.' 回傳與全域函數字典相關的函數物
     件 `op'。

 -- C 函式: PyObject* PyFunction_GetModule (PyObject *op)
     `Return value: Borrowed reference.' 返回函数对象 `op' 的
     `__module__' 属性，通常为一个包含了模块名称的字符串，但可以通过
     Python 代码设为返回其他任意对象。

 -- C 函式: PyObject* PyFunction_GetDefaults (PyObject *op)
     `Return value: Borrowed reference.' 返回函数对象 `op' 的参数默认值
     。 这可以是一个参数元组或 ‘NULL’。

 -- C 函式: int PyFunction_SetDefaults (PyObject *op,
          PyObject *defaults)

     为函数对象 `op' 设置参数默认值。 `defaults' 必须为 ‘Py_None’ 或一个
     元组。

     失败时引发 *note SystemError: 6f2. 异常并返回 ‘-1’ 。

 -- C 函式: PyObject* PyFunction_GetClosure (PyObject *op)
     `Return value: Borrowed reference.' 返回关联到函数对象 `op' 的闭包
     。 这可以是 ‘NULL’ 或 cell 对象的元组。

 -- C 函式: int PyFunction_SetClosure (PyObject *op, PyObject *closure)

     设置关联到函数对象 `op' 的闭包。 `closure' 必须为 ‘Py_None’ 或 cell
     对象的元组。

     失败时引发 *note SystemError: 6f2. 异常并返回 ‘-1’ 。

 -- C 函式: PyObject *PyFunction_GetAnnotations (PyObject *op)
     `Return value: Borrowed reference.' 返回函数对象 `op' 的标注。 这可
     以是一个可变字典或 ‘NULL’。

 -- C 函式: int PyFunction_SetAnnotations (PyObject *op,
          PyObject *annotations)

     设置函数对象 `op' 的标注。 `annotations' 必须为一个字典或
     ‘Py_None’。

     失败时引发 *note SystemError: 6f2. 异常并返回 ‘-1’ 。


File: python.info,  Node: 實體方法物件,  Next: 方法对象,  Prev: 函式（Function）物件,  Up: 函式物件<2>

7.8.5.2 實體方法物件
....................

实例方法是 *note PyCFunction: e9f. 的包装器，也是将 *note PyCFunction:
e9f. 绑定到类对象的一种新方式。 它替代了原先的调用 ‘PyMethod_New(func,
NULL, class)’。

 -- C 變數: PyTypeObject PyInstanceMethod_Type

     这个 *note PyTypeObject: 3f5. 实例代表 Python 实例方法类型。 它并不
     对 Python 程序公开。

 -- C 函式: int PyInstanceMethod_Check (PyObject *o)

     如果 `o' 是一个实例方法对象 (类型为 *note PyInstanceMethod_Type:
     40ae.) 则返回真值。 形参必须不为 ‘NULL’。 此函数总是会成功执行。

 -- C 函式: PyObject* PyInstanceMethod_New (PyObject *func)
     `Return value: New reference.' 返回一个新的实例方法对象，`func' 应
     为任意可调用对象，`func' 将在实例方法被调用时作为函数被调用。

 -- C 函式: PyObject* PyInstanceMethod_Function (PyObject *im)
     `Return value: Borrowed reference.' 返回关联到实例方法 `im' 的函数
     对象。

 -- C 函式: PyObject* PyInstanceMethod_GET_FUNCTION (PyObject *im)
     `Return value: Borrowed reference.' 宏版本的 *note
     PyInstanceMethod_Function(): 40b1.，略去了错误检测。


File: python.info,  Node: 方法对象,  Next: Cell 物件,  Prev: 實體方法物件,  Up: 函式物件<2>

7.8.5.3 方法对象
................

方法是绑定的函数对象。 方法总是会被绑定到一个用户自定义类的实例。 未绑定
方法（绑定到一个类的方法）已不再可用。

 -- C 變數: PyTypeObject PyMethod_Type

     这个 *note PyTypeObject: 3f5. 实例代表 Python 方法类型。 它作为
     ‘types.MethodType’ 向 Python 程序公开。

 -- C 函式: int PyMethod_Check (PyObject *o)

     如果 `o' 是一个方法对象 (类型为 *note PyMethod_Type: 40b5.) 则返回
     真值。 形参必须不为 ‘NULL’。 此函数总是会成功执行。

 -- C 函式: PyObject* PyMethod_New (PyObject *func, PyObject *self)
     `Return value: New reference.' 返回一个新的方法对象，`func' 应为任
     意可调用对象，`self' 为该方法应绑定的实例。 在方法被调用时 `func' 将
     作为函数被调用。 `self' 必须不为 ‘NULL’。

 -- C 函式: PyObject* PyMethod_Function (PyObject *meth)
     `Return value: Borrowed reference.' 返回关联到方法 `meth' 的函数对
     象。

 -- C 函式: PyObject* PyMethod_GET_FUNCTION (PyObject *meth)
     `Return value: Borrowed reference.' 宏版本的 *note
     PyMethod_Function(): 40b8.，略去了错误检测。

 -- C 函式: PyObject* PyMethod_Self (PyObject *meth)
     `Return value: Borrowed reference.' 返回关联到方法 `meth' 的实例。

 -- C 函式: PyObject* PyMethod_GET_SELF (PyObject *meth)
     `Return value: Borrowed reference.' 宏版本的 *note PyMethod_Self():
     40ba.，略去了错误检测。


File: python.info,  Node: Cell 物件,  Next: 代码对象<2>,  Prev: 方法对象,  Up: 函式物件<2>

7.8.5.4 Cell 物件
.................

“Cell”对象用于实现由多个作用域引用的变量。 对于每个这样的变量，一个
“Cell”对象为了存储该值而被创建；引用该值的每个堆栈框架的局部变量包含同样
使用该变量的对外部作用域的“Cell”引用。 访问该值时，将使用“Cell”中包含的
值而不是单元格对象本身。 这种对“Cell”对象的非关联化的引用需要支持生成的
字节码；访问时不会自动非关联化这些内容。 “Cell”对象在其他地方可能不太有
用。

 -- C 類型: PyCellObject

     C 結構的 cell 物件

 -- C 變數: PyTypeObject PyCell_Type

     對應 cell 物件的物件型別。

 -- C 函式: int PyCell_Check (ob)

     如果 `ob' 是一个 cell 对象则返回真值；`ob' 必须不为 ‘NULL’。 此函数
     总是会成功执行。

 -- C 函式: PyObject* PyCell_New (PyObject *ob)
     `Return value: New reference.' 创建并返回一个包含值 `ob' 的新 cell
     对象。形参可以为 ‘NULL’。

 -- C 函式: PyObject* PyCell_Get (PyObject *cell)
     `Return value: New reference.' 回傳 cell 內容中的 `cell'。

 -- C 函式: PyObject* PyCell_GET (PyObject *cell)
     `Return value: Borrowed reference.' 返回 cell 对象 `cell' 的内容，
     但是不检测 `cell' 是否非 ‘NULL’ 并且为一个 cell 对象。

 -- C 函式: int PyCell_Set (PyObject *cell, PyObject *value)

     将 cell 对象 `cell' 的内容设为 `value'。 这将释放任何对 cell 对象当
     前内容的引用。 `value' 可以为 ‘NULL’。 `cell' 必须为非 ‘NULL’；如果
     它不是一个 cell 对象则将返回 ‘-1’。 如果设置成功则将返回 ‘0’。

 -- C 函式: void PyCell_SET (PyObject *cell, PyObject *value)

     将 cell 对象 `cell' 的值设为 `value'。 不会调整引用计数，并且不会进
     行检测以保证安全；`cell' 必须为非 ‘NULL’ 并且为一个 cell 对象。


File: python.info,  Node: 代码对象<2>,  Prev: Cell 物件,  Up: 函式物件<2>

7.8.5.5 代码对象
................

代码对象是 CPython 实现的低级细节。 每个代表一块尚未绑定到函数中的可执行
代码。

 -- C 類型: PyCodeObject

     用于描述代码对象的对象的 C 结构。 此类型字段可随时更改。

 -- C 變數: PyTypeObject PyCode_Type

     这是一个 *note PyTypeObject: 3f5. 实例，其表示Python的 *note code:
     1a. 类型。

 -- C 函式: int PyCode_Check (PyObject *co)

     如果 `co' 是一个 *note code: 1a. 对象则返回真值。 此函数总是会成功
     执行。

 -- C 函式: int PyCode_GetNumFree (PyCodeObject *co)

     返回 `co' 中的自由变量数。

 -- C 函式: PyCodeObject* PyCode_New (int argcount, int kwonlyargcount,
          int nlocals, int stacksize, int flags, PyObject *code,
          PyObject *consts, PyObject *names, PyObject *varnames,
          PyObject *freevars, PyObject *cellvars, PyObject *filename,
          PyObject *name, int firstlineno, PyObject *lnotab)
     `Return value: New reference.' 返回一个新的代码对象。 如果你需要一
     个虚拟代码对象来创建一个代码帧，请使用 *note PyCode_NewEmpty():
     db1.。 调用 *note PyCode_New(): 39b. 直接可以绑定到准确的 Python 版
     本，因为字节码的定义经常变化。

 -- C 函式: PyCodeObject* PyCode_NewWithPosOnlyArgs (int argcount,
          int posonlyargcount, int kwonlyargcount, int nlocals,
          int stacksize, int flags, PyObject *code, PyObject *consts,
          PyObject *names, PyObject *varnames, PyObject *freevars,
          PyObject *cellvars, PyObject *filename, PyObject *name,
          int firstlineno, PyObject *lnotab)
     `Return value: New reference.' 类似于 *note PyCode_New(): 39b.，但
     带有一个额外的 "posonlyargcount" 用于仅限位置参数。

     3.8 版新加入.

 -- C 函式: PyCodeObject* PyCode_NewEmpty (const char *filename, const
          char *funcname, int firstlineno)
     `Return value: New reference.' 返回具有指定文件名、函数名和第一行号
     的新空代码对象。 对于 *note exec(): d0c. 或 *note eval(): c61. 生成
     的代码对象是非法的。


File: python.info,  Node: 其他对象<2>,  Prev: 函式物件<2>,  Up: 具体的对象层

7.8.6 其他对象
--------------

* Menu:

* 檔案（File）物件::
* 模組物件模組::
* 迭代器（Iterator）物件::
* 修飾器物件::
* 切片物件::
* Ellipsis 对象::
* MemoryView 对象::
* 弱參照物件::
* Capsule 对象::
* 產生器物件::
* 协程对象: 协程对象<2>.
* 上下文变量对象::
* DateTime 物件::
* 类型注解对象::


File: python.info,  Node: 檔案（File）物件,  Next: 模組物件模組,  Up: 其他对象<2>

7.8.6.1 檔案（File）物件
........................

这此 API 是对内置文件对象的 Python 2 C API 的最小仿真，它过去依赖于 C 标
准库的缓冲 I/O (‘FILE*’) 支持。 在 Python 3 中，文件和流使用新的 *note
io: a1. 模块，该模块在操作系统的低层级无缓冲 I/O 之上定义了几个层。 下面
所描述的函数是针对这些新 API 的便捷 C 包装器，主要用于解释器的内部错误报
告；建议第三方代码改为访问 *note io: a1. API。

 -- C 函式: PyObject* PyFile_FromFd (int fd, const char *name, const
          char *mode, int buffering, const char *encoding, const
          char *errors, const char *newline, int closefd)
     `Return value: New reference.' 根据已打开文件 `fd' 的文件描述符创建
     一个 Python 文件对象。 参数 `name', `encoding', `errors' 和
     `newline' 可以为 ‘NULL’ 表示使用默认值；`buffering' 可以为 `-1' 表
     示使用默认值。 `name' 会被忽略仅保留用于向下兼容。 失败时返回
     ‘NULL’。 有关参数的更全面描述，请参阅 *note io.open(): 74d. 函数的
     文档。

          警告: 由于Python流具有自己的缓冲层，因此将它们与 OS 级文件描述
          符混合会产生各种问题（例如数据的意外排序）。

     3.2 版更變: 忽略 `name' 屬性。

 -- C 函式: int PyObject_AsFileDescriptor (PyObject *p)

     将与 `p' 关联的文件描述器返回为 ‘int’ 。 如果对象是整数，则返回其值
     。 如果没有，则调用对象的 *note fileno(): 2069. 方法（如果存在）; 该
     方法必须返回一个整数，该整数作为文件描述器值返回。 设置异常并在失败
     时返回 ‘-1’。

 -- C 函式: PyObject* PyFile_GetLine (PyObject *p, int n)
     `Return value: New reference.'

     等价于 ‘p.readline([n])’ ，这个函数从对象 `p' 中读取一行。 `p' 可以
     是文件对象或具有 *note readline(): 1849. 方法的任何对象。 如果 `n'
     是 ‘0’ ，则无论该行的长度如何，都会读取一行。 如果 `n' 大于‘‘0‘‘，
     则从文件中读取不超过 `n' 个字节；可以返回行的一部分。 在这两种情况
     下，如果立即到达文件末尾，则返回空字符串。 但是，如果 `n' 小于 ‘0’
     ，则无论长度如何都会读取一行，但是如果立即到达文件末尾，则引发
     *note EOFError: d34.。

 -- C 函式: int PyFile_SetOpenCodeHook (Py_OpenCodeHookFunction handler)

     重载 *note io.open_code(): 1050. 的正常行为，将其形参通过所提供的处
     理程序来传递。

     处理程序是一个类型为 ‘PyObject *(*)(PyObject *path, void
     *userData)’ 的函数，其中 `path' 确保为 *note PyUnicodeObject:
     3ffd.。

     `userData' 指针会被传入钩子函数。 因于钩子函数可能由不同的运行时调
     用，该指针不应直接指向 Python 状态。

     鉴于这个钩子专门在导入期间使用的，请避免在新模块执行期间进行导入操
     作，除非已知它们为冻结状态或者是在 ‘sys.modules’ 中可用。

     一旦钩子被设定，它就不能被移除或替换，之后对 *note
     PyFile_SetOpenCodeHook(): 2144. 的调用也将失败，如果解释器已经被初
     始化，函数将返回 -1 并设置一个异常。

     此函数可以安全地在 *note Py_Initialize(): 20f. 之前调用。

     引发一个 *note 审计事件: fa1. ‘setopencodehook’，不附带任何参数。

     3.8 版新加入.

 -- C 函式: int PyFile_WriteObject (PyObject *obj, PyObject *p,
          int flags)

     将对象 `obj' 写入文件对象 `p' 。 `flags' 唯一支持的标志是
     ‘Py_PRINT_RAW’；如果给定，则写入对象的 *note str(): 205. 而不是
     *note repr(): 8b9.。成功时返回 ‘0’，失败时返回 ‘-1’。 将设置适当的
     例外。

 -- C 函式: int PyFile_WriteString (const char *s, PyObject *p)

     寫入字串 `s' 到 檔案物件 `p'。當成功時回傳 0，而當失敗時回傳 -1，並
     會設定合適的例外狀況。


File: python.info,  Node: 模組物件模組,  Next: 迭代器（Iterator）物件,  Prev: 檔案（File）物件,  Up: 其他对象<2>

7.8.6.2 模組物件模組
....................

 -- C 變數: PyTypeObject PyModule_Type

     This instance of *note PyTypeObject: 3f5. represents the Python
     module type.  This is exposed to Python programs as
     ‘types.ModuleType’.

 -- C 函式: int PyModule_Check (PyObject *p)

     Return true if `p' is a module object, or a subtype of a module
     object.  This function always succeeds.

 -- C 函式: int PyModule_CheckExact (PyObject *p)

     Return true if `p' is a module object, but not a subtype of *note
     PyModule_Type: 40da.  This function always succeeds.

 -- C 函式: PyObject* PyModule_NewObject (PyObject *name)
     `Return value: New reference.'

     Return a new module object with the *note __name__: dd8. attribute
     set to `name'.  The module’s *note __name__: dd8, ‘__doc__’, *note
     __package__: a36, and *note __loader__: a37. attributes are filled
     in (all but *note __name__: dd8. are set to ‘None’); the caller is
     responsible for providing a *note __file__: 1562. attribute.

     3.3 版新加入.

     3.4 版更變: *note __package__: a36. and *note __loader__: a37. are
     set to ‘None’.

 -- C 函式: PyObject* PyModule_New (const char *name)
     `Return value: New reference.'  Similar to *note
     PyModule_NewObject(): 40dd, but the name is a UTF-8 encoded string
     instead of a Unicode object.

 -- C 函式: PyObject* PyModule_GetDict (PyObject *module)
     `Return value: Borrowed reference.'

     Return the dictionary object that implements `module'’s namespace;
     this object is the same as the *note __dict__: 5f5. attribute of
     the module object.  If `module' is not a module object (or a
     subtype of a module object), *note SystemError: 6f2. is raised and
     ‘NULL’ is returned.

     It is recommended extensions use other ‘PyModule_*()’ and
     ‘PyObject_*()’ functions rather than directly manipulate a module’s
     *note __dict__: 5f5.

 -- C 函式: PyObject* PyModule_GetNameObject (PyObject *module)
     `Return value: New reference.'

     Return `module'’s *note __name__: dd8. value.  If the module does
     not provide one, or if it is not a string, *note SystemError: 6f2.
     is raised and ‘NULL’ is returned.

     3.3 版新加入.

 -- C 函式: const char* PyModule_GetName (PyObject *module)

     Similar to *note PyModule_GetNameObject(): 40e0. but return the
     name encoded to ‘'utf-8'’.

 -- C 函式: void* PyModule_GetState (PyObject *module)

     Return the "state" of the module, that is, a pointer to the block
     of memory allocated at module creation time, or ‘NULL’.  See *note
     PyModuleDef.m_size: 25d.

 -- C 函式: PyModuleDef* PyModule_GetDef (PyObject *module)

     Return a pointer to the *note PyModuleDef: 258. struct from which
     the module was created, or ‘NULL’ if the module wasn’t created from
     a definition.

 -- C 函式: PyObject* PyModule_GetFilenameObject (PyObject *module)
     `Return value: New reference.'

     Return the name of the file from which `module' was loaded using
     `module'’s *note __file__: 1562. attribute.  If this is not
     defined, or if it is not a unicode string, raise *note SystemError:
     6f2. and return ‘NULL’; otherwise return a reference to a Unicode
     object.

     3.2 版新加入.

 -- C 函式: const char* PyModule_GetFilename (PyObject *module)

     Similar to *note PyModule_GetFilenameObject(): 40e3. but return the
     filename encoded to ’utf-8’.

     3.2 版後已棄用: *note PyModule_GetFilename(): 40e4. raises
     ‘UnicodeEncodeError’ on unencodable filenames, use *note
     PyModule_GetFilenameObject(): 40e3. instead.

* Menu:

* Initializing C modules::
* Module lookup::


File: python.info,  Node: Initializing C modules,  Next: Module lookup,  Up: 模組物件模組

7.8.6.3 Initializing C modules
..............................

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 *note
PyImport_AppendInittab(): f9c.).  See *note 构建C/C++扩展: 3d29. or
*note 对嵌入 Python 功能进行扩展: 3dab. for details.

The initialization function can either pass a module definition instance
to *note PyModule_Create(): 3d26, and return the resulting module
object, or request "multi-phase initialization" by returning the
definition struct itself.

 -- 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.

      -- C 成員函數: PyModuleDef_Base m_base

          Always initialize this member to ‘PyModuleDef_HEAD_INIT’.

      -- C 成員函數: const char *m_name

          Name for the new module.

      -- C 成員函數: const char *m_doc

          Docstring for the module; usually a docstring variable created
          with *note PyDoc_STRVAR: 105a. is used.

      -- C 成員函數: Py_ssize_t m_size

          Module state may be kept in a per-module memory area that can
          be retrieved with *note PyModule_GetState(): 25e, rather than
          in static globals.  This makes modules safe for use in
          multiple sub-interpreters.

          This memory area is allocated based on `m_size' on module
          creation, and freed when the module object is deallocated,
          after the ‘m_free’ function has been called, if present.

          Setting ‘m_size’ to ‘-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 ‘m_size’ is
          required for multi-phase initialization.

          See PEP 3121(1) for more details.

      -- C 成員函數: PyMethodDef* m_methods

          A pointer to a table of module-level functions, described by
          *note PyMethodDef: edd. values.  Can be ‘NULL’ if no functions
          are present.

      -- C 成員函數: PyModuleDef_Slot* m_slots

          An array of slot definitions for multi-phase initialization,
          terminated by a ‘{0, NULL}’ entry.  When using single-phase
          initialization, `m_slots' must be ‘NULL’.

          3.5 版更變: Prior to version 3.5, this member was always set
          to ‘NULL’, and was defined as:

                -- C 成員函數: inquiry m_reload

      -- C 成員函數: traverseproc m_traverse

          A traversal function to call during GC traversal of the module
          object, or ‘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 (*note
          Py_mod_exec: 25c. function).  More precisely, this function is
          not called if ‘m_size’ is greater than 0 and the module state
          (as returned by *note PyModule_GetState(): 25e.) is ‘NULL’.

          3.9 版更變: No longer called before the module state is
          allocated.

      -- C 成員函數: inquiry m_clear

          A clear function to call during GC clearing of the module
          object, or ‘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 (*note
          Py_mod_exec: 25c. function).  More precisely, this function is
          not called if ‘m_size’ is greater than 0 and the module state
          (as returned by *note PyModule_GetState(): 25e.) is ‘NULL’.

          Like *note PyTypeObject.tp_clear: 3d72, this function is not
          `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 *note m_free: 25b. is called directly.

          3.9 版更變: No longer called before the module state is
          allocated.

      -- C 成員函數: freefunc m_free

          A function to call during deallocation of the module object,
          or ‘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 (*note
          Py_mod_exec: 25c. function).  More precisely, this function is
          not called if ‘m_size’ is greater than 0 and the module state
          (as returned by *note PyModule_GetState(): 25e.) is ‘NULL’.

          3.9 版更變: No longer called before the module state is
          allocated.

* Menu:

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

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3121


File: python.info,  Node: Single-phase initialization,  Next: Multi-phase initialization,  Up: Initializing C modules

7.8.6.4 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:

 -- C 函式: PyObject* PyModule_Create (PyModuleDef *def)
     `Return value: New reference.'  Create a new module object, given
     the definition in `def'.  This behaves like *note
     PyModule_Create2(): 40ed. with `module_api_version' set to
     ‘PYTHON_API_VERSION’.

 -- C 函式: PyObject* PyModule_Create2 (PyModuleDef *def,
          int module_api_version)
     `Return value: New reference.'  Create a new module object, given
     the definition in `def', assuming the API version
     `module_api_version'.  If that version does not match the version
     of the running interpreter, a *note RuntimeWarning: 3e2. is
     emitted.

          備註: Most uses of this function should be using *note
          PyModule_Create(): 3d26. instead; only use this if you are
          sure you need it.

Before it is returned from in the initialization function, the resulting
module object is typically populated using functions like *note
PyModule_AddObject(): 10dd.


File: python.info,  Node: Multi-phase initialization,  Next: Low-level module creation functions,  Prev: Single-phase initialization,  Up: Initializing C modules

7.8.6.5 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 `creation
phase', when the module object is created, and the `execution phase',
when it is populated.  The distinction is similar to the *note
__new__(): 974. and *note __init__(): e23. methods of classes.

Unlike modules created using single-phase initialization, these modules
are not singletons: if the `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 *note PyModule_GetState(): 25e.), or its contents (such as the
module’s *note __dict__: 5f5. or individual classes created with *note
PyType_FromSpec(): 23a.).

All modules created using multi-phase initialization are expected to
support *note sub-interpreters: 3e57.  Making sure multiple modules are
independent is typically enough to achieve this.

To request multi-phase initialization, the initialization function
(PyInit_modulename) returns a *note PyModuleDef: 258. instance with
non-empty *note m_slots: 40ea.  Before it is returned, the ‘PyModuleDef’
instance must be initialized with the following function:

 -- C 函式: PyObject* PyModuleDef_Init (PyModuleDef *def)
     `Return value: Borrowed reference.'  Ensures a module definition is
     a properly initialized Python object that correctly reports its
     type and reference count.

     Returns `def' cast to ‘PyObject*’, or ‘NULL’ if an error occurred.

     3.5 版新加入.

The `m_slots' member of the module definition must point to an array of
‘PyModuleDef_Slot’ structures:

 -- C 類型: PyModuleDef_Slot

      -- C 成員函數: int slot

          A slot ID, chosen from the available values explained below.

      -- C 成員函數: void* value

          Value of the slot, whose meaning depends on the slot ID.

     3.5 版新加入.

The `m_slots' array must be terminated by a slot with id 0.

The available slot types are:

 -- C 巨集: Py_mod_create

     Specifies a function that is called to create the module object
     itself.  The `value' pointer of this slot must point to a function
     of the signature:

      -- C 函式: PyObject* create_module (PyObject *spec,
               PyModuleDef *def)

     The function receives a *note ModuleSpec: 1601. instance, as
     defined in PEP 451(1), and the module definition.  It should return
     a new module object, or set an error and return ‘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 ‘Py_mod_create’ slots may not be specified in one module
     definition.

     If ‘Py_mod_create’ is not specified, the import machinery will
     create a normal module object using *note PyModule_New(): 40de.
     The name is taken from `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 *note PyModule_Type: 40da.  Any type can be used, as long as it
     supports setting and getting import-related attributes.  However,
     only ‘PyModule_Type’ instances may be returned if the ‘PyModuleDef’
     has non-‘NULL’ ‘m_traverse’, ‘m_clear’, ‘m_free’; non-zero
     ‘m_size’; or slots other than ‘Py_mod_create’.

 -- C 巨集: Py_mod_exec

     Specifies a function that is called to `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:

      -- C 函式: int exec_module (PyObject* module)

     If multiple ‘Py_mod_exec’ slots are specified, they are processed
     in the order they appear in the `m_slots' array.

See PEP 489(2) for more details on multi-phase initialization.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0451

   (2) https://www.python.org/dev/peps/pep-0489


File: python.info,  Node: Low-level module creation functions,  Next: Support functions,  Prev: Multi-phase initialization,  Up: Initializing C modules

7.8.6.6 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 ‘PyModule_FromDefAndSpec’
and ‘PyModule_ExecDef’ must be called to fully initialize a module.

 -- C 函式: PyObject * PyModule_FromDefAndSpec (PyModuleDef *def,
          PyObject *spec)
     `Return value: New reference.'  Create a new module object, given
     the definition in `module' and the ModuleSpec `spec'.  This behaves
     like *note PyModule_FromDefAndSpec2(): 89a. with
     `module_api_version' set to ‘PYTHON_API_VERSION’.

     3.5 版新加入.

 -- C 函式: PyObject * PyModule_FromDefAndSpec2 (PyModuleDef *def,
          PyObject *spec, int module_api_version)
     `Return value: New reference.'  Create a new module object, given
     the definition in `module' and the ModuleSpec `spec', assuming the
     API version `module_api_version'.  If that version does not match
     the version of the running interpreter, a *note RuntimeWarning:
     3e2. is emitted.

          備註: Most uses of this function should be using *note
          PyModule_FromDefAndSpec(): 899. instead; only use this if you
          are sure you need it.

     3.5 版新加入.

 -- C 函式: int PyModule_ExecDef (PyObject *module, PyModuleDef *def)

     Process any execution slots (*note Py_mod_exec: 25c.) given in
     `def'.

     3.5 版新加入.

 -- C 函式: int PyModule_SetDocString (PyObject *module, const
          char *docstring)

     Set the docstring for `module' to `docstring'.  This function is
     called automatically when creating a module from ‘PyModuleDef’,
     using either ‘PyModule_Create’ or ‘PyModule_FromDefAndSpec’.

     3.5 版新加入.

 -- C 函式: int PyModule_AddFunctions (PyObject *module,
          PyMethodDef *functions)

     Add the functions from the ‘NULL’ terminated `functions' array to
     `module'.  Refer to the *note PyMethodDef: edd. 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 ‘PyModuleDef’, using
     either ‘PyModule_Create’ or ‘PyModule_FromDefAndSpec’.

     3.5 版新加入.


File: python.info,  Node: Support functions,  Prev: Low-level module creation functions,  Up: Initializing C modules

7.8.6.7 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:

 -- C 函式: int PyModule_AddObject (PyObject *module, const char *name,
          PyObject *value)

     Add an object to `module' as `name'.  This is a convenience
     function which can be used from the module’s initialization
     function.  This steals a reference to `value' on success.  Return
     ‘-1’ on error, ‘0’ on success.

          備註: Unlike other functions that steal references,
          ‘PyModule_AddObject()’ only decrements the reference count of
          `value' `on success'.

          This means that its return value must be checked, and calling
          code must *note Py_DECREF(): 38f. `value' manually on error.
          Example usage:

               Py_INCREF(spam);
               if (PyModule_AddObject(module, "spam", spam) < 0) {
                   Py_DECREF(module);
                   Py_DECREF(spam);
                   return NULL;
               }

 -- C 函式: int PyModule_AddIntConstant (PyObject *module, const
          char *name, long value)

     Add an integer constant to `module' as `name'.  This convenience
     function can be used from the module’s initialization function.
     Return ‘-1’ on error, ‘0’ on success.

 -- C 函式: int PyModule_AddStringConstant (PyObject *module, const
          char *name, const char *value)

     Add a string constant to `module' as `name'.  This convenience
     function can be used from the module’s initialization function.
     The string `value' must be ‘NULL’-terminated.  Return ‘-1’ on
     error, ‘0’ on success.

 -- C 函式: int PyModule_AddIntMacro (PyObject *module, macro)

     Add an int constant to `module'.  The name and the value are taken
     from `macro'.  For example ‘PyModule_AddIntMacro(module, AF_INET)’
     adds the int constant `AF_INET' with the value of `AF_INET' to
     `module'.  Return ‘-1’ on error, ‘0’ on success.

 -- C 函式: int PyModule_AddStringMacro (PyObject *module, macro)

     Add a string constant to `module'.

 -- C 函式: int PyModule_AddType (PyObject *module, PyTypeObject *type)

     Add a type object to `module'.  The type object is finalized by
     calling internally *note PyType_Ready(): 3d5d.  The name of the
     type object is taken from the last component of *note tp_name:
     3d75. after dot.  Return ‘-1’ on error, ‘0’ on success.

     3.9 版新加入.


File: python.info,  Node: Module lookup,  Prev: Initializing C modules,  Up: 模組物件模組

7.8.6.8 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.

 -- C 函式: PyObject* PyState_FindModule (PyModuleDef *def)
     `Return value: Borrowed reference.'  Returns the module object that
     was created from `def' for the current interpreter.  This method
     requires that the module object has been attached to the
     interpreter state with *note PyState_AddModule(): 40ff. beforehand.
     In case the corresponding module object is not found or has not
     been attached to the interpreter state yet, it returns ‘NULL’.

 -- C 函式: int PyState_AddModule (PyObject *module, PyModuleDef *def)

     Attaches the module object passed to the function to the
     interpreter state.  This allows the module object to be accessible
     via *note PyState_FindModule(): 40fe.

     Only effective on modules created using single-phase
     initialization.

     Python calls ‘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 ‘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 版新加入.

 -- C 函式: int PyState_RemoveModule (PyModuleDef *def)

     Removes the module object created from `def' from the interpreter
     state.  Return 0 on success or -1 on failure.

     呼叫者必须持有GIL。

     3.3 版新加入.


File: python.info,  Node: 迭代器（Iterator）物件,  Next: 修飾器物件,  Prev: 模組物件模組,  Up: 其他对象<2>

7.8.6.9 迭代器（Iterator）物件
..............................

Python 提供了两个通用迭代器对象。 第一个是序列迭代器，它使用支持 *note
__getitem__(): 3a5. 方法的任意序列。 第二个使用可调用对象和一个 sentinel
值，为序列中的每个项调用可调用对象，并在返回 sentinel 值时结束迭代。

 -- C 變數: PyTypeObject PySeqIter_Type

     *note PySeqIter_New(): 4105. 返回迭代器对象的类型对象和内置序列类型
     内置函数 *note iter(): ded. 的单参数形式。

 -- C 函式: int PySeqIter_Check (op)

     如果 `op' 的类型为 *note PySeqIter_Type: 4104. 则返回真值。 此函数
     总是会成功执行。

 -- C 函式: PyObject* PySeqIter_New (PyObject *seq)
     `Return value: New reference.' 返回一个与常规序列对象一起使用的迭代
     器 `seq'。 当序列订阅操作引发 *note IndexError: f36. 时，迭代结束。

 -- C 變數: PyTypeObject PyCallIter_Type

     由函数 *note PyCallIter_New(): 4108. 和 *note iter(): ded. 内置函数
     的双参数形式返回的迭代器对象类型对象。

 -- C 函式: int PyCallIter_Check (op)

     如果 `op' 的类型为 *note PyCallIter_Type: 4107. 则返回真值。 此函数
     总是会成功执行。

 -- C 函式: PyObject* PyCallIter_New (PyObject *callable,
          PyObject *sentinel)
     `Return value: New reference.' 返回一个新的迭代器。 第一个参数
     `callable' 可以是任何可以在没有参数的情况下调用的 Python 可调用对象
     ；每次调用都应该返回迭代中的下一个项目。 当 `callable' 返回等于
     `sentinel' 的值时，迭代将终止。


File: python.info,  Node: 修飾器物件,  Next: 切片物件,  Prev: 迭代器（Iterator）物件,  Up: 其他对象<2>

7.8.6.10 修飾器物件
...................

“描述符”是描述对象的某些属性的对象。它们存在于类型对象的字典中。

 -- C 變數: PyTypeObject PyProperty_Type

     内建描述符类型的类型对象。

 -- C 函式: PyObject* PyDescr_NewGetSet (PyTypeObject *type, struct
          PyGetSetDef *getset)
     `Return value: New reference.'

 -- C 函式: PyObject* PyDescr_NewMember (PyTypeObject *type, struct
          PyMemberDef *meth)
     `Return value: New reference.'

 -- C 函式: PyObject* PyDescr_NewMethod (PyTypeObject *type, struct
          PyMethodDef *meth)
     `Return value: New reference.'

 -- C 函式: PyObject* PyDescr_NewWrapper (PyTypeObject *type, struct
          wrapperbase *wrapper, void *wrapped)
     `Return value: New reference.'

 -- C 函式: PyObject* PyDescr_NewClassMethod (PyTypeObject *type,
          PyMethodDef *method)
     `Return value: New reference.'

 -- C 函式: int PyDescr_IsData (PyObject *descr)

     如果描述符对象 `descr' 描述数据属性，则返回true；如果描述方法，则返
     回false。 `descr' 必须是描述符对象；没有错误检查。

 -- C 函式: PyObject* PyWrapper_New (PyObject *, PyObject *)
     `Return value: New reference.'


File: python.info,  Node: 切片物件,  Next: Ellipsis 对象,  Prev: 修飾器物件,  Up: 其他对象<2>

7.8.6.11 切片物件
.................

 -- C 變數: PyTypeObject PySlice_Type

     切片对象的类型对象。 它与 Python 层面的 *note slice: ec8. 是相同的
     对象。

 -- C 函式: int PySlice_Check (PyObject *ob)

     如果 `ob' 是一个 slice 对象则返回真值；`ob' 必须不为 ‘NULL’。 此函
     数总是会成功执行。

 -- C 函式: PyObject* PySlice_New (PyObject *start, PyObject *stop,
          PyObject *step)
     `Return value: New reference.' 返回一个具有给定值的新切片对象。
     `start', `stop' 和 `step' 形参会被用作 slice 对象相应名称的属性的值
     。 这些值中的任何一个都可以为 ‘NULL’，在这种情况下将使用 ‘None’ 作
     为对应属性的值。 如果新对象无法被分配则返回 ‘NULL’。

 -- C 函式: int PySlice_GetIndices (PyObject *slice, Py_ssize_t length,
          Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step)

     从切片对象 `slice' 提取 start, stop 和 step 索引号，将序列长度视为
     `length'。 大于 `length' 的序列号将被当作错误。

     成功时返回 ‘0’，出错时返回 ‘-1’ 并且不设置异常（除非某个序列号不为
     *note None: 203. 且无法被转换为整数，在这种情况下会返回 ‘-1’ 并且设
     置一个异常）。

     你可能不会打算使用此函数。

     3.2 版更變: 之前 `slice' 形参的形参类型是 ‘PySliceObject*’。

 -- C 函式: int PySlice_GetIndicesEx (PyObject *slice,
          Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop,
          Py_ssize_t *step, Py_ssize_t *slicelength)

     *note PySlice_GetIndices(): 411a. 的可用替代。 从切片对象 `slice' 提
     取 start, stop 和 step 索引号，将序列长度视为 `length'，并将切片的
     长度保存在 `slicelength' 中，超出范围的索引号会以与普通切片一致的方
     式进行剪切。

     成功时返回 ‘0’，出错时返回 ‘-1’ 并且不设置异常。

          備註: 此函数对于可变大小序列来说是不安全的。 对它的调用应被替
          换为 *note PySlice_Unpack(): 532. 和 *note
          PySlice_AdjustIndices(): 533. 的组合，其中

               if (PySlice_GetIndicesEx(slice, length, &start, &stop, &step, &slicelength) < 0) {
                   // return error
               }

          会被替换为

               if (PySlice_Unpack(slice, &start, &stop, &step) < 0) {
                   // return error
               }
               slicelength = PySlice_AdjustIndices(length, &start, &stop, step);

     3.2 版更變: 之前 `slice' 形参的形参类型是 ‘PySliceObject*’。

     3.6.1 版更變: 如果 ‘Py_LIMITED_API’ 未设置或设置为 ‘0x03050400’ 与
     ‘0x03060000’ 之间的值（不包括边界）或 ‘0x03060100’ 或更大则
     ‘PySlice_GetIndicesEx()’ 会被实现为一个使用 ‘PySlice_Unpack()’ 和
     ‘PySlice_AdjustIndices()’ 的宏。 参数 `start', `stop' 和 `step' 会
     被多被求值。

     3.6.1 版後已棄用: 如果 ‘Py_LIMITED_API’ 设置为小于 ‘0x03050400’ 或
     ‘0x03060000’ 与 ‘0x03060100’ 之间的值（不包括边界）则
     ‘PySlice_GetIndicesEx()’ 为已弃用的函数。

 -- C 函式: int PySlice_Unpack (PyObject *slice, Py_ssize_t *start,
          Py_ssize_t *stop, Py_ssize_t *step)

     从切片对象中将 start, stop 和 step 数据成员提取为 C 整数。 会静默地
     将大于 ‘PY_SSIZE_T_MAX’ 的值减小为 ‘PY_SSIZE_T_MAX’，静默地将小于
     ‘PY_SSIZE_T_MIN’ 的 start 和 stop 值增大为 ‘PY_SSIZE_T_MIN’，并静默
     地将小于 ‘-PY_SSIZE_T_MAX’ 的 step 值增大为 ‘-PY_SSIZE_T_MAX’。

     出错时返回 ‘-1’，成功时返回 ‘0’。

     3.6.1 版新加入.

 -- C 函式: Py_ssize_t PySlice_AdjustIndices (Py_ssize_t length,
          Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t step)

     将 start/end 切片索引号根据指定的序列长度进行调整。 超出范围的索引
     号会以与普通切片一致的方式进行剪切。

     返回切片的长度。 此操作总是会成功。 不会调用 Python 代码。

     3.6.1 版新加入.


File: python.info,  Node: Ellipsis 对象,  Next: MemoryView 对象,  Prev: 切片物件,  Up: 其他对象<2>

7.8.6.12 Ellipsis 对象
......................

 -- C 變數: PyObject *Py_Ellipsis

     Python 的 ‘Ellipsis’ 对象。 该对象没有任何方法。 它必须以与任何其他
     对象一样的方式遵循引用计数。 它与 *note Py_None: 3d23. 一样属于单例
     对象。


File: python.info,  Node: MemoryView 对象,  Next: 弱參照物件,  Prev: Ellipsis 对象,  Up: 其他对象<2>

7.8.6.13 MemoryView 对象
........................

一个 *note memoryview: 386. 对象C级别的 *note 缓冲区接口: 171c. 暴露为一
个可以像任何其他对象一样传递的 Python 对象。

 -- C 函式: PyObject *PyMemoryView_FromObject (PyObject *obj)
     `Return value: New reference.' 从提供缓冲区接口的对象创建
     memoryview 对象。 如果 `obj' 支持可写缓冲区导出，则 memoryview 对象
     将可以被读/写，否则它可能是只读的，也可以是导出器自行决定的读/写。

 -- C 函式: PyObject *PyMemoryView_FromMemory (char *mem,
          Py_ssize_t size, int flags)
     `Return value: New reference.' 使用 `mem' 作为底层缓冲区创建一个
     memoryview 对象。 `flags' 可以是 ‘PyBUF_READ’ 或者 ‘PyBUF_WRITE’ 之
     一.

     3.3 版新加入.

 -- C 函式: PyObject *PyMemoryView_FromBuffer (Py_buffer *view)
     `Return value: New reference.' 创建一个包含给定缓冲区结构 `view' 的
     memoryview 对象。 对于简单的字节缓冲区，*note
     PyMemoryView_FromMemory(): ba0. 是首选函数。

 -- C 函式: PyObject *PyMemoryView_GetContiguous (PyObject *obj,
          int buffertype, char order)
     `Return value: New reference.' 从定义缓冲区接口的对象创建一个
     memoryview 对象 *note contiguous: 17ec. 内存块（在 ’C’ 或 ’F’ortran
     `order' 中）。 如果内存是连续的，则 memoryview 对象指向原始内存。 否
     则，复制并且 memoryview 指向新的 bytes 对象。

 -- C 函式: int PyMemoryView_Check (PyObject *obj)

     如果 `obj' 是一个 memoryview 对象则返回真值。 目前不允许创建 *note
     memoryview: 386. 的子类。 此函数总是会成功执行。

 -- C 函式: Py_buffer *PyMemoryView_GET_BUFFER (PyObject *mview)

     返回指向 memoryview 的导出缓冲区私有副本的指针。 `mview' `必须' 是
     一个 memoryview 实例；这个宏不检查它的类型，你必须自己检查，否则你
     将面临崩溃风险。

 -- C 函式: Py_buffer *PyMemoryView_GET_BASE (PyObject *mview)

     返回 memoryview 所基于的导出对象的指针，或者如果 memoryview 已由函
     数 *note PyMemoryView_FromMemory(): ba0. 或 *note
     PyMemoryView_FromBuffer(): 3f43. 创建则返回 ‘NULL’。 `mview' `必须'
     是一个 memoryview 实例。


File: python.info,  Node: 弱參照物件,  Next: Capsule 对象,  Prev: MemoryView 对象,  Up: 其他对象<2>

7.8.6.14 弱參照物件
...................

Python 支持 “弱引用” 作为一类对象。具体来说，有两种直接实现弱引用的对象
。第一种就是简单的引用对象，第二种尽可能地作用为一个原对象的代理。

 -- C 函式: int PyWeakref_Check (ob)

     如果 `ob' 是一个引用或代理对象则返回真值。 此函数总是会成功执行。

 -- C 函式: int PyWeakref_CheckRef (ob)

     如果 `ob' 是一个引用对象则返回真值。 此函数总是会成功执行。

 -- C 函式: int PyWeakref_CheckProxy (ob)

     如果 `ob' 是一个代理对象则返回真值。 此函数总是会成功执行。

 -- C 函式: PyObject* PyWeakref_NewRef (PyObject *ob,
          PyObject *callback)
     `Return value: New reference.' 返回对象 `ob' 的一个弱引用对象。 该
     函数总是会返回一个新引用，但不保证创建一个新的对象；它有可能返回一
     个现有的引用对象。 第二个形参 `callback' 为一个可调用对象，它会在
     `ob' 被作为垃圾回收时接收通知；它应该接受一个单独形参，即弱引用对象
     本身。 `callback' 也可以为 ‘None’ 或 ‘NULL’。 如果 `ob' 不是一个弱
     引用对象，或者如果 `callback' 不是可调用对象，‘None’ 或 ‘NULL’，该
     函数将返回 ‘NULL’ 并且引发 *note TypeError: 1fe.。

 -- C 函式: PyObject* PyWeakref_NewProxy (PyObject *ob,
          PyObject *callback)
     `Return value: New reference.' 返回对象 `ob' 的一个弱引用代理对象。
     该函数将总是返回一个新的引用，但不保证创建一个新的对象；它有可能返
     回一个现有的代理对象。 第二个形参 `callback' 为一个可调用对象，它会
     在 `ob' 被作为垃圾回收时接收通知；它应该接受一个单独形参，即弱引用
     对象本身。 `callback' 也可以为 ‘None’ 或 ‘NULL’。 如果 `ob' 不是一
     个弱引用对象，或者如果 `callback' 不是可调用对象，‘None’ 或 ‘NULL’，
     该函数将返回 ‘NULL’ 并且引发 *note TypeError: 1fe.。

 -- C 函式: PyObject* PyWeakref_GetObject (PyObject *ref)
     `Return value: Borrowed reference.' 返回弱引用对象 ref 的被引用对象
     。如果被引用对象不再存在，则返回 ‘Py_None’。

          備註: 该函数返回被引用对象的一个**借来的引用**。这意味着除非你
          很清楚在你使用期间这个对象不可能被销毁，否则你应该始终对该对象
          调用 *note Py_INCREF(): 38e.。

 -- C 函式: PyObject* PyWeakref_GET_OBJECT (PyObject *ref)
     `Return value: Borrowed reference.' 类似 *note
     PyWeakref_GetObject(): 412c.，但实现为一个不做类型检查的宏。


File: python.info,  Node: Capsule 对象,  Next: 產生器物件,  Prev: 弱參照物件,  Up: 其他对象<2>

7.8.6.15 Capsule 对象
.....................

有关使用这些对象的更多信息请参阅 *note 给扩展模块提供C API: db7.。

3.1 版新加入.

 -- C 類型: PyCapsule

     这个 *note PyObject: 5b4. 的子类型代表一个隐藏的值，适用于需要将隐
     藏值（作为 ‘void*’ 指针）通过 Python 代码传递到其他 C 代码的 C 扩展
     模块。 它常常被用来让在一个模块中定义的 C 函数指针在其他模块中可用
     ，这样就可以使用常规导入机制来访问在动态加载的模块中定义的 C API。

 -- C 類型: PyCapsule_Destructor

     Capsule 的析构器回调的类型。 定义如下：

          typedef void (*PyCapsule_Destructor)(PyObject *);

     参阅 *note PyCapsule_New(): 3d49. 来获取 PyCapsule_Destructor 返回
     值的语义。

 -- C 函式: int PyCapsule_CheckExact (PyObject *p)

     如果参数是一个 *note PyCapsule: cd2. 则返回真值。 此函数总是会成功
     执行。

 -- C 函式: PyObject* PyCapsule_New (void *pointer, const char *name,
          PyCapsule_Destructor destructor)
     `Return value: New reference.' 创建一个封装了 `pointer' 的 *note
     PyCapsule: cd2.。 `pointer' 参考可以不为 ‘NULL’。

     在失败时设置一个异常并返回 ‘NULL’。

     字符串 `name' 可以是 ‘NULL’ 或是一个指向有效的 C 字符串的指针。 如
     果不为 ‘NULL’，则此字符串必须比 capsule 长（虽然也允许在
     `destructor' 中释放它。）

     如果 `destructor' 参数不为 ‘NULL’，则当它被销毁时将附带 capsule 作
     为参数来调用。

     如果此 capsule 将被保存为一个模块的属性，则 `name' 应当被指定为
     ‘modulename.attributename’。 这将允许其他模块使用 *note
     PyCapsule_Import(): 3d4a. 来导入此 capsule。

 -- C 函式: void* PyCapsule_GetPointer (PyObject *capsule, const
          char *name)

     提取保存在 capsule 中的 `pointer'。 在失败时设置一个异常并返回
     ‘NULL’。

     `name' 形参必须与保存在 capsule 中的名称进行精确比较。 如果保存在
     capsule 中的名称为 ‘NULL’，则传入的 `name' 也必须为 ‘NULL’。 Python
     会使用 C 函数 ‘strcmp()’ 来比较 capsule 名称。

 -- C 函式: PyCapsule_Destructor PyCapsule_GetDestructor
          (PyObject *capsule)

     返回保存在 capsule 中的当前析构器。 在失败时设置一个异常并返回
     ‘NULL’。

     capsule 具有 ‘NULL’ 析构器是合法的。 这会使得 ‘NULL’ 返回码有些歧义
     ；请使用 *note PyCapsule_IsValid(): db6. 或 *note PyErr_Occurred():
     3d1e. 来消除歧义。

 -- C 函式: void* PyCapsule_GetContext (PyObject *capsule)

     返回保存在 capsule 中的当前上下文。 在失败时设置一个异常并返回
     ‘NULL’。

     capsule 具有 ‘NULL’ 上下文是全法的。 这会使得 ‘NULL’ 返回码有些歧义
     ；请使用 *note PyCapsule_IsValid(): db6. 或 *note PyErr_Occurred():
     3d1e. 来消除歧义。

 -- C 函式: const char* PyCapsule_GetName (PyObject *capsule)

     返回保存在 capsule 中的当前名称。 在失败时设置一个异常并返回
     ‘NULL’。

     capsule 具有 ‘NULL’ 名称是合法的。 这会使得 ‘NULL’ 返回码有些歧义；
     请使用 *note PyCapsule_IsValid(): db6. 或 *note PyErr_Occurred():
     3d1e. 来消除歧义。

 -- C 函式: void* PyCapsule_Import (const char *name, int no_block)

     从一个模块的 capsule 属性导入指向 C 对象的指针。 `name' 形参应当指
     定属性的完整名称，与 ‘module.attribute’ 中的一致。 保存在 capsule 中
     的 `name' 必须完全匹配此字符串。 如果 `no_block' 为真值，则以无阻塞
     模式导入模块 (使用 *note PyImport_ImportModuleNoBlock(): aa0.)。 如
     果 `no_block' 为假值，则以传统模式导入模块 (使用 *note
     PyImport_ImportModule(): d3b.)。

     成功时返回 capsule 的内部 `指针'。 在失败时设置一个异常并返回
     ‘NULL’。

 -- C 函式: int PyCapsule_IsValid (PyObject *capsule, const char *name)

     确定 `capsule' 是否是一个有效的。 有效的 capsule 必须不为 ‘NULL’，
     传递 *note PyCapsule_CheckExact(): 4131.，在其中存储一个不为 ‘NULL’
     的指针，并且其内部名称与 `name' 形参相匹配。 （请参阅 *note
     PyCapsule_GetPointer(): 4132. 了解如何对 capsule 名称进行比较的有关
     信息。）

     换句话说，如果 *note PyCapsule_IsValid(): db6. 返回真值，则任何对访
     问器（以 ‘PyCapsule_Get()’ 开头的任何函数）的调用都保证会成功。

     如果对象有效并且匹配传入的名称则返回非零值。 否则返回 ‘0’。 此函数
     一定不会失败。

 -- C 函式: int PyCapsule_SetContext (PyObject *capsule, void *context)

     将 `capsule' 内部的上下文指针设为 `context'。

     成功时返回 ‘0’。 失败时返回非零值并设置一个异常。

 -- C 函式: int PyCapsule_SetDestructor (PyObject *capsule,
          PyCapsule_Destructor destructor)

     将 `capsule' 内部的析构器设为 `destructor'。

     成功时返回 ‘0’。 失败时返回非零值并设置一个异常。

 -- C 函式: int PyCapsule_SetName (PyObject *capsule, const char *name)

     将 `capsule' 内部的名称设为 `name'。 如果不为 ‘NULL’，则名称的存在
     期必须比 capsule 更长。 如果之前保存在 capsule 中的 `name' 不为
     ‘NULL’，则不会尝试释放它。

     成功时返回 ‘0’。 失败时返回非零值并设置一个异常。

 -- C 函式: int PyCapsule_SetPointer (PyObject *capsule, void *pointer)

     将 `capsule' 内部的空指针设为 `pointer'。 指针不可为 ‘NULL’。

     成功时返回 ‘0’。 失败时返回非零值并设置一个异常。


File: python.info,  Node: 產生器物件,  Next: 协程对象<2>,  Prev: Capsule 对象,  Up: 其他对象<2>

7.8.6.16 產生器物件
...................

生成器对象是Python用来实现生成器迭代器的对象。它们通常通过迭代产生值的函
数来创建，而不是显式调用 *note PyGen_New(): 413d. 或 *note
PyGen_NewWithQualName(): 413e.。

 -- C 類型: PyGenObject

     用于生成器对象的C结构体。

 -- C 變數: PyTypeObject PyGen_Type

     与生成器对象对应的类型对​​象。

 -- C 函式: int PyGen_Check (PyObject *ob)

     如果 `ob' 是一个 generator 对象则返回真值；`ob' 必须不为 ‘NULL’。 此
     函数总是会成功执行。

 -- C 函式: int PyGen_CheckExact (PyObject *ob)

     如果 `ob' 的类型是 *note PyGen_Type: 4140. 则返回真值；`ob' 必须不
     为 ‘NULL’。 此函数总是会成功执行。

 -- C 函式: PyObject* PyGen_New (PyFrameObject *frame)
     `Return value: New reference.' 基于 `frame' 对象创建并返回一个新的
     生成器对象。 此函数会取走一个对 `frame' 的引用。 参数必须不为
     ‘NULL’。

 -- C 函式: PyObject* PyGen_NewWithQualName (PyFrameObject *frame,
          PyObject *name, PyObject *qualname)
     `Return value: New reference.' 基于 `frame' 对象创建并返回一个新的
     生成器对象，其中 ‘__name__’ 和 ‘__qualname__’ 设为 `name' 和
     `qualname'。 此函数会取走一个对 `frame' 的引用。 `frame' 参数必须不
     为 ‘NULL’。


File: python.info,  Node: 协程对象<2>,  Next: 上下文变量对象,  Prev: 產生器物件,  Up: 其他对象<2>

7.8.6.17 协程对象
.................

3.5 版新加入.

协程对象是使用 ‘async’ 关键字声明的函数返回的。

 -- C 類型: PyCoroObject

     用于协程对象的C结构体。

 -- C 變數: PyTypeObject PyCoro_Type

     与协程对象对应的类型对​​象。

 -- C 函式: int PyCoro_CheckExact (PyObject *ob)

     如果 `ob' 的类型是 *note PyCoro_Type: 4146. 则返回真值；`ob' 必须不
     为 ‘NULL’。 此函数总是会成功执行。

 -- C 函式: PyObject* PyCoro_New (PyFrameObject *frame, PyObject *name,
          PyObject *qualname)
     `Return value: New reference.' 基于 `frame' 对象创建并返回一个新的
     协程对象，其中 ‘__name__’ 和 ‘__qualname__’ 设为 `name' 和
     `qualname'。 此函数会取得一个对 `frame' 的引用。 `frame' 参数必须不
     为 ‘NULL’。


File: python.info,  Node: 上下文变量对象,  Next: DateTime 物件,  Prev: 协程对象<2>,  Up: 其他对象<2>

7.8.6.18 上下文变量对象
.......................

     備註 3.7.1 版更變:: 在 Python 3.7.1 中，所有上下文变量 C API 的签名
     被 `更改' 为使用 *note PyObject: 5b4. 指针而不是 *note PyContext:
     414b, *note PyContextVar: 414c. 以及 *note PyContextToken: 414d.，
     例如:

          // in 3.7.0:
          PyContext *PyContext_New(void);

          // in 3.7.1+:
          PyObject *PyContext_New(void);

     请参阅 bpo-34762(1) 了解详情。

3.7 版新加入.

本节深入介绍了 *note contextvars: 24. 模块的公用 C API。

 -- C 類型: PyContext

     用于表示 *note contextvars.Context: 260f. 对象的 C 结构体。

 -- C 類型: PyContextVar

     用于表示 *note contextvars.ContextVar: 260d. 对象的 C 结构体。

 -- C 類型: PyContextToken

     用于表示 *note contextvars.Token: 2614. 对象的 C 结构体。

 -- C 變數: PyTypeObject PyContext_Type

     表示 `context' 类型的类型对象。

 -- C 變數: PyTypeObject PyContextVar_Type

     表示 `context variable' 类型的类型对象。

 -- C 變數: PyTypeObject PyContextToken_Type

     表示 `context variable token' 类型的类型对象。

类型检查宏：

 -- C 函式: int PyContext_CheckExact (PyObject *o)

     如果 `o' 的类型为 *note PyContext_Type: 414e. 则返回真值。 `o' 必须
     不为 ‘NULL’。 此函数总是会成功执行。

 -- C 函式: int PyContextVar_CheckExact (PyObject *o)

     如果 `o' 的类型为 *note PyContextVar_Type: 414f. 则返回真值。 `o' 必
     须不为 ‘NULL’。 此函数总是会成功执行。

 -- C 函式: int PyContextToken_CheckExact (PyObject *o)

     如果 `o' 的类型为 *note PyContextToken_Type: 4150. 则返回真值。 `o'
     必须不为 ‘NULL’。 此函数总是会成功执行。

上下文对象管理函数:

 -- C 函式: PyObject *PyContext_New (void)
     `Return value: New reference.' 创建一个新的空上下文对象。 如果发生
     错误则返回 ‘NULL’。

 -- C 函式: PyObject *PyContext_Copy (PyObject *ctx)
     `Return value: New reference.' 创建所传入的 `ctx' 上下文对象的浅拷
     贝。 如果发生错误则返回 ‘NULL’。

 -- C 函式: PyObject *PyContext_CopyCurrent (void)
     `Return value: New reference.' 创建当前线程上下文的浅拷贝。 如果发
     生错误则返回 ‘NULL’。

 -- C 函式: int PyContext_Enter (PyObject *ctx)

     将 `ctx' 设为当前线程的当前上下文。 成功时返回 ‘0’，出错时返回
     ‘-1’。

 -- C 函式: int PyContext_Exit (PyObject *ctx)

     取消激活 `ctx' 上下文并将之前的上下文恢复为当前线程的当前上下文。 成
     功时返回 ‘0’，出错时返回 ‘-1’。

上下文变量函数:

 -- C 函式: PyObject *PyContextVar_New (const char *name, PyObject *def)
     `Return value: New reference.' 创建一个新的 ‘ContextVar’ 对象。 形
     参 `name' 用于自我检查和调试目的。 形参 `def' 为上下文变量指定默认
     值，或为 ‘NULL’ 表示无默认值。 如果发生错误，这个函数会返回 ‘NULL’。

 -- C 函式: int PyContextVar_Get (PyObject *var,
          PyObject *default_value, PyObject **value)

     获取上下文变量的值。如果在查找过程中发生错误，返回’ ’ -1 ’ ’，如果
     没有发生错误，无论是否找到值，都返回’ ’ 0 ’ ’，

     如果找到上下文变量，`value' 将是指向它的指针。 如果上下文变量 `没有
     ' 找到，`value' 将指向：

        - `default_value'，如果非‘‘NULL‘‘;

        - `var' 的默认值，如果不是 ‘NULL’；

        - ‘NULL’

     除了返回 ‘NULL’，这个函数会返回一个新的引用。

 -- C 函式: PyObject *PyContextVar_Set (PyObject *var, PyObject *value)
     `Return value: New reference.' 在当前上下文中将 `var' 设为 `value'。
     返回针对此修改的新凭据对象，或者如果发生错误则返回 ‘NULL’。

 -- C 函式: int PyContextVar_Reset (PyObject *var, PyObject *token)

     将上下文变量 `var' 的状态重置为它在返回 `token' 的 *note
     PyContextVar_Set(): 415b. 被调用之前的状态。 此函数成功时返回 ‘0’，
     出错时返回 ‘-1’。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue34762


File: python.info,  Node: DateTime 物件,  Next: 类型注解对象,  Prev: 上下文变量对象,  Up: 其他对象<2>

7.8.6.19 DateTime 物件
......................

*note datetime: 30. 模块提供了各种日期和时间对象。 在使用任何这些函数之
前，必须在你的源码中包含头文件 ‘datetime.h’ (请注意此文件并未包含在
‘Python.h’ 中)，并且宏 ‘PyDateTime_IMPORT’ 必须被发起调用，通常是作为模
块初始化函数的一部分。 这个宏会将指向特定 C 结构的指针放入一个静态变量
‘PyDateTimeAPI’ 中，它会由下面的宏来使用。

宏访问UTC单例:

 -- C 變數: PyObject* PyDateTime_TimeZone_UTC

     返回表示 UTC 的时区单例，与 *note datetime.timezone.utc: 1a28. 为同
     一对象。

     3.7 版新加入.

类型检查宏：

 -- C 函式: int PyDate_Check (PyObject *ob)

     如果 `ob' 为 ‘PyDateTime_DateType’ 类型或 ‘PyDateTime_DateType’ 的
     某个子类型则返回真值。 `ob' 不能为 ‘NULL’。 此函数总是会成功执行。

 -- C 函式: int PyDate_CheckExact (PyObject *ob)

     如果 `ob' 为 ‘PyDateTime_DateType’ 类型则返回真值。 `ob' 不能为
     ‘NULL’。 此函数总是会成功执行。

 -- C 函式: int PyDateTime_Check (PyObject *ob)

     如果 `ob' 为 ‘PyDateTime_DateTimeType’ 类型或
     ‘PyDateTime_DateTimeType’ 的某个子类型则返回真值。 `ob' 不能为
     ‘NULL’。 此函数总是会成功执行。

 -- C 函式: int PyDateTime_CheckExact (PyObject *ob)

     如果 `ob' 为 ‘PyDateTime_DateTimeType’ 类型则返回真值。 `ob' 不能为
     ‘NULL’。 此函数总是会成功执行。

 -- C 函式: int PyTime_Check (PyObject *ob)

     如果 `ob' 的类型是 ‘PyDateTime_TimeType’ 或是 ‘PyDateTime_TimeType’
     的子类型则返回真值。 `ob' 必须不为 ‘NULL’。 此函数总是会成功执行。

 -- C 函式: int PyTime_CheckExact (PyObject *ob)

     如果 `ob' 为 ‘PyDateTime_TimeType’ 类型则返回真值。 `ob' 不能为
     ‘NULL’。 此函数总是会成功执行。

 -- C 函式: int PyDelta_Check (PyObject *ob)

     如果 `ob' 为 ‘PyDateTime_DeltaType’ 类型或 ‘PyDateTime_DeltaType’ 的
     某个子类型则返回真值。 `ob' 不能为 ‘NULL’。 此函数总是会成功执行。

 -- C 函式: int PyDelta_CheckExact (PyObject *ob)

     如果 `ob' 为 ‘PyDateTime_DeltaType’ 类型则返回真值。 `ob' 不能为
     ‘NULL’。 此函数总是会成功执行。

 -- C 函式: int PyTZInfo_Check (PyObject *ob)

     如果 `ob' 的类型是 ‘PyDateTime_TZInfoType’ 或是
     ‘PyDateTime_TZInfoType’ 的子类型则返回真值。 `ob' 必须不为 ‘NULL’。
     此函数总是会成功执行。

 -- C 函式: int PyTZInfo_CheckExact (PyObject *ob)

     如果 `ob' 为 ‘PyDateTime_TZInfoType’ 类型则返回真值。 `ob' 不能为
     ‘NULL’。 此函数总是会成功执行。

用于创建对象的宏：

 -- C 函式: PyObject* PyDate_FromDate (int year, int month, int day)
     `Return value: New reference.' 返回指定年、月、日的 *note
     datetime.date: 19d. 对象。

 -- C 函式: PyObject* PyDateTime_FromDateAndTime (int year, int month,
          int day, int hour, int minute, int second, int usecond)
     `Return value: New reference.' 返回具有指定 year, month, day, hour,
     minute, second 和 microsecond 属性的 *note datetime.datetime: 19f.
     对象。

 -- C 函式: PyObject* PyDateTime_FromDateAndTimeAndFold (int year,
          int month, int day, int hour, int minute, int second,
          int usecond, int fold)
     `Return value: New reference.' 返回具有指定 year, month, day, hour,
     minute, second, microsecond 和 fold 属性的 *note datetime.datetime:
     19f. 对象。

     3.6 版新加入.

 -- C 函式: PyObject* PyTime_FromTime (int hour, int minute, int second,
          int usecond)
     `Return value: New reference.' 返回具有指定 hour, minute, second
     and microsecond 属性的 *note datetime.time: 5ec. 对象。

 -- C 函式: PyObject* PyTime_FromTimeAndFold (int hour, int minute,
          int second, int usecond, int fold)
     `Return value: New reference.' 返回具有指定 hour, minute, second,
     microsecond 和 fold 属性的 *note datetime.time: 5ec. 对象。

     3.6 版新加入.

 -- C 函式: PyObject* PyDelta_FromDSU (int days, int seconds,
          int useconds)
     `Return value: New reference.' 返回代表给定天、秒和微秒数的 *note
     datetime.timedelta: 2ca. 对象。 将执行正规化操作以使最终的微秒和秒
     数处在 *note datetime.timedelta: 2ca. 对象的文档指明的区间之内。

 -- C 函式: PyObject* PyTimeZone_FromOffset
          (PyDateTime_DeltaType* offset)
     `Return value: New reference.' 返回一个 *note datetime.timezone:
     ae0. 对象，该对象具有以 `offset' 参数表示 的未命名固定时差。

     3.7 版新加入.

 -- C 函式: PyObject* PyTimeZone_FromOffsetAndName
          (PyDateTime_DeltaType* offset, PyUnicode* name)
     `Return value: New reference.' 返回一个 *note datetime.timezone:
     ae0. 对象，该对象具有以 `offset' 参数表示的固定时差和时区名称
     `name'。

     3.7 版新加入.

一些用来从 date 对象中提取字段的宏。 参数必须是 ‘PyDateTime_Date’ 包括其
子类 (例如 ‘PyDateTime_DateTime’) 的实例。 参数必须不为 ‘NULL’，并且类型
不被会检查:

 -- C 函式: int PyDateTime_GET_YEAR (PyDateTime_Date *o)

     回傳年份，為正整數。

 -- C 函式: int PyDateTime_GET_MONTH (PyDateTime_Date *o)

     回傳月份，為正整數，從 1 到 12。

 -- C 函式: int PyDateTime_GET_DAY (PyDateTime_Date *o)

     回傳日期，為正整數，從 1 到 31。

一些用来从 datetime 对象中提取字段的宏。 参数必须是
‘PyDateTime_DateTime’ 包括其子类的实例。 参数必须不为 ‘NULL’，并且类型不
会被检查:

 -- C 函式: int PyDateTime_DATE_GET_HOUR (PyDateTime_DateTime *o)

     回傳小時，為正整數，從 0 到 23。

 -- C 函式: int PyDateTime_DATE_GET_MINUTE (PyDateTime_DateTime *o)

     回傳分鐘，為正整數，從 0 到 59。

 -- C 函式: int PyDateTime_DATE_GET_SECOND (PyDateTime_DateTime *o)

     回傳秒，為正整數，從0 到59。

 -- C 函式: int PyDateTime_DATE_GET_MICROSECOND (PyDateTime_DateTime *o)

     回傳微秒，為正整數，從 0 到 999999。

一些用来从 time 对象中提取字段的宏。 参数必须是 ‘PyDateTime_Time’ 包括其
子类的实例。 参数必须不为 ‘NULL’，并且类型不会被检查:

 -- C 函式: int PyDateTime_TIME_GET_HOUR (PyDateTime_Time *o)

     回傳小時，為正整數，從 0 到 23。

 -- C 函式: int PyDateTime_TIME_GET_MINUTE (PyDateTime_Time *o)

     回傳分鐘，為正整數，從 0 到 59。

 -- C 函式: int PyDateTime_TIME_GET_SECOND (PyDateTime_Time *o)

     回傳秒，為正整數，從0 到59。

 -- C 函式: int PyDateTime_TIME_GET_MICROSECOND (PyDateTime_Time *o)

     回傳微秒，為正整數，從 0 到 999999。

一些用来从 timedelta 对象中提取字段的宏。 参数必须是 ‘PyDateTime_Delta’
包括其子类的实例。 参数必须不为 ‘NULL’，并且类型不会被检查:

 -- C 函式: int PyDateTime_DELTA_GET_DAYS (PyDateTime_Delta *o)

     返回天数，从-999999999到999999999的整数。

     3.3 版新加入.

 -- C 函式: int PyDateTime_DELTA_GET_SECONDS (PyDateTime_Delta *o)

     返回秒数，从0到86399的整数。

     3.3 版新加入.

 -- C 函式: int PyDateTime_DELTA_GET_MICROSECONDS (PyDateTime_Delta *o)

     返回微秒数，从0到999999的整数。

     3.3 版新加入.

一些便于模块实现 DB API 的宏:

 -- C 函式: PyObject* PyDateTime_FromTimestamp (PyObject *args)
     `Return value: New reference.' 创建并返回一个给定元组参数的新 *note
     datetime.datetime: 19f. 对象，适合传给 *note
     datetime.datetime.fromtimestamp(): 11c0.。

 -- C 函式: PyObject* PyDate_FromTimestamp (PyObject *args)
     `Return value: New reference.' 创建并返回一个给定元组参数的新 *note
     datetime.date: 19d. 对象，适合传给 *note
     datetime.date.fromtimestamp(): 19e9.。


File: python.info,  Node: 类型注解对象,  Prev: DateTime 物件,  Up: 其他对象<2>

7.8.6.20 类型注解对象
.....................

Python 提供了多种内置类型用于类型注解，但只有 *note GenericAlias: fe5. 暴
露给了 C。

 -- C 函式: PyObject* Py_GenericAlias (PyObject *origin, PyObject *args)

     创建一个 *note GenericAlias: fe5. 对象。相当于调用 Python 类 *note
     types.GenericAlias: 27c. 。参数 `origin' 和 `args' 分别设置
     ‘GenericAlias’’s ‘__origin__’ 属性和 ‘__args__’ 属性。 `origin' 应
     该是 *note PyTypeObject*: 3f5. 类型， `args' 可以是 *note
     PyTupleObject*: 3e6a. 类型或者任意 ‘PyObject*’ 类型。如果传递的
     `args' 不是一个元组，则自动构建一个 1 元元组，并将 ‘__args__’ 设置
     为 ‘(args,)’ 。对参数进行了最小限度的检查，因此即使 `origin' 不是类
     型，函数也会成功。‘GenericAlias’ 的 ‘__parameters__’ 属性是通过
     ‘__args__’ 懒加载的。如果失败，则触发异常并返回 ‘NULL’ 。

     下面是一个如何创建一个扩展类型泛型的例子:

          ...
          static PyMethodDef my_obj_methods[] = {
              // Other methods.
              ...
              {"__class_getitem__", (PyCFunction)Py_GenericAlias, METH_O|METH_CLASS, "See PEP 585"}
              ...
          }

     也參考
     ......

     数据模型的方法 *note __class_getitem__(): 437. 。

     3.9 版新加入.

 -- C 變數: PyTypeObject Py_GenericAliasType

     由 *note Py_GenericAlias(): 4182. 所返回的对象的 C 类型。等价于
     Python 中的 *note types.GenericAlias: 27c. 。

     3.9 版新加入.


File: python.info,  Node: 初始化，终结和线程,  Next: Python初始化配置,  Prev: 具体的对象层,  Up: Python/C API 參考手冊

7.9 初始化，终结和线程
======================

请参阅 *note Python 初始化配置: 2b6. 。

* Menu:

* 在Python初始化之前::
* 全局配置变量::
* Initializing and finalizing the interpreter::
* Process-wide parameters::
* Thread State and the Global Interpreter Lock::
* Sub-interpreter support::
* 异步通知::
* 分析和跟踪::
* 高级调试器支持::
* Thread Local Storage Support::


File: python.info,  Node: 在Python初始化之前,  Next: 全局配置变量,  Up: 初始化，终结和线程

7.9.1 在Python初始化之前
------------------------

在一个植入了 Python 的应用程序中，*note Py_Initialize(): 20f. 函数必须在
任何其他 Python/C API 函数之前被调用；例外的只有个别函数和 *note
全局配置变量: 4188.。

在初始化Python之前，可以安全地调用以下函数：

   * 配置函数：

        * *note PyImport_AppendInittab(): f9c.

        * *note PyImport_ExtendInittab(): f9d.

        * ‘PyInitFrozenExtensions()’

        * *note PyMem_SetAllocator(): 4189.

        * *note PyMem_SetupDebugHooks(): 603.

        * *note PyObject_SetArenaAllocator(): 418a.

        * *note Py_SetPath(): 39c.

        * *note Py_SetProgramName(): 10f2.

        * *note Py_SetPythonHome(): 10f1.

        * *note Py_SetStandardStreamEncoding(): a0a.

        * *note PySys_AddWarnOption(): 5ad.

        * *note PySys_AddXOption(): 3e68.

        * *note PySys_ResetWarnOptions(): 3e61.

   * 信息函数：

        * *note Py_IsInitialized(): 3dd6.

        * *note PyMem_GetAllocator(): 418b.

        * *note PyObject_GetArenaAllocator(): 418c.

        * *note Py_GetBuildInfo(): e5f.

        * *note Py_GetCompiler(): 418d.

        * *note Py_GetCopyright(): 418e.

        * *note Py_GetPlatform(): 418f.

        * *note Py_GetVersion(): 4190.

   * 工具

        * *note Py_DecodeLocale(): 53e.

   * 内存分配器：

        * *note PyMem_RawMalloc(): a4e.

        * *note PyMem_RawRealloc(): a4f.

        * *note PyMem_RawCalloc(): 893.

        * *note PyMem_RawFree(): 3e5b.

     備註: 以下函数 `不应该' 在 *note Py_Initialize(): 20f.: *note
     Py_EncodeLocale(): 53f, *note Py_GetPath(): 3dd3, *note
     Py_GetPrefix(): 3dd4, *note Py_GetExecPrefix(): 3dd5, *note
     Py_GetProgramFullPath(): 39e, *note Py_GetPythonHome(): 4191, *note
     Py_GetProgramName(): 39f. 和 *note PyEval_InitThreads(): 20c. 前调
     用。


File: python.info,  Node: 全局配置变量,  Next: Initializing and finalizing the interpreter,  Prev: 在Python初始化之前,  Up: 初始化，终结和线程

7.9.2 全局配置变量
------------------

Python 有负责控制全局配置中不同特性和选项的变量。这些标志默认被 *note
命令行选项: 146e.。

当一个选项设置一个旗标时，该旗标的值将是设置选项的次数。 例如，‘-b’ 会将
*note Py_BytesWarningFlag: 5ae. 设为 1 而 ‘-bb’ 会将 *note
Py_BytesWarningFlag: 5ae. 设为 2.

 -- C 變數: int Py_BytesWarningFlag

     Issue a warning when comparing *note bytes: 172. or *note
     bytearray: 173. with *note str: 205. or *note bytes: 172. with
     *note int: 204.  Issue an error if greater or equal to ‘2’.

     由 *note -b: 519. 选项设置。

 -- C 變數: int Py_DebugFlag

     Turn on parser debugging output (for expert only, depending on
     compilation options).

     Set by the *note -d: 1476. option and the *note PYTHONDEBUG: 1477.
     environment variable.

 -- C 變數: int Py_DontWriteBytecodeFlag

     If set to non-zero, Python won’t try to write ‘.pyc’ files on the
     import of source modules.

     Set by the *note -B: dfe. option and the *note
     PYTHONDONTWRITEBYTECODE: dff. environment variable.

 -- C 變數: int Py_FrozenFlag

     Suppress error messages when calculating the module search path in
     *note Py_GetPath(): 3dd3.

     Private flag used by ‘_freeze_importlib’ and ‘frozenmain’ programs.

 -- C 變數: int Py_HashRandomizationFlag

     Set to ‘1’ if the *note PYTHONHASHSEED: aa4. environment variable
     is set to a non-empty string.

     If the flag is non-zero, read the *note PYTHONHASHSEED: aa4.
     environment variable to initialize the secret hash seed.

 -- C 變數: int Py_IgnoreEnvironmentFlag

     忽略所有 ‘PYTHON*’ 环境变量，例如可能已设置的 *note PYTHONPATH:
     a34. 和 *note PYTHONHOME: 5d0.。

     由 *note -E: 230. 和 *note -I: 231. 选项设置。

 -- C 變數: int Py_InspectFlag

     When a script is passed as first argument or the *note -c: 1340.
     option is used, enter interactive mode after executing the script
     or the command, even when *note sys.stdin: 41e. does not appear to
     be a terminal.

     Set by the *note -i: ee1. option and the *note PYTHONINSPECT: ee0.
     environment variable.

 -- C 變數: int Py_InteractiveFlag

     由 *note -i: ee1. 选项设置。

 -- C 變數: int Py_IsolatedFlag

     Run Python in isolated mode.  In isolated mode *note sys.path: 261.
     contains neither the script’s directory nor the user’s
     site-packages directory.

     由 *note -I: 231. 选项设置。

     3.4 版新加入.

 -- C 變數: int Py_LegacyWindowsFSEncodingFlag

     If the flag is non-zero, use the ‘mbcs’ encoding instead of the
     UTF-8 encoding for the filesystem encoding.

     Set to ‘1’ if the *note PYTHONLEGACYWINDOWSFSENCODING: 5f0.
     environment variable is set to a non-empty string.

     有关更多详细信息，请参阅 PEP 529(1)。

     *note 可用性: 1491.: Windows。

 -- C 變數: int Py_LegacyWindowsStdioFlag

     If the flag is non-zero, use *note io.FileIO: d6c. instead of
     ‘WindowsConsoleIO’ for *note sys: fd. standard streams.

     Set to ‘1’ if the *note PYTHONLEGACYWINDOWSSTDIO: 5f3. environment
     variable is set to a non-empty string.

     有关更多详细信息，请参阅 PEP 528(2)。

     *note 可用性: 1491.: Windows。

 -- C 變數: int Py_NoSiteFlag

     禁用 *note site: eb. 的导入及其所附带的基于站点对 *note sys.path:
     261. 的操作。 如果 *note site: eb. 会在稍后被显式地导入也会禁用这些
     操作 (如果你希望触发它们则应调用 *note site.main(): 147b.)。

     由 *note -S: bf7. 选项设置。

 -- C 變數: int Py_NoUserSiteDirectory

     不要将 *note 用户 site-packages 目录: 147a. 添加到 *note sys.path:
     261.。

     Set by the *note -s: ddb. and *note -I: 231. options, and the *note
     PYTHONNOUSERSITE: ddc. environment variable.

 -- C 變數: int Py_OptimizeFlag

     Set by the *note -O: 77e. option and the *note PYTHONOPTIMIZE:
     1478. environment variable.

 -- C 變數: int Py_QuietFlag

     即使在交互模式下也不显示版权和版本信息。

     由 *note -q: 1479. 选项设置。

     3.2 版新加入.

 -- C 變數: int Py_UnbufferedStdioFlag

     Force the stdout and stderr streams to be unbuffered.

     Set by the *note -u: 109d. option and the *note PYTHONUNBUFFERED:
     109e. environment variable.

 -- 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 ‘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 *note -v: e4d. option and the *note PYTHONVERBOSE: 147c.
     environment variable.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0529

   (2) https://www.python.org/dev/peps/pep-0528


File: python.info,  Node: Initializing and finalizing the interpreter,  Next: Process-wide parameters,  Prev: 全局配置变量,  Up: 初始化，终结和线程

7.9.3 Initializing and finalizing the interpreter
-------------------------------------------------

 -- C 函式: void Py_Initialize ()

     Initialize the Python interpreter.  In an application embedding
     Python, this should be called before using any other Python/C API
     functions; see *note Before Python Initialization: 53c. for the few
     exceptions.

     This initializes the table of loaded modules (‘sys.modules’), and
     creates the fundamental modules *note builtins: 12, *note __main__:
     1. and *note sys: fd.  It also initializes the module search path
     (‘sys.path’).  It does not set ‘sys.argv’; use *note
     PySys_SetArgvEx(): cc5. for that.  This is a no-op when called for
     a second time (without calling *note Py_FinalizeEx(): 6c0. first).
     There is no return value; it is a fatal error if the initialization
     fails.

          備註: On Windows, changes the console mode from ‘O_TEXT’ to
          ‘O_BINARY’, which will also affect non-Python uses of the
          console using the C Runtime.

 -- C 函式: void Py_InitializeEx (int initsigs)

     This function works like *note Py_Initialize(): 20f. if `initsigs'
     is ‘1’.  If `initsigs' is ‘0’, it skips initialization registration
     of signal handlers, which might be useful when Python is embedded.

 -- C 函式: int Py_IsInitialized ()

     Return true (nonzero) when the Python interpreter has been
     initialized, false (zero) if not.  After *note Py_FinalizeEx():
     6c0. is called, this returns false until *note Py_Initialize():
     20f. is called again.

 -- C 函式: int Py_FinalizeEx ()

     Undo all initializations made by *note Py_Initialize(): 20f. and
     subsequent use of Python/C API functions, and destroy all
     sub-interpreters (see *note Py_NewInterpreter(): 41a1. below) that
     were created and not yet destroyed since the last call to *note
     Py_Initialize(): 20f.  Ideally, this frees all memory allocated by
     the Python interpreter.  This is a no-op when called for a second
     time (without calling *note Py_Initialize(): 20f. again first).
     Normally the return value is ‘0’.  If there were errors during
     finalization (flushing buffered data), ‘-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.

     `Bugs and caveats:' The destruction of modules and objects in
     modules is done in random order; this may cause destructors (*note
     __del__(): a04. 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 *note Py_Initialize(): 20f. and
     *note Py_FinalizeEx(): 6c0. more than once.

     Raises an *note auditing event: fa1.
     ‘cpython._PySys_ClearAuditHooks’ with no arguments.

     3.6 版新加入.

 -- C 函式: void Py_Finalize ()

     This is a backwards-compatible version of *note Py_FinalizeEx():
     6c0. that disregards the return value.


File: python.info,  Node: Process-wide parameters,  Next: Thread State and the Global Interpreter Lock,  Prev: Initializing and finalizing the interpreter,  Up: 初始化，终结和线程

7.9.4 Process-wide parameters
-----------------------------

 -- C 函式: int Py_SetStandardStreamEncoding (const char *encoding,
          const char *errors)

     This function should be called before *note Py_Initialize(): 20f,
     if it is called at all.  It specifies which encoding and error
     handling to use with standard IO, with the same meanings as in
     *note str.encode(): 170.

     It overrides *note PYTHONIOENCODING: a14. values, and allows
     embedding code to control IO encoding when the environment variable
     does not work.

     `encoding' and/or `errors' may be ‘NULL’ to use *note
     PYTHONIOENCODING: a14. and/or default values (depending on other
     settings).

     Note that *note sys.stderr: 1ea. always uses the "backslashreplace"
     error handler, regardless of this (or any other) setting.

     If *note Py_FinalizeEx(): 6c0. is called, this function will need
     to be called again in order to affect subsequent calls to *note
     Py_Initialize(): 20f.

     Returns ‘0’ if successful, a nonzero value on error (e.g.  calling
     after the interpreter has already been initialized).

     3.4 版新加入.

 -- C 函式: void Py_SetProgramName (const wchar_t *name)

     This function should be called before *note Py_Initialize(): 20f.
     is called for the first time, if it is called at all.  It tells the
     interpreter the value of the ‘argv[0]’ argument to the ‘main()’
     function of the program (converted to wide characters).  This is
     used by *note Py_GetPath(): 3dd3. and some other functions below to
     find the Python run-time libraries relative to the interpreter
     executable.  The default value is ‘'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 *note Py_DecodeLocale(): 53e. to decode a bytes string to get a
     ‘wchar_*’ string.

 -- C 函式: wchar* Py_GetProgramName ()

     Return the program name set with *note Py_SetProgramName(): 10f2,
     or the default.  The returned string points into static storage;
     the caller should not modify its value.

 -- C 函式: wchar_t* Py_GetPrefix ()

     Return the `prefix' for installed platform-independent files.  This
     is derived through a number of complicated rules from the program
     name set with *note Py_SetProgramName(): 10f2. and some environment
     variables; for example, if the program name is
     ‘'/usr/local/bin/python'’, the prefix is ‘'/usr/local'’.  The
     returned string points into static storage; the caller should not
     modify its value.  This corresponds to the ‘prefix’ variable in the
     top-level ‘Makefile’ and the ‘--prefix’ argument to the ‘configure’
     script at build time.  The value is available to Python code as
     ‘sys.prefix’.  It is only useful on Unix.  See also the next
     function.

 -- C 函式: wchar_t* Py_GetExecPrefix ()

     Return the `exec-prefix' for installed platform-`dependent' files.
     This is derived through a number of complicated rules from the
     program name set with *note Py_SetProgramName(): 10f2. and some
     environment variables; for example, if the program name is
     ‘'/usr/local/bin/python'’, the exec-prefix is ‘'/usr/local'’.  The
     returned string points into static storage; the caller should not
     modify its value.  This corresponds to the ‘exec_prefix’ variable
     in the top-level ‘Makefile’ and the ‘--exec-prefix’ argument to the
     ‘configure’ script at build time.  The value is available to Python
     code as ‘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
     ‘/usr/local/plat’ subtree while platform independent may be
     installed in ‘/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 ‘mount’ or
     ‘automount’ programs to share ‘/usr/local’ between platforms while
     having ‘/usr/local/plat’ be a different filesystem for each
     platform.

 -- C 函式: wchar_t* Py_GetProgramFullPath ()

     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 *note Py_SetProgramName(): 10f2.
     above).  The returned string points into static storage; the caller
     should not modify its value.  The value is available to Python code
     as ‘sys.executable’.

 -- C 函式: wchar_t* Py_GetPath ()

     Return the default module search path; this is computed from the
     program name (set by *note Py_SetProgramName(): 10f2. 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 ‘':'’ on Unix and
     macOS, ‘';'’ on Windows.  The returned string points into static
     storage; the caller should not modify its value.  The list *note
     sys.path: 261. 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 函式: void Py_SetPath (const wchar_t *)

     Set the default module search path.  If this function is called
     before *note Py_Initialize(): 20f, then *note Py_GetPath(): 3dd3.
     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 ‘':'’ on Unix and macOS, ‘';'’ on
     Windows.

     This also causes *note sys.executable: 39d. to be set to the
     program full path (see *note Py_GetProgramFullPath(): 39e.) and for
     *note sys.prefix: 379f. and *note sys.exec_prefix: 37a0. to be
     empty.  It is up to the caller to modify these if required after
     calling *note Py_Initialize(): 20f.

     Use *note Py_DecodeLocale(): 53e. to decode a bytes string to get a
     ‘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 *note
     sys.executable: 39d, instead of the program name.

 -- C 函式: const char* Py_GetVersion ()

     Return the version of this Python interpreter.  This is a string
     that looks something like

          "3.0a5+ (py3k:63103M, May 12 2008, 00:53:55) \n[GCC 4.2.3]"

     The first word (up to the first space character) is the current
     Python version; the first three 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 *note sys.version: 6ca.

 -- C 函式: const char* Py_GetPlatform ()

     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 ‘'sunos5'’.  On macOS, it is ‘'darwin'’.  On Windows, it is
     ‘'win'’.  The returned string points into static storage; the
     caller should not modify its value.  The value is available to
     Python code as ‘sys.platform’.

 -- C 函式: const char* Py_GetCopyright ()

     Return the official copyright string for the current Python
     version, for example

     ‘'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'’

     The returned string points into static storage; the caller should
     not modify its value.  The value is available to Python code as
     ‘sys.copyright’.

 -- C 函式: const char* Py_GetCompiler ()

     Return an indication of the compiler used to build the current
     Python version, in square brackets, for example:

          "[GCC 2.7.2.2]"

     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 ‘sys.version’.

 -- C 函式: const char* Py_GetBuildInfo ()

     Return information about the sequence number and build date and
     time of the current Python interpreter instance, for example

          "#67, Aug  1 1997, 22:34:28"

     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 ‘sys.version’.

 -- C 函式: void PySys_SetArgvEx (int argc, wchar_t **argv,
          int updatepath)

     Set *note sys.argv: cc6. based on `argc' and `argv'.  These
     parameters are similar to those passed to the program’s ‘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 `argv' can be an empty string.  If this function
     fails to initialize *note sys.argv: cc6, a fatal condition is
     signalled using *note Py_FatalError(): 266.

     If `updatepath' is zero, this is all the function does.  If
     `updatepath' is non-zero, the function also modifies *note
     sys.path: 261. according to the following algorithm:

        - If the name of an existing script is passed in ‘argv[0]’, the
          absolute path of the directory where the script is located is
          prepended to *note sys.path: 261.

        - Otherwise (that is, if `argc' is ‘0’ or ‘argv[0]’ doesn’t
          point to an existing file name), an empty string is prepended
          to *note sys.path: 261, which is the same as prepending the
          current working directory (‘"."’).

     Use *note Py_DecodeLocale(): 53e. to decode a bytes string to get a
     ‘wchar_*’ string.

          備註: It is recommended that applications embedding the Python
          interpreter for purposes other than executing a single script
          pass ‘0’ as `updatepath', and update *note sys.path: 261.
          themselves if desired.  See CVE-2008-5983(1).

          On versions before 3.1.3, you can achieve the same effect by
          manually popping the first *note sys.path: 261. element after
          having called *note PySys_SetArgv(): db2, for example using:

               PyRun_SimpleString("import sys; sys.path.pop(0)\n");

     3.1.3 版新加入.

 -- C 函式: void PySys_SetArgv (int argc, wchar_t **argv)

     This function works like *note PySys_SetArgvEx(): cc5. with
     `updatepath' set to ‘1’ unless the ‘python’ interpreter was started
     with the *note -I: 231.

     Use *note Py_DecodeLocale(): 53e. to decode a bytes string to get a
     ‘wchar_*’ string.

     3.4 版更變: The `updatepath' value depends on *note -I: 231.

 -- C 函式: void Py_SetPythonHome (const wchar_t *home)

     Set the default "home" directory, that is, the location of the
     standard Python libraries.  See *note PYTHONHOME: 5d0. 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 *note Py_DecodeLocale(): 53e. to decode a bytes string to get a
     ‘wchar_*’ string.

 -- C 函式: w_char* Py_GetPythonHome ()

     Return the default "home", that is, the value set by a previous
     call to *note Py_SetPythonHome(): 10f1, or the value of the *note
     PYTHONHOME: 5d0. environment variable if it is set.

   ---------- Footnotes ----------

   (1) https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-5983


File: python.info,  Node: Thread State and the Global Interpreter Lock,  Next: Sub-interpreter support,  Prev: Process-wide parameters,  Up: 初始化，终结和线程

7.9.5 Thread State and the Global Interpreter Lock
--------------------------------------------------

The Python interpreter is not fully thread-safe.  In order to support
multi-threaded Python programs, there’s a global lock, called the *note
global interpreter lock: 5ff. or *note GIL: 20e, 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.

Therefore, the rule exists that only the thread that has acquired the
*note GIL: 20e. 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 *note
sys.setswitchinterval(): 218.).  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.

The Python interpreter keeps some thread-specific bookkeeping
information inside a data structure called *note PyThreadState: 41a5.
There’s also one global variable pointing to the current *note
PyThreadState: 41a5.: it can be retrieved using *note
PyThreadState_Get(): 41a6.

* Menu:

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


File: python.info,  Node: Releasing the GIL from extension code,  Next: 非Python创建的线程,  Up: Thread State and the Global Interpreter Lock

7.9.5.1 Releasing the GIL from extension code
.............................................

Most extension code manipulating the *note GIL: 20e. has the following
simple structure:

     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.

This is so common that a pair of macros exists to simplify it:

     Py_BEGIN_ALLOW_THREADS
     ... Do some blocking I/O operation ...
     Py_END_ALLOW_THREADS

The *note Py_BEGIN_ALLOW_THREADS: 3d43. macro opens a new block and
declares a hidden local variable; the *note Py_END_ALLOW_THREADS: 3d7.
macro closes the block.

The block above expands to the following code:

     PyThreadState *_save;

     _save = PyEval_SaveThread();
     ... Do some blocking I/O operation ...
     PyEval_RestoreThread(_save);

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.

     備註: 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 *note zlib: 14d.
     and *note hashlib: 8c. modules release the GIL when compressing or
     hashing data.


File: python.info,  Node: 非Python创建的线程,  Next: Cautions about fork,  Prev: Releasing the GIL from extension code,  Up: Thread State and the Global Interpreter Lock

7.9.5.2 非Python创建的线程
..........................

When threads are created using the dedicated Python APIs (such as the
*note threading: 10b. 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 *note PyGILState_Ensure(): 3d8. and *note PyGILState_Release():
41aa. functions do all of the above automatically.  The typical idiom
for calling into Python from a C thread is:

     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);

Note that the ‘PyGILState_*()’ functions assume there is only one global
interpreter (created automatically by *note Py_Initialize(): 20f.).
Python supports the creation of additional interpreters (using *note
Py_NewInterpreter(): 41a1.), but mixing multiple interpreters and the
‘PyGILState_*()’ API is unsupported.


File: python.info,  Node: Cautions about fork,  Next: 高阶 API,  Prev: 非Python创建的线程,  Up: Thread State and the Global Interpreter Lock

7.9.5.3 Cautions about fork()
.............................

Another important thing to note about threads is their behaviour in the
face of the C ‘fork()’ call.  On most systems with ‘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 *note
os.fork(): a42. by acquiring the locks it uses internally before the
fork, and releasing them afterwards.  In addition, it resets any *note
锁对象: 24b9. 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
‘pthread_atfork()’ would need to be used to accomplish the same thing.
Additionally, when extending or embedding Python, calling ‘fork()’
directly rather than through *note os.fork(): a42. (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.
*note PyOS_AfterFork_Child(): 3ef. 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 *note os.fork():
a42. does.  This means finalizing all other *note PyThreadState: 41a5.
objects belonging to the current interpreter and all other *note
PyInterpreterState: 3e4. objects.  Due to this and the special nature of
the *note "main" interpreter: 3e57, ‘fork()’ should only be called in
that interpreter’s "main" thread, where the CPython global runtime was
originally initialized.  The only exception is if ‘exec()’ will be
called immediately after.


File: python.info,  Node: 高阶 API,  Next: Low-level API,  Prev: Cautions about fork,  Up: Thread State and the Global Interpreter Lock

7.9.5.4 高阶 API
................

These are the most commonly used types and functions when writing C
extension code, or when embedding the Python interpreter:

 -- 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.

 -- C 類型: PyThreadState

     This data structure represents the state of a single thread.  The
     only public data member is ‘interp’ (*note PyInterpreterState *:
     3e4.), which points to this thread’s interpreter state.

 -- C 函式: void PyEval_InitThreads ()

     Deprecated function which does nothing.

     In Python 3.6 and older, this function created the GIL if it didn’t
     exist.

     3.9 版更變: The function now does nothing.

     3.7 版更變: This function is now called by *note Py_Initialize():
     20f, so you don’t have to call it yourself anymore.

     3.2 版更變: This function cannot be called before *note
     Py_Initialize(): 20f. anymore.

     Deprecated since version 3.9, will be removed in version 3.11.

 -- C 函式: int PyEval_ThreadsInitialized ()

     Returns a non-zero value if *note PyEval_InitThreads(): 20c. 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 *note GIL: 20e. is now initialized by *note
     Py_Initialize(): 20f.

     Deprecated since version 3.9, will be removed in version 3.11.

 -- C 函式: PyThreadState* PyEval_SaveThread ()

     Release the global interpreter lock (if it has been created) and
     reset the thread state to ‘NULL’, returning the previous thread
     state (which is not ‘NULL’).  If the lock has been created, the
     current thread must have acquired it.

 -- C 函式: void PyEval_RestoreThread (PyThreadState *tstate)

     Acquire the global interpreter lock (if it has been created) and
     set the thread state to `tstate', which must not be ‘NULL’.  If the
     lock has been created, the current thread must not have acquired
     it, otherwise deadlock ensues.

          備註: 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 ‘_Py_IsFinalizing()’ or
          *note sys.is_finalizing(): 851. to check if the interpreter is
          in process of being finalized before calling this function to
          avoid unwanted termination.

 -- C 函式: PyThreadState* PyThreadState_Get ()

     Return the current thread state.  The global interpreter lock must
     be held.  When the current thread state is ‘NULL’, this issues a
     fatal error (so that the caller needn’t check for ‘NULL’).

 -- C 函式: PyThreadState* PyThreadState_Swap (PyThreadState *tstate)

     Swap the current thread state with the thread state given by the
     argument `tstate', which may be ‘NULL’.  The global interpreter
     lock must be held and is not released.

The following functions use thread-local storage, and are not compatible
with sub-interpreters:

 -- 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 *note
     PyGILState_Release(): 41aa.  In general, other thread-related APIs
     may be used between *note PyGILState_Ensure(): 3d8. and *note
     PyGILState_Release(): 41aa. calls as long as the thread state is
     restored to its previous state before the Release().  For example,
     normal usage of the *note Py_BEGIN_ALLOW_THREADS: 3d43. and *note
     Py_END_ALLOW_THREADS: 3d7. macros is acceptable.

     The return value is an opaque "handle" to the thread state when
     *note PyGILState_Ensure(): 3d8. was called, and must be passed to
     *note PyGILState_Release(): 41aa. to ensure Python is left in the
     same state.  Even though recursive calls are allowed, these handles
     `cannot' be shared - each unique call to *note PyGILState_Ensure():
     3d8. must save the handle for its call to *note
     PyGILState_Release(): 41aa.

     When the function returns, the current thread will hold the GIL and
     be able to call arbitrary Python code.  Failure is a fatal error.

          備註: 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 ‘_Py_IsFinalizing()’ or
          *note sys.is_finalizing(): 851. to check if the interpreter is
          in process of being finalized before calling this function to
          avoid unwanted termination.

 -- 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 *note PyGILState_Ensure(): 3d8. call (but generally
     this state will be unknown to the caller, hence the use of the
     GILState API).

     Every call to *note PyGILState_Ensure(): 3d8. must be matched by a
     call to *note PyGILState_Release(): 41aa. on the same thread.

 -- C 函式: PyThreadState* PyGILState_GetThisThreadState ()

     Get the current thread state for this thread.  May return ‘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.

 -- C 函式: int PyGILState_Check ()

     Return ‘1’ if the current thread is holding the GIL and ‘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 ‘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 版新加入.

The following macros are normally used without a trailing semicolon;
look for example usage in the Python source distribution.

 -- C 巨集: Py_BEGIN_ALLOW_THREADS

     This macro expands to ‘{ PyThreadState *_save; _save =
     PyEval_SaveThread();’.  Note that it contains an opening brace; it
     must be matched with a following *note Py_END_ALLOW_THREADS: 3d7.
     macro.  See above for further discussion of this macro.

 -- C 巨集: Py_END_ALLOW_THREADS

     此宏扩展为 ‘PyEval_RestoreThread(_save); }’。 注意它包含一个右花括
     号；它必须与之前的 *note Py_BEGIN_ALLOW_THREADS: 3d43. 宏匹配。 请
     参阅上文以进一步讨论此宏。

 -- C 巨集: Py_BLOCK_THREADS

     This macro expands to ‘PyEval_RestoreThread(_save);’: it is
     equivalent to *note Py_END_ALLOW_THREADS: 3d7. without the closing
     brace.

 -- C 巨集: Py_UNBLOCK_THREADS

     This macro expands to ‘_save = PyEval_SaveThread();’: it is
     equivalent to *note Py_BEGIN_ALLOW_THREADS: 3d43. without the
     opening brace and variable declaration.


File: python.info,  Node: Low-level API,  Prev: 高阶 API,  Up: Thread State and the Global Interpreter Lock

7.9.5.5 Low-level API
.....................

All of the following functions must be called after *note
Py_Initialize(): 20f.

3.7 版更變: *note Py_Initialize(): 20f. now initializes the *note GIL:
20e.

 -- 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 *note auditing event: fa1.
     ‘cpython.PyInterpreterState_New’ with no arguments.

 -- C 函式: void PyInterpreterState_Clear (PyInterpreterState *interp)

     Reset all information in an interpreter state object.  The global
     interpreter lock must be held.

     Raises an *note auditing event: fa1.
     ‘cpython.PyInterpreterState_Clear’ with no arguments.

 -- C 函式: void PyInterpreterState_Delete (PyInterpreterState *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 *note PyInterpreterState_Clear(): 366c.

 -- C 函式: PyThreadState* PyThreadState_New
          (PyInterpreterState *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.

 -- C 函式: void PyThreadState_Clear (PyThreadState *tstate)

     Reset all information in a thread state object.  The global
     interpreter lock must be held.

     3.9 版更變: This function now calls the ‘PyThreadState.on_delete’
     callback.  Previously, that happened in *note
     PyThreadState_Delete(): 1097.

 -- C 函式: void PyThreadState_Delete (PyThreadState *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 *note PyThreadState_Clear(): 104c.

 -- C 函式: void PyThreadState_DeleteCurrent (void)

     Destroy the current thread state and release the global interpreter
     lock.  Like *note PyThreadState_Delete(): 1097, the global
     interpreter lock need not be held.  The thread state must have been
     reset with a previous call to *note PyThreadState_Clear(): 104c.

 -- C 函式: PyFrameObject* PyThreadState_GetFrame
          (PyThreadState *tstate)

     Get the current frame of the Python thread state `tstate'.

     Return a strong reference.  Return ‘NULL’ if no frame is currently
     executing.

     See also *note PyEval_GetFrame(): 3ea4.

     `tstate' must not be ‘NULL’.

     3.9 版新加入.

 -- C 函式: uint64_t PyThreadState_GetID (PyThreadState *tstate)

     Get the unique thread state identifier of the Python thread state
     `tstate'.

     `tstate' must not be ‘NULL’.

     3.9 版新加入.

 -- C 函式: PyInterpreterState* PyThreadState_GetInterpreter
          (PyThreadState *tstate)

     Get the interpreter of the Python thread state `tstate'.

     `tstate' must not be ‘NULL’.

     3.9 版新加入.

 -- C 函式: PyInterpreterState* PyInterpreterState_Get (void)

     Get the current interpreter.

     Issue a fatal error if there no current Python thread state or no
     current interpreter.  It cannot return NULL.

     呼叫者必须持有GIL。

     3.9 版新加入.

 -- C 函式: int64_t PyInterpreterState_GetID
          (PyInterpreterState *interp)

     Return the interpreter’s unique ID. If there was any error in doing
     so then ‘-1’ is returned and an error is set.

     呼叫者必须持有GIL。

     3.7 版新加入.

 -- C 函式: PyObject* PyInterpreterState_GetDict
          (PyInterpreterState *interp)

     Return a dictionary in which interpreter-specific data may be
     stored.  If this function returns ‘NULL’ then no exception has been
     raised and the caller should assume no interpreter-specific dict is
     available.

     This is not a replacement for *note PyModule_GetState(): 25e, which
     extensions should use to store interpreter-specific state
     information.

     3.8 版新加入.

 -- C 類型: PyObject* (*_PyFrameEvalFunction) (PyThreadState *tstate,
          PyFrameObject *frame, int throwflag)

     Type of a frame evaluation function.

     The `throwflag' parameter is used by the ‘throw()’ method of
     generators: if non-zero, handle the current exception.

     3.9 版更變: The function now takes a `tstate' parameter.

 -- C 函式: _PyFrameEvalFunction _PyInterpreterState_GetEvalFrameFunc
          (PyInterpreterState *interp)

     Get the frame evaluation function.

     See the PEP 523(1) "Adding a frame evaluation API to CPython".

     3.9 版新加入.

 -- C 函式: void _PyInterpreterState_SetEvalFrameFunc
          (PyInterpreterState *interp, _PyFrameEvalFunction eval_frame)

     Set the frame evaluation function.

     See the PEP 523(2) "Adding a frame evaluation API to CPython".

     3.9 版新加入.

 -- C 函式: PyObject* PyThreadState_GetDict ()
     `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 ‘NULL’, no
     exception has been raised and the caller should assume no current
     thread state is available.

 -- C 函式: int PyThreadState_SetAsyncExc (unsigned long id,
          PyObject *exc)

     Asynchronously raise an exception in a thread.  The `id' argument
     is the thread id of the target thread; `exc' is the exception
     object to be raised.  This function does not steal any references
     to `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 `exc' is ‘NULL’, the
     pending exception (if any) for the thread is cleared.  This raises
     no exceptions.

     3.7 版更變: The type of the `id' parameter changed from ‘long’ to
     ‘unsigned long’.

 -- C 函式: void PyEval_AcquireThread (PyThreadState *tstate)

     Acquire the global interpreter lock and set the current thread
     state to `tstate', which must not be ‘NULL’.  The lock must have
     been created earlier.  If this thread already has the lock,
     deadlock ensues.

          備註: 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 ‘_Py_IsFinalizing()’ or
          *note sys.is_finalizing(): 851. to check if the interpreter is
          in process of being finalized before calling this function to
          avoid unwanted termination.

     3.8 版更變: Updated to be consistent with *note
     PyEval_RestoreThread(): 3d6, *note Py_END_ALLOW_THREADS(): 3d7, and
     *note PyGILState_Ensure(): 3d8, and terminate the current thread if
     called while the interpreter is finalizing.

     *note PyEval_RestoreThread(): 3d6. is a higher-level function which
     is always available (even when threads have not been initialized).

 -- C 函式: void PyEval_ReleaseThread (PyThreadState *tstate)

     Reset the current thread state to ‘NULL’ and release the global
     interpreter lock.  The lock must have been created earlier and must
     be held by the current thread.  The `tstate' argument, which must
     not be ‘NULL’, is only used to check that it represents the current
     thread state — if it isn’t, a fatal error is reported.

     *note PyEval_SaveThread(): cdc. is a higher-level function which is
     always available (even when threads have not been initialized).

 -- 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 *note PyEval_RestoreThread(): 3d6. or *note
     PyEval_AcquireThread(): 3d5. instead.

          備註: 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 ‘_Py_IsFinalizing()’ or
          *note sys.is_finalizing(): 851. to check if the interpreter is
          in process of being finalized before calling this function to
          avoid unwanted termination.

     3.8 版更變: Updated to be consistent with *note
     PyEval_RestoreThread(): 3d6, *note Py_END_ALLOW_THREADS(): 3d7, and
     *note PyGILState_Ensure(): 3d8, and terminate the current thread if
     called while the interpreter is finalizing.

 -- 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 *note PyEval_SaveThread(): cdc. or *note
     PyEval_ReleaseThread(): 41b7. instead.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0523

   (2) https://www.python.org/dev/peps/pep-0523


File: python.info,  Node: Sub-interpreter support,  Next: 异步通知,  Prev: Thread State and the Global Interpreter Lock,  Up: 初始化，终结和线程

7.9.6 Sub-interpreter support
-----------------------------

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 *note
PyInterpreterState_Main(): 41b9. function returns a pointer to its
state.

You can switch between sub-interpreters using the *note
PyThreadState_Swap(): 41ad. function.  You can create and destroy them
using the following functions:

 -- C 函式: PyThreadState* Py_NewInterpreter ()

     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 *note builtins: 12,
     *note __main__: 1. and *note sys: fd.  The table of loaded modules
     (‘sys.modules’) and the module search path (‘sys.path’) are also
     separate.  The new environment has no ‘sys.argv’ variable.  It has
     new standard I/O stream file objects ‘sys.stdin’, ‘sys.stdout’ and
     ‘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, ‘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.)

     Extension modules are shared between (sub-)interpreters as follows:

        * For modules using multi-phase initialization, e.g.  *note
          PyModule_FromDefAndSpec(): 899, a separate module object is
          created and initialized for each interpreter.  Only C-level
          static and global variables are shared between these module
          objects.

        * For modules using single-phase initialization, e.g.  *note
          PyModule_Create(): 3d26, 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 ‘init’ function is not called.  Objects
          in the module’s dictionary thus end up shared across
          (sub-)interpreters, which might cause unwanted behavior (see
          *note Bugs and caveats: 41ba. below).

          Note that this is different from what happens when an
          extension is imported after the interpreter has been
          completely re-initialized by calling *note Py_FinalizeEx():
          6c0. and *note Py_Initialize(): 20f.; in that case, the
          extension’s ‘initmodule’ function `is' called again.  As with
          multi-phase initialization, this means that only C-level
          static and global variables are shared between these modules.

 -- C 函式: void Py_EndInterpreter (PyThreadState *tstate)

     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 ‘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.)  *note Py_FinalizeEx(): 6c0. will destroy all
     sub-interpreters that haven’t been explicitly destroyed at that
     point.

* Menu:

* 错误和警告::


File: python.info,  Node: 错误和警告,  Up: Sub-interpreter support

7.9.6.1 错误和警告
..................

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 *note os.close(): 4d8. 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 ‘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 *note PyGILState_Ensure():
3d8. and *note PyGILState_Release(): 41aa. calls.  Furthermore,
extensions (such as *note ctypes: 2a.) using these APIs to allow calling
of Python code from non-Python created threads will probably be broken
when using sub-interpreters.


File: python.info,  Node: 异步通知,  Next: 分析和跟踪,  Prev: Sub-interpreter support,  Up: 初始化，终结和线程

7.9.7 异步通知
--------------

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.

 -- C 函式: int Py_AddPendingCall (int (*func)(void *), void *arg)

     Schedule a function to be called from the main interpreter thread.
     On success, ‘0’ is returned and `func' is queued for being called
     in the main thread.  On failure, ‘-1’ is returned without setting
     any exception.

     When successfully queued, `func' will be `eventually' called from
     the main interpreter thread with the argument `arg'.  It will be
     called asynchronously with respect to normally running Python code,
     but with both these conditions met:

        * on a *note bytecode: 709. boundary;

        * with the main thread holding the *note global interpreter
          lock: 5ff. (`func' can therefore use the full C API).

     `func' must return ‘0’ on success, or ‘-1’ on failure with an
     exception set.  `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 `func' can be scheduled to be called
     from the wrong interpreter.

          警告: This is a low-level function, only useful for very
          special cases.  There is no guarantee that `func' will be
          called as quick as possible.  If the main thread is busy
          executing a system call, `func' won’t be called before the
          system call returns.  This function is generally `not'
          suitable for calling Python code from arbitrary C threads.
          Instead, use the *note PyGILState API: 41a8.

     3.9 版更變: If this function is called in a subinterpreter, the
     function `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 版新加入.


File: python.info,  Node: 分析和跟踪,  Next: 高级调试器支持,  Prev: 异步通知,  Up: 初始化，终结和线程

7.9.8 分析和跟踪
----------------

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.

 -- C 類型: int (*Py_tracefunc) (PyObject *obj, PyFrameObject *frame,
          int what, PyObject *arg)

     The type of the trace function registered using *note
     PyEval_SetProfile(): efd. and *note PyEval_SetTrace(): efe.  The
     first parameter is the object passed to the registration function
     as `obj', `frame' is the frame object to which the event pertains,
     `what' is one of the constants ‘PyTrace_CALL’, ‘PyTrace_EXCEPTION’,
     ‘PyTrace_LINE’, ‘PyTrace_RETURN’, ‘PyTrace_C_CALL’,
     ‘PyTrace_C_EXCEPTION’, ‘PyTrace_C_RETURN’, or ‘PyTrace_OPCODE’, and
     `arg' depends on the value of `what':

     `what' 的值                        `arg' 的含义
                                        
     --------------------------------------------------------------------------------
                                        
     ‘PyTrace_CALL’                     总是 *note Py_None: 3d23.
                                        
                                        
     ‘PyTrace_EXCEPTION’                *note sys.exc_info(): d27. 返回的异常信息
                                        。
                                        
                                        
     ‘PyTrace_LINE’                     总是 *note Py_None: 3d23.
                                        
                                        
     ‘PyTrace_RETURN’                   Value being returned to the caller, or
                                        ‘NULL’ if caused by an exception.
                                        
                                        
     ‘PyTrace_C_CALL’                   正在调用函数对象。
                                        
                                        
     ‘PyTrace_C_EXCEPTION’              正在调用函数对象。
                                        
                                        
     ‘PyTrace_C_RETURN’                 正在调用函数对象。
                                        
                                        
     ‘PyTrace_OPCODE’                   总是 *note Py_None: 3d23.
                                        

 -- C 變數: int PyTrace_CALL

     The value of the `what' parameter to a *note Py_tracefunc: 41be.
     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.

 -- C 變數: int PyTrace_EXCEPTION

     The value of the `what' parameter to a *note Py_tracefunc: 41be.
     function when an exception has been raised.  The callback function
     is called with this value for `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.

 -- C 變數: int PyTrace_LINE

     The value passed as the `what' parameter to a *note Py_tracefunc:
     41be. function (but not a profiling function) when a line-number
     event is being reported.  It may be disabled for a frame by setting
     ‘f_trace_lines’ to `0' on that frame.

 -- C 變數: int PyTrace_RETURN

     The value for the `what' parameter to *note Py_tracefunc: 41be.
     functions when a call is about to return.

 -- C 變數: int PyTrace_C_CALL

     The value for the `what' parameter to *note Py_tracefunc: 41be.
     functions when a C function is about to be called.

 -- C 變數: int PyTrace_C_EXCEPTION

     The value for the `what' parameter to *note Py_tracefunc: 41be.
     functions when a C function has raised an exception.

 -- C 變數: int PyTrace_C_RETURN

     The value for the `what' parameter to *note Py_tracefunc: 41be.
     functions when a C function has returned.

 -- C 變數: int PyTrace_OPCODE

     The value for the `what' parameter to *note Py_tracefunc: 41be.
     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 ‘f_trace_opcodes’ to `1' on the
     frame.

 -- C 函式: void PyEval_SetProfile (Py_tracefunc func, PyObject *obj)

     Set the profiler function to `func'.  The `obj' parameter is passed
     to the function as its first parameter, and may be any Python
     object, or ‘NULL’.  If the profile function needs to maintain
     state, using a different value for `obj' for each thread provides a
     convenient and thread-safe place to store it.  The profile function
     is called for all monitored events except ‘PyTrace_LINE’
     ‘PyTrace_OPCODE’ and ‘PyTrace_EXCEPTION’.

     The caller must hold the *note GIL: 20e.

 -- C 函式: void PyEval_SetTrace (Py_tracefunc func, PyObject *obj)

     Set the tracing function to `func'.  This is similar to *note
     PyEval_SetProfile(): efd, 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 *note PyEval_SetTrace(): efe. will not
     receive ‘PyTrace_C_CALL’, ‘PyTrace_C_EXCEPTION’ or
     ‘PyTrace_C_RETURN’ as a value for the `what' parameter.

     The caller must hold the *note GIL: 20e.


File: python.info,  Node: 高级调试器支持,  Next: Thread Local Storage Support,  Prev: 分析和跟踪,  Up: 初始化，终结和线程

7.9.9 高级调试器支持
--------------------

These functions are only intended to be used by advanced debugging
tools.

 -- C 函式: PyInterpreterState* PyInterpreterState_Head ()

     Return the interpreter state object at the head of the list of all
     such objects.

 -- C 函式: PyInterpreterState* PyInterpreterState_Main ()

     Return the main interpreter state object.

 -- C 函式: PyInterpreterState* PyInterpreterState_Next
          (PyInterpreterState *interp)

     Return the next interpreter state object after `interp' from the
     list of all such objects.

 -- C 函式: PyThreadState * PyInterpreterState_ThreadHead
          (PyInterpreterState *interp)

     Return the pointer to the first *note PyThreadState: 41a5. object
     in the list of threads associated with the interpreter `interp'.

 -- C 函式: PyThreadState* PyThreadState_Next (PyThreadState *tstate)

     Return the next thread state object after `tstate' from the list of
     all such objects belonging to the same *note PyInterpreterState:
     3e4. object.


File: python.info,  Node: Thread Local Storage Support,  Prev: 高级调试器支持,  Up: 初始化，终结和线程

7.9.10 Thread Local Storage Support
-----------------------------------

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 (*note
threading.local: 244e.).  The CPython C level APIs are similar to those
offered by pthreads and Windows: use a thread key and functions to
associate a ‘void*’ value per thread.

The GIL does `not' need to be held when calling these functions; they
supply their own locking.

Note that ‘Python.h’ does not include the declaration of the TLS APIs,
you need to include ‘pythread.h’ to use thread-local storage.

     備註: None of these API functions handle memory management on
     behalf of the ‘void*’ values.  You need to allocate and deallocate
     them yourself.  If the ‘void*’ values happen to be *note PyObject*:
     5b4, these functions don’t do refcount operations on them either.

* Menu:

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


File: python.info,  Node: Thread Specific Storage TSS API,  Next: Thread Local Storage TLS API,  Up: Thread Local Storage Support

7.9.10.1 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 *note
Py_tss_t: 428. instead of ‘int’ to represent thread keys.

3.7 版新加入.

也參考
......

"A New C-API for Thread-Local Storage in CPython" ( PEP 539(1))

 -- 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 *note Py_LIMITED_API: 3dda. is not defined, static allocation
     of this type by *note Py_tss_NEEDS_INIT: 41cc. is allowed.

 -- C 巨集: Py_tss_NEEDS_INIT

     This macro expands to the initializer for *note Py_tss_t: 428.
     variables.  Note that this macro won’t be defined with *note
     Py_LIMITED_API: 3dda.

* Menu:

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

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0539


File: python.info,  Node: Dynamic Allocation,  Next: 方法<4>,  Up: Thread Specific Storage TSS API

7.9.10.2 Dynamic Allocation
...........................

Dynamic allocation of the *note Py_tss_t: 428, required in extension
modules built with *note Py_LIMITED_API: 3dda, where static allocation
of this type is not possible due to its implementation being opaque at
build time.

 -- C 函式: Py_tss_t* PyThread_tss_alloc ()

     Return a value which is the same state as a value initialized with
     *note Py_tss_NEEDS_INIT: 41cc, or ‘NULL’ in the case of dynamic
     allocation failure.

 -- C 函式: void PyThread_tss_free (Py_tss_t *key)

     Free the given `key' allocated by *note PyThread_tss_alloc(): 41ce,
     after first calling *note PyThread_tss_delete(): 41d0. to ensure
     any associated thread locals have been unassigned.  This is a no-op
     if the `key' argument is ‘NULL’.

          備註: A freed key becomes a dangling pointer, you should reset
          the key to ‘NULL’.


File: python.info,  Node: 方法<4>,  Prev: Dynamic Allocation,  Up: Thread Specific Storage TSS API

7.9.10.3 方法
.............

The parameter `key' of these functions must not be ‘NULL’.  Moreover,
the behaviors of *note PyThread_tss_set(): 41d2. and *note
PyThread_tss_get(): 41d3. are undefined if the given *note Py_tss_t:
428. has not been initialized by *note PyThread_tss_create(): 41d4.

 -- C 函式: int PyThread_tss_is_created (Py_tss_t *key)

     Return a non-zero value if the given *note Py_tss_t: 428. has been
     initialized by *note PyThread_tss_create(): 41d4.

 -- C 函式: int PyThread_tss_create (Py_tss_t *key)

     Return a zero value on successful initialization of a TSS key.  The
     behavior is undefined if the value pointed to by the `key' argument
     is not initialized by *note Py_tss_NEEDS_INIT: 41cc.  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.

 -- C 函式: void PyThread_tss_delete (Py_tss_t *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
     *note PyThread_tss_create(): 41d4.  This function can be called
     repeatedly on the same key – calling it on an already destroyed key
     is a no-op.

 -- C 函式: int PyThread_tss_set (Py_tss_t *key, void *value)

     Return a zero value to indicate successfully associating a ‘void*’
     value with a TSS key in the current thread.  Each thread has a
     distinct mapping of the key to a ‘void*’ value.

 -- C 函式: void* PyThread_tss_get (Py_tss_t *key)

     Return the ‘void*’ value associated with a TSS key in the current
     thread.  This returns ‘NULL’ if no value is associated with the key
     in the current thread.


File: python.info,  Node: Thread Local Storage TLS API,  Prev: Thread Specific Storage TSS API,  Up: Thread Local Storage Support

7.9.10.4 Thread Local Storage (TLS) API
.......................................

3.7 版後已棄用: This API is superseded by *note Thread Specific Storage
(TSS) API: 427.

     備註: 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
     ‘int’.  On such platforms, *note PyThread_create_key(): 41d7. will
     return immediately with a failure status, and the other TLS
     functions will all be no-ops on such platforms.

由于上面提到的兼容性问题，不应在新代码中使用此版本的API。

 -- C 函式: int PyThread_create_key ()

 -- C 函式: void PyThread_delete_key (int key)

 -- C 函式: int PyThread_set_key_value (int key, void *value)

 -- C 函式: void* PyThread_get_key_value (int key)

 -- C 函式: void PyThread_delete_key_value (int key)

 -- C 函式: void PyThread_ReInitTLS ()


File: python.info,  Node: Python初始化配置,  Next: 記憶體管理,  Prev: 初始化，终结和线程,  Up: Python/C API 參考手冊

7.10 Python初始化配置
=====================

3.8 版新加入.

结构

   * *note PyConfig: 226.

   * *note PyPreConfig: 299.

   * *note PyStatus: 29a.

   * *note PyWideStringList: 29b.

函数

   * *note PyConfig_Clear(): 29c.

   * *note PyConfig_InitIsolatedConfig(): 29d.

   * *note PyConfig_InitPythonConfig(): 29e.

   * *note PyConfig_Read(): 29f.

   * *note PyConfig_SetArgv(): 2a0.

   * *note PyConfig_SetBytesArgv(): 2a1.

   * *note PyConfig_SetBytesString(): 2a2.

   * *note PyConfig_SetString(): 2a3.

   * *note PyConfig_SetWideStringList(): 41de.

   * *note PyPreConfig_InitIsolatedConfig(): 2a4.

   * *note PyPreConfig_InitPythonConfig(): 2a5.

   * *note PyStatus_Error(): 2a6.

   * *note PyStatus_Exception(): 2a7.

   * *note PyStatus_Exit(): 2a8.

   * *note PyStatus_IsError(): 2a9.

   * *note PyStatus_IsExit(): 2aa.

   * *note PyStatus_NoMemory(): 2ab.

   * *note PyStatus_Ok(): 2ac.

   * *note PyWideStringList_Append(): 2ad.

   * *note PyWideStringList_Insert(): 2ae.

   * *note Py_ExitStatusException(): 2b0.

   * *note Py_InitializeFromConfig(): 2b1.

   * *note Py_PreInitialize(): 2b2.

   * *note Py_PreInitializeFromArgs(): 2b3.

   * *note Py_PreInitializeFromBytesArgs(): 2b4.

   * *note Py_RunMain(): 2b5.

   * *note Py_GetArgcArgv(): 1037.

The preconfiguration (‘PyPreConfig’ type) is stored in
‘_PyRuntime.preconfig’ and the configuration (‘PyConfig’ type) is stored
in ‘PyInterpreterState.config’.

See also *note Initialization, Finalization, and Threads: 4185.

也參考
......

PEP 587(1) "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::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0587


File: python.info,  Node: PyWideStringList,  Next: PyStatus,  Up: Python初始化配置

7.10.1 PyWideStringList
-----------------------

 -- C 類型: PyWideStringList

     List of ‘wchar_t*’ strings.

     If `length' is non-zero, `items' must be non-‘NULL’ and all strings
     must be non-‘NULL’.

     方法

      -- C 函式: PyStatus PyWideStringList_Append
               (PyWideStringList *list, const wchar_t *item)

          Append `item' to `list'.

          Python must be preinitialized to call this function.

      -- C 函式: PyStatus PyWideStringList_Insert
               (PyWideStringList *list, Py_ssize_t index, const
               wchar_t *item)

          Insert `item' into `list' at `index'.

          If `index' is greater than or equal to `list' length, append
          `item' to `list'.

          `index' must be greater than or equal to 0.

          Python must be preinitialized to call this function.

     Structure fields:

      -- C 成員函數: Py_ssize_t length

          List 长度。

      -- C 成員函數: wchar_t** items

          列表项目。


File: python.info,  Node: PyStatus,  Next: PyPreConfig,  Prev: PyWideStringList,  Up: Python初始化配置

7.10.2 PyStatus
---------------

 -- 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:

      -- C 成員函數: int exitcode

          Exit code.  Argument passed to ‘exit()’.

      -- C 成員函數: const char *err_msg

          错误信息

      -- C 成員函數: const char *func

          Name of the function which created an error, can be ‘NULL’.

     Functions to create a status:

      -- C 函式: PyStatus PyStatus_Ok (void)

          完成。

      -- C 函式: PyStatus PyStatus_Error (const char *err_msg)

          Initialization error with a message.

      -- C 函式: PyStatus PyStatus_NoMemory (void)

          Memory allocation failure (out of memory).

      -- C 函式: PyStatus PyStatus_Exit (int exitcode)

          以指定的退出代码退出 Python。

     Functions to handle a status:

      -- C 函式: int PyStatus_Exception (PyStatus status)

          Is the status an error or an exit?  If true, the exception
          must be handled; by calling *note Py_ExitStatusException():
          2b0. for example.

      -- C 函式: int PyStatus_IsError (PyStatus status)

          结果错误吗？

      -- C 函式: int PyStatus_IsExit (PyStatus status)

          结果是否退出？

      -- C 函式: void Py_ExitStatusException (PyStatus status)

          Call ‘exit(exitcode)’ if `status' is an exit.  Print the error
          message and exit with a non-zero exit code if `status' is an
          error.  Must only be called if ‘PyStatus_Exception(status)’ is
          non-zero.

     備註: Internally, Python uses macros which set ‘PyStatus.func’,
     whereas functions to create a status set ‘func’ to ‘NULL’.

示例:

     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;
     }


File: python.info,  Node: PyPreConfig,  Next: Preinitialization with PyPreConfig,  Prev: PyStatus,  Up: Python初始化配置

7.10.3 PyPreConfig
------------------

 -- C 類型: PyPreConfig

     Structure used to preinitialize Python:

        * Set the Python memory allocator

        * Configure the LC_CTYPE locale

        * 设置为 UTF-8 模式

     Function to initialize a preconfiguration:

      -- C 函式: void PyPreConfig_InitPythonConfig
               (PyPreConfig *preconfig)

          Initialize the preconfiguration with *note Python
          Configuration: 41e7.

      -- C 函式: void PyPreConfig_InitIsolatedConfig
               (PyPreConfig *preconfig)

          Initialize the preconfiguration with *note Isolated
          Configuration: 41e8.

     Structure fields:

      -- C 成員函數: int allocator

          Name of the memory allocator:

             * ‘PYMEM_ALLOCATOR_NOT_SET’ (‘0’): don’t change memory
               allocators (use defaults)

             * ‘PYMEM_ALLOCATOR_DEFAULT’ (‘1’): default memory
               allocators

             * ‘PYMEM_ALLOCATOR_DEBUG’ (‘2’): default memory allocators
               with debug hooks

             * ‘PYMEM_ALLOCATOR_MALLOC’ (‘3’): force usage of ‘malloc()’

             * ‘PYMEM_ALLOCATOR_MALLOC_DEBUG’ (‘4’): force usage of
               ‘malloc()’ with debug hooks

             * ‘PYMEM_ALLOCATOR_PYMALLOC’ (‘5’): *note Python pymalloc
               memory allocator: 6b8.

             * ‘PYMEM_ALLOCATOR_PYMALLOC_DEBUG’ (‘6’): *note Python
               pymalloc memory allocator: 6b8. with debug hooks

          ‘PYMEM_ALLOCATOR_PYMALLOC’ and
          ‘PYMEM_ALLOCATOR_PYMALLOC_DEBUG’ are not supported if Python
          is configured using ‘--without-pymalloc’

          See *note Memory Management: 41ea.

      -- C 成員函數: int configure_locale

          Set the LC_CTYPE locale to the user preferred locale?  If
          equals to 0, set ‘coerce_c_locale’ and ‘coerce_c_locale_warn’
          to 0.

      -- 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.

      -- C 成員函數: int coerce_c_locale_warn

          If non-zero, emit a warning if the C locale is coerced.

      -- C 成員函數: int dev_mode

          参见 *note PyConfig.dev_mode: 41ef.

      -- C 成員函數: int isolated

          参见 *note PyConfig.isolated: 41f1.

      -- C 成員函數: int legacy_windows_fs_encoding (Windows only)

          If non-zero, disable UTF-8 Mode, set the Python filesystem
          encoding to ‘mbcs’, set the filesystem error handler to
          ‘replace’.

          Only available on Windows.  ‘#ifdef MS_WINDOWS’ macro can be
          used for Windows specific code.

      -- C 成員函數: int parse_argv

          If non-zero, *note Py_PreInitializeFromArgs(): 2b3. and *note
          Py_PreInitializeFromBytesArgs(): 2b4. parse their ‘argv’
          argument the same way the regular Python parses command line
          arguments: see *note Command Line Arguments: a10.

      -- C 成員函數: int use_environment

          参见 *note PyConfig.use_environment: 260.

      -- C 成員函數: int utf8_mode

          If non-zero, enable the UTF-8 mode.


File: python.info,  Node: Preinitialization with PyPreConfig,  Next: PyConfig,  Prev: PyPreConfig,  Up: Python初始化配置

7.10.4 Preinitialization with PyPreConfig
-----------------------------------------

Functions to preinitialize Python:

 -- C 函式: PyStatus Py_PreInitialize (const PyPreConfig *preconfig)

     Preinitialize Python from `preconfig' preconfiguration.

 -- C 函式: PyStatus Py_PreInitializeFromBytesArgs (const
          PyPreConfig *preconfig, int argc, char * const *argv)

     Preinitialize Python from `preconfig' preconfiguration and command
     line arguments (bytes strings).

 -- C 函式: PyStatus Py_PreInitializeFromArgs (const
          PyPreConfig *preconfig, int argc, wchar_t * const * argv)

     Preinitialize Python from `preconfig' preconfiguration and command
     line arguments (wide strings).

The caller is responsible to handle exceptions (error or exit) using
*note PyStatus_Exception(): 2a7. and *note Py_ExitStatusException():
2b0.

For *note Python Configuration: 41e7. (*note
PyPreConfig_InitPythonConfig(): 2a5.), 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 *note -X utf8: 290.
command line option enables the UTF-8 Mode.

‘PyMem_SetAllocator()’ can be called after *note Py_PreInitialize():
2b2. and before *note Py_InitializeFromConfig(): 2b1. to install a
custom memory allocator.  It can be called before *note
Py_PreInitialize(): 2b2. if *note PyPreConfig.allocator: 41e9. is set to
‘PYMEM_ALLOCATOR_NOT_SET’.

Python memory allocation functions like *note PyMem_RawMalloc(): a4e.
must not be used before Python preinitialization, whereas calling
directly ‘malloc()’ and ‘free()’ is always safe.  *note
Py_DecodeLocale(): 53e. must not be called before the preinitialization.

Example using the preinitialization to enable the UTF-8 Mode:

     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();


File: python.info,  Node: PyConfig,  Next: Initialization with PyConfig,  Prev: Preinitialization with PyPreConfig,  Up: Python初始化配置

7.10.5 PyConfig
---------------

 -- C 類型: PyConfig

     Structure containing most parameters to configure Python.

     Structure methods:

      -- C 函式: void PyConfig_InitPythonConfig (PyConfig *config)

          Initialize configuration with *note Python Configuration:
          41e7.

      -- C 函式: void PyConfig_InitIsolatedConfig (PyConfig *config)

          Initialize configuration with *note Isolated Configuration:
          41e8.

      -- C 函式: PyStatus PyConfig_SetString (PyConfig *config, wchar_t
               * const *config_str, const wchar_t *str)

          Copy the wide character string `str' into ‘*config_str’.

          Preinitialize Python if needed.

      -- C 函式: PyStatus PyConfig_SetBytesString (PyConfig *config,
               wchar_t * const *config_str, const char *str)

          Decode `str' using ‘Py_DecodeLocale()’ and set the result into
          ‘*config_str’.

          Preinitialize Python if needed.

      -- C 函式: PyStatus PyConfig_SetArgv (PyConfig *config, int argc,
               wchar_t * const *argv)

          Set command line arguments from wide character strings.

          Preinitialize Python if needed.

      -- C 函式: PyStatus PyConfig_SetBytesArgv (PyConfig *config,
               int argc, char * const *argv)

          Set command line arguments: decode bytes using *note
          Py_DecodeLocale(): 53e.

          Preinitialize Python if needed.

      -- C 函式: PyStatus PyConfig_SetWideStringList (PyConfig *config,
               PyWideStringList *list, Py_ssize_t length,
               wchar_t **items)

          Set the list of wide strings `list' to `length' and `items'.

          Preinitialize Python if needed.

      -- C 函式: PyStatus PyConfig_Read (PyConfig *config)

          Read all Python configuration.

          Fields which are already initialized are left unchanged.

          Preinitialize Python if needed.

      -- C 函式: void PyConfig_Clear (PyConfig *config)

          Release configuration memory.

     Most ‘PyConfig’ methods preinitialize Python if needed.  In that
     case, the Python preinitialization configuration in based on the
     *note PyConfig: 226.  If configuration fields which are in common
     with *note PyPreConfig: 299. are tuned, they must be set before
     calling a *note PyConfig: 226. method:

        * *note dev_mode: 41ef.

        * *note isolated: 41f1.

        * *note parse_argv: 41f8.

        * *note use_environment: 260.

     Moreover, if *note PyConfig_SetArgv(): 2a0. or *note
     PyConfig_SetBytesArgv(): 2a1. is used, this method must be called
     first, before other methods, since the preinitialization
     configuration depends on command line arguments (if ‘parse_argv’ is
     non-zero).

     The caller of these methods is responsible to handle exceptions
     (error or exit) using ‘PyStatus_Exception()’ and
     ‘Py_ExitStatusException()’.

     Structure fields:

      -- C 成員函數: PyWideStringList argv

          Command line arguments, *note sys.argv: cc6.  See *note
          parse_argv: 41f8. to parse *note argv: 41f9. the same way the
          regular Python parses Python command line arguments.  If *note
          argv: 41f9. is empty, an empty string is added to ensure that
          *note sys.argv: cc6. always exists and is never empty.

      -- C 成員函數: wchar_t* base_exec_prefix

          *note sys.base_exec_prefix: 37a1.

      -- C 成員函數: wchar_t* base_executable

          ‘sys._base_executable’: ‘__PYVENV_LAUNCHER__’ environment
          variable value, or copy of *note PyConfig.executable: 41fc.

      -- C 成員函數: wchar_t* base_prefix

          *note sys.base_prefix: 3180.

      -- C 成員函數: wchar_t* platlibdir

          *note sys.platlibdir: 1e9.: platform library directory name,
          set at configure time by ‘--with-platlibdir’, overrideable by
          the ‘PYTHONPLATLIBDIR’ environment variable.

          3.9 版新加入.

      -- 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.

      -- C 成員函數: int bytes_warning

          If equals to 1, issue a warning when comparing *note bytes:
          172. or *note bytearray: 173. with *note str: 205, or
          comparing *note bytes: 172. with *note int: 204.  If equal or
          greater to 2, raise a *note BytesWarning: 5af. exception.

      -- C 成員函數: wchar_t* check_hash_pycs_mode

          Control the validation behavior of hash-based ‘.pyc’ files
          (see PEP 552(1)): *note –check-hash-based-pycs: 1475. command
          line option value.

          Valid values: ‘always’, ‘never’ and ‘default’.

          默认值为: ‘default’.

      -- C 成員函數: int configure_c_stdio

          If non-zero, configure C standard streams (‘stdio’, ‘stdout’,
          ‘stdout’).  For example, set their mode to ‘O_BINARY’ on
          Windows.

      -- C 成員函數: int dev_mode

          If non-zero, enable the *note Python Development Mode: 160.

      -- C 成員函數: int dump_refs

          If non-zero, dump all objects which are still alive at exit.

          ‘Py_TRACE_REFS’ macro must be defined in build.

      -- C 成員函數: wchar_t* exec_prefix

          *note sys.exec_prefix: 37a0.

      -- C 成員函數: wchar_t* executable

          *note sys.executable: 39d.

      -- C 成員函數: int faulthandler

          If non-zero, call *note faulthandler.enable(): 642. at
          startup.

      -- C 成員函數: wchar_t* filesystem_encoding

          Filesystem encoding, *note sys.getfilesystemencoding(): 5ef.

      -- C 成員函數: wchar_t* filesystem_errors

          Filesystem encoding errors, *note
          sys.getfilesystemencodeerrors(): 68b.

      -- C 成員函數: unsigned long hash_seed

      -- C 成員函數: int use_hash_seed

          Randomized hash function seed.

          If *note use_hash_seed: 4208. is zero, a seed is chosen
          randomly at Pythonstartup, and *note hash_seed: 4207. is
          ignored.

      -- C 成員函數: wchar_t* home

          Python home directory.

          Initialized from *note PYTHONHOME: 5d0. environment variable
          value by default.

      -- C 成員函數: int import_time

          If non-zero, profile import time.

      -- C 成員函數: int inspect

          Enter interactive mode after executing a script or a command.

      -- C 成員函數: int install_signal_handlers

          Install signal handlers?

      -- C 成員函數: int interactive

          交互模式

      -- C 成員函數: int isolated

          If greater than 0, enable isolated mode:

             * *note sys.path: 261. contains neither the script’s
               directory (computed from ‘argv[0]’ or the current
               directory) nor the user’s site-packages directory.

             * Python REPL doesn’t import *note readline: de. nor enable
               default readline configuration on interactive prompts.

             * Set *note use_environment: 260. and *note
               user_site_directory: 420d. to 0.

      -- C 成員函數: int legacy_windows_stdio

          If non-zero, use *note io.FileIO: d6c. instead of
          ‘io.WindowsConsoleIO’ for *note sys.stdin: 41e, *note
          sys.stdout: 41f. and *note sys.stderr: 1ea.

          Only available on Windows.  ‘#ifdef MS_WINDOWS’ macro can be
          used for Windows specific code.

      -- C 成員函數: int malloc_stats

          If non-zero, dump statistics on *note Python pymalloc memory
          allocator: 6b8. at exit.

          The option is ignored if Python is built using
          ‘--without-pymalloc’.

      -- C 成員函數: wchar_t* pythonpath_env

          Module search paths as a string separated by ‘DELIM’
          (‘os.path.pathsep’).

          Initialized from *note PYTHONPATH: a34. environment variable
          value by default.

      -- C 成員函數: PyWideStringList module_search_paths

      -- C 成員函數: int module_search_paths_set

          *note sys.path: 261.  If *note module_search_paths_set: 4212.
          is equal to 0, the *note module_search_paths: 4211. is
          overridden by the function calculating the *note Path
          Configuration: 1016.

      -- C 成員函數: int optimization_level

          Compilation optimization level:

             * 0: Peephole optimizer (and ‘__debug__’ is set to ‘True’)

             * 1: Remove assertions, set ‘__debug__’ to ‘False’

             * 2: Strip docstrings

      -- C 成員函數: int parse_argv

          If non-zero, parse *note argv: 41f9. the same way the regular
          Python command line arguments, and strip Python arguments from
          *note argv: 41f9.: see *note Command Line Arguments: a10.

      -- C 成員函數: int parser_debug

          If non-zero, turn on parser debugging output (for expert only,
          depending on compilation options).

      -- C 成員函數: int pathconfig_warnings

          If equal to 0, suppress warnings when calculating the *note
          Path Configuration: 1016. (Unix only, Windows does not log any
          warning).  Otherwise, warnings are written into ‘stderr’.

      -- C 成員函數: wchar_t* prefix

          *note sys.prefix: 379f.

      -- C 成員函數: wchar_t* program_name

          Program name.  Used to initialize *note executable: 41fc, and
          in early error messages.

      -- C 成員函數: wchar_t* pycache_prefix

          *note sys.pycache_prefix: 291.: ‘.pyc’ cache prefix.

          If ‘NULL’, *note sys.pycache_prefix: 291. is set to ‘None’.

      -- C 成員函數: int quiet

          Quiet mode.  For example, don’t display the copyright and
          version messages in interactive mode.

      -- C 成員函數: wchar_t* run_command

          ‘python3 -c COMMAND’ argument.  Used by *note Py_RunMain():
          2b5.

      -- C 成員函數: wchar_t* run_filename

          ‘python3 FILENAME’ argument.  Used by *note Py_RunMain(): 2b5.

      -- C 成員函數: wchar_t* run_module

          ‘python3 -m MODULE’ argument.  Used by *note Py_RunMain():
          2b5.

      -- C 成員函數: int show_ref_count

          Show total reference count at exit?

          Set to 1 by *note -X showrefcount: 290. command line option.

          Need a debug build of Python (‘Py_REF_DEBUG’ macro must be
          defined).

      -- C 成員函數: int site_import

          Import the *note site: eb. module at startup?

      -- C 成員函數: int skip_source_first_line

          Skip the first line of the source?

      -- C 成員函數: wchar_t* stdio_encoding

      -- C 成員函數: wchar_t* stdio_errors

          Encoding and encoding errors of *note sys.stdin: 41e, *note
          sys.stdout: 41f. and *note sys.stderr: 1ea.

      -- C 成員函數: int tracemalloc

          If non-zero, call *note tracemalloc.start(): 1481. at startup.

      -- C 成員函數: int use_environment

          If greater than 0, use *note environment variables: 1485.

      -- C 成員函數: int user_site_directory

          If non-zero, add user site directory to *note sys.path: 261.

      -- C 成員函數: int verbose

          If non-zero, enable verbose mode.

      -- C 成員函數: PyWideStringList warnoptions

          *note sys.warnoptions: 51a.: options of the *note warnings:
          12f. module to build warnings filters: lowest to highest
          priority.

          The *note warnings: 12f. module adds *note sys.warnoptions:
          51a. in the reverse order: the last *note
          PyConfig.warnoptions: 4224. item becomes the first item of
          ‘warnings.filters’ which is checked first (highest priority).

      -- C 成員函數: int write_bytecode

          If non-zero, write ‘.pyc’ files.

          *note sys.dont_write_bytecode: 37ce. is initialized to the
          inverted value of *note write_bytecode: 4225.

      -- C 成員函數: PyWideStringList xoptions

          *note sys._xoptions: 1482.

      -- C 成員函數: int _use_peg_parser

          Enable PEG parser?  Default: 1.

          Set to 0 by *note -X oldparser: 290. and *note
          PYTHONOLDPARSER: 1480.

          参见 PEP 617(2)。

          Deprecated since version 3.9, will be removed in version 3.10.

If ‘parse_argv’ is non-zero, ‘argv’ arguments are parsed the same way
the regular Python parses command line arguments, and Python arguments
are stripped from ‘argv’: see *note Command Line Arguments: a10.

The ‘xoptions’ options are parsed to set other options: see *note -X:
290. option.

3.9 版更變: The ‘show_alloc_count’ field has been removed.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0552

   (2) https://www.python.org/dev/peps/pep-0617


File: python.info,  Node: Initialization with PyConfig,  Next: Isolated Configuration,  Prev: PyConfig,  Up: Python初始化配置

7.10.6 Initialization with PyConfig
-----------------------------------

Function to initialize Python:

 -- C 函式: PyStatus Py_InitializeFromConfig (const PyConfig *config)

     Initialize Python from `config' configuration.

The caller is responsible to handle exceptions (error or exit) using
*note PyStatus_Exception(): 2a7. and *note Py_ExitStatusException():
2b0.

If *note PyImport_FrozenModules(): 2452, *note PyImport_AppendInittab():
f9c. or *note PyImport_ExtendInittab(): f9d. are used, they must be set
or called after Python preinitialization and before the Python
initialization.  If Python is initialized multiple times, *note
PyImport_AppendInittab(): f9c. or *note PyImport_ExtendInittab(): f9d.
must be called before each Python initialization.

Example setting the program name:

     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);
     }

More complete example modifying the default configuration, read the
configuration, and then override some parameters:

     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;
     }


File: python.info,  Node: Isolated Configuration,  Next: Python Configuration,  Prev: Initialization with PyConfig,  Up: Python初始化配置

7.10.7 Isolated Configuration
-----------------------------

*note PyPreConfig_InitIsolatedConfig(): 2a4. and *note
PyConfig_InitIsolatedConfig(): 29d. functions create a configuration to
isolate Python from the system.  For example, to embed Python into an
application.

This configuration ignores global configuration variables, environments
variables, command line arguments (*note PyConfig.argv: 41f9. is not
parsed) and user site directory.  The C standard streams (ex: ‘stdout’)
and the LC_CTYPE locale are left unchanged.  Signal handlers are not
installed.

Configuration files are still used with this configuration.  Set the
*note Path Configuration: 1016. ("output fields") to ignore these
configuration files and avoid the function computing the default path
configuration.


File: python.info,  Node: Python Configuration,  Next: 路径配置,  Prev: Isolated Configuration,  Up: Python初始化配置

7.10.8 Python Configuration
---------------------------

*note PyPreConfig_InitPythonConfig(): 2a5. and *note
PyConfig_InitPythonConfig(): 29e. 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 ( PEP 538(1)) and UTF-8 Mode (
PEP 540(2)) depending on the LC_CTYPE locale, *note PYTHONUTF8: 421. and
*note PYTHONCOERCECLOCALE: 41d. environment variables.

Example of customized Python always running in isolated mode:

     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);
     }

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0538

   (2) https://www.python.org/dev/peps/pep-0540


File: python.info,  Node: 路径配置,  Next: Py_RunMain,  Prev: Python Configuration,  Up: Python初始化配置

7.10.9 路径配置
---------------

*note PyConfig: 226. contains multiple fields for the path
configuration:

   * 路径配置输入：

        * *note PyConfig.home: 4209.

        * *note PyConfig.platlibdir: 1017.

        * *note PyConfig.pathconfig_warnings: 4215.

        * *note PyConfig.program_name: 4217.

        * *note PyConfig.pythonpath_env: 4210.

        * current working directory: to get absolute paths

        * ‘PATH’ environment variable to get the program full path (from
          *note PyConfig.program_name: 4217.)

        * ‘__PYVENV_LAUNCHER__’ environment variable

        * (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).

   * Path configuration output fields:

        * *note PyConfig.base_exec_prefix: 41fa.

        * *note PyConfig.base_executable: 41fb.

        * *note PyConfig.base_prefix: 41fd.

        * *note PyConfig.exec_prefix: 4203.

        * *note PyConfig.executable: 41fc.

        * *note PyConfig.module_search_paths_set: 4212, *note
          PyConfig.module_search_paths: 4211.

        * *note PyConfig.prefix: 4216.

If at least one "output field" is not set, Python calculates the path
configuration to fill unset fields.  If *note module_search_paths_set:
4212. is equal to 0, *note module_search_paths: 4211. is overridden and
*note module_search_paths_set: 4212. 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.  ‘module_search_paths’ is considered as set if
‘module_search_paths_set’ is set to 1.  In this case, path configuration
input fields are ignored as well.

Set *note pathconfig_warnings: 4215. to 0 to suppress warnings when
calculating the path configuration (Unix only, Windows does not log any
warning).

If *note base_prefix: 41fd. or *note base_exec_prefix: 41fa. fields are
not set, they inherit their value from *note prefix: 4216. and *note
exec_prefix: 4203. respectively.

*note Py_RunMain(): 2b5. and *note Py_Main(): 5b1. modify *note
sys.path: 261.:

   * If *note run_filename: 421b. is set and is a directory which
     contains a ‘__main__.py’ script, prepend *note run_filename: 421b.
     to *note sys.path: 261.

   * If *note isolated: 41f1. is zero:

        * If *note run_module: 421c. is set, prepend the current
          directory to *note sys.path: 261.  Do nothing if the current
          directory cannot be read.

        * If *note run_filename: 421b. is set, prepend the directory of
          the filename to *note sys.path: 261.

        * Otherwise, prepend an empty string to *note sys.path: 261.

If *note site_import: 421e. is non-zero, *note sys.path: 261. can be
modified by the *note site: eb. module.  If *note user_site_directory:
420d. is non-zero and the user’s site-package directory exists, the
*note site: eb. module appends the user’s site-package directory to
*note sys.path: 261.

The following configuration files are used by the path configuration:

   * ‘pyvenv.cfg’

   * ‘python._pth’ (仅Windows)

   * ‘pybuilddir.txt’ (仅Unix)

The ‘__PYVENV_LAUNCHER__’ environment variable is used to set *note
PyConfig.base_executable: 41fb.


File: python.info,  Node: Py_RunMain,  Next: Py_GetArgcArgv,  Prev: 路径配置,  Up: Python初始化配置

7.10.10 Py_RunMain()
--------------------

 -- C 函式: int Py_RunMain (void)

     Execute the command (*note PyConfig.run_command: 421a.), the script
     (*note PyConfig.run_filename: 421b.) or the module (*note
     PyConfig.run_module: 421c.) specified on the command line or in the
     configuration.

     By default and when if *note -i: ee1. option is used, run the REPL.

     Finally, finalizes Python and returns an exit status that can be
     passed to the ‘exit()’ function.

See *note Python Configuration: 41e7. for an example of customized
Python always running in isolated mode using *note Py_RunMain(): 2b5.


File: python.info,  Node: Py_GetArgcArgv,  Next: Multi-Phase Initialization Private Provisional API,  Prev: Py_RunMain,  Up: Python初始化配置

7.10.11 Py_GetArgcArgv()
------------------------

 -- C 函式: void Py_GetArgcArgv (int *argc, wchar_t ***argv)

     Get the original command line arguments, before Python modified
     them.


File: python.info,  Node: Multi-Phase Initialization Private Provisional API,  Prev: Py_GetArgcArgv,  Up: Python初始化配置

7.10.12 Multi-Phase Initialization Private Provisional API
----------------------------------------------------------

This section is a private provisional API introducing multi-phase
initialization, the core feature of the PEP 432(1):

   * "Core" initialization phase, "bare minimum Python":

        * Builtin types;

        * Builtin exceptions;

        * Builtin and frozen modules;

        * The *note sys: fd. module is only partially initialized (ex:
          *note sys.path: 261. doesn’t exist yet).

   * "Main" initialization phase, Python is fully initialized:

        * Install and configure *note importlib: 9a.;

        * Apply the *note Path Configuration: 1016.;

        * Install signal handlers;

        * Finish *note sys: fd. module initialization (ex: create *note
          sys.stdout: 41f. and *note sys.path: 261.);

        * Enable optional features like *note faulthandler: 7b. and
          *note tracemalloc: 11d.;

        * Import the *note site: eb. module;

        * 等等.

私有临时API：

   * ‘PyConfig._init_main’: if set to 0, *note
     Py_InitializeFromConfig(): 2b1. stops at the "Core" initialization
     phase.

   * ‘PyConfig._isolated_interpreter’: if non-zero, disallow threads,
     subprocesses and fork.

 -- C 函式: PyStatus _Py_InitializeMain (void)

     Move to the "Main" initialization phase, finish the Python
     initialization.

No module is imported during the "Core" phase and the ‘importlib’ module
is not configured: the *note Path Configuration: 1016. is only applied
during the "Main" phase.  It may allow to customize Python in Python to
override or tune the *note Path Configuration: 1016, maybe install a
custom *note sys.meta_path: 6dd. importer or an import hook, etc.

It may become possible to calculatin the *note Path Configuration: 1016.
in Python, after the Core phase and before the Main phase, which is one
of the PEP 432(2) 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:

     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);
         }
     }

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0432

   (2) https://www.python.org/dev/peps/pep-0432


File: python.info,  Node: 記憶體管理,  Next: 对象实现支持,  Prev: Python初始化配置,  Up: Python/C API 參考手冊

7.11 記憶體管理
===============

* Menu:

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


File: python.info,  Node: 總覽<2>,  Next: 原始内存接口,  Up: 記憶體管理

7.11.1 總覽
-----------

在 Python 中，内存管理涉及到一个包含所有 Python 对象和数据结构的私有堆（
heap）。这个私有堆的管理由内部的 `Python 内存管理器（Python memory
manager）' 保证。Python 内存管理器有不同的组件来处理各种动态存储管理方面
的问题，如共享、分割、预分配或缓存。

在最底层，一个原始内存分配器通过与操作系统的内存管理器交互，确保私有堆中
有足够的空间来存储所有与 Python 相关的数据。在原始内存分配器的基础上，几
个对象特定的分配器在同一堆上运行，并根据每种对象类型的特点实现不同的内存
管理策略。例如，整数对象在堆内的管理方式不同于字符串、元组或字典，因为整
数需要不同的存储需求和速度与空间的权衡。因此，Python 内存管理器将一些工
作分配给对象特定分配器，但确保后者在私有堆的范围内运行。

Python 堆内存的管理是由解释器来执行，用户对它没有控制权，即使他们经常操
作指向堆内内存块的对象指针，理解这一点十分重要。Python 对象和其他内部缓
冲区的堆空间分配是由 Python 内存管理器按需通过本文档中列出的 Python/C
API 函数进行的。

为了避免内存破坏，扩展的作者永远不应该试图用 C 库函数导出的函数来对
Python 对象进行操作，这些函数包括： ‘malloc()’, ‘calloc()’, ‘realloc()’
和 ‘free()’。这将导致 C 分配器和 Python 内存管理器之间的混用，引发严重后
果，这是由于它们实现了不同的算法，并在不同的堆上操作。但是，我们可以安全
地使用 C 库分配器为单独的目的分配和释放内存块，如下例所示：

     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;

在这个例子中，I/O 缓冲区的内存请求是由 C 库分配器处理的。Python 内存管理
器只参与了分配作为结果返回的字节对象。

然而，在大多数情况下，建议专门从 Python 堆中分配内存，因为后者由 Python
内存管理器控制。例如，当解释器扩展了用 C 写的新对象类型时，就必须这样做
。使用 Python 堆的另一个原因是希望*通知* Python 内存管理器关于扩展模块的
内存需求。即使所请求的内存全部只用于内部的、高度特定的目的，将所有的内存
请求交给 Python 内存管理器能让解释器对其内存占用的整体情况有更准确的了解
。因此，在某些情况下，Python 内存管理器可能会触发或不触发适当的操作，如
垃圾回收、内存压缩或其他预防性操作。请注意，通过使用前面例子中所示的 C 库
分配器，为 I/O 缓冲区分配的内存会完全不受 Python 内存管理器管理。

也參考
......

环境变量 *note PYTHONMALLOC: 5fc. 可被用来配置 Python 所使用的内存分配器
。

环境变量 *note PYTHONMALLOCSTATS: 1297. 可以用来在每次创建和关闭新的
pymalloc 对象区域时打印 *note pymalloc 内存分配器: 6b8. 的统计数据。


File: python.info,  Node: 原始内存接口,  Next: 内存接口,  Prev: 總覽<2>,  Up: 記憶體管理

7.11.2 原始内存接口
-------------------

以下函数集封装了系统分配器。这些函数是线程安全的，不需要持有 *note
全局解释器锁: 5ff.。

*note default raw memory allocator: 148f. 使用这些函数：‘malloc()’、
‘calloc()’、 ‘realloc()’ 和 ‘free()’；申请零字节时则调用 ‘malloc(1)’ （
或 ‘calloc(1, 1)’）

3.4 版新加入.

 -- C 函式: void* PyMem_RawMalloc (size_t n)

     分配 `n' 个字节并返回一个指向分配的内存的 ‘void*’ 类型指针，如果请
     求失败则返回 ‘NULL’。

     请求零字节可能返回一个独特的非 ‘NULL’ 指针，就像调用了
     ‘PyMem_RawMalloc(1)’ 一样。但是内存不会以任何方式被初始化。

 -- C 函式: void* PyMem_RawCalloc (size_t nelem, size_t elsize)

     分配 `nelem' 个元素，每个元素的大小为 `elsize' 字节，并返回指向分配
     的内存的 ‘void*’ 类型指针，如果请求失败则返回 ‘NULL’。 内存会被初始
     化为零。

     请求零字节可能返回一个独特的非 ‘NULL’ 指针，就像调用了
     ‘PyMem_RawCalloc(1, 1)’ 一样。

     3.5 版新加入.

 -- C 函式: void* PyMem_RawRealloc (void *p, size_t n)

     将 `p' 指向的内存块大小调整为 `n' 字节。以新旧内存块大小中的最小值
     为准，其中内容保持不变，

     如果 `p' 是 ‘NULL’ ，则相当于调用 ‘PyMem_RawMalloc(n)’ ；如果 `n' 等
     于 0，则内存块大小会被调整，但不会被释放，返回非 ‘NULL’ 指针。

     除非 `p' 是 ‘NULL’ ，否则它必须是之前调用 *note PyMem_RawMalloc():
     a4e. 、 *note PyMem_RawRealloc(): a4f. 或 *note PyMem_RawCalloc():
     893. 所返回的。

     如果请求失败，*note PyMem_RawRealloc(): a4f. 返回 ‘NULL’ ， `p' 仍
     然是指向先前内存区域的有效指针。

 -- C 函式: void PyMem_RawFree (void *p)

     释放 `p' 指向的内存块。 `p' 必须是之前调用 *note PyMem_RawMalloc():
     a4e. 、 *note PyMem_RawRealloc(): a4f. 或 *note PyMem_RawCalloc():
     893. 所返回的指针。否则，或在 ‘PyMem_RawFree(p)’ 之前已经调用过的情
     况下，未定义的行为会发生。

     如果 `p' 是 ‘NULL’, 那么什么操作也不会进行。


File: python.info,  Node: 内存接口,  Next: 对象分配器,  Prev: 原始内存接口,  Up: 記憶體管理

7.11.3 内存接口
---------------

以下函数集，仿照 ANSI C 标准，并指定了请求零字节时的行为，可用于从
Python堆分配和释放内存。

*note 默认内存分配器: 148f. 使用了 *note pymalloc 内存分配器: 6b8.

     警告: 在使用这些函数时，必须持有 *note 全局解释器锁（GIL）: 5ff. 。

3.6 版更變: 现在默认的分配器是 pymalloc 而非系统的 ‘malloc()’ 。

 -- C 函式: void* PyMem_Malloc (size_t n)

     分配 `n' 个字节并返回一个指向分配的内存的 ‘void*’ 类型指针，如果请
     求失败则返回 ‘NULL’。

     请求零字节可能返回一个独特的非 ‘NULL’ 指针，就像调用了
     ‘PyMem_Malloc(1)’ 一样。但是内存不会以任何方式被初始化。

 -- C 函式: void* PyMem_Calloc (size_t nelem, size_t elsize)

     分配 `nelem' 个元素，每个元素的大小为 `elsize' 字节，并返回指向分配
     的内存的 ‘void*’ 类型指针，如果请求失败则返回 ‘NULL’。 内存会被初始
     化为零。

     请求零字节可能返回一个独特的非 ‘NULL’ 指针，就像调用了
     ‘PyMem_Calloc(1, 1)’ 一样。

     3.5 版新加入.

 -- C 函式: void* PyMem_Realloc (void *p, size_t n)

     将 `p' 指向的内存块大小调整为 `n' 字节。以新旧内存块大小中的最小值
     为准，其中内容保持不变，

     如果 `p' 是 ‘NULL’ ，则相当于调用 ‘PyMem_Malloc(n)’ ；如果 `n' 等于
     0，则内存块大小会被调整，但不会被释放，返回非 ‘NULL’ 指针。

     除非 `p' 是 ‘NULL’ ，否则它必须是之前调用 *note PyMem_Malloc():
     5fe. 、 *note PyMem_Realloc(): a50. 或 *note PyMem_Calloc(): 894. 所
     返回的。

     如果请求失败，*note PyMem_Realloc(): a50. 返回 ‘NULL’ ， `p' 仍然是
     指向先前内存区域的有效指针。

 -- C 函式: void PyMem_Free (void *p)

     释放 `p' 指向的内存块。 `p' 必须是之前调用 *note PyMem_Malloc():
     5fe. 、 *note PyMem_Realloc(): a50. 或 *note PyMem_Calloc(): 894. 所
     返回的指针。否则，或在 ‘PyMem_Free(p)’ 之前已经调用过的情况下，未定
     义的行为会发生。

     如果 `p' 是 ‘NULL’, 那么什么操作也不会进行。

以下面向类型的宏为方便而提供。 注意 `TYPE' 可以指任何 C 类型。

 -- C 函式: TYPE* PyMem_New (TYPE, size_t n)

     与 *note PyMem_Malloc(): 5fe. 相同，但会分配 ‘(n * sizeof(TYPE))’ 字
     节的内存。 返回一个转换为 ‘TYPE*’ 的指针。 内存将不会以任何方式被初
     始化。

 -- C 函式: TYPE* PyMem_Resize (void *p, TYPE, size_t n)

     与 *note PyMem_Realloc(): a50. 相同，但内存块的大小被调整为 ‘(n *
     sizeof(TYPE))’ 字节。 返回一个转换为 ‘TYPE*’ 类型的指针。 返回时，
     `p' 将为指向新内存区域的指针，如果失败则返回 ‘NULL’。

     这是一个 C 预处理宏， `p' 总是被重新赋值。请保存 `p' 的原始值，以避
     免在处理错误时丢失内存。

 -- C 函式: void PyMem_Del (void *p)

     与 *note PyMem_Free(): e6e. 相同

此外，我们还提供了以下宏集用于直接调用 Python 内存分配器，而不涉及上面列
出的 C API 函数。但是请注意，使用它们并不能保证跨 Python 版本的二进制兼
容性，因此在扩展模块被弃用。

   * ‘PyMem_MALLOC(size)’

   * ‘PyMem_NEW(type, size)’

   * ‘PyMem_REALLOC(ptr, size)’

   * ‘PyMem_RESIZE(ptr, type, size)’

   * ‘PyMem_FREE(ptr)’

   * ‘PyMem_DEL(ptr)’


File: python.info,  Node: 对象分配器,  Next: 默认内存分配器,  Prev: 内存接口,  Up: 記憶體管理

7.11.4 对象分配器
-----------------

以下函数集，仿照 ANSI C 标准，并指定了请求零字节时的行为，可用于从
Python堆分配和释放内存。

*note 默认对象分配器: 148f. 使用 *note pymalloc 内存分配器: 6b8.

     警告: 在使用这些函数时，必须持有 *note 全局解释器锁（GIL）: 5ff. 。

 -- C 函式: void* PyObject_Malloc (size_t n)

     分配 `n' 个字节并返回一个指向分配的内存的 ‘void*’ 类型指针，如果请
     求失败则返回 ‘NULL’。

     请求零字节可能返回一个独特的非 ‘NULL’ 指针，就像调用了
     ‘PyObject_Malloc(1)’ 一样。但是内存不会以任何方式被初始化。

 -- C 函式: void* PyObject_Calloc (size_t nelem, size_t elsize)

     分配 `nelem' 个元素，每个元素的大小为 `elsize' 字节，并返回指向分配
     的内存的 ‘void*’ 类型指针，如果请求失败则返回 ‘NULL’。 内存会被初始
     化为零。

     请求零字节可能返回一个独特的非 ‘NULL’ 指针，就像调用了
     ‘PyObject_Calloc(1, 1)’ 一样。

     3.5 版新加入.

 -- C 函式: void* PyObject_Realloc (void *p, size_t n)

     将 `p' 指向的内存块大小调整为 `n' 字节。以新旧内存块大小中的最小值
     为准，其中内容保持不变，

     如果*p*是‘‘NULL‘‘，则相当于调用 ‘PyObject_Malloc(n)’ ；如果 `n' 等
     于 0，则内存块大小会被调整，但不会被释放，返回非 ‘NULL’ 指针。

     除非 `p' 是 ‘NULL’ ，否则它必须是之前调用 *note PyObject_Malloc():
     601. 、 *note PyObject_Realloc(): e6f. 或 *note PyObject_Calloc():
     895. 所返回的。

     如果请求失败，*note PyObject_Realloc(): e6f. 返回 ‘NULL’ ， `p' 仍
     然是指向先前内存区域的有效指针。

 -- C 函式: void PyObject_Free (void *p)

     释放 `p' 指向的内存块。 `p' 必须是之前调用 *note PyObject_Malloc():
     601. 、 *note PyObject_Realloc(): e6f. 或 *note PyObject_Calloc():
     895. 所返回的指针。否则，或在 ‘PyObject_Free(p)’ 之前已经调用过的情
     况下，未定义行为会发生。

     如果 `p' 是 ‘NULL’, 那么什么操作也不会进行。


File: python.info,  Node: 默认内存分配器,  Next: 自定义内存分配器,  Prev: 对象分配器,  Up: 記憶體管理

7.11.5 默认内存分配器
---------------------

默认内存分配器：

配置                                名称                     PyMem_RawMalloc        PyMem_Malloc              PyObject_Malloc
                                                                                                              
---------------------------------------------------------------------------------------------------------------------------------------
                                                                                                              
发布版本                            ‘"pymalloc"’             ‘malloc’               ‘pymalloc’                ‘pymalloc’
                                                                                                              
                                                                                                              
调试构建                            ‘"pymalloc_debug"’       ‘malloc’ + debug       ‘pymalloc’ + debug        ‘pymalloc’ + debug
                                                                                                              
                                                                                                              
没有 pymalloc 的发布版本            ‘"malloc"’               ‘malloc’               ‘malloc’                  ‘malloc’
                                                                                                              
                                                                                                              
没有 pymalloc 的调试构建            ‘"malloc_debug"’         ‘malloc’ + debug       ‘malloc’ + debug          ‘malloc’ + debug
                                                                                                              

说明：

   * 名称: 环境变量 *note PYTHONMALLOC: 5fc. 的值

   * ‘malloc’: 来自 C 标准库的系统分配, C 函数 ‘malloc()’, ‘calloc()’,
     ‘realloc()’ and ‘free()’

   * ‘pymalloc’: *note pymalloc 内存分配器: 6b8.

   * "+ debug": 带有 *note PyMem_SetupDebugHooks(): 603. 安装的调试钩子


File: python.info,  Node: 自定义内存分配器,  Next: pymalloc 分配器,  Prev: 默认内存分配器,  Up: 記憶體管理

7.11.6 自定义内存分配器
-----------------------

3.4 版新加入.

 -- C 類型: PyMemAllocatorEx

     用于描述内存块分配器的结构体。包含四个字段：

     域                                                             含义
                                                                    
     -----------------------------------------------------------------------------------------------------------
                                                                    
     ‘void *ctx’                                                    作为第一个参数传入的用户上下文
                                                                    
                                                                    
     ‘void* malloc(void *ctx, size_t size)’                         分配一个内存块
                                                                    
                                                                    
     ‘void* calloc(void *ctx, size_t nelem, size_t elsize)’         分配一个初始化为 0 的内存块
                                                                    
                                                                    
     ‘void* realloc(void *ctx, void *ptr, size_t new_size)’         分配一个内存块或调整其大小
                                                                    
                                                                    
     ‘void free(void *ctx, void *ptr)’                              释放一个内存块
                                                                    

     3.5 版更變: The ‘PyMemAllocator’ structure was renamed to *note
     PyMemAllocatorEx: 8b7. and a new ‘calloc’ field was added.

 -- C 類型: PyMemAllocatorDomain

     用来识别分配器域的枚举类。域有：

      -- C 巨集: PYMEM_DOMAIN_RAW

          函数

             * *note PyMem_RawMalloc(): a4e.

             * *note PyMem_RawRealloc(): a4f.

             * *note PyMem_RawCalloc(): 893.

             * *note PyMem_RawFree(): 3e5b.

      -- C 巨集: PYMEM_DOMAIN_MEM

          函数

             * *note PyMem_Malloc(): 5fe,

             * *note PyMem_Realloc(): a50.

             * *note PyMem_Calloc(): 894.

             * *note PyMem_Free(): e6e.

      -- C 巨集: PYMEM_DOMAIN_OBJ

          函数

             * *note PyObject_Malloc(): 601.

             * *note PyObject_Realloc(): e6f.

             * *note PyObject_Calloc(): 895.

             * *note PyObject_Free(): 5fd.

 -- C 函式: void PyMem_GetAllocator (PyMemAllocatorDomain domain,
          PyMemAllocatorEx *allocator)

     获取指定域的内存块分配器。

 -- C 函式: void PyMem_SetAllocator (PyMemAllocatorDomain domain,
          PyMemAllocatorEx *allocator)

     设置指定域的内存块分配器。

     当请求零字节时，新的分配器必须返回一个独特的非 ‘NULL’ 指针。

     对于 *note PYMEM_DOMAIN_RAW: 1490. 域，分配器必须是线程安全的：当分
     配器被调用时，不持有 *note 全局解释器锁: 5ff. 。

     如果新的分配器不是钩子（不调用之前的分配器），必须调用 *note
     PyMem_SetupDebugHooks(): 603. 函数在新分配器上重新安装调试钩子。

 -- C 函式: void PyMem_SetupDebugHooks (void)

     设置检测 Python 内存分配器函数中错误的钩子。

     新分配的内存由字节 ‘0xCD’ ( ‘CLEANBYTE’ ) 填充，释放的内存由字节
     ‘0xDD’ ( ‘DEADBYTE’ )填充。内存块被 "禁止字节" 包围（
     ‘FORBIDDENBYTE’ ：字节 ‘0xFD’ ）。

     运行时检查：

        - 检测对 API 的违反，例如：对用 *note PyMem_Malloc(): 5fe. 分配
          的缓冲区调用 *note PyObject_Free(): 5fd. 。

        - 检测缓冲区起始位置前的写入（缓冲区下溢）。

        - 检测缓冲区终止位置后的写入（缓冲区溢出）。

        - 检测当调用 *note PYMEM_DOMAIN_OBJ: 600. (如: *note
          PyObject_Malloc(): 601.) 和 *note PYMEM_DOMAIN_MEM: 602. (如:
          *note PyMem_Malloc(): 5fe.) 域的分配器函数时 *note GIL: 5ff. 已
          被保持。

     在出错时，调试钩子使用 *note tracemalloc: 11d. 模块来回溯内存块被分
     配的位置。只有当 *note tracemalloc: 11d. 正在追踪 Python 内存分配，
     并且内存块被追踪时，才会显示回溯。

     如果 Python 是在调试模式下编译的，这些钩子是 *note installed by
     default: 148f. 。环境变量 *note PYTHONMALLOC: 5fc. 可以用来在发布模
     式编译的 Python 上安装调试钩子。

     3.6 版更變: 这个函数现在也适用于以 发布模式编译的 Python。在出错时
     ，调试钩子现在使用 *note tracemalloc: 11d. 来回溯内存块被分配的位置
     。调试钩子现在也检查当 *note PYMEM_DOMAIN_OBJ: 600. 和 *note
     PYMEM_DOMAIN_MEM: 602. 域的函数被调用时，全局解释器锁是否被持有。

     3.8 版更變: 字节模式 ‘0xCB’ (‘CLEANBYTE’)、 ‘0xDB’ (‘DEADBYTE’) 和
     ‘0xFB’ (‘FORBIDDENBYTE’) 已被 ‘0xCD’ 、 ‘0xDD’ 和 ‘0xFD’ 替代以使用
     与 Windows CRT 调试 ‘malloc()’ 和 ‘free()’ 相同的值。


File: python.info,  Node: pymalloc 分配器,  Next: tracemalloc C API,  Prev: 自定义内存分配器,  Up: 記憶體管理

7.11.7 pymalloc 分配器
----------------------

Python 有为具有短生命周期的小对象（小于或等于 512 字节）优化的
`pymalloc' 分配器。它使用固定大小为 256 KiB 的称为 "arenas" 的内存映射。
对于大于512字节的分配，它回到使用 *note PyMem_RawMalloc(): a4e. 和 *note
PyMem_RawRealloc(): a4f. 。

`pymalloc' 是 *note PYMEM_DOMAIN_MEM: 602. (例如: *note PyMem_Malloc():
5fe.) 和 *note PYMEM_DOMAIN_OBJ: 600. (例如: *note PyObject_Malloc():
601.) 域的 *note 默认分配器: 148f. 。

arena 分配器使用以下函数：

   * Windows 上的 ‘VirtualAlloc()’ 和 ‘VirtualFree()’ ,

   * ‘mmap()’ 和 ‘munmap()’ ，如果可用，

   * 否则， ‘malloc()’ 和 ‘free()’ 。

* Menu:

* 自定义 pymalloc Arena 分配器::


File: python.info,  Node: 自定义 pymalloc Arena 分配器,  Up: pymalloc 分配器

7.11.7.1 自定义 pymalloc Arena 分配器
.....................................

3.4 版新加入.

 -- C 類型: PyObjectArenaAllocator

     用来描述一个 arena 分配器的结构体。这个结构体有三个字段：

     域                                                     含义
                                                            
     ---------------------------------------------------------------------------------------------------
                                                            
     ‘void *ctx’                                            作为第一个参数传入的用户上下文
                                                            
                                                            
     ‘void* alloc(void *ctx, size_t size)’                  分配一块 size 字节的区域
                                                            
                                                            
     ‘void free(void *ctx, void *ptr, size_t size)’         释放一块区域
                                                            

 -- C 函式: void PyObject_GetArenaAllocator
          (PyObjectArenaAllocator *allocator)

     获取 arena 分配器

 -- C 函式: void PyObject_SetArenaAllocator
          (PyObjectArenaAllocator *allocator)

     设置 arena 分配器


File: python.info,  Node: tracemalloc C API,  Next: 示例<51>,  Prev: pymalloc 分配器,  Up: 記憶體管理

7.11.8 tracemalloc C API
------------------------

3.7 版新加入.

 -- C 函式: int PyTraceMalloc_Track (unsigned int domain, uintptr_t ptr,
          size_t size)

     在 *note tracemalloc: 11d. 模块中跟踪一个已分配的内存块。

     成功时返回 ‘0’，出错时返回 ‘-1’ (无法分配内存来保存跟踪信息)。 如果
     禁用了 tracemalloc 则返回 ‘-2’。

     如果内存块已被跟踪，则更新现有跟踪信息。

 -- C 函式: int PyTraceMalloc_Untrack (unsigned int domain,
          uintptr_t ptr)

     在 *note tracemalloc: 11d. 模块中取消跟踪一个已分配的内存块。 如果
     内存块未被跟踪则不执行任何操作。

     如果 tracemalloc 被禁用则返回 ‘-2’，否则返回 ‘0’。


File: python.info,  Node: 示例<51>,  Prev: tracemalloc C API,  Up: 記憶體管理

7.11.9 示例
-----------

以下是来自 *note 總覽: 4232. 小节的示例，经过重写以使 I/O 缓冲区是通过使
用第一个函数集从 Python 堆中分配的:

     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;

使用面向类型函数集的相同代码:

     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;

请注意在以上两个示例中，缓冲区总是通过归属于相同集的函数来操纵的。 事实
上，对于一个给定的内存块必须使用相同的内存 API 族，以便使得混合不同分配
器的风险减至最低。 以下代码序列包含两处错误，其中一个被标记为 `fatal' 因
为它混合了两种在不同堆上操作的不同分配器。

     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()  */

除了旨在处理来自 Python 堆的原始内存块的函数之外， Python 中的对象是通过
*note PyObject_New(): 268, *note PyObject_NewVar(): 269. 和 *note
PyObject_Del(): ed8. 来分配和释放的。

这些将在有关如何在 C 中定义和实现新对象类型的下一章中讲解。


File: python.info,  Node: 对象实现支持,  Next: API 和 ABI 版本管理,  Prev: 記憶體管理,  Up: Python/C API 參考手冊

7.12 对象实现支持
=================

本章描述了定义新对象类型时所使用的函数、类型和宏。

* Menu:

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


File: python.info,  Node: 在堆中分配对象,  Next: 通用物件結構,  Up: 对象实现支持

7.12.1 在堆中分配对象
---------------------

 -- C 函式: PyObject* _PyObject_New (PyTypeObject *type)
     `Return value: New reference.'

 -- C 函式: PyVarObject* _PyObject_NewVar (PyTypeObject *type,
          Py_ssize_t size)
     `Return value: New reference.'

 -- C 函式: PyObject* PyObject_Init (PyObject *op, PyTypeObject *type)
     `Return value: Borrowed reference.' 为新分配的对象 `op' 初始化它的
     类型和引用。返回初始化后的对象。如果 `type' 声明这个对象参与循环垃
     圾检测，那么这个对象会被添加进垃圾检测的对象集中。这个对象的其他字
     段不会被影响。

 -- C 函式: PyVarObject* PyObject_InitVar (PyVarObject *op,
          PyTypeObject *type, Py_ssize_t size)
     `Return value: Borrowed reference.' 它的功能和 *note
     PyObject_Init(): 398. 一样，并且初始化变量大小的对象的长度。

 -- C 函式: TYPE* PyObject_New (TYPE, PyTypeObject *type)
     `Return value: New reference.' 使用 C 结构类型 `TYPE' 和 Python 类
     型对象 `type' 分配一个新的 Python 对象。 未在该 Python 对象头中定义
     的字段不会被初始化；对象的引用计数将为一。 内存分配大小由 type 对象
     的 *note tp_basicsize: 26a. 字段来确定。

 -- C 函式: TYPE* PyObject_NewVar (TYPE, PyTypeObject *type,
          Py_ssize_t size)
     `Return value: New reference.' 使用C的数据结构类型 `TYPE' 和
     Python的类型对象 `type' 分配一个新的Python对象。Python对象头文件中
     没有定义的字段不会被初始化。被分配的内存空间预留了 `TYPE' 结构加
     `type' 对象中 *note tp_itemsize: 3d54. 字段提供的 `size' 字段的值。
     这对于实现类似元组这种能够在构造期决定自己大小的对象是很实用的。将
     字段的数组嵌入到相同的内存分配中可以减少内存分配的次数，这提高了内
     存分配的效率。

 -- C 函式: void PyObject_Del (void *op)

     释放由 *note PyObject_New(): 268. 或者 *note PyObject_NewVar():
     269. 分配内存的对象。这通常由对象的type字段定义的 *note tp_dealloc:
     3d5a. 处理函数来调用。调用这个函数以后op对象中的字段都不可以被访问
     ，因为原分配的内存空间已不再是一个有效的Python对象。

 -- C 變數: PyObject _Py_NoneStruct

     像 ‘None’ 一样的Python对象。这个对象仅可以使用 *note Py_None: 3d23.
     宏访问，这个宏取得指向这个对象的指针。

也參考
......

*note PyModule_Create(): 3d26.

     分配内存和创建扩展模块。


File: python.info,  Node: 通用物件結構,  Next: Type 对象<2>,  Prev: 在堆中分配对象,  Up: 对象实现支持

7.12.2 通用物件結構
-------------------

大量的结构体被用于定义Python的对象类型。这一节描述了这些的结构体和它们的
使用方法。

* Menu:

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


File: python.info,  Node: 基本的对象类型和宏,  Next: Implementing functions and methods,  Up: 通用物件結構

7.12.2.1 基本的对象类型和宏
...........................

所有的 Python 对象都在对象的内存表示的开始部分共享少量的字段。 这些字段
用 *note PyObject: 5b4. 或 *note PyVarObject: 4251. 类型来表示，这些类型
又由一些宏定义，这些宏也直接或间接地用于所有其他 Python 对象的定义。

 -- 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 *note PyObject:
     5b4, but every pointer to a Python object can be cast to a *note
     PyObject*: 5b4.  Access to the members must be done by using the
     macros *note Py_REFCNT: 3d52. and *note Py_TYPE: 3d53.

 -- C 類型: PyVarObject

     This is an extension of *note PyObject: 5b4. that adds the
     ‘ob_size’ field.  This is only used for objects that have some
     notion of `length'.  This type does not often appear in the
     Python/C API. Access to the members must be done by using the
     macros *note Py_REFCNT: 3d52, *note Py_TYPE: 3d53, and *note
     Py_SIZE: 4252.

 -- 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:

          PyObject ob_base;

     See documentation of *note PyObject: 5b4. above.

 -- 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:

          PyVarObject ob_base;

     See documentation of *note PyVarObject: 4251. above.

 -- C 巨集: Py_TYPE (o)

     This macro is used to access the ‘ob_type’ member of a Python
     object.  It expands to:

          (((PyObject*)(o))->ob_type)

 -- C 函式: int Py_IS_TYPE (PyObject *o, PyTypeObject *type)

     Return non-zero if the object `o' type is `type'.  Return zero
     otherwise.  Equivalent to: ‘Py_TYPE(o) == type’.

     3.9 版新加入.

 -- C 函式: void Py_SET_TYPE (PyObject *o, PyTypeObject *type)

     Set the object `o' type to `type'.

     3.9 版新加入.

 -- C 巨集: Py_REFCNT (o)

     This macro is used to access the ‘ob_refcnt’ member of a Python
     object.  It expands to:

          (((PyObject*)(o))->ob_refcnt)

 -- C 函式: void Py_SET_REFCNT (PyObject *o, Py_ssize_t refcnt)

     Set the object `o' reference counter to `refcnt'.

     3.9 版新加入.

 -- C 巨集: Py_SIZE (o)

     This macro is used to access the ‘ob_size’ member of a Python
     object.  It expands to:

          (((PyVarObject*)(o))->ob_size)

 -- C 函式: void Py_SET_SIZE (PyVarObject *o, Py_ssize_t size)

     Set the object `o' size to `size'.

     3.9 版新加入.

 -- C 巨集: PyObject_HEAD_INIT (type)

     This is a macro which expands to initialization values for a new
     *note PyObject: 5b4. type.  This macro expands to:

          _PyObject_EXTRA_INIT
          1, type,

 -- C 巨集: PyVarObject_HEAD_INIT (type, size)

     This is a macro which expands to initialization values for a new
     *note PyVarObject: 4251. type, including the ‘ob_size’ field.  This
     macro expands to:

          _PyObject_EXTRA_INIT
          1, type, size,


File: python.info,  Node: Implementing functions and methods,  Next: Accessing attributes of extension types,  Prev: 基本的对象类型和宏,  Up: 通用物件結構

7.12.2.2 Implementing functions and methods
...........................................

 -- C 類型: PyCFunction

     Type of the functions used to implement most Python callables in C.
     Functions of this type take two *note PyObject*: 5b4. parameters
     and return one such value.  If the return value is ‘NULL’, an
     exception shall have been set.  If not ‘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:

          PyObject *PyCFunction(PyObject *self,
                                PyObject *args);

 -- C 類型: PyCFunctionWithKeywords

     Type of the functions used to implement Python callables in C with
     signature ‘METH_VARARGS | METH_KEYWORDS’.  The function signature
     is:

          PyObject *PyCFunctionWithKeywords(PyObject *self,
                                            PyObject *args,
                                            PyObject *kwargs);

 -- C 類型: _PyCFunctionFast

     Type of the functions used to implement Python callables in C with
     signature *note METH_FASTCALL: 10f3.  The function signature is:

          PyObject *_PyCFunctionFast(PyObject *self,
                                     PyObject *const *args,
                                     Py_ssize_t nargs);

 -- C 類型: _PyCFunctionFastWithKeywords

     Type of the functions used to implement Python callables in C with
     signature ‘METH_FASTCALL | METH_KEYWORDS’.  The function signature
     is:

          PyObject *_PyCFunctionFastWithKeywords(PyObject *self,
                                                 PyObject *const *args,
                                                 Py_ssize_t nargs,
                                                 PyObject *kwnames);

 -- C 類型: PyCMethod

     Type of the functions used to implement Python callables in C with
     signature ‘METH_METHOD | METH_FASTCALL | METH_KEYWORDS’.  The
     function signature is:

          PyObject *PyCMethod(PyObject *self,
                              PyTypeObject *defining_class,
                              PyObject *const *args,
                              Py_ssize_t nargs,
                              PyObject *kwnames)

     3.9 版新加入.

 -- C 類型: PyMethodDef

     Structure used to describe a method of an extension type.  This
     structure has four fields:

     域                     C Type              意义
                                                
     -------------------------------------------------------------------------------
                                                
     ‘ml_name’              const char *        name of the method
                                                
                                                
     ‘ml_meth’              PyCFunction         pointer to the C implementation
                                                
                                                
     ‘ml_flags’             int                 flag bits indicating how the call
                                                should be constructed
                                                
                                                
     ‘ml_doc’               const char *        points to the contents of the
                                                docstring
                                                

The ‘ml_meth’ is a C function pointer.  The functions may be of
different types, but they always return *note PyObject*: 5b4.  If the
function is not of the *note PyCFunction: e9f, the compiler will require
a cast in the method table.  Even though *note PyCFunction: e9f. defines
the first parameter as *note PyObject*: 5b4, it is common that the
method implementation uses the specific C type of the `self' object.

The ‘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:

 -- Data: METH_VARARGS

     This is the typical calling convention, where the methods have the
     type *note PyCFunction: e9f.  The function expects two *note
     PyObject*: 5b4. values.  The first one is the `self' object for
     methods; for module functions, it is the module object.  The second
     parameter (often called `args') is a tuple object representing all
     arguments.  This parameter is typically processed using *note
     PyArg_ParseTuple(): 393. or *note PyArg_UnpackTuple(): f08.

 -- Data: METH_VARARGS | METH_KEYWORDS

     Methods with these flags must be of type *note
     PyCFunctionWithKeywords: 4257.  The function expects three
     parameters: `self', `args', `kwargs' where `kwargs' is a dictionary
     of all the keyword arguments or possibly ‘NULL’ if there are no
     keyword arguments.  The parameters are typically processed using
     *note PyArg_ParseTupleAndKeywords(): 6c1.

 -- Data: METH_FASTCALL

     Fast calling convention supporting only positional arguments.  The
     methods have the type *note _PyCFunctionFast: 4258.  The first
     parameter is `self', the second parameter is a C array of *note
     PyObject*: 5b4. values indicating the arguments and the third
     parameter is the number of arguments (the length of the array).

     This is not part of the *note limited API: 3dda.

     3.7 版新加入.

 -- Data: METH_FASTCALL | METH_KEYWORDS

     Extension of *note METH_FASTCALL: 10f3. supporting also keyword
     arguments, with methods of type *note _PyCFunctionFastWithKeywords:
     4259.  Keyword arguments are passed the same way as in the *note
     vectorcall protocol: 2b8.: there is an additional fourth *note
     PyObject*: 5b4. parameter which is a tuple representing the names
     of the keyword arguments (which are guaranteed to be strings) or
     possibly ‘NULL’ if there are no keywords.  The values of the
     keyword arguments are stored in the `args' array, after the
     positional arguments.

     This is not part of the *note limited API: 3dda.

     3.7 版新加入.

 -- Data: METH_METHOD | METH_FASTCALL | METH_KEYWORDS

     Extension of ‘METH_FASTCALL | METH_KEYWORDS’ supporting the
     `defining class', that is, the class that contains the method in
     question.  The defining class might be a superclass of
     ‘Py_TYPE(self)’.

     The method needs to be of type *note PyCMethod: 248, the same as
     for ‘METH_FASTCALL | METH_KEYWORDS’ with ‘defining_class’ argument
     added after ‘self’.

     3.9 版新加入.

 -- Data: METH_NOARGS

     Methods without parameters don’t need to check whether arguments
     are given if they are listed with the *note METH_NOARGS: eda. flag.
     They need to be of type *note PyCFunction: e9f.  The first
     parameter is typically named `self' and will hold a reference to
     the module or object instance.  In all cases the second parameter
     will be ‘NULL’.

 -- Data: METH_O

     Methods with a single object argument can be listed with the *note
     METH_O: f09. flag, instead of invoking *note PyArg_ParseTuple():
     393. with a ‘"O"’ argument.  They have the type *note PyCFunction:
     e9f, with the `self' parameter, and a *note PyObject*: 5b4.
     parameter representing the single argument.

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.

 -- Data: METH_CLASS

     The method will be passed the type object as the first parameter
     rather than an instance of the type.  This is used to create `class
     methods', similar to what is created when using the *note
     classmethod(): 309. built-in function.

 -- Data: METH_STATIC

     The method will be passed ‘NULL’ as the first parameter rather than
     an instance of the type.  This is used to create `static methods',
     similar to what is created when using the *note staticmethod():
     30a. built-in function.

One other constant controls whether a method is loaded in place of
another definition with the same method name.

 -- Data: METH_COEXIST

     The method will be loaded in place of existing definitions.
     Without `METH_COEXIST', the default is to skip repeated
     definitions.  Since slot wrappers are loaded before the method
     table, the existence of a `sq_contains' slot, for example, would
     generate a wrapped method named *note __contains__(): dee. 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.


File: python.info,  Node: Accessing attributes of extension types,  Prev: Implementing functions and methods,  Up: 通用物件結構

7.12.2.3 Accessing attributes of extension types
................................................

 -- C 類型: PyMemberDef

     Structure which describes an attribute of a type which corresponds
     to a C struct member.  Its fields are:

     域                     C Type              意义
                                                
     -------------------------------------------------------------------------------
                                                
     ‘name’                 const char *        name of the member
                                                
                                                
     ‘type’                 int                 the type of the member in the C
                                                struct
                                                
                                                
     ‘offset’               Py_ssize_t          the offset in bytes that the
                                                member is located on the type’s
                                                object struct
                                                
                                                
     ‘flags’                int                 flag bits indicating if the field
                                                should be read-only or writable
                                                
                                                
     ‘doc’                  const char *        points to the contents of the
                                                docstring
                                                

     ‘type’ can be one of many ‘T_’ macros corresponding to various C
     types.  When the member is accessed in Python, it will be converted
     to the equivalent Python type.

     Macro name          C数据类型
                         
     -------------------------------------------
                         
     T_SHORT             short
                         
                         
     T_INT               int
                         
                         
     T_LONG              长整型
                         
                         
     T_FLOAT             float
                         
                         
     T_DOUBLE            double
                         
                         
     T_STRING            const char *
                         
                         
     T_OBJECT            PyObject *
                         
                         
     T_OBJECT_EX         PyObject *
                         
                         
     T_CHAR              char
                         
                         
     T_BYTE              char
                         
                         
     T_UBYTE             unsigned char
                         
                         
     T_UINT              unsigned int
                         
                         
     T_USHORT            unsigned short
                         
                         
     T_ULONG             unsigned long
                         
                         
     T_BOOL              char
                         
                         
     T_LONGLONG          long long
                         
                         
     T_ULONGLONG         unsigned long long
                         
                         
     T_PYSSIZET          Py_ssize_t
                         

     ‘T_OBJECT’ and ‘T_OBJECT_EX’ differ in that ‘T_OBJECT’ returns
     ‘None’ if the member is ‘NULL’ and ‘T_OBJECT_EX’ raises an *note
     AttributeError: 4a1.  Try to use ‘T_OBJECT_EX’ over ‘T_OBJECT’
     because ‘T_OBJECT_EX’ handles use of the *note del: 13a2. statement
     on that attribute more correctly than ‘T_OBJECT’.

     ‘flags’ can be ‘0’ for write and read access or ‘READONLY’ for
     read-only access.  Using ‘T_STRING’ for *note type: 6ff. implies
     ‘READONLY’.  ‘T_STRING’ data is interpreted as UTF-8.  Only
     ‘T_OBJECT’ and ‘T_OBJECT_EX’ members can be deleted.  (They are set
     to ‘NULL’).  Heap allocated types (created using *note
     PyType_FromSpec(): 23a. or similar), ‘PyMemberDef’ may contain
     definitions for the special members ‘__dictoffset__’,
     ‘__weaklistoffset__’ and ‘__vectorcalloffset__’, corresponding to
     *note tp_dictoffset: 3f97, *note tp_weaklistoffset: 26b. and *note
     tp_vectorcall_offset: 3ee0. in type objects.  These must be defined
     with ‘T_PYSSIZET’ and ‘READONLY’, for example:

          static PyMemberDef spam_type_members[] = {
              {"__dictoffset__", T_PYSSIZET, offsetof(Spam_object, dict), READONLY},
              {NULL}  /* Sentinel */
          };

 -- C 函式: PyObject* PyMember_GetOne (const char *obj_addr, struct
          PyMemberDef *m)

     Get an attribute belonging to the object at address `obj_addr'.
     The attribute is described by ‘PyMemberDef’ `m'.  Returns ‘NULL’ on
     error.

 -- C 函式: int PyMember_SetOne (char *obj_addr, struct PyMemberDef *m,
          PyObject *o)

     Set an attribute belonging to the object at address `obj_addr' to
     object `o'.  The attribute to set is described by ‘PyMemberDef’
     `m'.  Returns ‘0’ if successful and a negative value on failure.

 -- C 類型: PyGetSetDef

     Structure to define property-like access for a type.  See also
     description of the *note PyTypeObject.tp_getset: 3d64. slot.

     域                C Type                 意义
                                              
     ---------------------------------------------------------------------------------
                                              
     name              const char *           attribute name
                                              
                                              
     get               getter                 C Function to get the attribute
                                              
                                              
     set               setter                 optional C function to set or delete
                                              the attribute, if omitted the
                                              attribute is readonly
                                              
                                              
     doc               const char *           optional docstring
                                              
                                              
     closure           void *                 optional function pointer, providing
                                              additional data for getter and setter
                                              

     The ‘get’ function takes one *note PyObject*: 5b4. parameter (the
     instance) and a function pointer (the associated ‘closure’):

          typedef PyObject *(*getter)(PyObject *, void *);

     It should return a new reference on success or ‘NULL’ with a set
     exception on failure.

     ‘set’ functions take two *note PyObject*: 5b4. parameters (the
     instance and the value to be set) and a function pointer (the
     associated ‘closure’):

          typedef int (*setter)(PyObject *, PyObject *, void *);

     In case the attribute should be deleted the second parameter is
     ‘NULL’.  Should return ‘0’ on success or ‘-1’ with a set exception
     on failure.


File: python.info,  Node: Type 对象<2>,  Next: Number Object Structures,  Prev: 通用物件結構,  Up: 对象实现支持

7.12.3 Type 对象
----------------

也许 Python 对象系统中最重要的结构之一就是定义新类型的结构: *note
PyTypeObject: 3f5. 结构。 类型对象可以使用任何 ‘PyObject_*()’ 或
‘PyType_*()’ 函数来处理，但不能提供大多数 Python 应用程序所感兴趣的内容
。 这些对象是对象行为的基础，所以它们对解释器本身或任何实现新类型的扩展
模块都非常重要。

与大多数标准类型相比，类型对象相当大。这么大的原因是每个类型对象存储了大
量的值，大部分是C函数指针，每个指针实现了类型功能的一小部分。本节将详细
描述类型对象的字段。这些字段将按照它们在结构中出现的顺序进行描述。

除了下面的快速参考，*note 例子: 4260. 小节提供了快速了解 *note
PyTypeObject: 3f5. 的含义和用法的例子。

* Menu:

* 快速参考: 快速参考<2>.
* PyTypeObject Definition::
* PyObject Slots::
* PyVarObject Slots::
* PyTypeObject Slots::
* Heap Types::


File: python.info,  Node: 快速参考<2>,  Next: PyTypeObject Definition,  Up: Type 对象<2>

7.12.3.1 快速参考
.................

* Menu:

* "tp 槽"::
* 子方法槽（方法域）::
* slot typedefs::


File: python.info,  Node: "tp 槽",  Next: 子方法槽（方法域）,  Up: 快速参考<2>

7.12.3.2 "tp 槽"
................

PyTypeObject 槽 (1)    *note Type: 4264.      特殊方法/属性          信
                                                                     息
                                                                     (2)
                                                                     
---------------------------------------------------------------------------------------------
                                                                     
O                      T                      D                      I
                                                                     
                                                                                       
<R>                    const char *           __name__               X     X
*note tp_name: 3d75.                                                       

*note tp_basicsize: 26a.Py_ssize_t                                   X     X           X
                                                                                       
                                                                                       
*note tp_itemsize: 3d54.Py_ssize_t                                         X           X
                                                                                       
                                                                                       
*note tp_dealloc: 3d5a.*note destructor: 4265.                       X     X           X
                                                                                       
                                                                                       
*note tp_vectorcall_offset: 3ee0.Py_ssize_t                                X           X
                                                                                       
                                                                                       
(*note tp_getattr: 3d7c.)*note getattrfunc: 4266.__getattribute__,                     G
                                              __getattr__                              
                                              
                                                                                       
(*note tp_setattr: 3d7d.)*note setattrfunc: 4267.__setattr__,                          G
                                              __delattr__                              
                                              
                                                                                       
*note tp_as_async: 4268.*note PyAsyncMethods: 3f8d.*note 子方法槽（方法域）: 4269.     %
                       *                                                               
                       
                                                                                       
*note tp_repr: 3d74.   *note reprfunc: 426a.  __repr__               X     X           X
                                                                                       
                                                                                       
*note tp_as_number: 26f.*note PyNumberMethods: e46.*note 子方法槽（方法域）: 4269.     %
                       *                                                               
                       
                                                                                       
*note tp_as_sequence: 426b.*note PySequenceMethods: 3d83.*note 子方法槽（方法域）: 4269.%
                       *                                                               
                       
                                                                                       
*note tp_as_mapping: 426c.*note PyMappingMethods: 3d84.*note 子方法槽（方法域）: 4269. %
                       *                                                               
                       
                                                                                       
*note tp_hash: 3d85.   *note hashfunc: 426d.  __hash__               X                 G
                                                                                       
                                                                                       
*note tp_call: 3d86.   *note ternaryfunc: 426e.__call__                    X           X
                                                                                       
                                                                                       
*note tp_str: 3d76.    *note reprfunc: 426a.  __str__                X                 X
                                                                                       
                                                                                       
*note tp_getattro: 3d79.*note getattrofunc: 426f.__getattribute__,   X     X           G
                                              __getattr__                              
                                              
                                                                                       
*note tp_setattro: 3d7a.*note setattrofunc: 4270.__setattr__,        X     X           G
                                              __delattr__                              
                                              
                                                                                       
*note tp_as_buffer: 26d.*note PyBufferProcs: 3f99.                                     %
                       *                                                               
                       
                                                                                       
*note tp_flags: 1011.  无符号长整型                                  X     X           ?
                                                                                       
                                                                                       
*note tp_doc: 3d56.    const char *           __doc__                X     X
                                                                           
                                                                                       
*note tp_traverse: 23b.*note traverseproc: 4271.                           X           G
                                                                                       
                                                                                       
*note tp_clear: 3d72.  *note inquiry: 4272.                                X           G
                                                                                       
                                                                                       
*note tp_richcompare: 3d7f.*note richcmpfunc: 4273.__lt__, __le__,   X                 G
                                              __eq__, __ne__,                          
                                              __gt__, __ge__
                                              
                                                                                       
*note tp_weaklistoffset: 26b.Py_ssize_t                                    X           ?
                                                                                       
                                                                                       
*note tp_iter: ef2.    *note getiterfunc: 4274.__iter__                                X
                                                                                       
                                                                                       
*note tp_iternext: ef3.*note iternextfunc: 4275.__next__                               X
                                                                                       
                                                                                       
*note tp_methods: 3d61.*note PyMethodDef: edd.                       X     X
                       []                                                  
                       
                                                                                       
*note tp_members: 3d5f.*note PyMemberDef: 529.                             X
                       []                                                  
                       
                                                                                       
*note tp_getset: 3d64. *note PyGetSetDef: 52a.                       X     X
                       []                                                  
                       
                                                                                       
*note tp_base: 3d6a.   *note PyTypeObject: 3f5.__base__                          X
                       *                                                         
                       
                                                                                       
*note tp_dict: 3f90.   *note PyObject: 5b4.   __dict__                           ?
                       *                                                         
                       
                                                                                       
*note tp_descr_get: 4276.*note descrgetfunc: 4277.__get__                              X
                                                                                       
                                                                                       
*note tp_descr_set: 4278.*note descrsetfunc: 4279.__set__, __delete__                  X
                                                                                       
                                                                                       
*note tp_dictoffset: 3f97.Py_ssize_t                                       X           ?
                                                                                       
                                                                                       
*note tp_init: 3d5e.   *note initproc: 427a.  __init__               X     X           X
                                                                                       
                                                                                       
*note tp_alloc: 3d5c.  *note allocfunc: 427b.                        X           ?     ?
                                                                                       
                                                                                       
*note tp_new: 3d57.    *note newfunc: 427c.   __new__                X     X     ?     ?
                                                                                       
                                                                                       
*note tp_free: 3d5b.   *note freefunc: 427d.                         X     X     ?     ?
                                                                                       
                                                                                       
*note tp_is_gc: 427e.  *note inquiry: 4272.                                X           X
                                                                                       
                                                                                       
<*note tp_bases: 427f.>*note PyObject: 5b4.   __bases__                          ~
                       *                                                         
                       
                                                                                       
<*note tp_mro: 3f91.>  *note PyObject: 5b4.   __mro__                            ~
                       *                                                         
                       
                                                                                       
[*note tp_cache: 3f92.]*note PyObject: 5b4.
                       *
                       
                                                                                       
[*note tp_subclasses: 3f93.]*note PyObject: 5b4.__subclasses__
                       *                      
                       
                                                                                       
[*note tp_weaklist: 3f94.]*note PyObject: 5b4.
                       *
                       
                                                                                       
(*note tp_del: 4280.)  *note destructor: 4265.
                       
                                                                                       
[*note tp_version_tag: 4281.]无符号整型
                       
                                                                                       
*note tp_finalize: 3f6.*note destructor: 4265.__del__                                  X
                                                                                       
                                                                                       
*note tp_vectorcall: 3f95.*note vectorcallfunc: 3ee1.
                       

   ---------- Footnotes ----------

   (1) (1) 小括号中的槽名表示它(实际上)已弃用。尖括号中的名称应该被视为
只读的。方括号中的名称仅供内部使用。"<R>"(作为前缀)表示该字段是必需的(必
须是非null)。

   (2) (2) 列：

`"O"': ‘PyBaseObject_Type’ 必须设置

`"T"': *note PyType_Type: 3f7d. 必须设置

`"D"': 默认设置(如果方法槽被设置为NULL)

     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").

`"I"': 继承

     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

注意，有些方法槽是通过普通属性查找链有效继承的。


File: python.info,  Node: 子方法槽（方法域）,  Next: slot typedefs,  Prev: "tp 槽",  Up: 快速参考<2>

7.12.3.3 子方法槽（方法域）
...........................

槽                             *note Type: 4264.     特殊方法
                                                     
----------------------------------------------------------------------
                                                     
*note am_await: 4283.          *note unaryfunc: 4284.__await__
                                                     
                                                     
*note am_aiter: 4285.          *note unaryfunc: 4284.__aiter__
                                                     
                                                     
*note am_anext: 4286.          *note unaryfunc: 4284.__anext__
                                                     
                                                     
                                                     
*note nb_add: 3f8e.            *note binaryfunc: 4287.__add__
                                                     __radd__
                                                     
                                                     
*note nb_inplace_add: 4288.    *note binaryfunc: 4287.__iadd__
                                                     
                                                     
*note nb_subtract: 4289.       *note binaryfunc: 4287.__sub__
                                                     __rsub__
                                                     
                                                     
*note nb_inplace_subtract: 428a.*note binaryfunc: 4287.__isub__
                                                     
                                                     
*note nb_multiply: 428b.       *note binaryfunc: 4287.__mul__
                                                     __rmul__
                                                     
                                                     
*note nb_inplace_multiply: 428c.*note binaryfunc: 4287.__imul__
                                                     
                                                     
*note nb_remainder: 428d.      *note binaryfunc: 4287.__mod__
                                                     __rmod__
                                                     
                                                     
*note nb_inplace_remainder: 428e.*note binaryfunc: 4287.__imod__
                                                     
                                                     
*note nb_divmod: 428f.         *note binaryfunc: 4287.__divmod__
                                                     __rdivmod__
                                                     
                                                     
*note nb_power: 4290.          *note ternaryfunc: 426e.__pow__
                                                     __rpow__
                                                     
                                                     
*note nb_inplace_power: 4291.  *note ternaryfunc: 426e.__ipow__
                                                     
                                                     
*note nb_negative: 4292.       *note unaryfunc: 4284.__neg__
                                                     
                                                     
*note nb_positive: 4293.       *note unaryfunc: 4284.__pos__
                                                     
                                                     
*note nb_absolute: 4294.       *note unaryfunc: 4284.__abs__
                                                     
                                                     
*note nb_bool: 4295.           *note inquiry: 4272.  __bool__
                                                     
                                                     
*note nb_invert: 4296.         *note unaryfunc: 4284.__invert__
                                                     
                                                     
*note nb_lshift: 4297.         *note binaryfunc: 4287.__lshift__
                                                     __rlshift__
                                                     
                                                     
*note nb_inplace_lshift: 4298. *note binaryfunc: 4287.__ilshift__
                                                     
                                                     
*note nb_rshift: 4299.         *note binaryfunc: 4287.__rshift__
                                                     __rrshift__
                                                     
                                                     
*note nb_inplace_rshift: 429a. *note binaryfunc: 4287.__irshift__
                                                     
                                                     
*note nb_and: 429b.            *note binaryfunc: 4287.__and__
                                                     __rand__
                                                     
                                                     
*note nb_inplace_and: 429c.    *note binaryfunc: 4287.__iand__
                                                     
                                                     
*note nb_xor: 429d.            *note binaryfunc: 4287.__xor__
                                                     __rxor__
                                                     
                                                     
*note nb_inplace_xor: 429e.    *note binaryfunc: 4287.__ixor__
                                                     
                                                     
*note nb_or: 429f.             *note binaryfunc: 4287.__or__ __ror__
                                                     
                                                     
*note nb_inplace_or: 42a0.     *note binaryfunc: 4287.__ior__
                                                     
                                                     
*note nb_int: 42a1.            *note unaryfunc: 4284.__int__
                                                     
                                                     
*note nb_reserved: 42a2.       void *
                               
                                                     
*note nb_float: 42a3.          *note unaryfunc: 4284.__float__
                                                     
                                                     
*note nb_floor_divide: 42a4.   *note binaryfunc: 4287.__floordiv__
                                                     
                                                     
*note nb_inplace_floor_divide: 42a5.*note binaryfunc: 4287.__ifloordiv__
                                                     
                                                     
*note nb_true_divide: 42a6.    *note binaryfunc: 4287.__truediv__
                                                     
                                                     
*note nb_inplace_true_divide: 42a7.*note binaryfunc: 4287.__itruediv__
                                                     
                                                     
*note nb_index: 42a8.          *note unaryfunc: 4284.__index__
                                                     
                                                     
*note nb_matrix_multiply: 42a9.*note binaryfunc: 4287.__matmul__
                                                     __rmatmul__
                                                     
                                                     
*note nb_inplace_matrix_multiply: 42aa.*note binaryfunc: 4287.__imatmul__
                                                     
                                                     
                                                     
*note mp_length: 42ab.         *note lenfunc: 42ac.  __len__
                                                     
                                                     
*note mp_subscript: 42ad.      *note binaryfunc: 4287.__getitem__
                                                     
                                                     
*note mp_ass_subscript: 42ae.  *note objobjargproc: 42af.__setitem__,
                                                     __delitem__
                                                     
                                                     
                                                     
*note sq_length: 3f8f.         *note lenfunc: 42ac.  __len__
                                                     
                                                     
*note sq_concat: 42b0.         *note binaryfunc: 4287.__add__
                                                     
                                                     
*note sq_repeat: 42b1.         *note ssizeargfunc: 42b2.__mul__
                                                     
                                                     
*note sq_item: 10bf.           *note ssizeargfunc: 42b2.__getitem__
                                                     
                                                     
*note sq_ass_item: 42b3.       *note ssizeobjargproc: 42b4.__setitem__
                                                     __delitem__
                                                     
                                                     
*note sq_contains: 42b5.       *note objobjproc: 42b6.__contains__
                                                     
                                                     
*note sq_inplace_concat: 42b7. *note binaryfunc: 4287.__iadd__
                                                     
                                                     
*note sq_inplace_repeat: 42b8. *note ssizeargfunc: 42b2.__imul__
                                                     
                                                     
                                                     
*note bf_getbuffer: 3f98.      *note getbufferproc(): 42b9.
                               
                                                     
*note bf_releasebuffer: 3e8e.  *note releasebufferproc(): 42ba.
                               


File: python.info,  Node: slot typedefs,  Prev: 子方法槽（方法域）,  Up: 快速参考<2>

7.12.3.4 slot typedefs
......................

typedef                           参数类型                          返回类型
                                                                    
-----------------------------------------------------------------------------------------------
                                                                    
*note allocfunc: 427b.                 *note PyTypeObject: 3f5. *   *note PyObject: 5b4. *
                                       Py_ssize_t                   
                                  
                                                                    
*note destructor: 4265.           void *                            void
                                                                    
                                                                    
*note freefunc: 427d.             void *                            void
                                                                    
                                                                    
*note traverseproc: 4271.              void *                       整型
                                       *note visitproc: 42bc.       
                                       void * 
                                  
                                                                    
*note newfunc: 427c.                   *note PyObject: 5b4. *       *note PyObject: 5b4. *
                                       *note PyObject: 5b4. *       
                                       *note PyObject: 5b4. * 
                                  
                                                                    
*note initproc: 427a.                  *note PyObject: 5b4. *       整型
                                       *note PyObject: 5b4. *       
                                       *note PyObject: 5b4. * 
                                  
                                                                    
*note reprfunc: 426a.             *note PyObject: 5b4. *            *note PyObject: 5b4. *
                                                                    
                                                                    
*note getattrfunc: 4266.               *note PyObject: 5b4. *       *note PyObject: 5b4. *
                                       const char *                 
                                  
                                                                    
*note setattrfunc: 4267.               *note PyObject: 5b4. *       整型
                                       const char *                 
                                       *note PyObject: 5b4. * 
                                  
                                                                    
*note getattrofunc: 426f.              *note PyObject: 5b4. *       *note PyObject: 5b4. *
                                       *note PyObject: 5b4. *       
                                  
                                                                    
*note setattrofunc: 4270.              *note PyObject: 5b4. *       整型
                                       *note PyObject: 5b4. *       
                                       *note PyObject: 5b4. * 
                                  
                                                                    
*note descrgetfunc: 4277.              *note PyObject: 5b4. *       *note PyObject: 5b4. *
                                       *note PyObject: 5b4. *       
                                       *note PyObject: 5b4. * 
                                  
                                                                    
*note descrsetfunc: 4279.              *note PyObject: 5b4. *       整型
                                       *note PyObject: 5b4. *       
                                       *note PyObject: 5b4. * 
                                  
                                                                    
*note hashfunc: 426d.             *note PyObject: 5b4. *            Py_hash_t
                                                                    
                                                                    
*note richcmpfunc: 4273.               *note PyObject: 5b4. *       *note PyObject: 5b4. *
                                       *note PyObject: 5b4. *       
                                       整型 
                                  
                                                                    
*note getiterfunc: 4274.          *note PyObject: 5b4. *            *note PyObject: 5b4. *
                                                                    
                                                                    
*note iternextfunc: 4275.         *note PyObject: 5b4. *            *note PyObject: 5b4. *
                                                                    
                                                                    
*note lenfunc: 42ac.              *note PyObject: 5b4. *            Py_ssize_t
                                                                    
                                                                    
*note getbufferproc: 42b9.             *note PyObject: 5b4. *       整型
                                       *note Py_buffer: bee. *      
                                       整型 
                                  
                                                                    
*note releasebufferproc: 42ba.         *note PyObject: 5b4. *       void
                                       *note Py_buffer: bee. *      
                                  
                                                                    
*note inquiry: 4272.              void *                            整型
                                                                    
                                                                    
*note unaryfunc: 4284.                 *note PyObject: 5b4. *       *note PyObject: 5b4. *
                                                                    
                                                                    
*note binaryfunc: 4287.                *note PyObject: 5b4. *       *note PyObject: 5b4. *
                                       *note PyObject: 5b4. *       
                                  
                                                                    
*note ternaryfunc: 426e.               *note PyObject: 5b4. *       *note PyObject: 5b4. *
                                       *note PyObject: 5b4. *       
                                       *note PyObject: 5b4. * 
                                  
                                                                    
*note ssizeargfunc: 42b2.              *note PyObject: 5b4. *       *note PyObject: 5b4. *
                                       Py_ssize_t                   
                                  
                                                                    
*note ssizeobjargproc: 42b4.           *note PyObject: 5b4. *       整型
                                       Py_ssize_t                   
                                  
                                                                    
*note objobjproc: 42b6.                *note PyObject: 5b4. *       整型
                                       *note PyObject: 5b4. *       
                                  
                                                                    
*note objobjargproc: 42af.             *note PyObject: 5b4. *       整型
                                       *note PyObject: 5b4. *       
                                       *note PyObject: 5b4. * 
                                  

请参阅 *note Slot Type typedefs: 42bd. 里有更多详细信息。


File: python.info,  Node: PyTypeObject Definition,  Next: PyObject Slots,  Prev: 快速参考<2>,  Up: Type 对象<2>

7.12.3.5 PyTypeObject Definition
................................

*note PyTypeObject: 3f5. 的结构定义可以在 ‘Include/object.h’ 中找到。 为
了方便参考，此处复述了其中的定义:

     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;


File: python.info,  Node: PyObject Slots,  Next: PyVarObject Slots,  Prev: PyTypeObject Definition,  Up: Type 对象<2>

7.12.3.6 PyObject Slots
.......................

type 对象结构扩展了 *note PyVarObject: 4251. 结构。 ‘ob_size’ 字段用于动
态类型 (由 ‘type_new()’ 创建，通常通过 class 语句来调用)。 注意 *note
PyType_Type: 3f7d. (元类型) 会初始化 *note tp_itemsize: 3d54.，这意味着
它的实例 (即 type 对象) `必须' 具有 ‘ob_size’ 字段。

 -- C 成員函數: PyObject* PyObject._ob_next
 -- C 成員函數: PyObject* PyObject._ob_prev

     These fields are only present when the macro ‘Py_TRACE_REFS’ is
     defined.  Their initialization to ‘NULL’ is taken care of by the
     ‘PyObject_HEAD_INIT’ macro.  For statically allocated objects,
     these fields always remain ‘NULL’.  For dynamically allocated
     objects, these two fields are used to link the object into a
     doubly-linked list of `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 *note PYTHONDUMPREFS: 293. is set.

     `Inheritance:'

     These fields are not inherited by subtypes.

 -- C 成員函數: Py_ssize_t PyObject.ob_refcnt

     这是类型对象的引用计数，由 ‘PyObject_HEAD_INIT’ 宏初始化为 ‘1’。 请
     注意对于静态分配的类型对象 (对象的 ‘ob_type’ 指回该类型) `不会' 被
     加入引用计数。 但对于动态分配的类型对象，实例 `确实' 会被算作引用。

     `Inheritance:'

     子类型不继承此字段。

 -- C 成員函數: PyTypeObject* PyObject.ob_type

     This is the type’s type, in other words its metatype.  It is
     initialized by the argument to the ‘PyObject_HEAD_INIT’ macro, and
     its value should normally be ‘&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 ‘NULL’ to the
     ‘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:

          Foo_Type.ob_type = &PyType_Type;

     This should be done before any instances of the type are created.
     *note PyType_Ready(): 3d5d. checks if ‘ob_type’ is ‘NULL’, and if
     so, initializes it to the ‘ob_type’ field of the base class.  *note
     PyType_Ready(): 3d5d. will not change this field if it is non-zero.

     `Inheritance:'

     This field is inherited by subtypes.


File: python.info,  Node: PyVarObject Slots,  Next: PyTypeObject Slots,  Prev: PyObject Slots,  Up: Type 对象<2>

7.12.3.7 PyVarObject Slots
..........................

 -- 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.

     `Inheritance:'

     子类型不继承此字段。


File: python.info,  Node: PyTypeObject Slots,  Next: Heap Types,  Prev: PyVarObject Slots,  Up: Type 对象<2>

7.12.3.8 PyTypeObject Slots
...........................

Each slot has a section describing inheritance.  If *note
PyType_Ready(): 3d5d. may set a value when the field is set to ‘NULL’
then there will also be a "Default" section.  (Note that many fields set
on ‘PyBaseObject_Type’ and *note PyType_Type: 3f7d. effectively act as
defaults.)

 -- 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 ‘T’ defined in
     module ‘M’ in subpackage ‘Q’ in package ‘P’ should have the *note
     tp_name: 3d75. initializer ‘"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 ‘'__module__'’.

     For statically allocated type objects, the tp_name field should
     contain a dot.  Everything before the last dot is made accessible
     as the ‘__module__’ attribute, and everything after the last dot is
     made accessible as the *note __name__: d2f. attribute.

     If no dot is present, the entire *note tp_name: 3d75. field is made
     accessible as the *note __name__: d2f. attribute, and the
     ‘__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 ‘NULL’.  It is the only required field in
     *note PyTypeObject(): 3f5. (other than potentially *note
     tp_itemsize: 3d54.).

     `Inheritance:'

     子类型不继承此字段。

 -- C 成員函數: Py_ssize_t PyTypeObject.tp_basicsize
 -- 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 *note tp_itemsize: 3d54. field, types with
     variable-length instances have a non-zero *note tp_itemsize: 3d54.
     field.  For a type with fixed-length instances, all instances have
     the same size, given in *note tp_basicsize: 26a.

     For a type with variable-length instances, the instances must have
     an ‘ob_size’ field, and the instance size is *note tp_basicsize:
     26a. plus N times *note tp_itemsize: 3d54, where N is the "length"
     of the object.  The value of N is typically stored in the
     instance’s ‘ob_size’ field.  There are exceptions: for example,
     ints use a negative ‘ob_size’ to indicate a negative number, and N
     is ‘abs(ob_size)’ there.  Also, the presence of an ‘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
     ‘ob_size’ field).

     The basic size includes the fields in the instance declared by the
     macro *note PyObject_HEAD: d3a. or *note PyObject_VAR_HEAD: 4253.
     (whichever is used to declare the instance struct) and this in turn
     includes the ‘_ob_prev’ and ‘_ob_next’ fields if they are present.
     This means that the only correct way to get an initializer for the
     *note tp_basicsize: 26a. is to use the ‘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 *note
     tp_basicsize: 26a.  Example: suppose a type implements an array of
     ‘double’.  *note tp_itemsize: 3d54. is ‘sizeof(double)’.  It is the
     programmer’s responsibility that *note tp_basicsize: 26a. is a
     multiple of ‘sizeof(double)’ (assuming this is the alignment
     requirement for ‘double’).

     For any type with variable-length instances, this field must not be
     ‘NULL’.

     `Inheritance:'

     These fields are inherited separately by subtypes.  If the base
     type has a non-zero *note tp_itemsize: 3d54, it is generally not
     safe to set *note tp_itemsize: 3d54. to a different non-zero value
     in a subtype (though this depends on the implementation of the base
     type).

 -- 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 ‘None’ and
     ‘Ellipsis’).  The function signature is:

          void tp_dealloc(PyObject *self);

     The destructor function is called by the *note Py_DECREF(): 38f.
     and *note Py_XDECREF(): 391. 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 *note tp_free: 3d5b. function.  If the type is not
     subtypable (doesn’t have the *note Py_TPFLAGS_BASETYPE: 3d62. flag
     bit set), it is permissible to call the object deallocator directly
     instead of via *note tp_free: 3d5b.  The object deallocator should
     be the one used to allocate the instance; this is normally *note
     PyObject_Del(): ed8. if the instance was allocated using *note
     PyObject_New(): 268. or ‘PyObject_VarNew()’, or *note
     PyObject_GC_Del(): f05. if the instance was allocated using *note
     PyObject_GC_New(): 3f3. or *note PyObject_GC_NewVar(): 3f4.

     If the type supports garbage collection (has the *note
     Py_TPFLAGS_HAVE_GC: 3d68. flag bit set), the destructor should call
     *note PyObject_GC_UnTrack(): f07. before clearing any member
     fields.

          static void foo_dealloc(foo_object *self) {
              PyObject_GC_UnTrack(self);
              Py_CLEAR(self->ref);
              Py_TYPE(self)->tp_free((PyObject *)self);
          }

     Finally, if the type is heap allocated (*note Py_TPFLAGS_HEAPTYPE:
     3f84.), 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:

          static void foo_dealloc(foo_object *self) {
              PyTypeObject *tp = Py_TYPE(self);
              // free references and buffers here
              tp->tp_free(self);
              Py_DECREF(tp);
          }

     `Inheritance:'

     This field is inherited by subtypes.

 -- C 成員函數: Py_ssize_t PyTypeObject.tp_vectorcall_offset

     An optional offset to a per-instance function that implements
     calling the object using the *note vectorcall protocol: 2b8, a more
     efficient alternative of the simpler *note tp_call: 3d86.

     This field is only used if the flag *note
     Py_TPFLAGS_HAVE_VECTORCALL: 3edf. is set.  If so, this must be a
     positive integer containing the offset in the instance of a *note
     vectorcallfunc: 3ee1. pointer.

     The `vectorcallfunc' pointer may be ‘NULL’, in which case the
     instance behaves as if *note Py_TPFLAGS_HAVE_VECTORCALL: 3edf. was
     not set: calling the instance falls back to *note tp_call: 3d86.

     Any class that sets ‘Py_TPFLAGS_HAVE_VECTORCALL’ must also set
     *note tp_call: 3d86. and make sure its behaviour is consistent with
     the `vectorcallfunc' function.  This can be done by setting
     `tp_call' to *note PyVectorcall_Call(): 3ede.

          警告: It is not recommended for *note heap types: 3f83. to
          implement the vectorcall protocol.  When a user sets *note
          __call__: 1560. in Python code, only `tp_call' is updated,
          likely making it inconsistent with the vectorcall function.

          備註: The semantics of the ‘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.

     3.8 版更變: Before version 3.8, this slot was named ‘tp_print’.  In
     Python 2.x, it was used for printing to a file.  In Python 3.0 to
     3.7, it was unused.

     `Inheritance:'

     This field is always inherited.  However, the *note
     Py_TPFLAGS_HAVE_VECTORCALL: 3edf. flag is not always inherited.  If
     it’s not, then the subclass won’t use *note vectorcall: 2b8, except
     when *note PyVectorcall_Call(): 3ede. is explicitly called.  This
     is in particular the case for *note heap types: 42c7. (including
     subclasses defined in Python).

 -- 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 *note tp_getattro: 3d79.
     function, but taking a C string instead of a Python string object
     to give the attribute name.

     `Inheritance:'

     Group: ‘tp_getattr’, ‘tp_getattro’

     This field is inherited by subtypes together with *note
     tp_getattro: 3d79.: a subtype inherits both *note tp_getattr: 3d7c.
     and *note tp_getattro: 3d79. from its base type when the subtype’s
     *note tp_getattr: 3d7c. and *note tp_getattro: 3d79. are both
     ‘NULL’.

 -- 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 *note tp_setattro: 3d7a.
     function, but taking a C string instead of a Python string object
     to give the attribute name.

     `Inheritance:'

     Group: ‘tp_setattr’, ‘tp_setattro’

     This field is inherited by subtypes together with *note
     tp_setattro: 3d7a.: a subtype inherits both *note tp_setattr: 3d7d.
     and *note tp_setattro: 3d7a. from its base type when the subtype’s
     *note tp_setattr: 3d7d. and *note tp_setattro: 3d7a. are both
     ‘NULL’.

 -- C 成員函數: PyAsyncMethods* PyTypeObject.tp_as_async

     Pointer to an additional structure that contains fields relevant
     only to objects which implement *note awaitable: 612. and *note
     asynchronous iterator: 738. protocols at the C-level.  See *note
     Async Object Structures: 42c8. for details.

     3.5 版新加入: Formerly known as ‘tp_compare’ and ‘tp_reserved’.

     `Inheritance:'

     The *note tp_as_async: 4268. field is not inherited, but the
     contained fields are inherited individually.

 -- C 成員函數: reprfunc PyTypeObject.tp_repr

     An optional pointer to a function that implements the built-in
     function *note repr(): 8b9.

     The signature is the same as for *note PyObject_Repr(): a49.:

          PyObject *tp_repr(PyObject *self);

     The function must return a string or a Unicode object.  Ideally,
     this function should return a string that, when passed to *note
     eval(): c61, given a suitable environment, returns an object with
     the same value.  If this is not feasible, it should return a string
     starting with ‘'<'’ and ending with ‘'>'’ from which both the type
     and the value of the object can be deduced.

     `Inheritance:'

     This field is inherited by subtypes.

     `Default:'

     When this field is not set, a string of the form ‘<%s object at
     %p>’ is returned, where ‘%s’ is replaced by the type name, and ‘%p’
     by the object’s memory address.

 -- 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 *note Number Object Structures: 42c9.

     `Inheritance:'

     The *note tp_as_number: 26f. field is not inherited, but the
     contained fields are inherited individually.

 -- 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 *note Sequence Object Structures: 42ca.

     `Inheritance:'

     The *note tp_as_sequence: 426b. field is not inherited, but the
     contained fields are inherited individually.

 -- 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 *note Mapping Object Structures: 42cb.

     `Inheritance:'

     The *note tp_as_mapping: 426c. field is not inherited, but the
     contained fields are inherited individually.

 -- C 成員函數: hashfunc PyTypeObject.tp_hash

     An optional pointer to a function that implements the built-in
     function *note hash(): aa3.

     The signature is the same as for *note PyObject_Hash(): 3ed0.:

          Py_hash_t tp_hash(PyObject *);

     The value ‘-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 ‘-1’.

     When this field is not set (`and' ‘tp_richcompare’ is not set), an
     attempt to take the hash of the object raises *note TypeError: 1fe.
     This is the same as setting it to *note
     PyObject_HashNotImplemented(): df7.

     This field can be set explicitly to *note
     PyObject_HashNotImplemented(): df7. to block inheritance of the
     hash method from a parent type.  This is interpreted as the
     equivalent of ‘__hash__ = None’ at the Python level, causing
     ‘isinstance(o, collections.Hashable)’ to correctly return ‘False’.
     Note that the converse is also true - setting ‘__hash__ = None’ on
     a class at the Python level will result in the ‘tp_hash’ slot being
     set to *note PyObject_HashNotImplemented(): df7.

     `Inheritance:'

     Group: ‘tp_hash’, ‘tp_richcompare’

     This field is inherited by subtypes together with *note
     tp_richcompare: 3d7f.: a subtype inherits both of *note
     tp_richcompare: 3d7f. and *note tp_hash: 3d85, when the subtype’s
     *note tp_richcompare: 3d7f. and *note tp_hash: 3d85. are both
     ‘NULL’.

 -- C 成員函數: ternaryfunc PyTypeObject.tp_call

     An optional pointer to a function that implements calling the
     object.  This should be ‘NULL’ if the object is not callable.  The
     signature is the same as for *note PyObject_Call(): 23c.:

          PyObject *tp_call(PyObject *self, PyObject *args, PyObject *kwargs);

     `Inheritance:'

     This field is inherited by subtypes.

 -- C 成員函數: reprfunc PyTypeObject.tp_str

     An optional pointer to a function that implements the built-in
     operation *note str(): 205.  (Note that *note str: 205. is a type
     now, and *note str(): 205. calls the constructor for that type.
     This constructor calls *note PyObject_Str(): a4a. to do the actual
     work, and *note PyObject_Str(): a4a. will call this handler.)

     The signature is the same as for *note PyObject_Str(): a4a.:

          PyObject *tp_str(PyObject *self);

     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 *note
     print(): 971. function.

     `Inheritance:'

     This field is inherited by subtypes.

     `Default:'

     When this field is not set, *note PyObject_Repr(): a49. is called
     to return a string representation.

 -- C 成員函數: getattrofunc PyTypeObject.tp_getattro

     An optional pointer to the get-attribute function.

     The signature is the same as for *note PyObject_GetAttr(): 3ec4.:

          PyObject *tp_getattro(PyObject *self, PyObject *attr);

     It is usually convenient to set this field to *note
     PyObject_GenericGetAttr(): 3ec6, which implements the normal way of
     looking for object attributes.

     `Inheritance:'

     Group: ‘tp_getattr’, ‘tp_getattro’

     This field is inherited by subtypes together with *note tp_getattr:
     3d7c.: a subtype inherits both *note tp_getattr: 3d7c. and *note
     tp_getattro: 3d79. from its base type when the subtype’s *note
     tp_getattr: 3d7c. and *note tp_getattro: 3d79. are both ‘NULL’.

     `Default:'

     ‘PyBaseObject_Type’ uses *note PyObject_GenericGetAttr(): 3ec6.

 -- C 成員函數: setattrofunc PyTypeObject.tp_setattro

     An optional pointer to the function for setting and deleting
     attributes.

     The signature is the same as for *note PyObject_SetAttr(): 3ec7.:

          int tp_setattro(PyObject *self, PyObject *attr, PyObject *value);

     In addition, setting `value' to ‘NULL’ to delete an attribute must
     be supported.  It is usually convenient to set this field to *note
     PyObject_GenericSetAttr(): 3ec9, which implements the normal way of
     setting object attributes.

     `Inheritance:'

     Group: ‘tp_setattr’, ‘tp_setattro’

     This field is inherited by subtypes together with *note tp_setattr:
     3d7d.: a subtype inherits both *note tp_setattr: 3d7d. and *note
     tp_setattro: 3d7a. from its base type when the subtype’s *note
     tp_setattr: 3d7d. and *note tp_setattro: 3d7a. are both ‘NULL’.

     `Default:'

     ‘PyBaseObject_Type’ uses *note PyObject_GenericSetAttr(): 3ec9.

 -- 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 *note Buffer Object Structures: 3f3c.

     `Inheritance:'

     The *note tp_as_buffer: 26d. field is not inherited, but the
     contained fields are inherited individually.

 -- 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 *note tp_as_number: 26f, *note
     tp_as_sequence: 426b, *note tp_as_mapping: 426c, and *note
     tp_as_buffer: 26d.) 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 ‘NULL’
     value instead.

     `Inheritance:'

     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 *note Py_TPFLAGS_HAVE_GC: 3d68. flag bit is
     inherited together with the *note tp_traverse: 23b. and *note
     tp_clear: 3d72. fields, i.e.  if the *note Py_TPFLAGS_HAVE_GC:
     3d68. flag bit is clear in the subtype and the *note tp_traverse:
     23b. and *note tp_clear: 3d72. fields in the subtype exist and have
     ‘NULL’ values.

     `Default:'

     ‘PyBaseObject_Type’ uses ‘Py_TPFLAGS_DEFAULT |
     Py_TPFLAGS_BASETYPE’.

     `Bit Masks:'

     The following bit masks are currently defined; these can be ORed
     together using the ‘|’ operator to form the value of the *note
     tp_flags: 1011. field.  The macro *note PyType_HasFeature(): 1010.
     takes a type and a flags value, `tp' and `f', and checks whether
     ‘tp->tp_flags & f’ is non-zero.

      -- Data: Py_TPFLAGS_HEAPTYPE

          This bit is set when the type object itself is allocated on
          the heap, for example, types created dynamically using *note
          PyType_FromSpec(): 23a.  In this case, the ‘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).

          `Inheritance:'

          ???

      -- Data: 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).

          `Inheritance:'

          ???

      -- Data: Py_TPFLAGS_READY

          This bit is set when the type object has been fully
          initialized by *note PyType_Ready(): 3d5d.

          `Inheritance:'

          ???

      -- Data: Py_TPFLAGS_READYING

          This bit is set while *note PyType_Ready(): 3d5d. is in the
          process of initializing the type object.

          `Inheritance:'

          ???

      -- Data: Py_TPFLAGS_HAVE_GC

          This bit is set when the object supports garbage collection.
          If this bit is set, instances must be created using *note
          PyObject_GC_New(): 3f3. and destroyed using *note
          PyObject_GC_Del(): f05.  More information in section *note
          使对象类型支持循环垃圾回收: 42ce.  This bit also implies that
          the GC-related fields *note tp_traverse: 23b. and *note
          tp_clear: 3d72. are present in the type object.

          `Inheritance:'

          Group: *note Py_TPFLAGS_HAVE_GC: 3d68, ‘tp_traverse’,
          ‘tp_clear’

          The *note Py_TPFLAGS_HAVE_GC: 3d68. flag bit is inherited
          together with the ‘tp_traverse’ and ‘tp_clear’ fields, i.e.
          if the *note Py_TPFLAGS_HAVE_GC: 3d68. flag bit is clear in
          the subtype and the ‘tp_traverse’ and ‘tp_clear’ fields in the
          subtype exist and have ‘NULL’ values.

      -- Data: 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: ‘Py_TPFLAGS_HAVE_STACKLESS_EXTENSION’,
          ‘Py_TPFLAGS_HAVE_VERSION_TAG’.

          `Inheritance:'

          ???

      -- Data: Py_TPFLAGS_METHOD_DESCRIPTOR

          This bit indicates that objects behave like unbound methods.

          If this flag is set for ‘type(meth)’, then:

             - ‘meth.__get__(obj, cls)(*args, **kwds)’ (with ‘obj’ not
               None) must be equivalent to ‘meth(obj, *args, **kwds)’.

             - ‘meth.__get__(None, cls)(*args, **kwds)’ must be
               equivalent to ‘meth(*args, **kwds)’.

          This flag enables an optimization for typical method calls
          like ‘obj.meth()’: it avoids creating a temporary "bound
          method" object for ‘obj.meth’.

          3.8 版新加入.

          `Inheritance:'

          This flag is never inherited by heap types.  For extension
          types, it is inherited whenever *note tp_descr_get: 4276. is
          inherited.

      -- Data: Py_TPFLAGS_LONG_SUBCLASS

      -- Data: Py_TPFLAGS_LIST_SUBCLASS

      -- Data: Py_TPFLAGS_TUPLE_SUBCLASS

      -- Data: Py_TPFLAGS_BYTES_SUBCLASS

      -- Data: Py_TPFLAGS_UNICODE_SUBCLASS

      -- Data: Py_TPFLAGS_DICT_SUBCLASS

      -- Data: Py_TPFLAGS_BASE_EXC_SUBCLASS

      -- Data: Py_TPFLAGS_TYPE_SUBCLASS

          These flags are used by functions such as *note
          PyLong_Check(): 3fa5. to quickly determine if a type is a
          subclass of a built-in type; such specific checks are faster
          than a generic check, like *note PyObject_IsInstance(): 88c.
          Custom types that inherit from built-ins should have their
          *note tp_flags: 1011. set appropriately, or the code that
          interacts with such types will behave differently depending on
          what kind of check is used.

      -- Data: Py_TPFLAGS_HAVE_FINALIZE

          This bit is set when the *note tp_finalize: 3f6. slot is
          present in the type structure.

          3.4 版新加入.

          3.8 版後已棄用: This flag isn’t necessary anymore, as the
          interpreter assumes the *note tp_finalize: 3f6. slot is always
          present in the type structure.

      -- Data: Py_TPFLAGS_HAVE_VECTORCALL

          This bit is set when the class implements the *note vectorcall
          protocol: 2b8.  See *note tp_vectorcall_offset: 3ee0. for
          details.

          `Inheritance:'

          This bit is inherited for `static' subtypes if *note tp_call:
          3d86. is also inherited.  *note Heap types: 42c7. do not
          inherit ‘Py_TPFLAGS_HAVE_VECTORCALL’.

          3.9 版新加入.

 -- 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 ‘__doc__’
     attribute on the type and instances of the type.

     `Inheritance:'

     This field is `not' inherited by subtypes.

 -- C 成員函數: traverseproc PyTypeObject.tp_traverse

     An optional pointer to a traversal function for the garbage
     collector.  This is only used if the *note Py_TPFLAGS_HAVE_GC:
     3d68. flag bit is set.  The signature is:

          int tp_traverse(PyObject *self, visitproc visit, void *arg);

     More information about Python’s garbage collection scheme can be
     found in section *note 使对象类型支持循环垃圾回收: 42ce.

     The *note tp_traverse: 23b. pointer is used by the garbage
     collector to detect reference cycles.  A typical implementation of
     a *note tp_traverse: 23b. function simply calls *note Py_VISIT():
     3d66. on each of the instance’s members that are Python objects
     that the instance owns.  For example, this is function
     ‘local_traverse()’ from the *note _thread: 2. extension module:

          static int
          local_traverse(localobject *self, visitproc visit, void *arg)
          {
              Py_VISIT(self->args);
              Py_VISIT(self->kw);
              Py_VISIT(self->dict);
              return 0;
          }

     Note that *note Py_VISIT(): 3d66. is called only on those members
     that can participate in reference cycles.  Although there is also a
     ‘self->key’ member, it can only be ‘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 *note gc: 84. module’s *note get_referents(): fb7. function
     will include it.

          警告: When implementing *note tp_traverse: 23b, only the
          members that the instance `owns' (by having strong references
          to them) must be visited.  For instance, if an object supports
          weak references via the *note tp_weaklist: 3f94. slot, the
          pointer supporting the linked list (what `tp_weaklist' points
          to) must `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).

     Note that *note Py_VISIT(): 3d66. requires the `visit' and `arg'
     parameters to ‘local_traverse()’ to have these specific names;
     don’t name them just anything.

     Heap-allocated types (*note Py_TPFLAGS_HEAPTYPE: 3f84, such as
     those created with *note PyType_FromSpec(): 23a. and similar APIs)
     hold a reference to their type.  Their traversal function must
     therefore either visit *note Py_TYPE(self): 3d53, or delegate this
     responsibility by calling ‘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
     ‘Py_TYPE(self)’ in ‘tp_traverse’.  In earlier versions of Python,
     due to bug 40217(1), doing this may lead to crashes in subclasses.

     `Inheritance:'

     Group: *note Py_TPFLAGS_HAVE_GC: 3d68, ‘tp_traverse’, ‘tp_clear’

     This field is inherited by subtypes together with *note tp_clear:
     3d72. and the *note Py_TPFLAGS_HAVE_GC: 3d68. flag bit: the flag
     bit, *note tp_traverse: 23b, and *note tp_clear: 3d72. are all
     inherited from the base type if they are all zero in the subtype.

 -- C 成員函數: inquiry PyTypeObject.tp_clear

     An optional pointer to a clear function for the garbage collector.
     This is only used if the *note Py_TPFLAGS_HAVE_GC: 3d68. flag bit
     is set.  The signature is:

          int tp_clear(PyObject *);

     The *note tp_clear: 3d72. member function is used to break
     reference cycles in cyclic garbage detected by the garbage
     collector.  Taken together, all *note tp_clear: 3d72. functions in
     the system must combine to break all reference cycles.  This is
     subtle, and if in any doubt supply a *note tp_clear: 3d72.
     function.  For example, the tuple type does not implement a *note
     tp_clear: 3d72. function, because it’s possible to prove that no
     reference cycle can be composed entirely of tuples.  Therefore the
     *note tp_clear: 3d72. 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
     *note tp_clear: 3d72.

     Implementations of *note tp_clear: 3d72. should drop the instance’s
     references to those of its members that may be Python objects, and
     set its pointers to those members to ‘NULL’, as in the following
     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;
          }

     The *note Py_CLEAR(): 3d67. 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 ‘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
     `self' again, it’s important that the pointer to the contained
     object be ‘NULL’ at that time, so that `self' knows the contained
     object can no longer be used.  The *note Py_CLEAR(): 3d67. macro
     performs the operations in a safe order.

     Note that *note tp_clear: 3d72. is not `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 *note tp_dealloc: 3d5a. is
     called directly.

     Because the goal of *note tp_clear: 3d72. 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 *note
     tp_dealloc: 3d5a. function to invoke *note tp_clear: 3d72.

     More information about Python’s garbage collection scheme can be
     found in section *note 使对象类型支持循环垃圾回收: 42ce.

     `Inheritance:'

     Group: *note Py_TPFLAGS_HAVE_GC: 3d68, ‘tp_traverse’, ‘tp_clear’

     This field is inherited by subtypes together with *note
     tp_traverse: 23b. and the *note Py_TPFLAGS_HAVE_GC: 3d68. flag bit:
     the flag bit, *note tp_traverse: 23b, and *note tp_clear: 3d72. are
     all inherited from the base type if they are all zero in the
     subtype.

 -- C 成員函數: richcmpfunc PyTypeObject.tp_richcompare

     An optional pointer to the rich comparison function, whose
     signature is:

          PyObject *tp_richcompare(PyObject *self, PyObject *other, int op);

     The first parameter is guaranteed to be an instance of the type
     that is defined by *note PyTypeObject: 3f5.

     The function should return the result of the comparison (usually
     ‘Py_True’ or ‘Py_False’).  If the comparison is undefined, it must
     return ‘Py_NotImplemented’, if another error occurred it must
     return ‘NULL’ and set an exception condition.

     The following constants are defined to be used as the third
     argument for *note tp_richcompare: 3d7f. and for *note
     PyObject_RichCompare(): 3d80.:

     常数                 对照
                          
     --------------------------------------
                          
     ‘Py_LT’              ‘<’
                          
                          
     ‘Py_LE’              ‘<=’
                          
                          
     ‘Py_EQ’              ‘==’
                          
                          
     ‘Py_NE’              ‘!=’
                          
                          
     ‘Py_GT’              ‘>’
                          
                          
     ‘Py_GE’              ‘>=’
                          

     定义以下宏是为了简化编写丰富的比较函数：

      -- C 巨集: Py_RETURN_RICHCOMPARE (VAL_A, VAL_B, op)

          Return ‘Py_True’ or ‘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 *note PyObject_RichCompare(): 3d80.

          The return value’s reference count is properly incremented.

          On error, sets an exception and returns ‘NULL’ from the
          function.

          3.7 版新加入.

     `Inheritance:'

     Group: ‘tp_hash’, ‘tp_richcompare’

     This field is inherited by subtypes together with *note tp_hash:
     3d85.: a subtype inherits *note tp_richcompare: 3d7f. and *note
     tp_hash: 3d85. when the subtype’s *note tp_richcompare: 3d7f. and
     *note tp_hash: 3d85. are both ‘NULL’.

     `Default:'

     ‘PyBaseObject_Type’ provides a ‘tp_richcompare’ implementation,
     which may be inherited.  However, if only ‘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.

 -- 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 ‘PyObject_ClearWeakRefs()’ and
     the ‘PyWeakref_*()’ functions.  The instance structure needs to
     include a field of type *note PyObject*: 5b4. which is initialized
     to ‘NULL’.

     Do not confuse this field with *note tp_weaklist: 3f94.; that is
     the list head for weak references to the type object itself.

     `Inheritance:'

     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 *note
     tp_weaklistoffset: 26b, this should not be a problem.

     When a type defined by a class statement has no *note __slots__:
     eef. 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 *note tp_weaklistoffset: 26b. of that slot’s offset.

     When a type’s *note __slots__: eef. declaration contains a slot
     named ‘__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 *note tp_weaklistoffset: 26b.

     When a type’s *note __slots__: eef. declaration does not contain a
     slot named ‘__weakref__’, the type inherits its *note
     tp_weaklistoffset: 26b. from its base type.

 -- 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 *note PyObject_GetIter():
     3ed8.:

          PyObject *tp_iter(PyObject *self);

     `Inheritance:'

     This field is inherited by subtypes.

 -- C 成員函數: iternextfunc PyTypeObject.tp_iternext

     An optional pointer to a function that returns the next item in an
     iterator.  The signature is:

          PyObject *tp_iternext(PyObject *self);

     When the iterator is exhausted, it must return ‘NULL’; a *note
     StopIteration: 581. exception may or may not be set.  When another
     error occurs, it must return ‘NULL’ too.  Its presence signals that
     the instances of this type are iterators.

     Iterator types should also define the *note tp_iter: ef2. function,
     and that function should return the iterator instance itself (not a
     new iterator instance).

     This function has the same signature as *note PyIter_Next(): 3f39.

     `Inheritance:'

     This field is inherited by subtypes.

 -- C 成員函數: struct PyMethodDef* PyTypeObject.tp_methods

     An optional pointer to a static ‘NULL’-terminated array of *note
     PyMethodDef: edd. structures, declaring regular methods of this
     type.

     For each entry in the array, an entry is added to the type’s
     dictionary (see *note tp_dict: 3f90. below) containing a method
     descriptor.

     `Inheritance:'

     This field is not inherited by subtypes (methods are inherited
     through a different mechanism).

 -- C 成員函數: struct PyMemberDef* PyTypeObject.tp_members

     An optional pointer to a static ‘NULL’-terminated array of *note
     PyMemberDef: 529. 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 *note tp_dict: 3f90. below) containing a member
     descriptor.

     `Inheritance:'

     This field is not inherited by subtypes (members are inherited
     through a different mechanism).

 -- C 成員函數: struct PyGetSetDef* PyTypeObject.tp_getset

     An optional pointer to a static ‘NULL’-terminated array of *note
     PyGetSetDef: 52a. 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 *note tp_dict: 3f90. below) containing a getset
     descriptor.

     `Inheritance:'

     This field is not inherited by subtypes (computed attributes are
     inherited through a different mechanism).

 -- 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.

          備註: 
          Slot initialization is subject to the rules of initializing
          globals.  C99 requires the initializers to be "address
          constants".  Function designators like *note
          PyType_GenericNew(): 3d58, with implicit conversion to a
          pointer, are valid C99 address constants.

          However, the unary ’&’ operator applied to a non-static
          variable like ‘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, *note tp_base: 3d6a. should be set in the
          extension module’s init function.

     `Inheritance:'

     This field is not inherited by subtypes (obviously).

     `Default:'

     This field defaults to ‘&PyBaseObject_Type’ (which to Python
     programmers is known as the type *note object: 3d2.).

 -- C 成員函數: PyObject* PyTypeObject.tp_dict

     The type’s dictionary is stored here by *note PyType_Ready(): 3d5d.

     This field should normally be initialized to ‘NULL’ before
     PyType_Ready is called; it may also be initialized to a dictionary
     containing initial attributes for the type.  Once *note
     PyType_Ready(): 3d5d. 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 *note __add__(): 1595.).

     `Inheritance:'

     This field is not inherited by subtypes (though the attributes
     defined in here are inherited through a different mechanism).

     `Default:'

     If this field is ‘NULL’, *note PyType_Ready(): 3d5d. will assign a
     new dictionary to it.

          警告: It is not safe to use *note PyDict_SetItem(): 3d40. on
          or otherwise modify *note tp_dict: 3f90. with the dictionary
          C-API.

 -- C 成員函數: descrgetfunc PyTypeObject.tp_descr_get

     An optional pointer to a "descriptor get" function.

     The function signature is:

          PyObject * tp_descr_get(PyObject *self, PyObject *obj, PyObject *type);

     `Inheritance:'

     This field is inherited by subtypes.

 -- C 成員函數: descrsetfunc PyTypeObject.tp_descr_set

     An optional pointer to a function for setting and deleting a
     descriptor’s value.

     The function signature is:

          int tp_descr_set(PyObject *self, PyObject *obj, PyObject *value);

     The `value' argument is set to ‘NULL’ to delete the value.

     `Inheritance:'

     This field is inherited by subtypes.

 -- 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 *note PyObject_GenericGetAttr(): 3ec6.

     Do not confuse this field with *note tp_dict: 3f90.; 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 `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 *note str: 205. or *note tuple:
     1a2.  Note that the *note tp_basicsize: 26a. 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, *note tp_dictoffset: 3f97. should
     be set to ‘-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 *note tp_dictoffset: 3f97. as follows:

          dictoffset = tp_basicsize + abs(ob_size)*tp_itemsize + tp_dictoffset
          if dictoffset is not aligned on sizeof(void*):
              round up to sizeof(void*)

     where *note tp_basicsize: 26a, *note tp_itemsize: 3d54. and *note
     tp_dictoffset: 3f97. are taken from the type object, and ‘ob_size’
     is taken from the instance.  The absolute value is taken because
     ints use the sign of ‘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 ‘_PyObject_GetDictPtr()’.)

     `Inheritance:'

     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 *note
     tp_dictoffset: 3f97, this should not be a problem.

     When a type defined by a class statement has no *note __slots__:
     eef. declaration, and none of its base types has an instance
     variable dictionary, a dictionary slot is added to the instance
     layout and the *note tp_dictoffset: 3f97. is set to that slot’s
     offset.

     When a type defined by a class statement has a *note __slots__:
     eef. declaration, the type inherits its *note tp_dictoffset: 3f97.
     from its base type.

     (Adding a slot named *note __dict__: 5f5. to the *note __slots__:
     eef. declaration does not have the expected effect, it just causes
     confusion.  Maybe this should be added as a feature just like
     ‘__weakref__’ though.)

     `Default:'

     This slot has no default.  For static types, if the field is ‘NULL’
     then no *note __dict__: 5f5. gets created for instances.

 -- C 成員函數: initproc PyTypeObject.tp_init

     An optional pointer to an instance initialization function.

     This function corresponds to the *note __init__(): e23. method of
     classes.  Like *note __init__(): e23, it is possible to create an
     instance without calling *note __init__(): e23, and it is possible
     to reinitialize an instance by calling its *note __init__(): e23.
     method again.

     The function signature is:

          int tp_init(PyObject *self, PyObject *args, PyObject *kwds);

     The self argument is the instance to be initialized; the `args' and
     `kwds' arguments represent positional and keyword arguments of the
     call to *note __init__(): e23.

     The *note tp_init: 3d5e. function, if not ‘NULL’, is called when an
     instance is created normally by calling its type, after the type’s
     *note tp_new: 3d57. function has returned an instance of the type.
     If the *note tp_new: 3d57. function returns an instance of some
     other type that is not a subtype of the original type, no *note
     tp_init: 3d5e. function is called; if *note tp_new: 3d57. returns
     an instance of a subtype of the original type, the subtype’s *note
     tp_init: 3d5e. is called.

     Returns ‘0’ on success, ‘-1’ and sets an exception on error.

     `Inheritance:'

     This field is inherited by subtypes.

     `Default:'

     For static types this field does not have a default.

 -- C 成員函數: allocfunc PyTypeObject.tp_alloc

     An optional pointer to an instance allocation function.

     The function signature is:

          PyObject *tp_alloc(PyTypeObject *self, Py_ssize_t nitems);

     `Inheritance:'

     This field is inherited by static subtypes, but not by dynamic
     subtypes (subtypes created by a class statement).

     `Default:'

     For dynamic subtypes, this field is always set to *note
     PyType_GenericAlloc(): 399, to force a standard heap allocation
     strategy.

     For static subtypes, ‘PyBaseObject_Type’ uses *note
     PyType_GenericAlloc(): 399.  That is the recommended value for all
     statically defined types.

 -- C 成員函數: newfunc PyTypeObject.tp_new

     An optional pointer to an instance creation function.

     The function signature is:

          PyObject *tp_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds);

     The `subtype' argument is the type of the object being created; the
     `args' and `kwds' arguments represent positional and keyword
     arguments of the call to the type.  Note that `subtype' doesn’t
     have to equal the type whose *note tp_new: 3d57. function is
     called; it may be a subtype of that type (but not an unrelated
     type).

     The *note tp_new: 3d57. function should call
     ‘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 *note tp_init: 3d5e. handler.  A
     good rule of thumb is that for immutable types, all initialization
     should take place in *note tp_new: 3d57, while for mutable types,
     most initialization should be deferred to *note tp_init: 3d5e.

     `Inheritance:'

     This field is inherited by subtypes, except it is not inherited by
     static types whose *note tp_base: 3d6a. is ‘NULL’ or
     ‘&PyBaseObject_Type’.

     `Default:'

     For static types this field has no default.  This means if the slot
     is defined as ‘NULL’, the type cannot be called to create new
     instances; presumably there is some other way to create instances,
     like a factory function.

 -- C 成員函數: freefunc PyTypeObject.tp_free

     An optional pointer to an instance deallocation function.  Its
     signature is:

          void tp_free(void *self);

     An initializer that is compatible with this signature is *note
     PyObject_Free(): 5fd.

     `Inheritance:'

     This field is inherited by static subtypes, but not by dynamic
     subtypes (subtypes created by a class statement)

     `Default:'

     In dynamic subtypes, this field is set to a deallocator suitable to
     match *note PyType_GenericAlloc(): 399. and the value of the *note
     Py_TPFLAGS_HAVE_GC: 3d68. flag bit.

     For static subtypes, ‘PyBaseObject_Type’ uses PyObject_Del.

 -- 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 *note tp_flags: 1011. field, and check the *note
     Py_TPFLAGS_HAVE_GC: 3d68. 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 ‘1’ for a collectible
     instance, and ‘0’ for a non-collectible instance.  The signature
     is:

          int tp_is_gc(PyObject *self);

     (The only example of this are types themselves.  The metatype,
     *note PyType_Type: 3f7d, defines this function to distinguish
     between statically and dynamically allocated types.)

     `Inheritance:'

     This field is inherited by subtypes.

     `Default:'

     This slot has no default.  If this field is ‘NULL’, *note
     Py_TPFLAGS_HAVE_GC: 3d68. is used as the functional equivalent.

 -- C 成員函數: PyObject* PyTypeObject.tp_bases

     Tuple of base types.

     This is set for types created by a class statement.  It should be
     ‘NULL’ for statically defined types.

     `Inheritance:'

     This field is not inherited.

 -- C 成員函數: PyObject* PyTypeObject.tp_mro

     Tuple containing the expanded set of base types, starting with the
     type itself and ending with *note object: 3d2, in Method Resolution
     Order.

     `Inheritance:'

     This field is not inherited; it is calculated fresh by *note
     PyType_Ready(): 3d5d.

 -- C 成員函數: PyObject* PyTypeObject.tp_cache

     Unused.  Internal use only.

     `Inheritance:'

     This field is not inherited.

 -- C 成員函數: PyObject* PyTypeObject.tp_subclasses

     List of weak references to subclasses.  Internal use only.

     `Inheritance:'

     This field is not inherited.

 -- C 成員函數: PyObject* PyTypeObject.tp_weaklist

     Weak reference list head, for weak references to this type object.
     Not inherited.  Internal use only.

     `Inheritance:'

     This field is not inherited.

 -- C 成員函數: destructor PyTypeObject.tp_del

     This field is deprecated.  Use *note tp_finalize: 3f6. instead.

 -- C 成員函數: unsigned int PyTypeObject.tp_version_tag

     Used to index into the method cache.  Internal use only.

     `Inheritance:'

     This field is not inherited.

 -- C 成員函數: destructor PyTypeObject.tp_finalize

     An optional pointer to an instance finalization function.  Its
     signature is:

          void tp_finalize(PyObject *self);

     If *note tp_finalize: 3f6. 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.

     *note tp_finalize: 3f6. should not mutate the current exception
     status; therefore, a recommended way to write a non-trivial
     finalizer is:

          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);
          }

     For this field to be taken into account (even through inheritance),
     you must also set the *note Py_TPFLAGS_HAVE_FINALIZE: 3f7. flags
     bit.

     `Inheritance:'

     This field is inherited by subtypes.

     3.4 版新加入.

     也參考
     ......

     "Safe object finalization" ( PEP 442(2))

 -- C 成員函數: vectorcallfunc PyTypeObject.tp_vectorcall

     Vectorcall function to use for calls of this type object.  In other
     words, it is used to implement *note vectorcall: 2b8. for
     ‘type.__call__’.  If ‘tp_vectorcall’ is ‘NULL’, the default call
     implementation using *note __new__: 974. and *note __init__: e23.
     is used.

     `Inheritance:'

     This field is never inherited.

     3.9 版新加入: (the field exists since 3.8 but it’s only used since
     3.9)

Also, note that, in a garbage collected Python, *note tp_dealloc: 3d5a.
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.

   ---------- Footnotes ----------

   (1) https://bugs.python.org/issue40217

   (2) https://www.python.org/dev/peps/pep-0442


File: python.info,  Node: Heap Types,  Prev: PyTypeObject Slots,  Up: Type 对象<2>

7.12.3.9 Heap Types
...................

Traditionally, types defined in C code are `static', that is, a static
*note PyTypeObject: 3f5. structure is defined directly in code and
initialized using *note PyType_Ready(): 3d5d.

This results in types that are limited relative to types defined in
Python:

   * Static types are limited to one base, i.e.  they cannot use
     multiple inheritance.

   * 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.

   * Static type objects are shared across *note sub-interpreters: 3e57,
     so they should not include any subinterpreter-specific state.

Also, since *note PyTypeObject: 3f5. is not part of the *note stable
ABI: 3dda, any extension modules using static types must be compiled for
a specific Python minor version.

An alternative to static types is `heap-allocated types', or `heap
types' for short, which correspond closely to classes created by
Python’s ‘class’ statement.

This is done by filling a *note PyType_Spec: 3f85. structure and calling
*note PyType_FromSpecWithBases(): 102d.


File: python.info,  Node: Number Object Structures,  Next: Mapping Object Structures,  Prev: Type 对象<2>,  Up: 对象实现支持

7.12.4 Number Object Structures
-------------------------------

 -- 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 *note 数字协议: 3ef3.
     section.

     Here is the structure definition:

          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;

          備註: 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 ‘Py_NotImplemented’, if
          another error occurred they must return ‘NULL’ and set an
          exception.

          備註: The ‘nb_reserved’ field should always be ‘NULL’.  It was
          previously called ‘nb_long’, and was renamed in Python 3.0.1.

 -- C 成員函數: binaryfunc PyNumberMethods.nb_add

 -- C 成員函數: binaryfunc PyNumberMethods.nb_subtract

 -- C 成員函數: binaryfunc PyNumberMethods.nb_multiply

 -- C 成員函數: binaryfunc PyNumberMethods.nb_remainder

 -- C 成員函數: binaryfunc PyNumberMethods.nb_divmod

 -- C 成員函數: ternaryfunc PyNumberMethods.nb_power

 -- C 成員函數: unaryfunc PyNumberMethods.nb_negative

 -- C 成員函數: unaryfunc PyNumberMethods.nb_positive

 -- C 成員函數: unaryfunc PyNumberMethods.nb_absolute

 -- C 成員函數: inquiry PyNumberMethods.nb_bool

 -- C 成員函數: unaryfunc PyNumberMethods.nb_invert

 -- C 成員函數: binaryfunc PyNumberMethods.nb_lshift

 -- C 成員函數: binaryfunc PyNumberMethods.nb_rshift

 -- C 成員函數: binaryfunc PyNumberMethods.nb_and

 -- C 成員函數: binaryfunc PyNumberMethods.nb_xor

 -- C 成員函數: binaryfunc PyNumberMethods.nb_or

 -- C 成員函數: unaryfunc PyNumberMethods.nb_int

 -- C 成員函數: void *PyNumberMethods.nb_reserved

 -- C 成員函數: unaryfunc PyNumberMethods.nb_float

 -- C 成員函數: binaryfunc PyNumberMethods.nb_inplace_add

 -- C 成員函數: binaryfunc PyNumberMethods.nb_inplace_subtract

 -- C 成員函數: binaryfunc PyNumberMethods.nb_inplace_multiply

 -- C 成員函數: binaryfunc PyNumberMethods.nb_inplace_remainder

 -- C 成員函數: ternaryfunc PyNumberMethods.nb_inplace_power

 -- C 成員函數: binaryfunc PyNumberMethods.nb_inplace_lshift

 -- C 成員函數: binaryfunc PyNumberMethods.nb_inplace_rshift

 -- C 成員函數: binaryfunc PyNumberMethods.nb_inplace_and

 -- C 成員函數: binaryfunc PyNumberMethods.nb_inplace_xor

 -- C 成員函數: binaryfunc PyNumberMethods.nb_inplace_or

 -- C 成員函數: binaryfunc PyNumberMethods.nb_floor_divide

 -- C 成員函數: binaryfunc PyNumberMethods.nb_true_divide

 -- C 成員函數: binaryfunc PyNumberMethods.nb_inplace_floor_divide

 -- C 成員函數: binaryfunc PyNumberMethods.nb_inplace_true_divide

 -- C 成員函數: unaryfunc PyNumberMethods.nb_index

 -- C 成員函數: binaryfunc PyNumberMethods.nb_matrix_multiply

 -- C 成員函數: binaryfunc PyNumberMethods.nb_inplace_matrix_multiply


File: python.info,  Node: Mapping Object Structures,  Next: Sequence Object Structures,  Prev: Number Object Structures,  Up: 对象实现支持

7.12.5 Mapping Object Structures
--------------------------------

 -- C 類型: PyMappingMethods

     This structure holds pointers to the functions which an object uses
     to implement the mapping protocol.  It has three members:

 -- C 成員函數: lenfunc PyMappingMethods.mp_length

     This function is used by *note PyMapping_Size(): 1186. and *note
     PyObject_Size(): 3ed4, and has the same signature.  This slot may
     be set to ‘NULL’ if the object has no defined length.

 -- C 成員函數: binaryfunc PyMappingMethods.mp_subscript

     This function is used by *note PyObject_GetItem(): 3dcb. and *note
     PySequence_GetSlice(): 3f1d, and has the same signature as
     ‘PyObject_GetItem()’.  This slot must be filled for the *note
     PyMapping_Check(): 3f2e. function to return ‘1’, it can be ‘NULL’
     otherwise.

 -- C 成員函數: objobjargproc PyMappingMethods.mp_ass_subscript

     This function is used by *note PyObject_SetItem(): 3dc9, *note
     PyObject_DelItem(): 3ed6, ‘PyObject_SetSlice()’ and
     ‘PyObject_DelSlice()’.  It has the same signature as
     ‘PyObject_SetItem()’, but `v' can also be set to ‘NULL’ to delete
     an item.  If this slot is ‘NULL’, the object does not support item
     assignment and deletion.


File: python.info,  Node: Sequence Object Structures,  Next: Buffer Object Structures,  Prev: Mapping Object Structures,  Up: 对象实现支持

7.12.6 Sequence Object Structures
---------------------------------

 -- C 類型: PySequenceMethods

     This structure holds pointers to the functions which an object uses
     to implement the sequence protocol.

 -- C 成員函數: lenfunc PySequenceMethods.sq_length

     This function is used by *note PySequence_Size(): 1182. and *note
     PyObject_Size(): 3ed4, and has the same signature.  It is also used
     for handling negative indices via the *note sq_item: 10bf. and the
     *note sq_ass_item: 42b3. slots.

 -- C 成員函數: binaryfunc PySequenceMethods.sq_concat

     This function is used by *note PySequence_Concat(): 3f19. and has
     the same signature.  It is also used by the ‘+’ operator, after
     trying the numeric addition via the *note nb_add: 3f8e. slot.

 -- C 成員函數: ssizeargfunc PySequenceMethods.sq_repeat

     This function is used by *note PySequence_Repeat(): 3f1a. and has
     the same signature.  It is also used by the ‘*’ operator, after
     trying numeric multiplication via the *note nb_multiply: 428b.
     slot.

 -- C 成員函數: ssizeargfunc PySequenceMethods.sq_item

     This function is used by *note PySequence_GetItem(): 1183. and has
     the same signature.  It is also used by *note PyObject_GetItem():
     3dcb, after trying the subscription via the *note mp_subscript:
     42ad. slot.  This slot must be filled for the *note
     PySequence_Check(): 3f17. function to return ‘1’, it can be ‘NULL’
     otherwise.

     Negative indexes are handled as follows: if the ‘sq_length’ slot is
     filled, it is called and the sequence length is used to compute a
     positive index which is passed to ‘sq_item’.  If ‘sq_length’ is
     ‘NULL’, the index is passed as is to the function.

 -- C 成員函數: ssizeobjargproc PySequenceMethods.sq_ass_item

     This function is used by *note PySequence_SetItem(): 1184. and has
     the same signature.  It is also used by *note PyObject_SetItem():
     3dc9. and *note PyObject_DelItem(): 3ed6, after trying the item
     assignment and deletion via the *note mp_ass_subscript: 42ae. slot.
     This slot may be left to ‘NULL’ if the object does not support item
     assignment and deletion.

 -- C 成員函數: objobjproc PySequenceMethods.sq_contains

     This function may be used by *note PySequence_Contains(): 3f21. and
     has the same signature.  This slot may be left to ‘NULL’, in this
     case ‘PySequence_Contains()’ simply traverses the sequence until it
     finds a match.

 -- C 成員函數: binaryfunc PySequenceMethods.sq_inplace_concat

     This function is used by *note PySequence_InPlaceConcat(): 3f1b.
     and has the same signature.  It should modify its first operand,
     and return it.  This slot may be left to ‘NULL’, in this case
     ‘PySequence_InPlaceConcat()’ will fall back to *note
     PySequence_Concat(): 3f19.  It is also used by the augmented
     assignment ‘+=’, after trying numeric in-place addition via the
     *note nb_inplace_add: 4288. slot.

 -- C 成員函數: ssizeargfunc PySequenceMethods.sq_inplace_repeat

     This function is used by *note PySequence_InPlaceRepeat(): 3f1c.
     and has the same signature.  It should modify its first operand,
     and return it.  This slot may be left to ‘NULL’, in this case
     ‘PySequence_InPlaceRepeat()’ will fall back to *note
     PySequence_Repeat(): 3f1a.  It is also used by the augmented
     assignment ‘*=’, after trying numeric in-place multiplication via
     the *note nb_inplace_multiply: 428c. slot.


File: python.info,  Node: Buffer Object Structures,  Next: Async Object Structures,  Prev: Sequence Object Structures,  Up: 对象实现支持

7.12.7 Buffer Object Structures
-------------------------------

 -- C 類型: PyBufferProcs

     This structure holds pointers to the functions required by the
     *note Buffer protocol: 171c.  The protocol defines how an exporter
     object can expose its internal data to consumer objects.

 -- C 成員函數: getbufferproc PyBufferProcs.bf_getbuffer

     The signature of this function is:

          int (PyObject *exporter, Py_buffer *view, int flags);

     Handle a request to `exporter' to fill in `view' as specified by
     `flags'.  Except for point (3), an implementation of this function
     MUST take these steps:

       1. Check if the request can be met.  If not, raise
          ‘PyExc_BufferError’, set ‘view->obj’ to ‘NULL’ and return
          ‘-1’.

       2. Fill in the requested fields.

       3. Increment an internal counter for the number of exports.

       4. Set ‘view->obj’ to `exporter' and increment ‘view->obj’.

       5. Return ‘0’.

     If `exporter' is part of a chain or tree of buffer providers, two
     main schemes can be used:

        * Re-export: Each member of the tree acts as the exporting
          object and sets ‘view->obj’ to a new reference to itself.

        * Redirect: The buffer request is redirected to the root object
          of the tree.  Here, ‘view->obj’ will be a new reference to the
          root object.

     The individual fields of `view' are described in section *note
     Buffer structure: 3f3d, the rules how an exporter must react to
     specific requests are in section *note Buffer request types: 3f51.

     All memory pointed to in the *note Py_buffer: bee. structure
     belongs to the exporter and must remain valid until there are no
     consumers left.  *note format: 3f4a, *note shape: 3f4c, *note
     strides: 3f41, *note suboffsets: 3f4e. and *note internal: 3f50.
     are read-only for the consumer.

     *note PyBuffer_FillInfo(): 3f44. provides an easy way of exposing a
     simple bytes buffer while dealing correctly with all request types.

     *note PyObject_GetBuffer(): deb. is the interface for the consumer
     that wraps this function.

 -- C 成員函數: releasebufferproc PyBufferProcs.bf_releasebuffer

     The signature of this function is:

          void (PyObject *exporter, Py_buffer *view);

     Handle a request to release the resources of the buffer.  If no
     resources need to be released, *note
     PyBufferProcs.bf_releasebuffer: 3e8e. may be ‘NULL’.  Otherwise, a
     standard implementation of this function will take these optional
     steps:

       1. Decrement an internal counter for the number of exports.

       2. If the counter is ‘0’, free all memory associated with `view'.

     The exporter MUST use the *note internal: 3f50. 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 `view' argument.

     This function MUST NOT decrement ‘view->obj’, since that is done
     automatically in *note PyBuffer_Release(): e19. (this scheme is
     useful for breaking reference cycles).

     *note PyBuffer_Release(): e19. is the interface for the consumer
     that wraps this function.


File: python.info,  Node: Async Object Structures,  Next: Slot Type typedefs,  Prev: Buffer Object Structures,  Up: 对象实现支持

7.12.8 Async Object Structures
------------------------------

3.5 版新加入.

 -- C 類型: PyAsyncMethods

     This structure holds pointers to the functions required to
     implement *note awaitable: 612. and *note asynchronous iterator:
     738. objects.

     Here is the structure definition:

          typedef struct {
              unaryfunc am_await;
              unaryfunc am_aiter;
              unaryfunc am_anext;
          } PyAsyncMethods;

 -- C 成員函數: unaryfunc PyAsyncMethods.am_await

     The signature of this function is:

          PyObject *am_await(PyObject *self);

     The returned object must be an iterator, i.e.  *note
     PyIter_Check(): 1149. must return ‘1’ for it.

     This slot may be set to ‘NULL’ if an object is not an *note
     awaitable: 612.

 -- C 成員函數: unaryfunc PyAsyncMethods.am_aiter

     The signature of this function is:

          PyObject *am_aiter(PyObject *self);

     Must return an *note awaitable: 612. object.  See *note
     __anext__(): 155f. for details.

     This slot may be set to ‘NULL’ if an object does not implement
     asynchronous iteration protocol.

 -- C 成員函數: unaryfunc PyAsyncMethods.am_anext

     The signature of this function is:

          PyObject *am_anext(PyObject *self);

     Must return an *note awaitable: 612. object.  See *note
     __anext__(): 155f. for details.  This slot may be set to ‘NULL’.


File: python.info,  Node: Slot Type typedefs,  Next: 例子<2>,  Prev: Async Object Structures,  Up: 对象实现支持

7.12.9 Slot Type typedefs
-------------------------

 -- C 類型: PyObject *(*allocfunc) (PyTypeObject *cls,
          Py_ssize_t 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 ‘ob_refcnt’ set to ‘1’ and ‘ob_type’
     set to the type argument.  If the type’s *note tp_itemsize: 3d54.
     is non-zero, the object’s ‘ob_size’ field should be initialized to
     `nitems' and the length of the allocated memory block should be
     ‘tp_basicsize + nitems*tp_itemsize’, rounded up to a multiple of
     ‘sizeof(void*)’; otherwise, `nitems' is not used and the length of
     the block should be *note tp_basicsize: 26a.

     This function should not do any other instance initialization, not
     even to allocate additional memory; that should be done by *note
     tp_new: 3d57.

 -- C 類型: void (*destructor) (PyObject *)

 -- C 類型: void (*freefunc) (void *)

     See *note tp_free: 3d5b.

 -- C 類型: PyObject *(*newfunc) (PyObject *, PyObject *, PyObject *)

     See *note tp_new: 3d57.

 -- C 類型: int (*initproc) (PyObject *, PyObject *, PyObject *)

     See *note tp_init: 3d5e.

 -- C 類型: PyObject *(*reprfunc) (PyObject *)

     See *note tp_repr: 3d74.

 -- C 類型: PyObject *(*getattrfunc) (PyObject *self, char *attr)

     Return the value of the named attribute for the object.

 -- C 類型: int (*setattrfunc) (PyObject *self, char *attr,
          PyObject *value)

     Set the value of the named attribute for the object.  The value
     argument is set to ‘NULL’ to delete the attribute.

 -- C 類型: PyObject *(*getattrofunc) (PyObject *self, PyObject *attr)

     Return the value of the named attribute for the object.

     See *note tp_getattro: 3d79.

 -- C 類型: int (*setattrofunc) (PyObject *self, PyObject *attr,
          PyObject *value)

     Set the value of the named attribute for the object.  The value
     argument is set to ‘NULL’ to delete the attribute.

     See *note tp_setattro: 3d7a.

 -- C 類型: PyObject *(*descrgetfunc) (PyObject *, PyObject *,
          PyObject *)

     See ‘tp_descrget’.

 -- C 類型: int (*descrsetfunc) (PyObject *, PyObject *, PyObject *)

     See ‘tp_descrset’.

 -- C 類型: Py_hash_t (*hashfunc) (PyObject *)

     See *note tp_hash: 3d85.

 -- C 類型: PyObject *(*richcmpfunc) (PyObject *, PyObject *, int)

     See *note tp_richcompare: 3d7f.

 -- C 類型: PyObject *(*getiterfunc) (PyObject *)

     See *note tp_iter: ef2.

 -- C 類型: PyObject *(*iternextfunc) (PyObject *)

     See *note tp_iternext: ef3.

 -- C 類型: Py_ssize_t (*lenfunc) (PyObject *)

 -- C 類型: int (*getbufferproc) (PyObject *, Py_buffer *, int)

 -- C 類型: void (*releasebufferproc) (PyObject *, Py_buffer *)

 -- C 類型: PyObject *(*unaryfunc) (PyObject *)

 -- C 類型: PyObject *(*binaryfunc) (PyObject *, PyObject *)

 -- C 類型: PyObject *(*ternaryfunc) (PyObject *, PyObject *,
          PyObject *)

 -- C 類型: PyObject *(*ssizeargfunc) (PyObject *, Py_ssize_t)

 -- C 類型: int (*ssizeobjargproc) (PyObject *, Py_ssize_t)

 -- C 類型: int (*objobjproc) (PyObject *, PyObject *)

 -- C 類型: int (*objobjargproc) (PyObject *, PyObject *, PyObject *)


File: python.info,  Node: 例子<2>,  Next: 使对象类型支持循环垃圾回收,  Prev: Slot Type typedefs,  Up: 对象实现支持

7.12.10 例子
------------

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 *note
自定义扩展类型：教程: 3d4e. and *note 定义扩展类型：已分类主题: 3d6e.

A basic static type:

     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 = "My objects",
         .tp_new = myobj_new,
         .tp_dealloc = (destructor)myobj_dealloc,
         .tp_repr = (reprfunc)myobj_repr,
     };

You may also find older code (especially in the CPython code base) with
a more verbose initializer:

     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 */
         "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 */
     };

A type that supports weakrefs, instance dicts, and hashing:

     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 = "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,
     };

A str subclass that cannot be subclassed and cannot be called to create
instances (e.g.  uses a separate factory func):

     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 = "my custom str",
         .tp_flags = Py_TPFLAGS_DEFAULT,
         .tp_new = NULL,
         .tp_repr = (reprfunc)myobj_repr,
     };

The simplest static type (with fixed-length instances):

     typedef struct {
         PyObject_HEAD
     } MyObject;

     static PyTypeObject MyObject_Type = {
         PyVarObject_HEAD_INIT(NULL, 0)
         .tp_name = "mymod.MyObject",
     };

The simplest static type (with variable-length instances):

     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 *),
     };


File: python.info,  Node: 使对象类型支持循环垃圾回收,  Prev: 例子<2>,  Up: 对象实现支持

7.12.11 使对象类型支持循环垃圾回收
----------------------------------

Python 对循环引用的垃圾检测与回收需要“容器”对象类型的支持，此类型的容器
对象中可能包含其它容器对象。不保存其它对象的引用的类型，或者只保存原子类
型（如数字或字符串）的引用的类型，不需要显式提供垃圾回收的支持。

若要创建一个容器类，类型对象的 *note tp_flags: 1011. 字段必须包含 *note
Py_TPFLAGS_HAVE_GC: 3d68. 并提供一个 *note tp_traverse: 23b. 处理的实现
。如果该类型的实例是可变的，还需要实现 *note tp_clear: 3d72. 。

 -- Data: Py_TPFLAGS_HAVE_GC

     设置了此标志位的类型的对象必须符合此处记录的规则。为方便起见，下文
     把这些对象称为容器对象。

容器类型的构造函数必须符合两个规则：

  1. 必须使用 *note PyObject_GC_New(): 3f3. 或 *note
     PyObject_GC_NewVar(): 3f4. 为这些对象分配内存。

  2. 初始化了所有可能包含其他容器的引用的字段后，它必须调用 *note
     PyObject_GC_Track(): f06. 。

同样的，对象的释放器必须符合两个类似的规则：

  1. 在引用其它容器的字段失效前，必须调用 *note PyObject_GC_UnTrack():
     f07. 。

  2. 必须使用 *note PyObject_GC_Del(): f05. 释放对象的内存。

          警告: 如果一个类型添加了 Py_TPFLAGS_HAVE_GC，则它 `必须' 实现
          至少一个 *note tp_traverse: 23b. 句柄或显式地使用来自其一个或
          多个子类的句柄。

          当调用 *note PyType_Ready(): 3d5d. 或者 API 中某些间接调用它的
          函数例如 *note PyType_FromSpecWithBases(): 102d. 或 *note
          PyType_FromSpec(): 23a. 时解释器就自动填充 *note tp_flags:
          1011, *note tp_traverse: 23b. 和 *note tp_clear: 3d72. 字段，
          如果该类型是继承自实现了垃圾回收器协议的类并且该子类 `没有' 包
          括 *note Py_TPFLAGS_HAVE_GC: 3d68. 旗标的话。

 -- C 函式: TYPE* PyObject_GC_New (TYPE, PyTypeObject *type)

     类似于 *note PyObject_New(): 268. ，适用于设置了 *note
     Py_TPFLAGS_HAVE_GC: 3d68. 标签的容器对象。

 -- C 函式: TYPE* PyObject_GC_NewVar (TYPE, PyTypeObject *type,
          Py_ssize_t size)

     类似于 *note PyObject_NewVar(): 269. ，适用于设置了 *note
     Py_TPFLAGS_HAVE_GC: 3d68. 标签的容器对象。

 -- C 函式: TYPE* PyObject_GC_Resize (TYPE, PyVarObject *op,
          Py_ssize_t newsize)

     为 *note PyObject_NewVar(): 269. 所分配对象重新调整大小。 返回调整
     大小后的对象或在失败时返回 ‘NULL’。 `op' 必须尚未被垃圾回收器追踪。

 -- C 函式: void PyObject_GC_Track (PyObject *op)

     把对象 `op' 加入到垃圾回收器跟踪的容器对象中。对象在被回收器跟踪时
     必须保持有效的，因为回收器可能在任何时候开始运行。在 *note
     tp_traverse: 23b. 处理前的所有字段变为有效后，必须调用此函数，通常
     在靠近构造函数末尾的位置。

 -- C 函式: int PyObject_IS_GC (PyObject *obj)

     如果对象实现了垃圾回收器协议则返回非零值，否则返回 0。

     如果此函数返回 0 则对象无法被垃圾回收器追踪。

 -- C 函式: int PyObject_GC_IsTracked (PyObject *op)

     如果 `op' 对象的类型实现了 GC 协议且 `op' 目前正被垃圾回收器追踪则
     返回 1， 否则返回 0。

     这类似于 Python 函数 *note gc.is_tracked(): d6b.。

     3.9 版新加入.

 -- C 函式: int PyObject_GC_IsFinalized (PyObject *op)

     如果 `op' 对象的类型实现了 GC 协议且 `op' 已经被垃圾回收器终结则返
     回 1， 否则返回 0。

     这类似于 Python 函数 *note gc.is_finalized(): 1a9.。

     3.9 版新加入.

 -- C 函式: void PyObject_GC_Del (void *op)

     释放对象的内存，该对象初始化时由 *note PyObject_GC_New(): 3f3. 或
     *note PyObject_GC_NewVar(): 3f4. 分配内存。

 -- C 函式: void PyObject_GC_UnTrack (void *op)

     从回收器跟踪的容器对象集合中移除 `op' 对象。 请注意可以在此对象上再
     次调用 *note PyObject_GC_Track(): f06. 以将其加回到被跟踪对象集合。
     释放器 (*note tp_dealloc: 3d5a. 句柄) 应当在 *note tp_traverse:
     23b. 句柄所使用的任何字段失效之前为对象调用此函数。

3.8 版更變: ‘_PyObject_GC_TRACK()’ 和 ‘_PyObject_GC_UNTRACK()’ 宏已从公
有 C API 中移除。

*note tp_traverse: 23b. 处理接收以下类型的函数形参。

 -- C 類型: int (*visitproc) (PyObject *object, void *arg)

     传给 *note tp_traverse: 23b. 处理的访问函数的类型。`object' 是容器
     中需要被遍历的一个对象，第三个形参对应于 *note tp_traverse: 23b. 处
     理的 `arg' 。Python核心使用多个访问者函数实现循环引用的垃圾检测，不
     需要用户自行实现访问者函数。

*note tp_traverse: 23b. 处理必须是以下类型：

 -- C 類型: int (*traverseproc) (PyObject *self, visitproc visit,
          void *arg)

     用于容器对象的遍历函数。 它的实现必须对 `self' 所直接包含的每个对象
     调用 `visit' 函数，`visit' 的形参为所包含对象和传给处理程序的 `arg'
     值。 `visit' 函数调用不可附带 ‘NULL’ 对象作为参数。 如果 `visit' 返
     回非零值，则该值应当被立即返回。

为了简化 *note tp_traverse: 23b. 处理的实现，Python提供了一个 *note
Py_VISIT(): 3d66. 宏。若要使用这个宏，必须把 *note tp_traverse: 23b. 的
参数命名为 `visit' 和 `arg' 。

 -- C 函式: void Py_VISIT (PyObject *o)

     如果 `o' 不为 ‘NULL’，则调用 `visit' 回调函数，附带参数 `o' 和
     `arg'。 如果 `visit' 返回一个非零值，则返回该值。 使用此宏之后，
     *note tp_traverse: 23b. 处理程序的形式如下:

          static int
          my_traverse(Noddy *self, visitproc visit, void *arg)
          {
              Py_VISIT(self->foo);
              Py_VISIT(self->bar);
              return 0;
          }

*note tp_clear: 3d72. 处理程序必须为 *note inquiry: 4272. 类型，如果对象
不可变则为 ‘NULL’。

 -- C 類型: int (*inquiry) (PyObject *self)

     丢弃产生循环引用的引用。不可变对象不需要声明此方法，因为他们不可能
     直接产生循环引用。需要注意的是，对象在调用此方法后必须仍是有效的（
     不能对引用只调用 *note Py_DECREF(): 38f. 方法）。当垃圾回收器检测到
     该对象在循环引用中时，此方法会被调用。


File: python.info,  Node: API 和 ABI 版本管理,  Prev: 对象实现支持,  Up: Python/C API 參考手冊

7.13 API 和 ABI 版本管理
========================

‘PY_VERSION_HEX’ 是Python的版本号的整数形式。

例如，如果 ‘PY_VERSION_HEX’ 被置为 ‘0x030401a2’, 其包含的版本信息可以通
过以下方式将其作为一个32位数字来处理：

     字节        位数（大端字节序）            意义
                                               
     -----------------------------------------------------------------------------------------------
                                               
     ‘1’         ‘1-8’                         ‘PY_MAJOR_VERSION’ （‘3.4.1a2’ 中的 ‘3’ ）
                                               
                                               
     ‘2’         ‘9-16’                        ‘PY_MINOR_VERSION’ （‘3.4.1a2’ 中的 ‘4’ ）
                                               
                                               
     ‘3’         ‘17-24’                       ‘PY_MICRO_VERSION’ （‘3.4.1a2’ 中的 ‘1’ ）
                                               
                                               
     ‘4’         ‘25-28’                       ‘PY_RELEASE_LEVEL’ (‘0xA’ 是 alpha版本, ‘0xB’ 是
                                               beta版本, ‘0xC’ 发布的候选版本并且 ‘0xF’ 是最终版
                                               本)，在这个例子中这个版本是alpha版本。
                                               
                                               
                 ‘29-32’                       ‘PY_RELEASE_SERIAL’ （ ‘3.4.1a2’ 中的 ‘2’ ，最终版
                                               本用0)
                                               

因此 ‘3.4.1a2’ 的16进制版本号是 ‘0x030401a2’ 。

所有提到的宏都定义在 Include/patchlevel.h(1)。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Include/patchlevel.h


File: python.info,  Node: 發布 Python 模組,  Next: 安裝 Python 模組,  Prev: Python/C API 參考手冊,  Up: Top

8 發布 Python 模組
******************


電子郵件: <distutils-sig@python.org>

作為一個普及的開源開發專案，Python 有一個活躍的支持社群，由其貢獻者及使
用者組成，而他們也讓他們的軟體可被其他 Python 開發者在開源授權條款下使用
。

這樣可以讓 Python 使用者們有效地共享和合作，並受益於其他人對常見（有時甚
至是罕見）的問題已經建立的解決方案，更可以在公開社群中潛在地貢獻他們自己
的解決方案。

這份指南涵蓋了上述過程中的發布部分。如果是要安裝其他的 Python 專案，請參
考*note 安裝 Python 模組: 8e3.指南。

     備註: 對於企業和其他機構的使用者，要注意到，許多組織對於使用和貢獻
     開源軟體都有自己的政策。在開始使用配備 Python 的發布及安裝工具時，
     請將那些政策納入考量。

* Menu:

* 關鍵術語::
* 開源授權與協同合作::
* 安裝工具::
* 閱讀 Python 封裝使用者指南::
* 我該如何...？: 我該如何 ？.


File: python.info,  Node: 關鍵術語,  Next: 開源授權與協同合作,  Up: 發布 Python 模組

8.1 關鍵術語
============

   * Python 套件索引 (Python Package Index)(1) 是開源授權套件的一個公共
     儲存庫，其中的套件皆可被其他 Python 使用者所使用。

   * Python 封裝管理站 (Python Packaging Authority)(2) 是一個由開發者和
     說明文件作者組成的團隊，負責維護及改進標準封裝工具，以及相關的元資
     料 (metadata) 和檔案格式標準。他們在 GitHub(3) 和 Bitbucket(4) 這兩
     個平台上維護各種工具、說明文件及問題追蹤系統。

   * *note distutils: 38. 是最早的建置和發布系統，於 1998 年首次被加入
     Python 標準函式庫。雖然直接使用 *note distutils: 38. 的方式已經被逐
     步淘汰，它仍然是現今封裝和發布的基礎結構根基，而且它不僅仍然是標準
     函式庫的一部分，它的名稱也以其他的方式存活著（例如：用於協調 Python
     封裝標準開發的郵寄清單就是以它命名）。

   * setuptools(5) 是 *note distutils: 38. 的一個（主要的）偶然出現的替
     代品，它於 2004 年首次被發布。相較於未修改的 *note distutils: 38. 工
     具，它最值得注意的新功能，是能夠宣告對其他套件的依賴性
     (dependency)。它目前被推薦為 *note distutils: 38. 的一個替代方案，
     因其更新較為頻繁，且能在各個廣泛的 Python 版本之間，為較新的封裝標
     準提供一致性的支援。

   * wheel(6)（在此文中）是一個將 ‘bdist_wheel’ 指令附加到 *note
     distutils: 38./setuptools(7) 的專案。這會產生一個跨平台的二進制封裝
     格式（稱為「wheels」或「wheel 檔案」，並於 PEP 427(8) 中被定義），
     它可讓 Python 函式庫，甚至那些包含二進制擴充的函式庫，可以在系統中
     被安裝，但不需要在本機進行建置。

   ---------- Footnotes ----------

   (1) https://pypi.org

   (2) https://www.pypa.io/

   (3) https://github.com/pypa

   (4) https://bitbucket.org/pypa/

   (5) https://setuptools.readthedocs.io/en/latest/

   (6) https://wheel.readthedocs.io/

   (7) https://setuptools.readthedocs.io/en/latest/

   (8) https://www.python.org/dev/peps/pep-0427


File: python.info,  Node: 開源授權與協同合作,  Next: 安裝工具,  Prev: 關鍵術語,  Up: 發布 Python 模組

8.2 開源授權與協同合作
======================

在世界上多數地方，軟體會自動受版權所保護。這代表著其他開發人員需要明確的
許可，才能複製、使用、修改和重新發布軟體。

開源授權是一種以相對一致的方式，明確地授予此類許可的方法，它允許開發人員
透過為各種問題提供免費可用的共通解決方案，來達到高效率的共享和協作。這使
得許多開發人員可以自由地將更多時間專注於處理他們在特定情況中遇到的相對獨
特的問題。

Python 所提供的發布工具，被設計為讓開發人員能夠以合理的直觀方式，對該公
用軟體庫回饋他們自己的貢獻，前提是他們願意這樣做。

同一個發布工具也可用於在組織內發布軟體，不論該軟體是否有作為開源軟體被發
布。


File: python.info,  Node: 安裝工具,  Next: 閱讀 Python 封裝使用者指南,  Prev: 開源授權與協同合作,  Up: 發布 Python 模組

8.3 安裝工具
============

標準函式庫並不包含那些支援現代 Python 封裝標準的建置工具，因為核心開發團
隊發現，提供始終可運作的標準工具是很重要的，即使它們是在舊版的 Python 上
運作。

當今被推薦的建置及發布工具，可以透過在命令列中呼叫 ‘pip’ 模組來安裝它們
：

     python -m pip install setuptools wheel twine

     備註: 對於 POSIX 使用者（包括 Mac OS X 和 Linux 使用者），這些教學
     皆假設有使用 *note virtual environment: 1446.。

     對於 Windows 使用者，這些教學皆假設在安裝 Python 時，「可調整系統
     PATH 環境變數」的選項已被選取。

Python 封裝使用者指南包含了關於當今推薦工具(1)的更多細節。

   ---------- Footnotes ----------

   (1) 
https://packaging.python.org/guides/tool-recommendations/#packaging-tool-recommendations


File: python.info,  Node: 閱讀 Python 封裝使用者指南,  Next: 我該如何 ？,  Prev: 安裝工具,  Up: 發布 Python 模組

8.4 閱讀 Python 封裝使用者指南
==============================

Python 封裝使用者指南涵蓋了關於建立和發布一個專案的各項關鍵步驟和元素：

   * 專案結構(1)

   * 專案建置與封裝(2)

   * 上傳專案至 Python 套件索引 (Python Package Index)(3)

   * .pypirc 檔案(4)

   ---------- Footnotes ----------

   (1) 
https://packaging.python.org/tutorials/packaging-projects/#packaging-python-projects

   (2) 
https://packaging.python.org/tutorials/packaging-projects/#creating-the-package-files

   (3) 
https://packaging.python.org/tutorials/packaging-projects/#uploading-the-distribution-archives

   (4) https://packaging.python.org/specifications/pypirc/


File: python.info,  Node: 我該如何 ？,  Prev: 閱讀 Python 封裝使用者指南,  Up: 發布 Python 模組

8.5 我該如何...？
=================

接下來是關於一些常見任務的快速解答或連結。

* Menu:

* ...為我的專案選擇一個名稱？: 為我的專案選擇一個名稱？.
* ...建立和發布二進制擴充？: 建立和發布二進制擴充？.


File: python.info,  Node: 為我的專案選擇一個名稱？,  Next: 建立和發布二進制擴充？,  Up: 我該如何 ？

8.5.1 ...為我的專案選擇一個名稱？
---------------------------------

這不是一個簡單的題目，但這裡有一些提示：

   * 檢查 Python 套件索引，看看該名稱是否已被使用

   * 檢查常用的代管網站，像是 GitHub、Bitbucket 等，看看是否已經有一個使
     用該名稱的專案

   * 檢查您正在考慮的名稱在網路搜尋中會出現的內容

   * 避免使用特別常見的單字，尤其是那些有多重含義的單字，因為它們會讓使
     用者在搜尋你的軟體時時很難找到它


File: python.info,  Node: 建立和發布二進制擴充？,  Prev: 為我的專案選擇一個名稱？,  Up: 我該如何 ？

8.5.2 ...建立和發布二進制擴充？
-------------------------------

實際上這是一個非常複雜的題目，因為有各式各樣的替代方案可使用，取決於您確
實想要達成的目標。更多的資訊和建議，請參閱 Python 封裝使用者指南。

也參考
......

Python 封裝使用者指南：二進制擴充(1)

   ---------- Footnotes ----------

   (1) https://packaging.python.org/guides/packaging-binary-extensions/


File: python.info,  Node: 安裝 Python 模組,  Next: Python 如何達成任務,  Prev: 發布 Python 模組,  Up: Top

9 安裝 Python 模組
******************


電子郵件: <distutils-sig@python.org>

作為一個普及的開源開發專案，Python 有一個活躍的支持社群，由其貢獻者及使
用者組成，而他們也讓他們的軟體可被其他 Python 開發者在開源授權條款下使用
。

這樣可以讓 Python 使用者們有效地共享和合作，並受益於其他人對常見（有時甚
至是罕見）的問題已經建立的解決方案，更可以在公用社群中潛在地貢獻他們自己
的解決方案。

這份指南涵蓋了上述過程中的安裝部分。如果是要建立及分享您自己的 Python 專
案，請參考*note 發布 Python 模組: 8e3.指南。

     備註: 對於企業和其他機構的使用者，要注意到，許多組織對於使用和貢獻
     開源軟體都有自己的政策。在開始使用配備 Python 的發布及安裝工具時，
     請將那些政策納入考量。

* Menu:

* 關鍵術語: 關鍵術語<2>.
* 基本用法::
* 我該如何...？: 我該如何 ？<2>.
* 常見的安裝問題::


File: python.info,  Node: 關鍵術語<2>,  Next: 基本用法,  Up: 安裝 Python 模組

9.1 關鍵術語
============

   * ‘pip’ 是首選的安裝程式。從 Python 3.4 開始，它被預設包含在 Python 二
     進制安裝程式中。

   * `virtual environment（虛擬環境）'是一種半隔離的 Python 環境，可以為
     某個特定應用程式安裝其所需的套件，而不用在整個系統上安裝它們。

   * ‘venv’ 是建立虛擬環境的標準工具，它從 Python 3.3 開始成為 Python 的
     一部分。從 Python 3.4 開始，它會預設地安裝 ‘pip’ 到所有被建立的虛擬
     環境。

   * ‘virtualenv’ 是 ‘venv’ 的一個第三方替代方案（及其前身）。它使虛擬環
     境可以在 Python 3.4 之前的版本被使用，那些版本要不是根本沒提供
     ‘venv’，就是無法自動安裝 ‘pip’ 到所建立的環境中。

   * Python 套件索引 (Python Package Index)(1) 是開源授權套件的一個公共
     儲存庫，其中的套件皆可被其他 Python 使用者所使用。

   * Python 封裝管理站 (Python Packaging Authority)(2) 是一個由開發者和
     說明文件作者組成的團隊，負責維護及改進標準封裝工具，以及相關的元資
     料 (metadata) 和檔案格式標準。他們在 GitHub(3) 和 Bitbucket(4) 這兩
     個平台上維護各種工具、說明文件及問題追蹤系統。

   * ‘distutils’ 是最早的建置和發布系統，於 1998 年首次被加入 Python 標
     準函式庫。雖然直接使用 ‘distutils’ 的方式已經被逐步淘汰，它仍然是現
     今封裝和發布的基礎結構根基，而且它不僅仍然是標準函式庫的一部分，它
     的名稱也以其他的方式存活著（例如：用於協調 Python 封裝標準開發的郵
     寄清單就是以它命名）。

3.5 版更變: 對於建立虛擬環境，現在推薦使用 ‘venv’。

也參考
......

Python 封裝使用者指南：建立和使用虛擬環境(5)

   ---------- Footnotes ----------

   (1) https://pypi.org

   (2) https://www.pypa.io/

   (3) https://github.com/pypa

   (4) https://bitbucket.org/pypa/

   (5) 
https://packaging.python.org/installing/#creating-virtual-environments


File: python.info,  Node: 基本用法,  Next: 我該如何 ？<2>,  Prev: 關鍵術語<2>,  Up: 安裝 Python 模組

9.2 基本用法
============

標準封裝工具皆是以能從命令列使用的方式被設計的。

以下指令將從 Python 套件索引安裝一個模組的最新版本及其依賴套件
(dependencies)：

     python -m pip install SomePackage

     備註: 對於 POSIX 使用者（包括 macOS 和 Linux 使用者），本指南中的範
     例皆假設有使用 *note virtual environment: 1446.。

     對於 Windows 使用者，本指南中的範例皆假設在安裝 Python 時，「可調整
     系統 PATH 環境變數」的選項已被選取。

在命令列中直接指定一個明確的或最小的版本也是可行的。當使用像是 ‘>’、‘<’
的比較運算子，或某些可被 shell 所解釋的其他特殊字元時，套件名稱與版本編
號應該要放在雙引號內：

     python -m pip install SomePackage==1.0.4    # specific version
     python -m pip install "SomePackage>=1.0.4"  # minimum version

通常，如果一個合適的模組已被安裝，嘗試再次安裝它將不會有任何效果。要升級
現有的模組就必須明確地請求：

     python -m pip install --upgrade SomePackage

關於 ‘pip’ 及其能力的更多資訊和資源，可以在 Python 封裝使用者指南(1)中找
到。

虛擬環境的建立是使用 *note venv: 12e. 模組來完成。要在一個已啟用的虛擬環
境中安裝套件，可使用前面展示的指令。

也參考
......

Python 封裝使用者指南：安裝 Python 發布套件(2)

   ---------- Footnotes ----------

   (1) https://packaging.python.org

   (2) https://packaging.python.org/installing/


File: python.info,  Node: 我該如何 ？<2>,  Next: 常見的安裝問題,  Prev: 基本用法,  Up: 安裝 Python 模組

9.3 我該如何...？
=================

接下來是關於一些常見任務的快速解答或連結。

* Menu:

* ...在 Python 3.4 之前的 Python 版本中安裝 pip？: 在 Python 3 4 之前的 Python 版本中安裝 pip？.
* ...只為目前的使用者安裝套件？: 只為目前的使用者安裝套件？.
* ...安裝科學的 Python 套件？: 安裝科學的 Python 套件？.
* ...平行安裝多個 Python 版本並使用它們？: 平行安裝多個 Python 版本並使用它們？.


File: python.info,  Node: 在 Python 3 4 之前的 Python 版本中安裝 pip？,  Next: 只為目前的使用者安裝套件？,  Up: 我該如何 ？<2>

9.3.1 ...在 Python 3.4 之前的 Python 版本中安裝 ‘pip’？
-------------------------------------------------------

Python 是從 Python 3.4 才開始綁定 ‘pip’ 的。對於更早的版本，‘pip’ 需要被
「自助安裝 (bootstrapped)」，請參考 Python 封裝使用者指南中的說明。

也參考
......

Python 封裝使用者指南：安裝套件的需求(1)

   ---------- Footnotes ----------

   (1) 
https://packaging.python.org/installing/#requirements-for-installing-packages


File: python.info,  Node: 只為目前的使用者安裝套件？,  Next: 安裝科學的 Python 套件？,  Prev: 在 Python 3 4 之前的 Python 版本中安裝 pip？,  Up: 我該如何 ？<2>

9.3.2 ...只為目前的使用者安裝套件？
-----------------------------------

把 ‘--user’ 選項傳給 ‘python -m pip install’，這樣將會只為目前使用者而非
系統的所有使用者安裝套件。


File: python.info,  Node: 安裝科學的 Python 套件？,  Next: 平行安裝多個 Python 版本並使用它們？,  Prev: 只為目前的使用者安裝套件？,  Up: 我該如何 ？<2>

9.3.3 ...安裝科學的 Python 套件？
---------------------------------

許多科學類 Python 套件都有複雜的二進制依賴套件，且目前不太容易直接使用
‘pip’ 安裝。目前為止，使用其他方法(1)而非嘗試用 ‘pip’ 來安裝它們，對使用
者來說通常會更簡單。

也參考
......

Python 封裝使用者指南：安裝科學套件(2)

   ---------- Footnotes ----------

   (1) https://packaging.python.org/science/

   (2) https://packaging.python.org/science/


File: python.info,  Node: 平行安裝多個 Python 版本並使用它們？,  Prev: 安裝科學的 Python 套件？,  Up: 我該如何 ？<2>

9.3.4 ...平行安裝多個 Python 版本並使用它們？
---------------------------------------------

在 Linux、macOS 以及其他 POSIX 系統中，使用帶有版本編號的 Python 指令並
結合 ‘-m’ 開關參數 (switch)，來運行 ‘pip’ 的適當副本：

     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

使用帶有合適版本編號的 ‘pip’ 指令，也是可行的。

在 Windows 中，使用 Python 啟動指令 ‘py’ 並結合 ‘-m’ 開關參數 (switch)：

     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


File: python.info,  Node: 常見的安裝問題,  Prev: 我該如何 ？<2>,  Up: 安裝 Python 模組

9.4 常見的安裝問題
==================

* Menu:

* 在 Linux 上安裝套件至系統 Python::
* 未安裝 pip::
* 安裝二進制擴充 (binary extension): 安裝二進制擴充 binary extension.


File: python.info,  Node: 在 Linux 上安裝套件至系統 Python,  Next: 未安裝 pip,  Up: 常見的安裝問題

9.4.1 在 Linux 上安裝套件至系統 Python
--------------------------------------

在 Linux 系統，Python 的某個安裝版本通常會被內含在 Linux 的發行版中。要
安裝套件到這個 Python 版本上需要系統的 root 權限，並且可能會干擾到系統套
件管理器的運作。如果其他系統組件非預期地以 ‘pip’ 被升級，也會干擾這些組
件的運作。

在這樣的系統上，以 ‘pip’ 安裝套件時，通常較好的方式是使用虛擬環境，或以
個別使用者安裝。


File: python.info,  Node: 未安裝 pip,  Next: 安裝二進制擴充 binary extension,  Prev: 在 Linux 上安裝套件至系統 Python,  Up: 常見的安裝問題

9.4.2 未安裝 pip
----------------

‘pip’ 沒有預設被安裝也是有可能的。一個潛在的解法是：

     python -m ensurepip --default-pip

這裡還有其他關於安裝 pip(1)的資源。

   ---------- Footnotes ----------

   (1) 
https://packaging.python.org/tutorials/installing-packages/#install-pip-setuptools-and-wheel


File: python.info,  Node: 安裝二進制擴充 binary extension,  Prev: 未安裝 pip,  Up: 常見的安裝問題

9.4.3 安裝二進制擴充 (binary extension)
---------------------------------------

Python 基本上相當倚賴以原始碼為基礎的發布方式，也會期望使用者在安裝過程
的某個階段，從原始碼來編譯擴充模組。

隨著引入對二進制 ‘wheel’ 格式的支援，以及透過 Python 套件索引能夠至少在
Windows 和 macOS 發布 wheel 檔案，這個問題預期將會逐漸消失，因為使用者將
能夠更頻繁地安裝預建置 (pre-built) 的擴充，而不再需要自己建置它們。

有一些解決方案，可用來安裝那些還無法以預建置的 ‘wheel’ 檔案被使用的科學
軟體(1)，這些方案也有助於取得其他的二進制擴充，且無需在本機對它們進行建
置。

也參考
......

Python 封裝使用者指南：二進制擴充(2)

   ---------- Footnotes ----------

   (1) https://packaging.python.org/science/

   (2) https://packaging.python.org/extensions/


File: python.info,  Node: Python 如何達成任務,  Next: Python 常見問題,  Prev: 安裝 Python 模組,  Up: Top

10 Python 如何達成任務
**********************

「Python 如何達成任務 (HOWTOs)」是一系列的說明文件，其內容會盡量完整地涵
蓋某些單一、特定的主題。以 Linux 說明文件專案的 HOWTO 系列為模範，本系列
的目標是提供比 Python 函式庫參考手冊更實用的說明文件。

目前有以下這些任務指南：

* Menu:

* Python 2 的程式碼移植到Python 3::
* 遷移延伸模組到 Python 3::
* 用 Python 进行 Curses 编程::
* 修飾器 HowTo 指南::
* 函式編程 HOWTO::
* 如何使用 Logging 模組::
* 日志操作手册::
* 如何使用正規表達式::
* 套接字编程指南::
* 如何排序::
* Unicode 指南::
* 如何使用urllib套件取得網路資源::
* Argparse 教學::
* ipaddress模組介紹::
* Argument Clinic How-To::
* 使用 DTrace 和 SystemTap 检测CPython::


File: python.info,  Node: Python 2 的程式碼移植到Python 3,  Next: 遷移延伸模組到 Python 3,  Up: Python 如何達成任務

10.1 Python 2 的程式碼移植到Python 3
====================================


作者: Brett Cannon

摘要
....

Python 3 是 Python 的未来，但 Python 2 仍处于活跃使用阶段，最好让您的项
目在两个主要版本的Python 上都可用。本指南旨在帮助您了解如何最好地同时支
持 Python 2 和 3。

如果您希望迁移扩展模块而不是纯 Python 代码，请参阅 *note 遷移延伸模組到
Python 3: d3f.。

如果你想了解核心 Python 开发者对于 Python 3 的出现有何看法，你可以阅读
Nick Coghlan 的 Python 3 Q & A(1) 或 Brett Cannon 的 为什么要有 Python
3(2).

关于迁移的帮助，你可以查看存档的 python-porting(3) 邮件列表。

* Menu:

* 簡短的說明::
* 詳細的::

   ---------- Footnotes ----------

   (1) 
https://ncoghlan-devs-python-notes.readthedocs.io/en/latest/python3/questions_and_answers.html

   (2) https://snarky.ca/why-python-3-exists

   (3) https://mail.python.org/pipermail/python-porting/


File: python.info,  Node: 簡短的說明,  Next: 詳細的,  Up: Python 2 的程式碼移植到Python 3

10.1.1 簡短的說明
-----------------

为了使你的项目与单源Python 2/3兼容，基本步骤如下:

  1. 只担心支持Python 2.7的问题

  2. 确保你有良好的测试覆盖率（可以用 coverage.py(1)；‘python -m pip
     install coverage’）。

  3. 瞭解Python 2 & 3的差異

  4. 使用 Futurize(2) (或Modernize(3)) 来更新你的代码 (例如‘‘python -m
     pip install future‘‘)。

  5. 使用 Pylint(4) 来帮助确保你在Python 3支持上不倒退(‘python -m pip
     install pylint’)

  6. 使用 caniusepython3(5) 来找出你的哪些依赖关系阻碍了你对 Python 3 的
     使用 (‘python -m pip install caniusepython3’)

  7. 一旦你的依赖性不再阻碍你，使用持续集成来确保你与 Python 2 和 3 保持
     兼容 (tox(6) 可以帮助对多个版本的 Python 进行测试；‘python -m pip
     install tox’)

  8. 考虑使用可选的静态类型检查，以确保你的类型用法在 Python 2 和 3 中都
     适用 (例如，使用 mypy(7) 来检查你在 Python 2 和 Python 3 中的类型；
     ‘python -m pip install mypy’)。

     備註: 注意：使用 ‘python -m pip install’ 来确保你发起调用的 ‘pip’ 就
     是当前使用的 Python 所安装的那一个，无论它是系统级的 ‘pip’ 还是安装
     在 *note 虚拟环境: 1443. 中的。

   ---------- Footnotes ----------

   (1) https://pypi.org/project/coverage

   (2) http://python-future.org/automatic_conversion.html

   (3) https://python-modernize.readthedocs.io/

   (4) https://pypi.org/project/pylint

   (5) https://pypi.org/project/caniusepython3

   (6) https://pypi.org/project/tox

   (7) http://mypy-lang.org/


File: python.info,  Node: 詳細的,  Prev: 簡短的說明,  Up: Python 2 的程式碼移植到Python 3

10.1.2 詳細的
-------------

同时支持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和更舊的版本.
* 确保你在你的‘‘setup.py‘‘文件中指定适当的版本支持: 确保你在你的``setup py``文件中指定适当的版本支持.
* 有好的測試覆蓋率::
* 瞭解Python 2 & 3的差異::
* 更新你的程式碼::
* 防止兼容性退步::
* 检查哪些依赖性会阻碍你的过渡::
* 更新你的‘‘setup.py‘‘文件以表示对Python 3的兼容: 更新你的``setup py``文件以表示对Python 3的兼容.
* 使用持续集成以保持兼容::
* 考虑使用可选的静态类型检查::


File: python.info,  Node: 向下支援Python 2 6和更舊的版本,  Next: 确保你在你的``setup py``文件中指定适当的版本支持,  Up: 詳細的

10.1.2.1 向下支援Python 2.6和更舊的版本
.......................................

虽然你可以让 Python 2.5 与 Python 3 一起工作，但如果你只需要与 Python
2.7 一起工作，那就会 `更加容易'。 如果放弃 Python 2.5 不是一种选择，那么
six(1) 项目可以帮助你同时支持 Python 2.5 和 3 (‘python -m pip install
six’)。 不过请注意，本 HOWTO 中列出的几乎所有项目都有可能会不再可用。

如果你能够跳过Python 2.5和更早的版本，那么对你的代码所做的必要修改应该看
起来和感觉上都是你已经习惯的Python代码。在最坏的情况下，你将不得不使用一
个函数而不是一个实例方法，或者不得不导入一个函数而不是使用一个内置的函数
，但除此之外，整体的转变应该不会让你感到陌生。

但你的目标应该是只支持 Python 2.7。Python 2.6 不再被免费支持，因此也就没
有得到错误修复。这意味着**你**必须解决你在Python 2.6上遇到的任何问题。本
HOWTO中提到的一些工具也不支持Python 2.6 (例如，Pylint(2))，随着时间的推
移，这将变得越来越普遍。如果你只支持你必须支持的Python版本，那么对你来说
会更容易。

   ---------- Footnotes ----------

   (1) https://pypi.org/project/six

   (2) https://pypi.org/project/pylint


File: python.info,  Node: 确保你在你的``setup py``文件中指定适当的版本支持,  Next: 有好的測試覆蓋率,  Prev: 向下支援Python 2 6和更舊的版本,  Up: 詳細的

10.1.2.2 确保你在你的‘‘setup.py‘‘文件中指定适当的版本支持
.........................................................

在你的‘‘setup.py‘‘文件中，你应该有适当的 trove classifier(1) 指定你支持
哪些版本的 Python。由于你的项目还不支持 Python 3，你至少应该指定
‘‘Programming Language :: Python :: 2 :: Only‘‘。理想情况下，你还应该指
定你所支持的Python的每个主要/次要版本，例如：‘Programming Language ::
Python :: 2.7’。.

   ---------- Footnotes ----------

   (1) https://pypi.org/classifiers


File: python.info,  Node: 有好的測試覆蓋率,  Next: 瞭解Python 2 & 3的差異,  Prev: 确保你在你的``setup py``文件中指定适当的版本支持,  Up: 詳細的

10.1.2.3 有好的測試覆蓋率
.........................

一旦你的代码支持了你希望的Python 2的最老版本，你将希望确保你的测试套件有
良好的覆盖率。一个好的经验法则是，如果你想对你的测试套件有足够的信心，在
让工具重写你的代码后出现的任何故障都是工具中的实际错误，而不是你的代码中
的错误。如果你想要一个目标数字，试着获得超过80%的覆盖率（如果你发现很难
获得好于90%的覆盖率，也不要感到遗憾）。如果你还没有一个测量测试覆盖率的
工具，那么推荐使用coverage.py(1)。

   ---------- Footnotes ----------

   (1) https://pypi.org/project/coverage


File: python.info,  Node: 瞭解Python 2 & 3的差異,  Next: 更新你的程式碼,  Prev: 有好的測試覆蓋率,  Up: 詳細的

10.1.2.4 瞭解Python 2 & 3的差異
...............................

一旦你的代码经过了很好的测试，你就可以开始把你的代码移植到 Python 3 上了
！ 但是为了充分了解你的代码将发生怎样的变化，以及你在编码时要注意什么，
你将会想要了解 Python 3 相比 Python 2 的变化。 通常来说，两个最好的方法
是阅读 Python 3 每个版本的 *note "What’s New": 153. 文档和 Porting to
Python 3(1) 书（在线免费版本）。还有一个来自 Python-Future 项目的便利
cheat sheet(2)。

   ---------- Footnotes ----------

   (1) http://python3porting.com/

   (2) http://python-future.org/compatible_idioms.html


File: python.info,  Node: 更新你的程式碼,  Next: 防止兼容性退步,  Prev: 瞭解Python 2 & 3的差異,  Up: 詳細的

10.1.2.5 更新你的程式碼
.......................

一旦你觉得你知道了 Python 3 与 Python 2 相比有什么不同，就是时候更新你的
代码了！ 你可以选择两种工具来自动移植你的代码: Futurize(1) 和
Modernize(2)。 你选择哪个工具将取决于你希望你的代码有多像 Python 3。
Futurize(3) 尽力使 Python 3 的习性和做法在 Python 2 中存在，例如，从
Python 3 中回传 ‘bytes’ 类型，这样你就可以在 Python 的主要版本之间实现语
义上的平等。 另一方面，Modernize(4) 更加保守，它针对的是 Python 2/3 的子
集，直接依靠 six(5) 来帮助提供兼容性。 由于 Python 3 是未来，最好考虑
Futurize，以开始适应 Python 3 所引入的、你还不习惯的任何新做法。

无论你选择哪种工具，它们都会更新你的代码，使之在Python 3下运行，同时与你
开始使用的Python 2版本保持兼容。根据你想要的保守程度，你可能想先在你的测
试套件上运行该工具，并目测差异以确保转换的准确性。在你转换了你的测试套件
并验证了所有的测试仍然如期通过后，你就可以转换你的应用程序代码了，因为你
知道任何测试失败都是转译的错误。

不幸的是，这些工具不能自动地使你的代码在Python 3下工作，因此有一些东西你
需要手动更新以获得对Python 3的完全支持（这些步骤在不同的工具中是必要的）
。阅读你选择使用的工具的文档，看看它默认修复了什么，以及它可以选择做什么
，以了解哪些将（不）为你修复，哪些你可能必须自己修复（例如，在
Modernize中使用‘‘io.open()‘‘覆写内置的‘‘open()‘‘函数默认是关闭的）。不过
幸运的是，只有几件需要注意的事情，可以说是大问题，如果不注意的话，可能很
难调试。

* Menu:

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

   ---------- Footnotes ----------

   (1) http://python-future.org/automatic_conversion.html

   (2) https://python-modernize.readthedocs.io/

   (3) http://python-future.org/automatic_conversion.html

   (4) https://python-modernize.readthedocs.io/

   (5) https://pypi.org/project/six


File: python.info,  Node: 除法,  Next: 文本与二进制数据,  Up: 更新你的程式碼

10.1.2.6 除法
.............

在Python 3中，‘5 / 2 == 2.5``而不是``2’；所有‘‘int‘‘数值之间的除法都会产
生一个‘‘float‘‘、这个变化实际上从2002年发布的Python 2.2开始就已经计划好
了。从那时起，我们就鼓励用户在所有使用‘‘/‘和’//‘运算符的文件中添加``from
__future__ import division’，或者在运行解释器时使用‘‘-Q‘‘标志。如果你没
有这样做，那么你需要检查你的代码并做两件事。

  1. 添加 ‘from __future__ import division’ 到你的文件。

  2. 根据需要更新任何除法运算符，要么使用 ‘//’ 来使用向下取整除法，要么
     继续使用 ‘/’ 并得到一个浮点数

之所以没有简单地将 ‘/’ 自动翻译成 ‘//’，是因为如果一个对象定义了一个
‘__truediv__’ 方法，但没有定义 ‘__floordiv__’，那么你的代码就会运行失败
（例如，一个用户定义的类用 ‘/’ 来表示一些操作，但没有用 ‘//’ 来表示同样
的事情或根本没有定义）。


File: python.info,  Node: 文本与二进制数据,  Next: 使用特征检测而不是版本检测,  Prev: 除法,  Up: 更新你的程式碼

10.1.2.7 文本与二进制数据
.........................

在Python 2中，你可以对文本和二进制数据都使用‘‘str‘‘类型。不幸的是，这两
个不同概念的融合可能会导致脆弱的代码，有时对任何一种数据都有效，有时则无
效。如果人们没有明确说明某种接受‘‘str‘‘东西可以接受文本或二进制数据，而
不是一种特定的类型，这也会导致API的混乱。这使情况变得复杂，特别是对于任
何支持多种语言的人来说，因为API在声称支持文本数据时不会显式支持
‘‘unicode‘‘。

为了使文本和二进制数据之间的区别更加清晰和明显，Python 3做了大多数在互联
网时代创建的语言所做的事情，使文本和二进制数据成为不能盲目混合在一起的不
同类型（Python早于互联网的广泛使用）。对于任何只处理文本或只处理二进制数
据的代码，这种分离并不构成问题。但是对于必须处理这两种数据的代码来说，这
确实意味着你现在可能必须关心你何时使用文本或二进制数据，这就是为什么这不
能完全自动化迁移。

首先，你需要决定哪些 API 接受文本，哪些接受二进制（由于保持代码工作的难
度，`强烈' 建议你不要设计同时接受两种数据的 API；如前所述，这很难做得好
）。在 Python 2 中，这意味着要确保处理文本的 API 能够与 ‘unicode’ 一起工
作，而处理二进制数据的 API 能够与 Python 3 中的 ‘bytes’ 类型一起工作（在
Python 2 中是 ‘str’ 的一个子集，在 Python 2 中作为 ‘bytes’ 类型的别名）
。通常最大的问题是意识到哪些方法同时存在于 Python 2 和 3 的哪些类型上 (对
于文本来说，Python 2 中是 ‘unicode’，Python 3 中是 ‘str’，对于二进制来说
，Python 2 中是 ‘str’/‘bytes’，Python 3 中是‘‘bytes‘‘)。 下表列出了每个
数据类型在 Python 2 和 3 中的 `独特' 的方法 (例如，‘decode()’ 方法在
Python 2 或 3 中的等价二进制数据类型上是可用的，但是它不能在 Python 2 和
3 之间被文本数据类型一致使用，因为 Python 3 中的 ‘str’ 没有这个方法)。 请
注意，从 Python 3.5 开始，‘__mod__’ 方法被添加到 bytes 类型中。

`文本数据'                   `二进制数据'
                             
                             
                             decode
                             
                             
encode

format

isdecimal

isnumeric

通过在你的代码边缘对二进制数据和文本进行编码和解码，可以使这种区分更容易
处理。这意味着，当你收到二进制数据的文本时，你应该立即对其进行解码。而如
果你的代码需要将文本作为二进制数据发送，那么就尽可能晚地对其进行编码。这
使得你的代码在内部只与文本打交道，从而不必再去跟踪你所处理的数据类型。

下一个问题是确保你知道你的代码中的字符串字头是代表文本还是二进制数据。你
应该给任何呈现二进制数据的字面符号添加一个‘‘b‘‘前缀。对于文本，你应该给
文本字面添加一个‘‘u‘‘前缀。（有一个 *note __future__: 0. 导入来强制所有
未指定的字头为Unicode，但实际使用情况表明它并不像给所有字头显式添加一个
‘‘b‘‘或‘‘u‘‘前缀那样有效）

作为这种二分法的一部分，你还需要小心打开文件。除非你一直在 Windows 上工
作，否则你有可能在打开二进制文件时没有一直费心地添加‘‘b‘‘模式 （例如，用
‘‘rb‘‘进行二进制读取）。 在 Python 3 下，二进制文件和文本文件显然是不同
的，而且是相互不兼容的；详见 *note io: a1. 模块。因此，你必须**决定**一
个文件是用于二进制访问（允许读取和/或写入二进制数据）还是文本访问（允许
读取和/或写入文本数据）。你还应该使用 *note io.open(): 74d. 来打开文件，
而不是内置的 *note open(): 16f. 函数，因为 *note io: a1. 模块从 Python 2
到 3 是一致的，而内置的 *note open(): 16f. 函数则不是 (在 Python 3 中它
实际上是 *note io.open(): 74d.)。不要理会使用 *note codecs.open(): 10c3.
的过时做法，因为这只是为了保持与 Python 2.5 的兼容性。

在Python 2和3中，‘str``和``bytes``的构造函数对相同的参数有不同的语义。在
Python 2中，传递一个整数给``bytes’，你将得到整数的字符串表示：‘bytes(3)
== '3'’。但是在Python 3中，一个整数参数传递给‘‘bytes‘‘将给你一个与指定的
整数一样长的bytes对象，其中充满了空字节：‘bytes(3) == b'\x00\x00\x00'’。
当把bytes对象传给‘‘str‘‘时，类似的担心是必要的。 在Python 2中，你只是又
得到了该bytes对象：‘str(b'3') == b'3'’。但是在Python 3中，你得到bytes对
象的字符串表示：‘str(b'3') == "b'3'"’。

最后，二进制数据的索引需要仔细处理（切片 `不需要' 任何特殊处理）。在
Python 2 中 ‘b'123'[1] == b'2'’，而在 Python 3 中‘‘b’123’[1] == 50‘‘。 因
为二进制数据只是二进制数的集合，Python 3 会返回你索引的字节的整数值。 但
是在 Python 2 中，因为 ‘bytes == str’，索引会返回一个单项的字节片断。
six(1) 项目有一个名为 ‘six.indexbytes()’ 的函数，它将像在 Python 3 中一
样返回一个整数: ‘six.indexbytes(b'123', 1)’。

总结一下：

  1. 决定你的API中哪些采用文本，哪些采用二进制数据

  2. 确保你对文本工作的代码也能对‘‘unicode‘‘工作，对二进制数据的代码在
     Python 2中能对‘‘bytes‘‘工作（关于每种类型不能使用的方法，见上表）。

  3. 用‘‘b‘‘前缀标记所有二进制字词，用‘‘u‘‘前缀标记文本字词

  4. 尽快将二进制数据解码为文本，尽可能晚地将文本编码为二进制数据

  5. 使用 *note io.open(): 74d. 打开文件，并确保在适当时候指定 ‘b’ 模式
     。

  6. 在对二进制数据进行索引时要小心

   ---------- Footnotes ----------

   (1) https://pypi.org/project/six


File: python.info,  Node: 使用特征检测而不是版本检测,  Prev: 文本与二进制数据,  Up: 更新你的程式碼

10.1.2.8 使用特征检测而不是版本检测
...................................

你不可避免地会有一些代码需要根据运行的 Python 版本来选择要做什么。做到这
一点的最好方法是对你运行的 Python 版本是否支持你所需要的东西进行特征检测
。如果由于某种原因这不起作用，那么你应该让版本检测针对 Python 2 而不是
Python 3。为了帮助解释这个问题，让我们看一个例子。

假设你需要访问 *note importlib: 9a. 的一个功能，该功能自Python 3.3开始在
Python的标准库中提供，并且通过PyPI上的 importlib2(1) 提供给Python 2。你
可能会想写代码来访问例如 *note importlib.abc: 9b. 模块，方法如下:

     import sys

     if sys.version_info[0] == 3:
         from importlib import abc
     else:
         from importlib2 import abc

这段代码的问题是，当Python 4出来的时候会发生什么？最好是将Python 2作为例
外情况，而不是Python 3，并假设未来的Python版本与Python 3的兼容性比Python
2更强:

     import sys

     if sys.version_info[0] > 2:
         from importlib import abc
     else:
         from importlib2 import abc

不过，最好的解决办法是根本不做版本检测，而是依靠特征检测。这就避免了任何
潜在的版本检测错误的问题，并有助于保持你对未来的兼容:

     try:
         from importlib import abc
     except ImportError:
         from importlib2 import abc

   ---------- Footnotes ----------

   (1) https://pypi.org/project/importlib2


File: python.info,  Node: 防止兼容性退步,  Next: 检查哪些依赖性会阻碍你的过渡,  Prev: 更新你的程式碼,  Up: 詳細的

10.1.2.9 防止兼容性退步
.......................

一旦你完全翻译了你的代码，使之与 Python 3 兼容，你将希望确保你的代码不会
退步，不会在 Python 3上停止工作。如果你有一个依赖关系阻碍了你目前在
Python 3上的实际运行，那就更是如此了。

为了帮助保持兼容，你创建的任何新模块都应该在其顶部至少有以下代码块:

     from __future__ import absolute_import
     from __future__ import division
     from __future__ import print_function

你也可以在运行Python 2时使用‘‘-3‘‘标志，对你的代码在执行过程中引发的各种
兼容性问题进行警告。如果你用‘‘-Werror‘‘把警告变成错误，那么你可以确保你
不会意外地错过一个警告。

你也可以使用 Pylint(1) 项目和它的‘‘–py3k‘‘标志来提示你的代码，当你的代码
开始偏离 Python 3 的兼容性时，就会收到警告。这也避免了你不得不定期在你的
代码上运行 Modernize(2) 或 Futurize(3) 来捕捉兼容性的退步。这确实要求你
只支持Python 2.7和Python 3.4或更新的版本，因为这是Pylint支持的最小
Python版本。

   ---------- Footnotes ----------

   (1) https://pypi.org/project/pylint

   (2) https://python-modernize.readthedocs.io/

   (3) http://python-future.org/automatic_conversion.html


File: python.info,  Node: 检查哪些依赖性会阻碍你的过渡,  Next: 更新你的``setup py``文件以表示对Python 3的兼容,  Prev: 防止兼容性退步,  Up: 詳細的

10.1.2.10 检查哪些依赖性会阻碍你的过渡
......................................

在你使你的代码与 Python 3 兼容**之后**，你应该开始关心你的依赖关系是否也
被移植了。 caniusepython3(1) 项目的建立是为了帮助你确定哪些项目——直接或
间接地——阻碍了你对Python 3的支持。它既有一个命令行工具，也有一个在
https://caniusepython3.com的网页界面。

该项目还提供了一些代码，你可以将其集成到你的测试套件中，这样，当你不再有
依赖关系阻碍你使用Python 3时，你将有一个失败的测试。这使你不必手动检查你
的依赖性，并在你可以开始在Python 3上运行时迅速得到通知。

   ---------- Footnotes ----------

   (1) https://pypi.org/project/caniusepython3


File: python.info,  Node: 更新你的``setup py``文件以表示对Python 3的兼容,  Next: 使用持续集成以保持兼容,  Prev: 检查哪些依赖性会阻碍你的过渡,  Up: 詳細的

10.1.2.11 更新你的‘‘setup.py‘‘文件以表示对Python 3的兼容
........................................................

一旦你的代码在 Python 3 下工作，你应该更新你‘‘setup.py‘‘中的分类器，使其
包含‘‘Programming Language :: Python :: 3‘‘并不指定单独的 Python 2 支持
。这将告诉使用你的代码的人，你支持Python 2 `和' 3。理想情况下，你也希望
为你现在支持的Python的每个主要/次要版本添加分类器。


File: python.info,  Node: 使用持续集成以保持兼容,  Next: 考虑使用可选的静态类型检查,  Prev: 更新你的``setup py``文件以表示对Python 3的兼容,  Up: 詳細的

10.1.2.12 使用持续集成以保持兼容
................................

一旦你能够完全在Python 3下运行，你将希望确保你的代码总是在Python 2和3下
工作。在多个Python解释器下运行测试的最好工具可能是 tox(1) 。然后你可以将
tox 与你的持续集成系统集成，这样你就不会意外地破坏对 Python 2 或 3 的支
持。

你可能还想在 Python 3 解释器中使用‘‘-bb‘‘标志，以便在你将bytes与string或
bytes与int进行比较时触发一个异常（后者从 Python 3.5 开始可用）。默认情况
下，类型不同的比较只是简单地返回‘‘False‘‘，但是如果你在文本/二进制数据处
理或字节的索引分离中犯了一个错误，你就不容易发现这个错误。当这些类型的比
较发生时，这个标志会触发一个异常，使错误更容易被发现。

基本上就是这样了! 在这一点上，你的代码库同时与 Python 2 和 3 兼容。你的
测试也将被设置为不会意外地破坏 Python 2 或 3 的兼容性，无论你在开发时通
常在哪个版本下运行测试。

   ---------- Footnotes ----------

   (1) https://pypi.org/project/tox


File: python.info,  Node: 考虑使用可选的静态类型检查,  Prev: 使用持续集成以保持兼容,  Up: 詳細的

10.1.2.13 考虑使用可选的静态类型检查
....................................

另一个帮助移植你的代码的方法是在你的代码上使用静态类型检查器，如 mypy(1)
或 pytype(2)。这些工具可以用来分析你的代码，就像它在Python 2下运行一样，
然后你可以第二次运行这个工具，就像你的代码在Python 3下运行一样。通过像这
样两次运行静态类型检查器，你可以发现你是否错误地使用了二进制数据类型，例
如在Python的一个版本中与另一个版本相比。如果你在你的代码中添加了可选的类
型提示，你也可以明确说明你的API是使用文本数据还是二进制数据，这有助于确
保在两个版本的Python中所有的功能都符合预期。

   ---------- Footnotes ----------

   (1) http://mypy-lang.org/

   (2) https://github.com/google/pytype


File: python.info,  Node: 遷移延伸模組到 Python 3,  Next: 用 Python 进行 Curses 编程,  Prev: Python 2 的程式碼移植到Python 3,  Up: Python 如何達成任務

10.2 遷移延伸模組到 Python 3
============================

对于将扩展模块移植到 Python 3，我们推荐下列资源：

   * `Supporting Python 3: An in-depth guide' 中的 Migrating C
     extensions(1) 这一章，这本书介绍了如何从 Python 2 迁移到 Python 3，
     包括指导读者如何移植扩展模块。

   * `py3c' 项目中的 Porting guide(2) 提供了有关支持代码的指导性建议。

   * Cython(3) 和 CFFI(4) 库提供了对于 Python 的 C API 的抽象。 扩展大都
     需要进行重写以使用两者中的一个，然后就可以通过库来处理各种 Python 版
     本和实现之间的差异。

   ---------- Footnotes ----------

   (1) http://python3porting.com/cextensions.html

   (2) https://py3c.readthedocs.io/en/latest/guide.html

   (3) http://cython.org/

   (4) https://cffi.readthedocs.io/en/latest/


File: python.info,  Node: 用 Python 进行 Curses 编程,  Next: 修飾器 HowTo 指南,  Prev: 遷移延伸模組到 Python 3,  Up: Python 如何達成任務

10.3 用 Python 进行 Curses 编程
===============================


作者: A.M. Kuchling, Eric S. Raymond


发布版本: 2.04

摘要
....

本文档介绍了如何使用 *note curses: 2b. 扩展模块控制文本模式的显示。

* Menu:

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


File: python.info,  Node: curses 是什么？,  Next: 开始和结束 curses 应用程序,  Up: 用 Python 进行 Curses 编程

10.3.1 curses 是什么？
----------------------

curses 库为基于文本的终端提供了独立于终端的屏幕绘制和键盘处理功能；这些
终端包括 VT100，Linux 控制台以及各种程序提供的模拟终端。显示终端支持各种
控制代码以执行常见的操作，例如移动光标，滚动屏幕和擦除区域。不同的终端使
用相差很大的代码，并且往往有自己的小怪癖。

在普遍使用图形显示的世界中，人们可能会问“为什么自找要麻烦”？毕竟字符单元
显示终端确实是一种过时的技术，但是在某些领域中，能够用它们做花哨的事情仍
然很有价值。一个小众市场是在不运行 X server 的小型或嵌入式 Unix 上。另一
个是在提供图形支持之前，可能需要运行的工具，例如操作系统安装程序和内核配
置程序。

curses 库提供了相当基础的功能，为程序员提供了包含多个非重叠文本窗口的显
示的抽象。窗口的内容可以通过多种方式更改—添加文本，擦除文本，更改其外观
—以及curses库将确定需要向终端发送哪些控制代码以产生正确的输出。 curses并
没有提供诸多用户界面概念，例如按钮，复选框或对话框。如果需要这些功能，请
考虑用户界面库，例如 Urwid(1) 。

curses 库最初是为BSD Unix 编写的。 后来 AT&T 的Unix System V 版本加入了
许多增强功能和新功能。如今BSD curses已不再维护，被ncurses取代，ncurses是
AT&T 接口的开源实现。如果使用的是 Linux 或 FreeBSD 等开源Unix系统，则几
乎肯定会使用ncurses。由于大多数当前的商业Unix版本都基于System V代码，因
此这里描述的所有功能可能都可用。但是，某些专有Unix所带来的较早版本的
curses可能无法支持所有功能。

Windows 版本的 Python 不包含 *note curses: 2b. 模块。提供了一个名为
UniCurses(2) 的移植版本。也可以尝试使用 Fredrik Lundh 编写 the Console
module(3)，它使用了与curses不相同的API，但提供了可光标定位的文本输出，完
全支持鼠标和键盘输入。

* Menu:

* Python 的 curses 模块::

   ---------- Footnotes ----------

   (1) https://pypi.org/project/urwid/

   (2) https://pypi.org/project/UniCurses

   (3) http://effbot.org/zone/console-index.htm


File: python.info,  Node: Python 的 curses 模块,  Up: curses 是什么？

10.3.1.1 Python 的 curses 模块
..............................

此 Python 模块相当简单地封装了 curses 提供的 C 函数；如果你已经熟悉在 C
语言中使用 curses 编程，把这些知识转移的 Python 是非常容易的。最大的差异
在于 Python 中的接口通过把不同的 C 函数合并来让事情变得更简单，比如
‘addstr()’、‘mvaddstr()’ 和 ‘mvwaddstr()’ 三个 C 函数被并入 *note
addstr(): 22c0. 这一个方法。下文中会描述更多的细节。

本 HOWTO 是关于使用 curses 和 Python 编写文本模式程序的概述。它并不被设
计为一个 curses API 的完整指南；如需完整指南，请参见 ncurses 的 Python 库
指南章节和 ncurses 的 C 手册页。相对地，本 HOWTO 将会给你一些基本思路。


File: python.info,  Node: 开始和结束 curses 应用程序,  Next: 窗口和面板,  Prev: curses 是什么？,  Up: 用 Python 进行 Curses 编程

10.3.2 开始和结束 curses 应用程序
---------------------------------

在做任何事情之前，curses 必须先被初始化。可以通过调用函数 *note
initscr(): 22c7. 来实现，它将查明终端的类型，向终端发送任何必须的设置代
码，并创建多种内部数据结构。如果此操作成功，‘initscr()’ 将会返回一个代表
整个屏幕的窗口对象；它通常会遵循对应的 C 变量名被称作 ‘stdscr’：

     import curses
     stdscr = curses.initscr()

使用 curses 的应用程序通常会关闭按键自动上屏，目的是读取按键并只在特定情
况下展示它们。这需要调用函数 *note noecho(): 22e6.：

     curses.noecho()

应用程序也会广泛地需要立即响应按键，而不需要按下回车键；这被称为
“cbreak” 模式，与通常的缓冲输入模式相对：

     curses.cbreak()

终端通常会以多字节转义序列的形式返回特殊按键，比如光标键和导航键比如
Page Up 键和 Home 键。尽管你可以编写你的程序来应对这些序列，curses 能够
代替你做到这件事，返回一个特殊值比如 ‘curses.KEY_LEFT’。为了让 curses 做
这项工作，你需要启用 keypad 模式：

     stdscr.keypad(True)

终止一个 curses 应用程序比建立一个容易得多，你只需要调用：

     curses.nocbreak()
     stdscr.keypad(False)
     curses.echo()

来还原对终端作出的 curses 友好设置。然后，调用函数 *note endwin(): 22c4.
来将终端还原到它的原始操作模式：

     curses.endwin()

调试一个 curses 应用程序时常会发生，一个应用程序还未能还原终端到原本的状
态就意外退出了，这会搅乱你的终端。在 Python 中这常常会发生在你的代码中有
bug 并引发了一个未捕获的异常。当你尝试输入时按键不会上屏，这使得使用终端
变得困难。

在 Python 中你可以避免这些复杂问题并让调试变得更简单，只需要导入 *note
curses.wrapper(): 3c4. 函数并像这样使用它：

     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)

函数 *note wrapper(): 3c4. 接受一个可调用对象并首先进行上述初始化过程，
在终端支持着色时还会初始化颜色。接着 ‘wrapper()’ 运行你提供的可调用对象
。当该可调用对象返回时，‘wrapper()’ 会还原终端到初始状态。该可调用对象会
在 *note try: e37...*note except: c10. 这样的结构内被调用，当它捕获到异
常时，会先还原终端再重新引发这个异常。所以你的终端不会因为异常而被留在一
个搞笑的状态，你也可以正常阅读异常消息和回溯信息。


File: python.info,  Node: 窗口和面板,  Next: 显示文字,  Prev: 开始和结束 curses 应用程序,  Up: 用 Python 进行 Curses 编程

10.3.3 窗口和面板
-----------------

窗口是 curses 中的基本抽象。一个窗口对象表示了屏幕上的一个矩形区域，并且
提供方法来显示文本、擦除文本、允许用户输入字符串等等。

函数 *note initscr(): 22c7. 返回的 ‘stdscr’ 对象覆盖整个屏幕。许多程序可
能只需要这一个窗口，但你可能希望把屏幕分割为多个更小的窗口，来分别重绘或
者清除它们。函数 *note newwin(): 22e4. 根据给定的尺寸创建一个新窗口，并
返回这个新的窗口对象：

     begin_x = 20; begin_y = 7
     height = 5; width = 40
     win = curses.newwin(height, width, begin_y, begin_x)

注意 curses 使用的坐标系统与寻常的不同。坐标始终是以 `y,x' 的顺序传递，
并且左上角是坐标 (0,0)。这打破了正常的坐标处理约定，即 `x' 坐标在前。这
是一个与其他计算机应用程序糟糕的差异，但这从 curses 最初被编写出来就已是
它的一部分，现在想要修改它已为时已晚。

你的应用程序能够查明屏幕的尺寸，‘curses.LINES’ 和 ‘curses.COLS’ 分别代表
了 `y' 和 `x' 方向上的尺寸。合理的坐标应位于 ‘(0,0)’ 到 ‘(curses.LINES -
1, curses.COLS - 1)’ 范围内。

当你调用一个方法来显示或擦除文本时，效果并不会立即显示。相反，你必须调用
窗口对象的 *note refresh(): 22c2. 方法来更新屏幕。

这是因为 curses 最初是为 300 波特的龟速终端连接编写的；在这些终端上，压
制重绘屏幕的时间就非常重要。相对地，当你调用 ‘refresh()’ 时，curses 会累
积屏幕的修改并以效率最高的方式显示它们。打个比方，如果你的程序在一个窗口
内显示一些文本然后清楚了这个窗口，那么这些原始文本不需要被发送，因为它们
甚至不曾能被看见。

在实践中，显式地告诉 curses 来重绘一个窗口并不会太复杂化 curses 编程。大
部分程序会显示一堆内容然后等待按键或者其他某些用户侧动作。你要做的事情就
是，保证屏幕在暂停并等待用户输入前被重绘，只需要先调用
‘stdscr.refresh()’ 或者其他相关窗口的 ‘refresh()’ 方法。

一个面板是一种特殊的窗口，它可以比实际的显示屏幕更大，并且能只显示它的一
部分。创建面板需要指定面板的高度和宽度，但刷新一个面板需要给出屏幕坐标和
面板的需要显示的局部。

     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)

此 ‘refresh()’ 调用会在屏幕坐标 (5,5) 到坐标 (20,75) 的矩形范围内显示面
板的一个部分，被显示的部分在面板上的坐标是 (0,0)。除了上述差异，面板与常
规的窗口相同，也支持相同的方法。

如果你在屏幕上有多个窗口和面板，有一个更有效率的方法来更新窗口，避免每个
部分单独更新时烦人的屏幕闪烁。‘refresh()’ 实际上做了两件事：

  1. 调用每个窗口的 *note noutrefresh(): 22c1. 方法来更新一个表达屏幕期
     望状态的底层的数据结构。

  2. 调用函数 *note doupdate(): 22bf. 来改变物理屏幕来符合这个数据结构中
     记录的期望状态。

你可以改为调用在多个窗口上 ‘noutrefresh()’ 方法来更新该数据结构，然后调
用函数 ‘doupdate()’ 来更新屏幕。


File: python.info,  Node: 显示文字,  Next: 用户输入,  Prev: 窗口和面板,  Up: 用 Python 进行 Curses 编程

10.3.4 显示文字
---------------

从一名 C 语言程序员的视角来看，curses 有时看起来就像是一堆略有差异的函数
组成的扭曲迷宫。举个例子，‘addstr()’ 在 ‘stdscr’ 窗口的当前光标位置显示
一个字符串，而 ‘mvaddstr()’ 则是先移动到一个给定的 y,x 坐标再显示字符串
。‘waddstr()’ 与 ‘addstr()’ 类似，但允许指定一个窗口而非默认的 ‘stdscr’。
‘mvwaddstr()’ 允许同时指定一个窗口和一个坐标。

幸运的是，Python 接口隐藏了所有这些细节。‘stdscr’ 和其他任何窗口一样是一
个窗口对象，并且诸如 *note addstr(): 22c0. 之类的方法接受多种参数形式。
通常有四种形式。

形式                                  描述
                                      
------------------------------------------------------------------------------------------
                                      
`str' 或 `ch'                         在当前位置显示字符串 `str' 或字符 `ch'
                                      
                                      
`str' 或 `ch', `attr'                 在当前位置使用 `attr' 属性显示字符串 `str' 或字符
                                      `ch'
                                      
                                      
`y', `x', `str' 或 `ch'               移动到窗口内的 `y,x' 位置，并显示 `str' 或 `ch'
                                      
                                      
`y', `x', `str' 或 `ch', `attr'       移至窗口内的 `y,x' 位置，并使用 `attr' 属性显示
                                      `str' 或 `ch'
                                      

属性允许以突出显示形态显示文本，比如加粗、下划线、反相或添加颜色。这些属
性将来下一小节细说。

方法 *note addstr(): 22c0. 接受一个 Python 字符串或字节串作为用于显示的
值。字节串的内容会被原样发送到终端。字符串会使用窗口的 ‘encoding’ 属性值
编码为字节，它默认为 *note locale.getpreferredencoding(): 4ab. 返回的系
统默认编码。

方法 *note addch(): 22ff. 接受一个字符，可以是长度为 1 的字符串，长度为
1 的字节串或者一个整数。

对于特殊扩展字符有一些常量，这些常量是大于 255 的整数。比如，
‘ACS_PLMINUS’ 是一个 “加减” 符号，‘ACS_ULCORNER’ 是一个框的左上角（方便
绘制边界）。你也可以使用正确的 Unicode 字符。

窗口会记住上次操作之后光标所在位置，所以如果你忽略 `y,x' 坐标，字符串和
字符会出现在上次操作结束的位置。你也可以通过 ‘move(y,x)’ 的方法来移动光
标。因为一些终端始终会显示一个闪烁的光标，你可能会想要保证光标处于一些不
会让人感到分心的位置。在看似随机的位置出现一个闪烁的光标会令人非常迷惑。

如果你的应用程序完全不需要一个闪烁的光标，你可以调用 ‘curs_set(False)’ 来
使它隐形。为与旧版本 curses 的兼容性的关系，有函数 ‘leaveok(bool)’ 作为
*note curs_set(): 22b9. 的等价替换。如果 `bool' 是真值，curses 库会尝试
移除闪烁光标，并且你也不必担心它会留在一些奇怪的位置。

* Menu:

* 属性和颜色::


File: python.info,  Node: 属性和颜色,  Up: 显示文字

10.3.4.1 属性和颜色
...................

字符可以以不同的方式显示。基于文本的应用程序常常以反相显示状态行，一个文
本查看器可能需要突出显示某些单词。为了支持这种用法，curses 允许你为屏幕
上的每个单元指定一个属性值。

属性值是一个整数，它的每一个二进制位代表一个不同的属性。你可以尝试以多种
不属性位组合来显示文本，但 curses 不保证所有的组合都是有效的，或者看上去
有明显不同。这一点取决于用户终端的能力，所以最稳妥的方式是只采用最常见的
有效属性，见下表。

属性                       描述
                           
----------------------------------------------------------------------
                           
‘A_BLINK’                  闪烁文本
                           
                           
‘A_BOLD’                   超亮或粗体文本
                           
                           
‘A_DIM’                    半明亮文本
                           
                           
‘A_REVERSE’                反相显示文本
                           
                           
‘A_STANDOUT’               可用的最佳突出显示模式
                           
                           
‘A_UNDERLINE’              带下划线的文本
                           

所以，为了在屏幕顶部显示一个反相的状态行，你可以这么编写：

     stdscr.addstr(0, 0, "Current mode: Typing mode",
                   curses.A_REVERSE)
     stdscr.refresh()

curses 库还支持在提供了颜色功能的终端上显示颜色的功能。最常见的提供颜色
的终端很可能是 Linux 控制台，采用了 xterms 配色方案。

为了使用颜色，你必须在调用完函数 *note initscr(): 22c7. 后尽快调用函数
*note start_color(): 22f2.，来初始化默认颜色集 (*note curses.wrapper():
3c4. 函数自动完成了这一点)。 当它完成后，如果使用中的终端支持显示颜色，
*note has_colors(): 22cf. 会返回真值。 （注意：curses 使用美式拼写
“color”，而不是英式／加拿大拼写 “colour”。如果你习惯了英式拼写，你需要避
免自己在这些函数上拼写错误。）

curses 库维护一个有限数量的颜色对，包括一个前景（文本）色和一个背景色。
你可以使用函数 *note color_pair(): 22b7. 获得一个颜色对对应的属性值。它
可以通过按位或运算与其他属性，比如 ‘A_REVERSE’ 组合。但再说明一遍，这种
组合并不保证在所有终端上都有效。

一个样例，用 1 号颜色对显示一行文本：

     stdscr.addstr("Pretty text", curses.color_pair(1))
     stdscr.refresh()

如前所述， 颜色对由前景色和背景色组成。 ‘init_pair(n, f, b)’ 函数可改变
颜色对 `n' 的定义 为前景色 f 和背景色 b。 颜色对 0 硬编码为黑底白字，不
能改变。

颜色已经被编号，并且当其激活 color 模式时 ‘start_color()’ 会初始化 8 种
基本颜色。 它们是: 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta,
6:cyan 和 7:white。 *note curses: 2b. 模块为这些颜色定义了相应的名称常量
: ‘curses.COLOR_BLACK’, ‘curses.COLOR_RED’ 等等。

让我们来做个综合练习。 要将颜色 1 改为红色文本白色背景，你应当调用:

     curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)

当你改变一个颜色对时，任何已经使用该颜色对来显示的文本将会更改为新的颜色
。 你还可以这样来显示新颜色的文本:

     stdscr.addstr(0,0, "RED ALERT!", curses.color_pair(1))

某些非常花哨的终端可以将实际颜色定义修改为给定的 RGB 值。 这允许你将通常
为红色的 1 号颜色改成紫色或蓝色或者任何你喜欢的颜色。 不幸的是，Linux 控
制台不支持此特性，所以我无法尝试它，也无法提供任何示例。 想要检查你的终
端是否能做到你可以调用 *note can_change_color(): 22b3.，如果有此功能则它
将返回 ‘True’。 如果你幸运地拥有一个如此优秀的终端，请查询你的系统的帮助
页面来了解详情。


File: python.info,  Node: 用户输入,  Next: 更多的信息,  Prev: 显示文字,  Up: 用 Python 进行 Curses 编程

10.3.5 用户输入
---------------

C curses 库提供了非常简单的输入机制。 Python 的 *note curses: 2b. 模块添
加了一个基本的文本输入控件。 （其他的库例如 Urwid(1) 拥有更丰富的控件集
。）

有两个方法可以从窗口获取输入:

   * *note getch(): 22cb. 会刷新屏幕然后等待用户按键，如果之前调用过
     *note echo(): 22c3. 还会显示所按的键。 你还可以选择指定一个坐标以便
     在暂停之前让光标移动到那里。

   * *note getkey(): 2318. 将做同样的事但是会把整数转换为字符串。 每个字
     符将返回为长度为 1 个字符的字符串，特殊键例如函数键将返回包含键名的
     较长字符串例如 ‘KEY_UP’ 或 ‘^G’。

使用 *note nodelay(): 232e. 窗口方法可以做到不等待用户。 在
‘nodelay(True)’ 之后，窗口的 ‘getch()’ 和 ‘getkey()’ 将成为非阻塞的。 为
表明输入未就绪，‘getch()’ 会返回 ‘curses.ERR’ (值为 -1) 而 ‘getkey()’ 会
引发异常。 此外还有 *note halfdelay(): 22d3. 函数，它可被用来（实际地）
在每个 ‘getch()’ 上设置一个计时器；如果在指定的延迟内没有输入可用（以十
分之一秒为单位），curses 将引发异常。

‘getch()’ 方法返回一个整数；如果数值在 0 到 255 之间，它代表所按下键的
ASCII 码。 大于 255 的值为特殊键例如 Page Up, Home 或方向键等。 你可以将
返回的值与 ‘curses.KEY_PPAGE’, ‘curses.KEY_HOME’ 或 ‘curses.KEY_LEFT’ 等
常量做比较。 你的程序主循环看起来可能是这样:

     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

*note curses.ascii: 2c. 模块提供了一些 ASCII 类成员函数，它们接受整数或
长度为 1 个字符的字符串参数；这些函数在为这样的循环编写更具可读性的测试
时可能会很有用。 它还提供了一些转换函数，它们接受整数或长度为 1 个字符的
字符串参数并返回同样的类型。 例如，*note curses.ascii.ctrl(): 2362. 返回
与其参数相对应的控制字符。

还有一个可以提取整个字符串的方法 *note getstr(): 231b.。 它并不经常被使
用，因为它的功能相当受限；可用的编辑键只有 Backspace 和 Enter 键，它们会
结束字符串。 也可以选择限制为固定数量的字符。

     curses.echo()            # Enable echoing of characters

     # Get a 15-character string, with the cursor on the top line
     s = stdscr.getstr(0,0, 15)

*note curses.textpad: 2e. 模块提供了一个文本框，它支持类似 Emacs 的键绑
定集。 *note Textbox: 2348. 类的各种方法支持带输入验证的编辑及包含或不包
含末尾空格地收集编辑结果。 下面是一个例子:

     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()

请查看 *note curses.textpad: 2e. 的库文档了解更多细节。

   ---------- Footnotes ----------

   (1) https://pypi.org/project/urwid/


File: python.info,  Node: 更多的信息,  Prev: 用户输入,  Up: 用 Python 进行 Curses 编程

10.3.6 更多的信息
-----------------

本 HOWTO 没有涵盖一些进阶主题，例如读取屏幕的内容或从 xterm 实例捕获鼠标
事件等，但是 *note curses: 2b. 模块的 Python 库文档页面现在已相当完善。
接下来你应当去浏览一下其中的内容。

如果你对 curses 函数的细节行为有疑问，请查看你的 curses 实现版本的说明页
面，不论它是 ncurses 还是特定 Unix 厂商的版本。 说明页面将记录任何具体问
题，并提供所有函数、属性以及可用 ‘ACS_*’ 字符的完整列表。

由于 curses API 是如此的庞大，某些函数并不被 Python 接口所支持。 这往往
不是因为它们难以实现，而是因为还没有人需要它们。 此外，Python 尚不支持与
ncurses 相关联的菜单库。 欢迎提供添加这些功能的补丁；请参阅 Python 开发
者指南(1) 了解有关为 Python 提交补丁的详情。

   * 使用 NCURSES 编写程序(2): 一篇面向 C 程序员的详细教程。

   * ncurses 手册主页 <‘https://linux.die.net/man/3/ncurses’>‘_

   * ncurses 常见问题
     <‘http://invisible-island.net/ncurses/ncurses.faq.html’>‘_

   * "使用 curses... 请勿爆粗"(3): 一场有关使用 curses 或 Urwid 来控制终
     端的 PyCon 2013 演讲的视频。

   * "使用 Urwid 的控制台应用程序"(4): 一场演示使用 Urwid 编写应用程序的
     PyCon CA 2012 演讲的视频。

   ---------- Footnotes ----------

   (1) https://devguide.python.org/

   (2) http://invisible-island.net/ncurses/ncurses-intro.html

   (3) https://www.youtube.com/watch?v=eN1eZtjLEnU

   (4) http://www.pyvideo.org/video/1568/console-applications-with-urwid


File: python.info,  Node: 修飾器 HowTo 指南,  Next: 函式編程 HOWTO,  Prev: 用 Python 进行 Curses 编程,  Up: Python 如何達成任務

10.4 修飾器 HowTo 指南
======================


作者: Raymond Hettinger（译者：wh2099 at outlook dot com）


联系方式: <python at rcn dot com>

*note 描述器: 1579. 让对象能够自定义属性查找、存储和删除的操作。

本指南主要分为四个部分：

  1. “入门” 部分从简单的示例着手，逐步添加特性，从而给出基本的概述。如果
     你是刚接触到描述器，请从这里开始。

  2. 第二部分展示了完整的、实用的描述器示例。如果您已经掌握了基础知识，
     请从此处开始。

  3. 第三部分提供了更多技术教程，详细介绍了描述器如何工作。大多数人并不
     需要深入到这种程度。

  4. 最后一部分有对内置描述器（用 C 编写）的纯 Python 等价实现。如果您想
     了解函数如何变成绑定方法或对 *note classmethod(): 309.， *note
     staticmethod(): 30a.，*note property(): 308. 和 *note __slots__:
     393d. 这类常见工具的实现感兴趣，请阅读此部分。

* Menu:

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


File: python.info,  Node: 入门,  Next: 完整的实际例子,  Up: 修飾器 HowTo 指南

10.4.1 入门
-----------

现在，让我们从最基本的示例开始，然后逐步添加新功能。

* Menu:

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


File: python.info,  Node: 简单示例：返回常量的描述器,  Next: 动态查找,  Up: 入门

10.4.1.1 简单示例：返回常量的描述器
...................................

类 ‘Ten’ 是一个描述器，它的 *note __get__(): 156e. 方法总是返回常量
‘10’：

     class Ten:
         def __get__(self, obj, objtype=None):
             return 10

要使用描述器，它必须作为一个类变量存储在另一个类中：

     class A:
         x = 5                       # Regular class attribute
         y = Ten()                   # Descriptor instance

用交互式会话查看普通属性查找和描述器查找之间的区别：

     >>> a = A()                     # Make an instance of class A
     >>> a.x                         # Normal attribute lookup
     5
     >>> a.y                         # Descriptor lookup
     10

在 ‘a.x’ 属性查找中，点运算符会找到存储在类字典中的键 ‘x’ 及对应的值 ‘5’
。 在 ‘a.y’ 查找中，点运算符会根据描述器实例的 ‘__get__’ 方法将其识别出
来，调用该方法并返回 ‘10’ 。

请注意，值 ‘10’ 既不存储在类字典中也不存储在实例字典中。相反，值 ‘10’ 是
在调用时才取到的。

这个简单的例子展示了一个描述器是如何工作的，但它不是很有用。在查找常量时
，用常规属性查找会更好。

在下一节中，我们将创建更有用的东西，即动态查找。


File: python.info,  Node: 动态查找,  Next: 托管属性,  Prev: 简单示例：返回常量的描述器,  Up: 入门

10.4.1.2 动态查找
.................

有趣的描述器通常运行计算而不是返回常量：

     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

交互式会话显示查找是动态的，每次都会计算不同的，经过更新的返回值:

     >>> 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

除了说明描述器如何运行计算，这个例子也揭示了 *note __get__(): 156e. 参数
的目的。形参 `self' 接收的实参是 `size'，即 `DirectorySize' 的一个实例。
形参 `obj' 接收的实参是 `g' 或 `s'，即 `Directory' 的一个实例。而正是
`obj' 让 *note __get__(): 156e. 方法获得了作为目标的目录。形参 `objtype'
接收的实参是 `Directory' 类。


File: python.info,  Node: 托管属性,  Next: 定制名称,  Prev: 动态查找,  Up: 入门

10.4.1.3 托管属性
.................

描述器的一种流行用法是托管对实例数据的访问。描述器被分配给类字典中的公开
属性，而实际数据作为私有属性存储在实例字典中。当访问公开属性时，会触发描
述器的 *note __get__(): 156e. 和 *note __set__(): 1572. 方法。

在下面的例子中，`age' 是公开属性，`_age' 是私有属性。当访问公开属性时，
描述器会记录下查找或更新的日志：

     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__()

交互式会话展示中，对托管属性 `age' 的所有访问都被记录了下来，但常规属性
`name' 则未被记录：

     >>> 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

此示例的一个主要问题是私有名称 `_age' 在类 `LoggedAgeAccess' 中是硬耦合
的。这意味着每个实例只能有一个用于记录的属性，并且其名称不可更改。


File: python.info,  Node: 定制名称,  Next: 结束语,  Prev: 托管属性,  Up: 入门

10.4.1.4 定制名称
.................

当一个类使用描述器时，它可以告知每个描述器使用了什么变量名。

在此示例中， ‘Person’ 类具有两个描述器实例 `name' 和 `age'。当类
‘Person’ 被定义的时候，他回调了 `LoggedAccess' 中的 *note
__set_name__(): 5e2. 来记录字段名称，让每个描述器拥有自己的
`public_name' 和 `private_name'：

     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

交互交互式会话显示类 ‘Person’ 调用了 *note __set_name__(): 5e2. 方法来记
录字段的名称。在这里，我们调用 *note vars(): 116d. 来查找描述器而不触发
它：

     >>> vars(vars(Person)['name'])
     {'public_name': 'name', 'private_name': '_name'}
     >>> vars(vars(Person)['age'])
     {'public_name': 'age', 'private_name': '_age'}

现在，新类会记录对 `name' 和 `age' 二者的访问：

     >>> 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

这两个 `Person' 实例仅包含私有名称:

     >>> vars(pete)
     {'_name': 'Peter P', '_age': 10}
     >>> vars(kate)
     {'_name': 'Catherine C', '_age': 20}


File: python.info,  Node: 结束语,  Prev: 定制名称,  Up: 入门

10.4.1.5 结束语
...............

*note descriptor: 1579. 就是任何一个定义了 *note __get__(): 156e.，*note
__set__(): 1572. 或 *note __delete__(): 1573. 的对象。

可选地，描述器可以具有 *note __set_name__(): 5e2. 方法。这仅在描述器需要
知道创建它的类或分配给它的类变量名称时使用。（即使该类不是描述器，只要此
方法存在就会调用。）

在属性查找期间，描述器由点运算符调用。如果使用
‘vars(some_class)[descriptor_name]’ 间接访问描述器，则返回描述器实例而不
调用它。

描述器仅在用作类变量时起作用。放入实例时，它们将失效。

描述器的主要目的是提供一个挂钩，允许存储在类变量中的对象控制在属性查找期
间发生的情况。

传统上，调用类控制查找过程中发生的事情。描述器反转了这种关系，并允许正在
被查询的数据对此进行干涉。

描述器的使用贯穿了整个语言。就是它让函数变成绑定方法。常见工具诸如 *note
classmethod(): 309.， *note staticmethod(): 30a.，*note property(): 308.
和 *note functools.cached_property(): 2f9. 都作为描述器实现。


File: python.info,  Node: 完整的实际例子,  Next: 技术教程,  Prev: 入门,  Up: 修飾器 HowTo 指南

10.4.2 完整的实际例子
---------------------

在此示例中，我们创建了一个实用而强大的工具来查找难以发现的数据损坏错误。

* Menu:

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


File: python.info,  Node: 验证器类,  Next: 自定义验证器,  Up: 完整的实际例子

10.4.2.1 验证器类
.................

验证器是一个用于托管属性访问的描述器。在存储任何数据之前，它会验证新值是
否满足各种类型和范围限制。如果不满足这些限制，它将引发异常，从源头上防止
数据损坏。

这个 ‘Validator’ 类既是一个 *note abstract base class: c05. 也是一个托管
属性描述器。

     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

自定义验证器需要从 ‘Validator’ 继承，并且必须提供 ‘validate()’ 方法以根
据需要测试各种约束。


File: python.info,  Node: 自定义验证器,  Next: 实际应用,  Prev: 验证器类,  Up: 完整的实际例子

10.4.2.2 自定义验证器
.....................

这是三个实用的数据验证工具：

  1. ‘OneOf’ 验证值是一组受约束的选项之一。

  2. ‘Number’ 验证值是否为 *note int: 204. 或 *note float: 1fd.。根据可
     选参数，它还可以验证值在给定的最小值或最大值之间。

  3. ‘String’ 验证值是否为 *note str: 205.。根据可选参数，它可以验证给定
     的最小或最大长度。它还可以验证用户定义的 predicate(1)。

     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}'
                 )

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Predicate_(mathematical_logic)


File: python.info,  Node: 实际应用,  Prev: 自定义验证器,  Up: 完整的实际例子

10.4.2.3 实际应用
.................

这是在真实类中使用数据验证器的方法：

     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

描述器阻止无效实例的创建：

     >>> 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


File: python.info,  Node: 技术教程,  Next: 纯 Python 等价实现,  Prev: 完整的实际例子,  Up: 修飾器 HowTo 指南

10.4.3 技术教程
---------------

接下来是专业性更强的技术教程，以及描述器工作原理的详细信息。

* Menu:

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


File: python.info,  Node: 摘要,  Next: 定义与介绍,  Up: 技术教程

10.4.3.1 摘要
.............

定义描述器，总结协议，并说明如何调用描述器。提供一个展示对象关系映射如何
工作的示例。

学习描述器不仅能提供接触到更多工具集的途径，还能更深地理解 Python 工作的
原理。


File: python.info,  Node: 定义与介绍,  Next: 描述器协议,  Prev: 摘要,  Up: 技术教程

10.4.3.2 定义与介绍
...................

一般而言，描述器是一个包含了描述器协议中的方法的属性值。 这些方法有
*note __get__(): 156e, *note __set__(): 1572. 和 *note __delete__():
1573.。 如果为某个属性定义了这些方法中的任意一个，它就可以被称为 *note
descriptor: 1579.。

属性访问的默认行为是从一个对象的字典中获取、设置或删除属性。对于实例来说
，‘a.x’ 的查找顺序会从 ‘a.__dict__['x']’ 开始，然后是
‘type(a).__dict__['x']’，接下来依次查找 ‘type(a)’ 的方法解析顺序（MRO）
。 如果找到的值是定义了某个描述器方法的对象，则 Python 可能会重写默认行
为并转而发起调用描述器方法。这具体发生在优先级链的哪个环节则要根据所定义
的描述器方法及其被调用的方式来决定。

描述器是一个强大而通用的协议。 它们是属性、方法、静态方法、类方法和
*note super(): 5dd. 背后的实现机制。 它们在 Python 内部被广泛使用。 描述
器简化了底层的 C 代码并为 Python 的日常程序提供了一组灵活的新工具。


File: python.info,  Node: 描述器协议,  Next: 描述器调用概述,  Prev: 定义与介绍,  Up: 技术教程

10.4.3.3 描述器协议
...................

‘descr.__get__(self, obj, type=None) -> value’

‘descr.__set__(self, obj, value) -> None’

‘descr.__delete__(self, obj) -> None’

描述器的方法就这些。一个对象只要定义了以上方法中的任何一个，就被视为描述
器，并在被作为属性时覆盖其默认行为。

如果一个对象定义了 *note __set__(): 1572. 或 *note __delete__(): 1573.，
则它会被视为数据描述器。 仅定义了 *note __get__(): 156e. 的描述器称为非
数据描述器（它们经常被用于方法，但也可以有其他用途）。

数据和非数据描述器的不同之处在于，如何计算实例字典中条目的替代值。如果实
例的字典具有与数据描述器同名的条目，则数据描述器优先。如果实例的字典具有
与非数据描述器同名的条目，则该字典条目优先。

为了使数据描述器成为只读的，应该同时定义 *note __get__(): 156e. 和 *note
__set__(): 1572. ，并在 *note __set__(): 1572. 中引发 *note
AttributeError: 4a1. 。用引发异常的占位符定义 *note __set__(): 1572. 方
法使其成为数据描述器。


File: python.info,  Node: 描述器调用概述,  Next: 通过实例调用,  Prev: 描述器协议,  Up: 技术教程

10.4.3.4 描述器调用概述
.......................

描述器可以通过 ‘d.__get__(obj)’ 或 ‘desc.__get__(None, cls)’ 直接调用。

但更常见的是通过属性访问自动调用描述器。

表达式 ‘obj.x’ 在命名空间的链中查找‘‘obj‘‘ 的属性 ‘x’。如果搜索在实例
‘__dict__’ 之外找到描述器，则根据下面列出的优先级规则调用其 *note
__get__(): 156e. 方法。

调用的细节取决于 ‘obj’ 是对象、类还是超类的实例。


File: python.info,  Node: 通过实例调用,  Next: 通过类调用,  Prev: 描述器调用概述,  Up: 技术教程

10.4.3.5 通过实例调用
.....................

实例查找通过命名空间链进行扫描，数据描述器的优先级最高，其次是实例变量、
非数据描述器、类变量，最后是 *note __getattr__(): 42a. （如果存在的话）
。

如果 ‘a.x’ 找到了一个描述器，那么将通过 ‘desc.__get__(a, type(a))’ 调用
它。

点运算符的查找逻辑在 *note object.__getattribute__(): 549. 中。这里是一
个等价的纯 Python 实现：

     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)

有趣的是，属性查找不会直接调用 *note object.__getattribute__(): 549. ，
点运算符和 *note getattr(): 54b. 函数均通过辅助函数执行属性查找：

     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__

因此，如果 *note __getattr__(): 42a. 存在，则只要 *note
__getattribute__(): 549. 引发 *note AttributeError: 4a1. （直接引发异常
或在描述符调用中引发都一样），就会调用它。

同时，如果用户直接调用 *note object.__getattribute__(): 549. ，则 *note
__getattr__(): 42a. 的钩子将被绕开。


File: python.info,  Node: 通过类调用,  Next: 通过 super 调用,  Prev: 通过实例调用,  Up: 技术教程

10.4.3.6 通过类调用
...................

像 ‘A.x’ 这样的点操作符查找的逻辑在 ‘type.__getattribute__()’ 中。步骤与
*note object.__getattribute__(): 549. 相似，但是实例字典查找改为搜索类的
*note method resolution order: 1739.。

如果找到了一个描述器，那么将通过 ‘desc.__get__(None, A)’ 调用它。

完整的 C 实现可在 Objects/typeobject.c(1) 中的 ‘type_getattro()’ 和
‘_PyType_Lookup()’ 找到。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Objects/typeobject.c


File: python.info,  Node: 通过 super 调用,  Next: 调用逻辑总结,  Prev: 通过类调用,  Up: 技术教程

10.4.3.7 通过 super 调用
........................

super 的点操作符查找的逻辑在 *note super(): 5dd. 返回的对象的 *note
__getattribute__(): 549. 方法中。

类似 ‘super(A, obj).m’ 形式的点分查找将在 ‘obj.__class__.__mro__’ 中搜索
紧接在 ‘A’ 之后的基类 ‘B’，然后返回 ‘B.__dict__['m'].__get__(obj, A)’。
如果 ‘m’ 不是描述器，则直接返回其值。

完整的 C 实现可以在 Objects/typeobject.c(1) 的 ‘super_getattro()’ 中找到
。纯 Python 等价实现可以在 Guido’s Tutorial(2) 中找到。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Objects/typeobject.c

   (2) 
https://www.python.org/download/releases/2.2.3/descrintro/#cooperation


File: python.info,  Node: 调用逻辑总结,  Next: 自动名称通知,  Prev: 通过 super 调用,  Up: 技术教程

10.4.3.8 调用逻辑总结
.....................

描述器的机制嵌入在 *note object: 3d2.，*note type: 6ff. 和 *note
super(): 5dd. 的 *note __getattribute__(): 549. 方法中。

要记住的重要点是：

   * 描述器由 *note __getattribute__(): 549. 方法调用。

   * 类从 *note object: 3d2.，*note type: 6ff. 或 *note super(): 5dd. 继
     承此机制。

   * 由于描述器的逻辑在 *note __getattribute__(): 549. 中，因而重写该方
     法会阻止描述器的自动调用。

   * *note object.__getattribute__(): 549. 和 ‘type.__getattribute__()’
     会用不同的方式调用 *note __get__(): 156e.。前一个会传入实例，也可以
     包括类。后一个传入的实例为 ‘None’ ，并且总是包括类。

   * 数据描述器始终会覆盖实例字典。

   * 非数据描述器会被实例字典覆盖。


File: python.info,  Node: 自动名称通知,  Next: ORM （对象关系映射）示例,  Prev: 调用逻辑总结,  Up: 技术教程

10.4.3.9 自动名称通知
.....................

有时，描述器想知道它分配到的具体类变量名。创建新类时，元类 *note type:
6ff. 将扫描新类的字典。如果有描述器，并且它们定义了 *note
__set_name__(): 5e2.，则使用两个参数调用该方法。`owner' 是使用描述器的类
，`name' 是分配给描述器的类变量名。

实现的细节在 Objects/typeobject.c(1) 中的 ‘type_new()’ 和 ‘set_names()’
。

由于更新逻辑在 ‘type.__new__()’ 中，因此通知仅在创建类时发生。之后如果将
描述器添加到类中，则需要手动调用 *note __set_name__(): 5e2. 。

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Objects/typeobject.c


File: python.info,  Node: ORM （对象关系映射）示例,  Prev: 自动名称通知,  Up: 技术教程

10.4.3.10 ORM （对象关系映射）示例
..................................

以下代码展示了如何使用数据描述器来实现简单 object relational mapping(1)
框架。

其核心思路是将数据存储在外部数据库中，Python 实例仅持有数据库表中对应的
的键。描述器负责对值进行查找或更新：

     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()

我们可以用 ‘Field’ 类来定义描述了数据库中每张表的模式的 models(2)。

     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

要使用模型，首先要连接到数据库：

     >>> import sqlite3
     >>> conn = sqlite3.connect('entertainment.db')

交互式会话显示了如何从数据库中检索数据及如何对其进行更新：

     >>> 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'

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping

   (2) https://en.wikipedia.org/wiki/Database_model


File: python.info,  Node: 纯 Python 等价实现,  Prev: 技术教程,  Up: 修飾器 HowTo 指南

10.4.4 纯 Python 等价实现
-------------------------

描述器协议很简单，但它提供了令人兴奋的可能性。有几个用例非常通用，以至于
它们已预先打包到内置工具中。属性、绑定方法、静态方法、类方法和 __slots__
均基于描述器协议。

* Menu:

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


File: python.info,  Node: 属性<2>,  Next: 函数和方法,  Up: 纯 Python 等价实现

10.4.4.1 属性
.............

调用 *note property(): 308. 是构建数据描述器的简洁方式，该数据描述器在访
问属性时触发函数调用。它的签名是：

     property(fget=None, fset=None, fdel=None, doc=None) -> property

该文档显示了定义托管属性 ‘x’ 的典型用法：

     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.")

要了解 *note property(): 308. 如何根据描述器协议实现，这里是一个纯
Python 的等价实现：

     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__)

这个内置的 *note property(): 308. 每当用户访问属性时生效，随后的变化需要
一个方法的参与。

例如，一个电子表格类可以通过 ‘Cell('b10').value’ 授予对单元格值的访问权
限。对程序的后续改进要求每次访问都要重新计算单元格；但是，程序员不希望影
响直接访问该属性的现有客户端代码。解决方案是将对 value 属性的访问包装在
属性数据描述器中:

     class Cell:
         ...

         @property
         def value(self):
             "Recalculate the cell before returning value"
             self.recalc()
             return self._value

在此示例中，内置的 *note property(): 308. 或我们实现的的 ‘Property()’ 均
适用。


File: python.info,  Node: 函数和方法,  Next: 方法的种类,  Prev: 属性<2>,  Up: 纯 Python 等价实现

10.4.4.2 函数和方法
...................

Python 的面向对象功能是在基于函数的环境构建的。通过使用非数据描述器，这
两方面完成了无缝融合。

在调用时，存储在类词典中的函数将被转换为方法。方法与常规函数的不同之处仅
在于对象实例被置于其他参数之前。方法与常规函数的不同之处仅在于第一个参数
是为对象实例保留的。按照惯例，实例引用称为 `self' ，但也可以称为 `this'
或任何其他变量名称。

可以使用 *note types.MethodType: 1af8. 手动创建方法，其行为基本等价于：

     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)

为了支持自动创建方法，函数包含 *note __get__(): 156e. 方法以便在属性访问
时绑定其为方法。这意味着函数其是非数据描述器，它在通过实例进行点查找时返
回绑定方法，其运作方式如下：

     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)

在解释器中运行以下类，这显示了函数描述器的实际工作方式：

     class D:
         def f(self, x):
              return x

该函数具有 *note qualified name: 155c. 属性以支持自省：

     >>> D.f.__qualname__
     'D.f'

通过类字典访问函数不会调用 *note __get__(): 156e.。相反，它只返回基础函
数对象：

     >>> D.__dict__['f']
     <function D.f at 0x00C45070>

来自类的点运算符访问会调用 *note __get__(): 156e.，直接返回底层的函数。

     >>> D.f
     <function D.f at 0x00C45070>

有趣的行为发生在从实例进行点访问期间。点运算符查找调用 *note __get__():
156e.，返回绑定的方法对象：

     >>> d = D()
     >>> d.f
     <bound method D.f of <__main__.D object at 0x00B18C90>>

绑定方法在内部存储了底层函数和绑定的实例：

     >>> d.f.__func__
     <function D.f at 0x00C45070>

     >>> d.f.__self__
     <__main__.D object at 0x1012e1f98>

如果你曾好奇常规方法中的 `self' 或类方法中的 `cls' 是从什么地方来的，就
是这里了！


File: python.info,  Node: 方法的种类,  Next: 静态方法,  Prev: 函数和方法,  Up: 纯 Python 等价实现

10.4.4.3 方法的种类
...................

非数据描述器为把函数绑定为方法的通常模式提供了一种简单的机制。

概括地说，函数对象具有 *note __get__(): 156e. 方法，以便在作为属性访问时
可以将其转换为方法。非数据描述器将 ‘obj.f(*args)’ 的调用会被转换为
‘f(obj, *args)’ 。调用 ‘klass.f(*args)‘’ 因而变成 ‘f(*args)’ 。

下表总结了绑定及其两个最有用的变体：

     转换形式              通过对象调用               通过类调用
                                                      
     ------------------------------------------------------------------------
                                                      
     函数                  f(obj, *args)              f(*args)
                                                      
                                                      
     静态方法              f(*args)                   f(*args)
                                                      
                                                      
     类方法                f(type(obj), *args)        f(cls, *args)
                                                      


File: python.info,  Node: 静态方法,  Next: 类方法,  Prev: 方法的种类,  Up: 纯 Python 等价实现

10.4.4.4 静态方法
.................

静态方法返回底层函数，不做任何更改。调用 ‘c.f’ 或 ‘C.f’ 等效于通过
‘object.__getattribute__(c, "f")’ 或 ‘object.__getattribute__(C, "f")’ 查
找。这样该函数就可以从对象或类中进行相同的访问。

适合作为静态方法的是那些不引用 ‘self’ 变量的方法。

例如，一个统计用的包可能包含一个实验数据的容器类。该容器类提供了用于计算
数据的平均值，均值，中位数和其他描述性统计信息的常规方法。但是，可能有在
概念上相关但不依赖于数据的函数。例如， ‘erf(x)’ 是在统计中的便捷转换，但
并不直接依赖于特定的数据集。可以从对象或类中调用它： ‘s.erf(1.5) -->
.9332’ 或 ‘Sample.erf(1.5) --> .9332’。

由于静态方法返回的底层函数没有任何变化，因此示例调用也是意料之中：

     class E:
         @staticmethod
         def f(x):
             return x * 10

     >>> E.f(3)
     30
     >>> E().f(3)
     30

使用非数据描述器，纯 Python 版本的 *note staticmethod(): 30a. 如下所示：

     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


File: python.info,  Node: 类方法,  Next: 成员对象和 __slots__,  Prev: 静态方法,  Up: 纯 Python 等价实现

10.4.4.5 类方法
...............

与静态方法不同，类方法在调用函数之前将类引用放在参数列表的最前。无论调用
方是对象还是类，此格式相同：

     class F:
         @classmethod
         def f(cls, x):
             return cls.__name__, x

     >>> F.f(3)
     ('F', 3)
     >>> F().f(3)
     ('F', 3)

当方法仅需要具有类引用并且确实依赖于存储在特定实例中的数据时，此行为就很
有用。类方法的一种用途是创建备用类构造函数。例如，类方法 *note
dict.fromkeys(): 180a. 从键列表创建一个新字典。纯 Python 的等价实现是：

     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

现在可以这样构造一个新的唯一键字典：

     >>> d = Dict.fromkeys('abracadabra')
     >>> type(d) is Dict
     True
     >>> d
     {'a': None, 'b': None, 'r': None, 'c': None, 'd': None}

使用非数据描述器协议，纯 Python 版本的 *note classmethod(): 309. 如下：

     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)

‘hasattr(type(self.f), '__get__')’ 的代码路径在 Python 3.9 中被加入并让
*note classmethod(): 309. 可以支持链式装饰器。 例如，一个类方法和特征属
性可以被链接在一起:

     class G:
         @classmethod
         @property
         def __doc__(cls):
             return f'A doc for {cls.__name__!r}'

     >>> G.__doc__
     "A doc for 'G'"


File: python.info,  Node: 成员对象和 __slots__,  Prev: 类方法,  Up: 纯 Python 等价实现

10.4.4.6 成员对象和 __slots__
.............................

当一个类定义了 ‘__slots__’，它会用一个固定长度的 slot 值数组来替换实例字
典。 从用户的视角看，效果是这样的：

1.  Provides immediate detection of bugs due to misspelled attribute
assignments.  Only attribute names specified in ‘__slots__’ are allowed:

     class Vehicle:
         __slots__ = ('id_number', 'make', 'model')

     >>> auto = Vehicle()
     >>> auto.id_nubmer = 'VYE483814LQEX'
     Traceback (most recent call last):
         ...
     AttributeError: 'Vehicle' object has no attribute 'id_nubmer'

2.  Helps create immutable objects where descriptors manage access to
private attributes stored in ‘__slots__’:

     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

     >>> 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'

3.  Saves memory.  On a 64-bit Linux build, an instance with two
attributes takes 48 bytes with ‘__slots__’ and 152 bytes without.  This
flyweight design pattern(1) likely only matters when a large number of
instances are going to be created.

4.  Blocks tools like *note functools.cached_property(): 2f9. which
require an instance dictionary to function correctly:

     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)))

     >>> CP().pi
     Traceback (most recent call last):
       ...
     TypeError: No '__dict__' attribute on 'CP' instance to cache 'pi' property.

要创建一个一模一样的纯 Python 版的 ‘__slots__’ 是不可能的，因为它需要直
接访问 C 结构体并控制对象内存分配。 但是，我们可以构建一个非常相似的模拟
版，其中作为 slot 的实际 C 结构体由一个私有的 ‘_slotvalues’ 列表来模拟。
对该私有结构体的读写操作将由成员描述器来管理：

     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}>'

‘type.__new__()’ 方法负责将成员对象添加到类变量：

     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)

*note object.__new__(): 974. 方法负责创建具有 slot 而非实例字典的实例。
以下是一个纯 Python 的粗略模拟版：

     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)

要在真实的类中使用这个模拟版，只需从 ‘Object’ 继承并将 *note metaclass:
1590. 设为 ‘Type’：

     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

这时，metaclass 已经为 `x' 和 `y' 加载了成员对象：

     >>> 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'>}

当实例被创建时，它们将拥有一个用于存放属性的 ‘slot_values’ 列表：

     >>> h = H(10, 20)
     >>> vars(h)
     {'_slotvalues': [10, 20]}
     >>> h.x = 55
     >>> vars(h)
     {'_slotvalues': [55, 20]}

错误拼写或未赋值的属性将引发一个异常：

     >>> h.xz
     Traceback (most recent call last):
         ...
     AttributeError: 'H' object has no attribute 'xz'

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Flyweight_pattern


File: python.info,  Node: 函式編程 HOWTO,  Next: 如何使用 Logging 模組,  Prev: 修飾器 HowTo 指南,  Up: Python 如何達成任務

10.5 函式編程 HOWTO
===================


作者: A. M. Kuchling


发布版本: 0.32

本文档提供恰当的 Python 函数式编程范例，在函数式编程简单的介绍之后，将简
单介绍Python中关于函数式编程的特性如 *note iterator: 1171. 和 *note
generator: a83. 以及相关库模块如 *note itertools: a3. 和 *note
functools: 83. 等。

* Menu:

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


File: python.info,  Node: 簡介<13>,  Next: 迭代器,  Up: 函式編程 HOWTO

10.5.1 簡介
-----------

本章介绍函数式编程的基本概念。如您仅想学习 Python 语言的特性，可跳过本章
直接查看 *note 迭代器: 433f.

编程语言支持通过以下几种方式来解构具体问题：

   * 大多数的编程语言都是 `过程式' 的，所谓程序就是一连串告诉计算机怎样
     处理程序输入的指令。C、Pascal 甚至 Unix shells 都是过程式语言。

   * 在 `声明式' 语言中，你编写一个用来描述待解决问题的说明，并且这个语
     言的具体实现会指明怎样高效的进行计算。 SQL 可能是你最熟悉的声明式语
     言了。 一个 SQL 查询语句描述了你想要检索的数据集，并且 SQL 引擎会决
     定是扫描整张表还是使用索引，应该先执行哪些子句等等。

   * `面向对象' 程序会操作一组对象。 对象拥有内部状态，并能够以某种方式
     支持请求和修改这个内部状态的方法。Smalltalk 和 Java 都是面向对象的
     语言。 C++ 和 Python 支持面向对象编程，但并不强制使用面向对象特性。

   * `函数式' 编程则将一个问题分解成一系列函数。 理想情况下，函数只接受
     输入并输出结果，对一个给定的输入也不会有影响输出的内部状态。 著名的
     函数式语言有 ML 家族（Standard ML，Ocaml 以及其他变种）和 Haskell。

一些语言的设计者选择强调一种特定的编程方式。 这通常会让以不同的方式来编
写程序变得困难。其他多范式语言则支持几种不同的编程方式。Lisp，C++ 和
Python 都是多范式语言；使用这些语言，你可以编写主要为过程式，面向对象或
者函数式的程序和函数库。在大型程序中，不同的部分可能会采用不同的方式编写
；比如 GUI 可能是面向对象的而处理逻辑则是过程式或者函数式。

在函数式程序里，输入会流经一系列函数。每个函数接受输入并输出结果。函数式
风格反对使用带有副作用的函数，这些副作用会修改内部状态，或者引起一些无法
体现在函数的返回值中的变化。完全不产生副作用的函数被称作“纯函数”。消除副
作用意味着不能使用随程序运行而更新的数据结构；每个函数的输出必须只依赖于
输入。

Some languages are very strict about purity and don’t even have
assignment statements such as ‘a=3’ or ‘c = a + b’, but it’s difficult
to avoid all side effects, such as printing to the screen or writing to
a disk file.  Another example is a call to the *note print(): 971. or
*note time.sleep(): 773. function, neither of which returns a useful
value.  Both are called only for their side effects of sending some text
to the screen or pausing execution for a second.

函数式风格的 Python 程序并不会极端到消除所有 I/O 或者赋值的程度；相反，
他们会提供像函数式一样的接口，但会在内部使用非函数式的特性。比如，函数的
实现仍然会使用局部变量，但不会修改全局变量或者有其他副作用。

函数式编程可以被认为是面向对象编程的对立面。对象就像是颗小胶囊，包裹着内
部状态和随之而来的能让你修改这个内部状态的一组调用方法，以及由正确的状态
变化所构成的程序。函数式编程希望尽可能地消除状态变化，只和流经函数的数据
打交道。在 Python 里你可以把两种编程方式结合起来，在你的应用（电子邮件信
息，事务处理）中编写接受和返回对象实例的函数。

函数式设计在工作中看起来是个奇怪的约束。为什么你要消除对象和副作用呢？不
过函数式风格有其理论和实践上的优点：

   * 形式证明。

   * 模块化。

   * 组合性。

   * 易于调试和测试。

* Menu:

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


File: python.info,  Node: 形式证明,  Next: 模块化,  Up: 簡介<13>

10.5.1.1 形式证明
.................

一个理论上的优点是，构造数学证明来说明函数式程序是正确的相对更容易些。

很长时间，研究者们对寻找证明程序正确的数学方法都很感兴趣。这和通过大量输
入来测试，并得出程序的输出基本正确，或者阅读一个程序的源代码然后得出代码
看起来没问题不同；相反，这里的目标是一个严格的证明，证明程序对所有可能的
输入都能给出正确的结果。

证明程序正确性所用到的技术是写出 `不变量'，也就是对于输入数据和程序中的
变量永远为真的特性。然后对每行代码，你说明这行代码执行前的不变量 X 和 Y
以及执行后稍有不同的不变量 X’ 和 Y’ 为真。如此一直到程序结束，这时候在程
序的输出上，不变量应该会与期望的状态一致。

函数式编程之所以要消除赋值，是因为赋值在这个技术中难以处理；赋值可能会破
坏赋值前为真的不变量，却并不产生任何可以传递下去的新的不变量。

不幸的是，证明程序的正确性很大程度上是经验性质的，而且和 Python 软件无关
。即使是微不足道的程序都需要几页长的证明；一个中等复杂的程序的正确性证明
会非常庞大，而且，极少甚至没有你日常所使用的程序（Python 解释器，XML 解
析器，浏览器）的正确性能够被证明。即使你写出或者生成一个证明，验证证明也
会是一个问题；里面可能出了差错，而你错误地相信你证明了程序的正确性。


File: python.info,  Node: 模块化,  Next: 易于调试和测试,  Prev: 形式证明,  Up: 簡介<13>

10.5.1.2 模块化
...............

函数式编程的一个更实用的优点是，它强制你把问题分解成小的方面。因此程序会
更加模块化。相对于一个进行了复杂变换的大型函数，一个小的函数更明确，更易
于编写, 也更易于阅读和检查错误。


File: python.info,  Node: 易于调试和测试,  Next: 组合性,  Prev: 模块化,  Up: 簡介<13>

10.5.1.3 易于调试和测试
.......................

测试和调试函数式程序相对来说更容易。

调试很简单是因为函数通常都很小而且清晰明确。当程序无法工作的时候，每个函
数都是一个可以检查数据是否正确的接入点。你可以通过查看中间输入和输出迅速
找到出错的函数。

测试更容易是因为每个函数都是单元测试的潜在目标。在执行测试前，函数并不依
赖于需要重现的系统状态；相反，你只需要给出正确的输入，然后检查输出是否和
期望的结果一致。


File: python.info,  Node: 组合性,  Prev: 易于调试和测试,  Up: 簡介<13>

10.5.1.4 组合性
...............

当你编写函数式风格的程序时，你会写出很多带有不同输入和输出的函数。其中一
些不可避免地会局限于特定的应用，但其他的却可以广泛的用在程序中。举例来说
，一个接受文件夹目录返回所有文件夹中的 XML 文件的函数； 或是一个接受文件
名，然后返回文件内容的函数，都可以应用在很多不同的场合。

久而久之你会形成一个个人工具库。通常你可以重新组织已有的函数来组成新的程
序，然后为当前的工作写一些特殊的函数。


File: python.info,  Node: 迭代器,  Next: 生成器表达式和列表推导式,  Prev: 簡介<13>,  Up: 函式編程 HOWTO

10.5.2 迭代器
-------------

我会从 Python 的一个语言特性， 编写函数式风格程序的重要基石开始说起：迭
代器。

迭代器是一个表示数据流的对象；这个对象每次只返回一个元素。Python 迭代器
必须支持 *note __next__(): d2c. 方法；这个方法不接受参数，并总是返回数据
流中的下一个元素。如果数据流中没有元素，*note __next__(): d2c. 会抛出
*note StopIteration: 581. 异常。迭代器未必是有限的；完全有理由构造一个输
出无限数据流的迭代器。

内置的 *note iter(): ded. 函数接受任意对象并试图返回一个迭代器来输出对象
的内容或元素，并会在对象不支持迭代的时候抛出 *note TypeError: 1fe. 异常
。Python 有几种内置数据类型支持迭代，最常见的就是列表和字典。如果一个对
象能生成迭代器，那么它就会被称作 *note iterable: c7c.。

你可以手动试验迭代器的接口。

     >>> 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
     >>>

Python 有不少要求使用可迭代的对象的地方，其中最重要的就是 *note for:
cfa. 表达式。在表达式 ‘for X in Y’，Y 要么自身是一个迭代器，要么能够由
*note iter(): ded. 创建一个迭代器。以下两种表达是等价的:

     for i in iter(obj):
         print(i)

     for i in obj:
         print(i)

可以用 *note list(): 1f8. 或 *note tuple(): 1a2. 这样的构造函数把迭代器
具体化成列表或元组:

     >>> L = [1, 2, 3]
     >>> iterator = iter(L)
     >>> t = tuple(iterator)
     >>> t
     (1, 2, 3)

序列的解压操作也支持迭代器：如果你知道一个迭代器能够返回 N 个元素，你可
以把他们解压到有 N 个元素的元组:

     >>> L = [1, 2, 3]
     >>> iterator = iter(L)
     >>> a, b, c = iterator
     >>> a, b, c
     (1, 2, 3)

像 *note max(): 8f7. 和 *note min(): 8f6. 这样的内置函数可以接受单个迭代
器参数，然后返回其中最大或者最小的元素。‘"in"’ 和 ‘"not in"’ 操作也支持
迭代器：如果能够在迭代器 iterator 返回的数据流中找到 X 的话，则‘‘X in
iterator‘‘ 为真。很显然，如果迭代器是无限的，这么做你就会遇到问题；*note
max(): 8f7. 和 *note min(): 8f6. 永远也不会返回；如果元素 X 也不出现在数
据流中，‘"in"’ 和 ‘"not in"’ 操作同样也永远不会返回。

注意你只能在迭代器中顺序前进；没有获取前一个元素的方法，除非重置迭代器，
或者重新复制一份。迭代器对象可以提供这些额外的功能，但迭代器协议只明确了
*note __next__(): d2c. 方法。函数可能因此而耗尽迭代器的输出，如果你要对
同样的数据流做不同的操作，你必须重新创建一个迭代器。

* Menu:

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


File: python.info,  Node: 支持迭代器的数据类型,  Up: 迭代器

10.5.2.1 支持迭代器的数据类型
.............................

我们已经知道列表和元组支持迭代器。实际上，Python 中的任何序列类型，比如
字符串，都自动支持创建迭代器。

对字典调用 *note iter(): ded. 会返回一个遍历字典的键的迭代器:

     >>> 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

注意从 Python 3.7 开始，字典的遍历顺序一定和输入顺序一样。先前的版本并没
有明确这一点，所以不同的实现可能不一致。

对字典使用 *note iter(): ded. 总是会遍历键，但字典也有返回其他迭代器的方
法。如果你只遍历值或者键/值对，你可以明确地调用 *note values(): cf6. 或
*note items(): cf5. 方法得到合适的迭代器。

*note dict(): 164. 构造函数可以接受一个迭代器，然后返回一个有限的 ‘(key,
value)’ 元组的数据流:

     >>> L = [('Italy', 'Rome'), ('France', 'Paris'), ('US', 'Washington DC')]
     >>> dict(iter(L))
     {'Italy': 'Rome', 'France': 'Paris', 'US': 'Washington DC'}

文件也可以通过调用 *note readline(): 1d5b. 来遍历，直到穷尽文件中所有的
行。这意味着你可以像这样读取文件中的每一行:

     for line in file:
         # do something for each line
         ...

集合可以从可遍历的对象获取内容，也可以让你遍历集合的元素:

     S = {2, 3, 5, 7, 11, 13}
     for i in S:
         print(i)


File: python.info,  Node: 生成器表达式和列表推导式,  Next: 生成器,  Prev: 迭代器,  Up: 函式編程 HOWTO

10.5.3 生成器表达式和列表推导式
-------------------------------

迭代器的输出有两个很常见的使用方式，1) 对每一个元素执行操作，2) 选择一个
符合条件的元素子集。比如，给定一个字符串列表，你可能想去掉每个字符串尾部
的空白字符，或是选出所有包含给定子串的字符串。

列表推导式和生成器表达时（简写："listcomps" 和 "genexps"）让这些操作更加
简明，这个形式借鉴自函数式程序语言 Haskell（‘https://www.haskell.org/’）
。你可以用以下代码去掉一个字符串流中的所有空白字符:

     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]

你可以加上条件语句 ‘"if"’ 来选取特定的元素:

     stripped_list = [line.strip() for line in line_list
                      if line != ""]

通过列表推导式，你会获得一个 Python 列表；‘stripped_list’ 就是一个包含所
有结果行的列表，并不是迭代器。 生成器表达式会返回一个迭代器，它在必要的
时候计算结果，避免一次性生成所有的值。 这意味着，如果迭代器返回一个无限
数据流或者大量的数据，列表推导式就不太好用了。 这种情况下生成器表达式会
更受青睐。

生成器表达式两边使用圆括号 ("()") ，而列表推导式则使用方括号 ("[]")。生
成器表达式的形式为:

     ( 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 )

再次说明，列表推导式只有两边的括号不一样（方括号而不是圆括号）。

这些生成用于输出的元素会成为 ‘expression’ 的后继值。其中 ‘if’ 语句是可选
的；如果给定的话 ‘expression’ 只会在符合条件时计算并加入到结果中。

生成器表达式总是写在圆括号里面，不过也可以算上调用函数时用的括号。如果你
想即时创建一个传递给函数的迭代器，可以这么写:

     obj_total = sum(obj.count for obj in list_all_objects())

其中 ‘for...in’ 语句包含了将要遍历的序列。这些序列并不必须同样长，因为它
们会从左往右开始遍历，而 `不是' 同时执行。对每个 ‘sequence1’ 中的元素，
‘sequence2’ 会从头开始遍历。‘sequence3’ 会对每个 ‘sequence1’ 和
‘sequence2’ 的元素对开始遍历。

换句话说，列表推导式器是和下面的 Python 代码等价:

     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.

这说明，如果有多个 ‘for...in’ 语句而没有 ‘if’ 语句，输出结果的长度就是所
有序列长度的乘积。如果你的两个列表长度为3，那么输出的列表长度就是9:

     >>> 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)]

为了不让 Python 语法变得含糊，如果 ‘expression’ 会生成元组，那这个元组必
须要用括号括起来。下面第一个列表推导式语法错误，第二个则是正确的:

     # Syntax error
     [x, y for x in seq1 for y in seq2]
     # Correct
     [(x, y) for x in seq1 for y in seq2]


File: python.info,  Node: 生成器,  Next: 内置函数,  Prev: 生成器表达式和列表推导式,  Up: 函式編程 HOWTO

10.5.4 生成器
-------------

生成器是一类用来简化编写迭代器工作的特殊函数。普通的函数计算并返回一个值
，而生成器返回一个能返回数据流的迭代器。

毫无疑问，你已经对如何在 Python 和 C 中调用普通函数很熟悉了，这时候函数
会获得一个创建局部变量的私有命名空间。当函数到达 ‘return’ 表达式时，局部
变量会被销毁然后把返回给调用者。之后调用同样的函数时会创建一个新的私有命
名空间和一组全新的局部变量。但是，如果在退出一个函数时不扔掉局部变量会如
何呢？如果稍后你能够从退出函数的地方重新恢复又如何呢？这就是生成器所提供
的；他们可以被看成可恢复的函数。

这里有简单的生成器函数示例:

     >>> def generate_ints(N):
     ...    for i in range(N):
     ...        yield i

任何包含了 *note yield: 2c7. 关键字的函数都是生成器函数；Python 的 *note
bytecode: 709. 编译器会在编译的时候检测到并因此而特殊处理。

当你调用一个生成器函数，它并不会返回单独的值，而是返回一个支持生成器协议
的生成器对象。当执行 ‘yield’ 表达式时，生成器会输出 ‘i’ 的值，就像
‘return’ 表达式一样。‘yield’ 和 ‘return’ 最大的区别在于，到达 ‘yield’ 的
时候生成器的执行状态会挂起并保留局部变量。在下一次调用生成器 *note
__next__(): 140e. 方法的时候，函数会恢复执行。

这里有一个 ‘generate_ints()’ 生成器的示例:

     >>> 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

同样，你可以写出 ‘for i in generate_ints(5)’，或者 ‘a, b, c =
generate_ints(3)’。

在生成器函数里面，‘return value’ 会触发从 *note __next__(): 140e. 方法抛
出 ‘StopIteration(value)’ 异常。一旦抛出这个异常，或者函数结束，处理数据
的过程就会停止，生成器也不会再生成新的值。

你可以手动编写自己的类来达到生成器的效果，把生成器的所有局部变量作为实例
的成员变量存储起来。比如，可以这么返回一个整数列表：把 ‘self.count’ 设为
0，然后通过 ‘count`()’。然而，对于一个中等复杂程度的生成器，写出一个相应
的类可能会相当繁杂。

包含在 Python 库中的测试套件 Lib/test/test_generators.py(1) 里有很多非常
有趣的例子。这里是一个用生成器实现树的递归中序遍历示例。:

     # 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

另外两个 ‘test_generators.py’ 中的例子给出了 N 皇后问题（在 NxN 的棋盘上
放置 N 个皇后，任何一个都不能吃掉另一个），以及马的遍历路线（在NxN 的棋
盘上给马找出一条不重复的走过所有格子的路线）的解。

* Menu:

* 向生成器传递值::

   ---------- Footnotes ----------

   (1) 
https://github.com/python/cpython/tree/3.9/Lib/test/test_generators.py


File: python.info,  Node: 向生成器传递值,  Up: 生成器

10.5.4.1 向生成器传递值
.......................

在 Python 2.4 及之前的版本中，生成器只产生输出。一旦调用生成器的代码创建
一个迭代器，就没有办法在函数恢复执行的时候向它传递新的信息。你可以设法实
现这个功能，让生成器引用一个全局变量或者一个调用者可以修改的可变对象，但
是这些方法都很繁杂。

在 Python 2.5 里有一个简单的将值传递给生成器的方法。*note yield: 2c7. 变
成了一个表达式，返回一个可以赋给变量或执行操作的值:

     val = (yield i)

我建议你在处理 ‘yield’ 表达式返回值的时候， `总是' 两边写上括号，就像上
面的例子一样。括号并不总是必须的，但是比起记住什么时候需要括号，写出来会
更容易一点。

（ PEP 342(1) 解释了具体的规则，也就是 ‘yield’ 表达式必须括起来，除非是
出现在最顶级的赋值表达式的右边。这意味着你可以写 ‘val = yield i’，但是必
须在操作的时候加上括号，就像‘‘val = (yield i) + 12‘‘）

可以调用 ‘send(value)()’ <generator.send> 方法向生成器发送值。这个方法会
恢复执行生成器的代码，然后 ‘yield’ 表达式返回特定的值。如果调用普通的
‘__next__`方法，``yield`()’ 会返回 ‘None’.

这里有一个简单的每次加1的计数器，并允许改变内部计数器的值。

     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

这是改变计数器的一个示例

     >>> 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

因为 ‘yield’ 很多时候会返回 ‘None’，所以你应该总是检查这个情况。不要在表
达式中使用 ‘yield’ 的值，除非你确定 *note send(): 15cd. 是唯一的用来恢复
你的生成器函数的方法。

除了 *note send(): 15cd. 之外，生成器还有两个其他的方法:

   * *note throw(type, value=None, traceback=None): ff8. 用于在生成器内
     部抛出异常；这个异常会在生成器暂停执行的时候由 ‘yield’ 表达式抛出。

   * *note generator.close(): 15d0. 会在生成器内部抛出 *note
     GeneratorExit: df8. 异常来结束迭代。当接收到这个异常时，生成器的代
     码会抛出 *note GeneratorExit: df8. 或者 *note StopIteration: 581.；
     捕捉这个异常作其他处理是非法的，并会出发 *note RuntimeError: 3dc.。
     *note close(): 15d0. 也会在 Python 垃圾回收器回收生成器的时候调用。

     如果你要在 *note GeneratorExit: df8. 发生的时候清理代码，我建议使用
     ‘try: ... finally:’ 组合来代替 *note GeneratorExit: df8.。

这些改变的累积效应是，让生成器从单向的信息生产者变成了既是生产者，又是消
费者。

生成器也可以成为 `协程' ，一种更广义的子过程形式。子过程可以从一个地方进
入，然后从另一个地方退出（从函数的顶端进入，从 ‘return’ 语句退出），而协
程可以进入，退出，然后在很多不同的地方恢复（‘yield’ 语句）。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0342


File: python.info,  Node: 内置函数,  Next: itertools 模块,  Prev: 生成器,  Up: 函式編程 HOWTO

10.5.5 内置函数
---------------

我们可以看看迭代器常常用到的函数的更多细节。

Python 内置的两个函数 *note map(): cf7. 和 *note filter(): cf8. 复制了生
成器表达式的两个特性:

*note map(f, iterA, iterB, ...): cf7. 返回一个遍历序列的迭代器

     ‘f(iterA[0], iterB[0]), f(iterA[1], iterB[1]), f(iterA[2],
     iterB[2]), ...’.

          >>> def upper(s):
          ...     return s.upper()

          >>> list(map(upper, ['sentence', 'fragment']))
          ['SENTENCE', 'FRAGMENT']
          >>> [upper(s) for s in ['sentence', 'fragment']]
          ['SENTENCE', 'FRAGMENT']

你当然也可以用列表推导式达到同样的效果。

*note filter(predicate, iter): cf8. 返回一个遍历序列中满足指定条件的元素
的迭代器，和列表推导式的功能相似。 `predicate' （谓词）是一个在特定条件
下返回真值的函数；要使用函数 *note filter(): cf8.，谓词函数必须只能接受
一个参数。

     >>> def is_even(x):
     ...     return (x % 2) == 0

     >>> list(filter(is_even, range(10)))
     [0, 2, 4, 6, 8]

这也可以写成列表推导式:

     >>> list(x for x in range(10) if is_even(x))
     [0, 2, 4, 6, 8]

*note enumerate(iter, start=0): ea7. 计数可迭代对象中的元素，然后返回包
含每个计数（从 `start' 开始）和元素两个值的元组。:

     >>> for item in enumerate(['subject', 'verb', 'object']):
     ...     print(item)
     (0, 'subject')
     (1, 'verb')
     (2, 'object')

*note enumerate(): ea7. 常常用于遍历列表并记录达到特定条件时的下标:

     f = open('data.txt', 'r')
     for i, line in enumerate(f):
         if line.strip() == '':
             print('Blank line at line #%i' % i)

*note sorted(iterable, key=None, reverse=False): 546. 会将 iterable 中的
元素收集到一个列表中，然后排序并返回结果。其中 `key' 和 `reverse' 参数会
传递给所创建列表的 *note sort(): 547. 方法。:

     >>> 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]

（对排序更详细的讨论可参见 *note 如何排序: 1737.。）

内置函数 *note any(iter): e49. 和 *note all(iter): e4a. 会查看一个可迭代
对象内容的逻辑值。*note any(): e49. 在可迭代对象中任意一个元素为真时返回
‘True’，而 *note all(): e4a. 在所有元素为真时返回 ‘True’:

     >>> 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

*note zip(iterA, iterB, ...): cfc. 从每个可迭代对象中选取单个元素组成列
表并返回:

     zip(['a', 'b', 'c'], (1, 2, 3)) =>
       ('a', 1), ('b', 2), ('c', 3)

它并不会在内存创建一个列表并因此在返回前而耗尽输入的迭代器；相反，只有在
被请求的时候元组才会创建并返回。（这种行为的技术术语叫惰性计算，参见
lazy evaluation(1).）

这个迭代器设计用于长度相同的可迭代对象。如果可迭代对象的长度不一致，返回
的数据流的长度会和最短的可迭代对象相同

     zip(['a', 'b'], (1, 2, 3)) =>
       ('a', 1), ('b', 2)

然而，你应该避免这种情况，因为所有从更长的迭代器中取出的元素都会被丢弃。
这意味着之后你也无法冒着跳过被丢弃元素的风险来继续使用这个迭代器。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Lazy_evaluation


File: python.info,  Node: itertools 模块,  Next: functools 模块,  Prev: 内置函数,  Up: 函式編程 HOWTO

10.5.6 itertools 模块
---------------------

*note itertools: a3. 模块包含很多常用的迭代器以及用来组合迭代器的函数。
本节会用些小的例子来介绍这个模块的内容。

这个模块里的函数大致可以分为几类：

   * 从已有的迭代器创建新的迭代器的函数。

   * 接受迭代器元素作为参数的函数。

   * 选取部分迭代器输出的函数。

   * 给迭代器输出分组的函数。

* Menu:

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


File: python.info,  Node: 创建新的迭代器,  Next: 对元素使用函数,  Up: itertools 模块

10.5.6.1 创建新的迭代器
.......................

*note itertools.count(start, step): ce5. 返回一个等分的无限数据流。初始
值默认为0，间隔默认为1，你也选择可以指定初始值和间隔:

     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, ...

*note itertools.cycle(iter): 1c9a. 保存一份所提供的可迭代对象的副本，并
返回一个能产生整个可迭代对象序列的新迭代器。新迭代器会无限重复这些元素。
:

     itertools.cycle([1, 2, 3, 4, 5]) =>
       1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ...

*note itertools.repeat(elem, [n]): 11e7. 返回 `n' 次所提供的元素，当 `n'
不存在时，返回无数次所提供的元素。

     itertools.repeat('abc') =>
       abc, abc, abc, abc, abc, abc, abc, abc, abc, abc, ...
     itertools.repeat('abc', 5) =>
       abc, abc, abc, abc, abc

*note itertools.chain(iterA, iterB, ...): 1738. 接受任意数量的可迭代对象
作为输入，首先返回第一个迭代器的所有元素，然后是第二个的所有元素，如此一
直进行下去，直到消耗掉所有输入的可迭代对象。

     itertools.chain(['a', 'b', 'c'], (1, 2, 3)) =>
       a, b, c, 1, 2, 3

*note itertools.islice(iter, [start], stop, [step]): 4a8. 返回一个所输入
的迭代器切片的数据流。如果只单独给定 `stop' 参数的话，它会返回从起始算起
`stop' 个数量的元素。如果你提供了起始下标 `start'，你会得到 `stop-start'
个元素；如果你给定了 `step' 参数，数据流会跳过相应的元素。和 Python 里的
字符串和列表切片不同，你不能在 `start', `stop' 或者 `step' 这些参数中使
用负数。:

     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

*note itertools.tee(iter, [n]): 1c9f. 可以复制一个迭代器；它返回 `n' 个
能够返回源迭代器内容的独立迭代器。如果你不提供参数 `n'，默认值为 2。复制
迭代器需要保存源迭代器的一部分内容，因此在源迭代器比较大的时候会显著地占
用内存；同时，在所有新迭代器中，有一个迭代器会比其他迭代器占用更多的内存
。

     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, ...


File: python.info,  Node: 对元素使用函数,  Next: 选择元素,  Prev: 创建新的迭代器,  Up: itertools 模块

10.5.6.2 对元素使用函数
.......................

*note operator: c2. 模块包含一组对应于 Python 操作符的函数。比如 *note
operator.add(a, b): 1cc2. （把两个数加起来），*note operator.ne(a, b):
1cb2. （和 ‘a != b’ 相同），以及 *note operator.attrgetter(’id’): 80a. （
返回获取 ‘.id’ 属性的可调用对象）。

*note itertools.starmap(func, iter): b05. 假定可迭代对象能够返回一个元组
的流，并且利用这些元组作为参数来调用 `func':

     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


File: python.info,  Node: 选择元素,  Next: 组合函数,  Prev: 对元素使用函数,  Up: itertools 模块

10.5.6.3 选择元素
.................

另外一系列函数根据谓词选取一个迭代器中元素的子集。

*note itertools.filterfalse(predicate, iter): 1722. 和 *note filter():
cf8. 相反，返回所有让 predicate 返回 false 的元素:

     itertools.filterfalse(is_even, itertools.count()) =>
       1, 3, 5, 7, 9, 11, 13, 15, ...

*note itertools.takewhile(predicate, iter): 1c9e. 返回一直让 predicate 返
回 true 的元素。一旦 predicate 返回 false，迭代器就会发出终止结果的信号
。:

     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

*note itertools.dropwhile(predicate, iter): 1c9c. 在 predicate 返回 true
的时候丢弃元素，并且返回可迭代对象的剩余结果。:

     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, ...

*note itertools.compress(data, selectors): ce4. 接受两个迭代器，然后返回
`data' 中使相应地 `selector' 中的元素为真的元素；它会在任一个迭代器耗尽
的时候停止:

     itertools.compress([1, 2, 3, 4, 5], [True, True, False, False, True]) =>
        1, 2, 5


File: python.info,  Node: 组合函数,  Next: 为元素分组,  Prev: 选择元素,  Up: itertools 模块

10.5.6.4 组合函数
.................

*note itertools.combinations(iterable, r): d6e. 返回一个迭代器，它能给出
输入迭代器中所包含的元素的所有可能的 `r' 元元组的组合。:

     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)

每个元组中的元素保持着 `可迭代对象' 返回他们的顺序。例如，在上面的例子中
数字 1 总是会在 2, 3, 4 或 5 前面。一个类似的函数，*note
itertools.permutations(iterable, r=None): fc9.，取消了保持顺序的限制，返
回所有可能的长度为 `r' 的排列:

     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)

如果你不提供 `r' 参数的值，它会使用可迭代对象的长度，也就是说会排列所有
的元素。

注意这些函数会输出所有可能的位置组合，并不要求 `可迭代对象' 的内容不重复
:

     itertools.permutations('aba', 3) =>
       ('a', 'b', 'a'), ('a', 'a', 'b'), ('b', 'a', 'a'),
       ('b', 'a', 'a'), ('a', 'a', 'b'), ('a', 'b', 'a')

同一个元组 ‘('a', 'a', 'b')’ 出现了两次，但是两个 ’a’ 字符来自不同的位置
。

*note itertools.combinations_with_replacement(iterable, r): ce3. 函数放
松了一个不同的限制：元组中的元素可以重复。从概念讲，为每个元组第一个位置
选取一个元素，然后在选择第二个元素前替换掉它。:

     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)


File: python.info,  Node: 为元素分组,  Prev: 组合函数,  Up: itertools 模块

10.5.6.5 为元素分组
...................

我要讨论的最后一个函数，*note itertools.groupby(iter,key_func=None):
1c9d.，是最复杂的函数。 ‘key_func(elem)’ 是一个可以对迭代器返回的每个元
素计算键值的函数。 如果你不提供这个键值函数，它就会简化成每个元素自身。

*note groupby(): 1c9d. 从所依据的可迭代对象中连续地收集具有相同值的元素
，然后返回一个长度为2的元组的数据流, 每个元组包含键值以及对应这个键值的
元素所组成的迭代器。

     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')

*note groupby(): 1c9d. 假定了所依据的可迭代对象的内容已经根据键值排序。
注意，返回的迭代器也会使用所依据的可迭代对象，所以在请求迭代器 2和相应的
键之前你必须先消耗迭代器 1 的结果。


File: python.info,  Node: functools 模块,  Next: 小函数和 lambda 表达式,  Prev: itertools 模块,  Up: 函式編程 HOWTO

10.5.7 functools 模块
---------------------

Python 2.5 中的 *note functools: 83. 模块包含了一些高阶函数。 `高阶函数'
接受一个或多个函数作为输入，返回新的函数。 这个模块中最有用的工具是
*note functools.partial(): 8b5. 函数。

对于用函数式风格编写的程序，有时你会希望通过给定部分参数，将已有的函数构
变形称新的函数。考虑一个 Python 函数 ‘f(a, b, c)’；你希望创建一个和
‘f(1, b, c)’ 等价的新函数 ‘g(b, c)’；也就是说你给定了 ‘f()’ 的一个参数的
值。这就是所谓的“部分函数应用”。

*note partial(): 8b5. 接受参数 ‘(function, arg1, arg2, ...,
kwarg1=value1, kwarg2=value2)’。它会返回一个可调用的对象，所以你能够直接
调用这个结果以使用给定参数的 ‘function’。

这里有一个很小但很现实的例子:

     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')

*note functools.reduce(func, iter, [initial_value]): d37. 持续地在可迭代
对象的所有元素上执行操作，因此它不能够用在无限的可迭代对象上。`func' 必
须是一个接受两个元素并返回一个值的函数。*note functools.reduce(): d37. 接
受迭代器返回的前两个元素 A 和 B 并计算 ‘func(A, B)’ 。然后它会请求第三个
元素，C，计算 ‘func(func(A, B), C)’，然后把这个结果再和第四个元素组合并
返回，如此继续下去直到消耗整个可迭代对象。如果输入的可迭代对象完全不返回
任何值，*note TypeError: 1fe. 异常就会抛出。如果提供了初值(initial
value)，它会被用作起始值，也就是先计算 ‘func(initial_value, A)’ 。:

     >>> 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

如果你在 *note functools.reduce(): d37. 中使用 *note operator.add():
1cc2.，你就会把可迭代对象中的所有元素加起来.这种情况非常常见, 所以
Python 有一个特殊的内置函数 *note sum(): 316.:

     >>> import functools, operator
     >>> functools.reduce(operator.add, [1, 2, 3, 4], 0)
     10
     >>> sum([1, 2, 3, 4])
     10
     >>> sum([])
     0

不过, 对于很多使用 *note functools.reduce(): d37. 的情形, 使用明显的
*note for: cfa. 循环会更清晰:

     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

一个相关的函数是 *note itertools.accumulate(iterable,
func=operator.add): 30e. 。它执行同样的计算, 不过相对于只返回最终结果，
‘accumulate()’ 会返回一个迭代器来输出所有中间结果:

     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

* Menu:

* operator 模块::


File: python.info,  Node: operator 模块,  Up: functools 模块

10.5.7.1 operator 模块
......................

前面已经提到了 *note operator: c2. 模块。它包含一系列对应于 Python 操作
符的函数。在函数式风格的代码中，这些函数通常很有用，可以帮你省下不少时间
，避免写一些琐碎的仅仅执行一个简单操作的函数。

这个模块里的一些函数：

   * 数学运算： ‘add()’，‘sub()’，‘mul()’，‘floordiv()’，‘abs()’， ...

   * 逻辑运算： ‘not_()’，‘truth()’。

   * 位运算： ‘and_()’，‘or_()’，‘invert()’。

   * 比较： ‘eq()’，‘ne()’，‘lt()’，‘le()’，‘gt()’，和 ‘ge()’。

   * 确认对象： ‘is_()’，‘is_not()’。

全部函数列表可以参考 operator 模块的文档。


File: python.info,  Node: 小函数和 lambda 表达式,  Next: 修订记录和致谢,  Prev: functools 模块,  Up: 函式編程 HOWTO

10.5.8 小函数和 lambda 表达式
-----------------------------

编写函数式风格程序时，你会经常需要很小的函数，作为谓词函数或者以某种方式
来组合元素。

如果合适的 Python 内置的或者其他模块中的函数，你就一点也不需要定义新的函
数:

     stripped_lines = [line.strip() for line in lines]
     existing_files = filter(os.path.exists, file_list)

如果不存在你需要的函数，你就必须自己编写。一个编写小函数的方式是使用
*note lambda: cf9. 表达式。‘lambda’ 接受一组参数以及组合这些参数的表达式
，它会创建一个返回表达式值的匿名函数:

     adder = lambda x, y: x+y

     print_assign = lambda name, value: name + '=' + str(value)

另一种替代方案就是通常的使用 ‘def’ 语句来定义函数:

     def adder(x, y):
         return x + y

     def print_assign(name, value):
         return name + '=' + str(value)

哪一种更受青睐呢？这是一个风格问题；我通常的做法是避免使用 ‘lambda’。

我这么偏好的一个原因是，‘lambda’ 能够定义的函数非常受限。函数的结果必须
能够作为单独的表达式来计算，这意味着你不能使用多路 ‘if... elif... else’
比较，或者 ‘try... except’ 语句。如果你尝试在 ‘lambda’ 语句中做太多事情
，你最终会把表达式过于复杂以至于难以阅读。你能快速的说出下面的代码做了什
么事情吗？:

     import functools
     total = functools.reduce(lambda a, b: (0, a[1] + b[1]), items)[1]

你可以弄明白，不过要花上时间来理清表达式来搞清楚发生了什么。使用一个简短
的嵌套的 ‘def’ 语句可以让情况变得更好:

     import functools
     def combine(a, b):
         return 0, a[1] + b[1]

     total = functools.reduce(combine, items)[1]

如果我仅仅使用一个 ‘for’ 循环会更好:

     total = 0
     for a, b in items:
         total += b

或者使用内置的 *note sum(): 316. 和一个生成器表达式:

     total = sum(b for a, b in items)

许多使用 *note functools.reduce(): d37. 的情形可以更清晰地写成 ‘for’ 循
环的形式。

Fredrik Lundh 曾经建议以下一组规则来重构 ‘lambda’ 的使用:

  1. 写一个 lambda 函数。

  2. 写一句注释来说明这个 lambda 究竟干了什么。

  3. 研究一会这个注释，然后想出一个抓住注释本质的名字。

  4. 用这个名字，把这个 lambda 改写成 def 语句。

  5. 把注释去掉。

我非常喜欢这些规则，不过你完全有权利争辩这种消除 lambda 的风格是不是更好
。


File: python.info,  Node: 修订记录和致谢,  Next: 引用文献,  Prev: 小函数和 lambda 表达式,  Up: 函式編程 HOWTO

10.5.9 修订记录和致谢
---------------------

作者要感谢以下人员对本文各种草稿给予的建议，更正和协助：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 版: 添加了有关 ‘functional’ 模块的小节，由 Collin Winter 撰写；添加
了有关 operator 模块的简短小节；其他少量修改。


File: python.info,  Node: 引用文献,  Prev: 修订记录和致谢,  Up: 函式編程 HOWTO

10.5.10 引用文献
----------------

* Menu:

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


File: python.info,  Node: 通用文献,  Next: Python 相关,  Up: 引用文献

10.5.10.1 通用文献
..................

`Structure and Interpretation of Computer Programs', Harold Abelson,
Gerald Jay Sussman 和 Julie Sussman 著。全文可见
‘https://mitpress.mit.edu/sicp/’ 。在这部计算机科学的经典教科书中，第二
和第三章讨论了使用序列和流来组织程序内部的数据传递。书中的示例采用
Scheme 语言，但其中这些章节中描述的很多设计方法同样适用于函数式风格的
Python 代码。

‘http://www.defmacro.org/ramblings/fp.html’: 一个使用 Java 示例的函数式
编程的总体介绍，有很长的历史说明。

‘https://en.wikipedia.org/wiki/Functional_programming’: 一般性的函数式编
程的 Wikipedia 条目。

‘https://en.wikipedia.org/wiki/Coroutine’: 协程条目。

‘https://en.wikipedia.org/wiki/Currying’: 函数柯里化条目。


File: python.info,  Node: Python 相关,  Next: Python 文档,  Prev: 通用文献,  Up: 引用文献

10.5.10.2 Python 相关
.....................

‘http://gnosis.cx/TPiP/’：David Mertz 书中的第一章 ‘Text Processing in
Python’，"Utilizing Higher-Order Functions in Text Processing" 标题部分
讨论了文本处理的函数式编程。

Mertz 还在 IBM 的 DeveloperWorks 站点上针对函数式编程撰写了一系列共 3 篇
文章；参见 part 1(1), part 2(2) 和 part 3(3),

   ---------- Footnotes ----------

   (1) https://developer.ibm.com/articles/l-prog/

   (2) https://developer.ibm.com/tutorials/l-prog2/

   (3) https://developer.ibm.com/tutorials/l-prog3/


File: python.info,  Node: Python 文档,  Prev: Python 相关,  Up: 引用文献

10.5.10.3 Python 文档
.....................

*note itertools: a3. 模块文档。

*note functools: 83. 模块文档。

*note operator: c2. 模块文档。

PEP 289(1): "Generator Expressions"

PEP 342(2): "Coroutines via Enhanced Generators" 描述了 Python 2.5 中新
的生成器特性。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0289

   (2) https://www.python.org/dev/peps/pep-0342


File: python.info,  Node: 如何使用 Logging 模組,  Next: 日志操作手册,  Prev: 函式編程 HOWTO,  Up: Python 如何達成任務

10.6 如何使用 Logging 模組
==========================


作者: 原文作者 Vinay Sajip <vinay_sajip at red-dove dot com>

* Menu:

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


File: python.info,  Node: 基礎 Logging 指南,  Next: 进阶日志教程,  Up: 如何使用 Logging 模組

10.6.1 基礎 Logging 指南
------------------------

軟體執行時，追蹤有什麼事件發生的動作稱為 Logging。軟體開發者會使用
Logging 這樣的機制是因為想知道在運行過程中是否有特定的事件發生。事件會被
一段訊息所描述。這段訊息可能包含一些因為此事件發生而改變的資料。開發者也
可以指派事件的重要程度，重要程度有時候也會被稱作 `程度' 或是 `嚴重性' 。

* Menu:

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


File: python.info,  Node: 什麼時候使用 logging,  Next: 一个简单的例子<2>,  Up: 基礎 Logging 指南

10.6.1.1 什麼時候使用 logging
.............................

对于简单的日志使用来说日志功能提供了一系列便利的函数。它们是 *note
debug(): 21e1.，*note info(): 220c.，*note warning(): 221e.，*note
error(): 221f. 和 *note critical(): 2220.。想要决定何时使用日志，请看下
表，其中显示了对于每个通用任务集合来说最好的工具。

你想要执行的任务                          此任务的最好的工具
                                          
-------------------------------------------------------------------------------------
                                          
对于命令行或程序的应用，结果显示在控制    *note print(): 971.
台。                                      

在对程序的普通操作发生时提交事件报告(比   *note logging.info(): 220c. 函数(当有诊
如：状态监控和错误调查)                   断目的需要详细输出信息时使用
                                          *note logging.debug(): 21e1. 函数)
                                          
                                          
提出一个警告信息基于一个特殊的运行时事    *note warnings.warn(): f1a. 位于代码库中
件                                        ，该事件是可以避免的，需要修改客户端应用
                                          以消除告警
                                          
                                          *note logging.warning(): 221e. 不需要修
                                          改客户端应用，但是该事件还是需要引起关注
                                          
                                          
对一个特殊的运行时事件报告错误            引发异常
                                          
                                          
报告错误而不引发异常(如在长时间运行中的   *note logging.error(): 221f,
服务端进程的错误处理)                     *note logging.exception(): 2221. 或
                                          *note logging.critical(): 2220. 分别适用
                                          于特定的错误及应用领域
                                          

日志功能应以所追踪事件级别或严重性而定。各级别适用性如下（以严重性递增）
：

级别               何时使用
                   
---------------------------------------------------------------------
                   
‘DEBUG’            细节信息，仅当诊断问题时适用。
                   
                   
‘INFO’             确认程序按预期运行。
                   
                   
‘WARNING’          表明有已经或即将发生的意外（例如：磁盘空间不足
                   ）。程序仍按预期进行。
                   
                   
‘ERROR’            由于严重的问题，程序的某些功能已经不能正常执行
                   
                   
‘CRITICAL’         严重的错误，表明程序已不能继续执行
                   

默认的级别是 ‘WARNING’，意味着只会追踪该级别及以上的事件，除非更改日志配
置。

所追踪事件可以以不同形式处理。最简单的方式是输出到控制台。另一种常用的方
式是写入磁盘文件。


File: python.info,  Node: 一个简单的例子<2>,  Next: 记录日志到文件,  Prev: 什麼時候使用 logging,  Up: 基礎 Logging 指南

10.6.1.2 一个简单的例子
.......................

一个非常简单的例子:

     import logging
     logging.warning('Watch out!')  # will print a message to the console
     logging.info('I told you so')  # will not print anything

如果你在命令行中输入这些代码并运行，你将会看到：

     WARNING:root:Watch out!

输出到命令行。‘INFO’ 消息并没有出现，因为默认级别是 ‘WARNING’ 。打印的信
息包含事件的级别以及在日志调用中的对于事件的描述，例如 “Watch out!”。暂
时不用担心 “root” 部分：之后会作出解释。输出格式可按需要进行调整，格式化
选项同样会在之后作出解释。


File: python.info,  Node: 记录日志到文件,  Next: 从多个模块记录日志,  Prev: 一个简单的例子<2>,  Up: 基礎 Logging 指南

10.6.1.3 记录日志到文件
.......................

一种非常常见的情况是将日志事件记录到文件，让我们继续往下看。请确认启动新
的Python 解释器，不要在上一个环境中继续操作:

     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ö')

3.9 版更變: 增加了 `encoding' 参数。在更早的 Python 版本中或没有指定时，
编码会用 *note open(): 16f. 使用的默认值。尽管在上面的例子中没有展示，但
也可以传入一个决定如何处理编码错误的 `errors' 参数。可使用的值和默认值，
请参照 *note open(): 16f. 的文档。

现在，如果我们打开日志文件，我们应当能看到日志信息：

     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ö

该示例同样展示了如何设置日志追踪级别的阈值。该示例中，由于我们设置的阈值
是 ‘DEBUG’，所有信息都将被打印。

如果你想从命令行设置日志级别，例如：

     --log=INFO

并且在一些 `loglevel' 变量中你可以获得 ‘--log’ 命令的参数，你可以使用:

     getattr(logging, loglevel.upper())

通过 `level' 参数获得你将传递给 *note basicConfig(): 311. 的值。你需要对
用户输入数据进行错误排查，可如下例:

     # 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, ...)

对 *note basicConfig(): 311. 的调用应该在 *note debug(): 21e1. ， *note
info(): 220c. 等的前面。因为它被设计为一次性的配置，只有第一次调用会进行
操作，随后的调用不会产生有效操作。

如果多次运行上述脚本，则连续运行的消息将追加到文件 `example.log' 。 如果
你希望每次运行重新开始，而不是记住先前运行的消息，则可以通过将上例中的调
用更改为来指定 `filemode' 参数:

     logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)

输出将与之前相同，但不再追加进日志文件，因此早期运行的消息将丢失。


File: python.info,  Node: 从多个模块记录日志,  Next: 记录变量数据,  Prev: 记录日志到文件,  Up: 基礎 Logging 指南

10.6.1.4 从多个模块记录日志
...........................

如果你的程序包含多个模块，这里有一个如何组织日志记录的示例:

     # 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()

     # mylib.py
     import logging

     def do_something():
         logging.info('Doing something')

如果你运行 `myapp.py' ，你应该在 `myapp.log' 中看到：

     INFO:root:Started
     INFO:root:Doing something
     INFO:root:Finished

这是你期待看到的。 你可以使用 `mylib.py' 中的模式将此概括为多个模块。 请
注意，对于这种简单的使用模式，除了查看事件描述之外，你不能通过查看日志文
件来了解应用程序中消息的 `来源' 。 如果要跟踪消息的位置，则需要参考教程
级别以外的文档 —— 请参阅 *note 进阶日志教程: c44. 。


File: python.info,  Node: 记录变量数据,  Next: 更改显示消息的格式,  Prev: 从多个模块记录日志,  Up: 基礎 Logging 指南

10.6.1.5 记录变量数据
.....................

要记录变量数据，请使用格式字符串作为事件描述消息，并附加传入变量数据作为
参数。 例如:

     import logging
     logging.warning('%s before you %s', 'Look', 'leap!')

将显示：

     WARNING:root:Look before you leap!

如你所见，将可变数据合并到事件描述消息中使用旧的 %-s形式的字符串格式化。
这是为了向后兼容：logging 包的出现时间早于较新的格式化选项例如 *note
str.format(): 5d4. 和 *note string.Template: 4f0.。 这些较新格式化选项
`是' 受支持的，但探索它们超出了本教程的范围：有关详细信息，请参阅 *note
生效于整个应用程序的格式化样式: 2204.。


File: python.info,  Node: 更改显示消息的格式,  Next: 在消息中显示日期/时间,  Prev: 记录变量数据,  Up: 基礎 Logging 指南

10.6.1.6 更改显示消息的格式
...........................

要更改用于显示消息的格式，你需要指定要使用的格式:

     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')

这将输出：

     DEBUG:This message should appear on the console
     INFO:So should this
     WARNING:And this, too

请注意，前面示例中出现的 “root” 已消失。 对于可以出现在格式字符串中的全
部内容，你可以参考以下文档 *note LogRecord 属性: 2202. ，但为了简单使用
，你只需要 `levelname' （严重性）， `message' （事件描述，包括可变数据）
，也许在事件发生时显示。 这将在下一节中介绍。


File: python.info,  Node: 在消息中显示日期/时间,  Next: 后续步骤,  Prev: 更改显示消息的格式,  Up: 基礎 Logging 指南

10.6.1.7 在消息中显示日期/时间
..............................

要显示事件的日期和时间，你可以在格式字符串中放置 ’%(asctime)s’

     import logging
     logging.basicConfig(format='%(asctime)s %(message)s')
     logging.warning('is when this event was logged.')

应该打印这样的东西：

     2010-12-12 11:41:42,612 is when this event was logged.

日期/时间显示的默认格式（如上所示）类似于 ISO8601 或 RFC 3339(1) 。 如果
你需要更多地控制日期/时间的格式，请为 ‘basicConfig’ 提供 `datefmt' 参数
，如下例所示:

     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.')

这会显示如下内容：

     12/12/2010 11:46:36 AM is when this event was logged.

`datefmt' 参数的格式与 *note time.strftime(): c37. 支持的格式相同。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc3339.html


File: python.info,  Node: 后续步骤,  Prev: 在消息中显示日期/时间,  Up: 基礎 Logging 指南

10.6.1.8 后续步骤
.................

基本教程到此结束。 它应该足以让你启动并运行日志记录。 logging 包提供了更
多功能，但为了充分利用它，你需要花更多的时间来阅读以下部分。 如果你准备
好了，可以拿一些你最喜欢的饮料然后继续。

如果你的日志记录需求很简单，那么使用上面的示例将日志记录合并到你自己的脚
本中，如果你遇到问题或者不理解某些内容，请在 comp.lang.python Usenet 组
上发布一个问题（在
‘https://groups.google.com/forum/#!forum/comp.lang.python’ ） ，你将在短
时间内得到帮助。

还不够？ 你可以继续阅读接下来的几个部分，这些部分提供了比上面基本部分更
高级或深入的教程。 之后，你可以看一下 *note 日志操作手册: c45. 。


File: python.info,  Node: 进阶日志教程,  Next: 日志级别<2>,  Prev: 基礎 Logging 指南,  Up: 如何使用 Logging 模組

10.6.2 进阶日志教程
-------------------

日志库采用模块化方法，并提供几类组件：记录器、处理器、过滤器和格式器。

   * 记录器暴露了应用程序代码直接使用的接口。

   * 处理器将日志记录（由记录器创建）发送到适当的目标。

   * 过滤器提供了更精细的附加功能，用于确定要输出的日志记录。

   * 格式器指定最终输出中日志记录的样式。

日志事件信息在 *note LogRecord: 9ec. 实例中的记录器、处理器、过滤器和格
式器之间传递。

通过调用 *note Logger: 4ad. 类（以下称为 `loggers' ， 记录器）的实例来执
行日志记录。 每个实例都有一个名称，它们在概念上以点（句点）作为分隔符排
列在命名空间的层次结构中。 例如，名为 ’scan’ 的记录器是记录器
’scan.text’ ，’scan.html’ 和 ’scan.pdf’ 的父级。 记录器名称可以是你想要
的任何名称，并指示记录消息源自的应用程序区域。

在命名记录器时使用的一个好习惯是在每个使用日志记录的模块中使用模块级记录
器，命名如下:

     logger = logging.getLogger(__name__)

这意味着记录器名称跟踪包或模块的层次结构，并且直观地从记录器名称显示记录
事件的位置。

记录器层次结构的根称为根记录器。 这是函数 *note debug(): 21e1. 、 *note
info(): 220c. 、 *note warning(): 221e. 、 *note error(): 221f. 和 *note
critical(): 2220. 使用的记录器，它们就是调用了根记录器的同名方法。 函数
和方法具有相同的签名。 根记录器的名称在输出中打印为 ’root’ 。

当然，可以将消息记录到不同的地方。 软件包中的支持包含，用于将日志消息写
入文件、 HTTP GET/POST 位置、通过 SMTP 发送电子邮件、通用套接字、队列或
特定于操作系统的日志记录机制（如 syslog 或 Windows NT 事件日志）。 目标
由 `handler' 类提供。 如果你有任何内置处理器类未满足的特殊要求，则可以创
建自己的日志目标类。

默认情况下，没有为任何日志消息设置目标。 你可以使用 *note basicConfig():
311. 指定目标（例如控制台或文件），如教程示例中所示。 如果你调用函数
*note debug(): 21e1. 、 *note info(): 220c. 、 *note warning(): 221e. 、
*note error(): 221f. 和 *note critical(): 2220. ，它们将检查是否有设置目
标；如果没有设置，将在委托给根记录器进行实际的消息输出之前设置目标为控制
台（ ‘sys.stderr’ ）并设置显示消息的默认格式。

由 *note basicConfig(): 311. 设置的消息默认格式为：

     severity:logger name:message

你可以通过使用 `format' 参数将格式字符串传递给 *note basicConfig(): 311.
来更改此设置。有关如何构造格式字符串的所有选项，请参阅 *note 格式器对象:
2200. 。

* Menu:

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


File: python.info,  Node: 记录流程,  Next: 记录器,  Up: 进阶日志教程

10.6.2.1 记录流程
.................

记录器和处理器中的日志事件信息流程如下图所示。

[python-figures/logging_flow]

File: python.info,  Node: 记录器,  Next: 处理器,  Prev: 记录流程,  Up: 进阶日志教程

10.6.2.2 记录器
...............

*note Logger: 4ad. 对象有三重任务。首先，它们向应用程序代码公开了几种方
法，以便应用程序可以在运行时记录消息。其次，记录器对象根据严重性（默认过
滤工具）或过滤器对象确定要处理的日志消息。第三，记录器对象将相关的日志消
息传递给所有感兴趣的日志处理器。

记录器对象上使用最广泛的方法分为两类：配置和消息发送。

这些是最常见的配置方法：

   * *note Logger.setLevel(): 21da. 指定记录器将处理的最低严重性日志消息
     ，其中 debug 是最低内置严重性级别， critical 是最高内置严重性级别。
     例如，如果严重性级别为 INFO ，则记录器将仅处理 INFO 、 WARNING 、
     ERROR 和 CRITICAL 消息，并将忽略 DEBUG 消息。

   * *note Logger.addHandler(): 21e7. 和 *note Logger.removeHandler():
     21e8. 从记录器对象中添加和删除处理器对象。处理器在以下内容中有更详
     细的介绍 *note 处理器: 4367. 。

   * *note Logger.addFilter(): 21e4. 和 *note Logger.removeFilter():
     21e5. 可以添加或移除记录器对象中的过滤器。 *note 过滤器对象: 2209.
     包含更多的过滤器细节。

你不需要总是在你创建的每个记录器上都调用这些方法。 请参阅本节的最后两段
。

配置记录器对象后，以下方法将创建日志消息：

   * *note Logger.debug(): 801. 、 *note Logger.info(): 21e0. 、 *note
     Logger.warning(): 21e2. 、 *note Logger.error(): 21e3. 和 *note
     Logger.critical(): 800. 都创建日志记录，包含消息和与其各自方法名称
     对应的级别。该消息实际上是一个格式化字符串，它可能包含标题字符串替
     换语法 ‘%s’ 、 ‘%d’ 、 ‘%f’ 等等。其余参数是与消息中的替换字段对应
     的对象列表。关于 ‘**kwargs’ ，日志记录方法只关注 ‘exc_info’ 的关键
     字，并用它来确定是否记录异常信息。

   * *note Logger.exception(): 7ff. 创建与 *note Logger.error(): 21e3. 相
     似的日志信息。 不同之处是， *note Logger.exception(): 7ff. 同时还记
     录当前的堆栈追踪。仅从异常处理程序调用此方法。

   * *note Logger.log(): 7fe. 将日志级别作为显式参数。对于记录消息而言，
     这比使用上面列出的日志级别便利方法更加冗长，但这是使用自定义日志级
     别的方法。

*note getLogger(): 234. 返回对具有指定名称的记录器实例的引用（如果已提供
），或者如果没有则返回 ‘root’ 。名称是以句点分隔的层次结构。多次调用
*note getLogger(): 234. 具有相同的名称将返回对同一记录器对象的引用。在分
层列表中较低的记录器是列表中较高的记录器的子项。例如，给定一个名为 ‘foo’
的记录器，名称为 ‘foo.bar’ 、 ‘foo.bar.baz’ 和 ‘foo.bam’ 的记录器都是
‘foo’ 子项。

记录器具有 `有效等级' 的概念。如果未在记录器上显式设置级别，则使用其父记
录器的级别作为其有效级别。如果父记录器没有明确的级别设置，则检查 `其' 父
级。依此类推，搜索所有上级元素，直到找到明确设置的级别。根记录器始终具有
显式级别集（默认情况下为 ‘WARNING’ ）。在决定是否处理事件时，记录器的有
效级别用于确定事件是否传递给记录器相关的处理器。

子记录器将消息传播到与其父级记录器关联的处理器。因此，不必为应用程序使用
的所有记录器定义和配置处理器。一般为顶级记录器配置处理器，再根据需要创建
子记录器就足够了。（但是，你可以通过将记录器的 `propagate' 属性设置为
‘False’ 来关闭传播。）


File: python.info,  Node: 处理器,  Next: 格式器,  Prev: 记录器,  Up: 进阶日志教程

10.6.2.3 处理器
...............

*note Handler: 21df. 对象负责将适当的日志消息（基于日志消息的严重性）分
派给处理器的指定目标。 *note Logger: 4ad. 对象可以使用 *note
addHandler(): 21e7. 方法向自己添加零个或多个处理器对象。作为示例场景，应
用程序可能希望将所有日志消息发送到日志文件，将错误或更高的所有日志消息发
送到标准输出，以及将所有关键消息发送至一个邮件地址。 此方案需要三个单独
的处理器，其中每个处理器负责将特定严重性的消息发送到特定位置。

标准库包含很多处理器类型（参见 *note 有用的处理器: 4369. ）；教程主要使
用 *note StreamHandler: c46. 和 *note FileHandler: 2245. 。

处理器中很少有方法可供应用程序开发人员使用。使用内置处理器对象（即不创建
自定义处理器）的应用程序开发人员能用到的仅有以下配置方法：

   * ‘setLevel()’ 方法，就像在记录器对象中一样，指定将被分派到适当目标的
     最低严重性。为什么有两个 ‘setLevel()’ 方法？记录器中设置的级别确定
     将传递给其处理器的消息的严重性。每个处理器中设置的级别确定该处理器
     将发送哪些消息。

   * *note setFormatter(): 21f5. 选择一个该处理器使用的 Formatter 对象。

   * *note addFilter(): 21f6. 和 *note removeFilter(): 21f7. 分别在处理
     器上配置和取消配置过滤器对象。

应用程序代码不应直接实例化并使用 *note Handler: 21df. 的实例。 相反，
*note Handler: 21df. 类是一个基类，它定义了所有处理器应该具有的接口，并
建立了子类可以使用（或覆盖）的一些默认行为。


File: python.info,  Node: 格式器,  Next: 配置日志记录,  Prev: 处理器,  Up: 进阶日志教程

10.6.2.4 格式器
...............

格式化器对象配置日志消息的最终顺序、结构和内容。 与 *note
logging.Handler: 21df. 类不同，应用程序代码可以实例化格式器类，但如果应
用程序需要特殊行为，则可能会对格式化器进行子类化定制。构造函数有三个可选
参数 —— 消息格式字符串、日期格式字符串和样式指示符。

 -- 成員函式: logging.Formatter.__init__ (fmt=None, datefmt=None,
          style='%')

如果没有消息格式字符串，则默认使用原始消息。如果没有日期格式字符串，则默
认日期格式为：

     %Y-%m-%d %H:%M:%S

最后加上毫秒数。 ‘style’ 是 ‘％’，’{ ’ 或 ’$’ 之一。 如果未指定，则将使
用 ’％’。

如果 ‘style’ 是 ’％’，则消息格式字符串使用 ‘%(<dictionary key>)s’ 样式字
符串替换；可能的键值在 *note LogRecord 属性: 2202. 中。 如果样式为 ’{’，
则假定消息格式字符串与 *note str.format(): 5d4. （使用关键字参数）兼容，
而如果样式为 ’$’ ，则消息格式字符串应符合 *note
string.Template.substitute(): 1433. 。

3.2 版更變: 添加 ‘style’ 形参。

以下消息格式字符串将以人类可读的格式记录时间、消息的严重性以及消息的内容
，按此顺序:

     '%(asctime)s - %(levelname)s - %(message)s'

格式器通过用户可配置的函数将记录的创建时间转换为元组。 默认情况下，使用
*note time.localtime(): 1080. ；要为特定格式器实例更改此项，请将实例的
‘converter’ 属性设置为与 *note time.localtime(): 1080. 或 *note
time.gmtime(): c11. 具有相同签名的函数。 要为所有格式器更改它，例如，如
果你希望所有记录时间都以 GMT 显示，请在格式器类中设置 ‘converter’ 属性（
对于 GMT 显示，设置为 ‘time.gmtime’ ）。


File: python.info,  Node: 配置日志记录,  Next: 如果没有提供配置会发生什么,  Prev: 格式器,  Up: 进阶日志教程

10.6.2.5 配置日志记录
.....................

开发者可以通过三种方式配置日志记录：

  1. 使用调用上面列出的配置方法的 Python 代码显式创建记录器、处理器和格
     式器。

  2. 创建日志配置文件并使用 *note fileConfig(): 4af. 函数读取它。

  3. 创建配置信息字典并将其传递给 *note dictConfig(): bfe. 函数。

有关最后两个选项的参考文档，请参阅 *note 配置函数: d50. 。 以下示例使用
Python 代码配置一个非常简单的记录器、一个控制台处理器和一个简单的格式器:

     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')

从命令行运行此模块将生成以下输出：

     $ 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

以下 Python 模块创建的记录器、处理器和格式器几乎与上面列出的示例中的相同
，唯一的区别是对象的名称:

     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')

这是 logging.conf 文件：

     [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=

其输出与不基于配置文件的示例几乎相同：

     $ 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

你可以看到配置文件方法相较于 Python 代码方法有一些优势，主要是配置和代码
的分离以及非开发者轻松修改日志记录属性的能力。

     警告: *note fileConfig(): 4af. 函数接受一个默认参数
     ‘disable_existing_loggers’ ，出于向后兼容的原因，默认为 ‘True’ 。这
     可能与您的期望不同，因为除非在配置中明确命名它们（或其父级），否则
     它将导致在 *note fileConfig(): 4af. 调用之前存在的任何非 root 记录
     器被禁用。有关更多信息，请参阅参考文档，如果需要，请将此参数指定为
     ‘False’ 。

     传递给 *note dictConfig(): bfe. 的字典也可以用键
     ‘disable_existing_loggers’ 指定一个布尔值，如果没有在字典中明确指定
     ，也默认被解释为 ‘True’ 。这会导致上面描述的记录器禁用行为，这可能
     与你的期望不同——在这种情况下，请明确地为其提供 ‘False’ 值。

请注意，配置文件中引用的类名称需要相对于日志记录模块，或者可以使用常规导
入机制解析的绝对值。因此，你可以使用 *note WatchedFileHandler: 2257. （
相对于日志记录模块）或 ‘mypackage.mymodule.MyHandler’ （对于在
‘mypackage’ 包中定义的类和模块 ‘mymodule’ ，其中 ‘mypackage’ 在 Python 导
入路径上可用）。

在 Python 3.2 中，引入了一种新的配置日志记录的方法，使用字典来保存配置信
息。 这提供了上述基于配置文件方法的功能的超集，并且是新应用程序和部署的
推荐配置方法。 因为 Python 字典用于保存配置信息，并且由于你可以使用不同
的方式填充该字典，因此你有更多的配置选项。 例如，你可以使用 JSON 格式的
配置文件，或者如果你有权访问 YAML 处理功能，则可以使用 YAML 格式的文件来
填充配置字典。当然，你可以在 Python 代码中构造字典，通过套接字以 pickle
形式接收它，或者使用对你的应用程序合理的任何方法。

以下是与上述相同配置的示例，采用 YAML 格式，用于新的基于字典的方法：

     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]

有关使用字典进行日志记录的更多信息，请参阅 *note 配置函数: d50.。


File: python.info,  Node: 如果没有提供配置会发生什么,  Next: 配置库的日志记录,  Prev: 配置日志记录,  Up: 进阶日志教程

10.6.2.6 如果没有提供配置会发生什么
...................................

如果未提供日志记录配置，则可能出现需要输出日志记录事件但无法找到输出事件
的处理器的情况。 在这些情况下，logging 包的行为取决于 Python 版本。

对于 3.2 之前的 Python 版本，行为如下：

   * 如果 `logging.raiseExceptions' 为 ‘False’ （生产模式），则会以静默
     方式丢弃该事件。

   * 如果 `logging.raiseExceptions' 为 ‘True’ （开发模式），则会打印一条
     消息 ’No handlers could be found for logger X.Y.Z’。

在 Python 3.2 及更高版本中，行为如下：

   * 事件使用 “最后的处理器” 输出，存储在 ‘logging.lastResort’ 中。 这个
     内部处理器与任何记录器都没有关联，它的作用类似于 *note
     StreamHandler: c46. ，它将事件描述消息写入 ‘sys.stderr’ 的当前值（
     因此服从任何可能的重定向影响）。 没有对消息进行格式化——只打印裸事件
     描述消息。处理器的级别设置为 ‘WARNING’，因此将输出此级别和更高级别
     的所有事件。

要获得 3.2 之前的行为，可以设置 ‘logging.lastResort’ 为 ‘None’。


File: python.info,  Node: 配置库的日志记录,  Prev: 如果没有提供配置会发生什么,  Up: 进阶日志教程

10.6.2.7 配置库的日志记录
.........................

在开发使用日志记录的库时，你应该注意记录库如何使用日志记录——例如，使用的
记录器的名称。还需要考虑其日志记录配置。如果应用程序不使用日志记录，并且
库代码进行日志记录调用，那么（如上一节所述）严重性为 ‘WARNING’ 及更高级
别的事件将打印到 ‘sys.stderr’ 。这被认为是最好的默认行为。

如果由于某种原因，你 `不' 希望在没有任何日志记录配置的情况下打印这些消息
，则可以将无操作处理器附加到库的顶级记录器。这样可以避免打印消息，因为将
始终为库的事件找到处理器：它不会产生任何输出。如果库用户配置应用程序使用
的日志记录，可能是配置将添加一些处理器，如果级别已适当配置，则在库代码中
进行的日志记录调用将正常地将输出发送给这些处理器。

日志包中包含一个不做任何事情的处理器： *note NullHandler: ce6. （自
Python 3.1 起）。可以将此处理器的实例添加到库使用的日志记录命名空间的顶
级记录器中（ `如果' 你希望在没有日志记录配置的情况下阻止库的记录事件输出
到 ‘sys.stderr’ ）。如果库 `foo' 的所有日志记录都是使用名称匹配 ’foo.x’
， ’foo.x.y’ 等的记录器完成的，那么代码:

     import logging
     logging.getLogger('foo').addHandler(logging.NullHandler())

应该有预计的效果。如果一个组织生成了许多库，则指定的记录器名称可以是
“orgname.foo” 而不仅仅是 “foo” 。

     備註: 强烈建议你 `不要将' *note NullHandler: ce6. `以外的任何处理器
     添加到库的记录器中' 。这是因为处理器的配置是使用你的库的应用程序开
     发人员的权利。应用程序开发人员了解他们的目标受众以及哪些处理器最适
     合他们的应用程序：如果你在“底层”添加处理器，则可能会干扰他们执行单
     元测试和提供符合其要求的日志的能力。


File: python.info,  Node: 日志级别<2>,  Next: 有用的处理器,  Prev: 进阶日志教程,  Up: 如何使用 Logging 模組

10.6.3 日志级别
---------------

日志记录级别的数值在下表中给出。如果你想要定义自己的级别，并且需要它们具
有相对于预定义级别的特定值，那么你可能对一下内容感兴趣。如果你定义具有相
同数值的级别，它将覆盖预定义的值; 预定义的名称失效。

级别               数值
                   
---------------------------------------
                   
‘CRITICAL’         50
                   
                   
‘ERROR’            40
                   
                   
‘WARNING’          30
                   
                   
‘INFO’             20
                   
                   
‘DEBUG’            10
                   
                   
‘NOTSET’           0
                   

级别也可以与记录器相关联，由开发人员设置或通过加载已保存的日志记录配置。
在记录器上调用日志记录方法时，记录器会将其自己的级别与与方法调用关联的级
别进行比较。如果记录器的级别高于方法调用的级别，则实际上不会生成任何记录
消息。这是控制日志记录输出详细程度的基本机制。

记录消息被编码为 *note LogRecord: 9ec. 类的实例。当记录器决定实际记录事
件时，将用记录消息创建 *note LogRecord: 9ec. 实例。

记录消息受 `handlers' 建立的调度机制控制，它们是 *note Handler: 21df. 类
的子类实例。处理器负责确保记录的消息（以 *note LogRecord: 9ec. 的形式）
最终位于对该消息的目标受众（例如最终用户、 支持服务台员工、系统管理员、
开发人员）有用的特定位置（或一组位置）上。处理器传递适用于特定目标的
*note LogRecord: 9ec. 实例。 每个记录器可以有零个、一个或多个与之关联的
处理器（通过 *note Logger: 4ad. 的 *note addHandler(): 21e7. 方法）。除
了与记录器直接关联的所有处理器之外，还调用与记录器的 `所有祖先关联的处理
器来分派消息（除非记录器的 *propagate' 标志设置为 false 值，这将停止传递
到上级处理器）。

就像记录器一样，处理器可以具有与它们相关联的级别。处理器的级别作为过滤器
，其方式与记录器级别相同。如果处理器决定调度一个事件，则使用 ‘emit()’ 方
法将消息发送到其目标。大多数用户定义的 *note Handler: 21df. 子类都需要重
载 ‘emit()’ 。

* Menu:

* 自定义级别::


File: python.info,  Node: 自定义级别,  Up: 日志级别<2>

10.6.3.1 自定义级别
...................

定义你自己的级别是可能的，但不一定是必要的，因为现有级别是根据实践经验选
择的。但是，如果你确信需要自定义级别，那么在执行此操作时应特别小心，如果
你正在开发库，则 `定义自定义级别可能是一个非常糟糕的主意' 。 这是因为如
果多个库作者都定义了他们自己的自定义级别，那么使用开发人员很难控制和解释
这些多个库的日志记录输出，因为给定的数值对于不同的库可能意味着不同的东西
。


File: python.info,  Node: 有用的处理器,  Next: 记录日志时引发的异常,  Prev: 日志级别<2>,  Up: 如何使用 Logging 模組

10.6.4 有用的处理器
-------------------

作为 *note Handler: 21df. 基类的补充，提供了很多有用的子类：

  1. *note StreamHandler: c46. 实例发送消息到流（类似文件对象）。

  2. *note FileHandler: 2245. 实例将消息发送到硬盘文件。

  3. *note BaseRotatingHandler: 225b. 是轮换日志文件的处理器的基类。它并
     不应该直接实例化。而应该使用 *note RotatingFileHandler: 2236. 或
     *note TimedRotatingFileHandler: 959. 代替它。

  4. *note RotatingFileHandler: 2236. 实例将消息发送到硬盘文件，支持最大
     日志文件大小和日志文件轮换。

  5. *note TimedRotatingFileHandler: 959. 实例将消息发送到硬盘文件，以特
     定的时间间隔轮换日志文件。

  6. *note SocketHandler: 95a. 实例将消息发送到 TCP/IP 套接字。从 3.4 开
     始，也支持 Unix 域套接字。

  7. *note DatagramHandler: 95b. 实例将消息发送到 UDP 套接字。从 3.4 开
     始，也支持 Unix 域套接字。

  8. *note SMTPHandler: 2288. 实例将消息发送到指定的电子邮件地址。

  9. *note SysLogHandler: afb. 实例将消息发送到 Unix syslog 守护程序，可
     能在远程计算机上。

  10. *note NTEventLogHandler: 2280. 实例将消息发送到 Windows NT/2000/XP
     事件日志。

  11. *note MemoryHandler: 223f. 实例将消息发送到内存中的缓冲区，只要满
     足特定条件，缓冲区就会刷新。

  12. *note HTTPHandler: 802. 实例使用 ‘GET’ 或 ‘POST’ 方法将消息发送到
     HTTP 服务器。

  13. *note WatchedFileHandler: 2257. 实例会监视他们要写入日志的文件。如
     果文件发生更改，则会关闭该文件并使用文件名重新打开。此处理器仅在类
     Unix 系统上有用； Windows 不支持依赖的基础机制。

  14. *note QueueHandler: 229b. 实例将消息发送到队列，例如在 *note
     queue: da. 或 *note multiprocessing: b7. 模块中实现的队列。

  15. *note NullHandler: ce6. 实例对错误消息不执行任何操作。它们由想要使
     用日志记录的库开发人员使用，但是想要避免如果库用户没有配置日志记录
     ，则显示 ’No handlers could be found for logger XXX’ 消息的情况。更
     多有关信息，请参阅 *note 配置库的日志记录: 2254. 。

3.1 版新加入: *note NullHandler: ce6. 类。

3.2 版新加入: *note QueueHandler: 229b. 类。

The *note NullHandler: ce6. 、 *note StreamHandler: c46. 和 *note
FileHandler: 2245. 类在核心日志包中定义。其他处理器定义在 *note
logging.handlers: ac. 中。（还有另一个子模块 *note logging.config: ab. ，
用于配置功能）

记录的消息通过 *note Formatter: 21de. 类的实例进行格式化后呈现。 它们使
用能与 ％ 运算符一起使用的格式字符串和字典进行初始化。

要批量格式化多个消息，可以使用 ‘BufferingFormatter’ 的实例。除了格式字符
串（应用于批处理中的每个消息）之外，还提供了标题和尾部格式字符串。

当基于记录器级别和处理器级别的过滤不够时，可以将 *note Filter: c48. 的实
例添加到 *note Logger: 4ad. 和 *note Handler: 21df. 实例（通过它们的
*note addFilter(): 21f6. 方法）。在决定进一步处理消息之前，记录器和处理
器都会查询其所有过滤器以获得许可。如果任何过滤器返回 false 值，则不会进
一步处理该消息。

基本 *note Filter: c48. 的功能允许按特定的记录器名称进行过滤。如果使用此
功能，则允许通过过滤器发送到指定记录器及其子项的消息，并丢弃其他所有消息
。


File: python.info,  Node: 记录日志时引发的异常,  Next: 使用任意对象作为消息,  Prev: 有用的处理器,  Up: 如何使用 Logging 模組

10.6.5 记录日志时引发的异常
---------------------------

logging 包设计为忽略记录日志生产时发生的异常。这样，处理日志记录事件时发
生的错误（例如日志记录错误配置、网络或其他类似错误）不会导致使用日志记录
的应用程序过早终止。

*note SystemExit: 6f3. 和 *note KeyboardInterrupt: 2cc. 异常永远不会被忽
略。 在 *note Handler: 21df. 子类的 ‘emit()’ 方法中发生的其他异常被传递
给它的 ‘handleError()’ 方法。

*note Handler: 21df. 中默认实现的 ‘handleError()’ 检查是否设置了模块级变
量 ‘raiseExceptions’ 。如果有设置，则会将回溯打印到 *note sys.stderr:
1ea. 。如果未设置，则忽略异常。

     備註: ‘raiseExceptions’ 默认值是 ‘True’。 这是因为在开发期间，你通
     常希望收到任何发生异常的通知。建议你将 ‘raiseExceptions’ 设置为
     ‘False’ 以供生产环境使用。


File: python.info,  Node: 使用任意对象作为消息,  Next: 优化,  Prev: 记录日志时引发的异常,  Up: 如何使用 Logging 模組

10.6.6 使用任意对象作为消息
---------------------------

在前面的部分和示例中，都假设记录事件时传递的消息是字符串。 但是，这不是
唯一的可能性。你可以将任意对象作为消息传递，并且当日志记录系统需要将其转
换为字符串表示时，将调用其 ‘__ str__()’ 方法。实际上，如果你愿意，你可以
完全避免计算字符串表示。例如， *note SocketHandler: 95a. 用 pickle 处理
事件后，通过网络发送。


File: python.info,  Node: 优化,  Prev: 使用任意对象作为消息,  Up: 如何使用 Logging 模組

10.6.7 优化
-----------

消息参数的格式化将被推迟，直到无法避免。但是，计算传递给日志记录方法的参
数也可能很消耗资源，如果记录器只是丢弃你的事件，你可能希望避免这样做。要
决定做什么，可以调用 *note isEnabledFor(): 21dd. 方法，该方法接受一个
level 参数，如果记录器为该级别的调用创建了该事件，则返回 true 。 你可以
写这样的代码:

     if logger.isEnabledFor(logging.DEBUG):
         logger.debug('Message with %s, %s', expensive_func1(),
                                             expensive_func2())

因此，如果记录器的阈值设置在“DEBUG”以上，则永远不会调用
‘expensive_func1()’ 和 ‘expensive_func2()’ 。

     備註: 在某些情况下， *note isEnabledFor(): 21dd. 本身可能比你想要的
     更消耗资源（例如，对于深度嵌套的记录器，其中仅在记录器层次结构中设
     置了显式级别）。在这种情况下（或者如果你想避免在紧密循环中调用方法
     ），你可以在本地或实例变量中将调用的结果缓存到 *note
     isEnabledFor(): 21dd. ，并使用它而不是每次调用方法。在日志记录配置
     在应用程序运行时动态更改（这不常见）时，只需要重新计算这样的缓存值
     即可。

对于需要对收集的日志信息进行更精确控制的特定应用程序，还可以进行其他优化
。以下列出了在日志记录过程中您可以避免的非必须处理操作：

你不想收集的内容                                    如何避免收集它
                                                    
-------------------------------------------------------------------------------------------------
                                                    
有关调用来源的信息                                  将 ‘logging._srcfile’ 设置为 ‘None’ 。这避
                                                    免了调用 *note sys._getframe(): f25. ，如
                                                    果 PyPy 支持 Python 3.x ，这可能有助于加速
                                                    PyPy （无法加速使用
                                                    *note sys._getframe(): f25. 的代码）等环境
                                                    中的代码。
                                                    
                                                    
线程信息                                            将 ‘logging.logThreads’ 置为 ‘0’ 。
                                                    
                                                    
进程信息                                            将 ‘logging.logProcesses’ 置为 ‘0’ 。
                                                    

另请注意，核心日志记录模块仅包含基本处理器。如果你不导入 *note
logging.handlers: ac. 和 *note logging.config: ab. ，它们将不会占用任何
内存。

也參考
......

模块 *note logging: aa.

     日志记录模块的 API 参考。

模块 *note logging.config: ab.

     日志记录模块的配置 API 。

模块 *note logging.handlers: ac.

     日志记录模块附带的有用处理器。

*note 日志操作手册: c45.


File: python.info,  Node: 日志操作手册,  Next: 如何使用正規表達式,  Prev: 如何使用 Logging 模組,  Up: Python 如何達成任務

10.7 日志操作手册
=================


作者: 原文作者 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 程序::
* 理应避免的用法::


File: python.info,  Node: 在多个模块中使用日志,  Next: 在多个线程中记录日志,  Up: 日志操作手册

10.7.1 在多个模块中使用日志
---------------------------

无论对 ‘logging.getLogger('someLogger')’ 进行多少次调用，都会返回同一个
logger 对象的引用。不仅在同一个模块内如此，只要是在同一个 Python 解释器
进程中，跨模块调用也是一样。同样是引用同一个对象，应用程序也可以在一个模
块中定义和配置一个父 logger，而在另一个单独的模块中创建（但不配置）子
logger，对于子 logger 的所有调用都会传给父 logger。以下是主模块：

     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()')

以下是辅助模块：

     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"')

输出结果会像这样:

     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()


File: python.info,  Node: 在多个线程中记录日志,  Next: 多个 handler 和多种 formatter,  Prev: 在多个模块中使用日志,  Up: 日志操作手册

10.7.2 在多个线程中记录日志
---------------------------

多线程记录日志并不需要特殊处理，以下示例演示了在主线程（起始线程）和其他
线程中记录日志的过程：

     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()

运行结果会像如下这样:

        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

以上如期显示了不同线程的日志是交替输出的。当然更多的线程也会如此。


File: python.info,  Node: 多个 handler 和多种 formatter,  Next: 在多个地方记录日志,  Prev: 在多个线程中记录日志,  Up: 日志操作手册

10.7.3 多个 handler 和多种 formatter
------------------------------------

日志是个普通的 Python 对象。 *note addHandler(): 21e7. 方法可加入不限数
量的日志 handler。有时候，应用程序需把严重错误信息记入文本文件，而将一般
错误或其他级别的信息输出到控制台。若要进行这样的设定，只需多配置几个日志
handler 即可，应用程序的日志调用代码可以保持不变。下面对之前的分模块日志
示例略做修改：

     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')

需要注意的是，“应用程序”内的代码并不关心是否存在多个日志 handler。示例中
所做的改变，只是新加入并配置了一个名为 `fh' 的 handler。

在编写和测试应用程序时，若能创建日志 handler 对不同严重级别的日志信息进
行过滤，这将十分有用。调试时无需用多条 ‘print’ 语句，而是采用
‘logger.debug’ ：print 语句以后还得注释或删掉，而 logger.debug 语句可以
原样留在源码中保持静默。当需要再次调试时，只要改变日志对象或 handler 的
严重级别即可。


File: python.info,  Node: 在多个地方记录日志,  Next: 日志配置服务器示例,  Prev: 多个 handler 和多种 formatter,  Up: 日志操作手册

10.7.4 在多个地方记录日志
-------------------------

假定要根据不同的情况将日志以不同的格式写入控制台和文件。比如把 DEBUG 以
上级别的日志信息写于文件，并且把 INFO 以上的日志信息输出到控制台。再假设
日志文件需要包含时间戳，控制台信息则不需要。以下演示了做法：

     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('').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.')

当运行后，你会看到控制台如下所示

     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.

而日志文件将如下所示：

     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.

如您所见，DEBUG 级别的日志信息只出现在了文件中，而其他信息则两个地方都会
输出。

上述示例只用到了控制台和文件 handler，当然还可以自由组合任意数量的日志
handler。


File: python.info,  Node: 日志配置服务器示例,  Next: 处理日志 handler 的阻塞,  Prev: 在多个地方记录日志,  Up: 日志操作手册

10.7.5 日志配置服务器示例
-------------------------

以下是一个用到了日志配置服务器的模块示例：

     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()

以下脚本将接受文件名作为参数，然后将此文件发送到服务器，前面加上文件的二
进制编码长度，做为新的日志配置：

     #!/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')


File: python.info,  Node: 处理日志 handler 的阻塞,  Next: 通过网络收发日志事件,  Prev: 日志配置服务器示例,  Up: 日志操作手册

10.7.6 处理日志 handler 的阻塞
------------------------------

有时需让日志 handler 不要阻塞当前的线程。这在 Web 应用程序中比较常见，当
然在其他场景中也会发生。

有一种原因往往会让程序表现迟钝，这就是 *note SMTPHandler: 2288.：由于很
多因素是开发人员无法控制的（例如邮件或网络基础设施的性能不佳），发送电子
邮件可能需要很长时间。不过几乎所有网络 handler 都可能会发生阻塞：即使是
*note SocketHandler: 95a. 操作也可能在后台执行 DNS 查询，而这种查询实在
太慢了（并且 DNS 查询还可能在很底层的套接字库代码中，位于 Python 层之下
，超出了可控范围）。

有一种解决方案是分成两部分实现。第一部分，针对那些对性能有要求的关键线程
，只为日志对象连接一个 *note QueueHandler: 229b.。日志对象只需简单地写入
队列即可，可为队列设置足够大的容量，或者可以在初始化时不设置容量上限。尽
管为以防万一，可能需要在代码中捕获 *note queue.Full: 250c. 异常,不过队列
写入操作通常会很快得以处理。如果要开发库代码，包含性能要求较高的线程，为
了让使用该库的开发人员受益，请务必在开发文档中进行标明（包括建议仅连接
‘QueueHandlers’ ）。

解决方案的另一部分就是 *note QueueListener: 803.，它被设计为 *note
QueueHandler: 229b. 的对应部分。*note QueueListener: 803. 非常简单：传入
一个队列和一些 handler，并启动一个内部线程，用于侦听 ‘QueueHandlers``（
或其他 ``LogRecords’ 源）发送的 LogRecord 队列。‘LogRecords’ 会从队列中
移除并传给 handler 处理。

*note QueueListener: 803. 作为单独的类，好处就是可以用同一个实例为多个
‘QueueHandlers’ 服务。这比把现有 handler 类线程化更加资源友好，后者会每
个 handler 会占用一个线程，却没有特别的好处。

以下是这两个类的运用示例（省略了 import 语句）：

     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()

在运行后会产生:

     MainThread: Look out!

3.5 版更變: 在 Python 3.5 之前，*note QueueListener: 803. 总会把由队列接
收到的每条信息都传递给已初始化的每个处理程序。（因为这里假定级别过滤操作
已在写入队列时完成了。）从 3.5 版开始，可以修改这种处理方式，只要将关键
字参数 ‘respect_handler_level=True’ 传给侦听器的构造函数即可。这样侦听器
将会把每条信息的级别与 handler 的级别进行比较，只在适配时才会将信息传给
handler 。


File: python.info,  Node: 通过网络收发日志事件,  Next: 在自己的输出日志中添加上下文信息,  Prev: 处理日志 handler 的阻塞,  Up: 日志操作手册

10.7.7 通过网络收发日志事件
---------------------------

假定现在要通过网络发送日志事件，并在接收端进行处理。有一种简单的方案，就
是在发送端的根日志对象连接一个 *note SocketHandler: 95a. 实例：

     import logging, logging.handlers

     rootLogger = logging.getLogger('')
     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.')

在接收端，可以用 *note socketserver: f0. 模块设置一个接收器。简要示例如
下：

     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()

先运行服务端，再运行客户端。客户端控制台不会显示什么信息；在服务端应该会
看到如下内容：

     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.

请注意，某些时候 pickle 会存在一些安全问题。若有问题可换用自己的序列化方
案，只要覆盖 ‘makePickle()’ 方法即可，并调整上述脚本以采用自己的序列化方
案。

* Menu:

* Running a logging socket listener in production::


File: python.info,  Node: Running a logging socket listener in production,  Up: 通过网络收发日志事件

10.7.7.1 Running a logging socket listener in production
........................................................

To run a logging listener in production, you may need to use a
process-management tool such as Supervisor(1).  Here(2) is a Gist which
provides the bare-bones files to run the above functionality using
Supervisor: you will need to change the ‘/path/to/’ parts in the Gist to
reflect the actual paths you want to use.

   ---------- Footnotes ----------

   (1) http://supervisord.org/

   (2) https://gist.github.com/vsajip/4b227eeec43817465ca835ca66f75e2b


File: python.info,  Node: 在自己的输出日志中添加上下文信息,  Next: 在单个文件中记录多个进程的日志,  Prev: 通过网络收发日志事件,  Up: 日志操作手册

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

有时，除了调用日志对象时传入的参数之外，还希望日志输出中能包含上下文信息
。 比如在网络应用程序中，可能需要在日志中记录某客户端专属的信息（如远程
客户端的用户名或 IP 地址）。 这虽然可以用 `extra' 参数实现，但传递起来并
不总是很方便。 虽然为每个网络连接都创建 ‘Logger’ 实例貌似不错，但并不是
个好主意，因为这些实例不会被垃圾回收。 虽然在实践中不是问题，但当
‘Logger’ 实例的数量取决于应用程序要采用的日志粒度时，如果 ‘Logger’ 实例
的数量实际上是无限的，则有可能难以管理。

* Menu:

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


File: python.info,  Node: 利用 LoggerAdapter 传递上下文信息,  Next: 利用 Filter 传递上下文信息,  Up: 在自己的输出日志中添加上下文信息

10.7.8.1 利用 LoggerAdapter 传递上下文信息
..........................................

要传递上下文信息和日志事件信息，有一种简单方案是利用 ‘LoggerAdapter’ 类
。这个类设计得类似 ‘Logger’，所以可以直接调用 ‘debug()’、‘info()’、
‘warning()’、 ‘error()’、‘exception()’、 ‘critical()’ 和 ‘log()’。这些方
法的签名与 ‘Logger’ 对应的方法相同，所以这两类实例可以交换使用。

若要创建 ‘LoggerAdapter’ 的实例，需传入一个 ‘Logger’ 的实例和一个包含了
上下文信息的字典类对象。当在 ‘LoggerAdapter’ 实例上调用某个日志方法时，
会将调用委托给传入构造函数的底层 ‘Logger’ 实例，并在调用中传入上下文信息
。以下是 ‘LoggerAdapter’ 的一段代码：

     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)

‘LoggerAdapter’ 的 ‘process()’ 方法用于将上下文信息添加到日志的输出中去
。其入参为日志调用的信息和关键字参数，并将（可能）修改后的入参值传回，以
供底层的日志对象调用。该方法的默认实现代码不会对信息做改动，而只是在关键
字参数中增加一个键为“extra”的字段，其值即为传入构造函数的字典类对象。当
然，若是在调用时传入了一个名为“extra”的关键字参数，则传入值会被悄无声息
地覆盖掉。

使用“extra”的好处，就是字典类对象中的值会被并入 ‘LogRecord’ 实例的
__dict__ 中，这样就能利用 ‘Formatter’ 实例使用自定义字符串了，Formatter
知道该如何使用字典类对象的键。若要用到其他方法，比如想在信息字符串中预置
或追加上下文信息，只需继承 ‘LoggerAdapter’ 并覆盖 ‘process()’ 方法即可完
成处理。下面给出一个简单的示例：

     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

用法可如下所示：

     logger = logging.getLogger(__name__)
     adapter = CustomAdapter(logger, {'connid': some_conn_id})

这样，只要是该 Adapter 处理的任何日志事件，消息前都会加上
‘‘some_conn_id‘‘ 的值。

* Menu:

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


File: python.info,  Node: 利用非字典对象传入上下文信息,  Up: 利用 LoggerAdapter 传递上下文信息

10.7.8.2 利用非字典对象传入上下文信息
.....................................

传给 ‘LoggerAdapter’ 的不一定要是真正的字典对象，也可以传入一个实现了
‘__getitem__’ 和‘‘__iter__‘‘ 方法的类实例，类似要写入日志的字典对象。若
要动态生成值（而字典中的值应为常量），这就会很有用。


File: python.info,  Node: 利用 Filter 传递上下文信息,  Prev: 利用 LoggerAdapter 传递上下文信息,  Up: 在自己的输出日志中添加上下文信息

10.7.8.3 利用 Filter 传递上下文信息
...................................

还可以利用用户定义类 ‘Filter’ 在日志输出中添加上下文信息。‘Filter’ 实例
可以修改传入的 ‘LogRecords’，包括添加额外的属性，然后可以采用合适的格式
化字符串对这些属性进行输出，必要时还可采用自定义类 ‘Formatter’。

例如在某 web 应用程序中，正在处理的请求（或至少是当前关注的部分），可存
储于线程本地 (*note threading.local: 244e.) 变量中，然后从‘‘Filter‘‘ 中
去访问，把请求中的一些信息添加进去，比如在 ‘LogRecord’ 中写入远程 IP 地
址和远程用户名，可利用以上 ‘LoggerAdapter’ 示例中的“ip”和“user”属性名。
这时可采用与上例相同的格式化字符串来得到类似的输出结果。以下是一段示例代
码：

     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')

在运行时，产生如下内容:

     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


File: python.info,  Node: 在单个文件中记录多个进程的日志,  Next: 利用日志文件轮换机制,  Prev: 在自己的输出日志中添加上下文信息,  Up: 日志操作手册

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

尽管日志对象是线程安全的，也确实 `支持' 将一个进程中的多个线程日志记入单
个文件，但 `不' 支持将 `多进程' 日志记入单个文件，因为 Python 没有标准方
案来实现由多个进程串行访问单个文件。若要将多个进程的日志记入单个文件，一
种方案是让所有进程都用一个 ‘SocketHandler’ 处理日志，然后用一个单独的进
程实现套接字服务器，一边从套接字读取数据一边向文件中写入日志。（当然可在
某个现有进程中指定一个线程来执行此项功能。） *note 此部分: 437f. 更详细
地介绍了这种做法，包含了一个套接字接收器，可以此为起点建立适合自己应用程
序的代码。

编写自己的 handler 也是可以的，可利用 *note multiprocessing: b7. 模块中
的 *note Lock: 24ed. 类实现多个进程串行访问文件。现有的 ‘FileHandler’ 及
其子类目前没有用到 *note multiprocessing: b7.，或许将来有可能会吧。请注
意，目前 *note multiprocessing: b7. 模块并未在所有平台上都提供可用的同步
锁功能（参见 ‘https://bugs.python.org/issue3770’）。

或者，还可以利用 ‘Queue’ 和 *note QueueHandler: 229b. 将所有的日志事件发
送给自己的多进程应用中的某个进程。以下例程演示了这种做法，这里有一个单独
的监听进程负责监听其他进程发来的日志事件，并根据自己的日志配置记入日志。
尽管本例程只演示了一种实现方案（比如可能想用单独的监听线程而非进程 —— 实
现方式其实类似），但确实可以为应用程序的监听进程和其他进程采用不同的配置
，作为满足特定需求代码的基础：

     # 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()

上述代码可做个变化，在主进程中用单独的线程记录日志：

     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()

这段改过的代码展示了如何为某日志对象应用指定配置 —— 比如 ‘foo’ 日志对象
有个特别的 handler，将 ‘foo’ 子系统的所有事件保存至文件 ‘mplog-foo.log’
中。主进程的日志机制将会用到这段代码（即便日志事件是在其他的工作进程中产
生的），将信息定向输出到指定的地方。

* Menu:

* concurrent.futures.ProcessPoolExecutor 的用法: concurrent futures ProcessPoolExecutor 的用法.
* Deploying Web applications using Gunicorn and uWSGI::


File: python.info,  Node: concurrent futures ProcessPoolExecutor 的用法,  Next: Deploying Web applications using Gunicorn and uWSGI,  Up: 在单个文件中记录多个进程的日志

10.7.9.1 concurrent.futures.ProcessPoolExecutor 的用法
......................................................

若要利用 *note concurrent.futures.ProcessPoolExecutor: 196. 启动工作进程
，创建队列的方式应稍有不同。不能是：

     queue = multiprocessing.Queue(-1)

而应是：

     queue = multiprocessing.Manager().Queue(-1)  # also works with the examples above

然后就可以将以下工作进程的创建过程：

     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()

改为 (记得要先导入 *note concurrent.futures: 21.):

     with concurrent.futures.ProcessPoolExecutor(max_workers=10) as executor:
         for i in range(10):
             executor.submit(worker_process, queue, worker_configurer)


File: python.info,  Node: Deploying Web applications using Gunicorn and uWSGI,  Prev: concurrent futures ProcessPoolExecutor 的用法,  Up: 在单个文件中记录多个进程的日志

10.7.9.2 Deploying Web applications using Gunicorn and uWSGI
............................................................

When deploying Web applications using Gunicorn(1) or uWSGI(2) (or
similar), multiple worker processes are created to handle client
requests.  In such environments, avoid creating file-based handlers
directly in your web application.  Instead, use a *note SocketHandler:
95a. to log from the web application to a listener in a separate
process.  This can be set up using a process management tool such as
Supervisor - see *note Running a logging socket listener in production:
4381. for more details.

   ---------- Footnotes ----------

   (1) https://gunicorn.org/

   (2) https://uwsgi-docs.readthedocs.io/en/latest/


File: python.info,  Node: 利用日志文件轮换机制,  Next: 日志的其他格式,  Prev: 在单个文件中记录多个进程的日志,  Up: 日志操作手册

10.7.10 利用日志文件轮换机制
----------------------------

有时需要让日志文件增长到指定大小，然后打开一个新文件并记入日志。或许还需
要只保留一定数量的日志文件，当创建了指定数量的文件后，就轮换使用这些文件
，以便让文件数量和大小都维持上限。logging 包为这种使用模式提供了
‘RotatingFileHandler’ ：

     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)

结果应该是6个单独的文件，每个文件都包含了应用程序的部分历史日志:

     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

最新的文件始终是 ‘logging_rotatingfile_example.out’，每次达到大小限制时
，都会用后缀 ‘.1’ 重新命名。已有的备份文件全都会被重命名，将后缀递增（如
‘.1’ 变为 ‘.2’ ），而 ‘.6’ 文件则会被删除。

显然，这个例子将日志长度设置得太小，这是一个极端的例子。 你可能希望将
`maxBytes' 设置为一个合适的值。


File: python.info,  Node: 日志的其他格式,  Next: 自定义 LogRecord,  Prev: 利用日志文件轮换机制,  Up: 日志操作手册

10.7.11 日志的其他格式
----------------------

当日志模块刚加入 Python 标准库时，想要格式化输出带有可变内容的日志信息，
只有一种 %-f 方法。后来 Python 又有了两种格式化方法： *note
string.Template: 4f0. （Python 2.4 加入）和 *note str.format(): 5d4. （
Python 2.6 加入）。

从 Python 3.2 开始，日志模块为后加入的两种格式化方式提供了更多支持。
‘Formatter’ 得以增强，可以接受名为 ‘style’ 的可选关键字参数。其默认值为
‘'%'’ ，其他还可以是 ‘'{'’ 和 ‘'{TX-PL-LABEL}#x27;’，对应于另外两种格式
化的样式。如您所料，默认保持向下兼容，而通过显式指定样式参数，能够设置用
于 *note str.format(): 5d4. 或 *note string.Template: 4f0. 的格式串。下
面是个控制台会话示例，演示一下功能：

     >>> 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
     >>>

请注意，最终输出到日志的信息格式与某一条信息的构造方式完全独立。单条信息
仍然可以采用 %-f 格式，如下所示：

     >>> 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
     >>>

日志调用（‘logger.debug()’ 、‘logger.info()’ 等）接受的位置参数只会用于
日志信息本身，而关键字参数仅用于日志调用的可选处理参数（如关键字参数
‘exc_info’ 表示应记录跟踪信息， ‘extra’ 则标识了需要加入日志的额外上下文
信息）。所以不能直接用 *note str.format(): 5d4. 或 *note
string.Template: 4f0. 语法进行日志调用，因为日志包在内部使用 %-f 格式来
合并格式串和参数变量。在保持向下兼容性时，这一点不会改变，因为已有代码中
的所有日志调用都会使用%-f 格式串。

还有一种方法可以构建自己的日志信息，就是利用 {}- 和 $- 格式。回想一下，
任意对象都可用为日志信息的格式串，日志包将会调用该对象的 ‘str()’ 方法，
以获取最终的格式串。不妨看下一下两个类：

     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)

上述两个类均可代替格式串，使得能用 {}- 或 $-formatting 构建最终的“日志信
息”部分，这些信息将出现在格式化后的日志输出中，替换 %(message)s 或
“{message}”或“$message”。每次写入日志时都要使用类名，有点不大实用，但如
果用上 __ 之类的别名就相当合适了（双下划线 — 不要与 _ 混淆，单下划线用作
*note gettext.gettext(): e92. 或相关函数的同义词/别名 ）。

Python 并没有上述两个类，当然复制粘贴到自己的代码中也很容易。用法可如下
所示（假定在名为 ‘wherever’ 的模块中声明）：

     >>> 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
     >>>

上述示例用了 ‘print()’ 演示格式化输出的过程，实际记录日志时当然会用类似
‘logger.debug()’ 的方法来加以应用。

值得注意的是，上述做法对性能并没什么影响：格式化过程其实不是在日志记录调
用时发生的，而是在日志信息即将由 handler 输出到日志时发生。因此，唯一可
能让人困惑的稍不寻常的地方，就是包裹在格式串和参数外面的括号，而不是格式
串。因为 __ 符号只是对 XXXMessage 类的构造函数调用的语法糖。

只要愿意，上述类似的效果即可用 ‘LoggerAdapter’ 实现，如下例所示：

     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()

在用 Python 3.2 以上版本运行时，上述代码应该会把 ‘Hello, world!’ 写入日
志。


File: python.info,  Node: 自定义 LogRecord,  Next: 子类化 QueueHandler - ZeroMQ 示例,  Prev: 日志的其他格式,  Up: 日志操作手册

10.7.12 自定义 ‘LogRecord’
--------------------------

每条日志事件都由一个 *note LogRecord: 9ec. 实例表示。当某事件要记入日志
并且没有被某级别过滤掉时，就会创建一个 *note LogRecord: 9ec. 对象，并将
有关事件的信息填入，传给该日志对象的 handler（及其祖先，直至对象禁止向上
传播为止）。在 Python 3.2 之前，只有两个地方会进行事件的创建：

   * *note Logger.makeRecord(): 21eb.，在事件正常记入日志的过程中调用。
     这会直接调用 *note LogRecord: 9ec. 来创建一个实例。

   * *note makeLogRecord(): 2210.，调用时会带上一个字典参数，其中存放着
     要加入 LogRecord 的属性。这通常在通过网络接收到合适的字典时调用（如
     通过 *note SocketHandler: 95a. 以 pickle 形式，或通过 *note
     HTTPHandler: 802. 以 JSON 形式）。

于是这意味着若要对 *note LogRecord: 9ec. 进行定制，必须进行下述某种操作
。

   * 创建 *note Logger: 4ad.  自定义子类，重写 *note
     Logger.makeRecord(): 21eb.，并在实例化所需日志对象之前用 *note
     setLoggerClass(): 221d. 进行设置。

   * 为日志对象添加 *note Filter: c48. 或 handler，当其 *note filter():
     220b. 方法被调用时，会执行必要的定制操作。

比如说在有多个不同库要完成不同操作的场景下，第一种方式会有点笨拙。 每次
都要尝试设置自己的 *note Logger: 4ad. 子类，而起作用的是最后一次尝试。

第二种方式在多数情况下效果都比较良好，但不允许你使用特殊化的 *note
LogRecord: 9ec. 子类。 库开发者可以为他们的日志记录器设置合适的过滤器，
但他们应当要记得每次引入新的日志记录器时都需如此（他们只需通过添加新的包
或模块并执行以下操作即可）:

     logger = logging.getLogger(__name__)

或许这样要顾及太多事情。开发人员还可以将过滤器附加到其顶级日志对象的
*note NullHandler: ce6. 中，但如果应用程序开发人员将 handler 附加到较底
层库的日志对象，则不会调用该过滤器 — 所以 handler 输出的内容不会符合库开
发人员的预期。

在 Python 3.2 以上版本中，*note LogRecord: 9ec. 的创建是通过工厂对象完成
的，工厂对象可以指定。工厂对象只是一个可调用对象，可以用 *note
setLogRecordFactory(): 2213. 进行设置，并用 *note getLogRecordFactory():
2212. 进行查询。工厂对象的调用参数与 *note LogRecord: 9ec. 的构造函数相
同，因为 *note LogRecord: 9ec. 是工厂对象的默认设置。

这种方式可以让自定义工厂对象完全控制 LogRecord 的创建过程。比如可以返回
一个子类，或者在创建的日志对象中加入一些额外的属性，使用方式如下所示：

     old_factory = logging.getLogRecordFactory()

     def record_factory(*args, **kwargs):
         record = old_factory(*args, **kwargs)
         record.custom_attribute = 0xdecafbad
         return record

     logging.setLogRecordFactory(record_factory)

这种模式允许不同的库将多个工厂对象链在一起，只要不会覆盖彼此的属性或标准
属性，就不会出现意外。但应记住，工厂链中的每个节点都会增加日志操作的运行
开销，本技术仅在采用 *note Filter: c48. 无法达到目标时才应使用。


File: python.info,  Node: 子类化 QueueHandler - ZeroMQ 示例,  Next: 子类化 QueueListener —— ZeroMQ 示例,  Prev: 自定义 LogRecord,  Up: 日志操作手册

10.7.13 子类化 QueueHandler - ZeroMQ 示例
-----------------------------------------

你可以使用 ‘QueueHandler’ 子类将消息发送给其他类型的队列 ，比如 ZeroMQ
’publish’ 套接字。 在以下示例中，套接字将单独创建并传给处理句柄 (作为它
的 ’queue’):

     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)

当然还有其他方案，比如通过 hander 传入所需数据，以创建 socket：

     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()


File: python.info,  Node: 子类化 QueueListener —— ZeroMQ 示例,  Next: 基于字典进行日志配置的示例,  Prev: 子类化 QueueHandler - ZeroMQ 示例,  Up: 日志操作手册

10.7.14 子类化 QueueListener —— ZeroMQ 示例
-------------------------------------------

你还可以子类化 ‘QueueListener’ 来从其他类型的队列中获取消息，比如从
ZeroMQ ’subscribe’ 套接字。 下面是一个例子:

     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, '')  # subscribe to everything
             socket.connect(uri)
             super().__init__(socket, *handlers, **kwargs)

         def dequeue(self):
             msg = self.queue.recv_json()
             return logging.makeLogRecord(msg)

也參考
......

模块 *note logging: aa.

     日志记录模块的 API 参考。

模块 *note logging.config: ab.

     日志记录模块的配置 API 。

模块 *note logging.handlers: ac.

     日志记录模块中的常用 handler。

*note 日志操作基础教程: c43.

*note 日志操作的高级教程: c44.


File: python.info,  Node: 基于字典进行日志配置的示例,  Next: 利用 rotator 和 namer 自定义日志轮换操作,  Prev: 子类化 QueueListener —— ZeroMQ 示例,  Up: 日志操作手册

10.7.15 基于字典进行日志配置的示例
----------------------------------

以下是日志配置字典的一个示例——它取自 Django 项目的‘文档
<‘https://docs.djangoproject.com/en/stable/topics/logging/#configuring-logging’>‘_。
此字典将被传给 *note dictConfig(): bfe. 以使配置生效：

     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']
             }
         }
     }

有关本配置的更多信息，请参阅 Django 文档的 有关章节(1) 。

   ---------- Footnotes ----------

   (1) 
https://docs.djangoproject.com/en/stable/topics/logging/#configuring-logging


File: python.info,  Node: 利用 rotator 和 namer 自定义日志轮换操作,  Next: 更详细的多进程日志示例,  Prev: 基于字典进行日志配置的示例,  Up: 日志操作手册

10.7.16 利用 rotator 和 namer 自定义日志轮换操作
------------------------------------------------

以下代码给出了定义 namer 和 rotator 的示例，其中演示了基于 zlib 的日志文
件压缩过程：

     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

这些不是“真正的” .gz 文件，因为他们只是纯压缩数据，缺少真正 gzip 文件中
的“容器”。此段代码只是用于演示。


File: python.info,  Node: 更详细的多进程日志示例,  Next: 在发送给 SysLogHandler 的信息中插入一个 BOM。,  Prev: 利用 rotator 和 namer 自定义日志轮换操作,  Up: 日志操作手册

10.7.17 更详细的多进程日志示例
------------------------------

以下可运行的示例显示了如何利用配置文件在多进程中应用日志。这些配置相当简
单，但足以说明如何在真实的多进程场景中实现较为复杂的配置。

在此示例中，主进程产生一个侦听器进程和一些工作进程。每个主进程、侦听器进
程和工作进程都有三种独立的日志配置（工作进程共享同一套配置）。大家可以看
到主进程的日志记录过程、工作线程向 QueueHandler 写入日志的过程，以及侦听
器实现 QueueListener 和较为复杂的日志配置，如何将由队列接收到的事件分发
给配置指定的 handler。请注意，这些配置纯粹用于演示，但应该能调整代码以适
用于自己的场景。

以下是代码——但愿文档字符串和注释能有助于理解其工作原理：

     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()


File: python.info,  Node: 在发送给 SysLogHandler 的信息中插入一个 BOM。,  Next: 结构化日志的实现代码,  Prev: 更详细的多进程日志示例,  Up: 日志操作手册

10.7.18 在发送给 SysLogHandler 的信息中插入一个 BOM。
-----------------------------------------------------

RFC 5424(1) 要求，Unicode 信息应采用字节流形式发送到系统 syslog 守护程序
，字节流结构如下所示：可选的纯 ASCII部分，后跟 UTF-8 字节序标记（BOM），
然后是采用 UTF-8 编码的 Unicode。（参见 相关规范(2) 。）

在 Python 3.1 的 *note SysLogHandler: afb. 中，已加入了在日志信息中插入
BOM 的代码，但不幸的是，代码并不正确，BOM 出现在了日志信息的开头，因此在
它之前就不允许出现纯 ASCII 内容了。

由于无法正常工作， Python 3.2.4 以上版本已删除了出错的插入 BOM 代码。但
已有版本的代码不会被替换，若要生成与 RFC 5424(3) 兼容的日志信息，包括一
个 BOM 符，前面有可选的纯 ASCII 字节流，后面为 UTF-8 编码的任意 Unicode，
那么 需要执行以下操作：

  1. 为 *note SysLogHandler: afb. 实例串上一个 *note Formatter: 21de. 实
     例，格式串可如下：

          'ASCII section\ufeffUnicode section'

     用 UTF-8 编码时，Unicode 码位 U+FEFF 将会编码为 UTF-8 BOM——字节串
     ‘b'\xef\xbb\xbf'’ 。

  2. ASCII 部分可替换为任意字符，但要保证替换后的数据一定是 ASCII 码（这
     样在 UTF-8 编码后就会维持不变）。

  3. Unicode 部分可替换为任意字符；如果替换后的数据包含超出 ASCII 范围的
     字符，没问题——他们将用 UTF-8 进行编码。

‘SysLogHandler’ `将' 对格式化后的日志信息进行 UTF-8 编码。如果遵循上述规
则，应能生成符合 RFC 5424(4) 的日志信息。否则，日志记录过程可能不会有什
么反馈，但日志信息将不与 RFC 5424 兼容，syslog 守护程序可能会有出错反应
。

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc5424.html

   (2) https://tools.ietf.org/html/rfc5424.html#section-6

   (3) https://tools.ietf.org/html/rfc5424.html

   (4) https://tools.ietf.org/html/rfc5424.html


File: python.info,  Node: 结构化日志的实现代码,  Next: 利用 dictConfig 自定义 handler,  Prev: 在发送给 SysLogHandler 的信息中插入一个 BOM。,  Up: 日志操作手册

10.7.19 结构化日志的实现代码
----------------------------

大多数日志信息是供人阅读的，所以机器解析起来并不容易，但某些时候可能希望
以结构化的格式输出，以 `能够' 被程序解析（无需用到复杂的正则表达式）。这
可以直接用 logging 包实现。实现方式有很多，以下是一种比较简单的方案，利
用 JSON 以机器可解析的方式对事件信息进行序列化：

     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))

上述代码运行后的结果是：

     message 1 >>> {"fnum": 123.456, "num": 123, "bar": "baz", "foo": "bar"}

请注意，根据 Python 版本的不同，各项数据的输出顺序可能会不一样。

若需进行更为定制化的处理，可以使用自定义 JSON 编码对象，下面给出完整示例
：

     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()

上述代码运行后的结果是：

     message 1 >>> {"snowman": "\u2603", "set_value": [1, 2, 3]}

请注意，根据 Python 版本的不同，各项数据的输出顺序可能会不一样。


File: python.info,  Node: 利用 dictConfig 自定义 handler,  Next: 生效于整个应用程序的格式化样式,  Prev: 结构化日志的实现代码,  Up: 日志操作手册

10.7.20 利用 ‘dictConfig()’ 自定义 handler
------------------------------------------

有时需要以特定方式自定义日志 handler，如果采用 *note dictConfig(): bfe.，
可能无需生成子类就可以做到。比如要设置日志文件的所有权。在 POSIX 上，可
以利用 *note shutil.chown(): b51. 轻松完成，但 stdlib 中的文件 handler 并
不提供内置支持。于是可以用普通函数自定义 handler 的创建，例如：

     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)

然后，你可以在传给 *note dictConfig(): bfe. 的日志配置中指定通过调用此函
数来创建日志处理程序:

     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',
         },
     }

出于演示目的，以下示例设置用户和用户组为 ‘pulse’。代码置于一个可运行的脚
本文件 ‘chowntest.py’ 中：

     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')

可能需要 ‘root’ 权限才能运行：

     $ 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

请注意此示例用的是 Python 3.3，因为 *note shutil.chown(): b51. 是从此版
本开始出现的。 此方式应当适用于任何支持 *note dictConfig(): bfe. 的
Python 版本 —— 例如 Python 2.7, 3.2 或更新的版本。 对于 3.3 之前的版本，
你应当使用 *note os.chown(): b10. 之类的函数来实现实际的所有权修改。

实际应用中，handler 的创建函数可能位于项目的工具模块中。以下配置：

     '()': owned_file_handler,

应使用：

     '()': 'ext://project.util.owned_file_handler',

这里的 ‘project.util’ 可以换成函数所在包的实际名称。 在上述的可用脚本中
，应该可以使用 ‘'ext://__main__.owned_file_handler'’。 在这里，实际的可
调用对象是由 *note dictConfig(): bfe. 从 ‘ext://’ 说明中解析出来的。

上述示例还指明了其他的文件修改类型的实现方案 —— 比如同样利用 *note
os.chmod(): b0f. 设置 POSIX 访问权限位。

当然，以上做法也可以扩展到 *note FileHandler: 2245. 之外的其他类型的
handler ——比如某个轮换文件 handler，或类型完全不同的其他 handler。


File: python.info,  Node: 生效于整个应用程序的格式化样式,  Next: 用 dictConfig 配置过滤器,  Prev: 利用 dictConfig 自定义 handler,  Up: 日志操作手册

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

在 Python 3.2 中，*note Formatter: 21de. 增加了一个 ‘style’ 关键字形参，
它默认为 ‘%’ 以便向下兼容，但是允许采用 ‘{’ 或 ‘{TX-PL-LABEL}#x60;’ 来支
持 *note str.format(): 5d4. 和 *note string.Template: 4f0. 所支持的格式
化方式。 请注意此形参控制着用用于最终输出到日志的日志消息格式，并且与单
独日志消息的构造方式完全无关。

日志函数（*note debug(): 801, *note info(): 21e0. 等）只会读取位置参数获
取日志信息本身，而关键字参数仅用于确定日志函数的工作选项（比如关键字参数
‘exc_info’ 表示应将跟踪信息记入日志，关键字参数 ‘extra’ 则给出了需加入日
志的额外上下文信息）。所以不能直接使用 *note str.format(): 5d4. 或 *note
string.Template: 4f0. 这种语法进行日志调用，因为日志包在内部使用 %-f 格
式来合并格式串和可变参数。因为尚需保持向下兼容，这一点不会改变，已有代码
中的所有日志调用都将采用 %-f 格式串。

有人建议将格式化样式与特定的日志对象进行关联，但其实也会遇到向下兼容的问
题，因为已有代码可能用到了某日志对象并采用了 %-f 格式串。

为了让第三方库和自编代码都能够交互使用日志功能，需要决定在单次日志记录调
用级别采用什么格式。于是就出现了其他几种格式化样式方案。

* Menu:

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


File: python.info,  Node: LogRecord 工厂的用法,  Next: 自定义日志信息对象的使用,  Up: 生效于整个应用程序的格式化样式

10.7.21.1 LogRecord 工厂的用法
..............................

在 Python 3.2 中，伴随着 *note Formatter: 21de. 的上述变化，logging 包增
加了允许用户使用 *note setLogRecordFactory(): 2213. 函数来。设置自己的
*note LogRecord: 9ec. 子类的功能。 你可以使用此功能来设置自己的 *note
LogRecord: 9ec. 子类，它会通过重载 *note getMessage(): 2211. 方法来完成
适当的操作。 ‘msg % args’ 格式化是在此方法的基类实现中进行的，你可以在那
里用你自己的格式化操作来替换；但是，你应当注意要支持全部的格式化样式并允
许将 %-formatting 作为默认样式，以确保与其他代码进行配合。 还应当注意调
用 ‘str(self.msg)’，正如基类实现所做的一样。

更多信息请参阅 *note setLogRecordFactory(): 2213. 和 *note LogRecord:
9ec. 的参考文档。


File: python.info,  Node: 自定义日志信息对象的使用,  Prev: LogRecord 工厂的用法,  Up: 生效于整个应用程序的格式化样式

10.7.21.2 自定义日志信息对象的使用
..................................

另一种方案可能更为简单，可以利用 {}- 和 $- 格式构建自己的日志消息。大家
或许还记得（来自 *note 使用任意对象作为消息: 2215.），可以用任意对象作为
日志信息的格式串，日志包将调用该对象上 *note str(): 205. 获取实际的格式
串。看下以下两个类：

     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)

以上两个类均都可用于替代格式串，以便用 {}- 或 $-formatting 构建实际的“日
志信息”部分，此部分将出现在格式化后的日志输出中，替换 %(message)s 、
“{message}”或“$message”。每次要写入日志时都使用类名，如果觉得使用不便，
可以采用 ‘M’ 或 ‘_’ 之类的别名（如果将 ‘_’ 用于本地化操作，则可用 ‘__’）
。

下面给出示例。 首先用 *note str.format(): 5d4. 进行格式化：

     >>> __ = 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)

然后，用 *note string.Template: 4f0. 格式化：

     >>> __ = DollarMessage
     >>> print(__('Message with $num $what', num=2, what='placeholders'))
     Message with 2 placeholders
     >>>

值得注意的是，上述做法对性能并没什么影响：格式化过程其实不是在日志调用时
发生的，而是在日志信息即将由 handler 输出到日志时发生。因此，唯一可能让
人困惑的稍不寻常的地方，就是包裹在格式串和参数外面的括号，而不是格式串。
因为 __ 符号只是对 ‘XXXMessage’ 类的构造函数调用的语法糖。


File: python.info,  Node: 用 dictConfig 配置过滤器,  Next: 异常信息的自定义格式化,  Prev: 生效于整个应用程序的格式化样式,  Up: 日志操作手册

10.7.22 用 ‘dictConfig()’ 配置过滤器
------------------------------------

用 *note dictConfig(): bfe. `可以' 对日志过滤器进行设置，尽管乍一看做法
并不明显（所以才需要本秘籍）。 由于 *note Filter: c48. 是标准库中唯一的
日志过滤器类，不太可能满足众多的要求（它只是作为基类存在），通常需要定义
自己的 *note Filter: c48. 子类，并重写 *note filter(): 220b. 方法。为此
，请在过滤器的配置字典中设置 ‘()’ 键，指定要用于创建过滤器的可调用对象（
最明显可用的就是给出一个类，但也可以提供任何一个可调用对象，只要能返回
*note Filter: c48. 实例即可）。下面是一个完整的例子：

     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')

以上示例展示了将配置数据传给构造实例的可调用对象，形式是关键字参数。运行
后将会输出：

     changed: hello

这说明过滤器按照配置的参数生效了。

需要额外注意的地方：

   * 如果在配置中无法直接引用可调用对象（比如位于不同的模块中，并且不能
     在配置字典所在的位置直接导入），则可以采用 ‘ext://...’ 的形式，正如
     *note 访问外部对象: 223c. 所述。例如，在上述示例中可以使用文本
     ‘'ext://__main__.MyFilter'’ 而不是 ‘MyFilter’ 对象。

   * 与过滤器一样，上述技术还可用于配置自定义 handler 和格式化对象。有关
     如何在日志配置中使用用户自定义对象的更多信息，请参阅 *note
     用户定义对象: 2232.，以及上述 *note 利用 dictConfig() 自定义
     handler: 4397. 的其他指南。


File: python.info,  Node: 异常信息的自定义格式化,  Next: 语音播报日志信息,  Prev: 用 dictConfig 配置过滤器,  Up: 日志操作手册

10.7.23 异常信息的自定义格式化
------------------------------

有时可能需要设置自定义的异常信息格式——考虑到会用到参数，假定要让每条日志
事件只占一行，即便存在异常信息也一样。这可以用自定义格式化类来实现，如下
所示：

     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', '') + '|'
             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()

运行后将会生成只有两行信息的文件：

     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'|

虽然上述处理方式很简单，但也给出了根据喜好对异常信息进行格式化输出的方案
。或许 *note traceback: 11c. 模块能满足更专门的需求。


File: python.info,  Node: 语音播报日志信息,  Next: 缓冲日志信息并按条件输出,  Prev: 异常信息的自定义格式化,  Up: 日志操作手册

10.7.24 语音播报日志信息
------------------------

有时可能需要以声音的形式呈现日志消息。如果系统自带了文本转语音 （TTS）功
能，即便没与 Python 关联也很容易做到。大多数 TTS 系统都有一个可运行的命
令行程序，在 handler 中可以用 *note subprocess: f9. 进行调用。这里假定
TTS 命令行程序不会与用户交互，或需要很长时间才会执行完毕，写入日志的信息
也不会多到影响用户查看，并且可以接受每次播报一条信息，以下示例实现了等一
条信息播完再处理下一条，可能会导致其他 handler 的等待。这个简短示例仅供
演示，假定 ‘espeak’ TTS 包已就绪：

     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())

运行后将会以女声播报“Hello”和“Goodbye”。

当然，上述方案也适用于其他 TTS 系统，甚至可以利用命令行运行的外部程序来
处理日志信息。


File: python.info,  Node: 缓冲日志信息并按条件输出,  Next: 通过配置将时间格式化为 UTC（GMT）格式,  Prev: 语音播报日志信息,  Up: 日志操作手册

10.7.25 缓冲日志信息并按条件输出
--------------------------------

有时可能需要将日志信息写入临时位置，仅在特定情况下才进行输出。比如在函数
中记录调试事件，若函数执行完成且没有错误，收集到的调试信息就无需输出，以
免造成日志混乱，但在出现错误时则需要输出全部的调试和错误信息。

以下例子展示了如何在日志函数上使用装饰器，以实现上述功能。这里用到了
*note logging.handlers.MemoryHandler: 223f. ，将日志事件缓存下来，直至发
生某些状况时，缓存的事件才会被送出（‘flushed’）——传给另一个 handler（
‘target’）进行处理。默认情况下， ‘MemoryHandler’ 在缓冲区满时，或者事件
级别大于等于指定阈值的，会将数据刷出。若需自定义刷新行为，可以利用定制
‘MemoryHandler’ 子类来实现。

以下例程包含一个简单的 ‘foo’ 函数 ，它只是循环运行于全部日志级别上，写入
‘sys.stderr’ ，输出信息包括日志级别和日志消息。可为 ‘foo’ 传入一个参数，
true 则在 ERROR 和 CRITICAL 级别记录日志，否则只在DEBUG、INFO 和 WARNING
级别记录日志。

这里只是为 ‘foo’ 加了个装饰器 ，进行有条件的日志记录。该装饰器以日志对象
为参数，并在调用被装饰函数期间增加一个内存处理 handler。该装饰器的参数还
可以加上目标 handler、日志级别和缓冲区的容量（可缓存的日志条数量）。这些
参数的默认值分别是写入 ‘sys.stderr’ 的 *note StreamHandler: c46. 、
‘logging.ERROR’ 和 ‘100’。

以下是脚本：

     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)

运行此脚本时，应看到以下输出：

     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

由上可见，只有发生 ERROR 以上级别的事件时才会实际输出日志，但之前发生的
低等级事件还是会被记入日志。

当然采用传统的装饰方法也是可以的：

     @log_if_errors(logger)
     def foo(fail=False):
         ...


File: python.info,  Node: 通过配置将时间格式化为 UTC（GMT）格式,  Next: 用上下文管理器选择性记录日志,  Prev: 缓冲日志信息并按条件输出,  Up: 日志操作手册

10.7.26 通过配置将时间格式化为 UTC（GMT）格式
---------------------------------------------

有时需要将时间格式化为 UTC 格式，可以用类似 ‘UTCFormatter’ 的类来完成，
如下所示：

     import logging
     import time

     class UTCFormatter(logging.Formatter):
         converter = time.gmtime

然后自己的代码中即可采用 ‘UTCFormatter’ 了，而不用 *note Formatter:
21de. 了。若要通过配置来实现，可以用 *note dictConfig(): bfe. API 来完成
，以下完整示例中将会演示这种方案：

     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())

脚本会运行输出类似下面的内容:

     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

以上将时间格式化为本地时间和 UTC 两种形式，每种形式对应一个 handler。


File: python.info,  Node: 用上下文管理器选择性记录日志,  Next: 命令行日志应用起步,  Prev: 通过配置将时间格式化为 UTC（GMT）格式,  Up: 日志操作手册

10.7.27 用上下文管理器选择性记录日志
------------------------------------

有时需要临时更改日志配置，并在执行某些操作后还原配置。这时，上下文管理器
正是最明显的方案，可以实现日志上下文的保存和恢复。以下是一个上下文管理器
的简单示例，只在上下文管理器的作用域内更改日志等级和增加日志 handler：

     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

如果给出了 level 值，则在上下文管理器 with 语句覆盖的作用域内，日志记录
级别将设置为 level 值。如果给出了 handler 值，则在进入作用域时将会将其加
入，离开时将会移除。如果后续用不到该 handler 了，则可在离开作用域时让上
下文管理器将其关闭。

为了演示上述过程，可加入以下代码：

     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.')

最开始日志级别设为 ‘INFO’，因此会显示 #1 信息，而 #2 信息则没有出现。接
下来的 ‘with’ 代码块中，暂时将日志级别变为 ‘DEBUG’，于是 #3 信息出现了。
在离开该代码块后，日志记录器的级别恢复为 ‘INFO’，从而 #4 信息没有出现。
在下一个 ‘with’ 代码块中，再次将日志级别设为 ‘DEBUG’，并且加入一个写入
‘sys.stdout’ 的日志 handler。因此，#5 信息在控制台出现了两次（分别由
‘stderr’ 和 ‘stdout’ 显示）。在 ‘with’ 语句执行完毕后，状态复原，因此显
示了 #6 信息（类似 #1），而 #7 信息没有出现（类似 #2）。

运行结果如下：

     $ 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.

但若将 ‘stderr’ 重定向到 ‘/dev/null’，再次运行一下，写入 ‘stdout’ 的将只
有以下信息：

     $ python logctx.py 2>/dev/null
     5. This should appear twice - once on stderr and once on stdout.

再把 ‘stdout’ 重定向到 ‘/dev/null’，结果将如下所示：

     $ 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.

这符合预期，输出到 ‘stdout’ 的 #5 信息不会显示出来。

当然，上述做法可以推广到其他应用，比如临时加入日志过滤器。请注意，上述代
码对 Python 2 和 3 均适用。


File: python.info,  Node: 命令行日志应用起步,  Next: 用作日志的 Qt GUI 程序,  Prev: 用上下文管理器选择性记录日志,  Up: 日志操作手册

10.7.28 命令行日志应用起步
--------------------------

下面的示例提供了如下功能：

   * 根据命令行参数确定日志级别

   * 在单独的文件中分发多条子命令，同一级别的日志子命令均以一致的方式记
     录。

   * 最简单的配置用法

假定有一个命令行应用程序，用于停止、启动或重新启动某些服务。为了便于演示
，不妨将 ‘app.py’ 作为应用程序的主代码文件，并在 ‘start.py’、
‘stop.py``和 ``restart.py’ 中实现单独的命令。再假定要通过命令行参数控制
应用程序的日志粒度，默认为 ‘logging.INFO’ 。以下是 ‘app.py’ 的一个示例：

     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\'' % 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())

‘start’、‘stop’ 和 ‘restart’ 命令可以在单独的模块中实现，启动命令的代码
可如下：

     # 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)

然后是停止命令的代码：

     # stop.py
     import logging

     logger = logging.getLogger(__name__)

     def command(options):
         n = len(options.names)
         if n == 1:
             plural = ''
             services = '\'%s\'' % options.names[0]
         else:
             plural = 's'
             services = ', '.join('\'%s\'' % 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)

重启命令类似：

     # restart.py
     import logging

     logger = logging.getLogger(__name__)

     def command(options):
         n = len(options.names)
         if n == 1:
             plural = ''
             services = '\'%s\'' % options.names[0]
         else:
             plural = 's'
             services = ', '.join('\'%s\'' % 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)

如果以默认日志级别运行该程序，会得到以下结果：

     $ 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.

第一个单词是日志级别，第二个单词是日志事件所在的模块或包的名称。

如果修改了日志级别，发送给日志的信息就能得以改变。如要显示更多信息，则可
：

     $ 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.

若要显示的信息少一些，则：

     $ 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

这里的命令不会向控制台输出任何信息，因为没有记录 ‘WARNING’ 以上级别的日
志。


File: python.info,  Node: 用作日志的 Qt GUI 程序,  Next: 理应避免的用法,  Prev: 命令行日志应用起步,  Up: 日志操作手册

10.7.29 用作日志的 Qt GUI 程序
------------------------------

如何将日志写入某个 GUI 应用程序，这是个常见的问题。 Qt(1) 框架是一个流行
的跨平台 UI 框架，采用的是 PySide2(2) 或 PyQt5(3) 库。

下面的例子演示了将日志写入 Qt GUI 程序的过程。这里引入了一个简单的
‘QtHandler’ 类，参数是一个可调用对象，其应为嵌入主线程某个“槽位”中运行的
，因为GUI 的更新由主线程完成。这里还创建了一个工作线程，以便演示由 UI（
通过人工点击日志按钮）和后台工作线程（此处只是记录级别和时间间隔均随机生
成的日志信息）将日志写入 GUI 的过程。

该工作线程是用 Qt 的 ‘QThread’ 类实现的，而不是 *note threading: 10b. 模
块，因为某些情况下只能采用 ‘`QThread’，它与其他 ‘Qt’ 组件的集成性更好一
些。

以下代码应能适用于最新版的 ‘PySide2’ 或 ‘PyQt5’。对于低版本的 Qt 应该也
能适用。更多详情，请参阅代码注释。

     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()

   ---------- Footnotes ----------

   (1) https://www.qt.io/

   (2) https://pypi.org/project/PySide2/

   (3) https://pypi.org/project/PyQt5/


File: python.info,  Node: 理应避免的用法,  Prev: 用作日志的 Qt GUI 程序,  Up: 日志操作手册

10.7.30 理应避免的用法
----------------------

前几节虽介绍了几种方案，描述了可能需要处理的操作，但值得一提的是，有些用
法是 `没有好处' 的，大多数情况下应该避免使用。下面几节的顺序不分先后。

* Menu:

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


File: python.info,  Node: 多次打开同一个日志文件,  Next: 将日志对象用作属性或传递参数,  Up: 理应避免的用法

10.7.30.1 多次打开同一个日志文件
................................

因会导致 "文件被其他进程占用 "错误，所以在 Windows 中一般无法多次打开同
一个文件。但在 POSIX 平台中，多次打开同一个文件不会报任何错误。这种操作
可能是意外发生的，比如：

   * 多次添加指向同一文件的 handler（比如通过复制/粘贴，或忘记修改）。

   * 打开两个貌似不同（文件名不一样）的文件，但一个是另一个的符号链接，
     所以其实是同一个文件。

   * 进程 fork，然后父进程和子进程都有对同一文件的引用。 例如，这可能是
     通过使用 *note multiprocessing: b7. 模块实现的。

在大多数情况下，多次打开同一个文件 `貌似' 一切正常，但实际会导致很多问题
。

   * 由于多个线程或进程会尝试写入同一个文件，日志输出可能会出现乱码。尽
     管日志对象可以防止多个线程同时使用同一个 handler 实例，但如果两个不
     同的线程使用不同的 handler 实例同时写入文件，而这两个 handler 又恰
     好指向同一个文件，那么就失去了这种防护。

   * 删除文件（例如在轮换日志文件时）会静默失败，因为有另一个引用指向这
     个文件。这可能导致混乱并浪费调试时间——日志项最后会出现在意想不到的
     地方，或者干脆丢失。

请用 *note 在单个文件中记录多个进程的日志: 4387. 中介绍的技术来避免上述
问题。


File: python.info,  Node: 将日志对象用作属性或传递参数,  Next: 给日志库代码添加 NullHandler 之外的其他 handler,  Prev: 多次打开同一个日志文件,  Up: 理应避免的用法

10.7.30.2 将日志对象用作属性或传递参数
......................................

虽然特殊情况下可能有必要如此，但一般来说没有意义，因为日志是单实例对象。
代码总是可以通过 ‘logging.getLogger(name)’ 用名称访问一个已有的日志对象
实例，因此将实例作为参数来传递，或作为属性留存，都是毫无意义的。请注意，
在其他语言中，如 Java 和 C#，日志对象通常是静态类属性。但在 Python 中是
没有意义的，因为软件拆分的单位是模块（而不是类）。


File: python.info,  Node: 给日志库代码添加 NullHandler 之外的其他 handler,  Next: 创建大量的日志对象,  Prev: 将日志对象用作属性或传递参数,  Up: 理应避免的用法

10.7.30.3 给日志库代码添加 ‘NullHandler’ 之外的其他 handler
...........................................................

通过添加 handler、formatter 和 filter 来配置日志，这是应用程序开发人员的
责任，而不是库开发人员该做的。如果正在维护一个库，请确保不要向任何日志对
象添加 *note NullHandler: ce6. 实例以外的 handler。


File: python.info,  Node: 创建大量的日志对象,  Prev: 给日志库代码添加 NullHandler 之外的其他 handler,  Up: 理应避免的用法

10.7.30.4 创建大量的日志对象
............................

日志是单实例对象，在代码执行过程中不会被释放，因此创建大量的日志对象会占
用很多内存，而这些内存又不能被释放。与其为每个文件或网络连接创建一个日志
，还不如利用 *note 已有机制: 2218. 将上下文信息传给自定义日志对象，并将
创建的日志对象限制在应用程序内的指定区域（通常是模块，但偶尔会再精细些）
使用。


File: python.info,  Node: 如何使用正規表達式,  Next: 套接字编程指南,  Prev: 日志操作手册,  Up: Python 如何達成任務

10.8 如何使用正規表達式
=======================


作者: A.M. Kuchling <<amk@amk.ca>>

摘要
....

此文件為如何在 Python 中使用 *note re: dd. 模組來撰寫正規表達式的入門指
導。進階使用及參考文件請見函式庫參考一章。

* Menu:

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


File: python.info,  Node: 簡介<14>,  Next: 简单模式,  Up: 如何使用正規表達式

10.8.1 簡介
-----------

正規表示式 (也稱為 REs、regexes 或 regex patterns) 是一個輕量且高專業化
的程式語言。在 Python 中可透過內建的 *note re: dd. 模組直接使用。你可以
使用此輕量化的語言針對想要匹配的一組字串撰寫規則，這組字串可能包含了英語
句子、e-mail 地址、TeX 命令或任何東西。你可以檢查如「這組字串是否匹配這
個規則？」或「這組字串中是否有任一處匹配這個規則？」。除此之外，你也可以
使用 REs 來修改或是切割字串。

正则表达式模式被编译成一系列字节码，然后由用 C 编写的匹配引擎执行。对于
高级用途，可能需要特别注意引擎如何执行给定的正则，并将正则写入以某种方式
生成运行速度更快的字节码。 本文档未涉及优化，因为它要求你充分了解匹配引
擎的内部结构。

正则表达式语言相对较小且受限制，因此并非所有可能的字符串处理任务都可以使
用正则表达式完成。 还有一些任务 `可以' 用正则表达式完成，但表达式变得非
常复杂。 在这些情况下，你最好编写 Python 代码来进行处理；虽然 Python 代
码比精心设计的正则表达式慢，但它也可能更容易理解。


File: python.info,  Node: 简单模式,  Next: 使用正则表达式,  Prev: 簡介<14>,  Up: 如何使用正規表達式

10.8.2 简单模式
---------------

我们首先要了解最简单的正则表达式。 由于正则表达式用于对字符串进行操作，
因此我们将从最常见的任务开始：匹配字符。

有关正则表达式（确定性和非确定性有限自动机）的计算机科学的详细解释，你可
以参考几乎所有有关编写编译器的教科书。

* Menu:

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


File: python.info,  Node: 匹配字符,  Next: 重复,  Up: 简单模式

10.8.2.1 匹配字符
.................

大多数字母和字符只会匹配自己。 例如，正则表达式 ‘test’ 将完全匹配字符串
‘test’ 。 （你可以启用一个不区分大小写的模式，让这个正则匹配 ‘Test’ 或
‘TEST’，稍后会详细介绍。）

这条规则有例外；一些字符是特殊的 `metacharacters' ，并且不匹配自己。 相
反，它们表示应该匹配一些与众不同的东西，或者通过重复它们或改变它们的含义
来影响正则的其他部分。 本文档的大部分内容都致力于讨论各种元字符及其功能
。

这是元字符的完整列表；它们的意思将在本HOWTO的其余部分讨论。

     . ^ $ * + ? { } [ ] \ | ( )

我们将看到的第一个元字符是 ‘[’ 和 ‘]’ 。 它们用于指定字符类，它是你希望
匹配的一组字符。 可以单独列出字符，也可以通过给出两个字符并用 ‘'-'’ 标记
将它们分开来表示一系列字符。 例如， ‘[abc]’ 将匹配任何字符 ‘a’、 ‘b’ 或
‘c’ ；这与 ‘[a-c]’ 相同，它使用一个范围来表示同一组字符。 如果你只想匹配
小写字母，你的正则是 ‘[a-z]’ 。

字符类中的元字符不生效。 例如，‘[akm$]’ 将匹配 ‘'a'’ ， ‘'k'’ 、 ‘'m'’ 或
‘'$'’ 中的任意字符； ‘'$'’ 通常是一个元字符，但在一个字符类中它被剥夺了
特殊性。

你可以通过以下方式匹配 `complementing' 设置的字符类中未列出的字符。这通
过包含一个 ‘'^'’ 作为该类的第一个字符来表示。 例如，‘[^5]’ 将匹配除
‘'5'’ 之外的任何字符。 如果插入符出现在字符类的其他位置，则它没有特殊含
义。 例如：‘[5^]’ 将匹配 ‘'5'’ 或 ‘'^'’。

也许最重要的元字符是反斜杠，‘\’。 与 Python 字符串文字一样，反斜杠后面可
以跟各种字符，以指示各种特殊序列。它也用于转义所有元字符，因此您仍然可以
在模式中匹配它们；例如，如果你需要匹配 ‘[’ 或 ‘\’，你可以在它们前面加一
个反斜杠来移除它们的特殊含义：‘\[’ 或 ‘\\’。

一些以 ‘'\'’ 开头的特殊序列表示通常有用的预定义字符集，例如数字集、字母
集或任何非空格的集合。

让我们举一个例子：‘\w’ 匹配任何字母数字字符。 如果正则表达式模式以字节类
表示，这相当于类 ‘[a-zA-Z0-9_]’。如果正则表达式是一个字符串，‘\w’ 将匹配
由 *note unicodedata: 123. 模块提供的 Unicode 数据库中标记为字母的所有字
符。 通过在编译正则表达式时提供 *note re.ASCII: 4ce. 标志，可以在字符串
模式中使用更为受限制的 ‘\w’ 定义。

以下特殊序列列表不完整。 有关 Unicode 字符串模式的序列和扩展类定义的完整
列表，请参阅标准库参考中的最后一部分 *note 正则表达式语法: 1893. 。通常
，Unicode 版本匹配 Unicode 数据库中相应类别中的任何字符。

‘\d’

     匹配任何十进制数字；这等价于类 ‘[0-9]’。

‘\D’

     匹配任何非数字字符；这等价于类 ‘[^0-9]’。

‘\s’

     匹配任何空白字符；这等价于类 ‘[ \t\n\r\f\v]’。

‘\S’

     匹配任何非空白字符；这相当于类 ‘[^ \t\n\r\f\v]’。

‘\w’

     匹配任何字母与数字字符；这相当于类 ‘[a-zA-Z0-9_]’。

‘\W’

     匹配任何非字母与数字字符；这相当于类 ‘[^a-zA-Z0-9_]’。

这些序列可以包含在字符类中。 例如，‘[\s,.]’ 是一个匹配任何空格字符的字符
类或者 ‘','’ ，或 ‘'.'’。

本节的最后一个元字符是 ‘.’ 。 它匹配除换行符之外的任何内容，并且有一个可
选模式（ *note re.DOTALL: 1897. ）甚至可以匹配换行符。 ‘.’ 常用于你想匹
配“任何字符”的地方。


File: python.info,  Node: 重复,  Prev: 匹配字符,  Up: 简单模式

10.8.2.2 重复
.............

能够匹配不同的字符集合是正则表达式可以做的第一件事，这对于字符串可用方法
来说是不可能的。 但是，如果这是正则表达式的唯一额外功能，那么它们就不会
有太大的优势。 另一个功能是你可以指定正则的某些部分必须重复一定次数。

重复中我们要了解的第一个元字符是 ‘*’。 ‘*’ 与字面字符 ‘'*'’ 不匹配；相反
，它指定前一个字符可以匹配零次或多次，而不是恰好一次。

例如，‘ca*t’ 将匹配 ‘'ct'’ (0个 ‘'a'’ 字符)，‘'cat'’ (1个 ‘'a'’ )，
‘'caaat'’ (3个 ‘'a'’ 字符)，等等。

类似 ‘*’ 这样的重复是 `贪婪的'；当重复正则时，匹配引擎将尝试尽可能多地重
复它。 如果模式的后续部分不匹配，则匹配引擎将回退并以较少的重复次数再次
尝试。

一个逐步的例子将使这更加明显。 让我们考虑表达式 ‘a[bcd]*b’。 这个正则匹
配字母 ‘'a'’，类 ‘[bcd]’ 中的零或多个字母，最后以 ‘'b'’ 结尾。 现在想象
一下这个正则与字符串 ‘'abcbd'’ 匹配。

步骤       匹配            解释
                           
-----------------------------------------------------------------
                           
1          ‘a’             正则中的 ‘a’ 匹配。
                           
                           
2          ‘abcbd’         引擎尽可能多地匹配 ‘[bcd]*’ ，直到
                           字符串结束。
                           
                           
3          `失败'          引擎尝试匹配 ‘b’ ，但是当前位置位于
                           字符串结束，所以匹配失败。
                           
                           
4          ‘abcb’          回退一次，‘[bcd]*’ 少匹配一个字符。
                           
                           
5          `失败'          再次尝试匹配 ‘b’ ， 但是当前位置是
                           最后一个字符 ‘'d'’ 。
                           
                           
6          ‘abc’           再次回退，所以 ‘[bcd]*’ 只匹配 ‘bc’
                           。
                           
                           
6          ‘abcb’          再试一次 ‘b’ 。 这次当前位置的字符
                           是 ‘'b'’ ，所以它成功了。
                           

正则现在已经结束了，它已经匹配了 ‘'abcb'’。 这演示了匹配引擎最初如何进行
，如果没有找到匹配，它将逐步回退并一次又一次地重试正则的其余部分。 它将
回退，直到它为 ‘[bcd]*’ 尝试零匹配，如果随后失败，引擎将断定该字符串与正
则完全不匹配。

另一个重复的元字符是 ‘+’，它匹配一次或多次。 要特别注意 ‘*’ 和 ‘+’ 之间
的区别；‘*’ 匹配 `零次' 或更多次，因此重复的任何东西都可能根本不存在，而
‘+’ 至少需要 `一次'。 使用类似的例子，‘ca+t’ 将匹配 ‘'cat'’ (1 个
‘'a'’)，‘'caaat'’ (3 个 ‘'a'’)，但不会匹配 ‘'ct'’。

还有两个重复限定符。 问号字符 ‘?’ 匹配一次或零次；你可以把它想象成是可选
的。 例如，‘home-?brew’ 匹配 ‘'homebrew'’ 或 ‘'home-brew'’。

最复杂的重复限定符是 ‘{m,n}’，其中 `m' 和 `n' 是十进制整数。 这个限定符
意味着必须至少重复 `m' 次，最多重复 `n' 次。 例如，‘a/{1,3}b’ 将匹配
‘'a/b'’ ，‘'a//b'’ 和 ‘'a///b'’ 。 它不匹配没有斜线的 ‘'ab'’，或者有四个
的 ‘'a////b'’。

你可以省略 `m' 或 `n'; 在这种情况下，将假定缺失值的合理值。 省略 `m' 被
解释为 0 下限，而省略 `n' 则为无穷大的上限。

还原论者的读者可能会注意到其他三个限定符都可以用这种表示法表达。 ‘{0,}’
与 ‘*’ 相同， ‘{1,}’ 相当于 ‘+’ ， ‘{0,1}’ 和 ‘?’ 相同。 最好使用 ‘*’ ，
‘+’ 或 ‘?’ ，只要因为它们更短更容易阅读。


File: python.info,  Node: 使用正则表达式,  Next: 更多模式能力,  Prev: 简单模式,  Up: 如何使用正規表達式

10.8.3 使用正则表达式
---------------------

现在我们已经看了一些简单的正则表达式，我们如何在 Python 中实际使用它们？
*note re: dd. 模块提供了正则表达式引擎的接口，允许你将正则编译为对象，然
后用它们进行匹配。

* Menu:

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


File: python.info,  Node: 编译正则表达式,  Next: 反斜杠灾难,  Up: 使用正则表达式

10.8.3.1 编译正则表达式
.......................

正则表达式被编译成模式对象，模式对象具有各种操作的方法，例如搜索模式匹配
或执行字符串替换。:

     >>> import re
     >>> p = re.compile('ab*')
     >>> p
     re.compile('ab*')

*note re.compile(): 54c. 也接受一个可选的 `flags' 参数，用于启用各种特殊
功能和语法变体。 我们稍后将介绍可用的设置，但现在只需一个例子

     >>> p = re.compile('ab*', re.IGNORECASE)

正则作为字符串传递给 *note re.compile(): 54c. 。 正则被处理为字符串，因
为正则表达式不是核心Python语言的一部分，并且没有创建用于表达它们的特殊语
法。 （有些应用程序根本不需要正则，因此不需要通过包含它们来扩展语言规范
。）相反，*note re: dd. 模块只是Python附带的C扩展模块，就类似于 *note
socket: ef. 或 *note zlib: 14d. 模块。

将正则放在字符串中可以使 Python 语言更简单，但有一个缺点是下一节的主题。


File: python.info,  Node: 反斜杠灾难,  Next: 应用匹配,  Prev: 编译正则表达式,  Up: 使用正则表达式

10.8.3.2 反斜杠灾难
...................

如前所述，正则表达式使用反斜杠字符 (‘'\'’) 来表示特殊形式或允许使用特殊
字符而不调用它们的特殊含义。 这与 Python 在字符串文字中用于相同目的的相
同字符的使用相冲突。

假设你想要编写一个与字符串 ‘\section’ 相匹配的正则，它可以在 LaTeX 文件
中找到。 要找出在程序代码中写入的内容，请从要匹配的字符串开始。 接下来，
您必须通过在反斜杠前面添加反斜杠和其他元字符，从而产生字符串
‘\\section’。 必须传递给 *note re.compile(): 54c. 的结果字符串必须是
‘\\section’。 但是，要将其表示为 Python 字符串文字，必须 `再次' 转义两个
反斜杠。

字符                    阶段
                        
-----------------------------------------------------------------------
                        
‘\section’              被匹配的字符串
                        
                        
‘\\section’             为 *note re.compile(): 54c. 转义的反斜杠
                        
                        
‘"\\\\section"’         为字符串字面转义的反斜杠
                        

简而言之，要匹配文字反斜杠，必须将 ‘'\\\\'’ 写为正则字符串，因为正则表达
式必须是 ‘\\’，并且每个反斜杠必须表示为 ‘\\’ 在常规Python字符串字面中。
在反复使用反斜杠的正则中，这会导致大量重复的反斜杠，并使得生成的字符串难
以理解。

解决方案是使用 Python 的原始字符串表示法来表示正则表达式；反斜杠不以任何
特殊的方式处理前缀为 ‘'r'’ 的字符串字面，因此 ‘r"\n"’ 是一个包含 ‘'\'’ 和
‘'n'’ 的双字符字符串，而 ‘"\n"’ 是一个包含换行符的单字符字符串。 正则表
达式通常使用这种原始字符串表示法用 Python 代码编写。

此外，在正则表达式中有效但在 Python 字符串文字中无效的特殊转义序列现在导
致 *note DeprecationWarning: 15a. 并最终变为 *note SyntaxError: 559.。 这
意味着如果未使用原始字符串表示法或转义反斜杠，序列将无效。

常规字符串              原始字符串
                        
-----------------------------------------------
                        
‘"ab*"’                 ‘r"ab*"’
                        
                        
‘"\\\\section"’         ‘r"\\section"’
                        
                        
‘"\\w+\\s+\\1"’         ‘r"\w+\s+\1"’
                        


File: python.info,  Node: 应用匹配,  Next: 模块级别函数,  Prev: 反斜杠灾难,  Up: 使用正则表达式

10.8.3.3 应用匹配
.................

一旦你有一个表示编译正则表达式的对象，你用它做什么？ 模式对象有几种方法
和属性。 这里只介绍最重要的内容；请参阅 *note re: dd. 文档获取完整列表。

方法 / 属性            目的
                       
---------------------------------------------------------------------------
                       
‘match()’              确定正则是否从字符串的开头匹配。
                       
                       
‘search()’             扫描字符串，查找此正则匹配的任何位置。
                       
                       
‘findall()’            找到正则匹配的所有子字符串，并将它们作为列表返回
                       。
                       
                       
‘finditer()’           找到正则匹配的所有子字符串，并将它们返回为一个
                       *note iterator: 1171.。
                       

如果没有找到匹配， *note match(): 18a2. 和 *note search(): 18a3. 返回
‘None’ 。如果它们成功， 一个 *note 匹配对象: 984. 实例将被返回，包含匹配
相关的信息：起始和终结位置、匹配的子串以及其它。

你可以通过交互式实验 *note re: dd. 模块来了解这一点。 如果你有 *note
tkinter: 10e.，你可能还想查看 Tools/demo/redemo.py(1)，这是 Python 发行
附带的演示程序。 它允许你输入正则和字符串，并显示RE是匹配还是失败。
‘redemo.py’ 在尝试调试复杂的正则时非常有用。

本 HOWTO 使用标准 Python 解释器作为示例。 首先，运行 Python 解释器，导入
*note re: dd. 模块，然后编译一个正则

     >>> import re
     >>> p = re.compile('[a-z]+')
     >>> p
     re.compile('[a-z]+')

现在，你可以尝试匹配正则 ‘[a-z]+’ 的各种字符串。 空字符串根本不匹配，因
为 ‘+’ 表示“一次或多次重复”。 *note match(): 18a2. 在这种情况下应返回
‘None’，这将导致解释器不打印输出。 你可以显式打印 ‘match()’ 的结果，使其
清晰。:

     >>> p.match("")
     >>> print(p.match(""))
     None

现在，让我们尝试一下它应该匹配的字符串，例如 ‘tempo’。在这个例子中 *note
match(): 18a2. 将返回一个 *note 匹配对象: 984.，因此你应该将结果储存到一
个变量中以供稍后使用。

     >>> m = p.match('tempo')
     >>> m
     <re.Match object; span=(0, 5), match='tempo'>

现在你可以检查 *note 匹配对象: 984. 以获取有关匹配字符串的信息。 匹配对
象实例也有几个方法和属性；最重要的是：

方法 / 属性            目的
                       
------------------------------------------------------------------------
                       
‘group()’              返回正则匹配的字符串
                       
                       
‘start()’              返回匹配的开始位置
                       
                       
‘end()’                返回匹配的结束位置
                       
                       
‘span()’               返回包含匹配 (start, end) 位置的元组
                       

尝试这些方法很快就会清楚它们的含义:

     >>> m.group()
     'tempo'
     >>> m.start(), m.end()
     (0, 5)
     >>> m.span()
     (0, 5)

*note group(): 18b7. 返回正则匹配的子字符串。 *note start(): 18bb. 和
*note end(): 18bc. 返回匹配的起始和结束索引。 *note span(): 18bd. 在单个
元组中返回开始和结束索引。 由于 *note match(): 18a2. 方法只检查正则是否
在字符串的开头匹配，所以 ‘start()’ 将始终为零。 但是，模式的 *note
search(): 18a3. 方法会扫描字符串，因此在这种情况下匹配可能不会从零开始。
:

     >>> 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)

在实际程序中，最常见的样式是在变量中存储 *note 匹配对象: 984.，然后检查
它是否为 ‘None’。 这通常看起来像:

     p = re.compile( ... )
     m = p.match( 'string goes here' )
     if m:
         print('Match found: ', m.group())
     else:
         print('No match')

两种模式方法返回模式的所有匹配项。 *note findall(): 18ad. 返回匹配字符串
的列表:

     >>> p = re.compile(r'\d+')
     >>> p.findall('12 drummers drumming, 11 pipers piping, 10 lords a-leaping')
     ['12', '11', '10']

在这个例子中需要 ‘r’ 前缀，使字面为原始字符串字面，因为普通的“加工”字符
串字面中的转义序列不能被 Python 识别为正则表达式，导致 *note
DeprecationWarning: 15a. 并最终产生 *note SyntaxError: 559.。 请参阅
*note 反斜杠灾难: 43ba.。

*note findall(): 18ad. 必须先创建整个列表才能返回结果。 *note
finditer(): 18ae. 方法将一个 *note 匹配对象: 984. 的序列返回为一个 *note
iterator: 1171.

     >>> 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)

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Tools/demo/redemo.py


File: python.info,  Node: 模块级别函数,  Next: 编译标志,  Prev: 应用匹配,  Up: 使用正则表达式

10.8.3.4 模块级别函数
.....................

你不必创建模式对象并调用其方法；*note re: dd. 模块还提供了顶级函数 *note
match(): c83.，*note search(): c82.，*note findall(): a44.，*note sub():
579. 等等。 这些函数采用与相应模式方法相同的参数，并将正则字符串作为第一
个参数添加，并仍然返回 ‘None’ 或 *note 匹配对象: 984. 实例。:

     >>> 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 '>

本质上，这些函数只是为你创建一个模式对象，并在其上调用适当的方法。 它们
还将编译对象存储在缓存中，因此使用相同的未来调用将不需要一次又一次地解析
该模式。

你是否应该使用这些模块级函数，还是应该自己获取模式并调用其方法？ 如果你
正在循环中访问正则表达式，预编译它将节省一些函数调用。 在循环之外，由于
有内部缓存，没有太大区别。


File: python.info,  Node: 编译标志,  Prev: 模块级别函数,  Up: 使用正则表达式

10.8.3.5 编译标志
.................

编译标志允许你修改正则表达式的工作方式。 标志在 *note re: dd. 模块中有两
个名称，长名称如 ‘IGNORECASE’ 和一个简短的单字母形式，例如 ‘I’。 （如果
你熟悉 Perl 的模式修饰符，则单字母形式使用和其相同的字母；例如， *note
re.VERBOSE: 18a6. 的缩写形式为 *note re.X: 189e.。）多个标志可以 通过按
位或运算来指定它们；例如，‘re.I | re.M’ 设置 ‘I’ 和 ‘M’ 标志。

这是一个可用标志表，以及每个标志的更详细说明。

标志                                  意义
                                      
---------------------------------------------------------------------------------------
                                      
‘ASCII’, ‘A’                          使几个转义如 ‘\w’、‘\b’、‘\s’ 和 ‘\d’ 匹配仅与
                                      具有相应特征属性的 ASCII 字符匹配。
                                      
                                      
‘DOTALL’, ‘S’                         使 ‘.’ 匹配任何字符，包括换行符。
                                      
                                      
‘IGNORECASE’, ‘I’                     进行大小写不敏感匹配。
                                      
                                      
‘LOCALE’, ‘L’                         进行区域设置感知匹配。
                                      
                                      
‘MULTILINE’, ‘M’                      多行匹配，影响 ‘^’ 和 ‘$’。
                                      
                                      
‘VERBOSE’, ‘X’ （为 ’扩展’）          启用详细的正则，可以更清晰，更容易理解。
                                      

 -- Data: I

 -- Data: IGNORECASE

     执行不区分大小写的匹配；字符类和字面字符串将通过忽略大小写来匹配字
     母。 例如，‘[A-Z]’ 也匹配小写字母。 除非使用 ‘ASCII’ 标志来禁用非
     ASCII匹配，否则完全 Unicode 匹配也有效。 当 Unicode 模式 ‘[a-z]’ 或
     ‘[A-Z]’ 与 ‘IGNORECASE’ 标志结合使用时，它们将匹配 52 个 ASCII 字母
     和 4 个额外的非 ASCII 字母：’İ’ (U+0130，拉丁大写字母 I，带上面的点
     )，’ı’ (U+0131，拉丁文小写字母无点 i)，’s’ (U+017F，拉丁文小写字母
     长 s) 和’K’ (U+212A，开尔文符号)。 ‘Spam’ 将匹配 ‘'Spam'’，
     ‘'spam'’，‘'spAM'’ 或 ‘'ſpam'’ (后者仅在 Unicode 模式下匹配)。 此小
     写不考虑当前区域设置；如果你还设置了 ‘LOCALE’ 标志，则将考虑。

 -- Data: L

 -- Data: LOCALE

     使 ‘\w’、‘\W’、‘\b’、‘\B’ 和大小写敏感匹配依赖于当前区域而不是
     Unicode 数据库。

     区域设置是 C 库的一个功能，旨在帮助编写考虑到语言差异的程序。例如，
     如果你正在处理编码的法语文本，那么你希望能够编写 ‘\w+’ 来匹配单词，
     但 ‘\w’ 只匹配字符类 ‘[A-Za-z]’ 字节模式；它不会匹配对应于 ‘é’ 或
     ‘ç’ 的字节。如果你的系统配置正确并且选择了法语区域设置，某些C函数将
     告诉程序对应于 ‘é’ 的字节也应该被视为字母。在编译正则表达式时设置
     ‘LOCALE’ 标志将导致生成的编译对象将这些C函数用于 ‘\w’；这比较慢，但
     也可以使 ‘\w+’ 匹配你所期望的法语单词。在 Python 3 中不鼓励使用此标
     志，因为语言环境机制非常不可靠，它一次只处理一个“文化”，它只适用于
     8 位语言环境。默认情况下，Python 3 中已经为 Unicode（str）模式启用
     了 Unicode 匹配，并且它能够处理不同的区域/语言。

 -- Data: M

 -- Data: MULTILINE

     (‘^’ 和 ‘$’ 还没有解释；它们将在以下部分介绍 *note 更多元字符:
     43be.。)

     通常 ‘^’ 只匹配字符串的开头，而 ‘$’ 只匹配字符串的结尾，紧接在字符
     串末尾的换行符（如果有的话）之前。 当指定了这个标志时，‘^’ 匹配字符
     串的开头和字符串中每一行的开头，紧跟在每个换行符之后。 类似地，‘$’
     元字符匹配字符串的结尾和每行的结尾（紧接在每个换行符之前）。

 -- Data: S

 -- Data: DOTALL

     使 ‘'.'’ 特殊字符匹配任何字符，包括换行符；没有这个标志，‘'.'’ 将匹
     配任何字符 `除了' 换行符。

 -- Data: A

 -- Data: ASCII

     使 ‘\w’、‘\W’、‘\b’、‘\B’、‘\s’ 和 ‘\S’ 执行仅 ASCII 匹配而不是完整
     匹配 Unicode 匹配。 这仅对 Unicode 模式有意义，并且对于字节模式将被
     忽略。

 -- Data: X

 -- Data: VERBOSE

     此标志允许你编写更易读的正则表达式，方法是为您提供更灵活的格式化方
     式。 指定此标志后，将忽略正则字符串中的空格，除非空格位于字符类中或
     前面带有未转义的反斜杠；这使你可以更清楚地组织和缩进正则。 此标志还
     允许你将注释放在正则中，引擎将忽略该注释；注释标记为 ‘'#'’ 既不是在
     字符类中，也不是在未转义的反斜杠之前。

     例如，这里的正则使用 *note re.VERBOSE: 18a6.；看看阅读有多容易？:

          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)

     如果没有详细设置，正则将如下所示:

          charref = re.compile("&#(0[0-7]+"
                               "|[0-9]+"
                               "|x[0-9a-fA-F]+);")

     在上面的例子中，Python的字符串文字的自动连接已被用于将正则分解为更
     小的部分，但它仍然比以下使用 *note re.VERBOSE: 18a6. 版本更难理解。


File: python.info,  Node: 更多模式能力,  Next: 修改字符串,  Prev: 使用正则表达式,  Up: 如何使用正規表達式

10.8.4 更多模式能力
-------------------

到目前为止，我们只介绍了正则表达式的一部分功能。 在本节中，我们将介绍一
些新的元字符，以及如何使用组来检索匹配的文本部分。

* Menu:

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


File: python.info,  Node: 更多元字符,  Next: 分组,  Up: 更多模式能力

10.8.4.1 更多元字符
...................

我们还没有涉及到一些元字符。 其中大部分内容将在本节中介绍。

要讨论的其余一些元字符是 `零宽度断言' 。 它们不会使解析引擎在字符串中前
进一个字符；相反，它们根本不占用任何字符，只是成功或失败。例如，‘\b’ 是
一个断言，指明当前位置位于字边界；这个位置根本不会被 ‘\b’ 改变。这意味着
永远不应重复零宽度断言，因为如果它们在给定位置匹配一次，它们显然可以无限
次匹配。

‘|’

     或者“or”运算符。 如果 `A' 和 `B' 是正则表达式，‘A|B’ 将匹配任何与
     `A' 或 `B' 匹配的字符串。 ‘|’ 具有非常低的优先级，以便在交替使用多
     字符字符串时使其合理地工作。 ‘Crow|Servo’ 将匹配 ‘'Crow'’ 或
     ‘'Servo'’，而不是 ‘'Cro'’、‘'w'’ 或 ‘'S'’ 和 ‘'ervo'’。

     要匹配字面 ‘'|'’，请使用 ‘\|’，或将其括在字符类中，如 ‘[|]’。

‘^’

     在行的开头匹配。 除非设置了 ‘MULTILINE’ 标志，否则只会在字符串的开
     头匹配。 在 ‘MULTILINE’ 模式下，这也在字符串中的每个换行符后立即匹
     配。

     例如，如果你希望仅在行的开头匹配单词 ‘From’，则要使用的正则
     ‘^From’。:

          >>> print(re.search('^From', 'From Here to Eternity'))
          <re.Match object; span=(0, 4), match='From'>
          >>> print(re.search('^From', 'Reciting From Memory'))
          None

     要匹配字面 ‘'^'’，使用 ‘\^’。

‘$’

     匹配行的末尾，定义为字符串的结尾，或者后跟换行符的任何位置。:

          >>> 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='}'>

     以匹配字面 ‘'$'’，使用 ‘\$’ 或者将其包裹在一个字符类中，例如 ‘[$]’。

‘\A’

     仅匹配字符串的开头。 当不在 ‘MULTILINE’ 模式时，‘\A’ 和 ‘^’ 实际上
     是相同的。 在 ‘MULTILINE’ 模式中，它们是不同的: ‘\A’ 仍然只在字符串
     的开头匹配，但 ‘^’ 可以匹配在换行符之后的字符串内的任何位置。

‘\Z’

     只匹配字符串尾。

‘\b’

     字边界。 这是一个零宽度断言，仅在单词的开头或结尾处匹配。 单词被定
     义为一个字母数字字符序列，因此单词的结尾由空格或非字母数字字符表示
     。

     以下示例仅当它是一个完整的单词时匹配 ‘class’；当它包含在另一个单词
     中时将不会匹配。

          >>> 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

     使用这个特殊序列时，你应该记住两个细微之处。 首先，这是 Python 的字
     符串文字和正则表达式序列之间最严重的冲突。 在 Python 的字符串文字中
     ，‘\b’ 是退格字符，ASCII 值为8。 如果你没有使用原始字符串，那么
     Python 会将 ‘\b’ 转换为退格，你的正则不会按照你的预期匹配。 以下示
     例与我们之前的正则看起来相同，但省略了正则字符串前面的 ‘'r'’。:

          >>> 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'>

     其次，在一个字符类中，这个断言没有用处，‘\b’ 表示退格字符，以便与
     Python 的字符串文字兼容。

‘\B’

     另一个零宽度断言，这与 ‘\b’ 相反，仅在当前位置不在字边界时才匹配。


File: python.info,  Node: 分组,  Next: 非捕获和命名组,  Prev: 更多元字符,  Up: 更多模式能力

10.8.4.2 分组
.............

通常，你需要获取更多信息，而不仅仅是正则是否匹配。 正则表达式通常用于通
过将正则分成几个子组来解析字符串，这些子组匹配不同的感兴趣组件。 例如，
RFC-822 标题行分为标题名称和值，用 ‘':'’ 分隔，如下所示：

     From: author@example.com
     User-Agent: Thunderbird 1.5.0.9 (X11/20061227)
     MIME-Version: 1.0
     To: editor@example.com

这可以通过编写与整个标题行匹配的正则表达式来处理，并且具有与标题名称匹配
的一个组，以及与标题的值匹配的另一个组。

组由 ‘'('’，‘')'’ 元字符标记。 ‘'('’ 和 ‘')'’ 与数学表达式的含义大致相同
；它们将包含在其中的表达式组合在一起，你可以使用重复限定符重复组的内容，
例如 ‘*’，‘+’，‘?’ 或 ‘{m,n}’。 例如，‘(ab)*’ 将匹配 ‘ab’ 的零次或多次重
复。:

     >>> p = re.compile('(ab)*')
     >>> print(p.match('ababababab').span())
     (0, 10)

用 ‘'('’，‘')'’ 表示的组也捕获它们匹配的文本的起始和结束索引；这可以通过
将参数传递给 *note group(): 18b7.、*note start(): 18bb.、*note end():
18bc. 以及 *note span(): 18bd.。 组从 0 开始编号。组 0 始终存在；它表示
整个正则，所以 *note 匹配对象: 984. 方法都将组 0 作为默认参数。 稍后我们
将看到如何表达不捕获它们匹配的文本范围的组。:

     >>> p = re.compile('(a)b')
     >>> m = p.match('ab')
     >>> m.group()
     'ab'
     >>> m.group(0)
     'ab'

子组从左到右编号，从 1 向上编号。 组可以嵌套；要确定编号，只需计算从左到
右的左括号字符。:

     >>> p = re.compile('(a(b)c)d')
     >>> m = p.match('abcd')
     >>> m.group(0)
     'abcd'
     >>> m.group(1)
     'abc'
     >>> m.group(2)
     'b'

*note group(): 18b7. 可以一次传递多个组号，在这种情况下，它将返回一个包
含这些组的相应值的元组。:

     >>> m.group(2,1,2)
     ('b', 'abc', 'b')

*note groups(): 18b9. 方法返回一个元组，其中包含所有子组的字符串，从1到
最后一个子组。:

     >>> m.groups()
     ('abc', 'b')

模式中的后向引用允许你指定还必须在字符串中的当前位置找到先前捕获组的内容
。 例如，如果可以在当前位置找到组 1 的确切内容，则 ‘\1’ 将成功，否则将失
败。 请记住，Python 的字符串文字也使用反斜杠后跟数字以允许在字符串中包含
任意字符，因此正则中引入反向引用时务必使用原始字符串。

例如，以下正则检测字符串中的双字。:

     >>> p = re.compile(r'\b(\w+)\s+\1\b')
     >>> p.search('Paris in the the spring').group()
     'the the'

像这样的后向引用通常不仅仅用于搜索字符串 —— 很少有文本格式以这种方式重复
数据 —— 但是你很快就会发现它们在执行字符串替换时 `非常' 有用。


File: python.info,  Node: 非捕获和命名组,  Next: 前向断言,  Prev: 分组,  Up: 更多模式能力

10.8.4.3 非捕获和命名组
.......................

精心设计的正则可以使用许多组，既可以捕获感兴趣的子串，也可以对正则本身进
行分组和构建。 在复杂的正则中，很难跟踪组号。 有两个功能可以帮助解决这个
问题。 它们都使用常用语法进行正则表达式扩展，因此我们首先看一下。

Perl 5 以其对标准正则表达式的强大补充而闻名。 对于这些新功能，Perl 开发
人员无法选择新的单键击元字符或以 ‘\’ 开头的新特殊序列，否则 Perl 的正则
表达式与标准正则容易混淆。 例如，如果他们选择 ‘&’ 作为一个新的元字符，旧
的表达式将假设 ‘&’ 是一个普通字符，并且不会编写 ‘\&’ 或 ‘[&]’。

Perl 开发人员选择的解决方案是使用 ‘(?...)’ 作为扩展语法。 括号后面的 ‘?’
是一个语法错误，因为 ‘?’ 没有什么可重复的，所以这并没有引入任何兼容性问
题。 紧跟在 ‘?’ 之后的字符表示正在使用什么扩展名，所以 ‘(?=foo)’ 是一个
东西（一个正向的先行断言）和 ‘(?:foo)’ 是其它东西（ 包含子表达式 ‘foo’ 的
非捕获组）。

Python 支持一些 Perl 的扩展，并增加了新的扩展语法用于 Perl 的扩展语法。
如果在问号之后的第一个字符为 ‘P’，即表明其为 Python 专属的扩展。

现在我们已经了解了一般的扩展语法，我们可以回到简化复杂正则中组处理的功能
。

有时你会想要使用组来表示正则表达式的一部分，但是对检索组的内容不感兴趣。
你可以通过使用非捕获组来显式表达这个事实: ‘(?:...)’，你可以用任何其他正
则表达式替换 ‘...’。:

     >>> m = re.match("([abc])+", "abc")
     >>> m.groups()
     ('c',)
     >>> m = re.match("(?:[abc])+", "abc")
     >>> m.groups()
     ()

除了你无法检索组匹配内容的事实外，非捕获组的行为与捕获组完全相同；你可以
在里面放任何东西，用重复元字符重复它，比如 ‘*’，然后把它嵌入其他组（捕获
或不捕获）。 ‘(?:...)’ 在修改现有模式时特别有用，因为你可以添加新组而不
更改所有其他组的编号方式。 值得一提的是，捕获和非捕获组之间的搜索没有性
能差异；两种形式没有一种更快。

更重要的功能是命名组：不是通过数字引用它们，而是可以通过名称引用组。

命名组的语法是Python特定的扩展之一: ‘(?P<name>...)’。 `name' 显然是该组
的名称。 命名组的行为与捕获组完全相同，并且还将名称与组关联。 处理捕获组
的 *note 匹配对象: 984. 方法都接受按编号引用组的整数或包含所需组名的字符
串。 命名组仍然是给定的数字，因此你可以通过两种方式检索有关组的信息:

     >>> p = re.compile(r'(?P<word>\b\w+\b)')
     >>> m = p.search( '(((( Lots of punctuation )))' )
     >>> m.group('word')
     'Lots'
     >>> m.group(1)
     'Lots'

此外，你可以通过 *note groupdict(): 18ba. 将命名分组提取为一个字典:

     >>> m = re.match(r'(?P<first>\w+) (?P<last>\w+)', 'Jane Doe')
     >>> m.groupdict()
     {'first': 'Jane', 'last': 'Doe'}

命名组很有用，因为它们允许你使用容易记住的名称，而不必记住数字。 这是来
自 *note imaplib: 97. 模块的示例正则

     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'"')

检索 ‘m.group('zonem')’ 显然要容易得多，而不必记住检索第 9 组。

表达式中的后向引用语法，例如 ‘(...)\1’，指的是组的编号。 当然有一种变体
使用组名而不是数字。 这是另一个 Python 扩展: ‘(?P=name)’ 表示在当前点再
次匹配名为 `name' 的组的内容。 用于查找双字的正则表达式，
‘\b(\w+)\s+\1\b’ 也可以写为 ‘\b(?P<word>\w+)\s+(?P=word)\b’:

     >>> p = re.compile(r'\b(?P<word>\w+)\s+(?P=word)\b')
     >>> p.search('Paris in the the spring').group()
     'the the'


File: python.info,  Node: 前向断言,  Prev: 非捕获和命名组,  Up: 更多模式能力

10.8.4.4 前向断言
.................

另一个零宽度断言是前向断言。 前向断言以正面和负面形式提供，如下所示：

‘(?=…)’

     正向前向断言。 如果包含的正则表达式，由 ‘...’ 表示，在当前位置成功
     匹配，则成功，否则失败。 但是，一旦尝试了包含的表达式，匹配的引擎就
     不会前进；模式其余的部分会在在断言开始的地方尝试。

‘(?!…)’

     负向前向断言。 这与积正向断言相反；如果包含的表达式在字符串中的当前
     位置 `不' 匹配，则成功。

更具体一些，让我们看看前向是有用的情况。 考虑一个简单的模式来匹配文件名
并将其拆分为基本名称和扩展名，用 ‘.’ 分隔。 例如，在 ‘news.rc’ 中，
‘news’ 是基本名称，‘rc’ 是文件名的扩展名。

与此匹配的模式非常简单：

‘.*[.].*$’

请注意，‘.’ 需要特别处理，因为它是元字符，所以它在字符类中只能匹配特定字
符。 还要注意尾随的 ‘$’；添加此项以确保扩展名中的所有其余字符串都必须包
含在扩展名中。 这个正则表达式匹配 ‘foo.bar’、‘autoexec.bat’、
‘sendmail.cf’ 和 ‘printers.conf’。

现在，考虑使更复杂一点的问题；如果你想匹配扩展名不是 ‘bat’ 的文件名怎么
办？ 一些错误的尝试：

‘.*[.][^b].*$’ 上面的第一次尝试试图通过要求扩展名的第一个字符不是 ‘b’ 来
排除 ‘bat’。 这是错误的，因为模式也与 ‘foo.bar’ 不匹配。

‘.*[.]([^b]..|.[^a].|..[^t])$’

当你尝试通过要求以下一种情况匹配来修补第一个解决方案时，表达式变得更加混
乱：扩展的第一个字符不是 ‘b’。 第二个字符不 ‘a’；或者第三个字符不是 ‘t’。
这接受 ‘foo.bar’ 并拒绝 ‘autoexec.bat’，但它需要三个字母的扩展名，并且不
接受带有两个字母扩展名的文件名，例如 ‘sendmail.cf’。 为了解决这个问题，
我们会再次使模式复杂化。

‘.*[.]([^b].?.?|.[^a]?.?|..?[^t]?)$’

在第三次尝试中，第二个和第三个字母都是可选的，以便允许匹配的扩展名短于三
个字符，例如 ‘sendmail.cf’。

模式现在变得非常复杂，这使得它难以阅读和理解。 更糟糕的是，如果问题发生
变化并且你想要将 ‘bat’ 和 ‘exe’ 排除为扩展，那么该模式将变得更加复杂和混
乱。

负面前向消除了所有这些困扰：

‘.*[.](?!bat$)[^.]*$’ 负向前向意味着：如果表达式 ‘bat’ 此时不匹配，请尝
试其余的模式；如果 ‘bat$’ 匹配，整个模式将失败。 尾随的 ‘$’ 是必需的，以
确保允许像 ‘sample.batch’ 这样的扩展只以 ‘bat’ 开头的文件能通过。
‘[^.]*’ 确保当文件名中有多个点时，模式有效。

现在很容易排除另一个文件扩展名；只需在断言中添加它作为替代。 以下模块排
除以 ‘bat’ 或 ‘exe’:

‘.*[.](?!bat$|exe$)[^.]*$’


File: python.info,  Node: 修改字符串,  Next: 常见问题,  Prev: 更多模式能力,  Up: 如何使用正規表達式

10.8.5 修改字符串
-----------------

到目前为止，我们只是针对静态字符串执行搜索。 正则表达式通常也用于以各种
方式修改字符串，使用以下模式方法：

方法 / 属性            目的
                       
---------------------------------------------------------------------------
                       
‘split()’              将字符串拆分为一个列表，在正则匹配的任何地方将其
                       拆分
                       
                       
‘sub()’                找到正则匹配的所有子字符串，并用不同的字符串替换
                       它们
                       
                       
‘subn()’               与 ‘sub()’ 相同，但返回新字符串和替换次数
                       

* Menu:

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


File: python.info,  Node: 分割字符串,  Next: 搜索和替换,  Up: 修改字符串

10.8.5.1 分割字符串
...................

模式的 *note split(): 18ac. 方法在正则匹配的任何地方拆分字符串，返回一个
片段列表。 它类似于 *note split(): 890. 字符串方法，但在分隔符的分隔符中
提供了更多的通用性；字符串的 ‘split()’ 仅支持按空格或固定字符串进行拆分
。 正如你所期望的那样，还有一个模块级 *note re.split(): 4d0. 函数。

 -- 成員函式: .split (string[, maxsplit=0])

     通过正则表达式的匹配拆分 `字符串'。 如果在正则中使用捕获括号，则它
     们的内容也将作为结果列表的一部分返回。 如果 `maxsplit' 非零，则最多
     执行 `maxsplit' 次拆分。

你可以通过传递 `maxsplit' 的值来限制分割的数量。 当 `maxsplit' 非零时，
将最多进行 `maxsplit' 次拆分，并且字符串的其余部分将作为列表的最后一个元
素返回。 在以下示例中，分隔符是任何非字母数字字符序列。:

     >>> 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', '']
     >>> p.split('This is a test, short and sweet, of split().', 3)
     ['This', 'is', 'a', 'test, short and sweet, of split().']

有时你不仅对分隔符之间的文本感兴趣，而且还需要知道分隔符是什么。 如果在
正则中使用捕获括号，则它们的值也将作为列表的一部分返回。 比较以下调用:

     >>> p = re.compile(r'\W+')
     >>> p2 = re.compile(r'(\W+)')
     >>> p.split('This... is a test.')
     ['This', 'is', 'a', 'test', '']
     >>> p2.split('This... is a test.')
     ['This', '... ', 'is', ' ', 'a', ' ', 'test', '.', '']

模块级函数 *note re.split(): 4d0. 添加要正则作为第一个参数，但在其他方面
是相同的。:

     >>> re.split(r'[\W]+', 'Words, words, words.')
     ['Words', 'words', 'words', '']
     >>> re.split(r'([\W]+)', 'Words, words, words.')
     ['Words', ', ', 'words', ', ', 'words', '.', '']
     >>> re.split(r'[\W]+', 'Words, words, words.', 1)
     ['Words', 'words, words.']


File: python.info,  Node: 搜索和替换,  Prev: 分割字符串,  Up: 修改字符串

10.8.5.2 搜索和替换
...................

另一个常见任务是找到模式的所有匹配项，并用不同的字符串替换它们。 *note
sub(): 18af. 方法接受一个替换值，可以是字符串或函数，也可以是要处理的字
符串。

 -- 成員函式: .sub (replacement, string[, count=0])

     返回通过替换 `replacement' 替换 `string' 中正则的最左边非重叠出现而
     获得的字符串。 如果未找到模式，则 `string' 将保持不变。

     可选参数 `count' 是要替换的模式最大的出现次数；`count' 必须是非负整
     数。 默认值 0 表示替换所有。

这是一个使用 *note sub(): 18af. 方法的简单示例。 它用 ‘colour’ 这个词取
代颜色名称:

     >>> 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'

*note subn(): 18b0. 方法完成相同的工作，但返回一个包含新字符串值和已执行
的替换次数的 2 元组:

     >>> 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)

仅当空匹配与前一个空匹配不相邻时，才会替换空匹配。:

     >>> p = re.compile('x*')
     >>> p.sub('-', 'abxd')
     '-a-b--d-'

如果 `replacement' 是一个字符串，则处理其中的任何反斜杠转义。 也就是说，
‘\n’ 被转换为单个换行符，‘\r’ 被转换为回车符，依此类推。 诸如 ‘\&’ 之类
的未知转义是孤立的。 后向引用，例如 ‘\6’，被替换为正则中相应组匹配的子字
符串。 这使你可以在生成的替换字符串中合并原始文本的部分内容。

这个例子匹配单词 ‘section’ 后跟一个用 ‘{’，‘}’ 括起来的字符串，并将
‘section’ 改为 ‘subsection’

     >>> p = re.compile('section{ ( [^}]* ) }', re.VERBOSE)
     >>> p.sub(r'subsection{\1}','section{First} section{second}')
     'subsection{First} subsection{second}'

还有一种语法用于引用由 ‘(?P<name>...)’ 语法定义的命名组。 ‘\g<name>’ 将
使用名为 ‘name’ 的组匹配的子字符串，‘\g<number>’ 使用相应的组号。 因此
‘\g<2>’ 等同于 ‘\2’，但在诸如 ‘\g<2>0’ 之类的替换字符串中并不模糊。
(‘\20’ 将被解释为对组 20 的引用，而不是对组 2 的引用，后跟字面字符
‘'0'’。) 以下替换都是等效的，但使用所有三种变体替换字符串。:

     >>> 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}'

`replacement' 也可以是一个函数，它可以为你提供更多控制。 如果
`replacement' 是一个函数，则为 `pattern' 的每次非重叠出现将调用该函数。
在每次调用时，函数都会传递一个匹配的 *note 匹配对象: 984. 参数，并可以使
用此信息计算所需的替换字符串并将其返回。

在以下示例中，替换函数将小数转换为十六进制:

     >>> 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.'

使用模块级别 *note re.sub(): 579. 函数时，模式作为第一个参数传递。 图案
可以作为对象或字符串提供；如果需要指定正则表达式标志，则必须使用模式对象
作为第一个参数，或者在模式字符串中使用嵌入式修饰符，例如: ‘sub("(?i)b+",
"x", "bbbb BBBB")’ 返回 ‘'x x'’。


File: python.info,  Node: 常见问题,  Next: 反馈,  Prev: 修改字符串,  Up: 如何使用正規表達式

10.8.6 常见问题
---------------

正则表达式对于某些应用程序来说是一个强大的工具，但在某些方面，它们的行为
并不直观，有时它们的行为方式与你的预期不同。 本节将指出一些最常见的陷阱
。

* Menu:

* 使用字符串方法::
* match() 和 search(): match 和 search.
* 贪婪与非贪婪::
* 使用 re.VERBOSE: 使用 re VERBOSE.


File: python.info,  Node: 使用字符串方法,  Next: match 和 search,  Up: 常见问题

10.8.6.1 使用字符串方法
.......................

有时使用 *note re: dd. 模块是一个错误。 如果你匹配固定字符串或单个字符类
，并且你没有使用任何 *note re: dd. 功能，例如 *note IGNORECASE: 18a5. 标
志，那么正则表达式的全部功能可能不是必需的。 字符串有几种方法可以使用固
定字符串执行操作，它们通常要快得多，因为实现是一个针对此目的而优化的单个
小 C 循环，而不是大型、更通用的正则表达式引擎。

一个例子可能是用另一个固定字符串替换一个固定字符串；例如，你可以用
‘deed’ 替换 ‘word’ 。 *note re.sub(): 579. 看起来像是用于此的函数，但请
考虑 *note replace(): 1787. 方法。 注意 ‘replace()’ 也会替换单词里面的
‘word’ ，把 ‘swordfish’ 变成 ‘sdeedfish’ ，但简单的正则 ‘word’ 也会这样
做。 （为了避免对单词的部分进行替换，模式必须是 ‘\bword\b’，以便要求
‘word’ 在任何一方都有一个单词边界。这使得工作超出了 ‘replace()’ 的能力。
）

另一个常见任务是从字符串中删除单个字符的每个匹配项或将其替换为另一个字符
。 你可以用 ‘re.sub('\n', ' ', S)’ 之类的东西来做这件事，但是 *note
translate(): 1786. 能够完成这两项任务，并且比任何正则表达式都快。

简而言之，在转向 *note re: dd. 模块之前，请考虑是否可以使用更快更简单的
字符串方法解决问题。


File: python.info,  Node: match 和 search,  Next: 贪婪与非贪婪,  Prev: 使用字符串方法,  Up: 常见问题

10.8.6.2 match() 和 search()
............................

The *note match(): c83. function only checks if the RE matches at the
beginning of the string while *note search(): c82. will scan forward
through the string for a match.  It’s important to keep this distinction
in mind.  Remember, ‘match()’ will only report a successful match which
will start at 0; if the match wouldn’t start at zero, ‘match()’ will
`not' report it.

     >>> print(re.match('super', 'superstition').span())
     (0, 5)
     >>> print(re.match('super', 'insuperable'))
     None

另一方面， *note search(): c82. 将向前扫描字符串，报告它找到的第一个匹配
项。:

     >>> print(re.search('super', 'superstition').span())
     (0, 5)
     >>> print(re.search('super', 'insuperable').span())
     (2, 7)

有时你会被诱惑继续使用 *note re.match(): c83. ，只需在你的正则前面添加
‘.*’ 。抵制这种诱惑并使用 *note re.search(): c82. 代替。 正则表达式编译
器对正则进行一些分析，以加快寻找匹配的过程。 其中一个分析可以确定匹配的
第一个特征必须是什么；例如，以 ‘Crow’ 开头的模式必须与 ‘'C'’ 匹配。 分析
让引擎快速扫描字符串，寻找起始字符，只在找到 ‘'C'’ 时尝试完全匹配。

添加 ‘.*’ 会使这个优化失效，需要扫描到字符串的末尾，然后回溯以找到正则的
其余部分的匹配。 使用 *note re.search(): c82. 代替。


File: python.info,  Node: 贪婪与非贪婪,  Next: 使用 re VERBOSE,  Prev: match 和 search,  Up: 常见问题

10.8.6.3 贪婪与非贪婪
.....................

当重复一个正则表达式时，就像在 ‘a*’ 中一样，最终的动作就是消耗尽可能多的
模式。 当你尝试匹配一对对称分隔符，例如 HTML 标记周围的尖括号时，这个事
实经常会让你感到困惑。因为 ‘.*’ 的贪婪性质， 用于匹配单个 HTML 标记的简
单模式不起作用。

     >>> 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>

正则匹配 ‘'<'’ 中的 ‘'<html>'’ 和 ‘.*’ 消耗字符串的其余部分。 正则中还有
更多的剩余东西，并且 ‘>’ 在字符串的末尾不能匹配，所以正则表达式引擎必须
逐个字符地回溯，直到它找到匹配 ‘>’ 。最终匹配从 ‘'<html>'’ 中的 ‘'<'’ 扩
展到 ‘'</title>'’ 中的 ‘'>'’ ，而这并不是你想要的结果。

在这种情况下，解决方案是使用非贪婪的限定符 ‘*?’ 、 ‘+?’ 、 ‘??’ 或
‘{m,n}?’ ，匹配为尽可能 `少' 的文字。 在上面的例子中，在第一次 ‘'<'’ 匹
配后立即尝试 ‘'>'’ ，当它失败时，引擎一次前进一个字符，每一步都重试
‘'>'’ 。 这产生了正确的结果:

     >>> print(re.match('<.*?>', s).group())
     <html>

（请注意，使用正则表达式解析 HTML 或 XML 很痛苦。快而脏的模式将处理常见
情况，但 HTML 和 XML 有特殊情况会破坏明显的正则表达式；当你编写正则表达
式处理所有可能的情况时，模式将非常复杂。使用 HTML 或 XML 解析器模块来执
行此类任务。）


File: python.info,  Node: 使用 re VERBOSE,  Prev: 贪婪与非贪婪,  Up: 常见问题

10.8.6.4 使用 re.VERBOSE
........................

到目前为止，你可能已经注意到正则表达式是一种非常紧凑的表示法，但它们并不
是非常易读。 具有中等复杂度的正则可能会成为反斜杠、括号和元字符的冗长集
合，使其难以阅读和理解。

对于这样的正则，在编译正则表达式时指定 *note re.VERBOSE: 18a6. 标志可能
会有所帮助，因为它允许你更清楚地格式化正则表达式。

‘re.VERBOSE’ 标志有几种效果。 正则表达式中的 `不是' 在字符类中的空格将被
忽略。 这意味着表达式如 ‘dog | cat’ 等同于不太可读的 ‘dog|cat’ ，但 ‘[a
b]’ 仍将匹配字符 ‘'a'’ 、 ‘'b'’ 或空格。 此外，你还可以在正则中放置注释
；注释从 ‘#’ 字符扩展到下一个换行符。 当与三引号字符串一起使用时，这使正
则的格式更加整齐:

     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)

这更具有可读性:

     pat = re.compile(r"\s*(?P<header>[^:]+)\s*:(?P<value>.*?)\s*$")


File: python.info,  Node: 反馈,  Prev: 常见问题,  Up: 如何使用正規表達式

10.8.7 反馈
-----------

正则表达式是一个复杂的主题。 这份文档是否有助于你理解它们？ 是否存在不清
楚的部分，或者你遇到的问题未在此处涉及？ 如果是，请向作者发送改进建议。

关于正则表达式的最完整的书几乎肯定是由 O’Reilly 出版的 Jeffrey Friedl 的
Mastering Regular Expressions 。 不幸的是，它专注于 Perl 和 Java 的正则
表达式，并且根本不包含任何 Python 材料，因此它不能用作 Python 编程的参考
。 （第一版涵盖了 Python 现在删除的 ‘regex’ 模块，这对你没有多大帮助。）
考虑从你的图书馆中查找它。


File: python.info,  Node: 套接字编程指南,  Next: 如何排序,  Prev: 如何使用正規表達式,  Up: Python 如何達成任務

10.9 套接字编程指南
===================


作者: Gordon McMillan

摘要
....

套接字几乎无处不在，但是它却是被误解最严重的技术之一。这是一篇简单的套接
字概述。并不是一篇真正的教程 —— 你需要做更多的事情才能让它工作起来。其中
也并没有涵盖细节（细节会有很多），但是我希望它能提供足够的背景知识，让你
像模像样的开始使用套接字

* Menu:

* 套接字::
* 创建套接字: 创建套接字<2>.
* 使用一个套接字::
* 断开连接::
* 非阻塞的套接字::


File: python.info,  Node: 套接字,  Next: 创建套接字<2>,  Up: 套接字编程指南

10.9.1 套接字
-------------

我将只讨论关于 INET（比如：IPv4 地址族）的套接字，但是它将覆盖几乎 99% 的
套接字使用场景。并且我将仅讨论 STREAM（比如：TCP）类型的套接字 - 除非你
真的知道你在做什么（那么这篇 HOWTO 可能并不适合你），使用 STREAM 类型的
套接字将会得到比其它类型更好的表现与性能。我将尝试揭开套接字的神秘面纱，
也会讲到一些阻塞与非阻塞套接字的使用。但是我将以阻塞套接字为起点开始讨论
。只有你了解它是如何工作的以后才能处理非阻塞套接字。

理解这些东西的难点之一在于「套接字」可以表示很多微妙差异的东西，这取决于
上下文。所以首先，让我们先分清楚「客户端」套接字和「服务端」套接字之间的
不同，客户端套接字表示对话的一端，服务端套接字更像是总机接线员。客户端程
序只能（比如：你的浏览器）使用「客户端」套接字；网络服务器则可以使用「服
务端」套接字和「客户端」套接字来会话

* Menu:

* 历史::


File: python.info,  Node: 历史,  Up: 套接字

10.9.1.1 历史
.............

目前为止，在各种形式的 IPC (进程间通信) 中，套接字是最流行的。在任何指定
的平台上，可能会有其它更快的 IPC 形式，但是就跨平台通信来说，套接字大概
是唯一的玩法

套接字做为 BSD Unix 操作系统的一部分在伯克利诞生，像野火一样在因特网传播
。有一个很好的原因 —— 套接字与 INET 的结合使得与世界各地的任意机器间通信
变得令人难以置信的简单（至少对比与其他方案来说）


File: python.info,  Node: 创建套接字<2>,  Next: 使用一个套接字,  Prev: 套接字,  Up: 套接字编程指南

10.9.2 创建套接字
-----------------

简略地说，当你点击带你来到这个页面的链接时，你的浏览器就已经做了下面这几
件事情:

     # 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))

当连接完成，套接字可以用来发送请求来接收页面上显示的文字。同样是这个套接
字也会用来读取响应，最后再被销毁。是的，被销毁了。客户端套接字通常用来做
一次交换（或者说一小组序列的交换）。

网络服务器发生了什么这个问题就有点复杂了。首页，服务器创建一个「服务端套
接字」:

     # 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)

有几件事需要注意：我们使用了 ‘socket.gethostname()’，所以套接字将外网可
见。如果我们使用的是 ‘s.bind(('localhost', 80))’ 或者
‘s.bind(('127.0.0.1', 80))’，也会得到一个「服务端」套接字，但是后者只在
同一机器上可见。‘s.bind(('', 80))’ 则指定套接字可以被机器上的任何地址碰
巧连接

第二个需要注点是：低端口号通常被一些「常用的」服务（HTTP, SNMP 等）所保
留。如果你想把程序跑起来，最好使用一个高位端口号（通常是4位的数字）。

最后，‘listen’ 方法的参数会告诉套接字库，我们希望在队列中累积多达 5 个（
通常的最大值）连接请求后再拒绝外部连接。 如果所有其他代码都准确无误，这
个队列长度应该是足够的。

现在我们已经有一个「服务端」套接字，监听了 80 端口，我们可以进入网络服务
器的主循环了:

     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()

事际上，通常有 3 种方法可以让这个循环工作起来 - 调度一个线程来处理 ‘客户
端套接字’，或者把这个应用改成使用非阻塞模式套接字，亦或是使用 ‘select’ 库
来实现「服务端」套接字与任意活动 ‘客户端套接字’ 之间的多路复用。稍后会详
细介绍。现在最重要的是理解：这就是一个 `服务端' 套接字做的 `所有' 事情。
它并没有发送任何数据。也没有接收任何数据。它只创建「客户端」套接字。每个
‘客户端套接字’ 都是为了响应某些其它客户端套接字 ‘connect()’ 到我们绑定的
主机。一旦创建 ‘客户端套接字’ 完成，就会返回并监听更多的连接请求。现个客
户端可以随意通信 - 它们使用了一些动态分配的端口，会话结束时端口才会被回
收

* Menu:

* 进程间通信::


File: python.info,  Node: 进程间通信,  Up: 创建套接字<2>

10.9.2.1 进程间通信
...................

如果你需要在同一台机器上进行两个进程间的快速 IPC 通信，你应该了解管道或
者共享内存。如果你决定使用 AF_INET 类型的套接字，绑定「服务端」套接字到
‘'localhost'’ 。在大多数平台，这将会使用一个许多网络层间的通用快捷方式（
本地回环地址）并且速度会快很多

也參考
......

*note multiprocessing: b7. 模块使跨平台 IPC 通信成为一个高层的 API


File: python.info,  Node: 使用一个套接字,  Next: 断开连接,  Prev: 创建套接字<2>,  Up: 套接字编程指南

10.9.3 使用一个套接字
---------------------

首先需要注意，浏览器的「客户端」套接字和网络服务器的「客户端」套接字是极
为相似的。即这种会话是「点对点」的。或者也可以说 `你作为设计师需要自行决
定会话的规则和礼节' 。通常情况下，‘连接’ 套接字通过发送一个请求或者信号
来开始一次会话。但这属于设计决定，并不是套接字规则。

现在有两组用于通信的动词。你可以使用 ‘send’ 和 ‘recv’ ，或者你可以把客户
端套接字改成文件类型的形式来使用 ‘read’ 和 ‘write’ 方法。后者是 Java 语
言中表示套接字的方法，我将不会在这儿讨论这个，但是要提醒你需要调用套接字
的 ‘flush’ 方法。这些是“缓冲”的文件，一个经常出现的错误是 ‘write’ 一些东
西，然后就直接开始 ‘read’ 一个响应。如果不调用 ‘flush’ ，你可能会一直等
待这个响应，因为请求可能还在你的输出缓冲中。

现在我来到了套接字的两个主要的绊脚石 - ‘send’ 和 ‘recv’ 操作网络缓冲区。
它们并不一定可以处理所有你想要（期望）的字节，因为它们主要关注点是处理网
络缓冲。通常，它们在关联的网络缓冲区 ‘send’ 或者清空 ‘recv’ 时返回。然后
告诉你处理了多少个字节。`你' 的责任是一直调用它们直到你所有的消息处理完
成。

当 ‘recv’ 方法返回 0 字节时，就表示另一端已经关闭（或者它所在的进程关闭
）了连接。你再也不能从这个连接上获取到任何数据了。你可以成功的发送数据；
我将在后面讨论这一点。

像 HTTP 这样的协议只使用一个套接字进行一次传输。客户端发送一个请求，然后
读取响应。就这么简单。套接字会被销毁。 表示客户端可以通过接收 0 字节序列
表示检测到响应的结束。

但是如果你打算在随后来的传输中复用套接字的话，你需要明白 `套接字里面是不
存在 :abbr:‘EOT (传输结束)‘' 的。重复一下：套接字 ‘send’ 或者 ‘recv’ 完
0 字节后返回，连接会中断。如果连接没有被断开，你可能会永远处于等待
‘recv’ 的状态，因为（就目前来说）套接字 `不会' 告诉你不用再读取了。现在
如果你细心一点，你可能会意识到套接字基本事实：`消息必须要么具有固定长度
，要么可以界定，要么指定了长度（比较好的做法），要么以关闭连接为结束'。
选择完全由你而定（这比让别人定更合理）。

假定你不希望结束连接，那么最简单的解决方案就是使用定长消息:

     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'':
                     raise RuntimeError("socket connection broken")
                 chunks.append(chunk)
                 bytes_recd = bytes_recd + len(chunk)
             return b''.join(chunks)

发送分部代码几乎可用于任何消息传递方案 —— 在 Python 中你发送字符串，可以
使用 ‘len()’ 方法来确定它的长度（即使它嵌入了 ‘\0’ 字符），主要是接收代
码变得更复杂。（在 C 语言中，并没有更糟糕，除非消息嵌入了 ‘\0’ 字符而且
你又无法使用 ‘strlen’ ）

最简单的改进是让消息的第一个字符表示消息类型，由类型决定长度。现在你需要
两次 ‘recv’- 第一次取（至少）第一个字符来知晓长度，第二次在循环中获取剩
余所有的消息。如果你决定到分界线，你将收到一些任意大小的块，（4096 或者
8192 通常是比较合适的网络缓冲区大小），扫描你接收到的分界符

一个需要意识到的复杂情况是：如果你的会话协议允许多个消息被发送回来（没有
响应），调用 ‘recv’ 传入任意大小的块，你可能会因为读到后续接收的消息而停
止读取。你需要将它放在一边并保存，直到它需要为止。

以其长度（例如，作为5个数字字符）作为消息前缀时会变得更复杂，因为（信不
信由你）你可能无法在一个 ‘recv’ 中获得所有5个字符。在一般使用时，你会侥
幸避免该状况；但是在高网络负载中，除非你使用两个 ‘recv’ 循环，否则你的代
码将很快中断 —— 第一个用于确定长度，第二个用于获取消息的数据部分。这很讨
厌。当你发现 ‘send’ 并不总是设法在支持搞定一切时，你也会有这种感觉。 尽
管已经阅读过这篇文章，但最终还是会有所了解！

限于篇幅，建立你的角色，（保持与我的竞争位置），这些改进将留给读者做为练
习。现在让我们继续。

* Menu:

* 二进制数据::


File: python.info,  Node: 二进制数据,  Up: 使用一个套接字

10.9.3.1 二进制数据
...................

通过套接字传送二进制数据是可行的。主要问题在于并非所有机器都用同样的二进
制数据格式。比如 Motorola 芯片用两个十六进制字节 00 01 来表示一个 16 位
整数值 1。而 Intel 和 DEC 则会做字节反转 —— 即用 01 00 来表示 1。套接字
库要求转换 16 位和 32 位整数 —— ‘ntohl, htonl, ntohs, htons’ 其中的「n」
表示 `network'，「h」表示 `host'，「s」表示 `short'，「l」表示 `long'。
在网络序列就是主机序列时它们什么都不做，但是如果机器是字节反转的则会适当
地交换字节序。

在现今的 32 位机器中，二进制数据的 ascii 表示往往比二进制表示要小。这是
因为在非常多的时候所有 long 的值均为 0 或者 1。字符串形式的 "0" 为两个字
节，而二进制形式则为四个。当然这不适用于固定长度的信息。自行决定，请自行
决定。


File: python.info,  Node: 断开连接,  Next: 非阻塞的套接字,  Prev: 使用一个套接字,  Up: 套接字编程指南

10.9.4 断开连接
---------------

严格地讲，你应该在 ‘close’ 它之前将套接字 ‘shutdown’ 。 ‘shutdown’ 是发
送给套接字另一端的一种建议。调用时参数不同意义也不一样，它可能意味着「我
不会再发送了，但我仍然会监听」，或者「我没有监听了，真棒！」。然而，大多
数套接字库或者程序员都习惯了忽略使用这种礼节，因为通常情况下 ‘close’ 与
‘shutdown(); close()’ 是一样的。所以在大多数情况下，不需要显式的
‘shutdown’ 。

高效使用 ‘shutdown’ 的一种方法是在类似 HTTP 的交换中。客户端发送请求，然
后执行 ‘shutdown(1)’ 。 这告诉服务器“此客户端已完成发送，但仍可以接收”。
服务器可以通过接收 0 字节来检测 “EOF” 。它可以假设它有完整的请求。服务器
发送回复。如果 ‘send’ 成功完成，那么客户端仍在接收。

Python 进一步自动关闭，并说当一个套接字被垃圾收集时，如果需要它会自动执
行 ‘close’ 。但依靠这个机制是一个非常坏的习惯。如果你的套接字在没有
‘close’ 的情况下就消失了，那么另一端的套接字可能会无限期地挂起，以为你只
是慢了一步。完成后 `请' ‘close’ 你的套接字。

* Menu:

* 套接字何时销毁::


File: python.info,  Node: 套接字何时销毁,  Up: 断开连接

10.9.4.1 套接字何时销毁
.......................

使用阻塞套接字最糟糕的事情可能就是当另一边下线时（没有 ‘close’ ）会发生
什么。你的套接字可能会挂起。 TCP 是一种可靠的协议，它会在放弃连接之前等
待很长时间。如果你正在使用线程，那么整个线程基本上已经死了。你无能为力。
只要你没有做一些愚蠢的事情，比如在进行阻塞读取时持有一个锁，那么线程并没
有真正消耗掉资源。 `不要' 尝试杀死线程 —— 线程比进程更有效的部分原因是它
们避免了与自动回收资源相关的开销。换句话说，如果你设法杀死线程，你的整个
进程很可能被搞坏。


File: python.info,  Node: 非阻塞的套接字,  Prev: 断开连接,  Up: 套接字编程指南

10.9.5 非阻塞的套接字
---------------------

如果你已理解上述内容，那么你已经了解了使用套接字的机制所需了解的大部分内
容。你仍将以相同的方式使用相同的函数调用。 只是，如果你做得对，你的应用
程序几乎是由内到外的。

在 Python 中是使用 ‘socket.setblocking(False)’ 来设置非阻塞。 在 C 中的
做法更为复杂（例如，你需要在 BSD 风格的 ‘O_NONBLOCK’ 和几乎无区别的
POSIX 风格的 ‘O_NDELAY’ 之间作出选择，这与 ‘TCP_NODELAY’ 完全不一样），
但其思路实际上是相同的。 你要在创建套接字之后但在使用它之前执行此操作。
（实际上，如果你是疯子的话也可以反复进行切换。）

主要的机制差异是 ‘send’ 、 ‘recv’ 、 ‘connect’ 和 ‘accept’ 可以在没有做
任何事情的情况下返回。 你（当然）有很多选择。你可以检查返回代码和错误代
码，通常会让自己发疯。如果你不相信我，请尝试一下。你的应用程序将变得越来
越大、越来越 Bug 、吸干 CPU。因此，让我们跳过脑死亡的解决方案并做正确的
事。

使用 ‘select’ 库

在 C 中，编码 ‘select’ 相当复杂。 在 Python 中，它是很简单，但它与 C 版
本足够接近，如果你在 Python 中理解 ‘select’ ，那么在 C 中你会几乎不会遇
到麻烦:

     ready_to_read, ready_to_write, in_error = \
                    select.select(
                       potential_readers,
                       potential_writers,
                       potential_errs,
                       timeout)

你传递给 ‘select’ 三个列表：第一个包含你可能想要尝试读取的所有套接字；第
二个是你可能想要尝试写入的所有套接字，以及要检查错误的最后一个（通常为空
）。你应该注意，套接字可以进入多个列表。 ‘select’ 调用是阻塞的，但你可以
给它一个超时。这通常是一件明智的事情 —— 给它一个很长的超时（比如一分钟）
，除非你有充分的理由不这样做。

作为返回，你将获得三个列表。它们包含实际可读、可写和有错误的套接字。 这
些列表中的每一个都是你传入的相应列表的子集（可能为空）。

如果一个套接字在输出可读列表中，那么你可以像我们一样接近这个业务，那个套
接字上的 ‘recv’ 将返回 `一些内容' 。可写列表的也相同，你将能够发送 `一些
内容' 。 也许不是你想要的全部，但 `有些东西' 比没有东西更好。 （实际上，
任何合理健康的套接字都将以可写方式返回 —— 它只是意味着出站网络缓冲区空间
可用。）

如果你有一个“服务器”套接字，请将其放在 potential_readers 列表中。如果它
出现在可读列表中，那么你的 ‘accept’ （几乎肯定）会起作用。如果你已经创建
了一个新的套接字 ‘connect’ 其他人，请将它放在 potential_writers 列表中。
如果它出现在可写列表中，那么它有可能已连接。

实际上，即使使用阻塞套接字， ‘select’ 也很方便。这是确定是否阻塞的一种方
法 —— 当缓冲区中存在某些内容时，套接字返回为可读。然而，这仍然无助于确定
另一端是否完成或者只是忙于其他事情的问题。

`可移植性警告' ：在 Unix 上， ‘select’ 适用于套接字和文件。 不要在
Windows 上尝试。在 Windows 上， ‘select’ 仅适用于套接字。另请注意，在 C
中，许多更高级的套接字选项在 Windows 上的执行方式不同。事实上，在
Windows 上我通常在使用我的套接字使用线程（非常非常好）。


File: python.info,  Node: 如何排序,  Next: Unicode 指南,  Prev: 套接字编程指南,  Up: Python 如何達成任務

10.10 如何排序
==============


作者: Andrew Dalke 和 Raymond Hettinger


发布版本: 0.1

Python 列表有一个内置的 *note list.sort(): 547. 方法可以直接修改列表。还
有一个 *note sorted(): 546. 内置函数，它会从一个可迭代对象构建一个新的排
序列表。

在此文件，我們使用Python進行各種方式排序資料

* Menu:

* 排序 基本::
* 关键函数::
* Operator 模块函数::
* 升冪與降冪::
* 排序稳定性和排序复杂度::
* 使用装饰-排序-去装饰的旧方法::
* 使用 cmp 参数的旧方法::
* 其它::


File: python.info,  Node: 排序 基本,  Next: 关键函数,  Up: 如何排序

10.10.1 排序 基本
-----------------

简单的升序排序非常简单：只需调用 *note sorted(): 546. 函数即可。它会返回
一个新的已排序列表。

     >>> sorted([5, 2, 3, 1, 4])
     [1, 2, 3, 4, 5]

你也可以使用 *note list.sort(): 547. 方法，它会直接修改原列表（并返回
‘None’ 以避免混淆），通常来说它不如 *note sorted(): 546. 方便 ——— 但如果
你不需要原列表，它会更有效率。

     >>> a = [5, 2, 3, 1, 4]
     >>> a.sort()
     >>> a
     [1, 2, 3, 4, 5]

另外一个区别是， *note list.sort(): 547. 方法只是为列表定义的，而 *note
sorted(): 546. 函数可以接受任何可迭代对象。

     >>> sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})
     [1, 2, 3, 4, 5]


File: python.info,  Node: 关键函数,  Next: Operator 模块函数,  Prev: 排序 基本,  Up: 如何排序

10.10.2 关键函数
----------------

*note list.sort(): 547. 和 *note sorted(): 546. 都有一个 `key' 形参用来
指定在进行比较前要在每个列表元素上调用的函数（或其他可调用对象）。

例如，下面是一个不区分大小写的字符串比较：

     >>> sorted("This is a test string from Andrew".split(), key=str.lower)
     ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']

`key' 形参的值应该是个函数（或其他可调用对象），它接受一个参数并返回一个
用于排序的键。 这种机制速度很快，因为对于每个输入记录只会调用一次键函数
。

一种常见的模式是使用对象的一些索引作为键对复杂对象进行排序。例如：

     >>> 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)]

同样的技术也适用于具有命名属性的对象。例如：

     >>> 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))

     >>> 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)]


File: python.info,  Node: Operator 模块函数,  Next: 升冪與降冪,  Prev: 关键函数,  Up: 如何排序

10.10.3 Operator 模块函数
-------------------------

上面显示的键函数模式非常常见，因此 Python 提供了便利功能，使访问器功能更
容易，更快捷。 *note operator: c2. 模块有 *note itemgetter(): 38b. 、
*note attrgetter(): 80a. 和 *note methodcaller(): 80b. 函数。

使用这些函数，上述示例变得更简单，更快捷：

     >>> from operator import itemgetter, attrgetter

     >>> sorted(student_tuples, key=itemgetter(2))
     [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

     >>> sorted(student_objects, key=attrgetter('age'))
     [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

Operator 模块功能允许多级排序。 例如，按 `grade' 排序，然后按 `age' 排序
：

     >>> sorted(student_tuples, key=itemgetter(1,2))
     [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

     >>> sorted(student_objects, key=attrgetter('grade', 'age'))
     [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]


File: python.info,  Node: 升冪與降冪,  Next: 排序稳定性和排序复杂度,  Prev: Operator 模块函数,  Up: 如何排序

10.10.4 升冪與降冪
------------------

*note list.sort(): 547. 和 *note sorted(): 546. 接受布尔值的 `reverse' 参
数。这用于标记降序排序。 例如，要以反向 `age' 顺序获取学生数据：

     >>> sorted(student_tuples, key=itemgetter(2), reverse=True)
     [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

     >>> sorted(student_objects, key=attrgetter('age'), reverse=True)
     [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]


File: python.info,  Node: 排序稳定性和排序复杂度,  Next: 使用装饰-排序-去装饰的旧方法,  Prev: 升冪與降冪,  Up: 如何排序

10.10.5 排序稳定性和排序复杂度
------------------------------

排序保证是 稳定(1) 的。 这意味着当多个记录具有相同的键值时，将保留其原始
顺序。

     >>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)]
     >>> sorted(data, key=itemgetter(0))
     [('blue', 1), ('blue', 2), ('red', 1), ('red', 2)]

注意 `blue' 的两个记录如何保留它们的原始顺序，以便 ‘('blue', 1)’ 保证在
‘('blue', 2)’ 之前。

这个美妙的属性允许你在一系列排序步骤中构建复杂的排序。例如，要按 `grade'
降序然后 `age' 升序对学生数据进行排序，请先 `age' 排序，然后再使用
`grade' 排序：

     >>> 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)]

这可以被抽象为一个包装函数，该函数能接受一个列表以及字段和顺序的元组，以
对它们进行多重排序。

     >>> def multisort(xs, specs):
     ...     for key, reverse in reversed(specs):
     ...         xs.sort(key=attrgetter(key), reverse=reverse)
     ...     return xs

     >>> multisort(list(student_objects), (('grade', True), ('age', False)))
     [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

Python 中使用的 Timsort(2) 算法可以有效地进行多种排序，因为它可以利用数
据集中已存在的任何排序。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Sorting_algorithm#Stability

   (2) https://en.wikipedia.org/wiki/Timsort


File: python.info,  Node: 使用装饰-排序-去装饰的旧方法,  Next: 使用 cmp 参数的旧方法,  Prev: 排序稳定性和排序复杂度,  Up: 如何排序

10.10.6 使用装饰-排序-去装饰的旧方法
------------------------------------

这个三个步骤被称为 Decorate-Sort-Undecorate ：

   * 首先，初始列表使用控制排序顺序的新值进行修饰。

   * 然后，装饰列表已排序。

   * 最后，删除装饰，创建一个仅包含新排序中初始值的列表。

例如，要使用DSU方法按 `grade' 对学生数据进行排序：

     >>> 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)]

这方法语有效是因为元组按字典顺序进行比较，先比较第一项；如果它们相同则比
较第二个项目，依此类推。

不一定在所有情况下都要在装饰列表中包含索引 `i' ，但包含它有两个好处：

   * 排序是稳定的——如果两个项具有相同的键，它们的顺序将保留在排序列表中
     。

   * 原始项目不必具有可比性，因为装饰元组的排序最多由前两项决定。 因此，
     例如原始列表可能包含无法直接排序的复数。

这个方法的另一个名字是 Randal L. Schwartz 在 Perl 程序员中推广的
Schwartzian transform(1)。

既然 Python 排序提供了键函数，那么通常不需要这种技术。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Schwartzian_transform


File: python.info,  Node: 使用 cmp 参数的旧方法,  Next: 其它,  Prev: 使用装饰-排序-去装饰的旧方法,  Up: 如何排序

10.10.7 使用 `cmp' 参数的旧方法
-------------------------------

本 HOWTO 中给出的许多结构都假定为 Python 2.4 或更高版本。在此之前，没有
内置 *note sorted(): 546. ， *note list.sort(): 547. 也没有关键字参数。
相反，所有 Py2.x 版本都支持 `cmp' 参数来处理用户指定的比较函数。

在 Py3.0 中， `cmp' 参数被完全删除（作为简化和统一语言努力的一部分，消除
了丰富的比较与 ‘__cmp__()’ 魔术方法之间的冲突）。

在 Py2.x 中， sort 允许一个可选函数，可以调用它来进行比较。该函数应该采
用两个参数进行比较，然后返回负值为小于，如果它们相等则返回零，或者返回大
于大于的正值。例如，我们可以这样做：

     >>> def numeric_compare(x, y):
     ...     return x - y
     >>> sorted([5, 2, 4, 1, 3], cmp=numeric_compare)
     [1, 2, 3, 4, 5]

或者你可反转比较的顺序：

     >>> def reverse_numeric(x, y):
     ...     return y - x
     >>> sorted([5, 2, 4, 1, 3], cmp=reverse_numeric)
     [5, 4, 3, 2, 1]

将代码从 Python 2.x 移植到 3.x 时，如果用户提供比较功能并且需要将其转换
为键函数，则会出现这种情况。 以下包装器使这很容易：

     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

要转换为键函数，只需包装旧的比较函数：

     >>> sorted([5, 2, 4, 1, 3], key=cmp_to_key(reverse_numeric))
     [5, 4, 3, 2, 1]

在 Python 3.2 中， *note functools.cmp_to_key(): c28. 函数被添加到标准库
中的 *note functools: 83. 模块中。


File: python.info,  Node: 其它,  Prev: 使用 cmp 参数的旧方法,  Up: 如何排序

10.10.8 其它
------------

   * 对于区域相关的排序，请使用 *note locale.strxfrm(): 31c3. 作为键函数
     ，或者 *note locale.strcoll(): 31c1. 作为比较函数。

   * `reverse' 参数仍然保持排序稳定性（因此具有相等键的记录保留原始顺序
     ）。 有趣的是，通过使用内置的 *note reversed(): 2c6. 函数两次，可以
     在没有参数的情况下模拟该效果：

          >>> 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)]

   * 在两个对象之间进行比较时，保证排序例程使用 *note __lt__(): cfe. 。
     因此，通过定义 *note __lt__(): cfe. 方法，可以很容易地为类添加标准
     排序顺序:

          >>> Student.__lt__ = lambda self, other: self.age < other.age
          >>> sorted(student_objects)
          [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

   * 键函数不需要直接依赖于被排序的对象。键函数还可以访问外部资源。例如
     ，如果学生成绩存储在字典中，则可以使用它们对单独的学生姓名列表进行
     排序：

          >>> students = ['dave', 'john', 'jane']
          >>> newgrades = {'john': 'F', 'jane':'A', 'dave': 'C'}
          >>> sorted(students, key=newgrades.__getitem__)
          ['jane', 'dave', 'john']


File: python.info,  Node: Unicode 指南,  Next: 如何使用urllib套件取得網路資源,  Prev: 如何排序,  Up: Python 如何達成任務

10.11 Unicode 指南
==================


发布版本: 1.12

本文介绍了 Python 对表示文本数据的 Unicode 规范的支持，并对各种 Unicode
常见使用问题做了解释。

* Menu:

* Unicode 概述::
* Python对Unicode的支持::
* Unicode 数据的读写::
* 致谢: 致谢<10>.


File: python.info,  Node: Unicode 概述,  Next: Python对Unicode的支持,  Up: Unicode 指南

10.11.1 Unicode 概述
--------------------

* Menu:

* 定义::
* 编码::
* 引用文献: 引用文献<2>.


File: python.info,  Node: 定义,  Next: 编码,  Up: Unicode 概述

10.11.1.1 定义
..............

如今的程序需要能够处理各种各样的字符。应用程序通常做了国际化处理，用户可
以选择不同的语言显示信息和输出数据。同一个程序可能需要以英语、法语、日语
、希伯来语或俄语输出错误信息。网页内容可能由这些语言书写，并且可能包含不
同的表情符号。Python 的字符串类型采用 Unicode 标准来表示字符，使得
Python 程序能够正常处理所有这些不同的字符。

Unicode 规范（‘https://www.unicode.org/’）旨在罗列人类语言所用到的所有字
符，并赋予每个字符唯一的编码。该规范一直在进行修订和更新，不断加入新的语
种和符号。

一个 `字符' 是文本的最小组件。‘A’、‘B’、‘C’ 等都是不同的字符。‘È’ 和 ‘Í’
也一样。字符会随着语言或者上下文的变化而变化。比如，‘Ⅰ’ 是一个表示 “罗马
数字 1” 的字符，它与大写字母 ‘I’ 不同。他们往往看起来相同，但这是两个有
着不同含义的字符。

Unicode 标准描述了字符是如何用 `码位（code point）' 表示的。码位的取值范
围是 0 到 0x10FFFF 的整数（大约 110 万个值，实际分配的数字(1) 没有那么多
）。在 Unicode 标准和本文中，码位采用 ‘U+265E’ 的形式，表示值为 ‘0x265e’
的字符（十进制为 9822）。

Unicode 标准中包含了许多表格，列出了很多字符及其对应的码位。

     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
     ...

严格地说，上述定义暗示了以下说法是没有意义的：“这是字符 ‘U+265E’”。
‘U+265E’ 只是一个码位，代表某个特定的字符；这里它代表了字符 “国际象棋黑
骑士” ’♞’。在非正式的上下文中，有时会忽略码位和字符的区别。

一个字符在屏幕或纸上被表示为一组图形元素，被称为 `字形（glyph）' 。比如
，大写字母 A 的字形，是两笔斜线和一笔横线，而具体的细节取决于所使用的字
体。大部分 Python 代码不必担心字形，找到正确的显示字形通常是交给 GUI 工
具包或终端的字体渲染程序来完成。

   ---------- Footnotes ----------

   (1) https://www.unicode.org/versions/latest/#Summary


File: python.info,  Node: 编码,  Next: 引用文献<2>,  Prev: 定义,  Up: Unicode 概述

10.11.1.2 编码
..............

上一段可以归结为：一个 Unicode 字符串是一系列码位（从 0 到 ‘0x10FFFF’ 或
者说十进制的 1,114,111 的数字）组成的序列。这一序列在内存中需被表示为一
组 `码元（code unit）' ， `码元' 会映射成包含八个二进制位的字节。将
Unicode 字符串翻译成字节序列的规则称为 `字符编码' ，或者 `编码' 。

大家首先会想到的编码可能是用 32 位的整数作为代码位，然后采用 CPU 对 32 位
整数的表示法。字符串 “Python” 用这种表示法可能会如下所示：

        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

这种表示法非常直白，但也存在 一些问题。

  1. 不具可移植性；不同的处理器的字节序不同。

  2. 非常浪费空间。 在大多数文本中，大部分码位都小于 127 或 255，因此字
     节 ‘0x00’ 占用了大量空间。相较于 ASCII 表示法所需的 6 个字节，以上
     字符串需要占用 24 个字节。RAM 用量的增加没那么要紧（台式计算机有成
     GB 的 RAM，而字符串通常不会有那么大），但要把磁盘和网络带宽的用量增
     加 4 倍是无法忍受的。

  3. 与现有的 C 函数（如 ‘strlen()’ ）不兼容，因此需要采用一套新的宽字符
     串函数。

因此这种编码用得不多，人们转而选择其他更高效、更方便的编码，比如 UTF-8。

UTF-8 是最常用的编码之一，Python 往往默认会采用它。UTF 代表“Unicode
Transformation Format”，’8’ 表示编码采用 8 位数。（UTF-16 和 UTF-32 编码
也是存在的，但其使用频率不如 UTF-8。）UTF-8 的规则如下：

  1. 如果码位 < 128，则直接用对应的字节值表示。

  2. 如果码位 >= 128，则转换为 2、3、4 个字节的序列，每个字节值都位于
     128 和 255 之间。

UTF-8 有几个很方便的特性：

  1. 可以处理任何 Unicode 码位。

  2. Unicode 字符串被转换为一个字节序列，仅在表示空（null ）字符（
     U+0000）时才会包含零值的字节。这意味着 ‘strcpy()’ 之类的C 函数可以
     处理 UTF-8 字符串，而且用那些不能处理字符串结束符之外的零值字节的协
     议也能发送。

  3. ASCII 字符串也是也是也是合法的 UTF-8 文本。

  4. UTF-8 相当紧凑；大多数常用字符均可用一两个字节表示。

  5. 如果字节数据被损坏或丢失，则可以找出下一个 UTF-8 码点的开始位置并重
     新开始同步。随机的 8 位数据也不太可能像是有效的 UTF-8 编码。

  6. UTF-8 是一种面向字节的编码。编码规定了每个字符由一个或多个字节的序
     列表示。这避免了整数和双字节编码（如 UTF-16 和 UTF-32）可能出现的字
     节顺序问题，那时的字节序列会因执行编码的硬件而异。


File: python.info,  Node: 引用文献<2>,  Prev: 编码,  Up: Unicode 概述

10.11.1.3 引用文献
..................

Unicode Consortium 站点(1) 包含 Unicode 规范的字符图表、词汇表和 PDF 版
本。请做好准备，有些内容读起来有点难度。该网站上还提供了 Unicode 起源和
发展的‘年表 <‘https://www.unicode.org/history/’>‘_ 。

在 Computerphile 的 Youtube 频道上，Tom Scott 简要地‘讨论了 Unicode 和
UTF-8 <‘https://www.youtube.com/watch?v=MijmeoH9LT4’>‘_（9 分 36 秒）的
历史。

为了帮助理解该标准，Jukka Korpela 编写了阅读 Unicode 字符表的‘介绍性指南
<‘http://jkorpela.fi/unicode/guide.html’>‘_ 。

Joel Spolsky 撰写了另一篇不错的介绍性文章
<‘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 条目通常也有帮助；请参阅“字符编码(2)”和 UTF-8(3) 的条目，例如
：

   ---------- Footnotes ----------

   (1) https://www.unicode.org

   (2) https://en.wikipedia.org/wiki/Character_encoding

   (3) https://en.wikipedia.org/wiki/UTF-8


File: python.info,  Node: Python对Unicode的支持,  Next: Unicode 数据的读写,  Prev: Unicode 概述,  Up: Unicode 指南

10.11.2 Python对Unicode的支持
-----------------------------

现在您已经了解了 Unicode 的基础知识，可以看下 Python 的 Unicode 特性。

* Menu:

* 字符串类型::
* 转换为字节::
* Python 源代码中的 Unicode 文字::
* Unicode属性::
* 字符串比较::
* Unicode 正则表达式::
* 引用文献: 引用文献<3>.


File: python.info,  Node: 字符串类型,  Next: 转换为字节,  Up: Python对Unicode的支持

10.11.2.1 字符串类型
....................

从 Python 3.0 开始， *note str: 205. 类型包含了 Unicode 字符，这意味着用
‘‘"unicode rocks!"‘、’’unicode rocks!’‘‘ 或三重引号字符串语法创建的任何
字符串都会存储为 Unicode。

Python 源代码的默认编码是 UTF-8，因此可以直接在字符串中包含 Unicode 字符
：

     try:
         with open('/tmp/input.txt', 'r') as f:
             ...
     except OSError:
         # 'File not found' error message.
         print("Fichier non trouvé")

旁注：Python 3 还支持在标识符中使用 Unicode 字符：

     répertoire = "/tmp/records.log"
     with open(répertoire, "w") as f:
         f.write("test\n")

如果无法在编辑器中输入某个字符，或出于某种原因想只保留 ASCII 编码的源代
码，则还可以在字符串中使用转义序列。（根据系统的不同，可能会看到真的大写
Delta 字体而不是 u 转义符。）：

     >>> "\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'

此外，可以用 *note bytes: 172. 的 *note decode(): 171. 方法创建一个字符
串。 该方法可以接受 `encoding' 参数，比如可以为 ‘UTF-8’ ，以及可选的
`errors' 参数。

若无法根据编码规则对输入字符串进行编码，`errors' 参数指定了响应策略。 该
参数的合法值可以是 ‘'strict'’ (触发 *note UnicodeDecodeError: 32b. 异常
)、‘'replace'’ (用 ‘U+FFFD’、‘REPLACEMENT CHARACTER’)、‘'ignore'’ (只是
将字符从 Unicode 结果中去掉)，或 ‘'backslashreplace'’ (插入一个 ‘\xNN’ 转
义序列)。 以下示例演示了这些不同的参数:

     >>> 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'

编码格式以包含编码格式名称的字符串来指明。 Python 有大约 100 种不同的编
码格式；清单详见 Python 库参考文档 *note 标准编码: 782.。 一些编码格式有
多个名称，比如 ‘'latin-1'’、‘'iso_8859_1'’ 和 ‘'8859’ 都是指同一种编码。

利用内置函数 *note chr(): 155a. 还可以创建单字符的 Unicode 字符串，该函
数可接受整数参数，并返回包含对应码位的长度为 1 的 Unicode 字符串。内置函
数 *note ord(): 1559. 是其逆操作，参数为单个字符的 Unicode 字符串，并返
回码位值：

     >>> chr(57344)
     '\ue000'
     >>> ord('\ue000')
     57344


File: python.info,  Node: 转换为字节,  Next: Python 源代码中的 Unicode 文字,  Prev: 字符串类型,  Up: Python对Unicode的支持

10.11.2.2 转换为字节
....................

*note bytes.decode(): 171. 的逆方法是 *note str.encode(): 170. ，它会返
回 Unicode 字符串的 *note bytes: 172. 形式，已按要求的 `encoding' 进行了
编码。

参数 `errors' 的意义与 *note decode(): 171. 方法相同，但支持更多可能的
handler。除了 ‘'strict'’ 、 ‘'ignore'’ 和 ‘'replace'’ （这时会插入问号替
换掉无法编码的字符），还有 ‘'xmlcharrefreplace'’ （插入一个 XML 字符引用
）、 ‘backslashreplace’ （插入一个 ‘\uNNNN’ 转义序列）和 ‘namereplace’ （
插入一个 ‘\N{...}’ 转义序列 ）。

以下例子演示了各种不同的结果：

     >>> 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'

用于注册和访问可用编码格式的底层函数，位于 *note codecs: 1b. 模块中。 若
要实现新的编码格式，则还需要了解 *note codecs: 1b. 模块。 不过该模块返回
的编码和解码函数通常更为底层一些，不大好用，编写新的编码格式是一项专业的
任务，因此本文不会涉及该模块。


File: python.info,  Node: Python 源代码中的 Unicode 文字,  Next: Unicode属性,  Prev: 转换为字节,  Up: Python对Unicode的支持

10.11.2.3 Python 源代码中的 Unicode 文字
........................................

在 Python 源代码中，可以用 ‘\u’ 转义序列书写特定的 Unicode 码位，该序列
后跟 4 个代表码位的十六进制数字。‘\U’ 转义序列用法类似，但要用8 个十六进
制数字，而不是 4 个：

     >>> 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]

对大于 127 的码位使用转义序列，数量不多时没什么问题，但如果要用到很多重
音字符，这会变得很烦人，类似于程序中的信息是用法语或其他使用重音的语言写
的。也可以用内置函数 *note chr(): 155a. 拼装字符串，但会更加乏味。

理想情况下，都希望能用母语的编码书写文本。还能用喜好的编辑器编辑 Python
源代码，编辑器要能自然地显示重音符，并在运行时使用正确的字符。

默认情况下，Python 支持以 UTF-8 格式编写源代码，但如果声明要用的编码，则
几乎可以使用任何编码。只要在源文件的第一行或第二行包含一个特殊注释即可：

     #!/usr/bin/env python
     # -*- coding: latin-1 -*-

     u = 'abcdé'
     print(ord(u[-1]))

上述语法的灵感来自于 Emacs 用于指定文件局部变量的符号。Emacs 支持许多不
同的变量，但 Python 仅支持“编码”。 ‘-*-’ 符号向 Emacs 标明该注释是特殊的
；这对 Python 没有什么意义，只是一种约定。Python 会在注释中查找 ‘coding:
name’ 或 ‘coding=name’ 。

如果没有这种注释，则默认编码将会是前面提到的 UTF-8。更多信息请参阅 PEP
263(1) 。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0263


File: python.info,  Node: Unicode属性,  Next: 字符串比较,  Prev: Python 源代码中的 Unicode 文字,  Up: Python对Unicode的支持

10.11.2.4 Unicode属性
.....................

Unicode 规范包含了一个码位信息数据库。对于定义的每一个码位，都包含了字符
的名称、类别、数值（对于表示数字概念的字符，如罗马数字、分数如三分之一和
五分之四等）。还有有关显示的属性，比如如何在双向文本中使用码位。

以下程序显示了几个字符的信息，并打印一个字符的数值：

     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]))

当运行时，这将打印出：

     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

类别代码是描述字符性质的一个缩写。分为“字母”、“数字”、“标点符号”或“符号
”等类别，而这些类别又分为子类别。就以上输出的代码而言，‘'Ll'’ 表示“字母
，小写”，‘'No'’ 表示“数字，其他”，‘'Mn'’ 表示“标记，非空白符” , ‘'So'’ 是
“符号，其他”。有关类别代码的清单，请参阅 Unicode 字符库文档
<‘https://www.unicode.org/reports/tr44/#General_Category_Values’>‘_ 的
“通用类别值”部分。


File: python.info,  Node: 字符串比较,  Next: Unicode 正则表达式,  Prev: Unicode属性,  Up: Python对Unicode的支持

10.11.2.5 字符串比较
....................

Unicode 让字符串的比较变得复杂了一些，因为同一组字符可能由不同的码位序列
组成。例如，像“ê”这样的字母可以表示为单码位 U+00EA，或是 U+0065 U+0302，
即“e”的码位后跟“COMBINING CIRCUMFLEX ACCENT”的码位。虽然在打印时会产生同
样的输出，但一个是长度为 1 的字符串，另一个是长度为 2 的字符串。

一种不区分大小写比较的工具是字符串方法 *note casefold(): 7a3. ，将按照
Unicode 标准描述的算法将字符串转换为不区分大小写的形式。该算法对诸如德语
字母“ß”（代码点 U+00DF）之类的字符进行了特殊处理，变为一对小写字母“ss”。

     >>> street = 'Gürzenichstraße'
     >>> street.casefold()
     'gürzenichstrasse'

第二个工具是 *note unicodedata: 123. 模块的 *note normalize(): 11e4. 函
数，将字符串转换为几种规范化形式之一，其中后跟组合字符的字母将被替换为单
个字符。 ‘normalize()’ 可用于执行字符串比较，即便两个字符串采用不同的字
符组合，也不会错误地报告两者不相等：

     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))

当运行时，这将输出：

     $ python3 compare-strs.py
     length of first string= 1
     length of second string= 2
     True

*note normalize(): 11e4. 函数的第一个参数是个字符串，给出所需的规范化形
式，可以是“NFC”、“NFKC”、“NFD”和“NFKD”之一。

Unicode 标准还设定了如何进行不区分大小写的比较：

     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))

这将打印 ‘True’ 。（为什么 ‘NFD()’ 会被调用两次？因为有几个字符让
‘casefold()’ 返回非规范化的字符串，所以结果需要再次进行规范化。参见
Unicode 标准的 3.13 节 的一个讨论和示例。）


File: python.info,  Node: Unicode 正则表达式,  Next: 引用文献<3>,  Prev: 字符串比较,  Up: Python对Unicode的支持

10.11.2.6 Unicode 正则表达式
............................

*note re: dd. 模块支持的正则表达式可以用字节串或字符串的形式提供。有一些
特殊字符序列，比如 ‘\d’ 和 ‘\w’ 具有不同的含义，具体取决于匹配模式是以字
节串还是字符串形式提供的。例如，‘\d’ 将匹配字节串中的字符 ‘[0-9]’ ，但对
于字符串将会匹配 ‘'Nd'’ 类别中的任何字符。

上述示例中的字符串包含了泰语和阿拉伯数字书写的数字 57：

     import re
     p = re.compile(r'\d+')

     s = "Over \u0e55\u0e57 57 flavours"
     m = p.search(s)
     print(repr(m.group()))

执行时，‘\d+’ 将匹配上泰语数字并打印出来。如果向 *note compile(): 54c. 提
供的是 *note re.ASCII: 4ce. 标志，‘\d+’ 则会匹配子串 "57"。

类似地，‘\w’ 将匹配多种 Unicode 字符，但对于字节串则只会匹配
‘[a-zA-Z0-9_]’ ，如果指定 *note re.ASCII: 4ce.， ‘\s `` 将匹配 Unicode 空
白符或 ``[ \t\n\r\f\v]’。


File: python.info,  Node: 引用文献<3>,  Prev: Unicode 正则表达式,  Up: Python对Unicode的支持

10.11.2.7 引用文献
..................

关于 Python 的 Unicode 支持，其他还有一些很好的讨论：

   * 用 Python 3 处理文本文件(1) ，作者 Nick Coghlan。

   * 实用的 Unicode(2)，Ned Batchelder 在 PyCon 2012 上的演示。

*note str: 205. 类型在 Python 库参考文档 *note 文本序列类型 — str: 1357.
中有介绍。

*note unicodedata: 123. 模块的文档

*note codecs: 1b. 模块的文档

Marc-André Lemburg 在 EuroPython 2002 上做了一个题为“Python 和 Unicode”（
PDF 幻灯片）
<‘https://downloads.egenix.com/python/Unicode-EPC2002-Talk.pdf’>‘_ 的演
示文稿。该幻灯片很好地概括了 Python 2 的 Unicode 功能设计（其中 Unicode
字符串类型称为 ‘unicode’，文字以 ‘u’ 开头）。

   ---------- Footnotes ----------

   (1) 
http://python-notes.curiousefficiency.org/en/latest/python3/text_file_processing.html

   (2) https://nedbatchelder.com/text/unipain.html


File: python.info,  Node: Unicode 数据的读写,  Next: 致谢<10>,  Prev: Python对Unicode的支持,  Up: Unicode 指南

10.11.3 Unicode 数据的读写
--------------------------

既然处理 Unicode 数据的代码写好了，下一个问题就是输入/输出了。如何将
Unicode 字符串读入程序，如何将 Unicode 转换为适于存储或传输的形式呢？

根据输入源和输出目标的不同，或许什么都不用干；请检查一下应用程序用到的库
是否原生支持 Unicode。例如，XML 解析器往往会返回 Unicode 数据。许多关系
数据库的字段也支持 Unicode 值，并且 SQL 查询也能返回 Unicode 值。

在写入磁盘或通过套接字发送之前，Unicode 数据通常要转换为特定的编码。可以
自己完成所有工作：打开一个文件，从中读取一个 8 位字节对象，然后用
‘bytes.decode(encoding)’ 对字节串进行转换。但是，不推荐采用这种全人工的
方案。

编码的多字节特性就是一个难题； 一个 Unicode 字符可以用几个字节表示。 如
果要以任意大小的块（例如 1024 或 4096 字节）读取文件，那么在块的末尾可能
只读到某个 Unicode 字符的部分字节，这就需要编写错误处理代码。 有一种解决
方案是将整个文件读入内存，然后进行解码，但这样就没法处理很大的文件了；若
要读取 2 GB 的文件，就需要 2 GB 的 RAM。（其实需要的内存会更多些，因为至
少有一段时间需要在内存中同时存放已编码字符串及其 Unicode 版本。）

解决方案是利用底层解码接口去捕获编码序列不完整的情况。这部分代码已经是现
成的：内置函数 *note open(): 16f. 可以返回一个文件类的对象，该对象认为文
件的内容采用指定的编码，*note read(): 2162. 和 *note write(): 2165. 等方
法接受 Unicode 参数。只要用 *note open(): 16f. 的 `encoding' 和 `errors'
参数即可，参数释义同 *note str.encode(): 170. 和 *note bytes.decode():
171. 。

因此从文件读取 Unicode 就比较简单了：

     with open('unicode.txt', encoding='utf-8') as f:
         for line in f:
             print(repr(line))

也可以在更新模式下打开文件，以便同时读取和写入：

     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]))

Unicode 字符 ‘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>.


File: python.info,  Node: Unicode 文件名,  Next: 识别 Unicode 的编程技巧,  Up: Unicode 数据的读写

10.11.3.1 Unicode 文件名
........................

当今大多数操作系统的文件名都支持包含任意 Unicode 字符。通常这是通过将
Unicode 字符串转换为某系统的编码来实现的。如今的 Python 趋向于采用 UTF-8
编码：MacOS 上的 Python 已经在多个版本中采用了 UTF-8，而 Python 3.6 在
Windows 上也改用了 UTF-8。在 Unix 系统中，只有设置了 ‘LANG’ 或
‘LC_CTYPE’ 环境变量，才会采用某个文件系统编码；否则默认编码还是 UTF-8。

*note sys.getfilesystemencoding(): 5ef. 函数将返回要在当前系统采用的编码
，若想手动进行编码时即可用到，但无需多虑。在打开文件进行读写时，通常只需
提供 Unicode 字符串作为文件名，会自动转换为合适的编码格式：

     filename = 'filename\u4500abc'
     with open(filename, 'w') as f:
         f.write('blah\n')

*note os: c4. 模块中的函数也能接受 Unicode 文件名，如 *note os.stat():
321. 。

*note os.listdir(): b1c. 函数将返回文件名，这会引发一个难题：到底应返回
文件名的 Unicode 版本，还是应返回已编码的字节串呢？这两种操作 *note
os.listdir(): b1c. 均可执行，具体取决于给出的目录路径是字节串形式还是
Unicode 字符串。若传入一个 Unicode 字符串作为路径，文件名将用当前文件系
统的编码进行解码并返回一个 Unicode 字符串列表，而若传入一个字节串路径则
会返回字节串格式的文件名。以下假定默认文件系统编码为 UTF-8，运行以下程序
：

     fn = 'filename\u4500abc'
     f = open(fn, 'w')
     f.close()

     import os
     print(os.listdir(b'.'))
     print(os.listdir('.'))

将产生以下输出：

     $ python listdir-test.py
     [b'filename\xe4\x94\x80abc', ...]
     ['filename\u4500abc', ...]

第一个列表包含 UTF-8 编码的文件名，第二个列表则包含 Unicode 版本的。

请注意，大多时候应该坚持用这些 API 处理 Unicode。字节串 API 应该仅用于可
能存在不可解码文件名的系统；现在几乎仅剩 Unix 系统了。


File: python.info,  Node: 识别 Unicode 的编程技巧,  Next: 引用文献<4>,  Prev: Unicode 文件名,  Up: Unicode 数据的读写

10.11.3.2 识别 Unicode 的编程技巧
.................................

本节提供了一些关于编写 Unicode 处理软件的建议。

最重要的技巧如下：

     程序应只在内部处理 Unicode 字符串，尽快对输入数据进行解码，并只在最
     后对输出进行编码。

如果尝试编写的处理函数对 Unicode 和字节串形式的字符串都能接受，就会发现
组合使用两种不同类型的字符串时，容易产生差错。没办法做到自动编码或解码：
如果执行 ‘str + bytes’，则会触发 *note TypeError: 1fe.。

当要使用的数据来自 Web 浏览器或其他不受信来源时，常用技术是在用该字符串
生成命令行之前，或要存入数据库之前，先检查字符串中是否包含非法字符。请仔
细检查解码后的字符串，而不是编码格式的字节串数据；有些编码可能具备一些有
趣的特性，例如与 ASCII 不是一一对应或不完全兼容。如果输入数据还指定了编
码格式，则尤其如此，因为攻击者可以选择一种巧妙的方式将恶意文本隐藏在经过
编码的字节流中。

* Menu:

* 在文件编码格式之间进行转换::
* 编码格式未知的文件::


File: python.info,  Node: 在文件编码格式之间进行转换,  Next: 编码格式未知的文件,  Up: 识别 Unicode 的编程技巧

10.11.3.3 在文件编码格式之间进行转换
....................................

*note StreamRecoder: 1108. 类可以在两种编码之间透明地进行转换，参数为编
码格式为 #1 的数据流，表现行为则是编码格式为 #2 的数据流。

假设输入文件 `f' 采用 Latin-1 编码格式，即可用 *note StreamRecoder:
1108. 包装后返回 UTF-8 编码的字节串：

     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') )


File: python.info,  Node: 编码格式未知的文件,  Prev: 在文件编码格式之间进行转换,  Up: 识别 Unicode 的编程技巧

10.11.3.4 编码格式未知的文件
............................

若需对文件进行修改，但不知道文件的编码，那该怎么办呢？如果已知编码格式与
ASCII 兼容，并且只想查看或修改 ASCII 部分，则可利用 ‘surrogateescape’ 错
误处理 handler 打开文件：

     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)

‘surrogateescape’ 错误处理 handler 会把所有非 ASCII 字节解码为 U+DC80 至
U+DCFF 这一特殊范围的码位。当 ‘surrogateescape’ 错误处理 handler用于数据
编码并回写时，这些码位将转换回原样。


File: python.info,  Node: 引用文献<4>,  Prev: 识别 Unicode 的编程技巧,  Up: Unicode 数据的读写

10.11.3.5 引用文献
..................

David Beazley 在 PyCon 2010 上的演讲 掌握 Python 3 输入/输出(1) 中，有一
节讨论了文本和二进制数据的处理。

Marc-André Lemburg 演示的PDF 幻灯片“在 Python 中编写支持 Unicode 的应用
程序”(2) ，讨论了字符编码问题以及如何国际化和本地化应用程序。这些幻灯片
仅涵盖 Python 2.x。

Python Unicode 实质(3) 是 Benjamin Peterson 在 PyCon 2013 上的演讲，讨论
了 Unicode 在 Python 3.3 中的内部表示。

   ---------- Footnotes ----------

   (1) http://pyvideo.org/video/289/pycon-2010–mastering-python-3-io

   (2) 
https://downloads.egenix.com/python/LSM2005-Developing-Unicode-aware-applications-in-Python.pdf

   (3) http://pyvideo.org/video/1768/the-guts-of-unicode-in-python


File: python.info,  Node: 致谢<10>,  Prev: Unicode 数据的读写,  Up: Unicode 指南

10.11.4 致谢
------------

本文初稿由 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。


File: python.info,  Node: 如何使用urllib套件取得網路資源,  Next: Argparse 教學,  Prev: Unicode 指南,  Up: Python 如何達成任務

10.12 如何使用urllib套件取得網路資源
====================================


作者: 原文作者 Michael Foord(1)

     備註: 這份指南出自於早期版本的法文翻譯 urllib2 - Le Manuel
     manquant(2).

* Menu:

* 簡介: 簡介<15>.
* 從URL取得資源::
* 异常的处理::
* info 和 geturl 方法::
* Opener 和 Handler::
* 基本认证::
* 代理::
* 套接字与分层::
* 註解: 註解<3>.

   ---------- Footnotes ----------

   (1) http://www.voidspace.org.uk/python/index.shtml

   (2) 
http://www.voidspace.org.uk/python/articles/urllib2_francais.shtml


File: python.info,  Node: 簡介<15>,  Next: 從URL取得資源,  Up: 如何使用urllib套件取得網路資源

10.12.1 簡介
------------

Related Articles
................

以下這些與Python有關的文章說不定能幫到你:

   * Basic Authentication(1)

          以Python為例的 `Basic Authentication' 教學。

`urllib.request' 是一個用來從URLs (Uniform Resource Locators)取得資料的
Python模組。它提供一個了非常簡單的介面能接受多種不同的協議， `urlopen' 函
數。也提供了較複雜的介面用於處理一些常見的狀況，例如:基本的
authentication、cookies、proxies等等，這些都可以由handler或opener物件操
作。

urllib.request 支持多种 "URL 方案" （通过 URL中 ‘":"’ 之前的字符串加以区
分——如 ‘"ftp://python.org/"` 中的 ``"ftp"`’）即为采用其关联网络协议（
FTP、HTTP 之类）的 URL 方案 。本教程重点关注最常用的 HTTP 场景。

一般情形下 `urlopen' 是非常容易使用的，但當你遇到錯誤或者較複雜的情況下
，你可能需要對超文本協議HyperText Transfer Protocol有一定的了解。最完整
且具參考價值的是 RFC 2616(2)，不過它是一份技術文件並不容易閱讀，以下的教
學會提供足夠的HTTP知識來幫助你使用 `urllib'。這份教學並非要取代 *note
urllib.request: 129. 這份文件，你還是會需要它!

   ---------- Footnotes ----------

   (1) http://www.voidspace.org.uk/python/articles/authentication.shtml

   (2) https://tools.ietf.org/html/rfc2616.html


File: python.info,  Node: 從URL取得資源,  Next: 异常的处理,  Prev: 簡介<15>,  Up: 如何使用urllib套件取得網路資源

10.12.2 從URL取得資源
---------------------

以下是使用 urllib.request 最簡單的方法:

     import urllib.request
     with urllib.request.urlopen('http://python.org/') as response:
        html = response.read()

如果想通过 URL 获取资源并临时存储一下，可以采用 *note
shutil.copyfileobj(): 387. 和 *note tempfile.NamedTemporaryFile(): e0e.
函数：

     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

urllib 的很多用法就是这么简单（注意 URL 不仅可以 http: 开头，还可以是
ftp: 、file: 等）。不过本教程的目的是介绍更加复杂的应用场景，重点还是关
注 HTTP。

HTTP 以请求和响应为基础——客户端生成请求，服务器发送响应。urllib.request
用 ‘Request’ 对象来表示要生成的 HTTP 请求。最简单的形式就是创建一个
Request 对象，指定了想要获取的 URL。用这个 Request 对象作为参数调用
‘‘urlopen‘‘ ，将会返回该 URL 的响应对象。响应对象类似于文件对象，就是说
可以对其调用 ‘.read()’ 之类的命令：

     import urllib.request

     req = urllib.request.Request('http://www.voidspace.org.uk')
     with urllib.request.urlopen(req) as response:
        the_page = response.read()

请注意，urllib.request 用同一个 Request 接口处理所有 URL 方案。比如可生
成 FTP 请求如下：

     req = urllib.request.Request('ftp://example.com/')

就 HTTP 而言，Request 对象能够做两件额外的事情：首先可以把数据传给服务器
。其次，可以将 `有关' 数据或请求本身的额外信息（metadata）传给服务器——这
些信息将会作为 HTTP “头部”数据发送。下面依次看下。

* Menu:

* 数据::
* HTTP 头部信息::


File: python.info,  Node: 数据,  Next: HTTP 头部信息,  Up: 從URL取得資源

10.12.2.1 数据
..............

有时需要向某个 URL 发送数据，通常此 URL 会指向某个CGI（通用网关接口）脚
本或其他 web 应用。对于 HTTP 而言，这通常会用所谓的 `POST' 请求来完成。
当要把 Web 页填写的 HTML 表单提交时，浏览器通常会执行此操作。但并不是所
有的 POST 都来自表单：可以用 POST 方式传输任何数据到自己的应用上。对于通
常的 HTML 表单，数据需要以标准的方式编码，然后作为 ‘data’ 参数传给
Request 对象。编码过程是用 *note urllib.parse: 128. 库的函数完成的：

     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()

请注意，有时还需要采用其他编码，比如由 HTML 表单上传文件——更多细节请参见
HTML 规范，提交表单(1) 。

如果不传递 ‘data’ 参数，urllib 将采用 `GET' 请求。GET 和 POST 请求有一点
不同，POST 请求往往具有“副作用”，他们会以某种方式改变系统的状态。例如，
从网站下一个订单，购买一大堆罐装垃圾并运送到家。 尽管 HTTP 标准明确指出
POST `总是' 要导致副作用，而 GET 请求 `从来不会' 导致副作用。但没有什么
办法能阻止 GET 和 POST 请求的副作用。数据也可以在 HTTP GET 请求中传递，
只要把数据编码到 URL 中即可。

做法如下所示：

     >>> 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)

请注意，完整的 URL 是通过在其中添加 ‘?’ 创建的，后面跟着经过编码的数据。

   ---------- Footnotes ----------

   (1) https://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13


File: python.info,  Node: HTTP 头部信息,  Prev: 数据,  Up: 從URL取得資源

10.12.2.2 HTTP 头部信息
.......................

下面介绍一个具体的 HTTP 头部信息，以此说明如何在 HTTP 请求加入头部信息。

有些网站 (1) 不愿被程序浏览到，或者要向不同的浏览器发送不同版本 (2) 的网
页。默认情况下，urllib 将自身标识为“Python-urllib/xy”（其中 ‘x’ 、 ‘y’ 是
Python 版本的主、次版本号，例如 ‘Python-urllib/2.5’），这可能会让网站不
知所措，或者干脆就使其无法正常工作。浏览器是通过头部信息 ‘User-Agent’
(3) 来标识自己的。在创建 Request 对象时，可以传入字典形式的头部信息。以
下示例将生成与之前相同的请求，只是将自身标识为某个版本的 Internet
Explorer (4) ：

     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()

响应对象也有两个很有用的方法。请参阅有关 *note info 和 geturl: 43fe. 部
分，了解出现问题时会发生什么。

   ---------- Footnotes ----------

   (1) (1) 例如 Google。

   (2) (2) 对于网站设计而言，探测不同的浏览器是非常糟糕的做法——更为明智
的做法是采用 web 标准构建网站。不幸的是，很多网站依然向不同的浏览器发送
不同版本的网页。

   (3) (3) MSIE 6 的 user-agent 信息是 `“Mozilla/4.0 (compatible; MSIE
6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)”'

   (4) (4) 有关 HTTP 请求的头部信息，详情请参阅 *note Quick Reference to
HTTP Headers: 43fd.。


File: python.info,  Node: 异常的处理,  Next: info 和 geturl 方法,  Prev: 從URL取得資源,  Up: 如何使用urllib套件取得網路資源

10.12.3 异常的处理
------------------

如果 `urlopen' 无法处理响应信息，就会触发 ‘URLError’ 。尽管与通常的
Python API 一样，也可能触发 *note ValueError: 16d. 、 *note TypeError:
1fe. 等内置异常。

‘HTTPError’ 是 ‘URLError’ 的子类，当 URL 是 HTTP 的情况时将会触发。

上述异常类是从 *note urllib.error: 127. 模块中导出的。

* Menu:

* URLError::
* HTTPError::
* 总之::


File: python.info,  Node: URLError,  Next: HTTPError,  Up: 异常的处理

10.12.3.1 URLError
..................

触发 URLError 的原因，通常是网络不通（或者没有到指定服务器的路由），或者
指定的服务器不存在。这时触发的异常会带有一个 reason 属性，是一个包含错误
代码和文本错误信息的元组。

例如：

     >>> 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')


File: python.info,  Node: HTTPError,  Next: 总之,  Prev: URLError,  Up: 异常的处理

10.12.3.2 HTTPError
...................

从服务器返回的每个 HTTP 响应都包含一个数字的 “状态码”。有时该状态码表明
服务器无法完成该请求。默认的处理函数将会处理这其中的一部分响应。如若响应
是“redirection”，这是要求客户端从另一 URL 处获取数据，urllib 将会自行处
理。对于那些无法处理的状况，urlopen 将会引发 ‘HTTPError’ 。典型的错误包
括：“404”（页面无法找到）、“403”（请求遭拒绝）和“401”（需要身份认证）。

全部的 HTTP 错误码请参阅 RFC 2616(1) 。

‘HTTPError’ 实例将包含一个整数型的“code”属性，对应于服务器发来的错误。

* Menu:

* 错误代码::

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2616.html


File: python.info,  Node: 错误代码,  Up: HTTPError

10.12.3.3 错误代码
..................

由于默认处理函数会自行处理重定向（300 以内的错误码），而且 100–299 的状
态码表示成功，因此通常只会出现 400–599 的错误码。

*note http.server.BaseHTTPRequestHandler.responses: 2e15. 是很有用的响应
码字典，其中给出了 RFC 2616(1) 用到的所有响应代码。为方便起见，将此字典
转载如下：

     # 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.'),
         }

当触发错误时，服务器通过返回 HTTP 错误码 `和' 错误页面进行响应。可以将
‘HTTPError’ 实例用作返回页面的响应。这意味着除了 code 属性之外，错误对象
还像 ‘urllib.response’ 模块返回的那样具有 read、geturl 和 info 方法：

     >>> 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
       ...

   ---------- Footnotes ----------

   (1) https://tools.ietf.org/html/rfc2616.html


File: python.info,  Node: 总之,  Prev: HTTPError,  Up: 异常的处理

10.12.3.4 总之
..............

若要准备处理 ‘HTTPError’  `或' ‘URLError’ ，有两种简单的方案。推荐使用第
二种方案。

* Menu:

* 第一种方案::
* 第二种方案::


File: python.info,  Node: 第一种方案,  Next: 第二种方案,  Up: 总之

10.12.3.5 第一种方案
....................

     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

     備註: ‘except HTTPError’ `必须' 首先处理，否则 ‘except URLError’ 将
     会 `同时' 捕获 ‘HTTPError’ 。


File: python.info,  Node: 第二种方案,  Prev: 第一种方案,  Up: 总之

10.12.3.6 第二种方案
....................

     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


File: python.info,  Node: info 和 geturl 方法,  Next: Opener 和 Handler,  Prev: 异常的处理,  Up: 如何使用urllib套件取得網路資源

10.12.4 info 和 geturl 方法
---------------------------

由 urlopen （或者 ‘HTTPError’ 实例）所返回的响应包含两个有用的方法：
‘info()’ 和 ‘geturl()’，该响应由模块 *note urllib.response: 12a. 定义。

`geturl' ——返回所获取页面的真实 URL。该方法很有用，因为 ‘urlopen’ （或
opener 对象）可能已经经过了一次重定向。已获取页面的 URL 未必就是所请求的
URL 。

`info' - 该方法返回一个类似字典的对象，描述了所获取的页面，特别是由服务
器送出的头部信息（headers） 。目前它是一个 ‘http.client.HTTPMessage’ 实
例。

典型的 HTTP 头部信息包括“Content-length”、“Content-type”等。有关 HTTP 头
部信息的清单，包括含义和用途的简要说明，请参阅 HTTP Header 快速参考(1) 。

   ---------- Footnotes ----------

   (1) http://jkorpela.fi/http.html


File: python.info,  Node: Opener 和 Handler,  Next: 基本认证,  Prev: info 和 geturl 方法,  Up: 如何使用urllib套件取得網路資源

10.12.5 Opener 和 Handler
-------------------------

当获取 URL 时，会用到了一个 opener（一个类名可能经过混淆的 *note
urllib.request.OpenerDirector: 2d72. 的实例）。通常一直会用默认的 opener
——通过 ‘urlopen’ ——但也可以创建自定义的 opener 。opener 会用到 handler。
所有的“繁重工作”都由 handler 完成。每种 handler 知道某种 URL 方案（
http、ftp 等）的 URL 的打开方式，或是某方面 URL 的打开方式，例如 HTTP 重
定向或 HTTP cookie。

若要用已安装的某个 handler 获取 URL，需要创建一个 opener 对象，例如处理
cookie 的 opener，或对重定向不做处理的 opener。

若要创建 opener，请实例化一个 ‘OpenerDirector’ ，然后重复调用
‘.add_handler(some_handler_instance)’ 。

或者也可以用 ‘build_opener’ ，这是个用单次调用创建 opener 对象的便捷函数
。‘build_opener’ 默认会添加几个 handler，不过还提供了一种快速添加和/或覆
盖默认 handler 的方法。

可能还需要其他类型的 handler，以便处理代理、身份认证和其他常见但稍微特殊
的情况。

‘install_opener’ 可用于让 ‘opener’ 对象成为（全局）默认 opener。这意味着
调用 ‘urlopen’ 时会采用已安装的 opener。

opener 对象带有一个 ‘`open’ 方法，可供直接调用以获取 url，方式与
‘urlopen’ 函数相同。除非是为了调用方便，否则没必要去调用
‘install_opener’ 。


File: python.info,  Node: 基本认证,  Next: 代理,  Prev: Opener 和 Handler,  Up: 如何使用urllib套件取得網路資源

10.12.6 基本认证
----------------

为了说明 handler 的创建和安装过程，会用到 ‘HTTPBasicAuthHandler’ 。有关
该主题的更详细的介绍——包括基本身份认证的工作原理——请参阅 Basic
Authentication Tutorial(1) 。

如果需要身份认证，服务器会发送一条请求身份认证的头部信息（以及 401 错误
代码）。这条信息中指明了身份认证方式和“安全区域（realm）”。格式如下所示
：‘WWW-Authenticate: SCHEME realm="REALM"’ 。

例如

     WWW-Authenticate: Basic realm="cPanel Users"

然后，客户端应重试发起请求，请求数据中的头部信息应包含安全区域对应的用户
名和密码。这就是“基本身份认证”。为了简化此过程，可以创建
‘HTTPBasicAuthHandler’ 的一个实例及使用它的 opener。

‘HTTPBasicAuthHandler’ 用一个名为密码管理器的对象来管理 URL、安全区域与
密码、用户名之间的映射关系。如果知道确切的安全区域（来自服务器发送的身份
认证头部信息），那就可以用到 ‘HTTPPasswordMgr’ 。通常人们并不关心安全区
域是什么，这时用‘‘HTTPPasswordMgrWithDefaultRealm‘‘ 就很方便，允许为 URL
指定默认的用户名和密码。当没有为某个安全区域提供用户名和密码时，就会用到
默认值。下面用 ‘None’ 作为 ‘add_password’ 方法的安全区域参数，表明采用默
认用户名和密码。

首先需要身份认证的是顶级 URL。比传给 .add_password() 的 URL 级别“更深”的
URL 也会得以匹配：

     # 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)

     備註: 在以上例子中，只向 ‘build_opener’ 给出了
     ‘HTTPBasicAuthHandler’ 。默认情况下，opener 会有用于处理常见状况的
     handler ——‘ProxyHandler’ （如果设置代理的话，比如设置了环境变量
     ‘http_proxy’ ），‘UnknownHandler’ 、‘HTTPHandler’ 、
     ‘HTTPDefaultErrorHandler’ 、 ‘HTTPRedirectHandler’ 、 ‘FTPHandler’
     、 ‘FileHandler’ 、 ‘DataHandler’ 、 ‘HTTPErrorProcessor’ 。

‘top_level_url’ 其实 `要么' 是一条完整的 URL（包括 “http:” 部分和主机名
及可选的端口号），比如 ‘"http://example.com/"’ ， `要么' 是一条“访问权限
”（即主机名，及可选的端口号），比如 ‘"example.com"’ 或
‘"example.com:8080"’ （后一个示例包含了端口号）。访问权限 `不得' 包含“用
户信息”部分——比如 ‘"joe:password@example.com"’ 就不正确。

   ---------- Footnotes ----------

   (1) http://www.voidspace.org.uk/python/articles/authentication.shtml


File: python.info,  Node: 代理,  Next: 套接字与分层,  Prev: 基本认证,  Up: 如何使用urllib套件取得網路資源

10.12.7 代理
------------

`urllib' 将自动检测并使用代理设置。 这是通过 ‘ProxyHandler’ 实现的，当检
测到代理设置时，是正常 handler 链中的一部分。通常这是一件好事，但有时也
可能会无效 (1)。 一种方案是配置自己的 ‘ProxyHandler’ ，不要定义代理。 设
置的步骤与 Basic Authentication(2) handler 类似:

     >>> proxy_support = urllib.request.ProxyHandler({})
     >>> opener = urllib.request.build_opener(proxy_support)
     >>> urllib.request.install_opener(opener)

     備註: 目前 ‘urllib.request’ `尚不' 支持通过代理抓取 ‘https’ 链接地
     址。 但此功能可以通过扩展 urllib.request 来启用，如以下例程所示
     (3)。

     備註: 如果设置了 ‘REQUEST_METHOD’ 变量，则会忽略 ‘HTTP_PROXY’ ；参
     阅 *note getproxies(): 2d7f. 文档。

   ---------- Footnotes ----------

   (1) (5) 本人必须使用代理才能在工作中访问互联网。如果尝试通过代理获取
`localhost' URL，将会遭到阻止。IE 设置为代理模式，urllib 就会获取到配置
信息。为了用 localhost 服务器测试脚本，我必须阻止 urllib 使用代理。

   (2) http://www.voidspace.org.uk/python/articles/authentication.shtml

   (3) (6) urllib 的 SSL 代理 opener（CONNECT  方法）： ASPN Cookbook
Recipe (https://code.activestate.com/recipes/456195/) 。


File: python.info,  Node: 套接字与分层,  Next: 註解<3>,  Prev: 代理,  Up: 如何使用urllib套件取得網路資源

10.12.8 套接字与分层
--------------------

Python 获取 Web 资源的能力是分层的。urllib 用到的是 *note http.client:
93. 库，而后者又用到了套接字库。

从 Python 2.3 开始，可以指定套接字等待响应的超时时间。这对必须要读到网页
数据的应用程序会很有用。默认情况下，套接字模块 `不会超时' 并且可以挂起。
目前，套接字超时机制未暴露给 http.client 或 urllib.request 层使用。不过
可以为所有套接字应用设置默认的全局超时。

     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)

__________________________________________________________________


File: python.info,  Node: 註解<3>,  Prev: 套接字与分层,  Up: 如何使用urllib套件取得網路資源

10.12.9 註解
------------

这篇文档由 John Lee 审订。


File: python.info,  Node: Argparse 教學,  Next: ipaddress模組介紹,  Prev: 如何使用urllib套件取得網路資源,  Up: Python 如何達成任務

10.13 Argparse 教學
===================


作者: Tshepang Lekhonkhobe

這個教學傾向簡介 Python 官方標準含式庫中推薦的命令列解析模組 *note
argparse: 5.。

     備註: 另外兩個具有同樣功能的模組 *note getopt: 85. （一個相等於 C 語
     言中的 ‘getopt()’）以及被棄用的 *note optparse: c3.。而 *note
     argparse: 5. 也是根據 *note optparse: c3. 為基礎發展而來，因此有非
     常近似的使用方式。

* Menu:

* 概念::
* 基本用法: 基本用法<2>.
* 介紹位置參數::
* 介紹選項參數::
* 現在結合位置與選項參數::
* 进行一些小小的改进::
* 結論::


File: python.info,  Node: 概念,  Next: 基本用法<2>,  Up: Argparse 教學

10.13.1 概念
------------

藉由命令 ‘ls’ 的使用開始這些功能的介紹：

     $ 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.
     ...

我們可以從四個命令中可以學到的幾個概念：

   * 命令 ‘ls’ 在執行時不用其他參數就可以顯示出當前目錄底下的內容。

   * 根據這樣的概念延伸後來舉個例子，如果我們想秀出一個不在目錄的資料夾
     ‘pypy’ 的內容。我們可以在命令後加上一個位置參數。會用位置參數這樣的
     名稱是因為程式會知道輸入的參數該做的事情。這樣的概念很像另一個命令
     ‘cp’，基本的使用方式是 ‘cp SRC DEST’。第一個位置參數代表的是`想要複
     製的目標'，第二個位置的參數代表的則是`想要複製到的地方'。

   * 現在我們想再增加一些，要顯示除了檔名之外更多的資訊。在這裡就可以選
     擇加上 ‘-l’ 這個參數。

   * 這是 help 文件的片段。對於以前從未使用過的程序來說非常有用，可以透
     過這些 help 文件來了解這些該怎麼使用。


File: python.info,  Node: 基本用法<2>,  Next: 介紹位置參數,  Prev: 概念,  Up: Argparse 教學

10.13.2 基本用法
----------------

我們以一個很簡單的例子開始下面的介紹：

     import argparse
     parser = argparse.ArgumentParser()
     parser.parse_args()

下面是運行這些代碼的結果：

     $ 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

接者是發生的情況：

   * 運行這個腳本而沒有給與任何參數時就不會顯示任何東西至標準輸出畫面上
     。這裡並不是這麼的有用。

   * 第二個我們呈現出了 *note argparse: 5. 模組的用處。我們幾乎沒有做什
     麼事情，但已經得到一個很好的幫助信息。

   * 這個 ‘--help’ 選項可以簡短的表示成 ‘-h’ , 這是唯一一個選項我們不用
     去指明的（意即，沒有必要在這個參數後加上任何數值）。如果指定其他參
     數給他會造成錯誤。也因為這樣，我們得到了一個免費的信息。


File: python.info,  Node: 介紹位置參數,  Next: 介紹選項參數,  Prev: 基本用法<2>,  Up: Argparse 教學

10.13.3 介紹位置參數
--------------------

例子：

     import argparse
     parser = argparse.ArgumentParser()
     parser.add_argument("echo")
     args = parser.parse_args()
     print(args.echo)

運行這段代碼：

     $ 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

接者是發生的情況：

   * 我們增加了 ‘add_argument()’ ，利用這個方法可以指名讓我們的程式接受
     哪些命令列參數。

   * 現在呼叫我們的程序時需要指定一個參數選項。

   * 在這個例子中， ‘parse_args()’ 這個方法確實根據了 ‘echo’ 這個選項回
     傳了資料。

   * 这一变量是 *note argparse: 5. 免费施放的某种 “魔法”（即是说，不需要
     指定哪个变量是存储哪个值的）。你也可以注意到，这一名称与传递给方法
     的字符串参数一致，都是 ‘echo’。

注意, 雖然 help 秀出了看起來不錯的信息, 但現在並沒有給予到實質幫助。像剛
剛增加的 ‘echo’ 這個位置參數，除了猜測和讀原始碼之外，我們根本不曉得該怎
麼使用他。因此我們來做一點事讓他變得更有用：

     import argparse
     parser = argparse.ArgumentParser()
     parser.add_argument("echo", help="echo the string you use here")
     args = parser.parse_args()
     print(args.echo)

然後我們得到：

     $ 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

現在來做一些更有用處的事情：

     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)

下面是運行這些代碼的結果：

     $ 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'

那並沒有如預期這樣。這是因為 *note argparse: 5. 將我們給予選項的值當成字
串，除然我們告訴他要怎麼做。所以我們來告訴 *note argparse: 5. 將這個輸入
值當成整數來使用：

     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)

下面是運行這些代碼的結果：

     $ python3 prog.py 4
     16
     $ python3 prog.py four
     usage: prog.py [-h] square
     prog.py: error: argument square: invalid int value: 'four'

這樣很順利。現在程序在開始之前會因為錯誤的輸入而回報有用的訊息並結束掉。


File: python.info,  Node: 介紹選項參數,  Next: 現在結合位置與選項參數,  Prev: 介紹位置參數,  Up: Argparse 教學

10.13.4 介紹選項參數
--------------------

到目前为止，我们一直在研究位置参数。让我们看看如何添加可选的：

     import argparse
     parser = argparse.ArgumentParser()
     parser.add_argument("--verbosity", help="increase output verbosity")
     args = parser.parse_args()
     if args.verbosity:
         print("verbosity turned on")

接者是結果：

     $ 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

接者是發生的情況：

   * 這個程式是寫成如果有指名 ‘--verbosity’ 這個參數選項那才顯示些資訊，
     反之亦然。

   * 不添加这一选项时程序没有提示任何错误而退出，表明这一选项确实是可选
     的。注意，如果一个可选参数没有被使用时，相关变量被赋值为 ‘None’，在
     此例中是 ‘args.verbosity’，这也就是为什么它在 *note if: eab. 语句中
     被当作逻辑假。

   * Help 訊息稍微有些不一樣。

   * 當使用 ‘--verbosity’ 參數選項時必須要指定一個數值。

在上面的例子中 ‘--verbosity’，接受任意的整數，但對我們的程式來說只接受兩
個輸入值， ‘True’ 或 ‘False’。所以我們來修改一下程式碼使其符合：

     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")

接者是結果：

     $ 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

接者是發生的情況：

   * 现在，这一选项更多地是一个标志，而非需要接受一个值的什么东西。我们
     甚至改变了选项的名字来符合这一思路。注意我们现在指定了一个新的关键
     词 ‘action’，并赋值为 ‘"store_true"’。这意味着，当这一选项存在时，
     为 ‘args.verbose’ 赋值为 ‘True’。没有指定时则隐含地赋值为 ‘False’。

   * 当你为其指定一个值时，它会报错，符合作为标志的真正的精神。

   * 注意不同的 help 文件。

* Menu:

* 短选项::


File: python.info,  Node: 短选项,  Up: 介紹選項參數

10.13.4.1 短选项
................

如果你很熟悉命令列的使用的話，你將會發現我還沒講到關於短參數。其實這很簡
單：

     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")

效果就像这样：

     $ 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

注意新的表示對於幫助文件也是一樣的


File: python.info,  Node: 現在結合位置與選項參數,  Next: 进行一些小小的改进,  Prev: 介紹選項參數,  Up: Argparse 教學

10.13.5 現在結合位置與選項參數
------------------------------

我們的程式成長的越來越複雜：

     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)

然後現在的輸出結果：

     $ 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

   * 我们带回了一个位置参数，结果发生了报错。

   * 注意現在的順序對於程式來說已經不再重要了.

给我们的程序加上接受多个冗长度的值，然后实际来用用：

     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)

接者是結果：

     $ 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

除了最后一个，看上去都不错。最后一个暴露了我们的程序中有一个 bug。我们可
以通过限制 ‘--verbosity’ 选项可以接受的值来修复它：

     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)

接者是結果：

     $ 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

注意这一改变同时反应在错误信息和帮助信息里。

现在，让我们使用另一种的方式来改变冗长度。这种方式更常见，也和 CPython 的
可执行文件处理它自己的冗长度参数的方式一致（参考 ‘python --help’ 的输出
）：

     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)

我們已經介紹過另一個操作 "count" 用來計算指定的選項參數出現的次數。

     $ 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

   * 是的，它现在比前一版本更像是一个标志（和 ‘action="store_true"’ 相似
     ）。这能解释它为什么报错。

   * 它也表现得与 “store_true” 的行为相似。

   * 現在來秀一下 "count" 這個動作會給予什麼。你可能之前就有見過這種用法
     。

   * 如果你不添加 ‘-v’ 标志，这一标志的值会是 ‘None’。

   * 應該要如預期那樣，就算給予長選項我們也要獲得一樣的輸出結果。

   * 可惜的是，对于我们的脚本获得的新能力，我们的帮助输出并没有提供很多
     信息，但我们总是可以通过改善文档来修复这一问题（比如通过 ‘help’ 关
     键字参数）。

   * 最后一个输出暴露了我们程序中的一个 bug。

讓我們來解決問題

     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)

而這也正是它給的：

     $ 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'

   * 第一组输出很好，修复了之前的 bug。也就是说，我们希望任何 >= 2 的值
     尽可能详尽。

   * 第三個輸出不是這麼的好。

我們來修復這個錯誤：

     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)

我们刚刚引入了又一个新的关键字 ‘default’。我们把它设置为 ‘0’ 来让它可以
与其他整数值相互比较。记住，默认情况下如果一个可选参数没有被指定，它的值
会是 ‘None’，并且它不能和整数值相比较（所以产生了 *note TypeError: 1fe.
异常）。

而且

     $ python3 prog.py 4
     16

凭借我们目前已学的东西你就可以做到许多事情，而我们还仅仅学了一些皮毛而已
。 *note argparse: 5. 模块是非常强大的，在结束篇教程之前我们将再探索更多
一些内容。


File: python.info,  Node: 进行一些小小的改进,  Next: 結論,  Prev: 現在結合位置與選項參數,  Up: Argparse 教學

10.13.6 进行一些小小的改进
--------------------------

如果我們想要擴展我們的小程式做比範例更多的事：

     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)

結果：

     $ 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

请注意到目前为止我们一直在使用详细级别来 `更改' 所显示的文本。 以下示例
则使用详细级别来显示 `更多的' 文本:

     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)

結果：

     $ 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

* Menu:

* 矛盾的选项::


File: python.info,  Node: 矛盾的选项,  Up: 进行一些小小的改进

10.13.6.1 矛盾的选项
....................

到目前为止，我们一直在使用 *note argparse.ArgumentParser: 788. 实例的两
个方法。 让我们再介绍第三个方法 ‘add_mutually_exclusive_group()’。 它允
许我们指定彼此相互冲突的选项。 让我们再更改程序的其余部分以便使用新功能
更有意义：我们将引入 ‘--quiet’ 选项，它将与 ‘--verbose’ 正好相反:

     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))

我们的程序现在变得更简洁了，我们出于演示需要略去了一些功能。 无论如何，
输出是这样的:

     $ 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

这应该很容易理解。 我添加了末尾的输出这样你就可以看到其所达到的灵活性，
即混合使用长和短两种形式的选项。

在我們結論之前，你可能想告訴你的用戶這個程式的主要目的，以防萬一他們不知
道：

     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))

请注意用法文本中有细微的差异。 注意 ‘[-v | -q]’，它的意思是说我们可以使
用 ‘-v’ 或 ‘-q’，但不能同时使用两者：

     $ 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


File: python.info,  Node: 結論,  Prev: 进行一些小小的改进,  Up: Argparse 教學

10.13.7 結論
------------

*note argparse: 5. 模組提供了比這裡展示更多的功能。它的文件是非常全面詳
細且充滿了例子。通過本教學，你應該比較容易消化它們了。


File: python.info,  Node: ipaddress模組介紹,  Next: Argument Clinic How-To,  Prev: Argparse 教學,  Up: Python 如何達成任務

10.14 ipaddress模組介紹
=======================


作者: Peter Moody


作者: Nick Coghlan

概述
....

本文档旨在简要介绍 *note ipaddress: a2. 模块。 它主要针对那些不熟悉 IP 网
络术语的用户，但也可能对想要速览 *note ipaddress: a2. 如何代表IP网络寻址
概念的网络工程师有用。

* Menu:

* 创建 Address/Network/Interface 对象::
* 审查 Address/Network/Interface 对象::
* Network 作为 Address 列表::
* 比较: 比较<3>.
* 将IP地址与其他模块一起使用::
* 实例创建失败时获取更多详细信息::


File: python.info,  Node: 创建 Address/Network/Interface 对象,  Next: 审查 Address/Network/Interface 对象,  Up: ipaddress模組介紹

10.14.1 创建 Address/Network/Interface 对象
-------------------------------------------

因为 *note ipaddress: a2. 是一个用于检查和操作 IP 地址的模块，你要做的第
一件事就是创建一些对象。 您可以使用 *note ipaddress: a2. 从字符串和整数
创建对象。

* Menu:

* 关于IP版本的说明::
* IP主机地址::
* 定义网络::
* 主机接口::


File: python.info,  Node: 关于IP版本的说明,  Next: IP主机地址,  Up: 创建 Address/Network/Interface 对象

10.14.1.1 关于IP版本的说明
..........................

对于不太熟悉 IP 寻址的读者，重要的是要知道 Internet 协议当前正在从协议的
版本4转移到版本6。转换很大程度上是因为协议的版本4没有提供足够的地址来满
足整个世界的需求，特别是考虑到越来越多的设备直接连接到互联网。

解释协议的两个版本之间的差异的细节超出了本介绍的范围，但读者需要至少知道
存在这两个版本，并且有时需要强制使用一个版本或其他版本。


File: python.info,  Node: IP主机地址,  Next: 定义网络,  Prev: 关于IP版本的说明,  Up: 创建 Address/Network/Interface 对象

10.14.1.2 IP主机地址
....................

通常称为“主机地址”的地址是使用IP寻址时最基本的单元。 创建地址的最简单方
法是使用 *note ipaddress.ip_address(): 3045. 工厂函数，该函数根据传入的
值自动确定是创建 IPv4 还是 IPv6 地址：

     >>> ipaddress.ip_address('192.0.2.1')
     IPv4Address('192.0.2.1')
     >>> ipaddress.ip_address('2001:DB8::1')
     IPv6Address('2001:db8::1')

地址也可以直接从整数创建，适配32位的值并假定为IPv4地址:

     >>> ipaddress.ip_address(3221225985)
     IPv4Address('192.0.2.1')
     >>> ipaddress.ip_address(42540766411282592856903984951653826561)
     IPv6Address('2001:db8::1')

要强制使用IPv4或IPv6地址，可以直接调用相关的类。 这对于强制为小整数创建
IPv6地址特别有用:

     >>> ipaddress.ip_address(1)
     IPv4Address('0.0.0.1')
     >>> ipaddress.IPv4Address(1)
     IPv4Address('0.0.0.1')
     >>> ipaddress.IPv6Address(1)
     IPv6Address('::1')


File: python.info,  Node: 定义网络,  Next: 主机接口,  Prev: IP主机地址,  Up: 创建 Address/Network/Interface 对象

10.14.1.3 定义网络
..................

主机地址通常组合在一起形成IP网络，因此 *note ipaddress: a2. 提供了一种创
建、检查和操作网络定义的方法。 IP网络对象由字符串构成，这些字符串定义作
为该网络一部分的主机地址范围。 该信息的最简单形式是“网络地址/网络前缀”对
，其中前缀定义了比较的前导比特数，以确定地址是否是网络的一部分，并且网络
地址定义了那些位的预期值。

对于地址，提供了一个自动确定正确IP版本的工厂函数:

     >>> 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')

网络对象不能设置任何主机位。 这样做的实际效果是‘‘192.0.2.1/24‘‘没有描述
网络。 这种定义被称为接口对象，因为网络上IP表示法通常用于描述给定网络上
的计算机的网络接口，并在下一节中进一步描述。

默认情况下，尝试创建一个设置了主机位的网络对象将导致 *note ValueError:
16d. 被引发。 要请求将附加位强制为零，可以将标志‘‘strict=False‘‘ 传递给
构造函数:

     >>> 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')

虽然字符串形式提供了更大的灵活性，但网络也可以用整数定义，就像主机地址一
样。 在这种情况下，网络被认为只包含由整数标识的单个地址，因此网络前缀包
括整个网络地址:

     >>> ipaddress.ip_network(3221225984)
     IPv4Network('192.0.2.0/32')
     >>> ipaddress.ip_network(42540766411282592856903984951653826560)
     IPv6Network('2001:db8::/128')

与地址一样，可以通过直接调用类构造函数而不是使用工厂函数来强制创建特定类
型的网络。


File: python.info,  Node: 主机接口,  Prev: 定义网络,  Up: 创建 Address/Network/Interface 对象

10.14.1.4 主机接口
..................

如上所述，如果您需要描述特定网络上的地址，则地址和网络类都不够。 像
‘192.0.2.1/24’ 这样的表示法通常被网络工程师和为防火墙和路由器编写工具的
人用作“ ‘192.0.2.0/24’ 网络上的主机 ‘192.0.2.1’ ”的简写。因此，*note
ipaddress: a2. 提供了一组将地址与特定网络相关联的混合类。用于创建的接口
与用于定义网络对象的接口相同，除了地址部分不限于是网络地址。

     >>> 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')

接受整数输入（与网络一样），并且可以通过直接调用相关构造函数来强制使用特
定IP版本。


File: python.info,  Node: 审查 Address/Network/Interface 对象,  Next: Network 作为 Address 列表,  Prev: 创建 Address/Network/Interface 对象,  Up: ipaddress模組介紹

10.14.2 审查 Address/Network/Interface 对象
-------------------------------------------

你已经遇到了创建IPv(4|6)(Address|Network|Interface) 对象的麻烦，因此你可
能希望获得有关它的信息。 *note ipaddress: a2. 试图让这个过程变得简单直观
。

提取 IP 版本:

     >>> addr4 = ipaddress.ip_address('192.0.2.1')
     >>> addr6 = ipaddress.ip_address('2001:db8::1')
     >>> addr6.version
     6
     >>> addr4.version
     4

从接口获取网络:

     >>> 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')

找出网络中有多少独立地址:

     >>> 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

迭代网络上的“可用”地址:

     >>> 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

获取网络掩码（即对应于网络前缀的设置位）或主机掩码（不属于网络掩码的任何
位）：

     >>> 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')

展开或压缩地址:

     >>> 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'

虽然IPv4不支持展开或压缩，但关联对象仍提供相关属性，因此版本中性代码可以
轻松确保最简洁或最详细的形式用于IPv6地址，同时仍能正确处理IPv4地址。


File: python.info,  Node: Network 作为 Address 列表,  Next: 比较<3>,  Prev: 审查 Address/Network/Interface 对象,  Up: ipaddress模組介紹

10.14.3 Network 作为 Address 列表
---------------------------------

将网络视为列表有时很有用。 这意味着它可以像这样索引它们:

     >>> 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')

它还意味着网络对象可以使用像这样的列表成员测试语法:

     if address in network:
         # do something

根据网络前缀有效地完成包含性测试:

     >>> 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


File: python.info,  Node: 比较<3>,  Next: 将IP地址与其他模块一起使用,  Prev: Network 作为 Address 列表,  Up: ipaddress模組介紹

10.14.4 比较
------------

*note ipaddress: a2. 有意义地提供了一些简单、希望直观的比较对象的方法:

     >>> ipaddress.ip_address('192.0.2.1') < ipaddress.ip_address('192.0.2.2')
     True

如果你尝试比较不同版本或不同类型的对象，则会引发 *note TypeError: 1fe. 异
常。


File: python.info,  Node: 将IP地址与其他模块一起使用,  Next: 实例创建失败时获取更多详细信息,  Prev: 比较<3>,  Up: ipaddress模組介紹

10.14.5 将IP地址与其他模块一起使用
----------------------------------

其他使用IP地址的模块（例如 *note socket: ef. ）通常不会直接接受来自该模
块的对象。 相反，它们必须被强制转换为另一个模块可接受的整数或字符串:

     >>> addr4 = ipaddress.ip_address('192.0.2.1')
     >>> str(addr4)
     '192.0.2.1'
     >>> int(addr4)
     3221225985


File: python.info,  Node: 实例创建失败时获取更多详细信息,  Prev: 将IP地址与其他模块一起使用,  Up: ipaddress模組介紹

10.14.6 实例创建失败时获取更多详细信息
--------------------------------------

使用与版本无关的工厂函数创建 address/network/interface 对象时，任何错误
都将报告为 *note ValueError: 16d. ，带有一般错误消息，只是说传入的值未被
识别为该类型的对象。 缺少特定错误是因为有必要知道该值是*假设*是IPv4还是
IPv6，以便提供有关其被拒绝原因的更多详细信息。

为了支持访问这些额外细节的用例，各个类构造函数实际上引发了 *note
ValueError: 16d. 子类 *note ipaddress.AddressValueError: 304d. 和 *note
ipaddress.NetmaskValueError: 3074. 以准确指示定义的哪一部分无法正确解析
。

直接使用类构造函数时，错误消息更加详细。 例如:

     >>> 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

但是，两个模块特定的异常都有 *note ValueError: 16d. 作为它们的父类，所以
如果你不关心特定类型的错误，你仍然可以编写如下代码:

     try:
         network = ipaddress.IPv4Network(address)
     except ValueError:
         print('address/netmask is invalid for IPv4:', address)


File: python.info,  Node: Argument Clinic How-To,  Next: 使用 DTrace 和 SystemTap 检测CPython,  Prev: ipaddress模組介紹,  Up: Python 如何達成任務

10.15 Argument Clinic How-To
============================


作者: Larry Hastings

摘要
....

Argument Clinic is a preprocessor for CPython C files.  Its purpose is
to automate all the boilerplate involved with writing argument parsing
code for "builtins".  This document shows you how to convert your first
C function to work with Argument Clinic, and then introduces some
advanced topics on Argument Clinic usage.

Currently Argument Clinic is considered internal-only for CPython.  Its
use is not supported for files outside CPython, and no guarantees are
made regarding backwards compatibility for future versions.  In other
words: if you maintain an external C extension for CPython, you’re
welcome to experiment with Argument Clinic in your own code.  But the
version of Argument Clinic that ships with the next version of CPython
`could' be totally incompatible and break all your code.

* Menu:

* The Goals Of Argument Clinic::
* Basic Concepts And Usage::
* Converting Your First Function::
* Advanced Topics::


File: python.info,  Node: The Goals Of Argument Clinic,  Next: Basic Concepts And Usage,  Up: Argument Clinic How-To

10.15.1 The Goals Of Argument Clinic
------------------------------------

Argument Clinic’s primary goal is to take over responsibility for all
argument parsing code inside CPython.  This means that, when you convert
a function to work with Argument Clinic, that function should no longer
do any of its own argument parsing—the code generated by Argument Clinic
should be a "black box" to you, where CPython calls in at the top, and
your code gets called at the bottom, with ‘PyObject *args’ (and maybe
‘PyObject *kwargs’) magically converted into the C variables and types
you need.

In order for Argument Clinic to accomplish its primary goal, it must be
easy to use.  Currently, working with CPython’s argument parsing library
is a chore, requiring maintaining redundant information in a surprising
number of places.  When you use Argument Clinic, you don’t have to
repeat yourself.

Obviously, no one would want to use Argument Clinic unless it’s solving
their problem—and without creating new problems of its own.  So it’s
paramount that Argument Clinic generate correct code.  It’d be nice if
the code was faster, too, but at the very least it should not introduce
a major speed regression.  (Eventually Argument Clinic `should' make a
major speedup possible—we could rewrite its code generator to produce
tailor-made argument parsing code, rather than calling the
general-purpose CPython argument parsing library.  That would make for
the fastest argument parsing possible!)

Additionally, Argument Clinic must be flexible enough to work with any
approach to argument parsing.  Python has some functions with some very
strange parsing behaviors; Argument Clinic’s goal is to support all of
them.

Finally, the original motivation for Argument Clinic was to provide
introspection "signatures" for CPython builtins.  It used to be, the
introspection query functions would throw an exception if you passed in
a builtin.  With Argument Clinic, that’s a thing of the past!

One idea you should keep in mind, as you work with Argument Clinic: the
more information you give it, the better job it’ll be able to do.
Argument Clinic is admittedly relatively simple right now.  But as it
evolves it will get more sophisticated, and it should be able to do many
interesting and smart things with all the information you give it.


File: python.info,  Node: Basic Concepts And Usage,  Next: Converting Your First Function,  Prev: The Goals Of Argument Clinic,  Up: Argument Clinic How-To

10.15.2 Basic Concepts And Usage
--------------------------------

Argument Clinic ships with CPython; you’ll find it in
‘Tools/clinic/clinic.py’.  If you run that script, specifying a C file
as an argument:

     $ python3 Tools/clinic/clinic.py foo.c

Argument Clinic will scan over the file looking for lines that look
exactly like this:

     /*[clinic input]

When it finds one, it reads everything up to a line that looks exactly
like this:

     [clinic start generated code]*/

Everything in between these two lines is input for Argument Clinic.  All
of these lines, including the beginning and ending comment lines, are
collectively called an Argument Clinic "block".

When Argument Clinic parses one of these blocks, it generates output.
This output is rewritten into the C file immediately after the block,
followed by a comment containing a checksum.  The Argument Clinic block
now looks like this:

     /*[clinic input]
     ... clinic input goes here ...
     [clinic start generated code]*/
     ... clinic output goes here ...
     /*[clinic end generated code: checksum=...]*/

If you run Argument Clinic on the same file a second time, Argument
Clinic will discard the old output and write out the new output with a
fresh checksum line.  However, if the input hasn’t changed, the output
won’t change either.

You should never modify the output portion of an Argument Clinic block.
Instead, change the input until it produces the output you want.
(That’s the purpose of the checksum—to detect if someone changed the
output, as these edits would be lost the next time Argument Clinic
writes out fresh output.)

For the sake of clarity, here’s the terminology we’ll use with Argument
Clinic:

   * The first line of the comment (‘/*[clinic input]’) is the `start
     line'.

   * The last line of the initial comment (‘[clinic start generated
     code]*/’) is the `end line'.

   * The last line (‘/*[clinic end generated code: checksum=...]*/’) is
     the `checksum line'.

   * In between the start line and the end line is the `input'.

   * In between the end line and the checksum line is the `output'.

   * All the text collectively, from the start line to the checksum line
     inclusively, is the `block'.  (A block that hasn’t been
     successfully processed by Argument Clinic yet doesn’t have output
     or a checksum line, but it’s still considered a block.)


File: python.info,  Node: Converting Your First Function,  Next: Advanced Topics,  Prev: Basic Concepts And Usage,  Up: Argument Clinic How-To

10.15.3 Converting Your First Function
--------------------------------------

The best way to get a sense of how Argument Clinic works is to convert a
function to work with it.  Here, then, are the bare minimum steps you’d
need to follow to convert a function to work with Argument Clinic.  Note
that for code you plan to check in to CPython, you really should take
the conversion farther, using some of the advanced concepts you’ll see
later on in the document (like "return converters" and "self
converters").  But we’ll keep it simple for this walkthrough so you can
learn.

Let’s dive in!

  0. Make sure you’re working with a freshly updated checkout of the
     CPython trunk.

  1. Find a Python builtin that calls either *note PyArg_ParseTuple():
     393. or *note PyArg_ParseTupleAndKeywords(): 6c1, and hasn’t been
     converted to work with Argument Clinic yet.  For my example I’m
     using ‘_pickle.Pickler.dump()’.

  2. If the call to the ‘PyArg_Parse’ function uses any of the following
     format units:

          O&
          O!
          es
          es#
          et
          et#

     or if it has multiple calls to *note PyArg_ParseTuple(): 393, you
     should choose a different function.  Argument Clinic `does' support
     all of these scenarios.  But these are advanced topics—let’s do
     something simpler for your first function.

     Also, if the function has multiple calls to *note
     PyArg_ParseTuple(): 393. or *note PyArg_ParseTupleAndKeywords():
     6c1. where it supports different types for the same argument, or if
     the function uses something besides PyArg_Parse functions to parse
     its arguments, it probably isn’t suitable for conversion to
     Argument Clinic.  Argument Clinic doesn’t support generic functions
     or polymorphic parameters.

  3. Add the following boilerplate above the function, creating our
     block:

          /*[clinic input]
          [clinic start generated code]*/

  4. Cut the docstring and paste it in between the ‘[clinic]’ lines,
     removing all the junk that makes it a properly quoted C string.
     When you’re done you should have just the text, based at the left
     margin, with no line wider than 80 characters.  (Argument Clinic
     will preserve indents inside the docstring.)

     If the old docstring had a first line that looked like a function
     signature, throw that line away.  (The docstring doesn’t need it
     anymore—when you use ‘help()’ on your builtin in the future, the
     first line will be built automatically based on the function’s
     signature.)

     Sample:

          /*[clinic input]
          Write a pickled representation of obj to the open file.
          [clinic start generated code]*/

  5. If your docstring doesn’t have a "summary" line, Argument Clinic
     will complain.  So let’s make sure it has one.  The "summary" line
     should be a paragraph consisting of a single 80-column line at the
     beginning of the docstring.

     (Our example docstring consists solely of a summary line, so the
     sample code doesn’t have to change for this step.)

  6. Above the docstring, enter the name of the function, followed by a
     blank line.  This should be the Python name of the function, and
     should be the full dotted path to the function—it should start with
     the name of the module, include any sub-modules, and if the
     function is a method on a class it should include the class name
     too.

     Sample:

          /*[clinic input]
          _pickle.Pickler.dump

          Write a pickled representation of obj to the open file.
          [clinic start generated code]*/

  7. If this is the first time that module or class has been used with
     Argument Clinic in this C file, you must declare the module and/or
     class.  Proper Argument Clinic hygiene prefers declaring these in a
     separate block somewhere near the top of the C file, in the same
     way that include files and statics go at the top.  (In our sample
     code we’ll just show the two blocks next to each other.)

     The name of the class and module should be the same as the one seen
     by Python.  Check the name defined in the *note PyModuleDef: 258.
     or *note PyTypeObject: 3f5. as appropriate.

     When you declare a class, you must also specify two aspects of its
     type in C: the type declaration you’d use for a pointer to an
     instance of this class, and a pointer to the *note PyTypeObject:
     3f5. for this class.

     Sample:

          /*[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]*/

  8. Declare each of the parameters to the function.  Each parameter
     should get its own line.  All the parameter lines should be
     indented from the function name and the docstring.

     The general form of these parameter lines is as follows:

          name_of_parameter: converter

     If the parameter has a default value, add that after the converter:

          name_of_parameter: converter = default_value

     Argument Clinic’s support for "default values" is quite
     sophisticated; please see *note the section below on default
     values: 4427. for more information.

     Add a blank line below the parameters.

     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.

     For each parameter, copy the "format unit" for that parameter from
     the ‘PyArg_Parse()’ format argument and specify `that' as its
     converter, as a quoted string.  ("format unit" is the formal name
     for the one-to-three character substring of the ‘format’ parameter
     that tells the argument parsing function what the type of the
     variable is and how to convert it.  For more on format units please
     see *note 语句解释及变量编译: 3f2.)

     For multicharacter format units like ‘z#’, use the entire
     two-or-three character string.

     Sample:

           /*[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]*/

  9. If your function has ‘|’ in the format string, meaning some
     parameters have default values, you can ignore it.  Argument Clinic
     infers which parameters are optional based on whether or not they
     have default values.

     If your function has ‘$’ in the format string, meaning it takes
     keyword-only arguments, specify ‘*’ on a line by itself before the
     first keyword-only argument, indented the same as the parameter
     lines.

     (‘_pickle.Pickler.dump’ has neither, so our sample is unchanged.)

  10. If the existing C function calls *note PyArg_ParseTuple(): 393.
     (as opposed to *note PyArg_ParseTupleAndKeywords(): 6c1.), then all
     its arguments are positional-only.

     To mark all parameters as positional-only in Argument Clinic, add a
     ‘/’ on a line by itself after the last parameter, indented the same
     as the parameter lines.

     Currently this is all-or-nothing; either all parameters are
     positional-only, or none of them are.  (In the future Argument
     Clinic may relax this restriction.)

     Sample:

          /*[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]*/

  11. It’s helpful to write a per-parameter docstring for each
     parameter.  But per-parameter docstrings are optional; you can skip
     this step if you prefer.

     Here’s how to add a per-parameter docstring.  The first line of the
     per-parameter docstring must be indented further than the parameter
     definition.  The left margin of this first line establishes the
     left margin for the whole per-parameter docstring; all the text you
     write will be outdented by this amount.  You can write as much text
     as you like, across multiple lines if you wish.

     Sample:

          /*[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]*/

  12. Save and close the file, then run ‘Tools/clinic/clinic.py’ on it.
     With luck everything worked—your block now has output, and a ‘.c.h’
     file has been generated!  Reopen the file in your text editor to
     see:

          /*[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]*/

     Obviously, if Argument Clinic didn’t produce any output, it’s
     because it found an error in your input.  Keep fixing your errors
     and retrying until Argument Clinic processes your file without
     complaint.

     For readability, most of the glue code has been generated to a
     ‘.c.h’ file.  You’ll need to include that in your original ‘.c’
     file, typically right after the clinic module block:

          #include "clinic/_pickle.c.h"

  13. Double-check that the argument-parsing code Argument Clinic
     generated looks basically the same as the existing code.

     First, ensure both places use the same argument-parsing function.
     The existing code must call either *note PyArg_ParseTuple(): 393.
     or *note PyArg_ParseTupleAndKeywords(): 6c1.; ensure that the code
     generated by Argument Clinic calls the `exact' same function.

     Second, the format string passed in to *note PyArg_ParseTuple():
     393. or *note PyArg_ParseTupleAndKeywords(): 6c1. should be
     `exactly' the same as the hand-written one in the existing
     function, up to the colon or semi-colon.

     (Argument Clinic always generates its format strings with a ‘:’
     followed by the name of the function.  If the existing code’s
     format string ends with ‘;’, to provide usage help, this change is
     harmless—don’t worry about it.)

     Third, for parameters whose format units require two arguments
     (like a length variable, or an encoding string, or a pointer to a
     conversion function), ensure that the second argument is `exactly'
     the same between the two invocations.

     Fourth, inside the output portion of the block you’ll find a
     preprocessor macro defining the appropriate static *note
     PyMethodDef: edd. structure for this builtin:

          #define __PICKLE_PICKLER_DUMP_METHODDEF    \
          {"dump", (PyCFunction)__pickle_Pickler_dump, METH_O, __pickle_Pickler_dump__doc__},

     This static structure should be `exactly' the same as the existing
     static *note PyMethodDef: edd. structure for this builtin.

     If any of these items differ in `any way', adjust your Argument
     Clinic function specification and rerun ‘Tools/clinic/clinic.py’
     until they `are' the same.

  14. Notice that the last line of its output is the declaration of your
     "impl" function.  This is where the builtin’s implementation goes.
     Delete the existing prototype of the function you’re modifying, but
     leave the opening curly brace.  Now delete its argument parsing
     code and the declarations of all the variables it dumps the
     arguments into.  Notice how the Python arguments are now arguments
     to this impl function; if the implementation used different names
     for these variables, fix it.

     Let’s reiterate, just because it’s kind of weird.  Your code should
     now look like this:

          static return_type
          your_function_impl(...)
          /*[clinic end generated code: checksum=...]*/
          {
          ...

     Argument Clinic generated the checksum line and the function
     prototype just above it.  You should write the opening (and
     closing) curly braces for the function, and the implementation
     inside.

     Sample:

          /*[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;

              ...

  15. Remember the macro with the *note PyMethodDef: edd. structure for
     this function?  Find the existing *note PyMethodDef: edd. structure
     for this function and replace it with a reference to the macro.
     (If the builtin is at module scope, this will probably be very near
     the end of the file; if the builtin is a class method, this will
     probably be below but relatively near to the implementation.)

     Note that the body of the macro contains a trailing comma.  So when
     you replace the existing static *note PyMethodDef: edd. structure
     with the macro, `don’t' add a comma to the end.

     Sample:

          static struct PyMethodDef Pickler_methods[] = {
              __PICKLE_PICKLER_DUMP_METHODDEF
              __PICKLE_PICKLER_CLEAR_MEMO_METHODDEF
              {NULL, NULL}                /* sentinel */
          };

  16. Compile, then run the relevant portions of the regression-test
     suite.  This change should not introduce any new compile-time
     warnings or errors, and there should be no externally-visible
     change to Python’s behavior.

     Well, except for one difference: ‘inspect.signature()’ run on your
     function should now provide a valid signature!

     Congratulations, you’ve ported your first function to work with
     Argument Clinic!


File: python.info,  Node: Advanced Topics,  Prev: Converting Your First Function,  Up: Argument Clinic How-To

10.15.4 Advanced Topics
-----------------------

Now that you’ve had some experience working with Argument Clinic, it’s
time for some advanced topics.

* Menu:

* Symbolic default values::
* Renaming the C functions and variables generated by Argument Clinic::
* Converting functions using PyArg_UnpackTuple::
* Optional Groups::
* Using real Argument Clinic converters, instead of "legacy converters": Using real Argument Clinic converters instead of "legacy converters".
* Py_buffer::
* Advanced converters::
* Parameter default values::
* The NULL default value::
* Expressions specified as default values::
* Using a return converter::
* Cloning existing functions::
* Calling Python code::
* Using a "self converter"::
* Writing a custom converter::
* Writing a custom return converter::
* METH_O and METH_NOARGS::
* tp_new and tp_init functions::
* Changing and redirecting Clinic's output::
* The #ifdef trick::
* Using Argument Clinic in Python files::


File: python.info,  Node: Symbolic default values,  Next: Renaming the C functions and variables generated by Argument Clinic,  Up: Advanced Topics

10.15.4.1 Symbolic default values
.................................

The default value you provide for a parameter can’t be any arbitrary
expression.  Currently the following are explicitly supported:

   * Numeric constants (integer and float)

   * 字符串常量

   * ‘True’, ‘False’, and ‘None’

   * Simple symbolic constants like ‘sys.maxsize’, which must start with
     the name of the module

In case you’re curious, this is implemented in ‘from_builtin()’ in
‘Lib/inspect.py’.

(In the future, this may need to get even more elaborate, to allow full
expressions like ‘CONSTANT - 1’.)


File: python.info,  Node: Renaming the C functions and variables generated by Argument Clinic,  Next: Converting functions using PyArg_UnpackTuple,  Prev: Symbolic default values,  Up: Advanced Topics

10.15.4.2 Renaming the C functions and variables generated by Argument Clinic
.............................................................................

Argument Clinic automatically names the functions it generates for you.
Occasionally this may cause a problem, if the generated name collides
with the name of an existing C function.  There’s an easy solution:
override the names used for the C functions.  Just add the keyword
‘"as"’ to your function declaration line, followed by the function name
you wish to use.  Argument Clinic will use that function name for the
base (generated) function, then add ‘"_impl"’ to the end and use that
for the name of the impl function.

For example, if we wanted to rename the C function names generated for
‘pickle.Pickler.dump’, it’d look like this:

     /*[clinic input]
     pickle.Pickler.dump as pickler_dumper

     ...

The base function would now be named ‘pickler_dumper()’, and the impl
function would now be named ‘pickler_dumper_impl()’.

Similarly, you may have a problem where you want to give a parameter a
specific Python name, but that name may be inconvenient in C. Argument
Clinic allows you to give a parameter different names in Python and in
C, using the same ‘"as"’ syntax:

     /*[clinic input]
     pickle.Pickler.dump

         obj: object
         file as file_obj: object
         protocol: object = NULL
         *
         fix_imports: bool = True

Here, the name used in Python (in the signature and the ‘keywords’
array) would be ‘file’, but the C variable would be named ‘file_obj’.

You can use this to rename the ‘self’ parameter too!


File: python.info,  Node: Converting functions using PyArg_UnpackTuple,  Next: Optional Groups,  Prev: Renaming the C functions and variables generated by Argument Clinic,  Up: Advanced Topics

10.15.4.3 Converting functions using PyArg_UnpackTuple
......................................................

To convert a function parsing its arguments with *note
PyArg_UnpackTuple(): f08, simply write out all the arguments, specifying
each as an ‘object’.  You may specify the ‘type’ argument to cast the
type as appropriate.  All arguments should be marked positional-only
(add a ‘/’ on a line by itself after the last argument).

Currently the generated code will use *note PyArg_ParseTuple(): 393, but
this will change soon.


File: python.info,  Node: Optional Groups,  Next: Using real Argument Clinic converters instead of "legacy converters",  Prev: Converting functions using PyArg_UnpackTuple,  Up: Advanced Topics

10.15.4.4 Optional Groups
.........................

Some legacy functions have a tricky approach to parsing their arguments:
they count the number of positional arguments, then use a ‘switch’
statement to call one of several different *note PyArg_ParseTuple():
393. calls depending on how many positional arguments there are.  (These
functions cannot accept keyword-only arguments.)  This approach was used
to simulate optional arguments back before *note
PyArg_ParseTupleAndKeywords(): 6c1. was created.

While functions using this approach can often be converted to use *note
PyArg_ParseTupleAndKeywords(): 6c1, optional arguments, and default
values, it’s not always possible.  Some of these legacy functions have
behaviors *note PyArg_ParseTupleAndKeywords(): 6c1. doesn’t directly
support.  The most obvious example is the builtin function ‘range()’,
which has an optional argument on the `left' side of its required
argument!  Another example is ‘curses.window.addch()’, which has a group
of two arguments that must always be specified together.  (The arguments
are called ‘x’ and ‘y’; if you call the function passing in ‘x’, you
must also pass in ‘y’—and if you don’t pass in ‘x’ you may not pass in
‘y’ either.)

In any case, the goal of Argument Clinic is to support argument parsing
for all existing CPython builtins without changing their semantics.
Therefore Argument Clinic supports this alternate approach to parsing,
using what are called `optional groups'.  Optional groups are groups of
arguments that must all be passed in together.  They can be to the left
or the right of the required arguments.  They can `only' be used with
positional-only parameters.

     備註: Optional groups are `only' intended for use when converting
     functions that make multiple calls to *note PyArg_ParseTuple():
     393.!  Functions that use `any' other approach for parsing
     arguments should `almost never' be converted to Argument Clinic
     using optional groups.  Functions using optional groups currently
     cannot have accurate signatures in Python, because Python just
     doesn’t understand the concept.  Please avoid using optional groups
     wherever possible.

To specify an optional group, add a ‘[’ on a line by itself before the
parameters you wish to group together, and a ‘]’ on a line by itself
after these parameters.  As an example, here’s how ‘curses.window.addch’
uses optional groups to make the first two parameters and the last
parameter optional:

     /*[clinic input]

     curses.window.addch

         [
         x: int
           X-coordinate.
         y: int
           Y-coordinate.
         ]

         ch: object
           Character to add.

         [
         attr: long
           Attributes for the character.
         ]
         /

     ...

註解：

   * For every optional group, one additional parameter will be passed
     into the impl function representing the group.  The parameter will
     be an int named ‘group_{direction}_{number}’, where ‘{direction}’
     is either ‘right’ or ‘left’ depending on whether the group is
     before or after the required parameters, and ‘{number}’ is a
     monotonically increasing number (starting at 1) indicating how far
     away the group is from the required parameters.  When the impl is
     called, this parameter will be set to zero if this group was
     unused, and set to non-zero if this group was used.  (By used or
     unused, I mean whether or not the parameters received arguments in
     this invocation.)

   * If there are no required arguments, the optional groups will behave
     as if they’re to the right of the required arguments.

   * In the case of ambiguity, the argument parsing code favors
     parameters on the left (before the required parameters).

   * Optional groups can only contain positional-only parameters.

   * Optional groups are `only' intended for legacy code.  Please do not
     use optional groups for new code.


File: python.info,  Node: Using real Argument Clinic converters instead of "legacy converters",  Next: Py_buffer,  Prev: Optional Groups,  Up: Advanced Topics

10.15.4.5 Using real Argument Clinic converters, instead of "legacy converters"
...............................................................................

To save time, and to minimize how much you need to learn to achieve your
first port to Argument Clinic, the walkthrough above tells you to use
"legacy converters".  "Legacy converters" are a convenience, designed
explicitly to make porting existing code to Argument Clinic easier.  And
to be clear, their use is acceptable when porting code for Python 3.4.

However, in the long term we probably want all our blocks to use
Argument Clinic’s real syntax for converters.  Why?  A couple reasons:

   * The proper converters are far easier to read and clearer in their
     intent.

   * There are some format units that are unsupported as "legacy
     converters", because they require arguments, and the legacy
     converter syntax doesn’t support specifying arguments.

   * In the future we may have a new argument parsing library that isn’t
     restricted to what *note PyArg_ParseTuple(): 393. supports; this
     flexibility won’t be available to parameters using legacy
     converters.

Therefore, if you don’t mind a little extra effort, please use the
normal converters instead of legacy converters.

In a nutshell, the syntax for Argument Clinic (non-legacy) converters
looks like a Python function call.  However, if there are no explicit
arguments to the function (all functions take their default values), you
may omit the parentheses.  Thus ‘bool’ and ‘bool()’ are exactly the same
converters.

All arguments to Argument Clinic converters are keyword-only.  All
Argument Clinic converters accept the following arguments:

     ‘c_default’

          The default value for this parameter when defined in C.
          Specifically, this will be the initializer for the variable
          declared in the "parse function".  See *note the section on
          default values: 4427. for how to use this.  Specified as a
          string.

     ‘annotation’

          The annotation value for this parameter.  Not currently
          supported, because PEP 8(1) mandates that the Python library
          may not use annotations.

In addition, some converters accept additional arguments.  Here is a
list of these arguments, along with their meanings:

     ‘accept’

          A set of Python types (and possibly pseudo-types); this
          restricts the allowable Python argument to values of these
          types.  (This is not a general-purpose facility; as a rule it
          only supports specific lists of types as shown in the legacy
          converter table.)

          To accept ‘None’, add ‘NoneType’ to this set.

     ‘bitwise’

          Only supported for unsigned integers.  The native integer
          value of this Python argument will be written to the parameter
          without any range checking, even for negative values.

     ‘converter’

          Only supported by the ‘object’ converter.  Specifies the name
          of a *note C "converter function": 3e92. to use to convert
          this object to a native type.

     ‘encoding’

          Only supported for strings.  Specifies the encoding to use
          when converting this string from a Python str (Unicode) value
          into a C ‘char *’ value.

     ‘subclass_of’

          Only supported for the ‘object’ converter.  Requires that the
          Python value be a subclass of a Python type, as expressed in
          C.

     ‘type’

          Only supported for the ‘object’ and ‘self’ converters.
          Specifies the C type that will be used to declare the
          variable.  Default value is ‘"PyObject *"’.

     ‘zeroes’

          Only supported for strings.  If true, embedded NUL bytes
          (‘'\\0'’) are permitted inside the value.  The length of the
          string will be passed in to the impl function, just after the
          string parameter, as a parameter named
          ‘<parameter_name>_length’.

Please note, not every possible combination of arguments will work.
Usually these arguments are implemented by specific ‘PyArg_ParseTuple’
`format units', with specific behavior.  For example, currently you
cannot call ‘unsigned_short’ without also specifying ‘bitwise=True’.
Although it’s perfectly reasonable to think this would work, these
semantics don’t map to any existing format unit.  So Argument Clinic
doesn’t support it.  (Or, at least, not yet.)

下表显示了传统转换器映射到实参转换器的情况。左边是传统转换器，右边是要替
换它的文本。

‘'B'’         ‘unsigned_char(bitwise=True)’
              
              
‘'b'’         ‘unsigned_char’
              
              
‘'c'’         ‘char’
              
              
‘'C'’         ‘int(accept={str})’
              
              
‘'d'’         ‘double’
              
              
‘'D'’         ‘Py_complex’
              
              
‘'es'’        ‘str(encoding='name_of_encoding')’
              
              
‘'es#'’       ‘str(encoding='name_of_encoding', zeroes=True)’
              
              
‘'et'’        ‘str(encoding='name_of_encoding', accept={bytes, bytearray, str})’
              
              
‘'et#'’       ‘str(encoding='name_of_encoding', accept={bytes, bytearray, str}, zeroes=True)’
              
              
‘'f'’         ‘float’
              
              
‘'h'’         ‘short’
              
              
‘'H'’         ‘unsigned_short(bitwise=True)’
              
              
‘'i'’         ‘int’
              
              
‘'I'’         ‘unsigned_int(bitwise=True)’
              
              
‘'k'’         ‘unsigned_long(bitwise=True)’
              
              
‘'K'’         ‘unsigned_long_long(bitwise=True)’
              
              
‘'l'’         ‘long’
              
              
‘'L'’         ‘long long’
              
              
‘'n'’         ‘Py_ssize_t’
              
              
‘'O'’         ‘object’
              
              
‘'O!'’        ‘object(subclass_of='&PySomething_Type')’
              
              
‘'O&'’        ‘object(converter='name_of_c_function')’
              
              
‘'p'’         ‘bool’
              
              
‘'S'’         ‘PyBytesObject’
              
              
‘'s'’         ‘str’
              
              
‘'s#'’        ‘str(zeroes=True)’
              
              
‘'s*'’        ‘Py_buffer(accept={buffer, str})’
              
              
‘'U'’         ‘unicode’
              
              
‘'u'’         ‘Py_UNICODE’
              
              
‘'u#'’        ‘Py_UNICODE(zeroes=True)’
              
              
‘'w*'’        ‘Py_buffer(accept={rwbuffer})’
              
              
‘'Y'’         ‘PyByteArrayObject’
              
              
‘'y'’         ‘str(accept={bytes})’
              
              
‘'y#'’        ‘str(accept={robuffer}, zeroes=True)’
              
              
‘'y*'’        ‘Py_buffer’
              
              
‘'Z'’         ‘Py_UNICODE(accept={str, NoneType})’
              
              
‘'Z#'’        ‘Py_UNICODE(accept={str, NoneType}, zeroes=True)’
              
              
‘'z'’         ‘str(accept={str, NoneType})’
              
              
‘'z#'’        ‘str(accept={str, NoneType}, zeroes=True)’
              
              
‘'z*'’        ‘Py_buffer(accept={buffer, str, NoneType})’
              

As an example, here’s our sample ‘pickle.Pickler.dump’ using the proper
converter:

     /*[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]*/

One advantage of real converters is that they’re more flexible than
legacy converters.  For example, the ‘unsigned_int’ converter (and all
the ‘unsigned_’ converters) can be specified without ‘bitwise=True’.
Their default behavior performs range checking on the value, and they
won’t accept negative numbers.  You just can’t do that with a legacy
converter!

Argument Clinic will show you all the converters it has available.  For
each converter it’ll show you all the parameters it accepts, along with
the default value for each parameter.  Just run ‘Tools/clinic/clinic.py
--converters’ to see the full list.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0008


File: python.info,  Node: Py_buffer,  Next: Advanced converters,  Prev: Using real Argument Clinic converters instead of "legacy converters",  Up: Advanced Topics

10.15.4.6 Py_buffer
...................

When using the ‘Py_buffer’ converter (or the ‘'s*'’, ‘'w*'’, ‘'*y'’, or
‘'z*'’ legacy converters), you `must' not call *note PyBuffer_Release():
e19. on the provided buffer.  Argument Clinic generates code that does
it for you (in the parsing function).


File: python.info,  Node: Advanced converters,  Next: Parameter default values,  Prev: Py_buffer,  Up: Advanced Topics

10.15.4.7 Advanced converters
.............................

Remember those format units you skipped for your first time because they
were advanced?  Here’s how to handle those too.

The trick is, all those format units take arguments—either conversion
functions, or types, or strings specifying an encoding.  (But "legacy
converters" don’t support arguments.  That’s why we skipped them for
your first function.)  The argument you specified to the format unit is
now an argument to the converter; this argument is either ‘converter’
(for ‘O&’), ‘subclass_of’ (for ‘O!’), or ‘encoding’ (for all the format
units that start with ‘e’).

When using ‘subclass_of’, you may also want to use the other custom
argument for ‘object()’: ‘type’, which lets you set the type actually
used for the parameter.  For example, if you want to ensure that the
object is a subclass of ‘PyUnicode_Type’, you probably want to use the
converter ‘object(type='PyUnicodeObject *',
subclass_of='&PyUnicode_Type')’.

One possible problem with using Argument Clinic: it takes away some
possible flexibility for the format units starting with ‘e’.  When
writing a ‘PyArg_Parse’ call by hand, you could theoretically decide at
runtime what encoding string to pass in to *note PyArg_ParseTuple():
393.  But now this string must be hard-coded at
Argument-Clinic-preprocessing-time.  This limitation is deliberate; it
made supporting this format unit much easier, and may allow for future
optimizations.  This restriction doesn’t seem unreasonable; CPython
itself always passes in static hard-coded encoding strings for
parameters whose format units start with ‘e’.


File: python.info,  Node: Parameter default values,  Next: The NULL default value,  Prev: Advanced converters,  Up: Advanced Topics

10.15.4.8 Parameter default values
..................................

Default values for parameters can be any of a number of values.  At
their simplest, they can be string, int, or float literals:

     foo: str = "abc"
     bar: int = 123
     bat: float = 45.6

They can also use any of Python’s built-in constants:

     yep:  bool = True
     nope: bool = False
     nada: object = None

There’s also special support for a default value of ‘NULL’, and for
simple expressions, documented in the following sections.


File: python.info,  Node: The NULL default value,  Next: Expressions specified as default values,  Prev: Parameter default values,  Up: Advanced Topics

10.15.4.9 The ‘NULL’ default value
..................................

For string and object parameters, you can set them to ‘None’ to indicate
that there’s no default.  However, that means the C variable will be
initialized to ‘Py_None’.  For convenience’s sakes, there’s a special
value called ‘NULL’ for just this reason: from Python’s perspective it
behaves like a default value of ‘None’, but the C variable is
initialized with ‘NULL’.


File: python.info,  Node: Expressions specified as default values,  Next: Using a return converter,  Prev: The NULL default value,  Up: Advanced Topics

10.15.4.10 Expressions specified as default values
..................................................

The default value for a parameter can be more than just a literal value.
It can be an entire expression, using math operators and looking up
attributes on objects.  However, this support isn’t exactly simple,
because of some non-obvious semantics.

Consider the following example:

     foo: Py_ssize_t = sys.maxsize - 1

‘sys.maxsize’ can have different values on different platforms.
Therefore Argument Clinic can’t simply evaluate that expression locally
and hard-code it in C. So it stores the default in such a way that it
will get evaluated at runtime, when the user asks for the function’s
signature.

What namespace is available when the expression is evaluated?  It’s
evaluated in the context of the module the builtin came from.  So, if
your module has an attribute called "‘max_widgets’", you may simply use
it:

     foo: Py_ssize_t = max_widgets

If the symbol isn’t found in the current module, it fails over to
looking in ‘sys.modules’.  That’s how it can find ‘sys.maxsize’ for
example.  (Since you don’t know in advance what modules the user will
load into their interpreter, it’s best to restrict yourself to modules
that are preloaded by Python itself.)

Evaluating default values only at runtime means Argument Clinic can’t
compute the correct equivalent C default value.  So you need to tell it
explicitly.  When you use an expression, you must also specify the
equivalent expression in C, using the ‘c_default’ parameter to the
converter:

     foo: Py_ssize_t(c_default="PY_SSIZE_T_MAX - 1") = sys.maxsize - 1

Another complication: Argument Clinic can’t know in advance whether or
not the expression you supply is valid.  It parses it to make sure it
looks legal, but it can’t `actually' know.  You must be very careful
when using expressions to specify values that are guaranteed to be valid
at runtime!

Finally, because expressions must be representable as static C values,
there are many restrictions on legal expressions.  Here’s a list of
Python features you’re not permitted to use:

   * Function calls.

   * Inline if statements (‘3 if foo else 5’).

   * Automatic sequence unpacking (‘*[1, 2, 3]’).

   * List/set/dict comprehensions and generator expressions.

   * Tuple/list/set/dict literals.


File: python.info,  Node: Using a return converter,  Next: Cloning existing functions,  Prev: Expressions specified as default values,  Up: Advanced Topics

10.15.4.11 Using a return converter
...................................

By default the impl function Argument Clinic generates for you returns
‘PyObject *’.  But your C function often computes some C type, then
converts it into the ‘PyObject *’ at the last moment.  Argument Clinic
handles converting your inputs from Python types into native C types—why
not have it convert your return value from a native C type into a Python
type too?

That’s what a "return converter" does.  It changes your impl function to
return some C type, then adds code to the generated (non-impl) function
to handle converting that value into the appropriate ‘PyObject *’.

The syntax for return converters is similar to that of parameter
converters.  You specify the return converter like it was a return
annotation on the function itself.  Return converters behave much the
same as parameter converters; they take arguments, the arguments are all
keyword-only, and if you’re not changing any of the default arguments
you can omit the parentheses.

(If you use both ‘"as"’ `and' a return converter for your function, the
‘"as"’ should come before the return converter.)

There’s one additional complication when using return converters: how do
you indicate an error has occurred?  Normally, a function returns a
valid (non-‘NULL’) pointer for success, and ‘NULL’ for failure.  But if
you use an integer return converter, all integers are valid.  How can
Argument Clinic detect an error?  Its solution: each return converter
implicitly looks for a special value that indicates an error.  If you
return that value, and an error has been set (‘PyErr_Occurred()’ returns
a true value), then the generated code will propagate the error.
Otherwise it will encode the value you return like normal.

Currently Argument Clinic supports only a few return converters:

     bool
     int
     unsigned int
     long
     unsigned int
     size_t
     Py_ssize_t
     float
     double
     DecodeFSDefault

None of these take parameters.  For the first three, return -1 to
indicate error.  For ‘DecodeFSDefault’, the return type is ‘const char
*’; return a ‘NULL’ pointer to indicate an error.

(There’s also an experimental ‘NoneType’ converter, which lets you
return ‘Py_None’ on success or ‘NULL’ on failure, without having to
increment the reference count on ‘Py_None’.  I’m not sure it adds enough
clarity to be worth using.)

To see all the return converters Argument Clinic supports, along with
their parameters (if any), just run ‘Tools/clinic/clinic.py
--converters’ for the full list.


File: python.info,  Node: Cloning existing functions,  Next: Calling Python code,  Prev: Using a return converter,  Up: Advanced Topics

10.15.4.12 Cloning existing functions
.....................................

If you have a number of functions that look similar, you may be able to
use Clinic’s "clone" feature.  When you clone an existing function, you
reuse:

   * its parameters, including

        * their names,

        * their converters, with all parameters,

        * their default values,

        * their per-parameter docstrings,

        * their `kind' (whether they’re positional only, positional or
          keyword, or keyword only), and

   * its return converter.

The only thing not copied from the original function is its docstring;
the syntax allows you to specify a new docstring.

Here’s the syntax for cloning a function:

     /*[clinic input]
     module.class.new_function [as c_basename] = module.class.existing_function

     Docstring for new_function goes here.
     [clinic start generated code]*/

(The functions can be in different modules or classes.  I wrote
‘module.class’ in the sample just to illustrate that you must use the
full path to `both' functions.)

Sorry, there’s no syntax for partially-cloning a function, or cloning a
function then modifying it.  Cloning is an all-or nothing proposition.

Also, the function you are cloning from must have been previously
defined in the current file.


File: python.info,  Node: Calling Python code,  Next: Using a "self converter",  Prev: Cloning existing functions,  Up: Advanced Topics

10.15.4.13 Calling Python code
..............................

The rest of the advanced topics require you to write Python code which
lives inside your C file and modifies Argument Clinic’s runtime state.
This is simple: you simply define a Python block.

A Python block uses different delimiter lines than an Argument Clinic
function block.  It looks like this:

     /*[python input]
     # python code goes here
     [python start generated code]*/

All the code inside the Python block is executed at the time it’s
parsed.  All text written to stdout inside the block is redirected into
the "output" after the block.

As an example, here’s a Python block that adds a static integer variable
to the C code:

     /*[python input]
     print('static int __ignored_unused_variable__ = 0;')
     [python start generated code]*/
     static int __ignored_unused_variable__ = 0;
     /*[python checksum:...]*/


File: python.info,  Node: Using a "self converter",  Next: Writing a custom converter,  Prev: Calling Python code,  Up: Advanced Topics

10.15.4.14 Using a "self converter"
...................................

Argument Clinic automatically adds a "self" parameter for you using a
default converter.  It automatically sets the ‘type’ of this parameter
to the "pointer to an instance" you specified when you declared the
type.  However, you can override Argument Clinic’s converter and specify
one yourself.  Just add your own ‘self’ parameter as the first parameter
in a block, and ensure that its converter is an instance of
‘self_converter’ or a subclass thereof.

What’s the point?  This lets you override the type of ‘self’, or give it
a different default name.

How do you specify the custom type you want to cast ‘self’ to?  If you
only have one or two functions with the same type for ‘self’, you can
directly use Argument Clinic’s existing ‘self’ converter, passing in the
type you want to use as the ‘type’ parameter:

     /*[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]*/

On the other hand, if you have a lot of functions that will use the same
type for ‘self’, it’s best to create your own converter, subclassing
‘self_converter’ but overwriting the ‘type’ member:

     /*[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]*/


File: python.info,  Node: Writing a custom converter,  Next: Writing a custom return converter,  Prev: Using a "self converter",  Up: Advanced Topics

10.15.4.15 Writing a custom converter
.....................................

As we hinted at in the previous section...  you can write your own
converters!  A converter is simply a Python class that inherits from
‘CConverter’.  The main purpose of a custom converter is if you have a
parameter using the ‘O&’ format unit—parsing this parameter means
calling a *note PyArg_ParseTuple(): 393. "converter function".

Your converter class should be named ‘*something*_converter’.  If the
name follows this convention, then your converter class will be
automatically registered with Argument Clinic; its name will be the name
of your class with the ‘_converter’ suffix stripped off.  (This is
accomplished with a metaclass.)

You shouldn’t subclass ‘CConverter.__init__’.  Instead, you should write
a ‘converter_init()’ function.  ‘converter_init()’ always accepts a
‘self’ parameter; after that, all additional parameters `must' be
keyword-only.  Any arguments passed in to the converter in Argument
Clinic will be passed along to your ‘converter_init()’.

There are some additional members of ‘CConverter’ you may wish to
specify in your subclass.  Here’s the current list:

‘type’

     The C type to use for this variable.  ‘type’ should be a Python
     string specifying the type, e.g.  ‘int’.  If this is a pointer
     type, the type string should end with ‘' *'’.

‘default’

     The Python default value for this parameter, as a Python value.  Or
     the magic value ‘unspecified’ if there is no default.

‘py_default’

     ‘default’ as it should appear in Python code, as a string.  Or
     ‘None’ if there is no default.

‘c_default’

     ‘default’ as it should appear in C code, as a string.  Or ‘None’ if
     there is no default.

‘c_ignored_default’

     The default value used to initialize the C variable when there is
     no default, but not specifying a default may result in an
     "uninitialized variable" warning.  This can easily happen when
     using option groups—although properly-written code will never
     actually use this value, the variable does get passed in to the
     impl, and the C compiler will complain about the "use" of the
     uninitialized value.  This value should always be a non-empty
     string.

‘converter’

     The name of the C converter function, as a string.

‘impl_by_reference’

     A boolean value.  If true, Argument Clinic will add a ‘&’ in front
     of the name of the variable when passing it into the impl function.

‘parse_by_reference’

     A boolean value.  If true, Argument Clinic will add a ‘&’ in front
     of the name of the variable when passing it into *note
     PyArg_ParseTuple(): 393.

Here’s the simplest example of a custom converter, from
‘Modules/zlibmodule.c’:

     /*[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]*/

This block adds a converter to Argument Clinic named ‘ssize_t’.
Parameters declared as ‘ssize_t’ will be declared as type ‘Py_ssize_t’,
and will be parsed by the ‘'O&'’ format unit, which will call the
‘ssize_t_converter’ converter function.  ‘ssize_t’ variables
automatically support default values.

More sophisticated custom converters can insert custom C code to handle
initialization and cleanup.  You can see more examples of custom
converters in the CPython source tree; grep the C files for the string
‘CConverter’.


File: python.info,  Node: Writing a custom return converter,  Next: METH_O and METH_NOARGS,  Prev: Writing a custom converter,  Up: Advanced Topics

10.15.4.16 Writing a custom return converter
............................................

Writing a custom return converter is much like writing a custom
converter.  Except it’s somewhat simpler, because return converters are
themselves much simpler.

Return converters must subclass ‘CReturnConverter’.  There are no
examples yet of custom return converters, because they are not widely
used yet.  If you wish to write your own return converter, please read
‘Tools/clinic/clinic.py’, specifically the implementation of
‘CReturnConverter’ and all its subclasses.


File: python.info,  Node: METH_O and METH_NOARGS,  Next: tp_new and tp_init functions,  Prev: Writing a custom return converter,  Up: Advanced Topics

10.15.4.17 METH_O and METH_NOARGS
.................................

To convert a function using ‘METH_O’, make sure the function’s single
argument is using the ‘object’ converter, and mark the arguments as
positional-only:

     /*[clinic input]
     meth_o_sample

          argument: object
          /
     [clinic start generated code]*/

To convert a function using ‘METH_NOARGS’, just don’t specify any
arguments.

You can still use a self converter, a return converter, and specify a
‘type’ argument to the object converter for ‘METH_O’.


File: python.info,  Node: tp_new and tp_init functions,  Next: Changing and redirecting Clinic's output,  Prev: METH_O and METH_NOARGS,  Up: Advanced Topics

10.15.4.18 tp_new and tp_init functions
.......................................

You can convert ‘tp_new’ and ‘tp_init’ functions.  Just name them
‘__new__’ or ‘__init__’ as appropriate.  Notes:

   * The function name generated for ‘__new__’ doesn’t end in ‘__new__’
     like it would by default.  It’s just the name of the class,
     converted into a valid C identifier.

   * No ‘PyMethodDef’ ‘#define’ is generated for these functions.

   * ‘__init__’ functions return ‘int’, not ‘PyObject *’.

   * Use the docstring as the class docstring.

   * Although ‘__new__’ and ‘__init__’ functions must always accept both
     the ‘args’ and ‘kwargs’ objects, when converting you may specify
     any signature for these functions that you like.  (If your function
     doesn’t support keywords, the parsing function generated will throw
     an exception if it receives any.)


File: python.info,  Node: Changing and redirecting Clinic's output,  Next: The #ifdef trick,  Prev: tp_new and tp_init functions,  Up: Advanced Topics

10.15.4.19 Changing and redirecting Clinic’s output
...................................................

It can be inconvenient to have Clinic’s output interspersed with your
conventional hand-edited C code.  Luckily, Clinic is configurable: you
can buffer up its output for printing later (or earlier!), or write its
output to a separate file.  You can also add a prefix or suffix to every
line of Clinic’s generated output.

While changing Clinic’s output in this manner can be a boon to
readability, it may result in Clinic code using types before they are
defined, or your code attempting to use Clinic-generated code before it
is defined.  These problems can be easily solved by rearranging the
declarations in your file, or moving where Clinic’s generated code goes.
(This is why the default behavior of Clinic is to output everything into
the current block; while many people consider this hampers readability,
it will never require rearranging your code to fix definition-before-use
problems.)

Let’s start with defining some terminology:

`field'

     A field, in this context, is a subsection of Clinic’s output.  For
     example, the ‘#define’ for the ‘PyMethodDef’ structure is a field,
     called ‘methoddef_define’.  Clinic has seven different fields it
     can output per function definition:

          docstring_prototype
          docstring_definition
          methoddef_define
          impl_prototype
          parser_prototype
          parser_definition
          impl_definition

     All the names are of the form ‘"<a>_<b>"’, where ‘"<a>"’ is the
     semantic object represented (the parsing function, the impl
     function, the docstring, or the methoddef structure) and ‘"<b>"’
     represents what kind of statement the field is.  Field names that
     end in ‘"_prototype"’ represent forward declarations of that thing,
     without the actual body/data of the thing; field names that end in
     ‘"_definition"’ represent the actual definition of the thing, with
     the body/data of the thing.  (‘"methoddef"’ is special, it’s the
     only one that ends with ‘"_define"’, representing that it’s a
     preprocessor #define.)

`destination'

     A destination is a place Clinic can write output to.  There are
     five built-in destinations:

     ‘block’

          The default destination: printed in the output section of the
          current Clinic block.

     ‘buffer’

          A text buffer where you can save text for later.  Text sent
          here is appended to the end of any existing text.  It’s an
          error to have any text left in the buffer when Clinic finishes
          processing a file.

     ‘file’

          A separate "clinic file" that will be created automatically by
          Clinic.  The filename chosen for the file is
          ‘{basename}.clinic{extension}’, where ‘basename’ and
          ‘extension’ were assigned the output from ‘os.path.splitext()’
          run on the current file.  (Example: the ‘file’ destination for
          ‘_pickle.c’ would be written to ‘_pickle.clinic.c’.)

          `Important: When using a' ‘file’ `destination, you' `must
          check in' `the generated file!'

     ‘two-pass’

          A buffer like ‘buffer’.  However, a two-pass buffer can only
          be dumped once, and it prints out all text sent to it during
          all processing, even from Clinic blocks `after' the dumping
          point.

     ‘suppress’

          The text is suppressed—thrown away.

Clinic defines five new directives that let you reconfigure its output.

The first new directive is ‘dump’:

     dump <destination>

This dumps the current contents of the named destination into the output
of the current block, and empties it.  This only works with ‘buffer’ and
‘two-pass’ destinations.

The second new directive is ‘output’.  The most basic form of ‘output’
is like this:

     output <field> <destination>

This tells Clinic to output `field' to `destination'.  ‘output’ also
supports a special meta-destination, called ‘everything’, which tells
Clinic to output `all' fields to that `destination'.

‘output’ has a number of other functions:

     output push
     output pop
     output preset <preset>

‘output push’ and ‘output pop’ allow you to push and pop configurations
on an internal configuration stack, so that you can temporarily modify
the output configuration, then easily restore the previous
configuration.  Simply push before your change to save the current
configuration, then pop when you wish to restore the previous
configuration.

‘output preset’ sets Clinic’s output to one of several built-in preset
configurations, as follows:

     ‘block’

          Clinic’s original starting configuration.  Writes everything
          immediately after the input block.

          Suppress the ‘parser_prototype’ and ‘docstring_prototype’,
          write everything else to ‘block’.

     ‘file’

          Designed to write everything to the "clinic file" that it can.
          You then ‘#include’ this file near the top of your file.  You
          may need to rearrange your file to make this work, though
          usually this just means creating forward declarations for
          various ‘typedef’ and ‘PyTypeObject’ definitions.

          Suppress the ‘parser_prototype’ and ‘docstring_prototype’,
          write the ‘impl_definition’ to ‘block’, and write everything
          else to ‘file’.

          The default filename is ‘"{dirname}/clinic/{basename}.h"’.

     ‘buffer’

          Save up most of the output from Clinic, to be written into
          your file near the end.  For Python files implementing modules
          or builtin types, it’s recommended that you dump the buffer
          just above the static structures for your module or builtin
          type; these are normally very near the end.  Using ‘buffer’
          may require even more editing than ‘file’, if your file has
          static ‘PyMethodDef’ arrays defined in the middle of the file.

          Suppress the ‘parser_prototype’, ‘impl_prototype’, and
          ‘docstring_prototype’, write the ‘impl_definition’ to ‘block’,
          and write everything else to ‘file’.

     ‘two-pass’

          Similar to the ‘buffer’ preset, but writes forward
          declarations to the ‘two-pass’ buffer, and definitions to the
          ‘buffer’.  This is similar to the ‘buffer’ preset, but may
          require less editing than ‘buffer’.  Dump the ‘two-pass’
          buffer near the top of your file, and dump the ‘buffer’ near
          the end just like you would when using the ‘buffer’ preset.

          Suppresses the ‘impl_prototype’, write the ‘impl_definition’
          to ‘block’, write ‘docstring_prototype’, ‘methoddef_define’,
          and ‘parser_prototype’ to ‘two-pass’, write everything else to
          ‘buffer’.

     ‘partial-buffer’

          Similar to the ‘buffer’ preset, but writes more things to
          ‘block’, only writing the really big chunks of generated code
          to ‘buffer’.  This avoids the definition-before-use problem of
          ‘buffer’ completely, at the small cost of having slightly more
          stuff in the block’s output.  Dump the ‘buffer’ near the end,
          just like you would when using the ‘buffer’ preset.

          Suppresses the ‘impl_prototype’, write the
          ‘docstring_definition’ and ‘parser_definition’ to ‘buffer’,
          write everything else to ‘block’.

The third new directive is ‘destination’:

     destination <name> <command> [...]

This performs an operation on the destination named ‘name’.

There are two defined subcommands: ‘new’ and ‘clear’.

The ‘new’ subcommand works like this:

     destination <name> new <type>

This creates a new destination with name ‘<name>’ and type ‘<type>’.

There are five destination types:

     ‘suppress’

          Throws the text away.

     ‘block’

          Writes the text to the current block.  This is what Clinic
          originally did.

     ‘buffer’

          A simple text buffer, like the "buffer" builtin destination
          above.

     ‘file’

          A text file.  The file destination takes an extra argument, a
          template to use for building the filename, like so:

               destination <name> new <type> <file_template>

          The template can use three strings internally that will be
          replaced by bits of the filename:

               {path}

                    The full path to the file, including directory and
                    full filename.

               {dirname}

                    The name of the directory the file is in.

               {basename}

                    Just the name of the file, not including the
                    directory.

               {basename_root}

                    Basename with the extension clipped off (everything
                    up to but not including the last ’.’).

               {basename_extension}

                    The last ’.’ and everything after it.  If the
                    basename does not contain a period, this will be the
                    empty string.

          If there are no periods in the filename, {basename} and
          {filename} are the same, and {extension} is empty.
          "{basename}{extension}" is always exactly the same as
          "{filename}"."

     ‘two-pass’

          A two-pass buffer, like the "two-pass" builtin destination
          above.

The ‘clear’ subcommand works like this:

     destination <name> clear

It removes all the accumulated text up to this point in the destination.
(I don’t know what you’d need this for, but I thought maybe it’d be
useful while someone’s experimenting.)

The fourth new directive is ‘set’:

     set line_prefix "string"
     set line_suffix "string"

‘set’ lets you set two internal variables in Clinic.  ‘line_prefix’ is a
string that will be prepended to every line of Clinic’s output;
‘line_suffix’ is a string that will be appended to every line of
Clinic’s output.

Both of these support two format strings:

     ‘{block comment start}’

          Turns into the string ‘/*’, the start-comment text sequence
          for C files.

     ‘{block comment end}’

          Turns into the string ‘*/’, the end-comment text sequence for
          C files.

The final new directive is one you shouldn’t need to use directly,
called ‘preserve’:

     preserve

This tells Clinic that the current contents of the output should be
kept, unmodified.  This is used internally by Clinic when dumping output
into ‘file’ files; wrapping it in a Clinic block lets Clinic use its
existing checksum functionality to ensure the file was not modified by
hand before it gets overwritten.


File: python.info,  Node: The #ifdef trick,  Next: Using Argument Clinic in Python files,  Prev: Changing and redirecting Clinic's output,  Up: Advanced Topics

10.15.4.20 The #ifdef trick
...........................

If you’re converting a function that isn’t available on all platforms,
there’s a trick you can use to make life a little easier.  The existing
code probably looks like this:

     #ifdef HAVE_FUNCTIONNAME
     static module_functionname(...)
     {
     ...
     }
     #endif /* HAVE_FUNCTIONNAME */

And then in the ‘PyMethodDef’ structure at the bottom the existing code
will have:

     #ifdef HAVE_FUNCTIONNAME
     {'functionname', ... },
     #endif /* HAVE_FUNCTIONNAME */

In this scenario, you should enclose the body of your impl function
inside the ‘#ifdef’, like so:

     #ifdef HAVE_FUNCTIONNAME
     /*[clinic input]
     module.functionname
     ...
     [clinic start generated code]*/
     static module_functionname(...)
     {
     ...
     }
     #endif /* HAVE_FUNCTIONNAME */

Then, remove those three lines from the ‘PyMethodDef’ structure,
replacing them with the macro Argument Clinic generated:

     MODULE_FUNCTIONNAME_METHODDEF

(You can find the real name for this macro inside the generated code.
Or you can calculate it yourself: it’s the name of your function as
defined on the first line of your block, but with periods changed to
underscores, uppercased, and ‘"_METHODDEF"’ added to the end.)

Perhaps you’re wondering: what if ‘HAVE_FUNCTIONNAME’ isn’t defined?
The ‘MODULE_FUNCTIONNAME_METHODDEF’ macro won’t be defined either!

Here’s where Argument Clinic gets very clever.  It actually detects that
the Argument Clinic block might be deactivated by the ‘#ifdef’.  When
that happens, it generates a little extra code that looks like this:

     #ifndef MODULE_FUNCTIONNAME_METHODDEF
         #define MODULE_FUNCTIONNAME_METHODDEF
     #endif /* !defined(MODULE_FUNCTIONNAME_METHODDEF) */

That means the macro always works.  If the function is defined, this
turns into the correct structure, including the trailing comma.  If the
function is undefined, this turns into nothing.

However, this causes one ticklish problem: where should Argument Clinic
put this extra code when using the "block" output preset?  It can’t go
in the output block, because that could be deactivated by the ‘#ifdef’.
(That’s the whole point!)

In this situation, Argument Clinic writes the extra code to the "buffer"
destination.  This may mean that you get a complaint from Argument
Clinic:

     Warning in file "Modules/posixmodule.c" on line 12357:
     Destination buffer 'buffer' not empty at end of file, emptying.

When this happens, just open your file, find the ‘dump buffer’ block
that Argument Clinic added to your file (it’ll be at the very bottom),
then move it above the ‘PyMethodDef’ structure where that macro is used.


File: python.info,  Node: Using Argument Clinic in Python files,  Prev: The #ifdef trick,  Up: Advanced Topics

10.15.4.21 Using Argument Clinic in Python files
................................................

It’s actually possible to use Argument Clinic to preprocess Python
files.  There’s no point to using Argument Clinic blocks, of course, as
the output wouldn’t make any sense to the Python interpreter.  But using
Argument Clinic to run Python blocks lets you use Python as a Python
preprocessor!

Since Python comments are different from C comments, Argument Clinic
blocks embedded in Python files look slightly different.  They look like
this:

     #/*[python input]
     #print("def foo(): pass")
     #[python start generated code]*/
     def foo(): pass
     #/*[python checksum:...]*/


File: python.info,  Node: 使用 DTrace 和 SystemTap 检测CPython,  Prev: Argument Clinic How-To,  Up: Python 如何達成任務

10.16 使用 DTrace 和 SystemTap 检测CPython
==========================================


作者: David Malcolm


作者: Łukasz Langa

DTrace和SystemTap是监控工具，它们都提供了一种检查计算机系统上的进程的方
法。 它们都使用特定领域的语言，允许用户编写脚本，其中：

        - 进程监视的过滤器

        - 从感兴趣的进程中收集数据

        - 生成有关数据的报告

从Python 3.6开始，CPython可以使用嵌入式“标记”构建，也称为“探测器”，可以
通过DTrace或SystemTap脚本观察，从而更容易监视系统上的CPython进程正在做什
么。

`CPython implementation detail:' DTrace标记是CPython解释器的实现细节。 不
保证CPython版本之间的探针兼容性。 更改CPython版本时，DTrace脚本可能会停
止工作或无法正常工作而不会发出警告。

* Menu:

* 启用静态标记::
* 静态DTrace探针::
* 静态SystemTap标记::
* 可用的静态标记::
* SystemTap Tapsets::
* 示例: 示例<52>.


File: python.info,  Node: 启用静态标记,  Next: 静态DTrace探针,  Up: 使用 DTrace 和 SystemTap 检测CPython

10.16.1 启用静态标记
--------------------

macOS内置了对DTrace的支持。 在Linux上，为了使用SystemTap的嵌入式标记构建
CPython，必须安装SystemTap开发工具。

在Linux机器上，这可以通过：

     $ yum install systemtap-sdt-devel

或者：

     $ sudo apt-get install systemtap-sdt-dev

然后必须将CPython配置为‘‘–with-dtrace‘‘：

     checking for --with-dtrace... yes

在macOS上，您可以通过在后台运行Python进程列出可用的DTrace探测器，并列出
Python程序提供的所有探测器：

     $ 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

在Linux上，您可以通过查看是否包含“.note.stapsdt”部分来验证构建的二进制文
件中是否存在SystemTap静态标记。

     $ readelf -S ./python | grep .note.stapsdt
     [30] .note.stapsdt        NOTE         0000000000000000 00308d78

如果您已将Python构建为共享库（使用–enable-shared），则需要在共享库中查找
。 例如：

     $ readelf -S libpython3.3dm.so.1.0 | grep .note.stapsdt
     [29] .note.stapsdt        NOTE         0000000000000000 00365b68

足够现代的readelf命令可以打印元数据：

     $ 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

上述元数据包含SystemTap的信息，描述如何修补策略性放置的机器代码指令以启
用SystemTap脚本使用的跟踪钩子。


File: python.info,  Node: 静态DTrace探针,  Next: 静态SystemTap标记,  Prev: 启用静态标记,  Up: 使用 DTrace 和 SystemTap 检测CPython

10.16.2 静态DTrace探针
----------------------

下面的 DTrace 脚本示例可以用来显示一个 Python 脚本的调用/返回层次结构，
只在调用名为 "start" 的函数内进行跟踪。换句话说，导入时的函数调用不会被
列出。

     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;
     }

它可以这样调用:

     $ sudo dtrace -q -s call_stack.d -c "python3.6 script.py"

输出结果会像这样:

     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


File: python.info,  Node: 静态SystemTap标记,  Next: 可用的静态标记,  Prev: 静态DTrace探针,  Up: 使用 DTrace 和 SystemTap 检测CPython

10.16.3 静态SystemTap标记
-------------------------

使用 SystemTap 集成的底层方法是直接使用静态标记。 这需要你显式地说明包含
它们的二进制文件。

例如，这个SystemTap脚本可以用来显示Python脚本的调用/返回层次结构：

     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);
     }

它可以这样调用:

     $ stap \
       show-call-hierarchy.stp \
       -c "./python test.py"

输出结果会像这样:

     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

其中的列是：

        - 脚本开始后经过的微秒数

        - 可执行文件的名字

        - 进程的PID

其余部分则表示脚本执行时的调用/返回层次结构。

对于 ‘–enable-shared’ 构建的CPython来说，这些标记是包含在libpython共享库
中的，探针的点状路径需要反映这一点。比如上面例子中的这一行：

     probe process("python").mark("function__entry") {

应改为：

     probe process("python").library("libpython3.6dm.so.1.0").mark("function__entry") {

（假设是 CPython 3.6 的调试构建）


File: python.info,  Node: 可用的静态标记,  Next: SystemTap Tapsets,  Prev: 静态SystemTap标记,  Up: 使用 DTrace 和 SystemTap 检测CPython

10.16.4 可用的静态标记
----------------------

 -- Object: function__entry(str filename, str funcname, int lineno)

     这个标记表示一个Python函数的执行已经开始。它只对纯 Python （字节码
     ）函数触发。

     文件名、函数名和行号作为位置参数提供给跟踪脚本，必须使用 ‘$arg1’,
     ‘$arg2’, ‘$arg3’ 访问：

             * ‘$arg1’ : ‘(const char *)’ 文件名，使用
               ‘user_string($arg1)’ 访问

             * ‘$arg2’ : ‘(const char *)’ 函数名，使用
               ‘user_string($arg2)’ 访问

             * ‘$arg3’ : ‘int’ 行号

 -- Object: function__return(str filename, str funcname, int lineno)

     这个标记与 ‘function__entry()’ 相反，表示Python函数的执行已经结束
     (通过 ‘return’ 或者异常)。 它只对纯Python (字节码) 函数触发。

     参数和 ‘function__entry()’ 相同

 -- Object: line(str filename, str funcname, int lineno)

     这个标记表示一个 Python 行即将被执行。它相当于用 Python 分析器逐行
     追踪。它不会在C函数中触发。

     参数和 ‘function__entry()’ 相同

 -- Object: gc__start(int generation)

     当Python解释器启动一个垃圾回收循环时被触发。 ‘arg0’ 是要扫描的生成
     器，如 *note gc.collect(): 35b.。

 -- Object: gc__done(long collected)

     当Python解释器完成一个垃圾回收循环时被触发。‘arg0’ 是收集到的对象的
     数量。

 -- Object: import__find__load__start(str modulename)

     在 *note importlib: 9a. 试图查找并加载模块之前被触发。‘arg0’ 是模块
     名称。

     3.7 版新加入.

 -- Object: import__find__load__done(str modulename, int found)

     在 *note importlib: 9a. 的 find_and_load 函数被调用后被触发。
     ‘arg0’ 是模块名称， ‘arg1’ 表示模块是否成功加载。

     3.7 版新加入.

 -- Object: audit(str event, void *tuple)

     当 *note sys.audit(): 1056. 或 *note PySys_Audit(): 1068. 被调用时
     启动。 ‘arg0’ 是事件名称的 C 字符串，‘arg1’ 是一个指向元组对象的
     *note PyObject: 5b4. 指针。

     3.8 版新加入.


File: python.info,  Node: SystemTap Tapsets,  Next: 示例<52>,  Prev: 可用的静态标记,  Up: 使用 DTrace 和 SystemTap 检测CPython

10.16.5 SystemTap Tapsets
-------------------------

使用SystemTap集成的更高层次的方法是使用 "tapset" 。SystemTap 的等效库，
它隐藏了静态标记的一些底层细节。

这里是一个基于 CPython 的非共享构建的 tapset 文件。

     /*
        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
     }

如果这个文件安装在 SystemTap 的 tapset 目录下（例如
‘‘/usr/share/systemtap/tapset‘‘ ），那么这些额外的探测点就会变得可用。

 -- Object: python.function.entry(str filename, str funcname, int
          lineno, frameptr)

     这个探针点表示一个Python函数的执行已经开始。它只对纯Python （字节码
     ）函数触发。

 -- Object: python.function.return(str filename, str funcname, int
          lineno, frameptr)

     这个探针点是 ‘python.function.return’ 的反义操作，表示一个 Python 函
     数的执行已经结束（或是通过 ‘return’，或是通过异常）。 它只会针对纯
     Python（字节码）函数触发。


File: python.info,  Node: 示例<52>,  Prev: SystemTap Tapsets,  Up: 使用 DTrace 和 SystemTap 检测CPython

10.16.6 示例
------------

这个SystemTap脚本使用上面的tapset来更清晰地实现上面给出的跟踪Python函数
调用层次结构的例子，而不需要直接命名静态标记。

     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);
     }

下面的脚本使用上面的tapset提供了所有运行中的CPython代码的顶部视图，显示
了整个系统中每一秒钟最频繁输入的前20个字节码帧。

     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;
     }


File: python.info,  Node: Python 常見問題,  Next: 術語表,  Prev: Python 如何達成任務,  Up: Top

11 Python 常見問題
******************

* Menu:

* 常見Python問答集::
* 程式開發常見問答集::
* 设计和历史常见问题::
* 函式庫和擴充功能的常見問題::
* 扩展/嵌入常见问题::
* FAQ：在 Windows 使用 Python::
* 圖形化使用者界面常見問答集::
* 為什麼Python被安裝在我的機器上?常見問答集::


File: python.info,  Node: 常見Python問答集,  Next: 程式開發常見問答集,  Up: Python 常見問題

11.1 常見Python問答集
=====================

* Menu:

* 常見資訊::
* Python在真實世界::


File: python.info,  Node: 常見資訊,  Next: Python在真實世界,  Up: 常見Python問答集

11.1.1 常見資訊
---------------

* Menu:

* 什麼是Python?::
* 什麼是Python軟體基金會?::
* 當使用Python時有任何版權限制嗎?::
* 為什麼Python被創造出來::
* 什麼是Python擅長的事情::
* Python 版本的编号形式是怎样的？::
* 我如何拿到Python的原始碼::
* 如何取得Python的相關文件::
* 我從來沒寫過程式，有沒有Python的教學::
* 有沒有新手的群組或是郵件群組討論Python::
* 我应如何获取 Python 的公开测试版本？::
* 我应如何为 Python 提交错误报告和补丁？::
* 是否有任何公开发表的 Python 相关文章可以供我参考引用？::
* 有沒有關於Python的書::
* www.python.org 這個非營利組織位於哪裡: www python org 這個非營利組織位於哪裡.
* 為什麼要取名為Python::
* 我需要喜歡蒙提·派森的飛行馬戲團這個節目嗎::


File: python.info,  Node: 什麼是Python?,  Next: 什麼是Python軟體基金會?,  Up: 常見資訊

11.1.1.1 什麼是Python?
......................

Python 是一种解释型、交互式、面向对象的编程语言。 它包含了模块、异常、动
态类型、高层级动态数据类型以及类等特性。 在面向对象编程以外它还支持多种
编程范式，例如过程式和函数式编程等。 Python 结合了超强的功能和极清晰的语
法。 它带有许多系统调用和库以及多种窗口系统的接口，并且能用 C 或 C++ 来
进行扩展。 它还可用作需要可编程接口的应用程序的扩展语言。 最后，Python 非
常易于移植：它可以在包括 Linux 和 macOS 在内的许多 Unix 变种以及 Windows
上运行。

要了解更多详情，请先查看 *note Python 教學: 132f.。 Python 新手指南(1) 提
供了学习 Python 的其他入门教程及资源的链接。

   ---------- Footnotes ----------

   (1) https://wiki.python.org/moin/BeginnersGuide


File: python.info,  Node: 什麼是Python軟體基金會?,  Next: 當使用Python時有任何版權限制嗎?,  Prev: 什麼是Python?,  Up: 常見資訊

11.1.1.2 什麼是Python軟體基金會?
................................

Python軟體基金會是一個獨立非營利性組織，並且擁有Python版本2.1 與更新的版
本版權。Python軟體基金會的任務在於精進相關於Python 程式語言撰寫於開放原
始碼技術，而且宣傳使用Python 。Python軟體基金會網址
:‘https://www.python.org/psf/’

在美國捐款給Python軟體基金會是免稅的，如果你使用Python而且發現很好用，請
貢獻捐款到Python軟體基金會捐款頁面
<‘https://www.python.org/psf/donations/’>


File: python.info,  Node: 當使用Python時有任何版權限制嗎?,  Next: 為什麼Python被創造出來,  Prev: 什麼是Python軟體基金會?,  Up: 常見資訊

11.1.1.3 當使用Python時有任何版權限制嗎?
........................................

你可以任意使用源码，只要你保留版权信息并在你基于 Python 的产品文档中显示
该版权信息。 如果你遵守此版权规则，就可以将 Python 用于商业领域，以源码
或二进制码的形式（不论是否经过修改）销售 Python 的副本，或是以某种形式包
含了 Python 的产品。 当然，我们仍然希望获知所有对 Python 的商业使用。

請看Python軟體基金會的授權頁面<‘https://www.python.org/psf/license/’>有
更完整的授權說明

Python 的徽标是注册商标，在某些情况下需要获得允许方可使用。 请参阅 商标
使用政策(1) 了解详情。

   ---------- Footnotes ----------

   (1) https://www.python.org/psf/trademarks/


File: python.info,  Node: 為什麼Python被創造出來,  Next: 什麼是Python擅長的事情,  Prev: 當使用Python時有任何版權限制嗎?,  Up: 常見資訊

11.1.1.4 為什麼Python被創造出來
...............................

Guido van Rossum寫下這篇"非常長"的簡述說明Python的由來

     我在 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。 之后的
     事情就都可以在 ‘Misc/HISTORY’ 文件里面看了。


File: python.info,  Node: 什麼是Python擅長的事情,  Next: Python 版本的编号形式是怎样的？,  Prev: 為什麼Python被創造出來,  Up: 常見資訊

11.1.1.5 什麼是Python擅長的事情
...............................

Python是高階語言及一般任何用途都可以使用的語言，可以用來解決不同的問題

该语言附带一个庞大的标准库，涵盖了字符串处理（正则表达式，Unicode，比较
文件间的差异等），因特网协议（HTTP，FTP，SMTP，XML-RPC，POP，IMAP，CGI 编
程等），软件工程（单元测试，日志记录，性能分析，Python 代码解析等），以
及操作系统接口（系统调用，文件系统，TCP/IP 套接字等）。 请查看 *note
Python 標準函式庫 (Standard Library): 1330. 的目录以了解所有可用的内容。
此外还可以获取到各种各样的第三方扩展。 请访问 Python 包索引(1) 来查找你
感兴趣的软件包。

   ---------- Footnotes ----------

   (1) https://pypi.org


File: python.info,  Node: Python 版本的编号形式是怎样的？,  Next: 我如何拿到Python的原始碼,  Prev: 什麼是Python擅長的事情,  Up: 常見資訊

11.1.1.6 Python 版本的编号形式是怎样的？
........................................

Python 版本的编号形式是 A.B.C 或 A.B。 A 称为大版本号 —— 它仅在对语言特
性进行非常重大改变时才会递增。 B 称为小版本号，它会在语言特性发生较小改
变时递增。 C 称为微版本号 —— 它会在每次发布问题修正时递增。 请参阅 PEP
6(1) 了解有关问题修正发布版的详情。

发布版本并非都是问题修正版本。 在新的主要发布版本开发过程中，还会发布一
系列的开发版，它们以 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 的版本，而 `它们' 全都早于 2.0。

你还可能看到带有“+”后缀的版本号，例如“2.2+”。 这表示未发布版本，直接基于
CPython 开发代码仓库构建。 在实际操作中，当一个小版本最终发布后，未发布
版本号会递增到下一个小版本号，成为“a0”版本，例如“2.4a0”。

另请参阅 *note sys.version: 6ca, *note sys.hexversion: 37d8. 以及 *note
sys.version_info: bed. 的文档。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0006


File: python.info,  Node: 我如何拿到Python的原始碼,  Next: 如何取得Python的相關文件,  Prev: Python 版本的编号形式是怎样的？,  Up: 常見資訊

11.1.1.7 我如何拿到Python的原始碼
.................................

最新的 Python 发布版源代码总能从 python.org 获取，下载页链接为
‘https://www.python.org/downloads/’。 最新的开发版源代码可以在
‘https://github.com/python/cpython/’ 获取。

发布版源代码是一个以 gzip 压缩的 tar 文件，其中包含完整的 C 源代码、
Sphinx 格式的文档、Python 库模块、示例程序以及一些有用的自由分发软件。 该
源代码将可在大多数 UNIX 类平台上直接编译并运行。

请参阅 Python 开发者指南的初步上手部分(1) 了解有关获取源代码并进行编译的
更多信息。

   ---------- Footnotes ----------

   (1) https://devguide.python.org/setup/


File: python.info,  Node: 如何取得Python的相關文件,  Next: 我從來沒寫過程式，有沒有Python的教學,  Prev: 我如何拿到Python的原始碼,  Up: 常見資訊

11.1.1.8 如何取得Python的相關文件
.................................

当前的 Python 稳定版本的标准文档可在 ‘https://docs.python.org/3/’ 查看。
也可在 ‘https://docs.python.org/3/download.html’ 获取PDF、纯文本以及可下
载的 HTML 版本。

文档以 reStructuredText 格式撰写，并使用 Sphinx 文档工具(1) 生成。 文档
的 reStructuredText 源文件是 Python 源代码发布版的一部分。

   ---------- Footnotes ----------

   (1) http://sphinx-doc.org/


File: python.info,  Node: 我從來沒寫過程式，有沒有Python的教學,  Next: 有沒有新手的群組或是郵件群組討論Python,  Prev: 如何取得Python的相關文件,  Up: 常見資訊

11.1.1.9 我從來沒寫過程式，有沒有Python的教學
.............................................

有许多可选择的教程和书籍。 标准文档中也包含有 *note Python 教學: 132f.。

请参阅 新手指南(1) 以获取针对 Python 编程初学者的信息，包括教程的清单。

   ---------- Footnotes ----------

   (1) https://wiki.python.org/moin/BeginnersGuide


File: python.info,  Node: 有沒有新手的群組或是郵件群組討論Python,  Next: 我应如何获取 Python 的公开测试版本？,  Prev: 我從來沒寫過程式，有沒有Python的教學,  Up: 常見資訊

11.1.1.10 有沒有新手的群組或是郵件群組討論Python
................................................

有一个新闻组 ‘comp.lang.python’ 和一个邮件列表 python-list(1)。 新闻组和
邮件列表是彼此互通的 —— 如果你可以阅读新闻就不必再订阅邮件列表。
‘comp.lang.python’ 的流量很大，每天会收到数以百计的发帖，Usenet 使用者通
常更擅长处理这样大的流量。

有关新软件发布和活动的公告可以在 comp.lang.python.announce 中找到，这是
个严格管理的低流量列表，每天会收到五个左右的发帖。 可以在 Python 公告邮
件列表(2) 页面进行订阅。

有关其他邮件列表和新闻组的更多信息可以在
‘https://www.python.org/community/lists/’ 找到。

   ---------- Footnotes ----------

   (1) https://mail.python.org/mailman/listinfo/python-list

   (2) https://mail.python.org/mailman/listinfo/python-announce-list


File: python.info,  Node: 我应如何获取 Python 的公开测试版本？,  Next: 我应如何为 Python 提交错误报告和补丁？,  Prev: 有沒有新手的群組或是郵件群組討論Python,  Up: 常見資訊

11.1.1.11 我应如何获取 Python 的公开测试版本？
..............................................

可以从 ‘https://www.python.org/downloads/’ 下载 alpha 和 beta 发布版。 所
有发布版都会在 comp.lang.python 和 comp.lang.python.announce 新闻组以及
Python 主页 ‘https://www.python.org/’ 上进行公告；并会推送到 RSS 新闻源
。

你还可以通过 Git 访问 Python 的开发版。 请参阅 Python 开发者指南(1) 了解
详情。

   ---------- Footnotes ----------

   (1) https://devguide.python.org/


File: python.info,  Node: 我应如何为 Python 提交错误报告和补丁？,  Next: 是否有任何公开发表的 Python 相关文章可以供我参考引用？,  Prev: 我应如何获取 Python 的公开测试版本？,  Up: 常見資訊

11.1.1.12 我应如何为 Python 提交错误报告和补丁？
................................................

要报告错误或提交补丁，请使用安装于 ‘https://bugs.python.org/’ 上的
Roundup。

你必须拥有一个 Roundup 账号才能报告错误；这样我们就可以在有后续问题时与
你联系。 这也使得 Roundup 能在我们处理所报告的错误时向你发送更新消息。 如
果你之前使用过 SourceForge 向 Python 报告错误，你可以通过 Roundup 的 密
码重置操作(1) 来获取你的 Roundup 密码。

有关 Python 开发流程的更多信息，请参阅 Python 开发者指南(2)。

   ---------- Footnotes ----------

   (1) https://bugs.python.org/user?@template=forgotten

   (2) https://devguide.python.org/


File: python.info,  Node: 是否有任何公开发表的 Python 相关文章可以供我参考引用？,  Next: 有沒有關於Python的書,  Prev: 我应如何为 Python 提交错误报告和补丁？,  Up: 常見資訊

11.1.1.13 是否有任何公开发表的 Python 相关文章可以供我参考引用？
................................................................

可能作为参考文献的最好方式还是引用你喜欢的 Python 相关书籍。

最早討論Python的文章在1991年，但現在來看已經有點過時

     Guido van Rossum 与 Jelke de Boer, "使用 Python 编程语言交互式地测
     试远程服务器", CWI 季刊, 第 4 卷, 第 4 期 (1991 年 12 月), 阿姆斯特
     丹, 第 283–303 页。


File: python.info,  Node: 有沒有關於Python的書,  Next: www python org 這個非營利組織位於哪裡,  Prev: 是否有任何公开发表的 Python 相关文章可以供我参考引用？,  Up: 常見資訊

11.1.1.14 有沒有關於Python的書
..............................

是的已經有很多書出版，可以參考這個連結的參考書目
‘https://wiki.python.org/moin/PythonBooks’

你也可以上網搜尋網路書店關鍵字為"Python"，但不要使用"Monty Python"當作關
鍵字。或者可以搜尋"Python"和"語言"


File: python.info,  Node: www python org 這個非營利組織位於哪裡,  Next: 為什麼要取名為Python,  Prev: 有沒有關於Python的書,  Up: 常見資訊

11.1.1.15 www.python.org 這個非營利組織位於哪裡
...............................................

Python 项目的基础架构分布于世界各地并由 Python 基础架构团队负责管理。 详
情请访问 这里(1)。

   ---------- Footnotes ----------

   (1) http://infra.psf.io


File: python.info,  Node: 為什麼要取名為Python,  Next: 我需要喜歡蒙提·派森的飛行馬戲團這個節目嗎,  Prev: www python org 這個非營利組織位於哪裡,  Up: 常見資訊

11.1.1.16 為什麼要取名為Python
..............................

在着手编写 Python 实现的时候，Guido van Rossum 同时还阅读了刚出版的
"Monty Python 的飞行马戏团"(1) 剧本，这是一部自 1970 年代开始播出的 BBC
系列喜剧。 Van Rossum 觉得他需要选择一个简短、独特而又略显神秘的名字，于
是他决定将这个新语言命名为 Python。

   ---------- Footnotes ----------

   (1) https://en.wikipedia.org/wiki/Monty_Python


File: python.info,  Node: 我需要喜歡蒙提·派森的飛行馬戲團這個節目嗎,  Prev: 為什麼要取名為Python,  Up: 常見資訊

11.1.1.17 我需要喜歡蒙提·派森的飛行馬戲團這個節目嗎
...................................................

不需要，但它有幫助 :)


File: python.info,  Node: Python在真實世界,  Prev: 常見資訊,  Up: 常見Python問答集

11.1.2 Python在真實世界
-----------------------

* Menu:

* Python穩定性如何::
* 有多少人使用Python::
* 有沒有任何重要的案子使用Python完成開發::
* 對於程式開發者Python對於未來有什麼期待::
* 提议对 Python 加入不兼容的更改是否合理？::
* Python對於入門的程式設計者而言是否為好的程式語言::


File: python.info,  Node: Python穩定性如何,  Next: 有多少人使用Python,  Up: Python在真實世界

11.1.2.1 Python穩定性如何
.........................

非常穩定。自從 1991 年開始大約每隔 6 到 18 個月會釋出更新版，而且看起來
會繼續更新下去。從 3.9 開始，Python 每隔 12 個月會釋出一個主要發行版本 (
PEP 602(1))。

开发者也会推出旧版本的“问题修正”发布版，因此现有发布版的稳定性还会逐步提
升。 问题修正发布版会以版本号第三部分的数字来标示（例如 3.5.3, 3.6.2），
用于稳定性的管理；只有对已知问题的修正会包含在问题修正发布版中，同一系列
的问题修正发布版中的接口确定将会始终保持一致。

最后的稳定版本总是可以在 Python 下载页(2) 中找到。 有两个生产环境可用的
Python　版本：2.x 和 3.x。 推荐的版本是 3.x，大多数被广泛使用的库都支持它
。 虽然 2.x 也仍然被广泛使用，但是 它已经停止维护(3)。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0602

   (2) https://www.python.org/downloads/

   (3) https://www.python.org/dev/peps/pep-0373/


File: python.info,  Node: 有多少人使用Python,  Next: 有沒有任何重要的案子使用Python完成開發,  Prev: Python穩定性如何,  Up: Python在真實世界

11.1.2.2 有多少人使用Python
...........................

大約有超過一百萬個使用者，但實際上有多少人是很難準確的估算

Python 可以免费下载，因此并不存在销量数据，此外它也可以从许多不同网站获
取，并且包含于许多 Linux 发行版之中，因此下载量统计同样无法完全说明问题
。

comp.lang.python 新闻组非常活跃，但不是所有 Python 用户都会在新闻组发帖
，许多人甚至不会阅读新闻组。


File: python.info,  Node: 有沒有任何重要的案子使用Python完成開發,  Next: 對於程式開發者Python對於未來有什麼期待,  Prev: 有多少人使用Python,  Up: Python在真實世界

11.1.2.3 有沒有任何重要的案子使用Python完成開發
...............................................

请访问 ‘https://www.python.org/about/success’ 查看使用了 Python 的项目列
表。 阅览 历次 Python 会议(1) 的日程纪要可以看到许多不同公司和组织所做的
贡献。

高水准的 Python 项目包括 Mailman 邮件列表管理器(2) 和 Zope 应用服务器
(3)。 多个 Linux 发行版，其中最著名的有 Red Hat(4) 均已使用 Python 来编
写部分或全部的安装程序和系统管理软件。 在内部使用 Python 的大公司包括了
Google, Yahoo 以及 Lucasfilm 等。

   ---------- Footnotes ----------

   (1) https://www.python.org/community/workshops/

   (2) http://www.list.org

   (3) http://www.zope.org

   (4) https://www.redhat.com


File: python.info,  Node: 對於程式開發者Python對於未來有什麼期待,  Next: 提议对 Python 加入不兼容的更改是否合理？,  Prev: 有沒有任何重要的案子使用Python完成開發,  Up: Python在真實世界

11.1.2.4 對於程式開發者Python對於未來有什麼期待
...............................................

请访问 ‘https://www.python.org/dev/peps/’ 查看 Python 增强提议（PEP）。
PEP 是为 Python 加入某种新特性的提议进行描述的设计文档，其中会提供简明的
技术规格说明与基本原理。 可以查找标题为“Python X.Y Release Schedule”的
PEP，其中 X.Y 是某个尚未公开发布的版本。

新版本的开发会在 python-dev 邮件列表(1) 中进行讨论。

   ---------- Footnotes ----------

   (1) https://mail.python.org/mailman/listinfo/python-dev/


File: python.info,  Node: 提议对 Python 加入不兼容的更改是否合理？,  Next: Python對於入門的程式設計者而言是否為好的程式語言,  Prev: 對於程式開發者Python對於未來有什麼期待,  Up: Python在真實世界

11.1.2.5 提议对 Python 加入不兼容的更改是否合理？
.................................................

通常来说是不合理的。 世界上已存在的 Python 代码数以亿计，因此，任何对该
语言的更改即便仅会使得现有程序中极少的一部分失效也是难以令人接受的。 就
算你可以提供一个转换程序，也仍然存在需要更新全部文档的问题；另外还有大量
已出版的 Python 书籍，我们不希望让它们在一瞬间全部变成废纸。

如果必须更改某个特性，则应该提供渐进式的升级路径。 PEP 5(1) 描述了引入向
后不兼容的更改所需遵循的流程，以尽可能减少对用户的干扰。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0005


File: python.info,  Node: Python對於入門的程式設計者而言是否為好的程式語言,  Prev: 提议对 Python 加入不兼容的更改是否合理？,  Up: Python在真實世界

11.1.2.6 Python對於入門的程式設計者而言是否為好的程式語言
.........................................................

是的

从过程式、静态类型的编程语言例如 Pascal, C 或者 C++ 以及 Java 的某一子集
开始引导学生入门仍然是常见的做法。 但以 Python 作为第一种编程语言进行学
习对学生可能更有利。Python 具有非常简单和一致的语法和庞大的标准库，而且
最重要的是，在编程入门教学中使用 Python 可以让学生专注于更重要的编程技能
，例如问题分解与数据类型设计。 使用 Python，可以快速向学生介绍基本概念例
如循环与过程等。 他们甚至有可能在第一次课里就开始接触用户自定义对象。

对于之前从未接触过编程的学生来说，使用静态类型语言会感觉不够自然。 这会
给学生带来必须掌握的额外复杂性，并减慢教学的进度。 学生需要尝试像计算机
一样思考，分解问题，设计一致的接口并封装数据。 虽然从长远来看，学习和使
用一种静态类型语言是很重要的，但这并不是最适宜在学生的第一次编程课上就进
行探讨的主题。

还有许多其他方面的特点使得 Python 成为很好的入门语言。 像 Java 一样，
Python 拥有一个庞大的标准库，因此可以在课程非常早期的阶段就给学生布置一
些 `实用' 的编程项目。 编程作业不必仅限于标准四则运算和账目检查程序。 通
过使用标准库，学生可以在学习编程基础知识的同时开发真正的应用，从而获得更
大的满足感。 使用标准库还能使学生了解代码重用的概念。 而像 PyGame 这样的
第三方模块同样有助于扩大学生的接触领域。

Python 的解释器使学生能够在编程时测试语言特性。 他们可以在一个窗口中输入
程序源代码的同时开启一个解释器运行窗口。 如果他们不记得列表有哪些方法，
他们这以这样做:

     >>> 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]

通过使用解释器，学生编写程序时参考文档总是能伴随在他们身边。

Python 还拥有很好的 IDE。 IDLE 是一个跨平台的 Python IDE，它基于 Tkinter
库，使用 Python 语言编写。 PythonWin 是一个 Windows 专属的 IDE。 Emacs 用
户将高兴地了解到 Emacs 具有非常好的 Python 模式。 所有这些编程环境都提供
语法高亮，自动缩进以及在编写代码时使用交互式解释器等功能。 请访问 Python
wiki(1) 查看 Python 编程环境的完整列表。

如果你想要讨论 Python 在教育中的使用，你可能会有兴趣加入 edu-sig 邮件列
表(2)。

   ---------- Footnotes ----------

   (1) https://wiki.python.org/moin/PythonEditors

   (2) https://www.python.org/community/sigs/current/edu-sig


File: python.info,  Node: 程式開發常見問答集,  Next: 设计和历史常见问题,  Prev: 常見Python問答集,  Up: Python 常見問題

11.2 程式開發常見問答集
=======================

* Menu:

* 常見問題::
* 语言核心内容::
* 数字和字符串::
* 性能: 性能<4>.
* 序列（元组/列表）::
* 对象::
* 模块: 模块<2>.


File: python.info,  Node: 常見問題,  Next: 语言核心内容,  Up: 程式開發常見問答集

11.2.1 常見問題
---------------

* Menu:

* 是否有可以使用在程式碼階段,具有中斷點,步驟執行等功能的除錯器？: 是否有可以使用在程式碼階段 具有中斷點 步驟執行等功能的除錯器？.
* 有沒有工具能夠幫忙找 bug 或執行靜態分析？::
* 如何由 Python 脚本创建能独立运行的二进制程序？::
* 是否有 Python 编码标准或风格指南？::


File: python.info,  Node: 是否有可以使用在程式碼階段 具有中斷點 步驟執行等功能的除錯器？,  Next: 有沒有工具能夠幫忙找 bug 或執行靜態分析？,  Up: 常見問題

11.2.1.1 是否有可以使用在程式碼階段,具有中斷點,步驟執行等功能的除錯器？
.......................................................................

有的

以下介绍了一些 Python 的调试器，用内置函数 *note breakpoint(): 40b. 即可
切入这些调试器中。

pdb 模块是一个简单但是够用的控制台模式 Python 调试器。 它是标准 Python 库
的一部分，并且 *note 已收录于库参考手册: c9.。 你也可以通过使用 pdb 代码
作为样例来编写你自己的调试器。

作为标准 Python 发行版附带组件的 IDLE 交互式环境（通常位于
Tools/scripts/idle）中包含一个图形化的调试器。

PythonWin 是一种 Python IDE，其中包含了一个基于 pdb 的 GUI 调试器。
PythonWin 的调试器会为断点着色，并提供了相当多的超酷特性，例如调试非
PythonWin 程序等。PythonWin 是 pywin32(1) 项目的组成部分，也是
ActivePython(2) 发行版的组成部分。

Eric(3) 是一个基于PyQt和Scintilla编辑组件构建的IDE。

trepan3k(4) 是一个类似 gdb 的调试器。

Visual Studio Code(5) 是包含了调试工具的 IDE，并集成了版本控制软件。

有數個商業化Python整合化開發工具包含圖形除錯功能。這些包含：

   * Wing IDE(6)

   * Komodo IDE(7)

   * PyCharm(8)

   ---------- Footnotes ----------

   (1) https://github.com/mhammond/pywin32

   (2) https://www.activestate.com/products/python/

   (3) http://eric-ide.python-projects.org/

   (4) https://github.com/rocky/python3-trepan/

   (5) https://code.visualstudio.com/

   (6) https://wingware.com/

   (7) https://www.activestate.com/products/komodo-ide/

   (8) https://www.jetbrains.com/pycharm/


File: python.info,  Node: 有沒有工具能夠幫忙找 bug 或執行靜態分析？,  Next: 如何由 Python 脚本创建能独立运行的二进制程序？,  Prev: 是否有可以使用在程式碼階段 具有中斷點 步驟執行等功能的除錯器？,  Up: 常見問題

11.2.1.2 有沒有工具能夠幫忙找 bug 或執行靜態分析？
..................................................

有的

Pylint(1) 和 Pyflakes(2) 可进行基本检查来帮助你尽早捕捉漏洞。

静态类型检查器，例如 Mypy(3) 、 Pyre(4) 和 Pytype(5) 可以检查Python源代
码中的类型提示。

   ---------- Footnotes ----------

   (1) https://www.pylint.org/

   (2) https://github.com/PyCQA/pyflakes

   (3) http://mypy-lang.org/

   (4) https://pyre-check.org/

   (5) https://github.com/google/pytype


File: python.info,  Node: 如何由 Python 脚本创建能独立运行的二进制程序？,  Next: 是否有 Python 编码标准或风格指南？,  Prev: 有沒有工具能夠幫忙找 bug 或執行靜態分析？,  Up: 常見問題

11.2.1.3 如何由 Python 脚本创建能独立运行的二进制程序？
.......................................................

如果只是想要一个独立的程序，以便用户不必预先安装 Python 即可下载和运行它
，则不需要将 Python 编译成 C 代码。有许多工具可以检测程序所需的模块，并
将这些模块与 Python 二进制程序捆绑在一起生成单个可执行文件。

一种方案是使用 freeze 工具，它在 Python 源码目录的 ‘Tools/freeze’ 中提供
。它能把 Python 字节码转换为 C 数组；一个 C 编译器可以将所有模块嵌入到一
个新程序中，然后将其与标准 Python 模块链接。

它的工作原理是递归扫描源代码，获取两种格式的 import 语句，并在标准
Python 路径和源码目录（用于内置模块）检索这些模块。然后，把这些模块的
Python 字节码转换为 C 代码（可以利用 marshal 模块转换为代码对象的数组初
始化器），并创建一个定制的配置文件，该文件仅包含程序实际用到的内置模块。
然后，编译生成的 C 代码并将其与 Python 解释器的其余部分链接，形成一个自
给自足的二进制文件，其功能与 Python 脚本代码完全相同。

下列包可以用于帮助创建控制台和 GUI 的可执行文件:

   * Nuitka(1) （跨平台）

   * PyInstaller(2) （跨平台）

   * PyOxidizer(3) （跨平台）

   * cx_Freeze(4) （跨平台）

   * py2app(5) （仅限 macOS）

   * py2exe(6) （僅限 Windows）

   ---------- Footnotes ----------

   (1) https://nuitka.net/

   (2) http://www.pyinstaller.org/

   (3) https://pyoxidizer.readthedocs.io/en/stable/

   (4) https://marcelotduarte.github.io/cx_Freeze/

   (5) https://github.com/ronaldoussoren/py2app

   (6) http://www.py2exe.org/


File: python.info,  Node: 是否有 Python 编码标准或风格指南？,  Prev: 如何由 Python 脚本创建能独立运行的二进制程序？,  Up: 常見問題

11.2.1.4 是否有 Python 编码标准或风格指南？
...........................................

有的。 标准库模块所要求的编码风格记录于 PEP 8(1) 之中。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0008


File: python.info,  Node: 语言核心内容,  Next: 数字和字符串,  Prev: 常見問題,  Up: 程式開發常見問答集

11.2.2 语言核心内容
-------------------

* Menu:

* 為什麼當變數有值時我得到錯誤訊息 UnboundLocalError::
* Python 的區域變數和全域變數有什麼規則？::
* 为什么在循环中定义的参数各异的 lambda 都返回相同的结果？::
* 如何跨模块共享全局变量？::
* 导入模块的“最佳实践”是什么？::
* 为什么对象之间会共享默认值？::
* 如何将可选参数或关键字参数从一个函数传递到另一个函数？::
* 形参和实参之间有什么区别？::
* 为什么修改列表 'y' 也会更改列表 'x'？::
* 如何编写带有输出参数的函数（按照引用调用）？::
* 如何在 Python 中创建高阶函数？::
* 如何复制 Python 对象？::
* 如何找到对象的方法或属性？::
* 如何用代码获取对象的名称？::
* 逗号运算符的优先级是什么？::
* 是否提供等价于 C 语言 "?;" 三目运算符的东西？: 是否提供等价于 C 语言 "? " 三目运算符的东西？.
* 是否可以用 Python 编写让人眼晕的单行程序?::
* 函数形参列表中的斜杠（/）是什么意思？::


File: python.info,  Node: 為什麼當變數有值時我得到錯誤訊息 UnboundLocalError,  Next: Python 的區域變數和全域變數有什麼規則？,  Up: 语言核心内容

11.2.2.1 為什麼當變數有值時我得到錯誤訊息 UnboundLocalError
...........................................................

因为在函数内部某处添加了一条赋值语句，导致之前正常工作的代码报出
UnboundLocalError 错误，这可能是有点令人惊讶。

這段程式碼:

     >>> x = 10
     >>> def bar():
     ...     print(x)
     >>> bar()
     10

可以執行,但是這段程式:

     >>> x = 10
     >>> def foo():
     ...     print(x)
     ...     x += 1

導致UnboundLocalError

     >>> foo()
     Traceback (most recent call last):
       ...
     UnboundLocalError: local variable 'x' referenced before assignment

原因就是，当对某作用域内的变量进行赋值时，该变量将成为该作用域内的局部变
量，并覆盖外部作用域中的同名变量。由于 foo 的最后一条语句为 ‘x’ 分配了一
个新值，编译器会将其识别为局部变量。因此，前面的 ‘print(x)’ 试图输出未初
始化的局部变量，就会引发错误。

在上面的示例中，可以将外部作用域的变量声明为全局变量以便访问：

     >>> x = 10
     >>> def foobar():
     ...     global x
     ...     print(x)
     ...     x += 1
     >>> foobar()
     10

与类和实例变量貌似但不一样，其实以上是在修改外部作用域的变量值，为了提示
这一点，这里需要显式声明一下。

     >>> print(x)
     11

你可以使用 *note nonlocal: d07. 关键字在嵌套作用域中执行类似的操作：

     >>> def foo():
     ...    x = 10
     ...    def bar():
     ...        nonlocal x
     ...        print(x)
     ...        x += 1
     ...    bar()
     ...    print(x)
     >>> foo()
     10
     11


File: python.info,  Node: Python 的區域變數和全域變數有什麼規則？,  Next: 为什么在循环中定义的参数各异的 lambda 都返回相同的结果？,  Prev: 為什麼當變數有值時我得到錯誤訊息 UnboundLocalError,  Up: 语言核心内容

11.2.2.2 Python 的區域變數和全域變數有什麼規則？
................................................

函数内部只作引用的 Python 变量隐式视为全局变量。如果在函数内部任何位置为
变量赋值，则除非明确声明为全局变量，否则均将其视为局部变量。

起初尽管有点令人惊讶，不过考虑片刻即可释然。一方面，已分配的变量要求加上
*note global: 1378. 可以防止意外的副作用发生。另一方面，如果所有全局引用
都要加上 ‘global’ ，那处处都得用上 ‘global’ 了。那么每次对内置函数或导入
模块中的组件进行引用时，都得声明为全局变量。这种杂乱会破坏 ‘global’ 声明
用于警示副作用的有效性。


File: python.info,  Node: 为什么在循环中定义的参数各异的 lambda 都返回相同的结果？,  Next: 如何跨模块共享全局变量？,  Prev: Python 的區域變數和全域變數有什麼規則？,  Up: 语言核心内容

11.2.2.3 为什么在循环中定义的参数各异的 lambda 都返回相同的结果？
.................................................................

假设用 for 循环来定义几个取值各异的 lambda（即便是普通函数也一样）：

     >>> squares = []
     >>> for x in range(5):
     ...     squares.append(lambda: x**2)

以上会得到一个包含5个 lambda 函数的列表，这些函数将计算 ‘x**2’。大家或许
期望，调用这些函数会分别返回 ‘0’ 、‘1’ 、 ‘4’ 、 ‘9’ 和 ‘16’。然而，真的
试过就会发现，他们都会返回 ‘16’ ：

     >>> squares[2]()
     16
     >>> squares[4]()
     16

这是因为 ‘x’ 不是 lambda 函数的内部变量，而是定义于外部作用域中的，并且
‘x’ 是在调用 lambda 时访问的——而不是在定义时访问。循环结束时 ‘x’ 的值是
‘4’ ，所以此时所有的函数都将返回 ‘4**2’ ，即 ‘16’ 。通过改变 ‘x’ 的值并
查看 lambda 的结果变化，也可以验证这一点。

     >>> x = 8
     >>> squares[2]()
     64

为了避免发生上述情况，需要将值保存在 lambda 局部变量，以使其不依赖于全局
‘x’ 的值：

     >>> squares = []
     >>> for x in range(5):
     ...     squares.append(lambda n=x: n**2)

以上 ‘n=x’ 创建了一个新的 lambda 本地变量 ‘n’，并在定义 lambda 时计算其
值，使其与循环当前时点的 ‘x’ 值相同。这意味着 ‘n’ 的值在第 1 个 lambda 中
为 ‘0’ ，在第 2 个 lambda 中为 ‘1’ ，在第 3 个中为 ‘2’，依此类推。因此现
在每个 lambda 都会返回正确结果：

     >>> squares[2]()
     4
     >>> squares[4]()
     16

请注意，上述表现并不是 lambda 所特有的，常规的函数也同样适用。


File: python.info,  Node: 如何跨模块共享全局变量？,  Next: 导入模块的“最佳实践”是什么？,  Prev: 为什么在循环中定义的参数各异的 lambda 都返回相同的结果？,  Up: 语言核心内容

11.2.2.4 如何跨模块共享全局变量？
.................................

在单个程序中跨模块共享信息的规范方法是创建一个特殊模块（通常称为 config
或 cfg）。只需在应用程序的所有模块中导入该 config 模块；然后该模块就可当
作全局名称使用了。因为每个模块只有一个实例，所以对该模块对象所做的任何更
改将会在所有地方得以体现。 例如：

config.py：

     x = 0   # Default value of the 'x' configuration setting

mod.py：

     import config
     config.x = 1

main.py：

     import config
     import mod
     print(config.x)

请注意，出于同样的原因，采用模块也是实现单例设计模式的基础。


File: python.info,  Node: 导入模块的“最佳实践”是什么？,  Next: 为什么对象之间会共享默认值？,  Prev: 如何跨模块共享全局变量？,  Up: 语言核心内容

11.2.2.5 导入模块的“最佳实践”是什么？
.....................................

通常请勿使用 ‘from modulename import *’ 。因为这会扰乱 importer 的命名空
间，且会造成未定义名称更难以被 Linter 检查出来。

请在代码文件的首部就导入模块。这样代码所需的模块就一目了然了，也不用考虑
模块名是否在作用域内的问题。每行导入一个模块则增删起来会比较容易，每行导
入多个模块则更节省屏幕空间。

按如下顺序导入模块就是一种好做法：

  1. 标准库模块——比如： ‘sys’ 、 ‘os’ 、 ‘getopt’ 、 ‘re’ 等。

  2. 第三方库模块（安装于 Python site-packages 目录中的内容）——如
     mx.DateTime、ZODB、PIL.Image 等。

  3. 本地开发的模块

为了避免循环导入引发的问题，有时需要将模块导入语句移入函数或类的内部。
Gordon McMillan 的说法如下：

     当两个模块都采用 "import <module>" 的导入形式时，循环导入是没有问题
     的。但如果第 2 个模块想从第 1 个模块中取出一个名称（"from module
     import name"）并且导入处于代码的最顶层，那导入就会失败。原因是第 1
     个模块中的名称还不可用，这时第 1 个模块正忙于导入第 2 个模块呢。

如果只是在一个函数中用到第 2 个模块，那这时将导入语句移入该函数内部即可
。当调用到导入语句时，第 1 个模块将已经完成初始化，第 2 个模块就可以进行
导入了。

如果某些模块是平台相关的，可能还需要把导入语句移出最顶级代码。这种情况下
，甚至有可能无法导入文件首部的所有模块。于是在对应的平台相关代码中导入正
确的模块，就是一种不错的选择。

只有为了避免循环导入问题，或有必要减少模块初始化时间时，才把导入语句移入
类似函数定义内部的局部作用域。如果根据程序的执行方式，许多导入操作不是必
需的，那么这种技术尤其有用。如果模块仅在某个函数中用到，可能还要将导入操
作移入该函数内部。请注意，因为模块有一次初始化过程，所以第一次加载模块的
代价可能会比较高，但多次加载几乎没有什么花费，代价只是进行几次字典检索而
已。即使模块名超出了作用域，模块在 *note sys.modules: 1051. 中也是可用的
。


File: python.info,  Node: 为什么对象之间会共享默认值？,  Next: 如何将可选参数或关键字参数从一个函数传递到另一个函数？,  Prev: 导入模块的“最佳实践”是什么？,  Up: 语言核心内容

11.2.2.6 为什么对象之间会共享默认值？
.....................................

新手程序员常常中招这类 Bug。请看以下函数：

     def foo(mydict={}):  # Danger: shared reference to one dict for all calls
         ... compute something ...
         mydict[key] = value
         return mydict

第一次调用此函数时， ‘mydict’ 中只有一个数据项。第二次调用 ‘mydict’ 则会
包含两个数据项，因为 ‘foo()’ 开始执行时， ‘mydict’ 中已经带有一个数据项
了。

大家往往希望，函数调用会为默认值创建新的对象。但事实并非如此。默认值只会
在函数定义时创建一次。如果对象发生改变，就如上例中的字典那样，则后续调用
该函数时将会引用这个改动的对象。

按照定义，不可变对象改动起来是安全的，诸如数字、字符串、元组和 ‘None’ 之
类。而可变对象的改动则可能引起困惑，例如字典、列表和类实例等。

因此，不把可变对象用作默认值是一种良好的编程做法。而应采用 ‘None’ 作为默
认值，然后在函数中检查参数是否为 ‘None’ 并新建列表、字典或其他对象。例如
，代码不应如下所示：

     def foo(mydict={}):
         ...

而应这么写：

     def foo(mydict=None):
         if mydict is None:
             mydict = {}  # create a new dict for local namespace

参数默认值的特性有时会很有用处。 如果有个函数的计算过程会比较耗时，有一
种常见技巧是将每次函数调用的参数和结果缓存起来，并在同样的值被再次请求时
返回缓存的值。这种技巧被称为“memoize”，实现代码可如下所示：

     # 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

也可以不用参数默认值来实现，而是采用全局的字典变量；这取决于个人偏好。


File: python.info,  Node: 如何将可选参数或关键字参数从一个函数传递到另一个函数？,  Next: 形参和实参之间有什么区别？,  Prev: 为什么对象之间会共享默认值？,  Up: 语言核心内容

11.2.2.7 如何将可选参数或关键字参数从一个函数传递到另一个函数？
...............................................................

请利用函数参数列表中的标识符 ‘*’ 和 ‘**’ 归集实参；结果会是元组形式的位
置实参和字典形式的关键字实参。然后就可利用 ‘*’ 和 ‘**’ 在调用其他函数时
传入这些实参：

     def f(x, *args, **kwargs):
         ...
         kwargs['width'] = '14.3c'
         ...
         g(x, *args, **kwargs)


File: python.info,  Node: 形参和实参之间有什么区别？,  Next: 为什么修改列表 'y' 也会更改列表 'x'？,  Prev: 如何将可选参数或关键字参数从一个函数传递到另一个函数？,  Up: 语言核心内容

11.2.2.8 形参和实参之间有什么区别？
...................................

*note 形参: 1664. 是指出现在函数定义中的名称，而 *note 实参: 165b. 则是
在调用函数时实际传入的值。 形参定义了一个函数能接受何种类型的实参。 例如
，对于以下函数定义:

     def func(foo, bar=None, **kwargs):
         pass

`foo' 、 `bar' 和 `kwargs' 是 ‘func’ 的形参。 不过在调用 ‘func’ 时，例如
：

     func(42, bar=314, extra=somevar)

‘42’ 、 ‘314’ 和 ‘somevar’ 则是实参。


File: python.info,  Node: 为什么修改列表 'y' 也会更改列表 'x'？,  Next: 如何编写带有输出参数的函数（按照引用调用）？,  Prev: 形参和实参之间有什么区别？,  Up: 语言核心内容

11.2.2.9 为什么修改列表 ’y’ 也会更改列表 ’x’？
..............................................

如果代码编写如下：

     >>> x = []
     >>> y = x
     >>> y.append(10)
     >>> y
     [10]
     >>> x
     [10]

或许大家很想知道，为什么在 y 中添加一个元素时， x 也会改变。

产生这种结果有两个因素：

  1. 变量只是指向对象的一个名称。执行 ‘y = x’ 并不会创建列表的副本——而只
     是创建了一个新变量 ‘y’，并指向 ‘x’ 所指的同一对象。这就意味着只存在
     一个列表对象，‘x’ 和 ‘y’ 都是对它的引用。

  2. 列表属于 *note mutable: 135e. 对象，这意味着它的内容是可以修改的。

在调用 ‘append()’ 之后，该可变对象的内容由 ‘[]’ 变为 ‘[10]’。由于 x 和 y
这两个变量引用了同一对象，因此用其中任意一个名称所访问到的都是修改后的值
‘[10]’。

如果把赋给 ‘x’ 的对象换成一个不可变对象：

     >>> 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

可见这时 ‘x’ 和 ‘y’ 就不再相等了。因为整数是 *note immutable: 1356. 对象
，在执行 ‘x = x + 1’ 时，并不会修改整数对象 ‘5’，给它加上 1；而是创建了
一个新的对象（整数对象 ‘6’ ）并将其赋给 ‘x’ （也就是改变了 ‘x’ 所指向的
对象）。在赋值完成后，就有了两个对象（整数对象 ‘6’ 和 ‘5’ ）和分别指向他
俩的两个变量（ ‘x’ 现在指向 ‘6’ 而 ‘y’ 仍然指向 ‘5’ ）。

某些操作（例如 ‘y.append(10)’ 和 ‘y.sort()’ ）会直接修改原对象，而看上去
相似的另一些操作（例如 ‘y = y + [10]’ 和 ‘sorted(y)’ ）则会创建新的对象
。通常在 Python 中（以及所有标准库），直接修改原对象的方法将会返回
‘None’ ，以助避免混淆这两种不同类型的操作。因此如果误用了 ‘y.sort()’ 并
期望返回 ‘y’ 的有序副本，则结果只会是 ‘None’ ，这可能就能让程序引发一条
容易诊断的错误。

不过还存在一类操作，用不同的类型执行相同的操作有时会发生不同的行为：即增
量赋值运算符。例如，‘+=’ 会修改列表，但不会修改元组或整数（‘a_list +=
[1, 2, 3]’ 与 ‘a_list.extend([1, 2, 3])’ 同样都会改变 ‘a_list’，而
‘some_tuple += (1, 2, 3)’ 和 ‘some_int += 1’ 则会创建新的对象）。

换而言之：

   * 对于一个可变对象（ *note list: 1f8. 、 *note dict: 164. 、 *note
     set: 1f6. 等等），可以利用某些特定的操作进行修改，所有引用它的变量
     都会反映出改动情况。

   * 对于一个不可变对象（ *note str: 205. 、 *note int: 204. 、 *note
     tuple: 1a2. 等），所有引用它的变量都会给出相同的值，但所有改变其值
     的操作都将返回一个新的对象。

如要知道两个变量是否指向同一个对象，可以利用 *note is: 1551. 运算符或内
置函数 *note id(): e4b.。


File: python.info,  Node: 如何编写带有输出参数的函数（按照引用调用）？,  Next: 如何在 Python 中创建高阶函数？,  Prev: 为什么修改列表 'y' 也会更改列表 'x'？,  Up: 语言核心内容

11.2.2.10 如何编写带有输出参数的函数（按照引用调用）？
......................................................

请记住，Python 中的实参是通过赋值传递的。由于赋值只是创建了对象的引用，
所以调用方和被调用方的参数名都不存在别名，本质上也就不存在按引用调用的方
式。通过以下几种方式，可以得到所需的效果。

  1. 返回一个元组：

          >>> 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)

     这差不多是最明晰的解决方案了。

  2. 使用全局变量。这不是线程安全的方案，不推荐使用。

  3. 传递一个可变（即可原地修改的） 对象：

          >>> 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]

  4. 传入一个接收可变对象的字典:

          >>> 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}

  5. 或者把值用类实例封装起来：

          >>> 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}

     没有什么理由要把问题搞得这么复杂。

最佳选择就是返回一个包含多个结果值的元组。


File: python.info,  Node: 如何在 Python 中创建高阶函数？,  Next: 如何复制 Python 对象？,  Prev: 如何编写带有输出参数的函数（按照引用调用）？,  Up: 语言核心内容

11.2.2.11 如何在 Python 中创建高阶函数？
........................................

有两种选择：嵌套作用域、可调用对象。假定需要定义 ‘linear(a,b)’ ，其返回
结果是一个计算出 ‘a*x+b’ 的函数 ‘f(x)’。 采用嵌套作用域的方案如下：

     def linear(a, b):
         def result(x):
             return a * x + b
         return result

或者可采用可调用对象：

     class linear:

         def __init__(self, a, b):
             self.a, self.b = a, b

         def __call__(self, x):
             return self.a * x + self.b

采用这两种方案时：

     taxes = linear(0.3, 2)

都会得到一个可调用对象，可实现 ‘taxes(10e6) == 0.3 * 10e6 + 2’ 。

可调用对象的方案有个缺点，就是速度稍慢且生成的代码略长。不过值得注意的是
，同一组可调用对象能够通过继承来共享签名（类声明）：

     class exponential(linear):
         # __init__ inherited
         def __call__(self, x):
             return self.a * (x ** self.b)

对象可以为多个方法的运行状态进行封装：

     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

以上 ‘inc()’ 、 ‘dec()’ 和 ‘reset()’ 的表现，就如同共享了同一计数变量一
样。


File: python.info,  Node: 如何复制 Python 对象？,  Next: 如何找到对象的方法或属性？,  Prev: 如何在 Python 中创建高阶函数？,  Up: 语言核心内容

11.2.2.12 如何复制 Python 对象？
................................

一般情况下，用 *note copy.copy(): 4d1. 或 *note copy.deepcopy(): 4d2. 基
本就可以了。并不是所有对象都支持复制，但多数是可以的。

某些对象可以用更简便的方法进行复制。比如字典对象就提供了 *note copy():
548. 方法：

     newdict = olddict.copy()

序列可以用切片操作进行复制：

     new_l = l[:]


File: python.info,  Node: 如何找到对象的方法或属性？,  Next: 如何用代码获取对象的名称？,  Prev: 如何复制 Python 对象？,  Up: 语言核心内容

11.2.2.13 如何找到对象的方法或属性？
....................................

假定 x 是一个用户自定义类的实例，‘dir(x)’ 将返回一个按字母排序的名称列表
，其中包含了实例的属性及由类定义的方法和属性。


File: python.info,  Node: 如何用代码获取对象的名称？,  Next: 逗号运算符的优先级是什么？,  Prev: 如何找到对象的方法或属性？,  Up: 语言核心内容

11.2.2.14 如何用代码获取对象的名称？
....................................

一般而言这是无法实现的，因为对象并不存在真正的名称。赋值本质上是把某个名
称绑定到某个值上；‘def’ 和 ‘class’ 语句同样如此，只是值换成了某个可调用
对象。比如以下代码：

     >>> class A:
     ...     pass
     ...
     >>> B = A
     >>> a = B()
     >>> b = a
     >>> print(b)
     <__main__.A object at 0x16D07CC>
     >>> print(a)
     <__main__.A object at 0x16D07CC>

可以不太严谨地说，上述类具有一个名称：即便它绑定了两个名称并通过名称 B 发
起调用，可是创建出来的实例仍被视为是类 A 的实例。但无法说出实例的名称是
a 还是 b，因为这两个名称都被绑定到同一个值上了。

代码一般没有必要去“知晓”某个值的名称。通常这种需求预示着还是改变方案为好
，除非真的是要编写内审程序。

在 comp.lang.python 中，Fredrik Lundh 在回答这样的问题时曾经给出过一个绝
佳的类比：

     这就像要知道家门口的那只猫的名字一样：猫（对象）自己不会说出它的名
     字，它根本就不在乎自己叫什么——所以唯一方法就是问一遍你所有的邻居（
     命名空间），这是不是他们家的猫（对象）……

     ……并且如果你发现它有很多名字或根本没有名字，那也不必惊讶！


File: python.info,  Node: 逗号运算符的优先级是什么？,  Next: 是否提供等价于 C 语言 "? " 三目运算符的东西？,  Prev: 如何用代码获取对象的名称？,  Up: 语言核心内容

11.2.2.15 逗号运算符的优先级是什么？
....................................

逗号不是 Python 的运算符。 请看以下例子：

     >>> "a" in "b", "a"
     (False, 'a')

由于逗号不是运算符，而只是表达式之间的分隔符，因此上述代码就相当于：

     ("a" in "b"), "a"

而不是：

     "a" in ("b", "a")

对于各种赋值运算符（ ‘=’ 、 ‘+=’ 等）来说同样如此。他们并不是真正的运算
符，而只是赋值语句中的语法分隔符。


File: python.info,  Node: 是否提供等价于 C 语言 "? " 三目运算符的东西？,  Next: 是否可以用 Python 编写让人眼晕的单行程序?,  Prev: 逗号运算符的优先级是什么？,  Up: 语言核心内容

11.2.2.16 是否提供等价于 C 语言 "?:" 三目运算符的东西？
.......................................................

有的。语法如下：

     [on_true] if [expression] else [on_false]

     x, y = 50, 25
     small = x if x < y else y

在 Python 2.5 引入上述语法之前，通常的做法是使用逻辑运算符：

     [expression] and [on_true] or [on_false]

然而这种做法并不保险，因为当 `on_true' 为布尔值“假”时，结果将会出错。所
以肯定还是采用 ‘... if ... else ...’ 形式为妙。


File: python.info,  Node: 是否可以用 Python 编写让人眼晕的单行程序?,  Next: 函数形参列表中的斜杠（/）是什么意思？,  Prev: 是否提供等价于 C 语言 "? " 三目运算符的东西？,  Up: 语言核心内容

11.2.2.17 是否可以用 Python 编写让人眼晕的单行程序?
...................................................

可以。通常是在 *note lambda: cf9. 中嵌套 ‘lambda’ 来实现的。请参阅以下三
个来自 Ulf Bartelt 的示例代码：

     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

请不要在家里尝试，骚年！


File: python.info,  Node: 函数形参列表中的斜杠（/）是什么意思？,  Prev: 是否可以用 Python 编写让人眼晕的单行程序?,  Up: 语言核心内容

11.2.2.18 函数形参列表中的斜杠（/）是什么意思？
...............................................

函数参数列表中的斜杠表示在它之前的形参全都仅限位置形参。仅限位置形参没有
可供外部使用的名称。在调用仅接受位置形参的函数时，实参只会根据位置映射到
形参上。假定 *note divmod(): 28d. 是一个仅接受位置形参的函数。 它的帮助
文档如下所示：

     >>> 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.

形参列表尾部的斜杠说明，两个形参都是仅限位置形参。因此，用关键字参数调用
*note divmod(): 28d. 将会引发错误：

     >>> divmod(x=3, y=4)
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     TypeError: divmod() takes no keyword arguments


File: python.info,  Node: 数字和字符串,  Next: 性能<4>,  Prev: 语言核心内容,  Up: 程式開發常見問答集

11.2.3 数字和字符串
-------------------

* Menu:

* 如何给出十六进制和八进制整数？::
* 为什么 -22 // 10 会返回 -3 ？::
* How do I get int literal attribute instead of SyntaxError?::
* 如何将字符串转换为数字？::
* 如何将数字转换为字符串？::
* 如何修改字符串？::
* 如何使用字符串调用函数/方法？::
* 是否有与Perl 的chomp() 等效的方法，用于从字符串中删除尾随换行符？: 是否有与Perl 的chomp 等效的方法，用于从字符串中删除尾随换行符？.
* 是否有 scanf() 或 sscanf() 的等价函数？: 是否有 scanf 或 sscanf 的等价函数？.
* 'UnicodeDecodeError' 或 'UnicodeEncodeError' 错误是什么意思？::


File: python.info,  Node: 如何给出十六进制和八进制整数？,  Next: 为什么 -22 // 10 会返回 -3 ？,  Up: 数字和字符串

11.2.3.1 如何给出十六进制和八进制整数？
.......................................

要给出八进制数，需在八进制数值前面加上一个零和一个小写或大写字母 "o" 作
为前缀。例如，要将变量 "a" 设为八进制的 "10" （十进制的 8），写法如下：

     >>> a = 0o10
     >>> a
     8

十六进制数也很简单。只要在十六进制数前面加上一个零和一个小写或大写的字母
"x"。十六进制数中的字母可以为大写或小写。比如在 Python 解释器中输入：

     >>> a = 0xa5
     >>> a
     165
     >>> b = 0XB2
     >>> b
     178


File: python.info,  Node: 为什么 -22 // 10 会返回 -3 ？,  Next: How do I get int literal attribute instead of SyntaxError?,  Prev: 如何给出十六进制和八进制整数？,  Up: 数字和字符串

11.2.3.2 为什么 -22 // 10 会返回 -3 ？
......................................

这主要是为了让 ‘i % j’ 的正负与 ‘j’ 一致，如果期望如此，且期望如下等式成
立：

     i == (i // j) * j + (i % j)

那么整除就必须返回向下取整的结果。C 语言同样要求保持这种一致性，于是编译
器在截断 ‘i // j’ 的结果时需要让 ‘i % j’ 的正负与 ‘i’ 一致。

对于 ‘i % j’ 来说 ‘j’ 为负值的应用场景实际上是非常少的。 而 ‘j’ 为正值的
情况则非常多，并且实际上在所有情况下让 ‘i % j’ 的结果为 ‘>= 0’ 会更有用
处。 如果现在时间为 10 时，那么 200 小时前应是几时？ ‘-190 % 12 == 2’ 是
有用处的；‘-190 % 12 == -10’ 则是会导致意外的漏洞。


File: python.info,  Node: How do I get int literal attribute instead of SyntaxError?,  Next: 如何将字符串转换为数字？,  Prev: 为什么 -22 // 10 会返回 -3 ？,  Up: 数字和字符串

11.2.3.3 How do I get int literal attribute instead of SyntaxError?
...................................................................

Trying to lookup an ‘int’ literal attribute in the normal manner gives a
syntax error because the period is seen as a decimal point:

     >>> 1.__class__
       File "<stdin>", line 1
       1.__class__
        ^
     SyntaxError: invalid decimal literal

The solution is to separate the literal from the period with either a
space or parentheses.

     >>> 1 .__class__
     <class 'int'>
     >>> (1).__class__
     <class 'int'>


File: python.info,  Node: 如何将字符串转换为数字？,  Next: 如何将数字转换为字符串？,  Prev: How do I get int literal attribute instead of SyntaxError?,  Up: 数字和字符串

11.2.3.4 如何将字符串转换为数字？
.................................

对于整数，可使用内置的 *note int(): 204. 类型构造器，例如 ‘int('144') ==
144’。 类似地，可使用 *note float(): 1fd. 转换为浮点数，例如
‘float('144') == 144.0’。

默认情况下，这些操作会将数字按十进制来解读，因此 ‘int('0144') == 144’ 为
真值，而 ‘int('0x144')’ 会引发 *note ValueError: 16d.。 ‘int(string,
base)’ 接受第二个可选参数指定转换的基数，例如 ‘int( '0x144', 16) ==
324’。 如果指定基数为 0，则按 Python 规则解读数字：前缀 ’0o’ 表示八进制
，而 ’0x’ 表示十六进制。

如果只是想把字符串转为数字，请不要使用内置函数 *note eval(): c61.。
*note eval(): c61. 的速度慢很多且存在安全风险：别人可能会传入带有不良副
作用的 Python 表达式。比如可能会传入 ‘__import__('os').system("rm -rf
$HOME")’ ，这会把 home 目录给删了。

*note eval(): c61. 还有把数字解析为 Python 表达式的后果，因此如
‘eval('09')’ 将会导致语法错误，因为 Python 不允许十进制数带有前导 ’0’（
’0’ 除外）。


File: python.info,  Node: 如何将数字转换为字符串？,  Next: 如何修改字符串？,  Prev: 如何将字符串转换为数字？,  Up: 数字和字符串

11.2.3.5 如何将数字转换为字符串？
.................................

比如要把数字 144 转换为字符串 ’144’，可使用内置类型构造器 *note str():
205.。如果要表示为十六进制或八进制数格式，可使用内置函数 *note hex():
d2e. 或 *note oct(): d2d.。更复杂的格式化方法请参阅 *note
格式字符串字面值: 296. 和 *note 格式字符串语法: de0. 等章节，比如
‘"{:04d}".format(144)’ 会生成 ‘'0144'’ ， ‘"{:.3f}".format(1.0/3.0)’ 则
会生成 ‘'0.333'’。


File: python.info,  Node: 如何修改字符串？,  Next: 如何使用字符串调用函数/方法？,  Prev: 如何将数字转换为字符串？,  Up: 数字和字符串

11.2.3.6 如何修改字符串？
.........................

无法修改，因为字符串是不可变对象。 在大多数情况下，只要将各个部分组合起
来构造出一个新字符串即可。如果需要一个能原地修改 Unicode 数据的对象，可
以试试 *note io.StringIO: 91a. 对象或 *note array: 6. 模块：

     >>> 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'


File: python.info,  Node: 如何使用字符串调用函数/方法？,  Next: 是否有与Perl 的chomp 等效的方法，用于从字符串中删除尾随换行符？,  Prev: 如何修改字符串？,  Up: 数字和字符串

11.2.3.7 如何使用字符串调用函数/方法？
......................................

有多种技巧可供选择。

   * 最好的做法是采用一个字典，将字符串映射为函数。其主要优势就是字符串
     不必与函数名一样。这也是用来模拟 case 结构的主要技巧：

          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

   * 利用内置函数 *note getattr(): 54b. ：

          import foo
          getattr(foo, 'bar')()

     请注意 *note getattr(): 54b. 可用于任何对象，包括类、类实例、模块等
     等。

     标准库就多次使用了这个技巧，例如：

          class Foo:
              def do_foo(self):
                  ...

              def do_bar(self):
                  ...

          f = getattr(foo_instance, 'do_' + opname)
          f()

   * 用 *note locals(): 556. 解析出函数名：

          def myFunc():
              print("hello")

          fname = "myFunc"

          f = locals()[fname]
          f()


File: python.info,  Node: 是否有与Perl 的chomp 等效的方法，用于从字符串中删除尾随换行符？,  Next: 是否有 scanf 或 sscanf 的等价函数？,  Prev: 如何使用字符串调用函数/方法？,  Up: 数字和字符串

11.2.3.8 是否有与Perl 的chomp() 等效的方法，用于从字符串中删除尾随换行符？
..........................................................................

可以使用 ‘S.rstrip("\r\n")’ 从字符串 ‘S’ 的末尾删除所有的换行符，而不删
除其他尾随空格。如果字符串 ‘S’ 表示多行，且末尾有几个空行，则将删除所有
空行的换行符：

     >>> lines = ("line 1 \r\n"
     ...          "\r\n"
     ...          "\r\n")
     >>> lines.rstrip("\n\r")
     'line 1 '

由于通常只在一次读取一行文本时才需要这样做，所以使用 ‘S.rstrip()’ 这种方
式工作得很好。


File: python.info,  Node: 是否有 scanf 或 sscanf 的等价函数？,  Next: 'UnicodeDecodeError' 或 'UnicodeEncodeError' 错误是什么意思？,  Prev: 是否有与Perl 的chomp 等效的方法，用于从字符串中删除尾随换行符？,  Up: 数字和字符串

11.2.3.9 是否有 scanf() 或 sscanf() 的等价函数？
................................................

没有。

如果要对简单的输入进行解析，最容易的做法通常是利用字符串对象的 *note
split(): 890. 方法将一行按空白符分隔拆分为多个单词，然后用 *note int():
204. 或 *note float(): 1fd. 将十进制数字符串转换为数字值。 ‘split()’ 支
持可选的 "sep" 形参，适用于分隔符不用空白符的情况。

如果要对更复杂的输入进行解析，那么正则表达式要比 C 语言的 ‘sscanf()’ 更
强大，也更合适。


File: python.info,  Node: 'UnicodeDecodeError' 或 'UnicodeEncodeError' 错误是什么意思？,  Prev: 是否有 scanf 或 sscanf 的等价函数？,  Up: 数字和字符串

11.2.3.10 ’UnicodeDecodeError’ 或 ’UnicodeEncodeError’ 错误是什么意思？
.......................................................................

见 *note Unicode 指南: d04.


File: python.info,  Node: 性能<4>,  Next: 序列（元组/列表）,  Prev: 数字和字符串,  Up: 程式開發常見問答集

11.2.4 性能
-----------

* Menu:

* 我的程序太慢了。该如何加快速度？::
* 将多个字符串连接在一起的最有效方法是什么？::


File: python.info,  Node: 我的程序太慢了。该如何加快速度？,  Next: 将多个字符串连接在一起的最有效方法是什么？,  Up: 性能<4>

11.2.4.1 我的程序太慢了。该如何加快速度？
.........................................

总的来说，这是个棘手的问题。在进一步讨论之前，首先应该记住以下几件事：

   * 不同的 Python 实现具有不同的性能特点。 本 FAQ 着重解答的是 *note
     CPython: 1569.。

   * 不同操作系统可能会有不同表现，尤其是涉及 I/O 和多线程时。

   * 在尝试优化代码 `之前' ，务必要先找出程序中的热点（请参阅 *note
     profile: d3. 模块）。

   * 编写基准测试脚本，在寻求性能提升的过程中就能实现快速迭代（请参阅
     *note timeit: 10d. 模块）。

   * 强烈建议首先要保证足够高的代码测试覆盖率（通过单元测试或其他技术）
     ，因为复杂的优化有可能会导致代码回退。

话虽如此，Python 代码的提速还是有很多技巧的。以下列出了一些普适性的原则
，对于让性能达到可接受的水平会有很大帮助：

   * 相较于试图对全部代码铺开做微观优化，优化算法（或换用更快的算法）可
     以产出更大的收益。

   * 使用正确的数据结构。参考 *note 內建型態: 1748. 和 *note
     collections: 1d. 模块的文档。

   * 如果标准库已为某些操作提供了基础函数，则可能（当然不能保证）比所有
     自编的函数都要快。对于用 C 语言编写的基础函数则更是如此，比如内置函
     数和一些扩展类型。例如，一定要用内置方法 *note list.sort(): 547. 或
     *note sorted(): 546. 函数进行排序（某些高级用法的示例请参阅 *note
     如何排序: 1737. ）。

   * 抽象往往会造成中间层，并会迫使解释器执行更多的操作。如果抽象出来的
     中间层级太多，工作量超过了要完成的有效任务，那么程序就会被拖慢。应
     该避免过度的抽象，而且往往也会对可读性产生不利影响，特别是当函数或
     方法比较小的时候。

如果你已经达到纯 Python 允许的限制，那么有一些工具可以让你走得更远。 例
如， Cython(1) 可以将稍微修改的 Python 代码版本编译为 C 扩展，并且可以在
许多不同的平台上使用。 Cython 可以利用编译（和可选的类型注释）来使代码明
显快于解释运行时的速度。 如果您对 C 编程技能有信心，也可以自己 *note 编写
C 扩展模块: 1332. 。

也參考
......

专门介绍 性能提示(2) 的wiki页面。

   ---------- Footnotes ----------

   (1) http://cython.org

   (2) https://wiki.python.org/moin/PythonSpeed/PerformanceTips


File: python.info,  Node: 将多个字符串连接在一起的最有效方法是什么？,  Prev: 我的程序太慢了。该如何加快速度？,  Up: 性能<4>

11.2.4.2 将多个字符串连接在一起的最有效方法是什么？
...................................................

*note str: 205. 和 *note bytes: 172. 对象是不可变的，因此连接多个字符串
的效率会很低，因为每次连接都会创建一个新的对象。一般情况下，总耗时与字符
串总长是二次方的关系。

如果要连接多个 *note str: 205. 对象，通常推荐的方案是先全部放入列表，最
后再调用 *note str.join(): 1766. ：

     chunks = []
     for s in my_strings:
         chunks.append(s)
     result = ''.join(chunks)

（还有一种合理高效的习惯做法，就是利用 *note io.StringIO: 91a. ）

如果要连接多个 *note bytes: 172. 对象，推荐做法是用 *note bytearray:
173. 对象的原地连接操作（ ‘+=’ 运算符）追加数据：

     result = bytearray()
     for b in my_bytes_objects:
         result += b


File: python.info,  Node: 序列（元组/列表）,  Next: 对象,  Prev: 性能<4>,  Up: 程式開發常見問答集

11.2.5 序列（元组/列表）
------------------------

* Menu:

* 如何在元组和列表之间进行转换？::
* 什么是负数索引？::
* 序列如何以逆序遍历？::
* 如何从列表中删除重复项？::
* 如何从列表中删除多个项？::
* 如何在 Python 中创建数组？::
* 如何创建多维列表？::
* 如何将方法应用于一系列对象？::
* 为什么 a_tuple[i] += ['item'] 会引发异常？::
* 我想做一个复杂的排序：能用 Python 进行施瓦茨变换吗？::
* 如何根据另一个列表的值对某列表进行排序？::


File: python.info,  Node: 如何在元组和列表之间进行转换？,  Next: 什么是负数索引？,  Up: 序列（元组/列表）

11.2.5.1 如何在元组和列表之间进行转换？
.......................................

类型构造器 ‘tuple(seq)’ 可将任意序列（实际上是任意可迭代对象）转换为数据
项和顺序均不变的元组。

例如，‘tuple([1, 2, 3])’ 会生成 ‘(1, 2, 3)’ ， ‘tuple('abc')’ 则会生成
‘('a', 'b', 'c')’ 。 如果参数就是元组，则不会创建副本而是返回同一对象，
因此如果无法确定某个对象是否为元组时，直接调用 *note tuple(): 1a2. 也没
什么代价。

类型构造器 ‘list(seq)’ 可将任意序列或可迭代对象转换为数据项和顺序均不变
的列表。例如，‘list((1, 2, 3))’ 会生成 ‘[1, 2, 3]’ 而 ‘list('abc')’ 则会
生成 ‘['a', 'b', 'c']’。如果参数即为列表，则会像 ‘seq[:]’ 那样创建一个副
本。


File: python.info,  Node: 什么是负数索引？,  Next: 序列如何以逆序遍历？,  Prev: 如何在元组和列表之间进行转换？,  Up: 序列（元组/列表）

11.2.5.2 什么是负数索引？
.........................

Python 序列的索引可以是正数或负数。索引为正数时，0 是第一个索引值， 1 为
第二个，依此类推。索引为负数时，-1 为倒数第一个索引值，-2 为倒数第二个，
依此类推。可以认为 ‘seq[-n]’ 就相当于 ‘seq[len(seq)-n]’。

使用负数序号有时会很方便。 例如 ‘S[:-1]’ 就是原字符串去掉最后一个字符，
这可以用来移除某个字符串末尾的换行符。


File: python.info,  Node: 序列如何以逆序遍历？,  Next: 如何从列表中删除重复项？,  Prev: 什么是负数索引？,  Up: 序列（元组/列表）

11.2.5.3 序列如何以逆序遍历？
.............................

使用内置函数 *note reversed(): 2c6. ：

     for x in reversed(sequence):
         ...  # do something with x ...

原序列不会变化，而是构建一个逆序的新副本以供遍历。


File: python.info,  Node: 如何从列表中删除重复项？,  Next: 如何从列表中删除多个项？,  Prev: 序列如何以逆序遍历？,  Up: 序列（元组/列表）

11.2.5.4 如何从列表中删除重复项？
.................................

许多完成此操作的的详细介绍，可参阅 Python Cookbook：

     ‘https://code.activestate.com/recipes/52560/’

如果列表允许重新排序，不妨先对其排序，然后从列表末尾开始扫描，依次删除重
复项：

     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]

如果列表的所有元素都能用作集合的键（即都是 *note hashable: 276. ），以下
做法速度往往更快：

     mylist = list(set(mylist))

以上操作会将列表转换为集合，从而删除重复项，然后返回成列表。


File: python.info,  Node: 如何从列表中删除多个项？,  Next: 如何在 Python 中创建数组？,  Prev: 如何从列表中删除重复项？,  Up: 序列（元组/列表）

11.2.5.5 如何从列表中删除多个项？
.................................

类似于删除重复项，一种做法是反向遍历并根据条件删除。不过更简单快速的做法
就是切片替换操作，采用隐式或显式的正向迭代遍历。以下是三种变体写法：

     mylist[:] = filter(keep_function, mylist)
     mylist[:] = (x for x in mylist if keep_condition)
     mylist[:] = [x for x in mylist if keep_condition]

列表推导式可能是最快的。


File: python.info,  Node: 如何在 Python 中创建数组？,  Next: 如何创建多维列表？,  Prev: 如何从列表中删除多个项？,  Up: 序列（元组/列表）

11.2.5.6 如何在 Python 中创建数组？
...................................

用列表：

     ["this", 1, "is", "an", "array"]

列表在时间复杂度方面相当于 C 或 Pascal 的数组；主要区别在于，Python 列表
可以包含多种不同类型的对象。

The ‘array’ module also provides methods for creating arrays of fixed
types with compact representations, but they are slower to index than
lists.  Also note that NumPy and other third party packages define
array-like structures with various characteristics as well.

若要得到 Lisp 风格的列表，可以用元组模拟 cons 元素：

     lisp_list = ("like",  ("this",  ("example", None) ) )

若要具备可变性，可以不用元组而是用列表。模拟 lisp car 函数的是
‘lisp_list[0]’ ，模拟 cdr 函数的是 ‘lisp_list[1]’ 。仅当真正必要时才会这
么用，因为通常这种用法要比 Python 列表慢得多。


File: python.info,  Node: 如何创建多维列表？,  Next: 如何将方法应用于一系列对象？,  Prev: 如何在 Python 中创建数组？,  Up: 序列（元组/列表）

11.2.5.7 如何创建多维列表？
...........................

多维数组或许会用以下方式建立：

     >>> A = [[None] * 2] * 3

打印出来貌似没错：

     >>> A
     [[None, None], [None, None], [None, None]]

但如果给某一项赋值，结果会同时在多个位置体现出来：

     >>> A[0][0] = 5
     >>> A
     [[5, None], [5, None], [5, None]]

原因在于用 ‘*’ 对列表执行重复操作并不会创建副本，而只是创建现有对象的引
用。 ‘*3’ 创建的是包含 3 个引用的列表，每个引用指向的是同一个长度为 2 的
列表。1 处改动会体现在所有地方，这一定不是应有的方案。

推荐做法是先创建一个所需长度的列表，然后将每个元素都填充为一个新建列表。

     A = [None] * 3
     for i in range(3):
         A[i] = [None] * 2

以上生成了一个包含 3 个列表的列表，每个子列表的长度为 2。也可以采用列表
推导式：

     w, h = 2, 3
     A = [[None] * w for i in range(h)]

或者你还可以使用提供矩阵类型的扩展包；其中最著名的是 NumPy(1)。

   ---------- Footnotes ----------

   (1) http://www.numpy.org/


File: python.info,  Node: 如何将方法应用于一系列对象？,  Next: 为什么 a_tuple[i] += ['item'] 会引发异常？,  Prev: 如何创建多维列表？,  Up: 序列（元组/列表）

11.2.5.8 如何将方法应用于一系列对象？
.....................................

可以使用列表推导式：

     result = [obj.method() for obj in mylist]


File: python.info,  Node: 为什么 a_tuple[i] += ['item'] 会引发异常？,  Next: 我想做一个复杂的排序：能用 Python 进行施瓦茨变换吗？,  Prev: 如何将方法应用于一系列对象？,  Up: 序列（元组/列表）

11.2.5.9 为什么 a_tuple[i] += [’item’] 会引发异常？
...................................................

这是由两个因素共同导致的，一是增强赋值运算符属于 `赋值' 运算符，二是
Python 可变和不可变对象之间的差别。

只要元组的元素指向可变对象，这时对元素进行增强赋值，那么这里介绍的内容都
是适用的。在此只以 ‘list’ 和 ‘+=’ 举例。

如果你写成这样:

     >>> a_tuple = (1, 2)
     >>> a_tuple[0] += 1
     Traceback (most recent call last):
        ...
     TypeError: 'tuple' object does not support item assignment

触发异常的原因显而易见： ‘1’ 会与指向（‘1’）的对象 ‘a_tuple[0]’ 相加，生
成结果对象 ‘2’，但在试图将运算结果 ‘2’ 赋值给元组的 ‘0’ 号元素时就会报错
，因为元组元素的指向无法更改。

其实在幕后，上述增强赋值语句的执行过程大致如下：

     >>> result = a_tuple[0] + 1
     >>> a_tuple[0] = result
     Traceback (most recent call last):
       ...
     TypeError: 'tuple' object does not support item assignment

由于元组是不可变的，因此赋值这步会引发错误。

如果写成以下这样：

     >>> a_tuple = (['foo'], 'bar')
     >>> a_tuple[0] += ['item']
     Traceback (most recent call last):
       ...
     TypeError: 'tuple' object does not support item assignment

这时触发异常会令人略感惊讶，更让人吃惊的是虽有报错，但加法操作却生效了：

     >>> a_tuple[0]
     ['foo', 'item']

要明白为何会这样，需要知道 (a) 如果一个对象实现了 ‘__iadd__’ 魔法方法，
在执行 ‘+=’ 增强赋值时就会调用它，并采纳其返回值；(b) 对于列表而言，
‘__iadd__’ 相当于在列表上调用 ‘extend’ 并返回该列表。因此对于列表可以说
‘+=’ 就是 ‘list.extend’ 的“快捷方式”：

     >>> a_list = []
     >>> a_list += [1]
     >>> a_list
     [1]

这相当于：

     >>> result = a_list.__iadd__([1])
     >>> a_list = result

a_list 所引用的对象已被修改，而引用被修改对象的指针又重新被赋值给
‘a_list’。 赋值的最终结果没有变化，因为它是引用 ‘a_list’ 之前所引用的同
一对象的指针，但仍然发生了赋值操作。

因此，在此元组示例中，发生的事情等同于：

     >>> result = a_tuple[0].__iadd__(['item'])
     >>> a_tuple[0] = result
     Traceback (most recent call last):
       ...
     TypeError: 'tuple' object does not support item assignment

‘__iadd__’ 成功执行，因此列表得到了扩充，但是虽然 ‘result’ 指向了
‘a_tuple[0]’ 已经指向的同一对象，最后的赋值仍然导致了报错，因为元组是不
可变的。


File: python.info,  Node: 我想做一个复杂的排序：能用 Python 进行施瓦茨变换吗？,  Next: 如何根据另一个列表的值对某列表进行排序？,  Prev: 为什么 a_tuple[i] += ['item'] 会引发异常？,  Up: 序列（元组/列表）

11.2.5.10 我想做一个复杂的排序：能用 Python 进行施瓦茨变换吗？
..............................................................

归功于 Perl 社区的 Randal Schwartz，该技术根据度量值对列表进行排序，该度
量值将每个元素映射为“顺序值”。在 Python 中，请利用 *note list.sort():
547. 方法的 ‘key’ 参数：

     Isorted = L[:]
     Isorted.sort(key=lambda s: int(s[10:15]))


File: python.info,  Node: 如何根据另一个列表的值对某列表进行排序？,  Prev: 我想做一个复杂的排序：能用 Python 进行施瓦茨变换吗？,  Up: 序列（元组/列表）

11.2.5.11 如何根据另一个列表的值对某列表进行排序？
..................................................

将它们合并到元组的迭代器中，对结果列表进行排序，然后选择所需的元素。

     >>> 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']


File: python.info,  Node: 对象,  Next: 模块<2>,  Prev: 序列（元组/列表）,  Up: 程式開發常見問答集

11.2.6 对象
-----------

* Menu:

* 什么是类？::
* 什么是方法？::
* 什么是 self ？::
* 如何检查对象是否为给定类或其子类的一个实例？::
* 什么是委托？::
* 如何在派生类中调用被重载的基类方法?::
* 如何让代码更容易对基类进行修改？::
* 如何创建静态类数据和静态类方法？::
* 在 Python 中如何重载构造函数（或方法）？::
* 在用 __spam 的时候得到一个类似 _SomeClassName__spam 的错误信息。::
* 类定义了 __del__ 方法，但是删除对象时没有调用它。::
* 如何获取给定类的所有实例的列表？::
* 为什么 id() 的结果看起来不是唯一的？: 为什么 id 的结果看起来不是唯一的？.
* 什么情况下可以依靠 is 运算符进行对象的身份相等性测试？::
* How can a subclass control what data is stored in an immutable instance?::


File: python.info,  Node: 什么是类？,  Next: 什么是方法？,  Up: 对象

11.2.6.1 什么是类？
...................

类是通过执行 class 语句创建的某种对象的类型。创建实例对象时，用 Class 对
象作为模板，实例对象既包含了数据（属性），又包含了数据类型特有的代码（方
法）。

类可以基于一个或多个其他类（称之为基类）进行创建。基类的属性和方法都得以
继承。这样对象模型就可以通过继承不断地进行细化。比如通用的 ‘Mailbox’ 类
提供了邮箱的基本访问方法.，它的子类 ‘MboxMailbox’、 ‘MaildirMailbox’、
‘OutlookMailbox’ 则能够处理各种特定的邮箱格式。


File: python.info,  Node: 什么是方法？,  Next: 什么是 self ？,  Prev: 什么是类？,  Up: 对象

11.2.6.2 什么是方法？
.....................

方法是属于对象的函数，对于对象 ‘x’ ，通常以 ‘x.name(arguments...)’ 的形
式调用。方法以函数的形式给出定义，位于类的定义内：

     class C:
         def meth(self, arg):
             return arg * 2 + self.attribute


File: python.info,  Node: 什么是 self ？,  Next: 如何检查对象是否为给定类或其子类的一个实例？,  Prev: 什么是方法？,  Up: 对象

11.2.6.3 什么是 self ？
.......................

Self 只是方法的第一个参数的习惯性名称。假定某个类中有个方法定义为
‘meth(self, a, b, c)’ ，则其实例 ‘x’ 应以 ‘x.meth(a, b, c)’ 的形式进行调
用；而被调用的方法则应视其为做了 ‘meth(x, a, b, c)’ 形式的调用。

另请参阅 *note 为什么必须在方法定义和调用中显式使用“self”？: 449e. 。


File: python.info,  Node: 如何检查对象是否为给定类或其子类的一个实例？,  Next: 什么是委托？,  Prev: 什么是 self ？,  Up: 对象

11.2.6.4 如何检查对象是否为给定类或其子类的一个实例？
.....................................................

可使用内置函数 ‘isinstance(obj, cls)’。可以检测对象是否属于多个类中某一
个的实例，只要把单个类换成元组即可，比如 ‘isinstance(obj, (class1,
class2, ...))’，还可以检查对象是否属于某个 Python 内置类型，例如
‘isinstance(obj, str)’ 或 ‘isinstance(obj, (int, float, complex))’。

请注意 *note isinstance(): 551. 还会检测派生自 *note abstract base
class: c05. 的虚继承。 因此对于已注册的类，即便没有直接或间接继承自抽象
基类，对抽象基类的检测都将返回 ‘True’ 。要想检测“真正的继承”，请扫描类的
*note MRO: 29c7.:

     from collections.abc import Mapping

     class P:
          pass

     class C(P):
         pass

     Mapping.register(P)

     >>> 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

请注意，大多数程序不会经常用 *note isinstance(): 551. 对用户自定义类进行
检测。 如果是自已开发的类，更合适的面向对象编程风格应该是在类中定义多种
方法，以封装特定的行为，而不是检查对象属于什么类再据此干不同的事。假定有
如下执行某些操作的函数:

     def search(obj):
         if isinstance(obj, Mailbox):
             ...  # code to search a mailbox
         elif isinstance(obj, Document):
             ...  # code to search a document
         elif ...

更好的方法是在所有类上定义一个 ‘search()’ 方法，然后调用它：

     class Mailbox:
         def search(self):
             ...  # code to search a mailbox

     class Document:
         def search(self):
             ...  # code to search a document

     obj.search()


File: python.info,  Node: 什么是委托？,  Next: 如何在派生类中调用被重载的基类方法?,  Prev: 如何检查对象是否为给定类或其子类的一个实例？,  Up: 对象

11.2.6.5 什么是委托？
.....................

委托是一种面向对象的技术（也称为设计模式）。假设对象 ‘x’ 已经存在，现在
想要改变其某个方法的行为。可以创建一个新类，其中提供了所需修改方法的新实
现，而将所有其他方法都委托给 ‘x’ 的对应方法。

Python 程序员可以轻松实现委托。比如以下实现了一个类似于文件的类，只是会
把所有写入的数据转换为大写：

     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)

这里 ‘UpperOut’ 类重新定义了 ‘write()’ 方法，在调用下层的
‘self._outfile.write()’ 方法之前，会将参数字符串转换为大写。其他所有方法
则都被委托给下层的 ‘self._outfile’ 对象。委托是通过 ‘__getattr__’ 方法完
成的；请参阅 *note 语言参考: 156c. 了解有关控制属性访问的更多信息。

请注意，更常见情况下，委托可能会变得比较棘手。如果属性既需要写入又需要读
取，那么类还必须定义 *note __setattr__(): eee. 方法，而这时就必须十分的
小心。基础的 *note __setattr__(): eee. 实现代码大致如下：

     class X:
         ...
         def __setattr__(self, name, value):
             self.__dict__[name] = value
         ...

大多数 *note __setattr__(): eee. 实现必须修改 ‘self.__dict__’ 来为自身保
存局部状态，而不至于引起无限递归。


File: python.info,  Node: 如何在派生类中调用被重载的基类方法?,  Next: 如何让代码更容易对基类进行修改？,  Prev: 什么是委托？,  Up: 对象

11.2.6.6 如何在派生类中调用被重载的基类方法?
............................................

使用内置的 *note super(): 5dd. 函数：

     class Derived(Base):
         def meth(self):
             super(Derived, self).meth()

如果是 Python 3.0 之前的版本，可能用的还是传统类：对于诸如 ‘class
Derived(Base): ...’ 之类的类定义，可以用 ‘Base.meth(self, arguments...)’
的形式调用 ‘Base’ (或 ‘Base’ 的某个基类）中定义的方法 ‘meth()’ 。这里，
‘Base.meth’ 是一个未绑定的方法，因此需要给出 ‘self’ 参数。


File: python.info,  Node: 如何让代码更容易对基类进行修改？,  Next: 如何创建静态类数据和静态类方法？,  Prev: 如何在派生类中调用被重载的基类方法?,  Up: 对象

11.2.6.7 如何让代码更容易对基类进行修改？
.........................................

可以为基类赋一个别名并基于该别名进行派生。这样只要修改赋给该别名的值即可
。顺便提一下，如要动态地确定（例如根据可用的资源）该使用哪个基类，这个技
巧也非常方便。例如：

     class Base:
         ...

     BaseAlias = Base

     class Derived(BaseAlias):
         ...


File: python.info,  Node: 如何创建静态类数据和静态类方法？,  Next: 在 Python 中如何重载构造函数（或方法）？,  Prev: 如何让代码更容易对基类进行修改？,  Up: 对象

11.2.6.8 如何创建静态类数据和静态类方法？
.........................................

Python 支持静态数据和静态方法（以 C++ 或 Java 的定义而言）。

静态数据只需定义一个类属性即可。若要为属性赋新值，则必须在赋值时显式使用
类名：

     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

对于所有符合 ‘isinstance(c, C)’ 的 ‘c’， ‘c.count’ 也同样指向 ‘C.count’
，除非被 ‘c’ 自身重载，或者被从 ‘c.__class__’ 回溯到基类 ‘C’ 的搜索路径
上的某个类所重载。

注意：在 C 的某个方法内部，像 ‘self.count = 42’ 这样的赋值将在 ‘self’ 自
身的字典中新建一个名为 "count" 的不相关实例。 想要重新绑定类静态数据名称
就必须总是指明类名，无论是在方法内部还是外部:

     C.count = 314

Python 支持静态方法：

     class C:
         @staticmethod
         def static(arg1, arg2, arg3):
             # No 'self' parameter!
             ...

不过为了获得静态方法的效果，还有一种做法直接得多，也即使用模块级函数即可
：

     def getcount():
         return C.count

如果代码的结构化比较充分，每个模块只定义了一个类（或者多个类的层次关系密
切相关），那就具备了应有的封装。


File: python.info,  Node: 在 Python 中如何重载构造函数（或方法）？,  Next: 在用 __spam 的时候得到一个类似 _SomeClassName__spam 的错误信息。,  Prev: 如何创建静态类数据和静态类方法？,  Up: 对象

11.2.6.9 在 Python 中如何重载构造函数（或方法）？
.................................................

这个答案实际上适用于所有方法，但问题通常首先出现于构造函数的应用场景中。

在 C++ 中，代码会如下所示：

     class C {
         C() { cout << "No arguments\n"; }
         C(int i) { cout << "Argument is " << i << "\n"; }
     }

在 Python 中，只能编写一个构造函数，并用默认参数捕获所有情况。例如：

     class C:
         def __init__(self, i=None):
             if i is None:
                 print("No arguments")
             else:
                 print("Argument is", i)

这不完全等同，但在实践中足够接近。

也可以试试采用变长参数列表，例如：

     def __init__(self, *args):
         ...

上述做法同样适用于所有方法定义。


File: python.info,  Node: 在用 __spam 的时候得到一个类似 _SomeClassName__spam 的错误信息。,  Next: 类定义了 __del__ 方法，但是删除对象时没有调用它。,  Prev: 在 Python 中如何重载构造函数（或方法）？,  Up: 对象

11.2.6.10 在用 __spam 的时候得到一个类似 _SomeClassName__spam 的错误信息。
..........................................................................

以双下划线打头的变量名会被“破坏”，以便以一种简单高效的方式定义类私有变量
。任何形式为 ‘__spam’ 的标识符（至少前缀两个下划线，至多后缀一个下划线）
文本均会被替换为 ‘_classname__spam’，其中 ‘classname’ 为去除了全部前缀下
划线的当前类名称。

这并不能保证私密性：外部用户仍然可以访问 "_classname__spam" 属性，私有变
量值也在对象的 ‘__dict__’ 中可见。 许多 Python 程序员根本不操心要去使用
私有变量名。


File: python.info,  Node: 类定义了 __del__ 方法，但是删除对象时没有调用它。,  Next: 如何获取给定类的所有实例的列表？,  Prev: 在用 __spam 的时候得到一个类似 _SomeClassName__spam 的错误信息。,  Up: 对象

11.2.6.11 类定义了 __del__ 方法，但是删除对象时没有调用它。
...........................................................

这有几个可能的原因。

del 语句不一定调用 *note __del__(): a04. —— 它只是减少对象的引用计数，如
果（引用计数）达到零，才会调用 *note __del__(): a04.。

如果数据结构包含循环链接（比如树的每个子节点都带有父节点的引用，而每个父
节点也带有子节点的列表），则引用计数永远不会回零。尽管 Python 偶尔会用某
种算法检测这种循环引用，但在数据结构的最后一条引用消失之后，垃圾收集器可
能还要过段时间才会运行，因此 *note __del__(): a04. 方法可能会在不方便和
随机的时刻被调用。这对于重现一个问题，是非常不方便的。更糟糕的是，各个对
象的 *note __del__(): a04. 方法是以随机顺序执行的。虽然可以运行 *note
gc.collect(): 35b. 来强制执行垃圾回收工作，但 `仍会存在' 一些对象永远不
会被回收的失控情况。

尽管有垃圾回收器的存在，但为对象定义显式的 ‘close()’ 方法，只要一用完即
可供调用，这依然是一个好主意。这样 ‘close()’ 方法即可删除引用子对象的属
性。请勿直接调用 *note __del__(): a04. —— 而 *note __del__(): a04. 应该
调用 ‘close()’，并且应能确保可以对同一对象多次调用 ‘close()’ 。

另一种避免循环引用的做法是利用 *note weakref: 131. 模块，该模块允许指向
对象但不增加其引用计数。例如，树状数据结构应该对父节点和同级节点使用弱引
用（如果真要用的话！）

最后提一下，如果 *note __del__(): a04. 方法引发了异常，会将警告消息打印
到 *note sys.stderr: 1ea. 。


File: python.info,  Node: 如何获取给定类的所有实例的列表？,  Next: 为什么 id 的结果看起来不是唯一的？,  Prev: 类定义了 __del__ 方法，但是删除对象时没有调用它。,  Up: 对象

11.2.6.12 如何获取给定类的所有实例的列表？
..........................................

Python 不会记录类（或内置类型）的实例。可以在类的构造函数中编写代码，通
过保留每个实例的弱引用列表来跟踪所有实例。


File: python.info,  Node: 为什么 id 的结果看起来不是唯一的？,  Next: 什么情况下可以依靠 is 运算符进行对象的身份相等性测试？,  Prev: 如何获取给定类的所有实例的列表？,  Up: 对象

11.2.6.13 为什么 ‘id()’ 的结果看起来不是唯一的？
................................................

*note id(): e4b. 返回一个整数，该整数在对象的生命周期内保证是唯一的。 因
为在 CPython 中，这是对象的内存地址，所以经常发生在从内存中删除对象之后
，下一个新创建的对象被分配在内存中的相同位置。 这个例子说明了这一点：

     >>> id(1000)
     13901272
     >>> id(2000)
     13901272

这两个 id 属于不同的整数对象，之前先创建了对象，执行 ‘id()’ 调用后又立即
被删除了。若要确保检测 id 时的对象仍处于活动状态，请再创建一个对该对象的
引用：

     >>> a = 1000; b = 2000
     >>> id(a)
     13901272
     >>> id(b)
     13891296


File: python.info,  Node: 什么情况下可以依靠 is 运算符进行对象的身份相等性测试？,  Next: How can a subclass control what data is stored in an immutable instance?,  Prev: 为什么 id 的结果看起来不是唯一的？,  Up: 对象

11.2.6.14 什么情况下可以依靠 `is' 运算符进行对象的身份相等性测试？
..................................................................

‘is’ 运算符可用于测试对象的身份相等性。‘a is b’ 等价于 ‘id(a) == id(b)’。

身份相等性最重要的特性就是对象总是等同于自身，‘a is a’ 一定返回 ‘True’。
身份相等性测试的速度通常比相等性测试要快。而且与相等性测试不一样，身份相
等性测试会确保返回布尔值 ‘True’ 或 ‘False’。

但是，身份相等性测试 `只能' 在对象身份确定的场景下才可替代相等性测试。一
般来说，有以下3种情况对象身份是可以确定的：

1） 赋值操作创建了新的名称但没有改变对象身份。 在赋值操作 ‘new = old’ 之
后，可以保证 ‘new is old’。

2） 将对象置入存放对象引用的容器，对象身份不会改变。在列表赋值操作 ‘s[0]
= x’ 之后，可以保证 ‘s[0] is x’。

3） 单例对象，也即该对象只能存在一个实例。在赋值操作 ‘a = None’ 和 ‘b =
None’ 之后，可以保证 ‘a is b’，因为 ‘None’ 是单例对象。

其他大多数情况下，都不建议使用身份相等性测试，而应采用相等性测试。尤其是
不应将身份相等性测试用于检测常量值，例如 *note int: 204. 和 *note str:
205.，因为他们并不一定是单例对象：

     >>> a = 1000
     >>> b = 500
     >>> c = b + 500
     >>> a is c
     False

     >>> a = 'Python'
     >>> b = 'Py'
     >>> c = b + 'thon'
     >>> a is c
     False

同样地，可变容器的新实例，对象身份一定不同：

     >>> a = []
     >>> b = []
     >>> a is b
     False

在标准库代码中，给出了一些正确使用对象身份测试的常见模式：

1） 正如 PEP 8(1) 所推荐的，对象身份测试是 ‘None’ 值的推荐检测方式。这样
的代码读起来就像自然的英文，并可以避免与其他可能为布尔值且计算结果为
False 的对象相混淆。

2） 如果 ‘None’ 也是有效的输入值，则可选参数的检测就可能比较棘手。 这时
可以创建一个单例哨兵对象，要确保与其他对象都不相同。例如，下面是一个类似
*note dict.pop(): 180d. 的方法：

     _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

3） 编写容器的实现代码时，有时需要用对象身份测试来加强相等性检测。这样代
码就不会被 ‘float('NaN')’ 这类与自身不相等的对象所干扰。

例如，以下是 ‘collections.abc.Sequence.__contains__()’ 的实现代码：

     def __contains__(self, value):
         for v in self:
             if v is value or v == value:
                 return True
         return False

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0008


File: python.info,  Node: How can a subclass control what data is stored in an immutable instance?,  Prev: 什么情况下可以依靠 is 运算符进行对象的身份相等性测试？,  Up: 对象

11.2.6.15 How can a subclass control what data is stored in an immutable instance?
..................................................................................

When subclassing an immutable type, override the *note __new__(): 974.
method instead of the *note __init__(): e23. method.  The latter only
runs `after' an instance is created, which is too late to alter data in
an immutable instance.

All of these immutable classes have a different signature than their
parent class:

     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 = ''.join([c for c in s if c.isalnum() or c == '-'])
             return super().__new__(cls, s)

The classes can be used like this:

     >>> FirstOfMonthDate(2012, 2, 14)
     FirstOfMonthDate(2012, 2, 1)
     >>> NamedInt('ten')
     10
     >>> NamedInt(20)
     20
     >>> TitleStr('Blog: Why Python Rocks')
     'blog-why-python-rocks'


File: python.info,  Node: 模块<2>,  Prev: 对象,  Up: 程式開發常見問答集

11.2.7 模块
-----------

* Menu:

* 如何创建 .pyc 文件？: 如何创建 pyc 文件？.
* 如何找到当前模块名称？::
* 如何让模块相互导入？::
* __import__(’x.y.z’) 返回的是 <module ’x’> ；该如何得到 z 呢？: __import__ 'x y z' 返回的是 <module 'x'> ；该如何得到 z 呢？.
* 对已导入的模块进行了编辑并重新导入，但变动没有得以体现。这是为什么？::


File: python.info,  Node: 如何创建 pyc 文件？,  Next: 如何找到当前模块名称？,  Up: 模块<2>

11.2.7.1 如何创建 .pyc 文件？
.............................

当首次导入模块时（或当前已编译文件创建之后源文件发生了改动），在
‘‘.py‘‘文件所在目录的‘‘__pycache__‘‘子目录下会创建一个包含已编译代码的
‘‘.pyc‘‘文件。该‘‘.pyc‘‘文件的名称开头部分将与‘‘.py‘‘文件名相同，并以
‘‘.pyc‘‘为后缀，中间部分则依据创建它的‘‘python‘‘版本而各不相同。（详见
PEP 3147(1)。）

‘.pyc’ 文件有可能会无法创建，原因之一是源码文件所在的目录存在权限问题，
这样就无法创建 ‘__pycache__’ 子目录。假如以某个用户开发程序而以另一用户
运行程序，就有可能发生权限问题，测试 Web 服务器就属于这种情况。

除非设置了 *note PYTHONDONTWRITEBYTECODE: dff. 环境变量，否则导入模块并
且 Python 能够创建‘‘__pycache__‘‘子目录并把已编译模块写入该子目录（权限
、存储空间等等）时，.pyc 文件就将自动创建。

在最高层级运行的 Python 脚本不会被视为经过了导入操作，因此不会创建
‘.pyc’ 文件。假定有一个最高层级的模块文件 ‘foo.py’，它导入了另一个模块
‘xyz.py’，当运行 ‘foo’ 模块（通过输入 shell 命令 ‘python foo.py’ ），则
会为 ‘xyz’ 创建一个 ‘.pyc’，因为 ‘xyz’ 是被导入的，但不会为 ‘foo’ 创建
‘.pyc’ 文件，因为 ‘foo.py’ 不是被导入的。

若要为 ‘foo’ 创建 ‘.pyc’ 文件 —— 即为未做导入的模块创建 ‘.pyc’ 文件 —— 可
以利用 *note py_compile: d7. 和 *note compileall: 20. 模块。

*note py_compile: d7. 模块能够手动编译任意模块。 一种做法是交互式地使用
该模块中的 ‘compile()’ 函数:

     >>> import py_compile
     >>> py_compile.compile('foo.py')

这将会将 ‘.pyc’ 文件写入与 ‘foo.py’ 相同位置下的 ‘__pycache__’ 子目录（
或者你也可以通过可选参数 ‘cfile’ 来重载该行为）。

还可以用 *note compileall: 20. 模块自动编译一个或多个目录下的所有文件。
只要在命令行提示符中运行 ‘compileall.py’ 并给出要编译的 Python 文件所在
目录路径即可：

     python -m compileall .

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3147


File: python.info,  Node: 如何找到当前模块名称？,  Next: 如何让模块相互导入？,  Prev: 如何创建 pyc 文件？,  Up: 模块<2>

11.2.7.2 如何找到当前模块名称？
...............................

模块可以查看预定义的全局变量 ‘__name__’ 获悉自己的名称。如其值为
‘'__main__'’ ，程序将作为脚本运行。通常，许多通过导入使用的模块同时也提
供命令行接口或自检代码，这些代码只在检测到处于 ‘__name__’ 之后才会执行：

     def main():
         print('Running test...')
         ...

     if __name__ == '__main__':
         main()


File: python.info,  Node: 如何让模块相互导入？,  Next: __import__ 'x y z' 返回的是 <module 'x'> ；该如何得到 z 呢？,  Prev: 如何找到当前模块名称？,  Up: 模块<2>

11.2.7.3 如何让模块相互导入？
.............................

假设有以下模块：

foo.py：

     from bar import bar_var
     foo_var = 1

bar.py：

     from foo import foo_var
     bar_var = 2

问题是解释器将执行以下步骤：

   * 首先导入foo

   * 创建用于foo的空全局变量

   * foo被编译并开始执行

   * foo 导入 bar

   * 创建了用于bar 的空全局变量

   * bar被编译并开始执行

   * bar 导入 foo（这是一个空操作，因为已经有一个名为 foo 的模块）。

   * bar.foo_var = foo.foo_var

最后一步失败了，因为 Python 还没有完成对 foo 的解释，foo 的全局符号字典
仍然是空的。

当你使用 ‘import foo’ ，然后尝试在全局代码中访问 ‘foo.foo_var’ 时，会发
生同样的事情。

这个问题有（至少）三种可能的解决方法。

Guido van Rossum 建议完全避免使用 ‘from <module> import ...’ ，并将所有
代码放在函数中。全局变量和类变量的初始化只应使用常量或内置函数。这意味着
导入模块中的所有内容都以 ‘<module>.<name>’ 的形式引用。

Jim Roskind 建议每个模块都应遵循以下顺序：

   * 导出（全局变量、函数和不需要导入基类的类）

   * ‘import’ 语句

   * 本模块的功能代码（包括根据导入值进行初始化的全局变量）。

Van Rossum doesn’t like this approach much because the imports appear in
a strange place, but it does work.

Matthias Urlichs 建议对代码进行重构，使得递归导入根本就没必要发生。

这些解决方案并不相互排斥。


File: python.info,  Node: __import__ 'x y z' 返回的是 <module 'x'> ；该如何得到 z 呢？,  Next: 对已导入的模块进行了编辑并重新导入，但变动没有得以体现。这是为什么？,  Prev: 如何让模块相互导入？,  Up: 模块<2>

11.2.7.4 __import__(’x.y.z’) 返回的是 <module ’x’> ；该如何得到 z 呢？
......................................................................

不妨考虑换用 *note importlib: 9a. 中的函数 *note import_module(): be6. ：

     z = importlib.import_module('x.y.z')


File: python.info,  Node: 对已导入的模块进行了编辑并重新导入，但变动没有得以体现。这是为什么？,  Prev: __import__ 'x y z' 返回的是 <module 'x'> ；该如何得到 z 呢？,  Up: 模块<2>

11.2.7.5 对已导入的模块进行了编辑并重新导入，但变动没有得以体现。这是为什么？
.............................................................................

出于效率和一致性的原因，Python 仅在第一次导入模块时读取模块文件。否则，
在一个多模块的程序中，每个模块都会导入相同的基础模块，那么基础模块将会被
一而再、再而三地解析。如果要强行重新读取已更改的模块，请执行以下操作：

     import importlib
     import modname
     importlib.reload(modname)

警告：这种技术并非万无一失。尤其是模块包含了以下语句时：

     from modname import some_objects

仍将继续使用前一版的导入对象。如果模块包含了类的定义，并 `不会' 用新的类
定义更新现有的类实例。这样可能会导致以下矛盾的行为：

     >>> 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

只要把类对象的 id 打印出来，问题的性质就会一目了然：

     >>> hex(id(c.__class__))
     '0x7352a0'
     >>> hex(id(cls.C))
     '0x4198d0'


File: python.info,  Node: 设计和历史常见问题,  Next: 函式庫和擴充功能的常見問題,  Prev: 程式開發常見問答集,  Up: Python 常見問題

11.3 设计和历史常见问题
=======================

* 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在列表和元组的末尾允许使用逗号？::


File: python.info,  Node: 为什么Python使用缩进来分组语句？,  Next: 为什么简单的算术运算得到奇怪的结果？,  Up: 设计和历史常见问题

11.3.1 为什么Python使用缩进来分组语句？
---------------------------------------

Guido van Rossum 认为使用缩进进行分组非常优雅，并且大大提高了普通
Python程序的清晰度。大多数人在一段时间后就学会并喜欢上这个功能。

由于没有开始/结束括号，因此解析器感知的分组与人类读者之间不会存在分歧。
偶尔C程序员会遇到像这样的代码片段:

     if (x <= y)
             x++;
             y--;
     z++;

如果条件为真，则只执行 ‘x++’ 语句，但缩进会使你认为情况并非如此。 即使是
经验丰富的 C 程序员有时也会长久地盯着它发呆，不明白为什么在 ‘x > y``时
``y’ 也会减少。

因为没有开始/结束花括号，所以 Python 更不容易发生编码风格冲突。 在 C 中
有许多不同的放置花括号的方式。 在习惯了阅读和编写某种特定风格的代码之后
，当阅读（或被要求编写）另一种风格的代码时通常都会令人感觉有点不舒服）。

许多编码风格将开始/结束括号单独放在一行上。这使得程序相当长，浪费了宝贵
的屏幕空间，使得更难以对程序进行全面的了解。理想情况下，函数应该适合一个
屏幕（例如，20–30行）。 20行Python可以完成比20行C更多的工作。这不仅仅是
由于缺少开始/结束括号 – 缺少声明和高级数据类型也是其中的原因 – 但缩进基
于语法肯定有帮助。


File: python.info,  Node: 为什么简单的算术运算得到奇怪的结果？,  Next: 為何浮點數運算如此不精確?,  Prev: 为什么Python使用缩进来分组语句？,  Up: 设计和历史常见问题

11.3.2 为什么简单的算术运算得到奇怪的结果？
-------------------------------------------

請見下一個問題。


File: python.info,  Node: 為何浮點數運算如此不精確?,  Next: 為何Python字串為不可變動,  Prev: 为什么简单的算术运算得到奇怪的结果？,  Up: 设计和历史常见问题

11.3.3 為何浮點數運算如此不精確?
--------------------------------

用户经常对这样的结果感到惊讶:

     >>> 1.2 - 1.0
     0.19999999999999996

并且认为这是 Python中的一个 bug。其实不是这样。这与 Python 关系不大，而
与底层平台如何处理浮点数字关系更大。

CPython 中的 *note float: 1fd. 类型使用C语言的 ‘double’ 类型进行存储。
*note float: 1fd. 对象的值是以固定的精度（通常为 53 位）存储的二进制浮点
数，由于 Python 使用 C 操作，而后者依赖于处理器中的硬件实现来执行浮点运
算。 这意味着就浮点运算而言，Python 的行为类似于许多流行的语言，包括 C 和
Java。

许多可以轻松地用十进制表示的数字不能用二进制浮点表示。例如，在输入以下语
句后:

     >>> x = 1.2

为 ‘x’ 存储的值是与十进制的值 ‘1.2’ (非常接近) 的近似值，但不完全等于它
。 在典型的机器上，实际存储的值是：

     1.0011001100110011001100110011001100110011001100110011 (binary)

它对应于十进制数值:

     1.1999999999999999555910790149937383830547332763671875 (decimal)

典型的 53 位精度为 Python 浮点数提供了 15-16 位小数的精度。

要获得更完整的解释，请参阅 Python 教程中的 *note 浮点算术: 1456. 一章。


File: python.info,  Node: 為何Python字串為不可變動,  Next: 为什么必须在方法定义和调用中显式使用“self”？,  Prev: 為何浮點數運算如此不精確?,  Up: 设计和历史常见问题

11.3.4 為何Python字串為不可變動
-------------------------------

有許多優點。

一个是性能：知道字符串是不可变的，意味着我们可以在创建时为它分配空间，并
且存储需求是固定不变的。这也是元组和列表之间区别的原因之一。

另一个优点是，Python 中的字符串被视为与数字一样“基本”。 任何动作都不会将
值 8 更改为其他值，在 Python 中，任何动作都不会将字符串 "8" 更改为其他值
。


File: python.info,  Node: 为什么必须在方法定义和调用中显式使用“self”？,  Next: 为什么不能在表达式中赋值？,  Prev: 為何Python字串為不可變動,  Up: 设计和历史常见问题

11.3.5 为什么必须在方法定义和调用中显式使用“self”？
---------------------------------------------------

此構想從Modula-3而來。有許多原因可以說是非常實用。

首先，更明显的显示出，使用的是方法或实例属性而不是局部变量。 阅读
‘self.x’ 或 ‘self.meth()’ 可以清楚地表明，即使您不知道类的定义，也会使用
实例变量或方法。在 C++ 中，可以通过缺少局部变量声明来判断（假设全局变量
很少见或容易识别） —— 但是在 Python 中没有局部变量声明，所以必须查找类定
义才能确定。 一些 C++ 和 Java 编码标准要求实例属性具有 ‘m_’ 前缀，因此这
种显式性在这些语言中仍然有用。

其次，这意味着如果要显式引用或从特定类调用该方法，不需要特殊语法。 在
C++ 中，如果你想使用在派生类中重写基类中的方法，你必须使用 ‘::’ 运算符 –
在 Python 中你可以编写 ‘baseclass.methodname(self, <argument list>)’。 这
对于 *note __init__(): e23. 方法非常有用，特别是在派生类方法想要扩展同名
的基类方法，而必须以某种方式调用基类方法时。

最后，它解决了变量赋值的语法问题：为了 Python 中的局部变量（根据定义！）
在函数体中赋值的那些变量（并且没有明确声明为全局）赋值，就必须以某种方式
告诉解释器一个赋值是为了分配一个实例变量而不是一个局部变量，它最好是通过
语法实现的（出于效率原因）。 C++ 通过声明来做到这一点，但是 Python 没有
声明，仅仅为了这个目的而引入它们会很可惜。 使用显式的 ‘self.var’ 很好地
解决了这个问题。 类似地，对于使用实例变量，必须编写 ‘self.var’ 意味着对
方法内部的非限定名称的引用不必搜索实例的目录。 换句话说，局部变量和实例
变量存在于两个不同的命名空间中，您需要告诉 Python 使用哪个命名空间。


File: python.info,  Node: 为什么不能在表达式中赋值？,  Next: 为什么Python对某些功能（例如list index ）使用方法来实现，而其他功能（例如len List ）使用函数实现？,  Prev: 为什么必须在方法定义和调用中显式使用“self”？,  Up: 设计和历史常见问题

11.3.6 为什么不能在表达式中赋值？
---------------------------------

自 Python 3.8 开始，你能做到的！

赋值表达式使用海象运算符 ‘:=’ 在表达式中为变量赋值:

     while chunk := fp.read(200):
        print(chunk)

请参阅 PEP 572(1) 了解详情。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0572


File: python.info,  Node: 为什么Python对某些功能（例如list index ）使用方法来实现，而其他功能（例如len List ）使用函数实现？,  Next: 为什么 join 是一个字符串方法而不是列表或元组方法？,  Prev: 为什么不能在表达式中赋值？,  Up: 设计和历史常见问题

11.3.7 为什么Python对某些功能（例如list.index()）使用方法来实现，而其他功能（例如len(List)）使用函数实现？
----------------------------------------------------------------------------------------------------------

正如Guido所说：

     (a) 对于某些操作，前缀表示法比后缀更容易阅读 – 前缀（和中缀！）运算
     在数学中有着悠久的传统，就像在视觉上帮助数学家思考问题的记法。比较
     一下我们将 x*(a+b) 这样的公式改写为 x*a+x*b 的容易程度，以及使用原
     始OO符号做相同事情的笨拙程度。

     (b) 当读到写有len(X)的代码时，就知道它要求的是某件东西的长度。这告
     诉我们两件事：结果是一个整数，参数是某种容器。相反，当阅读x.len()时
     ，必须已经知道x是某种实现接口的容器，或者是从具有标准len()的类继承
     的容器。当没有实现映射的类有get()或key()方法，或者不是文件的类有
     write()方法时，我们偶尔会感到困惑。

— ‘https://mail.python.org/pipermail/python-3000/2006-November/004643.html’


File: python.info,  Node: 为什么 join 是一个字符串方法而不是列表或元组方法？,  Next: 异常有多快？,  Prev: 为什么Python对某些功能（例如list index ）使用方法来实现，而其他功能（例如len List ）使用函数实现？,  Up: 设计和历史常见问题

11.3.8 为什么 join()是一个字符串方法而不是列表或元组方法？
----------------------------------------------------------

从Python 1.6开始，字符串变得更像其他标准类型，当添加方法时，这些方法提供
的功能与始终使用String模块的函数时提供的功能相同。这些新方法中的大多数已
被广泛接受，但似乎让一些程序员感到不舒服的一种方法是：

     ", ".join(['1', '2', '4', '8', '16'])

结果如下:

     "1, 2, 4, 8, 16"

反对这种用法有两个常见的论点。

第一条是这样的：“使用字符串文本(String Constant)的方法看起来真的很难看
”，答案是也许吧，但是字符串文本只是一个固定值。如果在绑定到字符串的名称
上允许使用这些方法，则没有逻辑上的理由使其在文字上不可用。

第二个异议通常是这样的：“我实际上是在告诉序列使用字符串常量将其成员连接
在一起”。遗憾的是并非如此。出于某种原因，把 *note split(): 890. 作为一个
字符串方法似乎要容易得多，因为在这种情况下，很容易看到:

     "1, 2, 4, 8, 16".split(", ")

是对字符串文本的指令，用于返回由给定分隔符分隔的子字符串（或在默认情况下
，返回任意空格）。

*note join(): 1766. 是字符串方法，因为在使用该方法时，您告诉分隔符字符串
去迭代一个字符串序列，并在相邻元素之间插入自身。此方法的参数可以是任何遵
循序列规则的对象，包括您自己定义的任何新的类。对于字节和字节数组对象也有
类似的方法。


File: python.info,  Node: 异常有多快？,  Next: 为什么Python中没有switch或case语句？,  Prev: 为什么 join 是一个字符串方法而不是列表或元组方法？,  Up: 设计和历史常见问题

11.3.9 异常有多快？
-------------------

如果没有引发异常，则try/except块的效率极高。实际上捕获异常是昂贵的。在
2.0之前的Python版本中，通常使用这个习惯用法:

     try:
         value = mydict[key]
     except KeyError:
         mydict[key] = getvalue(key)
         value = mydict[key]

只有当你期望dict在任何时候都有key时，这才有意义。如果不是这样的话，你就
是应该这样编码：

     if key in mydict:
         value = mydict[key]
     else:
         value = mydict[key] = getvalue(key)

对于这种特定的情况，您还可以使用 ‘value = dict.setdefault(key,
getvalue(key))’，但前提是调用 ‘getvalue()’ 足够便宜，因为在所有情况下都
会对其进行评估。


File: python.info,  Node: 为什么Python中没有switch或case语句？,  Next: 难道不能在解释器中模拟线程，而非得依赖特定于操作系统的线程实现吗？,  Prev: 异常有多快？,  Up: 设计和历史常见问题

11.3.10 为什么Python中没有switch或case语句？
--------------------------------------------

你可以通过一系列 ‘if... elif... elif... else’.轻松完成这项工作。对于
switch语句语法已经有了一些建议，但尚未就是否以及如何进行范围测试达成共识
。有关完整的详细信息和当前状态，请参阅 PEP 275(1) 。

对于需要从大量可能性中进行选择的情况，可以创建一个字典，将case 值映射到
要调用的函数。例如：

     def function_1(...):
         ...

     functions = {'a': function_1,
                  'b': function_2,
                  'c': self.method_1, ...}

     func = functions[value]
     func()

对于对象调用方法，可以通过使用 *note getattr(): 54b. 内置检索具有特定名
称的方法来进一步简化：

     def visit_a(self, ...):
         ...
     ...

     def dispatch(self, value):
         method_name = 'visit_' + str(value)
         method = getattr(self, method_name)
         method()

建议对方法名使用前缀，例如本例中的 ‘visit_’ 。如果没有这样的前缀，如果值
来自不受信任的源，攻击者将能够调用对象上的任何方法。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0275


File: python.info,  Node: 难道不能在解释器中模拟线程，而非得依赖特定于操作系统的线程实现吗？,  Next: 為何lambda表示式不能包含在敘述內,  Prev: 为什么Python中没有switch或case语句？,  Up: 设计和历史常见问题

11.3.11 难道不能在解释器中模拟线程，而非得依赖特定于操作系统的线程实现吗？
--------------------------------------------------------------------------

答案1： 不幸的是，解释器为每个Python堆栈帧推送至少一个C堆栈帧。此外，扩
展可以随时回调Python。因此，一个完整的线程实现需要对C的线程支持。

答案2： 幸运的是， Stackless Python(1) 有一个完全重新设计的解释器循环，
可以避免C堆栈。

   ---------- Footnotes ----------

   (1) https://github.com/stackless-dev/stackless/wiki


File: python.info,  Node: 為何lambda表示式不能包含在敘述內,  Next: Python可以被編譯成機器語言或C語言或其他種語言嗎?,  Prev: 难道不能在解释器中模拟线程，而非得依赖特定于操作系统的线程实现吗？,  Up: 设计和历史常见问题

11.3.12 為何lambda表示式不能包含在敘述內
----------------------------------------

Python的 lambda表达式不能包含语句，因为Python的语法框架不能处理嵌套在表
达式内部的语句。然而，在Python中，这并不是一个严重的问题。与其他语言中添
加功能的lambda表单不同，Python的 lambdas只是一种速记符号，如果您懒得定义
函数的话。

函数已经是Python中的第一类对象，可以在本地范围内声明。 因此，使用
lambda而不是本地定义的函数的唯一优点是你不需要为函数创建一个名称 – 这只
是一个分配了函数对象(与lambda表达式生成的对象类型完全相同)的局部变量！


File: python.info,  Node: Python可以被編譯成機器語言或C語言或其他種語言嗎?,  Next: Python如何管理記憶體?,  Prev: 為何lambda表示式不能包含在敘述內,  Up: 设计和历史常见问题

11.3.13 Python可以被編譯成機器語言或C語言或其他種語言嗎?
--------------------------------------------------------

Cython(1) 将带有可选注释的Python修改版本编译到C扩展中。 Nuitka(2) 是一个
将Python编译成 C++ 代码的新兴编译器，旨在支持完整的Python语言。要编译成
Java，可以考虑 VOC(3) 。

   ---------- Footnotes ----------

   (1) http://cython.org/

   (2) http://www.nuitka.net/

   (3) https://voc.readthedocs.io


File: python.info,  Node: Python如何管理記憶體?,  Next: 為何CPython不使用更多傳統的垃圾回收機制?,  Prev: Python可以被編譯成機器語言或C語言或其他種語言嗎?,  Up: 设计和历史常见问题

11.3.14 Python如何管理記憶體?
-----------------------------

Python 内存管理的细节取决于实现。 Python 的标准实现 *note CPython: 1569.
使用引用计数来检测不可访问的对象，并使用另一种机制来收集引用循环，定期执
行循环检测算法来查找不可访问的循环并删除所涉及的对象。 *note gc: 84. 模
块提供了执行垃圾回收、获取调试统计信息和优化收集器参数的函数。

但是，其他实现(如 Jython(1) 或 PyPy(2) )，)可以依赖不同的机制，如完全的
垃圾回收器 。如果你的Python代码依赖于引用计数实现的行为，则这种差异可能
会导致一些微妙的移植问题。

在一些Python实现中，以下代码（在CPython中工作的很好）可能会耗尽文件描述
符:

     for file in very_long_list_of_files:
         f = open(file)
         c = f.read(1)

实际上，使用CPython的引用计数和析构函数方案， 每个新赋值的 `f' 都会关闭
前一个文件。然而，对于传统的GC，这些文件对象只能以不同的时间间隔（可能很
长的时间间隔）被收集（和关闭）。

如果要编写可用于任何python实现的代码，则应显式关闭该文件或使用 *note
with: 7da. 语句；无论内存管理方案如何，这都有效：

     for file in very_long_list_of_files:
         with open(file) as f:
             c = f.read(1)

   ---------- Footnotes ----------

   (1) http://www.jython.org

   (2) http://www.pypy.org


File: python.info,  Node: 為何CPython不使用更多傳統的垃圾回收機制?,  Next: 當CPython結束時，為何所有的記憶體不會被釋放?,  Prev: Python如何管理記憶體?,  Up: 设计和历史常见问题

11.3.15 為何CPython不使用更多傳統的垃圾回收機制?
------------------------------------------------

首先，这不是C标准特性，因此不能移植。(是的，我们知道Boehm GC库。它包含了
`大多数' 常见平台（但不是所有平台）的汇编代码，尽管它基本上是透明的，但
也不是完全透明的; 要让Python使用它，需要使用补丁。)

当Python嵌入到其他应用程序中时，传统的GC也成为一个问题。在独立的Python中
，可以用GC库提供的版本替换标准的malloc()和free()，嵌入Python的应用程序可
能希望用 `它自己' 替代malloc()和free()，而可能不需要Python的。现在，
CPython可以正确地实现malloc()和free()。


File: python.info,  Node: 當CPython結束時，為何所有的記憶體不會被釋放?,  Next: 为什么有单独的元组和列表数据类型？,  Prev: 為何CPython不使用更多傳統的垃圾回收機制?,  Up: 设计和历史常见问题

11.3.16 當CPython結束時，為何所有的記憶體不會被釋放?
----------------------------------------------------

当Python退出时，从全局命名空间或Python模块引用的对象并不总是被释放。 如
果存在循环引用，则可能发生这种情况 C库分配的某些内存也是不可能释放的（例
如像Purify这样的工具会抱怨这些内容）。 但是，Python在退出时清理内存并尝
试销毁每个对象。

如果要强制 Python 在释放时删除某些内容，请使用 *note atexit: b. 模块运行
一个函数，强制删除这些内容。


File: python.info,  Node: 为什么有单独的元组和列表数据类型？,  Next: 列表是如何在CPython中实现的？,  Prev: 當CPython結束時，為何所有的記憶體不會被釋放?,  Up: 设计和历史常见问题

11.3.17 为什么有单独的元组和列表数据类型？
------------------------------------------

虽然列表和元组在许多方面是相似的，但它们的使用方式通常是完全不同的。可以
认为元组类似于Pascal记录或C结构；它们是相关数据的小集合，可以是不同类型
的数据，可以作为一个组进行操作。例如，笛卡尔坐标适当地表示为两个或三个数
字的元组。

另一方面，列表更像其他语言中的数组。它们倾向于持有不同数量的对象，所有对
象都具有相同的类型，并且逐个操作。例如， ‘os.listdir('.')’ 返回表示当前
目录中的文件的字符串列表。如果向目录中添加了一两个文件，对此输出进行操作
的函数通常不会中断。

元组是不可变的，这意味着一旦创建了元组，就不能用新值替换它的任何元素。列
表是可变的，这意味着您始终可以更改列表的元素。只有不变元素可以用作字典的
key，因此只能将元组和非列表用作key。


File: python.info,  Node: 列表是如何在CPython中实现的？,  Next: 字典是如何在CPython中实现的？,  Prev: 为什么有单独的元组和列表数据类型？,  Up: 设计和历史常见问题

11.3.18 列表是如何在CPython中实现的？
-------------------------------------

CPython的列表实际上是可变长度的数组，而不是lisp风格的链表。该实现使用对
其他对象的引用的连续数组，并在列表头结构中保留指向该数组和数组长度的指针
。

这使得索引列表 ‘a[i]’ 的操作成本与列表的大小或索引的值无关。

当添加或插入项时，将调整引用数组的大小。并采用了一些巧妙的方法来提高重复
添加项的性能; 当数组必须增长时，会分配一些额外的空间，以便在接下来的几次
中不需要实际调整大小。


File: python.info,  Node: 字典是如何在CPython中实现的？,  Next: 为什么字典key必须是不可变的？,  Prev: 列表是如何在CPython中实现的？,  Up: 设计和历史常见问题

11.3.19 字典是如何在CPython中实现的？
-------------------------------------

CPython的字典实现为可调整大小的哈希表。与B-树相比，这在大多数情况下为查
找（目前最常见的操作）提供了更好的性能，并且实现更简单。

字典的工作方式是使用 *note hash(): aa3. 内置函数计算字典中存储的每个键的
hash代码。hash代码根据键和每个进程的种子而变化很大；例如，"Python" 的
hash值为-539294296，而"python"(一个按位不同的字符串)的hash值为
1142331976。然后，hash代码用于计算内部数组中将存储该值的位置。假设您存储
的键都具有不同的hash值，这意味着字典需要恒定的时间 – O(1)，用Big-O表示法
– 来检索一个键。


File: python.info,  Node: 为什么字典key必须是不可变的？,  Next: 為何list sort 不是回傳排序過的串列?,  Prev: 字典是如何在CPython中实现的？,  Up: 设计和历史常见问题

11.3.20 为什么字典key必须是不可变的？
-------------------------------------

字典的哈希表实现使用从键值计算的哈希值来查找键。如果键是可变对象，则其值
可能会发生变化，因此其哈希值也会发生变化。但是，由于无论谁更改键对象都无
法判断它是否被用作字典键值，因此无法在字典中修改条目。然后，当你尝试在字
典中查找相同的对象时，将无法找到它，因为其哈希值不同。如果你尝试查找旧值
，也不会找到它，因为在该哈希表中找到的对象的值会有所不同。

如果你想要一个用列表索引的字典，只需先将列表转换为元组；用函数
‘tuple(L)’ 创建一个元组，其条目与列表 ‘L’ 相同。 元组是不可变的，因此可
以用作字典键。

已经提出的一些不可接受的解决方案：

   - 哈希按其地址（对象ID）列出。这不起作用，因为如果你构造一个具有相同
     值的新列表，它将无法找到；例如:

          mydict = {[1, 2]: '12'}
          print(mydict[[1, 2]])

     会引发一个 *note KeyError: 3e9. 异常，因为第二行中使用的 ‘[1, 2]’ 的
     id 与第一行中的 id 不同。换句话说，应该使用 ‘==’ 来比较字典键，而不
     是使用 *note is: 1551. 。

   - 使用列表作为键时进行复制。这没有用的，因为作为可变对象的列表可以包
     含对自身的引用，然后复制代码将进入无限循环。

   - 允许列表作为键，但告诉用户不要修改它们。当你意外忘记或修改列表时，
     这将产生程序中的一类难以跟踪的错误。它还使一个重要的字典不变量无效
     ： ‘d.keys()’ 中的每个值都可用作字典的键。

   - 将列表用作字典键后，应标记为其只读。问题是，它不仅仅是可以改变其值
     的顶级对象；你可以使用包含列表作为键的元组。将任何内容作为键关联到
     字典中都需要将从那里可到达的所有对象标记为只读 —— 并且自引用对象可
     能会导致无限循环。

如果需要，可以使用以下方法来解决这个问题，但使用它需要你自担风险：你可以
将一个可变结构包装在一个类实例中，该实例同时具有 *note __eq__(): 44b. 和
*note __hash__(): 44c. 方法。然后，你必须确保驻留在字典（或其他基于 hash
的结构）中的所有此类包装器对象的哈希值在对象位于字典（或其他结构）中时保
持固定。:

     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

注意，哈希计算由于列表的某些成员可能不可用以及算术溢出的可能性而变得复杂
。

此外，必须始终如此，如果 ‘o1 == o2’ （即 ‘o1.__eq__(o2) is True’ ）则
‘hash(o1) == hash(o2)``（即 ``o1.__hash__() == o2.__hash__()’ ），无论对
象是否在字典中。 如果你不能满足这些限制，字典和其他基于 hash 的结构将会
出错。

对于 ListWrapper ，只要包装器对象在字典中，包装列表就不能更改以避免异常
。除非你准备好认真考虑需求以及不正确地满足这些需求的后果，否则不要这样做
。请留意。


File: python.info,  Node: 為何list sort 不是回傳排序過的串列?,  Next: 如何在Python中指定和实施接口规范？,  Prev: 为什么字典key必须是不可变的？,  Up: 设计和历史常见问题

11.3.21 為何list.sort()不是回傳排序過的串列?
--------------------------------------------

在性能很重要的情况下，仅仅为了排序而复制一份列表将是一种浪费。因此，
*note list.sort(): 547. 对列表进行了适当的排序。为了提醒您这一事实，它不
会返回已排序的列表。这样，当您需要排序的副本，但也需要保留未排序的版本时
，就不会意外地覆盖列表。

如果要返回新列表，请使用内置 *note sorted(): 546. 函数。此函数从提供的可
迭代列表中创建新列表，对其进行排序并返回。例如，下面是如何迭代遍历字典并
按keys排序:

     for key in sorted(mydict):
         ...  # do whatever with mydict[key]...


File: python.info,  Node: 如何在Python中指定和实施接口规范？,  Next: 為何沒有goto語法?,  Prev: 為何list sort 不是回傳排序過的串列?,  Up: 设计和历史常见问题

11.3.22 如何在Python中指定和实施接口规范？
------------------------------------------

由C++和Java等语言提供的模块接口规范描述了模块的方法和函数的原型。许多人
认为接口规范的编译时强制执行有助于构建大型程序。

Python 2.6添加了一个 *note abc: 3. 模块，允许定义抽象基类 (ABCs)。然后可
以使用 *note isinstance(): 551. 和 *note issubclass(): 552. 来检查实例或
类是否实现了特定的ABC。 *note collections.abc: 1e. 模块定义了一组有用的
ABCs 例如 *note Iterable: 1818. ， *note Container: 181a. , 和 *note
MutableMapping: ace.

对于 Python，接口规范的许多好处可以通过组件的适当测试规程来获得。

一个好的模块测试套件既可以提供回归测试，也可以作为模块接口规范和一组示例
。许多Python模块可以作为脚本运行，以提供简单的“自我测试”。即使是使用复杂
外部接口的模块，也常常可以使用外部接口的简单“桩代码（stub）”模拟进行隔离
测试。可以使用 *note doctest: 66. 和 *note unittest: 124. 模块或第三方测
试框架来构造详尽的测试套件，以运行模块中的每一行代码。

适当的测试规程可以帮助在Python中构建大型的、复杂的应用程序以及接口规范。
事实上，它可能会更好，因为接口规范不能测试程序的某些属性。例如，
‘append()’ 方法将向一些内部列表的末尾添加新元素；接口规范不能测试您的
‘append()’ 实现是否能够正确执行此操作，但是在测试套件中检查这个属性是很
简单的。

编写测试套件非常有用，并且你可能希望将你的代码设计为易于测试。 一种日益
流行的技术是面向测试的开发，它要求在编写任何实际代码之前首先编写测试套件
的各个部分。 当然 Python 也允许你采用更粗率的方式，不必编写任何测试用例
。


File: python.info,  Node: 為何沒有goto語法?,  Next: 为什么原始字符串（r-strings）不能以反斜杠结尾？,  Prev: 如何在Python中指定和实施接口规范？,  Up: 设计和历史常见问题

11.3.23 為何沒有goto語法?
-------------------------

在 1970 年代人们了解到不受限制的 goto 可能导致混乱得像“意大利面”那样难以
理解和修改的代码。 在高级语言中，它也是不必要的，只需有实现分支 (在
Python 中是使用 ‘if’ 语句以及 ‘or’, ‘and’ 和 ‘if-else’ 表达式) 和循环 (使
用 ‘while’ 和 ‘for’ 语句，并可能包含 ‘continue’ 和 ‘break’) 的手段就足够
了。

人们还可以使用异常捕获来提供甚至能跨函数调用的“结构化 goto”。 许多人认为
异常可以方便地模拟 C, Fortran 和其他语言中所有合理使用的“go”或“goto”构造
。 例如:

     class label(Exception): pass  # declare a label

     try:
         ...
         if condition: raise label()  # goto label
         ...
     except label:  # where to goto
         pass
     ...

但是不允许你跳到循环的中间，这通常被认为是滥用goto。谨慎使用。


File: python.info,  Node: 为什么原始字符串（r-strings）不能以反斜杠结尾？,  Next: 为什么Python没有属性赋值的“with”语句？,  Prev: 為何沒有goto語法?,  Up: 设计和历史常见问题

11.3.24 为什么原始字符串（r-strings）不能以反斜杠结尾？
-------------------------------------------------------

更准确地说，它们不能以奇数个反斜杠结束：结尾处的不成对反斜杠会转义结束引
号字符，留下未结束的字符串。

原始字符串的设计是为了方便想要执行自己的反斜杠转义处理的处理器(主要是正
则表达式引擎)创建输入。此类处理器将不匹配的尾随反斜杠视为错误，因此原始
字符串不允许这样做。反过来，允许通过使用引号字符转义反斜杠转义字符串。当
r-string用于它们的预期目的时，这些规则工作的很好。

如果您正在尝试构建Windows路径名，请注意所有Windows系统调用都使用正斜杠:

     f = open("/mydir/file.txt")  # works fine!

如果您正在尝试为DOS命令构建路径名，请尝试以下示例

     dir = r"\this\is\my\dos\dir" "\\"
     dir = r"\this\is\my\dos\dir\ "[:-1]
     dir = "\\this\\is\\my\\dos\\dir\\"


File: python.info,  Node: 为什么Python没有属性赋值的“with”语句？,  Next: 生成器为什么不支持 with 语句？,  Prev: 为什么原始字符串（r-strings）不能以反斜杠结尾？,  Up: 设计和历史常见问题

11.3.25 为什么Python没有属性赋值的“with”语句？
----------------------------------------------

Python 具有 ’with’ 语句，它能将一个代码块的执行包装起来，在进入和退出代
码块时调用特定的代码。 有些语言具有这样的结构:

     with obj:
         a = 1               # equivalent to obj.a = 1
         total = total + 1   # obj.total = obj.total + 1

在Python中，这样的结构是不明确的。

其他语言，如ObjectPascal、Delphi和C++ 使用静态类型，因此可以毫不含糊地知
道分配给什么成员。这是静态类型的要点 – 编译器 `总是' 在编译时知道每个变
量的作用域。

Python使用动态类型。事先不可能知道在运行时引用哪个属性。可以动态地在对象
中添加或删除成员属性。这使得无法通过简单的阅读就知道引用的是什么属性：局
部属性、全局属性还是成员属性？

例如，采用以下不完整的代码段:

     def foo(a):
         with a:
             print(x)

该代码段假设 "a" 必须有一个名为 "x" 的成员属性。然而，Python中并没有告诉
解释器这一点。假设 "a" 是整数，会发生什么？如果有一个名为 "x" 的全局变量
，它是否会在with块中使用？如您所见，Python的动态特性使得这样的选择更加困
难。

然而，Python 可以通过赋值轻松实现 "with" 和类似语言特性（减少代码量）的
主要好处。代替:

     function(args).mydict[index][index].a = 21
     function(args).mydict[index][index].b = 42
     function(args).mydict[index][index].c = 63

写成这样:

     ref = function(args).mydict[index][index]
     ref.a = 21
     ref.b = 42
     ref.c = 63

这也具有提高执行速度的副作用，因为Python在运行时解析名称绑定，而第二个版
本只需要执行一次解析。


File: python.info,  Node: 生成器为什么不支持 with 语句？,  Next: 为什么 if/while/def/class语句需要冒号？,  Prev: 为什么Python没有属性赋值的“with”语句？,  Up: 设计和历史常见问题

11.3.26 生成器为什么不支持 with 语句？
--------------------------------------

For technical reasons, a generator used directly as a context manager
would not work correctly.  When, as is most common, a generator is used
as an iterator run to completion, no closing is needed.  When it is,
wrap it as "contextlib.closing(generator)" in the ’with’ statement.


File: python.info,  Node: 为什么 if/while/def/class语句需要冒号？,  Next: 为什么Python在列表和元组的末尾允许使用逗号？,  Prev: 生成器为什么不支持 with 语句？,  Up: 设计和历史常见问题

11.3.27 为什么 if/while/def/class语句需要冒号？
-----------------------------------------------

冒号主要用于增强可读性(ABC语言实验的结果之一)。考虑一下这个:

     if a == b
         print(a)

与

     if a == b:
         print(a)

注意第二种方法稍微容易一些。请进一步注意，在这个FAQ解答的示例中，冒号是
如何设置的；这是英语中的标准用法。

另一个次要原因是冒号使带有语法突出显示的编辑器更容易工作；他们可以寻找冒
号来决定何时需要增加缩进，而不必对程序文本进行更精细的解析。


File: python.info,  Node: 为什么Python在列表和元组的末尾允许使用逗号？,  Prev: 为什么 if/while/def/class语句需要冒号？,  Up: 设计和历史常见问题

11.3.28 为什么Python在列表和元组的末尾允许使用逗号？
----------------------------------------------------

Python 允许您在列表，元组和字典的末尾添加一个尾随逗号:

     [1, 2, 3,]
     ('a', 'b', 'c',)
     d = {
         "A": [1, 5],
         "B": [6, 7],  # last trailing comma is optional but good style
     }

這有許多原因可被允許。

如果列表，元组或字典的字面值分布在多行中，则更容易添加更多元素，因为不必
记住在上一行中添加逗号。这些行也可以重新排序，而不会产生语法错误。

不小心省略逗号会导致难以诊断的错误。例如:

     x = [
       "fee",
       "fie"
       "foo",
       "fum"
     ]

这个列表看起来有四个元素，但实际上包含三个 : "fee", "fiefoo" 和 "fum" 。
总是加上逗号可以避免这个错误的来源。

允许尾随逗号也可以使编程代码更容易生成。


File: python.info,  Node: 函式庫和擴充功能的常見問題,  Next: 扩展/嵌入常见问题,  Prev: 设计和历史常见问题,  Up: Python 常見問題

11.4 函式庫和擴充功能的常見問題
===============================

* Menu:

* 常見函式問題::
* 一般性的工作::
* 线程相关::
* 输入输出::
* 网络 / Internet 编程::
* 数据库::
* 数学和数字::


File: python.info,  Node: 常見函式問題,  Next: 一般性的工作,  Up: 函式庫和擴充功能的常見問題

11.4.1 常見函式問題
-------------------

* Menu:

* 如何找到可以用来做 XXX 的模块或应用？::
* 哪裡可以找到math.py (socket.py, regex.py, 等...) 原始檔案: 哪裡可以找到math py socket py regex py 等 原始檔案.
* 我如何使Python script 執行在Unix ?::
* Python 中有 curses/termcap 包吗？::
* Python 中存在类似 C 的 onexit() 函数的东西吗？: Python 中存在类似 C 的 onexit 函数的东西吗？.
* 为什么我的信号处理函数不能工作？::


File: python.info,  Node: 如何找到可以用来做 XXX 的模块或应用？,  Next: 哪裡可以找到math py socket py regex py 等 原始檔案,  Up: 常見函式問題

11.4.1.1 如何找到可以用来做 XXX 的模块或应用？
..............................................

在 *note 代码库参考: 1330. 中查找是否有适合的标准库模块。（如果你已经了
解标准库的内容，可以跳过这一步）

对于第三方软件包，请搜索 Python Package Index(1) 或是 Google(2) 等其他搜
索引擎。用“Python”加上一两个你需要的关键字通常会找到有用的东西。

   ---------- Footnotes ----------

   (1) https://pypi.org

   (2) https://www.google.com


File: python.info,  Node: 哪裡可以找到math py socket py regex py 等 原始檔案,  Next: 我如何使Python script 執行在Unix ?,  Prev: 如何找到可以用来做 XXX 的模块或应用？,  Up: 常見函式問題

11.4.1.2 哪裡可以找到math.py (socket.py, regex.py, 等...) 原始檔案
..................................................................

如果找不到模块的源文件，可能它是一个内建的模块，或是使用 C，C++ 或其他编
译型语言实现的动态加载模块。这种情况下可能是没有源码文件的，类似
‘mathmodule.c’ 这样的文件会存放在 C 代码目录中（但不在 Python 目录中）。

有(至少)三種Python 模組：

  1. 在Python 的模組被寫成(.py)

  2. 使用 C 编写的动态加载模块（.dll，.pyd，.so，.sl 等）；

  3. 使用 C 编写并链接到解释器的模块，要获取此列表，输入：

          import sys
          print(sys.builtin_module_names)


File: python.info,  Node: 我如何使Python script 執行在Unix ?,  Next: Python 中有 curses/termcap 包吗？,  Prev: 哪裡可以找到math py socket py regex py 等 原始檔案,  Up: 常見函式問題

11.4.1.3 我如何使Python script 執行在Unix ?
...........................................

你需要作兩件事:腳本程式必須可以被執行而且第一行必須"#!"開頭後面接上
Python直譯器的路徑

第一点可以用执行 ‘chmod +x scriptfile’ 或是 ‘chmod 755 scriptfile’ 做到
。

第二点有很多种做法，最直接的方式是：

     #!/usr/local/bin/python

在文件第一行，使用你所在平台上的 Python 解释器的路径。

如果你希望脚本不依赖 Python 解释器的具体路径，你也可以使用 ‘env’ 程序。
假设你的 Python 解释器所在目录已经添加到了 ‘PATH’ 环境变量中，几乎所有的
类 Unix 系统都支持下面的写法：

     #!/usr/bin/env python

`不要' 在 CGI 脚本中这样做。CGI 脚本的 ‘PATH’ 环境变量通常会非常精简，所
以你必须使用解释器的完整绝对路径。

有时候，用户的环境变量如果太长，可能会导致 ‘/usr/bin/env’ 执行失败；又或
者甚至根本就不存在 env 程序。在这种情况下，你可以尝试使用下面的 hack 方
法（来自 Alex Rezinsky）：

     #! /bin/sh
     """:"
     exec python $0 ${1+"$@"}
     """

这样做有一个小小的缺点，它会定义脚本的 __doc__ 字符串。不过可以这样修复
：

     __doc__ = """...Whatever..."""


File: python.info,  Node: Python 中有 curses/termcap 包吗？,  Next: Python 中存在类似 C 的 onexit 函数的东西吗？,  Prev: 我如何使Python script 執行在Unix ?,  Up: 常見函式問題

11.4.1.4 Python 中有 curses/termcap 包吗？
..........................................

对于类 Unix 系统：标准 Python 源码发行版会在 Modules(1) 子目录中附带
curses 模块，但默认并不会编译。（注意：在 Windows 平台下不可用 ——
Windows 中没有 curses 模块。）

*note curses: 2b. 模块支持基本的 curses 特性，同时也支持 ncurses 和 SYSV
curses 中的很多额外功能，比如颜色、不同的字符集支持、填充和鼠标支持。这
意味着这个模块不兼容只有 BSD curses 模块的操作系统，但是目前仍在维护的系
统应该都不会存在这种情况。

对于 Windows 平台：使用 consolelib 模块(2).

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Modules

   (2) http://effbot.org/zone/console-index.htm


File: python.info,  Node: Python 中存在类似 C 的 onexit 函数的东西吗？,  Next: 为什么我的信号处理函数不能工作？,  Prev: Python 中有 curses/termcap 包吗？,  Up: 常見函式問題

11.4.1.5 Python 中存在类似 C 的 onexit() 函数的东西吗？
.......................................................

*note atexit: b. 模块提供了一个与 C 的 ‘onexit()’ 函数类似的注册函数。


File: python.info,  Node: 为什么我的信号处理函数不能工作？,  Prev: Python 中存在类似 C 的 onexit 函数的东西吗？,  Up: 常見函式問題

11.4.1.6 为什么我的信号处理函数不能工作？
.........................................

最常见的问题是信号处理函数没有正确定义参数列表。它会被这样调用：

     handler(signum, frame)

因此它应当声明为带有两个形参:

     def handler(signum, frame):
         ...


File: python.info,  Node: 一般性的工作,  Next: 线程相关,  Prev: 常見函式問題,  Up: 函式庫和擴充功能的常見問題

11.4.2 一般性的工作
-------------------

* Menu:

* 我如何測試Python程式::
* 怎样用 docstring 创建文档？::
* 怎样一次只获取一个按键？::


File: python.info,  Node: 我如何測試Python程式,  Next: 怎样用 docstring 创建文档？,  Up: 一般性的工作

11.4.2.1 我如何測試Python程式
.............................

Python 带有两个测试框架。*note doctest: 66. 模块从模块的 docstring 中寻
找示例并执行，对比输出是否与 docstring 中给出的是否一致。

*note unittest: 124. 模块是一个模仿 Java 和 Smalltalk 测试框架的更棒的测
试框架。

为了使测试更容易，你应该在程序中使用良好的模块化设计。程序中的绝大多数功
能都应该用函数或类方法封装 —— 有时这样做会有额外惊喜，程序会运行得更快（
因为局部变量比全局变量访问要快）。除此之外，程序应该避免依赖可变的局部变
量，这会使得测试困难许多。

程序的“全局主逻辑”应该尽量简单：

     if __name__ == "__main__":
         main_logic()

在你的程式主模組的底端

一旦你的程序已经组织为一个函数和类行为的有完整集合，你就应该编写测试函数
来检测这些行为。 可以将自动执行一系列测试的测试集关联到每个模块。 这听起
来似乎需要大量的工作，但是由于 Python 是如此简洁灵活因此它会极其容易。 你
可以通过与“生产代码”同步编写测试函数使编程更为愉快和有趣，因为这将更容易
并更早发现代码问题甚至设计缺陷。

程序主模块之外的其他“辅助模块”中可以增加自测试的入口。

     if __name__ == "__main__":
         self_test()

通过使用 Python 实现的“假”接口，即使是需要与复杂的外部接口交互的程序也可
以在外部接口不可用时进行测试。


File: python.info,  Node: 怎样用 docstring 创建文档？,  Next: 怎样一次只获取一个按键？,  Prev: 我如何測試Python程式,  Up: 一般性的工作

11.4.2.2 怎样用 docstring 创建文档？
....................................

*note pydoc: d9. 模块可以用 Python 源码中的 docstring 创建 HTML 文件。也
可以使用 epydoc(1) 来只通过 docstring 创建 API 文档。Sphinx(2) 也可以引
入 docstring 的内容。

   ---------- Footnotes ----------

   (1) http://epydoc.sourceforge.net/

   (2) http://sphinx-doc.org


File: python.info,  Node: 怎样一次只获取一个按键？,  Prev: 怎样用 docstring 创建文档？,  Up: 一般性的工作

11.4.2.3 怎样一次只获取一个按键？
.................................

在类 Unix 系统中有多种方案。最直接的方法是使用 curses，但是 curses 模块
太大了，难以学习。


File: python.info,  Node: 线程相关,  Next: 输入输出,  Prev: 一般性的工作,  Up: 函式庫和擴充功能的常見問題

11.4.3 线程相关
---------------

* Menu:

* 程序中怎样使用线程？::
* 我的线程都没有运行，为什么？::
* 如何将任务分配给多个工作线程？::
* 怎样修改全局变量是线程安全的？::
* 不能删除全局解释器锁吗？::


File: python.info,  Node: 程序中怎样使用线程？,  Next: 我的线程都没有运行，为什么？,  Up: 线程相关

11.4.3.1 程序中怎样使用线程？
.............................

一定要使用 *note threading: 10b. 模块，不要使用 *note _thread: 2. 模块。
*note threading: 10b. 模块对 *note _thread: 2. 模块提供的底层线程原语做
了更易用的抽象。


File: python.info,  Node: 我的线程都没有运行，为什么？,  Next: 如何将任务分配给多个工作线程？,  Prev: 程序中怎样使用线程？,  Up: 线程相关

11.4.3.2 我的线程都没有运行，为什么？
.....................................

一旦主线程退出，所有的子线程都会被杀掉。你的主线程运行得太快了，子线程还
没来得及工作。

简单的解决方法是在程序中加一个时间足够长的 sleep，让子线程能够完成运行。

     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)  # <---------------------------!

但目前（在许多平台上）线程不是并行运行的，而是按顺序依次执行！原因是系统
线程调度器在前一个线程阻塞之前不会启动新线程。

简单的解决方法是在运行函数的开始处加一个时间很短的 sleep。

     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)

比起用 *note time.sleep(): 773. 猜一个合适的等待时间，使用信号量机制会更
好些。有一个办法是使用 *note queue: da. 模块创建一个 queue 对象，让每一
个线程在运行结束时 append 一个令牌到 queue 对象中，主线程中从 queue 对象
中读取与线程数量一致的令牌数量即可。


File: python.info,  Node: 如何将任务分配给多个工作线程？,  Next: 怎样修改全局变量是线程安全的？,  Prev: 我的线程都没有运行，为什么？,  Up: 线程相关

11.4.3.3 如何将任务分配给多个工作线程？
.......................................

最简单的方式是使用 *note concurrent.futures: 21. 模块，特别是其中的
*note ThreadPoolExecutor: 18c. 类。

或者，如果你想更好地控制分发算法，你也可以自己写逻辑实现。使用 *note
queue: da. 模块来创建任务列表队列。*note Queue: dde. 类维护一个了一个存
有对象的列表，提供了 ‘.put(obj)’ 方法添加元素，并且可以用 ‘.get()’ 方法
获取元素。这个类会使用必要的加锁操作，以此确保每个任务只会执行一次。

这是一个简单的例子：

     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)

运行时会产生如下输出：

     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
     ...

查看模块的文档以获取更多信息；*note Queue: dde. 类提供了多种接口。


File: python.info,  Node: 怎样修改全局变量是线程安全的？,  Next: 不能删除全局解释器锁吗？,  Prev: 如何将任务分配给多个工作线程？,  Up: 线程相关

11.4.3.4 怎样修改全局变量是线程安全的？
.......................................

Python VM 内部会使用 *note global interpreter lock: 5ff. （GIL）来确保同
一时间只有一个线程运行。通常 Python 只会在字节码指令之间切换线程；切换的
频率可以通过设置 *note sys.setswitchinterval(): 218. 指定。从 Python 程
序的角度来看，每一条字节码指令以及每一条指令对应的 C 代码实现都是原子的
。

理论上说，具体的结果要看具体的 PVM 字节码实现对指令的解释。而实际上，对
内建类型（int，list，dict 等）的共享变量的“类原子”操作都是原子的。

举例来说，下面的操作是原子的（L、L1、L2 是列表，D、D1、D2 是字典，x、y 是
对象，i，j 是 int 变量）：

     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()

这些不是原子的：

     i = i+1
     L.append(L[-1])
     L[i] = L[j]
     D[x] = D[x] + 1

覆盖其他对象的操作会在其他对象的引用计数变成 0 时触发其 *note __del__():
a04. 方法，这可能会产生一些影响。对字典和列表进行大量操作时尤其如此。如
果有疑问的话，使用互斥锁！


File: python.info,  Node: 不能删除全局解释器锁吗？,  Prev: 怎样修改全局变量是线程安全的？,  Up: 线程相关

11.4.3.5 不能删除全局解释器锁吗？
.................................

*note global interpreter lock: 5ff. （GIL）通常被视为 Python 在高端多核
服务器上开发时的阻力，因为（几乎）所有 Python 代码只有在获取到 GIL 时才
能运行，所以多线程的 Python 程序只能有效地使用一个 CPU。

在 Python 1.5 时代，Greg Stein 开发了一个完整的补丁包（“free threadings”
补丁），移除了 GIL，并用粒度更合适的锁来代替。Adam Olsen 最近也在他的
python-safethread(1) 项目里做了类似的实验。不幸的是，由于为了移除 GIL 而
使用了大量细粒度的锁，这两个实验在单线程测试中的性能都有明显的下降（至少
慢 30%）。

但这并意味着你不能在多核机器上很好地使用 Python！你只需将任务划分为多*进
程*，而不是多*线程*。新的 *note concurrent.futures: 21. 模块中的 *note
ProcessPoolExecutor: 196. 类提供了一个简单的方法；如果你想对任务分发做更
多控制，可以使用 *note multiprocessing: b7. 模块提供的底层 API。

恰当地使用 C 拓展也很有用；使用 C 拓展处理耗时较久的任务时，拓展可以在线
程执行 C 代码时释放 GIL，让其他线程执行。*note zlib: 14d. 和 *note
hashlib: 8c. 等标准库模块已经这样做了。

也有建议说 GIL 应该是解释器状态锁，而不是完全的全局锁；解释器不应该共享
对象。不幸的是，这也不可能发生。由于目前许多对象的实现都有全局的状态，因
此这是一个艰巨的工作。举例来说，小整型数和短字符串会缓存起来，这些缓存将
不得不移动到解释器状态中。其他对象类型都有自己的自由变量列表，这些自由变
量列表也必须移动到解释器状态中。等等。

我甚至怀疑这些工作是否可能在有限的时间内完成，因为同样的问题在第三方拓展
中也会存在。第三方拓展编写的速度可比你将它们转换为把全局状态存入解释器状
态中的速度快得多。

最后，假设多个解释器不共享任何状态，那么这样做比每个进程一个解释器好在哪
里呢？

   ---------- Footnotes ----------

   (1) https://code.google.com/archive/p/python-safethread


File: python.info,  Node: 输入输出,  Next: 网络 / Internet 编程,  Prev: 线程相关,  Up: 函式庫和擴充功能的常見問題

11.4.4 输入输出
---------------

* Menu:

* 怎样删除文件？（以及其他文件相关的问题……）::
* 怎样复制文件？::
* 怎样读取（或写入）二进制数据？::
* 似乎 os.popen() 创建的管道不能使用 os.read()，这是为什么？: 似乎 os popen 创建的管道不能使用 os read ，这是为什么？.
* 怎样访问（RS232）串口？::
* 为什么关闭 sys.stdout（stdin，stderr）并不会真正关掉它？: 为什么关闭 sys stdout（stdin，stderr）并不会真正关掉它？.


File: python.info,  Node: 怎样删除文件？（以及其他文件相关的问题……）,  Next: 怎样复制文件？,  Up: 输入输出

11.4.4.1 怎样删除文件？（以及其他文件相关的问题……）
...................................................

使用 ‘os.remove(filename)’ 或 ‘os.unlink(filename)’。查看 *note os: c4.
模块以获取更多文档。这两个函数是一样的，*note unlink(): b18. 是这个函数
在 Unix 系统调用中的名字。

如果要删除目录，应该使用 *note os.rmdir(): b16.；使用 *note os.mkdir():
b12. 创建目录。‘os.makedirs(path)’ 会创建 ‘path’ 中任何不存在的目录。
‘os.removedirs(path)’ 则会删除其中的目录，只要它们都是空的；如果你想删除
整个目录以及其中的内容，可以使用 *note shutil.rmtree(): 349.。

重命名文件可以使用 ‘os.rename(old_path, new_path)’。

如果需要截断文件，使用 ‘f = open(filename, "rb+")’ 打开文件，然后使用
‘f.truncate(offset)’；offset 默认是当前的搜索位置。也可以对使用 *note
os.open(): 758. 打开的文件使用 ‘os.ftruncate(fd, offset)’，其中 `fd' 是
文件描述符（一个小的整型数）。

*note shutil: e9. 模块也包含了一些处理文件的函数，包括 *note copyfile():
382.，*note copytree(): 347. 和 *note rmtree(): 349.。


File: python.info,  Node: 怎样复制文件？,  Next: 怎样读取（或写入）二进制数据？,  Prev: 怎样删除文件？（以及其他文件相关的问题……）,  Up: 输入输出

11.4.4.2 怎样复制文件？
.......................

*note shutil: e9. 模块有一个 *note copyfile(): 382. 函数。注意在 MacOS 9
中不会复制 resource fork 和 Finder info。


File: python.info,  Node: 怎样读取（或写入）二进制数据？,  Next: 似乎 os popen 创建的管道不能使用 os read ，这是为什么？,  Prev: 怎样复制文件？,  Up: 输入输出

11.4.4.3 怎样读取（或写入）二进制数据？
.......................................

要读写复杂的二进制数据格式，最好使用 *note struct: f8. 模块。该模块可以
读取包含二进制数据（通常是数字）的字符串并转换为 Python 对象，反之亦然。

举例来说，下面的代码会从文件中以大端序格式读取一个 2 字节的整型和一个 4
字节的整型：

     import struct

     with open(filename, "rb") as f:
         s = f.read(8)
         x, y, z = struct.unpack(">hhl", s)

格式字符串中的 ‘>’ 强制以大端序读取数据；字母 ‘h’ 从字符串中读取一个“短
整型”（2 字节），字母 ‘l’ 读取一个“长整型”（4 字节）。

对于更常规的数据（例如整型或浮点类型的列表），你也可以使用 *note array:
6. 模块。

     備註: 要读写二进制数据的话，需要强制以二进制模式打开文件（这里为
     *note open(): 16f. 函数传入 ‘"rb"’）。如果（默认）传入 ‘"r"’ 的话，
     文件会以文本模式打开，‘f.read()’ 会返回 *note str: 205. 对象，而不
     是 *note bytes: 172. 对象。


File: python.info,  Node: 似乎 os popen 创建的管道不能使用 os read ，这是为什么？,  Next: 怎样访问（RS232）串口？,  Prev: 怎样读取（或写入）二进制数据？,  Up: 输入输出

11.4.4.4 似乎 os.popen() 创建的管道不能使用 os.read()，这是为什么？
...................................................................

*note os.read(): 75b. 是一个底层函数，它接收的是文件描述符 —— 用小整型数
表示的打开的文件。*note os.popen(): 3cb. 创建的是一个高级文件对象，和内
建的 *note open(): 16f. 方法返回的类型一样。因此，如果要从 *note
os.popen(): 3cb. 创建的管道 `p' 中读取 `n' 个字节的话，你应该使用
‘p.read(n)’。


File: python.info,  Node: 怎样访问（RS232）串口？,  Next: 为什么关闭 sys stdout（stdin，stderr）并不会真正关掉它？,  Prev: 似乎 os popen 创建的管道不能使用 os read ，这是为什么？,  Up: 输入输出

11.4.4.5 怎样访问（RS232）串口？
................................

For Win32, OSX, Linux, BSD, Jython, IronPython:

     ‘https://pypi.org/project/pyserial/’

对于 Unix，查看 Mitch Chapman 发布的帖子：

     ‘https://groups.google.com/groups?selm=34A04430.CF9@ohioee.com’


File: python.info,  Node: 为什么关闭 sys stdout（stdin，stderr）并不会真正关掉它？,  Prev: 怎样访问（RS232）串口？,  Up: 输入输出

11.4.4.6 为什么关闭 sys.stdout（stdin，stderr）并不会真正关掉它？
.................................................................

Python *note 文件对象: c14. 是一个对底层 C 文件描述符的高层抽象。

对于在 Python 中通过内建的 *note open(): 16f. 函数创建的多数文件对象来说
，‘f.close()’ 从 Python 的角度将其标记为已关闭，并且会关闭底层的 C 文件
描述符。在 ‘f’ 被垃圾回收的时候，析构函数中也会自动处理。

但由于 stdin，stdout 和 stderr 在 C 中的特殊地位，在 Python 中也会对它们
做特殊处理。运行 ‘sys.stdout.close()’ 会将 Python 的文件对象标记为已关闭
，但是*不会*关闭与之关联的文件描述符。

要关闭这三者的 C 文件描述符的话，首先你应该确认确实需要关闭它（比如，这
可能会影响到处理 I/O 的拓展）。如果确实需要这么做的话，使用 *note
os.close(): 4d8.：

     os.close(stdin.fileno())
     os.close(stdout.fileno())
     os.close(stderr.fileno())

或者也可以使用常量 0，1，2 代替。


File: python.info,  Node: 网络 / Internet 编程,  Next: 数据库,  Prev: 输入输出,  Up: 函式庫和擴充功能的常見問題

11.4.5 网络 / Internet 编程
---------------------------

* Menu:

* Python 中的 WWW 工具是什么？::
* 怎样模拟发送 CGI 表单（METHOD=POST）？::
* 生成 HTML 需要使用什么模块？::
* 怎样使用 Python 脚本发送邮件？::
* socket 的 connect() 方法怎样避免阻塞？: socket 的 connect 方法怎样避免阻塞？.


File: python.info,  Node: Python 中的 WWW 工具是什么？,  Next: 怎样模拟发送 CGI 表单（METHOD=POST）？,  Up: 网络 / Internet 编程

11.4.5.1 Python 中的 WWW 工具是什么？
.....................................

参阅代码库参考手册中 *note 互联网协议和支持: 2d07. 和 *note
互联网数据处理: 291c. 这两章的内容。Python 有大量模块来帮助你构建服务端
和客户端 web 系统。

Paul Boddie 维护了一份可用框架的概览，见
‘https://wiki.python.org/moin/WebProgramming’ 。

Cameron Laird 维护了一份关于 Python web 技术的实用网页的集合，见
‘http://phaseit.net/claird/comp.lang.python/web_python’ 。


File: python.info,  Node: 怎样模拟发送 CGI 表单（METHOD=POST）？,  Next: 生成 HTML 需要使用什么模块？,  Prev: Python 中的 WWW 工具是什么？,  Up: 网络 / Internet 编程

11.4.5.2 怎样模拟发送 CGI 表单（METHOD=POST）？
...............................................

我需要通过 POST 表单获取网页，有什么代码能简单做到吗？

是的。 这里是一个使用 *note urllib.request: 129. 的简单例子:

     #!/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()

注意，通常在百分号编码的 POST 操作中，查询字符串必须使用 *note
urllib.parse.urlencode(): 87a. 处理一下。举个例子，如果要发送 ‘name=Guy
Steele, Jr.’ 的话：

     >>> import urllib.parse
     >>> urllib.parse.urlencode({'name': 'Guy Steele, Jr.'})
     'name=Guy+Steele%2C+Jr.'

也參考
......

查看 *note 如何使用urllib套件取得網路資源: 2deb. 获取更多示例。


File: python.info,  Node: 生成 HTML 需要使用什么模块？,  Next: 怎样使用 Python 脚本发送邮件？,  Prev: 怎样模拟发送 CGI 表单（METHOD=POST）？,  Up: 网络 / Internet 编程

11.4.5.3 生成 HTML 需要使用什么模块？
.....................................

你可以在 Web 编程 wiki 页面(1) 找到许多有用的链接。

   ---------- Footnotes ----------

   (1) https://wiki.python.org/moin/WebProgramming


File: python.info,  Node: 怎样使用 Python 脚本发送邮件？,  Next: socket 的 connect 方法怎样避免阻塞？,  Prev: 生成 HTML 需要使用什么模块？,  Up: 网络 / Internet 编程

11.4.5.4 怎样使用 Python 脚本发送邮件？
.......................................

使用 *note smtplib: ed. 标准库模块。

下面是一个很简单的交互式发送邮件的代码。这个方法适用于任何支持 SMTP 协议
的主机。

     import sys, smtplib

     fromaddr = input("From: ")
     toaddrs  = input("To: ").split(',')
     print("Enter message, end with ^D:")
     msg = ''
     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()

在 Unix 系统中还可以使用 sendmail。sendmail 程序的位置在不同系统中不一样
，有时是在 ‘/usr/lib/sendmail’，有时是在 ‘/usr/sbin/sendmail’。sendmail
手册页面会对你有所帮助。以下是示例代码：

     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)


File: python.info,  Node: socket 的 connect 方法怎样避免阻塞？,  Prev: 怎样使用 Python 脚本发送邮件？,  Up: 网络 / Internet 编程

11.4.5.5 socket 的 connect() 方法怎样避免阻塞？
...............................................

通常会用 *note select: e5. 模块处理 socket 异步 I/O。

要防止 TCP 连接发生阻塞，你可以将 socket 设为非阻塞模式。 这样当你执行
‘socket.connect()’ 时，你将或是立即完成连接（不大可能）或是收到一个包含
‘.errno’ 错误码的异常。 ‘errno.EINPROGRESS’ 表示连接正在进行但还没有完成
。 不同的操作系统将返回不同的值，因此你需要确认你的系统会返回什么值。

你可以使用 ‘socket.connect_ex()’ 方法来避免生成异常。 它将只返回 errno 值
。 要进行轮询，你可以稍后再次调用 ‘socket.connect_ex()’ – ‘0’ 或
‘errno.EISCONN’ 表示连接已完成 – 或者你也可以将此 socket 传给 *note
select.select(): 766. 来检查它是否可写。

     備註: *note asyncio: 9. 模块提供了通用的单线程并发异步库，它可被用
     来编写非阻塞的网络代码。 第三方的 Twisted(1) 库是一个热门且功能丰富
     的替代选择。

   ---------- Footnotes ----------

   (1) https://twistedmatrix.com/trac/


File: python.info,  Node: 数据库,  Next: 数学和数字,  Prev: 网络 / Internet 编程,  Up: 函式庫和擴充功能的常見問題

11.4.6 数据库
-------------

* Menu:

* Python 中有数据库包的接口吗？::
* 在 Python 中如何实现持久化对象？::


File: python.info,  Node: Python 中有数据库包的接口吗？,  Next: 在 Python 中如何实现持久化对象？,  Up: 数据库

11.4.6.1 Python 中有数据库包的接口吗？
......................................

有的

标准 Python 还包含了基于磁盘的哈希接口例如 *note DBM: 34. 和 *note GDBM:
33. 。除此之外还有 *note sqlite3: f2. 模块，该模块提供了一个轻量级的基于
磁盘的关系型数据库。

大多数关系型数据库都已经支持。查看 数据库编程 wiki 页面(1) 获取更多信息
。

   ---------- Footnotes ----------

   (1) https://wiki.python.org/moin/DatabaseProgramming


File: python.info,  Node: 在 Python 中如何实现持久化对象？,  Prev: Python 中有数据库包的接口吗？,  Up: 数据库

11.4.6.2 在 Python 中如何实现持久化对象？
.........................................

*note pickle: ca. 库模块以一种非常通用的方式解决了这个问题（虽然你依然不
能用它保存打开的文件、套接字或窗口之类的东西），此外 *note shelve: e7. 库
模块可使用 pickle 和 (g)dbm 来创建包含任意 Python 对象的持久化映射。


File: python.info,  Node: 数学和数字,  Prev: 数据库,  Up: 函式庫和擴充功能的常見問題

11.4.7 数学和数字
-----------------

* Menu:

* Python 中怎样生成随机数？::


File: python.info,  Node: Python 中怎样生成随机数？,  Up: 数学和数字

11.4.7.1 Python 中怎样生成随机数？
..................................

*note random: dc. 标准库模块实现了随机数生成器，使用起来非常简单：

     import random
     random.random()

这个函数会返回 [0, 1) 之间的随机浮点数。

该模块中还有许多其他的专门的生成器，例如：

   * ‘randrange(a, b)’ 返回 [a, b) 区间内的一个整型数。

   * ‘uniform(a, b)’ 返回 [a, b) 区间之间的浮点数。

   * ‘normalvariate(mean, sdev)’ 使用正态（高斯）分布采样。

还有一些高级函数直接对序列进行操作，例如：

   * ‘choice(S)’ 从给定的序列中随机选择一个元素。

   * ‘shuffle(L)’ 会对列表执行原地重排，即将其随机地打乱。

还有 ‘Random’ 类，你可以将其实例化，用来创建多个独立的随机数生成器。


File: python.info,  Node: 扩展/嵌入常见问题,  Next: FAQ：在 Windows 使用 Python,  Prev: 函式庫和擴充功能的常見問題,  Up: Python 常見問題

11.5 扩展/嵌入常见问题
======================

* 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中实现（例如通过继承）？::


File: python.info,  Node: 可以使用 C 语言创建自己的函数吗？,  Next: 可以使用 C++ 语言创建自己的函数吗？,  Up: 扩展/嵌入常见问题

11.5.1 可以使用 C 语言创建自己的函数吗？
----------------------------------------

是的，您可以在C中创建包含函数、变量、异常甚至新类型的内置模块。在文档
*note 擴充和嵌入 Python 直譯器: 1332. 中有说明。

大多数中级或高级的Python书籍也涵盖这个主题。


File: python.info,  Node: 可以使用 C++ 语言创建自己的函数吗？,  Next: C很难写，有没有其他选择？,  Prev: 可以使用 C 语言创建自己的函数吗？,  Up: 扩展/嵌入常见问题

11.5.2 可以使用 C++ 语言创建自己的函数吗？
------------------------------------------

是的，可以使用C ++中兼容C的功能。 在Python include文件周围放置‘
‘extern“C”{...}‘’ ，并在Python解释器调用的每个函数之前放置 ‘extern“C”’ 。
具有构造函数的全局或静态C ++对象可能不是一个好主意。


File: python.info,  Node: C很难写，有没有其他选择？,  Next: 如何在 C 中执行任意 Python 语句？,  Prev: 可以使用 C++ 语言创建自己的函数吗？,  Up: 扩展/嵌入常见问题

11.5.3 C很难写，有没有其他选择？
--------------------------------

编写自己的C扩展有很多选择，具体取决于您要做的事情。

Cython(1) 及其相关的 Pyrex(2) 是接受稍微修改过的Python形式并生成相应C代
码的编译器。 Cython和Pyrex可以编写扩展而无需学习Python的C API。

如果需要连接到某些当前不存在Python扩展的C或C ++库，可以尝试使用 SWIG(3)
等工具包装库的数据类型和函数。 SIP(4) ， CXX(5) Boost(6) , 或 Weave(7) 也
是包装C ++库的替代方案。

   ---------- Footnotes ----------

   (1) http://cython.org

   (2) https://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/

   (3) http://www.swig.org

   (4) https://riverbankcomputing.com/software/sip/intro

   (5) http://cxx.sourceforge.net/

   (6) http://www.boost.org/libs/python/doc/index.html

   (7) https://github.com/scipy/weave


File: python.info,  Node: 如何在 C 中执行任意 Python 语句？,  Next: 如何在 C 中对任意 Python 表达式求值？,  Prev: C很难写，有没有其他选择？,  Up: 扩展/嵌入常见问题

11.5.4 如何在 C 中执行任意 Python 语句？
----------------------------------------

执行此操作的最高层级函数为 *note PyRun_SimpleString(): 3da0.，它接受单个
字符串参数用于在模块 ‘__main__’ 的上下文中执行并在成功时返回 ‘0’ 而在发
生异常 (包括 *note SyntaxError: 559.) 时返回 ‘-1’。 如果你想要更多可控性
，可以使用 *note PyRun_String(): 10e7.；请在 ‘Python/pythonrun.c’ 中查看
*note PyRun_SimpleString(): 3da0. 的源码。


File: python.info,  Node: 如何在 C 中对任意 Python 表达式求值？,  Next: 如何从Python对象中提取C的值？,  Prev: 如何在 C 中执行任意 Python 语句？,  Up: 扩展/嵌入常见问题

11.5.5 如何在 C 中对任意 Python 表达式求值？
--------------------------------------------

可以调用前一问题中介绍的函数 *note PyRun_String(): 10e7. 并附带起始标记
符 *note Py_eval_input: 3df9.；它会解析表达式，对其求值并返回结果值。


File: python.info,  Node: 如何从Python对象中提取C的值？,  Next: 如何使用Py_BuildValue 创建任意长度的元组？,  Prev: 如何在 C 中对任意 Python 表达式求值？,  Up: 扩展/嵌入常见问题

11.5.6 如何从Python对象中提取C的值？
------------------------------------

这取决于对象的类型。 如果是元组，*note PyTuple_Size(): 4056. 可返回其长
度而 *note PyTuple_GetItem(): 3d39. 可返回指定序号上的项。 对于列表也有
类似的函数 ‘PyListSize()’ 和 *note PyList_GetItem(): 3d3a.。

对于字节串，*note PyBytes_Size(): 3fe2. 可返回其长度而 *note
PyBytes_AsStringAndSize(): 3fe6. 提供一个指向其值和长度的指针。 请注意
Python 字节串可能为空，因此 C 的 ‘strlen()’ 不应被使用。

要检测一个对象的类型，首先要确保它不为 ‘NULL’，然后使用 *note
PyBytes_Check(): de5, *note PyTuple_Check(): 4052, *note PyList_Check():
4064. 等等。

还有一个针对 Python 对象的高层级 API，通过所谓的‘抽象’接口提供 —— 请参阅
‘Include/abstract.h’ 了解详情。 它允许使用 *note PySequence_Length():
3f18, *note PySequence_GetItem(): 1183. 这样的调用来与任意种类的 Python
序列进行对接，此外还可使用许多其他有用的协议例如数字 (*note
PyNumber_Index(): 3f12. 等) 以及 PyMapping API 中的各种映射等等。


File: python.info,  Node: 如何使用Py_BuildValue 创建任意长度的元组？,  Next: 如何从C调用对象的方法？,  Prev: 如何从Python对象中提取C的值？,  Up: 扩展/嵌入常见问题

11.5.7 如何使用Py_BuildValue()创建任意长度的元组？
--------------------------------------------------

不可以。应该使用 *note PyTuple_Pack(): 4055. 。


File: python.info,  Node: 如何从C调用对象的方法？,  Next: 如何捕获PyErr_Print （或打印到stdout / stderr的任何内容）的输出？,  Prev: 如何使用Py_BuildValue 创建任意长度的元组？,  Up: 扩展/嵌入常见问题

11.5.8 如何从C调用对象的方法？
------------------------------

可以使用 *note PyObject_CallMethod(): 3eea. 函数来调用某个对象的任意方法
。 形参为该对象、要调用的方法名、类似 *note Py_BuildValue(): 3f0. 所用的
格式字符串以及要传给方法的参数值:

     PyObject *
     PyObject_CallMethod(PyObject *object, const char *method_name,
                         const char *arg_format, ...);

这适用于任何具有方法的对象 —— 不论是内置方法还是用户自定义方法。 你需要
负责对返回值进行最终的 *note Py_DECREF(): 38f. 处理。

例如调用某个文件对象的 "seek" 方法并传入参数 10, 0 (假定文件对象的指针为
"f"):

     res = PyObject_CallMethod(f, "seek", "(ii)", 10, 0);
     if (res == NULL) {
             ... an exception occurred ...
     }
     else {
             Py_DECREF(res);
     }

请注意由于 *note PyObject_CallObject(): 3d2d. `总是' 接受一个元组作为参
数列表，要调用不带参数的函数，则传入格式为 "()"，要调用只带一个参数的函
数，则应将参数包含于圆括号中，例如 "(i)"。


File: python.info,  Node: 如何捕获PyErr_Print （或打印到stdout / stderr的任何内容）的输出？,  Next: 如何从C访问用Python编写的模块？,  Prev: 如何从C调用对象的方法？,  Up: 扩展/嵌入常见问题

11.5.9 如何捕获PyErr_Print()（或打印到stdout / stderr的任何内容）的输出？
-------------------------------------------------------------------------

在 Python 代码中，定义一个支持 ‘write()’ 方法的对象。 将此对象赋值给
*note sys.stdout: 41f. 和 *note sys.stderr: 1ea.。 调用 print_error 或者
只是允许标准回溯机制生效。 在此之后，输出将转往你的 ‘write()’ 方法所指向
的任何地方。

做到这一点的最简单方式是使用 *note io.StringIO: 91a. 类：

     >>> import io, sys
     >>> sys.stdout = io.StringIO()
     >>> print('foo')
     >>> print('hello world!')
     >>> sys.stderr.write(sys.stdout.getvalue())
     foo
     hello world!

实现同样效果的自定义对象看起来是这样的：

     >>> 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(''.join(sys.stdout.data))
     foo
     hello world!


File: python.info,  Node: 如何从C访问用Python编写的模块？,  Next: 如何在 Python 中对接 C ++ 对象？,  Prev: 如何捕获PyErr_Print （或打印到stdout / stderr的任何内容）的输出？,  Up: 扩展/嵌入常见问题

11.5.10 如何从C访问用Python编写的模块？
---------------------------------------

你可以通过如下方式获得一个指向模块对象的指针:

     module = PyImport_ImportModule("<modulename>");

如果模块尚未被导入（即它还不存在于 *note sys.modules: 1051. 中），这会初
始化该模块；否则它只是简单地返回 ‘sys.modules["<modulename>"]’ 的值。 请
注意它并不会将模块加入任何命名空间 —— 它只是确保模块被初始化并存在于
*note sys.modules: 1051. 中。

之后你就可以通过如下方式来访问模块的属性（即模块中定义的任何名称）:

     attr = PyObject_GetAttrString(module, "<attrname>");

调用 *note PyObject_SetAttrString(): 3ec8. 为模块中的变量赋值也是可以的
。


File: python.info,  Node: 如何在 Python 中对接 C ++ 对象？,  Next: 我使用Setup文件添加了一个模块，为什么make失败了？,  Prev: 如何从C访问用Python编写的模块？,  Up: 扩展/嵌入常见问题

11.5.11 如何在 Python 中对接 C ++ 对象？
----------------------------------------

根据你的需求，可以选择许多方式。 手动的实现方式请查阅 *note "扩展与嵌入"
文档: 1332. 来入门。 需要知道的是对于 Python 运行时系统来说，C 和 C++ 并
不没有太大的区别 —— 因此围绕一个 C 结构（指针）类型构建新 Python 对象的
策略同样适用于 C++ 对象。

有关C ++库，请参阅 *note C很难写，有没有其他选择？: 44f8.


File: python.info,  Node: 我使用Setup文件添加了一个模块，为什么make失败了？,  Next: 如何调试扩展？,  Prev: 如何在 Python 中对接 C ++ 对象？,  Up: 扩展/嵌入常见问题

11.5.12 我使用Setup文件添加了一个模块，为什么make失败了？
---------------------------------------------------------

安装程序必须以换行符结束，如果没有换行符，则构建过程将失败。 （修复这个
需要一些丑陋的shell脚本编程，而且这个bug很小，看起来不值得花这么大力气。
)


File: python.info,  Node: 如何调试扩展？,  Next: 我想在Linux系统上编译一个Python模块，但是缺少一些文件。为什么?,  Prev: 我使用Setup文件添加了一个模块，为什么make失败了？,  Up: 扩展/嵌入常见问题

11.5.13 如何调试扩展？
----------------------

将GDB与动态加载的扩展名一起使用时，在加载扩展名之前，不能在扩展名中设置
断点。

在您的 ‘.gdbinit’ 文件中（或交互式）添加命令：

     br _PyImport_LoadDynamicModule

然后运行GDB：

     $ 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


File: python.info,  Node: 我想在Linux系统上编译一个Python模块，但是缺少一些文件。为什么?,  Next: 如何区分“输入不完整”和“输入无效”？,  Prev: 如何调试扩展？,  Up: 扩展/嵌入常见问题

11.5.14 我想在Linux系统上编译一个Python模块，但是缺少一些文件。为什么?
----------------------------------------------------------------------

大多数打包的Python版本不包含 ‘/usr/lib/python2.`x'/config/’ 目录，该目录
中包含编译Python扩展所需的各种文件。

对于Red Hat，安装python-devel RPM以获取必要的文件。

对于Debian，运行 ‘apt-get install python-dev’ 。


File: python.info,  Node: 如何区分“输入不完整”和“输入无效”？,  Next: 如何找到未定义的g++符号__builtin_new或__pure_virtual？,  Prev: 我想在Linux系统上编译一个Python模块，但是缺少一些文件。为什么?,  Up: 扩展/嵌入常见问题

11.5.15 如何区分“输入不完整”和“输入无效”？
------------------------------------------

有时，希望模仿Python交互式解释器的行为，在输入不完整时(例如，您键入了
“if”语句的开头，或者没有关闭括号或三个字符串引号)，给出一个延续提示，但
当输入无效时，立即给出一条语法错误消息。

在Python中，您可以使用 *note codeop: 1c. 模块，该模块非常接近解析器的行
为。例如，IDLE就使用了这个。

在C中执行此操作的最简单方法是调用 *note PyRun_InteractiveLoop(): 3de3. （
可能在单独的线程中）并让Python解释器为您处理输入。您还可以设置 *note
PyOS_ReadlineFunctionPointer(): a4d. 指向您的自定义输入函数。有关更多提
示，请参阅 ‘Modules/readline.c’ 和 ‘Parser/myreadline.c’ 。

但是，有时必须在与其他应用程序相同的线程中运行嵌入式Python解释器，并且不
能允许 *note PyRun_InteractiveLoop(): 3de3. 在等待用户输入时停止。那么另
一个解决方案是调用 ‘PyParser_ParseString()’ 并测试 ‘e.error’ 等于
‘E_EOF’ ，如果等于，就意味着输入不完整。这是一个示例代码片段，未经测试，
灵感来自Alex Farber的代码:

     #define PY_SSIZE_T_CLEAN
     #include <Python.h>
     #include <node.h>
     #include <errcode.h>
     #include <grammar.h>
     #include <parsetok.h>
     #include <compile.h>

     int testcomplete(char *code)
       /* code should end in \n */
       /* return -1 for error, 0 for incomplete, 1 for complete */
     {
       node *n;
       perrdetail e;

       n = PyParser_ParseString(code, &_PyParser_Grammar,
                                Py_file_input, &e);
       if (n == NULL) {
         if (e.error == E_EOF)
           return 0;
         return -1;
       }

       PyNode_Free(n);
       return 1;
     }

另一个解决方案是尝试使用 *note Py_CompileString(): 3df1. 编译接收到的字
符串。如果编译时没有出现错误，请尝试通过调用 *note PyEval_EvalCode():
3df5. 来执行返回的代码对象。否则，请将输入保存到以后。如果编译失败，找出
是错误还是只需要更多的输入-从异常元组中提取消息字符串，并将其与字符串 “分
析时意外的EOF” 进行比较。下面是使用GNUreadline库的完整示例(您可能希望在
调用readline()时忽略 `SIGINT' )：

     #include <stdio.h>
     #include <readline.h>

     #define PY_SSIZE_T_CLEAN
     #include <Python.h>
     #include <object.h>
     #include <compile.h>
     #include <eval.h>

     int main (int argc, char* argv[])
     {
       int i, j, done = 0;                          /* lengths of line, code */
       char ps1[] = ">>> ";
       char ps2[] = "... ";
       char *prompt = ps1;
       char *msg, *line, *code = NULL;
       PyObject *src, *glb, *loc;
       PyObject *exc, *val, *trb, *obj, *dum;

       Py_Initialize ();
       loc = PyDict_New ();
       glb = PyDict_New ();
       PyDict_SetItemString (glb, "__builtins__", PyEval_GetBuiltins ());

       while (!done)
       {
         line = readline (prompt);

         if (NULL == line)                          /* Ctrl-D pressed */
         {
           done = 1;
         }
         else
         {
           i = strlen (line);

           if (i > 0)
             add_history (line);                    /* save non-empty lines */

           if (NULL == code)                        /* nothing in code yet */
             j = 0;
           else
             j = strlen (code);

           code = realloc (code, i + j + 2);
           if (NULL == code)                        /* out of memory */
             exit (1);

           if (0 == j)                              /* code was empty, so */
             code[0] = '\0';                        /* keep strncat happy */

           strncat (code, line, i);                 /* append line to code */
           code[i + j] = '\n';                      /* append '\n' to code */
           code[i + j + 1] = '\0';

           src = Py_CompileString (code, "<stdin>", Py_single_input);

           if (NULL != src)                         /* compiled just fine - */
           {
             if (ps1  == prompt ||                  /* ">>> " or */
                 '\n' == code[i + j - 1])           /* "... " and double '\n' */
             {                                               /* so execute it */
               dum = PyEval_EvalCode (src, glb, loc);
               Py_XDECREF (dum);
               Py_XDECREF (src);
               free (code);
               code = NULL;
               if (PyErr_Occurred ())
                 PyErr_Print ();
               prompt = ps1;
             }
           }                                        /* syntax error or E_EOF? */
           else if (PyErr_ExceptionMatches (PyExc_SyntaxError))
           {
             PyErr_Fetch (&exc, &val, &trb);        /* clears exception! */

             if (PyArg_ParseTuple (val, "sO", &msg, &obj) &&
                 !strcmp (msg, "unexpected EOF while parsing")) /* E_EOF */
             {
               Py_XDECREF (exc);
               Py_XDECREF (val);
               Py_XDECREF (trb);
               prompt = ps2;
             }
             else                                   /* some other syntax error */
             {
               PyErr_Restore (exc, val, trb);
               PyErr_Print ();
               free (code);
               code = NULL;
               prompt = ps1;
             }
           }
           else                                     /* some non-syntax error */
           {
             PyErr_Print ();
             free (code);
             code = NULL;
             prompt = ps1;
           }

           free (line);
         }
       }

       Py_XDECREF(glb);
       Py_XDECREF(loc);
       Py_Finalize();
       exit(0);
     }


File: python.info,  Node: 如何找到未定义的g++符号__builtin_new或__pure_virtual？,  Next: 能否创建一个对象类，其中部分方法在C中实现，而其他方法在Python中实现（例如通过继承）？,  Prev: 如何区分“输入不完整”和“输入无效”？,  Up: 扩展/嵌入常见问题

11.5.16 如何找到未定义的g++符号__builtin_new或__pure_virtual？
--------------------------------------------------------------

要动态加载g ++扩展模块，必须重新编译Python，要使用g ++重新链接（在Python
Modules Makefile中更改LINKCC），及链接扩展模块（例如： ‘g++ -shared -o
mymodule.so mymodule.o’ ）。


File: python.info,  Node: 能否创建一个对象类，其中部分方法在C中实现，而其他方法在Python中实现（例如通过继承）？,  Prev: 如何找到未定义的g++符号__builtin_new或__pure_virtual？,  Up: 扩展/嵌入常见问题

11.5.17 能否创建一个对象类，其中部分方法在C中实现，而其他方法在Python中实现（例如通过继承）？
---------------------------------------------------------------------------------------------

是的，您可以继承内置类，例如 *note int: 204. ， *note list: 1f8. ，
*note dict: 164. 等。

Boost Python库（BPL，http：//www.boost.org/libs/python/doc/index.html）
提供了一种从C ++执行此操作的方法（即，您可以使用BPL继承自C ++编写的扩展
类 ）。


File: python.info,  Node: FAQ：在 Windows 使用 Python,  Next: 圖形化使用者界面常見問答集,  Prev: 扩展/嵌入常见问题,  Up: Python 常見問題

11.6 FAQ：在 Windows 使用 Python
================================

* Menu:

* 在 Windows 作業系統裡我想執行 Python 程式，要怎麼做？::
* 我怎么让 Python 脚本可执行？::
* 为什么有时候 Python 程序会启动缓慢？::
* 我怎样使用 Python 脚本制作可执行文件？::
* *.pyd 文件和 DLL 文件相同吗？: * pyd 文件和 DLL 文件相同吗？.
* 我怎样将 Python 嵌入一个 Windows 程序？::
* 如何让编辑器不要在我的 Python 源代码中插入 tab ？::
* 如何在不阻塞的情况下检查按键？::


File: python.info,  Node: 在 Windows 作業系統裡我想執行 Python 程式，要怎麼做？,  Next: 我怎么让 Python 脚本可执行？,  Up: FAQ：在 Windows 使用 Python

11.6.1 在 Windows 作業系統裡我想執行 Python 程式，要怎麼做？
------------------------------------------------------------

這個問題的答案可能有點複雜。如果你經常使用「命令提示字元」執行程式，那這
對你來說不會是什麼難事。如果不然，那就需要更仔細的說明了。

除非你在使用某种集成开发环境，否则你将会在被称为“DOS 窗口”或“命令提示符
窗口”的地方 `输入' Windows 命令。 通常你可以在搜索栏搜索 ‘cmd’ 来创建这
种窗口。 你应该能够识别你何时打开了这样的窗口，因为你将看到一个
Windows“命令提示符”，通常看起来是这样：

     C:\>

前面的字母可能会不同，而且后面有可能会有其他东西，所以你也许会看到类似这
样的东西：

     D:\YourName\Projects\Python>

出现的内容具体取决与你的电脑如何设置和你最近用它做的事。 当你启动了这样
一个窗口后，就可以开始运行Python程序了。

Python 脚本需要被另外一个叫做 Python `解释器' 的程序来处理。 解释器读取
脚本，把它编译成字节码，然后执行字节码来运行你的程序。 所以怎样安排解释
器来处理你的 Python 脚本呢？

首先，确保命令窗口能够将“py”识别为指令来开启解释器。 如果你打开过一个命
令窗口， 尝试输入命令 ‘py’ 然后按回车：

     C:\Users\YourName> py

然后你应当看见类似类似这样的东西：

     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.
     >>>

解释器已经以“交互模式”打开。这意味着你可以交互输入Python语句或表达式，并
在等待时执行或评估它们。这是Python最强大的功能之一。输入几个表达式并看看
结果：

     >>> print("Hello")
     Hello
     >>> "Hello" * 3
     'HelloHelloHello'

许多人把交互模式当作方便和高度可编程的计算器。 想结束交互式Python会话时
，调用 *note exit(): 1743. 函数，或者按住 ‘Ctrl’ 键时输入 ‘Z’ ，之后按
‘Enter’ 键返回Windows命令提示符。

你可能发现在开始菜单有这样一个条目 开始 ‣ 所有程序 ‣ Python 3.x ‣ Python
(命令行)， 运行它后会出现一个有着 ‘>>>’ 提示的新窗口。 在此之后，如果调
用 *note exit(): 1743. 函数或按 ‘Ctrl-Z’ 组合键后窗口将会消失。 Windows
会在这个窗口中运行一个“python”命令，并且在你终止解释器的时候关闭它。

现在我们知道 ‘py’ 命令已经被识别，可以输入 Python 脚本了。 你需要提供
Python 脚本的绝对路径或相对路径。 假设 Python 脚本位于桌面上并命名为
‘hello.py’，并且命令提示符在用户主目录打开，那么可以看到类似于这样的东西
:

     C:\Users\YourName>

那么现在可以让‘‘py‘‘命令执行你的脚本，只需要输入‘‘py‘‘ 和脚本路径:

     C:\Users\YourName> py Desktop\hello.py
     hello


File: python.info,  Node: 我怎么让 Python 脚本可执行？,  Next: 为什么有时候 Python 程序会启动缓慢？,  Prev: 在 Windows 作業系統裡我想執行 Python 程式，要怎麼做？,  Up: FAQ：在 Windows 使用 Python

11.6.2 我怎么让 Python 脚本可执行？
-----------------------------------

在 Windows 上，标准 Python 安装程序已将 .py 扩展名与文件类型
(Python.File) 相关联，并为该文件类型提供运行解释器的打开命令
(‘D:\Program Files\Python\python.exe "%1" %*’) 。 这足以使脚本在命令提示
符下作为“foo.py”命令被执行。 如果希望通过简单地键入“foo”而无需输入文件扩
展名来执行脚本，则需要将 .py 添加到 PATHEXT 环境变量中。


File: python.info,  Node: 为什么有时候 Python 程序会启动缓慢？,  Next: 我怎样使用 Python 脚本制作可执行文件？,  Prev: 我怎么让 Python 脚本可执行？,  Up: FAQ：在 Windows 使用 Python

11.6.3 为什么有时候 Python 程序会启动缓慢？
-------------------------------------------

通常，Python 在 Windows 上启动得很快，但偶尔会有错误报告说 Python 突然需
要很长时间才能启动。更令人费解的是，在其他配置相同的 Windows 系统上，
Python 却可以工作得很好。

该问题可能是由于计算机上的杀毒软件配置错误造成的。当将病毒扫描配置为监视
文件系统中所有读取行为时，一些杀毒扫描程序会导致两个数量级的启动开销。请
检查你系统安装的杀毒扫描程序的配置，确保两台机它们是同样的配置。已知的，
McAfee 杀毒软件在将它设置为扫描所有文件系统访问时，会产生这个问题。


File: python.info,  Node: 我怎样使用 Python 脚本制作可执行文件？,  Next: * pyd 文件和 DLL 文件相同吗？,  Prev: 为什么有时候 Python 程序会启动缓慢？,  Up: FAQ：在 Windows 使用 Python

11.6.4 我怎样使用 Python 脚本制作可执行文件？
---------------------------------------------

请参阅 *note 如何由 Python 脚本创建能独立运行的二进制程序？: 4468. 查看
可用来生成可执行文件的工具清单。


File: python.info,  Node: * pyd 文件和 DLL 文件相同吗？,  Next: 我怎样将 Python 嵌入一个 Windows 程序？,  Prev: 我怎样使用 Python 脚本制作可执行文件？,  Up: FAQ：在 Windows 使用 Python

11.6.5 ‘*.pyd’ 文件和 DLL 文件相同吗？
--------------------------------------

是的， .pyd 文件也是 dll ，但有一些差异。如果你有一个名为 ‘foo.pyd’ 的
DLL，那么它必须有一个函数 ‘PyInit_foo()’ 。 然后你可以编写 Python 代码
“import foo” ，Python 将搜索 foo.pyd （以及 foo.py 、 foo.pyc ）。如果找
到它，将尝试调用 ‘PyInit_foo()’ 来初始化它。你不应将 .exe 与 foo.lib 链
接，因为这会导致 Windows 要求存在 DLL 。

请注意， foo.pyd 的搜索路径是 PYTHONPATH ，与 Windows 用于搜索 foo.dll 的
路径不同。此外， foo.pyd 不需要存在来运行你的程序，而如果你将程序与 dll
链接，则需要 dll 。 当然，如果你想 ‘import foo’ ，则需要 foo.pyd 。在
DLL 中，链接在源代码中用 ‘__declspec(dllexport)’ 声明。 在 .pyd 中，链接
在可用函数列表中定义。


File: python.info,  Node: 我怎样将 Python 嵌入一个 Windows 程序？,  Next: 如何让编辑器不要在我的 Python 源代码中插入 tab ？,  Prev: * pyd 文件和 DLL 文件相同吗？,  Up: FAQ：在 Windows 使用 Python

11.6.6 我怎样将 Python 嵌入一个 Windows 程序？
----------------------------------------------

在 Windows 应用程序中嵌入 Python 解释器可以总结如下：

  1. 请 _不要_ 直接在你的 .exe 文件中内置 Python 。在 Windows 上，
     Python 必须是一个 DLL ，这样才可以处理导入的本身就是 DLL 的模块。（
     这是第一个未记录的关键事实。）相反，链接到 ‘python`NN'.dll’ ；它通
     常安装在 ‘C:\Windows\System’ 中。 `NN' 是 Python 版本，如数字“33”代
     表 Python 3.3 。

     你可以通过两种不同的方式链接到 Python 。加载时链接意味着链接到
     ‘python`NN'.lib’ ，而运行时链接意味着链接 ‘python`NN'.dll’ 。（一般
     说明： ‘python `NN'.lib’ 是所谓的“import lib”，对应于
     ‘python`NN'.dll’ 。它只定义了链接器的符号。）

     运行时链接极大地简化了链接选项，一切都在运行时发生。你的代码必须使
     用 Windows 的 ‘LoadLibraryEx()’ 程序加载 ‘python`NN'.dll’ 。代码还
     必须使用使用 Windows 的 ‘GetProcAddress()’ 例程获得的指针访问
     ‘python`NN'.dll’ 中程序和数据（即 Python 的 C API ）。宏可以使这些
     指针对任何调用 Python C API 中的例程的 C 代码都是透明的。

     Borland 提示：首先使用 Coff2Omf.exe 将 ‘python`NN'.lib’ 转换为 OMF
     格式。

  2. 如果你使用 SWIG ，很容易创建一个 Python “扩展模块”，它将使应用程序
     的数据和方法可供 Python 使用。SWIG将为你处理所有蹩脚的细节。结果是
     你将链接到 .exe 文件 `中' 的C代码 (!) 你不必创建 DLL 文件，这也简化
     了链接。

  3. SWIG 将创建一个 init 函数（一个 C 函数），其名称取决于扩展模块的名
     称。例如，如果模块的名称是 leo ，则 init 函数将被称为 initleo() 。
     如果您使用 SWIG 阴影类，则 init 函数将被称为 initleoc() 。这初始化
     了一个由阴影类使用的隐藏辅助类。

     你可以将步骤 2 中的 C 代码链接到 .exe 文件的原因是调用初始化函数等
     同于将模块导入 Python ！ （这是第二个关键的未记载事实。）

  4. 简而言之，你可以用以下代码使用扩展模块初始化 Python 解释器。

          #include "python.h"
          ...
          Py_Initialize();  // Initialize Python.
          initmyAppc();  // Initialize (import) the helper class.
          PyRun_SimpleString("import myApp");  // Import the shadow class.

  5. Python C API 存在两个问题，如果你使用除 MSVC 之外的编译器用于构建
     python.dll ，这将会变得明显。

     问题1：采用 FILE* 参数的所谓“极高级”函数在多编译器环境中不起作用，
     因为每个编译器的FILE结构体概念都不同。从实现的角度来看，这些是非常
     _低_ 级的功能。

     问题2：在为 void 函数生成包装器时，SWIG 会生成以下代码：

          Py_INCREF(Py_None);
          _resultobj = Py_None;
          return _resultobj;

     Py_None 是一个宏，它扩展为对 pythonNN.dll 中名为 _Py_NoneStruct 的
     复杂数据结构的引用。同样，此代码将在多编译器环境中失败。将此类代码
     替换为：

          return Py_BuildValue("");

     有可能使用 SWIG 的 ‘%typemap’ 命令自动进行更改，但我无法使其工作（
     我是一个完全的SWIG新手）。

  6. 使用 Python shell 脚本从 Windows 应用程序内部建立 Python 解释器窗口
     并不是一个好主意；生成的窗口将独立于应用程序的窗口系统。相反，你（
     或 wxPythonWindow 类）应该创建一个“本机”解释器窗口。将该窗口连接到
     Python解释器很容易。你可以将 Python的 i/o 重定向到支持读写的 _任意_
     对象，因此你只需要一个包含 read() 和 write() 方法的 Python 对象（在
     扩展模块中定义）。


File: python.info,  Node: 如何让编辑器不要在我的 Python 源代码中插入 tab ？,  Next: 如何在不阻塞的情况下检查按键？,  Prev: 我怎样将 Python 嵌入一个 Windows 程序？,  Up: FAQ：在 Windows 使用 Python

11.6.7 如何让编辑器不要在我的 Python 源代码中插入 tab ？
--------------------------------------------------------

本 FAQ 不建议使用制表符， Python 样式指南 PEP 8(1) ，为发行的 Python 代
码推荐 4 个空格；这也是 Emacs python-mode 默认值。

在任何编辑器下，混合制表符和空格都是一个坏主意。 MSVC 在这方面没有什么不
同，并且很容易配置为使用空格： 点击 Tools ‣ Options ‣ Tabs，对于文件类型
“Default”，设置“Tab size”和“Indent size”为 4 ，并选择“插入空格”单选按钮
。

如果混合制表符和空格导致前导空格出现问题， Python 会引发 *note
IndentationError: f39. 或 *note TabError: f38. 。你还可以运行 *note
tabnanny: 100. 模块以批处理模式检查目录树。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0008


File: python.info,  Node: 如何在不阻塞的情况下检查按键？,  Prev: 如何让编辑器不要在我的 Python 源代码中插入 tab ？,  Up: FAQ：在 Windows 使用 Python

11.6.8 如何在不阻塞的情况下检查按键？
-------------------------------------

使用 *note msvcrt: b6. 模块。 这是一个标准的 Windows 专属扩展模块。 它定
义了一个函数 ‘kbhit()’ 用于检查是否有键盘中的某个键被按下，以及
‘getch()’ 用于获取一个字符而不将其回显。


File: python.info,  Node: 圖形化使用者界面常見問答集,  Next: 為什麼Python被安裝在我的機器上?常見問答集,  Prev: FAQ：在 Windows 使用 Python,  Up: Python 常見問題

11.7 圖形化使用者界面常見問答集
===============================

* Menu:

* 常見圖形化使用者界面(GUI) 問題: 常見圖形化使用者界面 GUI 問題.
* Python 有哪些 GUI 工具包？::
* 有关Tkinter的问题::


File: python.info,  Node: 常見圖形化使用者界面 GUI 問題,  Next: Python 有哪些 GUI 工具包？,  Up: 圖形化使用者界面常見問答集

11.7.1 常見圖形化使用者界面(GUI) 問題
-------------------------------------


File: python.info,  Node: Python 有哪些 GUI 工具包？,  Next: 有关Tkinter的问题,  Prev: 常見圖形化使用者界面 GUI 問題,  Up: 圖形化使用者界面常見問答集

11.7.2 Python 有哪些 GUI 工具包？
---------------------------------

Standard builds of Python include an object-oriented interface to the
Tcl/Tk widget set, called *note tkinter: 32ac.  This is probably the
easiest to install (since it comes included with most binary
distributions(1) of Python) and use.  For more info about Tk, including
pointers to the source, see the Tcl/Tk home page(2).  Tcl/Tk is fully
portable to the macOS, Windows, and Unix platforms.

存在多种选项，具体取决于你的目标平台。 Python Wiki 上提供了一个 跨平台
(3) 和 平台专属(4) 的 GUI 框架列表。

   ---------- Footnotes ----------

   (1) https://www.python.org/downloads/

   (2) https://www.tcl.tk

   (3) 
https://wiki.python.org/moin/GuiProgramming#Cross-Platform_Frameworks

   (4) 
https://wiki.python.org/moin/GuiProgramming#Platform-specific_Frameworks


File: python.info,  Node: 有关Tkinter的问题,  Prev: Python 有哪些 GUI 工具包？,  Up: 圖形化使用者界面常見問答集

11.7.3 有关Tkinter的问题
------------------------

* Menu:

* 我怎样“冻结”Tkinter程序？::
* 在等待 I/O 操作时能够处理 Tk 事件吗？::
* 在Tkinter中键绑定不工作：为什么？::


File: python.info,  Node: 我怎样“冻结”Tkinter程序？,  Next: 在等待 I/O 操作时能够处理 Tk 事件吗？,  Up: 有关Tkinter的问题

11.7.3.1 我怎样“冻结”Tkinter程序？
..................................

Freeze是一个用来创建独立应用程序的工具。 当冻结(freeze) Tkinter程序时，
程序并不是真的能够独立运行，因为程序仍然需要Tcl和Tk库。

一种解决方法是将程序与 Tcl 和 Tk 库一同发布，并且在运行时使用环境变量
‘TCL_LIBRARY’ 和 ‘TK_LIBRARY’ 指向他们的位置。

为了获得真正能独立运行的应用程序，来自库里的 Tcl 脚本也需要被整合进应用
程序。 一个做这种事情的工具叫 SAM (stand-alone modules，独立模块) ，它是
Tix distribution (‘http://tix.sourceforge.net/’) 的一部分。

在启用 SAM 时编译 Tix ，在 Python 文件 ‘Modules/tkappinit.c’ 中执行对
‘Tclsam_init()’ 等的适当调用，并且将程序与 libtclsam 和 libtksam 相链接
（可能也要包括 Tix 的库）。


File: python.info,  Node: 在等待 I/O 操作时能够处理 Tk 事件吗？,  Next: 在Tkinter中键绑定不工作：为什么？,  Prev: 我怎样“冻结”Tkinter程序？,  Up: 有关Tkinter的问题

11.7.3.2 在等待 I/O 操作时能够处理 Tk 事件吗？
..............................................

在 Windows 以外的其他平台上可以，你甚至不需要使用线程！ 但是你必须稍微修
改一下你的 I/O 代码。 Tk 有与 Xt 的 ‘XtAddInput()’ 对应的调用，它允许你
注册一个回调函数，当一个文件描述符可以进行 I/O 操作的时候，Tk 主循环将会
调用这个回调函数。 参见 *note File Handlers: 32c6.。


File: python.info,  Node: 在Tkinter中键绑定不工作：为什么？,  Prev: 在等待 I/O 操作时能够处理 Tk 事件吗？,  Up: 有关Tkinter的问题

11.7.3.3 在Tkinter中键绑定不工作：为什么？
..........................................

经常听到的抱怨是：已经通过 ‘bind()’ 方法绑定了事件的处理程序，但是，当按
下相关的按键后，这个处理程序却没有执行。

最常见的原因是，那个绑定的控件没有“键盘焦点”。请在 Tk 文档中查找 focus 指
令。通常一个控件要获得“键盘焦点”，需要点击那个控件（而不是标签；请查看
takefocus 选项）。


File: python.info,  Node: 為什麼Python被安裝在我的機器上?常見問答集,  Prev: 圖形化使用者界面常見問答集,  Up: Python 常見問題

11.8 為什麼Python被安裝在我的機器上?常見問答集
==============================================

* Menu:

* 什麼是Python?: 什麼是Python?<2>.
* 為什麼Python被安裝在我的機器上?::
* 我能夠自行刪除Python嗎?::


File: python.info,  Node: 什麼是Python?<2>,  Next: 為什麼Python被安裝在我的機器上?,  Up: 為什麼Python被安裝在我的機器上?常見問答集

11.8.1 什麼是Python?
--------------------

Python是一種程式語言。它被使用於不同種類的應用程式中。因為Python屬於容易
學習的語言，它被使用在一些高中和學院中作為介紹程式語言的工具；但它也被專
業的軟體開發人員所使用，例如：Google，美國太空總署與 盧卡斯電影公司。

若你希望學習更多關於Python語言，可以從"Python初學者指引"網站
<‘https://wiki.python.org/moin/BeginnersGuide’>‘ 進行閱讀。


File: python.info,  Node: 為什麼Python被安裝在我的機器上?,  Next: 我能夠自行刪除Python嗎?,  Prev: 什麼是Python?<2>,  Up: 為什麼Python被安裝在我的機器上?常見問答集

11.8.2 為什麼Python被安裝在我的機器上?
--------------------------------------

若你發現曾安裝Python於系統中，但不記得何時安裝過，以下有幾種可能的方法可
以得知。

   * 也許其他使用此電腦的使用者希望學習撰寫程式並且安裝Python；你必須指
     出誰曾經使用此機器且可能安裝過。

   * 第三方應用程式安裝於機器中可能以Python語言撰寫並且安裝Python。有許
     多類似的應用程式，從GUI 程式 到網路伺服器和管理者腳本。

   * 一些安裝Windows的機器也被安裝Python。截至目前此文件交付，我們得知HP
     出廠的機器預設安裝Python。顯然的HP管理工具程式是透過Python語言所撰
     寫。

   * 許多相容於 Unix 系統，例如：maxOS 和 一些 Linux 發行版本預設安裝
     Python；安裝時被包含在基本安裝功能內。


File: python.info,  Node: 我能夠自行刪除Python嗎?,  Prev: 為什麼Python被安裝在我的機器上?,  Up: 為什麼Python被安裝在我的機器上?常見問答集

11.8.3 我能夠自行刪除Python嗎?
------------------------------

需要依據Python的安裝方式決定。

若有人不小心安裝了Python，可自行移除移除它。 Windows作業系統中，請於控制
台中尋找新增/移除程式進行反安裝。

若Python是透過第三方元件應用程式被安裝時，也可自行移除，不過請小心該應用
程式將無法正常執行。你應該使用應用程式反安裝功能而非自行刪除Python目錄

當作業系統預設安裝Python，不建議移除它。對你而言某些工具程式是重要不可或
缺的，若自行移除它，透過Python撰寫的工具程式將無法正常執行。重新安裝整個
系統仍需再次處理這些事情。


File: python.info,  Node: 術語表,  Next: 關於這些說明文件,  Prev: Python 常見問題,  Up: Top

12 術語表
*********

‘>>>’

     互動式 shell 的預設 Python 提示字元。常見於能在直譯器中以互動方式被
     執行的程式碼範例。

‘...’

     可以表示：

        * 在一個被縮排的程式碼區塊、在一對匹配的左右定界符（delimiter，
          例如括號、方括號、花括號或三引號）內部，或是在指定一個裝飾器
          (decorator) 之後，要輸入程式碼時，互動式 shell 顯示的預設
          Python 提示字元。

        * 內建常數 *note Ellipsis: 1740.。

2to3

     一個試著將 Python 2.x 程式碼轉換為 Python 3.x 程式碼的工具，它是透
     過處理大部分的不相容性來達成此目的，而這些不相容性能夠透過剖析原始
     碼和遍歷剖析樹而被檢測出來。

     2to3 在可以標準函式庫中以 *note lib2to3: a7. 被使用；它提供了一個獨
     立的入口點，在 ‘Tools/scripts/2to3’。請參閱 *note 2to3 - 自動將
     Python 2的程式碼轉成 Python 3: d3e.。

abstract base class（抽象基底類別）

     抽象基底類別（又稱為 ABC）提供了一種定義介面的方法，作為 *note
     duck-typing: 4523.（鴨子型別）的補充。其他類似的技術，像是 *note
     hasattr(): 54a.，則顯得笨拙或是帶有細微的錯誤（例如使用*note
     魔術方法 (magic method): 156f.）。ABC 採用虛擬的 subclass（子類別）
     ，它們並不繼承自另一個 class（類別），但仍可被 *note isinstance():
     551. 及 *note issubclass(): 552. 辨識；請參閱 *note abc: 3. 模組的
     說明文件。Python 有許多內建的 ABC，用於資料結構（在 *note
     collections.abc: 1e. 模組）、數字（在 *note numbers: c1. 模組）、串
     流（在 *note io: a1. 模組）及 import 尋檢器和載入器（在 *note
     importlib.abc: 9b. 模組）。你可以使用 *note abc: 3. 模組建立自己的
     ABC。

annotation（註釋）

     一個與變數、class 屬性、函式的參數或回傳值相關聯的標籤。照慣例，它
     被用來作為 *note type hint: 158b.（型別提示）。

     在運行時 (runtime)，區域變數的註釋無法被存取，但全域變數、class 屬
     性和函式的註解，會分別被儲存在模組、class 和函式的
     ‘__annotations__’ 特殊屬性中。

     請參閱 *note variable annotation: 712.、*note function annotation:
     1391.、 PEP 484(1) 和 PEP 526(2)，這些章節皆有此功能的說明。

argument（引數）

     呼叫函式時被傳遞給 *note function: 165c.（或 *note method: 4524.）
     的值。引數有兩種：

        * `關鍵字引數 (keyword argument)'：在函式呼叫中，以識別字（
          identifier，例如 ‘name=’）開頭的引數，或是以 ‘**’ 後面
          dictionary（字典）內的值被傳遞的引數。例如，‘3’ 和 ‘5’ 都是以
          下 *note complex(): 2c1. 呼叫中的關鍵字引數：

               complex(real=3, imag=5)
               complex(**{'real': 3, 'imag': 5})

        * `位置引數 (positional argument)'：不是關鍵字引數的引數。位置引
          數可在一個引數列表的起始處出現，和（或）作為 ‘*’ 之後的 *note
          iterable: c7c.（可疊代物件）中的元素被傳遞。例如，‘3’ 和 ‘5’ 都
          是以下呼叫中的位置引數：

               complex(3, 5)
               complex(*(3, 5))

     引數會被指定給函式主體中的附名區域變數。關於支配這個指定過程的規則
     ，請參閱*note 调用: 73f.章節。在語法上，任何運算式都可以被用來表示
     一個引數；其評估值會被指定給區域變數。

     另請參閱術語表的 *note parameter: 1664.（參數）條目、常見問題中的
     *note 引數和參數之間的差異: 4473.，以及 PEP 362(3)。

asynchronous context manager（非同步情境管理器）

     一個可以控制 *note async with: 736. 陳述式中所見環境的物件，而它是
     透過定義 *note __aenter__(): 109a. 和 *note __aexit__(): 109b.
     method（方法）來控制的。由 PEP 492(4) 引入。

asynchronous generator（非同步產生器）

     一個會回傳 *note asynchronous generator iterator: 37d7.（非同步產生
     器疊代器）的函式。它看起來像一個以 *note async def: 3a9. 定義的協程
     函式 (coroutine function)，但不同的是它包含了 *note yield: 2c7. 運
     算式，能生成一系列可用於 *note async for: 3fd. 迴圈的值。

     這個術語通常用來表示一個非同步產生器函式，但在某些情境中，也可能是
     表示`非同步產生器疊代器 (asynchronous generator iterator)'。萬一想
     表達的意思不夠清楚，那就使用完整的術語，以避免歧義。

     一個非同步產生器函式可能包含 *note await: 2d8. 運算式，以及 *note
     async for: 3fd. 和 *note async with: 736. 陳述式。

asynchronous generator iterator（非同步產生器疊代器）

     一個由 *note asynchronous generator: 1640.（非同步產生器）函式所建
     立的物件。

     這是一個 *note asynchronous iterator: 738.（非同步疊代器），當它以
     *note __anext__(): 155f. method 被呼叫時，會回傳一個可等待物件
     (awaitable object)，該物件將執行非同步產生器的函式主體，直到遇到下
     一個 *note yield: 2c7. 運算式。

     每個 *note yield: 2c7. 會暫停處理程序，並記住位置執行狀態（包括區域
     變數及擱置中的 try 陳述式）。當`非同步產生器疊代器'以另一個被 *note
     __anext__(): 155f. 回傳的可等待物件有效地回復時，它會從停止的地方繼
     續執行。請參閱 PEP 492(5) 和 PEP 525(6)。

asynchronous iterable（非同步可疊代物件）

     一個物件，它可以在 *note async for: 3fd. 陳述式中被使用。必須從它的
     *note __aiter__(): 582. method 回傳一個 *note asynchronous
     iterator: 738.（非同步疊代器）。由 PEP 492(7) 引入。

asynchronous iterator（非同步疊代器）

     一個實作 *note __aiter__(): 582. 和 *note __anext__(): 155f. method
     的物件。‘__anext__’ 必須回傳一個 *note awaitable: 612.（可等待物件
     ）。*note async for: 3fd. 會解析非同步疊代器的 *note __anext__():
     155f. method 所回傳的可等待物件，直到它引發 *note
     StopAsyncIteration: 114a. 例外。由 PEP 492(8) 引入。

attribute（屬性）

     一個與某物件相關聯的值，該值能透過使用點分隔運算式 (dotted
     expression) 的名稱被參照。例如，如果物件 `o' 有一個屬性 `a'，則該屬
     性能以 `o.a' 被參照。

awaitable（可等待物件）

     一個可以在 *note await: 2d8. 運算式中被使用的物件。它可以是一個
     *note coroutine: 18a.（協程），或是一個有 *note __await__(): 735.
     method 的物件。另請參閱 PEP 492(9)。

BDFL

     Benevolent Dictator For Life（終身仁慈獨裁者），又名 Guido van
     Rossum(10)，Python 的創造者。

binary file（二進制檔案）

     一個能夠讀取和寫入 *note bytes-like objects: 6df.（類位元組串物件）
     的 *note file object: c14.（檔案物件）。二進制檔案的例子有：以二進
     制模式（‘'rb'’、‘'wb'’ 或 ‘'rb+'’）開啟的檔案、‘sys.stdin.buffer’、
     ‘sys.stdout.buffer’，以及 *note io.BytesIO: 88a. 和 *note
     gzip.GzipFile: 206. 實例。

     另請參閱 *note text file: 13d9.（文字檔案），它是一個能夠讀取和寫入
     *note str: 205. 物件的檔案物件。

bytes-like object（類位元組串物件）

     一個支援*note 缓冲协议: 171c.且能夠匯出 C-*note contiguous: 17ec. 緩
     衝區的物件。這包括所有的 *note bytes: 172.、*note bytearray: 173. 和
     *note array.array: 216. 物件，以及許多常見的 *note memoryview: 386.
     物件。類位元組串物件可用於處理二進制資料的各種運算；這些運算包括壓
     縮、儲存至二進制檔案和透過 socket（插座）發送。

     有些運算需要二進制資料是可變的。說明文件通常會將這些物件稱為「可讀
     寫的類位元組串物件」。可變緩衝區的物件包括 *note bytearray: 173.，
     以及 *note bytearray: 173. 的 *note memoryview: 386.。其他的運算需
     要讓二進制資料被儲存在不可變物件（「唯讀的類位元組串物件」）中；這
     些物件包括 *note bytes: 172.，以及 *note bytes: 172. 物件的 *note
     memoryview: 386.。

bytecode（位元組碼）

     Python 的原始碼會被編譯成位元組碼，它是 Python 程式在 CPython 直譯
     器中的內部表示法。該位元組碼也會被暫存在 ‘.pyc’ 檔案中，以便第二次
     執行同一個檔案時能夠更快速（可以不用從原始碼重新編譯為位元組碼）。
     這種「中間語言 (intermediate language)」據說是運行在一個 *note
     virtual machine: 28d0.（虛擬機器）上，該虛擬機器會執行與每個位元組
     碼對應的機器碼 (machine code)。要注意的是，位元組碼理論上是無法在不
     同的 Python 虛擬機器之間運作的，也不能在不同版本的 Python 之間保持
     穩定。

     位元組碼的指令列表可以在 *note dis 模組: 3abd.的說明文件中找到。

callback（回呼）

     作為引數被傳遞的一個副程式 (subroutine) 函式，會在未來的某個時間點
     被執行。

class（類別）

     一個用於建立使用者定義物件的模板。Class 的定義通常會包含 method 的
     定義，這些 method 可以在 class 的實例上進行操作。

class variable（類別變數）

     一個在 class 中被定義，且應該只能在 class 層次（意即不是在 class 的
     實例中）被修改的變數。

coercion（強制轉型）

     在涉及兩個不同型別引數的操作過程中，將某一種型別的實例換為另一種型
     別的隱式轉換 (implicit conversion) 過程。例如，‘int(3.15)’ 會將浮點
     數轉換為整數 ‘3’，但在 ‘3+4.5’ 中，每個引數是不同的型別（一個 int，
     一個 float），而這兩個引數必須在被轉換為相同的型別之後才能相加，否
     則就會引發 *note TypeError: 1fe.。如果沒有強制轉型，即使所有的引數
     型別皆相容，它們都必須要由程式設計師正規化 (normalize) 為相同的值，
     例如，要用 ‘float(3)+4.5’ 而不能只是 ‘3+4.5’。

complex number（複數）

     一個我們熟悉的實數系統的擴充，在此所有數字都會被表示為一個實部和一
     個虛部之和。虛數就是虛數單位（‘-1’ 的平方根）的實數倍，此單位通常在
     數學中被寫為 ‘i’，在工程學中被寫為 ‘j’。Python 內建了對複數的支援，
     它是用後者的記法來表示複數；虛部會帶著一個後綴的 ‘j’ 被編寫，例如
     ‘3+1j’。若要將 *note math: b1. 模組內的工具等效地用於複數，請使用
     *note cmath: 18. 模組。複數的使用是一個相當進階的數學功能。如果你沒
     有察覺到對它們的需求，那麼幾乎能確定你可以安全地忽略它們。

context manager（情境管理器）

     一個可以控制 *note with: 7da. 陳述式中所見環境的物件，而它是透過定
     義 *note __enter__(): d5d. 和 *note __exit__(): d5e. method 來控制
     的。請參閱 PEP 343(11)。

context variable（情境變數）

     一個變數，其值可以根據上下文的情境而有所不同。這類似執行緒區域儲存
     區 (Thread-Local Storage)，在其中，一個變數在每個執行緒可能具有不同
     的值。然而，關於情境變數，在一個執行緒中可能會有多個情境，而情境變
     數的主要用途，是在並行的非同步任務 (concurrent asynchronous task) 中
     ，對於變數狀態的追蹤。請參閱 *note contextvars: 24.。

contiguous（連續的）

     如果一個緩衝區是 `C-contiguous' 或是 `Fortran contiguous'，則它會確
     切地被視為是連續的。零維 (zero-dimensional) 的緩衝區都是 C 及
     Fortran contiguous。在一維 (one-dimensional) 陣列中，各項目必須在記
     憶體中彼此相鄰地排列，而其索引順序是從零開始遞增。在多維的
     (multidimensional) C-contiguous 陣列中，按記憶體位址的順序訪問各個
     項目時，最後一個索引的變化最快。然而，在 Fortran contiguous 陣列中
     ，第一個索引的變化最快。

coroutine（協程）

     協程是副程式 (subroutine) 的一種更為廣義的形式。副程式是在某個時間
     點被進入並在另一個時間點被退出。協程可以在許多不同的時間點被進入、
     退出和回復。它們能夠以 *note async def: 3a9. 陳述式被實作。另請參閱
     PEP 492(12)。

coroutine function（協程函式）

     一個回傳 *note coroutine: 18a.（協程）物件的函式。一個協程函式能以
     *note async def: 3a9. 陳述式被定義，並可能會包含 *note await: 2d8.、
     *note async for: 3fd. 和 *note async with: 736. 關鍵字。這些關鍵字
     由 PEP 492(13) 引入。

CPython

     Python 程式語言的標準實作 (canonical implementation)，被發布在
     python.org(14) 上。「CPython」這個術語在必要時被使用，以區分此實作
     與其它語言的實作，例如 Jython 或 IronPython。

decorator（裝飾器）

     一個函式，它會回傳另一個函式，通常它會使用 ‘@wrapper’ 語法，被應用
     為一種函式的變換 (function transformation)。裝飾器的常見範例是
     *note classmethod(): 309. 和 *note staticmethod(): 30a.。

     裝飾器語法只是語法糖。以下兩個函式定義在語義上是等效的：

          def f(...):
              ...
          f = staticmethod(f)

          @staticmethod
          def f(...):
              ...

     Class 也存在相同的概念，但在那裡比較不常用。關於裝飾器的更多內容，
     請參閱*note 函式定義: 1390.和 *note class 定義: d32.的說明文件。

descriptor（描述器）

     任何定義了 *note __get__(): 156e.、*note __set__(): 1572. 或 *note
     __delete__(): 1573. method 的物件。當一個 class 屬性是一個描述器時
     ，它的特殊連結行為會在屬性查找時被觸發。通常，使用 `a.b' 來取得、設
     定或刪除某個屬性時，會在 `a' 的 class 字典中查找名稱為 `b' 的物件，
     但如果 `b' 是一個描述器，則相對應的描述器 method 會被呼叫。對描述器
     的理解是深入理解 Python 的關鍵，因為它們是許多功能的基礎，這些功能
     包括函式、method、屬性 (property)、class method、靜態 method，以及
     對 super class（父類別）的參照。

     關於描述器 method 的更多資訊，請參閱*note 实现描述器: 5e3.或*note
     描述器使用指南: 431f.。

dictionary（字典）

     一個關聯陣列 (associative array)，其中任意的鍵會被映射到值。鍵可以
     是任何帶有 *note __hash__(): 44c. 和 *note __eq__(): 44b. method 的
     物件。在 Perl 中被稱為雜湊 (hash)。

dictionary comprehension（字典綜合運算）

     一種緊密的方法，用來處理一個可疊代物件中的全部或部分元素，並將處理
     結果以一個字典回傳。‘results = {n: n ** 2 for n in range(10)}’ 會產
     生一個字典，它包含了鍵 ‘n’ 映射到值 ‘n ** 2’。請參閱*note
     列表、集合与字典的显示: 1628.。

dictionary view（字典檢視）

     從 *note dict.keys(): cf4.、*note dict.values(): cf6. 及 *note
     dict.items(): cf5. 回傳的物件被稱為字典檢視。它們提供了字典中項目的
     動態檢視，這表示當字典有變動時，該檢視會反映這些變動。若要強制將字
     典檢視轉為完整的 list（串列），須使用 ‘list(dictview)’。請參閱*note
     字典视图对象: 180c.。

docstring（說明字串）

     一個在 class、函式或模組中，作為第一個運算式出現的字串文本。雖然它
     在套件執行時會被忽略，但它會被編譯器辨識，並被放入所屬 class、函式
     或模組的 ‘__doc__’ 屬性中。由於說明字串可以透過內省 (introspection)
     來瀏覽，因此它是物件的說明文件存放的標準位置。

duck-typing（鴨子型別）

     一種程式設計風格，它不是藉由檢查一個物件的型別來確定它是否具有正確
     的介面；取而代之的是，method 或屬性會單純地被呼叫或使用。（「如果它
     看起來像一隻鴨子而且叫起來像一隻鴨子，那麼它一定是一隻鴨子。」）因
     為強調介面而非特定型別，精心設計的程式碼能讓多形替代 (polymorphic
     substitution) 來增進它的靈活性。鴨子型別要避免使用 *note type():
     6ff. 或 *note isinstance(): 551. 進行測試。（但是請注意，鴨子型別可
     以用*note 抽象基底類別 (abstract base class): c05. 來補充。）然而，
     它通常會採用 *note hasattr(): 54a. 測試，或是 *note EAFP: 20a9. 程
     式設計風格。

EAFP

     Easier to ask for forgiveness than permission.（請求寬恕比請求許可
     更容易。）這種常見的 Python 編碼風格會先假設有效的鍵或屬性的存在，
     並在該假設被推翻時再捕獲例外。這種乾淨且快速的風格，其特色是存在許
     多的 *note try: e37. 和 *note except: c10. 陳述式。該技術與許多其他
     語言（例如 C）常見的 *note LBYL: 452c. 風格形成了對比。

expression（運算式）

     一段可以被評估並求值的語法。換句話說，一個運算式就是文字、名稱、屬
     性存取、運算子或函式呼叫等運算式元件的累積，而這些元件都能回傳一個
     值。與許多其他語言不同的是，並非所有的 Python 語言構造都是運算式。
     另外有一些 *note statement: 1cef.（陳述式）不能被用作運算式，例如
     *note while: 1361.。賦值 (assignment) 也是陳述式，而不是運算式。

extension module（擴充模組）

     一個以 C 或 C++ 編寫的模組，它使用 Python 的 C API 來與核心及使用者
     程式碼進行互動。

f-string（f 字串）

     以 ‘'f'’ 或 ‘'F'’ 為前綴的字串文本通常被稱為「f 字串」，它是*note
     格式化的字串文本: 296.的縮寫。另請參閱 PEP 498(15)。

file object（檔案物件）

     一個讓使用者透過檔案導向 (file-oriented) API（如 ‘read()’ 或
     ‘write()’ 等 method）來操作底層資源的物件。根據檔案物件被建立的方式
     ，它能夠協調對真實磁碟檔案或是其他類型的儲存器或通訊裝置（例如標準
     輸入／輸出、記憶體內緩衝區、socket（插座）、管線 (pipe) 等）的存取
     。檔案物件也被稱為`類檔案物件 (file-like object)' 或`串流
     (stream)'。

     實際上，有三種檔案物件：原始的*note 二進制檔案: 1e01.、緩衝的*note
     二進制檔案: 1e01.和*note 文字檔案: 13d9.。它們的介面在 *note io:
     a1. 模組中被定義。建立檔案物件的標準方法是使用 *note open(): 16f. 函
     式。

file-like object（類檔案物件）

     *note file object: c14.（檔案物件）的同義字。

finder（尋檢器）

     一個物件，它會嘗試為正在被 import 的模組尋找 *note loader: 15f6.（
     載入器）。

     從 Python 3.3 開始，有兩種類型的尋檢器：*note 元路徑尋檢器 (meta
     path finder): a91. 會使用 *note sys.meta_path: 6dd.，而*note
     路徑項目尋檢器 (path entry finder): a92. 會使用 *note
     sys.path_hooks: a3d.。

     請參閱 PEP 302(16)、 PEP 420(17) 和 PEP 451(18) 以了解更多細節。

floor division（向下取整除法）

     向下無條件捨去到最接近整數的數學除法。向下取整除法的運算子是 ‘//’。
     例如，運算式 ‘11 // 4’ 的計算結果為 ‘2’，與 float（浮點數）真除法所
     回傳的 ‘2.75’ 不同。請注意，‘(-11) // 4’ 的結果是 ‘-3’，因為是
     ‘-2.75’ 被`向下'無條件捨去。請參閱 PEP 238(19)。

function（函式）

     一連串的陳述式，它能夠向呼叫者回傳一些值。它也可以被傳遞零個或多個
     *note 引數: 165b.，這些引數可被使用於函式本體的執行。另請參閱 *note
     parameter: 1664.（參數）、*note method: 4524.（方法），以及*note
     函数定义: 1390.章節。

function annotation（函式註釋）

     函式參數或回傳值的一個 *note annotation: 1587.（註釋）。

     函式註釋通常被使用於*note 型別提示: 158b.：例如，這個函式預期會得到
     兩個 *note int: 204. 引數，並會有一個 *note int: 204. 回傳值：

          def sum_two_numbers(a: int, b: int) -> int:
             return a + b

     函式註釋的語法在*note 函数定义: 1390.章節有詳細解釋。

     請參閱 *note variable annotation: 712. 和 PEP 484(20)，皆有此功能的
     描述。

__future__

     *note future 陳述式: 16c4.：‘from __future__ import <feature>’，會
     指示編譯器使用那些在 Python 未來的發布版本中將成為標準的語法或語義
     ，來編譯當前的模組。而 *note __future__: 0. 模組則記錄了 `feature（
     功能）'可能的值。透過 import 此模組並對其變數求值，你可以看見一個新
     的功能是何時首次被新增到此語言中，以及它何時將會（或已經）成為預設
     的功能：

          >>> import __future__
          >>> __future__.division
          _Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192)

garbage collection（垃圾回收）

     當記憶體不再被使用時，將其釋放的過程。Python 執行垃圾回收，是透過參
     照計數 (reference counting)，以及一個能夠檢測和中斷參照循環
     (reference cycle) 的循環垃圾回收器 (cyclic garbage collector) 來完
     成。垃圾回收器可以使用 *note gc: 84. 模組對其進行控制。

generator（產生器）

     一個會回傳 *note generator iterator: 558.（產生器疊代器）的函式。它
     看起來像一個正常的函式，但不同的是它包含了 *note yield: 2c7. 運算式
     ，能產生一系列的值，這些值可用於 for 迴圈，或是以 *note next():
     775. 函式，每次檢索其中的一個值。

     這個術語通常用來表示一個產生器函式，但在某些情境中，也可能是表示`產
     生器疊代器'。萬一想表達的意思不夠清楚，那就使用完整的術語，以避免歧
     義。

generator iterator（產生器疊代器）

     一個由 *note generator: a83.（產生器）函式所建立的物件。

     每個 *note yield: 2c7. 會暫停處理程序，並記住位置執行狀態（包括區域
     變數及擱置中的 try 陳述式）。當`產生器疊代器'回復時，它會從停止的地
     方繼續執行（與那些每次調用時都要重新開始的函式有所不同）。

generator expression（產生器運算式）

     一個會回傳疊代器的運算式。它看起來像一個正常的運算式，後面接著一個
     ‘for’ 子句，該子句定義了迴圈變數、範圍以及一個選擇性的 ‘if’ 子句。
     該組合運算式會為外層函數產生多個值：

          >>> sum(i*i for i in range(10))         # sum of squares 0, 1, 4, ... 81
          285

generic function（泛型函式）

     一個由多個函式組成的函式，該函式會對不同的型別實作相同的運算。呼叫
     期間應該使用哪種實作，是由調度演算法 (dispatch algorithm) 來決定。

     另請參閱 *note single dispatch: 2fb.（單一調度）術語表條目、*note
     functools.singledispatch(): 490. 裝飾器和 PEP 443(21)。

generic type（泛型型別）

     A *note type: fe9. that can be parameterized; typically a *note
     container class: 1594. such as *note list: 1f8. or *note dict: 164.
     Used for *note type hints: 158b. and *note annotations: 1587.

     For more details, see *note generic alias types: fe5, PEP 483(22),
     PEP 484(23), PEP 585(24), and the *note typing: 122. module.

GIL

     請參閱 *note global interpreter lock: 5ff.（全域直譯器鎖）。

global interpreter lock（全域直譯器鎖）

     *note CPython: 1569. 直譯器所使用的機制，用以確保每次都只有一個執行
     緒能執行 Python 的 *note bytecode: 709.（位元組碼）。透過使物件模型
     （包括關鍵的內建型別，如 *note dict: 164.）自動地避免並行存取
     (concurrent access) 的危險，此機制可以簡化 CPython 的實作。鎖定整個
     直譯器，會使直譯器更容易成為多執行緒 (multi-threaded)，但代價是會犧
     牲掉多處理器的機器能夠提供的一大部分平行性 (parallelism)。

     然而，有些擴充模組，無論是標準的或是第三方的，它們被設計成在執行壓
     縮或雜湊等計算密集 (computationally-intensive) 的任務時，可以解除
     GIL。另外，在執行 I/O 時，GIL 總是會被解除。

     過去對於建立「無限制執行緒」直譯器（以更高的精細度鎖定共享資料的直
     譯器）的努力並未成功，因為在一般的單一處理器情況下，效能會有所損失
     。一般認為，若要克服這個效能問題，會使實作變得複雜許多，進而付出更
     高的維護成本。

hash-based pyc（雜湊架構的 pyc）

     一個位元組碼 (bytecode) 暫存檔，它使用雜湊值而不是對應原始檔案的最
     後修改時間，來確定其有效性。請參閱*note 已缓存字节码的失效: 439.。

hashable（可雜湊的）

     如果一個物件有一個雜湊值，該值在其生命週期中永不改變（它需要一個
     *note __hash__(): 44c. method），且可與其他物件互相比較（它需要一個
     *note __eq__(): 44b. method），那麼它就是一個`可雜湊'物件。比較結果
     為相等的多個可雜湊物件，它們必須擁有相同的雜湊值。

     可雜湊性 (hashability) 使一個物件可用作 dictionary（字典）的鍵和
     set（集合）的成員，因為這些資料結構都在其內部使用了雜湊值。

     大多數的 Python 不可變內建物件都是可雜湊的；可變的容器（例如 list 或
     dictionary）並不是；而不可變的容器（例如 tuple（元組）和 frozenset）
     ，只有當它們的元素是可雜湊的，它們本身才是可雜湊的。若物件是使用者
     自定 class 的實例，則這些物件會被預設為可雜湊的。它們在互相比較時都
     是不相等的（除非它們與自己比較），而它們的雜湊值則是衍生自它們的
     *note id(): e4b.。

IDLE

     Python 的 Integrated Development Environment（整合開發環境）。IDLE
     是一個基本的編輯器和直譯器環境，它和 Python 的標準發行版本一起被提
     供。

immutable（不可變物件）

     一個具有固定值的物件。不可變物件包括數字、字串和 tuple（元組）。這
     類物件是不能被改變的。如果一個不同的值必須被儲存，則必須建立一個新
     的物件。它們在需要恆定雜湊值的地方，扮演重要的角色，例如
     dictionary（字典）中的一個鍵。

import path（匯入路徑）

     一個位置（或*note 路徑項目: 160b.）的列表，而那些位置就是在 import
     模組時，會被 *note path based finder: 15fb.（基於路徑的尋檢器）搜尋
     模組的位置。在 import 期間，此位置列表通常是來自 *note sys.path:
     261.，但對於子套件 (subpackage) 而言，它也可能是來自父套件的
     ‘__path__’ 屬性。

importing（匯入）

     一個過程。一個模組中的 Python 程式碼可以透過此過程，被另一個模組中
     的 Python 程式碼使用。

importer（匯入器）

     一個能夠尋找及載入模組的物件；它既是 *note finder: 15f5.（尋檢器）
     也是 *note loader: 15f6.（載入器）物件。

interactive（互動的）

     Python 有一個互動式直譯器，這表示你可以在直譯器的提示字元輸入陳述式
     和運算式，立即執行它們並且看到它們的結果。只要啟動 ‘python’，不需要
     任何引數（可能藉由從你的電腦的主選單選擇它）。這是測試新想法或檢查
     模塊和包的非常強大的方法（請記住help(x)）。

interpreted（直譯的）

     Python 是一種直譯語言，而不是編譯語言，不過這個區分可能有些模糊，因
     為有位元組碼 (bytecode) 編譯器的存在。這表示原始檔案可以直接被運行
     ，而不需明確地建立另一個執行檔，然後再執行它。直譯語言通常比編譯語
     言有更短的開發／除錯週期，不過它們的程式通常也運行得較慢。另請參閱
     *note interactive: 4531.（互動的）。

interpreter shutdown（直譯器關閉）

     當 Python 直譯器被要求關閉時，它會進入一個特殊階段，在此它逐漸釋放
     所有被配置的資源，例如模組和各種關鍵內部結構。它也會多次呼叫*note
     垃圾回收器 (garbage collector): fc8.。這能夠觸發使用者自定的解構函
     式 (destructor) 或弱引用的回呼 (weakref callback)，並執行其中的程式
     碼。在關閉階段被執行的程式碼會遇到各種例外，因為它所依賴的資源可能
     不再有作用了（常見的例子是函式庫模組或是警告機制）。

     直譯器關閉的主要原因，是 ‘__main__’ 模組或正被運行的腳本已經執行完
     成。

iterable（可疊代物件）

     一種能夠一次回傳一個其中成員的物件。可疊代物件的例子包括所有的序列
     型別（像是 *note list: 1f8.、*note str: 205. 和 *note tuple: 1a2.）
     和某些非序列型別，像是 *note dict: 164.、*note 檔案物件: c14.，以及
     你所定義的任何 class 物件，只要那些 class 有 *note __iter__(): 608.
     method 或是實作 *note Sequence: 135c.（序列）語意的 *note
     __getitem__(): 3a5. method，該物件就是可疊代物件。

     可疊代物件可用於 *note for: cfa. 迴圈和許多其他需要一個序列的地方
     (*note zip(): cfc.、*note map(): cf7...)。當一個可疊代物件作為引數
     被傳遞給內建函式 *note iter(): ded. 時，它會為該物件回傳一個疊代器
     。此疊代器適用於針對一組值進行一遍 (one pass) 運算。使用疊代器時，
     通常不一定要呼叫 *note iter(): ded. 或自行處理疊代器物件。‘for’ 陳
     述式會自動地為你處理這些事，它會建立一個暫時性的未命名變數，用於在
     迴圈期間保有該疊代器。另請參閱 *note iterator: 1171.（疊代器）、
     *note sequence: 135c.（序列）和 *note generator: a83.（產生器）。

iterator（疊代器）

     一個表示資料流的物件。重複地呼叫疊代器的 *note __next__(): d2c.
     method（或是將它傳遞給內建函式 *note next(): 775.）會依序回傳資料流
     中的各項目。當不再有資料時，則會引發 *note StopIteration: 581. 例外
     。此時，該疊代器物件已被用盡，而任何對其 ‘__next__()’ method 的進一
     步呼叫，都只會再次引發 *note StopIteration: 581.。疊代器必須有一個
     *note __iter__(): 608. method，它會回傳疊代器物件本身，所以每個疊代
     器也都是可疊代物件，且可以用於大多數適用其他可疊代物件的場合。一個
     明顯的例外，是嘗試多遍疊代 (multiple iteration passes) 的程式碼。一
     個容器物件（像是 *note list: 1f8.）在每次你將它傳遞給 *note iter():
     ded. 函式或在 *note for: cfa. 迴圈中使用它時，都會產生一個全新的疊
     代器。使用疊代器嘗試此事（多遍疊代）時，只會回傳在前一遍疊代中被用
     過的、同一個已被用盡的疊代器物件，使其看起來就像一個空的容器。

     在*note 迭代器类型: 159a.文中可以找到更多資訊。

key function（鍵函式）

     鍵函式或理序函式 (collation function) 是一個可呼叫 (callable) 函式
     ，它會回傳一個用於排序 (sorting) 或定序 (ordering) 的值。例如，
     *note locale.strxfrm(): 31c3. 被用來產生一個了解區域特定排序慣例的
     排序鍵。

     Python 中的許多工具，都接受以鍵函式來控制元素被定序或分組的方式。它
     們包括 *note min(): 8f6.、*note max(): 8f7.、*note sorted(): 546.、
     *note list.sort(): 547.、*note heapq.merge(): 7d1.、*note
     heapq.nsmallest(): 1ab3.、*note heapq.nlargest(): 1ab2. 和 *note
     itertools.groupby(): 1c9d.。

     有幾種方法可以建立一個鍵函式。例如，*note str.lower(): 1777. method
     可以作為不分大小寫排序的鍵函式。或者，一個鍵函式也可以從 *note
     lambda: cf9. 運算式被建造，例如 ‘lambda r: (r[0], r[2])’。另外，
     *note operator: c2. 模組提供了三個鍵函式的建構函式 (constructor)：
     *note attrgetter(): 80a.、*note itemgetter(): 38b. 和 *note
     methodcaller(): 80b.。關於如何建立和使用鍵函式的範例，請參閱*note
     如何排序: 1737.。

keyword argument（關鍵字引數）

     請參閱 *note argument: 165b.（引數）。

lambda

     由單一 *note expression: 158f.（運算式）所組成的一個匿名行內函式
     (inline function)，於該函式被呼叫時求值。建立 lambda 函式的語法是
     ‘lambda [parameters]: expression’。

LBYL

     Look before you leap.（三思而後行。）這種編碼風格會在進行呼叫或查找
     之前，明確地測試先決條件。這種風格與 *note EAFP: 20a9. 方式形成對比
     ，且它的特色是會有許多 *note if: eab. 陳述式的存在。

     在一個多執行緒環境中，LBYL 方式有在「三思」和「後行」之間引入了競爭
     條件 (race condition) 的風險。例如以下程式碼 ‘if key in mapping:
     return mapping[key]’，如果另一個執行緒在測試之後但在查找之前，從
     `mapping' 中移除了 `key'，則該程式碼就會失效。這個問題可以用鎖
     (lock) 或使用 EAFP 編碼方式來解決。

list（串列）

     一個 Python 內建的 *note sequence: 135c. （序列）。儘管它的名字是
     list，它其實更類似其他語言中的一個陣列 (array) 而較不像一個鏈結串列
     (linked list)，因為存取元素的時間複雜度是 O(1)。

list comprehension（串列綜合運算）

     一種用來處理一個序列中的全部或部分元素，並將處理結果以一個 list 回
     傳的簡要方法。‘result = ['{:#04x}'.format(x) for x in range(256) if
     x % 2 == 0]’ 會產生一個字串 list，其中包含 0 到 255 範圍內，所有偶
     數的十六進位數 (0x..)。*note if: eab. 子句是選擇性的。如果省略它，
     則 ‘range(256)’ 中的所有元素都會被處理。

loader（載入器）

     一個能夠載入模組的物件。它必須定義一個名為 ‘load_module()’ 的
     method（方法）。載入器通常是被 *note finder: 15f5.（尋檢器）回傳。
     更多細節請參閱 PEP 302(25)，關於 *note abstract base class: c05.（
     抽象基底類別），請參閱 *note importlib.abc.Loader: 8af.。

magic method（魔術方法）

     *note special method: 3806.（特殊方法）的一個非正式同義詞。

mapping（對映）

     一個容器物件，它支援任意鍵的查找，且能實作 *note abstract base
     classes（抽象基底類別）: 15e.中，*note Mapping: 15f. 或 *note
     MutableMapping: ace. 所指定的 method。範例包括 *note dict: 164.、
     *note collections.defaultdict: c0c.、*note collections.OrderedDict:
     2ea. 和 *note collections.Counter: ab9.。

meta path finder（元路徑尋檢器）

     一種經由搜尋 *note sys.meta_path: 6dd. 而回傳的 *note finder:
     15f5.（尋檢器）。元路徑尋檢器與*note 路徑項目尋檢器 (path entry
     finder): a92. 相關但是不同。

     關於元路徑尋檢器實作的 method，請參閱 *note
     importlib.abc.MetaPathFinder: a93.。

metaclass（元類別）

     一種 class 的 class。Class 定義過程會建立一個 class 名稱、一個
     class dictionary（字典），以及一個 base class（基底類別）的列表。
     Metaclass 負責接受這三個引數，並建立該 class。大多數的物件導向程式
     語言會提供一個預設的實作。Python 的特別之處在於它能夠建立自訂的
     metaclass。大部分的使用者從未需要此工具，但是當需要時，metaclass 可
     以提供強大且優雅的解決方案。它們已被用於記錄屬性存取、增加執行緒安
     全性、追蹤物件建立、實作單例模式 (singleton)，以及許多其他的任務。

     更多資訊可以在*note 元类: 157c.章節中找到。

method（方法）

     一個在 class 本體內被定義的函式。如果 method 作為其 class 實例的一
     個屬性被呼叫，則它將會得到該實例物件成為它的第一個 *note argument:
     165b.（引數）（此引數通常被稱為 ‘self’）。請參閱 *note function:
     165c.（函式）和 *note nested scope: 1721.（巢狀作用域）。

method resolution order（方法解析順序）

     方法解析順序是在查找某個成員的過程中，base class（基底類別）被搜尋
     的順序。關於第 2.3 版至今，Python 直譯器所使用的演算法細節，請參閱
     Python 2.3 版方法解析順序(26)。

module（模組）

     一個擔任 Python 程式碼的組織單位 (organizational unit) 的物件。模組
     有一個命名空間，它包含任意的 Python 物件。模組是藉由 *note
     importing: 15e8. 的過程，被載入至 Python。

     另請參閱 *note package: 15eb.（套件）。

module spec（模組規格）

     一個命名空間，它包含用於載入模組的 import 相關資訊。它是 *note
     importlib.machinery.ModuleSpec: 1601. 的一個實例。

MRO

     請參閱 *note method resolution order: 1739.（方法解析順序）。

mutable（可變物件）

     可變物件可以改變它們的值，但維持它們的 *note id(): e4b.。另請參閱
     *note immutable: 1356.（不可變物件）。

named tuple（附名元組）

     術語「named tuple（附名元組）」是指從 tuple 繼承的任何型別或 class，
     且它的可索引 (indexable) 元素也可以用附名屬性來存取。這些型別或
     class 也可以具有其他的特性。

     有些內建型別是 named tuple，包括由 *note time.localtime(): 1080. 和
     *note os.stat(): 321. 回傳的值。另一個例子是 *note sys.float_info:
     10fc.：

          >>> 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

     有些 named tuple 是內建型別（如上例）。或者，一個 named tuple 也可
     以從一個正規的 class 定義來建立，只要該 class 是繼承自 *note tuple:
     1a2.，且定義了附名欄位 (named field) 即可。這類的 class 可以手工編
     寫，也可以使用工廠函式 (factory function) *note
     collections.namedtuple(): 1a1. 來建立。後者技術也增加了一些額外的
     method，這些 method 可能是在手寫或內建的 named tuple 中，無法找到的
     。

namespace（命名空間）

     變數被儲存的地方。命名空間是以 dictionary（字典）被實作。有區域的、
     全域的及內建的命名空間，而在物件中（在 method 中）也有巢狀的命名空
     間。命名空間藉由防止命名衝突，來支援模組化。例如，函式 *note
     builtins.open: 16f. 和 *note os.open(): 758. 是透過它們的命名空間來
     區分彼此。命名空間也藉由明確地區分是哪個模組在實作一個函式，來增進
     可讀性及可維護性。例如，寫出 *note random.seed(): cd3. 或 *note
     itertools.islice(): 4a8. 明確地表示，這些函式分別是由 *note random:
     dc. 和 *note itertools: a3. 模組在實作。

namespace package（命名空間套件）

     一個 PEP 420(27) *note package: 15eb.（套件），它只能作為子套件
     (subpackage) 的一個容器。命名空間套件可能沒有實體的表示法，而且具體
     來說它們不像是一個 *note regular package: 15ed.（正規套件），因為它
     們並沒有 ‘__init__.py’ 這個檔案。

     另請參閱 *note module: 15e7.（模組）。

nested scope（巢狀作用域）

     能夠參照外層定義 (enclosing definition) 中的變數的能力。舉例來說，
     一個函式如果是在另一個函式中被定義，則它便能夠參照外層函式中的變數
     。請注意，在預設情況下，巢狀作用域僅適用於參照，而無法用於賦值。區
     域變數能在最內層作用域中讀取及寫入。同樣地，全域變數是在全域命名空
     間中讀取及寫入。*note nonlocal: d07. 容許對外層作用域進行寫入。

new-style class（新式類別）

     一個舊名，它是指現在所有的 class 物件所使用的 class 風格。在早期的
     Python 版本中，只有新式 class 才能使用 Python 較新的、多樣的功能，
     像是 *note __slots__: eef.、描述器 (descriptor)、屬性 (property)、
     *note __getattribute__(): 549.、class method（類別方法）和 static
     method（靜態方法）。

object（物件）

     具有狀態（屬性或值）及被定義的行為（method）的任何資料。它也是任何
     *note new-style class: 1e09.（新式類別）的最終 base class（基底類別
     ）。

package（套件）

     一個 Python 的 *note module: 15e7.（模組），它可以包含子模組
     (submodule) 或是遞迴的子套件 (subpackage)。技術上而言，套件就是具有
     ‘__path__’ 屬性的一個 Python 模組。

     另請參閱 *note regular package: 15ed.（正規套件）和 *note namespace
     package: 15ee.（命名空間套件）。

parameter（參數）

     在 *note function: 165c.（函式）或 method 定義中的一個命名實體
     (named entity)，它指明該函式能夠接受的一個 *note argument: 165b.（
     引數），或在某些情況下指示多個引數。共有有五種不同的參數類型：

        * `positional-or-keyword'（位置或關鍵字）：指明一個可以*note
          按照位置: 165b.或是作為*note 關鍵字引數: 165b.被傳遞的引數。這
          是參數的預設類型，例如以下的 `foo' 和 `bar'：

               def func(foo, bar=None): ...

        * `positional-only'（僅限位置）：指明一個只能按照位置被提供的引
          數。在函式定義的參數列表中包含一個 ‘/’ 字元，就可以在該字元前
          面定義僅限位置參數，例如以下的 `posonly1' 和 `posonly2'：

               def func(posonly1, posonly2, /, positional_or_keyword): ...

        * `keyword-only'（僅限關鍵字）：指明一個只能以關鍵字被提供的引數
          。在函式定義的參數列表中，包含一個任意數量位置參數
          (var-positional parameter) 或是單純的 ‘*’ 字元，就可以在其後方
          定義僅限關鍵字參數，例如以下的 `kw_only1' 和 `kw_only2'：

               def func(arg, *, kw_only1, kw_only2): ...

        * `var-positional'（任意數量位置）：指明一串能以任意序列被提供的
          位置引數（在已被其他參數接受的任何位置引數之外）。這類參數是透
          過在其參數名稱字首加上 ‘*’ 來定義的，例如以下的 `args'：

               def func(*args, **kwargs): ...

        * `var-keyword'（任意數量關鍵字）：指明可被提供的任意數量關鍵字
          引數（在已被其他參數接受的任何關鍵字引數之外）。這類參數是透過
          在其參數名稱字首加上 ‘**’ 來定義的，例如上面範例中的 `kwargs'。

     參數可以指明引數是選擇性的或必需的，也可以為一些選擇性的引數指定預
     設值。

     另請參閱術語表的 *note argument: 165b.（引數）條目、常見問題中的
     *note 引數和參數之間的差異: 4473.、*note inspect.Parameter: 7e5.
     class、*note 函数定义: 1390.章節，以及 PEP 362(28)。

path entry（路徑項目）

     在 *note import path: 15f8.（匯入路徑）中的一個位置，而 *note path
     based finder: 15fb. （基於路徑的尋檢器）會參考該位置來尋找要 import
     的模組。

path entry finder（路徑項目尋檢器）

     被 *note sys.path_hooks: a3d. 中的一個可呼叫物件 (callable)（意即一
     個 *note path entry hook: 160d.）所回傳的一種 *note finder: 15f5.，
     它知道如何以一個 *note path entry: 160b.定位模組。

     關於路徑項目尋檢器實作的 method，請參閱 *note
     importlib.abc.PathEntryFinder: a94.。

path entry hook（路徑項目鉤）

     在 ‘sys.path_hook’ 列表中的一個可呼叫物件 (callable)，若它知道如何
     在一個特定的 *note path entry: 160b. 中尋找模組，則會回傳一個 *note
     path entry finder: a92.（路徑項目尋檢器）。

path based finder（基於路徑的尋檢器）

     預設的*note 元路徑尋檢器 (meta path finder): a91. 之一，它會在一個
     *note import path: 15f8. 中搜尋模組。

path-like object（類路徑物件）

     一個表示檔案系統路徑的物件。類路徑物件可以是一個表示路徑的 *note
     str: 205. 或 *note bytes: 172. 物件，或是一個實作 *note
     os.PathLike: 5e5. 協定的物件。透過呼叫 *note os.fspath(): 5e7. 函式
     ，一個支援 *note os.PathLike: 5e5. 協定的物件可以被轉換為 *note
     str: 205. 或 *note bytes: 172. 檔案系統路徑；而 *note
     os.fsdecode(): 5e8. 及 *note os.fsencode(): 5e9. 則分別可用於確保
     *note str: 205. 及 *note bytes: 172. 的結果。由 PEP 519(29) 引入。

PEP

     Python Enhancement Proposal（Python 增強提案）。PEP 是一份設計說明
     文件，它能為 Python 社群提供資訊，或是描述 Python 的一個新功能或該
     功能的程序和環境。PEP 應該要提供簡潔的技術規範以及被提案功能的運作
     原理。

     PEP 的存在目的，是要成為重大新功能的提案、社群中關於某個問題的意見
     收集，以及已納入 Python 的設計決策的記錄，這些過程的主要機制。PEP 的
     作者要負責在社群內建立共識並記錄反對意見。

     請參閱 PEP 1(30)。

portion（部分）

     在單一目錄中的一組檔案（也可能儲存在一個 zip 檔中），這些檔案能對一
     個命名空間套件 (namespace package) 有所貢獻，如同 PEP 420(31) 中的
     定義。

positional argument（位置引數）

     請參閱 *note argument: 165b.（引數）。

provisional API（暫行 API）

     暫行 API 是指，從標準函式庫的向後相容性 (backwards compatibility) 保
     證中，故意被排除的 API。雖然此類介面，只要它們被標示為暫行的，理論
     上並不會有重大的變更，但如果核心開發人員認為有必要，也可能會出現向
     後不相容的變更（甚至包括移除該介面）。這種變更並不會無端地產生——只
     有 API 被納入之前未察覺的嚴重基本缺陷被揭露時，它們才會發生。

     即使對於暫行 API，向後不相容的變更也會被視為「最後的解決方案」——對
     於任何被發現的問題，仍然會盡可能找出一個向後相容的解決方案。

     這個過程使得標準函式庫能隨著時間不斷進化，而避免耗費過長的時間去鎖
     定有問題的設計錯誤。請參閱 PEP 411(32) 了解更多細節。

provisional package（暫行套件）

     請參閱 *note provisional API: 454.（暫行 API）。

Python 3000

     Python 3.x 系列版本的暱稱（很久以前創造的，當時第 3 版的發布是在遙
     遠的未來。）也可以縮寫為「Py3k」。

Pythonic（Python 風格的）

     一個想法或一段程式碼，它應用了 Python 語言最常見的慣用語，而不是使
     用其他語言常見的概念來實作程式碼。例如，Python 中常見的一種習慣用法
     ，是使用一個 *note for: cfa. 陳述式，對一個可疊代物件的所有元素進行
     迴圈。許多其他語言並沒有這種類型的架構，所以不熟悉 Python 的人有時
     會使用一個數值計數器來代替：

          for i in range(len(food)):
              print(food[i])

     相較之下，以下方法更簡潔、更具有 Python 風格：

          for piece in food:
              print(piece)

qualified name（限定名稱）

     一個「點分隔名稱」，它顯示從一個模組的全域作用域到該模組中定義的
     class、函式或 method 的「路徑」，如 PEP 3155(33) 中的定義。對於頂層
     的函式和 class 而言，限定名稱與其物件名稱相同：

          >>> class C:
          ...     class D:
          ...         def meth(self):
          ...             pass
          ...
          >>> C.__qualname__
          'C'
          >>> C.D.__qualname__
          'C.D'
          >>> C.D.meth.__qualname__
          'C.D.meth'

     當用於引用模組時，`完全限定名稱 (fully qualified name)' 是表示該模
     組的完整點分隔路徑，包括任何的父套件，例如 ‘email.mime.text’：

          >>> import email.mime.text
          >>> email.mime.text.__name__
          'email.mime.text'

reference count（參照計數）

     對於一個物件的參照次數。當一個物件的參照計數下降到零時，它會被解除
     配置 (deallocated)。參照計數通常在 Python 程式碼中看不到，但它卻是
     *note CPython: 1569. 實作的一個關鍵元素。*note sys: fd. 模組定義了
     一個 *note getrefcount(): 37d5. 函式，程序設計師可以呼叫該函式來回
     傳一個特定物件的參照計數。

regular package（正規套件）

     一個傳統的 *note package: 15eb.（套件），例如一個包含 ‘__init__.py’
     檔案的目錄。

     另請參閱 *note namespace package: 15ee.（命名空間套件）。

__slots__

     在 class 內部的一個宣告，它藉由預先宣告實例屬性的空間，以及消除實例
     dictionary（字典），來節省記憶體。雖然該技術很普遍，但它有點難以正
     確地使用，最好保留給那種在一個記憶體關鍵 (memory-critical) 的應用程
     式中存在大量實例的罕見情況。

sequence（序列）

     一個 *note iterable: c7c.（可疊代物件），它透過 *note
     __getitem__(): 3a5. special method（特殊方法），使用整數索引來支援
     高效率的元素存取，並定義了一個 *note __len__(): e90. method 來回傳
     該序列的長度。一些內建序列型別包括 *note list: 1f8.、*note str:
     205.、*note tuple: 1a2. 和 *note bytes: 172.。請注意，雖然 *note
     dict: 164. 也支援 *note __getitem__(): 3a5. 和 *note __len__():
     e90.，但它被視為對映 (mapping) 而不是序列，因為其查找方式是使用任意
     的 *note immutable: 1356. 鍵，而不是整數。

     抽象基底類別 (abstract base class) *note collections.abc.Sequence:
     1764. 定義了一個更加豐富的介面，並不僅止於 *note __getitem__():
     3a5. 和 *note __len__(): e90.，還增加了 ‘count()’、‘index()’、*note
     __contains__(): dee. 和 *note __reversed__(): 628.。實作此擴充介面
     的型別，可以使用 *note register(): ab0. 被明確地註冊。

set comprehension（集合綜合運算）

     一種緊密的方法，用來處理一個可疊代物件中的全部或部分元素，並將處理
     結果以一個 set 回傳。‘results = {c for c in 'abracadabra' if c not
     in 'abc'}’ 會產生一個字串 set：‘{'r', 'd'}’。請參閱*note
     列表、集合与字典的显示: 1628.。

single dispatch（單一調度）

     *note generic function: 2fc.（泛型函式）調度的一種形式，在此，實作
     的選擇是基於單一引數的型別。

slice（切片）

     一個物件，它通常包含一段 *note sequence: 135c.（序列）的某一部分。
     建立一段切片的方法是使用下標符號（subscript notation）‘‘[]‘‘，若要
     給出多個數字，則在數字之間使用冒號，例如 ‘in variable_name[1:3:5]’。
     在括號（下標）符號的內部，會使用 *note slice: ec8. 物件。

special method（特殊方法）

     一種會被 Python 自動呼叫的 method，用於對某種型別執行某種運算，例如
     加法。這種 method 的名稱會在開頭和結尾有兩個下底線。Special method
     在*note 特殊方法名称: 607.中有詳細說明。

statement（陳述式）

     陳述式是一個套組（suite，一個程式碼「區塊」）中的一部分。陳述式可以
     是一個 *note expression: 158f.（運算式），或是含有關鍵字（例如
     *note if: eab.、*note while: 1361. 或 *note for: cfa.）的多種結構之
     一。

text encoding（文字編碼）

     將 Unicode 字串編碼為位元組的一個編解碼器 (codec)。

text file（文字檔案）

     一個能夠讀取和寫入 *note str: 205. 物件的一個 *note file object:
     c14.（檔案物件）。通常，文字檔案實際上是存取位元組導向的資料流
     (byte-oriented datastream) 並會自動處理 *note text encoding: 1731.（
     文字編碼）。文字檔案的例子有：以文字模式（‘'r'’ 或 ‘'w'’）開啟的檔
     案、*note sys.stdin: 41e.、*note sys.stdout: 41f. 以及 *note
     io.StringIO: 91a. 的實例。

     另請參閱 *note binary file: 1e01.（二進制檔案），它是一個能夠讀取和
     寫入*note 類位元組串物件 (bytes-like object): 6df. 的檔案物件。

triple-quoted string（三引號內字串）

     由三個雙引號 (“) 或單引號 (’) 的作為邊界的一個字串。雖然它們並沒有
     提供異於單引號字串的任何額外功能，但基於許多原因，它們仍是很有用的
     。它們讓你可以在字串中包含未跳脫 (unescaped) 的單引號和雙引號，而且
     它們不需使用連續字元 (continuation character) 就可以跨越多行，這使
     得它們在編寫說明字串時特別有用。

type（型別）

     一個 Python 物件的型別決定了它是什麼類型的物件；每個物件都有一個型
     別。一個物件的型別可以用它的 *note __class__: ecc. 屬性來存取，或以
     ‘type(obj)’ 來檢索。

type alias（型別別名）

     一個型別的同義詞，透過將型別指定給一個識別符 (identifier) 來建立。

     型別別名對於簡化*note 型別提示 (type hint): 158b. 很有用。例如：

          def remove_gray_shades(
                  colors: list[tuple[int, int, int]]) -> list[tuple[int, int, int]]:
              pass

     可以寫成這樣，更具有可讀性：

          Color = tuple[int, int, int]

          def remove_gray_shades(colors: list[Color]) -> list[Color]:
              pass

     請參閱 *note typing: 122. 和 PEP 484(34)，有此功能的描述。

type hint（型別提示）

     一種 *note annotation: 1587.（註釋），它指定一個變數、一個 class 屬
     性或一個函式的參數或回傳值的預期型別。

     型別提示是選擇性的，而不是被 Python 強制的，但它們對靜態型別分析工
     具很有用，並能協助 IDE 完成程式碼的補全 (completion) 和重構
     (refactoring)。

     全域變數、class 屬性和函式（不含區域變數）的型別提示，都可以使用
     *note typing.get_type_hints(): 1ef. 來存取。

     請參閱 *note typing: 122. 和 PEP 484(35)，有此功能的描述。

universal newlines（通用換行字元）

     一種解譯文字流 (text stream) 的方式，會將以下所有的情況識別為一行的
     結束：Unix 行尾慣例 ‘'\n'’、Windows 慣例 ‘'\r\n'’ 和舊的 Macintosh
     慣例 ‘'\r'’。請參閱 PEP 278(36) 和 PEP 3116(37)，以及用於 *note
     bytes.splitlines(): 17da. 的附加用途。

variable annotation（變數註釋）

     一個變數或 class 屬性的 *note annotation: 1587.（註釋）。

     註釋變數或 class 屬性時，賦值是選擇性的：

          class C:
              field: 'annotation'

     變數註釋通常用於*note 型別提示 (type hint): 158b.：例如，這個變數預
     期會取得 *note int: 204.（整數）值：

          count: int = 0

     變數註釋的語法在*note 带标注的赋值语句: 16ad.章節有詳細的解釋。

     請參閱 *note function annotation: 1391.（函式註釋）、 PEP 484(38) 和
     PEP 526(39)，皆有此功能的描述。

virtual environment（虛擬環境）

     一個協作隔離 (cooperatively isolated) 的執行環境，能讓 Python 的使
     用者和應用程式得以安裝和升級 Python 發佈套件，而不會對同一個系統上
     運行的其他 Python 應用程式的行為產生干擾。

     另請參閱 *note venv: 12e.。

virtual machine（虛擬機器）

     一部完全由軟體所定義的電腦 (computer)。Python 的虛擬機器會執行由
     *note bytecode: 709.（位元組碼）編譯器所發出的位元組碼。

Zen of Python（Python 之禪）

     Python 設計原則與哲學的列表，其內容有助於理解和使用此語言。此列表可
     以透過在互動式提式字元後輸入「‘import this’」來找到它。

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0484

   (2) https://www.python.org/dev/peps/pep-0526

   (3) https://www.python.org/dev/peps/pep-0362

   (4) https://www.python.org/dev/peps/pep-0492

   (5) https://www.python.org/dev/peps/pep-0492

   (6) https://www.python.org/dev/peps/pep-0525

   (7) https://www.python.org/dev/peps/pep-0492

   (8) https://www.python.org/dev/peps/pep-0492

   (9) https://www.python.org/dev/peps/pep-0492

   (10) https://gvanrossum.github.io/

   (11) https://www.python.org/dev/peps/pep-0343

   (12) https://www.python.org/dev/peps/pep-0492

   (13) https://www.python.org/dev/peps/pep-0492

   (14) https://www.python.org

   (15) https://www.python.org/dev/peps/pep-0498

   (16) https://www.python.org/dev/peps/pep-0302

   (17) https://www.python.org/dev/peps/pep-0420

   (18) https://www.python.org/dev/peps/pep-0451

   (19) https://www.python.org/dev/peps/pep-0238

   (20) https://www.python.org/dev/peps/pep-0484

   (21) https://www.python.org/dev/peps/pep-0443

   (22) https://www.python.org/dev/peps/pep-0483

   (23) https://www.python.org/dev/peps/pep-0484

   (24) https://www.python.org/dev/peps/pep-0585

   (25) https://www.python.org/dev/peps/pep-0302

   (26) https://www.python.org/download/releases/2.3/mro/

   (27) https://www.python.org/dev/peps/pep-0420

   (28) https://www.python.org/dev/peps/pep-0362

   (29) https://www.python.org/dev/peps/pep-0519

   (30) https://www.python.org/dev/peps/pep-0001

   (31) https://www.python.org/dev/peps/pep-0420

   (32) https://www.python.org/dev/peps/pep-0411

   (33) https://www.python.org/dev/peps/pep-3155

   (34) https://www.python.org/dev/peps/pep-0484

   (35) https://www.python.org/dev/peps/pep-0484

   (36) https://www.python.org/dev/peps/pep-0278

   (37) https://www.python.org/dev/peps/pep-3116

   (38) https://www.python.org/dev/peps/pep-0484

   (39) https://www.python.org/dev/peps/pep-0526


File: python.info,  Node: 關於這些說明文件,  Next: 處理錯誤 Bug,  Prev: 術語表,  Up: Top

13 關於這些說明文件
*******************

這些說明文件是透過 Sphinx(1) （一個專為 Python 說明文件所撰寫的文件處理
器）將使用 reStructuredText(2) 撰寫的原始檔轉換而成。

如同 Python 自身，透過自願者的努力下產出文件與封裝後自動化執行工具。若想
要回報臭蟲，請見 *note 處理錯誤 (Bug): 3daf. 頁面，內含相關資訊。我們永
遠歡迎新的自願者加入！

致謝：

   * Fred L. Drake, Jr.，原始 Python 文件工具集的創造者以及一大部份內容
     的作者。

   * 創造 reStructuredText 和 Docutils 工具組的 Docutils(3) 專案；

   * Fredrik Lundh 先生，Sphinx 從他的 Alternative Python Reference(4) 計
     劃中獲得許多的好主意。

* Menu:

* Python 文件的貢獻者們::

   ---------- Footnotes ----------

   (1) http://sphinx-doc.org/

   (2) http://docutils.sourceforge.net/rst.html

   (3) http://docutils.sourceforge.net/

   (4) http://effbot.org/zone/pyref.htm


File: python.info,  Node: Python 文件的貢獻者們,  Up: 關於這些說明文件

13.1 Python 文件的貢獻者們
==========================

許多人都曾為 Python 這門語言、Python 標準函式庫和 Python 說明文件貢獻過
。Python 所發佈的原始碼中含有部份貢獻者的清單，請見 Misc/ACKS(1) 。

正因為 Python 社群的撰寫與貢獻才有這份這麼棒的說明文件 – 感謝所有貢獻過
的人們！

   ---------- Footnotes ----------

   (1) https://github.com/python/cpython/tree/3.9/Misc/ACKS


File: python.info,  Node: 處理錯誤 Bug,  Next: 版權宣告,  Prev: 關於這些說明文件,  Up: Top

14 處理錯誤 (Bug)
*****************

Python 已經是一個以穩定著稱的成熟程式語言。為了維持「穩定」的信譽，開發
者們想知道任何您在 Python 中發現的缺失。

有時候自己直接修復錯誤並且送出一個修正給 Python 會比較快，因為這樣會加速
流程而且不會困擾到太多人。學習如何*note 貢獻給 Python: 4544.。

* Menu:

* 說明文件的錯誤::
* 使用 Python 問題追蹤系統::
* 開始讓自己貢獻 Python::


File: python.info,  Node: 說明文件的錯誤,  Next: 使用 Python 問題追蹤系統,  Up: 處理錯誤 Bug

14.1 說明文件的錯誤
===================

如果您在這份說明文件中發現了錯誤並想要幫助我們改進，請將錯誤報告提交到
*note 追蹤系統 (tracker): 4546.。如果您有相應的修正建議，請一併提交。（
譯者註：如果是繁體中文說明文件翻譯相關的錯誤，請提交到
‘https://github.com/python/python-docs-zh-tw/issues’。）

如果您的時間有限，也可以將說明文件的錯誤報告以電子郵件寄到
<docs@python.org>（程式碼執行的錯誤可以寄到 <python-list@python.org>）。
「docs@」是一個由志工們所運行的郵寄清單；您的請求會被注意到，但可能需要
一些時間才會被處理。

也參考
......

說明文件錯誤(1)

     一系列已被提交至 Python 問題追蹤系統的有關說明文件的錯誤。

問題追蹤系統(2)

     在追蹤系統上回報改進建議的過程簡介。

貢獻說明文件(3)

     給有意成為 Python 說明文件貢獻者的綜合指南。

   ---------- Footnotes ----------

   (1) 
https://bugs.python.org/issue?@filter=status&@filter=components&components=4&status=1&@columns=id,activity,title,status&@sort=-activity

   (2) https://devguide.python.org/tracker/

   (3) 
https://devguide.python.org/docquality/#helping-with-documentation


File: python.info,  Node: 使用 Python 問題追蹤系統,  Next: 開始讓自己貢獻 Python,  Prev: 說明文件的錯誤,  Up: 處理錯誤 Bug

14.2 使用 Python 問題追蹤系統
=============================

對於 Python 本身的錯誤報告，應該透過 Python 錯誤追蹤系統
(‘https://bugs.python.org/’) 提交。這個錯誤追蹤系統提供了一個網頁表單，
可以輸入並提交相關資訊給開發者。

填寫報告的第一步，是確認該問題是否已經被回報過了。這樣做的好處，除了可以
節省開發者的時間，也能讓您了解目前關於該問題的處理進度；有可能已經在下一
個發行版本中修正了這個問題，也有可能需要更詳細的資訊（在這種情況下，如果
可以，非常歡迎您提供資訊！）。要確認是否重複回報，請使用頁面頂端的搜尋框
來搜尋錯誤資料庫。

如果您想回報的問題還沒有在錯誤追蹤系統出現過，請返回並登入 Python 錯誤追
蹤系統。如果您還沒有系統的帳號，請點選「註冊 (Register)」，如果您有
OpenID，也可以在側邊欄中點選其中一個 OpenID 的提供者圖示。您無法以匿名方
式提交錯誤報告。

如果已經登入，那您就可以提交一個錯誤。請點選側邊欄中的「新建 (Create
New)」連結，開啟錯誤回報表單。

提交的表單中有幾個欄位。（譯者註：所有欄位請皆用英文輸入。）在「標題
(Title)」欄位，輸入對該問題`非常'簡短的描述；最好少於十個單字。在「類型
(Type)」欄位，選擇您的問題類型；也要選擇與錯誤相關的「Component（組件）
」和「Versions（版本）」。

在「Comment（說明）」欄位，請詳細描述該問題，包括您預期發生的情況和實際
發生的情況。請確定說明中包含了涉及到的任何擴充模組，以及您當時所使用的硬
體和軟體平台（視情況而定，可以附上版本資訊）。

每一份錯誤報告會被分派給一位開發者，並由他決定要做出什麼變更來修正這個問
題。每當該錯誤有修正動作時，您會收到更新回報。

也參考
......

如何有效地回報錯誤(1)

     這篇文章詳細說明如何建立一份有用的錯誤報告。它描述了什麼樣的資訊是
     有用的，以及這些資訊為什麼有用。

錯誤撰寫指南(2)

     撰寫一份優良錯誤報告的相關資訊。部分的文章內容是針對 Mozilla 專案，
     但它也描述了通用的好習慣。

   ---------- Footnotes ----------

   (1) https://www.chiark.greenend.org.uk/~sgtatham/bugs.html

   (2) https://bugzilla.mozilla.org/page.cgi?id=bug-writing.html


File: python.info,  Node: 開始讓自己貢獻 Python,  Prev: 使用 Python 問題追蹤系統,  Up: 處理錯誤 Bug

14.3 開始讓自己貢獻 Python
==========================

除了只是回報您所發現的錯誤之外，同樣也歡迎您提交修正它們的修補程式
(patch)。您可以在 Python 開發者指南(1)中找到如何開始修補 Python 的更多資
訊。如果您有任何問題，核心導師郵寄清單(2)是一個友善的地方，您可以在那裡
得到，關於 Python 修正錯誤的過程中，所有問題的答案。

   ---------- Footnotes ----------

   (1) https://devguide.python.org/

   (2) 
https://mail.python.org/mailman3/lists/core-mentorship.python.org/


File: python.info,  Node: 版權宣告,  Next: 沿革與授權,  Prev: 處理錯誤 Bug,  Up: Top

15 版權宣告
***********

Python 和這份說明文件的版權：

Copyright © 2001-2022 Python Software Foundation.  All rights reserved.

Copyright © 2000 BeOpen.com 保留一切權利。

Copyright © 1995-2000 Corporation for National Research Initiatives 保留
一切權利。

Copyright © 1991-1995 Stichting Mathematisch Centrum 保留一切權利。

__________________________________________________________________

完整的授權條款資訊請參見*note 沿革與授權: 454c.。


File: python.info,  Node: 沿革與授權,  Next: 發布 Python 模組（舊版）,  Prev: 版權宣告,  Up: Top

16 沿革與授權
*************

* Menu:

* 軟體沿革::
* 關於存取或以其他方式使用 Python 的合約條款::
* 被收錄軟體的授權與致謝::


File: python.info,  Node: 軟體沿革,  Next: 關於存取或以其他方式使用 Python 的合約條款,  Up: 沿革與授權

16.1 軟體沿革
=============

Python 是由荷蘭數學和計算機科學研究學會（CWI，見 ‘https://www.cwi.nl/’）
的 Guido van Rossum 於 1990 年代早期所創造，目的是作為一種稱為 ABC 語言
的後繼者。儘管 Python 包含了許多來自其他人的貢獻，Guido 仍是其主要作者。

1995 年，Guido 在維吉尼亞州雷斯頓的國家創新研究公司（CNRI，見
‘https://www.cnri.reston.va.us/’）繼續他在 Python 的工作，並在那裡發佈了
該軟體的多個版本。

2000 年五月，Guido 和 Python 核心開發團隊轉移到 BeOpen.com 並成立了
BeOpen PythonLabs 團隊。同年十月，PythonLabs 團隊轉移到 Digital
Creations（現為 Zope Corporation；見 ‘https://www.zope.org/’）。2001 年
，Python 軟體基金會（PSF，見 ‘https://www.python.org/psf/’）成立，這是一
個專為擁有 Python 相關的智慧財產權而創立的非營利組織。Zope Corporation 是
PSF 的一個贊助會員。

所有的 Python 版本都是開源的（有關開源的定義，參閱
‘https://opensource.org/’）。歷史上，大多數但非全部的 Python 版本，也是
GPL 相容的；以下表格總結各個版本的差異。

發佈版本             源自               年份             擁有者           GPL 相容性
                                                                          
------------------------------------------------------------------------------------------------
                                                                          
0.9.0 至 1.2         不適用             1991-1995        CWI              是
                                                                          
                                                                          
1.3 至 1.5.2         1.2                1995-1999        CNRI             是
                                                                          
                                                                          
1.6                  1.5.2              2000             CNRI             否
                                                                          
                                                                          
2.0                  1.6                2000             BeOpen.com       否
                                                                          
                                                                          
1.6.1                1.6                2001             CNRI             否
                                                                          
                                                                          
2.1                  2.0+1.6.1          2001             PSF              否
                                                                          
                                                                          
2.0.1                2.0+1.6.1          2001             PSF              是
                                                                          
                                                                          
2.1.1                2.1+2.0.1          2001             PSF              是
                                                                          
                                                                          
2.1.2                2.1.1              2002             PSF              是
                                                                          
                                                                          
2.1.3                2.1.2              2002             PSF              是
                                                                          
                                                                          
2.2 以上             2.1.1              2001 至今        PSF              是
                                                                          

     備註: GPL 相容並不表示我們是在 GPL 下發佈 Python。不像 GPL，所有的
     Python 授權都可以讓您發佈修改後的版本，但不一定要使您的變更成為開源
     。GPL 相容的授權使得 Python 可以結合其他在 GPL 下發佈的軟體一起使用
     ；但其它的授權則不行。

感謝許多的外部志工，在 Guido 指導下的付出，使得這些版本的發佈成為可能。


File: python.info,  Node: 關於存取或以其他方式使用 Python 的合約條款,  Next: 被收錄軟體的授權與致謝,  Prev: 軟體沿革,  Up: 沿革與授權

16.2 關於存取或以其他方式使用 Python 的合約條款
===============================================

Python 軟體和說明文件的授權是基於 *note PSF 授權合約: 4551.。

從 Python 3.8.6 開始，說明文件中的範例、程式庫和其他程式碼，是被雙重授權
(dual licensed) 於 PSF 授權合約以及 *note Zero-Clause BSD 授權: 4552.。

有些被納入 Python 中的軟體是基於不同的授權。這些授權將會與其授權之程式碼
一起被列出。關於這些授權的不完整清單，請參閱*note
被收錄軟體的授權與致謝: 4553.。

* Menu:

* 用於 PYTHON 3.9.9 的 PSF 授權合約: 用於 PYTHON 3 9 9 的 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 授權合約.
* 用於 PYTHON 3.9.9 說明文件內程式碼的 ZERO-CLAUSE BSD 授權: 用於 PYTHON 3 9 9 說明文件內程式碼的 ZERO-CLAUSE BSD 授權.


File: python.info,  Node: 用於 PYTHON 3 9 9 的 PSF 授權合約,  Next: 用於 PYTHON 2 0 的 BEOPEN COM 授權合約,  Up: 關於存取或以其他方式使用 Python 的合約條款

16.2.1 用於 PYTHON 3.9.9 的 PSF 授權合約
----------------------------------------

     1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and
        the Individual or Organization ("Licensee") accessing and otherwise using Python
        3.9.9 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.9 alone or in any derivative
        version, provided, however, that PSF's License Agreement and PSF's notice of
        copyright, i.e., "Copyright © 2001-2022 Python Software Foundation; All Rights
        Reserved" are retained in Python 3.9.9 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.9 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.9.

     4. PSF is making Python 3.9.9 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.9 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

     5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 3.9.9
        FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
        MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 3.9.9, 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.9, Licensee agrees
        to be bound by the terms and conditions of this License Agreement.


File: python.info,  Node: 用於 PYTHON 2 0 的 BEOPEN COM 授權合約,  Next: 用於 PYTHON 1 6 1 的 CNRI 授權合約,  Prev: 用於 PYTHON 3 9 9 的 PSF 授權合約,  Up: 關於存取或以其他方式使用 Python 的合約條款

16.2.2 用於 PYTHON 2.0 的 BEOPEN.COM 授權合約
---------------------------------------------

BEOPEN PYTHON 開源授權合約第 1 版

     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
        ‘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.


File: python.info,  Node: 用於 PYTHON 1 6 1 的 CNRI 授權合約,  Next: 用於 PYTHON 0 9 0 至 1 2 的 CWI 授權合約,  Prev: 用於 PYTHON 2 0 的 BEOPEN COM 授權合約,  Up: 關於存取或以其他方式使用 Python 的合約條款

16.2.3 用於 PYTHON 1.6.1 的 CNRI 授權合約
-----------------------------------------

     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: ‘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.


File: python.info,  Node: 用於 PYTHON 0 9 0 至 1 2 的 CWI 授權合約,  Next: 用於 PYTHON 3 9 9 說明文件內程式碼的 ZERO-CLAUSE BSD 授權,  Prev: 用於 PYTHON 1 6 1 的 CNRI 授權合約,  Up: 關於存取或以其他方式使用 Python 的合約條款

16.2.4 用於 PYTHON 0.9.0 至 1.2 的 CWI 授權合約
-----------------------------------------------

     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.


File: python.info,  Node: 用於 PYTHON 3 9 9 說明文件內程式碼的 ZERO-CLAUSE BSD 授權,  Prev: 用於 PYTHON 0 9 0 至 1 2 的 CWI 授權合約,  Up: 關於存取或以其他方式使用 Python 的合約條款

16.2.5 用於 PYTHON 3.9.9 說明文件內程式碼的 ZERO-CLAUSE BSD 授權
----------------------------------------------------------------

     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.


File: python.info,  Node: 被收錄軟體的授權與致謝,  Prev: 關於存取或以其他方式使用 Python 的合約條款,  Up: 沿革與授權

16.3 被收錄軟體的授權與致謝
===========================

本節是一個不完整但持續增加的授權與致謝清單，對象是在 Python 發佈版本中所
收錄的第三方軟體。

* Menu:

* Mersenne Twister::
* Sockets::
* 非同步 socket 服務::
* Cookie 管理::
* 執行追蹤::
* UUencode 與 UUdecode 函式::
* XML 遠端程序呼叫::
* test_epoll::
* Select kqueue::
* SipHash24::
* strtod 與 dtoa::
* OpenSSL::
* expat::
* libffi::
* zlib: zlib<3>.
* cfuhash::
* libmpdec::
* W3C C14N 測試套件::


File: python.info,  Node: Mersenne Twister,  Next: Sockets,  Up: 被收錄軟體的授權與致謝

16.3.1 Mersenne Twister
-----------------------

‘_random’ 模組包含了以
‘http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/emt19937ar.html’
的下載內容為基礎的程式碼。以下是原始程式碼的完整聲明：

     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)


File: python.info,  Node: Sockets,  Next: 非同步 socket 服務,  Prev: Mersenne Twister,  Up: 被收錄軟體的授權與致謝

16.3.2 Sockets
--------------

*note socket: ef. 模組使用 ‘getaddrinfo()’ 和 ‘getnameinfo()’ 函式，它們
在 WIDE 專案（‘http://www.wide.ad.jp/’）內，於不同的原始檔案中被編碼：

     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 ``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 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.


File: python.info,  Node: 非同步 socket 服務,  Next: Cookie 管理,  Prev: Sockets,  Up: 被收錄軟體的授權與致謝

16.3.3 非同步 socket 服務
-------------------------

*note asynchat: 8. 和 *note asyncore: a. 模組包含以下聲明：

     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.


File: python.info,  Node: Cookie 管理,  Next: 執行追蹤,  Prev: 非同步 socket 服務,  Up: 被收錄軟體的授權與致謝

16.3.4 Cookie 管理
------------------

*note http.cookies: 95. 模組包含以下聲明：

     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.


File: python.info,  Node: 執行追蹤,  Next: UUencode 與 UUdecode 函式,  Prev: Cookie 管理,  Up: 被收錄軟體的授權與致謝

16.3.5 執行追蹤
---------------

*note trace: 11b. 模組包含以下聲明：

     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.


File: python.info,  Node: UUencode 與 UUdecode 函式,  Next: XML 遠端程序呼叫,  Prev: 執行追蹤,  Up: 被收錄軟體的授權與致謝

16.3.6 UUencode 與 UUdecode 函式
--------------------------------

*note uu: 12c. 模組包含以下聲明：

     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


File: python.info,  Node: XML 遠端程序呼叫,  Next: test_epoll,  Prev: UUencode 與 UUdecode 函式,  Up: 被收錄軟體的授權與致謝

16.3.7 XML 遠端程序呼叫
-----------------------

*note xmlrpc.client: 148. 模組包含以下聲明：

         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.


File: python.info,  Node: test_epoll,  Next: Select kqueue,  Prev: XML 遠端程序呼叫,  Up: 被收錄軟體的授權與致謝

16.3.8 test_epoll
-----------------

‘test_epoll’ 模組包含以下聲明：

     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.


File: python.info,  Node: Select kqueue,  Next: SipHash24,  Prev: test_epoll,  Up: 被收錄軟體的授權與致謝

16.3.9 Select kqueue
--------------------

*note select: e5. 模組對於 kqueue 介面包含以下聲明：

     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 ``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.


File: python.info,  Node: SipHash24,  Next: strtod 與 dtoa,  Prev: Select kqueue,  Up: 被收錄軟體的授權與致謝

16.3.10 SipHash24
-----------------

‘Python/pyhash.c’ 檔案包含 Marek Majkowski’ 基於 Dan Bernstein 的
SipHash24 演算法的實作。它包含以下聲明：

     <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)


File: python.info,  Node: strtod 與 dtoa,  Next: OpenSSL,  Prev: SipHash24,  Up: 被收錄軟體的授權與致謝

16.3.11 strtod 與 dtoa
----------------------

‘Python/dtoa.c’ 檔案提供了 C 的 dtoa 和 strtod 函式，用於將 C 的雙精度浮
點數和字串互相轉換。該檔案是衍生自 David M. Gay 建立的同名檔案，後者現在
可以從 ‘http://www.netlib.org/fp/’ 下載。於 2009 年 3 月 16 日所檢索的原
始檔案包含以下版權與授權聲明：

     /****************************************************************
      *
      * 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.
      *
      ***************************************************************/


File: python.info,  Node: OpenSSL,  Next: expat,  Prev: strtod 與 dtoa,  Up: 被收錄軟體的授權與致謝

16.3.12 OpenSSL
---------------

如果 OpenSSL 函式庫可被作業系統使用，則 *note hashlib: 8c.、*note posix:
d1.、*note ssl: f3.、*note crypt: 28. 模組會使用它來提升效能。此外，因為
Windows 和 macOS 的 Python 安裝程式可能包含 OpenSSL 函式庫的副本，所以我
們也在此收錄 OpenSSL 授權的副本：

      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 ``AS IS'' 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 ``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.
         *
         * 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.]
         */


File: python.info,  Node: expat,  Next: libffi,  Prev: OpenSSL,  Up: 被收錄軟體的授權與致謝

16.3.13 expat
-------------

除非在建置 ‘pyexpat’ 擴充時設定為 ‘--with-system-expat’，否則該擴充會用
一個內含 expat 原始碼的副本來建置：

     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.


File: python.info,  Node: libffi,  Next: zlib<3>,  Prev: expat,  Up: 被收錄軟體的授權與致謝

16.3.14 libffi
--------------

除非在建置 ‘_ctypes’ 擴充時設定為 ‘--with-system-libffi’，否則該擴充會用
一個內含 libffi 原始碼的副本來建置：

     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
     ``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.


File: python.info,  Node: zlib<3>,  Next: cfuhash,  Prev: libffi,  Up: 被收錄軟體的授權與致謝

16.3.15 zlib
------------

如果在系統上找到的 zlib 版本太舊以致於無法用於建置 *note zlib: 14d. 擴充
，則該擴充會用一個內含 zlib 原始碼的副本來建置：

     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


File: python.info,  Node: cfuhash,  Next: libmpdec,  Prev: zlib<3>,  Up: 被收錄軟體的授權與致謝

16.3.16 cfuhash
---------------

*note tracemalloc: 11d. 使用的雜湊表 (hash table) 實作，是以 cfuhash 專
案為基礎：

     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.


File: python.info,  Node: libmpdec,  Next: W3C C14N 測試套件,  Prev: cfuhash,  Up: 被收錄軟體的授權與致謝

16.3.17 libmpdec
----------------

除非在建置 ‘_decimal’ 模組時設定為 ‘--with-system-libmpdec’，否則該模組
會用一個內含 libmpdec 函式庫的副本來建置：

     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.


File: python.info,  Node: W3C C14N 測試套件,  Prev: libmpdec,  Up: 被收錄軟體的授權與致謝

16.3.18 W3C C14N 測試套件
-------------------------

*note test: 105. 程式包中的 C14N 2.0 測試套件
(‘Lib/test/xmltestdata/c14n-20/’) 是從 W3C 網站
‘https://www.w3.org/TR/xml-c14n2-testcases/’ 被檢索，且是基於 3-clause
BSD 授權被發佈：

     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.


File: python.info,  Node: 發布 Python 模組（舊版）,  Next: 安裝 Python 模組（舊版）,  Prev: 沿革與授權,  Up: Top

17 發布 Python 模組（舊版）
***************************


作者: Greg Ward ， Anthony Baxter


电子邮箱: <distutils-sig@python.org>

也參考
......

*note 發布 Python 模組: 8e3.

     最新的模块分发文档

     備註: 这篇文档只有在
     ‘https://setuptools.readthedocs.io/en/latest/setuptools.html’ 上的
     ‘setuptools’ 文档独立涵盖此处包含的所有相关信息之前，才会单独保留。

     備註: 本指南仅介绍构建和分发扩展的基本工具，这些扩展是作为此
     Python版本的一部分提供的。 第三方工具提供更易于使用和更安全的替代方
     案。有关详细信息，请参阅 Python 打包用户指南中的 快速推荐部分(1) 。

本文档从模块开发人员的角度描述了 Python Distribution Utilities
("Distutils")。 描述了 ‘setuptools’ 构建所依赖的下层功能，以允许 Python
开发者方便地为更广泛的受众编写 Python 模块和扩展。

* Menu:

* Distutils 模块介绍::
* 编写安装脚本::
* 编写设置脚本的配置文件::
* Creating a Source Distribution::
* 创建构建分布::
* Distutils 示例::
* 扩展 Distutils::
* 指令參照::
* API參照::

   ---------- Footnotes ----------

   (1) https://packaging.python.org/guides/tool-recommendations/


File: python.info,  Node: Distutils 模块介绍,  Next: 编写安装脚本,  Up: 發布 Python 模組（舊版）

17.1 Distutils 模块介绍
=======================

     備註: 这篇文档是历史遗留文档，在
     ‘https://setuptools.readthedocs.io/en/latest/setuptools.html’ 上的
     ‘setuptools’ 文档独立涵盖此处包含的所有相关信息之后，将不再单独作为
     正式文档保留。

本文档介绍了使用 Distutils 模块分发你的 Python 模块，主要是针对开发者/分
发者的使用的——如果你想了解如何安装 Python 模块，你应该参考这个章节：
*note 安裝 Python 模組（舊版）: 8e4.。

* Menu:

* 概念和术语::
* 一个简单的例子: 一个简单的例子<3>.
* 通用的 Python 术语::
* Distutils 特定的术语::


File: python.info,  Node: 概念和术语,  Next: 一个简单的例子<3>,  Up: Distutils 模块介绍

17.1.1 概念和术语
-----------------

Distutils 用起来非常简单，对于模块开发者或安装第三方模块的用户/管理员均
是如此。开发者的责任（当然还有编写可靠、良好文档和经过良好测试的代码！）
就是：

   * 编写一个设置脚本 (‘setup.py’ by convention)

   * (可选)编写设置脚本的配置文件

   * 创建源码的发行版

   * （可选）创建一个或多个编译好（二进制）的发行版

这些操作在此文档均有讲解。

并非所有的模块开发者都能接触到众多的平台，所以期望他们创造众多的内置发行
版不是总是可行的。最好是有一类名为 `打包者' 的中介，以满足这一需求。打包
者将读取模块开发者发布的源代码，在一个或多个平台上进行编译，并发布构建出
来的发行版。这样，最流行平台的用户就能以最自然的方式安装最流行的 Python
模块发行版，不必运行什么设置脚本或编译代码了。


File: python.info,  Node: 一个简单的例子<3>,  Next: 通用的 Python 术语,  Prev: 概念和术语,  Up: Distutils 模块介绍

17.1.2 一个简单的例子
---------------------

setup 脚本通常很简单，尽管是用 Python 编写的，它能干的事情没有限制，当然
应小心别在 setup 脚本中加入什么运行缓慢的操作。与 Autoconf 风格的
configure 脚本不同，在构建和安装模块的过程中 setup 脚本可能会被多次运行
。

如果只想发布一个名为 ‘foo’ 的模块，位于 ‘foo.py’ 文件中，那么 setup 脚本
可以如此简单：

     from distutils.core import setup
     setup(name='foo',
           version='1.0',
           py_modules=['foo'],
           )

注意要点：

   * 提供给 Distutils 的大部分信息将作为关键字参数发给 ‘setup()’ 函数。

   * 这些关键字参数分为两类：包的元数据（名称、版本号）和包中内容的描述
     信息（本例中是纯 Python 模块的列表）。

   * 模块由模块名指定，而不是文件名（包和扩展也是如此）。

   * 建议多提供一些元数据，特别是开发者姓名、电子邮件地址和项目的URL（参
     见 *note 编写安装脚本: 4575. 中的例子）。

要为该模块创建一个源码发布版本，需要创建一段 setup 脚本 ‘setup.py’，包含
上述代码，然后从终端运行以下命令：

     python setup.py sdist

对于 Windows 用户来说，打开命令行窗口（Start ‣ Accessories）并且写上如下
命令:

     setup.py sdist

‘sdist’ 将创建一个归档文件（例如在 Unix 中为 tarball，在 Windows 中为
ZIP 文件），其中包含你的配置脚本 ‘setup.py’ 以及你的模块 ‘foo.py’。 此归
档文件将被命名为 ‘foo-1.0.tar.gz’ (或 ‘.zip’)，并将解包到目录 ‘foo-1.0’
当中。

如果最终用户希望安装 ‘foo’ 模块，只需下载 ‘foo-1.0.tar.gz’ （或 ‘.zip’ ）
并解压，进入 ‘foo-1.0’ 目录运行：

     python setup.py install

这会把 ‘foo.py’ 复制到 Python 安装环境的第三方模块目录中。

上述简单例子展示了 Distutils 的一些基本概念。首先，开发者和安装者拥有相
同的基本用户界面，即 setup 脚本。区别在于使用哪种 Distutils `命令' ：
‘sdist’ 命令几乎只适用于模块开发者，而 ‘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
‘bdist_wininst’ command.  For example:

     python setup.py bdist_wininst

will create an executable installer, ‘foo-1.0.win32.exe’, in the current
directory.

其他有用的内置分发格式是 RPM，可由 ‘bdist_rpm’ 、Solaris ‘pkgtool`（
:command:`bdist_pkgtool’）和 HP-UX ‘swinstall`（:command:`bdist_sdux’）
实现。比如，以下命令将创建一个名为 ‘foo-1.0.noarch.rpm’ 的RPM文件：

     python setup.py bdist_rpm

（‘bdist_rpm’ 命令用到了 ‘rpm’ 可执行文件，因此必须运行在基于 RPM 的系统
中，如 Red Hat Linux 、 SuSE Linux 或 Mandrake Linux）。

可以随时运行以下命令，以便了解当前可用的分发格式：

     python setup.py bdist --help-formats


File: python.info,  Node: 通用的 Python 术语,  Next: Distutils 特定的术语,  Prev: 一个简单的例子<3>,  Up: Distutils 模块介绍

17.1.3 通用的 Python 术语
-------------------------

本文读者可能对模块、扩展等已有了很好的理解。但为确保所有人都站在同一起点
上，下面提供了 Python 常用术语表：

模块

     实现 Python 代码重用的基本单位：可被其他代码导入的一段代码。有三种
     类型的模块与本文有关：纯 Python 模块、扩展模块和包。

纯 Python 模块

     用 Python 编写的模块，包含在某 ‘.py’ 文件中（可能还会有相关的
     ‘.pyc’ 文件）。有时被称为 "纯模块"。

扩展模块

     用低级语言编写的 Python 模块。Python 用 C/C++ ，而 Jython 则用
     Java。通常包含在一个可动态加载的预编译文件中，比如 Unix 中的 Python
     扩展是一个共享对象（‘.so’）文件，Windows 中的 Python 扩展则是一个
     DLL （扩展名为 ‘.pyd’ )，而 Jython 的扩展是个 Java class 文件。（注
     意，目前，Distutils 只能处理 Python 的 C/C++ 扩展。）

包

     包含其他模块的模块；通常位于文件系统的某个目录中，区别于其他目录的
     标记就是存在一个 ‘__init__.py’ 文件。

根包

     包的层次结构的根。（其并非一个真正的包，因为没有 ‘__init__.py’ 文件
     。但总得给它起个名字）。 绝大多数标准库都在根包中，还有许多不属于任
     何大型模块的小型、独立的第三方模块。与普通的包不同，根包中的模块可
     能会在很多目录中出现：事实上，‘sys.path’ 列出的每个目录都会为根包提
     供模块。


File: python.info,  Node: Distutils 特定的术语,  Prev: 通用的 Python 术语,  Up: Distutils 模块介绍

17.1.4 Distutils 特定的术语
---------------------------

以下属于更加特别地用于 Distutils 发布 Python 模块。

模块的发布

     一组 Python 模块，作为可下载的资源组团发布，以便 `大规模' 安装。模
     块发布版的著名例子是 NumPy 、 SciPy 、 Pillow 或 mxBase。（这些会被
     称为 `package'，这个词在 Python 的语境中也使用过：一个模块发行版可
     能包含零个、一个或多个 Python 包。)

纯模块发行版

     只包含纯 Python 模块和软件包的模块发布版。有时被称为“纯发行版”。

非纯模块发行版

     至少包含一个扩展模块的模块发行版。 有时被称为“非纯发行版”。

根发行版

     源代码树（或源代码发行版）的顶级目录；即 ‘setup.py’ 所在的目录。 一
     般来说，‘setup.py’ 会在该目录下运行。


File: python.info,  Node: 编写安装脚本,  Next: 编写设置脚本的配置文件,  Prev: Distutils 模块介绍,  Up: 發布 Python 模組（舊版）

17.2 编写安装脚本
=================

     備註: 这篇文档只有在
     ‘https://setuptools.readthedocs.io/en/latest/setuptools.html’ 上的
     ‘setuptools’ 文档独立涵盖此处包含的所有相关信息之前，才会单独保留。

The setup script is the centre of all activity in building,
distributing, and installing modules using the Distutils.  The main
purpose of the setup script is to describe your module distribution to
the Distutils, so that the various commands that operate on your modules
do the right thing.  As we saw in section *note 一个简单的例子: 4574.
above, the setup script consists mainly of a call to ‘setup()’, and most
information supplied to the Distutils by the module developer is
supplied as keyword arguments to ‘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.)

     #!/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'],
          )

There are only two differences between this and the trivial one-file
distribution presented in section *note 一个简单的例子: 4574.: 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
*note Additional meta-data: 457c.

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 *note
glob.glob(): 6bd. or *note os.listdir(): b1c. to specify files, you
should be careful to write portable code instead of hardcoding path
separators:

     glob.glob(os.path.join('mydir', 'subdir', '*.html'))
     os.listdir(os.path.join('mydir', 'subdir'))

* Menu:

* Listing whole packages::
* Listing individual modules::
* Describing extension modules::
* Relationships between Distributions and Packages::
* Installing Scripts::
* Installing Package Data::
* Installing Additional Files::
* Additional meta-data::
* Debugging the setup script::


File: python.info,  Node: Listing whole packages,  Next: Listing individual modules,  Up: 编写安装脚本

17.2.1 Listing whole packages
-----------------------------

The ‘packages’ option tells the Distutils to process (build, distribute,
install, etc.)  all pure Python modules found in each package mentioned
in the ‘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 *note distutils: 38. is found in the directory ‘distutils’
relative to the distribution root.  Thus, when you say ‘packages =
['foo']’ in your setup script, you are promising that the Distutils will
find a file ‘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 ‘package_dir’ option to
tell the Distutils about your convention.  For example, say you keep all
Python source under ‘lib’, so that modules in the "root package" (i.e.,
not in any package at all) are in ‘lib’, modules in the ‘foo’ package
are in ‘lib/foo’, and so forth.  Then you would put

     package_dir = {'': 'lib'}

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 ‘packages = ['foo']’, you are promising that the file
‘lib/foo/__init__.py’ exists.

Another possible convention is to put the ‘foo’ package right in ‘lib’,
the ‘foo.bar’ package in ‘lib/bar’, etc.  This would be written in the
setup script as

     package_dir = {'foo': 'lib'}

A ‘package: dir’ entry in the ‘package_dir’ dictionary implicitly
applies to all packages below `package', so the ‘foo.bar’ case is
automatically handled here.  In this example, having ‘packages = ['foo',
'foo.bar']’ tells the Distutils to look for ‘lib/__init__.py’ and
‘lib/bar/__init__.py’.  (Keep in mind that although ‘package_dir’
applies recursively, you must explicitly list all packages in
‘packages’: the Distutils will `not' recursively scan your source tree
looking for any directory with an ‘__init__.py’ file.)


File: python.info,  Node: Listing individual modules,  Next: Describing extension modules,  Prev: Listing whole packages,  Up: 编写安装脚本

17.2.2 Listing individual modules
---------------------------------

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 *note 一个简单的例子: 4574.; here is a
slightly more involved example:

     py_modules = ['mod1', 'pkg.mod2']

This describes two modules, one of them in the "root" package, the other
in the ‘pkg’ package.  Again, the default package/directory layout
implies that these two modules can be found in ‘mod1.py’ and
‘pkg/mod2.py’, and that ‘pkg/__init__.py’ exists as well.  And again,
you can override the package/directory correspondence using the
‘package_dir’ option.


File: python.info,  Node: Describing extension modules,  Next: Relationships between Distributions and Packages,  Prev: Listing individual modules,  Up: 编写安装脚本

17.2.3 Describing extension modules
-----------------------------------

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.).

All of this is done through another keyword argument to ‘setup()’, the
‘ext_modules’ option.  ‘ext_modules’ is just a list of *note Extension:
4583. instances, each of which describes a single extension module.
Suppose your distribution includes a single extension, called ‘foo’ and
implemented by ‘foo.c’.  If no additional instructions to the
compiler/linker are needed, describing this extension is quite simple:

     Extension('foo', ['foo.c'])

The ‘Extension’ class can be imported from *note distutils.core: 53.
along with ‘setup()’.  Thus, the setup script for a module distribution
that contains only this one extension and nothing else might be:

     from distutils.core import setup, Extension
     setup(name='foo',
           version='1.0',
           ext_modules=[Extension('foo', ['foo.c'])],
           )

The ‘Extension’ class (actually, the underlying extension-building
machinery implemented by the ‘build_ext’ command) supports a great deal
of flexibility in describing Python extensions, which is explained in
the following sections.

* Menu:

* 扩展名和软件包::
* Extension source files::
* Preprocessor options::
* Library options::
* 其他选项: 其他选项<2>.


File: python.info,  Node: 扩展名和软件包,  Next: Extension source files,  Up: Describing extension modules

17.2.3.1 扩展名和软件包
.......................

The first argument to the *note Extension: 4583. constructor is always
the name of the extension, including any package names.  For example,

     Extension('foo', ['src/foo1.c', 'src/foo2.c'])

describes an extension that lives in the root package, while

     Extension('pkg.foo', ['src/foo1.c', 'src/foo2.c'])

describes the same extension in the ‘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 ‘ext_package’ keyword argument to
‘setup()’.  For example,

     setup(...,
           ext_package='pkg',
           ext_modules=[Extension('foo', ['foo.c']),
                        Extension('subpkg.bar', ['bar.c'])],
          )

will compile ‘foo.c’ to the extension ‘pkg.foo’, and ‘bar.c’ to
‘pkg.subpkg.bar’.


File: python.info,  Node: Extension source files,  Next: Preprocessor options,  Prev: 扩展名和软件包,  Up: Describing extension modules

17.2.3.2 Extension source files
...............................

The second argument to the *note Extension: 4583. 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: ‘.cc’ and ‘.cpp’ seem to be recognized by both Unix and Windows
compilers.)

However, you can also include SWIG interface (‘.i’) files in the list;
the ‘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.

This warning notwithstanding, options to SWIG can be currently passed
like this:

     setup(...,
           ext_modules=[Extension('_foo', ['foo.i'],
                                  swig_opts=['-modern', '-I../include'])],
           py_modules=['foo'],
          )

Or on the commandline like this:

     > python setup.py build_ext --swig-opts="-modern -I../include"

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 (‘.mc’) files and resource definition (‘.rc’)
files for Visual C++.  These will be compiled to binary resource
(‘.res’) files and linked into the executable.


File: python.info,  Node: Preprocessor options,  Next: Library options,  Prev: Extension source files,  Up: Describing extension modules

17.2.3.3 Preprocessor options
.............................

Three optional arguments to *note Extension: 4583. will help if you need
to specify include directories to search or preprocessor macros to
define/undefine: ‘include_dirs’, ‘define_macros’, and ‘undef_macros’.

For example, if your extension requires header files in the ‘include’
directory under your distribution root, use the ‘include_dirs’ option:

     Extension('foo', ['foo.c'], include_dirs=['include'])

You can specify absolute directories there; if you know that your
extension will only be built on Unix systems with X11R6 installed to
‘/usr’, you can get away with

     Extension('foo', ['foo.c'], include_dirs=['/usr/include/X11'])

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

     #include <X11/Xlib.h>

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 ‘install_headers’ command.  For example,
the Numerical Python header files are installed (on a standard Unix
installation) to ‘/usr/local/include/python1.5/Numerical’.  (The exact
location will differ according to your platform and Python
installation.)  Since the Python include
directory—‘/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

     #include <Numerical/arrayobject.h>

If you must put the ‘Numerical’ include directory right into your header
search path, though, you can find that directory using the Distutils
*note distutils.sysconfig: 61. module:

     from distutils.sysconfig import get_python_inc
     incdir = os.path.join(get_python_inc(plat_specific=1), 'Numerical')
     setup(...,
           Extension(..., include_dirs=[incdir]),
           )

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
‘define_macros’ and ‘undef_macros’ options.  ‘define_macros’ takes a
list of ‘(name, value)’ tuples, where ‘name’ is the name of the macro to
define (a string) and ‘value’ is its value: either a string or ‘None’.
(Defining a macro ‘FOO’ to ‘None’ is the equivalent of a bare ‘#define
FOO’ in your C source: with most compilers, this sets ‘FOO’ to the
string ‘1’.)  ‘undef_macros’ is just a list of macros to undefine.

例如:

     Extension(...,
               define_macros=[('NDEBUG', '1'),
                              ('HAVE_STRFTIME', None)],
               undef_macros=['HAVE_FOO', 'HAVE_BAR'])

is the equivalent of having this at the top of every C source file:

     #define NDEBUG 1
     #define HAVE_STRFTIME
     #undef HAVE_FOO
     #undef HAVE_BAR


File: python.info,  Node: Library options,  Next: 其他选项<2>,  Prev: Preprocessor options,  Up: Describing extension modules

17.2.3.4 Library options
........................

You can also specify the libraries to link against when building your
extension, and the directories to search for those libraries.  The
‘libraries’ option is a list of libraries to link against,
‘library_dirs’ is a list of directories to search for libraries at
link-time, and ‘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

     Extension(...,
               libraries=['gdbm', 'readline'])

If you need to link with libraries in a non-standard location, you’ll
have to include the location in ‘library_dirs’:

     Extension(...,
               library_dirs=['/usr/X11R6/lib'],
               libraries=['X11', 'Xt'])

(Again, this sort of non-portable construct should be avoided if you
intend to distribute your code.)


File: python.info,  Node: 其他选项<2>,  Prev: Library options,  Up: Describing extension modules

17.2.3.5 其他选项
.................

There are still some other options which can be used to handle special
cases.

The ‘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 ‘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.

‘extra_compile_args’ and ‘extra_link_args’ can be used to specify
additional command line options for the respective compiler and linker
command lines.

‘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 ‘initmodule’ to the list of exported symbols.

The ‘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.


File: python.info,  Node: Relationships between Distributions and Packages,  Next: Installing Scripts,  Prev: Describing extension modules,  Up: 编写安装脚本

17.2.4 Relationships between Distributions and Packages
-------------------------------------------------------

A distribution may relate to packages in three specific ways:

  1. It can require packages or modules.

  2. It can provide packages or modules.

  3. It can obsolete packages or modules.

These relationships can be specified using keyword arguments to the
*note distutils.core.setup(): 3d90. function.

Dependencies on other Python modules and packages can be specified by
supplying the `requires' keyword argument to ‘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 ‘'mymodule'’ and ‘'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:

     <    >    ==
     <=   >=   !=

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:

Requires Expression           解释
                              
---------------------------------------------------------------------------------
                              
‘==1.0’                       Only version ‘1.0’ is compatible
                              
                              
‘>1.0, !=1.5.1, <2.0’         Any version after ‘1.0’ and before ‘2.0’ is
                              compatible, except ‘1.5.1’
                              

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 `provides' keyword argument to ‘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:

Provides Expression       解释
                          
-----------------------------------------------------------------------------
                          
‘mypkg’                   Provide ‘mypkg’, using the distribution version
                          
                          
‘mypkg (1.1)’             Provide ‘mypkg’ version 1.1, regardless of the
                          distribution version
                          

A package can declare that it obsoletes other packages using the
`obsoletes' keyword argument.  The value for this is similar to that of
the `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.


File: python.info,  Node: Installing Scripts,  Next: Installing Package Data,  Prev: Relationships between Distributions and Packages,  Up: 编写安装脚本

17.2.5 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 ‘#!’ 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 ‘--executable’ (or ‘-e’) option will allow the
interpreter path to be explicitly overridden.

The ‘scripts’ option simply is a list of files to be handled in this
way.  From the PyXML setup script:

     setup(...,
           scripts=['scripts/xmlproc_parse', 'scripts/xmlproc_val']
           )

3.1 版更變: All the scripts will also be added to the ‘MANIFEST’ file if
no template is provided.  See *note Specifying the files to distribute:
3d93.


File: python.info,  Node: Installing Package Data,  Next: Installing Additional Files,  Prev: Installing Scripts,  Up: 编写安装脚本

17.2.6 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
`package data'.

Package data can be added to packages using the ‘package_data’ keyword
argument to the ‘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 ‘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:

     setup.py
     src/
         mypkg/
             __init__.py
             module.py
             data/
                 tables.dat
                 spoons.dat
                 forks.dat

The corresponding call to ‘setup()’ might be:

     setup(...,
           packages=['mypkg'],
           package_dir={'mypkg': 'src/mypkg'},
           package_data={'mypkg': ['data/*.dat']},
           )

3.1 版更變: All the files that match ‘package_data’ will be added to the
‘MANIFEST’ file if no template is provided.  See *note Specifying the
files to distribute: 3d93.


File: python.info,  Node: Installing Additional Files,  Next: Additional meta-data,  Prev: Installing Package Data,  Up: 编写安装脚本

17.2.7 Installing Additional Files
----------------------------------

The ‘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.

‘data_files’ specifies a sequence of (`directory', `files') pairs in the
following way:

     setup(...,
           data_files=[('bitmaps', ['bm/b1.gif', 'bm/b2.gif']),
                       ('config', ['cfg/data.cfg'])],
          )

Each (`directory', `files') pair in the sequence specifies the
installation directory and the files to install there.

Each file name in `files' is interpreted relative to the ‘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 `directory' should be a relative path.  It is interpreted relative
to the installation prefix (Python’s ‘sys.prefix’ for system
installations; ‘site.USER_BASE’ for user installations).  Distutils
allows `directory' to be an absolute installation path, but this is
discouraged since it is incompatible with the wheel packaging format.
No directory information from `files' is used to determine the final
location of the installed file; only the name of the file is used.

You can specify the ‘data_files’ options as a simple sequence of files
without specifying a target directory, but this is not recommended, and
the ‘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 ‘data_files’ will be added to the
‘MANIFEST’ file if no template is provided.  See *note Specifying the
files to distribute: 3d93.


File: python.info,  Node: Additional meta-data,  Next: Debugging the setup script,  Prev: Installing Additional Files,  Up: 编写安装脚本

17.2.8 Additional meta-data
---------------------------

The setup script may include additional meta-data beyond the name and
version.  This information includes:

元数据                     描述                            值                    註解
                                                                                 
----------------------------------------------------------------------------------------------
                                                                                 
‘name’                     包名称                          短字符串              (1)
                                                                                 
                                                                                 
‘version’                  此发布的版本                    短字符串              (1)(2)
                                                                                 
                                                                                 
‘author’                   软件包作者的姓名                短字符串              (3)
                                                                                 
                                                                                 
‘author_email’             软件包的作者的电子邮件地址      电子邮件地址          (3)
                                                                                 
                                                                                 
‘maintainer’               软件包维护者的名字              短字符串              (3)
                                                                                 
                                                                                 
‘maintainer_email’         软件包维护者的电子邮件地址      电子邮件地址          (3)
                                                                                 
                                                                                 
‘url’                      软件包的网址                    网址                  (1)
                                                                                 
                                                                                 
‘description’              软件包的简短摘要说明            短字符串
                                                           
                                                                                 
‘long_description’         软件包的详细说明                长字符串              (4)
                                                                                 
                                                                                 
‘download_url’             可以下载软件包的网址            网址
                                                           
                                                                                 
‘classifiers’              分类列表                        字符串列表            (6)(7)
                                                                                 
                                                                                 
‘platforms’                平台清单                        字符串列表            (6)(8)
                                                                                 
                                                                                 
‘keywords’                 关键字列表                      字符串列表            (6)(8)
                                                                                 
                                                                                 
‘license’                  软件包许可证                    短字符串              (5)
                                                                                 

註解：

  1. These fields are required.

  2. It is recommended that versions take the form
     `major.minor[.patch[.sub]]'.

  3. Either the author or the maintainer must be identified.  If
     maintainer is provided, distutils lists it as the author in
     ‘PKG-INFO’.

  4. The ‘long_description’ field is used by PyPI when you publish a
     package, to build its project page.

  5. The ‘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 ‘Classifier’ field.  Notice that
     there’s a ‘licence’ distribution option which is deprecated but
     still acts as an alias for ‘license’.

  6. This field must be a list.

  7. The valid classifiers are listed on PyPI(1).

  8. To preserve backward compatibility, this field also accepts a
     string.  If you pass a comma-separated string ‘'foo, bar'’, it will
     be converted to ‘['foo', 'bar']’, Otherwise, it will be converted
     to a list of one string.

’short string’

     A single line of text, not more than 200 characters.

’long string’

     Multiple lines of plain text in reStructuredText format (see
     ‘http://docutils.sourceforge.net/’).

’list of strings’

     See below.

Encoding the version information is an art in itself.  Python packages
generally adhere to the version format `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:

0.1.0

     the first, experimental release of a package

1.0.1a2

     the second alpha release of the first patch version of 1.0

‘classifiers’ must be specified in a list:

     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',
               ],
           )

3.7 版更變: *note setup: 3d90. now warns when ‘classifiers’, ‘keywords’
or ‘platforms’ fields are not specified as a list or a string.

   ---------- Footnotes ----------

   (1) https://pypi.org/classifiers


File: python.info,  Node: Debugging the setup script,  Prev: Additional meta-data,  Up: 编写安装脚本

17.2.9 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 ‘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.


File: python.info,  Node: 编写设置脚本的配置文件,  Next: Creating a Source Distribution,  Prev: 编写安装脚本,  Up: 發布 Python 模組（舊版）

17.3 编写设置脚本的配置文件
===========================

     備註: 这篇文档只有在
     ‘https://setuptools.readthedocs.io/en/latest/setuptools.html’ 上的
     ‘setuptools’ 文档独立涵盖此处包含的所有相关信息之前，才会单独保留。

通常，在 `事前' 就写出构建发布包所需的一切是不可能的：你可能需要从用户或
者用户的系统获取一些信息，才能继续下去。 只要这些信息相当简单 —— 例如一
个用于搜索 C 头文件或库的目录列表 —— 那么提供配置文件 ‘setup.cfg’ 供用户
配置就是一个低成本且方便的解决方式。 配置文件还允许你为任何命令选项提供
默认值，而安装器可以通过命令行或编辑配置文件来覆盖这些默认值。

安装配置文件是在安装脚本和安装脚本命令行之间一个适当的折衷方式 — 安装脚
本在理想情况下应当不受安装者的控制 (1) — 而安装脚本命令行则在你的控制范
围之外且完全取决于安装者的选择。 实际上，‘setup.cfg’ (以及目标系统上的其
他任何 Distutils 配置文件) 是在配置脚本之后、命令行之前被处理。 这导致了
几个有用的后果:

   * 安装者可以通过编辑 ‘setup.cfg’ 来覆盖你放在 ‘setup.py’ 中的配置

   * 你可以为无法在 ‘setup.py’ 中方便设置的选项提供非标准的默认值

   * 安装者可以使用 ‘setup.py’ 的命令行选项来覆盖 ‘setup.cfg’ 中的一切

配置文件的基本语法很简单:

     [command]
     option=value
     ...

其中 `command' 是一个 Distutils 命令 (例如 ‘build_py’, ‘install’)，而
`option' 是该命令所支持的某个选项。 可以为每个命令提供任意数量的选项，并
且可以在文件中包括任意数量的命令组。 空白行会被忽略，以一个 ‘'#'’ 开始的
注释行也是如此。 长选项值可以简单地通过缩进后续行的方式被拆分为多行。

你可以用通用的 ‘--help’ 选项找出特定命令所支持的选项列表，例如

     $ 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
     [...]

请注意在命令行中拼写为 ‘--foo-bar’ 的选项在配置文件中会拼写为 ‘foo_bar’。
例如，假设你希望你的扩展在“原地”构建 — 就是说你有一个扩展 ‘pkg.ext’，你
希望编译出的扩展文件 (例如在 Unix 上为 ‘ext.so’) 放在与你的纯 Python 模
块 ‘pkg.mod1’ 和 ‘pkg.mod2’ 相同的源目录中。 你总是可以在命令行中使用
‘--inplace’ 选项来确保这一点:

     python setup.py build_ext --inplace

但是这要求你总是显式地指定 ‘build_ext’ 命令，并且记得提供 ‘--inplace’。
一个更容易的方式是通过将其编码在此发布包的配置文件 ‘setup.cfg’ 中，“设置
并忘记”该选项。

     [build_ext]
     inplace=1

这将影响此模块发布包的所有构建，不论你是否显式指定 ‘build_ext’。 如果你
在你的源发布包中包括了 ‘setup.cfg’，它还将影响最终用户的构建 — 对此选项
来说这可能不是个好主意，因为总是原地构建扩展会破坏模块发布包的安装。 不
过在某些特殊情况下，模块是在其安装目录中被构建的，因此这可能会是个有用的
功能。 （但是，发布预期在其安装目录中被构建的扩展几乎总是一个坏主意。）

另一个例子：特定的命令会接受许多在多次运行中都不发生变化的选项；例如，
‘bdist_rpm’ 需要知道为创建 RPM 发布包生成 "spec" 文件所要求的所有信息。
这些信息有的来自安装脚本，有的由 Distutils 自动生成（例如已安装文件列表
）。 但有的则必须作为 ‘bdist_rpm’ 的选项提供，每次运行时都在命令行中完成
将会非常繁琐。 因此，这里提供 Distutils 本身的 ‘setup.cfg’ 中的一段代码:

     [bdist_rpm]
     release = 1
     packager = Greg Ward <gward@python.net>
     doc_files = CHANGES.txt
                 README.txt
                 USAGE.txt
                 doc/
                 examples/

请注意 ‘doc_files’ 选项只是一个空格分隔以提高可读性的多行字符串。

也參考
......

"安装 Python 模块" 中的 *note Syntax of config files: 4597.

     有关配置文件的更多信息可在系统管理员手册中查看。

註解
....

   ---------- Footnotes ----------

   (1) (1) 在 Distutils 完全支持自动配置之前，这一理想可能是无法实现的。


File: python.info,  Node: Creating a Source Distribution,  Next: 创建构建分布,  Prev: 编写设置脚本的配置文件,  Up: 發布 Python 模組（舊版）

17.4 Creating a Source Distribution
===================================

     備註: 这篇文档只有在
     ‘https://setuptools.readthedocs.io/en/latest/setuptools.html’ 上的
     ‘setuptools’ 文档独立涵盖此处包含的所有相关信息之前，才会单独保留。

As shown in section *note 一个简单的例子: 4574, you use the ‘sdist’
command to create a source distribution.  In the simplest case,

     python setup.py sdist

(assuming you haven’t specified any ‘sdist’ options in the setup script
or config file), ‘sdist’ creates the archive of the default format for
the current platform.  The default format is a gzip’ed tar file
(‘.tar.gz’) on Unix, and ZIP file on Windows.

You can specify as many formats as you like using the ‘--formats’
option, for example:

     python setup.py sdist --formats=gztar,zip

to create a gzipped tarball and a zip file.  The available formats are:

文件格式        描述                          註解
                                              
----------------------------------------------------------------
                                              
‘zip’           zip 文件 (‘.zip’)             (1),(3)
                                              
                                              
‘gztar’         gzip’ed tar 文件              (2)
                (‘.tar.gz’)                   
                
                                              
‘bztar’         bzip2’ed tar 文件             (5)
                (‘.tar.bz2’)                  
                
                                              
‘xztar’         xz’ed tar 文件 (‘.tar.xz’)    (5)
                                              
                                              
‘ztar’          压缩 tar 文件 (‘.tar.Z’)      (4),(5)
                                              
                                              
‘tar’           tar 文件 (‘.tar’)             (5)
                                              

3.5 版更變: 添加了对 ‘xztar’ 格式的支持

註解：

  1. 默认Windows

  2. 默认 Unix

  3. requires either external ‘zip’ utility or *note zipfile: 14b.
     module (part of the standard Python library since Python 1.6)

  4. requires the ‘compress’ program.  Notice that this format is now
     pending for deprecation and will be removed in the future versions
     of Python.

  5. deprecated by PEP 527(1); PyPI(2) only accepts ‘.zip’ and ‘.tar.gz’
     files.

When using any ‘tar’ format (‘gztar’, ‘bztar’, ‘xztar’, ‘ztar’ or
‘tar’), under Unix you can specify the ‘owner’ and ‘group’ names that
will be set for each member of the archive.

For example, if you want all files of the archive to be owned by root:

     python setup.py sdist --owner=root --group=root

* Menu:

* Specifying the files to distribute::
* Manifest-related options::

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0527/

   (2) https://pypi.org


File: python.info,  Node: Specifying the files to distribute,  Next: Manifest-related options,  Up: Creating a Source Distribution

17.4.1 Specifying the files to distribute
-----------------------------------------

If you don’t supply an explicit list of files (or instructions on how to
generate one), the ‘sdist’ command puts a minimal default set into the
source distribution:

   * all Python source files implied by the ‘py_modules’ and ‘packages’
     options

   * all C source files mentioned in the ‘ext_modules’ or ‘libraries’
     options

   * scripts identified by the ‘scripts’ option See *note Installing
     Scripts: 458a.

   * anything that looks like a test script: ‘test/test*.py’ (currently,
     the Distutils don’t do anything with test scripts except include
     them in source distributions, but in the future there will be a
     standard for testing Python module distributions)

   * Any of the standard README files (‘README’, ‘README.txt’, or
     ‘README.rst’), ‘setup.py’ (or whatever you called your setup
     script), and ‘setup.cfg’.

   * all files that matches the ‘package_data’ metadata.  See *note
     Installing Package Data: 458c.

   * all files that matches the ‘data_files’ metadata.  See *note
     Installing Additional Files: 458e.

Sometimes this is enough, but usually you will want to specify
additional files to distribute.  The typical way to do this is to write
a `manifest template', called ‘MANIFEST.in’ by default.  The manifest
template is just a list of instructions for how to generate your
manifest file, ‘MANIFEST’, which is the exact list of files to include
in your source distribution.  The ‘sdist’ command processes this
template and generates a manifest based on its instructions and what it
finds in the filesystem.

If you prefer to roll your own manifest file, the format is simple: one
filename per line, regular files (or symlinks to them) only.  If you do
supply your own ‘MANIFEST’, you must specify everything: the default set
of files described above does not apply in this case.

3.1 版更變: An existing generated ‘MANIFEST’ will be regenerated without
‘sdist’ comparing its modification time to the one of ‘MANIFEST.in’ or
‘setup.py’.

3.1.3 版更變: ‘MANIFEST’ files start with a comment indicating they are
generated.  Files without this comment are not overwritten or removed.

3.2.2 版更變: ‘sdist’ will read a ‘MANIFEST’ file if no ‘MANIFEST.in’
exists, like it used to do.

3.7 版更變: ‘README.rst’ is now included in the list of distutils
standard READMEs.

The manifest template has one command per line, where each command
specifies a set of files to include or exclude from the source
distribution.  For an example, again we turn to the Distutils’ own
manifest template:

     include *.txt
     recursive-include examples *.txt *.py
     prune examples/sample?/build

The meanings should be fairly clear: include all files in the
distribution root matching ‘*.txt’, all files anywhere under the
‘examples’ directory matching ‘*.txt’ or ‘*.py’, and exclude all
directories matching ‘examples/sample?/build’.  All of this is done
`after' the standard include set, so you can exclude files from the
standard set with explicit instructions in the manifest template.  (Or,
you can use the ‘--no-defaults’ option to disable the standard set
entirely.)  There are several other commands available in the manifest
template mini-language; see section *note 创建源码发行包; sdist 命令:
459c.

The order of commands in the manifest template matters: initially, we
have the list of default files as described above, and each command in
the template adds to or removes from that list of files.  Once we have
fully processed the manifest template, we remove files that should not
be included in the source distribution:

   * all files in the Distutils "build" tree (default ‘build/’)

   * all files in directories named ‘RCS’, ‘CVS’, ‘.svn’, ‘.hg’, ‘.git’,
     ‘.bzr’ or ‘_darcs’

Now we have our complete list of files, which is written to the manifest
for future reference, and then used to build the source distribution
archive(s).

You can disable the default set of included files with the
‘--no-defaults’ option, and you can disable the standard exclude set
with ‘--no-prune’.

Following the Distutils’ own manifest template, let’s trace how the
‘sdist’ command builds the list of files to include in the Distutils
source distribution:

  1. include all Python source files in the ‘distutils’ and
     ‘distutils/command’ subdirectories (because packages corresponding
     to those two directories were mentioned in the ‘packages’ option in
     the setup script—see section *note 编写安装脚本: 4575.)

  2. include ‘README.txt’, ‘setup.py’, and ‘setup.cfg’ (standard files)

  3. include ‘test/test*.py’ (standard files)

  4. include ‘*.txt’ in the distribution root (this will find
     ‘README.txt’ a second time, but such redundancies are weeded out
     later)

  5. include anything matching ‘*.txt’ or ‘*.py’ in the sub-tree under
     ‘examples’,

  6. exclude all files in the sub-trees starting at directories matching
     ‘examples/sample?/build’—this may exclude files included by the
     previous two steps, so it’s important that the ‘prune’ command in
     the manifest template comes after the ‘recursive-include’ command

  7. exclude the entire ‘build’ tree, and any ‘RCS’, ‘CVS’, ‘.svn’,
     ‘.hg’, ‘.git’, ‘.bzr’ and ‘_darcs’ directories

Just like in the setup script, file and directory names in the manifest
template should always be slash-separated; the Distutils will take care
of converting them to the standard representation on your platform.
That way, the manifest template is portable across operating systems.


File: python.info,  Node: Manifest-related options,  Prev: Specifying the files to distribute,  Up: Creating a Source Distribution

17.4.2 Manifest-related options
-------------------------------

The normal course of operations for the ‘sdist’ command is as follows:

   * if the manifest file (‘MANIFEST’ by default) exists and the first
     line does not have a comment indicating it is generated from
     ‘MANIFEST.in’, then it is used as is, unaltered

   * if the manifest file doesn’t exist or has been previously
     automatically generated, read ‘MANIFEST.in’ and create the manifest

   * if neither ‘MANIFEST’ nor ‘MANIFEST.in’ exist, create a manifest
     with just the default file set

   * use the list of files now in ‘MANIFEST’ (either just generated or
     read in) to create the source distribution archive(s)

There are a couple of options that modify this behaviour.  First, use
the ‘--no-defaults’ and ‘--no-prune’ to disable the standard "include"
and "exclude" sets.

Second, you might just want to (re)generate the manifest, but not create
a source distribution:

     python setup.py sdist --manifest-only

‘-o’ is a shortcut for ‘--manifest-only’.


File: python.info,  Node: 创建构建分布,  Next: Distutils 示例,  Prev: Creating a Source Distribution,  Up: 發布 Python 模組（舊版）

17.5 创建构建分布
=================

     備註: 这篇文档只有在
     ‘https://setuptools.readthedocs.io/en/latest/setuptools.html’ 上的
     ‘setuptools’ 文档独立涵盖此处包含的所有相关信息之前，才会单独保留。

A "built distribution" is what you’re probably used to thinking of
either as a "binary package" or an "installer" (depending on your
background).  It’s not necessarily binary, though, because it might
contain only Python source code and/or byte-code; and we don’t call it a
package, because that word is already spoken for in Python.  (And
"installer" is a term specific to the world of mainstream desktop
systems.)

A built distribution is how you make life as easy as possible for
installers of your module distribution: for users of RPM-based Linux
systems, it’s a binary RPM; for Windows users, it’s an executable
installer; for Debian-based Linux users, it’s a Debian package; and so
forth.  Obviously, no one person will be able to create built
distributions for every platform under the sun, so the Distutils are
designed to enable module developers to concentrate on their
specialty—writing code and creating source distributions—while an
intermediary species called `packagers' springs up to turn source
distributions into built distributions for as many platforms as there
are packagers.

Of course, the module developer could be their own packager; or the
packager could be a volunteer "out there" somewhere who has access to a
platform which the original developer does not; or it could be software
periodically grabbing new source distributions and turning them into
built distributions for as many platforms as the software has access to.
Regardless of who they are, a packager uses the setup script and the
‘bdist’ command family to generate built distributions.

As a simple example, if I run the following command in the Distutils
source tree:

     python setup.py bdist

then the Distutils builds my module distribution (the Distutils itself
in this case), does a "fake" installation (also in the ‘build’
directory), and creates the default type of built distribution for my
platform.  The default format for built distributions is a "dumb" tar
file on Unix, and a simple executable installer on Windows.  (That tar
file is considered "dumb" because it has to be unpacked in a specific
location to work.)

Thus, the above command on a Unix system creates
‘Distutils-1.0.`plat'.tar.gz’; unpacking this tarball from the right
place installs the Distutils just as though you had downloaded the
source distribution and run ‘python setup.py install’.  (The "right
place" is either the root of the filesystem or Python’s ‘`prefix'’
directory, depending on the options given to the ‘bdist_dumb’ command;
the default is to make dumb distributions relative to ‘`prefix'’.)

Obviously, for pure Python distributions, this isn’t any simpler than
just running ‘python setup.py install’—but for non-pure distributions,
which include extensions that would need to be compiled, it can mean the
difference between someone being able to use your extensions or not.
And creating "smart" built distributions, such as an RPM package or an
executable installer for Windows, is far more convenient for users even
if your distribution doesn’t include any extensions.

The ‘bdist’ command has a ‘--formats’ option, similar to the ‘sdist’
command, which you can use to select the types of built distribution to
generate: for example,

     python setup.py bdist --format=zip

would, when run on a Unix system, create
‘Distutils-1.0.`plat'.zip’—again, this archive would be unpacked from
the root directory to install the Distutils.

The available formats for built distributions are:

文件格式          描述                               註解
                                                     
-------------------------------------------------------------------
                                                     
‘gztar’           gzipped tar 文件 (‘.tar.gz’)       (1)
                                                     
                                                     
‘bztar’           bzipped tar 文件 (‘.tar.bz2’)
                  
                                                     
‘xztar’           xzipped tar 文件 (‘.tar.xz’)
                  
                                                     
‘ztar’            压缩 tar 文件 (‘.tar.Z’)           (3)
                                                     
                                                     
‘tar’             tar 文件 (‘.tar’)
                  
                                                     
‘zip’             zip 文件 (‘.zip’)                  (2),(4)
                                                     
                                                     
‘rpm’             RPM                                (5)
                                                     
                                                     
‘pkgtool’         Solaris ‘pkgtool’
                  
                                                     
‘sdux’            HP-UX ‘swinstall’
                  
                                                     
‘wininst’         Windows的自解压ZIP文件             (4)
                                                     
                                                     
‘msi’             Microsoft安装程序。
                  

3.5 版更變: 添加了对 ‘xztar’ 格式的支持

註解：

  1. 默认 Unix

  2. 默认Windows

  3. requires external ‘compress’ utility.

  4. requires either external ‘zip’ utility or *note zipfile: 14b.
     module (part of the standard Python library since Python 1.6)

  5. requires external ‘rpm’ utility, version 3.0.4 or better (use ‘rpm
     --version’ to find out which version you have)

You don’t have to use the ‘bdist’ command with the ‘--formats’ option;
you can also use the command that directly implements the format you’re
interested in.  Some of these ‘bdist’ "sub-commands" actually generate
several similar formats; for instance, the ‘bdist_dumb’ command
generates all the "dumb" archive formats (‘tar’, ‘gztar’, ‘bztar’,
‘xztar’, ‘ztar’, and ‘zip’), and ‘bdist_rpm’ generates both binary and
source RPMs.  The ‘bdist’ sub-commands, and the formats generated by
each, are:

命令                           格式
                               
-------------------------------------------------------------------------
                               
‘bdist_dumb’                   tar, gztar, bztar, xztar, ztar, zip
                               
                               
‘bdist_rpm’                    rpm, srpm
                               
                               
‘bdist_wininst’                wininst
                               
                               
‘bdist_msi’                    msi
                               

     備註: 从Python 3.8开始不推荐使用 bdist_wininst

     備註: bdist_msi 从 Python 3.9 起被弃用。

The following sections give details on the individual ‘bdist_*’
commands.

* Menu:

* 创建RPM软件包::
* Creating Windows Installers::
* Cross-compiling on Windows::
* Vista User Access Control (UAC): Vista User Access Control UAC.


File: python.info,  Node: 创建RPM软件包,  Next: Creating Windows Installers,  Up: 创建构建分布

17.5.1 创建RPM软件包
--------------------

The RPM format is used by many popular Linux distributions, including
Red Hat, SuSE, and Mandrake.  If one of these (or any of the other
RPM-based Linux distributions) is your usual environment, creating RPM
packages for other users of that same distribution is trivial.
Depending on the complexity of your module distribution and differences
between Linux distributions, you may also be able to create RPMs that
work on different RPM-based distributions.

The usual way to create an RPM of your module distribution is to run the
‘bdist_rpm’ command:

     python setup.py bdist_rpm

or the ‘bdist’ command with the ‘--format’ option:

     python setup.py bdist --formats=rpm

The former allows you to specify RPM-specific options; the latter allows
you to easily specify multiple formats in one run.  If you need to do
both, you can explicitly specify multiple ‘bdist_*’ commands and their
options:

     python setup.py bdist_rpm --packager="John Doe <jdoe@example.org>" \
                     bdist_wininst --target-version="2.0"

Creating RPM packages is driven by a ‘.spec’ file, much as using the
Distutils is driven by the setup script.  To make your life easier, the
‘bdist_rpm’ command normally creates a ‘.spec’ file based on the
information you supply in the setup script, on the command line, and in
any Distutils configuration files.  Various options and sections in the
‘.spec’ file are derived from options in the setup script as follows:

RPM ‘.spec’ 文件配置或选项                     Distutils安装脚本选项
                                               
--------------------------------------------------------------------------------------------------
                                               
名称                                           ‘name’
                                               
                                               
摘要（在序言中）                               ‘description’
                                               
                                               
版本                                           ‘version’
                                               
                                               
供应商                                         ‘author’ 和 ‘author_email’, 或 — & ‘maintainer’
                                               和 ‘maintainer_email’
                                               
                                               
版權宣告                                       ‘license’
                                               
                                               
Url                                            ‘url’
                                               
                                               
%d描述（部分）                                 ‘long_description’
                                               

Additionally, there are many options in ‘.spec’ files that don’t have
corresponding options in the setup script.  Most of these are handled
through options to the ‘bdist_rpm’ command as follows:

RPM ‘.spec’ 文件配置或选项          ‘bdist_rpm’ 选项                  默认值
                                                                      
----------------------------------------------------------------------------------------------------
                                                                      
发布版本                            ‘release’                         "1"
                                                                      
                                                                      
组织                                ‘group’                           "Development/Libraries"
                                                                      
                                                                      
供应商                              ‘vendor’                          （同上）
                                                                      
                                                                      
打包                                ‘packager’                        (none)
                                                                      
                                                                      
提供                                ‘provides’                        (none)
                                                                      
                                                                      
需求                                ‘requires’                        (none)
                                                                      
                                                                      
冲突                                ‘conflicts’                       (none)
                                                                      
                                                                      
淘汰                                ‘obsoletes’                       (none)
                                                                      
                                                                      
Distribution                        ‘distribution_name’               (none)
                                                                      
                                                                      
构建要求                            ‘build_requires’                  (none)
                                                                      
                                                                      
Icon                                ‘icon’                            (none)
                                                                      

Obviously, supplying even a few of these options on the command-line
would be tedious and error-prone, so it’s usually best to put them in
the setup configuration file, ‘setup.cfg’—see section *note
编写设置脚本的配置文件: 4594.  If you distribute or package many Python
module distributions, you might want to put options that apply to all of
them in your personal Distutils configuration file
(‘~/.pydistutils.cfg’).  If you want to temporarily disable this file,
you can pass the ‘--no-user-cfg’ option to ‘setup.py’.

There are three steps to building a binary RPM package, all of which are
handled automatically by the Distutils:

  1. create a ‘.spec’ file, which describes the package (analogous to
     the Distutils setup script; in fact, much of the information in the
     setup script winds up in the ‘.spec’ file)

  2. create the source RPM

  3. create the "binary" RPM (which may or may not contain binary code,
     depending on whether your module distribution contains Python
     extensions)

Normally, RPM bundles the last two steps together; when you use the
Distutils, all three steps are typically bundled together.

If you wish, you can separate these three steps.  You can use the
‘--spec-only’ option to make ‘bdist_rpm’ just create the ‘.spec’ file
and exit; in this case, the ‘.spec’ file will be written to the
"distribution directory"—normally ‘dist/’, but customizable with the
‘--dist-dir’ option.  (Normally, the ‘.spec’ file winds up deep in the
"build tree," in a temporary directory created by ‘bdist_rpm’.)


File: python.info,  Node: Creating Windows Installers,  Next: Cross-compiling on Windows,  Prev: 创建RPM软件包,  Up: 创建构建分布

17.5.2 Creating Windows Installers
----------------------------------

     警告: 从Python 3.8开始不推荐使用 bdist_wininst

     警告: bdist_msi 从 Python 3.9 起被弃用。

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:

     python setup.py bdist_wininst

or the ‘bdist’ command with the ‘--formats’ option:

     python setup.py bdist --formats=wininst

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 ‘foo-1.0.win32.exe’.  Note that
creating ‘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
‘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 *note bytecode: 709.
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
‘bdist_wininst’ command with the ‘--no-target-compile’ and/or the
‘--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 ‘.bmp’ file with the ‘--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 ‘--title’ option.

The installer file will be written to the "distribution directory" —
normally ‘dist/’, but customizable with the ‘--dist-dir’ option.


File: python.info,  Node: Cross-compiling on Windows,  Next: Vista User Access Control UAC,  Prev: Creating Windows Installers,  Up: 创建构建分布

17.5.3 Cross-compiling on Windows
---------------------------------

Starting with Python 2.6, distutils is capable of cross-compiling
between Windows platforms.  In practice, this means that with the
correct tools installed, you can use a 32bit version of Windows to
create 64bit extensions and vice-versa.

To build for an alternate platform, specify the ‘--plat-name’ option to
the build command.  Valid values are currently ’win32’, and ’win-amd64’.
For example, on a 32bit version of Windows, you could execute:

     python setup.py build --plat-name=win-amd64

to build a 64bit version of your extension.  The Windows Installers also
support this option, so the command:

     python setup.py build --plat-name=win-amd64 bdist_wininst

would create a 64bit installation executable on your 32bit version of
Windows.

To cross-compile, you must download the Python source code and
cross-compile Python itself for the platform you are targeting - it is
not possible from a binary installation of Python (as the .lib etc file
for other platforms are not included.)  In practice, this means the user
of a 32 bit operating system will need to use Visual Studio 2008 to open
the ‘PCbuild/PCbuild.sln’ solution in the Python source tree and build
the "x64" configuration of the ’pythoncore’ project before
cross-compiling extensions is possible.

Note that by default, Visual Studio 2008 does not install 64bit
compilers or tools.  You may need to reexecute the Visual Studio setup
process and select these tools (using Control Panel->[Add/Remove]
Programs is a convenient way to check or modify your existing install.)

* Menu:

* The Postinstallation script::


File: python.info,  Node: The Postinstallation script,  Up: Cross-compiling on Windows

17.5.3.1 The Postinstallation script
....................................

Starting with Python 2.3, a postinstallation script can be specified
with the ‘--install-script’ option.  The basename of the script must be
specified, and the script filename must also be listed in the scripts
argument to the setup function.

This script will be run at installation time on the target system after
all the files have been copied, with ‘argv[1]’ set to ‘-install’, and
again at uninstallation time before the files are removed with ‘argv[1]’
set to ‘-remove’.

The installation script runs embedded in the windows installer, every
output (‘sys.stdout’, ‘sys.stderr’) is redirected into a buffer and will
be displayed in the GUI after the script has finished.

Some functions especially useful in this context are available as
additional built-in functions in the installation script.

 -- 函式: directory_created (path)
 -- 函式: file_created (path)

     These functions should be called when a directory or file is
     created by the postinstall script at installation time.  It will
     register `path' with the uninstaller, so that it will be removed
     when the distribution is uninstalled.  To be safe, directories are
     only removed if they are empty.

 -- 函式: get_special_folder_path (csidl_string)

     This function can be used to retrieve special folder locations on
     Windows like the Start Menu or the Desktop.  It returns the full
     path to the folder.  `csidl_string' must be one of the following
     strings:

          "CSIDL_APPDATA"

          "CSIDL_COMMON_STARTMENU"
          "CSIDL_STARTMENU"

          "CSIDL_COMMON_DESKTOPDIRECTORY"
          "CSIDL_DESKTOPDIRECTORY"

          "CSIDL_COMMON_STARTUP"
          "CSIDL_STARTUP"

          "CSIDL_COMMON_PROGRAMS"
          "CSIDL_PROGRAMS"

          "CSIDL_FONTS"

     如果文件夹不能被检索到，会触发 *note OSError: 304. 。

     Which folders are available depends on the exact Windows version,
     and probably also the configuration.  For details refer to
     Microsoft’s documentation of the ‘SHGetSpecialFolderPath()’
     function.

 -- 函式: create_shortcut (target, description, filename[, arguments[,
          workdir[, iconpath[, iconindex]]]])

     This function creates a shortcut.  `target' is the path to the
     program to be started by the shortcut.  `description' is the
     description of the shortcut.  `filename' is the title of the
     shortcut that the user will see.  `arguments' specifies the command
     line arguments, if any.  `workdir' is the working directory for the
     program.  `iconpath' is the file containing the icon for the
     shortcut, and `iconindex' is the index of the icon in the file
     `iconpath'.  Again, for details consult the Microsoft documentation
     for the ‘IShellLink’ interface.


File: python.info,  Node: Vista User Access Control UAC,  Prev: Cross-compiling on Windows,  Up: 创建构建分布

17.5.4 Vista User Access Control (UAC)
--------------------------------------

Starting with Python 2.6, bdist_wininst supports a
‘--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).

     備註: 从Python 3.8开始不推荐使用 bdist_wininst

     備註: bdist_msi 从 Python 3.9 起被弃用。


File: python.info,  Node: Distutils 示例,  Next: 扩展 Distutils,  Prev: 创建构建分布,  Up: 發布 Python 模組（舊版）

17.6 Distutils 示例
===================

     備註: 这篇文档只有在
     ‘https://setuptools.readthedocs.io/en/latest/setuptools.html’ 上的
     ‘setuptools’ 文档独立涵盖此处包含的所有相关信息之前，才会单独保留。

本章节提供几个基础示例，来帮助用户入门 distutils。关于使用 distutils 的
额外信息可以参考 Distutils Cookbook。

也參考
......

Distutils Cookbook(1)

     一套展示如何更好地控制和使用 distutils 的方法。

* Menu:

* 纯 Python 分发（通过 module）::
* 纯 Python 分发（通过 包）::
* 单个扩展模块::
* 检查一个包::
* 读取元数据::

   ---------- Footnotes ----------

   (1) https://wiki.python.org/moin/Distutils/Cookbook


File: python.info,  Node: 纯 Python 分发（通过 module）,  Next: 纯 Python 分发（通过 包）,  Up: Distutils 示例

17.6.1 纯 Python 分发（通过 module）
------------------------------------

如果你要分发一组模块，特别是它们不在特定的包中，你可以在配置脚本中使用
‘py_modules’ 选项单独指定它们。

最简单的情况下，你只用关心两个文件：一个配置脚本，和单个你要分发的模块，
这个示例中的 ‘foo.py’: ：

     <root>/
             setup.py
             foo.py

（在本章节的所有图中，`<root>' 表示分发根目录。）这种情况下的一个最小配
置脚本是：

     from distutils.core import setup
     setup(name='foo',
           version='1.0',
           py_modules=['foo'],
           )

注意分发的包名用 ‘name’ 选项单独指定，没有规定它必须和包中单独的模块同名
（虽然这也是个可以遵循的好习惯）。然而，分发名用来生成文件名，所以你应该
坚持用字母、数字、下划线和连词号。

因为 ‘py_modules’ 是个列表，你当然可以指定多个模块，比如，如果你要分发模
块 ‘foo’ 和 ‘bar’，你的配置可能是这样：

     <root>/
             setup.py
             foo.py
             bar.py

并且配置脚本是：

     from distutils.core import setup
     setup(name='foobar',
           version='1.0',
           py_modules=['foo', 'bar'],
           )

你可以把模块源文件放进另一个目录，但是如果你有足够的模块，也许用包指定模
块更简单，而不是单独列出它们。


File: python.info,  Node: 纯 Python 分发（通过 包）,  Next: 单个扩展模块,  Prev: 纯 Python 分发（通过 module）,  Up: Distutils 示例

17.6.2 纯 Python 分发（通过 包）
--------------------------------

如果你有超过一组模块要分发，特别是它们在不同的包中，也许指定整个包更简单
，而不是指定单独的模块。这样即使你的模块不在一个包中也有效；你可以直接令
Distutils 来从根包来处理模块，并且这样对任何其他包也有效（除非你不需要
‘__init__.py’ 文件）。

上一个示例的配置脚本也可以写成：

     from distutils.core import setup
     setup(name='foobar',
           version='1.0',
           packages=[''],
           )

（空字符串表示根包。）

如果两个文件移动到子目录，但是依然在根包中，如：

     <root>/
             setup.py
             src/      foo.py
                       bar.py

那么你依然需要指定根包，但是你还需要告诉 Distutils 根包中的源文件在哪：

     from distutils.core import setup
     setup(name='foobar',
           version='1.0',
           package_dir={'': 'src'},
           packages=[''],
           )

更一般地，你要分发多个在同一个包（或者子包）中的模块。举个例子，假设
‘foo’ 和 ‘bar’ 模块属于 ‘foobar’ 包，排布源文件树的一种方式是：

     <root>/
             setup.py
             foobar/
                      __init__.py
                      foo.py
                      bar.py

这其实是 Distutils 默认的排布，也是你的配置脚本中需要的工作量最小的。

     from distutils.core import setup
     setup(name='foobar',
           version='1.0',
           packages=['foobar'],
           )

如果你要把模块放到没有按照它们的包名命名的目录里，那你需要再次使用
‘package_dir’ 选项。比如，如果 ‘src’ 目录包含包 ‘foobar’ 中的模块：

     <root>/
             setup.py
             src/
                      __init__.py
                      foo.py
                      bar.py

一个合适的配置脚本可以是：

     from distutils.core import setup
     setup(name='foobar',
           version='1.0',
           package_dir={'foobar': 'src'},
           packages=['foobar'],
           )

或者，你可以把主包中的模块直接放到分发根目录：

     <root>/
             setup.py
             __init__.py
             foo.py
             bar.py

这样你的配置文件是：

     from distutils.core import setup
     setup(name='foobar',
           version='1.0',
           package_dir={'foobar': ''},
           packages=['foobar'],
           )

（空字符串同样表示当前目录。）

如果你有子包，则它们必须显式列在 ‘packages’ 中，但是 ‘package_dir’ 中的
任何条目会自动扩展到子包。（也就是说，Distutils `不会' 扫描你的源码树，
而是尝试通过查找 ‘__init__.py’ 文件，来弄清哪些目录与 Python 包关联。）
这样，如果默认排布产生一个子包：

     <root>/
             setup.py
             foobar/
                      __init__.py
                      foo.py
                      bar.py
                      subfoo/
                                __init__.py
                                blah.py

则相应的配置脚本是：

     from distutils.core import setup
     setup(name='foobar',
           version='1.0',
           packages=['foobar', 'foobar.subfoo'],
           )


File: python.info,  Node: 单个扩展模块,  Next: 检查一个包,  Prev: 纯 Python 分发（通过 包）,  Up: Distutils 示例

17.6.3 单个扩展模块
-------------------

扩展模块用 ‘ext_modules’ 选项指定。‘package_dir’ 对在哪寻找扩展源文件无
效；它只对纯 Python 模块的源文件有效。最简单的，一个用单个C源文件写的单
扩展模块是：

     <root>/
             setup.py
             foo.c

如果 ‘foo’ 扩展属于根包，则配置脚本可以是：

     from distutils.core import setup
     from distutils.extension import Extension
     setup(name='foobar',
           version='1.0',
           ext_modules=[Extension('foo', ['foo.c'])],
           )

如果扩展在包中，比如 ‘foopkg’，那么

使用完全相同的源文件树排布，通过改变扩展的名字，这个扩展很容易放入
‘foopkg’ 包中：

     from distutils.core import setup
     from distutils.extension import Extension
     setup(name='foobar',
           version='1.0',
           ext_modules=[Extension('foopkg.foo', ['foo.c'])],
           )


File: python.info,  Node: 检查一个包,  Next: 读取元数据,  Prev: 单个扩展模块,  Up: Distutils 示例

17.6.4 检查一个包
-----------------

‘check’ 命令允许你校验你的包的元数据是否满足生成分发的最低要求。

直接使用你的 ‘setup.py’ 脚本来运行它。如果缺了一些东西，‘check’ 会显示警
告。

我们来用单个脚本举例：

     from distutils.core import setup

     setup(name='foobar')

运行 ‘check’ 命令会显示一些警告：

     $ 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

如果你在 ‘long_description’ 域中使用 reStructuredText 语法，并且安装了
docutils(1) ，你可以用 ‘check’ 命令，和 ‘restructuredtext’ 选项检查语法
是否正确。

比如，如果 ‘setup.py’ 脚本改成：

     from distutils.core import setup

     desc = """\
     My description
     ==============

     This is the description of the ``foobar`` package.
     """

     setup(name='foobar', version='1', author='tarek',
         author_email='tarek@ziade.org',
         url='http://example.com', long_description=desc)

长描述中有问题的地方，通过使用 ‘docutils’ 解析器，‘check’ 能进行删除：

     $ python setup.py check --restructuredtext
     running check
     warning: check: Title underline too short. (line 2)
     warning: check: Could not finish the parsing.

   ---------- Footnotes ----------

   (1) http://docutils.sourceforge.net


File: python.info,  Node: 读取元数据,  Prev: 检查一个包,  Up: Distutils 示例

17.6.5 读取元数据
-----------------

*note distutils.core.setup(): 3d90. 函数提供一个通过项目的 ‘setup.py’ 脚
本，来查询项目的元数据的域的命令行接口：

     $ python setup.py --name
     distribute

这个调用通过运行 *note distutils.core.setup(): 3d90. 函数读取 ‘name’ 元
数据。然而，当源文件或者二进制分发用 Distutils 创建时，元数据域写入一个
名为 ‘PKG-INFO’ 的静态文件。当一个基于Distutils的项目安装在 Python 中时
，‘PKG-INFO’ 文件随着分发的模块和包一起复制到
‘NAME-VERSION-pyX.X.egg-info’ 中，其中 ‘NAME’ 是项目的名字，‘VERSION’ 是
元数据中定义的版本， ‘pyX.X’ 则是 Python 的大版本和小版本，如 ‘2.7’ 或者
‘3.2’。

你可以读回静态文件，使用 ‘distutils.dist.DistributionMetadata’ 类和它的
‘read_pkg_file()’ 方法：

     >>> 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'

注意类也可以用元数据文件载入值来实例化：

     >>> pkg_info_path = 'distribute-0.6.8-py2.7.egg-info'
     >>> DistributionMetadata(pkg_info_path).name
     'distribute'


File: python.info,  Node: 扩展 Distutils,  Next: 指令參照,  Prev: Distutils 示例,  Up: 發布 Python 模組（舊版）

17.7 扩展 Distutils
===================

     備註: 这篇文档只有在
     ‘https://setuptools.readthedocs.io/en/latest/setuptools.html’ 上的
     ‘setuptools’ 文档独立涵盖此处包含的所有相关信息之前，才会单独保留。

Distutils 可以通过各种方式扩展。 大多数扩展都采用新命令或现有命令的替换
形式。 例如，可以编写新命令以支持新的特定于平台的包格式，但是可以修改现
有命令的替换，以修改命令在包上的操作细节。

distutils 的大多数扩展都在想要修改现有命令的 ‘setup.py’ 脚本中编写；其中
许多只是简单地在 ‘.py’ 文件以外添加了一些应当被拷贝到包中的文件后缀以便
使用。

大多部 distutils 命令的实现都是 *note distutils.cmd.Command: 45bd. 类的
子类。 新增命令可直接继承自 ‘Command’，而替换命令往往间接派生自
‘Command’， 直接子类化它们所替换的命令。 所有命令都要求自 ‘Command’ 派生
。

* Menu:

* 集成新的命令::
* 添加新的发布类型::


File: python.info,  Node: 集成新的命令,  Next: 添加新的发布类型,  Up: 扩展 Distutils

17.7.1 集成新的命令
-------------------

有多种方法可将新的命令实现集成到 distutils 中。 最困难的一种是鼓动在
distutils 自身内部包含新特性，并等待（以及要求）某个 Python 版本提供该支
持。 出于多种原因，这确实是相当难的。

对于大多数需求来说最为常见并且可能最为合理的一种则是通过你自己的
‘setup.py’ 脚本来包含新的实现，然后让 *note distutils.core.setup():
3d90. 函数使用它们:

     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},
           ...)

如果新的实现必须通过特定的包来使用则此方式最为适宜，因为每个对这个包感兴
趣的人都将会需要有新的命令实现。

从 Python 2.4 开始，还有第三个选项可用，其目标是允许添加支持现有
‘setup.py’ 脚本的新命令，而不需要修改 Python 安装包。 这预计可允许第三方
扩展提供对附加打包系统的支持，而相应命令又可用于任何 distutils 命令可被
使用的地方。 新的配置选项 ‘command_packages’ (命令行选项为
‘--command-packages’) 可用来指定附加包，以在其中查找实现新增命令的模块。
像所有 distutils 选项一样，这可以通过命令行或配置文件来指定。 此选项只能
在配置文件的 ‘[global]’ 小节之中或在命令行的任何命令之前设置。 如果是设
置在配置文件中，则它可被命令行设置重载；如果在命令行中将其设为空字符串则
将会使用默认值。 此选项绝不应当在随特定包提供的配置文件中设置。

这个新选项可被用来添加任意数量的包到查找命令实现的包列表；多个包名应当以
逗号分隔。 当未指明时，查找将只在 *note distutils.command: 3d. 包中进行
。 但是当 ‘setup.py’ 附带 ‘--command-packages distcmds,buildcmds’ 选项运
行时，*note distutils.command: 3d, ‘distcmds’ 和 ‘buildcmds’ 包将按此顺
序被查找。 新的命令应当在与命名同名的模块中由同名的类来实现。 给定上述示
例命令行选项，则命令 ‘bdist_openpkg’ 可由类
‘distcmds.bdist_openpkg.bdist_openpkg’ 或
‘buildcmds.bdist_openpkg.bdist_openpkg’ 来实现。


File: python.info,  Node: 添加新的发布类型,  Prev: 集成新的命令,  Up: 扩展 Distutils

17.7.2 添加新的发布类型
-----------------------

创建发布（在 ‘dist/’ 目录中的文件）的命令需要将 ‘(command, filename)’ 二
元组添加到 ‘self.distribution.dist_files’ 以便 ‘upload’ 可以将其上传到
PyPI。 二元组中的 `filename' 不包含路径信息而只有文件名本身。 在 dry-run
模式下，二元组仍然应当被添加以表示必须创建的内容。


File: python.info,  Node: 指令參照,  Next: API參照,  Prev: 扩展 Distutils,  Up: 發布 Python 模組（舊版）

17.8 指令參照
=============

     備註: 这篇文档只有在
     ‘https://setuptools.readthedocs.io/en/latest/setuptools.html’ 上的
     ‘setuptools’ 文档独立涵盖此处包含的所有相关信息之前，才会单独保留。

* Menu:

* 安装模块; install 命令族: 安装模块 install 命令族.
* 创建源码发行包; sdist 命令: 创建源码发行包 sdist 命令.


File: python.info,  Node: 安装模块 install 命令族,  Next: 创建源码发行包 sdist 命令,  Up: 指令參照

17.8.1 安装模块: ‘install’ 命令族
---------------------------------

install 命令会确保 build 命令已经运行，然后运行子命令 ‘install_lib’,
‘install_data’ 和 ‘install_scripts’。

* Menu:

* install_data::
* install_scripts::


File: python.info,  Node: install_data,  Next: install_scripts,  Up: 安装模块 install 命令族

17.8.1.1 ‘install_data’
.......................

此命令会安装随发行包一同提供的所有数据文件。


File: python.info,  Node: install_scripts,  Prev: install_data,  Up: 安装模块 install 命令族

17.8.1.2 ‘install_scripts’
..........................

此命令会安装发行包中的所有（Python）脚本。


File: python.info,  Node: 创建源码发行包 sdist 命令,  Prev: 安装模块 install 命令族,  Up: 指令參照

17.8.2 创建源码发行包: ‘sdist’ 命令
-----------------------------------

列出的模板命令有:

命令                                            描述
                                                
----------------------------------------------------------------------------------------------------
                                                
‘include pat1 pat2 ...’                         包括与列出的模式匹配的所有文件
                                                
                                                
‘exclude pat1 pat2 ...’                         排除与列出的模式匹配的所有文件
                                                
                                                
‘recursive-include dir pat1 pat2 ...’           包括 `dir' 下与列出的模式匹配的所有文件
                                                
                                                
‘recursive-exclude dir pat1 pat2 ...’           排除 `dir' 下与列出的模式匹配的所有文件
                                                
                                                
‘global-include pat1 pat2 ...’                  包括与源树匹配的所有文件—和任何列出的模式
                                                
                                                
‘global-exclude pat1 pat2 ...’                  排除与源树匹配的所有文件—和任何列出的模式
                                                
                                                
‘prune dir’                                     排除 `dir' 下的所有文件
                                                
                                                
‘graft dir’                                     包括 `dir' 下的所有文件
                                                

此处的模式是 Unix 风格的 "glob" 模式: ‘*’ 匹配任意的常规文件名字符序列，
‘?’ 匹配任意单个常规文件名字符，而 ‘[range]’ 匹配 `range' 范围内的任意字
符 (例如 ‘a-z’, ‘a-zA-Z’, ‘a-f0-9_.’)。 “常规文件名字符”的定义取决于具体
平台：在 Unix 上是指正斜杠以外的任何字符；在 Windows 则是指反斜杠或冒号
以外的任何字符。


File: python.info,  Node: API參照,  Prev: 指令參照,  Up: 發布 Python 模組（舊版）

17.9 API參照
============

也參考
......

New and changed setup.py arguments in setuptools(1)

     The ‘setuptools’ project adds new capabilities to the ‘setup’
     function and other APIs, makes the API consistent across different
     Python versions, and is hence recommended over using ‘distutils’
     directly.

     備註: 这篇文档只有在
     ‘https://setuptools.readthedocs.io/en/latest/setuptools.html’ 上的
     ‘setuptools’ 文档独立涵盖此处包含的所有相关信息之前，才会单独保留。

* 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

   ---------- Footnotes ----------

   (1) 
https://setuptools.readthedocs.io/en/latest/setuptools.html#new-and-changed-setup-keywords


File: python.info,  Node: distutils core --- 分发包功能的核心,  Next: distutils ccompiler --- CCompiler基类,  Up: API參照

17.9.1 ‘distutils.core’ — 分发包功能的核心
------------------------------------------

The *note distutils.core: 53. 是为了使用 Distutils 工具唯一要安装的模块
。它提供函数 *note setup(): 3d90. （该函数被 setup 脚本调用）。间接提供
了类 ‘distutils.dist.Distribution’ 和 *note distutils.cmd.Command: 45bd.

 -- 函式: 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.

     参数名称                 值                                   类型
                                                                   
     --------------------------------------------------------------------------------------------------------------------------------
                                                                   
     `name'                   包的名字                             字符串
                                                                   
                                                                   
     `version'                包的版本号；参见                     字符串
                              *note distutils.version: 65.         
                              
                                                                   
     `description'            单行的包的描述                       字符串
                                                                   
                                                                   
     `long_description'       更长的包描述                         字符串
                                                                   
                                                                   
     `author'                 包的作者                             字符串
                                                                   
                                                                   
     `author_email'           包的作者的电子邮件                   字符串
                                                                   
                                                                   
     `maintainer'             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
                              ‘PKG-INFO’
                              
                                                                   
     `maintainer_email'       当前维护者的电子邮件地址，如果不同   字符串
                              与作者                               
                              
                                                                   
     `url'                    包的URL（主页）                      字符串
                                                                   
                                                                   
     `download_url'           包的下载地址                         字符串
                                                                   
                                                                   
     `packages'               A list of Python packages that       字符串列表
                              distutils will manipulate            
                              
                                                                   
     `py_modules'             distutils 会操作的 Python 模块列表   字符串列表
                                                                   
                                                                   
     `scripts'                要构建和安装的独立脚本文件的列表     字符串列表
                                                                   
                                                                   
     `ext_modules'            要构建的 Python 扩展的列表           类 *note distutils.core.Extension: 4583. 的实例的列表
                                                                   
                                                                   
     `classifiers'            包的类别列表                         a list of strings; valid classifiers are listed on PyPI(1).
                                                                   
                                                                   
     `distclass'              要使用的类                           *note distutils.core.Distribution: 45ce. 的子类
                              *note Distribution: 45ce. 类         
                              
                                                                   
     `script_name'            setup.py 脚本名称 —— 默认为          字符串
                              ‘sys.argv[0]’                        
                              
                                                                   
     `script_args'            提供给安装脚本的参数                 字符串列表
                                                                   
                                                                   
     `options'                安装脚本的默认选项                   字典
                                                                   
                                                                   
     `license'                包的许可证                           字符串
                                                                   
                                                                   
     `keywords'               Descriptive meta-data, see PEP       字符串列表或逗号分隔的字符串
                              314(2)                               
                              
                                                                   
     `platforms'                                                   字符串列表或逗号分隔的字符串
                                                                   
                                                                   
     `cmdclass'               A mapping of command names to        字典
                              *note Command: 45cf. subclasses      
                              
                                                                   
     `data_files'             要安装的数据文件列表                 列表
                                                                   
                                                                   
     `package_dir'            A mapping of package to directory    字典
                              names                                
                              

 -- 函式: distutils.core.run_setup (script_name[, script_args=None,
          stop_after='run'])

     Run a setup script in a somewhat controlled environment, and return
     the ‘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 `script' to *note setup(): 3d90.), or
     the contents of the config files or command-line.

     `script_name' is a file that will be read and run with *note
     exec(): d0c.  ‘sys.argv[0]’ will be replaced with `script' for the
     duration of the call.  `script_args' is a list of strings; if
     supplied, ‘sys.argv[1:]’ will be replaced by `script_args' for the
     duration of the call.

     `stop_after' tells *note setup(): 3d90. when to stop processing;
     possible values:

     值                  描述
                         
     ----------------------------------------------------------------------
                         
     `init'              Stop after the *note Distribution: 45ce.
                         instance has been created and populated with
                         the keyword arguments to *note setup(): 3d90.
                         
                         
     `config'            Stop after config files have been parsed (and
                         their data stored in the
                         *note Distribution: 45ce. instance)
                         
                         
     `commandline'       Stop after the command-line (‘sys.argv[1:]’ or
                         `script_args') have been parsed (and the data
                         stored in the *note Distribution: 45ce.
                         instance.)
                         
                         
     `run'               Stop after all commands have been run (the same
                         as if *note setup(): 3d90. had been called in
                         the usual way).  This is the default value.
                         

In addition, the *note distutils.core: 53. module exposed a number of
classes that live elsewhere.

   * ‘Extension’ from *note distutils.extension: 5a.

   * *note Command: 45bd. from *note distutils.cmd: 3c.

   * ‘Distribution’ from *note distutils.dist: 58.

A short description of each of these follows, but see the relevant
module for the full reference.

 -- 類別: 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:

     参数名称                     值                                   类型
                                                                       
     --------------------------------------------------------------------------------------------------
                                                                       
     `name'                       the full name of the extension,      字符串
                                  including any packages — ie.         
                                  `not' a filename or pathname, but
                                  Python dotted name
                                  
                                                                       
     `sources'                    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 ‘build_ext’ command as source
                                  for a Python extension.
                                  
                                                                       
     `include_dirs'               list of directories to search for    字符串列表
                                  C/C++ header files (in Unix form     
                                  for portability)
                                  
                                                                       
     `define_macros'              list of macros to define; each       元组列表
                                  macro is defined using a 2-tuple     
                                  ‘(name, value)’, where `value' is
                                  either the string to define it to
                                  or ‘None’ to define it without a
                                  particular value (equivalent of
                                  ‘#define FOO’ in source or ‘-DFOO’
                                  on Unix C compiler command line)
                                  
                                                                       
     `undef_macros'               要明确取消定义的宏列表               字符串列表
                                                                       
                                                                       
     `library_dirs'               list of directories to search for    字符串列表
                                  C/C++ libraries at link time         
                                  
                                                                       
     `libraries'                  要链接的库名列表（不是文件名或路径   字符串列表
                                  ）                                   
                                  
                                                                       
     `runtime_library_dirs'       list of directories to search for    字符串列表
                                  C/C++ libraries at run time (for     
                                  shared extensions, this is when
                                  the extension is loaded)
                                  
                                                                       
     `extra_objects'              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.)
                                  
                                                                       
     `extra_compile_args'         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.
                                  
                                                                       
     `extra_link_args'            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’.
                                  
                                                                       
     `export_symbols'             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: ‘init’ +
                                  extension_name.
                                  
                                                                       
     `depends'                    扩展名依赖的文件列表                 字符串列表
                                                                       
                                                                       
     `language'                   extension language (i.e.  ‘'c'’,     字符串
                                  ‘'c++'’, ‘'objc'’).  Will be         
                                  detected from the source
                                  extensions if not provided.
                                  
                                                                       
     `optional'                   指定扩展中的构建失败不应中止构建过   布尔
                                  程，而只是跳过扩展。                 
                                  

     3.8 版更變: On Unix, C extensions are no longer linked to libpython
     except on Android and Cygwin.

 -- 類別: distutils.core.Distribution

     A *note Distribution: 45ce. describes how to build, install and
     package up a Python software package.

     See the *note setup(): 3d90. function for a list of keyword
     arguments accepted by the Distribution constructor.  *note setup():
     3d90. creates a Distribution instance.

     3.7 版更變: *note Distribution: 45ce. now warns if ‘classifiers’,
     ‘keywords’ and ‘platforms’ fields are not specified as a list or a
     string.

 -- 類別: distutils.core.Command

     A *note Command: 45cf. class (or rather, an instance of one of its
     subclasses) implement a single distutils command.

   ---------- Footnotes ----------

   (1) https://pypi.org/classifiers

   (2) https://www.python.org/dev/peps/pep-0314


File: python.info,  Node: distutils ccompiler --- CCompiler基类,  Next: distutils unixccompiler --- Unix C Compiler,  Prev: distutils core --- 分发包功能的核心,  Up: API參照

17.9.2 ‘distutils.ccompiler’ — CCompiler基类
--------------------------------------------

This module provides the abstract base class for the *note CCompiler:
45d2. classes.  A *note CCompiler: 45d2. 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.

 -- 函式: distutils.ccompiler.gen_lib_options (compiler, library_dirs,
          runtime_library_dirs, libraries)

     Generate linker options for searching library directories and
     linking with specific libraries.  `libraries' and `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).

 -- 函式: distutils.ccompiler.gen_preprocess_options (macros,
          include_dirs)

     Generate C pre-processor options (‘-D’, ‘-U’, ‘-I’) as used by at
     least two types of compilers: the typical Unix compiler and Visual
     C++.  `macros' is the usual thing, a list of 1- or 2-tuples, where
     ‘(name,)’ means undefine (‘-U’) macro `name', and ‘(name, value)’
     means define (‘-D’) macro `name' to `value'.  `include_dirs' is
     just a list of directory names to be added to the header file
     search path (‘-I’).  Returns a list of command-line options
     suitable for either Unix compilers or Visual C++.

 -- 函式: distutils.ccompiler.get_default_compiler (osname, platform)

     Determine the default compiler to use for the given platform.

     `osname' should be one of the standard Python OS names (i.e.  the
     ones returned by ‘os.name’) and `platform' the common value
     returned by ‘sys.platform’ for the platform in question.

     The default values are ‘os.name’ and ‘sys.platform’ in case the
     parameters are not given.

 -- 函式: 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.  `plat' defaults to
     ‘os.name’ (eg.  ‘'posix'’, ‘'nt'’), and `compiler' defaults to the
     default compiler for that platform.  Currently only ‘'posix'’ and
     ‘'nt'’ are supported, and the default compilers are "traditional
     Unix interface" (‘UnixCCompiler’ class) and Visual C++
     (‘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 `compiler', `plat' is
     ignored.

 -- 函式: distutils.ccompiler.show_compilers ()

     Print list of available compilers (used by the ‘--help-compiler’
     options to ‘build’, ‘build_ext’, ‘build_clib’).

 -- 類別: distutils.ccompiler.CCompiler ([verbose=0, dry_run=0,
          force=0])

     The abstract base class *note CCompiler: 45d2. 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 `verbose' (show verbose output),
     `dry_run' (don’t actually execute the steps) and `force' (rebuild
     everything, regardless of dependencies).  All of these flags
     default to ‘0’ (off).  Note that you probably don’t want to
     instantiate *note CCompiler: 45d2. or one of its subclasses
     directly - use the ‘distutils.CCompiler.new_compiler()’ factory
     function instead.

     The following methods allow you to manually alter compiler options
     for the instance of the Compiler class.

      -- 成員函式: add_include_dir (dir)

          Add `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 *note add_include_dir(): 45d8.

      -- 成員函式: set_include_dirs (dirs)

          Set the list of directories that will be searched to `dirs' (a
          list of strings).  Overrides any preceding calls to *note
          add_include_dir(): 45d8.; subsequent calls to *note
          add_include_dir(): 45d8. add to the list passed to *note
          set_include_dirs(): 45d9.  This does not affect any list of
          standard include directories that the compiler may search by
          default.

      -- 成員函式: add_library (libname)

          Add `libname' to the list of libraries that will be included
          in all links driven by this compiler object.  Note that
          `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 *note add_library(): 45da. and/or
          *note set_libraries(): 45db.  It is perfectly valid to
          duplicate library names; the linker will be instructed to link
          against libraries as many times as they are mentioned.

      -- 成員函式: set_libraries (libnames)

          Set the list of libraries to be included in all links driven
          by this compiler object to `libnames' (a list of strings).
          This does not affect any standard system libraries that the
          linker may include by default.

      -- 成員函式: add_library_dir (dir)

          Add `dir' to the list of directories that will be searched for
          libraries specified to *note add_library(): 45da. and *note
          set_libraries(): 45db.  The linker will be instructed to
          search for libraries in the order they are supplied to *note
          add_library_dir(): 45dc. and/or *note set_library_dirs():
          45dd.

      -- 成員函式: set_library_dirs (dirs)

          Set the list of library search directories to `dirs' (a list
          of strings).  This does not affect any standard library search
          path that the linker may search by default.

      -- 成員函式: add_runtime_library_dir (dir)

          Add `dir' to the list of directories that will be searched for
          shared libraries at runtime.

      -- 成員函式: set_runtime_library_dirs (dirs)

          Set the list of directories to search for shared libraries at
          runtime to `dirs' (a list of strings).  This does not affect
          any standard search path that the runtime linker may search by
          default.

      -- 成員函式: define_macro (name[, value=None])

          Define a preprocessor macro for all compilations driven by
          this compiler object.  The optional parameter `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.

      -- 成員函式: undefine_macro (name)

          Undefine a preprocessor macro for all compilations driven by
          this compiler object.  If the same macro is defined by *note
          define_macro(): 45e0. and undefined by *note undefine_macro():
          45e1. 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 *note compile(): 2e7.), then that takes precedence.

      -- 成員函式: add_link_object (object)

          Add `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.

      -- 成員函式: set_link_objects (objects)

          Set the list of object files (or analogues) to be included in
          every link to `objects'.  This does not affect any standard
          object files that the linker may include by default (such as
          system libraries).

     The following methods implement methods for autodetection of
     compiler options, providing some functionality similar to GNU
     ‘autoconf’.

      -- 成員函式: detect_language (sources)

          Detect the language of a given file, or list of files.  Uses
          the instance attributes ‘language_map’ (a dictionary), and
          ‘language_order’ (a list) to do the job.

      -- 成員函式: find_library_file (dirs, lib[, debug=0])

          Search the specified list of directories for a static or
          shared library file `lib' and return the full path to that
          file.  If `debug' is true, look for a debugging version (if
          that makes sense on the current platform).  Return ‘None’ if
          `lib' wasn’t found in any of the specified directories.

      -- 成員函式: has_function (funcname[, includes=None,
               include_dirs=None, libraries=None, library_dirs=None])

          Return a boolean indicating whether `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.

      -- 成員函式: library_dir_option (dir)

          Return the compiler option to add `dir' to the list of
          directories searched for libraries.

      -- 成員函式: library_option (lib)

          Return the compiler option to add `lib' to the list of
          libraries linked into the shared library or executable.

      -- 成員函式: runtime_library_dir_option (dir)

          Return the compiler option to add `dir' to the list of
          directories searched for runtime libraries.

      -- 成員函式: 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:

          属性               描述
                             
          ------------------------------------------------------------------
                             
          `compiler'         C/C++ 编译器
                             
                             
          `linker_so'        用于创建共享对象和库的链接器
                             
                             
          `linker_exe'       用于创建二进制可执行文件的链接器
                             
                             
          `archiver'         静态库创建者
                             

          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
          *note distutils.util.split_quoted(): 45eb.)

     The following methods invoke stages in the build process.

      -- 成員函式: 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 ‘.c’ file to a ‘.o’ file.)

          `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.  ‘MSVCCompiler’
          can handle resource files in `sources').  Return a list of
          object filenames, one per source filename in `sources'.
          Depending on the implementation, not all source files will
          necessarily be compiled, but all corresponding object
          filenames will be returned.

          If `output_dir' is given, object files will be put under it,
          while retaining their original path component.  That is,
          ‘foo/bar.c’ normally compiles to ‘foo/bar.o’ (for a Unix
          implementation); if `output_dir' is `build', then it would
          compile to ‘build/foo/bar.o’.

          `macros', if given, must be a list of macro definitions.  A
          macro definition is either a ‘(name, value)’ 2-tuple or a
          ‘(name,)’ 1-tuple.  The former defines a macro; if the value
          is ‘None’, the macro is defined without an explicit value.
          The 1-tuple case undefines a macro.  Later
          definitions/redefinitions/undefinitions take precedence.

          `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.

          `debug' is a boolean; if true, the compiler will be instructed
          to output debug symbols in (or alongside) the object file(s).

          `extra_preargs' and `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.

          `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 ‘CompileError’ on failure.

      -- 成員函式: 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 `objects', the extra object files supplied
          to *note add_link_object(): 45e2. and/or *note
          set_link_objects(): 45e3, the libraries supplied to *note
          add_library(): 45da. and/or *note set_libraries(): 45db, and
          the libraries supplied as `libraries' (if any).

          `output_libname' should be a library name, not a filename; the
          filename will be inferred from the library name.  `output_dir'
          is the directory where the library file will be put.

          `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 `debug' flag is
          included here just for consistency).

          `target_lang' is the target language for which the given
          objects are being compiled.  This allows specific linkage time
          treatment of certain languages.

          Raises ‘LibError’ on failure.

      -- 成員函式: 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 `objects'.  `output_filename' should be a
          filename.  If `output_dir' is supplied, `output_filename' is
          relative to it (i.e.  `output_filename' can provide directory
          components if needed).

          `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.  `foo' becomes
          ‘libfoo.a’ on Unix and ‘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.

          `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 *note add_library_dir():
          45dc. and/or *note set_library_dirs(): 45dd.
          `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.)

          `export_symbols' is a list of symbols that the shared library
          will export.  (This appears to be relevant only on Windows.)

          `debug' is as for *note compile(): 2e7. and *note
          create_static_lib(): 45ed, with the slight distinction that it
          actually matters on most platforms (as opposed to *note
          create_static_lib(): 45ed, which includes a `debug' flag
          mostly for form’s sake).

          `extra_preargs' and `extra_postargs' are as for *note
          compile(): 2e7. (except of course that they supply
          command-line arguments for the particular linker being used).

          `target_lang' is the target language for which the given
          objects are being compiled.  This allows specific linkage time
          treatment of certain languages.

          Raises ‘LinkError’ on failure.

      -- 成員函式: 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.  `output_progname' is the name of the file
          executable, while `objects' are a list of object filenames to
          link in.  Other arguments are as for the *note link(): 45ee.
          method.

      -- 成員函式: 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.  `output_libname' is the name of the
          output library, while `objects' is a list of object filenames
          to link in.  Other arguments are as for the *note link():
          45ee. method.

      -- 成員函式: 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.  `output_filename' is the name of the
          shared object that will be created, while `objects' is a list
          of object filenames to link in.  Other arguments are as for
          the *note link(): 45ee. method.

      -- 成員函式: 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 `source'.
          Output will be written to file named `output_file', or
          `stdout' if `output_file' not supplied.  `macros' is a list of
          macro definitions as for *note compile(): 2e7, which will
          augment the macros set with *note define_macro(): 45e0. and
          *note undefine_macro(): 45e1.  `include_dirs' is a list of
          directory names that will be added to the default list, in the
          same way as *note add_include_dir(): 45d8.

          Raises ‘PreprocessError’ on failure.

     The following utility methods are defined by the *note CCompiler:
     45d2. class, for use by the various concrete subclasses.

      -- 成員函式: executable_filename (basename[, strip_dir=0,
               output_dir=''])

          Returns the filename of the executable for the given
          `basename'.  Typically for non-Windows platforms this is the
          same as the basename, while Windows will get a ‘.exe’ added.

      -- 成員函式: library_filename (libname[, lib_type='static',
               strip_dir=0, output_dir=''])

          Returns the filename for the given library name on the current
          platform.  On Unix a library with `lib_type' of ‘'static'’
          will typically be of the form ‘liblibname.a’, while a
          `lib_type' of ‘'dynamic'’ will be of the form ‘liblibname.so’.

      -- 成員函式: object_filenames (source_filenames[, strip_dir=0,
               output_dir=''])

          Returns the name of the object files for the given source
          files.  `source_filenames' should be a list of filenames.

      -- 成員函式: shared_object_filename (basename[, strip_dir=0,
               output_dir=''])

          Returns the name of a shared object file for the given file
          name `basename'.

      -- 成員函式: execute (func, args[, msg=None, level=1])

          Invokes *note distutils.util.execute(): 45f8.  This method
          invokes a Python function `func' with the given arguments
          `args', after logging and taking into account the `dry_run'
          flag.

      -- 成員函式: spawn (cmd)

          Invokes ‘distutils.util.spawn()’.  This invokes an external
          process to run the given command.

      -- 成員函式: mkpath (name[, mode=511])

          Invokes *note distutils.dir_util.mkpath(): 45fb.  This creates
          a directory and any missing ancestor directories.

      -- 成員函式: move_file (src, dst)

          Invokes *note distutils.file_util.move_file(): 45fd.  Renames
          `src' to `dst'.

      -- 成員函式: announce (msg[, level=1])

          Write a message using ‘distutils.log.debug()’.

      -- 成員函式: warn (msg)

          Write a warning message `msg' to standard error.

      -- 成員函式: debug_print (msg)

          If the `debug' flag is set on this *note CCompiler: 45d2.
          instance, print `msg' to standard output, otherwise do
          nothing.


File: python.info,  Node: distutils unixccompiler --- Unix C Compiler,  Next: distutils msvccompiler --- Microsoft Compiler,  Prev: distutils ccompiler --- CCompiler基类,  Up: API參照

17.9.3 ‘distutils.unixccompiler’ — Unix C Compiler
--------------------------------------------------

This module provides the ‘UnixCCompiler’ class, a subclass of
‘CCompiler’ that handles the typical Unix-style command-line C compiler:

   * macros defined with ‘-Dname[=value]’

   * macros undefined with ‘-Uname’

   * include search directories specified with ‘-Idir’

   * libraries specified with ‘-llib’

   * library search directories specified with ‘-Ldir’

   * compile handled by ‘cc’ (or similar) executable with ‘-c’ option:
     compiles ‘.c’ to ‘.o’

   * link static library handled by ‘ar’ command (possibly with
     ‘ranlib’)

   * link shared library handled by ‘cc’ ‘-shared’


File: python.info,  Node: distutils msvccompiler --- Microsoft Compiler,  Next: distutils bcppcompiler --- Borland Compiler,  Prev: distutils unixccompiler --- Unix C Compiler,  Up: API參照

17.9.4 ‘distutils.msvccompiler’ — Microsoft Compiler
----------------------------------------------------

This module provides ‘MSVCCompiler’, an implementation of the abstract
‘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.

‘MSVCCompiler’ will normally choose the right compiler, linker etc.  on
its own.  To override this choice, the environment variables
`DISTUTILS_USE_SDK' and `MSSdk' must be both set.  `MSSdk' indicates
that the current environment has been setup by the SDK’s ‘SetEnv.Cmd’
script, or that the environment variables had been registered when the
SDK was installed; `DISTUTILS_USE_SDK' indicates that the distutils user
has made an explicit choice to override the compiler selection by
‘MSVCCompiler’.


File: python.info,  Node: distutils bcppcompiler --- Borland Compiler,  Next: distutils cygwincompiler --- Cygwin Compiler,  Prev: distutils msvccompiler --- Microsoft Compiler,  Up: API參照

17.9.5 ‘distutils.bcppcompiler’ — Borland Compiler
--------------------------------------------------

This module provides ‘BorlandCCompiler’, a subclass of the abstract
‘CCompiler’ class for the Borland C++ compiler.


File: python.info,  Node: distutils cygwincompiler --- Cygwin Compiler,  Next: distutils archive_util --- Archiving utilities,  Prev: distutils bcppcompiler --- Borland Compiler,  Up: API參照

17.9.6 ‘distutils.cygwincompiler’ — Cygwin Compiler
---------------------------------------------------

This module provides the ‘CygwinCCompiler’ class, a subclass of
‘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).


File: python.info,  Node: distutils archive_util --- Archiving utilities,  Next: distutils dep_util --- Dependency checking,  Prev: distutils cygwincompiler --- Cygwin Compiler,  Up: API參照

17.9.7 ‘distutils.archive_util’ — Archiving utilities
-----------------------------------------------------

This module provides a few functions for creating archive files, such as
tarballs or zipfiles.

 -- 函式: distutils.archive_util.make_archive (base_name, format[,
          root_dir=None, base_dir=None, verbose=0, dry_run=0])

     Create an archive file (eg.  ‘zip’ or ‘tar’).  `base_name' is the
     name of the file to create, minus any format-specific extension;
     `format' is the archive format: one of ‘zip’, ‘tar’, ‘gztar’,
     ‘bztar’, ‘xztar’, or ‘ztar’.  `root_dir' is a directory that will
     be the root directory of the archive; ie.  we typically ‘chdir’
     into `root_dir' before creating the archive.  `base_dir' is the
     directory where we start archiving from; ie.  `base_dir' will be
     the common prefix of all files and directories in the archive.
     `root_dir' and `base_dir' both default to the current directory.
     Returns the name of the archive file.

     3.5 版更變: 添加了对 ‘xztar’ 格式的支持

 -- 函式: 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 `base_dir'.  `compress' must be ‘'gzip'’ (the
     default), ‘'bzip2'’, ‘'xz'’, ‘'compress'’, or ‘None’.  For the
     ‘'compress'’ method the compression utility named by ‘compress’
     must be on the default program search path, so this is probably
     Unix-specific.  The output tar file will be named ‘base_dir.tar’,
     possibly plus the appropriate compression extension (‘.gz’, ‘.bz2’,
     ‘.xz’ or ‘.Z’).  Return the output filename.

     3.5 版更變: Added support for the ‘xz’ compression.

 -- 函式: distutils.archive_util.make_zipfile (base_name, base_dir[,
          verbose=0, dry_run=0])

     Create a zip file from all files in and under `base_dir'.  The
     output zip file will be named `base_name' + ‘.zip’.  Uses either
     the *note zipfile: 14b. Python module (if available) or the InfoZIP
     ‘zip’ utility (if installed and found on the default search path).
     If neither tool is available, raises ‘DistutilsExecError’.  Returns
     the name of the output zip file.


File: python.info,  Node: distutils dep_util --- Dependency checking,  Next: distutils dir_util --- Directory tree operations,  Prev: distutils archive_util --- Archiving utilities,  Up: API參照

17.9.8 ‘distutils.dep_util’ — Dependency checking
-------------------------------------------------

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.

 -- 函式: distutils.dep_util.newer (source, target)

     Return true if `source' exists and is more recently modified than
     `target', or if `source' exists and `target' doesn’t.  Return false
     if both exist and `target' is the same age or newer than `source'.
     Raise ‘DistutilsFileError’ if `source' does not exist.

 -- 函式: 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
     (`sources', `targets') where source is newer than target, according
     to the semantics of *note newer(): 460a.

 -- 函式: distutils.dep_util.newer_group (sources, target[,
          missing='error'])

     Return true if `target' is out-of-date with respect to any file
     listed in `sources'.  In other words, if `target' exists and is
     newer than every file in `sources', return false; otherwise return
     true.  `missing' controls what we do when a source file is missing;
     the default (‘'error'’) is to blow up with an *note OSError: 304.
     from inside *note os.stat(): 321.; if it is ‘'ignore'’, we silently
     drop any missing source files; if it is ‘'newer'’, any missing
     source files make us assume that `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).


File: python.info,  Node: distutils dir_util --- Directory tree operations,  Next: distutils file_util --- Single file operations,  Prev: distutils dep_util --- Dependency checking,  Up: API參照

17.9.9 ‘distutils.dir_util’ — Directory tree operations
-------------------------------------------------------

This module provides functions for operating on directories and trees of
directories.

 -- 函式: 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 `name' is the empty string, which
     means the current directory, which of course exists), then do
     nothing.  Raise ‘DistutilsFileError’ if unable to create some
     directory along the way (eg.  some sub-path exists, but is a file
     rather than a directory).  If `verbose' is true, print a one-line
     summary of each mkdir to stdout.  Return the list of directories
     actually created.

 -- 函式: distutils.dir_util.create_tree (base_dir, files[, mode=0o777,
          verbose=0, dry_run=0])

     Create all the empty directories under `base_dir' needed to put
     `files' there.  `base_dir' is just the name of a directory which
     doesn’t necessarily exist yet; `files' is a list of filenames to be
     interpreted relative to `base_dir'.  `base_dir' + the directory
     portion of every file in `files' will be created if it doesn’t
     already exist.  `mode', `verbose' and `dry_run' flags are as for
     *note mkpath(): 45fb.

 -- 函式: 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 `src' to a new location `dst'.  Both
     `src' and `dst' must be directory names.  If `src' is not a
     directory, raise ‘DistutilsFileError’.  If `dst' does not exist, it
     is created with *note mkpath(): 45fb.  The end result of the copy
     is that every file in `src' is copied to `dst', and directories
     under `src' are recursively copied to `dst'.  Return the list of
     files that were copied or might have been copied, using their
     output name.  The return value is unaffected by `update' or
     `dry_run': it is simply the list of all files under `src', with the
     names changed to be under `dst'.

     `preserve_mode' and `preserve_times' are the same as for *note
     distutils.file_util.copy_file(): 4610.; note that they only apply
     to regular files, not to directories.  If `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.  `update' and `verbose' are the same as for
     ‘copy_file()’.

     Files in `src' that begin with ‘.nfs’ are skipped (more information
     on these files is available in answer D2 of the NFS FAQ page(1)).

     3.3.1 版更變: NFS files are ignored.

 -- 函式: distutils.dir_util.remove_tree (directory[, verbose=0,
          dry_run=0])

     Recursively remove `directory' and all files and directories
     underneath it.  Any errors are ignored (apart from being reported
     to ‘sys.stdout’ if `verbose' is true).

   ---------- Footnotes ----------

   (1) http://nfs.sourceforge.net/#section_d


File: python.info,  Node: distutils file_util --- Single file operations,  Next: distutils util --- Miscellaneous other utility functions,  Prev: distutils dir_util --- Directory tree operations,  Up: API參照

17.9.10 ‘distutils.file_util’ — Single file operations
------------------------------------------------------

This module contains some utility functions for operating on individual
files.

 -- 函式: distutils.file_util.copy_file (src, dst[, preserve_mode=1,
          preserve_times=1, update=0, link=None, verbose=0, dry_run=0])

     Copy file `src' to `dst'.  If `dst' is a directory, then `src' is
     copied there with the same name; otherwise, it must be a filename.
     (If the file exists, it will be ruthlessly clobbered.)  If
     `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 `preserve_times' is true (the default), the
     last-modified and last-access times are copied as well.  If
     `update' is true, `src' will only be copied if `dst' does not
     exist, or if `dst' does exist but is older than `src'.

     `link' allows you to make hard links (using *note os.link(): b11.)
     or symbolic links (using *note os.symlink(): b17.) instead of
     copying: set it to ‘'hard'’ or ‘'sym'’; if it is ‘None’ (the
     default), files are copied.  Don’t set `link' on systems that don’t
     support it: *note copy_file(): 4610. doesn’t check if hard or
     symbolic linking is available.  It uses ‘_copy_file_contents()’ to
     copy file contents.

     Return a tuple ‘(dest_name, copied)’: `dest_name' is the actual
     name of the output file, and `copied' is true if the file was
     copied (or would have been copied, if `dry_run' true).

 -- 函式: distutils.file_util.move_file (src, dst[, verbose, dry_run])

     Move file `src' to `dst'.  If `dst' is a directory, the file will
     be moved into it with the same name; otherwise, `src' is just
     renamed to `dst'.  Returns the new full name of the file.

          警告: Handles cross-device moves on Unix using *note
          copy_file(): 4610.  What about other systems?

 -- 函式: distutils.file_util.write_file (filename, contents)

     Create a file called `filename' and write `contents' (a sequence of
     strings without line terminators) to it.


File: python.info,  Node: distutils util --- Miscellaneous other utility functions,  Next: distutils dist --- The Distribution class,  Prev: distutils file_util --- Single file operations,  Up: API參照

17.9.11 ‘distutils.util’ — Miscellaneous other utility functions
----------------------------------------------------------------

This module contains other assorted bits and pieces that don’t fit into
any other utility module.

 -- 函式: 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.

     返回值的示例：

        * ‘linux-i586’

        * ‘linux-alpha’

        * ‘solaris-2.6-sun4u’

     For non-POSIX platforms, currently just returns ‘sys.platform’.

     For macOS systems the OS version reflects the minimal version on
     which binaries will run (that is, the value of
     ‘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 ‘fat’, for 64-bit universal binaries the
     architecture is ‘fat64’, and for 4-way universal binaries the
     architecture is ‘universal’.  Starting from Python 2.7 and Python
     3.2 the architecture ‘fat3’ is used for a 3-way universal build
     (ppc, i386, x86_64) and ‘intel’ is used for a universal build with
     the i386 and x86_64 architectures

     Examples of returned values on macOS:

        * ‘macosx-10.3-ppc’

        * ‘macosx-10.3-fat’

        * ‘macosx-10.5-universal’

        * ‘macosx-10.6-intel’

     For AIX, Python 3.9 and later return a string starting with "aix",
     followed by additional fields (separated by ‘'-'’) 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:

        * ‘aix-5307-0747-32’ # 32-bit build on AIX ‘oslevel -s’:
          5300-07-00-0000

        * ‘aix-7105-1731-64’ # 64-bit build on AIX ‘oslevel -s’:
          7100-05-01-1731

        * ‘aix-7.2’ # Legacy form reported in Python 3.8 and earlier

     3.9 版更變: The AIX platform string format now also includes the
     technology level, build date, and ABI bit-size.

 -- 函式: 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 *note ValueError: 16d. on non-Unix-ish
     systems if `pathname' either starts or ends with a slash.

 -- 函式: distutils.util.change_root (new_root, pathname)

     Return `pathname' with `new_root' prepended.  If `pathname' is
     relative, this is equivalent to ‘os.path.join(new_root,pathname)’
     Otherwise, it requires making `pathname' relative and then joining
     the two, which is tricky on DOS/Windows.

 -- 函式: 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:

        * ‘HOME’ - user’s home directory (Unix only)

        * ‘PLAT’ - description of the current platform, including
          hardware and OS (see *note get_platform(): 4615.)

 -- 函式: distutils.util.subst_vars (s, local_vars)

     Perform shell/Perl-style variable substitution on `s'.  Every
     occurrence of ‘$’ followed by a name is considered a variable, and
     variable is substituted by the value found in the `local_vars'
     dictionary, or in ‘os.environ’ if it’s not in `local_vars'.
     `os.environ' is first checked/augmented to guarantee that it
     contains certain values: see *note check_environ(): 4618.  Raise
     *note ValueError: 16d. for any variables not found in either
     `local_vars' or ‘os.environ’.

     Note that this is not a fully-fledged string interpolation
     function.  A valid ‘$variable’ can consist only of upper and lower
     case letters, numbers and an underscore.  No { } or ( ) style
     quoting is available.

 -- 函式: 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.

 -- 函式: 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 `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.

 -- 函式: distutils.util.strtobool (val)

     Convert a string representation of truth to true (1) or false (0).

     True values are ‘y’, ‘yes’, ‘t’, ‘true’, ‘on’ and ‘1’; false values
     are ‘n’, ‘no’, ‘f’, ‘false’, ‘off’ and ‘0’.  Raises *note
     ValueError: 16d. if `val' is anything else.

 -- 函式: 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 ‘.pyc’ files in
     a ‘__pycache__’ subdirectory (see PEP 3147(1) and PEP 488(2)).
     `py_files' is a list of files to compile; any files that don’t end
     in ‘.py’ are silently skipped.  `optimize' must be one of the
     following:

        * ‘0’ - don’t optimize

        * ‘1’ - normal optimization (like ‘python -O’)

        * ‘2’ - extra optimization (like ‘python -OO’)

     If `force' is true, all files are recompiled regardless of
     timestamps.

     The source filename encoded in each *note bytecode: 709. file
     defaults to the filenames listed in `py_files'; you can modify
     these with `prefix' and `basedir'.  `prefix' is a string that will
     be stripped off of each source filename, and `base_dir' is a
     directory name that will be prepended (after `prefix' is stripped).
     You can supply either or both (or neither) of `prefix' and
     `base_dir', as you wish.

     If `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 *note py_compile: d7. module, or
     indirectly by writing a temporary script and executing it.
     Normally, you should let *note byte_compile(): 461b. figure out to
     use direct compilation or not (see the source for details).  The
     `direct' flag is used by the script generated in indirect mode;
     unless you know what you’re doing, leave it set to ‘None’.

     3.2.3 版更變: Create ‘.pyc’ files with an *note import magic tag:
     3d00. in their name, in a ‘__pycache__’ subdirectory instead of
     files without tag in the current directory.

     3.5 版更變: Create ‘.pyc’ files according to PEP 488(3).

 -- 函式: distutils.util.rfc822_escape (header)

     Return a version of `header' escaped for inclusion in an RFC 822(4)
     header, by ensuring there are 8 spaces space after each newline.
     Note that it does no other modification of the string.

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-3147

   (2) https://www.python.org/dev/peps/pep-0488

   (3) https://www.python.org/dev/peps/pep-0488

   (4) https://tools.ietf.org/html/rfc822.html


File: python.info,  Node: distutils dist --- The Distribution class,  Next: distutils extension --- The Extension class,  Prev: distutils util --- Miscellaneous other utility functions,  Up: API參照

17.9.12 ‘distutils.dist’ — The Distribution class
-------------------------------------------------

This module provides the *note Distribution: 45ce. class, which
represents the module distribution being built/installed/distributed.


File: python.info,  Node: distutils extension --- The Extension class,  Next: distutils debug --- Distutils debug mode,  Prev: distutils dist --- The Distribution class,  Up: API參照

17.9.13 ‘distutils.extension’ — The Extension class
---------------------------------------------------

This module provides the ‘Extension’ class, used to describe C/C++
extension modules in setup scripts.


File: python.info,  Node: distutils debug --- Distutils debug mode,  Next: distutils errors --- Distutils exceptions,  Prev: distutils extension --- The Extension class,  Up: API參照

17.9.14 ‘distutils.debug’ — Distutils debug mode
------------------------------------------------

本模块提供DEBUG标识。


File: python.info,  Node: distutils errors --- Distutils exceptions,  Next: distutils fancy_getopt --- Wrapper around the standard getopt module,  Prev: distutils debug --- Distutils debug mode,  Up: API參照

17.9.15 ‘distutils.errors’ — Distutils exceptions
-------------------------------------------------

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 ‘from ... import *’ mode; it only exports
symbols whose names start with ‘Distutils’ and end with ‘Error’.


File: python.info,  Node: distutils fancy_getopt --- Wrapper around the standard getopt module,  Next: distutils filelist --- The FileList class,  Prev: distutils errors --- Distutils exceptions,  Up: API參照

17.9.16 ‘distutils.fancy_getopt’ — Wrapper around the standard getopt module
----------------------------------------------------------------------------

This module provides a wrapper around the standard *note getopt: 85.
module that provides the following additional features:

   * short and long options are tied together

   * options have help strings, so *note fancy_getopt(): 4622. could
     potentially create a complete usage summary

   * options set attributes of a passed-in object

   * boolean options can have "negative aliases" — eg.  if ‘--quiet’ is
     the "negative alias" of ‘--verbose’, then ‘--quiet’ on the command
     line sets `verbose' to false.

 -- 函式: distutils.fancy_getopt.fancy_getopt (options, negative_opt,
          object, args)

     Wrapper function.  `options' is a list of ‘(long_option,
     short_option, help_string)’ 3-tuples as described in the
     constructor for *note FancyGetopt: 4623.  `negative_opt' should be
     a dictionary mapping option names to option names, both the key and
     value should be in the `options' list.  `object' is an object which
     will be used to store values (see the *note getopt(): 85. method of
     the *note FancyGetopt: 4623. class).  `args' is the argument list.
     Will use ‘sys.argv[1:]’ if you pass ‘None’ as `args'.

 -- 函式: distutils.fancy_getopt.wrap_text (text, width)

     Wraps `text' to less than `width' wide.

 -- 類別: distutils.fancy_getopt.FancyGetopt ([option_table=None])

     The option_table is a list of 3-tuples: ‘(long_option,
     short_option, help_string)’

     If an option takes an argument, its `long_option' should have ‘'='’
     appended; `short_option' should just be a single character, no
     ‘':'’ in any case.  `short_option' should be ‘None’ if a
     `long_option' doesn’t have a corresponding `short_option'.  All
     option tuples must have long options.

The *note FancyGetopt: 4623. class provides the following methods:

 -- 成員函式: FancyGetopt.getopt ([args=None, object=None])

     Parse command-line options in args.  Store as attributes on
     `object'.

     If `args' is ‘None’ or not supplied, uses ‘sys.argv[1:]’.  If
     `object' is ‘None’ or not supplied, creates a new ‘OptionDummy’
     instance, stores option values there, and returns a tuple ‘(args,
     object)’.  If `object' is supplied, it is modified in place and
     *note getopt(): 85. just returns `args'; in both cases, the
     returned `args' is a modified copy of the passed-in `args' list,
     which is left untouched.

 -- 成員函式: FancyGetopt.get_option_order ()

     Returns the list of ‘(option, value)’ tuples processed by the
     previous run of *note getopt(): 85. Raises *note RuntimeError: 3dc.
     if *note getopt(): 85. hasn’t been called yet.

 -- 成員函式: FancyGetopt.generate_help ([header=None])

     Generate help text (a list of strings, one per suggested line of
     output) from the option table for this *note FancyGetopt: 4623.
     object.

     If supplied, prints the supplied `header' at the top of the help.


File: python.info,  Node: distutils filelist --- The FileList class,  Next: distutils log --- Simple PEP 282-style logging,  Prev: distutils fancy_getopt --- Wrapper around the standard getopt module,  Up: API參照

17.9.17 ‘distutils.filelist’ — The FileList class
-------------------------------------------------

This module provides the ‘FileList’ class, used for poking about the
filesystem and building lists of files.


File: python.info,  Node: distutils log --- Simple PEP 282-style logging,  Next: distutils spawn --- Spawn a sub-process,  Prev: distutils filelist --- The FileList class,  Up: API參照

17.9.18 ‘distutils.log’ — Simple `PEP 282'-style logging
--------------------------------------------------------


File: python.info,  Node: distutils spawn --- Spawn a sub-process,  Next: distutils sysconfig --- System configuration information,  Prev: distutils log --- Simple PEP 282-style logging,  Up: API參照

17.9.19 ‘distutils.spawn’ — Spawn a sub-process
-----------------------------------------------

This module provides the ‘spawn()’ function, a front-end to various
platform-specific functions for launching another program in a
sub-process.  Also provides ‘find_executable()’ to search the path for a
given executable name.


File: python.info,  Node: distutils sysconfig --- System configuration information,  Next: distutils text_file --- The TextFile class,  Prev: distutils spawn --- Spawn a sub-process,  Up: API參照

17.9.20 ‘distutils.sysconfig’ — System configuration information
----------------------------------------------------------------

The *note distutils.sysconfig: 61. 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
‘Makefile’ and configuration header that are installed with Python on
Unix systems.  The configuration header is called ‘pyconfig.h’ for
Python versions starting with 2.2, and ‘config.h’ for earlier versions
of Python.

Some additional functions are provided which perform some useful
manipulations for other parts of the *note distutils: 38. package.

 -- Data: distutils.sysconfig.PREFIX

     The result of ‘os.path.normpath(sys.prefix)’.

 -- Data: distutils.sysconfig.EXEC_PREFIX

     The result of ‘os.path.normpath(sys.exec_prefix)’.

 -- 函式: distutils.sysconfig.get_config_var (name)

     Return the value of a single variable.  This is equivalent to
     ‘get_config_vars().get(name)’.

 -- 函式: 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, ‘None’ will be
     included for that variable.

 -- 函式: 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 ‘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.

 -- 函式: distutils.sysconfig.get_makefile_filename ()

     Return the full path name of the ‘Makefile’ used to build Python.
     For Unix, this will be a file generated by the ‘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.

 -- 函式: distutils.sysconfig.get_python_inc ([plat_specific[, prefix]])

     Return the directory for either the general or platform-dependent C
     include files.  If `plat_specific' is true, the platform-dependent
     include directory is returned; if false or omitted, the
     platform-independent directory is returned.  If `prefix' is given,
     it is used as either the prefix instead of *note PREFIX: 462c, or
     as the exec-prefix instead of *note EXEC_PREFIX: 462d. if
     `plat_specific' is true.

 -- 函式: distutils.sysconfig.get_python_lib ([plat_specific[,
          standard_lib[, prefix]]])

     Return the directory for either the general or platform-dependent
     library installation.  If `plat_specific' is true, the
     platform-dependent include directory is returned; if false or
     omitted, the platform-independent directory is returned.  If
     `prefix' is given, it is used as either the prefix instead of *note
     PREFIX: 462c, or as the exec-prefix instead of *note EXEC_PREFIX:
     462d. if `plat_specific' is true.  If `standard_lib' is true, the
     directory for the standard library is returned rather than the
     directory for the installation of third-party extensions.

The following function is only intended for use within the *note
distutils: 38. package.

 -- 函式: distutils.sysconfig.customize_compiler (compiler)

     Do any platform-specific customization of a *note
     distutils.ccompiler.CCompiler: 45d2. 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 ‘Makefile’.  This information includes the selected
     compiler, compiler and linker options, and the extension used by
     the linker for shared objects.

This function is even more special-purpose, and should only be used from
Python’s own build procedures.

 -- 函式: distutils.sysconfig.set_python_build ()

     Inform the *note distutils.sysconfig: 61. 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.


File: python.info,  Node: distutils text_file --- The TextFile class,  Next: distutils version --- Version number classes,  Prev: distutils sysconfig --- System configuration information,  Up: API參照

17.9.21 ‘distutils.text_file’ — The TextFile class
--------------------------------------------------

This module provides the *note TextFile: 4637. class, which gives an
interface to text files that (optionally) takes care of stripping
comments, ignoring blank lines, and joining lines with backslashes.

 -- 類別: 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 ‘#’ 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 *note warn(): 4638. 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 *note unreadline(): 4639. for implementing line-at-a-time
     lookahead.

     *note TextFile: 4637. instances are create with either `filename',
     `file', or both.  *note RuntimeError: 3dc. is raised if both are
     ‘None’.  `filename' should be a string, and `file' a file object
     (or something that provides *note readline(): de. and *note
     close(): 463a. methods).  It is recommended that you supply at
     least `filename', so that *note TextFile: 4637. can include it in
     warning messages.  If `file' is not supplied, *note TextFile: 4637.
     creates its own using the *note open(): 16f. built-in function.

     The options are all boolean, and affect the values returned by
     *note readline(): de.

     选项名称               描述                                 默认值
                                                                 
     --------------------------------------------------------------------------
                                                                 
     `strip_comments'       strip from ‘'#'’ to end-of-line,     true
                            as well as any whitespace leading    
                            up to the ‘'#'’—unless it is
                            escaped by a backslash
                            
                                                                 
     `lstrip_ws'            strip leading whitespace from each   false
                            line before returning it             
                            
                                                                 
     `rstrip_ws'            strip trailing whitespace            true
                            (including line terminator!)  from   
                            each line before returning it.
                            
                                                                 
     `skip_blanks'          skip lines that are empty *after*    true
                            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 `skip_blanks' is true.)
                            
                                                                 
     `join_lines'           if a backslash is the last           false
                            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.
                            
                                                                 
     `collapse_join'        strip leading whitespace from        false
                            lines that are joined to their       
                            predecessor; only matters if
                            ‘(join_lines and not lstrip_ws)’
                            

     Note that since `rstrip_ws' can strip the trailing newline, the
     semantics of *note readline(): de. must differ from those of the
     built-in file object’s *note readline(): de. method!  In
     particular, *note readline(): de. returns ‘None’ for end-of-file:
     an empty string might just be a blank line (or an all-whitespace
     line), if `rstrip_ws' is true but `skip_blanks' is not.

      -- 成員函式: open (filename)

          Open a new file `filename'.  This overrides any `file' or
          `filename' constructor arguments.

      -- 成員函式: close ()

          Close the current file and forget everything we know about it
          (including the filename and the current line number).

      -- 成員函式: 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 ‘"lines 3-5"’.  If `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.

      -- 成員函式: readline ()

          Read and return a single logical line from the current file
          (or from an internal buffer if lines have previously been
          "unread" with *note unreadline(): 4639.).  If the `join_lines'
          option is true, this may involve reading multiple physical
          lines concatenated into a single string.  Updates the current
          line number, so calling *note warn(): 4638. after *note
          readline(): de. emits a warning about the physical line(s)
          just read.  Returns ‘None’ on end-of-file, since the empty
          string can occur if `rstrip_ws' is true but `strip_blanks' is
          not.

      -- 成員函式: 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.

      -- 成員函式: unreadline (line)

          Push `line' (a string) onto an internal buffer that will be
          checked by future *note readline(): de. calls.  Handy for
          implementing a parser with line-at-a-time lookahead.  Note
          that lines that are "unread" with *note unreadline(): 4639.
          are not subsequently re-cleansed (whitespace stripped, or
          whatever) when read with *note readline(): de.  If multiple
          calls are made to *note unreadline(): 4639. before a call to
          *note readline(): de, the lines will be returned most in most
          recent first order.


File: python.info,  Node: distutils version --- Version number classes,  Next: distutils cmd --- Abstract base class for Distutils commands,  Prev: distutils text_file --- The TextFile class,  Up: API參照

17.9.22 ‘distutils.version’ — Version number classes
----------------------------------------------------


File: python.info,  Node: distutils cmd --- Abstract base class for Distutils commands,  Next: Creating a new Distutils command,  Prev: distutils version --- Version number classes,  Up: API參照

17.9.23 ‘distutils.cmd’ — Abstract base class for Distutils commands
--------------------------------------------------------------------

This module supplies the abstract base class *note Command: 45bd.

 -- 類別: 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 `options'.  The
     options are declared in *note initialize_options(): 4640. and
     defined (given their final values) in *note finalize_options():
     4641, 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 *note
     finalize_options(): 4641.  The body of the subroutine, where it
     does all its work based on the values of its options, is the *note
     run(): 4642. method, which must also be implemented by every
     command class.

     The class constructor takes a single argument `dist', a *note
     Distribution: 45ce. instance.


File: python.info,  Node: Creating a new Distutils command,  Next: distutils command --- Individual Distutils commands,  Prev: distutils cmd --- Abstract base class for Distutils commands,  Up: API參照

17.9.24 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 *note distutils.command: 3d.
package.  There is a sample template in that directory called
‘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 ‘peel_banana’ (so that users can run
‘setup.py peel_banana’), you’d copy ‘command_template’ to
‘distutils/command/peel_banana.py’, then edit it so that it’s
implementing the class ‘peel_banana’, a subclass of *note
distutils.cmd.Command: 45bd.

Subclasses of *note Command: 45bd. must define the following methods.

 -- 成員函式: 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, *note initialize_options(): 4640. implementations are
     just a bunch of ‘self.foo = None’ assignments.

 -- 成員函式: 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
     `foo' depends on `bar', then it is safe to set `foo' from `bar' as
     long as `foo' still has the same value it was assigned in *note
     initialize_options(): 4640.

 -- 成員函式: Command.run ()

     A command’s raison d’etre: carry out the action it exists to
     perform, controlled by the options initialized in *note
     initialize_options(): 4640, customized by other commands, the setup
     script, the command-line, and config files, and finalized in *note
     finalize_options(): 4641.  All terminal output and filesystem
     interaction should be done by *note run(): 4642.

 -- 屬性: Command.sub_commands

     `sub_commands' formalizes the notion of a "family" of commands,
     e.g.  ‘install’ as the parent with sub-commands ‘install_lib’,
     ‘install_headers’, etc.  The parent of a family of commands defines
     `sub_commands' as a class attribute; it’s a list of 2-tuples
     ‘(command_name, predicate)’, with `command_name' a string and
     `predicate' a function, a string or ‘None’.  `predicate' is a
     method of the parent command that determines whether the
     corresponding command is applicable in the current situation.
     (E.g.  ‘install_headers’ is only applicable if we have any C header
     files to install.)  If `predicate' is ‘None’, that command is
     always applicable.

     `sub_commands' is usually defined at the `end' of a class, because
     predicates can be methods of the class, so they must already have
     been defined.  The canonical example is the ‘install’ command.


File: python.info,  Node: distutils command --- Individual Distutils commands,  Next: distutils command bdist --- Build a binary installer,  Prev: Creating a new Distutils command,  Up: API參照

17.9.25 ‘distutils.command’ — Individual Distutils commands
-----------------------------------------------------------


File: python.info,  Node: distutils command bdist --- Build a binary installer,  Next: distutils command bdist_packager --- Abstract base class for packagers,  Prev: distutils command --- Individual Distutils commands,  Up: API參照

17.9.26 ‘distutils.command.bdist’ — Build a binary installer
------------------------------------------------------------


File: python.info,  Node: distutils command bdist_packager --- Abstract base class for packagers,  Next: distutils command bdist_dumb --- Build a "dumb" installer,  Prev: distutils command bdist --- Build a binary installer,  Up: API參照

17.9.27 ‘distutils.command.bdist_packager’ — Abstract base class for packagers
------------------------------------------------------------------------------


File: python.info,  Node: distutils command bdist_dumb --- Build a "dumb" installer,  Next: distutils command bdist_msi --- Build a Microsoft Installer binary package,  Prev: distutils command bdist_packager --- Abstract base class for packagers,  Up: API參照

17.9.28 ‘distutils.command.bdist_dumb’ — Build a "dumb" installer
-----------------------------------------------------------------


File: python.info,  Node: distutils command bdist_msi --- Build a Microsoft Installer binary package,  Next: distutils command bdist_rpm --- Build a binary distribution as a Redhat RPM and SRPM,  Prev: distutils command bdist_dumb --- Build a "dumb" installer,  Up: API參照

17.9.29 ‘distutils.command.bdist_msi’ — Build a Microsoft Installer binary package
----------------------------------------------------------------------------------

 -- 類別: distutils.command.bdist_msi.bdist_msi

3.9 版後已棄用: Use bdist_wheel (wheel packages) instead.

Builds a Windows Installer(1) (.msi) binary package.

In most cases, the ‘bdist_msi’ installer is a better choice than the
‘bdist_wininst’ installer, because it provides better support for Win64
platforms, allows administrators to perform non-interactive
installations, and allows installation through group policies.

   ---------- Footnotes ----------

   (1) https://msdn.microsoft.com/en-us/library/cc185688(VS.85).aspx


File: python.info,  Node: distutils command bdist_rpm --- Build a binary distribution as a Redhat RPM and SRPM,  Next: distutils command bdist_wininst --- Build a Windows installer,  Prev: distutils command bdist_msi --- Build a Microsoft Installer binary package,  Up: API參照

17.9.30 ‘distutils.command.bdist_rpm’ — Build a binary distribution as a Redhat RPM and SRPM
--------------------------------------------------------------------------------------------


File: python.info,  Node: distutils command bdist_wininst --- Build a Windows installer,  Next: distutils command sdist --- Build a source distribution,  Prev: distutils command bdist_rpm --- Build a binary distribution as a Redhat RPM and SRPM,  Up: API參照

17.9.31 ‘distutils.command.bdist_wininst’ — Build a Windows installer
---------------------------------------------------------------------

3.8 版後已棄用: Use bdist_wheel (wheel packages) instead.


File: python.info,  Node: distutils command sdist --- Build a source distribution,  Next: distutils command build --- Build all files of a package,  Prev: distutils command bdist_wininst --- Build a Windows installer,  Up: API參照

17.9.32 ‘distutils.command.sdist’ — Build a source distribution
---------------------------------------------------------------


File: python.info,  Node: distutils command build --- Build all files of a package,  Next: distutils command build_clib --- Build any C libraries in a package,  Prev: distutils command sdist --- Build a source distribution,  Up: API參照

17.9.33 ‘distutils.command.build’ — Build all files of a package
----------------------------------------------------------------


File: python.info,  Node: distutils command build_clib --- Build any C libraries in a package,  Next: distutils command build_ext --- Build any extensions in a package,  Prev: distutils command build --- Build all files of a package,  Up: API參照

17.9.34 ‘distutils.command.build_clib’ — Build any C libraries in a package
---------------------------------------------------------------------------


File: python.info,  Node: distutils command build_ext --- Build any extensions in a package,  Next: distutils command build_py --- Build the py/ pyc files of a package,  Prev: distutils command build_clib --- Build any C libraries in a package,  Up: API參照

17.9.35 ‘distutils.command.build_ext’ — Build any extensions in a package
-------------------------------------------------------------------------


File: python.info,  Node: distutils command build_py --- Build the py/ pyc files of a package,  Next: distutils command build_scripts --- Build the scripts of a package,  Prev: distutils command build_ext --- Build any extensions in a package,  Up: API參照

17.9.36 ‘distutils.command.build_py’ — Build the .py/.pyc files of a package
----------------------------------------------------------------------------

 -- 類別: distutils.command.build_py.build_py

 -- 類別: 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:

          try:
              from distutils.command.build_py import build_py_2to3 as build_py
          except ImportError:
              from distutils.command.build_py import build_py

     to your setup.py, and later:

          cmdclass = {'build_py': build_py}

     to the invocation of setup().


File: python.info,  Node: distutils command build_scripts --- Build the scripts of a package,  Next: distutils command clean --- Clean a package build area,  Prev: distutils command build_py --- Build the py/ pyc files of a package,  Up: API參照

17.9.37 ‘distutils.command.build_scripts’ — Build the scripts of a package
--------------------------------------------------------------------------


File: python.info,  Node: distutils command clean --- Clean a package build area,  Next: distutils command config --- Perform package configuration,  Prev: distutils command build_scripts --- Build the scripts of a package,  Up: API參照

17.9.38 ‘distutils.command.clean’ — Clean a package build area
--------------------------------------------------------------

This command removes the temporary files created by ‘build’ and its
subcommands, like intermediary compiled object files.  With the ‘--all’
option, the complete build directory will be removed.

Extension modules built *note in place: 4596. will not be cleaned, as
they are not in the build directory.


File: python.info,  Node: distutils command config --- Perform package configuration,  Next: distutils command install --- Install a package,  Prev: distutils command clean --- Clean a package build area,  Up: API參照

17.9.39 ‘distutils.command.config’ — Perform package configuration
------------------------------------------------------------------


File: python.info,  Node: distutils command install --- Install a package,  Next: distutils command install_data --- Install data files from a package,  Prev: distutils command config --- Perform package configuration,  Up: API參照

17.9.40 ‘distutils.command.install’ — Install a package
-------------------------------------------------------


File: python.info,  Node: distutils command install_data --- Install data files from a package,  Next: distutils command install_headers --- Install C/C++ header files from a package,  Prev: distutils command install --- Install a package,  Up: API參照

17.9.41 ‘distutils.command.install_data’ — Install data files from a package
----------------------------------------------------------------------------


File: python.info,  Node: distutils command install_headers --- Install C/C++ header files from a package,  Next: distutils command install_lib --- Install library files from a package,  Prev: distutils command install_data --- Install data files from a package,  Up: API參照

17.9.42 ‘distutils.command.install_headers’ — Install C/C++ header files from a package
---------------------------------------------------------------------------------------


File: python.info,  Node: distutils command install_lib --- Install library files from a package,  Next: distutils command install_scripts --- Install script files from a package,  Prev: distutils command install_headers --- Install C/C++ header files from a package,  Up: API參照

17.9.43 ‘distutils.command.install_lib’ — Install library files from a package
------------------------------------------------------------------------------


File: python.info,  Node: distutils command install_scripts --- Install script files from a package,  Next: distutils command register --- Register a module with the Python Package Index,  Prev: distutils command install_lib --- Install library files from a package,  Up: API參照

17.9.44 ‘distutils.command.install_scripts’ — Install script files from a package
---------------------------------------------------------------------------------


File: python.info,  Node: distutils command register --- Register a module with the Python Package Index,  Next: distutils command check --- Check the meta-data of a package,  Prev: distutils command install_scripts --- Install script files from a package,  Up: API參照

17.9.45 ‘distutils.command.register’ — Register a module with the Python Package Index
--------------------------------------------------------------------------------------

The ‘register’ command registers the package with the Python Package
Index.  This is described in more detail in PEP 301(1).

   ---------- Footnotes ----------

   (1) https://www.python.org/dev/peps/pep-0301


File: python.info,  Node: distutils command check --- Check the meta-data of a package,  Prev: distutils command register --- Register a module with the Python Package Index,  Up: API參照

17.9.46 ‘distutils.command.check’ — Check the meta-data of a package
--------------------------------------------------------------------

The ‘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 ‘setup()’ function.


File: python.info,  Node: 安裝 Python 模組（舊版）,  Next: Python 模組索引,  Prev: 發布 Python 模組（舊版）,  Up: Top

18 安裝 Python 模組（舊版）
***************************


作者: Greg Ward

也參考
......

*note 安裝 Python 模組: 8e2.

     最新的模块安装文档。对于常规Python使用，你几乎肯定像使用该文档而非
     这个。

     備註: 这篇文档只有在
     ‘https://setuptools.readthedocs.io/en/latest/setuptools.html’ 上的
     ‘setuptools’ 文档独立涵盖此处包含的所有相关信息之前，才会单独保留。

     備註: 本指南仅介绍构建和分发扩展的基本工具，这些扩展是作为此
     Python版本的一部分提供的。 第三方工具提供更易于使用和更安全的替代方
     案。有关详细信息，请参阅 Python 打包用户指南中的 快速推荐部分(1) 。

* Menu:

* 簡介: 簡介<16>.
* Standard Build and Install::
* Alternate Installation::
* 自定义安装::
* Distutils Configuration Files::
* Building Extensions; Tips and Tricks: Building Extensions Tips and Tricks.

   ---------- Footnotes ----------

   (1) https://packaging.python.org/guides/tool-recommendations/


File: python.info,  Node: 簡介<16>,  Next: Standard Build and Install,  Up: 安裝 Python 模組（舊版）

18.1 簡介
=========

在Python 2.0中，‘distutils’ API 首次被添加到标准库中。这向Linux发行版维
护者提供了一个将Python项目转换为发行版软件包的标准方法，以及向系统管理员
们提供了直接将这些软件包安装到目标系统的标准方法。

自从很多年前 Python 2.0 发布，将构建系统和包安装器与语言运行时的释放循环
紧密连接在一起产生了很多问题。现在推荐做法是在项目中使用 ‘pip’ 包安装器
和 ‘setuptools’ 构建系统，而不是直接使用 ‘distutils’。

请参阅 *note 安裝 Python 模組: 8e2. 和 *note 發布 Python 模組: 8e3. 了解
更多细节。

这个旧文档将被保留，至到我们相信 ‘setuptools’ 覆盖了所有内容。

* Menu:

* 基于分布式系统的源代码分发::


File: python.info,  Node: 基于分布式系统的源代码分发,  Up: 簡介<16>

18.1.1 基于分布式系统的源代码分发
---------------------------------

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.
‘foo-1.0.tar.gz’ or ‘widget-0.9.7.zip’.  Next, the archive will unpack
into a similarly-named directory: ‘foo-1.0’ or ‘widget-0.9.7’.
Additionally, the distribution will contain a setup script ‘setup.py’,
and a file named ‘README.txt’ or possibly just ‘README’, which should
explain that building and installing the module distribution is a simple
matter of running one command from a terminal:

     python setup.py install

Windows 用户应该使用命令提示符来运行命令(Start ‣ Accessories):

     setup.py install

If all these things are true, then you already know how to build and
install the modules you’ve just downloaded: Run the command above.
Unless you need to install things in a non-standard way or customize the
build process, you don’t really need this manual.  Or rather, the above
command is everything you need to get out of this manual.


File: python.info,  Node: Standard Build and Install,  Next: Alternate Installation,  Prev: 簡介<16>,  Up: 安裝 Python 模組（舊版）

18.2 Standard Build and Install
===============================

As described in section *note 基于分布式系统的源代码分发: 4663, building
and installing a module distribution using the Distutils is usually one
simple command to run from a terminal:

     python setup.py install

* Menu:

* Platform variations::
* Splitting the job up::
* How building works::
* How installation works::


File: python.info,  Node: Platform variations,  Next: Splitting the job up,  Up: Standard Build and Install

18.2.1 Platform variations
--------------------------

You should always run the setup command from the distribution root
directory, i.e.  the top-level subdirectory that the module source
distribution unpacks into.  For example, if you’ve just downloaded a
module source distribution ‘foo-1.0.tar.gz’ onto a Unix system, the
normal thing to do is:

     gunzip -c foo-1.0.tar.gz | tar xf -    # unpacks into directory foo-1.0
     cd foo-1.0
     python setup.py install

On Windows, you’d probably download ‘foo-1.0.zip’.  If you downloaded
the archive file to ‘C:\Temp’, then it would unpack into
‘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 ‘unzip’ or ‘pkunzip’) to unpack the archive.  Then, open a command
prompt window and run:

     cd c:\Temp\foo-1.0
     python setup.py install


File: python.info,  Node: Splitting the job up,  Next: How building works,  Prev: Platform variations,  Up: Standard Build and Install

18.2.2 Splitting the job up
---------------------------

Running ‘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:

     python setup.py build
     python setup.py install

If you do this, you will notice that running the ‘install’ command first
runs the ‘build’ command, which—in this case—quickly notices that it has
nothing to do, since everything in the ‘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.


File: python.info,  Node: How building works,  Next: How installation works,  Prev: Splitting the job up,  Up: Standard Build and Install

18.2.3 How building works
-------------------------

As implied above, the ‘build’ command is responsible for putting the
files to install into a `build directory'.  By default, this is ‘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 ‘--build-base’ option.  For example:

     python setup.py build --build-base=/path/to/pybuild/foo-1.0

(Or you could do this permanently with a directive in your system or
personal Distutils configuration file; see section *note Distutils
Configuration Files: 466c.)  Normally, this isn’t necessary.

The default layout for the build tree is as follows:

     --- build/ --- lib/
     or
     --- build/ --- lib.<plat>/
                    temp.<plat>/

where ‘<plat>’ expands to a brief description of the current OS/hardware
platform and Python version.  The first form, with just a ‘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 ‘<plat>’ directories, is used.  In that case,
the ‘temp.`plat'’ directory holds temporary files generated by the
compile/link process that don’t actually get installed.  In either case,
the ‘lib’ (or ‘lib.`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.


File: python.info,  Node: How installation works,  Prev: How building works,  Up: Standard Build and Install

18.2.4 How installation works
-----------------------------

After the ‘build’ command runs (whether you run it explicitly, or the
‘install’ command does it for you), the work of the ‘install’ command is
relatively simple: all it has to do is copy everything under ‘build/lib’
(or ‘build/lib.`plat'’) to your chosen installation directory.

If you don’t choose an installation directory—i.e., if you just run
‘setup.py install’—then the ‘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"):

平台                  标准安装位置                                              默认值                                                 註解
                                                                                                                                       
---------------------------------------------------------------------------------------------------------------------------------------------------
                                                                                                                                       
（单一）Unix          ‘`prefix'/lib/python`X.Y'/site-packages’                  ‘/usr/local/lib/python`X.Y'/site-packages’             (1)
                                                                                                                                       
                                                                                                                                       
（类）Unix            ‘`exec-prefix'/lib/python`X.Y'/site-packages’             ‘/usr/local/lib/python`X.Y'/site-packages’             (1)
                                                                                                                                       
                                                                                                                                       
Windows               ‘`prefix'\Lib\site-packages’                              ‘C:\Python`XY'\Lib\site-packages’                      (2)
                                                                                                                                       

註解：

  1. Most Linux distributions include Python as a standard part of the
     system, so ‘`prefix'’ and ‘`exec-prefix'’ are usually both ‘/usr’
     on Linux.  If you build Python yourself on Linux (or any Unix-like
     system), the default ‘`prefix'’ and ‘`exec-prefix'’ are
     ‘/usr/local’.

  2. The default installation directory on Windows was ‘C:\Program
     Files\Python’ under Python 1.6a1, 1.5.2, and earlier.

‘`prefix'’ and ‘`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
‘`prefix'’ and ‘`exec-prefix'’ by running Python in interactive mode and
typing a few simple commands.  Under Unix, just type ‘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 ‘`prefix'’ and ‘`exec-prefix'’:

     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'

A few other placeholders are used in this document: ‘`X.Y'’ stands for
the version of Python, for example ‘3.2’; ‘`abiflags'’ will be replaced
by the value of *note sys.abiflags: 38d. or the empty string for
platforms which don’t define ABI flags; ‘`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 ‘python3.2’ on UNIX will typically use ‘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 *note Alternate Installation: 466f.
If you want to customize your installation directories more heavily, see
section *note 自定义安装: 4670. on custom installations.


File: python.info,  Node: Alternate Installation,  Next: 自定义安装,  Prev: Standard Build and Install,  Up: 安裝 Python 模組（舊版）

18.3 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 ‘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
‘install’ command picks a set of directories (called an `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 ‘--user’, or ‘--home’, or ‘--prefix’ and
‘--exec-prefix’, or ‘--install-base’ and ‘--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.


File: python.info,  Node: Alternate installation the user scheme,  Next: Alternate installation the home scheme,  Up: Alternate Installation

18.3.1 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:

     python setup.py install --user

Files will be installed into subdirectories of *note site.USER_BASE:
1489. (written as ‘`userbase'’ hereafter).  This scheme installs pure
Python modules and extension modules in the same location (also known as
*note site.USER_SITE: 147a.).  Here are the values for UNIX, including
macOS:

文件类型            安装目录
                    
------------------------------------------------------------------------------------
                    
模块                ‘`userbase'/lib/python`X.Y'/site-packages’
                    
                    
脚本                ‘`userbase'/bin’
                    
                    
数据                ‘`userbase'’
                    
                    
C 头文件            ‘`userbase'/include/python`X.Y'`abiflags'/`distname'’
                    

以下是Windows上使用的值：

文件类型            安装目录
                    
------------------------------------------------------------------------------------
                    
模块                ‘`userbase'\Python`XY'\site-packages’
                    
                    
脚本                ‘`userbase'\Python`XY'\Scripts’
                    
                    
数据                ‘`userbase'’
                    
                    
C 头文件            ‘`userbase'\Python`XY'\Include{distname}’
                    

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 *note sys.path: 261. (see *note site: eb.
for more information), which means that there is no additional step to
perform after running the ‘setup.py’ script to finalize the
installation.

The ‘build_ext’ command also has a ‘--user’ option to add
‘`userbase'/include’ to the compiler search path for header files and
‘`userbase'/lib’ to the compiler search path for libraries as well as to
the runtime search path for shared C libraries (rpath).


File: python.info,  Node: Alternate installation the home scheme,  Next: Alternate installation Unix the prefix scheme,  Prev: Alternate installation the user scheme,  Up: Alternate Installation

18.3.2 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 ‘/usr/’
or ‘/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

     python setup.py install --home=<dir>

where you can supply any directory you like for the ‘--home’ option.  On
Unix, lazy typists can just type a tilde (‘~’); the ‘install’ command
will expand this to your home directory:

     python setup.py install --home=~

To make Python find the distributions installed with this scheme, you
may have to *note modify Python’s search path: 4675. or edit
‘sitecustomize’ (see *note site: eb.) to call *note site.addsitedir():
38ac. or edit *note sys.path: 261.

The ‘--home’ option defines the installation base directory.  Files are
installed to the following directories under the installation base as
follows:

文件类型            安装目录
                    
------------------------------------------------------------------------------------
                    
模块                ‘`home'/lib/python’
                    
                    
脚本                ‘`home'/bin’
                    
                    
数据                ‘`home'’
                    
                    
C 头文件            ‘`home'/include/python/`distname'’
                    

(Mentally replace slashes with backslashes if you’re on Windows.)


File: python.info,  Node: Alternate installation Unix the prefix scheme,  Next: Alternate installation Windows the prefix scheme,  Prev: Alternate installation the home scheme,  Up: Alternate Installation

18.3.3 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 ‘/usr’,
rather than the more traditional ‘/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 ‘/usr/local/lib/python2.`X'’
rather than ‘/usr/lib/python2.`X'’.  This can be done with

     /usr/bin/python setup.py install --prefix=/usr/local

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 ‘/usr/local/bin/python’
might search for modules in ‘/usr/local/lib/python2.`X'’, but those
modules would have to be installed to, say,
‘/mnt/`@server'/export/lib/python2.`X'’.  This could be done with

     /usr/local/bin/python setup.py install --prefix=/mnt/@server/export

In either case, the ‘--prefix’ option defines the installation base, and
the ‘--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 ‘--exec-prefix’ is not
supplied, it defaults to ‘--prefix’.  Files are installed as follows:

文件类型              安装目录
                      
-------------------------------------------------------------------------------------
                      
Python 模块           ‘`prefix'/lib/python`X.Y'/site-packages’
                      
                      
扩展模块              ‘`exec-prefix'/lib/python`X.Y'/site-packages’
                      
                      
脚本                  ‘`prefix'/bin’
                      
                      
数据                  ‘`prefix'’
                      
                      
C 头文件              ‘`prefix'/include/python`X.Y'`abiflags'/`distname'’
                      

There is no requirement that ‘--prefix’ or ‘--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
‘--prefix’ and ‘--exec-prefix’ supplied by Python itself as ‘sys.prefix’
and ‘sys.exec_prefix’.  Thus, you might think you’ll never use the
prefix scheme, but every time you run ‘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 (‘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 ‘--prefix’ and ‘--exec-prefix’ don’t even point to an alternate
Python installation, this is immaterial.)


File: python.info,  Node: Alternate installation Windows the prefix scheme,  Prev: Alternate installation Unix the prefix scheme,  Up: Alternate Installation

18.3.4 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 ‘--prefix’ option has traditionally been used to install additional
packages in separate locations on Windows.

     python setup.py install --prefix="\Temp\Python"

to install modules to the ‘\Temp\Python’ directory on the current drive.

The installation base is defined by the ‘--prefix’ option; the
‘--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:

文件类型            安装目录
                    
-----------------------------------------------------------------------------------
                    
模块                ‘`prefix'\Lib\site-packages’
                    
                    
脚本                ‘`prefix'\Scripts’
                    
                    
数据                ‘`prefix'’
                    
                    
C 头文件            ‘`prefix'\Include{distname}’
                    


File: python.info,  Node: 自定义安装,  Next: Distutils Configuration Files,  Prev: Alternate Installation,  Up: 安裝 Python 模組（舊版）

18.4 自定义安装
===============

Sometimes, the alternate installation schemes described in section *note
Alternate Installation: 466f. 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 `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:

文件类型                   覆盖选项
                           
-------------------------------------------------------
                           
Python 模块                ‘--install-purelib’
                           
                           
扩展模块                   ‘--install-platlib’
                           
                           
所有模块                   ‘--install-lib’
                           
                           
脚本                       ‘--install-scripts’
                           
                           
数据                       ‘--install-data’
                           
                           
C 头文件                   ‘--install-headers’
                           

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
‘--prefix’ and ‘--exec-prefix’ options; using ‘--install-lib’ will
override values computed or given for ‘--install-purelib’ and
‘--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 ‘~/scripts’ rather
than ‘~/bin’.  As you might expect, you can override this directory with
the ‘--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):

     python setup.py install --home=~ --install-scripts=scripts

Another Unix example: suppose your Python installation was built and
installed with a prefix of ‘/usr/local/python’, so under a standard
installation scripts will wind up in ‘/usr/local/python/bin’.  If you
want them in ‘/usr/local/bin’ instead, you would supply this absolute
directory for the ‘--install-scripts’ option:

     python setup.py install --install-scripts=/usr/local/bin

(This performs an installation using the "prefix scheme", where the
prefix is whatever your Python interpreter was installed with—
‘/usr/local/python’ in this case.)

If you maintain Python on Windows, you might want third-party modules to
live in a subdirectory of ‘`prefix'’, rather than right in ‘`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:

     python setup.py install --install-lib=Site

The specified installation directory is relative to ‘`prefix'’.  Of
course, you also have to ensure that this directory is in Python’s
module search path, such as by putting a ‘.pth’ file in a site directory
(see *note site: eb.).  See section *note Modifying Python’s Search
Path: 4675. 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 ‘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:

     python setup.py install --home=~ \
                             --install-purelib=python/lib \
                             --install-platlib=python/lib.$PLAT \
                             --install-scripts=python/scripts
                             --install-data=python/data

或者，等价于

     python setup.py install --home=~/python \
                             --install-purelib=lib \
                             --install-platlib='lib.$PLAT' \
                             --install-scripts=scripts
                             --install-data=data

‘$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 *note
Distutils Configuration Files: 466c.):

     [install]
     install-base=$HOME
     install-purelib=python/lib
     install-platlib=python/lib.$PLAT
     install-scripts=python/scripts
     install-data=python/data

或者，等价于，

     [install]
     install-base=$HOME/python
     install-purelib=lib
     install-platlib=lib.$PLAT
     install-scripts=scripts
     install-data=data

Note that these two are `not' equivalent if you supply a different
installation base directory when you run the setup script.  For example,

     python setup.py install --install-base=/tmp

would install pure modules to ‘/tmp/python/lib’ in the first case, and
to ‘/tmp/lib’ in the second case.  (For the second case, you probably
want to supply an installation base of ‘/tmp/python’.)

You probably noticed the use of ‘$HOME’ and ‘$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 ‘$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 *note Distutils Configuration Files:
466c. for details.

     備註: When a *note virtual environment: 379e. 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.

* Menu:

* Modifying Python's Search Path::


File: python.info,  Node: Modifying Python's Search Path,  Up: 自定义安装

18.4.1 Modifying Python’s Search Path
-------------------------------------

When the Python interpreter executes an *note import: ce7. 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
*note sys: fd. module and printing the value of ‘sys.path’.

     $ 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
     ['', '/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']
     >>>

The null string in ‘sys.path’ represents the current working directory.

The expected convention for locally installed packages is to put them in
the ‘`...'/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
‘/www’.  Add-on Python modules might then belong in ‘/www/python’, and
in order to import them, this directory must be added to ‘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
‘.../site-packages/’ directory.  Path configuration files have an
extension of ‘.pth’, and each line must contain a single path that will
be appended to ‘sys.path’.  (Because the new paths are appended to
‘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 ‘.pth’ file.  See the documentation of the
*note site: eb. module for more information.

A slightly less convenient way is to edit the ‘site.py’ file in Python’s
standard library, and modify ‘sys.path’.  ‘site.py’ is automatically
imported when the Python interpreter is executed, unless the *note -S:
bf7. switch is supplied to suppress this behaviour.  So you could simply
edit ‘site.py’ and add two lines to it:

     import sys
     sys.path.append('/www/python/')

However, if you reinstall the same major version of Python (perhaps when
upgrading from 2.2 to 2.2.2, for example) ‘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 ‘sys.path’.  *note
PYTHONHOME: 5d0. sets an alternate value for the prefix of the Python
installation.  For example, if *note PYTHONHOME: 5d0. is set to
‘/www/python’, the search path will be set to ‘['',
'/www/python/lib/pythonX.Y/', '/www/python/lib/pythonX.Y/plat-linux2',
...]’.

The *note PYTHONPATH: a34. variable can be set to a list of paths that
will be added to the beginning of ‘sys.path’.  For example, if *note
PYTHONPATH: a34. is set to ‘/www/python:/opt/py’, the search path will
begin with ‘['/www/python', '/opt/py']’.  (Note that directories must
exist in order to be added to ‘sys.path’; the *note site: eb. module
removes paths that don’t exist.)

Finally, ‘sys.path’ is just a regular Python list, so any Python
application can modify it by adding or removing entries.


File: python.info,  Node: Distutils Configuration Files,  Next: Building Extensions Tips and Tricks,  Prev: 自定义安装,  Up: 安裝 Python 模組（舊版）

18.5 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::


File: python.info,  Node: Location and names of config files,  Next: Syntax of config files,  Up: Distutils Configuration Files

18.5.1 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:

文件类型           位置和文件名                                                   註解
                                                                                  
----------------------------------------------------------------------------------------------
                                                                                  
system             ‘`prefix'/lib/python`ver'/distutils/distutils.cfg’             (1)
                                                                                  
                                                                                  
personal           ‘$HOME/.pydistutils.cfg’                                       (2)
                                                                                  
                                                                                  
local              ‘setup.cfg’                                                    (3)
                                                                                  

And on Windows, the configuration files are:

文件类型           位置和文件名                                          註解
                                                                         
-------------------------------------------------------------------------------------
                                                                         
system             ‘`prefix'\Lib\distutils\distutils.cfg’                (4)
                                                                         
                                                                         
personal           ‘%HOME%\pydistutils.cfg’                              (5)
                                                                         
                                                                         
local              ‘setup.cfg’                                           (3)
                                                                         

On all platforms, the "personal" file can be temporarily disabled by
passing the ‘–no-user-cfg’ option.

註解：

  1. 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
     ‘`prefix'/lib/python1.5/site-packages/distutils’, so the system
     configuration file should be put there under Python 1.5.2.

  2. On Unix, if the ‘HOME’ environment variable is not defined, the
     user’s home directory will be determined with the ‘getpwuid()’
     function from the standard *note pwd: d6. module.  This is done by
     the *note os.path.expanduser(): 32c. function used by Distutils.

  3. I.e., in the current directory (usually the location of the setup
     script).

  4. (See also note (1).)  Under Python 1.6 and later, Python’s default
     "installation prefix" is ‘C:\Python’, so the system configuration
     file is normally ‘C:\Python\Lib\distutils\distutils.cfg’.  Under
     Python 1.5.2, the default prefix was ‘C:\Program Files\Python’, and
     the Distutils were not part of the standard library—so the system
     configuration file would be ‘C:\Program
     Files\Python\distutils\distutils.cfg’ in a standard Python 1.5.2
     installation under Windows.

  5. On Windows, if the ‘HOME’ environment variable is not defined,
     ‘USERPROFILE’ then ‘HOMEDRIVE’ and ‘HOMEPATH’ will be tried.  This
     is done by the *note os.path.expanduser(): 32c. function used by
     Distutils.


File: python.info,  Node: Syntax of config files,  Prev: Location and names of config files,  Up: Distutils Configuration Files

18.5.2 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 ‘global’ section for global options that
affect every command.  Each section consists of one option per line,
specified as ‘option=value’.

For example, the following is a complete config file that just forces
all commands to run quietly by default:

     [global]
     verbose=0

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 ‘setup.cfg’ for a particular module
distribution, it affects only that distribution.

You could override the default "build base" directory and make the
‘build*’ commands always forcibly rebuild all files with the following:

     [build]
     build-base=blib
     force=1

which corresponds to the command-line arguments

     python setup.py build --build-base=blib --force

except that including the ‘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
‘--help’ option, e.g.:

     python setup.py build --help

and you can find out the complete list of global options by using
‘--help’ without a command:

     python setup.py --help

See also the "Reference" section of the "Distributing Python Modules"
manual.


File: python.info,  Node: Building Extensions Tips and Tricks,  Prev: Distutils Configuration Files,  Up: 安裝 Python 模組（舊版）

18.6 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
‘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::


File: python.info,  Node: Tweaking compiler/linker flags,  Next: Using non-Microsoft compilers on Windows,  Up: Building Extensions Tips and Tricks

18.6.1 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 ‘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 ‘Setup’ file, if present, is parsed in order to get a list of
extensions to build.  Each line in a ‘Setup’ describes a single module.
Lines have the following structure:

     module ... [sourcefile ...] [cpparg ...] [library ...]

Let’s examine each of the fields in turn.

   * `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.

   * `sourcefile' is anything that’s likely to be a source code file, at
     least judging by the filename.  Filenames ending in ‘.c’ are
     assumed to be written in C, filenames ending in ‘.C’, ‘.cc’, and
     ‘.c++’ are assumed to be C++, and filenames ending in ‘.m’ or ‘.mm’
     are assumed to be in Objective C.

   * `cpparg' is an argument for the C preprocessor, and is anything
     starting with ‘-I’, ‘-D’, ‘-U’ or ‘-C’.

   * `library' is anything ending in ‘.a’ or beginning with ‘-l’ or
     ‘-L’.

If a particular platform requires a special library on your platform,
you can add it by editing the ‘Setup’ file and running ‘python setup.py
build’.  For example, if the module defined by the line

     foo foomodule.c

must be linked with the math library ‘libm.a’ on your platform, simply
add ‘-lm’ to the line:

     foo foomodule.c -lm

Arbitrary switches intended for the compiler or the linker can be
supplied with the ‘-Xcompiler’ `arg' and ‘-Xlinker’ `arg' options:

     foo foomodule.c -Xcompiler -o32 -Xlinker -shared -lm

The next option after ‘-Xcompiler’ and ‘-Xlinker’ will be appended to
the proper command line, so in the above example the compiler will be
passed the ‘-o32’ option, and the linker will be passed ‘-shared’.  If a
compiler option requires an argument, you’ll have to supply multiple
‘-Xcompiler’ options; for example, to pass ‘-x c++’ the ‘Setup’ file
would have to contain ‘-Xcompiler -x -Xcompiler c++’.

Compiler flags can also be supplied through setting the ‘CFLAGS’
environment variable.  If set, the contents of ‘CFLAGS’ will be added to
the compiler flags specified in the ‘Setup’ file.


File: python.info,  Node: Using non-Microsoft compilers on Windows,  Prev: Tweaking compiler/linker flags,  Up: Building Extensions Tips and Tricks

18.6.2 Using non-Microsoft compilers on Windows
-----------------------------------------------

* Menu:

* Borland/CodeGear C++::
* GNU C / Cygwin / MinGW::


File: python.info,  Node: Borland/CodeGear C++,  Next: GNU C / Cygwin / MinGW,  Up: Using non-Microsoft compilers on Windows

18.6.2.1 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 ‘python25.lib’ into the Borland format.  You can do this as
follows:

     coff2omf python25.lib python25_bcpp.lib

The ‘coff2omf’ program comes with the Borland compiler.  The file
‘python25.lib’ is in the ‘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.  ‘foo’) Distutils checks
first if it finds a library with suffix ‘_bcpp’ (eg.  ‘foo_bcpp.lib’)
and then uses this library.  In the case it doesn’t find such a special
library it uses the default name (‘foo.lib’.)  (1)

To let Distutils compile your extension with Borland C++ you now have to
type:

     python setup.py build --compiler=bcpp

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 *note Distutils Configuration Files: 466c.)

也參考
......

C++Builder Compiler(2)

     Information about the free C++ compiler from Borland, including
     links to the download pages.

Creating Python Extensions Using Borland’s Free Compiler(3)

     Document describing how to use Borland’s free command-line C++
     compiler to build Python.

   ---------- Footnotes ----------

   (1) (1) This also means you could replace all existing COFF-libraries
with OMF-libraries of the same name.

   (2) https://www.embarcadero.com/products

   (3) http://www.cyberus.ca/~g_will/pyExtenDL.shtml


File: python.info,  Node: GNU C / Cygwin / MinGW,  Prev: Borland/CodeGear C++,  Up: Using non-Microsoft compilers on Windows

18.6.2.2 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.  (1) 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:

     python setup.py build --compiler=cygwin

and for Cygwin in no-cygwin mode (2) or for MinGW type:

     python setup.py build --compiler=mingw32

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 *note Distutils Configuration Files: 466c.)

* Menu:

* Older Versions of Python and MinGW::

   ---------- Footnotes ----------

   (1) (2) Check ‘https://www.sourceware.org/cygwin/’ for more
information

   (2) (3) Then you have no POSIX emulation available, but you also
don’t need ‘cygwin1.dll’.


File: python.info,  Node: Older Versions of Python and MinGW,  Up: GNU C / Cygwin / MinGW

18.6.2.3 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
‘https://sourceforge.net/projects/mingw/files/MinGW/Extension/pexports/’).

     pexports python25.dll >python25.def

The location of an installed ‘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.

     /cygwin/bin/dlltool --dllname python25.dll --def python25.def --output-lib libpython25.a

The resulting library has to be placed in the same directory as
‘python25.lib’.  (Should be the ‘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.

也參考
......

Building Python modules on MS Windows platform with MinGW(1)

     Information about building the required libraries for the MinGW
     environment.

註解
....

   ---------- Footnotes ----------

   (1) http://old.zope.org/Members/als/tips/win32_mingw_modules


File: python.info,  Node: Python 模組索引,  Next: 索引,  Prev: 安裝 Python 模組（舊版）,  Up: Top

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, Base32, 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, 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, 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, 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, zip files, ...)
* 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, which
                        represents the module distribution being
                        built/installed/distributed
* distutils.errors: 59. Provides standard distutils exceptions
* distutils.extension: 5a. Provides the Extension class, 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, used for poking about the
                        file system and building lists of files.
* distutils.log: 5e. A simple logging mechanism, :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, 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,
                        manipulating, 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, opening, 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, 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,
                        Real, Integral, 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, 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, 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, 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(), os.lstat() and os.fstat().
* statistics: f5. Mathematical statistics functions
* string: f6. Common string operations.
* stringprep: f7. String preparation, 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


File: python.info,  Node: 索引,  Prev: Python 模組索引,  Up: Top

索引
****

[index]
* Menu:

* ! (exclamation); in a command interpreter: Cmd 对象.       (line   23)
* ! (exclamation); in curses module:     curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  213)
* ! (exclamation); in formatted string literal: 字符串字面值合并.
                                                             (line   19)
* ! (exclamation); in glob-style wildcards: glob --- Unix 风格路径名模式扩展.
                                                             (line   10)
* ! (exclamation); in glob-style wildcards <1>: fnmatch --- Unix 文件名模式匹配.
                                                             (line   14)
* ! (exclamation); in string formatting: 格式字符串语法.     (line   11)
* ! (exclamation); in struct format strings: 字节顺序，大小和对齐方式.
                                                             (line    9)
* ! (pdb command):                       调试器命令.         (line  258)
* " (double quote); string literal:      字面值.             (line    8)
* """; string literal:                   字符串与字节串字面值.
                                                             (line   33)
* # (hash); comment:                     一個非正式的 Python 簡介.
                                                             (line   12)
* # (hash); comment <1>:                 注释.               (line    6)
* # (hash); comment <2>:                 site —— 指定域的配置钩子.
                                                             (line   39)
* # (hash); in doctests:                 选项标记.           (line  151)
* # (hash); in printf-style formatting:  printf 风格的字符串格式化.
                                                             (line   53)
* # (hash); in printf-style formatting <1>: printf 风格的字节串格式化.
                                                             (line   52)
* # (hash); in regular expressions:      模块内容.           (line   97)
* # (hash); in string formatting:        格式规格迷你语言.   (line   72)
* # (hash); source encoding declaration: 编码声明.           (line    6)
* $ (dollar); environment variables expansion: os path --- 常用路径操作.
                                                             (line  138)
* $ (dollar); in regular expressions:    正则表达式语法.     (line   46)
* $ (dollar); in template strings:       模板字符串.         (line   11)
* $ (dollar); interpolation in configuration files: 值的插值.
                                                             (line   35)
* % (percent); datetime format:          timezone 对象.      (line   60)
* % (percent); datetime format <1>:      函数<3>.            (line  198)
* % (percent); datetime format <2>:      函数<3>.            (line  315)
* % (percent); environment variables expansion (Windows): os path --- 常用路径操作.
                                                             (line  138)
* % (percent); environment variables expansion (Windows) <1>: 函数<12>.
                                                             (line  212)
* % (percent); interpolation in configuration files: 值的插值.
                                                             (line    9)
* % (percent); printf-style formatting:  printf 风格的字符串格式化.
                                                             (line    6)
* % (percent); printf-style formatting <1>: printf 风格的字节串格式化.
                                                             (line    6)
* %=; augmented assignment:              增强赋值语句.       (line    6)
* &=; augmented assignment:              增强赋值语句.       (line    6)
* ’ (single quote); string literal:      字面值.             (line    8)
* ’’’; string literal:                   字符串与字节串字面值.
                                                             (line   33)
* () (parentheses); call:                切片.               (line   30)
* () (parentheses); class definition:    类定义.             (line    6)
* () (parentheses); function definition: 函数定义.           (line    6)
* () (parentheses); generator expression: 生成器表达式.      (line    6)
* () (parentheses); in assignment target list: 赋值语句.     (line   30)
* () (parentheses); in printf-style formatting: printf 风格的字符串格式化.
                                                             (line   21)
* () (parentheses); in printf-style formatting <1>: printf 风格的字节串格式化.
                                                             (line   20)
* () (parentheses); in regular expressions: 正则表达式语法.  (line  156)
* () (parentheses); tuple display:       带圆括号的形式.     (line    6)
* (?!; in regular expressions:           正则表达式语法.     (line  254)
* (?#; in regular expressions:           正则表达式语法.     (line  244)
* (?; in regular expressions:            正则表达式语法.     (line  163)
* (?;; in regular expressions:           正则表达式语法.     (line  181)
* (?<!; in regular expressions:          正则表达式语法.     (line  284)
* (?<=; in regular expressions:          正则表达式语法.     (line  260)
* (?=; in regular expressions:           正则表达式语法.     (line  248)
* (?P<; in regular expressions:          正则表达式语法.     (line  207)
* (?P=; in regular expressions:          正则表达式语法.     (line  239)
* * (asterisk); function definition:     函数定义.           (line   67)
* * (asterisk); import statement:        import 语句.        (line   68)
* * (asterisk); in argparse module:      nargs.              (line   48)
* * (asterisk); in assignment target list: 赋值语句.         (line   30)
* * (asterisk); in AST grammar:          节点类.             (line   18)
* * (asterisk); in expression lists:     表达式列表.         (line   14)
* * (asterisk); in function calls:       任意引數列表 Arbitrary Argument Lists.
                                                             (line    6)
* * (asterisk); in function calls <1>:   调用.               (line   55)
* * (asterisk); in glob-style wildcards: glob --- Unix 风格路径名模式扩展.
                                                             (line   10)
* * (asterisk); in glob-style wildcards <1>: fnmatch --- Unix 文件名模式匹配.
                                                             (line   14)
* * (asterisk); in printf-style formatting: printf 风格的字符串格式化.
                                                             (line   21)
* * (asterisk); in printf-style formatting <1>: printf 风格的字节串格式化.
                                                             (line   20)
* * (asterisk); in regular expressions:  正则表达式语法.     (line   55)
* **; function definition:               函数定义.           (line   67)
* **; in dictionary displays:            字典显示.           (line   19)
* **; in function calls:                 拆解引數列表（Unpacking Argument Lists）.
                                                             (line   17)
* **; in function calls <1>:             调用.               (line   80)
* **; in glob-style wildcards:           glob --- Unix 风格路径名模式扩展.
                                                             (line   37)
* **=; augmented assignment:             增强赋值语句.       (line    6)
* *=; augmented assignment:              增强赋值语句.       (line    6)
* *?; in regular expressions:            正则表达式语法.     (line   69)
* + (plus); binary operator:             二元算术运算符.     (line   55)
* + (plus); binary operator <1>:         数字类型 --- int float complex.
                                                             (line   20)
* + (plus); in argparse module:          nargs.              (line   58)
* + (plus); in doctests:                 选项标记.           (line  151)
* + (plus); in printf-style formatting:  printf 风格的字符串格式化.
                                                             (line   53)
* + (plus); in printf-style formatting <1>: printf 风格的字节串格式化.
                                                             (line   52)
* + (plus); in regular expressions:      正则表达式语法.     (line   60)
* + (plus); in string formatting:        格式规格迷你语言.   (line   59)
* + (plus); unary operator:              一元算术和位运算.   (line   13)
* + (plus); unary operator <1>:          数字类型 --- int float complex.
                                                             (line   20)
* +=; augmented assignment:              增强赋值语句.       (line    6)
* +?; in regular expressions:            正则表达式语法.     (line   69)
* , (comma):                             带圆括号的形式.     (line   18)
* , (comma); argument list:              切片.               (line   30)
* , (comma); expression list:            列表显示.           (line    6)
* , (comma); expression list <1>:        集合显示.           (line    6)
* , (comma); expression list <2>:        表达式列表.         (line    6)
* , (comma); expression list <3>:        assert 语句.        (line    6)
* , (comma); expression list <4>:        类定义.             (line    6)
* , (comma); identifier list:            global 语句.        (line    6)
* , (comma); identifier list <1>:        nonlocal 语句.      (line    6)
* , (comma); import statement:           import 语句.        (line    6)
* , (comma); in dictionary displays:     字典显示.           (line    6)
* , (comma); in string formatting:       格式规格迷你语言.   (line   80)
* , (comma); in target list:             赋值语句.           (line   30)
* , (comma); parameter list:             函数定义.           (line    6)
* , (comma); slicing:                    切片.               (line    6)
* , (comma); with statement:             with 语句.          (line    6)
* - (minus); binary operator:            二元算术运算符.     (line   62)
* - (minus); binary operator <1>:        数字类型 --- int float complex.
                                                             (line   20)
* - (minus); in doctests:                选项标记.           (line  150)
* - (minus); in glob-style wildcards:    glob --- Unix 风格路径名模式扩展.
                                                             (line   10)
* - (minus); in glob-style wildcards <1>: fnmatch --- Unix 文件名模式匹配.
                                                             (line   14)
* - (minus); in printf-style formatting: printf 风格的字符串格式化.
                                                             (line   53)
* - (minus); in printf-style formatting <1>: printf 风格的字节串格式化.
                                                             (line   52)
* - (minus); in regular expressions:     正则表达式语法.     (line  114)
* - (minus); in string formatting:       格式规格迷你语言.   (line   59)
* - (minus); unary operator:             一元算术和位运算.   (line   10)
* - (minus); unary operator <1>:         数字类型 --- int float complex.
                                                             (line   20)
* -=; augmented assignment:              增强赋值语句.       (line    6)
* ->; function annotations:              函式註釋 Function Annotations.
                                                             (line    6)
* ->; function annotations <1>:          函数定义.           (line   79)
* . (dot); attribute reference:          属性引用.           (line    6)
* . (dot); in glob-style wildcards:      glob --- Unix 风格路径名模式扩展.
                                                             (line   10)
* . (dot); in numeric literal:           整数字面值.         (line   35)
* . (dot); in pathnames:                 其他系统信息.       (line   67)
* . (dot); in pathnames <1>:             其他系统信息.       (line   90)
* . (dot); in printf-style formatting:   printf 风格的字符串格式化.
                                                             (line   21)
* . (dot); in printf-style formatting <1>: printf 风格的字节串格式化.
                                                             (line   20)
* . (dot); in regular expressions:       正则表达式语法.     (line   36)
* . (dot); in string formatting:         格式字符串语法.     (line   11)
* . (dot); in Tkinter:                   Tcl/Tk 速览.        (line   37)
* ...:                                   術語表.             (line    9)
* ...; ellipsis literal:                 标准类型层级结构.   (line   34)
* ...; ellipsis literal <1>:             內建常數.           (line   48)
* ...; ellipsis literal <2>:             空对象.             (line   10)
* ...; in doctests:                      选项标记.           (line   39)
* ...; interpreter prompt:               文档串的例子是如何被识别的？.
                                                             (line   25)
* ...; interpreter prompt <1>:           sys --- 系统相关的参数和函数.
                                                             (line 1026)
* ...; placeholder:                      textwrap --- 文本自动换行与填充.
                                                             (line  242)
* ...; placeholder <1>:                  pprint --- 数据美化输出.
                                                             (line   25)
* ...; placeholder <2>:                  reprlib --- 另一种 repr 实现.
                                                             (line   34)
* ..; in pathnames:                      其他系统信息.       (line   72)
* .ini; file:                            configparser --- 配置文件解析器.
                                                             (line    8)
* .pdbrc; file:                          调试器命令.         (line   27)
* / (slash); function definition:        函数定义.           (line   67)
* / (slash); in pathnames:               其他系统信息.       (line   77)
* / (slash); in pathnames <1>:           其他系统信息.       (line   84)
* //=; augmented assignment:             增强赋值语句.       (line    6)
* /=; augmented assignment:              增强赋值语句.       (line    6)
* 0b; integer literal:                   数值字面值.         (line   12)
* 0o; integer literal:                   数值字面值.         (line   12)
* 0x; integer literal:                   数值字面值.         (line   12)
* 2-digit years:                         time --- 时间的访问和转换.
                                                             (line   28)
* 2to3:                                  術語表.             (line   21)
* ; (colon); annotated variable:         带标注的赋值语句.   (line    6)
* ; (colon); compound statement:         if 语句.            (line    6)
* ; (colon); compound statement <1>:     while 语句.         (line    6)
* ; (colon); compound statement <2>:     for 语句.           (line    6)
* ; (colon); compound statement <3>:     try 语句.           (line    6)
* ; (colon); compound statement <4>:     with 语句.          (line    6)
* ; (colon); compound statement <5>:     函数定义.           (line    6)
* ; (colon); compound statement <6>:     类定义.             (line    6)
* ; (colon); function annotations:       函式註釋 Function Annotations.
                                                             (line    6)
* ; (colon); function annotations <1>:   函数定义.           (line   79)
* ; (colon); in dictionary expressions:  字典显示.           (line    6)
* ; (colon); in formatted string literal: 字符串字面值合并.  (line   19)
* ; (colon); in SQL statements:          Cursor 对象.        (line   10)
* ; (colon); in string formatting:       格式字符串语法.     (line   11)
* ; (colon); lambda expression:          lambda 表达式.      (line    6)
* ; (colon); path separator (POSIX):     其他系统信息.       (line   95)
* ; (colon); slicing:                    切片.               (line    6)
* ; (semicolon):                         复合语句.           (line   15)
* ; (semicolon) <1>:                     其他系统信息.       (line   95)
* < (less); in string formatting:        格式规格迷你语言.   (line   36)
* < (less); in struct format strings:    字节顺序，大小和对齐方式.
                                                             (line    9)
* <<=; augmented assignment:             增强赋值语句.       (line    6)
* <BLANKLINE>:                           选项标记.           (line   25)
* = (equals); assignment statement:      赋值语句.           (line    6)
* = (equals); class definition:          元类.               (line    6)
* = (equals); for help in debugging using string literals: 字符串字面值合并.
                                                             (line   18)
* = (equals); function definition:       函数定义.           (line   48)
* = (equals); in function calls:         切片.               (line   29)
* = (equals); in string formatting:      格式规格迷你语言.   (line   36)
* = (equals); in struct format strings:  字节顺序，大小和对齐方式.
                                                             (line    9)
* > (greater); in string formatting:     格式规格迷你语言.   (line   36)
* > (greater); in struct format strings: 字节顺序，大小和对齐方式.
                                                             (line    9)
* >>=; augmented assignment:             增强赋值语句.       (line    6)
* >>>:                                   術語表.             (line    6)
* >>>; interpreter prompt:               文档串的例子是如何被识别的？.
                                                             (line   25)
* >>>; interpreter prompt <1>:           sys --- 系统相关的参数和函数.
                                                             (line 1026)
* ? (question mark); in a command interpreter: Cmd 对象.     (line   23)
* ? (question mark); in argparse module: nargs.              (line   19)
* ? (question mark); in AST grammar:     节点类.             (line   18)
* ? (question mark); in glob-style wildcards: glob --- Unix 风格路径名模式扩展.
                                                             (line   10)
* ? (question mark); in glob-style wildcards <1>: fnmatch --- Unix 文件名模式匹配.
                                                             (line   14)
* ? (question mark); in regular expressions: 正则表达式语法. (line   65)
* ? (question mark); in SQL statements:  Cursor 对象.        (line   10)
* ? (question mark); in struct format strings: 格式字符.     (line   84)
* ? (question mark); in struct format strings <1>: 格式字符. (line  141)
* ? (question mark); replacement character: 错误处理方案.    (line   25)
* ??; in regular expressions:            正则表达式语法.     (line   69)
* @ (at); class definition:              类定义.             (line   35)
* @ (at); function definition:           函数定义.           (line   29)
* @ (at); in struct format strings:      字节顺序，大小和对齐方式.
                                                             (line    9)
* [] (square brackets); in assignment target list: 赋值语句. (line   30)
* [] (square brackets); in glob-style wildcards: glob --- Unix 风格路径名模式扩展.
                                                             (line   10)
* [] (square brackets); in glob-style wildcards <1>: fnmatch --- Unix 文件名模式匹配.
                                                             (line   14)
* [] (square brackets); in regular expressions: 正则表达式语法.
                                                             (line  107)
* [] (square brackets); in string formatting: 格式字符串语法.
                                                             (line   11)
* [] (square brackets); list expression: 列表显示.           (line    6)
* [] (square brackets); subscription:    抽取.               (line    6)
* \ (backslash); escape sequence:        字符串与字节串字面值.
                                                             (line   59)
* \ (backslash); escape sequence <1>:    错误处理方案.       (line   25)
* \ (backslash); in pathnames (Windows): 其他系统信息.       (line   77)
* \ (backslash); in regular expressions: 正则表达式语法.     (line   96)
* \ (backslash); in regular expressions <1>: 正则表达式语法. (line  123)
* \ (backslash); in regular expressions <2>: 正则表达式语法. (line  302)
* \a; escape sequence:                   字符串与字节串字面值.
                                                             (line   59)
* \A; in regular expressions:            正则表达式语法.     (line  311)
* \a; in regular expressions:            正则表达式语法.     (line  394)
* \b; escape sequence:                   字符串与字节串字面值.
                                                             (line   59)
* \b; in regular expressions:            正则表达式语法.     (line  315)
* \B; in regular expressions:            正则表达式语法.     (line  328)
* \b; in regular expressions <1>:        正则表达式语法.     (line  394)
* \d; in regular expressions:            正则表达式语法.     (line  336)
* \D; in regular expressions:            正则表达式语法.     (line  348)
* \f; escape sequence:                   字符串与字节串字面值.
                                                             (line   59)
* \f; in regular expressions:            正则表达式语法.     (line  394)
* \g; in regular expressions:            模块内容.           (line  236)
* \n; escape sequence:                   字符串与字节串字面值.
                                                             (line   59)
* \N; escape sequence:                   字符串与字节串字面值.
                                                             (line   59)
* \N; escape sequence <1>:               错误处理方案.       (line   25)
* \n; in regular expressions:            正则表达式语法.     (line  394)
* \N; in regular expressions:            正则表达式语法.     (line  394)
* \r; escape sequence:                   字符串与字节串字面值.
                                                             (line   59)
* \r; in regular expressions:            正则表达式语法.     (line  394)
* \s; in regular expressions:            正则表达式语法.     (line  353)
* \S; in regular expressions:            正则表达式语法.     (line  365)
* \t; escape sequence:                   字符串与字节串字面值.
                                                             (line   59)
* \t; in regular expressions:            正则表达式语法.     (line  394)
* \u; escape sequence:                   字符串与字节串字面值.
                                                             (line   59)
* \U; escape sequence:                   字符串与字节串字面值.
                                                             (line   59)
* \u; escape sequence <1>:               错误处理方案.       (line   25)
* \U; escape sequence <1>:               错误处理方案.       (line   25)
* \u; in regular expressions:            正则表达式语法.     (line  394)
* \U; in regular expressions:            正则表达式语法.     (line  394)
* \v; escape sequence:                   字符串与字节串字面值.
                                                             (line   59)
* \v; in regular expressions:            正则表达式语法.     (line  394)
* \w; in regular expressions:            正则表达式语法.     (line  370)
* \W; in regular expressions:            正则表达式语法.     (line  384)
* \x; escape sequence:                   字符串与字节串字面值.
                                                             (line   59)
* \x; escape sequence <1>:               错误处理方案.       (line   25)
* \x; in regular expressions:            正则表达式语法.     (line  394)
* \Z; in regular expressions:            正则表达式语法.     (line  390)
* \\; escape sequence:                   字符串与字节串字面值.
                                                             (line   59)
* \\; in regular expressions:            正则表达式语法.     (line  394)
* ^ (caret); in curses module:           curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  213)
* ^ (caret); in regular expressions:     正则表达式语法.     (line   41)
* ^ (caret); in regular expressions <1>: 正则表达式语法.     (line  127)
* ^ (caret); in string formatting:       格式规格迷你语言.   (line   36)
* ^ (caret); marker:                     异常如何处理？.     (line   78)
* ^ (caret); marker <1>:                 traceback --- 打印或检索堆栈回溯.
                                                             (line   43)
* ^=; augmented assignment:              增强赋值语句.       (line    6)
* _ (underscore); gettext:               GNU gettext API.    (line   37)
* _ (underscore); in numeric literal:    数值字面值.         (line   11)
* _ (underscore); in numeric literal <1>: 整数字面值.        (line   34)
* _ (underscore); in string formatting:  格式规格迷你语言.   (line   85)
* _, identifiers:                        关键字.             (line   17)
* _anonymous_ (ctypes.Structure 的屬性): 结构化数据类型.     (line   65)
* _asdict() (collections.somenamedtuple 的方法): namedtuple 命名元组的工厂函数.
                                                             (line   92)
* _b_base_ (ctypes._CData 的屬性):       数据类型<2>.        (line   62)
* _b_needsfree_ (ctypes._CData 的屬性):  数据类型<2>.        (line   68)
* _callmethod() (multiprocessing.managers.BaseProxy 的方法): 代理对象.
                                                             (line   86)
* _CData (ctypes 中的類別):              数据类型<2>.        (line    6)
* _clear_type_cache() (於 sys 模組中):   sys --- 系统相关的参数和函数.
                                                             (line  132)
* _current_frames() (於 sys 模組中):     sys --- 系统相关的参数和函数.
                                                             (line  139)
* _debugmallocstats() (於 sys 模組中):   sys --- 系统相关的参数和函数.
                                                             (line  183)
* _enablelegacywindowsfsencoding() (於 sys 模組中): sys --- 系统相关的参数和函数.
                                                             (line 1229)
* _exit() (於 os 模組中):                进程管理.           (line   97)
* _fields (ast.AST 的屬性):              节点类.             (line   18)
* _fields (collections.somenamedtuple 的屬性): namedtuple 命名元组的工厂函数.
                                                             (line  119)
* _fields_ (ctypes.Structure 的屬性):    结构化数据类型.     (line   30)
* _field_defaults (collections.somenamedtuple 的屬性): namedtuple 命名元组的工厂函数.
                                                             (line  132)
* _flush() (wsgiref.handlers.BaseHandler 的方法): wsgiref handlers -- 服务器/网关基类.
                                                             (line   95)
* _frozen (C 型態):                      匯入模組<2>.        (line  245)
* _FuncPtr (ctypes 中的類別):            外部函数.           (line   10)
* _getframe() (於 sys 模組中):           sys --- 系统相关的参数和函数.
                                                             (line  609)
* _getvalue() (multiprocessing.managers.BaseProxy 的方法): 代理对象.
                                                             (line  123)
* _get_child_mock() (unittest.mock.Mock 的方法): Mock 类.    (line  267)
* _handle (ctypes.PyDLL 的屬性):         加载动态链接库.     (line  118)
* _inittab (C 型態):                     匯入模組<2>.        (line  275)
* _length_ (ctypes.Array 的屬性):        数组与指针.         (line   16)
* _make() (collections.somenamedtuple 的類別成員): namedtuple 命名元组的工厂函数.
                                                             (line   84)
* _makeResult() (unittest.TextTestRunner 的方法): Loading and running tests.
                                                             (line  464)
* _name (ctypes.PyDLL 的屬性):           加载动态链接库.     (line  122)
* _objects (ctypes._CData 的屬性):       数据类型<2>.        (line   73)
* _pack_ (ctypes.Structure 的屬性):      结构化数据类型.     (line   59)
* _parse() (gettext.NullTranslations 的方法): NullTranslations 类.
                                                             (line   18)
* _Pointer (ctypes 中的類別):            数组与指针.         (line   27)
* _PyBytes_Resize (C 函式):              字节对象.           (line  157)
* _PyCFunctionFast (C 型態):             Implementing functions and methods.
                                                             (line   30)
* _PyCFunctionFastWithKeywords (C 型態): Implementing functions and methods.
                                                             (line   39)
* _PyFrameEvalFunction (C 型態):         Low-level API.      (line  132)
* _PyInterpreterState_GetEvalFrameFunc (C 函式): Low-level API.
                                                             (line  143)
* _PyInterpreterState_SetEvalFrameFunc (C 函式): Low-level API.
                                                             (line  153)
* _PyObject_New (C 函式):                在堆中分配对象.     (line    6)
* _PyObject_NewVar (C 函式):             在堆中分配对象.     (line    9)
* _PyTuple_Resize (C 函式):              元組（Tuple）物件.  (line   81)
* _Py_c_diff (C 函式):                   表示复数的C结构体.  (line   23)
* _Py_c_neg (C 函式):                    表示复数的C结构体.  (line   27)
* _Py_c_pow (C 函式):                    表示复数的C结构体.  (line   42)
* _Py_c_prod (C 函式):                   表示复数的C结构体.  (line   31)
* _Py_c_quot (C 函式):                   表示复数的C结构体.  (line   35)
* _Py_c_sum (C 函式):                    表示复数的C结构体.  (line   19)
* _Py_InitializeMain (C 函式):           Multi-Phase Initialization Private Provisional API.
                                                             (line   47)
* _Py_NoneStruct (C 變數):               在堆中分配对象.     (line   49)
* _replace() (collections.somenamedtuple 的方法): namedtuple 命名元组的工厂函数.
                                                             (line  108)
* _setroot() (xml.etree.ElementTree.ElementTree 的方法): ElementTree 对象.
                                                             (line   14)
* _SimpleCData (ctypes 中的類別):        基础数据类型<2>.    (line    6)
* _structure() (於 email.iterators 模組中): email iterators 迭代器.
                                                             (line   37)
* _thread (模組):                        _thread --- 底层多线程 API.
                                                             (line    6)
* _type_ (ctypes.Array 的屬性):          数组与指针.         (line   21)
* _type_ (ctypes._Pointer 的屬性):       数组与指针.         (line   39)
* _write() (wsgiref.handlers.BaseHandler 的方法): wsgiref handlers -- 服务器/网关基类.
                                                             (line   89)
* _xoptions (於 sys 模組中):             sys --- 系统相关的参数和函数.
                                                             (line 1425)
* __, identifiers:                       关键字.             (line   16)
* __abs__() (object 的方法):             模拟数字类型.       (line   95)
* __abs__() (於 operator 模組中):        operator --- 标准运算符替代函数.
                                                             (line   62)
* __add__() (object 的方法):             模拟数字类型.       (line    9)
* __add__() (於 operator 模組中):        operator --- 标准运算符替代函数.
                                                             (line   67)
* __aenter__() (object 的方法):          异步上下文管理器.   (line   11)
* __aexit__() (object 的方法):           异步上下文管理器.   (line   16)
* __aiter__() (object 的方法):           异步迭代器.         (line   10)
* __all__:                               從套件中 import *.  (line    6)
* __all__ (optional module attribute):   import 语句.        (line   71)
* __all__ (package variable):            匯入模組<2>.        (line    7)
* __and__() (object 的方法):             模拟数字类型.       (line    9)
* __and__() (於 operator 模組中):        operator --- 标准运算符替代函数.
                                                             (line   72)
* __anext__() (agen 的方法):             异步生成器-迭代器方法.
                                                             (line    9)
* __anext__() (object 的方法):           异步迭代器.         (line   14)
* __annotations__ (class attribute):     标准类型层级结构.   (line  454)
* __annotations__ (function attribute):  标准类型层级结构.   (line  239)
* __annotations__ (module attribute):    标准类型层级结构.   (line  418)
* __args__ (genericalias 的屬性):        泛型的特殊属性.     (line   15)
* __await__() (object 的方法):           可等待对象.         (line   15)
* __bases__ (class attribute):           标准类型层级结构.   (line  454)
* __bases__ (class 的屬性):              特殊属性.           (line   17)
* __bool__() (object method):            模拟容器类型.       (line   40)
* __bool__() (object 的方法):            基本定制.           (line  245)
* __breakpointhook__ (於 sys 模組中):    sys --- 系统相关的参数和函数.
                                                             (line  280)
* __bytes__() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  100)
* __bytes__() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  113)
* __bytes__() (object 的方法):           基本定制.           (line  118)
* __cached__:                            导入相关的模块属性. (line   59)
* __callback__ (weakref.ref 的屬性):     weakref --- 弱引用. (line   96)
* __call__() (email.headerregistry.HeaderRegistry 的方法): email headerregistry 自定义标头对象.
                                                             (line  333)
* __call__() (object method):            调用.               (line  119)
* __call__() (object 的方法):            模拟可调用对象.     (line    6)
* __call__() (weakref.finalize 的方法):  weakref --- 弱引用. (line  209)
* __cause__ (exception attribute):       raise 语句.         (line   25)
* __cause__ (traceback.TracebackException 的屬性): TracebackException Objects.
                                                             (line   21)
* __ceil__() (fractions.Fraction 的方法): fractions --- 分数.
                                                             (line  145)
* __ceil__() (object 的方法):            模拟数字类型.       (line  121)
* __classcell__ (class namespace entry): 创建类对象.         (line    6)
* __class_getitem__() (object 的類別成員): 模拟泛型类型.     (line   32)
* __class__ (instance attribute):        标准类型层级结构.   (line  487)
* __class__ (instance 的屬性):           特殊属性.           (line   13)
* __class__ (method cell):               创建类对象.         (line    6)
* __class__ (module attribute):          自定义模块属性访问. (line    6)
* __class__ (unittest.mock.Mock 的屬性): Mock 类.            (line  518)
* __closure__ (function attribute):      标准类型层级结构.   (line  239)
* __code__ (function attribute):         标准类型层级结构.   (line  239)
* __code__ (function object attribute):  代码对象.           (line    6)
* __complex__() (object 的方法):         模拟数字类型.       (line  102)
* __concat__() (於 operator 模組中):     operator --- 标准运算符替代函数.
                                                             (line  158)
* __contains__() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  143)
* __contains__() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  247)
* __contains__() (mailbox.Mailbox 的方法): Mailbox 对象.     (line  157)
* __contains__() (object 的方法):        模拟容器类型.       (line  137)
* __contains__() (於 operator 模組中):   operator --- 标准运算符替代函数.
                                                             (line  163)
* __context__ (exception attribute):     raise 语句.         (line   25)
* __context__ (traceback.TracebackException 的屬性): TracebackException Objects.
                                                             (line   25)
* __copy__() (copy protocol):            copy --- 浅层 shallow 和深层 deep 复制操作.
                                                             (line   63)
* __debug__:                             assert 语句.        (line   20)
* __debug__ (內建變數):                  內建常數.           (line   53)
* __deepcopy__() (copy protocol):        copy --- 浅层 shallow 和深层 deep 复制操作.
                                                             (line   63)
* __defaults__ (function attribute):     标准类型层级结构.   (line  239)
* __delattr__() (object 的方法):         自定义属性访问.     (line   55)
* __delete__() (object 的方法):          实现描述器.         (line   34)
* __delitem__() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  183)
* __delitem__() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  278)
* __delitem__() (mailbox.Mailbox 的方法): Mailbox 对象.      (line   58)
* __delitem__() (mailbox.MH 的方法):     MH.                 (line   68)
* __delitem__() (object 的方法):         模拟容器类型.       (line  100)
* __delitem__() (於 operator 模組中):    operator --- 标准运算符替代函数.
                                                             (line  172)
* __del__() (io.IOBase 的方法):          I/O 基类.           (line  139)
* __del__() (object 的方法):             基本定制.           (line   44)
* __dict__ (class attribute):            标准类型层级结构.   (line  454)
* __dict__ (function attribute):         标准类型层级结构.   (line  239)
* __dict__ (instance attribute):         标准类型层级结构.   (line  487)
* __dict__ (module attribute):           标准类型层级结构.   (line  426)
* __dict__ (module attribute) <1>:       模組物件模組.       (line   42)
* __dict__ (object 的屬性):              特殊属性.           (line    9)
* __dir__ (module attribute):            自定义模块属性访问. (line    6)
* __dir__() (object 的方法):             自定义属性访问.     (line   63)
* __dir__() (unittest.mock.Mock 的方法): Mock 类.            (line  258)
* __displayhook__ (於 sys 模組中):       sys --- 系统相关的参数和函数.
                                                             (line  280)
* __divmod__() (object 的方法):          模拟数字类型.       (line    9)
* __doc__ (class attribute):             标准类型层级结构.   (line  454)
* __doc__ (function attribute):          标准类型层级结构.   (line  239)
* __doc__ (method attribute):            标准类型层级结构.   (line  306)
* __doc__ (module attribute):            标准类型层级结构.   (line  418)
* __doc__ (module attribute) <1>:        模組物件模組.       (line   23)
* __doc__ (types.ModuleType 的屬性):     标准解释器类型.     (line  112)
* __enter__() (contextmanager 的方法):   上下文管理器类型.   (line   10)
* __enter__() (object 的方法):           with 语句上下文管理器.
                                                             (line   16)
* __enter__() (winreg.PyHKEY 的方法):    注册表句柄对象.     (line   47)
* __eq__() (email.charset.Charset 的方法): email charset 表示字符集.
                                                             (line  134)
* __eq__() (email.header.Header 的方法): email header 国际化标头.
                                                             (line  134)
* __eq__() (instance method):            比较.               (line   46)
* __eq__() (memoryview 的方法):          内存视图.           (line   98)
* __eq__() (object 的方法):              基本定制.           (line  142)
* __eq__() (於 operator 模組中):         operator --- 标准运算符替代函数.
                                                             (line   19)
* __excepthook__ (於 sys 模組中):        sys --- 系统相关的参数和函数.
                                                             (line  280)
* __exit__() (contextmanager 的方法):    上下文管理器类型.   (line   26)
* __exit__() (object 的方法):            with 语句上下文管理器.
                                                             (line   21)
* __exit__() (winreg.PyHKEY 的方法):     注册表句柄对象.     (line   47)
* __file__:                              导入相关的模块属性. (line   57)
* __file__ (module attribute):           标准类型层级结构.   (line  418)
* __file__ (module attribute) <1>:       模組物件模組.       (line   23)
* __file__ (module attribute) <2>:       模組物件模組.       (line   81)
* __float__() (object 的方法):           模拟数字类型.       (line  102)
* __floordiv__() (object 的方法):        模拟数字类型.       (line    9)
* __floordiv__() (於 operator 模組中):   operator --- 标准运算符替代函数.
                                                             (line   77)
* __floor__() (fractions.Fraction 的方法): fractions --- 分数.
                                                             (line  136)
* __floor__() (object 的方法):           模拟数字类型.       (line  121)
* __format__:                            內建函式.           (line  540)
* __format__() (datetime.date 的方法):   date 对象.          (line  256)
* __format__() (datetime.datetime 的方法): datetime 对象.    (line  638)
* __format__() (datetime.time 的方法):   time 对象.          (line  194)
* __format__() (ipaddress.IPv4Address 的方法): 地址对象.     (line  125)
* __format__() (ipaddress.IPv6Address 的方法): 地址对象.     (line  249)
* __format__() (object 的方法):          基本定制.           (line  123)
* __fspath__() (os.PathLike 的方法):     进程参数.           (line  111)
* __func__ (method attribute):           标准类型层级结构.   (line  306)
* __future__:                            術語表.             (line  426)
* __future__ (模組):                     __future__ --- Future 语句定义.
                                                             (line    6)
* __future__; future statement:          future 语句.        (line    6)
* __getattribute__() (object 的方法):    自定义属性访问.     (line   27)
* __getattr__ (module attribute):        自定义模块属性访问. (line    6)
* __getattr__() (object 的方法):         自定义属性访问.     (line    9)
* __getitem__() (email.headerregistry.HeaderRegistry 的方法): email headerregistry 自定义标头对象.
                                                             (line  329)
* __getitem__() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  152)
* __getitem__() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  256)
* __getitem__() (mailbox.Mailbox 的方法): Mailbox 对象.      (line  113)
* __getitem__() (mapping object method): 特殊方法名称.       (line    6)
* __getitem__() (object 的方法):         模拟容器类型.       (line   71)
* __getitem__() (re.Match 的方法):       匹配对象.           (line   69)
* __getitem__() (於 operator 模組中):    operator --- 标准运算符替代函数.
                                                             (line  177)
* __getnewargs_ex__() (object 的方法):   封存类实例.         (line   24)
* __getnewargs__() (object 的方法):      封存类实例.         (line   39)
* __getstate__() (copy protocol):        处理有状态的对象.   (line    6)
* __getstate__() (object 的方法):        封存类实例.         (line   52)
* __get__() (object 的方法):             实现描述器.         (line   11)
* __ge__() (instance method):            比较.               (line   46)
* __ge__() (object 的方法):              基本定制.           (line  142)
* __ge__() (於 operator 模組中):         operator --- 标准运算符替代函数.
                                                             (line   19)
* __globals__ (function attribute):      标准类型层级结构.   (line  239)
* __gt__() (instance method):            比较.               (line   46)
* __gt__() (object 的方法):              基本定制.           (line  142)
* __gt__() (於 operator 模組中):         operator --- 标准运算符替代函数.
                                                             (line   19)
* __hash__() (object 的方法):            基本定制.           (line  179)
* __iadd__() (object 的方法):            模拟数字类型.       (line   66)
* __iadd__() (於 operator 模組中):       原地运算符.         (line   33)
* __iand__() (object 的方法):            模拟数字类型.       (line   66)
* __iand__() (於 operator 模組中):       原地运算符.         (line   38)
* __iconcat__() (於 operator 模組中):    原地运算符.         (line   43)
* __ifloordiv__() (object 的方法):       模拟数字类型.       (line   66)
* __ifloordiv__() (於 operator 模組中):  原地运算符.         (line   48)
* __ilshift__() (object 的方法):         模拟数字类型.       (line   66)
* __ilshift__() (於 operator 模組中):    原地运算符.         (line   53)
* __imatmul__() (object 的方法):         模拟数字类型.       (line   66)
* __imatmul__() (於 operator 模組中):    原地运算符.         (line   68)
* __imod__() (object 的方法):            模拟数字类型.       (line   66)
* __imod__() (於 operator 模組中):       原地运算符.         (line   58)
* __import__() (內建函式):               內建函式.           (line 1528)
* __import__() (於 importlib 模組中):    函数<11>.           (line    6)
* __imul__() (object 的方法):            模拟数字类型.       (line   66)
* __imul__() (於 operator 模組中):       原地运算符.         (line   63)
* __index__() (object 的方法):           模拟数字类型.       (line  109)
* __index__() (於 operator 模組中):      operator --- 标准运算符替代函数.
                                                             (line   82)
* __init_subclass__() (object 的類別成員): 自定义类创建.     (line   13)
* __init__() (difflib.HtmlDiff 的方法):  difflib --- 计算差异的辅助工具.
                                                             (line   74)
* __init__() (logging.Handler 的方法):   处理器对象.         (line   12)
* __init__() (logging.logging.Formatter 的方法): 格式器.     (line   11)
* __init__() (object 的方法):            基本定制.           (line   31)
* __instancecheck__() (class 的方法):    自定义实例及子类检查.
                                                             (line   13)
* __interactivehook__ (於 sys 模組中):   sys --- 系统相关的参数和函数.
                                                             (line  808)
* __int__() (object 的方法):             模拟数字类型.       (line  102)
* __invert__() (object 的方法):          模拟数字类型.       (line   95)
* __invert__() (於 operator 模組中):     operator --- 标准运算符替代函数.
                                                             (line   87)
* __inv__() (於 operator 模組中):        operator --- 标准运算符替代函数.
                                                             (line   87)
* __ior__() (object 的方法):             模拟数字类型.       (line   66)
* __ior__() (於 operator 模組中):        原地运算符.         (line   75)
* __ipow__() (object 的方法):            模拟数字类型.       (line   66)
* __ipow__() (於 operator 模組中):       原地运算符.         (line   80)
* __irshift__() (object 的方法):         模拟数字类型.       (line   66)
* __irshift__() (於 operator 模組中):    原地运算符.         (line   85)
* __isub__() (object 的方法):            模拟数字类型.       (line   66)
* __isub__() (於 operator 模組中):       原地运算符.         (line   90)
* __iter__() (container 的方法):         迭代器类型.         (line   12)
* __iter__() (iterator 的方法):          迭代器类型.         (line   22)
* __iter__() (mailbox.Mailbox 的方法):   Mailbox 对象.       (line   89)
* __iter__() (object 的方法):            模拟容器类型.       (line  112)
* __iter__() (unittest.TestSuite 的方法): Grouping tests.    (line   60)
* __itruediv__() (object 的方法):        模拟数字类型.       (line   66)
* __itruediv__() (於 operator 模組中):   原地运算符.         (line   95)
* __ixor__() (object 的方法):            模拟数字类型.       (line   66)
* __ixor__() (於 operator 模組中):       原地运算符.         (line  100)
* __kwdefaults__ (function attribute):   标准类型层级结构.   (line  239)
* __length_hint__() (object 的方法):     模拟容器类型.       (line   51)
* __len__() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  139)
* __len__() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  243)
* __len__() (mailbox.Mailbox 的方法):    Mailbox 对象.       (line  161)
* __len__() (mapping object method):     基本定制.           (line  247)
* __len__() (object 的方法):             模拟容器类型.       (line   38)
* __le__() (instance method):            比较.               (line   46)
* __le__() (object 的方法):              基本定制.           (line  142)
* __le__() (於 operator 模組中):         operator --- 标准运算符替代函数.
                                                             (line   19)
* __loader__:                            导入相关的模块属性. (line   14)
* __loader__ (module attribute):         模組物件模組.       (line   23)
* __loader__ (types.ModuleType 的屬性):  标准解释器类型.     (line  116)
* __lshift__() (object 的方法):          模拟数字类型.       (line    9)
* __lshift__() (於 operator 模組中):     operator --- 标准运算符替代函数.
                                                             (line   94)
* __lt__() (instance method):            比较.               (line   46)
* __lt__() (object 的方法):              基本定制.           (line  142)
* __lt__() (於 operator 模組中):         operator --- 标准运算符替代函数.
                                                             (line   19)
* __main__ (模組):                       __main__ --- 顶层脚本环境.
                                                             (line    6)
* __matmul__() (object 的方法):          模拟数字类型.       (line    9)
* __matmul__() (於 operator 模組中):     operator --- 标准运算符替代函数.
                                                             (line  109)
* __missing__():                         映射类型 --- dict.  (line   81)
* __missing__() (collections.defaultdict 的方法): defaultdict 对象.
                                                             (line   19)
* __missing__() (object 的方法):         模拟容器类型.       (line  107)
* __module__ (class attribute):          标准类型层级结构.   (line  454)
* __module__ (function attribute):       标准类型层级结构.   (line  239)
* __module__ (method attribute):         标准类型层级结构.   (line  306)
* __mod__() (object 的方法):             模拟数字类型.       (line    9)
* __mod__() (於 operator 模組中):        operator --- 标准运算符替代函数.
                                                             (line   99)
* __mro__ (class 的屬性):                特殊属性.           (line   31)
* __mul__() (object 的方法):             模拟数字类型.       (line    9)
* __mul__() (於 operator 模組中):        operator --- 标准运算符替代函数.
                                                             (line  104)
* __name__:                              导入相关的模块属性. (line    9)
* __name__ (class attribute):            标准类型层级结构.   (line  454)
* __name__ (definition 的屬性):          特殊属性.           (line   21)
* __name__ (function attribute):         标准类型层级结构.   (line  239)
* __name__ (method attribute):           标准类型层级结构.   (line  306)
* __name__ (module attribute):           标准类型层级结构.   (line  418)
* __name__ (module attribute) <1>:       模組物件模組.       (line   23)
* __name__ (module attribute) <2>:       模組物件模組.       (line   55)
* __name__ (types.ModuleType 的屬性):    标准解释器类型.     (line  131)
* __neg__() (object 的方法):             模拟数字类型.       (line   95)
* __neg__() (於 operator 模組中):        operator --- 标准运算符替代函数.
                                                             (line  116)
* __new__() (object 的方法):             基本定制.           (line    6)
* __next__() (csv.csvreader 的方法):     Reader 对象.        (line    9)
* __next__() (generator 的方法):         生成器-迭代器的方法.
                                                             (line   11)
* __next__() (iterator 的方法):          迭代器类型.         (line   28)
* __ne__() (email.charset.Charset 的方法): email charset 表示字符集.
                                                             (line  138)
* __ne__() (email.header.Header 的方法): email header 国际化标头.
                                                             (line  138)
* __ne__() (instance method):            比较.               (line   46)
* __ne__() (object 的方法):              基本定制.           (line  142)
* __ne__() (於 operator 模組中):         operator --- 标准运算符替代函数.
                                                             (line   19)
* __not__() (於 operator 模組中):        operator --- 标准运算符替代函数.
                                                             (line   40)
* __origin__ (genericalias 的屬性):      泛型的特殊属性.     (line    8)
* __or__() (object 的方法):              模拟数字类型.       (line    9)
* __or__() (於 operator 模組中):         operator --- 标准运算符替代函数.
                                                             (line  121)
* __package__:                           导入相关的模块属性. (line   20)
* __package__ (module attribute):        模組物件模組.       (line   23)
* __package__ (types.ModuleType 的屬性): 标准解释器类型.     (line  136)
* __parameters__ (genericalias 的屬性):  泛型的特殊属性.     (line   23)
* __path__:                              导入相关的模块属性. (line   47)
* __pos__() (object 的方法):             模拟数字类型.       (line   95)
* __pos__() (於 operator 模組中):        operator --- 标准运算符替代函数.
                                                             (line  126)
* __pow__() (object 的方法):             模拟数字类型.       (line    9)
* __pow__() (於 operator 模組中):        operator --- 标准运算符替代函数.
                                                             (line  131)
* __prepare__ (metaclass method):        准备类命名空间.     (line    6)
* __qualname__ (definition 的屬性):      特殊属性.           (line   25)
* __radd__() (object 的方法):            模拟数字类型.       (line   36)
* __rand__() (object 的方法):            模拟数字类型.       (line   36)
* __rdivmod__() (object 的方法):         模拟数字类型.       (line   36)
* __reduce_ex__() (object 的方法):       封存类实例.         (line  130)
* __reduce__() (object 的方法):          封存类实例.         (line   88)
* __repr__() (multiprocessing.managers.BaseProxy 的方法): 代理对象.
                                                             (line  129)
* __repr__() (netrc.netrc 的方法):       netrc 对象.         (line   15)
* __repr__() (object 的方法):            基本定制.           (line   92)
* __reversed__() (object 的方法):        模拟容器类型.       (line  121)
* __rfloordiv__() (object 的方法):       模拟数字类型.       (line   36)
* __rlshift__() (object 的方法):         模拟数字类型.       (line   36)
* __rmatmul__() (object 的方法):         模拟数字类型.       (line   36)
* __rmod__() (object 的方法):            模拟数字类型.       (line   36)
* __rmul__() (object 的方法):            模拟数字类型.       (line   36)
* __ror__() (object 的方法):             模拟数字类型.       (line   36)
* __round__() (fractions.Fraction 的方法): fractions --- 分数.
                                                             (line  150)
* __round__() (object 的方法):           模拟数字类型.       (line  121)
* __rpow__() (object 的方法):            模拟数字类型.       (line   36)
* __rrshift__() (object 的方法):         模拟数字类型.       (line   36)
* __rshift__() (object 的方法):          模拟数字类型.       (line    9)
* __rshift__() (於 operator 模組中):     operator --- 标准运算符替代函数.
                                                             (line  136)
* __rsub__() (object 的方法):            模拟数字类型.       (line   36)
* __rtruediv__() (object 的方法):        模拟数字类型.       (line   36)
* __rxor__() (object 的方法):            模拟数字类型.       (line   36)
* __self__ (method attribute):           标准类型层级结构.   (line  306)
* __setattr__() (object 的方法):         自定义属性访问.     (line   44)
* __setitem__() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  164)
* __setitem__() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  266)
* __setitem__() (mailbox.Mailbox 的方法): Mailbox 对象.      (line   70)
* __setitem__() (mailbox.Maildir 的方法): Maildir.           (line   77)
* __setitem__() (object 的方法):         模拟容器类型.       (line   93)
* __setitem__() (於 operator 模組中):    operator --- 标准运算符替代函数.
                                                             (line  186)
* __setstate__() (copy protocol):        处理有状态的对象.   (line    6)
* __setstate__() (object 的方法):        封存类实例.         (line   59)
* __set_name__() (object 的方法):        实现描述器.         (line   38)
* __set__() (object 的方法):             实现描述器.         (line   25)
* __slots__:                             術語表.             (line 1016)
* __spec__:                              导入相关的模块属性. (line   33)
* __spec__ (types.ModuleType 的屬性):    标准解释器类型.     (line  154)
* __stderr__ (於 sys 模組中):            sys --- 系统相关的参数和函数.
                                                             (line 1293)
* __stdin__ (於 sys 模組中):             sys --- 系统相关的参数和函数.
                                                             (line 1293)
* __stdout__ (於 sys 模組中):            sys --- 系统相关的参数和函数.
                                                             (line 1293)
* __str__() (datetime.date 的方法):      date 对象.          (line  231)
* __str__() (datetime.datetime 的方法):  datetime 对象.      (line  610)
* __str__() (datetime.time 的方法):      time 对象.          (line  185)
* __str__() (email.charset.Charset 的方法): email charset 表示字符集.
                                                             (line  129)
* __str__() (email.header.Header 的方法): email header 国际化标头.
                                                             (line  125)
* __str__() (email.headerregistry.Address 的方法): email headerregistry 自定义标头对象.
                                                             (line  381)
* __str__() (email.headerregistry.Group 的方法): email headerregistry 自定义标头对象.
                                                             (line  410)
* __str__() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line   74)
* __str__() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line   81)
* __str__() (multiprocessing.managers.BaseProxy 的方法): 代理对象.
                                                             (line  133)
* __str__() (object 的方法):             基本定制.           (line  105)
* __subclasscheck__() (class 的方法):    自定义实例及子类检查.
                                                             (line   18)
* __subclasses__() (class 的方法):       特殊属性.           (line   40)
* __subclasshook__() (abc.ABCMeta 的方法): abc --- 抽象基类. (line   79)
* __sub__() (object 的方法):             模拟数字类型.       (line    9)
* __sub__() (於 operator 模組中):        operator --- 标准运算符替代函数.
                                                             (line  141)
* __suppress_context__ (traceback.TracebackException 的屬性): TracebackException Objects.
                                                             (line   30)
* __traceback__ (exception attribute):   raise 语句.         (line    6)
* __truediv__() (importlib.abc.Traversable 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  551)
* __truediv__() (object 的方法):         模拟数字类型.       (line    9)
* __truediv__() (於 operator 模組中):    operator --- 标准运算符替代函数.
                                                             (line  146)
* __trunc__() (object 的方法):           模拟数字类型.       (line  121)
* __unraisablehook__ (於 sys 模組中):    sys --- 系统相关的参数和函数.
                                                             (line  280)
* __xor__() (object 的方法):             模拟数字类型.       (line    9)
* __xor__() (於 operator 模組中):        operator --- 标准运算符替代函数.
                                                             (line  151)
* {} (curly brackets); dictionary expression: 字典显示.      (line    6)
* {} (curly brackets); in formatted string literal: 字符串字面值合并.
                                                             (line   19)
* {} (curly brackets); in regular expressions: 正则表达式语法.
                                                             (line   77)
* {} (curly brackets); in string formatting: 格式字符串语法. (line   11)
* {} (curly brackets); set expression:   集合显示.           (line    6)
* | (vertical bar); in regular expressions: 正则表达式语法.  (line  146)
* |=; augmented assignment:              增强赋值语句.       (line    6)
* ~ (tilde); home directory expansion:   os path --- 常用路径操作.
                                                             (line  119)
* A (於 re 模組中):                      模块内容.           (line   36)
* a-LAW:                                 audioop --- 处理原始音频数据.
                                                             (line   15)
* A-LAW:                                 aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line  140)
* A-LAW <1>:                             sndhdr --- 推测声音文件的类型.
                                                             (line    8)
* a2b_base64() (於 binascii 模組中):     binascii --- 二进制和 ASCII 码互转.
                                                             (line   36)
* a2b_hex() (於 binascii 模組中):        binascii --- 二进制和 ASCII 码互转.
                                                             (line  145)
* a2b_hqx() (於 binascii 模組中):        binascii --- 二进制和 ASCII 码互转.
                                                             (line   66)
* a2b_qp() (於 binascii 模組中):         binascii --- 二进制和 ASCII 码互转.
                                                             (line   49)
* a2b_uu() (於 binascii 模組中):         binascii --- 二进制和 ASCII 码互转.
                                                             (line   23)
* a85decode() (於 base64 模組中):        base64 —— Base16、Base32、Base64、Base85 資料編碼.
                                                             (line  142)
* a85encode() (於 base64 模組中):        base64 —— Base16、Base32、Base64、Base85 資料編碼.
                                                             (line  121)
* ABC (abc 中的類別):                    abc --- 抽象基类.   (line   22)
* abc (模組):                            abc --- 抽象基类.   (line    6)
* ABCMeta (abc 中的類別):                abc --- 抽象基类.   (line   45)
* abiflags (於 sys 模組中):              sys --- 系统相关的参数和函数.
                                                             (line   11)
* abort():                               行程（Process）控制.
                                                             (line    8)
* abort() (asyncio.DatagramTransport 的方法): 数据报传输.    (line   14)
* abort() (asyncio.WriteTransport 的方法): 只写传输.         (line    6)
* abort() (ftplib.FTP 的方法):           FTP 对象.           (line   49)
* abort() (threading.Barrier 的方法):    栅栏对象.           (line   70)
* abort() (於 os 模組中):                进程管理.           (line   14)
* above() (curses.panel.Panel 的方法):   Panel 对象.         (line   12)
* ABOVE_NORMAL_PRIORITY_CLASS (於 subprocess 模組中): Windows 常数.
                                                             (line   46)
* abs() (decimal.Context 的方法):        上下文对象.         (line  196)
* abs() (內建函式):                      內建函式.           (line   55)
* abs() (於 operator 模組中):            operator --- 标准运算符替代函数.
                                                             (line   62)
* abspath() (於 os.path 模組中):         os path --- 常用路径操作.
                                                             (line   46)
* abstract base class（抽象基底類別）:   術語表.             (line   30)
* AbstractAsyncContextManager (contextlib 中的類別): 工具.   (line   18)
* AbstractBasicAuthHandler (urllib.request 中的類別): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  275)
* AbstractChildWatcher (asyncio 中的類別): 进程监视器.       (line   33)
* abstractclassmethod() (於 abc 模組中): abc --- 抽象基类.   (line  206)
* AbstractContextManager (contextlib 中的類別): 工具.        (line    8)
* AbstractDigestAuthHandler (urllib.request 中的類別): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  305)
* AbstractEventLoop (asyncio 中的類別):  事件循环实现.       (line   39)
* AbstractEventLoopPolicy (asyncio 中的類別): 策略对象.      (line    8)
* AbstractFormatter (formatter 中的類別): Formatter Implementations.
                                                             (line   18)
* abstractmethod() (於 abc 模組中):      abc --- 抽象基类.   (line  141)
* abstractproperty() (於 abc 模組中):    abc --- 抽象基类.   (line  244)
* AbstractSet (typing 中的類別):         collections abc 对应的容器.
                                                             (line    6)
* abstractstaticmethod() (於 abc 模組中): abc --- 抽象基类.  (line  225)
* AbstractWriter (formatter 中的類別):   Writer Implementations.
                                                             (line   16)
* accept() (asyncore.dispatcher 的方法): asyncore --- 异步套接字处理器.
                                                             (line  187)
* accept() (multiprocessing.connection.Listener 的方法): 监听器及客户端.
                                                             (line   74)
* accept() (socket.socket 的方法):       套接字对象.         (line   12)
* access() (於 os 模組中):               文件和目录.         (line   40)
* accumulate() (於 itertools 模組中):    Itertool函数.       (line    9)
* aclose() (agen 的方法):                异步生成器-迭代器方法.
                                                             (line   42)
* aclose() (contextlib.AsyncExitStack 的方法): 工具.         (line  443)
* acos() (於 cmath 模組中):              三角函数<2>.        (line    6)
* acos() (於 math 模組中):               三角函数.           (line    6)
* acosh() (於 cmath 模組中):             双曲函数<2>.        (line    6)
* acosh() (於 math 模組中):              双曲函数.           (line    8)
* acquire() (asyncio.Condition 的方法):  Condition.          (line   42)
* acquire() (asyncio.Lock 的方法):       Lock.               (line   34)
* acquire() (asyncio.Semaphore 的方法):  Semaphore.          (line   40)
* acquire() (logging.Handler 的方法):    处理器对象.         (line   23)
* acquire() (multiprocessing.Lock 的方法): 同步原语.         (line   55)
* acquire() (multiprocessing.RLock 的方法): 同步原语.        (line   98)
* acquire() (threading.Condition 的方法): 条件对象.          (line   71)
* acquire() (threading.Lock 的方法):     锁对象.             (line   34)
* acquire() (threading.RLock 的方法):    递归锁对象.         (line   27)
* acquire() (threading.Semaphore 的方法): 信号量对象.        (line   30)
* acquire() (_thread.lock 的方法):       _thread --- 底层多线程 API.
                                                             (line  103)
* acquire_lock() (於 imp 模組中):        imp —— 由代码内部访问 import 。.
                                                             (line  267)
* Action (argparse 中的類別):            Action 类.          (line   10)
* action (optparse.Option 的屬性):       Option attributes.  (line   11)
* ACTIONS (optparse.Option 的屬性):      Adding new actions. (line   31)
* active_children() (於 multiprocessing 模組中): 杂项<3>.    (line    6)
* active_count() (於 threading 模組中):  threading --- 基于线程的并行.
                                                             (line   27)
* actual() (tkinter.font.Font 的方法):   tkinter font --- Tkinter 字体封装.
                                                             (line   45)
* Add (ast 中的類別):                    表达式<2>.          (line   54)
* add() (decimal.Context 的方法):        上下文对象.         (line  200)
* add() (frozenset 的方法):              集合类型 --- set frozenset.
                                                             (line  175)
* add() (graphlib.TopologicalSorter 的方法): graphlib --- 操作类似图的结构的功能.
                                                             (line   70)
* add() (mailbox.Mailbox 的方法):        Mailbox 对象.       (line   44)
* add() (mailbox.Maildir 的方法):        Maildir.            (line   77)
* add() (msilib.RadioButtonGroup 的方法): GUI classes.       (line   34)
* add() (pstats.Stats 的方法):           Stats 类.           (line   49)
* add() (tarfile.TarFile 的方法):        TarFile 对象.       (line  173)
* add() (tkinter.ttk.Notebook 的方法):   ttk Notebook.       (line    8)
* add() (於 audioop 模組中):             audioop --- 处理原始音频数据.
                                                             (line   26)
* add() (於 operator 模組中):            operator --- 标准运算符替代函数.
                                                             (line   67)
* addAsyncCleanup() (unittest.IsolatedAsyncioTestCase 的方法): 测试用例.
                                                             (line  833)
* addaudithook() (於 sys 模組中):        sys --- 系统相关的参数和函数.
                                                             (line   21)
* addch() (curses.window 的方法):        Window 对象.        (line    9)
* addClassCleanup() (unittest.TestCase 的類別成員): 测试用例.
                                                             (line  769)
* addCleanup() (unittest.TestCase 的方法): 测试用例.         (line  739)
* addcomponent() (turtle.Shape 的方法):  公共类.             (line   62)
* addError() (unittest.TestResult 的方法): Loading and running tests.
                                                             (line  350)
* addExpectedFailure() (unittest.TestResult 的方法): Loading and running tests.
                                                             (line  386)
* addFailure() (unittest.TestResult 的方法): Loading and running tests.
                                                             (line  361)
* addfile() (tarfile.TarFile 的方法):    TarFile 对象.       (line  189)
* addFilter() (logging.Handler 的方法):  处理器对象.         (line   46)
* addFilter() (logging.Logger 的方法):   记录器对象.         (line  208)
* addHandler() (logging.Logger 的方法):  记录器对象.         (line  223)
* addinfourl (urllib.response 中的類別): urllib response --- urllib 使用的 Response 类.
                                                             (line   11)
* addition:                              二元算术运算符.     (line   55)
* addLevelName() (於 logging 模組中):    模块级函数.         (line  154)
* addModuleCleanup() (於 unittest 模組中): setUpModule and tearDownModule.
                                                             (line   22)
* addnstr() (curses.window 的方法):      Window 对象.        (line   20)
* AddPackagePath() (於 modulefinder 模組中): modulefinder --- 查找脚本使用的模块.
                                                             (line   14)
* addr (smtpd.SMTPChannel 的屬性):       SMTPChannel 对象.   (line   45)
* Address (email.headerregistry 中的類別): email headerregistry 自定义标头对象.
                                                             (line  343)
* address (email.headerregistry.SingleAddressHeader 的屬性): email headerregistry 自定义标头对象.
                                                             (line  180)
* address (multiprocessing.connection.Listener 的屬性): 监听器及客户端.
                                                             (line   87)
* address (multiprocessing.managers.BaseManager 的屬性): 管理器.
                                                             (line  101)
* addresses (email.headerregistry.AddressHeader 的屬性): email headerregistry 自定义标头对象.
                                                             (line  159)
* addresses (email.headerregistry.Group 的屬性): email headerregistry 自定义标头对象.
                                                             (line  405)
* AddressHeader (email.headerregistry 中的類別): email headerregistry 自定义标头对象.
                                                             (line  146)
* addressof() (於 ctypes 模組中):        工具函数.           (line    6)
* AddressValueError:                     自定义异常.         (line    8)
* address_exclude() (ipaddress.IPv4Network 的方法): 网络对象.
                                                             (line  138)
* address_exclude() (ipaddress.IPv6Network 的方法): 网络对象.
                                                             (line  306)
* address_family (socketserver.BaseServer 的屬性): Server 对象<2>.
                                                             (line   58)
* address_string() (http.server.BaseHTTPRequestHandler 的方法): http server --- HTTP 服务器.
                                                             (line  275)
* addr_spec (email.headerregistry.Address 的屬性): email headerregistry 自定义标头对象.
                                                             (line  376)
* addshape() (於 turtle 模組中):         设置与特殊方法.     (line   68)
* addsitedir() (於 site 模組中):         模块内容<8>.        (line   47)
* addSkip() (unittest.TestResult 的方法): Loading and running tests.
                                                             (line  378)
* addstr() (curses.window 的方法):       Window 对象.        (line   27)
* addSubTest() (unittest.TestResult 的方法): Loading and running tests.
                                                             (line  404)
* addSuccess() (unittest.TestResult 的方法): Loading and running tests.
                                                             (line  372)
* addTest() (unittest.TestSuite 的方法): Grouping tests.     (line   25)
* addTests() (unittest.TestSuite 的方法): Grouping tests.    (line   30)
* addTypeEqualityFunc() (unittest.TestCase 的方法): 测试用例.
                                                             (line  558)
* addUnexpectedSuccess() (unittest.TestResult 的方法): Loading and running tests.
                                                             (line  396)
* add_alias() (於 email.charset 模組中): email charset 表示字符集.
                                                             (line  169)
* add_alternative() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  541)
* add_argument() (argparse.ArgumentParser 的方法): add_argument 方法.
                                                             (line    6)
* add_argument_group() (argparse.ArgumentParser 的方法): 参数组.
                                                             (line    6)
* add_attachment() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  551)
* add_cgi_vars() (wsgiref.handlers.BaseHandler 的方法): wsgiref handlers -- 服务器/网关基类.
                                                             (line  110)
* add_charset() (於 email.charset 模組中): email charset 表示字符集.
                                                             (line  145)
* add_child_handler() (asyncio.AbstractChildWatcher 的方法): 进程监视器.
                                                             (line   35)
* add_codec() (於 email.charset 模組中): email charset 表示字符集.
                                                             (line  176)
* add_cookie_header() (http.cookiejar.CookieJar 的方法): CookieJar 和 FileCookieJar 对象.
                                                             (line   11)
* add_data() (於 msilib 模組中):         msilib --- Read and write Microsoft Installer files.
                                                             (line   74)
* add_dll_directory() (於 os 模組中):    进程管理.           (line   21)
* add_done_callback() (asyncio.Future 的方法): Future 对象<2>.
                                                             (line   69)
* add_done_callback() (asyncio.Task 的方法): Task 对象.      (line  137)
* add_done_callback() (concurrent.futures.Future 的方法): Future 对象.
                                                             (line   58)
* add_fallback() (gettext.NullTranslations 的方法): NullTranslations 类.
                                                             (line   24)
* add_file() (msilib.Directory 的方法):  Directory Objects.  (line   30)
* add_flag() (mailbox.MaildirMessage 的方法): MaildirMessage.
                                                             (line   70)
* add_flag() (mailbox.mboxMessage 的方法): mboxMessage.      (line   68)
* add_flag() (mailbox.MMDFMessage 的方法): MMDFMessage.      (line   67)
* add_flowing_data() (formatter.formatter 的方法): The Formatter Interface.
                                                             (line   43)
* add_folder() (mailbox.Maildir 的方法): Maildir.            (line   59)
* add_folder() (mailbox.MH 的方法):      MH.                 (line   37)
* add_get_handler() (email.contentmanager.ContentManager 的方法): email contentmanager 管理 MIME 内容.
                                                             (line   64)
* add_handler() (urllib.request.OpenerDirector 的方法): OpenerDirector 对象.
                                                             (line    8)
* add_header() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  213)
* add_header() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  308)
* add_header() (urllib.request.Request 的方法): Request 对象.
                                                             (line   70)
* add_header() (wsgiref.headers.Headers 的方法): wsgiref headers -- WSGI 响应标头工具.
                                                             (line   49)
* add_history() (於 readline 模組中):    历史列表.           (line   33)
* add_hor_rule() (formatter.formatter 的方法): The Formatter Interface.
                                                             (line   36)
* add_include_dir() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line   95)
* add_label() (mailbox.BabylMessage 的方法): BabylMessage.   (line   52)
* add_label_data() (formatter.formatter 的方法): The Formatter Interface.
                                                             (line   59)
* add_library() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  112)
* add_library_dir() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  134)
* add_line_break() (formatter.formatter 的方法): The Formatter Interface.
                                                             (line   31)
* add_link_object() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  179)
* add_literal_data() (formatter.formatter 的方法): The Formatter Interface.
                                                             (line   53)
* add_mutually_exclusive_group() (argparse.ArgumentParser 的方法): 互斥.
                                                             (line    6)
* add_option() (optparse.OptionParser 的方法): 定义选项.     (line   14)
* add_parent() (urllib.request.BaseHandler 的方法): BaseHandler 对象.
                                                             (line    9)
* add_password() (urllib.request.HTTPPasswordMgr 的方法): HTTPPasswordMgr 对象.
                                                             (line    9)
* add_password() (urllib.request.HTTPPasswordMgrWithPriorAuth 的方法): HTTPPasswordMgrWithPriorAuth 对象.
                                                             (line    9)
* add_reader() (asyncio.loop 的方法):    监控文件描述符.     (line    6)
* add_related() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  530)
* add_runtime_library_dir() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  149)
* add_section() (configparser.ConfigParser 的方法): ConfigParser 对象.
                                                             (line   73)
* add_section() (configparser.RawConfigParser 的方法): RawConfigParser 对象.
                                                             (line   23)
* add_sequence() (mailbox.MHMessage 的方法): MHMessage.      (line   38)
* add_set_handler() (email.contentmanager.ContentManager 的方法): email contentmanager 管理 MIME 内容.
                                                             (line   69)
* add_signal_handler() (asyncio.loop 的方法): Unix 信号.     (line    6)
* add_stream() (於 msilib 模組中):       msilib --- Read and write Microsoft Installer files.
                                                             (line  104)
* add_subparsers() (argparse.ArgumentParser 的方法): 子命令. (line    6)
* add_tables() (於 msilib 模組中):       msilib --- Read and write Microsoft Installer files.
                                                             (line   95)
* add_type() (於 mimetypes 模組中):      mimetypes --- 映射文件名到 MIME 类型.
                                                             (line   88)
* add_unredirected_header() (urllib.request.Request 的方法): Request 对象.
                                                             (line   78)
* add_writer() (asyncio.loop 的方法):    监控文件描述符.     (line   15)
* adjusted() (decimal.Decimal 的方法):   Decimal 对象.       (line   94)
* adler32() (於 zlib 模組中):            zlib --- 与 gzip 兼容的压缩.
                                                             (line   24)
* ADPCM, Intel/DVI:                      audioop --- 处理原始音频数据.
                                                             (line   15)
* adpcm2lin() (於 audioop 模組中):       audioop --- 处理原始音频数据.
                                                             (line   32)
* AF_ALG (於 socket 模組中):             常数<6>.            (line  196)
* AF_CAN (於 socket 模組中):             常数<6>.            (line   88)
* AF_INET (於 socket 模組中):            常数<6>.            (line   11)
* AF_INET6 (於 socket 模組中):           常数<6>.            (line   11)
* AF_LINK (於 socket 模組中):            常数<6>.            (line  220)
* AF_PACKET (於 socket 模組中):          常数<6>.            (line  157)
* AF_QIPCRTR (於 socket 模組中):         常数<6>.            (line  245)
* AF_RDS (於 socket 模組中):             常数<6>.            (line  167)
* AF_UNIX (於 socket 模組中):            常数<6>.            (line   11)
* AF_VSOCK (於 socket 模組中):           常数<6>.            (line  207)
* aifc (模組):                           aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line    6)
* aifc() (aifc.aifc 的方法):             aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line  116)
* AIFF:                                  aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line    8)
* AIFF <1>:                              chunk --- 读取 IFF 分块数据.
                                                             (line    8)
* aiff() (aifc.aifc 的方法):             aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line  111)
* AIFF-C:                                aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line    8)
* AIFF-C <1>:                            chunk --- 读取 IFF 分块数据.
                                                             (line    8)
* alarm() (於 signal 模組中):            模块内容<5>.        (line  211)
* alaw2lin() (於 audioop 模組中):        audioop --- 处理原始音频数据.
                                                             (line   38)
* AlertDescription (ssl 中的類別):       常量<3>.            (line  441)
* ALERT_DESCRIPTION_HANDSHAKE_FAILURE (於 ssl 模組中): 常量<3>.
                                                             (line  428)
* ALERT_DESCRIPTION_INTERNAL_ERROR (於 ssl 模組中): 常量<3>. (line  428)
* algorithms_available (於 hashlib 模組中): 哈希算法.        (line   81)
* algorithms_guaranteed (於 hashlib 模組中): 哈希算法.       (line   73)
* alias (ast 中的類別):                  Imports.            (line   40)
* alias (pdb command):                   调试器命令.         (line  236)
* alignment() (於 ctypes 模組中):        工具函数.           (line   12)
* alive (weakref.finalize 的屬性):       weakref --- 弱引用. (line  226)
* all() (內建函式):                      內建函式.           (line   60)
* allocate_lock() (於 _thread 模組中):   _thread --- 底层多线程 API.
                                                             (line   57)
* allocfunc (C 型態):                    Slot Type typedefs. (line    6)
* allowed_domains() (http.cookiejar.DefaultCookiePolicy 的方法): DefaultCookiePolicy 对象.
                                                             (line   59)
* allow_reuse_address (socketserver.BaseServer 的屬性): Server 对象<2>.
                                                             (line   82)
* all_errors (於 ftplib 模組中):         ftplib --- FTP 协议客户端.
                                                             (line  132)
* all_features (於 xml.sax.handler 模組中): xml sax handler --- SAX 处理句柄的基类.
                                                             (line   81)
* all_frames (tracemalloc.Filter 的屬性): 过滤器<2>.         (line   57)
* all_properties (於 xml.sax.handler 模組中): xml sax handler --- SAX 处理句柄的基类.
                                                             (line  113)
* all_suffixes() (於 importlib.machinery 模組中): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line   49)
* all_tasks() (於 asyncio 模組中):       内省.               (line   16)
* alt() (於 curses.ascii 模組中):        curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  206)
* altsep (於 os 模組中):                 其他系统信息.       (line   84)
* altzone (於 time 模組中):              时区常量.           (line    6)
* ALT_DIGITS (於 locale 模組中):         locale --- 国际化服务.
                                                             (line  245)
* ALWAYS_EQ (於 test.support 模組中):    test support --- Utilities for the Python test suite.
                                                             (line  200)
* ALWAYS_TYPED_ACTIONS (optparse.Option 的屬性): Adding new actions.
                                                             (line   43)
* AMPER (於 token 模組中):               token --- 与Python解析树一起使用的常量.
                                                             (line   98)
* AMPEREQUAL (於 token 模組中):          token --- 与Python解析树一起使用的常量.
                                                             (line  186)
* And (ast 中的類別):                    表达式<2>.          (line   87)
* and_() (於 operator 模組中):           operator --- 标准运算符替代函数.
                                                             (line   72)
* AnnAssign (ast 中的類別):              Statements.         (line   43)
* Annotated (於 typing 模組中):          特殊形式.           (line  195)
* annotated; assignment:                 带标注的赋值语句.   (line    6)
* annotation (inspect.Parameter 的屬性): Introspecting callables with the Signature object.
                                                             (line  174)
* annotation（註釋）:                    術語表.             (line   44)
* announce() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  501)
* anonymous; function:                   lambda 表达式.      (line    6)
* answer_challenge() (於 multiprocessing.connection 模組中): 监听器及客户端.
                                                             (line   23)
* anticipate_failure() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  632)
* Any (於 typing 模組中):                特殊类型.           (line    8)
* ANY (於 unittest.mock 模組中):         ANY.                (line    6)
* any() (內建函式):                      內建函式.           (line   71)
* AnyStr (於 typing 模組中):             构建泛型类型.       (line   65)
* apilevel (於 sqlite3 模組中):          模块函数和常量.     (line    6)
* api_version (於 sys 模組中):           sys --- 系统相关的参数和函数.
                                                             (line 1395)
* apop() (poplib.POP3 的方法):           POP3 对象.          (line   38)
* APPDATA:                               PEP 370 分用户的 site-packages 目录.
                                                             (line   26)
* append() (array.array 的方法):         array --- 高效率的數值型態陣列.
                                                             (line  104)
* append() (collections.deque 的方法):   deque 对象.         (line   27)
* append() (email.header.Header 的方法): email header 国际化标头.
                                                             (line   77)
* append() (imaplib.IMAP4 的方法):       IMAP4 对象.         (line   27)
* append() (msilib.CAB 的方法):          CAB Objects.        (line   15)
* append() (pipes.Template 的方法):      模板对象.           (line   22)
* append() (sequence method):            可变序列类型.       (line   14)
* append() (xml.etree.ElementTree.Element 的方法): 元素对象. (line   74)
* appendChild() (xml.dom.Node 的方法):   节点对象.           (line   99)
* appendleft() (collections.deque 的方法): deque 对象.       (line   31)
* append_history_file() (於 readline 模組中): 历史文件.      (line   18)
* application_uri() (於 wsgiref.util 模組中): wsgiref util -- WSGI 环境工具.
                                                             (line   27)
* apply (2to3 fixer):                    修复器.             (line   10)
* apply() (multiprocessing.pool.Pool 的方法): 进程池.        (line   49)
* apply_async() (multiprocessing.pool.Pool 的方法): 进程池.  (line   55)
* apply_defaults() (inspect.BoundArguments 的方法): Introspecting callables with the Signature object.
                                                             (line  314)
* architecture() (於 platform 模組中):   跨平台.             (line    6)
* archive (zipimport.zipimporter 的屬性): zipimporter 对象.  (line   62)
* aRepr (於 reprlib 模組中):             reprlib --- 另一种 repr 实现.
                                                             (line   20)
* arg (ast 中的類別):                    Function and class definitions.
                                                             (line   69)
* argparse (模組):                       argparse --- 命令行选项、参数和子命令解析器.
                                                             (line    6)
* args (BaseException 的屬性):           基类.               (line   14)
* args (functools.partial 的屬性):       partial 对象.       (line   14)
* args (inspect.BoundArguments 的屬性):  Introspecting callables with the Signature object.
                                                             (line  300)
* args (pdb command):                    调试器命令.         (line  189)
* args (subprocess.CompletedProcess 的屬性): 使用 subprocess 模块.
                                                             (line   81)
* args (subprocess.Popen 的屬性):        Popen 对象.         (line   87)
* args_from_interpreter_flags() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  445)
* argtypes (ctypes._FuncPtr 的屬性):     外部函数.           (line   29)
* argument; call semantics:              切片.               (line   30)
* argument; difference from parameter:   如何将可选参数或关键字参数从一个函数传递到另一个函数？.
                                                             (line   16)
* argument; function definition:         函数定义.           (line   48)
* ArgumentDefaultsHelpFormatter (argparse 中的類別): formatter_class.
                                                             (line    9)
* ArgumentError:                         外部函数.           (line   64)
* ArgumentParser (argparse 中的類別):    ArgumentParser 对象.
                                                             (line    6)
* arguments (ast 中的類別):              Function and class definitions.
                                                             (line   50)
* arguments (inspect.BoundArguments 的屬性): Introspecting callables with the Signature object.
                                                             (line  281)
* argument（引數）:                      術語表.             (line   56)
* argv (in module sys):                  Process-wide parameters.
                                                             (line  217)
* argv (於 sys 模組中):                  sys --- 系统相关的参数和函数.
                                                             (line   49)
* arithmetic:                            数字类型 --- int float complex.
                                                             (line   20)
* arithmetic; conversion:                算术转换.           (line    6)
* ArithmeticError:                       基类.               (line   36)
* array (array 中的類別):                array --- 高效率的數值型態陣列.
                                                             (line   71)
* Array (ctypes 中的類別):               数组与指针.         (line    6)
* array (模組):                          array --- 高效率的數值型態陣列.
                                                             (line    6)
* Array() (multiprocessing.managers.SyncManager 的方法): 管理器.
                                                             (line  171)
* Array() (於 multiprocessing 模組中):   共享 ctypes 对象.   (line   38)
* Array() (於 multiprocessing.sharedctypes 模組中): multiprocessing sharedctypes 模块.
                                                             (line   43)
* arrays:                                array --- 高效率的數值型態陣列.
                                                             (line    6)
* arraysize (sqlite3.Cursor 的屬性):     Cursor 对象.        (line  183)
* article() (nntplib.NNTP 的方法):       方法<3>.            (line  215)
* as; except clause:                     try 语句.           (line   31)
* as; import statement:                  import 语句.        (line   33)
* as; with statement:                    with 语句.          (line    6)
* ASCII:                                 标注.               (line   23)
* ASCII <1>:                             字面值.             (line    8)
* ASCII (於 re 模組中):                  模块内容.           (line   36)
* ascii() (內建函式):                    內建函式.           (line   82)
* ascii() (於 curses.ascii 模組中):      curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  197)
* ascii_letters (於 string 模組中):      字符串常量.         (line    8)
* ascii_lowercase (於 string 模組中):    字符串常量.         (line   13)
* ascii_uppercase (於 string 模組中):    字符串常量.         (line   18)
* asctime() (於 time 模組中):            函数<3>.            (line    6)
* asdict() (於 dataclasses 模組中):      模块级装饰器、类和函数.
                                                             (line  219)
* asend() (agen 的方法):                 异步生成器-迭代器方法.
                                                             (line   22)
* asin() (於 cmath 模組中):              三角函数<2>.        (line   12)
* asin() (於 math 模組中):               三角函数.           (line   10)
* asinh() (於 cmath 模組中):             双曲函数<2>.        (line   11)
* asinh() (於 math 模組中):              双曲函数.           (line   12)
* askcolor() (於 tkinter.colorchooser 模組中): tkinter colorchooser --- 颜色选择对话框.
                                                             (line   16)
* askdirectory() (於 tkinter.filedialog 模組中): 原生 加载/保存 对话框.
                                                             (line   48)
* askfloat() (於 tkinter.simpledialog 模組中): tkinter simpledialog --- 标准 Tkinter 输入对话框.
                                                             (line   13)
* askinteger() (於 tkinter.simpledialog 模組中): tkinter simpledialog --- 标准 Tkinter 输入对话框.
                                                             (line   13)
* askokcancel() (於 tkinter.messagebox 模組中): tkinter messagebox --- Tkinter 消息提示.
                                                             (line   35)
* askopenfile() (於 tkinter.filedialog 模組中): 原生 加载/保存 对话框.
                                                             (line   28)
* askopenfilename() (於 tkinter.filedialog 模組中): 原生 加载/保存 对话框.
                                                             (line   38)
* askopenfilenames() (於 tkinter.filedialog 模組中): 原生 加载/保存 对话框.
                                                             (line   38)
* askopenfiles() (於 tkinter.filedialog 模組中): 原生 加载/保存 对话框.
                                                             (line   28)
* askquestion() (於 tkinter.messagebox 模組中): tkinter messagebox --- Tkinter 消息提示.
                                                             (line   35)
* askretrycancel() (於 tkinter.messagebox 模組中): tkinter messagebox --- Tkinter 消息提示.
                                                             (line   35)
* asksaveasfile() (於 tkinter.filedialog 模組中): 原生 加载/保存 对话框.
                                                             (line   34)
* asksaveasfilename() (於 tkinter.filedialog 模組中): 原生 加载/保存 对话框.
                                                             (line   44)
* askstring() (於 tkinter.simpledialog 模組中): tkinter simpledialog --- 标准 Tkinter 输入对话框.
                                                             (line   13)
* askyesno() (於 tkinter.messagebox 模組中): tkinter messagebox --- Tkinter 消息提示.
                                                             (line   35)
* askyesnocancel() (於 tkinter.messagebox 模組中): tkinter messagebox --- Tkinter 消息提示.
                                                             (line   35)
* Assert (ast 中的類別):                 Statements.         (line  130)
* assertAlmostEqual() (unittest.TestCase 的方法): 测试用例.  (line  482)
* assertCountEqual() (unittest.TestCase 的方法): 测试用例.   (line  537)
* assertDictEqual() (unittest.TestCase 的方法): 测试用例.    (line  645)
* assertEqual() (unittest.TestCase 的方法): 测试用例.        (line  177)
* assertFalse() (unittest.TestCase 的方法): 测试用例.        (line  201)
* assertGreater() (unittest.TestCase 的方法): 测试用例.      (line  506)
* assertGreaterEqual() (unittest.TestCase 的方法): 测试用例. (line  506)
* assertIn() (unittest.TestCase 的方法): 测试用例.           (line  228)
* assertInBytecode() (test.support.bytecode_helper.BytecodeTestCase 的方法): test support bytecode_helper --- Support tools for testing correct bytecode generation.
                                                             (line   22)
* AssertionError:                        具体异常.           (line    8)
* assertIs() (unittest.TestCase 的方法): 测试用例.           (line  213)
* assertIsInstance() (unittest.TestCase 的方法): 测试用例.   (line  235)
* assertIsNone() (unittest.TestCase 的方法): 测试用例.       (line  221)
* assertIsNot() (unittest.TestCase 的方法): 测试用例.        (line  213)
* assertIsNotNone() (unittest.TestCase 的方法): 测试用例.    (line  221)
* assertLess() (unittest.TestCase 的方法): 测试用例.         (line  506)
* assertLessEqual() (unittest.TestCase 的方法): 测试用例.    (line  506)
* assertListEqual() (unittest.TestCase 的方法): 测试用例.    (line  622)
* assertLogs() (unittest.TestCase 的方法): 测试用例.         (line  403)
* assertMultiLineEqual() (unittest.TestCase 的方法): 测试用例.
                                                             (line  597)
* assertNotAlmostEqual() (unittest.TestCase 的方法): 测试用例.
                                                             (line  482)
* assertNotEqual() (unittest.TestCase 的方法): 测试用例.     (line  196)
* assertNotIn() (unittest.TestCase 的方法): 测试用例.        (line  228)
* assertNotInBytecode() (test.support.bytecode_helper.BytecodeTestCase 的方法): test support bytecode_helper --- Support tools for testing correct bytecode generation.
                                                             (line   28)
* assertNotIsInstance() (unittest.TestCase 的方法): 测试用例.
                                                             (line  235)
* assertNotRegex() (unittest.TestCase 的方法): 测试用例.     (line  519)
* assertRaises() (unittest.TestCase 的方法): 测试用例.       (line  270)
* assertRaisesRegex() (unittest.TestCase 的方法): 测试用例.  (line  311)
* assertRegex() (unittest.TestCase 的方法): 测试用例.        (line  519)
* asserts (2to3 fixer):                  修复器.             (line   15)
* assertSequenceEqual() (unittest.TestCase 的方法): 测试用例.
                                                             (line  607)
* assertSetEqual() (unittest.TestCase 的方法): 测试用例.     (line  633)
* assertTrue() (unittest.TestCase 的方法): 测试用例.         (line  201)
* assertTupleEqual() (unittest.TestCase 的方法): 测试用例.   (line  622)
* assertWarns() (unittest.TestCase 的方法): 测试用例.        (line  337)
* assertWarnsRegex() (unittest.TestCase 的方法): 测试用例.   (line  378)
* assert_any_await() (unittest.mock.AsyncMock 的方法): Mock 类.
                                                             (line  790)
* assert_any_call() (unittest.mock.Mock 的方法): Mock 类.    (line  128)
* assert_awaited() (unittest.mock.AsyncMock 的方法): Mock 类.
                                                             (line  720)
* assert_awaited_once() (unittest.mock.AsyncMock 的方法): Mock 类.
                                                             (line  740)
* assert_awaited_once_with() (unittest.mock.AsyncMock 的方法): Mock 类.
                                                             (line  773)
* assert_awaited_with() (unittest.mock.AsyncMock 的方法): Mock 类.
                                                             (line  756)
* assert_called() (unittest.mock.Mock 的方法): Mock 类.      (line   77)
* assert_called_once() (unittest.mock.Mock 的方法): Mock 类. (line   88)
* assert_called_once_with() (unittest.mock.Mock 的方法): Mock 类.
                                                             (line  114)
* assert_called_with() (unittest.mock.Mock 的方法): Mock 类. (line  105)
* assert_has_awaits() (unittest.mock.AsyncMock 的方法): Mock 类.
                                                             (line  807)
* assert_has_calls() (unittest.mock.Mock 的方法): Mock 类.   (line  144)
* assert_line_data() (formatter.formatter 的方法): The Formatter Interface.
                                                             (line  143)
* assert_not_awaited() (unittest.mock.AsyncMock 的方法): Mock 类.
                                                             (line  834)
* assert_not_called() (unittest.mock.Mock 的方法): Mock 类.  (line  165)
* assert_python_failure() (於 test.support.script_helper 模組中): test support script_helper --- Utilities for the Python execution tests.
                                                             (line   55)
* assert_python_ok() (於 test.support.script_helper 模組中): test support script_helper --- Utilities for the Python execution tests.
                                                             (line   39)
* Assign (ast 中的類別):                 Statements.         (line    6)
* assignment; statement:                 标准类型层级结构.   (line  151)
* assignment; statement <1>:             赋值语句.           (line    6)
* AST (ast 中的類別):                    节点类.             (line    6)
* ast (模組):                            ast --- 抽象语法树. (line    6)
* ast command line option; -a:           命令行用法<2>.      (line   29)
* ast command line option; -h:           命令行用法<2>.      (line   15)
* ast command line option; –help:        命令行用法<2>.      (line   15)
* ast command line option; -i <indent>:  命令行用法<2>.      (line   33)
* ast command line option; –include-attributes: 命令行用法<2>.
                                                             (line   29)
* ast command line option; –indent <indent>: 命令行用法<2>.  (line   33)
* ast command line option; -m <mode>:    命令行用法<2>.      (line   19)
* ast command line option; –mode <mode>: 命令行用法<2>.      (line   19)
* ast command line option; –no-type-comments: 命令行用法<2>. (line   25)
* astimezone() (datetime.datetime 的方法): datetime 对象.    (line  387)
* astuple() (於 dataclasses 模組中):     模块级装饰器、类和函数.
                                                             (line  251)
* ASYNC (於 token 模組中):               token --- 与Python解析树一起使用的常量.
                                                             (line  242)
* async for; in comprehensions:          列表、集合与字典的显示.
                                                             (line   13)
* AsyncContextManager (typing 中的類別): 上下文管理器类型<2>.
                                                             (line   17)
* asynccontextmanager() (於 contextlib 模組中): 工具.        (line   78)
* AsyncExitStack (contextlib 中的類別):  工具.               (line  419)
* AsyncFor (ast 中的類別):               Async and await.    (line   41)
* AsyncFunctionDef (ast 中的類別):       Async and await.    (line    6)
* AsyncGenerator (collections.abc 中的類別): 容器抽象基类.   (line  235)
* AsyncGenerator (typing 中的類別):      异步编程.           (line   23)
* AsyncGeneratorType (於 types 模組中):  标准解释器类型.     (line   37)
* asynchat (模組):                       asynchat --- 异步套接字指令/响应处理程序.
                                                             (line    6)
* asynchronous context manager（非同步情境管理器）: 術語表.  (line   84)
* asynchronous generator iterator（非同步產生器疊代器）: 術語表.
                                                             (line  104)
* asynchronous generator; asynchronous iterator: 标准类型层级结构.
                                                             (line  360)
* asynchronous generator; function:      标准类型层级结构.   (line  360)
* asynchronous generator（非同步產生器）: 術語表.            (line   90)
* asynchronous iterable（非同步可疊代物件）: 術語表.         (line  119)
* asynchronous iterator（非同步疊代器）: 術語表.             (line  125)
* asyncio (模組):                        asyncio --- 异步 I/O.
                                                             (line    6)
* asyncio.subprocess.DEVNULL (於 asyncio 模組中): 常数<5>.   (line   22)
* asyncio.subprocess.PIPE (於 asyncio 模組中): 常数<5>.      (line    6)
* asyncio.subprocess.Process (asyncio 中的類別): 与子进程交互.
                                                             (line   10)
* asyncio.subprocess.STDOUT (於 asyncio 模組中): 常数<5>.    (line   17)
* AsyncIterable (collections.abc 中的類別): 容器抽象基类.    (line  221)
* AsyncIterable (typing 中的類別):       异步编程.           (line   58)
* AsyncIterator (collections.abc 中的類別): 容器抽象基类.    (line  228)
* AsyncIterator (typing 中的類別):       异步编程.           (line   67)
* AsyncMock (unittest.mock 中的類別):    Mock 类.            (line  648)
* asyncore (模組):                       asyncore --- 异步套接字处理器.
                                                             (line    6)
* AsyncResult (multiprocessing.pool 中的類別): 进程池.       (line  158)
* asyncSetUp() (unittest.IsolatedAsyncioTestCase 的方法): 测试用例.
                                                             (line  809)
* asyncTearDown() (unittest.IsolatedAsyncioTestCase 的方法): 测试用例.
                                                             (line  818)
* AsyncWith (ast 中的類別):              Async and await.    (line   41)
* async_chat (asynchat 中的類別):        asynchat --- 异步套接字指令/响应处理程序.
                                                             (line   24)
* async_chat.ac_in_buffer_size (於 asynchat 模組中): asynchat --- 异步套接字指令/响应处理程序.
                                                             (line   39)
* async_chat.ac_out_buffer_size (於 asynchat 模組中): asynchat --- 异步套接字指令/响应处理程序.
                                                             (line   43)
* as_bytes() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line   83)
* as_bytes() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line   86)
* as_completed() (於 asyncio 模組中):    简单等待.           (line   80)
* as_completed() (於 concurrent.futures 模組中): 模块函数.   (line   38)
* as_file() (於 importlib.resources 模組中): importlib resources -- 资源.
                                                             (line   55)
* as_integer_ratio() (decimal.Decimal 的方法): Decimal 对象. (line  100)
* as_integer_ratio() (float 的方法):     浮点类型的附加方法. (line    9)
* as_integer_ratio() (fractions.Fraction 的方法): fractions --- 分数.
                                                             (line   92)
* as_integer_ratio() (int 的方法):       整数类型的附加方法. (line   89)
* AS_IS (於 formatter 模組中):           The Formatter Interface.
                                                             (line   12)
* as_posix() (pathlib.PurePath 的方法):  方法和特征属性.     (line  139)
* as_string() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line   48)
* as_string() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line   47)
* as_tuple() (decimal.Decimal 的方法):   Decimal 对象.       (line  113)
* as_uri() (pathlib.PurePath 的方法):    方法和特征属性.     (line  149)
* AT (於 token 模組中):                  token --- 与Python解析树一起使用的常量.
                                                             (line  218)
* atan() (於 cmath 模組中):              三角函数<2>.        (line   16)
* atan() (於 math 模組中):               三角函数.           (line   15)
* atan2() (於 math 模組中):              三角函数.           (line   20)
* atanh() (於 cmath 模組中):             双曲函数<2>.        (line   16)
* atanh() (於 math 模組中):              双曲函数.           (line   16)
* ATEQUAL (於 token 模組中):             token --- 与Python解析树一起使用的常量.
                                                             (line  222)
* atexit (weakref.finalize 的屬性):      weakref --- 弱引用. (line  230)
* atexit (模組):                         atexit --- 退出处理器.
                                                             (line    6)
* athrow() (agen 的方法):                异步生成器-迭代器方法.
                                                             (line   33)
* atof() (於 locale 模組中):             locale --- 国际化服务.
                                                             (line  369)
* atoi() (於 locale 模組中):             locale --- 国际化服务.
                                                             (line  373)
* atom:                                  原子.               (line    6)
* attach() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  138)
* attach_loop() (asyncio.AbstractChildWatcher 的方法): 进程监视器.
                                                             (line   50)
* attach_mock() (unittest.mock.Mock 的方法): Mock 类.        (line  216)
* AttlistDeclHandler() (xml.parsers.expat.xmlparser 的方法): XMLParser对象<2>.
                                                             (line  173)
* attrgetter() (於 operator 模組中):     operator --- 标准运算符替代函数.
                                                             (line  203)
* attrib (xml.etree.ElementTree.Element 的屬性): 元素对象.   (line   39)
* attribute:                             标准类型层级结构.   (line   10)
* Attribute (ast 中的類別):              表达式<2>.          (line  171)
* attribute; assignment:                 赋值语句.           (line    6)
* attribute; assignment <1>:             赋值语句.           (line   63)
* attribute; deletion:                   del 语句.           (line   17)
* attribute; reference:                  属性引用.           (line    6)
* AttributeError:                        具体异常.           (line   12)
* attributes (xml.dom.Node 的屬性):      节点对象.           (line   23)
* AttributesImpl (xml.sax.xmlreader 中的類別): xml sax xmlreader --- 用于 XML 解析器的接口.
                                                             (line   56)
* AttributesNSImpl (xml.sax.xmlreader 中的類別): xml sax xmlreader --- 用于 XML 解析器的接口.
                                                             (line   64)
* attribute（屬性）:                     術語表.             (line  133)
* attroff() (curses.window 的方法):      Window 对象.        (line   45)
* attron() (curses.window 的方法):       Window 对象.        (line   49)
* attrset() (curses.window 的方法):      Window 对象.        (line   53)
* at_eof() (asyncio.StreamReader 的方法): StreamReader.      (line   56)
* Audio Interchange File Format:         aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line    8)
* Audio Interchange File Format <1>:     chunk --- 读取 IFF 分块数据.
                                                             (line    8)
* AUDIODEV:                              ossaudiodev --- 访问兼容OSS的音频设备.
                                                             (line   47)
* audioop (模組):                        audioop --- 处理原始音频数据.
                                                             (line    6)
* AUDIO_FILE_ENCODING_ADPCM_G721 (於 sunau 模組中): sunau --- 读写 Sun AU 文件.
                                                             (line   85)
* AUDIO_FILE_ENCODING_ADPCM_G722 (於 sunau 模組中): sunau --- 读写 Sun AU 文件.
                                                             (line   85)
* AUDIO_FILE_ENCODING_ADPCM_G723_3 (於 sunau 模組中): sunau --- 读写 Sun AU 文件.
                                                             (line   85)
* AUDIO_FILE_ENCODING_ADPCM_G723_5 (於 sunau 模組中): sunau --- 读写 Sun AU 文件.
                                                             (line   85)
* AUDIO_FILE_ENCODING_ALAW_8 (於 sunau 模組中): sunau --- 读写 Sun AU 文件.
                                                             (line   76)
* AUDIO_FILE_ENCODING_DOUBLE (於 sunau 模組中): sunau --- 读写 Sun AU 文件.
                                                             (line   85)
* AUDIO_FILE_ENCODING_FLOAT (於 sunau 模組中): sunau --- 读写 Sun AU 文件.
                                                             (line   85)
* AUDIO_FILE_ENCODING_LINEAR_16 (於 sunau 模組中): sunau --- 读写 Sun AU 文件.
                                                             (line   76)
* AUDIO_FILE_ENCODING_LINEAR_24 (於 sunau 模組中): sunau --- 读写 Sun AU 文件.
                                                             (line   76)
* AUDIO_FILE_ENCODING_LINEAR_32 (於 sunau 模組中): sunau --- 读写 Sun AU 文件.
                                                             (line   76)
* AUDIO_FILE_ENCODING_LINEAR_8 (於 sunau 模組中): sunau --- 读写 Sun AU 文件.
                                                             (line   76)
* AUDIO_FILE_ENCODING_MULAW_8 (於 sunau 模組中): sunau --- 读写 Sun AU 文件.
                                                             (line   76)
* AUDIO_FILE_MAGIC (於 sunau 模組中):    sunau --- 读写 Sun AU 文件.
                                                             (line   71)
* audit events:                          调试和分析.         (line    9)
* audit() (於 sys 模組中):               sys --- 系统相关的参数和函数.
                                                             (line   64)
* auditing:                              sys --- 系统相关的参数和函数.
                                                             (line   66)
* AugAssign (ast 中的類別):              Statements.         (line   96)
* augmented; assignment:                 增强赋值语句.       (line    6)
* auth() (ftplib.FTP_TLS 的方法):        FTP_TLS 对象.       (line   12)
* auth() (smtplib.SMTP 的方法):          SMTP 对象.          (line  117)
* authenticate() (imaplib.IMAP4 的方法): IMAP4 对象.         (line   31)
* AuthenticationError:                   Process 和异常.     (line  187)
* authenticators() (netrc.netrc 的方法): netrc 对象.         (line    8)
* authkey (multiprocessing.Process 的屬性): Process 和异常.  (line   99)
* auto (enum 中的類別):                  模块内容<2>.        (line   35)
* autorange() (timeit.Timer 的方法):     Python 接口.        (line   73)
* available_timezones() (於 zoneinfo 模組中): 函数<2>.       (line    6)
* avg() (於 audioop 模組中):             audioop --- 处理原始音频数据.
                                                             (line   43)
* avgpp() (於 audioop 模組中):           audioop --- 处理原始音频数据.
                                                             (line   47)
* avoids_symlink_attacks (shutil.rmtree 的屬性): 目录和文件操作.
                                                             (line  243)
* Await (ast 中的類別):                  Async and await.    (line   12)
* AWAIT (於 token 模組中):               token --- 与Python解析树一起使用的常量.
                                                             (line  240)
* await; in comprehensions:              列表、集合与字典的显示.
                                                             (line   37)
* Awaitable (collections.abc 中的類別):  容器抽象基类.       (line  187)
* Awaitable (typing 中的類別):           异步编程.           (line   76)
* awaitable（可等待物件）:               術語表.             (line  139)
* await_args (unittest.mock.AsyncMock 的屬性): Mock 类.      (line  863)
* await_args_list (unittest.mock.AsyncMock 的屬性): Mock 类. (line  881)
* await_count (unittest.mock.AsyncMock 的屬性): Mock 类.     (line  847)
* b"; bytes literal:                     字符串与字节串字面值.
                                                             (line   37)
* b’; bytes literal:                     字符串与字节串字面值.
                                                             (line   37)
* b16decode() (於 base64 模組中):        base64 —— Base16、Base32、Base64、Base85 資料編碼.
                                                             (line  110)
* b16encode() (於 base64 模組中):        base64 —— Base16、Base32、Base64、Base85 資料編碼.
                                                             (line  105)
* b2a_base64() (於 binascii 模組中):     binascii --- 二进制和 ASCII 码互转.
                                                             (line   41)
* b2a_hex() (於 binascii 模組中):        binascii --- 二进制和 ASCII 码互转.
                                                             (line  119)
* b2a_hqx() (於 binascii 模組中):        binascii --- 二进制和 ASCII 码互转.
                                                             (line   91)
* b2a_qp() (於 binascii 模組中):         binascii --- 二进制和 ASCII 码互转.
                                                             (line   55)
* b2a_uu() (於 binascii 模組中):         binascii --- 二进制和 ASCII 码互转.
                                                             (line   28)
* b32decode() (於 base64 模組中):        base64 —— Base16、Base32、Base64、Base85 資料編碼.
                                                             (line   88)
* b32encode() (於 base64 模組中):        base64 —— Base16、Base32、Base64、Base85 資料編碼.
                                                             (line   83)
* b64decode() (於 base64 模組中):        base64 —— Base16、Base32、Base64、Base85 資料編碼.
                                                             (line   45)
* b64encode() (於 base64 模組中):        base64 —— Base16、Base32、Base64、Base85 資料編碼.
                                                             (line   35)
* b85decode() (於 base64 模組中):        base64 —— Base16、Base32、Base64、Base85 資料編碼.
                                                             (line  169)
* b85encode() (於 base64 模組中):        base64 —— Base16、Base32、Base64、Base85 資料編碼.
                                                             (line  159)
* Babyl (mailbox 中的類別):              Babyl.              (line    6)
* BabylMessage (mailbox 中的類別):       BabylMessage.       (line    6)
* back() (於 turtle 模組中):             海龟动作.           (line   23)
* backslash character:                   显式拼接行.         (line    6)
* backslashreplace_errors() (於 codecs 模組中): 错误处理方案.
                                                             (line  126)
* backup() (sqlite3.Connection 的方法):  连接对象（Connection）.
                                                             (line  376)
* backward() (於 turtle 模組中):         海龟动作.           (line   23)
* BadGzipFile:                           gzip --- 对 gzip 格式的支持.
                                                             (line   56)
* BadStatusLine:                         http client --- HTTP 协议客户端.
                                                             (line  155)
* BadZipFile:                            zipfile --- 使用ZIP存档.
                                                             (line   20)
* BadZipfile:                            zipfile --- 使用ZIP存档.
                                                             (line   26)
* Balloon (tkinter.tix 中的類別):        Basic Widgets.      (line    6)
* Barrier (multiprocessing 中的類別):    同步原语.           (line   11)
* Barrier (threading 中的類別):          栅栏对象.           (line   31)
* Barrier() (multiprocessing.managers.SyncManager 的方法): 管理器.
                                                             (line  121)
* base64 (模組):                         base64 —— Base16、Base32、Base64、Base85 資料編碼.
                                                             (line    6)
* base64; encoding:                      base64 —— Base16、Base32、Base64、Base85 資料編碼.
                                                             (line    8)
* BaseCGIHandler (wsgiref.handlers 中的類別): wsgiref handlers -- 服务器/网关基类.
                                                             (line   45)
* BaseCookie (http.cookies 中的類別):    http cookies --- HTTP状态管理.
                                                             (line   34)
* BaseException:                         基类.               (line    8)
* BaseHandler (urllib.request 中的類別): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  221)
* BaseHandler (wsgiref.handlers 中的類別): wsgiref handlers -- 服务器/网关基类.
                                                             (line   73)
* BaseHeader (email.headerregistry 中的類別): email headerregistry 自定义标头对象.
                                                             (line   29)
* BaseHTTPRequestHandler (http.server 中的類別): http server --- HTTP 服务器.
                                                             (line   42)
* BaseManager (multiprocessing.managers 中的類別): 管理器.   (line   19)
* basename() (於 os.path 模組中):        os path --- 常用路径操作.
                                                             (line   54)
* BaseProtocol (asyncio 中的類別):       基础协议.           (line    6)
* BaseProxy (multiprocessing.managers 中的類別): 代理对象.   (line   82)
* BaseRequestHandler (socketserver 中的類別): 请求处理句柄对象.
                                                             (line    6)
* BaseRotatingHandler (logging.handlers 中的類別): BaseRotatingHandler.
                                                             (line   11)
* BaseSelector (selectors 中的類別):     类<2>.              (line   51)
* BaseServer (socketserver 中的類別):    Server 对象<2>.     (line    6)
* basestring (2to3 fixer):               修复器.             (line   59)
* BaseTransport (asyncio 中的類別):      传输层级.           (line    6)
* base_exec_prefix (於 sys 模組中):      sys --- 系统相关的参数和函数.
                                                             (line   90)
* base_prefix (於 sys 模組中):           sys --- 系统相关的参数和函数.
                                                             (line  101)
* basicConfig() (於 logging 模組中):     模块级函数.         (line  196)
* BasicContext (decimal 中的類別):       上下文对象.         (line   42)
* BasicInterpolation (configparser 中的類別): 值的插值.      (line    9)
* BasicTestRunner (test.support 中的類別): test support --- Utilities for the Python test suite.
                                                             (line 1122)
* baudrate() (於 curses 模組中):         函数<4>.            (line   17)
* bbox() (tkinter.ttk.Treeview 的方法):  ttk Treeview.       (line    8)
* BDADDR_ANY (於 socket 模組中):         常数<6>.            (line  230)
* BDADDR_LOCAL (於 socket 模組中):       常数<6>.            (line  230)
* Bdb (bdb 中的類別):                    bdb --- Debugger framework.
                                                             (line   79)
* bdb (模組):                            bdb --- Debugger framework.
                                                             (line    6)
* BdbQuit:                               bdb --- Debugger framework.
                                                             (line   15)
* BDFL:                                  術語表.             (line  145)
* bdist_msi (distutils.command.bdist_msi 中的類別): distutils command bdist_msi --- Build a Microsoft Installer binary package.
                                                             (line    6)
* beep() (於 curses 模組中):             函数<4>.            (line   23)
* Beep() (於 winsound 模組中):           winsound —— Windows 系统的声音播放接口.
                                                             (line   11)
* BEFORE_ASYNC_WITH (opcode):            Python字节码说明.   (line  283)
* begin_fill() (於 turtle 模組中):       填充.               (line   16)
* begin_poly() (於 turtle 模組中):       特殊海龟方法.       (line    6)
* below() (curses.panel.Panel 的方法):   Panel 对象.         (line   16)
* BELOW_NORMAL_PRIORITY_CLASS (於 subprocess 模組中): Windows 常数.
                                                             (line   53)
* benchmarking:                          函数<3>.            (line  159)
* benchmarking <1>:                      函数<3>.            (line  174)
* benchmarking <2>:                      函数<3>.            (line  416)
* Benchmarking:                          timeit --- 测量小代码片段的执行时间.
                                                             (line    8)
* betavariate() (於 random 模組中):      实值分布.           (line   27)
* bgcolor() (於 turtle 模組中):          窗口控制.           (line    6)
* bgpic() (於 turtle 模組中):            窗口控制.           (line   21)
* bias() (於 audioop 模組中):            audioop --- 处理原始音频数据.
                                                             (line   52)
* bidirectional() (於 unicodedata 模組中): unicodedata --- Unicode 数据库.
                                                             (line   45)
* bigaddrspacetest() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  740)
* BigEndianStructure (ctypes 中的類別):  结构化数据类型.     (line   10)
* bigmemtest() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  724)
* bin() (內建函式):                      內建函式.           (line   89)
* Binary (msilib 中的類別):              msilib --- Read and write Microsoft Installer files.
                                                             (line   89)
* Binary (xmlrpc.client 中的類別):       Binary 对象.        (line    6)
* binary file（二進制檔案）:             術語表.             (line  150)
* binary literal:                        数值字面值.         (line    6)
* binary mode:                           內建函式.           (line 1030)
* binary semaphores:                     _thread --- 底层多线程 API.
                                                             (line    6)
* binary; arithmetic; operation:         二元算术运算符.     (line    6)
* binary; bitwise; operation:            二元位运算.         (line    6)
* binary; literals:                      数字类型 --- int float complex.
                                                             (line   14)
* binaryfunc (C 型態):                   Slot Type typedefs. (line  100)
* BinaryIO (typing 中的類別):            其他具象类型.       (line    6)
* BINARY_ADD (opcode):                   Python字节码说明.   (line  149)
* BINARY_AND (opcode):                   Python字节码说明.   (line  169)
* BINARY_FLOOR_DIVIDE (opcode):          Python字节码说明.   (line  137)
* BINARY_LSHIFT (opcode):                Python字节码说明.   (line  161)
* BINARY_MATRIX_MULTIPLY (opcode):       Python字节码说明.   (line  131)
* BINARY_MODULO (opcode):                Python字节码说明.   (line  145)
* BINARY_MULTIPLY (opcode):              Python字节码说明.   (line  127)
* BINARY_OR (opcode):                    Python字节码说明.   (line  177)
* BINARY_POWER (opcode):                 Python字节码说明.   (line  123)
* BINARY_RSHIFT (opcode):                Python字节码说明.   (line  165)
* BINARY_SUBSCR (opcode):                Python字节码说明.   (line  157)
* BINARY_SUBTRACT (opcode):              Python字节码说明.   (line  153)
* BINARY_TRUE_DIVIDE (opcode):           Python字节码说明.   (line  141)
* BINARY_XOR (opcode):                   Python字节码说明.   (line  173)
* binascii (模組):                       binascii --- 二进制和 ASCII 码互转.
                                                             (line    6)
* bind (widgets):                        绑定和事件.         (line    6)
* bind() (asyncore.dispatcher 的方法):   asyncore --- 异步套接字处理器.
                                                             (line  180)
* bind() (inspect.Signature 的方法):     Introspecting callables with the Signature object.
                                                             (line   95)
* bind() (socket.socket 的方法):         套接字对象.         (line   26)
* binding; name:                         名称的绑定.         (line    6)
* binding; name <1>:                     赋值语句.           (line    6)
* bindtextdomain() (於 gettext 模組中):  GNU gettext API.    (line   12)
* bindtextdomain() (於 locale 模組中):   访问信息目录.       (line   14)
* bind_partial() (inspect.Signature 的方法): Introspecting callables with the Signature object.
                                                             (line  102)
* bind_port() (於 test.support.socket_helper 模組中): test support socket_helper --- Utilities for socket tests.
                                                             (line   37)
* bind_textdomain_codeset() (於 gettext 模組中): GNU gettext API.
                                                             (line   23)
* bind_unix_socket() (於 test.support.socket_helper 模組中): test support socket_helper --- Utilities for socket tests.
                                                             (line   54)
* binhex (模組):                         binhex --- 对binhex4文件进行编码和解码.
                                                             (line    6)
* binhex() (於 binhex 模組中):           binhex --- 对binhex4文件进行编码和解码.
                                                             (line   17)
* BinOp (ast 中的類別):                  表达式<2>.          (line   42)
* bisect (模組):                         bisect --- 陣列二分演算法 Array bisection algorithm.
                                                             (line    6)
* bisect() (於 bisect 模組中):           bisect --- 陣列二分演算法 Array bisection algorithm.
                                                             (line   30)
* bisect_left() (於 bisect 模組中):      bisect --- 陣列二分演算法 Array bisection algorithm.
                                                             (line   18)
* bisect_right() (於 bisect 模組中):     bisect --- 陣列二分演算法 Array bisection algorithm.
                                                             (line   30)
* BitAnd (ast 中的類別):                 表达式<2>.          (line   54)
* bitmap() (msilib.Dialog 的方法):       GUI classes.        (line   60)
* BitOr (ast 中的類別):                  表达式<2>.          (line   54)
* bitwise; and:                          二元位运算.         (line   12)
* bitwise; operations:                   整数类型的按位运算. (line    6)
* bitwise; or:                           二元位运算.         (line   20)
* bitwise; xor:                          二元位运算.         (line   16)
* BitXor (ast 中的類別):                 表达式<2>.          (line   54)
* bit_length() (int 的方法):             整数类型的附加方法. (line    9)
* bk() (於 turtle 模組中):               海龟动作.           (line   23)
* bkgd() (curses.window 的方法):         Window 对象.        (line   57)
* bkgdset() (curses.window 的方法):      Window 对象.        (line   67)
* blake2b() (於 hashlib 模組中):         创建哈希对象.       (line    8)
* blake2b, blake2s:                      BLAKE2.             (line    6)
* blake2b.MAX_DIGEST_SIZE (於 hashlib 模組中): 常数<4>.      (line   24)
* blake2b.MAX_KEY_SIZE (於 hashlib 模組中): 常数<4>.         (line   18)
* blake2b.PERSON_SIZE (於 hashlib 模組中): 常数<4>.          (line   12)
* blake2b.SALT_SIZE (於 hashlib 模組中): 常数<4>.            (line    6)
* blake2s() (於 hashlib 模組中):         创建哈希对象.       (line   14)
* blake2s.MAX_DIGEST_SIZE (於 hashlib 模組中): 常数<4>.      (line   26)
* blake2s.MAX_KEY_SIZE (於 hashlib 模組中): 常数<4>.         (line   20)
* blake2s.PERSON_SIZE (於 hashlib 模組中): 常数<4>.          (line   14)
* blake2s.SALT_SIZE (於 hashlib 模組中): 常数<4>.            (line    8)
* blank line:                            空白行.             (line    6)
* block:                                 程序的结构.         (line    6)
* blocked_domains() (http.cookiejar.DefaultCookiePolicy 的方法): DefaultCookiePolicy 对象.
                                                             (line   46)
* BlockingIOError:                       OS 异常.            (line    8)
* BlockingIOError <1>:                   高阶模块接口.       (line   33)
* blocksize (http.client.HTTPConnection 的屬性): HTTPConnection 对象.
                                                             (line   96)
* block_size (hmac.HMAC 的屬性):         hmac --- 基于密钥的消息验证.
                                                             (line   80)
* BNF:                                   标注.               (line    6)
* BNF <1>:                               表达式.             (line    6)
* body() (nntplib.NNTP 的方法):          方法<3>.            (line  243)
* body() (tkinter.simpledialog.Dialog 的方法): tkinter simpledialog --- 标准 Tkinter 输入对话框.
                                                             (line   23)
* body_encode() (email.charset.Charset 的方法): email charset 表示字符集.
                                                             (line  120)
* body_encoding (email.charset.Charset 的屬性): email charset 表示字符集.
                                                             (line   60)
* body_line_iterator() (於 email.iterators 模組中): email iterators 迭代器.
                                                             (line   13)
* BOLD (於 tkinter.font 模組中):         tkinter font --- Tkinter 字体封装.
                                                             (line   15)
* BOM (於 codecs 模組中):                codecs --- 编解码器注册和相关基类.
                                                             (line  203)
* BOM_BE (於 codecs 模組中):             codecs --- 编解码器注册和相关基类.
                                                             (line  203)
* BOM_LE (於 codecs 模組中):             codecs --- 编解码器注册和相关基类.
                                                             (line  203)
* BOM_UTF16 (於 codecs 模組中):          codecs --- 编解码器注册和相关基类.
                                                             (line  203)
* BOM_UTF16_BE (於 codecs 模組中):       codecs --- 编解码器注册和相关基类.
                                                             (line  203)
* BOM_UTF16_LE (於 codecs 模組中):       codecs --- 编解码器注册和相关基类.
                                                             (line  203)
* BOM_UTF32 (於 codecs 模組中):          codecs --- 编解码器注册和相关基类.
                                                             (line  203)
* BOM_UTF32_BE (於 codecs 模組中):       codecs --- 编解码器注册和相关基类.
                                                             (line  203)
* BOM_UTF32_LE (於 codecs 模組中):       codecs --- 编解码器注册和相关基类.
                                                             (line  203)
* BOM_UTF8 (於 codecs 模組中):           codecs --- 编解码器注册和相关基类.
                                                             (line  203)
* bool (內建類別):                       內建函式.           (line  109)
* Boolean; operation:                    布尔运算.           (line    6)
* Boolean; operations:                   逻辑值检测.         (line    6)
* Boolean; operations <1>:               布尔运算 --- and or not.
                                                             (line    6)
* Boolean; type:                         內建函式.           (line  118)
* Boolean; values:                       布尔值.             (line   12)
* BOOLEAN_STATES (configparser.ConfigParser 的屬性): 定制解析器行为.
                                                             (line  213)
* BoolOp (ast 中的類別):                 表达式<2>.          (line   70)
* bootstrap() (於 ensurepip 模組中):     Module API.         (line   13)
* border() (curses.window 的方法):       Window 对象.        (line   74)
* bottom() (curses.panel.Panel 的方法):  Panel 对象.         (line   20)
* bottom_panel() (於 curses.panel 模組中): 函数<5>.          (line    8)
* BoundArguments (inspect 中的類別):     Introspecting callables with the Signature object.
                                                             (line  275)
* BoundaryError:                         email errors 异常和缺陷类.
                                                             (line   32)
* BoundedSemaphore (asyncio 中的類別):   BoundedSemaphore.   (line    6)
* BoundedSemaphore (multiprocessing 中的類別): 同步原语.     (line   17)
* BoundedSemaphore (threading 中的類別): 信号量对象.         (line   62)
* BoundedSemaphore() (multiprocessing.managers.SyncManager 的方法): 管理器.
                                                             (line  128)
* box() (curses.window 的方法):          Window 对象.        (line  111)
* bpformat() (bdb.Breakpoint 的方法):    bdb --- Debugger framework.
                                                             (line   55)
* bpprint() (bdb.Breakpoint 的方法):     bdb --- Debugger framework.
                                                             (line   74)
* Break (ast 中的類別):                  Control flow.       (line  101)
* break (pdb command):                   调试器命令.         (line   56)
* Breakpoint (bdb 中的類別):             bdb --- Debugger framework.
                                                             (line   22)
* breakpoint() (內建函式):               內建函式.           (line  120)
* breakpointhook() (於 sys 模組中):      sys --- 系统相关的参数和函数.
                                                             (line  153)
* breakpoints:                           帮助菜单（命令行和编辑器）.
                                                             (line   25)
* break_anywhere() (bdb.Bdb 的方法):     bdb --- Debugger framework.
                                                             (line  203)
* break_here() (bdb.Bdb 的方法):         bdb --- Debugger framework.
                                                             (line  196)
* break_long_words (textwrap.TextWrapper 的屬性): textwrap --- 文本自动换行与填充.
                                                             (line  219)
* break_on_hyphens (textwrap.TextWrapper 的屬性): textwrap --- 文本自动换行与填充.
                                                             (line  227)
* broadcast_address (ipaddress.IPv4Network 的屬性): 网络对象.
                                                             (line   76)
* broadcast_address (ipaddress.IPv6Network 的屬性): 网络对象.
                                                             (line  277)
* broken (threading.Barrier 的屬性):     栅栏对象.           (line   87)
* BrokenBarrierError:                    栅栏对象.           (line   91)
* BrokenExecutor:                        Exception 类.       (line   14)
* BrokenPipeError:                       OS 异常.            (line   34)
* BrokenProcessPool:                     Exception 类.       (line   34)
* BrokenThreadPool:                      Exception 类.       (line   27)
* BROWSER:                               webbrowser --- 方便的Web浏览器控制器.
                                                             (line   17)
* BROWSER <1>:                           webbrowser --- 方便的Web浏览器控制器.
                                                             (line   79)
* BsdDbShelf (shelve 中的類別):          限制.               (line   42)
* buf (multiprocessing.shared_memory.SharedMemory 的屬性): multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line   65)
* buffer (2to3 fixer):                   修复器.             (line   63)
* buffer (io.TextIOBase 的屬性):         文本 I/O<2>.        (line   28)
* buffer (unittest.TestResult 的屬性):   Loading and running tests.
                                                             (line  276)
* buffer interface; (see buffer protocol): 迭代器协议.       (line   43)
* buffer object; (see buffer protocol):  迭代器协议.         (line   42)
* buffer protocol:                       迭代器协议.         (line   43)
* buffer protocol; binary sequence types: printf 风格的字符串格式化.
                                                             (line  161)
* buffer protocol; str (built-in class): 文本序列类型 --- str.
                                                             (line   51)
* buffer size, I/O:                      內建函式.           (line 1030)
* BufferedIOBase (io 中的類別):          I/O 基类.           (line  189)
* BufferedProtocol (asyncio 中的類別):   基础协议.           (line   14)
* BufferedRandom (io 中的類別):          缓冲流.             (line  118)
* BufferedReader (io 中的類別):          缓冲流.             (line   51)
* BufferedRWPair (io 中的類別):          缓冲流.             (line  132)
* BufferedWriter (io 中的類別):          缓冲流.             (line   84)
* BufferError:                           基类.               (line   42)
* BufferingHandler (logging.handlers 中的類別): MemoryHandler.
                                                             (line   15)
* BufferTooShort:                        Process 和异常.     (line  179)
* buffer_info() (array.array 的方法):    array --- 高效率的數值型態陣列.
                                                             (line  108)
* buffer_size (xml.parsers.expat.xmlparser 的屬性): XMLParser对象<2>.
                                                             (line   70)
* buffer_text (xml.parsers.expat.xmlparser 的屬性): XMLParser对象<2>.
                                                             (line   76)
* buffer_updated() (asyncio.BufferedProtocol 的方法): 缓冲流协议.
                                                             (line   26)
* buffer_used (xml.parsers.expat.xmlparser 的屬性): XMLParser对象<2>.
                                                             (line   83)
* bufsize() (ossaudiodev.oss_audio_device 的方法): 音频设备对象.
                                                             (line  197)
* BUILD_CONST_KEY_MAP (opcode):          Python字节码说明.   (line  470)
* BUILD_LIST (opcode):                   Python字节码说明.   (line  454)
* BUILD_MAP (opcode):                    Python字节码说明.   (line  462)
* build_opener() (於 urllib.request 模組中): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  102)
* build_py (distutils.command.build_py 中的類別): distutils command build_py --- Build the py/ pyc files of a package.
                                                             (line    6)
* build_py_2to3 (distutils.command.build_py 中的類別): distutils command build_py --- Build the py/ pyc files of a package.
                                                             (line    8)
* BUILD_SET (opcode):                    Python字节码说明.   (line  458)
* BUILD_SLICE (opcode):                  Python字节码说明.   (line  727)
* BUILD_STRING (opcode):                 Python字节码说明.   (line  477)
* BUILD_TUPLE (opcode):                  Python字节码说明.   (line  450)
* built-in function; call:               调用.               (line  105)
* built-in method; call:                 调用.               (line  105)
* built-in; method:                      标准类型层级结构.   (line  386)
* built-in; types:                       內建型態.           (line    8)
* BuiltinFunctionType (於 types 模組中): 标准解释器类型.     (line   71)
* BuiltinImporter (importlib.machinery 中的類別): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line   57)
* BuiltinMethodType (於 types 模組中):   标准解释器类型.     (line   71)
* builtins (模組):                       builtins --- 内建对象.
                                                             (line    6)
* builtin_module_names (於 sys 模組中):  sys --- 系统相关的参数和函数.
                                                             (line  117)
* ButtonBox (tkinter.tix 中的類別):      Basic Widgets.      (line   13)
* buttonbox() (tkinter.simpledialog.Dialog 的方法): tkinter simpledialog --- 标准 Tkinter 输入对话框.
                                                             (line   28)
* bye() (於 turtle 模組中):              Screen 专有方法 而非继承自 TurtleScreen.
                                                             (line    6)
* byref() (於 ctypes 模組中):            工具函数.           (line   17)
* byte:                                  标准类型层级结构.   (line  143)
* bytearray:                             标准类型层级结构.   (line  164)
* bytearray (內建類別):                  bytearray 对象.     (line    8)
* bytearray; formatting:                 printf 风格的字节串格式化.
                                                             (line    6)
* bytearray; interpolation:              printf 风格的字节串格式化.
                                                             (line    6)
* bytearray; methods:                    bytes 和 bytearray 操作.
                                                             (line    6)
* bytecode:                              标准类型层级结构.   (line  506)
* Bytecode (dis 中的類別):               字节码分析.         (line   11)
* Bytecode.codeobj (於 dis 模組中):      字节码分析.         (line   33)
* Bytecode.first_line (於 dis 模組中):   字节码分析.         (line   37)
* BytecodeTestCase (test.support.bytecode_helper 中的類別): test support bytecode_helper --- Support tools for testing correct bytecode generation.
                                                             (line   13)
* BYTECODE_SUFFIXES (於 importlib.machinery 模組中): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line   34)
* bytecode（位元組碼）:                  術語表.             (line  176)
* byteorder (於 sys 模組中):             sys --- 系统相关的参数和函数.
                                                             (line  112)
* bytes:                                 标准类型层级结构.   (line  143)
* bytes (uuid.UUID 的屬性):              uuid --- RFC 4122 定义的UUID对象.
                                                             (line   74)
* bytes (內建類別):                      bytes 对象.         (line   10)
* bytes literal:                         字面值.             (line    8)
* bytes-like object（類位元組串物件）:   術語表.             (line  161)
* bytes; formatting:                     printf 风格的字节串格式化.
                                                             (line    6)
* bytes; interpolation:                  printf 风格的字节串格式化.
                                                             (line    6)
* bytes; methods:                        bytes 和 bytearray 操作.
                                                             (line    6)
* bytes; str (built-in class):           文本序列类型 --- str.
                                                             (line   51)
* BytesFeedParser (email.parser 中的類別): FeedParser API.   (line   24)
* BytesGenerator (email.generator 中的類別): email generator 生成 MIME 文档.
                                                             (line   33)
* BytesHeaderParser (email.parser 中的類別): Parser API.     (line   58)
* BytesIO (io 中的類別):                 缓冲流.             (line    8)
* BytesParser (email.parser 中的類別):   Parser API.         (line   14)
* ByteString (collections.abc 中的類別): 容器抽象基类.       (line  155)
* ByteString (typing 中的類別):          collections abc 对应的容器.
                                                             (line   13)
* byteswap() (array.array 的方法):       array --- 高效率的數值型態陣列.
                                                             (line  121)
* byteswap() (於 audioop 模組中):        audioop --- 处理原始音频数据.
                                                             (line   57)
* BytesWarning:                          警告.               (line   62)
* bytes_le (uuid.UUID 的屬性):           uuid --- RFC 4122 定义的UUID对象.
                                                             (line   78)
* byte_compile() (於 distutils.util 模組中): distutils util --- Miscellaneous other utility functions.
                                                             (line  147)
* bz2 (模組):                            bz2 --- 对 bzip2 压缩算法的支持.
                                                             (line    6)
* BZ2Compressor (bz2 中的類別):          增量压缩和解压.     (line    6)
* BZ2Decompressor (bz2 中的類別):        增量压缩和解压.     (line   28)
* BZ2File (bz2 中的類別):                文件压缩和解压.     (line   37)
* C:                                     字符串与字节串字面值.
                                                             (line   59)
* C-contiguous:                          形状，步幅，子偏移量.
                                                             (line   25)
* C-contiguous <1>:                      術語表.             (line  242)
* C14NWriterTarget (xml.etree.ElementTree 中的類別): TreeBuilder 对象.
                                                             (line   82)
* C; language:                           标准类型层级结构.   (line    6)
* C; language <1>:                       标准类型层级结构.   (line   84)
* C; language <2>:                       标准类型层级结构.   (line  376)
* C; language <3>:                       比较运算.           (line    6)
* C; language <4>:                       数字类型 --- int float complex.
                                                             (line    6)
* C; language <5>:                       数字类型 --- int float complex.
                                                             (line   92)
* C; structures:                         struct --- 将字节串解读为打包的二进制数据.
                                                             (line    8)
* CAB (msilib 中的類別):                 CAB Objects.        (line    6)
* cache() (於 functools 模組中):         functools --- 高阶函数和可调用对象上的操作.
                                                             (line   15)
* cached (importlib.machinery.ModuleSpec 的屬性): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  351)
* cached_property() (於 functools 模組中): functools --- 高阶函数和可调用对象上的操作.
                                                             (line   38)
* CacheFTPHandler (urllib.request 中的類別): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  356)
* cache_from_source() (於 imp 模組中):   imp —— 由代码内部访问 import 。.
                                                             (line  195)
* cache_from_source() (於 importlib.util 模組中): importlib util —— 导入器的工具程序代码.
                                                             (line   19)
* calcobjsize() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  600)
* calcsize() (於 struct 模組中):         函数和异常.         (line   48)
* calcvobjsize() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  605)
* Calendar (calendar 中的類別):          calendar --- 日历相关函数.
                                                             (line   21)
* calendar (模組):                       calendar --- 日历相关函数.
                                                             (line    6)
* calendar() (於 calendar 模組中):       calendar --- 日历相关函数.
                                                             (line  305)
* call:                                  切片.               (line   30)
* Call (ast 中的類別):                   表达式<2>.          (line  122)
* call() (於 subprocess 模組中):         较旧的高阶 API.     (line    9)
* call() (於 unittest.mock 模組中):      call.               (line    6)
* call; instance:                        模拟可调用对象.     (line    8)
* Callable (collections.abc 中的類別):   容器抽象基类.       (line  116)
* Callable (於 typing 模組中):           特殊形式.           (line   73)
* callable() (內建函式):                 內建函式.           (line  175)
* CallableProxyType (於 weakref 模組中): weakref --- 弱引用. (line  251)
* callback (optparse.Option 的屬性):     Option attributes.  (line   60)
* callback() (contextlib.ExitStack 的方法): 工具.            (line  380)
* callbacks (於 gc 模組中):              gc --- 垃圾回收器接口.
                                                             (line  208)
* callback_args (optparse.Option 的屬性): Option attributes. (line   66)
* callback_kwargs (optparse.Option 的屬性): Option attributes.
                                                             (line   66)
* callback（回呼）:                      術語表.             (line  189)
* called (unittest.mock.Mock 的屬性):    Mock 类.            (line  277)
* CalledProcessError:                    使用 subprocess 模块.
                                                             (line  170)
* calloc():                              總覽<2>.            (line   23)
* call_args (unittest.mock.Mock 的屬性): Mock 类.            (line  396)
* call_args_list (unittest.mock.Mock 的屬性): Mock 类.       (line  440)
* call_at() (asyncio.loop 的方法):       调度延迟回调.       (line   34)
* call_count (unittest.mock.Mock 的屬性): Mock 类.           (line  289)
* call_exception_handler() (asyncio.loop 的方法): 错误处理API.
                                                             (line   34)
* CALL_FUNCTION (opcode):                Python字节码说明.   (line  656)
* CALL_FUNCTION_EX (opcode):             Python字节码说明.   (line  678)
* CALL_FUNCTION_KW (opcode):             Python字节码说明.   (line  665)
* call_later() (asyncio.loop 的方法):    调度延迟回调.       (line    9)
* call_list() (unittest.mock.call 的方法): call.             (line   20)
* CALL_METHOD (opcode):                  Python字节码说明.   (line  699)
* call_soon() (asyncio.loop 的方法):     安排回调.           (line    6)
* call_soon_threadsafe() (asyncio.loop 的方法): 安排回调.    (line   21)
* call_tracing() (於 sys 模組中):        sys --- 系统相关的参数和函数.
                                                             (line  123)
* cancel() (asyncio.Future 的方法):      Future 对象<2>.     (line   99)
* cancel() (asyncio.Handle 的方法):      回调处理.           (line   11)
* cancel() (asyncio.Task 的方法):        Task 对象.          (line   46)
* cancel() (concurrent.futures.Future 的方法): Future 对象.  (line   14)
* cancel() (sched.scheduler 的方法):     调度器对象.         (line   36)
* cancel() (threading.Timer 的方法):     定时器对象.         (line   31)
* cancel() (tkinter.dnd.DndHandler 的方法): tkinter dnd --- 拖放操作支持.
                                                             (line   42)
* cancelled() (asyncio.Future 的方法):   Future 对象<2>.     (line   60)
* cancelled() (asyncio.Handle 的方法):   回调处理.           (line   16)
* cancelled() (asyncio.Task 的方法):     Task 对象.          (line   97)
* cancelled() (concurrent.futures.Future 的方法): Future 对象.
                                                             (line   20)
* CancelledError:                        Exception 类.       (line    6)
* CancelledError <1>:                    异常<9>.            (line   16)
* cancel_command() (tkinter.filedialog.FileDialog 的方法): 原生 加载/保存 对话框.
                                                             (line   73)
* cancel_dump_traceback_later() (於 faulthandler 模組中): 一定时间后转储跟踪数据。.
                                                             (line   26)
* cancel_join_thread() (multiprocessing.Queue 的方法): 管道和队列.
                                                             (line  156)
* CannotSendHeader:                      http client --- HTTP 协议客户端.
                                                             (line  147)
* CannotSendRequest:                     http client --- HTTP 协议客户端.
                                                             (line  143)
* canonic() (bdb.Bdb 的方法):            bdb --- Debugger framework.
                                                             (line   99)
* canonical() (decimal.Context 的方法):  上下文对象.         (line  204)
* canonical() (decimal.Decimal 的方法):  Decimal 对象.       (line  118)
* canonicalize() (於 xml.etree.ElementTree 模組中): 函数<7>. (line    6)
* CAN_BCM (於 socket 模組中):            常数<6>.            (line  102)
* can_change_color() (於 curses 模組中): 函数<4>.            (line   27)
* can_fetch() (urllib.robotparser.RobotFileParser 的方法): urllib robotparser --- robots txt 语法分析程序.
                                                             (line   32)
* CAN_ISOTP (於 socket 模組中):          常数<6>.            (line  139)
* CAN_J1939 (於 socket 模組中):          常数<6>.            (line  148)
* CAN_RAW_FD_FRAMES (於 socket 模組中):  常数<6>.            (line  116)
* CAN_RAW_JOIN_FILTERS (於 socket 模組中): 常数<6>.          (line  128)
* can_symlink() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  615)
* can_write_eof() (asyncio.StreamWriter 的方法): StreamWriter.
                                                             (line   43)
* can_write_eof() (asyncio.WriteTransport 的方法): 只写传输. (line   12)
* can_xattr() (於 test.support 模組中):  test support --- Utilities for the Python test suite.
                                                             (line  619)
* capa() (poplib.POP3 的方法):           POP3 对象.          (line   22)
* capitalize() (bytearray 的方法):       bytes 和 bytearray 操作.
                                                             (line  391)
* capitalize() (bytes 的方法):           bytes 和 bytearray 操作.
                                                             (line  391)
* capitalize() (str 的方法):             字符串的方法<2>.    (line   19)
* captured_stderr() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  455)
* captured_stdin() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  455)
* captured_stdout() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  455)
* captureWarnings() (於 logging 模組中): 与警告模块集成.     (line    9)
* capwords() (於 string 模組中):         辅助函数.           (line    6)
* casefold() (str 的方法):               字符串的方法<2>.    (line   26)
* cast() (memoryview 的方法):            内存视图.           (line  246)
* cast() (於 ctypes 模組中):             工具函数.           (line   29)
* cast() (於 typing 模組中):             函数与装饰器.       (line    6)
* cat() (於 nis 模組中):                 nis --- Sun 的 NIS 黄页 接口.
                                                             (line   26)
* catch_threading_exception() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  868)
* catch_unraisable_exception() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  903)
* catch_warnings (warnings 中的類別):    可用的上下文管理器. (line    6)
* category() (於 unicodedata 模組中):    unicodedata --- Unicode 数据库.
                                                             (line   41)
* cbreak() (於 curses 模組中):           函数<4>.            (line   31)
* CC:                                    新增，改进和弃用的模块<4>.
                                                             (line   58)
* ccc() (ftplib.FTP_TLS 的方法):         FTP_TLS 对象.       (line   21)
* CCompiler (distutils.ccompiler 中的類別): distutils ccompiler --- CCompiler基类.
                                                             (line   66)
* cdf() (statistics.NormalDist 的方法):  NormalDist 对象.    (line   67)
* CDLL (ctypes 中的類別):                加载动态链接库.     (line    9)
* ceil() (in module math):               数字类型 --- int float complex.
                                                             (line   92)
* ceil() (於 math 模組中):               数论与表示函数.     (line    6)
* CellType (於 types 模組中):            标准解释器类型.     (line   61)
* center() (bytearray 的方法):           bytes 和 bytearray 操作.
                                                             (line  241)
* center() (bytes 的方法):               bytes 和 bytearray 操作.
                                                             (line  241)
* center() (str 的方法):                 字符串的方法<2>.    (line   40)
* CertificateError:                      异常<12>.           (line   83)
* certificates:                          SSL 上下文.         (line  588)
* CERT_NONE (於 ssl 模組中):             常量<3>.            (line   11)
* CERT_OPTIONAL (於 ssl 模組中):         常量<3>.            (line   24)
* CERT_REQUIRED (於 ssl 模組中):         常量<3>.            (line   39)
* cert_store_stats() (ssl.SSLContext 的方法): SSL 上下文.    (line   63)
* cert_time_to_seconds() (於 ssl 模組中): 证书处理.          (line   42)
* CFLAGS:                                新增，改进和弃用的模块<4>.
                                                             (line   58)
* CFLAGS <1>:                            Tweaking compiler/linker flags.
                                                             (line   66)
* CFLAGS <2>:                            Tweaking compiler/linker flags.
                                                             (line   67)
* CFUNCTYPE() (於 ctypes 模組中):        函数原型.           (line   12)
* cget() (tkinter.font.Font 的方法):     tkinter font --- Tkinter 字体封装.
                                                             (line   49)
* cgi (模組):                            cgi --- 通用网关接口支持.
                                                             (line    6)
* CGI; debugging:                        调试 CGI 脚本.      (line    6)
* CGI; exceptions:                       cgitb --- 用于 CGI 脚本的回溯管理器.
                                                             (line    8)
* CGI; protocol:                         cgi --- 通用网关接口支持.
                                                             (line    8)
* CGI; security:                         对于安全性的关注.   (line    6)
* CGI; tracebacks:                       cgitb --- 用于 CGI 脚本的回溯管理器.
                                                             (line    8)
* CGIHandler (wsgiref.handlers 中的類別): wsgiref handlers -- 服务器/网关基类.
                                                             (line   10)
* CGIHTTPRequestHandler (http.server 中的類別): http server --- HTTP 服务器.
                                                             (line  383)
* cgitb (模組):                          cgitb --- 用于 CGI 脚本的回溯管理器.
                                                             (line    6)
* CGIXMLRPCRequestHandler (xmlrpc.server 中的類別): xmlrpc server --- 基本 XML-RPC 服务器.
                                                             (line   40)
* cgi_directories (http.server.CGIHTTPRequestHandler 的屬性): http server --- HTTP 服务器.
                                                             (line  404)
* chain() (於 itertools 模組中):         Itertool函数.       (line   79)
* chaining; comparisons:                 比较运算.           (line   18)
* chaining; comparisons <1>:             比较.               (line    6)
* ChainMap (collections 中的類別):       ChainMap objects.   (line   14)
* ChainMap (typing 中的類別):            collections 对应类型.
                                                             (line   26)
* change_cwd() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  489)
* change_root() (於 distutils.util 模組中): distutils util --- Miscellaneous other utility functions.
                                                             (line   84)
* channels() (ossaudiodev.oss_audio_device 的方法): 音频设备对象.
                                                             (line  117)
* CHANNEL_BINDING_TYPES (於 ssl 模組中): 常量<3>.            (line  392)
* channel_class (smtpd.SMTPServer 的屬性): SMTPServer 对象.  (line   67)
* character:                             标准类型层级结构.   (line  122)
* character <1>:                         抽取.               (line   29)
* character <2>:                         unicodedata --- Unicode 数据库.
                                                             (line    6)
* CharacterDataHandler() (xml.parsers.expat.xmlparser 的方法): XMLParser对象<2>.
                                                             (line  200)
* characters() (xml.sax.handler.ContentHandler 的方法): ContentHandler 对象.
                                                             (line  108)
* characters_written (BlockingIOError 的屬性): OS 异常.      (line   17)
* Charset (email.charset 中的類別):      email charset 表示字符集.
                                                             (line   22)
* charset() (gettext.NullTranslations 的方法): NullTranslations 类.
                                                             (line   71)
* CHAR_MAX (於 locale 模組中):           locale --- 国际化服务.
                                                             (line  417)
* chdir() (於 os 模組中):                文件和目录.         (line   97)
* check (lzma.LZMADecompressor 的屬性):  在内存中压缩和解压缩数据.
                                                             (line  127)
* check() (imaplib.IMAP4 的方法):        IMAP4 对象.         (line   49)
* check() (於 tabnanny 模組中):          tabnanny --- 模糊缩进检测.
                                                             (line   16)
* checkbox() (msilib.Dialog 的方法):     GUI classes.        (line   78)
* checkcache() (於 linecache 模組中):    linecache --- 随机读写文本行.
                                                             (line   36)
* CHECKED_HASH (py_compile.PycInvalidationMode 的屬性): py_compile --- 编译 Python 源文件.
                                                             (line   88)
* checkfuncname() (於 bdb 模組中):       bdb --- Debugger framework.
                                                             (line  385)
* CheckList (tkinter.tix 中的類別):      Hierarchical ListBox.
                                                             (line   13)
* checksizeof() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  610)
* checksum; Cyclic Redundancy Check:     zlib --- 与 gzip 兼容的压缩.
                                                             (line   89)
* check_call() (於 subprocess 模組中):   较旧的高阶 API.     (line   32)
* check_environ() (於 distutils.util 模組中): distutils util --- Miscellaneous other utility functions.
                                                             (line   91)
* check_free_after_iterating() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  976)
* check_hostname (ssl.SSLContext 的屬性): SSL 上下文.        (line  428)
* check_impl_detail() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  347)
* check_no_resource_warning() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  424)
* check_output() (doctest.OutputChecker 的方法): OutputChecker 对象.
                                                             (line   15)
* check_output() (於 subprocess 模組中): 较旧的高阶 API.     (line   59)
* check_returncode() (subprocess.CompletedProcess 的方法): 使用 subprocess 模块.
                                                             (line  108)
* check_syntax_error() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  750)
* check_syntax_warning() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  761)
* check_unused_args() (string.Formatter 的方法): 自定义字符串格式化.
                                                             (line   73)
* check_warnings() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  356)
* check__all__() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  988)
* chflags() (於 os 模組中):              文件和目录.         (line  114)
* chgat() (curses.window 的方法):        Window 对象.        (line  116)
* childNodes (xml.dom.Node 的屬性):      节点对象.           (line   41)
* ChildProcessError:                     OS 异常.            (line   22)
* children (pyclbr.Class 的屬性):        Class 对象.         (line   31)
* children (pyclbr.Function 的屬性):     函式物件.           (line   30)
* chmod() (pathlib.Path 的方法):         方法<2>.            (line   49)
* chmod() (於 os 模組中):                文件和目录.         (line  154)
* choice() (於 random 模組中):           序列用函数.         (line    6)
* choice() (於 secrets 模組中):          亂數.               (line   14)
* choices (optparse.Option 的屬性):      Option attributes.  (line   55)
* choices() (於 random 模組中):          序列用函数.         (line   11)
* Chooser (tkinter.colorchooser 中的類別): tkinter colorchooser --- 颜色选择对话框.
                                                             (line   14)
* chown() (於 os 模組中):                文件和目录.         (line  213)
* chown() (於 shutil 模組中):            目录和文件操作.     (line  298)
* chr() (內建函式):                      內建函式.           (line  186)
* chroot() (於 os 模組中):               文件和目录.         (line  235)
* Chunk (chunk 中的類別):                chunk --- 读取 IFF 分块数据.
                                                             (line   45)
* chunk (模組):                          chunk --- 读取 IFF 分块数据.
                                                             (line    6)
* cipher() (ssl.SSLSocket 的方法):       SSL 套接字.         (line  181)
* cipher; DES:                           crypt —— 检查 Unix 口令的函数.
                                                             (line    8)
* circle() (於 turtle 模組中):           海龟动作.           (line  169)
* CIRCUMFLEX (於 token 模組中):          token --- 与Python解析树一起使用的常量.
                                                             (line  150)
* CIRCUMFLEXEQUAL (於 token 模組中):     token --- 与Python解析树一起使用的常量.
                                                             (line  194)
* Clamped (decimal 中的類別):            信号.               (line   17)
* Class (symtable 中的類別):             符号表的查看.       (line   82)
* Class browser:                         文件菜单 （命令行和编辑器）.
                                                             (line   22)
* class instance; attribute:             标准类型层级结构.   (line  463)
* class instance; attribute; assignment: 标准类型层级结构.   (line  479)
* class instance; call:                  调用.               (line  114)
* class object; call:                    标准类型层级结构.   (line  444)
* class object; call <1>:                标准类型层级结构.   (line  452)
* class object; call <2>:                调用.               (line  110)
* class variable（類別變數）:            術語表.             (line  199)
* class; attribute:                      标准类型层级结构.   (line  444)
* class; attribute; assignment:          标准类型层级结构.   (line  450)
* class; body:                           执行类主体.         (line    6)
* class; constructor:                    基本定制.           (line   33)
* class; definition:                     return 语句.        (line    6)
* class; definition <1>:                 类定义.             (line    6)
* class; instance:                       标准类型层级结构.   (line  463)
* class; name:                           类定义.             (line    6)
* ClassDef (ast 中的類別):               Function and class definitions.
                                                             (line  177)
* classmethod() (內建函式):              內建函式.           (line  195)
* ClassMethodDescriptorType (於 types 模組中): 标准解释器类型.
                                                             (line   97)
* ClassVar (於 typing 模組中):           特殊形式.           (line  153)
* class（類別）:                         術語表.             (line  194)
* clause:                                复合语句.           (line   15)
* CLD_CONTINUED (於 os 模組中):          进程管理.           (line  683)
* CLD_DUMPED (於 os 模組中):             进程管理.           (line  683)
* CLD_EXITED (於 os 模組中):             进程管理.           (line  683)
* CLD_KILLED (於 os 模組中):             进程管理.           (line  683)
* CLD_STOPPED (於 os 模組中):            进程管理.           (line  683)
* CLD_TRAPPED (於 os 模組中):            进程管理.           (line  683)
* clean() (mailbox.Maildir 的方法):      Maildir.            (line   69)
* cleandoc() (於 inspect 模組中):        Retrieving source code.
                                                             (line   65)
* CleanImport (test.support 中的類別):   test support --- Utilities for the Python test suite.
                                                             (line 1080)
* cleanup functions:                     行程（Process）控制.
                                                             (line   32)
* clear (pdb command):                   调试器命令.         (line   75)
* Clear Breakpoint:                      帮助菜单（命令行和编辑器）.
                                                             (line   26)
* clear() (asyncio.Event 的方法):        Event.              (line   56)
* clear() (collections.deque 的方法):    deque 对象.         (line   35)
* clear() (curses.window 的方法):        Window 对象.        (line  129)
* clear() (dict 的方法):                 映射类型 --- dict.  (line  125)
* clear() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  565)
* clear() (frame 的方法):                标准类型层级结构.   (line  575)
* clear() (frozenset 的方法):            集合类型 --- set frozenset.
                                                             (line  193)
* clear() (http.cookiejar.CookieJar 的方法): CookieJar 和 FileCookieJar 对象.
                                                             (line   69)
* clear() (mailbox.Mailbox 的方法):      Mailbox 对象.       (line  165)
* clear() (sequence method):             可变序列类型.       (line   14)
* clear() (threading.Event 的方法):      事件对象.           (line   32)
* clear() (xml.etree.ElementTree.Element 的方法): 元素对象.  (line   48)
* clear() (於 turtle 模組中):            更多绘图控制.       (line   22)
* clearcache() (於 linecache 模組中):    linecache --- 随机读写文本行.
                                                             (line   31)
* ClearData() (msilib.Record 的方法):    Record Objects.     (line   37)
* clearok() (curses.window 的方法):      Window 对象.        (line  134)
* clearscreen() (於 turtle 模組中):      窗口控制.           (line   42)
* clearstamp() (於 turtle 模組中):       海龟动作.           (line  235)
* clearstamps() (於 turtle 模組中):      海龟动作.           (line  254)
* clear_all_breaks() (bdb.Bdb 的方法):   bdb --- Debugger framework.
                                                             (line  304)
* clear_all_file_breaks() (bdb.Bdb 的方法): bdb --- Debugger framework.
                                                             (line  299)
* clear_bpbynumber() (bdb.Bdb 的方法):   bdb --- Debugger framework.
                                                             (line  293)
* clear_break() (bdb.Bdb 的方法):        bdb --- Debugger framework.
                                                             (line  288)
* clear_cache() (zoneinfo.ZoneInfo 的類別成員): ZoneInfo 类. (line   49)
* clear_cache() (於 filecmp 模組中):     filecmp --- 文件及目录的比较.
                                                             (line   49)
* clear_content() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  569)
* clear_flags() (decimal.Context 的方法): 上下文对象.        (line  127)
* clear_frames() (於 traceback 模組中):  traceback --- 打印或检索堆栈回溯.
                                                             (line  147)
* clear_history() (於 readline 模組中):  历史列表.           (line    8)
* clear_session_cookies() (http.cookiejar.CookieJar 的方法): CookieJar 和 FileCookieJar 对象.
                                                             (line   80)
* clear_traces() (於 tracemalloc 模組中): 函数<10>.          (line    6)
* clear_traps() (decimal.Context 的方法): 上下文对象.        (line  131)
* Client() (於 multiprocessing.connection 模組中): 监听器及客户端.
                                                             (line   32)
* client_address (http.server.BaseHTTPRequestHandler 的屬性): http server --- HTTP 服务器.
                                                             (line   57)
* CLOCK_BOOTTIME (於 time 模組中):       Clock ID 常量.      (line    9)
* clock_getres() (於 time 模組中):       函数<3>.            (line   35)
* clock_gettime() (於 time 模組中):      函数<3>.            (line   44)
* clock_gettime_ns() (於 time 模組中):   函数<3>.            (line   53)
* CLOCK_HIGHRES (於 time 模組中):        Clock ID 常量.      (line   22)
* CLOCK_MONOTONIC (於 time 模組中):      Clock ID 常量.      (line   31)
* CLOCK_MONOTONIC_RAW (於 time 模組中):  Clock ID 常量.      (line   39)
* CLOCK_PROCESS_CPUTIME_ID (於 time 模組中): Clock ID 常量.  (line   49)
* CLOCK_PROF (於 time 模組中):           Clock ID 常量.      (line   57)
* CLOCK_REALTIME (於 time 模組中):       Clock ID 常量.      (line  104)
* clock_settime() (於 time 模組中):      函数<3>.            (line   61)
* clock_settime_ns() (於 time 模組中):   函数<3>.            (line   70)
* CLOCK_TAI (於 time 模組中):            Clock ID 常量.      (line   65)
* CLOCK_THREAD_CPUTIME_ID (於 time 模組中): Clock ID 常量.   (line   76)
* CLOCK_UPTIME (於 time 模組中):         Clock ID 常量.      (line   84)
* CLOCK_UPTIME_RAW (於 time 模組中):     Clock ID 常量.      (line   93)
* clone() (email.generator.BytesGenerator 的方法): email generator 生成 MIME 文档.
                                                             (line   92)
* clone() (email.generator.Generator 的方法): email generator 生成 MIME 文档.
                                                             (line  173)
* clone() (email.policy.Policy 的方法):  email policy Policy 对象.
                                                             (line  168)
* clone() (pipes.Template 的方法):       模板对象.           (line   12)
* clone() (於 turtle 模組中):            特殊海龟方法.       (line   30)
* cloneNode() (xml.dom.Node 的方法):     节点对象.           (line  127)
* close() (aifc.aifc 的方法):            aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line  101)
* close() (asyncio.AbstractChildWatcher 的方法): 进程监视器. (line   68)
* close() (asyncio.BaseTransport 的方法): 基础传输.          (line    6)
* close() (asyncio.loop 的方法):         运行和停止循环.     (line   40)
* close() (asyncio.Server 的方法):       Server 对象.        (line   27)
* close() (asyncio.StreamWriter 的方法): StreamWriter.       (line   34)
* close() (asyncio.SubprocessTransport 的方法): 子进程传输.  (line   53)
* close() (asyncore.dispatcher 的方法):  asyncore --- 异步套接字处理器.
                                                             (line  196)
* close() (chunk.Chunk 的方法):          chunk --- 读取 IFF 分块数据.
                                                             (line   68)
* close() (contextlib.ExitStack 的方法): 工具.               (line  412)
* close() (coroutine 的方法):            协程对象.           (line   42)
* close() (dbm.dumb.dumbdbm 的方法):     dbm dumb --- 便携式 DBM 实现.
                                                             (line   69)
* close() (dbm.gnu.gdbm 的方法):         dbm gnu --- GNU 对 dbm 的重解析.
                                                             (line   99)
* close() (dbm.ndbm.ndbm 的方法):        dbm ndbm --- 基于 ndbm 的接口.
                                                             (line   54)
* close() (distutils.text_file.TextFile 的方法): distutils text_file --- The TextFile class.
                                                             (line   96)
* close() (email.parser.BytesFeedParser 的方法): FeedParser API.
                                                             (line   56)
* close() (ftplib.FTP 的方法):           FTP 对象.           (line  205)
* close() (generator 的方法):            生成器-迭代器的方法.
                                                             (line   38)
* close() (html.parser.HTMLParser 的方法): HTMLParser 方法.  (line   14)
* close() (http.client.HTTPConnection 的方法): HTTPConnection 对象.
                                                             (line   92)
* close() (imaplib.IMAP4 的方法):        IMAP4 对象.         (line   53)
* close() (in module os):                Sub-interpreter support.
                                                             (line   76)
* close() (io.IOBase 的方法):            I/O 基类.           (line   39)
* close() (logging.FileHandler 的方法):  FileHandler.        (line   24)
* close() (logging.Handler 的方法):      处理器对象.         (line   65)
* close() (logging.handlers.MemoryHandler 的方法): MemoryHandler.
                                                             (line   48)
* close() (logging.handlers.NTEventLogHandler 的方法): NTEventLogHandler.
                                                             (line   23)
* close() (logging.handlers.SocketHandler 的方法): SocketHandler.
                                                             (line   17)
* close() (logging.handlers.SysLogHandler 的方法): SysLogHandler.
                                                             (line   34)
* close() (mailbox.Mailbox 的方法):      Mailbox 对象.       (line  213)
* close() (mailbox.Maildir 的方法):      Maildir.            (line   96)
* close() (mailbox.MH 的方法):           MH.                 (line   93)
* close() (mmap.mmap 的方法):            mmap --- 内存映射文件支持.
                                                             (line  143)
* Close() (msilib.Database 的方法):      Database Objects.   (line   22)
* Close() (msilib.View 的方法):          View Objects.       (line   35)
* close() (multiprocessing.connection.Connection 的方法): 连接（Connection）对象.
                                                             (line   32)
* close() (multiprocessing.connection.Listener 的方法): 监听器及客户端.
                                                             (line   80)
* close() (multiprocessing.pool.Pool 的方法): 进程池.        (line  139)
* close() (multiprocessing.Process 的方法): Process 和异常.  (line  146)
* close() (multiprocessing.Queue 的方法): 管道和队列.        (line  139)
* close() (multiprocessing.shared_memory.SharedMemory 的方法): multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line   49)
* close() (multiprocessing.SimpleQueue 的方法): 管道和队列.  (line  177)
* close() (os.scandir 的方法):           文件和目录.         (line  685)
* close() (ossaudiodev.oss_audio_device 的方法): 音频设备对象.
                                                             (line   19)
* close() (ossaudiodev.oss_mixer_device 的方法): Mixer Device Objects.
                                                             (line    8)
* close() (select.devpoll 的方法):       /dev/poll 轮询对象. (line   12)
* close() (select.epoll 的方法):         边缘触发和水平触发的轮询 epoll 对象.
                                                             (line   63)
* close() (select.kqueue 的方法):        Kqueue 对象.        (line    6)
* close() (selectors.BaseSelector 的方法): 类<2>.            (line  119)
* close() (shelve.Shelf 的方法):         shelve --- Python 对象持久化.
                                                             (line   58)
* close() (socket.socket 的方法):        套接字对象.         (line   34)
* close() (sqlite3.Connection 的方法):   连接对象（Connection）.
                                                             (line   41)
* close() (sqlite3.Cursor 的方法):       Cursor 对象.        (line  136)
* close() (sunau.AU_read 的方法):        AU_read 对象.       (line    8)
* close() (sunau.AU_write 的方法):       AU_write 对象.      (line   52)
* close() (tarfile.TarFile 的方法):      TarFile 对象.       (line  213)
* close() (telnetlib.Telnet 的方法):     Telnet 对象.        (line   81)
* close() (urllib.request.BaseHandler 的方法): BaseHandler 对象.
                                                             (line   13)
* close() (wave.Wave_read 的方法):       Wave_read对象.      (line    8)
* close() (wave.Wave_write 的方法):      Wave_write 对象.    (line   18)
* Close() (winreg.PyHKEY 的方法):        注册表句柄对象.     (line   28)
* close() (xml.etree.ElementTree.TreeBuilder 的方法): TreeBuilder 对象.
                                                             (line   23)
* close() (xml.etree.ElementTree.XMLParser 的方法): XMLParser对象.
                                                             (line   19)
* close() (xml.etree.ElementTree.XMLPullParser 的方法): XMLPullParser对象.
                                                             (line   20)
* close() (xml.sax.xmlreader.IncrementalParser 的方法): IncrementalParser 对象.
                                                             (line   12)
* close() (zipfile.ZipFile 的方法):      ZipFile 对象.       (line   74)
* close() (於 fileinput 模組中):         fileinput --- 迭代来自多个输入流的行.
                                                             (line  103)
* close() (於 os 模組中):                文件描述符操作.     (line   17)
* close() (於 socket 模組中):            其他功能.           (line    8)
* closed (http.client.HTTPResponse 的屬性): HTTPResponse 对象.
                                                             (line   68)
* closed (io.IOBase 的屬性):             I/O 基类.           (line   47)
* closed (mmap.mmap 的屬性):             mmap --- 内存映射文件支持.
                                                             (line  148)
* closed (ossaudiodev.oss_audio_device 的屬性): 音频设备对象.
                                                             (line  213)
* closed (select.devpoll 的屬性):        /dev/poll 轮询对象. (line   18)
* closed (select.epoll 的屬性):          边缘触发和水平触发的轮询 epoll 对象.
                                                             (line   67)
* closed (select.kqueue 的屬性):         Kqueue 对象.        (line   10)
* CloseKey() (於 winreg 模組中):         函数<12>.           (line    8)
* closelog() (於 syslog 模組中):         Unix syslog 库例程. (line   52)
* closerange() (於 os 模組中):           文件描述符操作.     (line   27)
* close_connection (http.server.BaseHTTPRequestHandler 的屬性): http server --- HTTP 服务器.
                                                             (line   65)
* close_when_done() (asynchat.async_chat 的方法): asynchat --- 异步套接字指令/响应处理程序.
                                                             (line   61)
* closing() (於 contextlib 模組中):      工具.               (line  106)
* clrtobot() (curses.window 的方法):     Window 对象.        (line  139)
* clrtoeol() (curses.window 的方法):     Window 对象.        (line  144)
* cmath (模組):                          cmath --- 关于复数的数学函数.
                                                             (line    6)
* Cmd (cmd 中的類別):                    cmd --- 支持面向行的命令解释器.
                                                             (line   13)
* cmd (subprocess.CalledProcessError 的屬性): 使用 subprocess 模块.
                                                             (line  181)
* cmd (subprocess.TimeoutExpired 的屬性): 使用 subprocess 模块.
                                                             (line  144)
* cmd (模組):                            cmd --- 支持面向行的命令解释器.
                                                             (line    6)
* cmdloop() (cmd.Cmd 的方法):            Cmd 对象.           (line    8)
* cmdqueue (cmd.Cmd 的屬性):             Cmd 对象.           (line  107)
* cmp() (於 filecmp 模組中):             filecmp --- 文件及目录的比较.
                                                             (line   16)
* cmpfiles() (於 filecmp 模組中):        filecmp --- 文件及目录的比较.
                                                             (line   32)
* cmp_op (於 dis 模組中):                操作码集合.         (line   16)
* cmp_to_key() (於 functools 模組中):    functools --- 高阶函数和可调用对象上的操作.
                                                             (line   91)
* CMSG_LEN() (於 socket 模組中):         其他功能.           (line  248)
* CMSG_SPACE() (於 socket 模組中):       其他功能.           (line  260)
* code (SystemExit 的屬性):              具体异常.           (line  278)
* code (urllib.error.HTTPError 的屬性):  urllib error --- urllib request 引发的异常类.
                                                             (line   34)
* code (urllib.response.addinfourl 的屬性): urllib response --- urllib 使用的 Response 类.
                                                             (line   35)
* code (xml.etree.ElementTree.ParseError 的屬性): 异常<14>.  (line   12)
* code (xml.parsers.expat.ExpatError 的屬性): ExpatError 异常.
                                                             (line    8)
* code (模組):                           code --- 解释器基类.
                                                             (line    6)
* code object:                           标准类型层级结构.   (line  506)
* code object <1>:                       方法.               (line   35)
* code object <2>:                       marshal --- 内部 Python 对象序列化.
                                                             (line   24)
* code object <3>:                       Cell 物件.          (line   46)
* code; block:                           执行模型.           (line    6)
* CodecInfo (codecs 中的類別):           codecs --- 编解码器注册和相关基类.
                                                             (line   49)
* Codecs:                                codecs --- 编解码器注册和相关基类.
                                                             (line    8)
* codecs (模組):                         codecs --- 编解码器注册和相关基类.
                                                             (line    6)
* Codecs; decode:                        codecs --- 编解码器注册和相关基类.
                                                             (line    8)
* Codecs; encode:                        codecs --- 编解码器注册和相关基类.
                                                             (line    8)
* coded_value (http.cookies.Morsel 的屬性): Morsel 对象.     (line   52)
* codeop (模組):                         codeop --- 编译Python代码.
                                                             (line    6)
* codepoint2name (於 html.entities 模組中): html entities --- HTML 一般实体的定义.
                                                             (line   30)
* codes (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line   14)
* CODESET (於 locale 模組中):            locale --- 国际化服务.
                                                             (line  149)
* CodeType (types 中的類別):             标准解释器类型.     (line   44)
* code_info() (於 dis 模組中):           分析函数.           (line    9)
* coding; style:                         間奏曲：程式碼風格 Coding Style.
                                                             (line    6)
* coercion（強制轉型）:                  術語表.             (line  204)
* collapse_addresses() (於 ipaddress 模組中): 其他模块级别函数.
                                                             (line   39)
* collapse_rfc2231_value() (於 email.utils 模組中): email utils 其他工具.
                                                             (line  159)
* collect() (於 gc 模組中):              gc --- 垃圾回收器接口.
                                                             (line   30)
* Collection (collections.abc 中的類別): 容器抽象基类.       (line  130)
* Collection (typing 中的類別):          collections abc 对应的容器.
                                                             (line   25)
* collections (模組):                    collections --- 容器資料型態.
                                                             (line    6)
* collections.abc (模組):                collections abc --- 容器的抽象基类.
                                                             (line    6)
* collect_incoming_data() (asynchat.async_chat 的方法): asynchat --- 异步套接字指令/响应处理程序.
                                                             (line   66)
* colno (json.JSONDecodeError 的屬性):   例外.               (line   26)
* colno (re.error 的屬性):               模块内容.           (line  319)
* COLON (於 token 模組中):               token --- 与Python解析树一起使用的常量.
                                                             (line   66)
* COLONEQUAL (於 token 模組中):          token --- 与Python解析树一起使用的常量.
                                                             (line  234)
* color() (於 turtle 模組中):            颜色控制.           (line   94)
* colormode() (於 turtle 模組中):        设置与特殊方法.     (line   32)
* colorsys (模組):                       colorsys --- 颜色系统间的转换.
                                                             (line    6)
* color_content() (於 curses 模組中):    函数<4>.            (line   39)
* color_pair() (於 curses 模組中):       函数<4>.            (line   45)
* COLS:                                  curses<3>.          (line    7)
* COLS <1>:                              函数<4>.            (line  462)
* column() (tkinter.ttk.Treeview 的方法): ttk Treeview.      (line   30)
* COLUMNS:                               函数<4>.            (line  482)
* COLUMNS <1>:                           函数<4>.            (line  483)
* columns (os.terminal_size 的屬性):     查询终端的尺寸.     (line   27)
* col_offset (ast.AST 的屬性):           节点类.             (line   32)
* comb() (於 math 模組中):               数论与表示函数.     (line   12)
* combinations() (於 itertools 模組中):  Itertool函数.       (line  102)
* combinations_with_replacement() (於 itertools 模組中): Itertool函数.
                                                             (line  147)
* combine() (datetime.datetime 的類別成員): datetime 对象.   (line  152)
* combining() (於 unicodedata 模組中):   unicodedata --- Unicode 数据库.
                                                             (line   50)
* ComboBox (tkinter.tix 中的類別):       Basic Widgets.      (line   18)
* Combobox (tkinter.ttk 中的類別):       ttk Combobox.       (line    6)
* comma:                                 带圆括号的形式.     (line   18)
* COMMA (於 token 模組中):               token --- 与Python解析树一起使用的常量.
                                                             (line   70)
* Command (distutils.cmd 中的類別):      distutils cmd --- Abstract base class for Distutils commands.
                                                             (line    8)
* Command (distutils.core 中的類別):     distutils core --- 分发包功能的核心.
                                                             (line  291)
* command (http.server.BaseHTTPRequestHandler 的屬性): http server --- HTTP 服务器.
                                                             (line   76)
* command line:                          完整的 Python 程序. (line   19)
* command line option; -?:               通用选项.           (line    6)
* command line option; -b:               其他选项.           (line    6)
* command line option; -B:               其他选项.           (line   14)
* command line option; -c <command>:     接口选项.           (line   29)
* command line option; –check-hash-based-pycs default|always|never: 其他选项.
                                                             (line   19)
* command line option; -d:               其他选项.           (line   30)
* command line option; -E:               其他选项.           (line   35)
* command line option; -h:               通用选项.           (line    6)
* command line option; –help:            通用选项.           (line    6)
* command line option; -i:               其他选项.           (line   40)
* command line option; -I:               其他选项.           (line   49)
* command line option; -J:               不应当使用的选项.   (line    6)
* command line option; -m <module-name>: 接口选项.           (line   42)
* command line option; -O:               其他选项.           (line   58)
* command line option; -OO:              其他选项.           (line   67)
* command line option; -q:               其他选项.           (line   75)
* command line option; -R:               其他选项.           (line   81)
* command line option; -s:               其他选项.           (line  103)
* command line option; -S:               其他选项.           (line  113)
* command line option; -u:               其他选项.           (line  119)
* command line option; -V:               通用选项.           (line   12)
* command line option; -v:               其他选项.           (line  127)
* command line option; –version:         通用选项.           (line   12)
* command line option; -W arg:           其他选项.           (line  133)
* command line option; -x:               其他选项.           (line  166)
* command line option; -X:               其他选项.           (line  171)
* CommandCompiler (codeop 中的類別):     codeop --- 编译Python代码.
                                                             (line   56)
* commands (pdb command):                调试器命令.         (line  103)
* comment:                               注释.               (line    6)
* comment (http.cookiejar.Cookie 的屬性): Cookie 对象<2>.    (line   54)
* comment (zipfile.ZipFile 的屬性):      ZipFile 对象.       (line  273)
* comment (zipfile.ZipInfo 的屬性):      ZipInfo 对象.       (line   80)
* COMMENT (於 token 模組中):             token --- 与Python解析树一起使用的常量.
                                                             (line  257)
* comment() (xml.etree.ElementTree.TreeBuilder 的方法): TreeBuilder 对象.
                                                             (line   42)
* Comment() (於 xml.etree.ElementTree 模組中): 函数<7>.      (line   65)
* commenters (shlex.shlex 的屬性):       shlex 对象.         (line   71)
* CommentHandler() (xml.parsers.expat.xmlparser 的方法): XMLParser对象<2>.
                                                             (line  245)
* comment_url (http.cookiejar.Cookie 的屬性): Cookie 对象<2>.
                                                             (line   59)
* commit() (msilib.CAB 的方法):          CAB Objects.        (line   24)
* Commit() (msilib.Database 的方法):     Database Objects.   (line   11)
* commit() (sqlite3.Connection 的方法):  连接对象（Connection）.
                                                             (line   29)
* common (filecmp.dircmp 的屬性):        dircmp 类.          (line   51)
* Common Gateway Interface:              cgi --- 通用网关接口支持.
                                                             (line    8)
* commonpath() (於 os.path 模組中):      os path --- 常用路径操作.
                                                             (line   63)
* commonprefix() (於 os.path 模組中):    os path --- 常用路径操作.
                                                             (line   76)
* common_dirs (filecmp.dircmp 的屬性):   dircmp 类.          (line   63)
* common_files (filecmp.dircmp 的屬性):  dircmp 类.          (line   67)
* common_funny (filecmp.dircmp 的屬性):  dircmp 类.          (line   71)
* common_types (於 mimetypes 模組中):    mimetypes --- 映射文件名到 MIME 类型.
                                                             (line  121)
* communicate() (asyncio.asyncio.subprocess.Process 的方法): 与子进程交互.
                                                             (line   44)
* communicate() (subprocess.Popen 的方法): Popen 对象.       (line   30)
* Compare (ast 中的類別):                表达式<2>.          (line   92)
* compare() (decimal.Context 的方法):    上下文对象.         (line  208)
* compare() (decimal.Decimal 的方法):    Decimal 对象.       (line  123)
* compare() (difflib.Differ 的方法):     Differ 对象.        (line   30)
* compare_digest() (於 hmac 模組中):     hmac --- 基于密钥的消息验证.
                                                             (line   97)
* compare_digest() (於 secrets 模組中):  其他函式.           (line    6)
* compare_networks() (ipaddress.IPv4Network 的方法): 网络对象.
                                                             (line  209)
* compare_networks() (ipaddress.IPv6Network 的方法): 网络对象.
                                                             (line  316)
* COMPARE_OP (opcode):                   Python字节码说明.   (line  517)
* compare_signal() (decimal.Context 的方法): 上下文对象.     (line  212)
* compare_signal() (decimal.Decimal 的方法): Decimal 对象.   (line  133)
* compare_to() (tracemalloc.Snapshot 的方法): 快照.          (line   13)
* compare_total() (decimal.Context 的方法): 上下文对象.      (line  216)
* compare_total() (decimal.Decimal 的方法): Decimal 对象.    (line  139)
* compare_total_mag() (decimal.Context 的方法): 上下文对象.  (line  220)
* compare_total_mag() (decimal.Decimal 的方法): Decimal 对象.
                                                             (line  159)
* comparison:                            比较运算.           (line    6)
* comparisons:                           基本定制.           (line  149)
* COMPARISON_FLAGS (於 doctest 模組中):  选项标记.           (line   94)
* Compat32 (email.policy 中的類別):      email policy Policy 对象.
                                                             (line  441)
* compat32 (於 email.policy 模組中):     email policy Policy 对象.
                                                             (line  488)
* Compile (codeop 中的類別):             codeop --- 编译Python代码.
                                                             (line   49)
* compile() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  267)
* compile() (parser.ST 的方法):          ST 对象.            (line   17)
* compile() (內建函式):                  內建函式.           (line  220)
* compile() (於 py_compile 模組中):      py_compile --- 编译 Python 源文件.
                                                             (line   20)
* compile() (於 re 模組中):              模块内容.           (line   12)
* compileall (模組):                     compileall --- Byte-compile Python libraries.
                                                             (line    6)
* compileall command line option; -b:    Command-line use.   (line   59)
* compileall command line option; -d destdir: Command-line use.
                                                             (line   32)
* compileall command line option; -e dir: Command-line use.  (line  101)
* compileall command line option; -f:    Command-line use.   (line   22)
* compileall command line option; –hardlink-dupes: Command-line use.
                                                             (line  105)
* compileall command line option; -i list: Command-line use. (line   53)
* compileall command line option; –invalidation-mode [timestamp|checked-hash|unchecked-hash]: Command-line use.
                                                             (line   80)
* compileall command line option; -j N:  Command-line use.   (line   74)
* compileall command line option; -l:    Command-line use.   (line   17)
* compileall command line option; -o level: Command-line use.
                                                             (line   95)
* compileall command line option; -p prepend_prefix: Command-line use.
                                                             (line   42)
* compileall command line option; -q:    Command-line use.   (line   26)
* compileall command line option; -r:    Command-line use.   (line   67)
* compileall command line option; -s strip_prefix: Command-line use.
                                                             (line   40)
* compileall command line option; -x regex: Command-line use.
                                                             (line   47)
* compileall command line option; directory ...: Command-line use.
                                                             (line    9)
* compileall command line option; file ...: Command-line use.
                                                             (line    9)
* compilest() (於 parser 模組中):        转换 ST 对象.       (line   43)
* compile_command() (於 code 模組中):    code --- 解释器基类.
                                                             (line   40)
* compile_command() (於 codeop 模組中):  codeop --- 编译Python代码.
                                                             (line   26)
* compile_dir() (於 compileall 模組中):  Public functions.   (line    6)
* compile_file() (於 compileall 模組中): Public functions.   (line   92)
* compile_path() (於 compileall 模組中): Public functions.   (line  154)
* complete() (rlcompleter.Completer 的方法): Completer 对象. (line    8)
* completedefault() (cmd.Cmd 的方法):    Cmd 对象.           (line   62)
* CompletedProcess (subprocess 中的類別): 使用 subprocess 模块.
                                                             (line   77)
* complete_statement() (於 sqlite3 模組中): 模块函数和常量.  (line  154)
* Complex (numbers 中的類別):            数字的层次.         (line    6)
* complex (內建類別):                    內建函式.           (line  281)
* complex literal:                       数值字面值.         (line    6)
* complex number; literals:              数字类型 --- int float complex.
                                                             (line   14)
* complex number（複數）:                術語表.             (line  214)
* complex; number:                       标准类型层级结构.   (line   92)
* compound; statement:                   复合语句.           (line    6)
* comprehension (ast 中的類別):          Comprehensions.     (line   52)
* comprehensions:                        列表、集合与字典的显示.
                                                             (line    6)
* compress() (bz2.BZ2Compressor 的方法): 增量压缩和解压.     (line   14)
* compress() (lzma.LZMACompressor 的方法): 在内存中压缩和解压缩数据.
                                                             (line   64)
* compress() (zlib.Compress 的方法):     zlib --- 与 gzip 兼容的压缩.
                                                             (line  149)
* compress() (於 bz2 模組中):            一次性压缩或解压缩. (line    6)
* compress() (於 gzip 模組中):           gzip --- 对 gzip 格式的支持.
                                                             (line  147)
* compress() (於 itertools 模組中):      Itertool函数.       (line  192)
* compress() (於 lzma 模組中):           在内存中压缩和解压缩数据.
                                                             (line  149)
* compress() (於 zlib 模組中):           zlib --- 与 gzip 兼容的压缩.
                                                             (line   35)
* compressed (ipaddress.IPv4Address 的屬性): 地址对象.       (line   57)
* compressed (ipaddress.IPv4Network 的屬性): 网络对象.       (line   91)
* compressed (ipaddress.IPv6Address 的屬性): 地址对象.       (line  178)
* compressed (ipaddress.IPv6Network 的屬性): 网络对象.       (line  285)
* compression() (ssl.SSLSocket 的方法):  SSL 套接字.         (line  196)
* CompressionError:                      tarfile --- 读写tar归档文件.
                                                             (line  176)
* compressobj() (於 zlib 模組中):        zlib --- 与 gzip 兼容的压缩.
                                                             (line   47)
* compress_size (zipfile.ZipInfo 的屬性): ZipInfo 对象.      (line  129)
* compress_type (zipfile.ZipInfo 的屬性): ZipInfo 对象.      (line   76)
* COMSPEC:                               进程管理.           (line  576)
* COMSPEC <1>:                           Popen 构造函数.     (line   75)
* concat() (於 operator 模組中):         operator --- 标准运算符替代函数.
                                                             (line  158)
* concatenation; operation:              通用序列操作.       (line   17)
* concurrent.futures (模組):             concurrent futures --- 启动并行任务.
                                                             (line    6)
* Condition (asyncio 中的類別):          Condition.          (line    6)
* Condition (multiprocessing 中的類別):  同步原语.           (line   28)
* condition (pdb command):               调试器命令.         (line   97)
* Condition (threading 中的類別):        条件对象.           (line   60)
* condition() (msilib.Control 的方法):   GUI classes.        (line   24)
* Condition() (multiprocessing.managers.SyncManager 的方法): 管理器.
                                                             (line  133)
* Conditional; expression:               布尔运算.           (line    6)
* conditional; expression:               条件表达式.         (line    6)
* config() (tkinter.font.Font 的方法):   tkinter font --- Tkinter 字体封装.
                                                             (line   53)
* ConfigParser (configparser 中的類別):  ConfigParser 对象.  (line    6)
* configparser (模組):                   configparser --- 配置文件解析器.
                                                             (line    6)
* configuration information:             sysconfig --- Provide access to Python's configuration information.
                                                             (line   10)
* configuration; file:                   configparser --- 配置文件解析器.
                                                             (line    8)
* configure() (tkinter.ttk.Style 的方法): Ttk 风格.          (line   22)
* configure_mock() (unittest.mock.Mock 的方法): Mock 类.     (line  223)
* confstr() (於 os 模組中):              其他系统信息.       (line    6)
* confstr_names (於 os 模組中):          其他系统信息.       (line   23)
* conjugate() (complex number method):   数字类型 --- int float complex.
                                                             (line   83)
* conjugate() (decimal.Decimal 的方法):  Decimal 对象.       (line  170)
* conjugate() (numbers.Complex 的方法):  数字的层次.         (line   22)
* conn (smtpd.SMTPChannel 的屬性):       SMTPChannel 对象.   (line   41)
* connect() (asyncore.dispatcher 的方法): asyncore --- 异步套接字处理器.
                                                             (line  157)
* connect() (ftplib.FTP 的方法):         FTP 对象.           (line   19)
* connect() (http.client.HTTPConnection 的方法): HTTPConnection 对象.
                                                             (line   87)
* connect() (multiprocessing.managers.BaseManager 的方法): 管理器.
                                                             (line   51)
* connect() (smtplib.SMTP 的方法):       SMTP 对象.          (line   30)
* connect() (socket.socket 的方法):      套接字对象.         (line   51)
* connect() (於 sqlite3 模組中):         模块函数和常量.     (line   78)
* Connection (multiprocessing.connection 中的類別): 连接（Connection）对象.
                                                             (line   12)
* Connection (sqlite3 中的類別):         连接对象（Connection）.
                                                             (line    6)
* connection (sqlite3.Cursor 的屬性):    Cursor 对象.        (line  196)
* ConnectionAbortedError:                OS 异常.            (line   40)
* ConnectionError:                       OS 异常.            (line   26)
* ConnectionRefusedError:                OS 异常.            (line   45)
* ConnectionResetError:                  OS 异常.            (line   50)
* connection_lost() (asyncio.BaseProtocol 的方法): 基础协议<2>.
                                                             (line   21)
* connection_made() (asyncio.BaseProtocol 的方法): 基础协议<2>.
                                                             (line   14)
* ConnectRegistry() (於 winreg 模組中):  函数<12>.           (line   16)
* connect_accepted_socket() (asyncio.loop 的方法): 创建网络服务.
                                                             (line  110)
* connect_ex() (socket.socket 的方法):   套接字对象.         (line   70)
* connect_read_pipe() (asyncio.loop 的方法): 使用管道.       (line    6)
* connect_write_pipe() (asyncio.loop 的方法): 使用管道.      (line   22)
* const (optparse.Option 的屬性):        Option attributes.  (line   50)
* constant:                              字面值.             (line    6)
* Constant (ast 中的類別):               字面值<3>.          (line    6)
* constructor() (於 copyreg 模組中):     copyreg --- 注册配合 pickle 模块使用的函数.
                                                             (line   15)
* consumed (asyncio.LimitOverrunError 的屬性): 异常<9>.      (line   60)
* container:                             对象、值与类型.     (line   50)
* container <1>:                         标准类型层级结构.   (line  444)
* Container (collections.abc 中的類別):  容器抽象基类.       (line  104)
* Container (typing 中的類別):           collections abc 对应的容器.
                                                             (line   34)
* container; iteration over:             迭代器类型.         (line    6)
* contains() (於 operator 模組中):       operator --- 标准运算符替代函数.
                                                             (line  163)
* CONTAINS_OP (opcode):                  Python字节码说明.   (line  527)
* ContentDispositionHeader (email.headerregistry 中的類別): email headerregistry 自定义标头对象.
                                                             (line  230)
* ContentHandler (xml.sax.handler 中的類別): xml sax handler --- SAX 处理句柄的基类.
                                                             (line   15)
* ContentManager (email.contentmanager 中的類別): email contentmanager 管理 MIME 内容.
                                                             (line   12)
* contents (ctypes._Pointer 的屬性):     数组与指针.         (line   43)
* contents() (importlib.abc.ResourceReader 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  292)
* contents() (於 importlib.resources 模組中): importlib resources -- 资源.
                                                             (line  133)
* ContentTooShortError:                  urllib error --- urllib request 引发的异常类.
                                                             (line   50)
* ContentTransferEncoding (email.headerregistry 中的類別): email headerregistry 自定义标头对象.
                                                             (line  239)
* ContentTypeHeader (email.headerregistry 中的類別): email headerregistry 自定义标头对象.
                                                             (line  217)
* content_disposition (email.headerregistry.ContentDispositionHeader 的屬性): email headerregistry 自定义标头对象.
                                                             (line  235)
* content_manager (email.policy.EmailPolicy 的屬性): email policy Policy 对象.
                                                             (line  324)
* content_type (email.headerregistry.ContentTypeHeader 的屬性): email headerregistry 自定义标头对象.
                                                             (line  222)
* Context (contextvars 中的類別):        手动上下文管理.     (line   18)
* Context (decimal 中的類別):            上下文对象.         (line   81)
* context (ssl.SSLSocket 的屬性):        SSL 套接字.         (line  273)
* context management protocol:           上下文管理器类型.   (line    6)
* context manager:                       with 语句上下文管理器.
                                                             (line   11)
* context manager <1>:                   上下文管理器类型.   (line    6)
* context manager（情境管理器）:         術語表.             (line  224)
* context variable（情境變數）:          術語表.             (line  230)
* ContextDecorator (contextlib 中的類別): 工具.              (line  244)
* contextlib (模組):                     contextlib --- 为 with语句上下文提供的工具.
                                                             (line    6)
* ContextManager (typing 中的類別):      上下文管理器类型<2>.
                                                             (line    6)
* contextmanager() (於 contextlib 模組中): 工具.             (line   28)
* ContextVar (contextvars 中的類別):     上下文变量.         (line    6)
* contextvars (模組):                    contextvars --- 上下文变量.
                                                             (line    6)
* context_diff() (於 difflib 模組中):    difflib --- 计算差异的辅助工具.
                                                             (line  130)
* contiguous:                            形状，步幅，子偏移量.
                                                             (line   25)
* contiguous (memoryview 的屬性):        内存视图.           (line  444)
* contiguous（連續的）:                  術語表.             (line  238)
* Continue (ast 中的類別):               Control flow.       (line  101)
* continue (pdb command):                调试器命令.         (line  157)
* Control (msilib 中的類別):             GUI classes.        (line   11)
* Control (tkinter.tix 中的類別):        Basic Widgets.      (line   24)
* control() (msilib.Dialog 的方法):      GUI classes.        (line   47)
* control() (select.kqueue 的方法):      Kqueue 对象.        (line   22)
* controlnames (於 curses.ascii 模組中): curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  221)
* controls() (ossaudiodev.oss_mixer_device 的方法): Mixer Device Objects.
                                                             (line   22)
* ConversionError:                       异常<6>.            (line   13)
* convert_arg_line_to_args() (argparse.ArgumentParser 的方法): 自定义文件解析.
                                                             (line    6)
* convert_field() (string.Formatter 的方法): 自定义字符串格式化.
                                                             (line   86)
* convert_path() (於 distutils.util 模組中): distutils util --- Miscellaneous other utility functions.
                                                             (line   74)
* Cookie (http.cookiejar 中的類別):      http cookiejar —— HTTP 客户端的 Cookie 处理.
                                                             (line   90)
* CookieError:                           http cookies --- HTTP状态管理.
                                                             (line   29)
* CookieJar (http.cookiejar 中的類別):   http cookiejar —— HTTP 客户端的 Cookie 处理.
                                                             (line   38)
* cookiejar (urllib.request.HTTPCookieProcessor 的屬性): HTTPCookieProcessor 对象.
                                                             (line    8)
* CookiePolicy (http.cookiejar 中的類別): http cookiejar —— HTTP 客户端的 Cookie 处理.
                                                             (line   60)
* Coordinated Universal Time:            time --- 时间的访问和转换.
                                                             (line   33)
* Copy:                                  帮助菜单（命令行和编辑器）.
                                                             (line   26)
* copy (模組):                           copy --- 浅层 shallow 和深层 deep 复制操作.
                                                             (line    6)
* copy() (collections.deque 的方法):     deque 对象.         (line   39)
* copy() (contextvars.Context 的方法):   手动上下文管理.     (line   64)
* copy() (decimal.Context 的方法):       上下文对象.         (line  137)
* copy() (dict 的方法):                  映射类型 --- dict.  (line  129)
* copy() (frozenset 的方法):             集合类型 --- set frozenset.
                                                             (line  114)
* copy() (hashlib.hash 的方法):          哈希算法.           (line  133)
* copy() (hmac.HMAC 的方法):             hmac --- 基于密钥的消息验证.
                                                             (line   69)
* copy() (http.cookies.Morsel 的方法):   Morsel 对象.        (line   94)
* copy() (imaplib.IMAP4 的方法):         IMAP4 对象.         (line   58)
* copy() (pipes.Template 的方法):        模板对象.           (line   45)
* copy() (sequence method):              可变序列类型.       (line   14)
* copy() (tkinter.font.Font 的方法):     tkinter font --- Tkinter 字体封装.
                                                             (line   57)
* copy() (types.MappingProxyType 的方法): 标准解释器类型.    (line  239)
* copy() (zlib.Compress 的方法):         zlib --- 与 gzip 兼容的压缩.
                                                             (line  165)
* copy() (zlib.Decompress 的方法):       zlib --- 与 gzip 兼容的压缩.
                                                             (line  221)
* copy() (於 copy 模組中):               copy --- 浅层 shallow 和深层 deep 复制操作.
                                                             (line   16)
* copy() (於 multiprocessing.sharedctypes 模組中): multiprocessing sharedctypes 模块.
                                                             (line   70)
* copy() (於 shutil 模組中):             目录和文件操作.     (line  100)
* copy2() (於 shutil 模組中):            目录和文件操作.     (line  127)
* copy; protocol:                        封存类实例.         (line   78)
* copyfile() (於 shutil 模組中):         目录和文件操作.     (line   14)
* copyfileobj() (於 shutil 模組中):      目录和文件操作.     (line    6)
* copying files:                         shutil --- 高阶文件操作.
                                                             (line    8)
* copymode() (於 shutil 模組中):         目录和文件操作.     (line   49)
* copyreg (模組):                        copyreg --- 注册配合 pickle 模块使用的函数.
                                                             (line    6)
* copyright (in module sys):             Process-wide parameters.
                                                             (line  188)
* copyright (內建變數):                  由 site 模块添加的常量.
                                                             (line   17)
* copyright (於 sys 模組中):             sys --- 系统相关的参数和函数.
                                                             (line  128)
* copysign() (於 math 模組中):           数论与表示函数.     (line   27)
* copystat() (於 shutil 模組中):         目录和文件操作.     (line   64)
* copytree() (於 shutil 模組中):         目录和文件操作.     (line  160)
* copy_abs() (decimal.Context 的方法):   上下文对象.         (line  224)
* copy_abs() (decimal.Decimal 的方法):   Decimal 对象.       (line  174)
* copy_context() (於 contextvars 模組中): 手动上下文管理.    (line    6)
* copy_decimal() (decimal.Context 的方法): 上下文对象.       (line  141)
* copy_file() (於 distutils.file_util 模組中): distutils file_util --- Single file operations.
                                                             (line    9)
* copy_file_range() (於 os 模組中):      文件描述符操作.     (line   38)
* copy_location() (於 ast 模組中):       ast 中的辅助函数.   (line  126)
* copy_negate() (decimal.Context 的方法): 上下文对象.        (line  228)
* copy_negate() (decimal.Decimal 的方法): Decimal 对象.      (line  179)
* copy_sign() (decimal.Context 的方法):  上下文对象.         (line  232)
* copy_sign() (decimal.Decimal 的方法):  Decimal 对象.       (line  184)
* copy_tree() (於 distutils.dir_util 模組中): distutils dir_util --- Directory tree operations.
                                                             (line   32)
* coroutine:                             特殊方法查找.       (line   72)
* coroutine <1>:                         yield 表达式.       (line   44)
* Coroutine (collections.abc 中的類別):  容器抽象基类.       (line  204)
* Coroutine (typing 中的類別):           异步编程.           (line    6)
* coroutine function（協程函式）:        術語表.             (line  255)
* coroutine() (於 asyncio 模組中):       基于生成器的协程.   (line   15)
* coroutine() (於 types 模組中):         协程工具函数.       (line    6)
* coroutine; function:                   标准类型层级结构.   (line  352)
* CoroutineType (於 types 模組中):       标准解释器类型.     (line   30)
* coroutine（協程）:                     術語表.             (line  248)
* cos() (於 cmath 模組中):               三角函数<2>.        (line   22)
* cos() (於 math 模組中):                三角函数.           (line   28)
* cosh() (於 cmath 模組中):              双曲函数<2>.        (line   22)
* cosh() (於 math 模組中):               双曲函数.           (line   20)
* count (tracemalloc.Statistic 的屬性):  统计.               (line   15)
* count (tracemalloc.StatisticDiff 的屬性): StatisticDiff.   (line   15)
* count() (array.array 的方法):          array --- 高效率的數值型態陣列.
                                                             (line  127)
* count() (bytearray 的方法):            bytes 和 bytearray 操作.
                                                             (line   30)
* count() (bytes 的方法):                bytes 和 bytearray 操作.
                                                             (line   30)
* count() (collections.deque 的方法):    deque 对象.         (line   45)
* count() (multiprocessing.shared_memory.ShareableList 的方法): multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line  225)
* count() (sequence method):             通用序列操作.       (line   17)
* count() (str 的方法):                  字符串的方法<2>.    (line   46)
* count() (於 itertools 模組中):         Itertool函数.       (line  203)
* Counter (collections 中的類別):        Counter 物件.       (line   22)
* Counter (typing 中的類別):             collections 对应类型.
                                                             (line   37)
* countOf() (於 operator 模組中):        operator --- 标准运算符替代函数.
                                                             (line  168)
* countTestCases() (unittest.TestCase 的方法): 测试用例.     (line  705)
* countTestCases() (unittest.TestSuite 的方法): Grouping tests.
                                                             (line   55)
* count_diff (tracemalloc.StatisticDiff 的屬性): StatisticDiff.
                                                             (line   20)
* CoverageResults (trace 中的類別):      编程接口.           (line   39)
* co_argcount (code object attribute):   标准类型层级结构.   (line  515)
* CO_ASYNC_GENERATOR (於 inspect 模組中): Code Objects Bit Flags.
                                                             (line   56)
* co_cellvars (code object attribute):   标准类型层级结构.   (line  515)
* co_code (code object attribute):       标准类型层级结构.   (line  515)
* co_consts (code object attribute):     标准类型层级结构.   (line  515)
* CO_COROUTINE (於 inspect 模組中):      Code Objects Bit Flags.
                                                             (line   39)
* co_filename (code object attribute):   标准类型层级结构.   (line  515)
* co_firstlineno (code object attribute): 标准类型层级结构.  (line  515)
* co_flags (code object attribute):      标准类型层级结构.   (line  515)
* co_freevars (code object attribute):   标准类型层级结构.   (line  515)
* CO_FUTURE_DIVISION (C 變數):           The Very High Level Layer.
                                                             (line  430)
* CO_GENERATOR (於 inspect 模組中):      Code Objects Bit Flags.
                                                             (line   30)
* CO_ITERABLE_COROUTINE (於 inspect 模組中): Code Objects Bit Flags.
                                                             (line   47)
* co_kwonlyargcount (code object attribute): 标准类型层级结构.
                                                             (line  515)
* co_lnotab (code object attribute):     标准类型层级结构.   (line  515)
* co_name (code object attribute):       标准类型层级结构.   (line  515)
* co_names (code object attribute):      标准类型层级结构.   (line  515)
* CO_NESTED (於 inspect 模組中):         Code Objects Bit Flags.
                                                             (line   26)
* CO_NEWLOCALS (於 inspect 模組中):      Code Objects Bit Flags.
                                                             (line   13)
* co_nlocals (code object attribute):    标准类型层级结构.   (line  515)
* CO_NOFREE (於 inspect 模組中):         Code Objects Bit Flags.
                                                             (line   35)
* CO_OPTIMIZED (於 inspect 模組中):      Code Objects Bit Flags.
                                                             (line    9)
* co_posonlyargcount (code object attribute): 标准类型层级结构.
                                                             (line  515)
* co_stacksize (code object attribute):  标准类型层级结构.   (line  515)
* CO_VARARGS (於 inspect 模組中):        Code Objects Bit Flags.
                                                             (line   18)
* CO_VARKEYWORDS (於 inspect 模組中):    Code Objects Bit Flags.
                                                             (line   22)
* co_varnames (code object attribute):   标准类型层级结构.   (line  515)
* CPP:                                   新增，改进和弃用的模块<4>.
                                                             (line   59)
* CPPFLAGS:                              新增，改进和弃用的模块<4>.
                                                             (line   59)
* cProfile (模組):                       profile 和 cProfile 模块参考.
                                                             (line    6)
* CPU time:                              函数<3>.            (line  174)
* CPU time <1>:                          函数<3>.            (line  416)
* cpu_count() (於 multiprocessing 模組中): 杂项<3>.          (line   12)
* cpu_count() (於 os 模組中):            其他系统信息.       (line   31)
* CPython:                               術語表.             (line  262)
* cpython_only() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  697)
* crawl_delay() (urllib.robotparser.RobotFileParser 的方法): urllib robotparser --- robots txt 语法分析程序.
                                                             (line   46)
* CRC (zipfile.ZipInfo 的屬性):          ZipInfo 对象.       (line  125)
* crc32() (於 binascii 模組中):          binascii --- 二进制和 ASCII 码互转.
                                                             (line  104)
* crc32() (於 zlib 模組中):              zlib --- 与 gzip 兼容的压缩.
                                                             (line   87)
* crc_hqx() (於 binascii 模組中):        binascii --- 二进制和 ASCII 码互转.
                                                             (line   98)
* create() (imaplib.IMAP4 的方法):       IMAP4 对象.         (line   62)
* create() (venv.EnvBuilder 的方法):     API<2>.             (line   50)
* create() (於 venv 模組中):             API<2>.             (line  145)
* createAttribute() (xml.dom.Document 的方法): Document 对象.
                                                             (line   40)
* createAttributeNS() (xml.dom.Document 的方法): Document 对象.
                                                             (line   46)
* createComment() (xml.dom.Document 的方法): Document 对象.  (line   30)
* createDocument() (xml.dom.DOMImplementation 的方法): DOMImplementation 对象.
                                                             (line   15)
* createDocumentType() (xml.dom.DOMImplementation 的方法): DOMImplementation 对象.
                                                             (line   24)
* createElement() (xml.dom.Document 的方法): Document 对象.  (line   13)
* createElementNS() (xml.dom.Document 的方法): Document 对象.
                                                             (line   19)
* createfilehandler() (tkinter.Widget.tk 的方法): File Handlers.
                                                             (line   27)
* CreateKey() (於 winreg 模組中):        函数<12>.           (line   34)
* CreateKeyEx() (於 winreg 模組中):      函数<12>.           (line   59)
* createLock() (logging.Handler 的方法): 处理器对象.         (line   18)
* createLock() (logging.NullHandler 的方法): NullHandler.    (line   23)
* createProcessingInstruction() (xml.dom.Document 的方法): Document 对象.
                                                             (line   35)
* CreateRecord() (於 msilib 模組中):     msilib --- Read and write Microsoft Installer files.
                                                             (line   55)
* createSocket() (logging.handlers.SocketHandler 的方法): SocketHandler.
                                                             (line   59)
* createTextNode() (xml.dom.Document 的方法): Document 对象. (line   25)
* create_aggregate() (sqlite3.Connection 的方法): 连接对象（Connection）.
                                                             (line   98)
* create_archive() (於 zipapp 模組中):   Python API.         (line    8)
* create_autospec() (於 unittest.mock 模組中): create_autospec.
                                                             (line    6)
* CREATE_BREAKAWAY_FROM_JOB (於 subprocess 模組中): Windows 常数.
                                                             (line  113)
* create_collation() (sqlite3.Connection 的方法): 连接对象（Connection）.
                                                             (line  135)
* create_configuration() (venv.EnvBuilder 的方法): API<2>.   (line   83)
* create_connection() (asyncio.loop 的方法): 打开网络连接.   (line    6)
* create_connection() (於 socket 模組中): 创建套接字.        (line   71)
* create_datagram_endpoint() (asyncio.loop 的方法): 打开网络连接.
                                                             (line  113)
* create_decimal() (decimal.Context 的方法): 上下文对象.     (line  145)
* create_decimal_from_float() (decimal.Context 的方法): 上下文对象.
                                                             (line  165)
* create_default_context() (於 ssl 模組中): 上下文创建.      (line    8)
* CREATE_DEFAULT_ERROR_MODE (於 subprocess 模組中): Windows 常数.
                                                             (line  105)
* create_empty_file() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  297)
* create_function() (sqlite3.Connection 的方法): 连接对象（Connection）.
                                                             (line   65)
* create_future() (asyncio.loop 的方法): 创建 Future 和 Task.
                                                             (line    6)
* create_module (C 函式):                Multi-phase initialization.
                                                             (line   67)
* create_module() (importlib.abc.Loader 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  150)
* create_module() (importlib.machinery.ExtensionFileLoader 的方法): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  277)
* CREATE_NEW_CONSOLE (於 subprocess 模組中): Windows 常数.   (line   34)
* CREATE_NEW_PROCESS_GROUP (於 subprocess 模組中): Windows 常数.
                                                             (line   38)
* CREATE_NO_WINDOW (於 subprocess 模組中): Windows 常数.     (line   91)
* create_server() (asyncio.loop 的方法): 创建网络服务.       (line    6)
* create_server() (於 socket 模組中):    创建套接字.         (line   92)
* create_shortcut() (內建函式):          The Postinstallation script.
                                                             (line   62)
* create_socket() (asyncore.dispatcher 的方法): asyncore --- 异步套接字处理器.
                                                             (line  149)
* create_static_lib() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  321)
* create_stats() (profile.Profile 的方法): profile 和 cProfile 模块参考.
                                                             (line   85)
* create_string_buffer() (於 ctypes 模組中): 工具函数.       (line   35)
* create_subprocess_exec() (於 asyncio 模組中): 创建子进程.  (line    6)
* create_subprocess_shell() (於 asyncio 模組中): 创建子进程. (line   24)
* create_system (zipfile.ZipInfo 的屬性): ZipInfo 对象.      (line   89)
* create_task() (asyncio.loop 的方法):   创建 Future 和 Task.
                                                             (line   15)
* create_task() (於 asyncio 模組中):     创建任务.           (line    6)
* create_tree() (於 distutils.dir_util 模組中): distutils dir_util --- Directory tree operations.
                                                             (line   21)
* create_unicode_buffer() (於 ctypes 模組中): 工具函数.      (line   50)
* create_unix_connection() (asyncio.loop 的方法): 打开网络连接.
                                                             (line  179)
* create_unix_server() (asyncio.loop 的方法): 创建网络服务.  (line   89)
* create_version (zipfile.ZipInfo 的屬性): ZipInfo 对象.     (line   93)
* credits (內建變數):                    由 site 模块添加的常量.
                                                             (line   17)
* critical() (logging.Logger 的方法):    记录器对象.         (line  192)
* critical() (於 logging 模組中):        模块级函数.         (line  113)
* CRNCYSTR (於 locale 模組中):           locale --- 国际化服务.
                                                             (line  213)
* cross() (於 audioop 模組中):           audioop --- 处理原始音频数据.
                                                             (line   64)
* crypt (模組):                          crypt —— 检查 Unix 口令的函数.
                                                             (line    6)
* crypt() (於 crypt 模組中):             模块函数<2>.        (line    8)
* crypt(3):                              crypt —— 检查 Unix 口令的函数.
                                                             (line    8)
* crypt(3) <1>:                          crypt —— 检查 Unix 口令的函数.
                                                             (line   15)
* crypt(3) <2>:                          模块函数<2>.        (line   26)
* cryptography:                          加密服务.           (line    6)
* cssclasses (calendar.HTMLCalendar 的屬性): calendar --- 日历相关函数.
                                                             (line  160)
* cssclasses_weekday_head (calendar.HTMLCalendar 的屬性): calendar --- 日历相关函数.
                                                             (line  178)
* cssclass_month (calendar.HTMLCalendar 的屬性): calendar --- 日历相关函数.
                                                             (line  192)
* cssclass_month_head (calendar.HTMLCalendar 的屬性): calendar --- 日历相关函数.
                                                             (line  185)
* cssclass_noday (calendar.HTMLCalendar 的屬性): calendar --- 日历相关函数.
                                                             (line  172)
* cssclass_year (calendar.HTMLCalendar 的屬性): calendar --- 日历相关函数.
                                                             (line  199)
* cssclass_year_head (calendar.HTMLCalendar 的屬性): calendar --- 日历相关函数.
                                                             (line  206)
* csv:                                   csv --- CSV 文件读写.
                                                             (line    8)
* csv (模組):                            csv --- CSV 文件读写.
                                                             (line    6)
* cte (email.headerregistry.ContentTransferEncoding 的屬性): email headerregistry 自定义标头对象.
                                                             (line  243)
* ctermid() (於 os 模組中):              进程参数.           (line    8)
* cte_type (email.policy.Policy 的屬性): email policy Policy 对象.
                                                             (line  126)
* ctime() (datetime.date 的方法):        date 对象.          (line  235)
* ctime() (datetime.datetime 的方法):    datetime 对象.      (line  615)
* ctime() (於 time 模組中):              函数<3>.            (line   78)
* ctrl() (於 curses.ascii 模組中):       curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  201)
* CTRL_BREAK_EVENT (於 signal 模組中):   模块内容<5>.        (line  149)
* CTRL_C_EVENT (於 signal 模組中):       模块内容<5>.        (line  140)
* ctypes (模組):                         ctypes --- Python 的外部函数库.
                                                             (line    6)
* curdir (於 os 模組中):                 其他系统信息.       (line   67)
* currency() (於 locale 模組中):         locale --- 国际化服务.
                                                             (line  345)
* current() (tkinter.ttk.Combobox 的方法): ttk Combobox.     (line    8)
* CurrentByteIndex (xml.parsers.expat.xmlparser 的屬性): XMLParser对象<2>.
                                                             (line  129)
* CurrentColumnNumber (xml.parsers.expat.xmlparser 的屬性): XMLParser对象<2>.
                                                             (line  133)
* currentframe() (於 inspect 模組中):    The interpreter stack.
                                                             (line   72)
* CurrentLineNumber (xml.parsers.expat.xmlparser 的屬性): XMLParser对象<2>.
                                                             (line  137)
* current_process() (於 multiprocessing 模組中): 杂项<3>.    (line   27)
* current_task() (於 asyncio 模組中):    内省.               (line    6)
* current_thread() (於 threading 模組中): threading --- 基于线程的并行.
                                                             (line   32)
* curses (模組):                         curses --- 终端字符单元显示的处理.
                                                             (line    6)
* curses.ascii (模組):                   curses ascii --- 用于 ASCII 字符的工具.
                                                             (line    6)
* curses.panel (模組):                   curses panel --- curses 的面板栈扩展.
                                                             (line    6)
* curses.textpad (模組):                 curses textpad --- 用于 curses 程序的文本输入控件.
                                                             (line    6)
* Cursor (sqlite3 中的類別):             Cursor 对象.        (line    6)
* cursor() (sqlite3.Connection 的方法):  连接对象（Connection）.
                                                             (line   23)
* cursyncup() (curses.window 的方法):    Window 对象.        (line  148)
* curs_set() (於 curses 模組中):         函数<4>.            (line   51)
* customize_compiler() (於 distutils.sysconfig 模組中): distutils sysconfig --- System configuration information.
                                                             (line   83)
* Cut:                                   帮助菜单（命令行和编辑器）.
                                                             (line   26)
* cwd() (ftplib.FTP 的方法):             FTP 对象.           (line  176)
* cwd() (pathlib.Path 的類別成員):       方法<2>.            (line   15)
* cycle() (於 itertools 模組中):         Itertool函数.       (line  222)
* CycleError:                            异常<2>.            (line    8)
* Cyclic Redundancy Check:               zlib --- 与 gzip 兼容的压缩.
                                                             (line   89)
* c_bool (ctypes 中的類別):              基础数据类型<2>.    (line  179)
* C_BUILTIN (於 imp 模組中):             imp —— 由代码内部访问 import 。.
                                                             (line  323)
* c_byte (ctypes 中的類別):              基础数据类型<2>.    (line   36)
* c_char (ctypes 中的類別):              基础数据类型<2>.    (line   41)
* c_char_p (ctypes 中的類別):            基础数据类型<2>.    (line   46)
* c_contiguous (memoryview 的屬性):      内存视图.           (line  432)
* c_double (ctypes 中的類別):            基础数据类型<2>.    (line   52)
* C_EXTENSION (於 imp 模組中):           imp —— 由代码内部访问 import 。.
                                                             (line  311)
* c_float (ctypes 中的類別):             基础数据类型<2>.    (line   62)
* c_int (ctypes 中的類別):               基础数据类型<2>.    (line   66)
* c_int16 (ctypes 中的類別):             基础数据类型<2>.    (line   77)
* c_int32 (ctypes 中的類別):             基础数据类型<2>.    (line   82)
* c_int64 (ctypes 中的類別):             基础数据类型<2>.    (line   87)
* c_int8 (ctypes 中的類別):              基础数据类型<2>.    (line   72)
* c_long (ctypes 中的類別):              基础数据类型<2>.    (line   92)
* c_longdouble (ctypes 中的類別):        基础数据类型<2>.    (line   56)
* c_longlong (ctypes 中的類別):          基础数据类型<2>.    (line   97)
* c_short (ctypes 中的類別):             基础数据类型<2>.    (line  102)
* c_size_t (ctypes 中的類別):            基础数据类型<2>.    (line  107)
* c_ssize_t (ctypes 中的類別):           基础数据类型<2>.    (line  111)
* c_ubyte (ctypes 中的類別):             基础数据类型<2>.    (line  117)
* c_uint (ctypes 中的類別):              基础数据类型<2>.    (line  122)
* c_uint16 (ctypes 中的類別):            基础数据类型<2>.    (line  133)
* c_uint32 (ctypes 中的類別):            基础数据类型<2>.    (line  138)
* c_uint64 (ctypes 中的類別):            基础数据类型<2>.    (line  143)
* c_uint8 (ctypes 中的類別):             基础数据类型<2>.    (line  128)
* c_ulong (ctypes 中的類別):             基础数据类型<2>.    (line  148)
* c_ulonglong (ctypes 中的類別):         基础数据类型<2>.    (line  153)
* c_ushort (ctypes 中的類別):            基础数据类型<2>.    (line  158)
* c_void_p (ctypes 中的類別):            基础数据类型<2>.    (line  163)
* c_wchar (ctypes 中的類別):             基础数据类型<2>.    (line  168)
* c_wchar_p (ctypes 中的類別):           基础数据类型<2>.    (line  174)
* daemon (multiprocessing.Process 的屬性): Process 和异常.   (line   73)
* daemon (threading.Thread 的屬性):      线程对象.           (line  154)
* dangling; else:                        复合语句.           (line   46)
* data:                                  对象、值与类型.     (line    6)
* data (collections.UserDict 的屬性):    UserDict 对象.      (line   19)
* data (collections.UserList 的屬性):    UserList 对象.      (line   22)
* data (collections.UserString 的屬性):  UserString 对象.    (line   20)
* data (select.kevent 的屬性):           Kevent 对象.        (line  171)
* data (selectors.SelectorKey 的屬性):   类<2>.              (line   46)
* data (urllib.request.Request 的屬性):  Request 对象.       (line   37)
* data (xml.dom.Comment 的屬性):         注释对象.           (line    9)
* data (xml.dom.ProcessingInstruction 的屬性): ProcessingInstruction 对象.
                                                             (line   12)
* data (xml.dom.Text 的屬性):            Text 和 CDATASection 对象.
                                                             (line   12)
* data (xmlrpc.client.Binary 的屬性):    Binary 对象.        (line   11)
* data() (xml.etree.ElementTree.TreeBuilder 的方法): TreeBuilder 对象.
                                                             (line   28)
* data; tabular:                         csv --- CSV 文件读写.
                                                             (line    8)
* data; type:                            标准类型层级结构.   (line    6)
* DatabaseError:                         异常<4>.            (line   14)
* databases:                             dbm dumb --- 便携式 DBM 实现.
                                                             (line    8)
* dataclass() (於 dataclasses 模組中):   模块级装饰器、类和函数.
                                                             (line    6)
* dataclasses (模組):                    dataclasses --- 数据类.
                                                             (line    6)
* DatagramHandler (logging.handlers 中的類別): DatagramHandler.
                                                             (line    9)
* DatagramProtocol (asyncio 中的類別):   基础协议.           (line   18)
* DatagramRequestHandler (socketserver 中的類別): 请求处理句柄对象.
                                                             (line   34)
* DatagramTransport (asyncio 中的類別):  传输层级.           (line   37)
* datagram_received() (asyncio.DatagramProtocol 的方法): 数据报协议.
                                                             (line    9)
* DataHandler (urllib.request 中的類別): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  346)
* data_open() (urllib.request.DataHandler 的方法): DataHandler 对象.
                                                             (line    6)
* data_received() (asyncio.Protocol 的方法): 流式协议.       (line   13)
* date (datetime 中的類別):              date 对象.          (line   12)
* date() (datetime.datetime 的方法):     datetime 对象.      (line  357)
* date() (nntplib.NNTP 的方法):          方法<3>.            (line  265)
* DateHeader (email.headerregistry 中的類別): email headerregistry 自定义标头对象.
                                                             (line  110)
* datetime (datetime 中的類別):          datetime 对象.      (line   15)
* datetime (email.headerregistry.DateHeader 的屬性): email headerregistry 自定义标头对象.
                                                             (line  118)
* DateTime (xmlrpc.client 中的類別):     日期時間物件.       (line    6)
* datetime (模組):                       datetime --- 基本日期和时间类型.
                                                             (line    6)
* date_time (zipfile.ZipInfo 的屬性):    ZipInfo 对象.       (line   48)
* date_time_string() (http.server.BaseHTTPRequestHandler 的方法): http server --- HTTP 服务器.
                                                             (line  263)
* datum:                                 字典显示.           (line    6)
* day (datetime.date 的屬性):            date 对象.          (line  102)
* day (datetime.datetime 的屬性):        datetime 对象.      (line  251)
* daylight (於 time 模組中):             时区常量.           (line   12)
* Daylight Saving Time:                  time --- 时间的访问和转换.
                                                             (line   37)
* day_abbr (於 calendar 模組中):         calendar --- 日历相关函数.
                                                             (line  323)
* day_name (於 calendar 模組中):         calendar --- 日历相关函数.
                                                             (line  319)
* DbfilenameShelf (shelve 中的類別):     限制.               (line   53)
* dbm (模組):                            dbm --- Unix "数据库" 接口.
                                                             (line    6)
* dbm.dumb (模組):                       dbm dumb --- 便携式 DBM 实现.
                                                             (line    6)
* dbm.gnu (模組):                        dbm gnu --- GNU 对 dbm 的重解析.
                                                             (line    6)
* dbm.ndbm (模組):                       dbm ndbm --- 基于 ndbm 的接口.
                                                             (line    6)
* dcgettext() (於 locale 模組中):        访问信息目录.       (line   10)
* deallocation, object:                  终结和内存释放.     (line    6)
* debug (imaplib.IMAP4 的屬性):          IMAP4 对象.         (line  356)
* debug (pdb command):                   调试器命令.         (line  279)
* debug (shlex.shlex 的屬性):            shlex 对象.         (line  132)
* debug (zipfile.ZipFile 的屬性):        ZipFile 对象.       (line  268)
* DEBUG (於 re 模組中):                  模块内容.           (line   47)
* debug() (logging.Logger 的方法):       记录器对象.         (line   99)
* debug() (pipes.Template 的方法):       模板对象.           (line   16)
* debug() (unittest.TestCase 的方法):    测试用例.           (line  120)
* debug() (unittest.TestSuite 的方法):   Grouping tests.     (line   48)
* debug() (於 doctest 模組中):           调试.               (line  114)
* debug() (於 logging 模組中):           模块级函数.         (line   39)
* debugger:                              调试菜单（仅 window 编辑器）.
                                                             (line   15)
* debugger <1>:                          sys --- 系统相关的参数和函数.
                                                             (line  626)
* debugger <2>:                          sys --- 系统相关的参数和函数.
                                                             (line 1114)
* debugger; configuration; file:         调试器命令.         (line   27)
* debugging:                             pdb --- Python 的调试器.
                                                             (line    8)
* debugging; assertions:                 assert 语句.        (line    6)
* DebuggingServer (smtpd 中的類別):      DebuggingServer 对象.
                                                             (line    6)
* debuglevel (http.client.HTTPResponse 的屬性): HTTPResponse 对象.
                                                             (line   63)
* DebugRunner (doctest 中的類別):        调试.               (line  148)
* DEBUG_BYTECODE_SUFFIXES (於 importlib.machinery 模組中): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line   18)
* DEBUG_COLLECTABLE (於 gc 模組中):      gc --- 垃圾回收器接口.
                                                             (line  246)
* DEBUG_LEAK (於 gc 模組中):             gc --- 垃圾回收器接口.
                                                             (line  263)
* debug_print() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  509)
* DEBUG_SAVEALL (於 gc 模組中):          gc --- 垃圾回收器接口.
                                                             (line  258)
* debug_src() (於 doctest 模組中):       调试.               (line  131)
* DEBUG_STATS (於 gc 模組中):            gc --- 垃圾回收器接口.
                                                             (line  241)
* DEBUG_UNCOLLECTABLE (於 gc 模組中):    gc --- 垃圾回收器接口.
                                                             (line  250)
* Decimal (decimal 中的類別):            Decimal 对象.       (line    6)
* decimal (模組):                        decimal --- 十进制定点和浮点运算.
                                                             (line    6)
* decimal literal:                       数值字面值.         (line    6)
* decimal() (於 unicodedata 模組中):     unicodedata --- Unicode 数据库.
                                                             (line   26)
* DecimalException (decimal 中的類別):   信号.               (line   24)
* decode (codecs.CodecInfo 的屬性):      codecs --- 编解码器注册和相关基类.
                                                             (line   60)
* decode() (bytearray 的方法):           bytes 和 bytearray 操作.
                                                             (line   77)
* decode() (bytes 的方法):               bytes 和 bytearray 操作.
                                                             (line   77)
* decode() (codecs.Codec 的方法):        无状态的编码和解码. (line   24)
* decode() (codecs.IncrementalDecoder 的方法): IncrementalDecoder 对象.
                                                             (line   24)
* decode() (json.JSONDecoder 的方法):    编码器和解码器.     (line   78)
* decode() (xmlrpc.client.Binary 的方法): Binary 对象.       (line   19)
* decode() (xmlrpc.client.DateTime 的方法): 日期時間物件.    (line   12)
* decode() (於 base64 模組中):           base64 —— Base16、Base32、Base64、Base85 資料編碼.
                                                             (line  179)
* decode() (於 codecs 模組中):           codecs --- 编解码器注册和相关基类.
                                                             (line   28)
* decode() (於 quopri 模組中):           quopri --- 编码与解码经过 MIME 转码的可打印数据.
                                                             (line   17)
* decode() (於 uu 模組中):               uu --- 对 uuencode 文件进行编码与解码.
                                                             (line   31)
* decodebytes() (於 base64 模組中):      base64 —— Base16、Base32、Base64、Base85 資料編碼.
                                                             (line  185)
* DecodedGenerator (email.generator 中的類別): email generator 生成 MIME 文档.
                                                             (line  194)
* decodestring() (於 quopri 模組中):     quopri --- 编码与解码经过 MIME 转码的可打印数据.
                                                             (line   35)
* decode_header() (於 email.header 模組中): email header 国际化标头.
                                                             (line  144)
* decode_header() (於 nntplib 模組中):   工具函数<2>.        (line    8)
* decode_params() (於 email.utils 模組中): email utils 其他工具.
                                                             (line  173)
* decode_rfc2231() (於 email.utils 模組中): email utils 其他工具.
                                                             (line  148)
* decode_source() (於 importlib.util 模組中): importlib util —— 导入器的工具程序代码.
                                                             (line   63)
* decomposition() (於 unicodedata 模組中): unicodedata --- Unicode 数据库.
                                                             (line   64)
* decompress() (bz2.BZ2Decompressor 的方法): 增量压缩和解压. (line   38)
* decompress() (lzma.LZMADecompressor 的方法): 在内存中压缩和解压缩数据.
                                                             (line  104)
* decompress() (zlib.Decompress 的方法): zlib --- 与 gzip 兼容的压缩.
                                                             (line  197)
* decompress() (於 bz2 模組中):          一次性压缩或解压缩. (line   15)
* decompress() (於 gzip 模組中):         gzip --- 对 gzip 格式的支持.
                                                             (line  157)
* decompress() (於 lzma 模組中):         在内存中压缩和解压缩数据.
                                                             (line  158)
* decompress() (於 zlib 模組中):         zlib --- 与 gzip 兼容的压缩.
                                                             (line   97)
* decompressobj() (於 zlib 模組中):      zlib --- 与 gzip 兼容的压缩.
                                                             (line  131)
* decorator（裝飾器）:                   術語表.             (line  268)
* DEDENT (於 token 模組中):              token --- 与Python解析树一起使用的常量.
                                                             (line   48)
* DEDENT token:                          缩进.               (line   23)
* DEDENT token <1>:                      复合语句.           (line   46)
* dedent() (於 textwrap 模組中):         textwrap --- 文本自动换行与填充.
                                                             (line   69)
* deepcopy() (於 copy 模組中):           copy --- 浅层 shallow 和深层 deep 复制操作.
                                                             (line   20)
* default (inspect.Parameter 的屬性):    Introspecting callables with the Signature object.
                                                             (line  168)
* default (optparse.Option 的屬性):      Option attributes.  (line   36)
* default (於 email.policy 模組中):      email policy Policy 对象.
                                                             (line  392)
* DEFAULT (於 unittest.mock 模組中):     DEFAULT.            (line    6)
* default() (cmd.Cmd 的方法):            Cmd 对象.           (line   57)
* default() (json.JSONEncoder 的方法):   编码器和解码器.     (line  177)
* default; parameter; value:             函数定义.           (line   48)
* DefaultContext (decimal 中的類別):     上下文对象.         (line   61)
* DefaultCookiePolicy (http.cookiejar 中的類別): http cookiejar —— HTTP 客户端的 Cookie 处理.
                                                             (line   64)
* defaultdict (collections 中的類別):    defaultdict 对象.   (line    6)
* DefaultDict (typing 中的類別):         collections 对应类型.
                                                             (line    6)
* DefaultEventLoopPolicy (asyncio 中的類別): 策略对象.       (line   50)
* DefaultHandler() (xml.parsers.expat.xmlparser 的方法): XMLParser对象<2>.
                                                             (line  260)
* DefaultHandlerExpand() (xml.parsers.expat.xmlparser 的方法): XMLParser对象<2>.
                                                             (line  265)
* defaults() (configparser.ConfigParser 的方法): ConfigParser 对象.
                                                             (line   65)
* DefaultSelector (selectors 中的類別):  类<2>.              (line  140)
* defaultTestLoader (於 unittest 模組中): Loading and running tests.
                                                             (line  428)
* defaultTestResult() (unittest.TestCase 的方法): 测试用例.  (line  710)
* DEFAULT_BUFFER_SIZE (於 io 模組中):    高阶模块接口.       (line    6)
* default_bufsize (於 xml.dom.pulldom 模組中): xml dom pulldom --- 支持构建部分 DOM 树.
                                                             (line   92)
* default_exception_handler() (asyncio.loop 的方法): 错误处理API.
                                                             (line   24)
* default_factory (collections.defaultdict 的屬性): defaultdict 对象.
                                                             (line   42)
* DEFAULT_FORMAT (於 tarfile 模組中):    tarfile --- 读写tar归档文件.
                                                             (line  216)
* DEFAULT_IGNORES (於 filecmp 模組中):   dircmp 类.          (line   94)
* default_open() (urllib.request.BaseHandler 的方法): BaseHandler 对象.
                                                             (line   28)
* DEFAULT_PROTOCOL (於 pickle 模組中):   模块接口.           (line   19)
* default_timer() (於 timeit 模組中):    Python 接口.        (line   29)
* defects (email.headerregistry.BaseHeader 的屬性): email headerregistry 自定义标头对象.
                                                             (line   43)
* defects (email.message.EmailMessage 的屬性): email message 表示一封电子邮件信息.
                                                             (line  600)
* defects (email.message.Message 的屬性): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  610)
* define_macro() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  161)
* defpath (於 os 模組中):                其他系统信息.       (line  100)
* DefragResult (urllib.parse 中的類別):  结构化解析结果.     (line   33)
* DefragResultBytes (urllib.parse 中的類別): 结构化解析结果. (line   56)
* def_prog_mode() (於 curses 模組中):    函数<4>.            (line   58)
* def_shell_mode() (於 curses 模組中):   函数<4>.            (line   64)
* degrees() (於 math 模組中):            角度转换.           (line    6)
* degrees() (於 turtle 模組中):          度量单位设置.       (line    6)
* Del (ast 中的類別):                    Variables.          (line   11)
* delattr() (內建函式):                  內建函式.           (line  306)
* delay() (於 turtle 模組中):            动画控制.           (line    6)
* delayload (http.cookiejar.FileCookieJar 的屬性): CookieJar 和 FileCookieJar 对象.
                                                             (line  142)
* delay_output() (於 curses 模組中):     函数<4>.            (line   70)
* delch() (curses.window 的方法):        Window 对象.        (line  152)
* dele() (poplib.POP3 的方法):           POP3 对象.          (line   61)
* Delete (ast 中的類別):                 Statements.         (line  143)
* delete() (ftplib.FTP 的方法):          FTP 对象.           (line  170)
* delete() (imaplib.IMAP4 的方法):       IMAP4 对象.         (line   66)
* delete() (tkinter.ttk.Treeview 的方法): ttk Treeview.      (line   67)
* deleteacl() (imaplib.IMAP4 的方法):    IMAP4 对象.         (line   70)
* deletefilehandler() (tkinter.Widget.tk 的方法): File Handlers.
                                                             (line   37)
* DeleteKey() (於 winreg 模組中):        函数<12>.           (line   93)
* DeleteKeyEx() (於 winreg 模組中):      函数<12>.           (line  113)
* deleteln() (curses.window 的方法):     Window 对象.        (line  156)
* deleteMe() (bdb.Breakpoint 的方法):    bdb --- Debugger framework.
                                                             (line   41)
* DeleteValue() (於 winreg 模組中):      函数<12>.           (line  149)
* DELETE_ATTR (opcode):                  Python字节码说明.   (line  430)
* DELETE_DEREF (opcode):                 Python字节码说明.   (line  637)
* DELETE_FAST (opcode):                  Python字节码说明.   (line  610)
* DELETE_GLOBAL (opcode):                Python字节码说明.   (line  438)
* DELETE_NAME (opcode):                  Python字节码说明.   (line  407)
* DELETE_SUBSCR (opcode):                Python字节码说明.   (line  245)
* deletion; target:                      del 语句.           (line    6)
* deletion; target; list:                del 语句.           (line    6)
* delimiter (csv.Dialect 的屬性):        变种与格式参数.     (line   16)
* delimiters:                            分隔符.             (line    6)
* delitem() (於 operator 模組中):        operator --- 标准运算符替代函数.
                                                             (line  172)
* deliver_challenge() (於 multiprocessing.connection 模組中): 监听器及客户端.
                                                             (line   14)
* delocalize() (於 locale 模組中):       locale --- 国际化服务.
                                                             (line  362)
* del_param() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  318)
* del_param() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  453)
* demo_app() (於 wsgiref.simple_server 模組中): wsgiref simple_server -- 一个简单的 WSGI HTTP 服务器.
                                                             (line   34)
* denominator (fractions.Fraction 的屬性): fractions --- 分数.
                                                             (line   88)
* denominator (numbers.Rational 的屬性): 数字的层次.         (line   49)
* DeprecationWarning:                    警告.               (line   16)
* deque (collections 中的類別):          deque 对象.         (line    6)
* Deque (typing 中的類別):               collections 对应类型.
                                                             (line   48)
* dequeue() (logging.handlers.QueueListener 的方法): QueueListener.
                                                             (line   38)
* derwin() (curses.window 的方法):       Window 对象.        (line  160)
* DER_cert_to_PEM_cert() (於 ssl 模組中): 证书处理.          (line   79)
* descrgetfunc (C 型態):                 Slot Type typedefs. (line   67)
* description (inspect.Parameter.kind 的屬性): Introspecting callables with the Signature object.
                                                             (line  233)
* description (sqlite3.Cursor 的屬性):   Cursor 对象.        (line  188)
* description() (nntplib.NNTP 的方法):   方法<3>.            (line  131)
* descriptions() (nntplib.NNTP 的方法):  方法<3>.            (line  118)
* descriptor（描述器）:                  術語表.             (line  287)
* descrsetfunc (C 型態):                 Slot Type typedefs. (line   72)
* dest (optparse.Option 的屬性):         Option attributes.  (line   27)
* destructor:                            基本定制.           (line   46)
* destructor <1>:                        赋值语句.           (line   59)
* destructor (C 型態):                   Slot Type typedefs. (line   24)
* detach() (io.BufferedIOBase 的方法):   I/O 基类.           (line  219)
* detach() (io.TextIOBase 的方法):       文本 I/O<2>.        (line   34)
* detach() (socket.socket 的方法):       套接字对象.         (line   80)
* detach() (tkinter.ttk.Treeview 的方法): ttk Treeview.      (line   73)
* detach() (weakref.finalize 的方法):    weakref --- 弱引用. (line  215)
* Detach() (winreg.PyHKEY 的方法):       注册表句柄对象.     (line   34)
* DETACHED_PROCESS (於 subprocess 模組中): Windows 常数.     (line   98)
* detect_api_mismatch() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  950)
* detect_encoding() (於 tokenize 模組中): 对输入进行解析标记.
                                                             (line   64)
* detect_language() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  197)
* deterministic profiling:               profile分析器简介.  (line    6)
* device_encoding() (於 os 模組中):      文件描述符操作.     (line   58)
* devnull (於 os 模組中):                其他系统信息.       (line  113)
* DEVNULL (於 subprocess 模組中):        使用 subprocess 模块.
                                                             (line  115)
* devpoll() (於 select 模組中):          select --- 等待 I/O 完成.
                                                             (line   27)
* DevpollSelector (selectors 中的類別):  类<2>.              (line  162)
* dgettext() (於 gettext 模組中):        GNU gettext API.    (line   42)
* dgettext() (於 locale 模組中):         访问信息目录.       (line    8)
* Dialect (csv 中的類別):                模块内容<3>.        (line  154)
* dialect (csv.csvreader 的屬性):        Reader 对象.        (line   18)
* dialect (csv.csvwriter 的屬性):        Writer 对象.        (line   27)
* Dialog (msilib 中的類別):              GUI classes.        (line   40)
* Dialog (tkinter.commondialog 中的類別): tkinter commondialog --- 对话窗口模板.
                                                             (line   13)
* Dialog (tkinter.simpledialog 中的類別): tkinter simpledialog --- 标准 Tkinter 输入对话框.
                                                             (line   19)
* dict (2to3 fixer):                     修复器.             (line   68)
* Dict (ast 中的類別):                   字面值<3>.          (line  105)
* Dict (typing 中的類別):                对应的内置类型.     (line    6)
* dict (內建類別):                       映射类型 --- dict.  (line   21)
* dict() (multiprocessing.managers.SyncManager 的方法): 管理器.
                                                             (line  179)
* DictComp (ast 中的類別):               Comprehensions.     (line    6)
* dictConfig() (於 logging.config 模組中): 配置函数.         (line   11)
* dictionary comprehension（字典綜合運算）: 術語表.          (line  307)
* dictionary view（字典檢視）:           術語表.             (line  314)
* dictionary; comprehensions:            字典显示.           (line    6)
* dictionary; display:                   字典显示.           (line    6)
* dictionary（字典）:                    術語表.             (line  301)
* DictReader (csv 中的類別):             模块内容<3>.        (line   89)
* DictWriter (csv 中的類別):             模块内容<3>.        (line  125)
* DICT_MERGE (opcode):                   Python字节码说明.   (line  507)
* DICT_UPDATE (opcode):                  Python字节码说明.   (line  501)
* Differ (difflib 中的類別):             difflib --- 计算差异的辅助工具.
                                                             (line   39)
* difference() (frozenset 的方法):       集合类型 --- set frozenset.
                                                             (line  100)
* difference_update() (frozenset 的方法): 集合类型 --- set frozenset.
                                                             (line  163)
* difflib (模組):                        difflib --- 计算差异的辅助工具.
                                                             (line    6)
* diff_bytes() (於 difflib 模組中):      difflib --- 计算差异的辅助工具.
                                                             (line  295)
* diff_files (filecmp.dircmp 的屬性):    dircmp 类.          (line   80)
* digest() (hashlib.hash 的方法):        哈希算法.           (line  121)
* digest() (hashlib.shake 的方法):       SHAKE 可变长度摘要. (line   10)
* digest() (hmac.HMAC 的方法):           hmac --- 基于密钥的消息验证.
                                                             (line   49)
* digest() (於 hmac 模組中):             hmac --- 基于密钥的消息验证.
                                                             (line   28)
* digest_size (hmac.HMAC 的屬性):        hmac --- 基于密钥的消息验证.
                                                             (line   76)
* digit() (於 unicodedata 模組中):       unicodedata --- Unicode 数据库.
                                                             (line   31)
* digits (於 string 模組中):             字符串常量.         (line   23)
* dir() (ftplib.FTP 的方法):             FTP 对象.           (line  155)
* dir() (內建函式):                      內建函式.           (line  324)
* dircmp (filecmp 中的類別):             dircmp 类.          (line    6)
* Directory (msilib 中的類別):           Directory Objects.  (line    6)
* Directory (tkinter.filedialog 中的類別): 原生 加载/保存 对话框.
                                                             (line   63)
* directory; changing:                   文件和目录.         (line   99)
* directory; creating:                   文件和目录.         (line  408)
* directory; deleting:                   目录和文件操作.     (line  214)
* directory; deleting <1>:               文件和目录.         (line  569)
* directory; traversal:                  文件和目录.         (line 1302)
* directory; traversal <1>:              文件和目录.         (line 1383)
* directory; walking:                    文件和目录.         (line 1302)
* directory; walking <1>:                文件和目录.         (line 1383)
* directory_created() (內建函式):        The Postinstallation script.
                                                             (line   23)
* DirEntry (os 中的類別):                文件和目录.         (line  717)
* DirList (tkinter.tix 中的類別):        File Selectors.     (line    6)
* dirname() (於 os.path 模組中):         os path --- 常用路径操作.
                                                             (line   92)
* DirSelectBox (tkinter.tix 中的類別):   File Selectors.     (line   26)
* DirSelectDialog (tkinter.tix 中的類別): File Selectors.    (line   20)
* DirsOnSysPath (test.support 中的類別): test support --- Utilities for the Python test suite.
                                                             (line 1089)
* dirs_double_event() (tkinter.filedialog.FileDialog 的方法): 原生 加载/保存 对话框.
                                                             (line   77)
* dirs_select_event() (tkinter.filedialog.FileDialog 的方法): 原生 加载/保存 对话框.
                                                             (line   81)
* DirTree (tkinter.tix 中的類別):        File Selectors.     (line   13)
* dis (模組):                            dis --- Python bytecode的反組譯器.
                                                             (line    6)
* dis() (dis.Bytecode 的方法):           字节码分析.         (line   41)
* dis() (於 dis 模組中):                 分析函数.           (line   33)
* dis() (於 pickletools 模組中):         编程接口<2>.        (line    6)
* disable (pdb command):                 调试器命令.         (line   81)
* disable() (bdb.Breakpoint 的方法):     bdb --- Debugger framework.
                                                             (line   51)
* disable() (profile.Profile 的方法):    profile 和 cProfile 模块参考.
                                                             (line   81)
* disable() (於 faulthandler 模組中):    错误处理程序的状态. (line   21)
* disable() (於 gc 模組中):              gc --- 垃圾回收器接口.
                                                             (line   22)
* disable() (於 logging 模組中):         模块级函数.         (line  137)
* DisableReflectionKey() (於 winreg 模組中): 函数<12>.       (line  436)
* disable_faulthandler() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  516)
* disable_gc() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  528)
* disable_interspersed_args() (optparse.OptionParser 的方法): Querying and manipulating your option parser.
                                                             (line   10)
* disassemble() (於 dis 模組中):         分析函数.           (line   66)
* discard (http.cookiejar.Cookie 的屬性): Cookie 对象<2>.    (line   50)
* discard() (frozenset 的方法):          集合类型 --- set frozenset.
                                                             (line  184)
* discard() (mailbox.Mailbox 的方法):    Mailbox 对象.       (line   58)
* discard() (mailbox.MH 的方法):         MH.                 (line   68)
* discard_buffers() (asynchat.async_chat 的方法): asynchat --- 异步套接字指令/响应处理程序.
                                                             (line   71)
* disco() (於 dis 模組中):               分析函数.           (line   66)
* discover() (unittest.TestLoader 的方法): Loading and running tests.
                                                             (line  117)
* disk_usage() (於 shutil 模組中):       目录和文件操作.     (line  286)
* dispatcher (asyncore 中的類別):        asyncore --- 异步套接字处理器.
                                                             (line   53)
* dispatcher_with_send (asyncore 中的類別): asyncore --- 异步套接字处理器.
                                                             (line  202)
* dispatch_call() (bdb.Bdb 的方法):      bdb --- Debugger framework.
                                                             (line  156)
* dispatch_exception() (bdb.Bdb 的方法): bdb --- Debugger framework.
                                                             (line  176)
* dispatch_line() (bdb.Bdb 的方法):      bdb --- Debugger framework.
                                                             (line  146)
* dispatch_return() (bdb.Bdb 的方法):    bdb --- Debugger framework.
                                                             (line  166)
* dispatch_table (pickle.Pickler 的屬性): 模块接口.          (line  158)
* display (pdb command):                 调试器命令.         (line  215)
* displayhook() (於 sys 模組中):         sys --- 系统相关的参数和函数.
                                                             (line  201)
* display_name (email.headerregistry.Address 的屬性): email headerregistry 自定义标头对象.
                                                             (line  363)
* display_name (email.headerregistry.Group 的屬性): email headerregistry 自定义标头对象.
                                                             (line  400)
* dist() (於 math 模組中):               三角函数.           (line   32)
* distance() (於 turtle 模組中):         获取海龟的状态.     (line   64)
* distb() (於 dis 模組中):               分析函数.           (line   56)
* Distribution (distutils.core 中的類別): distutils core --- 分发包功能的核心.
                                                             (line  278)
* distutils (模組):                      distutils --- 构建和安装 Python 模块.
                                                             (line    6)
* distutils.archive_util (模組):         distutils archive_util --- Archiving utilities.
                                                             (line    6)
* distutils.bcppcompiler (模組):         distutils bcppcompiler --- Borland Compiler.
                                                             (line    6)
* distutils.ccompiler (模組):            distutils ccompiler --- CCompiler基类.
                                                             (line    6)
* distutils.cmd (模組):                  distutils cmd --- Abstract base class for Distutils commands.
                                                             (line    6)
* distutils.command (模組):              distutils command --- Individual Distutils commands.
                                                             (line    5)
* distutils.command.bdist (模組):        distutils command bdist --- Build a binary installer.
                                                             (line    5)
* distutils.command.bdist_dumb (模組):   distutils command bdist_dumb --- Build a "dumb" installer.
                                                             (line    5)
* distutils.command.bdist_msi (模組):    distutils command bdist_msi --- Build a Microsoft Installer binary package.
                                                             (line    6)
* distutils.command.bdist_packager (模組): distutils command bdist_packager --- Abstract base class for packagers.
                                                             (line    5)
* distutils.command.bdist_rpm (模組):    distutils command bdist_rpm --- Build a binary distribution as a Redhat RPM and SRPM.
                                                             (line    5)
* distutils.command.bdist_wininst (模組): distutils command bdist_wininst --- Build a Windows installer.
                                                             (line    6)
* distutils.command.build (模組):        distutils command build --- Build all files of a package.
                                                             (line    5)
* distutils.command.build_clib (模組):   distutils command build_clib --- Build any C libraries in a package.
                                                             (line    5)
* distutils.command.build_ext (模組):    distutils command build_ext --- Build any extensions in a package.
                                                             (line    5)
* distutils.command.build_py (模組):     distutils command build_py --- Build the py/ pyc files of a package.
                                                             (line    6)
* distutils.command.build_scripts (模組): distutils command build_scripts --- Build the scripts of a package.
                                                             (line    5)
* distutils.command.check (模組):        distutils command check --- Check the meta-data of a package.
                                                             (line    6)
* distutils.command.clean (模組):        distutils command clean --- Clean a package build area.
                                                             (line    6)
* distutils.command.config (模組):       distutils command config --- Perform package configuration.
                                                             (line    5)
* distutils.command.install (模組):      distutils command install --- Install a package.
                                                             (line    5)
* distutils.command.install_data (模組): distutils command install_data --- Install data files from a package.
                                                             (line    5)
* distutils.command.install_headers (模組): distutils command install_headers --- Install C/C++ header files from a package.
                                                             (line    5)
* distutils.command.install_lib (模組):  distutils command install_lib --- Install library files from a package.
                                                             (line    5)
* distutils.command.install_scripts (模組): distutils command install_scripts --- Install script files from a package.
                                                             (line    5)
* distutils.command.register (模組):     distutils command register --- Register a module with the Python Package Index.
                                                             (line    6)
* distutils.command.sdist (模組):        distutils command sdist --- Build a source distribution.
                                                             (line    5)
* distutils.core (模組):                 distutils core --- 分发包功能的核心.
                                                             (line    6)
* distutils.cygwinccompiler (模組):      distutils cygwincompiler --- Cygwin Compiler.
                                                             (line    6)
* distutils.debug (模組):                distutils debug --- Distutils debug mode.
                                                             (line    6)
* distutils.dep_util (模組):             distutils dep_util --- Dependency checking.
                                                             (line    6)
* distutils.dir_util (模組):             distutils dir_util --- Directory tree operations.
                                                             (line    6)
* distutils.dist (模組):                 distutils dist --- The Distribution class.
                                                             (line    6)
* distutils.errors (模組):               distutils errors --- Distutils exceptions.
                                                             (line    6)
* distutils.extension (模組):            distutils extension --- The Extension class.
                                                             (line    6)
* distutils.fancy_getopt (模組):         distutils fancy_getopt --- Wrapper around the standard getopt module.
                                                             (line    6)
* distutils.filelist (模組):             distutils filelist --- The FileList class.
                                                             (line    6)
* distutils.file_util (模組):            distutils file_util --- Single file operations.
                                                             (line    6)
* distutils.log (模組):                  distutils log --- Simple PEP 282-style logging.
                                                             (line    5)
* distutils.msvccompiler (模組):         distutils msvccompiler --- Microsoft Compiler.
                                                             (line    6)
* distutils.spawn (模組):                distutils spawn --- Spawn a sub-process.
                                                             (line    6)
* distutils.sysconfig (模組):            distutils sysconfig --- System configuration information.
                                                             (line    6)
* distutils.text_file (模組):            distutils text_file --- The TextFile class.
                                                             (line    6)
* distutils.unixccompiler (模組):        distutils unixccompiler --- Unix C Compiler.
                                                             (line    6)
* distutils.util (模組):                 distutils util --- Miscellaneous other utility functions.
                                                             (line    6)
* distutils.version (模組):              distutils version --- Version number classes.
                                                             (line    5)
* DISTUTILS_DEBUG:                       Debugging the setup script.
                                                             (line   19)
* Div (ast 中的類別):                    表达式<2>.          (line   54)
* divide() (decimal.Context 的方法):     上下文对象.         (line  236)
* divide_int() (decimal.Context 的方法): 上下文对象.         (line  240)
* division:                              二元算术运算符.     (line   28)
* DivisionByZero (decimal 中的類別):     信号.               (line   28)
* divmod() (decimal.Context 的方法):     上下文对象.         (line  244)
* divmod() (內建函式):                   內建函式.           (line  371)
* DllCanUnloadNow() (於 ctypes 模組中):  工具函数.           (line   65)
* DllGetClassObject() (於 ctypes 模組中): 工具函数.          (line   70)
* dllhandle (於 sys 模組中):             sys --- 系统相关的参数和函数.
                                                             (line  195)
* DndHandler (tkinter.dnd 中的類別):     tkinter dnd --- 拖放操作支持.
                                                             (line   37)
* dnd_start() (於 tkinter.dnd 模組中):   tkinter dnd --- 拖放操作支持.
                                                             (line   58)
* dngettext() (於 gettext 模組中):       GNU gettext API.    (line   57)
* dnpgettext() (於 gettext 模組中):      GNU gettext API.    (line   68)
* doc (json.JSONDecodeError 的屬性):     例外.               (line   14)
* DocCGIXMLRPCRequestHandler (xmlrpc.server 中的類別): XMLRPC 服务器文档.
                                                             (line   21)
* DocFileSuite() (於 doctest 模組中):    Unittest API.       (line   21)
* doClassCleanups() (unittest.TestCase 的類別成員): 测试用例.
                                                             (line  785)
* doCleanups() (unittest.TestCase 的方法): 测试用例.         (line  753)
* docmd() (smtplib.SMTP 的方法):         SMTP 对象.          (line   16)
* docstring:                             类定义.             (line    6)
* docstring (doctest.DocTest 的屬性):    DocTest 对象.       (line   43)
* docstrings:                            定義函式 function.  (line   20)
* docstrings <1>:                        說明文件字串 Documentation Strings.
                                                             (line    6)
* docstring（說明字串）:                 術語表.             (line  322)
* DocTest (doctest 中的類別):            DocTest 对象.       (line    6)
* doctest (模組):                        doctest --- 测试交互性的Python示例.
                                                             (line    6)
* DocTestFailure:                        调试.               (line  162)
* DocTestFinder (doctest 中的類別):      DocTestFinder 对象. (line    6)
* DocTestParser (doctest 中的類別):      DocTestParser 对象. (line    6)
* DocTestRunner (doctest 中的類別):      DocTestRunner 对象. (line    6)
* DocTestSuite() (於 doctest 模組中):    Unittest API.       (line   84)
* doctype() (xml.etree.ElementTree.TreeBuilder 的方法): TreeBuilder 对象.
                                                             (line   58)
* documentation string:                  标准类型层级结构.   (line  543)
* documentation strings:                 定義函式 function.  (line   20)
* documentation strings <1>:             說明文件字串 Documentation Strings.
                                                             (line    6)
* documentation; generation:             pydoc --- 文档生成器和在线帮助系统.
                                                             (line    8)
* documentation; online:                 pydoc --- 文档生成器和在线帮助系统.
                                                             (line    8)
* documentElement (xml.dom.Document 的屬性): Document 对象.  (line    9)
* DocXMLRPCRequestHandler (xmlrpc.server 中的類別): XMLRPC 服务器文档.
                                                             (line   25)
* DocXMLRPCServer (xmlrpc.server 中的類別): XMLRPC 服务器文档.
                                                             (line   10)
* doc_header (cmd.Cmd 的屬性):           Cmd 对象.           (line  118)
* domain (email.headerregistry.Address 的屬性): email headerregistry 自定义标头对象.
                                                             (line  372)
* domain (tracemalloc.DomainFilter 的屬性): 域过滤器.        (line   20)
* domain (tracemalloc.Filter 的屬性):    过滤器<2>.          (line   30)
* domain (tracemalloc.Trace 的屬性):     跟踪.               (line   15)
* DomainFilter (tracemalloc 中的類別):   域过滤器.           (line    6)
* DomainLiberal (http.cookiejar.DefaultCookiePolicy 的屬性): DefaultCookiePolicy 对象.
                                                             (line  141)
* DomainRFC2965Match (http.cookiejar.DefaultCookiePolicy 的屬性): DefaultCookiePolicy 对象.
                                                             (line  135)
* DomainStrict (http.cookiejar.DefaultCookiePolicy 的屬性): DefaultCookiePolicy 对象.
                                                             (line  145)
* DomainStrictNoDots (http.cookiejar.DefaultCookiePolicy 的屬性): DefaultCookiePolicy 对象.
                                                             (line  122)
* DomainStrictNonDomain (http.cookiejar.DefaultCookiePolicy 的屬性): DefaultCookiePolicy 对象.
                                                             (line  128)
* domain_initial_dot (http.cookiejar.Cookie 的屬性): Cookie 对象<2>.
                                                             (line   81)
* domain_return_ok() (http.cookiejar.CookiePolicy 的方法): CookiePolicy 对象.
                                                             (line   23)
* domain_specified (http.cookiejar.Cookie 的屬性): Cookie 对象<2>.
                                                             (line   77)
* DOMEventStream (xml.dom.pulldom 中的類別): DOMEventStream 对象.
                                                             (line    6)
* DOMException:                          异常<15>.           (line   14)
* doModuleCleanups() (於 unittest 模組中): setUpModule and tearDownModule.
                                                             (line   35)
* DomstringSizeErr:                      异常<15>.           (line   18)
* done() (asyncio.Future 的方法):        Future 对象<2>.     (line   52)
* done() (asyncio.Task 的方法):          Task 对象.          (line  104)
* done() (concurrent.futures.Future 的方法): Future 对象.    (line   28)
* done() (graphlib.TopologicalSorter 的方法): graphlib --- 操作类似图的结构的功能.
                                                             (line  115)
* done() (xdrlib.Unpacker 的方法):       Unpacker 对象.      (line   25)
* done() (於 turtle 模組中):             使用屏幕事件.       (line   98)
* DONT_ACCEPT_BLANKLINE (於 doctest 模組中): 选项标记.       (line   25)
* DONT_ACCEPT_TRUE_FOR_1 (於 doctest 模組中): 选项标记.      (line   16)
* dont_write_bytecode (於 sys 模組中):   sys --- 系统相关的参数和函数.
                                                             (line  236)
* doRollover() (logging.handlers.RotatingFileHandler 的方法): RotatingFileHandler.
                                                             (line   37)
* doRollover() (logging.handlers.TimedRotatingFileHandler 的方法): TimedRotatingFileHandler.
                                                             (line   86)
* DOT (於 token 模組中):                 token --- 与Python解析树一起使用的常量.
                                                             (line  114)
* dot() (於 turtle 模組中):              海龟动作.           (line  205)
* DOTALL (於 re 模組中):                 模块内容.           (line   88)
* doublequote (csv.Dialect 的屬性):      变种与格式参数.     (line   20)
* DOUBLESLASH (於 token 模組中):         token --- 与Python解析树一起使用的常量.
                                                             (line  210)
* DOUBLESLASHEQUAL (於 token 模組中):    token --- 与Python解析树一起使用的常量.
                                                             (line  214)
* DOUBLESTAR (於 token 模組中):          token --- 与Python解析树一起使用的常量.
                                                             (line  162)
* DOUBLESTAREQUAL (於 token 模組中):     token --- 与Python解析树一起使用的常量.
                                                             (line  206)
* doupdate() (於 curses 模組中):         函数<4>.            (line   74)
* down (pdb command):                    调试器命令.         (line   46)
* down() (於 turtle 模組中):             绘图状态.           (line    6)
* do_clear() (bdb.Bdb 的方法):           bdb --- Debugger framework.
                                                             (line  233)
* do_command() (curses.textpad.Textbox 的方法): 文本框对象.  (line   25)
* do_GET() (http.server.SimpleHTTPRequestHandler 的方法): http server --- HTTP 服务器.
                                                             (line  318)
* do_handshake() (ssl.SSLSocket 的方法): SSL 套接字.         (line  107)
* do_HEAD() (http.server.SimpleHTTPRequestHandler 的方法): http server --- HTTP 服务器.
                                                             (line  312)
* do_POST() (http.server.CGIHTTPRequestHandler 的方法): http server --- HTTP 服务器.
                                                             (line  410)
* dpgettext() (於 gettext 模組中):       GNU gettext API.    (line   64)
* drain() (asyncio.StreamWriter 的方法): StreamWriter.       (line   61)
* dropwhile() (於 itertools 模組中):     Itertool函数.       (line  239)
* drop_whitespace (textwrap.TextWrapper 的屬性): textwrap --- 文本自动换行与填充.
                                                             (line  181)
* dst() (datetime.datetime 的方法):      datetime 对象.      (line  437)
* dst() (datetime.time 的方法):          time 对象.          (line  209)
* dst() (datetime.timezone 的方法):      timezone 对象.      (line   46)
* dst() (datetime.tzinfo 的方法):        tzinfo 对象.        (line   55)
* DTDHandler (xml.sax.handler 中的類別): xml sax handler --- SAX 处理句柄的基类.
                                                             (line   20)
* duck-typing（鴨子型別）:               術語表.             (line  329)
* DumbWriter (formatter 中的類別):       Writer Implementations.
                                                             (line   22)
* dump() (pickle.Pickler 的方法):        模块接口.           (line  138)
* dump() (tracemalloc.Snapshot 的方法):  快照.               (line   29)
* dump() (於 ast 模組中):                ast 中的辅助函数.   (line  224)
* dump() (於 json 模組中):               基本使用.           (line    6)
* dump() (於 marshal 模組中):            marshal --- 内部 Python 对象序列化.
                                                             (line   36)
* dump() (於 pickle 模組中):             模块接口.           (line   31)
* dump() (於 plistlib 模組中):           plistlib --- 生成与解析 Apple plist 文件.
                                                             (line   74)
* dump() (於 xml.etree.ElementTree 模組中): 函数<7>.         (line   75)
* dumps() (於 json 模組中):              基本使用.           (line   68)
* dumps() (於 marshal 模組中):           marshal --- 内部 Python 对象序列化.
                                                             (line   66)
* dumps() (於 pickle 模組中):            模块接口.           (line   42)
* dumps() (於 plistlib 模組中):          plistlib --- 生成与解析 Apple plist 文件.
                                                             (line   99)
* dumps() (於 xmlrpc.client 模組中):     便捷函数.           (line    6)
* dump_stats() (profile.Profile 的方法): profile 和 cProfile 模块参考.
                                                             (line   94)
* dump_stats() (pstats.Stats 的方法):    Stats 类.           (line   59)
* dump_traceback() (於 faulthandler 模組中): 转储跟踪信息.   (line    6)
* dump_traceback_later() (於 faulthandler 模組中): 一定时间后转储跟踪数据。.
                                                             (line    6)
* dup() (socket.socket 的方法):          套接字对象.         (line   87)
* dup() (於 os 模組中):                  文件描述符操作.     (line   63)
* dup2() (於 os 模組中):                 文件描述符操作.     (line   73)
* DuplicateOptionError:                  异常<5>.            (line   22)
* DuplicateSectionError:                 异常<5>.            (line   14)
* DUP_TOP (opcode):                      Python字节码说明.   (line   75)
* DUP_TOP_TWO (opcode):                  Python字节码说明.   (line   81)
* dwFlags (subprocess.STARTUPINFO 的屬性): Windows Popen 助手.
                                                             (line   17)
* DynamicClassAttribute() (於 types 模組中): 附加工具类和函数.
                                                             (line   37)
* D_FMT (於 locale 模組中):              locale --- 国际化服务.
                                                             (line  158)
* D_T_FMT (於 locale 模組中):            locale --- 国际化服务.
                                                             (line  153)
* e (於 cmath 模組中):                   常数<2>.            (line   10)
* e (於 math 模組中):                    常数.               (line   10)
* E2BIG (於 errno 模組中):               errno --- 标准 errno 系统符号.
                                                             (line   50)
* e; in numeric literal:                 整数字面值.         (line   35)
* EACCES (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line   74)
* EADDRINUSE (於 errno 模組中):          errno --- 标准 errno 系统符号.
                                                             (line  414)
* EADDRNOTAVAIL (於 errno 模組中):       errno --- 标准 errno 系统符号.
                                                             (line  418)
* EADV (於 errno 模組中):                errno --- 标准 errno 系统符号.
                                                             (line  294)
* EAFNOSUPPORT (於 errno 模組中):        errno --- 标准 errno 系统符号.
                                                             (line  410)
* EAFP:                                  術語表.             (line  341)
* EAGAIN (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line   66)
* EALREADY (於 errno 模組中):            errno --- 标准 errno 系统符号.
                                                             (line  478)
* east_asian_width() (於 unicodedata 模組中): unicodedata --- Unicode 数据库.
                                                             (line   55)
* EBADE (於 errno 模組中):               errno --- 标准 errno 系统符号.
                                                             (line  230)
* EBADF (於 errno 模組中):               errno --- 标准 errno 系统符号.
                                                             (line   58)
* EBADFD (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line  330)
* EBADMSG (於 errno 模組中):             errno --- 标准 errno 系统符号.
                                                             (line  318)
* EBADR (於 errno 模組中):               errno --- 标准 errno 系统符号.
                                                             (line  234)
* EBADRQC (於 errno 模組中):             errno --- 标准 errno 系统符号.
                                                             (line  246)
* EBADSLT (於 errno 模組中):             errno --- 标准 errno 系统符号.
                                                             (line  250)
* EBFONT (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line  258)
* EBUSY (於 errno 模組中):               errno --- 标准 errno 系统符号.
                                                             (line   86)
* ECHILD (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line   62)
* echo() (於 curses 模組中):             函数<4>.            (line   86)
* echochar() (curses.window 的方法):     Window 对象.        (line  169)
* ECHRNG (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line  198)
* ECOMM (於 errno 模組中):               errno --- 标准 errno 系统符号.
                                                             (line  302)
* ECONNABORTED (於 errno 模組中):        errno --- 标准 errno 系统符号.
                                                             (line  434)
* ECONNREFUSED (於 errno 模組中):        errno --- 标准 errno 系统符号.
                                                             (line  466)
* ECONNRESET (於 errno 模組中):          errno --- 标准 errno 系统符号.
                                                             (line  438)
* EDEADLK (於 errno 模組中):             errno --- 标准 errno 系统符号.
                                                             (line  162)
* EDEADLOCK (於 errno 模組中):           errno --- 标准 errno 系统符号.
                                                             (line  254)
* EDESTADDRREQ (於 errno 模組中):        errno --- 标准 errno 系统符号.
                                                             (line  378)
* edit() (curses.textpad.Textbox 的方法): 文本框对象.        (line   17)
* EDOM (於 errno 模組中):                errno --- 标准 errno 系统符号.
                                                             (line  154)
* EDOTDOT (於 errno 模組中):             errno --- 标准 errno 系统符号.
                                                             (line  314)
* EDQUOT (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line  510)
* EEXIST (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line   90)
* EFAULT (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line   78)
* EFBIG (於 errno 模組中):               errno --- 标准 errno 系统符号.
                                                             (line  130)
* effective() (於 bdb 模組中):           bdb --- Debugger framework.
                                                             (line  396)
* ehlo() (smtplib.SMTP 的方法):          SMTP 对象.          (line   50)
* ehlo_or_helo_if_needed() (smtplib.SMTP 的方法): SMTP 对象. (line   62)
* EHOSTDOWN (於 errno 模組中):           errno --- 标准 errno 系统符号.
                                                             (line  470)
* EHOSTUNREACH (於 errno 模組中):        errno --- 标准 errno 系统符号.
                                                             (line  474)
* EIDRM (於 errno 模組中):               errno --- 标准 errno 系统符号.
                                                             (line  194)
* EILSEQ (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line  358)
* EINPROGRESS (於 errno 模組中):         errno --- 标准 errno 系统符号.
                                                             (line  482)
* EINTR (於 errno 模組中):               errno --- 标准 errno 系统符号.
                                                             (line   33)
* EINVAL (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line  110)
* EIO (於 errno 模組中):                 errno --- 标准 errno 系统符号.
                                                             (line   42)
* EISCONN (於 errno 模組中):             errno --- 标准 errno 系统符号.
                                                             (line  446)
* EISDIR (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line  106)
* EISNAM (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line  502)
* EL2HLT (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line  226)
* EL2NSYNC (於 errno 模組中):            errno --- 标准 errno 系统符号.
                                                             (line  202)
* EL3HLT (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line  206)
* EL3RST (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line  210)
* Element (xml.etree.ElementTree 中的類別): 元素对象.        (line    6)
* ElementDeclHandler() (xml.parsers.expat.xmlparser 的方法): XMLParser对象<2>.
                                                             (line  168)
* elements() (collections.Counter 的方法): Counter 物件.     (line   59)
* ElementTree (xml.etree.ElementTree 中的類別): ElementTree 对象.
                                                             (line    6)
* element_create() (tkinter.ttk.Style 的方法): Ttk 风格.     (line  126)
* element_names() (tkinter.ttk.Style 的方法): Ttk 风格.      (line  178)
* element_options() (tkinter.ttk.Style 的方法): Ttk 风格.    (line  182)
* ELIBACC (於 errno 模組中):             errno --- 标准 errno 系统符号.
                                                             (line  338)
* ELIBBAD (於 errno 模組中):             errno --- 标准 errno 系统符号.
                                                             (line  342)
* ELIBEXEC (於 errno 模組中):            errno --- 标准 errno 系统符号.
                                                             (line  354)
* ELIBMAX (於 errno 模組中):             errno --- 标准 errno 系统符号.
                                                             (line  350)
* ELIBSCN (於 errno 模組中):             errno --- 标准 errno 系统符号.
                                                             (line  346)
* Ellinghouse, Lance:                    uu --- 对 uuencode 文件进行编码与解码.
                                                             (line   17)
* Ellipsis (內建變數):                   內建常數.           (line   48)
* ELLIPSIS (於 doctest 模組中):          选项标记.           (line   39)
* ELLIPSIS (於 token 模組中):            token --- 与Python解析树一起使用的常量.
                                                             (line  230)
* ELNRNG (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line  214)
* ELOOP (於 errno 模組中):               errno --- 标准 errno 系统符号.
                                                             (line  182)
* else; conditional expression:          条件表达式.         (line    6)
* email (模組):                          email --- 电子邮件与 MIME 处理包.
                                                             (line    6)
* email.charset (模組):                  email charset 表示字符集.
                                                             (line    6)
* email.contentmanager (模組):           email contentmanager 管理 MIME 内容.
                                                             (line    6)
* email.encoders (模組):                 email encoders 编码器.
                                                             (line    6)
* email.errors (模組):                   email errors 异常和缺陷类.
                                                             (line    6)
* email.generator (模組):                email generator 生成 MIME 文档.
                                                             (line    6)
* email.header (模組):                   email header 国际化标头.
                                                             (line    6)
* email.headerregistry (模組):           email headerregistry 自定义标头对象.
                                                             (line    6)
* email.iterators (模組):                email iterators 迭代器.
                                                             (line    6)
* email.message (模組):                  email message 表示一封电子邮件信息.
                                                             (line    6)
* email.mime (模組):                     email mime 从头创建电子邮件和 MIME 对象.
                                                             (line    6)
* email.parser (模組):                   email parser 解析电子邮件信息.
                                                             (line    6)
* email.policy (模組):                   email policy Policy 对象.
                                                             (line    6)
* email.utils (模組):                    email utils 其他工具.
                                                             (line    6)
* EmailMessage (email.message 中的類別): email message 表示一封电子邮件信息.
                                                             (line   40)
* EmailPolicy (email.policy 中的類別):   email policy Policy 对象.
                                                             (line  274)
* EMFILE (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line  118)
* emit() (logging.FileHandler 的方法):   FileHandler.        (line   28)
* emit() (logging.Handler 的方法):       处理器对象.         (line   91)
* emit() (logging.handlers.BufferingHandler 的方法): MemoryHandler.
                                                             (line   20)
* emit() (logging.handlers.DatagramHandler 的方法): DatagramHandler.
                                                             (line   17)
* emit() (logging.handlers.HTTPHandler 的方法): HTTPHandler. (line   31)
* emit() (logging.handlers.NTEventLogHandler 的方法): NTEventLogHandler.
                                                             (line   30)
* emit() (logging.handlers.QueueHandler 的方法): QueueHandler.
                                                             (line   26)
* emit() (logging.handlers.RotatingFileHandler 的方法): RotatingFileHandler.
                                                             (line   41)
* emit() (logging.handlers.SMTPHandler 的方法): SMTPHandler. (line   28)
* emit() (logging.handlers.SocketHandler 的方法): SocketHandler.
                                                             (line   21)
* emit() (logging.handlers.SysLogHandler 的方法): SysLogHandler.
                                                             (line   38)
* emit() (logging.handlers.TimedRotatingFileHandler 的方法): TimedRotatingFileHandler.
                                                             (line   90)
* emit() (logging.handlers.WatchedFileHandler 的方法): WatchedFileHandler.
                                                             (line   42)
* emit() (logging.NullHandler 的方法):   NullHandler.        (line   15)
* emit() (logging.StreamHandler 的方法): StreamHandler.      (line   15)
* EMLINK (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line  146)
* Empty:                                 queue --- 一个同步的队列类.
                                                             (line   68)
* empty (inspect.Parameter 的屬性):      Introspecting callables with the Signature object.
                                                             (line  151)
* empty (inspect.Signature 的屬性):      Introspecting callables with the Signature object.
                                                             (line   73)
* empty() (asyncio.Queue 的方法):        队列.               (line   26)
* empty() (multiprocessing.Queue 的方法): 管道和队列.        (line   92)
* empty() (multiprocessing.SimpleQueue 的方法): 管道和队列.  (line  186)
* empty() (queue.Queue 的方法):          Queue对象.          (line   14)
* empty() (queue.SimpleQueue 的方法):    SimpleQueue 对象.   (line   12)
* empty() (sched.scheduler 的方法):      调度器对象.         (line   41)
* empty; list:                           列表显示.           (line    6)
* empty; tuple:                          标准类型层级结构.   (line  135)
* empty; tuple <1>:                      带圆括号的形式.     (line   14)
* emptyline() (cmd.Cmd 的方法):          Cmd 对象.           (line   52)
* EMPTY_NAMESPACE (於 xml.dom 模組中):   模块内容<6>.        (line   29)
* EMSGSIZE (於 errno 模組中):            errno --- 标准 errno 系统符号.
                                                             (line  382)
* EMULTIHOP (於 errno 模組中):           errno --- 标准 errno 系统符号.
                                                             (line  310)
* enable (pdb command):                  调试器命令.         (line   87)
* enable() (bdb.Breakpoint 的方法):      bdb --- Debugger framework.
                                                             (line   47)
* enable() (imaplib.IMAP4 的方法):       IMAP4 对象.         (line   74)
* enable() (profile.Profile 的方法):     profile 和 cProfile 模块参考.
                                                             (line   77)
* enable() (於 cgitb 模組中):            cgitb --- 用于 CGI 脚本的回溯管理器.
                                                             (line   25)
* enable() (於 faulthandler 模組中):     错误处理程序的状态. (line    6)
* enable() (於 gc 模組中):               gc --- 垃圾回收器接口.
                                                             (line   18)
* EnableControlFlowGuard:                构建<4>.            (line    6)
* EnableReflectionKey() (於 winreg 模組中): 函数<12>.        (line  452)
* enable_callback_tracebacks() (於 sqlite3 模組中): 模块函数和常量.
                                                             (line  193)
* enable_interspersed_args() (optparse.OptionParser 的方法): Querying and manipulating your option parser.
                                                             (line   31)
* enable_load_extension() (sqlite3.Connection 的方法): 连接对象（Connection）.
                                                             (line  233)
* enable_traversal() (tkinter.ttk.Notebook 的方法): ttk Notebook.
                                                             (line   65)
* ENABLE_USER_SITE (於 site 模組中):     模块内容<8>.        (line   10)
* ENAMETOOLONG (於 errno 模組中):        errno --- 标准 errno 系统符号.
                                                             (line  166)
* ENAVAIL (於 errno 模組中):             errno --- 标准 errno 系统符号.
                                                             (line  498)
* enclose() (curses.window 的方法):      Window 对象.        (line  174)
* encode (codecs.CodecInfo 的屬性):      codecs --- 编解码器注册和相关基类.
                                                             (line   60)
* encode() (codecs.Codec 的方法):        无状态的编码和解码. (line    9)
* encode() (codecs.IncrementalEncoder 的方法): IncrementalEncoder 对象.
                                                             (line   24)
* encode() (email.header.Header 的方法): email header 国际化标头.
                                                             (line  101)
* encode() (json.JSONEncoder 的方法):    编码器和解码器.     (line  195)
* encode() (str 的方法):                 字符串的方法<2>.    (line   51)
* encode() (xmlrpc.client.Binary 的方法): Binary 对象.       (line   24)
* encode() (xmlrpc.client.DateTime 的方法): 日期時間物件.    (line   16)
* encode() (於 base64 模組中):           base64 —— Base16、Base32、Base64、Base85 資料編碼.
                                                             (line  192)
* encode() (於 codecs 模組中):           codecs --- 编解码器注册和相关基类.
                                                             (line   19)
* encode() (於 quopri 模組中):           quopri --- 编码与解码经过 MIME 转码的可打印数据.
                                                             (line   26)
* encode() (於 uu 模組中):               uu --- 对 uuencode 文件进行编码与解码.
                                                             (line   21)
* encodebytes() (於 base64 模組中):      base64 —— Base16、Base32、Base64、Base85 資料編碼.
                                                             (line  200)
* EncodedFile() (於 codecs 模組中):      codecs --- 编解码器注册和相关基类.
                                                             (line  165)
* encodePriority() (logging.handlers.SysLogHandler 的方法): SysLogHandler.
                                                             (line   63)
* encodestring() (於 quopri 模組中):     quopri --- 编码与解码经过 MIME 转码的可打印数据.
                                                             (line   40)
* encode_7or8bit() (於 email.encoders 模組中): email encoders 编码器.
                                                             (line   49)
* encode_base64() (於 email.encoders 模組中): email encoders 编码器.
                                                             (line   42)
* encode_noop() (於 email.encoders 模組中): email encoders 编码器.
                                                             (line   54)
* encode_quopri() (於 email.encoders 模組中): email encoders 编码器.
                                                             (line   35)
* encode_rfc2231() (於 email.utils 模組中): email utils 其他工具.
                                                             (line  152)
* encoding (curses.window 的屬性):       Window 对象.        (line  180)
* encoding (io.TextIOBase 的屬性):       文本 I/O<2>.        (line   14)
* encoding (UnicodeError 的屬性):        具体异常.           (line  309)
* ENCODING (於 tarfile 模組中):          tarfile --- 读写tar归档文件.
                                                             (line  196)
* ENCODING (於 token 模組中):            token --- 与Python解析树一起使用的常量.
                                                             (line  267)
* encoding declarations (source file):   编码声明.           (line    6)
* encodings.idna (模組):                 encodings idna --- 应用程序中的国际化域名.
                                                             (line    6)
* encodings.mbcs (模組):                 encodings mbcs --- Windows ANSI代码页.
                                                             (line    6)
* encodings.utf_8_sig (模組):            encodings utf_8_sig --- 带BOM签名的UTF-8编解码器.
                                                             (line    6)
* encodings_map (mimetypes.MimeTypes 的屬性): MimeTypes 对象.
                                                             (line   26)
* encodings_map (於 mimetypes 模組中):   mimetypes --- 映射文件名到 MIME 类型.
                                                             (line  113)
* end (UnicodeError 的屬性):             具体异常.           (line  325)
* end() (re.Match 的方法):               匹配对象.           (line  112)
* end() (xml.etree.ElementTree.TreeBuilder 的方法): TreeBuilder 对象.
                                                             (line   33)
* EndCdataSectionHandler() (xml.parsers.expat.xmlparser 的方法): XMLParser对象<2>.
                                                             (line  256)
* EndDoctypeDeclHandler() (xml.parsers.expat.xmlparser 的方法): XMLParser对象<2>.
                                                             (line  163)
* endDocument() (xml.sax.handler.ContentHandler 的方法): ContentHandler 对象.
                                                             (line   33)
* endElement() (xml.sax.handler.ContentHandler 的方法): ContentHandler 对象.
                                                             (line   79)
* EndElementHandler() (xml.parsers.expat.xmlparser 的方法): XMLParser对象<2>.
                                                             (line  192)
* endElementNS() (xml.sax.handler.ContentHandler 的方法): ContentHandler 对象.
                                                             (line  101)
* endheaders() (http.client.HTTPConnection 的方法): HTTPConnection 对象.
                                                             (line  120)
* ENDMARKER (於 token 模組中):           token --- 与Python解析树一起使用的常量.
                                                             (line   36)
* EndNamespaceDeclHandler() (xml.parsers.expat.xmlparser 的方法): XMLParser对象<2>.
                                                             (line  237)
* endpos (re.Match 的屬性):              匹配对象.           (line  146)
* endPrefixMapping() (xml.sax.handler.ContentHandler 的方法): ContentHandler 对象.
                                                             (line   61)
* endswith() (bytearray 的方法):         bytes 和 bytearray 操作.
                                                             (line  100)
* endswith() (bytes 的方法):             bytes 和 bytearray 操作.
                                                             (line  100)
* endswith() (str 的方法):               字符串的方法<2>.    (line   70)
* endwin() (於 curses 模組中):           函数<4>.            (line   91)
* END_ASYNC_FOR (opcode):                Python字节码说明.   (line  274)
* end_col_offset (ast.AST 的屬性):       节点类.             (line   32)
* end_fill() (於 turtle 模組中):         填充.               (line   20)
* end_headers() (http.server.BaseHTTPRequestHandler 的方法): http server --- HTTP 服务器.
                                                             (line  226)
* end_lineno (ast.AST 的屬性):           节点类.             (line   32)
* end_ns() (xml.etree.ElementTree.TreeBuilder 的方法): TreeBuilder 对象.
                                                             (line   75)
* end_paragraph() (formatter.formatter 的方法): The Formatter Interface.
                                                             (line   26)
* end_poly() (於 turtle 模組中):         特殊海龟方法.       (line   10)
* ENETDOWN (於 errno 模組中):            errno --- 标准 errno 系统符号.
                                                             (line  422)
* ENETRESET (於 errno 模組中):           errno --- 标准 errno 系统符号.
                                                             (line  430)
* ENETUNREACH (於 errno 模組中):         errno --- 标准 errno 系统符号.
                                                             (line  426)
* ENFILE (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line  114)
* ENOANO (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line  242)
* ENOBUFS (於 errno 模組中):             errno --- 标准 errno 系统符号.
                                                             (line  442)
* ENOCSI (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line  222)
* ENODATA (於 errno 模組中):             errno --- 标准 errno 系统符号.
                                                             (line  266)
* ENODEV (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line   98)
* ENOENT (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line   25)
* ENOEXEC (於 errno 模組中):             errno --- 标准 errno 系统符号.
                                                             (line   54)
* ENOLCK (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line  170)
* ENOLINK (於 errno 模組中):             errno --- 标准 errno 系统符号.
                                                             (line  290)
* ENOMEM (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line   70)
* ENOMSG (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line  190)
* ENONET (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line  278)
* ENOPKG (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line  282)
* ENOPROTOOPT (於 errno 模組中):         errno --- 标准 errno 系统符号.
                                                             (line  390)
* ENOSPC (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line  134)
* ENOSR (於 errno 模組中):               errno --- 标准 errno 系统符号.
                                                             (line  274)
* ENOSTR (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line  262)
* ENOSYS (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line  174)
* ENOTBLK (於 errno 模組中):             errno --- 标准 errno 系统符号.
                                                             (line   82)
* ENOTCONN (於 errno 模組中):            errno --- 标准 errno 系统符号.
                                                             (line  450)
* ENOTDIR (於 errno 模組中):             errno --- 标准 errno 系统符号.
                                                             (line  102)
* ENOTEMPTY (於 errno 模組中):           errno --- 标准 errno 系统符号.
                                                             (line  178)
* ENOTNAM (於 errno 模組中):             errno --- 标准 errno 系统符号.
                                                             (line  494)
* ENOTSOCK (於 errno 模組中):            errno --- 标准 errno 系统符号.
                                                             (line  374)
* ENOTTY (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line  122)
* ENOTUNIQ (於 errno 模組中):            errno --- 标准 errno 系统符号.
                                                             (line  326)
* enqueue() (logging.handlers.QueueHandler 的方法): QueueHandler.
                                                             (line   44)
* enqueue_sentinel() (logging.handlers.QueueListener 的方法): QueueListener.
                                                             (line   74)
* ensurepip (模組):                      ensurepip --- Bootstrapping the pip installer.
                                                             (line    6)
* ensure_directories() (venv.EnvBuilder 的方法): API<2>.     (line   76)
* ensure_future() (於 asyncio 模組中):   Future 函数.        (line   18)
* enter() (sched.scheduler 的方法):      调度器对象.         (line   26)
* enterabs() (sched.scheduler 的方法):   调度器对象.         (line    8)
* enter_async_context() (contextlib.AsyncExitStack 的方法): 工具.
                                                             (line  429)
* enter_context() (contextlib.ExitStack 的方法): 工具.       (line  348)
* entities (xml.dom.DocumentType 的屬性): 文档类型对象.      (line   31)
* EntityDeclHandler() (xml.parsers.expat.xmlparser 的方法): XMLParser对象<2>.
                                                             (line  214)
* entitydefs (於 html.entities 模組中):  html entities --- HTML 一般实体的定义.
                                                             (line   22)
* EntityResolver (xml.sax.handler 中的類別): xml sax handler --- SAX 处理句柄的基类.
                                                             (line   26)
* Enum (enum 中的類別):                  模块内容<2>.        (line   11)
* enum (模組):                           enum --- 对枚举的支持.
                                                             (line    6)
* enumerate() (內建函式):                內建函式.           (line  380)
* enumerate() (於 threading 模組中):     threading --- 基于线程的并行.
                                                             (line   93)
* EnumKey() (於 winreg 模組中):          函数<12>.           (line  161)
* EnumValue() (於 winreg 模組中):        函数<12>.           (line  178)
* enum_certificates() (於 ssl 模組中):   证书处理.           (line  112)
* enum_crls() (於 ssl 模組中):           证书处理.           (line  133)
* EnvBuilder (venv 中的類別):            API<2>.             (line   10)
* environ (於 os 模組中):                进程参数.           (line   14)
* environ (於 posix 模組中):             重要的模块内容.     (line    9)
* environb (於 os 模組中):               进程参数.           (line   45)
* environment:                           名称的解析.         (line   11)
* environment variables; deleting:       进程参数.           (line  454)
* environment variables; setting:        进程参数.           (line  291)
* EnvironmentError:                      具体异常.           (line  357)
* Environments; virtual:                 venv --- 创建虚拟环境.
                                                             (line   10)
* EnvironmentVarGuard (test.support 中的類別): test support --- Utilities for the Python test suite.
                                                             (line 1045)
* ENXIO (於 errno 模組中):               errno --- 标准 errno 系统符号.
                                                             (line   46)
* eof (bz2.BZ2Decompressor 的屬性):      增量压缩和解压.     (line   61)
* eof (lzma.LZMADecompressor 的屬性):    在内存中压缩和解压缩数据.
                                                             (line  132)
* eof (shlex.shlex 的屬性):              shlex 对象.         (line  145)
* eof (ssl.MemoryBIO 的屬性):            内存 BIO 支持<2>.   (line  126)
* eof (zlib.Decompress 的屬性):          zlib --- 与 gzip 兼容的压缩.
                                                             (line  188)
* EOFError:                              具体异常.           (line   18)
* EOFError (built-in exception):         檔案（File）物件.   (line   36)
* eof_received() (asyncio.BufferedProtocol 的方法): 缓冲流协议.
                                                             (line   32)
* eof_received() (asyncio.Protocol 的方法): 流式协议.        (line   26)
* EOPNOTSUPP (於 errno 模組中):          errno --- 标准 errno 系统符号.
                                                             (line  402)
* EOVERFLOW (於 errno 模組中):           errno --- 标准 errno 系统符号.
                                                             (line  322)
* EPERM (於 errno 模組中):               errno --- 标准 errno 系统符号.
                                                             (line   21)
* EPFNOSUPPORT (於 errno 模組中):        errno --- 标准 errno 系统符号.
                                                             (line  406)
* epilogue (email.message.EmailMessage 的屬性): email message 表示一封电子邮件信息.
                                                             (line  594)
* epilogue (email.message.Message 的屬性): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  602)
* EPIPE (於 errno 模組中):               errno --- 标准 errno 系统符号.
                                                             (line  150)
* epoch:                                 time --- 时间的访问和转换.
                                                             (line   15)
* epoll() (於 select 模組中):            select --- 等待 I/O 完成.
                                                             (line   43)
* EpollSelector (selectors 中的類別):    类<2>.              (line  153)
* EPROTO (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line  306)
* EPROTONOSUPPORT (於 errno 模組中):     errno --- 标准 errno 系统符号.
                                                             (line  394)
* EPROTOTYPE (於 errno 模組中):          errno --- 标准 errno 系统符号.
                                                             (line  386)
* Eq (ast 中的類別):                     表达式<2>.          (line  109)
* eq() (於 operator 模組中):             operator --- 标准运算符替代函数.
                                                             (line   19)
* EQEQUAL (於 token 模組中):             token --- 与Python解析树一起使用的常量.
                                                             (line  130)
* EQUAL (於 token 模組中):               token --- 与Python解析树一起使用的常量.
                                                             (line  110)
* ERA (於 locale 模組中):                locale --- 国际化服务.
                                                             (line  219)
* ERANGE (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line  158)
* erase() (curses.window 的方法):        Window 对象.        (line  189)
* erasechar() (於 curses 模組中):        函数<4>.            (line   95)
* ERA_D_FMT (於 locale 模組中):          locale --- 国际化服务.
                                                             (line  235)
* ERA_D_T_FMT (於 locale 模組中):        locale --- 国际化服务.
                                                             (line  230)
* ERA_T_FMT (於 locale 模組中):          locale --- 国际化服务.
                                                             (line  240)
* EREMCHG (於 errno 模組中):             errno --- 标准 errno 系统符号.
                                                             (line  334)
* EREMOTE (於 errno 模組中):             errno --- 标准 errno 系统符号.
                                                             (line  286)
* EREMOTEIO (於 errno 模組中):           errno --- 标准 errno 系统符号.
                                                             (line  506)
* ERESTART (於 errno 模組中):            errno --- 标准 errno 系统符号.
                                                             (line  362)
* erf() (於 math 模組中):                特殊函数.           (line    6)
* erfc() (於 math 模組中):               特殊函数.           (line   19)
* EROFS (於 errno 模組中):               errno --- 标准 errno 系统符号.
                                                             (line  142)
* ERR (於 curses 模組中):                常量<2>.            (line    8)
* errcheck (ctypes._FuncPtr 的屬性):     外部函数.           (line   46)
* errcode (xmlrpc.client.ProtocolError 的屬性): ProtocolError 对象.
                                                             (line   16)
* errmsg (xmlrpc.client.ProtocolError 的屬性): ProtocolError 对象.
                                                             (line   20)
* errno (OSError 的屬性):                具体异常.           (line  113)
* errno (模組):                          errno --- 标准 errno 系统符号.
                                                             (line    6)
* error:                                 模块内容.           (line  297)
* error <1>:                             函数和异常.         (line    8)
* Error:                                 copy --- 浅层 shallow 和深层 deep 复制操作.
                                                             (line   24)
* Error <1>:                             目录和文件操作.     (line  340)
* error <2>:                             dbm --- Unix "数据库" 接口.
                                                             (line   15)
* error <3>:                             dbm gnu --- GNU 对 dbm 的重解析.
                                                             (line   19)
* error <4>:                             dbm ndbm --- 基于 ndbm 的接口.
                                                             (line   17)
* error <5>:                             dbm dumb --- 便携式 DBM 实现.
                                                             (line   20)
* Error <2>:                             异常<4>.            (line   10)
* error <6>:                             zlib --- 与 gzip 兼容的压缩.
                                                             (line   20)
* Error <3>:                             模块内容<3>.        (line  241)
* Error <4>:                             异常<5>.            (line    6)
* Error <5>:                             异常<6>.            (line    8)
* error <7>:                             os --- 多种操作系统接口.
                                                             (line   36)
* error <8>:                             getopt --- C 风格的命令行选项解析器.
                                                             (line   63)
* error <9>:                             函数<4>.            (line    8)
* error <10>:                            _thread --- 底层多线程 API.
                                                             (line   17)
* error <11>:                            异常<11>.           (line    6)
* error <12>:                            select --- 等待 I/O 完成.
                                                             (line   21)
* Error <6>:                             异常<13>.           (line    8)
* Error <7>:                             binhex --- 对binhex4文件进行编码和解码.
                                                             (line   31)
* Error <8>:                             binascii --- 二进制和 ASCII 码互转.
                                                             (line  155)
* Error <9>:                             uu --- 对 uuencode 文件进行编码与解码.
                                                             (line   43)
* error <13>:                            xml parsers expat --- 使用 Expat 的快速 XML 解析.
                                                             (line   27)
* Error <10>:                            webbrowser --- 方便的Web浏览器控制器.
                                                             (line   34)
* error <14>:                            audioop --- 处理原始音频数据.
                                                             (line   22)
* Error <11>:                            sunau --- 读写 Sun AU 文件.
                                                             (line   65)
* Error <12>:                            wave --- 读写WAV格式文件.
                                                             (line   43)
* Error <13>:                            locale --- 国际化服务.
                                                             (line   19)
* error <15>:                            resource --- 资源使用信息.
                                                             (line   15)
* error <16>:                            nis --- Sun 的 NIS 黄页 接口.
                                                             (line   49)
* error handling:                        异常.               (line    6)
* error() (argparse.ArgumentParser 的方法): 退出方法.        (line   18)
* error() (logging.Logger 的方法):       记录器对象.         (line  187)
* error() (urllib.request.OpenerDirector 的方法): OpenerDirector 对象.
                                                             (line   52)
* error() (xml.sax.handler.ErrorHandler 的方法): ErrorHandler 对象.
                                                             (line   13)
* error() (於 logging 模組中):           模块级函数.         (line  108)
* ErrorByteIndex (xml.parsers.expat.xmlparser 的屬性): XMLParser对象<2>.
                                                             (line  107)
* ErrorCode (xml.parsers.expat.xmlparser 的屬性): XMLParser对象<2>.
                                                             (line  111)
* errorcode (於 errno 模組中):           errno --- 标准 errno 系统符号.
                                                             (line   11)
* ErrorColumnNumber (xml.parsers.expat.xmlparser 的屬性): XMLParser对象<2>.
                                                             (line  116)
* ErrorHandler (xml.sax.handler 中的類別): xml sax handler --- SAX 处理句柄的基类.
                                                             (line   31)
* ErrorLineNumber (xml.parsers.expat.xmlparser 的屬性): XMLParser对象<2>.
                                                             (line  120)
* errors:                                异常.               (line    6)
* errors (io.TextIOBase 的屬性):         文本 I/O<2>.        (line   19)
* errors (unittest.TestLoader 的屬性):   Loading and running tests.
                                                             (line   17)
* errors (unittest.TestResult 的屬性):   Loading and running tests.
                                                             (line  236)
* Errors; logging:                       logging --- Python 的日志记录工具.
                                                             (line    8)
* ErrorString() (於 xml.parsers.expat 模組中): xml parsers expat --- 使用 Expat 的快速 XML 解析.
                                                             (line   37)
* ERRORTOKEN (於 token 模組中):          token --- 与Python解析树一起使用的常量.
                                                             (line  248)
* error_body (wsgiref.handlers.BaseHandler 的屬性): wsgiref handlers -- 服务器/网关基类.
                                                             (line  215)
* error_content_type (http.server.BaseHTTPRequestHandler 的屬性): http server --- HTTP 服务器.
                                                             (line  129)
* error_headers (wsgiref.handlers.BaseHandler 的屬性): wsgiref handlers -- 服务器/网关基类.
                                                             (line  209)
* error_leader() (shlex.shlex 的方法):   shlex 对象.         (line   58)
* error_message_format (http.server.BaseHTTPRequestHandler 的屬性): http server --- HTTP 服务器.
                                                             (line  123)
* error_output() (wsgiref.handlers.BaseHandler 的方法): wsgiref handlers -- 服务器/网关基类.
                                                             (line  187)
* error_perm:                            ftplib --- FTP 协议客户端.
                                                             (line  122)
* error_proto:                           ftplib --- FTP 协议客户端.
                                                             (line  127)
* error_proto <1>:                       poplib --- POP3 协议客户端.
                                                             (line   74)
* error_received() (asyncio.DatagramProtocol 的方法): 数据报协议.
                                                             (line   14)
* error_reply:                           ftplib --- FTP 协议客户端.
                                                             (line  113)
* error_status (wsgiref.handlers.BaseHandler 的屬性): wsgiref handlers -- 服务器/网关基类.
                                                             (line  204)
* error_temp:                            ftplib --- FTP 协议客户端.
                                                             (line  117)
* escape (shlex.shlex 的屬性):           shlex 对象.         (line   90)
* escape sequence:                       字符串与字节串字面值.
                                                             (line   59)
* escape() (於 glob 模組中):             glob --- Unix 风格路径名模式扩展.
                                                             (line   57)
* escape() (於 html 模組中):             html --- 超文本标记语言支持.
                                                             (line   12)
* escape() (於 re 模組中):               模块内容.           (line  263)
* escape() (於 xml.sax.saxutils 模組中): xml sax saxutils --- SAX 工具集.
                                                             (line   13)
* escapechar (csv.Dialect 的屬性):       变种与格式参数.     (line   29)
* escapedquotes (shlex.shlex 的屬性):    shlex 对象.         (line  100)
* ESHUTDOWN (於 errno 模組中):           errno --- 标准 errno 系统符号.
                                                             (line  454)
* ESOCKTNOSUPPORT (於 errno 模組中):     errno --- 标准 errno 系统符号.
                                                             (line  398)
* ESPIPE (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line  138)
* ESRCH (於 errno 模組中):               errno --- 标准 errno 系统符号.
                                                             (line   29)
* ESRMNT (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line  298)
* ESTALE (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line  486)
* ESTRPIPE (於 errno 模組中):            errno --- 标准 errno 系统符号.
                                                             (line  366)
* ETIME (於 errno 模組中):               errno --- 标准 errno 系统符号.
                                                             (line  270)
* ETIMEDOUT (於 errno 模組中):           errno --- 标准 errno 系统符号.
                                                             (line  462)
* Etiny() (decimal.Context 的方法):      上下文对象.         (line  182)
* ETOOMANYREFS (於 errno 模組中):        errno --- 标准 errno 系统符号.
                                                             (line  458)
* Etop() (decimal.Context 的方法):       上下文对象.         (line  187)
* ETXTBSY (於 errno 模組中):             errno --- 标准 errno 系统符号.
                                                             (line  126)
* EUCLEAN (於 errno 模組中):             errno --- 标准 errno 系统符号.
                                                             (line  490)
* EUNATCH (於 errno 模組中):             errno --- 标准 errno 系统符号.
                                                             (line  218)
* EUSERS (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line  370)
* eval() (內建函式):                     內建函式.           (line  401)
* evaluation; order:                     求值顺序.           (line    6)
* Event (asyncio 中的類別):              Event.              (line    6)
* Event (multiprocessing 中的類別):      同步原语.           (line   37)
* Event (threading 中的類別):            事件对象.           (line   13)
* event scheduling:                      sched --- 事件调度器.
                                                             (line    8)
* event() (msilib.Control 的方法):       GUI classes.        (line   16)
* Event() (multiprocessing.managers.SyncManager 的方法): 管理器.
                                                             (line  143)
* events (selectors.SelectorKey 的屬性): 类<2>.              (line   42)
* events (widgets):                      绑定和事件.         (line    6)
* EWOULDBLOCK (於 errno 模組中):         errno --- 标准 errno 系统符号.
                                                             (line  186)
* Example (doctest 中的類別):            Example 对象.       (line    6)
* example (doctest.DocTestFailure 的屬性): 调试.             (line  173)
* example (doctest.UnexpectedException 的屬性): 调试.        (line  192)
* examples (doctest.DocTest 的屬性):     DocTest 对象.       (line   15)
* excel (csv 中的類別):                  模块内容<3>.        (line  171)
* excel_tab (csv 中的類別):              模块内容<3>.        (line  176)
* except (2to3 fixer):                   修复器.             (line   79)
* ExceptHandler (ast 中的類別):          Control flow.       (line  178)
* excepthook() (in module sys):          cgitb --- 用于 CGI 脚本的回溯管理器.
                                                             (line   28)
* excepthook() (於 sys 模組中):          sys --- 系统相关的参数和函数.
                                                             (line  260)
* excepthook() (於 threading 模組中):    threading --- 基于线程的并行.
                                                             (line   38)
* exception:                             异常.               (line    6)
* exception <1>:                         raise 语句.         (line    6)
* Exception:                             基类.               (line   31)
* EXCEPTION (於 tkinter 模組中):         File Handlers.      (line   41)
* exception handler:                     异常.               (line    6)
* exception() (asyncio.Future 的方法):   Future 对象<2>.     (line  108)
* exception() (asyncio.Task 的方法):     Task 对象.          (line  124)
* exception() (concurrent.futures.Future 的方法): Future 对象.
                                                             (line   45)
* exception() (logging.Logger 的方法):   记录器对象.         (line  202)
* exception() (於 logging 模組中):       模块级函数.         (line  118)
* exception; chaining:                   raise 语句.         (line   25)
* exception; handler:                    标准类型层级结构.   (line  587)
* exceptions; in CGI scripts:            cgitb --- 用于 CGI 脚本的回溯管理器.
                                                             (line    8)
* exclusive; or:                         二元位运算.         (line   16)
* exc_info (doctest.UnexpectedException 的屬性): 调试.       (line  196)
* exc_info (in module sys):              标准类型层级结构.   (line  587)
* exc_info() (in module sys):            异常<17>.           (line   43)
* exc_info() (於 sys 模組中):            sys --- 系统相关的参数和函数.
                                                             (line  294)
* exc_msg (doctest.Example 的屬性):      Example 对象.       (line   27)
* exc_type (traceback.TracebackException 的屬性): TracebackException Objects.
                                                             (line   38)
* EXDEV (於 errno 模組中):               errno --- 标准 errno 系统符号.
                                                             (line   94)
* exec (2to3 fixer):                     修复器.             (line   83)
* exec() (內建函式):                     內建函式.           (line  437)
* execfile (2to3 fixer):                 修复器.             (line   87)
* execl() (於 os 模組中):                进程管理.           (line   45)
* execle() (於 os 模組中):               进程管理.           (line   45)
* execlp() (於 os 模組中):               进程管理.           (line   45)
* execlpe() (於 os 模組中):              进程管理.           (line   45)
* executable (in module sys):            Process-wide parameters.
                                                             (line  111)
* executable (於 sys 模組中):            sys --- 系统相关的参数和函数.
                                                             (line  322)
* Executable Zip Files:                  zipapp —— 管理可执行的 Python zip 打包文件.
                                                             (line   10)
* executable_filename() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  449)
* execute() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  479)
* Execute() (msilib.View 的方法):        View Objects.       (line    6)
* execute() (sqlite3.Connection 的方法): 连接对象（Connection）.
                                                             (line   47)
* execute() (sqlite3.Cursor 的方法):     Cursor 对象.        (line   10)
* execute() (於 distutils.util 模組中):  distutils util --- Miscellaneous other utility functions.
                                                             (line  129)
* executemany() (sqlite3.Connection 的方法): 连接对象（Connection）.
                                                             (line   53)
* executemany() (sqlite3.Cursor 的方法): Cursor 对象.        (line   20)
* executescript() (sqlite3.Connection 的方法): 连接对象（Connection）.
                                                             (line   59)
* executescript() (sqlite3.Cursor 的方法): Cursor 对象.      (line   73)
* execution model:                       执行模型.           (line    6)
* execution; frame:                      程序的结构.         (line   15)
* execution; frame <1>:                  类定义.             (line    6)
* execution; stack:                      标准类型层级结构.   (line  587)
* ExecutionLoader (importlib.abc 中的類別): importlib abc —— 关于导入的抽象基类.
                                                             (line  387)
* Executor (concurrent.futures 中的類別): Executor 对象.     (line    6)
* execv() (於 os 模組中):                进程管理.           (line   45)
* execve() (於 os 模組中):               进程管理.           (line   45)
* execvp() (於 os 模組中):               进程管理.           (line   45)
* execvpe() (於 os 模組中):              进程管理.           (line   45)
* exec_module (C 函式):                  Multi-phase initialization.
                                                             (line  102)
* exec_module() (importlib.abc.InspectLoader 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  375)
* exec_module() (importlib.abc.Loader 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  160)
* exec_module() (importlib.abc.SourceLoader 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  500)
* exec_module() (importlib.machinery.ExtensionFileLoader 的方法): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  283)
* exec_prefix:                           与Python相关的路径和文件.
                                                             (line    6)
* exec_prefix <1>:                       包含文件.           (line   32)
* exec_prefix <2>:                       包含文件.           (line   40)
* EXEC_PREFIX (於 distutils.sysconfig 模組中): distutils sysconfig --- System configuration information.
                                                             (line   23)
* exec_prefix (於 sys 模組中):           sys --- 系统相关的参数和函数.
                                                             (line  308)
* ExFileSelectBox (tkinter.tix 中的類別): File Selectors.    (line   34)
* EXFULL (於 errno 模組中):              errno --- 标准 errno 系统符号.
                                                             (line  238)
* exists() (pathlib.Path 的方法):        方法<2>.            (line   60)
* exists() (tkinter.ttk.Treeview 的方法): ttk Treeview.      (line   81)
* exists() (zipfile.Path 的方法):        Path 对象.          (line   46)
* exists() (於 os.path 模組中):          os path --- 常用路径操作.
                                                             (line   99)
* exit (內建變數):                       由 site 模块添加的常量.
                                                             (line   10)
* exit():                                行程（Process）控制.
                                                             (line   23)
* exit() (argparse.ArgumentParser 的方法): 退出方法.         (line    6)
* exit() (於 sys 模組中):                sys --- 系统相关的参数和函数.
                                                             (line  328)
* exit() (於 _thread 模組中):            _thread --- 底层多线程 API.
                                                             (line   52)
* exitcode (multiprocessing.Process 的屬性): Process 和异常. (line   94)
* exitfunc (2to3 fixer):                 修复器.             (line   92)
* exitonclick() (於 turtle 模組中):      Screen 专有方法 而非继承自 TurtleScreen.
                                                             (line   10)
* ExitStack (contextlib 中的類別):       工具.               (line  317)
* exp() (decimal.Context 的方法):        上下文对象.         (line  248)
* exp() (decimal.Decimal 的方法):        Decimal 对象.       (line  196)
* exp() (於 cmath 模組中):               幂函数与对数函数<2>.
                                                             (line    6)
* exp() (於 math 模組中):                幂函数与对数函数.   (line    6)
* expand() (re.Match 的方法):            匹配对象.           (line   16)
* ExpandEnvironmentStrings() (於 winreg 模組中): 函数<12>.   (line  212)
* expandNode() (xml.dom.pulldom.DOMEventStream 的方法): DOMEventStream 对象.
                                                             (line   19)
* expandtabs() (bytearray 的方法):       bytes 和 bytearray 操作.
                                                             (line  400)
* expandtabs() (bytes 的方法):           bytes 和 bytearray 操作.
                                                             (line  400)
* expandtabs() (str 的方法):             字符串的方法<2>.    (line   77)
* expanduser() (pathlib.Path 的方法):    方法<2>.            (line   76)
* expanduser() (於 os.path 模組中):      os path --- 常用路径操作.
                                                             (line  119)
* expandvars() (於 os.path 模組中):      os path --- 常用路径操作.
                                                             (line  138)
* expand_tabs (textwrap.TextWrapper 的屬性): textwrap --- 文本自动换行与填充.
                                                             (line  152)
* Expat:                                 xml parsers expat --- 使用 Expat 的快速 XML 解析.
                                                             (line   11)
* ExpatError:                            xml parsers expat --- 使用 Expat 的快速 XML 解析.
                                                             (line   22)
* expect() (telnetlib.Telnet 的方法):    Telnet 对象.        (line  112)
* expected (asyncio.IncompleteReadError 的屬性): 异常<9>.    (line   46)
* expectedFailure() (於 unittest 模組中): 跳过测试与预计的失败.
                                                             (line   94)
* expectedFailures (unittest.TestResult 的屬性): Loading and running tests.
                                                             (line  256)
* expires (http.cookiejar.Cookie 的屬性): Cookie 对象<2>.    (line   45)
* exploded (ipaddress.IPv4Address 的屬性): 地址对象.         (line   59)
* exploded (ipaddress.IPv4Network 的屬性): 网络对象.         (line   93)
* exploded (ipaddress.IPv6Address 的屬性): 地址对象.         (line  185)
* exploded (ipaddress.IPv6Network 的屬性): 网络对象.         (line  287)
* expm1() (於 math 模組中):              幂函数与对数函数.   (line   11)
* expovariate() (於 random 模組中):      实值分布.           (line   32)
* Expr (ast 中的類別):                   表达式<2>.          (line    6)
* expr() (於 parser 模組中):             创建 ST 对象.       (line   10)
* expression:                            表达式.             (line    6)
* expression; list:                      表达式列表.         (line    6)
* expression; list <1>:                  表达式语句.         (line    6)
* expression; list <2>:                  表达式语句.         (line    6)
* expression; statement:                 表达式语句.         (line    6)
* expression（運算式）:                  術語表.             (line  349)
* expunge() (imaplib.IMAP4 的方法):      IMAP4 对象.         (line   82)
* extend() (array.array 的方法):         array --- 高效率的數值型態陣列.
                                                             (line  131)
* extend() (collections.deque 的方法):   deque 对象.         (line   51)
* extend() (sequence method):            可变序列类型.       (line   14)
* extend() (xml.etree.ElementTree.Element 的方法): 元素对象. (line   80)
* ExtendedContext (decimal 中的類別):    上下文对象.         (line   51)
* ExtendedInterpolation (configparser 中的類別): 值的插值.   (line   35)
* EXTENDED_ARG (opcode):                 Python字节码说明.   (line  733)
* extendleft() (collections.deque 的方法): deque 对象.       (line   55)
* extend_path() (於 pkgutil 模組中):     pkgutil --- 包扩展工具.
                                                             (line   18)
* Extension (distutils.core 中的類別):   distutils core --- 分发包功能的核心.
                                                             (line  165)
* extension module（擴充模組）:          術語表.             (line  357)
* extension; module:                     标准类型层级结构.   (line    6)
* ExtensionFileLoader (importlib.machinery 中的類別): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  259)
* extensions_map (http.server.SimpleHTTPRequestHandler 的屬性): http server --- HTTP 服务器.
                                                             (line  303)
* EXTENSION_SUFFIXES (於 importlib.machinery 模組中): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line   43)
* External Data Representation:          数据流格式.         (line    6)
* External Data Representation <1>:      xdrlib --- 编码与解码 XDR 数据.
                                                             (line    8)
* ExternalClashError:                    异常<13>.           (line   23)
* ExternalEntityParserCreate() (xml.parsers.expat.xmlparser 的方法): XMLParser对象<2>.
                                                             (line   36)
* ExternalEntityRefHandler() (xml.parsers.expat.xmlparser 的方法): XMLParser对象<2>.
                                                             (line  278)
* external_attr (zipfile.ZipInfo 的屬性): ZipInfo 对象.      (line  117)
* extra (zipfile.ZipInfo 的屬性):        ZipInfo 对象.       (line   84)
* extract() (tarfile.TarFile 的方法):    TarFile 对象.       (line  139)
* extract() (traceback.StackSummary 的類別成員): StackSummary Objects.
                                                             (line   13)
* extract() (zipfile.ZipFile 的方法):    ZipFile 对象.       (line  141)
* extractall() (tarfile.TarFile 的方法): TarFile 对象.       (line  117)
* extractall() (zipfile.ZipFile 的方法): ZipFile 对象.       (line  164)
* ExtractError:                          tarfile --- 读写tar归档文件.
                                                             (line  184)
* extractfile() (tarfile.TarFile 的方法): TarFile 对象.      (line  163)
* extract_cookies() (http.cookiejar.CookieJar 的方法): CookieJar 和 FileCookieJar 对象.
                                                             (line   28)
* extract_stack() (於 traceback 模組中): traceback --- 打印或检索堆栈回溯.
                                                             (line   93)
* extract_tb() (於 traceback 模組中):    traceback --- 打印或检索堆栈回溯.
                                                             (line   80)
* extract_version (zipfile.ZipInfo 的屬性): ZipInfo 对象.    (line   97)
* extsep (於 os 模組中):                 其他系统信息.       (line   90)
* EX_CANTCREAT (於 os 模組中):           进程管理.           (line  171)
* EX_CONFIG (於 os 模組中):              进程管理.           (line  202)
* EX_DATAERR (於 os 模組中):             进程管理.           (line  123)
* EX_IOERR (於 os 模組中):               进程管理.           (line  177)
* EX_NOHOST (於 os 模組中):              进程管理.           (line  141)
* EX_NOINPUT (於 os 模組中):             进程管理.           (line  129)
* EX_NOPERM (於 os 模組中):              进程管理.           (line  196)
* EX_NOTFOUND (於 os 模組中):            进程管理.           (line  208)
* EX_NOUSER (於 os 模組中):              进程管理.           (line  135)
* EX_OK (於 os 模組中):                  进程管理.           (line  111)
* EX_OSERR (於 os 模組中):               进程管理.           (line  159)
* EX_OSFILE (於 os 模組中):              进程管理.           (line  165)
* EX_PROTOCOL (於 os 模組中):            进程管理.           (line  190)
* EX_SOFTWARE (於 os 模組中):            进程管理.           (line  153)
* EX_TEMPFAIL (於 os 模組中):            进程管理.           (line  183)
* EX_UNAVAILABLE (於 os 模組中):         进程管理.           (line  147)
* EX_USAGE (於 os 模組中):               进程管理.           (line  117)
* f"; formatted string literal:          字符串与字节串字面值.
                                                             (line   51)
* f’; formatted string literal:          字符串与字节串字面值.
                                                             (line   51)
* f-string:                              字符串字面值合并.   (line   19)
* f-string（f 字串）:                    術語表.             (line  362)
* fabs() (於 math 模組中):               数论与表示函数.     (line   32)
* factorial() (於 math 模組中):          数论与表示函数.     (line   36)
* factory() (importlib.util.LazyLoader 的類別成員): importlib util —— 导入器的工具程序代码.
                                                             (line  219)
* fail() (unittest.TestCase 的方法):     测试用例.           (line  657)
* failfast (unittest.TestResult 的屬性): Loading and running tests.
                                                             (line  287)
* failureException (unittest.TestCase 的屬性): 测试用例.     (line  662)
* failures (unittest.TestResult 的屬性): Loading and running tests.
                                                             (line  242)
* FAIL_FAST (於 doctest 模組中):         选项标记.           (line  125)
* FakePath (test.support 中的類別):      test support --- Utilities for the Python test suite.
                                                             (line 1128)
* False:                                 标准类型层级结构.   (line   74)
* false:                                 逻辑值检测.         (line    6)
* False <1>:                             逻辑值检测.         (line   19)
* False <2>:                             布尔值.             (line   12)
* False (Built-in object):               逻辑值检测.         (line   13)
* False (內建變數):                      內建常數.           (line    8)
* families() (於 tkinter.font 模組中):   tkinter font --- Tkinter 字体封装.
                                                             (line   84)
* family (socket.socket 的屬性):         套接字对象.         (line  497)
* FancyGetopt (distutils.fancy_getopt 中的類別): distutils fancy_getopt --- Wrapper around the standard getopt module.
                                                             (line   36)
* FancyURLopener (urllib.request 中的類別): 沿袭的接口.      (line  120)
* fancy_getopt() (於 distutils.fancy_getopt 模組中): distutils fancy_getopt --- Wrapper around the standard getopt module.
                                                             (line   20)
* fast (pickle.Pickler 的屬性):          模块接口.           (line  191)
* FastChildWatcher (asyncio 中的類別):   进程监视器.         (line  114)
* fatalError() (xml.sax.handler.ErrorHandler 的方法): ErrorHandler 对象.
                                                             (line   19)
* Fault (xmlrpc.client 中的類別):        Fault 对象.         (line    6)
* faultCode (xmlrpc.client.Fault 的屬性): Fault 对象.        (line   11)
* faulthandler (模組):                   faulthandler —— 转储 Python 的跟踪信息.
                                                             (line    6)
* faultString (xmlrpc.client.Fault 的屬性): Fault 对象.      (line   15)
* fchdir() (於 os 模組中):               文件和目录.         (line  243)
* fchmod() (於 os 模組中):               文件描述符操作.     (line   83)
* fchown() (於 os 模組中):               文件描述符操作.     (line   94)
* FCICreate() (於 msilib 模組中):        msilib --- Read and write Microsoft Installer files.
                                                             (line   26)
* fcntl (模組):                          fcntl —— 系统调用 fcntl 和 ioctl.
                                                             (line    6)
* fcntl() (於 fcntl 模組中):             fcntl —— 系统调用 fcntl 和 ioctl.
                                                             (line   30)
* fd (selectors.SelectorKey 的屬性):     类<2>.              (line   38)
* fd() (於 turtle 模組中):               海龟动作.           (line    6)
* fdatasync() (於 os 模組中):            文件描述符操作.     (line  105)
* fdopen() (於 os 模組中):               创建文件对象.       (line    9)
* fd_count() (於 test.support 模組中):   test support --- Utilities for the Python test suite.
                                                             (line  302)
* Feature (msilib 中的類別):             相关特性<3>.        (line    6)
* feature_external_ges (於 xml.sax.handler 模組中): xml sax handler --- SAX 处理句柄的基类.
                                                             (line   67)
* feature_external_pes (於 xml.sax.handler 模組中): xml sax handler --- SAX 处理句柄的基类.
                                                             (line   74)
* feature_namespaces (於 xml.sax.handler 模組中): xml sax handler --- SAX 处理句柄的基类.
                                                             (line   39)
* feature_namespace_prefixes (於 xml.sax.handler 模組中): xml sax handler --- SAX 处理句柄的基类.
                                                             (line   46)
* feature_string_interning (於 xml.sax.handler 模組中): xml sax handler --- SAX 处理句柄的基类.
                                                             (line   53)
* feature_validation (於 xml.sax.handler 模組中): xml sax handler --- SAX 处理句柄的基类.
                                                             (line   60)
* feed() (email.parser.BytesFeedParser 的方法): FeedParser API.
                                                             (line   48)
* feed() (html.parser.HTMLParser 的方法): HTMLParser 方法.   (line    8)
* feed() (xml.etree.ElementTree.XMLParser 的方法): XMLParser对象.
                                                             (line   24)
* feed() (xml.etree.ElementTree.XMLPullParser 的方法): XMLPullParser对象.
                                                             (line   16)
* feed() (xml.sax.xmlreader.IncrementalParser 的方法): IncrementalParser 对象.
                                                             (line    8)
* FeedParser (email.parser 中的類別):    FeedParser API.     (line   61)
* fetch() (imaplib.IMAP4 的方法):        IMAP4 对象.         (line   88)
* Fetch() (msilib.View 的方法):          View Objects.       (line   18)
* fetchall() (sqlite3.Cursor 的方法):    Cursor 对象.        (line  130)
* fetchmany() (sqlite3.Cursor 的方法):   Cursor 对象.        (line  115)
* fetchone() (sqlite3.Cursor 的方法):    Cursor 对象.        (line  110)
* fflags (select.kevent 的屬性):         Kevent 对象.        (line   86)
* Field (dataclasses 中的類別):          模块级装饰器、类和函数.
                                                             (line  197)
* field() (於 dataclasses 模組中):       模块级装饰器、类和函数.
                                                             (line  126)
* fieldnames (csv.csvreader 的屬性):     Reader 对象.        (line   29)
* fields (uuid.UUID 的屬性):             uuid --- RFC 4122 定义的UUID对象.
                                                             (line   83)
* fields() (於 dataclasses 模組中):      模块级装饰器、类和函数.
                                                             (line  213)
* field_size_limit() (於 csv 模組中):    模块内容<3>.        (line   82)
* file (pyclbr.Class 的屬性):            Class 对象.         (line    9)
* file (pyclbr.Function 的屬性):         函式物件.           (line    8)
* file object; io module:                總覽.               (line    6)
* file object; open() built-in function: 內建函式.           (line  870)
* file object（檔案物件）:               術語表.             (line  367)
* file-like object（類檔案物件）:        術語表.             (line  381)
* file; byte-code:                       py_compile --- 编译 Python 源文件.
                                                             (line    8)
* file; byte-code <1>:                   imp —— 由代码内部访问 import 。.
                                                             (line   18)
* file; copying:                         shutil --- 高阶文件操作.
                                                             (line    8)
* file; large files:                     大文件支持.         (line    6)
* file; mime.types:                      mimetypes --- 映射文件名到 MIME 类型.
                                                             (line  104)
* file; modes:                           內建函式.           (line  889)
* filecmp (模組):                        filecmp --- 文件及目录的比较.
                                                             (line    6)
* fileConfig() (於 logging.config 模組中): 配置函数.         (line   52)
* FileCookieJar (http.cookiejar 中的類別): http cookiejar —— HTTP 客户端的 Cookie 处理.
                                                             (line   47)
* FileDialog (tkinter.filedialog 中的類別): 原生 加载/保存 对话框.
                                                             (line   69)
* FileEntry (tkinter.tix 中的類別):      File Selectors.     (line   50)
* FileExistsError:                       OS 异常.            (line   55)
* FileFinder (importlib.machinery 中的類別): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  136)
* FileHandler (logging 中的類別):        FileHandler.        (line    9)
* FileHandler (urllib.request 中的類別): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  342)
* FileInput (fileinput 中的類別):        fileinput --- 迭代来自多个输入流的行.
                                                             (line  109)
* fileinput (模組):                      fileinput --- 迭代来自多个输入流的行.
                                                             (line    6)
* FileIO (io 中的類別):                  原始文件 I/O.       (line    6)
* filelineno() (於 fileinput 模組中):    fileinput --- 迭代来自多个输入流的行.
                                                             (line   82)
* FileLoader (importlib.abc 中的類別):   importlib abc —— 关于导入的抽象基类.
                                                             (line  403)
* filemode() (於 stat 模組中):           stat --- 解析 stat 结果.
                                                             (line  112)
* filename (doctest.DocTest 的屬性):     DocTest 对象.       (line   31)
* filename (http.cookiejar.FileCookieJar 的屬性): CookieJar 和 FileCookieJar 对象.
                                                             (line  138)
* filename (OSError 的屬性):             具体异常.           (line  133)
* filename (SyntaxError 的屬性):         具体异常.           (line  217)
* filename (traceback.TracebackException 的屬性): TracebackException Objects.
                                                             (line   42)
* filename (tracemalloc.Frame 的屬性):   Frame.              (line   13)
* filename (zipfile.ZipFile 的屬性):     ZipFile 对象.       (line  264)
* filename (zipfile.ZipInfo 的屬性):     ZipInfo 对象.       (line   44)
* filename() (於 fileinput 模組中):      fileinput --- 迭代来自多个输入流的行.
                                                             (line   68)
* filename2 (OSError 的屬性):            具体异常.           (line  133)
* filenames; pathname expansion:         glob --- Unix 风格路径名模式扩展.
                                                             (line    8)
* filenames; wildcard expansion:         fnmatch --- Unix 文件名模式匹配.
                                                             (line    8)
* filename_only (於 tabnanny 模組中):    tabnanny --- 模糊缩进检测.
                                                             (line   28)
* filename_pattern (tracemalloc.Filter 的屬性): 过滤器<2>.   (line   53)
* fileno() (http.client.HTTPResponse 的方法): HTTPResponse 对象.
                                                             (line   33)
* fileno() (io.IOBase 的方法):           I/O 基类.           (line   51)
* fileno() (multiprocessing.connection.Connection 的方法): 连接（Connection）对象.
                                                             (line   28)
* fileno() (ossaudiodev.oss_audio_device 的方法): 音频设备对象.
                                                             (line   24)
* fileno() (ossaudiodev.oss_mixer_device 的方法): Mixer Device Objects.
                                                             (line   14)
* fileno() (select.devpoll 的方法):      /dev/poll 轮询对象. (line   24)
* fileno() (select.epoll 的方法):        边缘触发和水平触发的轮询 epoll 对象.
                                                             (line   71)
* fileno() (select.kqueue 的方法):       Kqueue 对象.        (line   14)
* fileno() (selectors.DevpollSelector 的方法): 类<2>.        (line  166)
* fileno() (selectors.EpollSelector 的方法): 类<2>.          (line  157)
* fileno() (selectors.KqueueSelector 的方法): 类<2>.         (line  177)
* fileno() (socket.socket 的方法):       套接字对象.         (line   95)
* fileno() (socketserver.BaseServer 的方法): Server 对象<2>. (line   12)
* fileno() (telnetlib.Telnet 的方法):    Telnet 对象.        (line   89)
* fileno() (於 fileinput 模組中):        fileinput --- 迭代来自多个输入流的行.
                                                             (line   72)
* FileNotFoundError:                     OS 异常.            (line   60)
* fileobj (selectors.SelectorKey 的屬性): 类<2>.             (line   34)
* files() (於 importlib.resources 模組中): importlib resources -- 资源.
                                                             (line   45)
* FileSelectBox (tkinter.tix 中的類別):  File Selectors.     (line   42)
* files_double_event() (tkinter.filedialog.FileDialog 的方法): 原生 加载/保存 对话框.
                                                             (line   85)
* files_select_event() (tkinter.filedialog.FileDialog 的方法): 原生 加载/保存 对话框.
                                                             (line   89)
* FileType (argparse 中的類別):          FileType 对象.      (line    6)
* FileWrapper (wsgiref.util 中的類別):   wsgiref util -- WSGI 环境工具.
                                                             (line   99)
* FILE_ATTRIBUTE_ARCHIVE (於 stat 模組中): stat --- 解析 stat 结果.
                                                             (line  368)
* FILE_ATTRIBUTE_COMPRESSED (於 stat 模組中): stat --- 解析 stat 结果.
                                                             (line  368)
* FILE_ATTRIBUTE_DEVICE (於 stat 模組中): stat --- 解析 stat 结果.
                                                             (line  368)
* FILE_ATTRIBUTE_DIRECTORY (於 stat 模組中): stat --- 解析 stat 结果.
                                                             (line  368)
* FILE_ATTRIBUTE_ENCRYPTED (於 stat 模組中): stat --- 解析 stat 结果.
                                                             (line  368)
* FILE_ATTRIBUTE_HIDDEN (於 stat 模組中): stat --- 解析 stat 结果.
                                                             (line  368)
* FILE_ATTRIBUTE_INTEGRITY_STREAM (於 stat 模組中): stat --- 解析 stat 结果.
                                                             (line  368)
* FILE_ATTRIBUTE_NORMAL (於 stat 模組中): stat --- 解析 stat 结果.
                                                             (line  368)
* FILE_ATTRIBUTE_NOT_CONTENT_INDEXED (於 stat 模組中): stat --- 解析 stat 结果.
                                                             (line  368)
* FILE_ATTRIBUTE_NO_SCRUB_DATA (於 stat 模組中): stat --- 解析 stat 结果.
                                                             (line  368)
* FILE_ATTRIBUTE_OFFLINE (於 stat 模組中): stat --- 解析 stat 结果.
                                                             (line  368)
* FILE_ATTRIBUTE_READONLY (於 stat 模組中): stat --- 解析 stat 结果.
                                                             (line  368)
* FILE_ATTRIBUTE_REPARSE_POINT (於 stat 模組中): stat --- 解析 stat 结果.
                                                             (line  368)
* FILE_ATTRIBUTE_SPARSE_FILE (於 stat 模組中): stat --- 解析 stat 结果.
                                                             (line  368)
* FILE_ATTRIBUTE_SYSTEM (於 stat 模組中): stat --- 解析 stat 结果.
                                                             (line  368)
* FILE_ATTRIBUTE_TEMPORARY (於 stat 模組中): stat --- 解析 stat 结果.
                                                             (line  368)
* FILE_ATTRIBUTE_VIRTUAL (於 stat 模組中): stat --- 解析 stat 结果.
                                                             (line  368)
* file_created() (內建函式):             The Postinstallation script.
                                                             (line   23)
* file_dispatcher (asyncore 中的類別):   asyncore --- 异步套接字处理器.
                                                             (line  207)
* file_open() (urllib.request.FileHandler 的方法): FileHandler 对象.
                                                             (line    6)
* file_size (zipfile.ZipInfo 的屬性):    ZipInfo 对象.       (line  133)
* file_wrapper (asyncore 中的類別):      asyncore --- 异步套接字处理器.
                                                             (line  216)
* fill() (textwrap.TextWrapper 的方法):  textwrap --- 文本自动换行与填充.
                                                             (line  259)
* fill() (於 textwrap 模組中):           textwrap --- 文本自动换行与填充.
                                                             (line   30)
* fillcolor() (於 turtle 模組中):        颜色控制.           (line   53)
* filling() (於 turtle 模組中):          填充.               (line    6)
* filter (2to3 fixer):                   修复器.             (line   96)
* Filter (logging 中的類別):             过滤器对象.         (line   12)
* filter (select.kevent 的屬性):         Kevent 对象.        (line   14)
* Filter (tracemalloc 中的類別):         过滤器<2>.          (line    6)
* filter() (logging.Filter 的方法):      过滤器对象.         (line   18)
* filter() (logging.Handler 的方法):     处理器对象.         (line   54)
* filter() (logging.Logger 的方法):      记录器对象.         (line  216)
* filter() (內建函式):                   內建函式.           (line  475)
* filter() (於 curses 模組中):           函数<4>.            (line  101)
* filter() (於 fnmatch 模組中):          fnmatch --- Unix 文件名模式匹配.
                                                             (line   61)
* filterfalse() (於 itertools 模組中):   Itertool函数.       (line  255)
* filterwarnings() (於 warnings 模組中): 可用的函数.         (line   62)
* filter_command() (tkinter.filedialog.FileDialog 的方法): 原生 加载/保存 对话框.
                                                             (line   93)
* FILTER_DIR (於 unittest.mock 模組中):  FILTER_DIR.         (line    6)
* filter_traces() (tracemalloc.Snapshot 的方法): 快照.       (line   35)
* Final (於 typing 模組中):              特殊形式.           (line  177)
* final() (於 typing 模組中):            函数与装饰器.       (line   37)
* finalization, of objects:              终结和内存释放.     (line    6)
* finalize (weakref 中的類別):           weakref --- 弱引用. (line  189)
* finalizer:                             基本定制.           (line   46)
* finalize_options() (distutils.cmd.Command 的方法): Creating a new Distutils command.
                                                             (line   30)
* find() (bytearray 的方法):             bytes 和 bytearray 操作.
                                                             (line  110)
* find() (bytes 的方法):                 bytes 和 bytearray 操作.
                                                             (line  110)
* find() (doctest.DocTestFinder 的方法): DocTestFinder 对象. (line   28)
* find() (mmap.mmap 的方法):             mmap --- 内存映射文件支持.
                                                             (line  154)
* find() (str 的方法):                   字符串的方法<2>.    (line   93)
* find() (xml.etree.ElementTree.Element 的方法): 元素对象.   (line   87)
* find() (xml.etree.ElementTree.ElementTree 的方法): ElementTree 对象.
                                                             (line   19)
* find() (於 gettext 模組中):            基于类的 API.       (line   12)
* findall() (re.Pattern 的方法):         正则表达式对象 （正则对象）.
                                                             (line   64)
* findall() (xml.etree.ElementTree.Element 的方法): 元素对象.
                                                             (line   94)
* findall() (xml.etree.ElementTree.ElementTree 的方法): ElementTree 对象.
                                                             (line   23)
* findall() (於 re 模組中):              模块内容.           (line  173)
* findCaller() (logging.Logger 的方法):  记录器对象.         (line  231)
* finder:                                查找器和加载器.     (line    6)
* Finder (importlib.abc 中的類別):       importlib abc —— 关于导入的抽象基类.
                                                             (line   28)
* finder; find_spec:                     元路径.             (line    6)
* finder（尋檢器）:                      術語表.             (line  385)
* findfactor() (於 audioop 模組中):      audioop --- 处理原始音频数据.
                                                             (line   68)
* findfile() (於 test.support 模組中):   test support --- Utilities for the Python test suite.
                                                             (line  288)
* findfit() (於 audioop 模組中):         audioop --- 处理原始音频数据.
                                                             (line   76)
* finditer() (re.Pattern 的方法):        正则表达式对象 （正则对象）.
                                                             (line   69)
* finditer() (於 re 模組中):             模块内容.           (line  194)
* findlabels() (於 dis 模組中):          分析函数.           (line  116)
* findlinestarts() (於 dis 模組中):      分析函数.           (line  107)
* findmatch() (於 mailcap 模組中):       mailcap --- Mailcap 文件处理.
                                                             (line   21)
* findmax() (於 audioop 模組中):         audioop --- 处理原始音频数据.
                                                             (line   85)
* findtext() (xml.etree.ElementTree.Element 的方法): 元素对象.
                                                             (line  101)
* findtext() (xml.etree.ElementTree.ElementTree 的方法): ElementTree 对象.
                                                             (line   27)
* find_class() (pickle protocol):        限制全局变量.       (line    6)
* find_class() (pickle.Unpickler 的方法): 模块接口.          (line  249)
* find_library() (於 ctypes.util 模組中): 工具函数.          (line   76)
* find_library_file() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  203)
* find_loader() (importlib.abc.PathEntryFinder 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  106)
* find_loader() (importlib.machinery.FileFinder 的方法): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  166)
* find_loader() (於 importlib 模組中):   函数<11>.           (line   35)
* find_loader() (於 pkgutil 模組中):     pkgutil --- 包扩展工具.
                                                             (line   76)
* find_longest_match() (difflib.SequenceMatcher 的方法): SequenceMatcher 对象.
                                                             (line   55)
* find_module() (imp.NullImporter 的方法): imp —— 由代码内部访问 import 。.
                                                             (line  345)
* find_module() (importlib.abc.Finder 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line   35)
* find_module() (importlib.abc.MetaPathFinder 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line   62)
* find_module() (importlib.abc.PathEntryFinder 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  125)
* find_module() (importlib.machinery.PathFinder 的類別成員): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  117)
* find_module() (zipimport.zipimporter 的方法): zipimporter 对象.
                                                             (line   18)
* find_module() (於 imp 模組中):         imp —— 由代码内部访问 import 。.
                                                             (line   40)
* find_msvcrt() (於 ctypes.util 模組中): 工具函数.           (line   84)
* find_spec() (importlib.abc.MetaPathFinder 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line   51)
* find_spec() (importlib.abc.PathEntryFinder 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line   97)
* find_spec() (importlib.machinery.FileFinder 的方法): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  160)
* find_spec() (importlib.machinery.PathFinder 的類別成員): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line   98)
* find_spec() (於 importlib.util 模組中): importlib util —— 导入器的工具程序代码.
                                                             (line   90)
* find_unused_port() (於 test.support.socket_helper 模組中): test support socket_helper --- Utilities for socket tests.
                                                             (line   15)
* find_user_password() (urllib.request.HTTPPasswordMgr 的方法): HTTPPasswordMgr 对象.
                                                             (line   15)
* find_user_password() (urllib.request.HTTPPasswordMgrWithPriorAuth 的方法): HTTPPasswordMgrWithPriorAuth 对象.
                                                             (line   17)
* finish() (socketserver.BaseRequestHandler 的方法): 请求处理句柄对象.
                                                             (line   28)
* finish() (tkinter.dnd.DndHandler 的方法): tkinter dnd --- 拖放操作支持.
                                                             (line   46)
* finish_request() (socketserver.BaseServer 的方法): Server 对象<2>.
                                                             (line  109)
* firstChild (xml.dom.Node 的屬性):      节点对象.           (line   45)
* firstkey() (dbm.gnu.gdbm 的方法):      dbm gnu --- GNU 对 dbm 的重解析.
                                                             (line   71)
* firstweekday() (於 calendar 模組中):   calendar --- 日历相关函数.
                                                             (line  257)
* fix_missing_locations() (於 ast 模組中): ast 中的辅助函数. (line  111)
* fix_sentence_endings (textwrap.TextWrapper 的屬性): textwrap --- 文本自动换行与填充.
                                                             (line  198)
* Flag (enum 中的類別):                  模块内容<2>.        (line   26)
* flags (re.Pattern 的屬性):             正则表达式对象 （正则对象）.
                                                             (line   83)
* flags (select.kevent 的屬性):          Kevent 对象.        (line   48)
* flags (於 sys 模組中):                 sys --- 系统相关的参数和函数.
                                                             (line  350)
* flag_bits (zipfile.ZipInfo 的屬性):    ZipInfo 对象.       (line  105)
* flash() (於 curses 模組中):            函数<4>.            (line  110)
* flatten() (email.generator.BytesGenerator 的方法): email generator 生成 MIME 文档.
                                                             (line   66)
* flatten() (email.generator.Generator 的方法): email generator 生成 MIME 文档.
                                                             (line  146)
* flattening; objects:                   pickle --- Python 对象序列化.
                                                             (line    8)
* float (內建類別):                      內建函式.           (line  490)
* floating point literal:                数值字面值.         (line    6)
* floating point; literals:              数字类型 --- int float complex.
                                                             (line   14)
* floating point; number:                标准类型层级结构.   (line   84)
* FloatingPointError:                    具体异常.           (line   24)
* FloatOperation (decimal 中的類別):     信号.               (line   91)
* float_info (於 sys 模組中):            sys --- 系统相关的参数和函数.
                                                             (line  416)
* float_repr_style (於 sys 模組中):      sys --- 系统相关的参数和函数.
                                                             (line  488)
* flock() (於 fcntl 模組中):             fcntl —— 系统调用 fcntl 和 ioctl.
                                                             (line   93)
* floor division（向下取整除法）:        術語表.             (line  397)
* floor() (in module math):              数字类型 --- int float complex.
                                                             (line   92)
* floor() (於 math 模組中):              数论与表示函数.     (line   44)
* FloorDiv (ast 中的類別):               表达式<2>.          (line   54)
* floordiv() (於 operator 模組中):       operator --- 标准运算符替代函数.
                                                             (line   77)
* flush() (bz2.BZ2Compressor 的方法):    增量压缩和解压.     (line   22)
* flush() (formatter.writer 的方法):     The Writer Interface.
                                                             (line   13)
* flush() (io.BufferedWriter 的方法):    缓冲流.             (line  107)
* flush() (io.IOBase 的方法):            I/O 基类.           (line   56)
* flush() (logging.Handler 的方法):      处理器对象.         (line   60)
* flush() (logging.handlers.BufferingHandler 的方法): MemoryHandler.
                                                             (line   25)
* flush() (logging.handlers.MemoryHandler 的方法): MemoryHandler.
                                                             (line   52)
* flush() (logging.StreamHandler 的方法): StreamHandler.     (line   22)
* flush() (lzma.LZMACompressor 的方法):  在内存中压缩和解压缩数据.
                                                             (line   72)
* flush() (mailbox.Mailbox 的方法):      Mailbox 对象.       (line  196)
* flush() (mailbox.Maildir 的方法):      Maildir.            (line   85)
* flush() (mailbox.MH 的方法):           MH.                 (line   88)
* flush() (mmap.mmap 的方法):            mmap --- 内存映射文件支持.
                                                             (line  162)
* flush() (zlib.Compress 的方法):        zlib --- 与 gzip 兼容的压缩.
                                                             (line  155)
* flush() (zlib.Decompress 的方法):      zlib --- 与 gzip 兼容的压缩.
                                                             (line  213)
* flushinp() (於 curses 模組中):         函数<4>.            (line  116)
* FlushKey() (於 winreg 模組中):         函数<12>.           (line  223)
* flush_headers() (http.server.BaseHTTPRequestHandler 的方法): http server --- HTTP 服务器.
                                                             (line  233)
* flush_softspace() (formatter.formatter 的方法): The Formatter Interface.
                                                             (line   83)
* fma() (decimal.Context 的方法):        上下文对象.         (line  252)
* fma() (decimal.Decimal 的方法):        Decimal 对象.       (line  229)
* fmean() (於 statistics 模組中):        函式細節.           (line   43)
* fmod() (於 math 模組中):               数论与表示函数.     (line   49)
* FMT_BINARY (於 plistlib 模組中):       plistlib --- 生成与解析 Apple plist 文件.
                                                             (line  127)
* FMT_XML (於 plistlib 模組中):          plistlib --- 生成与解析 Apple plist 文件.
                                                             (line  121)
* fnmatch (模組):                        fnmatch --- Unix 文件名模式匹配.
                                                             (line    6)
* fnmatch() (於 fnmatch 模組中):         fnmatch --- Unix 文件名模式匹配.
                                                             (line   38)
* fnmatchcase() (於 fnmatch 模組中):     fnmatch --- Unix 文件名模式匹配.
                                                             (line   55)
* focus() (tkinter.ttk.Treeview 的方法): ttk Treeview.       (line   85)
* fold (datetime.datetime 的屬性):       datetime 对象.      (line  276)
* fold (datetime.time 的屬性):           time 对象.          (line   67)
* fold() (email.headerregistry.BaseHeader 的方法): email headerregistry 自定义标头对象.
                                                             (line   59)
* fold() (email.policy.Compat32 的方法): email policy Policy 对象.
                                                             (line  472)
* fold() (email.policy.EmailPolicy 的方法): email policy Policy 对象.
                                                             (line  363)
* fold() (email.policy.Policy 的方法):   email policy Policy 对象.
                                                             (line  255)
* fold_binary() (email.policy.Compat32 的方法): email policy Policy 对象.
                                                             (line  479)
* fold_binary() (email.policy.EmailPolicy 的方法): email policy Policy 对象.
                                                             (line  378)
* fold_binary() (email.policy.Policy 的方法): email policy Policy 对象.
                                                             (line  266)
* Font (tkinter.font 中的類別):          tkinter font --- Tkinter 字体封装.
                                                             (line   20)
* For (ast 中的類別):                    Control flow.       (line   45)
* for; in comprehensions:                列表、集合与字典的显示.
                                                             (line   13)
* forget() (tkinter.ttk.Notebook 的方法): ttk Notebook.      (line   17)
* forget() (於 test.support 模組中):     test support --- Utilities for the Python test suite.
                                                             (line  222)
* fork() (於 os 模組中):                 进程管理.           (line  214)
* fork() (於 pty 模組中):                pty --- 伪终端工具. (line   18)
* ForkingMixIn (socketserver 中的類別):  服务器创建的说明.   (line   26)
* ForkingTCPServer (socketserver 中的類別): 服务器创建的说明.
                                                             (line   55)
* ForkingUDPServer (socketserver 中的類別): 服务器创建的说明.
                                                             (line   55)
* forkpty() (於 os 模組中):              进程管理.           (line  232)
* Form (tkinter.tix 中的類別):           Form Geometry Manager.
                                                             (line    9)
* format (memoryview 的屬性):            内存视图.           (line  388)
* format (multiprocessing.shared_memory.ShareableList 的屬性): multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line  234)
* format (struct.Struct 的屬性):         类.                 (line   48)
* format() (built-in function); __str__() (object method): 基本定制.
                                                             (line  105)
* format() (logging.Formatter 的方法):   格式器对象.         (line   42)
* format() (logging.Handler 的方法):     处理器对象.         (line   86)
* format() (pprint.PrettyPrinter 的方法): PrettyPrinter 对象.
                                                             (line   34)
* format() (str 的方法):                 字符串的方法<2>.    (line  106)
* format() (string.Formatter 的方法):    自定义字符串格式化. (line   15)
* format() (traceback.StackSummary 的方法): StackSummary Objects.
                                                             (line   36)
* format() (traceback.TracebackException 的方法): TracebackException Objects.
                                                             (line   73)
* format() (tracemalloc.Traceback 的方法): 回溯.             (line   37)
* format() (內建函式):                   內建函式.           (line  540)
* format() (於 locale 模組中):           locale --- 国际化服务.
                                                             (line  335)
* formataddr() (於 email.utils 模組中):  email utils 其他工具.
                                                             (line   54)
* formatargspec() (於 inspect 模組中):   类与函数<2>.        (line   91)
* formatargvalues() (於 inspect 模組中): 类与函数<2>.        (line  120)
* formatdate() (於 email.utils 模組中):  email utils 其他工具.
                                                             (line  117)
* FormatError:                           异常<13>.           (line   29)
* FormatError() (於 ctypes 模組中):      工具函数.           (line   92)
* formatException() (logging.Formatter 的方法): 格式器对象.  (line   87)
* formatmonth() (calendar.HTMLCalendar 的方法): calendar --- 日历相关函数.
                                                             (line  140)
* formatmonth() (calendar.TextCalendar 的方法): calendar --- 日历相关函数.
                                                             (line  112)
* formatStack() (logging.Formatter 的方法): 格式器对象.      (line   93)
* formatted string literal:              字符串字面值合并.   (line   19)
* FormattedValue (ast 中的類別):         字面值<3>.          (line   18)
* Formatter (logging 中的類別):          格式器对象.         (line   21)
* Formatter (string 中的類別):           自定义字符串格式化. (line   11)
* formatter (模組):                      formatter --- 通用格式化输出.
                                                             (line    6)
* formatTime() (logging.Formatter 的方法): 格式器对象.       (line   58)
* formatting, string (%):                printf 风格的字符串格式化.
                                                             (line    6)
* formatting; bytearray (%):             printf 风格的字节串格式化.
                                                             (line    6)
* formatting; bytes (%):                 printf 风格的字节串格式化.
                                                             (line    6)
* formatwarning() (於 warnings 模組中):  可用的函数.         (line   55)
* formatyear() (calendar.HTMLCalendar 的方法): calendar --- 日历相关函数.
                                                             (line  145)
* formatyear() (calendar.TextCalendar 的方法): calendar --- 日历相关函数.
                                                             (line  123)
* formatyearpage() (calendar.HTMLCalendar 的方法): calendar --- 日历相关函数.
                                                             (line  150)
* format_datetime() (於 email.utils 模組中): email utils 其他工具.
                                                             (line  137)
* format_exc() (於 traceback 模組中):    traceback --- 打印或检索堆栈回溯.
                                                             (line  134)
* format_exception() (於 traceback 模組中): traceback --- 打印或检索堆栈回溯.
                                                             (line  121)
* format_exception_only() (traceback.TracebackException 的方法): TracebackException Objects.
                                                             (line   88)
* format_exception_only() (於 traceback 模組中): traceback --- 打印或检索堆栈回溯.
                                                             (line  110)
* format_field() (string.Formatter 的方法): 自定义字符串格式化.
                                                             (line   81)
* format_help() (argparse.ArgumentParser 的方法): 打印帮助.  (line   28)
* format_list() (於 traceback 模組中):   traceback --- 打印或检索堆栈回溯.
                                                             (line  100)
* format_map() (str 的方法):             字符串的方法<2>.    (line  130)
* format_stack() (於 traceback 模組中):  traceback --- 打印或检索堆栈回溯.
                                                             (line  143)
* format_stack_entry() (bdb.Bdb 的方法): bdb --- Debugger framework.
                                                             (line  343)
* format_string() (於 locale 模組中):    locale --- 国际化服务.
                                                             (line  322)
* format_tb() (於 traceback 模組中):     traceback --- 打印或检索堆栈回溯.
                                                             (line  139)
* format_usage() (argparse.ArgumentParser 的方法): 打印帮助. (line   23)
* FORMAT_VALUE (opcode):                 Python字节码说明.   (line  739)
* Fortran contiguous:                    形状，步幅，子偏移量.
                                                             (line   24)
* Fortran contiguous <1>:                術語表.             (line  242)
* forward() (於 turtle 模組中):          海龟动作.           (line    6)
* ForwardRef (typing 中的類別):          内省辅助器.         (line   53)
* FOR_ITER (opcode):                     Python字节码说明.   (line  586)
* found_terminator() (asynchat.async_chat 的方法): asynchat --- 异步套接字指令/响应处理程序.
                                                             (line   76)
* fpathconf() (於 os 模組中):            文件描述符操作.     (line  113)
* fqdn (smtpd.SMTPChannel 的屬性):       SMTPChannel 对象.   (line   76)
* Fraction (fractions 中的類別):         fractions --- 分数. (line   14)
* fractions (模組):                      fractions --- 分数. (line    6)
* frame (tkinter.scrolledtext.ScrolledText 的屬性): tkinter scrolledtext --- 滚动文字控件.
                                                             (line   22)
* Frame (tracemalloc 中的類別):          Frame.              (line    6)
* FrameSummary (traceback 中的類別):     FrameSummary Objects.
                                                             (line   11)
* FrameType (於 types 模組中):           标准解释器类型.     (line  187)
* free():                                總覽<2>.            (line   23)
* free; variable:                        名称的绑定.         (line   21)
* freefunc (C 型態):                     Slot Type typedefs. (line   26)
* freeze utility:                        匯入模組<2>.        (line  247)
* freeze() (於 gc 模組中):               gc --- 垃圾回收器接口.
                                                             (line  167)
* freeze_support() (於 multiprocessing 模組中): 杂项<3>.     (line   41)
* frexp() (於 math 模組中):              数论与表示函数.     (line   61)
* from; import statement:                名称的绑定.         (line    8)
* from; import statement <1>:            import 语句.        (line   43)
* from; yield from expression:           yield 表达式.       (line   53)
* frombuf() (tarfile.TarInfo 的類別成員): TarInfo 对象.      (line   17)
* frombytes() (array.array 的方法):      array --- 高效率的數值型態陣列.
                                                             (line  138)
* fromfd() (select.epoll 的方法):        边缘触发和水平触发的轮询 epoll 对象.
                                                             (line   75)
* fromfd() (select.kqueue 的方法):       Kqueue 对象.        (line   18)
* fromfd() (於 socket 模組中):           创建套接字.         (line  132)
* fromfile() (array.array 的方法):       array --- 高效率的數值型態陣列.
                                                             (line  146)
* fromhex() (bytearray 的類別成員):      bytearray 对象.     (line   30)
* fromhex() (bytes 的類別成員):          bytes 对象.         (line   50)
* fromhex() (float 的類別成員):          浮点类型的附加方法. (line   33)
* fromisocalendar() (datetime.date 的類別成員): date 对象.   (line   71)
* fromisocalendar() (datetime.datetime 的類別成員): datetime 对象.
                                                             (line  202)
* fromisoformat() (datetime.date 的類別成員): date 对象.     (line   57)
* fromisoformat() (datetime.datetime 的類別成員): datetime 对象.
                                                             (line  168)
* fromisoformat() (datetime.time 的類別成員): time 对象.     (line  100)
* fromkeys() (collections.Counter 的方法): Counter 物件.     (line   95)
* fromkeys() (dict 的類別成員):          映射类型 --- dict.  (line  133)
* fromlist() (array.array 的方法):       array --- 高效率的數值型態陣列.
                                                             (line  152)
* fromordinal() (datetime.date 的類別成員): date 对象.       (line   48)
* fromordinal() (datetime.datetime 的類別成員): datetime 对象.
                                                             (line  144)
* fromshare() (於 socket 模組中):        创建套接字.         (line  146)
* fromstring() (於 xml.etree.ElementTree 模組中): 函数<7>.   (line   87)
* fromstringlist() (於 xml.etree.ElementTree 模組中): 函数<7>.
                                                             (line   94)
* fromtarfile() (tarfile.TarInfo 的類別成員): TarInfo 对象.  (line   23)
* fromtimestamp() (datetime.date 的類別成員): date 对象.     (line   32)
* fromtimestamp() (datetime.datetime 的類別成員): datetime 对象.
                                                             (line   86)
* fromunicode() (array.array 的方法):    array --- 高效率的數值型態陣列.
                                                             (line  157)
* fromutc() (datetime.timezone 的方法):  timezone 对象.      (line   50)
* fromutc() (datetime.tzinfo 的方法):    tzinfo 对象.        (line  139)
* from_address() (ctypes._CData 的方法): 数据类型<2>.        (line   37)
* from_buffer() (ctypes._CData 的方法):  数据类型<2>.        (line   17)
* from_buffer_copy() (ctypes._CData 的方法): 数据类型<2>.    (line   27)
* from_bytes() (int 的類別成員):         整数类型的附加方法. (line   61)
* from_callable() (inspect.Signature 的類別成員): Introspecting callables with the Signature object.
                                                             (line  126)
* from_decimal() (fractions.Fraction 的方法): fractions --- 分数.
                                                             (line  108)
* from_exception() (traceback.TracebackException 的類別成員): TracebackException Objects.
                                                             (line   63)
* from_file() (zipfile.ZipInfo 的類別成員): ZipInfo 对象.    (line   12)
* from_file() (zoneinfo.ZoneInfo 的類別成員): ZoneInfo 类.   (line   25)
* from_float() (decimal.Decimal 的方法): Decimal 对象.       (line  206)
* from_float() (fractions.Fraction 的方法): fractions --- 分数.
                                                             (line   99)
* from_iterable() (itertools.chain 的類別成員): Itertool函数.
                                                             (line   91)
* from_list() (traceback.StackSummary 的類別成員): StackSummary Objects.
                                                             (line   29)
* from_param() (ctypes._CData 的方法):   数据类型<2>.        (line   45)
* from_samples() (statistics.NormalDist 的類別成員): NormalDist 对象.
                                                             (line   39)
* from_traceback() (dis.Bytecode 的類別成員): 字节码分析.    (line   28)
* FrozenImporter (importlib.machinery 中的類別): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line   69)
* FrozenInstanceError:                   异常<16>.           (line    6)
* FrozenSet (typing 中的類別):           对应的内置类型.     (line   45)
* frozenset (內建類別):                  集合类型 --- set frozenset.
                                                             (line   28)
* fsdecode() (於 os 模組中):             进程参数.           (line   81)
* fsencode() (於 os 模組中):             进程参数.           (line   69)
* fspath() (於 os 模組中):               进程参数.           (line   93)
* fstat() (於 os 模組中):                文件描述符操作.     (line  130)
* fstatvfs() (於 os 模組中):             文件描述符操作.     (line  142)
* fstring:                               字符串字面值合并.   (line   19)
* fsum() (於 math 模組中):               数论与表示函数.     (line   68)
* fsync() (於 os 模組中):                文件描述符操作.     (line  150)
* fs_is_case_insensitive() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  945)
* FS_NONASCII (於 test.support 模組中):  test support --- Utilities for the Python test suite.
                                                             (line   48)
* FTP:                                   urllib request 的限制.
                                                             (line   30)
* FTP (ftplib 中的類別):                 ftplib --- FTP 协议客户端.
                                                             (line   40)
* FTP; ftplib (standard module):         ftplib --- FTP 协议客户端.
                                                             (line    8)
* FTP; protocol:                         urllib request 的限制.
                                                             (line    6)
* FTP; protocol <1>:                     ftplib --- FTP 协议客户端.
                                                             (line    8)
* FTPHandler (urllib.request 中的類別):  urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  352)
* ftplib (模組):                         ftplib --- FTP 协议客户端.
                                                             (line    6)
* ftp_open() (urllib.request.FTPHandler 的方法): FTPHandler 对象.
                                                             (line    6)
* FTP_TLS (ftplib 中的類別):             ftplib --- FTP 协议客户端.
                                                             (line   73)
* ftruncate() (於 os 模組中):            文件描述符操作.     (line  161)
* Full:                                  queue --- 一个同步的队列类.
                                                             (line   73)
* full() (asyncio.Queue 的方法):         队列.               (line   30)
* full() (multiprocessing.Queue 的方法): 管道和队列.         (line   97)
* full() (queue.Queue 的方法):           Queue对象.          (line   20)
* fullmatch() (re.Pattern 的方法):       正则表达式对象 （正则对象）.
                                                             (line   45)
* fullmatch() (於 re 模組中):            模块内容.           (line  129)
* full_url (urllib.request.Request 的屬性): Request 对象.    (line   10)
* func (functools.partial 的屬性):       partial 对象.       (line    9)
* funcattrs (2to3 fixer):                修复器.             (line  100)
* Function (symtable 中的類別):          符号表的查看.       (line   58)
* function annotation（函式註釋）:       術語表.             (line  411)
* function; annotations:                 函式註釋 Function Annotations.
                                                             (line    6)
* function; annotations <1>:             函数定义.           (line   79)
* function; argument:                    标准类型层级结构.   (line  229)
* function; call:                        标准类型层级结构.   (line  229)
* function; call <1>:                    调用.               (line   99)
* function; call <2>:                    调用.               (line  105)
* function; definition:                  return 语句.        (line    6)
* function; definition <1>:              函数定义.           (line    6)
* function; generator:                   yield 语句.         (line    6)
* function; name:                        函数定义.           (line    6)
* function; name <1>:                    函数定义.           (line    6)
* FunctionDef (ast 中的類別):            Function and class definitions.
                                                             (line    6)
* FunctionTestCase (unittest 中的類別):  测试用例.           (line  888)
* FunctionType (於 types 模組中):        标准解释器类型.     (line   17)
* function（函式）:                      術語表.             (line  404)
* functools (模組):                      functools --- 高阶函数和可调用对象上的操作.
                                                             (line    6)
* funny_files (filecmp.dircmp 的屬性):   dircmp 类.          (line   85)
* future (2to3 fixer):                   修复器.             (line  105)
* Future (asyncio 中的類別):             Future 对象<2>.     (line    6)
* Future (concurrent.futures 中的類別):  Future 对象.        (line    9)
* future; statement:                     future 语句.        (line    6)
* FutureWarning:                         警告.               (line   46)
* fwalk() (於 os 模組中):                文件和目录.         (line 1380)
* f_back (frame attribute):              标准类型层级结构.   (line  551)
* f_builtins (frame attribute):          标准类型层级结构.   (line  551)
* f_code (frame attribute):              标准类型层级结构.   (line  551)
* f_contiguous (memoryview 的屬性):      内存视图.           (line  438)
* f_globals (frame attribute):           标准类型层级结构.   (line  551)
* f_lasti (frame attribute):             标准类型层级结构.   (line  551)
* f_lineno (frame attribute):            标准类型层级结构.   (line  560)
* f_locals (frame attribute):            标准类型层级结构.   (line  551)
* F_LOCK (於 os 模組中):                 文件描述符操作.     (line  204)
* F_OK (於 os 模組中):                   文件和目录.         (line   89)
* F_TEST (於 os 模組中):                 文件描述符操作.     (line  204)
* F_TLOCK (於 os 模組中):                文件描述符操作.     (line  204)
* f_trace (frame attribute):             标准类型层级结构.   (line  560)
* f_trace_lines (frame attribute):       标准类型层级结构.   (line  560)
* f_trace_opcodes (frame attribute):     标准类型层级结构.   (line  560)
* F_ULOCK (於 os 模組中):                文件描述符操作.     (line  204)
* G.722:                                 aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line  140)
* gaierror:                              异常<11>.           (line   23)
* gamma() (於 math 模組中):              特殊函数.           (line   26)
* gammavariate() (於 random 模組中):     实值分布.           (line   39)
* garbage (於 gc 模組中):                gc --- 垃圾回收器接口.
                                                             (line  191)
* garbage collection:                    对象、值与类型.     (line   29)
* garbage collection（垃圾回收）:        術語表.             (line  440)
* gather() (curses.textpad.Textbox 的方法): 文本框对象.      (line   97)
* gather() (於 asyncio 模組中):          并发运行任务.       (line    6)
* gauss() (於 random 模組中):            实值分布.           (line   50)
* gc (模組):                             gc --- 垃圾回收器接口.
                                                             (line    6)
* gcd() (於 math 模組中):                数论与表示函数.     (line   84)
* gc_collect() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  520)
* ge() (於 operator 模組中):             operator --- 标准运算符替代函数.
                                                             (line   19)
* generate_help() (distutils.fancy_getopt.FancyGetopt 的方法): distutils fancy_getopt --- Wrapper around the standard getopt module.
                                                             (line   68)
* generate_tokens() (於 tokenize 模組中): 对输入进行解析标记.
                                                             (line   32)
* generator:                             術語表.             (line  448)
* Generator (collections.abc 中的類別):  容器抽象基类.       (line  147)
* Generator (email.generator 中的類別):  email generator 生成 MIME 文档.
                                                             (line  115)
* Generator (typing 中的類別):           collections abc 对应的其他类型.
                                                             (line   20)
* generator expression:                  術語表.             (line  467)
* generator expression（產生器運算式）:  術語表.             (line  467)
* generator iterator（產生器疊代器）:    術語表.             (line  457)
* generator; expression:                 生成器表达式.       (line    6)
* generator; function:                   标准类型层级结构.   (line  342)
* generator; function <1>:               yield 表达式.       (line    6)
* generator; function <2>:               yield 语句.         (line    6)
* generator; iterator:                   标准类型层级结构.   (line  342)
* generator; iterator <1>:               yield 语句.         (line    6)
* GeneratorExit:                         具体异常.           (line   28)
* GeneratorExp (ast 中的類別):           Comprehensions.     (line    6)
* GeneratorType (於 types 模組中):       标准解释器类型.     (line   26)
* generator（產生器）:                   術語表.             (line  448)
* Generic (typing 中的類別):             构建泛型类型.       (line    8)
* generic function（泛型函式）:          術語表.             (line  475)
* generic type（泛型型別）:              術語表.             (line  482)
* Generic; Alias:                        GenericAlias 类型.  (line    6)
* generic; special; attribute:           标准类型层级结构.   (line   10)
* GenericAlias (types 中的類別):         标准解释器类型.     (line  161)
* generic_visit() (ast.NodeVisitor 的方法): ast 中的辅助函数.
                                                             (line  166)
* genops() (於 pickletools 模組中):      编程接口<2>.        (line   19)
* gen_lib_options() (於 distutils.ccompiler 模組中): distutils ccompiler --- CCompiler基类.
                                                             (line   14)
* gen_preprocess_options() (於 distutils.ccompiler 模組中): distutils ccompiler --- CCompiler基类.
                                                             (line   24)
* gen_uuid() (於 msilib 模組中):         msilib --- Read and write Microsoft Installer files.
                                                             (line  109)
* geometric_mean() (於 statistics 模組中): 函式細節.         (line   56)
* get() (asyncio.Queue 的方法):          队列.               (line   37)
* get() (configparser.ConfigParser 的方法): ConfigParser 对象.
                                                             (line  164)
* get() (contextvars.Context 的方法):    手动上下文管理.     (line   78)
* get() (contextvars.ContextVar 的方法): 上下文变量.         (line   27)
* get() (dict 的方法):                   映射类型 --- dict.  (line  142)
* get() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  200)
* get() (email.message.Message 的方法):  email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  295)
* get() (mailbox.Mailbox 的方法):        Mailbox 对象.       (line  113)
* get() (multiprocessing.pool.AsyncResult 的方法): 进程池.   (line  163)
* get() (multiprocessing.Queue 的方法):  管道和队列.         (line  119)
* get() (multiprocessing.SimpleQueue 的方法): 管道和队列.    (line  190)
* get() (ossaudiodev.oss_mixer_device 的方法): Mixer Device Objects.
                                                             (line   59)
* get() (queue.Queue 的方法):            Queue对象.          (line   39)
* get() (queue.SimpleQueue 的方法):      SimpleQueue 对象.   (line   35)
* get() (tkinter.ttk.Combobox 的方法):   ttk Combobox.       (line   13)
* get() (tkinter.ttk.Spinbox 的方法):    ttk Spinbox.        (line    8)
* get() (types.MappingProxyType 的方法): 标准解释器类型.     (line  243)
* get() (xml.etree.ElementTree.Element 的方法): 元素对象.    (line   53)
* get() (於 webbrowser 模組中):          webbrowser --- 方便的Web浏览器控制器.
                                                             (line   64)
* getacl() (imaplib.IMAP4 的方法):       IMAP4 对象.         (line   94)
* getaddresses() (於 email.utils 模組中): email utils 其他工具.
                                                             (line   66)
* getaddrinfo() (asyncio.loop 的方法):   DNS.                (line    6)
* getaddrinfo() (於 socket 模組中):      其他功能.           (line   16)
* getallocatedblocks() (於 sys 模組中):  sys --- 系统相关的参数和函数.
                                                             (line  499)
* getandroidapilevel() (於 sys 模組中):  sys --- 系统相关的参数和函数.
                                                             (line  511)
* getannotation() (imaplib.IMAP4 的方法): IMAP4 对象.        (line   99)
* getargspec() (於 inspect 模組中):      类与函数<2>.        (line   17)
* getargvalues() (於 inspect 模組中):    类与函数<2>.        (line   80)
* getatime() (於 os.path 模組中):        os path --- 常用路径操作.
                                                             (line  148)
* getattr() (內建函式):                  內建函式.           (line  568)
* getattrfunc (C 型態):                  Slot Type typedefs. (line   42)
* getAttribute() (xml.dom.Element 的方法): 元素对象<2>.      (line   30)
* getAttributeNode() (xml.dom.Element 的方法): 元素对象<2>.  (line   35)
* getAttributeNodeNS() (xml.dom.Element 的方法): 元素对象<2>.
                                                             (line   44)
* getAttributeNS() (xml.dom.Element 的方法): 元素对象<2>.    (line   39)
* getattrofunc (C 型態):                 Slot Type typedefs. (line   52)
* getattr_static() (於 inspect 模組中):  Fetching attributes statically.
                                                             (line   16)
* GetBase() (xml.parsers.expat.xmlparser 的方法): XMLParser对象<2>.
                                                             (line   26)
* getbegyx() (curses.window 的方法):     Window 对象.        (line  193)
* getbkgd() (curses.window 的方法):      Window 对象.        (line  197)
* getblocking() (socket.socket 的方法):  套接字对象.         (line  130)
* getboolean() (configparser.ConfigParser 的方法): ConfigParser 对象.
                                                             (line  194)
* getbuffer() (io.BytesIO 的方法):       缓冲流.             (line   19)
* getbufferproc (C 型態):                Slot Type typedefs. (line   94)
* getByteStream() (xml.sax.xmlreader.InputSource 的方法): InputSource 对象.
                                                             (line   46)
* getcallargs() (於 inspect 模組中):     类与函数<2>.        (line  139)
* getcanvas() (於 turtle 模組中):        设置与特殊方法.     (line   52)
* getcapabilities() (nntplib.NNTP 的方法): 方法<3>.          (line   29)
* getcaps() (於 mailcap 模組中):         mailcap --- Mailcap 文件处理.
                                                             (line   47)
* getch() (curses.window 的方法):        Window 对象.        (line  201)
* getch() (於 msvcrt 模組中):            控制台 I/O.         (line   10)
* getCharacterStream() (xml.sax.xmlreader.InputSource 的方法): InputSource 对象.
                                                             (line   60)
* getche() (於 msvcrt 模組中):           控制台 I/O.         (line   21)
* getChild() (logging.Logger 的方法):    记录器对象.         (line   89)
* getclasstree() (於 inspect 模組中):    类与函数<2>.        (line    6)
* getclosurevars() (於 inspect 模組中):  类与函数<2>.        (line  169)
* GetColumnInfo() (msilib.View 的方法):  View Objects.       (line   12)
* getColumnNumber() (xml.sax.xmlreader.Locator 的方法): Locator 对象.
                                                             (line    8)
* getcomments() (於 inspect 模組中):     Retrieving source code.
                                                             (line   17)
* getcompname() (aifc.aifc 的方法):      aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line   62)
* getcompname() (sunau.AU_read 的方法):  AU_read 对象.       (line   32)
* getcompname() (wave.Wave_read 的方法): Wave_read对象.      (line   33)
* getcomptype() (aifc.aifc 的方法):      aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line   57)
* getcomptype() (sunau.AU_read 的方法):  AU_read 对象.       (line   28)
* getcomptype() (wave.Wave_read 的方法): Wave_read对象.      (line   29)
* getContentHandler() (xml.sax.xmlreader.XMLReader 的方法): XMLReader 对象.
                                                             (line   20)
* getcontext() (於 decimal 模組中):      上下文对象.         (line   12)
* getcoroutinelocals() (於 inspect 模組中): Current State of Generators and Coroutines.
                                                             (line   73)
* getcoroutinestate() (於 inspect 模組中): Current State of Generators and Coroutines.
                                                             (line   28)
* getctime() (於 os.path 模組中):        os path --- 常用路径操作.
                                                             (line  162)
* getcwd() (於 os 模組中):               文件和目录.         (line  252)
* getcwdb() (於 os 模組中):              文件和目录.         (line  256)
* getcwdu (2to3 fixer):                  修复器.             (line  109)
* getdecoder() (於 codecs 模組中):       codecs --- 编解码器注册和相关基类.
                                                             (line   92)
* getdefaultencoding() (於 sys 模組中):  sys --- 系统相关的参数和函数.
                                                             (line  519)
* getdefaultlocale() (於 locale 模組中): locale --- 国际化服务.
                                                             (line  249)
* getdefaulttimeout() (於 socket 模組中): 其他功能.          (line  275)
* getdlopenflags() (於 sys 模組中):      sys --- 系统相关的参数和函数.
                                                             (line  523)
* getdoc() (於 inspect 模組中):          Retrieving source code.
                                                             (line    6)
* getDOMImplementation() (於 xml.dom 模組中): 模块内容<6>.   (line   15)
* getDTDHandler() (xml.sax.xmlreader.XMLReader 的方法): XMLReader 对象.
                                                             (line   29)
* getEffectiveLevel() (logging.Logger 的方法): 记录器对象.   (line   82)
* getegid() (於 os 模組中):              进程参数.           (line  150)
* getElementsByTagName() (xml.dom.Document 的方法): Document 对象.
                                                             (line   52)
* getElementsByTagName() (xml.dom.Element 的方法): 元素对象<2>.
                                                             (line   13)
* getElementsByTagNameNS() (xml.dom.Document 的方法): Document 对象.
                                                             (line   57)
* getElementsByTagNameNS() (xml.dom.Element 的方法): 元素对象<2>.
                                                             (line   17)
* getencoder() (於 codecs 模組中):       codecs --- 编解码器注册和相关基类.
                                                             (line   86)
* getEncoding() (xml.sax.xmlreader.InputSource 的方法): InputSource 对象.
                                                             (line   32)
* getEntityResolver() (xml.sax.xmlreader.XMLReader 的方法): XMLReader 对象.
                                                             (line   38)
* getenv() (於 os 模組中):               进程参数.           (line  118)
* getenvb() (於 os 模組中):              进程参数.           (line  130)
* getErrorHandler() (xml.sax.xmlreader.XMLReader 的方法): XMLReader 对象.
                                                             (line   48)
* geteuid() (於 os 模組中):              进程参数.           (line  156)
* getEvent() (xml.dom.pulldom.DOMEventStream 的方法): DOMEventStream 对象.
                                                             (line   10)
* getEventCategory() (logging.handlers.NTEventLogHandler 的方法): NTEventLogHandler.
                                                             (line   35)
* getEventType() (logging.handlers.NTEventLogHandler 的方法): NTEventLogHandler.
                                                             (line   40)
* getException() (xml.sax.SAXException 的方法): SAXException 对象.
                                                             (line   12)
* getFeature() (xml.sax.xmlreader.XMLReader 的方法): XMLReader 对象.
                                                             (line   65)
* GetFieldCount() (msilib.Record 的方法): Record Objects.    (line    6)
* getfile() (於 inspect 模組中):         Retrieving source code.
                                                             (line   26)
* getFilesToDelete() (logging.handlers.TimedRotatingFileHandler 的方法): TimedRotatingFileHandler.
                                                             (line   94)
* getfilesystemencodeerrors() (於 sys 模組中): sys --- 系统相关的参数和函数.
                                                             (line  563)
* getfilesystemencoding() (於 sys 模組中): sys --- 系统相关的参数和函数.
                                                             (line  531)
* getfirst() (cgi.FieldStorage 的方法):  更高层级的接口.     (line   45)
* getfloat() (configparser.ConfigParser 的方法): ConfigParser 对象.
                                                             (line  187)
* getfmts() (ossaudiodev.oss_audio_device 的方法): 音频设备对象.
                                                             (line   65)
* getfqdn() (於 socket 模組中):          其他功能.           (line   60)
* getframeinfo() (於 inspect 模組中):    The interpreter stack.
                                                             (line   46)
* getframerate() (aifc.aifc 的方法):     aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line   49)
* getframerate() (sunau.AU_read 的方法): AU_read 对象.       (line   20)
* getframerate() (wave.Wave_read 的方法): Wave_read对象.     (line   21)
* getfullargspec() (於 inspect 模組中):  类与函数<2>.        (line   36)
* getgeneratorlocals() (於 inspect 模組中): Current State of Generators and Coroutines.
                                                             (line   53)
* getgeneratorstate() (於 inspect 模組中): Current State of Generators and Coroutines.
                                                             (line   12)
* getgid() (於 os 模組中):               进程参数.           (line  162)
* getgrall() (於 grp 模組中):            grp --- 组数据库.   (line   49)
* getgrgid() (於 grp 模組中):            grp --- 组数据库.   (line   36)
* getgrnam() (於 grp 模組中):            grp --- 组数据库.   (line   44)
* getgrouplist() (於 os 模組中):         进程参数.           (line  168)
* getgroups() (於 os 模組中):            进程参数.           (line  178)
* getheader() (http.client.HTTPResponse 的方法): HTTPResponse 对象.
                                                             (line   22)
* getheaders() (http.client.HTTPResponse 的方法): HTTPResponse 对象.
                                                             (line   29)
* gethostbyaddr() (in module socket):    进程参数.           (line  428)
* gethostbyaddr() (於 socket 模組中):    其他功能.           (line  107)
* gethostbyname() (於 socket 模組中):    其他功能.           (line   72)
* gethostbyname_ex() (於 socket 模組中): 其他功能.           (line   83)
* gethostname() (in module socket):      进程参数.           (line  428)
* gethostname() (於 socket 模組中):      其他功能.           (line   98)
* getincrementaldecoder() (於 codecs 模組中): codecs --- 编解码器注册和相关基类.
                                                             (line  105)
* getincrementalencoder() (於 codecs 模組中): codecs --- 编解码器注册和相关基类.
                                                             (line   98)
* getinfo() (zipfile.ZipFile 的方法):    ZipFile 对象.       (line   79)
* getinnerframes() (於 inspect 模組中):  The interpreter stack.
                                                             (line   62)
* GetInputContext() (xml.parsers.expat.xmlparser 的方法): XMLParser对象<2>.
                                                             (line   31)
* getint() (configparser.ConfigParser 的方法): ConfigParser 对象.
                                                             (line  180)
* GetInteger() (msilib.Record 的方法):   Record Objects.     (line   11)
* getitem() (於 operator 模組中):        operator --- 标准运算符替代函数.
                                                             (line  177)
* getiterfunc (C 型態):                  Slot Type typedefs. (line   84)
* getitimer() (於 signal 模組中):        模块内容<5>.        (line  351)
* getkey() (curses.window 的方法):       Window 对象.        (line  215)
* GetLastError() (於 ctypes 模組中):     工具函数.           (line   97)
* getLength() (xml.sax.xmlreader.Attributes 的方法): Attributes 接口.
                                                             (line   10)
* getLevelName() (於 logging 模組中):    模块级函数.         (line  165)
* getline() (於 linecache 模組中):       linecache --- 随机读写文本行.
                                                             (line   20)
* getLineNumber() (xml.sax.xmlreader.Locator 的方法): Locator 对象.
                                                             (line   12)
* getlist() (cgi.FieldStorage 的方法):   更高层级的接口.     (line   53)
* getloadavg() (於 os 模組中):           其他系统信息.       (line   40)
* getlocale() (於 locale 模組中):        locale --- 国际化服务.
                                                             (line  268)
* getLogger() (於 logging 模組中):       模块级函数.         (line    8)
* getLoggerClass() (於 logging 模組中):  模块级函数.         (line   18)
* getlogin() (於 os 模組中):             进程参数.           (line  196)
* getLogRecordFactory() (於 logging 模組中): 模块级函数.     (line   28)
* getmark() (aifc.aifc 的方法):          aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line   79)
* getmark() (sunau.AU_read 的方法):      AU_read 对象.       (line   70)
* getmark() (wave.Wave_read 的方法):     Wave_read对象.      (line   58)
* getmarkers() (aifc.aifc 的方法):       aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line   73)
* getmarkers() (sunau.AU_read 的方法):   AU_read 对象.       (line   66)
* getmarkers() (wave.Wave_read 的方法):  Wave_read对象.      (line   54)
* getmaxyx() (curses.window 的方法):     Window 对象.        (line  221)
* getmember() (tarfile.TarFile 的方法):  TarFile 对象.       (line   84)
* getmembers() (tarfile.TarFile 的方法): TarFile 对象.       (line   92)
* getmembers() (於 inspect 模組中):      类型和成员.         (line  256)
* getMessage() (logging.LogRecord 的方法): LogRecord 属性.   (line   45)
* getMessage() (xml.sax.SAXException 的方法): SAXException 对象.
                                                             (line    8)
* getMessageID() (logging.handlers.NTEventLogHandler 的方法): NTEventLogHandler.
                                                             (line   49)
* getmodule() (於 inspect 模組中):       Retrieving source code.
                                                             (line   32)
* getmodulename() (於 inspect 模組中):   类型和成员.         (line  269)
* getmouse() (於 curses 模組中):         函数<4>.            (line  121)
* getmro() (於 inspect 模組中):          类与函数<2>.        (line  131)
* getmtime() (於 os.path 模組中):        os path --- 常用路径操作.
                                                             (line  154)
* getname() (chunk.Chunk 的方法):        chunk --- 读取 IFF 分块数据.
                                                             (line   60)
* getName() (threading.Thread 的方法):   线程对象.           (line  118)
* getNameByQName() (xml.sax.xmlreader.AttributesNS 的方法): AttributesNS 接口.
                                                             (line   15)
* getnameinfo() (asyncio.loop 的方法):   DNS.                (line   11)
* getnameinfo() (於 socket 模組中):      其他功能.           (line  119)
* getnames() (tarfile.TarFile 的方法):   TarFile 对象.       (line   97)
* getNames() (xml.sax.xmlreader.Attributes 的方法): Attributes 接口.
                                                             (line   14)
* getnchannels() (aifc.aifc 的方法):     aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line   41)
* getnchannels() (sunau.AU_read 的方法): AU_read 对象.       (line   12)
* getnchannels() (wave.Wave_read 的方法): Wave_read对象.     (line   13)
* getnframes() (aifc.aifc 的方法):       aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line   53)
* getnframes() (sunau.AU_read 的方法):   AU_read 对象.       (line   24)
* getnframes() (wave.Wave_read 的方法):  Wave_read对象.      (line   25)
* getnode:                               uuid --- RFC 4122 定义的UUID对象.
                                                             (line  160)
* getnode() (於 uuid 模組中):            uuid --- RFC 4122 定义的UUID对象.
                                                             (line  147)
* getopt (模組):                         getopt --- C 风格的命令行选项解析器.
                                                             (line    6)
* getopt() (distutils.fancy_getopt.FancyGetopt 的方法): distutils fancy_getopt --- Wrapper around the standard getopt module.
                                                             (line   49)
* getopt() (於 getopt 模組中):           getopt --- C 风格的命令行选项解析器.
                                                             (line   21)
* GetoptError:                           getopt --- C 风格的命令行选项解析器.
                                                             (line   55)
* getouterframes() (於 inspect 模組中):  The interpreter stack.
                                                             (line   52)
* getoutput() (於 subprocess 模組中):    旧式的 Shell 发起函数.
                                                             (line   38)
* getpagesize() (於 resource 模組中):    资源用量.           (line   94)
* getparams() (aifc.aifc 的方法):        aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line   67)
* getparams() (sunau.AU_read 的方法):    AU_read 对象.       (line   38)
* getparams() (wave.Wave_read 的方法):   Wave_read对象.      (line   38)
* getparyx() (curses.window 的方法):     Window 对象.        (line  225)
* getpass (模組):                        getpass --- 便携式密码输入工具.
                                                             (line    6)
* getpass() (於 getpass 模組中):         getpass --- 便携式密码输入工具.
                                                             (line   12)
* GetPassWarning:                        getpass --- 便携式密码输入工具.
                                                             (line   27)
* getpeercert() (ssl.SSLSocket 的方法):  SSL 套接字.         (line  122)
* getpeername() (socket.socket 的方法):  套接字对象.         (line  110)
* getpen() (於 turtle 模組中):           特殊海龟方法.       (line   37)
* getpgid() (於 os 模組中):              进程参数.           (line  205)
* getpgrp() (於 os 模組中):              进程参数.           (line  212)
* getpid() (於 os 模組中):               进程参数.           (line  218)
* getpos() (html.parser.HTMLParser 的方法): HTMLParser 方法. (line   25)
* getppid() (於 os 模組中):              进程参数.           (line  222)
* getpreferredencoding() (於 locale 模組中): locale --- 国际化服务.
                                                             (line  277)
* getpriority() (於 os 模組中):          进程参数.           (line  232)
* getprofile() (於 sys 模組中):          sys --- 系统相关的参数和函数.
                                                             (line  620)
* GetProperty() (msilib.SummaryInformation 的方法): Summary Information Objects.
                                                             (line    6)
* getProperty() (xml.sax.xmlreader.XMLReader 的方法): XMLReader 对象.
                                                             (line   77)
* GetPropertyCount() (msilib.SummaryInformation 的方法): Summary Information Objects.
                                                             (line   17)
* getprotobyname() (於 socket 模組中):   其他功能.           (line  133)
* getproxies() (於 urllib.request 模組中): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  133)
* getPublicId() (xml.sax.xmlreader.InputSource 的方法): InputSource 对象.
                                                             (line   10)
* getPublicId() (xml.sax.xmlreader.Locator 的方法): Locator 对象.
                                                             (line   16)
* getpwall() (於 pwd 模組中):            pwd --- 用户密码数据库.
                                                             (line   59)
* getpwnam() (於 pwd 模組中):            pwd --- 用户密码数据库.
                                                             (line   55)
* getpwuid() (於 pwd 模組中):            pwd --- 用户密码数据库.
                                                             (line   51)
* getQNameByName() (xml.sax.xmlreader.AttributesNS 的方法): AttributesNS 接口.
                                                             (line   19)
* getQNames() (xml.sax.xmlreader.AttributesNS 的方法): AttributesNS 接口.
                                                             (line   23)
* getquota() (imaplib.IMAP4 的方法):     IMAP4 对象.         (line  104)
* getquotaroot() (imaplib.IMAP4 的方法): IMAP4 对象.         (line  109)
* getrandbits() (於 random 模組中):      整数用函数.         (line   26)
* getrandom() (於 os 模組中):            随机数.             (line    6)
* getreader() (於 codecs 模組中):        codecs --- 编解码器注册和相关基类.
                                                             (line  112)
* getrecursionlimit() (於 sys 模組中):   sys --- 系统相关的参数和函数.
                                                             (line  579)
* getrefcount() (於 sys 模組中):         sys --- 系统相关的参数和函数.
                                                             (line  574)
* getresgid() (於 os 模組中):            进程参数.           (line  265)
* getresponse() (http.client.HTTPConnection 的方法): HTTPConnection 对象.
                                                             (line   48)
* getresuid() (於 os 模組中):            进程参数.           (line  256)
* getrlimit() (於 resource 模組中):      资源限制<2>.        (line   20)
* getroot() (xml.etree.ElementTree.ElementTree 的方法): ElementTree 对象.
                                                             (line   31)
* getrusage() (於 resource 模組中):      资源用量.           (line    8)
* getsample() (於 audioop 模組中):       audioop --- 处理原始音频数据.
                                                             (line   94)
* getsampwidth() (aifc.aifc 的方法):     aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line   45)
* getsampwidth() (sunau.AU_read 的方法): AU_read 对象.       (line   16)
* getsampwidth() (wave.Wave_read 的方法): Wave_read对象.     (line   17)
* getscreen() (於 turtle 模組中):        特殊海龟方法.       (line   47)
* getservbyname() (於 socket 模組中):    其他功能.           (line  140)
* getservbyport() (於 socket 模組中):    其他功能.           (line  148)
* GetSetDescriptorType (於 types 模組中): 标准解释器类型.    (line  194)
* getshapes() (於 turtle 模組中):        设置与特殊方法.     (line   61)
* getsid() (於 os 模組中):               进程参数.           (line  392)
* getsignal() (於 signal 模組中):        模块内容<5>.        (line  222)
* getsitepackages() (於 site 模組中):    模块内容<8>.        (line   52)
* getsize() (chunk.Chunk 的方法):        chunk --- 读取 IFF 分块数据.
                                                             (line   64)
* getsize() (於 os.path 模組中):         os path --- 常用路径操作.
                                                             (line  171)
* getsizeof() (於 sys 模組中):           sys --- 系统相关的参数和函数.
                                                             (line  585)
* getsockname() (socket.socket 的方法):  套接字对象.         (line  116)
* getsockopt() (socket.socket 的方法):   套接字对象.         (line  121)
* getsource() (於 inspect 模組中):       Retrieving source code.
                                                             (line   55)
* getsourcefile() (於 inspect 模組中):   Retrieving source code.
                                                             (line   36)
* getsourcelines() (於 inspect 模組中):  Retrieving source code.
                                                             (line   42)
* getspall() (於 spwd 模組中):           spwd —— shadow 密码库.
                                                             (line   58)
* getspnam() (於 spwd 模組中):           spwd —— shadow 密码库.
                                                             (line   51)
* getstate() (codecs.IncrementalDecoder 的方法): IncrementalDecoder 对象.
                                                             (line   37)
* getstate() (codecs.IncrementalEncoder 的方法): IncrementalEncoder 对象.
                                                             (line   36)
* getstate() (於 random 模組中):         簿记功能.           (line   28)
* getstatus() (http.client.HTTPResponse 的方法): HTTPResponse 对象.
                                                             (line   80)
* getstatus() (urllib.response.addinfourl 的方法): urllib response --- urllib 使用的 Response 类.
                                                             (line   39)
* getstatusoutput() (於 subprocess 模組中): 旧式的 Shell 发起函数.
                                                             (line   10)
* getstr() (curses.window 的方法):       Window 对象.        (line  230)
* GetString() (msilib.Record 的方法):    Record Objects.     (line   16)
* getSubject() (logging.handlers.SMTPHandler 的方法): SMTPHandler.
                                                             (line   32)
* GetSummaryInformation() (msilib.Database 的方法): Database Objects.
                                                             (line   16)
* getswitchinterval() (於 sys 模組中):   sys --- 系统相关的参数和函数.
                                                             (line  602)
* getSystemId() (xml.sax.xmlreader.InputSource 的方法): InputSource 对象.
                                                             (line   18)
* getSystemId() (xml.sax.xmlreader.Locator 的方法): Locator 对象.
                                                             (line   20)
* getsyx() (於 curses 模組中):           函数<4>.            (line  133)
* gettarinfo() (tarfile.TarFile 的方法): TarFile 对象.       (line  196)
* gettempdir() (於 tempfile 模組中):     tempfile --- 生成临时文件和目录.
                                                             (line  190)
* gettempdirb() (於 tempfile 模組中):    tempfile --- 生成临时文件和目录.
                                                             (line  216)
* gettempprefix() (於 tempfile 模組中):  tempfile --- 生成临时文件和目录.
                                                             (line  222)
* gettempprefixb() (於 tempfile 模組中): tempfile --- 生成临时文件和目录.
                                                             (line  226)
* getTestCaseNames() (unittest.TestLoader 的方法): Loading and running tests.
                                                             (line  111)
* gettext (模組):                        gettext --- 多语种国际化服务.
                                                             (line    6)
* gettext() (gettext.GNUTranslations 的方法): GNUTranslations 类.
                                                             (line   32)
* gettext() (gettext.NullTranslations 的方法): NullTranslations 类.
                                                             (line   29)
* gettext() (於 gettext 模組中):         GNU gettext API.    (line   37)
* gettext() (於 locale 模組中):          访问信息目录.       (line    6)
* gettimeout() (socket.socket 的方法):   套接字对象.         (line  138)
* gettrace() (於 sys 模組中):            sys --- 系统相关的参数和函数.
                                                             (line  624)
* getturtle() (於 turtle 模組中):        特殊海龟方法.       (line   37)
* getType() (xml.sax.xmlreader.Attributes 的方法): Attributes 接口.
                                                             (line   18)
* getuid() (於 os 模組中):               进程参数.           (line  274)
* geturl() (http.client.HTTPResponse 的方法): HTTPResponse 对象.
                                                             (line   72)
* geturl() (urllib.parse.urllib.parse.SplitResult 的方法): 结构化解析结果.
                                                             (line   10)
* geturl() (urllib.response.addinfourl 的方法): urllib response --- urllib 使用的 Response 类.
                                                             (line   27)
* getuser() (於 getpass 模組中):         getpass --- 便携式密码输入工具.
                                                             (line   31)
* getuserbase() (於 site 模組中):        模块内容<8>.        (line   58)
* getusersitepackages() (於 site 模組中): 模块内容<8>.       (line   65)
* getvalue() (io.BytesIO 的方法):        缓冲流.             (line   35)
* getvalue() (io.StringIO 的方法):       文本 I/O<2>.        (line  183)
* getValue() (xml.sax.xmlreader.Attributes 的方法): Attributes 接口.
                                                             (line   22)
* getValueByQName() (xml.sax.xmlreader.AttributesNS 的方法): AttributesNS 接口.
                                                             (line   11)
* getwch() (於 msvcrt 模組中):           控制台 I/O.         (line   17)
* getwche() (於 msvcrt 模組中):          控制台 I/O.         (line   26)
* getweakrefcount() (於 weakref 模組中): weakref --- 弱引用. (line  116)
* getweakrefs() (於 weakref 模組中):     weakref --- 弱引用. (line  120)
* getwelcome() (ftplib.FTP 的方法):      FTP 对象.           (line   34)
* getwelcome() (nntplib.NNTP 的方法):    方法<3>.            (line   24)
* getwelcome() (poplib.POP3 的方法):     POP3 对象.          (line   18)
* getwin() (於 curses 模組中):           函数<4>.            (line  138)
* getwindowsversion() (於 sys 模組中):   sys --- 系统相关的参数和函数.
                                                             (line  632)
* getwriter() (於 codecs 模組中):        codecs --- 编解码器注册和相关基类.
                                                             (line  119)
* getxattr() (於 os 模組中):             Linux 扩展属性.     (line   10)
* getyx() (curses.window 的方法):        Window 对象.        (line  240)
* GET_AITER (opcode):                    Python字节码说明.   (line  259)
* get_all() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  208)
* get_all() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  303)
* get_all() (wsgiref.headers.Headers 的方法): wsgiref headers -- WSGI 响应标头工具.
                                                             (line   40)
* get_all_breaks() (bdb.Bdb 的方法):     bdb --- Debugger framework.
                                                             (line  331)
* get_all_start_methods() (於 multiprocessing 模組中): 杂项<3>.
                                                             (line   68)
* GET_ANEXT (opcode):                    Python字节码说明.   (line  267)
* get_app() (wsgiref.simple_server.WSGIServer 的方法): wsgiref simple_server -- 一个简单的 WSGI HTTP 服务器.
                                                             (line   60)
* get_archive_formats() (於 shutil 模組中): 归档操作.        (line   54)
* get_args() (於 typing 模組中):         内省辅助器.         (line   32)
* get_asyncgen_hooks() (於 sys 模組中):  sys --- 系统相关的参数和函数.
                                                             (line  677)
* get_attribute() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  863)
* GET_AWAITABLE (opcode):                Python字节码说明.   (line  251)
* get_begidx() (於 readline 模組中):     Completion.         (line   33)
* get_blocking() (於 os 模組中):         文件描述符操作.     (line  173)
* get_body() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  440)
* get_body_encoding() (email.charset.Charset 的方法): email charset 表示字符集.
                                                             (line   85)
* get_boundary() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  336)
* get_boundary() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  485)
* get_bpbynumber() (bdb.Bdb 的方法):     bdb --- Debugger framework.
                                                             (line  308)
* get_break() (bdb.Bdb 的方法):          bdb --- Debugger framework.
                                                             (line  317)
* get_breaks() (bdb.Bdb 的方法):         bdb --- Debugger framework.
                                                             (line  321)
* get_buffer() (asyncio.BufferedProtocol 的方法): 缓冲流协议.
                                                             (line   16)
* get_buffer() (xdrlib.Packer 的方法):   Packer 对象.        (line    8)
* get_buffer() (xdrlib.Unpacker 的方法): Unpacker 对象.      (line   21)
* get_bytes() (mailbox.Mailbox 的方法):  Mailbox 对象.       (line  129)
* get_cache_token() (於 abc 模組中):     abc --- 抽象基类.   (line  284)
* get_ca_certs() (ssl.SSLContext 的方法): SSL 上下文.        (line  138)
* get_channel_binding() (ssl.SSLSocket 的方法): SSL 套接字.  (line  206)
* get_charset() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  220)
* get_charsets() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  360)
* get_charsets() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  513)
* get_children() (symtable.SymbolTable 的方法): 符号表的查看.
                                                             (line   54)
* get_children() (tkinter.ttk.Treeview 的方法): ttk Treeview.
                                                             (line   16)
* get_child_watcher() (asyncio.AbstractEventLoopPolicy 的方法): 策略对象.
                                                             (line   33)
* get_child_watcher() (於 asyncio 模組中): 进程监视器.       (line   21)
* get_ciphers() (ssl.SSLContext 的方法): SSL 上下文.         (line  151)
* get_clock_info() (於 time 模組中):     函数<3>.            (line   88)
* get_close_matches() (於 difflib 模組中): difflib --- 计算差异的辅助工具.
                                                             (line  172)
* get_code() (importlib.abc.InspectLoader 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  329)
* get_code() (importlib.abc.SourceLoader 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  496)
* get_code() (importlib.machinery.ExtensionFileLoader 的方法): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  294)
* get_code() (importlib.machinery.SourcelessFileLoader 的方法): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  243)
* get_code() (zipimport.zipimporter 的方法): zipimporter 对象.
                                                             (line   25)
* get_completer() (於 readline 模組中):  Completion.         (line   24)
* get_completer_delims() (於 readline 模組中): Completion.   (line   40)
* get_completion_type() (於 readline 模組中): Completion.    (line   28)
* get_config_h_filename() (於 distutils.sysconfig 模組中): distutils sysconfig --- System configuration information.
                                                             (line   41)
* get_config_h_filename() (於 sysconfig 模組中): 其他功能<2>.
                                                             (line   67)
* get_config_var() (於 distutils.sysconfig 模組中): distutils sysconfig --- System configuration information.
                                                             (line   27)
* get_config_var() (於 sysconfig 模組中): 配置变量.          (line   26)
* get_config_vars() (於 distutils.sysconfig 模組中): distutils sysconfig --- System configuration information.
                                                             (line   32)
* get_config_vars() (於 sysconfig 模組中): 配置变量.         (line   16)
* get_content() (email.contentmanager.ContentManager 的方法): email contentmanager 管理 MIME 内容.
                                                             (line   17)
* get_content() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  493)
* get_content() (於 email.contentmanager 模組中): 内容管理器实例.
                                                             (line   19)
* get_content_charset() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  355)
* get_content_charset() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  505)
* get_content_disposition() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  380)
* get_content_disposition() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  524)
* get_content_maintype() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  266)
* get_content_maintype() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  361)
* get_content_subtype() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  272)
* get_content_subtype() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  367)
* get_content_type() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  252)
* get_content_type() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  348)
* get_context() (於 multiprocessing 模組中): 杂项<3>.        (line   77)
* get_coro() (asyncio.Task 的方法):      Task 对象.          (line  183)
* get_coroutine_origin_tracking_depth() (於 sys 模組中): sys --- 系统相关的参数和函数.
                                                             (line  688)
* get_count() (於 gc 模組中):            gc --- 垃圾回收器接口.
                                                             (line   90)
* get_current_history_length() (於 readline 模組中): 历史列表.
                                                             (line   13)
* get_data() (importlib.abc.FileLoader 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  432)
* get_data() (importlib.abc.ResourceLoader 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  313)
* get_data() (zipimport.zipimporter 的方法): zipimporter 对象.
                                                             (line   30)
* get_data() (於 pkgutil 模組中):        pkgutil --- 包扩展工具.
                                                             (line  200)
* get_date() (mailbox.MaildirMessage 的方法): MaildirMessage.
                                                             (line   82)
* get_debug() (asyncio.loop 的方法):     开启调试模式.       (line    6)
* get_debug() (於 gc 模組中):            gc --- 垃圾回收器接口.
                                                             (line   47)
* get_default() (argparse.ArgumentParser 的方法): 解析器默认值.
                                                             (line   29)
* get_default_compiler() (於 distutils.ccompiler 模組中): distutils ccompiler --- CCompiler基类.
                                                             (line   36)
* get_default_domain() (於 nis 模組中):  nis --- Sun 的 NIS 黄页 接口.
                                                             (line   43)
* get_default_type() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  278)
* get_default_type() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  373)
* get_default_verify_paths() (於 ssl 模組中): 证书处理.      (line   89)
* get_dialect() (於 csv 模組中):         模块内容<3>.        (line   72)
* get_disassembly_as_string() (test.support.bytecode_helper.BytecodeTestCase 的方法): test support bytecode_helper --- Support tools for testing correct bytecode generation.
                                                             (line   18)
* get_docstring() (於 ast 模組中):       ast 中的辅助函数.   (line   90)
* get_doctest() (doctest.DocTestParser 的方法): DocTestParser 对象.
                                                             (line   13)
* get_endidx() (於 readline 模組中):     Completion.         (line   33)
* get_environ() (wsgiref.simple_server.WSGIRequestHandler 的方法): wsgiref simple_server -- 一个简单的 WSGI HTTP 服务器.
                                                             (line   80)
* get_errno() (於 ctypes 模組中):        工具函数.           (line  103)
* get_escdelay() (於 curses 模組中):     函数<4>.            (line  358)
* get_event_loop() (asyncio.AbstractEventLoopPolicy 的方法): 策略对象.
                                                             (line   12)
* get_event_loop() (於 asyncio 模組中):  事件循环.           (line   34)
* get_event_loop_policy() (於 asyncio 模組中): 获取和设置策略.
                                                             (line    8)
* get_examples() (doctest.DocTestParser 的方法): DocTestParser 对象.
                                                             (line   22)
* get_exception_handler() (asyncio.loop 的方法): 错误处理API.
                                                             (line   18)
* get_exec_path() (於 os 模組中):        进程参数.           (line  142)
* get_extra_info() (asyncio.BaseTransport 的方法): 基础传输. (line   19)
* get_extra_info() (asyncio.StreamWriter 的方法): StreamWriter.
                                                             (line   56)
* get_field() (string.Formatter 的方法): 自定义字符串格式化. (line   44)
* get_file() (mailbox.Babyl 的方法):     Babyl.              (line   39)
* get_file() (mailbox.Mailbox 的方法):   Mailbox 对象.       (line  143)
* get_file() (mailbox.Maildir 的方法):   Maildir.            (line  101)
* get_file() (mailbox.mbox 的方法):      mbox.               (line   27)
* get_file() (mailbox.MH 的方法):        MH.                 (line   83)
* get_file() (mailbox.MMDF 的方法):      MMDF.               (line   24)
* get_filename() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  328)
* get_filename() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  477)
* get_filename() (importlib.abc.ExecutionLoader 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  392)
* get_filename() (importlib.abc.FileLoader 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  428)
* get_filename() (importlib.machinery.ExtensionFileLoader 的方法): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  302)
* get_filename() (zipimport.zipimporter 的方法): zipimporter 对象.
                                                             (line   38)
* get_file_breaks() (bdb.Bdb 的方法):    bdb --- Debugger framework.
                                                             (line  326)
* get_filter() (tkinter.filedialog.FileDialog 的方法): 原生 加载/保存 对话框.
                                                             (line   97)
* get_flags() (mailbox.MaildirMessage 的方法): MaildirMessage.
                                                             (line   59)
* get_flags() (mailbox.mboxMessage 的方法): mboxMessage.     (line   56)
* get_flags() (mailbox.MMDFMessage 的方法): MMDFMessage.     (line   55)
* get_folder() (mailbox.Maildir 的方法): Maildir.            (line   53)
* get_folder() (mailbox.MH 的方法):      MH.                 (line   32)
* get_frees() (symtable.Function 的方法): 符号表的查看.      (line   78)
* get_freeze_count() (於 gc 模組中):     gc --- 垃圾回收器接口.
                                                             (line  183)
* get_from() (mailbox.mboxMessage 的方法): mboxMessage.      (line   43)
* get_from() (mailbox.MMDFMessage 的方法): MMDFMessage.      (line   42)
* get_full_url() (urllib.request.Request 的方法): Request 对象.
                                                             (line   94)
* get_globals() (symtable.Function 的方法): 符号表的查看.    (line   70)
* get_grouped_opcodes() (difflib.SequenceMatcher 的方法): SequenceMatcher 对象.
                                                             (line  147)
* get_handle_inheritable() (於 os 模組中): 文件描述符的继承. (line   29)
* get_header() (urllib.request.Request 的方法): Request 对象.
                                                             (line  107)
* get_history_item() (於 readline 模組中): 历史列表.         (line   18)
* get_history_length() (於 readline 模組中): 历史文件.       (line   27)
* get_id() (symtable.SymbolTable 的方法): 符号表的查看.      (line   15)
* get_ident() (於 threading 模組中):     threading --- 基于线程的并行.
                                                             (line   74)
* get_ident() (於 _thread 模組中):       _thread --- 底层多线程 API.
                                                             (line   62)
* get_identifiers() (symtable.SymbolTable 的方法): 符号表的查看.
                                                             (line   42)
* get_importer() (於 pkgutil 模組中):    pkgutil --- 包扩展工具.
                                                             (line   91)
* get_info() (mailbox.MaildirMessage 的方法): MaildirMessage.
                                                             (line   90)
* get_inheritable() (socket.socket 的方法): 套接字对象.      (line  103)
* get_inheritable() (於 os 模組中):      文件描述符的继承.   (line   21)
* get_instructions() (於 dis 模組中):    分析函数.           (line   93)
* get_interpreter() (於 zipapp 模組中):  Python API.         (line   67)
* GET_ITER (opcode):                     Python字节码说明.   (line  107)
* get_key() (selectors.BaseSelector 的方法): 类<2>.          (line  126)
* get_labels() (mailbox.Babyl 的方法):   Babyl.              (line   28)
* get_labels() (mailbox.BabylMessage 的方法): BabylMessage.  (line   44)
* get_last_error() (於 ctypes 模組中):   工具函数.           (line  110)
* get_lineno() (symtable.SymbolTable 的方法): 符号表的查看.  (line   25)
* get_line_buffer() (於 readline 模組中): 行缓冲区.          (line    8)
* get_loader() (於 pkgutil 模組中):      pkgutil --- 包扩展工具.
                                                             (line  105)
* get_locals() (symtable.Function 的方法): 符号表的查看.     (line   66)
* get_logger() (於 multiprocessing 模組中): 日志.            (line   10)
* get_loop() (asyncio.Future 的方法):    Future 对象<2>.     (line  121)
* get_loop() (asyncio.Server 的方法):    Server 对象.        (line   37)
* get_magic() (於 imp 模組中):           imp —— 由代码内部访问 import 。.
                                                             (line   16)
* get_makefile_filename() (於 distutils.sysconfig 模組中): distutils sysconfig --- System configuration information.
                                                             (line   49)
* get_makefile_filename() (於 sysconfig 模組中): 其他功能<2>.
                                                             (line   71)
* get_map() (selectors.BaseSelector 的方法): 类<2>.          (line  133)
* get_matching_blocks() (difflib.SequenceMatcher 的方法): SequenceMatcher 对象.
                                                             (line   90)
* get_message() (mailbox.Mailbox 的方法): Mailbox 对象.      (line  123)
* get_method() (urllib.request.Request 的方法): Request 对象.
                                                             (line   61)
* get_methods() (symtable.Class 的方法): 符号表的查看.       (line   86)
* get_mixed_type_key() (於 ipaddress 模組中): 其他模块级别函数.
                                                             (line   51)
* get_name() (asyncio.Task 的方法):      Task 对象.          (line  189)
* get_name() (symtable.Symbol 的方法):   符号表的查看.       (line   95)
* get_name() (symtable.SymbolTable 的方法): 符号表的查看.    (line   19)
* get_namespace() (symtable.Symbol 的方法): 符号表的查看.    (line  161)
* get_namespaces() (symtable.Symbol 的方法): 符号表的查看.   (line  157)
* get_native_id() (於 threading 模組中): threading --- 基于线程的并行.
                                                             (line   82)
* get_native_id() (於 _thread 模組中):   _thread --- 底层多线程 API.
                                                             (line   68)
* get_nonlocals() (symtable.Function 的方法): 符号表的查看.  (line   74)
* get_nonstandard_attr() (http.cookiejar.Cookie 的方法): Cookie 对象<2>.
                                                             (line   92)
* get_nowait() (asyncio.Queue 的方法):   队列.               (line   42)
* get_nowait() (multiprocessing.Queue 的方法): 管道和队列.   (line  132)
* get_nowait() (queue.Queue 的方法):     Queue对象.          (line   53)
* get_nowait() (queue.SimpleQueue 的方法): SimpleQueue 对象. (line   44)
* get_objects() (於 gc 模組中):          gc --- 垃圾回收器接口.
                                                             (line   51)
* get_object_traceback() (於 tracemalloc 模組中): 函数<10>.  (line   12)
* get_opcodes() (difflib.SequenceMatcher 的方法): SequenceMatcher 对象.
                                                             (line  106)
* get_option() (optparse.OptionParser 的方法): Querying and manipulating your option parser.
                                                             (line   37)
* get_option_group() (optparse.OptionParser 的方法): Grouping Options.
                                                             (line  103)
* get_option_order() (distutils.fancy_getopt.FancyGetopt 的方法): distutils fancy_getopt --- Wrapper around the standard getopt module.
                                                             (line   62)
* get_origin() (於 typing 模組中):       内省辅助器.         (line   34)
* get_original_stdout() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  440)
* get_osfhandle() (於 msvcrt 模組中):    文件操作.           (line   50)
* get_output_charset() (email.charset.Charset 的方法): email charset 表示字符集.
                                                             (line   98)
* get_param() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  400)
* get_parameters() (symtable.Function 的方法): 符号表的查看. (line   62)
* get_params() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  385)
* get_path() (於 sysconfig 模組中):      安装路径.           (line   70)
* get_paths() (於 sysconfig 模組中):     安装路径.           (line  100)
* get_path_names() (於 sysconfig 模組中): 安装路径.          (line   65)
* get_payload() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  149)
* get_pid() (asyncio.SubprocessTransport 的方法): 子进程传输.
                                                             (line    6)
* get_pipe_transport() (asyncio.SubprocessTransport 的方法): 子进程传输.
                                                             (line   10)
* get_platform() (於 distutils.util 模組中): distutils util --- Miscellaneous other utility functions.
                                                             (line    9)
* get_platform() (於 sysconfig 模組中):  其他功能<2>.        (line   11)
* get_poly() (於 turtle 模組中):         特殊海龟方法.       (line   15)
* get_position() (xdrlib.Unpacker 的方法): Unpacker 对象.    (line   12)
* get_protocol() (asyncio.BaseTransport 的方法): 基础传输.   (line   79)
* get_python_inc() (於 distutils.sysconfig 模組中): distutils sysconfig --- System configuration information.
                                                             (line   57)
* get_python_lib() (於 distutils.sysconfig 模組中): distutils sysconfig --- System configuration information.
                                                             (line   67)
* get_python_version() (於 sysconfig 模組中): 其他功能<2>.   (line    6)
* get_ready() (graphlib.TopologicalSorter 的方法): graphlib --- 操作类似图的结构的功能.
                                                             (line  128)
* get_recsrc() (ossaudiodev.oss_mixer_device 的方法): Mixer Device Objects.
                                                             (line   83)
* get_referents() (於 gc 模組中):        gc --- 垃圾回收器接口.
                                                             (line  115)
* get_referrers() (於 gc 模組中):        gc --- 垃圾回收器接口.
                                                             (line   99)
* get_request() (socketserver.BaseServer 的方法): Server 对象<2>.
                                                             (line  114)
* get_returncode() (asyncio.SubprocessTransport 的方法): 子进程传输.
                                                             (line   25)
* get_running_loop() (於 asyncio 模組中): 事件循环.          (line   25)
* get_scheme() (wsgiref.handlers.BaseHandler 的方法): wsgiref handlers -- 服务器/网关基类.
                                                             (line  156)
* get_scheme_names() (於 sysconfig 模組中): 安装路径.        (line   60)
* get_selection() (tkinter.filedialog.FileDialog 的方法): 原生 加载/保存 对话框.
                                                             (line  101)
* get_sequences() (mailbox.MH 的方法):   MH.                 (line   47)
* get_sequences() (mailbox.MHMessage 的方法): MHMessage.     (line   30)
* get_server() (multiprocessing.managers.BaseManager 的方法): 管理器.
                                                             (line   39)
* get_server_certificate() (於 ssl 模組中): 证书处理.        (line   64)
* get_shapepoly() (於 turtle 模組中):    外观.               (line  171)
* get_socket() (telnetlib.Telnet 的方法): Telnet 对象.       (line   85)
* get_source() (importlib.abc.InspectLoader 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  340)
* get_source() (importlib.abc.SourceLoader 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  512)
* get_source() (importlib.machinery.ExtensionFileLoader 的方法): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  298)
* get_source() (importlib.machinery.SourcelessFileLoader 的方法): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  247)
* get_source() (zipimport.zipimporter 的方法): zipimporter 对象.
                                                             (line   45)
* get_source_segment() (於 ast 模組中):  ast 中的辅助函数.   (line  100)
* get_special_folder_path() (內建函式):  The Postinstallation script.
                                                             (line   32)
* get_stack() (asyncio.Task 的方法):     Task 对象.          (line  155)
* get_stack() (bdb.Bdb 的方法):          bdb --- Debugger framework.
                                                             (line  338)
* get_starttag_text() (html.parser.HTMLParser 的方法): HTMLParser 方法.
                                                             (line   29)
* get_start_method() (於 multiprocessing 模組中): 杂项<3>.   (line   88)
* get_stats() (於 gc 模組中):            gc --- 垃圾回收器接口.
                                                             (line   61)
* get_stats_profile() (pstats.Stats 的方法): Stats 类.       (line  225)
* get_stderr() (wsgiref.handlers.BaseHandler 的方法): wsgiref handlers -- 服务器/网关基类.
                                                             (line  105)
* get_stderr() (wsgiref.simple_server.WSGIRequestHandler 的方法): wsgiref simple_server -- 一个简单的 WSGI HTTP 服务器.
                                                             (line   87)
* get_stdin() (wsgiref.handlers.BaseHandler 的方法): wsgiref handlers -- 服务器/网关基类.
                                                             (line  100)
* get_string() (mailbox.Mailbox 的方法): Mailbox 对象.       (line  136)
* get_subdir() (mailbox.MaildirMessage 的方法): MaildirMessage.
                                                             (line   43)
* get_suffixes() (於 imp 模組中):        imp —— 由代码内部访问 import 。.
                                                             (line   25)
* get_symbols() (symtable.SymbolTable 的方法): 符号表的查看. (line   50)
* get_tabsize() (於 curses 模組中):      函数<4>.            (line  371)
* get_tag() (於 imp 模組中):             imp —— 由代码内部访问 import 。.
                                                             (line  234)
* get_task_factory() (asyncio.loop 的方法): 创建 Future 和 Task.
                                                             (line   36)
* get_terminal_size() (於 os 模組中):    查询终端的尺寸.     (line    8)
* get_terminal_size() (於 shutil 模組中): 查询输出终端的尺寸.
                                                             (line    6)
* get_terminator() (asynchat.async_chat 的方法): asynchat --- 异步套接字指令/响应处理程序.
                                                             (line   83)
* get_threshold() (於 gc 模組中):        gc --- 垃圾回收器接口.
                                                             (line   94)
* get_token() (shlex.shlex 的方法):      shlex 对象.         (line    8)
* get_traceback_limit() (於 tracemalloc 模組中): 函数<10>.   (line   22)
* get_traced_memory() (於 tracemalloc 模組中): 函数<10>.     (line   32)
* get_tracemalloc_memory() (於 tracemalloc 模組中): 函数<10>.
                                                             (line   56)
* get_type() (symtable.SymbolTable 的方法): 符号表的查看.    (line   10)
* get_type_hints() (於 typing 模組中):   内省辅助器.         (line    6)
* get_unixfrom() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  121)
* get_unixfrom() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  134)
* get_unpack_formats() (於 shutil 模組中): 归档操作.         (line  136)
* get_usage() (optparse.OptionParser 的方法): Other methods. (line   22)
* get_value() (string.Formatter 的方法): 自定义字符串格式化. (line   53)
* get_version() (optparse.OptionParser 的方法): Printing a version string.
                                                             (line   34)
* get_visible() (mailbox.BabylMessage 的方法): BabylMessage. (line   60)
* get_wch() (curses.window 的方法):      Window 对象.        (line  207)
* get_write_buffer_limits() (asyncio.WriteTransport 的方法): 只写传输.
                                                             (line   21)
* get_write_buffer_size() (asyncio.WriteTransport 的方法): 只写传输.
                                                             (line   17)
* GET_YIELD_FROM_ITER (opcode):          Python字节码说明.   (line  111)
* gid (tarfile.TarInfo 的屬性):          TarInfo 对象.       (line   70)
* GIL:                                   術語表.             (line  491)
* glob (模組):                           glob --- Unix 风格路径名模式扩展.
                                                             (line    6)
* glob() (msilib.Directory 的方法):      Directory Objects.  (line   40)
* glob() (pathlib.Path 的方法):          方法<2>.            (line   92)
* glob() (於 glob 模組中):               glob --- Unix 风格路径名模式扩展.
                                                             (line   27)
* Global (ast 中的類別):                 Function and class definitions.
                                                             (line  151)
* global interpreter lock:               Thread State and the Global Interpreter Lock.
                                                             (line    6)
* global interpreter lock（全域直譯器鎖）: 術語表.           (line  495)
* global; name; binding:                 global 语句.        (line    6)
* global; namespace:                     标准类型层级结构.   (line  239)
* globals() (內建函式):                  內建函式.           (line  579)
* globs (doctest.DocTest 的屬性):        DocTest 对象.       (line   20)
* gmtime() (於 time 模組中):             函数<3>.            (line  117)
* gname (tarfile.TarInfo 的屬性):        TarInfo 对象.       (line   78)
* GNOME:                                 编目构造器.         (line    6)
* GNUTranslations (gettext 中的類別):    GNUTranslations 类. (line   28)
* GNU_FORMAT (於 tarfile 模組中):        tarfile --- 读写tar归档文件.
                                                             (line  208)
* gnu_getopt() (於 getopt 模組中):       getopt --- C 风格的命令行选项解析器.
                                                             (line   46)
* go() (tkinter.filedialog.FileDialog 的方法): 原生 加载/保存 对话框.
                                                             (line  105)
* got (doctest.DocTestFailure 的屬性):   调试.               (line  177)
* goto() (於 turtle 模組中):             海龟动作.           (line   71)
* grammar:                               标注.               (line    6)
* Graphical User Interface:              以 Tk 打造 GUI.     (line    6)
* graphlib (模組):                       graphlib --- 操作类似图的结构的功能.
                                                             (line    6)
* GREATER (於 token 模組中):             token --- 与Python解析树一起使用的常量.
                                                             (line  106)
* GREATEREQUAL (於 token 模組中):        token --- 与Python解析树一起使用的常量.
                                                             (line  142)
* Greenwich Mean Time:                   time --- 时间的访问和转换.
                                                             (line   33)
* GRND_NONBLOCK (於 os 模組中):          随机数.             (line   61)
* GRND_RANDOM (於 os 模組中):            随机数.             (line   73)
* Group (email.headerregistry 中的類別): email headerregistry 自定义标头对象.
                                                             (line  390)
* group() (nntplib.NNTP 的方法):         方法<3>.            (line  140)
* group() (pathlib.Path 的方法):         方法<2>.            (line  117)
* group() (re.Match 的方法):             匹配对象.           (line   24)
* groupby() (於 itertools 模組中):       Itertool函数.       (line  269)
* groupdict() (re.Match 的方法):         匹配对象.           (line  103)
* groupindex (re.Pattern 的屬性):        正则表达式对象 （正则对象）.
                                                             (line   92)
* grouping:                              缩进.               (line    6)
* groups (email.headerregistry.AddressHeader 的屬性): email headerregistry 自定义标头对象.
                                                             (line  153)
* groups (re.Pattern 的屬性):            正则表达式对象 （正则对象）.
                                                             (line   88)
* groups() (re.Match 的方法):            匹配对象.           (line   83)
* grp (模組):                            grp --- 组数据库.   (line    6)
* Gt (ast 中的類別):                     表达式<2>.          (line  109)
* gt() (於 operator 模組中):             operator --- 标准运算符替代函数.
                                                             (line   19)
* GtE (ast 中的類別):                    表达式<2>.          (line  109)
* guess_all_extensions() (mimetypes.MimeTypes 的方法): MimeTypes 对象.
                                                             (line   53)
* guess_all_extensions() (於 mimetypes 模組中): mimetypes --- 映射文件名到 MIME 类型.
                                                             (line   43)
* guess_extension() (mimetypes.MimeTypes 的方法): MimeTypes 对象.
                                                             (line   43)
* guess_extension() (於 mimetypes 模組中): mimetypes --- 映射文件名到 MIME 类型.
                                                             (line   53)
* guess_scheme() (於 wsgiref.util 模組中): wsgiref util -- WSGI 环境工具.
                                                             (line   11)
* guess_type() (mimetypes.MimeTypes 的方法): MimeTypes 对象. (line   48)
* guess_type() (於 mimetypes 模組中):    mimetypes --- 映射文件名到 MIME 类型.
                                                             (line   21)
* GUI:                                   以 Tk 打造 GUI.     (line    6)
* gzip (模組):                           gzip --- 对 gzip 格式的支持.
                                                             (line    6)
* gzip command line option; –best:       命令行选项.         (line   14)
* gzip command line option; -d:          命令行选项.         (line   18)
* gzip command line option; –decompress: 命令行选项.         (line   18)
* gzip command line option; –fast:       命令行选项.         (line   10)
* gzip command line option; -h:          命令行选项.         (line   22)
* gzip command line option; –help:       命令行选项.         (line   22)
* gzip command line option; file:        命令行选项.         (line    6)
* GzipFile (gzip 中的類別):              gzip --- 对 gzip 格式的支持.
                                                             (line   64)
* halfdelay() (於 curses 模組中):        函数<4>.            (line  163)
* Handle (asyncio 中的類別):             回调处理.           (line    6)
* handle an exception:                   异常.               (line    6)
* handle() (http.server.BaseHTTPRequestHandler 的方法): http server --- HTTP 服务器.
                                                             (line  159)
* handle() (logging.Handler 的方法):     处理器对象.         (line   71)
* handle() (logging.handlers.QueueListener 的方法): QueueListener.
                                                             (line   53)
* handle() (logging.Logger 的方法):      记录器对象.         (line  242)
* handle() (logging.NullHandler 的方法): NullHandler.        (line   19)
* handle() (socketserver.BaseRequestHandler 的方法): 请求处理句柄对象.
                                                             (line   17)
* handle() (wsgiref.simple_server.WSGIRequestHandler 的方法): wsgiref simple_server -- 一个简单的 WSGI HTTP 服务器.
                                                             (line   92)
* handleError() (logging.Handler 的方法): 处理器对象.        (line   76)
* handleError() (logging.handlers.SocketHandler 的方法): SocketHandler.
                                                             (line   28)
* Handler (logging 中的類別):            处理器对象.         (line   10)
* handler() (於 cgitb 模組中):           cgitb --- 用于 CGI 脚本的回溯管理器.
                                                             (line   52)
* handle_accept() (asyncore.dispatcher 的方法): asyncore --- 异步套接字处理器.
                                                             (line  117)
* handle_accepted() (asyncore.dispatcher 的方法): asyncore --- 异步套接字处理器.
                                                             (line  125)
* handle_charref() (html.parser.HTMLParser 的方法): HTMLParser 方法.
                                                             (line   76)
* handle_close() (asyncore.dispatcher 的方法): asyncore --- 异步套接字处理器.
                                                             (line  108)
* handle_comment() (html.parser.HTMLParser 的方法): HTMLParser 方法.
                                                             (line   83)
* handle_connect() (asyncore.dispatcher 的方法): asyncore --- 异步套接字处理器.
                                                             (line  103)
* handle_data() (html.parser.HTMLParser 的方法): HTMLParser 方法.
                                                             (line   65)
* handle_decl() (html.parser.HTMLParser 的方法): HTMLParser 方法.
                                                             (line   94)
* handle_defect() (email.policy.Policy 的方法): email policy Policy 对象.
                                                             (line  176)
* handle_endtag() (html.parser.HTMLParser 的方法): HTMLParser 方法.
                                                             (line   52)
* handle_entityref() (html.parser.HTMLParser 的方法): HTMLParser 方法.
                                                             (line   70)
* handle_error() (asyncore.dispatcher 的方法): asyncore --- 异步套接字处理器.
                                                             (line  112)
* handle_error() (socketserver.BaseServer 的方法): Server 对象<2>.
                                                             (line  119)
* handle_expect_100() (http.server.BaseHTTPRequestHandler 的方法): http server --- HTTP 服务器.
                                                             (line  170)
* handle_expt() (asyncore.dispatcher 的方法): asyncore --- 异步套接字处理器.
                                                             (line   98)
* handle_one_request() (http.server.BaseHTTPRequestHandler 的方法): http server --- HTTP 服务器.
                                                             (line  165)
* handle_pi() (html.parser.HTMLParser 的方法): HTMLParser 方法.
                                                             (line  101)
* handle_read() (asyncore.dispatcher 的方法): asyncore --- 异步套接字处理器.
                                                             (line   84)
* handle_request() (socketserver.BaseServer 的方法): Server 对象<2>.
                                                             (line   18)
* handle_request() (xmlrpc.server.CGIXMLRPCRequestHandler 的方法): CGIXMLRPCRequestHandler.
                                                             (line   43)
* handle_startendtag() (html.parser.HTMLParser 的方法): HTMLParser 方法.
                                                             (line   58)
* handle_starttag() (html.parser.HTMLParser 的方法): HTMLParser 方法.
                                                             (line   38)
* handle_timeout() (socketserver.BaseServer 的方法): Server 对象<2>.
                                                             (line  128)
* handle_write() (asyncore.dispatcher 的方法): asyncore --- 异步套接字处理器.
                                                             (line   89)
* harmonic_mean() (於 statistics 模組中): 函式細節.          (line   73)
* hasattr() (內建函式):                  內建函式.           (line  585)
* hasAttribute() (xml.dom.Element 的方法): 元素对象<2>.      (line   21)
* hasAttributeNS() (xml.dom.Element 的方法): 元素对象<2>.    (line   25)
* hasAttributes() (xml.dom.Node 的方法): 节点对象.           (line   81)
* hasChildNodes() (xml.dom.Node 的方法): 节点对象.           (line   85)
* hascompare (於 dis 模組中):            操作码集合.         (line   46)
* hasconst (於 dis 模組中):              操作码集合.         (line   20)
* hasFeature() (xml.dom.DOMImplementation 的方法): DOMImplementation 对象.
                                                             (line   10)
* hasfree (於 dis 模組中):               操作码集合.         (line   24)
* hash character:                        注释.               (line    6)
* hash() (內建函式):                     內建函式.           (line  591)
* hash-based pyc（雜湊架構的 pyc）:      術語表.             (line  513)
* hash.block_size (於 hashlib 模組中):   哈希算法.           (line   96)
* hash.digest_size (於 hashlib 模組中):  哈希算法.           (line   92)
* hashable:                              字典显示.           (line   29)
* Hashable (collections.abc 中的類別):   容器抽象基类.       (line  108)
* Hashable (typing 中的類別):            collections abc 对应的其他类型.
                                                             (line   53)
* hashable（可雜湊的）:                  術語表.             (line  518)
* hasHandlers() (logging.Logger 的方法): 记录器对象.         (line  255)
* hashfunc (C 型態):                     Slot Type typedefs. (line   76)
* hashlib (模組):                        hashlib --- 安全哈希与消息摘要.
                                                             (line    6)
* hash_info (於 sys 模組中):             sys --- 系统相关的参数和函数.
                                                             (line  698)
* hasjabs (於 dis 模組中):               操作码集合.         (line   38)
* hasjrel (於 dis 模組中):               操作码集合.         (line   34)
* haslocal (於 dis 模組中):              操作码集合.         (line   42)
* hasname (於 dis 模組中):               操作码集合.         (line   30)
* HAS_ALPN (於 ssl 模組中):              常量<3>.            (line  320)
* has_children() (symtable.SymbolTable 的方法): 符号表的查看.
                                                             (line   37)
* has_colors() (於 curses 模組中):       函数<4>.            (line  143)
* has_dualstack_ipv6() (於 socket 模組中): 创建套接字.       (line  125)
* HAS_ECDH (於 ssl 模組中):              常量<3>.            (line  334)
* has_extn() (smtplib.SMTP 的方法):      SMTP 对象.          (line   71)
* has_function() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  211)
* has_header() (csv.Sniffer 的方法):     模块内容<3>.        (line  201)
* has_header() (urllib.request.Request 的方法): Request 对象.
                                                             (line   82)
* has_ic() (於 curses 模組中):           函数<4>.            (line  147)
* has_il() (於 curses 模組中):           函数<4>.            (line  152)
* has_ipv6 (於 socket 模組中):           常数<6>.            (line  226)
* has_key (2to3 fixer):                  修复器.             (line  113)
* has_key() (於 curses 模組中):          函数<4>.            (line  158)
* has_location (importlib.machinery.ModuleSpec 的屬性): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  364)
* HAS_NEVER_CHECK_COMMON_NAME (於 ssl 模組中): 常量<3>.      (line  327)
* has_nonstandard_attr() (http.cookiejar.Cookie 的方法): Cookie 对象<2>.
                                                             (line   88)
* HAS_NPN (於 ssl 模組中):               常量<3>.            (line  348)
* has_option() (configparser.ConfigParser 的方法): ConfigParser 对象.
                                                             (line   91)
* has_option() (optparse.OptionParser 的方法): Querying and manipulating your option parser.
                                                             (line   42)
* has_section() (configparser.ConfigParser 的方法): ConfigParser 对象.
                                                             (line   82)
* HAS_SNI (於 ssl 模組中):               常量<3>.            (line  341)
* HAS_SSLv2 (於 ssl 模組中):             常量<3>.            (line  356)
* HAS_SSLv3 (於 ssl 模組中):             常量<3>.            (line  362)
* has_ticket (ssl.SSLSession 的屬性):    SSL 会话.           (line   20)
* HAS_TLSv1 (於 ssl 模組中):             常量<3>.            (line  368)
* HAS_TLSv1_1 (於 ssl 模組中):           常量<3>.            (line  374)
* HAS_TLSv1_2 (於 ssl 模組中):           常量<3>.            (line  380)
* HAS_TLSv1_3 (於 ssl 模組中):           常量<3>.            (line  386)
* HAVE_ARGUMENT (opcode):                Python字节码说明.   (line  762)
* HAVE_CONTEXTVAR (於 decimal 模組中):   常数<3>.            (line   30)
* HAVE_DOCSTRINGS (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  192)
* HAVE_THREADS (於 decimal 模組中):      常数<3>.            (line   24)
* HCI_DATA_DIR (於 socket 模組中):       常数<6>.            (line  237)
* HCI_FILTER (於 socket 模組中):         常数<6>.            (line  237)
* HCI_TIME_STAMP (於 socket 模組中):     常数<6>.            (line  237)
* head() (nntplib.NNTP 的方法):          方法<3>.            (line  238)
* Header (email.header 中的類別):        email header 国际化标头.
                                                             (line   49)
* HeaderError:                           tarfile --- 读写tar归档文件.
                                                             (line  189)
* HeaderParseError:                      email errors 异常和缺陷类.
                                                             (line   23)
* HeaderParser (email.parser 中的類別):  Parser API.         (line   93)
* HeaderRegistry (email.headerregistry 中的類別): email headerregistry 自定义标头对象.
                                                             (line  248)
* headers (http.client.HTTPResponse 的屬性): HTTPResponse 对象.
                                                             (line   50)
* headers (http.server.BaseHTTPRequestHandler 的屬性): http server --- HTTP 服务器.
                                                             (line   90)
* headers (urllib.error.HTTPError 的屬性): urllib error --- urllib request 引发的异常类.
                                                             (line   44)
* headers (urllib.response.addinfourl 的屬性): urllib response --- urllib 使用的 Response 类.
                                                             (line   17)
* Headers (wsgiref.headers 中的類別):    wsgiref headers -- WSGI 响应标头工具.
                                                             (line    9)
* headers (xmlrpc.client.ProtocolError 的屬性): ProtocolError 对象.
                                                             (line   24)
* header_encode() (email.charset.Charset 的方法): email charset 表示字符集.
                                                             (line  105)
* header_encode_lines() (email.charset.Charset 的方法): email charset 表示字符集.
                                                             (line  112)
* header_encoding (email.charset.Charset 的屬性): email charset 表示字符集.
                                                             (line   52)
* header_factory (email.policy.EmailPolicy 的屬性): email policy Policy 对象.
                                                             (line  315)
* header_fetch_parse() (email.policy.Compat32 的方法): email policy Policy 对象.
                                                             (line  466)
* header_fetch_parse() (email.policy.EmailPolicy 的方法): email policy Policy 对象.
                                                             (line  356)
* header_fetch_parse() (email.policy.Policy 的方法): email policy Policy 对象.
                                                             (line  242)
* header_items() (urllib.request.Request 的方法): Request 对象.
                                                             (line  111)
* header_max_count() (email.policy.EmailPolicy 的方法): email policy Policy 对象.
                                                             (line  337)
* header_max_count() (email.policy.Policy 的方法): email policy Policy 对象.
                                                             (line  197)
* header_offset (zipfile.ZipInfo 的屬性): ZipInfo 对象.      (line  121)
* header_source_parse() (email.policy.Compat32 的方法): email policy Policy 对象.
                                                             (line  456)
* header_source_parse() (email.policy.EmailPolicy 的方法): email policy Policy 对象.
                                                             (line  342)
* header_source_parse() (email.policy.Policy 的方法): email policy Policy 对象.
                                                             (line  213)
* header_store_parse() (email.policy.Compat32 的方法): email policy Policy 对象.
                                                             (line  462)
* header_store_parse() (email.policy.EmailPolicy 的方法): email policy Policy 对象.
                                                             (line  348)
* header_store_parse() (email.policy.Policy 的方法): email policy Policy 对象.
                                                             (line  229)
* heading() (tkinter.ttk.Treeview 的方法): ttk Treeview.     (line   91)
* heading() (於 turtle 模組中):          获取海龟的状态.     (line   55)
* heapify() (於 heapq 模組中):           heapq --- 堆積佇列 heap queue 演算法.
                                                             (line   48)
* heapmin() (於 msvcrt 模組中):          其他函数.           (line    6)
* heappop() (於 heapq 模組中):           heapq --- 堆積佇列 heap queue 演算法.
                                                             (line   36)
* heappush() (於 heapq 模組中):          heapq --- 堆積佇列 heap queue 演算法.
                                                             (line   32)
* heappushpop() (於 heapq 模組中):       heapq --- 堆積佇列 heap queue 演算法.
                                                             (line   42)
* heapq (模組):                          heapq --- 堆積佇列 heap queue 演算法.
                                                             (line    6)
* heapreplace() (於 heapq 模組中):       heapq --- 堆積佇列 heap queue 演算法.
                                                             (line   52)
* helo() (smtplib.SMTP 的方法):          SMTP 对象.          (line   41)
* help (optparse.Option 的屬性):         Option attributes.  (line   72)
* help (pdb command):                    调试器命令.         (line   34)
* help() (nntplib.NNTP 的方法):          方法<3>.            (line  189)
* help() (內建函式):                     內建函式.           (line  601)
* help; online:                          pydoc --- 文档生成器和在线帮助系统.
                                                             (line    8)
* herror:                                异常<11>.           (line   12)
* hex (uuid.UUID 的屬性):                uuid --- RFC 4122 定义的UUID对象.
                                                             (line  115)
* hex() (bytearray 的方法):              bytearray 对象.     (line   45)
* hex() (bytes 的方法):                  bytes 对象.         (line   64)
* hex() (float 的方法):                  浮点类型的附加方法. (line   28)
* hex() (memoryview 的方法):             内存视图.           (line  166)
* hex() (內建函式):                      內建函式.           (line  617)
* hexadecimal literal:                   数值字面值.         (line    6)
* hexadecimal; literals:                 数字类型 --- int float complex.
                                                             (line   14)
* hexbin() (於 binhex 模組中):           binhex --- 对binhex4文件进行编码和解码.
                                                             (line   23)
* hexdigest() (hashlib.hash 的方法):     哈希算法.           (line  127)
* hexdigest() (hashlib.shake 的方法):    SHAKE 可变长度摘要. (line   15)
* hexdigest() (hmac.HMAC 的方法):        hmac --- 基于密钥的消息验证.
                                                             (line   59)
* hexdigits (於 string 模組中):          字符串常量.         (line   27)
* hexlify() (於 binascii 模組中):        binascii --- 二进制和 ASCII 码互转.
                                                             (line  119)
* hexversion (於 sys 模組中):            sys --- 系统相关的参数和函数.
                                                             (line  735)
* hidden() (curses.panel.Panel 的方法):  Panel 对象.         (line   24)
* hide() (curses.panel.Panel 的方法):    Panel 对象.         (line   28)
* hide() (tkinter.ttk.Notebook 的方法):  ttk Notebook.       (line   21)
* hideturtle() (於 turtle 模組中):       可见性.             (line    6)
* hide_cookie2 (http.cookiejar.CookiePolicy 的屬性): CookiePolicy 对象.
                                                             (line   64)
* HierarchyRequestErr:                   异常<15>.           (line   23)
* HIGHEST_PROTOCOL (於 pickle 模組中):   模块接口.           (line   13)
* HIGH_PRIORITY_CLASS (於 subprocess 模組中): Windows 常数.  (line   60)
* HKEY_CLASSES_ROOT (於 winreg 模組中):  HKEY_* 常量.        (line    6)
* HKEY_CURRENT_CONFIG (於 winreg 模組中): HKEY_* 常量.       (line   31)
* HKEY_CURRENT_USER (於 winreg 模組中):  HKEY_* 常量.        (line   11)
* HKEY_DYN_DATA (於 winreg 模組中):      HKEY_* 常量.        (line   35)
* HKEY_LOCAL_MACHINE (於 winreg 模組中): HKEY_* 常量.        (line   16)
* HKEY_PERFORMANCE_DATA (於 winreg 模組中): HKEY_* 常量.     (line   26)
* HKEY_USERS (於 winreg 模組中):         HKEY_* 常量.        (line   21)
* hline() (curses.window 的方法):        Window 对象.        (line  244)
* HList (tkinter.tix 中的類別):          Hierarchical ListBox.
                                                             (line    6)
* hls_to_rgb() (於 colorsys 模組中):     colorsys --- 颜色系统间的转换.
                                                             (line   36)
* hmac (模組):                           hmac --- 基于密钥的消息验证.
                                                             (line    6)
* HOME:                                  os path.            (line   14)
* HOME <1>:                              更改的Python API.   (line  103)
* HOME <2>:                              Windows<17>.        (line   15)
* HOME <3>:                              Windows<17>.        (line   18)
* HOME <4>:                              os path --- 常用路径操作.
                                                             (line  124)
* HOME <5>:                              os path --- 常用路径操作.
                                                             (line  136)
* HOME <6>:                              distutils util --- Miscellaneous other utility functions.
                                                             (line   97)
* HOME <7>:                              Location and names of config files.
                                                             (line   50)
* HOME <8>:                              Location and names of config files.
                                                             (line   67)
* home() (pathlib.Path 的類別成員):      方法<2>.            (line   23)
* home() (於 turtle 模組中):             海龟动作.           (line  154)
* HOMEDRIVE:                             os path --- 常用路径操作.
                                                             (line  129)
* HOMEDRIVE <1>:                         Location and names of config files.
                                                             (line   68)
* HOMEPATH:                              os path --- 常用路径操作.
                                                             (line  128)
* HOMEPATH <1>:                          Location and names of config files.
                                                             (line   68)
* hooks; import:                         导入钩子.           (line    6)
* hooks; meta:                           导入钩子.           (line    6)
* hooks; path:                           导入钩子.           (line    6)
* hook_compressed() (於 fileinput 模組中): fileinput --- 迭代来自多个输入流的行.
                                                             (line  153)
* hook_encoded() (於 fileinput 模組中):  fileinput --- 迭代来自多个输入流的行.
                                                             (line  163)
* host (urllib.request.Request 的屬性):  Request 对象.       (line   24)
* hostmask (ipaddress.IPv4Network 的屬性): 网络对象.         (line   81)
* hostmask (ipaddress.IPv6Network 的屬性): 网络对象.         (line  279)
* hostname_checks_common_name (ssl.SSLContext 的屬性): SSL 上下文.
                                                             (line  550)
* hosts (netrc.netrc 的屬性):            netrc 对象.         (line   22)
* hosts() (ipaddress.IPv4Network 的方法): 网络对象.          (line  116)
* hosts() (ipaddress.IPv6Network 的方法): 网络对象.          (line  297)
* hour (datetime.datetime 的屬性):       datetime 对象.      (line  255)
* hour (datetime.time 的屬性):           time 对象.          (line   46)
* HRESULT (ctypes 中的類別):             基础数据类型<2>.    (line  184)
* hStdError (subprocess.STARTUPINFO 的屬性): Windows Popen 助手.
                                                             (line   38)
* hStdInput (subprocess.STARTUPINFO 的屬性): Windows Popen 助手.
                                                             (line   25)
* hStdOutput (subprocess.STARTUPINFO 的屬性): Windows Popen 助手.
                                                             (line   32)
* hsv_to_rgb() (於 colorsys 模組中):     colorsys --- 颜色系统间的转换.
                                                             (line   44)
* ht() (於 turtle 模組中):               可见性.             (line    6)
* HTML:                                  html parser --- 简单的 HTML 和 XHTML 解析器.
                                                             (line    8)
* HTML <1>:                              urllib request 的限制.
                                                             (line   24)
* html (模組):                           html --- 超文本标记语言支持.
                                                             (line    6)
* html() (於 cgitb 模組中):              cgitb --- 用于 CGI 脚本的回溯管理器.
                                                             (line   45)
* html.entities (模組):                  html entities --- HTML 一般实体的定义.
                                                             (line    6)
* html.parser (模組):                    html parser --- 简单的 HTML 和 XHTML 解析器.
                                                             (line    6)
* html5 (於 html.entities 模組中):       html entities --- HTML 一般实体的定义.
                                                             (line   13)
* HTMLCalendar (calendar 中的類別):      calendar --- 日历相关函数.
                                                             (line  134)
* HtmlDiff (difflib 中的類別):           difflib --- 计算差异的辅助工具.
                                                             (line   66)
* HTMLParser (html.parser 中的類別):     html parser --- 简单的 HTML 和 XHTML 解析器.
                                                             (line   13)
* htonl() (於 socket 模組中):            其他功能.           (line  170)
* htons() (於 socket 模組中):            其他功能.           (line  175)
* HTTP (於 email.policy 模組中):         email policy Policy 对象.
                                                             (line  409)
* http (模組):                           http --- HTTP 模块. (line    6)
* http.client (模組):                    http client --- HTTP 协议客户端.
                                                             (line    6)
* http.cookiejar (模組):                 http cookiejar —— HTTP 客户端的 Cookie 处理.
                                                             (line    6)
* http.cookies (模組):                   http cookies --- HTTP状态管理.
                                                             (line    6)
* http.server (模組):                    http server --- HTTP 服务器.
                                                             (line    6)
* HTTP; http (standard module):          http --- HTTP 模块. (line    8)
* HTTP; http.client (standard module):   http client --- HTTP 协议客户端.
                                                             (line    8)
* HTTP; protocol:                        cgi --- 通用网关接口支持.
                                                             (line    8)
* HTTP; protocol <1>:                    urllib request 的限制.
                                                             (line    6)
* HTTP; protocol <2>:                    urllib request 的限制.
                                                             (line   24)
* HTTP; protocol <3>:                    http --- HTTP 模块. (line    8)
* HTTP; protocol <4>:                    http client --- HTTP 协议客户端.
                                                             (line    8)
* HTTP; protocol <5>:                    http server --- HTTP 服务器.
                                                             (line    8)
* HTTPBasicAuthHandler (urllib.request 中的類別): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  292)
* HTTPConnection (http.client 中的類別): http client --- HTTP 协议客户端.
                                                             (line   23)
* HTTPCookieProcessor (urllib.request 中的類別): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  234)
* httpd:                                 http server --- HTTP 服务器.
                                                             (line    8)
* HTTPDefaultErrorHandler (urllib.request 中的類別): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  225)
* HTTPDigestAuthHandler (urllib.request 中的類別): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  311)
* HTTPError:                             urllib error --- urllib request 引发的异常类.
                                                             (line   27)
* HTTPErrorProcessor (urllib.request 中的類別): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  364)
* HTTPException:                         http client --- HTTP 协议客户端.
                                                             (line  110)
* HTTPHandler (logging.handlers 中的類別): HTTPHandler.      (line    9)
* HTTPHandler (urllib.request 中的類別): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  330)
* HTTPPasswordMgr (urllib.request 中的類別): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  258)
* HTTPPasswordMgrWithDefaultRealm (urllib.request 中的類別): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  262)
* HTTPPasswordMgrWithPriorAuth (urllib.request 中的類別): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  267)
* HTTPRedirectHandler (urllib.request 中的類別): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  230)
* HTTPResponse (http.client 中的類別):   http client --- HTTP 协议客户端.
                                                             (line   83)
* HTTPSConnection (http.client 中的類別): http client --- HTTP 协议客户端.
                                                             (line   49)
* HTTPServer (http.server 中的類別):     http server --- HTTP 服务器.
                                                             (line   24)
* HTTPSHandler (urllib.request 中的類別): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  334)
* HTTPStatus (http 中的類別):            http --- HTTP 模块. (line   26)
* https_open() (urllib.request.HTTPSHandler 的方法): HTTPSHandler 对象.
                                                             (line    6)
* HTTPS_PORT (於 http.client 模組中):    http client --- HTTP 协议客户端.
                                                             (line  180)
* https_response() (urllib.request.HTTPErrorProcessor 的方法): HTTPErrorProcessor 对象.
                                                             (line   17)
* http_error_301() (urllib.request.HTTPRedirectHandler 的方法): HTTPRedirectHandler 对象.
                                                             (line   28)
* http_error_302() (urllib.request.HTTPRedirectHandler 的方法): HTTPRedirectHandler 对象.
                                                             (line   34)
* http_error_303() (urllib.request.HTTPRedirectHandler 的方法): HTTPRedirectHandler 对象.
                                                             (line   40)
* http_error_307() (urllib.request.HTTPRedirectHandler 的方法): HTTPRedirectHandler 对象.
                                                             (line   46)
* http_error_401() (urllib.request.HTTPBasicAuthHandler 的方法): HTTPBasicAuthHandler 对象.
                                                             (line    6)
* http_error_401() (urllib.request.HTTPDigestAuthHandler 的方法): HTTPDigestAuthHandler 对象.
                                                             (line    6)
* http_error_407() (urllib.request.ProxyBasicAuthHandler 的方法): ProxyBasicAuthHandler 对象.
                                                             (line    6)
* http_error_407() (urllib.request.ProxyDigestAuthHandler 的方法): ProxyDigestAuthHandler 对象.
                                                             (line    6)
* http_error_auth_reqed() (urllib.request.AbstractBasicAuthHandler 的方法): AbstractBasicAuthHandler 对象.
                                                             (line    6)
* http_error_auth_reqed() (urllib.request.AbstractDigestAuthHandler 的方法): AbstractDigestAuthHandler 对象.
                                                             (line    6)
* http_error_default() (urllib.request.BaseHandler 的方法): BaseHandler 对象.
                                                             (line   58)
* http_open() (urllib.request.HTTPHandler 的方法): HTTPHandler 对象.
                                                             (line    6)
* HTTP_PORT (於 http.client 模組中):     http client --- HTTP 协议客户端.
                                                             (line  176)
* http_proxy:                            urllib request --- 用于打开 URL 的可扩展库.
                                                             (line   67)
* http_proxy <1>:                        示例<33>.           (line   89)
* http_proxy <2>:                        基本认证.           (line   56)
* http_response() (urllib.request.HTTPErrorProcessor 的方法): HTTPErrorProcessor 对象.
                                                             (line    6)
* http_version (wsgiref.handlers.BaseHandler 的屬性): wsgiref handlers -- 服务器/网关基类.
                                                             (line  245)
* hypot() (於 math 模組中):              三角函数.           (line   43)
* I (於 re 模組中):                      模块内容.           (line   51)
* I/O control; buffering:                內建函式.           (line 1030)
* I/O control; buffering <1>:            套接字对象.         (line  171)
* iadd() (於 operator 模組中):           原地运算符.         (line   33)
* iand() (於 operator 模組中):           原地运算符.         (line   38)
* iconcat() (於 operator 模組中):        原地运算符.         (line   43)
* id (ssl.SSLSession 的屬性):            SSL 会话.           (line   12)
* id() (unittest.TestCase 的方法):       测试用例.           (line  720)
* id() (內建函式):                       內建函式.           (line  646)
* idcok() (curses.window 的方法):        Window 对象.        (line  250)
* ident (select.kevent 的屬性):          Kevent 对象.        (line    8)
* ident (threading.Thread 的屬性):       线程对象.           (line  124)
* identchars (cmd.Cmd 的屬性):           Cmd 对象.           (line   99)
* identifier:                            标识符和关键字.     (line    6)
* identifier <1>:                        标识符（名称）.     (line    6)
* identify() (tkinter.ttk.Notebook 的方法): ttk Notebook.    (line   28)
* identify() (tkinter.ttk.Treeview 的方法): ttk Treeview.    (line  122)
* identify() (tkinter.ttk.Widget 的方法): ttk Widget.        (line   11)
* identify_column() (tkinter.ttk.Treeview 的方法): ttk Treeview.
                                                             (line  131)
* identify_element() (tkinter.ttk.Treeview 的方法): ttk Treeview.
                                                             (line  159)
* identify_region() (tkinter.ttk.Treeview 的方法): ttk Treeview.
                                                             (line  137)
* identify_row() (tkinter.ttk.Treeview 的方法): ttk Treeview.
                                                             (line  127)
* identity of an object:                 对象、值与类型.     (line   10)
* identity; test:                        成员检测运算.       (line   32)
* idioms (2to3 fixer):                   修复器.             (line  117)
* IDLE:                                  IDLE<51>.           (line    8)
* IDLE <1>:                              術語表.             (line  535)
* IDLESTARTUP:                           IDLE<24>.           (line  174)
* IDLESTARTUP <1>:                       IDLE<28>.           (line    9)
* IDLESTARTUP <2>:                       IDLE<34>.           (line    9)
* IDLESTARTUP <3>:                       启动和代码执行.     (line    7)
* IDLE_PRIORITY_CLASS (於 subprocess 模組中): Windows 常数.  (line   67)
* idlok() (curses.window 的方法):        Window 对象.        (line  256)
* If (ast 中的類別):                     Control flow.       (line    9)
* if; conditional expression:            条件表达式.         (line    6)
* if; in comprehensions:                 列表、集合与字典的显示.
                                                             (line   13)
* IfExp (ast 中的類別):                  表达式<2>.          (line  158)
* ifloordiv() (於 operator 模組中):      原地运算符.         (line   48)
* if_indextoname() (於 socket 模組中):   其他功能.           (line  339)
* if_nameindex() (於 socket 模組中):     其他功能.           (line  298)
* if_nametoindex() (於 socket 模組中):   其他功能.           (line  323)
* iglob() (於 glob 模組中):              glob --- Unix 风格路径名模式扩展.
                                                             (line   49)
* ignorableWhitespace() (xml.sax.handler.ContentHandler 的方法): ContentHandler 对象.
                                                             (line  126)
* ignore (pdb command):                  调试器命令.         (line   91)
* IGNORECASE (於 re 模組中):             模块内容.           (line   51)
* ignore_errors() (於 codecs 模組中):    错误处理方案.       (line  116)
* IGNORE_EXCEPTION_DETAIL (於 doctest 模組中): 选项标记.     (line   48)
* ignore_patterns() (於 shutil 模組中):  目录和文件操作.     (line  154)
* ihave() (nntplib.NNTP 的方法):         方法<3>.            (line  259)
* IISCGIHandler (wsgiref.handlers 中的類別): wsgiref handlers -- 服务器/网关基类.
                                                             (line   21)
* ilshift() (於 operator 模組中):        原地运算符.         (line   53)
* imag (numbers.Complex 的屬性):         数字的层次.         (line   18)
* imaginary literal:                     数值字面值.         (line    6)
* imap() (multiprocessing.pool.Pool 的方法): 进程池.         (line  100)
* IMAP4 (imaplib 中的類別):              imaplib --- IMAP4 协议客户端.
                                                             (line   17)
* IMAP4.abort:                           imaplib --- IMAP4 协议客户端.
                                                             (line   44)
* IMAP4.error:                           imaplib --- IMAP4 协议客户端.
                                                             (line   40)
* IMAP4.readonly:                        imaplib --- IMAP4 协议客户端.
                                                             (line   50)
* IMAP4; protocol:                       imaplib --- IMAP4 协议客户端.
                                                             (line    8)
* IMAP4_SSL (imaplib 中的類別):          imaplib --- IMAP4 协议客户端.
                                                             (line   58)
* IMAP4_SSL; protocol:                   imaplib --- IMAP4 协议客户端.
                                                             (line    8)
* IMAP4_stream (imaplib 中的類別):       imaplib --- IMAP4 协议客户端.
                                                             (line   93)
* IMAP4_stream; protocol:                imaplib --- IMAP4 协议客户端.
                                                             (line    8)
* imaplib (模組):                        imaplib --- IMAP4 协议客户端.
                                                             (line    6)
* imap_unordered() (multiprocessing.pool.Pool 的方法): 进程池.
                                                             (line  113)
* imatmul() (於 operator 模組中):        原地运算符.         (line   68)
* imghdr (模組):                         imghdr --- 推测图像类型.
                                                             (line    6)
* immedok() (curses.window 的方法):      Window 对象.        (line  261)
* immutable object:                      对象、值与类型.     (line   10)
* immutable; data; type:                 字面值<2>.          (line   15)
* immutable; object:                     字面值<2>.          (line   15)
* immutable; object <1>:                 字典显示.           (line   29)
* immutable; sequence; types:            不可变序列类型.     (line    6)
* immutable（不可變物件）:               術語表.             (line  541)
* imod() (於 operator 模組中):           原地运算符.         (line   58)
* imp (模組):                            imp —— 由代码内部访问 import 。.
                                                             (line    6)
* ImpImporter (pkgutil 中的類別):        pkgutil --- 包扩展工具.
                                                             (line   52)
* implementation (於 sys 模組中):        sys --- 系统相关的参数和函数.
                                                             (line  755)
* ImpLoader (pkgutil 中的類別):          pkgutil --- 包扩展工具.
                                                             (line   68)
* impl_detail() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  701)
* import (2to3 fixer):                   修复器.             (line  132)
* Import (ast 中的類別):                 Imports.            (line    6)
* import hooks:                          导入钩子.           (line    6)
* import machinery:                      导入系统.           (line    6)
* import path（匯入路徑）:               術語表.             (line  548)
* ImportError:                           具体异常.           (line   35)
* importer（匯入器）:                    術語表.             (line  561)
* ImportFrom (ast 中的類別):             Imports.            (line   21)
* importing（匯入）:                     術語表.             (line  556)
* importlib (模組):                      importlib --- import 的实现.
                                                             (line    6)
* importlib.abc (模組):                  importlib abc —— 关于导入的抽象基类.
                                                             (line    6)
* importlib.machinery (模組):            importlib machinery —— 导入器和路径钩子函数。.
                                                             (line    6)
* importlib.metadata (模組):             Using importlib metadata.
                                                             (line    6)
* importlib.resources (模組):            importlib resources -- 资源.
                                                             (line    6)
* importlib.util (模組):                 importlib util —— 导入器的工具程序代码.
                                                             (line    6)
* imports (2to3 fixer):                  修复器.             (line  136)
* imports2 (2to3 fixer):                 修复器.             (line  140)
* ImportWarning:                         警告.               (line   51)
* import_fresh_module() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  797)
* IMPORT_FROM (opcode):                  Python字节码说明.   (line  540)
* import_module() (於 importlib 模組中): 函数<11>.           (line   14)
* import_module() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  782)
* IMPORT_NAME (opcode):                  Python字节码说明.   (line  533)
* IMPORT_STAR (opcode):                  Python字节码说明.   (line  345)
* ImproperConnectionState:               http client --- HTTP 协议客户端.
                                                             (line  139)
* imul() (於 operator 模組中):           原地运算符.         (line   63)
* In (ast 中的類別):                     表达式<2>.          (line  109)
* inch() (curses.window 的方法):         Window 对象.        (line  267)
* inclusive (tracemalloc.DomainFilter 的屬性): 域过滤器.     (line   12)
* inclusive (tracemalloc.Filter 的屬性): 过滤器<2>.          (line   38)
* inclusive; or:                         二元位运算.         (line   20)
* Incomplete:                            binascii --- 二进制和 ASCII 码互转.
                                                             (line  159)
* IncompleteRead:                        http client --- HTTP 协议客户端.
                                                             (line  135)
* IncompleteReadError:                   异常<9>.            (line   38)
* IncrementalDecoder (codecs 中的類別):  IncrementalDecoder 对象.
                                                             (line   10)
* incrementaldecoder (codecs.CodecInfo 的屬性): codecs --- 编解码器注册和相关基类.
                                                             (line   68)
* IncrementalEncoder (codecs 中的類別):  IncrementalEncoder 对象.
                                                             (line   10)
* incrementalencoder (codecs.CodecInfo 的屬性): codecs --- 编解码器注册和相关基类.
                                                             (line   68)
* IncrementalNewlineDecoder (io 中的類別): 文本 I/O<2>.      (line  204)
* IncrementalParser (xml.sax.xmlreader 中的類別): xml sax xmlreader --- 用于 XML 解析器的接口.
                                                             (line   18)
* increment_lineno() (於 ast 模組中):    ast 中的辅助函数.   (line  120)
* incr_item():                           异常<17>.           (line   76)
* incr_item() <1>:                       异常<17>.           (line  121)
* indent (doctest.Example 的屬性):       Example 对象.       (line   39)
* INDENT (於 token 模組中):              token --- 与Python解析树一起使用的常量.
                                                             (line   46)
* INDENT token:                          缩进.               (line   23)
* indent() (於 textwrap 模組中):         textwrap --- 文本自动换行与填充.
                                                             (line   92)
* indent() (於 xml.etree.ElementTree 模組中): 函数<7>.       (line  103)
* indentation:                           缩进.               (line    6)
* IndentationError:                      具体异常.           (line  240)
* index operation:                       标准类型层级结构.   (line   98)
* index() (array.array 的方法):          array --- 高效率的數值型態陣列.
                                                             (line  164)
* index() (bytearray 的方法):            bytes 和 bytearray 操作.
                                                             (line  129)
* index() (bytes 的方法):                bytes 和 bytearray 操作.
                                                             (line  129)
* index() (collections.deque 的方法):    deque 对象.         (line   60)
* index() (multiprocessing.shared_memory.ShareableList 的方法): multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line  229)
* index() (sequence method):             通用序列操作.       (line   17)
* index() (str 的方法):                  字符串的方法<2>.    (line  145)
* index() (tkinter.ttk.Notebook 的方法): ttk Notebook.       (line   33)
* index() (tkinter.ttk.Treeview 的方法): ttk Treeview.       (line  165)
* index() (於 operator 模組中):          operator --- 标准运算符替代函数.
                                                             (line   82)
* IndexError:                            具体异常.           (line   53)
* indexOf() (於 operator 模組中):        operator --- 标准运算符替代函数.
                                                             (line  182)
* IndexSizeErr:                          异常<15>.           (line   27)
* indices() (slice 的方法):              标准类型层级结构.   (line  629)
* inet_aton() (於 socket 模組中):        其他功能.           (line  184)
* inet_ntoa() (於 socket 模組中):        其他功能.           (line  200)
* inet_ntop() (於 socket 模組中):        其他功能.           (line  229)
* inet_pton() (於 socket 模組中):        其他功能.           (line  213)
* Inexact (decimal 中的類別):            信号.               (line   36)
* inf (於 cmath 模組中):                 常数<2>.            (line   20)
* inf (於 math 模組中):                  常数.               (line   22)
* infile (shlex.shlex 的屬性):           shlex 对象.         (line  115)
* Infinity:                              內建函式.           (line  492)
* infj (於 cmath 模組中):                常数<2>.            (line   26)
* info() (dis.Bytecode 的方法):          字节码分析.         (line   46)
* info() (gettext.NullTranslations 的方法): NullTranslations 类.
                                                             (line   66)
* info() (http.client.HTTPResponse 的方法): HTTPResponse 对象.
                                                             (line   76)
* info() (logging.Logger 的方法):        记录器对象.         (line  174)
* info() (urllib.response.addinfourl 的方法): urllib response --- urllib 使用的 Response 类.
                                                             (line   31)
* info() (於 logging 模組中):            模块级函数.         (line   95)
* infolist() (zipfile.ZipFile 的方法):   ZipFile 对象.       (line   85)
* inheritance:                           类定义.             (line    6)
* ini file:                              configparser --- 配置文件解析器.
                                                             (line    8)
* init() (於 mimetypes 模組中):          mimetypes --- 映射文件名到 MIME 类型.
                                                             (line   65)
* inited (於 mimetypes 模組中):          mimetypes --- 映射文件名到 MIME 类型.
                                                             (line   97)
* initgroups() (於 os 模組中):           进程参数.           (line  280)
* initialize_options() (distutils.cmd.Command 的方法): Creating a new Distutils command.
                                                             (line   21)
* initial_indent (textwrap.TextWrapper 的屬性): textwrap --- 文本自动换行与填充.
                                                             (line  188)
* initproc (C 型態):                     Slot Type typedefs. (line   34)
* initscr() (於 curses 模組中):          函数<4>.            (line  188)
* init_color() (於 curses 模組中):       函数<4>.            (line  170)
* init_database() (於 msilib 模組中):    msilib --- Read and write Microsoft Installer files.
                                                             (line   60)
* init_pair() (於 curses 模組中):        函数<4>.            (line  179)
* inode() (os.DirEntry 的方法):          文件和目录.         (line  761)
* INPLACE_ADD (opcode):                  Python字节码说明.   (line  213)
* INPLACE_AND (opcode):                  Python字节码说明.   (line  229)
* INPLACE_FLOOR_DIVIDE (opcode):         Python字节码说明.   (line  201)
* INPLACE_LSHIFT (opcode):               Python字节码说明.   (line  221)
* INPLACE_MATRIX_MULTIPLY (opcode):      Python字节码说明.   (line  195)
* INPLACE_MODULO (opcode):               Python字节码说明.   (line  209)
* INPLACE_MULTIPLY (opcode):             Python字节码说明.   (line  191)
* INPLACE_OR (opcode):                   Python字节码说明.   (line  237)
* INPLACE_POWER (opcode):                Python字节码说明.   (line  187)
* INPLACE_RSHIFT (opcode):               Python字节码说明.   (line  225)
* INPLACE_SUBTRACT (opcode):             Python字节码说明.   (line  217)
* INPLACE_TRUE_DIVIDE (opcode):          Python字节码说明.   (line  205)
* INPLACE_XOR (opcode):                  Python字节码说明.   (line  233)
* input:                                 表达式输入.         (line    6)
* input (2to3 fixer):                    修复器.             (line  145)
* input() (內建函式):                    內建函式.           (line  657)
* input() (於 fileinput 模組中):         fileinput --- 迭代来自多个输入流的行.
                                                             (line   46)
* InputOnly (tkinter.tix 中的類別):      Miscellaneous Widgets.
                                                             (line    6)
* InputSource (xml.sax.xmlreader 中的類別): xml sax xmlreader --- 用于 XML 解析器的接口.
                                                             (line   42)
* input_charset (email.charset.Charset 的屬性): email charset 表示字符集.
                                                             (line   46)
* input_codec (email.charset.Charset 的屬性): email charset 表示字符集.
                                                             (line   72)
* inquiry (C 型態):                      使对象类型支持循环垃圾回收.
                                                             (line  149)
* insch() (curses.window 的方法):        Window 对象.        (line  272)
* insdelln() (curses.window 的方法):     Window 对象.        (line  279)
* insert() (array.array 的方法):         array --- 高效率的數值型態陣列.
                                                             (line  168)
* insert() (collections.deque 的方法):   deque 对象.         (line   68)
* insert() (sequence method):            可变序列类型.       (line   14)
* insert() (tkinter.ttk.Notebook 的方法): ttk Notebook.      (line   38)
* insert() (tkinter.ttk.Treeview 的方法): ttk Treeview.      (line  169)
* insert() (xml.etree.ElementTree.Element 的方法): 元素对象. (line  110)
* insertBefore() (xml.dom.Node 的方法):  节点对象.           (line  104)
* insertln() (curses.window 的方法):     Window 对象.        (line  286)
* insert_text() (於 readline 模組中):    行缓冲区.           (line   12)
* insnstr() (curses.window 的方法):      Window 对象.        (line  290)
* insort() (於 bisect 模組中):           bisect --- 陣列二分演算法 Array bisection algorithm.
                                                             (line   47)
* insort_left() (於 bisect 模組中):      bisect --- 陣列二分演算法 Array bisection algorithm.
                                                             (line   40)
* insort_right() (於 bisect 模組中):     bisect --- 陣列二分演算法 Array bisection algorithm.
                                                             (line   47)
* inspect (模組):                        inspect --- 检查对象.
                                                             (line    6)
* inspect command line option; –details: 命令行界面<5>.      (line   13)
* InspectLoader (importlib.abc 中的類別): importlib abc —— 关于导入的抽象基类.
                                                             (line  324)
* insstr() (curses.window 的方法):       Window 对象.        (line  299)
* install() (gettext.NullTranslations 的方法): NullTranslations 类.
                                                             (line   88)
* install() (於 gettext 模組中):         基于类的 API.       (line   59)
* installHandler() (於 unittest 模組中): 信号处理.           (line   29)
* install_opener() (於 urllib.request 模組中): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line   94)
* install_scripts() (venv.EnvBuilder 的方法): API<2>.        (line  121)
* instance; call:                        调用.               (line  119)
* instate() (tkinter.ttk.Widget 的方法): ttk Widget.         (line   18)
* instr() (curses.window 的方法):        Window 对象.        (line  307)
* instream (shlex.shlex 的屬性):         shlex 对象.         (line  120)
* Instruction (dis 中的類別):            Python字节码说明.   (line    9)
* Instruction.arg (於 dis 模組中):       Python字节码说明.   (line   22)
* Instruction.argrepr (於 dis 模組中):   Python字节码说明.   (line   30)
* Instruction.argval (於 dis 模組中):    Python字节码说明.   (line   26)
* Instruction.is_jump_target (於 dis 模組中): Python字节码说明.
                                                             (line   42)
* Instruction.offset (於 dis 模組中):    Python字节码说明.   (line   34)
* Instruction.opcode (於 dis 模組中):    Python字节码说明.   (line   13)
* Instruction.opname (於 dis 模組中):    Python字节码说明.   (line   18)
* Instruction.starts_line (於 dis 模組中): Python字节码说明. (line   38)
* int (uuid.UUID 的屬性):                uuid --- RFC 4122 定义的UUID对象.
                                                             (line  119)
* int (內建類別):                        內建函式.           (line  676)
* Int2AP() (於 imaplib 模組中):          imaplib --- IMAP4 协议客户端.
                                                             (line  107)
* integer:                               标准类型层级结构.   (line  122)
* integer literal:                       数值字面值.         (line    6)
* integer; literals:                     数字类型 --- int float complex.
                                                             (line   14)
* integer; representation:               标准类型层级结构.   (line   79)
* Integral (numbers 中的類別):           数字的层次.         (line   53)
* Integrated Development Environment:    IDLE<51>.           (line    8)
* IntegrityError:                        异常<4>.            (line   18)
* Intel/DVI ADPCM:                       audioop --- 处理原始音频数据.
                                                             (line   15)
* IntEnum (enum 中的類別):               模块内容<2>.        (line   16)
* interact (pdb command):                调试器命令.         (line  229)
* interact() (code.InteractiveConsole 的方法): 交互式控制台对象.
                                                             (line    9)
* interact() (telnetlib.Telnet 的方法):  Telnet 对象.        (line  104)
* interact() (於 code 模組中):           code --- 解释器基类.
                                                             (line   27)
* interactive mode:                      完整的 Python 程序. (line   15)
* InteractiveConsole (code 中的類別):    code --- 解释器基类.
                                                             (line   21)
* InteractiveInterpreter (code 中的類別): code --- 解释器基类.
                                                             (line   13)
* interactive（互動的）:                 術語表.             (line  566)
* intern (2to3 fixer):                   修复器.             (line  149)
* intern() (於 sys 模組中):              sys --- 系统相关的参数和函数.
                                                             (line  820)
* internal type:                         标准类型层级结构.   (line  503)
* Internaldate2tuple() (於 imaplib 模組中): imaplib --- IMAP4 协议客户端.
                                                             (line  101)
* internalSubset (xml.dom.DocumentType 的屬性): 文档类型对象.
                                                             (line   22)
* internal_attr (zipfile.ZipInfo 的屬性): ZipInfo 对象.      (line  113)
* Internet:                              互联网协议和支持.   (line    6)
* INTERNET_TIMEOUT (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  100)
* interpolated string literal:           字符串字面值合并.   (line   19)
* interpolation, string (%):             printf 风格的字符串格式化.
                                                             (line    6)
* interpolation; bytearray (%):          printf 风格的字节串格式化.
                                                             (line    6)
* interpolation; bytes (%):              printf 风格的字节串格式化.
                                                             (line    6)
* InterpolationDepthError:               异常<5>.            (line   36)
* InterpolationError:                    异常<5>.            (line   32)
* InterpolationMissingOptionError:       异常<5>.            (line   41)
* InterpolationSyntaxError:              异常<5>.            (line   46)
* interpreted（直譯的）:                 術語表.             (line  573)
* interpreter:                           顶级组件.           (line    6)
* interpreter lock:                      Thread State and the Global Interpreter Lock.
                                                             (line    6)
* interpreter prompts:                   sys --- 系统相关的参数和函数.
                                                             (line 1026)
* interpreter shutdown（直譯器關閉）:    術語表.             (line  581)
* interpreter_requires_environment() (於 test.support.script_helper 模組中): test support script_helper --- Utilities for the Python execution tests.
                                                             (line    9)
* interrupt() (sqlite3.Connection 的方法): 连接对象（Connection）.
                                                             (line  173)
* InterruptedError:                      OS 异常.            (line   64)
* interrupt_main() (於 _thread 模組中):  _thread --- 底层多线程 API.
                                                             (line   43)
* intersection() (frozenset 的方法):     集合类型 --- set frozenset.
                                                             (line   93)
* intersection_update() (frozenset 的方法): 集合类型 --- set frozenset.
                                                             (line  157)
* IntFlag (enum 中的類別):               模块内容<2>.        (line   20)
* intro (cmd.Cmd 的屬性):                Cmd 对象.           (line  113)
* int_info (於 sys 模組中):              sys --- 系统相关的参数和函数.
                                                             (line  790)
* InuseAttributeErr:                     异常<15>.           (line   31)
* inv() (於 operator 模組中):            operator --- 标准运算符替代函数.
                                                             (line   87)
* InvalidAccessErr:                      异常<15>.           (line   35)
* invalidate_caches() (importlib.abc.MetaPathFinder 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line   78)
* invalidate_caches() (importlib.abc.PathEntryFinder 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  132)
* invalidate_caches() (importlib.machinery.FileFinder 的方法): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  170)
* invalidate_caches() (importlib.machinery.PathFinder 的類別成員): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  123)
* invalidate_caches() (於 importlib 模組中): 函数<11>.       (line   56)
* InvalidCharacterErr:                   异常<15>.           (line   39)
* InvalidModificationErr:                异常<15>.           (line   45)
* InvalidOperation (decimal 中的類別):   信号.               (line   43)
* InvalidStateErr:                       异常<15>.           (line   49)
* InvalidStateError:                     Exception 类.       (line   21)
* InvalidStateError <1>:                 异常<9>.            (line   26)
* InvalidTZPathWarning:                  异常与警告.         (line   11)
* InvalidURL:                            http client --- HTTP 协议客户端.
                                                             (line  118)
* inversion:                             一元算术和位运算.   (line   16)
* Invert (ast 中的類別):                 表达式<2>.          (line   28)
* invert() (於 operator 模組中):         operator --- 标准运算符替代函数.
                                                             (line   87)
* invocation:                            标准类型层级结构.   (line  229)
* inv_cdf() (statistics.NormalDist 的方法): NormalDist 对象. (line   72)
* in_dll() (ctypes._CData 的方法):       数据类型<2>.        (line   55)
* in_table_a1() (於 stringprep 模組中):  stringprep --- 因特网字符串预备.
                                                             (line   29)
* in_table_b1() (於 stringprep 模組中):  stringprep --- 因特网字符串预备.
                                                             (line   33)
* in_table_c11() (於 stringprep 模組中): stringprep --- 因特网字符串预备.
                                                             (line   47)
* in_table_c11_c12() (於 stringprep 模組中): stringprep --- 因特网字符串预备.
                                                             (line   55)
* in_table_c12() (於 stringprep 模組中): stringprep --- 因特网字符串预备.
                                                             (line   51)
* in_table_c21() (於 stringprep 模組中): stringprep --- 因特网字符串预备.
                                                             (line   59)
* in_table_c21_c22() (於 stringprep 模組中): stringprep --- 因特网字符串预备.
                                                             (line   67)
* in_table_c22() (於 stringprep 模組中): stringprep --- 因特网字符串预备.
                                                             (line   63)
* in_table_c3() (於 stringprep 模組中):  stringprep --- 因特网字符串预备.
                                                             (line   71)
* in_table_c4() (於 stringprep 模組中):  stringprep --- 因特网字符串预备.
                                                             (line   75)
* in_table_c5() (於 stringprep 模組中):  stringprep --- 因特网字符串预备.
                                                             (line   79)
* in_table_c6() (於 stringprep 模組中):  stringprep --- 因特网字符串预备.
                                                             (line   83)
* in_table_c7() (於 stringprep 模組中):  stringprep --- 因特网字符串预备.
                                                             (line   87)
* in_table_c8() (於 stringprep 模組中):  stringprep --- 因特网字符串预备.
                                                             (line   91)
* in_table_c9() (於 stringprep 模組中):  stringprep --- 因特网字符串预备.
                                                             (line   95)
* in_table_d1() (於 stringprep 模組中):  stringprep --- 因特网字符串预备.
                                                             (line   99)
* in_table_d2() (於 stringprep 模組中):  stringprep --- 因特网字符串预备.
                                                             (line  103)
* in_transaction (sqlite3.Connection 的屬性): 连接对象（Connection）.
                                                             (line   16)
* IO (typing 中的類別):                  其他具象类型.       (line    6)
* io (模組):                             io --- 处理流的核心工具.
                                                             (line    6)
* IOBase (io 中的類別):                  I/O 基类.           (line    6)
* ioctl() (socket.socket 的方法):        套接字对象.         (line  144)
* ioctl() (於 fcntl 模組中):             fcntl —— 系统调用 fcntl 和 ioctl.
                                                             (line   49)
* IOCTL_VM_SOCKETS_GET_LOCAL_CID (於 socket 模組中): 常数<6>.
                                                             (line  207)
* IOError:                               具体异常.           (line  359)
* ior() (於 operator 模組中):            原地运算符.         (line   75)
* IO_REPARSE_TAG_APPEXECLINK (於 stat 模組中): stat --- 解析 stat 结果.
                                                             (line  391)
* IO_REPARSE_TAG_MOUNT_POINT (於 stat 模組中): stat --- 解析 stat 结果.
                                                             (line  391)
* IO_REPARSE_TAG_SYMLINK (於 stat 模組中): stat --- 解析 stat 结果.
                                                             (line  391)
* ip (ipaddress.IPv4Interface 的屬性):   接口对象.           (line   16)
* ip (ipaddress.IPv6Interface 的屬性):   接口对象.           (line   64)
* ipaddress (模組):                      ipaddress --- IPv4/IPv6 操作库.
                                                             (line    6)
* ipow() (於 operator 模組中):           原地运算符.         (line   80)
* IPv4Address (ipaddress 中的類別):      地址对象.           (line   11)
* IPv4Interface (ipaddress 中的類別):    接口对象.           (line    8)
* IPv4Network (ipaddress 中的類別):      网络对象.           (line   11)
* ipv4_mapped (ipaddress.IPv6Address 的屬性): 地址对象.      (line  221)
* IPv6Address (ipaddress 中的類別):      地址对象.           (line  147)
* IPv6Interface (ipaddress 中的類別):    接口对象.           (line   56)
* IPv6Network (ipaddress 中的類別):      网络对象.           (line  224)
* IPV6_ENABLED (於 test.support.socket_helper 模組中): test support socket_helper --- Utilities for socket tests.
                                                             (line   11)
* ip_address() (於 ipaddress 模組中):    方便的工厂函数.     (line    9)
* ip_interface() (於 ipaddress 模組中):  方便的工厂函数.     (line   37)
* ip_network() (於 ipaddress 模組中):    方便的工厂函数.     (line   23)
* irshift() (於 operator 模組中):        原地运算符.         (line   85)
* Is (ast 中的類別):                     表达式<2>.          (line  109)
* isabs() (於 os.path 模組中):           os path --- 常用路径操作.
                                                             (line  178)
* isabstract() (於 inspect 模組中):      类型和成员.         (line  398)
* IsADirectoryError:                     OS 异常.            (line   73)
* isalnum() (bytearray 的方法):          bytes 和 bytearray 操作.
                                                             (line  421)
* isalnum() (bytes 的方法):              bytes 和 bytearray 操作.
                                                             (line  421)
* isalnum() (str 的方法):                字符串的方法<2>.    (line  150)
* isalnum() (於 curses.ascii 模組中):    curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  127)
* isalpha() (bytearray 的方法):          bytes 和 bytearray 操作.
                                                             (line  437)
* isalpha() (bytes 的方法):              bytes 和 bytearray 操作.
                                                             (line  437)
* isalpha() (str 的方法):                字符串的方法<2>.    (line  158)
* isalpha() (於 curses.ascii 模組中):    curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  131)
* isascii() (bytearray 的方法):          bytes 和 bytearray 操作.
                                                             (line  452)
* isascii() (bytes 的方法):              bytes 和 bytearray 操作.
                                                             (line  452)
* isascii() (str 的方法):                字符串的方法<2>.    (line  165)
* isascii() (於 curses.ascii 模組中):    curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  135)
* isasyncgen() (於 inspect 模組中):      类型和成员.         (line  368)
* isasyncgenfunction() (於 inspect 模組中): 类型和成员.      (line  351)
* isatty() (chunk.Chunk 的方法):         chunk --- 读取 IFF 分块数据.
                                                             (line   76)
* isatty() (io.IOBase 的方法):           I/O 基类.           (line   60)
* isatty() (於 os 模組中):               文件描述符操作.     (line  185)
* isawaitable() (於 inspect 模組中):     类型和成员.         (line  332)
* isblank() (於 curses.ascii 模組中):    curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  139)
* isblk() (tarfile.TarInfo 的方法):      TarInfo 对象.       (line  112)
* isbuiltin() (於 inspect 模組中):       类型和成员.         (line  388)
* ischr() (tarfile.TarInfo 的方法):      TarInfo 对象.       (line  108)
* isclass() (於 inspect 模組中):         类型和成员.         (line  288)
* isclose() (於 cmath 模組中):           分类函数.           (line   20)
* isclose() (於 math 模組中):            数论与表示函数.     (line   95)
* iscntrl() (於 curses.ascii 模組中):    curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  143)
* iscode() (於 inspect 模組中):          类型和成员.         (line  384)
* iscoroutine() (於 asyncio 模組中):     基于生成器的协程.   (line   33)
* iscoroutine() (於 inspect 模組中):     类型和成员.         (line  325)
* iscoroutinefunction() (於 asyncio 模組中): 基于生成器的协程.
                                                             (line   40)
* iscoroutinefunction() (於 inspect 模組中): 类型和成员.     (line  314)
* isctrl() (於 curses.ascii 模組中):     curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  181)
* isDaemon() (threading.Thread 的方法):  线程对象.           (line  164)
* isdatadescriptor() (於 inspect 模組中): 类型和成员.        (line  420)
* isdecimal() (str 的方法):              字符串的方法<2>.    (line  172)
* isdev() (tarfile.TarInfo 的方法):      TarInfo 对象.       (line  120)
* isdigit() (bytearray 的方法):          bytes 和 bytearray 操作.
                                                             (line  460)
* isdigit() (bytes 的方法):              bytes 和 bytearray 操作.
                                                             (line  460)
* isdigit() (str 的方法):                字符串的方法<2>.    (line  179)
* isdigit() (於 curses.ascii 模組中):    curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  147)
* isdir() (tarfile.TarInfo 的方法):      TarInfo 对象.       (line   96)
* isdir() (於 os.path 模組中):           os path --- 常用路径操作.
                                                             (line  194)
* isdisjoint() (frozenset 的方法):       集合类型 --- set frozenset.
                                                             (line   59)
* isdown() (於 turtle 模組中):           绘图状态.           (line   82)
* iselement() (於 xml.etree.ElementTree 模組中): 函数<7>.    (line  112)
* isenabled() (於 gc 模組中):            gc --- 垃圾回收器接口.
                                                             (line   26)
* isEnabledFor() (logging.Logger 的方法): 记录器对象.        (line   76)
* isendwin() (於 curses 模組中):         函数<4>.            (line  200)
* ISEOF() (於 token 模組中):             token --- 与Python解析树一起使用的常量.
                                                             (line   30)
* isexpr() (parser.ST 的方法):           ST 对象.            (line   21)
* isexpr() (於 parser 模組中):           Queries on ST Objects.
                                                             (line   12)
* isfifo() (tarfile.TarInfo 的方法):     TarInfo 对象.       (line  116)
* isfile() (tarfile.TarInfo 的方法):     TarInfo 对象.       (line   88)
* isfile() (於 os.path 模組中):          os path --- 常用路径操作.
                                                             (line  186)
* isfinite() (於 cmath 模組中):          分类函数.           (line    6)
* isfinite() (於 math 模組中):           数论与表示函数.     (line  123)
* isfirstline() (於 fileinput 模組中):   fileinput --- 迭代来自多个输入流的行.
                                                             (line   87)
* isframe() (於 inspect 模組中):         类型和成员.         (line  380)
* isfunction() (於 inspect 模組中):      类型和成员.         (line  297)
* isfuture() (於 asyncio 模組中):        Future 函数.        (line    6)
* isgenerator() (於 inspect 模組中):     类型和成员.         (line  310)
* isgeneratorfunction() (於 inspect 模組中): 类型和成员.     (line  302)
* isgetsetdescriptor() (於 inspect 模組中): 类型和成员.      (line  433)
* isgraph() (於 curses.ascii 模組中):    curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  152)
* isidentifier() (str 的方法):           字符串的方法<2>.    (line  187)
* isinf() (於 cmath 模組中):             分类函数.           (line   12)
* isinf() (於 math 模組中):              数论与表示函数.     (line  130)
* isinstance (2to3 fixer):               修复器.             (line  153)
* isinstance() (內建函式):               內建函式.           (line  710)
* iskeyword() (於 keyword 模組中):       keyword --- 检验Python关键字.
                                                             (line   12)
* isleap() (於 calendar 模組中):         calendar --- 日历相关函数.
                                                             (line  261)
* islice() (於 itertools 模組中):        Itertool函数.       (line  321)
* islink() (於 os.path 模組中):          os path --- 常用路径操作.
                                                             (line  202)
* islnk() (tarfile.TarInfo 的方法):      TarInfo 对象.       (line  104)
* islower() (bytearray 的方法):          bytes 和 bytearray 操作.
                                                             (line  474)
* islower() (bytes 的方法):              bytes 和 bytearray 操作.
                                                             (line  474)
* islower() (str 的方法):                字符串的方法<2>.    (line  204)
* islower() (於 curses.ascii 模組中):    curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  156)
* ismemberdescriptor() (於 inspect 模組中): 类型和成员.      (line  442)
* ismeta() (於 curses.ascii 模組中):     curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  185)
* ismethod() (於 inspect 模組中):        类型和成员.         (line  293)
* ismethoddescriptor() (於 inspect 模組中): 类型和成员.      (line  402)
* ismodule() (於 inspect 模組中):        类型和成员.         (line  284)
* ismount() (於 os.path 模組中):         os path --- 常用路径操作.
                                                             (line  209)
* isnan() (於 cmath 模組中):             分类函数.           (line   16)
* isnan() (於 math 模組中):              数论与表示函数.     (line  134)
* ISNONTERMINAL() (於 token 模組中):     token --- 与Python解析树一起使用的常量.
                                                             (line   26)
* IsNot (ast 中的類別):                  表达式<2>.          (line  109)
* isnumeric() (str 的方法):              字符串的方法<2>.    (line  209)
* isocalendar() (datetime.date 的方法):  date 对象.          (line  198)
* isocalendar() (datetime.datetime 的方法): datetime 对象.   (line  533)
* isoformat() (datetime.date 的方法):    date 对象.          (line  221)
* isoformat() (datetime.datetime 的方法): datetime 对象.     (line  538)
* isoformat() (datetime.time 的方法):    time 对象.          (line  135)
* IsolatedAsyncioTestCase (unittest 中的類別): 测试用例.     (line  802)
* isolation_level (sqlite3.Connection 的屬性): 连接对象（Connection）.
                                                             (line   10)
* isoweekday() (datetime.date 的方法):   date 对象.          (line  192)
* isoweekday() (datetime.datetime 的方法): datetime 对象.    (line  527)
* isprint() (於 curses.ascii 模組中):    curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  160)
* isprintable() (str 的方法):            字符串的方法<2>.    (line  217)
* ispunct() (於 curses.ascii 模組中):    curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  164)
* isqrt() (於 math 模組中):              数论与表示函数.     (line  138)
* isreadable() (pprint.PrettyPrinter 的方法): PrettyPrinter 对象.
                                                             (line   20)
* isreadable() (於 pprint 模組中):       pprint --- 数据美化输出.
                                                             (line  115)
* isrecursive() (pprint.PrettyPrinter 的方法): PrettyPrinter 对象.
                                                             (line   27)
* isrecursive() (於 pprint 模組中):      pprint --- 数据美化输出.
                                                             (line  123)
* isreg() (tarfile.TarInfo 的方法):      TarInfo 对象.       (line   92)
* isReservedKey() (http.cookies.Morsel 的方法): Morsel 对象. (line   64)
* isroutine() (於 inspect 模組中):       类型和成员.         (line  393)
* isSameNode() (xml.dom.Node 的方法):    节点对象.           (line   89)
* issoftkeyword() (於 keyword 模組中):   keyword --- 检验Python关键字.
                                                             (line   22)
* isspace() (bytearray 的方法):          bytes 和 bytearray 操作.
                                                             (line  491)
* isspace() (bytes 的方法):              bytes 和 bytearray 操作.
                                                             (line  491)
* isspace() (str 的方法):                字符串的方法<2>.    (line  226)
* isspace() (於 curses.ascii 模組中):    curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  168)
* isstdin() (於 fileinput 模組中):       fileinput --- 迭代来自多个输入流的行.
                                                             (line   91)
* issubclass() (內建函式):               內建函式.           (line  719)
* issubset() (frozenset 的方法):         集合类型 --- set frozenset.
                                                             (line   64)
* issuite() (parser.ST 的方法):          ST 对象.            (line   25)
* issuite() (於 parser 模組中):          Queries on ST Objects.
                                                             (line   22)
* issuperset() (frozenset 的方法):       集合类型 --- set frozenset.
                                                             (line   75)
* issym() (tarfile.TarInfo 的方法):      TarInfo 对象.       (line  100)
* ISTERMINAL() (於 token 模組中):        token --- 与Python解析树一起使用的常量.
                                                             (line   22)
* istitle() (bytearray 的方法):          bytes 和 bytearray 操作.
                                                             (line  498)
* istitle() (bytes 的方法):              bytes 和 bytearray 操作.
                                                             (line  498)
* istitle() (str 的方法):                字符串的方法<2>.    (line  235)
* istraceback() (於 inspect 模組中):     类型和成员.         (line  376)
* isub() (於 operator 模組中):           原地运算符.         (line   90)
* isupper() (bytearray 的方法):          bytes 和 bytearray 操作.
                                                             (line  512)
* isupper() (bytes 的方法):              bytes 和 bytearray 操作.
                                                             (line  512)
* isupper() (str 的方法):                字符串的方法<2>.    (line  241)
* isupper() (於 curses.ascii 模組中):    curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  173)
* isvisible() (於 turtle 模組中):        可见性.             (line   21)
* isxdigit() (於 curses.ascii 模組中):   curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  177)
* is_() (於 operator 模組中):            operator --- 标准运算符替代函数.
                                                             (line   52)
* is_absolute() (pathlib.PurePath 的方法): 方法和特征属性.   (line  161)
* is_active() (asyncio.AbstractChildWatcher 的方法): 进程监视器.
                                                             (line   59)
* is_active() (graphlib.TopologicalSorter 的方法): graphlib --- 操作类似图的结构的功能.
                                                             (line   93)
* is_alive() (multiprocessing.Process 的方法): Process 和异常.
                                                             (line   66)
* is_alive() (threading.Thread 的方法):  线程对象.           (line  146)
* is_android (於 test.support 模組中):   test support --- Utilities for the Python test suite.
                                                             (line   40)
* is_annotated() (symtable.Symbol 的方法): 符号表的查看.     (line  127)
* is_assigned() (symtable.Symbol 的方法): 符号表的查看.      (line  137)
* is_attachment() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  371)
* is_authenticated() (urllib.request.HTTPPasswordMgrWithPriorAuth 的方法): HTTPPasswordMgrWithPriorAuth 对象.
                                                             (line   27)
* is_blocked() (http.cookiejar.DefaultCookiePolicy 的方法): DefaultCookiePolicy 对象.
                                                             (line   54)
* is_block_device() (pathlib.Path 的方法): 方法<2>.          (line  170)
* is_canonical() (decimal.Context 的方法): 上下文对象.       (line  256)
* is_canonical() (decimal.Decimal 的方法): Decimal 对象.     (line  237)
* IS_CHARACTER_JUNK() (於 difflib 模組中): difflib --- 计算差异的辅助工具.
                                                             (line  317)
* is_char_device() (pathlib.Path 的方法): 方法<2>.           (line  178)
* is_check_supported() (於 lzma 模組中): 杂项<2>.            (line    6)
* is_closed() (asyncio.loop 的方法):     运行和停止循环.     (line   36)
* is_closing() (asyncio.BaseTransport 的方法): 基础传输.     (line   15)
* is_closing() (asyncio.StreamWriter 的方法): StreamWriter.  (line   73)
* is_dataclass() (於 dataclasses 模組中): 模块级装饰器、类和函数.
                                                             (line  327)
* is_declared_global() (symtable.Symbol 的方法): 符号表的查看.
                                                             (line  119)
* is_dir() (importlib.abc.Traversable 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  539)
* is_dir() (os.DirEntry 的方法):         文件和目录.         (line  772)
* is_dir() (pathlib.Path 的方法):        方法<2>.            (line  122)
* is_dir() (zipfile.Path 的方法):        Path 对象.          (line   38)
* is_dir() (zipfile.ZipInfo 的方法):     ZipInfo 对象.       (line   36)
* is_enabled() (於 faulthandler 模組中): 错误处理程序的状态. (line   25)
* is_expired() (http.cookiejar.Cookie 的方法): Cookie 对象<2>.
                                                             (line  103)
* is_fifo() (pathlib.Path 的方法):       方法<2>.            (line  162)
* is_file() (importlib.abc.Traversable 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  543)
* is_file() (os.DirEntry 的方法):        文件和目录.         (line  796)
* is_file() (pathlib.Path 的方法):       方法<2>.            (line  130)
* is_file() (zipfile.Path 的方法):       Path 对象.          (line   42)
* is_finalized() (於 gc 模組中):         gc --- 垃圾回收器接口.
                                                             (line  148)
* is_finalizing() (於 sys 模組中):       sys --- 系统相关的参数和函数.
                                                             (line  831)
* is_finite() (decimal.Context 的方法):  上下文对象.         (line  260)
* is_finite() (decimal.Decimal 的方法):  Decimal 对象.       (line  243)
* is_free() (symtable.Symbol 的方法):    符号表的查看.       (line  133)
* is_global (ipaddress.IPv4Address 的屬性): 地址对象.        (line   98)
* is_global (ipaddress.IPv6Address 的屬性): 地址对象.        (line  203)
* is_global() (symtable.Symbol 的方法):  符号表的查看.       (line  111)
* is_hop_by_hop() (於 wsgiref.util 模組中): wsgiref util -- WSGI 环境工具.
                                                             (line   94)
* is_imported() (symtable.Symbol 的方法): 符号表的查看.      (line  103)
* is_infinite() (decimal.Context 的方法): 上下文对象.        (line  264)
* is_infinite() (decimal.Decimal 的方法): Decimal 对象.      (line  248)
* is_integer() (float 的方法):           浮点类型的附加方法. (line   14)
* is_jython (於 test.support 模組中):    test support --- Utilities for the Python test suite.
                                                             (line   36)
* is_linetouched() (curses.window 的方法): Window 对象.      (line  315)
* IS_LINE_JUNK() (於 difflib 模組中):    difflib --- 计算差异的辅助工具.
                                                             (line  311)
* is_link_local (ipaddress.IPv4Address 的屬性): 地址对象.    (line  121)
* is_link_local (ipaddress.IPv4Network 的屬性): 网络对象.    (line   67)
* is_link_local (ipaddress.IPv6Address 的屬性): 地址对象.    (line  211)
* is_link_local (ipaddress.IPv6Network 的屬性): 网络对象.    (line  273)
* is_local() (symtable.Symbol 的方法):   符号表的查看.       (line  123)
* is_loopback (ipaddress.IPv4Address 的屬性): 地址对象.      (line  116)
* is_loopback (ipaddress.IPv4Network 的屬性): 网络对象.      (line   65)
* is_loopback (ipaddress.IPv6Address 的屬性): 地址对象.      (line  209)
* is_loopback (ipaddress.IPv6Network 的屬性): 网络对象.      (line  271)
* is_mount() (pathlib.Path 的方法):      方法<2>.            (line  138)
* is_multicast (ipaddress.IPv4Address 的屬性): 地址对象.     (line   87)
* is_multicast (ipaddress.IPv4Network 的屬性): 网络对象.     (line   57)
* is_multicast (ipaddress.IPv6Address 的屬性): 地址对象.     (line  199)
* is_multicast (ipaddress.IPv6Network 的屬性): 网络对象.     (line  263)
* is_multipart() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  105)
* is_multipart() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  120)
* is_namespace() (symtable.Symbol 的方法): 符号表的查看.     (line  141)
* is_nan() (decimal.Context 的方法):     上下文对象.         (line  268)
* is_nan() (decimal.Decimal 的方法):     Decimal 对象.       (line  253)
* is_nested() (symtable.SymbolTable 的方法): 符号表的查看.   (line   33)
* is_nonlocal() (symtable.Symbol 的方法): 符号表的查看.      (line  115)
* is_normal() (decimal.Context 的方法):  上下文对象.         (line  272)
* is_normal() (decimal.Decimal 的方法):  Decimal 对象.       (line  258)
* is_normalized() (於 unicodedata 模組中): unicodedata --- Unicode 数据库.
                                                             (line   95)
* is_not() (於 operator 模組中):         operator --- 标准运算符替代函数.
                                                             (line   56)
* is_not_allowed() (http.cookiejar.DefaultCookiePolicy 的方法): DefaultCookiePolicy 对象.
                                                             (line   67)
* IS_OP (opcode):                        Python字节码说明.   (line  521)
* is_optimized() (symtable.SymbolTable 的方法): 符号表的查看.
                                                             (line   29)
* is_package() (importlib.abc.InspectLoader 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  350)
* is_package() (importlib.abc.SourceLoader 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  516)
* is_package() (importlib.machinery.ExtensionFileLoader 的方法): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  289)
* is_package() (importlib.machinery.SourceFileLoader 的方法): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  199)
* is_package() (importlib.machinery.SourcelessFileLoader 的方法): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  239)
* is_package() (zipimport.zipimporter 的方法): zipimporter 对象.
                                                             (line   51)
* is_parameter() (symtable.Symbol 的方法): 符号表的查看.     (line  107)
* is_private (ipaddress.IPv4Address 的屬性): 地址对象.       (line   92)
* is_private (ipaddress.IPv4Network 的屬性): 网络对象.       (line   59)
* is_private (ipaddress.IPv6Address 的屬性): 地址对象.       (line  201)
* is_private (ipaddress.IPv6Network 的屬性): 网络对象.       (line  265)
* is_python_build() (於 sysconfig 模組中): 其他功能<2>.      (line   49)
* is_qnan() (decimal.Context 的方法):    上下文对象.         (line  276)
* is_qnan() (decimal.Decimal 的方法):    Decimal 对象.       (line  263)
* is_reading() (asyncio.ReadTransport 的方法): 只读传输.     (line    6)
* is_referenced() (symtable.Symbol 的方法): 符号表的查看.    (line   99)
* is_relative_to() (pathlib.PurePath 的方法): 方法和特征属性.
                                                             (line  180)
* is_reserved (ipaddress.IPv4Address 的屬性): 地址对象.      (line  111)
* is_reserved (ipaddress.IPv4Network 的屬性): 网络对象.      (line   63)
* is_reserved (ipaddress.IPv6Address 的屬性): 地址对象.      (line  207)
* is_reserved (ipaddress.IPv6Network 的屬性): 网络对象.      (line  269)
* is_reserved() (pathlib.PurePath 的方法): 方法和特征属性.   (line  192)
* is_resource() (importlib.abc.ResourceReader 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  287)
* is_resource() (於 importlib.resources 模組中): importlib resources -- 资源.
                                                             (line  127)
* is_resource_enabled() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  257)
* is_running() (asyncio.loop 的方法):    运行和停止循环.     (line   32)
* is_safe (uuid.UUID 的屬性):            uuid --- RFC 4122 定义的UUID对象.
                                                             (line  138)
* is_serving() (asyncio.Server 的方法):  Server 对象.        (line   82)
* is_set() (asyncio.Event 的方法):       Event.              (line   63)
* is_set() (threading.Event 的方法):     事件对象.           (line   22)
* is_signed() (decimal.Context 的方法):  上下文对象.         (line  280)
* is_signed() (decimal.Decimal 的方法):  Decimal 对象.       (line  268)
* is_site_local (ipaddress.IPv6Address 的屬性): 地址对象.    (line  215)
* is_site_local (ipaddress.IPv6Network 的屬性): 网络对象.    (line  320)
* is_snan() (decimal.Context 的方法):    上下文对象.         (line  284)
* is_snan() (decimal.Decimal 的方法):    Decimal 对象.       (line  273)
* is_socket() (pathlib.Path 的方法):     方法<2>.            (line  154)
* is_subnormal() (decimal.Context 的方法): 上下文对象.       (line  288)
* is_subnormal() (decimal.Decimal 的方法): Decimal 对象.     (line  278)
* is_symlink() (os.DirEntry 的方法):     文件和目录.         (line  809)
* is_symlink() (pathlib.Path 的方法):    方法<2>.            (line  148)
* is_tarfile() (於 tarfile 模組中):      tarfile --- 读写tar归档文件.
                                                             (line  157)
* is_term_resized() (於 curses 模組中):  函数<4>.            (line  195)
* is_tracing() (於 tracemalloc 模組中):  函数<10>.           (line   61)
* is_tracked() (於 gc 模組中):           gc --- 垃圾回收器接口.
                                                             (line  126)
* is_unspecified (ipaddress.IPv4Address 的屬性): 地址对象.   (line  106)
* is_unspecified (ipaddress.IPv4Network 的屬性): 网络对象.   (line   61)
* is_unspecified (ipaddress.IPv6Address 的屬性): 地址对象.   (line  205)
* is_unspecified (ipaddress.IPv6Network 的屬性): 网络对象.   (line  267)
* is_wintouched() (curses.window 的方法): Window 对象.       (line  321)
* is_zero() (decimal.Context 的方法):    上下文对象.         (line  292)
* is_zero() (decimal.Decimal 的方法):    Decimal 对象.       (line  283)
* is_zipfile() (於 zipfile 模組中):      zipfile --- 使用ZIP存档.
                                                             (line   62)
* ITALIC (於 tkinter.font 模組中):       tkinter font --- Tkinter 字体封装.
                                                             (line   15)
* item selection:                        标准类型层级结构.   (line   98)
* item() (tkinter.ttk.Treeview 的方法):  ttk Treeview.       (line  181)
* item() (xml.dom.NamedNodeMap 的方法):  NamedNodeMap 对象.  (line   12)
* item() (xml.dom.NodeList 的方法):      节点列表对象.       (line   13)
* itemgetter() (於 operator 模組中):     operator --- 标准运算符替代函数.
                                                             (line  237)
* items() (configparser.ConfigParser 的方法): ConfigParser 对象.
                                                             (line  205)
* items() (contextvars.Context 的方法):  手动上下文管理.     (line   99)
* items() (dict 的方法):                 映射类型 --- dict.  (line  148)
* items() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  196)
* items() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  291)
* items() (mailbox.Mailbox 的方法):      Mailbox 对象.       (line  103)
* items() (types.MappingProxyType 的方法): 标准解释器类型.   (line  249)
* items() (xml.etree.ElementTree.Element 的方法): 元素对象.  (line   59)
* itemsize (array.array 的屬性):         array --- 高效率的數值型態陣列.
                                                             (line  100)
* itemsize (memoryview 的屬性):          内存视图.           (line  397)
* ItemsView (collections.abc 中的類別):  容器抽象基类.       (line  180)
* ItemsView (typing 中的類別):           collections abc 对应的容器.
                                                             (line   41)
* iter() (xml.etree.ElementTree.Element 的方法): 元素对象.   (line  115)
* iter() (xml.etree.ElementTree.ElementTree 的方法): ElementTree 对象.
                                                             (line   35)
* iter() (內建函式):                     內建函式.           (line  727)
* Iterable (collections.abc 中的類別):   容器抽象基类.       (line  120)
* Iterable (typing 中的類別):            collections abc 对应的其他类型.
                                                             (line    6)
* iterable; unpacking:                   表达式列表.         (line   14)
* iterable（可疊代物件）:                術語表.             (line  593)
* Iterator (collections.abc 中的類別):   容器抽象基类.       (line  136)
* Iterator (typing 中的類別):            collections abc 对应的其他类型.
                                                             (line   13)
* iterator protocol:                     迭代器类型.         (line    6)
* iterator（疊代器）:                    術語表.             (line  611)
* iterdecode() (於 codecs 模組中):       codecs --- 编解码器注册和相关基类.
                                                             (line  190)
* iterdir() (importlib.abc.Traversable 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  535)
* iterdir() (pathlib.Path 的方法):       方法<2>.            (line  186)
* iterdir() (zipfile.Path 的方法):       Path 对象.          (line   34)
* iterdump() (sqlite3.Connection 的方法): 连接对象（Connection）.
                                                             (line  359)
* iterencode() (json.JSONEncoder 的方法): 编码器和解码器.    (line  202)
* iterencode() (於 codecs 模組中):       codecs --- 编解码器注册和相关基类.
                                                             (line  180)
* iterfind() (xml.etree.ElementTree.Element 的方法): 元素对象.
                                                             (line  124)
* iterfind() (xml.etree.ElementTree.ElementTree 的方法): ElementTree 对象.
                                                             (line   40)
* iteritems() (mailbox.Mailbox 的方法):  Mailbox 对象.       (line  103)
* iterkeys() (mailbox.Mailbox 的方法):   Mailbox 对象.       (line   83)
* itermonthdates() (calendar.Calendar 的方法): calendar --- 日历相关函数.
                                                             (line   36)
* itermonthdays() (calendar.Calendar 的方法): calendar --- 日历相关函数.
                                                             (line   42)
* itermonthdays2() (calendar.Calendar 的方法): calendar --- 日历相关函数.
                                                             (line   49)
* itermonthdays3() (calendar.Calendar 的方法): calendar --- 日历相关函数.
                                                             (line   56)
* itermonthdays4() (calendar.Calendar 的方法): calendar --- 日历相关函数.
                                                             (line   64)
* iternextfunc (C 型態):                 Slot Type typedefs. (line   88)
* iterparse() (於 xml.etree.ElementTree 模組中): 函数<7>.    (line  117)
* itertext() (xml.etree.ElementTree.Element 的方法): 元素对象.
                                                             (line  132)
* itertools (2to3 fixer):                修复器.             (line  166)
* itertools (模組):                      itertools --- 为高效循环而创建迭代器的函数.
                                                             (line    6)
* itertools_imports (2to3 fixer):        修复器.             (line  160)
* itervalues() (mailbox.Mailbox 的方法): Mailbox 对象.       (line   89)
* iterweekdays() (calendar.Calendar 的方法): calendar --- 日历相关函数.
                                                             (line   31)
* iter_attachments() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  475)
* iter_child_nodes() (於 ast 模組中):    ast 中的辅助函数.   (line  137)
* iter_fields() (於 ast 模組中):         ast 中的辅助函数.   (line  132)
* iter_importers() (於 pkgutil 模組中):  pkgutil --- 包扩展工具.
                                                             (line  122)
* iter_modules() (於 pkgutil 模組中):    pkgutil --- 包扩展工具.
                                                             (line  140)
* iter_parts() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  488)
* iter_unpack() (struct.Struct 的方法):  类.                 (line   41)
* iter_unpack() (於 struct 模組中):      函数和异常.         (line   37)
* ItimerError:                           模块内容<5>.        (line  199)
* ITIMER_PROF (於 signal 模組中):        模块内容<5>.        (line  170)
* ITIMER_REAL (於 signal 模組中):        模块内容<5>.        (line  162)
* ITIMER_VIRTUAL (於 signal 模組中):     模块内容<5>.        (line  166)
* itruediv() (於 operator 模組中):       原地运算符.         (line   95)
* ixor() (於 operator 模組中):           原地运算符.         (line  100)
* j; in numeric literal:                 浮点数字面值.       (line   24)
* Jansen, Jack:                          uu --- 对 uuencode 文件进行编码与解码.
                                                             (line   17)
* Java; language:                        标准类型层级结构.   (line   84)
* java_ver() (於 platform 模組中):       Java平台.           (line    6)
* join() (asyncio.Queue 的方法):         队列.               (line   47)
* join() (bytearray 的方法):             bytes 和 bytearray 操作.
                                                             (line  140)
* join() (bytes 的方法):                 bytes 和 bytearray 操作.
                                                             (line  140)
* join() (multiprocessing.JoinableQueue 的方法): 管道和队列. (line  216)
* join() (multiprocessing.pool.Pool 的方法): 进程池.         (line  149)
* join() (multiprocessing.Process 的方法): Process 和异常.   (line   43)
* join() (queue.Queue 的方法):           Queue对象.          (line   73)
* join() (str 的方法):                   字符串的方法<2>.    (line  255)
* join() (threading.Thread 的方法):      线程对象.           (line   92)
* join() (於 os.path 模組中):            os path --- 常用路径操作.
                                                             (line  223)
* join() (於 shlex 模組中):              shlex —— 简单的词义分析.
                                                             (line   30)
* JoinableQueue (multiprocessing 中的類別): 管道和队列.      (line  198)
* JoinedStr (ast 中的類別):              字面值<3>.          (line   42)
* joinpath() (importlib.abc.Traversable 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  547)
* joinpath() (pathlib.PurePath 的方法):  方法和特征属性.     (line  206)
* join_thread() (multiprocessing.Queue 的方法): 管道和队列.  (line  145)
* join_thread() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  851)
* json (模組):                           json --- JSON 编码和解码器.
                                                             (line    6)
* json.tool (模組):                      命令行界面<4>.      (line    6)
* json.tool command line option; –compact: 命令行选项<4>.    (line   47)
* json.tool command line option; -h:     命令行选项<4>.      (line   53)
* json.tool command line option; –help:  命令行选项<4>.      (line   53)
* json.tool command line option; –indent: 命令行选项<4>.     (line   47)
* json.tool command line option; –json-lines: 命令行选项<4>. (line   41)
* json.tool command line option; –no-ensure-ascii: 命令行选项<4>.
                                                             (line   35)
* json.tool command line option; –no-indent: 命令行选项<4>.  (line   47)
* json.tool command line option; –sort-keys: 命令行选项<4>.  (line   29)
* json.tool command line option; –tab:   命令行选项<4>.      (line   47)
* json.tool command line option; infile: 命令行选项<4>.      (line    6)
* json.tool command line option; outfile: 命令行选项<4>.     (line   24)
* JSONDecodeError:                       例外.               (line    6)
* JSONDecoder (json 中的類別):           编码器和解码器.     (line    6)
* JSONEncoder (json 中的類別):           编码器和解码器.     (line   94)
* js_output() (http.cookies.BaseCookie 的方法): Cookie 对象. (line   28)
* js_output() (http.cookies.Morsel 的方法): Morsel 对象.     (line   74)
* jump (pdb command):                    调试器命令.         (line  161)
* JUMP_ABSOLUTE (opcode):                Python字节码说明.   (line  582)
* JUMP_FORWARD (opcode):                 Python字节码说明.   (line  545)
* JUMP_IF_FALSE_OR_POP (opcode):         Python字节码说明.   (line  575)
* JUMP_IF_NOT_EXC_MATCH (opcode):        Python字节码说明.   (line  561)
* JUMP_IF_TRUE_OR_POP (opcode):          Python字节码说明.   (line  568)
* kbhit() (於 msvcrt 模組中):            控制台 I/O.         (line    6)
* KDEDIR:                                webbrowser --- 方便的Web浏览器控制器.
                                                             (line  164)
* kevent() (於 select 模組中):           select --- 等待 I/O 完成.
                                                             (line   86)
* key:                                   字典显示.           (line    6)
* key (http.cookies.Morsel 的屬性):      Morsel 对象.        (line   56)
* key (zoneinfo.ZoneInfo 的屬性):        ZoneInfo 类.        (line   63)
* key function（鍵函式）:                術語表.             (line  628)
* key/datum pair:                        字典显示.           (line    6)
* KeyboardInterrupt:                     具体异常.           (line   62)
* KeyboardInterrupt (built-in exception): 信号处理<2>.       (line    8)
* KeyboardInterrupt (built-in exception) <1>: 信号处理<2>.   (line   20)
* KeyError:                              具体异常.           (line   58)
* keylog_filename (ssl.SSLContext 的屬性): SSL 上下文.       (line  461)
* keyname() (於 curses 模組中):          函数<4>.            (line  205)
* keypad() (curses.window 的方法):       Window 对象.        (line  326)
* keyrefs() (weakref.WeakKeyDictionary 的方法): weakref --- 弱引用.
                                                             (line  138)
* keys() (contextvars.Context 的方法):   手动上下文管理.     (line   91)
* keys() (dict 的方法):                  映射类型 --- dict.  (line  153)
* keys() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  188)
* keys() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  283)
* keys() (mailbox.Mailbox 的方法):       Mailbox 对象.       (line   83)
* keys() (sqlite3.Row 的方法):           行对象.             (line   18)
* keys() (types.MappingProxyType 的方法): 标准解释器类型.    (line  253)
* keys() (xml.etree.ElementTree.Element 的方法): 元素对象.   (line   64)
* KeysView (collections.abc 中的類別):   容器抽象基类.       (line  180)
* KeysView (typing 中的類別):            collections abc 对应的容器.
                                                             (line   48)
* keyword:                               关键字.             (line    6)
* keyword (ast 中的類別):                表达式<2>.          (line  152)
* keyword (模組):                        keyword --- 检验Python关键字.
                                                             (line    6)
* keyword argument（關鍵字引數）:        術語表.             (line  649)
* keywords (functools.partial 的屬性):   partial 对象.       (line   19)
* KEY_ALL_ACCESS (於 winreg 模組中):     访问权限.           (line    8)
* KEY_CREATE_LINK (於 winreg 模組中):    访问权限.           (line   49)
* KEY_CREATE_SUB_KEY (於 winreg 模組中): 访问权限.           (line   37)
* KEY_ENUMERATE_SUB_KEYS (於 winreg 模組中): 访问权限.       (line   41)
* KEY_EXECUTE (於 winreg 模組中):        访问权限.           (line   25)
* KEY_NOTIFY (於 winreg 模組中):         访问权限.           (line   45)
* KEY_QUERY_VALUE (於 winreg 模組中):    访问权限.           (line   29)
* KEY_READ (於 winreg 模組中):           访问权限.           (line   20)
* KEY_SET_VALUE (於 winreg 模組中):      访问权限.           (line   33)
* KEY_WOW64_32KEY (於 winreg 模組中):    64 位系统特有.      (line   12)
* KEY_WOW64_64KEY (於 winreg 模組中):    64 位系统特有.      (line    8)
* KEY_WRITE (於 winreg 模組中):          访问权限.           (line   15)
* kill() (asyncio.asyncio.subprocess.Process 的方法): 与子进程交互.
                                                             (line   91)
* kill() (asyncio.SubprocessTransport 的方法): 子进程传输.   (line   30)
* kill() (multiprocessing.Process 的方法): Process 和异常.   (line  139)
* kill() (subprocess.Popen 的方法):      Popen 对象.         (line   79)
* kill() (於 os 模組中):                 进程管理.           (line  247)
* killchar() (於 curses 模組中):         函数<4>.            (line  213)
* killpg() (於 os 模組中):               进程管理.           (line  264)
* kill_python() (於 test.support.script_helper 模組中): test support script_helper --- Utilities for the Python execution tests.
                                                             (line   75)
* kind (inspect.Parameter 的屬性):       Introspecting callables with the Signature object.
                                                             (line  180)
* knownfiles (於 mimetypes 模組中):      mimetypes --- 映射文件名到 MIME 类型.
                                                             (line  102)
* kqueue() (於 select 模組中):           select --- 等待 I/O 完成.
                                                             (line   77)
* KqueueSelector (selectors 中的類別):   类<2>.              (line  173)
* kwargs (inspect.BoundArguments 的屬性): Introspecting callables with the Signature object.
                                                             (line  305)
* kwlist (於 keyword 模組中):            keyword --- 检验Python关键字.
                                                             (line   16)
* L (於 re 模組中):                      模块内容.           (line   66)
* LabelEntry (tkinter.tix 中的類別):     Basic Widgets.      (line   30)
* LabelFrame (tkinter.tix 中的類別):     Basic Widgets.      (line   36)
* lambda:                                術語表.             (line  653)
* Lambda (ast 中的類別):                 Function and class definitions.
                                                             (line   28)
* lambda; expression:                    lambda 表达式.      (line    6)
* lambda; expression <1>:                函数定义.           (line   89)
* lambda; form:                          lambda 表达式.      (line    6)
* LambdaType (於 types 模組中):          标准解释器类型.     (line   17)
* LANG:                                  GNU gettext API.    (line   18)
* LANG <1>:                              基于类的 API.       (line   22)
* LANG <2>:                              locale --- 国际化服务.
                                                             (line   40)
* LANG <3>:                              locale --- 国际化服务.
                                                             (line  255)
* LANG <4>:                              locale --- 国际化服务.
                                                             (line  259)
* LANGUAGE:                              GNU gettext API.    (line   17)
* LANGUAGE <1>:                          基于类的 API.       (line   21)
* large files:                           大文件支持.         (line    6)
* LARGEST (於 test.support 模組中):      test support --- Utilities for the Python test suite.
                                                             (line  210)
* LargeZipFile:                          zipfile --- 使用ZIP存档.
                                                             (line   32)
* last() (nntplib.NNTP 的方法):          方法<3>.            (line  211)
* lastChild (xml.dom.Node 的屬性):       节点对象.           (line   49)
* lastcmd (cmd.Cmd 的屬性):              Cmd 对象.           (line  103)
* lastgroup (re.Match 的屬性):           匹配对象.           (line  158)
* lastindex (re.Match 的屬性):           匹配对象.           (line  152)
* lastResort (於 logging 模組中):        模块级属性.         (line    6)
* lastrowid (sqlite3.Cursor 的屬性):     Cursor 对象.        (line  168)
* last_accepted (multiprocessing.connection.Listener 的屬性): 监听器及客户端.
                                                             (line   91)
* last_traceback (in module sys):        标准类型层级结构.   (line  587)
* last_traceback (於 sys 模組中):        sys --- 系统相关的参数和函数.
                                                             (line  838)
* last_type (於 sys 模組中):             sys --- 系统相关的参数和函数.
                                                             (line  838)
* last_value (於 sys 模組中):            sys --- 系统相关的参数和函数.
                                                             (line  838)
* layout() (tkinter.ttk.Style 的方法):   Ttk 风格.           (line   91)
* lazycache() (於 linecache 模組中):     linecache --- 随机读写文本行.
                                                             (line   42)
* LazyLoader (importlib.util 中的類別):  importlib util —— 导入器的工具程序代码.
                                                             (line  198)
* LBRACE (於 token 模組中):              token --- 与Python解析树一起使用的常量.
                                                             (line  122)
* LBYL:                                  術語表.             (line  659)
* lchflags() (於 os 模組中):             文件和目录.         (line  264)
* lchmod() (pathlib.Path 的方法):        方法<2>.            (line  205)
* lchmod() (於 os 模組中):               文件和目录.         (line  277)
* lchown() (於 os 模組中):               文件和目录.         (line  291)
* lcm() (於 math 模組中):                数论与表示函数.     (line  149)
* LC_ALL:                                GNU gettext API.    (line   17)
* LC_ALL <1>:                            基于类的 API.       (line   21)
* LC_ALL (於 locale 模組中):             locale --- 国际化服务.
                                                             (line  410)
* LC_COLLATE (於 locale 模組中):         locale --- 国际化服务.
                                                             (line  382)
* LC_CTYPE (於 locale 模組中):           locale --- 国际化服务.
                                                             (line  377)
* LC_MESSAGES:                           GNU gettext API.    (line   18)
* LC_MESSAGES <1>:                       基于类的 API.       (line   21)
* LC_MESSAGES (於 locale 模組中):        locale --- 国际化服务.
                                                             (line  397)
* LC_MONETARY (於 locale 模組中):        locale --- 国际化服务.
                                                             (line  392)
* LC_NUMERIC (於 locale 模組中):         locale --- 国际化服务.
                                                             (line  403)
* LC_TIME (於 locale 模組中):            locale --- 国际化服务.
                                                             (line  387)
* LDCXXSHARED:                           构建和 C API 的改变<8>.
                                                             (line  153)
* ldexp() (於 math 模組中):              数论与表示函数.     (line  157)
* LDFLAGS:                               新增，改进和弃用的模块<4>.
                                                             (line   59)
* ldgettext() (於 gettext 模組中):       GNU gettext API.    (line   78)
* ldngettext() (於 gettext 模組中):      GNU gettext API.    (line   82)
* le() (於 operator 模組中):             operator --- 标准运算符替代函数.
                                                             (line   19)
* leading whitespace:                    缩进.               (line    6)
* leapdays() (於 calendar 模組中):       calendar --- 日历相关函数.
                                                             (line  266)
* leaveok() (curses.window 的方法):      Window 对象.        (line  332)
* left (filecmp.dircmp 的屬性):          dircmp 类.          (line   35)
* left() (於 turtle 模組中):             海龟动作.           (line   55)
* LEFTSHIFT (於 token 模組中):           token --- 与Python解析树一起使用的常量.
                                                             (line  154)
* LEFTSHIFTEQUAL (於 token 模組中):      token --- 与Python解析树一起使用的常量.
                                                             (line  198)
* left_list (filecmp.dircmp 的屬性):     dircmp 类.          (line   43)
* left_only (filecmp.dircmp 的屬性):     dircmp 类.          (line   55)
* len() (內建函式):                      內建函式.           (line  749)
* lenfunc (C 型態):                      Slot Type typedefs. (line   92)
* length (xml.dom.NamedNodeMap 的屬性):  NamedNodeMap 对象.  (line    8)
* length (xml.dom.NodeList 的屬性):      节点列表对象.       (line   18)
* length_hint() (於 operator 模組中):    operator --- 标准运算符替代函数.
                                                             (line  191)
* LESS (於 token 模組中):                token --- 与Python解析树一起使用的常量.
                                                             (line  102)
* LESSEQUAL (於 token 模組中):           token --- 与Python解析树一起使用的常量.
                                                             (line  138)
* lexical analysis:                      词法分析.           (line    6)
* lexical definitions:                   标注.               (line   23)
* lexists() (於 os.path 模組中):         os path --- 常用路径操作.
                                                             (line  111)
* lgamma() (於 math 模組中):             特殊函数.           (line   32)
* lgettext() (gettext.GNUTranslations 的方法): GNUTranslations 类.
                                                             (line   78)
* lgettext() (gettext.NullTranslations 的方法): NullTranslations 类.
                                                             (line   53)
* lgettext() (於 gettext 模組中):        GNU gettext API.    (line   76)
* lib2to3 (模組):                        lib2to3 —— 2to3 支持库.
                                                             (line    6)
* libc_ver() (於 platform 模組中):       Unix 平台.          (line    6)
* library (ssl.SSLError 的屬性):         异常<12>.           (line   16)
* library (於 dbm.ndbm 模組中):          dbm ndbm --- 基于 ndbm 的接口.
                                                             (line   22)
* LibraryLoader (ctypes 中的類別):       加载动态链接库.     (line  130)
* library_dir_option() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  219)
* library_filename() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  457)
* library_option() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  224)
* license (內建變數):                    由 site 模块添加的常量.
                                                             (line   22)
* LifoQueue (asyncio 中的類別):          后进先出队列.       (line    6)
* LifoQueue (queue 中的類別):            queue --- 一个同步的队列类.
                                                             (line   35)
* light-weight processes:                _thread --- 底层多线程 API.
                                                             (line    6)
* LimitOverrunError:                     异常<9>.            (line   54)
* limit_denominator() (fractions.Fraction 的方法): fractions --- 分数.
                                                             (line  116)
* lin2adpcm() (於 audioop 模組中):       audioop --- 处理原始音频数据.
                                                             (line   98)
* lin2alaw() (於 audioop 模組中):        audioop --- 处理原始音频数据.
                                                             (line  110)
* lin2lin() (於 audioop 模組中):         audioop --- 处理原始音频数据.
                                                             (line  116)
* lin2ulaw() (於 audioop 模組中):        audioop --- 处理原始音频数据.
                                                             (line  130)
* line continuation:                     显式拼接行.         (line    6)
* line joining:                          逻辑行.             (line    6)
* line joining <1>:                      显式拼接行.         (line    6)
* line structure:                        行结构.             (line    6)
* line() (msilib.Dialog 的方法):         GUI classes.        (line   64)
* line-buffered I/O:                     內建函式.           (line 1030)
* linecache (模組):                      linecache --- 随机读写文本行.
                                                             (line    6)
* lineno (ast.AST 的屬性):               节点类.             (line   32)
* lineno (doctest.DocTest 的屬性):       DocTest 对象.       (line   36)
* lineno (doctest.Example 的屬性):       Example 对象.       (line   34)
* lineno (json.JSONDecodeError 的屬性):  例外.               (line   22)
* lineno (pyclbr.Class 的屬性):          Class 对象.         (line   21)
* lineno (pyclbr.Function 的屬性):       函式物件.           (line   20)
* lineno (re.error 的屬性):              模块内容.           (line  315)
* lineno (shlex.shlex 的屬性):           shlex 对象.         (line  137)
* lineno (SyntaxError 的屬性):           具体异常.           (line  221)
* lineno (traceback.TracebackException 的屬性): TracebackException Objects.
                                                             (line   46)
* lineno (tracemalloc.Filter 的屬性):    过滤器<2>.          (line   48)
* lineno (tracemalloc.Frame 的屬性):     Frame.              (line   17)
* lineno (xml.parsers.expat.ExpatError 的屬性): ExpatError 异常.
                                                             (line   24)
* lineno() (於 fileinput 模組中):        fileinput --- 迭代来自多个输入流的行.
                                                             (line   77)
* LINES:                                 curses<3>.          (line    6)
* LINES <1>:                             函数<4>.            (line  104)
* LINES <2>:                             函数<4>.            (line  462)
* LINES <3>:                             函数<4>.            (line  482)
* LINES <4>:                             函数<4>.            (line  483)
* lines (os.terminal_size 的屬性):       查询终端的尺寸.     (line   31)
* linesep (email.policy.Policy 的屬性):  email policy Policy 对象.
                                                             (line  121)
* linesep (於 os 模組中):                其他系统信息.       (line  106)
* lineterminator (csv.Dialect 的屬性):   变种与格式参数.     (line   36)
* LineTooLong:                           http client --- HTTP 协议客户端.
                                                             (line  160)
* line_buffering (io.TextIOWrapper 的屬性): 文本 I/O<2>.     (line  140)
* line_num (csv.csvreader 的屬性):       Reader 对象.        (line   22)
* link() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  347)
* link() (於 os 模組中):                 文件和目录.         (line  304)
* linkname (tarfile.TarInfo 的屬性):     TarInfo 对象.       (line   61)
* link_executable() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  399)
* link_shared_lib() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  409)
* link_shared_object() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  420)
* link_to() (pathlib.Path 的方法):       方法<2>.            (line  400)
* List (ast 中的類別):                   字面值<3>.          (line   67)
* list (pdb command):                    调试器命令.         (line  169)
* List (typing 中的類別):                对应的内置类型.     (line   19)
* list (內建類別):                       List（串列）<2>.    (line    9)
* list comprehension（串列綜合運算）:    術語表.             (line  677)
* list() (imaplib.IMAP4 的方法):         IMAP4 对象.         (line  114)
* list() (multiprocessing.managers.SyncManager 的方法): 管理器.
                                                             (line  187)
* list() (nntplib.NNTP 的方法):          方法<3>.            (line   91)
* list() (poplib.POP3 的方法):           POP3 对象.          (line   51)
* list() (tarfile.TarFile 的方法):       TarFile 对象.       (line  102)
* list; comprehensions:                  列表显示.           (line    6)
* list; display:                         列表显示.           (line    6)
* ListComp (ast 中的類別):               Comprehensions.     (line    6)
* listdir() (於 os 模組中):              文件和目录.         (line  325)
* listen() (asyncore.dispatcher 的方法): asyncore --- 异步套接字处理器.
                                                             (line  175)
* listen() (socket.socket 的方法):       套接字对象.         (line  160)
* listen() (於 logging.config 模組中):   配置函数.           (line   88)
* listen() (於 turtle 模組中):           使用屏幕事件.       (line    6)
* Listener (multiprocessing.connection 中的類別): 监听器及客户端.
                                                             (line   46)
* listMethods() (xmlrpc.client.ServerProxy.system 的方法): ServerProxy 对象.
                                                             (line   15)
* ListNoteBook (tkinter.tix 中的類別):   Manager Widgets.    (line   13)
* listxattr() (於 os 模組中):            Linux 扩展属性.     (line   25)
* LIST_APPEND (opcode):                  Python字节码说明.   (line  307)
* list_dialects() (於 csv 模組中):       模块内容<3>.        (line   78)
* LIST_EXTEND (opcode):                  Python字节码说明.   (line  489)
* list_folders() (mailbox.Maildir 的方法): Maildir.          (line   49)
* list_folders() (mailbox.MH 的方法):    MH.                 (line   28)
* LIST_TO_TUPLE (opcode):                Python字节码说明.   (line  483)
* list（串列）:                          術語表.             (line  671)
* literal:                               字面值.             (line    6)
* literal <1>:                           字面值<2>.          (line    6)
* Literal (於 typing 模組中):            特殊形式.           (line  128)
* literal_eval() (於 ast 模組中):        ast 中的辅助函数.   (line   72)
* LittleEndianStructure (ctypes 中的類別): 结构化数据类型.   (line   14)
* ljust() (bytearray 的方法):            bytes 和 bytearray 操作.
                                                             (line  252)
* ljust() (bytes 的方法):                bytes 和 bytearray 操作.
                                                             (line  252)
* ljust() (str 的方法):                  字符串的方法<2>.    (line  261)
* LK_LOCK (於 msvcrt 模組中):            文件操作.           (line   17)
* LK_NBLCK (於 msvcrt 模組中):           文件操作.           (line   24)
* LK_NBRLCK (於 msvcrt 模組中):          文件操作.           (line   24)
* LK_RLCK (於 msvcrt 模組中):            文件操作.           (line   17)
* LK_UNLCK (於 msvcrt 模組中):           文件操作.           (line   30)
* ll (pdb command):                      调试器命令.         (line  182)
* LMTP (smtplib 中的類別):               smtplib ---SMTP协议客户端.
                                                             (line   87)
* ln() (decimal.Context 的方法):         上下文对象.         (line  296)
* ln() (decimal.Decimal 的方法):         Decimal 对象.       (line  288)
* LNAME:                                 getpass --- 便携式密码输入工具.
                                                             (line   35)
* lngettext() (gettext.GNUTranslations 的方法): GNUTranslations 类.
                                                             (line   80)
* lngettext() (gettext.NullTranslations 的方法): NullTranslations 类.
                                                             (line   55)
* lngettext() (於 gettext 模組中):       GNU gettext API.    (line   80)
* Load (ast 中的類別):                   Variables.          (line   11)
* load() (http.cookiejar.FileCookieJar 的方法): CookieJar 和 FileCookieJar 对象.
                                                             (line  113)
* load() (http.cookies.BaseCookie 的方法): Cookie 对象.      (line   35)
* load() (pickle.Unpickler 的方法):      模块接口.           (line  234)
* load() (tracemalloc.Snapshot 的類別成員): 快照.            (line   50)
* load() (於 json 模組中):               基本使用.           (line   81)
* load() (於 marshal 模組中):            marshal --- 内部 Python 对象序列化.
                                                             (line   50)
* load() (於 pickle 模組中):             模块接口.           (line   53)
* load() (於 plistlib 模組中):           plistlib --- 生成与解析 Apple plist 文件.
                                                             (line   44)
* loader:                                查找器和加载器.     (line    6)
* Loader (importlib.abc 中的類別):       importlib abc —— 关于导入的抽象基类.
                                                             (line  138)
* loader (importlib.machinery.ModuleSpec 的屬性): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  326)
* LoadError:                             http cookiejar —— HTTP 客户端的 Cookie 处理.
                                                             (line   28)
* loader_state (importlib.machinery.ModuleSpec 的屬性): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  347)
* loader（載入器）:                      術語表.             (line  685)
* LoadFileDialog (tkinter.filedialog 中的類別): 原生 加载/保存 对话框.
                                                             (line  126)
* LoadKey() (於 winreg 模組中):          函数<12>.           (line  239)
* LoadLibrary() (ctypes.LibraryLoader 的方法): 加载动态链接库.
                                                             (line  139)
* loads() (於 json 模組中):              基本使用.           (line  128)
* loads() (於 marshal 模組中):           marshal --- 内部 Python 对象序列化.
                                                             (line   77)
* loads() (於 pickle 模組中):            模块接口.           (line   68)
* loads() (於 plistlib 模組中):          plistlib --- 生成与解析 Apple plist 文件.
                                                             (line   67)
* loads() (於 xmlrpc.client 模組中):     便捷函数.           (line   17)
* loadTestsFromModule() (unittest.TestLoader 的方法): Loading and running tests.
                                                             (line   41)
* loadTestsFromName() (unittest.TestLoader 的方法): Loading and running tests.
                                                             (line   70)
* loadTestsFromNames() (unittest.TestLoader 的方法): Loading and running tests.
                                                             (line  104)
* loadTestsFromTestCase() (unittest.TestLoader 的方法): Loading and running tests.
                                                             (line   29)
* LOAD_ASSERTION_ERROR (opcode):         Python字节码说明.   (line  375)
* LOAD_ATTR (opcode):                    Python字节码说明.   (line  513)
* LOAD_BUILD_CLASS (opcode):             Python字节码说明.   (line  382)
* load_cert_chain() (ssl.SSLContext 的方法): SSL 上下文.     (line   75)
* LOAD_CLASSDEREF (opcode):              Python字节码说明.   (line  625)
* LOAD_CLOSURE (opcode):                 Python字节码说明.   (line  614)
* LOAD_CONST (opcode):                   Python字节码说明.   (line  442)
* load_default_certs() (ssl.SSLContext 的方法): SSL 上下文.  (line   98)
* LOAD_DEREF (opcode):                   Python字节码说明.   (line  620)
* load_dh_params() (ssl.SSLContext 的方法): SSL 上下文.      (line  311)
* load_extension() (sqlite3.Connection 的方法): 连接对象（Connection）.
                                                             (line  272)
* LOAD_FAST (opcode):                    Python字节码说明.   (line  602)
* LOAD_GLOBAL (opcode):                  Python字节码说明.   (line  593)
* LOAD_METHOD (opcode):                  Python字节码说明.   (line  689)
* load_module() (importlib.abc.FileLoader 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  422)
* load_module() (importlib.abc.InspectLoader 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  381)
* load_module() (importlib.abc.Loader 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  171)
* load_module() (importlib.abc.SourceLoader 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  506)
* load_module() (importlib.machinery.SourceFileLoader 的方法): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  213)
* load_module() (importlib.machinery.SourcelessFileLoader 的方法): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  251)
* load_module() (zipimport.zipimporter 的方法): zipimporter 对象.
                                                             (line   56)
* load_module() (於 imp 模組中):         imp —— 由代码内部访问 import 。.
                                                             (line   89)
* LOAD_NAME (opcode):                    Python字节码说明.   (line  446)
* load_package_tests() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  930)
* load_verify_locations() (ssl.SSLContext 的方法): SSL 上下文.
                                                             (line  114)
* local (threading 中的類別):            线程本地数据.       (line   14)
* localcontext() (於 decimal 模組中):    上下文对象.         (line   23)
* LOCALE (於 re 模組中):                 模块内容.           (line   66)
* locale (模組):                         locale --- 国际化服务.
                                                             (line    6)
* localeconv() (於 locale 模組中):       locale --- 国际化服务.
                                                             (line   44)
* LocaleHTMLCalendar (calendar 中的類別): calendar --- 日历相关函数.
                                                             (line  234)
* LocaleTextCalendar (calendar 中的類別): calendar --- 日历相关函数.
                                                             (line  228)
* localName (xml.dom.Attr 的屬性):       Attr 对象.          (line   12)
* localName (xml.dom.Node 的屬性):       节点对象.           (line   53)
* locals() (內建函式):                   內建函式.           (line  765)
* localtime() (於 email.utils 模組中):   email utils 其他工具.
                                                             (line   12)
* localtime() (於 time 模組中):          函数<3>.            (line  125)
* Locator (xml.sax.xmlreader 中的類別):  xml sax xmlreader --- 用于 XML 解析器的接口.
                                                             (line   36)
* Lock (asyncio 中的類別):               Lock.               (line    6)
* Lock (multiprocessing 中的類別):       同步原语.           (line   41)
* Lock (threading 中的類別):             锁对象.             (line   26)
* lock() (mailbox.Babyl 的方法):         Babyl.              (line   47)
* lock() (mailbox.Mailbox 的方法):       Mailbox 对象.       (line  202)
* lock() (mailbox.Maildir 的方法):       Maildir.            (line   90)
* lock() (mailbox.mbox 的方法):          mbox.               (line   32)
* lock() (mailbox.MH 的方法):            MH.                 (line   75)
* lock() (mailbox.MMDF 的方法):          MMDF.               (line   29)
* Lock() (multiprocessing.managers.SyncManager 的方法): 管理器.
                                                             (line  148)
* lock, interpreter:                     Thread State and the Global Interpreter Lock.
                                                             (line    6)
* locked() (asyncio.Condition 的方法):   Condition.          (line   57)
* locked() (asyncio.Lock 的方法):        Lock.               (line   54)
* locked() (asyncio.Semaphore 的方法):   Semaphore.          (line   48)
* locked() (threading.Lock 的方法):      锁对象.             (line   69)
* locked() (_thread.lock 的方法):        _thread --- 底层多线程 API.
                                                             (line  126)
* lockf() (於 fcntl 模組中):             fcntl —— 系统调用 fcntl 和 ioctl.
                                                             (line  104)
* lockf() (於 os 模組中):                文件描述符操作.     (line  190)
* locking() (於 msvcrt 模組中):          文件操作.           (line    6)
* LockType (於 _thread 模組中):          _thread --- 底层多线程 API.
                                                             (line   23)
* lock_held() (於 imp 模組中):           imp —— 由代码内部访问 import 。.
                                                             (line  247)
* log() (logging.Logger 的方法):         记录器对象.         (line  197)
* log() (於 cmath 模組中):               幂函数与对数函数<2>.
                                                             (line   10)
* log() (於 logging 模組中):             模块级函数.         (line  124)
* log() (於 math 模組中):                幂函数与对数函数.   (line   26)
* log10() (decimal.Context 的方法):      上下文对象.         (line  300)
* log10() (decimal.Decimal 的方法):      Decimal 对象.       (line  293)
* log10() (於 cmath 模組中):             幂函数与对数函数<2>.
                                                             (line   15)
* log10() (於 math 模組中):              幂函数与对数函数.   (line   50)
* log1p() (於 math 模組中):              幂函数与对数函数.   (line   33)
* log2() (於 math 模組中):               幂函数与对数函数.   (line   38)
* logb() (decimal.Context 的方法):       上下文对象.         (line  304)
* logb() (decimal.Decimal 的方法):       Decimal 对象.       (line  298)
* Logger (logging 中的類別):             记录器对象.         (line   18)
* LoggerAdapter (logging 中的類別):      LoggerAdapter 对象. (line   10)
* logging (模組):                        logging --- Python 的日志记录工具.
                                                             (line    6)
* logging.config (模組):                 logging config --- 日志记录配置.
                                                             (line    6)
* logging.handlers (模組):               logging handlers --- 日志处理程序.
                                                             (line    6)
* logical line:                          逻辑行.             (line    6)
* logical_and() (decimal.Context 的方法): 上下文对象.        (line  308)
* logical_and() (decimal.Decimal 的方法): Decimal 对象.      (line  305)
* logical_invert() (decimal.Context 的方法): 上下文对象.     (line  312)
* logical_invert() (decimal.Decimal 的方法): Decimal 对象.   (line  311)
* logical_or() (decimal.Context 的方法): 上下文对象.         (line  316)
* logical_or() (decimal.Decimal 的方法): Decimal 对象.       (line  316)
* logical_xor() (decimal.Context 的方法): 上下文对象.        (line  320)
* logical_xor() (decimal.Decimal 的方法): Decimal 对象.      (line  322)
* login() (ftplib.FTP 的方法):           FTP 对象.           (line   39)
* login() (imaplib.IMAP4 的方法):        IMAP4 对象.         (line  120)
* login() (nntplib.NNTP 的方法):         方法<3>.            (line   41)
* login() (smtplib.SMTP 的方法):         SMTP 对象.          (line   84)
* login_cram_md5() (imaplib.IMAP4 的方法): IMAP4 对象.       (line  124)
* LOGNAME:                               进程参数.           (line  199)
* LOGNAME <1>:                           getpass --- 便携式密码输入工具.
                                                             (line   35)
* lognormvariate() (於 random 模組中):   实值分布.           (line   60)
* logout() (imaplib.IMAP4 的方法):       IMAP4 对象.         (line  129)
* LogRecord (logging 中的類別):          LogRecord 属性.     (line   10)
* log_date_time_string() (http.server.BaseHTTPRequestHandler 的方法): http server --- HTTP 服务器.
                                                             (line  271)
* log_error() (http.server.BaseHTTPRequestHandler 的方法): http server --- HTTP 服务器.
                                                             (line  244)
* log_exception() (wsgiref.handlers.BaseHandler 的方法): wsgiref handlers -- 服务器/网关基类.
                                                             (line  174)
* log_message() (http.server.BaseHTTPRequestHandler 的方法): http server --- HTTP 服务器.
                                                             (line  250)
* log_request() (http.server.BaseHTTPRequestHandler 的方法): http server --- HTTP 服务器.
                                                             (line  239)
* log_to_stderr() (於 multiprocessing 模組中): 日志.         (line   21)
* long (2to3 fixer):                     修复器.             (line  173)
* longMessage (unittest.TestCase 的屬性): 测试用例.          (line  671)
* longname() (於 curses 模組中):         函数<4>.            (line  219)
* LONG_MAX:                              整數物件.           (line   95)
* LONG_TIMEOUT (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  128)
* lookup() (symtable.SymbolTable 的方法): 符号表的查看.      (line   46)
* lookup() (tkinter.ttk.Style 的方法):   Ttk 风格.           (line   76)
* lookup() (於 codecs 模組中):           codecs --- 编解码器注册和相关基类.
                                                             (line   39)
* lookup() (於 unicodedata 模組中):      unicodedata --- Unicode 数据库.
                                                             (line   14)
* LookupError:                           基类.               (line   46)
* lookup_error() (於 codecs 模組中):     错误处理方案.       (line   97)
* loop control; target:                  break 语句.         (line   12)
* loop() (於 asyncore 模組中):           asyncore --- 异步套接字处理器.
                                                             (line   39)
* loop; over mutable sequence:           for 语句.           (line   38)
* loop; statement:                       break 语句.         (line    6)
* loop; statement <1>:                   continue 语句.      (line    6)
* loop; statement <2>:                   while 语句.         (line    6)
* loop; statement <3>:                   for 语句.           (line    6)
* LOOPBACK_TIMEOUT (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line   83)
* lower() (bytearray 的方法):            bytes 和 bytearray 操作.
                                                             (line  529)
* lower() (bytes 的方法):                bytes 和 bytearray 操作.
                                                             (line  529)
* lower() (str 的方法):                  字符串的方法<2>.    (line  267)
* LPAR (於 token 模組中):                token --- 与Python解析树一起使用的常量.
                                                             (line   50)
* lpAttributeList (subprocess.STARTUPINFO 的屬性): Windows Popen 助手.
                                                             (line   53)
* lru_cache() (於 functools 模組中):     functools --- 高阶函数和可调用对象上的操作.
                                                             (line  112)
* lseek() (於 os 模組中):                文件描述符操作.     (line  215)
* LShift (ast 中的類別):                 表达式<2>.          (line   54)
* lshift() (於 operator 模組中):         operator --- 标准运算符替代函数.
                                                             (line   94)
* LSQB (於 token 模組中):                token --- 与Python解析树一起使用的常量.
                                                             (line   58)
* lstat() (pathlib.Path 的方法):         方法<2>.            (line  210)
* lstat() (於 os 模組中):                文件和目录.         (line  356)
* lstrip() (bytearray 的方法):           bytes 和 bytearray 操作.
                                                             (line  262)
* lstrip() (bytes 的方法):               bytes 和 bytearray 操作.
                                                             (line  262)
* lstrip() (str 的方法):                 字符串的方法<2>.    (line  273)
* lsub() (imaplib.IMAP4 的方法):         IMAP4 对象.         (line  135)
* Lt (ast 中的類別):                     表达式<2>.          (line  109)
* lt() (於 operator 模組中):             operator --- 标准运算符替代函数.
                                                             (line   19)
* lt() (於 turtle 模組中):               海龟动作.           (line   55)
* LtE (ast 中的類別):                    表达式<2>.          (line  109)
* LWPCookieJar (http.cookiejar 中的類別): FileCookieJar 的子类及其与 Web 浏览器的协同.
                                                             (line   24)
* lzma (模組):                           lzma --- 用 LZMA 算法压缩.
                                                             (line    6)
* LZMACompressor (lzma 中的類別):        在内存中压缩和解压缩数据.
                                                             (line    6)
* LZMADecompressor (lzma 中的類別):      在内存中压缩和解压缩数据.
                                                             (line   79)
* LZMAError:                             lzma --- 用 LZMA 算法压缩.
                                                             (line   21)
* LZMAFile (lzma 中的類別):              读写压缩文件.       (line   40)
* M (於 re 模組中):                      模块内容.           (line   80)
* machine() (於 platform 模組中):        跨平台.             (line   32)
* macros (netrc.netrc 的屬性):           netrc 对象.         (line   27)
* mac_ver() (於 platform 模組中):        macOS Platform.     (line    6)
* madvise() (mmap.mmap 的方法):          mmap --- 内存映射文件支持.
                                                             (line  176)
* MADV_AUTOSYNC (於 mmap 模組中):        MADV_* 常量.        (line    6)
* MADV_CORE (於 mmap 模組中):            MADV_* 常量.        (line    6)
* MADV_DODUMP (於 mmap 模組中):          MADV_* 常量.        (line    6)
* MADV_DOFORK (於 mmap 模組中):          MADV_* 常量.        (line    6)
* MADV_DONTDUMP (於 mmap 模組中):        MADV_* 常量.        (line    6)
* MADV_DONTFORK (於 mmap 模組中):        MADV_* 常量.        (line    6)
* MADV_DONTNEED (於 mmap 模組中):        MADV_* 常量.        (line    6)
* MADV_FREE (於 mmap 模組中):            MADV_* 常量.        (line    6)
* MADV_HUGEPAGE (於 mmap 模組中):        MADV_* 常量.        (line    6)
* MADV_HWPOISON (於 mmap 模組中):        MADV_* 常量.        (line    6)
* MADV_MERGEABLE (於 mmap 模組中):       MADV_* 常量.        (line    6)
* MADV_NOCORE (於 mmap 模組中):          MADV_* 常量.        (line    6)
* MADV_NOHUGEPAGE (於 mmap 模組中):      MADV_* 常量.        (line    6)
* MADV_NORMAL (於 mmap 模組中):          MADV_* 常量.        (line    6)
* MADV_NOSYNC (於 mmap 模組中):          MADV_* 常量.        (line    6)
* MADV_PROTECT (於 mmap 模組中):         MADV_* 常量.        (line    6)
* MADV_RANDOM (於 mmap 模組中):          MADV_* 常量.        (line    6)
* MADV_REMOVE (於 mmap 模組中):          MADV_* 常量.        (line    6)
* MADV_SEQUENTIAL (於 mmap 模組中):      MADV_* 常量.        (line    6)
* MADV_SOFT_OFFLINE (於 mmap 模組中):    MADV_* 常量.        (line    6)
* MADV_UNMERGEABLE (於 mmap 模組中):     MADV_* 常量.        (line    6)
* MADV_WILLNEED (於 mmap 模組中):        MADV_* 常量.        (line    6)
* magic method（魔術方法）:              術語表.             (line  692)
* magic; method:                         術語表.             (line  696)
* MagicMock (unittest.mock 中的類別):    Magic Mock.         (line    9)
* MAGIC_NUMBER (於 importlib.util 模組中): importlib util —— 导入器的工具程序代码.
                                                             (line   12)
* Mailbox (mailbox 中的類別):            Mailbox 对象.       (line    6)
* mailbox (模組):                        mailbox --- 操作多种格式的邮箱.
                                                             (line    6)
* mailcap (模組):                        mailcap --- Mailcap 文件处理.
                                                             (line    6)
* Maildir (mailbox 中的類別):            Maildir.            (line    6)
* MaildirMessage (mailbox 中的類別):     MaildirMessage.     (line    6)
* mailfrom (smtpd.SMTPChannel 的屬性):   SMTPChannel 对象.   (line   63)
* MailmanProxy (smtpd 中的類別):         MailmanProxy 对象.  (line    6)
* main():                                Process-wide parameters.
                                                             (line    9)
* main() <1>:                            Process-wide parameters.
                                                             (line   36)
* main() <2>:                            Process-wide parameters.
                                                             (line  217)
* main() (於 py_compile 模組中):         py_compile --- 编译 Python 源文件.
                                                             (line  102)
* main() (於 site 模組中):               模块内容<8>.        (line   40)
* main() (於 unittest 模組中):           Loading and running tests.
                                                             (line  487)
* mainloop() (於 turtle 模組中):         使用屏幕事件.       (line   98)
* maintype (email.headerregistry.ContentTypeHeader 的屬性): email headerregistry 自定义标头对象.
                                                             (line  226)
* main_thread() (於 threading 模組中):   threading --- 基于线程的并行.
                                                             (line  100)
* major (email.headerregistry.MIMEVersionHeader 的屬性): email headerregistry 自定义标头对象.
                                                             (line  199)
* major() (於 os 模組中):                文件和目录.         (line  475)
* makedev() (於 os 模組中):              文件和目录.         (line  485)
* makedirs() (於 os 模組中):             文件和目录.         (line  406)
* makeelement() (xml.etree.ElementTree.Element 的方法): 元素对象.
                                                             (line  139)
* makefile() (socket method):            标准类型层级结构.   (line  492)
* makefile() (socket.socket 的方法):     套接字对象.         (line  168)
* makeLogRecord() (於 logging 模組中):   模块级函数.         (line  189)
* makePickle() (logging.handlers.SocketHandler 的方法): SocketHandler.
                                                             (line   38)
* makeRecord() (logging.Logger 的方法):  记录器对象.         (line  249)
* makeSocket() (logging.handlers.DatagramHandler 的方法): DatagramHandler.
                                                             (line   24)
* makeSocket() (logging.handlers.SocketHandler 的方法): SocketHandler.
                                                             (line   33)
* maketrans() (bytearray 的靜態成員):    bytes 和 bytearray 操作.
                                                             (line  148)
* maketrans() (bytes 的靜態成員):        bytes 和 bytearray 操作.
                                                             (line  148)
* maketrans() (str 的靜態成員):          字符串的方法<2>.    (line  292)
* make_alternative() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  514)
* make_archive() (於 distutils.archive_util 模組中): distutils archive_util --- Archiving utilities.
                                                             (line    9)
* make_archive() (於 shutil 模組中):     归档操作.           (line   13)
* make_bad_fd() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  745)
* make_cookies() (http.cookiejar.CookieJar 的方法): CookieJar 和 FileCookieJar 对象.
                                                             (line   54)
* make_dataclass() (於 dataclasses 模組中): 模块级装饰器、类和函数.
                                                             (line  271)
* make_file() (difflib.HtmlDiff 的方法): difflib --- 计算差异的辅助工具.
                                                             (line   92)
* MAKE_FUNCTION (opcode):                Python字节码说明.   (line  709)
* make_header() (於 email.header 模組中): email header 国际化标头.
                                                             (line  158)
* make_legacy_pyc() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  250)
* make_mixed() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  522)
* make_msgid() (於 email.utils 模組中):  email utils 其他工具.
                                                             (line   23)
* make_parser() (於 xml.sax 模組中):     xml sax --- 支持 SAX2 解析器.
                                                             (line   24)
* make_pkg() (於 test.support.script_helper 模組中): test support script_helper --- Utilities for the Python execution tests.
                                                             (line   95)
* make_related() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  507)
* make_script() (於 test.support.script_helper 模組中): test support script_helper --- Utilities for the Python execution tests.
                                                             (line   80)
* make_server() (於 wsgiref.simple_server 模組中): wsgiref simple_server -- 一个简单的 WSGI HTTP 服务器.
                                                             (line   13)
* make_table() (difflib.HtmlDiff 的方法): difflib --- 计算差异的辅助工具.
                                                             (line  117)
* make_tarball() (於 distutils.archive_util 模組中): distutils archive_util --- Archiving utilities.
                                                             (line   25)
* make_zipfile() (於 distutils.archive_util 模組中): distutils archive_util --- Archiving utilities.
                                                             (line   39)
* make_zip_pkg() (於 test.support.script_helper 模組中): test support script_helper --- Utilities for the Python execution tests.
                                                             (line  100)
* make_zip_script() (於 test.support.script_helper 模組中): test support script_helper --- Utilities for the Python execution tests.
                                                             (line   87)
* malloc():                              總覽<2>.            (line   23)
* mangle_from_ (email.policy.Compat32 的屬性): email policy Policy 对象.
                                                             (line  450)
* mangle_from_ (email.policy.Policy 的屬性): email policy Policy 对象.
                                                             (line  150)
* map (2to3 fixer):                      修复器.             (line  177)
* map() (concurrent.futures.Executor 的方法): Executor 对象. (line   20)
* map() (multiprocessing.pool.Pool 的方法): 进程池.          (line   71)
* map() (tkinter.ttk.Style 的方法):      Ttk 风格.           (line   44)
* map() (內建函式):                      內建函式.           (line  774)
* mapLogRecord() (logging.handlers.HTTPHandler 的方法): HTTPHandler.
                                                             (line   24)
* Mapping (collections.abc 中的類別):    容器抽象基类.       (line  175)
* Mapping (typing 中的類別):             collections abc 对应的容器.
                                                             (line   55)
* mapping() (msilib.Control 的方法):     GUI classes.        (line   20)
* MappingProxyType (types 中的類別):     标准解释器类型.     (line  211)
* MappingView (collections.abc 中的類別): 容器抽象基类.      (line  180)
* MappingView (typing 中的類別):         collections abc 对应的容器.
                                                             (line   65)
* mapping（對映）:                       術語表.             (line  696)
* mapPriority() (logging.handlers.SysLogHandler 的方法): SysLogHandler.
                                                             (line  167)
* maps (collections.ChainMap 的屬性):    ChainMap objects.   (line   32)
* maps() (於 nis 模組中):                nis --- Sun 的 NIS 黄页 接口.
                                                             (line   36)
* MAP_ADD (opcode):                      Python字节码说明.   (line  311)
* map_async() (multiprocessing.pool.Pool 的方法): 进程池.    (line   84)
* map_table_b2() (於 stringprep 模組中): stringprep --- 因特网字符串预备.
                                                             (line   37)
* map_table_b3() (於 stringprep 模組中): stringprep --- 因特网字符串预备.
                                                             (line   42)
* map_to_type() (email.headerregistry.HeaderRegistry 的方法): email headerregistry 自定义标头对象.
                                                             (line  323)
* marshal (模組):                        marshal --- 内部 Python 对象序列化.
                                                             (line    6)
* marshalling; objects:                  pickle --- Python 对象序列化.
                                                             (line    8)
* masking; operations:                   整数类型的按位运算. (line    6)
* Match (typing 中的類別):               其他具象类型.       (line   18)
* match() (pathlib.PurePath 的方法):     方法和特征属性.     (line  219)
* match() (re.Pattern 的方法):           正则表达式对象 （正则对象）.
                                                             (line   29)
* match() (於 nis 模組中):               nis --- Sun 的 NIS 黄页 接口.
                                                             (line   15)
* match() (於 re 模組中):                模块内容.           (line  117)
* Matcher (test.support 中的類別):       test support --- Utilities for the Python test suite.
                                                             (line 1106)
* matches() (test.support.Matcher 的方法): test support --- Utilities for the Python test suite.
                                                             (line 1108)
* match_hostname() (於 ssl 模組中):      证书处理.           (line    6)
* match_test() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  306)
* match_value() (test.support.Matcher 的方法): test support --- Utilities for the Python test suite.
                                                             (line 1112)
* math (模組):                           math --- 数学函数.  (line    6)
* matmul() (於 operator 模組中):         operator --- 标准运算符替代函数.
                                                             (line  109)
* MatMult (ast 中的類別):                表达式<2>.          (line   54)
* matrix multiplication:                 二元算术运算符.     (line   23)
* max (datetime.date 的屬性):            date 对象.          (line   84)
* max (datetime.datetime 的屬性):        datetime 对象.      (line  231)
* max (datetime.time 的屬性):            time 对象.          (line   34)
* max (datetime.timedelta 的屬性):       timedelta 类对象.   (line   73)
* max() (decimal.Context 的方法):        上下文对象.         (line  324)
* max() (decimal.Decimal 的方法):        Decimal 对象.       (line  328)
* max() (內建函式):                      內建函式.           (line  782)
* max() (於 audioop 模組中):             audioop --- 处理原始音频数据.
                                                             (line  136)
* maxarray (reprlib.Repr 的屬性):        Repr 对象.          (line   13)
* maxdeque (reprlib.Repr 的屬性):        Repr 对象.          (line   13)
* maxdict (reprlib.Repr 的屬性):         Repr 对象.          (line   13)
* maxDiff (unittest.TestCase 的屬性):    测试用例.           (line  688)
* maxfrozenset (reprlib.Repr 的屬性):    Repr 对象.          (line   13)
* MAXIMUM_SUPPORTED (ssl.TLSVersion 的屬性): 常量<3>.        (line  479)
* maximum_version (ssl.SSLContext 的屬性): SSL 上下文.       (line  472)
* maxlen (collections.deque 的屬性):     deque 对象.         (line  108)
* maxlevel (reprlib.Repr 的屬性):        Repr 对象.          (line    9)
* maxlist (reprlib.Repr 的屬性):         Repr 对象.          (line   13)
* maxlong (reprlib.Repr 的屬性):         Repr 对象.          (line   24)
* maxother (reprlib.Repr 的屬性):        Repr 对象.          (line   34)
* maxpp() (於 audioop 模組中):           audioop --- 处理原始音频数据.
                                                             (line  140)
* maxset (reprlib.Repr 的屬性):          Repr 对象.          (line   13)
* maxsize (asyncio.Queue 的屬性):        队列.               (line   22)
* maxsize (於 sys 模組中):               sys --- 系统相关的参数和函数.
                                                             (line  850)
* maxstring (reprlib.Repr 的屬性):       Repr 对象.          (line   28)
* maxtuple (reprlib.Repr 的屬性):        Repr 对象.          (line   13)
* maxunicode (於 sys 模組中):            sys --- 系统相关的参数和函数.
                                                             (line  855)
* MAXYEAR (於 datetime 模組中):          常量.               (line   13)
* max_count (email.headerregistry.BaseHeader 的屬性): email headerregistry 自定义标头对象.
                                                             (line   50)
* MAX_EMAX (於 decimal 模組中):          常数<3>.            (line   15)
* MAX_INTERPOLATION_DEPTH (於 configparser 模組中): ConfigParser 对象.
                                                             (line  283)
* max_lines (textwrap.TextWrapper 的屬性): textwrap --- 文本自动换行与填充.
                                                             (line  235)
* max_line_length (email.policy.Policy 的屬性): email policy Policy 对象.
                                                             (line  115)
* max_mag() (decimal.Context 的方法):    上下文对象.         (line  328)
* max_mag() (decimal.Decimal 的方法):    Decimal 对象.       (line  334)
* max_memuse (於 test.support 模組中):   test support --- Utilities for the Python test suite.
                                                             (line  177)
* MAX_PREC (於 decimal 模組中):          常数<3>.            (line   12)
* max_prefixlen (ipaddress.IPv4Address 的屬性): 地址对象.    (line   49)
* max_prefixlen (ipaddress.IPv4Network 的屬性): 网络对象.    (line   53)
* max_prefixlen (ipaddress.IPv6Address 的屬性): 地址对象.    (line  197)
* max_prefixlen (ipaddress.IPv6Network 的屬性): 网络对象.    (line  261)
* MAX_Py_ssize_t (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  173)
* mbox (mailbox 中的類別):               mbox.               (line    6)
* mboxMessage (mailbox 中的類別):        mboxMessage.        (line    6)
* MB_ICONASTERISK (於 winsound 模組中):  winsound —— Windows 系统的声音播放接口.
                                                             (line  118)
* MB_ICONEXCLAMATION (於 winsound 模組中): winsound —— Windows 系统的声音播放接口.
                                                             (line  122)
* MB_ICONHAND (於 winsound 模組中):      winsound —— Windows 系统的声音播放接口.
                                                             (line  126)
* MB_ICONQUESTION (於 winsound 模組中):  winsound —— Windows 系统的声音播放接口.
                                                             (line  130)
* MB_OK (於 winsound 模組中):            winsound —— Windows 系统的声音播放接口.
                                                             (line  134)
* mean (statistics.NormalDist 的屬性):   NormalDist 对象.    (line   18)
* mean() (於 statistics 模組中):         函式細節.           (line    9)
* measure() (tkinter.font.Font 的方法):  tkinter font --- Tkinter 字体封装.
                                                             (line   61)
* median (statistics.NormalDist 的屬性): NormalDist 对象.    (line   22)
* median() (於 statistics 模組中):       函式細節.           (line  104)
* median_grouped() (於 statistics 模組中): 函式細節.         (line  160)
* median_high() (於 statistics 模組中):  函式細節.           (line  144)
* median_low() (於 statistics 模組中):   函式細節.           (line  128)
* MemberDescriptorType (於 types 模組中): 标准解释器类型.    (line  201)
* membership; test:                      成员检测运算.       (line   30)
* memfd_create() (於 os 模組中):         文件和目录.         (line 1434)
* memmove() (於 ctypes 模組中):          工具函数.           (line  118)
* MemoryBIO (ssl 中的類別):              内存 BIO 支持<2>.   (line  118)
* MemoryError:                           具体异常.           (line   69)
* MemoryHandler (logging.handlers 中的類別): MemoryHandler.  (line   35)
* memoryview (內建類別):                 内存视图.           (line    9)
* memset() (於 ctypes 模組中):           工具函数.           (line  123)
* merge() (於 heapq 模組中):             heapq --- 堆積佇列 heap queue 演算法.
                                                             (line   67)
* Message (email.message 中的類別):      email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line   38)
* Message (mailbox 中的類別):            Message 对象.       (line    6)
* Message (tkinter.messagebox 中的類別): tkinter messagebox --- Tkinter 消息提示.
                                                             (line   17)
* message digest, MD5:                   hashlib --- 安全哈希与消息摘要.
                                                             (line    8)
* MessageBeep() (於 winsound 模組中):    winsound —— Windows 系统的声音播放接口.
                                                             (line   27)
* MessageClass (http.server.BaseHTTPRequestHandler 的屬性): http server --- HTTP 服务器.
                                                             (line  142)
* MessageError:                          email errors 异常和缺陷类.
                                                             (line   12)
* MessageParseError:                     email errors 异常和缺陷类.
                                                             (line   17)
* messages (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line   20)
* message_factory (email.policy.Policy 的屬性): email policy Policy 对象.
                                                             (line  158)
* message_from_binary_file() (於 email 模組中): Parser API.  (line  113)
* message_from_bytes() (於 email 模組中): Parser API.        (line  102)
* message_from_file() (於 email 模組中): Parser API.         (line  133)
* message_from_string() (於 email 模組中): Parser API.       (line  124)
* meta hooks:                            导入钩子.           (line    6)
* meta path finder（元路徑尋檢器）:      術語表.             (line  704)
* meta() (於 curses 模組中):             函数<4>.            (line  225)
* metaclass:                             元类.               (line    6)
* metaclass (2to3 fixer):                修复器.             (line  183)
* metaclass hint:                        确定适当的元类.     (line    6)
* metaclass（元類別）:                   術語表.             (line  713)
* MetaPathFinder (importlib.abc 中的類別): importlib abc —— 关于导入的抽象基类.
                                                             (line   44)
* metavar (optparse.Option 的屬性):      Option attributes.  (line   80)
* MetavarTypeHelpFormatter (argparse 中的類別): formatter_class.
                                                             (line    9)
* meta_path (於 sys 模組中):             sys --- 系统相关的参数和函数.
                                                             (line  864)
* Meter (tkinter.tix 中的類別):          Basic Widgets.      (line   43)
* method (urllib.request.Request 的屬性): Request 对象.      (line   48)
* method resolution order（方法解析順序）: 術語表.           (line  732)
* method; call:                          调用.               (line  105)
* methodattrs (2to3 fixer):              修复器.             (line  188)
* methodcaller() (於 operator 模組中):   operator --- 标准运算符替代函数.
                                                             (line  285)
* MethodDescriptorType (於 types 模組中): 标准解释器类型.    (line   91)
* methodHelp() (xmlrpc.client.ServerProxy.system 的方法): ServerProxy 对象.
                                                             (line   36)
* methods (pyclbr.Class 的屬性):         Class 对象.         (line   43)
* methods (於 crypt 模組中):             模块属性.           (line    8)
* methodSignature() (xmlrpc.client.ServerProxy.system 的方法): ServerProxy 对象.
                                                             (line   20)
* MethodType (in module types):          函式（Function）物件.
                                                             (line   14)
* MethodType (in module types) <1>:      方法对象.           (line   11)
* MethodType (於 types 模組中):          标准解释器类型.     (line   67)
* MethodWrapperType (於 types 模組中):   标准解释器类型.     (line   84)
* METHOD_BLOWFISH (於 crypt 模組中):     哈希方法.           (line   21)
* method_calls (unittest.mock.Mock 的屬性): Mock 类.         (line  463)
* METHOD_CRYPT (於 crypt 模組中):        哈希方法.           (line   33)
* METHOD_MD5 (於 crypt 模組中):          哈希方法.           (line   28)
* METHOD_SHA256 (於 crypt 模組中):       哈希方法.           (line   16)
* METHOD_SHA512 (於 crypt 模組中):       哈希方法.           (line   11)
* method（方法）:                        術語表.             (line  725)
* METH_CLASS (內建變數):                 Implementing functions and methods.
                                                             (line  182)
* METH_COEXIST (內建變數):               Implementing functions and methods.
                                                             (line  199)
* METH_FASTCALL (內建變數):              Implementing functions and methods.
                                                             (line  119)
* METH_NOARGS (內建變數):                Implementing functions and methods.
                                                             (line  160)
* METH_O (內建變數):                     Implementing functions and methods.
                                                             (line  169)
* METH_STATIC (內建變數):                Implementing functions and methods.
                                                             (line  189)
* METH_VARARGS (內建變數):               Implementing functions and methods.
                                                             (line  100)
* metrics() (tkinter.font.Font 的方法):  tkinter font --- Tkinter 字体封装.
                                                             (line   66)
* MFD_ALLOW_SEALING (於 os 模組中):      文件和目录.         (line 1450)
* MFD_CLOEXEC (於 os 模組中):            文件和目录.         (line 1450)
* MFD_HUGETLB (於 os 模組中):            文件和目录.         (line 1450)
* MFD_HUGE_16GB (於 os 模組中):          文件和目录.         (line 1450)
* MFD_HUGE_16MB (於 os 模組中):          文件和目录.         (line 1450)
* MFD_HUGE_1GB (於 os 模組中):           文件和目录.         (line 1450)
* MFD_HUGE_1MB (於 os 模組中):           文件和目录.         (line 1450)
* MFD_HUGE_256MB (於 os 模組中):         文件和目录.         (line 1450)
* MFD_HUGE_2GB (於 os 模組中):           文件和目录.         (line 1450)
* MFD_HUGE_2MB (於 os 模組中):           文件和目录.         (line 1450)
* MFD_HUGE_32MB (於 os 模組中):          文件和目录.         (line 1450)
* MFD_HUGE_512KB (於 os 模組中):         文件和目录.         (line 1450)
* MFD_HUGE_512MB (於 os 模組中):         文件和目录.         (line 1450)
* MFD_HUGE_64KB (於 os 模組中):          文件和目录.         (line 1450)
* MFD_HUGE_8MB (於 os 模組中):           文件和目录.         (line 1450)
* MFD_HUGE_MASK (於 os 模組中):          文件和目录.         (line 1450)
* MFD_HUGE_SHIFT (於 os 模組中):         文件和目录.         (line 1450)
* MH (mailbox 中的類別):                 MH.                 (line    6)
* MHMessage (mailbox 中的類別):          MHMessage.          (line    6)
* microsecond (datetime.datetime 的屬性): datetime 对象.     (line  267)
* microsecond (datetime.time 的屬性):    time 对象.          (line   58)
* MIME; base64 encoding:                 base64 —— Base16、Base32、Base64、Base85 資料編碼.
                                                             (line    8)
* MIME; content type:                    mimetypes --- 映射文件名到 MIME 类型.
                                                             (line    8)
* MIME; headers:                         mimetypes --- 映射文件名到 MIME 类型.
                                                             (line   23)
* MIME; headers <1>:                     cgi --- 通用网关接口支持.
                                                             (line    8)
* MIME; quoted-printable encoding:       quopri --- 编码与解码经过 MIME 转码的可打印数据.
                                                             (line    8)
* MIMEApplication (email.mime.application 中的類別): email mime 从头创建电子邮件和 MIME 对象.
                                                             (line   82)
* MIMEAudio (email.mime.audio 中的類別): email mime 从头创建电子邮件和 MIME 对象.
                                                             (line  108)
* MIMEBase (email.mime.base 中的類別):   email mime 从头创建电子邮件和 MIME 对象.
                                                             (line   26)
* MIMEImage (email.mime.image 中的類別): email mime 从头创建电子邮件和 MIME 对象.
                                                             (line  135)
* MIMEMessage (email.mime.message 中的類別): email mime 从头创建电子邮件和 MIME 对象.
                                                             (line  162)
* MIMEMultipart (email.mime.multipart 中的類別): email mime 从头创建电子邮件和 MIME 对象.
                                                             (line   58)
* MIMENonMultipart (email.mime.nonmultipart 中的類別): email mime 从头创建电子邮件和 MIME 对象.
                                                             (line   49)
* MIMEPart (email.message 中的類別):     email message 表示一封电子邮件信息.
                                                             (line  605)
* MIMEText (email.mime.text 中的類別):   email mime 从头创建电子邮件和 MIME 对象.
                                                             (line  178)
* MimeTypes (mimetypes 中的類別):        MimeTypes 对象.     (line    9)
* mimetypes (模組):                      mimetypes --- 映射文件名到 MIME 类型.
                                                             (line    6)
* MIMEVersionHeader (email.headerregistry 中的類別): email headerregistry 自定义标头对象.
                                                             (line  189)
* min (datetime.date 的屬性):            date 对象.          (line   80)
* min (datetime.datetime 的屬性):        datetime 对象.      (line  226)
* min (datetime.time 的屬性):            time 对象.          (line   30)
* min (datetime.timedelta 的屬性):       timedelta 类对象.   (line   68)
* min() (decimal.Context 的方法):        上下文对象.         (line  332)
* min() (decimal.Decimal 的方法):        Decimal 对象.       (line  338)
* min() (內建函式):                      內建函式.           (line  810)
* MINEQUAL (於 token 模組中):            token --- 与Python解析树一起使用的常量.
                                                             (line  170)
* MINIMUM_SUPPORTED (ssl.TLSVersion 的屬性): 常量<3>.        (line  477)
* minimum_version (ssl.SSLContext 的屬性): SSL 上下文.       (line  490)
* minmax() (於 audioop 模組中):          audioop --- 处理原始音频数据.
                                                             (line  144)
* minor (email.headerregistry.MIMEVersionHeader 的屬性): email headerregistry 自定义标头对象.
                                                             (line  203)
* minor() (於 os 模組中):                文件和目录.         (line  480)
* minus:                                 一元算术和位运算.   (line   10)
* MINUS (於 token 模組中):               token --- 与Python解析树一起使用的常量.
                                                             (line   82)
* minus() (decimal.Context 的方法):      上下文对象.         (line  340)
* minute (datetime.datetime 的屬性):     datetime 对象.      (line  259)
* minute (datetime.time 的屬性):         time 对象.          (line   50)
* MINYEAR (於 datetime 模組中):          常量.               (line    8)
* MIN_EMIN (於 decimal 模組中):          常数<3>.            (line   18)
* MIN_ETINY (於 decimal 模組中):         常数<3>.            (line   21)
* min_mag() (decimal.Context 的方法):    上下文对象.         (line  336)
* min_mag() (decimal.Decimal 的方法):    Decimal 对象.       (line  344)
* mirrored() (於 unicodedata 模組中):    unicodedata --- Unicode 数据库.
                                                             (line   59)
* misc_header (cmd.Cmd 的屬性):          Cmd 对象.           (line  122)
* MISSING (contextvars.Token 的屬性):    上下文变量.         (line   81)
* MissingSectionHeaderError:             异常<5>.            (line   51)
* missing_compiler_executable() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  981)
* MISSING_C_DOCSTRINGS (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  187)
* MIXERDEV:                              ossaudiodev --- 访问兼容OSS的音频设备.
                                                             (line   62)
* mkd() (ftplib.FTP 的方法):             FTP 对象.           (line  180)
* mkdir() (pathlib.Path 的方法):         方法<2>.            (line  215)
* mkdir() (於 os 模組中):                文件和目录.         (line  384)
* mkdtemp() (於 tempfile 模組中):        tempfile --- 生成临时文件和目录.
                                                             (line  167)
* mkfifo() (於 os 模組中):               文件和目录.         (line  438)
* mknod() (於 os 模組中):                文件和目录.         (line  457)
* mkpath() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  491)
* mkpath() (於 distutils.dir_util 模組中): distutils dir_util --- Directory tree operations.
                                                             (line    9)
* mksalt() (於 crypt 模組中):            模块函数<2>.        (line   31)
* mkstemp() (於 tempfile 模組中):        tempfile --- 生成临时文件和目录.
                                                             (line  119)
* mktemp() (於 tempfile 模組中):         已弃用的函数和变量. (line   12)
* mktime() (於 time 模組中):             函数<3>.            (line  131)
* mktime_tz() (於 email.utils 模組中):   email utils 其他工具.
                                                             (line  111)
* mlsd() (ftplib.FTP 的方法):            FTP 对象.           (line  135)
* mmap (mmap 中的類別):                  mmap --- 内存映射文件支持.
                                                             (line   38)
* mmap (模組):                           mmap --- 内存映射文件支持.
                                                             (line    6)
* MMDF (mailbox 中的類別):               MMDF.               (line    6)
* MMDFMessage (mailbox 中的類別):        MMDFMessage.        (line    6)
* Mock (unittest.mock 中的類別):         Mock 类.            (line   19)
* mock_add_spec() (unittest.mock.Mock 的方法): Mock 类.      (line  207)
* mock_calls (unittest.mock.Mock 的屬性): Mock 类.           (line  481)
* mock_open() (於 unittest.mock 模組中): mock_open.          (line    6)
* Mod (ast 中的類別):                    表达式<2>.          (line   54)
* mod() (於 operator 模組中):            operator --- 标准运算符替代函数.
                                                             (line   99)
* mode (io.FileIO 的屬性):               原始文件 I/O.       (line   46)
* mode (ossaudiodev.oss_audio_device 的屬性): 音频设备对象.  (line  221)
* mode (statistics.NormalDist 的屬性):   NormalDist 对象.    (line   26)
* mode (tarfile.TarInfo 的屬性):         TarInfo 对象.       (line   50)
* mode() (於 statistics 模組中):         函式細節.           (line  200)
* mode() (於 turtle 模組中):             设置与特殊方法.     (line    6)
* modf() (於 math 模組中):               数论与表示函数.     (line  161)
* modified() (urllib.robotparser.RobotFileParser 的方法): urllib robotparser --- robots txt 语法分析程序.
                                                             (line   42)
* Modify() (msilib.View 的方法):         View Objects.       (line   23)
* modify() (select.devpoll 的方法):      /dev/poll 轮询对象. (line   45)
* modify() (select.epoll 的方法):        边缘触发和水平触发的轮询 epoll 对象.
                                                             (line   83)
* modify() (select.poll 的方法):         Poll 对象.          (line   51)
* modify() (selectors.BaseSelector 的方法): 类<2>.           (line   85)
* module (pyclbr.Class 的屬性):          Class 对象.         (line   13)
* module (pyclbr.Function 的屬性):       函式物件.           (line   12)
* module spec:                           查找器和加载器.     (line    6)
* module spec（模組規格）:               術語表.             (line  746)
* module; importing:                     import 语句.        (line    6)
* module; namespace:                     标准类型层级结构.   (line  418)
* module; search; path:                  模組的搜尋路徑.     (line    6)
* module; search; path <1>:              linecache --- 随机读写文本行.
                                                             (line   25)
* module; search; path <2>:              sys --- 系统相关的参数和函数.
                                                             (line  897)
* module; search; path <3>:              site —— 指定域的配置钩子.
                                                             (line   13)
* module; search; path <4>:              嵌入式Python.       (line   12)
* module; search; path <5>:              Initializing and finalizing the interpreter.
                                                             (line    8)
* module; search; path <6>:              Process-wide parameters.
                                                             (line  120)
* module; search; path <7>:              Process-wide parameters.
                                                             (line  133)
* ModuleFinder (modulefinder 中的類別):  modulefinder --- 查找脚本使用的模块.
                                                             (line   22)
* modulefinder (模組):                   modulefinder --- 查找脚本使用的模块.
                                                             (line    6)
* ModuleInfo (pkgutil 中的類別):         pkgutil --- 包扩展工具.
                                                             (line   12)
* ModuleNotFoundError:                   具体异常.           (line   45)
* modules (in module sys):               匯入模組<2>.        (line    7)
* modules (in module sys) <1>:           Initializing and finalizing the interpreter.
                                                             (line    8)
* modules (modulefinder.ModuleFinder 的屬性): modulefinder --- 查找脚本使用的模块.
                                                             (line   41)
* modules (於 sys 模組中):               sys --- 系统相关的参数和函数.
                                                             (line  889)
* ModuleSpec (importlib.machinery 中的類別): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  308)
* modules_cleanup() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  837)
* modules_setup() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  833)
* ModuleType (in module types):          模組物件模組.       (line    8)
* ModuleType (types 中的類別):           标准解释器类型.     (line  104)
* module_for_loader() (於 importlib.util 模組中): importlib util —— 导入器的工具程序代码.
                                                             (line  122)
* module_from_spec() (於 importlib.util 模組中): importlib util —— 导入器的工具程序代码.
                                                             (line  108)
* module_repr() (importlib.abc.Loader 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  237)
* module（模組）:                        術語表.             (line  738)
* modulo:                                二元算术运算符.     (line   36)
* monotonic() (於 time 模組中):          函数<3>.            (line  141)
* monotonic_ns() (於 time 模組中):       函数<3>.            (line  151)
* month (datetime.date 的屬性):          date 对象.          (line   98)
* month (datetime.datetime 的屬性):      datetime 对象.      (line  247)
* month() (於 calendar 模組中):          calendar --- 日历相关函数.
                                                             (line  296)
* monthcalendar() (於 calendar 模組中):  calendar --- 日历相关函数.
                                                             (line  286)
* monthdatescalendar() (calendar.Calendar 的方法): calendar --- 日历相关函数.
                                                             (line   73)
* monthdays2calendar() (calendar.Calendar 的方法): calendar --- 日历相关函数.
                                                             (line   78)
* monthdayscalendar() (calendar.Calendar 的方法): calendar --- 日历相关函数.
                                                             (line   83)
* monthrange() (於 calendar 模組中):     calendar --- 日历相关函数.
                                                             (line  282)
* month_abbr (於 calendar 模組中):       calendar --- 日历相关函数.
                                                             (line  332)
* month_name (於 calendar 模組中):       calendar --- 日历相关函数.
                                                             (line  327)
* Morsel (http.cookies 中的類別):        Morsel 对象.        (line    6)
* most_common() (collections.Counter 的方法): Counter 物件.  (line   69)
* mouseinterval() (於 curses 模組中):    函数<4>.            (line  230)
* mousemask() (於 curses 模組中):        函数<4>.            (line  235)
* move() (curses.panel.Panel 的方法):    Panel 对象.         (line   32)
* move() (curses.window 的方法):         Window 对象.        (line  339)
* move() (mmap.mmap 的方法):             mmap --- 内存映射文件支持.
                                                             (line  188)
* move() (tkinter.ttk.Treeview 的方法):  ttk Treeview.       (line  188)
* move() (於 shutil 模組中):             目录和文件操作.     (line  251)
* move_file() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  496)
* move_file() (於 distutils.file_util 模組中): distutils file_util --- Single file operations.
                                                             (line   34)
* move_to_end() (collections.OrderedDict 的方法): OrderedDict 对象.
                                                             (line   46)
* MozillaCookieJar (http.cookiejar 中的類別): FileCookieJar 的子类及其与 Web 浏览器的协同.
                                                             (line    8)
* MRO:                                   術語表.             (line  751)
* mro() (class 的方法):                  特殊属性.           (line   35)
* msg (http.client.HTTPResponse 的屬性): HTTPResponse 对象.  (line   37)
* msg (json.JSONDecodeError 的屬性):     例外.               (line   10)
* msg (re.error 的屬性):                 模块内容.           (line  303)
* msg (traceback.TracebackException 的屬性): TracebackException Objects.
                                                             (line   59)
* msg() (telnetlib.Telnet 的方法):       Telnet 对象.        (line   71)
* msi:                                   msilib --- Read and write Microsoft Installer files.
                                                             (line    8)
* msilib (模組):                         msilib --- Read and write Microsoft Installer files.
                                                             (line    6)
* msvcrt (模組):                         msvcrt --- 来自 MS VC++ 运行时的有用例程.
                                                             (line    6)
* mtime (gzip.GzipFile 的屬性):          gzip --- 对 gzip 格式的支持.
                                                             (line  120)
* mtime (tarfile.TarInfo 的屬性):        TarInfo 对象.       (line   46)
* mtime() (urllib.robotparser.RobotFileParser 的方法): urllib robotparser --- robots txt 语法分析程序.
                                                             (line   37)
* mt_interact() (telnetlib.Telnet 的方法): Telnet 对象.      (line  108)
* mul() (於 audioop 模組中):             audioop --- 处理原始音频数据.
                                                             (line  148)
* mul() (於 operator 模組中):            operator --- 标准运算符替代函数.
                                                             (line  104)
* Mult (ast 中的類別):                   表达式<2>.          (line   54)
* MultiCall (xmlrpc.client 中的類別):    MultiCall 对象.     (line    9)
* MULTILINE (於 re 模組中):              模块内容.           (line   80)
* MultiLoopChildWatcher (asyncio 中的類別): 进程监视器.      (line   87)
* multimode() (於 statistics 模組中):    函式細節.           (line  225)
* MultipartConversionError:              email errors 异常和缺陷类.
                                                             (line   36)
* multiplication:                        二元算术运算符.     (line   15)
* multiply() (decimal.Context 的方法):   上下文对象.         (line  344)
* multiprocessing (模組):                multiprocessing --- 基于进程的并行.
                                                             (line    6)
* multiprocessing.connection (模組):     监听器及客户端.     (line    6)
* multiprocessing.dummy (模組):          multiprocessing dummy 模块.
                                                             (line    6)
* multiprocessing.Manager() (於 multiprocessing.sharedctypes 模組中): 管理器.
                                                             (line   10)
* multiprocessing.managers (模組):       管理器.             (line   15)
* multiprocessing.pool (模組):           进程池.             (line    6)
* multiprocessing.sharedctypes (模組):   multiprocessing sharedctypes 模块.
                                                             (line    6)
* multiprocessing.shared_memory (模組):  multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line    6)
* mutable object:                        对象、值与类型.     (line   10)
* mutable sequence; loop over:           for 语句.           (line   38)
* mutable; sequence; types:              可变序列类型.       (line    6)
* MutableMapping (collections.abc 中的類別): 容器抽象基类.   (line  175)
* MutableMapping (typing 中的類別):      collections abc 对应的容器.
                                                             (line   72)
* MutableSequence (collections.abc 中的類別): 容器抽象基类.  (line  155)
* MutableSequence (typing 中的類別):     collections abc 对应的容器.
                                                             (line   79)
* MutableSet (collections.abc 中的類別): 容器抽象基类.       (line  170)
* MutableSet (typing 中的類別):          collections abc 对应的容器.
                                                             (line   86)
* mutable（可變物件）:                   術語表.             (line  755)
* mvderwin() (curses.window 的方法):     Window 对象.        (line  343)
* mvwin() (curses.window 的方法):        Window 对象.        (line  348)
* myrights() (imaplib.IMAP4 的方法):     IMAP4 对象.         (line  141)
* name:                                  标识符和关键字.     (line    6)
* name <1>:                              名称的绑定.         (line    6)
* name <2>:                              标识符（名称）.     (line    6)
* Name (ast 中的類別):                   Variables.          (line    6)
* name (codecs.CodecInfo 的屬性):        codecs --- 编解码器注册和相关基类.
                                                             (line   56)
* name (contextvars.ContextVar 的屬性):  上下文变量.         (line   21)
* name (doctest.DocTest 的屬性):         DocTest 对象.       (line   26)
* name (email.headerregistry.BaseHeader 的屬性): email headerregistry 自定义标头对象.
                                                             (line   37)
* name (hashlib.hash 的屬性):            哈希算法.           (line  102)
* name (hmac.HMAC 的屬性):               hmac --- 基于密钥的消息验证.
                                                             (line   86)
* name (http.cookiejar.Cookie 的屬性):   Cookie 对象<2>.     (line   24)
* name (importlib.abc.FileLoader 的屬性): importlib abc —— 关于导入的抽象基类.
                                                             (line  414)
* name (importlib.machinery.ExtensionFileLoader 的屬性): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  269)
* name (importlib.machinery.ModuleSpec 的屬性): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  320)
* name (importlib.machinery.SourceFileLoader 的屬性): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  191)
* name (importlib.machinery.SourcelessFileLoader 的屬性): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  231)
* name (inspect.Parameter 的屬性):       Introspecting callables with the Signature object.
                                                             (line  156)
* name (io.FileIO 的屬性):               原始文件 I/O.       (line   50)
* name (multiprocessing.Process 的屬性): Process 和异常.     (line   56)
* name (multiprocessing.shared_memory.SharedMemory 的屬性): multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line   69)
* name (os.DirEntry 的屬性):             文件和目录.         (line  739)
* name (ossaudiodev.oss_audio_device 的屬性): 音频设备对象.  (line  217)
* name (pyclbr.Class 的屬性):            Class 对象.         (line   17)
* name (pyclbr.Function 的屬性):         函式物件.           (line   16)
* name (tarfile.TarInfo 的屬性):         TarInfo 对象.       (line   38)
* name (threading.Thread 的屬性):        线程对象.           (line  113)
* name (xml.dom.Attr 的屬性):            Attr 对象.          (line    8)
* name (xml.dom.DocumentType 的屬性):    文档类型对象.       (line   27)
* name (zipfile.Path 的屬性):            Path 对象.          (line   19)
* name (於 os 模組中):                   os --- 多种操作系统接口.
                                                             (line   40)
* NAME (於 token 模組中):                token --- 与Python解析树一起使用的常量.
                                                             (line   38)
* name() (importlib.abc.Traversable 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  531)
* name() (於 unicodedata 模組中):        unicodedata --- Unicode 数据库.
                                                             (line   21)
* name2codepoint (於 html.entities 模組中): html entities --- HTML 一般实体的定义.
                                                             (line   26)
* name; binding:                         import 语句.        (line    6)
* name; binding <1>:                     import 语句.        (line   43)
* name; binding <2>:                     函数定义.           (line    6)
* name; binding <3>:                     函数定义.           (line    6)
* name; binding <4>:                     类定义.             (line    6)
* name; mangling:                        私有變數.           (line   12)
* name; mangling <1>:                    标识符（名称）.     (line   10)
* Named Shared Memory:                   multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line   10)
* named tuple（附名元組）:               術語表.             (line  760)
* NamedExpr (ast 中的類別):              表达式<2>.          (line  185)
* NamedTemporaryFile() (於 tempfile 模組中): tempfile --- 生成临时文件和目录.
                                                             (line   59)
* NamedTuple (typing 中的類別):          其他特殊指令.       (line    8)
* namedtuple() (於 collections 模組中):  namedtuple 命名元组的工厂函数.
                                                             (line    9)
* NameError:                             具体异常.           (line   77)
* NameError (built-in exception):        名称的解析.         (line   14)
* namelist() (zipfile.ZipFile 的方法):   ZipFile 对象.       (line   91)
* nameprep() (於 encodings.idna 模組中): encodings idna --- 应用程序中的国际化域名.
                                                             (line   38)
* namer (logging.handlers.BaseRotatingHandler 的屬性): BaseRotatingHandler.
                                                             (line   16)
* namereplace_errors() (於 codecs 模組中): 错误处理方案.     (line  131)
* names() (於 tkinter.font 模組中):      tkinter font --- Tkinter 字体封装.
                                                             (line   88)
* namespace:                             命名与绑定.         (line    6)
* Namespace (argparse 中的類別):         命名空间对象.       (line    6)
* Namespace (multiprocessing.managers 中的類別): 管理器.     (line  197)
* namespace package（命名空間套件）:     術語表.             (line  796)
* namespace() (imaplib.IMAP4 的方法):    IMAP4 对象.         (line  145)
* Namespace() (multiprocessing.managers.SyncManager 的方法): 管理器.
                                                             (line  153)
* NamespaceErr:                          异常<15>.           (line   53)
* namespaceURI (xml.dom.Node 的屬性):    节点对象.           (line   63)
* NAMESPACE_DNS (於 uuid 模組中):        uuid --- RFC 4122 定义的UUID对象.
                                                             (line  184)
* NAMESPACE_OID (於 uuid 模組中):        uuid --- RFC 4122 定义的UUID对象.
                                                             (line  192)
* NAMESPACE_URL (於 uuid 模組中):        uuid --- RFC 4122 定义的UUID对象.
                                                             (line  188)
* NAMESPACE_X500 (於 uuid 模組中):       uuid --- RFC 4122 定义的UUID对象.
                                                             (line  196)
* namespace（命名空間）:                 術語表.             (line  785)
* nametofont() (於 tkinter.font 模組中): tkinter font --- Tkinter 字体封装.
                                                             (line   92)
* NaN:                                   內建函式.           (line  492)
* nan (於 cmath 模組中):                 常数<2>.            (line   32)
* nan (於 math 模組中):                  常数.               (line   29)
* nanj (於 cmath 模組中):                常数<2>.            (line   38)
* NannyNag:                              tabnanny --- 模糊缩进检测.
                                                             (line   33)
* napms() (於 curses 模組中):            函数<4>.            (line  242)
* nargs (optparse.Option 的屬性):        Option attributes.  (line   42)
* native_id (threading.Thread 的屬性):   线程对象.           (line  131)
* nbytes (memoryview 的屬性):            内存视图.           (line  348)
* ncurses_version (於 curses 模組中):    常量<2>.            (line   22)
* ndiff() (於 difflib 模組中):           difflib --- 计算差异的辅助工具.
                                                             (line  198)
* ndim (memoryview 的屬性):              内存视图.           (line  410)
* ne (2to3 fixer):                       修复器.             (line  192)
* ne() (於 operator 模組中):             operator --- 标准运算符替代函数.
                                                             (line   19)
* needs_input (bz2.BZ2Decompressor 的屬性): 增量压缩和解压.  (line   73)
* needs_input (lzma.LZMADecompressor 的屬性): 在内存中压缩和解压缩数据.
                                                             (line  142)
* neg() (於 operator 模組中):            operator --- 标准运算符替代函数.
                                                             (line  116)
* negation:                              一元算术和位运算.   (line   10)
* nested scope（巢狀作用域）:            術語表.             (line  805)
* netmask (ipaddress.IPv4Network 的屬性): 网络对象.          (line   85)
* netmask (ipaddress.IPv6Network 的屬性): 网络对象.          (line  281)
* NetmaskValueError:                     自定义异常.         (line   12)
* netrc (netrc 中的類別):                netrc --- netrc 文件处理.
                                                             (line   13)
* netrc (模組):                          netrc --- netrc 文件处理.
                                                             (line    6)
* NetrcParseError:                       netrc --- netrc 文件处理.
                                                             (line   31)
* netscape (http.cookiejar.CookiePolicy 的屬性): CookiePolicy 对象.
                                                             (line   56)
* network (ipaddress.IPv4Interface 的屬性): 接口对象.        (line   24)
* network (ipaddress.IPv6Interface 的屬性): 接口对象.        (line   66)
* Network News Transfer Protocol:        nntplib --- NNTP 协议客户端.
                                                             (line    8)
* network_address (ipaddress.IPv4Network 的屬性): 网络对象.  (line   72)
* network_address (ipaddress.IPv6Network 的屬性): 网络对象.  (line  275)
* NEVER_EQ (於 test.support 模組中):     test support --- Utilities for the Python test suite.
                                                             (line  205)
* new() (於 hashlib 模組中):             哈希算法.           (line   57)
* new() (於 hmac 模組中):                hmac --- 基于密钥的消息验证.
                                                             (line   12)
* new-style class（新式類別）:           術語表.             (line  813)
* newer() (於 distutils.dep_util 模組中): distutils dep_util --- Dependency checking.
                                                             (line   10)
* newer_group() (於 distutils.dep_util 模組中): distutils dep_util --- Dependency checking.
                                                             (line   24)
* newer_pairwise() (於 distutils.dep_util 模組中): distutils dep_util --- Dependency checking.
                                                             (line   17)
* newfunc (C 型態):                      Slot Type typedefs. (line   30)
* newgroups() (nntplib.NNTP 的方法):     方法<3>.            (line   69)
* NEWLINE (於 token 模組中):             token --- 与Python解析树一起使用的常量.
                                                             (line   44)
* NEWLINE token:                         逻辑行.             (line    6)
* NEWLINE token <1>:                     复合语句.           (line   46)
* newlines (io.TextIOBase 的屬性):       文本 I/O<2>.        (line   23)
* newnews() (nntplib.NNTP 的方法):       方法<3>.            (line   83)
* newpad() (於 curses 模組中):           函数<4>.            (line  246)
* NewType() (於 typing 模組中):          其他特殊指令.       (line   61)
* newwin() (於 curses 模組中):           函数<4>.            (line  260)
* new_alignment() (formatter.writer 的方法): The Writer Interface.
                                                             (line   17)
* new_child() (collections.ChainMap 的方法): ChainMap objects.
                                                             (line   38)
* new_class() (於 types 模組中):         动态类型创建.       (line    6)
* new_compiler() (於 distutils.ccompiler 模組中): distutils ccompiler --- CCompiler基类.
                                                             (line   47)
* new_event_loop() (asyncio.AbstractEventLoopPolicy 的方法): 策略对象.
                                                             (line   27)
* new_event_loop() (於 asyncio 模組中):  事件循环.           (line   53)
* new_font() (formatter.writer 的方法):  The Writer Interface.
                                                             (line   25)
* new_margin() (formatter.writer 的方法): The Writer Interface.
                                                             (line   35)
* new_module() (於 imp 模組中):          imp —— 由代码内部访问 import 。.
                                                             (line  123)
* new_panel() (於 curses.panel 模組中):  函数<5>.            (line   12)
* new_spacing() (formatter.writer 的方法): The Writer Interface.
                                                             (line   42)
* new_styles() (formatter.writer 的方法): The Writer Interface.
                                                             (line   46)
* next (2to3 fixer):                     修复器.             (line  196)
* next (pdb command):                    调试器命令.         (line  137)
* next() (nntplib.NNTP 的方法):          方法<3>.            (line  207)
* next() (tarfile.TarFile 的方法):       TarFile 对象.       (line  111)
* next() (tkinter.ttk.Treeview 的方法):  ttk Treeview.       (line  197)
* next() (內建函式):                     內建函式.           (line  833)
* nextafter() (於 math 模組中):          数论与表示函数.     (line  165)
* nextfile() (於 fileinput 模組中):      fileinput --- 迭代来自多个输入流的行.
                                                             (line   95)
* nextkey() (dbm.gnu.gdbm 的方法):       dbm gnu --- GNU 对 dbm 的重解析.
                                                             (line   77)
* nextSibling (xml.dom.Node 的屬性):     节点对象.           (line   35)
* next_minus() (decimal.Context 的方法): 上下文对象.         (line  348)
* next_minus() (decimal.Decimal 的方法): Decimal 对象.       (line  348)
* next_plus() (decimal.Context 的方法):  上下文对象.         (line  352)
* next_plus() (decimal.Decimal 的方法):  Decimal 对象.       (line  353)
* next_toward() (decimal.Context 的方法): 上下文对象.        (line  356)
* next_toward() (decimal.Decimal 的方法): Decimal 对象.      (line  358)
* ngettext() (gettext.GNUTranslations 的方法): GNUTranslations 类.
                                                             (line   39)
* ngettext() (gettext.NullTranslations 的方法): NullTranslations 类.
                                                             (line   34)
* ngettext() (於 gettext 模組中):        GNU gettext API.    (line   46)
* nice() (於 os 模組中):                 进程管理.           (line  272)
* nis (模組):                            nis --- Sun 的 NIS 黄页 接口.
                                                             (line    6)
* NL (於 token 模組中):                  token --- 与Python解析树一起使用的常量.
                                                             (line  261)
* nl() (於 curses 模組中):               函数<4>.            (line  269)
* nlargest() (於 heapq 模組中):          heapq --- 堆積佇列 heap queue 演算法.
                                                             (line   88)
* nlst() (ftplib.FTP 的方法):            FTP 对象.           (line  146)
* nl_langinfo() (於 locale 模組中):      locale --- 国际化服务.
                                                             (line  140)
* NNTP (nntplib 中的類別):               nntplib --- NNTP 协议客户端.
                                                             (line   50)
* NNTP; protocol:                        nntplib --- NNTP 协议客户端.
                                                             (line    8)
* NNTPDataError:                         nntplib --- NNTP 协议客户端.
                                                             (line  139)
* NNTPError:                             nntplib --- NNTP 协议客户端.
                                                             (line  114)
* nntplib (模組):                        nntplib --- NNTP 协议客户端.
                                                             (line    6)
* NNTPPermanentError:                    nntplib --- NNTP 协议客户端.
                                                             (line  131)
* NNTPProtocolError:                     nntplib --- NNTP 协议客户端.
                                                             (line  135)
* NNTPReplyError:                        nntplib --- NNTP 协议客户端.
                                                             (line  123)
* NNTPTemporaryError:                    nntplib --- NNTP 协议客户端.
                                                             (line  127)
* nntp_implementation (nntplib.NNTP 的屬性): 属性.           (line   13)
* NNTP_SSL (nntplib 中的類別):           nntplib --- NNTP 协议客户端.
                                                             (line   86)
* nntp_version (nntplib.NNTP 的屬性):    属性.               (line    6)
* nocbreak() (於 curses 模組中):         函数<4>.            (line  274)
* NoDataAllowedErr:                      异常<15>.           (line   68)
* node() (於 platform 模組中):           跨平台.             (line   37)
* nodelay() (curses.window 的方法):      Window 对象.        (line  352)
* nodeName (xml.dom.Node 的屬性):        节点对象.           (line   68)
* NodeTransformer (ast 中的類別):        ast 中的辅助函数.   (line  184)
* nodeType (xml.dom.Node 的屬性):        节点对象.           (line    8)
* nodeValue (xml.dom.Node 的屬性):       节点对象.           (line   75)
* NodeVisitor (ast 中的類別):            ast 中的辅助函数.   (line  149)
* noecho() (於 curses 模組中):           函数<4>.            (line  278)
* NOEXPR (於 locale 模組中):             locale --- 国际化服务.
                                                             (line  208)
* NoModificationAllowedErr:              异常<15>.           (line   72)
* nonblock() (ossaudiodev.oss_audio_device 的方法): 音频设备对象.
                                                             (line   61)
* NonCallableMagicMock (unittest.mock 中的類別): Magic Mock. (line   21)
* NonCallableMock (unittest.mock 中的類別): Mock 类.         (line  539)
* None (Built-in object):                逻辑值检测.         (line   13)
* None (內建變數):                       內建常數.           (line   18)
* nonl() (於 curses 模組中):             函数<4>.            (line  282)
* Nonlocal (ast 中的類別):               Function and class definitions.
                                                             (line  151)
* nonzero (2to3 fixer):                  修复器.             (line  201)
* noop() (imaplib.IMAP4 的方法):         IMAP4 对象.         (line  149)
* noop() (poplib.POP3 的方法):           POP3 对象.          (line   71)
* NoOptionError:                         异常<5>.            (line   28)
* NOP (opcode):                          Python字节码说明.   (line   52)
* noqiflush() (於 curses 模組中):        函数<4>.            (line  289)
* noraw() (於 curses 模組中):            函数<4>.            (line  296)
* NoReturn (於 typing 模組中):           特殊类型.           (line   16)
* NORMAL (於 tkinter.font 模組中):       tkinter font --- Tkinter 字体封装.
                                                             (line   15)
* NormalDist (statistics 中的類別):      NormalDist 对象.    (line   11)
* normalize() (decimal.Context 的方法):  上下文对象.         (line  360)
* normalize() (decimal.Decimal 的方法):  Decimal 对象.       (line  364)
* normalize() (xml.dom.Node 的方法):     节点对象.           (line  122)
* normalize() (於 locale 模組中):        locale --- 国际化服务.
                                                             (line  295)
* normalize() (於 unicodedata 模組中):   unicodedata --- Unicode 数据库.
                                                             (line   69)
* NORMALIZE_WHITESPACE (於 doctest 模組中): 选项标记.        (line   32)
* normalvariate() (於 random 模組中):    实值分布.           (line   66)
* NORMAL_PRIORITY_CLASS (於 subprocess 模組中): Windows 常数.
                                                             (line   74)
* normcase() (於 os.path 模組中):        os path --- 常用路径操作.
                                                             (line  240)
* normpath() (於 os.path 模組中):        os path --- 常用路径操作.
                                                             (line  247)
* NoSectionError:                        异常<5>.            (line   10)
* NoSuchMailboxError:                    异常<13>.           (line   12)
* Not (ast 中的類別):                    表达式<2>.          (line   28)
* NotADirectoryError:                    OS 异常.            (line   78)
* notation:                              标注.               (line    6)
* notationDecl() (xml.sax.handler.DTDHandler 的方法): DTDHandler 对象.
                                                             (line    8)
* NotationDeclHandler() (xml.parsers.expat.xmlparser 的方法): XMLParser对象<2>.
                                                             (line  225)
* notations (xml.dom.DocumentType 的屬性): 文档类型对象.     (line   37)
* NotConnected:                          http client --- HTTP 协议客户端.
                                                             (line  114)
* NoteBook (tkinter.tix 中的類別):       Manager Widgets.    (line   22)
* Notebook (tkinter.ttk 中的類別):       ttk Notebook.       (line    6)
* NotEmptyError:                         异常<13>.           (line   18)
* NotEq (ast 中的類別):                  表达式<2>.          (line  109)
* NOTEQUAL (於 token 模組中):            token --- 与Python解析树一起使用的常量.
                                                             (line  134)
* NotFoundErr:                           异常<15>.           (line   58)
* notify() (asyncio.Condition 的方法):   Condition.          (line   49)
* notify() (threading.Condition 的方法): 条件对象.           (line  124)
* notify_all() (asyncio.Condition 的方法): Condition.        (line   61)
* notify_all() (threading.Condition 的方法): 条件对象.       (line  140)
* notimeout() (curses.window 的方法):    Window 对象.        (line  356)
* NotImplemented (內建變數):             內建常數.           (line   24)
* NotImplementedError:                   具体异常.           (line   82)
* NotIn (ast 中的類別):                  表达式<2>.          (line  109)
* NotStandaloneHandler() (xml.parsers.expat.xmlparser 的方法): XMLParser对象<2>.
                                                             (line  270)
* NotSupportedErr:                       异常<15>.           (line   64)
* NotSupportedError:                     异常<4>.            (line   34)
* not_() (於 operator 模組中):           operator --- 标准运算符替代函数.
                                                             (line   40)
* noutrefresh() (curses.window 的方法):  Window 对象.        (line  363)
* now() (datetime.datetime 的類別成員):  datetime 对象.      (line   57)
* no_cache() (zoneinfo.ZoneInfo 的類別成員): ZoneInfo 类.    (line   36)
* no_proxy:                              urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  251)
* no_tracing() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  707)
* no_type_check() (於 typing 模組中):    函数与装饰器.       (line   60)
* no_type_check_decorator() (於 typing 模組中): 函数与装饰器.
                                                             (line   69)
* npgettext() (gettext.GNUTranslations 的方法): GNUTranslations 类.
                                                             (line   67)
* npgettext() (gettext.NullTranslations 的方法): NullTranslations 类.
                                                             (line   46)
* npgettext() (於 gettext 模組中):       GNU gettext API.    (line   66)
* NSIG (於 signal 模組中):               模块内容<5>.        (line  158)
* nsmallest() (於 heapq 模組中):         heapq --- 堆積佇列 heap queue 演算法.
                                                             (line   95)
* NTEventLogHandler (logging.handlers 中的類別): NTEventLogHandler.
                                                             (line   10)
* ntohl() (於 socket 模組中):            其他功能.           (line  156)
* ntohs() (於 socket 模組中):            其他功能.           (line  161)
* ntransfercmd() (ftplib.FTP 的方法):    FTP 对象.           (line  129)
* NT_OFFSET (於 token 模組中):           token --- 与Python解析树一起使用的常量.
                                                             (line  252)
* null; operation:                       pass 语句.          (line    6)
* null; operation <1>:                   pass 语句.          (line    6)
* nullcontext() (於 contextlib 模組中):  工具.               (line  131)
* NullFormatter (formatter 中的類別):    Formatter Implementations.
                                                             (line   10)
* NullHandler (logging 中的類別):        NullHandler.        (line   11)
* NullImporter (imp 中的類別):           imp —— 由代码内部访问 import 。.
                                                             (line  335)
* NullTranslations (gettext 中的類別):   NullTranslations 类.
                                                             (line   11)
* NullWriter (formatter 中的類別):       Writer Implementations.
                                                             (line   10)
* number:                                数值字面值.         (line    6)
* Number (numbers 中的類別):             numbers --- 数字的抽象基类.
                                                             (line   13)
* NUMBER (於 token 模組中):              token --- 与Python解析树一起使用的常量.
                                                             (line   40)
* numbers (模組):                        numbers --- 数字的抽象基类.
                                                             (line    6)
* number_class() (decimal.Context 的方法): 上下文对象.       (line  364)
* number_class() (decimal.Decimal 的方法): Decimal 对象.     (line  371)
* numerator (fractions.Fraction 的屬性): fractions --- 分数. (line   84)
* numerator (numbers.Rational 的屬性):   数字的层次.         (line   45)
* numeric literal:                       数值字面值.         (line    6)
* numeric() (於 unicodedata 模組中):     unicodedata --- Unicode 数据库.
                                                             (line   36)
* numeric; conversions:                  数字类型 --- int float complex.
                                                             (line   92)
* numeric; literals:                     数字类型 --- int float complex.
                                                             (line   14)
* numinput() (於 turtle 模組中):         输入方法.           (line   21)
* numliterals (2to3 fixer):              修复器.             (line  206)
* num_addresses (ipaddress.IPv4Network 的屬性): 网络对象.    (line  108)
* num_addresses (ipaddress.IPv6Network 的屬性): 网络对象.    (line  293)
* num_tickets (ssl.SSLContext 的屬性):   SSL 上下文.         (line  500)
* N_TOKENS (於 token 模組中):            token --- 与Python解析树一起使用的常量.
                                                             (line  250)
* n_waiting (threading.Barrier 的屬性):  栅栏对象.           (line   83)
* obj (memoryview 的屬性):               内存视图.           (line  337)
* object:                                对象、值与类型.     (line    6)
* object (UnicodeError 的屬性):          具体异常.           (line  317)
* object (內建類別):                     內建函式.           (line  839)
* object.__slots__ (內建變數):           __slots__.          (line   14)
* object; code:                          标准类型层级结构.   (line  506)
* object; code <1>:                      方法.               (line   36)
* object; code <2>:                      marshal --- 内部 Python 对象序列化.
                                                             (line   24)
* object; code <3>:                      Cell 物件.          (line   47)
* object; deallocation:                  终结和内存释放.     (line    6)
* object; finalization:                  终结和内存释放.     (line    6)
* object; numeric:                       比较.               (line   41)
* objects; comparing:                    比较.               (line   41)
* object_filenames() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  465)
* object（物件）:                        術語表.             (line  821)
* objobjargproc (C 型態):                Slot Type typedefs. (line  111)
* objobjproc (C 型態):                   Slot Type typedefs. (line  109)
* obufcount() (ossaudiodev.oss_audio_device 的方法): 音频设备对象.
                                                             (line  201)
* obuffree() (ossaudiodev.oss_audio_device 的方法): 音频设备对象.
                                                             (line  206)
* oct() (內建函式):                      內建函式.           (line  847)
* octal literal:                         数值字面值.         (line    6)
* octal; literals:                       数字类型 --- int float complex.
                                                             (line   14)
* octdigits (於 string 模組中):          字符串常量.         (line   31)
* offset (SyntaxError 的屬性):           具体异常.           (line  226)
* offset (traceback.TracebackException 的屬性): TracebackException Objects.
                                                             (line   54)
* offset (xml.parsers.expat.ExpatError 的屬性): ExpatError 异常.
                                                             (line   28)
* OK (於 curses 模組中):                 常量<2>.            (line   13)
* ok_command() (tkinter.filedialog.LoadFileDialog 的方法): 原生 加载/保存 对话框.
                                                             (line  130)
* ok_command() (tkinter.filedialog.SaveFileDialog 的方法): 原生 加载/保存 对话框.
                                                             (line  138)
* ok_event() (tkinter.filedialog.FileDialog 的方法): 原生 加载/保存 对话框.
                                                             (line  110)
* old_value (contextvars.Token 的屬性):  上下文变量.         (line   75)
* OleDLL (ctypes 中的類別):              加载动态链接库.     (line   28)
* onclick() (於 turtle 模組中):          使用屏幕事件.       (line   51)
* ondrag() (於 turtle 模組中):           使用事件.           (line   52)
* onecmd() (cmd.Cmd 的方法):             Cmd 对象.           (line   44)
* onkey() (於 turtle 模組中):            使用屏幕事件.       (line   11)
* onkeypress() (於 turtle 模組中):       使用屏幕事件.       (line   32)
* onkeyrelease() (於 turtle 模組中):     使用屏幕事件.       (line   11)
* onrelease() (於 turtle 模組中):        使用事件.           (line   27)
* onscreenclick() (於 turtle 模組中):    使用屏幕事件.       (line   51)
* ontimer() (於 turtle 模組中):          使用屏幕事件.       (line   78)
* on_motion() (tkinter.dnd.DndHandler 的方法): tkinter dnd --- 拖放操作支持.
                                                             (line   50)
* on_release() (tkinter.dnd.DndHandler 的方法): tkinter dnd --- 拖放操作支持.
                                                             (line   54)
* OP (於 token 模組中):                  token --- 与Python解析树一起使用的常量.
                                                             (line  238)
* Open (tkinter.filedialog 中的類別):    原生 加载/保存 对话框.
                                                             (line   54)
* open() (distutils.text_file.TextFile 的方法): distutils text_file --- The TextFile class.
                                                             (line   91)
* open() (imaplib.IMAP4 的方法):         IMAP4 对象.         (line  153)
* open() (importlib.abc.Traversable 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  555)
* open() (pathlib.Path 的方法):          方法<2>.            (line  237)
* open() (pipes.Template 的方法):        模板对象.           (line   40)
* open() (tarfile.TarFile 的類別成員):   TarFile 对象.       (line   79)
* open() (telnetlib.Telnet 的方法):      Telnet 对象.        (line   60)
* open() (urllib.request.OpenerDirector 的方法): OpenerDirector 对象.
                                                             (line   40)
* open() (urllib.request.URLopener 的方法): 沿袭的接口.      (line   81)
* open() (webbrowser.controller 的方法): 浏览器控制器对象.   (line    8)
* open() (zipfile.Path 的方法):          Path 对象.          (line   23)
* open() (zipfile.ZipFile 的方法):       ZipFile 对象.       (line   95)
* open() (內建函式):                     內建函式.           (line  870)
* open() (於 aifc 模組中):               aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line   26)
* open() (於 bz2 模組中):                文件压缩和解压.     (line    6)
* open() (於 codecs 模組中):             codecs --- 编解码器注册和相关基类.
                                                             (line  144)
* open() (於 dbm 模組中):                dbm --- Unix "数据库" 接口.
                                                             (line   31)
* open() (於 dbm.dumb 模組中):           dbm dumb --- 便携式 DBM 实现.
                                                             (line   25)
* open() (於 dbm.gnu 模組中):            dbm gnu --- GNU 对 dbm 的重解析.
                                                             (line   24)
* open() (於 dbm.ndbm 模組中):           dbm ndbm --- 基于 ndbm 的接口.
                                                             (line   26)
* open() (於 gzip 模組中):               gzip --- 对 gzip 格式的支持.
                                                             (line   25)
* open() (於 io 模組中):                 高阶模块接口.       (line   11)
* open() (於 lzma 模組中):               读写压缩文件.       (line    6)
* open() (於 os 模組中):                 文件描述符操作.     (line  232)
* open() (於 ossaudiodev 模組中):        ossaudiodev --- 访问兼容OSS的音频设备.
                                                             (line   37)
* open() (於 shelve 模組中):             shelve --- Python 对象持久化.
                                                             (line   15)
* open() (於 sunau 模組中):              sunau --- 读写 Sun AU 文件.
                                                             (line   45)
* open() (於 tarfile 模組中):            tarfile --- 读写tar归档文件.
                                                             (line   31)
* open() (於 tokenize 模組中):           对输入进行解析标记. (line   83)
* open() (於 wave 模組中):               wave --- 读写WAV格式文件.
                                                             (line   15)
* open() (於 webbrowser 模組中):         webbrowser --- 方便的Web浏览器控制器.
                                                             (line   40)
* OpenDatabase() (於 msilib 模組中):     msilib --- Read and write Microsoft Installer files.
                                                             (line   45)
* OpenerDirector (urllib.request 中的類別): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  216)
* OpenKey() (於 winreg 模組中):          函数<12>.           (line  262)
* OpenKeyEx() (於 winreg 模組中):        函数<12>.           (line  262)
* openlog() (於 syslog 模組中):          Unix syslog 库例程. (line   33)
* openmixer() (於 ossaudiodev 模組中):   ossaudiodev --- 访问兼容OSS的音频设备.
                                                             (line   59)
* openpty() (於 os 模組中):              文件描述符操作.     (line  316)
* openpty() (於 pty 模組中):             pty --- 伪终端工具. (line   25)
* OpenSSL; (use in module hashlib):      哈希算法.           (line   18)
* OpenSSL; (use in module ssl):          ssl --- 套接字对象的 TLS/SSL 包装器.
                                                             (line    8)
* OPENSSL_VERSION (於 ssl 模組中):       常量<3>.            (line  399)
* OPENSSL_VERSION_INFO (於 ssl 模組中):  常量<3>.            (line  408)
* OPENSSL_VERSION_NUMBER (於 ssl 模組中): 常量<3>.           (line  417)
* OpenView() (msilib.Database 的方法):   Database Objects.   (line    6)
* open_binary() (於 importlib.resources 模組中): importlib resources -- 资源.
                                                             (line   70)
* open_code() (於 io 模組中):            高阶模块接口.       (line   19)
* open_connection() (於 asyncio 模組中): 流.                 (line   40)
* open_new() (webbrowser.controller 的方法): 浏览器控制器对象.
                                                             (line   14)
* open_new() (於 webbrowser 模組中):     webbrowser --- 方便的Web浏览器控制器.
                                                             (line   54)
* open_new_tab() (webbrowser.controller 的方法): 浏览器控制器对象.
                                                             (line   19)
* open_new_tab() (於 webbrowser 模組中): webbrowser --- 方便的Web浏览器控制器.
                                                             (line   59)
* open_osfhandle() (於 msvcrt 模組中):   文件操作.           (line   40)
* open_resource() (importlib.abc.ResourceReader 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  273)
* open_text() (於 importlib.resources 模組中): importlib resources -- 资源.
                                                             (line   81)
* open_unix_connection() (於 asyncio 模組中): 流.            (line   90)
* open_unknown() (urllib.request.URLopener 的方法): 沿袭的接口.
                                                             (line   90)
* open_urlresource() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  778)
* OperationalError:                      异常<4>.            (line   28)
* operations on; dictionary; type:       映射类型 --- dict.  (line    6)
* operations on; integer; types:         整数类型的按位运算. (line    6)
* operations on; list; type:             可变序列类型.       (line   14)
* operations on; mapping; types:         映射类型 --- dict.  (line    6)
* operations on; numeric; types:         数字类型 --- int float complex.
                                                             (line   83)
* operations on; sequence; types:        通用序列操作.       (line   17)
* operations on; sequence; types <1>:    可变序列类型.       (line   14)
* operator (2to3 fixer):                 修复器.             (line  210)
* operator (模組):                       operator --- 标准运算符替代函数.
                                                             (line    6)
* operator; + (plus):                    一元算术和位运算.   (line   13)
* operator; + (plus) <1>:                二元算术运算符.     (line   55)
* operator; + (plus) <2>:                数字类型 --- int float complex.
                                                             (line   20)
* operator; - (minus):                   一元算术和位运算.   (line   10)
* operator; - (minus) <1>:               二元算术运算符.     (line   62)
* operator; - (minus) <2>:               数字类型 --- int float complex.
                                                             (line   20)
* operator; comparison:                  比较.               (line    6)
* operator; overloading:                 特殊方法名称.       (line    6)
* operator; precedence:                  运算符优先级.       (line    6)
* operators:                             运算符.             (line    6)
* opmap (於 dis 模組中):                 操作码集合.         (line   12)
* opname (於 dis 模組中):                操作码集合.         (line    8)
* optimize() (於 pickletools 模組中):    编程接口<2>.        (line   26)
* OPTIMIZED_BYTECODE_SUFFIXES (於 importlib.machinery 模組中): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line   26)
* optim_args_from_interpreter_flags() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  450)
* Optional (於 typing 模組中):           特殊形式.           (line   55)
* OptionGroup (optparse 中的類別):       Grouping Options.   (line   12)
* OptionMenu (tkinter.tix 中的類別):     Basic Widgets.      (line   48)
* OptionParser (optparse 中的類別):      创建解析器.         (line    9)
* options (doctest.Example 的屬性):      Example 对象.       (line   44)
* Options (ssl 中的類別):                常量<3>.            (line  302)
* options (ssl.SSLContext 的屬性):       SSL 上下文.         (line  510)
* options() (configparser.ConfigParser 的方法): ConfigParser 对象.
                                                             (line   87)
* optionxform() (configparser.ConfigParser 的方法): ConfigParser 对象.
                                                             (line  247)
* optparse (模組):                       optparse --- 解析器的命令行选项.
                                                             (line    6)
* OP_ALL (於 ssl 模組中):                常量<3>.            (line  187)
* OP_CIPHER_SERVER_PREFERENCE (於 ssl 模組中): 常量<3>.      (line  264)
* OP_ENABLE_MIDDLEBOX_COMPAT (於 ssl 模組中): 常量<3>.       (line  285)
* OP_IGNORE_UNEXPECTED_EOF (於 ssl 模組中): 常量<3>.         (line  312)
* OP_NO_COMPRESSION (於 ssl 模組中):     常量<3>.            (line  294)
* OP_NO_RENEGOTIATION (於 ssl 模組中):   常量<3>.            (line  255)
* OP_NO_SSLv2 (於 ssl 模組中):           常量<3>.            (line  194)
* OP_NO_SSLv3 (於 ssl 模組中):           常量<3>.            (line  203)
* OP_NO_TICKET (於 ssl 模組中):          常量<3>.            (line  306)
* OP_NO_TLSv1 (於 ssl 模組中):           常量<3>.            (line  212)
* OP_NO_TLSv1_1 (於 ssl 模組中):         常量<3>.            (line  223)
* OP_NO_TLSv1_2 (於 ssl 模組中):         常量<3>.            (line  233)
* OP_NO_TLSv1_3 (於 ssl 模組中):         常量<3>.            (line  243)
* OP_SINGLE_DH_USE (於 ssl 模組中):      常量<3>.            (line  271)
* OP_SINGLE_ECDH_USE (於 ssl 模組中):    常量<3>.            (line  278)
* Or (ast 中的類別):                     表达式<2>.          (line   87)
* ord() (內建函式):                      內建函式.           (line 1073)
* OrderedDict (collections 中的類別):    OrderedDict 对象.   (line   33)
* OrderedDict (typing 中的類別):         collections 对应类型.
                                                             (line   16)
* ordered_attributes (xml.parsers.expat.xmlparser 的屬性): XMLParser对象<2>.
                                                             (line   89)
* origin (importlib.machinery.ModuleSpec 的屬性): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  333)
* origin_req_host (urllib.request.Request 的屬性): Request 对象.
                                                             (line   28)
* origin_server (wsgiref.handlers.BaseHandler 的屬性): wsgiref handlers -- 服务器/网关基类.
                                                             (line  236)
* or_() (於 operator 模組中):            operator --- 标准运算符替代函数.
                                                             (line  121)
* os (模組):                             os --- 多种操作系统接口.
                                                             (line    6)
* os.path (模組):                        os path --- 常用路径操作.
                                                             (line    6)
* OSError:                               具体异常.           (line   96)
* ossaudiodev (模組):                    ossaudiodev --- 访问兼容OSS的音频设备.
                                                             (line    6)
* OSSAudioError:                         ossaudiodev --- 访问兼容OSS的音频设备.
                                                             (line   26)
* os_environ (wsgiref.handlers.BaseHandler 的屬性): wsgiref handlers -- 服务器/网关基类.
                                                             (line  138)
* output:                                表达式语句.         (line   15)
* output (subprocess.CalledProcessError 的屬性): 使用 subprocess 模块.
                                                             (line  185)
* output (subprocess.TimeoutExpired 的屬性): 使用 subprocess 模块.
                                                             (line  152)
* output (unittest.TestCase 的屬性):     测试用例.           (line  431)
* output() (http.cookies.BaseCookie 的方法): Cookie 对象.    (line   21)
* output() (http.cookies.Morsel 的方法): Morsel 对象.        (line   68)
* OutputChecker (doctest 中的類別):      OutputChecker 对象. (line    6)
* OutputString() (http.cookies.Morsel 的方法): Morsel 对象.  (line   81)
* output_charset (email.charset.Charset 的屬性): email charset 表示字符集.
                                                             (line   66)
* output_charset() (gettext.NullTranslations 的方法): NullTranslations 类.
                                                             (line   75)
* output_codec (email.charset.Charset 的屬性): email charset 表示字符集.
                                                             (line   77)
* output_difference() (doctest.OutputChecker 的方法): OutputChecker 对象.
                                                             (line   22)
* over() (nntplib.NNTP 的方法):          方法<3>.            (line  148)
* Overflow (decimal 中的類別):           信号.               (line   60)
* OverflowError:                         具体异常.           (line  151)
* OverflowError (built-in exception):    整數物件.           (line   95)
* OverflowError (built-in exception) <1>: 整數物件.          (line  129)
* OverflowError (built-in exception) <2>: 整數物件.          (line  165)
* OverflowError (built-in exception) <3>: 整數物件.          (line  175)
* OverflowError (built-in exception) <4>: 整數物件.          (line  186)
* OverflowError (built-in exception) <5>: 整數物件.          (line  198)
* overlap() (statistics.NormalDist 的方法): NormalDist 对象. (line   80)
* overlaps() (ipaddress.IPv4Network 的方法): 网络对象.       (line  132)
* overlaps() (ipaddress.IPv6Network 的方法): 网络对象.       (line  304)
* overlay() (curses.window 的方法):      Window 对象.        (line  368)
* overload() (於 typing 模組中):         函数与装饰器.       (line   13)
* overwrite() (curses.window 的方法):    Window 对象.        (line  379)
* owner() (pathlib.Path 的方法):         方法<2>.            (line  248)
* O_APPEND (於 os 模組中):               文件描述符操作.     (line  269)
* O_ASYNC (於 os 模組中):                文件描述符操作.     (line  301)
* O_BINARY (於 os 模組中):               文件描述符操作.     (line  291)
* O_CLOEXEC (於 os 模組中):              文件描述符操作.     (line  279)
* O_CREAT (於 os 模組中):                文件描述符操作.     (line  269)
* O_DIRECT (於 os 模組中):               文件描述符操作.     (line  301)
* O_DIRECTORY (於 os 模組中):            文件描述符操作.     (line  301)
* O_DSYNC (於 os 模組中):                文件描述符操作.     (line  279)
* O_EXCL (於 os 模組中):                 文件描述符操作.     (line  269)
* O_EXLOCK (於 os 模組中):               文件描述符操作.     (line  301)
* O_NDELAY (於 os 模組中):               文件描述符操作.     (line  279)
* O_NOATIME (於 os 模組中):              文件描述符操作.     (line  301)
* O_NOCTTY (於 os 模組中):               文件描述符操作.     (line  279)
* O_NOFOLLOW (於 os 模組中):             文件描述符操作.     (line  301)
* O_NOINHERIT (於 os 模組中):            文件描述符操作.     (line  291)
* O_NONBLOCK (於 os 模組中):             文件描述符操作.     (line  279)
* O_PATH (於 os 模組中):                 文件描述符操作.     (line  301)
* O_RANDOM (於 os 模組中):               文件描述符操作.     (line  291)
* O_RDONLY (於 os 模組中):               文件描述符操作.     (line  269)
* O_RDWR (於 os 模組中):                 文件描述符操作.     (line  269)
* O_RSYNC (於 os 模組中):                文件描述符操作.     (line  279)
* O_SEQUENTIAL (於 os 模組中):           文件描述符操作.     (line  291)
* O_SHLOCK (於 os 模組中):               文件描述符操作.     (line  301)
* O_SHORT_LIVED (於 os 模組中):          文件描述符操作.     (line  291)
* O_SYNC (於 os 模組中):                 文件描述符操作.     (line  279)
* O_TEMPORARY (於 os 模組中):            文件描述符操作.     (line  291)
* O_TEXT (於 os 模組中):                 文件描述符操作.     (line  291)
* O_TMPFILE (於 os 模組中):              文件描述符操作.     (line  301)
* O_TRUNC (於 os 模組中):                文件描述符操作.     (line  269)
* O_WRONLY (於 os 模組中):               文件描述符操作.     (line  269)
* p (pdb command):                       调试器命令.         (line  193)
* pack() (mailbox.MH 的方法):            MH.                 (line   58)
* pack() (struct.Struct 的方法):         类.                 (line   21)
* pack() (於 struct 模組中):             函数和异常.         (line   12)
* package:                               包.                 (line    6)
* package <1>:                           site —— 指定域的配置钩子.
                                                             (line   52)
* Package (於 importlib.resources 模組中): importlib resources -- 资源.
                                                             (line   32)
* package variable; __all__:             匯入模組<2>.        (line    7)
* package; namespace:                    命名空间包.         (line    6)
* package; portion:                      命名空间包.         (line    6)
* package; regular:                      常规包.             (line    6)
* package（套件）:                       術語表.             (line  827)
* packed (ipaddress.IPv4Address 的屬性): 地址对象.           (line   68)
* packed (ipaddress.IPv6Address 的屬性): 地址对象.           (line  191)
* Packer (xdrlib 中的類別):              xdrlib --- 编码与解码 XDR 数据.
                                                             (line   17)
* packing (widgets):                     The Packer.         (line    6)
* packing; binary; data:                 struct --- 将字节串解读为打包的二进制数据.
                                                             (line    8)
* pack_array() (xdrlib.Packer 的方法):   Packer 对象.        (line   75)
* pack_bytes() (xdrlib.Packer 的方法):   Packer 对象.        (line   49)
* pack_double() (xdrlib.Packer 的方法):  Packer 对象.        (line   25)
* pack_farray() (xdrlib.Packer 的方法):  Packer 对象.        (line   68)
* pack_float() (xdrlib.Packer 的方法):   Packer 对象.        (line   21)
* pack_fopaque() (xdrlib.Packer 的方法): Packer 对象.        (line   36)
* pack_fstring() (xdrlib.Packer 的方法): Packer 对象.        (line   31)
* pack_into() (struct.Struct 的方法):    类.                 (line   26)
* pack_into() (於 struct 模組中):        函数和异常.         (line   17)
* pack_list() (xdrlib.Packer 的方法):    Packer 对象.        (line   55)
* pack_opaque() (xdrlib.Packer 的方法):  Packer 对象.        (line   45)
* pack_string() (xdrlib.Packer 的方法):  Packer 对象.        (line   40)
* PAGER:                                 pydoc --- 文档生成器和在线帮助系统.
                                                             (line   37)
* pair_content() (於 curses 模組中):     函数<4>.            (line  300)
* pair_number() (於 curses 模組中):      函数<4>.            (line  305)
* PanedWindow (tkinter.tix 中的類別):    Manager Widgets.    (line    6)
* Parameter (inspect 中的類別):          Introspecting callables with the Signature object.
                                                             (line  142)
* parameter; call semantics:             调用.               (line   24)
* parameter; difference from argument:   如何将可选参数或关键字参数从一个函数传递到另一个函数？.
                                                             (line   15)
* parameter; function definition:        with 语句.          (line   91)
* ParameterizedMIMEHeader (email.headerregistry 中的類別): email headerregistry 自定义标头对象.
                                                             (line  207)
* parameters (inspect.Signature 的屬性): Introspecting callables with the Signature object.
                                                             (line   78)
* parameter（參數）:                     術語表.             (line  836)
* params (email.headerregistry.ParameterizedMIMEHeader 的屬性): email headerregistry 自定义标头对象.
                                                             (line  213)
* paramstyle (於 sqlite3 模組中):        模块函数和常量.     (line   11)
* pardir (於 os 模組中):                 其他系统信息.       (line   72)
* paren (2to3 fixer):                    修复器.             (line  241)
* parent (importlib.machinery.ModuleSpec 的屬性): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  357)
* parent (pyclbr.Class 的屬性):          Class 对象.         (line   25)
* parent (pyclbr.Function 的屬性):       函式物件.           (line   24)
* parent (urllib.request.BaseHandler 的屬性): BaseHandler 对象.
                                                             (line   23)
* parent() (tkinter.ttk.Treeview 的方法): ttk Treeview.      (line  203)
* parenthesized form:                    带圆括号的形式.     (line    6)
* parentNode (xml.dom.Node 的屬性):      节点对象.           (line   16)
* parents (collections.ChainMap 的屬性): ChainMap objects.   (line   48)
* parent_process() (於 multiprocessing 模組中): 杂项<3>.     (line   33)
* paretovariate() (於 random 模組中):    实值分布.           (line   76)
* parse() (doctest.DocTestParser 的方法): DocTestParser 对象.
                                                             (line   28)
* parse() (email.parser.BytesParser 的方法): Parser API.     (line   29)
* parse() (email.parser.Parser 的方法):  Parser API.         (line   74)
* parse() (string.Formatter 的方法):     自定义字符串格式化. (line   32)
* parse() (urllib.robotparser.RobotFileParser 的方法): urllib robotparser --- robots txt 语法分析程序.
                                                             (line   28)
* parse() (xml.etree.ElementTree.ElementTree 的方法): ElementTree 对象.
                                                             (line   46)
* Parse() (xml.parsers.expat.xmlparser 的方法): XMLParser对象<2>.
                                                             (line    8)
* parse() (xml.sax.xmlreader.XMLReader 的方法): XMLReader 对象.
                                                             (line    8)
* parse() (於 ast 模組中):               ast 中的辅助函数.   (line    8)
* parse() (於 cgi 模組中):               函数<9>.            (line    9)
* parse() (於 xml.dom.minidom 模組中):   xml dom minidom --- 最小化的 DOM 实现.
                                                             (line   33)
* parse() (於 xml.dom.pulldom 模組中):   xml dom pulldom --- 支持构建部分 DOM 树.
                                                             (line   77)
* parse() (於 xml.etree.ElementTree 模組中): 函数<7>.        (line  146)
* parse() (於 xml.sax 模組中):           xml sax --- 支持 SAX2 解析器.
                                                             (line   34)
* parseaddr() (於 email.utils 模組中):   email utils 其他工具.
                                                             (line   48)
* parsebytes() (email.parser.BytesParser 的方法): Parser API.
                                                             (line   45)
* parsedate() (於 email.utils 模組中):   email utils 其他工具.
                                                             (line   80)
* parsedate_to_datetime() (於 email.utils 模組中): email utils 其他工具.
                                                             (line   99)
* parsedate_tz() (於 email.utils 模組中): email utils 其他工具.
                                                             (line   90)
* ParseError (xml.etree.ElementTree 中的類別): 异常<14>.     (line    6)
* ParseFile() (xml.parsers.expat.xmlparser 的方法): XMLParser对象<2>.
                                                             (line   14)
* ParseFlags() (於 imaplib 模組中):      imaplib --- IMAP4 协议客户端.
                                                             (line  111)
* parser:                                词法分析.           (line    6)
* Parser (email.parser 中的類別):        Parser API.         (line   66)
* parser (模組):                         parser --- 访问 Python 解析树.
                                                             (line    6)
* ParserCreate() (於 xml.parsers.expat 模組中): xml parsers expat --- 使用 Expat 的快速 XML 解析.
                                                             (line   41)
* ParserError:                           异常和错误处理.     (line   11)
* ParseResult (urllib.parse 中的類別):   结构化解析结果.     (line   41)
* ParseResultBytes (urllib.parse 中的類別): 结构化解析结果.  (line   63)
* parsestr() (email.parser.Parser 的方法): Parser API.       (line   83)
* parseString() (於 xml.dom.minidom 模組中): xml dom minidom --- 最小化的 DOM 实现.
                                                             (line   44)
* parseString() (於 xml.dom.pulldom 模組中): xml dom pulldom --- 支持构建部分 DOM 树.
                                                             (line   88)
* parseString() (於 xml.sax 模組中):     xml sax --- 支持 SAX2 解析器.
                                                             (line   44)
* parse_and_bind() (於 readline 模組中): 初始化文件.         (line    8)
* parse_args() (argparse.ArgumentParser 的方法): parse_args 方法.
                                                             (line    6)
* PARSE_COLNAMES (於 sqlite3 模組中):    模块函数和常量.     (line   66)
* parse_config_h() (於 sysconfig 模組中): 其他功能<2>.       (line   56)
* PARSE_DECLTYPES (於 sqlite3 模組中):   模块函数和常量.     (line   57)
* parse_header() (於 cgi 模組中):        函数<9>.            (line   35)
* parse_headers() (於 http.client 模組中): http client --- HTTP 协议客户端.
                                                             (line   93)
* parse_intermixed_args() (argparse.ArgumentParser 的方法): 混合解析.
                                                             (line    6)
* parse_known_args() (argparse.ArgumentParser 的方法): 部分解析.
                                                             (line    6)
* parse_known_intermixed_args() (argparse.ArgumentParser 的方法): 混合解析.
                                                             (line    9)
* parse_multipart() (於 cgi 模組中):     函数<9>.            (line   16)
* parse_qs() (於 urllib.parse 模組中):   URL 解析.           (line  136)
* parse_qsl() (於 urllib.parse 模組中):  URL 解析.           (line  174)
* parsing; Python source code:           parser --- 访问 Python 解析树.
                                                             (line    6)
* ParsingError:                          异常<5>.            (line   55)
* partial (asyncio.IncompleteReadError 的屬性): 异常<9>.     (line   50)
* partial() (imaplib.IMAP4 的方法):      IMAP4 对象.         (line  169)
* partial() (於 functools 模組中):       functools --- 高阶函数和可调用对象上的操作.
                                                             (line  241)
* partialmethod (functools 中的類別):    functools --- 高阶函数和可调用对象上的操作.
                                                             (line  268)
* parties (threading.Barrier 的屬性):    栅栏对象.           (line   79)
* partition() (bytearray 的方法):        bytes 和 bytearray 操作.
                                                             (line  157)
* partition() (bytes 的方法):            bytes 和 bytearray 操作.
                                                             (line  157)
* partition() (str 的方法):              字符串的方法<2>.    (line  305)
* Pass (ast 中的類別):                   Statements.         (line  159)
* pass_() (poplib.POP3 的方法):          POP3 对象.          (line   33)
* Paste:                                 帮助菜单（命令行和编辑器）.
                                                             (line   26)
* patch() (於 test.support 模組中):      test support --- Utilities for the Python test suite.
                                                             (line  963)
* patch() (於 unittest.mock 模組中):     patch.              (line    9)
* patch.dict() (於 unittest.mock 模組中): patch dict.        (line    6)
* patch.multiple() (於 unittest.mock 模組中): patch multiple.
                                                             (line    6)
* patch.object() (於 unittest.mock 模組中): patch object.    (line    6)
* patch.stopall() (於 unittest.mock 模組中): patch methods start and stop.
                                                             (line   70)
* PATH:                                  更改的Python API.   (line  125)
* PATH <1>:                              'python' 命令行为的变化<2>.
                                                             (line    6)
* PATH <2>:                              'python' 命令行为的变化<2>.
                                                             (line   11)
* PATH <3>:                              'python' 命令行为的变化<2>.
                                                             (line   12)
* PATH <4>:                              安全性<16>.         (line   16)
* PATH <5>:                              安全性<16>.         (line   20)
* PATH <6>:                              模組的搜尋路徑.     (line   13)
* PATH <7>:                              可執行的 Python 腳本.
                                                             (line   11)
* PATH <8>:                              环境变量.           (line   22)
* PATH <9>:                              杂项.               (line   14)
* PATH <10>:                             安装步骤.           (line   26)
* PATH <11>:                             安装步骤.           (line   46)
* PATH <12>:                             安裝排除使用者介面. (line   49)
* PATH <13>:                             附录：设置环境变量. (line   19)
* PATH <14>:                             附录：设置环境变量. (line   27)
* PATH <15>:                             查找Python可执行文件.
                                                             (line   12)
* PATH <16>:                             查找Python可执行文件.
                                                             (line   17)
* PATH <17>:                             查找Python可执行文件.
                                                             (line   18)
* PATH <18>:                             适用于Windows的Python启动器.
                                                             (line   12)
* PATH <19>:                             从命令行.           (line    8)
* PATH <20>:                             从命令行.           (line   33)
* PATH <21>:                             Shebang Lines.      (line   39)
* PATH <22>:                             Shebang Lines.      (line   40)
* PATH <23>:                             进程管理.           (line   39)
* PATH <24>:                             进程管理.           (line   69)
* PATH <25>:                             进程管理.           (line   71)
* PATH <26>:                             进程管理.           (line   73)
* PATH <27>:                             进程管理.           (line  402)
* PATH <28>:                             进程管理.           (line  474)
* PATH <29>:                             进程管理.           (line  475)
* PATH <30>:                             进程管理.           (line  477)
* PATH <31>:                             其他系统信息.       (line   97)
* PATH <32>:                             webbrowser --- 方便的Web浏览器控制器.
                                                             (line  192)
* PATH <33>:                             在 Unix 系统上安装你的 CGI 脚本.
                                                             (line   22)
* PATH <34>:                             常见问题和解决方案. (line   20)
* PATH <35>:                             site —— 指定域的配置钩子.
                                                             (line   47)
* PATH <36>:                             嵌入式Python.       (line   31)
* PATH <37>:                             嵌入式Python.       (line   37)
* PATH <38>:                             我如何使Python script 執行在Unix ?.
                                                             (line   19)
* PATH <39>:                             我如何使Python script 執行在Unix ?.
                                                             (line   24)
* path (http.cookiejar.Cookie 的屬性):   Cookie 对象<2>.     (line   37)
* path (http.server.BaseHTTPRequestHandler 的屬性): http server --- HTTP 服务器.
                                                             (line   80)
* path (importlib.abc.FileLoader 的屬性): importlib abc —— 关于导入的抽象基类.
                                                             (line  418)
* path (importlib.machinery.ExtensionFileLoader 的屬性): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  273)
* path (importlib.machinery.FileFinder 的屬性): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  156)
* path (importlib.machinery.SourceFileLoader 的屬性): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  195)
* path (importlib.machinery.SourcelessFileLoader 的屬性): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  235)
* path (in module sys):                  嵌入式Python.       (line   12)
* path (in module sys) <1>:              Initializing and finalizing the interpreter.
                                                             (line    8)
* path (in module sys) <2>:              Process-wide parameters.
                                                             (line  120)
* path (in module sys) <3>:              Process-wide parameters.
                                                             (line  133)
* path (os.DirEntry 的屬性):             文件和目录.         (line  748)
* Path (pathlib 中的類別):               具体路径.           (line    9)
* Path (zipfile 中的類別):               Path 对象.          (line    6)
* path (於 sys 模組中):                  sys --- 系统相关的参数和函数.
                                                             (line  895)
* path based finder:                     基于路径的查找器.   (line    6)
* path based finder（基於路徑的尋檢器）: 術語表.             (line  899)
* Path browser:                          文件菜单 （命令行和编辑器）.
                                                             (line   22)
* path entry finder（路徑項目尋檢器）:   術語表.             (line  884)
* path entry hook（路徑項目鉤）:         術語表.             (line  893)
* path entry（路徑項目）:                術語表.             (line  878)
* path hooks:                            导入钩子.           (line    6)
* path() (於 importlib.resources 模組中): importlib resources -- 资源.
                                                             (line  114)
* path-like object（類路徑物件）:        術語表.             (line  904)
* path; configuration; file:             site —— 指定域的配置钩子.
                                                             (line   52)
* path; operations:                      pathlib --- 面向对象的文件系统路径.
                                                             (line   10)
* path; operations <1>:                  os path --- 常用路径操作.
                                                             (line    9)
* pathconf() (於 os 模組中):             文件和目录.         (line  489)
* pathconf_names (於 os 模組中):         文件和目录.         (line  508)
* PathEntryFinder (importlib.abc 中的類別): importlib abc —— 关于导入的抽象基类.
                                                             (line   88)
* PATHEXT:                               其他改进<2>.        (line   30)
* PATHEXT <1>:                           库<11>.             (line  104)
* PATHEXT <2>:                           安裝排除使用者介面. (line   50)
* PathFinder (importlib.machinery 中的類別): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line   91)
* pathlib (模組):                        pathlib --- 面向对象的文件系统路径.
                                                             (line    6)
* PathLike (os 中的類別):                进程参数.           (line  104)
* pathname2url() (於 urllib.request 模組中): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  121)
* pathsep (於 os 模組中):                其他系统信息.       (line   95)
* path_hook() (importlib.machinery.FileFinder 的類別成員): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  174)
* path_hooks (於 sys 模組中):            sys --- 系统相关的参数和函数.
                                                             (line  915)
* path_importer_cache (於 sys 模組中):   sys --- 系统相关的参数和函数.
                                                             (line  923)
* path_mtime() (importlib.abc.SourceLoader 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  473)
* path_return_ok() (http.cookiejar.CookiePolicy 的方法): CookiePolicy 对象.
                                                             (line   47)
* path_stats() (importlib.abc.SourceLoader 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  456)
* path_stats() (importlib.machinery.SourceFileLoader 的方法): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  203)
* pattern (re.error 的屬性):             模块内容.           (line  307)
* pattern (re.Pattern 的屬性):           正则表达式对象 （正则对象）.
                                                             (line   97)
* Pattern (typing 中的類別):             其他具象类型.       (line   18)
* pause() (於 signal 模組中):            模块内容<5>.        (line  245)
* pause_reading() (asyncio.ReadTransport 的方法): 只读传输.  (line   12)
* pause_writing() (asyncio.BaseProtocol 的方法): 基础协议<2>.
                                                             (line   35)
* PAX_FORMAT (於 tarfile 模組中):        tarfile --- 读写tar归档文件.
                                                             (line  212)
* pax_headers (tarfile.TarFile 的屬性):  TarFile 对象.       (line  218)
* pax_headers (tarfile.TarInfo 的屬性):  TarInfo 对象.       (line   82)
* pbkdf2_hmac() (於 hashlib 模組中):     密钥派生.           (line   10)
* pd() (於 turtle 模組中):               绘图状态.           (line    6)
* Pdb (class in pdb):                    pdb --- Python 的调试器.
                                                             (line   15)
* Pdb (pdb 中的類別):                    pdb --- Python 的调试器.
                                                             (line  125)
* pdb (模組):                            pdb --- Python 的调试器.
                                                             (line    6)
* pdf() (statistics.NormalDist 的方法):  NormalDist 对象.    (line   57)
* peek() (bz2.BZ2File 的方法):           文件压缩和解压.     (line   64)
* peek() (gzip.GzipFile 的方法):         gzip --- 对 gzip 格式的支持.
                                                             (line  108)
* peek() (io.BufferedReader 的方法):     缓冲流.             (line   66)
* peek() (lzma.LZMAFile 的方法):         读写压缩文件.       (line   74)
* peek() (weakref.finalize 的方法):      weakref --- 弱引用. (line  221)
* peer (smtpd.SMTPChannel 的屬性):       SMTPChannel 对象.   (line   81)
* PEM_cert_to_DER_cert() (於 ssl 模組中): 证书处理.          (line   84)
* pen() (於 turtle 模組中):              绘图状态.           (line   32)
* pencolor() (於 turtle 模組中):         颜色控制.           (line    6)
* pending (ssl.MemoryBIO 的屬性):        内存 BIO 支持<2>.   (line  122)
* pending() (ssl.SSLSocket 的方法):      SSL 套接字.         (line  269)
* PendingDeprecationWarning:             警告.               (line   26)
* pendown() (於 turtle 模組中):          绘图状态.           (line    6)
* pensize() (於 turtle 模組中):          绘图状态.           (line   18)
* penup() (於 turtle 模組中):            绘图状态.           (line   12)
* PEP:                                   術語表.             (line  914)
* PERCENT (於 token 模組中):             token --- 与Python解析树一起使用的常量.
                                                             (line  118)
* PERCENTEQUAL (於 token 模組中):        token --- 与Python解析树一起使用的常量.
                                                             (line  182)
* Performance:                           timeit --- 测量小代码片段的执行时间.
                                                             (line    8)
* perf_counter() (於 time 模組中):       函数<3>.            (line  157)
* perf_counter_ns() (於 time 模組中):    函数<3>.            (line  166)
* perm() (於 math 模組中):               数论与表示函数.     (line  186)
* PermissionError:                       OS 异常.            (line   84)
* permutations() (於 itertools 模組中):  Itertool函数.       (line  361)
* Persist() (msilib.SummaryInformation 的方法): Summary Information Objects.
                                                             (line   29)
* persistence:                           pickle --- Python 对象序列化.
                                                             (line    8)
* persistent; objects:                   pickle --- Python 对象序列化.
                                                             (line    8)
* persistent_id (pickle protocol):       持久化外部对象.     (line    6)
* persistent_id() (pickle.Pickler 的方法): 模块接口.         (line  143)
* persistent_load (pickle protocol):     持久化外部对象.     (line    6)
* persistent_load() (pickle.Unpickler 的方法): 模块接口.     (line  239)
* pformat() (pprint.PrettyPrinter 的方法): PrettyPrinter 对象.
                                                             (line    8)
* pformat() (於 pprint 模組中):          pprint --- 数据美化输出.
                                                             (line   71)
* PF_CAN (於 socket 模組中):             常数<6>.            (line   88)
* PF_PACKET (於 socket 模組中):          常数<6>.            (line  157)
* PF_RDS (於 socket 模組中):             常数<6>.            (line  167)
* pgettext() (gettext.GNUTranslations 的方法): GNUTranslations 类.
                                                             (line   58)
* pgettext() (gettext.NullTranslations 的方法): NullTranslations 类.
                                                             (line   39)
* pgettext() (於 gettext 模組中):        GNU gettext API.    (line   62)
* PGO (於 test.support 模組中):          test support --- Utilities for the Python test suite.
                                                             (line  146)
* phase() (於 cmath 模組中):             到极坐标和从极坐标的转换.
                                                             (line   18)
* Philbrick, Geoff:                      给扩展函数的关键字参数.
                                                             (line   21)
* physical line:                         逻辑行.             (line    6)
* physical line <1>:                     显式拼接行.         (line    6)
* physical line <2>:                     字符串与字节串字面值.
                                                             (line   59)
* pi (於 cmath 模組中):                  常数<2>.            (line    6)
* pi (於 math 模組中):                   常数.               (line    6)
* pi() (xml.etree.ElementTree.TreeBuilder 的方法): TreeBuilder 对象.
                                                             (line   49)
* pickle (模組):                         pickle --- Python 对象序列化.
                                                             (line    6)
* pickle() (於 copyreg 模組中):          copyreg --- 注册配合 pickle 模块使用的函数.
                                                             (line   20)
* PickleBuffer (pickle 中的類別):        模块接口.           (line  263)
* PickleError:                           模块接口.           (line   85)
* Pickler (pickle 中的類別):             模块接口.           (line  107)
* pickletools (模組):                    pickletools --- pickle 开发者工具集.
                                                             (line    6)
* pickletools command line option; -a:   命令行选项<5>.      (line    6)
* pickletools command line option; –annotate: 命令行选项<5>. (line    6)
* pickletools command line option; –indentlevel=<num>: 命令行选项<5>.
                                                             (line   14)
* pickletools command line option; -l:   命令行选项<5>.      (line   14)
* pickletools command line option; -m:   命令行选项<5>.      (line   18)
* pickletools command line option; –memo: 命令行选项<5>.     (line   18)
* pickletools command line option; -o:   命令行选项<5>.      (line   10)
* pickletools command line option; –output=<file>: 命令行选项<5>.
                                                             (line   10)
* pickletools command line option; -p:   命令行选项<5>.      (line   22)
* pickletools command line option; –preamble=<preamble>: 命令行选项<5>.
                                                             (line   22)
* pickling; objects:                     pickle --- Python 对象序列化.
                                                             (line    8)
* PicklingError:                         模块接口.           (line   89)
* pid (asyncio.asyncio.subprocess.Process 的屬性): 与子进程交互.
                                                             (line  120)
* pid (multiprocessing.Process 的屬性):  Process 和异常.     (line   90)
* pid (subprocess.Popen 的屬性):         Popen 对象.         (line  121)
* PidfdChildWatcher (asyncio 中的類別):  进程监视器.         (line  124)
* pidfd_open() (於 os 模組中):           进程管理.           (line  278)
* pidfd_send_signal() (於 signal 模組中): 模块内容<5>.       (line  261)
* PIPE (於 subprocess 模組中):           使用 subprocess 模块.
                                                             (line  122)
* Pipe() (於 multiprocessing 模組中):    管道和队列.         (line   62)
* pipe() (於 os 模組中):                 文件描述符操作.     (line  326)
* pipe2() (於 os 模組中):                文件描述符操作.     (line  335)
* pipes (模組):                          pipes --- 终端管道接口.
                                                             (line    6)
* PIPE_BUF (於 select 模組中):           select --- 等待 I/O 完成.
                                                             (line  128)
* pipe_connection_lost() (asyncio.SubprocessProtocol 的方法): 子进程协议.
                                                             (line   17)
* pipe_data_received() (asyncio.SubprocessProtocol 的方法): 子进程协议.
                                                             (line    9)
* PIPE_MAX_SIZE (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  150)
* PIP_USER:                              Windows<19>.        (line  101)
* pkgutil (模組):                        pkgutil --- 包扩展工具.
                                                             (line    6)
* PKG_DIRECTORY (於 imp 模組中):         imp —— 由代码内部访问 import 。.
                                                             (line  317)
* placeholder (textwrap.TextWrapper 的屬性): textwrap --- 文本自动换行与填充.
                                                             (line  242)
* PLAT:                                  distutils util --- Miscellaneous other utility functions.
                                                             (line   99)
* platform (in module sys):              Process-wide parameters.
                                                             (line  172)
* platform (於 sys 模組中):              sys --- 系统相关的参数和函数.
                                                             (line  935)
* platform (模組):                       platform --- 获取底层平台的标识数据.
                                                             (line    6)
* platform() (於 platform 模組中):       跨平台.             (line   42)
* platlibdir (於 sys 模組中):            sys --- 系统相关的参数和函数.
                                                             (line  990)
* PlaySound() (於 winsound 模組中):      winsound —— Windows 系统的声音播放接口.
                                                             (line   18)
* plist; file:                           plistlib --- 生成与解析 Apple plist 文件.
                                                             (line    8)
* plistlib (模組):                       plistlib --- 生成与解析 Apple plist 文件.
                                                             (line    6)
* plock() (於 os 模組中):                进程管理.           (line  290)
* plus:                                  一元算术和位运算.   (line   13)
* PLUS (於 token 模組中):                token --- 与Python解析树一起使用的常量.
                                                             (line   78)
* plus() (decimal.Context 的方法):       上下文对象.         (line  368)
* PLUSEQUAL (於 token 模組中):           token --- 与Python解析树一起使用的常量.
                                                             (line  166)
* pm() (於 pdb 模組中):                  pdb --- Python 的调试器.
                                                             (line  117)
* POINTER() (於 ctypes 模組中):          工具函数.           (line  128)
* pointer() (於 ctypes 模組中):          工具函数.           (line  134)
* polar() (於 cmath 模組中):             到极坐标和从极坐标的转换.
                                                             (line   34)
* Policy (email.policy 中的類別):        email policy Policy 对象.
                                                             (line  103)
* poll() (multiprocessing.connection.Connection 的方法): 连接（Connection）对象.
                                                             (line   38)
* poll() (select.devpoll 的方法):        /dev/poll 轮询对象. (line   58)
* poll() (select.epoll 的方法):          边缘触发和水平触发的轮询 epoll 对象.
                                                             (line   93)
* poll() (select.poll 的方法):           Poll 对象.          (line   65)
* poll() (subprocess.Popen 的方法):      Popen 对象.         (line    8)
* poll() (於 select 模組中):             select --- 等待 I/O 完成.
                                                             (line   71)
* PollSelector (selectors 中的類別):     类<2>.              (line  149)
* Pool (multiprocessing.pool 中的類別):  进程池.             (line    8)
* pop() (array.array 的方法):            array --- 高效率的數值型態陣列.
                                                             (line  172)
* pop() (collections.deque 的方法):      deque 对象.         (line   77)
* pop() (dict 的方法):                   映射类型 --- dict.  (line  157)
* pop() (frozenset 的方法):              集合类型 --- set frozenset.
                                                             (line  188)
* pop() (mailbox.Mailbox 的方法):        Mailbox 对象.       (line  169)
* pop() (sequence method):               可变序列类型.       (line   14)
* POP3 (poplib 中的類別):                poplib --- POP3 协议客户端.
                                                             (line   24)
* POP3; protocol:                        poplib --- POP3 协议客户端.
                                                             (line    8)
* POP3_SSL (poplib 中的類別):            poplib --- POP3 协议客户端.
                                                             (line   40)
* Popen (subprocess 中的類別):           Popen 构造函数.     (line    9)
* popen() (in module os):                标准类型层级结构.   (line  492)
* popen() (in module os) <1>:            select --- 等待 I/O 完成.
                                                             (line  113)
* popen() (於 os 模組中):                进程管理.           (line  297)
* popitem() (collections.OrderedDict 的方法): OrderedDict 对象.
                                                             (line   40)
* popitem() (dict 的方法):               映射类型 --- dict.  (line  163)
* popitem() (mailbox.Mailbox 的方法):    Mailbox 对象.       (line  176)
* popleft() (collections.deque 的方法):  deque 对象.         (line   82)
* poplib (模組):                         poplib --- POP3 协议客户端.
                                                             (line    6)
* PopupMenu (tkinter.tix 中的類別):      Basic Widgets.      (line   52)
* pop_alignment() (formatter.formatter 的方法): The Formatter Interface.
                                                             (line   97)
* pop_all() (contextlib.ExitStack 的方法): 工具.             (line  392)
* POP_BLOCK (opcode):                    Python字节码说明.   (line  350)
* POP_EXCEPT (opcode):                   Python字节码说明.   (line  355)
* pop_font() (formatter.formatter 的方法): The Formatter Interface.
                                                             (line  109)
* POP_JUMP_IF_FALSE (opcode):            Python字节码说明.   (line  555)
* POP_JUMP_IF_TRUE (opcode):             Python字节码说明.   (line  549)
* pop_margin() (formatter.formatter 的方法): The Formatter Interface.
                                                             (line  121)
* pop_source() (shlex.shlex 的方法):     shlex 对象.         (line   53)
* pop_style() (formatter.formatter 的方法): The Formatter Interface.
                                                             (line  132)
* POP_TOP (opcode):                      Python字节码说明.   (line   56)
* port (http.cookiejar.Cookie 的屬性):   Cookie 对象<2>.     (line   32)
* portion（部分）:                       術語表.             (line  927)
* port_specified (http.cookiejar.Cookie 的屬性): Cookie 对象<2>.
                                                             (line   72)
* pos (json.JSONDecodeError 的屬性):     例外.               (line   18)
* pos (re.error 的屬性):                 模块内容.           (line  311)
* pos (re.Match 的屬性):                 匹配对象.           (line  140)
* pos() (於 operator 模組中):            operator --- 标准运算符替代函数.
                                                             (line  126)
* pos() (於 turtle 模組中):              获取海龟的状态.     (line    6)
* position (xml.etree.ElementTree.ParseError 的屬性): 异常<14>.
                                                             (line   17)
* position() (於 turtle 模組中):         获取海龟的状态.     (line    6)
* positional argument（位置引數）:       術語表.             (line  933)
* posix (模組):                          posix --- 最常见的 POSIX 系统调用.
                                                             (line    6)
* POSIX Shared Memory:                   multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line   10)
* POSIX; I/O control:                    termios --- POSIX 风格的 tty 控制.
                                                             (line    6)
* POSIXLY_CORRECT:                       getopt --- C 风格的命令行选项解析器.
                                                             (line   52)
* PosixPath (pathlib 中的類別):          具体路径.           (line   19)
* posix_fadvise() (於 os 模組中):        文件描述符操作.     (line  354)
* POSIX_FADV_DONTNEED (於 os 模組中):    文件描述符操作.     (line  367)
* POSIX_FADV_NOREUSE (於 os 模組中):     文件描述符操作.     (line  367)
* POSIX_FADV_NORMAL (於 os 模組中):      文件描述符操作.     (line  367)
* POSIX_FADV_RANDOM (於 os 模組中):      文件描述符操作.     (line  367)
* POSIX_FADV_SEQUENTIAL (於 os 模組中):  文件描述符操作.     (line  367)
* POSIX_FADV_WILLNEED (於 os 模組中):    文件描述符操作.     (line  367)
* posix_fallocate() (於 os 模組中):      文件描述符操作.     (line  345)
* posix_spawn() (於 os 模組中):          进程管理.           (line  318)
* posix_spawnp() (於 os 模組中):         进程管理.           (line  396)
* POSIX_SPAWN_CLOSE (於 os 模組中):      进程管理.           (line  344)
* POSIX_SPAWN_DUP2 (於 os 模組中):       进程管理.           (line  350)
* POSIX_SPAWN_OPEN (於 os 模組中):       进程管理.           (line  338)
* post() (nntplib.NNTP 的方法):          方法<3>.            (line  248)
* post() (ossaudiodev.oss_audio_device 的方法): 音频设备对象.
                                                             (line  162)
* postcmd() (cmd.Cmd 的方法):            Cmd 对象.           (line   74)
* postloop() (cmd.Cmd 的方法):           Cmd 对象.           (line   87)
* post_handshake_auth (ssl.SSLContext 的屬性): SSL 上下文.   (line  526)
* post_mortem() (於 pdb 模組中):         pdb --- Python 的调试器.
                                                             (line  112)
* post_setup() (venv.EnvBuilder 的方法): API<2>.             (line  104)
* Pow (ast 中的類別):                    表达式<2>.          (line   54)
* pow() (內建函式):                      內建函式.           (line 1079)
* pow() (於 math 模組中):                幂函数与对数函数.   (line   54)
* pow() (於 operator 模組中):            operator --- 标准运算符替代函数.
                                                             (line  131)
* power() (decimal.Context 的方法):      上下文对象.         (line  373)
* power; operation:                      幂运算符.           (line    6)
* pp (pdb command):                      调试器命令.         (line  200)
* pp() (於 pprint 模組中):               pprint --- 数据美化输出.
                                                             (line   82)
* pprint (模組):                         pprint --- 数据美化输出.
                                                             (line    6)
* pprint() (pprint.PrettyPrinter 的方法): PrettyPrinter 对象.
                                                             (line   13)
* pprint() (於 pprint 模組中):           pprint --- 数据美化输出.
                                                             (line   90)
* prcal() (於 calendar 模組中):          calendar --- 日历相关函数.
                                                             (line  301)
* pread() (於 os 模組中):                文件描述符操作.     (line  381)
* preadv() (於 os 模組中):               文件描述符操作.     (line  393)
* preamble (email.message.EmailMessage 的屬性): email message 表示一封电子邮件信息.
                                                             (line  576)
* preamble (email.message.Message 的屬性): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  584)
* precmd() (cmd.Cmd 的方法):             Cmd 对象.           (line   67)
* prefix:                                与Python相关的路径和文件.
                                                             (line    6)
* prefix <1>:                            包含文件.           (line   32)
* prefix <2>:                            包含文件.           (line   35)
* prefix <3>:                            包含文件.           (line   39)
* prefix (xml.dom.Attr 的屬性):          Attr 对象.          (line   16)
* prefix (xml.dom.Node 的屬性):          节点对象.           (line   58)
* prefix (zipimport.zipimporter 的屬性): zipimporter 对象.   (line   66)
* PREFIX (於 distutils.sysconfig 模組中): distutils sysconfig --- System configuration information.
                                                             (line   19)
* prefix (於 sys 模組中):                sys --- 系统相关的参数和函数.
                                                             (line 1011)
* PREFIXES (於 site 模組中):             模块内容<8>.        (line    6)
* prefixlen (ipaddress.IPv4Network 的屬性): 网络对象.        (line  112)
* prefixlen (ipaddress.IPv6Network 的屬性): 网络对象.        (line  295)
* preloop() (cmd.Cmd 的方法):            Cmd 对象.           (line   82)
* prepare() (graphlib.TopologicalSorter 的方法): graphlib --- 操作类似图的结构的功能.
                                                             (line   85)
* prepare() (logging.handlers.QueueHandler 的方法): QueueHandler.
                                                             (line   34)
* prepare() (logging.handlers.QueueListener 的方法): QueueListener.
                                                             (line   45)
* prepare_class() (於 types 模組中):     动态类型创建.       (line   19)
* prepare_input_source() (於 xml.sax.saxutils 模組中): xml sax saxutils --- SAX 工具集.
                                                             (line   64)
* prepend() (pipes.Template 的方法):     模板对象.           (line   35)
* preprocess() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  431)
* PrettyPrinter (pprint 中的類別):       pprint --- 数据美化输出.
                                                             (line   25)
* prev() (tkinter.ttk.Treeview 的方法):  ttk Treeview.       (line  207)
* previousSibling (xml.dom.Node 的屬性): 节点对象.           (line   28)
* primary:                               原型.               (line    6)
* print (2to3 fixer):                    修复器.             (line  246)
* print() (built-in function); __str__() (object method): 基本定制.
                                                             (line  105)
* print() (內建函式):                    內建函式.           (line 1114)
* printable (於 string 模組中):          字符串常量.         (line   40)
* printdir() (zipfile.ZipFile 的方法):   ZipFile 对象.       (line  181)
* printf-style formatting:               printf 风格的字符串格式化.
                                                             (line    6)
* printf-style formatting <1>:           printf 风格的字节串格式化.
                                                             (line    6)
* print_callees() (pstats.Stats 的方法): Stats 类.           (line  217)
* print_callers() (pstats.Stats 的方法): Stats 类.           (line  196)
* print_directory() (於 cgi 模組中):     函数<9>.            (line   53)
* print_environ() (於 cgi 模組中):       函数<9>.            (line   45)
* print_environ_usage() (於 cgi 模組中): 函数<9>.            (line   57)
* print_exc() (timeit.Timer 的方法):     Python 接口.        (line  104)
* print_exc() (於 traceback 模組中):     traceback --- 打印或检索堆栈回溯.
                                                             (line   57)
* print_exception() (於 traceback 模組中): traceback --- 打印或检索堆栈回溯.
                                                             (line   32)
* PRINT_EXPR (opcode):                   Python字节码说明.   (line  298)
* print_form() (於 cgi 模組中):          函数<9>.            (line   49)
* print_help() (argparse.ArgumentParser 的方法): 打印帮助.   (line   15)
* print_last() (於 traceback 模組中):    traceback --- 打印或检索堆栈回溯.
                                                             (line   62)
* print_stack() (asyncio.Task 的方法):   Task 对象.          (line  171)
* print_stack() (於 traceback 模組中):   traceback --- 打印或检索堆栈回溯.
                                                             (line   69)
* print_stats() (profile.Profile 的方法): profile 和 cProfile 模块参考.
                                                             (line   89)
* print_stats() (pstats.Stats 的方法):   Stats 类.           (line  164)
* print_tb() (於 traceback 模組中):      traceback --- 打印或检索堆栈回溯.
                                                             (line   20)
* print_usage() (argparse.ArgumentParser 的方法): 打印帮助.  (line    9)
* print_usage() (optparse.OptionParser 的方法): Other methods.
                                                             (line   15)
* print_version() (optparse.OptionParser 的方法): Printing a version string.
                                                             (line   26)
* print_warning() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  567)
* PriorityQueue (asyncio 中的類別):      优先级队列.         (line    6)
* PriorityQueue (queue 中的類別):        queue --- 一个同步的队列类.
                                                             (line   41)
* PRIO_PGRP (於 os 模組中):              进程参数.           (line  245)
* PRIO_PROCESS (於 os 模組中):           进程参数.           (line  245)
* PRIO_USER (於 os 模組中):              进程参数.           (line  245)
* private; names:                        标识符（名称）.     (line   10)
* prlimit() (於 resource 模組中):        资源限制<2>.        (line   47)
* prmonth() (calendar.TextCalendar 的方法): calendar --- 日历相关函数.
                                                             (line  119)
* prmonth() (於 calendar 模組中):        calendar --- 日历相关函数.
                                                             (line  292)
* ProactorEventLoop (asyncio 中的類別):  事件循环实现.       (line   28)
* procedure; call:                       表达式语句.         (line   15)
* Process (multiprocessing 中的類別):    Process 和异常.     (line    6)
* process() (logging.LoggerAdapter 的方法): LoggerAdapter 对象.
                                                             (line   15)
* process; group:                        进程参数.           (line  164)
* process; group <1>:                    进程参数.           (line  214)
* process; id:                           进程参数.           (line  220)
* process; id of parent:                 进程参数.           (line  224)
* process; killing:                      进程管理.           (line  249)
* process; killing <1>:                  进程管理.           (line  266)
* process; scheduling priority:          进程参数.           (line  234)
* process; scheduling priority <1>:      进程参数.           (line  352)
* process; signalling:                   进程管理.           (line  249)
* process; signalling <1>:               进程管理.           (line  266)
* ProcessError:                          Process 和异常.     (line  175)
* processes, light-weight:               _thread --- 底层多线程 API.
                                                             (line    6)
* processingInstruction() (xml.sax.handler.ContentHandler 的方法): ContentHandler 对象.
                                                             (line  138)
* ProcessingInstruction() (於 xml.etree.ElementTree 模組中): 函数<7>.
                                                             (line  153)
* ProcessingInstructionHandler() (xml.parsers.expat.xmlparser 的方法): XMLParser对象<2>.
                                                             (line  196)
* ProcessLookupError:                    OS 异常.            (line   89)
* processor time:                        函数<3>.            (line  174)
* processor time <1>:                    函数<3>.            (line  416)
* processor() (於 platform 模組中):      跨平台.             (line   58)
* ProcessPoolExecutor (concurrent.futures 中的類別): ProcessPoolExecutor.
                                                             (line   17)
* process_exited() (asyncio.SubprocessProtocol 的方法): 子进程协议.
                                                             (line   23)
* process_message() (smtpd.SMTPServer 的方法): SMTPServer 对象.
                                                             (line   35)
* process_request() (socketserver.BaseServer 的方法): Server 对象<2>.
                                                             (line  135)
* process_time() (於 time 模組中):       函数<3>.            (line  172)
* process_time_ns() (於 time 模組中):    函数<3>.            (line  180)
* process_tokens() (於 tabnanny 模組中): tabnanny --- 模糊缩进检测.
                                                             (line   38)
* prod() (於 math 模組中):               数论与表示函数.     (line  199)
* product() (於 itertools 模組中):       Itertool函数.       (line  415)
* Profile (profile 中的類別):            profile 和 cProfile 模块参考.
                                                             (line   34)
* profile (模組):                        profile 和 cProfile 模块参考.
                                                             (line    6)
* profile function:                      threading --- 基于线程的并行.
                                                             (line  115)
* profile function <1>:                  sys --- 系统相关的参数和函数.
                                                             (line  622)
* profile function <2>:                  sys --- 系统相关的参数和函数.
                                                             (line 1045)
* profiler:                              sys --- 系统相关的参数和函数.
                                                             (line  622)
* profiler <1>:                          sys --- 系统相关的参数和函数.
                                                             (line 1045)
* profiling, deterministic:              profile分析器简介.  (line    6)
* program:                               完整的 Python 程序. (line    6)
* ProgrammingError:                      异常<4>.            (line   23)
* Progressbar (tkinter.ttk 中的類別):    ttk Progressbar.    (line    6)
* prompt (cmd.Cmd 的屬性):               Cmd 对象.           (line   95)
* prompts, interpreter:                  sys --- 系统相关的参数和函数.
                                                             (line 1026)
* prompt_user_passwd() (urllib.request.FancyURLopener 的方法): 沿袭的接口.
                                                             (line  148)
* propagate (logging.Logger 的屬性):     记录器对象.         (line   20)
* property (內建類別):                   內建函式.           (line 1136)
* property list:                         plistlib --- 生成与解析 Apple plist 文件.
                                                             (line    8)
* PropertyMock (unittest.mock 中的類別): Mock 类.            (line  608)
* property_declaration_handler (於 xml.sax.handler 模組中): xml sax handler --- SAX 处理句柄的基类.
                                                             (line   92)
* property_dom_node (於 xml.sax.handler 模組中): xml sax handler --- SAX 处理句柄的基类.
                                                             (line   99)
* property_lexical_handler (於 xml.sax.handler 模組中): xml sax handler --- SAX 处理句柄的基类.
                                                             (line   85)
* property_xml_string (於 xml.sax.handler 模組中): xml sax handler --- SAX 处理句柄的基类.
                                                             (line  106)
* proto (socket.socket 的屬性):          套接字对象.         (line  505)
* Protocol (asyncio 中的類別):           基础协议.           (line   10)
* protocol (ssl.SSLContext 的屬性):      SSL 上下文.         (line  546)
* Protocol (typing 中的類別):            构建泛型类型.       (line   79)
* protocol; context management:          上下文管理器类型.   (line    6)
* protocol; iterator:                    迭代器类型.         (line    6)
* protocol; Telnet:                      telnetlib -- Telnet 客户端.
                                                             (line    8)
* ProtocolError (xmlrpc.client 中的類別): ProtocolError 对象.
                                                             (line    6)
* PROTOCOL_SSLv2 (於 ssl 模組中):        常量<3>.            (line  135)
* PROTOCOL_SSLv23 (於 ssl 模組中):       常量<3>.            (line  129)
* PROTOCOL_SSLv3 (於 ssl 模組中):        常量<3>.            (line  145)
* PROTOCOL_TLS (於 ssl 模組中):          常量<3>.            (line  107)
* PROTOCOL_TLSv1 (於 ssl 模組中):        常量<3>.            (line  157)
* PROTOCOL_TLSv1_1 (於 ssl 模組中):      常量<3>.            (line  165)
* PROTOCOL_TLSv1_2 (於 ssl 模組中):      常量<3>.            (line  175)
* PROTOCOL_TLS_CLIENT (於 ssl 模組中):   常量<3>.            (line  114)
* PROTOCOL_TLS_SERVER (於 ssl 模組中):   常量<3>.            (line  122)
* protocol_version (http.server.BaseHTTPRequestHandler 的屬性): http server --- HTTP 服务器.
                                                             (line  134)
* PROTOCOL_VERSION (imaplib.IMAP4 的屬性): IMAP4 对象.       (line  352)
* prot_c() (ftplib.FTP_TLS 的方法):      FTP_TLS 对象.       (line   32)
* prot_p() (ftplib.FTP_TLS 的方法):      FTP_TLS 对象.       (line   28)
* provisional API（暫行 API）:           術語表.             (line  937)
* provisional package（暫行套件）:       術語表.             (line  951)
* proxy() (於 weakref 模組中):           weakref --- 弱引用. (line  103)
* proxyauth() (imaplib.IMAP4 的方法):    IMAP4 对象.         (line  173)
* ProxyBasicAuthHandler (urllib.request 中的類別): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  299)
* ProxyDigestAuthHandler (urllib.request 中的類別): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  324)
* ProxyHandler (urllib.request 中的類別): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  238)
* ProxyType (於 weakref 模組中):         weakref --- 弱引用. (line  247)
* ProxyTypes (於 weakref 模組中):        weakref --- 弱引用. (line  255)
* pryear() (calendar.TextCalendar 的方法): calendar --- 日历相关函数.
                                                             (line  130)
* ps1 (於 sys 模組中):                   sys --- 系统相关的参数和函数.
                                                             (line 1023)
* ps2 (於 sys 模組中):                   sys --- 系统相关的参数和函数.
                                                             (line 1023)
* pstats (模組):                         Stats 类.           (line    7)
* pstdev() (於 statistics 模組中):       函式細節.           (line  238)
* pthreads:                              _thread --- 底层多线程 API.
                                                             (line   13)
* pthread_getcpuclockid() (於 time 模組中): 函数<3>.         (line   19)
* pthread_kill() (於 signal 模組中):     模块内容<5>.        (line  273)
* pthread_sigmask() (於 signal 模組中):  模块内容<5>.        (line  298)
* pty (模組):                            pty --- 伪终端工具. (line    6)
* pu() (於 turtle 模組中):               绘图状态.           (line   12)
* publicId (xml.dom.DocumentType 的屬性): 文档类型对象.      (line   13)
* PullDom (xml.dom.pulldom 中的類別):    xml dom pulldom --- 支持构建部分 DOM 树.
                                                             (line   69)
* punctuation (於 string 模組中):        字符串常量.         (line   35)
* punctuation_chars (shlex.shlex 的屬性): shlex 对象.        (line  150)
* PurePath (pathlib 中的類別):           纯路径.             (line    9)
* PurePath.anchor (於 pathlib 模組中):   方法和特征属性.     (line   40)
* PurePath.drive (於 pathlib 模組中):    方法和特征属性.     (line    8)
* PurePath.name (於 pathlib 模組中):     方法和特征属性.     (line   92)
* PurePath.parent (於 pathlib 模組中):   方法和特征属性.     (line   66)
* PurePath.parents (於 pathlib 模組中):  方法和特征属性.     (line   53)
* PurePath.parts (於 pathlib 模組中):    访问个别部分.       (line    8)
* PurePath.root (於 pathlib 模組中):     方法和特征属性.     (line   24)
* PurePath.stem (於 pathlib 模組中):     方法和特征属性.     (line  128)
* PurePath.suffix (於 pathlib 模組中):   方法和特征属性.     (line  106)
* PurePath.suffixes (於 pathlib 模組中): 方法和特征属性.     (line  117)
* PurePosixPath (pathlib 中的類別):      纯路径.             (line   63)
* PureProxy (smtpd 中的類別):            PureProxy对象.      (line    6)
* PureWindowsPath (pathlib 中的類別):    纯路径.             (line   72)
* purge() (於 re 模組中):                模块内容.           (line  293)
* Purpose.CLIENT_AUTH (於 ssl 模組中):   常量<3>.            (line  455)
* Purpose.SERVER_AUTH (於 ssl 模組中):   常量<3>.            (line  447)
* push() (asynchat.async_chat 的方法):   asynchat --- 异步套接字指令/响应处理程序.
                                                             (line   87)
* push() (code.InteractiveConsole 的方法): 交互式控制台对象. (line   24)
* push() (contextlib.ExitStack 的方法):  工具.               (line  359)
* pushbutton() (msilib.Dialog 的方法):   GUI classes.        (line   68)
* push_alignment() (formatter.formatter 的方法): The Formatter Interface.
                                                             (line   90)
* push_async_callback() (contextlib.AsyncExitStack 的方法): 工具.
                                                             (line  439)
* push_async_exit() (contextlib.AsyncExitStack 的方法): 工具.
                                                             (line  434)
* push_font() (formatter.formatter 的方法): The Formatter Interface.
                                                             (line  101)
* push_margin() (formatter.formatter 的方法): The Formatter Interface.
                                                             (line  113)
* push_source() (shlex.shlex 的方法):    shlex 对象.         (line   48)
* push_style() (formatter.formatter 的方法): The Formatter Interface.
                                                             (line  125)
* push_token() (shlex.shlex 的方法):     shlex 对象.         (line   16)
* push_with_producer() (asynchat.async_chat 的方法): asynchat --- 异步套接字指令/响应处理程序.
                                                             (line   93)
* put() (asyncio.Queue 的方法):          队列.               (line   56)
* put() (multiprocessing.Queue 的方法):  管道和队列.         (line  102)
* put() (multiprocessing.SimpleQueue 的方法): 管道和队列.    (line  194)
* put() (queue.Queue 的方法):            Queue对象.          (line   26)
* put() (queue.SimpleQueue 的方法):      SimpleQueue 对象.   (line   17)
* putch() (於 msvcrt 模組中):            控制台 I/O.         (line   30)
* putenv() (於 os 模組中):               进程参数.           (line  289)
* putheader() (http.client.HTTPConnection 的方法): HTTPConnection 对象.
                                                             (line  114)
* putp() (於 curses 模組中):             函数<4>.            (line  310)
* putrequest() (http.client.HTTPConnection 的方法): HTTPConnection 对象.
                                                             (line  105)
* putwch() (於 msvcrt 模組中):           控制台 I/O.         (line   34)
* putwin() (curses.window 的方法):       Window 对象.        (line  390)
* put_nowait() (asyncio.Queue 的方法):   队列.               (line   61)
* put_nowait() (multiprocessing.Queue 的方法): 管道和队列.   (line  115)
* put_nowait() (queue.Queue 的方法):     Queue对象.          (line   35)
* put_nowait() (queue.SimpleQueue 的方法): SimpleQueue 对象. (line   30)
* pvariance() (於 statistics 模組中):    函式細節.           (line  246)
* pwd (模組):                            pwd --- 用户密码数据库.
                                                             (line    6)
* pwd() (ftplib.FTP 的方法):             FTP 对象.           (line  184)
* pwrite() (於 os 模組中):               文件描述符操作.     (line  444)
* pwritev() (於 os 模組中):              文件描述符操作.     (line  455)
* PyAnySet_Check (C 函式):               集合对象.           (line   49)
* PyAnySet_CheckExact (C 函式):          集合对象.           (line   54)
* PyArg_Parse (C 函式):                  API 函数.           (line   44)
* PyArg_ParseTuple (C 函式):             API 函数.           (line    6)
* PyArg_ParseTuple():                    提取扩展函数的参数. (line    6)
* PyArg_ParseTupleAndKeywords (C 函式):  API 函数.           (line   19)
* PyArg_ParseTupleAndKeywords():         给扩展函数的关键字参数.
                                                             (line    6)
* PyArg_UnpackTuple (C 函式):            API 函数.           (line   51)
* PyArg_ValidateKeywordArguments (C 函式): API 函数.         (line   36)
* PyArg_VaParse (C 函式):                API 函数.           (line   12)
* PyArg_VaParseTupleAndKeywords (C 函式): API 函数.          (line   29)
* PyASCIIObject (C 型態):                Unicode类型.        (line   29)
* PyAsyncMethods (C 型態):               Async Object Structures.
                                                             (line    8)
* PyAsyncMethods.am_aiter (C 成員函數):  Async Object Structures.
                                                             (line   34)
* PyAsyncMethods.am_anext (C 成員函數):  Async Object Structures.
                                                             (line   46)
* PyAsyncMethods.am_await (C 成員函數):  Async Object Structures.
                                                             (line   22)
* PyBool_Check (C 函式):                 布林物件.           (line    9)
* PyBool_FromLong (C 函式):              布林物件.           (line   31)
* PyBufferProcs:                         缓冲协议.           (line   17)
* PyBufferProcs (C 型態):                Buffer Object Structures.
                                                             (line    6)
* PyBufferProcs.bf_getbuffer (C 成員函數): Buffer Object Structures.
                                                             (line   12)
* PyBufferProcs.bf_releasebuffer (C 成員函數): Buffer Object Structures.
                                                             (line   60)
* PyBuffer_FillContiguousStrides (C 函式): 缓冲区相关函数.   (line   74)
* PyBuffer_FillInfo (C 函式):            缓冲区相关函数.     (line   82)
* PyBuffer_FromContiguous (C 函式):      缓冲区相关函数.     (line   54)
* PyBuffer_GetPointer (C 函式):          缓冲区相关函数.     (line   48)
* PyBuffer_IsContiguous (C 函式):        缓冲区相关函数.     (line   42)
* PyBuffer_Release (C 函式):             缓冲区相关函数.     (line   27)
* PyBuffer_SizeFromFormat (C 函式):      缓冲区相关函数.     (line   35)
* PyBuffer_ToContiguous (C 函式):        缓冲区相关函数.     (line   63)
* PyBUF_ANY_CONTIGUOUS (C 巨集):         连续性的请求.       (line   19)
* PyBUF_CONTIG (C 巨集):                 复合请求.           (line   34)
* PyBUF_CONTIG_RO (C 巨集):              复合请求.           (line   37)
* PyBUF_C_CONTIGUOUS (C 巨集):           连续性的请求.       (line   13)
* PyBUF_FORMAT (C 巨集):                 只读，格式.         (line   12)
* PyBUF_FULL (C 巨集):                   复合请求.           (line   16)
* PyBUF_FULL_RO (C 巨集):                复合请求.           (line   19)
* PyBUF_F_CONTIGUOUS (C 巨集):           连续性的请求.       (line   16)
* PyBUF_INDIRECT (C 巨集):               形状，步幅，子偏移量.
                                                             (line   13)
* PyBUF_ND (C 巨集):                     形状，步幅，子偏移量.
                                                             (line   19)
* PyBUF_RECORDS (C 巨集):                复合请求.           (line   22)
* PyBUF_RECORDS_RO (C 巨集):             复合请求.           (line   25)
* PyBUF_SIMPLE (C 巨集):                 形状，步幅，子偏移量.
                                                             (line   22)
* PyBUF_STRIDED (C 巨集):                复合请求.           (line   28)
* PyBUF_STRIDED_RO (C 巨集):             复合请求.           (line   31)
* PyBUF_STRIDES (C 巨集):                形状，步幅，子偏移量.
                                                             (line   16)
* PyBUF_WRITABLE (C 巨集):               只读，格式.         (line    6)
* PyByteArrayObject (C 型態):            字节数组对象.       (line    6)
* PyByteArray_AsString (C 函式):         直接 API 函数.      (line   23)
* PyByteArray_AS_STRING (C 函式):        宏.                 (line    8)
* PyByteArray_Check (C 函式):            类型检查宏.         (line    6)
* PyByteArray_CheckExact (C 函式):       类型检查宏.         (line   11)
* PyByteArray_Concat (C 函式):           直接 API 函数.      (line   15)
* PyByteArray_FromObject (C 函式):       直接 API 函数.      (line    6)
* PyByteArray_FromStringAndSize (C 函式): 直接 API 函数.     (line   10)
* PyByteArray_GET_SIZE (C 函式):         宏.                 (line   12)
* PyByteArray_Resize (C 函式):           直接 API 函数.      (line   28)
* PyByteArray_Size (C 函式):             直接 API 函数.      (line   19)
* PyByteArray_Type (C 變數):             字节数组对象.       (line   10)
* PyBytesObject (C 型態):                字节对象.           (line    9)
* PyBytes_AsString (C 函式):             字节对象.           (line  111)
* PyBytes_AsStringAndSize (C 函式):      字节对象.           (line  124)
* PyBytes_AS_STRING (C 函式):            字节对象.           (line  120)
* PyBytes_Check (C 函式):                字节对象.           (line   18)
* PyBytes_CheckExact (C 函式):           字节对象.           (line   23)
* PyBytes_Concat (C 函式):               字节对象.           (line  144)
* PyBytes_ConcatAndDel (C 函式):         字节对象.           (line  151)
* PyBytes_FromFormat (C 函式):           字节对象.           (line   40)
* PyBytes_FromFormatV (C 函式):          字节对象.           (line   94)
* PyBytes_FromObject (C 函式):           字节对象.           (line   99)
* PyBytes_FromString (C 函式):           字节对象.           (line   28)
* PyBytes_FromStringAndSize (C 函式):    字节对象.           (line   33)
* PyBytes_GET_SIZE (C 函式):             字节对象.           (line  107)
* PyBytes_Size (C 函式):                 字节对象.           (line  103)
* PyBytes_Type (C 變數):                 字节对象.           (line   13)
* pycache_prefix (於 sys 模組中):        sys --- 系统相关的参数和函数.
                                                             (line  243)
* PyCallable_Check (C 函式):             调用支持 API.       (line    6)
* PyCallIter_Check (C 函式):             迭代器（Iterator）物件.
                                                             (line   29)
* PyCallIter_New (C 函式):               迭代器（Iterator）物件.
                                                             (line   34)
* PyCallIter_Type (C 變數):              迭代器（Iterator）物件.
                                                             (line   24)
* PyCapsule (C 型態):                    Capsule 对象.       (line   10)
* PyCapsule_CheckExact (C 函式):         Capsule 对象.       (line   26)
* PyCapsule_Destructor (C 型態):         Capsule 对象.       (line   17)
* PyCapsule_GetContext (C 函式):         Capsule 对象.       (line   70)
* PyCapsule_GetDestructor (C 函式):      Capsule 对象.       (line   60)
* PyCapsule_GetName (C 函式):            Capsule 对象.       (line   79)
* PyCapsule_GetPointer (C 函式):         Capsule 对象.       (line   50)
* PyCapsule_Import (C 函式):             Capsule 对象.       (line   88)
* PyCapsule_IsValid (C 函式):            Capsule 对象.       (line  100)
* PyCapsule_New (C 函式):                Capsule 对象.       (line   31)
* PyCapsule_SetContext (C 函式):         Capsule 对象.       (line  114)
* PyCapsule_SetDestructor (C 函式):      Capsule 对象.       (line  120)
* PyCapsule_SetName (C 函式):            Capsule 对象.       (line  128)
* PyCapsule_SetPointer (C 函式):         Capsule 对象.       (line  136)
* PyCellObject (C 型態):                 Cell 物件.          (line   13)
* PyCell_Check (C 函式):                 Cell 物件.          (line   21)
* PyCell_Get (C 函式):                   Cell 物件.          (line   30)
* PyCell_GET (C 函式):                   Cell 物件.          (line   33)
* PyCell_New (C 函式):                   Cell 物件.          (line   26)
* PyCell_Set (C 函式):                   Cell 物件.          (line   37)
* PyCell_SET (C 函式):                   Cell 物件.          (line   43)
* PyCell_Type (C 變數):                  Cell 物件.          (line   17)
* PyCFunction (C 型態):                  Implementing functions and methods.
                                                             (line    6)
* PyCFunctionWithKeywords (C 型態):      Implementing functions and methods.
                                                             (line   20)
* PyCF_ALLOW_TOP_LEVEL_AWAIT (於 ast 模組中): Compiler Flags.
                                                             (line    9)
* PyCF_ONLY_AST (於 ast 模組中):         Compiler Flags.     (line   16)
* PyCF_TYPE_COMMENTS (於 ast 模組中):    Compiler Flags.     (line   21)
* PycInvalidationMode (py_compile 中的類別): py_compile --- 编译 Python 源文件.
                                                             (line   74)
* pyclbr (模組):                         pyclbr --- Python 模块浏览器支持.
                                                             (line    6)
* PyCMethod (C 型態):                    Implementing functions and methods.
                                                             (line   50)
* PyCodec_BackslashReplaceErrors (C 函式): 用于Unicode编码错误处理程序的注册表API.
                                                             (line   42)
* PyCodec_Decode (C 函式):               编解码器注册与支持功能.
                                                             (line   26)
* PyCodec_Decoder (C 函式):              Codec 查找API.      (line   14)
* PyCodec_Encode (C 函式):               编解码器注册与支持功能.
                                                             (line   18)
* PyCodec_Encoder (C 函式):              Codec 查找API.      (line   10)
* PyCodec_IgnoreErrors (C 函式):         用于Unicode编码错误处理程序的注册表API.
                                                             (line   31)
* PyCodec_IncrementalDecoder (C 函式):   Codec 查找API.      (line   23)
* PyCodec_IncrementalEncoder (C 函式):   Codec 查找API.      (line   18)
* PyCodec_KnownEncoding (C 函式):        编解码器注册与支持功能.
                                                             (line   13)
* PyCodec_LookupError (C 函式):          用于Unicode编码错误处理程序的注册表API.
                                                             (line   23)
* PyCodec_NameReplaceErrors (C 函式):    用于Unicode编码错误处理程序的注册表API.
                                                             (line   46)
* PyCodec_Register (C 函式):             编解码器注册与支持功能.
                                                             (line    6)
* PyCodec_RegisterError (C 函式):        用于Unicode编码错误处理程序的注册表API.
                                                             (line    6)
* PyCodec_ReplaceErrors (C 函式):        用于Unicode编码错误处理程序的注册表API.
                                                             (line   34)
* PyCodec_StreamReader (C 函式):         Codec 查找API.      (line   28)
* PyCodec_StreamWriter (C 函式):         Codec 查找API.      (line   34)
* PyCodec_StrictErrors (C 函式):         用于Unicode编码错误处理程序的注册表API.
                                                             (line   28)
* PyCodec_XMLCharRefReplaceErrors (C 函式): 用于Unicode编码错误处理程序的注册表API.
                                                             (line   38)
* PyCodeObject (C 型態):                 代码对象<2>.        (line    9)
* PyCode_Check (C 函式):                 代码对象<2>.        (line   18)
* PyCode_GetNumFree (C 函式):            代码对象<2>.        (line   23)
* PyCode_New (C 函式):                   代码对象<2>.        (line   27)
* PyCode_NewEmpty (C 函式):              代码对象<2>.        (line   54)
* PyCode_NewWithPosOnlyArgs (C 函式):    代码对象<2>.        (line   41)
* PyCode_Type (C 變數):                  代码对象<2>.        (line   13)
* PyCompactUnicodeObject (C 型態):       Unicode类型.        (line   29)
* PyCompileError:                        py_compile --- 编译 Python 源文件.
                                                             (line   16)
* PyCompilerFlags (C 型態):              The Very High Level Layer.
                                                             (line  404)
* PyCompilerFlags.cf_feature_version (C 成員函數): The Very High Level Layer.
                                                             (line  420)
* PyCompilerFlags.cf_flags (C 成員函數): The Very High Level Layer.
                                                             (line  416)
* PyComplexObject (C 型態):              表示复数的Python对象.
                                                             (line    6)
* PyComplex_AsCComplex (C 函式):         表示复数的Python对象.
                                                             (line   41)
* PyComplex_Check (C 函式):              表示复数的Python对象.
                                                             (line   15)
* PyComplex_CheckExact (C 函式):         表示复数的Python对象.
                                                             (line   20)
* PyComplex_FromCComplex (C 函式):       表示复数的Python对象.
                                                             (line   25)
* PyComplex_FromDoubles (C 函式):        表示复数的Python对象.
                                                             (line   29)
* PyComplex_ImagAsDouble (C 函式):       表示复数的Python对象.
                                                             (line   37)
* PyComplex_RealAsDouble (C 函式):       表示复数的Python对象.
                                                             (line   33)
* PyComplex_Type (C 變數):               表示复数的Python对象.
                                                             (line   10)
* PyConfig (C 型態):                     PyConfig.           (line    6)
* PyConfig.argv (C 成員函數):            PyConfig.           (line   99)
* PyConfig.base_executable (C 成員函數): PyConfig.           (line  111)
* PyConfig.base_exec_prefix (C 成員函數): PyConfig.          (line  107)
* PyConfig.base_prefix (C 成員函數):     PyConfig.           (line  116)
* PyConfig.buffered_stdio (C 成員函數):  PyConfig.           (line  128)
* PyConfig.bytes_warning (C 成員函數):   PyConfig.           (line  135)
* PyConfig.check_hash_pycs_mode (C 成員函數): PyConfig.      (line  142)
* PyConfig.configure_c_stdio (C 成員函數): PyConfig.         (line  152)
* PyConfig.dev_mode (C 成員函數):        PyConfig.           (line  158)
* PyConfig.dump_refs (C 成員函數):       PyConfig.           (line  162)
* PyConfig.executable (C 成員函數):      PyConfig.           (line  172)
* PyConfig.exec_prefix (C 成員函數):     PyConfig.           (line  168)
* PyConfig.faulthandler (C 成員函數):    PyConfig.           (line  176)
* PyConfig.filesystem_encoding (C 成員函數): PyConfig.       (line  181)
* PyConfig.filesystem_errors (C 成員函數): PyConfig.         (line  185)
* PyConfig.hash_seed (C 成員函數):       PyConfig.           (line  190)
* PyConfig.home (C 成員函數):            PyConfig.           (line  200)
* PyConfig.import_time (C 成員函數):     PyConfig.           (line  207)
* PyConfig.inspect (C 成員函數):         PyConfig.           (line  211)
* PyConfig.install_signal_handlers (C 成員函數): PyConfig.   (line  215)
* PyConfig.interactive (C 成員函數):     PyConfig.           (line  219)
* PyConfig.isolated (C 成員函數):        PyConfig.           (line  223)
* PyConfig.legacy_windows_stdio (C 成員函數): PyConfig.      (line  237)
* PyConfig.malloc_stats (C 成員函數):    PyConfig.           (line  246)
* PyConfig.module_search_paths (C 成員函數): PyConfig.       (line  262)
* PyConfig.module_search_paths_set (C 成員函數): PyConfig.   (line  264)
* PyConfig.optimization_level (C 成員函數): PyConfig.        (line  271)
* PyConfig.parser_debug (C 成員函數):    PyConfig.           (line  287)
* PyConfig.parse_argv (C 成員函數):      PyConfig.           (line  281)
* PyConfig.pathconfig_warnings (C 成員函數): PyConfig.       (line  292)
* PyConfig.platlibdir (C 成員函數):      PyConfig.           (line  120)
* PyConfig.prefix (C 成員函數):          PyConfig.           (line  298)
* PyConfig.program_name (C 成員函數):    PyConfig.           (line  302)
* PyConfig.pycache_prefix (C 成員函數):  PyConfig.           (line  307)
* PyConfig.pythonpath_env (C 成員函數):  PyConfig.           (line  254)
* PyConfig.quiet (C 成員函數):           PyConfig.           (line  313)
* PyConfig.run_command (C 成員函數):     PyConfig.           (line  318)
* PyConfig.run_filename (C 成員函數):    PyConfig.           (line  323)
* PyConfig.run_module (C 成員函數):      PyConfig.           (line  327)
* PyConfig.show_ref_count (C 成員函數):  PyConfig.           (line  332)
* PyConfig.site_import (C 成員函數):     PyConfig.           (line  341)
* PyConfig.skip_source_first_line (C 成員函數): PyConfig.    (line  345)
* PyConfig.stdio_encoding (C 成員函數):  PyConfig.           (line  349)
* PyConfig.stdio_errors (C 成員函數):    PyConfig.           (line  351)
* PyConfig.tracemalloc (C 成員函數):     PyConfig.           (line  356)
* PyConfig.user_site_directory (C 成員函數): PyConfig.       (line  364)
* PyConfig.use_environment (C 成員函數): PyConfig.           (line  360)
* PyConfig.use_hash_seed (C 成員函數):   PyConfig.           (line  192)
* PyConfig.verbose (C 成員函數):         PyConfig.           (line  368)
* PyConfig.warnoptions (C 成員函數):     PyConfig.           (line  372)
* PyConfig.write_bytecode (C 成員函數):  PyConfig.           (line  383)
* PyConfig.xoptions (C 成員函數):        PyConfig.           (line  390)
* PyConfig._use_peg_parser (C 成員函數): PyConfig.           (line  394)
* PyConfig_Clear (C 函式):               PyConfig.           (line   69)
* PyConfig_InitIsolatedConfig (C 函式):  PyConfig.           (line   17)
* PyConfig_InitPythonConfig (C 函式):    PyConfig.           (line   12)
* PyConfig_Read (C 函式):                PyConfig.           (line   61)
* PyConfig_SetArgv (C 函式):             PyConfig.           (line   37)
* PyConfig_SetBytesArgv (C 函式):        PyConfig.           (line   44)
* PyConfig_SetBytesString (C 函式):      PyConfig.           (line   29)
* PyConfig_SetString (C 函式):           PyConfig.           (line   22)
* PyConfig_SetWideStringList (C 函式):   PyConfig.           (line   52)
* PyContext (C 型態):                    上下文变量对象.     (line   23)
* PyContextToken (C 型態):               上下文变量对象.     (line   31)
* PyContextToken_CheckExact (C 函式):    上下文变量对象.     (line   59)
* PyContextToken_Type (C 變數):          上下文变量对象.     (line   43)
* PyContextVar (C 型態):                 上下文变量对象.     (line   27)
* PyContextVar_CheckExact (C 函式):      上下文变量对象.     (line   54)
* PyContextVar_Get (C 函式):             上下文变量对象.     (line   95)
* PyContextVar_New (C 函式):             上下文变量对象.     (line   90)
* PyContextVar_Reset (C 函式):           上下文变量对象.     (line  116)
* PyContextVar_Set (C 函式):             上下文变量对象.     (line  112)
* PyContextVar_Type (C 變數):            上下文变量对象.     (line   39)
* PyContext_CheckExact (C 函式):         上下文变量对象.     (line   49)
* PyContext_Copy (C 函式):               上下文变量对象.     (line   70)
* PyContext_CopyCurrent (C 函式):        上下文变量对象.     (line   74)
* PyContext_Enter (C 函式):              上下文变量对象.     (line   78)
* PyContext_Exit (C 函式):               上下文变量对象.     (line   83)
* PyContext_New (C 函式):                上下文变量对象.     (line   66)
* PyContext_Type (C 變數):               上下文变量对象.     (line   35)
* PyCoroObject (C 型態):                 协程对象<2>.        (line   10)
* PyCoro_CheckExact (C 函式):            协程对象<2>.        (line   18)
* PyCoro_New (C 函式):                   协程对象<2>.        (line   23)
* PyCoro_Type (C 變數):                  协程对象<2>.        (line   14)
* PyDateTime_Check (C 函式):             DateTime 物件.      (line   33)
* PyDateTime_CheckExact (C 函式):        DateTime 物件.      (line   39)
* PyDateTime_DATE_GET_HOUR (C 函式):     DateTime 物件.      (line  151)
* PyDateTime_DATE_GET_MICROSECOND (C 函式): DateTime 物件.   (line  163)
* PyDateTime_DATE_GET_MINUTE (C 函式):   DateTime 物件.      (line  155)
* PyDateTime_DATE_GET_SECOND (C 函式):   DateTime 物件.      (line  159)
* PyDateTime_DELTA_GET_DAYS (C 函式):    DateTime 物件.      (line  189)
* PyDateTime_DELTA_GET_MICROSECONDS (C 函式): DateTime 物件. (line  201)
* PyDateTime_DELTA_GET_SECONDS (C 函式): DateTime 物件.      (line  195)
* PyDateTime_FromDateAndTime (C 函式):   DateTime 物件.      (line   81)
* PyDateTime_FromDateAndTimeAndFold (C 函式): DateTime 物件. (line   88)
* PyDateTime_FromTimestamp (C 函式):     DateTime 物件.      (line  209)
* PyDateTime_GET_DAY (C 函式):           DateTime 物件.      (line  143)
* PyDateTime_GET_MONTH (C 函式):         DateTime 物件.      (line  139)
* PyDateTime_GET_YEAR (C 函式):          DateTime 物件.      (line  135)
* PyDateTime_TimeZone_UTC (C 變數):      DateTime 物件.      (line   14)
* PyDateTime_TIME_GET_HOUR (C 函式):     DateTime 物件.      (line  170)
* PyDateTime_TIME_GET_MICROSECOND (C 函式): DateTime 物件.   (line  182)
* PyDateTime_TIME_GET_MINUTE (C 函式):   DateTime 物件.      (line  174)
* PyDateTime_TIME_GET_SECOND (C 函式):   DateTime 物件.      (line  178)
* PyDate_Check (C 函式):                 DateTime 物件.      (line   23)
* PyDate_CheckExact (C 函式):            DateTime 物件.      (line   28)
* PyDate_FromDate (C 函式):              DateTime 物件.      (line   77)
* PyDate_FromTimestamp (C 函式):         DateTime 物件.      (line  214)
* PyDelta_Check (C 函式):                DateTime 物件.      (line   54)
* PyDelta_CheckExact (C 函式):           DateTime 物件.      (line   59)
* PyDelta_FromDSU (C 函式):              DateTime 物件.      (line  109)
* PyDescr_IsData (C 函式):               修飾器物件.         (line   37)
* PyDescr_NewClassMethod (C 函式):       修飾器物件.         (line   32)
* PyDescr_NewGetSet (C 函式):            修飾器物件.         (line   12)
* PyDescr_NewMember (C 函式):            修飾器物件.         (line   17)
* PyDescr_NewMethod (C 函式):            修飾器物件.         (line   22)
* PyDescr_NewWrapper (C 函式):           修飾器物件.         (line   27)
* PyDictObject (C 型態):                 字典物件.           (line    6)
* PyDictProxy_New (C 函式):              字典物件.           (line   29)
* PyDict_Check (C 函式):                 字典物件.           (line   15)
* PyDict_CheckExact (C 函式):            字典物件.           (line   20)
* PyDict_Clear (C 函式):                 字典物件.           (line   34)
* PyDict_Contains (C 函式):              字典物件.           (line   38)
* PyDict_Copy (C 函式):                  字典物件.           (line   44)
* PyDict_DelItem (C 函式):               字典物件.           (line   62)
* PyDict_DelItemString (C 函式):         字典物件.           (line   68)
* PyDict_GetItem (C 函式):               字典物件.           (line   74)
* PyDict_GetItemString (C 函式):         字典物件.           (line   88)
* PyDict_GetItemWithError (C 函式):      字典物件.           (line   82)
* PyDict_Items (C 函式):                 字典物件.           (line  109)
* PyDict_Keys (C 函式):                  字典物件.           (line  113)
* PyDict_Merge (C 函式):                 字典物件.           (line  167)
* PyDict_MergeFromSeq2 (C 函式):         字典物件.           (line  183)
* PyDict_New (C 函式):                   字典物件.           (line   25)
* PyDict_Next (C 函式):                  字典物件.           (line  125)
* PyDict_SetDefault (C 函式):            字典物件.           (line   98)
* PyDict_SetItem (C 函式):               字典物件.           (line   47)
* PyDict_SetItemString (C 函式):         字典物件.           (line   54)
* PyDict_Size (C 函式):                  字典物件.           (line  121)
* PyDict_Type (C 變數):                  字典物件.           (line   10)
* PyDict_Update (C 函式):                字典物件.           (line  176)
* PyDict_Values (C 函式):                字典物件.           (line  117)
* PyDLL (ctypes 中的類別):               加载动态链接库.     (line   52)
* pydoc (模組):                          pydoc --- 文档生成器和在线帮助系统.
                                                             (line    6)
* PyDoc_STR (C 巨集):                    有用的宏.           (line  106)
* PyDoc_STRVAR (C 巨集):                 有用的宏.           (line   88)
* PyErr_BadArgument (C 函式):            抛出异常.           (line   41)
* PyErr_BadInternalCall (C 函式):        抛出异常.           (line  175)
* PyErr_CheckSignals (C 函式):           信号处理<2>.        (line    6)
* PyErr_Clear (C 函式):                  打印和清理.         (line    6)
* PyErr_Clear():                         异常<17>.           (line   23)
* PyErr_Clear() <1>:                     异常<17>.           (line  121)
* PyErr_ExceptionMatches (C 函式):       查询错误指示器.     (line   22)
* PyErr_ExceptionMatches():              异常<17>.           (line  121)
* PyErr_Fetch (C 函式):                  查询错误指示器.     (line   37)
* PyErr_Fetch():                         终结和内存释放.     (line   31)
* PyErr_Format (C 函式):                 抛出异常.           (line   22)
* PyErr_FormatV (C 函式):                抛出异常.           (line   30)
* PyErr_GetExcInfo (C 函式):             查询错误指示器.     (line   98)
* PyErr_GivenExceptionMatches (C 函式):  查询错误指示器.     (line   28)
* PyErr_NewException (C 函式):           Exception 类<2>.    (line    6)
* PyErr_NewExceptionWithDoc (C 函式):    Exception 类<2>.    (line   23)
* PyErr_NoMemory (C 函式):               抛出异常.           (line   46)
* PyErr_NormalizeException (C 函式):     查询错误指示器.     (line   79)
* PyErr_Occurred (C 函式):               查询错误指示器.     (line    6)
* PyErr_Occurred():                      异常<17>.           (line   10)
* PyErr_Print (C 函式):                  打印和清理.         (line   22)
* PyErr_PrintEx (C 函式):                打印和清理.         (line   10)
* PyErr_ResourceWarning (C 函式):        发出警告.           (line   70)
* PyErr_Restore (C 函式):                查询错误指示器.     (line   60)
* PyErr_Restore():                       终结和内存释放.     (line   31)
* PyErr_SetExcFromWindowsErr (C 函式):   抛出异常.           (line   98)
* PyErr_SetExcFromWindowsErrWithFilename (C 函式): 抛出异常. (line  135)
* PyErr_SetExcFromWindowsErrWithFilenameObject (C 函式): 抛出异常.
                                                             (line  114)
* PyErr_SetExcFromWindowsErrWithFilenameObjects (C 函式): 抛出异常.
                                                             (line  123)
* PyErr_SetExcInfo (C 函式):             查询错误指示器.     (line  116)
* PyErr_SetFromErrno (C 函式):           抛出异常.           (line   51)
* PyErr_SetFromErrnoWithFilename (C 函式): 抛出异常.         (line   79)
* PyErr_SetFromErrnoWithFilenameObject (C 函式): 抛出异常.   (line   63)
* PyErr_SetFromErrnoWithFilenameObjects (C 函式): 抛出异常.  (line   70)
* PyErr_SetFromWindowsErr (C 函式):      抛出异常.           (line   86)
* PyErr_SetFromWindowsErrWithFilename (C 函式): 抛出异常.    (line  105)
* PyErr_SetImportError (C 函式):         抛出异常.           (line  143)
* PyErr_SetImportErrorSubclass (C 函式): 发出警告.           (line   33)
* PyErr_SetInterrupt (C 函式):           信号处理<2>.        (line   18)
* PyErr_SetNone (C 函式):                抛出异常.           (line   37)
* PyErr_SetObject (C 函式):              抛出异常.           (line   17)
* PyErr_SetString (C 函式):              抛出异常.           (line    9)
* PyErr_SetString():                     异常<17>.           (line   23)
* PyErr_SyntaxLocation (C 函式):         抛出异常.           (line  170)
* PyErr_SyntaxLocationEx (C 函式):       抛出异常.           (line  161)
* PyErr_SyntaxLocationObject (C 函式):   抛出异常.           (line  152)
* PyErr_WarnEx (C 函式):                 发出警告.           (line   15)
* PyErr_WarnExplicit (C 函式):           发出警告.           (line   53)
* PyErr_WarnExplicitObject (C 函式):     发出警告.           (line   41)
* PyErr_WarnFormat (C 函式):             发出警告.           (line   61)
* PyErr_WriteUnraisable (C 函式):        打印和清理.         (line   26)
* PyEval_AcquireLock (C 函式):           Low-level API.      (line  221)
* PyEval_AcquireThread (C 函式):         Low-level API.      (line  188)
* PyEval_AcquireThread():                高阶 API.           (line   29)
* PyEval_EvalCode (C 函式):              The Very High Level Layer.
                                                             (line  337)
* PyEval_EvalCodeEx (C 函式):            The Very High Level Layer.
                                                             (line  344)
* PyEval_EvalFrame (C 函式):             The Very High Level Layer.
                                                             (line  363)
* PyEval_EvalFrameEx (C 函式):           The Very High Level Layer.
                                                             (line  368)
* PyEval_GetBuiltins (C 函式):           反射.               (line    6)
* PyEval_GetFrame (C 函式):              反射.               (line   18)
* PyEval_GetFuncDesc (C 函式):           反射.               (line   55)
* PyEval_GetFuncName (C 函式):           反射.               (line   50)
* PyEval_GetGlobals (C 函式):            反射.               (line   14)
* PyEval_GetLocals (C 函式):             反射.               (line   10)
* PyEval_InitThreads (C 函式):           高阶 API.           (line   27)
* PyEval_InitThreads():                  Initializing and finalizing the interpreter.
                                                             (line    8)
* PyEval_MergeCompilerFlags (C 函式):    The Very High Level Layer.
                                                             (line  381)
* PyEval_ReleaseLock (C 函式):           Low-level API.      (line  243)
* PyEval_ReleaseThread (C 函式):         Low-level API.      (line  210)
* PyEval_ReleaseThread():                高阶 API.           (line   29)
* PyEval_RestoreThread (C 函式):         高阶 API.           (line   63)
* PyEval_RestoreThread():                Releasing the GIL from extension code.
                                                             (line   33)
* PyEval_RestoreThread() <1>:            高阶 API.           (line   29)
* PyEval_SaveThread (C 函式):            高阶 API.           (line   56)
* PyEval_SaveThread():                   Releasing the GIL from extension code.
                                                             (line   33)
* PyEval_SaveThread() <1>:               高阶 API.           (line   29)
* PyEval_SetProfile (C 函式):            分析和跟踪.         (line  116)
* PyEval_SetTrace (C 函式):              分析和跟踪.         (line  128)
* PyEval_ThreadsInitialized (C 函式):    高阶 API.           (line   44)
* PyException_GetCause (C 函式):         异常对象.           (line   29)
* PyException_GetContext (C 函式):       异常对象.           (line   16)
* PyException_GetTraceback (C 函式):     异常对象.           (line    6)
* PyException_SetCause (C 函式):         异常对象.           (line   35)
* PyException_SetContext (C 函式):       异常对象.           (line   23)
* PyException_SetTraceback (C 函式):     异常对象.           (line   12)
* PyExc_ArithmeticError:                 标准异常.           (line   11)
* PyExc_AssertionError:                  标准异常.           (line   11)
* PyExc_AttributeError:                  标准异常.           (line   11)
* PyExc_BaseException:                   标准异常.           (line   11)
* PyExc_BlockingIOError:                 标准异常.           (line   11)
* PyExc_BrokenPipeError:                 标准异常.           (line   11)
* PyExc_BufferError:                     标准异常.           (line   11)
* PyExc_BytesWarning:                    标准警告类别.       (line   11)
* PyExc_ChildProcessError:               标准异常.           (line   11)
* PyExc_ConnectionAbortedError:          标准异常.           (line   11)
* PyExc_ConnectionError:                 标准异常.           (line   11)
* PyExc_ConnectionRefusedError:          标准异常.           (line   11)
* PyExc_ConnectionResetError:            标准异常.           (line   11)
* PyExc_DeprecationWarning:              标准警告类别.       (line   11)
* PyExc_EnvironmentError:                标准异常.           (line  189)
* PyExc_EOFError:                        标准异常.           (line   11)
* PyExc_Exception:                       标准异常.           (line   11)
* PyExc_FileExistsError:                 标准异常.           (line   11)
* PyExc_FileNotFoundError:               标准异常.           (line   11)
* PyExc_FloatingPointError:              标准异常.           (line   11)
* PyExc_FutureWarning:                   标准警告类别.       (line   11)
* PyExc_GeneratorExit:                   标准异常.           (line   11)
* PyExc_ImportError:                     标准异常.           (line   11)
* PyExc_ImportWarning:                   标准警告类别.       (line   11)
* PyExc_IndentationError:                标准异常.           (line   11)
* PyExc_IndexError:                      标准异常.           (line   11)
* PyExc_InterruptedError:                标准异常.           (line   11)
* PyExc_IOError:                         标准异常.           (line  189)
* PyExc_IsADirectoryError:               标准异常.           (line   11)
* PyExc_KeyboardInterrupt:               标准异常.           (line   11)
* PyExc_KeyError:                        标准异常.           (line   11)
* PyExc_LookupError:                     标准异常.           (line   11)
* PyExc_MemoryError:                     标准异常.           (line   11)
* PyExc_ModuleNotFoundError:             标准异常.           (line   11)
* PyExc_NameError:                       标准异常.           (line   11)
* PyExc_NotADirectoryError:              标准异常.           (line   11)
* PyExc_NotImplementedError:             标准异常.           (line   11)
* PyExc_OSError:                         标准异常.           (line   11)
* PyExc_OverflowError:                   标准异常.           (line   11)
* PyExc_PendingDeprecationWarning:       标准警告类别.       (line   11)
* PyExc_PermissionError:                 标准异常.           (line   11)
* PyExc_ProcessLookupError:              标准异常.           (line   11)
* PyExc_RecursionError:                  标准异常.           (line   11)
* PyExc_ReferenceError:                  标准异常.           (line   11)
* PyExc_ResourceWarning:                 标准警告类别.       (line   11)
* PyExc_RuntimeError:                    标准异常.           (line   11)
* PyExc_RuntimeWarning:                  标准警告类别.       (line   11)
* PyExc_StopAsyncIteration:              标准异常.           (line   11)
* PyExc_StopIteration:                   标准异常.           (line   11)
* PyExc_SyntaxError:                     标准异常.           (line   11)
* PyExc_SyntaxWarning:                   标准警告类别.       (line   11)
* PyExc_SystemError:                     标准异常.           (line   11)
* PyExc_SystemExit:                      标准异常.           (line   11)
* PyExc_TabError:                        标准异常.           (line   11)
* PyExc_TimeoutError:                    标准异常.           (line   11)
* PyExc_TypeError:                       标准异常.           (line   11)
* PyExc_UnboundLocalError:               标准异常.           (line   11)
* PyExc_UnicodeDecodeError:              标准异常.           (line   11)
* PyExc_UnicodeEncodeError:              标准异常.           (line   11)
* PyExc_UnicodeError:                    标准异常.           (line   11)
* PyExc_UnicodeTranslateError:           标准异常.           (line   11)
* PyExc_UnicodeWarning:                  标准警告类别.       (line   11)
* PyExc_UserWarning:                     标准警告类别.       (line   11)
* PyExc_ValueError:                      标准异常.           (line   11)
* PyExc_Warning:                         标准警告类别.       (line   11)
* PyExc_WindowsError:                    标准异常.           (line  189)
* PyExc_ZeroDivisionError:               标准异常.           (line   11)
* PyFile_FromFd (C 函式):                檔案（File）物件.   (line   12)
* PyFile_GetLine (C 函式):               檔案（File）物件.   (line   35)
* PyFile_SetOpenCodeHook (C 函式):       檔案（File）物件.   (line   46)
* PyFile_WriteObject (C 函式):           檔案（File）物件.   (line   71)
* PyFile_WriteString (C 函式):           檔案（File）物件.   (line   79)
* PyFloatObject (C 型態):                浮點數（Floating Point）物件.
                                                             (line    6)
* PyFloat_AsDouble (C 函式):             浮點數（Floating Point）物件.
                                                             (line   33)
* PyFloat_AS_DOUBLE (C 函式):            浮點數（Floating Point）物件.
                                                             (line   43)
* PyFloat_Check (C 函式):                浮點數（Floating Point）物件.
                                                             (line   15)
* PyFloat_CheckExact (C 函式):           浮點數（Floating Point）物件.
                                                             (line   20)
* PyFloat_FromDouble (C 函式):           浮點數（Floating Point）物件.
                                                             (line   29)
* PyFloat_FromString (C 函式):           浮點數（Floating Point）物件.
                                                             (line   25)
* PyFloat_GetInfo (C 函式):              浮點數（Floating Point）物件.
                                                             (line   47)
* PyFloat_GetMax (C 函式):               浮點數（Floating Point）物件.
                                                             (line   52)
* PyFloat_GetMin (C 函式):               浮點數（Floating Point）物件.
                                                             (line   56)
* PyFloat_Type (C 變數):                 浮點數（Floating Point）物件.
                                                             (line   10)
* PyFrameObject (C 型態):                The Very High Level Layer.
                                                             (line  358)
* PyFrame_GetBack (C 函式):              反射.               (line   24)
* PyFrame_GetCode (C 函式):              反射.               (line   34)
* PyFrame_GetLineNumber (C 函式):        反射.               (line   44)
* PyFrozenSet_Check (C 函式):            集合对象.           (line   44)
* PyFrozenSet_CheckExact (C 函式):       集合对象.           (line   59)
* PyFrozenSet_New (C 函式):              集合对象.           (line   71)
* PyFrozenSet_Type (C 變數):             集合对象.           (line   31)
* PyFunctionObject (C 型態):             函式（Function）物件.
                                                             (line    8)
* PyFunction_Check (C 函式):             函式（Function）物件.
                                                             (line   17)
* PyFunction_GetAnnotations (C 函式):    函式（Function）物件.
                                                             (line   76)
* PyFunction_GetClosure (C 函式):        函式（Function）物件.
                                                             (line   65)
* PyFunction_GetCode (C 函式):           函式（Function）物件.
                                                             (line   40)
* PyFunction_GetDefaults (C 函式):       函式（Function）物件.
                                                             (line   53)
* PyFunction_GetGlobals (C 函式):        函式（Function）物件.
                                                             (line   44)
* PyFunction_GetModule (C 函式):         函式（Function）物件.
                                                             (line   48)
* PyFunction_New (C 函式):               函式（Function）物件.
                                                             (line   22)
* PyFunction_NewWithQualName (C 函式):   函式（Function）物件.
                                                             (line   30)
* PyFunction_SetAnnotations (C 函式):    函式（Function）物件.
                                                             (line   80)
* PyFunction_SetClosure (C 函式):        函式（Function）物件.
                                                             (line   69)
* PyFunction_SetDefaults (C 函式):       函式（Function）物件.
                                                             (line   57)
* PyFunction_Type (C 變數):              函式（Function）物件.
                                                             (line   12)
* PYFUNCTYPE() (於 ctypes 模組中):       函数原型.           (line   28)
* PyGenObject (C 型態):                  產生器物件.         (line   10)
* PyGen_Check (C 函式):                  產生器物件.         (line   18)
* PyGen_CheckExact (C 函式):             產生器物件.         (line   23)
* PyGen_New (C 函式):                    產生器物件.         (line   28)
* PyGen_NewWithQualName (C 函式):        產生器物件.         (line   33)
* PyGen_Type (C 變數):                   產生器物件.         (line   14)
* PyGetSetDef (C 型態):                  Accessing attributes of extension types.
                                                             (line  136)
* PyGILState_Check (C 函式):             高阶 API.           (line  142)
* PyGILState_Ensure (C 函式):            高阶 API.           (line   92)
* PyGILState_GetThisThreadState (C 函式): 高阶 API.          (line  134)
* PyGILState_Release (C 函式):           高阶 API.           (line  123)
* PyImport_AddModule (C 函式):           匯入模組<2>.        (line  109)
* PyImport_AddModuleObject (C 函式):     匯入模組<2>.        (line   93)
* PyImport_AppendInittab (C 函式):       匯入模組<2>.        (line  264)
* PyImport_ExecCodeModule (C 函式):      匯入模組<2>.        (line  114)
* PyImport_ExecCodeModuleEx (C 函式):    匯入模組<2>.        (line  150)
* PyImport_ExecCodeModuleObject (C 函式): 匯入模組<2>.       (line  160)
* PyImport_ExecCodeModuleWithPathnames (C 函式): 匯入模組<2>.
                                                             (line  171)
* PyImport_ExtendInittab (C 函式):       匯入模組<2>.        (line  290)
* PyImport_FrozenModules (C 變數):       匯入模組<2>.        (line  258)
* PyImport_GetImporter (C 函式):         匯入模組<2>.        (line  216)
* PyImport_GetMagicNumber (C 函式):      匯入模組<2>.        (line  185)
* PyImport_GetMagicTag (C 函式):         匯入模組<2>.        (line  194)
* PyImport_GetModule (C 函式):           匯入模組<2>.        (line  208)
* PyImport_GetModuleDict (C 函式):       匯入模組<2>.        (line  203)
* PyImport_Import (C 函式):              匯入模組<2>.        (line   78)
* PyImport_ImportFrozenModule (C 函式):  匯入模組<2>.        (line  240)
* PyImport_ImportFrozenModuleObject (C 函式): 匯入模組<2>.   (line  227)
* PyImport_ImportModule (C 函式):        匯入模組<2>.        (line    6)
* PyImport_ImportModuleEx (C 函式):      匯入模組<2>.        (line   34)
* PyImport_ImportModuleLevel (C 函式):   匯入模組<2>.        (line   68)
* PyImport_ImportModuleLevelObject (C 函式): 匯入模組<2>.    (line   51)
* PyImport_ImportModuleNoBlock (C 函式): 匯入模組<2>.        (line   25)
* PyImport_ReloadModule (C 函式):        匯入模組<2>.        (line   88)
* PyIndex_Check (C 函式):                数字协议.           (line  219)
* PyInit_modulename (C 函式):            构建C/C++扩展.      (line   14)
* PyInstanceMethod_Check (C 函式):       實體方法物件.       (line   15)
* PyInstanceMethod_Function (C 函式):    實體方法物件.       (line   24)
* PyInstanceMethod_GET_FUNCTION (C 函式): 實體方法物件.      (line   28)
* PyInstanceMethod_New (C 函式):         實體方法物件.       (line   20)
* PyInstanceMethod_Type (C 變數):        實體方法物件.       (line   10)
* PyInterpreterState (C 型態):           高阶 API.           (line    9)
* PyInterpreterState_Clear (C 函式):     Low-level API.      (line   21)
* PyInterpreterState_Delete (C 函式):    Low-level API.      (line   29)
* PyInterpreterState_Get (C 函式):       Low-level API.      (line   97)
* PyInterpreterState_GetDict (C 函式):   Low-level API.      (line  118)
* PyInterpreterState_GetID (C 函式):     Low-level API.      (line  108)
* PyInterpreterState_Head (C 函式):      高级调试器支持.     (line    9)
* PyInterpreterState_Main (C 函式):      高级调试器支持.     (line   14)
* PyInterpreterState_New (C 函式):       Low-level API.      (line   12)
* PyInterpreterState_Next (C 函式):      高级调试器支持.     (line   18)
* PyInterpreterState_ThreadHead (C 函式): 高级调试器支持.    (line   25)
* PyIter_Check (C 函式):                 迭代器协议.         (line    8)
* PyIter_Next (C 函式):                  迭代器协议.         (line   12)
* PyListObject (C 型態):                 List（串列）物件.   (line    6)
* PyList_Append (C 函式):                List（串列）物件.   (line   81)
* PyList_AsTuple (C 函式):               List（串列）物件.   (line  112)
* PyList_Check (C 函式):                 List（串列）物件.   (line   15)
* PyList_CheckExact (C 函式):            List（串列）物件.   (line   20)
* PyList_GetItem (C 函式):               List（串列）物件.   (line   42)
* PyList_GetItem():                      引用计数细节.       (line  117)
* PyList_GetSlice (C 函式):              List（串列）物件.   (line   86)
* PyList_GET_ITEM (C 函式):              List（串列）物件.   (line   48)
* PyList_GET_SIZE (C 函式):              List（串列）物件.   (line   38)
* PyList_Insert (C 函式):                List（串列）物件.   (line   73)
* PyList_New (C 函式):                   List（串列）物件.   (line   25)
* PyList_Reverse (C 函式):               List（串列）物件.   (line  107)
* PyList_SetItem (C 函式):               List（串列）物件.   (line   52)
* PyList_SetItem():                      引用计数细节.       (line   26)
* PyList_SetSlice (C 函式):              List（串列）物件.   (line   93)
* PyList_SET_ITEM (C 函式):              List（串列）物件.   (line   62)
* PyList_Size (C 函式):                  List（串列）物件.   (line   34)
* PyList_Sort (C 函式):                  List（串列）物件.   (line  102)
* PyList_Type (C 變數):                  List（串列）物件.   (line   10)
* PyLongObject (C 型態):                 整數物件.           (line   11)
* PyLong_AsDouble (C 函式):              整數物件.           (line  245)
* PyLong_AsLong (C 函式):                整數物件.           (line   93)
* PyLong_AsLongAndOverflow (C 函式):     整數物件.           (line  109)
* PyLong_AsLongLong (C 函式):            整數物件.           (line  127)
* PyLong_AsLongLongAndOverflow (C 函式): 整數物件.           (line  142)
* PyLong_AsSize_t (C 函式):              整數物件.           (line  184)
* PyLong_AsSsize_t (C 函式):             整數物件.           (line  163)
* PyLong_AsUnsignedLong (C 函式):        整數物件.           (line  173)
* PyLong_AsUnsignedLongLong (C 函式):    整數物件.           (line  195)
* PyLong_AsUnsignedLongLongMask (C 函式): 整數物件.          (line  227)
* PyLong_AsUnsignedLongMask (C 函式):    整數物件.           (line  210)
* PyLong_AsVoidPtr (C 函式):             整數物件.           (line  256)
* PyLong_Check (C 函式):                 整數物件.           (line   20)
* PyLong_CheckExact (C 函式):            整數物件.           (line   25)
* PyLong_FromDouble (C 函式):            整數物件.           (line   58)
* PyLong_FromLong (C 函式):              整數物件.           (line   30)
* PyLong_FromLongLong (C 函式):          整數物件.           (line   50)
* PyLong_FromSize_t (C 函式):            整數物件.           (line   46)
* PyLong_FromSsize_t (C 函式):           整數物件.           (line   42)
* PyLong_FromString (C 函式):            整數物件.           (line   62)
* PyLong_FromUnicode (C 函式):           整數物件.           (line   74)
* PyLong_FromUnicodeObject (C 函式):     整數物件.           (line   83)
* PyLong_FromUnsignedLong (C 函式):      整數物件.           (line   38)
* PyLong_FromUnsignedLongLong (C 函式):  整數物件.           (line   54)
* PyLong_FromVoidPtr (C 函式):           整數物件.           (line   89)
* PyLong_Type (C 變數):                  整數物件.           (line   15)
* PyMappingMethods (C 型態):             Mapping Object Structures.
                                                             (line    6)
* PyMappingMethods.mp_ass_subscript (C 成員函數): Mapping Object Structures.
                                                             (line   25)
* PyMappingMethods.mp_length (C 成員函數): Mapping Object Structures.
                                                             (line   11)
* PyMappingMethods.mp_subscript (C 成員函數): Mapping Object Structures.
                                                             (line   17)
* PyMapping_Check (C 函式):              映射协议.           (line    9)
* PyMapping_DelItem (C 函式):            映射协议.           (line   35)
* PyMapping_DelItemString (C 函式):      映射协议.           (line   41)
* PyMapping_GetItemString (C 函式):      映射协议.           (line   21)
* PyMapping_HasKey (C 函式):             映射协议.           (line   46)
* PyMapping_HasKeyString (C 函式):       映射协议.           (line   54)
* PyMapping_Items (C 函式):              映射协议.           (line   74)
* PyMapping_Keys (C 函式):               映射协议.           (line   62)
* PyMapping_Length (C 函式):             映射协议.           (line   15)
* PyMapping_SetItemString (C 函式):      映射协议.           (line   27)
* PyMapping_Size (C 函式):               映射协议.           (line   15)
* PyMapping_Values (C 函式):             映射协议.           (line   68)
* PyMarshal_ReadLastObjectFromFile (C 函式): 数据 marshal 操作支持.
                                                             (line   58)
* PyMarshal_ReadLongFromFile (C 函式):   数据 marshal 操作支持.
                                                             (line   37)
* PyMarshal_ReadObjectFromFile (C 函式): 数据 marshal 操作支持.
                                                             (line   51)
* PyMarshal_ReadObjectFromString (C 函式): 数据 marshal 操作支持.
                                                             (line   69)
* PyMarshal_ReadShortFromFile (C 函式):  数据 marshal 操作支持.
                                                             (line   44)
* PyMarshal_WriteLongToFile (C 函式):    数据 marshal 操作支持.
                                                             (line   16)
* PyMarshal_WriteObjectToFile (C 函式):  数据 marshal 操作支持.
                                                             (line   23)
* PyMarshal_WriteObjectToString (C 函式): 数据 marshal 操作支持.
                                                             (line   29)
* PyMemAllocatorDomain (C 型態):         自定义内存分配器.   (line   34)
* PyMemAllocatorEx (C 型態):             自定义内存分配器.   (line    8)
* PyMemberDef (C 型態):                  Accessing attributes of extension types.
                                                             (line    6)
* PyMember_GetOne (C 函式):              Accessing attributes of extension types.
                                                             (line  120)
* PyMember_SetOne (C 函式):              Accessing attributes of extension types.
                                                             (line  128)
* PyMemoryView_Check (C 函式):           MemoryView 对象.    (line   34)
* PyMemoryView_FromBuffer (C 函式):      MemoryView 对象.    (line   22)
* PyMemoryView_FromMemory (C 函式):      MemoryView 对象.    (line   14)
* PyMemoryView_FromObject (C 函式):      MemoryView 对象.    (line    9)
* PyMemoryView_GetContiguous (C 函式):   MemoryView 对象.    (line   27)
* PyMemoryView_GET_BASE (C 函式):        MemoryView 对象.    (line   45)
* PyMemoryView_GET_BUFFER (C 函式):      MemoryView 对象.    (line   39)
* PyMem_Calloc (C 函式):                 内存接口.           (line   23)
* PyMem_Del (C 函式):                    内存接口.           (line   75)
* PYMEM_DOMAIN_MEM (C 巨集):             自定义内存分配器.   (line   50)
* PYMEM_DOMAIN_OBJ (C 巨集):             自定义内存分配器.   (line   62)
* PYMEM_DOMAIN_RAW (C 巨集):             自定义内存分配器.   (line   38)
* PyMem_Free (C 函式):                   内存接口.           (line   49)
* PyMem_GetAllocator (C 函式):           自定义内存分配器.   (line   74)
* PyMem_Malloc (C 函式):                 内存接口.           (line   15)
* PyMem_New (C 函式):                    内存接口.           (line   60)
* PyMem_RawCalloc (C 函式):              原始内存接口.       (line   23)
* PyMem_RawFree (C 函式):                原始内存接口.       (line   49)
* PyMem_RawMalloc (C 函式):              原始内存接口.       (line   15)
* PyMem_RawRealloc (C 函式):             原始内存接口.       (line   34)
* PyMem_Realloc (C 函式):                内存接口.           (line   34)
* PyMem_Resize (C 函式):                 内存接口.           (line   66)
* PyMem_SetAllocator (C 函式):           自定义内存分配器.   (line   80)
* PyMem_SetupDebugHooks (C 函式):        自定义内存分配器.   (line   94)
* PyMethodDef (C 型態):                  Implementing functions and methods.
                                                             (line   64)
* PyMethod_Check (C 函式):               方法对象.           (line   14)
* PyMethod_Function (C 函式):            方法对象.           (line   24)
* PyMethod_GET_FUNCTION (C 函式):        方法对象.           (line   28)
* PyMethod_GET_SELF (C 函式):            方法对象.           (line   35)
* PyMethod_New (C 函式):                 方法对象.           (line   19)
* PyMethod_Self (C 函式):                方法对象.           (line   32)
* PyMethod_Type (C 變數):                方法对象.           (line    9)
* PyModuleDef (C 型態):                  Initializing C modules.
                                                             (line   17)
* PyModuleDef.m_base (C 成員函數):       Initializing C modules.
                                                             (line   23)
* PyModuleDef.m_clear (C 成員函數):      Initializing C modules.
                                                             (line   89)
* PyModuleDef.m_doc (C 成員函數):        Initializing C modules.
                                                             (line   31)
* PyModuleDef.m_free (C 成員函數):       Initializing C modules.
                                                             (line  110)
* PyModuleDef.m_methods (C 成員函數):    Initializing C modules.
                                                             (line   57)
* PyModuleDef.m_name (C 成員函數):       Initializing C modules.
                                                             (line   27)
* PyModuleDef.m_reload (C 成員函數):     Initializing C modules.
                                                             (line   72)
* PyModuleDef.m_size (C 成員函數):       Initializing C modules.
                                                             (line   36)
* PyModuleDef.m_slots (C 成員函數):      Initializing C modules.
                                                             (line   63)
* PyModuleDef.m_traverse (C 成員函數):   Initializing C modules.
                                                             (line   74)
* PyModuleDef_Init (C 函式):             Multi-phase initialization.
                                                             (line   33)
* PyModuleDef_Slot (C 型態):             Multi-phase initialization.
                                                             (line   45)
* PyModuleDef_Slot.slot (C 成員函數):    Multi-phase initialization.
                                                             (line   47)
* PyModuleDef_Slot.value (C 成員函數):   Multi-phase initialization.
                                                             (line   51)
* PyModule_AddFunctions (C 函式):        Low-level module creation functions.
                                                             (line   52)
* PyModule_AddIntConstant (C 函式):      Support functions.  (line   35)
* PyModule_AddIntMacro (C 函式):         Support functions.  (line   51)
* PyModule_AddObject (C 函式):           Support functions.  (line   11)
* PyModule_AddStringConstant (C 函式):   Support functions.  (line   42)
* PyModule_AddStringMacro (C 函式):      Support functions.  (line   58)
* PyModule_AddType (C 函式):             Support functions.  (line   62)
* PyModule_Check (C 函式):               模組物件模組.       (line   12)
* PyModule_CheckExact (C 函式):          模組物件模組.       (line   17)
* PyModule_Create (C 函式):              Single-phase initialization.
                                                             (line   10)
* PyModule_Create2 (C 函式):             Single-phase initialization.
                                                             (line   16)
* PyModule_ExecDef (C 函式):             Low-level module creation functions.
                                                             (line   36)
* PyModule_FromDefAndSpec (C 函式):      Low-level module creation functions.
                                                             (line   11)
* PyModule_FromDefAndSpec2 (C 函式):     Low-level module creation functions.
                                                             (line   21)
* PyModule_GetDef (C 函式):              模組物件模組.       (line   74)
* PyModule_GetDict (C 函式):             模組物件模組.       (line   41)
* PyModule_GetFilename (C 函式):         模組物件模組.       (line   91)
* PyModule_GetFilenameObject (C 函式):   模組物件模組.       (line   80)
* PyModule_GetName (C 函式):             模組物件模組.       (line   63)
* PyModule_GetNameObject (C 函式):       模組物件模組.       (line   54)
* PyModule_GetState (C 函式):            模組物件模組.       (line   68)
* PyModule_New (C 函式):                 模組物件模組.       (line   36)
* PyModule_NewObject (C 函式):           模組物件模組.       (line   22)
* PyModule_SetDocString (C 函式):        Low-level module creation functions.
                                                             (line   43)
* PyModule_Type (C 變數):                模組物件模組.       (line    6)
* PyNumberMethods (C 型態):              Number Object Structures.
                                                             (line    6)
* PyNumberMethods.nb_absolute (C 成員函數): Number Object Structures.
                                                             (line   85)
* PyNumberMethods.nb_add (C 成員函數):   Number Object Structures.
                                                             (line   69)
* PyNumberMethods.nb_and (C 成員函數):   Number Object Structures.
                                                             (line   95)
* PyNumberMethods.nb_bool (C 成員函數):  Number Object Structures.
                                                             (line   87)
* PyNumberMethods.nb_divmod (C 成員函數): Number Object Structures.
                                                             (line   77)
* PyNumberMethods.nb_float (C 成員函數): Number Object Structures.
                                                             (line  105)
* PyNumberMethods.nb_floor_divide (C 成員函數): Number Object Structures.
                                                             (line  127)
* PyNumberMethods.nb_index (C 成員函數): Number Object Structures.
                                                             (line  135)
* PyNumberMethods.nb_inplace_add (C 成員函數): Number Object Structures.
                                                             (line  107)
* PyNumberMethods.nb_inplace_and (C 成員函數): Number Object Structures.
                                                             (line  121)
* PyNumberMethods.nb_inplace_floor_divide (C 成員函數): Number Object Structures.
                                                             (line  131)
* PyNumberMethods.nb_inplace_lshift (C 成員函數): Number Object Structures.
                                                             (line  117)
* PyNumberMethods.nb_inplace_matrix_multiply (C 成員函數): Number Object Structures.
                                                             (line  139)
* PyNumberMethods.nb_inplace_multiply (C 成員函數): Number Object Structures.
                                                             (line  111)
* PyNumberMethods.nb_inplace_or (C 成員函數): Number Object Structures.
                                                             (line  125)
* PyNumberMethods.nb_inplace_power (C 成員函數): Number Object Structures.
                                                             (line  115)
* PyNumberMethods.nb_inplace_remainder (C 成員函數): Number Object Structures.
                                                             (line  113)
* PyNumberMethods.nb_inplace_rshift (C 成員函數): Number Object Structures.
                                                             (line  119)
* PyNumberMethods.nb_inplace_subtract (C 成員函數): Number Object Structures.
                                                             (line  109)
* PyNumberMethods.nb_inplace_true_divide (C 成員函數): Number Object Structures.
                                                             (line  133)
* PyNumberMethods.nb_inplace_xor (C 成員函數): Number Object Structures.
                                                             (line  123)
* PyNumberMethods.nb_int (C 成員函數):   Number Object Structures.
                                                             (line  101)
* PyNumberMethods.nb_invert (C 成員函數): Number Object Structures.
                                                             (line   89)
* PyNumberMethods.nb_lshift (C 成員函數): Number Object Structures.
                                                             (line   91)
* PyNumberMethods.nb_matrix_multiply (C 成員函數): Number Object Structures.
                                                             (line  137)
* PyNumberMethods.nb_multiply (C 成員函數): Number Object Structures.
                                                             (line   73)
* PyNumberMethods.nb_negative (C 成員函數): Number Object Structures.
                                                             (line   81)
* PyNumberMethods.nb_or (C 成員函數):    Number Object Structures.
                                                             (line   99)
* PyNumberMethods.nb_positive (C 成員函數): Number Object Structures.
                                                             (line   83)
* PyNumberMethods.nb_power (C 成員函數): Number Object Structures.
                                                             (line   79)
* PyNumberMethods.nb_remainder (C 成員函數): Number Object Structures.
                                                             (line   75)
* PyNumberMethods.nb_reserved (C 成員函數): Number Object Structures.
                                                             (line  103)
* PyNumberMethods.nb_rshift (C 成員函數): Number Object Structures.
                                                             (line   93)
* PyNumberMethods.nb_subtract (C 成員函數): Number Object Structures.
                                                             (line   71)
* PyNumberMethods.nb_true_divide (C 成員函數): Number Object Structures.
                                                             (line  129)
* PyNumberMethods.nb_xor (C 成員函數):   Number Object Structures.
                                                             (line   97)
* PyNumber_Absolute (C 函式):            数字协议.           (line   70)
* PyNumber_Add (C 函式):                 数字协议.           (line   13)
* PyNumber_And (C 函式):                 数字协议.           (line   88)
* PyNumber_AsSsize_t (C 函式):           数字协议.           (line  208)
* PyNumber_Check (C 函式):               数字协议.           (line    6)
* PyNumber_Divmod (C 函式):              数字协议.           (line   46)
* PyNumber_Float (C 函式):               数字协议.           (line  191)
* PyNumber_FloorDivide (C 函式):         数字协议.           (line   32)
* PyNumber_Index (C 函式):               数字协议.           (line  197)
* PyNumber_InPlaceAdd (C 函式):          数字协议.           (line  100)
* PyNumber_InPlaceAnd (C 函式):          数字协议.           (line  170)
* PyNumber_InPlaceFloorDivide (C 函式):  数字协议.           (line  127)
* PyNumber_InPlaceLshift (C 函式):       数字协议.           (line  158)
* PyNumber_InPlaceMatrixMultiply (C 函式): 数字协议.         (line  118)
* PyNumber_InPlaceMultiply (C 函式):     数字协议.           (line  111)
* PyNumber_InPlaceOr (C 函式):           数字协议.           (line  180)
* PyNumber_InPlacePower (C 函式):        数字协议.           (line  148)
* PyNumber_InPlaceRemainder (C 函式):    数字协议.           (line  142)
* PyNumber_InPlaceRshift (C 函式):       数字协议.           (line  164)
* PyNumber_InPlaceSubtract (C 函式):     数字协议.           (line  105)
* PyNumber_InPlaceTrueDivide (C 函式):   数字协议.           (line  134)
* PyNumber_InPlaceXor (C 函式):          数字协议.           (line  175)
* PyNumber_Invert (C 函式):              数字协议.           (line   76)
* PyNumber_Long (C 函式):                数字协议.           (line  185)
* PyNumber_Lshift (C 函式):              数字协议.           (line   80)
* PyNumber_MatrixMultiply (C 函式):      数字协议.           (line   25)
* PyNumber_Multiply (C 函式):            数字协议.           (line   21)
* PyNumber_Negative (C 函式):            数字协议.           (line   62)
* PyNumber_Or (C 函式):                  数字协议.           (line   96)
* PyNumber_Positive (C 函式):            数字协议.           (line   66)
* PyNumber_Power (C 函式):               数字协议.           (line   52)
* PyNumber_Remainder (C 函式):           数字协议.           (line   42)
* PyNumber_Rshift (C 函式):              数字协议.           (line   84)
* PyNumber_Subtract (C 函式):            数字协议.           (line   17)
* PyNumber_ToBase (C 函式):              数字协议.           (line  201)
* PyNumber_TrueDivide (C 函式):          数字协议.           (line   36)
* PyNumber_Xor (C 函式):                 数字协议.           (line   92)
* PyObject (C 型態):                     基本的对象类型和宏. (line   10)
* PyObject.ob_refcnt (C 成員函數):       PyObject Slots.     (line   28)
* PyObject.ob_type (C 成員函數):         PyObject Slots.     (line   38)
* PyObject._ob_next (C 成員函數):        PyObject Slots.     (line   11)
* PyObject._ob_prev (C 成員函數):        PyObject Slots.     (line   11)
* PyObjectArenaAllocator (C 型態):       自定义 pymalloc Arena 分配器.
                                                             (line    8)
* PyObject_AsCharBuffer (C 函式):        旧缓冲协议.         (line   18)
* PyObject_ASCII (C 函式):               对象协议.           (line  148)
* PyObject_AsFileDescriptor (C 函式):    檔案（File）物件.   (line   28)
* PyObject_AsReadBuffer (C 函式):        旧缓冲协议.         (line   26)
* PyObject_AsWriteBuffer (C 函式):       旧缓冲协议.         (line   43)
* PyObject_Bytes (C 函式):               对象协议.           (line  166)
* PyObject_Call (C 函式):                调用对象的 API.     (line   57)
* PyObject_CallFunction (C 函式):        调用对象的 API.     (line  101)
* PyObject_CallFunctionObjArgs (C 函式): 调用对象的 API.     (line  136)
* PyObject_CallMethod (C 函式):          调用对象的 API.     (line  118)
* PyObject_CallMethodNoArgs (C 函式):    调用对象的 API.     (line  156)
* PyObject_CallMethodObjArgs (C 函式):   调用对象的 API.     (line  146)
* PyObject_CallMethodOneArg (C 函式):    调用对象的 API.     (line  169)
* PyObject_CallNoArgs (C 函式):          调用对象的 API.     (line   70)
* PyObject_CallObject (C 函式):          调用对象的 API.     (line   91)
* PyObject_CallObject():                 在C中调用Python函数.
                                                             (line   51)
* PyObject_Calloc (C 函式):              对象分配器.         (line   21)
* PyObject_CallOneArg (C 函式):          调用对象的 API.     (line   79)
* PyObject_CheckBuffer (C 函式):         缓冲区相关函数.     (line    6)
* PyObject_CheckReadBuffer (C 函式):     旧缓冲协议.         (line   34)
* PyObject_Del (C 函式):                 在堆中分配对象.     (line   42)
* PyObject_DelAttr (C 函式):             对象协议.           (line   89)
* PyObject_DelAttrString (C 函式):       对象协议.           (line   94)
* PyObject_DelItem (C 函式):             对象协议.           (line  274)
* PyObject_Dir (C 函式):                 对象协议.           (line  279)
* PyObject_Free (C 函式):                对象分配器.         (line   47)
* PyObject_GC_Del (C 函式):              使对象类型支持循环垃圾回收.
                                                             (line   94)
* PyObject_GC_IsFinalized (C 函式):      使对象类型支持循环垃圾回收.
                                                             (line   85)
* PyObject_GC_IsTracked (C 函式):        使对象类型支持循环垃圾回收.
                                                             (line   76)
* PyObject_GC_New (C 函式):              使对象类型支持循环垃圾回收.
                                                             (line   45)
* PyObject_GC_NewVar (C 函式):           使对象类型支持循环垃圾回收.
                                                             (line   50)
* PyObject_GC_Resize (C 函式):           使对象类型支持循环垃圾回收.
                                                             (line   57)
* PyObject_GC_Track (C 函式):            使对象类型支持循环垃圾回收.
                                                             (line   63)
* PyObject_GC_UnTrack (C 函式):          使对象类型支持循环垃圾回收.
                                                             (line   99)
* PyObject_GenericGetAttr (C 函式):      对象协议.           (line   52)
* PyObject_GenericGetDict (C 函式):      对象协议.           (line  100)
* PyObject_GenericSetAttr (C 函式):      对象协议.           (line   79)
* PyObject_GenericSetDict (C 函式):      对象协议.           (line  107)
* PyObject_GetArenaAllocator (C 函式):   自定义 pymalloc Arena 分配器.
                                                             (line   25)
* PyObject_GetAttr (C 函式):             对象协议.           (line   40)
* PyObject_GetAttrString (C 函式):       对象协议.           (line   46)
* PyObject_GetBuffer (C 函式):           缓冲区相关函数.     (line   12)
* PyObject_GetItem (C 函式):             对象协议.           (line  263)
* PyObject_GetIter (C 函式):             对象协议.           (line  286)
* PyObject_HasAttr (C 函式):             对象协议.           (line   21)
* PyObject_HasAttrString (C 函式):       对象协议.           (line   30)
* PyObject_Hash (C 函式):                对象协议.           (line  209)
* PyObject_HashNotImplemented (C 函式):  对象协议.           (line  217)
* PyObject_HEAD (C 巨集):                基本的对象类型和宏. (line   30)
* PyObject_HEAD_INIT (C 巨集):           基本的对象类型和宏. (line   96)
* PyObject_Init (C 函式):                在堆中分配对象.     (line   14)
* PyObject_InitVar (C 函式):             在堆中分配对象.     (line   20)
* PyObject_IsInstance (C 函式):          对象协议.           (line  191)
* PyObject_IsSubclass (C 函式):          对象协议.           (line  174)
* PyObject_IsTrue (C 函式):              对象协议.           (line  223)
* PyObject_IS_GC (C 函式):               使对象类型支持循环垃圾回收.
                                                             (line   70)
* PyObject_Length (C 函式):              对象协议.           (line  247)
* PyObject_LengthHint (C 函式):          对象协议.           (line  253)
* PyObject_Malloc (C 函式):              对象分配器.         (line   13)
* PyObject_New (C 函式):                 在堆中分配对象.     (line   26)
* PyObject_NewVar (C 函式):              在堆中分配对象.     (line   32)
* PyObject_Not (C 函式):                 对象协议.           (line  228)
* PyObject_Print (C 函式):               对象协议.           (line   15)
* PyObject_Realloc (C 函式):             对象分配器.         (line   32)
* PyObject_Repr (C 函式):                对象协议.           (line  138)
* PyObject_RichCompare (C 函式):         对象协议.           (line  115)
* PyObject_RichCompareBool (C 函式):     对象协议.           (line  124)
* PyObject_SetArenaAllocator (C 函式):   自定义 pymalloc Arena 分配器.
                                                             (line   30)
* PyObject_SetAttr (C 函式):             对象协议.           (line   60)
* PyObject_SetAttrString (C 函式):       对象协议.           (line   70)
* PyObject_SetItem (C 函式):             对象协议.           (line  267)
* PyObject_Size (C 函式):                对象协议.           (line  247)
* PyObject_Str (C 函式):                 对象协议.           (line  157)
* PyObject_Type (C 函式):                对象协议.           (line  233)
* PyObject_TypeCheck (C 函式):           对象协议.           (line  242)
* PyObject_VAR_HEAD (C 巨集):            基本的对象类型和宏. (line   40)
* PyObject_Vectorcall (C 函式):          调用对象的 API.     (line  182)
* PyObject_VectorcallDict (C 函式):      调用对象的 API.     (line  196)
* PyObject_VectorcallMethod (C 函式):    调用对象的 API.     (line  211)
* PyOS_AfterFork (C 函式):               作業系統工具.       (line   75)
* PyOS_AfterFork_Child (C 函式):         作業系統工具.       (line   53)
* PyOS_AfterFork_Parent (C 函式):        作業系統工具.       (line   39)
* PyOS_BeforeFork (C 函式):              作業系統工具.       (line   26)
* PyOS_CheckStack (C 函式):              作業系統工具.       (line   85)
* PyOS_double_to_string (C 函式):        字串轉換與格式化.   (line   73)
* PyOS_FSPath (C 函式):                  作業系統工具.       (line    6)
* PyOS_getsig (C 函式):                  作業系統工具.       (line   93)
* PyOS_InputHook (C 變數):               The Very High Level Layer.
                                                             (line  161)
* PyOS_ReadlineFunctionPointer (C 變數): The Very High Level Layer.
                                                             (line  171)
* PyOS_setsig (C 函式):                  作業系統工具.       (line  100)
* PyOS_snprintf (C 函式):                字串轉換與格式化.   (line    8)
* PyOS_stricmp (C 函式):                 字串轉換與格式化.   (line  105)
* PyOS_string_to_double (C 函式):        字串轉換與格式化.   (line   45)
* PyOS_strnicmp (C 函式):                字串轉換與格式化.   (line  110)
* PyOS_vsnprintf (C 函式):               字串轉換與格式化.   (line   14)
* PyParser_SimpleParseFile (C 函式):     The Very High Level Layer.
                                                             (line  223)
* PyParser_SimpleParseFileFlags (C 函式): The Very High Level Layer.
                                                             (line  233)
* PyParser_SimpleParseString (C 函式):   The Very High Level Layer.
                                                             (line  192)
* PyParser_SimpleParseStringFlags (C 函式): The Very High Level Layer.
                                                             (line  202)
* PyParser_SimpleParseStringFlagsFilename (C 函式): The Very High Level Layer.
                                                             (line  211)
* PyPI; (see Python Package Index (PyPI)): 安裝工具.         (line   22)
* PyPreConfig (C 型態):                  PyPreConfig.        (line    6)
* PyPreConfig.allocator (C 成員函數):    PyPreConfig.        (line   32)
* PyPreConfig.coerce_c_locale (C 成員函數): PyPreConfig.     (line   68)
* PyPreConfig.coerce_c_locale_warn (C 成員函數): PyPreConfig.
                                                             (line   73)
* PyPreConfig.configure_locale (C 成員函數): PyPreConfig.    (line   62)
* PyPreConfig.dev_mode (C 成員函數):     PyPreConfig.        (line   77)
* PyPreConfig.isolated (C 成員函數):     PyPreConfig.        (line   81)
* PyPreConfig.legacy_windows_fs_encoding (C 成員函數): PyPreConfig.
                                                             (line   85)
* PyPreConfig.parse_argv (C 成員函數):   PyPreConfig.        (line   94)
* PyPreConfig.use_environment (C 成員函數): PyPreConfig.     (line  101)
* PyPreConfig.utf8_mode (C 成員函數):    PyPreConfig.        (line  105)
* PyPreConfig_InitIsolatedConfig (C 函式): PyPreConfig.      (line   24)
* PyPreConfig_InitPythonConfig (C 函式): PyPreConfig.        (line   18)
* PyProperty_Type (C 變數):              修飾器物件.         (line    8)
* PyRun_AnyFile (C 函式):                The Very High Level Layer.
                                                             (line   48)
* PyRun_AnyFileEx (C 函式):              The Very High Level Layer.
                                                             (line   61)
* PyRun_AnyFileExFlags (C 函式):         The Very High Level Layer.
                                                             (line   67)
* PyRun_AnyFileFlags (C 函式):           The Very High Level Layer.
                                                             (line   54)
* PyRun_File (C 函式):                   The Very High Level Layer.
                                                             (line  262)
* PyRun_FileEx (C 函式):                 The Very High Level Layer.
                                                             (line  268)
* PyRun_FileExFlags (C 函式):            The Very High Level Layer.
                                                             (line  283)
* PyRun_FileFlags (C 函式):              The Very High Level Layer.
                                                             (line  274)
* PyRun_InteractiveLoop (C 函式):        The Very High Level Layer.
                                                             (line  146)
* PyRun_InteractiveLoopFlags (C 函式):   The Very High Level Layer.
                                                             (line  152)
* PyRun_InteractiveOne (C 函式):         The Very High Level Layer.
                                                             (line  125)
* PyRun_InteractiveOneFlags (C 函式):    The Very High Level Layer.
                                                             (line  131)
* PyRun_SimpleFile (C 函式):             The Very High Level Layer.
                                                             (line  100)
* PyRun_SimpleFileEx (C 函式):           The Very High Level Layer.
                                                             (line  105)
* PyRun_SimpleFileExFlags (C 函式):      The Very High Level Layer.
                                                             (line  111)
* PyRun_SimpleString (C 函式):           The Very High Level Layer.
                                                             (line   79)
* PyRun_SimpleStringFlags (C 函式):      The Very High Level Layer.
                                                             (line   85)
* PyRun_String (C 函式):                 The Very High Level Layer.
                                                             (line  242)
* PyRun_StringFlags (C 函式):            The Very High Level Layer.
                                                             (line  249)
* PySeqIter_Check (C 函式):              迭代器（Iterator）物件.
                                                             (line   15)
* PySeqIter_New (C 函式):                迭代器（Iterator）物件.
                                                             (line   20)
* PySeqIter_Type (C 變數):               迭代器（Iterator）物件.
                                                             (line   10)
* PySequenceMethods (C 型態):            Sequence Object Structures.
                                                             (line    6)
* PySequenceMethods.sq_ass_item (C 成員函數): Sequence Object Structures.
                                                             (line   45)
* PySequenceMethods.sq_concat (C 成員函數): Sequence Object Structures.
                                                             (line   18)
* PySequenceMethods.sq_contains (C 成員函數): Sequence Object Structures.
                                                             (line   54)
* PySequenceMethods.sq_inplace_concat (C 成員函數): Sequence Object Structures.
                                                             (line   61)
* PySequenceMethods.sq_inplace_repeat (C 成員函數): Sequence Object Structures.
                                                             (line   71)
* PySequenceMethods.sq_item (C 成員函數): Sequence Object Structures.
                                                             (line   31)
* PySequenceMethods.sq_length (C 成員函數): Sequence Object Structures.
                                                             (line   11)
* PySequenceMethods.sq_repeat (C 成員函數): Sequence Object Structures.
                                                             (line   24)
* PySequence_Check (C 函式):             序列协议.           (line    6)
* PySequence_Concat (C 函式):            序列协议.           (line   19)
* PySequence_Contains (C 函式):          序列协议.           (line   84)
* PySequence_Count (C 函式):             序列协议.           (line   79)
* PySequence_DelItem (C 函式):           序列协议.           (line   60)
* PySequence_DelSlice (C 函式):          序列协议.           (line   72)
* PySequence_Fast (C 函式):              序列协议.           (line  108)
* PySequence_Fast_GET_ITEM (C 函式):     序列协议.           (line  129)
* PySequence_Fast_GET_SIZE (C 函式):     序列协议.           (line  121)
* PySequence_Fast_ITEMS (C 函式):        序列协议.           (line  135)
* PySequence_GetItem (C 函式):           序列协议.           (line   40)
* PySequence_GetItem():                  引用计数细节.       (line  117)
* PySequence_GetSlice (C 函式):          序列协议.           (line   44)
* PySequence_Index (C 函式):             序列协议.           (line   90)
* PySequence_InPlaceConcat (C 函式):     序列协议.           (line   27)
* PySequence_InPlaceRepeat (C 函式):     序列协议.           (line   33)
* PySequence_ITEM (C 函式):              序列协议.           (line  143)
* PySequence_Length (C 函式):            序列协议.           (line   13)
* PySequence_List (C 函式):              序列协议.           (line   96)
* PySequence_Repeat (C 函式):            序列协议.           (line   23)
* PySequence_SetItem (C 函式):           序列协议.           (line   50)
* PySequence_SetSlice (C 函式):          序列协议.           (line   65)
* PySequence_Size (C 函式):              序列协议.           (line   13)
* PySequence_Tuple (C 函式):             序列协议.           (line  101)
* PySetObject (C 型態):                  集合对象.           (line   17)
* PySet_Add (C 函式):                    集合对象.           (line   98)
* PySet_Check (C 函式):                  集合对象.           (line   39)
* PySet_Clear (C 函式):                  集合对象.           (line  126)
* PySet_Contains (C 函式):               集合对象.           (line   90)
* PySet_Discard (C 函式):                集合对象.           (line  111)
* PySet_GET_SIZE (C 函式):               集合对象.           (line   86)
* PySet_New (C 函式):                    集合对象.           (line   64)
* PySet_Pop (C 函式):                    集合对象.           (line  120)
* PySet_Size (C 函式):                   集合对象.           (line   80)
* PySet_Type (C 變數):                   集合对象.           (line   26)
* PySignal_SetWakeupFd (C 函式):         信号处理<2>.        (line   28)
* PySlice_AdjustIndices (C 函式):        切片物件.           (line   91)
* PySlice_Check (C 函式):                切片物件.           (line   11)
* PySlice_GetIndices (C 函式):           切片物件.           (line   24)
* PySlice_GetIndicesEx (C 函式):         切片物件.           (line   39)
* PySlice_New (C 函式):                  切片物件.           (line   16)
* PySlice_Type (C 變數):                 切片物件.           (line    6)
* PySlice_Unpack (C 函式):               切片物件.           (line   78)
* PyState_AddModule (C 函式):            Module lookup.      (line   23)
* PyState_FindModule (C 函式):           Module lookup.      (line   15)
* PyState_RemoveModule (C 函式):         Module lookup.      (line   46)
* PyStatus (C 型態):                     PyStatus.           (line    6)
* PyStatus.err_msg (C 成員函數):         PyStatus.           (line   20)
* PyStatus.exitcode (C 成員函數):        PyStatus.           (line   16)
* PyStatus.func (C 成員函數):            PyStatus.           (line   24)
* PyStatus_Error (C 函式):               PyStatus.           (line   34)
* PyStatus_Exception (C 函式):           PyStatus.           (line   48)
* PyStatus_Exit (C 函式):                PyStatus.           (line   42)
* PyStatus_IsError (C 函式):             PyStatus.           (line   54)
* PyStatus_IsExit (C 函式):              PyStatus.           (line   58)
* PyStatus_NoMemory (C 函式):            PyStatus.           (line   38)
* PyStatus_Ok (C 函式):                  PyStatus.           (line   30)
* PyStructSequence_Desc (C 型態):        结构序列对象.       (line   32)
* PyStructSequence_Field (C 型態):       结构序列对象.       (line   54)
* PyStructSequence_GetItem (C 函式):     结构序列对象.       (line   83)
* PyStructSequence_GET_ITEM (C 函式):    结构序列对象.       (line   88)
* PyStructSequence_InitType (C 函式):    结构序列对象.       (line   17)
* PyStructSequence_InitType2 (C 函式):   结构序列对象.       (line   23)
* PyStructSequence_New (C 函式):         结构序列对象.       (line   79)
* PyStructSequence_NewType (C 函式):     结构序列对象.       (line   10)
* PyStructSequence_SetItem (C 函式):     结构序列对象.       (line   94)
* PyStructSequence_SET_ITEM (C 函式):    结构序列对象.       (line  103)
* PyStructSequence_UnnamedField (C 變數): 结构序列对象.      (line   73)
* PySys_AddAuditHook (C 函式):           系統函式.           (line  127)
* PySys_AddWarnOption (C 函式):          系統函式.           (line   27)
* PySys_AddWarnOptionUnicode (C 函式):   系統函式.           (line   33)
* PySys_AddXOption (C 函式):             系統函式.           (line   87)
* PySys_Audit (C 函式):                  系統函式.           (line  103)
* PySys_FormatStderr (C 函式):           系統函式.           (line   80)
* PySys_FormatStdout (C 函式):           系統函式.           (line   72)
* PySys_GetObject (C 函式):              系統函式.           (line   11)
* PySys_GetXOptions (C 函式):            系統函式.           (line   96)
* PySys_ResetWarnOptions (C 函式):       系統函式.           (line   22)
* PySys_SetArgv (C 函式):                Process-wide parameters.
                                                             (line  255)
* PySys_SetArgv():                       Initializing and finalizing the interpreter.
                                                             (line    8)
* PySys_SetArgvEx (C 函式):              Process-wide parameters.
                                                             (line  214)
* PySys_SetArgvEx():                     嵌入式Python.       (line   17)
* PySys_SetArgvEx() <1>:                 Initializing and finalizing the interpreter.
                                                             (line    8)
* PySys_SetObject (C 函式):              系統函式.           (line   16)
* PySys_SetPath (C 函式):                系統函式.           (line   43)
* PySys_WriteStderr (C 函式):            系統函式.           (line   67)
* PySys_WriteStdout (C 函式):            系統函式.           (line   49)
* Python 3000:                           術語表.             (line  955)
* Python Editor:                         IDLE<51>.           (line    8)
* Python Enhancement Proposals; PEP 1:   新开发流程.         (line   67)
* Python Enhancement Proposals; PEP 1 <1>: 新开发流程.       (line   82)
* Python Enhancement Proposals; PEP 1 <2>: 術語表.           (line  927)
* Python Enhancement Proposals; PEP 100: Unicode<2>.         (line   15)
* Python Enhancement Proposals; PEP 11:  PEP 538 传统 C 区域强制转换.
                                                             (line   16)
* Python Enhancement Proposals; PEP 11 <1>: 不支持的操作系统.
                                                             (line    6)
* Python Enhancement Proposals; PEP 11 <2>: Library Changes. (line   15)
* Python Enhancement Proposals; PEP 11 <3>: 构建<32>.        (line   14)
* Python Enhancement Proposals; PEP 11 <4>: 在 Windows 上使用 Python.
                                                             (line   15)
* Python Enhancement Proposals; PEP 11 <5>: 其他平台.        (line    7)
* Python Enhancement Proposals; PEP 201: 新开发流程.         (line   86)
* Python Enhancement Proposals; PEP 205: PEP 205 Weak References.
                                                             (line   82)
* Python Enhancement Proposals; PEP 205 <1>: weakref --- 弱引用.
                                                             (line  263)
* Python Enhancement Proposals; PEP 207: PEP 207 Rich Comparisons.
                                                             (line   71)
* Python Enhancement Proposals; PEP 207 <1>: PEP 207 Rich Comparisons.
                                                             (line   77)
* Python Enhancement Proposals; PEP 208: PEP 208 New Coercion Model.
                                                             (line   30)
* Python Enhancement Proposals; PEP 217: PEP 217 Interactive Display Hook.
                                                             (line   27)
* Python Enhancement Proposals; PEP 218: PEP 218 内置集合对象.
                                                             (line   50)
* Python Enhancement Proposals; PEP 218 <1>: 其他语言特性修改<13>.
                                                             (line   12)
* Python Enhancement Proposals; PEP 218 <2>: PEP 218 A Standard Set Datatype.
                                                             (line   80)
* Python Enhancement Proposals; PEP 227: PEP 227 Nested Scopes.
                                                             (line   96)
* Python Enhancement Proposals; PEP 227 <1>: PEP 227 Nested Scopes<2>.
                                                             (line   96)
* Python Enhancement Proposals; PEP 227 <2>: __future__ --- Future 语句定义.
                                                             (line   62)
* Python Enhancement Proposals; PEP 229: PEP 229 New Build System.
                                                             (line   39)
* Python Enhancement Proposals; PEP 230: PEP 230 Warning Framework.
                                                             (line   73)
* Python Enhancement Proposals; PEP 232: PEP 232 Function Attributes.
                                                             (line   36)
* Python Enhancement Proposals; PEP 234: PEP 234 Iterators.  (line  124)
* Python Enhancement Proposals; PEP 235: 簡介<11>.           (line   31)
* Python Enhancement Proposals; PEP 236: PEP 227 Nested Scopes<2>.
                                                             (line   87)
* Python Enhancement Proposals; PEP 236 <1>: PEP 227 Nested Scopes<2>.
                                                             (line   88)
* Python Enhancement Proposals; PEP 236 <2>: PEP 236 __future__ Directives.
                                                             (line   29)
* Python Enhancement Proposals; PEP 236 <3>: future 语句.    (line   71)
* Python Enhancement Proposals; PEP 237: 整数.               (line    6)
* Python Enhancement Proposals; PEP 237 <1>: PEP 237 统一长整数和整数.
                                                             (line   22)
* Python Enhancement Proposals; PEP 237 <2>: 其他语言特性修改<13>.
                                                             (line   18)
* Python Enhancement Proposals; PEP 237 <3>: PEP 237 统一长整数和整数<2>.
                                                             (line   37)
* Python Enhancement Proposals; PEP 237 <4>: printf 风格的字符串格式化.
                                                             (line  155)
* Python Enhancement Proposals; PEP 237 <5>: printf 风格的字节串格式化.
                                                             (line  164)
* Python Enhancement Proposals; PEP 238: 整数.               (line   10)
* Python Enhancement Proposals; PEP 238 <1>: PEP 238 Changing the Division Operator.
                                                             (line   21)
* Python Enhancement Proposals; PEP 238 <2>: PEP 238 Changing the Division Operator.
                                                             (line   27)
* Python Enhancement Proposals; PEP 238 <3>: PEP 238 Changing the Division Operator.
                                                             (line   68)
* Python Enhancement Proposals; PEP 238 <4>: __future__ --- Future 语句定义.
                                                             (line   68)
* Python Enhancement Proposals; PEP 238 <5>: The Very High Level Layer.
                                                             (line  433)
* Python Enhancement Proposals; PEP 238 <6>: 術語表.         (line  404)
* Python Enhancement Proposals; PEP 241: PEP 241 Metadata in Python Packages.
                                                             (line   15)
* Python Enhancement Proposals; PEP 241 <1>: PEP 241 Metadata in Python Packages.
                                                             (line   28)
* Python Enhancement Proposals; PEP 241 <2>: PEP 241 Metadata in Python Packages.
                                                             (line   35)
* Python Enhancement Proposals; PEP 243: PEP 241 Metadata in Python Packages.
                                                             (line   39)
* Python Enhancement Proposals; PEP 247: hmac<2>.            (line   20)
* Python Enhancement Proposals; PEP 249: sqlite3 包.         (line   16)
* Python Enhancement Proposals; PEP 249 <1>: sqlite3 包.     (line  107)
* Python Enhancement Proposals; PEP 249 <2>: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块.
                                                             (line   16)
* Python Enhancement Proposals; PEP 249 <3>: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块.
                                                             (line  127)
* Python Enhancement Proposals; PEP 252: Related Links.      (line   17)
* Python Enhancement Proposals; PEP 252 <1>: Related Links.  (line   17)
* Python Enhancement Proposals; PEP 252 <2>: 实现描述器.     (line   20)
* Python Enhancement Proposals; PEP 253: Old and New Classes.
                                                             (line   28)
* Python Enhancement Proposals; PEP 253 <1>: Multiple Inheritance The Diamond Rule.
                                                             (line    8)
* Python Enhancement Proposals; PEP 253 <2>: Related Links.  (line   17)
* Python Enhancement Proposals; PEP 253 <3>: Related Links.  (line   19)
* Python Enhancement Proposals; PEP 253 <4>: Related Links.  (line   21)
* Python Enhancement Proposals; PEP 255: PEP 255 Simple Generators.
                                                             (line   45)
* Python Enhancement Proposals; PEP 255 <1>: PEP 255 Simple Generators.
                                                             (line  131)
* Python Enhancement Proposals; PEP 255 <2>: PEP 255 Simple Generators<2>.
                                                             (line   43)
* Python Enhancement Proposals; PEP 255 <3>: PEP 255 Simple Generators<2>.
                                                             (line  129)
* Python Enhancement Proposals; PEP 255 <4>: yield 表达式.   (line   72)
* Python Enhancement Proposals; PEP 255 <5>: __future__ --- Future 语句定义.
                                                             (line   65)
* Python Enhancement Proposals; PEP 261: Unicode Changes.    (line   18)
* Python Enhancement Proposals; PEP 261 <1>: Unicode Changes.
                                                             (line   61)
* Python Enhancement Proposals; PEP 263: 其他语言特性修改<12>.
                                                             (line   98)
* Python Enhancement Proposals; PEP 263 <1>: PEP 263 Source Code Encodings.
                                                             (line   29)
* Python Enhancement Proposals; PEP 263 <2>: 核心与内置函数. (line   32)
* Python Enhancement Proposals; PEP 263 <3>: 簡介<11>.       (line   35)
* Python Enhancement Proposals; PEP 263 <4>: 对输入进行解析标记.
                                                             (line   73)
* Python Enhancement Proposals; PEP 263 <5>: Python 源代码中的 Unicode 文字.
                                                             (line   38)
* Python Enhancement Proposals; PEP 264: Other Changes and Fixes<3>.
                                                             (line   55)
* Python Enhancement Proposals; PEP 273: PEP 273 从ZIP压缩包导入模块.
                                                             (line   41)
* Python Enhancement Proposals; PEP 273 <1>: PEP 273 从ZIP压缩包导入模块.
                                                             (line   44)
* Python Enhancement Proposals; PEP 273 <2>: zipimport --- 从 Zip 存档中导入模块.
                                                             (line   36)
* Python Enhancement Proposals; PEP 273 <3>: zipimport --- 从 Zip 存档中导入模块.
                                                             (line   38)
* Python Enhancement Proposals; PEP 274: 新语法.             (line   38)
* Python Enhancement Proposals; PEP 275: 为什么Python中没有switch或case语句？.
                                                             (line    8)
* Python Enhancement Proposals; PEP 277: PEP 277 Unicode file name support for Windows NT.
                                                             (line   32)
* Python Enhancement Proposals; PEP 278: PEP 278 通用换行支持.
                                                             (line   33)
* Python Enhancement Proposals; PEP 278 <1>: 術語表.         (line 1142)
* Python Enhancement Proposals; PEP 279: PEP 279 enumerate.  (line   27)
* Python Enhancement Proposals; PEP 282: PEP 282 logging 包. (line  101)
* Python Enhancement Proposals; PEP 282 <1>: PEP 282 logging 包.
                                                             (line  107)
* Python Enhancement Proposals; PEP 282 <2>: 归档操作.       (line   41)
* Python Enhancement Proposals; PEP 282 <3>: 与警告模块集成. (line   33)
* Python Enhancement Proposals; PEP 282 <4>: distutils log --- Simple PEP 282-style logging.
                                                             (line    6)
* Python Enhancement Proposals; PEP 285: PEP 285 布尔类型.   (line   47)
* Python Enhancement Proposals; PEP 285 <1>: PEP 285 布尔类型.
                                                             (line   70)
* Python Enhancement Proposals; PEP 288: PEP 342 生成器的新特性.
                                                             (line  145)
* Python Enhancement Proposals; PEP 289: PEP 289 生成器表达式.
                                                             (line   56)
* Python Enhancement Proposals; PEP 289 <1>: 其他语言特性修改<13>.
                                                             (line   15)
* Python Enhancement Proposals; PEP 289 <2>: Python 文档.    (line   12)
* Python Enhancement Proposals; PEP 292: PEP 292 Simpler String Substitutions.
                                                             (line   45)
* Python Enhancement Proposals; PEP 292 <1>: 模板字符串.     (line    6)
* Python Enhancement Proposals; PEP 293: PEP 293 Codec Error Handling Callbacks.
                                                             (line   33)
* Python Enhancement Proposals; PEP 3000: Python 3 0.        (line   43)
* Python Enhancement Proposals; PEP 301: PEP 301 Distutils的软件包索引和元数据.
                                                             (line   45)
* Python Enhancement Proposals; PEP 301 <1>: distutils command register --- Register a module with the Python Package Index.
                                                             (line    7)
* Python Enhancement Proposals; PEP 302: Using importlib as the Implementation of Import.
                                                             (line   13)
* Python Enhancement Proposals; PEP 302 <1>: Visible Changes.
                                                             (line   18)
* Python Enhancement Proposals; PEP 302 <2>: Porting Python code.
                                                             (line   71)
* Python Enhancement Proposals; PEP 302 <3>: 新增，改进和弃用的模块<2>.
                                                             (line  106)
* Python Enhancement Proposals; PEP 302 <4>: 新增，改进和删除的模块.
                                                             (line  287)
* Python Enhancement Proposals; PEP 302 <5>: PEP 273 从ZIP压缩包导入模块.
                                                             (line   46)
* Python Enhancement Proposals; PEP 302 <6>: PEP 302 New Import Hooks.
                                                             (line   13)
* Python Enhancement Proposals; PEP 302 <7>: PEP 302 New Import Hooks.
                                                             (line   38)
* Python Enhancement Proposals; PEP 302 <8>: PEP 302 New Import Hooks.
                                                             (line   62)
* Python Enhancement Proposals; PEP 302 <9>: 导入系统.       (line   33)
* Python Enhancement Proposals; PEP 302 <10>: 参考文献.      (line    9)
* Python Enhancement Proposals; PEP 302 <11>: 內建函式.      (line 1537)
* Python Enhancement Proposals; PEP 302 <12>: linecache --- 随机读写文本行.
                                                             (line   26)
* Python Enhancement Proposals; PEP 302 <13>: sys --- 系统相关的参数和函数.
                                                             (line  921)
* Python Enhancement Proposals; PEP 302 <14>: sys --- 系统相关的参数和函数.
                                                             (line  930)
* Python Enhancement Proposals; PEP 302 <15>: zipimport --- 从 Zip 存档中导入模块.
                                                             (line   39)
* Python Enhancement Proposals; PEP 302 <16>: zipimport --- 从 Zip 存档中导入模块.
                                                             (line   42)
* Python Enhancement Proposals; PEP 302 <17>: pkgutil --- 包扩展工具.
                                                             (line   54)
* Python Enhancement Proposals; PEP 302 <18>: pkgutil --- 包扩展工具.
                                                             (line   56)
* Python Enhancement Proposals; PEP 302 <19>: pkgutil --- 包扩展工具.
                                                             (line   57)
* Python Enhancement Proposals; PEP 302 <20>: pkgutil --- 包扩展工具.
                                                             (line   65)
* Python Enhancement Proposals; PEP 302 <21>: pkgutil --- 包扩展工具.
                                                             (line   73)
* Python Enhancement Proposals; PEP 302 <22>: pkgutil --- 包扩展工具.
                                                             (line   86)
* Python Enhancement Proposals; PEP 302 <23>: pkgutil --- 包扩展工具.
                                                             (line  102)
* Python Enhancement Proposals; PEP 302 <24>: pkgutil --- 包扩展工具.
                                                             (line  117)
* Python Enhancement Proposals; PEP 302 <25>: pkgutil --- 包扩展工具.
                                                             (line  137)
* Python Enhancement Proposals; PEP 302 <26>: pkgutil --- 包扩展工具.
                                                             (line  158)
* Python Enhancement Proposals; PEP 302 <27>: pkgutil --- 包扩展工具.
                                                             (line  197)
* Python Enhancement Proposals; PEP 302 <28>: runpy ——查找并执行 Python 模块.
                                                             (line   27)
* Python Enhancement Proposals; PEP 302 <29>: 簡介<11>.      (line   39)
* Python Enhancement Proposals; PEP 302 <30>: importlib abc —— 关于导入的抽象基类.
                                                             (line   37)
* Python Enhancement Proposals; PEP 302 <31>: importlib abc —— 关于导入的抽象基类.
                                                             (line  140)
* Python Enhancement Proposals; PEP 302 <32>: importlib abc —— 关于导入的抽象基类.
                                                             (line  307)
* Python Enhancement Proposals; PEP 302 <33>: importlib abc —— 关于导入的抽象基类.
                                                             (line  326)
* Python Enhancement Proposals; PEP 302 <34>: importlib abc —— 关于导入的抽象基类.
                                                             (line  390)
* Python Enhancement Proposals; PEP 302 <35>: imp —— 由代码内部访问 import 。.
                                                             (line  337)
* Python Enhancement Proposals; PEP 302 <36>: 術語表.        (line  397)
* Python Enhancement Proposals; PEP 302 <37>: 術語表.        (line  691)
* Python Enhancement Proposals; PEP 305: PEP 305 逗号分隔文件.
                                                             (line   42)
* Python Enhancement Proposals; PEP 307: PEP 307 Pickle Enhancements.
                                                             (line    8)
* Python Enhancement Proposals; PEP 307 <1>: PEP 307 Pickle Enhancements.
                                                             (line   30)
* Python Enhancement Proposals; PEP 307 <2>: PEP 307 Pickle Enhancements.
                                                             (line   42)
* Python Enhancement Proposals; PEP 307 <3>: 数据流格式.     (line   25)
* Python Enhancement Proposals; PEP 308: PEP 308 条件表达式. (line   72)
* Python Enhancement Proposals; PEP 308 <1>: PEP 308 条件表达式.
                                                             (line   78)
* Python Enhancement Proposals; PEP 308 <2>: 条件表达式.     (line   14)
* Python Enhancement Proposals; PEP 309: PEP 309 部分功能应用.
                                                             (line   73)
* Python Enhancement Proposals; PEP 3100: Python 3 0.        (line   44)
* Python Enhancement Proposals; PEP 3101: PEP 3101 A New Approach To String Formatting.
                                                             (line    6)
* Python Enhancement Proposals; PEP 3101 <1>: PEP 3101 A New Approach To String Formatting.
                                                             (line    9)
* Python Enhancement Proposals; PEP 3101 <2>: PEP 3101 高级字符串格式.
                                                             (line  159)
* Python Enhancement Proposals; PEP 3101 <3>: 自定义字符串格式化.
                                                             (line    6)
* Python Enhancement Proposals; PEP 3101 <4>: 自定义字符串格式化.
                                                             (line   48)
* Python Enhancement Proposals; PEP 3102: 新语法.            (line   13)
* Python Enhancement Proposals; PEP 3104: 新语法.            (line   24)
* Python Enhancement Proposals; PEP 3104 <1>: nonlocal 语句. (line   23)
* Python Enhancement Proposals; PEP 3105: Print Is A Function.
                                                             (line    8)
* Python Enhancement Proposals; PEP 3105 <1>: PEP 3105 print 改为函数.
                                                             (line   35)
* Python Enhancement Proposals; PEP 3105 <2>: __future__ --- Future 语句定义.
                                                             (line   78)
* Python Enhancement Proposals; PEP 3106: PEP 3106 Dictionary Views.
                                                             (line   58)
* Python Enhancement Proposals; PEP 3107: PEP 563：延迟的标注求值.
                                                             (line    6)
* Python Enhancement Proposals; PEP 3107 <1>: PEP 484 - 类型提示.
                                                             (line    7)
* Python Enhancement Proposals; PEP 3107 <2>: 新语法.        (line    6)
* Python Enhancement Proposals; PEP 3107 <3>: 函式註釋 Function Annotations.
                                                             (line    7)
* Python Enhancement Proposals; PEP 3107 <4>: 函数定义.      (line  102)
* Python Enhancement Proposals; PEP 3108: Library Changes.   (line    7)
* Python Enhancement Proposals; PEP 3108 <1>: Library Changes.
                                                             (line   17)
* Python Enhancement Proposals; PEP 3108 <2>: Library Changes.
                                                             (line   95)
* Python Enhancement Proposals; PEP 3109: 修改的语法.        (line    6)
* Python Enhancement Proposals; PEP 3109 <1>: Changes To Exceptions.
                                                             (line   29)
* Python Enhancement Proposals; PEP 3110: 修改的语法.        (line   16)
* Python Enhancement Proposals; PEP 3110 <1>: Changes To Exceptions.
                                                             (line   35)
* Python Enhancement Proposals; PEP 3110 <2>: PEP 3110 异常处理的变更.
                                                             (line   48)
* Python Enhancement Proposals; PEP 3111: Builtins.          (line   12)
* Python Enhancement Proposals; PEP 3112: PEP 3112 字节字面值.
                                                             (line   75)
* Python Enhancement Proposals; PEP 3112 <1>: __future__ --- Future 语句定义.
                                                             (line   81)
* Python Enhancement Proposals; PEP 3113: 移除的语法.        (line    6)
* Python Enhancement Proposals; PEP 3114: Operators And Special Methods.
                                                             (line   19)
* Python Enhancement Proposals; PEP 3115: types<4>.          (line   10)
* Python Enhancement Proposals; PEP 3115 <1>: 修改的语法.    (line   18)
* Python Enhancement Proposals; PEP 3115 <2>: 准备类命名空间.
                                                             (line   21)
* Python Enhancement Proposals; PEP 3115 <3>: 类定义.        (line   60)
* Python Enhancement Proposals; PEP 3115 <4>: 动态类型创建.  (line   44)
* Python Enhancement Proposals; PEP 3116: 性能优化<8>.       (line    8)
* Python Enhancement Proposals; PEP 3116 <1>: PEP 3116 新 I/O 库.
                                                             (line   69)
* Python Enhancement Proposals; PEP 3116 <2>: 術語表.        (line 1142)
* Python Enhancement Proposals; PEP 3118: 具有外部数据缓冲区的 pickle 协议 5.
                                                             (line   10)
* Python Enhancement Proposals; PEP 3118 <1>: PEP 3118 新的内存视图实现和缓冲协议文档.
                                                             (line    6)
* Python Enhancement Proposals; PEP 3118 <2>: API changes.   (line   29)
* Python Enhancement Proposals; PEP 3118 <3>: 构建和 C API 的改变<4>.
                                                             (line    8)
* Python Enhancement Proposals; PEP 3118 <4>: 构建和 C API 的改变<7>.
                                                             (line   12)
* Python Enhancement Proposals; PEP 3118 <5>: PEP 3118 修改缓冲区协议.
                                                             (line   46)
* Python Enhancement Proposals; PEP 3118 <6>: 库<41>.        (line   99)
* Python Enhancement Proposals; PEP 3118 <7>: 库<46>.        (line   61)
* Python Enhancement Proposals; PEP 3118 <8>: 库<89>.        (line  955)
* Python Enhancement Proposals; PEP 3118 <9>: 内存视图.      (line  100)
* Python Enhancement Proposals; PEP 3119: PEP 3119 抽象基类. (line  139)
* Python Enhancement Proposals; PEP 3119 <1>: 自定义实例及子类检查.
                                                             (line   31)
* Python Enhancement Proposals; PEP 3119 <2>: 容器抽象基类.  (line  301)
* Python Enhancement Proposals; PEP 3119 <3>: abc --- 抽象基类.
                                                             (line   10)
* Python Enhancement Proposals; PEP 3119 <4>: 对象协议.      (line  182)
* Python Enhancement Proposals; PEP 3119 <5>: 对象协议.      (line  200)
* Python Enhancement Proposals; PEP 3120: Text Vs Data Instead Of Unicode Vs 8-bit.
                                                             (line  107)
* Python Enhancement Proposals; PEP 3120 <1>: 词法分析.      (line   10)
* Python Enhancement Proposals; PEP 3120 <2>: 簡介<11>.      (line   71)
* Python Enhancement Proposals; PEP 3121: 构建和 C API 的改变<7>.
                                                             (line   14)
* Python Enhancement Proposals; PEP 3121 <1>: Initializing C modules.
                                                             (line   55)
* Python Enhancement Proposals; PEP 3123: 构建和 C API 的改变<7>.
                                                             (line   16)
* Python Enhancement Proposals; PEP 3127: PEP 3127 整型文字支持和语法.
                                                             (line   47)
* Python Enhancement Proposals; PEP 3129: PEP 3129 类装饰器. (line   24)
* Python Enhancement Proposals; PEP 3129 <1>: 类定义.        (line   65)
* Python Enhancement Proposals; PEP 3131: Text Vs Data Instead Of Unicode Vs 8-bit.
                                                             (line  109)
* Python Enhancement Proposals; PEP 3131 <1>: 标识符和关键字.
                                                             (line    9)
* Python Enhancement Proposals; PEP 3131 <2>: 标识符和关键字.
                                                             (line   15)
* Python Enhancement Proposals; PEP 3132: 新语法.            (line   28)
* Python Enhancement Proposals; PEP 3132 <1>: 赋值语句.      (line  121)
* Python Enhancement Proposals; PEP 3134: 修改的语法.        (line    6)
* Python Enhancement Proposals; PEP 3134 <1>: Changes To Exceptions.
                                                             (line   40)
* Python Enhancement Proposals; PEP 3134 <2>: Changes To Exceptions.
                                                             (line   60)
* Python Enhancement Proposals; PEP 3135: Builtins.          (line    6)
* Python Enhancement Proposals; PEP 3135 <1>: 创建类对象.    (line   43)
* Python Enhancement Proposals; PEP 3137: PEP 3137 The memoryview Object.
                                                             (line   49)
* Python Enhancement Proposals; PEP 3138: Text Vs Data Instead Of Unicode Vs 8-bit.
                                                             (line  103)
* Python Enhancement Proposals; PEP 314: PEP 314 Python软件包的元数据 v1 1.
                                                             (line   42)
* Python Enhancement Proposals; PEP 314 <1>: distutils core --- 分发包功能的核心.
                                                             (line   92)
* Python Enhancement Proposals; PEP 3141: PEP 3141 A Type Hierarchy for Numbers.
                                                             (line   43)
* Python Enhancement Proposals; PEP 3141 <1>: numbers --- 数字的抽象基类.
                                                             (line   10)
* Python Enhancement Proposals; PEP 3141 <2>: abc --- 抽象基类.
                                                             (line   12)
* Python Enhancement Proposals; PEP 3147: PEP 421 添加 sys implementation.
                                                             (line   21)
* Python Enhancement Proposals; PEP 3147 <1>: PEP 3147 PYC 仓库目录.
                                                             (line   69)
* Python Enhancement Proposals; PEP 3147 <2>: 「編譯」Python 檔案.
                                                             (line   35)
* Python Enhancement Proposals; PEP 3147 <3>: 导入相关的模块属性.
                                                             (line   67)
* Python Enhancement Proposals; PEP 3147 <4>: test support --- Utilities for the Python test suite.
                                                             (line  252)
* Python Enhancement Proposals; PEP 3147 <5>: runpy ——查找并执行 Python 模块.
                                                             (line   70)
* Python Enhancement Proposals; PEP 3147 <6>: 簡介<11>.      (line   75)
* Python Enhancement Proposals; PEP 3147 <7>: importlib util —— 导入器的工具程序代码.
                                                             (line   22)
* Python Enhancement Proposals; PEP 3147 <8>: importlib util —— 导入器的工具程序代码.
                                                             (line   51)
* Python Enhancement Proposals; PEP 3147 <9>: importlib util —— 导入器的工具程序代码.
                                                             (line   54)
* Python Enhancement Proposals; PEP 3147 <10>: py_compile --- 编译 Python 源文件.
                                                             (line   25)
* Python Enhancement Proposals; PEP 3147 <11>: py_compile --- 编译 Python 源文件.
                                                             (line   56)
* Python Enhancement Proposals; PEP 3147 <12>: Command-line use.
                                                             (line   63)
* Python Enhancement Proposals; PEP 3147 <13>: Public functions.
                                                             (line   40)
* Python Enhancement Proposals; PEP 3147 <14>: Public functions.
                                                             (line  118)
* Python Enhancement Proposals; PEP 3147 <15>: imp —— 由代码内部访问 import 。.
                                                             (line  190)
* Python Enhancement Proposals; PEP 3147 <16>: imp —— 由代码内部访问 import 。.
                                                             (line  197)
* Python Enhancement Proposals; PEP 3147 <17>: imp —— 由代码内部访问 import 。.
                                                             (line  220)
* Python Enhancement Proposals; PEP 3147 <18>: imp —— 由代码内部访问 import 。.
                                                             (line  224)
* Python Enhancement Proposals; PEP 3147 <19>: imp —— 由代码内部访问 import 。.
                                                             (line  236)
* Python Enhancement Proposals; PEP 3147 <20>: 匯入模組<2>.  (line  196)
* Python Enhancement Proposals; PEP 3147 <21>: 如何创建 pyc 文件？.
                                                             (line   12)
* Python Enhancement Proposals; PEP 3147 <22>: distutils util --- Miscellaneous other utility functions.
                                                             (line  152)
* Python Enhancement Proposals; PEP 3148: PEP 3148 concurrent futures 模块.
                                                             (line   51)
* Python Enhancement Proposals; PEP 3148 <1>: 模块函数.      (line   53)
* Python Enhancement Proposals; PEP 3149: PEP 3149 ABI Version Tagged so Files.
                                                             (line   33)
* Python Enhancement Proposals; PEP 3149 <1>: 核心与内置函数<70>.
                                                             (line    9)
* Python Enhancement Proposals; PEP 3149 <2>: sys --- 系统相关的参数和函数.
                                                             (line   14)
* Python Enhancement Proposals; PEP 3151: PEP 3151 重写 OS 和 IO 异常的层次结构.
                                                             (line   84)
* Python Enhancement Proposals; PEP 3151 <1>: OS 异常.       (line  103)
* Python Enhancement Proposals; PEP 3151 <2>: 异常<11>.      (line   10)
* Python Enhancement Proposals; PEP 3151 <3>: select --- 等待 I/O 完成.
                                                             (line   25)
* Python Enhancement Proposals; PEP 3151 <4>: resource --- 资源使用信息.
                                                             (line   19)
* Python Enhancement Proposals; PEP 3151 <5>: 标准异常.      (line  181)
* Python Enhancement Proposals; PEP 3154: 摘要 - 发布重点<6>.
                                                             (line   57)
* Python Enhancement Proposals; PEP 3154 <1>: pickle<4>.     (line   16)
* Python Enhancement Proposals; PEP 3154 <2>: 库<30>.        (line 1280)
* Python Enhancement Proposals; PEP 3154 <3>: 数据流格式.    (line   34)
* Python Enhancement Proposals; PEP 3155: PEP 3155 类和函数的限定名称.
                                                             (line   62)
* Python Enhancement Proposals; PEP 3155 <1>: 術語表.        (line  981)
* Python Enhancement Proposals; PEP 3156: 摘要 - 发布重点<6>.
                                                             (line   31)
* Python Enhancement Proposals; PEP 3156 <1>: 摘要 - 发布重点<6>.
                                                             (line   44)
* Python Enhancement Proposals; PEP 3156 <2>: asyncio<7>.    (line    6)
* Python Enhancement Proposals; PEP 3156 <3>: asyncio<7>.    (line   17)
* Python Enhancement Proposals; PEP 3156 <4>: selectors<2>.  (line    6)
* Python Enhancement Proposals; PEP 318: PEP 318 Decorators for Functions and Methods.
                                                             (line  101)
* Python Enhancement Proposals; PEP 318 <1>: PEP 318 Decorators for Functions and Methods.
                                                             (line  125)
* Python Enhancement Proposals; PEP 318 <2>: 其他语言特性修改<13>.
                                                             (line    9)
* Python Enhancement Proposals; PEP 318 <3>: 类定义.         (line   67)
* Python Enhancement Proposals; PEP 322: PEP 322 反向迭代.   (line   35)
* Python Enhancement Proposals; PEP 322 <1>: 其他语言特性修改<13>.
                                                             (line   13)
* Python Enhancement Proposals; PEP 324: PEP 324 新的子进程模块.
                                                             (line   86)
* Python Enhancement Proposals; PEP 324 <1>: subprocess --- 子进程管理.
                                                             (line   22)
* Python Enhancement Proposals; PEP 325: PEP 342 生成器的新特性.
                                                             (line  145)
* Python Enhancement Proposals; PEP 327: Context 类型.       (line   56)
* Python Enhancement Proposals; PEP 328: Porting Python code.
                                                             (line   36)
* Python Enhancement Proposals; PEP 328 <1>: 移除的语法.     (line   29)
* Python Enhancement Proposals; PEP 328 <2>: PEP 328 绝对导入和相对导入.
                                                             (line    6)
* Python Enhancement Proposals; PEP 328 <3>: PEP 328 绝对导入和相对导入.
                                                             (line   82)
* Python Enhancement Proposals; PEP 328 <4>: PEP 328 多行导入.
                                                             (line   35)
* Python Enhancement Proposals; PEP 328 <5>: 其他语言特性修改<13>.
                                                             (line   21)
* Python Enhancement Proposals; PEP 328 <6>: 参考文献.       (line   17)
* Python Enhancement Proposals; PEP 328 <7>: 內建函式.       (line 1548)
* Python Enhancement Proposals; PEP 328 <8>: __future__ --- Future 语句定义.
                                                             (line   71)
* Python Enhancement Proposals; PEP 328 <9>: 簡介<11>.       (line   43)
* Python Enhancement Proposals; PEP 331: PEP 331 Locale-Independent Float/String Conversions.
                                                             (line   38)
* Python Enhancement Proposals; PEP 333: wsgiref 包.         (line    8)
* Python Enhancement Proposals; PEP 333 <1>: wsgiref 包.     (line   31)
* Python Enhancement Proposals; PEP 3333: PEP 3333 Python Web服务器网关接口v1 0 1.
                                                             (line   50)
* Python Enhancement Proposals; PEP 3333 <1>: wsgiref --- WSGI 工具和引用的实现.
                                                             (line   19)
* Python Enhancement Proposals; PEP 3333 <2>: wsgiref util -- WSGI 环境工具.
                                                             (line    6)
* Python Enhancement Proposals; PEP 3333 <3>: wsgiref util -- WSGI 环境工具.
                                                             (line    8)
* Python Enhancement Proposals; PEP 3333 <4>: wsgiref util -- WSGI 环境工具.
                                                             (line   23)
* Python Enhancement Proposals; PEP 3333 <5>: wsgiref util -- WSGI 环境工具.
                                                             (line   62)
* Python Enhancement Proposals; PEP 3333 <6>: wsgiref headers -- WSGI 响应标头工具.
                                                             (line   11)
* Python Enhancement Proposals; PEP 3333 <7>: wsgiref simple_server -- 一个简单的 WSGI HTTP 服务器.
                                                             (line   18)
* Python Enhancement Proposals; PEP 3333 <8>: wsgiref simple_server -- 一个简单的 WSGI HTTP 服务器.
                                                             (line   84)
* Python Enhancement Proposals; PEP 3333 <9>: wsgiref validate --- WSGI 一致性检查器.
                                                             (line   11)
* Python Enhancement Proposals; PEP 3333 <10>: wsgiref validate --- WSGI 一致性检查器.
                                                             (line   30)
* Python Enhancement Proposals; PEP 3333 <11>: wsgiref handlers -- 服务器/网关基类.
                                                             (line  193)
* Python Enhancement Proposals; PEP 3333 <12>: wsgiref handlers -- 服务器/网关基类.
                                                             (line  206)
* Python Enhancement Proposals; PEP 3333 <13>: wsgiref handlers -- 服务器/网关基类.
                                                             (line  212)
* Python Enhancement Proposals; PEP 3333 <14>: wsgiref handlers -- 服务器/网关基类.
                                                             (line  220)
* Python Enhancement Proposals; PEP 3333 <15>: wsgiref handlers -- 服务器/网关基类.
                                                             (line  252)
* Python Enhancement Proposals; PEP 338: PEP 338 将模块作为脚本执行.
                                                             (line   21)
* Python Enhancement Proposals; PEP 338 <1>: 接口选项.       (line   83)
* Python Enhancement Proposals; PEP 338 <2>: 参考文献.       (line   20)
* Python Enhancement Proposals; PEP 338 <3>: runpy ——查找并执行 Python 模块.
                                                             (line  141)
* Python Enhancement Proposals; PEP 339: 构建和 C API 的改变<10>.
                                                             (line   45)
* Python Enhancement Proposals; PEP 341: PEP 341 统一 try/except/finally.
                                                             (line   44)
* Python Enhancement Proposals; PEP 342: PEP 342 生成器的新特性.
                                                             (line   42)
* Python Enhancement Proposals; PEP 342 <1>: PEP 342 生成器的新特性.
                                                             (line  140)
* Python Enhancement Proposals; PEP 342 <2>: 移植到Python 2 5.
                                                             (line   15)
* Python Enhancement Proposals; PEP 342 <3>: yield 表达式.   (line   76)
* Python Enhancement Proposals; PEP 342 <4>: 容器抽象基类.   (line  149)
* Python Enhancement Proposals; PEP 342 <5>: 向生成器传递值. (line   20)
* Python Enhancement Proposals; PEP 342 <6>: Python 文档.    (line   14)
* Python Enhancement Proposals; PEP 343: contextlib 模块.    (line   64)
* Python Enhancement Proposals; PEP 343 <1>: PEP 342 生成器的新特性.
                                                             (line  129)
* Python Enhancement Proposals; PEP 343 <2>: contextlib 模块<2>.
                                                             (line   64)
* Python Enhancement Proposals; PEP 343 <3>: with 语句上下文管理器.
                                                             (line   35)
* Python Enhancement Proposals; PEP 343 <4>: with 语句.      (line   87)
* Python Enhancement Proposals; PEP 343 <5>: Using a context manager as a function decorator.
                                                             (line   51)
* Python Enhancement Proposals; PEP 343 <6>: __future__ --- Future 语句定义.
                                                             (line   75)
* Python Enhancement Proposals; PEP 343 <7>: 術語表.         (line  230)
* Python Enhancement Proposals; PEP 347: 构建和 C API 的改变<10>.
                                                             (line   10)
* Python Enhancement Proposals; PEP 352: Changes To Exceptions.
                                                             (line    9)
* Python Enhancement Proposals; PEP 352 <1>: Deprecations and Removals.
                                                             (line    9)
* Python Enhancement Proposals; PEP 352 <2>: PEP 352 异常作为新型的类.
                                                             (line   57)
* Python Enhancement Proposals; PEP 353: PEP 353 使用ssize_t作为索引类型.
                                                             (line   48)
* Python Enhancement Proposals; PEP 353 <1>: PEP 353 使用ssize_t作为索引类型.
                                                             (line   54)
* Python Enhancement Proposals; PEP 353 <2>: 构建和 C API 的改变<10>.
                                                             (line   20)
* Python Enhancement Proposals; PEP 356: Python 2 5 有什么新变化.
                                                             (line   10)
* Python Enhancement Proposals; PEP 357: PEP 357 '__index__' 方法.
                                                             (line   39)
* Python Enhancement Proposals; PEP 361: Python 2 6 有什么新变化.
                                                             (line   10)
* Python Enhancement Proposals; PEP 362: PEP 362 函数签名对象.
                                                             (line   19)
* Python Enhancement Proposals; PEP 362 <1>: Introspecting callables with the Signature object.
                                                             (line  345)
* Python Enhancement Proposals; PEP 362 <2>: 術語表.         (line   84)
* Python Enhancement Proposals; PEP 362 <3>: 術語表.         (line  878)
* Python Enhancement Proposals; PEP 366: Visible Changes.    (line   24)
* Python Enhancement Proposals; PEP 366 <1>: 导入相关的模块属性.
                                                             (line   25)
* Python Enhancement Proposals; PEP 366 <2>: 导入相关的模块属性.
                                                             (line   28)
* Python Enhancement Proposals; PEP 366 <3>: 参考文献.       (line   15)
* Python Enhancement Proposals; PEP 366 <4>: 参考文献.       (line   18)
* Python Enhancement Proposals; PEP 366 <5>: runpy ——查找并执行 Python 模块.
                                                             (line  145)
* Python Enhancement Proposals; PEP 366 <6>: 簡介<11>.       (line   47)
* Python Enhancement Proposals; PEP 370: PEP 370 分用户的 site-packages 目录.
                                                             (line   36)
* Python Enhancement Proposals; PEP 370 <1>: 其他选项.       (line  111)
* Python Enhancement Proposals; PEP 370 <2>: 环境变量.       (line  160)
* Python Enhancement Proposals; PEP 370 <3>: 环境变量.       (line  171)
* Python Enhancement Proposals; PEP 370 <4>: 命令行界面<6>.  (line   34)
* Python Enhancement Proposals; PEP 371: PEP 371 多任务处理包.
                                                             (line  145)
* Python Enhancement Proposals; PEP 372: PEP 372 有序字典.   (line   31)
* Python Enhancement Proposals; PEP 372 <1>: PEP 372 Adding an Ordered Dictionary to collections.
                                                             (line   97)
* Python Enhancement Proposals; PEP 373: Python 2 x的未来.   (line   17)
* Python Enhancement Proposals; PEP 378: PEP 378 千位分隔符的格式说明符.
                                                             (line   32)
* Python Enhancement Proposals; PEP 378 <1>: PEP 378 千位分隔符的格式说明符<2>.
                                                             (line   37)
* Python Enhancement Proposals; PEP 378 <2>: 格式规格迷你语言.
                                                             (line   83)
* Python Enhancement Proposals; PEP 380: PEP 380 委托给子生成器的语法.
                                                             (line   66)
* Python Enhancement Proposals; PEP 380 <1>: yield 表达式.   (line   80)
* Python Enhancement Proposals; PEP 383: 错误处理方案.       (line   50)
* Python Enhancement Proposals; PEP 383 <1>: 套接字协议族.   (line   13)
* Python Enhancement Proposals; PEP 383 <2>: Locale Encoding.
                                                             (line   15)
* Python Enhancement Proposals; PEP 383 <3>: Locale Encoding.
                                                             (line   53)
* Python Enhancement Proposals; PEP 383 <4>: File System Encoding.
                                                             (line    9)
* Python Enhancement Proposals; PEP 384: PEP 384 定义稳定的ABI.
                                                             (line   24)
* Python Enhancement Proposals; PEP 384 <1>: 稳定的应用程序二进制接口.
                                                             (line   28)
* Python Enhancement Proposals; PEP 385: 代码库.             (line   13)
* Python Enhancement Proposals; PEP 387: 警告.               (line   24)
* Python Enhancement Proposals; PEP 387 <1>: 警告.           (line   36)
* Python Enhancement Proposals; PEP 389: PEP 389 Argparse 命令行解析模块.
                                                             (line   92)
* Python Enhancement Proposals; PEP 389 <1>: PEP 389 The argparse Module for Parsing Command Lines.
                                                             (line  100)
* Python Enhancement Proposals; PEP 391: PEP 391 基于字典的日志配置.
                                                             (line   52)
* Python Enhancement Proposals; PEP 391 <1>: PEP 391 Dictionary-Based Configuration For Logging.
                                                             (line   94)
* Python Enhancement Proposals; PEP 392: Python 3 2 有什么新变化.
                                                             (line   16)
* Python Enhancement Proposals; PEP 393: 移植到 Python 3 9<2>.
                                                             (line   39)
* Python Enhancement Proposals; PEP 393 <1>: 移除<2>.        (line   94)
* Python Enhancement Proposals; PEP 393 <2>: PEP 393 灵活的字符串表示.
                                                             (line   16)
* Python Enhancement Proposals; PEP 393 <3>: Functionality.  (line    6)
* Python Enhancement Proposals; PEP 393 <4>: Performance and resource usage.
                                                             (line   29)
* Python Enhancement Proposals; PEP 393 <5>: 性能优化<6>.    (line    8)
* Python Enhancement Proposals; PEP 393 <6>: 构建和 C API 的改变<4>.
                                                             (line   12)
* Python Enhancement Proposals; PEP 393 <7>: 已弃用的 Python 模块、函数和方法<4>.
                                                             (line   10)
* Python Enhancement Proposals; PEP 393 <8>: 已弃用的 C API 函数和类型<3>.
                                                             (line    6)
* Python Enhancement Proposals; PEP 393 <9>: Porting C code. (line   17)
* Python Enhancement Proposals; PEP 393 <10>: 编码格式与 Unicode.
                                                             (line    6)
* Python Enhancement Proposals; PEP 393 <11>: sys --- 系统相关的参数和函数.
                                                             (line  860)
* Python Enhancement Proposals; PEP 393 <12>: Unicode对象.   (line    6)
* Python Enhancement Proposals; PEP 393 <13>: Deprecated Py_UNICODE APIs.
                                                             (line    8)
* Python Enhancement Proposals; PEP 395: 开放问题项.         (line   16)
* Python Enhancement Proposals; PEP 397: PEP 486 Make the Python Launcher aware of virtual environments.
                                                             (line    6)
* Python Enhancement Proposals; PEP 397 <1>: PEP 397 适用于Windows的Python启动器.
                                                             (line   31)
* Python Enhancement Proposals; PEP 397 <2>: 适用于Windows的Python启动器.
                                                             (line   15)
* Python Enhancement Proposals; PEP 397 <3>: 创建虚拟环境.   (line  167)
* Python Enhancement Proposals; PEP 398: Python 3 3 有什么新变化.
                                                             (line   12)
* Python Enhancement Proposals; PEP 4:   Library Changes.    (line   13)
* Python Enhancement Proposals; PEP 405: PEP 405 虚拟环境.   (line   22)
* Python Enhancement Proposals; PEP 405 <1>: venv --- 创建虚拟环境.
                                                             (line   17)
* Python Enhancement Proposals; PEP 409: PEP 409 清除异常上下文.
                                                             (line   63)
* Python Enhancement Proposals; PEP 411: sys --- 系统相关的参数和函数.
                                                             (line  686)
* Python Enhancement Proposals; PEP 411 <1>: sys --- 系统相关的参数和函数.
                                                             (line  695)
* Python Enhancement Proposals; PEP 411 <2>: sys --- 系统相关的参数和函数.
                                                             (line 1210)
* Python Enhancement Proposals; PEP 411 <3>: sys --- 系统相关的参数和函数.
                                                             (line 1226)
* Python Enhancement Proposals; PEP 411 <4>: 術語表.         (line  951)
* Python Enhancement Proposals; PEP 412: PEP 412 Key-Sharing Dictionary.
                                                             (line   15)
* Python Enhancement Proposals; PEP 412 <1>: functools --- 高阶函数和可调用对象上的操作.
                                                             (line   67)
* Python Enhancement Proposals; PEP 414: PEP 414 显式的Unicode文本.
                                                             (line   17)
* Python Enhancement Proposals; PEP 414 <1>: 字符串与字节串字面值.
                                                             (line   49)
* Python Enhancement Proposals; PEP 418: time<6>.            (line    6)
* Python Enhancement Proposals; PEP 420: PEP 420 隐式命名空间包.
                                                             (line    9)
* Python Enhancement Proposals; PEP 420 <1>: PEP 420 隐式命名空间包.
                                                             (line   14)
* Python Enhancement Proposals; PEP 420 <2>: 核心与内置函数<55>.
                                                             (line   56)
* Python Enhancement Proposals; PEP 420 <3>: 核心与内置函数<60>.
                                                             (line  114)
* Python Enhancement Proposals; PEP 420 <4>: 导入系统.       (line   35)
* Python Enhancement Proposals; PEP 420 <5>: 命名空间包.     (line   20)
* Python Enhancement Proposals; PEP 420 <6>: module __path__.
                                                             (line   16)
* Python Enhancement Proposals; PEP 420 <7>: module __path__.
                                                             (line   17)
* Python Enhancement Proposals; PEP 420 <8>: 参考文献.       (line   10)
* Python Enhancement Proposals; PEP 420 <9>: 参考文献.       (line   12)
* Python Enhancement Proposals; PEP 420 <10>: 参考文献.      (line   12)
* Python Enhancement Proposals; PEP 420 <11>: 簡介<11>.      (line   51)
* Python Enhancement Proposals; PEP 420 <12>: 術語表.        (line  397)
* Python Enhancement Proposals; PEP 420 <13>: 術語表.        (line  800)
* Python Enhancement Proposals; PEP 420 <14>: 術語表.        (line  932)
* Python Enhancement Proposals; PEP 421: SimpleNamespace.    (line   16)
* Python Enhancement Proposals; PEP 421 <1>: sys --- 系统相关的参数和函数.
                                                             (line  782)
* Python Enhancement Proposals; PEP 421 <2>: sys --- 系统相关的参数和函数.
                                                             (line  787)
* Python Enhancement Proposals; PEP 424: 其他语言特性修改<6>.
                                                             (line   57)
* Python Enhancement Proposals; PEP 424 <1>: operator<2>.    (line    8)
* Python Enhancement Proposals; PEP 427: 關鍵術語.           (line   29)
* Python Enhancement Proposals; PEP 428: 摘要 - 发布重点<6>. (line   39)
* Python Enhancement Proposals; PEP 428 <1>: pathlib<6>.     (line   17)
* Python Enhancement Proposals; PEP 428 <2>: pathlib --- 面向对象的文件系统路径.
                                                             (line   32)
* Python Enhancement Proposals; PEP 429: Python 3 4 有什么新变化.
                                                             (line   16)
* Python Enhancement Proposals; PEP 432: 其他 CPython 实现的改变<2>.
                                                             (line    6)
* Python Enhancement Proposals; PEP 432 <1>: 核心与内置函数<38>.
                                                             (line  313)
* Python Enhancement Proposals; PEP 432 <2>: Multi-Phase Initialization Private Provisional API.
                                                             (line    7)
* Python Enhancement Proposals; PEP 432 <3>: Multi-Phase Initialization Private Provisional API.
                                                             (line   60)
* Python Enhancement Proposals; PEP 434: PEP 434 IDLE Enhancement Exception for All Branches.
                                                             (line    6)
* Python Enhancement Proposals; PEP 435: 摘要 - 发布重点<6>. (line   36)
* Python Enhancement Proposals; PEP 435 <1>: enum<5>.        (line    6)
* Python Enhancement Proposals; PEP 435 <2>: enum<5>.        (line   15)
* Python Enhancement Proposals; PEP 436: 摘要 - 发布重点<6>. (line  120)
* Python Enhancement Proposals; PEP 436 <1>: PEP 436 Argument Clinic.
                                                             (line    6)
* Python Enhancement Proposals; PEP 436 <2>: PEP 436 Argument Clinic.
                                                             (line   28)
* Python Enhancement Proposals; PEP 441: zipapp<2>.          (line    6)
* Python Enhancement Proposals; PEP 441 <1>: zipapp<2>.      (line   24)
* Python Enhancement Proposals; PEP 442: 移除.               (line   59)
* Python Enhancement Proposals; PEP 442 <1>: 摘要 - 发布重点<6>.
                                                             (line  113)
* Python Enhancement Proposals; PEP 442 <2>: 摘要 - 发布重点<6>.
                                                             (line  115)
* Python Enhancement Proposals; PEP 442 <3>: PEP 442 Safe Object Finalization.
                                                             (line    6)
* Python Enhancement Proposals; PEP 442 <4>: PEP 442 Safe Object Finalization.
                                                             (line   21)
* Python Enhancement Proposals; PEP 442 <5>: C API<16>.      (line   57)
* Python Enhancement Proposals; PEP 442 <6>: gc --- 垃圾回收器接口.
                                                             (line  205)
* Python Enhancement Proposals; PEP 442 <7>: 终结和内存释放. (line   80)
* Python Enhancement Proposals; PEP 442 <8>: PyTypeObject Slots.
                                                             (line 1390)
* Python Enhancement Proposals; PEP 443: 摘要 - 发布重点<6>. (line   55)
* Python Enhancement Proposals; PEP 443 <1>: functools<4>.   (line   22)
* Python Enhancement Proposals; PEP 443 <2>: 術語表.         (line  482)
* Python Enhancement Proposals; PEP 445: 摘要 - 发布重点<6>. (line  118)
* Python Enhancement Proposals; PEP 445 <1>: PEP 445 Customization of CPython Memory Allocators.
                                                             (line    6)
* Python Enhancement Proposals; PEP 445 <2>: PEP 445 Customization of CPython Memory Allocators.
                                                             (line   12)
* Python Enhancement Proposals; PEP 445 <3>: 其他改进<2>.    (line   63)
* Python Enhancement Proposals; PEP 446: 摘要 - 发布重点<6>. (line   14)
* Python Enhancement Proposals; PEP 446 <1>: 摘要 - 发布重点<6>.
                                                             (line   78)
* Python Enhancement Proposals; PEP 446 <2>: PEP 446 Newly Created File Descriptors Are Non-Inheritable.
                                                             (line    6)
* Python Enhancement Proposals; PEP 446 <3>: PEP 446 Newly Created File Descriptors Are Non-Inheritable.
                                                             (line   26)
* Python Enhancement Proposals; PEP 448: PEP 448 - Additional Unpacking Generalizations.
                                                             (line    6)
* Python Enhancement Proposals; PEP 448 <1>: PEP 448 - Additional Unpacking Generalizations.
                                                             (line   38)
* Python Enhancement Proposals; PEP 448 <2>: 文档<45>.       (line   10)
* Python Enhancement Proposals; PEP 448 <3>: 文档<49>.       (line    9)
* Python Enhancement Proposals; PEP 448 <4>: 核心与内置函数<63>.
                                                             (line   12)
* Python Enhancement Proposals; PEP 448 <5>: 核心与内置函数<66>.
                                                             (line    9)
* Python Enhancement Proposals; PEP 448 <6>: 字典显示.       (line   23)
* Python Enhancement Proposals; PEP 448 <7>: 调用.           (line   89)
* Python Enhancement Proposals; PEP 448 <8>: 表达式列表.     (line   18)
* Python Enhancement Proposals; PEP 450: 摘要 - 发布重点<6>. (line   47)
* Python Enhancement Proposals; PEP 450 <1>: statistics<3>.  (line    6)
* Python Enhancement Proposals; PEP 450 <2>: statistics<3>.  (line   14)
* Python Enhancement Proposals; PEP 451: PEP 489 Multi-phase extension module initialization.
                                                             (line    7)
* Python Enhancement Proposals; PEP 451 <1>: 摘要 - 发布重点<6>.
                                                             (line   22)
* Python Enhancement Proposals; PEP 451 <2>: PEP 451 A ModuleSpec Type for the Import System.
                                                             (line    6)
* Python Enhancement Proposals; PEP 451 <3>: 核心与内置函数<55>.
                                                             (line   76)
* Python Enhancement Proposals; PEP 451 <4>: 参考文献.       (line   22)
* Python Enhancement Proposals; PEP 451 <5>: sys --- 系统相关的参数和函数.
                                                             (line  884)
* Python Enhancement Proposals; PEP 451 <6>: pkgutil --- 包扩展工具.
                                                             (line   89)
* Python Enhancement Proposals; PEP 451 <7>: pkgutil --- 包扩展工具.
                                                             (line  120)
* Python Enhancement Proposals; PEP 451 <8>: runpy ——查找并执行 Python 模块.
                                                             (line   72)
* Python Enhancement Proposals; PEP 451 <9>: runpy ——查找并执行 Python 模块.
                                                             (line  133)
* Python Enhancement Proposals; PEP 451 <10>: runpy ——查找并执行 Python 模块.
                                                             (line  149)
* Python Enhancement Proposals; PEP 451 <11>: 簡介<11>.      (line   55)
* Python Enhancement Proposals; PEP 451 <12>: Multi-phase initialization.
                                                             (line   71)
* Python Enhancement Proposals; PEP 451 <13>: 術語表.        (line  397)
* Python Enhancement Proposals; PEP 453: 摘要 - 发布重点<6>. (line   12)
* Python Enhancement Proposals; PEP 453 <1>: 摘要 - 发布重点<6>.
                                                             (line   34)
* Python Enhancement Proposals; PEP 453 <2>: Bootstrapping pip By Default.
                                                             (line    6)
* Python Enhancement Proposals; PEP 453 <3>: 文档更改.       (line   20)
* Python Enhancement Proposals; PEP 453 <4>: ensurepip.      (line    7)
* Python Enhancement Proposals; PEP 453 <5>: venv<5>.        (line   13)
* Python Enhancement Proposals; PEP 453 <6>: 其他改进<2>.    (line   73)
* Python Enhancement Proposals; PEP 453 <7>: PEP 477 Backport ensurepip PEP 453 to Python 2 7.
                                                             (line    6)
* Python Enhancement Proposals; PEP 453 <8>: Bootstrapping pip By Default<2>.
                                                             (line    6)
* Python Enhancement Proposals; PEP 453 <9>: 文档更改<2>.    (line   20)
* Python Enhancement Proposals; PEP 453 <10>: ensurepip --- Bootstrapping the pip installer.
                                                             (line   33)
* Python Enhancement Proposals; PEP 454: 摘要 - 发布重点<6>. (line   50)
* Python Enhancement Proposals; PEP 454 <1>: tracemalloc<4>. (line    6)
* Python Enhancement Proposals; PEP 454 <2>: tracemalloc<4>. (line   22)
* Python Enhancement Proposals; PEP 456: 摘要 - 发布重点<6>. (line   75)
* Python Enhancement Proposals; PEP 456 <1>: PEP 456 Secure and Interchangeable Hash Algorithm.
                                                             (line    6)
* Python Enhancement Proposals; PEP 461: PEP 461 - percent formatting support for bytes and bytearray.
                                                             (line    6)
* Python Enhancement Proposals; PEP 461 <1>: PEP 461 - percent formatting support for bytes and bytearray.
                                                             (line   41)
* Python Enhancement Proposals; PEP 461 <2>: printf 风格的字节串格式化.
                                                             (line  172)
* Python Enhancement Proposals; PEP 465: PEP 465 - 用于矩阵乘法的专用中缀运算符.
                                                             (line    6)
* Python Enhancement Proposals; PEP 465 <1>: PEP 465 - 用于矩阵乘法的专用中缀运算符.
                                                             (line   44)
* Python Enhancement Proposals; PEP 465 <2>: 构建和 C API 的改变<3>.
                                                             (line   43)
* Python Enhancement Proposals; PEP 466: PEP 466 Network Security Enhancements for Python 2 7.
                                                             (line    6)
* Python Enhancement Proposals; PEP 466 <1>: PEP 466 Network Security Enhancements for Python 2 7.
                                                             (line   11)
* Python Enhancement Proposals; PEP 466 <2>: PEP 466 Network Security Enhancements for Python 2 7.
                                                             (line   21)
* Python Enhancement Proposals; PEP 466 <3>: PEP 466 Network Security Enhancements for Python 2 7.
                                                             (line   32)
* Python Enhancement Proposals; PEP 468: PEP 468 保留关键字参数顺序.
                                                             (line   12)
* Python Enhancement Proposals; PEP 468 <1>: 库<49>.         (line   87)
* Python Enhancement Proposals; PEP 468 <2>: OrderedDict 对象.
                                                             (line   73)
* Python Enhancement Proposals; PEP 471: PEP 471 - os scandir function -- a better and faster directory iterator.
                                                             (line    6)
* Python Enhancement Proposals; PEP 471 <1>: PEP 471 - os scandir function -- a better and faster directory iterator.
                                                             (line   29)
* Python Enhancement Proposals; PEP 471 <2>: 库<88>.         (line    6)
* Python Enhancement Proposals; PEP 475: PEP 475 Retry system calls failing with EINTR.
                                                             (line   32)
* Python Enhancement Proposals; PEP 475 <1>: PEP 475 Retry system calls failing with EINTR.
                                                             (line   75)
* Python Enhancement Proposals; PEP 475 <2>: 改变了的Python API.
                                                             (line    6)
* Python Enhancement Proposals; PEP 475 <3>: 库<39>.         (line  229)
* Python Enhancement Proposals; PEP 475 <4>: 库<86>.         (line  143)
* Python Enhancement Proposals; PEP 475 <5>: 內建函式.       (line 1062)
* Python Enhancement Proposals; PEP 475 <6>: OS 异常.        (line   70)
* Python Enhancement Proposals; PEP 475 <7>: 文件描述符操作. (line  261)
* Python Enhancement Proposals; PEP 475 <8>: 文件描述符操作. (line  515)
* Python Enhancement Proposals; PEP 475 <9>: 文件描述符操作. (line  623)
* Python Enhancement Proposals; PEP 475 <10>: 进程管理.      (line  726)
* Python Enhancement Proposals; PEP 475 <11>: 函数<3>.       (line  196)
* Python Enhancement Proposals; PEP 475 <12>: 套接字对象.    (line   24)
* Python Enhancement Proposals; PEP 475 <13>: 套接字对象.    (line   67)
* Python Enhancement Proposals; PEP 475 <14>: 套接字对象.    (line  198)
* Python Enhancement Proposals; PEP 475 <15>: 套接字对象.    (line  209)
* Python Enhancement Proposals; PEP 475 <16>: 套接字对象.    (line  269)
* Python Enhancement Proposals; PEP 475 <17>: 套接字对象.    (line  329)
* Python Enhancement Proposals; PEP 475 <18>: 套接字对象.    (line  344)
* Python Enhancement Proposals; PEP 475 <19>: 套接字对象.    (line  360)
* Python Enhancement Proposals; PEP 475 <20>: 套接字对象.    (line  395)
* Python Enhancement Proposals; PEP 475 <21>: select --- 等待 I/O 完成.
                                                             (line  126)
* Python Enhancement Proposals; PEP 475 <22>: /dev/poll 轮询对象.
                                                             (line   71)
* Python Enhancement Proposals; PEP 475 <23>: 边缘触发和水平触发的轮询 epoll 对象.
                                                             (line   99)
* Python Enhancement Proposals; PEP 475 <24>: Poll 对象.     (line   78)
* Python Enhancement Proposals; PEP 475 <25>: Kqueue 对象.   (line   36)
* Python Enhancement Proposals; PEP 475 <26>: 类<2>.         (line  116)
* Python Enhancement Proposals; PEP 475 <27>: 模块内容<5>.   (line  471)
* Python Enhancement Proposals; PEP 475 <28>: 模块内容<5>.   (line  488)
* Python Enhancement Proposals; PEP 476: PEP 476 Enabling certificate verification by default for stdlib http clients<2>.
                                                             (line    6)
* Python Enhancement Proposals; PEP 477: PEP 477 Backport ensurepip PEP 453 to Python 2 7.
                                                             (line    6)
* Python Enhancement Proposals; PEP 478: Python 3 5 有什麼新功能.
                                                             (line   17)
* Python Enhancement Proposals; PEP 479: Python 行为的更改.  (line   10)
* Python Enhancement Proposals; PEP 479 <1>: PEP 479 Change StopIteration handling inside generators.
                                                             (line   12)
* Python Enhancement Proposals; PEP 479 <2>: PEP 479 Change StopIteration handling inside generators.
                                                             (line   47)
* Python Enhancement Proposals; PEP 479 <3>: 库<30>.         (line 1268)
* Python Enhancement Proposals; PEP 479 <4>: 库<34>.         (line   52)
* Python Enhancement Proposals; PEP 479 <5>: 核心与内置函数<34>.
                                                             (line   34)
* Python Enhancement Proposals; PEP 479 <6>: 库<42>.         (line   95)
* Python Enhancement Proposals; PEP 479 <7>: 库<56>.         (line   80)
* Python Enhancement Proposals; PEP 479 <8>: 库<69>.         (line  326)
* Python Enhancement Proposals; PEP 479 <9>: 具体异常.       (line  195)
* Python Enhancement Proposals; PEP 479 <10>: 具体异常.      (line  197)
* Python Enhancement Proposals; PEP 479 <11>: __future__ --- Future 语句定义.
                                                             (line   84)
* Python Enhancement Proposals; PEP 483: PEP 484 - 类型提示. (line   47)
* Python Enhancement Proposals; PEP 483 <1>: typing --- 类型提示支持.
                                                             (line   19)
* Python Enhancement Proposals; PEP 483 <2>: Relevant PEPs.  (line    6)
* Python Enhancement Proposals; PEP 483 <3>: 術語表.         (line  490)
* Python Enhancement Proposals; PEP 484: ast<2>.             (line   16)
* Python Enhancement Proposals; PEP 484 <1>: ast<2>.         (line   19)
* Python Enhancement Proposals; PEP 484 <2>: PEP 560 对 typing 模块和泛型类型的核心支持.
                                                             (line    6)
* Python Enhancement Proposals; PEP 484 <3>: PEP 526 变量标注的语法.
                                                             (line    6)
* Python Enhancement Proposals; PEP 484 <4>: PEP 484 - 类型提示.
                                                             (line   16)
* Python Enhancement Proposals; PEP 484 <5>: PEP 484 - 类型提示.
                                                             (line   41)
* Python Enhancement Proposals; PEP 484 <6>: 函式註釋 Function Annotations.
                                                             (line    7)
* Python Enhancement Proposals; PEP 484 <7>: 模拟泛型类型.   (line   15)
* Python Enhancement Proposals; PEP 484 <8>: 带标注的赋值语句.
                                                             (line   37)
* Python Enhancement Proposals; PEP 484 <9>: 函数定义.       (line  106)
* Python Enhancement Proposals; PEP 484 <10>: typing --- 类型提示支持.
                                                             (line   18)
* Python Enhancement Proposals; PEP 484 <11>: Relevant PEPs. (line    6)
* Python Enhancement Proposals; PEP 484 <12>: NewType.       (line   59)
* Python Enhancement Proposals; PEP 484 <13>: 名义子类型 vs 结构子类型.
                                                             (line    6)
* Python Enhancement Proposals; PEP 484 <14>: 名义子类型 vs 结构子类型.
                                                             (line   11)
* Python Enhancement Proposals; PEP 484 <15>: 特殊形式.      (line  112)
* Python Enhancement Proposals; PEP 484 <16>: 构建泛型类型.  (line   61)
* Python Enhancement Proposals; PEP 484 <17>: 构建泛型类型.  (line   63)
* Python Enhancement Proposals; PEP 484 <18>: 函数与装饰器.  (line   35)
* Python Enhancement Proposals; PEP 484 <19>: ast 中的辅助函数.
                                                             (line   15)
* Python Enhancement Proposals; PEP 484 <20>: ast 中的辅助函数.
                                                             (line   25)
* Python Enhancement Proposals; PEP 484 <21>: Compiler Flags.
                                                             (line   23)
* Python Enhancement Proposals; PEP 484 <22>: 術語表.        (line   56)
* Python Enhancement Proposals; PEP 484 <23>: 術語表.        (line  425)
* Python Enhancement Proposals; PEP 484 <24>: 術語表.        (line  490)
* Python Enhancement Proposals; PEP 484 <25>: 術語表.        (line 1122)
* Python Enhancement Proposals; PEP 484 <26>: 術語表.        (line 1136)
* Python Enhancement Proposals; PEP 484 <27>: 術語表.        (line 1161)
* Python Enhancement Proposals; PEP 485: PEP 485 A function for testing approximate equality.
                                                             (line    6)
* Python Enhancement Proposals; PEP 485 <1>: PEP 485 A function for testing approximate equality.
                                                             (line   36)
* Python Enhancement Proposals; PEP 485 <2>: 库<84>.         (line   10)
* Python Enhancement Proposals; PEP 485 <3>: 数论与表示函数. (line  121)
* Python Enhancement Proposals; PEP 485 <4>: 分类函数.       (line   46)
* Python Enhancement Proposals; PEP 486: PEP 486 Make the Python Launcher aware of virtual environments.
                                                             (line    6)
* Python Enhancement Proposals; PEP 486 <1>: PEP 486 Make the Python Launcher aware of virtual environments.
                                                             (line   14)
* Python Enhancement Proposals; PEP 486 <2>: Windows<53>.    (line    6)
* Python Enhancement Proposals; PEP 487: PEP 487 更简单的自定义类创建.
                                                             (line   29)
* Python Enhancement Proposals; PEP 487 <1>: PEP 487 描述器协议的增强.
                                                             (line    6)
* Python Enhancement Proposals; PEP 487 <2>: PEP 487 描述器协议的增强.
                                                             (line   30)
* Python Enhancement Proposals; PEP 487 <3>: Python API 的更改.
                                                             (line  103)
* Python Enhancement Proposals; PEP 487 <4>: 文档<35>.       (line   52)
* Python Enhancement Proposals; PEP 487 <5>: 文档<42>.       (line    8)
* Python Enhancement Proposals; PEP 487 <6>: 核心与内置函数<52>.
                                                             (line   46)
* Python Enhancement Proposals; PEP 488: PEP 488 Elimination of PYO files.
                                                             (line    6)
* Python Enhancement Proposals; PEP 488 <1>: PEP 488 Elimination of PYO files.
                                                             (line   20)
* Python Enhancement Proposals; PEP 488 <2>: 改变了的Python API.
                                                             (line   79)
* Python Enhancement Proposals; PEP 488 <3>: 核心与内置函数<70>.
                                                             (line   15)
* Python Enhancement Proposals; PEP 488 <4>: 其他选项.       (line   62)
* Python Enhancement Proposals; PEP 488 <5>: 其他选项.       (line   65)
* Python Enhancement Proposals; PEP 488 <6>: 其他选项.       (line   71)
* Python Enhancement Proposals; PEP 488 <7>: 其他选项.       (line   73)
* Python Enhancement Proposals; PEP 488 <8>: test support --- Utilities for the Python test suite.
                                                             (line  252)
* Python Enhancement Proposals; PEP 488 <9>: 簡介<11>.       (line   59)
* Python Enhancement Proposals; PEP 488 <10>: importlib util —— 导入器的工具程序代码.
                                                             (line   22)
* Python Enhancement Proposals; PEP 488 <11>: importlib util —— 导入器的工具程序代码.
                                                             (line   55)
* Python Enhancement Proposals; PEP 488 <12>: py_compile --- 编译 Python 源文件.
                                                             (line   25)
* Python Enhancement Proposals; PEP 488 <13>: distutils util --- Miscellaneous other utility functions.
                                                             (line  152)
* Python Enhancement Proposals; PEP 488 <14>: distutils util --- Miscellaneous other utility functions.
                                                             (line  189)
* Python Enhancement Proposals; PEP 489: PEP 489 Multi-phase extension module initialization.
                                                             (line    6)
* Python Enhancement Proposals; PEP 489 <1>: PEP 489 Multi-phase extension module initialization.
                                                             (line   18)
* Python Enhancement Proposals; PEP 489 <2>: 构建和 C API 的改变<3>.
                                                             (line   37)
* Python Enhancement Proposals; PEP 489 <3>: 库<18>.         (line   65)
* Python Enhancement Proposals; PEP 489 <4>: 核心与内置函数<17>.
                                                             (line   28)
* Python Enhancement Proposals; PEP 489 <5>: 核心与内置函数<17>.
                                                             (line   35)
* Python Enhancement Proposals; PEP 489 <6>: 核心与内置函数<17>.
                                                             (line   50)
* Python Enhancement Proposals; PEP 489 <7>: 核心与内置函数<18>.
                                                             (line   46)
* Python Enhancement Proposals; PEP 489 <8>: 核心与内置函数<18>.
                                                             (line   49)
* Python Enhancement Proposals; PEP 489 <9>: 核心与内置函数<18>.
                                                             (line   51)
* Python Enhancement Proposals; PEP 489 <10>: 核心与内置函数<18>.
                                                             (line   71)
* Python Enhancement Proposals; PEP 489 <11>: 核心与内置函数<18>.
                                                             (line   75)
* Python Enhancement Proposals; PEP 489 <12>: 核心与内置函数<19>.
                                                             (line   17)
* Python Enhancement Proposals; PEP 489 <13>: 核心与内置函数<19>.
                                                             (line   20)
* Python Enhancement Proposals; PEP 489 <14>: 核心与内置函数<19>.
                                                             (line   40)
* Python Enhancement Proposals; PEP 489 <15>: 核心与内置函数<19>.
                                                             (line   54)
* Python Enhancement Proposals; PEP 489 <16>: 核心与内置函数<19>.
                                                             (line  109)
* Python Enhancement Proposals; PEP 489 <17>: 核心与内置函数<19>.
                                                             (line  118)
* Python Enhancement Proposals; PEP 489 <18>: 核心与内置函数<20>.
                                                             (line   29)
* Python Enhancement Proposals; PEP 489 <19>: 核心与内置函数<20>.
                                                             (line   32)
* Python Enhancement Proposals; PEP 489 <20>: 核心与内置函数<20>.
                                                             (line   52)
* Python Enhancement Proposals; PEP 489 <21>: 核心与内置函数<20>.
                                                             (line   55)
* Python Enhancement Proposals; PEP 489 <22>: 核心与内置函数<20>.
                                                             (line   58)
* Python Enhancement Proposals; PEP 489 <23>: 核心与内置函数<21>.
                                                             (line   62)
* Python Enhancement Proposals; PEP 489 <24>: 簡介<11>.      (line   63)
* Python Enhancement Proposals; PEP 489 <25>: importlib machinery —— 导入器和路径钩子函数。.
                                                             (line   66)
* Python Enhancement Proposals; PEP 489 <26>: importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  279)
* Python Enhancement Proposals; PEP 489 <27>: importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  285)
* Python Enhancement Proposals; PEP 489 <28>: 模块方法表和初始化函数.
                                                             (line  114)
* Python Enhancement Proposals; PEP 489 <29>: 构建C/C++扩展. (line   34)
* Python Enhancement Proposals; PEP 489 <30>: Multi-phase initialization.
                                                             (line  107)
* Python Enhancement Proposals; PEP 492: PEP 525 异步生成器. (line    6)
* Python Enhancement Proposals; PEP 492 <1>: 新关键字.       (line    7)
* Python Enhancement Proposals; PEP 492 <2>: PEP 492 - 使用 async 和 await 语法实现协程.
                                                             (line    6)
* Python Enhancement Proposals; PEP 492 <3>: PEP 492 - 使用 async 和 await 语法实现协程.
                                                             (line   97)
* Python Enhancement Proposals; PEP 492 <4>: 新关键字<2>.    (line    7)
* Python Enhancement Proposals; PEP 492 <5>: C API 中的改变<4>.
                                                             (line   25)
* Python Enhancement Proposals; PEP 492 <6>: 核心与内置函数<37>.
                                                             (line   99)
* Python Enhancement Proposals; PEP 492 <7>: 库<60>.         (line   36)
* Python Enhancement Proposals; PEP 492 <8>: 库<72>.         (line   16)
* Python Enhancement Proposals; PEP 492 <9>: 核心与内置函数<67>.
                                                             (line   14)
* Python Enhancement Proposals; PEP 492 <10>: 可等待对象.    (line   26)
* Python Enhancement Proposals; PEP 492 <11>: yield 表达式.  (line   86)
* Python Enhancement Proposals; PEP 492 <12>: async with 语句.
                                                             (line   43)
* Python Enhancement Proposals; PEP 492 <13>: 容器抽象基类.  (line  237)
* Python Enhancement Proposals; PEP 492 <14>: Code Objects Bit Flags.
                                                             (line   42)
* Python Enhancement Proposals; PEP 492 <15>: Code Objects Bit Flags.
                                                             (line   51)
* Python Enhancement Proposals; PEP 492 <16>: 術語表.        (line   90)
* Python Enhancement Proposals; PEP 492 <17>: 術語表.        (line  119)
* Python Enhancement Proposals; PEP 492 <18>: 術語表.        (line  125)
* Python Enhancement Proposals; PEP 492 <19>: 術語表.        (line  133)
* Python Enhancement Proposals; PEP 492 <20>: 術語表.        (line  145)
* Python Enhancement Proposals; PEP 492 <21>: 術語表.        (line  255)
* Python Enhancement Proposals; PEP 492 <22>: 術語表.        (line  262)
* Python Enhancement Proposals; PEP 493: PEP 493：适用于Python 2 7 的 HTTPS 验证迁移工具.
                                                             (line    6)
* Python Enhancement Proposals; PEP 494: Python 3 6 有什么新变化.
                                                             (line   16)
* Python Enhancement Proposals; PEP 495: PEP 495 消除本地时间的歧义.
                                                             (line   13)
* Python Enhancement Proposals; PEP 495 <1>: PEP 495 消除本地时间的歧义.
                                                             (line   36)
* Python Enhancement Proposals; PEP 495 <2>: 库<55>.         (line   96)
* Python Enhancement Proposals; PEP 495 <3>: 使用 ZoneInfo.  (line   31)
* Python Enhancement Proposals; PEP 498: PEP 498 格式化字符串字面值.
                                                             (line    6)
* Python Enhancement Proposals; PEP 498 <1>: PEP 498 格式化字符串字面值.
                                                             (line   25)
* Python Enhancement Proposals; PEP 498 <2>: 核心与内置函数<55>.
                                                             (line  284)
* Python Enhancement Proposals; PEP 498 <3>: 格式字符串字面值.
                                                             (line  117)
* Python Enhancement Proposals; PEP 498 <4>: 術語表.         (line  367)
* Python Enhancement Proposals; PEP 5:   PEP 230 Warning Framework.
                                                             (line   66)
* Python Enhancement Proposals; PEP 5 <1>: 提议对 Python 加入不兼容的更改是否合理？.
                                                             (line   11)
* Python Enhancement Proposals; PEP 506: secrets.            (line   19)
* Python Enhancement Proposals; PEP 506 <1>: 库<62>.         (line   60)
* Python Enhancement Proposals; PEP 506 <2>: secrets --- 產生用於管理機密的安全亂數.
                                                             (line   23)
* Python Enhancement Proposals; PEP 511: Python API 的更改.  (line   32)
* Python Enhancement Proposals; PEP 514: Windows<43>.        (line    8)
* Python Enhancement Proposals; PEP 515: PEP 515 数字字面值中的下划线。.
                                                             (line    6)
* Python Enhancement Proposals; PEP 515 <1>: PEP 515 数字字面值中的下划线。.
                                                             (line   28)
* Python Enhancement Proposals; PEP 515 <2>: 核心与内置函数<51>.
                                                             (line   15)
* Python Enhancement Proposals; PEP 515 <3>: 核心与内置函数<51>.
                                                             (line   43)
* Python Enhancement Proposals; PEP 515 <4>: 格式规格迷你语言.
                                                             (line   89)
* Python Enhancement Proposals; PEP 519: PEP 519 添加文件系统路径协议.
                                                             (line   62)
* Python Enhancement Proposals; PEP 519 <1>: 库<55>.         (line    6)
* Python Enhancement Proposals; PEP 519 <2>: 核心与内置函数<54>.
                                                             (line   19)
* Python Enhancement Proposals; PEP 519 <3>: 库<60>.         (line   16)
* Python Enhancement Proposals; PEP 519 <4>: 库<60>.         (line   27)
* Python Enhancement Proposals; PEP 519 <5>: 库<60>.         (line   29)
* Python Enhancement Proposals; PEP 519 <6>: C API<37>.      (line    6)
* Python Enhancement Proposals; PEP 519 <7>: 術語表.         (line  914)
* Python Enhancement Proposals; PEP 520: PEP 520 保留类属性定义顺序.
                                                             (line   17)
* Python Enhancement Proposals; PEP 523: 移植到 Python 3 9<2>.
                                                             (line    6)
* Python Enhancement Proposals; PEP 523 <1>: PEP 523 向CPython 添加框架评估API.
                                                             (line   12)
* Python Enhancement Proposals; PEP 523 <2>: PEP 523 向CPython 添加框架评估API.
                                                             (line   26)
* Python Enhancement Proposals; PEP 523 <3>: 工具/示例<17>.  (line    7)
* Python Enhancement Proposals; PEP 523 <4>: 工具/示例<21>.  (line    7)
* Python Enhancement Proposals; PEP 523 <5>: 核心与内置函数<51>.
                                                             (line   83)
* Python Enhancement Proposals; PEP 523 <6>: Low-level API.  (line  149)
* Python Enhancement Proposals; PEP 523 <7>: Low-level API.  (line  159)
* Python Enhancement Proposals; PEP 524: 摘要 - 发布重点<4>. (line   66)
* Python Enhancement Proposals; PEP 524 <1>: os<4>.          (line   20)
* Python Enhancement Proposals; PEP 524 <2>: os<4>.          (line   24)
* Python Enhancement Proposals; PEP 524 <3>: 库<54>.         (line  150)
* Python Enhancement Proposals; PEP 524 <4>: 库<54>.         (line  154)
* Python Enhancement Proposals; PEP 524 <5>: 随机数.         (line   35)
* Python Enhancement Proposals; PEP 525: PEP 525 异步生成器. (line   22)
* Python Enhancement Proposals; PEP 525 <1>: 核心与内置函数<51>.
                                                             (line   49)
* Python Enhancement Proposals; PEP 525 <2>: yield 表达式.   (line   84)
* Python Enhancement Proposals; PEP 525 <3>: 容器抽象基类.   (line  237)
* Python Enhancement Proposals; PEP 525 <4>: sys --- 系统相关的参数和函数.
                                                             (line  684)
* Python Enhancement Proposals; PEP 525 <5>: sys --- 系统相关的参数和函数.
                                                             (line 1206)
* Python Enhancement Proposals; PEP 525 <6>: Code Objects Bit Flags.
                                                             (line   60)
* Python Enhancement Proposals; PEP 525 <7>: 術語表.         (line  119)
* Python Enhancement Proposals; PEP 526: ast<2>.             (line   17)
* Python Enhancement Proposals; PEP 526 <1>: PEP 563：延迟的标注求值.
                                                             (line    6)
* Python Enhancement Proposals; PEP 526 <2>: PEP 526 变量标注的语法.
                                                             (line   26)
* Python Enhancement Proposals; PEP 526 <3>: typing<4>.      (line   23)
* Python Enhancement Proposals; PEP 526 <4>: 核心与内置函数<51>.
                                                             (line   51)
* Python Enhancement Proposals; PEP 526 <5>: 带标注的赋值语句.
                                                             (line   32)
* Python Enhancement Proposals; PEP 526 <6>: 函数定义.       (line  110)
* Python Enhancement Proposals; PEP 526 <7>: Relevant PEPs.  (line   11)
* Python Enhancement Proposals; PEP 526 <8>: 特殊形式.       (line  157)
* Python Enhancement Proposals; PEP 526 <9>: 其他特殊指令.   (line   51)
* Python Enhancement Proposals; PEP 526 <10>: 其他特殊指令.  (line   91)
* Python Enhancement Proposals; PEP 526 <11>: dataclasses --- 数据类.
                                                             (line   14)
* Python Enhancement Proposals; PEP 526 <12>: 类变量.        (line    7)
* Python Enhancement Proposals; PEP 526 <13>: ast 中的辅助函数.
                                                             (line   15)
* Python Enhancement Proposals; PEP 526 <14>: Compiler Flags.
                                                             (line   23)
* Python Enhancement Proposals; PEP 526 <15>: 術語表.        (line   56)
* Python Enhancement Proposals; PEP 526 <16>: 術語表.        (line 1162)
* Python Enhancement Proposals; PEP 528: PEP 528 将Windows控制台编码更改为UTF-8.
                                                             (line   17)
* Python Enhancement Proposals; PEP 528 <1>: UTF-8 模式.     (line   38)
* Python Enhancement Proposals; PEP 528 <2>: 全局配置变量.   (line  103)
* Python Enhancement Proposals; PEP 529: 更改的Python API.   (line    7)
* Python Enhancement Proposals; PEP 529 <1>: PEP 529 将Windows文件系统编码更改为UTF-8.
                                                             (line   22)
* Python Enhancement Proposals; PEP 529 <2>: 库<25>.         (line  621)
* Python Enhancement Proposals; PEP 529 <3>: Windows<38>.    (line   14)
* Python Enhancement Proposals; PEP 529 <4>: 环境变量.       (line  285)
* Python Enhancement Proposals; PEP 529 <5>: UTF-8 模式.     (line   40)
* Python Enhancement Proposals; PEP 529 <6>: 文件和目录.     (line  261)
* Python Enhancement Proposals; PEP 529 <7>: sys --- 系统相关的参数和函数.
                                                             (line  558)
* Python Enhancement Proposals; PEP 529 <8>: sys --- 系统相关的参数和函数.
                                                             (line 1239)
* Python Enhancement Proposals; PEP 529 <9>: File System Encoding.
                                                             (line    9)
* Python Enhancement Proposals; PEP 529 <10>: 全局配置变量.  (line   91)
* Python Enhancement Proposals; PEP 530: PEP 530 异步推导式. (line    6)
* Python Enhancement Proposals; PEP 530 <1>: PEP 530 异步推导式.
                                                             (line   18)
* Python Enhancement Proposals; PEP 530 <2>: 核心与内置函数<51>.
                                                             (line  145)
* Python Enhancement Proposals; PEP 530 <3>: 列表、集合与字典的显示.
                                                             (line   42)
* Python Enhancement Proposals; PEP 538: PEP 538 传统 C 区域强制转换.
                                                             (line   10)
* Python Enhancement Proposals; PEP 538 <1>: PEP 538 传统 C 区域强制转换.
                                                             (line   29)
* Python Enhancement Proposals; PEP 538 <2>: PEP 538 传统 C 区域强制转换.
                                                             (line   38)
* Python Enhancement Proposals; PEP 538 <3>: PEP 540 强制 UTF-8 运行时模式.
                                                             (line   22)
* Python Enhancement Proposals; PEP 538 <4>: 文档<25>.       (line   68)
* Python Enhancement Proposals; PEP 538 <5>: 文档<26>.       (line    6)
* Python Enhancement Proposals; PEP 538 <6>: 核心与内置函数<38>.
                                                             (line  135)
* Python Enhancement Proposals; PEP 538 <7>: 环境变量.       (line  341)
* Python Enhancement Proposals; PEP 538 <8>: Python Configuration.
                                                             (line   13)
* Python Enhancement Proposals; PEP 539: PEP 539 用于线程局部存储的新 C API.
                                                             (line   11)
* Python Enhancement Proposals; PEP 539 <1>: PEP 539 用于线程局部存储的新 C API.
                                                             (line   25)
* Python Enhancement Proposals; PEP 539 <2>: C API<26>.      (line   13)
* Python Enhancement Proposals; PEP 539 <3>: Thread Specific Storage TSS API.
                                                             (line   15)
* Python Enhancement Proposals; PEP 540: PEP 540 强制 UTF-8 运行时模式.
                                                             (line   16)
* Python Enhancement Proposals; PEP 540 <1>: PEP 540 强制 UTF-8 运行时模式.
                                                             (line   29)
* Python Enhancement Proposals; PEP 540 <2>: 核心与内置函数<35>.
                                                             (line   63)
* Python Enhancement Proposals; PEP 540 <3>: 环境变量.       (line  400)
* Python Enhancement Proposals; PEP 540 <4>: Python Configuration.
                                                             (line   13)
* Python Enhancement Proposals; PEP 544: typing<3>.          (line   29)
* Python Enhancement Proposals; PEP 544 <1>: Relevant PEPs.  (line   17)
* Python Enhancement Proposals; PEP 544 <2>: 名义子类型 vs 结构子类型.
                                                             (line   20)
* Python Enhancement Proposals; PEP 544 <3>: 构建泛型类型.   (line   99)
* Python Enhancement Proposals; PEP 545: PEP 545 Python 文档翻译.
                                                             (line    6)
* Python Enhancement Proposals; PEP 545 <1>: PEP 545 Python 文档翻译.
                                                             (line   19)
* Python Enhancement Proposals; PEP 552: PEP 552 基于哈希值的 pyc 文件.
                                                             (line   12)
* Python Enhancement Proposals; PEP 552 <1>: PEP 552 基于哈希值的 pyc 文件.
                                                             (line   29)
* Python Enhancement Proposals; PEP 552 <2>: 库<30>.         (line  794)
* Python Enhancement Proposals; PEP 552 <3>: 核心与内置函数<35>.
                                                             (line   75)
* Python Enhancement Proposals; PEP 552 <4>: 簡介<11>.       (line   67)
* Python Enhancement Proposals; PEP 552 <5>: py_compile --- 编译 Python 源文件.
                                                             (line   65)
* Python Enhancement Proposals; PEP 552 <6>: PyConfig.       (line  145)
* Python Enhancement Proposals; PEP 553: PEP 553 内置的 breakpoint.
                                                             (line   19)
* Python Enhancement Proposals; PEP 553 <1>: 核心与内置函数<37>.
                                                             (line   73)
* Python Enhancement Proposals; PEP 557: dataclasses.        (line   25)
* Python Enhancement Proposals; PEP 557 <1>: dataclasses --- 数据类.
                                                             (line   12)
* Python Enhancement Proposals; PEP 560: PEP 560 对 typing 模块和泛型类型的核心支持.
                                                             (line   17)
* Python Enhancement Proposals; PEP 560 <1>: types.          (line   11)
* Python Enhancement Proposals; PEP 560 <2>: 核心与内置函数<35>.
                                                             (line   66)
* Python Enhancement Proposals; PEP 560 <3>: 解析 MRO 条目.  (line   14)
* Python Enhancement Proposals; PEP 560 <4>: __class_getitem__ versus __getitem__.
                                                             (line   85)
* Python Enhancement Proposals; PEP 560 <5>: 动态类型创建.   (line   50)
* Python Enhancement Proposals; PEP 560 <6>: 动态类型创建.   (line   63)
* Python Enhancement Proposals; PEP 562: PEP 562 定制对模块属性的访问.
                                                             (line   15)
* Python Enhancement Proposals; PEP 562 <1>: 库<37>.         (line   63)
* Python Enhancement Proposals; PEP 562 <2>: 核心与内置函数<35>.
                                                             (line   69)
* Python Enhancement Proposals; PEP 562 <3>: 自定义模块属性访问.
                                                             (line   44)
* Python Enhancement Proposals; PEP 563: PEP 563：延迟的标注求值.
                                                             (line   43)
* Python Enhancement Proposals; PEP 563 <1>: future 语句.    (line   30)
* Python Enhancement Proposals; PEP 563 <2>: 函数定义.       (line  114)
* Python Enhancement Proposals; PEP 563 <3>: 常量<4>.        (line   23)
* Python Enhancement Proposals; PEP 563 <4>: __future__ --- Future 语句定义.
                                                             (line   88)
* Python Enhancement Proposals; PEP 564: PEP 564 具有纳秒级精度的新时间函数.
                                                             (line    7)
* Python Enhancement Proposals; PEP 564 <1>: PEP 564 具有纳秒级精度的新时间函数.
                                                             (line   30)
* Python Enhancement Proposals; PEP 564 <2>: time<3>.        (line    6)
* Python Enhancement Proposals; PEP 564 <3>: 库<39>.         (line  300)
* Python Enhancement Proposals; PEP 565: PEP 565 在 __main__ 中显示 DeprecationWarning.
                                                             (line   35)
* Python Enhancement Proposals; PEP 565 <1>: 警告.           (line   21)
* Python Enhancement Proposals; PEP 566: Using importlib metadata.
                                                             (line   24)
* Python Enhancement Proposals; PEP 566 <1>: Distributions.  (line   28)
* Python Enhancement Proposals; PEP 567: contextvars.        (line   17)
* Python Enhancement Proposals; PEP 567 <1>: asyncio<3>.     (line   17)
* Python Enhancement Proposals; PEP 567 <2>: 文档<25>.       (line   86)
* Python Enhancement Proposals; PEP 567 <3>: 文档<27>.       (line    9)
* Python Enhancement Proposals; PEP 567 <4>: 核心与内置函数<34>.
                                                             (line   63)
* Python Enhancement Proposals; PEP 567 <5>: contextvars --- 上下文变量.
                                                             (line   16)
* Python Enhancement Proposals; PEP 567 <6>: 安排回调.       (line   31)
* Python Enhancement Proposals; PEP 567 <7>: 调度延迟回调.   (line   28)
* Python Enhancement Proposals; PEP 567 <8>: 调度延迟回调.   (line   44)
* Python Enhancement Proposals; PEP 567 <9>: Future 对象<2>. (line   89)
* Python Enhancement Proposals; PEP 570: 仅限位置形参.       (line   61)
* Python Enhancement Proposals; PEP 570 <1>: 更改的Python API.
                                                             (line  136)
* Python Enhancement Proposals; PEP 570 <2>: 核心与内置函数<25>.
                                                             (line   36)
* Python Enhancement Proposals; PEP 570 <3>: 函数定义.       (line   76)
* Python Enhancement Proposals; PEP 572: 赋值表达式.         (line   36)
* Python Enhancement Proposals; PEP 572 <1>: CPython 字节码的改变<2>.
                                                             (line   23)
* Python Enhancement Proposals; PEP 572 <2>: 文档<16>.       (line    6)
* Python Enhancement Proposals; PEP 572 <3>: 核心与内置函数<23>.
                                                             (line  181)
* Python Enhancement Proposals; PEP 572 <4>: 核心与内置函数<28>.
                                                             (line   90)
* Python Enhancement Proposals; PEP 572 <5>: 字典显示.       (line   35)
* Python Enhancement Proposals; PEP 572 <6>: 赋值表达式<2>.  (line   22)
* Python Enhancement Proposals; PEP 572 <7>: 为什么不能在表达式中赋值？.
                                                             (line   13)
* Python Enhancement Proposals; PEP 573: 摘要 - 发布重点.    (line   26)
* Python Enhancement Proposals; PEP 573 <1>: 新的特性<2>.    (line    6)
* Python Enhancement Proposals; PEP 573 <2>: 核心与内置函数<17>.
                                                             (line   19)
* Python Enhancement Proposals; PEP 573 <3>: C API<10>.      (line   57)
* Python Enhancement Proposals; PEP 574: 具有外部数据缓冲区的 pickle 协议 5.
                                                             (line   13)
* Python Enhancement Proposals; PEP 574 <1>: 数据流格式.     (line   37)
* Python Enhancement Proposals; PEP 574 <2>: 示例<7>.        (line   60)
* Python Enhancement Proposals; PEP 578: PEP 578 Python 运行时审核钩子.
                                                             (line   10)
* Python Enhancement Proposals; PEP 578 <1>: 审计事件表.     (line    8)
* Python Enhancement Proposals; PEP 578 <2>: sys --- 系统相关的参数和函数.
                                                             (line   38)
* Python Enhancement Proposals; PEP 578 <3>: 系統函式.       (line  150)
* Python Enhancement Proposals; PEP 584: 摘要 - 发布重点.    (line    8)
* Python Enhancement Proposals; PEP 584 <1>: 字典合并与更新运算符.
                                                             (line   18)
* Python Enhancement Proposals; PEP 584 <2>: 库<20>.         (line  192)
* Python Enhancement Proposals; PEP 584 <3>: 库<20>.         (line  195)
* Python Enhancement Proposals; PEP 584 <4>: 库<20>.         (line  209)
* Python Enhancement Proposals; PEP 584 <5>: 库<21>.         (line   49)
* Python Enhancement Proposals; PEP 584 <6>: 库<21>.         (line   62)
* Python Enhancement Proposals; PEP 584 <7>: 库<21>.         (line  120)
* Python Enhancement Proposals; PEP 584 <8>: 库<21>.         (line  142)
* Python Enhancement Proposals; PEP 584 <9>: ChainMap objects.
                                                             (line   72)
* Python Enhancement Proposals; PEP 584 <10>: defaultdict 对象.
                                                             (line   48)
* Python Enhancement Proposals; PEP 584 <11>: OrderedDict 对象.
                                                             (line   76)
* Python Enhancement Proposals; PEP 584 <12>: weakref --- 弱引用.
                                                             (line  130)
* Python Enhancement Proposals; PEP 584 <13>: weakref --- 弱引用.
                                                             (line  147)
* Python Enhancement Proposals; PEP 584 <14>: 标准解释器类型.
                                                             (line  218)
* Python Enhancement Proposals; PEP 584 <15>: 进程参数.      (line   42)
* Python Enhancement Proposals; PEP 584 <16>: 进程参数.      (line   58)
* Python Enhancement Proposals; PEP 585: 摘要 - 发布重点.    (line   10)
* Python Enhancement Proposals; PEP 585 <1>: 标准多项集中的类型标注泛型.
                                                             (line   16)
* Python Enhancement Proposals; PEP 585 <2>: 文档<4>.        (line   25)
* Python Enhancement Proposals; PEP 585 <3>: 泛型的特殊属性. (line   37)
* Python Enhancement Proposals; PEP 585 <4>: collections abc --- 容器的抽象基类.
                                                             (line   16)
* Python Enhancement Proposals; PEP 585 <5>: Relevant PEPs.  (line   23)
* Python Enhancement Proposals; PEP 585 <6>: 模块内容<7>.    (line   16)
* Python Enhancement Proposals; PEP 585 <7>: 特殊形式.       (line   20)
* Python Enhancement Proposals; PEP 585 <8>: 特殊形式.       (line   87)
* Python Enhancement Proposals; PEP 585 <9>: 特殊形式.       (line  125)
* Python Enhancement Proposals; PEP 585 <10>: 对应的内置类型.
                                                             (line   16)
* Python Enhancement Proposals; PEP 585 <11>: 对应的内置类型.
                                                             (line   34)
* Python Enhancement Proposals; PEP 585 <12>: 对应的内置类型.
                                                             (line   42)
* Python Enhancement Proposals; PEP 585 <13>: 对应的内置类型.
                                                             (line   49)
* Python Enhancement Proposals; PEP 585 <14>: collections 对应类型.
                                                             (line   14)
* Python Enhancement Proposals; PEP 585 <15>: collections 对应类型.
                                                             (line   24)
* Python Enhancement Proposals; PEP 585 <16>: collections 对应类型.
                                                             (line   35)
* Python Enhancement Proposals; PEP 585 <17>: collections 对应类型.
                                                             (line   46)
* Python Enhancement Proposals; PEP 585 <18>: collections 对应类型.
                                                             (line   56)
* Python Enhancement Proposals; PEP 585 <19>: 其他具象类型.  (line   31)
* Python Enhancement Proposals; PEP 585 <20>: collections abc 对应的容器.
                                                             (line   11)
* Python Enhancement Proposals; PEP 585 <21>: collections abc 对应的容器.
                                                             (line   23)
* Python Enhancement Proposals; PEP 585 <22>: collections abc 对应的容器.
                                                             (line   32)
* Python Enhancement Proposals; PEP 585 <23>: collections abc 对应的容器.
                                                             (line   39)
* Python Enhancement Proposals; PEP 585 <24>: collections abc 对应的容器.
                                                             (line   46)
* Python Enhancement Proposals; PEP 585 <25>: collections abc 对应的容器.
                                                             (line   53)
* Python Enhancement Proposals; PEP 585 <26>: collections abc 对应的容器.
                                                             (line   63)
* Python Enhancement Proposals; PEP 585 <27>: collections abc 对应的容器.
                                                             (line   70)
* Python Enhancement Proposals; PEP 585 <28>: collections abc 对应的容器.
                                                             (line   77)
* Python Enhancement Proposals; PEP 585 <29>: collections abc 对应的容器.
                                                             (line   84)
* Python Enhancement Proposals; PEP 585 <30>: collections abc 对应的容器.
                                                             (line   91)
* Python Enhancement Proposals; PEP 585 <31>: collections abc 对应的容器.
                                                             (line   98)
* Python Enhancement Proposals; PEP 585 <32>: collections abc 对应的容器.
                                                             (line  105)
* Python Enhancement Proposals; PEP 585 <33>: collections abc 对应的其他类型.
                                                             (line   11)
* Python Enhancement Proposals; PEP 585 <34>: collections abc 对应的其他类型.
                                                             (line   18)
* Python Enhancement Proposals; PEP 585 <35>: collections abc 对应的其他类型.
                                                             (line   51)
* Python Enhancement Proposals; PEP 585 <36>: collections abc 对应的其他类型.
                                                             (line   62)
* Python Enhancement Proposals; PEP 585 <37>: 异步编程.      (line   21)
* Python Enhancement Proposals; PEP 585 <38>: 异步编程.      (line   56)
* Python Enhancement Proposals; PEP 585 <39>: 异步编程.      (line   65)
* Python Enhancement Proposals; PEP 585 <40>: 异步编程.      (line   74)
* Python Enhancement Proposals; PEP 585 <41>: 异步编程.      (line   83)
* Python Enhancement Proposals; PEP 585 <42>: 上下文管理器类型<2>.
                                                             (line   15)
* Python Enhancement Proposals; PEP 585 <43>: 上下文管理器类型<2>.
                                                             (line   26)
* Python Enhancement Proposals; PEP 585 <44>: 内省辅助器.    (line   59)
* Python Enhancement Proposals; PEP 585 <45>: 術語表.        (line  491)
* Python Enhancement Proposals; PEP 586: typing<2>.          (line    6)
* Python Enhancement Proposals; PEP 586 <1>: typing<3>.      (line   17)
* Python Enhancement Proposals; PEP 586 <2>: Relevant PEPs.  (line   29)
* Python Enhancement Proposals; PEP 586 <3>: 特殊形式.       (line  145)
* Python Enhancement Proposals; PEP 587: PEP 587 Python 初始化配置.
                                                             (line    6)
* Python Enhancement Proposals; PEP 587 <1>: PEP 587 Python 初始化配置.
                                                             (line   80)
* Python Enhancement Proposals; PEP 587 <2>: 核心与内置函数<23>.
                                                             (line   75)
* Python Enhancement Proposals; PEP 587 <3>: C API<17>.      (line    6)
* Python Enhancement Proposals; PEP 587 <4>: Python初始化配置.
                                                             (line   83)
* Python Enhancement Proposals; PEP 589: typing<3>.          (line    8)
* Python Enhancement Proposals; PEP 589 <1>: Relevant PEPs.  (line   34)
* Python Enhancement Proposals; PEP 589 <2>: 其他特殊指令.   (line  108)
* Python Enhancement Proposals; PEP 590: 摘要 - 发布重点.    (line   31)
* Python Enhancement Proposals; PEP 590 <1>: 性能优化.       (line   31)
* Python Enhancement Proposals; PEP 590 <2>: PEP 590 Vectorcall 用于 CPython 的快速调用协议.
                                                             (line   12)
* Python Enhancement Proposals; PEP 590 <3>: 核心与内置函数<18>.
                                                             (line   39)
* Python Enhancement Proposals; PEP 590 <4>: 核心与内置函数<18>.
                                                             (line   91)
* Python Enhancement Proposals; PEP 590 <5>: 核心与内置函数<19>.
                                                             (line   42)
* Python Enhancement Proposals; PEP 590 <6>: 核心与内置函数<19>.
                                                             (line   50)
* Python Enhancement Proposals; PEP 590 <7>: 核心与内置函数<19>.
                                                             (line   67)
* Python Enhancement Proposals; PEP 590 <8>: C API<17>.      (line   17)
* Python Enhancement Proposals; PEP 590 <9>: Vectorcall 协议.
                                                             (line    8)
* Python Enhancement Proposals; PEP 591: typing<3>.          (line   23)
* Python Enhancement Proposals; PEP 591 <1>: Relevant PEPs.  (line   39)
* Python Enhancement Proposals; PEP 591 <2>: 特殊形式.       (line  191)
* Python Enhancement Proposals; PEP 591 <3>: 函数与装饰器.   (line   56)
* Python Enhancement Proposals; PEP 593: 摘要 - 发布重点.    (line   20)
* Python Enhancement Proposals; PEP 593 <1>: typing.         (line    6)
* Python Enhancement Proposals; PEP 593 <2>: 库<22>.         (line   91)
* Python Enhancement Proposals; PEP 593 <3>: Relevant PEPs.  (line   45)
* Python Enhancement Proposals; PEP 593 <4>: 特殊形式.       (line  197)
* Python Enhancement Proposals; PEP 593 <5>: 内省辅助器.     (line   30)
* Python Enhancement Proposals; PEP 596: Python 3 9 有什么新变化.
                                                             (line   23)
* Python Enhancement Proposals; PEP 6:   Python 版本的编号形式是怎样的？.
                                                             (line    8)
* Python Enhancement Proposals; PEP 602: 摘要 - 发布重点.    (line   54)
* Python Enhancement Proposals; PEP 602 <1>: Python穩定性如何.
                                                             (line    8)
* Python Enhancement Proposals; PEP 612: 核心与内置函数<9>.  (line   63)
* Python Enhancement Proposals; PEP 614: 摘要 - 发布重点.    (line   12)
* Python Enhancement Proposals; PEP 614 <1>: 其他语言特性修改.
                                                             (line   32)
* Python Enhancement Proposals; PEP 614 <2>: 核心与内置函数<19>.
                                                             (line  112)
* Python Enhancement Proposals; PEP 614 <3>: 函数定义.       (line   46)
* Python Enhancement Proposals; PEP 614 <4>: 类定义.         (line   49)
* Python Enhancement Proposals; PEP 615: 摘要 - 发布重点.    (line   47)
* Python Enhancement Proposals; PEP 615 <1>: zoneinfo.       (line   35)
* Python Enhancement Proposals; PEP 615 <2>: 库<19>.         (line   54)
* Python Enhancement Proposals; PEP 615 <3>: zoneinfo --- IANA 时区支持.
                                                             (line   10)
* Python Enhancement Proposals; PEP 616: 摘要 - 发布重点.    (line   16)
* Python Enhancement Proposals; PEP 616 <1>: 新增用于移除前缀和后缀的字符串方法.
                                                             (line    9)
* Python Enhancement Proposals; PEP 616 <2>: 核心与内置函数<18>.
                                                             (line   82)
* Python Enhancement Proposals; PEP 617: 摘要 - 发布重点.    (line   28)
* Python Enhancement Proposals; PEP 617 <1>: 新的解析器.     (line   17)
* Python Enhancement Proposals; PEP 617 <2>: 弃用.           (line   83)
* Python Enhancement Proposals; PEP 617 <3>: 库<20>.         (line   35)
* Python Enhancement Proposals; PEP 617 <4>: 其他选项.       (line  178)
* Python Enhancement Proposals; PEP 617 <5>: 环境变量.       (line   80)
* Python Enhancement Proposals; PEP 617 <6>: lib2to3 —— 2to3 支持库.
                                                             (line   10)
* Python Enhancement Proposals; PEP 617 <7>: PyConfig.       (line  401)
* Python Enhancement Proposals; PEP 623: 文档<8>.            (line   19)
* Python Enhancement Proposals; PEP 623 <1>: Unicode对象.    (line   31)
* Python Enhancement Proposals; PEP 628: cmath.              (line    7)
* Python Enhancement Proposals; PEP 628 <1>: math<4>.        (line    7)
* Python Enhancement Proposals; PEP 628 <2>: 库<55>.         (line   32)
* Python Enhancement Proposals; PEP 7:   构建和 C API 的改变<2>.
                                                             (line    9)
* Python Enhancement Proposals; PEP 7 <1>: 代码标准.         (line    6)
* Python Enhancement Proposals; PEP 7 <2>: 有用的宏.         (line   93)
* Python Enhancement Proposals; PEP 7 <3>: 有用的宏.         (line  111)
* Python Enhancement Proposals; PEP 8:   Library Changes.    (line   26)
* Python Enhancement Proposals; PEP 8 <1>: 库<39>.           (line  125)
* Python Enhancement Proposals; PEP 8 <2>: IDLE<50>.         (line   81)
* Python Enhancement Proposals; PEP 8 <3>: 間奏曲：程式碼風格 Coding Style.
                                                             (line   11)
* Python Enhancement Proposals; PEP 8 <4>: 编辑器和集成开发环境.
                                                             (line    7)
* Python Enhancement Proposals; PEP 8 <5>: 值比较.           (line   46)
* Python Enhancement Proposals; PEP 8 <6>: 內建函式.         (line 1312)
* Python Enhancement Proposals; PEP 8 <7>: Using real Argument Clinic converters instead of "legacy converters".
                                                             (line   50)
* Python Enhancement Proposals; PEP 8 <8>: 是否有 Python 编码标准或风格指南？.
                                                             (line    6)
* Python Enhancement Proposals; PEP 8 <9>: 什么情况下可以依靠 is 运算符进行对象的身份相等性测试？.
                                                             (line   49)
* Python Enhancement Proposals; PEP 8 <10>: 如何让编辑器不要在我的 Python 源代码中插入 tab ？.
                                                             (line    6)
* Python Package Index (PyPI):           安裝工具.           (line   23)
* PYTHON*:                               其他改进<2>.        (line    9)
* PYTHON* <1>:                           接口选项.           (line   65)
* PYTHON* <2>:                           接口选项.           (line  118)
* PYTHON* <3>:                           其他选项.           (line   37)
* PYTHON* <4>:                           其他选项.           (line   53)
* PYTHON* <5>:                           全局配置变量.       (line   54)
* PYTHONASYNCIODEBUG:                    开启调试模式.       (line   10)
* PYTHONASYNCIODEBUG <1>:                Debug 模式.         (line   11)
* PYTHONASYNCIODEBUG <2>:                Python 开发模式的效果.
                                                             (line   57)
* PYTHONBREAKPOINT:                      PEP 553 内置的 breakpoint.
                                                             (line   12)
* PYTHONBREAKPOINT <1>:                  sys --- 系统相关的参数和函数.
                                                             (line  165)
* PYTHONBREAKPOINT <2>:                  sys --- 系统相关的参数和函数.
                                                             (line  175)
* PYTHONBREAKPOINT <3>:                  sys --- 系统相关的参数和函数.
                                                             (line  179)
* PYTHONCASEOK:                          Python API 的变化.  (line   28)
* PYTHONCASEOK <1>:                      PEP 235 Importing Modules on Case-Insensitive Platforms.
                                                             (line   17)
* PYTHONCASEOK <2>:                      库<21>.             (line  144)
* PYTHONCASEOK <3>:                      內建函式.           (line 1581)
* PYTHONCOERCECLOCALE:                   PEP 538 传统 C 区域强制转换.
                                                             (line   11)
* PYTHONCOERCECLOCALE <1>:               环境变量.           (line  393)
* PYTHONCOERCECLOCALE <2>:               Python Configuration.
                                                             (line   15)
* PYTHONDEBUG:                           其他选项.           (line   32)
* PYTHONDEBUG <1>:                       全局配置变量.       (line   26)
* PYTHONDEVMODE:                         Python 开发模式 -X dev.
                                                             (line    6)
* PYTHONDEVMODE <1>:                     Python 开发模式.    (line   12)
* PYTHONDOCS:                            pydoc --- 文档生成器和在线帮助系统.
                                                             (line   66)
* PYTHONDONTWRITEBYTECODE:               Interpreter Changes<2>.
                                                             (line   16)
* PYTHONDONTWRITEBYTECODE <1>:           新增和改进的模块<2>.
                                                             (line  624)
* PYTHONDONTWRITEBYTECODE <2>:           其他选项.           (line   16)
* PYTHONDONTWRITEBYTECODE <3>:           sys --- 系统相关的参数和函数.
                                                             (line  240)
* PYTHONDONTWRITEBYTECODE <4>:           全局配置变量.       (line   34)
* PYTHONDONTWRITEBYTECODE <5>:           如何创建 pyc 文件？.
                                                             (line   19)
* PYTHONDUMPREFS:                        调试构建使用与发布构建相同的 ABI.
                                                             (line   12)
* PYTHONDUMPREFS <1>:                    构建<21>.           (line   54)
* PYTHONDUMPREFS <2>:                    PyObject Slots.     (line   22)
* PYTHONFAULTHANDLER:                    faulthandler<3>.    (line   11)
* PYTHONFAULTHANDLER <1>:                Python 开发模式的效果.
                                                             (line   51)
* PYTHONFAULTHANDLER <2>:                faulthandler —— 转储 Python 的跟踪信息.
                                                             (line   12)
* PYTHONHASHSEED:                        Builtin functions and types.
                                                             (line   17)
* PYTHONHASHSEED <1>:                    Porting Python code.
                                                             (line    6)
* PYTHONHASHSEED <2>:                    核心与内置函数<35>. (line   30)
* PYTHONHASHSEED <3>:                    其他选项.           (line   83)
* PYTHONHASHSEED <4>:                    其他选项.           (line   97)
* PYTHONHASHSEED <5>:                    环境变量.           (line  125)
* PYTHONHASHSEED <6>:                    基本定制.           (line  241)
* PYTHONHASHSEED <7>:                    全局配置变量.       (line   46)
* PYTHONHASHSEED <8>:                    全局配置变量.       (line   49)
* PYTHONHOME:                            摘要 - 发布重点<4>. (line   90)
* PYTHONHOME <1>:                        其他选项.           (line   38)
* PYTHONHOME <2>:                        环境变量.           (line   16)
* PYTHONHOME <3>:                        环境变量.           (line   17)
* PYTHONHOME <4>:                        环境变量.           (line   31)
* PYTHONHOME <5>:                        查找模块.           (line   38)
* PYTHONHOME <6>:                        查找模块.           (line   52)
* PYTHONHOME <7>:                        查找模块.           (line   80)
* PYTHONHOME <8>:                        test support script_helper --- Utilities for the Python execution tests.
                                                             (line   24)
* PYTHONHOME <9>:                        嵌入式Python.       (line   38)
* PYTHONHOME <10>:                       嵌入式Python.       (line   44)
* PYTHONHOME <11>:                       全局配置变量.       (line   55)
* PYTHONHOME <12>:                       Process-wide parameters.
                                                             (line  269)
* PYTHONHOME <13>:                       Process-wide parameters.
                                                             (line  283)
* PYTHONHOME <14>:                       PyConfig.           (line  204)
* PYTHONHOME <15>:                       Modifying Python's Search Path.
                                                             (line   60)
* PYTHONHOME <16>:                       Modifying Python's Search Path.
                                                             (line   62)
* Pythonic（Python 風格的）:             術語表.             (line  960)
* PYTHONINSPECT:                         Other Changes and Fixes<2>.
                                                             (line   13)
* PYTHONINSPECT <1>:                     其他选项.           (line   46)
* PYTHONINSPECT <2>:                     全局配置变量.       (line   66)
* PYTHONIOENCODING:                      其他改进<2>.        (line   75)
* PYTHONIOENCODING <1>:                  Interpreter Changes<2>.
                                                             (line   23)
* PYTHONIOENCODING <2>:                  环境变量.           (line  327)
* PYTHONIOENCODING <3>:                  环境变量.           (line  385)
* PYTHONIOENCODING <4>:                  sys --- 系统相关的参数和函数.
                                                             (line 1272)
* PYTHONIOENCODING <5>:                  Process-wide parameters.
                                                             (line   14)
* PYTHONIOENCODING <6>:                  Process-wide parameters.
                                                             (line   18)
* PYTHONLEGACYWINDOWSFSENCODING:         PEP 529 将Windows文件系统编码更改为UTF-8.
                                                             (line   18)
* PYTHONLEGACYWINDOWSFSENCODING <1>:     sys --- 系统相关的参数和函数.
                                                             (line 1234)
* PYTHONLEGACYWINDOWSFSENCODING <2>:     全局配置变量.       (line   88)
* PYTHONLEGACYWINDOWSSTDIO:              PEP 528 将Windows控制台编码更改为UTF-8.
                                                             (line   12)
* PYTHONLEGACYWINDOWSSTDIO <1>:          环境变量.           (line  149)
* PYTHONLEGACYWINDOWSSTDIO <2>:          sys --- 系统相关的参数和函数.
                                                             (line 1275)
* PYTHONLEGACYWINDOWSSTDIO <3>:          全局配置变量.       (line  100)
* PYTHONMALLOC:                          PYTHONMALLOC 环境变量.
                                                             (line    6)
* PYTHONMALLOC <1>:                      C API 中的改变<3>.  (line    9)
* PYTHONMALLOC <2>:                      核心与内置函数<55>. (line   91)
* PYTHONMALLOC <3>:                      环境变量.           (line  267)
* PYTHONMALLOC <4>:                      Python 开发模式的效果.
                                                             (line   42)
* PYTHONMALLOC <5>:                      Python 开发模式的效果.
                                                             (line   45)
* PYTHONMALLOC <6>:                      總覽<2>.            (line   54)
* PYTHONMALLOC <7>:                      默认内存分配器.     (line   26)
* PYTHONMALLOC <8>:                      自定义内存分配器.   (line  121)
* PYTHONMALLOCSTATS:                     核心与内置函数<55>. (line   97)
* PYTHONMALLOCSTATS <1>:                 總覽<2>.            (line   57)
* PYTHONNOUSERSITE:                      PEP 370 分用户的 site-packages 目录.
                                                             (line   30)
* PYTHONNOUSERSITE <1>:                  模块内容<8>.        (line   14)
* PYTHONNOUSERSITE <2>:                  全局配置变量.       (line  120)
* PYTHONOLDPARSER:                       其他选项.           (line  177)
* PYTHONOLDPARSER <1>:                   PyConfig.           (line  398)
* PYTHONOPTIMIZE:                        其他选项.           (line   62)
* PYTHONOPTIMIZE <1>:                    全局配置变量.       (line  125)
* PYTHONPATH:                            'python' 命令行为的变化<2>.
                                                             (line    8)
* PYTHONPATH <1>:                        'python' 命令行为的变化<2>.
                                                             (line    9)
* PYTHONPATH <2>:                        模組的搜尋路徑.     (line   13)
* PYTHONPATH <3>:                        標準模組.           (line   27)
* PYTHONPATH <4>:                        標準模組.           (line   27)
* PYTHONPATH <5>:                        其他选项.           (line   37)
* PYTHONPATH <6>:                        环境变量.           (line   26)
* PYTHONPATH <7>:                        环境变量.           (line   32)
* PYTHONPATH <8>:                        环境变量.           (line   34)
* PYTHONPATH <9>:                        附录：设置环境变量. (line   30)
* PYTHONPATH <10>:                       查找模块.           (line   27)
* PYTHONPATH <11>:                       查找模块.           (line   45)
* PYTHONPATH <12>:                       查找模块.           (line   79)
* PYTHONPATH <13>:                       設定.               (line    6)
* PYTHONPATH <14>:                       路径条目查找器.     (line    6)
* PYTHONPATH <15>:                       在 Unix 系统上安装你的 CGI 脚本.
                                                             (line   23)
* PYTHONPATH <16>:                       test support script_helper --- Utilities for the Python execution tests.
                                                             (line   25)
* PYTHONPATH <17>:                       sys --- 系统相关的参数和函数.
                                                             (line  897)
* PYTHONPATH <18>:                       sys --- 系统相关的参数和函数.
                                                             (line  903)
* PYTHONPATH <19>:                       构建C/C++扩展.      (line    9)
* PYTHONPATH <20>:                       嵌入式Python.       (line   39)
* PYTHONPATH <21>:                       嵌入式Python.       (line   44)
* PYTHONPATH <22>:                       全局配置变量.       (line   54)
* PYTHONPATH <23>:                       PyConfig.           (line  259)
* PYTHONPATH <24>:                       Modifying Python's Search Path.
                                                             (line   67)
* PYTHONPATH <25>:                       Modifying Python's Search Path.
                                                             (line   68)
* PYTHONPLATLIBDIR:                      核心与内置函数<16>. (line   25)
* PYTHONPROFILEIMPORTTIME:               其他语言特性修改<3>.
                                                             (line   44)
* PYTHONPROFILEIMPORTTIME <1>:           核心与内置函数<37>. (line   67)
* PYTHONPROFILEIMPORTTIME <2>:           其他选项.           (line  192)
* PYTHONPYCACHEPREFIX:                   用于已编译字节码文件的并行文件系统缓存.
                                                             (line    6)
* PYTHONPYCACHEPREFIX <1>:               核心与内置函数<28>. (line  396)
* PYTHONPYCACHEPREFIX <2>:               其他选项.           (line  203)
* PYTHONPYCACHEPREFIX <3>:               sys --- 系统相关的参数和函数.
                                                             (line  255)
* PYTHONSHOWALLOCCOUNT:                  Two new environment variables for debug mode.
                                                             (line   11)
* PYTHONSHOWREFCOUNT:                    Two new environment variables for debug mode.
                                                             (line    7)
* PYTHONSTARTUP:                         sys<7>.             (line   17)
* PYTHONSTARTUP <1>:                     sys<7>.             (line   21)
* PYTHONSTARTUP <2>:                     IDLE<24>.           (line  174)
* PYTHONSTARTUP <3>:                     IDLE<28>.           (line    9)
* PYTHONSTARTUP <4>:                     IDLE<34>.           (line    9)
* PYTHONSTARTUP <5>:                     互動式啟動檔案.     (line    7)
* PYTHONSTARTUP <6>:                     其他选项.           (line   43)
* PYTHONSTARTUP <7>:                     示例<2>.            (line    8)
* PYTHONSTARTUP <8>:                     启动和代码执行.     (line    7)
* PYTHONSTARTUP <9>:                     sys --- 系统相关的参数和函数.
                                                             (line  811)
* PYTHONSTARTUP <10>:                    Readline 配置.      (line   10)
* PYTHONTRACEMALLOC:                     tracemalloc --- 跟踪内存分配.
                                                             (line   25)
* PYTHONTRACEMALLOC <1>:                 tracemalloc --- 跟踪内存分配.
                                                             (line   32)
* PYTHONTRACEMALLOC <2>:                 函数<10>.           (line   90)
* PYTHONTZPATH:                          异常与警告.         (line   13)
* PYTHONUNBUFFERED:                      核心与内置函数<21>. (line  107)
* PYTHONUNBUFFERED <1>:                  其他选项.           (line  123)
* PYTHONUNBUFFERED <2>:                  sys --- 系统相关的参数和函数.
                                                             (line 1280)
* PYTHONUNBUFFERED <3>:                  全局配置变量.       (line  140)
* PYTHONUSERBASE:                        PEP 370 分用户的 site-packages 目录.
                                                             (line   23)
* PYTHONUSERBASE <1>:                    模块内容<8>.        (line   38)
* PYTHONUSERBASE <2>:                    模块内容<8>.        (line   61)
* PYTHONUSERSITE:                        test support script_helper --- Utilities for the Python execution tests.
                                                             (line   25)
* PYTHONUTF8:                            PEP 540 强制 UTF-8 运行时模式.
                                                             (line    6)
* PYTHONUTF8 <1>:                        其他选项.           (line  200)
* PYTHONUTF8 <2>:                        环境变量.           (line  335)
* PYTHONUTF8 <3>:                        UTF-8 模式.         (line   16)
* PYTHONUTF8 <4>:                        sys --- 系统相关的参数和函数.
                                                             (line 1274)
* PYTHONUTF8 <5>:                        Python Configuration.
                                                             (line   14)
* PYTHONVERBOSE:                         其他选项.           (line  131)
* PYTHONVERBOSE <1>:                     全局配置变量.       (line  151)
* PYTHONWARNINGS:                        warnings.           (line   18)
* PYTHONWARNINGS <1>:                    其他语言特性修改<8>.
                                                             (line  158)
* PYTHONWARNINGS <2>:                    Changes to the Handling of Deprecation Warnings.
                                                             (line   25)
* PYTHONWARNINGS <3>:                    Interpreter Changes.
                                                             (line    6)
* PYTHONWARNINGS <4>:                    其他选项.           (line  147)
* PYTHONWARNINGS <5>:                    Python 开发模式的效果.
                                                             (line   27)
* PYTHONWARNINGS <6>:                    警告过滤器的介绍.   (line    6)
* PYTHONWARNINGS <7>:                    警告过滤器的介绍.   (line   17)
* PYTHONWARNINGS <8>:                    默认警告过滤器.     (line    6)
* python_branch() (於 platform 模組中):  跨平台.             (line   75)
* python_build() (於 platform 模組中):   跨平台.             (line   66)
* python_compiler() (於 platform 模組中): 跨平台.            (line   71)
* PYTHON_DOM:                            模块内容<6>.        (line   19)
* python_implementation() (於 platform 模組中): 跨平台.      (line   79)
* python_is_optimized() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  263)
* python_revision() (於 platform 模組中): 跨平台.            (line   84)
* python_version() (於 platform 模組中): 跨平台.             (line   88)
* python_version_tuple() (於 platform 模組中): 跨平台.       (line   95)
* PyThreadState:                         Thread State and the Global Interpreter Lock.
                                                             (line   23)
* PyThreadState <1>:                     Thread State and the Global Interpreter Lock.
                                                             (line   23)
* PyThreadState (C 型態):                高阶 API.           (line   21)
* PyThreadState_Clear (C 函式):          Low-level API.      (line   42)
* PyThreadState_Delete (C 函式):         Low-level API.      (line   51)
* PyThreadState_DeleteCurrent (C 函式):  Low-level API.      (line   57)
* PyThreadState_Get (C 函式):            高阶 API.           (line   77)
* PyThreadState_GetDict (C 函式):        Low-level API.      (line  163)
* PyThreadState_GetFrame (C 函式):       Low-level API.      (line   64)
* PyThreadState_GetID (C 函式):          Low-level API.      (line   78)
* PyThreadState_GetInterpreter (C 函式): Low-level API.      (line   87)
* PyThreadState_New (C 函式):            Low-level API.      (line   35)
* PyThreadState_Next (C 函式):           高级调试器支持.     (line   32)
* PyThreadState_SetAsyncExc (C 函式):    Low-level API.      (line  172)
* PyThreadState_Swap (C 函式):           高阶 API.           (line   83)
* PyThread_create_key (C 函式):          Thread Local Storage TLS API.
                                                             (line   17)
* PyThread_delete_key (C 函式):          Thread Local Storage TLS API.
                                                             (line   19)
* PyThread_delete_key_value (C 函式):    Thread Local Storage TLS API.
                                                             (line   25)
* PyThread_get_key_value (C 函式):       Thread Local Storage TLS API.
                                                             (line   23)
* PyThread_ReInitTLS (C 函式):           Thread Local Storage TLS API.
                                                             (line   27)
* PyThread_set_key_value (C 函式):       Thread Local Storage TLS API.
                                                             (line   21)
* PyThread_tss_alloc (C 函式):           Dynamic Allocation. (line   11)
* PyThread_tss_create (C 函式):          方法<4>.            (line   16)
* PyThread_tss_delete (C 函式):          方法<4>.            (line   24)
* PyThread_tss_free (C 函式):            Dynamic Allocation. (line   17)
* PyThread_tss_get (C 函式):             方法<4>.            (line   39)
* PyThread_tss_is_created (C 函式):      方法<4>.            (line   11)
* PyThread_tss_set (C 函式):             方法<4>.            (line   33)
* PyTimeZone_FromOffset (C 函式):        DateTime 物件.      (line  115)
* PyTimeZone_FromOffsetAndName (C 函式): DateTime 物件.      (line  122)
* PyTime_Check (C 函式):                 DateTime 物件.      (line   44)
* PyTime_CheckExact (C 函式):            DateTime 物件.      (line   49)
* PyTime_FromTime (C 函式):              DateTime 物件.      (line   97)
* PyTime_FromTimeAndFold (C 函式):       DateTime 物件.      (line  102)
* PyTraceMalloc_Track (C 函式):          tracemalloc C API.  (line    8)
* PyTraceMalloc_Untrack (C 函式):        tracemalloc C API.  (line   18)
* PyTrace_CALL (C 變數):                 分析和跟踪.         (line   61)
* PyTrace_C_CALL (C 變數):               分析和跟踪.         (line   93)
* PyTrace_C_EXCEPTION (C 變數):          分析和跟踪.         (line   98)
* PyTrace_C_RETURN (C 變數):             分析和跟踪.         (line  103)
* PyTrace_EXCEPTION (C 變數):            分析和跟踪.         (line   69)
* PyTrace_LINE (C 變數):                 分析和跟踪.         (line   81)
* PyTrace_OPCODE (C 變數):               分析和跟踪.         (line  108)
* PyTrace_RETURN (C 變數):               分析和跟踪.         (line   88)
* PyTupleObject (C 型態):                元組（Tuple）物件.  (line    6)
* PyTuple_Check (C 函式):                元組（Tuple）物件.  (line   15)
* PyTuple_CheckExact (C 函式):           元組（Tuple）物件.  (line   20)
* PyTuple_GetItem (C 函式):              元組（Tuple）物件.  (line   44)
* PyTuple_GetSlice (C 函式):             元組（Tuple）物件.  (line   53)
* PyTuple_GET_ITEM (C 函式):             元組（Tuple）物件.  (line   49)
* PyTuple_GET_SIZE (C 函式):             元組（Tuple）物件.  (line   39)
* PyTuple_New (C 函式):                  元組（Tuple）物件.  (line   25)
* PyTuple_Pack (C 函式):                 元組（Tuple）物件.  (line   29)
* PyTuple_SetItem (C 函式):              元組（Tuple）物件.  (line   60)
* PyTuple_SetItem():                     引用计数细节.       (line   26)
* PyTuple_SET_ITEM (C 函式):             元組（Tuple）物件.  (line   70)
* PyTuple_Size (C 函式):                 元組（Tuple）物件.  (line   35)
* PyTuple_Type (C 變數):                 元組（Tuple）物件.  (line   10)
* PyTypeObject (C 型態):                 Type 对象.          (line    6)
* PyTypeObject.tp_alloc (C 成員函數):    PyTypeObject Slots. (line 1174)
* PyTypeObject.tp_as_async (C 成員函數): PyTypeObject Slots. (line  234)
* PyTypeObject.tp_as_buffer (C 成員函數): PyTypeObject Slots.
                                                             (line  434)
* PyTypeObject.tp_as_mapping (C 成員函數): PyTypeObject Slots.
                                                             (line  296)
* PyTypeObject.tp_as_number (C 成員函數): PyTypeObject Slots.
                                                             (line  274)
* PyTypeObject.tp_as_sequence (C 成員函數): PyTypeObject Slots.
                                                             (line  285)
* PyTypeObject.tp_base (C 成員函數):     PyTypeObject Slots. (line  987)
* PyTypeObject.tp_bases (C 成員函數):    PyTypeObject Slots. (line 1286)
* PyTypeObject.tp_basicsize (C 成員函數): PyTypeObject Slots.
                                                             (line   47)
* PyTypeObject.tp_cache (C 成員函數):    PyTypeObject Slots. (line 1308)
* PyTypeObject.tp_call (C 成員函數):     PyTypeObject Slots. (line  344)
* PyTypeObject.tp_clear (C 成員函數):    PyTypeObject Slots. (line  719)
* PyTypeObject.tp_dealloc (C 成員函數):  PyTypeObject Slots. (line   99)
* PyTypeObject.tp_del (C 成員函數):      PyTypeObject Slots. (line 1333)
* PyTypeObject.tp_descr_get (C 成員函數): PyTypeObject Slots.
                                                             (line 1044)
* PyTypeObject.tp_descr_set (C 成員函數): PyTypeObject Slots.
                                                             (line 1056)
* PyTypeObject.tp_dict (C 成員函數):     PyTypeObject Slots. (line 1019)
* PyTypeObject.tp_dictoffset (C 成員函數): PyTypeObject Slots.
                                                             (line 1071)
* PyTypeObject.tp_doc (C 成員函數):      PyTypeObject Slots. (line  635)
* PyTypeObject.tp_finalize (C 成員函數): PyTypeObject Slots. (line 1345)
* PyTypeObject.tp_flags (C 成員函數):    PyTypeObject Slots. (line  445)
* PyTypeObject.tp_free (C 成員函數):     PyTypeObject Slots. (line 1234)
* PyTypeObject.tp_getattr (C 成員函數):  PyTypeObject Slots. (line  195)
* PyTypeObject.tp_getattro (C 成員函數): PyTypeObject Slots. (line  382)
* PyTypeObject.tp_getset (C 成員函數):   PyTypeObject Slots. (line  972)
* PyTypeObject.tp_hash (C 成員函數):     PyTypeObject Slots. (line  307)
* PyTypeObject.tp_init (C 成員函數):     PyTypeObject Slots. (line 1137)
* PyTypeObject.tp_is_gc (C 成員函數):    PyTypeObject Slots. (line 1257)
* PyTypeObject.tp_itemsize (C 成員函數): PyTypeObject Slots. (line   47)
* PyTypeObject.tp_iter (C 成員函數):     PyTypeObject Slots. (line  904)
* PyTypeObject.tp_iternext (C 成員函數): PyTypeObject Slots. (line  920)
* PyTypeObject.tp_members (C 成員函數):  PyTypeObject Slots. (line  957)
* PyTypeObject.tp_methods (C 成員函數):  PyTypeObject Slots. (line  942)
* PyTypeObject.tp_mro (C 成員函數):      PyTypeObject Slots. (line 1297)
* PyTypeObject.tp_name (C 成員函數):     PyTypeObject Slots. (line   12)
* PyTypeObject.tp_new (C 成員函數):      PyTypeObject Slots. (line 1197)
* PyTypeObject.tp_repr (C 成員函數):     PyTypeObject Slots. (line  248)
* PyTypeObject.tp_richcompare (C 成員函數): PyTypeObject Slots.
                                                             (line  794)
* PyTypeObject.tp_setattr (C 成員函數):  PyTypeObject Slots. (line  214)
* PyTypeObject.tp_setattro (C 成員函數): PyTypeObject Slots. (line  407)
* PyTypeObject.tp_str (C 成員函數):      PyTypeObject Slots. (line  356)
* PyTypeObject.tp_subclasses (C 成員函數): PyTypeObject Slots.
                                                             (line 1316)
* PyTypeObject.tp_traverse (C 成員函數): PyTypeObject Slots. (line  645)
* PyTypeObject.tp_vectorcall (C 成員函數): PyTypeObject Slots.
                                                             (line 1392)
* PyTypeObject.tp_vectorcall_offset (C 成員函數): PyTypeObject Slots.
                                                             (line  152)
* PyTypeObject.tp_version_tag (C 成員函數): PyTypeObject Slots.
                                                             (line 1337)
* PyTypeObject.tp_weaklist (C 成員函數): PyTypeObject Slots. (line 1324)
* PyTypeObject.tp_weaklistoffset (C 成員函數): PyTypeObject Slots.
                                                             (line  868)
* PyType_Check (C 函式):                 Type 对象.          (line   15)
* PyType_CheckExact (C 函式):            Type 对象.          (line   21)
* PyType_ClearCache (C 函式):            Type 对象.          (line   27)
* PyType_FromModuleAndSpec (C 函式):     Creating Heap-Allocated Types.
                                                             (line    9)
* PyType_FromSpec (C 函式):              Creating Heap-Allocated Types.
                                                             (line   41)
* PyType_FromSpecWithBases (C 函式):     Creating Heap-Allocated Types.
                                                             (line   33)
* PyType_GenericAlloc (C 函式):          Type 对象.          (line   69)
* PyType_GenericNew (C 函式):            Type 对象.          (line   77)
* PyType_GetFlags (C 函式):              Type 对象.          (line   31)
* PyType_GetModule (C 函式):             Type 对象.          (line  113)
* PyType_GetModuleState (C 函式):        Type 对象.          (line  131)
* PyType_GetSlot (C 函式):               Type 对象.          (line   99)
* PyType_HasFeature (C 函式):            Type 对象.          (line   50)
* PyType_IsSubtype (C 函式):             Type 对象.          (line   60)
* PyType_IS_GC (C 函式):                 Type 对象.          (line   55)
* PyType_Modified (C 函式):              Type 对象.          (line   44)
* PyType_Ready (C 函式):                 Type 对象.          (line   83)
* PyType_Slot (C 型態):                  Creating Heap-Allocated Types.
                                                             (line   74)
* PyType_Slot.PyType_Slot.pfunc (C 成員函數): Creating Heap-Allocated Types.
                                                             (line  137)
* PyType_Slot.PyType_Slot.slot (C 成員函數): Creating Heap-Allocated Types.
                                                             (line   79)
* PyType_Spec (C 型態):                  Creating Heap-Allocated Types.
                                                             (line   45)
* PyType_Spec.PyType_Spec.basicsize (C 成員函數): Creating Heap-Allocated Types.
                                                             (line   54)
* PyType_Spec.PyType_Spec.flags (C 成員函數): Creating Heap-Allocated Types.
                                                             (line   62)
* PyType_Spec.PyType_Spec.itemsize (C 成員函數): Creating Heap-Allocated Types.
                                                             (line   56)
* PyType_Spec.PyType_Spec.name (C 成員函數): Creating Heap-Allocated Types.
                                                             (line   49)
* PyType_Spec.PyType_Spec.slots (C 成員函數): Creating Heap-Allocated Types.
                                                             (line   69)
* PyType_Type (C 變數):                  Type 对象.          (line   10)
* PyTZInfo_Check (C 函式):               DateTime 物件.      (line   64)
* PyTZInfo_CheckExact (C 函式):          DateTime 物件.      (line   70)
* PyUnicodeDecodeError_Create (C 函式):  Unicode 异常对象.   (line    9)
* PyUnicodeDecodeError_GetEncoding (C 函式): Unicode 异常对象.
                                                             (line   45)
* PyUnicodeDecodeError_GetEnd (C 函式):  Unicode 异常对象.   (line   81)
* PyUnicodeDecodeError_GetObject (C 函式): Unicode 异常对象. (line   49)
* PyUnicodeDecodeError_GetReason (C 函式): Unicode 异常对象. (line  104)
* PyUnicodeDecodeError_GetStart (C 函式): Unicode 异常对象.  (line   54)
* PyUnicodeDecodeError_SetEnd (C 函式):  Unicode 异常对象.   (line   93)
* PyUnicodeDecodeError_SetReason (C 函式): Unicode 异常对象. (line  109)
* PyUnicodeDecodeError_SetStart (C 函式): Unicode 异常对象.  (line   68)
* PyUnicodeEncodeError_Create (C 函式):  Unicode 异常对象.   (line   18)
* PyUnicodeEncodeError_GetEncoding (C 函式): Unicode 异常对象.
                                                             (line   45)
* PyUnicodeEncodeError_GetEnd (C 函式):  Unicode 异常对象.   (line   81)
* PyUnicodeEncodeError_GetObject (C 函式): Unicode 异常对象. (line   49)
* PyUnicodeEncodeError_GetReason (C 函式): Unicode 异常对象. (line  104)
* PyUnicodeEncodeError_GetStart (C 函式): Unicode 异常对象.  (line   54)
* PyUnicodeEncodeError_SetEnd (C 函式):  Unicode 异常对象.   (line   93)
* PyUnicodeEncodeError_SetReason (C 函式): Unicode 异常对象. (line  109)
* PyUnicodeEncodeError_SetStart (C 函式): Unicode 异常对象.  (line   68)
* PyUnicodeObject (C 型態):              Unicode类型.        (line   29)
* PyUnicodeTranslateError_Create (C 函式): Unicode 异常对象. (line   31)
* PyUnicodeTranslateError_GetEnd (C 函式): Unicode 异常对象. (line   81)
* PyUnicodeTranslateError_GetObject (C 函式): Unicode 异常对象.
                                                             (line   49)
* PyUnicodeTranslateError_GetReason (C 函式): Unicode 异常对象.
                                                             (line  104)
* PyUnicodeTranslateError_GetStart (C 函式): Unicode 异常对象.
                                                             (line   54)
* PyUnicodeTranslateError_SetEnd (C 函式): Unicode 异常对象. (line   93)
* PyUnicodeTranslateError_SetReason (C 函式): Unicode 异常对象.
                                                             (line  109)
* PyUnicodeTranslateError_SetStart (C 函式): Unicode 异常对象.
                                                             (line   68)
* PyUnicode_1BYTE_DATA (C 函式):         Unicode类型.        (line   80)
* PyUnicode_1BYTE_KIND (C 巨集):         Unicode类型.        (line   93)
* PyUnicode_2BYTE_DATA (C 函式):         Unicode类型.        (line   80)
* PyUnicode_2BYTE_KIND (C 巨集):         Unicode类型.        (line   93)
* PyUnicode_4BYTE_DATA (C 函式):         Unicode类型.        (line   80)
* PyUnicode_4BYTE_KIND (C 巨集):         Unicode类型.        (line   93)
* PyUnicode_AsASCIIString (C 函式):      ASCII Codecs.       (line   15)
* PyUnicode_AsCharmapString (C 函式):    Character Map Codecs.
                                                             (line   30)
* PyUnicode_AsEncodedString (C 函式):    Generic Codecs.     (line   17)
* PyUnicode_AsLatin1String (C 函式):     Latin-1 Codecs.     (line   16)
* PyUnicode_AsMBCSString (C 函式):       MBCS codecs for Windows.
                                                             (line   27)
* PyUnicode_AsRawUnicodeEscapeString (C 函式): Raw-Unicode-Escape Codecs.
                                                             (line   15)
* PyUnicode_AsUCS4 (C 函式):             Creating and accessing Unicode strings.
                                                             (line  242)
* PyUnicode_AsUCS4Copy (C 函式):         Creating and accessing Unicode strings.
                                                             (line  253)
* PyUnicode_AsUnicode (C 函式):          Deprecated Py_UNICODE APIs.
                                                             (line   35)
* PyUnicode_AsUnicodeAndSize (C 函式):   Deprecated Py_UNICODE APIs.
                                                             (line   64)
* PyUnicode_AsUnicodeCopy (C 函式):      Deprecated Py_UNICODE APIs.
                                                             (line   81)
* PyUnicode_AsUnicodeEscapeString (C 函式): Unicode-Escape Codecs.
                                                             (line   15)
* PyUnicode_AsUTF16String (C 函式):      UTF-16 Codecs.      (line   49)
* PyUnicode_AsUTF32String (C 函式):      UTF-32 Codecs.      (line   48)
* PyUnicode_AsUTF8 (C 函式):             UTF-8 Codecs.       (line   52)
* PyUnicode_AsUTF8AndSize (C 函式):      UTF-8 Codecs.       (line   29)
* PyUnicode_AsUTF8String (C 函式):       UTF-8 Codecs.       (line   24)
* PyUnicode_AsWideChar (C 函式):         wchar_t Support.    (line   16)
* PyUnicode_AsWideCharString (C 函式):   wchar_t Support.    (line   30)
* PyUnicode_AS_DATA (C 函式):            Unicode类型.        (line  180)
* PyUnicode_AS_UNICODE (C 函式):         Unicode类型.        (line  180)
* PyUnicode_Check (C 函式):              Unicode类型.        (line   48)
* PyUnicode_CheckExact (C 函式):         Unicode类型.        (line   53)
* PyUnicode_Compare (C 函式):            Methods and Slot Functions.
                                                             (line   86)
* PyUnicode_CompareWithASCIIString (C 函式): Methods and Slot Functions.
                                                             (line   94)
* PyUnicode_Concat (C 函式):             Methods and Slot Functions.
                                                             (line   12)
* PyUnicode_Contains (C 函式):           Methods and Slot Functions.
                                                             (line  125)
* PyUnicode_CopyCharacters (C 函式):     Creating and accessing Unicode strings.
                                                             (line  184)
* PyUnicode_Count (C 函式):              Methods and Slot Functions.
                                                             (line   73)
* PyUnicode_DATA (C 函式):               Unicode类型.        (line  114)
* PyUnicode_Decode (C 函式):             Generic Codecs.     (line    8)
* PyUnicode_DecodeASCII (C 函式):        ASCII Codecs.       (line    9)
* PyUnicode_DecodeCharmap (C 函式):      Character Map Codecs.
                                                             (line   15)
* PyUnicode_DecodeFSDefault (C 函式):    File System Encoding.
                                                             (line   65)
* PyUnicode_DecodeFSDefaultAndSize (C 函式): File System Encoding.
                                                             (line   43)
* PyUnicode_DecodeLatin1 (C 函式):       Latin-1 Codecs.     (line   10)
* PyUnicode_DecodeLocale (C 函式):       Locale Encoding.    (line   38)
* PyUnicode_DecodeLocaleAndSize (C 函式): Locale Encoding.   (line    9)
* PyUnicode_DecodeMBCS (C 函式):         MBCS codecs for Windows.
                                                             (line   12)
* PyUnicode_DecodeMBCSStateful (C 函式): MBCS codecs for Windows.
                                                             (line   18)
* PyUnicode_DecodeRawUnicodeEscape (C 函式): Raw-Unicode-Escape Codecs.
                                                             (line    8)
* PyUnicode_DecodeUnicodeEscape (C 函式): Unicode-Escape Codecs.
                                                             (line    8)
* PyUnicode_DecodeUTF16 (C 函式):        UTF-16 Codecs.      (line    8)
* PyUnicode_DecodeUTF16Stateful (C 函式): UTF-16 Codecs.     (line   36)
* PyUnicode_DecodeUTF32 (C 函式):        UTF-32 Codecs.      (line    8)
* PyUnicode_DecodeUTF32Stateful (C 函式): UTF-32 Codecs.     (line   35)
* PyUnicode_DecodeUTF7 (C 函式):         UTF-7 Codecs.       (line    8)
* PyUnicode_DecodeUTF7Stateful (C 函式): UTF-7 Codecs.       (line   14)
* PyUnicode_DecodeUTF8 (C 函式):         UTF-8 Codecs.       (line    8)
* PyUnicode_DecodeUTF8Stateful (C 函式): UTF-8 Codecs.       (line   14)
* PyUnicode_Encode (C 函式):             Generic Codecs.     (line   26)
* PyUnicode_EncodeASCII (C 函式):        ASCII Codecs.       (line   20)
* PyUnicode_EncodeCharmap (C 函式):      Character Map Codecs.
                                                             (line   44)
* PyUnicode_EncodeCodePage (C 函式):     MBCS codecs for Windows.
                                                             (line   32)
* PyUnicode_EncodeFSDefault (C 函式):    File System Encoding.
                                                             (line   78)
* PyUnicode_EncodeLatin1 (C 函式):       Latin-1 Codecs.     (line   22)
* PyUnicode_EncodeLocale (C 函式):       Locale Encoding.    (line   47)
* PyUnicode_EncodeMBCS (C 函式):         MBCS codecs for Windows.
                                                             (line   41)
* PyUnicode_EncodeRawUnicodeEscape (C 函式): Raw-Unicode-Escape Codecs.
                                                             (line   22)
* PyUnicode_EncodeUnicodeEscape (C 函式): Unicode-Escape Codecs.
                                                             (line   22)
* PyUnicode_EncodeUTF16 (C 函式):        UTF-16 Codecs.      (line   55)
* PyUnicode_EncodeUTF32 (C 函式):        UTF-32 Codecs.      (line   54)
* PyUnicode_EncodeUTF7 (C 函式):         UTF-7 Codecs.       (line   24)
* PyUnicode_EncodeUTF8 (C 函式):         UTF-8 Codecs.       (line   62)
* PyUnicode_Fill (C 函式):               Creating and accessing Unicode strings.
                                                             (line  197)
* PyUnicode_Find (C 函式):               Methods and Slot Functions.
                                                             (line   46)
* PyUnicode_FindChar (C 函式):           Methods and Slot Functions.
                                                             (line   57)
* PyUnicode_Format (C 函式):             Methods and Slot Functions.
                                                             (line  120)
* PyUnicode_FromEncodedObject (C 函式):  Creating and accessing Unicode strings.
                                                             (line  160)
* PyUnicode_FromFormat (C 函式):         Creating and accessing Unicode strings.
                                                             (line   48)
* PyUnicode_FromFormatV (C 函式):        Creating and accessing Unicode strings.
                                                             (line  153)
* PyUnicode_FromKindAndData (C 函式):    Creating and accessing Unicode strings.
                                                             (line   20)
* PyUnicode_FromObject (C 函式):         Deprecated Py_UNICODE APIs.
                                                             (line  106)
* PyUnicode_FromString (C 函式):         Creating and accessing Unicode strings.
                                                             (line   44)
* PyUnicode_FromString():                字典物件.           (line   58)
* PyUnicode_FromStringAndSize (C 函式):  Creating and accessing Unicode strings.
                                                             (line   30)
* PyUnicode_FromUnicode (C 函式):        Deprecated Py_UNICODE APIs.
                                                             (line   13)
* PyUnicode_FromWideChar (C 函式):       wchar_t Support.    (line    8)
* PyUnicode_FSConverter (C 函式):        File System Encoding.
                                                             (line   13)
* PyUnicode_FSDecoder (C 函式):          File System Encoding.
                                                             (line   30)
* PyUnicode_GetLength (C 函式):          Creating and accessing Unicode strings.
                                                             (line  178)
* PyUnicode_GetSize (C 函式):            Deprecated Py_UNICODE APIs.
                                                             (line   96)
* PyUnicode_GET_DATA_SIZE (C 函式):      Unicode类型.        (line  170)
* PyUnicode_GET_LENGTH (C 函式):         Unicode类型.        (line   72)
* PyUnicode_GET_SIZE (C 函式):           Unicode类型.        (line  160)
* PyUnicode_InternFromString (C 函式):   Methods and Slot Functions.
                                                             (line  147)
* PyUnicode_InternInPlace (C 函式):      Methods and Slot Functions.
                                                             (line  134)
* PyUnicode_IsIdentifier (C 函式):       Unicode类型.        (line  201)
* PyUnicode_Join (C 函式):               Methods and Slot Functions.
                                                             (line   32)
* PyUnicode_KIND (C 函式):               Unicode类型.        (line  105)
* PyUnicode_MAX_CHAR_VALUE (C 巨集):     Unicode类型.        (line  151)
* PyUnicode_New (C 函式):                Creating and accessing Unicode strings.
                                                             (line    9)
* PyUnicode_READ (C 函式):               Unicode类型.        (line  134)
* PyUnicode_ReadChar (C 函式):           Creating and accessing Unicode strings.
                                                             (line  225)
* PyUnicode_READY (C 函式):              Unicode类型.        (line   58)
* PyUnicode_READ_CHAR (C 函式):          Unicode类型.        (line  143)
* PyUnicode_Replace (C 函式):            Methods and Slot Functions.
                                                             (line   79)
* PyUnicode_RichCompare (C 函式):        Methods and Slot Functions.
                                                             (line  106)
* PyUnicode_Split (C 函式):              Methods and Slot Functions.
                                                             (line   16)
* PyUnicode_Splitlines (C 函式):         Methods and Slot Functions.
                                                             (line   26)
* PyUnicode_Substring (C 函式):          Creating and accessing Unicode strings.
                                                             (line  234)
* PyUnicode_Tailmatch (C 函式):          Methods and Slot Functions.
                                                             (line   37)
* PyUnicode_TransformDecimalToASCII (C 函式): Deprecated Py_UNICODE APIs.
                                                             (line   52)
* PyUnicode_Translate (C 函式):          Character Map Codecs.
                                                             (line   59)
* PyUnicode_TranslateCharmap (C 函式):   Character Map Codecs.
                                                             (line   76)
* PyUnicode_Type (C 變數):               Unicode类型.        (line   40)
* PyUnicode_WCHAR_KIND (C 巨集):         Unicode类型.        (line   93)
* PyUnicode_WRITE (C 函式):              Unicode类型.        (line  121)
* PyUnicode_WriteChar (C 函式):          Creating and accessing Unicode strings.
                                                             (line  211)
* PyVarObject (C 型態):                  基本的对象类型和宏. (line   21)
* PyVarObject.ob_size (C 成員函數):      PyVarObject Slots.  (line    6)
* PyVarObject_HEAD_INIT (C 巨集):        基本的对象类型和宏. (line  104)
* PyVectorcall_Call (C 函式):            Vectorcall 支持 API.
                                                             (line   31)
* PyVectorcall_Function (C 函式):        Vectorcall 支持 API.
                                                             (line   18)
* PyVectorcall_NARGS (C 函式):           Vectorcall 支持 API.
                                                             (line    6)
* PyWeakref_Check (C 函式):              弱參照物件.         (line    9)
* PyWeakref_CheckProxy (C 函式):         弱參照物件.         (line   17)
* PyWeakref_CheckRef (C 函式):           弱參照物件.         (line   13)
* PyWeakref_GetObject (C 函式):          弱參照物件.         (line   41)
* PyWeakref_GET_OBJECT (C 函式):         弱參照物件.         (line   49)
* PyWeakref_NewProxy (C 函式):           弱參照物件.         (line   31)
* PyWeakref_NewRef (C 函式):             弱參照物件.         (line   21)
* PyWideStringList (C 型態):             PyWideStringList.   (line    6)
* PyWideStringList.items (C 成員函數):   PyWideStringList.   (line   41)
* PyWideStringList.length (C 成員函數):  PyWideStringList.   (line   37)
* PyWideStringList_Append (C 函式):      PyWideStringList.   (line   15)
* PyWideStringList_Insert (C 函式):      PyWideStringList.   (line   22)
* PyWrapper_New (C 函式):                修飾器物件.         (line   42)
* PyZipFile (zipfile 中的類別):          PyZipFile 对象.     (line    9)
* Py_ABS (C 巨集):                       有用的宏.           (line   31)
* Py_AddPendingCall (C 函式):            异步通知.           (line   10)
* Py_AddPendingCall():                   异步通知.           (line   12)
* Py_AtExit (C 函式):                    行程（Process）控制.
                                                             (line   30)
* Py_BEGIN_ALLOW_THREADS:                Releasing the GIL from extension code.
                                                             (line   21)
* Py_BEGIN_ALLOW_THREADS (C 巨集):       高阶 API.           (line  158)
* Py_BLOCK_THREADS (C 巨集):             高阶 API.           (line  171)
* Py_buffer (C 型態):                    缓冲区结构.         (line   19)
* Py_buffer.buf (C 成員函數):            缓冲区结构.         (line   21)
* Py_buffer.format (C 成員函數):         缓冲区结构.         (line   73)
* Py_buffer.internal (C 成員函數):       缓冲区结构.         (line  129)
* Py_buffer.itemsize (C 成員函數):       缓冲区结构.         (line   56)
* Py_buffer.len (C 成員函數):            缓冲区结构.         (line   40)
* Py_buffer.ndim (C 成員函數):           缓冲区结构.         (line   80)
* Py_buffer.obj (C 成員函數):            缓冲区结构.         (line   30)
* Py_buffer.readonly (C 成員函數):       缓冲区结构.         (line   51)
* Py_buffer.shape (C 成員函數):          缓冲区结构.         (line   90)
* Py_buffer.strides (C 成員函數):        缓冲区结构.         (line  102)
* Py_buffer.suboffsets (C 成員函數):     缓冲区结构.         (line  113)
* Py_BuildValue (C 函式):                创建变量.           (line    6)
* Py_BytesMain (C 函式):                 The Very High Level Layer.
                                                             (line   41)
* Py_BytesWarningFlag (C 變數):          全局配置变量.       (line   13)
* Py_CHARMASK (C 巨集):                  有用的宏.           (line   61)
* Py_CLEAR (C 函式):                     參照計數.           (line   39)
* py_compile (模組):                     py_compile --- 编译 Python 源文件.
                                                             (line    6)
* PY_COMPILED (於 imp 模組中):           imp —— 由代码内部访问 import 。.
                                                             (line  305)
* Py_CompileString (C 函式):             The Very High Level Layer.
                                                             (line  294)
* Py_CompileString():                    The Very High Level Layer.
                                                             (line  388)
* Py_CompileString() <1>:                The Very High Level Layer.
                                                             (line  393)
* Py_CompileString() <2>:                The Very High Level Layer.
                                                             (line  400)
* Py_CompileStringExFlags (C 函式):      The Very High Level Layer.
                                                             (line  327)
* Py_CompileStringFlags (C 函式):        The Very High Level Layer.
                                                             (line  300)
* Py_CompileStringObject (C 函式):       The Very High Level Layer.
                                                             (line  307)
* Py_complex (C 型態):                   表示复数的C结构体.  (line    9)
* Py_DebugFlag (C 變數):                 全局配置变量.       (line   21)
* Py_DecodeLocale (C 函式):              作業系統工具.       (line  107)
* Py_DECREF (C 函式):                    參照計數.           (line   18)
* Py_DECREF():                           引用计数<2>.        (line   13)
* Py_DEPRECATED (C 巨集):                有用的宏.           (line   78)
* Py_DontWriteBytecodeFlag (C 變數):     全局配置变量.       (line   29)
* Py_Ellipsis (C 變數):                  Ellipsis 对象.      (line    6)
* Py_EncodeLocale (C 函式):              作業系統工具.       (line  160)
* Py_EndInterpreter (C 函式):            Sub-interpreter support.
                                                             (line   76)
* Py_END_ALLOW_THREADS:                  Releasing the GIL from extension code.
                                                             (line   21)
* Py_END_ALLOW_THREADS (C 巨集):         高阶 API.           (line  165)
* Py_EnterRecursiveCall (C 函式):        递归控制.           (line   13)
* Py_eval_input (C 變數):                The Very High Level Layer.
                                                             (line  386)
* Py_Exit (C 函式):                      行程（Process）控制.
                                                             (line   21)
* Py_ExitStatusException (C 函式):       PyStatus.           (line   62)
* Py_False (C 變數):                     布林物件.           (line   13)
* Py_FatalError (C 函式):                行程（Process）控制.
                                                             (line    6)
* Py_FatalError():                       Process-wide parameters.
                                                             (line  217)
* Py_FdIsInteractive (C 函式):           作業系統工具.       (line   17)
* Py_file_input (C 變數):                The Very High Level Layer.
                                                             (line  391)
* Py_Finalize (C 函式):                  Initializing and finalizing the interpreter.
                                                             (line   78)
* Py_FinalizeEx (C 函式):                Initializing and finalizing the interpreter.
                                                             (line   39)
* Py_FinalizeEx():                       行程（Process）控制.
                                                             (line   23)
* Py_FinalizeEx() <1>:                   行程（Process）控制.
                                                             (line   32)
* Py_FinalizeEx() <2>:                   Initializing and finalizing the interpreter.
                                                             (line    8)
* Py_FinalizeEx() <3>:                   Sub-interpreter support.
                                                             (line   49)
* Py_FinalizeEx() <4>:                   Sub-interpreter support.
                                                             (line   78)
* PY_FROZEN (於 imp 模組中):             imp —— 由代码内部访问 import 。.
                                                             (line  329)
* Py_FrozenFlag (C 變數):                全局配置变量.       (line   37)
* Py_GenericAlias (C 函式):              类型注解对象.       (line    9)
* Py_GenericAliasType (C 變數):          类型注解对象.       (line   38)
* Py_GetArgcArgv (C 函式):               Py_GetArgcArgv.     (line    6)
* Py_GetBuildInfo (C 函式):              Process-wide parameters.
                                                             (line  203)
* Py_GetCompiler (C 函式):               Process-wide parameters.
                                                             (line  192)
* Py_GetCopyright (C 函式):              Process-wide parameters.
                                                             (line  181)
* Py_GETENV (C 巨集):                    有用的宏.           (line   66)
* Py_GetExecPrefix (C 函式):             Process-wide parameters.
                                                             (line   71)
* Py_GetExecPrefix():                    嵌入式Python.       (line   42)
* Py_GetPath (C 函式):                   Process-wide parameters.
                                                             (line  118)
* Py_GetPath():                          嵌入式Python.       (line   42)
* Py_GetPath() <1>:                      Process-wide parameters.
                                                             (line   36)
* Py_GetPath() <2>:                      Process-wide parameters.
                                                             (line  133)
* Py_GetPlatform (C 函式):               Process-wide parameters.
                                                             (line  170)
* Py_GetPrefix (C 函式):                 Process-wide parameters.
                                                             (line   57)
* Py_GetPrefix():                        嵌入式Python.       (line   42)
* Py_GetProgramFullPath (C 函式):        Process-wide parameters.
                                                             (line  109)
* Py_GetProgramFullPath():               嵌入式Python.       (line   42)
* Py_GetProgramName (C 函式):            Process-wide parameters.
                                                             (line   51)
* Py_GetPythonHome (C 函式):             Process-wide parameters.
                                                             (line  280)
* Py_GetVersion (C 函式):                Process-wide parameters.
                                                             (line  157)
* Py_HashRandomizationFlag (C 變數):     全局配置变量.       (line   44)
* Py_IgnoreEnvironmentFlag (C 變數):     全局配置变量.       (line   52)
* Py_INCREF (C 函式):                    參照計數.           (line    8)
* Py_INCREF():                           引用计数<2>.        (line   13)
* Py_Initialize (C 函式):                Initializing and finalizing the interpreter.
                                                             (line    6)
* Py_Initialize():                       嵌入式Python.       (line   12)
* Py_Initialize() <1>:                   Process-wide parameters.
                                                             (line    9)
* Py_Initialize() <2>:                   Process-wide parameters.
                                                             (line   36)
* Py_Initialize() <3>:                   Sub-interpreter support.
                                                             (line   49)
* Py_InitializeEx (C 函式):              Initializing and finalizing the interpreter.
                                                             (line   26)
* Py_InitializeFromConfig (C 函式):      Initialization with PyConfig.
                                                             (line    8)
* Py_InspectFlag (C 變數):               全局配置变量.       (line   59)
* Py_InteractiveFlag (C 變數):           全局配置变量.       (line   69)
* Py_IsInitialized (C 函式):             Initializing and finalizing the interpreter.
                                                             (line   32)
* Py_IsInitialized():                    嵌入式Python.       (line   51)
* Py_IsolatedFlag (C 變數):              全局配置变量.       (line   73)
* Py_IS_TYPE (C 函式):                   基本的对象类型和宏. (line   57)
* Py_LeaveRecursiveCall (C 函式):        递归控制.           (line   32)
* Py_LegacyWindowsFSEncodingFlag (C 變數): 全局配置变量.     (line   83)
* Py_LegacyWindowsStdioFlag (C 變數):    全局配置变量.       (line   95)
* Py_Main (C 函式):                      The Very High Level Layer.
                                                             (line   24)
* Py_MAX (C 巨集):                       有用的宏.           (line   43)
* Py_MEMBER_SIZE (C 巨集):               有用的宏.           (line   55)
* Py_MIN (C 巨集):                       有用的宏.           (line   37)
* Py_mod_create (C 巨集):                Multi-phase initialization.
                                                             (line   61)
* Py_mod_exec (C 巨集):                  Multi-phase initialization.
                                                             (line   95)
* Py_NewInterpreter (C 函式):            Sub-interpreter support.
                                                             (line   24)
* Py_None (C 變數):                      None 对象.          (line   10)
* Py_NoSiteFlag (C 變數):                全局配置变量.       (line  107)
* Py_NotImplemented (C 變數):            对象协议.           (line    6)
* Py_NoUserSiteDirectory (C 變數):       全局配置变量.       (line  115)
* py_object (ctypes 中的類別):           基础数据类型<2>.    (line  189)
* Py_OptimizeFlag (C 變數):              全局配置变量.       (line  123)
* Py_PreInitialize (C 函式):             Preinitialization with PyPreConfig.
                                                             (line    8)
* Py_PreInitializeFromArgs (C 函式):     Preinitialization with PyPreConfig.
                                                             (line   18)
* Py_PreInitializeFromBytesArgs (C 函式): Preinitialization with PyPreConfig.
                                                             (line   12)
* Py_PRINT_RAW:                          檔案（File）物件.   (line   74)
* PY_PYTHON:                             自定义默认的Python版本.
                                                             (line   13)
* Py_QuietFlag (C 變數):                 全局配置变量.       (line  128)
* Py_REFCNT (C 巨集):                    基本的对象类型和宏. (line   70)
* Py_ReprEnter (C 函式):                 递归控制.           (line   45)
* Py_ReprLeave (C 函式):                 递归控制.           (line   63)
* Py_RETURN_FALSE (C 巨集):              布林物件.           (line   23)
* Py_RETURN_NONE (C 巨集):               None 对象.          (line   15)
* Py_RETURN_NOTIMPLEMENTED (C 巨集):     对象协议.           (line   10)
* Py_RETURN_RICHCOMPARE (C 巨集):        PyTypeObject Slots. (line  837)
* Py_RETURN_TRUE (C 巨集):               布林物件.           (line   27)
* Py_RunMain (C 函式):                   Py_RunMain.         (line    6)
* Py_SetPath (C 函式):                   Process-wide parameters.
                                                             (line  131)
* Py_SetPath():                          Process-wide parameters.
                                                             (line  120)
* Py_SetProgramName (C 函式):            Process-wide parameters.
                                                             (line   34)
* Py_SetProgramName():                   嵌入式Python.       (line   42)
* Py_SetProgramName() <1>:               Initializing and finalizing the interpreter.
                                                             (line    8)
* Py_SetProgramName() <2>:               Process-wide parameters.
                                                             (line   53)
* Py_SetProgramName() <3>:               Process-wide parameters.
                                                             (line  111)
* Py_SetPythonHome (C 函式):             Process-wide parameters.
                                                             (line  266)
* Py_SetStandardStreamEncoding (C 函式): Process-wide parameters.
                                                             (line    6)
* Py_SET_REFCNT (C 函式):                基本的对象类型和宏. (line   77)
* Py_SET_SIZE (C 函式):                  基本的对象类型和宏. (line   90)
* Py_SET_TYPE (C 函式):                  基本的对象类型和宏. (line   64)
* Py_single_input (C 變數):              The Very High Level Layer.
                                                             (line  398)
* Py_SIZE (C 巨集):                      基本的对象类型和宏. (line   83)
* PY_SOURCE (於 imp 模組中):             imp —— 由代码内部访问 import 。.
                                                             (line  299)
* PY_SSIZE_T_MAX:                        整數物件.           (line  165)
* Py_STRINGIFY (C 巨集):                 有用的宏.           (line   49)
* Py_TPFLAGS_BASETYPE (內建變數):        PyTypeObject Slots. (line  500)
* Py_TPFLAGS_BASE_EXC_SUBCLASS (內建變數): PyTypeObject Slots.
                                                             (line  597)
* Py_TPFLAGS_BYTES_SUBCLASS (內建變數):  PyTypeObject Slots. (line  591)
* Py_TPFLAGS_DEFAULT (內建變數):         PyTypeObject Slots. (line  549)
* Py_TPFLAGS_DICT_SUBCLASS (內建變數):   PyTypeObject Slots. (line  595)
* Py_TPFLAGS_HAVE_FINALIZE (內建變數):   PyTypeObject Slots. (line  610)
* Py_TPFLAGS_HAVE_GC (內建變數):         PyTypeObject Slots. (line  528)
* Py_TPFLAGS_HAVE_VECTORCALL (內建變數): PyTypeObject Slots. (line  621)
* Py_TPFLAGS_HEAPTYPE (內建變數):        PyTypeObject Slots. (line  485)
* Py_TPFLAGS_LIST_SUBCLASS (內建變數):   PyTypeObject Slots. (line  587)
* Py_TPFLAGS_LONG_SUBCLASS (內建變數):   PyTypeObject Slots. (line  585)
* Py_TPFLAGS_METHOD_DESCRIPTOR (內建變數): PyTypeObject Slots.
                                                             (line  561)
* Py_TPFLAGS_READY (內建變數):           PyTypeObject Slots. (line  510)
* Py_TPFLAGS_READYING (內建變數):        PyTypeObject Slots. (line  519)
* Py_TPFLAGS_TUPLE_SUBCLASS (內建變數):  PyTypeObject Slots. (line  589)
* Py_TPFLAGS_TYPE_SUBCLASS (內建變數):   PyTypeObject Slots. (line  599)
* Py_TPFLAGS_UNICODE_SUBCLASS (內建變數): PyTypeObject Slots.
                                                             (line  593)
* Py_tracefunc (C 型態):                 分析和跟踪.         (line   18)
* Py_True (C 變數):                      布林物件.           (line   18)
* Py_tss_NEEDS_INIT (C 巨集):            Thread Specific Storage TSS API.
                                                             (line   28)
* Py_tss_t (C 型態):                     Thread Specific Storage TSS API.
                                                             (line   17)
* Py_TYPE (C 巨集):                      基本的对象类型和宏. (line   50)
* Py_UCS1 (C 型態):                      Unicode类型.        (line    9)
* Py_UCS2 (C 型態):                      Unicode类型.        (line    9)
* Py_UCS4 (C 型態):                      Unicode类型.        (line    9)
* Py_UNBLOCK_THREADS (C 巨集):           高阶 API.           (line  177)
* Py_UnbufferedStdioFlag (C 變數):       全局配置变量.       (line  136)
* Py_UNICODE (C 型態):                   Unicode类型.        (line   20)
* Py_UNICODE_ISALNUM (C 函式):           Unicode字符属性.    (line   52)
* Py_UNICODE_ISALPHA (C 函式):           Unicode字符属性.    (line   47)
* Py_UNICODE_ISDECIMAL (C 函式):         Unicode字符属性.    (line   35)
* Py_UNICODE_ISDIGIT (C 函式):           Unicode字符属性.    (line   39)
* Py_UNICODE_ISLINEBREAK (C 函式):       Unicode字符属性.    (line   30)
* Py_UNICODE_ISLOWER (C 函式):           Unicode字符属性.    (line   15)
* Py_UNICODE_ISNUMERIC (C 函式):         Unicode字符属性.    (line   43)
* Py_UNICODE_ISPRINTABLE (C 函式):       Unicode字符属性.    (line   57)
* Py_UNICODE_ISSPACE (C 函式):           Unicode字符属性.    (line   10)
* Py_UNICODE_ISTITLE (C 函式):           Unicode字符属性.    (line   25)
* Py_UNICODE_ISUPPER (C 函式):           Unicode字符属性.    (line   20)
* Py_UNICODE_IS_HIGH_SURROGATE (C 巨集): Unicode字符属性.    (line  111)
* Py_UNICODE_IS_LOW_SURROGATE (C 巨集):  Unicode字符属性.    (line  115)
* Py_UNICODE_IS_SURROGATE (C 巨集):      Unicode字符属性.    (line  107)
* Py_UNICODE_JOIN_SURROGATES (C 巨集):   Unicode字符属性.    (line  119)
* Py_UNICODE_TODECIMAL (C 函式):         Unicode字符属性.    (line   88)
* Py_UNICODE_TODIGIT (C 函式):           Unicode字符属性.    (line   94)
* Py_UNICODE_TOLOWER (C 函式):           Unicode字符属性.    (line   70)
* Py_UNICODE_TONUMERIC (C 函式):         Unicode字符属性.    (line  100)
* Py_UNICODE_TOTITLE (C 函式):           Unicode字符属性.    (line   82)
* Py_UNICODE_TOUPPER (C 函式):           Unicode字符属性.    (line   76)
* Py_UNREACHABLE (C 巨集):               有用的宏.           (line   10)
* Py_UNUSED (C 巨集):                    有用的宏.           (line   71)
* Py_VaBuildValue (C 函式):              创建变量.           (line  187)
* PY_VECTORCALL_ARGUMENTS_OFFSET (C 巨集): Vectorcall 协议.  (line   53)
* Py_VerboseFlag (C 變數):               全局配置变量.       (line  143)
* Py_VISIT (C 函式):                     使对象类型支持循环垃圾回收.
                                                             (line  132)
* Py_XDECREF (C 函式):                   參照計數.           (line   33)
* Py_XDECREF():                          异常<17>.           (line  121)
* Py_XINCREF (C 函式):                   參照計數.           (line   13)
* P_ALL (於 os 模組中):                  进程管理.           (line  652)
* P_DETACH (於 os 模組中):               进程管理.           (line  525)
* P_NOWAIT (於 os 模組中):               进程管理.           (line  508)
* P_NOWAITO (於 os 模組中):              进程管理.           (line  508)
* P_OVERLAY (於 os 模組中):              进程管理.           (line  525)
* P_PGID (於 os 模組中):                 进程管理.           (line  652)
* P_PID (於 os 模組中):                  进程管理.           (line  652)
* P_PIDFD (於 os 模組中):                进程管理.           (line  663)
* P_WAIT (於 os 模組中):                 进程管理.           (line  517)
* qiflush() (於 curses 模組中):          函数<4>.            (line  315)
* QName (xml.etree.ElementTree 中的類別): QName 对象.        (line    6)
* qsize() (asyncio.Queue 的方法):        队列.               (line   67)
* qsize() (multiprocessing.Queue 的方法): 管道和队列.        (line   83)
* qsize() (queue.Queue 的方法):          Queue对象.          (line    9)
* qsize() (queue.SimpleQueue 的方法):    SimpleQueue 对象.   (line    8)
* qualified name（限定名稱）:            術語表.             (line  977)
* quantiles() (statistics.NormalDist 的方法): NormalDist 对象.
                                                             (line   85)
* quantiles() (於 statistics 模組中):    函式細節.           (line  348)
* quantize() (decimal.Context 的方法):   上下文对象.         (line  405)
* quantize() (decimal.Decimal 的方法):   Decimal 对象.       (line  396)
* QueryInfoKey() (於 winreg 模組中):     函数<12>.           (line  292)
* QueryReflectionKey() (於 winreg 模組中): 函数<12>.         (line  467)
* QueryValue() (於 winreg 模組中):       函数<12>.           (line  318)
* QueryValueEx() (於 winreg 模組中):     函数<12>.           (line  336)
* Queue (asyncio 中的類別):              队列.               (line    6)
* Queue (multiprocessing 中的類別):      管道和队列.         (line   71)
* Queue (queue 中的類別):                queue --- 一个同步的队列类.
                                                             (line   27)
* queue (sched.scheduler 的屬性):        调度器对象.         (line   63)
* queue (模組):                          queue --- 一个同步的队列类.
                                                             (line    6)
* Queue() (multiprocessing.managers.SyncManager 的方法): 管理器.
                                                             (line  157)
* QueueEmpty:                            异常<8>.            (line    6)
* QueueFull:                             异常<8>.            (line   11)
* QueueHandler (logging.handlers 中的類別): QueueHandler.    (line   18)
* QueueListener (logging.handlers 中的類別): QueueListener.  (line   21)
* quick_ratio() (difflib.SequenceMatcher 的方法): SequenceMatcher 对象.
                                                             (line  177)
* quit (pdb command):                    调试器命令.         (line  275)
* quit (內建變數):                       由 site 模块添加的常量.
                                                             (line   10)
* quit() (ftplib.FTP 的方法):            FTP 对象.           (line  198)
* quit() (nntplib.NNTP 的方法):          方法<3>.            (line   19)
* quit() (poplib.POP3 的方法):           POP3 对象.          (line   75)
* quit() (smtplib.SMTP 的方法):          SMTP 对象.          (line  288)
* quit() (tkinter.filedialog.FileDialog 的方法): 原生 加载/保存 对话框.
                                                             (line  114)
* quopri (模組):                         quopri --- 编码与解码经过 MIME 转码的可打印数据.
                                                             (line    6)
* quote() (於 email.utils 模組中):       email utils 其他工具.
                                                             (line   37)
* quote() (於 shlex 模組中):             shlex —— 简单的词义分析.
                                                             (line   44)
* quote() (於 urllib.parse 模組中):      URL 转码.           (line   11)
* quoteattr() (於 xml.sax.saxutils 模組中): xml sax saxutils --- SAX 工具集.
                                                             (line   30)
* quotechar (csv.Dialect 的屬性):        变种与格式参数.     (line   43)
* quoted-printable; encoding:            quopri --- 编码与解码经过 MIME 转码的可打印数据.
                                                             (line    8)
* quotes (shlex.shlex 的屬性):           shlex 对象.         (line   94)
* QUOTE_ALL (於 csv 模組中):             模块内容<3>.        (line  216)
* quote_from_bytes() (於 urllib.parse 模組中): URL 转码.     (line   46)
* QUOTE_MINIMAL (於 csv 模組中):         模块内容<3>.        (line  220)
* QUOTE_NONE (於 csv 模組中):            模块内容<3>.        (line  231)
* QUOTE_NONNUMERIC (於 csv 模組中):      模块内容<3>.        (line  225)
* quote_plus() (於 urllib.parse 模組中): URL 转码.           (line   36)
* quoting (csv.Dialect 的屬性):          变种与格式参数.     (line   48)
* r"; raw string literal:                字符串与字节串字面值.
                                                             (line   41)
* r’; raw string literal:                字符串与字节串字面值.
                                                             (line   41)
* radians() (於 math 模組中):            角度转换.           (line   10)
* radians() (於 turtle 模組中):          度量单位设置.       (line   27)
* RadioButtonGroup (msilib 中的類別):    GUI classes.        (line   29)
* radiogroup() (msilib.Dialog 的方法):   GUI classes.        (line   73)
* radix() (decimal.Context 的方法):      上下文对象.         (line  409)
* radix() (decimal.Decimal 的方法):      Decimal 对象.       (line  416)
* RADIXCHAR (於 locale 模組中):          locale --- 国际化服务.
                                                             (line  192)
* raise (2to3 fixer):                    修复器.             (line  250)
* Raise (ast 中的類別):                  Statements.         (line  115)
* raise an exception:                    异常.               (line    6)
* raise_on_defect (email.policy.Policy 的屬性): email policy Policy 对象.
                                                             (line  144)
* raise_signal() (於 signal 模組中):     模块内容<5>.        (line  255)
* RAISE_VARARGS (opcode):                Python字节码说明.   (line  644)
* raising; exception:                    raise 语句.         (line    6)
* randbelow() (於 secrets 模組中):       亂數.               (line   18)
* randbits() (於 secrets 模組中):        亂數.               (line   22)
* randbytes() (於 random 模組中):        用于字节数据的函数. (line    6)
* randint() (於 random 模組中):          整数用函数.         (line   22)
* Random (random 中的類別):              替代生成器.         (line    6)
* random (模組):                         random --- 生成伪随机数.
                                                             (line    6)
* random() (於 random 模組中):           实值分布.           (line    9)
* randrange() (於 random 模組中):        整数用函数.         (line    6)
* RAND_add() (於 ssl 模組中):            随机生成.           (line   55)
* RAND_bytes() (於 ssl 模組中):          随机生成.           (line    6)
* RAND_egd() (於 ssl 模組中):            随机生成.           (line   43)
* RAND_pseudo_bytes() (於 ssl 模組中):   随机生成.           (line   20)
* RAND_status() (於 ssl 模組中):         随机生成.           (line   37)
* range (內建類別):                      range 对象.         (line    9)
* RARROW (於 token 模組中):              token --- 与Python解析树一起使用的常量.
                                                             (line  226)
* ratecv() (於 audioop 模組中):          audioop --- 处理原始音频数据.
                                                             (line  153)
* ratio() (difflib.SequenceMatcher 的方法): SequenceMatcher 对象.
                                                             (line  156)
* Rational (numbers 中的類別):           数字的层次.         (line   39)
* raw (io.BufferedIOBase 的屬性):        I/O 基类.           (line  213)
* raw string:                            字符串与字节串字面值.
                                                             (line   33)
* raw() (pickle.PickleBuffer 的方法):    模块接口.           (line  277)
* raw() (於 curses 模組中):              函数<4>.            (line  321)
* RawArray() (於 multiprocessing.sharedctypes 模組中): multiprocessing sharedctypes 模块.
                                                             (line   13)
* RawConfigParser (configparser 中的類別): RawConfigParser 对象.
                                                             (line    6)
* RawDescriptionHelpFormatter (argparse 中的類別): formatter_class.
                                                             (line    9)
* RawIOBase (io 中的類別):               I/O 基类.           (line  144)
* RawPen (turtle 中的類別):              公共类.             (line    6)
* RawTextHelpFormatter (argparse 中的類別): formatter_class. (line    9)
* RawTurtle (turtle 中的類別):           公共类.             (line    6)
* RawValue() (於 multiprocessing.sharedctypes 模組中): multiprocessing sharedctypes 模块.
                                                             (line   28)
* raw_data_manager (於 email.contentmanager 模組中): 内容管理器实例.
                                                             (line   10)
* raw_decode() (json.JSONDecoder 的方法): 编码器和解码器.    (line   85)
* raw_input (2to3 fixer):                修复器.             (line  256)
* raw_input() (code.InteractiveConsole 的方法): 交互式控制台对象.
                                                             (line   37)
* RBRACE (於 token 模組中):              token --- 与Python解析树一起使用的常量.
                                                             (line  126)
* rcpttos (smtpd.SMTPChannel 的屬性):    SMTPChannel 对象.   (line   67)
* re (re.Match 的屬性):                  匹配对象.           (line  162)
* re (模組):                             re --- 正则表达式操作.
                                                             (line    6)
* read() (asyncio.StreamReader 的方法):  StreamReader.       (line   14)
* read() (chunk.Chunk 的方法):           chunk --- 读取 IFF 分块数据.
                                                             (line   91)
* read() (codecs.StreamReader 的方法):   StreamReader 对象.  (line   30)
* read() (configparser.ConfigParser 的方法): ConfigParser 对象.
                                                             (line   97)
* read() (http.client.HTTPResponse 的方法): HTTPResponse 对象.
                                                             (line   12)
* read() (imaplib.IMAP4 的方法):         IMAP4 对象.         (line  178)
* read() (io.BufferedIOBase 的方法):     I/O 基类.           (line  230)
* read() (io.BufferedReader 的方法):     缓冲流.             (line   71)
* read() (io.RawIOBase 的方法):          I/O 基类.           (line  156)
* read() (io.TextIOBase 的方法):         文本 I/O<2>.        (line   47)
* read() (mimetypes.MimeTypes 的方法):   MimeTypes 对象.     (line   58)
* read() (mmap.mmap 的方法):             mmap --- 内存映射文件支持.
                                                             (line  194)
* read() (ossaudiodev.oss_audio_device 的方法): 音频设备对象.
                                                             (line   28)
* read() (ssl.MemoryBIO 的方法):         内存 BIO 支持<2>.   (line  130)
* read() (ssl.SSLSocket 的方法):         SSL 套接字.         (line   66)
* read() (urllib.robotparser.RobotFileParser 的方法): urllib robotparser --- robots txt 语法分析程序.
                                                             (line   24)
* read() (zipfile.ZipFile 的方法):       ZipFile 对象.       (line  189)
* read() (於 os 模組中):                 文件描述符操作.     (line  500)
* read1() (io.BufferedIOBase 的方法):    I/O 基类.           (line  243)
* read1() (io.BufferedReader 的方法):    缓冲流.             (line   76)
* read1() (io.BytesIO 的方法):           缓冲流.             (line   39)
* READABLE (於 tkinter 模組中):          File Handlers.      (line   41)
* readable() (asyncore.dispatcher 的方法): asyncore --- 异步套接字处理器.
                                                             (line  134)
* readable() (io.IOBase 的方法):         I/O 基类.           (line   64)
* readall() (io.RawIOBase 的方法):       I/O 基类.           (line  169)
* reader() (於 csv 模組中):              模块内容<3>.        (line    8)
* ReadError:                             tarfile --- 读写tar归档文件.
                                                             (line  171)
* readexactly() (asyncio.StreamReader 的方法): StreamReader. (line   29)
* readfp() (configparser.ConfigParser 的方法): ConfigParser 对象.
                                                             (line  264)
* readfp() (mimetypes.MimeTypes 的方法): MimeTypes 对象.     (line   66)
* readframes() (aifc.aifc 的方法):       aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line   84)
* readframes() (sunau.AU_read 的方法):   AU_read 对象.       (line   44)
* readframes() (wave.Wave_read 的方法):  Wave_read对象.      (line   44)
* readinto() (http.client.HTTPResponse 的方法): HTTPResponse 对象.
                                                             (line   16)
* readinto() (io.BufferedIOBase 的方法): I/O 基类.           (line  253)
* readinto() (io.RawIOBase 的方法):      I/O 基类.           (line  173)
* readinto1() (io.BufferedIOBase 的方法): I/O 基类.          (line  265)
* readinto1() (io.BytesIO 的方法):       缓冲流.             (line   45)
* readline (模組):                       readline --- GNU readline 接口.
                                                             (line    6)
* readline() (asyncio.StreamReader 的方法): StreamReader.    (line   21)
* readline() (codecs.StreamReader 的方法): StreamReader 对象.
                                                             (line   49)
* readline() (distutils.text_file.TextFile 的方法): distutils text_file --- The TextFile class.
                                                             (line  111)
* readline() (imaplib.IMAP4 的方法):     IMAP4 对象.         (line  182)
* readline() (io.IOBase 的方法):         I/O 基类.           (line   69)
* readline() (io.TextIOBase 的方法):     文本 I/O<2>.        (line   52)
* readline() (mmap.mmap 的方法):         mmap --- 内存映射文件支持.
                                                             (line  207)
* readlines() (codecs.StreamReader 的方法): StreamReader 对象.
                                                             (line   58)
* readlines() (distutils.text_file.TextFile 的方法): distutils text_file --- The TextFile class.
                                                             (line  124)
* readlines() (io.IOBase 的方法):        I/O 基类.           (line   78)
* readlink() (pathlib.Path 的方法):      方法<2>.            (line  279)
* readlink() (於 os 模組中):             文件和目录.         (line  516)
* readmodule() (於 pyclbr 模組中):       pyclbr --- Python 模块浏览器支持.
                                                             (line   16)
* readmodule_ex() (於 pyclbr 模組中):    pyclbr --- Python 模块浏览器支持.
                                                             (line   25)
* READONLY:                              泛型属性管理.       (line   87)
* readonly (memoryview 的屬性):          内存视图.           (line  384)
* ReadTransport (asyncio 中的類別):      传输层级.           (line   18)
* readuntil() (asyncio.StreamReader 的方法): StreamReader.   (line   38)
* readv() (於 os 模組中):                文件描述符操作.     (line  573)
* ready() (multiprocessing.pool.AsyncResult 的方法): 进程池. (line  174)
* read_all() (telnetlib.Telnet 的方法):  Telnet 对象.        (line   15)
* read_binary() (於 importlib.resources 模組中): importlib resources -- 资源.
                                                             (line   95)
* read_byte() (mmap.mmap 的方法):        mmap --- 内存映射文件支持.
                                                             (line  203)
* read_bytes() (importlib.abc.Traversable 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  564)
* read_bytes() (pathlib.Path 的方法):    方法<2>.            (line  253)
* read_bytes() (zipfile.Path 的方法):    Path 对象.          (line   55)
* read_dict() (configparser.ConfigParser 的方法): ConfigParser 对象.
                                                             (line  150)
* read_eager() (telnetlib.Telnet 的方法): Telnet 对象.       (line   32)
* read_environ() (於 wsgiref.handlers 模組中): wsgiref handlers -- 服务器/网关基类.
                                                             (line  250)
* read_events() (xml.etree.ElementTree.XMLPullParser 的方法): XMLPullParser对象.
                                                             (line   26)
* read_file() (configparser.ConfigParser 的方法): ConfigParser 对象.
                                                             (line  130)
* read_history_file() (於 readline 模組中): 历史文件.        (line    8)
* read_init_file() (於 readline 模組中): 初始化文件.         (line   13)
* read_lazy() (telnetlib.Telnet 的方法): Telnet 对象.        (line   40)
* read_mime_types() (於 mimetypes 模組中): mimetypes --- 映射文件名到 MIME 类型.
                                                             (line   81)
* READ_RESTRICTED:                       泛型属性管理.       (line   87)
* read_sb_data() (telnetlib.Telnet 的方法): Telnet 对象.     (line   55)
* read_some() (telnetlib.Telnet 的方法): Telnet 对象.        (line   19)
* read_string() (configparser.ConfigParser 的方法): ConfigParser 对象.
                                                             (line  140)
* read_text() (importlib.abc.Traversable 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  568)
* read_text() (pathlib.Path 的方法):     方法<2>.            (line  265)
* read_text() (zipfile.Path 的方法):     Path 对象.          (line   50)
* read_text() (於 importlib.resources 模組中): importlib resources -- 资源.
                                                             (line  103)
* read_token() (shlex.shlex 的方法):     shlex 对象.         (line   20)
* read_until() (telnetlib.Telnet 的方法): Telnet 对象.       (line    8)
* read_very_eager() (telnetlib.Telnet 的方法): Telnet 对象.  (line   24)
* read_very_lazy() (telnetlib.Telnet 的方法): Telnet 对象.   (line   48)
* read_windows_registry() (mimetypes.MimeTypes 的方法): MimeTypes 对象.
                                                             (line   74)
* Real (numbers 中的類別):               数字的层次.         (line   26)
* real (numbers.Complex 的屬性):         数字的层次.         (line   14)
* Real Media File Format:                chunk --- 读取 IFF 分块数据.
                                                             (line    8)
* realloc():                             總覽<2>.            (line   23)
* realpath() (於 os.path 模組中):        os path --- 常用路径操作.
                                                             (line  263)
* REALTIME_PRIORITY_CLASS (於 subprocess 模組中): Windows 常数.
                                                             (line   81)
* real_max_memuse (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  182)
* real_quick_ratio() (difflib.SequenceMatcher 的方法): SequenceMatcher 对象.
                                                             (line  181)
* reap_children() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  856)
* reap_threads() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  719)
* reason (http.client.HTTPResponse 的屬性): HTTPResponse 对象.
                                                             (line   59)
* reason (ssl.SSLError 的屬性):          异常<12>.           (line   24)
* reason (UnicodeError 的屬性):          具体异常.           (line  313)
* reason (urllib.error.HTTPError 的屬性): urllib error --- urllib request 引发的异常类.
                                                             (line   40)
* reason (urllib.error.URLError 的屬性): urllib error --- urllib request 引发的异常类.
                                                             (line   20)
* reattach() (tkinter.ttk.Treeview 的方法): ttk Treeview.    (line  213)
* rebinding; name:                       赋值语句.           (line    6)
* reccontrols() (ossaudiodev.oss_mixer_device 的方法): Mixer Device Objects.
                                                             (line   53)
* received_data (smtpd.SMTPChannel 的屬性): SMTPChannel 对象.
                                                             (line   71)
* received_lines (smtpd.SMTPChannel 的屬性): SMTPChannel 对象.
                                                             (line   49)
* recent() (imaplib.IMAP4 的方法):       IMAP4 对象.         (line  186)
* reconfigure() (io.TextIOWrapper 的方法): 文本 I/O<2>.      (line  150)
* records (unittest.TestCase 的屬性):    测试用例.           (line  426)
* record_original_stdout() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  435)
* rect() (於 cmath 模組中):              到极坐标和从极坐标的转换.
                                                             (line   40)
* rectangle() (於 curses.textpad 模組中): curses textpad --- 用于 curses 程序的文本输入控件.
                                                             (line   13)
* RecursionError:                        具体异常.           (line  158)
* recursive_repr() (於 reprlib 模組中):  reprlib --- 另一种 repr 实现.
                                                             (line   34)
* recv() (asyncore.dispatcher 的方法):   asyncore --- 异步套接字处理器.
                                                             (line  166)
* recv() (multiprocessing.connection.Connection 的方法): 连接（Connection）对象.
                                                             (line   22)
* recv() (socket.socket 的方法):         套接字对象.         (line  187)
* recvfrom() (socket.socket 的方法):     套接字对象.         (line  200)
* recvfrom_into() (socket.socket 的方法): 套接字对象.        (line  304)
* recvmsg() (socket.socket 的方法):      套接字对象.         (line  215)
* recvmsg_into() (socket.socket 的方法): 套接字对象.         (line  271)
* recv_bytes() (multiprocessing.connection.Connection 的方法): 连接（Connection）对象.
                                                             (line   59)
* recv_bytes_into() (multiprocessing.connection.Connection 的方法): 连接（Connection）对象.
                                                             (line   71)
* recv_fds() (於 socket 模組中):         其他功能.           (line  366)
* recv_into() (socket.socket 的方法):    套接字对象.         (line  312)
* redirect_request() (urllib.request.HTTPRedirectHandler 的方法): HTTPRedirectHandler 对象.
                                                             (line   13)
* redirect_stderr() (於 contextlib 模組中): 工具.            (line  235)
* redirect_stdout() (於 contextlib 模組中): 工具.            (line  197)
* redisplay() (於 readline 模組中):      行缓冲区.           (line   17)
* redrawln() (curses.window 的方法):     Window 对象.        (line  395)
* redrawwin() (curses.window 的方法):    Window 对象.        (line  400)
* reduce (2to3 fixer):                   修复器.             (line  260)
* reduce() (於 functools 模組中):        functools --- 高阶函数和可调用对象上的操作.
                                                             (line  308)
* reducer_override() (pickle.Pickler 的方法): 模块接口.      (line  178)
* ref (weakref 中的類別):                weakref --- 弱引用. (line   70)
* refcount_test() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  712)
* reference counting:                    对象、值与类型.     (line   29)
* reference count（參照計數）:           術語表.             (line 1002)
* ReferenceError:                        具体异常.           (line  165)
* ReferenceType (於 weakref 模組中):     weakref --- 弱引用. (line  243)
* refold_source (email.policy.EmailPolicy 的屬性): email policy Policy 对象.
                                                             (line  298)
* refresh() (curses.window 的方法):      Window 对象.        (line  404)
* register() (abc.ABCMeta 的方法):       abc --- 抽象基类.   (line   58)
* register() (multiprocessing.managers.BaseManager 的方法): 管理器.
                                                             (line   66)
* register() (select.devpoll 的方法):    /dev/poll 轮询对象. (line   30)
* register() (select.epoll 的方法):      边缘触发和水平触发的轮询 epoll 对象.
                                                             (line   79)
* register() (select.poll 的方法):       Poll 对象.          (line   12)
* register() (selectors.BaseSelector 的方法): 类<2>.         (line   61)
* register() (於 atexit 模組中):         atexit --- 退出处理器.
                                                             (line   19)
* register() (於 codecs 模組中):         codecs --- 编解码器注册和相关基类.
                                                             (line  128)
* register() (於 faulthandler 模組中):   转储用户信号的跟踪信息。.
                                                             (line    6)
* register() (於 webbrowser 模組中):     webbrowser --- 方便的Web浏览器控制器.
                                                             (line   69)
* registerDOMImplementation() (於 xml.dom 模組中): 模块内容<6>.
                                                             (line    8)
* registerResult() (於 unittest 模組中): 信号处理.           (line   35)
* register_adapter() (於 sqlite3 模組中): 模块函数和常量.    (line  148)
* register_archive_format() (於 shutil 模組中): 归档操作.    (line   77)
* register_at_fork() (於 os 模組中):     进程管理.           (line  412)
* register_converter() (於 sqlite3 模組中): 模块函数和常量.  (line  140)
* register_defect() (email.policy.Policy 的方法): email policy Policy 对象.
                                                             (line  186)
* register_dialect() (於 csv 模組中):    模块内容<3>.        (line   59)
* register_error() (於 codecs 模組中):   错误处理方案.       (line   75)
* register_function() (xmlrpc.server.CGIXMLRPCRequestHandler 的方法): CGIXMLRPCRequestHandler.
                                                             (line    9)
* register_function() (xmlrpc.server.SimpleXMLRPCServer 的方法): SimpleXMLRPCServer 对象.
                                                             (line    9)
* register_instance() (xmlrpc.server.CGIXMLRPCRequestHandler 的方法): CGIXMLRPCRequestHandler.
                                                             (line   23)
* register_instance() (xmlrpc.server.SimpleXMLRPCServer 的方法): SimpleXMLRPCServer 对象.
                                                             (line   23)
* register_introspection_functions() (xmlrpc.server.CGIXMLRPCRequestHandler 的方法): CGIXMLRPCRequestHandler.
                                                             (line   33)
* register_introspection_functions() (xmlrpc.server.SimpleXMLRPCServer 的方法): SimpleXMLRPCServer 对象.
                                                             (line   44)
* register_multicall_functions() (xmlrpc.server.CGIXMLRPCRequestHandler 的方法): CGIXMLRPCRequestHandler.
                                                             (line   39)
* register_multicall_functions() (xmlrpc.server.SimpleXMLRPCServer 的方法): SimpleXMLRPCServer 对象.
                                                             (line   49)
* register_namespace() (於 xml.etree.ElementTree 模組中): 函数<7>.
                                                             (line  164)
* register_optionflag() (於 doctest 模組中): 选项标记.       (line  142)
* register_shape() (於 turtle 模組中):   设置与特殊方法.     (line   68)
* register_unpack_format() (於 shutil 模組中): 归档操作.     (line  117)
* regular package（正規套件）:           術語表.             (line 1009)
* REG_BINARY (於 winreg 模組中):         注册表值的类型.     (line    8)
* REG_DWORD (於 winreg 模組中):          注册表值的类型.     (line   12)
* REG_DWORD_BIG_ENDIAN (於 winreg 模組中): 注册表值的类型.   (line   20)
* REG_DWORD_LITTLE_ENDIAN (於 winreg 模組中): 注册表值的类型.
                                                             (line   16)
* REG_EXPAND_SZ (於 winreg 模組中):      注册表值的类型.     (line   24)
* REG_FULL_RESOURCE_DESCRIPTOR (於 winreg 模組中): 注册表值的类型.
                                                             (line   57)
* REG_LINK (於 winreg 模組中):           注册表值的类型.     (line   28)
* REG_MULTI_SZ (於 winreg 模組中):       注册表值的类型.     (line   32)
* REG_NONE (於 winreg 模組中):           注册表值的类型.     (line   37)
* REG_QWORD (於 winreg 模組中):          注册表值的类型.     (line   41)
* REG_QWORD_LITTLE_ENDIAN (於 winreg 模組中): 注册表值的类型.
                                                             (line   47)
* REG_RESOURCE_LIST (於 winreg 模組中):  注册表值的类型.     (line   53)
* REG_RESOURCE_REQUIREMENTS_LIST (於 winreg 模組中): 注册表值的类型.
                                                             (line   61)
* REG_SZ (於 winreg 模組中):             注册表值的类型.     (line   65)
* relative; import:                      import 语句.        (line   82)
* relative; URL:                         urllib parse 用于解析 URL.
                                                             (line    8)
* relative_to() (pathlib.PurePath 的方法): 方法和特征属性.   (line  248)
* release() (asyncio.Condition 的方法):  Condition.          (line   71)
* release() (asyncio.Lock 的方法):       Lock.               (line   46)
* release() (asyncio.Semaphore 的方法):  Semaphore.          (line   52)
* release() (logging.Handler 的方法):    处理器对象.         (line   27)
* release() (memoryview 的方法):         内存视图.           (line  215)
* release() (multiprocessing.Lock 的方法): 同步原语.         (line   77)
* release() (multiprocessing.RLock 的方法): 同步原语.        (line  118)
* release() (pickle.PickleBuffer 的方法): 模块接口.          (line  284)
* release() (threading.Condition 的方法): 条件对象.          (line   76)
* release() (threading.Lock 的方法):     锁对象.             (line   58)
* release() (threading.RLock 的方法):    递归锁对象.         (line   50)
* release() (threading.Semaphore 的方法): 信号量对象.        (line   55)
* release() (_thread.lock 的方法):       _thread --- 底层多线程 API.
                                                             (line  122)
* release() (於 platform 模組中):        跨平台.             (line  102)
* releasebufferproc (C 型態):            Slot Type typedefs. (line   96)
* release_lock() (於 imp 模組中):        imp —— 由代码内部访问 import 。.
                                                             (line  285)
* reload (2to3 fixer):                   修复器.             (line  264)
* reload() (於 imp 模組中):              imp —— 由代码内部访问 import 。.
                                                             (line  131)
* reload() (於 importlib 模組中):        函数<11>.           (line   65)
* relpath() (於 os.path 模組中):         os path --- 常用路径操作.
                                                             (line  276)
* remainder() (decimal.Context 的方法):  上下文对象.         (line  413)
* remainder() (於 math 模組中):          数论与表示函数.     (line  208)
* remainder_near() (decimal.Context 的方法): 上下文对象.     (line  419)
* remainder_near() (decimal.Decimal 的方法): Decimal 对象.   (line  421)
* RemoteDisconnected:                    http client --- HTTP 协议客户端.
                                                             (line  165)
* remove() (array.array 的方法):         array --- 高效率的數值型態陣列.
                                                             (line  177)
* remove() (collections.deque 的方法):   deque 对象.         (line   87)
* remove() (frozenset 的方法):           集合类型 --- set frozenset.
                                                             (line  179)
* remove() (mailbox.Mailbox 的方法):     Mailbox 对象.       (line   58)
* remove() (mailbox.MH 的方法):          MH.                 (line   68)
* remove() (sequence method):            可变序列类型.       (line   14)
* remove() (xml.etree.ElementTree.Element 的方法): 元素对象. (line  144)
* remove() (於 os 模組中):               文件和目录.         (line  546)
* removeAttribute() (xml.dom.Element 的方法): 元素对象<2>.   (line   48)
* removeAttributeNode() (xml.dom.Element 的方法): 元素对象<2>.
                                                             (line   53)
* removeAttributeNS() (xml.dom.Element 的方法): 元素对象<2>. (line   58)
* removeChild() (xml.dom.Node 的方法):   节点对象.           (line  111)
* removedirs() (於 os 模組中):           文件和目录.         (line  567)
* removeFilter() (logging.Handler 的方法): 处理器对象.       (line   50)
* removeFilter() (logging.Logger 的方法): 记录器对象.        (line  212)
* removeHandler() (logging.Logger 的方法): 记录器对象.       (line  227)
* removeHandler() (於 unittest 模組中):  信号处理.           (line   52)
* removeprefix() (bytearray 的方法):     bytes 和 bytearray 操作.
                                                             (line   41)
* removeprefix() (bytes 的方法):         bytes 和 bytearray 操作.
                                                             (line   41)
* removeprefix() (str 的方法):           字符串的方法<2>.    (line  311)
* removeResult() (於 unittest 模組中):   信号处理.           (line   46)
* removesuffix() (bytearray 的方法):     bytes 和 bytearray 操作.
                                                             (line   59)
* removesuffix() (bytes 的方法):         bytes 和 bytearray 操作.
                                                             (line   59)
* removesuffix() (str 的方法):           字符串的方法<2>.    (line  323)
* removexattr() (於 os 模組中):          Linux 扩展属性.     (line   38)
* remove_child_handler() (asyncio.AbstractChildWatcher 的方法): 进程监视器.
                                                             (line   44)
* remove_done_callback() (asyncio.Future 的方法): Future 对象<2>.
                                                             (line   92)
* remove_done_callback() (asyncio.Task 的方法): Task 对象.   (line  146)
* remove_flag() (mailbox.MaildirMessage 的方法): MaildirMessage.
                                                             (line   76)
* remove_flag() (mailbox.mboxMessage 的方法): mboxMessage.   (line   73)
* remove_flag() (mailbox.MMDFMessage 的方法): MMDFMessage.   (line   72)
* remove_folder() (mailbox.Maildir 的方法): Maildir.         (line   64)
* remove_folder() (mailbox.MH 的方法):   MH.                 (line   42)
* remove_header() (urllib.request.Request 的方法): Request 对象.
                                                             (line   87)
* remove_history_item() (於 readline 模組中): 历史列表.      (line   23)
* remove_label() (mailbox.BabylMessage 的方法): BabylMessage.
                                                             (line   56)
* remove_option() (configparser.ConfigParser 的方法): ConfigParser 对象.
                                                             (line  236)
* remove_option() (optparse.OptionParser 的方法): Querying and manipulating your option parser.
                                                             (line   47)
* remove_pyc() (msilib.Directory 的方法): Directory Objects. (line   46)
* remove_reader() (asyncio.loop 的方法): 监控文件描述符.     (line   11)
* remove_section() (configparser.ConfigParser 的方法): ConfigParser 对象.
                                                             (line  242)
* remove_sequence() (mailbox.MHMessage 的方法): MHMessage.   (line   42)
* remove_signal_handler() (asyncio.loop 的方法): Unix 信号.  (line   23)
* remove_tree() (於 distutils.dir_util 模組中): distutils dir_util --- Directory tree operations.
                                                             (line   60)
* remove_writer() (asyncio.loop 的方法): 监控文件描述符.     (line   23)
* rename() (ftplib.FTP 的方法):          FTP 对象.           (line  166)
* rename() (imaplib.IMAP4 的方法):       IMAP4 对象.         (line  191)
* rename() (pathlib.Path 的方法):        方法<2>.            (line  290)
* rename() (於 os 模組中):               文件和目录.         (line  582)
* renames (2to3 fixer):                  修复器.             (line  268)
* renames() (於 os 模組中):              文件和目录.         (line  610)
* reopenIfNeeded() (logging.handlers.WatchedFileHandler 的方法): WatchedFileHandler.
                                                             (line   35)
* reorganize() (dbm.gnu.gdbm 的方法):    dbm gnu --- GNU 对 dbm 的重解析.
                                                             (line   87)
* repeat() (timeit.Timer 的方法):        Python 接口.        (line   87)
* repeat() (於 itertools 模組中):        Itertool函数.       (line  446)
* repeat() (於 timeit 模組中):           Python 接口.        (line   17)
* repetition; operation:                 通用序列操作.       (line   17)
* replace() (bytearray 的方法):          bytes 和 bytearray 操作.
                                                             (line  167)
* replace() (bytes 的方法):              bytes 和 bytearray 操作.
                                                             (line  167)
* replace() (curses.panel.Panel 的方法): Panel 对象.         (line   36)
* replace() (datetime.date 的方法):      date 对象.          (line  153)
* replace() (datetime.datetime 的方法):  datetime 对象.      (line  376)
* replace() (datetime.time 的方法):      time 对象.          (line  124)
* replace() (inspect.Parameter 的方法):  Introspecting callables with the Signature object.
                                                             (line  252)
* replace() (inspect.Signature 的方法):  Introspecting callables with the Signature object.
                                                             (line  110)
* replace() (pathlib.Path 的方法):       方法<2>.            (line  311)
* replace() (str 的方法):                字符串的方法<2>.    (line  335)
* replace() (types.CodeType 的方法):     标准解释器类型.     (line   55)
* replace() (於 dataclasses 模組中):     模块级装饰器、类和函数.
                                                             (line  304)
* replace() (於 os 模組中):              文件和目录.         (line  624)
* replaceChild() (xml.dom.Node 的方法):  节点对象.           (line  117)
* ReplacePackage() (於 modulefinder 模組中): modulefinder --- 查找脚本使用的模块.
                                                             (line   18)
* replace_errors() (於 codecs 模組中):   错误处理方案.       (line  110)
* replace_header() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  246)
* replace_header() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  342)
* replace_history_item() (於 readline 模組中): 历史列表.     (line   28)
* replace_whitespace (textwrap.TextWrapper 的屬性): textwrap --- 文本自动换行与填充.
                                                             (line  165)
* report() (filecmp.dircmp 的方法):      dircmp 类.          (line   17)
* report() (modulefinder.ModuleFinder 的方法): modulefinder --- 查找脚本使用的模块.
                                                             (line   32)
* REPORTING_FLAGS (於 doctest 模組中):   选项标记.           (line  135)
* REPORT_CDIFF (於 doctest 模組中):      选项标记.           (line  104)
* report_failure() (doctest.DocTestRunner 的方法): DocTestRunner 对象.
                                                             (line   61)
* report_full_closure() (filecmp.dircmp 的方法): dircmp 类.  (line   25)
* REPORT_NDIFF (於 doctest 模組中):      选项标记.           (line  108)
* REPORT_ONLY_FIRST_FAILURE (於 doctest 模組中): 选项标记.   (line  117)
* report_partial_closure() (filecmp.dircmp 的方法): dircmp 类.
                                                             (line   21)
* report_start() (doctest.DocTestRunner 的方法): DocTestRunner 对象.
                                                             (line   42)
* report_success() (doctest.DocTestRunner 的方法): DocTestRunner 对象.
                                                             (line   51)
* REPORT_UDIFF (於 doctest 模組中):      选项标记.           (line  100)
* report_unexpected_exception() (doctest.DocTestRunner 的方法): DocTestRunner 对象.
                                                             (line   71)
* repr (2to3 fixer):                     修复器.             (line  272)
* Repr (reprlib 中的類別):               reprlib --- 另一种 repr 实现.
                                                             (line   15)
* repr() (built-in function); __repr__() (object method): 基本定制.
                                                             (line   92)
* repr() (reprlib.Repr 的方法):          Repr 对象.          (line   40)
* repr() (內建函式):                     內建函式.           (line 1218)
* repr() (於 reprlib 模組中):            reprlib --- 另一种 repr 实现.
                                                             (line   26)
* repr1() (reprlib.Repr 的方法):         Repr 对象.          (line   44)
* reprfunc (C 型態):                     Slot Type typedefs. (line   38)
* reprlib (模組):                        reprlib --- 另一种 repr 实现.
                                                             (line    6)
* Request (urllib.request 中的類別):     urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  151)
* request() (http.client.HTTPConnection 的方法): HTTPConnection 对象.
                                                             (line    8)
* RequestHandlerClass (socketserver.BaseServer 的屬性): Server 对象<2>.
                                                             (line   63)
* requestline (http.server.BaseHTTPRequestHandler 的屬性): http server --- HTTP 服务器.
                                                             (line   70)
* request_queue_size (socketserver.BaseServer 的屬性): Server 对象<2>.
                                                             (line   87)
* request_rate() (urllib.robotparser.RobotFileParser 的方法): urllib robotparser --- robots txt 语法分析程序.
                                                             (line   54)
* request_uri() (於 wsgiref.util 模組中): wsgiref util -- WSGI 环境工具.
                                                             (line   21)
* request_version (http.server.BaseHTTPRequestHandler 的屬性): http server --- HTTP 服务器.
                                                             (line   86)
* requires() (於 test.support 模組中):   test support --- Utilities for the Python test suite.
                                                             (line  271)
* requires_bz2() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  681)
* requires_docstrings() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  693)
* requires_freebsd_version() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  651)
* requires_gzip() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  677)
* requires_IEEE_754() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  669)
* requires_linux_version() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  657)
* requires_lzma() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  685)
* requires_mac_version() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  663)
* requires_resource() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  689)
* requires_zlib() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  673)
* RERAISE (opcode):                      Python字节码说明.   (line  361)
* reserved (zipfile.ZipInfo 的屬性):     ZipInfo 对象.       (line  101)
* reserved word:                         关键字.             (line    6)
* RESERVED_FUTURE (於 uuid 模組中):      uuid --- RFC 4122 定义的UUID对象.
                                                             (line  215)
* RESERVED_MICROSOFT (於 uuid 模組中):   uuid --- RFC 4122 定义的UUID对象.
                                                             (line  211)
* RESERVED_NCS (於 uuid 模組中):         uuid --- RFC 4122 定义的UUID对象.
                                                             (line  203)
* reset() (bdb.Bdb 的方法):              bdb --- Debugger framework.
                                                             (line  106)
* reset() (codecs.IncrementalDecoder 的方法): IncrementalDecoder 对象.
                                                             (line   33)
* reset() (codecs.IncrementalEncoder 的方法): IncrementalEncoder 对象.
                                                             (line   30)
* reset() (codecs.StreamReader 的方法):  StreamReader 对象.  (line   68)
* reset() (codecs.StreamWriter 的方法):  StreamWriter 对象.  (line   36)
* reset() (contextvars.ContextVar 的方法): 上下文变量.       (line   49)
* reset() (html.parser.HTMLParser 的方法): HTMLParser 方法.  (line   21)
* reset() (ossaudiodev.oss_audio_device 的方法): 音频设备对象.
                                                             (line  155)
* reset() (pipes.Template 的方法):       模板对象.           (line    8)
* reset() (threading.Barrier 的方法):    栅栏对象.           (line   62)
* reset() (xdrlib.Packer 的方法):        Packer 对象.        (line   12)
* reset() (xdrlib.Unpacker 的方法):      Unpacker 对象.      (line    8)
* reset() (xml.dom.pulldom.DOMEventStream 的方法): DOMEventStream 对象.
                                                             (line   35)
* reset() (xml.sax.xmlreader.IncrementalParser 的方法): IncrementalParser 对象.
                                                             (line   17)
* reset() (於 turtle 模組中):            更多绘图控制.       (line    6)
* resetbuffer() (code.InteractiveConsole 的方法): 交互式控制台对象.
                                                             (line   33)
* resetlocale() (於 locale 模組中):      locale --- 国际化服务.
                                                             (line  303)
* resetscreen() (於 turtle 模組中):      窗口控制.           (line   53)
* resetty() (於 curses 模組中):          函数<4>.            (line  336)
* resetwarnings() (於 warnings 模組中):  可用的函数.         (line   78)
* reset_mock() (unittest.mock.AsyncMock 的方法): Mock 类.    (line  841)
* reset_mock() (unittest.mock.Mock 的方法): Mock 类.         (line  179)
* reset_peak() (於 tracemalloc 模組中):  函数<10>.           (line   38)
* reset_prog_mode() (於 curses 模組中):  函数<4>.            (line  326)
* reset_shell_mode() (於 curses 模組中): 函数<4>.            (line  331)
* reset_tzpath() (於 zoneinfo 模組中):   函数<2>.            (line   22)
* resize() (curses.window 的方法):       Window 对象.        (line  418)
* resize() (mmap.mmap 的方法):           mmap --- 内存映射文件支持.
                                                             (line  212)
* resize() (於 ctypes 模組中):           工具函数.           (line  142)
* resizemode() (於 turtle 模組中):       外观.               (line   23)
* resizeterm() (於 curses 模組中):       函数<4>.            (line  348)
* resize_term() (於 curses 模組中):      函数<4>.            (line  340)
* resolution (datetime.date 的屬性):     date 对象.          (line   88)
* resolution (datetime.datetime 的屬性): datetime 对象.      (line  236)
* resolution (datetime.time 的屬性):     time 对象.          (line   38)
* resolution (datetime.timedelta 的屬性): timedelta 类对象.  (line   79)
* resolve() (pathlib.Path 的方法):       方法<2>.            (line  322)
* resolveEntity() (xml.sax.handler.EntityResolver 的方法): EntityResolver 对象.
                                                             (line    6)
* resolve_bases() (於 types 模組中):     动态类型创建.       (line   48)
* resolve_name() (於 importlib.util 模組中): importlib util —— 导入器的工具程序代码.
                                                             (line   71)
* resolve_name() (於 pkgutil 模組中):    pkgutil --- 包扩展工具.
                                                             (line  226)
* Resource (於 importlib.resources 模組中): importlib resources -- 资源.
                                                             (line   38)
* resource (模組):                       resource --- 资源使用信息.
                                                             (line    6)
* ResourceDenied:                        test support --- Utilities for the Python test suite.
                                                             (line   22)
* ResourceLoader (importlib.abc 中的類別): importlib abc —— 关于导入的抽象基类.
                                                             (line  305)
* ResourceReader (importlib.abc 中的類別): importlib abc —— 关于导入的抽象基类.
                                                             (line  248)
* ResourceWarning:                       警告.               (line   66)
* resource_path() (importlib.abc.ResourceReader 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  280)
* response (nntplib.NNTPError 的屬性):   nntplib --- NNTP 协议客户端.
                                                             (line  119)
* response() (imaplib.IMAP4 的方法):     IMAP4 对象.         (line  195)
* ResponseNotReady:                      http client --- HTTP 协议客户端.
                                                             (line  151)
* responses (http.server.BaseHTTPRequestHandler 的屬性): http server --- HTTP 服务器.
                                                             (line  148)
* responses (於 http.client 模組中):     http client --- HTTP 协议客户端.
                                                             (line  184)
* restart (pdb command):                 调试器命令.         (line  267)
* restore() (於 difflib 模組中):         difflib --- 计算差异的辅助工具.
                                                             (line  233)
* RESTRICTED:                            泛型属性管理.       (line   87)
* restricted; execution:                 内置命名空间和受限的执行.
                                                             (line    6)
* restype (ctypes._FuncPtr 的屬性):      外部函数.           (line   18)
* result() (asyncio.Future 的方法):      Future 对象<2>.     (line   22)
* result() (asyncio.Task 的方法):        Task 对象.          (line  111)
* result() (concurrent.futures.Future 的方法): Future 对象.  (line   32)
* results() (trace.Trace 的方法):        编程接口.           (line   33)
* resume_reading() (asyncio.ReadTransport 的方法): 只读传输. (line   19)
* resume_writing() (asyncio.BaseProtocol 的方法): 基础协议<2>.
                                                             (line   39)
* retr() (poplib.POP3 的方法):           POP3 对象.          (line   56)
* retrbinary() (ftplib.FTP 的方法):      FTP 对象.           (line   69)
* retrieve() (urllib.request.URLopener 的方法): 沿袭的接口.  (line   94)
* retrlines() (ftplib.FTP 的方法):       FTP 对象.           (line   78)
* Return (ast 中的類別):                 Function and class definitions.
                                                             (line  117)
* return (pdb command):                  调试器命令.         (line  153)
* returncode (asyncio.asyncio.subprocess.Process 的屬性): 与子进程交互.
                                                             (line  128)
* returncode (subprocess.CalledProcessError 的屬性): 使用 subprocess 模块.
                                                             (line  176)
* returncode (subprocess.CompletedProcess 的屬性): 使用 subprocess 模块.
                                                             (line   85)
* returncode (subprocess.Popen 的屬性):  Popen 对象.         (line  128)
* return_annotation (inspect.Signature 的屬性): Introspecting callables with the Signature object.
                                                             (line   89)
* return_ok() (http.cookiejar.CookiePolicy 的方法): CookiePolicy 对象.
                                                             (line   15)
* RETURN_VALUE (opcode):                 Python字节码说明.   (line  323)
* return_value (unittest.mock.Mock 的屬性): Mock 类.         (line  302)
* retval (pdb command):                  调试器命令.         (line  284)
* reverse() (array.array 的方法):        array --- 高效率的數值型態陣列.
                                                             (line  181)
* reverse() (collections.deque 的方法):  deque 对象.         (line   92)
* reverse() (sequence method):           可变序列类型.       (line   14)
* reverse() (於 audioop 模組中):         audioop --- 处理原始音频数据.
                                                             (line  165)
* reversed() (內建函式):                 內建函式.           (line 1227)
* reverse_order() (pstats.Stats 的方法): Stats 类.           (line  157)
* reverse_pointer (ipaddress.IPv4Address 的屬性): 地址对象.  (line   74)
* reverse_pointer (ipaddress.IPv6Address 的屬性): 地址对象.  (line  193)
* Reversible (collections.abc 中的類別): 容器抽象基类.       (line  141)
* Reversible (typing 中的類別):          collections abc 对应的其他类型.
                                                             (line   57)
* revert() (http.cookiejar.FileCookieJar 的方法): CookieJar 和 FileCookieJar 对象.
                                                             (line  128)
* rewind() (aifc.aifc 的方法):           aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line   89)
* rewind() (sunau.AU_read 的方法):       AU_read 对象.       (line   49)
* rewind() (wave.Wave_read 的方法):      Wave_read对象.      (line   48)
* rfc2109 (http.cookiejar.Cookie 的屬性): Cookie 对象<2>.    (line   64)
* rfc2109_as_netscape (http.cookiejar.DefaultCookiePolicy 的屬性): DefaultCookiePolicy 对象.
                                                             (line   75)
* rfc2965 (http.cookiejar.CookiePolicy 的屬性): CookiePolicy 对象.
                                                             (line   60)
* rfc822_escape() (於 distutils.util 模組中): distutils util --- Miscellaneous other utility functions.
                                                             (line  191)
* RFC; RFC 1014:                         xdrlib --- 编码与解码 XDR 数据.
                                                             (line   10)
* RFC; RFC 1014 <1>:                     xdrlib --- 编码与解码 XDR 数据.
                                                             (line   30)
* RFC; RFC 1123:                         函数<3>.            (line  535)
* RFC; RFC 1321:                         hashlib --- 安全哈希与消息摘要.
                                                             (line   12)
* RFC; RFC 1422:                         证书.               (line   26)
* RFC; RFC 1422 <1>:                     LibreSSL 支持.      (line   28)
* RFC; RFC 1521:                         base64 —— Base16、Base32、Base64、Base85 資料編碼.
                                                             (line  226)
* RFC; RFC 1521 <1>:                     quopri --- 编码与解码经过 MIME 转码的可打印数据.
                                                             (line   10)
* RFC; RFC 1521 <2>:                     quopri --- 编码与解码经过 MIME 转码的可打印数据.
                                                             (line   32)
* RFC; RFC 1522:                         binascii --- 二进制和 ASCII 码互转.
                                                             (line   62)
* RFC; RFC 1522 <1>:                     quopri --- 编码与解码经过 MIME 转码的可打印数据.
                                                             (line   22)
* RFC; RFC 1522 <2>:                     quopri --- 编码与解码经过 MIME 转码的可打印数据.
                                                             (line   33)
* RFC; RFC 1524:                         mailcap --- Mailcap 文件处理.
                                                             (line   17)
* RFC; RFC 1524 <1>:                     mailcap --- Mailcap 文件处理.
                                                             (line   31)
* RFC; RFC 1730:                         imaplib --- IMAP4 协议客户端.
                                                             (line   12)
* RFC; RFC 1738:                         URL 转码.           (line  160)
* RFC; RFC 1750:                         随机生成.           (line   59)
* RFC; RFC 1766:                         locale --- 国际化服务.
                                                             (line  265)
* RFC; RFC 1766 <1>:                     locale --- 国际化服务.
                                                             (line  274)
* RFC; RFC 1808:                         urllib.             (line   23)
* RFC; RFC 1808 <1>:                     URL 解析.           (line   41)
* RFC; RFC 1808 <2>:                     URL 转码.           (line  155)
* RFC; RFC 1832:                         xdrlib --- 编码与解码 XDR 数据.
                                                             (line   33)
* RFC; RFC 1832 <1>:                     xdrlib --- 编码与解码 XDR 数据.
                                                             (line   35)
* RFC; RFC 1869:                         smtplib ---SMTP协议客户端.
                                                             (line   12)
* RFC; RFC 1869 <1>:                     smtplib ---SMTP协议客户端.
                                                             (line  162)
* RFC; RFC 1870:                         smtpd<3>.           (line    7)
* RFC; RFC 1870 <1>:                     smtpd --- SMTP 服务器.
                                                             (line   24)
* RFC; RFC 1870 <2>:                     SMTPChannel 对象.   (line  109)
* RFC; RFC 1939:                         poplib --- POP3 协议客户端.
                                                             (line   11)
* RFC; RFC 1939 <1>:                     poplib --- POP3 协议客户端.
                                                             (line   11)
* RFC; RFC 2033:                         新增和改进的模块<2>.
                                                             (line  568)
* RFC; RFC 2045:                         email --- 电子邮件与 MIME 处理包.
                                                             (line   14)
* RFC; RFC 2045 <1>:                     email message 表示一封电子邮件信息.
                                                             (line  259)
* RFC; RFC 2045 <2>:                     email message 表示一封电子邮件信息.
                                                             (line  260)
* RFC; RFC 2045 <3>:                     email message 表示一封电子邮件信息.
                                                             (line  263)
* RFC; RFC 2045 <4>:                     email headerregistry 自定义标头对象.
                                                             (line  192)
* RFC; RFC 2045 <5>:                     email headerregistry 自定义标头对象.
                                                             (line  246)
* RFC; RFC 2045 <6>:                     email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  353)
* RFC; RFC 2045 <7>:                     email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  356)
* RFC; RFC 2045 <8>:                     email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  358)
* RFC; RFC 2045 <9>:                     email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  437)
* RFC; RFC 2045 <10>:                    email header 国际化标头.
                                                             (line   24)
* RFC; RFC 2045 <11>:                    base64 —— Base16、Base32、Base64、Base85 資料編碼.
                                                             (line   23)
* RFC; RFC 2045 <12>:                    base64 —— Base16、Base32、Base64、Base85 資料編碼.
                                                             (line   24)
* RFC; RFC 2045 <13>:                    base64 —— Base16、Base32、Base64、Base85 資料編碼.
                                                             (line  198)
* RFC; RFC 2045 <14>:                    base64 —— Base16、Base32、Base64、Base85 資料編碼.
                                                             (line  204)
* RFC; RFC 2045#section-6.8:             Binary 对象.        (line   28)
* RFC; RFC 2046:                         email --- 电子邮件与 MIME 处理包.
                                                             (line   14)
* RFC; RFC 2046 <1>:                     内容管理器实例.     (line   73)
* RFC; RFC 2046 <2>:                     email header 国际化标头.
                                                             (line   24)
* RFC; RFC 2047:                         PEP 3333 Python Web服务器网关接口v1 0 1.
                                                             (line   21)
* RFC; RFC 2047 <1>:                     email<5>.           (line   27)
* RFC; RFC 2047 <2>:                     email --- 电子邮件与 MIME 处理包.
                                                             (line   14)
* RFC; RFC 2047 <3>:                     email policy Policy 对象.
                                                             (line  277)
* RFC; RFC 2047 <4>:                     email policy Policy 对象.
                                                             (line  280)
* RFC; RFC 2047 <5>:                     email headerregistry 自定义标头对象.
                                                             (line   64)
* RFC; RFC 2047 <6>:                     email headerregistry 自定义标头对象.
                                                             (line  101)
* RFC; RFC 2047 <7>:                     email headerregistry 自定义标头对象.
                                                             (line  103)
* RFC; RFC 2047 <8>:                     email header 国际化标头.
                                                             (line   25)
* RFC; RFC 2047 <9>:                     email header 国际化标头.
                                                             (line   44)
* RFC; RFC 2047 <10>:                    email header 国际化标头.
                                                             (line   94)
* RFC; RFC 2047 <11>:                    email header 国际化标头.
                                                             (line  113)
* RFC; RFC 2047 <12>:                    email utils 其他工具.
                                                             (line   60)
* RFC; RFC 2060:                         imaplib --- IMAP4 协议客户端.
                                                             (line   11)
* RFC; RFC 2060 <1>:                     IMAP4 对象.         (line  285)
* RFC; RFC 2068:                         http cookies --- HTTP状态管理.
                                                             (line   14)
* RFC; RFC 2104:                         新增和改进的模块<3>.
                                                             (line   35)
* RFC; RFC 2104 <1>:                     hmac --- 基于密钥的消息验证.
                                                             (line   10)
* RFC; RFC 2109:                         http cookies --- HTTP状态管理.
                                                             (line   14)
* RFC; RFC 2109 <1>:                     http cookies --- HTTP状态管理.
                                                             (line   31)
* RFC; RFC 2109 <2>:                     http cookies --- HTTP状态管理.
                                                             (line   57)
* RFC; RFC 2109 <3>:                     Morsel 对象.        (line    8)
* RFC; RFC 2109 <4>:                     Morsel 对象.        (line   10)
* RFC; RFC 2109 <5>:                     Morsel 对象.        (line   90)
* RFC; RFC 2109 <6>:                     Morsel 对象.        (line  102)
* RFC; RFC 2109 <7>:                     http cookiejar —— HTTP 客户端的 Cookie 处理.
                                                             (line   15)
* RFC; RFC 2109 <8>:                     http cookiejar —— HTTP 客户端的 Cookie 处理.
                                                             (line   82)
* RFC; RFC 2109 <9>:                     http cookiejar —— HTTP 客户端的 Cookie 处理.
                                                             (line   92)
* RFC; RFC 2109 <10>:                    http cookiejar —— HTTP 客户端的 Cookie 处理.
                                                             (line  116)
* RFC; RFC 2109 <11>:                    DefaultCookiePolicy 对象.
                                                             (line   77)
* RFC; RFC 2109 <12>:                    Cookie 对象<2>.     (line    8)
* RFC; RFC 2109 <13>:                    Cookie 对象<2>.     (line   19)
* RFC; RFC 2109 <14>:                    Cookie 对象<2>.     (line   66)
* RFC; RFC 2183:                         email --- 电子邮件与 MIME 处理包.
                                                             (line   14)
* RFC; RFC 2183 <1>:                     email message 表示一封电子邮件信息.
                                                             (line  383)
* RFC; RFC 2183 <2>:                     email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  527)
* RFC; RFC 2231:                         email --- 电子邮件与 MIME 处理包.
                                                             (line   15)
* RFC; RFC 2231 <1>:                     email message 表示一封电子邮件信息.
                                                             (line  230)
* RFC; RFC 2231 <2>:                     email message 表示一封电子邮件信息.
                                                             (line  302)
* RFC; RFC 2231 <3>:                     email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  320)
* RFC; RFC 2231 <4>:                     email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  322)
* RFC; RFC 2231 <5>:                     email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  411)
* RFC; RFC 2231 <6>:                     email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  417)
* RFC; RFC 2231 <7>:                     email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  444)
* RFC; RFC 2231 <8>:                     email header 国际化标头.
                                                             (line   25)
* RFC; RFC 2231 <9>:                     email utils 其他工具.
                                                             (line  150)
* RFC; RFC 2231 <10>:                    email utils 其他工具.
                                                             (line  154)
* RFC; RFC 2231 <11>:                    email utils 其他工具.
                                                             (line  162)
* RFC; RFC 2231 <12>:                    email utils 其他工具.
                                                             (line  167)
* RFC; RFC 2231 <13>:                    email utils 其他工具.
                                                             (line  175)
* RFC; RFC 2295:                         HTTP 状态码.        (line  189)
* RFC; RFC 2324:                         HTTP 状态码.        (line  136)
* RFC; RFC 2342:                         新增和改进的模块<3>.
                                                             (line   93)
* RFC; RFC 2342 <1>:                     IMAP4 对象.         (line  147)
* RFC; RFC 2368:                         URL 转码.           (line  151)
* RFC; RFC 2373:                         地址对象.           (line   90)
* RFC; RFC 2373 <1>:                     地址对象.           (line  108)
* RFC; RFC 2373 <2>:                     地址对象.           (line  119)
* RFC; RFC 2396:                         urllib parse<3>.    (line    6)
* RFC; RFC 2396 <1>:                     urllib.             (line   24)
* RFC; RFC 2396 <2>:                     URL 解析.           (line  223)
* RFC; RFC 2396 <3>:                     URL 转码.           (line   21)
* RFC; RFC 2396 <4>:                     URL 转码.           (line  147)
* RFC; RFC 2397:                         DataHandler 对象.   (line    8)
* RFC; RFC 2449:                         POP3 对象.          (line   24)
* RFC; RFC 2487:                         新增和改进的模块<3>.
                                                             (line   85)
* RFC; RFC 2595:                         poplib --- POP3 协议客户端.
                                                             (line   12)
* RFC; RFC 2595 <1>:                     POP3 对象.          (line  103)
* RFC; RFC 2616:                         PEP 3333 Python Web服务器网关接口v1 0 1.
                                                             (line   20)
* RFC; RFC 2616 <1>:                     wsgiref util -- WSGI 环境工具.
                                                             (line   96)
* RFC; RFC 2616 <2>:                     wsgiref validate --- WSGI 一致性检查器.
                                                             (line   21)
* RFC; RFC 2616 <3>:                     HTTPRedirectHandler 对象.
                                                             (line    7)
* RFC; RFC 2616 <4>:                     HTTPRedirectHandler 对象.
                                                             (line   23)
* RFC; RFC 2616 <5>:                     沿袭的接口.         (line  133)
* RFC; RFC 2616 <6>:                     urllib error --- urllib request 引发的异常类.
                                                             (line   36)
* RFC; RFC 2616 <7>:                     簡介<15>.           (line   27)
* RFC; RFC 2616 <8>:                     HTTPError.          (line   12)
* RFC; RFC 2616 <9>:                     错误代码.           (line   10)
* RFC; RFC 2640:                         Python API 的变化.  (line   32)
* RFC; RFC 2640 <1>:                     测试<15>.           (line   22)
* RFC; RFC 2640 <2>:                     ftplib --- FTP 协议客户端.
                                                             (line   15)
* RFC; RFC 2640 <3>:                     ftplib --- FTP 协议客户端.
                                                             (line   71)
* RFC; RFC 2640 <4>:                     ftplib --- FTP 协议客户端.
                                                             (line  101)
* RFC; RFC 2732:                         urllib parse<4>.    (line   10)
* RFC; RFC 2732 <1>:                     新增和改进的模块.   (line  638)
* RFC; RFC 2732 <2>:                     URL 转码.           (line  143)
* RFC; RFC 2818:                         ssl<9>.             (line   16)
* RFC; RFC 2818 <1>:                     证书处理.           (line    9)
* RFC; RFC 2821:                         email --- 电子邮件与 MIME 处理包.
                                                             (line   11)
* RFC; RFC 2822:                         新增和改进的模块<3>.
                                                             (line   97)
* RFC; RFC 2822 <1>:                     標準模組庫.         (line   13)
* RFC; RFC 2822 <2>:                     函数<3>.            (line  302)
* RFC; RFC 2822 <3>:                     函数<3>.            (line  535)
* RFC; RFC 2822 <4>:                     email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  227)
* RFC; RFC 2822 <5>:                     email header 国际化标头.
                                                             (line   17)
* RFC; RFC 2822 <6>:                     email header 国际化标头.
                                                             (line   18)
* RFC; RFC 2822 <7>:                     email header 国际化标头.
                                                             (line   24)
* RFC; RFC 2822 <8>:                     email header 国际化标头.
                                                             (line   71)
* RFC; RFC 2822 <9>:                     email header 国际化标头.
                                                             (line   94)
* RFC; RFC 2822 <10>:                    email header 国际化标头.
                                                             (line  108)
* RFC; RFC 2822 <11>:                    email utils 其他工具.
                                                             (line   25)
* RFC; RFC 2822 <12>:                    email utils 其他工具.
                                                             (line   82)
* RFC; RFC 2822 <13>:                    email utils 其他工具.
                                                             (line   85)
* RFC; RFC 2822 <14>:                    email utils 其他工具.
                                                             (line  194)
* RFC; RFC 2822 <15>:                    email utils 其他工具.
                                                             (line  120)
* RFC; RFC 2822 <16>:                    Message 对象.       (line   15)
* RFC; RFC 2822 <17>:                    http client --- HTTP 协议客户端.
                                                             (line   96)
* RFC; RFC 2822 <18>:                    http server --- HTTP 服务器.
                                                             (line   95)
* RFC; RFC 2965:                         urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  186)
* RFC; RFC 2965 <1>:                     urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  192)
* RFC; RFC 2965 <2>:                     Request 对象.       (line   46)
* RFC; RFC 2965 <3>:                     http cookiejar —— HTTP 客户端的 Cookie 处理.
                                                             (line   14)
* RFC; RFC 2965 <4>:                     http cookiejar —— HTTP 客户端的 Cookie 处理.
                                                             (line   81)
* RFC; RFC 2965 <5>:                     http cookiejar —— HTTP 客户端的 Cookie 处理.
                                                             (line   92)
* RFC; RFC 2965 <6>:                     http cookiejar —— HTTP 客户端的 Cookie 处理.
                                                             (line  118)
* RFC; RFC 2965 <7>:                     http cookiejar —— HTTP 客户端的 Cookie 处理.
                                                             (line  120)
* RFC; RFC 2965 <8>:                     FileCookieJar 的子类及其与 Web 浏览器的协同.
                                                             (line   15)
* RFC; RFC 2965 <9>:                     CookiePolicy 对象.  (line   62)
* RFC; RFC 2965 <10>:                    CookiePolicy 对象.  (line   66)
* RFC; RFC 2965 <11>:                    DefaultCookiePolicy 对象.
                                                             (line    8)
* RFC; RFC 2965 <12>:                    DefaultCookiePolicy 对象.
                                                             (line   81)
* RFC; RFC 2965 <13>:                    DefaultCookiePolicy 对象.
                                                             (line   91)
* RFC; RFC 2965 <14>:                    DefaultCookiePolicy 对象.
                                                             (line   95)
* RFC; RFC 2965 <15>:                    DefaultCookiePolicy 对象.
                                                             (line  103)
* RFC; RFC 2965 <16>:                    DefaultCookiePolicy 对象.
                                                             (line  137)
* RFC; RFC 2965 <17>:                    Cookie 对象<2>.     (line   19)
* RFC; RFC 2965 <18>:                    示例<38>.           (line   22)
* RFC; RFC 2980:                         nntplib --- NNTP 协议客户端.
                                                             (line   12)
* RFC; RFC 2980 <1>:                     方法<3>.            (line  281)
* RFC; RFC 3056:                         地址对象.           (line  235)
* RFC; RFC 3171:                         地址对象.           (line   90)
* RFC; RFC 3207:                         新增和改进的模块<2>.
                                                             (line  573)
* RFC; RFC 3280:                         SSL 套接字.         (line  131)
* RFC; RFC 3330:                         地址对象.           (line  118)
* RFC; RFC 3339:                         在消息中显示日期/时间.
                                                             (line   16)
* RFC; RFC 3454:                         stringprep --- 因特网字符串预备.
                                                             (line   14)
* RFC; RFC 3454 <1>:                     stringprep --- 因特网字符串预备.
                                                             (line   20)
* RFC; RFC 3490:                         文字编码.           (line   14)
* RFC; RFC 3490 <1>:                     encodings idna --- 应用程序中的国际化域名.
                                                             (line    6)
* RFC; RFC 3490 <2>:                     encodings idna --- 应用程序中的国际化域名.
                                                             (line   45)
* RFC; RFC 3490 <3>:                     encodings idna --- 应用程序中的国际化域名.
                                                             (line   50)
* RFC; RFC 3490#section-3.1:             encodings idna --- 应用程序中的国际化域名.
                                                             (line   22)
* RFC; RFC 3492:                         文字编码.           (line   34)
* RFC; RFC 3492 <1>:                     encodings idna --- 应用程序中的国际化域名.
                                                             (line    6)
* RFC; RFC 3493:                         示例<23>.           (line  215)
* RFC; RFC 3501:                         IMAP4 对象.         (line  296)
* RFC; RFC 3542:                         库<30>.             (line  350)
* RFC; RFC 3542 <1>:                     其他功能.           (line  252)
* RFC; RFC 3548:                         新增，改进和弃用的模块<3>.
                                                             (line   16)
* RFC; RFC 3548 <1>:                     base64 —— Base16、Base32、Base64、Base85 資料編碼.
                                                             (line   11)
* RFC; RFC 3548 <2>:                     base64 —— Base16、Base32、Base64、Base85 資料編碼.
                                                             (line   14)
* RFC; RFC 3548 <3>:                     base64 —— Base16、Base32、Base64、Base85 資料編碼.
                                                             (line   19)
* RFC; RFC 3548 <4>:                     base64 —— Base16、Base32、Base64、Base85 資料編碼.
                                                             (line   96)
* RFC; RFC 3659:                         FTP 对象.           (line  137)
* RFC; RFC 3879:                         地址对象.           (line  218)
* RFC; RFC 3927:                         地址对象.           (line  123)
* RFC; RFC 3977:                         nntplib --- NNTP 协议客户端.
                                                             (line   11)
* RFC; RFC 3977 <1>:                     属性.               (line    8)
* RFC; RFC 3977 <2>:                     方法<3>.            (line   31)
* RFC; RFC 3977 <3>:                     方法<3>.            (line  120)
* RFC; RFC 3977 <4>:                     方法<3>.            (line  281)
* RFC; RFC 3986:                         urllib parse<2>.    (line    6)
* RFC; RFC 3986 <1>:                     urllib parse<3>.    (line    6)
* RFC; RFC 3986 <2>:                     urllib.             (line   22)
* RFC; RFC 3986 <3>:                     新增和改进的模块.   (line  617)
* RFC; RFC 3986 <4>:                     移植到 Python 2 7.  (line   80)
* RFC; RFC 3986 <5>:                     URL 解析.           (line  127)
* RFC; RFC 3986 <6>:                     URL 解析.           (line  316)
* RFC; RFC 3986 <7>:                     URL 转码.           (line   21)
* RFC; RFC 3986 <8>:                     URL 转码.           (line  137)
* RFC; RFC 3986 <9>:                     http server --- HTTP 服务器.
                                                             (line   83)
* RFC; RFC 4086:                         LibreSSL 支持.      (line   32)
* RFC; RFC 4122:                         新增，改进和删除的模块.
                                                             (line  415)
* RFC; RFC 4122 <1>:                     新增，改进和删除的模块.
                                                             (line  420)
* RFC; RFC 4122 <2>:                     uuid --- RFC 4122 定义的UUID对象.
                                                             (line    6)
* RFC; RFC 4122 <3>:                     uuid --- RFC 4122 定义的UUID对象.
                                                             (line   12)
* RFC; RFC 4122 <4>:                     uuid --- RFC 4122 定义的UUID对象.
                                                             (line   62)
* RFC; RFC 4122 <5>:                     uuid --- RFC 4122 定义的UUID对象.
                                                             (line  125)
* RFC; RFC 4122 <6>:                     uuid --- RFC 4122 定义的UUID对象.
                                                             (line  151)
* RFC; RFC 4122 <7>:                     uuid --- RFC 4122 定义的UUID对象.
                                                             (line  209)
* RFC; RFC 4122 <8>:                     uuid --- RFC 4122 定义的UUID对象.
                                                             (line  222)
* RFC; RFC 4180:                         csv --- CSV 文件读写.
                                                             (line   11)
* RFC; RFC 4193:                         地址对象.           (line  219)
* RFC; RFC 4217:                         ftplib --- FTP 协议客户端.
                                                             (line   77)
* RFC; RFC 4627:                         json --- JSON 编码和解码器.
                                                             (line   11)
* RFC; RFC 4627 <1>:                     顶级非对象，非数组值.
                                                             (line    6)
* RFC; RFC 4642:                         nntplib --- NNTP 协议客户端.
                                                             (line   96)
* RFC; RFC 4954:                         SMTP 对象.          (line  111)
* RFC; RFC 4954 <1>:                     SMTP 对象.          (line  131)
* RFC; RFC 5161:                         imaplib<2>.         (line   11)
* RFC; RFC 5161 <1>:                     IMAP4 对象.         (line   76)
* RFC; RFC 5246:                         常量<3>.            (line  433)
* RFC; RFC 5246 <1>:                     LibreSSL 支持.      (line   40)
* RFC; RFC 5280:                         Other Changes.      (line   20)
* RFC; RFC 5280 <1>:                     改变了的Python API. (line   95)
* RFC; RFC 5280 <2>:                     证书处理.           (line    9)
* RFC; RFC 5280 <3>:                     证书处理.           (line   58)
* RFC; RFC 5280 <4>:                     LibreSSL 支持.      (line   36)
* RFC; RFC 5321:                         smtpd<3>.           (line    6)
* RFC; RFC 5321 <1>:                     email headerregistry 自定义标头对象.
                                                             (line  386)
* RFC; RFC 5321 <2>:                     smtpd --- SMTP 服务器.
                                                             (line   24)
* RFC; RFC 5321 <3>:                     SMTPServer 对象.    (line   42)
* RFC; RFC 5321 <4>:                     SMTPServer 对象.    (line   64)
* RFC; RFC 5322:                         email --- 电子邮件与 MIME 处理包.
                                                             (line   13)
* RFC; RFC 5322 <1>:                     email message 表示一封电子邮件信息.
                                                             (line   17)
* RFC; RFC 5322 <2>:                     email message 表示一封电子邮件信息.
                                                             (line   25)
* RFC; RFC 5322 <3>:                     Parser API.         (line   35)
* RFC; RFC 5322 <4>:                     email generator 生成 MIME 文档.
                                                             (line   82)
* RFC; RFC 5322 <5>:                     email generator 生成 MIME 文档.
                                                             (line  160)
* RFC; RFC 5322 <6>:                     email policy Policy 对象.
                                                             (line  118)
* RFC; RFC 5322 <7>:                     email policy Policy 对象.
                                                             (line  260)
* RFC; RFC 5322 <8>:                     email policy Policy 对象.
                                                             (line  277)
* RFC; RFC 5322 <9>:                     email policy Policy 对象.
                                                             (line  281)
* RFC; RFC 5322 <10>:                    email policy Policy 对象.
                                                             (line  293)
* RFC; RFC 5322 <11>:                    email policy Policy 对象.
                                                             (line  320)
* RFC; RFC 5322 <12>:                    email errors 异常和缺陷类.
                                                             (line   25)
* RFC; RFC 5322 <13>:                    email headerregistry 自定义标头对象.
                                                             (line   14)
* RFC; RFC 5322 <14>:                    email headerregistry 自定义标头对象.
                                                             (line   96)
* RFC; RFC 5322 <15>:                    email headerregistry 自定义标头对象.
                                                             (line  100)
* RFC; RFC 5322 <16>:                    email headerregistry 自定义标头对象.
                                                             (line  101)
* RFC; RFC 5322 <17>:                    email headerregistry 自定义标头对象.
                                                             (line  112)
* RFC; RFC 5322 <18>:                    email headerregistry 自定义标头对象.
                                                             (line  128)
* RFC; RFC 5322 <19>:                    email headerregistry 自定义标头对象.
                                                             (line  355)
* RFC; RFC 5322 <20>:                    email headerregistry 自定义标头对象.
                                                             (line  383)
* RFC; RFC 5322 <21>:                    email headerregistry 自定义标头对象.
                                                             (line  412)
* RFC; RFC 5322 <22>:                    email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line   17)
* RFC; RFC 5322 <23>:                    SMTP 对象.          (line  266)
* RFC; RFC 5424:                         SysLogHandler.      (line   46)
* RFC; RFC 5424 <1>:                     在发送给 SysLogHandler 的信息中插入一个 BOM。.
                                                             (line    6)
* RFC; RFC 5424 <2>:                     在发送给 SysLogHandler 的信息中插入一个 BOM。.
                                                             (line   15)
* RFC; RFC 5424 <3>:                     在发送给 SysLogHandler 的信息中插入一个 BOM。.
                                                             (line   34)
* RFC; RFC 5424#section-6:               在发送给 SysLogHandler 的信息中插入一个 BOM。.
                                                             (line    8)
* RFC; RFC 5735:                         地址对象.           (line  108)
* RFC; RFC 5891:                         encodings idna --- 应用程序中的国际化域名.
                                                             (line   10)
* RFC; RFC 5895:                         encodings idna --- 应用程序中的国际化域名.
                                                             (line   10)
* RFC; RFC 5929:                         SSL 套接字.         (line  212)
* RFC; RFC 6066:                         常量<3>.            (line  343)
* RFC; RFC 6066 <1>:                     SSL 上下文.         (line  262)
* RFC; RFC 6066 <2>:                     LibreSSL 支持.      (line   44)
* RFC; RFC 6125:                         证书处理.           (line   10)
* RFC; RFC 6125 <1>:                     证书处理.           (line   26)
* RFC; RFC 6152:                         smtpd.              (line   17)
* RFC; RFC 6152 <1>:                     SMTPServer 对象.    (line   30)
* RFC; RFC 6531:                         email<2>.           (line   19)
* RFC; RFC 6531 <1>:                     smtpd.              (line   23)
* RFC; RFC 6531 <2>:                     smtplib<2>.         (line   15)
* RFC; RFC 6531 <3>:                     email message 表示一封电子邮件信息.
                                                             (line   80)
* RFC; RFC 6531 <4>:                     email policy Policy 对象.
                                                             (line  296)
* RFC; RFC 6531 <5>:                     smtplib ---SMTP协议客户端.
                                                             (line   52)
* RFC; RFC 6531 <6>:                     smtpd --- SMTP 服务器.
                                                             (line   24)
* RFC; RFC 6531 <7>:                     SMTPServer 对象.    (line   22)
* RFC; RFC 6531 <8>:                     SMTPChannel 对象.   (line   18)
* RFC; RFC 6532:                         email<2>.           (line   18)
* RFC; RFC 6532 <1>:                     email --- 电子邮件与 MIME 处理包.
                                                             (line   13)
* RFC; RFC 6532 <2>:                     email message 表示一封电子邮件信息.
                                                             (line   18)
* RFC; RFC 6532 <3>:                     Parser API.         (line   36)
* RFC; RFC 6532 <4>:                     email policy Policy 对象.
                                                             (line  294)
* RFC; RFC 6585:                         HTTP 状态码.        (line  202)
* RFC; RFC 6855:                         imaplib<2>.         (line   12)
* RFC; RFC 6855 <1>:                     imaplib<2>.         (line   14)
* RFC; RFC 6855 <2>:                     IMAP4 对象.         (line   77)
* RFC; RFC 6855 <3>:                     IMAP4 对象.         (line   79)
* RFC; RFC 6856:                         poplib<2>.          (line    6)
* RFC; RFC 6856 <1>:                     POP3 对象.          (line   97)
* RFC; RFC 7159:                         json --- JSON 编码和解码器.
                                                             (line   10)
* RFC; RFC 7159 <1>:                     标准符合性和互操作性.
                                                             (line    6)
* RFC; RFC 7159 <2>:                     顶级非对象，非数组值.
                                                             (line    8)
* RFC; RFC 7230:                         urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  163)
* RFC; RFC 7230 <1>:                     HTTPConnection 对象.
                                                             (line  127)
* RFC; RFC 7231:                         HTTP 状态码.        (line   12)
* RFC; RFC 7231 <1>:                     HTTP 状态码.        (line   72)
* RFC; RFC 7231 <2>:                     HTTP 状态码.        (line  104)
* RFC; RFC 7238:                         HTTP 状态码.        (line   75)
* RFC; RFC 7301:                         Application-Layer Protocol Negotiation Support.
                                                             (line   10)
* RFC; RFC 7301 <1>:                     常量<3>.            (line  322)
* RFC; RFC 7301 <2>:                     SSL 上下文.         (line  231)
* RFC; RFC 7525:                         LibreSSL 支持.      (line   52)
* RFC; RFC 7540:                         HTTP 状态码.        (line  139)
* RFC; RFC 7693:                         BLAKE2.             (line    6)
* RFC; RFC 7725:                         HTTP 状态码.        (line  167)
* RFC; RFC 7914:                         密钥派生.           (line   42)
* RFC; RFC 821:                          smtplib ---SMTP协议客户端.
                                                             (line   12)
* RFC; RFC 821 <1>:                      smtplib ---SMTP协议客户端.
                                                             (line  158)
* RFC; RFC 822:                          新增和改进的模块<3>.
                                                             (line   97)
* RFC; RFC 822 <1>:                      函数<3>.            (line  531)
* RFC; RFC 822 <2>:                      函数<3>.            (line  533)
* RFC; RFC 822 <3>:                      email 示例.         (line   35)
* RFC; RFC 822 <4>:                      email header 国际化标头.
                                                             (line   17)
* RFC; RFC 822 <5>:                      HTTPConnection 对象.
                                                             (line  116)
* RFC; RFC 822 <6>:                      SMTP 对象.          (line   79)
* RFC; RFC 822 <7>:                      SMTP 对象.          (line  197)
* RFC; RFC 822 <8>:                      SMTP 对象.          (line  197)
* RFC; RFC 822 <9>:                      SMTP 示例.          (line    7)
* RFC; RFC 822 <10>:                     GNUTranslations 类. (line   11)
* RFC; RFC 822 <11>:                     distutils util --- Miscellaneous other utility functions.
                                                             (line  193)
* RFC; RFC 8297:                         HTTP 状态码.        (line   21)
* RFC; RFC 8305:                         打开网络连接.       (line   65)
* RFC; RFC 8305 <1>:                     打开网络连接.       (line   72)
* RFC; RFC 8470:                         HTTP 状态码.        (line  151)
* RFC; RFC 854:                          telnetlib -- Telnet 客户端.
                                                             (line   11)
* RFC; RFC 854 <1>:                      telnetlib -- Telnet 客户端.
                                                             (line   48)
* RFC; RFC 959:                          ftplib --- FTP 协议客户端.
                                                             (line   13)
* RFC; RFC 977:                          nntplib --- NNTP 协议客户端.
                                                             (line   12)
* RFC_4122 (於 uuid 模組中):             uuid --- RFC 4122 定义的UUID对象.
                                                             (line  207)
* rfile (http.server.BaseHTTPRequestHandler 的屬性): http server --- HTTP 服务器.
                                                             (line   97)
* rfind() (bytearray 的方法):            bytes 和 bytearray 操作.
                                                             (line  178)
* rfind() (bytes 的方法):                bytes 和 bytearray 操作.
                                                             (line  178)
* rfind() (mmap.mmap 的方法):            mmap --- 内存映射文件支持.
                                                             (line  218)
* rfind() (str 的方法):                  字符串的方法<2>.    (line  340)
* rgb_to_hls() (於 colorsys 模組中):     colorsys --- 颜色系统间的转换.
                                                             (line   32)
* rgb_to_hsv() (於 colorsys 模組中):     colorsys --- 颜色系统间的转换.
                                                             (line   40)
* rgb_to_yiq() (於 colorsys 模組中):     colorsys --- 颜色系统间的转换.
                                                             (line   24)
* rglob() (pathlib.Path 的方法):         方法<2>.            (line  346)
* richcmpfunc (C 型態):                  Slot Type typedefs. (line   80)
* right (filecmp.dircmp 的屬性):         dircmp 类.          (line   39)
* right() (於 turtle 模組中):            海龟动作.           (line   39)
* RIGHTSHIFT (於 token 模組中):          token --- 与Python解析树一起使用的常量.
                                                             (line  158)
* RIGHTSHIFTEQUAL (於 token 模組中):     token --- 与Python解析树一起使用的常量.
                                                             (line  202)
* right_list (filecmp.dircmp 的屬性):    dircmp 类.          (line   47)
* right_only (filecmp.dircmp 的屬性):    dircmp 类.          (line   59)
* rindex() (bytearray 的方法):           bytes 和 bytearray 操作.
                                                             (line  190)
* rindex() (bytes 的方法):               bytes 和 bytearray 操作.
                                                             (line  190)
* rindex() (str 的方法):                 字符串的方法<2>.    (line  346)
* rjust() (bytearray 的方法):            bytes 和 bytearray 操作.
                                                             (line  287)
* rjust() (bytes 的方法):                bytes 和 bytearray 操作.
                                                             (line  287)
* rjust() (str 的方法):                  字符串的方法<2>.    (line  351)
* rlcompleter (模組):                    rlcompleter --- GNU readline 的补全函数.
                                                             (line    6)
* rlecode_hqx() (於 binascii 模組中):    binascii --- 二进制和 ASCII 码互转.
                                                             (line   85)
* rledecode_hqx() (於 binascii 模組中):  binascii --- 二进制和 ASCII 码互转.
                                                             (line   74)
* RLIMIT_AS (於 resource 模組中):        资源限制<2>.        (line  126)
* RLIMIT_CORE (於 resource 模組中):      资源限制<2>.        (line   77)
* RLIMIT_CPU (於 resource 模組中):       资源限制<2>.        (line   82)
* RLIMIT_DATA (於 resource 模組中):      资源限制<2>.        (line   93)
* RLIMIT_FSIZE (於 resource 模組中):     资源限制<2>.        (line   89)
* RLIMIT_MEMLOCK (於 resource 模組中):   资源限制<2>.        (line  118)
* RLIMIT_MSGQUEUE (於 resource 模組中):  资源限制<2>.        (line  130)
* RLIMIT_NICE (於 resource 模組中):      资源限制<2>.        (line  138)
* RLIMIT_NOFILE (於 resource 模組中):    资源限制<2>.        (line  110)
* RLIMIT_NPROC (於 resource 模組中):     资源限制<2>.        (line  106)
* RLIMIT_NPTS (於 resource 模組中):      资源限制<2>.        (line  190)
* RLIMIT_OFILE (於 resource 模組中):     资源限制<2>.        (line  114)
* RLIMIT_RSS (於 resource 模組中):       资源限制<2>.        (line  102)
* RLIMIT_RTPRIO (於 resource 模組中):    资源限制<2>.        (line  146)
* RLIMIT_RTTIME (於 resource 模組中):    资源限制<2>.        (line  154)
* RLIMIT_SBSIZE (於 resource 模組中):    资源限制<2>.        (line  171)
* RLIMIT_SIGPENDING (於 resource 模組中): 资源限制<2>.       (line  163)
* RLIMIT_STACK (於 resource 模組中):     资源限制<2>.        (line   97)
* RLIMIT_SWAP (於 resource 模組中):      资源限制<2>.        (line  180)
* RLIMIT_VMEM (於 resource 模組中):      资源限制<2>.        (line  122)
* RLIM_INFINITY (於 resource 模組中):    资源限制<2>.        (line   16)
* RLock (multiprocessing 中的類別):      同步原语.           (line   85)
* RLock (threading 中的類別):            递归锁对象.         (line   18)
* RLock() (multiprocessing.managers.SyncManager 的方法): 管理器.
                                                             (line  161)
* rmd() (ftplib.FTP 的方法):             FTP 对象.           (line  188)
* rmdir() (pathlib.Path 的方法):         方法<2>.            (line  361)
* rmdir() (於 os 模組中):                文件和目录.         (line  642)
* rmdir() (於 test.support 模組中):      test support --- Utilities for the Python test suite.
                                                             (line  237)
* RMFF:                                  chunk --- 读取 IFF 分块数据.
                                                             (line    8)
* rms() (於 audioop 模組中):             audioop --- 处理原始音频数据.
                                                             (line  169)
* rmtree() (於 shutil 模組中):           目录和文件操作.     (line  212)
* rmtree() (於 test.support 模組中):     test support --- Utilities for the Python test suite.
                                                             (line  243)
* RobotFileParser (urllib.robotparser 中的類別): urllib robotparser --- robots txt 语法分析程序.
                                                             (line   15)
* robots.txt:                            urllib robotparser --- robots txt 语法分析程序.
                                                             (line    8)
* rollback() (sqlite3.Connection 的方法): 连接对象（Connection）.
                                                             (line   36)
* ROMAN (於 tkinter.font 模組中):        tkinter font --- Tkinter 字体封装.
                                                             (line   15)
* rotate() (collections.deque 的方法):   deque 对象.         (line   98)
* rotate() (decimal.Context 的方法):     上下文对象.         (line  424)
* rotate() (decimal.Decimal 的方法):     Decimal 对象.       (line  437)
* rotate() (logging.handlers.BaseRotatingHandler 的方法): BaseRotatingHandler.
                                                             (line   68)
* RotatingFileHandler (logging.handlers 中的類別): RotatingFileHandler.
                                                             (line    9)
* rotation_filename() (logging.handlers.BaseRotatingHandler 的方法): BaseRotatingHandler.
                                                             (line   53)
* rotator (logging.handlers.BaseRotatingHandler 的屬性): BaseRotatingHandler.
                                                             (line   45)
* ROT_FOUR (opcode):                     Python字节码说明.   (line   68)
* ROT_THREE (opcode):                    Python字节码说明.   (line   64)
* ROT_TWO (opcode):                      Python字节码说明.   (line   60)
* round() (內建函式):                    內建函式.           (line 1234)
* Rounded (decimal 中的類別):            信号.               (line   69)
* ROUND_05UP (於 decimal 模組中):        舍入模式.           (line   34)
* ROUND_CEILING (於 decimal 模組中):     舍入模式.           (line    6)
* ROUND_DOWN (於 decimal 模組中):        舍入模式.           (line   10)
* ROUND_FLOOR (於 decimal 模組中):       舍入模式.           (line   14)
* ROUND_HALF_DOWN (於 decimal 模組中):   舍入模式.           (line   18)
* ROUND_HALF_EVEN (於 decimal 模組中):   舍入模式.           (line   22)
* ROUND_HALF_UP (於 decimal 模組中):     舍入模式.           (line   26)
* ROUND_UP (於 decimal 模組中):          舍入模式.           (line   30)
* Row (sqlite3 中的類別):                行对象.             (line    6)
* rowcount (sqlite3.Cursor 的屬性):      Cursor 对象.        (line  151)
* row_factory (sqlite3.Connection 的屬性): 连接对象（Connection）.
                                                             (line  281)
* RPAR (於 token 模組中):                token --- 与Python解析树一起使用的常量.
                                                             (line   54)
* rpartition() (bytearray 的方法):       bytes 和 bytearray 操作.
                                                             (line  201)
* rpartition() (bytes 的方法):           bytes 和 bytearray 操作.
                                                             (line  201)
* rpartition() (str 的方法):             字符串的方法<2>.    (line  357)
* rpc_paths (xmlrpc.server.SimpleXMLRPCRequestHandler 的屬性): SimpleXMLRPCServer 对象.
                                                             (line   53)
* rpop() (poplib.POP3 的方法):           POP3 对象.          (line   42)
* rset() (poplib.POP3 的方法):           POP3 对象.          (line   67)
* RShift (ast 中的類別):                 表达式<2>.          (line   54)
* rshift() (於 operator 模組中):         operator --- 标准运算符替代函数.
                                                             (line  136)
* rsplit() (bytearray 的方法):           bytes 和 bytearray 操作.
                                                             (line  297)
* rsplit() (bytes 的方法):               bytes 和 bytearray 操作.
                                                             (line  297)
* rsplit() (str 的方法):                 字符串的方法<2>.    (line  363)
* RSQB (於 token 模組中):                token --- 与Python解析树一起使用的常量.
                                                             (line   62)
* rstrip() (bytearray 的方法):           bytes 和 bytearray 操作.
                                                             (line  306)
* rstrip() (bytes 的方法):               bytes 和 bytearray 操作.
                                                             (line  306)
* rstrip() (str 的方法):                 字符串的方法<2>.    (line  371)
* rt() (於 turtle 模組中):               海龟动作.           (line   39)
* RTLD_DEEPBIND (於 os 模組中):          其他系统信息.       (line  118)
* RTLD_GLOBAL (於 os 模組中):            其他系统信息.       (line  118)
* RTLD_LAZY (於 os 模組中):              其他系统信息.       (line  118)
* RTLD_LOCAL (於 os 模組中):             其他系统信息.       (line  118)
* RTLD_NODELETE (於 os 模組中):          其他系统信息.       (line  118)
* RTLD_NOLOAD (於 os 模組中):            其他系统信息.       (line  118)
* RTLD_NOW (於 os 模組中):               其他系统信息.       (line  118)
* ruler (cmd.Cmd 的屬性):                Cmd 对象.           (line  132)
* run (pdb command):                     调试器命令.         (line  267)
* Run script:                            格式菜单（仅 window 编辑器）.
                                                             (line   49)
* run() (bdb.Bdb 的方法):                bdb --- Debugger framework.
                                                             (line  362)
* run() (contextvars.Context 的方法):    手动上下文管理.     (line   27)
* run() (distutils.cmd.Command 的方法):  Creating a new Distutils command.
                                                             (line   40)
* run() (doctest.DocTestRunner 的方法):  DocTestRunner 对象. (line   83)
* run() (multiprocessing.Process 的方法): Process 和异常.    (line   28)
* run() (pdb.Pdb 的方法):                pdb --- Python 的调试器.
                                                             (line  158)
* run() (profile.Profile 的方法):        profile 和 cProfile 模块参考.
                                                             (line   98)
* run() (sched.scheduler 的方法):        调度器对象.         (line   45)
* run() (test.support.BasicTestRunner 的方法): test support --- Utilities for the Python test suite.
                                                             (line 1124)
* run() (threading.Thread 的方法):       线程对象.           (line   83)
* run() (trace.Trace 的方法):            编程接口.           (line   18)
* run() (unittest.IsolatedAsyncioTestCase 的方法): 测试用例. (line  838)
* run() (unittest.TestCase 的方法):      测试用例.           (line   83)
* run() (unittest.TestSuite 的方法):     Grouping tests.     (line   41)
* run() (unittest.TextTestRunner 的方法): Loading and running tests.
                                                             (line  479)
* run() (wsgiref.handlers.BaseHandler 的方法): wsgiref handlers -- 服务器/网关基类.
                                                             (line   80)
* run() (於 asyncio 模組中):             运行 asyncio 程序.  (line    6)
* run() (於 pdb 模組中):                 pdb --- Python 的调试器.
                                                             (line   82)
* run() (於 profile 模組中):             profile 和 cProfile 模块参考.
                                                             (line    8)
* run() (於 subprocess 模組中):          使用 subprocess 模块.
                                                             (line   12)
* runcall() (bdb.Bdb 的方法):            bdb --- Debugger framework.
                                                             (line  379)
* runcall() (pdb.Pdb 的方法):            pdb --- Python 的调试器.
                                                             (line  158)
* runcall() (profile.Profile 的方法):    profile 和 cProfile 模块参考.
                                                             (line  107)
* runcall() (於 pdb 模組中):             pdb --- Python 的调试器.
                                                             (line   98)
* runcode() (code.InteractiveInterpreter 的方法): 交互解释器对象.
                                                             (line   29)
* runctx() (bdb.Bdb 的方法):             bdb --- Debugger framework.
                                                             (line  374)
* runctx() (profile.Profile 的方法):     profile 和 cProfile 模块参考.
                                                             (line  102)
* runctx() (trace.Trace 的方法):         编程接口.           (line   23)
* runctx() (於 profile 模組中):          profile 和 cProfile 模块参考.
                                                             (line   22)
* runeval() (bdb.Bdb 的方法):            bdb --- Debugger framework.
                                                             (line  368)
* runeval() (pdb.Pdb 的方法):            pdb --- Python 的调试器.
                                                             (line  158)
* runeval() (於 pdb 模組中):             pdb --- Python 的调试器.
                                                             (line   92)
* runfunc() (trace.Trace 的方法):        编程接口.           (line   28)
* running() (concurrent.futures.Future 的方法): Future 对象. (line   24)
* runpy (模組):                          runpy ——查找并执行 Python 模块.
                                                             (line    6)
* runsource() (code.InteractiveInterpreter 的方法): 交互解释器对象.
                                                             (line    6)
* RuntimeError:                          具体异常.           (line  171)
* RuntimeWarning:                        警告.               (line   42)
* runtime_checkable() (於 typing 模組中): 构建泛型类型.      (line  111)
* runtime_library_dir_option() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  229)
* run_coroutine_threadsafe() (於 asyncio 模組中): 跨线程调度.
                                                             (line    6)
* run_docstring_examples() (於 doctest 模組中): 基本API.     (line  112)
* run_doctest() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  330)
* run_forever() (asyncio.loop 的方法):   运行和停止循环.     (line   15)
* run_in_executor() (asyncio.loop 的方法): 在线程或者进程池中执行代码。.
                                                             (line    6)
* run_in_subinterp() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  971)
* run_module() (於 runpy 模組中):        runpy ——查找并执行 Python 模块.
                                                             (line   23)
* run_path() (於 runpy 模組中):          runpy ——查找并执行 Python 模块.
                                                             (line   76)
* run_python_until_end() (於 test.support.script_helper 模組中): test support script_helper --- Utilities for the Python execution tests.
                                                             (line   29)
* run_script() (modulefinder.ModuleFinder 的方法): modulefinder --- 查找脚本使用的模块.
                                                             (line   37)
* run_setup() (於 distutils.core 模組中): distutils core --- 分发包功能的核心.
                                                             (line  110)
* run_unittest() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  314)
* run_until_complete() (asyncio.loop 的方法): 运行和停止循环.
                                                             (line    6)
* run_with_locale() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  638)
* run_with_tz() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  646)
* RUSAGE_BOTH (於 resource 模組中):      资源用量.           (line  111)
* RUSAGE_CHILDREN (於 resource 模組中):  资源用量.           (line  106)
* RUSAGE_SELF (於 resource 模組中):      资源用量.           (line  101)
* RUSAGE_THREAD (於 resource 模組中):    资源用量.           (line  116)
* RWF_DSYNC (於 os 模組中):              文件描述符操作.     (line  482)
* RWF_HIPRI (於 os 模組中):              文件描述符操作.     (line  432)
* RWF_NOWAIT (於 os 模組中):             文件描述符操作.     (line  420)
* RWF_SYNC (於 os 模組中):               文件描述符操作.     (line  491)
* R_OK (於 os 模組中):                   文件和目录.         (line   89)
* S (於 re 模組中):                      模块内容.           (line   88)
* safe (uuid.SafeUUID 的屬性):           uuid --- RFC 4122 定义的UUID对象.
                                                             (line   29)
* SafeChildWatcher (asyncio 中的類別):   进程监视器.         (line  102)
* saferepr() (於 pprint 模組中):         pprint --- 数据美化输出.
                                                             (line  129)
* SafeUUID (uuid 中的類別):              uuid --- RFC 4122 定义的UUID对象.
                                                             (line   25)
* safe_substitute() (string.Template 的方法): 模板字符串.    (line   39)
* samefile() (pathlib.Path 的方法):      方法<2>.            (line  365)
* samefile() (於 os.path 模組中):        os path --- 常用路径操作.
                                                             (line  289)
* SameFileError:                         目录和文件操作.     (line   43)
* sameopenfile() (於 os.path 模組中):    os path --- 常用路径操作.
                                                             (line  303)
* samestat() (於 os.path 模組中):        os path --- 常用路径操作.
                                                             (line  313)
* same_files (filecmp.dircmp 的屬性):    dircmp 类.          (line   76)
* same_quantum() (decimal.Context 的方法): 上下文对象.       (line  428)
* same_quantum() (decimal.Decimal 的方法): Decimal 对象.     (line  446)
* sample() (於 random 模組中):           序列用函数.         (line   61)
* samples() (statistics.NormalDist 的方法): NormalDist 对象. (line   49)
* save() (http.cookiejar.FileCookieJar 的方法): CookieJar 和 FileCookieJar 对象.
                                                             (line   93)
* SaveAs (tkinter.filedialog 中的類別):  原生 加载/保存 对话框.
                                                             (line   54)
* SAVEDCWD (於 test.support 模組中):     test support --- Utilities for the Python test suite.
                                                             (line  142)
* SaveFileDialog (tkinter.filedialog 中的類別): 原生 加载/保存 对话框.
                                                             (line  134)
* SaveKey() (於 winreg 模組中):          函数<12>.           (line  361)
* SaveSignals (test.support 中的類別):   test support --- Utilities for the Python test suite.
                                                             (line 1101)
* savetty() (於 curses 模組中):          函数<4>.            (line  353)
* SAX2DOM (xml.dom.pulldom 中的類別):    xml dom pulldom --- 支持构建部分 DOM 树.
                                                             (line   73)
* SAXException:                          xml sax --- 支持 SAX2 解析器.
                                                             (line   72)
* SAXNotRecognizedException:             xml sax --- 支持 SAX2 解析器.
                                                             (line   93)
* SAXNotSupportedException:              xml sax --- 支持 SAX2 解析器.
                                                             (line   99)
* SAXParseException:                     xml sax --- 支持 SAX2 解析器.
                                                             (line   86)
* scaleb() (decimal.Context 的方法):     上下文对象.         (line  432)
* scaleb() (decimal.Decimal 的方法):     Decimal 对象.       (line  454)
* scandir() (於 os 模組中):              文件和目录.         (line  657)
* scanf():                               模拟 scanf.         (line    6)
* sched (模組):                          sched --- 事件调度器.
                                                             (line    6)
* scheduler (sched 中的類別):            sched --- 事件调度器.
                                                             (line   12)
* SCHED_BATCH (於 os 模組中):            调度器接口.         (line   17)
* SCHED_FIFO (於 os 模組中):             调度器接口.         (line   30)
* sched_getaffinity() (於 os 模組中):    调度器接口.         (line   98)
* sched_getparam() (於 os 模組中):       调度器接口.         (line   79)
* sched_getscheduler() (於 os 模組中):   调度器接口.         (line   69)
* sched_get_priority_max() (於 os 模組中): 调度器接口.       (line   59)
* sched_get_priority_min() (於 os 模組中): 调度器接口.       (line   55)
* SCHED_IDLE (於 os 模組中):             调度器接口.         (line   22)
* SCHED_OTHER (於 os 模組中):            调度器接口.         (line   13)
* sched_param (os 中的類別):             调度器接口.         (line   43)
* sched_priority (os.sched_param 的屬性): 调度器接口.        (line   51)
* SCHED_RESET_ON_FORK (於 os 模組中):    调度器接口.         (line   38)
* SCHED_RR (於 os 模組中):               调度器接口.         (line   34)
* sched_rr_get_interval() (於 os 模組中): 调度器接口.        (line   84)
* sched_setaffinity() (於 os 模組中):    调度器接口.         (line   93)
* sched_setparam() (於 os 模組中):       调度器接口.         (line   74)
* sched_setscheduler() (於 os 模組中):   调度器接口.         (line   63)
* SCHED_SPORADIC (於 os 模組中):         调度器接口.         (line   26)
* sched_yield() (於 os 模組中):          调度器接口.         (line   89)
* schema (於 msilib 模組中):             Precomputed tables. (line   10)
* scope:                                 命名与绑定.         (line    6)
* scope <1>:                             名称的解析.         (line    6)
* scope_id (ipaddress.IPv6Address 的屬性): 地址对象.         (line  226)
* Screen (turtle 中的類別):              公共类.             (line   28)
* screensize() (於 turtle 模組中):       窗口控制.           (line   57)
* script_from_examples() (於 doctest 模組中): 调试.          (line   67)
* scroll() (curses.window 的方法):       Window 对象.        (line  424)
* ScrolledCanvas (turtle 中的類別):      公共类.             (line   32)
* ScrolledText (tkinter.scrolledtext 中的類別): tkinter scrolledtext --- 滚动文字控件.
                                                             (line   20)
* scrollok() (curses.window 的方法):     Window 对象.        (line  428)
* scrypt() (於 hashlib 模組中):          密钥派生.           (line   39)
* seal() (於 unittest.mock 模組中):      Sealing mocks.      (line    6)
* search() (imaplib.IMAP4 的方法):       IMAP4 对象.         (line  200)
* search() (re.Pattern 的方法):          正则表达式对象 （正则对象）.
                                                             (line    8)
* search() (於 re 模組中):               模块内容.           (line  111)
* second (datetime.datetime 的屬性):     datetime 对象.      (line  263)
* second (datetime.time 的屬性):         time 对象.          (line   54)
* seconds since the epoch:               time --- 时间的访问和转换.
                                                             (line   21)
* secrets (模組):                        secrets --- 產生用於管理機密的安全亂數.
                                                             (line    6)
* SECTCRE (configparser.ConfigParser 的屬性): 定制解析器行为.
                                                             (line  262)
* sections() (configparser.ConfigParser 的方法): ConfigParser 对象.
                                                             (line   69)
* secure (http.cookiejar.Cookie 的屬性): Cookie 对象<2>.     (line   41)
* secure hash algorithm, SHA1, SHA224, SHA256, SHA384, SHA512: hashlib --- 安全哈希与消息摘要.
                                                             (line    8)
* Secure Sockets Layer:                  ssl --- 套接字对象的 TLS/SSL 包装器.
                                                             (line    8)
* security considerations:               平台特定模块.       (line   15)
* see() (tkinter.ttk.Treeview 的方法):   ttk Treeview.       (line  217)
* seed() (於 random 模組中):             簿记功能.           (line    6)
* seek() (chunk.Chunk 的方法):           chunk --- 读取 IFF 分块数据.
                                                             (line   80)
* seek() (io.IOBase 的方法):             I/O 基类.           (line   89)
* seek() (io.TextIOBase 的方法):         文本 I/O<2>.        (line   59)
* seek() (mmap.mmap 的方法):             mmap --- 内存映射文件支持.
                                                             (line  226)
* seekable() (io.IOBase 的方法):         I/O 基类.           (line  110)
* SEEK_CUR (於 os 模組中):               文件描述符操作.     (line  223)
* SEEK_END (於 os 模組中):               文件描述符操作.     (line  223)
* SEEK_SET (於 os 模組中):               文件描述符操作.     (line  223)
* seen_greeting (smtpd.SMTPChannel 的屬性): SMTPChannel 对象.
                                                             (line   59)
* Select (tkinter.tix 中的類別):         Basic Widgets.      (line   58)
* select (模組):                         select --- 等待 I/O 完成.
                                                             (line    6)
* select() (imaplib.IMAP4 的方法):       IMAP4 对象.         (line  215)
* select() (selectors.BaseSelector 的方法): 类<2>.           (line   97)
* select() (tkinter.ttk.Notebook 的方法): ttk Notebook.      (line   47)
* select() (於 select 模組中):           select --- 等待 I/O 完成.
                                                             (line   92)
* selected_alpn_protocol() (ssl.SSLSocket 的方法): SSL 套接字.
                                                             (line  218)
* selected_npn_protocol() (ssl.SSLSocket 的方法): SSL 套接字.
                                                             (line  227)
* selection() (tkinter.ttk.Treeview 的方法): ttk Treeview.   (line  224)
* selection_add() (tkinter.ttk.Treeview 的方法): ttk Treeview.
                                                             (line  238)
* selection_remove() (tkinter.ttk.Treeview 的方法): ttk Treeview.
                                                             (line  245)
* selection_set() (tkinter.ttk.Treeview 的方法): ttk Treeview.
                                                             (line  231)
* selection_toggle() (tkinter.ttk.Treeview 的方法): ttk Treeview.
                                                             (line  252)
* selector (urllib.request.Request 的屬性): Request 对象.    (line   32)
* SelectorEventLoop (asyncio 中的類別):  事件循环实现.       (line   12)
* SelectorKey (selectors 中的類別):      类<2>.              (line   28)
* selectors (模組):                      selectors --- 高级 I/O 复用库.
                                                             (line    6)
* SelectSelector (selectors 中的類別):   类<2>.              (line  145)
* Semaphore (asyncio 中的類別):          Semaphore.          (line    6)
* Semaphore (multiprocessing 中的類別):  同步原语.           (line  132)
* Semaphore (threading 中的類別):        信号量对象.         (line   17)
* Semaphore() (multiprocessing.managers.SyncManager 的方法): 管理器.
                                                             (line  166)
* semaphores, binary:                    _thread --- 底层多线程 API.
                                                             (line    6)
* SEMI (於 token 模組中):                token --- 与Python解析树一起使用的常量.
                                                             (line   74)
* send() (asyncore.dispatcher 的方法):   asyncore --- 异步套接字处理器.
                                                             (line  162)
* send() (coroutine 的方法):             协程对象.           (line   20)
* send() (generator 的方法):             生成器-迭代器的方法.
                                                             (line   23)
* send() (http.client.HTTPConnection 的方法): HTTPConnection 对象.
                                                             (line  141)
* send() (imaplib.IMAP4 的方法):         IMAP4 对象.         (line  221)
* send() (logging.handlers.DatagramHandler 的方法): DatagramHandler.
                                                             (line   29)
* send() (logging.handlers.SocketHandler 的方法): SocketHandler.
                                                             (line   52)
* send() (multiprocessing.connection.Connection 的方法): 连接（Connection）对象.
                                                             (line   14)
* send() (socket.socket 的方法):         套接字对象.         (line  319)
* sendall() (socket.socket 的方法):      套接字对象.         (line  331)
* sendcmd() (ftplib.FTP 的方法):         FTP 对象.           (line   53)
* sendfile() (asyncio.loop 的方法):      传输文件.           (line    6)
* sendfile() (socket.socket 的方法):     套接字对象.         (line  408)
* sendfile() (wsgiref.handlers.BaseHandler 的方法): wsgiref handlers -- 服务器/网关基类.
                                                             (line  227)
* sendfile() (於 os 模組中):             文件描述符操作.     (line  517)
* SendfileNotAvailableError:             异常<9>.            (line   32)
* sendmail() (smtplib.SMTP 的方法):      SMTP 对象.          (line  194)
* sendmsg() (socket.socket 的方法):      套接字对象.         (line  362)
* sendmsg_afalg() (socket.socket 的方法): 套接字对象.        (line  397)
* sendto() (asyncio.DatagramTransport 的方法): 数据报传输.   (line    6)
* sendto() (socket.socket 的方法):       套接字对象.         (line  346)
* send_bytes() (multiprocessing.connection.Connection 的方法): 连接（Connection）对象.
                                                             (line   49)
* send_error() (http.server.BaseHTTPRequestHandler 的方法): http server --- HTTP 服务器.
                                                             (line  180)
* send_fds() (於 socket 模組中):         其他功能.           (line  355)
* send_flowing_data() (formatter.writer 的方法): The Writer Interface.
                                                             (line   76)
* send_header() (http.server.BaseHTTPRequestHandler 的方法): http server --- HTTP 服务器.
                                                             (line  208)
* send_hor_rule() (formatter.writer 的方法): The Writer Interface.
                                                             (line   68)
* send_label_data() (formatter.writer 的方法): The Writer Interface.
                                                             (line   92)
* send_line_break() (formatter.writer 的方法): The Writer Interface.
                                                             (line   54)
* send_literal_data() (formatter.writer 的方法): The Writer Interface.
                                                             (line   83)
* send_message() (smtplib.SMTP 的方法):  SMTP 对象.          (line  257)
* send_paragraph() (formatter.writer 的方法): The Writer Interface.
                                                             (line   58)
* send_response() (http.server.BaseHTTPRequestHandler 的方法): http server --- HTTP 服务器.
                                                             (line  195)
* send_response_only() (http.server.BaseHTTPRequestHandler 的方法): http server --- HTTP 服务器.
                                                             (line  218)
* send_signal() (asyncio.asyncio.subprocess.Process 的方法): 与子进程交互.
                                                             (line   72)
* send_signal() (asyncio.SubprocessTransport 的方法): 子进程传输.
                                                             (line   39)
* send_signal() (subprocess.Popen 的方法): Popen 对象.       (line   63)
* sentinel (multiprocessing.Process 的屬性): Process 和异常. (line  112)
* sentinel (於 unittest.mock 模組中):    sentinel.           (line    6)
* sep (於 os 模組中):                    其他系统信息.       (line   77)
* Sequence (collections.abc 中的類別):   容器抽象基类.       (line  155)
* Sequence (typing 中的類別):            collections abc 对应的容器.
                                                             (line   93)
* sequence (於 msilib 模組中):           Precomputed tables. (line   16)
* sequence2st() (於 parser 模組中):      创建 ST 对象.       (line   26)
* sequence; item:                        抽取.               (line    6)
* sequence; iteration:                   迭代器类型.         (line    6)
* SequenceMatcher (difflib 中的類別):    SequenceMatcher 对象.
                                                             (line    8)
* sequence（序列）:                      術語表.             (line 1023)
* serializing; objects:                  pickle --- Python 对象序列化.
                                                             (line    8)
* Server (asyncio 中的類別):             Server 对象.        (line   12)
* server (http.server.BaseHTTPRequestHandler 的屬性): http server --- HTTP 服务器.
                                                             (line   61)
* ServerProxy (xmlrpc.client 中的類別):  xmlrpc client --- XML-RPC 客户端访问.
                                                             (line   22)
* server_activate() (socketserver.BaseServer 的方法): Server 对象<2>.
                                                             (line  142)
* server_address (socketserver.BaseServer 的屬性): Server 对象<2>.
                                                             (line   67)
* server_bind() (socketserver.BaseServer 的方法): Server 对象<2>.
                                                             (line  147)
* server_close() (socketserver.BaseServer 的方法): Server 对象<2>.
                                                             (line   54)
* server_hostname (ssl.SSLSocket 的屬性): SSL 套接字.        (line  289)
* server_side (ssl.SSLSocket 的屬性):    SSL 套接字.         (line  282)
* server_software (wsgiref.handlers.BaseHandler 的屬性): wsgiref handlers -- 服务器/网关基类.
                                                             (line  145)
* server_version (http.server.BaseHTTPRequestHandler 的屬性): http server --- HTTP 服务器.
                                                             (line  111)
* server_version (http.server.SimpleHTTPRequestHandler 的屬性): http server --- HTTP 服务器.
                                                             (line  298)
* serve_forever() (asyncio.Server 的方法): Server 对象.      (line   58)
* serve_forever() (socketserver.BaseServer 的方法): Server 对象<2>.
                                                             (line   28)
* service_actions() (socketserver.BaseServer 的方法): Server 对象<2>.
                                                             (line   40)
* session (ssl.SSLSocket 的屬性):        SSL 套接字.         (line  300)
* session_reused (ssl.SSLSocket 的屬性): SSL 套接字.         (line  308)
* session_stats() (ssl.SSLContext 的方法): SSL 上下文.       (line  418)
* Set (ast 中的類別):                    字面值<3>.          (line   92)
* Set (collections.abc 中的類別):        容器抽象基类.       (line  170)
* Set (typing 中的類別):                 对应的内置类型.     (line   37)
* set (內建類別):                        集合类型 --- set frozenset.
                                                             (line   28)
* Set Breakpoint:                        帮助菜单（命令行和编辑器）.
                                                             (line   26)
* set comprehension（集合綜合運算）:     術語表.             (line 1040)
* set() (asyncio.Event 的方法):          Event.              (line   50)
* set() (configparser.ConfigParser 的方法): ConfigParser 对象.
                                                             (line  219)
* set() (configparser.RawConfigParser 的方法): RawConfigParser 对象.
                                                             (line   32)
* set() (contextvars.ContextVar 的方法): 上下文变量.         (line   40)
* set() (http.cookies.Morsel 的方法):    Morsel 对象.        (line   60)
* set() (ossaudiodev.oss_mixer_device 的方法): Mixer Device Objects.
                                                             (line   71)
* set() (test.support.EnvironmentVarGuard 的方法): test support --- Utilities for the Python test suite.
                                                             (line 1056)
* set() (threading.Event 的方法):        事件对象.           (line   26)
* set() (tkinter.ttk.Combobox 的方法):   ttk Combobox.       (line   17)
* set() (tkinter.ttk.Spinbox 的方法):    ttk Spinbox.        (line   12)
* set() (tkinter.ttk.Treeview 的方法):   ttk Treeview.       (line  259)
* set() (xml.etree.ElementTree.Element 的方法): 元素对象.    (line   68)
* set; comprehensions:                   集合显示.           (line    6)
* set; display:                          集合显示.           (line    6)
* setacl() (imaplib.IMAP4 的方法):       IMAP4 对象.         (line  228)
* setannotation() (imaplib.IMAP4 的方法): IMAP4 对象.        (line  233)
* setattr() (內建函式):                  內建函式.           (line 1265)
* setattrfunc (C 型態):                  Slot Type typedefs. (line   46)
* setAttribute() (xml.dom.Element 的方法): 元素对象<2>.      (line   63)
* setAttributeNode() (xml.dom.Element 的方法): 元素对象<2>.  (line   67)
* setAttributeNodeNS() (xml.dom.Element 的方法): 元素对象<2>.
                                                             (line   73)
* setAttributeNS() (xml.dom.Element 的方法): 元素对象<2>.    (line   80)
* setattrofunc (C 型態):                 Slot Type typedefs. (line   58)
* SetBase() (xml.parsers.expat.xmlparser 的方法): XMLParser对象<2>.
                                                             (line   19)
* setblocking() (socket.socket 的方法):  套接字对象.         (line  427)
* setByteStream() (xml.sax.xmlreader.InputSource 的方法): InputSource 对象.
                                                             (line   36)
* setcbreak() (於 tty 模組中):           tty --- 终端控制功能.
                                                             (line   21)
* setCharacterStream() (xml.sax.xmlreader.InputSource 的方法): InputSource 对象.
                                                             (line   53)
* SetComp (ast 中的類別):                Comprehensions.     (line    6)
* setcomptype() (aifc.aifc 的方法):      aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line  138)
* setcomptype() (sunau.AU_write 的方法): AU_write 对象.      (line   26)
* setcomptype() (wave.Wave_write 的方法): Wave_write 对象.   (line   43)
* setContentHandler() (xml.sax.xmlreader.XMLReader 的方法): XMLReader 对象.
                                                             (line   24)
* setcontext() (於 decimal 模組中):      上下文对象.         (line   16)
* setDaemon() (threading.Thread 的方法): 线程对象.           (line  164)
* setdefault() (dict 的方法):            映射类型 --- dict.  (line  182)
* setdefault() (http.cookies.Morsel 的方法): Morsel 对象.    (line  100)
* setdefaulttimeout() (於 socket 模組中): 其他功能.          (line  280)
* setdlopenflags() (於 sys 模組中):      sys --- 系统相关的参数和函数.
                                                             (line 1032)
* setDocumentLocator() (xml.sax.handler.ContentHandler 的方法): ContentHandler 对象.
                                                             (line    9)
* setDTDHandler() (xml.sax.xmlreader.XMLReader 的方法): XMLReader 对象.
                                                             (line   33)
* setegid() (於 os 模組中):              进程参数.           (line  306)
* setEncoding() (xml.sax.xmlreader.InputSource 的方法): InputSource 对象.
                                                             (line   22)
* setEntityResolver() (xml.sax.xmlreader.XMLReader 的方法): XMLReader 对象.
                                                             (line   42)
* setErrorHandler() (xml.sax.xmlreader.XMLReader 的方法): XMLReader 对象.
                                                             (line   52)
* seteuid() (於 os 模組中):              进程参数.           (line  312)
* setFeature() (xml.sax.xmlreader.XMLReader 的方法): XMLReader 对象.
                                                             (line   71)
* setfirstweekday() (於 calendar 模組中): calendar --- 日历相关函数.
                                                             (line  248)
* setfmt() (ossaudiodev.oss_audio_device 的方法): 音频设备对象.
                                                             (line  109)
* setFormatter() (logging.Handler 的方法): 处理器对象.       (line   42)
* setframerate() (aifc.aifc 的方法):     aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line  129)
* setframerate() (sunau.AU_write 的方法): AU_write 对象.     (line   18)
* setframerate() (wave.Wave_write 的方法): Wave_write 对象.  (line   32)
* setgid() (於 os 模組中):               进程参数.           (line  318)
* setgroups() (於 os 模組中):            进程参数.           (line  324)
* seth() (於 turtle 模組中):             海龟动作.           (line  126)
* setheading() (於 turtle 模組中):       海龟动作.           (line  126)
* sethostname() (於 socket 模組中):      其他功能.           (line  286)
* setinputsizes() (sqlite3.Cursor 的方法): Cursor 对象.      (line  143)
* SetInteger() (msilib.Record 的方法):   Record Objects.     (line   32)
* setitem() (於 operator 模組中):        operator --- 标准运算符替代函数.
                                                             (line  186)
* setitimer() (於 signal 模組中):        模块内容<5>.        (line  331)
* setLevel() (logging.Handler 的方法):   处理器对象.         (line   31)
* setLevel() (logging.Logger 的方法):    记录器对象.         (line   50)
* setLocale() (xml.sax.xmlreader.XMLReader 的方法): XMLReader 对象.
                                                             (line   57)
* setlocale() (於 locale 模組中):        locale --- 国际化服务.
                                                             (line   23)
* setLoggerClass() (於 logging 模組中):  模块级函数.         (line  292)
* setlogmask() (於 syslog 模組中):       Unix syslog 库例程. (line   63)
* setLogRecordFactory() (於 logging 模組中): 模块级函数.     (line  302)
* setmark() (aifc.aifc 的方法):          aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line  152)
* setMaxConns() (urllib.request.CacheFTPHandler 的方法): CacheFTPHandler 对象.
                                                             (line   13)
* setmode() (於 msvcrt 模組中):          文件操作.           (line   34)
* setName() (threading.Thread 的方法):   线程对象.           (line  118)
* setnchannels() (aifc.aifc 的方法):     aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line  121)
* setnchannels() (sunau.AU_write 的方法): AU_write 对象.     (line    8)
* setnchannels() (wave.Wave_write 的方法): Wave_write 对象.  (line   24)
* setnframes() (aifc.aifc 的方法):       aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line  133)
* setnframes() (sunau.AU_write 的方法):  AU_write 对象.      (line   22)
* setnframes() (wave.Wave_write 的方法): Wave_write 对象.    (line   38)
* setoutputsize() (sqlite3.Cursor 的方法): Cursor 对象.      (line  147)
* SetParamEntityParsing() (xml.parsers.expat.xmlparser 的方法): XMLParser对象<2>.
                                                             (line   44)
* setparameters() (ossaudiodev.oss_audio_device 的方法): 音频设备对象.
                                                             (line  172)
* setparams() (aifc.aifc 的方法):        aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line  145)
* setparams() (sunau.AU_write 的方法):   AU_write 对象.      (line   30)
* setparams() (wave.Wave_write 的方法):  Wave_write 对象.    (line   47)
* setpassword() (zipfile.ZipFile 的方法): ZipFile 对象.      (line  185)
* setpgid() (於 os 模組中):              进程参数.           (line  343)
* setpgrp() (於 os 模組中):              进程参数.           (line  336)
* setpos() (aifc.aifc 的方法):           aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line   93)
* setpos() (sunau.AU_read 的方法):       AU_read 对象.       (line   55)
* setpos() (wave.Wave_read 的方法):      Wave_read对象.      (line   64)
* setpos() (於 turtle 模組中):           海龟动作.           (line   71)
* setposition() (於 turtle 模組中):      海龟动作.           (line   71)
* setpriority() (於 os 模組中):          进程参数.           (line  350)
* setprofile() (於 sys 模組中):          sys --- 系统相关的参数和函数.
                                                             (line 1043)
* setprofile() (於 threading 模組中):    threading --- 基于线程的并行.
                                                             (line  113)
* SetProperty() (msilib.SummaryInformation 的方法): Summary Information Objects.
                                                             (line   22)
* setProperty() (xml.sax.xmlreader.XMLReader 的方法): XMLReader 对象.
                                                             (line   83)
* setPublicId() (xml.sax.xmlreader.InputSource 的方法): InputSource 对象.
                                                             (line    6)
* setquota() (imaplib.IMAP4 的方法):     IMAP4 对象.         (line  238)
* setraw() (於 tty 模組中):              tty --- 终端控制功能.
                                                             (line   16)
* setrecursionlimit() (於 sys 模組中):   sys --- 系统相关的参数和函数.
                                                             (line 1088)
* setregid() (於 os 模組中):             进程参数.           (line  364)
* setresgid() (於 os 模組中):            进程参数.           (line  370)
* setresuid() (於 os 模組中):            进程参数.           (line  378)
* setreuid() (於 os 模組中):             进程参数.           (line  386)
* setrlimit() (於 resource 模組中):      资源限制<2>.        (line   26)
* setsampwidth() (aifc.aifc 的方法):     aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line  125)
* setsampwidth() (sunau.AU_write 的方法): AU_write 对象.     (line   12)
* setsampwidth() (wave.Wave_write 的方法): Wave_write 对象.  (line   28)
* setscrreg() (curses.window 的方法):    Window 对象.        (line  436)
* setsid() (於 os 模組中):               进程参数.           (line  398)
* setsockopt() (socket.socket 的方法):   套接字对象.         (line  454)
* setstate() (codecs.IncrementalDecoder 的方法): IncrementalDecoder 对象.
                                                             (line   48)
* setstate() (codecs.IncrementalEncoder 的方法): IncrementalEncoder 对象.
                                                             (line   42)
* setstate() (於 random 模組中):         簿记功能.           (line   33)
* setStream() (logging.StreamHandler 的方法): StreamHandler. (line   28)
* SetStream() (msilib.Record 的方法):    Record Objects.     (line   26)
* SetString() (msilib.Record 的方法):    Record Objects.     (line   21)
* setswitchinterval() (in module sys):   Thread State and the Global Interpreter Lock.
                                                             (line   15)
* setswitchinterval() (於 sys 模組中):   sys --- 系统相关的参数和函数.
                                                             (line 1103)
* setswitchinterval() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  341)
* setSystemId() (xml.sax.xmlreader.InputSource 的方法): InputSource 对象.
                                                             (line   14)
* setsyx() (於 curses 模組中):           函数<4>.            (line  384)
* setTarget() (logging.handlers.MemoryHandler 的方法): MemoryHandler.
                                                             (line   58)
* settiltangle() (於 turtle 模組中):     外观.               (line  108)
* settimeout() (socket.socket 的方法):   套接字对象.         (line  441)
* setTimeout() (urllib.request.CacheFTPHandler 的方法): CacheFTPHandler 对象.
                                                             (line    9)
* settrace() (於 sys 模組中):            sys --- 系统相关的参数和函数.
                                                             (line 1112)
* settrace() (於 threading 模組中):      threading --- 基于线程的并行.
                                                             (line  107)
* setuid() (於 os 模組中):               进程参数.           (line  404)
* setundobuffer() (於 turtle 模組中):    特殊海龟方法.       (line   57)
* setup() (socketserver.BaseRequestHandler 的方法): 请求处理句柄对象.
                                                             (line   12)
* setUp() (unittest.TestCase 的方法):    测试用例.           (line   33)
* setup() (於 distutils.core 模組中):    distutils core --- 分发包功能的核心.
                                                             (line   10)
* setup() (於 turtle 模組中):            Screen 专有方法 而非继承自 TurtleScreen.
                                                             (line   19)
* setUpClass() (unittest.TestCase 的方法): 测试用例.         (line   55)
* setupterm() (於 curses 模組中):        函数<4>.            (line  389)
* SETUP_ANNOTATIONS (opcode):            Python字节码说明.   (line  337)
* SETUP_ASYNC_WITH (opcode):             Python字节码说明.   (line  290)
* setup_environ() (wsgiref.handlers.BaseHandler 的方法): wsgiref handlers -- 服务器/网关基类.
                                                             (line  162)
* SETUP_FINALLY (opcode):                Python字节码说明.   (line  597)
* setup_python() (venv.EnvBuilder 的方法): API<2>.           (line   87)
* setup_scripts() (venv.EnvBuilder 的方法): API<2>.          (line   93)
* setup_testing_defaults() (於 wsgiref.util 模組中): wsgiref util -- WSGI 环境工具.
                                                             (line   56)
* SETUP_WITH (opcode):                   Python字节码说明.   (line  387)
* SetValue() (於 winreg 模組中):         函数<12>.           (line  382)
* SetValueEx() (於 winreg 模組中):       函数<12>.           (line  408)
* setworldcoordinates() (於 turtle 模組中): 窗口控制.        (line   81)
* setx() (於 turtle 模組中):             海龟动作.           (line  100)
* setxattr() (於 os 模組中):             Linux 扩展属性.     (line   53)
* sety() (於 turtle 模組中):             海龟动作.           (line  113)
* SET_ADD (opcode):                      Python字节码说明.   (line  303)
* set_all():                             引用计数细节.       (line   98)
* set_allowed_domains() (http.cookiejar.DefaultCookiePolicy 的方法): DefaultCookiePolicy 对象.
                                                             (line   63)
* set_alpn_protocols() (ssl.SSLContext 的方法): SSL 上下文.  (line  227)
* set_app() (wsgiref.simple_server.WSGIServer 的方法): wsgiref simple_server -- 一个简单的 WSGI HTTP 服务器.
                                                             (line   56)
* set_asyncgen_hooks() (於 sys 模組中):  sys --- 系统相关的参数和函数.
                                                             (line 1191)
* set_authorizer() (sqlite3.Connection 的方法): 连接对象（Connection）.
                                                             (line  179)
* set_auto_history() (於 readline 模組中): 历史列表.         (line   38)
* set_blocked_domains() (http.cookiejar.DefaultCookiePolicy 的方法): DefaultCookiePolicy 对象.
                                                             (line   50)
* set_blocking() (於 os 模組中):         文件描述符操作.     (line  551)
* set_boundary() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  343)
* set_boundary() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  492)
* set_break() (bdb.Bdb 的方法):          bdb --- Debugger framework.
                                                             (line  280)
* set_charset() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  196)
* set_children() (tkinter.ttk.Treeview 的方法): ttk Treeview.
                                                             (line   22)
* set_child_watcher() (asyncio.AbstractEventLoopPolicy 的方法): 策略对象.
                                                             (line   42)
* set_child_watcher() (於 asyncio 模組中): 进程监视器.       (line   25)
* set_ciphers() (ssl.SSLContext 的方法): SSL 上下文.         (line  215)
* set_completer() (於 readline 模組中):  Completion.         (line   12)
* set_completer_delims() (於 readline 模組中): Completion.   (line   40)
* set_completion_display_matches_hook() (於 readline 模組中): Completion.
                                                             (line   47)
* set_content() (email.contentmanager.ContentManager 的方法): email contentmanager 管理 MIME 内容.
                                                             (line   34)
* set_content() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  500)
* set_content() (於 email.contentmanager 模組中): 内容管理器实例.
                                                             (line   30)
* set_continue() (bdb.Bdb 的方法):       bdb --- Debugger framework.
                                                             (line  265)
* set_cookie() (http.cookiejar.CookieJar 的方法): CookieJar 和 FileCookieJar 对象.
                                                             (line   65)
* set_cookie_if_ok() (http.cookiejar.CookieJar 的方法): CookieJar 和 FileCookieJar 对象.
                                                             (line   61)
* set_coroutine_origin_tracking_depth() (於 sys 模組中): sys --- 系统相关的参数和函数.
                                                             (line 1212)
* set_current() (msilib.Feature 的方法): 相关特性<3>.        (line   14)
* set_data() (importlib.abc.SourceLoader 的方法): importlib abc —— 关于导入的抽象基类.
                                                             (line  485)
* set_data() (importlib.machinery.SourceFileLoader 的方法): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  208)
* set_date() (mailbox.MaildirMessage 的方法): MaildirMessage.
                                                             (line   86)
* set_debug() (asyncio.loop 的方法):     开启调试模式.       (line   13)
* set_debug() (於 gc 模組中):            gc --- 垃圾回收器接口.
                                                             (line   41)
* set_debuglevel() (ftplib.FTP 的方法):  FTP 对象.           (line   12)
* set_debuglevel() (http.client.HTTPConnection 的方法): HTTPConnection 对象.
                                                             (line   59)
* set_debuglevel() (nntplib.NNTP 的方法): 方法<3>.           (line  274)
* set_debuglevel() (poplib.POP3 的方法): POP3 对象.          (line   11)
* set_debuglevel() (smtplib.SMTP 的方法): SMTP 对象.         (line    8)
* set_debuglevel() (telnetlib.Telnet 的方法): Telnet 对象.   (line   76)
* set_defaults() (argparse.ArgumentParser 的方法): 解析器默认值.
                                                             (line    6)
* set_defaults() (optparse.OptionParser 的方法): Other methods.
                                                             (line   27)
* set_default_executor() (asyncio.loop 的方法): 在线程或者进程池中执行代码。.
                                                             (line   64)
* set_default_type() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  284)
* set_default_type() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  379)
* set_default_verify_paths() (ssl.SSLContext 的方法): SSL 上下文.
                                                             (line  208)
* set_ecdh_curve() (ssl.SSLContext 的方法): SSL 上下文.      (line  322)
* set_errno() (於 ctypes 模組中):        工具函数.           (line  148)
* set_escdelay() (於 curses 模組中):     函数<4>.            (line  364)
* set_event_loop() (asyncio.AbstractEventLoopPolicy 的方法): 策略对象.
                                                             (line   23)
* set_event_loop() (於 asyncio 模組中):  事件循环.           (line   49)
* set_event_loop_policy() (於 asyncio 模組中): 获取和设置策略.
                                                             (line   12)
* set_exception() (asyncio.Future 的方法): Future 对象<2>.   (line   45)
* set_exception() (concurrent.futures.Future 的方法): Future 对象.
                                                             (line  103)
* set_exception_handler() (asyncio.loop 的方法): 错误处理API.
                                                             (line    8)
* set_executable() (於 multiprocessing 模組中): 杂项<3>.     (line  105)
* set_executables() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  234)
* set_filter() (tkinter.filedialog.FileDialog 的方法): 原生 加载/保存 对话框.
                                                             (line  118)
* set_flags() (mailbox.MaildirMessage 的方法): MaildirMessage.
                                                             (line   66)
* set_flags() (mailbox.mboxMessage 的方法): mboxMessage.     (line   62)
* set_flags() (mailbox.MMDFMessage 的方法): MMDFMessage.     (line   61)
* set_from() (mailbox.mboxMessage 的方法): mboxMessage.      (line   48)
* set_from() (mailbox.MMDFMessage 的方法): MMDFMessage.      (line   47)
* set_handle_inheritable() (於 os 模組中): 文件描述符的继承. (line   35)
* set_history_length() (於 readline 模組中): 历史文件.       (line   27)
* set_include_dirs() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  102)
* set_info() (mailbox.MaildirMessage 的方法): MaildirMessage.
                                                             (line   95)
* set_inheritable() (socket.socket 的方法): 套接字对象.      (line  421)
* set_inheritable() (於 os 模組中):      文件描述符的继承.   (line   25)
* set_labels() (mailbox.BabylMessage 的方法): BabylMessage.  (line   48)
* set_last_error() (於 ctypes 模組中):   工具函数.           (line  155)
* set_libraries() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  127)
* set_library_dirs() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  143)
* set_link_objects() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  186)
* set_literal (2to3 fixer):              修复器.             (line  276)
* set_loader() (於 importlib.util 模組中): importlib util —— 导入器的工具程序代码.
                                                             (line  150)
* set_match_tests() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  310)
* set_memlimit() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  430)
* set_name() (asyncio.Task 的方法):      Task 对象.          (line  198)
* set_next() (bdb.Bdb 的方法):           bdb --- Debugger framework.
                                                             (line  247)
* set_nonstandard_attr() (http.cookiejar.Cookie 的方法): Cookie 对象<2>.
                                                             (line   97)
* set_npn_protocols() (ssl.SSLContext 的方法): SSL 上下文.   (line  244)
* set_ok() (http.cookiejar.CookiePolicy 的方法): CookiePolicy 对象.
                                                             (line    8)
* set_option_negotiation_callback() (telnetlib.Telnet 的方法): Telnet 对象.
                                                             (line  130)
* set_output_charset() (gettext.NullTranslations 的方法): NullTranslations 类.
                                                             (line   82)
* set_package() (於 importlib.util 模組中): importlib util —— 导入器的工具程序代码.
                                                             (line  163)
* set_param() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  292)
* set_param() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  432)
* set_pasv() (ftplib.FTP 的方法):        FTP 对象.           (line   87)
* set_payload() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  187)
* set_policy() (http.cookiejar.CookieJar 的方法): CookieJar 和 FileCookieJar 对象.
                                                             (line   50)
* set_position() (xdrlib.Unpacker 的方法): Unpacker 对象.    (line   16)
* set_pre_input_hook() (於 readline 模組中): 启动钩子.       (line   13)
* set_progress_handler() (sqlite3.Connection 的方法): 连接对象（Connection）.
                                                             (line  197)
* set_protocol() (asyncio.BaseTransport 的方法): 基础传输.   (line   73)
* set_proxy() (urllib.request.Request 的方法): Request 对象. (line  102)
* set_python_build() (於 distutils.sysconfig 模組中): distutils sysconfig --- System configuration information.
                                                             (line   98)
* set_quit() (bdb.Bdb 的方法):           bdb --- Debugger framework.
                                                             (line  270)
* set_recsrc() (ossaudiodev.oss_mixer_device 的方法): Mixer Device Objects.
                                                             (line   88)
* set_result() (asyncio.Future 的方法):  Future 对象<2>.     (line   38)
* set_result() (concurrent.futures.Future 的方法): Future 对象.
                                                             (line   93)
* set_return() (bdb.Bdb 的方法):         bdb --- Debugger framework.
                                                             (line  251)
* set_running_or_notify_cancel() (concurrent.futures.Future 的方法): Future 对象.
                                                             (line   74)
* set_runtime_library_dirs() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  154)
* set_selection() (tkinter.filedialog.FileDialog 的方法): 原生 加载/保存 对话框.
                                                             (line  122)
* set_seq1() (difflib.SequenceMatcher 的方法): SequenceMatcher 对象.
                                                             (line   47)
* set_seq2() (difflib.SequenceMatcher 的方法): SequenceMatcher 对象.
                                                             (line   51)
* set_seqs() (difflib.SequenceMatcher 的方法): SequenceMatcher 对象.
                                                             (line   38)
* set_sequences() (mailbox.MH 的方法):   MH.                 (line   52)
* set_sequences() (mailbox.MHMessage 的方法): MHMessage.     (line   34)
* set_servername_callback (ssl.SSLContext 的屬性): SSL 上下文.
                                                             (line  298)
* set_server_documentation() (xmlrpc.server.DocCGIXMLRPCRequestHandler 的方法): DocCGIXMLRPCRequestHandler.
                                                             (line   22)
* set_server_documentation() (xmlrpc.server.DocXMLRPCServer 的方法): DocXMLRPCServer 对象.
                                                             (line   21)
* set_server_name() (xmlrpc.server.DocCGIXMLRPCRequestHandler 的方法): DocCGIXMLRPCRequestHandler.
                                                             (line   17)
* set_server_name() (xmlrpc.server.DocXMLRPCServer 的方法): DocXMLRPCServer 对象.
                                                             (line   16)
* set_server_title() (xmlrpc.server.DocCGIXMLRPCRequestHandler 的方法): DocCGIXMLRPCRequestHandler.
                                                             (line   12)
* set_server_title() (xmlrpc.server.DocXMLRPCServer 的方法): DocXMLRPCServer 对象.
                                                             (line   11)
* set_spacing() (formatter.formatter 的方法): The Formatter Interface.
                                                             (line  139)
* set_startup_hook() (於 readline 模組中): 启动钩子.         (line    6)
* set_start_method() (於 multiprocessing 模組中): 杂项<3>.   (line  117)
* set_step() (bdb.Bdb 的方法):           bdb --- Debugger framework.
                                                             (line  243)
* set_subdir() (mailbox.MaildirMessage 的方法): MaildirMessage.
                                                             (line   54)
* set_tabsize() (於 curses 模組中):      函数<4>.            (line  377)
* set_task_factory() (asyncio.loop 的方法): 创建 Future 和 Task.
                                                             (line   27)
* set_terminator() (asynchat.async_chat 的方法): asynchat --- 异步套接字指令/响应处理程序.
                                                             (line   99)
* set_threshold() (於 gc 模組中):        gc --- 垃圾回收器接口.
                                                             (line   76)
* set_trace() (bdb.Bdb 的方法):          bdb --- Debugger framework.
                                                             (line  260)
* set_trace() (pdb.Pdb 的方法):          pdb --- Python 的调试器.
                                                             (line  158)
* set_trace() (於 bdb 模組中):           bdb --- Debugger framework.
                                                             (line  403)
* set_trace() (於 pdb 模組中):           pdb --- Python 的调试器.
                                                             (line  104)
* set_trace_callback() (sqlite3.Connection 的方法): 连接对象（Connection）.
                                                             (line  209)
* set_tunnel() (http.client.HTTPConnection 的方法): HTTPConnection 对象.
                                                             (line   67)
* set_type() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  461)
* set_unittest_reportflags() (於 doctest 模組中): Unittest API.
                                                             (line  137)
* set_unixfrom() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  116)
* set_unixfrom() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  130)
* set_until() (bdb.Bdb 的方法):          bdb --- Debugger framework.
                                                             (line  255)
* SET_UPDATE (opcode):                   Python字节码说明.   (line  495)
* set_url() (urllib.robotparser.RobotFileParser 的方法): urllib robotparser --- robots txt 语法分析程序.
                                                             (line   20)
* set_usage() (optparse.OptionParser 的方法): Other methods. (line    8)
* set_userptr() (curses.panel.Panel 的方法): Panel 对象.     (line   40)
* set_visible() (mailbox.BabylMessage 的方法): BabylMessage. (line   65)
* set_wakeup_fd() (於 signal 模組中):    模块内容<5>.        (line  357)
* set_write_buffer_limits() (asyncio.WriteTransport 的方法): 只写传输.
                                                             (line   30)
* SF_APPEND (於 stat 模組中):            stat --- 解析 stat 结果.
                                                             (line  349)
* SF_ARCHIVED (於 stat 模組中):          stat --- 解析 stat 结果.
                                                             (line  341)
* SF_IMMUTABLE (於 stat 模組中):         stat --- 解析 stat 结果.
                                                             (line  345)
* SF_MNOWAIT (於 os 模組中):             文件描述符操作.     (line  563)
* SF_NODISKIO (於 os 模組中):            文件描述符操作.     (line  563)
* SF_NOUNLINK (於 stat 模組中):          stat --- 解析 stat 结果.
                                                             (line  353)
* SF_SNAPSHOT (於 stat 模組中):          stat --- 解析 stat 结果.
                                                             (line  357)
* SF_SYNC (於 os 模組中):                文件描述符操作.     (line  563)
* shape (memoryview 的屬性):             内存视图.           (line  414)
* Shape (turtle 中的類別):               公共类.             (line   41)
* shape() (於 turtle 模組中):            外观.               (line    6)
* shapesize() (於 turtle 模組中):        外观.               (line   47)
* shapetransform() (於 turtle 模組中):   外观.               (line  143)
* share() (socket.socket 的方法):        套接字对象.         (line  479)
* ShareableList (multiprocessing.shared_memory 中的類別): multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line  208)
* ShareableList() (multiprocessing.managers.SharedMemoryManager 的方法): multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line  172)
* Shared Memory:                         multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line   10)
* SharedMemory (multiprocessing.shared_memory 中的類別): multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line   24)
* SharedMemory() (multiprocessing.managers.SharedMemoryManager 的方法): multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line  167)
* SharedMemoryManager (multiprocessing.managers 中的類別): multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line  146)
* shared_ciphers() (ssl.SSLSocket 的方法): SSL 套接字.       (line  187)
* shared_object_filename() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  472)
* shearfactor() (於 turtle 模組中):      外观.               (line   76)
* Shelf (shelve 中的類別):               限制.               (line   18)
* shelve (模組):                         shelve --- Python 对象持久化.
                                                             (line    6)
* shield() (於 asyncio 模組中):          屏蔽取消操作.       (line    6)
* shift() (decimal.Context 的方法):      上下文对象.         (line  436)
* shift() (decimal.Decimal 的方法):      Decimal 对象.       (line  460)
* shifting; operation:                   移位运算.           (line    6)
* shifting; operations:                  整数类型的按位运算. (line    6)
* shift_path_info() (於 wsgiref.util 模組中): wsgiref util -- WSGI 环境工具.
                                                             (line   33)
* shlex (shlex 中的類別):                shlex —— 简单的词义分析.
                                                             (line   80)
* shlex (模組):                          shlex —— 简单的词义分析.
                                                             (line    6)
* shm (multiprocessing.shared_memory.ShareableList 的屬性): multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line  239)
* shortDescription() (unittest.TestCase 的方法): 测试用例.   (line  726)
* shorten() (於 textwrap 模組中):        textwrap --- 文本自动换行与填充.
                                                             (line   44)
* SHORT_TIMEOUT (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  115)
* shouldFlush() (logging.handlers.BufferingHandler 的方法): MemoryHandler.
                                                             (line   30)
* shouldFlush() (logging.handlers.MemoryHandler 的方法): MemoryHandler.
                                                             (line   62)
* shouldStop (unittest.TestResult 的屬性): Loading and running tests.
                                                             (line  267)
* show() (curses.panel.Panel 的方法):    Panel 对象.         (line   45)
* show() (tkinter.commondialog.Dialog 的方法): tkinter commondialog --- 对话窗口模板.
                                                             (line   15)
* showerror() (於 tkinter.messagebox 模組中): tkinter messagebox --- Tkinter 消息提示.
                                                             (line   28)
* showinfo() (於 tkinter.messagebox 模組中): tkinter messagebox --- Tkinter 消息提示.
                                                             (line   23)
* showsyntaxerror() (code.InteractiveInterpreter 的方法): 交互解释器对象.
                                                             (line   38)
* showtraceback() (code.InteractiveInterpreter 的方法): 交互解释器对象.
                                                             (line   45)
* showturtle() (於 turtle 模組中):       可见性.             (line   14)
* showwarning() (於 tkinter.messagebox 模組中): tkinter messagebox --- Tkinter 消息提示.
                                                             (line   28)
* showwarning() (於 warnings 模組中):    可用的函数.         (line   44)
* show_code() (於 dis 模組中):           分析函数.           (line   21)
* show_compilers() (於 distutils.ccompiler 模組中): distutils ccompiler --- CCompiler基类.
                                                             (line   61)
* shuffle() (於 random 模組中):          序列用函数.         (line   42)
* shutdown() (concurrent.futures.Executor 的方法): Executor 对象.
                                                             (line   50)
* shutdown() (imaplib.IMAP4 的方法):     IMAP4 对象.         (line  243)
* shutdown() (multiprocessing.managers.BaseManager 的方法): 管理器.
                                                             (line   59)
* shutdown() (socket.socket 的方法):     套接字对象.         (line  473)
* shutdown() (socketserver.BaseServer 的方法): Server 对象<2>.
                                                             (line   48)
* shutdown() (於 logging 模組中):        模块级函数.         (line  284)
* shutdown_asyncgens() (asyncio.loop 的方法): 运行和停止循环.
                                                             (line   51)
* shutdown_default_executor() (asyncio.loop 的方法): 运行和停止循环.
                                                             (line   70)
* shutil (模組):                         shutil --- 高阶文件操作.
                                                             (line    6)
* side_effect (unittest.mock.Mock 的屬性): Mock 类.          (line  328)
* SIGABRT (於 signal 模組中):            模块内容<5>.        (line   25)
* SIGALRM (於 signal 模組中):            模块内容<5>.        (line   29)
* SIGBREAK (於 signal 模組中):           模块内容<5>.        (line   35)
* SIGBUS (於 signal 模組中):             模块内容<5>.        (line   41)
* SIGCHLD (於 signal 模組中):            模块内容<5>.        (line   47)
* SIGCLD (於 signal 模組中):             模块内容<5>.        (line   53)
* SIGCONT (於 signal 模組中):            模块内容<5>.        (line   57)
* SIGFPE (於 signal 模組中):             模块内容<5>.        (line   63)
* SIGHUP (於 signal 模組中):             模块内容<5>.        (line   73)
* SIGILL (於 signal 模組中):             模块内容<5>.        (line   79)
* SIGINT:                                信号处理<2>.        (line    8)
* SIGINT <1>:                            信号处理<2>.        (line   20)
* SIGINT (於 signal 模組中):             模块内容<5>.        (line   83)
* siginterrupt() (於 signal 模組中):     模块内容<5>.        (line  391)
* SIGKILL (於 signal 模組中):            模块内容<5>.        (line   89)
* signal (模組):                         signal --- 设置异步事件处理程序.
                                                             (line    6)
* signal() (於 signal 模組中):           模块内容<5>.        (line  403)
* Signature (inspect 中的類別):          Introspecting callables with the Signature object.
                                                             (line   50)
* signature (inspect.BoundArguments 的屬性): Introspecting callables with the Signature object.
                                                             (line  310)
* signature() (於 inspect 模組中):       Introspecting callables with the Signature object.
                                                             (line   12)
* sigpending() (於 signal 模組中):       模块内容<5>.        (line  425)
* SIGPIPE (於 signal 模組中):            模块内容<5>.        (line   97)
* SIGSEGV (於 signal 模組中):            模块内容<5>.        (line  105)
* SIGTERM (於 signal 模組中):            模块内容<5>.        (line  109)
* sigtimedwait() (於 signal 模組中):     模块内容<5>.        (line  473)
* SIGUSR1 (於 signal 模組中):            模块内容<5>.        (line  113)
* SIGUSR2 (於 signal 模組中):            模块内容<5>.        (line  119)
* sigwait() (於 signal 模組中):          模块内容<5>.        (line  437)
* sigwaitinfo() (於 signal 模組中):      模块内容<5>.        (line  450)
* SIGWINCH (於 signal 模組中):           模块内容<5>.        (line  125)
* SIG_BLOCK (於 signal 模組中):          模块内容<5>.        (line  176)
* SIG_DFL (於 signal 模組中):            模块内容<5>.        (line   15)
* SIG_IGN (於 signal 模組中):            模块内容<5>.        (line   21)
* SIG_SETMASK (於 signal 模組中):        模块内容<5>.        (line  190)
* SIG_UNBLOCK (於 signal 模組中):        模块内容<5>.        (line  183)
* Simple Mail Transfer Protocol:         smtplib ---SMTP协议客户端.
                                                             (line    8)
* simple; statement:                     简单语句.           (line    6)
* SimpleCookie (http.cookies 中的類別):  http cookies --- HTTP状态管理.
                                                             (line   42)
* simplefilter() (於 warnings 模組中):   可用的函数.         (line   71)
* SimpleHandler (wsgiref.handlers 中的類別): wsgiref handlers -- 服务器/网关基类.
                                                             (line   58)
* SimpleHTTPRequestHandler (http.server 中的類別): http server --- HTTP 服务器.
                                                             (line  282)
* SimpleNamespace (types 中的類別):      附加工具类和函数.   (line    6)
* SimpleQueue (multiprocessing 中的類別): 管道和队列.        (line  172)
* SimpleQueue (queue 中的類別):          queue --- 一个同步的队列类.
                                                             (line   62)
* SimpleXMLRPCRequestHandler (xmlrpc.server 中的類別): xmlrpc server --- 基本 XML-RPC 服务器.
                                                             (line   51)
* SimpleXMLRPCServer (xmlrpc.server 中的類別): xmlrpc server --- 基本 XML-RPC 服务器.
                                                             (line   19)
* sin() (於 cmath 模組中):               三角函数<2>.        (line   26)
* sin() (於 math 模組中):                三角函数.           (line   53)
* single dispatch（單一調度）:           術語表.             (line 1047)
* SingleAddressHeader (email.headerregistry 中的類別): email headerregistry 自定义标头对象.
                                                             (line  176)
* singledispatch() (於 functools 模組中): functools --- 高阶函数和可调用对象上的操作.
                                                             (line  333)
* singledispatchmethod (functools 中的類別): functools --- 高阶函数和可调用对象上的操作.
                                                             (line  463)
* singleton; tuple:                      标准类型层级结构.   (line  135)
* sinh() (於 cmath 模組中):              双曲函数<2>.        (line   26)
* sinh() (於 math 模組中):               双曲函数.           (line   24)
* SIO_KEEPALIVE_VALS (於 socket 模組中): 常数<6>.            (line  180)
* SIO_LOOPBACK_FAST_PATH (於 socket 模組中): 常数<6>.        (line  180)
* SIO_RCVALL (於 socket 模組中):         常数<6>.            (line  180)
* site (模組):                           site —— 指定域的配置钩子.
                                                             (line    6)
* site command line option; –user-base:  命令行界面<6>.      (line   16)
* site command line option; –user-site:  命令行界面<6>.      (line   20)
* site-packages; directory:              site —— 指定域的配置钩子.
                                                             (line   21)
* site_maps() (urllib.robotparser.RobotFileParser 的方法): urllib robotparser --- robots txt 语法分析程序.
                                                             (line   63)
* sixtofour (ipaddress.IPv6Address 的屬性): 地址对象.        (line  233)
* size (multiprocessing.shared_memory.SharedMemory 的屬性): multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line   73)
* size (struct.Struct 的屬性):           类.                 (line   55)
* size (tarfile.TarInfo 的屬性):         TarInfo 对象.       (line   42)
* size (tracemalloc.Statistic 的屬性):   统计.               (line   19)
* size (tracemalloc.StatisticDiff 的屬性): StatisticDiff.    (line   26)
* size (tracemalloc.Trace 的屬性):       跟踪.               (line   23)
* size() (ftplib.FTP 的方法):            FTP 对象.           (line  192)
* size() (mmap.mmap 的方法):             mmap --- 内存映射文件支持.
                                                             (line  233)
* Sized (collections.abc 中的類別):      容器抽象基类.       (line  112)
* Sized (typing 中的類別):               collections abc 对应的其他类型.
                                                             (line   64)
* sizeof() (於 ctypes 模組中):           工具函数.           (line  163)
* size_diff (tracemalloc.StatisticDiff 的屬性): StatisticDiff.
                                                             (line   32)
* SIZE_MAX:                              整數物件.           (line  186)
* SKIP (於 doctest 模組中):              选项标记.           (line   85)
* skip() (chunk.Chunk 的方法):           chunk --- 读取 IFF 分块数据.
                                                             (line   98)
* skip() (於 unittest 模組中):           跳过测试与预计的失败.
                                                             (line   82)
* skipIf() (於 unittest 模組中):         跳过测试与预计的失败.
                                                             (line   86)
* skipinitialspace (csv.Dialect 的屬性): 变种与格式参数.     (line   54)
* skipped (unittest.TestResult 的屬性):  Loading and running tests.
                                                             (line  249)
* skippedEntity() (xml.sax.handler.ContentHandler 的方法): ContentHandler 对象.
                                                             (line  148)
* SkipTest:                              跳过测试与预计的失败.
                                                             (line  101)
* skipTest() (unittest.TestCase 的方法): 测试用例.           (line   97)
* skipUnless() (於 unittest 模組中):     跳过测试与预计的失败.
                                                             (line   90)
* skip_unless_bind_unix_socket() (於 test.support.socket_helper 模組中): test support socket_helper --- Utilities for socket tests.
                                                             (line   59)
* skip_unless_symlink() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  623)
* skip_unless_xattr() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  628)
* SLASH (於 token 模組中):               token --- 与Python解析树一起使用的常量.
                                                             (line   90)
* SLASHEQUAL (於 token 模組中):          token --- 与Python解析树一起使用的常量.
                                                             (line  178)
* slave() (nntplib.NNTP 的方法):         方法<3>.            (line  270)
* sleep() (於 asyncio 模組中):           休眠.               (line    6)
* sleep() (於 time 模組中):              函数<3>.            (line  186)
* slice:                                 切片.               (line    6)
* Slice (ast 中的類別):                  Subscripting.       (line   27)
* slice (內建類別):                      內建函式.           (line 1276)
* slice; assignment:                     可变序列类型.       (line   14)
* slice; operation:                      通用序列操作.       (line   17)
* slice（切片）:                         術語表.             (line 1052)
* slicing:                               标准类型层级结构.   (line  102)
* slicing <1>:                           标准类型层级结构.   (line  151)
* slicing <2>:                           切片.               (line    6)
* slicing; assignment:                   赋值语句.           (line   98)
* SMALLEST (於 test.support 模組中):     test support --- Utilities for the Python test suite.
                                                             (line  215)
* SMTP (smtplib 中的類別):               smtplib ---SMTP协议客户端.
                                                             (line   15)
* SMTP (於 email.policy 模組中):         email policy Policy 对象.
                                                             (line  397)
* SMTP; protocol:                        smtplib ---SMTP协议客户端.
                                                             (line    8)
* SMTPAuthenticationError:               smtplib ---SMTP协议客户端.
                                                             (line  150)
* SMTPChannel (smtpd 中的類別):          SMTPChannel 对象.   (line    6)
* SMTPConnectError:                      smtplib ---SMTP协议客户端.
                                                             (line  136)
* smtpd (模組):                          smtpd --- SMTP 服务器.
                                                             (line    6)
* SMTPDataError:                         smtplib ---SMTP协议客户端.
                                                             (line  132)
* SMTPException:                         smtplib ---SMTP协议客户端.
                                                             (line  103)
* SMTPHandler (logging.handlers 中的類別): SMTPHandler.      (line    9)
* SMTPHeloError:                         smtplib ---SMTP协议客户端.
                                                             (line  140)
* smtplib (模組):                        smtplib ---SMTP协议客户端.
                                                             (line    6)
* SMTPNotSupportedError:                 smtplib ---SMTP协议客户端.
                                                             (line  144)
* SMTPRecipientsRefused:                 smtplib ---SMTP协议客户端.
                                                             (line  126)
* SMTPResponseException:                 smtplib ---SMTP协议客户端.
                                                             (line  114)
* SMTPSenderRefused:                     smtplib ---SMTP协议客户端.
                                                             (line  120)
* SMTPServer (smtpd 中的類別):           SMTPServer 对象.    (line    6)
* SMTPServerDisconnected:                smtplib ---SMTP协议客户端.
                                                             (line  109)
* SMTPUTF8 (於 email.policy 模組中):     email policy Policy 对象.
                                                             (line  402)
* smtp_server (smtpd.SMTPChannel 的屬性): SMTPChannel 对象.  (line   37)
* SMTP_SSL (smtplib 中的類別):           smtplib ---SMTP协议客户端.
                                                             (line   57)
* smtp_state (smtpd.SMTPChannel 的屬性): SMTPChannel 对象.   (line   54)
* Snapshot (tracemalloc 中的類別):       快照.               (line    6)
* sndhdr (模組):                         sndhdr --- 推测声音文件的类型.
                                                             (line    6)
* SND_ALIAS (於 winsound 模組中):        winsound —— Windows 系统的声音播放接口.
                                                             (line   41)
* SND_ASYNC (於 winsound 模組中):        winsound —— Windows 系统的声音播放接口.
                                                             (line  100)
* SND_FILENAME (於 winsound 模組中):     winsound —— Windows 系统的声音播放接口.
                                                             (line   36)
* SND_LOOP (於 winsound 模組中):         winsound —— Windows 系统的声音播放接口.
                                                             (line   81)
* SND_MEMORY (於 winsound 模組中):       winsound —— Windows 系统的声音播放接口.
                                                             (line   86)
* SND_NODEFAULT (於 winsound 模組中):    winsound —— Windows 系统的声音播放接口.
                                                             (line  104)
* SND_NOSTOP (於 winsound 模組中):       winsound —— Windows 系统的声音播放接口.
                                                             (line  108)
* SND_NOWAIT (於 winsound 模組中):       winsound —— Windows 系统的声音播放接口.
                                                             (line  112)
* SND_PURGE (於 winsound 模組中):        winsound —— Windows 系统的声音播放接口.
                                                             (line   94)
* sniff() (csv.Sniffer 的方法):          模块内容<3>.        (line  195)
* Sniffer (csv 中的類別):                模块内容<3>.        (line  189)
* sni_callback (ssl.SSLContext 的屬性):  SSL 上下文.         (line  258)
* socket (socket 中的類別):              创建套接字.         (line    8)
* socket (socketserver.BaseServer 的屬性): Server 对象<2>.   (line   76)
* socket (模組):                         socket --- 底层网络接口.
                                                             (line    6)
* socket() (imaplib.IMAP4 的方法):       IMAP4 对象.         (line  248)
* socket() (in module socket):           select --- 等待 I/O 完成.
                                                             (line  113)
* SocketHandler (logging.handlers 中的類別): SocketHandler.  (line    9)
* socketpair() (於 socket 模組中):       创建套接字.         (line   55)
* sockets (asyncio.Server 的屬性):       Server 对象.        (line   92)
* socketserver (模組):                   socketserver --- 用于网络服务器的框架.
                                                             (line    6)
* SocketType (於 socket 模組中):         创建套接字.         (line  155)
* socket_type (socketserver.BaseServer 的屬性): Server 对象<2>.
                                                             (line   95)
* sock_accept() (asyncio.loop 的方法):   直接使用 socket 对象.
                                                             (line   68)
* SOCK_CLOEXEC (於 socket 模組中):       常数<6>.            (line   29)
* sock_connect() (asyncio.loop 的方法):  直接使用 socket 对象.
                                                             (line   50)
* SOCK_DGRAM (於 socket 模組中):         常数<6>.            (line   19)
* SOCK_MAX_SIZE (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  155)
* SOCK_NONBLOCK (於 socket 模組中):      常数<6>.            (line   29)
* SOCK_RAW (於 socket 模組中):           常数<6>.            (line   19)
* SOCK_RDM (於 socket 模組中):           常数<6>.            (line   19)
* sock_recv() (asyncio.loop 的方法):     直接使用 socket 对象.
                                                             (line   11)
* sock_recv_into() (asyncio.loop 的方法): 直接使用 socket 对象.
                                                             (line   24)
* sock_sendall() (asyncio.loop 的方法):  直接使用 socket 对象.
                                                             (line   35)
* sock_sendfile() (asyncio.loop 的方法): 直接使用 socket 对象.
                                                             (line   87)
* SOCK_SEQPACKET (於 socket 模組中):     常数<6>.            (line   19)
* SOCK_STREAM (於 socket 模組中):        常数<6>.            (line   19)
* softkwlist (於 keyword 模組中):        keyword --- 检验Python关键字.
                                                             (line   28)
* SOL_ALG (於 socket 模組中):            常数<6>.            (line  196)
* SOL_RDS (於 socket 模組中):            常数<6>.            (line  167)
* SOMAXCONN (於 socket 模組中):          常数<6>.            (line   45)
* sort() (imaplib.IMAP4 的方法):         IMAP4 对象.         (line  252)
* sort() (list 的方法):                  List（串列）<2>.    (line   33)
* sortdict() (於 test.support 模組中):   test support --- Utilities for the Python test suite.
                                                             (line  284)
* sorted() (內建函式):                   內建函式.           (line 1291)
* sortTestMethodsUsing (unittest.TestLoader 的屬性): Loading and running tests.
                                                             (line  185)
* sort_stats() (pstats.Stats 的方法):    Stats 类.           (line   67)
* source (doctest.Example 的屬性):       Example 对象.       (line   15)
* source (pdb command):                  调试器命令.         (line  209)
* source (shlex.shlex 的屬性):           shlex 对象.         (line  124)
* source character set:                  编码声明.           (line    6)
* SourceFileLoader (importlib.machinery 中的類別): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  183)
* sourcehook() (shlex.shlex 的方法):     shlex 对象.         (line   25)
* SourcelessFileLoader (importlib.machinery 中的類別): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  221)
* SourceLoader (importlib.abc 中的類別): importlib abc —— 关于导入的抽象基类.
                                                             (line  436)
* SOURCE_DATE_EPOCH:                     py_compile<2>.      (line    7)
* SOURCE_DATE_EPOCH <1>:                 库<30>.             (line  451)
* SOURCE_DATE_EPOCH <2>:                 构建<29>.           (line   15)
* SOURCE_DATE_EPOCH <3>:                 py_compile --- 编译 Python 源文件.
                                                             (line   51)
* SOURCE_DATE_EPOCH <4>:                 py_compile --- 编译 Python 源文件.
                                                             (line   66)
* SOURCE_DATE_EPOCH <5>:                 py_compile --- 编译 Python 源文件.
                                                             (line   69)
* SOURCE_DATE_EPOCH <6>:                 Command-line use.   (line   90)
* source_from_cache() (於 imp 模組中):   imp —— 由代码内部访问 import 。.
                                                             (line  218)
* source_from_cache() (於 importlib.util 模組中): importlib util —— 导入器的工具程序代码.
                                                             (line   49)
* source_hash() (於 importlib.util 模組中): importlib util —— 导入器的工具程序代码.
                                                             (line  191)
* SOURCE_SUFFIXES (於 importlib.machinery 模組中): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line   12)
* source_to_code() (importlib.abc.InspectLoader 的靜態成員): importlib abc —— 关于导入的抽象基类.
                                                             (line  359)
* space:                                 缩进.               (line    6)
* space; in printf-style formatting:     printf 风格的字符串格式化.
                                                             (line   53)
* space; in printf-style formatting <1>: printf 风格的字节串格式化.
                                                             (line   52)
* space; in string formatting:           格式规格迷你语言.   (line   59)
* span() (re.Match 的方法):              匹配对象.           (line  134)
* spawn() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  486)
* spawn() (於 pty 模組中):               pty --- 伪终端工具. (line   31)
* spawnl() (於 os 模組中):               进程管理.           (line  442)
* spawnle() (於 os 模組中):              进程管理.           (line  442)
* spawnlp() (於 os 模組中):              进程管理.           (line  442)
* spawnlpe() (於 os 模組中):             进程管理.           (line  442)
* spawnv() (於 os 模組中):               进程管理.           (line  442)
* spawnve() (於 os 模組中):              进程管理.           (line  442)
* spawnvp() (於 os 模組中):              进程管理.           (line  442)
* spawnvpe() (於 os 模組中):             进程管理.           (line  442)
* spawn_python() (於 test.support.script_helper 模組中): test support script_helper --- Utilities for the Python execution tests.
                                                             (line   67)
* special method（特殊方法）:            術語表.             (line 1060)
* special; attribute:                    标准类型层级结构.   (line   10)
* special; method:                       術語表.             (line 1064)
* specified_attributes (xml.parsers.expat.xmlparser 的屬性): XMLParser对象<2>.
                                                             (line   96)
* spec_from_file_location() (於 importlib.util 模組中): importlib util —— 导入器的工具程序代码.
                                                             (line  180)
* spec_from_loader() (於 importlib.util 模組中): importlib util —— 导入器的工具程序代码.
                                                             (line  171)
* speed() (ossaudiodev.oss_audio_device 的方法): 音频设备对象.
                                                             (line  124)
* speed() (於 turtle 模組中):            海龟动作.           (line  288)
* Spinbox (tkinter.ttk 中的類別):        ttk Spinbox.        (line    6)
* split() (bytearray 的方法):            bytes 和 bytearray 操作.
                                                             (line  331)
* split() (bytes 的方法):                bytes 和 bytearray 操作.
                                                             (line  331)
* split() (re.Pattern 的方法):           正则表达式对象 （正则对象）.
                                                             (line   60)
* split() (str 的方法):                  字符串的方法<2>.    (line  390)
* split() (於 os.path 模組中):           os path --- 常用路径操作.
                                                             (line  326)
* split() (於 re 模組中):                模块内容.           (line  137)
* split() (於 shlex 模組中):             shlex —— 简单的词义分析.
                                                             (line   16)
* splitdrive() (於 os.path 模組中):      os path --- 常用路径操作.
                                                             (line  339)
* splitext() (於 os.path 模組中):        os path --- 常用路径操作.
                                                             (line  361)
* splitlines() (bytearray 的方法):       bytes 和 bytearray 操作.
                                                             (line  546)
* splitlines() (bytes 的方法):           bytes 和 bytearray 操作.
                                                             (line  546)
* splitlines() (str 的方法):             字符串的方法<2>.    (line  425)
* SplitResult (urllib.parse 中的類別):   结构化解析结果.     (line   47)
* SplitResultBytes (urllib.parse 中的類別): 结构化解析结果.  (line   71)
* split_quoted() (於 distutils.util 模組中): distutils util --- Miscellaneous other utility functions.
                                                             (line  118)
* SpooledTemporaryFile() (於 tempfile 模組中): tempfile --- 生成临时文件和目录.
                                                             (line   78)
* sprintf-style formatting:              printf 风格的字符串格式化.
                                                             (line    6)
* sprintf-style formatting <1>:          printf 风格的字节串格式化.
                                                             (line    6)
* spwd (模組):                           spwd —— shadow 密码库.
                                                             (line    6)
* sqlite3 (模組):                        sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块.
                                                             (line    6)
* sqlite_version (於 sqlite3 模組中):    模块函数和常量.     (line   30)
* sqlite_version_info (於 sqlite3 模組中): 模块函数和常量.   (line   34)
* sqrt() (decimal.Context 的方法):       上下文对象.         (line  440)
* sqrt() (decimal.Decimal 的方法):       Decimal 对象.       (line  468)
* sqrt() (於 cmath 模組中):              幂函数与对数函数<2>.
                                                             (line   20)
* sqrt() (於 math 模組中):               幂函数与对数函数.   (line   65)
* ssizeargfunc (C 型態):                 Slot Type typedefs. (line  105)
* ssizeobjargproc (C 型態):              Slot Type typedefs. (line  107)
* SSL:                                   ssl --- 套接字对象的 TLS/SSL 包装器.
                                                             (line    8)
* ssl (模組):                            ssl --- 套接字对象的 TLS/SSL 包装器.
                                                             (line    6)
* SSLCertVerificationError:              异常<12>.           (line   69)
* SSLContext (ssl 中的類別):             SSL 上下文.         (line   12)
* SSLEOFError:                           异常<12>.           (line   62)
* SSLError:                              异常<12>.           (line    6)
* SSLErrorNumber (ssl 中的類別):         常量<3>.            (line  463)
* SSLKEYLOGFILE:                         上下文创建.         (line   27)
* SSLKEYLOGFILE <1>:                     上下文创建.         (line   55)
* SSLObject (ssl 中的類別):              内存 BIO 支持<2>.   (line   26)
* sslobject_class (ssl.SSLContext 的屬性): SSL 上下文.       (line  410)
* SSLSession (ssl 中的類別):             SSL 会话.           (line    8)
* SSLSocket (ssl 中的類別):              SSL 套接字.         (line    6)
* sslsocket_class (ssl.SSLContext 的屬性): SSL 上下文.       (line  387)
* SSLSyscallError:                       异常<12>.           (line   55)
* SSLv3 (ssl.TLSVersion 的屬性):         常量<3>.            (line  484)
* SSLWantReadError:                      异常<12>.           (line   39)
* SSLWantWriteError:                     异常<12>.           (line   47)
* SSLZeroReturnError:                    异常<12>.           (line   32)
* SSL_CERT_FILE:                         LibreSSL 支持.      (line   13)
* SSL_CERT_PATH:                         LibreSSL 支持.      (line   14)
* ssl_version (ftplib.FTP_TLS 的屬性):   FTP_TLS 对象.       (line    8)
* st() (於 turtle 模組中):               可见性.             (line   14)
* st2list() (於 parser 模組中):          转换 ST 对象.       (line   11)
* st2tuple() (於 parser 模組中):         转换 ST 对象.       (line   31)
* stack (traceback.TracebackException 的屬性): TracebackException Objects.
                                                             (line   34)
* stack viewer:                          调试菜单（仅 window 编辑器）.
                                                             (line   15)
* stack() (於 inspect 模組中):           The interpreter stack.
                                                             (line   82)
* stack; trace:                          标准类型层级结构.   (line  587)
* stackable; streams:                    codecs --- 编解码器注册和相关基类.
                                                             (line    8)
* StackSummary (traceback 中的類別):     StackSummary Objects.
                                                             (line   11)
* stack_effect() (於 dis 模組中):        分析函数.           (line  121)
* stack_size() (於 threading 模組中):    threading --- 基于线程的并行.
                                                             (line  119)
* stack_size() (於 _thread 模組中):      _thread --- 底层多线程 API.
                                                             (line   79)
* stamp() (於 turtle 模組中):            海龟动作.           (line  225)
* Standard C:                            字符串与字节串字面值.
                                                             (line   59)
* standard input:                        完整的 Python 程序. (line   19)
* standard; output:                      表达式语句.         (line   15)
* standarderror (2to3 fixer):            修复器.             (line  281)
* standard_b64decode() (於 base64 模組中): base64 —— Base16、Base32、Base64、Base85 資料編碼.
                                                             (line   66)
* standard_b64encode() (於 base64 模組中): base64 —— Base16、Base32、Base64、Base85 資料編碼.
                                                             (line   61)
* standend() (curses.window 的方法):     Window 对象.        (line  441)
* standout() (curses.window 的方法):     Window 对象.        (line  445)
* STAR (於 token 模組中):                token --- 与Python解析树一起使用的常量.
                                                             (line   86)
* STAREQUAL (於 token 模組中):           token --- 与Python解析树一起使用的常量.
                                                             (line  174)
* starmap() (multiprocessing.pool.Pool 的方法): 进程池.      (line  119)
* starmap() (於 itertools 模組中):       Itertool函数.       (line  469)
* starmap_async() (multiprocessing.pool.Pool 的方法): 进程池.
                                                             (line  130)
* Starred (ast 中的類別):                Variables.          (line   43)
* start (range 的屬性):                  range 对象.         (line   54)
* start (slice object attribute):        标准类型层级结构.   (line  624)
* start (slice object attribute) <1>:    切片.               (line   22)
* start (UnicodeError 的屬性):           具体异常.           (line  321)
* start() (logging.handlers.QueueListener 的方法): QueueListener.
                                                             (line   60)
* start() (multiprocessing.managers.BaseManager 的方法): 管理器.
                                                             (line   34)
* start() (multiprocessing.Process 的方法): Process 和异常.  (line   36)
* start() (re.Match 的方法):             匹配对象.           (line  112)
* start() (threading.Thread 的方法):     线程对象.           (line   73)
* start() (tkinter.ttk.Progressbar 的方法): ttk Progressbar. (line    8)
* start() (xml.etree.ElementTree.TreeBuilder 的方法): TreeBuilder 对象.
                                                             (line   37)
* start() (於 tracemalloc 模組中):       函数<10>.           (line   68)
* StartCdataSectionHandler() (xml.parsers.expat.xmlparser 的方法): XMLParser对象<2>.
                                                             (line  250)
* StartDoctypeDeclHandler() (xml.parsers.expat.xmlparser 的方法): XMLParser对象<2>.
                                                             (line  154)
* startDocument() (xml.sax.handler.ContentHandler 的方法): ContentHandler 对象.
                                                             (line   25)
* startElement() (xml.sax.handler.ContentHandler 的方法): ContentHandler 对象.
                                                             (line   69)
* StartElementHandler() (xml.parsers.expat.xmlparser 的方法): XMLParser对象<2>.
                                                             (line  185)
* startElementNS() (xml.sax.handler.ContentHandler 的方法): ContentHandler 对象.
                                                             (line   86)
* startfile() (於 os 模組中):            进程管理.           (line  535)
* STARTF_USESHOWWINDOW (於 subprocess 模組中): Windows 常数. (line   30)
* STARTF_USESTDHANDLES (於 subprocess 模組中): Windows 常数. (line   24)
* StartNamespaceDeclHandler() (xml.parsers.expat.xmlparser 的方法): XMLParser对象<2>.
                                                             (line  232)
* startPrefixMapping() (xml.sax.handler.ContentHandler 的方法): ContentHandler 对象.
                                                             (line   41)
* startswith() (bytearray 的方法):       bytes 和 bytearray 操作.
                                                             (line  211)
* startswith() (bytes 的方法):           bytes 和 bytearray 操作.
                                                             (line  211)
* startswith() (str 的方法):             字符串的方法<2>.    (line  494)
* startTest() (unittest.TestResult 的方法): Loading and running tests.
                                                             (line  329)
* startTestRun() (unittest.TestResult 的方法): Loading and running tests.
                                                             (line  338)
* starttls() (imaplib.IMAP4 的方法):     IMAP4 对象.         (line  267)
* starttls() (nntplib.NNTP 的方法):      方法<3>.            (line   53)
* starttls() (smtplib.SMTP 的方法):      SMTP 对象.          (line  154)
* STARTUPINFO (subprocess 中的類別):     Windows Popen 助手. (line    8)
* start_color() (於 curses 模組中):      函数<4>.            (line  396)
* start_component() (msilib.Directory 的方法): Directory Objects.
                                                             (line   20)
* start_new_thread() (於 _thread 模組中): _thread --- 底层多线程 API.
                                                             (line   27)
* start_ns() (xml.etree.ElementTree.TreeBuilder 的方法): TreeBuilder 对象.
                                                             (line   66)
* start_server() (於 asyncio 模組中):    流.                 (line   59)
* start_serving() (asyncio.Server 的方法): Server 对象.      (line   43)
* start_threads() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  595)
* start_tls() (asyncio.loop 的方法):     TLS 升级.           (line    6)
* start_unix_server() (於 asyncio 模組中): 流.               (line  107)
* stat (模組):                           stat --- 解析 stat 结果.
                                                             (line    6)
* stat() (nntplib.NNTP 的方法):          方法<3>.            (line  194)
* stat() (os.DirEntry 的方法):           文件和目录.         (line  825)
* stat() (pathlib.Path 的方法):          方法<2>.            (line   38)
* stat() (poplib.POP3 的方法):           POP3 对象.          (line   46)
* stat() (於 os 模組中):                 文件和目录.         (line  853)
* state() (tkinter.ttk.Widget 的方法):   ttk Widget.         (line   25)
* statement grouping:                    缩进.               (line    6)
* statement; assignment, annotated:      带标注的赋值语句.   (line    6)
* statement; assignment, augmented:      增强赋值语句.       (line    6)
* statement（陳述式）:                   術語表.             (line 1066)
* staticmethod() (內建函式):             內建函式.           (line 1322)
* static_order() (graphlib.TopologicalSorter 的方法): graphlib --- 操作类似图的结构的功能.
                                                             (line  139)
* Statistic (tracemalloc 中的類別):      统计.               (line    6)
* StatisticDiff (tracemalloc 中的類別):  StatisticDiff.      (line    6)
* statistics (模組):                     statistics --- 數學統計函式.
                                                             (line    6)
* statistics() (tracemalloc.Snapshot 的方法): 快照.          (line   56)
* StatisticsError:                       异常<3>.            (line    8)
* Stats (pstats 中的類別):               Stats 类.           (line    9)
* status (http.client.HTTPResponse 的屬性): HTTPResponse 对象.
                                                             (line   55)
* status (urllib.response.addinfourl 的屬性): urllib response --- urllib 使用的 Response 类.
                                                             (line   21)
* status() (imaplib.IMAP4 的方法):       IMAP4 对象.         (line  279)
* statvfs() (於 os 模組中):              文件和目录.         (line 1085)
* stat_result (os 中的類別):             文件和目录.         (line  900)
* StdButtonBox (tkinter.tix 中的類別):   Basic Widgets.      (line   64)
* stderr (asyncio.asyncio.subprocess.Process 的屬性): 与子进程交互.
                                                             (line  109)
* stderr (in module sys):                标准类型层级结构.   (line  492)
* stderr (in module sys) <1>:            Sub-interpreter support.
                                                             (line   26)
* stderr (subprocess.CalledProcessError 的屬性): 使用 subprocess 模块.
                                                             (line  194)
* stderr (subprocess.CompletedProcess 的屬性): 使用 subprocess 模块.
                                                             (line  102)
* stderr (subprocess.Popen 的屬性):      Popen 对象.         (line  109)
* stderr (subprocess.TimeoutExpired 的屬性): 使用 subprocess 模块.
                                                             (line  161)
* stderr (於 sys 模組中):                sys --- 系统相关的参数和函数.
                                                             (line 1241)
* stdev (statistics.NormalDist 的屬性):  NormalDist 对象.    (line   30)
* stdev() (於 statistics 模組中):        函式細節.           (line  292)
* stdin (asyncio.asyncio.subprocess.Process 的屬性): 与子进程交互.
                                                             (line   99)
* stdin (in module sys):                 标准类型层级结构.   (line  492)
* stdin (in module sys) <1>:             Sub-interpreter support.
                                                             (line   26)
* stdin (subprocess.Popen 的屬性):       Popen 对象.         (line   94)
* stdin (於 sys 模組中):                 sys --- 系统相关的参数和函数.
                                                             (line 1241)
* stdin; stdout; sdterr:                 Process-wide parameters.
                                                             (line    9)
* stdio:                                 标准类型层级结构.   (line  492)
* stdout (asyncio.asyncio.subprocess.Process 的屬性): 与子进程交互.
                                                             (line  104)
* stdout (in module sys):                标准类型层级结构.   (line  492)
* stdout (in module sys) <1>:            Sub-interpreter support.
                                                             (line   26)
* stdout (subprocess.CalledProcessError 的屬性): 使用 subprocess 模块.
                                                             (line  190)
* stdout (subprocess.CompletedProcess 的屬性): 使用 subprocess 模块.
                                                             (line   92)
* stdout (subprocess.Popen 的屬性):      Popen 对象.         (line  101)
* stdout (subprocess.TimeoutExpired 的屬性): 使用 subprocess 模块.
                                                             (line  157)
* STDOUT (於 subprocess 模組中):         使用 subprocess 模块.
                                                             (line  128)
* stdout (於 sys 模組中):                sys --- 系统相关的参数和函数.
                                                             (line 1241)
* STD_ERROR_HANDLE (於 subprocess 模組中): Windows 常数.     (line   16)
* STD_INPUT_HANDLE (於 subprocess 模組中): Windows 常数.     (line    8)
* STD_OUTPUT_HANDLE (於 subprocess 模組中): Windows 常数.    (line   12)
* step (pdb command):                    调试器命令.         (line  132)
* step (range 的屬性):                   range 对象.         (line   62)
* step (slice object attribute):         标准类型层级结构.   (line  624)
* step (slice object attribute) <1>:     切片.               (line   22)
* step() (tkinter.ttk.Progressbar 的方法): ttk Progressbar.  (line   14)
* stereocontrols() (ossaudiodev.oss_mixer_device 的方法): Mixer Device Objects.
                                                             (line   43)
* stls() (poplib.POP3 的方法):           POP3 对象.          (line  101)
* stop (range 的屬性):                   range 对象.         (line   58)
* stop (slice object attribute):         标准类型层级结构.   (line  624)
* stop (slice object attribute) <1>:     切片.               (line   22)
* stop() (asyncio.loop 的方法):          运行和停止循环.     (line   28)
* stop() (logging.handlers.QueueListener 的方法): QueueListener.
                                                             (line   66)
* stop() (tkinter.ttk.Progressbar 的方法): ttk Progressbar.  (line   20)
* stop() (unittest.TestResult 的方法):   Loading and running tests.
                                                             (line  310)
* stop() (於 tracemalloc 模組中):        函数<10>.           (line   98)
* StopAsyncIteration:                    具体异常.           (line  200)
* StopIteration:                         具体异常.           (line  176)
* stopListening() (於 logging.config 模組中): 配置函数.      (line  137)
* stopTest() (unittest.TestResult 的方法): Loading and running tests.
                                                             (line  333)
* stopTestRun() (unittest.TestResult 的方法): Loading and running tests.
                                                             (line  344)
* stop_here() (bdb.Bdb 的方法):          bdb --- Debugger framework.
                                                             (line  190)
* storbinary() (ftplib.FTP 的方法):      FTP 对象.           (line   92)
* Store (ast 中的類別):                  Variables.          (line   11)
* store() (imaplib.IMAP4 的方法):        IMAP4 对象.         (line  283)
* STORE_ACTIONS (optparse.Option 的屬性): Adding new actions.
                                                             (line   35)
* STORE_ATTR (opcode):                   Python字节码说明.   (line  425)
* STORE_DEREF (opcode):                  Python字节码说明.   (line  632)
* STORE_FAST (opcode):                   Python字节码说明.   (line  606)
* STORE_GLOBAL (opcode):                 Python字节码说明.   (line  434)
* STORE_NAME (opcode):                   Python字节码说明.   (line  401)
* STORE_SUBSCR (opcode):                 Python字节码说明.   (line  241)
* storlines() (ftplib.FTP 的方法):       FTP 对象.           (line  105)
* str (built-in class); (see also string): range 对象.       (line  112)
* str (內建類別):                        文本序列类型 --- str.
                                                             (line   37)
* str() (於 locale 模組中):              locale --- 国际化服务.
                                                             (line  357)
* strcoll() (於 locale 模組中):          locale --- 国际化服务.
                                                             (line  310)
* StreamError:                           tarfile --- 读写tar归档文件.
                                                             (line  180)
* StreamHandler (logging 中的類別):      StreamHandler.      (line   10)
* StreamReader (asyncio 中的類別):       StreamReader.       (line    6)
* StreamReader (codecs 中的類別):        StreamReader 对象.  (line    9)
* streamreader (codecs.CodecInfo 的屬性): codecs --- 编解码器注册和相关基类.
                                                             (line   76)
* StreamReaderWriter (codecs 中的類別):  StreamReaderWriter 对象.
                                                             (line   12)
* StreamRecoder (codecs 中的類別):       StreamRecoder 对象. (line   12)
* StreamRequestHandler (socketserver 中的類別): 请求处理句柄对象.
                                                             (line   34)
* streams:                               codecs --- 编解码器注册和相关基类.
                                                             (line    8)
* StreamWriter (asyncio 中的類別):       StreamWriter.       (line    6)
* StreamWriter (codecs 中的類別):        StreamWriter 对象.  (line    9)
* streamwriter (codecs.CodecInfo 的屬性): codecs --- 编解码器注册和相关基类.
                                                             (line   76)
* strerror (OSError 的屬性):             具体异常.           (line  128)
* strerror():                            抛出异常.           (line   52)
* strerror() (於 os 模組中):             进程参数.           (line  410)
* strftime() (datetime.date 的方法):     date 对象.          (line  250)
* strftime() (datetime.datetime 的方法): datetime 对象.      (line  632)
* strftime() (datetime.time 的方法):     time 对象.          (line  189)
* strftime() (於 time 模組中):           函数<3>.            (line  198)
* strict (csv.Dialect 的屬性):           变种与格式参数.     (line   59)
* strict (於 email.policy 模組中):       email policy Policy 对象.
                                                             (line  414)
* strict_domain (http.cookiejar.DefaultCookiePolicy 的屬性): DefaultCookiePolicy 对象.
                                                             (line   86)
* strict_errors() (於 codecs 模組中):    错误处理方案.       (line  105)
* strict_ns_domain (http.cookiejar.DefaultCookiePolicy 的屬性): DefaultCookiePolicy 对象.
                                                             (line  105)
* strict_ns_set_initial_dollar (http.cookiejar.DefaultCookiePolicy 的屬性): DefaultCookiePolicy 对象.
                                                             (line  110)
* strict_ns_set_path (http.cookiejar.DefaultCookiePolicy 的屬性): DefaultCookiePolicy 对象.
                                                             (line  115)
* strict_ns_unverifiable (http.cookiejar.DefaultCookiePolicy 的屬性): DefaultCookiePolicy 对象.
                                                             (line  101)
* strict_rfc2965_unverifiable (http.cookiejar.DefaultCookiePolicy 的屬性): DefaultCookiePolicy 对象.
                                                             (line   93)
* strides (memoryview 的屬性):           内存视图.           (line  421)
* string (re.Match 的屬性):              匹配对象.           (line  167)
* STRING (於 token 模組中):              token --- 与Python解析树一起使用的常量.
                                                             (line   42)
* string (模組):                         string --- 常见的字符串操作.
                                                             (line    6)
* string literal:                        字面值.             (line    8)
* string; conversion:                    基本定制.           (line  123)
* string; conversion <1>:                表达式语句.         (line   15)
* string; format() (built-in function):  內建函式.           (line  540)
* string; formatted literal:             字符串字面值合并.   (line   19)
* string; formatting, printf:            printf 风格的字符串格式化.
                                                             (line    6)
* string; immutable sequences:           标准类型层级结构.   (line  120)
* string; interpolated literal:          字符串字面值合并.   (line   19)
* string; interpolation, printf:         printf 风格的字符串格式化.
                                                             (line    6)
* string; item:                          抽取.               (line   29)
* string; methods:                       文本序列类型 --- str.
                                                             (line   74)
* string; object representation:         终结和内存释放.     (line   82)
* string; PyObject_Str (C function):     对象协议.           (line  157)
* string; str (built-in class):          文本序列类型 --- str.
                                                             (line   37)
* string; str() (built-in function):     內建函式.           (line 1351)
* string; text sequence type:            range 对象.         (line  112)
* string; __format__() (object method):  基本定制.           (line  123)
* string; __str__() (object method):     基本定制.           (line  105)
* StringIO (io 中的類別):                文本 I/O<2>.        (line  166)
* stringprep (模組):                     stringprep --- 因特网字符串预备.
                                                             (line    6)
* strings, documentation:                定義函式 function.  (line   20)
* strings, documentation <1>:            說明文件字串 Documentation Strings.
                                                             (line    6)
* string_at() (於 ctypes 模組中):        工具函数.           (line  168)
* strip() (bytearray 的方法):            bytes 和 bytearray 操作.
                                                             (line  369)
* strip() (bytes 的方法):                bytes 和 bytearray 操作.
                                                             (line  369)
* strip() (str 的方法):                  字符串的方法<2>.    (line  501)
* stripspaces (curses.textpad.Textbox 的屬性): 文本框对象.   (line  102)
* strip_dirs() (pstats.Stats 的方法):    Stats 类.           (line   34)
* strptime() (datetime.datetime 的類別成員): datetime 对象.  (line  210)
* strptime() (於 time 模組中):           函数<3>.            (line  315)
* strsignal() (於 signal 模組中):        模块内容<5>.        (line  231)
* strtobool() (於 distutils.util 模組中): distutils util --- Miscellaneous other utility functions.
                                                             (line  139)
* Struct (struct 中的類別):              类.                 (line    8)
* struct (模組):                         struct --- 将字节串解读为打包的二进制数据.
                                                             (line    6)
* Structure (ctypes 中的類別):           结构化数据类型.     (line   21)
* struct_time (time 中的類別):           函数<3>.            (line  342)
* strxfrm() (於 locale 模組中):          locale --- 国际化服务.
                                                             (line  316)
* STType (於 parser 模組中):             ST 对象.            (line   10)
* Style (tkinter.ttk 中的類別):          Ttk 风格.           (line   18)
* st_atime (os.stat_result 的屬性):      文件和目录.         (line  943)
* ST_ATIME (於 stat 模組中):             stat --- 解析 stat 结果.
                                                             (line  152)
* st_atime_ns (os.stat_result 的屬性):   文件和目录.         (line  959)
* st_birthtime (os.stat_result 的屬性):  文件和目录.         (line 1016)
* st_blksize (os.stat_result 的屬性):    文件和目录.         (line  996)
* st_blocks (os.stat_result 的屬性):     文件和目录.         (line  991)
* st_creator (os.stat_result 的屬性):    文件和目录.         (line 1032)
* st_ctime (os.stat_result 的屬性):      文件和目录.         (line  951)
* ST_CTIME (於 stat 模組中):             stat --- 解析 stat 结果.
                                                             (line  160)
* st_ctime_ns (os.stat_result 的屬性):   文件和目录.         (line  967)
* st_dev (os.stat_result 的屬性):        文件和目录.         (line  920)
* ST_DEV (於 stat 模組中):               stat --- 解析 stat 结果.
                                                             (line  132)
* st_file_attributes (os.stat_result 的屬性): 文件和目录.    (line 1042)
* st_flags (os.stat_result 的屬性):      文件和目录.         (line 1005)
* st_fstype (os.stat_result 的屬性):     文件和目录.         (line 1022)
* st_gen (os.stat_result 的屬性):        文件和目录.         (line 1012)
* st_gid (os.stat_result 的屬性):        文件和目录.         (line  932)
* ST_GID (於 stat 模組中):               stat --- 解析 stat 结果.
                                                             (line  144)
* st_ino (os.stat_result 的屬性):        文件和目录.         (line  911)
* ST_INO (於 stat 模組中):               stat --- 解析 stat 结果.
                                                             (line  128)
* st_mode (os.stat_result 的屬性):       文件和目录.         (line  907)
* ST_MODE (於 stat 模組中):              stat --- 解析 stat 结果.
                                                             (line  124)
* st_mtime (os.stat_result 的屬性):      文件和目录.         (line  947)
* ST_MTIME (於 stat 模組中):             stat --- 解析 stat 结果.
                                                             (line  156)
* st_mtime_ns (os.stat_result 的屬性):   文件和目录.         (line  963)
* st_nlink (os.stat_result 的屬性):      文件和目录.         (line  924)
* ST_NLINK (於 stat 模組中):             stat --- 解析 stat 结果.
                                                             (line  136)
* st_rdev (os.stat_result 的屬性):       文件和目录.         (line 1001)
* st_reparse_tag (os.stat_result 的屬性): 文件和目录.        (line 1049)
* st_rsize (os.stat_result 的屬性):      文件和目录.         (line 1028)
* st_size (os.stat_result 的屬性):       文件和目录.         (line  936)
* ST_SIZE (於 stat 模組中):              stat --- 解析 stat 结果.
                                                             (line  148)
* st_type (os.stat_result 的屬性):       文件和目录.         (line 1036)
* st_uid (os.stat_result 的屬性):        文件和目录.         (line  928)
* ST_UID (於 stat 模組中):               stat --- 解析 stat 结果.
                                                             (line  140)
* Sub (ast 中的類別):                    表达式<2>.          (line   54)
* sub() (re.Pattern 的方法):             正则表达式对象 （正则对象）.
                                                             (line   75)
* sub() (於 operator 模組中):            operator --- 标准运算符替代函数.
                                                             (line  141)
* sub() (於 re 模組中):                  模块内容.           (line  202)
* subclassing; immutable types:          基本定制.           (line    8)
* subdirs (filecmp.dircmp 的屬性):       dircmp 类.          (line   89)
* SubElement() (於 xml.etree.ElementTree 模組中): 函数<7>.   (line  173)
* submit() (concurrent.futures.Executor 的方法): Executor 对象.
                                                             (line   10)
* submodule_search_locations (importlib.machinery.ModuleSpec 的屬性): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line  341)
* subn() (re.Pattern 的方法):            正则表达式对象 （正则对象）.
                                                             (line   79)
* subn() (於 re 模組中):                 模块内容.           (line  254)
* subnets() (ipaddress.IPv4Network 的方法): 网络对象.        (line  150)
* subnets() (ipaddress.IPv6Network 的方法): 网络对象.        (line  308)
* subnet_of() (ipaddress.IPv4Network 的方法): 网络对象.      (line  187)
* subnet_of() (ipaddress.IPv6Network 的方法): 网络对象.      (line  312)
* Subnormal (decimal 中的類別):          信号.               (line   77)
* suboffsets (memoryview 的屬性):        内存视图.           (line  428)
* subpad() (curses.window 的方法):       Window 对象.        (line  449)
* subprocess (模組):                     subprocess --- 子进程管理.
                                                             (line    6)
* SubprocessError:                       使用 subprocess 模块.
                                                             (line  133)
* SubprocessProtocol (asyncio 中的類別): 基础协议.           (line   22)
* SubprocessTransport (asyncio 中的類別): 传输层级.          (line   44)
* subprocess_exec() (asyncio.loop 的方法): 运行子进程.       (line   15)
* subprocess_shell() (asyncio.loop 的方法): 运行子进程.      (line   95)
* subscribe() (imaplib.IMAP4 的方法):    IMAP4 对象.         (line  304)
* Subscript (ast 中的類別):              Subscripting.       (line    6)
* subscript; assignment:                 可变序列类型.       (line   14)
* subscript; operation:                  通用序列操作.       (line   17)
* subscription:                          标准类型层级结构.   (line   98)
* subscription <1>:                      标准类型层级结构.   (line  151)
* subscription <2>:                      标准类型层级结构.   (line  198)
* subscription <3>:                      抽取.               (line    6)
* subscription; assignment:              赋值语句.           (line   81)
* subsequent_indent (textwrap.TextWrapper 的屬性): textwrap --- 文本自动换行与填充.
                                                             (line  193)
* substitute() (string.Template 的方法): 模板字符串.         (line   32)
* subst_vars() (於 distutils.util 模組中): distutils util --- Miscellaneous other utility functions.
                                                             (line  102)
* subTest() (unittest.TestCase 的方法):  测试用例.           (line  105)
* subtract() (collections.Counter 的方法): Counter 物件.     (line   79)
* subtract() (decimal.Context 的方法):   上下文对象.         (line  444)
* subtraction:                           二元算术运算符.     (line   62)
* subtype (email.headerregistry.ContentTypeHeader 的屬性): email headerregistry 自定义标头对象.
                                                             (line  228)
* subwin() (curses.window 的方法):       Window 对象.        (line  456)
* sub_commands (distutils.cmd.Command 的屬性): Creating a new Distutils command.
                                                             (line   49)
* successful() (multiprocessing.pool.AsyncResult 的方法): 进程池.
                                                             (line  178)
* suffix_map (mimetypes.MimeTypes 的屬性): MimeTypes 对象.   (line   19)
* suffix_map (於 mimetypes 模組中):      mimetypes --- 映射文件名到 MIME 类型.
                                                             (line  107)
* suite:                                 复合语句.           (line   15)
* suite() (於 parser 模組中):            创建 ST 对象.       (line   18)
* suiteClass (unittest.TestLoader 的屬性): Loading and running tests.
                                                             (line  191)
* sum() (內建函式):                      內建函式.           (line 1361)
* summarize() (doctest.DocTestRunner 的方法): DocTestRunner 对象.
                                                             (line  101)
* summarize_address_range() (於 ipaddress 模組中): 其他模块级别函数.
                                                             (line   25)
* sum_list():                            引用计数细节.       (line  143)
* sum_sequence():                        引用计数细节.       (line  170)
* sum_sequence() <1>:                    异常<17>.           (line   63)
* sunau (模組):                          sunau --- 读写 Sun AU 文件.
                                                             (line    6)
* super (pyclbr.Class 的屬性):           Class 对象.         (line   37)
* super() (內建函式):                    內建函式.           (line 1373)
* supernet() (ipaddress.IPv4Network 的方法): 网络对象.       (line  173)
* supernet() (ipaddress.IPv6Network 的方法): 网络对象.       (line  310)
* supernet_of() (ipaddress.IPv4Network 的方法): 网络对象.    (line  198)
* supernet_of() (ipaddress.IPv6Network 的方法): 网络对象.    (line  314)
* SupportsAbs (typing 中的類別):         协议<3>.            (line    8)
* SupportsBytes (typing 中的類別):       协议<3>.            (line   12)
* SupportsComplex (typing 中的類別):     协议<3>.            (line   16)
* SupportsFloat (typing 中的類別):       协议<3>.            (line   20)
* SupportsIndex (typing 中的類別):       协议<3>.            (line   24)
* SupportsInt (typing 中的類別):         协议<3>.            (line   30)
* SupportsRound (typing 中的類別):       协议<3>.            (line   34)
* supports_bytes_environ (於 os 模組中): 进程参数.           (line  415)
* supports_dir_fd (於 os 模組中):        文件和目录.         (line 1120)
* supports_effective_ids (於 os 模組中): 文件和目录.         (line 1140)
* supports_fd (於 os 模組中):            文件和目录.         (line 1156)
* supports_follow_symlinks (於 os 模組中): 文件和目录.       (line 1172)
* supports_unicode_filenames (於 os.path 模組中): os path --- 常用路径操作.
                                                             (line  389)
* suppress() (於 contextlib 模組中):     工具.               (line  161)
* SuppressCrashReport (test.support 中的類別): test support --- Utilities for the Python test suite.
                                                             (line 1065)
* swapcase() (bytearray 的方法):         bytes 和 bytearray 操作.
                                                             (line  568)
* swapcase() (bytes 的方法):             bytes 和 bytearray 操作.
                                                             (line  568)
* swapcase() (str 的方法):               字符串的方法<2>.    (line  521)
* swap_attr() (於 test.support 模組中):  test support --- Utilities for the Python test suite.
                                                             (line  533)
* swap_item() (於 test.support 模組中):  test support --- Utilities for the Python test suite.
                                                             (line  550)
* SW_HIDE (於 subprocess 模組中):        Windows 常数.       (line   20)
* Symbol (symtable 中的類別):            符号表的查看.       (line   90)
* symbol (模組):                         symbol --- 与 Python 解析树一起使用的常量.
                                                             (line    6)
* SymbolTable (symtable 中的類別):       符号表的查看.       (line    6)
* symlink() (於 os 模組中):              文件和目录.         (line 1191)
* symlink_to() (pathlib.Path 的方法):    方法<2>.            (line  382)
* symmetric_difference() (frozenset 的方法): 集合类型 --- set frozenset.
                                                             (line  107)
* symmetric_difference_update() (frozenset 的方法): 集合类型 --- set frozenset.
                                                             (line  169)
* symtable (模組):                       symtable ——访问编译器的符号表.
                                                             (line    6)
* symtable() (於 symtable 模組中):       符号表的生成.       (line    6)
* sym_name (於 symbol 模組中):           symbol --- 与 Python 解析树一起使用的常量.
                                                             (line   19)
* sync() (dbm.dumb.dumbdbm 的方法):      dbm dumb --- 便携式 DBM 实现.
                                                             (line   64)
* sync() (dbm.gnu.gdbm 的方法):          dbm gnu --- GNU 对 dbm 的重解析.
                                                             (line   94)
* sync() (ossaudiodev.oss_audio_device 的方法): 音频设备对象.
                                                             (line  148)
* sync() (shelve.Shelf 的方法):          shelve --- Python 对象持久化.
                                                             (line   52)
* sync() (於 os 模組中):                 文件和目录.         (line 1226)
* syncdown() (curses.window 的方法):     Window 对象.        (line  465)
* synchronized() (於 multiprocessing.sharedctypes 模組中): multiprocessing sharedctypes 模块.
                                                             (line   75)
* SyncManager (multiprocessing.managers 中的類別): 管理器.   (line  113)
* syncok() (curses.window 的方法):       Window 对象.        (line  470)
* syncup() (curses.window 的方法):       Window 对象.        (line  475)
* syntax:                                标注.               (line    6)
* SyntaxErr:                             异常<15>.           (line   76)
* SyntaxError:                           具体异常.           (line  207)
* SyntaxWarning:                         警告.               (line   38)
* sys (模組):                            sys --- 系统相关的参数和函数.
                                                             (line    6)
* sys.exc_info:                          标准类型层级结构.   (line  587)
* sys.last_traceback:                    标准类型层级结构.   (line  587)
* sys.meta_path:                         元路径.             (line    6)
* sys.modules:                           模块缓存.           (line    6)
* sys.path:                              路径条目查找器.     (line    6)
* sys.path_hooks:                        路径条目查找器.     (line    6)
* sys.path_importer_cache:               路径条目查找器.     (line    6)
* sys.stderr:                            标准类型层级结构.   (line  492)
* sys.stdin:                             标准类型层级结构.   (line  492)
* sys.stdout:                            标准类型层级结构.   (line  492)
* sysconf() (於 os 模組中):              其他系统信息.       (line   47)
* sysconfig (模組):                      sysconfig --- Provide access to Python's configuration information.
                                                             (line    6)
* sysconf_names (於 os 模組中):          其他系统信息.       (line   55)
* syslog (模組):                         Unix syslog 库例程. (line    6)
* syslog() (於 syslog 模組中):           Unix syslog 库例程. (line   17)
* SysLogHandler (logging.handlers 中的類別): SysLogHandler.  (line    9)
* system() (於 os 模組中):               进程管理.           (line  564)
* system() (於 platform 模組中):         跨平台.             (line  107)
* SystemError:                           具体异常.           (line  250)
* SystemError (built-in exception):      模組物件模組.       (line   55)
* SystemError (built-in exception) <1>:  模組物件模組.       (line   81)
* SystemExit:                            具体异常.           (line  261)
* SystemExit (built-in exception):       异常.               (line   20)
* systemId (xml.dom.DocumentType 的屬性): 文档类型对象.      (line   17)
* SystemRandom (random 中的類別):        替代生成器.         (line   14)
* SystemRandom (secrets 中的類別):       亂數.               (line    9)
* SystemRoot:                            Popen 构造函数.     (line  223)
* system_alias() (於 platform 模組中):   跨平台.             (line  112)
* system_must_validate_cert() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  279)
* sys_exc (2to3 fixer):                  修复器.             (line  285)
* sys_version (http.server.BaseHTTPRequestHandler 的屬性): http server --- HTTP 服务器.
                                                             (line  117)
* S_ENFMT (於 stat 模組中):              stat --- 解析 stat 结果.
                                                             (line  293)
* S_IEXEC (於 stat 模組中):              stat --- 解析 stat 结果.
                                                             (line  307)
* S_IFBLK (於 stat 模組中):              stat --- 解析 stat 结果.
                                                             (line  189)
* S_IFCHR (於 stat 模組中):              stat --- 解析 stat 结果.
                                                             (line  197)
* S_IFDIR (於 stat 模組中):              stat --- 解析 stat 结果.
                                                             (line  193)
* S_IFDOOR (於 stat 模組中):             stat --- 解析 stat 结果.
                                                             (line  205)
* S_IFIFO (於 stat 模組中):              stat --- 解析 stat 结果.
                                                             (line  201)
* S_IFLNK (於 stat 模組中):              stat --- 解析 stat 结果.
                                                             (line  181)
* S_IFMT() (於 stat 模組中):             stat --- 解析 stat 结果.
                                                             (line   73)
* S_IFPORT (於 stat 模組中):             stat --- 解析 stat 结果.
                                                             (line  211)
* S_IFREG (於 stat 模組中):              stat --- 解析 stat 结果.
                                                             (line  185)
* S_IFSOCK (於 stat 模組中):             stat --- 解析 stat 结果.
                                                             (line  177)
* S_IFWHT (於 stat 模組中):              stat --- 解析 stat 结果.
                                                             (line  217)
* S_IMODE() (於 stat 模組中):            stat --- 解析 stat 结果.
                                                             (line   67)
* S_IREAD (於 stat 模組中):              stat --- 解析 stat 结果.
                                                             (line  299)
* S_IRGRP (於 stat 模組中):              stat --- 解析 stat 结果.
                                                             (line  265)
* S_IROTH (於 stat 模組中):              stat --- 解析 stat 结果.
                                                             (line  281)
* S_IRUSR (於 stat 模組中):              stat --- 解析 stat 结果.
                                                             (line  249)
* S_IRWXG (於 stat 模組中):              stat --- 解析 stat 结果.
                                                             (line  261)
* S_IRWXO (於 stat 模組中):              stat --- 解析 stat 结果.
                                                             (line  277)
* S_IRWXU (於 stat 模組中):              stat --- 解析 stat 结果.
                                                             (line  245)
* S_ISBLK() (於 stat 模組中):            stat --- 解析 stat 结果.
                                                             (line   27)
* S_ISCHR() (於 stat 模組中):            stat --- 解析 stat 结果.
                                                             (line   23)
* S_ISDIR() (於 stat 模組中):            stat --- 解析 stat 结果.
                                                             (line   19)
* S_ISDOOR() (於 stat 模組中):           stat --- 解析 stat 结果.
                                                             (line   47)
* S_ISFIFO() (於 stat 模組中):           stat --- 解析 stat 结果.
                                                             (line   35)
* S_ISGID (於 stat 模組中):              stat --- 解析 stat 结果.
                                                             (line  232)
* S_ISLNK() (於 stat 模組中):            stat --- 解析 stat 结果.
                                                             (line   39)
* S_ISPORT() (於 stat 模組中):           stat --- 解析 stat 结果.
                                                             (line   53)
* S_ISREG() (於 stat 模組中):            stat --- 解析 stat 结果.
                                                             (line   31)
* S_ISSOCK() (於 stat 模組中):           stat --- 解析 stat 结果.
                                                             (line   43)
* S_ISUID (於 stat 模組中):              stat --- 解析 stat 结果.
                                                             (line  228)
* S_ISVTX (於 stat 模組中):              stat --- 解析 stat 结果.
                                                             (line  240)
* S_ISWHT() (於 stat 模組中):            stat --- 解析 stat 结果.
                                                             (line   59)
* S_IWGRP (於 stat 模組中):              stat --- 解析 stat 结果.
                                                             (line  269)
* S_IWOTH (於 stat 模組中):              stat --- 解析 stat 结果.
                                                             (line  285)
* S_IWRITE (於 stat 模組中):             stat --- 解析 stat 结果.
                                                             (line  303)
* S_IWUSR (於 stat 模組中):              stat --- 解析 stat 结果.
                                                             (line  253)
* S_IXGRP (於 stat 模組中):              stat --- 解析 stat 结果.
                                                             (line  273)
* S_IXOTH (於 stat 模組中):              stat --- 解析 stat 结果.
                                                             (line  289)
* S_IXUSR (於 stat 模組中):              stat --- 解析 stat 结果.
                                                             (line  257)
* tab:                                   缩进.               (line    6)
* tab() (tkinter.ttk.Notebook 的方法):   ttk Notebook.       (line   54)
* TabError:                              具体异常.           (line  245)
* tabnanny (模組):                       tabnanny --- 模糊缩进检测.
                                                             (line    6)
* tabs() (tkinter.ttk.Notebook 的方法):  ttk Notebook.       (line   61)
* tabsize (textwrap.TextWrapper 的屬性): textwrap --- 文本自动换行与填充.
                                                             (line  157)
* tag (xml.etree.ElementTree.Element 的屬性): 元素对象.      (line   14)
* tagName (xml.dom.Element 的屬性):      元素对象<2>.        (line    8)
* tag_bind() (tkinter.ttk.Treeview 的方法): ttk Treeview.    (line  265)
* tag_configure() (tkinter.ttk.Treeview 的方法): ttk Treeview.
                                                             (line  271)
* tag_has() (tkinter.ttk.Treeview 的方法): ttk Treeview.     (line  279)
* tail (xml.etree.ElementTree.Element 的屬性): 元素对象.     (line   18)
* takewhile() (於 itertools 模組中):     Itertool函数.       (line  482)
* take_snapshot() (於 tracemalloc 模組中): 函数<10>.         (line  110)
* tan() (於 cmath 模組中):               三角函数<2>.        (line   30)
* tan() (於 math 模組中):                三角函数.           (line   57)
* tanh() (於 cmath 模組中):              双曲函数<2>.        (line   30)
* tanh() (於 math 模組中):               双曲函数.           (line   28)
* TarError:                              tarfile --- 读写tar归档文件.
                                                             (line  167)
* TarFile (tarfile 中的類別):            TarFile 对象.       (line   18)
* tarfile (模組):                        tarfile --- 读写tar归档文件.
                                                             (line    6)
* tarfile command line option; -c <tarfile> <source1> ... <sourceN>: 命令行选项<3>.
                                                             (line   11)
* tarfile command line option; –create <tarfile> <source1> ... <sourceN>: 命令行选项<3>.
                                                             (line   11)
* tarfile command line option; -e <tarfile> [<output_dir>]: 命令行选项<3>.
                                                             (line   16)
* tarfile command line option; –extract <tarfile> [<output_dir>]: 命令行选项<3>.
                                                             (line   16)
* tarfile command line option; -l <tarfile>: 命令行选项<3>.  (line    6)
* tarfile command line option; –list <tarfile>: 命令行选项<3>.
                                                             (line    6)
* tarfile command line option; -t <tarfile>: 命令行选项<3>.  (line   21)
* tarfile command line option; –test <tarfile>: 命令行选项<3>.
                                                             (line   21)
* tarfile command line option; -v:       命令行选项<3>.      (line   26)
* tarfile command line option; –verbose: 命令行选项<3>.      (line   26)
* target:                                赋值语句.           (line   25)
* target (xml.dom.ProcessingInstruction 的屬性): ProcessingInstruction 对象.
                                                             (line    8)
* target; list:                          赋值语句.           (line   25)
* target; list <1>:                      for 语句.           (line    6)
* target; list; assignment:              赋值语句.           (line   30)
* TarInfo (tarfile 中的類別):            TarInfo 对象.       (line   13)
* Task (asyncio 中的類別):               Task 对象.          (line    6)
* task_done() (asyncio.Queue 的方法):    队列.               (line   71)
* task_done() (multiprocessing.JoinableQueue 的方法): 管道和队列.
                                                             (line  203)
* task_done() (queue.Queue 的方法):      Queue对象.          (line   60)
* tau (於 cmath 模組中):                 常数<2>.            (line   14)
* tau (於 math 模組中):                  常数.               (line   14)
* tbreak (pdb command):                  调试器命令.         (line   70)
* tb_frame (traceback attribute):        标准类型层级结构.   (line  604)
* tb_lasti (traceback attribute):        标准类型层级结构.   (line  604)
* tb_lineno (traceback attribute):       标准类型层级结构.   (line  604)
* tb_locals (unittest.TestResult 的屬性): Loading and running tests.
                                                             (line  294)
* tb_next (traceback attribute):         标准类型层级结构.   (line  612)
* tcdrain() (於 termios 模組中):         termios --- POSIX 风格的 tty 控制.
                                                             (line   44)
* tcflow() (於 termios 模組中):          termios --- POSIX 风格的 tty 控制.
                                                             (line   54)
* tcflush() (於 termios 模組中):         termios --- POSIX 风格的 tty 控制.
                                                             (line   48)
* tcgetattr() (於 termios 模組中):       termios --- POSIX 风格的 tty 控制.
                                                             (line   22)
* tcgetpgrp() (於 os 模組中):            文件描述符操作.     (line  588)
* Tcl() (於 tkinter 模組中):             Tkinter 模块.       (line   20)
* TCL_LIBRARY:                           我怎样“冻结”Tkinter程序？.
                                                             (line    9)
* TCPServer (socketserver 中的類別):     socketserver --- 用于网络服务器的框架.
                                                             (line   14)
* tcsendbreak() (於 termios 模組中):     termios --- POSIX 风格的 tty 控制.
                                                             (line   39)
* tcsetattr() (於 termios 模組中):       termios --- POSIX 风格的 tty 控制.
                                                             (line   31)
* tcsetpgrp() (於 os 模組中):            文件描述符操作.     (line  595)
* tearDown() (unittest.TestCase 的方法): 测试用例.           (line   41)
* tearDownClass() (unittest.TestCase 的方法): 测试用例.      (line   69)
* tee() (於 itertools 模組中):           Itertool函数.       (line  495)
* tell() (aifc.aifc 的方法):             aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line   97)
* tell() (chunk.Chunk 的方法):           chunk --- 读取 IFF 分块数据.
                                                             (line   87)
* tell() (io.IOBase 的方法):             I/O 基类.           (line  116)
* tell() (io.TextIOBase 的方法):         文本 I/O<2>.        (line   78)
* tell() (mmap.mmap 的方法):             mmap --- 内存映射文件支持.
                                                             (line  237)
* tell() (sunau.AU_read 的方法):         AU_read 对象.       (line   60)
* tell() (sunau.AU_write 的方法):        AU_write 对象.      (line   35)
* tell() (wave.Wave_read 的方法):        Wave_read对象.      (line   68)
* tell() (wave.Wave_write 的方法):       Wave_write 对象.    (line   53)
* Telnet (telnetlib 中的類別):           telnetlib -- Telnet 客户端.
                                                             (line   21)
* telnetlib (模組):                      telnetlib -- Telnet 客户端.
                                                             (line    6)
* TEMP:                                  tempfile --- 生成临时文件和目录.
                                                             (line  200)
* tempdir (於 tempfile 模組中):          tempfile --- 生成临时文件和目录.
                                                             (line  237)
* tempfile (模組):                       tempfile --- 生成临时文件和目录.
                                                             (line    6)
* Template (pipes 中的類別):             pipes --- 终端管道接口.
                                                             (line   18)
* Template (string 中的類別):            模板字符串.         (line   28)
* template (string.Template 的屬性):     模板字符串.         (line   55)
* temporary; file:                       tempfile --- 生成临时文件和目录.
                                                             (line    8)
* temporary; file name:                  tempfile --- 生成临时文件和目录.
                                                             (line    8)
* TemporaryDirectory() (於 tempfile 模組中): tempfile --- 生成临时文件和目录.
                                                             (line  100)
* TemporaryFile() (於 tempfile 模組中):  tempfile --- 生成临时文件和目录.
                                                             (line   23)
* temp_cwd() (於 test.support 模組中):   test support --- Utilities for the Python test suite.
                                                             (line  498)
* temp_dir() (於 test.support 模組中):   test support --- Utilities for the Python test suite.
                                                             (line  479)
* temp_umask() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  512)
* teredo (ipaddress.IPv6Address 的屬性): 地址对象.           (line  241)
* TERM:                                  函数<4>.            (line  392)
* TERM <1>:                              函数<4>.            (line  413)
* termattrs() (於 curses 模組中):        函数<4>.            (line  406)
* terminal_size (os 中的類別):           查询终端的尺寸.     (line   23)
* terminate() (asyncio.asyncio.subprocess.Process 的方法): 与子进程交互.
                                                             (line   81)
* terminate() (asyncio.SubprocessTransport 的方法): 子进程传输.
                                                             (line   44)
* terminate() (multiprocessing.pool.Pool 的方法): 进程池.    (line  144)
* terminate() (multiprocessing.Process 的方法): Process 和异常.
                                                             (line  127)
* terminate() (subprocess.Popen 的方法): Popen 对象.         (line   73)
* termination model:                     异常.               (line   16)
* terminator (logging.StreamHandler 的屬性): StreamHandler.  (line   41)
* termios (模組):                        termios --- POSIX 风格的 tty 控制.
                                                             (line    6)
* termname() (於 curses 模組中):         函数<4>.            (line  411)
* ternary; operator:                     条件表达式.         (line    6)
* ternaryfunc (C 型態):                  Slot Type typedefs. (line  102)
* test (doctest.DocTestFailure 的屬性):  调试.               (line  169)
* test (doctest.UnexpectedException 的屬性): 调试.           (line  188)
* test (模組):                           test --- Python回归测试包.
                                                             (line    6)
* test() (於 cgi 模組中):                函数<9>.            (line   40)
* test.support (模組):                   test support --- Utilities for the Python test suite.
                                                             (line    6)
* test.support.bytecode_helper (模組):   test support bytecode_helper --- Support tools for testing correct bytecode generation.
                                                             (line    6)
* test.support.script_helper (模組):     test support script_helper --- Utilities for the Python execution tests.
                                                             (line    6)
* test.support.socket_helper (模組):     test support socket_helper --- Utilities for socket tests.
                                                             (line    6)
* TestCase (unittest 中的類別):          测试用例.           (line    6)
* TestFailed:                            test support --- Utilities for the Python test suite.
                                                             (line   16)
* testfile() (於 doctest 模組中):        基本API.            (line   11)
* TESTFN (於 test.support 模組中):       test support --- Utilities for the Python test suite.
                                                             (line   52)
* TESTFN_ENCODING (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line   62)
* TESTFN_NONASCII (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line   78)
* TESTFN_UNDECODABLE (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line   72)
* TESTFN_UNENCODABLE (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line   66)
* TESTFN_UNICODE (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line   58)
* TestLoader (unittest 中的類別):        Loading and running tests.
                                                             (line    6)
* testMethodPrefix (unittest.TestLoader 的屬性): Loading and running tests.
                                                             (line  177)
* testmod() (於 doctest 模組中):         基本API.            (line   81)
* testNamePatterns (unittest.TestLoader 的屬性): Loading and running tests.
                                                             (line  199)
* TestResult (unittest 中的類別):        Loading and running tests.
                                                             (line  216)
* tests (於 imghdr 模組中):              imghdr --- 推测图像类型.
                                                             (line   72)
* testsource() (於 doctest 模組中):      调试.               (line   98)
* testsRun (unittest.TestResult 的屬性): Loading and running tests.
                                                             (line  272)
* TestSuite (unittest 中的類別):         Grouping tests.     (line    6)
* testzip() (zipfile.ZipFile 的方法):    ZipFile 对象.       (line  204)
* TEST_DATA_DIR (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  169)
* TEST_HOME_DIR (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  165)
* TEST_HTTP_URL (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  196)
* TEST_SUPPORT_DIR (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  160)
* text (SyntaxError 的屬性):             具体异常.           (line  231)
* text (traceback.TracebackException 的屬性): TracebackException Objects.
                                                             (line   50)
* Text (typing 中的類別):                其他具象类型.       (line   33)
* text (xml.etree.ElementTree.Element 的屬性): 元素对象.     (line   18)
* text (於 msilib 模組中):               Precomputed tables. (line   23)
* text encoding（文字編碼）:             術語表.             (line 1073)
* text file（文字檔案）:                 術語表.             (line 1077)
* text mode:                             內建函式.           (line 1030)
* text() (msilib.Dialog 的方法):         GUI classes.        (line   56)
* text() (於 cgitb 模組中):              cgitb --- 用于 CGI 脚本的回溯管理器.
                                                             (line   38)
* Textbox (curses.textpad 中的類別):     文本框对象.         (line    8)
* TextCalendar (calendar 中的類別):      calendar --- 日历相关函数.
                                                             (line  106)
* textdomain() (於 gettext 模組中):      GNU gettext API.    (line   32)
* textdomain() (於 locale 模組中):       访问信息目录.       (line   12)
* TextFile (distutils.text_file 中的類別): distutils text_file --- The TextFile class.
                                                             (line   10)
* textinput() (於 turtle 模組中):        输入方法.           (line    6)
* TextIO (typing 中的類別):              其他具象类型.       (line    6)
* TextIOBase (io 中的類別):              文本 I/O<2>.        (line    6)
* TextIOWrapper (io 中的類別):           文本 I/O<2>.        (line   87)
* TextTestResult (unittest 中的類別):    Loading and running tests.
                                                             (line  420)
* TextTestRunner (unittest 中的類別):    Loading and running tests.
                                                             (line  434)
* textwrap (模組):                       textwrap --- 文本自动换行与填充.
                                                             (line    6)
* TextWrapper (textwrap 中的類別):       textwrap --- 文本自动换行与填充.
                                                             (line  128)
* text_factory (sqlite3.Connection 的屬性): 连接对象（Connection）.
                                                             (line  311)
* theme_create() (tkinter.ttk.Style 的方法): Ttk 风格.       (line  186)
* theme_names() (tkinter.ttk.Style 的方法): Ttk 风格.        (line  234)
* theme_settings() (tkinter.ttk.Style 的方法): Ttk 风格.     (line  196)
* theme_use() (tkinter.ttk.Style 的方法): Ttk 风格.          (line  238)
* THOUSEP (於 locale 模組中):            locale --- 国际化服务.
                                                             (line  196)
* Thread (threading 中的類別):           线程对象.           (line   48)
* thread() (imaplib.IMAP4 的方法):       IMAP4 对象.         (line  308)
* ThreadedChildWatcher (asyncio 中的類別): 进程监视器.       (line   74)
* threading (模組):                      threading --- 基于线程的并行.
                                                             (line    6)
* ThreadingHTTPServer (http.server 中的類別): http server --- HTTP 服务器.
                                                             (line   30)
* ThreadingMixIn (socketserver 中的類別): 服务器创建的说明.  (line   26)
* ThreadingTCPServer (socketserver 中的類別): 服务器创建的说明.
                                                             (line   55)
* ThreadingUDPServer (socketserver 中的類別): 服务器创建的说明.
                                                             (line   55)
* threading_cleanup() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  846)
* threading_setup() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  842)
* ThreadPool (multiprocessing.pool 中的類別): multiprocessing dummy 模块.
                                                             (line   13)
* ThreadPoolExecutor (concurrent.futures 中的類別): ThreadPoolExecutor.
                                                             (line   39)
* threads; POSIX:                        _thread --- 底层多线程 API.
                                                             (line   13)
* threadsafety (於 sqlite3 模組中):      模块函数和常量.     (line   38)
* thread_info (於 sys 模組中):           sys --- 系统相关的参数和函数.
                                                             (line 1310)
* thread_time() (於 time 模組中):        函数<3>.            (line  414)
* thread_time_ns() (於 time 模組中):     函数<3>.            (line  425)
* throw (2to3 fixer):                    修复器.             (line  290)
* throw() (coroutine 的方法):            协程对象.           (line   31)
* throw() (generator 的方法):            生成器-迭代器的方法.
                                                             (line   31)
* ticket_lifetime_hint (ssl.SSLSession 的屬性): SSL 会话.    (line   18)
* tigetflag() (於 curses 模組中):        函数<4>.            (line  415)
* tigetnum() (於 curses 模組中):         函数<4>.            (line  421)
* tigetstr() (於 curses 模組中):         函数<4>.            (line  427)
* TILDE (於 token 模組中):               token --- 与Python解析树一起使用的常量.
                                                             (line  146)
* tilt() (於 turtle 模組中):             外观.               (line   92)
* tiltangle() (於 turtle 模組中):        外观.               (line  126)
* time (datetime 中的類別):              time 对象.          (line    9)
* time (ssl.SSLSession 的屬性):          SSL 会话.           (line   14)
* time (模組):                           time --- 时间的访问和转换.
                                                             (line    6)
* time() (asyncio.loop 的方法):          调度延迟回调.       (line   50)
* time() (datetime.datetime 的方法):     datetime 对象.      (line  361)
* time() (於 time 模組中):               函数<3>.            (line  396)
* Time2Internaldate() (於 imaplib 模組中): imaplib --- IMAP4 协议客户端.
                                                             (line  115)
* timedelta (datetime 中的類別):         timedelta 类对象.   (line    8)
* TimedRotatingFileHandler (logging.handlers 中的類別): TimedRotatingFileHandler.
                                                             (line    9)
* timegm() (於 calendar 模組中):         calendar --- 日历相关函数.
                                                             (line  310)
* timeit (模組):                         timeit --- 测量小代码片段的执行时间.
                                                             (line    6)
* timeit command line option; -h:        命令執行列介面.     (line   42)
* timeit command line option; –help:     命令執行列介面.     (line   42)
* timeit command line option; -n N:      命令執行列介面.     (line   12)
* timeit command line option; –number=N: 命令執行列介面.     (line   12)
* timeit command line option; -p:        命令執行列介面.     (line   24)
* timeit command line option; –process:  命令執行列介面.     (line   24)
* timeit command line option; -r N:      命令執行列介面.     (line   16)
* timeit command line option; –repeat=N: 命令執行列介面.     (line   16)
* timeit command line option; -s S:      命令執行列介面.     (line   20)
* timeit command line option; –setup=S:  命令執行列介面.     (line   20)
* timeit command line option; -u:        命令執行列介面.     (line   32)
* timeit command line option; –unit=U:   命令執行列介面.     (line   32)
* timeit command line option; -v:        命令執行列介面.     (line   38)
* timeit command line option; –verbose:  命令執行列介面.     (line   38)
* timeit() (timeit.Timer 的方法):        Python 接口.        (line   58)
* timeit() (於 timeit 模組中):           Python 接口.        (line    8)
* timeout:                               异常<11>.           (line   33)
* timeout (socketserver.BaseServer 的屬性): Server 对象<2>.  (line  100)
* timeout (ssl.SSLSession 的屬性):       SSL 会话.           (line   16)
* timeout (subprocess.TimeoutExpired 的屬性): 使用 subprocess 模块.
                                                             (line  148)
* timeout() (curses.window 的方法):      Window 对象.        (line  479)
* TimeoutError:                          OS 异常.            (line   93)
* TimeoutError <1>:                      Process 和异常.     (line  191)
* TimeoutError <2>:                      Exception 类.       (line   10)
* TimeoutError <3>:                      异常<9>.            (line   10)
* TimeoutExpired:                        使用 subprocess 模块.
                                                             (line  139)
* TIMEOUT_MAX (於 threading 模組中):     threading --- 基于线程的并行.
                                                             (line  136)
* TIMEOUT_MAX (於 _thread 模組中):       _thread --- 底层多线程 API.
                                                             (line   94)
* Timer (threading 中的類別):            定时器对象.         (line   22)
* Timer (timeit 中的類別):               Python 接口.        (line   35)
* TimerHandle (asyncio 中的類別):        回调处理.           (line   22)
* times() (於 os 模組中):                进程管理.           (line  592)
* TIMESTAMP (py_compile.PycInvalidationMode 的屬性): py_compile --- 编译 Python 源文件.
                                                             (line   83)
* timestamp() (datetime.datetime 的方法): datetime 对象.     (line  492)
* timetuple() (datetime.date 的方法):    date 对象.          (line  166)
* timetuple() (datetime.datetime 的方法): datetime 对象.     (line  451)
* timetz() (datetime.datetime 的方法):   datetime 对象.      (line  369)
* timezone (datetime 中的類別):          timezone 对象.      (line   12)
* timezone (於 time 模組中):             时区常量.           (line   16)
* time_ns() (於 time 模組中):            函数<3>.            (line  431)
* title() (bytearray 的方法):            bytes 和 bytearray 操作.
                                                             (line  590)
* title() (bytes 的方法):                bytes 和 bytearray 操作.
                                                             (line  590)
* title() (str 的方法):                  字符串的方法<2>.    (line  526)
* title() (於 turtle 模組中):            Screen 专有方法 而非继承自 TurtleScreen.
                                                             (line   45)
* Tix:                                   tkinter tix --- TK扩展包.
                                                             (line    8)
* tixCommand (tkinter.tix 中的類別):     Tix Commands.       (line    6)
* tix_addbitmapdir() (tkinter.tix.tixCommand 的方法): Tix Commands.
                                                             (line   47)
* tix_cget() (tkinter.tix.tixCommand 的方法): Tix Commands.  (line   32)
* tix_configure() (tkinter.tix.tixCommand 的方法): Tix Commands.
                                                             (line   20)
* tix_filedialog() (tkinter.tix.tixCommand 的方法): Tix Commands.
                                                             (line   57)
* tix_getbitmap() (tkinter.tix.tixCommand 的方法): Tix Commands.
                                                             (line   37)
* tix_getimage() (tkinter.tix.tixCommand 的方法): Tix Commands.
                                                             (line   68)
* tix_option_get() (tkinter.tix.tixCommand 的方法): Tix Commands.
                                                             (line   82)
* tix_resetoptions() (tkinter.tix.tixCommand 的方法): Tix Commands.
                                                             (line   86)
* Tk:                                    以 Tk 打造 GUI.     (line    6)
* Tk (tkinter 中的類別):                 Tkinter 模块.       (line   14)
* Tk (tkinter.tix 中的類別):             Using Tix.          (line    6)
* Tk Option Data Types:                  Tk 参数的数据类型.  (line    6)
* Tkinter:                               以 Tk 打造 GUI.     (line    6)
* tkinter (模組):                        tkinter --- Tcl/Tk的Python接口.
                                                             (line    6)
* tkinter.colorchooser (模組):           tkinter colorchooser --- 颜色选择对话框.
                                                             (line    6)
* tkinter.commondialog (模組):           tkinter commondialog --- 对话窗口模板.
                                                             (line    6)
* tkinter.dnd (模組):                    tkinter dnd --- 拖放操作支持.
                                                             (line    6)
* tkinter.filedialog (模組):             tkinter filedialog --- 文件选择对话框.
                                                             (line    6)
* tkinter.font (模組):                   tkinter font --- Tkinter 字体封装.
                                                             (line    6)
* tkinter.messagebox (模組):             tkinter messagebox --- Tkinter 消息提示.
                                                             (line    6)
* tkinter.scrolledtext (模組):           tkinter scrolledtext --- 滚动文字控件.
                                                             (line    6)
* tkinter.simpledialog (模組):           tkinter simpledialog --- 标准 Tkinter 输入对话框.
                                                             (line    6)
* tkinter.tix (模組):                    tkinter tix --- TK扩展包.
                                                             (line    6)
* tkinter.ttk (模組):                    tkinter ttk --- Tk主题部件.
                                                             (line    6)
* TK_LIBRARY:                            我怎样“冻结”Tkinter程序？.
                                                             (line   10)
* TList (tkinter.tix 中的類別):          Tabular ListBox.    (line    6)
* TLS:                                   ssl --- 套接字对象的 TLS/SSL 包装器.
                                                             (line    8)
* TLSv1 (ssl.TLSVersion 的屬性):         常量<3>.            (line  486)
* TLSv1_1 (ssl.TLSVersion 的屬性):       常量<3>.            (line  488)
* TLSv1_2 (ssl.TLSVersion 的屬性):       常量<3>.            (line  490)
* TLSv1_3 (ssl.TLSVersion 的屬性):       常量<3>.            (line  492)
* TLSVersion (ssl 中的類別):             常量<3>.            (line  469)
* TMP:                                   tempfile --- 生成临时文件和目录.
                                                             (line  202)
* TMPDIR:                                tempfile --- 生成临时文件和目录.
                                                             (line  198)
* ToASCII() (於 encodings.idna 模組中):  encodings idna --- 应用程序中的国际化域名.
                                                             (line   43)
* tobuf() (tarfile.TarInfo 的方法):      TarInfo 对象.       (line   28)
* tobytes() (array.array 的方法):        array --- 高效率的數值型態陣列.
                                                             (line  185)
* tobytes() (memoryview 的方法):         内存视图.           (line  145)
* today() (datetime.date 的類別成員):    date 对象.          (line   26)
* today() (datetime.datetime 的類別成員): datetime 对象.     (line   44)
* tofile() (array.array 的方法):         array --- 高效率的數值型態陣列.
                                                             (line  193)
* token:                                 词法分析.           (line    6)
* Token (contextvars 中的類別):          上下文变量.         (line   65)
* token (shlex.shlex 的屬性):            shlex 对象.         (line  141)
* token (模組):                          token --- 与Python解析树一起使用的常量.
                                                             (line    6)
* TokenError:                            对输入进行解析标记. (line   90)
* tokenize (模組):                       tokenize --- 对 Python 代码使用的标记解析器.
                                                             (line    6)
* tokenize command line option; -e:      命令行用法<3>.      (line   18)
* tokenize command line option; –exact:  命令行用法<3>.      (line   18)
* tokenize command line option; -h:      命令行用法<3>.      (line   14)
* tokenize command line option; –help:   命令行用法<3>.      (line   14)
* tokenize() (於 tokenize 模組中):       对输入进行解析标记. (line    8)
* token_bytes() (於 secrets 模組中):     產生權杖（token）.  (line    9)
* token_hex() (於 secrets 模組中):       產生權杖（token）.  (line   17)
* token_urlsafe() (於 secrets 模組中):   產生權杖（token）.  (line   26)
* tok_name (於 token 模組中):            token --- 与Python解析树一起使用的常量.
                                                             (line   17)
* tolist() (array.array 的方法):         array --- 高效率的數值型態陣列.
                                                             (line  198)
* tolist() (memoryview 的方法):          内存视图.           (line  181)
* tolist() (parser.ST 的方法):           ST 对象.            (line   29)
* tomono() (於 audioop 模組中):          audioop --- 处理原始音频数据.
                                                             (line  175)
* toordinal() (datetime.date 的方法):    date 对象.          (line  180)
* toordinal() (datetime.datetime 的方法): datetime 对象.     (line  488)
* top() (curses.panel.Panel 的方法):     Panel 对象.         (line   49)
* top() (poplib.POP3 的方法):            POP3 对象.          (line   79)
* TopologicalSorter (graphlib 中的類別): graphlib --- 操作类似图的结构的功能.
                                                             (line   10)
* toprettyxml() (xml.dom.minidom.Node 的方法): DOM 对象.     (line   59)
* top_panel() (於 curses.panel 模組中):  函数<5>.            (line   18)
* toreadonly() (memoryview 的方法):      内存视图.           (line  196)
* tostereo() (於 audioop 模組中):        audioop --- 处理原始音频数据.
                                                             (line  180)
* tostring() (於 xml.etree.ElementTree 模組中): 函数<7>.     (line  184)
* tostringlist() (於 xml.etree.ElementTree 模組中): 函数<7>. (line  203)
* total_changes (sqlite3.Connection 的屬性): 连接对象（Connection）.
                                                             (line  355)
* total_nframe (tracemalloc.Traceback 的屬性): 回溯.         (line   28)
* total_ordering() (於 functools 模組中): functools --- 高阶函数和可调用对象上的操作.
                                                             (line  204)
* total_seconds() (datetime.timedelta 的方法): timedelta 类对象.
                                                             (line  225)
* totuple() (parser.ST 的方法):          ST 对象.            (line   33)
* touch() (pathlib.Path 的方法):         方法<2>.            (line  411)
* touchline() (curses.window 的方法):    Window 对象.        (line  487)
* touchwin() (curses.window 的方法):     Window 对象.        (line  493)
* tounicode() (array.array 的方法):      array --- 高效率的數值型態陣列.
                                                             (line  202)
* ToUnicode() (於 encodings.idna 模組中): encodings idna --- 应用程序中的国际化域名.
                                                             (line   48)
* towards() (於 turtle 模組中):          获取海龟的状态.     (line   14)
* toxml() (xml.dom.minidom.Node 的方法): DOM 对象.           (line   44)
* to_bytes() (int 的方法):               整数类型的附加方法. (line   33)
* to_eng_string() (decimal.Context 的方法): 上下文对象.      (line  448)
* to_eng_string() (decimal.Decimal 的方法): Decimal 对象.    (line  472)
* to_integral() (decimal.Decimal 的方法): Decimal 对象.      (line  482)
* to_integral_exact() (decimal.Context 的方法): 上下文对象.  (line  455)
* to_integral_exact() (decimal.Decimal 的方法): Decimal 对象.
                                                             (line  487)
* to_integral_value() (decimal.Decimal 的方法): Decimal 对象.
                                                             (line  494)
* to_sci_string() (decimal.Context 的方法): 上下文对象.      (line  459)
* to_thread() (於 asyncio 模組中):       在线程中运行.       (line    6)
* tparm() (於 curses 模組中):            函数<4>.            (line  433)
* Trace (trace 中的類別):                编程接口.           (line    6)
* Trace (tracemalloc 中的類別):          跟踪.               (line    6)
* trace (模組):                          trace --- 跟踪Python语句执行.
                                                             (line    6)
* trace command line option; -c:         主要的可选参数.     (line   11)
* trace command line option; -C:         修饰器.             (line   11)
* trace command line option; –count:     主要的可选参数.     (line   11)
* trace command line option; –coverdir=<dir>: 修饰器.        (line   11)
* trace command line option; -f:         修饰器.             (line    6)
* trace command line option; –file=<file>: 修饰器.           (line    6)
* trace command line option; -g:         修饰器.             (line   30)
* trace command line option; –help:      命令行用法.         (line   13)
* trace command line option; –ignore-dir=<dir>: 过滤器.      (line   12)
* trace command line option; –ignore-module=<mod>: 过滤器.   (line    8)
* trace command line option; -l:         主要的可选参数.     (line   21)
* trace command line option; –listfuncs: 主要的可选参数.     (line   21)
* trace command line option; -m:         修饰器.             (line   16)
* trace command line option; –missing:   修饰器.             (line   16)
* trace command line option; –no-report: 修饰器.             (line   25)
* trace command line option; -r:         主要的可选参数.     (line   25)
* trace command line option; -R:         修饰器.             (line   25)
* trace command line option; –report:    主要的可选参数.     (line   25)
* trace command line option; -s:         修饰器.             (line   20)
* trace command line option; –summary:   修饰器.             (line   20)
* trace command line option; -t:         主要的可选参数.     (line   17)
* trace command line option; -T:         主要的可选参数.     (line   30)
* trace command line option; –timing:    修饰器.             (line   30)
* trace command line option; –trace:     主要的可选参数.     (line   17)
* trace command line option; –trackcalls: 主要的可选参数.    (line   30)
* trace command line option; –version:   命令行用法.         (line   17)
* trace function:                        threading --- 基于线程的并行.
                                                             (line  109)
* trace function <1>:                    sys --- 系统相关的参数和函数.
                                                             (line  626)
* trace function <2>:                    sys --- 系统相关的参数和函数.
                                                             (line 1114)
* trace() (於 inspect 模組中):           The interpreter stack.
                                                             (line   91)
* Traceback (tracemalloc 中的類別):      回溯.               (line    6)
* traceback (tracemalloc.Statistic 的屬性): 统计.            (line   23)
* traceback (tracemalloc.StatisticDiff 的屬性): StatisticDiff.
                                                             (line   38)
* traceback (tracemalloc.Trace 的屬性):  跟踪.               (line   27)
* traceback (模組):                      traceback --- 打印或检索堆栈回溯.
                                                             (line    6)
* TracebackException (traceback 中的類別): TracebackException Objects.
                                                             (line   11)
* tracebacklimit (於 sys 模組中):        sys --- 系统相关的参数和函数.
                                                             (line 1342)
* tracebacks; in CGI scripts:            cgitb --- 用于 CGI 脚本的回溯管理器.
                                                             (line    8)
* TracebackType (types 中的類別):        标准解释器类型.     (line  180)
* traceback_limit (tracemalloc.Snapshot 的屬性): 快照.       (line   82)
* traceback_limit (wsgiref.handlers.BaseHandler 的屬性): wsgiref handlers -- 服务器/网关基类.
                                                             (line  182)
* tracemalloc (模組):                    tracemalloc --- 跟踪内存分配.
                                                             (line    6)
* tracer() (於 turtle 模組中):           动画控制.           (line   22)
* traces (tracemalloc.Snapshot 的屬性):  快照.               (line   88)
* trace_dispatch() (bdb.Bdb 的方法):     bdb --- Debugger framework.
                                                             (line  111)
* trailing; comma:                       表达式列表.         (line   20)
* transfercmd() (ftplib.FTP 的方法):     FTP 对象.           (line  113)
* TransientResource (test.support 中的類別): test support --- Utilities for the Python test suite.
                                                             (line 1036)
* transient_internet() (於 test.support.socket_helper 模組中): test support socket_helper --- Utilities for socket tests.
                                                             (line   64)
* translate() (bytearray 的方法):        bytes 和 bytearray 操作.
                                                             (line  221)
* translate() (bytes 的方法):            bytes 和 bytearray 操作.
                                                             (line  221)
* translate() (str 的方法):              字符串的方法<2>.    (line  554)
* translate() (於 fnmatch 模組中):       fnmatch --- Unix 文件名模式匹配.
                                                             (line   66)
* translation() (於 gettext 模組中):     基于类的 API.       (line   35)
* Transport (asyncio 中的類別):          传输层级.           (line   26)
* transport (asyncio.StreamWriter 的屬性): StreamWriter.     (line   52)
* Transport Layer Security:              ssl --- 套接字对象的 TLS/SSL 包装器.
                                                             (line    8)
* Traversable (importlib.abc 中的類別):  importlib abc —— 关于导入的抽象基类.
                                                             (line  525)
* TraversableResources (importlib.abc 中的類別): importlib abc —— 关于导入的抽象基类.
                                                             (line  572)
* traverseproc (C 型態):                 使对象类型支持循环垃圾回收.
                                                             (line  120)
* Tree (tkinter.tix 中的類別):           Hierarchical ListBox.
                                                             (line   20)
* TreeBuilder (xml.etree.ElementTree 中的類別): TreeBuilder 对象.
                                                             (line    6)
* Treeview (tkinter.ttk 中的類別):       ttk Treeview.       (line    6)
* triangular() (於 random 模組中):       实值分布.           (line   21)
* triple-quoted string:                  字符串与字节串字面值.
                                                             (line   33)
* triple-quoted string（三引號內字串）:  術語表.             (line 1089)
* True:                                  标准类型层级结构.   (line   74)
* true:                                  逻辑值检测.         (line    9)
* True <1>:                              逻辑值检测.         (line   19)
* True <2>:                              布尔值.             (line   12)
* True (內建變數):                       內建常數.           (line   13)
* truediv() (於 operator 模組中):        operator --- 标准运算符替代函数.
                                                             (line  146)
* trunc() (in module math):              数字类型 --- int float complex.
                                                             (line   92)
* trunc() (於 math 模組中):              数论与表示函数.     (line  226)
* truncate() (io.IOBase 的方法):         I/O 基类.           (line  120)
* truncate() (於 os 模組中):             文件和目录.         (line 1234)
* truth() (於 operator 模組中):          operator --- 标准运算符替代函数.
                                                             (line   47)
* truth; value:                          逻辑值检测.         (line    6)
* Try (ast 中的類別):                    Control flow.       (line  134)
* ttk:                                   tkinter ttk --- Tk主题部件.
                                                             (line    8)
* tty (模組):                            tty --- 终端控制功能.
                                                             (line    6)
* tty; I/O control:                      termios --- POSIX 风格的 tty 控制.
                                                             (line    6)
* ttyname() (於 os 模組中):              文件描述符操作.     (line  602)
* Tuple (ast 中的類別):                  字面值<3>.          (line   67)
* tuple (內建類別):                      元组.               (line   11)
* Tuple (於 typing 模組中):              特殊形式.           (line    8)
* tuple2st() (於 parser 模組中):         创建 ST 对象.       (line   51)
* tuple_params (2to3 fixer):             修复器.             (line  294)
* Turtle (turtle 中的類別):              公共类.             (line   16)
* turtle (模組):                         turtle --- 龜圖學.  (line    6)
* turtledemo (模組):                     turtledemo --- 演示脚本集.
                                                             (line    6)
* turtles() (於 turtle 模組中):          设置与特殊方法.     (line   92)
* TurtleScreen (turtle 中的類別):        公共类.             (line   21)
* turtlesize() (於 turtle 模組中):       外观.               (line   47)
* type:                                  标准类型层级结构.   (line    6)
* type (optparse.Option 的屬性):         Option attributes.  (line   19)
* type (socket.socket 的屬性):           套接字对象.         (line  501)
* type (tarfile.TarInfo 的屬性):         TarInfo 对象.       (line   54)
* Type (typing 中的類別):                特殊形式.           (line   89)
* type (urllib.request.Request 的屬性):  Request 对象.       (line   20)
* type (內建類別):                       內建函式.           (line 1434)
* type alias（型別別名）:                術語表.             (line 1103)
* type hint（型別提示）:                 術語表.             (line 1122)
* type of an object:                     对象、值与类型.     (line   10)
* type; hierarchy:                       标准类型层级结构.   (line    6)
* typeahead() (於 curses 模組中):        函数<4>.            (line  439)
* typecode (array.array 的屬性):         array --- 高效率的數值型態陣列.
                                                             (line   96)
* typecodes (於 array 模組中):           array --- 高效率的數值型態陣列.
                                                             (line   85)
* TypedDict (typing 中的類別):           其他特殊指令.       (line   71)
* TYPED_ACTIONS (optparse.Option 的屬性): Adding new actions.
                                                             (line   39)
* typed_subpart_iterator() (於 email.iterators 模組中): email iterators 迭代器.
                                                             (line   22)
* TypeError:                             具体异常.           (line  282)
* types (2to3 fixer):                    修复器.             (line  298)
* TYPES (optparse.Option 的屬性):        Adding new types.   (line   11)
* types (模組):                          types --- 动态类型创建和内置类型名称.
                                                             (line    6)
* types, internal:                       标准类型层级结构.   (line  503)
* types_map (mimetypes.MimeTypes 的屬性): MimeTypes 对象.    (line   31)
* types_map (於 mimetypes 模組中):       mimetypes --- 映射文件名到 MIME 类型.
                                                             (line  117)
* types_map_inv (mimetypes.MimeTypes 的屬性): MimeTypes 对象.
                                                             (line   37)
* TypeVar (typing 中的類別):             构建泛型类型.       (line   31)
* TYPE_CHECKER (optparse.Option 的屬性): Adding new types.   (line   16)
* TYPE_CHECKING (於 typing 模組中):      常量<4>.            (line    6)
* type_check_only() (於 typing 模組中):  函数与装饰器.       (line   76)
* type_comment (ast.arg 的屬性):         Function and class definitions.
                                                             (line   75)
* type_comment (ast.Assign 的屬性):      Statements.         (line   15)
* type_comment (ast.For 的屬性):         Control flow.       (line   54)
* type_comment (ast.FunctionDef 的屬性): Function and class definitions.
                                                             (line   23)
* type_comment (ast.With 的屬性):        Control flow.       (line  216)
* TYPE_COMMENT (於 token 模組中):        token --- 与Python解析树一起使用的常量.
                                                             (line  246)
* TYPE_IGNORE (於 token 模組中):         token --- 与Python解析树一起使用的常量.
                                                             (line  244)
* type（型別）:                          術語表.             (line 1097)
* typing (模組):                         typing --- 类型提示支持.
                                                             (line    6)
* TZ:                                    函数<3>.            (line  440)
* TZ <1>:                                函数<3>.            (line  441)
* TZ <2>:                                函数<3>.            (line  448)
* TZ <3>:                                函数<3>.            (line  452)
* TZ <4>:                                函数<3>.            (line  454)
* TZ <5>:                                函数<3>.            (line  507)
* tzinfo (datetime 中的類別):            tzinfo 对象.        (line    6)
* tzinfo (datetime.datetime 的屬性):     datetime 对象.      (line  271)
* tzinfo (datetime.time 的屬性):         time 对象.          (line   62)
* tzname (於 time 模組中):               时区常量.           (line   21)
* tzname() (datetime.datetime 的方法):   datetime 对象.      (line  445)
* tzname() (datetime.time 的方法):       time 对象.          (line  217)
* tzname() (datetime.timezone 的方法):   timezone 对象.      (line   34)
* tzname() (datetime.tzinfo 的方法):     tzinfo 对象.        (line  106)
* TZPATH (於 zoneinfo 模組中):           全局变量.           (line    6)
* tzset() (於 time 模組中):              函数<3>.            (line  438)
* T_FMT (於 locale 模組中):              locale --- 国际化服务.
                                                             (line  163)
* T_FMT_AMPM (於 locale 模組中):         locale --- 国际化服务.
                                                             (line  168)
* u"; string literal:                    字面值.             (line    8)
* u’; string literal:                    字面值.             (line    8)
* u-LAW:                                 audioop --- 处理原始音频数据.
                                                             (line   15)
* u-LAW <1>:                             aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line  140)
* u-LAW <2>:                             sndhdr --- 推测声音文件的类型.
                                                             (line    8)
* UAdd (ast 中的類別):                   表达式<2>.          (line   28)
* ucd_3_2_0 (於 unicodedata 模組中):     unicodedata --- Unicode 数据库.
                                                             (line  108)
* udata (select.kevent 的屬性):          Kevent 对象.        (line  175)
* UDPServer (socketserver 中的類別):     socketserver --- 用于网络服务器的框架.
                                                             (line   24)
* UF_APPEND (於 stat 模組中):            stat --- 解析 stat 结果.
                                                             (line  321)
* UF_COMPRESSED (於 stat 模組中):        stat --- 解析 stat 结果.
                                                             (line  333)
* UF_HIDDEN (於 stat 模組中):            stat --- 解析 stat 结果.
                                                             (line  337)
* UF_IMMUTABLE (於 stat 模組中):         stat --- 解析 stat 结果.
                                                             (line  317)
* UF_NODUMP (於 stat 模組中):            stat --- 解析 stat 结果.
                                                             (line  313)
* UF_NOUNLINK (於 stat 模組中):          stat --- 解析 stat 结果.
                                                             (line  329)
* UF_OPAQUE (於 stat 模組中):            stat --- 解析 stat 结果.
                                                             (line  325)
* UID (plistlib 中的類別):               plistlib --- 生成与解析 Apple plist 文件.
                                                             (line  109)
* uid (tarfile.TarInfo 的屬性):          TarInfo 对象.       (line   66)
* uid() (imaplib.IMAP4 的方法):          IMAP4 对象.         (line  327)
* uidl() (poplib.POP3 的方法):           POP3 对象.          (line   88)
* ulaw2lin() (於 audioop 模組中):        audioop --- 处理原始音频数据.
                                                             (line  185)
* ULONG_MAX:                             整數物件.           (line  175)
* ulp() (於 math 模組中):                数论与表示函数.     (line  231)
* umask() (於 os 模組中):                进程参数.           (line  422)
* unalias (pdb command):                 调试器命令.         (line  254)
* uname (tarfile.TarInfo 的屬性):        TarInfo 对象.       (line   74)
* uname() (於 os 模組中):                进程参数.           (line  426)
* uname() (於 platform 模組中):          跨平台.             (line  122)
* unary; arithmetic; operation:          一元算术和位运算.   (line    6)
* unary; bitwise; operation:             一元算术和位运算.   (line    6)
* unaryfunc (C 型態):                    Slot Type typedefs. (line   98)
* UnaryOp (ast 中的類別):                表达式<2>.          (line   23)
* UNARY_INVERT (opcode):                 Python字节码说明.   (line  103)
* UNARY_NEGATIVE (opcode):               Python字节码说明.   (line   95)
* UNARY_NOT (opcode):                    Python字节码说明.   (line   99)
* UNARY_POSITIVE (opcode):               Python字节码说明.   (line   91)
* unbinding; name:                       del 语句.           (line   13)
* UnboundLocalError:                     名称的解析.         (line   14)
* UnboundLocalError <1>:                 具体异常.           (line  295)
* unbuffered I/O:                        內建函式.           (line 1030)
* UNC paths; and os.makedirs():          文件和目录.         (line  408)
* UNCHECKED_HASH (py_compile.PycInvalidationMode 的屬性): py_compile --- 编译 Python 源文件.
                                                             (line   93)
* unconsumed_tail (zlib.Decompress 的屬性): zlib --- 与 gzip 兼容的压缩.
                                                             (line  181)
* unctrl() (於 curses 模組中):           函数<4>.            (line  449)
* unctrl() (於 curses.ascii 模組中):     curses ascii --- 用于 ASCII 字符的工具.
                                                             (line  213)
* undefine_macro() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  169)
* Underflow (decimal 中的類別):          信号.               (line   84)
* undisplay (pdb command):               调试器命令.         (line  223)
* undo() (於 turtle 模組中):             海龟动作.           (line  277)
* undobufferentries() (於 turtle 模組中): 特殊海龟方法.      (line   68)
* undoc_header (cmd.Cmd 的屬性):         Cmd 对象.           (line  127)
* unescape() (於 html 模組中):           html --- 超文本标记语言支持.
                                                             (line   21)
* unescape() (於 xml.sax.saxutils 模組中): xml sax saxutils --- SAX 工具集.
                                                             (line   21)
* UnexpectedException:                   调试.               (line  181)
* unexpectedSuccesses (unittest.TestResult 的屬性): Loading and running tests.
                                                             (line  262)
* unfreeze() (於 gc 模組中):             gc --- 垃圾回收器接口.
                                                             (line  177)
* ungetch() (於 curses 模組中):          函数<4>.            (line  454)
* ungetch() (於 msvcrt 模組中):          控制台 I/O.         (line   38)
* ungetmouse() (於 curses 模組中):       函数<4>.            (line  474)
* ungetwch() (於 msvcrt 模組中):         控制台 I/O.         (line   43)
* unget_wch() (於 curses 模組中):        函数<4>.            (line  466)
* unhexlify() (於 binascii 模組中):      binascii --- 二进制和 ASCII 码互转.
                                                             (line  145)
* Unicode:                               标准类型层级结构.   (line  122)
* Unicode <1>:                           unicodedata --- Unicode 数据库.
                                                             (line    6)
* Unicode <2>:                           codecs --- 编解码器注册和相关基类.
                                                             (line    8)
* unicode (2to3 fixer):                  修复器.             (line  302)
* Unicode Consortium:                    字符串与字节串字面值.
                                                             (line   33)
* Unicode; database:                     unicodedata --- Unicode 数据库.
                                                             (line    6)
* unicodedata (模組):                    unicodedata --- Unicode 数据库.
                                                             (line    6)
* UnicodeDecodeError:                    具体异常.           (line  334)
* UnicodeEncodeError:                    具体异常.           (line  329)
* UnicodeError:                          具体异常.           (line  300)
* UnicodeTranslateError:                 具体异常.           (line  339)
* UnicodeWarning:                        警告.               (line   58)
* unidata_version (於 unicodedata 模組中): unicodedata --- Unicode 数据库.
                                                             (line  104)
* unified_diff() (於 difflib 模組中):    difflib --- 计算差异的辅助工具.
                                                             (line  255)
* uniform() (於 random 模組中):          实值分布.           (line   13)
* UnimplementedFileMode:                 http client --- HTTP 协议客户端.
                                                             (line  131)
* Union (ctypes 中的類別):               结构化数据类型.     (line    6)
* Union (於 typing 模組中):              特殊形式.           (line   23)
* union() (frozenset 的方法):            集合类型 --- set frozenset.
                                                             (line   86)
* unique() (於 enum 模組中):             确保唯一枚举值.     (line    9)
* unittest (模組):                       unittest --- 單元測試框架.
                                                             (line    6)
* unittest command line option; -b:      命令列模式選項.     (line    8)
* unittest command line option; –buffer: 命令列模式選項.     (line    8)
* unittest command line option; -c:      命令列模式選項.     (line   14)
* unittest command line option; –catch:  命令列模式選項.     (line   14)
* unittest command line option; -f:      命令列模式選項.     (line   22)
* unittest command line option; –failfast: 命令列模式選項.   (line   22)
* unittest command line option; -k:      命令列模式選項.     (line   26)
* unittest command line option; –locals: 命令列模式選項.     (line   41)
* unittest-discover command line option; -p: Test Discovery（測試探索）.
                                                             (line   33)
* unittest-discover command line option; –pattern pattern: Test Discovery（測試探索）.
                                                             (line   33)
* unittest-discover command line option; -s: Test Discovery（測試探索）.
                                                             (line   29)
* unittest-discover command line option; –start-directory directory: Test Discovery（測試探索）.
                                                             (line   29)
* unittest-discover command line option; -t: Test Discovery（測試探索）.
                                                             (line   37)
* unittest-discover command line option; –top-level-directory directory: Test Discovery（測試探索）.
                                                             (line   37)
* unittest-discover command line option; -v: Test Discovery（測試探索）.
                                                             (line   25)
* unittest-discover command line option; –verbose: Test Discovery（測試探索）.
                                                             (line   25)
* unittest.mock (模組):                  unittest mock --- mock对象库.
                                                             (line    6)
* universal newlines; bytearray.splitlines method: bytes 和 bytearray 操作.
                                                             (line  546)
* universal newlines; bytes.splitlines method: bytes 和 bytearray 操作.
                                                             (line  546)
* universal newlines; csv.reader function: 模块内容<3>.      (line    8)
* universal newlines; importlib.abc.InspectLoader.get_source method: importlib abc —— 关于导入的抽象基类.
                                                             (line  338)
* universal newlines; io.IncrementalNewlineDecoder class: 文本 I/O<2>.
                                                             (line  204)
* universal newlines; io.TextIOWrapper class: 文本 I/O<2>.   (line  106)
* universal newlines; open() built-in function: 內建函式.    (line  980)
* universal newlines; str.splitlines method: 字符串的方法<2>.
                                                             (line  425)
* universal newlines; subprocess module: 常用参数.           (line   25)
* universal newlines; What’s new:        PEP 3116 新 I/O 库. (line   42)
* universal newlines; What’s new <1>:    新增，改进和删除的模块.
                                                             (line  136)
* universal newlines; What’s new <2>:    PEP 324 新的子进程模块.
                                                             (line   36)
* universal newlines; What’s new <3>:    PEP 277 Unicode file name support for Windows NT.
                                                             (line   36)
* universal newlines（通用換行字元）:    術語表.             (line 1136)
* UNIX:                                  完整的 Python 程序. (line   19)
* UNIX; file control:                    fcntl —— 系统调用 fcntl 和 ioctl.
                                                             (line    6)
* UNIX; I/O control:                     fcntl —— 系统调用 fcntl 和 ioctl.
                                                             (line    6)
* UnixDatagramServer (socketserver 中的類別): socketserver --- 用于网络服务器的框架.
                                                             (line   30)
* UnixStreamServer (socketserver 中的類別): socketserver --- 用于网络服务器的框架.
                                                             (line   30)
* unix_dialect (csv 中的類別):           模块内容<3>.        (line  181)
* unix_shell (於 test.support 模組中):   test support --- Utilities for the Python test suite.
                                                             (line   44)
* unknown (uuid.SafeUUID 的屬性):        uuid --- RFC 4122 定义的UUID对象.
                                                             (line   37)
* UnknownHandler (urllib.request 中的類別): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  360)
* UnknownProtocol:                       http client --- HTTP 协议客户端.
                                                             (line  123)
* UnknownTransferEncoding:               http client --- HTTP 协议客户端.
                                                             (line  127)
* unknown_decl() (html.parser.HTMLParser 的方法): HTMLParser 方法.
                                                             (line  111)
* unknown_open() (urllib.request.BaseHandler 的方法): BaseHandler 对象.
                                                             (line   49)
* unknown_open() (urllib.request.UnknownHandler 的方法): UnknownHandler 对象.
                                                             (line    6)
* unlink() (multiprocessing.shared_memory.SharedMemory 的方法): multiprocessing shared_memory --- 可从进程直接访问的共享内存.
                                                             (line   55)
* unlink() (pathlib.Path 的方法):        方法<2>.            (line  418)
* unlink() (xml.dom.minidom.Node 的方法): DOM 对象.          (line    9)
* unlink() (於 os 模組中):               文件和目录.         (line 1251)
* unlink() (於 test.support 模組中):     test support --- Utilities for the Python test suite.
                                                             (line  231)
* unload() (於 test.support 模組中):     test support --- Utilities for the Python test suite.
                                                             (line  227)
* unlock() (mailbox.Babyl 的方法):       Babyl.              (line   47)
* unlock() (mailbox.Mailbox 的方法):     Mailbox 对象.       (line  209)
* unlock() (mailbox.Maildir 的方法):     Maildir.            (line   90)
* unlock() (mailbox.mbox 的方法):        mbox.               (line   32)
* unlock() (mailbox.MH 的方法):          MH.                 (line   75)
* unlock() (mailbox.MMDF 的方法):        MMDF.               (line   29)
* unpack() (struct.Struct 的方法):       类.                 (line   30)
* unpack() (於 struct 模組中):           函数和异常.         (line   23)
* Unpacker (xdrlib 中的類別):            xdrlib --- 编码与解码 XDR 数据.
                                                             (line   22)
* unpacking; dictionary:                 字典显示.           (line   19)
* unpacking; in function calls:          调用.               (line   55)
* unpack_archive() (於 shutil 模組中):   归档操作.           (line   98)
* unpack_array() (xdrlib.Unpacker 的方法): Unpacker 对象.    (line   81)
* unpack_bytes() (xdrlib.Unpacker 的方法): Unpacker 对象.    (line   63)
* unpack_double() (xdrlib.Unpacker 的方法): Unpacker 对象.   (line   38)
* UNPACK_EX (opcode):                    Python字节码说明.   (line  416)
* unpack_farray() (xdrlib.Unpacker 的方法): Unpacker 对象.   (line   75)
* unpack_float() (xdrlib.Unpacker 的方法): Unpacker 对象.    (line   34)
* unpack_fopaque() (xdrlib.Unpacker 的方法): Unpacker 对象.  (line   49)
* unpack_from() (struct.Struct 的方法):  类.                 (line   35)
* unpack_from() (於 struct 模組中):      函数和异常.         (line   30)
* unpack_fstring() (xdrlib.Unpacker 的方法): Unpacker 对象.  (line   44)
* unpack_list() (xdrlib.Unpacker 的方法): Unpacker 对象.     (line   69)
* unpack_opaque() (xdrlib.Unpacker 的方法): Unpacker 对象.   (line   58)
* UNPACK_SEQUENCE (opcode):              Python字节码说明.   (line  411)
* unpack_string() (xdrlib.Unpacker 的方法): Unpacker 对象.   (line   53)
* unparse() (於 ast 模組中):             ast 中的辅助函数.   (line   56)
* unparsedEntityDecl() (xml.sax.handler.DTDHandler 的方法): DTDHandler 对象.
                                                             (line   12)
* UnparsedEntityDeclHandler() (xml.parsers.expat.xmlparser 的方法): XMLParser对象<2>.
                                                             (line  207)
* Unpickler (pickle 中的類別):           模块接口.           (line  201)
* UnpicklingError:                       模块接口.           (line   96)
* unquote() (於 email.utils 模組中):     email utils 其他工具.
                                                             (line   42)
* unquote() (於 urllib.parse 模組中):    URL 转码.           (line   53)
* unquote_plus() (於 urllib.parse 模組中): URL 转码.         (line   69)
* unquote_to_bytes() (於 urllib.parse 模組中): URL 转码.     (line   79)
* unraisablehook() (於 sys 模組中):      sys --- 系统相关的参数和函数.
                                                             (line 1348)
* unreachable object:                    对象、值与类型.     (line   29)
* unreadline() (distutils.text_file.TextFile 的方法): distutils text_file --- The TextFile class.
                                                             (line  130)
* unrecognized escape sequence:          字符串与字节串字面值.
                                                             (line  137)
* unregister() (select.devpoll 的方法):  /dev/poll 轮询对象. (line   50)
* unregister() (select.epoll 的方法):    边缘触发和水平触发的轮询 epoll 对象.
                                                             (line   87)
* unregister() (select.poll 的方法):     Poll 对象.          (line   57)
* unregister() (selectors.BaseSelector 的方法): 类<2>.       (line   73)
* unregister() (於 atexit 模組中):       atexit --- 退出处理器.
                                                             (line   35)
* unregister() (於 faulthandler 模組中): 转储用户信号的跟踪信息。.
                                                             (line   20)
* unregister_archive_format() (於 shutil 模組中): 归档操作.  (line   94)
* unregister_dialect() (於 csv 模組中):  模块内容<3>.        (line   67)
* unregister_unpack_format() (於 shutil 模組中): 归档操作.   (line  132)
* unsafe (uuid.SafeUUID 的屬性):         uuid --- RFC 4122 定义的UUID对象.
                                                             (line   33)
* unselect() (imaplib.IMAP4 的方法):     IMAP4 对象.         (line  337)
* unset() (test.support.EnvironmentVarGuard 的方法): test support --- Utilities for the Python test suite.
                                                             (line 1061)
* unsetenv() (於 os 模組中):             进程参数.           (line  452)
* UnstructuredHeader (email.headerregistry 中的類別): email headerregistry 自定义标头对象.
                                                             (line   94)
* unsubscribe() (imaplib.IMAP4 的方法):  IMAP4 对象.         (line  333)
* UnsupportedOperation:                  高阶模块接口.       (line   37)
* until (pdb command):                   调试器命令.         (line  144)
* untokenize() (於 tokenize 模組中):     对输入进行解析标记. (line   48)
* untouchwin() (curses.window 的方法):   Window 对象.        (line  497)
* unused_data (bz2.BZ2Decompressor 的屬性): 增量压缩和解压.  (line   67)
* unused_data (lzma.LZMADecompressor 的屬性): 在内存中压缩和解压缩数据.
                                                             (line  136)
* unused_data (zlib.Decompress 的屬性):  zlib --- 与 gzip 兼容的压缩.
                                                             (line  175)
* unverifiable (urllib.request.Request 的屬性): Request 对象.
                                                             (line   44)
* unwrap() (ssl.SSLSocket 的方法):       SSL 套接字.         (line  236)
* unwrap() (於 inspect 模組中):          类与函数<2>.        (line  185)
* unwrap() (於 urllib.parse 模組中):     URL 解析.           (line  341)
* up (pdb command):                      调试器命令.         (line   51)
* up() (於 turtle 模組中):               绘图状态.           (line   12)
* update() (collections.Counter 的方法): Counter 物件.       (line   99)
* update() (dict 的方法):                映射类型 --- dict.  (line  188)
* update() (frozenset 的方法):           集合类型 --- set frozenset.
                                                             (line  151)
* update() (hashlib.hash 的方法):        哈希算法.           (line  112)
* update() (hmac.HMAC 的方法):           hmac --- 基于密钥的消息验证.
                                                             (line   42)
* update() (http.cookies.Morsel 的方法): Morsel 对象.        (line   87)
* update() (mailbox.Mailbox 的方法):     Mailbox 对象.       (line  184)
* update() (mailbox.Maildir 的方法):     Maildir.            (line   77)
* update() (trace.CoverageResults 的方法): 编程接口.         (line   44)
* update() (於 turtle 模組中):           动画控制.           (line   43)
* update_authenticated() (urllib.request.HTTPPasswordMgrWithPriorAuth 的方法): HTTPPasswordMgrWithPriorAuth 对象.
                                                             (line   22)
* update_lines_cols() (於 curses 模組中): 函数<4>.           (line  460)
* update_panels() (於 curses.panel 模組中): 函数<5>.         (line   22)
* update_visible() (mailbox.BabylMessage 的方法): BabylMessage.
                                                             (line   72)
* update_wrapper() (於 functools 模組中): functools --- 高阶函数和可调用对象上的操作.
                                                             (line  512)
* upgrade_dependencies() (venv.EnvBuilder 的方法): API<2>.   (line   97)
* upper() (bytearray 的方法):            bytes 和 bytearray 操作.
                                                             (line  628)
* upper() (bytes 的方法):                bytes 和 bytearray 操作.
                                                             (line  628)
* upper() (str 的方法):                  字符串的方法<2>.    (line  569)
* urandom() (於 os 模組中):              随机数.             (line   26)
* URL:                                   cgi --- 通用网关接口支持.
                                                             (line    8)
* URL <1>:                               urllib parse 用于解析 URL.
                                                             (line    8)
* URL <2>:                               urllib robotparser --- robots txt 语法分析程序.
                                                             (line    8)
* URL <3>:                               http server --- HTTP 服务器.
                                                             (line    8)
* url (http.client.HTTPResponse 的屬性): HTTPResponse 对象.  (line   46)
* url (urllib.response.addinfourl 的屬性): urllib response --- urllib 使用的 Response 类.
                                                             (line   13)
* url (xmlrpc.client.ProtocolError 的屬性): ProtocolError 对象.
                                                             (line   12)
* url2pathname() (於 urllib.request 模組中): urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  127)
* URL; parsing:                          urllib parse 用于解析 URL.
                                                             (line    8)
* urlcleanup() (於 urllib.request 模組中): 沿袭的接口.       (line   51)
* urldefrag() (於 urllib.parse 模組中):  URL 解析.           (line  318)
* urlencode() (於 urllib.parse 模組中):  URL 转码.           (line   91)
* URLError:                              urllib error --- urllib request 引发的异常类.
                                                             (line   15)
* urljoin() (於 urllib.parse 模組中):    URL 解析.           (line  291)
* urllib (2to3 fixer):                   修复器.             (line  306)
* urllib (模組):                         urllib --- URL 处理模块.
                                                             (line    6)
* urllib.error (模組):                   urllib error --- urllib request 引发的异常类.
                                                             (line    6)
* urllib.parse (模組):                   urllib parse 用于解析 URL.
                                                             (line    6)
* urllib.request (模組):                 urllib request --- 用于打开 URL 的可扩展库.
                                                             (line    6)
* urllib.response (模組):                urllib response --- urllib 使用的 Response 类.
                                                             (line    6)
* urllib.robotparser (模組):             urllib robotparser --- robots txt 语法分析程序.
                                                             (line    6)
* urlopen() (於 urllib.request 模組中):  urllib request --- 用于打开 URL 的可扩展库.
                                                             (line   20)
* URLopener (urllib.request 中的類別):   沿袭的接口.         (line   55)
* urlparse() (於 urllib.parse 模組中):   URL 解析.           (line    9)
* urlretrieve() (於 urllib.request 模組中): 沿袭的接口.      (line    9)
* urlsafe_b64decode() (於 base64 模組中): base64 —— Base16、Base32、Base64、Base85 資料編碼.
                                                             (line   77)
* urlsafe_b64encode() (於 base64 模組中): base64 —— Base16、Base32、Base64、Base85 資料編碼.
                                                             (line   71)
* urlsplit() (於 urllib.parse 模組中):   URL 解析.           (line  218)
* urlunparse() (於 urllib.parse 模組中): URL 解析.           (line  211)
* urlunsplit() (於 urllib.parse 模組中): URL 解析.           (line  284)
* urn (uuid.UUID 的屬性):                uuid --- RFC 4122 定义的UUID对象.
                                                             (line  123)
* UseForeignDTD() (xml.parsers.expat.xmlparser 的方法): XMLParser对象<2>.
                                                             (line   51)
* USER:                                  getpass --- 便携式密码输入工具.
                                                             (line   35)
* user() (poplib.POP3 的方法):           POP3 对象.          (line   29)
* user-defined; function:                标准类型层级结构.   (line  233)
* user-defined; function; call:          调用.               (line   99)
* user-defined; method:                  标准类型层级结构.   (line  303)
* user; effective id:                    进程参数.           (line  158)
* user; id:                              进程参数.           (line  276)
* user; id, setting:                     进程参数.           (line  406)
* UserDict (collections 中的類別):       UserDict 对象.      (line   10)
* UserList (collections 中的類別):       UserList 对象.      (line   13)
* USERNAME:                              进程参数.           (line  200)
* USERNAME <1>:                          getpass --- 便携式密码输入工具.
                                                             (line   35)
* username (email.headerregistry.Address 的屬性): email headerregistry 自定义标头对象.
                                                             (line  368)
* USERPROFILE:                           os path.            (line   13)
* USERPROFILE <1>:                       更改的Python API.   (line  102)
* USERPROFILE <2>:                       Windows<17>.        (line   15)
* USERPROFILE <3>:                       os path --- 常用路径操作.
                                                             (line  128)
* USERPROFILE <4>:                       Location and names of config files.
                                                             (line   67)
* userptr() (curses.panel.Panel 的方法): Panel 对象.         (line   53)
* UserString (collections 中的類別):     UserString 对象.    (line   10)
* UserWarning:                           警告.               (line   12)
* USER_BASE:                             新增和改进的模块.   (line  469)
* USER_BASE (於 site 模組中):            模块内容<8>.        (line   29)
* user_call() (bdb.Bdb 的方法):          bdb --- Debugger framework.
                                                             (line  211)
* user_exception() (bdb.Bdb 的方法):     bdb --- Debugger framework.
                                                             (line  228)
* user_line() (bdb.Bdb 的方法):          bdb --- Debugger framework.
                                                             (line  217)
* user_return() (bdb.Bdb 的方法):        bdb --- Debugger framework.
                                                             (line  223)
* USER_SITE (於 site 模組中):            模块内容<8>.        (line   18)
* use_default_colors() (於 curses 模組中): 函数<4>.          (line  486)
* use_env() (於 curses 模組中):          函数<4>.            (line  478)
* use_rawinput (cmd.Cmd 的屬性):         Cmd 对象.           (line  137)
* USTAR_FORMAT (於 tarfile 模組中):      tarfile --- 读写tar归档文件.
                                                             (line  204)
* USub (ast 中的類別):                   表达式<2>.          (line   28)
* UTC:                                   time --- 时间的访问和转换.
                                                             (line   33)
* utc (datetime.timezone 的屬性):        timezone 对象.      (line   57)
* utcfromtimestamp() (datetime.datetime 的類別成員): datetime 对象.
                                                             (line  113)
* utcnow() (datetime.datetime 的類別成員): datetime 对象.    (line   71)
* utcoffset() (datetime.datetime 的方法): datetime 对象.     (line  429)
* utcoffset() (datetime.time 的方法):    time 对象.          (line  201)
* utcoffset() (datetime.timezone 的方法): timezone 对象.     (line   25)
* utcoffset() (datetime.tzinfo 的方法):  tzinfo 对象.        (line   31)
* utctimetuple() (datetime.datetime 的方法): datetime 对象.  (line  469)
* utf8 (email.policy.EmailPolicy 的屬性): email policy Policy 对象.
                                                             (line  291)
* utf8() (poplib.POP3 的方法):           POP3 对象.          (line   94)
* utf8_enabled (imaplib.IMAP4 的屬性):   IMAP4 对象.         (line  361)
* utime() (於 os 模組中):                文件和目录.         (line 1264)
* uu (模組):                             uu --- 对 uuencode 文件进行编码与解码.
                                                             (line    6)
* UUID (uuid 中的類別):                  uuid --- RFC 4122 定义的UUID对象.
                                                             (line   41)
* uuid (模組):                           uuid --- RFC 4122 定义的UUID对象.
                                                             (line    6)
* uuid1:                                 uuid --- RFC 4122 定义的UUID对象.
                                                             (line  167)
* uuid1() (於 uuid 模組中):              uuid --- RFC 4122 定义的UUID对象.
                                                             (line  160)
* uuid3:                                 uuid --- RFC 4122 定义的UUID对象.
                                                             (line  172)
* uuid3() (於 uuid 模組中):              uuid --- RFC 4122 定义的UUID对象.
                                                             (line  167)
* uuid4:                                 uuid --- RFC 4122 定义的UUID对象.
                                                             (line  176)
* uuid4() (於 uuid 模組中):              uuid --- RFC 4122 定义的UUID对象.
                                                             (line  172)
* uuid5:                                 uuid --- RFC 4122 定义的UUID对象.
                                                             (line  181)
* uuid5() (於 uuid 模組中):              uuid --- RFC 4122 定义的UUID对象.
                                                             (line  176)
* UuidCreate() (於 msilib 模組中):       msilib --- Read and write Microsoft Installer files.
                                                             (line   39)
* v4_int_to_packed() (於 ipaddress 模組中): 其他模块级别函数.
                                                             (line    8)
* v6_int_to_packed() (於 ipaddress 模組中): 其他模块级别函数.
                                                             (line   19)
* validator() (於 wsgiref.validate 模組中): wsgiref validate --- WSGI 一致性检查器.
                                                             (line   17)
* valid_signals() (於 signal 模組中):    模块内容<5>.        (line  238)
* value (ctypes._SimpleCData 的屬性):    基础数据类型<2>.    (line   15)
* value (http.cookiejar.Cookie 的屬性):  Cookie 对象<2>.     (line   28)
* value (http.cookies.Morsel 的屬性):    Morsel 对象.        (line   48)
* value (xml.dom.Attr 的屬性):           Attr 对象.          (line   20)
* value of an object:                    对象、值与类型.     (line   10)
* Value() (multiprocessing.managers.SyncManager 的方法): 管理器.
                                                             (line  175)
* Value() (於 multiprocessing 模組中):   共享 ctypes 对象.   (line    8)
* Value() (於 multiprocessing.sharedctypes 模組中): multiprocessing sharedctypes 模块.
                                                             (line   57)
* ValueError:                            具体异常.           (line  344)
* valuerefs() (weakref.WeakValueDictionary 的方法): weakref --- 弱引用.
                                                             (line  153)
* values() (contextvars.Context 的方法): 手动上下文管理.     (line   95)
* values() (dict 的方法):                映射类型 --- dict.  (line  198)
* values() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  192)
* values() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  287)
* values() (mailbox.Mailbox 的方法):     Mailbox 对象.       (line   89)
* values() (types.MappingProxyType 的方法): 标准解释器类型.  (line  257)
* ValuesView (collections.abc 中的類別): 容器抽象基类.       (line  180)
* ValuesView (typing 中的類別):          collections abc 对应的容器.
                                                             (line  100)
* value_decode() (http.cookies.BaseCookie 的方法): Cookie 对象.
                                                             (line    6)
* value_encode() (http.cookies.BaseCookie 的方法): Cookie 对象.
                                                             (line   12)
* var (contextvars.Token 的屬性):        上下文变量.         (line   71)
* variable annotation（變數註釋）:       術語表.             (line 1143)
* variance (statistics.NormalDist 的屬性): NormalDist 对象.  (line   34)
* variance() (於 statistics 模組中):     函式細節.           (line  300)
* variant (uuid.UUID 的屬性):            uuid --- RFC 4122 定义的UUID对象.
                                                             (line  127)
* vars() (內建函式):                     內建函式.           (line 1468)
* vbar (tkinter.scrolledtext.ScrolledText 的屬性): tkinter scrolledtext --- 滚动文字控件.
                                                             (line   26)
* VBAR (於 token 模組中):                token --- 与Python解析树一起使用的常量.
                                                             (line   94)
* VBAREQUAL (於 token 模組中):           token --- 与Python解析树一起使用的常量.
                                                             (line  190)
* Vec2D (turtle 中的類別):               公共类.             (line   82)
* vectorcallfunc (C 型態):               Vectorcall 协议.    (line   29)
* venv (模組):                           venv --- 创建虚拟环境.
                                                             (line    6)
* VERBOSE (於 re 模組中):                模块内容.           (line   94)
* verbose (於 tabnanny 模組中):          tabnanny --- 模糊缩进检测.
                                                             (line   23)
* verbose (於 test.support 模組中):      test support --- Utilities for the Python test suite.
                                                             (line   30)
* verify() (smtplib.SMTP 的方法):        SMTP 对象.          (line   76)
* VerifyFlags (ssl 中的類別):            常量<3>.            (line  101)
* VerifyMode (ssl 中的類別):             常量<3>.            (line   56)
* verify_client_post_handshake() (ssl.SSLSocket 的方法): SSL 套接字.
                                                             (line  242)
* verify_code (ssl.SSLCertVerificationError 的屬性): 异常<12>.
                                                             (line   75)
* VERIFY_CRL_CHECK_CHAIN (於 ssl 模組中): 常量<3>.           (line   79)
* VERIFY_CRL_CHECK_LEAF (於 ssl 模組中): 常量<3>.            (line   69)
* VERIFY_DEFAULT (於 ssl 模組中):        常量<3>.            (line   62)
* verify_flags (ssl.SSLContext 的屬性):  SSL 上下文.         (line  562)
* verify_message (ssl.SSLCertVerificationError 的屬性): 异常<12>.
                                                             (line   79)
* verify_mode (ssl.SSLContext 的屬性):   SSL 上下文.         (line  576)
* verify_request() (socketserver.BaseServer 的方法): Server 对象<2>.
                                                             (line  151)
* VERIFY_X509_STRICT (於 ssl 模組中):    常量<3>.            (line   86)
* VERIFY_X509_TRUSTED_FIRST (於 ssl 模組中): 常量<3>.        (line   93)
* version (email.headerregistry.MIMEVersionHeader 的屬性): email headerregistry 自定义标头对象.
                                                             (line  195)
* version (http.client.HTTPResponse 的屬性): HTTPResponse 对象.
                                                             (line   42)
* version (http.cookiejar.Cookie 的屬性): Cookie 对象<2>.    (line   16)
* version (in module sys):               Process-wide parameters.
                                                             (line  164)
* version (in module sys) <1>:           Process-wide parameters.
                                                             (line  199)
* version (in module sys) <2>:           Process-wide parameters.
                                                             (line  210)
* version (ipaddress.IPv4Address 的屬性): 地址对象.          (line   45)
* version (ipaddress.IPv4Network 的屬性): 网络对象.          (line   51)
* version (ipaddress.IPv6Address 的屬性): 地址对象.          (line  195)
* version (ipaddress.IPv6Network 的屬性): 网络对象.          (line  259)
* version (urllib.request.URLopener 的屬性): 沿袭的接口.     (line  114)
* version (uuid.UUID 的屬性):            uuid --- RFC 4122 定义的UUID对象.
                                                             (line  133)
* version (於 curses 模組中):            常量<2>.            (line   18)
* version (於 marshal 模組中):           marshal --- 内部 Python 对象序列化.
                                                             (line   90)
* version (於 sqlite3 模組中):           模块函数和常量.     (line   22)
* version (於 sys 模組中):               sys --- 系统相关的参数和函数.
                                                             (line 1388)
* version() (ssl.SSLSocket 的方法):      SSL 套接字.         (line  260)
* version() (於 ensurepip 模組中):       Module API.         (line    8)
* version() (於 platform 模組中):        跨平台.             (line  117)
* version_info (於 sqlite3 模組中):      模块函数和常量.     (line   26)
* version_info (於 sys 模組中):          sys --- 系统相关的参数和函数.
                                                             (line 1400)
* version_string() (http.server.BaseHTTPRequestHandler 的方法): http server --- HTTP 服务器.
                                                             (line  258)
* vformat() (string.Formatter 的方法):   自定义字符串格式化. (line   22)
* virtual environment（虛擬環境）:       術語表.             (line 1162)
* virtual machine（虛擬機器）:           術語表.             (line 1170)
* VIRTUAL_ENV:                           创建虚拟环境.       (line  121)
* visit() (ast.NodeVisitor 的方法):      ast 中的辅助函数.   (line  159)
* visitproc (C 型態):                    使对象类型支持循环垃圾回收.
                                                             (line  111)
* vline() (curses.window 的方法):        Window 对象.        (line  502)
* voidcmd() (ftplib.FTP 的方法):         FTP 对象.           (line   60)
* volume (zipfile.ZipInfo 的屬性):       ZipInfo 对象.       (line  109)
* vonmisesvariate() (於 random 模組中):  实值分布.           (line   70)
* wait() (asyncio.asyncio.subprocess.Process 的方法): 与子进程交互.
                                                             (line   33)
* wait() (asyncio.Condition 的方法):     Condition.          (line   77)
* wait() (asyncio.Event 的方法):         Event.              (line   43)
* wait() (multiprocessing.pool.AsyncResult 的方法): 进程池.  (line  170)
* wait() (subprocess.Popen 的方法):      Popen 对象.         (line   13)
* wait() (threading.Barrier 的方法):     栅栏对象.           (line   38)
* wait() (threading.Condition 的方法):   条件对象.           (line   80)
* wait() (threading.Event 的方法):       事件对象.           (line   38)
* wait() (於 asyncio 模組中):            简单等待.           (line    6)
* wait() (於 concurrent.futures 模組中): 模块函数.           (line    6)
* wait() (於 multiprocessing.connection 模組中): 监听器及客户端.
                                                             (line   99)
* wait() (於 os 模組中):                 进程管理.           (line  619)
* wait3() (於 os 模組中):                进程管理.           (line  728)
* wait4() (於 os 模組中):                进程管理.           (line  741)
* waitid() (於 os 模組中):               进程管理.           (line  636)
* waitpid() (於 os 模組中):              进程管理.           (line  699)
* waitstatus_to_exitcode() (於 os 模組中): 进程管理.         (line  753)
* wait_closed() (asyncio.Server 的方法): Server 对象.        (line   88)
* wait_closed() (asyncio.StreamWriter 的方法): StreamWriter. (line   79)
* wait_for() (asyncio.Condition 的方法): Condition.          (line   88)
* wait_for() (threading.Condition 的方法): 条件对象.         (line  104)
* wait_for() (於 asyncio 模組中):        超时.               (line    6)
* wait_process() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  575)
* wait_threads_exit() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  590)
* walk() (email.message.EmailMessage 的方法): email message 表示一封电子邮件信息.
                                                             (line  391)
* walk() (email.message.Message 的方法): email message Message 使用 compat32 API 来表示电子邮件消息.
                                                             (line  533)
* walk() (於 ast 模組中):                ast 中的辅助函数.   (line  142)
* walk() (於 os 模組中):                 文件和目录.         (line 1300)
* walk_packages() (於 pkgutil 模組中):   pkgutil --- 包扩展工具.
                                                             (line  161)
* walk_stack() (於 traceback 模組中):    traceback --- 打印或检索堆栈回溯.
                                                             (line  154)
* walk_tb() (於 traceback 模組中):       traceback --- 打印或检索堆栈回溯.
                                                             (line  163)
* want (doctest.Example 的屬性):         Example 对象.       (line   20)
* warn() (distutils.ccompiler.CCompiler 的方法): distutils ccompiler --- CCompiler基类.
                                                             (line  505)
* warn() (distutils.text_file.TextFile 的方法): distutils text_file --- The TextFile class.
                                                             (line  101)
* warn() (於 warnings 模組中):           可用的函数.         (line    6)
* Warning:                               警告.               (line    8)
* Warning <1>:                           异常<4>.            (line    6)
* warning() (logging.Logger 的方法):     记录器对象.         (line  179)
* warning() (xml.sax.handler.ErrorHandler 的方法): ErrorHandler 对象.
                                                             (line   23)
* warning() (於 logging 模組中):         模块级函数.         (line  100)
* warnings:                              warnings —— 警告信息的控制.
                                                             (line    8)
* warnings (模組):                       warnings —— 警告信息的控制.
                                                             (line    6)
* WarningsRecorder (test.support 中的類別): test support --- Utilities for the Python test suite.
                                                             (line 1117)
* warnoptions (於 sys 模組中):           sys --- 系统相关的参数和函数.
                                                             (line 1411)
* warn_explicit() (於 warnings 模組中):  可用的函数.         (line   27)
* wasSuccessful() (unittest.TestResult 的方法): Loading and running tests.
                                                             (line  301)
* WatchedFileHandler (logging.handlers 中的類別): WatchedFileHandler.
                                                             (line   20)
* wave (模組):                           wave --- 读写WAV格式文件.
                                                             (line    6)
* WCONTINUED (於 os 模組中):             进程管理.           (line  791)
* WCOREDUMP() (於 os 模組中):            进程管理.           (line  809)
* WeakKeyDictionary (weakref 中的類別):  weakref --- 弱引用. (line  124)
* WeakMethod (weakref 中的類別):         weakref --- 弱引用. (line  162)
* weakref (模組):                        weakref --- 弱引用. (line    6)
* WeakSet (weakref 中的類別):            weakref --- 弱引用. (line  157)
* WeakValueDictionary (weakref 中的類別): weakref --- 弱引用.
                                                             (line  142)
* webbrowser (模組):                     webbrowser --- 方便的Web浏览器控制器.
                                                             (line    6)
* weekday() (datetime.date 的方法):      date 对象.          (line  186)
* weekday() (datetime.datetime 的方法):  datetime 对象.      (line  522)
* weekday() (於 calendar 模組中):        calendar --- 日历相关函数.
                                                             (line  273)
* weekheader() (於 calendar 模組中):     calendar --- 日历相关函数.
                                                             (line  278)
* weibullvariate() (於 random 模組中):   实值分布.           (line   80)
* WEXITED (於 os 模組中):                进程管理.           (line  672)
* WEXITSTATUS() (於 os 模組中):          进程管理.           (line  849)
* wfile (http.server.BaseHTTPRequestHandler 的屬性): http server --- HTTP 服务器.
                                                             (line  102)
* what() (於 imghdr 模組中):             imghdr --- 推测图像类型.
                                                             (line   14)
* what() (於 sndhdr 模組中):             sndhdr --- 推测声音文件的类型.
                                                             (line   21)
* whathdr() (於 sndhdr 模組中):          sndhdr --- 推测声音文件的类型.
                                                             (line   28)
* whatis (pdb command):                  调试器命令.         (line  205)
* when() (asyncio.TimerHandle 的方法):   回调处理.           (line   29)
* where (pdb command):                   调试器命令.         (line   41)
* which() (於 shutil 模組中):            目录和文件操作.     (line  314)
* whichdb() (於 dbm 模組中):             dbm --- Unix "数据库" 接口.
                                                             (line   21)
* While (ast 中的類別):                  Control flow.       (line   78)
* whitespace (shlex.shlex 的屬性):       shlex 对象.         (line   85)
* whitespace (於 string 模組中):         字符串常量.         (line   46)
* whitespace_split (shlex.shlex 的屬性): shlex 对象.         (line  105)
* Widget (tkinter.ttk 中的類別):         ttk Widget.         (line    9)
* width (textwrap.TextWrapper 的屬性):   textwrap --- 文本自动换行与填充.
                                                             (line  146)
* width() (於 turtle 模組中):            绘图状态.           (line   18)
* WIFCONTINUED() (於 os 模組中):         进程管理.           (line  817)
* WIFEXITED() (於 os 模組中):            进程管理.           (line  842)
* WIFSIGNALED() (於 os 模組中):          进程管理.           (line  836)
* WIFSTOPPED() (於 os 模組中):           进程管理.           (line  826)
* win32_edition() (於 platform 模組中):  Windows平台.        (line   17)
* win32_is_iot() (於 platform 模組中):   Windows平台.        (line   24)
* win32_ver() (於 platform 模組中):      Windows平台.        (line    6)
* WinDLL (ctypes 中的類別):              加载动态链接库.     (line   39)
* window manager (widgets):              窗口管理器.         (line    6)
* window() (curses.panel.Panel 的方法):  Panel 对象.         (line   57)
* Windows:                               完整的 Python 程序. (line   19)
* Windows ini file:                      configparser --- 配置文件解析器.
                                                             (line    8)
* WindowsError:                          具体异常.           (line  361)
* WindowsPath (pathlib 中的類別):        具体路径.           (line   29)
* WindowsProactorEventLoopPolicy (asyncio 中的類別): 策略对象.
                                                             (line   67)
* WindowsRegistryFinder (importlib.machinery 中的類別): importlib machinery —— 导入器和路径钩子函数。.
                                                             (line   79)
* WindowsSelectorEventLoopPolicy (asyncio 中的類別): 策略对象.
                                                             (line   60)
* window_height() (於 turtle 模組中):    设置与特殊方法.     (line   99)
* window_width() (於 turtle 模組中):     设置与特殊方法.     (line  106)
* winerror (OSError 的屬性):             具体异常.           (line  117)
* WinError() (於 ctypes 模組中):         工具函数.           (line  176)
* WINFUNCTYPE() (於 ctypes 模組中):      函数原型.           (line   20)
* winreg (模組):                         winreg --- Windows 注册表访问.
                                                             (line    6)
* WinSock:                               select --- 等待 I/O 完成.
                                                             (line  119)
* winsound (模組):                       winsound —— Windows 系统的声音播放接口.
                                                             (line    6)
* winver (於 sys 模組中):                sys --- 系统相关的参数和函数.
                                                             (line 1416)
* With (ast 中的類別):                   Control flow.       (line  210)
* withitem (ast 中的類別):               Control flow.       (line  221)
* WITH_EXCEPT_START (opcode):            Python字节码说明.   (line  367)
* with_hostmask (ipaddress.IPv4Interface 的屬性): 接口对象.  (line   48)
* with_hostmask (ipaddress.IPv4Network 的屬性): 网络对象.    (line  104)
* with_hostmask (ipaddress.IPv6Interface 的屬性): 接口对象.  (line   72)
* with_hostmask (ipaddress.IPv6Network 的屬性): 网络对象.    (line  291)
* with_name() (pathlib.PurePath 的方法): 方法和特征属性.     (line  268)
* with_netmask (ipaddress.IPv4Interface 的屬性): 接口对象.   (line   40)
* with_netmask (ipaddress.IPv4Network 的屬性): 网络对象.     (line  100)
* with_netmask (ipaddress.IPv6Interface 的屬性): 接口对象.   (line   70)
* with_netmask (ipaddress.IPv6Network 的屬性): 网络对象.     (line  289)
* with_prefixlen (ipaddress.IPv4Interface 的屬性): 接口对象. (line   32)
* with_prefixlen (ipaddress.IPv4Network 的屬性): 网络对象.   (line   89)
* with_prefixlen (ipaddress.IPv6Interface 的屬性): 接口对象. (line   68)
* with_prefixlen (ipaddress.IPv6Network 的屬性): 网络对象.   (line  283)
* with_pymalloc() (於 test.support 模組中): test support --- Utilities for the Python test suite.
                                                             (line  267)
* with_stem() (pathlib.PurePath 的方法): 方法和特征属性.     (line  284)
* with_suffix() (pathlib.PurePath 的方法): 方法和特征属性.   (line  307)
* with_traceback() (BaseException 的方法): 基类.             (line   20)
* WNOHANG (於 os 模組中):                进程管理.           (line  784)
* WNOWAIT (於 os 模組中):                进程管理.           (line  672)
* wordchars (shlex.shlex 的屬性):        shlex 对象.         (line   76)
* World Wide Web:                        互联网协议和支持.   (line    6)
* World Wide Web <1>:                    urllib parse 用于解析 URL.
                                                             (line    8)
* World Wide Web <2>:                    urllib robotparser --- robots txt 语法分析程序.
                                                             (line    8)
* wrap() (textwrap.TextWrapper 的方法):  textwrap --- 文本自动换行与填充.
                                                             (line  251)
* wrap() (於 textwrap 模組中):           textwrap --- 文本自动换行与填充.
                                                             (line   15)
* wrapper() (於 curses 模組中):          函数<4>.            (line  493)
* WrapperDescriptorType (於 types 模組中): 标准解释器类型.   (line   77)
* wraps() (於 functools 模組中):         functools --- 高阶函数和可调用对象上的操作.
                                                             (line  546)
* wrap_bio() (ssl.SSLContext 的方法):    SSL 上下文.         (line  395)
* wrap_future() (於 asyncio 模組中):     Future 函数.        (line   43)
* wrap_socket() (ssl.SSLContext 的方法): SSL 上下文.         (line  343)
* wrap_socket() (於 ssl 模組中):         证书处理.           (line  146)
* wrap_text() (於 distutils.fancy_getopt 模組中): distutils fancy_getopt --- Wrapper around the standard getopt module.
                                                             (line   32)
* WRITABLE (於 tkinter 模組中):          File Handlers.      (line   41)
* writable() (asyncore.dispatcher 的方法): asyncore --- 异步套接字处理器.
                                                             (line  140)
* writable() (io.IOBase 的方法):         I/O 基类.           (line  129)
* write() (asyncio.StreamWriter 的方法): StreamWriter.       (line   13)
* write() (asyncio.WriteTransport 的方法): 只写传输.         (line   53)
* write() (code.InteractiveInterpreter 的方法): 交互解释器对象.
                                                             (line   52)
* write() (codecs.StreamWriter 的方法):  StreamWriter 对象.  (line   27)
* write() (configparser.ConfigParser 的方法): ConfigParser 对象.
                                                             (line  225)
* write() (email.generator.BytesGenerator 的方法): email generator 生成 MIME 文档.
                                                             (line   97)
* write() (email.generator.Generator 的方法): email generator 生成 MIME 文档.
                                                             (line  178)
* write() (io.BufferedIOBase 的方法):    I/O 基类.           (line  276)
* write() (io.BufferedWriter 的方法):    缓冲流.             (line  112)
* write() (io.RawIOBase 的方法):         I/O 基类.           (line  180)
* write() (io.TextIOBase 的方法):        文本 I/O<2>.        (line   83)
* write() (mmap.mmap 的方法):            mmap --- 内存映射文件支持.
                                                             (line  241)
* write() (ossaudiodev.oss_audio_device 的方法): 音频设备对象.
                                                             (line   34)
* write() (ssl.MemoryBIO 的方法):        内存 BIO 支持<2>.   (line  135)
* write() (ssl.SSLSocket 的方法):        SSL 套接字.         (line   83)
* write() (telnetlib.Telnet 的方法):     Telnet 对象.        (line   93)
* write() (xml.etree.ElementTree.ElementTree 的方法): ElementTree 对象.
                                                             (line   53)
* write() (zipfile.ZipFile 的方法):      ZipFile 对象.       (line  213)
* write() (於 os 模組中):                文件描述符操作.     (line  609)
* write() (於 turtle 模組中):            更多绘图控制.       (line   27)
* writeall() (ossaudiodev.oss_audio_device 的方法): 音频设备对象.
                                                             (line   43)
* writeframes() (aifc.aifc 的方法):      aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line  162)
* writeframes() (sunau.AU_write 的方法): AU_write 对象.      (line   46)
* writeframes() (wave.Wave_write 的方法): Wave_write 对象.   (line   64)
* writeframesraw() (aifc.aifc 的方法):   aifc --- 读写 AIFF 和 AIFC 文件.
                                                             (line  168)
* writeframesraw() (sunau.AU_write 的方法): AU_write 对象.   (line   40)
* writeframesraw() (wave.Wave_write 的方法): Wave_write 对象.
                                                             (line   58)
* writeheader() (csv.DictWriter 的方法): Writer 对象.        (line   33)
* writelines() (asyncio.StreamWriter 的方法): StreamWriter.  (line   23)
* writelines() (asyncio.WriteTransport 的方法): 只写传输.    (line   59)
* writelines() (codecs.StreamWriter 的方法): StreamWriter 对象.
                                                             (line   31)
* writelines() (io.IOBase 的方法):       I/O 基类.           (line  134)
* writepy() (zipfile.PyZipFile 的方法):  PyZipFile 对象.     (line   18)
* writer (formatter.formatter 的屬性):   The Formatter Interface.
                                                             (line   22)
* writer() (於 csv 模組中):              模块内容<3>.        (line   34)
* writerow() (csv.csvwriter 的方法):     Writer 对象.        (line   13)
* writerows() (csv.csvwriter 的方法):    Writer 对象.        (line   20)
* writestr() (zipfile.ZipFile 的方法):   ZipFile 对象.       (line  235)
* WriteTransport (asyncio 中的類別):     传输层级.           (line   10)
* writev() (於 os 模組中):               文件描述符操作.     (line  625)
* writexml() (xml.dom.minidom.Node 的方法): DOM 对象.        (line   23)
* write_byte() (mmap.mmap 的方法):       mmap --- 内存映射文件支持.
                                                             (line  253)
* write_bytes() (pathlib.Path 的方法):   方法<2>.            (line  431)
* write_docstringdict() (於 turtle 模組中): 文档字符串翻译为不同的语言.
                                                             (line    9)
* write_eof() (asyncio.StreamWriter 的方法): StreamWriter.   (line   48)
* write_eof() (asyncio.WriteTransport 的方法): 只写传输.     (line   65)
* write_eof() (ssl.MemoryBIO 的方法):    内存 BIO 支持<2>.   (line  142)
* write_file() (於 distutils.file_util 模組中): distutils file_util --- Single file operations.
                                                             (line   43)
* write_history_file() (於 readline 模組中): 历史文件.       (line   13)
* WRITE_RESTRICTED:                      泛型属性管理.       (line   87)
* write_results() (trace.CoverageResults 的方法): 编程接口.  (line   48)
* write_text() (pathlib.Path 的方法):    方法<2>.            (line  445)
* write_through (io.TextIOWrapper 的屬性): 文本 I/O<2>.      (line  144)
* writing; values:                       表达式语句.         (line   15)
* WrongDocumentErr:                      异常<15>.           (line   80)
* wsgiref (模組):                        wsgiref --- WSGI 工具和引用的实现.
                                                             (line    6)
* wsgiref.handlers (模組):               wsgiref handlers -- 服务器/网关基类.
                                                             (line    6)
* wsgiref.headers (模組):                wsgiref headers -- WSGI 响应标头工具.
                                                             (line    6)
* wsgiref.simple_server (模組):          wsgiref simple_server -- 一个简单的 WSGI HTTP 服务器.
                                                             (line    6)
* wsgiref.util (模組):                   wsgiref util -- WSGI 环境工具.
                                                             (line    6)
* wsgiref.validate (模組):               wsgiref validate --- WSGI 一致性检查器.
                                                             (line    6)
* WSGIRequestHandler (wsgiref.simple_server 中的類別): wsgiref simple_server -- 一个简单的 WSGI HTTP 服务器.
                                                             (line   68)
* WSGIServer (wsgiref.simple_server 中的類別): wsgiref simple_server -- 一个简单的 WSGI HTTP 服务器.
                                                             (line   41)
* wsgi_file_wrapper (wsgiref.handlers.BaseHandler 的屬性): wsgiref handlers -- 服务器/网关基类.
                                                             (line  222)
* wsgi_multiprocess (wsgiref.handlers.BaseHandler 的屬性): wsgiref handlers -- 服务器/网关基类.
                                                             (line  126)
* wsgi_multithread (wsgiref.handlers.BaseHandler 的屬性): wsgiref handlers -- 服务器/网关基类.
                                                             (line  120)
* wsgi_run_once (wsgiref.handlers.BaseHandler 的屬性): wsgiref handlers -- 服务器/网关基类.
                                                             (line  132)
* wShowWindow (subprocess.STARTUPINFO 的屬性): Windows Popen 助手.
                                                             (line   44)
* WSTOPPED (於 os 模組中):               进程管理.           (line  672)
* WSTOPSIG() (於 os 模組中):             进程管理.           (line  857)
* wstring_at() (於 ctypes 模組中):       工具函数.           (line  185)
* ws_comma (2to3 fixer):                 修复器.             (line  310)
* WTERMSIG() (於 os 模組中):             进程管理.           (line  865)
* WUNTRACED (於 os 模組中):              进程管理.           (line  798)
* WWW:                                   互联网协议和支持.   (line    6)
* WWW <1>:                               urllib parse 用于解析 URL.
                                                             (line    8)
* WWW <2>:                               urllib robotparser --- robots txt 语法分析程序.
                                                             (line    8)
* WWW; server:                           cgi --- 通用网关接口支持.
                                                             (line    8)
* WWW; server <1>:                       http server --- HTTP 服务器.
                                                             (line    8)
* W_OK (於 os 模組中):                   文件和目录.         (line   89)
* X (於 re 模組中):                      模块内容.           (line   94)
* X509 certificate:                      SSL 上下文.         (line  587)
* xatom() (imaplib.IMAP4 的方法):        IMAP4 对象.         (line  346)
* XATTR_CREATE (於 os 模組中):           Linux 扩展属性.     (line   80)
* XATTR_REPLACE (於 os 模組中):          Linux 扩展属性.     (line   85)
* XATTR_SIZE_MAX (於 os 模組中):         Linux 扩展属性.     (line   76)
* xcor() (於 turtle 模組中):             获取海龟的状态.     (line   31)
* XDR:                                   xdrlib --- 编码与解码 XDR 数据.
                                                             (line    8)
* xdrlib (模組):                         xdrlib --- 编码与解码 XDR 数据.
                                                             (line    6)
* xhdr() (nntplib.NNTP 的方法):          方法<3>.            (line  284)
* XHTML:                                 html parser --- 简单的 HTML 和 XHTML 解析器.
                                                             (line    8)
* XHTML_NAMESPACE (於 xml.dom 模組中):   模块内容<6>.        (line   45)
* xml (模組):                            XML 處理模組.       (line    6)
* XML() (於 xml.etree.ElementTree 模組中): 函数<7>.          (line  226)
* xml.dom (模組):                        xml dom --- 文档对象模型 API.
                                                             (line    6)
* xml.dom.minidom (模組):                xml dom minidom --- 最小化的 DOM 实现.
                                                             (line    6)
* xml.dom.pulldom (模組):                xml dom pulldom --- 支持构建部分 DOM 树.
                                                             (line    6)
* xml.etree.ElementInclude.default_loader() (於 xml.etree.ElementTree 模組中): 函数<8>.
                                                             (line    6)
* xml.etree.ElementInclude.include() (於 xml.etree.ElementTree 模組中): 函数<8>.
                                                             (line   16)
* xml.etree.ElementTree (模組):          xml etree ElementTree --- ElementTree XML API.
                                                             (line    6)
* xml.parsers.expat (模組):              xml parsers expat --- 使用 Expat 的快速 XML 解析.
                                                             (line    6)
* xml.parsers.expat.errors (模組):       Expat 错误常量.     (line    6)
* xml.parsers.expat.model (模組):        内容模型描述.       (line    6)
* xml.sax (模組):                        xml sax --- 支持 SAX2 解析器.
                                                             (line    6)
* xml.sax.handler (模組):                xml sax handler --- SAX 处理句柄的基类.
                                                             (line    6)
* xml.sax.saxutils (模組):               xml sax saxutils --- SAX 工具集.
                                                             (line    6)
* xml.sax.xmlreader (模組):              xml sax xmlreader --- 用于 XML 解析器的接口.
                                                             (line    6)
* xmlcharrefreplace_errors() (於 codecs 模組中): 错误处理方案.
                                                             (line  121)
* XmlDeclHandler() (xml.parsers.expat.xmlparser 的方法): XMLParser对象<2>.
                                                             (line  146)
* XMLFilterBase (xml.sax.saxutils 中的類別): xml sax saxutils --- SAX 工具集.
                                                             (line   57)
* XMLGenerator (xml.sax.saxutils 中的類別): xml sax saxutils --- SAX 工具集.
                                                             (line   44)
* XMLID() (於 xml.etree.ElementTree 模組中): 函数<7>.        (line  233)
* XMLNS_NAMESPACE (於 xml.dom 模組中):   模块内容<6>.        (line   40)
* XMLParser (xml.etree.ElementTree 中的類別): XMLParser对象. (line    6)
* XMLParserType (於 xml.parsers.expat 模組中): xml parsers expat --- 使用 Expat 的快速 XML 解析.
                                                             (line   31)
* XMLPullParser (xml.etree.ElementTree 中的類別): XMLPullParser对象.
                                                             (line    6)
* XMLReader (xml.sax.xmlreader 中的類別): xml sax xmlreader --- 用于 XML 解析器的接口.
                                                             (line   14)
* xmlrpc.client (模組):                  xmlrpc client --- XML-RPC 客户端访问.
                                                             (line    6)
* xmlrpc.server (模組):                  xmlrpc server --- 基本 XML-RPC 服务器.
                                                             (line    6)
* XML_ERROR_ABORTED (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line  161)
* XML_ERROR_ASYNC_ENTITY (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line   26)
* XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line   28)
* XML_ERROR_BAD_CHAR_REF (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line   33)
* XML_ERROR_BINARY_ENTITY_REF (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line   37)
* XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line  122)
* XML_ERROR_DUPLICATE_ATTRIBUTE (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line   41)
* XML_ERROR_ENTITY_DECLARED_IN_PE (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line  114)
* XML_ERROR_EXTERNAL_ENTITY_HANDLING (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line  105)
* XML_ERROR_FEATURE_REQUIRES_XML_DTD (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line  116)
* XML_ERROR_FINISHED (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line  165)
* XML_ERROR_INCOMPLETE_PE (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line  136)
* XML_ERROR_INCORRECT_ENCODING (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line   45)
* XML_ERROR_INVALID_TOKEN (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line   47)
* XML_ERROR_JUNK_AFTER_DOC_ELEMENT (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line   52)
* XML_ERROR_MISPLACED_XML_PI (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line   56)
* XML_ERROR_NOT_STANDALONE (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line  107)
* XML_ERROR_NOT_SUSPENDED (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line  157)
* XML_ERROR_NO_ELEMENTS (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line   60)
* XML_ERROR_NO_MEMORY (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line   64)
* XML_ERROR_PARAM_ENTITY_REF (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line   68)
* XML_ERROR_PARTIAL_CHAR (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line   72)
* XML_ERROR_PUBLICID (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line  148)
* XML_ERROR_RECURSIVE_ENTITY_REF (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line   76)
* XML_ERROR_SUSPENDED (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line  152)
* XML_ERROR_SUSPEND_PE (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line  170)
* XML_ERROR_SYNTAX (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line   81)
* XML_ERROR_TAG_MISMATCH (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line   85)
* XML_ERROR_TEXT_DECL (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line  144)
* XML_ERROR_UNBOUND_PREFIX (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line  128)
* XML_ERROR_UNCLOSED_CDATA_SECTION (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line  101)
* XML_ERROR_UNCLOSED_TOKEN (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line   89)
* XML_ERROR_UNDECLARING_PREFIX (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line  132)
* XML_ERROR_UNDEFINED_ENTITY (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line   93)
* XML_ERROR_UNEXPECTED_STATE (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line  112)
* XML_ERROR_UNKNOWN_ENCODING (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line   97)
* XML_ERROR_XML_DECL (於 xml.parsers.expat.errors 模組中): Expat 错误常量.
                                                             (line  140)
* XML_NAMESPACE (於 xml.dom 模組中):     模块内容<6>.        (line   35)
* xor() (於 operator 模組中):            operator --- 标准运算符替代函数.
                                                             (line  151)
* xover() (nntplib.NNTP 的方法):         方法<3>.            (line  296)
* xrange (2to3 fixer):                   修复器.             (line  314)
* xreadlines (2to3 fixer):               修复器.             (line  319)
* xview() (tkinter.ttk.Treeview 的方法): ttk Treeview.       (line  286)
* X_OK (於 os 模組中):                   文件和目录.         (line   89)
* ycor() (於 turtle 模組中):             获取海龟的状态.     (line   43)
* year (datetime.date 的屬性):           date 对象.          (line   94)
* year (datetime.datetime 的屬性):       datetime 对象.      (line  243)
* Year 2038:                             time --- 时间的访问和转换.
                                                             (line   25)
* yeardatescalendar() (calendar.Calendar 的方法): calendar --- 日历相关函数.
                                                             (line   87)
* yeardays2calendar() (calendar.Calendar 的方法): calendar --- 日历相关函数.
                                                             (line   94)
* yeardayscalendar() (calendar.Calendar 的方法): calendar --- 日历相关函数.
                                                             (line  100)
* YESEXPR (於 locale 模組中):            locale --- 国际化服务.
                                                             (line  200)
* Yield (ast 中的類別):                  Function and class definitions.
                                                             (line  128)
* yield; examples:                       生成器-迭代器的方法.
                                                             (line   46)
* yield; expression:                     yield 表达式.       (line    6)
* yield; yield from (in What’s New):     PEP 3151 重写 OS 和 IO 异常的层次结构.
                                                             (line   87)
* YieldFrom (ast 中的類別):              Function and class definitions.
                                                             (line  128)
* YIELD_FROM (opcode):                   Python字节码说明.   (line  331)
* YIELD_VALUE (opcode):                  Python字节码说明.   (line  327)
* yiq_to_rgb() (於 colorsys 模組中):     colorsys --- 颜色系统间的转换.
                                                             (line   28)
* yview() (tkinter.ttk.Treeview 的方法): ttk Treeview.       (line  290)
* Zen of Python（Python 之禪）:          術語表.             (line 1175)
* ZeroDivisionError:                     具体异常.           (line  349)
* zfill() (bytearray 的方法):            bytes 和 bytearray 操作.
                                                             (line  645)
* zfill() (bytes 的方法):                bytes 和 bytearray 操作.
                                                             (line  645)
* zfill() (str 的方法):                  字符串的方法<2>.    (line  578)
* zip (2to3 fixer):                      修复器.             (line  323)
* zip() (內建函式):                      內建函式.           (line 1485)
* zipapp (模組):                         zipapp —— 管理可执行的 Python zip 打包文件.
                                                             (line    6)
* zipapp command line option; -c:        命令執行列介面<2>.  (line   40)
* zipapp command line option; –compress: 命令執行列介面<2>.  (line   40)
* zipapp command line option; -h:        命令執行列介面<2>.  (line   54)
* zipapp command line option; –help:     命令執行列介面<2>.  (line   54)
* zipapp command line option; –info:     命令執行列介面<2>.  (line   49)
* zipapp command line option; -m <mainfn>: 命令執行列介面<2>.
                                                             (line   31)
* zipapp command line option; –main=<mainfn>: 命令執行列介面<2>.
                                                             (line   31)
* zipapp command line option; -o <output>: 命令執行列介面<2>.
                                                             (line   16)
* zipapp command line option; –output=<output>: 命令執行列介面<2>.
                                                             (line   16)
* zipapp command line option; -p <interpreter>: 命令執行列介面<2>.
                                                             (line   25)
* zipapp command line option; –python=<interpreter>: 命令執行列介面<2>.
                                                             (line   25)
* ZipFile (zipfile 中的類別):            ZipFile 对象.       (line    6)
* zipfile (模組):                        zipfile --- 使用ZIP存档.
                                                             (line    6)
* zipfile command line option; -c <zipfile> <source1> ... <sourceN>: 命令行选项<2>.
                                                             (line   11)
* zipfile command line option; –create <zipfile> <source1> ... <sourceN>: 命令行选项<2>.
                                                             (line   11)
* zipfile command line option; -e <zipfile> <output_dir>: 命令行选项<2>.
                                                             (line   16)
* zipfile command line option; –extract <zipfile> <output_dir>: 命令行选项<2>.
                                                             (line   16)
* zipfile command line option; -l <zipfile>: 命令行选项<2>.  (line    6)
* zipfile command line option; –list <zipfile>: 命令行选项<2>.
                                                             (line    6)
* zipfile command line option; -t <zipfile>: 命令行选项<2>.  (line   21)
* zipfile command line option; –test <zipfile>: 命令行选项<2>.
                                                             (line   21)
* zipimport (模組):                      zipimport --- 从 Zip 存档中导入模块.
                                                             (line    6)
* zipimporter (zipimport 中的類別):      zipimporter 对象.   (line    8)
* ZipImportError:                        zipimport --- 从 Zip 存档中导入模块.
                                                             (line   48)
* ZipInfo (zipfile 中的類別):            zipfile --- 使用ZIP存档.
                                                             (line   52)
* ZIP_BZIP2 (於 zipfile 模組中):         zipfile --- 使用ZIP存档.
                                                             (line   78)
* ZIP_DEFLATED (於 zipfile 模組中):      zipfile --- 使用ZIP存档.
                                                             (line   74)
* zip_longest() (於 itertools 模組中):   Itertool函数.       (line  530)
* ZIP_LZMA (於 zipfile 模組中):          zipfile --- 使用ZIP存档.
                                                             (line   84)
* ZIP_STORED (於 zipfile 模組中):        zipfile --- 使用ZIP存档.
                                                             (line   70)
* zlib (模組):                           zlib --- 与 gzip 兼容的压缩.
                                                             (line    6)
* ZLIB_RUNTIME_VERSION (於 zlib 模組中): zlib --- 与 gzip 兼容的压缩.
                                                             (line  237)
* ZLIB_VERSION (於 zlib 模組中):         zlib --- 与 gzip 兼容的压缩.
                                                             (line  231)
* ZoneInfo (zoneinfo 中的類別):          ZoneInfo 类.        (line    6)
* zoneinfo (模組):                       zoneinfo --- IANA 时区支持.
                                                             (line    6)
* ZoneInfoNotFoundError:                 异常与警告.         (line    6)
* zscore() (statistics.NormalDist 的方法): NormalDist 对象.  (line   94)
* 例外; AssertionError:                  assert 语句.        (line   20)
* 例外; AttributeError:                  属性引用.           (line   10)
* 例外; GeneratorExit:                   生成器-迭代器的方法.
                                                             (line   38)
* 例外; GeneratorExit <1>:               异步生成器-迭代器方法.
                                                             (line   42)
* 例外; ImportError:                     import 语句.        (line    6)
* 例外; NameError:                       标识符（名称）.     (line    9)
* 例外; StopAsyncIteration:              异步生成器-迭代器方法.
                                                             (line    9)
* 例外; StopIteration:                   生成器-迭代器的方法.
                                                             (line   11)
* 例外; StopIteration <1>:               yield 语句.         (line    6)
* 例外; TypeError:                       一元算术和位运算.   (line   20)
* 例外; ValueError:                      移位运算.           (line   16)
* 例外; ZeroDivisionError:               二元算术运算符.     (line   28)
* 內建函式; abs:                         模拟数字类型.       (line  100)
* 內建函式; abs <1>:                     数字协议.           (line   71)
* 內建函式; ascii:                       对象协议.           (line  149)
* 內建函式; bytes:                       基本定制.           (line  120)
* 內建函式; bytes <1>:                   对象协议.           (line  167)
* 內建函式; chr:                         标准类型层级结构.   (line  122)
* 內建函式; classmethod:                 Implementing functions and methods.
                                                             (line  184)
* 內建函式; compile:                     global 语句.        (line   23)
* 內建函式; compile <1>:                 代码对象.           (line    6)
* 內建函式; compile <2>:                 标准解释器类型.     (line   46)
* 內建函式; compile <3>:                 Queries on ST Objects.
                                                             (line   14)
* 內建函式; compile <4>:                 匯入模組<2>.        (line  117)
* 內建函式; complex:                     模拟数字类型.       (line  106)
* 內建函式; complex <1>:                 数字类型 --- int float complex.
                                                             (line   20)
* 內建函式; divmod:                      模拟数字类型.       (line   24)
* 內建函式; divmod <1>:                  模拟数字类型.       (line   51)
* 內建函式; divmod <2>:                  数字协议.           (line   47)
* 內建函式; eval:                        global 语句.        (line   23)
* 內建函式; eval <1>:                    表达式输入.         (line    6)
* 內建函式; eval <2>:                    代码对象.           (line   14)
* 內建函式; eval <3>:                    pprint --- 数据美化输出.
                                                             (line  117)
* 內建函式; eval <4>:                    PrettyPrinter 对象. (line   22)
* 內建函式; eval <5>:                    转换 ST 对象.       (line   45)
* 內建函式; exec:                        global 语句.        (line   23)
* 內建函式; exec <1>:                    內建函式.           (line  437)
* 內建函式; exec <2>:                    代码对象.           (line   14)
* 內建函式; exec <3>:                    转换 ST 对象.       (line   45)
* 內建函式; float:                       模拟数字类型.       (line  106)
* 內建函式; float <1>:                   数字类型 --- int float complex.
                                                             (line   20)
* 內建函式; float <2>:                   数字协议.           (line  192)
* 內建函式; hash:                        基本定制.           (line  181)
* 內建函式; hash <1>:                    不可变序列类型.     (line    6)
* 內建函式; hash <2>:                    对象协议.           (line  211)
* 內建函式; hash <3>:                    PyTypeObject Slots. (line  309)
* 內建函式; help:                        作業系統介面.       (line   18)
* 內建函式; id:                          对象、值与类型.     (line   10)
* 內建函式; int:                         模拟数字类型.       (line  106)
* 內建函式; int <1>:                     数字类型 --- int float complex.
                                                             (line   20)
* 內建函式; int <2>:                     数字协议.           (line  186)
* 內建函式; len:                         标准类型层级结构.   (line   98)
* 內建函式; len <1>:                     标准类型层级结构.   (line  174)
* 內建函式; len <2>:                     标准类型层级结构.   (line  198)
* 內建函式; len <3>:                     模拟容器类型.       (line   40)
* 內建函式; len <4>:                     通用序列操作.       (line   17)
* 內建函式; len <5>:                     映射类型 --- dict.  (line    6)
* 內建函式; len <6>:                     对象协议.           (line  250)
* 內建函式; len <7>:                     序列协议.           (line   16)
* 內建函式; len <8>:                     映射协议.           (line   18)
* 內建函式; len <9>:                     List（串列）物件.   (line   36)
* 內建函式; len <10>:                    字典物件.           (line  123)
* 內建函式; len <11>:                    集合对象.           (line   82)
* 內建函式; max:                         通用序列操作.       (line   17)
* 內建函式; min:                         通用序列操作.       (line   17)
* 內建函式; open:                        讀寫檔案.           (line    6)
* 內建函式; open <1>:                    标准类型层级结构.   (line  492)
* 內建函式; ord:                         标准类型层级结构.   (line  122)
* 內建函式; pow:                         模拟数字类型.       (line   24)
* 內建函式; pow <1>:                     模拟数字类型.       (line   24)
* 內建函式; pow <2>:                     模拟数字类型.       (line   51)
* 內建函式; pow <3>:                     模拟数字类型.       (line   59)
* 內建函式; pow <4>:                     数字协议.           (line   55)
* 內建函式; pow <5>:                     数字协议.           (line  150)
* 內建函式; print:                       基本定制.           (line  123)
* 內建函式; range:                       for 语句.           (line   33)
* 內建函式; repr:                        表达式语句.         (line   15)
* 內建函式; repr <1>:                    终结和内存释放.     (line   81)
* 內建函式; repr <2>:                    对象协议.           (line  139)
* 內建函式; repr <3>:                    PyTypeObject Slots. (line  250)
* 內建函式; round:                       模拟数字类型.       (line  126)
* 內建函式; slice:                       标准类型层级结构.   (line  620)
* 內建函式; slice <1>:                   Python字节码说明.   (line  729)
* 內建函式; staticmethod:                Implementing functions and methods.
                                                             (line  191)
* 內建函式; tuple:                       序列协议.           (line  102)
* 內建函式; tuple <1>:                   List（串列）物件.   (line  113)
* 內建函式; type:                        对象、值与类型.     (line   10)
* 內建函式; type <1>:                    元类.               (line    6)
* 內建函式; type <2>:                    类型对象.           (line    6)
* 內建函式; type <3>:                    对象协议.           (line  234)
* 內建函式; __import__:                  匯入模組<2>.        (line   37)
* 模組; array:                           标准类型层级结构.   (line  169)
* 模組; array <1>:                       二进制序列类型 --- bytes bytearray memoryview.
                                                             (line    6)
* 模組; base64:                          binascii --- 二进制和 ASCII 码互转.
                                                             (line    6)
* 模組; bdb:                             pdb --- Python 的调试器.
                                                             (line   15)
* 模組; binhex:                          binascii --- 二进制和 ASCII 码互转.
                                                             (line    6)
* 模組; builtins:                        dir 函式.           (line   45)
* 模組; builtins <1>:                    完整的 Python 程序. (line    6)
* 模組; builtins <2>:                    嵌入式Python.       (line   12)
* 模組; builtins <3>:                    Initializing and finalizing the interpreter.
                                                             (line    8)
* 模組; builtins <4>:                    Sub-interpreter support.
                                                             (line   26)
* 模組; cmd:                             pdb --- Python 的调试器.
                                                             (line   15)
* 模組; copy:                            copyreg --- 注册配合 pickle 模块使用的函数.
                                                             (line    8)
* 模組; crypt:                           pwd --- 用户密码数据库.
                                                             (line   41)
* 模組; dbm.gnu:                         标准类型层级结构.   (line  220)
* 模組; dbm.gnu <1>:                     限制.               (line    6)
* 模組; dbm.ndbm:                        标准类型层级结构.   (line  220)
* 模組; dbm.ndbm <1>:                    限制.               (line    6)
* 模組; errno:                           具体异常.           (line  100)
* 模組; glob:                            fnmatch --- Unix 文件名模式匹配.
                                                             (line   33)
* 模組; imp:                             內建函式.           (line 1531)
* 模組; io:                              标准类型层级结构.   (line  492)
* 模組; json:                            使用 json 儲存結構化資料.
                                                             (line    6)
* 模組; math:                            数字类型 --- int float complex.
                                                             (line   92)
* 模組; math <1>:                        常数<2>.            (line   44)
* 模組; os:                              posix --- 最常见的 POSIX 系统调用.
                                                             (line   11)
* 模組; pickle:                          copy --- 浅层 shallow 和深层 deep 复制操作.
                                                             (line   59)
* 模組; pickle <1>:                      copyreg --- 注册配合 pickle 模块使用的函数.
                                                             (line    8)
* 模組; pickle <2>:                      shelve --- Python 对象持久化.
                                                             (line    8)
* 模組; pickle <3>:                      marshal --- 内部 Python 对象序列化.
                                                             (line   13)
* 模組; pty:                             文件描述符操作.     (line  318)
* 模組; pwd:                             os path --- 常用路径操作.
                                                             (line  124)
* 模組; pyexpat:                         xml parsers expat --- 使用 Expat 的快速 XML 解析.
                                                             (line   17)
* 模組; re:                              字符串的方法<2>.    (line    6)
* 模組; re <1>:                          fnmatch --- Unix 文件名模式匹配.
                                                             (line    8)
* 模組; shelve:                          marshal --- 内部 Python 对象序列化.
                                                             (line   13)
* 模組; signal:                          _thread --- 底层多线程 API.
                                                             (line  141)
* 模組; signal <1>:                      信号处理<2>.        (line    8)
* 模組; sitecustomize:                   site —— 指定域的配置钩子.
                                                             (line   79)
* 模組; socket:                          互联网协议和支持.   (line    6)
* 模組; stat:                            文件和目录.         (line  874)
* 模組; string:                          locale --- 国际化服务.
                                                             (line  379)
* 模組; struct:                          套接字对象.         (line  460)
* 模組; sys:                             標準模組.           (line    6)
* 模組; sys <1>:                         try 语句.           (line   56)
* 模組; sys <2>:                         完整的 Python 程序. (line    6)
* 模組; sys <3>:                         內建函式.           (line 1030)
* 模組; sys <4>:                         嵌入式Python.       (line   12)
* 模組; sys <5>:                         Initializing and finalizing the interpreter.
                                                             (line    8)
* 模組; sys <6>:                         Sub-interpreter support.
                                                             (line   26)
* 模組; types:                           类型对象.           (line    6)
* 模組; urllib.request:                  http client --- HTTP 协议客户端.
                                                             (line    8)
* 模組; usercustomize:                   site —— 指定域的配置钩子.
                                                             (line   87)
* 模組; uu:                              binascii --- 二进制和 ASCII 码互转.
                                                             (line    6)
* 模組; _locale:                         locale --- 国际化服务.
                                                             (line   14)
* 模組; _thread:                         高阶 API.           (line   44)
* 模組; __main__:                        名称的解析.         (line   43)
* 模組; __main__ <1>:                    完整的 Python 程序. (line    6)
* 模組; __main__ <2>:                    完整的 Python 程序. (line   15)
* 模組; __main__ <3>:                    runpy ——查找并执行 Python 模块.
                                                             (line   26)
* 模組; __main__ <4>:                    runpy ——查找并执行 Python 模块.
                                                             (line   78)
* 模組; __main__ <5>:                    嵌入式Python.       (line   12)
* 模組; __main__ <6>:                    Initializing and finalizing the interpreter.
                                                             (line    8)
* 模組; __main__ <7>:                    Sub-interpreter support.
                                                             (line   26)
* 物件; asynchronous-generator:          异步生成器函数.     (line   41)
* 物件; Boolean:                         标准类型层级结构.   (line   74)
* 物件; Boolean <1>:                     数字类型 --- int float complex.
                                                             (line    6)
* 物件; built-in function:               标准类型层级结构.   (line  376)
* 物件; built-in function <1>:           调用.               (line  105)
* 物件; built-in method:                 标准类型层级结构.   (line  386)
* 物件; built-in method <1>:             调用.               (line  105)
* 物件; bytearray:                       可变序列类型.       (line    6)
* 物件; bytearray <1>:                   二进制序列类型 --- bytes bytearray memoryview.
                                                             (line    6)
* 物件; bytearray <2>:                   bytearray 对象.     (line    6)
* 物件; bytearray <3>:                   字节数组对象.       (line    6)
* 物件; bytes:                           二进制序列类型 --- bytes bytearray memoryview.
                                                             (line    6)
* 物件; bytes <1>:                       bytes 对象.         (line    6)
* 物件; bytes <2>:                       字节对象.           (line    9)
* 物件; callable:                        标准类型层级结构.   (line  229)
* 物件; callable <1>:                    切片.               (line   30)
* 物件; Capsule:                         Capsule 对象.       (line    6)
* 物件; class:                           标准类型层级结构.   (line  444)
* 物件; class <1>:                       调用.               (line  110)
* 物件; class <2>:                       类定义.             (line    6)
* 物件; class instance:                  标准类型层级结构.   (line  444)
* 物件; class instance <1>:              标准类型层级结构.   (line  463)
* 物件; class instance <2>:              调用.               (line  114)
* 物件; complex:                         标准类型层级结构.   (line   92)
* 物件; complex number:                  数字类型 --- int float complex.
                                                             (line    6)
* 物件; complex number <1>:              复数对象.           (line    6)
* 物件; dictionary:                      标准类型层级结构.   (line  207)
* 物件; dictionary <1>:                  标准类型层级结构.   (line  444)
* 物件; dictionary <2>:                  基本定制.           (line  181)
* 物件; dictionary <3>:                  字典显示.           (line    6)
* 物件; dictionary <4>:                  抽取.               (line    6)
* 物件; dictionary <5>:                  赋值语句.           (line   90)
* 物件; dictionary <6>:                  映射类型 --- dict.  (line    6)
* 物件; dictionary <7>:                  字典物件.           (line    6)
* 物件; Ellipsis:                        标准类型层级结构.   (line   34)
* 物件; file:                            讀寫檔案.           (line    6)
* 物件; file <1>:                        檔案（File）物件.   (line    6)
* 物件; floating point:                  标准类型层级结构.   (line   84)
* 物件; floating point <1>:              数字类型 --- int float complex.
                                                             (line    6)
* 物件; floating point <2>:              浮點數（Floating Point）物件.
                                                             (line    6)
* 物件; frame:                           标准类型层级结构.   (line  548)
* 物件; frozenset:                       标准类型层级结构.   (line  192)
* 物件; frozenset <1>:                   集合对象.           (line    6)
* 物件; function:                        标准类型层级结构.   (line  233)
* 物件; function <1>:                    标准类型层级结构.   (line  376)
* 物件; function <2>:                    调用.               (line   99)
* 物件; function <3>:                    调用.               (line  105)
* 物件; function <4>:                    函数定义.           (line    6)
* 物件; function <5>:                    函式（Function）物件.
                                                             (line    6)
* 物件; generator:                       标准类型层级结构.   (line  531)
* 物件; generator <1>:                   生成器表达式.       (line    6)
* 物件; generator <2>:                   yield 表达式.       (line   88)
* 物件; GenericAlias:                    GenericAlias 类型.  (line    6)
* 物件; immutable:                       标准类型层级结构.   (line  114)
* 物件; immutable sequence:              标准类型层级结构.   (line  114)
* 物件; instance:                        标准类型层级结构.   (line  444)
* 物件; instance <1>:                    标准类型层级结构.   (line  463)
* 物件; instance <2>:                    调用.               (line  114)
* 物件; instancemethod:                  實體方法物件.       (line    6)
* 物件; integer:                         标准类型层级结构.   (line   62)
* 物件; integer <1>:                     数字类型 --- int float complex.
                                                             (line    6)
* 物件; integer <2>:                     整數物件.           (line    6)
* 物件; io.StringIO:                     文本序列类型 --- str.
                                                             (line   31)
* 物件; list:                            标准类型层级结构.   (line  158)
* 物件; list <1>:                        列表显示.           (line    6)
* 物件; list <2>:                        属性引用.           (line   10)
* 物件; list <3>:                        抽取.               (line    6)
* 物件; list <4>:                        切片.               (line    6)
* 物件; list <5>:                        赋值语句.           (line   85)
* 物件; list <6>:                        可变序列类型.       (line    6)
* 物件; list <7>:                        List（串列）<2>.    (line    6)
* 物件; list <8>:                        List（串列）物件.   (line    6)
* 物件; long integer:                    整數物件.           (line    6)
* 物件; mapping:                         标准类型层级结构.   (line  198)
* 物件; mapping <1>:                     标准类型层级结构.   (line  484)
* 物件; mapping <2>:                     抽取.               (line    6)
* 物件; mapping <3>:                     赋值语句.           (line   90)
* 物件; mapping <4>:                     映射类型 --- dict.  (line    6)
* 物件; mapping <5>:                     容器对象.           (line    6)
* 物件; memoryview:                      二进制序列类型 --- bytes bytearray memoryview.
                                                             (line    6)
* 物件; memoryview <1>:                  Ellipsis 对象.      (line   10)
* 物件; method:                          實例物件.           (line   26)
* 物件; method <1>:                      标准类型层级结构.   (line  303)
* 物件; method <2>:                      标准类型层级结构.   (line  386)
* 物件; method <3>:                      调用.               (line  105)
* 物件; method <4>:                      方法.               (line    6)
* 物件; method <5>:                      方法对象.           (line    6)
* 物件; module:                          标准类型层级结构.   (line  407)
* 物件; module <1>:                      属性引用.           (line   10)
* 物件; module <2>:                      模組物件模組.       (line    6)
* 物件; mutable:                         标准类型层级结构.   (line  151)
* 物件; mutable <1>:                     赋值语句.           (line    6)
* 物件; mutable <2>:                     赋值语句.           (line   81)
* 物件; mutable sequence:                标准类型层级结构.   (line  151)
* 物件; None:                            标准类型层级结构.   (line   15)
* 物件; None <1>:                        表达式语句.         (line   15)
* 物件; None <2>:                        None 对象.          (line    6)
* 物件; NotImplemented:                  标准类型层级结构.   (line   21)
* 物件; numeric:                         标准类型层级结构.   (line   39)
* 物件; numeric <1>:                     标准类型层级结构.   (line  484)
* 物件; numeric <2>:                     数字类型 --- int float complex.
                                                             (line    6)
* 物件; numeric <3>:                     数值对象.           (line    6)
* 物件; range:                           range 对象.         (line    6)
* 物件; sequence:                        标准类型层级结构.   (line   98)
* 物件; sequence <1>:                    标准类型层级结构.   (line  484)
* 物件; sequence <2>:                    抽取.               (line    6)
* 物件; sequence <3>:                    切片.               (line    6)
* 物件; sequence <4>:                    成员检测运算.       (line   30)
* 物件; sequence <5>:                    赋值语句.           (line   85)
* 物件; sequence <6>:                    for 语句.           (line    6)
* 物件; sequence <7>:                    通用序列操作.       (line    6)
* 物件; sequence <8>:                    序列对象.           (line    6)
* 物件; set:                             标准类型层级结构.   (line  187)
* 物件; set <1>:                         集合显示.           (line    6)
* 物件; set <2>:                         集合类型 --- set frozenset.
                                                             (line    6)
* 物件; set <3>:                         集合对象.           (line    6)
* 物件; set type:                        标准类型层级结构.   (line  174)
* 物件; slice:                           模拟容器类型.       (line   61)
* 物件; socket:                          socket --- 底层网络接口.
                                                             (line   15)
* 物件; string:                          抽取.               (line    6)
* 物件; string <1>:                      切片.               (line    6)
* 物件; string <2>:                      range 对象.         (line  111)
* 物件; traceback:                       标准类型层级结构.   (line  587)
* 物件; traceback <1>:                   raise 语句.         (line   18)
* 物件; traceback <2>:                   try 语句.           (line   56)
* 物件; traceback <3>:                   sys --- 系统相关的参数和函数.
                                                             (line  302)
* 物件; traceback <4>:                   traceback --- 打印或检索堆栈回溯.
                                                             (line   14)
* 物件; tuple:                           标准类型层级结构.   (line  135)
* 物件; tuple <1>:                       抽取.               (line    6)
* 物件; tuple <2>:                       切片.               (line    6)
* 物件; tuple <3>:                       表达式列表.         (line   11)
* 物件; tuple <4>:                       不可变序列类型.     (line    6)
* 物件; tuple <5>:                       元组.               (line    6)
* 物件; tuple <6>:                       元組（Tuple）物件.  (line    6)
* 物件; type:                            內建函式.           (line 1438)
* 物件; type <1>:                        对象、类型和引用计数.
                                                             (line    6)
* 物件; type <2>:                        Type 对象.          (line    6)
* 物件; user-defined function:           标准类型层级结构.   (line  233)
* 物件; user-defined function <1>:       调用.               (line   99)
* 物件; user-defined function <2>:       函数定义.           (line    6)
* 物件; user-defined method:             标准类型层级结构.   (line  303)
* 環境變數; APPDATA:                     PEP 370 分用户的 site-packages 目录.
                                                             (line   26)
* 環境變數; AUDIODEV:                    ossaudiodev --- 访问兼容OSS的音频设备.
                                                             (line   47)
* 環境變數; BROWSER:                     webbrowser --- 方便的Web浏览器控制器.
                                                             (line   17)
* 環境變數; BROWSER <1>:                 webbrowser --- 方便的Web浏览器控制器.
                                                             (line   79)
* 環境變數; CC:                          新增，改进和弃用的模块<4>.
                                                             (line   58)
* 環境變數; CFLAGS:                      新增，改进和弃用的模块<4>.
                                                             (line   58)
* 環境變數; CFLAGS <1>:                  Tweaking compiler/linker flags.
                                                             (line   66)
* 環境變數; CFLAGS <2>:                  Tweaking compiler/linker flags.
                                                             (line   67)
* 環境變數; COLS:                        curses<3>.          (line    7)
* 環境變數; COLS <1>:                    函数<4>.            (line  462)
* 環境變數; COLUMNS:                     函数<4>.            (line  482)
* 環境變數; COLUMNS <1>:                 函数<4>.            (line  483)
* 環境變數; COMSPEC:                     进程管理.           (line  576)
* 環境變數; COMSPEC <1>:                 Popen 构造函数.     (line   75)
* 環境變數; CPP:                         新增，改进和弃用的模块<4>.
                                                             (line   59)
* 環境變數; CPPFLAGS:                    新增，改进和弃用的模块<4>.
                                                             (line   59)
* 環境變數; DISTUTILS_DEBUG:             Debugging the setup script.
                                                             (line   19)
* 環境變數; EnableControlFlowGuard:      构建<4>.            (line    6)
* 環境變數; exec_prefix:                 与Python相关的路径和文件.
                                                             (line    6)
* 環境變數; exec_prefix <1>:             包含文件.           (line   32)
* 環境變數; exec_prefix <2>:             包含文件.           (line   40)
* 環境變數; HOME:                        os path.            (line   14)
* 環境變數; HOME <1>:                    更改的Python API.   (line  103)
* 環境變數; HOME <2>:                    Windows<17>.        (line   15)
* 環境變數; HOME <3>:                    Windows<17>.        (line   18)
* 環境變數; HOME <4>:                    os path --- 常用路径操作.
                                                             (line  124)
* 環境變數; HOME <5>:                    os path --- 常用路径操作.
                                                             (line  136)
* 環境變數; HOME <6>:                    distutils util --- Miscellaneous other utility functions.
                                                             (line   97)
* 環境變數; HOME <7>:                    Location and names of config files.
                                                             (line   50)
* 環境變數; HOME <8>:                    Location and names of config files.
                                                             (line   67)
* 環境變數; HOMEDRIVE:                   os path --- 常用路径操作.
                                                             (line  129)
* 環境變數; HOMEDRIVE <1>:               Location and names of config files.
                                                             (line   68)
* 環境變數; HOMEPATH:                    os path --- 常用路径操作.
                                                             (line  128)
* 環境變數; HOMEPATH <1>:                Location and names of config files.
                                                             (line   68)
* 環境變數; http_proxy:                  urllib request --- 用于打开 URL 的可扩展库.
                                                             (line   67)
* 環境變數; http_proxy <1>:              示例<33>.           (line   89)
* 環境變數; http_proxy <2>:              基本认证.           (line   56)
* 環境變數; IDLESTARTUP:                 IDLE<24>.           (line  174)
* 環境變數; IDLESTARTUP <1>:             IDLE<28>.           (line    9)
* 環境變數; IDLESTARTUP <2>:             IDLE<34>.           (line    9)
* 環境變數; IDLESTARTUP <3>:             启动和代码执行.     (line    7)
* 環境變數; KDEDIR:                      webbrowser --- 方便的Web浏览器控制器.
                                                             (line  164)
* 環境變數; LANG:                        GNU gettext API.    (line   18)
* 環境變數; LANG <1>:                    基于类的 API.       (line   22)
* 環境變數; LANG <2>:                    locale --- 国际化服务.
                                                             (line   40)
* 環境變數; LANG <3>:                    locale --- 国际化服务.
                                                             (line  255)
* 環境變數; LANG <4>:                    locale --- 国际化服务.
                                                             (line  259)
* 環境變數; LANGUAGE:                    GNU gettext API.    (line   17)
* 環境變數; LANGUAGE <1>:                基于类的 API.       (line   21)
* 環境變數; LC_ALL:                      GNU gettext API.    (line   17)
* 環境變數; LC_ALL <1>:                  基于类的 API.       (line   21)
* 環境變數; LC_MESSAGES:                 GNU gettext API.    (line   18)
* 環境變數; LC_MESSAGES <1>:             基于类的 API.       (line   21)
* 環境變數; LDCXXSHARED:                 构建和 C API 的改变<8>.
                                                             (line  153)
* 環境變數; LDFLAGS:                     新增，改进和弃用的模块<4>.
                                                             (line   59)
* 環境變數; LINES:                       curses<3>.          (line    6)
* 環境變數; LINES <1>:                   函数<4>.            (line  104)
* 環境變數; LINES <2>:                   函数<4>.            (line  462)
* 環境變數; LINES <3>:                   函数<4>.            (line  482)
* 環境變數; LINES <4>:                   函数<4>.            (line  483)
* 環境變數; LNAME:                       getpass --- 便携式密码输入工具.
                                                             (line   35)
* 環境變數; LOGNAME:                     进程参数.           (line  199)
* 環境變數; LOGNAME <1>:                 getpass --- 便携式密码输入工具.
                                                             (line   35)
* 環境變數; MIXERDEV:                    ossaudiodev --- 访问兼容OSS的音频设备.
                                                             (line   62)
* 環境變數; no_proxy:                    urllib request --- 用于打开 URL 的可扩展库.
                                                             (line  251)
* 環境變數; PAGER:                       pydoc --- 文档生成器和在线帮助系统.
                                                             (line   37)
* 環境變數; PATH:                        更改的Python API.   (line  125)
* 環境變數; PATH <1>:                    'python' 命令行为的变化<2>.
                                                             (line    6)
* 環境變數; PATH <2>:                    'python' 命令行为的变化<2>.
                                                             (line   11)
* 環境變數; PATH <3>:                    'python' 命令行为的变化<2>.
                                                             (line   12)
* 環境變數; PATH <4>:                    安全性<16>.         (line   16)
* 環境變數; PATH <5>:                    安全性<16>.         (line   20)
* 環境變數; PATH <6>:                    模組的搜尋路徑.     (line   13)
* 環境變數; PATH <7>:                    可執行的 Python 腳本.
                                                             (line   11)
* 環境變數; PATH <8>:                    环境变量.           (line   22)
* 環境變數; PATH <9>:                    杂项.               (line   14)
* 環境變數; PATH <10>:                   安装步骤.           (line   26)
* 環境變數; PATH <11>:                   安装步骤.           (line   46)
* 環境變數; PATH <12>:                   安裝排除使用者介面. (line   49)
* 環境變數; PATH <13>:                   附录：设置环境变量. (line   19)
* 環境變數; PATH <14>:                   附录：设置环境变量. (line   27)
* 環境變數; PATH <15>:                   查找Python可执行文件.
                                                             (line   12)
* 環境變數; PATH <16>:                   查找Python可执行文件.
                                                             (line   17)
* 環境變數; PATH <17>:                   查找Python可执行文件.
                                                             (line   18)
* 環境變數; PATH <18>:                   适用于Windows的Python启动器.
                                                             (line   12)
* 環境變數; PATH <19>:                   从命令行.           (line    8)
* 環境變數; PATH <20>:                   从命令行.           (line   33)
* 環境變數; PATH <21>:                   Shebang Lines.      (line   39)
* 環境變數; PATH <22>:                   Shebang Lines.      (line   40)
* 環境變數; PATH <23>:                   进程管理.           (line   39)
* 環境變數; PATH <24>:                   进程管理.           (line   69)
* 環境變數; PATH <25>:                   进程管理.           (line   71)
* 環境變數; PATH <26>:                   进程管理.           (line   73)
* 環境變數; PATH <27>:                   进程管理.           (line  402)
* 環境變數; PATH <28>:                   进程管理.           (line  474)
* 環境變數; PATH <29>:                   进程管理.           (line  475)
* 環境變數; PATH <30>:                   进程管理.           (line  477)
* 環境變數; PATH <31>:                   其他系统信息.       (line   97)
* 環境變數; PATH <32>:                   webbrowser --- 方便的Web浏览器控制器.
                                                             (line  192)
* 環境變數; PATH <33>:                   在 Unix 系统上安装你的 CGI 脚本.
                                                             (line   22)
* 環境變數; PATH <34>:                   常见问题和解决方案. (line   20)
* 環境變數; PATH <35>:                   site —— 指定域的配置钩子.
                                                             (line   47)
* 環境變數; PATH <36>:                   嵌入式Python.       (line   31)
* 環境變數; PATH <37>:                   嵌入式Python.       (line   37)
* 環境變數; PATH <38>:                   我如何使Python script 執行在Unix ?.
                                                             (line   19)
* 環境變數; PATH <39>:                   我如何使Python script 執行在Unix ?.
                                                             (line   24)
* 環境變數; PATHEXT:                     其他改进<2>.        (line   30)
* 環境變數; PATHEXT <1>:                 库<11>.             (line  104)
* 環境變數; PATHEXT <2>:                 安裝排除使用者介面. (line   50)
* 環境變數; PIP_USER:                    Windows<19>.        (line  101)
* 環境變數; PLAT:                        distutils util --- Miscellaneous other utility functions.
                                                             (line   99)
* 環境變數; POSIXLY_CORRECT:             getopt --- C 风格的命令行选项解析器.
                                                             (line   52)
* 環境變數; prefix:                      与Python相关的路径和文件.
                                                             (line    6)
* 環境變數; prefix <1>:                  包含文件.           (line   32)
* 環境變數; prefix <2>:                  包含文件.           (line   35)
* 環境變數; prefix <3>:                  包含文件.           (line   39)
* 環境變數; PYTHON*:                     其他改进<2>.        (line    9)
* 環境變數; PYTHON* <1>:                 接口选项.           (line   65)
* 環境變數; PYTHON* <2>:                 接口选项.           (line  118)
* 環境變數; PYTHON* <3>:                 其他选项.           (line   37)
* 環境變數; PYTHON* <4>:                 其他选项.           (line   53)
* 環境變數; PYTHON* <5>:                 全局配置变量.       (line   54)
* 環境變數; PYTHONASYNCIODEBUG:          环境变量.           (line  223)
* 環境變數; PYTHONASYNCIODEBUG <1>:      开启调试模式.       (line   10)
* 環境變數; PYTHONASYNCIODEBUG <2>:      Debug 模式.         (line   11)
* 環境變數; PYTHONASYNCIODEBUG <3>:      Python 开发模式的效果.
                                                             (line   57)
* 環境變數; PYTHONBREAKPOINT:            PEP 553 内置的 breakpoint.
                                                             (line   12)
* 環境變數; PYTHONBREAKPOINT <1>:        环境变量.           (line   60)
* 環境變數; PYTHONBREAKPOINT <2>:        sys --- 系统相关的参数和函数.
                                                             (line  165)
* 環境變數; PYTHONBREAKPOINT <3>:        sys --- 系统相关的参数和函数.
                                                             (line  175)
* 環境變數; PYTHONBREAKPOINT <4>:        sys --- 系统相关的参数和函数.
                                                             (line  179)
* 環境變數; PYTHONCASEOK:                Python API 的变化.  (line   28)
* 環境變數; PYTHONCASEOK <1>:            PEP 235 Importing Modules on Case-Insensitive Platforms.
                                                             (line   17)
* 環境變數; PYTHONCASEOK <2>:            库<21>.             (line  144)
* 環境變數; PYTHONCASEOK <3>:            环境变量.           (line  102)
* 環境變數; PYTHONCASEOK <4>:            內建函式.           (line 1581)
* 環境變數; PYTHONCOERCECLOCALE:         PEP 538 传统 C 区域强制转换.
                                                             (line   11)
* 環境變數; PYTHONCOERCECLOCALE <1>:     环境变量.           (line  299)
* 環境變數; PYTHONCOERCECLOCALE <2>:     环境变量.           (line  393)
* 環境變數; PYTHONCOERCECLOCALE <3>:     Python Configuration.
                                                             (line   15)
* 環境變數; PYTHONDEBUG:                 其他选项.           (line   32)
* 環境變數; PYTHONDEBUG <1>:             环境变量.           (line   71)
* 環境變數; PYTHONDEBUG <2>:             全局配置变量.       (line   26)
* 環境變數; PYTHONDEVMODE:               Python 开发模式 -X dev.
                                                             (line    6)
* 環境變數; PYTHONDEVMODE <1>:           环境变量.           (line  343)
* 環境變數; PYTHONDEVMODE <2>:           Python 开发模式.    (line   12)
* 環境變數; PYTHONDOCS:                  pydoc --- 文档生成器和在线帮助系统.
                                                             (line   66)
* 環境變數; PYTHONDONTWRITEBYTECODE:     Interpreter Changes<2>.
                                                             (line   16)
* 環境變數; PYTHONDONTWRITEBYTECODE <1>: 新增和改进的模块<2>.
                                                             (line  624)
* 環境變數; PYTHONDONTWRITEBYTECODE <2>: 其他选项.           (line   16)
* 環境變數; PYTHONDONTWRITEBYTECODE <3>: 环境变量.           (line  107)
* 環境變數; PYTHONDONTWRITEBYTECODE <4>: sys --- 系统相关的参数和函数.
                                                             (line  240)
* 環境變數; PYTHONDONTWRITEBYTECODE <5>: 全局配置变量.       (line   34)
* 環境變數; PYTHONDONTWRITEBYTECODE <6>: 如何创建 pyc 文件？.
                                                             (line   19)
* 環境變數; PYTHONDUMPREFS:              调试构建使用与发布构建相同的 ABI.
                                                             (line   12)
* 環境變數; PYTHONDUMPREFS <1>:          构建<21>.           (line   54)
* 環境變數; PYTHONDUMPREFS <2>:          调试模式变量.       (line   14)
* 環境變數; PYTHONDUMPREFS <3>:          PyObject Slots.     (line   22)
* 環境變數; PYTHONEXECUTABLE:            环境变量.           (line  173)
* 環境變數; PYTHONFAULTHANDLER:          faulthandler<3>.    (line   11)
* 環境變數; PYTHONFAULTHANDLER <1>:      环境变量.           (line  198)
* 環境變數; PYTHONFAULTHANDLER <2>:      Python 开发模式的效果.
                                                             (line   51)
* 環境變數; PYTHONFAULTHANDLER <3>:      faulthandler —— 转储 Python 的跟踪信息.
                                                             (line   12)
* 環境變數; PYTHONHASHSEED:              Builtin functions and types.
                                                             (line   17)
* 環境變數; PYTHONHASHSEED <1>:          Porting Python code.
                                                             (line    6)
* 環境變數; PYTHONHASHSEED <2>:          核心与内置函数<35>. (line   30)
* 環境變數; PYTHONHASHSEED <3>:          其他选项.           (line   83)
* 環境變數; PYTHONHASHSEED <4>:          其他选项.           (line   97)
* 環境變數; PYTHONHASHSEED <5>:          环境变量.           (line  120)
* 環境變數; PYTHONHASHSEED <6>:          环境变量.           (line  125)
* 環境變數; PYTHONHASHSEED <7>:          基本定制.           (line  241)
* 環境變數; PYTHONHASHSEED <8>:          全局配置变量.       (line   46)
* 環境變數; PYTHONHASHSEED <9>:          全局配置变量.       (line   49)
* 環境變數; PYTHONHOME:                  摘要 - 发布重点<4>. (line   90)
* 環境變數; PYTHONHOME <1>:              其他选项.           (line   38)
* 環境變數; PYTHONHOME <2>:              环境变量.           (line    9)
* 環境變數; PYTHONHOME <3>:              环境变量.           (line   16)
* 環境變數; PYTHONHOME <4>:              环境变量.           (line   17)
* 環境變數; PYTHONHOME <5>:              环境变量.           (line   31)
* 環境變數; PYTHONHOME <6>:              查找模块.           (line   38)
* 環境變數; PYTHONHOME <7>:              查找模块.           (line   52)
* 環境變數; PYTHONHOME <8>:              查找模块.           (line   80)
* 環境變數; PYTHONHOME <9>:              test support script_helper --- Utilities for the Python execution tests.
                                                             (line   24)
* 環境變數; PYTHONHOME <10>:             嵌入式Python.       (line   38)
* 環境變數; PYTHONHOME <11>:             嵌入式Python.       (line   44)
* 環境變數; PYTHONHOME <12>:             全局配置变量.       (line   55)
* 環境變數; PYTHONHOME <13>:             Process-wide parameters.
                                                             (line  269)
* 環境變數; PYTHONHOME <14>:             Process-wide parameters.
                                                             (line  283)
* 環境變數; PYTHONHOME <15>:             PyConfig.           (line  204)
* 環境變數; PYTHONHOME <16>:             Modifying Python's Search Path.
                                                             (line   60)
* 環境變數; PYTHONHOME <17>:             Modifying Python's Search Path.
                                                             (line   62)
* 環境變數; PYTHONINSPECT:               Other Changes and Fixes<2>.
                                                             (line   13)
* 環境變數; PYTHONINSPECT <1>:           其他选项.           (line   46)
* 環境變數; PYTHONINSPECT <2>:           环境变量.           (line   84)
* 環境變數; PYTHONINSPECT <3>:           全局配置变量.       (line   66)
* 環境變數; PYTHONIOENCODING:            其他改进<2>.        (line   75)
* 環境變數; PYTHONIOENCODING <1>:        Interpreter Changes<2>.
                                                             (line   23)
* 環境變數; PYTHONIOENCODING <2>:        环境变量.           (line  136)
* 環境變數; PYTHONIOENCODING <3>:        环境变量.           (line  327)
* 環境變數; PYTHONIOENCODING <4>:        环境变量.           (line  385)
* 環境變數; PYTHONIOENCODING <5>:        sys --- 系统相关的参数和函数.
                                                             (line 1272)
* 環境變數; PYTHONIOENCODING <6>:        Process-wide parameters.
                                                             (line   14)
* 環境變數; PYTHONIOENCODING <7>:        Process-wide parameters.
                                                             (line   18)
* 環境變數; PYTHONLEGACYWINDOWSFSENCODING: PEP 529 将Windows文件系统编码更改为UTF-8.
                                                             (line   18)
* 環境變數; PYTHONLEGACYWINDOWSFSENCODING <1>: 环境变量.     (line  274)
* 環境變數; PYTHONLEGACYWINDOWSFSENCODING <2>: sys --- 系统相关的参数和函数.
                                                             (line 1234)
* 環境變數; PYTHONLEGACYWINDOWSFSENCODING <3>: 全局配置变量. (line   88)
* 環境變數; PYTHONLEGACYWINDOWSSTDIO:    PEP 528 将Windows控制台编码更改为UTF-8.
                                                             (line   12)
* 環境變數; PYTHONLEGACYWINDOWSSTDIO <1>: 环境变量.          (line  149)
* 環境變數; PYTHONLEGACYWINDOWSSTDIO <2>: 环境变量.          (line  287)
* 環境變數; PYTHONLEGACYWINDOWSSTDIO <3>: sys --- 系统相关的参数和函数.
                                                             (line 1275)
* 環境變數; PYTHONLEGACYWINDOWSSTDIO <4>: 全局配置变量.      (line  100)
* 環境變數; PYTHONMALLOC:                PYTHONMALLOC 环境变量.
                                                             (line    6)
* 環境變數; PYTHONMALLOC <1>:            C API 中的改变<3>.  (line    9)
* 環境變數; PYTHONMALLOC <2>:            核心与内置函数<55>. (line   91)
* 環境變數; PYTHONMALLOC <3>:            环境变量.           (line  230)
* 環境變數; PYTHONMALLOC <4>:            环境变量.           (line  267)
* 環境變數; PYTHONMALLOC <5>:            Python 开发模式的效果.
                                                             (line   42)
* 環境變數; PYTHONMALLOC <6>:            Python 开发模式的效果.
                                                             (line   45)
* 環境變數; PYTHONMALLOC <7>:            總覽<2>.            (line   54)
* 環境變數; PYTHONMALLOC <8>:            默认内存分配器.     (line   26)
* 環境變數; PYTHONMALLOC <9>:            自定义内存分配器.   (line  121)
* 環境變數; PYTHONMALLOCSTATS:           核心与内置函数<55>. (line   97)
* 環境變數; PYTHONMALLOCSTATS <1>:       环境变量.           (line  262)
* 環境變數; PYTHONMALLOCSTATS <2>:       總覽<2>.            (line   57)
* 環境變數; PYTHONNOUSERSITE:            PEP 370 分用户的 site-packages 目录.
                                                             (line   30)
* 環境變數; PYTHONNOUSERSITE <1>:        环境变量.           (line  152)
* 環境變數; PYTHONNOUSERSITE <2>:        模块内容<8>.        (line   14)
* 環境變數; PYTHONNOUSERSITE <3>:        全局配置变量.       (line  120)
* 環境變數; PYTHONOLDPARSER:             其他选项.           (line  177)
* 環境變數; PYTHONOLDPARSER <1>:         环境变量.           (line   76)
* 環境變數; PYTHONOLDPARSER <2>:         PyConfig.           (line  398)
* 環境變數; PYTHONOPTIMIZE:              其他选项.           (line   62)
* 環境變數; PYTHONOPTIMIZE <1>:          环境变量.           (line   55)
* 環境變數; PYTHONOPTIMIZE <2>:          全局配置变量.       (line  125)
* 環境變數; PYTHONPATH:                  'python' 命令行为的变化<2>.
                                                             (line    8)
* 環境變數; PYTHONPATH <1>:              'python' 命令行为的变化<2>.
                                                             (line    9)
* 環境變數; PYTHONPATH <2>:              模組的搜尋路徑.     (line   13)
* 環境變數; PYTHONPATH <3>:              標準模組.           (line   27)
* 環境變數; PYTHONPATH <4>:              標準模組.           (line   27)
* 環境變數; PYTHONPATH <5>:              其他选项.           (line   37)
* 環境變數; PYTHONPATH <6>:              环境变量.           (line   20)
* 環境變數; PYTHONPATH <7>:              环境变量.           (line   26)
* 環境變數; PYTHONPATH <8>:              环境变量.           (line   32)
* 環境變數; PYTHONPATH <9>:              环境变量.           (line   34)
* 環境變數; PYTHONPATH <10>:             附录：设置环境变量. (line   30)
* 環境變數; PYTHONPATH <11>:             查找模块.           (line   27)
* 環境變數; PYTHONPATH <12>:             查找模块.           (line   45)
* 環境變數; PYTHONPATH <13>:             查找模块.           (line   79)
* 環境變數; PYTHONPATH <14>:             設定.               (line    6)
* 環境變數; PYTHONPATH <15>:             在 Unix 系统上安装你的 CGI 脚本.
                                                             (line   23)
* 環境變數; PYTHONPATH <16>:             test support script_helper --- Utilities for the Python execution tests.
                                                             (line   25)
* 環境變數; PYTHONPATH <17>:             sys --- 系统相关的参数和函数.
                                                             (line  897)
* 環境變數; PYTHONPATH <18>:             sys --- 系统相关的参数和函数.
                                                             (line  903)
* 環境變數; PYTHONPATH <19>:             构建C/C++扩展.      (line    9)
* 環境變數; PYTHONPATH <20>:             嵌入式Python.       (line   39)
* 環境變數; PYTHONPATH <21>:             嵌入式Python.       (line   44)
* 環境變數; PYTHONPATH <22>:             全局配置变量.       (line   54)
* 環境變數; PYTHONPATH <23>:             PyConfig.           (line  259)
* 環境變數; PYTHONPATH <24>:             Modifying Python's Search Path.
                                                             (line   67)
* 環境變數; PYTHONPATH <25>:             Modifying Python's Search Path.
                                                             (line   68)
* 環境變數; PYTHONPLATLIBDIR:            核心与内置函数<16>. (line   25)
* 環境變數; PYTHONPLATLIBDIR <1>:        环境变量.           (line   38)
* 環境變數; PYTHONPROFILEIMPORTTIME:     其他语言特性修改<3>.
                                                             (line   44)
* 環境變數; PYTHONPROFILEIMPORTTIME <1>: 核心与内置函数<37>. (line   67)
* 環境變數; PYTHONPROFILEIMPORTTIME <2>: 其他选项.           (line  192)
* 環境變數; PYTHONPROFILEIMPORTTIME <3>: 环境变量.           (line  216)
* 環境變數; PYTHONPYCACHEPREFIX:         用于已编译字节码文件的并行文件系统缓存.
                                                             (line    6)
* 環境變數; PYTHONPYCACHEPREFIX <1>:     核心与内置函数<28>. (line  396)
* 環境變數; PYTHONPYCACHEPREFIX <2>:     其他选项.           (line  203)
* 環境變數; PYTHONPYCACHEPREFIX <3>:     环境变量.           (line  112)
* 環境變數; PYTHONPYCACHEPREFIX <4>:     sys --- 系统相关的参数和函数.
                                                             (line  255)
* 環境變數; PYTHONSHOWALLOCCOUNT:        Two new environment variables for debug mode.
                                                             (line   11)
* 環境變數; PYTHONSHOWREFCOUNT:          Two new environment variables for debug mode.
                                                             (line    7)
* 環境變數; PYTHONSTARTUP:               sys<7>.             (line   17)
* 環境變數; PYTHONSTARTUP <1>:           sys<7>.             (line   21)
* 環境變數; PYTHONSTARTUP <2>:           IDLE<24>.           (line  174)
* 環境變數; PYTHONSTARTUP <3>:           IDLE<28>.           (line    9)
* 環境變數; PYTHONSTARTUP <4>:           IDLE<34>.           (line    9)
* 環境變數; PYTHONSTARTUP <5>:           互動式啟動檔案.     (line    7)
* 環境變數; PYTHONSTARTUP <6>:           其他选项.           (line   43)
* 環境變數; PYTHONSTARTUP <7>:           环境变量.           (line   44)
* 環境變數; PYTHONSTARTUP <8>:           示例<2>.            (line    8)
* 環境變數; PYTHONSTARTUP <9>:           启动和代码执行.     (line    7)
* 環境變數; PYTHONSTARTUP <10>:          sys --- 系统相关的参数和函数.
                                                             (line  811)
* 環境變數; PYTHONSTARTUP <11>:          Readline 配置.      (line   10)
* 環境變數; PYTHONTHREADDEBUG:           调试模式变量.       (line    8)
* 環境變數; PYTHONTRACEMALLOC:           环境变量.           (line  207)
* 環境變數; PYTHONTRACEMALLOC <1>:       tracemalloc --- 跟踪内存分配.
                                                             (line   25)
* 環境變數; PYTHONTRACEMALLOC <2>:       tracemalloc --- 跟踪内存分配.
                                                             (line   32)
* 環境變數; PYTHONTRACEMALLOC <3>:       函数<10>.           (line   90)
* 環境變數; PYTHONTZPATH:                环境配置.           (line   10)
* 環境變數; PYTHONTZPATH <1>:            异常与警告.         (line   13)
* 環境變數; PYTHONUNBUFFERED:            核心与内置函数<21>. (line  107)
* 環境變數; PYTHONUNBUFFERED <1>:        其他选项.           (line  123)
* 環境變數; PYTHONUNBUFFERED <2>:        环境变量.           (line   92)
* 環境變數; PYTHONUNBUFFERED <3>:        sys --- 系统相关的参数和函数.
                                                             (line 1280)
* 環境變數; PYTHONUNBUFFERED <4>:        全局配置变量.       (line  140)
* 環境變數; PYTHONUSERBASE:              PEP 370 分用户的 site-packages 目录.
                                                             (line   23)
* 環境變數; PYTHONUSERBASE <1>:          环境变量.           (line  162)
* 環境變數; PYTHONUSERBASE <2>:          模块内容<8>.        (line   38)
* 環境變數; PYTHONUSERBASE <3>:          模块内容<8>.        (line   61)
* 環境變數; PYTHONUSERSITE:              test support script_helper --- Utilities for the Python execution tests.
                                                             (line   25)
* 環境變數; PYTHONUTF8:                  PEP 540 强制 UTF-8 运行时模式.
                                                             (line    6)
* 環境變數; PYTHONUTF8 <1>:              其他选项.           (line  200)
* 環境變數; PYTHONUTF8 <2>:              环境变量.           (line  335)
* 環境變數; PYTHONUTF8 <3>:              环境变量.           (line  350)
* 環境變數; PYTHONUTF8 <4>:              UTF-8 模式.         (line   16)
* 環境變數; PYTHONUTF8 <5>:              sys --- 系统相关的参数和函数.
                                                             (line 1274)
* 環境變數; PYTHONUTF8 <6>:              Python Configuration.
                                                             (line   14)
* 環境變數; PYTHONVERBOSE:               其他选项.           (line  131)
* 環境變數; PYTHONVERBOSE <1>:           环境变量.           (line   97)
* 環境變數; PYTHONVERBOSE <2>:           全局配置变量.       (line  151)
* 環境變數; PYTHONWARNINGS:              warnings.           (line   18)
* 環境變數; PYTHONWARNINGS <1>:          其他语言特性修改<8>.
                                                             (line  158)
* 環境變數; PYTHONWARNINGS <2>:          Changes to the Handling of Deprecation Warnings.
                                                             (line   25)
* 環境變數; PYTHONWARNINGS <3>:          Interpreter Changes.
                                                             (line    6)
* 環境變數; PYTHONWARNINGS <4>:          其他选项.           (line  147)
* 環境變數; PYTHONWARNINGS <5>:          环境变量.           (line  179)
* 環境變數; PYTHONWARNINGS <6>:          Python 开发模式的效果.
                                                             (line   27)
* 環境變數; PYTHONWARNINGS <7>:          警告过滤器的介绍.   (line    6)
* 環境變數; PYTHONWARNINGS <8>:          警告过滤器的介绍.   (line   17)
* 環境變數; PYTHONWARNINGS <9>:          默认警告过滤器.     (line    6)
* 環境變數; PYTHON_DOM:                  模块内容<6>.        (line   19)
* 環境變數; PY_PYTHON:                   自定义默认的Python版本.
                                                             (line   13)
* 環境變數; SOURCE_DATE_EPOCH:           py_compile<2>.      (line    7)
* 環境變數; SOURCE_DATE_EPOCH <1>:       库<30>.             (line  451)
* 環境變數; SOURCE_DATE_EPOCH <2>:       构建<29>.           (line   15)
* 環境變數; SOURCE_DATE_EPOCH <3>:       py_compile --- 编译 Python 源文件.
                                                             (line   51)
* 環境變數; SOURCE_DATE_EPOCH <4>:       py_compile --- 编译 Python 源文件.
                                                             (line   66)
* 環境變數; SOURCE_DATE_EPOCH <5>:       py_compile --- 编译 Python 源文件.
                                                             (line   69)
* 環境變數; SOURCE_DATE_EPOCH <6>:       Command-line use.   (line   90)
* 環境變數; SSLKEYLOGFILE:               上下文创建.         (line   27)
* 環境變數; SSLKEYLOGFILE <1>:           上下文创建.         (line   55)
* 環境變數; SSL_CERT_FILE:               LibreSSL 支持.      (line   13)
* 環境變數; SSL_CERT_PATH:               LibreSSL 支持.      (line   14)
* 環境變數; SystemRoot:                  Popen 构造函数.     (line  223)
* 環境變數; TCL_LIBRARY:                 我怎样“冻结”Tkinter程序？.
                                                             (line    9)
* 環境變數; TEMP:                        tempfile --- 生成临时文件和目录.
                                                             (line  200)
* 環境變數; TERM:                        函数<4>.            (line  392)
* 環境變數; TERM <1>:                    函数<4>.            (line  413)
* 環境變數; TK_LIBRARY:                  我怎样“冻结”Tkinter程序？.
                                                             (line   10)
* 環境變數; TMP:                         tempfile --- 生成临时文件和目录.
                                                             (line  202)
* 環境變數; TMPDIR:                      tempfile --- 生成临时文件和目录.
                                                             (line  198)
* 環境變數; TZ:                          函数<3>.            (line  440)
* 環境變數; TZ <1>:                      函数<3>.            (line  441)
* 環境變數; TZ <2>:                      函数<3>.            (line  448)
* 環境變數; TZ <3>:                      函数<3>.            (line  452)
* 環境變數; TZ <4>:                      函数<3>.            (line  454)
* 環境變數; TZ <5>:                      函数<3>.            (line  507)
* 環境變數; USER:                        getpass --- 便携式密码输入工具.
                                                             (line   35)
* 環境變數; USERNAME:                    进程参数.           (line  200)
* 環境變數; USERNAME <1>:                getpass --- 便携式密码输入工具.
                                                             (line   35)
* 環境變數; USERPROFILE:                 os path.            (line   13)
* 環境變數; USERPROFILE <1>:             更改的Python API.   (line  102)
* 環境變數; USERPROFILE <2>:             Windows<17>.        (line   15)
* 環境變數; USERPROFILE <3>:             os path --- 常用路径操作.
                                                             (line  128)
* 環境變數; USERPROFILE <4>:             Location and names of config files.
                                                             (line   67)
* 環境變數; USER_BASE:                   新增和改进的模块.   (line  469)
* 環境變數; VIRTUAL_ENV:                 创建虚拟环境.       (line  121)
* 運算子; !=:                            比较运算.           (line    6)
* 運算子; != <1>:                        比较.               (line    6)
* 運算子; % (percent):                   二元算术运算符.     (line   36)
* 運算子; % (percent) <1>:               数字类型 --- int float complex.
                                                             (line   20)
* 運算子; & (ampersand):                 二元位运算.         (line   12)
* 運算子; & (ampersand) <1>:             整数类型的按位运算. (line    6)
* 運算子; * (asterisk):                  二元算术运算符.     (line   15)
* 運算子; * (asterisk) <1>:              数字类型 --- int float complex.
                                                             (line   20)
* 運算子; **:                            幂运算符.           (line    6)
* 運算子; ** <1>:                        数字类型 --- int float complex.
                                                             (line   20)
* 運算子; / (slash):                     二元算术运算符.     (line   28)
* 運算子; / (slash) <1>:                 数字类型 --- int float complex.
                                                             (line   20)
* 運算子; //:                            二元算术运算符.     (line   28)
* 運算子; // <1>:                        数字类型 --- int float complex.
                                                             (line   20)
* 運算子; < (less):                      比较运算.           (line    6)
* 運算子; < (less) <1>:                  比较.               (line    6)
* 運算子; <<:                            移位运算.           (line    6)
* 運算子; << <1>:                        整数类型的按位运算. (line    6)
* 運算子; <=:                            比较运算.           (line    6)
* 運算子; <= <1>:                        比较.               (line    6)
* 運算子; ==:                            比较运算.           (line    6)
* 運算子; == <1>:                        比较.               (line    6)
* 運算子; > (greater):                   比较运算.           (line    6)
* 運算子; > (greater) <1>:               比较.               (line    6)
* 運算子; >=:                            比较运算.           (line    6)
* 運算子; >= <1>:                        比较.               (line    6)
* 運算子; >>:                            移位运算.           (line    6)
* 運算子; >> <1>:                        整数类型的按位运算. (line    6)
* 運算子; @ (at):                        二元算术运算符.     (line   23)
* 運算子; and:                           布尔运算.           (line   17)
* 運算子; and <1>:                       逻辑值检测.         (line   19)
* 運算子; and <2>:                       布尔运算 --- and or not.
                                                             (line   22)
* 運算子; in:                            成员检测运算.       (line   30)
* 運算子; in <1>:                        比较.               (line   59)
* 運算子; in <2>:                        通用序列操作.       (line   17)
* 運算子; is:                            成员检测运算.       (line   32)
* 運算子; is <1>:                        比较.               (line    6)
* 運算子; is not:                        成员检测运算.       (line   32)
* 運算子; is not <1>:                    比较.               (line    6)
* 運算子; not:                           布尔运算.           (line   15)
* 運算子; not <1>:                       布尔运算 --- and or not.
                                                             (line   22)
* 運算子; not in:                        成员检测运算.       (line   30)
* 運算子; not in <1>:                    比较.               (line   59)
* 運算子; not in <2>:                    通用序列操作.       (line   17)
* 運算子; or:                            布尔运算.           (line   20)
* 運算子; or <1>:                        逻辑值检测.         (line   19)
* 運算子; or <2>:                        布尔运算 --- and or not.
                                                             (line   22)
* 運算子; ^ (caret):                     二元位运算.         (line   16)
* 運算子; ^ (caret) <1>:                 整数类型的按位运算. (line    6)
* 運算子; | (vertical bar):              二元位运算.         (line   20)
* 運算子; | (vertical bar) <1>:          整数类型的按位运算. (line    6)
* 運算子; ~ (tilde):                     一元算术和位运算.   (line   16)
* 運算子; ~ (tilde) <1>:                 整数类型的按位运算. (line    6)
* 關鍵字; as:                            import 语句.        (line    6)
* 關鍵字; as <1>:                        try 语句.           (line    6)
* 關鍵字; as <2>:                        with 语句.          (line    6)
* 關鍵字; async:                         协程函数定义.       (line    9)
* 關鍵字; await:                         调用.               (line  121)
* 關鍵字; await <1>:                     协程函数定义.       (line    9)
* 關鍵字; elif:                          if 语句.            (line    6)
* 關鍵字; else:                          break 语句.         (line   12)
* 關鍵字; else <1>:                      if 语句.            (line    6)
* 關鍵字; else <2>:                      while 语句.         (line    6)
* 關鍵字; else <3>:                      for 语句.           (line    6)
* 關鍵字; else <4>:                      try 语句.           (line    6)
* 關鍵字; else <5>:                      try 语句.           (line   62)
* 關鍵字; except:                        try 语句.           (line    6)
* 關鍵字; finally:                       return 语句.        (line   16)
* 關鍵字; finally <1>:                   break 语句.         (line   17)
* 關鍵字; finally <2>:                   continue 语句.      (line    6)
* 關鍵字; finally <3>:                   try 语句.           (line    6)
* 關鍵字; finally <4>:                   try 语句.           (line   67)
* 關鍵字; from:                          yield 表达式.       (line    6)
* 關鍵字; from <1>:                      import 语句.        (line    6)
* 關鍵字; in:                            for 语句.           (line    6)
* 關鍵字; yield:                         yield 表达式.       (line    6)
* 陳述式; assert:                        assert 语句.        (line    6)
* 陳述式; assert <1>:                    具体异常.           (line   10)
* 陳述式; async def:                     协程<2>.            (line    8)
* 陳述式; async for:                     协程函数定义.       (line   24)
* 陳述式; async with:                    async for 语句.     (line   40)
* 陳述式; break:                         break 语句.         (line    6)
* 陳述式; break <1>:                     while 语句.         (line   15)
* 陳述式; break <2>:                     for 语句.           (line   19)
* 陳述式; break <3>:                     try 语句.           (line   62)
* 陳述式; break <4>:                     try 语句.           (line   86)
* 陳述式; class:                         类定义.             (line    6)
* 陳述式; continue:                      continue 语句.      (line    6)
* 陳述式; continue <1>:                  while 语句.         (line   15)
* 陳述式; continue <2>:                  for 语句.           (line   19)
* 陳述式; continue <3>:                  try 语句.           (line   62)
* 陳述式; continue <4>:                  try 语句.           (line   86)
* 陳述式; def:                           函数定义.           (line    6)
* 陳述式; del:                           基本定制.           (line   46)
* 陳述式; del <1>:                       del 语句.           (line    6)
* 陳述式; del <2>:                       可变序列类型.       (line   14)
* 陳述式; del <3>:                       映射类型 --- dict.  (line    6)
* 陳述式; except:                        內建的例外.         (line    6)
* 陳述式; for:                           for 陳述式.         (line    6)
* 陳述式; for <1>:                       break 语句.         (line    6)
* 陳述式; for <2>:                       continue 语句.      (line    6)
* 陳述式; for <3>:                       for 语句.           (line    6)
* 陳述式; global:                        del 语句.           (line   13)
* 陳述式; global <1>:                    global 语句.        (line    6)
* 陳述式; if:                            if 语句.            (line    6)
* 陳述式; if <1>:                        逻辑值检测.         (line    6)
* 陳述式; import:                        标准类型层级结构.   (line  407)
* 陳述式; import <1>:                    import 语句.        (line    6)
* 陳述式; import <2>:                    內建函式.           (line 1531)
* 陳述式; import <3>:                    site —— 指定域的配置钩子.
                                                             (line   39)
* 陳述式; import <4>:                    imp —— 由代码内部访问 import 。.
                                                             (line   11)
* 陳述式; nonlocal:                      nonlocal 语句.      (line    6)
* 陳述式; pass:                          pass 语句.          (line    6)
* 陳述式; raise:                         raise 语句.         (line    6)
* 陳述式; raise <1>:                     內建的例外.         (line   12)
* 陳述式; return:                        return 语句.        (line    6)
* 陳述式; return <1>:                    try 语句.           (line   62)
* 陳述式; return <2>:                    try 语句.           (line   86)
* 陳述式; try:                           标准类型层级结构.   (line  604)
* 陳述式; try <1>:                       try 语句.           (line    6)
* 陳述式; try <2>:                       內建的例外.         (line    6)
* 陳述式; while:                         break 语句.         (line    6)
* 陳述式; while <1>:                     continue 语句.      (line    6)
* 陳述式; while <2>:                     while 语句.         (line    6)
* 陳述式; while <3>:                     逻辑值检测.         (line    6)
* 陳述式; with:                          with 语句上下文管理器.
                                                             (line   11)
* 陳述式; with <1>:                      with 语句.          (line    6)
* 陳述式; yield:                         yield 语句.         (line    6)

                                                             
                                                             
                                                             



Tag Table:
Node: Top339
Ref: contents doc541
Ref: 14f541
Node: Python 有什麼新功能？186310
Ref: whatsnew/index doc186412
Ref: 150186412
Ref: whatsnew/index python-documentation-contents186412
Ref: 151186412
Ref: whatsnew/index what-s-new-in-python186412
Ref: 152186412
Ref: whatsnew/index whatsnew-index186412
Ref: 153186412
Node: Python 3 9 有什么新变化187939
Ref: whatsnew/3 9 doc188071
Ref: 154188071
Ref: whatsnew/3 9 what-s-new-in-python-3-9188071
Ref: 155188071
Ref: Python 3 9 有什么新变化-Footnote-1189006
Node: 摘要 - 发布重点189055
Ref: whatsnew/3 9 summary-release-highlights189194
Ref: 157189194
Ref: 摘要 - 发布重点-Footnote-1191023
Ref: 摘要 - 发布重点-Footnote-2191072
Ref: 摘要 - 发布重点-Footnote-3191121
Ref: 摘要 - 发布重点-Footnote-4191170
Ref: 摘要 - 发布重点-Footnote-5191219
Ref: 摘要 - 发布重点-Footnote-6191268
Ref: 摘要 - 发布重点-Footnote-7191317
Ref: 摘要 - 发布重点-Footnote-8191366
Ref: 摘要 - 发布重点-Footnote-9191415
Ref: 摘要 - 发布重点-Footnote-10191464
Node: 请检查代码中的 DeprecationWarning。191514
Ref: whatsnew/3 9 you-should-check-for-deprecationwarning-in-your-code191674
Ref: 159191674
Node: 新的特性193195
Ref: whatsnew/3 9 new-features193358
Ref: 162193358
Node: 字典合并与更新运算符193558
Ref: whatsnew/3 9 dictionary-merge-update-operators193697
Ref: 163193697
Ref: 字典合并与更新运算符-Footnote-1194398
Ref: 字典合并与更新运算符-Footnote-2194447
Node: 新增用于移除前缀和后缀的字符串方法194490
Ref: whatsnew/3 9 new-string-methods-to-remove-prefixes-and-suffixes194677
Ref: 165194677
Ref: 新增用于移除前缀和后缀的字符串方法-Footnote-1195162
Ref: 新增用于移除前缀和后缀的字符串方法-Footnote-2195211
Node: 标准多项集中的类型标注泛型195254
Ref: whatsnew/3 9 type-hinting-generics-in-standard-collections195426
Ref: 168195426
Ref: 标准多项集中的类型标注泛型-Footnote-1196083
Ref: 标准多项集中的类型标注泛型-Footnote-2196132
Node: 新的解析器196175
Ref: whatsnew/3 9 new-parser196287
Ref: 169196287
Ref: 新的解析器-Footnote-1197165
Ref: 新的解析器-Footnote-2197230
Ref: 新的解析器-Footnote-3197278
Ref: 新的解析器-Footnote-4197327
Node: 其他语言特性修改197370
Ref: whatsnew/3 9 other-language-changes197502
Ref: 16a197502
Ref: 其他语言特性修改-Footnote-1200548
Ref: 其他语言特性修改-Footnote-2200591
Ref: 其他语言特性修改-Footnote-3200634
Ref: 其他语言特性修改-Footnote-4200677
Ref: 其他语言特性修改-Footnote-5200720
Ref: 其他语言特性修改-Footnote-6200769
Ref: 其他语言特性修改-Footnote-7200812
Ref: 其他语言特性修改-Footnote-8200855
Ref: 其他语言特性修改-Footnote-9200898
Ref: 其他语言特性修改-Footnote-10200941
Ref: 其他语言特性修改-Footnote-11200985
Node: 新增模块201029
Ref: whatsnew/3 9 new-modules201164
Ref: 17d201164
Node: zoneinfo201235
Ref: whatsnew/3 9 zoneinfo201309
Ref: 17e201309
Ref: zoneinfo-Footnote-1202331
Ref: zoneinfo-Footnote-2202372
Node: graphlib202421
Ref: whatsnew/3 9 graphlib202495
Ref: 181202495
Ref: graphlib-Footnote-1202789
Node: 改进的模块202832
Ref: whatsnew/3 9 improved-modules202955
Ref: 183202955
Node: ast203464
Ref: whatsnew/3 9 ast203535
Ref: 184203535
Ref: ast-Footnote-1204234
Ref: ast-Footnote-2204277
Ref: ast-Footnote-3204320
Node: asyncio204363
Ref: whatsnew/3 9 asyncio204453
Ref: 188204453
Ref: asyncio-Footnote-1206158
Ref: asyncio-Footnote-2206201
Ref: asyncio-Footnote-3206244
Ref: asyncio-Footnote-4206287
Ref: asyncio-Footnote-5206330
Ref: asyncio-Footnote-6206373
Node: compileall206416
Ref: whatsnew/3 9 compileall206521
Ref: 193206521
Ref: compileall-Footnote-1207085
Ref: compileall-Footnote-2207128
Node: concurrent futures207171
Ref: whatsnew/3 9 concurrent-futures207275
Ref: 194207275
Ref: concurrent futures-Footnote-1208134
Ref: concurrent futures-Footnote-2208177
Ref: concurrent futures-Footnote-3208220
Node: curses208263
Ref: whatsnew/3 9 curses208365
Ref: 197208365
Ref: curses-Footnote-1208649
Node: datetime208692
Ref: whatsnew/3 9 datetime208785
Ref: 19c208785
Ref: datetime-Footnote-1209113
Node: distutils209156
Ref: whatsnew/3 9 distutils209248
Ref: 1a3209248
Ref: distutils-Footnote-1209508
Node: fcntl209551
Ref: whatsnew/3 9 fcntl209641
Ref: 1a4209641
Ref: fcntl-Footnote-1209842
Node: ftplib209885
Ref: whatsnew/3 9 ftplib209968
Ref: 1a5209968
Ref: ftplib-Footnote-1210259
Node: gc210302
Ref: whatsnew/3 9 gc210387
Ref: 1a8210387
Ref: gc-Footnote-1210896
Ref: gc-Footnote-2210939
Node: hashlib210982
Ref: whatsnew/3 9 hashlib211065
Ref: 1aa211065
Ref: hashlib-Footnote-1211595
Ref: hashlib-Footnote-2211638
Node: http211681
Ref: whatsnew/3 9 http211778
Ref: 1ab211778
Ref: http-Footnote-1212058
Ref: http-Footnote-2212101
Node: IDLE 与 idlelib212144
Ref: whatsnew/3 9 idle-and-idlelib212241
Ref: 1ad212241
Ref: IDLE 与 idlelib-Footnote-1212699
Ref: IDLE 与 idlelib-Footnote-2212741
Ref: IDLE 与 idlelib-Footnote-3212784
Node: imaplib212827
Ref: whatsnew/3 9 imaplib212929
Ref: 1ae212929
Ref: imaplib-Footnote-1213733
Ref: imaplib-Footnote-2213776
Node: importlib213819
Ref: whatsnew/3 9 importlib213912
Ref: 1b5213912
Ref: importlib-Footnote-1214706
Ref: importlib-Footnote-2214749
Ref: importlib-Footnote-3214792
Node: inspect214835
Ref: whatsnew/3 9 inspect214930
Ref: 1b8214930
Ref: inspect-Footnote-1215164
Ref: inspect-Footnote-2215207
Node: ipaddress215250
Ref: whatsnew/3 9 ipaddress215340
Ref: 1ba215340
Ref: ipaddress-Footnote-1215922
Ref: ipaddress-Footnote-2215965
Node: math216008
Ref: whatsnew/3 9 math216106
Ref: 1bd216106
Ref: math-Footnote-1216829
Ref: math-Footnote-2216872
Ref: math-Footnote-3216915
Ref: math-Footnote-4216958
Ref: math-Footnote-5217001
Node: multiprocessing217044
Ref: whatsnew/3 9 multiprocessing217140
Ref: 1c2217140
Ref: multiprocessing-Footnote-1217394
Node: nntplib217437
Ref: whatsnew/3 9 nntplib217531
Ref: 1c5217531
Ref: nntplib-Footnote-1217828
Node: os217871
Ref: whatsnew/3 9 os217957
Ref: 1c8217957
Ref: os-Footnote-1218736
Ref: os-Footnote-2218779
Ref: os-Footnote-3218822
Ref: os-Footnote-4218865
Ref: os-Footnote-5218908
Ref: os-Footnote-6218951
Node: pathlib218994
Ref: whatsnew/3 9 pathlib219076
Ref: 1cf219076
Ref: pathlib-Footnote-1219300
Node: pdb219343
Ref: whatsnew/3 9 pdb219429
Ref: 1d2219429
Ref: pdb-Footnote-1219629
Node: poplib219672
Ref: whatsnew/3 9 poplib219757
Ref: 1d4219757
Ref: poplib-Footnote-1220052
Node: pprint220095
Ref: whatsnew/3 9 pprint220182
Ref: 1d7220182
Ref: pprint-Footnote-1220390
Node: pydoc220433
Ref: whatsnew/3 9 pydoc220520
Ref: 1d9220520
Ref: pydoc-Footnote-1220778
Node: random220821
Ref: whatsnew/3 9 random220908
Ref: 1da220908
Ref: random-Footnote-1221113
Node: signal221156
Ref: whatsnew/3 9 signal221245
Ref: 1db221245
Ref: signal-Footnote-1221468
Node: smtplib221511
Ref: whatsnew/3 9 smtplib221600
Ref: 1dd221600
Ref: smtplib-Footnote-1222019
Ref: smtplib-Footnote-2222062
Node: socket222105
Ref: whatsnew/3 9 socket222192
Ref: 1e1222192
Ref: socket-Footnote-1222778
Ref: socket-Footnote-2222821
Ref: socket-Footnote-3222864
Node: time222907
Ref: whatsnew/3 9 time222990
Ref: 1e6222990
Ref: time-Footnote-1223311
Node: sys223354
Ref: whatsnew/3 9 sys223442
Ref: 1e8223442
Ref: sys-Footnote-1224091
Ref: sys-Footnote-2224136
Node: tracemalloc224179
Ref: whatsnew/3 9 tracemalloc224269
Ref: 1eb224269
Ref: tracemalloc-Footnote-1224547
Node: typing224590
Ref: whatsnew/3 9 typing224688
Ref: 1ed224688
Ref: typing-Footnote-1225058
Node: unicodedata225107
Ref: whatsnew/3 9 unicodedata225198
Ref: 1f0225198
Ref: unicodedata-Footnote-1225340
Node: venv225383
Ref: whatsnew/3 9 venv225471
Ref: 1f1225471
Ref: venv-Footnote-1225951
Node: xml225994
Ref: whatsnew/3 9 xml226062
Ref: 1f2226062
Ref: xml-Footnote-1226427
Node: 性能优化226470
Ref: whatsnew/3 9 optimizations226587
Ref: 1f3226587
Ref: 性能优化-Footnote-1232267
Ref: 性能优化-Footnote-2232310
Ref: 性能优化-Footnote-3232353
Ref: 性能优化-Footnote-4232396
Ref: 性能优化-Footnote-5232439
Ref: 性能优化-Footnote-6232488
Ref: 性能优化-Footnote-7232531
Ref: 性能优化-Footnote-8232573
Ref: 性能优化-Footnote-9232616
Ref: 性能优化-Footnote-10232659
Ref: 性能优化-Footnote-11232703
Ref: 性能优化-Footnote-12232832
Node: 弃用232883
Ref: whatsnew/3 9 deprecated232991
Ref: 1fb232991
Ref: 弃用-Footnote-1237913
Ref: 弃用-Footnote-2237956
Ref: 弃用-Footnote-3237999
Ref: 弃用-Footnote-4238042
Ref: 弃用-Footnote-5238085
Ref: 弃用-Footnote-6238128
Ref: 弃用-Footnote-7238171
Ref: 弃用-Footnote-8238214
Ref: 弃用-Footnote-9238257
Ref: 弃用-Footnote-10238300
Ref: 弃用-Footnote-11238344
Ref: 弃用-Footnote-12238388
Ref: 弃用-Footnote-13238432
Ref: 弃用-Footnote-14238476
Ref: 弃用-Footnote-15238520
Ref: 弃用-Footnote-16238570
Ref: 弃用-Footnote-17238610
Ref: 弃用-Footnote-18238649
Ref: 弃用-Footnote-19238693
Node: 移除238737
Ref: whatsnew/3 9 removed238853
Ref: 213238853
Ref: whatsnew/3 9 removed-in-python-39238853
Ref: 161238853
Ref: 移除-Footnote-1244859
Ref: 移除-Footnote-2244902
Ref: 移除-Footnote-3244945
Ref: 移除-Footnote-4244988
Ref: 移除-Footnote-5245031
Ref: 移除-Footnote-6245074
Ref: 移除-Footnote-7245117
Ref: 移除-Footnote-8245160
Ref: 移除-Footnote-9245203
Ref: 移除-Footnote-10245246
Ref: 移除-Footnote-11245290
Ref: 移除-Footnote-12245340
Ref: 移除-Footnote-13245384
Ref: 移除-Footnote-14245428
Ref: 移除-Footnote-15245472
Ref: 移除-Footnote-16245516
Ref: 移除-Footnote-17245560
Ref: 移除-Footnote-18245604
Ref: 移除-Footnote-19245648
Ref: 移除-Footnote-20245692
Ref: 移除-Footnote-21245736
Ref: 移除-Footnote-22245780
Node: 移植到 Python 3 9245824
Ref: whatsnew/3 9 porting-to-python-3-9245949
Ref: 22c245949
Node: Python API 的变化246179
Ref: whatsnew/3 9 changes-in-the-python-api246280
Ref: 22d246280
Ref: Python API 的变化-Footnote-1250338
Ref: Python API 的变化-Footnote-2250381
Ref: Python API 的变化-Footnote-3250424
Ref: Python API 的变化-Footnote-4250467
Ref: Python API 的变化-Footnote-5250516
Ref: Python API 的变化-Footnote-6250559
Ref: Python API 的变化-Footnote-7250602
Ref: Python API 的变化-Footnote-8250645
Ref: Python API 的变化-Footnote-9250688
Ref: Python API 的变化-Footnote-10250731
Ref: Python API 的变化-Footnote-11250775
Node: C API 的变化250819
Ref: whatsnew/3 9 changes-in-the-c-api250955
Ref: 239250955
Ref: C API 的变化-Footnote-1253031
Ref: C API 的变化-Footnote-2253074
Ref: C API 的变化-Footnote-3253117
Node: CPython 字节码的改变253160
Ref: whatsnew/3 9 cpython-bytecode-changes253267
Ref: 23d253267
Ref: CPython 字节码的改变-Footnote-1254053
Ref: CPython 字节码的改变-Footnote-2254096
Node: 构建的改变254139
Ref: whatsnew/3 9 build-changes254273
Ref: 242254273
Ref: 构建的改变-Footnote-1256640
Ref: 构建的改变-Footnote-2256685
Ref: 构建的改变-Footnote-3256728
Ref: 构建的改变-Footnote-4256771
Ref: 构建的改变-Footnote-5256814
Ref: 构建的改变-Footnote-6256857
Ref: 构建的改变-Footnote-7256900
Ref: 构建的改变-Footnote-8256943
Node: C API 的改变256986
Ref: whatsnew/3 9 c-api-changes257131
Ref: 243257131
Node: 新的特性<2>257288
Ref: whatsnew/3 9 id1257387
Ref: 244257387
Ref: 新的特性<2>-Footnote-1260363
Ref: 新的特性<2>-Footnote-2260412
Ref: 新的特性<2>-Footnote-3260455
Ref: 新的特性<2>-Footnote-4260498
Ref: 新的特性<2>-Footnote-5260541
Ref: 新的特性<2>-Footnote-6260584
Ref: 新的特性<2>-Footnote-7260627
Ref: 新的特性<2>-Footnote-8260670
Ref: 新的特性<2>-Footnote-9260713
Ref: 新的特性<2>-Footnote-10260756
Ref: 新的特性<2>-Footnote-11260800
Ref: 新的特性<2>-Footnote-12260844
Node: 移植到 Python 3 9<2>260888
Ref: whatsnew/3 9 id2261005
Ref: 257261005
Ref: 移植到 Python 3 9<2>-Footnote-1264571
Ref: 移植到 Python 3 9<2>-Footnote-2264620
Ref: 移植到 Python 3 9<2>-Footnote-3264663
Ref: 移植到 Python 3 9<2>-Footnote-4264706
Ref: 移植到 Python 3 9<2>-Footnote-5264748
Ref: 移植到 Python 3 9<2>-Footnote-6264791
Ref: 移植到 Python 3 9<2>-Footnote-7264834
Ref: 移植到 Python 3 9<2>-Footnote-8264883
Ref: 移植到 Python 3 9<2>-Footnote-9264926
Ref: 移植到 Python 3 9<2>-Footnote-10264969
Ref: 移植到 Python 3 9<2>-Footnote-11265013
Node: 移除<2>265057
Ref: whatsnew/3 9 id3265150
Ref: 270265150
Ref: 移除<2>-Footnote-1269009
Ref: 移除<2>-Footnote-2269052
Ref: 移除<2>-Footnote-3269095
Ref: 移除<2>-Footnote-4269138
Ref: 移除<2>-Footnote-5269181
Ref: 移除<2>-Footnote-6269224
Ref: 移除<2>-Footnote-7269267
Ref: 移除<2>-Footnote-8269310
Ref: 移除<2>-Footnote-9269353
Ref: 移除<2>-Footnote-10269396
Ref: 移除<2>-Footnote-11269440
Ref: 移除<2>-Footnote-12269490
Ref: 移除<2>-Footnote-13269534
Node: Python 3 9 1 中的重要变化269578
Ref: whatsnew/3 9 notable-changes-in-python-3-9-1269739
Ref: 273269739
Node: typing<2>269945
Ref: whatsnew/3 9 id4270078
Ref: 274270078
Ref: typing<2>-Footnote-1271192
Ref: typing<2>-Footnote-2271241
Node: macOS 11 0 Big Sur 与 Apple Silicon Mac 支持271284
Ref: whatsnew/3 9 macos-11-0-big-sur-and-apple-silicon-mac-support271417
Ref: 277271417
Ref: macOS 11 0 Big Sur 与 Apple Silicon Mac 支持-Footnote-1272199
Node: Python 3 9 2 中的重要变化272242
Ref: whatsnew/3 9 notable-changes-in-python-3-9-2272419
Ref: 278272419
Node: collections abc272568
Ref: whatsnew/3 9 collections-abc272672
Ref: 279272672
Ref: collections abc-Footnote-1273640
Node: urllib parse273683
Ref: whatsnew/3 9 urllib-parse273787
Ref: 27e273787
Ref: urllib parse-Footnote-1274454
Node: Python 3 9 3 中的重要变化274497
Ref: whatsnew/3 9 notable-changes-in-python-3-9-3274674
Ref: 283274674
Ref: Python 3 9 3 中的重要变化-Footnote-1275167
Node: Python 3 9 5 中的重要变化275210
Ref: whatsnew/3 9 notable-changes-in-python-3-9-5275347
Ref: 284275347
Node: urllib parse<2>275463
Ref: whatsnew/3 9 id5275546
Ref: 285275546
Ref: urllib parse<2>-Footnote-1276039
Ref: urllib parse<2>-Footnote-2276088
Node: Python 3 8 有什么新变化276131
Ref: whatsnew/3 8 doc276301
Ref: 286276301
Ref: whatsnew/3 8 what-s-new-in-python-3-8276301
Ref: 287276301
Node: 摘要 - 发布重点<2>277089
Ref: whatsnew/3 8 summary-release-highlights277203
Ref: 288277203
Node: 新的特性<3>277254
Ref: whatsnew/3 8 new-features277404
Ref: 289277404
Node: 赋值表达式277987
Ref: whatsnew/3 8 assignment-expressions278081
Ref: 28a278081
Ref: 赋值表达式-Footnote-1279500
Ref: 赋值表达式-Footnote-2279597
Ref: 赋值表达式-Footnote-3279646
Node: 仅限位置形参279689
Ref: whatsnew/3 8 positional-only-parameters279849
Ref: 28c279849
Ref: 仅限位置形参-Footnote-1282302
Ref: 仅限位置形参-Footnote-2282354
Ref: 仅限位置形参-Footnote-3282403
Node: 用于已编译字节码文件的并行文件系统缓存282446
Ref: whatsnew/3 8 parallel-filesystem-cache-for-compiled-bytecode-files282637
Ref: 28e282637
Ref: 用于已编译字节码文件的并行文件系统缓存-Footnote-1283233
Node: 调试构建使用与发布构建相同的 ABI283276
Ref: whatsnew/3 8 debug-build-uses-the-same-abi-as-release-build283511
Ref: 292283511
Ref: 调试构建使用与发布构建相同的 ABI-Footnote-1285830
Ref: 调试构建使用与发布构建相同的 ABI-Footnote-2285873
Ref: 调试构建使用与发布构建相同的 ABI-Footnote-3285916
Ref: 调试构建使用与发布构建相同的 ABI-Footnote-4285959
Node: f-字符串支持 = 用于自动记录表达式和调试文档286002
Ref: whatsnew/3 8 f-strings-support-for-self-documenting-expressions-and-debugging286216
Ref: 294286216
Ref: f-字符串支持 = 用于自动记录表达式和调试文档-Footnote-1287238
Node: PEP 578 Python 运行时审核钩子287281
Ref: whatsnew/3 8 pep-578-python-runtime-audit-hooks287479
Ref: 297287479
Ref: PEP 578 Python 运行时审核钩子-Footnote-1287913
Node: PEP 587 Python 初始化配置287962
Ref: whatsnew/3 8 pep-587-python-initialization-configuration288153
Ref: 298288153
Ref: PEP 587 Python 初始化配置-Footnote-1290069
Ref: PEP 587 Python 初始化配置-Footnote-2290118
Ref: PEP 587 Python 初始化配置-Footnote-3290167
Node: PEP 590 Vectorcall 用于 CPython 的快速调用协议290210
Ref: whatsnew/3 8 pep-590-vectorcall-a-fast-calling-protocol-for-cpython290411
Ref: 2b7290411
Ref: PEP 590 Vectorcall 用于 CPython 的快速调用协议-Footnote-1290981
Ref: PEP 590 Vectorcall 用于 CPython 的快速调用协议-Footnote-2291030
Node: 具有外部数据缓冲区的 pickle 协议 5291073
Ref: whatsnew/3 8 pickle-protocol-5-with-out-of-band-data-buffers291235
Ref: 2b9291235
Ref: 具有外部数据缓冲区的 pickle 协议 5-Footnote-1291906
Ref: 具有外部数据缓冲区的 pickle 协议 5-Footnote-2291955
Ref: 具有外部数据缓冲区的 pickle 协议 5-Footnote-3292004
Node: 其他语言特性修改<2>292047
Ref: whatsnew/3 8 other-language-changes292188
Ref: 2ba292188
Ref: 其他语言特性修改<2>-Footnote-1299228
Ref: 其他语言特性修改<2>-Footnote-2299271
Ref: 其他语言特性修改<2>-Footnote-3299314
Ref: 其他语言特性修改<2>-Footnote-4299357
Ref: 其他语言特性修改<2>-Footnote-5299400
Ref: 其他语言特性修改<2>-Footnote-6299443
Ref: 其他语言特性修改<2>-Footnote-7299486
Ref: 其他语言特性修改<2>-Footnote-8299529
Ref: 其他语言特性修改<2>-Footnote-9299572
Ref: 其他语言特性修改<2>-Footnote-10299615
Ref: 其他语言特性修改<2>-Footnote-11299659
Ref: 其他语言特性修改<2>-Footnote-12299705
Ref: 其他语言特性修改<2>-Footnote-13299749
Ref: 其他语言特性修改<2>-Footnote-14299819
Ref: 其他语言特性修改<2>-Footnote-15299879
Ref: 其他语言特性修改<2>-Footnote-16299923
Ref: 其他语言特性修改<2>-Footnote-17299967
Node: 新增模块<2>300011
Ref: whatsnew/3 8 new-modules300155
Ref: 2d2300155
Ref: 新增模块<2>-Footnote-1301204
Node: 改进的模块<2>301247
Ref: whatsnew/3 8 improved-modules301379
Ref: 2d3301379
Node: ast<2>302192
Ref: whatsnew/3 8 ast302272
Ref: 2d4302272
Ref: ast<2>-Footnote-1303257
Ref: ast<2>-Footnote-2303300
Ref: ast<2>-Footnote-3303349
Ref: ast<2>-Footnote-4303398
Ref: ast<2>-Footnote-5303447
Node: asyncio<2>303490
Ref: whatsnew/3 8 asyncio303587
Ref: 2d9303587
Ref: asyncio<2>-Footnote-1306711
Ref: asyncio<2>-Footnote-2306754
Ref: asyncio<2>-Footnote-3306797
Ref: asyncio<2>-Footnote-4306840
Ref: asyncio<2>-Footnote-5306883
Ref: asyncio<2>-Footnote-6306926
Ref: asyncio<2>-Footnote-7306969
Ref: asyncio<2>-Footnote-8307012
Ref: asyncio<2>-Footnote-9307055
Ref: asyncio<2>-Footnote-10307108
Node: builtins307152
Ref: whatsnew/3 8 builtins307254
Ref: 2e6307254
Ref: builtins-Footnote-1307724
Node: collections307767
Ref: whatsnew/3 8 collections307867
Ref: 2e8307867
Ref: collections-Footnote-1308394
Node: cProfile308437
Ref: whatsnew/3 8 cprofile308532
Ref: 2eb308532
Ref: cProfile-Footnote-1308897
Node: csv308940
Ref: whatsnew/3 8 csv309033
Ref: 2ed309033
Ref: csv-Footnote-1309341
Node: curses<2>309384
Ref: whatsnew/3 8 curses309475
Ref: 2ef309475
Ref: curses<2>-Footnote-1309705
Node: ctypes309748
Ref: whatsnew/3 8 ctypes309847
Ref: 2f1309847
Ref: ctypes-Footnote-1310329
Node: datetime<2>310372
Ref: whatsnew/3 8 datetime310471
Ref: 2f4310471
Ref: datetime<2>-Footnote-1310917
Node: functools310960
Ref: whatsnew/3 8 functools311058
Ref: 2f7311058
Ref: functools-Footnote-1312606
Ref: functools-Footnote-2312649
Ref: functools-Footnote-3312692
Node: gc<2>312735
Ref: whatsnew/3 8 gc312829
Ref: 2fd312829
Ref: gc<2>-Footnote-1313071
Node: gettext313114
Ref: whatsnew/3 8 gettext313203
Ref: 2ff313203
Ref: gettext-Footnote-1313416
Node: gzip313458
Ref: whatsnew/3 8 gzip313561
Ref: 301313561
Ref: gzip-Footnote-1313977
Ref: gzip-Footnote-2314020
Node: IDLE 与 idlelib<2>314062
Ref: whatsnew/3 8 idle-and-idlelib314168
Ref: 305314168
Ref: IDLE 与 idlelib<2>-Footnote-1316129
Ref: IDLE 与 idlelib<2>-Footnote-2316174
Ref: IDLE 与 idlelib<2>-Footnote-3316216
Ref: IDLE 与 idlelib<2>-Footnote-4316259
Ref: IDLE 与 idlelib<2>-Footnote-5316302
Ref: IDLE 与 idlelib<2>-Footnote-6316345
Ref: IDLE 与 idlelib<2>-Footnote-7316387
Ref: IDLE 与 idlelib<2>-Footnote-8316430
Node: inspect<2>316473
Ref: whatsnew/3 8 inspect316577
Ref: 306316577
Ref: inspect<2>-Footnote-1317354
Node: io317397
Ref: whatsnew/3 8 io317491
Ref: 30b317491
Ref: io-Footnote-1317833
Node: itertools317876
Ref: whatsnew/3 8 itertools317969
Ref: 30d317969
Ref: itertools-Footnote-1318348
Node: json tool318391
Ref: whatsnew/3 8 json-tool318489
Ref: 30f318489
Ref: json tool-Footnote-1318708
Node: logging318751
Ref: whatsnew/3 8 logging318847
Ref: 310318847
Ref: logging-Footnote-1319549
Node: math<2>319592
Ref: whatsnew/3 8 math319683
Ref: 312319683
Ref: math<2>-Footnote-1321391
Ref: math<2>-Footnote-2321434
Ref: math<2>-Footnote-3321477
Ref: math<2>-Footnote-4321520
Ref: math<2>-Footnote-5321563
Ref: math<2>-Footnote-6321606
Ref: math<2>-Footnote-7321649
Ref: math<2>-Footnote-8321692
Node: mmap321735
Ref: whatsnew/3 8 mmap321837
Ref: 31b321837
Ref: mmap-Footnote-1322074
Node: multiprocessing<2>322117
Ref: whatsnew/3 8 multiprocessing322217
Ref: 31e322217
Ref: multiprocessing<2>-Footnote-1322553
Ref: multiprocessing<2>-Footnote-2322596
Node: os<2>322639
Ref: whatsnew/3 8 os322742
Ref: 31f322742
Ref: os<2>-Footnote-1324201
Ref: os<2>-Footnote-2324244
Ref: os<2>-Footnote-3324287
Node: os path324330
Ref: whatsnew/3 8 os-path324425
Ref: 324324425
Ref: os path-Footnote-1325437
Ref: os path-Footnote-2325480
Ref: os path-Footnote-3325523
Node: pathlib<2>325566
Ref: whatsnew/3 8 pathlib325662
Ref: 32e325662
Ref: pathlib<2>-Footnote-1326402
Ref: pathlib<2>-Footnote-2326445
Node: pickle326488
Ref: whatsnew/3 8 pickle326585
Ref: 33a326585
Ref: pickle-Footnote-1326909
Node: plistlib326952
Ref: whatsnew/3 8 plistlib327048
Ref: 33d327048
Ref: plistlib-Footnote-1327306
Node: pprint<2>327349
Ref: whatsnew/3 8 pprint327449
Ref: 33f327449
Ref: pprint<2>-Footnote-1328494
Node: py_compile328537
Ref: whatsnew/3 8 py-compile328634
Ref: 342328634
Ref: py_compile-Footnote-1328830
Node: shlex328873
Ref: whatsnew/3 8 shlex328967
Ref: 344328967
Ref: shlex-Footnote-1329176
Node: shutil329219
Ref: whatsnew/3 8 shutil329312
Ref: 346329312
Ref: shutil-Footnote-1329959
Ref: shutil-Footnote-2330002
Ref: shutil-Footnote-3330045
Node: socket<2>330088
Ref: whatsnew/3 8 socket330179
Ref: 34a330179
Ref: socket<2>-Footnote-1330742
Ref: socket<2>-Footnote-2330785
Node: ssl330828
Ref: whatsnew/3 8 ssl330923
Ref: 350330923
Ref: ssl-Footnote-1331186
Node: statistics331229
Ref: whatsnew/3 8 statistics331321
Ref: 353331321
Ref: statistics-Footnote-1333061
Ref: statistics-Footnote-2333104
Ref: statistics-Footnote-3333147
Ref: statistics-Footnote-4333190
Ref: statistics-Footnote-5333233
Node: sys<2>333276
Ref: whatsnew/3 8 sys333372
Ref: 359333372
Ref: sys<2>-Footnote-1333789
Node: tarfile333832
Ref: whatsnew/3 8 tarfile333927
Ref: 35c333927
Ref: tarfile-Footnote-1334315
Node: threading334358
Ref: whatsnew/3 8 threading334455
Ref: 35d334455
Ref: threading-Footnote-1335163
Ref: threading-Footnote-2335208
Node: tokenize335251
Ref: whatsnew/3 8 tokenize335348
Ref: 362335348
Ref: tokenize-Footnote-1335659
Node: tkinter335702
Ref: whatsnew/3 8 tkinter335797
Ref: 363335797
Ref: tkinter-Footnote-1336356
Ref: tkinter-Footnote-2336399
Ref: tkinter-Footnote-3336442
Node: time<2>336485
Ref: whatsnew/3 8 time336581
Ref: 364336581
Ref: time<2>-Footnote-1336774
Node: typing<3>336817
Ref: whatsnew/3 8 typing336920
Ref: 366336920
Ref: typing<3>-Footnote-1338347
Ref: typing<3>-Footnote-2338396
Ref: typing<3>-Footnote-3338445
Ref: typing<3>-Footnote-4338494
Node: unicodedata<2>338543
Ref: whatsnew/3 8 unicodedata338647
Ref: 36f338647
Ref: unicodedata<2>-Footnote-1339071
Ref: unicodedata<2>-Footnote-2339132
Ref: unicodedata<2>-Footnote-3339175
Node: unittest339218
Ref: whatsnew/3 8 unittest339320
Ref: 371339320
Ref: unittest-Footnote-1340608
Ref: unittest-Footnote-2340651
Ref: unittest-Footnote-3340694
Ref: unittest-Footnote-4340737
Node: venv<2>340780
Ref: whatsnew/3 8 venv340875
Ref: 378340875
Ref: venv<2>-Footnote-1341130
Node: weakref341173
Ref: whatsnew/3 8 weakref341266
Ref: 379341266
Ref: weakref-Footnote-1341536
Node: xml<2>341579
Ref: whatsnew/3 8 xml341671
Ref: 37b341671
Ref: xml<2>-Footnote-1342788
Ref: xml<2>-Footnote-2342831
Ref: xml<2>-Footnote-3342874
Ref: xml<2>-Footnote-4342917
Ref: xml<2>-Footnote-5342960
Node: xmlrpc343003
Ref: whatsnew/3 8 xmlrpc343079
Ref: 37e343079
Ref: xmlrpc-Footnote-1343451
Node: 性能优化<2>343494
Ref: whatsnew/3 8 optimizations343636
Ref: 380343636
Ref: 性能优化<2>-Footnote-1347989
Ref: 性能优化<2>-Footnote-2348032
Ref: 性能优化<2>-Footnote-3348075
Ref: 性能优化<2>-Footnote-4348118
Ref: 性能优化<2>-Footnote-5348161
Ref: 性能优化<2>-Footnote-6348204
Ref: 性能优化<2>-Footnote-7348247
Ref: 性能优化<2>-Footnote-8348290
Ref: 性能优化<2>-Footnote-9348333
Ref: 性能优化<2>-Footnote-10348376
Ref: 性能优化<2>-Footnote-11348420
Ref: 性能优化<2>-Footnote-12348464
Ref: 性能优化<2>-Footnote-13348508
Node: 构建和 C API 的改变348552
Ref: whatsnew/3 8 build-and-c-api-changes348685
Ref: 38c348685
Ref: 构建和 C API 的改变-Footnote-1354006
Ref: 构建和 C API 的改变-Footnote-2354049
Ref: 构建和 C API 的改变-Footnote-3354092
Ref: 构建和 C API 的改变-Footnote-4354135
Ref: 构建和 C API 的改变-Footnote-5354178
Ref: 构建和 C API 的改变-Footnote-6354221
Ref: 构建和 C API 的改变-Footnote-7354264
Ref: 构建和 C API 的改变-Footnote-8354307
Ref: 构建和 C API 的改变-Footnote-9354350
Ref: 构建和 C API 的改变-Footnote-10354393
Ref: 构建和 C API 的改变-Footnote-11354437
Ref: 构建和 C API 的改变-Footnote-12354481
Node: 弃用<2>354525
Ref: whatsnew/3 8 deprecated354665
Ref: 3a0354665
Ref: 弃用<2>-Footnote-1360340
Ref: 弃用<2>-Footnote-2360383
Ref: 弃用<2>-Footnote-3360426
Ref: 弃用<2>-Footnote-4360469
Ref: 弃用<2>-Footnote-5360511
Ref: 弃用<2>-Footnote-6360554
Ref: 弃用<2>-Footnote-7360597
Ref: 弃用<2>-Footnote-8360640
Ref: 弃用<2>-Footnote-9360683
Ref: 弃用<2>-Footnote-10360726
Ref: 弃用<2>-Footnote-11360770
Ref: 弃用<2>-Footnote-12360814
Ref: 弃用<2>-Footnote-13360858
Node: API 与特性的移除360902
Ref: whatsnew/3 8 api-and-feature-removals361037
Ref: 3ca361037
Ref: API 与特性的移除-Footnote-1363815
Ref: API 与特性的移除-Footnote-2363858
Ref: API 与特性的移除-Footnote-3363901
Ref: API 与特性的移除-Footnote-4363944
Ref: API 与特性的移除-Footnote-5363987
Ref: API 与特性的移除-Footnote-6364030
Ref: API 与特性的移除-Footnote-7364073
Ref: API 与特性的移除-Footnote-8364116
Ref: API 与特性的移除-Footnote-9364159
Ref: API 与特性的移除-Footnote-10364202
Ref: API 与特性的移除-Footnote-11364246
Node: 移植到 Python 3 8364290
Ref: whatsnew/3 8 porting-to-python-3-8364447
Ref: 3d0364447
Node: Python 行为的改变364756
Ref: whatsnew/3 8 changes-in-python-behavior364863
Ref: 3d1364863
Ref: Python 行为的改变-Footnote-1367140
Ref: Python 行为的改变-Footnote-2367183
Ref: Python 行为的改变-Footnote-3367226
Ref: Python 行为的改变-Footnote-4367269
Ref: Python 行为的改变-Footnote-5367312
Ref: Python 行为的改变-Footnote-6367355
Node: 更改的Python API367398
Ref: whatsnew/3 8 changes-in-the-python-api367532
Ref: 3d9367532
Ref: whatsnew/3 8 bpo-36085-whatsnew374326
Ref: 3ec374326
Ref: 更改的Python API-Footnote-1375727
Ref: 更改的Python API-Footnote-2375776
Ref: 更改的Python API-Footnote-3375819
Ref: 更改的Python API-Footnote-4375862
Ref: 更改的Python API-Footnote-5375905
Ref: 更改的Python API-Footnote-6375948
Ref: 更改的Python API-Footnote-7375991
Ref: 更改的Python API-Footnote-8376034
Ref: 更改的Python API-Footnote-9376077
Ref: 更改的Python API-Footnote-10376120
Ref: 更改的Python API-Footnote-11376164
Ref: 更改的Python API-Footnote-12376208
Ref: 更改的Python API-Footnote-13376252
Ref: 更改的Python API-Footnote-14376296
Ref: 更改的Python API-Footnote-15376340
Ref: 更改的Python API-Footnote-16376384
Ref: 更改的Python API-Footnote-17376428
Ref: 更改的Python API-Footnote-18376471
Ref: 更改的Python API-Footnote-19376515
Ref: 更改的Python API-Footnote-20376559
Ref: 更改的Python API-Footnote-21376603
Ref: 更改的Python API-Footnote-22376647
Ref: 更改的Python API-Footnote-23376691
Ref: 更改的Python API-Footnote-24376735
Ref: 更改的Python API-Footnote-25376779
Ref: 更改的Python API-Footnote-26376823
Ref: 更改的Python API-Footnote-27376867
Node: C API 中的改变376917
Ref: whatsnew/3 8 changes-in-the-c-api377058
Ref: 3ed377058
Ref: C API 中的改变-Footnote-1382677
Ref: C API 中的改变-Footnote-2382720
Ref: C API 中的改变-Footnote-3382763
Ref: C API 中的改变-Footnote-4382806
Ref: C API 中的改变-Footnote-5382849
Ref: C API 中的改变-Footnote-6382892
Ref: C API 中的改变-Footnote-7382935
Ref: C API 中的改变-Footnote-8382978
Node: CPython 字节码的改变<2>383021
Ref: whatsnew/3 8 cpython-bytecode-changes383158
Ref: 3f9383158
Ref: CPython 字节码的改变<2>-Footnote-1384394
Ref: CPython 字节码的改变<2>-Footnote-2384437
Ref: CPython 字节码的改变<2>-Footnote-3384480
Ref: CPython 字节码的改变<2>-Footnote-4384529
Node: 演示和工具384572
Ref: whatsnew/3 8 demos-and-tools384682
Ref: 3ff384682
Ref: 演示和工具-Footnote-1387979
Ref: 演示和工具-Footnote-2388022
Ref: 演示和工具-Footnote-3388150
Node: Python 3 8 1 中的重要变化388200
Ref: whatsnew/3 8 notable-changes-in-python-3-8-1388366
Ref: 400388366
Ref: Python 3 8 1 中的重要变化-Footnote-1388847
Node: Python 3 8 8 中的重要变化388890
Ref: whatsnew/3 8 notable-changes-in-python-3-8-8389068
Ref: 401389068
Ref: Python 3 8 8 中的重要变化-Footnote-1389763
Node: Notable changes in Python 3 8 12389806
Ref: whatsnew/3 8 notable-changes-in-python-3-8-12389944
Ref: 402389944
Ref: Notable changes in Python 3 8 12-Footnote-1390565
Node: Python 3 7 有什么新变化390608
Ref: whatsnew/3 7 doc390778
Ref: 403390778
Ref: whatsnew/3 7 what-s-new-in-python-3-7390778
Ref: 404390778
Node: 摘要 - 发布重点<3>391980
Ref: whatsnew/3 7 summary-release-highlights392094
Ref: 405392094
Ref: 摘要 - 发布重点<3>-Footnote-1394029
Ref: 摘要 - 发布重点<3>-Footnote-2394109
Ref: 摘要 - 发布重点<3>-Footnote-3394145
Ref: 摘要 - 发布重点<3>-Footnote-4394181
Node: 新的特性<4>394217
Ref: whatsnew/3 7 new-features394367
Ref: 41a394367
Node: PEP 563：延迟的标注求值395373
Ref: whatsnew/3 7 pep-563-postponed-evaluation-of-annotations395500
Ref: 41b395500
Ref: whatsnew/3 7 whatsnew37-pep563395500
Ref: 406395500
Ref: PEP 563：延迟的标注求值-Footnote-1397058
Ref: PEP 563：延迟的标注求值-Footnote-2397107
Ref: PEP 563：延迟的标注求值-Footnote-3397156
Node: PEP 538 传统 C 区域强制转换397205
Ref: whatsnew/3 7 pep-538-legacy-c-locale-coercion397377
Ref: 41c397377
Ref: whatsnew/3 7 whatsnew37-pep538397377
Ref: 411397377
Ref: PEP 538 传统 C 区域强制转换-Footnote-1399623
Ref: PEP 538 传统 C 区域强制转换-Footnote-2399672
Ref: PEP 538 传统 C 区域强制转换-Footnote-3399721
Ref: PEP 538 传统 C 区域强制转换-Footnote-4399770
Node: PEP 540 强制 UTF-8 运行时模式399819
Ref: whatsnew/3 7 pep-540-forced-utf-8-runtime-mode399988
Ref: 420399988
Ref: whatsnew/3 7 whatsnew37-pep540399988
Ref: 412399988
Ref: PEP 540 强制 UTF-8 运行时模式-Footnote-1401426
Ref: PEP 540 强制 UTF-8 运行时模式-Footnote-2401475
Ref: PEP 540 强制 UTF-8 运行时模式-Footnote-3401524
Node: PEP 553 内置的 breakpoint401573
Ref: whatsnew/3 7 pep-553-built-in-breakpoint401751
Ref: 422401751
Ref: whatsnew/3 7 whatsnew37-pep553401751
Ref: 40a401751
Ref: PEP 553 内置的 breakpoint-Footnote-1402578
Node: PEP 539 用于线程局部存储的新 C API402627
Ref: whatsnew/3 7 pep-539-new-c-api-for-thread-local-storage402807
Ref: 425402807
Ref: whatsnew/3 7 whatsnew37-pep539402807
Ref: 416402807
Ref: PEP 539 用于线程局部存储的新 C API-Footnote-1404224
Ref: PEP 539 用于线程局部存储的新 C API-Footnote-2404273
Node: PEP 562 定制对模块属性的访问404322
Ref: whatsnew/3 7 pep-562-customization-of-access-to-module-attributes404521
Ref: 429404521
Ref: whatsnew/3 7 whatsnew37-pep562404521
Ref: 40c404521
Ref: PEP 562 定制对模块属性的访问-Footnote-1405054
Node: PEP 564 具有纳秒级精度的新时间函数405103
Ref: whatsnew/3 7 pep-564-new-time-functions-with-nanosecond-resolution405307
Ref: 42c405307
Ref: whatsnew/3 7 whatsnew37-pep564405307
Ref: 410405307
Ref: PEP 564 具有纳秒级精度的新时间函数-Footnote-1406269
Ref: PEP 564 具有纳秒级精度的新时间函数-Footnote-2406318
Ref: PEP 564 具有纳秒级精度的新时间函数-Footnote-3406403
Node: PEP 565 在 __main__ 中显示 DeprecationWarning406452
Ref: whatsnew/3 7 pep-565-show-deprecationwarning-in-main406673
Ref: 434406673
Ref: whatsnew/3 7 whatsnew37-pep565406673
Ref: 415406673
Ref: PEP 565 在 __main__ 中显示 DeprecationWarning-Footnote-1408492
Node: PEP 560 对 typing 模块和泛型类型的核心支持408541
Ref: whatsnew/3 7 pep-560-core-support-for-typing-module-and-generic-types408752
Ref: 436408752
Ref: whatsnew/3 7 whatsnew37-pep560408752
Ref: 40d408752
Ref: PEP 560 对 typing 模块和泛型类型的核心支持-Footnote-1409648
Ref: PEP 560 对 typing 模块和泛型类型的核心支持-Footnote-2409697
Node: PEP 552 基于哈希值的 pyc 文件409746
Ref: whatsnew/3 7 pep-552-hash-based-pyc-files409935
Ref: 438409935
Ref: whatsnew/3 7 whatsnew37-pep552409935
Ref: 413409935
Ref: PEP 552 基于哈希值的 pyc 文件-Footnote-1411639
Ref: PEP 552 基于哈希值的 pyc 文件-Footnote-2411680
Ref: PEP 552 基于哈希值的 pyc 文件-Footnote-3411729
Node: PEP 545 Python 文档翻译411778
Ref: whatsnew/3 7 pep-545-python-documentation-translations411938
Ref: 43a411938
Ref: whatsnew/3 7 whatsnew37-pep545411938
Ref: 417411938
Ref: PEP 545 Python 文档翻译-Footnote-1412435
Ref: PEP 545 Python 文档翻译-Footnote-2412484
Node: Python 开发模式 -X dev412533
Ref: whatsnew/3 7 python-development-mode-x-dev412647
Ref: 43b412647
Ref: whatsnew/3 7 whatsnew37-devmode412647
Ref: 414412647
Node: 其他语言特性修改<3>413049
Ref: whatsnew/3 7 other-language-changes413190
Ref: 43d413190
Ref: 其他语言特性修改<3>-Footnote-1415488
Ref: 其他语言特性修改<3>-Footnote-2415531
Ref: 其他语言特性修改<3>-Footnote-3415574
Ref: 其他语言特性修改<3>-Footnote-4415617
Ref: 其他语言特性修改<3>-Footnote-5415660
Ref: 其他语言特性修改<3>-Footnote-6415703
Ref: 其他语言特性修改<3>-Footnote-7415746
Ref: 其他语言特性修改<3>-Footnote-8415789
Ref: 其他语言特性修改<3>-Footnote-9415832
Ref: 其他语言特性修改<3>-Footnote-10415875
Node: 新增模块<3>415919
Ref: whatsnew/3 7 new-modules416063
Ref: 445416063
Node: contextvars416184
Ref: whatsnew/3 7 contextvars416267
Ref: 446416267
Ref: whatsnew/3 7 whatsnew37-pep567416267
Ref: 407416267
Ref: contextvars-Footnote-1416936
Node: dataclasses416985
Ref: whatsnew/3 7 dataclasses417096
Ref: 448417096
Ref: whatsnew/3 7 whatsnew37-pep557417096
Ref: 408417096
Ref: dataclasses-Footnote-1417725
Node: importlib resources417774
Ref: whatsnew/3 7 importlib-resources417865
Ref: 44d417865
Ref: whatsnew/3 7 whatsnew37-importlib-resources417865
Ref: 409417865
Ref: importlib resources-Footnote-1418600
Ref: importlib resources-Footnote-2418643
Node: 改进的模块<3>418704
Ref: whatsnew/3 7 improved-modules418839
Ref: 44f418839
Node: argparse420083
Ref: whatsnew/3 7 argparse420165
Ref: 450420165
Ref: argparse-Footnote-1420387
Node: asyncio<3>420430
Ref: whatsnew/3 7 asyncio420529
Ref: 452420529
Ref: whatsnew/3 7 whatsnew37-asyncio420529
Ref: 40f420529
Ref: asyncio<3>-Footnote-1426613
Ref: asyncio<3>-Footnote-2426656
Ref: asyncio<3>-Footnote-3426705
Ref: asyncio<3>-Footnote-4426748
Ref: asyncio<3>-Footnote-5426791
Ref: asyncio<3>-Footnote-6426834
Ref: asyncio<3>-Footnote-7426877
Ref: asyncio<3>-Footnote-8426920
Ref: asyncio<3>-Footnote-9426963
Ref: asyncio<3>-Footnote-10427006
Ref: asyncio<3>-Footnote-11427050
Ref: asyncio<3>-Footnote-12427094
Ref: asyncio<3>-Footnote-13427138
Ref: asyncio<3>-Footnote-14427182
Ref: asyncio<3>-Footnote-15427226
Ref: asyncio<3>-Footnote-16427270
Ref: asyncio<3>-Footnote-17427314
Ref: asyncio<3>-Footnote-18427358
Ref: asyncio<3>-Footnote-19427402
Ref: asyncio<3>-Footnote-20427446
Ref: asyncio<3>-Footnote-21427490
Ref: asyncio<3>-Footnote-22427534
Ref: asyncio<3>-Footnote-23427578
Ref: asyncio<3>-Footnote-24427622
Node: binascii427666
Ref: whatsnew/3 7 binascii427765
Ref: 474427765
Ref: binascii-Footnote-1428036
Node: calendar428079
Ref: whatsnew/3 7 calendar428182
Ref: 476428182
Ref: calendar-Footnote-1428415
Node: collections<2>428458
Ref: whatsnew/3 7 collections428566
Ref: 478428566
Ref: collections<2>-Footnote-1428758
Node: compileall<2>428801
Ref: whatsnew/3 7 compileall428922
Ref: 479428922
Ref: compileall<2>-Footnote-1429305
Node: concurrent futures<2>429348
Ref: whatsnew/3 7 concurrent-futures429465
Ref: 47b429465
Ref: concurrent futures<2>-Footnote-1429911
Ref: concurrent futures<2>-Footnote-2429954
Node: contextlib429997
Ref: whatsnew/3 7 contextlib430112
Ref: 47c430112
Ref: contextlib-Footnote-1430663
Ref: contextlib-Footnote-2430706
Ref: contextlib-Footnote-3430749
Ref: contextlib-Footnote-4430792
Node: cProfile<2>430835
Ref: whatsnew/3 7 cprofile430934
Ref: 482430934
Ref: cProfile<2>-Footnote-1431155
Node: crypt431198
Ref: whatsnew/3 7 crypt431298
Ref: 483431298
Ref: crypt-Footnote-1431612
Ref: crypt-Footnote-2431655
Node: datetime<3>431698
Ref: whatsnew/3 7 datetime431790
Ref: 485431790
Ref: datetime<3>-Footnote-1432210
Ref: datetime<3>-Footnote-2432253
Node: dbm432295
Ref: whatsnew/3 7 dbm432389
Ref: 487432389
Node: decimal432523
Ref: whatsnew/3 7 decimal432609
Ref: 488432609
Ref: decimal-Footnote-1432837
Node: dis432880
Ref: whatsnew/3 7 dis432975
Ref: 489432975
Ref: dis-Footnote-1433334
Node: distutils<2>433377
Ref: whatsnew/3 7 distutils433469
Ref: 48b433469
Ref: distutils<2>-Footnote-1433715
Node: enum433758
Ref: whatsnew/3 7 enum433859
Ref: 48c433859
Ref: enum-Footnote-1434502
Ref: enum-Footnote-2434545
Node: functools<2>434588
Ref: whatsnew/3 7 functools434682
Ref: 48f434682
Ref: functools<2>-Footnote-1434900
Node: gc<3>434943
Ref: whatsnew/3 7 gc435037
Ref: 491435037
Ref: gc<3>-Footnote-1435544
Node: hmac435587
Ref: whatsnew/3 7 hmac435680
Ref: 495435680
Ref: hmac-Footnote-1435926
Node: http client435969
Ref: whatsnew/3 7 http-client436068
Ref: 497436068
Ref: http client-Footnote-1436324
Node: http server436367
Ref: whatsnew/3 7 http-server436478
Ref: 49a436478
Ref: http server-Footnote-1437339
Ref: http server-Footnote-2437382
Ref: http server-Footnote-3437425
Node: idlelib 与 IDLE437468
Ref: whatsnew/3 7 idlelib-and-idle437580
Ref: 49d437580
Ref: idlelib 与 IDLE-Footnote-1440587
Ref: idlelib 与 IDLE-Footnote-2440630
Ref: idlelib 与 IDLE-Footnote-3440675
Ref: idlelib 与 IDLE-Footnote-4440718
Ref: idlelib 与 IDLE-Footnote-5440761
Ref: idlelib 与 IDLE-Footnote-6440804
Ref: idlelib 与 IDLE-Footnote-7440847
Ref: idlelib 与 IDLE-Footnote-8440890
Ref: idlelib 与 IDLE-Footnote-9440933
Ref: idlelib 与 IDLE-Footnote-10440976
Ref: idlelib 与 IDLE-Footnote-11441022
Ref: idlelib 与 IDLE-Footnote-12441065
Ref: idlelib 与 IDLE-Footnote-13441109
Node: importlib<2>441153
Ref: whatsnew/3 7 importlib441259
Ref: 49e441259
Ref: importlib<2>-Footnote-1442115
Ref: importlib<2>-Footnote-2442158
Ref: importlib<2>-Footnote-3442201
Node: io<2>442244
Ref: whatsnew/3 7 io442346
Ref: 4a2442346
Ref: io<2>-Footnote-1442605
Ref: io<2>-Footnote-2442648
Node: ipaddress<2>442691
Ref: whatsnew/3 7 ipaddress442793
Ref: 4a4442793
Ref: ipaddress<2>-Footnote-1443118
Node: itertools<2>443161
Ref: whatsnew/3 7 itertools443264
Ref: 4a7443264
Ref: itertools<2>-Footnote-1443504
Node: locale443547
Ref: whatsnew/3 7 locale443648
Ref: 4a9443648
Ref: locale-Footnote-1444039
Node: logging<2>444082
Ref: whatsnew/3 7 logging444178
Ref: 4ac444178
Ref: logging<2>-Footnote-1444690
Ref: logging<2>-Footnote-2444733
Ref: logging<2>-Footnote-3444776
Node: math<3>444819
Ref: whatsnew/3 7 math444918
Ref: 4b0444918
Ref: math<3>-Footnote-1445126
Node: mimetypes445169
Ref: whatsnew/3 7 mimetypes445264
Ref: 4b2445264
Ref: mimetypes-Footnote-1445469
Node: msilib445512
Ref: whatsnew/3 7 msilib445618
Ref: 4b3445618
Ref: msilib-Footnote-1445838
Node: multiprocessing<3>445881
Ref: whatsnew/3 7 multiprocessing445983
Ref: 4b5445983
Ref: multiprocessing<3>-Footnote-1446617
Ref: multiprocessing<3>-Footnote-2446660
Ref: multiprocessing<3>-Footnote-3446703
Node: os<3>446746
Ref: whatsnew/3 7 os446852
Ref: 4b9446852
Ref: os<3>-Footnote-1448131
Ref: os<3>-Footnote-2448174
Ref: os<3>-Footnote-3448217
Ref: os<3>-Footnote-4448260
Ref: os<3>-Footnote-5448303
Ref: os<3>-Footnote-6448346
Ref: os<3>-Footnote-7448389
Node: pathlib<3>448432
Ref: whatsnew/3 7 pathlib448526
Ref: 4c6448526
Ref: pathlib<3>-Footnote-1448772
Node: pdb<2>448815
Ref: whatsnew/3 7 pdb448917
Ref: 4c7448917
Ref: pdb<2>-Footnote-1449337
Ref: pdb<2>-Footnote-2449380
Node: py_compile<2>449423
Ref: whatsnew/3 7 py-compile449523
Ref: 4c9449523
Ref: py_compile<2>-Footnote-1449966
Ref: py_compile<2>-Footnote-2450007
Node: pydoc<2>450050
Ref: whatsnew/3 7 pydoc450149
Ref: 4ca450149
Ref: pydoc<2>-Footnote-1450372
Node: queue450415
Ref: whatsnew/3 7 queue450503
Ref: 4cb450503
Ref: queue-Footnote-1450716
Node: re450759
Ref: whatsnew/3 7 re450848
Ref: 4cd450848
Ref: re-Footnote-1451915
Ref: re-Footnote-2451958
Ref: re-Footnote-3452001
Ref: re-Footnote-4452044
Ref: re-Footnote-5452087
Node: signal<2>452130
Ref: whatsnew/3 7 signal452223
Ref: 4d3452223
Ref: signal<2>-Footnote-1452524
Node: socket<3>452567
Ref: whatsnew/3 7 socket452670
Ref: 4d5452670
Ref: socket<3>-Footnote-1453773
Ref: socket<3>-Footnote-2453816
Ref: socket<3>-Footnote-3453859
Ref: socket<3>-Footnote-4453902
Ref: socket<3>-Footnote-5453945
Ref: socket<3>-Footnote-6453988
Node: socketserver454031
Ref: whatsnew/3 7 socketserver454132
Ref: 4da454132
Node: sqlite3454595
Ref: whatsnew/3 7 sqlite3454693
Ref: 4dd454693
Ref: sqlite3-Footnote-1455138
Ref: sqlite3-Footnote-2455181
Node: ssl<2>455224
Ref: whatsnew/3 7 ssl455316
Ref: 4e1455316
Ref: ssl<2>-Footnote-1458215
Ref: ssl<2>-Footnote-2458258
Ref: ssl<2>-Footnote-3458301
Ref: ssl<2>-Footnote-4458344
Ref: ssl<2>-Footnote-5458387
Ref: ssl<2>-Footnote-6458430
Ref: ssl<2>-Footnote-7458473
Ref: ssl<2>-Footnote-8458516
Ref: ssl<2>-Footnote-9458559
Ref: ssl<2>-Footnote-10458602
Ref: ssl<2>-Footnote-11458646
Ref: ssl<2>-Footnote-12458690
Ref: ssl<2>-Footnote-13458734
Node: string458778
Ref: whatsnew/3 7 string458873
Ref: 4ef458873
Ref: string-Footnote-1459157
Node: subprocess459202
Ref: whatsnew/3 7 subprocess459297
Ref: 4f1459297
Ref: subprocess-Footnote-1460579
Ref: subprocess-Footnote-2460622
Ref: subprocess-Footnote-3460665
Ref: subprocess-Footnote-4460708
Node: sys<3>460751
Ref: whatsnew/3 7 sys460847
Ref: 4f5460847
Ref: sys<3>-Footnote-1461594
Ref: sys<3>-Footnote-2461637
Ref: sys<3>-Footnote-3461680
Node: time<3>461723
Ref: whatsnew/3 7 time461819
Ref: 4f9461819
Ref: time<3>-Footnote-1462970
Ref: time<3>-Footnote-2463019
Node: tkinter<2>463062
Ref: whatsnew/3 7 tkinter463166
Ref: 500463166
Ref: tkinter<2>-Footnote-1463347
Node: tracemalloc<2>463390
Ref: whatsnew/3 7 tracemalloc463492
Ref: 502463492
Ref: tracemalloc<2>-Footnote-1463981
Node: types464024
Ref: whatsnew/3 7 types464130
Ref: 505464130
Ref: types-Footnote-1464648
Ref: types-Footnote-2464691
Ref: types-Footnote-3464734
Ref: types-Footnote-4464783
Node: unicodedata<3>464826
Ref: whatsnew/3 7 unicodedata464929
Ref: 50b464929
Ref: unicodedata<3>-Footnote-1465126
Node: unittest<2>465181
Ref: whatsnew/3 7 unittest465292
Ref: 50c465292
Ref: unittest<2>-Footnote-1465721
Node: unittest mock465764
Ref: whatsnew/3 7 unittest-mock465876
Ref: 50d465876
Ref: unittest mock-Footnote-1466373
Ref: unittest mock-Footnote-2466416
Node: urllib parse<3>466459
Ref: whatsnew/3 7 urllib-parse466562
Ref: 510466562
Ref: urllib parse<3>-Footnote-1466867
Ref: urllib parse<3>-Footnote-2466916
Ref: urllib parse<3>-Footnote-3466965
Node: uu467008
Ref: whatsnew/3 7 uu467102
Ref: 512467102
Ref: uu-Footnote-1467363
Node: uuid467406
Ref: whatsnew/3 7 uuid467493
Ref: 514467493
Ref: uuid-Footnote-1468088
Ref: uuid-Footnote-2468131
Node: warnings468174
Ref: whatsnew/3 7 warnings468268
Ref: 518468268
Ref: warnings-Footnote-1469606
Ref: warnings-Footnote-2469649
Ref: warnings-Footnote-3469692
Ref: warnings-Footnote-4469735
Node: xml etree469778
Ref: whatsnew/3 7 xml-etree469881
Ref: 51c469881
Ref: xml etree-Footnote-1470231
Node: xmlrpc server470274
Ref: whatsnew/3 7 xmlrpc-server470375
Ref: 51e470375
Ref: xmlrpc server-Footnote-1470591
Node: zipapp470633
Ref: whatsnew/3 7 zipapp470732
Ref: 51f470732
Ref: zipapp-Footnote-1471225
Ref: zipapp-Footnote-2471268
Node: zipfile471311
Ref: whatsnew/3 7 zipfile471388
Ref: 521471388
Ref: zipfile-Footnote-1471749
Ref: zipfile-Footnote-2471792
Node: C API 的改变<2>471835
Ref: whatsnew/3 7 c-api-changes471973
Ref: 523471973
Ref: C API 的改变<2>-Footnote-1476494
Ref: C API 的改变<2>-Footnote-2476537
Ref: C API 的改变<2>-Footnote-3476580
Ref: C API 的改变<2>-Footnote-4476623
Ref: C API 的改变<2>-Footnote-5476666
Ref: C API 的改变<2>-Footnote-6476709
Ref: C API 的改变<2>-Footnote-7476752
Ref: C API 的改变<2>-Footnote-8476795
Ref: C API 的改变<2>-Footnote-9476838
Ref: C API 的改变<2>-Footnote-10476881
Ref: C API 的改变<2>-Footnote-11476925
Ref: C API 的改变<2>-Footnote-12476969
Ref: C API 的改变<2>-Footnote-13477013
Ref: C API 的改变<2>-Footnote-14477057
Ref: C API 的改变<2>-Footnote-15477101
Ref: C API 的改变<2>-Footnote-16477144
Ref: C API 的改变<2>-Footnote-17477188
Ref: C API 的改变<2>-Footnote-18477232
Ref: C API 的改变<2>-Footnote-19477276
Ref: C API 的改变<2>-Footnote-20477320
Node: 构建的改变<2>477364
Ref: whatsnew/3 7 build-changes477499
Ref: 543477499
Ref: 构建的改变<2>-Footnote-1478573
Ref: 构建的改变<2>-Footnote-2478616
Ref: 构建的改变<2>-Footnote-3478659
Node: 性能优化<3>478702
Ref: whatsnew/3 7 optimizations478849
Ref: 544478849
Ref: whatsnew/3 7 whatsnew37-perf478849
Ref: 418478849
Ref: whatsnew/3 7 whatsnew37-asyncio-perf479544
Ref: 453479544
Ref: 性能优化<3>-Footnote-1484132
Ref: 性能优化<3>-Footnote-2484175
Ref: 性能优化<3>-Footnote-3484218
Ref: 性能优化<3>-Footnote-4484261
Ref: 性能优化<3>-Footnote-5484304
Ref: 性能优化<3>-Footnote-6484347
Ref: 性能优化<3>-Footnote-7484390
Ref: 性能优化<3>-Footnote-8484433
Ref: 性能优化<3>-Footnote-9484476
Ref: 性能优化<3>-Footnote-10484519
Ref: 性能优化<3>-Footnote-11484563
Ref: 性能优化<3>-Footnote-12484607
Ref: 性能优化<3>-Footnote-13484651
Ref: 性能优化<3>-Footnote-14484695
Ref: 性能优化<3>-Footnote-15484739
Ref: 性能优化<3>-Footnote-16484783
Ref: 性能优化<3>-Footnote-17484827
Ref: 性能优化<3>-Footnote-18484871
Ref: 性能优化<3>-Footnote-19484915
Ref: 性能优化<3>-Footnote-20484959
Ref: 性能优化<3>-Footnote-21485003
Ref: 性能优化<3>-Footnote-22485047
Ref: 性能优化<3>-Footnote-23485091
Ref: 性能优化<3>-Footnote-24485135
Ref: 性能优化<3>-Footnote-25485179
Ref: 性能优化<3>-Footnote-26485223
Ref: 性能优化<3>-Footnote-27485267
Ref: 性能优化<3>-Footnote-28485311
Ref: 性能优化<3>-Footnote-29485355
Ref: 性能优化<3>-Footnote-30485399
Node: 其他 CPython 实现的改变485443
Ref: whatsnew/3 7 other-cpython-implementation-changes485598
Ref: 555485598
Ref: 其他 CPython 实现的改变-Footnote-1486875
Ref: 其他 CPython 实现的改变-Footnote-2486918
Ref: 其他 CPython 实现的改变-Footnote-3486961
Ref: 其他 CPython 实现的改变-Footnote-4487004
Ref: 其他 CPython 实现的改变-Footnote-5487047
Node: 已弃用的 Python 行为487090
Ref: whatsnew/3 7 deprecated-python-behavior487274
Ref: 557487274
Ref: 已弃用的 Python 行为-Footnote-1488364
Ref: 已弃用的 Python 行为-Footnote-2488407
Node: 已弃用的 Python 模块、函数和方法488450
Ref: whatsnew/3 7 deprecated-python-modules-functions-and-methods488638
Ref: 55a488638
Node: aifc489016
Ref: whatsnew/3 7 aifc489120
Ref: 55b489120
Ref: aifc-Footnote-1489342
Node: asyncio<4>489385
Ref: whatsnew/3 7 id2489512
Ref: 55d489512
Ref: whatsnew/3 7 whatsnew37-asyncio-deprecated489512
Ref: 473489512
Ref: asyncio<4>-Footnote-1489966
Ref: asyncio<4>-Footnote-2490009
Node: collections<3>490052
Ref: whatsnew/3 7 id3490181
Ref: 55e490181
Ref: collections<3>-Footnote-1490511
Node: dbm<2>490554
Ref: whatsnew/3 7 id4490680
Ref: 55f490680
Ref: dbm<2>-Footnote-1491083
Node: enum<2>491126
Ref: whatsnew/3 7 id5491248
Ref: 560491248
Ref: enum<2>-Footnote-1491681
Node: gettext<2>491724
Ref: whatsnew/3 7 gettext491852
Ref: 561491852
Ref: gettext<2>-Footnote-1492097
Node: importlib<3>492140
Ref: whatsnew/3 7 id6492270
Ref: 562492270
Ref: importlib<3>-Footnote-1492807
Node: locale<2>492850
Ref: whatsnew/3 7 id7492977
Ref: 568492977
Ref: locale<2>-Footnote-1493182
Node: macpath493225
Ref: whatsnew/3 7 macpath493352
Ref: 56a493352
Ref: macpath-Footnote-1493543
Node: threading<2>493585
Ref: whatsnew/3 7 threading493712
Ref: 56b493712
Ref: threading<2>-Footnote-1493988
Node: socket<4>494031
Ref: whatsnew/3 7 id8494157
Ref: 56c494157
Ref: socket<4>-Footnote-1494481
Node: ssl<3>494524
Ref: whatsnew/3 7 id9494643
Ref: 56f494643
Ref: ssl<3>-Footnote-1494863
Node: sunau494906
Ref: whatsnew/3 7 sunau495022
Ref: 571495022
Ref: sunau-Footnote-1495250
Node: sys<4>495293
Ref: whatsnew/3 7 id10495407
Ref: 573495407
Ref: sys<4>-Footnote-1495719
Node: wave495762
Ref: whatsnew/3 7 wave495862
Ref: 574495862
Ref: wave-Footnote-1496086
Node: 已弃用的 C API 函数和类型496129
Ref: whatsnew/3 7 deprecated-functions-and-types-of-the-c-api496312
Ref: 575496312
Ref: 已弃用的 C API 函数和类型-Footnote-1496935
Ref: 已弃用的 C API 函数和类型-Footnote-2496978
Node: 平台支持的移除497021
Ref: whatsnew/3 7 id11497185
Ref: 577497185
Ref: whatsnew/3 7 platform-support-removals497185
Ref: 4e5497185
Ref: 平台支持的移除-Footnote-1498566
Ref: 平台支持的移除-Footnote-2498629
Node: API 与特性的移除<2>498708
Ref: whatsnew/3 7 api-and-feature-removals498853
Ref: 578498853
Ref: API 与特性的移除<2>-Footnote-1501607
Ref: API 与特性的移除<2>-Footnote-2501650
Ref: API 与特性的移除<2>-Footnote-3501693
Node: 移除的模块501736
Ref: whatsnew/3 7 module-removals501883
Ref: 57d501883
Ref: 移除的模块-Footnote-1502195
Node: Windows 专属的改变502238
Ref: whatsnew/3 7 windows-only-changes502380
Ref: 57e502380
Ref: Windows 专属的改变-Footnote-1503218
Ref: Windows 专属的改变-Footnote-2503261
Node: 移植到 Python 3 7503304
Ref: whatsnew/3 7 porting-to-python-3-7503462
Ref: 57f503462
Ref: whatsnew/3 7 porting-to-python-37503462
Ref: 419503462
Node: Python 行为的更改503920
Ref: whatsnew/3 7 changes-in-python-behavior504030
Ref: 580504030
Ref: Python 行为的更改-Footnote-1505744
Ref: Python 行为的更改-Footnote-2505787
Ref: Python 行为的更改-Footnote-3505836
Ref: Python 行为的更改-Footnote-4505879
Ref: Python 行为的更改-Footnote-5505922
Ref: Python 行为的更改-Footnote-6505965
Node: 更改的Python API<2>506008
Ref: whatsnew/3 7 changes-in-the-python-api506148
Ref: 583506148
Ref: 更改的Python API<2>-Footnote-1515421
Ref: 更改的Python API<2>-Footnote-2515464
Ref: 更改的Python API<2>-Footnote-3515507
Ref: 更改的Python API<2>-Footnote-4515550
Ref: 更改的Python API<2>-Footnote-5515593
Ref: 更改的Python API<2>-Footnote-6515636
Ref: 更改的Python API<2>-Footnote-7515679
Ref: 更改的Python API<2>-Footnote-8515722
Ref: 更改的Python API<2>-Footnote-9515765
Ref: 更改的Python API<2>-Footnote-10515808
Ref: 更改的Python API<2>-Footnote-11515852
Ref: 更改的Python API<2>-Footnote-12515896
Ref: 更改的Python API<2>-Footnote-13515940
Ref: 更改的Python API<2>-Footnote-14515984
Ref: 更改的Python API<2>-Footnote-15516027
Ref: 更改的Python API<2>-Footnote-16516071
Ref: 更改的Python API<2>-Footnote-17516115
Ref: 更改的Python API<2>-Footnote-18516159
Ref: 更改的Python API<2>-Footnote-19516203
Ref: 更改的Python API<2>-Footnote-20516247
Ref: 更改的Python API<2>-Footnote-21516291
Ref: 更改的Python API<2>-Footnote-22516335
Ref: 更改的Python API<2>-Footnote-23516379
Ref: 更改的Python API<2>-Footnote-24516423
Ref: 更改的Python API<2>-Footnote-25516467
Ref: 更改的Python API<2>-Footnote-26516511
Ref: 更改的Python API<2>-Footnote-27516555
Ref: 更改的Python API<2>-Footnote-28516599
Ref: 更改的Python API<2>-Footnote-29516643
Ref: 更改的Python API<2>-Footnote-30516687
Node: C API 中的改变<2>516731
Ref: whatsnew/3 7 changes-in-the-c-api516878
Ref: 5a5516878
Ref: C API 中的改变<2>-Footnote-1517503
Node: CPython 字节码的改变<3>517546
Ref: whatsnew/3 7 cpython-bytecode-changes517697
Ref: 5a6517697
Ref: CPython 字节码的改变<3>-Footnote-1518057
Ref: CPython 字节码的改变<3>-Footnote-2518100
Node: Windows 专属的改变<2>518143
Ref: whatsnew/3 7 id12518306
Ref: 5a9518306
Ref: Windows 专属的改变<2>-Footnote-1518634
Node: 其他 CPython 实现的改变<2>518677
Ref: whatsnew/3 7 id13518802
Ref: 5ab518802
Ref: 其他 CPython 实现的改变<2>-Footnote-1520902
Ref: 其他 CPython 实现的改变<2>-Footnote-2520951
Ref: 其他 CPython 实现的改变<2>-Footnote-3520994
Node: Python 3 7 1 中的重要变化521037
Ref: whatsnew/3 7 notable-changes-in-python-3-7-1521203
Ref: 5b0521203
Ref: Python 3 7 1 中的重要变化-Footnote-1522130
Ref: Python 3 7 1 中的重要变化-Footnote-2522173
Ref: Python 3 7 1 中的重要变化-Footnote-3522216
Node: Python 3 7 2 中的重要变化522259
Ref: whatsnew/3 7 notable-changes-in-python-3-7-2522436
Ref: 5b5522436
Node: Python 3 7 6 中的重要变化522909
Ref: whatsnew/3 7 notable-changes-in-python-3-7-6523087
Ref: 5b6523087
Ref: Python 3 7 6 中的重要变化-Footnote-1523568
Node: Python 3 7 10 中的重要变化523611
Ref: whatsnew/3 7 notable-changes-in-python-3-7-10523749
Ref: 5b7523749
Ref: Python 3 7 10 中的重要变化-Footnote-1524446
Node: Python 3 6 有什么新变化524489
Ref: whatsnew/3 6 doc524659
Ref: 5b8524659
Ref: whatsnew/3 6 what-s-new-in-python-3-6524659
Ref: 5b9524659
Ref: Python 3 6 有什么新变化-Footnote-1525883
Ref: Python 3 6 有什么新变化-Footnote-2525943
Node: 摘要 - 发布重点<4>525992
Ref: whatsnew/3 6 summary-release-highlights526106
Ref: 5ba526106
Ref: 摘要 - 发布重点<4>-Footnote-1529790
Ref: 摘要 - 发布重点<4>-Footnote-2529870
Ref: 摘要 - 发布重点<4>-Footnote-3529960
Node: 新的特性<5>530009
Ref: whatsnew/3 6 new-features530159
Ref: 5d1530159
Ref: whatsnew/3 6 pypy-dict-implementation530159
Ref: 5d2530159
Node: PEP 498 格式化字符串字面值531395
Ref: whatsnew/3 6 pep-498-formatted-string-literals531520
Ref: 5d3531520
Ref: whatsnew/3 6 whatsnew36-pep498531520
Ref: 5bb531520
Ref: PEP 498 格式化字符串字面值-Footnote-1532465
Ref: PEP 498 格式化字符串字面值-Footnote-2532514
Node: PEP 526 变量标注的语法532563
Ref: whatsnew/3 6 pep-526-syntax-for-variable-annotations532738
Ref: 5d6532738
Ref: whatsnew/3 6 whatsnew36-pep526532738
Ref: 5bd532738
Ref: PEP 526 变量标注的语法-Footnote-1533799
Ref: PEP 526 变量标注的语法-Footnote-2533848
Ref: PEP 526 变量标注的语法-Footnote-3533897
Ref: PEP 526 变量标注的语法-Footnote-4533931
Node: PEP 515 数字字面值中的下划线。533972
Ref: whatsnew/3 6 pep-515-underscores-in-numeric-literals534135
Ref: 5d7534135
Ref: whatsnew/3 6 whatsnew36-pep515534135
Ref: 5bc534135
Ref: PEP 515 数字字面值中的下划线。-Footnote-1535105
Ref: PEP 515 数字字面值中的下划线。-Footnote-2535154
Node: PEP 525 异步生成器535203
Ref: whatsnew/3 6 pep-525-asynchronous-generators535360
Ref: 5d9535360
Ref: whatsnew/3 6 whatsnew36-pep525535360
Ref: 5be535360
Ref: PEP 525 异步生成器-Footnote-1536110
Ref: PEP 525 异步生成器-Footnote-2536159
Node: PEP 530 异步推导式536208
Ref: whatsnew/3 6 pep-530-asynchronous-comprehensions536362
Ref: 5da536362
Ref: whatsnew/3 6 whatsnew36-pep530536362
Ref: 5bf536362
Ref: PEP 530 异步推导式-Footnote-1536869
Ref: PEP 530 异步推导式-Footnote-2536918
Node: PEP 487 更简单的自定义类创建536967
Ref: whatsnew/3 6 pep-487-simpler-customization-of-class-creation537130
Ref: 5db537130
Ref: whatsnew/3 6 whatsnew36-pep487537130
Ref: 5c2537130
Ref: PEP 487 更简单的自定义类创建-Footnote-1538109
Node: PEP 487 描述器协议的增强538158
Ref: whatsnew/3 6 pep-487-descriptor-protocol-enhancements538336
Ref: 5e0538336
Ref: whatsnew/3 6 whatsnew36-pep487-descriptors538336
Ref: 5e1538336
Ref: PEP 487 描述器协议的增强-Footnote-1539463
Ref: PEP 487 描述器协议的增强-Footnote-2539512
Node: PEP 519 添加文件系统路径协议539561
Ref: whatsnew/3 6 pep-519-adding-a-file-system-path-protocol539736
Ref: 5e4539736
Ref: whatsnew/3 6 whatsnew36-pep519539736
Ref: 5c7539736
Ref: PEP 519 添加文件系统路径协议-Footnote-1542544
Node: PEP 495 消除本地时间的歧义542593
Ref: whatsnew/3 6 pep-495-local-time-disambiguation542786
Ref: 5eb542786
Ref: whatsnew/3 6 whatsnew36-pep495542786
Ref: 5c8542786
Ref: PEP 495 消除本地时间的歧义-Footnote-1544191
Ref: PEP 495 消除本地时间的歧义-Footnote-2544240
Node: PEP 529 将Windows文件系统编码更改为UTF-8544289
Ref: whatsnew/3 6 pep-529-change-windows-filesystem-encoding-to-utf-8544491
Ref: 5ee544491
Ref: whatsnew/3 6 whatsnew36-pep529544491
Ref: 5ce544491
Ref: PEP 529 将Windows文件系统编码更改为UTF-8-Footnote-1545499
Node: PEP 528 将Windows控制台编码更改为UTF-8545548
Ref: whatsnew/3 6 pep-528-change-windows-console-encoding-to-utf-8545750
Ref: 5f2545750
Ref: whatsnew/3 6 whatsnew36-pep528545750
Ref: 5cd545750
Ref: PEP 528 将Windows控制台编码更改为UTF-8-Footnote-1546435
Node: PEP 520 保留类属性定义顺序546484
Ref: whatsnew/3 6 pep-520-preserving-class-attribute-definition-order546671
Ref: 5f4546671
Ref: whatsnew/3 6 whatsnew36-pep520546671
Ref: 5c3546671
Ref: PEP 520 保留类属性定义顺序-Footnote-1547245
Node: PEP 468 保留关键字参数顺序547294
Ref: whatsnew/3 6 pep-468-preserving-keyword-argument-order547452
Ref: 5f7547452
Ref: whatsnew/3 6 whatsnew36-pep468547452
Ref: 5c4547452
Ref: PEP 468 保留关键字参数顺序-Footnote-1547777
Node: 新的 dict 实现547826
Ref: whatsnew/3 6 new-dict-implementation547989
Ref: 5f8547989
Ref: whatsnew/3 6 whatsnew36-compactdict547989
Ref: 5c1547989
Ref: 新的 dict 实现-Footnote-1548949
Ref: 新的 dict 实现-Footnote-2549029
Ref: 新的 dict 实现-Footnote-3549119
Ref: 新的 dict 实现-Footnote-4549162
Node: PEP 523 向CPython 添加框架评估API549242
Ref: whatsnew/3 6 pep-523-adding-a-frame-evaluation-api-to-cpython549395
Ref: 5f9549395
Ref: whatsnew/3 6 whatsnew36-pep523549395
Ref: 5fa549395
Ref: PEP 523 向CPython 添加框架评估API-Footnote-1550536
Ref: PEP 523 向CPython 添加框架评估API-Footnote-2550585
Node: PYTHONMALLOC 环境变量550634
Ref: whatsnew/3 6 pythonmalloc-environment-variable550802
Ref: 5fb550802
Ref: whatsnew/3 6 whatsnew36-pythonmalloc550802
Ref: 5c6550802
Ref: PYTHONMALLOC 环境变量-Footnote-1553946
Ref: PYTHONMALLOC 环境变量-Footnote-2553989
Node: DTrace 和 SystemTap 探测支持554032
Ref: whatsnew/3 6 dtrace-and-systemtap-probing-support554151
Ref: 604554151
Ref: whatsnew/3 6 whatsnew36-tracing554151
Ref: 5c5554151
Ref: DTrace 和 SystemTap 探测支持-Footnote-1554958
Node: 其他语言特性修改<4>555001
Ref: whatsnew/3 6 other-language-changes555142
Ref: 606555142
Ref: 其他语言特性修改<4>-Footnote-1556508
Ref: 其他语言特性修改<4>-Footnote-2556551
Ref: 其他语言特性修改<4>-Footnote-3556594
Ref: 其他语言特性修改<4>-Footnote-4556637
Node: 新增模块<4>556680
Ref: whatsnew/3 6 new-modules556824
Ref: 60a556824
Node: secrets556881
Ref: whatsnew/3 6 secrets556940
Ref: 60b556940
Ref: whatsnew/3 6 whatsnew36-pep506556940
Ref: 5c0556940
Ref: secrets-Footnote-1557606
Node: 改进的模块<4>557655
Ref: whatsnew/3 6 improved-modules557787
Ref: 60c557787
Node: array559182
Ref: whatsnew/3 6 array559257
Ref: 60d559257
Ref: array-Footnote-1559552
Node: ast<3>559595
Ref: whatsnew/3 6 ast559689
Ref: 60e559689
Ref: ast<3>-Footnote-1559940
Node: asyncio<5>559983
Ref: whatsnew/3 6 asyncio560083
Ref: 60f560083
Ref: asyncio<5>-Footnote-1563423
Ref: asyncio<5>-Footnote-2563466
Ref: asyncio<5>-Footnote-3563511
Ref: asyncio<5>-Footnote-4563554
Ref: asyncio<5>-Footnote-5563597
Ref: asyncio<5>-Footnote-6563640
Ref: asyncio<5>-Footnote-7563683
Ref: asyncio<5>-Footnote-8563726
Ref: asyncio<5>-Footnote-9563769
Ref: asyncio<5>-Footnote-10563812
Ref: asyncio<5>-Footnote-11563856
Ref: asyncio<5>-Footnote-12563900
Node: binascii<2>563944
Ref: whatsnew/3 6 binascii564043
Ref: 61b564043
Ref: binascii<2>-Footnote-1564328
Node: cmath564371
Ref: whatsnew/3 6 cmath564474
Ref: 61d564474
Ref: cmath-Footnote-1564945
Ref: cmath-Footnote-2564988
Ref: cmath-Footnote-3565037
Node: collections<4>565080
Ref: whatsnew/3 6 collections565193
Ref: 625565193
Ref: collections<4>-Footnote-1566294
Ref: collections<4>-Footnote-2566337
Ref: collections<4>-Footnote-3566380
Ref: collections<4>-Footnote-4566423
Ref: collections<4>-Footnote-5566466
Ref: collections<4>-Footnote-6566509
Node: concurrent futures<3>566552
Ref: whatsnew/3 6 concurrent-futures566673
Ref: 62b566673
Ref: concurrent futures<3>-Footnote-1567003
Node: contextlib<2>567046
Ref: whatsnew/3 6 contextlib567164
Ref: 62c567164
Ref: contextlib<2>-Footnote-1567660
Node: datetime<4>567703
Ref: whatsnew/3 6 datetime567810
Ref: 62f567810
Ref: datetime<4>-Footnote-1568827
Ref: datetime<4>-Footnote-2568870
Ref: datetime<4>-Footnote-3568913
Ref: datetime<4>-Footnote-4568956
Node: decimal<2>568999
Ref: whatsnew/3 6 decimal569105
Ref: 634569105
Ref: decimal<2>-Footnote-1569524
Node: distutils<3>569567
Ref: whatsnew/3 6 distutils569667
Ref: 636569667
Ref: distutils<3>-Footnote-1570041
Node: email570084
Ref: whatsnew/3 6 email570183
Ref: 637570183
Ref: email-Footnote-1571099
Ref: email-Footnote-2571142
Ref: email-Footnote-3571185
Node: encodings571228
Ref: whatsnew/3 6 encodings571322
Ref: 63d571322
Ref: encodings-Footnote-1571617
Node: enum<3>571660
Ref: whatsnew/3 6 enum571761
Ref: 63e571761
Ref: enum<3>-Footnote-1572509
Node: faulthandler572552
Ref: whatsnew/3 6 faulthandler572653
Ref: 641572653
Ref: faulthandler-Footnote-1572916
Node: fileinput572959
Ref: whatsnew/3 6 fileinput573063
Ref: 643573063
Ref: fileinput-Footnote-1573251
Node: hashlib<2>573294
Ref: whatsnew/3 6 hashlib573400
Ref: 645573400
Ref: hashlib<2>-Footnote-1574418
Ref: hashlib<2>-Footnote-2574461
Ref: hashlib<2>-Footnote-3574504
Ref: hashlib<2>-Footnote-4574547
Node: http client<2>574590
Ref: whatsnew/3 6 http-client574706
Ref: 648574706
Ref: http client<2>-Footnote-1574966
Node: idlelib 与 IDLE<2>575009
Ref: whatsnew/3 6 idlelib-and-idle575127
Ref: 64b575127
Ref: idlelib 与 IDLE<2>-Footnote-1578604
Ref: idlelib 与 IDLE<2>-Footnote-2578647
Ref: idlelib 与 IDLE<2>-Footnote-3578690
Ref: idlelib 与 IDLE<2>-Footnote-4578735
Ref: idlelib 与 IDLE<2>-Footnote-5578778
Ref: idlelib 与 IDLE<2>-Footnote-6578821
Ref: idlelib 与 IDLE<2>-Footnote-7578864
Ref: idlelib 与 IDLE<2>-Footnote-8578907
Ref: idlelib 与 IDLE<2>-Footnote-9578950
Ref: idlelib 与 IDLE<2>-Footnote-10578993
Ref: idlelib 与 IDLE<2>-Footnote-11579037
Node: importlib<4>579083
Ref: whatsnew/3 6 importlib579197
Ref: 64c579197
Ref: importlib<4>-Footnote-1580024
Node: inspect<3>580067
Ref: whatsnew/3 6 inspect580166
Ref: 654580166
Ref: inspect<3>-Footnote-1580947
Ref: inspect<3>-Footnote-2580990
Node: json581033
Ref: whatsnew/3 6 json581130
Ref: 658581130
Ref: json-Footnote-1581402
Node: logging<3>581445
Ref: whatsnew/3 6 logging581539
Ref: 65a581539
Ref: logging<3>-Footnote-1581803
Node: math<4>581846
Ref: whatsnew/3 6 math581954
Ref: 65c581954
Ref: math<4>-Footnote-1582186
Ref: math<4>-Footnote-2582229
Node: multiprocessing<4>582278
Ref: whatsnew/3 6 multiprocessing582381
Ref: 65d582381
Ref: multiprocessing<4>-Footnote-1582604
Node: os<4>582646
Ref: whatsnew/3 6 os582752
Ref: 65f582752
Ref: os<4>-Footnote-1583740
Ref: os<4>-Footnote-2583783
Ref: os<4>-Footnote-3583832
Node: pathlib<4>583881
Ref: whatsnew/3 6 pathlib583975
Ref: 663583975
Ref: pathlib<4>-Footnote-1584209
Node: pdb<3>584252
Ref: whatsnew/3 6 pdb584350
Ref: 664584350
Node: pickle<2>584507
Ref: whatsnew/3 6 pickle584606
Ref: 665584606
Ref: pickle<2>-Footnote-1584923
Node: pickletools584966
Ref: whatsnew/3 6 pickletools585067
Ref: 667585067
Ref: pickletools-Footnote-1585295
Node: pydoc<3>585338
Ref: whatsnew/3 6 pydoc585439
Ref: 669585439
Ref: pydoc<3>-Footnote-1585833
Ref: pydoc<3>-Footnote-2585875
Node: random<2>585918
Ref: whatsnew/3 6 random586013
Ref: 66a586013
Ref: random<2>-Footnote-1586268
Node: re<2>586311
Ref: whatsnew/3 6 re586406
Ref: 66c586406
Ref: re<2>-Footnote-1587111
Ref: re<2>-Footnote-2587155
Ref: re<2>-Footnote-3587198
Node: readline587241
Ref: whatsnew/3 6 readline587338
Ref: 66d587338
Ref: readline-Footnote-1587569
Node: rlcompleter587612
Ref: whatsnew/3 6 rlcompleter587712
Ref: 66f587712
Ref: rlcompleter-Footnote-1588016
Ref: rlcompleter-Footnote-2588059
Node: shlex<2>588102
Ref: whatsnew/3 6 shlex588198
Ref: 670588198
Ref: shlex<2>-Footnote-1588488
Node: site588533
Ref: whatsnew/3 6 site588628
Ref: 673588628
Ref: site-Footnote-1588892
Node: sqlite3<2>588935
Ref: whatsnew/3 6 sqlite3589031
Ref: 674589031
Ref: sqlite3<2>-Footnote-1589234
Node: socket<5>589277
Ref: whatsnew/3 6 socket589384
Ref: 676589384
Ref: socket<5>-Footnote-1590346
Ref: socket<5>-Footnote-2590389
Ref: socket<5>-Footnote-3590432
Ref: socket<5>-Footnote-4590475
Node: socketserver<2>590518
Ref: whatsnew/3 6 socketserver590621
Ref: 67d590621
Ref: socketserver<2>-Footnote-1591250
Ref: socketserver<2>-Footnote-2591293
Node: ssl<4>591336
Ref: whatsnew/3 6 ssl591443
Ref: 681591443
Ref: ssl<4>-Footnote-1592639
Ref: ssl<4>-Footnote-2592682
Ref: ssl<4>-Footnote-3592725
Ref: ssl<4>-Footnote-4592768
Ref: ssl<4>-Footnote-5592811
Ref: ssl<4>-Footnote-6592854
Ref: ssl<4>-Footnote-7592897
Node: statistics<2>592940
Ref: whatsnew/3 6 statistics593038
Ref: 685593038
Ref: statistics<2>-Footnote-1593228
Node: struct593271
Ref: whatsnew/3 6 struct593376
Ref: 687593376
Ref: struct-Footnote-1593607
Node: subprocess<2>593650
Ref: whatsnew/3 6 subprocess593748
Ref: 688593748
Ref: subprocess<2>-Footnote-1594441
Ref: subprocess<2>-Footnote-2594484
Node: sys<5>594526
Ref: whatsnew/3 6 sys594627
Ref: 68a594627
Ref: sys<5>-Footnote-1595228
Ref: sys<5>-Footnote-2595271
Node: telnetlib595314
Ref: whatsnew/3 6 telnetlib595409
Ref: 68d595409
Ref: telnetlib-Footnote-1595580
Node: time<4>595623
Ref: whatsnew/3 6 time595718
Ref: 68f595718
Node: timeit595857
Ref: whatsnew/3 6 timeit595953
Ref: 691595953
Ref: timeit-Footnote-1596413
Ref: timeit-Footnote-2596455
Node: tkinter<3>596498
Ref: whatsnew/3 6 tkinter596596
Ref: 694596596
Ref: tkinter<3>-Footnote-1597022
Node: traceback597065
Ref: whatsnew/3 6 traceback597171
Ref: 695597171
Ref: whatsnew/3 6 whatsnew36-traceback597171
Ref: 609597171
Ref: traceback-Footnote-1597811
Node: tracemalloc<3>597854
Ref: whatsnew/3 6 tracemalloc597959
Ref: 696597959
Ref: tracemalloc<3>-Footnote-1598326
Node: typing<4>598369
Ref: whatsnew/3 6 typing598479
Ref: 698598479
Ref: whatsnew/3 6 whatsnew36-typing598479
Ref: 5c9598479
Ref: typing<4>-Footnote-1600131
Ref: typing<4>-Footnote-2600181
Ref: typing<4>-Footnote-3600224
Ref: typing<4>-Footnote-4600267
Ref: typing<4>-Footnote-5600316
Ref: typing<4>-Footnote-6600366
Ref: typing<4>-Footnote-7600418
Node: unicodedata<4>600470
Ref: whatsnew/3 6 unicodedata600582
Ref: 69d600582
Ref: unicodedata<4>-Footnote-1600770
Node: unittest mock<2>600820
Ref: whatsnew/3 6 unittest-mock600937
Ref: 69e600937
Ref: unittest mock<2>-Footnote-1601454
Ref: unittest mock<2>-Footnote-2601497
Node: urllib request601540
Ref: whatsnew/3 6 urllib-request601661
Ref: 6a2601661
Ref: urllib request-Footnote-1602026
Node: urllib robotparser602069
Ref: whatsnew/3 6 urllib-robotparser602181
Ref: 6a3602181
Ref: urllib robotparser-Footnote-1602426
Node: venv<3>602469
Ref: whatsnew/3 6 venv602578
Ref: 6a5602578
Ref: venv<3>-Footnote-1602865
Node: warnings<2>602908
Ref: whatsnew/3 6 warnings603005
Ref: 6a6603005
Ref: warnings<2>-Footnote-1604276
Ref: warnings<2>-Footnote-2604319
Node: winreg604362
Ref: whatsnew/3 6 winreg604460
Ref: 6a8604460
Ref: winreg-Footnote-1604633
Node: winsound604676
Ref: whatsnew/3 6 winsound604776
Ref: 6aa604776
Ref: winsound-Footnote-1604975
Node: xmlrpc client605018
Ref: whatsnew/3 6 xmlrpc-client605122
Ref: 6ae605122
Ref: xmlrpc client-Footnote-1605415
Node: zipfile<2>605458
Ref: whatsnew/3 6 zipfile605558
Ref: 6af605558
Ref: zipfile<2>-Footnote-1606092
Ref: zipfile<2>-Footnote-2606135
Node: zlib606178
Ref: whatsnew/3 6 zlib606256
Ref: 6b4606256
Ref: zlib-Footnote-1606512
Ref: zlib-Footnote-2606555
Node: 性能优化<4>606598
Ref: whatsnew/3 6 optimizations606743
Ref: 6b7606743
Ref: 性能优化<4>-Footnote-1610606
Ref: 性能优化<4>-Footnote-2610649
Ref: 性能优化<4>-Footnote-3610692
Ref: 性能优化<4>-Footnote-4610735
Ref: 性能优化<4>-Footnote-5610778
Ref: 性能优化<4>-Footnote-6610821
Ref: 性能优化<4>-Footnote-7610864
Ref: 性能优化<4>-Footnote-8610907
Ref: 性能优化<4>-Footnote-9610950
Ref: 性能优化<4>-Footnote-10610993
Ref: 性能优化<4>-Footnote-11611037
Ref: 性能优化<4>-Footnote-12611081
Ref: 性能优化<4>-Footnote-13611125
Ref: 性能优化<4>-Footnote-14611169
Ref: 性能优化<4>-Footnote-15611213
Ref: 性能优化<4>-Footnote-16611257
Ref: 性能优化<4>-Footnote-17611301
Ref: 性能优化<4>-Footnote-18611345
Ref: 性能优化<4>-Footnote-19611389
Ref: 性能优化<4>-Footnote-20611433
Ref: 性能优化<4>-Footnote-21611477
Node: 构建和 C API 的改变<2>611521
Ref: whatsnew/3 6 build-and-c-api-changes611660
Ref: 6bf611660
Ref: 构建和 C API 的改变<2>-Footnote-1614111
Ref: 构建和 C API 的改变<2>-Footnote-2614160
Ref: 构建和 C API 的改变<2>-Footnote-3614203
Ref: 构建和 C API 的改变<2>-Footnote-4614246
Ref: 构建和 C API 的改变<2>-Footnote-5614289
Ref: 构建和 C API 的改变<2>-Footnote-6614331
Ref: 构建和 C API 的改变<2>-Footnote-7614374
Ref: 构建和 C API 的改变<2>-Footnote-8614417
Ref: 构建和 C API 的改变<2>-Footnote-9614460
Ref: 构建和 C API 的改变<2>-Footnote-10614503
Node: 其他改进614547
Ref: whatsnew/3 6 other-improvements614680
Ref: 6c7614680
Node: 弃用<3>615035
Ref: whatsnew/3 6 deprecated615149
Ref: 6cb615149
Node: 新关键字615462
Ref: whatsnew/3 6 new-keywords615558
Ref: 6cc615558
Ref: 新关键字-Footnote-1615947
Node: 已弃用的 Python 行为<2>615996
Ref: whatsnew/3 6 deprecated-python-behavior616148
Ref: 6cd616148
Ref: 已弃用的 Python 行为<2>-Footnote-1617349
Ref: 已弃用的 Python 行为<2>-Footnote-2617392
Ref: 已弃用的 Python 行为<2>-Footnote-3617435
Node: 已弃用的 Python 模块、函数和方法<2>617478
Ref: whatsnew/3 6 deprecated-python-modules-functions-and-methods617655
Ref: 6d0617655
Node: asynchat617944
Ref: whatsnew/3 6 asynchat618053
Ref: 6d1618053
Ref: asynchat-Footnote-1618241
Node: asyncore618284
Ref: whatsnew/3 6 asyncore618408
Ref: 6d2618408
Ref: asyncore-Footnote-1618596
Node: dbm<3>618639
Ref: whatsnew/3 6 dbm618767
Ref: 6d3618767
Ref: dbm<3>-Footnote-1619127
Node: distutils<4>619170
Ref: whatsnew/3 6 id2619293
Ref: 6d4619293
Ref: distutils<4>-Footnote-1619613
Node: grp619656
Ref: whatsnew/3 6 grp619785
Ref: 6d5619785
Ref: grp-Footnote-1619983
Node: importlib<5>620026
Ref: whatsnew/3 6 id3620148
Ref: 6d7620148
Node: os<5>620802
Ref: whatsnew/3 6 id4620926
Ref: 6de620926
Ref: os<5>-Footnote-1621220
Ref: os<5>-Footnote-2621263
Node: re<3>621306
Ref: whatsnew/3 6 id5621424
Ref: 6e0621424
Ref: re<3>-Footnote-1621750
Node: ssl<5>621793
Ref: whatsnew/3 6 id6621916
Ref: 6e1621916
Ref: ssl<5>-Footnote-1622711
Ref: ssl<5>-Footnote-2622754
Ref: ssl<5>-Footnote-3622797
Node: tkinter<4>622840
Ref: whatsnew/3 6 id7622965
Ref: 6e2622965
Node: venv<4>623126
Ref: whatsnew/3 6 id8623236
Ref: 6e3623236
Ref: venv<4>-Footnote-1623587
Node: 已弃用的 C API 函数和类型<2>623630
Ref: whatsnew/3 6 deprecated-functions-and-types-of-the-c-api623799
Ref: 6e4623799
Node: 弃用的构建选项624121
Ref: whatsnew/3 6 deprecated-build-options624234
Ref: 6e6624234
Node: 移除<3>624662
Ref: whatsnew/3 6 removed624783
Ref: 6e7624783
Node: API 与特性的移除<3>624873
Ref: whatsnew/3 6 api-and-feature-removals624944
Ref: 6e8624944
Ref: API 与特性的移除<3>-Footnote-1627026
Ref: API 与特性的移除<3>-Footnote-2627069
Node: 移植到Python 3 6627142
Ref: whatsnew/3 6 porting-to-python-3-6627285
Ref: 6ec627285
Node: 'python' 命令行为的变化627603
Ref: whatsnew/3 6 changes-in-python-command-behavior627718
Ref: 6ed627718
Ref: 'python' 命令行为的变化-Footnote-1628179
Node: Python API 的更改628222
Ref: whatsnew/3 6 changes-in-the-python-api628367
Ref: 6ee628367
Ref: Python API 的更改-Footnote-1638460
Ref: Python API 的更改-Footnote-2638502
Ref: Python API 的更改-Footnote-3638551
Ref: Python API 的更改-Footnote-4638594
Ref: Python API 的更改-Footnote-5638637
Ref: Python API 的更改-Footnote-6638680
Ref: Python API 的更改-Footnote-7638723
Ref: Python API 的更改-Footnote-8638766
Ref: Python API 的更改-Footnote-9638809
Ref: Python API 的更改-Footnote-10638852
Ref: Python API 的更改-Footnote-11638896
Ref: Python API 的更改-Footnote-12638946
Ref: Python API 的更改-Footnote-13638990
Ref: Python API 的更改-Footnote-14639034
Ref: Python API 的更改-Footnote-15639078
Ref: Python API 的更改-Footnote-16639122
Ref: Python API 的更改-Footnote-17639165
Ref: Python API 的更改-Footnote-18639209
Ref: Python API 的更改-Footnote-19639253
Ref: Python API 的更改-Footnote-20639297
Node: C API 中的改变<3>639341
Ref: whatsnew/3 6 changes-in-the-c-api639485
Ref: 706639485
Ref: C API 中的改变<3>-Footnote-1640131
Ref: C API 中的改变<3>-Footnote-2640174
Node: CPython 字节码的改变<4>640216
Ref: whatsnew/3 6 cpython-bytecode-changes640331
Ref: 708640331
Ref: CPython 字节码的改变<4>-Footnote-1641973
Ref: CPython 字节码的改变<4>-Footnote-2642016
Ref: CPython 字节码的改变<4>-Footnote-3642059
Ref: CPython 字节码的改变<4>-Footnote-4642102
Ref: CPython 字节码的改变<4>-Footnote-5642145
Ref: CPython 字节码的改变<4>-Footnote-6642188
Ref: CPython 字节码的改变<4>-Footnote-7642231
Ref: CPython 字节码的改变<4>-Footnote-8642274
Ref: CPython 字节码的改变<4>-Footnote-9642317
Node: Python 3 6 2 中的重要变化642360
Ref: whatsnew/3 6 notable-changes-in-python-3-6-2642525
Ref: 713642525
Node: New make regen-all build target642683
Ref: whatsnew/3 6 new-make-regen-all-build-target642825
Ref: 714642825
Ref: New make regen-all build target-Footnote-1643616
Ref: New make regen-all build target-Footnote-2643683
Node: Removal of make touch build target643726
Ref: whatsnew/3 6 removal-of-make-touch-build-target643868
Ref: 715643868
Ref: Removal of make touch build target-Footnote-1644295
Node: Python 3 6 4 中的重要变化644338
Ref: whatsnew/3 6 notable-changes-in-python-3-6-4644515
Ref: 716644515
Ref: Python 3 6 4 中的重要变化-Footnote-1644882
Ref: Python 3 6 4 中的重要变化-Footnote-2644925
Node: Python 3 6 5 中的重要变化644968
Ref: whatsnew/3 6 notable-changes-in-python-3-6-5645145
Ref: 717645145
Ref: Python 3 6 5 中的重要变化-Footnote-1645442
Node: Python 3 6 7 中的重要变化645485
Ref: whatsnew/3 6 notable-changes-in-python-3-6-7645663
Ref: 718645663
Ref: Python 3 6 7 中的重要变化-Footnote-1646034
Node: Python 3 6 10 中的重要变化646077
Ref: whatsnew/3 6 notable-changes-in-python-3-6-10646256
Ref: 719646256
Ref: Python 3 6 10 中的重要变化-Footnote-1646739
Node: Notable changes in Python 3 6 13646782
Ref: whatsnew/3 6 notable-changes-in-python-3-6-13646921
Ref: 71a646921
Ref: Notable changes in Python 3 6 13-Footnote-1647624
Node: Python 3 5 有什麼新功能647667
Ref: whatsnew/3 5 doc647837
Ref: 71b647837
Ref: whatsnew/3 5 what-s-new-in-python-3-5647837
Ref: 71c647837
Ref: Python 3 5 有什麼新功能-Footnote-1648735
Ref: Python 3 5 有什麼新功能-Footnote-2648795
Node: 摘要 - 发布重点<5>648844
Ref: whatsnew/3 5 summary-release-highlights648958
Ref: 71d648958
Ref: 摘要 - 发布重点<5>-Footnote-1652614
Ref: 摘要 - 发布重点<5>-Footnote-2652656
Ref: 摘要 - 发布重点<5>-Footnote-3652699
Ref: 摘要 - 发布重点<5>-Footnote-4652742
Ref: 摘要 - 发布重点<5>-Footnote-5652785
Ref: 摘要 - 发布重点<5>-Footnote-6652828
Ref: 摘要 - 发布重点<5>-Footnote-7652871
Node: 新的特性<6>652914
Ref: whatsnew/3 5 new-features653064
Ref: 730653064
Node: PEP 492 - 使用 async 和 await 语法实现协程654146
Ref: whatsnew/3 5 pep-492-coroutines-with-async-and-await-syntax654310
Ref: 731654310
Ref: whatsnew/3 5 whatsnew-pep-492654310
Ref: 71e654310
Ref: PEP 492 - 使用 async 和 await 语法实现协程-Footnote-1657366
Ref: PEP 492 - 使用 async 和 await 语法实现协程-Footnote-2657415
Node: PEP 465 - 用于矩阵乘法的专用中缀运算符657464
Ref: whatsnew/3 5 pep-465-a-dedicated-infix-operator-for-matrix-multiplication657683
Ref: 73a657683
Ref: whatsnew/3 5 whatsnew-pep-465657683
Ref: 71f657683
Ref: PEP 465 - 用于矩阵乘法的专用中缀运算符-Footnote-1659008
Ref: PEP 465 - 用于矩阵乘法的专用中缀运算符-Footnote-2659057
Node: PEP 448 - Additional Unpacking Generalizations659106
Ref: whatsnew/3 5 pep-448-additional-unpacking-generalizations659334
Ref: 73e659334
Ref: whatsnew/3 5 whatsnew-pep-448659334
Ref: 720659334
Ref: PEP 448 - Additional Unpacking Generalizations-Footnote-1660418
Ref: PEP 448 - Additional Unpacking Generalizations-Footnote-2660467
Node: PEP 461 - percent formatting support for bytes and bytearray660516
Ref: whatsnew/3 5 pep-461-percent-formatting-support-for-bytes-and-bytearray660714
Ref: 742660714
Ref: whatsnew/3 5 whatsnew-pep-461660714
Ref: 723660714
Ref: PEP 461 - percent formatting support for bytes and bytearray-Footnote-1662248
Ref: PEP 461 - percent formatting support for bytes and bytearray-Footnote-2662297
Node: PEP 484 - 类型提示662346
Ref: whatsnew/3 5 pep-484-type-hints662569
Ref: 744662569
Ref: whatsnew/3 5 whatsnew-pep-484662569
Ref: 721662569
Ref: PEP 484 - 类型提示-Footnote-1664201
Ref: PEP 484 - 类型提示-Footnote-2664250
Ref: PEP 484 - 类型提示-Footnote-3664299
Ref: PEP 484 - 类型提示-Footnote-4664328
Ref: PEP 484 - 类型提示-Footnote-5664377
Node: PEP 471 - os scandir function -- a better and faster directory iterator664426
Ref: whatsnew/3 5 pep-471-os-scandir-function-a-better-and-faster-directory-iterator664634
Ref: 746664634
Ref: whatsnew/3 5 whatsnew-pep-471664634
Ref: 72c664634
Ref: PEP 471 - os scandir function -- a better and faster directory iterator-Footnote-1665975
Ref: PEP 471 - os scandir function -- a better and faster directory iterator-Footnote-2666024
Node: PEP 475 Retry system calls failing with EINTR666073
Ref: whatsnew/3 5 pep-475-retry-system-calls-failing-with-eintr666314
Ref: 749666314
Ref: whatsnew/3 5 whatsnew-pep-475666314
Ref: 74a666314
Ref: PEP 475 Retry system calls failing with EINTR-Footnote-1669337
Ref: PEP 475 Retry system calls failing with EINTR-Footnote-2669386
Node: PEP 479 Change StopIteration handling inside generators669435
Ref: whatsnew/3 5 pep-479-change-stopiteration-handling-inside-generators669656
Ref: 774669656
Ref: whatsnew/3 5 whatsnew-pep-479669656
Ref: 6ce669656
Ref: PEP 479 Change StopIteration handling inside generators-Footnote-1671585
Ref: PEP 479 Change StopIteration handling inside generators-Footnote-2671634
Node: PEP 485 A function for testing approximate equality671683
Ref: whatsnew/3 5 pep-485-a-function-for-testing-approximate-equality671921
Ref: 777671921
Ref: whatsnew/3 5 whatsnew-pep-485671921
Ref: 778671921
Ref: PEP 485 A function for testing approximate equality-Footnote-1673086
Ref: PEP 485 A function for testing approximate equality-Footnote-2673135
Node: PEP 486 Make the Python Launcher aware of virtual environments673184
Ref: whatsnew/3 5 pep-486-make-the-python-launcher-aware-of-virtual-environments673399
Ref: 77b673399
Ref: whatsnew/3 5 whatsnew-pep-486673399
Ref: 77c673399
Ref: PEP 486 Make the Python Launcher aware of virtual environments-Footnote-1673964
Ref: PEP 486 Make the Python Launcher aware of virtual environments-Footnote-2674013
Ref: PEP 486 Make the Python Launcher aware of virtual environments-Footnote-3674062
Node: PEP 488 Elimination of PYO files674111
Ref: whatsnew/3 5 pep-488-elimination-of-pyo-files674326
Ref: 77d674326
Ref: whatsnew/3 5 whatsnew-pep-488674326
Ref: 728674326
Ref: PEP 488 Elimination of PYO files-Footnote-1675186
Ref: PEP 488 Elimination of PYO files-Footnote-2675235
Node: PEP 489 Multi-phase extension module initialization675284
Ref: whatsnew/3 5 pep-489-multi-phase-extension-module-initialization675428
Ref: 780675428
Ref: whatsnew/3 5 whatsnew-pep-489675428
Ref: 729675428
Ref: PEP 489 Multi-phase extension module initialization-Footnote-1676189
Ref: PEP 489 Multi-phase extension module initialization-Footnote-2676238
Ref: PEP 489 Multi-phase extension module initialization-Footnote-3676287
Node: 其他语言特性修改<5>676336
Ref: whatsnew/3 5 other-language-changes676477
Ref: 781676477
Ref: 其他语言特性修改<5>-Footnote-1677456
Ref: 其他语言特性修改<5>-Footnote-2677499
Ref: 其他语言特性修改<5>-Footnote-3677542
Ref: 其他语言特性修改<5>-Footnote-4677585
Ref: 其他语言特性修改<5>-Footnote-5677628
Ref: 其他语言特性修改<5>-Footnote-6677671
Ref: 其他语言特性修改<5>-Footnote-7677714
Node: 新增模块<5>677757
Ref: whatsnew/3 5 new-modules677901
Ref: 783677901
Node: typing<5>677988
Ref: whatsnew/3 5 typing678067
Ref: 784678067
Node: zipapp<2>678278
Ref: whatsnew/3 5 whatsnew-zipapp678357
Ref: 722678357
Ref: whatsnew/3 5 zipapp678357
Ref: 785678357
Ref: zipapp<2>-Footnote-1679066
Ref: zipapp<2>-Footnote-2679115
Ref: zipapp<2>-Footnote-3679160
Ref: zipapp<2>-Footnote-4679203
Node: 改进的模块<5>679252
Ref: whatsnew/3 5 improved-modules679390
Ref: 786679390
Node: argparse<2>680990
Ref: whatsnew/3 5 argparse681075
Ref: 787681075
Ref: argparse<2>-Footnote-1681398
Node: asyncio<6>681441
Ref: whatsnew/3 5 asyncio681538
Ref: 78b681538
Ref: asyncio<6>-Footnote-1685024
Ref: asyncio<6>-Footnote-2685067
Ref: asyncio<6>-Footnote-3685110
Node: bz2685155
Ref: whatsnew/3 5 bz2685244
Ref: 795685244
Ref: bz2-Footnote-1685499
Node: cgi685542
Ref: whatsnew/3 5 cgi685629
Ref: 797685629
Ref: cgi-Footnote-1685824
Node: cmath<2>685867
Ref: whatsnew/3 5 cmath685955
Ref: 798685955
Ref: cmath<2>-Footnote-1686169
Node: code686212
Ref: whatsnew/3 5 code686311
Ref: 799686311
Ref: code-Footnote-1686562
Node: collections<5>686605
Ref: whatsnew/3 5 collections686714
Ref: 79b686714
Ref: whatsnew/3 5 whatsnew-ordereddict686755
Ref: 72a686755
Ref: collections<5>-Footnote-1688040
Ref: collections<5>-Footnote-2688083
Ref: collections<5>-Footnote-3688126
Ref: collections<5>-Footnote-4688169
Ref: collections<5>-Footnote-5688212
Node: collections abc<2>688255
Ref: whatsnew/3 5 collections-abc688373
Ref: 7a7688373
Ref: collections abc<2>-Footnote-1689043
Ref: collections abc<2>-Footnote-2689086
Ref: collections abc<2>-Footnote-3689129
Ref: collections abc<2>-Footnote-4689172
Node: compileall<3>689219
Ref: whatsnew/3 5 compileall689344
Ref: 7ad689344
Ref: compileall<3>-Footnote-1690221
Ref: compileall<3>-Footnote-2690264
Ref: compileall<3>-Footnote-3690307
Node: concurrent futures<4>690350
Ref: whatsnew/3 5 concurrent-futures690469
Ref: 7b0690469
Ref: concurrent futures<4>-Footnote-1690971
Ref: concurrent futures<4>-Footnote-2691014
Node: configparser691057
Ref: whatsnew/3 5 configparser691176
Ref: 7b2691176
Ref: configparser-Footnote-1692132
Node: contextlib<3>692175
Ref: whatsnew/3 5 contextlib692279
Ref: 7b3692279
Ref: contextlib<3>-Footnote-1692895
Node: csv<2>692938
Ref: whatsnew/3 5 csv693039
Ref: 7b6693039
Ref: csv<2>-Footnote-1693243
Node: curses<3>693286
Ref: whatsnew/3 5 curses693380
Ref: 7b8693380
Ref: curses<3>-Footnote-1693661
Node: dbm<4>693703
Ref: whatsnew/3 5 dbm693798
Ref: 7ba693798
Ref: dbm<4>-Footnote-1694001
Node: difflib694044
Ref: whatsnew/3 5 difflib694142
Ref: 7bb694142
Ref: difflib-Footnote-1694678
Ref: difflib-Footnote-2694720
Node: distutils<5>694763
Ref: whatsnew/3 5 distutils694862
Ref: 7be694862
Ref: distutils<5>-Footnote-1695317
Ref: distutils<5>-Footnote-2695359
Node: doctest695402
Ref: whatsnew/3 5 doctest695502
Ref: 7bf695502
Ref: doctest-Footnote-1695787
Node: email<2>695830
Ref: whatsnew/3 5 email695925
Ref: 7c2695925
Ref: email<2>-Footnote-1697036
Ref: email<2>-Footnote-2697079
Ref: email<2>-Footnote-3697122
Ref: email<2>-Footnote-4697171
Ref: email<2>-Footnote-5697220
Ref: email<2>-Footnote-6697263
Node: enum<4>697306
Ref: whatsnew/3 5 enum697409
Ref: 7c8697409
Ref: enum<4>-Footnote-1697806
Node: faulthandler<2>697849
Ref: whatsnew/3 5 faulthandler697956
Ref: 7c9697956
Ref: faulthandler<2>-Footnote-1698268
Node: functools<3>698311
Ref: whatsnew/3 5 functools698415
Ref: 7cd698415
Ref: whatsnew/3 5 whatsnew-lrucache698454
Ref: 72d698454
Ref: functools<3>-Footnote-1698680
Node: glob698723
Ref: whatsnew/3 5 glob698819
Ref: 7ce698819
Ref: glob-Footnote-1699071
Node: gzip<2>699114
Ref: whatsnew/3 5 gzip699203
Ref: 7cf699203
Ref: gzip<2>-Footnote-1699428
Node: heapq699471
Ref: whatsnew/3 5 heapq699563
Ref: 7d0699563
Ref: heapq-Footnote-1700209
Node: http<2>700252
Ref: whatsnew/3 5 http700351
Ref: 7d3700351
Ref: http<2>-Footnote-1700597
Node: http client<3>700640
Ref: whatsnew/3 5 http-client700753
Ref: 7d4700753
Ref: http client<3>-Footnote-1701503
Node: idlelib 与 IDLE<3>701545
Ref: whatsnew/3 5 idlelib-and-idle701661
Ref: 7d8701661
Node: imaplib<2>702054
Ref: whatsnew/3 5 imaplib702162
Ref: 7d9702162
Ref: imaplib<2>-Footnote-1703041
Ref: imaplib<2>-Footnote-2703083
Ref: imaplib<2>-Footnote-3703132
Ref: imaplib<2>-Footnote-4703181
Ref: imaplib<2>-Footnote-5703230
Ref: imaplib<2>-Footnote-6703273
Node: imghdr703316
Ref: whatsnew/3 5 imghdr703417
Ref: 7dd703417
Ref: imghdr-Footnote-1703711
Ref: imghdr-Footnote-2703742
Ref: imghdr-Footnote-3703785
Ref: imghdr-Footnote-4703828
Node: importlib<6>703871
Ref: whatsnew/3 5 importlib703972
Ref: 7df703972
Ref: importlib<6>-Footnote-1704807
Ref: importlib<6>-Footnote-2704850
Ref: importlib<6>-Footnote-3704893
Node: inspect<4>704936
Ref: whatsnew/3 5 inspect705036
Ref: 7e3705036
Ref: inspect<4>-Footnote-1706599
Ref: inspect<4>-Footnote-2706642
Ref: inspect<4>-Footnote-3706685
Ref: inspect<4>-Footnote-4706728
Ref: inspect<4>-Footnote-5706771
Ref: inspect<4>-Footnote-6706814
Ref: inspect<4>-Footnote-7706857
Ref: inspect<4>-Footnote-8706900
Node: io<3>706943
Ref: whatsnew/3 5 io707043
Ref: 7f1707043
Ref: io<3>-Footnote-1707341
Node: ipaddress<3>707384
Ref: whatsnew/3 5 ipaddress707481
Ref: 7f5707481
Ref: ipaddress<3>-Footnote-1708521
Ref: ipaddress<3>-Footnote-2708564
Node: json<2>708607
Ref: whatsnew/3 5 json708708
Ref: 7f6708708
Ref: json<2>-Footnote-1709208
Ref: json<2>-Footnote-2709251
Node: linecache709294
Ref: whatsnew/3 5 linecache709392
Ref: 7f8709392
Ref: linecache-Footnote-1709802
Node: locale<3>709845
Ref: whatsnew/3 5 locale709946
Ref: 7fb709946
Ref: locale<3>-Footnote-1710517
Node: logging<4>710560
Ref: whatsnew/3 5 logging710656
Ref: 7fd710656
Ref: logging<4>-Footnote-1711632
Ref: logging<4>-Footnote-2711675
Node: lzma711718
Ref: whatsnew/3 5 lzma711812
Ref: 804711812
Ref: lzma-Footnote-1712074
Node: math<5>712117
Ref: whatsnew/3 5 math712219
Ref: 806712219
Ref: math<5>-Footnote-1712761
Ref: math<5>-Footnote-2712804
Ref: math<5>-Footnote-3712847
Node: multiprocessing<5>712890
Ref: whatsnew/3 5 multiprocessing712996
Ref: 807712996
Ref: multiprocessing<5>-Footnote-1713246
Node: operator713289
Ref: whatsnew/3 5 operator713393
Ref: 809713393
Ref: operator-Footnote-1713798
Ref: operator-Footnote-2713841
Node: os<6>713884
Ref: whatsnew/3 5 os713980
Ref: 80e713980
Ref: os<6>-Footnote-1715834
Ref: os<6>-Footnote-2715877
Ref: os<6>-Footnote-3715920
Ref: os<6>-Footnote-4715963
Ref: os<6>-Footnote-5716006
Ref: os<6>-Footnote-6716049
Node: pathlib<5>716092
Ref: whatsnew/3 5 pathlib716189
Ref: 816716189
Ref: pathlib<5>-Footnote-1717672
Ref: pathlib<5>-Footnote-2717715
Ref: pathlib<5>-Footnote-3717758
Ref: pathlib<5>-Footnote-4717801
Ref: pathlib<5>-Footnote-5717844
Node: pickle<3>717887
Ref: whatsnew/3 5 pickle717988
Ref: 81f717988
Ref: pickle<3>-Footnote-1718304
Node: poplib<2>718347
Ref: whatsnew/3 5 poplib718443
Ref: 820718443
Ref: poplib<2>-Footnote-1718685
Ref: poplib<2>-Footnote-2718734
Node: re<4>718777
Ref: whatsnew/3 5 re718875
Ref: 822718875
Ref: re<4>-Footnote-1720123
Ref: re<4>-Footnote-2720165
Ref: re<4>-Footnote-3720208
Ref: re<4>-Footnote-4720253
Node: readline<2>720296
Ref: whatsnew/3 5 readline720394
Ref: 82a720394
Ref: readline<2>-Footnote-1720657
Node: selectors720700
Ref: whatsnew/3 5 selectors720802
Ref: 82c720802
Ref: selectors-Footnote-1721024
Node: shutil<2>721067
Ref: whatsnew/3 5 shutil721167
Ref: 82d721167
Ref: shutil<2>-Footnote-1721646
Ref: shutil<2>-Footnote-2721689
Node: signal<3>721731
Ref: whatsnew/3 5 signal721827
Ref: 82e721827
Ref: signal<3>-Footnote-1722290
Ref: signal<3>-Footnote-2722333
Node: smtpd722376
Ref: whatsnew/3 5 smtpd722473
Ref: 82f722473
Ref: smtpd-Footnote-1724157
Ref: smtpd-Footnote-2724200
Ref: smtpd-Footnote-3724249
Ref: smtpd-Footnote-4724292
Ref: smtpd-Footnote-5724341
Ref: smtpd-Footnote-6724384
Node: smtplib<2>724427
Ref: whatsnew/3 5 smtplib724521
Ref: 830724521
Ref: smtplib<2>-Footnote-1725142
Ref: smtplib<2>-Footnote-2725185
Ref: smtplib<2>-Footnote-3725228
Ref: smtplib<2>-Footnote-4725277
Node: sndhdr725320
Ref: whatsnew/3 5 sndhdr725418
Ref: 835725418
Ref: sndhdr-Footnote-1725633
Node: socket<6>725676
Ref: whatsnew/3 5 socket725770
Ref: 838725770
Ref: socket<6>-Footnote-1726741
Ref: socket<6>-Footnote-2726784
Ref: socket<6>-Footnote-3726827
Ref: socket<6>-Footnote-4726870
Node: ssl<6>726913
Ref: whatsnew/3 5 ssl727011
Ref: 83c727011
Node: 内存 BIO 支持727139
Ref: whatsnew/3 5 memory-bio-support727254
Ref: 83d727254
Ref: whatsnew/3 5 whatsnew-sslmemorybio727254
Ref: 72b727254
Ref: 内存 BIO 支持-Footnote-1728133
Node: Application-Layer Protocol Negotiation Support728176
Ref: whatsnew/3 5 application-layer-protocol-negotiation-support728313
Ref: 83f728313
Ref: Application-Layer Protocol Negotiation Support-Footnote-1729024
Ref: Application-Layer Protocol Negotiation Support-Footnote-2729067
Node: Other Changes729116
Ref: whatsnew/3 5 other-changes729227
Ref: 843729227
Ref: Other Changes-Footnote-1730820
Ref: Other Changes-Footnote-2730863
Ref: Other Changes-Footnote-3730906
Ref: Other Changes-Footnote-4730949
Ref: Other Changes-Footnote-5730998
Ref: Other Changes-Footnote-6731041
Ref: Other Changes-Footnote-7731084
Ref: Other Changes-Footnote-8731127
Node: sqlite3<3>731170
Ref: whatsnew/3 5 sqlite3731272
Ref: 84c731272
Ref: sqlite3<3>-Footnote-1731601
Ref: sqlite3<3>-Footnote-2731644
Node: subprocess<3>731687
Ref: whatsnew/3 5 subprocess731789
Ref: 84e731789
Ref: whatsnew/3 5 whatsnew-subprocess731789
Ref: 72e731789
Ref: subprocess<3>-Footnote-1732801
Node: sys<6>732844
Ref: whatsnew/3 5 sys732945
Ref: 850732945
Ref: sys<6>-Footnote-1733595
Ref: sys<6>-Footnote-2733638
Node: sysconfig733681
Ref: whatsnew/3 5 sysconfig733779
Ref: 853733779
Ref: sysconfig-Footnote-1734012
Node: tarfile<2>734055
Ref: whatsnew/3 5 tarfile734159
Ref: 854734159
Ref: tarfile<2>-Footnote-1735070
Ref: tarfile<2>-Footnote-2735113
Ref: tarfile<2>-Footnote-3735156
Node: threading<3>735199
Ref: whatsnew/3 5 threading735301
Ref: 85a735301
Ref: threading<3>-Footnote-1735553
Node: time<5>735596
Ref: whatsnew/3 5 time735697
Ref: 85d735697
Ref: time<5>-Footnote-1735874
Node: timeit<2>735917
Ref: whatsnew/3 5 timeit736016
Ref: 85f736016
Ref: timeit<2>-Footnote-1736483
Ref: timeit<2>-Footnote-2736526
Node: tkinter<5>736568
Ref: whatsnew/3 5 tkinter736672
Ref: 861736672
Ref: tkinter<5>-Footnote-1737004
Node: traceback<2>737047
Ref: whatsnew/3 5 traceback737150
Ref: 862737150
Ref: whatsnew/3 5 whatsnew-traceback737150
Ref: 72f737150
Ref: traceback<2>-Footnote-1737733
Ref: traceback<2>-Footnote-2737776
Ref: traceback<2>-Footnote-3737819
Node: types<2>737862
Ref: whatsnew/3 5 types737969
Ref: 86a737969
Ref: types<2>-Footnote-1738413
Ref: types<2>-Footnote-2738456
Node: unicodedata<5>738499
Ref: whatsnew/3 5 unicodedata738605
Ref: 86d738605
Ref: unicodedata<5>-Footnote-1738757
Node: unittest<3>738807
Ref: whatsnew/3 5 unittest738921
Ref: 86e738921
Ref: unittest<3>-Footnote-1739715
Ref: unittest<3>-Footnote-2739758
Ref: unittest<3>-Footnote-3739801
Node: unittest mock<3>739844
Ref: whatsnew/3 5 unittest-mock739950
Ref: 872739950
Ref: unittest mock<3>-Footnote-1740891
Ref: unittest mock<3>-Footnote-2740934
Ref: unittest mock<3>-Footnote-3740977
Ref: unittest mock<3>-Footnote-4741020
Ref: unittest mock<3>-Footnote-5741063
Ref: unittest mock<3>-Footnote-6741106
Node: urllib741149
Ref: whatsnew/3 5 urllib741251
Ref: 878741251
Ref: urllib-Footnote-1742411
Ref: urllib-Footnote-2742454
Ref: urllib-Footnote-3742496
Ref: urllib-Footnote-4742539
Ref: urllib-Footnote-5742582
Ref: urllib-Footnote-6742631
Ref: urllib-Footnote-7742680
Ref: urllib-Footnote-8742729
Node: wsgiref742772
Ref: whatsnew/3 5 wsgiref742867
Ref: 87d742867
Ref: wsgiref-Footnote-1743105
Node: xmlrpc<2>743147
Ref: whatsnew/3 5 xmlrpc743243
Ref: 87f743243
Ref: xmlrpc<2>-Footnote-1743613
Ref: xmlrpc<2>-Footnote-2743656
Node: xml sax743699
Ref: whatsnew/3 5 xml-sax743798
Ref: 880743798
Ref: xml sax-Footnote-1744131
Ref: xml sax-Footnote-2744173
Node: zipfile<3>744216
Ref: whatsnew/3 5 zipfile744297
Ref: 883744297
Ref: zipfile<3>-Footnote-1744637
Ref: zipfile<3>-Footnote-2744680
Node: 其他模块级更改744723
Ref: whatsnew/3 5 other-module-level-changes744861
Ref: 884744861
Ref: 其他模块级更改-Footnote-1745175
Node: 性能优化<5>745218
Ref: whatsnew/3 5 optimizations745366
Ref: 885745366
Ref: 性能优化<5>-Footnote-1748417
Ref: 性能优化<5>-Footnote-2748460
Ref: 性能优化<5>-Footnote-3748503
Ref: 性能优化<5>-Footnote-4748546
Ref: 性能优化<5>-Footnote-5748589
Ref: 性能优化<5>-Footnote-6748632
Ref: 性能优化<5>-Footnote-7748675
Ref: 性能优化<5>-Footnote-8748718
Ref: 性能优化<5>-Footnote-9748761
Ref: 性能优化<5>-Footnote-10748804
Ref: 性能优化<5>-Footnote-11748848
Ref: 性能优化<5>-Footnote-12748892
Ref: 性能优化<5>-Footnote-13748936
Ref: 性能优化<5>-Footnote-14748980
Ref: 性能优化<5>-Footnote-15749024
Ref: 性能优化<5>-Footnote-16749068
Ref: 性能优化<5>-Footnote-17749112
Ref: 性能优化<5>-Footnote-18749156
Ref: 性能优化<5>-Footnote-19749200
Ref: 性能优化<5>-Footnote-20749244
Node: 构建和 C API 的改变<3>749288
Ref: whatsnew/3 5 build-and-c-api-changes749424
Ref: 892749424
Ref: 构建和 C API 的改变<3>-Footnote-1752956
Ref: 构建和 C API 的改变<3>-Footnote-2752999
Ref: 构建和 C API 的改变<3>-Footnote-3753042
Ref: 构建和 C API 的改变<3>-Footnote-4753085
Ref: 构建和 C API 的改变<3>-Footnote-5753128
Ref: 构建和 C API 的改变<3>-Footnote-6753171
Ref: 构建和 C API 的改变<3>-Footnote-7753220
Ref: 构建和 C API 的改变<3>-Footnote-8753263
Ref: 构建和 C API 的改变<3>-Footnote-9753306
Ref: 构建和 C API 的改变<3>-Footnote-10753355
Node: 弃用<4>753394
Ref: whatsnew/3 5 deprecated753524
Ref: 89e753524
Node: 新关键字<2>753779
Ref: whatsnew/3 5 new-keywords753878
Ref: 89f753878
Ref: 新关键字<2>-Footnote-1754148
Node: 已弃用的 Python 行为<3>754197
Ref: whatsnew/3 5 deprecated-python-behavior754329
Ref: 8a0754329
Node: 不支持的操作系统754738
Ref: whatsnew/3 5 unsupported-operating-systems754902
Ref: 8a1754902
Ref: 不支持的操作系统-Footnote-1755125
Node: 已弃用的 Python 模块、函数和方法<3>755174
Ref: whatsnew/3 5 deprecated-python-modules-functions-and-methods755300
Ref: 8a2755300
Ref: 已弃用的 Python 模块、函数和方法<3>-Footnote-1758218
Ref: 已弃用的 Python 模块、函数和方法<3>-Footnote-2758261
Ref: 已弃用的 Python 模块、函数和方法<3>-Footnote-3758303
Ref: 已弃用的 Python 模块、函数和方法<3>-Footnote-4758346
Ref: 已弃用的 Python 模块、函数和方法<3>-Footnote-5758389
Ref: 已弃用的 Python 模块、函数和方法<3>-Footnote-6758432
Ref: 已弃用的 Python 模块、函数和方法<3>-Footnote-7758475
Ref: 已弃用的 Python 模块、函数和方法<3>-Footnote-8758518
Node: 移除<4>758561
Ref: whatsnew/3 5 removed758682
Ref: 8a8758682
Node: API 与特性的移除<4>758772
Ref: whatsnew/3 5 api-and-feature-removals758843
Ref: 8a9758843
Ref: API 与特性的移除<4>-Footnote-1759690
Ref: API 与特性的移除<4>-Footnote-2759732
Node: 移植到Python 3 5759775
Ref: whatsnew/3 5 porting-to-python-3-5759915
Ref: 8aa759915
Node: Python 行为的改变<2>760192
Ref: whatsnew/3 5 changes-in-python-behavior760304
Ref: 8ab760304
Node: 改变了的Python API760684
Ref: whatsnew/3 5 changes-in-the-python-api760826
Ref: 8ac760826
Ref: 改变了的Python API-Footnote-1767730
Ref: 改变了的Python API-Footnote-2767779
Ref: 改变了的Python API-Footnote-3767822
Ref: 改变了的Python API-Footnote-4767865
Ref: 改变了的Python API-Footnote-5767908
Ref: 改变了的Python API-Footnote-6767951
Ref: 改变了的Python API-Footnote-7767994
Ref: 改变了的Python API-Footnote-8768037
Ref: 改变了的Python API-Footnote-9768080
Ref: 改变了的Python API-Footnote-10768123
Ref: 改变了的Python API-Footnote-11768167
Ref: 改变了的Python API-Footnote-12768211
Ref: 改变了的Python API-Footnote-13768254
Ref: 改变了的Python API-Footnote-14768304
Ref: 改变了的Python API-Footnote-15768354
Ref: 改变了的Python API-Footnote-16768398
Ref: 改变了的Python API-Footnote-17768442
Ref: 改变了的Python API-Footnote-18768486
Node: C API 中的改变<4>768529
Ref: whatsnew/3 5 changes-in-the-c-api768637
Ref: 8b6768637
Ref: C API 中的改变<4>-Footnote-1769896
Ref: C API 中的改变<4>-Footnote-2769939
Ref: C API 中的改变<4>-Footnote-3769982
Node: Python 3 5 4 的显著变化770031
Ref: whatsnew/3 5 notable-changes-in-python-3-5-4770153
Ref: 8bb770153
Node: New make regen-all build target<2>770379
Ref: whatsnew/3 5 new-make-regen-all-build-target770524
Ref: 8bc770524
Ref: New make regen-all build target<2>-Footnote-1771315
Ref: New make regen-all build target<2>-Footnote-2771382
Node: Removal of make touch build target<2>771425
Ref: whatsnew/3 5 removal-of-make-touch-build-target771570
Ref: 8bd771570
Ref: Removal of make touch build target<2>-Footnote-1771997
Node: Python 3 4 有什么新变化772040
Ref: whatsnew/3 4 doc772210
Ref: 8be772210
Ref: whatsnew/3 4 what-s-new-in-python-3-4772210
Ref: 8bf772210
Ref: Python 3 4 有什么新变化-Footnote-1772909
Ref: Python 3 4 有什么新变化-Footnote-2772969
Node: 摘要 - 发布重点<6>773018
Ref: whatsnew/3 4 summary-release-highlights773132
Ref: 8c0773132
Ref: 摘要 - 发布重点<6>-Footnote-1777379
Ref: 摘要 - 发布重点<6>-Footnote-2777428
Ref: 摘要 - 发布重点<6>-Footnote-3777477
Ref: 摘要 - 发布重点<6>-Footnote-4777520
Ref: 摘要 - 发布重点<6>-Footnote-5777569
Ref: 摘要 - 发布重点<6>-Footnote-6777612
Ref: 摘要 - 发布重点<6>-Footnote-7777661
Ref: 摘要 - 发布重点<6>-Footnote-8777710
Ref: 摘要 - 发布重点<6>-Footnote-9777759
Ref: 摘要 - 发布重点<6>-Footnote-10777808
Ref: 摘要 - 发布重点<6>-Footnote-11777858
Ref: 摘要 - 发布重点<6>-Footnote-12777908
Ref: 摘要 - 发布重点<6>-Footnote-13777958
Ref: 摘要 - 发布重点<6>-Footnote-14778008
Ref: 摘要 - 发布重点<6>-Footnote-15778058
Ref: 摘要 - 发布重点<6>-Footnote-16778101
Ref: 摘要 - 发布重点<6>-Footnote-17778145
Ref: 摘要 - 发布重点<6>-Footnote-18778195
Ref: 摘要 - 发布重点<6>-Footnote-19778245
Ref: 摘要 - 发布重点<6>-Footnote-20778289
Ref: 摘要 - 发布重点<6>-Footnote-21778335
Ref: 摘要 - 发布重点<6>-Footnote-22778385
Ref: 摘要 - 发布重点<6>-Footnote-23778435
Ref: 摘要 - 发布重点<6>-Footnote-24778479
Ref: 摘要 - 发布重点<6>-Footnote-25778529
Node: 新的特性<7>778579
Ref: whatsnew/3 4 new-features778717
Ref: 8dc778717
Node: PEP 453 Explicit Bootstrapping of PIP in Python Installations779207
Ref: whatsnew/3 4 pep-453-explicit-bootstrapping-of-pip-in-python-installations779387
Ref: 8dd779387
Ref: whatsnew/3 4 whatsnew-pep-453779387
Ref: 8c1779387
Node: Bootstrapping pip By Default779590
Ref: whatsnew/3 4 bootstrapping-pip-by-default779737
Ref: 8de779737
Ref: Bootstrapping pip By Default-Footnote-1782639
Ref: Bootstrapping pip By Default-Footnote-2782688
Node: 文档更改782783
Ref: whatsnew/3 4 documentation-changes782930
Ref: 8e1782930
Ref: 文档更改-Footnote-1783804
Ref: 文档更改-Footnote-2783841
Node: PEP 446 Newly Created File Descriptors Are Non-Inheritable783890
Ref: whatsnew/3 4 pep-446-newly-created-file-descriptors-are-non-inheritable784109
Ref: 8e6784109
Ref: whatsnew/3 4 whatsnew-pep-446784109
Ref: 8c2784109
Ref: PEP 446 Newly Created File Descriptors Are Non-Inheritable-Footnote-1785121
Ref: PEP 446 Newly Created File Descriptors Are Non-Inheritable-Footnote-2785170
Node: Improvements to Codec Handling785219
Ref: whatsnew/3 4 codec-handling-improvements785424
Ref: 8c4785424
Ref: whatsnew/3 4 improvements-to-codec-handling785424
Ref: 8ee785424
Ref: Improvements to Codec Handling-Footnote-1789625
Ref: Improvements to Codec Handling-Footnote-2789667
Ref: Improvements to Codec Handling-Footnote-3789710
Ref: Improvements to Codec Handling-Footnote-4789753
Node: PEP 451 A ModuleSpec Type for the Import System789796
Ref: whatsnew/3 4 pep-451-a-modulespec-type-for-the-import-system789970
Ref: 8f3789970
Ref: whatsnew/3 4 whatsnew-pep-451789970
Ref: 8c5789970
Ref: PEP 451 A ModuleSpec Type for the Import System-Footnote-1790917
Ref: PEP 451 A ModuleSpec Type for the Import System-Footnote-2790966
Node: 其他语言特性修改<6>791046
Ref: whatsnew/3 4 other-language-changes791181
Ref: 8f5791181
Ref: 其他语言特性修改<6>-Footnote-1793799
Ref: 其他语言特性修改<6>-Footnote-2793842
Ref: 其他语言特性修改<6>-Footnote-3793885
Ref: 其他语言特性修改<6>-Footnote-4793928
Ref: 其他语言特性修改<6>-Footnote-5793973
Ref: 其他语言特性修改<6>-Footnote-6794016
Ref: 其他语言特性修改<6>-Footnote-7794059
Ref: 其他语言特性修改<6>-Footnote-8794102
Ref: 其他语言特性修改<6>-Footnote-9794145
Ref: 其他语言特性修改<6>-Footnote-10794188
Ref: 其他语言特性修改<6>-Footnote-11794232
Ref: 其他语言特性修改<6>-Footnote-12794282
Node: 新增模块<6>794326
Ref: whatsnew/3 4 new-modules794458
Ref: 8fa794458
Node: asyncio<7>794667
Ref: whatsnew/3 4 asyncio794747
Ref: 8fb794747
Ref: whatsnew/3 4 whatsnew-asyncio794747
Ref: 8c7794747
Ref: asyncio<7>-Footnote-1795334
Ref: asyncio<7>-Footnote-2795383
Node: ensurepip795432
Ref: whatsnew/3 4 ensurepip795528
Ref: 8fc795528
Ref: whatsnew/3 4 whatsnew-ensurepip795528
Ref: 8c8795528
Ref: ensurepip-Footnote-1796800
Node: enum<5>796849
Ref: whatsnew/3 4 enum796945
Ref: 8fd796945
Ref: whatsnew/3 4 whatsnew-enum796945
Ref: 8c9796945
Ref: enum<5>-Footnote-1797515
Ref: enum<5>-Footnote-2797564
Node: pathlib<6>797613
Ref: whatsnew/3 4 pathlib797712
Ref: 8fe797712
Ref: whatsnew/3 4 whatsnew-pathlib797712
Ref: 8ca797712
Ref: pathlib<6>-Footnote-1798321
Node: selectors<2>798370
Ref: whatsnew/3 4 selectors798475
Ref: 8ff798475
Ref: whatsnew/3 4 whatsnew-selectors798475
Ref: 8cb798475
Ref: selectors<2>-Footnote-1798733
Node: statistics<3>798782
Ref: whatsnew/3 4 statistics798891
Ref: 900798891
Ref: whatsnew/3 4 whatsnew-statistics798891
Ref: 8cc798891
Ref: statistics<3>-Footnote-1799351
Ref: statistics<3>-Footnote-2799400
Node: tracemalloc<4>799449
Ref: whatsnew/3 4 tracemalloc799537
Ref: 901799537
Ref: whatsnew/3 4 whatsnew-tracemalloc799537
Ref: 8cd799537
Ref: tracemalloc<4>-Footnote-1800194
Ref: tracemalloc<4>-Footnote-2800243
Node: 改进的模块<6>800292
Ref: whatsnew/3 4 improved-modules800439
Ref: 902800439
Node: abc801744
Ref: whatsnew/3 4 abc801818
Ref: 903801818
Ref: abc-Footnote-1802339
Ref: abc-Footnote-2802382
Node: aifc<2>802425
Ref: whatsnew/3 4 aifc802519
Ref: 907802519
Ref: aifc<2>-Footnote-1803157
Ref: aifc<2>-Footnote-2803200
Ref: aifc<2>-Footnote-3803243
Node: argparse<3>803285
Ref: whatsnew/3 4 argparse803383
Ref: 90c803383
Ref: argparse<3>-Footnote-1803629
Node: audioop803672
Ref: whatsnew/3 4 audioop803769
Ref: 90e803769
Ref: audioop-Footnote-1804308
Ref: audioop-Footnote-2804351
Ref: audioop-Footnote-3804394
Node: base64804437
Ref: whatsnew/3 4 base64804537
Ref: 910804537
Ref: base64-Footnote-1805368
Ref: base64-Footnote-2805411
Node: collections<6>805454
Ref: whatsnew/3 4 collections805555
Ref: 915805555
Ref: collections<6>-Footnote-1805885
Node: colorsys805928
Ref: whatsnew/3 4 colorsys806036
Ref: 917806036
Ref: colorsys-Footnote-1806404
Node: contextlib<4>806447
Ref: whatsnew/3 4 contextlib806547
Ref: 918806547
Ref: contextlib<4>-Footnote-1807732
Ref: contextlib<4>-Footnote-2807775
Ref: contextlib<4>-Footnote-3807818
Node: dbm<5>807861
Ref: whatsnew/3 4 dbm807959
Ref: 91c807959
Ref: dbm<5>-Footnote-1808306
Node: dis<2>808349
Ref: whatsnew/3 4 dis808444
Ref: 91e808444
Ref: dis<2>-Footnote-1811043
Ref: dis<2>-Footnote-2811086
Ref: dis<2>-Footnote-3811129
Node: doctest<2>811172
Ref: whatsnew/3 4 doctest811269
Ref: 928811269
Ref: doctest<2>-Footnote-1812037
Ref: doctest<2>-Footnote-2812080
Ref: doctest<2>-Footnote-3812123
Node: email<3>812165
Ref: whatsnew/3 4 email812263
Ref: 92b812263
Ref: whatsnew/3 4 whatsnew-email-contentmanager813511
Ref: 8d1813511
Ref: email<3>-Footnote-1814438
Ref: email<3>-Footnote-2814481
Ref: email<3>-Footnote-3814524
Ref: email<3>-Footnote-4814567
Node: filecmp814610
Ref: whatsnew/3 4 filecmp814710
Ref: 933814710
Ref: filecmp-Footnote-1815456
Ref: filecmp-Footnote-2815499
Node: functools<4>815542
Ref: whatsnew/3 4 functools815639
Ref: 937815639
Ref: whatsnew/3 4 whatsnew-singledispatch816086
Ref: 8ce816086
Ref: functools<4>-Footnote-1817039
Ref: functools<4>-Footnote-2817081
Ref: functools<4>-Footnote-3817130
Ref: functools<4>-Footnote-4817173
Node: gc<4>817216
Ref: whatsnew/3 4 gc817313
Ref: 939817313
Ref: gc<4>-Footnote-1817579
Node: glob<2>817622
Ref: whatsnew/3 4 glob817717
Ref: 93b817717
Ref: glob<2>-Footnote-1818021
Node: hashlib<3>818063
Ref: whatsnew/3 4 hashlib818160
Ref: 93d818160
Ref: hashlib<3>-Footnote-1818793
Ref: hashlib<3>-Footnote-2818838
Ref: hashlib<3>-Footnote-3818881
Node: hmac<2>818924
Ref: whatsnew/3 4 hmac819018
Ref: 93f819018
Ref: hmac<2>-Footnote-1820044
Ref: hmac<2>-Footnote-2820087
Ref: hmac<2>-Footnote-3820130
Ref: hmac<2>-Footnote-4820179
Node: html820222
Ref: whatsnew/3 4 html820313
Ref: 945820313
Ref: html-Footnote-1821070
Ref: html-Footnote-2821112
Ref: html-Footnote-3821155
Node: http<3>821198
Ref: whatsnew/3 4 http821301
Ref: 946821301
Ref: http<3>-Footnote-1821942
Ref: http<3>-Footnote-2821985
Node: idlelib 与 IDLE<4>822028
Ref: whatsnew/3 4 idlelib-and-idle822139
Ref: 949822139
Node: importlib<7>822532
Ref: whatsnew/3 4 importlib822646
Ref: 94a822646
Ref: importlib<7>-Footnote-1824647
Ref: importlib<7>-Footnote-2824690
Ref: importlib<7>-Footnote-3824733
Ref: importlib<7>-Footnote-4824776
Ref: importlib<7>-Footnote-5824819
Ref: importlib<7>-Footnote-6824862
Ref: importlib<7>-Footnote-7824905
Node: inspect<5>824948
Ref: whatsnew/3 4 inspect825055
Ref: 952825055
Ref: inspect<5>-Footnote-1826769
Ref: inspect<5>-Footnote-2826812
Ref: inspect<5>-Footnote-3826855
Ref: inspect<5>-Footnote-4826898
Ref: inspect<5>-Footnote-5826941
Ref: inspect<5>-Footnote-6826984
Node: ipaddress<4>827027
Ref: whatsnew/3 4 ipaddress827132
Ref: 956827132
Ref: ipaddress<4>-Footnote-1827658
Node: logging<5>827701
Ref: whatsnew/3 4 logging827803
Ref: 958827803
Ref: logging<5>-Footnote-1828933
Ref: logging<5>-Footnote-2828975
Ref: logging<5>-Footnote-3829018
Node: marshal829061
Ref: whatsnew/3 4 marshal829158
Ref: 95e829158
Ref: whatsnew/3 4 whatsnew-marshal-3829158
Ref: 8c6829158
Ref: marshal-Footnote-1829833
Ref: marshal-Footnote-2829876
Node: mmap<2>829919
Ref: whatsnew/3 4 mmap830024
Ref: 95f830024
Ref: mmap<2>-Footnote-1830187
Node: multiprocessing<6>830229
Ref: whatsnew/3 4 multiprocessing830338
Ref: 960830338
Ref: whatsnew/3 4 whatsnew-multiprocessing-no-fork830389
Ref: 8d0830389
Ref: multiprocessing<6>-Footnote-1832201
Ref: multiprocessing<6>-Footnote-2832243
Ref: multiprocessing<6>-Footnote-3832286
Ref: multiprocessing<6>-Footnote-4832328
Node: operator<2>832371
Ref: whatsnew/3 4 operator832478
Ref: 967832478
Ref: operator<2>-Footnote-1833029
Ref: operator<2>-Footnote-2833078
Ref: operator<2>-Footnote-3833121
Node: os<7>833164
Ref: whatsnew/3 4 os833259
Ref: 969833259
Ref: os<7>-Footnote-1834704
Ref: os<7>-Footnote-2834747
Ref: os<7>-Footnote-3834790
Ref: os<7>-Footnote-4834832
Node: pdb<4>834875
Ref: whatsnew/3 4 pdb834968
Ref: 970834968
Ref: pdb<4>-Footnote-1835962
Ref: pdb<4>-Footnote-2836005
Node: pickle<4>836048
Ref: whatsnew/3 4 pickle836147
Ref: 973836147
Ref: whatsnew/3 4 whatsnew-protocol-4836147
Ref: 8cf836147
Ref: pickle<4>-Footnote-1836732
Node: plistlib<2>836781
Ref: whatsnew/3 4 plistlib836883
Ref: 975836883
Ref: plistlib<2>-Footnote-1837417
Node: poplib<3>837460
Ref: whatsnew/3 4 poplib837562
Ref: 978837562
Ref: poplib<3>-Footnote-1837950
Node: pprint<3>837992
Ref: whatsnew/3 4 pprint838086
Ref: 97b838086
Ref: pprint<3>-Footnote-1838704
Ref: pprint<3>-Footnote-2838747
Node: pty838790
Ref: whatsnew/3 4 pty838883
Ref: 97e838883
Node: pydoc<4>839074
Ref: whatsnew/3 4 pydoc839163
Ref: 980839163
Ref: pydoc<4>-Footnote-1840218
Ref: pydoc<4>-Footnote-2840261
Node: re<5>840304
Ref: whatsnew/3 4 re840398
Ref: 981840398
Ref: re<5>-Footnote-1841139
Ref: re<5>-Footnote-2841182
Ref: re<5>-Footnote-3841225
Node: resource841268
Ref: whatsnew/3 4 resource841360
Ref: 985841360
Ref: resource-Footnote-1842211
Ref: resource-Footnote-2842254
Ref: resource-Footnote-3842297
Node: select842340
Ref: whatsnew/3 4 select842433
Ref: 98f842433
Ref: select-Footnote-1842940
Ref: select-Footnote-2842983
Node: shelve843026
Ref: whatsnew/3 4 shelve843120
Ref: 996843120
Ref: shelve-Footnote-1843390
Node: shutil<3>843433
Ref: whatsnew/3 4 shutil843529
Ref: 998843529
Ref: shutil<3>-Footnote-1843900
Node: smtpd<2>843945
Ref: whatsnew/3 4 smtpd844045
Ref: 99b844045
Ref: smtpd<2>-Footnote-1844421
Node: smtplib<3>844464
Ref: whatsnew/3 4 smtplib844564
Ref: 99d844564
Ref: smtplib<3>-Footnote-1844924
Node: socket<7>844966
Ref: whatsnew/3 4 socket845068
Ref: 99f845068
Ref: socket<7>-Footnote-1845845
Ref: socket<7>-Footnote-2845888
Node: sqlite3<4>845930
Ref: whatsnew/3 4 sqlite3846028
Ref: 9a3846028
Ref: sqlite3<4>-Footnote-1846317
Ref: sqlite3<4>-Footnote-2846357
Node: ssl<7>846400
Ref: whatsnew/3 4 ssl846493
Ref: 9a4846493
Ref: whatsnew/3 4 whatsnew-tls-11-12846520
Ref: 8d4846520
Ref: whatsnew/3 4 whatsnew34-sslcontext846790
Ref: 8d7846790
Ref: whatsnew/3 4 whatsnew34-win-cert-store849460
Ref: 8d5849460
Ref: whatsnew/3 4 whatsnew34-sni849714
Ref: 8d6849714
Ref: ssl<7>-Footnote-1850163
Ref: ssl<7>-Footnote-2850206
Ref: ssl<7>-Footnote-3850249
Ref: ssl<7>-Footnote-4850292
Ref: ssl<7>-Footnote-5850335
Ref: ssl<7>-Footnote-6850378
Ref: ssl<7>-Footnote-7850420
Ref: ssl<7>-Footnote-8850463
Ref: ssl<7>-Footnote-9850506
Ref: ssl<7>-Footnote-10850548
Node: stat850592
Ref: whatsnew/3 4 stat850684
Ref: 9b8850684
Ref: stat-Footnote-1851155
Ref: stat-Footnote-2851198
Node: struct<2>851241
Ref: whatsnew/3 4 struct851340
Ref: 9bd851340
Ref: struct<2>-Footnote-1851670
Node: subprocess<4>851713
Ref: whatsnew/3 4 subprocess851816
Ref: 9c0851816
Ref: subprocess<4>-Footnote-1852260
Ref: subprocess<4>-Footnote-2852303
Node: sunau<2>852346
Ref: whatsnew/3 4 sunau852446
Ref: 9c3852446
Ref: sunau<2>-Footnote-1853251
Ref: sunau<2>-Footnote-2853294
Ref: sunau<2>-Footnote-3853337
Ref: sunau<2>-Footnote-4853380
Node: sys<7>853422
Ref: whatsnew/3 4 sys853519
Ref: 9c7853519
Ref: sys<7>-Footnote-1854797
Ref: sys<7>-Footnote-2854840
Node: tarfile<3>854882
Ref: whatsnew/3 4 tarfile854979
Ref: 9cd854979
Ref: tarfile<3>-Footnote-1855289
Node: textwrap855332
Ref: whatsnew/3 4 textwrap855435
Ref: 9cf855435
Ref: textwrap-Footnote-1856134
Ref: textwrap-Footnote-2856177
Node: threading<4>856220
Ref: whatsnew/3 4 threading856325
Ref: 9d4856325
Ref: threading<4>-Footnote-1856668
Node: traceback<3>856711
Ref: whatsnew/3 4 traceback856816
Ref: 9d6856816
Ref: traceback<3>-Footnote-1857129
Node: types<3>857174
Ref: whatsnew/3 4 types857276
Ref: 9d8857276
Ref: types<3>-Footnote-1857780
Node: urllib<2>857823
Ref: whatsnew/3 4 urllib857924
Ref: 9da857924
Ref: urllib<2>-Footnote-1859238
Ref: urllib<2>-Footnote-2859281
Ref: urllib<2>-Footnote-3859324
Ref: urllib<2>-Footnote-4859367
Ref: urllib<2>-Footnote-5859410
Ref: urllib<2>-Footnote-6859453
Node: unittest<4>859496
Ref: whatsnew/3 4 unittest859596
Ref: 9e4859596
Ref: unittest<4>-Footnote-1862746
Ref: unittest<4>-Footnote-2862789
Ref: unittest<4>-Footnote-3862832
Ref: unittest<4>-Footnote-4862875
Ref: unittest<4>-Footnote-5862918
Ref: unittest<4>-Footnote-6862961
Ref: unittest<4>-Footnote-7863004
Ref: unittest<4>-Footnote-8863047
Ref: unittest<4>-Footnote-9863090
Node: venv<5>863133
Ref: whatsnew/3 4 venv863231
Ref: 9ed863231
Ref: venv<5>-Footnote-1863787
Ref: venv<5>-Footnote-2863830
Ref: venv<5>-Footnote-3863873
Node: wave<2>863922
Ref: whatsnew/3 4 wave864019
Ref: 9f0864019
Ref: wave<2>-Footnote-1864654
Ref: wave<2>-Footnote-2864697
Ref: wave<2>-Footnote-3864740
Ref: wave<2>-Footnote-4864782
Node: weakref<2>864824
Ref: whatsnew/3 4 weakref864926
Ref: 9f4864926
Ref: weakref<2>-Footnote-1865545
Ref: weakref<2>-Footnote-2865588
Ref: weakref<2>-Footnote-3865631
Node: xml etree<2>865674
Ref: whatsnew/3 4 xml-etree865779
Ref: 9f8865779
Ref: xml etree<2>-Footnote-1866517
Ref: xml etree<2>-Footnote-2866560
Node: zipfile<4>866603
Ref: whatsnew/3 4 zipfile866689
Ref: 9fe866689
Ref: zipfile<4>-Footnote-1867218
Ref: zipfile<4>-Footnote-2867261
Node: CPython Implementation Changes867304
Ref: whatsnew/3 4 cpython-implementation-changes867445
Ref: a01867445
Node: PEP 445 Customization of CPython Memory Allocators867963
Ref: whatsnew/3 4 pep-445-customization-of-cpython-memory-allocators868121
Ref: a02868121
Ref: whatsnew/3 4 whatsnew-pep-445868121
Ref: 8da868121
Ref: PEP 445 Customization of CPython Memory Allocators-Footnote-1868510
Ref: PEP 445 Customization of CPython Memory Allocators-Footnote-2868559
Node: PEP 442 Safe Object Finalization868608
Ref: whatsnew/3 4 pep-442-safe-object-finalization868824
Ref: a03868824
Ref: whatsnew/3 4 whatsnew-pep-442868824
Ref: 8d9868824
Ref: PEP 442 Safe Object Finalization-Footnote-1869682
Ref: PEP 442 Safe Object Finalization-Footnote-2869731
Node: PEP 456 Secure and Interchangeable Hash Algorithm869780
Ref: whatsnew/3 4 pep-456-secure-and-interchangeable-hash-algorithm869969
Ref: a05869969
Ref: whatsnew/3 4 whatsnew-pep-456869969
Ref: 8d2869969
Ref: PEP 456 Secure and Interchangeable Hash Algorithm-Footnote-1870915
Ref: PEP 456 Secure and Interchangeable Hash Algorithm-Footnote-2870964
Node: PEP 436 Argument Clinic871007
Ref: whatsnew/3 4 pep-436-argument-clinic871193
Ref: a07871193
Ref: whatsnew/3 4 whatsnew-pep-436871193
Ref: 8db871193
Ref: PEP 436 Argument Clinic-Footnote-1872288
Ref: PEP 436 Argument Clinic-Footnote-2872337
Node: Other Build and C API Changes872386
Ref: whatsnew/3 4 other-build-and-c-api-changes872538
Ref: a08872538
Ref: Other Build and C API Changes-Footnote-1874622
Ref: Other Build and C API Changes-Footnote-2874665
Ref: Other Build and C API Changes-Footnote-3874708
Ref: Other Build and C API Changes-Footnote-4874753
Ref: Other Build and C API Changes-Footnote-5874795
Ref: Other Build and C API Changes-Footnote-6874838
Ref: Other Build and C API Changes-Footnote-7874911
Ref: Other Build and C API Changes-Footnote-8874975
Ref: Other Build and C API Changes-Footnote-9875018
Node: 其他改进<2>875061
Ref: whatsnew/3 4 other-improvements875215
Ref: a0e875215
Ref: whatsnew/3 4 other-improvements-3-4875215
Ref: a0f875215
Ref: whatsnew/3 4 whatsnew-isolated-mode875254
Ref: 8c3875254
Ref: 其他改进<2>-Footnote-1879375
Ref: 其他改进<2>-Footnote-2879418
Ref: 其他改进<2>-Footnote-3879460
Ref: 其他改进<2>-Footnote-4879503
Ref: 其他改进<2>-Footnote-5879546
Ref: 其他改进<2>-Footnote-6879589
Ref: 其他改进<2>-Footnote-7879632
Ref: 其他改进<2>-Footnote-8879727
Ref: 其他改进<2>-Footnote-9879780
Ref: 其他改进<2>-Footnote-10879823
Ref: 其他改进<2>-Footnote-11879867
Ref: 其他改进<2>-Footnote-12879911
Ref: 其他改进<2>-Footnote-13879961
Ref: 其他改进<2>-Footnote-14880005
Ref: 其他改进<2>-Footnote-15880049
Ref: 其他改进<2>-Footnote-16880093
Ref: 其他改进<2>-Footnote-17880137
Ref: 其他改进<2>-Footnote-18880187
Ref: 其他改进<2>-Footnote-19880231
Ref: 其他改进<2>-Footnote-20880275
Ref: 其他改进<2>-Footnote-21880319
Node: Significant Optimizations880363
Ref: whatsnew/3 4 significant-optimizations880479
Ref: a15880479
Ref: Significant Optimizations-Footnote-1883282
Ref: Significant Optimizations-Footnote-2883325
Ref: Significant Optimizations-Footnote-3883368
Ref: Significant Optimizations-Footnote-4883411
Ref: Significant Optimizations-Footnote-5883454
Ref: Significant Optimizations-Footnote-6883497
Ref: Significant Optimizations-Footnote-7883540
Ref: Significant Optimizations-Footnote-8883582
Ref: Significant Optimizations-Footnote-9883625
Ref: Significant Optimizations-Footnote-10883668
Ref: Significant Optimizations-Footnote-11883712
Ref: Significant Optimizations-Footnote-12883756
Ref: Significant Optimizations-Footnote-13883800
Node: 弃用<5>883844
Ref: whatsnew/3 4 deprecated883976
Ref: a19883976
Ref: whatsnew/3 4 deprecated-3-4883976
Ref: 8f4883976
Node: Deprecations in the Python API884406
Ref: whatsnew/3 4 deprecations-in-the-python-api884510
Ref: a1a884510
Node: Deprecated Features888240
Ref: whatsnew/3 4 deprecated-features888344
Ref: a2a888344
Ref: Deprecated Features-Footnote-1888723
Ref: Deprecated Features-Footnote-2888766
Node: 移除<5>888809
Ref: whatsnew/3 4 removed888931
Ref: a2c888931
Node: 不再支持的操作系统889069
Ref: whatsnew/3 4 operating-systems-no-longer-supported889176
Ref: a2d889176
Ref: 不再支持的操作系统-Footnote-1889553
Ref: 不再支持的操作系统-Footnote-2889596
Ref: 不再支持的操作系统-Footnote-3889639
Node: API 与特性的移除<5>889682
Ref: whatsnew/3 4 api-and-feature-removals889811
Ref: a2e889811
Ref: API 与特性的移除<5>-Footnote-1892247
Ref: API 与特性的移除<5>-Footnote-2892283
Ref: API 与特性的移除<5>-Footnote-3892326
Ref: API 与特性的移除<5>-Footnote-4892369
Ref: API 与特性的移除<5>-Footnote-5892412
Ref: API 与特性的移除<5>-Footnote-6892455
Ref: API 与特性的移除<5>-Footnote-7892497
Node: Code Cleanups892540
Ref: whatsnew/3 4 code-cleanups892633
Ref: a31892633
Ref: Code Cleanups-Footnote-1893296
Node: 移植到 Python 3 4893339
Ref: whatsnew/3 4 porting-to-python-3-4893467
Ref: a32893467
Node: 'python' 命令行为的变化<2>893780
Ref: whatsnew/3 4 changes-in-python-command-behavior893902
Ref: a33893902
Ref: 'python' 命令行为的变化<2>-Footnote-1894988
Node: Python API 的变化<2>895031
Ref: whatsnew/3 4 changes-in-the-python-api895180
Ref: a35895180
Ref: Python API 的变化<2>-Footnote-1908549
Ref: Python API 的变化<2>-Footnote-2908592
Ref: Python API 的变化<2>-Footnote-3908635
Ref: Python API 的变化<2>-Footnote-4908678
Ref: Python API 的变化<2>-Footnote-5908721
Ref: Python API 的变化<2>-Footnote-6908764
Ref: Python API 的变化<2>-Footnote-7908807
Ref: Python API 的变化<2>-Footnote-8908850
Ref: Python API 的变化<2>-Footnote-9908892
Ref: Python API 的变化<2>-Footnote-10908935
Ref: Python API 的变化<2>-Footnote-11908979
Ref: Python API 的变化<2>-Footnote-12909023
Ref: Python API 的变化<2>-Footnote-13909067
Ref: Python API 的变化<2>-Footnote-14909111
Ref: Python API 的变化<2>-Footnote-15909155
Ref: Python API 的变化<2>-Footnote-16909199
Ref: Python API 的变化<2>-Footnote-17909243
Ref: Python API 的变化<2>-Footnote-18909287
Ref: Python API 的变化<2>-Footnote-19909331
Ref: Python API 的变化<2>-Footnote-20909375
Ref: Python API 的变化<2>-Footnote-21909419
Ref: Python API 的变化<2>-Footnote-22909463
Ref: Python API 的变化<2>-Footnote-23909507
Ref: Python API 的变化<2>-Footnote-24909550
Node: C API 的变化<2>909594
Ref: whatsnew/3 4 changes-in-the-c-api909701
Ref: a47909701
Ref: C API 的变化<2>-Footnote-1911448
Ref: C API 的变化<2>-Footnote-2911491
Node: 3 4 3 的变化911534
Ref: whatsnew/3 4 changed-in-3-4-3911644
Ref: a53911644
Node: PEP 476 Enabling certificate verification by default for stdlib http clients911855
Ref: whatsnew/3 4 pep-476911983
Ref: a54911983
Ref: whatsnew/3 4 pep-476-enabling-certificate-verification-by-default-for-stdlib-http-clients911983
Ref: a55911983
Node: Python 3 3 有什么新变化912982
Ref: whatsnew/3 3 doc913152
Ref: a56913152
Ref: whatsnew/3 3 what-s-new-in-python-3-3913152
Ref: a57913152
Ref: Python 3 3 有什么新变化-Footnote-1914902
Ref: Python 3 3 有什么新变化-Footnote-2914962
Node: 摘要 - 发布重点<7>915011
Ref: whatsnew/3 3 summary-release-highlights915130
Ref: a58915130
Node: PEP 405 虚拟环境916391
Ref: whatsnew/3 3 pep-405916548
Ref: a5a916548
Ref: whatsnew/3 3 pep-405-virtual-environments916548
Ref: a62916548
Ref: PEP 405 虚拟环境-Footnote-1917498
Node: PEP 420 隐式命名空间包917547
Ref: whatsnew/3 3 pep-420-implicit-namespace-packages917734
Ref: a63917734
Ref: PEP 420 隐式命名空间包-Footnote-1918208
Ref: PEP 420 隐式命名空间包-Footnote-2918257
Node: PEP 3118 新的内存视图实现和缓冲协议文档918306
Ref: whatsnew/3 3 pep-3118-new-memoryview-implementation-and-buffer-protocol-documentation918505
Ref: a64918505
Ref: whatsnew/3 3 pep-3118-update918505
Ref: a65918505
Ref: PEP 3118 新的内存视图实现和缓冲协议文档-Footnote-1919588
Node: 相关特性919637
Ref: whatsnew/3 3 features919760
Ref: a66919760
Ref: 相关特性-Footnote-1920564
Node: API changes920607
Ref: whatsnew/3 3 api-changes920730
Ref: a67920730
Ref: API changes-Footnote-1921743
Ref: API changes-Footnote-2921786
Node: PEP 393 灵活的字符串表示921835
Ref: whatsnew/3 3 pep-393922047
Ref: a5d922047
Ref: whatsnew/3 3 pep-393-flexible-string-representation922047
Ref: a6a922047
Ref: PEP 393 灵活的字符串表示-Footnote-1923086
Node: Functionality923135
Ref: whatsnew/3 3 functionality923256
Ref: a6b923256
Ref: Functionality-Footnote-1924703
Ref: Functionality-Footnote-2924752
Node: Performance and resource usage924795
Ref: whatsnew/3 3 performance-and-resource-usage924916
Ref: a6d924916
Ref: Performance and resource usage-Footnote-1926136
Node: PEP 397 适用于Windows的Python启动器926185
Ref: whatsnew/3 3 pep-397926390
Ref: a6e926390
Ref: whatsnew/3 3 pep-397-python-launcher-for-windows926390
Ref: a6f926390
Ref: PEP 397 适用于Windows的Python启动器-Footnote-1927936
Ref: PEP 397 适用于Windows的Python启动器-Footnote-2927978
Node: PEP 3151 重写 OS 和 IO 异常的层次结构928027
Ref: whatsnew/3 3 pep-3151928238
Ref: a5b928238
Ref: whatsnew/3 3 pep-3151-reworking-the-os-and-io-exception-hierarchy928238
Ref: a72928238
Ref: PEP 3151 重写 OS 和 IO 异常的层次结构-Footnote-1930774
Node: PEP 380 委托给子生成器的语法930823
Ref: whatsnew/3 3 pep-380931021
Ref: a59931021
Ref: whatsnew/3 3 pep-380-syntax-for-delegating-to-a-subgenerator931021
Ref: a82931021
Ref: PEP 380 委托给子生成器的语法-Footnote-1933417
Node: PEP 409 清除异常上下文933466
Ref: whatsnew/3 3 pep-409-suppressing-exception-context933647
Ref: a84933647
Ref: PEP 409 清除异常上下文-Footnote-1935698
Node: PEP 414 显式的Unicode文本935747
Ref: whatsnew/3 3 pep-414-explicit-unicode-literals935926
Ref: a85935926
Ref: PEP 414 显式的Unicode文本-Footnote-1936619
Node: PEP 3155 类和函数的限定名称936668
Ref: whatsnew/3 3 pep-3155-qualified-name-for-classes-and-functions936848
Ref: a86936848
Ref: PEP 3155 类和函数的限定名称-Footnote-1938379
Node: PEP 412 Key-Sharing Dictionary938428
Ref: whatsnew/3 3 pep-412938604
Ref: a5e938604
Ref: whatsnew/3 3 pep-412-key-sharing-dictionary938604
Ref: a87938604
Ref: PEP 412 Key-Sharing Dictionary-Footnote-1939117
Node: PEP 362 函数签名对象939166
Ref: whatsnew/3 3 pep-362-function-signature-object939339
Ref: a88939339
Ref: PEP 362 函数签名对象-Footnote-1940205
Node: PEP 421 添加 sys implementation940254
Ref: whatsnew/3 3 pep-421-adding-sys-implementation940444
Ref: a8a940444
Ref: PEP 421 添加 sys implementation-Footnote-1941656
Node: SimpleNamespace941705
Ref: whatsnew/3 3 simplenamespace941790
Ref: a8c941790
Ref: SimpleNamespace-Footnote-1942399
Node: Using importlib as the Implementation of Import942448
Ref: whatsnew/3 3 importlib942639
Ref: a5c942639
Ref: whatsnew/3 3 using-importlib-as-the-implementation-of-import942639
Ref: a8d942639
Ref: Using importlib as the Implementation of Import-Footnote-1943916
Ref: Using importlib as the Implementation of Import-Footnote-2943958
Ref: Using importlib as the Implementation of Import-Footnote-3944001
Ref: Using importlib as the Implementation of Import-Footnote-4944044
Ref: Using importlib as the Implementation of Import-Footnote-5944087
Node: New APIs944136
Ref: whatsnew/3 3 new-apis944252
Ref: a90944252
Node: Visible Changes946094
Ref: whatsnew/3 3 visible-changes946210
Ref: a9a946210
Ref: Visible Changes-Footnote-1948064
Ref: Visible Changes-Footnote-2948113
Node: 其他语言特性修改<7>948162
Ref: whatsnew/3 3 other-language-changes948347
Ref: a9c948347
Ref: 其他语言特性修改<7>-Footnote-1950314
Ref: 其他语言特性修改<7>-Footnote-2950357
Ref: 其他语言特性修改<7>-Footnote-3950400
Ref: 其他语言特性修改<7>-Footnote-4950443
Ref: 其他语言特性修改<7>-Footnote-5950486
Ref: 其他语言特性修改<7>-Footnote-6950529
Ref: 其他语言特性修改<7>-Footnote-7950572
Ref: 其他语言特性修改<7>-Footnote-8950615
Node: A Finer-Grained Import Lock950658
Ref: whatsnew/3 3 a-finer-grained-import-lock950823
Ref: a9f950823
Ref: A Finer-Grained Import Lock-Footnote-1951572
Node: Builtin functions and types951614
Ref: whatsnew/3 3 builtin-functions-and-types951767
Ref: aa1951767
Ref: Builtin functions and types-Footnote-1953000
Node: 新增模块<7>953042
Ref: whatsnew/3 3 new-modules953186
Ref: aa5953186
Node: faulthandler<3>953310
Ref: whatsnew/3 3 faulthandler953398
Ref: aa6953398
Node: ipaddress<5>954323
Ref: whatsnew/3 3 ipaddress954427
Ref: aa8954427
Ref: ipaddress<5>-Footnote-1954777
Node: lzma<2>954819
Ref: whatsnew/3 3 lzma954899
Ref: aa9954899
Ref: lzma<2>-Footnote-1955217
Node: 改进的模块<7>955259
Ref: whatsnew/3 3 improved-modules955391
Ref: aaa955391
Node: abc<2>956675
Ref: whatsnew/3 3 abc956753
Ref: aab956753
Ref: abc<2>-Footnote-1957793
Ref: abc<2>-Footnote-2957836
Node: array<2>957879
Ref: whatsnew/3 3 array957975
Ref: ab1957975
Ref: array<2>-Footnote-1958219
Node: base64<2>958264
Ref: whatsnew/3 3 base64958365
Ref: ab2958365
Ref: base64<2>-Footnote-1958663
Node: binascii<3>958706
Ref: whatsnew/3 3 binascii958805
Ref: ab3958805
Ref: binascii<3>-Footnote-1959059
Node: bz2<2>959102
Ref: whatsnew/3 3 bz2959201
Ref: ab4959201
Ref: bz2<2>-Footnote-1960184
Ref: bz2<2>-Footnote-2960226
Node: 编码器960268
Ref: whatsnew/3 3 codecs960370
Ref: ab7960370
Ref: 编码器-Footnote-1961693
Ref: 编码器-Footnote-2961736
Ref: 编码器-Footnote-3961779
Node: collections<7>961822
Ref: whatsnew/3 3 collections961931
Ref: ab8961931
Ref: collections<7>-Footnote-1962696
Ref: collections<7>-Footnote-2962739
Ref: collections<7>-Footnote-3962782
Ref: collections<7>-Footnote-4962825
Node: contextlib<5>962868
Ref: whatsnew/3 3 contextlib962976
Ref: aba962976
Ref: contextlib<5>-Footnote-1963570
Node: crypt<2>963613
Ref: whatsnew/3 3 crypt963716
Ref: abb963716
Ref: crypt<2>-Footnote-1963929
Node: curses<4>963972
Ref: whatsnew/3 3 curses964073
Ref: curses<4>-Footnote-1964937
Node: datetime<5>964979
Ref: whatsnew/3 3 datetime965082
Ref: ac0965082
Ref: datetime<5>-Footnote-1965800
Node: decimal<3>965843
Ref: whatsnew/3 3 decimal965945
Ref: ac2965945
Ref: whatsnew/3 3 new-decimal965945
Ref: a5f965945
Ref: decimal<3>-Footnote-1967667
Node: 相关特性<2>967709
Ref: whatsnew/3 3 id1967794
Ref: ac3967794
Node: API changes<2>968170
Ref: whatsnew/3 3 id2968255
Ref: ac6968255
Node: email<4>971018
Ref: whatsnew/3 3 email971118
Ref: ad1971118
Ref: whatsnew/3 3 new-email971118
Ref: a60971118
Node: Policy Framework971247
Ref: whatsnew/3 3 policy-framework971355
Ref: ad2971355
Node: Provisional Policy with New Header API974363
Ref: whatsnew/3 3 provisional-policy-with-new-header-api974497
Ref: ad6974497
Node: Other API Changes979133
Ref: whatsnew/3 3 other-api-changes979242
Ref: ada979242
Node: ftplib<2>980133
Ref: whatsnew/3 3 ftplib980235
Ref: ae1980235
Ref: ftplib<2>-Footnote-1981142
Ref: ftplib<2>-Footnote-2981184
Ref: ftplib<2>-Footnote-3981227
Node: functools<5>981270
Ref: whatsnew/3 3 functools981369
Ref: ae6981369
Ref: functools<5>-Footnote-1981715
Node: gc<5>981758
Ref: whatsnew/3 3 gc981855
Ref: ae7981855
Node: hmac<3>982027
Ref: whatsnew/3 3 hmac982119
Ref: ae9982119
Ref: hmac<3>-Footnote-1982383
Node: http<4>982426
Ref: whatsnew/3 3 http982520
Ref: aeb982520
Ref: http<4>-Footnote-1983198
Ref: http<4>-Footnote-2983240
Ref: http<4>-Footnote-3983283
Node: html<2>983326
Ref: whatsnew/3 3 html983423
Ref: af2983423
Ref: html<2>-Footnote-1984421
Ref: html<2>-Footnote-2984464
Ref: html<2>-Footnote-3984507
Ref: html<2>-Footnote-4984550
Ref: html<2>-Footnote-5984593
Ref: html<2>-Footnote-6984636
Ref: html<2>-Footnote-7984681
Ref: html<2>-Footnote-8984725
Ref: html<2>-Footnote-9984768
Ref: html<2>-Footnote-10984811
Ref: html<2>-Footnote-11984857
Ref: html<2>-Footnote-12984902
Ref: html<2>-Footnote-13984946
Ref: html<2>-Footnote-14984990
Ref: html<2>-Footnote-15985033
Ref: html<2>-Footnote-16985077
Node: imaplib<3>985121
Ref: whatsnew/3 3 imaplib985221
Ref: af4985221
Ref: imaplib<3>-Footnote-1985467
Node: inspect<6>985509
Ref: whatsnew/3 3 inspect985607
Ref: af5985607
Ref: inspect<6>-Footnote-1986329
Ref: inspect<6>-Footnote-2986372
Node: io<4>986415
Ref: whatsnew/3 3 io986515
Ref: af8986515
Ref: io<4>-Footnote-1987168
Node: itertools<3>987211
Ref: whatsnew/3 3 itertools987311
Ref: af9987311
Node: logging<6>987467
Ref: whatsnew/3 3 logging987569
Ref: afa987569
Node: math<6>988020
Ref: whatsnew/3 3 math988117
Ref: afc988117
Ref: math<6>-Footnote-1988340
Node: mmap<3>988383
Ref: whatsnew/3 3 mmap988488
Ref: afe988488
Ref: mmap<3>-Footnote-1988823
Node: multiprocessing<7>988866
Ref: whatsnew/3 3 multiprocessing988974
Ref: b00988974
Ref: multiprocessing<7>-Footnote-1990124
Ref: multiprocessing<7>-Footnote-2990167
Ref: multiprocessing<7>-Footnote-3990209
Ref: multiprocessing<7>-Footnote-4990251
Node: nntplib<2>990294
Ref: whatsnew/3 3 nntplib990400
Ref: b08990400
Ref: nntplib<2>-Footnote-1990969
Node: os<8>991011
Ref: whatsnew/3 3 os991105
Ref: b09991105
Ref: os<8>-Footnote-1998475
Ref: os<8>-Footnote-2998518
Ref: os<8>-Footnote-3998560
Ref: os<8>-Footnote-4998603
Ref: os<8>-Footnote-5998646
Ref: os<8>-Footnote-6998689
Ref: os<8>-Footnote-7998731
Ref: os<8>-Footnote-8998774
Ref: os<8>-Footnote-9998817
Ref: os<8>-Footnote-10998860
Ref: os<8>-Footnote-11998903
Node: pdb<5>998947
Ref: whatsnew/3 3 pdb999040
Ref: b42999040
Ref: pdb<5>-Footnote-1999325
Node: pickle<5>999368
Ref: whatsnew/3 3 pickle999464
Ref: b43999464
Ref: pickle<5>-Footnote-1999738
Node: pydoc<5>999781
Ref: whatsnew/3 3 pydoc999876
Ref: b45999876
Node: re<6>1000073
Ref: whatsnew/3 3 re1000164
Ref: b461000164
Ref: re<6>-Footnote-11000364
Node: sched1000406
Ref: whatsnew/3 3 sched1000498
Ref: b471000498
Ref: sched-Footnote-11001630
Ref: sched-Footnote-21001673
Ref: sched-Footnote-31001715
Ref: sched-Footnote-41001758
Ref: sched-Footnote-51001801
Node: select<2>1001844
Ref: whatsnew/3 3 select1001939
Ref: b4c1001939
Ref: select<2>-Footnote-11002202
Node: shlex<3>1002244
Ref: whatsnew/3 3 shlex1002343
Ref: b4d1002343
Node: shutil<4>1002654
Ref: whatsnew/3 3 shutil1002753
Ref: b4f1002753
Ref: shutil<4>-Footnote-11004620
Ref: shutil<4>-Footnote-21004663
Ref: shutil<4>-Footnote-31004706
Ref: shutil<4>-Footnote-41004749
Ref: shutil<4>-Footnote-51004792
Ref: shutil<4>-Footnote-61004835
Ref: shutil<4>-Footnote-71004878
Ref: shutil<4>-Footnote-81004920
Node: signal<4>1004962
Ref: whatsnew/3 3 signal1005061
Ref: b531005061
Ref: signal<4>-Footnote-11006126
Node: smtpd<3>1006168
Ref: whatsnew/3 3 smtpd1006268
Ref: b5a1006268
Ref: smtpd<3>-Footnote-11006754
Ref: smtpd<3>-Footnote-21006803
Ref: smtpd<3>-Footnote-31006852
Node: smtplib<4>1006894
Ref: whatsnew/3 3 smtplib1006994
Ref: b5b1006994
Ref: smtplib<4>-Footnote-11007745
Ref: smtplib<4>-Footnote-21007788
Ref: smtplib<4>-Footnote-31007831
Node: socket<8>1007873
Ref: whatsnew/3 3 socket1007980
Ref: b5d1007980
Ref: socket<8>-Footnote-11009222
Ref: socket<8>-Footnote-21009264
Ref: socket<8>-Footnote-31009307
Ref: socket<8>-Footnote-41009350
Node: socketserver<3>1009393
Ref: whatsnew/3 3 socketserver1009500
Ref: b601009500
Ref: socketserver<3>-Footnote-11009873
Node: sqlite3<5>1009916
Ref: whatsnew/3 3 sqlite31010020
Ref: b641010020
Ref: sqlite3<5>-Footnote-11010295
Node: ssl<8>1010338
Ref: whatsnew/3 3 ssl1010434
Ref: b661010434
Ref: ssl<8>-Footnote-11012657
Ref: ssl<8>-Footnote-21012700
Ref: ssl<8>-Footnote-31012743
Ref: ssl<8>-Footnote-41012786
Ref: ssl<8>-Footnote-51012829
Ref: ssl<8>-Footnote-61012872
Ref: ssl<8>-Footnote-71012915
Ref: ssl<8>-Footnote-81012958
Ref: ssl<8>-Footnote-91013001
Ref: ssl<8>-Footnote-101013044
Ref: ssl<8>-Footnote-111013088
Node: stat<2>1013132
Ref: whatsnew/3 3 stat1013227
Ref: b741013227
Ref: stat<2>-Footnote-11013528
Node: struct<3>1013571
Ref: whatsnew/3 3 struct1013673
Ref: b761013673
Ref: struct<3>-Footnote-11013920
Node: subprocess<5>1013962
Ref: whatsnew/3 3 subprocess1014063
Ref: b771014063
Ref: subprocess<5>-Footnote-11014398
Ref: subprocess<5>-Footnote-21014440
Node: sys<8>1014482
Ref: whatsnew/3 3 sys1014584
Ref: b791014584
Ref: sys<8>-Footnote-11014802
Node: tarfile<4>1014845
Ref: whatsnew/3 3 tarfile1014942
Ref: b7c1014942
Ref: tarfile<4>-Footnote-11015150
Node: tempfile1015192
Ref: whatsnew/3 3 tempfile1015294
Ref: b7d1015294
Ref: tempfile-Footnote-11015521
Node: textwrap<2>1015563
Ref: whatsnew/3 3 textwrap1015667
Ref: b7f1015667
Ref: textwrap<2>-Footnote-11015912
Node: threading<5>1015955
Ref: whatsnew/3 3 threading1016058
Ref: b811016058
Ref: threading<5>-Footnote-11016989
Ref: threading<5>-Footnote-21017032
Node: time<6>1017074
Ref: whatsnew/3 3 time1017174
Ref: b881017174
Ref: time<6>-Footnote-11018141
Ref: time<6>-Footnote-21018190
Node: types<4>1018233
Ref: whatsnew/3 3 types1018332
Ref: b8d1018332
Ref: types<4>-Footnote-11018668
Ref: types<4>-Footnote-21018711
Ref: types<4>-Footnote-31018760
Node: unittest<5>1018803
Ref: whatsnew/3 3 unittest1018904
Ref: b911018904
Ref: unittest<5>-Footnote-11019317
Node: urllib<3>1019360
Ref: whatsnew/3 3 urllib1019463
Ref: b981019463
Ref: urllib<3>-Footnote-11019815
Node: webbrowser1019860
Ref: whatsnew/3 3 webbrowser1019973
Ref: b9a1019973
Ref: webbrowser-Footnote-11020511
Ref: webbrowser-Footnote-21020554
Node: xml etree ElementTree1020597
Ref: whatsnew/3 3 xml-etree-elementtree1020708
Ref: b9b1020708
Node: zlib<2>1021227
Ref: whatsnew/3 3 zlib1021319
Ref: b9c1021319
Ref: zlib<2>-Footnote-11021791
Ref: zlib<2>-Footnote-21021834
Node: 性能优化<6>1021877
Ref: whatsnew/3 3 optimizations1022022
Ref: b9f1022022
Ref: 性能优化<6>-Footnote-11022827
Ref: 性能优化<6>-Footnote-21022876
Ref: 性能优化<6>-Footnote-31022919
Ref: 性能优化<6>-Footnote-41022962
Node: 构建和 C API 的改变<4>1023005
Ref: whatsnew/3 3 build-and-c-api-changes1023141
Ref: a681023141
Ref: 构建和 C API 的改变<4>-Footnote-11025001
Ref: 构建和 C API 的改变<4>-Footnote-21025050
Ref: 构建和 C API 的改变<4>-Footnote-31025099
Node: 弃用<6>1025142
Ref: whatsnew/3 3 deprecated1025283
Ref: bbe1025283
Node: 不支持的操作系统<2>1025571
Ref: whatsnew/3 3 unsupported-operating-systems1025700
Ref: bbf1025700
Node: 已弃用的 Python 模块、函数和方法<4>1026014
Ref: whatsnew/3 3 deprecated-python-modules-functions-and-methods1026189
Ref: bc01026189
Ref: 已弃用的 Python 模块、函数和方法<4>-Footnote-11028494
Ref: 已弃用的 Python 模块、函数和方法<4>-Footnote-21028536
Ref: 已弃用的 Python 模块、函数和方法<4>-Footnote-31028585
Ref: 已弃用的 Python 模块、函数和方法<4>-Footnote-41028628
Ref: 已弃用的 Python 模块、函数和方法<4>-Footnote-51028671
Node: 已弃用的 C API 函数和类型<3>1028714
Ref: whatsnew/3 3 deprecated-functions-and-types-of-the-c-api1028877
Ref: bc41028877
Ref: 已弃用的 C API 函数和类型<3>-Footnote-11032055
Node: 弃用的功能1032104
Ref: whatsnew/3 3 deprecated-features1032211
Ref: be31032211
Node: 移植到 Python 3 31032421
Ref: whatsnew/3 3 porting-to-python-3-31032525
Ref: be41032525
Node: Porting Python code1032780
Ref: whatsnew/3 3 porting-python-code1032879
Ref: a8f1032879
Ref: whatsnew/3 3 portingpythoncode1032879
Ref: be51032879
Ref: Porting Python code-Footnote-11039907
Ref: Porting Python code-Footnote-21039950
Ref: Porting Python code-Footnote-31039993
Ref: Porting Python code-Footnote-41040036
Ref: Porting Python code-Footnote-51040085
Ref: Porting Python code-Footnote-61040134
Ref: Porting Python code-Footnote-71040176
Ref: Porting Python code-Footnote-81040221
Ref: Porting Python code-Footnote-91040264
Ref: Porting Python code-Footnote-101040306
Node: Porting C code1040350
Ref: whatsnew/3 3 porting-c-code1040479
Ref: a691040479
Ref: Porting C code-Footnote-11041971
Node: Building C extensions1042020
Ref: whatsnew/3 3 building-c-extensions1042157
Ref: bf51042157
Ref: Building C extensions-Footnote-11042755
Node: Command Line Switch Changes1042798
Ref: whatsnew/3 3 command-line-switch-changes1042912
Ref: bf61042912
Ref: Command Line Switch Changes-Footnote-11043480
Ref: Command Line Switch Changes-Footnote-21043523
Node: Python 3 2 有什么新变化1043566
Ref: whatsnew/3 2 doc1043736
Ref: bf81043736
Ref: whatsnew/3 2 what-s-new-in-python-3-21043736
Ref: bf91043736
Ref: Python 3 2 有什么新变化-Footnote-11044946
Ref: Python 3 2 有什么新变化-Footnote-21045045
Node: PEP 384 定义稳定的ABI1045094
Ref: whatsnew/3 2 pep-384-defining-a-stable-abi1045233
Ref: bfa1045233
Ref: PEP 384 定义稳定的ABI-Footnote-11046308
Node: PEP 389 Argparse 命令行解析模块1046357
Ref: whatsnew/3 2 pep-389-argparse-command-line-parsing-module1046540
Ref: bfb1046540
Ref: PEP 389 Argparse 命令行解析模块-Footnote-11050640
Node: PEP 391 基于字典的日志配置1050689
Ref: whatsnew/3 2 pep-391-dictionary-based-configuration-for-logging1050880
Ref: bfd1050880
Ref: PEP 391 基于字典的日志配置-Footnote-11053115
Node: PEP 3148 concurrent futures 模块1053164
Ref: whatsnew/3 2 pep-3148-the-concurrent-futures-module1053342
Ref: bff1053342
Ref: PEP 3148 concurrent futures 模块-Footnote-11056011
Node: PEP 3147 PYC 仓库目录1056060
Ref: whatsnew/3 2 pep-3147-pyc-repository-directories1056239
Ref: c031056239
Ref: PEP 3147 PYC 仓库目录-Footnote-11059249
Node: PEP 3149 ABI Version Tagged so Files1059298
Ref: whatsnew/3 2 pep-3149-abi-version-tagged-so-files1059489
Ref: c061059489
Ref: PEP 3149 ABI Version Tagged so Files-Footnote-11060725
Node: PEP 3333 Python Web服务器网关接口v1 0 11060774
Ref: whatsnew/3 2 pep-3333-python-web-server-gateway-interface-v1-0-11060967
Ref: c071060967
Ref: PEP 3333 Python Web服务器网关接口v1 0 1-Footnote-11063305
Ref: PEP 3333 Python Web服务器网关接口v1 0 1-Footnote-21063354
Ref: PEP 3333 Python Web服务器网关接口v1 0 1-Footnote-31063403
Node: 其他语言特性修改<8>1063452
Ref: whatsnew/3 2 other-language-changes1063642
Ref: c0a1063642
Ref: 其他语言特性修改<8>-Footnote-11073165
Ref: 其他语言特性修改<8>-Footnote-21073207
Ref: 其他语言特性修改<8>-Footnote-31073249
Ref: 其他语言特性修改<8>-Footnote-41073294
Ref: 其他语言特性修改<8>-Footnote-51073336
Ref: 其他语言特性修改<8>-Footnote-61073378
Ref: 其他语言特性修改<8>-Footnote-71073420
Ref: 其他语言特性修改<8>-Footnote-81073462
Ref: 其他语言特性修改<8>-Footnote-91073504
Ref: 其他语言特性修改<8>-Footnote-101073546
Ref: 其他语言特性修改<8>-Footnote-111073590
Ref: 其他语言特性修改<8>-Footnote-121073635
Ref: 其他语言特性修改<8>-Footnote-131073678
Ref: 其他语言特性修改<8>-Footnote-141073721
Ref: 其他语言特性修改<8>-Footnote-151073765
Ref: 其他语言特性修改<8>-Footnote-161073809
Node: 新增，改进和弃用的模块1073852
Ref: whatsnew/3 2 new-improved-and-deprecated-modules1074005
Ref: c171074005
Node: email<5>1076012
Ref: whatsnew/3 2 email1076110
Ref: c181076110
Ref: email<5>-Footnote-11078084
Ref: email<5>-Footnote-21078133
Ref: email<5>-Footnote-31078175
Node: elementtree1078218
Ref: whatsnew/3 2 elementtree1078337
Ref: c201078337
Ref: elementtree-Footnote-11079816
Ref: elementtree-Footnote-21079872
Node: functools<6>1079914
Ref: whatsnew/3 2 functools1080037
Ref: c271080037
Ref: functools<6>-Footnote-11083496
Ref: functools<6>-Footnote-21083548
Ref: functools<6>-Footnote-31083600
Ref: functools<6>-Footnote-41083643
Ref: functools<6>-Footnote-51083686
Ref: functools<6>-Footnote-61083728
Ref: functools<6>-Footnote-71083770
Ref: functools<6>-Footnote-81083812
Node: itertools<4>1083864
Ref: whatsnew/3 2 itertools1083990
Ref: c291083990
Node: collections<8>1084680
Ref: whatsnew/3 2 collections1084806
Ref: c2b1084806
Ref: collections<8>-Footnote-11087054
Ref: collections<8>-Footnote-21087114
Node: threading<6>1087161
Ref: whatsnew/3 2 threading1087292
Ref: c301087292
Ref: threading<6>-Footnote-11090053
Ref: threading<6>-Footnote-21090114
Ref: threading<6>-Footnote-31090212
Ref: threading<6>-Footnote-41090284
Node: datetime 和 time1090326
Ref: whatsnew/3 2 datetime-and-time1090450
Ref: c341090450
Ref: datetime 和 time-Footnote-11093237
Ref: datetime 和 time-Footnote-21093282
Ref: datetime 和 time-Footnote-31093324
Ref: datetime 和 time-Footnote-41093366
Ref: datetime 和 time-Footnote-51093408
Ref: datetime 和 time-Footnote-61093453
Ref: datetime 和 time-Footnote-71093495
Node: math<7>1093538
Ref: whatsnew/3 2 math1093656
Ref: c381093656
Ref: math<7>-Footnote-11095532
Node: abc<3>1095585
Ref: whatsnew/3 2 abc1095691
Ref: c3d1095691
Ref: abc<3>-Footnote-11096313
Node: io<5>1096355
Ref: whatsnew/3 2 io1096461
Ref: c3e1096461
Ref: io<5>-Footnote-11097632
Node: reprlib1097674
Ref: whatsnew/3 2 reprlib1097784
Ref: c401097784
Ref: reprlib-Footnote-11098775
Ref: reprlib-Footnote-21098817
Node: logging<7>1098859
Ref: whatsnew/3 2 logging1098970
Ref: c421098970
Node: csv<3>1100809
Ref: whatsnew/3 2 csv1100926
Ref: c491100926
Ref: csv<3>-Footnote-11101787
Ref: csv<3>-Footnote-21101829
Node: contextlib<6>1101874
Ref: whatsnew/3 2 contextlib1102002
Ref: c4d1102002
Ref: contextlib<6>-Footnote-11104221
Node: decimal and fractions1104263
Ref: whatsnew/3 2 decimal-and-fractions1104388
Ref: c501104388
Ref: decimal and fractions-Footnote-11106811
Ref: decimal and fractions-Footnote-21106853
Ref: decimal and fractions-Footnote-31106895
Ref: decimal and fractions-Footnote-41106937
Ref: decimal and fractions-Footnote-51106979
Ref: decimal and fractions-Footnote-61107021
Node: ftp1107063
Ref: whatsnew/3 2 ftp1107180
Ref: c541107180
Ref: ftp-Footnote-11108544
Ref: ftp-Footnote-21108633
Ref: ftp-Footnote-31108675
Node: popen1108717
Ref: whatsnew/3 2 popen1108822
Ref: c551108822
Ref: popen-Footnote-11109134
Ref: popen-Footnote-21109176
Node: select<3>1109219
Ref: whatsnew/3 2 select1109337
Ref: c561109337
Ref: select<3>-Footnote-11109768
Node: gzip 和 zipfile1109810
Ref: whatsnew/3 2 gzip-and-zipfile1109933
Ref: c581109933
Ref: gzip 和 zipfile-Footnote-11111504
Ref: gzip 和 zipfile-Footnote-21111546
Ref: gzip 和 zipfile-Footnote-31111588
Ref: gzip 和 zipfile-Footnote-41111633
Ref: gzip 和 zipfile-Footnote-51111675
Ref: gzip 和 zipfile-Footnote-61111717
Node: tarfile<5>1111759
Ref: whatsnew/3 2 tarfile1111883
Ref: c5c1111883
Ref: tarfile<5>-Footnote-11113454
Node: hashlib<4>1113496
Ref: whatsnew/3 2 hashlib1113610
Ref: c5f1113610
Ref: hashlib<4>-Footnote-11114373
Node: ast<4>1114415
Ref: whatsnew/3 2 ast1114524
Ref: c601114524
Node: os<9>1115462
Ref: whatsnew/3 2 os1115570
Ref: c621115570
Node: shutil<5>1116341
Ref: whatsnew/3 2 shutil1116453
Ref: c661116453
Node: sqlite3<6>1118624
Ref: whatsnew/3 2 sqlite31118738
Ref: c691118738
Ref: sqlite3<6>-Footnote-11119391
Node: html<3>1119433
Ref: whatsnew/3 2 html1119547
Ref: c6c1119547
Node: socket<9>1119833
Ref: whatsnew/3 2 socket1119943
Ref: c6d1119943
Ref: socket<9>-Footnote-11120585
Ref: socket<9>-Footnote-21120627
Node: ssl<9>1120669
Ref: whatsnew/3 2 ssl1120776
Ref: c701120776
Ref: ssl<9>-Footnote-11122875
Ref: ssl<9>-Footnote-21122924
Ref: ssl<9>-Footnote-31123009
Ref: ssl<9>-Footnote-41123051
Ref: ssl<9>-Footnote-51123093
Ref: ssl<9>-Footnote-61123135
Ref: ssl<9>-Footnote-71123177
Ref: ssl<9>-Footnote-81123219
Ref: ssl<9>-Footnote-91123261
Node: nntp1123303
Ref: whatsnew/3 2 nntp1123413
Ref: c751123413
Ref: nntp-Footnote-11124002
Ref: nntp-Footnote-21124044
Node: certificates1124086
Ref: whatsnew/3 2 certificates1124200
Ref: c771124200
Ref: certificates-Footnote-11124595
Node: imaplib<4>1124637
Ref: whatsnew/3 2 imaplib1124761
Ref: c791124761
Ref: imaplib<4>-Footnote-11125040
Node: http client<4>1125082
Ref: whatsnew/3 2 http-client1125205
Ref: c7b1125205
Ref: http client<4>-Footnote-11126627
Node: unittest<6>1126670
Ref: whatsnew/3 2 unittest1126792
Ref: c7e1126792
Ref: unittest<6>-Footnote-11131580
Ref: unittest<6>-Footnote-21131623
Ref: unittest<6>-Footnote-31131665
Node: random<3>1131707
Ref: whatsnew/3 2 random1131824
Ref: c8a1131824
Ref: random<3>-Footnote-11132494
Node: poplib<4>1132536
Ref: whatsnew/3 2 poplib1132653
Ref: c8f1132653
Ref: poplib<4>-Footnote-11133013
Node: asyncore<2>1133055
Ref: whatsnew/3 2 asyncore1133174
Ref: c901133174
Ref: asyncore<2>-Footnote-11133658
Node: tempfile<2>1133700
Ref: whatsnew/3 2 tempfile1133820
Ref: c951133820
Ref: tempfile<2>-Footnote-11134235
Node: inspect<7>1134277
Ref: whatsnew/3 2 inspect1134394
Ref: c971134394
Ref: inspect<7>-Footnote-11135759
Node: pydoc<6>1135802
Ref: whatsnew/3 2 pydoc1135914
Ref: c9a1135914
Ref: pydoc<6>-Footnote-11136239
Node: dis<3>1136281
Ref: whatsnew/3 2 dis1136389
Ref: c9b1136389
Ref: dis<3>-Footnote-11138543
Node: dbm<6>1138585
Ref: whatsnew/3 2 dbm1138694
Ref: c9d1138694
Ref: dbm<6>-Footnote-11138889
Node: ctypes<2>1138931
Ref: whatsnew/3 2 ctypes1139041
Ref: c9e1139041
Node: site<2>1139157
Ref: whatsnew/3 2 site1139273
Ref: ca01139273
Ref: site<2>-Footnote-11140508
Node: sysconfig<2>1140550
Ref: whatsnew/3 2 sysconfig1140663
Ref: ca41140663
Node: pdb<6>1142875
Ref: whatsnew/3 2 pdb1142996
Ref: ca81142996
Node: configparser<2>1143895
Ref: whatsnew/3 2 configparser1144019
Ref: ca91144019
Node: urllib parse<4>1146883
Ref: whatsnew/3 2 urllib-parse1147008
Ref: cab1147008
Ref: urllib parse<4>-Footnote-11149012
Ref: urllib parse<4>-Footnote-21149055
Ref: urllib parse<4>-Footnote-31149104
Ref: urllib parse<4>-Footnote-41149146
Ref: urllib parse<4>-Footnote-51149188
Node: mailbox1149230
Ref: whatsnew/3 2 mailbox1149350
Ref: caf1149350
Ref: mailbox-Footnote-11150922
Node: turtledemo1150964
Ref: whatsnew/3 2 turtledemo1151060
Ref: cb61151060
Ref: turtledemo-Footnote-11151495
Node: 多线程1151538
Ref: whatsnew/3 2 multi-threading1151679
Ref: cb71151679
Ref: 多线程-Footnote-11153295
Ref: 多线程-Footnote-21153374
Ref: 多线程-Footnote-31153416
Ref: 多线程-Footnote-41153460
Node: 性能优化<7>1153502
Ref: whatsnew/3 2 optimizations1153617
Ref: cb91153617
Ref: 性能优化<7>-Footnote-11157072
Ref: 性能优化<7>-Footnote-21157114
Ref: 性能优化<7>-Footnote-31157156
Ref: 性能优化<7>-Footnote-41157198
Ref: 性能优化<7>-Footnote-51157244
Ref: 性能优化<7>-Footnote-61157286
Ref: 性能优化<7>-Footnote-71157328
Ref: 性能优化<7>-Footnote-81157371
Ref: 性能优化<7>-Footnote-91157413
Ref: 性能优化<7>-Footnote-101157455
Ref: 性能优化<7>-Footnote-111157498
Ref: 性能优化<7>-Footnote-121157541
Ref: 性能优化<7>-Footnote-131157584
Ref: 性能优化<7>-Footnote-141157630
Ref: 性能优化<7>-Footnote-151157673
Ref: 性能优化<7>-Footnote-161157717
Node: Unicode1157760
Ref: whatsnew/3 2 unicode1157878
Ref: cbb1157878
Ref: Unicode-Footnote-11158428
Ref: Unicode-Footnote-21158478
Ref: Unicode-Footnote-31158522
Node: 编解码器1158593
Ref: whatsnew/3 2 codecs1158702
Ref: cbc1158702
Ref: 编解码器-Footnote-11159639
Node: 文档1159684
Ref: whatsnew/3 2 documentation1159790
Ref: cbd1159790
Ref: 文档-Footnote-11161413
Ref: 文档-Footnote-21161481
Ref: 文档-Footnote-31161557
Ref: 文档-Footnote-41161599
Node: IDLE1161641
Ref: whatsnew/3 2 idle1161744
Ref: cc11161744
Ref: IDLE-Footnote-11162144
Ref: IDLE-Footnote-21162186
Node: 代码库1162228
Ref: whatsnew/3 2 code-repository1162353
Ref: cc21162353
Ref: 代码库-Footnote-11162944
Ref: 代码库-Footnote-21162983
Ref: 代码库-Footnote-31163032
Ref: 代码库-Footnote-41163086
Node: 构建和 C API 的改变<5>1163130
Ref: whatsnew/3 2 build-and-c-api-changes1163271
Ref: cc31163271
Ref: 构建和 C API 的改变<5>-Footnote-11167422
Ref: 构建和 C API 的改变<5>-Footnote-21167465
Ref: 构建和 C API 的改变<5>-Footnote-31167507
Ref: 构建和 C API 的改变<5>-Footnote-41167549
Ref: 构建和 C API 的改变<5>-Footnote-51167591
Ref: 构建和 C API 的改变<5>-Footnote-61167633
Ref: 构建和 C API 的改变<5>-Footnote-71167675
Ref: 构建和 C API 的改变<5>-Footnote-81167717
Ref: 构建和 C API 的改变<5>-Footnote-91167759
Ref: 构建和 C API 的改变<5>-Footnote-101167801
Ref: 构建和 C API 的改变<5>-Footnote-111167844
Ref: 构建和 C API 的改变<5>-Footnote-121167887
Ref: 构建和 C API 的改变<5>-Footnote-131167930
Ref: 构建和 C API 的改变<5>-Footnote-141167992
Ref: 构建和 C API 的改变<5>-Footnote-151168072
Node: 移植到 Python 3 21168129
Ref: whatsnew/3 2 porting-to-python-3-21168252
Ref: ccc1168252
Ref: 移植到 Python 3 2-Footnote-11175088
Ref: 移植到 Python 3 2-Footnote-21175130
Ref: 移植到 Python 3 2-Footnote-31175172
Ref: 移植到 Python 3 2-Footnote-41175217
Ref: 移植到 Python 3 2-Footnote-51175260
Ref: 移植到 Python 3 2-Footnote-61175303
Ref: 移植到 Python 3 2-Footnote-71175346
Node: Python 3 1 有什么新变化1175388
Ref: whatsnew/3 1 doc1175558
Ref: cdd1175558
Ref: whatsnew/3 1 what-s-new-in-python-3-11175558
Ref: cde1175558
Node: PEP 372 有序字典1176154
Ref: whatsnew/3 1 pep-372-ordered-dictionaries1176290
Ref: cdf1176290
Ref: PEP 372 有序字典-Footnote-11177798
Ref: PEP 372 有序字典-Footnote-21177825
Node: PEP 378 千位分隔符的格式说明符1177874
Ref: whatsnew/3 1 pep-378-format-specifier-for-thousands-separator1178046
Ref: ce01178046
Ref: PEP 378 千位分隔符的格式说明符-Footnote-11179249
Node: 其他语言特性修改<9>1179298
Ref: whatsnew/3 1 other-language-changes1179486
Ref: ce11179486
Ref: 其他语言特性修改<9>-Footnote-11184282
Ref: 其他语言特性修改<9>-Footnote-21184327
Ref: 其他语言特性修改<9>-Footnote-31184369
Ref: 其他语言特性修改<9>-Footnote-41184411
Ref: 其他语言特性修改<9>-Footnote-51184453
Ref: 其他语言特性修改<9>-Footnote-61184498
Ref: 其他语言特性修改<9>-Footnote-71184540
Node: 新增，改进和弃用的模块<2>1184582
Ref: whatsnew/3 1 new-improved-and-deprecated-modules1184744
Ref: ce21184744
Ref: 新增，改进和弃用的模块<2>-Footnote-11193336
Ref: 新增，改进和弃用的模块<2>-Footnote-21193381
Ref: 新增，改进和弃用的模块<2>-Footnote-31193423
Ref: 新增，改进和弃用的模块<2>-Footnote-41193465
Ref: 新增，改进和弃用的模块<2>-Footnote-51193507
Ref: 新增，改进和弃用的模块<2>-Footnote-61193549
Ref: 新增，改进和弃用的模块<2>-Footnote-71193598
Ref: 新增，改进和弃用的模块<2>-Footnote-81193640
Ref: 新增，改进和弃用的模块<2>-Footnote-91193682
Ref: 新增，改进和弃用的模块<2>-Footnote-101193724
Ref: 新增，改进和弃用的模块<2>-Footnote-111193767
Ref: 新增，改进和弃用的模块<2>-Footnote-121193810
Ref: 新增，改进和弃用的模块<2>-Footnote-131193853
Node: 性能优化<8>1193896
Ref: whatsnew/3 1 optimizations1194038
Ref: ce81194038
Ref: 性能优化<8>-Footnote-11196227
Ref: 性能优化<8>-Footnote-21196276
Ref: 性能优化<8>-Footnote-31196318
Ref: 性能优化<8>-Footnote-41196360
Ref: 性能优化<8>-Footnote-51196402
Ref: 性能优化<8>-Footnote-61196427
Ref: 性能优化<8>-Footnote-71196469
Node: IDLE<2>1196511
Ref: whatsnew/3 1 idle1196645
Ref: ce91196645
Ref: IDLE<2>-Footnote-11196868
Node: 构建和 C API 的改变<6>1196910
Ref: whatsnew/3 1 build-and-c-api-changes1197049
Ref: cea1197049
Ref: 构建和 C API 的改变<6>-Footnote-11199328
Ref: 构建和 C API 的改变<6>-Footnote-21199370
Ref: 构建和 C API 的改变<6>-Footnote-31199412
Ref: 构建和 C API 的改变<6>-Footnote-41199454
Ref: 构建和 C API 的改变<6>-Footnote-51199496
Node: 移植到 Python 3 11199538
Ref: whatsnew/3 1 porting-to-python-3-11199661
Ref: cee1199661
Node: Python 3 0 有什么新变化1200786
Ref: whatsnew/3 0 doc1200956
Ref: cef1200956
Ref: whatsnew/3 0 what-s-new-in-python-3-01200956
Ref: cf01200956
Node: 常见的绊脚石1202755
Ref: whatsnew/3 0 common-stumbling-blocks1202874
Ref: cf11202874
Node: Print Is A Function1203226
Ref: whatsnew/3 0 print-is-a-function1203345
Ref: cf21203345
Ref: Print Is A Function-Footnote-11205028
Node: Views And Iterators Instead Of Lists1205077
Ref: whatsnew/3 0 views-and-iterators-instead-of-lists1205225
Ref: cf31205225
Node: Ordering Comparisons1207063
Ref: whatsnew/3 0 ordering-comparisons1207198
Ref: cfd1207198
Node: 整数1208647
Ref: whatsnew/3 0 integers1208786
Ref: cff1208786
Ref: 整数-Footnote-11210000
Ref: 整数-Footnote-21210049
Node: Text Vs Data Instead Of Unicode Vs 8-bit1210098
Ref: whatsnew/3 0 text-vs-data-instead-of-unicode-vs-8-bit1210208
Ref: d001210208
Ref: Text Vs Data Instead Of Unicode Vs 8-bit-Footnote-11216791
Ref: Text Vs Data Instead Of Unicode Vs 8-bit-Footnote-21216840
Ref: Text Vs Data Instead Of Unicode Vs 8-bit-Footnote-31216889
Node: Overview Of Syntax Changes1216938
Ref: whatsnew/3 0 overview-of-syntax-changes1217103
Ref: d051217103
Node: 新语法1217316
Ref: whatsnew/3 0 new-syntax1217412
Ref: d061217412
Ref: 新语法-Footnote-11219955
Ref: 新语法-Footnote-21220004
Ref: 新语法-Footnote-31220053
Ref: 新语法-Footnote-41220102
Ref: 新语法-Footnote-51220151
Node: 修改的语法1220200
Ref: whatsnew/3 0 changed-syntax1220320
Ref: d091220320
Ref: 修改的语法-Footnote-11222012
Ref: 修改的语法-Footnote-21222061
Ref: 修改的语法-Footnote-31222110
Ref: 修改的语法-Footnote-41222159
Node: 移除的语法1222208
Ref: whatsnew/3 0 removed-syntax1222310
Ref: d0b1222310
Ref: 移除的语法-Footnote-11223499
Ref: 移除的语法-Footnote-21223548
Node: Changes Already Present In Python 2 61223597
Ref: whatsnew/3 0 changes-already-present-in-python-2-61223759
Ref: d0e1223759
Node: Library Changes1227521
Ref: whatsnew/3 0 library-changes1227701
Ref: d211227701
Ref: Library Changes-Footnote-11233931
Ref: Library Changes-Footnote-21233980
Ref: Library Changes-Footnote-31234029
Ref: Library Changes-Footnote-41234078
Ref: Library Changes-Footnote-51234127
Ref: Library Changes-Footnote-61234176
Node: PEP 3101 A New Approach To String Formatting1234225
Ref: whatsnew/3 0 pep-3101-a-new-approach-to-string-formatting1234389
Ref: d251234389
Ref: PEP 3101 A New Approach To String Formatting-Footnote-11234843
Node: Changes To Exceptions1234892
Ref: whatsnew/3 0 changes-to-exceptions1235068
Ref: d261235068
Ref: Changes To Exceptions-Footnote-11238574
Ref: Changes To Exceptions-Footnote-21238623
Ref: Changes To Exceptions-Footnote-31238672
Ref: Changes To Exceptions-Footnote-41238721
Ref: Changes To Exceptions-Footnote-51238770
Node: Miscellaneous Other Changes1238819
Ref: whatsnew/3 0 miscellaneous-other-changes1238979
Ref: d281238979
Node: Operators And Special Methods1239107
Ref: whatsnew/3 0 operators-and-special-methods1239217
Ref: d291239217
Ref: Operators And Special Methods-Footnote-11240855
Node: Builtins1240904
Ref: whatsnew/3 0 builtins1241014
Ref: d311241014
Ref: Builtins-Footnote-11243487
Ref: Builtins-Footnote-21243536
Node: 构建和 C API 的改变<7>1243585
Ref: whatsnew/3 0 build-and-c-api-changes1243730
Ref: d391243730
Ref: 构建和 C API 的改变<7>-Footnote-11244763
Ref: 构建和 C API 的改变<7>-Footnote-21244812
Ref: 构建和 C API 的改变<7>-Footnote-31244861
Node: 性能1244910
Ref: whatsnew/3 0 performance1245048
Ref: d3c1245048
Node: 移植到 Python 3 01245357
Ref: whatsnew/3 0 porting-to-python-3-01245458
Ref: d3d1245458
Node: Python 2 7 有什么新变化1247054
Ref: whatsnew/2 7 doc1247224
Ref: d401247224
Ref: whatsnew/2 7 what-s-new-in-python-2-71247224
Ref: d411247224
Node: Python 2 x的未来1249641
Ref: whatsnew/2 7 the-future-for-python-2-x1249782
Ref: d421249782
Ref: whatsnew/2 7 whatsnew27-python311249782
Ref: d431249782
Ref: Python 2 x的未来-Footnote-11252546
Ref: Python 2 x的未来-Footnote-21252595
Node: Changes to the Handling of Deprecation Warnings1252632
Ref: whatsnew/2 7 changes-to-the-handling-of-deprecation-warnings1252801
Ref: d461252801
Ref: Changes to the Handling of Deprecation Warnings-Footnote-11254376
Node: Python 3 1 Features1254418
Ref: whatsnew/2 7 python-3-1-features1254619
Ref: d471254619
Node: PEP 372 Adding an Ordered Dictionary to collections1256500
Ref: whatsnew/2 7 pep-03721256698
Ref: d481256698
Ref: whatsnew/2 7 pep-372-adding-an-ordered-dictionary-to-collections1256698
Ref: d4b1256698
Ref: PEP 372 Adding an Ordered Dictionary to collections-Footnote-11260290
Ref: PEP 372 Adding an Ordered Dictionary to collections-Footnote-21260317
Node: PEP 378 千位分隔符的格式说明符<2>1260366
Ref: whatsnew/2 7 pep-03781260598
Ref: d491260598
Ref: whatsnew/2 7 pep-378-format-specifier-for-thousands-separator1260598
Ref: d4d1260598
Ref: PEP 378 千位分隔符的格式说明符<2>-Footnote-11262070
Node: PEP 389 The argparse Module for Parsing Command Lines1262119
Ref: whatsnew/2 7 pep-389-the-argparse-module-for-parsing-command-lines1262350
Ref: d4e1262350
Ref: PEP 389 The argparse Module for Parsing Command Lines-Footnote-11266355
Node: PEP 391 Dictionary-Based Configuration For Logging1266404
Ref: whatsnew/2 7 pep-391-dictionary-based-configuration-for-logging1266616
Ref: d4f1266616
Ref: PEP 391 Dictionary-Based Configuration For Logging-Footnote-11270441
Node: PEP 3106 Dictionary Views1270490
Ref: whatsnew/2 7 pep-3106-dictionary-views1270679
Ref: d551270679
Ref: PEP 3106 Dictionary Views-Footnote-11272792
Ref: PEP 3106 Dictionary Views-Footnote-21272841
Node: PEP 3137 The memoryview Object1272883
Ref: whatsnew/2 7 pep-3137-the-memoryview-object1273050
Ref: d561273050
Ref: PEP 3137 The memoryview Object-Footnote-11274710
Ref: PEP 3137 The memoryview Object-Footnote-21274759
Node: 其他语言特性修改<10>1274801
Ref: whatsnew/2 7 other-language-changes1274967
Ref: d571274967
Ref: 其他语言特性修改<10>-Footnote-11284887
Ref: 其他语言特性修改<10>-Footnote-21284929
Ref: 其他语言特性修改<10>-Footnote-31284971
Ref: 其他语言特性修改<10>-Footnote-41285013
Ref: 其他语言特性修改<10>-Footnote-51285055
Ref: 其他语言特性修改<10>-Footnote-61285097
Ref: 其他语言特性修改<10>-Footnote-71285139
Ref: 其他语言特性修改<10>-Footnote-81285181
Ref: 其他语言特性修改<10>-Footnote-91285223
Ref: 其他语言特性修改<10>-Footnote-101285265
Ref: 其他语言特性修改<10>-Footnote-111285308
Ref: 其他语言特性修改<10>-Footnote-121285351
Ref: 其他语言特性修改<10>-Footnote-131285394
Ref: 其他语言特性修改<10>-Footnote-141285437
Ref: 其他语言特性修改<10>-Footnote-151285483
Ref: 其他语言特性修改<10>-Footnote-161285526
Ref: 其他语言特性修改<10>-Footnote-171285569
Ref: 其他语言特性修改<10>-Footnote-181285612
Ref: 其他语言特性修改<10>-Footnote-191285658
Ref: 其他语言特性修改<10>-Footnote-201285701
Ref: 其他语言特性修改<10>-Footnote-211285744
Ref: 其他语言特性修改<10>-Footnote-221285787
Ref: 其他语言特性修改<10>-Footnote-231285830
Ref: 其他语言特性修改<10>-Footnote-241285873
Node: Interpreter Changes1285916
Ref: whatsnew/2 7 interpreter-changes1286024
Ref: d5a1286024
Ref: whatsnew/2 7 new-27-interpreter1286024
Ref: d5b1286024
Ref: Interpreter Changes-Footnote-11286678
Node: 性能优化<9>1286720
Ref: whatsnew/2 7 optimizations1286828
Ref: d5c1286828
Ref: 性能优化<9>-Footnote-11291709
Ref: 性能优化<9>-Footnote-21291751
Ref: 性能优化<9>-Footnote-31291793
Ref: 性能优化<9>-Footnote-41291835
Ref: 性能优化<9>-Footnote-51291877
Ref: 性能优化<9>-Footnote-61291919
Ref: 性能优化<9>-Footnote-71291964
Ref: 性能优化<9>-Footnote-81292006
Ref: 性能优化<9>-Footnote-91292048
Ref: 性能优化<9>-Footnote-101292090
Ref: 性能优化<9>-Footnote-111292133
Ref: 性能优化<9>-Footnote-121292176
Ref: 性能优化<9>-Footnote-131292219
Node: 新增和改进的模块1292262
Ref: whatsnew/2 7 new-and-improved-modules1292426
Ref: d5f1292426
Ref: 新增和改进的模块-Footnote-11327532
Ref: 新增和改进的模块-Footnote-21327574
Ref: 新增和改进的模块-Footnote-31327616
Ref: 新增和改进的模块-Footnote-41327669
Ref: 新增和改进的模块-Footnote-51327711
Ref: 新增和改进的模块-Footnote-61327753
Ref: 新增和改进的模块-Footnote-71327798
Ref: 新增和改进的模块-Footnote-81327840
Ref: 新增和改进的模块-Footnote-91327882
Ref: 新增和改进的模块-Footnote-101327924
Ref: 新增和改进的模块-Footnote-111327967
Ref: 新增和改进的模块-Footnote-121328010
Ref: 新增和改进的模块-Footnote-131328053
Ref: 新增和改进的模块-Footnote-141328093
Ref: 新增和改进的模块-Footnote-151328136
Ref: 新增和改进的模块-Footnote-161328179
Ref: 新增和改进的模块-Footnote-171328222
Ref: 新增和改进的模块-Footnote-181328265
Ref: 新增和改进的模块-Footnote-191328308
Ref: 新增和改进的模块-Footnote-201328351
Ref: 新增和改进的模块-Footnote-211328394
Ref: 新增和改进的模块-Footnote-221328437
Ref: 新增和改进的模块-Footnote-231328480
Ref: 新增和改进的模块-Footnote-241328523
Ref: 新增和改进的模块-Footnote-251328566
Ref: 新增和改进的模块-Footnote-261328609
Ref: 新增和改进的模块-Footnote-271328655
Ref: 新增和改进的模块-Footnote-281328698
Ref: 新增和改进的模块-Footnote-291328741
Ref: 新增和改进的模块-Footnote-301328784
Ref: 新增和改进的模块-Footnote-311328827
Ref: 新增和改进的模块-Footnote-321328870
Ref: 新增和改进的模块-Footnote-331328913
Ref: 新增和改进的模块-Footnote-341328956
Ref: 新增和改进的模块-Footnote-351328999
Ref: 新增和改进的模块-Footnote-361329042
Ref: 新增和改进的模块-Footnote-371329085
Ref: 新增和改进的模块-Footnote-381329128
Ref: 新增和改进的模块-Footnote-391329171
Ref: 新增和改进的模块-Footnote-401329214
Ref: 新增和改进的模块-Footnote-411329257
Ref: 新增和改进的模块-Footnote-421329300
Ref: 新增和改进的模块-Footnote-431329343
Ref: 新增和改进的模块-Footnote-441329386
Ref: 新增和改进的模块-Footnote-451329429
Ref: 新增和改进的模块-Footnote-461329472
Ref: 新增和改进的模块-Footnote-471329515
Ref: 新增和改进的模块-Footnote-481329558
Ref: 新增和改进的模块-Footnote-491329604
Ref: 新增和改进的模块-Footnote-501329647
Ref: 新增和改进的模块-Footnote-511329690
Ref: 新增和改进的模块-Footnote-521329733
Ref: 新增和改进的模块-Footnote-531329776
Ref: 新增和改进的模块-Footnote-541329819
Ref: 新增和改进的模块-Footnote-551329862
Ref: 新增和改进的模块-Footnote-561329905
Ref: 新增和改进的模块-Footnote-571329948
Ref: 新增和改进的模块-Footnote-581329991
Ref: 新增和改进的模块-Footnote-591330034
Ref: 新增和改进的模块-Footnote-601330077
Ref: 新增和改进的模块-Footnote-611330120
Ref: 新增和改进的模块-Footnote-621330163
Ref: 新增和改进的模块-Footnote-631330206
Ref: 新增和改进的模块-Footnote-641330249
Ref: 新增和改进的模块-Footnote-651330292
Ref: 新增和改进的模块-Footnote-661330335
Ref: 新增和改进的模块-Footnote-671330378
Ref: 新增和改进的模块-Footnote-681330421
Ref: 新增和改进的模块-Footnote-691330464
Ref: 新增和改进的模块-Footnote-701330510
Ref: 新增和改进的模块-Footnote-711330553
Ref: 新增和改进的模块-Footnote-721330596
Ref: 新增和改进的模块-Footnote-731330682
Ref: 新增和改进的模块-Footnote-741330725
Ref: 新增和改进的模块-Footnote-751330768
Ref: 新增和改进的模块-Footnote-761330811
Ref: 新增和改进的模块-Footnote-771330854
Ref: 新增和改进的模块-Footnote-781330897
Ref: 新增和改进的模块-Footnote-791330943
Ref: 新增和改进的模块-Footnote-801330986
Ref: 新增和改进的模块-Footnote-811331029
Ref: 新增和改进的模块-Footnote-821331072
Ref: 新增和改进的模块-Footnote-831331115
Ref: 新增和改进的模块-Footnote-841331158
Ref: 新增和改进的模块-Footnote-851331201
Ref: 新增和改进的模块-Footnote-861331247
Ref: 新增和改进的模块-Footnote-871331293
Ref: 新增和改进的模块-Footnote-881331336
Ref: 新增和改进的模块-Footnote-891331386
Ref: 新增和改进的模块-Footnote-901331436
Ref: 新增和改进的模块-Footnote-911331479
Ref: 新增和改进的模块-Footnote-921331522
Ref: 新增和改进的模块-Footnote-931331565
Ref: 新增和改进的模块-Footnote-941331608
Ref: 新增和改进的模块-Footnote-951331651
Ref: 新增和改进的模块-Footnote-961331694
Ref: 新增和改进的模块-Footnote-971331737
Node: 新模块：importlib1331780
Ref: whatsnew/2 7 importlib-section1331892
Ref: d4a1331892
Ref: whatsnew/2 7 new-module-importlib1331892
Ref: d841331892
Node: 新模块：sysconfig1333424
Ref: whatsnew/2 7 new-module-sysconfig1333570
Ref: d851333570
Node: ttk Themed Widgets for Tk1334892
Ref: whatsnew/2 7 ttk-themed-widgets-for-tk1335043
Ref: d881335043
Ref: ttk Themed Widgets for Tk-Footnote-11336111
Ref: ttk Themed Widgets for Tk-Footnote-21336153
Node: 更新的模块：unittest1336195
Ref: whatsnew/2 7 unittest-section1336358
Ref: d891336358
Ref: whatsnew/2 7 updated-module-unittest1336358
Ref: d8a1336358
Ref: 更新的模块：unittest-Footnote-11345210
Ref: 更新的模块：unittest-Footnote-21345236
Ref: 更新的模块：unittest-Footnote-31345273
Ref: 更新的模块：unittest-Footnote-41345315
Ref: 更新的模块：unittest-Footnote-51345357
Ref: 更新的模块：unittest-Footnote-61345402
Ref: 更新的模块：unittest-Footnote-71345444
Ref: 更新的模块：unittest-Footnote-81345486
Ref: 更新的模块：unittest-Footnote-91345528
Ref: 更新的模块：unittest-Footnote-101345570
Ref: 更新的模块：unittest-Footnote-111345613
Ref: 更新的模块：unittest-Footnote-121345656
Ref: 更新的模块：unittest-Footnote-131345699
Ref: 更新的模块：unittest-Footnote-141345742
Node: 更新的模块：ElementTree 1 31345785
Ref: whatsnew/2 7 elementtree-section1345914
Ref: dad1345914
Ref: whatsnew/2 7 updated-module-elementtree-1-31345914
Ref: dae1345914
Ref: 更新的模块：ElementTree 1 3-Footnote-11349855
Node: 构建和 C API 的改变<8>1349897
Ref: whatsnew/2 7 build-and-c-api-changes1350056
Ref: db01350056
Ref: 构建和 C API 的改变<8>-Footnote-11358624
Ref: 构建和 C API 的改变<8>-Footnote-21358694
Ref: 构建和 C API 的改变<8>-Footnote-31358736
Ref: 构建和 C API 的改变<8>-Footnote-41358778
Ref: 构建和 C API 的改变<8>-Footnote-51358820
Ref: 构建和 C API 的改变<8>-Footnote-61358862
Ref: 构建和 C API 的改变<8>-Footnote-71358904
Ref: 构建和 C API 的改变<8>-Footnote-81358946
Ref: 构建和 C API 的改变<8>-Footnote-91359015
Ref: 构建和 C API 的改变<8>-Footnote-101359057
Ref: 构建和 C API 的改变<8>-Footnote-111359100
Ref: 构建和 C API 的改变<8>-Footnote-121359143
Ref: 构建和 C API 的改变<8>-Footnote-131359186
Ref: 构建和 C API 的改变<8>-Footnote-141359232
Ref: 构建和 C API 的改变<8>-Footnote-151359278
Ref: 构建和 C API 的改变<8>-Footnote-161359321
Ref: 构建和 C API 的改变<8>-Footnote-171359364
Ref: 构建和 C API 的改变<8>-Footnote-181359407
Ref: 构建和 C API 的改变<8>-Footnote-191359450
Ref: 构建和 C API 的改变<8>-Footnote-201359493
Ref: 构建和 C API 的改变<8>-Footnote-211359539
Ref: 构建和 C API 的改变<8>-Footnote-221359582
Node: 胶囊1359625
Ref: whatsnew/2 7 capsules1359735
Ref: db41359735
Ref: whatsnew/2 7 whatsnew27-capsules1359735
Ref: db51359735
Ref: 胶囊-Footnote-11361713
Node: 特定于 Windows 的更改：1361755
Ref: whatsnew/2 7 port-specific-changes-windows1361905
Ref: db81361905
Ref: 特定于 Windows 的更改：-Footnote-11363590
Ref: 特定于 Windows 的更改：-Footnote-21363632
Ref: 特定于 Windows 的更改：-Footnote-31363674
Ref: 特定于 Windows 的更改：-Footnote-41363716
Ref: 特定于 Windows 的更改：-Footnote-51363761
Ref: 特定于 Windows 的更改：-Footnote-61363803
Node: 特定于 Mac OS X 的更改：1363845
Ref: whatsnew/2 7 port-specific-changes-mac-os-x1364019
Ref: dba1364019
Ref: 特定于 Mac OS X 的更改：-Footnote-11365047
Ref: 特定于 Mac OS X 的更改：-Footnote-21365089
Node: 特定于 FreeBSD 的更改：1365132
Ref: whatsnew/2 7 port-specific-changes-freebsd1365267
Ref: dbb1365267
Ref: 特定于 FreeBSD 的更改：-Footnote-11365620
Node: Other Changes and Fixes1365662
Ref: whatsnew/2 7 other-changes-and-fixes1365817
Ref: dbc1365817
Ref: Other Changes and Fixes-Footnote-11368005
Ref: Other Changes and Fixes-Footnote-21368047
Ref: Other Changes and Fixes-Footnote-31368092
Ref: Other Changes and Fixes-Footnote-41368134
Ref: Other Changes and Fixes-Footnote-51368176
Node: 移植到 Python 2 71368218
Ref: whatsnew/2 7 porting-to-python-2-71368398
Ref: dbd1368398
Ref: 移植到 Python 2 7-Footnote-11373963
Ref: 移植到 Python 2 7-Footnote-21374005
Ref: 移植到 Python 2 7-Footnote-31374047
Ref: 移植到 Python 2 7-Footnote-41374089
Ref: 移植到 Python 2 7-Footnote-51374131
Ref: 移植到 Python 2 7-Footnote-61374173
Ref: 移植到 Python 2 7-Footnote-71374215
Ref: 移植到 Python 2 7-Footnote-81374257
Ref: 移植到 Python 2 7-Footnote-91374299
Ref: 移植到 Python 2 7-Footnote-101374341
Ref: 移植到 Python 2 7-Footnote-111374384
Ref: 移植到 Python 2 7-Footnote-121374427
Ref: 移植到 Python 2 7-Footnote-131374470
Ref: 移植到 Python 2 7-Footnote-141374520
Node: New Features Added to Python 2 7 Maintenance Releases1374563
Ref: whatsnew/2 7 new-features-added-to-python-2-7-maintenance-releases1374726
Ref: dbe1374726
Ref: whatsnew/2 7 py27-maintenance-enhancements1374726
Ref: d441374726
Node: Two new environment variables for debug mode1376192
Ref: whatsnew/2 7 two-new-environment-variables-for-debug-mode1376386
Ref: dbf1376386
Ref: Two new environment variables for debug mode-Footnote-11377063
Ref: Two new environment variables for debug mode-Footnote-21377106
Node: PEP 434 IDLE Enhancement Exception for All Branches1377149
Ref: whatsnew/2 7 pep-434-idle-enhancement-exception-for-all-branches1377404
Ref: dc01377404
Ref: PEP 434 IDLE Enhancement Exception for All Branches-Footnote-11377924
Node: PEP 466 Network Security Enhancements for Python 2 71377973
Ref: whatsnew/2 7 pep-466-network-security-enhancements-for-python-2-71378232
Ref: dc11378232
Ref: PEP 466 Network Security Enhancements for Python 2 7-Footnote-11380460
Ref: PEP 466 Network Security Enhancements for Python 2 7-Footnote-21380509
Ref: PEP 466 Network Security Enhancements for Python 2 7-Footnote-31380558
Ref: PEP 466 Network Security Enhancements for Python 2 7-Footnote-41380601
Ref: PEP 466 Network Security Enhancements for Python 2 7-Footnote-51380644
Ref: PEP 466 Network Security Enhancements for Python 2 7-Footnote-61380693
Ref: PEP 466 Network Security Enhancements for Python 2 7-Footnote-71380736
Ref: PEP 466 Network Security Enhancements for Python 2 7-Footnote-81380779
Ref: PEP 466 Network Security Enhancements for Python 2 7-Footnote-91380828
Ref: PEP 466 Network Security Enhancements for Python 2 7-Footnote-101380871
Ref: PEP 466 Network Security Enhancements for Python 2 7-Footnote-111380915
Node: PEP 477 Backport ensurepip PEP 453 to Python 2 71380959
Ref: whatsnew/2 7 pep-477-backport-ensurepip-pep-453-to-python-2-71381246
Ref: dc41381246
Ref: PEP 477 Backport ensurepip PEP 453 to Python 2 7-Footnote-11381724
Ref: PEP 477 Backport ensurepip PEP 453 to Python 2 7-Footnote-21381773
Node: Bootstrapping pip By Default<2>1381822
Ref: whatsnew/2 7 bootstrapping-pip-by-default1381962
Ref: dc51381962
Ref: Bootstrapping pip By Default<2>-Footnote-11383630
Ref: Bootstrapping pip By Default<2>-Footnote-21383679
Node: 文档更改<2>1383777
Ref: whatsnew/2 7 documentation-changes1383917
Ref: dc61383917
Ref: whatsnew/2 7 id11383917
Ref: dc71383917
Ref: 文档更改<2>-Footnote-11384795
Ref: 文档更改<2>-Footnote-21384831
Node: PEP 476 Enabling certificate verification by default for stdlib http clients<2>1384880
Ref: whatsnew/2 7 pep-476-enabling-certificate-verification-by-default-for-stdlib-http-clients1385173
Ref: dc81385173
Ref: PEP 476 Enabling certificate verification by default for stdlib http clients<2>-Footnote-11386254
Node: PEP 493：适用于Python 2 7 的 HTTPS 验证迁移工具1386303
Ref: whatsnew/2 7 pep-493-https-verification-migration-tools-for-python-2-71386582
Ref: dc91386582
Ref: PEP 493：适用于Python 2 7 的 HTTPS 验证迁移工具-Footnote-11387735
Node: New make regen-all build target<3>1387784
Ref: whatsnew/2 7 new-make-regen-all-build-target1388021
Ref: dca1388021
Ref: New make regen-all build target<3>-Footnote-11388815
Ref: New make regen-all build target<3>-Footnote-21388882
Node: Removal of make touch build target<3>1388925
Ref: whatsnew/2 7 removal-of-make-touch-build-target1389095
Ref: dcb1389095
Ref: Removal of make touch build target<3>-Footnote-11389527
Node: 致谢1389570
Ref: whatsnew/2 7 acknowledgements1389704
Ref: dcc1389704
Ref: whatsnew/2 7 acks271389704
Ref: dcd1389704
Node: Python 2 6 有什么新变化1389898
Ref: whatsnew/2 6 doc1390068
Ref: dce1390068
Ref: whatsnew/2 6 what-s-new-in-python-2-61390068
Ref: dcf1390068
Ref: whatsnew/2 6 whats-new-in-2-61390068
Ref: d0f1390068
Ref: Python 2 6 有什么新变化-Footnote-11392949
Node: Python 3 01392998
Ref: whatsnew/2 6 python-3-01393104
Ref: dd01393104
Ref: Python 3 0-Footnote-11395217
Ref: Python 3 0-Footnote-21395266
Node: 开发过程的变化1395315
Ref: whatsnew/2 6 changes-to-the-development-process1395451
Ref: dd11395451
Node: New Issue Tracker Roundup1395881
Ref: whatsnew/2 6 new-issue-tracker-roundup1396028
Ref: dd21396028
Ref: New Issue Tracker Roundup-Footnote-11398059
Ref: New Issue Tracker Roundup-Footnote-21398108
Ref: New Issue Tracker Roundup-Footnote-31398139
Ref: New Issue Tracker Roundup-Footnote-41398179
Ref: New Issue Tracker Roundup-Footnote-51398214
Node: 新的文档格式：使用 Sphinx 的 reStructuredText1398255
Ref: whatsnew/2 6 new-documentation-format-restructuredtext-using-sphinx1398402
Ref: dd31398402
Ref: 新的文档格式：使用 Sphinx 的 reStructuredText-Footnote-11400469
Ref: 新的文档格式：使用 Sphinx 的 reStructuredText-Footnote-21400528
Ref: 新的文档格式：使用 Sphinx 的 reStructuredText-Footnote-31400577
Ref: 新的文档格式：使用 Sphinx 的 reStructuredText-Footnote-41400608
Node: PEP 343 "with" 语句1400648
Ref: whatsnew/2 6 pep-03431400812
Ref: d101400812
Ref: whatsnew/2 6 pep-343-the-with-statement1400812
Ref: dd41400812
Node: Writing Context Managers1404062
Ref: whatsnew/2 6 new-26-context-managers1404170
Ref: d111404170
Ref: whatsnew/2 6 writing-context-managers1404170
Ref: dd51404170
Node: contextlib 模块1408679
Ref: whatsnew/2 6 new-module-contextlib1408787
Ref: d121408787
Ref: whatsnew/2 6 the-contextlib-module1408787
Ref: dd61408787
Ref: contextlib 模块-Footnote-11411252
Node: PEP 366 从主模块显式相对导入1411301
Ref: whatsnew/2 6 pep-03661411485
Ref: d131411485
Ref: whatsnew/2 6 pep-366-explicit-relative-imports-from-a-main-module1411485
Ref: dd71411485
Node: PEP 370 分用户的 site-packages 目录1412210
Ref: whatsnew/2 6 pep-03701412399
Ref: d141412399
Ref: whatsnew/2 6 pep-370-per-user-site-packages-directory1412399
Ref: dd91412399
Ref: PEP 370 分用户的 site-packages 目录-Footnote-11413832
Node: PEP 371 多任务处理包1413881
Ref: whatsnew/2 6 pep-03711414062
Ref: d151414062
Ref: whatsnew/2 6 pep-371-the-multiprocessing-package1414062
Ref: ddd1414062
Ref: PEP 371 多任务处理包-Footnote-11419134
Node: PEP 3101 高级字符串格式1419183
Ref: whatsnew/2 6 pep-31011419350
Ref: d161419350
Ref: whatsnew/2 6 pep-3101-advanced-string-formatting1419350
Ref: ddf1419350
Ref: PEP 3101 高级字符串格式-Footnote-11424937
Node: PEP 3105 print 改为函数1424986
Ref: whatsnew/2 6 pep-31051425157
Ref: d171425157
Ref: whatsnew/2 6 pep-3105-print-as-a-function1425157
Ref: de11425157
Ref: PEP 3105 print 改为函数-Footnote-11426300
Node: PEP 3110 异常处理的变更1426349
Ref: whatsnew/2 6 pep-31101426514
Ref: d181426514
Ref: whatsnew/2 6 pep-3110-exception-handling-changes1426514
Ref: de21426514
Ref: PEP 3110 异常处理的变更-Footnote-11428070
Node: PEP 3112 字节字面值1428119
Ref: whatsnew/2 6 pep-31121428277
Ref: d191428277
Ref: whatsnew/2 6 pep-3112-byte-literals1428277
Ref: de31428277
Ref: PEP 3112 字节字面值-Footnote-11431292
Node: PEP 3116 新 I/O 库1431341
Ref: whatsnew/2 6 pep-31161431499
Ref: d1a1431499
Ref: whatsnew/2 6 pep-3116-new-i-o-library1431499
Ref: de91431499
Ref: PEP 3116 新 I/O 库-Footnote-11435114
Node: PEP 3118 修改缓冲区协议1435163
Ref: whatsnew/2 6 pep-31181435318
Ref: d1b1435318
Ref: whatsnew/2 6 pep-3118-revised-buffer-protocol1435318
Ref: dea1435318
Ref: PEP 3118 修改缓冲区协议-Footnote-11437438
Node: PEP 3119 抽象基类1437487
Ref: whatsnew/2 6 pep-31191437658
Ref: d1c1437658
Ref: whatsnew/2 6 pep-3119-abstract-base-classes1437658
Ref: dec1437658
Ref: PEP 3119 抽象基类-Footnote-11442985
Node: PEP 3127 整型文字支持和语法1443034
Ref: whatsnew/2 6 pep-31271443196
Ref: d1d1443196
Ref: whatsnew/2 6 pep-3127-integer-literal-support-and-syntax1443196
Ref: def1443196
Ref: PEP 3127 整型文字支持和语法-Footnote-11444498
Node: PEP 3129 类装饰器1444547
Ref: whatsnew/2 6 pep-31291444725
Ref: d1e1444725
Ref: whatsnew/2 6 pep-3129-class-decorators1444725
Ref: df01444725
Ref: PEP 3129 类装饰器-Footnote-11445098
Node: PEP 3141 A Type Hierarchy for Numbers1445147
Ref: whatsnew/2 6 pep-31411445317
Ref: d1f1445317
Ref: whatsnew/2 6 pep-3141-a-type-hierarchy-for-numbers1445317
Ref: df11445317
Ref: PEP 3141 A Type Hierarchy for Numbers-Footnote-11447512
Ref: PEP 3141 A Type Hierarchy for Numbers-Footnote-21447561
Ref: PEP 3141 A Type Hierarchy for Numbers-Footnote-31447659
Node: fractions 模块1447744
Ref: whatsnew/2 6 the-fractions-module1447834
Ref: df51447834
Node: 其他语言特性修改<11>1449431
Ref: whatsnew/2 6 other-language-changes1449607
Ref: df61449607
Ref: 其他语言特性修改<11>-Footnote-11458446
Ref: 其他语言特性修改<11>-Footnote-21458491
Ref: 其他语言特性修改<11>-Footnote-31458533
Ref: 其他语言特性修改<11>-Footnote-41458578
Ref: 其他语言特性修改<11>-Footnote-51458620
Ref: 其他语言特性修改<11>-Footnote-61458662
Ref: 其他语言特性修改<11>-Footnote-71458704
Ref: 其他语言特性修改<11>-Footnote-81458746
Ref: 其他语言特性修改<11>-Footnote-91458788
Ref: 其他语言特性修改<11>-Footnote-101458830
Ref: 其他语言特性修改<11>-Footnote-111458873
Ref: 其他语言特性修改<11>-Footnote-121458916
Ref: 其他语言特性修改<11>-Footnote-131458962
Ref: 其他语言特性修改<11>-Footnote-141459008
Ref: 其他语言特性修改<11>-Footnote-151459054
Ref: 其他语言特性修改<11>-Footnote-161459100
Node: 性能优化<10>1459146
Ref: whatsnew/2 6 optimizations1459258
Ref: dfa1459258
Ref: 性能优化<10>-Footnote-11462108
Ref: 性能优化<10>-Footnote-21462153
Ref: 性能优化<10>-Footnote-31462198
Ref: 性能优化<10>-Footnote-41462240
Node: Interpreter Changes<2>1462282
Ref: whatsnew/2 6 interpreter-changes1462394
Ref: dfb1462394
Ref: whatsnew/2 6 new-26-interpreter1462394
Ref: dfc1462394
Node: 新增和改进的模块<2>1463968
Ref: whatsnew/2 6 new-and-improved-modules1464132
Ref: e001464132
Ref: 新增和改进的模块<2>-Footnote-11506528
Ref: 新增和改进的模块<2>-Footnote-21506573
Ref: 新增和改进的模块<2>-Footnote-31506626
Ref: 新增和改进的模块<2>-Footnote-41506668
Ref: 新增和改进的模块<2>-Footnote-51506712
Ref: 新增和改进的模块<2>-Footnote-61506754
Ref: 新增和改进的模块<2>-Footnote-71506799
Ref: 新增和改进的模块<2>-Footnote-81506841
Ref: 新增和改进的模块<2>-Footnote-91506894
Ref: 新增和改进的模块<2>-Footnote-101506939
Ref: 新增和改进的模块<2>-Footnote-111506985
Ref: 新增和改进的模块<2>-Footnote-121507031
Ref: 新增和改进的模块<2>-Footnote-131507074
Ref: 新增和改进的模块<2>-Footnote-141507117
Ref: 新增和改进的模块<2>-Footnote-151507162
Ref: 新增和改进的模块<2>-Footnote-161507205
Ref: 新增和改进的模块<2>-Footnote-171507251
Ref: 新增和改进的模块<2>-Footnote-181507294
Ref: 新增和改进的模块<2>-Footnote-191507340
Ref: 新增和改进的模块<2>-Footnote-201507386
Ref: 新增和改进的模块<2>-Footnote-211507432
Ref: 新增和改进的模块<2>-Footnote-221507477
Ref: 新增和改进的模块<2>-Footnote-231507523
Ref: 新增和改进的模块<2>-Footnote-241507569
Ref: 新增和改进的模块<2>-Footnote-251507612
Ref: 新增和改进的模块<2>-Footnote-261507655
Ref: 新增和改进的模块<2>-Footnote-271507701
Ref: 新增和改进的模块<2>-Footnote-281507747
Ref: 新增和改进的模块<2>-Footnote-291507792
Ref: 新增和改进的模块<2>-Footnote-301507835
Ref: 新增和改进的模块<2>-Footnote-311507878
Ref: 新增和改进的模块<2>-Footnote-321507921
Ref: 新增和改进的模块<2>-Footnote-331507964
Ref: 新增和改进的模块<2>-Footnote-341508007
Ref: 新增和改进的模块<2>-Footnote-351508050
Ref: 新增和改进的模块<2>-Footnote-361508093
Ref: 新增和改进的模块<2>-Footnote-371508143
Ref: 新增和改进的模块<2>-Footnote-381508188
Ref: 新增和改进的模块<2>-Footnote-391508238
Ref: 新增和改进的模块<2>-Footnote-401508283
Ref: 新增和改进的模块<2>-Footnote-411508326
Ref: 新增和改进的模块<2>-Footnote-421508371
Ref: 新增和改进的模块<2>-Footnote-431508417
Ref: 新增和改进的模块<2>-Footnote-441508460
Ref: 新增和改进的模块<2>-Footnote-451508503
Ref: 新增和改进的模块<2>-Footnote-461508546
Ref: 新增和改进的模块<2>-Footnote-471508592
Ref: 新增和改进的模块<2>-Footnote-481508635
Ref: 新增和改进的模块<2>-Footnote-491508678
Ref: 新增和改进的模块<2>-Footnote-501508724
Ref: 新增和改进的模块<2>-Footnote-511508767
Ref: 新增和改进的模块<2>-Footnote-521508813
Ref: 新增和改进的模块<2>-Footnote-531508856
Ref: 新增和改进的模块<2>-Footnote-541508902
Ref: 新增和改进的模块<2>-Footnote-551508945
Ref: 新增和改进的模块<2>-Footnote-561508991
Ref: 新增和改进的模块<2>-Footnote-571509034
Ref: 新增和改进的模块<2>-Footnote-581509080
Ref: 新增和改进的模块<2>-Footnote-591509126
Ref: 新增和改进的模块<2>-Footnote-601509169
Ref: 新增和改进的模块<2>-Footnote-611509212
Ref: 新增和改进的模块<2>-Footnote-621509257
Ref: 新增和改进的模块<2>-Footnote-631509303
Node: ast 模块1509349
Ref: whatsnew/2 6 the-ast-module1509454
Ref: e0f1509454
Node: future_builtins 模块1512105
Ref: whatsnew/2 6 the-future-builtins-module1512261
Ref: e101512261
Node: The json module JavaScript Object Notation1513366
Ref: whatsnew/2 6 the-json-module-javascript-object-notation1513551
Ref: e121513551
Node: plistlib 模块：属性列表解析器1514563
Ref: whatsnew/2 6 the-plistlib-module-a-property-list-parser1514745
Ref: e131514745
Node: ctypes Enhancements1516098
Ref: whatsnew/2 6 ctypes-enhancements1516258
Ref: e141516258
Ref: ctypes Enhancements-Footnote-11518025
Ref: ctypes Enhancements-Footnote-21518070
Node: Improved SSL Support1518112
Ref: whatsnew/2 6 improved-ssl-support1518224
Ref: e151518224
Ref: Improved SSL Support-Footnote-11519161
Node: Deprecations and Removals1519194
Ref: whatsnew/2 6 deprecations-and-removals1519358
Ref: e161519358
Ref: Deprecations and Removals-Footnote-11521199
Node: 构建和 C API 的改变<9>1521248
Ref: whatsnew/2 6 build-and-c-api-changes1521404
Ref: e181521404
Ref: 构建和 C API 的改变<9>-Footnote-11527379
Ref: 构建和 C API 的改变<9>-Footnote-21527421
Ref: 构建和 C API 的改变<9>-Footnote-31527466
Ref: 构建和 C API 的改变<9>-Footnote-41527508
Ref: 构建和 C API 的改变<9>-Footnote-51527550
Node: 特定于 Windows 的更改：<2>1527595
Ref: whatsnew/2 6 port-specific-changes-windows1527741
Ref: e1f1527741
Ref: 特定于 Windows 的更改：<2>-Footnote-11530136
Ref: 特定于 Windows 的更改：<2>-Footnote-21530180
Ref: 特定于 Windows 的更改：<2>-Footnote-31530225
Node: 特定于 Mac OS X 的更改：Mac OS X1530267
Ref: whatsnew/2 6 port-specific-changes-mac-os-x1530449
Ref: e201530449
Ref: 特定于 Mac OS X 的更改：Mac OS X-Footnote-11531656
Node: 特定于 IRIX 的更改：1531701
Ref: whatsnew/2 6 port-specific-changes-irix1531841
Ref: e211531841
Node: 移植到Python 2 61532341
Ref: whatsnew/2 6 porting-to-python-2-61532481
Ref: e221532481
Ref: 移植到Python 2 6-Footnote-11535899
Ref: 移植到Python 2 6-Footnote-21535944
Ref: 移植到Python 2 6-Footnote-31535989
Node: 致谢<2>1536034
Ref: whatsnew/2 6 acknowledgements1536137
Ref: e251536137
Ref: whatsnew/2 6 acks1536137
Ref: e261536137
Node: Python 2 5 有什么新变化1536397
Ref: whatsnew/2 5 doc1536567
Ref: e271536567
Ref: whatsnew/2 5 what-s-new-in-python-2-51536567
Ref: e281536567
Ref: Python 2 5 有什么新变化-Footnote-11539984
Node: PEP 308 条件表达式1540033
Ref: whatsnew/2 5 pep-3081540157
Ref: e291540157
Ref: whatsnew/2 5 pep-308-conditional-expressions1540157
Ref: e2e1540157
Ref: PEP 308 条件表达式-Footnote-11543599
Ref: PEP 308 条件表达式-Footnote-21543648
Node: PEP 309 部分功能应用1543697
Ref: whatsnew/2 5 pep-3091543870
Ref: e2f1543870
Ref: whatsnew/2 5 pep-309-partial-function-application1543870
Ref: e301543870
Ref: PEP 309 部分功能应用-Footnote-11546680
Node: PEP 314 Python软件包的元数据 v1 11546729
Ref: whatsnew/2 5 pep-3141546914
Ref: e311546914
Ref: whatsnew/2 5 pep-314-metadata-for-python-software-packages-v1-11546914
Ref: e321546914
Ref: PEP 314 Python软件包的元数据 v1 1-Footnote-11548701
Node: PEP 328 绝对导入和相对导入1548750
Ref: whatsnew/2 5 pep-3281548944
Ref: e2c1548944
Ref: whatsnew/2 5 pep-328-absolute-and-relative-imports1548944
Ref: e331548944
Ref: PEP 328 绝对导入和相对导入-Footnote-11552737
Ref: PEP 328 绝对导入和相对导入-Footnote-21552786
Node: PEP 338 将模块作为脚本执行1552835
Ref: whatsnew/2 5 pep-3381553022
Ref: e341553022
Ref: whatsnew/2 5 pep-338-executing-modules-as-scripts1553022
Ref: e351553022
Ref: PEP 338 将模块作为脚本执行-Footnote-11553899
Node: PEP 341 统一 try/except/finally1553948
Ref: whatsnew/2 5 pep-3411554129
Ref: e2d1554129
Ref: whatsnew/2 5 pep-341-unified-try-except-finally1554129
Ref: e361554129
Ref: PEP 341 统一 try/except/finally-Footnote-11555885
Node: PEP 342 生成器的新特性1555934
Ref: whatsnew/2 5 pep-3421556104
Ref: e2b1556104
Ref: whatsnew/2 5 pep-342-new-generator-features1556104
Ref: e381556104
Ref: PEP 342 生成器的新特性-Footnote-11562697
Ref: PEP 342 生成器的新特性-Footnote-21562746
Ref: PEP 342 生成器的新特性-Footnote-31562795
Ref: PEP 342 生成器的新特性-Footnote-41562844
Ref: PEP 342 生成器的新特性-Footnote-51562893
Node: PEP 343 "with" 语句<2>1562942
Ref: whatsnew/2 5 pep-3431563111
Ref: e2a1563111
Ref: whatsnew/2 5 pep-343-the-with-statement1563111
Ref: e391563111
Node: Writing Context Managers<2>1566095
Ref: whatsnew/2 5 new-25-context-managers1566212
Ref: e3a1566212
Ref: whatsnew/2 5 writing-context-managers1566212
Ref: e3b1566212
Node: contextlib 模块<2>1570604
Ref: whatsnew/2 5 contextlibmod1570721
Ref: e3c1570721
Ref: whatsnew/2 5 the-contextlib-module1570721
Ref: e3d1570721
Ref: contextlib 模块<2>-Footnote-11573177
Node: PEP 352 异常作为新型的类1573226
Ref: whatsnew/2 5 pep-3521573405
Ref: e3e1573405
Ref: whatsnew/2 5 pep-352-exceptions-as-new-style-classes1573405
Ref: e3f1573405
Ref: PEP 352 异常作为新型的类-Footnote-11575842
Node: PEP 353 使用ssize_t作为索引类型1575891
Ref: whatsnew/2 5 pep-3531576072
Ref: e411576072
Ref: whatsnew/2 5 pep-353-using-ssize-t-as-the-index-type1576072
Ref: e421576072
Ref: PEP 353 使用ssize_t作为索引类型-Footnote-11578970
Ref: PEP 353 使用ssize_t作为索引类型-Footnote-21579019
Node: PEP 357 '__index__' 方法1579068
Ref: whatsnew/2 5 pep-3571579245
Ref: e441579245
Ref: whatsnew/2 5 pep-357-the-index-method1579245
Ref: e451579245
Ref: PEP 357 '__index__' 方法-Footnote-11580948
Node: 其他语言特性修改<12>1580997
Ref: whatsnew/2 5 other-lang1581168
Ref: e471581168
Ref: whatsnew/2 5 other-language-changes1581168
Ref: e481581168
Ref: 其他语言特性修改<12>-Footnote-11588112
Node: 交互解释器变更1588161
Ref: whatsnew/2 5 interactive1588272
Ref: e4e1588272
Ref: whatsnew/2 5 interactive-interpreter-changes1588272
Ref: e4f1588272
Node: 性能优化<11>1589025
Ref: whatsnew/2 5 optimizations1589136
Ref: e521589136
Ref: whatsnew/2 5 opts1589136
Ref: e531589136
Node: 新增，改进和删除的模块1592944
Ref: whatsnew/2 5 modules1593118
Ref: e541593118
Ref: whatsnew/2 5 new-improved-and-removed-modules1593118
Ref: e551593118
Ref: 新增，改进和删除的模块-Footnote-11617518
Ref: 新增，改进和删除的模块-Footnote-21617567
Ref: 新增，改进和删除的模块-Footnote-31617616
Node: ctypes 包1617665
Ref: whatsnew/2 5 module-ctypes1617769
Ref: e621617769
Ref: whatsnew/2 5 the-ctypes-package1617769
Ref: e631617769
Node: ElementTree 包1620957
Ref: whatsnew/2 5 module-etree1621081
Ref: e641621081
Ref: whatsnew/2 5 the-elementtree-package1621081
Ref: e651621081
Node: hashlib 包1626122
Ref: whatsnew/2 5 module-hashlib1626247
Ref: e661626247
Ref: whatsnew/2 5 the-hashlib-package1626247
Ref: e671626247
Node: sqlite3 包1627799
Ref: whatsnew/2 5 module-sqlite1627920
Ref: e681627920
Ref: whatsnew/2 5 the-sqlite3-package1627920
Ref: e691627920
Ref: sqlite3 包-Footnote-11631864
Ref: sqlite3 包-Footnote-21631913
Node: wsgiref 包1631962
Ref: whatsnew/2 5 module-wsgiref1632063
Ref: e6a1632063
Ref: whatsnew/2 5 the-wsgiref-package1632063
Ref: e6b1632063
Ref: wsgiref 包-Footnote-11632949
Ref: wsgiref 包-Footnote-21632998
Node: 构建和 C API 的改变<10>1633047
Ref: whatsnew/2 5 build-and-c-api-changes1633212
Ref: e6c1633212
Ref: whatsnew/2 5 build-api1633212
Ref: e6d1633212
Ref: 构建和 C API 的改变<10>-Footnote-11640229
Ref: 构建和 C API 的改变<10>-Footnote-21640278
Ref: 构建和 C API 的改变<10>-Footnote-31640327
Node: Port-Specific Changes1640376
Ref: whatsnew/2 5 port-specific-changes1640463
Ref: e771640463
Ref: whatsnew/2 5 ports1640463
Ref: e781640463
Ref: Port-Specific Changes-Footnote-11641140
Node: 移植到Python 2 51641182
Ref: whatsnew/2 5 porting1641323
Ref: e791641323
Ref: whatsnew/2 5 porting-to-python-2-51641323
Ref: e7a1641323
Ref: 移植到Python 2 5-Footnote-11644138
Node: 致谢<3>1644187
Ref: whatsnew/2 5 acknowledgements1644290
Ref: e7b1644290
Node: Python 2 4 有什么新变化1644702
Ref: whatsnew/2 4 doc1644872
Ref: e7c1644872
Ref: whatsnew/2 4 what-s-new-in-python-2-41644872
Ref: e7d1644872
Node: PEP 218 内置集合对象1646899
Ref: whatsnew/2 4 pep-218-built-in-set-objects1647032
Ref: e7e1647032
Ref: PEP 218 内置集合对象-Footnote-11649231
Node: PEP 237 统一长整数和整数1649280
Ref: whatsnew/2 4 pep-237-unifying-long-integers-and-integers1649448
Ref: e7f1649448
Ref: PEP 237 统一长整数和整数-Footnote-11650431
Node: PEP 289 生成器表达式1650480
Ref: whatsnew/2 4 pep-289-generator-expressions1650658
Ref: e801650658
Ref: PEP 289 生成器表达式-Footnote-11652913
Node: PEP 292 Simpler String Substitutions1652962
Ref: whatsnew/2 4 pep-292-simpler-string-substitutions1653152
Ref: e811653152
Ref: PEP 292 Simpler String Substitutions-Footnote-11654938
Node: PEP 318 Decorators for Functions and Methods1654987
Ref: whatsnew/2 4 pep-318-decorators-for-functions-and-methods1655171
Ref: e821655171
Ref: PEP 318 Decorators for Functions and Methods-Footnote-11659675
Ref: PEP 318 Decorators for Functions and Methods-Footnote-21659724
Node: PEP 322 反向迭代1659773
Ref: whatsnew/2 4 pep-322-reverse-iteration1659950
Ref: e841659950
Ref: PEP 322 反向迭代-Footnote-11660887
Node: PEP 324 新的子进程模块1660936
Ref: whatsnew/2 4 pep-324-new-subprocess-module1661098
Ref: e851661098
Ref: PEP 324 新的子进程模块-Footnote-11664832
Node: PEP 327 十进制数据类型1664881
Ref: whatsnew/2 4 pep-327-decimal-data-type1665043
Ref: e871665043
Node: 为什么需要十进制？1665623
Ref: whatsnew/2 4 why-is-decimal-needed1665739
Ref: e881665739
Node: Decimal 类型1668330
Ref: whatsnew/2 4 the-decimal-type1668469
Ref: e891668469
Node: Context 类型1671635
Ref: whatsnew/2 4 the-context-type1671738
Ref: e8a1671738
Ref: Context 类型-Footnote-11674335
Node: PEP 328 多行导入1674384
Ref: whatsnew/2 4 pep-328-multi-line-imports1674568
Ref: e8b1674568
Ref: PEP 328 多行导入-Footnote-11676022
Node: PEP 331 Locale-Independent Float/String Conversions1676071
Ref: whatsnew/2 4 pep-331-locale-independent-float-string-conversions1676254
Ref: e8c1676254
Ref: PEP 331 Locale-Independent Float/String Conversions-Footnote-11677986
Node: 其他语言特性修改<13>1678035
Ref: whatsnew/2 4 other-language-changes1678234
Ref: e8d1678234
Ref: 其他语言特性修改<13>-Footnote-11685214
Ref: 其他语言特性修改<13>-Footnote-21685263
Ref: 其他语言特性修改<13>-Footnote-31685312
Ref: 其他语言特性修改<13>-Footnote-41685361
Ref: 其他语言特性修改<13>-Footnote-51685410
Ref: 其他语言特性修改<13>-Footnote-61685459
Node: 性能优化<12>1685508
Ref: whatsnew/2 4 optimizations1685589
Ref: e8f1685589
Node: 新增，改进和弃用的模块<3>1688338
Ref: whatsnew/2 4 new-improved-and-deprecated-modules1688515
Ref: e911688515
Ref: 新增，改进和弃用的模块<3>-Footnote-11705764
Node: cookielib1705813
Ref: whatsnew/2 4 cookielib1705914
Ref: e931705914
Node: doctest<3>1706824
Ref: whatsnew/2 4 doctest1706925
Ref: e941706925
Node: 构建和 C API 的改变<11>1709659
Ref: whatsnew/2 4 build-and-c-api-changes1709828
Ref: e9a1709828
Node: Port-Specific Changes<2>1712448
Ref: whatsnew/2 4 port-specific-changes1712538
Ref: ea01712538
Node: 移植到 Python 2 41712717
Ref: whatsnew/2 4 porting-to-python-2-41712859
Ref: ea11712859
Node: 致谢<4>1714822
Ref: whatsnew/2 4 acknowledgements1714926
Ref: ea31714926
Ref: whatsnew/2 4 acks1714926
Ref: ea41714926
Node: Python 2 3 有什么新变化1715176
Ref: whatsnew/2 3 doc1715346
Ref: ea51715346
Ref: whatsnew/2 3 what-s-new-in-python-2-31715346
Ref: ea61715346
Node: PEP 218 A Standard Set Datatype1718278
Ref: whatsnew/2 3 pep-218-a-standard-set-datatype1718409
Ref: ea81718409
Ref: PEP 218 A Standard Set Datatype-Footnote-11720894
Node: PEP 255 Simple Generators1720943
Ref: whatsnew/2 3 pep-255-simple-generators1721112
Ref: ea91721112
Ref: whatsnew/2 3 section-generators1721112
Ref: eaa1721112
Ref: PEP 255 Simple Generators-Footnote-11727279
Ref: PEP 255 Simple Generators-Footnote-21727328
Node: PEP 263 Source Code Encodings1727377
Ref: whatsnew/2 3 pep-263-source-code-encodings1727550
Ref: eac1727550
Ref: whatsnew/2 3 section-encodings1727550
Ref: ead1727550
Ref: PEP 263 Source Code Encodings-Footnote-11728760
Node: PEP 273 从ZIP压缩包导入模块1728809
Ref: whatsnew/2 3 pep-273-importing-modules-from-zip-archives1729005
Ref: eae1729005
Ref: PEP 273 从ZIP压缩包导入模块-Footnote-11731010
Ref: PEP 273 从ZIP压缩包导入模块-Footnote-21731059
Ref: PEP 273 从ZIP压缩包导入模块-Footnote-31731108
Node: PEP 277 Unicode file name support for Windows NT1731157
Ref: whatsnew/2 3 pep-277-unicode-file-name-support-for-windows-nt1731350
Ref: eb01731350
Ref: PEP 277 Unicode file name support for Windows NT-Footnote-11732825
Node: PEP 278 通用换行支持1732874
Ref: whatsnew/2 3 pep-278-universal-newline-support1733049
Ref: eb21733049
Ref: PEP 278 通用换行支持-Footnote-11734531
Node: PEP 279 enumerate1734580
Ref: whatsnew/2 3 pep-279-enumerate1734726
Ref: eb31734726
Ref: whatsnew/2 3 section-enumerate1734726
Ref: eb41734726
Ref: PEP 279 enumerate-Footnote-11735561
Node: PEP 282 logging 包1735610
Ref: whatsnew/2 3 pep-282-the-logging-package1735750
Ref: eb51735750
Ref: PEP 282 logging 包-Footnote-11740423
Ref: PEP 282 logging 包-Footnote-21740472
Node: PEP 285 布尔类型1740521
Ref: whatsnew/2 3 pep-285-a-boolean-type1740682
Ref: eb61740682
Ref: whatsnew/2 3 section-bool1740682
Ref: eb71740682
Ref: PEP 285 布尔类型-Footnote-11743117
Ref: PEP 285 布尔类型-Footnote-21743166
Node: PEP 293 Codec Error Handling Callbacks1743215
Ref: whatsnew/2 3 pep-293-codec-error-handling-callbacks1743404
Ref: eb81743404
Ref: PEP 293 Codec Error Handling Callbacks-Footnote-11744923
Node: PEP 301 Distutils的软件包索引和元数据1744972
Ref: whatsnew/2 3 pep-301-package-index-and-metadata-for-distutils1745165
Ref: ebb1745165
Ref: whatsnew/2 3 section-pep3011745165
Ref: ebc1745165
Ref: PEP 301 Distutils的软件包索引和元数据-Footnote-11746791
Ref: PEP 301 Distutils的软件包索引和元数据-Footnote-21746827
Node: PEP 302 New Import Hooks1746876
Ref: whatsnew/2 3 pep-302-new-import-hooks1747057
Ref: ebd1747057
Ref: whatsnew/2 3 section-pep3021747057
Ref: eaf1747057
Ref: PEP 302 New Import Hooks-Footnote-11749652
Ref: PEP 302 New Import Hooks-Footnote-21749701
Ref: PEP 302 New Import Hooks-Footnote-31749750
Node: PEP 305 逗号分隔文件1749799
Ref: whatsnew/2 3 pep-305-comma-separated-files1749960
Ref: ebe1749960
Ref: whatsnew/2 3 section-pep3051749960
Ref: ebf1749960
Ref: PEP 305 逗号分隔文件-Footnote-11751420
Node: PEP 307 Pickle Enhancements1751469
Ref: whatsnew/2 3 pep-307-pickle-enhancements1751618
Ref: ec11751618
Ref: whatsnew/2 3 section-pep3071751618
Ref: ec21751618
Ref: PEP 307 Pickle Enhancements-Footnote-11753587
Ref: PEP 307 Pickle Enhancements-Footnote-21753636
Ref: PEP 307 Pickle Enhancements-Footnote-31753685
Node: 扩展切片1753734
Ref: whatsnew/2 3 extended-slices1753885
Ref: ec61753885
Ref: whatsnew/2 3 section-slices1753885
Ref: ec71753885
Node: 其他语言特性修改<14>1757259
Ref: whatsnew/2 3 other-language-changes1757419
Ref: ec91757419
Ref: 其他语言特性修改<14>-Footnote-11765188
Ref: 其他语言特性修改<14>-Footnote-21765260
Node: String Changes1765314
Ref: whatsnew/2 3 string-changes1765418
Ref: ecd1765418
Node: 性能优化<13>1767873
Ref: whatsnew/2 3 optimizations1767977
Ref: ece1767977
Node: 新增，改进和弃用的模块<4>1769418
Ref: whatsnew/2 3 new-improved-and-deprecated-modules1769605
Ref: ed01769605
Ref: 新增，改进和弃用的模块<4>-Footnote-11794186
Node: Date/Time 类型1794225
Ref: whatsnew/2 3 date-time-type1794338
Ref: ed41794338
Node: optparse 模块1796604
Ref: whatsnew/2 3 the-optparse-module1796717
Ref: ed51796717
Node: Pymalloc A Specialized Object Allocator1798771
Ref: whatsnew/2 3 pymalloc-a-specialized-object-allocator1798959
Ref: ed61798959
Ref: whatsnew/2 3 section-pymalloc1798959
Ref: ed71798959
Node: 构建和 C API 的改变<12>1802844
Ref: whatsnew/2 3 build-and-c-api-changes1803022
Ref: ed91803022
Node: Port-Specific Changes<3>1806442
Ref: whatsnew/2 3 port-specific-changes1806532
Ref: ede1806532
Node: Other Changes and Fixes<2>1807767
Ref: whatsnew/2 3 other-changes-and-fixes1807926
Ref: edf1807926
Ref: whatsnew/2 3 section-other1807926
Ref: ecf1807926
Node: 移植到 Python 2 31810400
Ref: whatsnew/2 3 porting-to-python-2-31810539
Ref: ee21810539
Node: 致谢<5>1813342
Ref: whatsnew/2 3 acknowledgements1813446
Ref: ee31813446
Ref: whatsnew/2 3 acks1813446
Ref: ee41813446
Node: Python 2 2 有什么新变化1813985
Ref: whatsnew/2 2 doc1814155
Ref: ee51814155
Ref: whatsnew/2 2 what-s-new-in-python-2-21814155
Ref: ee61814155
Node: 簡介1814844
Ref: whatsnew/2 2 introduction1814964
Ref: ee71814964
Ref: 簡介-Footnote-11815918
Ref: 簡介-Footnote-21815967
Node: PEPs 252 and 253 Type and Class Changes1816016
Ref: whatsnew/2 2 peps-252-and-253-type-and-class-changes1816162
Ref: ee81816162
Node: Old and New Classes1819590
Ref: whatsnew/2 2 old-and-new-classes1819705
Ref: eea1819705
Ref: Old and New Classes-Footnote-11822110
Node: Descriptors1822159
Ref: whatsnew/2 2 descriptors1822320
Ref: eeb1822320
Node: Multiple Inheritance The Diamond Rule1826180
Ref: whatsnew/2 2 multiple-inheritance-the-diamond-rule1826338
Ref: eec1826338
Ref: Multiple Inheritance The Diamond Rule-Footnote-11829223
Node: Attribute Access1829272
Ref: whatsnew/2 2 attribute-access1829432
Ref: eed1829432
Node: Related Links1833249
Ref: whatsnew/2 2 related-links1833363
Ref: ef01833363
Ref: whatsnew/2 2 sect-rellinks1833363
Ref: ee91833363
Ref: Related Links-Footnote-11834856
Ref: Related Links-Footnote-21834905
Ref: Related Links-Footnote-31834954
Ref: Related Links-Footnote-41835003
Ref: Related Links-Footnote-51835052
Node: PEP 234 Iterators1835101
Ref: whatsnew/2 2 pep-234-iterators1835269
Ref: ef11835269
Ref: PEP 234 Iterators-Footnote-11840156
Node: PEP 255 Simple Generators<2>1840205
Ref: whatsnew/2 2 pep-255-simple-generators1840369
Ref: ef41840369
Ref: PEP 255 Simple Generators<2>-Footnote-11846414
Ref: PEP 255 Simple Generators<2>-Footnote-21846463
Node: PEP 237 统一长整数和整数<2>1846512
Ref: whatsnew/2 2 pep-237-unifying-long-integers-and-integers1846697
Ref: ef51846697
Ref: PEP 237 统一长整数和整数<2>-Footnote-11848380
Node: PEP 238 Changing the Division Operator1848429
Ref: whatsnew/2 2 pep-238-changing-the-division-operator1848601
Ref: ef61848601
Ref: PEP 238 Changing the Division Operator-Footnote-11852238
Ref: PEP 238 Changing the Division Operator-Footnote-21852287
Ref: PEP 238 Changing the Division Operator-Footnote-31852336
Node: Unicode Changes1852385
Ref: whatsnew/2 2 unicode-changes1852543
Ref: ef81852543
Ref: Unicode Changes-Footnote-11855167
Ref: Unicode Changes-Footnote-21855216
Node: PEP 227 Nested Scopes1855265
Ref: whatsnew/2 2 pep-227-nested-scopes1855412
Ref: efa1855412
Ref: PEP 227 Nested Scopes-Footnote-11859744
Node: 新增和改进的模块<3>1859793
Ref: whatsnew/2 2 new-and-improved-modules1859954
Ref: efb1859954
Ref: 新增和改进的模块<3>-Footnote-11866564
Ref: 新增和改进的模块<3>-Footnote-21866613
Ref: 新增和改进的模块<3>-Footnote-31866662
Ref: 新增和改进的模块<3>-Footnote-41866711
Ref: 新增和改进的模块<3>-Footnote-51866760
Node: Interpreter Changes and Fixes1866808
Ref: whatsnew/2 2 interpreter-changes-and-fixes1866974
Ref: efc1866974
Node: Other Changes and Fixes<3>1871731
Ref: whatsnew/2 2 other-changes-and-fixes1871879
Ref: f0e1871879
Ref: Other Changes and Fixes<3>-Footnote-11878533
Node: 致谢<6>1878582
Ref: whatsnew/2 2 acknowledgements1878692
Ref: f111878692
Node: Python 2 1 有什么新变化1879211
Ref: whatsnew/2 1 doc1879381
Ref: f121879381
Ref: whatsnew/2 1 what-s-new-in-python-2-11879381
Ref: f131879381
Node: 簡介<2>1880356
Ref: whatsnew/2 1 introduction1880464
Ref: f141880464
Node: PEP 227 Nested Scopes<2>1881541
Ref: whatsnew/2 1 pep-227-nested-scopes1881687
Ref: f151881687
Ref: PEP 227 Nested Scopes<2>-Footnote-11886042
Ref: PEP 227 Nested Scopes<2>-Footnote-21886091
Ref: PEP 227 Nested Scopes<2>-Footnote-31886140
Node: PEP 236 __future__ Directives1886189
Ref: whatsnew/2 1 pep-236-future-directives1886350
Ref: f161886350
Ref: PEP 236 __future__ Directives-Footnote-11887577
Node: PEP 207 Rich Comparisons1887626
Ref: whatsnew/2 1 pep-207-rich-comparisons1887788
Ref: f171887788
Ref: PEP 207 Rich Comparisons-Footnote-11891185
Ref: PEP 207 Rich Comparisons-Footnote-21891234
Node: PEP 230 Warning Framework1891283
Ref: whatsnew/2 1 pep-230-warning-framework1891440
Ref: f191891440
Ref: PEP 230 Warning Framework-Footnote-11894714
Ref: PEP 230 Warning Framework-Footnote-21894763
Node: PEP 229 New Build System1894812
Ref: whatsnew/2 1 pep-229-new-build-system1894968
Ref: f1b1894968
Ref: PEP 229 New Build System-Footnote-11896882
Node: PEP 205 Weak References1896931
Ref: whatsnew/2 1 pep-205-weak-references1897089
Ref: f1c1897089
Ref: PEP 205 Weak References-Footnote-11900190
Node: PEP 232 Function Attributes1900239
Ref: whatsnew/2 1 pep-232-function-attributes1900428
Ref: f1d1900428
Ref: PEP 232 Function Attributes-Footnote-11901930
Node: PEP 235 Importing Modules on Case-Insensitive Platforms1901979
Ref: whatsnew/2 1 pep-235-importing-modules-on-case-insensitive-platforms1902177
Ref: f1e1902177
Node: PEP 217 Interactive Display Hook1903080
Ref: whatsnew/2 1 pep-217-interactive-display-hook1903277
Ref: f1f1903277
Ref: PEP 217 Interactive Display Hook-Footnote-11904196
Node: PEP 208 New Coercion Model1904245
Ref: whatsnew/2 1 pep-208-new-coercion-model1904422
Ref: f211904422
Ref: PEP 208 New Coercion Model-Footnote-11906043
Node: PEP 241 Metadata in Python Packages1906092
Ref: whatsnew/2 1 pep-241-metadata-in-python-packages1906264
Ref: f221906264
Ref: PEP 241 Metadata in Python Packages-Footnote-11908301
Ref: PEP 241 Metadata in Python Packages-Footnote-21908350
Ref: PEP 241 Metadata in Python Packages-Footnote-31908399
Ref: PEP 241 Metadata in Python Packages-Footnote-41908448
Node: 新增和改进的模块<4>1908497
Ref: whatsnew/2 1 new-and-improved-modules1908669
Ref: f231908669
Node: Other Changes and Fixes<4>1914493
Ref: whatsnew/2 1 other-changes-and-fixes1914639
Ref: f261914639
Node: 致谢<7>1920573
Ref: whatsnew/2 1 acknowledgements1920683
Ref: f271920683
Node: Python 2 0 有什么新变化1920904
Ref: whatsnew/2 0 doc1921072
Ref: f281921072
Ref: whatsnew/2 0 what-s-new-in-python-2-01921072
Ref: f291921072
Node: 簡介<3>1921685
Ref: whatsnew/2 0 introduction1921791
Ref: f2a1921791
Node: What About Python 1 6?1922661
Ref: whatsnew/2 0 what-about-python-1-61922791
Ref: f2b1922791
Node: 新开发流程1924032
Ref: whatsnew/2 0 new-development-process1924163
Ref: f2c1924163
Ref: 新开发流程-Footnote-11929274
Ref: 新开发流程-Footnote-21929323
Ref: 新开发流程-Footnote-31929372
Node: Unicode<2>1929421
Ref: whatsnew/2 0 unicode1929572
Ref: f2d1929572
Ref: Unicode<2>-Footnote-11935742
Node: 串列綜合運算（List Comprehension）1935791
Ref: whatsnew/2 0 list-comprehensions1935947
Ref: f2e1935947
Node: Augmented Assignment1939716
Ref: whatsnew/2 0 augmented-assignment1939880
Ref: f2f1939880
Node: 字符串的方法1941426
Ref: whatsnew/2 0 string-methods1941576
Ref: f321941576
Node: Garbage Collection of Cycles1943431
Ref: whatsnew/2 0 garbage-collection-of-cycles1943579
Ref: f331943579
Node: 其他核心变化1946918
Ref: whatsnew/2 0 other-core-changes1947065
Ref: f341947065
Node: Minor Language Changes1947344
Ref: whatsnew/2 0 minor-language-changes1947459
Ref: f351947459
Node: Changes to Built-in Functions1952538
Ref: whatsnew/2 0 changes-to-built-in-functions1952653
Ref: f3a1952653
Node: 移植 Python 2 01954935
Ref: whatsnew/2 0 porting-to-2-01955073
Ref: f3d1955073
Node: 扩展/嵌入更改1960396
Ref: whatsnew/2 0 extending-embedding-changes1960549
Ref: f3e1960549
Node: Distutils：使模块易于安装1964349
Ref: whatsnew/2 0 distutils-making-modules-easy-to-install1964495
Ref: f3f1964495
Node: XML 模块1967819
Ref: whatsnew/2 0 xml-modules1967958
Ref: f401967958
Node: SAX2 Support1968853
Ref: whatsnew/2 0 sax2-support1968932
Ref: f411968932
Node: DOM Support1970570
Ref: whatsnew/2 0 dom-support1970679
Ref: f421970679
Node: Relationship to PyXML1973507
Ref: whatsnew/2 0 relationship-to-pyxml1973595
Ref: f431973595
Node: 模块更改1974885
Ref: whatsnew/2 0 module-changes1975006
Ref: f441975006
Node: 新增模块<8>1977470
Ref: whatsnew/2 0 new-modules1977592
Ref: f451977592
Node: IDLE 改进1981582
Ref: whatsnew/2 0 idle-improvements1981716
Ref: f471981716
Node: 删除和弃用的模块1982825
Ref: whatsnew/2 0 deleted-and-deprecated-modules1982953
Ref: f481982953
Node: 致谢<8>1983685
Ref: whatsnew/2 0 acknowledgements1983793
Ref: f491983793
Ref: 致谢<8>-Footnote-11984291
Ref: 致谢<8>-Footnote-21984354
Node: Changelog（更動日誌）1984393
Ref: whatsnew/changelog doc1984523
Ref: f4a1984523
Ref: whatsnew/changelog changelog1984523
Ref: 1561984523
Ref: whatsnew/changelog id11984523
Ref: f4b1984523
Node: Python 下一版1988593
Ref: whatsnew/changelog python-next1988700
Ref: f4c1988700
Node: 核心与内置函数1988911
Ref: whatsnew/changelog core-and-builtins1988997
Ref: f4d1988997
Ref: 核心与内置函数-Footnote-11990651
Ref: 核心与内置函数-Footnote-21990694
Ref: 核心与内置函数-Footnote-31990737
Ref: 核心与内置函数-Footnote-41990780
Ref: 核心与内置函数-Footnote-51990823
Ref: 核心与内置函数-Footnote-61990866
Ref: 核心与内置函数-Footnote-71990909
Ref: 核心与内置函数-Footnote-81990952
Ref: 核心与内置函数-Footnote-91990995
Ref: 核心与内置函数-Footnote-101991044
Ref: 核心与内置函数-Footnote-111991088
Node: 库1991132
Ref: whatsnew/changelog library1991236
Ref: f4f1991236
Ref: 库-Footnote-11994857
Ref: 库-Footnote-21994900
Ref: 库-Footnote-31994943
Ref: 库-Footnote-41994986
Ref: 库-Footnote-51995029
Ref: 库-Footnote-61995072
Ref: 库-Footnote-71995115
Ref: 库-Footnote-81995158
Ref: 库-Footnote-91995201
Ref: 库-Footnote-101995244
Ref: 库-Footnote-111995288
Ref: 库-Footnote-121995332
Ref: 库-Footnote-131995376
Ref: 库-Footnote-141995420
Ref: 库-Footnote-151995464
Ref: 库-Footnote-161995508
Ref: 库-Footnote-171995552
Ref: 库-Footnote-181995596
Ref: 库-Footnote-191995640
Ref: 库-Footnote-201995684
Node: 文档<2>1995728
Ref: whatsnew/changelog documentation1995817
Ref: f541995817
Ref: 文档<2>-Footnote-11996611
Ref: 文档<2>-Footnote-21996654
Ref: 文档<2>-Footnote-31996697
Ref: 文档<2>-Footnote-41996740
Ref: 文档<2>-Footnote-51996783
Ref: 文档<2>-Footnote-61996826
Node: 测试1996869
Ref: whatsnew/changelog tests1996961
Ref: f581996961
Ref: 测试-Footnote-11997857
Ref: 测试-Footnote-21997900
Ref: 测试-Footnote-31997943
Ref: 测试-Footnote-41997986
Ref: 测试-Footnote-51998029
Ref: 测试-Footnote-61998072
Ref: 测试-Footnote-71998115
Ref: 测试-Footnote-81998158
Node: 构建1998201
Ref: whatsnew/changelog build1998291
Ref: f5a1998291
Ref: 构建-Footnote-11999549
Ref: 构建-Footnote-21999592
Ref: 构建-Footnote-31999635
Ref: 构建-Footnote-41999678
Ref: 构建-Footnote-51999721
Ref: 构建-Footnote-61999764
Ref: 构建-Footnote-71999807
Node: Windows1999850
Ref: whatsnew/changelog windows1999939
Ref: f5b1999939
Ref: Windows-Footnote-12000326
Node: macOS2000369
Ref: whatsnew/changelog macos2000465
Ref: f5c2000465
Ref: macOS-Footnote-12000782
Ref: macOS-Footnote-22000825
Node: 工具/示例2000868
Ref: whatsnew/changelog tools-demos2000962
Ref: f5d2000962
Ref: 工具/示例-Footnote-12001126
Node: C API2001169
Ref: whatsnew/changelog c-api2001249
Ref: f5e2001249
Ref: C API-Footnote-12001452
Node: Python 3 9 9 final2001495
Ref: whatsnew/changelog python-3-9-9-final2001629
Ref: f5f2001629
Node: 核心与内置函数<2>2001830
Ref: whatsnew/changelog id22001924
Ref: f602001924
Ref: 核心与内置函数<2>-Footnote-12002151
Node: 库<2>2002194
Ref: whatsnew/changelog id32002306
Ref: f612002306
Ref: 库<2>-Footnote-12002878
Ref: 库<2>-Footnote-22002921
Ref: 库<2>-Footnote-32002964
Node: 文档<3>2003007
Ref: whatsnew/changelog id42003105
Ref: f622003105
Ref: 文档<3>-Footnote-12003437
Ref: 文档<3>-Footnote-22003480
Node: Windows<2>2003523
Ref: whatsnew/changelog id52003606
Ref: f632003606
Ref: Windows<2>-Footnote-12003916
Ref: Windows<2>-Footnote-22003959
Node: Python 3 9 8 final2004002
Ref: whatsnew/changelog python-3-9-8-final2004138
Ref: f642004138
Node: 核心与内置函数<3>2004436
Ref: whatsnew/changelog id62004530
Ref: f652004530
Ref: 核心与内置函数<3>-Footnote-12006334
Ref: 核心与内置函数<3>-Footnote-22006377
Ref: 核心与内置函数<3>-Footnote-32006420
Ref: 核心与内置函数<3>-Footnote-42006463
Ref: 核心与内置函数<3>-Footnote-52006506
Ref: 核心与内置函数<3>-Footnote-62006549
Ref: 核心与内置函数<3>-Footnote-72006592
Ref: 核心与内置函数<3>-Footnote-82006635
Ref: 核心与内置函数<3>-Footnote-92006678
Ref: 核心与内置函数<3>-Footnote-102006721
Node: 库<3>2006765
Ref: whatsnew/changelog id72006877
Ref: f682006877
Ref: 库<3>-Footnote-12013507
Ref: 库<3>-Footnote-22013550
Ref: 库<3>-Footnote-32013593
Ref: 库<3>-Footnote-42013636
Ref: 库<3>-Footnote-52013679
Ref: 库<3>-Footnote-62013722
Ref: 库<3>-Footnote-72013765
Ref: 库<3>-Footnote-82013808
Ref: 库<3>-Footnote-92013851
Ref: 库<3>-Footnote-102013894
Ref: 库<3>-Footnote-112013938
Ref: 库<3>-Footnote-122013982
Ref: 库<3>-Footnote-132014026
Ref: 库<3>-Footnote-142014070
Ref: 库<3>-Footnote-152014114
Ref: 库<3>-Footnote-162014158
Ref: 库<3>-Footnote-172014202
Ref: 库<3>-Footnote-182014246
Ref: 库<3>-Footnote-192014290
Ref: 库<3>-Footnote-202014336
Ref: 库<3>-Footnote-212014380
Ref: 库<3>-Footnote-222014424
Ref: 库<3>-Footnote-232014468
Ref: 库<3>-Footnote-242014512
Ref: 库<3>-Footnote-252014556
Ref: 库<3>-Footnote-262014600
Ref: 库<3>-Footnote-272014644
Ref: 库<3>-Footnote-282014688
Ref: 库<3>-Footnote-292014732
Ref: 库<3>-Footnote-302014776
Ref: 库<3>-Footnote-312014820
Ref: 库<3>-Footnote-322014864
Ref: 库<3>-Footnote-332014908
Ref: 库<3>-Footnote-342014952
Ref: 库<3>-Footnote-352014996
Ref: 库<3>-Footnote-362015040
Node: 文档<4>2015084
Ref: whatsnew/changelog id82015181
Ref: f722015181
Ref: 文档<4>-Footnote-12016577
Ref: 文档<4>-Footnote-22016620
Ref: 文档<4>-Footnote-32016663
Ref: 文档<4>-Footnote-42016706
Ref: 文档<4>-Footnote-52016749
Ref: 文档<4>-Footnote-62016792
Ref: 文档<4>-Footnote-72016835
Ref: 文档<4>-Footnote-82016884
Ref: 文档<4>-Footnote-92016927
Ref: 文档<4>-Footnote-102016970
Node: 测试<2>2017014
Ref: whatsnew/changelog id92017114
Ref: f752017114
Ref: 测试<2>-Footnote-12018435
Ref: 测试<2>-Footnote-22018478
Ref: 测试<2>-Footnote-32018521
Ref: 测试<2>-Footnote-42018564
Ref: 测试<2>-Footnote-52018607
Ref: 测试<2>-Footnote-62018650
Ref: 测试<2>-Footnote-72018693
Ref: 测试<2>-Footnote-82018736
Ref: 测试<2>-Footnote-92018779
Ref: 测试<2>-Footnote-102018822
Node: 构建<2>2018866
Ref: whatsnew/changelog id102018967
Ref: f762018967
Ref: 构建<2>-Footnote-12019835
Ref: 构建<2>-Footnote-22019878
Ref: 构建<2>-Footnote-32019921
Ref: 构建<2>-Footnote-42019964
Ref: 构建<2>-Footnote-52020007
Node: Windows<3>2020050
Ref: whatsnew/changelog id112020150
Ref: f772020150
Ref: Windows<3>-Footnote-12020478
Node: macOS<2>2020521
Ref: whatsnew/changelog id122020619
Ref: f782020619
Ref: macOS<2>-Footnote-12020878
Node: IDLE<3>2020921
Ref: whatsnew/changelog idle2021017
Ref: f792021017
Ref: IDLE<3>-Footnote-12021238
Node: C API<2>2021281
Ref: whatsnew/changelog id132021360
Ref: f7a2021360
Ref: C API<2>-Footnote-12021661
Ref: C API<2>-Footnote-22021704
Node: Python 3 9 7 final2021747
Ref: whatsnew/changelog python-3-9-7-final2021887
Ref: f7b2021887
Node: 安全性2022163
Ref: whatsnew/changelog security2022260
Ref: f7c2022260
Ref: 安全性-Footnote-12023247
Ref: 安全性-Footnote-22023290
Ref: 安全性-Footnote-32023333
Ref: 安全性-Footnote-42023376
Node: 核心与内置函数<4>2023419
Ref: whatsnew/changelog id142023531
Ref: f7e2023531
Ref: 核心与内置函数<4>-Footnote-12025932
Ref: 核心与内置函数<4>-Footnote-22025975
Ref: 核心与内置函数<4>-Footnote-32026018
Ref: 核心与内置函数<4>-Footnote-42026061
Ref: 核心与内置函数<4>-Footnote-52026104
Ref: 核心与内置函数<4>-Footnote-62026147
Ref: 核心与内置函数<4>-Footnote-72026190
Ref: 核心与内置函数<4>-Footnote-82026233
Ref: 核心与内置函数<4>-Footnote-92026276
Ref: 核心与内置函数<4>-Footnote-102026319
Ref: 核心与内置函数<4>-Footnote-112026363
Ref: 核心与内置函数<4>-Footnote-122026407
Ref: 核心与内置函数<4>-Footnote-132026451
Ref: 核心与内置函数<4>-Footnote-142026495
Ref: 核心与内置函数<4>-Footnote-152026539
Ref: 核心与内置函数<4>-Footnote-162026583
Node: 库<4>2026627
Ref: whatsnew/changelog id152026739
Ref: f7f2026739
Ref: 库<4>-Footnote-12034066
Ref: 库<4>-Footnote-22034109
Ref: 库<4>-Footnote-32034152
Ref: 库<4>-Footnote-42034195
Ref: 库<4>-Footnote-52034238
Ref: 库<4>-Footnote-62034281
Ref: 库<4>-Footnote-72034324
Ref: 库<4>-Footnote-82034367
Ref: 库<4>-Footnote-92034410
Ref: 库<4>-Footnote-102034453
Ref: 库<4>-Footnote-112034497
Ref: 库<4>-Footnote-122034541
Ref: 库<4>-Footnote-132034585
Ref: 库<4>-Footnote-142034629
Ref: 库<4>-Footnote-152034673
Ref: 库<4>-Footnote-162034717
Ref: 库<4>-Footnote-172034761
Ref: 库<4>-Footnote-182034805
Ref: 库<4>-Footnote-192034849
Ref: 库<4>-Footnote-202034893
Ref: 库<4>-Footnote-212034937
Ref: 库<4>-Footnote-222034981
Ref: 库<4>-Footnote-232035025
Ref: 库<4>-Footnote-242035069
Ref: 库<4>-Footnote-252035113
Ref: 库<4>-Footnote-262035157
Ref: 库<4>-Footnote-272035201
Ref: 库<4>-Footnote-282035245
Ref: 库<4>-Footnote-292035289
Ref: 库<4>-Footnote-302035333
Ref: 库<4>-Footnote-312035377
Ref: 库<4>-Footnote-322035421
Ref: 库<4>-Footnote-332035465
Ref: 库<4>-Footnote-342035509
Ref: 库<4>-Footnote-352035553
Ref: 库<4>-Footnote-362035597
Ref: 库<4>-Footnote-372035641
Ref: 库<4>-Footnote-382035685
Ref: 库<4>-Footnote-392035729
Node: 文档<5>2035773
Ref: whatsnew/changelog id162035870
Ref: f842035870
Ref: 文档<5>-Footnote-12038208
Ref: 文档<5>-Footnote-22038251
Ref: 文档<5>-Footnote-32038294
Ref: 文档<5>-Footnote-42038337
Ref: 文档<5>-Footnote-52038380
Ref: 文档<5>-Footnote-62038423
Ref: 文档<5>-Footnote-72038466
Ref: 文档<5>-Footnote-82038509
Ref: 文档<5>-Footnote-92038552
Ref: 文档<5>-Footnote-102038595
Ref: 文档<5>-Footnote-112038639
Ref: 文档<5>-Footnote-122038683
Ref: 文档<5>-Footnote-132038727
Ref: 文档<5>-Footnote-142038771
Node: 测试<3>2038815
Ref: whatsnew/changelog id172038915
Ref: f882038915
Ref: 测试<3>-Footnote-12040123
Ref: 测试<3>-Footnote-22040166
Ref: 测试<3>-Footnote-32040209
Ref: 测试<3>-Footnote-42040252
Ref: 测试<3>-Footnote-52040295
Ref: 测试<3>-Footnote-62040338
Ref: 测试<3>-Footnote-72040381
Ref: 测试<3>-Footnote-82040424
Node: 构建<3>2040467
Ref: whatsnew/changelog id182040568
Ref: f892040568
Ref: 构建<3>-Footnote-12040818
Ref: 构建<3>-Footnote-22040861
Node: Windows<4>2040904
Ref: whatsnew/changelog id192041004
Ref: f8a2041004
Ref: Windows<4>-Footnote-12041424
Ref: Windows<4>-Footnote-22041467
Ref: Windows<4>-Footnote-32041510
Node: macOS<3>2041553
Ref: whatsnew/changelog id202041635
Ref: f8b2041635
Ref: macOS<3>-Footnote-12042138
Ref: macOS<3>-Footnote-22042181
Node: Python 3 9 6 最终版2042224
Ref: whatsnew/changelog python-3-9-6-final2042368
Ref: f8c2042368
Node: 安全性<2>2042733
Ref: whatsnew/changelog id212042837
Ref: f8d2042837
Ref: 安全性<2>-Footnote-12043097
Node: 核心与内置函数<5>2043140
Ref: whatsnew/changelog id222043259
Ref: f8e2043259
Ref: 核心与内置函数<5>-Footnote-12044374
Ref: 核心与内置函数<5>-Footnote-22044417
Ref: 核心与内置函数<5>-Footnote-32044460
Ref: 核心与内置函数<5>-Footnote-42044503
Ref: 核心与内置函数<5>-Footnote-52044546
Ref: 核心与内置函数<5>-Footnote-62044589
Ref: 核心与内置函数<5>-Footnote-72044632
Node: 库<5>2044675
Ref: whatsnew/changelog id232044791
Ref: f8f2044791
Ref: 库<5>-Footnote-12048702
Ref: 库<5>-Footnote-22048745
Ref: 库<5>-Footnote-32048788
Ref: 库<5>-Footnote-42048831
Ref: 库<5>-Footnote-52048874
Ref: 库<5>-Footnote-62048917
Ref: 库<5>-Footnote-72048960
Ref: 库<5>-Footnote-82049003
Ref: 库<5>-Footnote-92049046
Ref: 库<5>-Footnote-102049089
Ref: 库<5>-Footnote-112049133
Ref: 库<5>-Footnote-122049177
Ref: 库<5>-Footnote-132049221
Ref: 库<5>-Footnote-142049265
Ref: 库<5>-Footnote-152049309
Ref: 库<5>-Footnote-162049353
Ref: 库<5>-Footnote-172049397
Ref: 库<5>-Footnote-182049441
Ref: 库<5>-Footnote-192049485
Ref: 库<5>-Footnote-202049529
Ref: 库<5>-Footnote-212049573
Ref: 库<5>-Footnote-222049617
Ref: 库<5>-Footnote-232049661
Node: 文档<6>2049705
Ref: whatsnew/changelog id242049806
Ref: f922049806
Ref: 文档<6>-Footnote-12051338
Ref: 文档<6>-Footnote-22051381
Ref: 文档<6>-Footnote-32051424
Ref: 文档<6>-Footnote-42051467
Ref: 文档<6>-Footnote-52051510
Ref: 文档<6>-Footnote-62051553
Ref: 文档<6>-Footnote-72051596
Ref: 文档<6>-Footnote-82051639
Ref: 文档<6>-Footnote-92051682
Ref: 文档<6>-Footnote-102051725
Node: 测试<4>2051769
Ref: whatsnew/changelog id252051873
Ref: f932051873
Ref: 测试<4>-Footnote-12052401
Ref: 测试<4>-Footnote-22052444
Node: 构建<4>2052487
Ref: whatsnew/changelog id262052592
Ref: f952052592
Ref: 构建<4>-Footnote-12052777
Node: Windows<5>2052820
Ref: whatsnew/changelog id272052924
Ref: f962052924
Ref: Windows<5>-Footnote-12053178
Node: macOS<4>2053221
Ref: whatsnew/changelog id282053323
Ref: f982053323
Ref: macOS<4>-Footnote-12053665
Ref: macOS<4>-Footnote-22053708
Node: IDLE<4>2053751
Ref: whatsnew/changelog id292053859
Ref: f992053859
Ref: IDLE<4>-Footnote-12054718
Ref: IDLE<4>-Footnote-22054761
Ref: IDLE<4>-Footnote-32054804
Ref: IDLE<4>-Footnote-42054847
Ref: IDLE<4>-Footnote-52054890
Node: 工具/示例<2>2054933
Ref: whatsnew/changelog id302055041
Ref: f9a2055041
Ref: 工具/示例<2>-Footnote-12055259
Node: C API<3>2055302
Ref: whatsnew/changelog id312055394
Ref: f9b2055394
Ref: C API<3>-Footnote-12055888
Ref: C API<3>-Footnote-22055931
Node: Python 3 9 5 最终版2055974
Ref: whatsnew/changelog python-3-9-5-final2056118
Ref: f9f2056118
Node: 安全性<3>2056408
Ref: whatsnew/changelog id322056512
Ref: fa02056512
Ref: 安全性<3>-Footnote-12058346
Ref: 安全性<3>-Footnote-22058389
Ref: 安全性<3>-Footnote-32058432
Ref: 安全性<3>-Footnote-42058475
Ref: 安全性<3>-Footnote-52058518
Ref: 安全性<3>-Footnote-62058561
Node: 核心与内置函数<6>2058604
Ref: whatsnew/changelog id332058723
Ref: fa32058723
Ref: 核心与内置函数<6>-Footnote-12059195
Ref: 核心与内置函数<6>-Footnote-22059238
Node: 库<6>2059281
Ref: whatsnew/changelog id342059397
Ref: fa42059397
Ref: 库<6>-Footnote-12062414
Ref: 库<6>-Footnote-22062457
Ref: 库<6>-Footnote-32062500
Ref: 库<6>-Footnote-42062543
Ref: 库<6>-Footnote-52062586
Ref: 库<6>-Footnote-62062629
Ref: 库<6>-Footnote-72062672
Ref: 库<6>-Footnote-82062715
Ref: 库<6>-Footnote-92062758
Ref: 库<6>-Footnote-102062801
Ref: 库<6>-Footnote-112062845
Ref: 库<6>-Footnote-122062889
Ref: 库<6>-Footnote-132062933
Ref: 库<6>-Footnote-142062977
Ref: 库<6>-Footnote-152063021
Ref: 库<6>-Footnote-162063065
Ref: 库<6>-Footnote-172063109
Ref: 库<6>-Footnote-182063153
Ref: 库<6>-Footnote-192063197
Node: 文档<7>2063241
Ref: whatsnew/changelog id352063342
Ref: faa2063342
Ref: 文档<7>-Footnote-12064004
Ref: 文档<7>-Footnote-22064047
Ref: 文档<7>-Footnote-32064090
Ref: 文档<7>-Footnote-42064133
Node: 测试<5>2064176
Ref: whatsnew/changelog id362064281
Ref: fab2064281
Ref: 测试<5>-Footnote-12065025
Ref: 测试<5>-Footnote-22065068
Ref: 测试<5>-Footnote-32065111
Ref: 测试<5>-Footnote-42065154
Node: Windows<6>2065197
Ref: whatsnew/changelog id372065301
Ref: fac2065301
Ref: Windows<6>-Footnote-12066361
Ref: Windows<6>-Footnote-22066404
Ref: Windows<6>-Footnote-32066447
Ref: Windows<6>-Footnote-42066490
Ref: Windows<6>-Footnote-52066533
Ref: Windows<6>-Footnote-62066576
Node: macOS<5>2066619
Ref: whatsnew/changelog id382066721
Ref: faf2066721
Ref: macOS<5>-Footnote-12067672
Ref: macOS<5>-Footnote-22067715
Ref: macOS<5>-Footnote-32067758
Node: IDLE<5>2067801
Ref: whatsnew/changelog id392067884
Ref: fb02067884
Ref: IDLE<5>-Footnote-12068066
Node: Python 3 9 4 final2068109
Ref: whatsnew/changelog python-3-9-4-final2068249
Ref: fb12068249
Node: 核心与内置函数<7>2068406
Ref: whatsnew/changelog id402068500
Ref: fb22068500
Ref: 核心与内置函数<7>-Footnote-12068887
Node: 库<7>2068930
Ref: whatsnew/changelog id412069024
Ref: fb32069024
Ref: 库<7>-Footnote-12069274
Node: Python 3 9 3 final2069317
Ref: whatsnew/changelog python-3-9-3-final2069453
Ref: fb42069453
Node: 安全性<4>2069736
Ref: whatsnew/changelog id422069836
Ref: fb52069836
Ref: 安全性<4>-Footnote-12070914
Ref: 安全性<4>-Footnote-22070957
Ref: 安全性<4>-Footnote-32071000
Node: 核心与内置函数<8>2071043
Ref: whatsnew/changelog id432071158
Ref: fb82071158
Ref: 核心与内置函数<8>-Footnote-12072336
Ref: 核心与内置函数<8>-Footnote-22072379
Ref: 核心与内置函数<8>-Footnote-32072422
Ref: 核心与内置函数<8>-Footnote-42072465
Ref: 核心与内置函数<8>-Footnote-52072508
Ref: 核心与内置函数<8>-Footnote-62072551
Node: 库<8>2072594
Ref: whatsnew/changelog id442072706
Ref: fb92072706
Ref: 库<8>-Footnote-12074592
Ref: 库<8>-Footnote-22074635
Ref: 库<8>-Footnote-32074678
Ref: 库<8>-Footnote-42074721
Ref: 库<8>-Footnote-52074764
Ref: 库<8>-Footnote-62074807
Ref: 库<8>-Footnote-72074850
Ref: 库<8>-Footnote-82074893
Ref: 库<8>-Footnote-92074936
Ref: 库<8>-Footnote-102074979
Ref: 库<8>-Footnote-112075023
Ref: 库<8>-Footnote-122075067
Node: 文档<8>2075111
Ref: whatsnew/changelog id452075208
Ref: fbb2075208
Ref: 文档<8>-Footnote-12075933
Ref: 文档<8>-Footnote-22075976
Ref: 文档<8>-Footnote-32076019
Ref: 文档<8>-Footnote-42076062
Ref: 文档<8>-Footnote-52076105
Node: 测试<6>2076154
Ref: whatsnew/changelog id462076254
Ref: fbc2076254
Ref: 测试<6>-Footnote-12076678
Ref: 测试<6>-Footnote-22076721
Ref: 测试<6>-Footnote-32076764
Node: 构建<5>2076807
Ref: whatsnew/changelog id472076906
Ref: fbd2076906
Ref: 构建<5>-Footnote-12077172
Ref: 构建<5>-Footnote-22077215
Node: macOS<6>2077258
Ref: whatsnew/changelog id482077355
Ref: fbe2077355
Ref: macOS<6>-Footnote-12077494
Node: IDLE<6>2077537
Ref: whatsnew/changelog id492077616
Ref: fbf2077616
Ref: IDLE<6>-Footnote-12078058
Ref: IDLE<6>-Footnote-22078101
Node: Python 3 9 2 final2078144
Ref: whatsnew/changelog python-3-9-2-final2078292
Ref: fc02078292
Node: Windows<7>2078406
Ref: whatsnew/changelog id502078471
Ref: fc12078471
Ref: Windows<7>-Footnote-12078621
Node: Python 3 9 2 发布候选版 12078664
Ref: whatsnew/changelog python-3-9-2-release-candidate-12078812
Ref: fc22078812
Node: 安全性<5>2079193
Ref: whatsnew/changelog id512079305
Ref: fc32079305
Ref: 安全性<5>-Footnote-12079695
Ref: 安全性<5>-Footnote-22079738
Node: 核心与内置函数<9>2079781
Ref: whatsnew/changelog id522079908
Ref: fc62079908
Ref: 核心与内置函数<9>-Footnote-12082642
Ref: 核心与内置函数<9>-Footnote-22082685
Ref: 核心与内置函数<9>-Footnote-32082728
Ref: 核心与内置函数<9>-Footnote-42082771
Ref: 核心与内置函数<9>-Footnote-52082814
Ref: 核心与内置函数<9>-Footnote-62082857
Ref: 核心与内置函数<9>-Footnote-72082900
Node: 库<9>2082949
Ref: whatsnew/changelog id532083073
Ref: fca2083073
Ref: 库<9>-Footnote-12088461
Ref: 库<9>-Footnote-22088504
Ref: 库<9>-Footnote-32088547
Ref: 库<9>-Footnote-42088590
Ref: 库<9>-Footnote-52088633
Ref: 库<9>-Footnote-62088676
Ref: 库<9>-Footnote-72088719
Ref: 库<9>-Footnote-82088762
Ref: 库<9>-Footnote-92088805
Ref: 库<9>-Footnote-102088848
Ref: 库<9>-Footnote-112088892
Ref: 库<9>-Footnote-122088936
Ref: 库<9>-Footnote-132088980
Ref: 库<9>-Footnote-142089024
Ref: 库<9>-Footnote-152089068
Ref: 库<9>-Footnote-162089112
Ref: 库<9>-Footnote-172089156
Ref: 库<9>-Footnote-182089200
Ref: 库<9>-Footnote-192089244
Ref: 库<9>-Footnote-202089288
Ref: 库<9>-Footnote-212089332
Ref: 库<9>-Footnote-222089376
Ref: 库<9>-Footnote-232089420
Ref: 库<9>-Footnote-242089464
Ref: 库<9>-Footnote-252089508
Ref: 库<9>-Footnote-262089552
Ref: 库<9>-Footnote-272089596
Ref: 库<9>-Footnote-282089640
Ref: 库<9>-Footnote-292089684
Ref: 库<9>-Footnote-302089728
Ref: 库<9>-Footnote-312089772
Ref: 库<9>-Footnote-322089816
Ref: 库<9>-Footnote-332089860
Ref: 库<9>-Footnote-342089904
Ref: 库<9>-Footnote-352089948
Ref: 库<9>-Footnote-362089992
Ref: 库<9>-Footnote-372090036
Ref: 库<9>-Footnote-382090080
Ref: 库<9>-Footnote-392090124
Node: 文档<9>2090168
Ref: whatsnew/changelog id542090277
Ref: fcd2090277
Ref: 文档<9>-Footnote-12090692
Ref: 文档<9>-Footnote-22090735
Ref: 文档<9>-Footnote-32090778
Node: 测试<7>2090821
Ref: whatsnew/changelog id552090933
Ref: fcf2090933
Ref: 测试<7>-Footnote-12091232
Ref: 测试<7>-Footnote-22091275
Node: 构建<6>2091318
Ref: whatsnew/changelog id562091431
Ref: fd02091431
Ref: 构建<6>-Footnote-12092214
Ref: 构建<6>-Footnote-22092257
Ref: 构建<6>-Footnote-32092300
Ref: 构建<6>-Footnote-42092343
Ref: 构建<6>-Footnote-52092386
Node: Windows<8>2092429
Ref: whatsnew/changelog id572092541
Ref: fd12092541
Ref: Windows<8>-Footnote-12092754
Ref: Windows<8>-Footnote-22092797
Node: macOS<7>2092840
Ref: whatsnew/changelog id582092950
Ref: fd22092950
Ref: macOS<7>-Footnote-12093450
Ref: macOS<7>-Footnote-22093493
Ref: macOS<7>-Footnote-32093536
Ref: macOS<7>-Footnote-42093579
Node: IDLE<7>2093622
Ref: whatsnew/changelog id592093738
Ref: fd32093738
Ref: IDLE<7>-Footnote-12094300
Ref: IDLE<7>-Footnote-22094343
Ref: IDLE<7>-Footnote-32094386
Ref: IDLE<7>-Footnote-42094429
Node: 工具/示例<3>2094472
Ref: whatsnew/changelog id602094588
Ref: fd42094588
Ref: 工具/示例<3>-Footnote-12094914
Ref: 工具/示例<3>-Footnote-22094957
Node: C API<4>2095000
Ref: whatsnew/changelog id612095100
Ref: fd52095100
Ref: C API<4>-Footnote-12095683
Ref: C API<4>-Footnote-22095726
Ref: C API<4>-Footnote-32095769
Node: Python 3 9 1 final2095812
Ref: whatsnew/changelog python-3-9-1-final2095974
Ref: fd72095974
Node: 核心与内置函数<10>2096192
Ref: whatsnew/changelog id622096288
Ref: fd82096288
Ref: 核心与内置函数<10>-Footnote-12096718
Node: 库<10>2096761
Ref: whatsnew/changelog id632096875
Ref: fd92096875
Ref: 库<10>-Footnote-12098585
Ref: 库<10>-Footnote-22098627
Ref: 库<10>-Footnote-32098670
Ref: 库<10>-Footnote-42098713
Ref: 库<10>-Footnote-52098756
Ref: 库<10>-Footnote-62098799
Ref: 库<10>-Footnote-72098842
Ref: 库<10>-Footnote-82098885
Node: 测试<8>2098928
Ref: whatsnew/changelog id642099025
Ref: fdc2099025
Ref: 测试<8>-Footnote-12099444
Ref: 测试<8>-Footnote-22099487
Node: macOS<8>2099530
Ref: whatsnew/changelog id652099627
Ref: fdd2099627
Ref: macOS<8>-Footnote-12099974
Ref: macOS<8>-Footnote-22100017
Node: IDLE<8>2100060
Ref: whatsnew/changelog id662100139
Ref: fde2100139
Ref: IDLE<8>-Footnote-12100391
Node: Python 3 9 1 release candidate 12100434
Ref: whatsnew/changelog python-3-9-1-release-candidate-12100584
Ref: fdf2100584
Node: 安全性<6>2100942
Ref: whatsnew/changelog id672101057
Ref: fe02101057
Ref: 安全性<6>-Footnote-12101705
Ref: 安全性<6>-Footnote-22101748
Ref: 安全性<6>-Footnote-32101791
Node: 核心与内置函数<11>2101834
Ref: whatsnew/changelog id682101965
Ref: fe12101965
Ref: 核心与内置函数<11>-Footnote-12105389
Ref: 核心与内置函数<11>-Footnote-22105432
Ref: 核心与内置函数<11>-Footnote-32105475
Ref: 核心与内置函数<11>-Footnote-42105518
Ref: 核心与内置函数<11>-Footnote-52105561
Ref: 核心与内置函数<11>-Footnote-62105604
Ref: 核心与内置函数<11>-Footnote-72105647
Ref: 核心与内置函数<11>-Footnote-82105690
Ref: 核心与内置函数<11>-Footnote-92105733
Ref: 核心与内置函数<11>-Footnote-102105776
Ref: 核心与内置函数<11>-Footnote-112105820
Ref: 核心与内置函数<11>-Footnote-122105864
Ref: 核心与内置函数<11>-Footnote-132105908
Ref: 核心与内置函数<11>-Footnote-142105952
Ref: 核心与内置函数<11>-Footnote-152105996
Ref: 核心与内置函数<11>-Footnote-162106040
Ref: 核心与内置函数<11>-Footnote-172106084
Ref: 核心与内置函数<11>-Footnote-182106128
Node: 库<11>2106172
Ref: whatsnew/changelog id692106301
Ref: fe32106301
Ref: 库<11>-Footnote-12111270
Ref: 库<11>-Footnote-22111313
Ref: 库<11>-Footnote-32111356
Ref: 库<11>-Footnote-42111399
Ref: 库<11>-Footnote-52111442
Ref: 库<11>-Footnote-62111485
Ref: 库<11>-Footnote-72111528
Ref: 库<11>-Footnote-82111571
Ref: 库<11>-Footnote-92111614
Ref: 库<11>-Footnote-102111657
Ref: 库<11>-Footnote-112111701
Ref: 库<11>-Footnote-122111745
Ref: 库<11>-Footnote-132111789
Ref: 库<11>-Footnote-142111833
Ref: 库<11>-Footnote-152111877
Ref: 库<11>-Footnote-162111921
Ref: 库<11>-Footnote-172111965
Ref: 库<11>-Footnote-182112009
Ref: 库<11>-Footnote-192112053
Ref: 库<11>-Footnote-202112097
Ref: 库<11>-Footnote-212112141
Ref: 库<11>-Footnote-222112185
Ref: 库<11>-Footnote-232112229
Ref: 库<11>-Footnote-242112273
Ref: 库<11>-Footnote-252112317
Ref: 库<11>-Footnote-262112361
Ref: 库<11>-Footnote-272112405
Ref: 库<11>-Footnote-282112449
Ref: 库<11>-Footnote-292112493
Ref: 库<11>-Footnote-302112537
Ref: 库<11>-Footnote-312112581
Node: 文档<10>2112625
Ref: whatsnew/changelog id702112738
Ref: fe72112738
Ref: 文档<10>-Footnote-12113957
Ref: 文档<10>-Footnote-22114000
Ref: 文档<10>-Footnote-32114043
Ref: 文档<10>-Footnote-42114086
Ref: 文档<10>-Footnote-52114129
Ref: 文档<10>-Footnote-62114172
Ref: 文档<10>-Footnote-72114215
Ref: 文档<10>-Footnote-82114258
Ref: 文档<10>-Footnote-92114301
Ref: 文档<10>-Footnote-102114344
Node: 测试<9>2114388
Ref: whatsnew/changelog id712114503
Ref: feb2114503
Ref: 测试<9>-Footnote-12115600
Ref: 测试<9>-Footnote-22115643
Ref: 测试<9>-Footnote-32115686
Ref: 测试<9>-Footnote-42115729
Ref: 测试<9>-Footnote-52115772
Ref: 测试<9>-Footnote-62115815
Ref: 测试<9>-Footnote-72115858
Ref: 测试<9>-Footnote-82115901
Node: 构建<7>2115944
Ref: whatsnew/changelog id722116059
Ref: fec2116059
Ref: 构建<7>-Footnote-12116930
Ref: 构建<7>-Footnote-22116973
Ref: 构建<7>-Footnote-32117016
Ref: 构建<7>-Footnote-42117059
Node: Windows<9>2117102
Ref: whatsnew/changelog id732117216
Ref: fed2117216
Ref: Windows<9>-Footnote-12117723
Ref: Windows<9>-Footnote-22117766
Ref: Windows<9>-Footnote-32117809
Ref: Windows<9>-Footnote-42117852
Ref: Windows<9>-Footnote-52117895
Node: macOS<9>2117938
Ref: whatsnew/changelog id742118050
Ref: fee2118050
Ref: macOS<9>-Footnote-12118977
Ref: macOS<9>-Footnote-22119020
Ref: macOS<9>-Footnote-32119063
Ref: macOS<9>-Footnote-42119106
Ref: macOS<9>-Footnote-52119149
Node: IDLE<9>2119192
Ref: whatsnew/changelog id752119302
Ref: fef2119302
Ref: IDLE<9>-Footnote-12120299
Ref: IDLE<9>-Footnote-22120342
Ref: IDLE<9>-Footnote-32120385
Ref: IDLE<9>-Footnote-42120428
Ref: IDLE<9>-Footnote-52120471
Ref: IDLE<9>-Footnote-62120514
Ref: IDLE<9>-Footnote-72120557
Ref: IDLE<9>-Footnote-82120600
Node: C API<5>2120643
Ref: whatsnew/changelog id762120736
Ref: ff02120736
Ref: C API<5>-Footnote-12121135
Ref: C API<5>-Footnote-22121178
Node: Python 3 9 0 final2121221
Ref: whatsnew/changelog python-3-9-0-final2121385
Ref: ff12121385
Node: 库<12>2121537
Ref: whatsnew/changelog id772121618
Ref: ff22121618
Ref: 库<12>-Footnote-12122253
Ref: 库<12>-Footnote-22122296
Ref: 库<12>-Footnote-32122339
Ref: 库<12>-Footnote-42122382
Node: 测试<10>2122425
Ref: whatsnew/changelog id782122524
Ref: ff42122524
Ref: 测试<10>-Footnote-12122664
Node: 构建<8>2122707
Ref: whatsnew/changelog id792122790
Ref: ff52122790
Ref: 构建<8>-Footnote-12123016
Node: Python 3 9 0 release candidate 22123059
Ref: whatsnew/changelog python-3-9-0-release-candidate-22123221
Ref: ff62123221
Node: 核心与内置函数<12>2123518
Ref: whatsnew/changelog id802123628
Ref: ff72123628
Ref: 核心与内置函数<12>-Footnote-12125210
Ref: 核心与内置函数<12>-Footnote-22125253
Ref: 核心与内置函数<12>-Footnote-32125296
Ref: 核心与内置函数<12>-Footnote-42125339
Ref: 核心与内置函数<12>-Footnote-52125382
Ref: 核心与内置函数<12>-Footnote-62125425
Ref: 核心与内置函数<12>-Footnote-72125468
Ref: 核心与内置函数<12>-Footnote-82125511
Ref: 核心与内置函数<12>-Footnote-92125554
Node: 库<13>2125597
Ref: whatsnew/changelog id812125726
Ref: ff92125726
Ref: 库<13>-Footnote-12128197
Ref: 库<13>-Footnote-22128240
Ref: 库<13>-Footnote-32128283
Ref: 库<13>-Footnote-42128326
Ref: 库<13>-Footnote-52128369
Ref: 库<13>-Footnote-62128412
Ref: 库<13>-Footnote-72128455
Ref: 库<13>-Footnote-82128498
Ref: 库<13>-Footnote-92128541
Ref: 库<13>-Footnote-102128584
Ref: 库<13>-Footnote-112128628
Ref: 库<13>-Footnote-122128672
Ref: 库<13>-Footnote-132128716
Ref: 库<13>-Footnote-142128760
Ref: 库<13>-Footnote-152128804
Ref: 库<13>-Footnote-162128848
Ref: 库<13>-Footnote-172128892
Ref: 库<13>-Footnote-182128936
Node: 文档<11>2128980
Ref: whatsnew/changelog id822129094
Ref: ffa2129094
Ref: 文档<11>-Footnote-12129941
Ref: 文档<11>-Footnote-22129984
Ref: 文档<11>-Footnote-32130027
Ref: 文档<11>-Footnote-42130070
Ref: 文档<11>-Footnote-52130113
Node: 测试<11>2130156
Ref: whatsnew/changelog id832130272
Ref: ffc2130272
Ref: 测试<11>-Footnote-12130415
Node: 构建<9>2130458
Ref: whatsnew/changelog id842130575
Ref: ffd2130575
Ref: 构建<9>-Footnote-12130807
Node: Windows<10>2130850
Ref: whatsnew/changelog id852130965
Ref: ffe2130965
Ref: Windows<10>-Footnote-12131177
Node: C API<6>2131220
Ref: whatsnew/changelog id862131317
Ref: fff2131317
Ref: C API<6>-Footnote-12131511
Node: Python 3 9 0 发布候选版 12131554
Ref: whatsnew/changelog python-3-9-0-release-candidate-12131717
Ref: 10002131717
Node: 核心与内置函数<13>2131961
Ref: whatsnew/changelog id872132069
Ref: 10012132069
Ref: 核心与内置函数<13>-Footnote-12132251
Node: 库<14>2132294
Ref: whatsnew/changelog id882132421
Ref: 10022132421
Ref: 库<14>-Footnote-12133634
Ref: 库<14>-Footnote-22133677
Ref: 库<14>-Footnote-32133720
Ref: 库<14>-Footnote-42133763
Ref: 库<14>-Footnote-52133806
Ref: 库<14>-Footnote-62133849
Ref: 库<14>-Footnote-72133892
Ref: 库<14>-Footnote-82133935
Ref: 库<14>-Footnote-92133978
Ref: 库<14>-Footnote-102134021
Ref: 库<14>-Footnote-112134065
Node: 文档<12>2134109
Ref: whatsnew/changelog id892134222
Ref: 10042134222
Ref: 文档<12>-Footnote-12134513
Ref: 文档<12>-Footnote-22134556
Node: Windows<11>2134599
Ref: whatsnew/changelog id902134713
Ref: 10052134713
Ref: Windows<11>-Footnote-12135156
Ref: Windows<11>-Footnote-22135199
Ref: Windows<11>-Footnote-32135242
Ref: Windows<11>-Footnote-42135285
Node: IDLE<10>2135328
Ref: whatsnew/changelog id912135423
Ref: 10062135423
Ref: IDLE<10>-Footnote-12135772
Ref: IDLE<10>-Footnote-22135815
Node: Python 3 9 0 beta 52135858
Ref: whatsnew/changelog python-3-9-0-beta-52136008
Ref: 10072136008
Node: 安全性<7>2136277
Ref: whatsnew/changelog id922136379
Ref: 10082136379
Ref: 安全性<7>-Footnote-12136931
Ref: 安全性<7>-Footnote-22136974
Ref: 安全性<7>-Footnote-32137017
Ref: 安全性<7>-Footnote-42137060
Ref: 安全性<7>-Footnote-52137103
Node: 核心与内置函数<14>2137146
Ref: whatsnew/changelog id932137264
Ref: 10092137264
Ref: 核心与内置函数<14>-Footnote-12138609
Ref: 核心与内置函数<14>-Footnote-22138652
Ref: 核心与内置函数<14>-Footnote-32138695
Ref: 核心与内置函数<14>-Footnote-42138738
Ref: 核心与内置函数<14>-Footnote-52138781
Ref: 核心与内置函数<14>-Footnote-62138824
Ref: 核心与内置函数<14>-Footnote-72138867
Node: 库<15>2138910
Ref: whatsnew/changelog id942139026
Ref: 100a2139026
Ref: 库<15>-Footnote-12139931
Ref: 库<15>-Footnote-22139974
Ref: 库<15>-Footnote-32140017
Ref: 库<15>-Footnote-42140060
Ref: 库<15>-Footnote-52140103
Ref: 库<15>-Footnote-62140146
Ref: 库<15>-Footnote-72140189
Node: 文档<13>2140232
Ref: whatsnew/changelog id952140332
Ref: 100c2140332
Ref: 文档<13>-Footnote-12140513
Node: macOS<10>2140556
Ref: whatsnew/changelog id962140657
Ref: 100d2140657
Ref: macOS<10>-Footnote-12140791
Node: IDLE<11>2140834
Ref: whatsnew/changelog id972140933
Ref: 100e2140933
Ref: IDLE<11>-Footnote-12141217
Ref: IDLE<11>-Footnote-22141260
Node: C API<7>2141303
Ref: whatsnew/changelog id982141384
Ref: 100f2141384
Ref: C API<7>-Footnote-12141736
Node: Python 3 9 0 beta 42141779
Ref: whatsnew/changelog python-3-9-0-beta-42141918
Ref: 10132141918
Node: 安全性<8>2142233
Ref: whatsnew/changelog id992142335
Ref: 10142142335
Ref: 安全性<8>-Footnote-12142751
Node: 核心与内置函数<15>2142794
Ref: whatsnew/changelog id1002142912
Ref: 10152142912
Ref: 核心与内置函数<15>-Footnote-12145832
Ref: 核心与内置函数<15>-Footnote-22145875
Ref: 核心与内置函数<15>-Footnote-32145918
Ref: 核心与内置函数<15>-Footnote-42145961
Ref: 核心与内置函数<15>-Footnote-52146004
Ref: 核心与内置函数<15>-Footnote-62146047
Ref: 核心与内置函数<15>-Footnote-72146090
Ref: 核心与内置函数<15>-Footnote-82146133
Ref: 核心与内置函数<15>-Footnote-92146176
Ref: 核心与内置函数<15>-Footnote-102146219
Ref: 核心与内置函数<15>-Footnote-112146263
Ref: 核心与内置函数<15>-Footnote-122146307
Ref: 核心与内置函数<15>-Footnote-132146351
Ref: 核心与内置函数<15>-Footnote-142146395
Ref: 核心与内置函数<15>-Footnote-152146439
Ref: 核心与内置函数<15>-Footnote-162146483
Node: 库<16>2146527
Ref: whatsnew/changelog id1012146643
Ref: 10182146643
Ref: 库<16>-Footnote-12149692
Ref: 库<16>-Footnote-22149735
Ref: 库<16>-Footnote-32149778
Ref: 库<16>-Footnote-42149821
Ref: 库<16>-Footnote-52149864
Ref: 库<16>-Footnote-62149907
Ref: 库<16>-Footnote-72149950
Ref: 库<16>-Footnote-82149993
Ref: 库<16>-Footnote-92150036
Ref: 库<16>-Footnote-102150079
Ref: 库<16>-Footnote-112150123
Ref: 库<16>-Footnote-122150167
Ref: 库<16>-Footnote-132150211
Ref: 库<16>-Footnote-142150255
Ref: 库<16>-Footnote-152150299
Ref: 库<16>-Footnote-162150343
Ref: 库<16>-Footnote-172150387
Ref: 库<16>-Footnote-182150431
Ref: 库<16>-Footnote-192150475
Ref: 库<16>-Footnote-202150519
Ref: 库<16>-Footnote-212150563
Ref: 库<16>-Footnote-222150607
Node: 测试<12>2150651
Ref: whatsnew/changelog id1022150752
Ref: 101b2150752
Ref: 测试<12>-Footnote-12152112
Ref: 测试<12>-Footnote-22152155
Ref: 测试<12>-Footnote-32152198
Ref: 测试<12>-Footnote-42152241
Ref: 测试<12>-Footnote-52152284
Ref: 测试<12>-Footnote-62152327
Ref: 测试<12>-Footnote-72152370
Ref: 测试<12>-Footnote-82152413
Node: 构建<10>2152456
Ref: whatsnew/changelog id1032152561
Ref: 101e2152561
Ref: 构建<10>-Footnote-12152701
Node: Windows<12>2152744
Ref: whatsnew/changelog id1042152848
Ref: 101f2152848
Ref: Windows<12>-Footnote-12153320
Ref: Windows<12>-Footnote-22153363
Ref: Windows<12>-Footnote-32153406
Node: macOS<11>2153449
Ref: whatsnew/changelog id1052153551
Ref: 10232153551
Ref: macOS<11>-Footnote-12154245
Ref: macOS<11>-Footnote-22154288
Ref: macOS<11>-Footnote-32154331
Node: IDLE<12>2154374
Ref: whatsnew/changelog id1062154473
Ref: 10242154473
Ref: IDLE<12>-Footnote-12154734
Ref: IDLE<12>-Footnote-22154777
Node: C API<8>2154820
Ref: whatsnew/changelog id1072154901
Ref: 10252154901
Ref: C API<8>-Footnote-12155613
Ref: C API<8>-Footnote-22155656
Ref: C API<8>-Footnote-32155699
Node: Python 3 9 0 beta 32155742
Ref: whatsnew/changelog python-3-9-0-beta-32155881
Ref: 10262155881
Node: 库<17>2156014
Ref: whatsnew/changelog id1082156096
Ref: 10272156096
Ref: 库<17>-Footnote-12156480
Node: 构建<11>2156523
Ref: whatsnew/changelog id1092156605
Ref: 10282156605
Ref: 构建<11>-Footnote-12156861
Node: Python 3 9 0 beta 22156904
Ref: whatsnew/changelog python-3-9-0-beta-22157043
Ref: 10292157043
Node: 核心与内置函数<16>2157331
Ref: whatsnew/changelog id1102157428
Ref: 102a2157428
Ref: 核心与内置函数<16>-Footnote-12159536
Ref: 核心与内置函数<16>-Footnote-22159579
Ref: 核心与内置函数<16>-Footnote-32159622
Ref: 核心与内置函数<16>-Footnote-42159665
Ref: 核心与内置函数<16>-Footnote-52159708
Ref: 核心与内置函数<16>-Footnote-62159751
Ref: 核心与内置函数<16>-Footnote-72159794
Ref: 核心与内置函数<16>-Footnote-82159837
Ref: 核心与内置函数<16>-Footnote-92159880
Ref: 核心与内置函数<16>-Footnote-102159923
Ref: 核心与内置函数<16>-Footnote-112159967
Ref: 核心与内置函数<16>-Footnote-122160011
Node: 库<18>2160055
Ref: whatsnew/changelog id1112160171
Ref: 102e2160171
Ref: 库<18>-Footnote-12164290
Ref: 库<18>-Footnote-22164333
Ref: 库<18>-Footnote-32164376
Ref: 库<18>-Footnote-42164419
Ref: 库<18>-Footnote-52164462
Ref: 库<18>-Footnote-62164505
Ref: 库<18>-Footnote-72164548
Ref: 库<18>-Footnote-82164591
Ref: 库<18>-Footnote-92164634
Ref: 库<18>-Footnote-102164677
Ref: 库<18>-Footnote-112164721
Ref: 库<18>-Footnote-122164765
Ref: 库<18>-Footnote-132164809
Ref: 库<18>-Footnote-142164853
Ref: 库<18>-Footnote-152164897
Ref: 库<18>-Footnote-162164940
Ref: 库<18>-Footnote-172164984
Ref: 库<18>-Footnote-182165028
Ref: 库<18>-Footnote-192165078
Ref: 库<18>-Footnote-202165122
Ref: 库<18>-Footnote-212165166
Ref: 库<18>-Footnote-222165210
Ref: 库<18>-Footnote-232165254
Ref: 库<18>-Footnote-242165298
Ref: 库<18>-Footnote-252165342
Ref: 库<18>-Footnote-262165386
Node: 测试<13>2165430
Ref: whatsnew/changelog id1122165531
Ref: 10312165531
Ref: 测试<13>-Footnote-12165701
Node: 构建<12>2165744
Ref: whatsnew/changelog id1132165849
Ref: 10322165849
Ref: 构建<12>-Footnote-12166278
Ref: 构建<12>-Footnote-22166321
Node: Windows<13>2166364
Ref: whatsnew/changelog id1142166468
Ref: 10332166468
Ref: Windows<13>-Footnote-12166798
Ref: Windows<13>-Footnote-22166841
Node: macOS<12>2166884
Ref: whatsnew/changelog id1152166986
Ref: 10342166986
Ref: macOS<12>-Footnote-12167120
Node: IDLE<13>2167163
Ref: whatsnew/changelog id1162167262
Ref: 10352167262
Ref: IDLE<13>-Footnote-12167499
Ref: IDLE<13>-Footnote-22167542
Node: C API<9>2167585
Ref: whatsnew/changelog id1172167666
Ref: 10362167666
Ref: C API<9>-Footnote-12168174
Ref: C API<9>-Footnote-22168217
Ref: C API<9>-Footnote-32168260
Node: Python 3 9 0 beta 12168303
Ref: whatsnew/changelog python-3-9-0-beta-12168443
Ref: 10382168443
Node: 安全性<9>2168798
Ref: whatsnew/changelog id1182168900
Ref: 10392168900
Ref: 安全性<9>-Footnote-12169103
Node: 核心与内置函数<17>2169146
Ref: whatsnew/changelog id1192169264
Ref: 103a2169264
Ref: 核心与内置函数<17>-Footnote-12171814
Ref: 核心与内置函数<17>-Footnote-22171857
Ref: 核心与内置函数<17>-Footnote-32171900
Ref: 核心与内置函数<17>-Footnote-42171943
Ref: 核心与内置函数<17>-Footnote-52171986
Ref: 核心与内置函数<17>-Footnote-62172029
Ref: 核心与内置函数<17>-Footnote-72172078
Ref: 核心与内置函数<17>-Footnote-82172121
Ref: 核心与内置函数<17>-Footnote-92172164
Ref: 核心与内置函数<17>-Footnote-102172209
Ref: 核心与内置函数<17>-Footnote-112172259
Ref: 核心与内置函数<17>-Footnote-122172303
Ref: 核心与内置函数<17>-Footnote-132172349
Ref: 核心与内置函数<17>-Footnote-142172399
Ref: 核心与内置函数<17>-Footnote-152172443
Ref: 核心与内置函数<17>-Footnote-162172487
Ref: 核心与内置函数<17>-Footnote-172172531
Ref: 核心与内置函数<17>-Footnote-182172575
Ref: 核心与内置函数<17>-Footnote-192172621
Ref: 核心与内置函数<17>-Footnote-202172671
Ref: 核心与内置函数<17>-Footnote-212172715
Ref: 核心与内置函数<17>-Footnote-222172759
Ref: 核心与内置函数<17>-Footnote-232172803
Ref: 核心与内置函数<17>-Footnote-242172847
Node: 库<19>2172891
Ref: whatsnew/changelog id1202173007
Ref: 103d2173007
Ref: 库<19>-Footnote-12180381
Ref: 库<19>-Footnote-22180424
Ref: 库<19>-Footnote-32180467
Ref: 库<19>-Footnote-42180510
Ref: 库<19>-Footnote-52180553
Ref: 库<19>-Footnote-62180596
Ref: 库<19>-Footnote-72180639
Ref: 库<19>-Footnote-82180682
Ref: 库<19>-Footnote-92180725
Ref: 库<19>-Footnote-102180768
Ref: 库<19>-Footnote-112180812
Ref: 库<19>-Footnote-122180856
Ref: 库<19>-Footnote-132180900
Ref: 库<19>-Footnote-142180944
Ref: 库<19>-Footnote-152180988
Ref: 库<19>-Footnote-162181038
Ref: 库<19>-Footnote-172181082
Ref: 库<19>-Footnote-182181126
Ref: 库<19>-Footnote-192181170
Ref: 库<19>-Footnote-202181214
Ref: 库<19>-Footnote-212181258
Ref: 库<19>-Footnote-222181302
Ref: 库<19>-Footnote-232181346
Ref: 库<19>-Footnote-242181390
Ref: 库<19>-Footnote-252181434
Ref: 库<19>-Footnote-262181478
Ref: 库<19>-Footnote-272181522
Ref: 库<19>-Footnote-282181566
Ref: 库<19>-Footnote-292181610
Ref: 库<19>-Footnote-302181654
Ref: 库<19>-Footnote-312181698
Ref: 库<19>-Footnote-322181742
Ref: 库<19>-Footnote-332181786
Ref: 库<19>-Footnote-342181830
Ref: 库<19>-Footnote-352181874
Ref: 库<19>-Footnote-362181918
Ref: 库<19>-Footnote-372181962
Ref: 库<19>-Footnote-382182006
Ref: 库<19>-Footnote-392182050
Ref: 库<19>-Footnote-402182094
Ref: 库<19>-Footnote-412182138
Ref: 库<19>-Footnote-422182182
Ref: 库<19>-Footnote-432182226
Ref: 库<19>-Footnote-442182270
Ref: 库<19>-Footnote-452182314
Ref: 库<19>-Footnote-462182358
Ref: 库<19>-Footnote-472182402
Ref: 库<19>-Footnote-482182446
Ref: 库<19>-Footnote-492182490
Ref: 库<19>-Footnote-502182534
Node: 文档<14>2182578
Ref: whatsnew/changelog id1212182679
Ref: 10422182679
Ref: 文档<14>-Footnote-12183338
Ref: 文档<14>-Footnote-22183381
Ref: 文档<14>-Footnote-32183424
Ref: 文档<14>-Footnote-42183467
Ref: 文档<14>-Footnote-52183510
Node: 测试<14>2183553
Ref: whatsnew/changelog id1222183657
Ref: 10432183657
Ref: 测试<14>-Footnote-12184012
Ref: 测试<14>-Footnote-22184055
Node: 构建<13>2184098
Ref: whatsnew/changelog id1232184203
Ref: 10442184203
Ref: 构建<13>-Footnote-12184543
Ref: 构建<13>-Footnote-22184586
Node: Windows<14>2184629
Ref: whatsnew/changelog id1242184733
Ref: 10452184733
Ref: Windows<14>-Footnote-12185188
Ref: Windows<14>-Footnote-22185231
Ref: Windows<14>-Footnote-32185274
Node: macOS<13>2185317
Ref: whatsnew/changelog id1252185427
Ref: 10462185427
Ref: macOS<13>-Footnote-12186050
Ref: macOS<13>-Footnote-22186093
Node: 工具/示例<4>2186136
Ref: whatsnew/changelog id1262186244
Ref: 10472186244
Ref: 工具/示例<4>-Footnote-12186729
Ref: 工具/示例<4>-Footnote-22186772
Ref: 工具/示例<4>-Footnote-32186815
Node: C API<10>2186858
Ref: whatsnew/changelog id1272186948
Ref: 10482186948
Ref: C API<10>-Footnote-12188969
Ref: C API<10>-Footnote-22189012
Ref: C API<10>-Footnote-32189055
Ref: C API<10>-Footnote-42189098
Ref: C API<10>-Footnote-52189141
Ref: C API<10>-Footnote-62189184
Ref: C API<10>-Footnote-72189227
Ref: C API<10>-Footnote-82189270
Ref: C API<10>-Footnote-92189313
Ref: C API<10>-Footnote-102189356
Ref: C API<10>-Footnote-112189400
Node: Python 3 9 0 alpha 62189450
Ref: whatsnew/changelog python-3-9-0-alpha-62189591
Ref: 10492189591
Node: 安全性<10>2189967
Ref: whatsnew/changelog id1282190071
Ref: 104a2190071
Ref: 安全性<10>-Footnote-12190714
Ref: 安全性<10>-Footnote-22190757
Ref: 安全性<10>-Footnote-32190800
Node: 核心与内置函数<18>2190843
Ref: whatsnew/changelog id1292190963
Ref: 104b2190963
Ref: 核心与内置函数<18>-Footnote-12194732
Ref: 核心与内置函数<18>-Footnote-22194775
Ref: 核心与内置函数<18>-Footnote-32194818
Ref: 核心与内置函数<18>-Footnote-42194861
Ref: 核心与内置函数<18>-Footnote-52194904
Ref: 核心与内置函数<18>-Footnote-62194947
Ref: 核心与内置函数<18>-Footnote-72194990
Ref: 核心与内置函数<18>-Footnote-82195033
Ref: 核心与内置函数<18>-Footnote-92195076
Ref: 核心与内置函数<18>-Footnote-102195119
Ref: 核心与内置函数<18>-Footnote-112195169
Ref: 核心与内置函数<18>-Footnote-122195213
Ref: 核心与内置函数<18>-Footnote-132195259
Ref: 核心与内置函数<18>-Footnote-142195309
Ref: 核心与内置函数<18>-Footnote-152195355
Ref: 核心与内置函数<18>-Footnote-162195405
Ref: 核心与内置函数<18>-Footnote-172195451
Ref: 核心与内置函数<18>-Footnote-182195501
Ref: 核心与内置函数<18>-Footnote-192195545
Ref: 核心与内置函数<18>-Footnote-202195589
Ref: 核心与内置函数<18>-Footnote-212195635
Ref: 核心与内置函数<18>-Footnote-222195681
Ref: 核心与内置函数<18>-Footnote-232195725
Ref: 核心与内置函数<18>-Footnote-242195771
Ref: 核心与内置函数<18>-Footnote-252195821
Ref: 核心与内置函数<18>-Footnote-262195867
Ref: 核心与内置函数<18>-Footnote-272195917
Ref: 核心与内置函数<18>-Footnote-282195961
Ref: 核心与内置函数<18>-Footnote-292196005
Ref: 核心与内置函数<18>-Footnote-302196055
Ref: 核心与内置函数<18>-Footnote-312196099
Ref: 核心与内置函数<18>-Footnote-322196143
Ref: 核心与内置函数<18>-Footnote-332196187
Node: 库<20>2196237
Ref: whatsnew/changelog id1302196354
Ref: 104d2196354
Ref: 库<20>-Footnote-12206595
Ref: 库<20>-Footnote-22206638
Ref: 库<20>-Footnote-32206681
Ref: 库<20>-Footnote-42206724
Ref: 库<20>-Footnote-52206767
Ref: 库<20>-Footnote-62206810
Ref: 库<20>-Footnote-72206859
Ref: 库<20>-Footnote-82206902
Ref: 库<20>-Footnote-92206945
Ref: 库<20>-Footnote-102206988
Ref: 库<20>-Footnote-112207032
Ref: 库<20>-Footnote-122207076
Ref: 库<20>-Footnote-132207120
Ref: 库<20>-Footnote-142207164
Ref: 库<20>-Footnote-152207208
Ref: 库<20>-Footnote-162207252
Ref: 库<20>-Footnote-172207296
Ref: 库<20>-Footnote-182207340
Ref: 库<20>-Footnote-192207384
Ref: 库<20>-Footnote-202207428
Ref: 库<20>-Footnote-212207472
Ref: 库<20>-Footnote-222207516
Ref: 库<20>-Footnote-232207560
Ref: 库<20>-Footnote-242207604
Ref: 库<20>-Footnote-252207648
Ref: 库<20>-Footnote-262207692
Ref: 库<20>-Footnote-272207736
Ref: 库<20>-Footnote-282207780
Ref: 库<20>-Footnote-292207824
Ref: 库<20>-Footnote-302207868
Ref: 库<20>-Footnote-312207912
Ref: 库<20>-Footnote-322207956
Ref: 库<20>-Footnote-332208000
Ref: 库<20>-Footnote-342208044
Ref: 库<20>-Footnote-352208088
Ref: 库<20>-Footnote-362208132
Ref: 库<20>-Footnote-372208176
Ref: 库<20>-Footnote-382208220
Ref: 库<20>-Footnote-392208264
Ref: 库<20>-Footnote-402208308
Ref: 库<20>-Footnote-412208352
Ref: 库<20>-Footnote-422208396
Ref: 库<20>-Footnote-432208440
Ref: 库<20>-Footnote-442208484
Ref: 库<20>-Footnote-452208528
Ref: 库<20>-Footnote-462208572
Ref: 库<20>-Footnote-472208616
Ref: 库<20>-Footnote-482208660
Ref: 库<20>-Footnote-492208710
Ref: 库<20>-Footnote-502208754
Ref: 库<20>-Footnote-512208804
Ref: 库<20>-Footnote-522208848
Ref: 库<20>-Footnote-532208892
Ref: 库<20>-Footnote-542208936
Ref: 库<20>-Footnote-552208986
Ref: 库<20>-Footnote-562209030
Ref: 库<20>-Footnote-572209074
Ref: 库<20>-Footnote-582209118
Ref: 库<20>-Footnote-592209162
Ref: 库<20>-Footnote-602209206
Ref: 库<20>-Footnote-612209250
Node: 文档<15>2209294
Ref: whatsnew/changelog id1312209396
Ref: 10582209396
Ref: 文档<15>-Footnote-12209957
Ref: 文档<15>-Footnote-22210000
Ref: 文档<15>-Footnote-32210043
Ref: 文档<15>-Footnote-42210086
Node: 测试<15>2210129
Ref: whatsnew/changelog id1322210234
Ref: 105b2210234
Ref: 测试<15>-Footnote-12211315
Ref: 测试<15>-Footnote-22211358
Ref: 测试<15>-Footnote-32211401
Ref: 测试<15>-Footnote-42211444
Ref: 测试<15>-Footnote-52211487
Ref: 测试<15>-Footnote-62211530
Ref: 测试<15>-Footnote-72211573
Ref: 测试<15>-Footnote-82211622
Ref: 测试<15>-Footnote-92211665
Node: 构建<14>2211707
Ref: whatsnew/changelog id1332211813
Ref: 105d2211813
Ref: 构建<14>-Footnote-12212226
Ref: 构建<14>-Footnote-22212269
Ref: 构建<14>-Footnote-32212312
Node: Windows<15>2212355
Ref: whatsnew/changelog id1342212460
Ref: 105e2212460
Ref: Windows<15>-Footnote-12212673
Ref: Windows<15>-Footnote-22212716
Node: macOS<14>2212758
Ref: whatsnew/changelog id1352212861
Ref: 105f2212861
Ref: macOS<14>-Footnote-12213317
Ref: macOS<14>-Footnote-22213360
Node: IDLE<14>2213403
Ref: whatsnew/changelog id1362213511
Ref: 10602213511
Ref: IDLE<14>-Footnote-12213855
Ref: IDLE<14>-Footnote-22213898
Node: 工具/示例<5>2213941
Ref: whatsnew/changelog id1372214049
Ref: 10612214049
Ref: 工具/示例<5>-Footnote-12214515
Ref: 工具/示例<5>-Footnote-22214558
Ref: 工具/示例<5>-Footnote-32214601
Node: C API<11>2214644
Ref: whatsnew/changelog id1382214735
Ref: 10622214735
Ref: C API<11>-Footnote-12216710
Ref: C API<11>-Footnote-22216753
Ref: C API<11>-Footnote-32216796
Ref: C API<11>-Footnote-42216839
Ref: C API<11>-Footnote-52216882
Ref: C API<11>-Footnote-62216925
Ref: C API<11>-Footnote-72216968
Ref: C API<11>-Footnote-82217011
Ref: C API<11>-Footnote-92217054
Node: Python 3 9 0 alpha 52217097
Ref: whatsnew/changelog python-3-9-0-alpha-52217239
Ref: 10632217239
Node: 安全性<11>2217615
Ref: whatsnew/changelog id1392217719
Ref: 10642217719
Ref: 安全性<11>-Footnote-12217994
Node: 核心与内置函数<19>2218037
Ref: whatsnew/changelog id1402218157
Ref: 10652218157
Ref: 核心与内置函数<19>-Footnote-12224013
Ref: 核心与内置函数<19>-Footnote-22224056
Ref: 核心与内置函数<19>-Footnote-32224101
Ref: 核心与内置函数<19>-Footnote-42224150
Ref: 核心与内置函数<19>-Footnote-52224195
Ref: 核心与内置函数<19>-Footnote-62224244
Ref: 核心与内置函数<19>-Footnote-72224287
Ref: 核心与内置函数<19>-Footnote-82224330
Ref: 核心与内置函数<19>-Footnote-92224375
Ref: 核心与内置函数<19>-Footnote-102224420
Ref: 核心与内置函数<19>-Footnote-112224470
Ref: 核心与内置函数<19>-Footnote-122224514
Ref: 核心与内置函数<19>-Footnote-132224564
Ref: 核心与内置函数<19>-Footnote-142224608
Ref: 核心与内置函数<19>-Footnote-152224652
Ref: 核心与内置函数<19>-Footnote-162224702
Ref: 核心与内置函数<19>-Footnote-172224748
Ref: 核心与内置函数<19>-Footnote-182224798
Ref: 核心与内置函数<19>-Footnote-192224842
Ref: 核心与内置函数<19>-Footnote-202224886
Ref: 核心与内置函数<19>-Footnote-212224930
Ref: 核心与内置函数<19>-Footnote-222224974
Ref: 核心与内置函数<19>-Footnote-232225024
Ref: 核心与内置函数<19>-Footnote-242225068
Ref: 核心与内置函数<19>-Footnote-252225112
Ref: 核心与内置函数<19>-Footnote-262225156
Ref: 核心与内置函数<19>-Footnote-272225200
Ref: 核心与内置函数<19>-Footnote-282225244
Ref: 核心与内置函数<19>-Footnote-292225288
Ref: 核心与内置函数<19>-Footnote-302225332
Ref: 核心与内置函数<19>-Footnote-312225376
Ref: 核心与内置函数<19>-Footnote-322225422
Ref: 核心与内置函数<19>-Footnote-332225472
Ref: 核心与内置函数<19>-Footnote-342225516
Ref: 核心与内置函数<19>-Footnote-352225566
Ref: 核心与内置函数<19>-Footnote-362225610
Ref: 核心与内置函数<19>-Footnote-372225656
Ref: 核心与内置函数<19>-Footnote-382225706
Ref: 核心与内置函数<19>-Footnote-392225750
Ref: 核心与内置函数<19>-Footnote-402225794
Ref: 核心与内置函数<19>-Footnote-412225838
Ref: 核心与内置函数<19>-Footnote-422225882
Node: 库<21>2225926
Ref: whatsnew/changelog id1412226043
Ref: 10662226043
Ref: 库<21>-Footnote-12235169
Ref: 库<21>-Footnote-22235212
Ref: 库<21>-Footnote-32235255
Ref: 库<21>-Footnote-42235298
Ref: 库<21>-Footnote-52235341
Ref: 库<21>-Footnote-62235384
Ref: 库<21>-Footnote-72235427
Ref: 库<21>-Footnote-82235470
Ref: 库<21>-Footnote-92235513
Ref: 库<21>-Footnote-102235556
Ref: 库<21>-Footnote-112235600
Ref: 库<21>-Footnote-122235644
Ref: 库<21>-Footnote-132235694
Ref: 库<21>-Footnote-142235738
Ref: 库<21>-Footnote-152235782
Ref: 库<21>-Footnote-162235826
Ref: 库<21>-Footnote-172235876
Ref: 库<21>-Footnote-182235920
Ref: 库<21>-Footnote-192235964
Ref: 库<21>-Footnote-202236008
Ref: 库<21>-Footnote-212236052
Ref: 库<21>-Footnote-222236096
Ref: 库<21>-Footnote-232236140
Ref: 库<21>-Footnote-242236184
Ref: 库<21>-Footnote-252236228
Ref: 库<21>-Footnote-262236272
Ref: 库<21>-Footnote-272236316
Ref: 库<21>-Footnote-282236360
Ref: 库<21>-Footnote-292236404
Ref: 库<21>-Footnote-302236448
Ref: 库<21>-Footnote-312236492
Ref: 库<21>-Footnote-322236536
Ref: 库<21>-Footnote-332236586
Ref: 库<21>-Footnote-342236630
Ref: 库<21>-Footnote-352236674
Ref: 库<21>-Footnote-362236718
Ref: 库<21>-Footnote-372236762
Ref: 库<21>-Footnote-382236806
Ref: 库<21>-Footnote-392236850
Ref: 库<21>-Footnote-402236900
Ref: 库<21>-Footnote-412236944
Ref: 库<21>-Footnote-422236988
Ref: 库<21>-Footnote-432237032
Ref: 库<21>-Footnote-442237076
Ref: 库<21>-Footnote-452237120
Ref: 库<21>-Footnote-462237164
Ref: 库<21>-Footnote-472237208
Ref: 库<21>-Footnote-482237252
Ref: 库<21>-Footnote-492237296
Ref: 库<21>-Footnote-502237340
Ref: 库<21>-Footnote-512237384
Ref: 库<21>-Footnote-522237428
Ref: 库<21>-Footnote-532237472
Ref: 库<21>-Footnote-542237516
Node: 文档<16>2237560
Ref: whatsnew/changelog id1422237662
Ref: 106e2237662
Ref: 文档<16>-Footnote-12238289
Ref: 文档<16>-Footnote-22238332
Ref: 文档<16>-Footnote-32238381
Ref: 文档<16>-Footnote-42238424
Ref: 文档<16>-Footnote-52238467
Ref: 文档<16>-Footnote-62238510
Ref: 文档<16>-Footnote-72238553
Node: 测试<16>2238596
Ref: whatsnew/changelog id1432238701
Ref: 106f2238701
Ref: 测试<16>-Footnote-12239383
Ref: 测试<16>-Footnote-22239426
Ref: 测试<16>-Footnote-32239469
Ref: 测试<16>-Footnote-42239512
Node: 构建<15>2239555
Ref: whatsnew/changelog id1442239661
Ref: 10702239661
Ref: 构建<15>-Footnote-12240536
Ref: 构建<15>-Footnote-22240579
Ref: 构建<15>-Footnote-32240622
Node: Windows<16>2240667
Ref: whatsnew/changelog id1452240772
Ref: 10712240772
Ref: Windows<16>-Footnote-12241660
Ref: Windows<16>-Footnote-22241703
Ref: Windows<16>-Footnote-32241746
Ref: Windows<16>-Footnote-42241789
Ref: Windows<16>-Footnote-52241832
Ref: Windows<16>-Footnote-62241875
Node: macOS<15>2241918
Ref: whatsnew/changelog id1462242021
Ref: 10722242021
Ref: macOS<15>-Footnote-12242151
Node: IDLE<15>2242194
Ref: whatsnew/changelog id1472242302
Ref: 10732242302
Ref: IDLE<15>-Footnote-12242860
Ref: IDLE<15>-Footnote-22242903
Ref: IDLE<15>-Footnote-32242946
Ref: IDLE<15>-Footnote-42242989
Node: 工具/示例<6>2243032
Ref: whatsnew/changelog id1482243140
Ref: 10742243140
Ref: 工具/示例<6>-Footnote-12243669
Ref: 工具/示例<6>-Footnote-22243712
Node: C API<12>2243755
Ref: whatsnew/changelog id1492243846
Ref: 10752243846
Ref: C API<12>-Footnote-12247397
Ref: C API<12>-Footnote-22247440
Ref: C API<12>-Footnote-32247483
Ref: C API<12>-Footnote-42247526
Ref: C API<12>-Footnote-52247569
Ref: C API<12>-Footnote-62247612
Ref: C API<12>-Footnote-72247655
Ref: C API<12>-Footnote-82247698
Ref: C API<12>-Footnote-92247741
Ref: C API<12>-Footnote-102247784
Ref: C API<12>-Footnote-112247828
Ref: C API<12>-Footnote-122247872
Ref: C API<12>-Footnote-132247916
Ref: C API<12>-Footnote-142247960
Ref: C API<12>-Footnote-152248004
Ref: C API<12>-Footnote-162248048
Ref: C API<12>-Footnote-172248092
Node: Python 3 9 0 alpha 42248136
Ref: whatsnew/changelog python-3-9-0-alpha-42248278
Ref: 107b2248278
Node: 安全性<12>2248599
Ref: whatsnew/changelog id1502248703
Ref: 107c2248703
Ref: 安全性<12>-Footnote-12249147
Ref: 安全性<12>-Footnote-22249190
Ref: 安全性<12>-Footnote-32249233
Node: 核心与内置函数<20>2249276
Ref: whatsnew/changelog id1512249396
Ref: 107d2249396
Ref: 核心与内置函数<20>-Footnote-12252805
Ref: 核心与内置函数<20>-Footnote-22252848
Ref: 核心与内置函数<20>-Footnote-32252891
Ref: 核心与内置函数<20>-Footnote-42252934
Ref: 核心与内置函数<20>-Footnote-52252977
Ref: 核心与内置函数<20>-Footnote-62253020
Ref: 核心与内置函数<20>-Footnote-72253063
Ref: 核心与内置函数<20>-Footnote-82253106
Ref: 核心与内置函数<20>-Footnote-92253151
Ref: 核心与内置函数<20>-Footnote-102253200
Ref: 核心与内置函数<20>-Footnote-112253246
Ref: 核心与内置函数<20>-Footnote-122253296
Ref: 核心与内置函数<20>-Footnote-132253340
Ref: 核心与内置函数<20>-Footnote-142253384
Ref: 核心与内置函数<20>-Footnote-152253428
Ref: 核心与内置函数<20>-Footnote-162253472
Ref: 核心与内置函数<20>-Footnote-172253516
Ref: 核心与内置函数<20>-Footnote-182253562
Ref: 核心与内置函数<20>-Footnote-192253612
Ref: 核心与内置函数<20>-Footnote-202253658
Ref: 核心与内置函数<20>-Footnote-212253708
Ref: 核心与内置函数<20>-Footnote-222253754
Ref: 核心与内置函数<20>-Footnote-232253804
Ref: 核心与内置函数<20>-Footnote-242253848
Ref: 核心与内置函数<20>-Footnote-252253892
Ref: 核心与内置函数<20>-Footnote-262253936
Ref: 核心与内置函数<20>-Footnote-272253980
Ref: 核心与内置函数<20>-Footnote-282254024
Ref: 核心与内置函数<20>-Footnote-292254068
Node: 库<22>2254112
Ref: whatsnew/changelog id1522254229
Ref: 10822254229
Ref: 库<22>-Footnote-12260421
Ref: 库<22>-Footnote-22260464
Ref: 库<22>-Footnote-32260507
Ref: 库<22>-Footnote-42260550
Ref: 库<22>-Footnote-52260593
Ref: 库<22>-Footnote-62260636
Ref: 库<22>-Footnote-72260679
Ref: 库<22>-Footnote-82260722
Ref: 库<22>-Footnote-92260765
Ref: 库<22>-Footnote-102260808
Ref: 库<22>-Footnote-112260852
Ref: 库<22>-Footnote-122260896
Ref: 库<22>-Footnote-132260940
Ref: 库<22>-Footnote-142260984
Ref: 库<22>-Footnote-152261028
Ref: 库<22>-Footnote-162261072
Ref: 库<22>-Footnote-172261166
Ref: 库<22>-Footnote-182261210
Ref: 库<22>-Footnote-192261254
Ref: 库<22>-Footnote-202261298
Ref: 库<22>-Footnote-212261342
Ref: 库<22>-Footnote-222261386
Ref: 库<22>-Footnote-232261430
Ref: 库<22>-Footnote-242261474
Ref: 库<22>-Footnote-252261518
Ref: 库<22>-Footnote-262261562
Ref: 库<22>-Footnote-272261606
Ref: 库<22>-Footnote-282261656
Ref: 库<22>-Footnote-292261700
Ref: 库<22>-Footnote-302261744
Ref: 库<22>-Footnote-312261788
Ref: 库<22>-Footnote-322261832
Ref: 库<22>-Footnote-332261876
Ref: 库<22>-Footnote-342261920
Ref: 库<22>-Footnote-352261964
Ref: 库<22>-Footnote-362262008
Ref: 库<22>-Footnote-372262052
Ref: 库<22>-Footnote-382262096
Ref: 库<22>-Footnote-392262140
Node: 文档<17>2262184
Ref: whatsnew/changelog id1532262286
Ref: 108a2262286
Ref: 文档<17>-Footnote-12263311
Ref: 文档<17>-Footnote-22263354
Ref: 文档<17>-Footnote-32263397
Ref: 文档<17>-Footnote-42263440
Ref: 文档<17>-Footnote-52263483
Ref: 文档<17>-Footnote-62263526
Ref: 文档<17>-Footnote-72263569
Node: 测试<17>2263611
Ref: whatsnew/changelog id1542263716
Ref: 108b2263716
Ref: 测试<17>-Footnote-12264050
Ref: 测试<17>-Footnote-22264093
Node: 构建<16>2264136
Ref: whatsnew/changelog id1552264242
Ref: 108c2264242
Ref: 构建<16>-Footnote-12264372
Node: Windows<17>2264415
Ref: whatsnew/changelog id1562264519
Ref: 108d2264519
Ref: Windows<17>-Footnote-12265325
Ref: Windows<17>-Footnote-22265368
Ref: Windows<17>-Footnote-32265411
Ref: Windows<17>-Footnote-42265454
Ref: Windows<17>-Footnote-52265497
Ref: Windows<17>-Footnote-62265540
Node: IDLE<16>2265583
Ref: whatsnew/changelog id1572265686
Ref: 108e2265686
Ref: IDLE<16>-Footnote-12266233
Ref: IDLE<16>-Footnote-22266276
Ref: IDLE<16>-Footnote-32266319
Ref: IDLE<16>-Footnote-42266362
Ref: IDLE<16>-Footnote-52266405
Node: C API<13>2266448
Ref: whatsnew/changelog id1582266531
Ref: 108f2266531
Ref: C API<13>-Footnote-12269193
Ref: C API<13>-Footnote-22269236
Ref: C API<13>-Footnote-32269279
Ref: C API<13>-Footnote-42269322
Ref: C API<13>-Footnote-52269365
Ref: C API<13>-Footnote-62269408
Ref: C API<13>-Footnote-72269451
Ref: C API<13>-Footnote-82269494
Ref: C API<13>-Footnote-92269537
Ref: C API<13>-Footnote-102269580
Ref: C API<13>-Footnote-112269624
Ref: C API<13>-Footnote-122269668
Node: Python 3 9 0 alpha 32269712
Ref: whatsnew/changelog python-3-9-0-alpha-32269854
Ref: 10982269854
Node: 核心与内置函数<21>2270101
Ref: whatsnew/changelog id1592270199
Ref: 10992270199
Ref: 核心与内置函数<21>-Footnote-12274318
Ref: 核心与内置函数<21>-Footnote-22274361
Ref: 核心与内置函数<21>-Footnote-32274404
Ref: 核心与内置函数<21>-Footnote-42274447
Ref: 核心与内置函数<21>-Footnote-52274490
Ref: 核心与内置函数<21>-Footnote-62274533
Ref: 核心与内置函数<21>-Footnote-72274576
Ref: 核心与内置函数<21>-Footnote-82274619
Ref: 核心与内置函数<21>-Footnote-92274662
Ref: 核心与内置函数<21>-Footnote-102274705
Ref: 核心与内置函数<21>-Footnote-112274749
Ref: 核心与内置函数<21>-Footnote-122274795
Ref: 核心与内置函数<21>-Footnote-132274845
Ref: 核心与内置函数<21>-Footnote-142274889
Ref: 核心与内置函数<21>-Footnote-152274933
Ref: 核心与内置函数<21>-Footnote-162274977
Ref: 核心与内置函数<21>-Footnote-172275021
Ref: 核心与内置函数<21>-Footnote-182275065
Ref: 核心与内置函数<21>-Footnote-192275109
Ref: 核心与内置函数<21>-Footnote-202275153
Ref: 核心与内置函数<21>-Footnote-212275197
Ref: 核心与内置函数<21>-Footnote-222275241
Ref: 核心与内置函数<21>-Footnote-232275285
Ref: 核心与内置函数<21>-Footnote-242275329
Node: 库<23>2275373
Ref: whatsnew/changelog id1602275490
Ref: 109f2275490
Ref: 库<23>-Footnote-12285190
Ref: 库<23>-Footnote-22285233
Ref: 库<23>-Footnote-32285276
Ref: 库<23>-Footnote-42285319
Ref: 库<23>-Footnote-52285362
Ref: 库<23>-Footnote-62285405
Ref: 库<23>-Footnote-72285448
Ref: 库<23>-Footnote-82285491
Ref: 库<23>-Footnote-92285534
Ref: 库<23>-Footnote-102285577
Ref: 库<23>-Footnote-112285621
Ref: 库<23>-Footnote-122285665
Ref: 库<23>-Footnote-132285709
Ref: 库<23>-Footnote-142285753
Ref: 库<23>-Footnote-152285797
Ref: 库<23>-Footnote-162285841
Ref: 库<23>-Footnote-172285885
Ref: 库<23>-Footnote-182285929
Ref: 库<23>-Footnote-192285973
Ref: 库<23>-Footnote-202286017
Ref: 库<23>-Footnote-212286061
Ref: 库<23>-Footnote-222286105
Ref: 库<23>-Footnote-232286149
Ref: 库<23>-Footnote-242286193
Ref: 库<23>-Footnote-252286237
Ref: 库<23>-Footnote-262286281
Ref: 库<23>-Footnote-272286325
Ref: 库<23>-Footnote-282286369
Ref: 库<23>-Footnote-292286413
Ref: 库<23>-Footnote-302286457
Ref: 库<23>-Footnote-312286501
Ref: 库<23>-Footnote-322286545
Ref: 库<23>-Footnote-332286589
Ref: 库<23>-Footnote-342286633
Ref: 库<23>-Footnote-352286677
Ref: 库<23>-Footnote-362286721
Ref: 库<23>-Footnote-372286765
Ref: 库<23>-Footnote-382286809
Ref: 库<23>-Footnote-392286853
Ref: 库<23>-Footnote-402286897
Ref: 库<23>-Footnote-412286941
Ref: 库<23>-Footnote-422286985
Ref: 库<23>-Footnote-432287029
Ref: 库<23>-Footnote-442287073
Ref: 库<23>-Footnote-452287117
Ref: 库<23>-Footnote-462287161
Ref: 库<23>-Footnote-472287205
Ref: 库<23>-Footnote-482287249
Ref: 库<23>-Footnote-492287293
Ref: 库<23>-Footnote-502287337
Ref: 库<23>-Footnote-512287381
Ref: 库<23>-Footnote-522287425
Ref: 库<23>-Footnote-532287469
Node: 文档<18>2287513
Ref: whatsnew/changelog id1612287615
Ref: 10a72287615
Ref: 文档<18>-Footnote-12288178
Ref: 文档<18>-Footnote-22288221
Ref: 文档<18>-Footnote-32288264
Ref: 文档<18>-Footnote-42288337
Node: 构建<17>2288379
Ref: whatsnew/changelog id1622288482
Ref: 10a82288482
Ref: 构建<17>-Footnote-12289007
Ref: 构建<17>-Footnote-22289050
Ref: 构建<17>-Footnote-32289093
Node: IDLE<17>2289136
Ref: whatsnew/changelog id1632289238
Ref: 10a92289238
Ref: IDLE<17>-Footnote-12289659
Ref: IDLE<17>-Footnote-22289702
Ref: IDLE<17>-Footnote-32289745
Node: C API<14>2289788
Ref: whatsnew/changelog id1642289871
Ref: 10aa2289871
Ref: C API<14>-Footnote-12290636
Ref: C API<14>-Footnote-22290679
Node: Python 3 9 0 alpha 22290722
Ref: whatsnew/changelog python-3-9-0-alpha-22290864
Ref: 10ab2290864
Node: 安全性<13>2291205
Ref: whatsnew/changelog id1652291309
Ref: 10ac2291309
Ref: 安全性<13>-Footnote-12292181
Ref: 安全性<13>-Footnote-22292224
Ref: 安全性<13>-Footnote-32292267
Ref: 安全性<13>-Footnote-42292310
Node: 核心与内置函数<22>2292353
Ref: whatsnew/changelog id1662292473
Ref: 10ad2292473
Ref: 核心与内置函数<22>-Footnote-12296168
Ref: 核心与内置函数<22>-Footnote-22296211
Ref: 核心与内置函数<22>-Footnote-32296254
Ref: 核心与内置函数<22>-Footnote-42296297
Ref: 核心与内置函数<22>-Footnote-52296340
Ref: 核心与内置函数<22>-Footnote-62296383
Ref: 核心与内置函数<22>-Footnote-72296426
Ref: 核心与内置函数<22>-Footnote-82296469
Ref: 核心与内置函数<22>-Footnote-92296512
Ref: 核心与内置函数<22>-Footnote-102296555
Ref: 核心与内置函数<22>-Footnote-112296599
Ref: 核心与内置函数<22>-Footnote-122296643
Ref: 核心与内置函数<22>-Footnote-132296687
Ref: 核心与内置函数<22>-Footnote-142296731
Ref: 核心与内置函数<22>-Footnote-152296775
Ref: 核心与内置函数<22>-Footnote-162296819
Ref: 核心与内置函数<22>-Footnote-172296863
Ref: 核心与内置函数<22>-Footnote-182296907
Ref: 核心与内置函数<22>-Footnote-192296951
Ref: 核心与内置函数<22>-Footnote-202296995
Node: 库<24>2297039
Ref: whatsnew/changelog id1672297156
Ref: 10ae2297156
Ref: 库<24>-Footnote-12304950
Ref: 库<24>-Footnote-22304993
Ref: 库<24>-Footnote-32305036
Ref: 库<24>-Footnote-42305079
Ref: 库<24>-Footnote-52305122
Ref: 库<24>-Footnote-62305165
Ref: 库<24>-Footnote-72305208
Ref: 库<24>-Footnote-82305251
Ref: 库<24>-Footnote-92305294
Ref: 库<24>-Footnote-102305337
Ref: 库<24>-Footnote-112305381
Ref: 库<24>-Footnote-122305425
Ref: 库<24>-Footnote-132305469
Ref: 库<24>-Footnote-142305513
Ref: 库<24>-Footnote-152305557
Ref: 库<24>-Footnote-162305601
Ref: 库<24>-Footnote-172305645
Ref: 库<24>-Footnote-182305689
Ref: 库<24>-Footnote-192305733
Ref: 库<24>-Footnote-202305777
Ref: 库<24>-Footnote-212305821
Ref: 库<24>-Footnote-222305865
Ref: 库<24>-Footnote-232305909
Ref: 库<24>-Footnote-242305953
Ref: 库<24>-Footnote-252305997
Ref: 库<24>-Footnote-262306041
Ref: 库<24>-Footnote-272306085
Ref: 库<24>-Footnote-282306129
Ref: 库<24>-Footnote-292306173
Ref: 库<24>-Footnote-302306217
Ref: 库<24>-Footnote-312306261
Ref: 库<24>-Footnote-322306305
Ref: 库<24>-Footnote-332306349
Ref: 库<24>-Footnote-342306393
Ref: 库<24>-Footnote-352306437
Ref: 库<24>-Footnote-362306481
Ref: 库<24>-Footnote-372306525
Ref: 库<24>-Footnote-382306569
Ref: 库<24>-Footnote-392306613
Ref: 库<24>-Footnote-402306657
Node: 文档<19>2306701
Ref: whatsnew/changelog id1682306803
Ref: 10af2306803
Ref: 文档<19>-Footnote-12307376
Ref: 文档<19>-Footnote-22307419
Ref: 文档<19>-Footnote-32307462
Node: 测试<18>2307505
Ref: whatsnew/changelog id1692307610
Ref: 10b02307610
Ref: 测试<18>-Footnote-12310182
Ref: 测试<18>-Footnote-22310225
Ref: 测试<18>-Footnote-32310268
Ref: 测试<18>-Footnote-42310311
Ref: 测试<18>-Footnote-52310354
Ref: 测试<18>-Footnote-62310397
Ref: 测试<18>-Footnote-72310440
Ref: 测试<18>-Footnote-82310483
Ref: 测试<18>-Footnote-92310526
Ref: 测试<18>-Footnote-102310569
Ref: 测试<18>-Footnote-112310613
Ref: 测试<18>-Footnote-122310657
Ref: 测试<18>-Footnote-132310701
Node: 构建<18>2310745
Ref: whatsnew/changelog id1702310851
Ref: 10b52310851
Ref: 构建<18>-Footnote-12311244
Ref: 构建<18>-Footnote-22311287
Node: Windows<18>2311330
Ref: whatsnew/changelog id1712311435
Ref: 10b62311435
Ref: Windows<18>-Footnote-12311676
Ref: Windows<18>-Footnote-22311719
Node: macOS<16>2311762
Ref: whatsnew/changelog id1722311865
Ref: 10b72311865
Ref: macOS<16>-Footnote-12312173
Node: IDLE<18>2312216
Ref: whatsnew/changelog id1732312317
Ref: 10b82312317
Ref: IDLE<18>-Footnote-12312912
Ref: IDLE<18>-Footnote-22312955
Ref: IDLE<18>-Footnote-32312998
Ref: IDLE<18>-Footnote-42313041
Node: C API<15>2313084
Ref: whatsnew/changelog id1742313167
Ref: 10b92313167
Ref: C API<15>-Footnote-12313701
Ref: C API<15>-Footnote-22313744
Ref: C API<15>-Footnote-32313787
Node: Python 3 9 0 alpha 12313830
Ref: whatsnew/changelog python-3-9-0-alpha-12313971
Ref: 10ba2313971
Node: 安全性<14>2314347
Ref: whatsnew/changelog id1752314451
Ref: 10bb2314451
Ref: 安全性<14>-Footnote-12316752
Ref: 安全性<14>-Footnote-22316795
Ref: 安全性<14>-Footnote-32316838
Ref: 安全性<14>-Footnote-42316881
Ref: 安全性<14>-Footnote-52316924
Ref: 安全性<14>-Footnote-62316967
Ref: 安全性<14>-Footnote-72317010
Ref: 安全性<14>-Footnote-82317053
Ref: 安全性<14>-Footnote-92317096
Ref: 安全性<14>-Footnote-102317139
Ref: 安全性<14>-Footnote-112317183
Ref: 安全性<14>-Footnote-122317227
Ref: 安全性<14>-Footnote-132317271
Ref: 安全性<14>-Footnote-142317315
Node: 核心与内置函数<23>2317359
Ref: whatsnew/changelog id1762317479
Ref: 10be2317479
Ref: 核心与内置函数<23>-Footnote-12332945
Ref: 核心与内置函数<23>-Footnote-22332988
Ref: 核心与内置函数<23>-Footnote-32333031
Ref: 核心与内置函数<23>-Footnote-42333074
Ref: 核心与内置函数<23>-Footnote-52333117
Ref: 核心与内置函数<23>-Footnote-62333160
Ref: 核心与内置函数<23>-Footnote-72333203
Ref: 核心与内置函数<23>-Footnote-82333246
Ref: 核心与内置函数<23>-Footnote-92333289
Ref: 核心与内置函数<23>-Footnote-102333332
Ref: 核心与内置函数<23>-Footnote-112333376
Ref: 核心与内置函数<23>-Footnote-122333420
Ref: 核心与内置函数<23>-Footnote-132333464
Ref: 核心与内置函数<23>-Footnote-142333508
Ref: 核心与内置函数<23>-Footnote-152333552
Ref: 核心与内置函数<23>-Footnote-162333596
Ref: 核心与内置函数<23>-Footnote-172333640
Ref: 核心与内置函数<23>-Footnote-182333684
Ref: 核心与内置函数<23>-Footnote-192333728
Ref: 核心与内置函数<23>-Footnote-202333772
Ref: 核心与内置函数<23>-Footnote-212333822
Ref: 核心与内置函数<23>-Footnote-222333866
Ref: 核心与内置函数<23>-Footnote-232333910
Ref: 核心与内置函数<23>-Footnote-242333954
Ref: 核心与内置函数<23>-Footnote-252333998
Ref: 核心与内置函数<23>-Footnote-262334042
Ref: 核心与内置函数<23>-Footnote-272334086
Ref: 核心与内置函数<23>-Footnote-282334130
Ref: 核心与内置函数<23>-Footnote-292334174
Ref: 核心与内置函数<23>-Footnote-302334218
Ref: 核心与内置函数<23>-Footnote-312334262
Ref: 核心与内置函数<23>-Footnote-322334306
Ref: 核心与内置函数<23>-Footnote-332334350
Ref: 核心与内置函数<23>-Footnote-342334394
Ref: 核心与内置函数<23>-Footnote-352334438
Ref: 核心与内置函数<23>-Footnote-362334482
Ref: 核心与内置函数<23>-Footnote-372334526
Ref: 核心与内置函数<23>-Footnote-382334570
Ref: 核心与内置函数<23>-Footnote-392334614
Ref: 核心与内置函数<23>-Footnote-402334658
Ref: 核心与内置函数<23>-Footnote-412334701
Ref: 核心与内置函数<23>-Footnote-422334745
Ref: 核心与内置函数<23>-Footnote-432334789
Ref: 核心与内置函数<23>-Footnote-442334833
Ref: 核心与内置函数<23>-Footnote-452334877
Ref: 核心与内置函数<23>-Footnote-462334921
Ref: 核心与内置函数<23>-Footnote-472334965
Ref: 核心与内置函数<23>-Footnote-482335009
Ref: 核心与内置函数<23>-Footnote-492335053
Ref: 核心与内置函数<23>-Footnote-502335097
Ref: 核心与内置函数<23>-Footnote-512335141
Ref: 核心与内置函数<23>-Footnote-522335185
Ref: 核心与内置函数<23>-Footnote-532335229
Ref: 核心与内置函数<23>-Footnote-542335279
Ref: 核心与内置函数<23>-Footnote-552335323
Ref: 核心与内置函数<23>-Footnote-562335367
Ref: 核心与内置函数<23>-Footnote-572335411
Ref: 核心与内置函数<23>-Footnote-582335455
Ref: 核心与内置函数<23>-Footnote-592335499
Ref: 核心与内置函数<23>-Footnote-602335543
Ref: 核心与内置函数<23>-Footnote-612335587
Ref: 核心与内置函数<23>-Footnote-622335631
Ref: 核心与内置函数<23>-Footnote-632335675
Ref: 核心与内置函数<23>-Footnote-642335719
Ref: 核心与内置函数<23>-Footnote-652335763
Ref: 核心与内置函数<23>-Footnote-662335807
Ref: 核心与内置函数<23>-Footnote-672335851
Ref: 核心与内置函数<23>-Footnote-682335895
Ref: 核心与内置函数<23>-Footnote-692335939
Ref: 核心与内置函数<23>-Footnote-702335983
Ref: 核心与内置函数<23>-Footnote-712336027
Ref: 核心与内置函数<23>-Footnote-722336071
Ref: 核心与内置函数<23>-Footnote-732336115
Ref: 核心与内置函数<23>-Footnote-742336159
Ref: 核心与内置函数<23>-Footnote-752336203
Ref: 核心与内置函数<23>-Footnote-762336247
Ref: 核心与内置函数<23>-Footnote-772336291
Ref: 核心与内置函数<23>-Footnote-782336335
Ref: 核心与内置函数<23>-Footnote-792336379
Ref: 核心与内置函数<23>-Footnote-802336423
Ref: 核心与内置函数<23>-Footnote-812336467
Ref: 核心与内置函数<23>-Footnote-822336511
Ref: 核心与内置函数<23>-Footnote-832336555
Ref: 核心与内置函数<23>-Footnote-842336599
Ref: 核心与内置函数<23>-Footnote-852336643
Ref: 核心与内置函数<23>-Footnote-862336687
Ref: 核心与内置函数<23>-Footnote-872336731
Ref: 核心与内置函数<23>-Footnote-882336775
Ref: 核心与内置函数<23>-Footnote-892336819
Ref: 核心与内置函数<23>-Footnote-902336863
Ref: 核心与内置函数<23>-Footnote-912336907
Ref: 核心与内置函数<23>-Footnote-922336951
Ref: 核心与内置函数<23>-Footnote-932336995
Ref: 核心与内置函数<23>-Footnote-942337039
Node: 库<25>2337083
Ref: whatsnew/changelog id1772337200
Ref: 10c62337200
Ref: 库<25>-Footnote-12376706
Ref: 库<25>-Footnote-22376749
Ref: 库<25>-Footnote-32376792
Ref: 库<25>-Footnote-42376835
Ref: 库<25>-Footnote-52376878
Ref: 库<25>-Footnote-62376921
Ref: 库<25>-Footnote-72376964
Ref: 库<25>-Footnote-82377007
Ref: 库<25>-Footnote-92377050
Ref: 库<25>-Footnote-102377093
Ref: 库<25>-Footnote-112377137
Ref: 库<25>-Footnote-122377181
Ref: 库<25>-Footnote-132377225
Ref: 库<25>-Footnote-142377269
Ref: 库<25>-Footnote-152377313
Ref: 库<25>-Footnote-162377357
Ref: 库<25>-Footnote-172377401
Ref: 库<25>-Footnote-182377445
Ref: 库<25>-Footnote-192377489
Ref: 库<25>-Footnote-202377533
Ref: 库<25>-Footnote-212377577
Ref: 库<25>-Footnote-222377621
Ref: 库<25>-Footnote-232377665
Ref: 库<25>-Footnote-242377709
Ref: 库<25>-Footnote-252377753
Ref: 库<25>-Footnote-262377797
Ref: 库<25>-Footnote-272377841
Ref: 库<25>-Footnote-282377885
Ref: 库<25>-Footnote-292377929
Ref: 库<25>-Footnote-302377973
Ref: 库<25>-Footnote-312378017
Ref: 库<25>-Footnote-322378061
Ref: 库<25>-Footnote-332378105
Ref: 库<25>-Footnote-342378149
Ref: 库<25>-Footnote-352378193
Ref: 库<25>-Footnote-362378237
Ref: 库<25>-Footnote-372378281
Ref: 库<25>-Footnote-382378325
Ref: 库<25>-Footnote-392378369
Ref: 库<25>-Footnote-402378413
Ref: 库<25>-Footnote-412378457
Ref: 库<25>-Footnote-422378501
Ref: 库<25>-Footnote-432378545
Ref: 库<25>-Footnote-442378589
Ref: 库<25>-Footnote-452378633
Ref: 库<25>-Footnote-462378677
Ref: 库<25>-Footnote-472378721
Ref: 库<25>-Footnote-482378765
Ref: 库<25>-Footnote-492378809
Ref: 库<25>-Footnote-502378853
Ref: 库<25>-Footnote-512378897
Ref: 库<25>-Footnote-522378941
Ref: 库<25>-Footnote-532378985
Ref: 库<25>-Footnote-542379029
Ref: 库<25>-Footnote-552379073
Ref: 库<25>-Footnote-562379117
Ref: 库<25>-Footnote-572379161
Ref: 库<25>-Footnote-582379205
Ref: 库<25>-Footnote-592379249
Ref: 库<25>-Footnote-602379293
Ref: 库<25>-Footnote-612379337
Ref: 库<25>-Footnote-622379381
Ref: 库<25>-Footnote-632379425
Ref: 库<25>-Footnote-642379468
Ref: 库<25>-Footnote-652379512
Ref: 库<25>-Footnote-662379556
Ref: 库<25>-Footnote-672379600
Ref: 库<25>-Footnote-682379644
Ref: 库<25>-Footnote-692379688
Ref: 库<25>-Footnote-702379732
Ref: 库<25>-Footnote-712379776
Ref: 库<25>-Footnote-722379820
Ref: 库<25>-Footnote-732379864
Ref: 库<25>-Footnote-742379908
Ref: 库<25>-Footnote-752379952
Ref: 库<25>-Footnote-762379996
Ref: 库<25>-Footnote-772380104
Ref: 库<25>-Footnote-782380148
Ref: 库<25>-Footnote-792380192
Ref: 库<25>-Footnote-802380236
Ref: 库<25>-Footnote-812380280
Ref: 库<25>-Footnote-822380324
Ref: 库<25>-Footnote-832380368
Ref: 库<25>-Footnote-842380412
Ref: 库<25>-Footnote-852380456
Ref: 库<25>-Footnote-862380500
Ref: 库<25>-Footnote-872380544
Ref: 库<25>-Footnote-882380588
Ref: 库<25>-Footnote-892380632
Ref: 库<25>-Footnote-902380676
Ref: 库<25>-Footnote-912380720
Ref: 库<25>-Footnote-922380764
Ref: 库<25>-Footnote-932380808
Ref: 库<25>-Footnote-942380852
Ref: 库<25>-Footnote-952380896
Ref: 库<25>-Footnote-962380940
Ref: 库<25>-Footnote-972380984
Ref: 库<25>-Footnote-982381028
Ref: 库<25>-Footnote-992381072
Ref: 库<25>-Footnote-1002381116
Ref: 库<25>-Footnote-1012381161
Ref: 库<25>-Footnote-1022381206
Ref: 库<25>-Footnote-1032381251
Ref: 库<25>-Footnote-1042381296
Ref: 库<25>-Footnote-1052381341
Ref: 库<25>-Footnote-1062381386
Ref: 库<25>-Footnote-1072381431
Ref: 库<25>-Footnote-1082381475
Ref: 库<25>-Footnote-1092381520
Ref: 库<25>-Footnote-1102381565
Ref: 库<25>-Footnote-1112381610
Ref: 库<25>-Footnote-1122381655
Ref: 库<25>-Footnote-1132381700
Ref: 库<25>-Footnote-1142381745
Ref: 库<25>-Footnote-1152381790
Ref: 库<25>-Footnote-1162381835
Ref: 库<25>-Footnote-1172381880
Ref: 库<25>-Footnote-1182381925
Ref: 库<25>-Footnote-1192381970
Ref: 库<25>-Footnote-1202382015
Ref: 库<25>-Footnote-1212382060
Ref: 库<25>-Footnote-1222382105
Ref: 库<25>-Footnote-1232382150
Ref: 库<25>-Footnote-1242382195
Ref: 库<25>-Footnote-1252382240
Ref: 库<25>-Footnote-1262382285
Ref: 库<25>-Footnote-1272382330
Ref: 库<25>-Footnote-1282382375
Ref: 库<25>-Footnote-1292382420
Ref: 库<25>-Footnote-1302382465
Ref: 库<25>-Footnote-1312382510
Ref: 库<25>-Footnote-1322382555
Ref: 库<25>-Footnote-1332382600
Ref: 库<25>-Footnote-1342382645
Ref: 库<25>-Footnote-1352382690
Ref: 库<25>-Footnote-1362382735
Ref: 库<25>-Footnote-1372382812
Ref: 库<25>-Footnote-1382382857
Ref: 库<25>-Footnote-1392382902
Ref: 库<25>-Footnote-1402382947
Ref: 库<25>-Footnote-1412382992
Ref: 库<25>-Footnote-1422383037
Ref: 库<25>-Footnote-1432383082
Ref: 库<25>-Footnote-1442383127
Ref: 库<25>-Footnote-1452383172
Ref: 库<25>-Footnote-1462383217
Ref: 库<25>-Footnote-1472383262
Ref: 库<25>-Footnote-1482383307
Ref: 库<25>-Footnote-1492383352
Ref: 库<25>-Footnote-1502383397
Ref: 库<25>-Footnote-1512383442
Ref: 库<25>-Footnote-1522383487
Ref: 库<25>-Footnote-1532383532
Ref: 库<25>-Footnote-1542383577
Ref: 库<25>-Footnote-1552383622
Ref: 库<25>-Footnote-1562383667
Ref: 库<25>-Footnote-1572383712
Ref: 库<25>-Footnote-1582383757
Ref: 库<25>-Footnote-1592383802
Ref: 库<25>-Footnote-1602383847
Ref: 库<25>-Footnote-1612383892
Ref: 库<25>-Footnote-1622383937
Ref: 库<25>-Footnote-1632383982
Ref: 库<25>-Footnote-1642384027
Ref: 库<25>-Footnote-1652384072
Ref: 库<25>-Footnote-1662384117
Ref: 库<25>-Footnote-1672384162
Ref: 库<25>-Footnote-1682384207
Ref: 库<25>-Footnote-1692384252
Ref: 库<25>-Footnote-1702384297
Ref: 库<25>-Footnote-1712384342
Ref: 库<25>-Footnote-1722384387
Ref: 库<25>-Footnote-1732384438
Ref: 库<25>-Footnote-1742384483
Ref: 库<25>-Footnote-1752384528
Ref: 库<25>-Footnote-1762384573
Ref: 库<25>-Footnote-1772384618
Ref: 库<25>-Footnote-1782384663
Ref: 库<25>-Footnote-1792384708
Ref: 库<25>-Footnote-1802384753
Ref: 库<25>-Footnote-1812384798
Ref: 库<25>-Footnote-1822384843
Ref: 库<25>-Footnote-1832384888
Ref: 库<25>-Footnote-1842384933
Ref: 库<25>-Footnote-1852384978
Ref: 库<25>-Footnote-1862385023
Ref: 库<25>-Footnote-1872385068
Ref: 库<25>-Footnote-1882385113
Ref: 库<25>-Footnote-1892385158
Ref: 库<25>-Footnote-1902385203
Ref: 库<25>-Footnote-1912385248
Ref: 库<25>-Footnote-1922385293
Ref: 库<25>-Footnote-1932385338
Ref: 库<25>-Footnote-1942385383
Ref: 库<25>-Footnote-1952385428
Ref: 库<25>-Footnote-1962385473
Ref: 库<25>-Footnote-1972385518
Ref: 库<25>-Footnote-1982385563
Ref: 库<25>-Footnote-1992385608
Ref: 库<25>-Footnote-2002385653
Ref: 库<25>-Footnote-2012385698
Ref: 库<25>-Footnote-2022385743
Ref: 库<25>-Footnote-2032385788
Ref: 库<25>-Footnote-2042385833
Ref: 库<25>-Footnote-2052385878
Ref: 库<25>-Footnote-2062385923
Ref: 库<25>-Footnote-2072385968
Ref: 库<25>-Footnote-2082386013
Ref: 库<25>-Footnote-2092386058
Ref: 库<25>-Footnote-2102386103
Ref: 库<25>-Footnote-2112386148
Ref: 库<25>-Footnote-2122386193
Ref: 库<25>-Footnote-2132386238
Ref: 库<25>-Footnote-2142386283
Ref: 库<25>-Footnote-2152386328
Ref: 库<25>-Footnote-2162386373
Ref: 库<25>-Footnote-2172386418
Ref: 库<25>-Footnote-2182386463
Ref: 库<25>-Footnote-2192386508
Ref: 库<25>-Footnote-2202386553
Ref: 库<25>-Footnote-2212386598
Ref: 库<25>-Footnote-2222386643
Ref: 库<25>-Footnote-2232386688
Ref: 库<25>-Footnote-2242386733
Ref: 库<25>-Footnote-2252386778
Ref: 库<25>-Footnote-2262386823
Ref: 库<25>-Footnote-2272386868
Ref: 库<25>-Footnote-2282386913
Ref: 库<25>-Footnote-2292386958
Ref: 库<25>-Footnote-2302387003
Ref: 库<25>-Footnote-2312387048
Ref: 库<25>-Footnote-2322387093
Ref: 库<25>-Footnote-2332387138
Ref: 库<25>-Footnote-2342387183
Ref: 库<25>-Footnote-2352387228
Ref: 库<25>-Footnote-2362387273
Ref: 库<25>-Footnote-2372387318
Ref: 库<25>-Footnote-2382387363
Ref: 库<25>-Footnote-2392387408
Ref: 库<25>-Footnote-2402387452
Ref: 库<25>-Footnote-2412387497
Ref: 库<25>-Footnote-2422387542
Ref: 库<25>-Footnote-2432387587
Ref: 库<25>-Footnote-2442387632
Ref: 库<25>-Footnote-2452387677
Ref: 库<25>-Footnote-2462387722
Ref: 库<25>-Footnote-2472387767
Ref: 库<25>-Footnote-2482387812
Ref: 库<25>-Footnote-2492387857
Ref: 库<25>-Footnote-2502387902
Ref: 库<25>-Footnote-2512387947
Ref: 库<25>-Footnote-2522387992
Ref: 库<25>-Footnote-2532388037
Node: 文档<20>2388081
Ref: whatsnew/changelog id1782388183
Ref: 10dc2388183
Ref: 文档<20>-Footnote-12392643
Ref: 文档<20>-Footnote-22392686
Ref: 文档<20>-Footnote-32392729
Ref: 文档<20>-Footnote-42392772
Ref: 文档<20>-Footnote-52392815
Ref: 文档<20>-Footnote-62392858
Ref: 文档<20>-Footnote-72392901
Ref: 文档<20>-Footnote-82392944
Ref: 文档<20>-Footnote-92392987
Ref: 文档<20>-Footnote-102393030
Ref: 文档<20>-Footnote-112393074
Ref: 文档<20>-Footnote-122393118
Ref: 文档<20>-Footnote-132393162
Ref: 文档<20>-Footnote-142393206
Ref: 文档<20>-Footnote-152393250
Ref: 文档<20>-Footnote-162393294
Ref: 文档<20>-Footnote-172393338
Ref: 文档<20>-Footnote-182393382
Ref: 文档<20>-Footnote-192393426
Ref: 文档<20>-Footnote-202393470
Ref: 文档<20>-Footnote-212393514
Ref: 文档<20>-Footnote-222393558
Ref: 文档<20>-Footnote-232393602
Ref: 文档<20>-Footnote-242393646
Ref: 文档<20>-Footnote-252393690
Ref: 文档<20>-Footnote-262393734
Ref: 文档<20>-Footnote-272393778
Ref: 文档<20>-Footnote-282393822
Ref: 文档<20>-Footnote-292393866
Ref: 文档<20>-Footnote-302393910
Ref: 文档<20>-Footnote-312393954
Ref: 文档<20>-Footnote-322393998
Ref: 文档<20>-Footnote-332394042
Ref: 文档<20>-Footnote-342394086
Ref: 文档<20>-Footnote-352394130
Node: 测试<19>2394174
Ref: whatsnew/changelog id1792394279
Ref: 10df2394279
Ref: 测试<19>-Footnote-12402386
Ref: 测试<19>-Footnote-22402429
Ref: 测试<19>-Footnote-32402472
Ref: 测试<19>-Footnote-42402515
Ref: 测试<19>-Footnote-52402558
Ref: 测试<19>-Footnote-62402601
Ref: 测试<19>-Footnote-72402644
Ref: 测试<19>-Footnote-82402687
Ref: 测试<19>-Footnote-92402730
Ref: 测试<19>-Footnote-102402773
Ref: 测试<19>-Footnote-112402817
Ref: 测试<19>-Footnote-122402861
Ref: 测试<19>-Footnote-132402905
Ref: 测试<19>-Footnote-142402949
Ref: 测试<19>-Footnote-152402993
Ref: 测试<19>-Footnote-162403037
Ref: 测试<19>-Footnote-172403081
Ref: 测试<19>-Footnote-182403125
Ref: 测试<19>-Footnote-192403169
Ref: 测试<19>-Footnote-202403213
Ref: 测试<19>-Footnote-212403257
Ref: 测试<19>-Footnote-222403301
Ref: 测试<19>-Footnote-232403345
Ref: 测试<19>-Footnote-242403389
Ref: 测试<19>-Footnote-252403433
Ref: 测试<19>-Footnote-262403477
Ref: 测试<19>-Footnote-272403521
Ref: 测试<19>-Footnote-282403565
Ref: 测试<19>-Footnote-292403609
Ref: 测试<19>-Footnote-302403653
Ref: 测试<19>-Footnote-312403697
Ref: 测试<19>-Footnote-322403741
Ref: 测试<19>-Footnote-332403785
Ref: 测试<19>-Footnote-342403829
Ref: 测试<19>-Footnote-352403873
Ref: 测试<19>-Footnote-362403917
Ref: 测试<19>-Footnote-372403961
Ref: 测试<19>-Footnote-382404005
Ref: 测试<19>-Footnote-392404049
Ref: 测试<19>-Footnote-402404093
Ref: 测试<19>-Footnote-412404137
Ref: 测试<19>-Footnote-422404181
Ref: 测试<19>-Footnote-432404225
Ref: 测试<19>-Footnote-442404269
Ref: 测试<19>-Footnote-452404313
Ref: 测试<19>-Footnote-462404357
Ref: 测试<19>-Footnote-472404401
Ref: 测试<19>-Footnote-482404445
Node: 构建<19>2404489
Ref: whatsnew/changelog id1802404595
Ref: 10e62404595
Ref: 构建<19>-Footnote-12408416
Ref: 构建<19>-Footnote-22408459
Ref: 构建<19>-Footnote-32408502
Ref: 构建<19>-Footnote-42408545
Ref: 构建<19>-Footnote-52408588
Ref: 构建<19>-Footnote-62408631
Ref: 构建<19>-Footnote-72408674
Ref: 构建<19>-Footnote-82408717
Ref: 构建<19>-Footnote-92408760
Ref: 构建<19>-Footnote-102408803
Ref: 构建<19>-Footnote-112408847
Ref: 构建<19>-Footnote-122408891
Ref: 构建<19>-Footnote-132408935
Ref: 构建<19>-Footnote-142408979
Ref: 构建<19>-Footnote-152409023
Ref: 构建<19>-Footnote-162409067
Node: Windows<19>2409111
Ref: whatsnew/changelog id1812409216
Ref: 10e82409216
Ref: Windows<19>-Footnote-12414120
Ref: Windows<19>-Footnote-22414163
Ref: Windows<19>-Footnote-32414206
Ref: Windows<19>-Footnote-42414249
Ref: Windows<19>-Footnote-52414292
Ref: Windows<19>-Footnote-62414335
Ref: Windows<19>-Footnote-72414378
Ref: Windows<19>-Footnote-82414421
Ref: Windows<19>-Footnote-92414464
Ref: Windows<19>-Footnote-102414507
Ref: Windows<19>-Footnote-112414551
Ref: Windows<19>-Footnote-122414595
Ref: Windows<19>-Footnote-132414639
Ref: Windows<19>-Footnote-142414683
Ref: Windows<19>-Footnote-152414727
Ref: Windows<19>-Footnote-162414771
Ref: Windows<19>-Footnote-172414815
Ref: Windows<19>-Footnote-182414859
Ref: Windows<19>-Footnote-192414903
Ref: Windows<19>-Footnote-202414947
Ref: Windows<19>-Footnote-212414991
Ref: Windows<19>-Footnote-222415035
Ref: Windows<19>-Footnote-232415079
Ref: Windows<19>-Footnote-242415122
Ref: Windows<19>-Footnote-252415165
Ref: Windows<19>-Footnote-262415209
Ref: Windows<19>-Footnote-272415253
Ref: Windows<19>-Footnote-282415297
Ref: Windows<19>-Footnote-292415341
Ref: Windows<19>-Footnote-302415385
Ref: Windows<19>-Footnote-312415429
Ref: Windows<19>-Footnote-322415473
Ref: Windows<19>-Footnote-332415517
Ref: Windows<19>-Footnote-342415561
Ref: Windows<19>-Footnote-352415605
Ref: Windows<19>-Footnote-362415649
Ref: Windows<19>-Footnote-372415693
Ref: Windows<19>-Footnote-382415737
Ref: Windows<19>-Footnote-392415781
Ref: Windows<19>-Footnote-402415825
Ref: Windows<19>-Footnote-412415869
Ref: Windows<19>-Footnote-422415913
Node: macOS<17>2415957
Ref: whatsnew/changelog id1822416060
Ref: 10eb2416060
Ref: macOS<17>-Footnote-12416907
Ref: macOS<17>-Footnote-22416950
Ref: macOS<17>-Footnote-32416993
Ref: macOS<17>-Footnote-42417036
Ref: macOS<17>-Footnote-52417079
Ref: macOS<17>-Footnote-62417122
Node: IDLE<19>2417165
Ref: whatsnew/changelog id1832417273
Ref: 10ec2417273
Ref: IDLE<19>-Footnote-12422005
Ref: IDLE<19>-Footnote-22422048
Ref: IDLE<19>-Footnote-32422090
Ref: IDLE<19>-Footnote-42422133
Ref: IDLE<19>-Footnote-52422176
Ref: IDLE<19>-Footnote-62422219
Ref: IDLE<19>-Footnote-72422262
Ref: IDLE<19>-Footnote-82422305
Ref: IDLE<19>-Footnote-92422348
Ref: IDLE<19>-Footnote-102422391
Ref: IDLE<19>-Footnote-112422435
Ref: IDLE<19>-Footnote-122422479
Ref: IDLE<19>-Footnote-132422523
Ref: IDLE<19>-Footnote-142422567
Ref: IDLE<19>-Footnote-152422611
Ref: IDLE<19>-Footnote-162422655
Ref: IDLE<19>-Footnote-172422699
Ref: IDLE<19>-Footnote-182422743
Ref: IDLE<19>-Footnote-192422787
Ref: IDLE<19>-Footnote-202422831
Ref: IDLE<19>-Footnote-212422875
Ref: IDLE<19>-Footnote-222422919
Ref: IDLE<19>-Footnote-232422963
Ref: IDLE<19>-Footnote-242423007
Ref: IDLE<19>-Footnote-252423051
Ref: IDLE<19>-Footnote-262423095
Ref: IDLE<19>-Footnote-272423139
Ref: IDLE<19>-Footnote-282423183
Ref: IDLE<19>-Footnote-292423227
Ref: IDLE<19>-Footnote-302423270
Node: 工具/示例<7>2423314
Ref: whatsnew/changelog id1842423422
Ref: 10ed2423422
Ref: 工具/示例<7>-Footnote-12424423
Ref: 工具/示例<7>-Footnote-22424466
Ref: 工具/示例<7>-Footnote-32424509
Ref: 工具/示例<7>-Footnote-42424552
Ref: 工具/示例<7>-Footnote-52424595
Ref: 工具/示例<7>-Footnote-62424638
Ref: 工具/示例<7>-Footnote-72424681
Ref: 工具/示例<7>-Footnote-82424724
Node: C API<16>2424767
Ref: whatsnew/changelog id1852424858
Ref: 10ef2424858
Ref: C API<16>-Footnote-12430286
Ref: C API<16>-Footnote-22430329
Ref: C API<16>-Footnote-32430372
Ref: C API<16>-Footnote-42430415
Ref: C API<16>-Footnote-52430458
Ref: C API<16>-Footnote-62430501
Ref: C API<16>-Footnote-72430544
Ref: C API<16>-Footnote-82430587
Ref: C API<16>-Footnote-92430630
Ref: C API<16>-Footnote-102430673
Ref: C API<16>-Footnote-112430717
Ref: C API<16>-Footnote-122430761
Ref: C API<16>-Footnote-132430805
Ref: C API<16>-Footnote-142430849
Ref: C API<16>-Footnote-152430899
Ref: C API<16>-Footnote-162430943
Ref: C API<16>-Footnote-172430987
Ref: C API<16>-Footnote-182431031
Ref: C API<16>-Footnote-192431075
Ref: C API<16>-Footnote-202431119
Ref: C API<16>-Footnote-212431163
Ref: C API<16>-Footnote-222431207
Ref: C API<16>-Footnote-232431251
Ref: C API<16>-Footnote-242431295
Ref: C API<16>-Footnote-252431339
Ref: C API<16>-Footnote-262431383
Ref: C API<16>-Footnote-272431427
Ref: C API<16>-Footnote-282431471
Ref: C API<16>-Footnote-292431515
Ref: C API<16>-Footnote-302431559
Ref: C API<16>-Footnote-312431603
Ref: C API<16>-Footnote-322431647
Ref: C API<16>-Footnote-332431691
Ref: C API<16>-Footnote-342431735
Node: Python 3 8 0 beta 12431779
Ref: whatsnew/changelog python-3-8-0-beta-12431920
Ref: 10f52431920
Node: 安全性<15>2432294
Ref: whatsnew/changelog id1862432397
Ref: 10f62432397
Ref: 安全性<15>-Footnote-12432987
Ref: 安全性<15>-Footnote-22433030
Ref: 安全性<15>-Footnote-32433073
Node: 核心与内置函数<24>2433116
Ref: whatsnew/changelog id1872433235
Ref: 10f72433235
Ref: 核心与内置函数<24>-Footnote-12441306
Ref: 核心与内置函数<24>-Footnote-22441349
Ref: 核心与内置函数<24>-Footnote-32441392
Ref: 核心与内置函数<24>-Footnote-42441435
Ref: 核心与内置函数<24>-Footnote-52441478
Ref: 核心与内置函数<24>-Footnote-62441521
Ref: 核心与内置函数<24>-Footnote-72441564
Ref: 核心与内置函数<24>-Footnote-82441607
Ref: 核心与内置函数<24>-Footnote-92441650
Ref: 核心与内置函数<24>-Footnote-102441693
Ref: 核心与内置函数<24>-Footnote-112441737
Ref: 核心与内置函数<24>-Footnote-122441781
Ref: 核心与内置函数<24>-Footnote-132441825
Ref: 核心与内置函数<24>-Footnote-142441869
Ref: 核心与内置函数<24>-Footnote-152441913
Ref: 核心与内置函数<24>-Footnote-162441957
Ref: 核心与内置函数<24>-Footnote-172442001
Ref: 核心与内置函数<24>-Footnote-182442045
Ref: 核心与内置函数<24>-Footnote-192442088
Ref: 核心与内置函数<24>-Footnote-202442132
Ref: 核心与内置函数<24>-Footnote-212442176
Ref: 核心与内置函数<24>-Footnote-222442220
Ref: 核心与内置函数<24>-Footnote-232442263
Ref: 核心与内置函数<24>-Footnote-242442307
Ref: 核心与内置函数<24>-Footnote-252442351
Ref: 核心与内置函数<24>-Footnote-262442395
Ref: 核心与内置函数<24>-Footnote-272442439
Ref: 核心与内置函数<24>-Footnote-282442483
Ref: 核心与内置函数<24>-Footnote-292442527
Ref: 核心与内置函数<24>-Footnote-302442571
Ref: 核心与内置函数<24>-Footnote-312442615
Ref: 核心与内置函数<24>-Footnote-322442659
Ref: 核心与内置函数<24>-Footnote-332442703
Ref: 核心与内置函数<24>-Footnote-342442747
Ref: 核心与内置函数<24>-Footnote-352442791
Ref: 核心与内置函数<24>-Footnote-362442835
Ref: 核心与内置函数<24>-Footnote-372442879
Ref: 核心与内置函数<24>-Footnote-382442923
Ref: 核心与内置函数<24>-Footnote-392442967
Ref: 核心与内置函数<24>-Footnote-402443011
Ref: 核心与内置函数<24>-Footnote-412443055
Ref: 核心与内置函数<24>-Footnote-422443099
Ref: 核心与内置函数<24>-Footnote-432443143
Ref: 核心与内置函数<24>-Footnote-442443187
Node: 库<26>2443231
Ref: whatsnew/changelog id1882443347
Ref: 10fd2443347
Ref: 库<26>-Footnote-12461644
Ref: 库<26>-Footnote-22461687
Ref: 库<26>-Footnote-32461730
Ref: 库<26>-Footnote-42461773
Ref: 库<26>-Footnote-52461816
Ref: 库<26>-Footnote-62461859
Ref: 库<26>-Footnote-72461902
Ref: 库<26>-Footnote-82461945
Ref: 库<26>-Footnote-92461988
Ref: 库<26>-Footnote-102462031
Ref: 库<26>-Footnote-112462075
Ref: 库<26>-Footnote-122462119
Ref: 库<26>-Footnote-132462163
Ref: 库<26>-Footnote-142462207
Ref: 库<26>-Footnote-152462251
Ref: 库<26>-Footnote-162462295
Ref: 库<26>-Footnote-172462339
Ref: 库<26>-Footnote-182462383
Ref: 库<26>-Footnote-192462427
Ref: 库<26>-Footnote-202462471
Ref: 库<26>-Footnote-212462515
Ref: 库<26>-Footnote-222462559
Ref: 库<26>-Footnote-232462603
Ref: 库<26>-Footnote-242462647
Ref: 库<26>-Footnote-252462693
Ref: 库<26>-Footnote-262462737
Ref: 库<26>-Footnote-272462781
Ref: 库<26>-Footnote-282462825
Ref: 库<26>-Footnote-292462869
Ref: 库<26>-Footnote-302462913
Ref: 库<26>-Footnote-312462957
Ref: 库<26>-Footnote-322463001
Ref: 库<26>-Footnote-332463045
Ref: 库<26>-Footnote-342463089
Ref: 库<26>-Footnote-352463133
Ref: 库<26>-Footnote-362463177
Ref: 库<26>-Footnote-372463221
Ref: 库<26>-Footnote-382463265
Ref: 库<26>-Footnote-392463309
Ref: 库<26>-Footnote-402463353
Ref: 库<26>-Footnote-412463397
Ref: 库<26>-Footnote-422463441
Ref: 库<26>-Footnote-432463485
Ref: 库<26>-Footnote-442463529
Ref: 库<26>-Footnote-452463573
Ref: 库<26>-Footnote-462463617
Ref: 库<26>-Footnote-472463661
Ref: 库<26>-Footnote-482463705
Ref: 库<26>-Footnote-492463749
Ref: 库<26>-Footnote-502463793
Ref: 库<26>-Footnote-512463837
Ref: 库<26>-Footnote-522463881
Ref: 库<26>-Footnote-532463925
Ref: 库<26>-Footnote-542463969
Ref: 库<26>-Footnote-552464013
Ref: 库<26>-Footnote-562464057
Ref: 库<26>-Footnote-572464101
Ref: 库<26>-Footnote-582464145
Ref: 库<26>-Footnote-592464189
Ref: 库<26>-Footnote-602464233
Ref: 库<26>-Footnote-612464277
Ref: 库<26>-Footnote-622464321
Ref: 库<26>-Footnote-632464365
Ref: 库<26>-Footnote-642464409
Ref: 库<26>-Footnote-652464453
Ref: 库<26>-Footnote-662464497
Ref: 库<26>-Footnote-672464541
Ref: 库<26>-Footnote-682464585
Ref: 库<26>-Footnote-692464628
Ref: 库<26>-Footnote-702464672
Ref: 库<26>-Footnote-712464715
Ref: 库<26>-Footnote-722464759
Ref: 库<26>-Footnote-732464803
Ref: 库<26>-Footnote-742464847
Ref: 库<26>-Footnote-752464891
Ref: 库<26>-Footnote-762464935
Ref: 库<26>-Footnote-772464979
Ref: 库<26>-Footnote-782465023
Ref: 库<26>-Footnote-792465067
Ref: 库<26>-Footnote-802465111
Ref: 库<26>-Footnote-812465155
Ref: 库<26>-Footnote-822465199
Ref: 库<26>-Footnote-832465243
Ref: 库<26>-Footnote-842465287
Ref: 库<26>-Footnote-852465331
Ref: 库<26>-Footnote-862465375
Ref: 库<26>-Footnote-872465419
Ref: 库<26>-Footnote-882465463
Ref: 库<26>-Footnote-892465507
Ref: 库<26>-Footnote-902465551
Ref: 库<26>-Footnote-912465595
Ref: 库<26>-Footnote-922465639
Ref: 库<26>-Footnote-932465683
Ref: 库<26>-Footnote-942465727
Ref: 库<26>-Footnote-952465771
Ref: 库<26>-Footnote-962465815
Ref: 库<26>-Footnote-972465859
Ref: 库<26>-Footnote-982465903
Ref: 库<26>-Footnote-992465947
Ref: 库<26>-Footnote-1002465991
Ref: 库<26>-Footnote-1012466036
Ref: 库<26>-Footnote-1022466081
Ref: 库<26>-Footnote-1032466126
Ref: 库<26>-Footnote-1042466171
Ref: 库<26>-Footnote-1052466216
Ref: 库<26>-Footnote-1062466261
Ref: 库<26>-Footnote-1072466306
Node: 文档<21>2466351
Ref: whatsnew/changelog id1892466452
Ref: 110b2466452
Ref: 文档<21>-Footnote-12468525
Ref: 文档<21>-Footnote-22468568
Ref: 文档<21>-Footnote-32468611
Ref: 文档<21>-Footnote-42468654
Ref: 文档<21>-Footnote-52468697
Ref: 文档<21>-Footnote-62468740
Ref: 文档<21>-Footnote-72468783
Ref: 文档<21>-Footnote-82468826
Ref: 文档<21>-Footnote-92468869
Ref: 文档<21>-Footnote-102468912
Ref: 文档<21>-Footnote-112468956
Ref: 文档<21>-Footnote-122469000
Ref: 文档<21>-Footnote-132469044
Ref: 文档<21>-Footnote-142469088
Node: 测试<20>2469132
Ref: whatsnew/changelog id1902469236
Ref: 110c2469236
Ref: 测试<20>-Footnote-12470880
Ref: 测试<20>-Footnote-22470923
Ref: 测试<20>-Footnote-32470966
Ref: 测试<20>-Footnote-42471009
Ref: 测试<20>-Footnote-52471052
Ref: 测试<20>-Footnote-62471095
Ref: 测试<20>-Footnote-72471138
Ref: 测试<20>-Footnote-82471181
Ref: 测试<20>-Footnote-92471224
Ref: 测试<20>-Footnote-102471267
Node: 构建<20>2471311
Ref: whatsnew/changelog id1912471416
Ref: 110e2471416
Ref: 构建<20>-Footnote-12472642
Ref: 构建<20>-Footnote-22472685
Node: Windows<20>2472728
Ref: whatsnew/changelog id1922472832
Ref: 110f2472832
Ref: Windows<20>-Footnote-12473271
Ref: Windows<20>-Footnote-22473314
Ref: Windows<20>-Footnote-32473357
Ref: Windows<20>-Footnote-42473400
Node: macOS<18>2473443
Ref: whatsnew/changelog id1932473545
Ref: 11102473545
Ref: macOS<18>-Footnote-12473847
Node: IDLE<20>2473890
Ref: whatsnew/changelog id1942473997
Ref: 11112473997
Ref: IDLE<20>-Footnote-12474599
Ref: IDLE<20>-Footnote-22474642
Ref: IDLE<20>-Footnote-32474685
Ref: IDLE<20>-Footnote-42474728
Ref: IDLE<20>-Footnote-52474771
Ref: IDLE<20>-Footnote-62474814
Node: 工具/示例<8>2474857
Ref: whatsnew/changelog id1952474964
Ref: 11122474964
Ref: 工具/示例<8>-Footnote-12475163
Node: C API<17>2475206
Ref: whatsnew/changelog id1962475296
Ref: 11132475296
Ref: C API<17>-Footnote-12476632
Ref: C API<17>-Footnote-22476675
Ref: C API<17>-Footnote-32476724
Ref: C API<17>-Footnote-42476767
Ref: C API<17>-Footnote-52476810
Ref: C API<17>-Footnote-62476853
Ref: C API<17>-Footnote-72476902
Ref: C API<17>-Footnote-82476945
Ref: C API<17>-Footnote-92476988
Node: Python 3 8 0 alpha 42477031
Ref: whatsnew/changelog python-3-8-0-alpha-42477172
Ref: 11152477172
Node: 安全性<16>2477548
Ref: whatsnew/changelog id1972477652
Ref: 11162477652
Ref: 安全性<16>-Footnote-12478551
Ref: 安全性<16>-Footnote-22478594
Ref: 安全性<16>-Footnote-32478637
Node: 核心与内置函数<25>2478680
Ref: whatsnew/changelog id1982478800
Ref: 11172478800
Ref: 核心与内置函数<25>-Footnote-12482194
Ref: 核心与内置函数<25>-Footnote-22482237
Ref: 核心与内置函数<25>-Footnote-32482280
Ref: 核心与内置函数<25>-Footnote-42482323
Ref: 核心与内置函数<25>-Footnote-52482366
Ref: 核心与内置函数<25>-Footnote-62482409
Ref: 核心与内置函数<25>-Footnote-72482452
Ref: 核心与内置函数<25>-Footnote-82482495
Ref: 核心与内置函数<25>-Footnote-92482538
Ref: 核心与内置函数<25>-Footnote-102482587
Ref: 核心与内置函数<25>-Footnote-112482631
Ref: 核心与内置函数<25>-Footnote-122482675
Ref: 核心与内置函数<25>-Footnote-132482719
Ref: 核心与内置函数<25>-Footnote-142482763
Ref: 核心与内置函数<25>-Footnote-152482807
Ref: 核心与内置函数<25>-Footnote-162482851
Ref: 核心与内置函数<25>-Footnote-172482895
Ref: 核心与内置函数<25>-Footnote-182482939
Ref: 核心与内置函数<25>-Footnote-192482983
Ref: 核心与内置函数<25>-Footnote-202483027
Node: 库<27>2483071
Ref: whatsnew/changelog id1992483188
Ref: 11182483188
Ref: 库<27>-Footnote-12492492
Ref: 库<27>-Footnote-22492535
Ref: 库<27>-Footnote-32492578
Ref: 库<27>-Footnote-42492621
Ref: 库<27>-Footnote-52492666
Ref: 库<27>-Footnote-62492709
Ref: 库<27>-Footnote-72492752
Ref: 库<27>-Footnote-82492795
Ref: 库<27>-Footnote-92492838
Ref: 库<27>-Footnote-102492881
Ref: 库<27>-Footnote-112492925
Ref: 库<27>-Footnote-122492969
Ref: 库<27>-Footnote-132493013
Ref: 库<27>-Footnote-142493057
Ref: 库<27>-Footnote-152493101
Ref: 库<27>-Footnote-162493145
Ref: 库<27>-Footnote-172493189
Ref: 库<27>-Footnote-182493233
Ref: 库<27>-Footnote-192493277
Ref: 库<27>-Footnote-202493321
Ref: 库<27>-Footnote-212493365
Ref: 库<27>-Footnote-222493409
Ref: 库<27>-Footnote-232493453
Ref: 库<27>-Footnote-242493497
Ref: 库<27>-Footnote-252493541
Ref: 库<27>-Footnote-262493585
Ref: 库<27>-Footnote-272493629
Ref: 库<27>-Footnote-282493673
Ref: 库<27>-Footnote-292493717
Ref: 库<27>-Footnote-302493761
Ref: 库<27>-Footnote-312493805
Ref: 库<27>-Footnote-322493849
Ref: 库<27>-Footnote-332493893
Ref: 库<27>-Footnote-342493937
Ref: 库<27>-Footnote-352493981
Ref: 库<27>-Footnote-362494025
Ref: 库<27>-Footnote-372494069
Ref: 库<27>-Footnote-382494113
Ref: 库<27>-Footnote-392494157
Ref: 库<27>-Footnote-402494201
Ref: 库<27>-Footnote-412494245
Ref: 库<27>-Footnote-422494289
Ref: 库<27>-Footnote-432494333
Ref: 库<27>-Footnote-442494377
Ref: 库<27>-Footnote-452494421
Ref: 库<27>-Footnote-462494465
Ref: 库<27>-Footnote-472494509
Ref: 库<27>-Footnote-482494553
Ref: 库<27>-Footnote-492494597
Ref: 库<27>-Footnote-502494641
Ref: 库<27>-Footnote-512494685
Ref: 库<27>-Footnote-522494729
Ref: 库<27>-Footnote-532494773
Ref: 库<27>-Footnote-542494817
Node: 文档<22>2494861
Ref: whatsnew/changelog id2002494963
Ref: 111d2494963
Ref: 文档<22>-Footnote-12496382
Ref: 文档<22>-Footnote-22496425
Ref: 文档<22>-Footnote-32496468
Ref: 文档<22>-Footnote-42496511
Ref: 文档<22>-Footnote-52496554
Ref: 文档<22>-Footnote-62496593
Ref: 文档<22>-Footnote-72496636
Ref: 文档<22>-Footnote-82496679
Ref: 文档<22>-Footnote-92496722
Ref: 文档<22>-Footnote-102496765
Ref: 文档<22>-Footnote-112496809
Ref: 文档<22>-Footnote-122496853
Node: 测试<21>2496897
Ref: whatsnew/changelog id2012497002
Ref: 111e2497002
Ref: 测试<21>-Footnote-12499253
Ref: 测试<21>-Footnote-22499296
Ref: 测试<21>-Footnote-32499339
Ref: 测试<21>-Footnote-42499382
Ref: 测试<21>-Footnote-52499425
Ref: 测试<21>-Footnote-62499468
Ref: 测试<21>-Footnote-72499511
Ref: 测试<21>-Footnote-82499554
Ref: 测试<21>-Footnote-92499597
Ref: 测试<21>-Footnote-102499640
Ref: 测试<21>-Footnote-112499684
Ref: 测试<21>-Footnote-122499728
Ref: 测试<21>-Footnote-132499772
Ref: 测试<21>-Footnote-142499816
Ref: 测试<21>-Footnote-152499860
Node: 构建<21>2499904
Ref: whatsnew/changelog id2022500010
Ref: 11202500010
Ref: 构建<21>-Footnote-12503145
Ref: 构建<21>-Footnote-22503188
Ref: 构建<21>-Footnote-32503231
Ref: 构建<21>-Footnote-42503274
Ref: 构建<21>-Footnote-52503317
Ref: 构建<21>-Footnote-62503360
Ref: 构建<21>-Footnote-72503403
Ref: 构建<21>-Footnote-82503446
Ref: 构建<21>-Footnote-92503489
Ref: 构建<21>-Footnote-102503532
Ref: 构建<21>-Footnote-112503576
Ref: 构建<21>-Footnote-122503620
Ref: 构建<21>-Footnote-132503664
Node: Windows<21>2503708
Ref: whatsnew/changelog id2032503813
Ref: 11212503813
Ref: Windows<21>-Footnote-12506465
Ref: Windows<21>-Footnote-22506508
Ref: Windows<21>-Footnote-32506551
Ref: Windows<21>-Footnote-42506594
Ref: Windows<21>-Footnote-52506637
Ref: Windows<21>-Footnote-62506680
Ref: Windows<21>-Footnote-72506723
Ref: Windows<21>-Footnote-82506766
Ref: Windows<21>-Footnote-92506809
Ref: Windows<21>-Footnote-102506852
Ref: Windows<21>-Footnote-112506896
Ref: Windows<21>-Footnote-122506940
Node: macOS<19>2506984
Ref: whatsnew/changelog id2042507087
Ref: 11222507087
Ref: macOS<19>-Footnote-12507401
Ref: macOS<19>-Footnote-22507444
Node: IDLE<21>2507487
Ref: whatsnew/changelog id2052507595
Ref: 11232507595
Ref: IDLE<21>-Footnote-12507842
Node: 工具/示例<9>2507885
Ref: whatsnew/changelog id2062507993
Ref: 11242507993
Ref: 工具/示例<9>-Footnote-12508147
Node: C API<18>2508190
Ref: whatsnew/changelog id2072508281
Ref: 11252508281
Ref: C API<18>-Footnote-12510282
Ref: C API<18>-Footnote-22510325
Ref: C API<18>-Footnote-32510368
Ref: C API<18>-Footnote-42510411
Ref: C API<18>-Footnote-52510454
Ref: C API<18>-Footnote-62510497
Node: Python 3 8 0 alpha 32510540
Ref: whatsnew/changelog python-3-8-0-alpha-32510682
Ref: 11272510682
Node: 安全性<17>2511041
Ref: whatsnew/changelog id2082511145
Ref: 11282511145
Ref: 安全性<17>-Footnote-12511708
Ref: 安全性<17>-Footnote-22511751
Node: 核心与内置函数<26>2511794
Ref: whatsnew/changelog id2092511914
Ref: 112a2511914
Ref: 核心与内置函数<26>-Footnote-12515523
Ref: 核心与内置函数<26>-Footnote-22515566
Ref: 核心与内置函数<26>-Footnote-32515609
Ref: 核心与内置函数<26>-Footnote-42515652
Ref: 核心与内置函数<26>-Footnote-52515695
Ref: 核心与内置函数<26>-Footnote-62515738
Ref: 核心与内置函数<26>-Footnote-72515781
Ref: 核心与内置函数<26>-Footnote-82515824
Ref: 核心与内置函数<26>-Footnote-92515867
Ref: 核心与内置函数<26>-Footnote-102515910
Ref: 核心与内置函数<26>-Footnote-112515954
Ref: 核心与内置函数<26>-Footnote-122515998
Ref: 核心与内置函数<26>-Footnote-132516042
Ref: 核心与内置函数<26>-Footnote-142516086
Ref: 核心与内置函数<26>-Footnote-152516130
Ref: 核心与内置函数<26>-Footnote-162516174
Ref: 核心与内置函数<26>-Footnote-172516218
Ref: 核心与内置函数<26>-Footnote-182516262
Ref: 核心与内置函数<26>-Footnote-192516306
Ref: 核心与内置函数<26>-Footnote-202516350
Ref: 核心与内置函数<26>-Footnote-212516394
Ref: 核心与内置函数<26>-Footnote-222516438
Node: 库<28>2516482
Ref: whatsnew/changelog id2102516599
Ref: 112c2516599
Ref: 库<28>-Footnote-12522219
Ref: 库<28>-Footnote-22522262
Ref: 库<28>-Footnote-32522305
Ref: 库<28>-Footnote-42522348
Ref: 库<28>-Footnote-52522391
Ref: 库<28>-Footnote-62522434
Ref: 库<28>-Footnote-72522477
Ref: 库<28>-Footnote-82522520
Ref: 库<28>-Footnote-92522563
Ref: 库<28>-Footnote-102522606
Ref: 库<28>-Footnote-112522650
Ref: 库<28>-Footnote-122522694
Ref: 库<28>-Footnote-132522738
Ref: 库<28>-Footnote-142522782
Ref: 库<28>-Footnote-152522826
Ref: 库<28>-Footnote-162522870
Ref: 库<28>-Footnote-172522914
Ref: 库<28>-Footnote-182522958
Ref: 库<28>-Footnote-192523002
Ref: 库<28>-Footnote-202523046
Ref: 库<28>-Footnote-212523090
Ref: 库<28>-Footnote-222523134
Ref: 库<28>-Footnote-232523178
Ref: 库<28>-Footnote-242523222
Ref: 库<28>-Footnote-252523266
Ref: 库<28>-Footnote-262523310
Ref: 库<28>-Footnote-272523354
Ref: 库<28>-Footnote-282523398
Ref: 库<28>-Footnote-292523442
Ref: 库<28>-Footnote-302523486
Ref: 库<28>-Footnote-312523530
Ref: 库<28>-Footnote-322523574
Ref: 库<28>-Footnote-332523618
Ref: 库<28>-Footnote-342523662
Ref: 库<28>-Footnote-352523706
Ref: 库<28>-Footnote-362523750
Ref: 库<28>-Footnote-372523794
Node: 文档<23>2523838
Ref: whatsnew/changelog id2112523940
Ref: 112e2523940
Ref: 文档<23>-Footnote-12524495
Ref: 文档<23>-Footnote-22524538
Ref: 文档<23>-Footnote-32524581
Node: 测试<22>2524624
Ref: whatsnew/changelog id2122524729
Ref: 112f2524729
Ref: 测试<22>-Footnote-12525241
Ref: 测试<22>-Footnote-22525284
Ref: 测试<22>-Footnote-32525327
Node: 构建<22>2525370
Ref: whatsnew/changelog id2132525476
Ref: 11302525476
Ref: 构建<22>-Footnote-12525996
Ref: 构建<22>-Footnote-22526039
Ref: 构建<22>-Footnote-32526082
Ref: 构建<22>-Footnote-42526125
Node: Windows<22>2526168
Ref: whatsnew/changelog id2142526272
Ref: 11312526272
Ref: Windows<22>-Footnote-12526723
Ref: Windows<22>-Footnote-22526766
Ref: Windows<22>-Footnote-32526809
Node: IDLE<22>2526852
Ref: whatsnew/changelog id2152526963
Ref: 11322526963
Ref: IDLE<22>-Footnote-12528084
Ref: IDLE<22>-Footnote-22528127
Ref: IDLE<22>-Footnote-32528170
Ref: IDLE<22>-Footnote-42528213
Ref: IDLE<22>-Footnote-52528256
Ref: IDLE<22>-Footnote-62528299
Ref: IDLE<22>-Footnote-72528342
Ref: IDLE<22>-Footnote-82528385
Ref: IDLE<22>-Footnote-92528428
Node: 工具/示例<10>2528471
Ref: whatsnew/changelog id2162528580
Ref: 11332528580
Ref: 工具/示例<10>-Footnote-12528793
Ref: 工具/示例<10>-Footnote-22528836
Node: C API<19>2528879
Ref: whatsnew/changelog id2172528971
Ref: 11342528971
Ref: C API<19>-Footnote-12529363
Ref: C API<19>-Footnote-22529406
Node: Python 3 8 0 alpha 22529449
Ref: whatsnew/changelog python-3-8-0-alpha-22529591
Ref: 11352529591
Node: 核心与内置函数<27>2529842
Ref: whatsnew/changelog id2182529940
Ref: 11362529940
Ref: 核心与内置函数<27>-Footnote-12533086
Ref: 核心与内置函数<27>-Footnote-22533129
Ref: 核心与内置函数<27>-Footnote-32533172
Ref: 核心与内置函数<27>-Footnote-42533215
Ref: 核心与内置函数<27>-Footnote-52533258
Ref: 核心与内置函数<27>-Footnote-62533303
Ref: 核心与内置函数<27>-Footnote-72533346
Ref: 核心与内置函数<27>-Footnote-82533389
Ref: 核心与内置函数<27>-Footnote-92533432
Ref: 核心与内置函数<27>-Footnote-102533475
Ref: 核心与内置函数<27>-Footnote-112533519
Ref: 核心与内置函数<27>-Footnote-122533563
Ref: 核心与内置函数<27>-Footnote-132533607
Ref: 核心与内置函数<27>-Footnote-142533651
Ref: 核心与内置函数<27>-Footnote-152533695
Ref: 核心与内置函数<27>-Footnote-162533739
Ref: 核心与内置函数<27>-Footnote-172533783
Node: 库<29>2533827
Ref: whatsnew/changelog id2192533944
Ref: 11382533944
Ref: 库<29>-Footnote-12537649
Ref: 库<29>-Footnote-22537692
Ref: 库<29>-Footnote-32537735
Ref: 库<29>-Footnote-42537778
Ref: 库<29>-Footnote-52537821
Ref: 库<29>-Footnote-62537864
Ref: 库<29>-Footnote-72537907
Ref: 库<29>-Footnote-82537950
Ref: 库<29>-Footnote-92537993
Ref: 库<29>-Footnote-102538036
Ref: 库<29>-Footnote-112538080
Ref: 库<29>-Footnote-122538124
Ref: 库<29>-Footnote-132538168
Ref: 库<29>-Footnote-142538212
Ref: 库<29>-Footnote-152538256
Ref: 库<29>-Footnote-162538300
Ref: 库<29>-Footnote-172538344
Node: 文档<24>2538388
Ref: whatsnew/changelog id2202538490
Ref: 113c2538490
Ref: 文档<24>-Footnote-12538852
Ref: 文档<24>-Footnote-22538895
Ref: 文档<24>-Footnote-32538938
Node: 测试<23>2538981
Ref: whatsnew/changelog id2212539087
Ref: 113d2539087
Ref: 测试<23>-Footnote-12540463
Ref: 测试<23>-Footnote-22540506
Ref: 测试<23>-Footnote-32540549
Ref: 测试<23>-Footnote-42540592
Ref: 测试<23>-Footnote-52540635
Ref: 测试<23>-Footnote-62540678
Ref: 测试<23>-Footnote-72540721
Ref: 测试<23>-Footnote-82540764
Node: Windows<23>2540807
Ref: whatsnew/changelog id2222540911
Ref: 113f2540911
Ref: Windows<23>-Footnote-12541508
Ref: Windows<23>-Footnote-22541551
Ref: Windows<23>-Footnote-32541594
Ref: Windows<23>-Footnote-42541637
Ref: Windows<23>-Footnote-52541680
Node: IDLE<23>2541723
Ref: whatsnew/changelog id2232541808
Ref: 11402541808
Ref: IDLE<23>-Footnote-12542118
Ref: IDLE<23>-Footnote-22542161
Ref: IDLE<23>-Footnote-32542204
Node: Python 3 8 0 alpha 12542247
Ref: whatsnew/changelog python-3-8-0-alpha-12542391
Ref: 11412542391
Node: 安全性<18>2542768
Ref: whatsnew/changelog id2242542872
Ref: 11422542872
Ref: 安全性<18>-Footnote-12545192
Ref: 安全性<18>-Footnote-22545235
Ref: 安全性<18>-Footnote-32545278
Ref: 安全性<18>-Footnote-42545321
Ref: 安全性<18>-Footnote-52545364
Ref: 安全性<18>-Footnote-62545407
Ref: 安全性<18>-Footnote-72545450
Ref: 安全性<18>-Footnote-82545493
Ref: 安全性<18>-Footnote-92545536
Ref: 安全性<18>-Footnote-102545579
Ref: 安全性<18>-Footnote-112545623
Ref: 安全性<18>-Footnote-122545667
Node: 核心与内置函数<28>2545711
Ref: whatsnew/changelog id2252545831
Ref: 11432545831
Ref: 核心与内置函数<28>-Footnote-12571845
Ref: 核心与内置函数<28>-Footnote-22571888
Ref: 核心与内置函数<28>-Footnote-32571931
Ref: 核心与内置函数<28>-Footnote-42571974
Ref: 核心与内置函数<28>-Footnote-52572017
Ref: 核心与内置函数<28>-Footnote-62572060
Ref: 核心与内置函数<28>-Footnote-72572103
Ref: 核心与内置函数<28>-Footnote-82572146
Ref: 核心与内置函数<28>-Footnote-92572189
Ref: 核心与内置函数<28>-Footnote-102572232
Ref: 核心与内置函数<28>-Footnote-112572276
Ref: 核心与内置函数<28>-Footnote-122572320
Ref: 核心与内置函数<28>-Footnote-132572364
Ref: 核心与内置函数<28>-Footnote-142572408
Ref: 核心与内置函数<28>-Footnote-152572452
Ref: 核心与内置函数<28>-Footnote-162572496
Ref: 核心与内置函数<28>-Footnote-172572540
Ref: 核心与内置函数<28>-Footnote-182572584
Ref: 核心与内置函数<28>-Footnote-192572628
Ref: 核心与内置函数<28>-Footnote-202572672
Ref: 核心与内置函数<28>-Footnote-212572716
Ref: 核心与内置函数<28>-Footnote-222572760
Ref: 核心与内置函数<28>-Footnote-232572804
Ref: 核心与内置函数<28>-Footnote-242572848
Ref: 核心与内置函数<28>-Footnote-252572892
Ref: 核心与内置函数<28>-Footnote-262572942
Ref: 核心与内置函数<28>-Footnote-272572986
Ref: 核心与内置函数<28>-Footnote-282573030
Ref: 核心与内置函数<28>-Footnote-292573074
Ref: 核心与内置函数<28>-Footnote-302573118
Ref: 核心与内置函数<28>-Footnote-312573162
Ref: 核心与内置函数<28>-Footnote-322573206
Ref: 核心与内置函数<28>-Footnote-332573250
Ref: 核心与内置函数<28>-Footnote-342573294
Ref: 核心与内置函数<28>-Footnote-352573338
Ref: 核心与内置函数<28>-Footnote-362573382
Ref: 核心与内置函数<28>-Footnote-372573426
Ref: 核心与内置函数<28>-Footnote-382573470
Ref: 核心与内置函数<28>-Footnote-392573514
Ref: 核心与内置函数<28>-Footnote-402573558
Ref: 核心与内置函数<28>-Footnote-412573602
Ref: 核心与内置函数<28>-Footnote-422573646
Ref: 核心与内置函数<28>-Footnote-432573690
Ref: 核心与内置函数<28>-Footnote-442573734
Ref: 核心与内置函数<28>-Footnote-452573778
Ref: 核心与内置函数<28>-Footnote-462573822
Ref: 核心与内置函数<28>-Footnote-472573866
Ref: 核心与内置函数<28>-Footnote-482573910
Ref: 核心与内置函数<28>-Footnote-492573954
Ref: 核心与内置函数<28>-Footnote-502573998
Ref: 核心与内置函数<28>-Footnote-512574042
Ref: 核心与内置函数<28>-Footnote-522574086
Ref: 核心与内置函数<28>-Footnote-532574130
Ref: 核心与内置函数<28>-Footnote-542574174
Ref: 核心与内置函数<28>-Footnote-552574218
Ref: 核心与内置函数<28>-Footnote-562574262
Ref: 核心与内置函数<28>-Footnote-572574306
Ref: 核心与内置函数<28>-Footnote-582574350
Ref: 核心与内置函数<28>-Footnote-592574394
Ref: 核心与内置函数<28>-Footnote-602574437
Ref: 核心与内置函数<28>-Footnote-612574481
Ref: 核心与内置函数<28>-Footnote-622574525
Ref: 核心与内置函数<28>-Footnote-632574569
Ref: 核心与内置函数<28>-Footnote-642574613
Ref: 核心与内置函数<28>-Footnote-652574657
Ref: 核心与内置函数<28>-Footnote-662574701
Ref: 核心与内置函数<28>-Footnote-672574745
Ref: 核心与内置函数<28>-Footnote-682574789
Ref: 核心与内置函数<28>-Footnote-692574833
Ref: 核心与内置函数<28>-Footnote-702574877
Ref: 核心与内置函数<28>-Footnote-712574921
Ref: 核心与内置函数<28>-Footnote-722574965
Ref: 核心与内置函数<28>-Footnote-732575009
Ref: 核心与内置函数<28>-Footnote-742575053
Ref: 核心与内置函数<28>-Footnote-752575097
Ref: 核心与内置函数<28>-Footnote-762575141
Ref: 核心与内置函数<28>-Footnote-772575185
Ref: 核心与内置函数<28>-Footnote-782575229
Ref: 核心与内置函数<28>-Footnote-792575273
Ref: 核心与内置函数<28>-Footnote-802575317
Ref: 核心与内置函数<28>-Footnote-812575361
Ref: 核心与内置函数<28>-Footnote-822575405
Ref: 核心与内置函数<28>-Footnote-832575449
Ref: 核心与内置函数<28>-Footnote-842575493
Ref: 核心与内置函数<28>-Footnote-852575537
Ref: 核心与内置函数<28>-Footnote-862575581
Ref: 核心与内置函数<28>-Footnote-872575625
Ref: 核心与内置函数<28>-Footnote-882575669
Ref: 核心与内置函数<28>-Footnote-892575713
Ref: 核心与内置函数<28>-Footnote-902575757
Ref: 核心与内置函数<28>-Footnote-912575801
Ref: 核心与内置函数<28>-Footnote-922575845
Ref: 核心与内置函数<28>-Footnote-932575889
Ref: 核心与内置函数<28>-Footnote-942575933
Ref: 核心与内置函数<28>-Footnote-952575977
Ref: 核心与内置函数<28>-Footnote-962576021
Ref: 核心与内置函数<28>-Footnote-972576067
Ref: 核心与内置函数<28>-Footnote-982576111
Ref: 核心与内置函数<28>-Footnote-992576155
Ref: 核心与内置函数<28>-Footnote-1002576199
Ref: 核心与内置函数<28>-Footnote-1012576244
Ref: 核心与内置函数<28>-Footnote-1022576289
Ref: 核心与内置函数<28>-Footnote-1032576334
Ref: 核心与内置函数<28>-Footnote-1042576379
Ref: 核心与内置函数<28>-Footnote-1052576424
Ref: 核心与内置函数<28>-Footnote-1062576469
Ref: 核心与内置函数<28>-Footnote-1072576514
Ref: 核心与内置函数<28>-Footnote-1082576559
Ref: 核心与内置函数<28>-Footnote-1092576604
Ref: 核心与内置函数<28>-Footnote-1102576649
Ref: 核心与内置函数<28>-Footnote-1112576694
Ref: 核心与内置函数<28>-Footnote-1122576739
Ref: 核心与内置函数<28>-Footnote-1132576784
Ref: 核心与内置函数<28>-Footnote-1142576829
Ref: 核心与内置函数<28>-Footnote-1152576874
Ref: 核心与内置函数<28>-Footnote-1162576919
Ref: 核心与内置函数<28>-Footnote-1172576964
Ref: 核心与内置函数<28>-Footnote-1182577009
Ref: 核心与内置函数<28>-Footnote-1192577054
Ref: 核心与内置函数<28>-Footnote-1202577099
Ref: 核心与内置函数<28>-Footnote-1212577144
Ref: 核心与内置函数<28>-Footnote-1222577189
Ref: 核心与内置函数<28>-Footnote-1232577234
Ref: 核心与内置函数<28>-Footnote-1242577279
Ref: 核心与内置函数<28>-Footnote-1252577324
Ref: 核心与内置函数<28>-Footnote-1262577369
Ref: 核心与内置函数<28>-Footnote-1272577414
Ref: 核心与内置函数<28>-Footnote-1282577459
Ref: 核心与内置函数<28>-Footnote-1292577504
Ref: 核心与内置函数<28>-Footnote-1302577549
Ref: 核心与内置函数<28>-Footnote-1312577594
Ref: 核心与内置函数<28>-Footnote-1322577639
Ref: 核心与内置函数<28>-Footnote-1332577684
Ref: 核心与内置函数<28>-Footnote-1342577729
Ref: 核心与内置函数<28>-Footnote-1352577774
Ref: 核心与内置函数<28>-Footnote-1362577819
Ref: 核心与内置函数<28>-Footnote-1372577864
Ref: 核心与内置函数<28>-Footnote-1382577909
Ref: 核心与内置函数<28>-Footnote-1392577954
Ref: 核心与内置函数<28>-Footnote-1402577999
Ref: 核心与内置函数<28>-Footnote-1412578044
Ref: 核心与内置函数<28>-Footnote-1422578089
Ref: 核心与内置函数<28>-Footnote-1432578134
Ref: 核心与内置函数<28>-Footnote-1442578179
Ref: 核心与内置函数<28>-Footnote-1452578224
Ref: 核心与内置函数<28>-Footnote-1462578269
Ref: 核心与内置函数<28>-Footnote-1472578314
Ref: 核心与内置函数<28>-Footnote-1482578359
Ref: 核心与内置函数<28>-Footnote-1492578404
Ref: 核心与内置函数<28>-Footnote-1502578449
Ref: 核心与内置函数<28>-Footnote-1512578494
Ref: 核心与内置函数<28>-Footnote-1522578539
Ref: 核心与内置函数<28>-Footnote-1532578584
Ref: 核心与内置函数<28>-Footnote-1542578629
Ref: 核心与内置函数<28>-Footnote-1552578674
Ref: 核心与内置函数<28>-Footnote-1562578719
Ref: 核心与内置函数<28>-Footnote-1572578764
Ref: 核心与内置函数<28>-Footnote-1582578809
Ref: 核心与内置函数<28>-Footnote-1592578854
Ref: 核心与内置函数<28>-Footnote-1602578899
Ref: 核心与内置函数<28>-Footnote-1612578944
Ref: 核心与内置函数<28>-Footnote-1622578989
Node: 库<30>2579034
Ref: whatsnew/changelog id2262579151
Ref: 114c2579151
Ref: 库<30>-Footnote-12650299
Ref: 库<30>-Footnote-22650342
Ref: 库<30>-Footnote-32650385
Ref: 库<30>-Footnote-42650428
Ref: 库<30>-Footnote-52650471
Ref: 库<30>-Footnote-62650514
Ref: 库<30>-Footnote-72650557
Ref: 库<30>-Footnote-82650600
Ref: 库<30>-Footnote-92650643
Ref: 库<30>-Footnote-102650686
Ref: 库<30>-Footnote-112650730
Ref: 库<30>-Footnote-122650774
Ref: 库<30>-Footnote-132650818
Ref: 库<30>-Footnote-142650862
Ref: 库<30>-Footnote-152650906
Ref: 库<30>-Footnote-162650950
Ref: 库<30>-Footnote-172650994
Ref: 库<30>-Footnote-182651038
Ref: 库<30>-Footnote-192651082
Ref: 库<30>-Footnote-202651126
Ref: 库<30>-Footnote-212651170
Ref: 库<30>-Footnote-222651214
Ref: 库<30>-Footnote-232651258
Ref: 库<30>-Footnote-242651302
Ref: 库<30>-Footnote-252651346
Ref: 库<30>-Footnote-262651390
Ref: 库<30>-Footnote-272651434
Ref: 库<30>-Footnote-282651478
Ref: 库<30>-Footnote-292651522
Ref: 库<30>-Footnote-302651566
Ref: 库<30>-Footnote-312651610
Ref: 库<30>-Footnote-322651654
Ref: 库<30>-Footnote-332651698
Ref: 库<30>-Footnote-342651742
Ref: 库<30>-Footnote-352651786
Ref: 库<30>-Footnote-362651830
Ref: 库<30>-Footnote-372651874
Ref: 库<30>-Footnote-382651918
Ref: 库<30>-Footnote-392651962
Ref: 库<30>-Footnote-402652006
Ref: 库<30>-Footnote-412652050
Ref: 库<30>-Footnote-422652094
Ref: 库<30>-Footnote-432652138
Ref: 库<30>-Footnote-442652182
Ref: 库<30>-Footnote-452652226
Ref: 库<30>-Footnote-462652270
Ref: 库<30>-Footnote-472652314
Ref: 库<30>-Footnote-482652358
Ref: 库<30>-Footnote-492652402
Ref: 库<30>-Footnote-502652446
Ref: 库<30>-Footnote-512652490
Ref: 库<30>-Footnote-522652534
Ref: 库<30>-Footnote-532652578
Ref: 库<30>-Footnote-542652622
Ref: 库<30>-Footnote-552652666
Ref: 库<30>-Footnote-562652710
Ref: 库<30>-Footnote-572652754
Ref: 库<30>-Footnote-582652798
Ref: 库<30>-Footnote-592652842
Ref: 库<30>-Footnote-602652886
Ref: 库<30>-Footnote-612652930
Ref: 库<30>-Footnote-622652974
Ref: 库<30>-Footnote-632653018
Ref: 库<30>-Footnote-642653062
Ref: 库<30>-Footnote-652653106
Ref: 库<30>-Footnote-662653150
Ref: 库<30>-Footnote-672653194
Ref: 库<30>-Footnote-682653238
Ref: 库<30>-Footnote-692653282
Ref: 库<30>-Footnote-702653326
Ref: 库<30>-Footnote-712653370
Ref: 库<30>-Footnote-722653414
Ref: 库<30>-Footnote-732653458
Ref: 库<30>-Footnote-742653502
Ref: 库<30>-Footnote-752653546
Ref: 库<30>-Footnote-762653590
Ref: 库<30>-Footnote-772653634
Ref: 库<30>-Footnote-782653678
Ref: 库<30>-Footnote-792653722
Ref: 库<30>-Footnote-802653766
Ref: 库<30>-Footnote-812653810
Ref: 库<30>-Footnote-822653854
Ref: 库<30>-Footnote-832653898
Ref: 库<30>-Footnote-842653942
Ref: 库<30>-Footnote-852653986
Ref: 库<30>-Footnote-862654030
Ref: 库<30>-Footnote-872654074
Ref: 库<30>-Footnote-882654118
Ref: 库<30>-Footnote-892654162
Ref: 库<30>-Footnote-902654206
Ref: 库<30>-Footnote-912654250
Ref: 库<30>-Footnote-922654294
Ref: 库<30>-Footnote-932654338
Ref: 库<30>-Footnote-942654388
Ref: 库<30>-Footnote-952654432
Ref: 库<30>-Footnote-962654476
Ref: 库<30>-Footnote-972654520
Ref: 库<30>-Footnote-982654564
Ref: 库<30>-Footnote-992654608
Ref: 库<30>-Footnote-1002654652
Ref: 库<30>-Footnote-1012654697
Ref: 库<30>-Footnote-1022654742
Ref: 库<30>-Footnote-1032654787
Ref: 库<30>-Footnote-1042654832
Ref: 库<30>-Footnote-1052654877
Ref: 库<30>-Footnote-1062654922
Ref: 库<30>-Footnote-1072654967
Ref: 库<30>-Footnote-1082655012
Ref: 库<30>-Footnote-1092655057
Ref: 库<30>-Footnote-1102655102
Ref: 库<30>-Footnote-1112655147
Ref: 库<30>-Footnote-1122655192
Ref: 库<30>-Footnote-1132655237
Ref: 库<30>-Footnote-1142655282
Ref: 库<30>-Footnote-1152655327
Ref: 库<30>-Footnote-1162655372
Ref: 库<30>-Footnote-1172655417
Ref: 库<30>-Footnote-1182655462
Ref: 库<30>-Footnote-1192655507
Ref: 库<30>-Footnote-1202655552
Ref: 库<30>-Footnote-1212655597
Ref: 库<30>-Footnote-1222655642
Ref: 库<30>-Footnote-1232655687
Ref: 库<30>-Footnote-1242655732
Ref: 库<30>-Footnote-1252655777
Ref: 库<30>-Footnote-1262655821
Ref: 库<30>-Footnote-1272655866
Ref: 库<30>-Footnote-1282655911
Ref: 库<30>-Footnote-1292655956
Ref: 库<30>-Footnote-1302656001
Ref: 库<30>-Footnote-1312656046
Ref: 库<30>-Footnote-1322656091
Ref: 库<30>-Footnote-1332656136
Ref: 库<30>-Footnote-1342656181
Ref: 库<30>-Footnote-1352656226
Ref: 库<30>-Footnote-1362656271
Ref: 库<30>-Footnote-1372656315
Ref: 库<30>-Footnote-1382656360
Ref: 库<30>-Footnote-1392656405
Ref: 库<30>-Footnote-1402656450
Ref: 库<30>-Footnote-1412656495
Ref: 库<30>-Footnote-1422656540
Ref: 库<30>-Footnote-1432656585
Ref: 库<30>-Footnote-1442656630
Ref: 库<30>-Footnote-1452656675
Ref: 库<30>-Footnote-1462656720
Ref: 库<30>-Footnote-1472656765
Ref: 库<30>-Footnote-1482656810
Ref: 库<30>-Footnote-1492656855
Ref: 库<30>-Footnote-1502656900
Ref: 库<30>-Footnote-1512656945
Ref: 库<30>-Footnote-1522656990
Ref: 库<30>-Footnote-1532657035
Ref: 库<30>-Footnote-1542657080
Ref: 库<30>-Footnote-1552657124
Ref: 库<30>-Footnote-1562657169
Ref: 库<30>-Footnote-1572657214
Ref: 库<30>-Footnote-1582657259
Ref: 库<30>-Footnote-1592657304
Ref: 库<30>-Footnote-1602657349
Ref: 库<30>-Footnote-1612657394
Ref: 库<30>-Footnote-1622657439
Ref: 库<30>-Footnote-1632657484
Ref: 库<30>-Footnote-1642657529
Ref: 库<30>-Footnote-1652657573
Ref: 库<30>-Footnote-1662657618
Ref: 库<30>-Footnote-1672657663
Ref: 库<30>-Footnote-1682657708
Ref: 库<30>-Footnote-1692657753
Ref: 库<30>-Footnote-1702657798
Ref: 库<30>-Footnote-1712657843
Ref: 库<30>-Footnote-1722657888
Ref: 库<30>-Footnote-1732657933
Ref: 库<30>-Footnote-1742657977
Ref: 库<30>-Footnote-1752658022
Ref: 库<30>-Footnote-1762658067
Ref: 库<30>-Footnote-1772658112
Ref: 库<30>-Footnote-1782658157
Ref: 库<30>-Footnote-1792658202
Ref: 库<30>-Footnote-1802658246
Ref: 库<30>-Footnote-1812658291
Ref: 库<30>-Footnote-1822658336
Ref: 库<30>-Footnote-1832658381
Ref: 库<30>-Footnote-1842658426
Ref: 库<30>-Footnote-1852658471
Ref: 库<30>-Footnote-1862658516
Ref: 库<30>-Footnote-1872658561
Ref: 库<30>-Footnote-1882658606
Ref: 库<30>-Footnote-1892658651
Ref: 库<30>-Footnote-1902658696
Ref: 库<30>-Footnote-1912658741
Ref: 库<30>-Footnote-1922658786
Ref: 库<30>-Footnote-1932658831
Ref: 库<30>-Footnote-1942658876
Ref: 库<30>-Footnote-1952658921
Ref: 库<30>-Footnote-1962658966
Ref: 库<30>-Footnote-1972659011
Ref: 库<30>-Footnote-1982659056
Ref: 库<30>-Footnote-1992659101
Ref: 库<30>-Footnote-2002659146
Ref: 库<30>-Footnote-2012659191
Ref: 库<30>-Footnote-2022659237
Ref: 库<30>-Footnote-2032659282
Ref: 库<30>-Footnote-2042659327
Ref: 库<30>-Footnote-2052659372
Ref: 库<30>-Footnote-2062659417
Ref: 库<30>-Footnote-2072659462
Ref: 库<30>-Footnote-2082659507
Ref: 库<30>-Footnote-2092659552
Ref: 库<30>-Footnote-2102659597
Ref: 库<30>-Footnote-2112659642
Ref: 库<30>-Footnote-2122659687
Ref: 库<30>-Footnote-2132659738
Ref: 库<30>-Footnote-2142659783
Ref: 库<30>-Footnote-2152659828
Ref: 库<30>-Footnote-2162659873
Ref: 库<30>-Footnote-2172659918
Ref: 库<30>-Footnote-2182659963
Ref: 库<30>-Footnote-2192660008
Ref: 库<30>-Footnote-2202660053
Ref: 库<30>-Footnote-2212660098
Ref: 库<30>-Footnote-2222660143
Ref: 库<30>-Footnote-2232660188
Ref: 库<30>-Footnote-2242660233
Ref: 库<30>-Footnote-2252660278
Ref: 库<30>-Footnote-2262660323
Ref: 库<30>-Footnote-2272660368
Ref: 库<30>-Footnote-2282660413
Ref: 库<30>-Footnote-2292660458
Ref: 库<30>-Footnote-2302660503
Ref: 库<30>-Footnote-2312660548
Ref: 库<30>-Footnote-2322660593
Ref: 库<30>-Footnote-2332660638
Ref: 库<30>-Footnote-2342660683
Ref: 库<30>-Footnote-2352660728
Ref: 库<30>-Footnote-2362660773
Ref: 库<30>-Footnote-2372660818
Ref: 库<30>-Footnote-2382660863
Ref: 库<30>-Footnote-2392660908
Ref: 库<30>-Footnote-2402660953
Ref: 库<30>-Footnote-2412660998
Ref: 库<30>-Footnote-2422661043
Ref: 库<30>-Footnote-2432661088
Ref: 库<30>-Footnote-2442661133
Ref: 库<30>-Footnote-2452661178
Ref: 库<30>-Footnote-2462661223
Ref: 库<30>-Footnote-2472661268
Ref: 库<30>-Footnote-2482661313
Ref: 库<30>-Footnote-2492661358
Ref: 库<30>-Footnote-2502661403
Ref: 库<30>-Footnote-2512661448
Ref: 库<30>-Footnote-2522661493
Ref: 库<30>-Footnote-2532661538
Ref: 库<30>-Footnote-2542661583
Ref: 库<30>-Footnote-2552661628
Ref: 库<30>-Footnote-2562661673
Ref: 库<30>-Footnote-2572661718
Ref: 库<30>-Footnote-2582661763
Ref: 库<30>-Footnote-2592661808
Ref: 库<30>-Footnote-2602661852
Ref: 库<30>-Footnote-2612661897
Ref: 库<30>-Footnote-2622661942
Ref: 库<30>-Footnote-2632661987
Ref: 库<30>-Footnote-2642662032
Ref: 库<30>-Footnote-2652662077
Ref: 库<30>-Footnote-2662662122
Ref: 库<30>-Footnote-2672662167
Ref: 库<30>-Footnote-2682662212
Ref: 库<30>-Footnote-2692662257
Ref: 库<30>-Footnote-2702662302
Ref: 库<30>-Footnote-2712662347
Ref: 库<30>-Footnote-2722662392
Ref: 库<30>-Footnote-2732662437
Ref: 库<30>-Footnote-2742662482
Ref: 库<30>-Footnote-2752662527
Ref: 库<30>-Footnote-2762662572
Ref: 库<30>-Footnote-2772662617
Ref: 库<30>-Footnote-2782662662
Ref: 库<30>-Footnote-2792662707
Ref: 库<30>-Footnote-2802662752
Ref: 库<30>-Footnote-2812662797
Ref: 库<30>-Footnote-2822662842
Ref: 库<30>-Footnote-2832662887
Ref: 库<30>-Footnote-2842662932
Ref: 库<30>-Footnote-2852662977
Ref: 库<30>-Footnote-2862663022
Ref: 库<30>-Footnote-2872663067
Ref: 库<30>-Footnote-2882663112
Ref: 库<30>-Footnote-2892663157
Ref: 库<30>-Footnote-2902663202
Ref: 库<30>-Footnote-2912663247
Ref: 库<30>-Footnote-2922663292
Ref: 库<30>-Footnote-2932663337
Ref: 库<30>-Footnote-2942663382
Ref: 库<30>-Footnote-2952663427
Ref: 库<30>-Footnote-2962663472
Ref: 库<30>-Footnote-2972663517
Ref: 库<30>-Footnote-2982663562
Ref: 库<30>-Footnote-2992663607
Ref: 库<30>-Footnote-3002663652
Ref: 库<30>-Footnote-3012663697
Ref: 库<30>-Footnote-3022663742
Ref: 库<30>-Footnote-3032663787
Ref: 库<30>-Footnote-3042663832
Ref: 库<30>-Footnote-3052663877
Ref: 库<30>-Footnote-3062663922
Ref: 库<30>-Footnote-3072663967
Ref: 库<30>-Footnote-3082664012
Ref: 库<30>-Footnote-3092664057
Ref: 库<30>-Footnote-3102664102
Ref: 库<30>-Footnote-3112664147
Ref: 库<30>-Footnote-3122664192
Ref: 库<30>-Footnote-3132664237
Ref: 库<30>-Footnote-3142664282
Ref: 库<30>-Footnote-3152664327
Ref: 库<30>-Footnote-3162664372
Ref: 库<30>-Footnote-3172664417
Ref: 库<30>-Footnote-3182664462
Ref: 库<30>-Footnote-3192664507
Ref: 库<30>-Footnote-3202664552
Ref: 库<30>-Footnote-3212664597
Ref: 库<30>-Footnote-3222664642
Ref: 库<30>-Footnote-3232664687
Ref: 库<30>-Footnote-3242664732
Ref: 库<30>-Footnote-3252664777
Ref: 库<30>-Footnote-3262664822
Ref: 库<30>-Footnote-3272664867
Ref: 库<30>-Footnote-3282664913
Ref: 库<30>-Footnote-3292664958
Ref: 库<30>-Footnote-3302665003
Ref: 库<30>-Footnote-3312665048
Ref: 库<30>-Footnote-3322665093
Ref: 库<30>-Footnote-3332665138
Ref: 库<30>-Footnote-3342665183
Ref: 库<30>-Footnote-3352665228
Ref: 库<30>-Footnote-3362665273
Ref: 库<30>-Footnote-3372665318
Ref: 库<30>-Footnote-3382665363
Ref: 库<30>-Footnote-3392665408
Ref: 库<30>-Footnote-3402665453
Ref: 库<30>-Footnote-3412665498
Ref: 库<30>-Footnote-3422665543
Ref: 库<30>-Footnote-3432665588
Ref: 库<30>-Footnote-3442665633
Ref: 库<30>-Footnote-3452665684
Ref: 库<30>-Footnote-3462665729
Ref: 库<30>-Footnote-3472665774
Ref: 库<30>-Footnote-3482665819
Ref: 库<30>-Footnote-3492665870
Ref: 库<30>-Footnote-3502665915
Ref: 库<30>-Footnote-3512665960
Ref: 库<30>-Footnote-3522666005
Ref: 库<30>-Footnote-3532666050
Ref: 库<30>-Footnote-3542666095
Ref: 库<30>-Footnote-3552666140
Ref: 库<30>-Footnote-3562666185
Ref: 库<30>-Footnote-3572666230
Ref: 库<30>-Footnote-3582666275
Ref: 库<30>-Footnote-3592666320
Ref: 库<30>-Footnote-3602666365
Ref: 库<30>-Footnote-3612666410
Ref: 库<30>-Footnote-3622666455
Ref: 库<30>-Footnote-3632666500
Ref: 库<30>-Footnote-3642666545
Ref: 库<30>-Footnote-3652666590
Ref: 库<30>-Footnote-3662666635
Ref: 库<30>-Footnote-3672666680
Ref: 库<30>-Footnote-3682666725
Ref: 库<30>-Footnote-3692666770
Ref: 库<30>-Footnote-3702666815
Ref: 库<30>-Footnote-3712666860
Ref: 库<30>-Footnote-3722666905
Ref: 库<30>-Footnote-3732666950
Ref: 库<30>-Footnote-3742666995
Ref: 库<30>-Footnote-3752667040
Ref: 库<30>-Footnote-3762667085
Ref: 库<30>-Footnote-3772667130
Ref: 库<30>-Footnote-3782667175
Ref: 库<30>-Footnote-3792667220
Ref: 库<30>-Footnote-3802667265
Ref: 库<30>-Footnote-3812667310
Ref: 库<30>-Footnote-3822667355
Ref: 库<30>-Footnote-3832667400
Ref: 库<30>-Footnote-3842667445
Ref: 库<30>-Footnote-3852667490
Ref: 库<30>-Footnote-3862667535
Ref: 库<30>-Footnote-3872667580
Ref: 库<30>-Footnote-3882667625
Ref: 库<30>-Footnote-3892667670
Ref: 库<30>-Footnote-3902667715
Ref: 库<30>-Footnote-3912667760
Ref: 库<30>-Footnote-3922667805
Ref: 库<30>-Footnote-3932667850
Ref: 库<30>-Footnote-3942667895
Ref: 库<30>-Footnote-3952667940
Ref: 库<30>-Footnote-3962667985
Ref: 库<30>-Footnote-3972668030
Ref: 库<30>-Footnote-3982668075
Ref: 库<30>-Footnote-3992668120
Ref: 库<30>-Footnote-4002668165
Ref: 库<30>-Footnote-4012668210
Ref: 库<30>-Footnote-4022668255
Ref: 库<30>-Footnote-4032668300
Ref: 库<30>-Footnote-4042668345
Ref: 库<30>-Footnote-4052668390
Ref: 库<30>-Footnote-4062668435
Ref: 库<30>-Footnote-4072668480
Ref: 库<30>-Footnote-4082668525
Ref: 库<30>-Footnote-4092668570
Ref: 库<30>-Footnote-4102668615
Ref: 库<30>-Footnote-4112668660
Ref: 库<30>-Footnote-4122668705
Ref: 库<30>-Footnote-4132668750
Ref: 库<30>-Footnote-4142668795
Ref: 库<30>-Footnote-4152668840
Ref: 库<30>-Footnote-4162668885
Ref: 库<30>-Footnote-4172668930
Ref: 库<30>-Footnote-4182668975
Ref: 库<30>-Footnote-4192669020
Ref: 库<30>-Footnote-4202669065
Ref: 库<30>-Footnote-4212669110
Ref: 库<30>-Footnote-4222669154
Ref: 库<30>-Footnote-4232669199
Ref: 库<30>-Footnote-4242669244
Ref: 库<30>-Footnote-4252669289
Ref: 库<30>-Footnote-4262669334
Ref: 库<30>-Footnote-4272669379
Ref: 库<30>-Footnote-4282669424
Ref: 库<30>-Footnote-4292669469
Ref: 库<30>-Footnote-4302669514
Ref: 库<30>-Footnote-4312669559
Ref: 库<30>-Footnote-4322669604
Ref: 库<30>-Footnote-4332669649
Ref: 库<30>-Footnote-4342669694
Ref: 库<30>-Footnote-4352669739
Ref: 库<30>-Footnote-4362669784
Node: 文档<25>2669829
Ref: whatsnew/changelog id2272669931
Ref: 11752669931
Ref: 文档<25>-Footnote-12676626
Ref: 文档<25>-Footnote-22676669
Ref: 文档<25>-Footnote-32676712
Ref: 文档<25>-Footnote-42676755
Ref: 文档<25>-Footnote-52676798
Ref: 文档<25>-Footnote-62676841
Ref: 文档<25>-Footnote-72676884
Ref: 文档<25>-Footnote-82676927
Ref: 文档<25>-Footnote-92676970
Ref: 文档<25>-Footnote-102677013
Ref: 文档<25>-Footnote-112677057
Ref: 文档<25>-Footnote-122677101
Ref: 文档<25>-Footnote-132677145
Ref: 文档<25>-Footnote-142677189
Ref: 文档<25>-Footnote-152677233
Ref: 文档<25>-Footnote-162677277
Ref: 文档<25>-Footnote-172677321
Ref: 文档<25>-Footnote-182677365
Ref: 文档<25>-Footnote-192677409
Ref: 文档<25>-Footnote-202677453
Ref: 文档<25>-Footnote-212677497
Ref: 文档<25>-Footnote-222677541
Ref: 文档<25>-Footnote-232677585
Ref: 文档<25>-Footnote-242677635
Ref: 文档<25>-Footnote-252677679
Ref: 文档<25>-Footnote-262677723
Ref: 文档<25>-Footnote-272677767
Ref: 文档<25>-Footnote-282677811
Ref: 文档<25>-Footnote-292677855
Ref: 文档<25>-Footnote-302677905
Ref: 文档<25>-Footnote-312677949
Ref: 文档<25>-Footnote-322677993
Ref: 文档<25>-Footnote-332678037
Ref: 文档<25>-Footnote-342678081
Ref: 文档<25>-Footnote-352678125
Ref: 文档<25>-Footnote-362678169
Ref: 文档<25>-Footnote-372678213
Ref: 文档<25>-Footnote-382678257
Ref: 文档<25>-Footnote-392678301
Ref: 文档<25>-Footnote-402678345
Ref: 文档<25>-Footnote-412678389
Ref: 文档<25>-Footnote-422678433
Ref: 文档<25>-Footnote-432678477
Ref: 文档<25>-Footnote-442678521
Ref: 文档<25>-Footnote-452678565
Ref: 文档<25>-Footnote-462678609
Ref: 文档<25>-Footnote-472678653
Ref: 文档<25>-Footnote-482678697
Ref: 文档<25>-Footnote-492678741
Ref: 文档<25>-Footnote-502678785
Ref: 文档<25>-Footnote-512678828
Ref: 文档<25>-Footnote-522678872
Ref: 文档<25>-Footnote-532678916
Ref: 文档<25>-Footnote-542678960
Ref: 文档<25>-Footnote-552679004
Ref: 文档<25>-Footnote-562679048
Ref: 文档<25>-Footnote-572679091
Ref: 文档<25>-Footnote-582679135
Ref: 文档<25>-Footnote-592679179
Node: 测试<24>2679223
Ref: whatsnew/changelog id2282679328
Ref: 11772679328
Ref: 测试<24>-Footnote-12686917
Ref: 测试<24>-Footnote-22686960
Ref: 测试<24>-Footnote-32687003
Ref: 测试<24>-Footnote-42687046
Ref: 测试<24>-Footnote-52687089
Ref: 测试<24>-Footnote-62687132
Ref: 测试<24>-Footnote-72687175
Ref: 测试<24>-Footnote-82687218
Ref: 测试<24>-Footnote-92687261
Ref: 测试<24>-Footnote-102687304
Ref: 测试<24>-Footnote-112687348
Ref: 测试<24>-Footnote-122687392
Ref: 测试<24>-Footnote-132687436
Ref: 测试<24>-Footnote-142687480
Ref: 测试<24>-Footnote-152687524
Ref: 测试<24>-Footnote-162687568
Ref: 测试<24>-Footnote-172687612
Ref: 测试<24>-Footnote-182687656
Ref: 测试<24>-Footnote-192687700
Ref: 测试<24>-Footnote-202687744
Ref: 测试<24>-Footnote-212687788
Ref: 测试<24>-Footnote-222687832
Ref: 测试<24>-Footnote-232687876
Ref: 测试<24>-Footnote-242687920
Ref: 测试<24>-Footnote-252687964
Ref: 测试<24>-Footnote-262688008
Ref: 测试<24>-Footnote-272688052
Ref: 测试<24>-Footnote-282688096
Ref: 测试<24>-Footnote-292688140
Ref: 测试<24>-Footnote-302688184
Ref: 测试<24>-Footnote-312688228
Ref: 测试<24>-Footnote-322688272
Ref: 测试<24>-Footnote-332688316
Ref: 测试<24>-Footnote-342688360
Ref: 测试<24>-Footnote-352688404
Ref: 测试<24>-Footnote-362688448
Ref: 测试<24>-Footnote-372688492
Ref: 测试<24>-Footnote-382688536
Ref: 测试<24>-Footnote-392688580
Ref: 测试<24>-Footnote-402688624
Ref: 测试<24>-Footnote-412688668
Ref: 测试<24>-Footnote-422688712
Ref: 测试<24>-Footnote-432688756
Ref: 测试<24>-Footnote-442688800
Ref: 测试<24>-Footnote-452688844
Ref: 测试<24>-Footnote-462688888
Ref: 测试<24>-Footnote-472688932
Ref: 测试<24>-Footnote-482688976
Node: 构建<23>2689020
Ref: whatsnew/changelog id2292689126
Ref: 11792689126
Ref: 构建<23>-Footnote-12694239
Ref: 构建<23>-Footnote-22694282
Ref: 构建<23>-Footnote-32694325
Ref: 构建<23>-Footnote-42694368
Ref: 构建<23>-Footnote-52694411
Ref: 构建<23>-Footnote-62694454
Ref: 构建<23>-Footnote-72694497
Ref: 构建<23>-Footnote-82694540
Ref: 构建<23>-Footnote-92694583
Ref: 构建<23>-Footnote-102694626
Ref: 构建<23>-Footnote-112694670
Ref: 构建<23>-Footnote-122694714
Ref: 构建<23>-Footnote-132694758
Ref: 构建<23>-Footnote-142694802
Ref: 构建<23>-Footnote-152694846
Ref: 构建<23>-Footnote-162694890
Ref: 构建<23>-Footnote-172694934
Ref: 构建<23>-Footnote-182694978
Ref: 构建<23>-Footnote-192695022
Ref: 构建<23>-Footnote-202695066
Ref: 构建<23>-Footnote-212695110
Ref: 构建<23>-Footnote-222695154
Ref: 构建<23>-Footnote-232695198
Ref: 构建<23>-Footnote-242695241
Ref: 构建<23>-Footnote-252695285
Ref: 构建<23>-Footnote-262695329
Ref: 构建<23>-Footnote-272695373
Ref: 构建<23>-Footnote-282695417
Ref: 构建<23>-Footnote-292695461
Ref: 构建<23>-Footnote-302695505
Ref: 构建<23>-Footnote-312695549
Ref: 构建<23>-Footnote-322695593
Ref: 构建<23>-Footnote-332695637
Ref: 构建<23>-Footnote-342695681
Ref: 构建<23>-Footnote-352695725
Ref: 构建<23>-Footnote-362695769
Ref: 构建<23>-Footnote-372695813
Node: Windows<24>2695857
Ref: whatsnew/changelog id2302695962
Ref: 117a2695962
Ref: Windows<24>-Footnote-12700398
Ref: Windows<24>-Footnote-22700441
Ref: Windows<24>-Footnote-32700484
Ref: Windows<24>-Footnote-42700527
Ref: Windows<24>-Footnote-52700570
Ref: Windows<24>-Footnote-62700613
Ref: Windows<24>-Footnote-72700656
Ref: Windows<24>-Footnote-82700699
Ref: Windows<24>-Footnote-92700742
Ref: Windows<24>-Footnote-102700785
Ref: Windows<24>-Footnote-112700829
Ref: Windows<24>-Footnote-122700873
Ref: Windows<24>-Footnote-132700917
Ref: Windows<24>-Footnote-142700961
Ref: Windows<24>-Footnote-152701005
Ref: Windows<24>-Footnote-162701049
Ref: Windows<24>-Footnote-172701093
Ref: Windows<24>-Footnote-182701137
Ref: Windows<24>-Footnote-192701181
Ref: Windows<24>-Footnote-202701225
Ref: Windows<24>-Footnote-212701269
Ref: Windows<24>-Footnote-222701313
Ref: Windows<24>-Footnote-232701357
Ref: Windows<24>-Footnote-242701401
Ref: Windows<24>-Footnote-252701445
Ref: Windows<24>-Footnote-262701489
Ref: Windows<24>-Footnote-272701533
Ref: Windows<24>-Footnote-282701577
Ref: Windows<24>-Footnote-292701621
Ref: Windows<24>-Footnote-302701665
Ref: Windows<24>-Footnote-312701709
Ref: Windows<24>-Footnote-322701753
Ref: Windows<24>-Footnote-332701797
Ref: Windows<24>-Footnote-342701841
Ref: Windows<24>-Footnote-352701885
Ref: Windows<24>-Footnote-362701929
Ref: Windows<24>-Footnote-372701973
Ref: Windows<24>-Footnote-382702017
Ref: Windows<24>-Footnote-392702061
Ref: Windows<24>-Footnote-402702105
Node: macOS<20>2702148
Ref: whatsnew/changelog id2312702251
Ref: 117b2702251
Ref: macOS<20>-Footnote-12703864
Ref: macOS<20>-Footnote-22703907
Ref: macOS<20>-Footnote-32703950
Ref: macOS<20>-Footnote-42703993
Ref: macOS<20>-Footnote-52704036
Ref: macOS<20>-Footnote-62704079
Ref: macOS<20>-Footnote-72704122
Ref: macOS<20>-Footnote-82704165
Ref: macOS<20>-Footnote-92704208
Ref: macOS<20>-Footnote-102704251
Node: IDLE<24>2704295
Ref: whatsnew/changelog id2322704404
Ref: 117c2704404
Ref: IDLE<24>-Footnote-12712811
Ref: IDLE<24>-Footnote-22712854
Ref: IDLE<24>-Footnote-32712897
Ref: IDLE<24>-Footnote-42712940
Ref: IDLE<24>-Footnote-52712983
Ref: IDLE<24>-Footnote-62713026
Ref: IDLE<24>-Footnote-72713069
Ref: IDLE<24>-Footnote-82713112
Ref: IDLE<24>-Footnote-92713155
Ref: IDLE<24>-Footnote-102713198
Ref: IDLE<24>-Footnote-112713242
Ref: IDLE<24>-Footnote-122713286
Ref: IDLE<24>-Footnote-132713330
Ref: IDLE<24>-Footnote-142713374
Ref: IDLE<24>-Footnote-152713418
Ref: IDLE<24>-Footnote-162713462
Ref: IDLE<24>-Footnote-172713506
Ref: IDLE<24>-Footnote-182713550
Ref: IDLE<24>-Footnote-192713594
Ref: IDLE<24>-Footnote-202713638
Ref: IDLE<24>-Footnote-212713682
Ref: IDLE<24>-Footnote-222713726
Ref: IDLE<24>-Footnote-232713770
Ref: IDLE<24>-Footnote-242713814
Ref: IDLE<24>-Footnote-252713858
Ref: IDLE<24>-Footnote-262713902
Ref: IDLE<24>-Footnote-272713946
Ref: IDLE<24>-Footnote-282713992
Ref: IDLE<24>-Footnote-292714036
Ref: IDLE<24>-Footnote-302714080
Ref: IDLE<24>-Footnote-312714124
Ref: IDLE<24>-Footnote-322714168
Ref: IDLE<24>-Footnote-332714212
Ref: IDLE<24>-Footnote-342714256
Ref: IDLE<24>-Footnote-352714300
Ref: IDLE<24>-Footnote-362714344
Ref: IDLE<24>-Footnote-372714388
Ref: IDLE<24>-Footnote-382714432
Ref: IDLE<24>-Footnote-392714476
Ref: IDLE<24>-Footnote-402714520
Ref: IDLE<24>-Footnote-412714564
Ref: IDLE<24>-Footnote-422714608
Ref: IDLE<24>-Footnote-432714652
Ref: IDLE<24>-Footnote-442714696
Ref: IDLE<24>-Footnote-452714740
Ref: IDLE<24>-Footnote-462714784
Ref: IDLE<24>-Footnote-472714828
Ref: IDLE<24>-Footnote-482714872
Ref: IDLE<24>-Footnote-492714916
Ref: IDLE<24>-Footnote-502714960
Ref: IDLE<24>-Footnote-512715004
Ref: IDLE<24>-Footnote-522715048
Ref: IDLE<24>-Footnote-532715092
Ref: IDLE<24>-Footnote-542715136
Ref: IDLE<24>-Footnote-552715180
Ref: IDLE<24>-Footnote-562715224
Ref: IDLE<24>-Footnote-572715268
Ref: IDLE<24>-Footnote-582715312
Ref: IDLE<24>-Footnote-592715356
Node: 工具/示例<11>2715400
Ref: whatsnew/changelog id2332715509
Ref: 117d2715509
Ref: 工具/示例<11>-Footnote-12717158
Ref: 工具/示例<11>-Footnote-22717201
Ref: 工具/示例<11>-Footnote-32717244
Ref: 工具/示例<11>-Footnote-42717287
Ref: 工具/示例<11>-Footnote-52717330
Ref: 工具/示例<11>-Footnote-62717373
Ref: 工具/示例<11>-Footnote-72717416
Ref: 工具/示例<11>-Footnote-82717459
Ref: 工具/示例<11>-Footnote-92717502
Ref: 工具/示例<11>-Footnote-102717545
Ref: 工具/示例<11>-Footnote-112717589
Ref: 工具/示例<11>-Footnote-122717633
Node: C API<20>2717677
Ref: whatsnew/changelog id2342717769
Ref: 117e2717769
Ref: C API<20>-Footnote-12721179
Ref: C API<20>-Footnote-22721222
Ref: C API<20>-Footnote-32721265
Ref: C API<20>-Footnote-42721308
Ref: C API<20>-Footnote-52721351
Ref: C API<20>-Footnote-62721394
Ref: C API<20>-Footnote-72721437
Ref: C API<20>-Footnote-82721480
Ref: C API<20>-Footnote-92721523
Ref: C API<20>-Footnote-102721566
Ref: C API<20>-Footnote-112721610
Ref: C API<20>-Footnote-122721654
Ref: C API<20>-Footnote-132721698
Ref: C API<20>-Footnote-142721742
Ref: C API<20>-Footnote-152721786
Ref: C API<20>-Footnote-162721830
Ref: C API<20>-Footnote-172721874
Ref: C API<20>-Footnote-182721918
Ref: C API<20>-Footnote-192721962
Ref: C API<20>-Footnote-202722006
Ref: C API<20>-Footnote-212722050
Ref: C API<20>-Footnote-222722094
Node: Python 3 7 0 正式版2722138
Ref: whatsnew/changelog python-3-7-0-final2722278
Ref: 11882722278
Node: 库<31>2722412
Ref: whatsnew/changelog id2352722496
Ref: 11892722496
Ref: 库<31>-Footnote-12722657
Node: C API<21>2722700
Ref: whatsnew/changelog id2362722784
Ref: 118b2722784
Ref: C API<21>-Footnote-12722995
Node: Python 3 7 0 rc12723038
Ref: whatsnew/changelog python-3-7-0-release-candidate-12723177
Ref: 118c2723177
Node: 核心与内置函数<29>2723420
Ref: whatsnew/changelog id2372723514
Ref: 118d2723514
Ref: 核心与内置函数<29>-Footnote-12724159
Ref: 核心与内置函数<29>-Footnote-22724202
Ref: 核心与内置函数<29>-Footnote-32724245
Ref: 核心与内置函数<29>-Footnote-42724288
Node: 库<32>2724331
Ref: whatsnew/changelog id2382724444
Ref: 118e2724444
Ref: 库<32>-Footnote-12726133
Ref: 库<32>-Footnote-22726176
Ref: 库<32>-Footnote-32726219
Ref: 库<32>-Footnote-42726262
Ref: 库<32>-Footnote-52726305
Ref: 库<32>-Footnote-62726348
Ref: 库<32>-Footnote-72726391
Ref: 库<32>-Footnote-82726434
Ref: 库<32>-Footnote-92726477
Ref: 库<32>-Footnote-102726520
Ref: 库<32>-Footnote-112726564
Ref: 库<32>-Footnote-122726608
Ref: 库<32>-Footnote-132726652
Node: 文档<26>2726696
Ref: whatsnew/changelog id2392726794
Ref: 118f2726794
Ref: 文档<26>-Footnote-12727285
Ref: 文档<26>-Footnote-22727328
Ref: 文档<26>-Footnote-32727377
Ref: 文档<26>-Footnote-42727420
Node: 构建<24>2727463
Ref: whatsnew/changelog id2402727565
Ref: 11902727565
Ref: 构建<24>-Footnote-12727827
Node: Windows<25>2727869
Ref: whatsnew/changelog id2412727969
Ref: 11912727969
Ref: Windows<25>-Footnote-12728126
Node: IDLE<25>2728169
Ref: whatsnew/changelog id2422728250
Ref: 11922728250
Ref: IDLE<25>-Footnote-12729470
Ref: IDLE<25>-Footnote-22729513
Ref: IDLE<25>-Footnote-32729556
Ref: IDLE<25>-Footnote-42729599
Ref: IDLE<25>-Footnote-52729642
Ref: IDLE<25>-Footnote-62729685
Node: Python 3 7 0 beta 52729728
Ref: whatsnew/changelog python-3-7-0-beta-52729864
Ref: 11932729864
Node: 核心与内置函数<30>2730131
Ref: whatsnew/changelog id2432730228
Ref: 11942730228
Ref: 核心与内置函数<30>-Footnote-12731749
Ref: 核心与内置函数<30>-Footnote-22731792
Ref: 核心与内置函数<30>-Footnote-32731835
Ref: 核心与内置函数<30>-Footnote-42731878
Ref: 核心与内置函数<30>-Footnote-52731921
Ref: 核心与内置函数<30>-Footnote-62731964
Ref: 核心与内置函数<30>-Footnote-72732007
Ref: 核心与内置函数<30>-Footnote-82732050
Ref: 核心与内置函数<30>-Footnote-92732093
Node: 库<33>2732136
Ref: whatsnew/changelog id2442732252
Ref: 11952732252
Ref: 库<33>-Footnote-12737858
Ref: 库<33>-Footnote-22737901
Ref: 库<33>-Footnote-32737944
Ref: 库<33>-Footnote-42737987
Ref: 库<33>-Footnote-52738030
Ref: 库<33>-Footnote-62738073
Ref: 库<33>-Footnote-72738116
Ref: 库<33>-Footnote-82738159
Ref: 库<33>-Footnote-92738202
Ref: 库<33>-Footnote-102738245
Ref: 库<33>-Footnote-112738289
Ref: 库<33>-Footnote-122738333
Ref: 库<33>-Footnote-132738377
Ref: 库<33>-Footnote-142738421
Ref: 库<33>-Footnote-152738465
Ref: 库<33>-Footnote-162738509
Ref: 库<33>-Footnote-172738553
Ref: 库<33>-Footnote-182738597
Ref: 库<33>-Footnote-192738641
Ref: 库<33>-Footnote-202738685
Ref: 库<33>-Footnote-212738729
Ref: 库<33>-Footnote-222738773
Ref: 库<33>-Footnote-232738817
Ref: 库<33>-Footnote-242738861
Ref: 库<33>-Footnote-252738905
Ref: 库<33>-Footnote-262738949
Ref: 库<33>-Footnote-272738993
Ref: 库<33>-Footnote-282739037
Ref: 库<33>-Footnote-292739081
Ref: 库<33>-Footnote-302739125
Ref: 库<33>-Footnote-312739169
Ref: 库<33>-Footnote-322739213
Ref: 库<33>-Footnote-332739257
Ref: 库<33>-Footnote-342739301
Ref: 库<33>-Footnote-352739345
Ref: 库<33>-Footnote-362739389
Ref: 库<33>-Footnote-372739433
Ref: 库<33>-Footnote-382739477
Node: 文档<27>2739521
Ref: whatsnew/changelog id2452739622
Ref: 11962739622
Ref: 文档<27>-Footnote-12740084
Ref: 文档<27>-Footnote-22740127
Ref: 文档<27>-Footnote-32740170
Ref: 文档<27>-Footnote-42740219
Ref: 文档<27>-Footnote-52740262
Ref: 文档<27>-Footnote-62740305
Node: 测试<25>2740348
Ref: whatsnew/changelog id2462740452
Ref: 11972740452
Ref: 测试<25>-Footnote-12740765
Ref: 测试<25>-Footnote-22740808
Node: 构建<25>2740851
Ref: whatsnew/changelog id2472740954
Ref: 11982740954
Ref: 构建<25>-Footnote-12741433
Ref: 构建<25>-Footnote-22741476
Ref: 构建<25>-Footnote-32741519
Node: macOS<21>2741562
Ref: whatsnew/changelog id2482741663
Ref: 11992741663
Ref: macOS<21>-Footnote-12741905
Node: IDLE<26>2741948
Ref: whatsnew/changelog id2492742030
Ref: 119a2742030
Ref: IDLE<26>-Footnote-12742309
Ref: IDLE<26>-Footnote-22742352
Ref: IDLE<26>-Footnote-32742395
Node: Python 3 7 0 beta 42742438
Ref: whatsnew/changelog python-3-7-0-beta-42742577
Ref: 119b2742577
Node: 核心与内置函数<31>2742904
Ref: whatsnew/changelog id2502743001
Ref: 119c2743001
Ref: 核心与内置函数<31>-Footnote-12744145
Ref: 核心与内置函数<31>-Footnote-22744188
Ref: 核心与内置函数<31>-Footnote-32744231
Ref: 核心与内置函数<31>-Footnote-42744274
Ref: 核心与内置函数<31>-Footnote-52744317
Ref: 核心与内置函数<31>-Footnote-62744360
Ref: 核心与内置函数<31>-Footnote-72744403
Node: 库<34>2744446
Ref: whatsnew/changelog id2512744562
Ref: 119d2744562
Ref: 库<34>-Footnote-12747396
Ref: 库<34>-Footnote-22747439
Ref: 库<34>-Footnote-32747482
Ref: 库<34>-Footnote-42747525
Ref: 库<34>-Footnote-52747569
Ref: 库<34>-Footnote-62747612
Ref: 库<34>-Footnote-72747655
Ref: 库<34>-Footnote-82747698
Ref: 库<34>-Footnote-92747741
Ref: 库<34>-Footnote-102747784
Ref: 库<34>-Footnote-112747828
Ref: 库<34>-Footnote-122747872
Ref: 库<34>-Footnote-132747916
Ref: 库<34>-Footnote-142747960
Ref: 库<34>-Footnote-152748004
Ref: 库<34>-Footnote-162748048
Ref: 库<34>-Footnote-172748092
Ref: 库<34>-Footnote-182748142
Ref: 库<34>-Footnote-192748186
Ref: 库<34>-Footnote-202748230
Ref: 库<34>-Footnote-212748274
Ref: 库<34>-Footnote-222748318
Node: 文档<28>2748362
Ref: whatsnew/changelog id2522748463
Ref: 119e2748463
Ref: 文档<28>-Footnote-12749198
Ref: 文档<28>-Footnote-22749241
Ref: 文档<28>-Footnote-32749284
Ref: 文档<28>-Footnote-42749327
Ref: 文档<28>-Footnote-52749370
Ref: 文档<28>-Footnote-62749412
Node: 测试<26>2749455
Ref: whatsnew/changelog id2532749559
Ref: 119f2749559
Ref: 测试<26>-Footnote-12749775
Node: 构建<26>2749818
Ref: whatsnew/changelog id2542749923
Ref: 11a02749923
Ref: 构建<26>-Footnote-12750613
Ref: 构建<26>-Footnote-22750656
Ref: 构建<26>-Footnote-32750699
Ref: 构建<26>-Footnote-42750742
Ref: 构建<26>-Footnote-52750785
Node: Windows<26>2750828
Ref: whatsnew/changelog id2552750932
Ref: 11a12750932
Ref: Windows<26>-Footnote-12751077
Node: macOS<22>2751120
Ref: whatsnew/changelog id2562751222
Ref: 11a22751222
Ref: macOS<22>-Footnote-12751363
Node: IDLE<27>2751406
Ref: whatsnew/changelog id2572751514
Ref: 11a32751514
Ref: IDLE<27>-Footnote-12752104
Ref: IDLE<27>-Footnote-22752147
Node: 工具/示例<12>2752190
Ref: whatsnew/changelog id2582752280
Ref: 11a42752280
Ref: 工具/示例<12>-Footnote-12752888
Ref: 工具/示例<12>-Footnote-22752931
Ref: 工具/示例<12>-Footnote-32752974
Ref: 工具/示例<12>-Footnote-42753017
Node: Python 3 7 0 beta 32753060
Ref: whatsnew/changelog python-3-7-0-beta-32753199
Ref: 11a52753199
Node: 安全性<19>2753574
Ref: whatsnew/changelog id2592753677
Ref: 11a62753677
Ref: 安全性<19>-Footnote-12754299
Ref: 安全性<19>-Footnote-22754342
Ref: 安全性<19>-Footnote-32754385
Node: 核心与内置函数<32>2754428
Ref: whatsnew/changelog id2602754547
Ref: 11a72754547
Ref: 核心与内置函数<32>-Footnote-12755754
Ref: 核心与内置函数<32>-Footnote-22755797
Ref: 核心与内置函数<32>-Footnote-32755840
Ref: 核心与内置函数<32>-Footnote-42755883
Ref: 核心与内置函数<32>-Footnote-52755926
Ref: 核心与内置函数<32>-Footnote-62755969
Ref: 核心与内置函数<32>-Footnote-72756012
Node: 库<35>2756055
Ref: whatsnew/changelog id2612756171
Ref: 11a82756171
Ref: 库<35>-Footnote-12760212
Ref: 库<35>-Footnote-22760255
Ref: 库<35>-Footnote-32760298
Ref: 库<35>-Footnote-42760341
Ref: 库<35>-Footnote-52760384
Ref: 库<35>-Footnote-62760427
Ref: 库<35>-Footnote-72760470
Ref: 库<35>-Footnote-82760513
Ref: 库<35>-Footnote-92760556
Ref: 库<35>-Footnote-102760599
Ref: 库<35>-Footnote-112760643
Ref: 库<35>-Footnote-122760687
Ref: 库<35>-Footnote-132760731
Ref: 库<35>-Footnote-142760775
Ref: 库<35>-Footnote-152760819
Ref: 库<35>-Footnote-162760863
Ref: 库<35>-Footnote-172760907
Ref: 库<35>-Footnote-182760951
Ref: 库<35>-Footnote-192760995
Ref: 库<35>-Footnote-202761039
Ref: 库<35>-Footnote-212761083
Ref: 库<35>-Footnote-222761127
Ref: 库<35>-Footnote-232761171
Ref: 库<35>-Footnote-242761215
Ref: 库<35>-Footnote-252761259
Ref: 库<35>-Footnote-262761303
Ref: 库<35>-Footnote-272761347
Node: 文档<29>2761391
Ref: whatsnew/changelog id2622761492
Ref: 11a92761492
Ref: 文档<29>-Footnote-12762113
Ref: 文档<29>-Footnote-22762156
Ref: 文档<29>-Footnote-32762199
Ref: 文档<29>-Footnote-42762242
Ref: 文档<29>-Footnote-52762285
Node: 测试<27>2762328
Ref: whatsnew/changelog id2632762432
Ref: 11aa2762432
Ref: 测试<27>-Footnote-12762765
Ref: 测试<27>-Footnote-22762808
Ref: 测试<27>-Footnote-32762851
Node: 构建<27>2762894
Ref: whatsnew/changelog id2642762999
Ref: 11ab2762999
Ref: 构建<27>-Footnote-12763136
Node: Windows<27>2763179
Ref: whatsnew/changelog id2652763283
Ref: 11ac2763283
Ref: Windows<27>-Footnote-12763562
Ref: Windows<27>-Footnote-22763605
Node: macOS<23>2763648
Ref: whatsnew/changelog id2662763750
Ref: 11ad2763750
Ref: macOS<23>-Footnote-12764182
Node: IDLE<28>2764225
Ref: whatsnew/changelog id2672764333
Ref: 11ae2764333
Ref: IDLE<28>-Footnote-12765047
Ref: IDLE<28>-Footnote-22765090
Node: 工具/示例<13>2765133
Ref: whatsnew/changelog id2682765241
Ref: 11af2765241
Ref: 工具/示例<13>-Footnote-12765471
Node: C API<22>2765514
Ref: whatsnew/changelog id2692765605
Ref: 11b02765605
Ref: C API<22>-Footnote-12765989
Ref: C API<22>-Footnote-22766032
Node: Python 3 7 0 beta 22766075
Ref: whatsnew/changelog python-3-7-0-beta-22766214
Ref: 11b12766214
Node: 安全性<20>2766569
Ref: whatsnew/changelog id2702766672
Ref: 11b22766672
Ref: 安全性<20>-Footnote-12766856
Node: 核心与内置函数<33>2766899
Ref: whatsnew/changelog id2712767018
Ref: 11b32767018
Ref: 核心与内置函数<33>-Footnote-12767850
Ref: 核心与内置函数<33>-Footnote-22767893
Ref: 核心与内置函数<33>-Footnote-32767936
Ref: 核心与内置函数<33>-Footnote-42767979
Ref: 核心与内置函数<33>-Footnote-52768022
Ref: 核心与内置函数<33>-Footnote-62768065
Ref: 核心与内置函数<33>-Footnote-72768108
Node: 库<36>2768151
Ref: whatsnew/changelog id2722768267
Ref: 11b42768267
Ref: 库<36>-Footnote-12774641
Ref: 库<36>-Footnote-22774684
Ref: 库<36>-Footnote-32774727
Ref: 库<36>-Footnote-42774770
Ref: 库<36>-Footnote-52774813
Ref: 库<36>-Footnote-62774856
Ref: 库<36>-Footnote-72774899
Ref: 库<36>-Footnote-82774942
Ref: 库<36>-Footnote-92774985
Ref: 库<36>-Footnote-102775028
Ref: 库<36>-Footnote-112775072
Ref: 库<36>-Footnote-122775116
Ref: 库<36>-Footnote-132775160
Ref: 库<36>-Footnote-142775204
Ref: 库<36>-Footnote-152775248
Ref: 库<36>-Footnote-162775292
Ref: 库<36>-Footnote-172775336
Ref: 库<36>-Footnote-182775380
Ref: 库<36>-Footnote-192775424
Ref: 库<36>-Footnote-202775468
Ref: 库<36>-Footnote-212775512
Ref: 库<36>-Footnote-222775556
Ref: 库<36>-Footnote-232775600
Ref: 库<36>-Footnote-242775644
Ref: 库<36>-Footnote-252775688
Ref: 库<36>-Footnote-262775732
Ref: 库<36>-Footnote-272775776
Ref: 库<36>-Footnote-282775820
Ref: 库<36>-Footnote-292775864
Ref: 库<36>-Footnote-302775908
Ref: 库<36>-Footnote-312775952
Ref: 库<36>-Footnote-322775996
Ref: 库<36>-Footnote-332776040
Ref: 库<36>-Footnote-342776084
Node: 文档<30>2776128
Ref: whatsnew/changelog id2732776229
Ref: 11b52776229
Ref: 文档<30>-Footnote-12777182
Ref: 文档<30>-Footnote-22777225
Ref: 文档<30>-Footnote-32777268
Ref: 文档<30>-Footnote-42777311
Ref: 文档<30>-Footnote-52777354
Ref: 文档<30>-Footnote-62777397
Ref: 文档<30>-Footnote-72777439
Ref: 文档<30>-Footnote-82777482
Node: 测试<28>2777525
Ref: whatsnew/changelog id2742777629
Ref: 11b62777629
Ref: 测试<28>-Footnote-12777772
Node: 构建<28>2777815
Ref: whatsnew/changelog id2752777920
Ref: 11b72777920
Ref: 构建<28>-Footnote-12778061
Node: Windows<28>2778104
Ref: whatsnew/changelog id2762778208
Ref: 11b82778208
Ref: Windows<28>-Footnote-12778944
Ref: Windows<28>-Footnote-22778987
Ref: Windows<28>-Footnote-32779030
Ref: Windows<28>-Footnote-42779073
Ref: Windows<28>-Footnote-52779116
Ref: Windows<28>-Footnote-62779159
Node: macOS<24>2779202
Ref: whatsnew/changelog id2772779304
Ref: 11b92779304
Ref: macOS<24>-Footnote-12779439
Node: IDLE<29>2779482
Ref: whatsnew/changelog id2782779590
Ref: 11ba2779590
Ref: IDLE<29>-Footnote-12780433
Ref: IDLE<29>-Footnote-22780476
Ref: IDLE<29>-Footnote-32780519
Ref: IDLE<29>-Footnote-42780562
Ref: IDLE<29>-Footnote-52780605
Ref: IDLE<29>-Footnote-62780648
Node: 工具/示例<14>2780691
Ref: whatsnew/changelog id2792780781
Ref: 11bb2780781
Ref: 工具/示例<14>-Footnote-12781000
Node: Python 3 7 0 beta 12781043
Ref: whatsnew/changelog python-3-7-0-beta-12781183
Ref: 11bc2781183
Node: 核心与内置函数<34>2781476
Ref: whatsnew/changelog id2802781573
Ref: 11bd2781573
Ref: 核心与内置函数<34>-Footnote-12785004
Ref: 核心与内置函数<34>-Footnote-22785047
Ref: 核心与内置函数<34>-Footnote-32785090
Ref: 核心与内置函数<34>-Footnote-42785133
Ref: 核心与内置函数<34>-Footnote-52785176
Ref: 核心与内置函数<34>-Footnote-62785219
Ref: 核心与内置函数<34>-Footnote-72785262
Ref: 核心与内置函数<34>-Footnote-82785305
Ref: 核心与内置函数<34>-Footnote-92785348
Ref: 核心与内置函数<34>-Footnote-102785397
Ref: 核心与内置函数<34>-Footnote-112785441
Ref: 核心与内置函数<34>-Footnote-122785485
Ref: 核心与内置函数<34>-Footnote-132785529
Ref: 核心与内置函数<34>-Footnote-142785573
Ref: 核心与内置函数<34>-Footnote-152785617
Ref: 核心与内置函数<34>-Footnote-162785661
Ref: 核心与内置函数<34>-Footnote-172785705
Ref: 核心与内置函数<34>-Footnote-182785749
Ref: 核心与内置函数<34>-Footnote-192785799
Ref: 核心与内置函数<34>-Footnote-202785843
Ref: 核心与内置函数<34>-Footnote-212785887
Ref: 核心与内置函数<34>-Footnote-222785931
Ref: 核心与内置函数<34>-Footnote-232785975
Node: 库<37>2786019
Ref: whatsnew/changelog id2812786135
Ref: 11be2786135
Ref: 库<37>-Footnote-12793510
Ref: 库<37>-Footnote-22793553
Ref: 库<37>-Footnote-32793596
Ref: 库<37>-Footnote-42793639
Ref: 库<37>-Footnote-52793682
Ref: 库<37>-Footnote-62793725
Ref: 库<37>-Footnote-72793768
Ref: 库<37>-Footnote-82793811
Ref: 库<37>-Footnote-92793854
Ref: 库<37>-Footnote-102793897
Ref: 库<37>-Footnote-112793941
Ref: 库<37>-Footnote-122793985
Ref: 库<37>-Footnote-132794029
Ref: 库<37>-Footnote-142794073
Ref: 库<37>-Footnote-152794117
Ref: 库<37>-Footnote-162794161
Ref: 库<37>-Footnote-172794205
Ref: 库<37>-Footnote-182794249
Ref: 库<37>-Footnote-192794299
Ref: 库<37>-Footnote-202794343
Ref: 库<37>-Footnote-212794387
Ref: 库<37>-Footnote-222794431
Ref: 库<37>-Footnote-232794475
Ref: 库<37>-Footnote-242794519
Ref: 库<37>-Footnote-252794563
Ref: 库<37>-Footnote-262794607
Ref: 库<37>-Footnote-272794651
Ref: 库<37>-Footnote-282794695
Ref: 库<37>-Footnote-292794739
Ref: 库<37>-Footnote-302794783
Ref: 库<37>-Footnote-312794827
Ref: 库<37>-Footnote-322794871
Ref: 库<37>-Footnote-332794915
Ref: 库<37>-Footnote-342794959
Ref: 库<37>-Footnote-352795003
Ref: 库<37>-Footnote-362795047
Ref: 库<37>-Footnote-372795091
Ref: 库<37>-Footnote-382795135
Ref: 库<37>-Footnote-392795179
Ref: 库<37>-Footnote-402795223
Ref: 库<37>-Footnote-412795267
Ref: 库<37>-Footnote-422795311
Ref: 库<37>-Footnote-432795355
Ref: 库<37>-Footnote-442795399
Ref: 库<37>-Footnote-452795443
Ref: 库<37>-Footnote-462795487
Ref: 库<37>-Footnote-472795531
Node: 文档<31>2795575
Ref: whatsnew/changelog id2822795676
Ref: 11c12795676
Ref: 文档<31>-Footnote-12796201
Ref: 文档<31>-Footnote-22796244
Ref: 文档<31>-Footnote-32796287
Node: 测试<29>2796330
Ref: whatsnew/changelog id2832796434
Ref: 11c22796434
Ref: 测试<29>-Footnote-12797342
Ref: 测试<29>-Footnote-22797385
Ref: 测试<29>-Footnote-32797428
Ref: 测试<29>-Footnote-42797471
Ref: 测试<29>-Footnote-52797514
Ref: 测试<29>-Footnote-62797557
Node: 构建<29>2797600
Ref: whatsnew/changelog id2842797705
Ref: 11c32797705
Ref: 构建<29>-Footnote-12798319
Ref: 构建<29>-Footnote-22798362
Ref: 构建<29>-Footnote-32798405
Ref: 构建<29>-Footnote-42798448
Node: Windows<29>2798491
Ref: whatsnew/changelog id2852798595
Ref: 11c42798595
Ref: Windows<29>-Footnote-12798976
Ref: Windows<29>-Footnote-22799019
Ref: Windows<29>-Footnote-32799062
Node: macOS<25>2799105
Ref: whatsnew/changelog id2862799208
Ref: 11c52799208
Ref: macOS<25>-Footnote-12799730
Ref: macOS<25>-Footnote-22799773
Node: C API<23>2799816
Ref: whatsnew/changelog id2872799899
Ref: 11c62799899
Ref: C API<23>-Footnote-12800220
Ref: C API<23>-Footnote-22800263
Node: Python 3 7 0 alpha 42800306
Ref: whatsnew/changelog python-3-7-0-alpha-42800447
Ref: 11c72800447
Node: 核心与内置函数<35>2800736
Ref: whatsnew/changelog id2882800834
Ref: 11c82800834
Ref: 核心与内置函数<35>-Footnote-12804341
Ref: 核心与内置函数<35>-Footnote-22804384
Ref: 核心与内置函数<35>-Footnote-32804427
Ref: 核心与内置函数<35>-Footnote-42804470
Ref: 核心与内置函数<35>-Footnote-52804513
Ref: 核心与内置函数<35>-Footnote-62804556
Ref: 核心与内置函数<35>-Footnote-72804599
Ref: 核心与内置函数<35>-Footnote-82804642
Ref: 核心与内置函数<35>-Footnote-92804685
Ref: 核心与内置函数<35>-Footnote-102804728
Ref: 核心与内置函数<35>-Footnote-112804772
Ref: 核心与内置函数<35>-Footnote-122804816
Ref: 核心与内置函数<35>-Footnote-132804860
Ref: 核心与内置函数<35>-Footnote-142804904
Ref: 核心与内置函数<35>-Footnote-152804948
Ref: 核心与内置函数<35>-Footnote-162804992
Ref: 核心与内置函数<35>-Footnote-172805036
Ref: 核心与内置函数<35>-Footnote-182805080
Ref: 核心与内置函数<35>-Footnote-192805124
Ref: 核心与内置函数<35>-Footnote-202805174
Ref: 核心与内置函数<35>-Footnote-212805218
Ref: 核心与内置函数<35>-Footnote-222805268
Ref: 核心与内置函数<35>-Footnote-232805312
Ref: 核心与内置函数<35>-Footnote-242805362
Ref: 核心与内置函数<35>-Footnote-252805406
Ref: 核心与内置函数<35>-Footnote-262805450
Ref: 核心与内置函数<35>-Footnote-272805500
Node: 库<38>2805544
Ref: whatsnew/changelog id2892805661
Ref: 11ca2805661
Ref: 库<38>-Footnote-12813664
Ref: 库<38>-Footnote-22813707
Ref: 库<38>-Footnote-32813750
Ref: 库<38>-Footnote-42813793
Ref: 库<38>-Footnote-52813836
Ref: 库<38>-Footnote-62813879
Ref: 库<38>-Footnote-72813922
Ref: 库<38>-Footnote-82813965
Ref: 库<38>-Footnote-92814008
Ref: 库<38>-Footnote-102814051
Ref: 库<38>-Footnote-112814095
Ref: 库<38>-Footnote-122814139
Ref: 库<38>-Footnote-132814183
Ref: 库<38>-Footnote-142814227
Ref: 库<38>-Footnote-152814271
Ref: 库<38>-Footnote-162814315
Ref: 库<38>-Footnote-172814359
Ref: 库<38>-Footnote-182814403
Ref: 库<38>-Footnote-192814447
Ref: 库<38>-Footnote-202814491
Ref: 库<38>-Footnote-212814535
Ref: 库<38>-Footnote-222814579
Ref: 库<38>-Footnote-232814623
Ref: 库<38>-Footnote-242814667
Ref: 库<38>-Footnote-252814711
Ref: 库<38>-Footnote-262814755
Ref: 库<38>-Footnote-272814799
Ref: 库<38>-Footnote-282814843
Ref: 库<38>-Footnote-292814887
Ref: 库<38>-Footnote-302814931
Ref: 库<38>-Footnote-312814975
Ref: 库<38>-Footnote-322815019
Ref: 库<38>-Footnote-332815063
Ref: 库<38>-Footnote-342815107
Ref: 库<38>-Footnote-352815151
Ref: 库<38>-Footnote-362815195
Ref: 库<38>-Footnote-372815239
Ref: 库<38>-Footnote-382815283
Ref: 库<38>-Footnote-392815327
Ref: 库<38>-Footnote-402815371
Ref: 库<38>-Footnote-412815415
Ref: 库<38>-Footnote-422815459
Ref: 库<38>-Footnote-432815503
Ref: 库<38>-Footnote-442815547
Ref: 库<38>-Footnote-452815591
Ref: 库<38>-Footnote-462815635
Ref: 库<38>-Footnote-472815679
Ref: 库<38>-Footnote-482815723
Ref: 库<38>-Footnote-492815767
Ref: 库<38>-Footnote-502815811
Ref: 库<38>-Footnote-512815855
Ref: 库<38>-Footnote-522815899
Ref: 库<38>-Footnote-532815943
Ref: 库<38>-Footnote-542815987
Node: 文档<32>2816031
Ref: whatsnew/changelog id2902816133
Ref: 11cd2816133
Ref: 文档<32>-Footnote-12816287
Node: 测试<30>2816330
Ref: whatsnew/changelog id2912816436
Ref: 11ce2816436
Ref: 测试<30>-Footnote-12816831
Ref: 测试<30>-Footnote-22816874
Node: Windows<30>2816917
Ref: whatsnew/changelog id2922817030
Ref: 11cf2817030
Ref: Windows<30>-Footnote-12817229
Node: 工具/示例<15>2817272
Ref: whatsnew/changelog id2932817384
Ref: 11d02817384
Ref: 工具/示例<15>-Footnote-12817666
Node: C API<24>2817709
Ref: whatsnew/changelog id2942817801
Ref: 11d12817801
Ref: C API<24>-Footnote-12818464
Ref: C API<24>-Footnote-22818507
Ref: C API<24>-Footnote-32818550
Ref: C API<24>-Footnote-42818593
Node: Python 3 7 0 alpha 32818636
Ref: whatsnew/changelog python-3-7-0-alpha-32818778
Ref: 11d22818778
Node: 核心与内置函数<36>2819127
Ref: whatsnew/changelog id2952819225
Ref: 11d32819225
Ref: 核心与内置函数<36>-Footnote-12824353
Ref: 核心与内置函数<36>-Footnote-22824396
Ref: 核心与内置函数<36>-Footnote-32824439
Ref: 核心与内置函数<36>-Footnote-42824482
Ref: 核心与内置函数<36>-Footnote-52824525
Ref: 核心与内置函数<36>-Footnote-62824568
Ref: 核心与内置函数<36>-Footnote-72824611
Ref: 核心与内置函数<36>-Footnote-82824654
Ref: 核心与内置函数<36>-Footnote-92824697
Ref: 核心与内置函数<36>-Footnote-102824740
Ref: 核心与内置函数<36>-Footnote-112824784
Ref: 核心与内置函数<36>-Footnote-122824828
Ref: 核心与内置函数<36>-Footnote-132824872
Ref: 核心与内置函数<36>-Footnote-142824916
Ref: 核心与内置函数<36>-Footnote-152824960
Ref: 核心与内置函数<36>-Footnote-162825004
Ref: 核心与内置函数<36>-Footnote-172825048
Ref: 核心与内置函数<36>-Footnote-182825092
Ref: 核心与内置函数<36>-Footnote-192825136
Ref: 核心与内置函数<36>-Footnote-202825180
Ref: 核心与内置函数<36>-Footnote-212825224
Ref: 核心与内置函数<36>-Footnote-222825268
Node: 库<39>2825312
Ref: whatsnew/changelog id2962825429
Ref: 11d42825429
Ref: 库<39>-Footnote-12841485
Ref: 库<39>-Footnote-22841528
Ref: 库<39>-Footnote-32841571
Ref: 库<39>-Footnote-42841614
Ref: 库<39>-Footnote-52841657
Ref: 库<39>-Footnote-62841700
Ref: 库<39>-Footnote-72841743
Ref: 库<39>-Footnote-82841786
Ref: 库<39>-Footnote-92841830
Ref: 库<39>-Footnote-102841873
Ref: 库<39>-Footnote-112841917
Ref: 库<39>-Footnote-122841961
Ref: 库<39>-Footnote-132842005
Ref: 库<39>-Footnote-142842049
Ref: 库<39>-Footnote-152842093
Ref: 库<39>-Footnote-162842137
Ref: 库<39>-Footnote-172842181
Ref: 库<39>-Footnote-182842225
Ref: 库<39>-Footnote-192842269
Ref: 库<39>-Footnote-202842313
Ref: 库<39>-Footnote-212842357
Ref: 库<39>-Footnote-222842401
Ref: 库<39>-Footnote-232842445
Ref: 库<39>-Footnote-242842489
Ref: 库<39>-Footnote-252842533
Ref: 库<39>-Footnote-262842579
Ref: 库<39>-Footnote-272842623
Ref: 库<39>-Footnote-282842667
Ref: 库<39>-Footnote-292842711
Ref: 库<39>-Footnote-302842755
Ref: 库<39>-Footnote-312842799
Ref: 库<39>-Footnote-322842843
Ref: 库<39>-Footnote-332842893
Ref: 库<39>-Footnote-342842937
Ref: 库<39>-Footnote-352842981
Ref: 库<39>-Footnote-362843025
Ref: 库<39>-Footnote-372843069
Ref: 库<39>-Footnote-382843113
Ref: 库<39>-Footnote-392843157
Ref: 库<39>-Footnote-402843201
Ref: 库<39>-Footnote-412843245
Ref: 库<39>-Footnote-422843289
Ref: 库<39>-Footnote-432843333
Ref: 库<39>-Footnote-442843377
Ref: 库<39>-Footnote-452843421
Ref: 库<39>-Footnote-462843465
Ref: 库<39>-Footnote-472843508
Ref: 库<39>-Footnote-482843552
Ref: 库<39>-Footnote-492843596
Ref: 库<39>-Footnote-502843640
Ref: 库<39>-Footnote-512843684
Ref: 库<39>-Footnote-522843728
Ref: 库<39>-Footnote-532843772
Ref: 库<39>-Footnote-542843816
Ref: 库<39>-Footnote-552843860
Ref: 库<39>-Footnote-562843904
Ref: 库<39>-Footnote-572843948
Ref: 库<39>-Footnote-582843992
Ref: 库<39>-Footnote-592844036
Ref: 库<39>-Footnote-602844080
Ref: 库<39>-Footnote-612844124
Ref: 库<39>-Footnote-622844168
Ref: 库<39>-Footnote-632844218
Ref: 库<39>-Footnote-642844262
Ref: 库<39>-Footnote-652844306
Ref: 库<39>-Footnote-662844350
Ref: 库<39>-Footnote-672844394
Ref: 库<39>-Footnote-682844438
Ref: 库<39>-Footnote-692844482
Ref: 库<39>-Footnote-702844526
Ref: 库<39>-Footnote-712844570
Ref: 库<39>-Footnote-722844614
Ref: 库<39>-Footnote-732844658
Ref: 库<39>-Footnote-742844702
Ref: 库<39>-Footnote-752844746
Ref: 库<39>-Footnote-762844790
Ref: 库<39>-Footnote-772844834
Ref: 库<39>-Footnote-782844878
Ref: 库<39>-Footnote-792844922
Ref: 库<39>-Footnote-802844966
Ref: 库<39>-Footnote-812845010
Ref: 库<39>-Footnote-822845054
Ref: 库<39>-Footnote-832845104
Ref: 库<39>-Footnote-842845148
Ref: 库<39>-Footnote-852845192
Ref: 库<39>-Footnote-862845236
Ref: 库<39>-Footnote-872845280
Ref: 库<39>-Footnote-882845324
Ref: 库<39>-Footnote-892845368
Ref: 库<39>-Footnote-902845412
Ref: 库<39>-Footnote-912845456
Ref: 库<39>-Footnote-922845500
Ref: 库<39>-Footnote-932845544
Ref: 库<39>-Footnote-942845588
Ref: 库<39>-Footnote-952845632
Ref: 库<39>-Footnote-962845676
Ref: 库<39>-Footnote-972845720
Ref: 库<39>-Footnote-982845764
Node: 文档<33>2845808
Ref: whatsnew/changelog id2972845910
Ref: 11da2845910
Ref: 文档<33>-Footnote-12846077
Node: 测试<31>2846120
Ref: whatsnew/changelog id2982846225
Ref: 11db2846225
Ref: 测试<31>-Footnote-12847435
Ref: 测试<31>-Footnote-22847478
Ref: 测试<31>-Footnote-32847521
Ref: 测试<31>-Footnote-42847564
Ref: 测试<31>-Footnote-52847607
Ref: 测试<31>-Footnote-62847650
Ref: 测试<31>-Footnote-72847693
Node: 构建<30>2847736
Ref: whatsnew/changelog id2992847842
Ref: 11dc2847842
Ref: 构建<30>-Footnote-12849063
Ref: 构建<30>-Footnote-22849106
Ref: 构建<30>-Footnote-32849149
Ref: 构建<30>-Footnote-42849192
Ref: 构建<30>-Footnote-52849235
Ref: 构建<30>-Footnote-62849278
Ref: 构建<30>-Footnote-72849321
Ref: 构建<30>-Footnote-82849364
Ref: 构建<30>-Footnote-92849407
Ref: 构建<30>-Footnote-102849450
Ref: 构建<30>-Footnote-112849494
Ref: 构建<30>-Footnote-122849538
Node: Windows<31>2849582
Ref: whatsnew/changelog id3002849687
Ref: 11dd2849687
Ref: Windows<31>-Footnote-12850220
Ref: Windows<31>-Footnote-22850262
Ref: Windows<31>-Footnote-32850305
Ref: Windows<31>-Footnote-42850348
Node: macOS<26>2850391
Ref: whatsnew/changelog id3012850494
Ref: 11de2850494
Ref: macOS<26>-Footnote-12850632
Node: IDLE<30>2850675
Ref: whatsnew/changelog id3022850784
Ref: 11df2850784
Ref: IDLE<30>-Footnote-12852877
Ref: IDLE<30>-Footnote-22852920
Ref: IDLE<30>-Footnote-32852963
Ref: IDLE<30>-Footnote-42853006
Ref: IDLE<30>-Footnote-52853049
Ref: IDLE<30>-Footnote-62853092
Ref: IDLE<30>-Footnote-72853135
Ref: IDLE<30>-Footnote-82853178
Node: 工具/示例<16>2853221
Ref: whatsnew/changelog id3032853330
Ref: 11e02853330
Ref: 工具/示例<16>-Footnote-12853862
Ref: 工具/示例<16>-Footnote-22853905
Node: C API<25>2853948
Ref: whatsnew/changelog id3042854040
Ref: 11e12854040
Ref: C API<25>-Footnote-12855168
Ref: C API<25>-Footnote-22855211
Ref: C API<25>-Footnote-32855254
Ref: C API<25>-Footnote-42855297
Ref: C API<25>-Footnote-52855340
Ref: C API<25>-Footnote-62855383
Node: Python 3 7 0 alpha 22855426
Ref: whatsnew/changelog python-3-7-0-alpha-22855568
Ref: 11e22855568
Node: 核心与内置函数<37>2855815
Ref: whatsnew/changelog id3052855913
Ref: 11e32855913
Ref: 核心与内置函数<37>-Footnote-12860110
Ref: 核心与内置函数<37>-Footnote-22860153
Ref: 核心与内置函数<37>-Footnote-32860196
Ref: 核心与内置函数<37>-Footnote-42860239
Ref: 核心与内置函数<37>-Footnote-52860282
Ref: 核心与内置函数<37>-Footnote-62860325
Ref: 核心与内置函数<37>-Footnote-72860368
Ref: 核心与内置函数<37>-Footnote-82860411
Ref: 核心与内置函数<37>-Footnote-92860454
Ref: 核心与内置函数<37>-Footnote-102860497
Ref: 核心与内置函数<37>-Footnote-112860541
Ref: 核心与内置函数<37>-Footnote-122860585
Ref: 核心与内置函数<37>-Footnote-132860629
Ref: 核心与内置函数<37>-Footnote-142860673
Ref: 核心与内置函数<37>-Footnote-152860717
Ref: 核心与内置函数<37>-Footnote-162860761
Ref: 核心与内置函数<37>-Footnote-172860805
Ref: 核心与内置函数<37>-Footnote-182860849
Ref: 核心与内置函数<37>-Footnote-192860893
Ref: 核心与内置函数<37>-Footnote-202860937
Ref: 核心与内置函数<37>-Footnote-212860987
Ref: 核心与内置函数<37>-Footnote-222861031
Ref: 核心与内置函数<37>-Footnote-232861075
Ref: 核心与内置函数<37>-Footnote-242861119
Ref: 核心与内置函数<37>-Footnote-252861163
Ref: 核心与内置函数<37>-Footnote-262861207
Ref: 核心与内置函数<37>-Footnote-272861251
Node: 库<40>2861301
Ref: whatsnew/changelog id3062861418
Ref: 11e62861418
Ref: 库<40>-Footnote-12865490
Ref: 库<40>-Footnote-22865533
Ref: 库<40>-Footnote-32865576
Ref: 库<40>-Footnote-42865619
Ref: 库<40>-Footnote-52865662
Ref: 库<40>-Footnote-62865705
Ref: 库<40>-Footnote-72865748
Ref: 库<40>-Footnote-82865791
Ref: 库<40>-Footnote-92865834
Ref: 库<40>-Footnote-102865877
Ref: 库<40>-Footnote-112865921
Ref: 库<40>-Footnote-122865965
Ref: 库<40>-Footnote-132866009
Ref: 库<40>-Footnote-142866053
Ref: 库<40>-Footnote-152866097
Ref: 库<40>-Footnote-162866141
Ref: 库<40>-Footnote-172866185
Ref: 库<40>-Footnote-182866229
Ref: 库<40>-Footnote-192866273
Ref: 库<40>-Footnote-202866317
Ref: 库<40>-Footnote-212866361
Ref: 库<40>-Footnote-222866405
Ref: 库<40>-Footnote-232866449
Ref: 库<40>-Footnote-242866493
Ref: 库<40>-Footnote-252866537
Ref: 库<40>-Footnote-262866581
Node: 文档<34>2866625
Ref: whatsnew/changelog id3072866727
Ref: 11e82866727
Ref: 文档<34>-Footnote-12867102
Ref: 文档<34>-Footnote-22867145
Node: 构建<31>2867188
Ref: whatsnew/changelog id3082867291
Ref: 11e92867291
Ref: 构建<31>-Footnote-12867921
Ref: 构建<31>-Footnote-22867964
Ref: 构建<31>-Footnote-32868007
Ref: 构建<31>-Footnote-42868050
Ref: 构建<31>-Footnote-52868093
Ref: 构建<31>-Footnote-62868136
Node: IDLE<31>2868179
Ref: whatsnew/changelog id3092868281
Ref: 11ea2868281
Ref: IDLE<31>-Footnote-12869587
Ref: IDLE<31>-Footnote-22869630
Ref: IDLE<31>-Footnote-32869673
Ref: IDLE<31>-Footnote-42869716
Ref: IDLE<31>-Footnote-52869759
Ref: IDLE<31>-Footnote-62869802
Node: C API<26>2869847
Ref: whatsnew/changelog id3102869930
Ref: 11eb2869930
Ref: C API<26>-Footnote-12870672
Ref: C API<26>-Footnote-22870715
Ref: C API<26>-Footnote-32870758
Ref: C API<26>-Footnote-42870801
Node: Python 3 7 0 alpha 12870850
Ref: whatsnew/changelog python-3-7-0-alpha-12870994
Ref: 11ec2870994
Node: 安全性<21>2871351
Ref: whatsnew/changelog id3112871455
Ref: 11ed2871455
Ref: 安全性<21>-Footnote-12873078
Ref: 安全性<21>-Footnote-22873121
Ref: 安全性<21>-Footnote-32873164
Ref: 安全性<21>-Footnote-42873207
Ref: 安全性<21>-Footnote-52873250
Ref: 安全性<21>-Footnote-62873293
Ref: 安全性<21>-Footnote-72873336
Node: 核心与内置函数<38>2873379
Ref: whatsnew/changelog id3122873499
Ref: 11ee2873499
Ref: 核心与内置函数<38>-Footnote-12894393
Ref: 核心与内置函数<38>-Footnote-22894436
Ref: 核心与内置函数<38>-Footnote-32894479
Ref: 核心与内置函数<38>-Footnote-42894522
Ref: 核心与内置函数<38>-Footnote-52894565
Ref: 核心与内置函数<38>-Footnote-62894608
Ref: 核心与内置函数<38>-Footnote-72894651
Ref: 核心与内置函数<38>-Footnote-82894694
Ref: 核心与内置函数<38>-Footnote-92894737
Ref: 核心与内置函数<38>-Footnote-102894780
Ref: 核心与内置函数<38>-Footnote-112894824
Ref: 核心与内置函数<38>-Footnote-122894868
Ref: 核心与内置函数<38>-Footnote-132894912
Ref: 核心与内置函数<38>-Footnote-142894956
Ref: 核心与内置函数<38>-Footnote-152895000
Ref: 核心与内置函数<38>-Footnote-162895044
Ref: 核心与内置函数<38>-Footnote-172895088
Ref: 核心与内置函数<38>-Footnote-182895132
Ref: 核心与内置函数<38>-Footnote-192895176
Ref: 核心与内置函数<38>-Footnote-202895220
Ref: 核心与内置函数<38>-Footnote-212895264
Ref: 核心与内置函数<38>-Footnote-222895308
Ref: 核心与内置函数<38>-Footnote-232895352
Ref: 核心与内置函数<38>-Footnote-242895396
Ref: 核心与内置函数<38>-Footnote-252895440
Ref: 核心与内置函数<38>-Footnote-262895484
Ref: 核心与内置函数<38>-Footnote-272895528
Ref: 核心与内置函数<38>-Footnote-282895572
Ref: 核心与内置函数<38>-Footnote-292895616
Ref: 核心与内置函数<38>-Footnote-302895660
Ref: 核心与内置函数<38>-Footnote-312895704
Ref: 核心与内置函数<38>-Footnote-322895748
Ref: 核心与内置函数<38>-Footnote-332895792
Ref: 核心与内置函数<38>-Footnote-342895836
Ref: 核心与内置函数<38>-Footnote-352895880
Ref: 核心与内置函数<38>-Footnote-362895930
Ref: 核心与内置函数<38>-Footnote-372895974
Ref: 核心与内置函数<38>-Footnote-382896018
Ref: 核心与内置函数<38>-Footnote-392896062
Ref: 核心与内置函数<38>-Footnote-402896106
Ref: 核心与内置函数<38>-Footnote-412896150
Ref: 核心与内置函数<38>-Footnote-422896194
Ref: 核心与内置函数<38>-Footnote-432896238
Ref: 核心与内置函数<38>-Footnote-442896282
Ref: 核心与内置函数<38>-Footnote-452896326
Ref: 核心与内置函数<38>-Footnote-462896370
Ref: 核心与内置函数<38>-Footnote-472896414
Ref: 核心与内置函数<38>-Footnote-482896458
Ref: 核心与内置函数<38>-Footnote-492896502
Ref: 核心与内置函数<38>-Footnote-502896546
Ref: 核心与内置函数<38>-Footnote-512896590
Ref: 核心与内置函数<38>-Footnote-522896634
Ref: 核心与内置函数<38>-Footnote-532896678
Ref: 核心与内置函数<38>-Footnote-542896722
Ref: 核心与内置函数<38>-Footnote-552896766
Ref: 核心与内置函数<38>-Footnote-562896810
Ref: 核心与内置函数<38>-Footnote-572896854
Ref: 核心与内置函数<38>-Footnote-582896898
Ref: 核心与内置函数<38>-Footnote-592896942
Ref: 核心与内置函数<38>-Footnote-602896986
Ref: 核心与内置函数<38>-Footnote-612897030
Ref: 核心与内置函数<38>-Footnote-622897074
Ref: 核心与内置函数<38>-Footnote-632897118
Ref: 核心与内置函数<38>-Footnote-642897162
Ref: 核心与内置函数<38>-Footnote-652897206
Ref: 核心与内置函数<38>-Footnote-662897250
Ref: 核心与内置函数<38>-Footnote-672897294
Ref: 核心与内置函数<38>-Footnote-682897338
Ref: 核心与内置函数<38>-Footnote-692897382
Ref: 核心与内置函数<38>-Footnote-702897426
Ref: 核心与内置函数<38>-Footnote-712897470
Ref: 核心与内置函数<38>-Footnote-722897514
Ref: 核心与内置函数<38>-Footnote-732897558
Ref: 核心与内置函数<38>-Footnote-742897602
Ref: 核心与内置函数<38>-Footnote-752897646
Ref: 核心与内置函数<38>-Footnote-762897690
Ref: 核心与内置函数<38>-Footnote-772897734
Ref: 核心与内置函数<38>-Footnote-782897778
Ref: 核心与内置函数<38>-Footnote-792897822
Ref: 核心与内置函数<38>-Footnote-802897866
Ref: 核心与内置函数<38>-Footnote-812897910
Ref: 核心与内置函数<38>-Footnote-822897954
Ref: 核心与内置函数<38>-Footnote-832897998
Ref: 核心与内置函数<38>-Footnote-842898042
Ref: 核心与内置函数<38>-Footnote-852898086
Ref: 核心与内置函数<38>-Footnote-862898130
Ref: 核心与内置函数<38>-Footnote-872898174
Ref: 核心与内置函数<38>-Footnote-882898218
Ref: 核心与内置函数<38>-Footnote-892898262
Ref: 核心与内置函数<38>-Footnote-902898306
Ref: 核心与内置函数<38>-Footnote-912898356
Ref: 核心与内置函数<38>-Footnote-922898400
Ref: 核心与内置函数<38>-Footnote-932898444
Ref: 核心与内置函数<38>-Footnote-942898488
Ref: 核心与内置函数<38>-Footnote-952898532
Ref: 核心与内置函数<38>-Footnote-962898576
Ref: 核心与内置函数<38>-Footnote-972898620
Ref: 核心与内置函数<38>-Footnote-982898664
Ref: 核心与内置函数<38>-Footnote-992898708
Ref: 核心与内置函数<38>-Footnote-1002898752
Ref: 核心与内置函数<38>-Footnote-1012898797
Ref: 核心与内置函数<38>-Footnote-1022898842
Ref: 核心与内置函数<38>-Footnote-1032898887
Ref: 核心与内置函数<38>-Footnote-1042898932
Ref: 核心与内置函数<38>-Footnote-1052898977
Ref: 核心与内置函数<38>-Footnote-1062899022
Ref: 核心与内置函数<38>-Footnote-1072899067
Ref: 核心与内置函数<38>-Footnote-1082899112
Ref: 核心与内置函数<38>-Footnote-1092899157
Ref: 核心与内置函数<38>-Footnote-1102899202
Ref: 核心与内置函数<38>-Footnote-1112899247
Ref: 核心与内置函数<38>-Footnote-1122899292
Ref: 核心与内置函数<38>-Footnote-1132899337
Ref: 核心与内置函数<38>-Footnote-1142899382
Ref: 核心与内置函数<38>-Footnote-1152899427
Ref: 核心与内置函数<38>-Footnote-1162899472
Ref: 核心与内置函数<38>-Footnote-1172899517
Ref: 核心与内置函数<38>-Footnote-1182899562
Ref: 核心与内置函数<38>-Footnote-1192899607
Ref: 核心与内置函数<38>-Footnote-1202899652
Ref: 核心与内置函数<38>-Footnote-1212899697
Ref: 核心与内置函数<38>-Footnote-1222899742
Ref: 核心与内置函数<38>-Footnote-1232899787
Ref: 核心与内置函数<38>-Footnote-1242899832
Ref: 核心与内置函数<38>-Footnote-1252899877
Ref: 核心与内置函数<38>-Footnote-1262899922
Ref: 核心与内置函数<38>-Footnote-1272899967
Ref: 核心与内置函数<38>-Footnote-1282900012
Ref: 核心与内置函数<38>-Footnote-1292900057
Ref: 核心与内置函数<38>-Footnote-1302900102
Ref: 核心与内置函数<38>-Footnote-1312900147
Ref: 核心与内置函数<38>-Footnote-1322900192
Ref: 核心与内置函数<38>-Footnote-1332900237
Ref: 核心与内置函数<38>-Footnote-1342900282
Ref: 核心与内置函数<38>-Footnote-1352900327
Ref: 核心与内置函数<38>-Footnote-1362900372
Ref: 核心与内置函数<38>-Footnote-1372900417
Ref: 核心与内置函数<38>-Footnote-1382900462
Ref: 核心与内置函数<38>-Footnote-1392900507
Ref: 核心与内置函数<38>-Footnote-1402900552
Ref: 核心与内置函数<38>-Footnote-1412900597
Ref: 核心与内置函数<38>-Footnote-1422900642
Ref: 核心与内置函数<38>-Footnote-1432900687
Ref: 核心与内置函数<38>-Footnote-1442900732
Ref: 核心与内置函数<38>-Footnote-1452900777
Ref: 核心与内置函数<38>-Footnote-1462900822
Ref: 核心与内置函数<38>-Footnote-1472900867
Ref: 核心与内置函数<38>-Footnote-1482900912
Node: 库<41>2900957
Ref: whatsnew/changelog id3132901074
Ref: 11f02901074
Ref: 库<41>-Footnote-12947680
Ref: 库<41>-Footnote-22947723
Ref: 库<41>-Footnote-32947766
Ref: 库<41>-Footnote-42947809
Ref: 库<41>-Footnote-52947852
Ref: 库<41>-Footnote-62947895
Ref: 库<41>-Footnote-72947938
Ref: 库<41>-Footnote-82947981
Ref: 库<41>-Footnote-92948024
Ref: 库<41>-Footnote-102948067
Ref: 库<41>-Footnote-112948111
Ref: 库<41>-Footnote-122948155
Ref: 库<41>-Footnote-132948199
Ref: 库<41>-Footnote-142948243
Ref: 库<41>-Footnote-152948287
Ref: 库<41>-Footnote-162948331
Ref: 库<41>-Footnote-172948375
Ref: 库<41>-Footnote-182948419
Ref: 库<41>-Footnote-192948463
Ref: 库<41>-Footnote-202948507
Ref: 库<41>-Footnote-212948551
Ref: 库<41>-Footnote-222948597
Ref: 库<41>-Footnote-232948641
Ref: 库<41>-Footnote-242948685
Ref: 库<41>-Footnote-252948729
Ref: 库<41>-Footnote-262948773
Ref: 库<41>-Footnote-272948823
Ref: 库<41>-Footnote-282948867
Ref: 库<41>-Footnote-292948911
Ref: 库<41>-Footnote-302948955
Ref: 库<41>-Footnote-312948999
Ref: 库<41>-Footnote-322949043
Ref: 库<41>-Footnote-332949087
Ref: 库<41>-Footnote-342949131
Ref: 库<41>-Footnote-352949174
Ref: 库<41>-Footnote-362949218
Ref: 库<41>-Footnote-372949262
Ref: 库<41>-Footnote-382949306
Ref: 库<41>-Footnote-392949350
Ref: 库<41>-Footnote-402949393
Ref: 库<41>-Footnote-412949437
Ref: 库<41>-Footnote-422949481
Ref: 库<41>-Footnote-432949525
Ref: 库<41>-Footnote-442949569
Ref: 库<41>-Footnote-452949613
Ref: 库<41>-Footnote-462949657
Ref: 库<41>-Footnote-472949701
Ref: 库<41>-Footnote-482949745
Ref: 库<41>-Footnote-492949789
Ref: 库<41>-Footnote-502949833
Ref: 库<41>-Footnote-512949877
Ref: 库<41>-Footnote-522949921
Ref: 库<41>-Footnote-532949964
Ref: 库<41>-Footnote-542950008
Ref: 库<41>-Footnote-552950052
Ref: 库<41>-Footnote-562950096
Ref: 库<41>-Footnote-572950140
Ref: 库<41>-Footnote-582950184
Ref: 库<41>-Footnote-592950228
Ref: 库<41>-Footnote-602950272
Ref: 库<41>-Footnote-612950316
Ref: 库<41>-Footnote-622950360
Ref: 库<41>-Footnote-632950404
Ref: 库<41>-Footnote-642950448
Ref: 库<41>-Footnote-652950492
Ref: 库<41>-Footnote-662950536
Ref: 库<41>-Footnote-672950580
Ref: 库<41>-Footnote-682950624
Ref: 库<41>-Footnote-692950668
Ref: 库<41>-Footnote-702950712
Ref: 库<41>-Footnote-712950756
Ref: 库<41>-Footnote-722950800
Ref: 库<41>-Footnote-732950843
Ref: 库<41>-Footnote-742950887
Ref: 库<41>-Footnote-752950931
Ref: 库<41>-Footnote-762950975
Ref: 库<41>-Footnote-772951019
Ref: 库<41>-Footnote-782951063
Ref: 库<41>-Footnote-792951107
Ref: 库<41>-Footnote-802951151
Ref: 库<41>-Footnote-812951195
Ref: 库<41>-Footnote-822951239
Ref: 库<41>-Footnote-832951283
Ref: 库<41>-Footnote-842951327
Ref: 库<41>-Footnote-852951371
Ref: 库<41>-Footnote-862951415
Ref: 库<41>-Footnote-872951459
Ref: 库<41>-Footnote-882951503
Ref: 库<41>-Footnote-892951547
Ref: 库<41>-Footnote-902951591
Ref: 库<41>-Footnote-912951635
Ref: 库<41>-Footnote-922951679
Ref: 库<41>-Footnote-932951723
Ref: 库<41>-Footnote-942951767
Ref: 库<41>-Footnote-952951811
Ref: 库<41>-Footnote-962951855
Ref: 库<41>-Footnote-972951899
Ref: 库<41>-Footnote-982951943
Ref: 库<41>-Footnote-992951987
Ref: 库<41>-Footnote-1002952031
Ref: 库<41>-Footnote-1012952076
Ref: 库<41>-Footnote-1022952121
Ref: 库<41>-Footnote-1032952166
Ref: 库<41>-Footnote-1042952211
Ref: 库<41>-Footnote-1052952256
Ref: 库<41>-Footnote-1062952301
Ref: 库<41>-Footnote-1072952346
Ref: 库<41>-Footnote-1082952391
Ref: 库<41>-Footnote-1092952436
Ref: 库<41>-Footnote-1102952481
Ref: 库<41>-Footnote-1112952526
Ref: 库<41>-Footnote-1122952571
Ref: 库<41>-Footnote-1132952616
Ref: 库<41>-Footnote-1142952661
Ref: 库<41>-Footnote-1152952706
Ref: 库<41>-Footnote-1162952751
Ref: 库<41>-Footnote-1172952795
Ref: 库<41>-Footnote-1182952840
Ref: 库<41>-Footnote-1192952885
Ref: 库<41>-Footnote-1202952930
Ref: 库<41>-Footnote-1212952975
Ref: 库<41>-Footnote-1222953020
Ref: 库<41>-Footnote-1232953065
Ref: 库<41>-Footnote-1242953110
Ref: 库<41>-Footnote-1252953155
Ref: 库<41>-Footnote-1262953200
Ref: 库<41>-Footnote-1272953245
Ref: 库<41>-Footnote-1282953290
Ref: 库<41>-Footnote-1292953335
Ref: 库<41>-Footnote-1302953380
Ref: 库<41>-Footnote-1312953425
Ref: 库<41>-Footnote-1322953470
Ref: 库<41>-Footnote-1332953515
Ref: 库<41>-Footnote-1342953560
Ref: 库<41>-Footnote-1352953605
Ref: 库<41>-Footnote-1362953650
Ref: 库<41>-Footnote-1372953695
Ref: 库<41>-Footnote-1382953740
Ref: 库<41>-Footnote-1392953785
Ref: 库<41>-Footnote-1402953830
Ref: 库<41>-Footnote-1412953875
Ref: 库<41>-Footnote-1422953920
Ref: 库<41>-Footnote-1432953965
Ref: 库<41>-Footnote-1442954010
Ref: 库<41>-Footnote-1452954055
Ref: 库<41>-Footnote-1462954100
Ref: 库<41>-Footnote-1472954144
Ref: 库<41>-Footnote-1482954189
Ref: 库<41>-Footnote-1492954234
Ref: 库<41>-Footnote-1502954279
Ref: 库<41>-Footnote-1512954324
Ref: 库<41>-Footnote-1522954369
Ref: 库<41>-Footnote-1532954414
Ref: 库<41>-Footnote-1542954459
Ref: 库<41>-Footnote-1552954504
Ref: 库<41>-Footnote-1562954549
Ref: 库<41>-Footnote-1572954594
Ref: 库<41>-Footnote-1582954639
Ref: 库<41>-Footnote-1592954684
Ref: 库<41>-Footnote-1602954729
Ref: 库<41>-Footnote-1612954774
Ref: 库<41>-Footnote-1622954819
Ref: 库<41>-Footnote-1632954864
Ref: 库<41>-Footnote-1642954909
Ref: 库<41>-Footnote-1652954954
Ref: 库<41>-Footnote-1662954999
Ref: 库<41>-Footnote-1672955044
Ref: 库<41>-Footnote-1682955089
Ref: 库<41>-Footnote-1692955134
Ref: 库<41>-Footnote-1702955178
Ref: 库<41>-Footnote-1712955223
Ref: 库<41>-Footnote-1722955268
Ref: 库<41>-Footnote-1732955313
Ref: 库<41>-Footnote-1742955358
Ref: 库<41>-Footnote-1752955403
Ref: 库<41>-Footnote-1762955448
Ref: 库<41>-Footnote-1772955493
Ref: 库<41>-Footnote-1782955538
Ref: 库<41>-Footnote-1792955583
Ref: 库<41>-Footnote-1802955628
Ref: 库<41>-Footnote-1812955672
Ref: 库<41>-Footnote-1822955717
Ref: 库<41>-Footnote-1832955762
Ref: 库<41>-Footnote-1842955807
Ref: 库<41>-Footnote-1852955852
Ref: 库<41>-Footnote-1862955897
Ref: 库<41>-Footnote-1872955941
Ref: 库<41>-Footnote-1882955986
Ref: 库<41>-Footnote-1892956031
Ref: 库<41>-Footnote-1902956076
Ref: 库<41>-Footnote-1912956121
Ref: 库<41>-Footnote-1922956166
Ref: 库<41>-Footnote-1932956211
Ref: 库<41>-Footnote-1942956256
Ref: 库<41>-Footnote-1952956301
Ref: 库<41>-Footnote-1962956346
Ref: 库<41>-Footnote-1972956391
Ref: 库<41>-Footnote-1982956436
Ref: 库<41>-Footnote-1992956481
Ref: 库<41>-Footnote-2002956526
Ref: 库<41>-Footnote-2012956571
Ref: 库<41>-Footnote-2022956616
Ref: 库<41>-Footnote-2032956661
Ref: 库<41>-Footnote-2042956706
Ref: 库<41>-Footnote-2052956751
Ref: 库<41>-Footnote-2062956796
Ref: 库<41>-Footnote-2072956841
Ref: 库<41>-Footnote-2082956886
Ref: 库<41>-Footnote-2092956931
Ref: 库<41>-Footnote-2102956976
Ref: 库<41>-Footnote-2112957021
Ref: 库<41>-Footnote-2122957066
Ref: 库<41>-Footnote-2132957111
Ref: 库<41>-Footnote-2142957156
Ref: 库<41>-Footnote-2152957201
Ref: 库<41>-Footnote-2162957246
Ref: 库<41>-Footnote-2172957291
Ref: 库<41>-Footnote-2182957336
Ref: 库<41>-Footnote-2192957381
Ref: 库<41>-Footnote-2202957426
Ref: 库<41>-Footnote-2212957471
Ref: 库<41>-Footnote-2222957516
Ref: 库<41>-Footnote-2232957561
Ref: 库<41>-Footnote-2242957606
Ref: 库<41>-Footnote-2252957650
Ref: 库<41>-Footnote-2262957695
Ref: 库<41>-Footnote-2272957740
Ref: 库<41>-Footnote-2282957785
Ref: 库<41>-Footnote-2292957830
Ref: 库<41>-Footnote-2302957875
Ref: 库<41>-Footnote-2312957920
Ref: 库<41>-Footnote-2322957965
Ref: 库<41>-Footnote-2332958010
Ref: 库<41>-Footnote-2342958055
Ref: 库<41>-Footnote-2352958100
Ref: 库<41>-Footnote-2362958145
Ref: 库<41>-Footnote-2372958190
Ref: 库<41>-Footnote-2382958235
Ref: 库<41>-Footnote-2392958280
Ref: 库<41>-Footnote-2402958325
Ref: 库<41>-Footnote-2412958370
Ref: 库<41>-Footnote-2422958415
Ref: 库<41>-Footnote-2432958460
Ref: 库<41>-Footnote-2442958505
Ref: 库<41>-Footnote-2452958550
Ref: 库<41>-Footnote-2462958595
Ref: 库<41>-Footnote-2472958640
Ref: 库<41>-Footnote-2482958685
Ref: 库<41>-Footnote-2492958730
Ref: 库<41>-Footnote-2502958775
Ref: 库<41>-Footnote-2512958820
Ref: 库<41>-Footnote-2522958865
Ref: 库<41>-Footnote-2532958910
Ref: 库<41>-Footnote-2542958955
Ref: 库<41>-Footnote-2552959000
Ref: 库<41>-Footnote-2562959045
Ref: 库<41>-Footnote-2572959090
Ref: 库<41>-Footnote-2582959135
Ref: 库<41>-Footnote-2592959180
Ref: 库<41>-Footnote-2602959225
Ref: 库<41>-Footnote-2612959270
Ref: 库<41>-Footnote-2622959315
Ref: 库<41>-Footnote-2632959360
Ref: 库<41>-Footnote-2642959405
Ref: 库<41>-Footnote-2652959450
Ref: 库<41>-Footnote-2662959495
Ref: 库<41>-Footnote-2672959540
Ref: 库<41>-Footnote-2682959585
Ref: 库<41>-Footnote-2692959630
Ref: 库<41>-Footnote-2702959675
Ref: 库<41>-Footnote-2712959720
Ref: 库<41>-Footnote-2722959765
Ref: 库<41>-Footnote-2732959821
Ref: 库<41>-Footnote-2742959866
Ref: 库<41>-Footnote-2752959911
Ref: 库<41>-Footnote-2762959956
Ref: 库<41>-Footnote-2772960001
Ref: 库<41>-Footnote-2782960046
Ref: 库<41>-Footnote-2792960091
Ref: 库<41>-Footnote-2802960136
Ref: 库<41>-Footnote-2812960181
Ref: 库<41>-Footnote-2822960226
Ref: 库<41>-Footnote-2832960271
Ref: 库<41>-Footnote-2842960316
Ref: 库<41>-Footnote-2852960361
Ref: 库<41>-Footnote-2862960406
Ref: 库<41>-Footnote-2872960451
Ref: 库<41>-Footnote-2882960496
Ref: 库<41>-Footnote-2892960541
Ref: 库<41>-Footnote-2902960586
Ref: 库<41>-Footnote-2912960631
Ref: 库<41>-Footnote-2922960676
Ref: 库<41>-Footnote-2932960721
Ref: 库<41>-Footnote-2942960766
Ref: 库<41>-Footnote-2952960811
Ref: 库<41>-Footnote-2962960856
Ref: 库<41>-Footnote-2972960901
Ref: 库<41>-Footnote-2982960946
Ref: 库<41>-Footnote-2992960991
Ref: 库<41>-Footnote-3002961036
Ref: 库<41>-Footnote-3012961081
Ref: 库<41>-Footnote-3022961126
Ref: 库<41>-Footnote-3032961171
Ref: 库<41>-Footnote-3042961216
Ref: 库<41>-Footnote-3052961261
Ref: 库<41>-Footnote-3062961306
Ref: 库<41>-Footnote-3072961351
Ref: 库<41>-Footnote-3082961396
Ref: 库<41>-Footnote-3092961441
Ref: 库<41>-Footnote-3102961486
Ref: 库<41>-Footnote-3112961531
Ref: 库<41>-Footnote-3122961576
Ref: 库<41>-Footnote-3132961621
Ref: 库<41>-Footnote-3142961666
Ref: 库<41>-Footnote-3152961711
Ref: 库<41>-Footnote-3162961756
Ref: 库<41>-Footnote-3172961801
Ref: 库<41>-Footnote-3182961846
Ref: 库<41>-Footnote-3192961891
Ref: 库<41>-Footnote-3202961936
Ref: 库<41>-Footnote-3212961981
Ref: 库<41>-Footnote-3222962026
Ref: 库<41>-Footnote-3232962071
Ref: 库<41>-Footnote-3242962116
Ref: 库<41>-Footnote-3252962161
Ref: 库<41>-Footnote-3262962206
Node: 文档<35>2962251
Ref: whatsnew/changelog id3142962353
Ref: 11f12962353
Ref: 文档<35>-Footnote-12964503
Ref: 文档<35>-Footnote-22964546
Ref: 文档<35>-Footnote-32964589
Ref: 文档<35>-Footnote-42964632
Ref: 文档<35>-Footnote-52964675
Ref: 文档<35>-Footnote-62964718
Ref: 文档<35>-Footnote-72964761
Ref: 文档<35>-Footnote-82964804
Ref: 文档<35>-Footnote-92964847
Ref: 文档<35>-Footnote-102964890
Ref: 文档<35>-Footnote-112964934
Ref: 文档<35>-Footnote-122964978
Ref: 文档<35>-Footnote-132965022
Ref: 文档<35>-Footnote-142965066
Ref: 文档<35>-Footnote-152965110
Ref: 文档<35>-Footnote-162965154
Ref: 文档<35>-Footnote-172965204
Node: 测试<32>2965248
Ref: whatsnew/changelog id3152965353
Ref: 11f42965353
Ref: 测试<32>-Footnote-12968103
Ref: 测试<32>-Footnote-22968146
Ref: 测试<32>-Footnote-32968189
Ref: 测试<32>-Footnote-42968232
Ref: 测试<32>-Footnote-52968275
Ref: 测试<32>-Footnote-62968318
Ref: 测试<32>-Footnote-72968361
Ref: 测试<32>-Footnote-82968404
Ref: 测试<32>-Footnote-92968447
Ref: 测试<32>-Footnote-102968490
Ref: 测试<32>-Footnote-112968534
Ref: 测试<32>-Footnote-122968578
Ref: 测试<32>-Footnote-132968622
Ref: 测试<32>-Footnote-142968666
Ref: 测试<32>-Footnote-152968710
Ref: 测试<32>-Footnote-162968754
Ref: 测试<32>-Footnote-172968798
Ref: 测试<32>-Footnote-182968842
Ref: 测试<32>-Footnote-192968886
Node: 构建<32>2968930
Ref: whatsnew/changelog id3162969036
Ref: 11f52969036
Ref: 构建<32>-Footnote-12973788
Ref: 构建<32>-Footnote-22973831
Ref: 构建<32>-Footnote-32973874
Ref: 构建<32>-Footnote-42973917
Ref: 构建<32>-Footnote-52973966
Ref: 构建<32>-Footnote-62974009
Ref: 构建<32>-Footnote-72974052
Ref: 构建<32>-Footnote-82974095
Ref: 构建<32>-Footnote-92974138
Ref: 构建<32>-Footnote-102974181
Ref: 构建<32>-Footnote-112974225
Ref: 构建<32>-Footnote-122974269
Ref: 构建<32>-Footnote-132974313
Ref: 构建<32>-Footnote-142974357
Ref: 构建<32>-Footnote-152974401
Ref: 构建<32>-Footnote-162974445
Ref: 构建<32>-Footnote-172974489
Ref: 构建<32>-Footnote-182974533
Ref: 构建<32>-Footnote-192974577
Ref: 构建<32>-Footnote-202974621
Ref: 构建<32>-Footnote-212974665
Ref: 构建<32>-Footnote-222974709
Ref: 构建<32>-Footnote-232974753
Ref: 构建<32>-Footnote-242974797
Ref: 构建<32>-Footnote-252974841
Ref: 构建<32>-Footnote-262974885
Ref: 构建<32>-Footnote-272974929
Ref: 构建<32>-Footnote-282974973
Ref: 构建<32>-Footnote-292975017
Ref: 构建<32>-Footnote-302975061
Ref: 构建<32>-Footnote-312975105
Ref: 构建<32>-Footnote-322975149
Ref: 构建<32>-Footnote-332975193
Ref: 构建<32>-Footnote-342975237
Ref: 构建<32>-Footnote-352975281
Ref: 构建<32>-Footnote-362975325
Ref: 构建<32>-Footnote-372975369
Node: Windows<32>2975413
Ref: whatsnew/changelog id3172975517
Ref: 11f62975517
Ref: Windows<32>-Footnote-12978004
Ref: Windows<32>-Footnote-22978047
Ref: Windows<32>-Footnote-32978090
Ref: Windows<32>-Footnote-42978133
Ref: Windows<32>-Footnote-52978176
Ref: Windows<32>-Footnote-62978219
Ref: Windows<32>-Footnote-72978262
Ref: Windows<32>-Footnote-82978305
Ref: Windows<32>-Footnote-92978348
Ref: Windows<32>-Footnote-102978391
Ref: Windows<32>-Footnote-112978435
Ref: Windows<32>-Footnote-122978479
Ref: Windows<32>-Footnote-132978523
Ref: Windows<32>-Footnote-142978567
Ref: Windows<32>-Footnote-152978611
Ref: Windows<32>-Footnote-162978655
Ref: Windows<32>-Footnote-172978699
Ref: Windows<32>-Footnote-182978743
Ref: Windows<32>-Footnote-192978787
Ref: Windows<32>-Footnote-202978831
Ref: Windows<32>-Footnote-212978875
Ref: Windows<32>-Footnote-222978919
Ref: Windows<32>-Footnote-232978963
Ref: Windows<32>-Footnote-242979007
Ref: Windows<32>-Footnote-252979051
Node: IDLE<32>2979095
Ref: whatsnew/changelog id3182979206
Ref: 11f72979206
Ref: IDLE<32>-Footnote-12989223
Ref: IDLE<32>-Footnote-22989266
Ref: IDLE<32>-Footnote-32989309
Ref: IDLE<32>-Footnote-42989352
Ref: IDLE<32>-Footnote-52989395
Ref: IDLE<32>-Footnote-62989438
Ref: IDLE<32>-Footnote-72989481
Ref: IDLE<32>-Footnote-82989524
Ref: IDLE<32>-Footnote-92989567
Ref: IDLE<32>-Footnote-102989610
Ref: IDLE<32>-Footnote-112989654
Ref: IDLE<32>-Footnote-122989698
Ref: IDLE<32>-Footnote-132989742
Ref: IDLE<32>-Footnote-142989786
Ref: IDLE<32>-Footnote-152989830
Ref: IDLE<32>-Footnote-162989874
Ref: IDLE<32>-Footnote-172989918
Ref: IDLE<32>-Footnote-182989962
Ref: IDLE<32>-Footnote-192990006
Ref: IDLE<32>-Footnote-202990050
Ref: IDLE<32>-Footnote-212990094
Ref: IDLE<32>-Footnote-222990138
Ref: IDLE<32>-Footnote-232990182
Ref: IDLE<32>-Footnote-242990226
Ref: IDLE<32>-Footnote-252990270
Ref: IDLE<32>-Footnote-262990314
Ref: IDLE<32>-Footnote-272990358
Ref: IDLE<32>-Footnote-282990402
Ref: IDLE<32>-Footnote-292990446
Ref: IDLE<32>-Footnote-302990490
Ref: IDLE<32>-Footnote-312990534
Ref: IDLE<32>-Footnote-322990578
Ref: IDLE<32>-Footnote-332990622
Ref: IDLE<32>-Footnote-342990666
Ref: IDLE<32>-Footnote-352990709
Ref: IDLE<32>-Footnote-362990753
Ref: IDLE<32>-Footnote-372990797
Ref: IDLE<32>-Footnote-382990841
Ref: IDLE<32>-Footnote-392990885
Ref: IDLE<32>-Footnote-402990929
Ref: IDLE<32>-Footnote-412990973
Ref: IDLE<32>-Footnote-422991017
Ref: IDLE<32>-Footnote-432991061
Ref: IDLE<32>-Footnote-442991104
Ref: IDLE<32>-Footnote-452991148
Ref: IDLE<32>-Footnote-462991192
Ref: IDLE<32>-Footnote-472991236
Ref: IDLE<32>-Footnote-482991280
Ref: IDLE<32>-Footnote-492991324
Ref: IDLE<32>-Footnote-502991368
Ref: IDLE<32>-Footnote-512991412
Node: 工具/示例<17>2991456
Ref: whatsnew/changelog id3192991565
Ref: 11f82991565
Ref: 工具/示例<17>-Footnote-12993060
Ref: 工具/示例<17>-Footnote-22993103
Ref: 工具/示例<17>-Footnote-32993152
Ref: 工具/示例<17>-Footnote-42993195
Ref: 工具/示例<17>-Footnote-52993238
Ref: 工具/示例<17>-Footnote-62993281
Ref: 工具/示例<17>-Footnote-72993324
Ref: 工具/示例<17>-Footnote-82993367
Node: C API<27>2993410
Ref: whatsnew/changelog id3202993502
Ref: 11f92993502
Ref: C API<27>-Footnote-12996558
Ref: C API<27>-Footnote-22996601
Ref: C API<27>-Footnote-32996644
Ref: C API<27>-Footnote-42996687
Ref: C API<27>-Footnote-52996730
Ref: C API<27>-Footnote-62996772
Ref: C API<27>-Footnote-72996815
Ref: C API<27>-Footnote-82996858
Ref: C API<27>-Footnote-92996901
Ref: C API<27>-Footnote-102996944
Ref: C API<27>-Footnote-112996988
Ref: C API<27>-Footnote-122997032
Ref: C API<27>-Footnote-132997076
Ref: C API<27>-Footnote-142997120
Ref: C API<27>-Footnote-152997164
Node: Python 3 6 6 正式版2997208
Ref: whatsnew/changelog python-3-6-6-final2997348
Ref: 11fa2997348
Node: Python 3 6 6 rc12997478
Ref: whatsnew/changelog python-3-6-6-release-candidate-12997620
Ref: 11fb2997620
Node: 核心与内置函数<39>2997961
Ref: whatsnew/changelog id3212998055
Ref: 11fc2998055
Ref: 核心与内置函数<39>-Footnote-12999643
Ref: 核心与内置函数<39>-Footnote-22999686
Ref: 核心与内置函数<39>-Footnote-32999729
Ref: 核心与内置函数<39>-Footnote-42999772
Ref: 核心与内置函数<39>-Footnote-52999815
Ref: 核心与内置函数<39>-Footnote-62999858
Ref: 核心与内置函数<39>-Footnote-72999901
Ref: 核心与内置函数<39>-Footnote-82999944
Ref: 核心与内置函数<39>-Footnote-92999987
Ref: 核心与内置函数<39>-Footnote-103000030
Ref: 核心与内置函数<39>-Footnote-113000074
Ref: 核心与内置函数<39>-Footnote-123000118
Node: 库<42>3000162
Ref: whatsnew/changelog id3223000275
Ref: 11fd3000275
Ref: 库<42>-Footnote-13005741
Ref: 库<42>-Footnote-23005784
Ref: 库<42>-Footnote-33005827
Ref: 库<42>-Footnote-43005870
Ref: 库<42>-Footnote-53005913
Ref: 库<42>-Footnote-63005956
Ref: 库<42>-Footnote-73005999
Ref: 库<42>-Footnote-83006042
Ref: 库<42>-Footnote-93006085
Ref: 库<42>-Footnote-103006128
Ref: 库<42>-Footnote-113006172
Ref: 库<42>-Footnote-123006216
Ref: 库<42>-Footnote-133006260
Ref: 库<42>-Footnote-143006304
Ref: 库<42>-Footnote-153006348
Ref: 库<42>-Footnote-163006392
Ref: 库<42>-Footnote-173006436
Ref: 库<42>-Footnote-183006480
Ref: 库<42>-Footnote-193006524
Ref: 库<42>-Footnote-203006568
Ref: 库<42>-Footnote-213006612
Ref: 库<42>-Footnote-223006657
Ref: 库<42>-Footnote-233006701
Ref: 库<42>-Footnote-243006745
Ref: 库<42>-Footnote-253006789
Ref: 库<42>-Footnote-263006833
Ref: 库<42>-Footnote-273006877
Ref: 库<42>-Footnote-283006921
Ref: 库<42>-Footnote-293006971
Ref: 库<42>-Footnote-303007015
Ref: 库<42>-Footnote-313007059
Ref: 库<42>-Footnote-323007103
Ref: 库<42>-Footnote-333007147
Ref: 库<42>-Footnote-343007191
Ref: 库<42>-Footnote-353007235
Ref: 库<42>-Footnote-363007279
Ref: 库<42>-Footnote-373007323
Ref: 库<42>-Footnote-383007367
Ref: 库<42>-Footnote-393007411
Node: 文档<36>3007455
Ref: whatsnew/changelog id3233007553
Ref: 11fe3007553
Ref: 文档<36>-Footnote-13009030
Ref: 文档<36>-Footnote-23009073
Ref: 文档<36>-Footnote-33009116
Ref: 文档<36>-Footnote-43009159
Ref: 文档<36>-Footnote-53009202
Ref: 文档<36>-Footnote-63009245
Ref: 文档<36>-Footnote-73009288
Ref: 文档<36>-Footnote-83009331
Ref: 文档<36>-Footnote-93009374
Ref: 文档<36>-Footnote-103009417
Ref: 文档<36>-Footnote-113009461
Ref: 文档<36>-Footnote-123009505
Ref: 文档<36>-Footnote-133009548
Node: 测试<33>3009592
Ref: whatsnew/changelog id3243009693
Ref: 11ff3009693
Ref: 测试<33>-Footnote-13009894
Ref: 测试<33>-Footnote-23009937
Node: 构建<33>3009980
Ref: whatsnew/changelog id3253010082
Ref: 12003010082
Ref: 构建<33>-Footnote-13010879
Ref: 构建<33>-Footnote-23010921
Ref: 构建<33>-Footnote-33010964
Ref: 构建<33>-Footnote-43011007
Ref: 构建<33>-Footnote-53011050
Node: Windows<33>3011093
Ref: whatsnew/changelog id3263011194
Ref: 12013011194
Ref: Windows<33>-Footnote-13011332
Node: macOS<27>3011375
Ref: whatsnew/changelog id3273011474
Ref: 12023011474
Ref: macOS<27>-Footnote-13011612
Node: IDLE<33>3011655
Ref: whatsnew/changelog id3283011760
Ref: 12033011760
Ref: IDLE<33>-Footnote-13013829
Ref: IDLE<33>-Footnote-23013872
Ref: IDLE<33>-Footnote-33013915
Ref: IDLE<33>-Footnote-43013958
Ref: IDLE<33>-Footnote-53014001
Ref: IDLE<33>-Footnote-63014044
Ref: IDLE<33>-Footnote-73014087
Ref: IDLE<33>-Footnote-83014130
Ref: IDLE<33>-Footnote-93014173
Ref: IDLE<33>-Footnote-103014216
Ref: IDLE<33>-Footnote-113014260
Ref: IDLE<33>-Footnote-123014304
Node: 工具/示例<18>3014348
Ref: whatsnew/changelog id3293014453
Ref: 12043014453
Ref: 工具/示例<18>-Footnote-13015208
Ref: 工具/示例<18>-Footnote-23015251
Ref: 工具/示例<18>-Footnote-33015294
Ref: 工具/示例<18>-Footnote-43015337
Ref: 工具/示例<18>-Footnote-53015380
Node: C API<28>3015423
Ref: whatsnew/changelog id3303015511
Ref: 12053015511
Ref: C API<28>-Footnote-13015724
Node: Python 3 6 5 正式版3015767
Ref: whatsnew/changelog python-3-6-5-final3015903
Ref: 12063015903
Node: 测试<34>3016045
Ref: whatsnew/changelog id3313016133
Ref: 12073016133
Ref: 测试<34>-Footnote-13016287
Node: 构建<34>3016330
Ref: whatsnew/changelog id3323016418
Ref: 12083016418
Ref: 构建<34>-Footnote-13016555
Node: Python 3 6 5 rc13016598
Ref: whatsnew/changelog python-3-6-5-release-candidate-13016740
Ref: 12093016740
Node: 安全性<22>3017109
Ref: whatsnew/changelog id3333017209
Ref: 120a3017209
Ref: 安全性<22>-Footnote-13017633
Ref: 安全性<22>-Footnote-23017676
Node: 核心与内置函数<40>3017719
Ref: whatsnew/changelog id3343017835
Ref: 120b3017835
Ref: 核心与内置函数<40>-Footnote-13020006
Ref: 核心与内置函数<40>-Footnote-23020049
Ref: 核心与内置函数<40>-Footnote-33020092
Ref: 核心与内置函数<40>-Footnote-43020135
Ref: 核心与内置函数<40>-Footnote-53020178
Ref: 核心与内置函数<40>-Footnote-63020221
Ref: 核心与内置函数<40>-Footnote-73020264
Ref: 核心与内置函数<40>-Footnote-83020307
Ref: 核心与内置函数<40>-Footnote-93020350
Ref: 核心与内置函数<40>-Footnote-103020393
Ref: 核心与内置函数<40>-Footnote-113020437
Ref: 核心与内置函数<40>-Footnote-123020481
Ref: 核心与内置函数<40>-Footnote-133020525
Ref: 核心与内置函数<40>-Footnote-143020569
Node: 库<43>3020613
Ref: whatsnew/changelog id3353020726
Ref: 120c3020726
Ref: 库<43>-Footnote-13026647
Ref: 库<43>-Footnote-23026690
Ref: 库<43>-Footnote-33026733
Ref: 库<43>-Footnote-43026776
Ref: 库<43>-Footnote-53026819
Ref: 库<43>-Footnote-63026862
Ref: 库<43>-Footnote-73026905
Ref: 库<43>-Footnote-83026948
Ref: 库<43>-Footnote-93026991
Ref: 库<43>-Footnote-103027034
Ref: 库<43>-Footnote-113027078
Ref: 库<43>-Footnote-123027122
Ref: 库<43>-Footnote-133027166
Ref: 库<43>-Footnote-143027210
Ref: 库<43>-Footnote-153027254
Ref: 库<43>-Footnote-163027298
Ref: 库<43>-Footnote-173027342
Ref: 库<43>-Footnote-183027386
Ref: 库<43>-Footnote-193027430
Ref: 库<43>-Footnote-203027474
Ref: 库<43>-Footnote-213027518
Ref: 库<43>-Footnote-223027562
Ref: 库<43>-Footnote-233027606
Ref: 库<43>-Footnote-243027650
Ref: 库<43>-Footnote-253027694
Ref: 库<43>-Footnote-263027738
Ref: 库<43>-Footnote-273027782
Ref: 库<43>-Footnote-283027826
Ref: 库<43>-Footnote-293027870
Ref: 库<43>-Footnote-303027914
Ref: 库<43>-Footnote-313027958
Ref: 库<43>-Footnote-323028002
Ref: 库<43>-Footnote-333028046
Ref: 库<43>-Footnote-343028090
Ref: 库<43>-Footnote-353028134
Ref: 库<43>-Footnote-363028178
Ref: 库<43>-Footnote-373028222
Ref: 库<43>-Footnote-383028266
Ref: 库<43>-Footnote-393028310
Ref: 库<43>-Footnote-403028354
Node: 文档<37>3028398
Ref: whatsnew/changelog id3363028496
Ref: 120d3028496
Ref: 文档<37>-Footnote-13029333
Ref: 文档<37>-Footnote-23029376
Ref: 文档<37>-Footnote-33029419
Ref: 文档<37>-Footnote-43029461
Ref: 文档<37>-Footnote-53029504
Ref: 文档<37>-Footnote-63029547
Node: 测试<35>3029590
Ref: whatsnew/changelog id3373029691
Ref: 120e3029691
Ref: 测试<35>-Footnote-13030352
Ref: 测试<35>-Footnote-23030395
Ref: 测试<35>-Footnote-33030438
Ref: 测试<35>-Footnote-43030481
Node: 构建<35>3030524
Ref: whatsnew/changelog id3383030626
Ref: 120f3030626
Ref: 构建<35>-Footnote-13030815
Node: Windows<34>3030858
Ref: whatsnew/changelog id3393030959
Ref: 12103030959
Ref: Windows<34>-Footnote-13031909
Ref: Windows<34>-Footnote-23031952
Ref: Windows<34>-Footnote-33031995
Ref: Windows<34>-Footnote-43032038
Ref: Windows<34>-Footnote-53032081
Ref: Windows<34>-Footnote-63032124
Ref: Windows<34>-Footnote-73032167
Ref: Windows<34>-Footnote-83032210
Node: macOS<28>3032253
Ref: whatsnew/changelog id3403032352
Ref: 12113032352
Ref: macOS<28>-Footnote-13032745
Node: IDLE<34>3032788
Ref: whatsnew/changelog id3413032893
Ref: 12123032893
Ref: IDLE<34>-Footnote-13034383
Ref: IDLE<34>-Footnote-23034426
Ref: IDLE<34>-Footnote-33034469
Ref: IDLE<34>-Footnote-43034512
Ref: IDLE<34>-Footnote-53034555
Ref: IDLE<34>-Footnote-63034598
Ref: IDLE<34>-Footnote-73034641
Ref: IDLE<34>-Footnote-83034684
Node: 工具/示例<19>3034727
Ref: whatsnew/changelog id3423034832
Ref: 12133034832
Ref: 工具/示例<19>-Footnote-13035252
Ref: 工具/示例<19>-Footnote-23035295
Node: C API<29>3035338
Ref: whatsnew/changelog id3433035426
Ref: 12143035426
Ref: C API<29>-Footnote-13035676
Node: Python 3 6 4 正式版3035719
Ref: whatsnew/changelog python-3-6-4-final3035855
Ref: 12153035855
Node: Python 3 6 4 rc13036008
Ref: whatsnew/changelog python-3-6-4-release-candidate-13036150
Ref: 12163036150
Node: 核心与内置函数<41>3036491
Ref: whatsnew/changelog id3443036585
Ref: 12173036585
Ref: 核心与内置函数<41>-Footnote-13041335
Ref: 核心与内置函数<41>-Footnote-23041378
Ref: 核心与内置函数<41>-Footnote-33041421
Ref: 核心与内置函数<41>-Footnote-43041464
Ref: 核心与内置函数<41>-Footnote-53041507
Ref: 核心与内置函数<41>-Footnote-63041550
Ref: 核心与内置函数<41>-Footnote-73041593
Ref: 核心与内置函数<41>-Footnote-83041636
Ref: 核心与内置函数<41>-Footnote-93041679
Ref: 核心与内置函数<41>-Footnote-103041722
Ref: 核心与内置函数<41>-Footnote-113041766
Ref: 核心与内置函数<41>-Footnote-123041810
Ref: 核心与内置函数<41>-Footnote-133041854
Ref: 核心与内置函数<41>-Footnote-143041898
Ref: 核心与内置函数<41>-Footnote-153041942
Ref: 核心与内置函数<41>-Footnote-163041986
Ref: 核心与内置函数<41>-Footnote-173042030
Ref: 核心与内置函数<41>-Footnote-183042074
Ref: 核心与内置函数<41>-Footnote-193042118
Ref: 核心与内置函数<41>-Footnote-203042162
Ref: 核心与内置函数<41>-Footnote-213042206
Ref: 核心与内置函数<41>-Footnote-223042250
Ref: 核心与内置函数<41>-Footnote-233042294
Ref: 核心与内置函数<41>-Footnote-243042338
Node: 库<44>3042382
Ref: whatsnew/changelog id3453042495
Ref: 12183042495
Ref: 库<44>-Footnote-13049824
Ref: 库<44>-Footnote-23049867
Ref: 库<44>-Footnote-33049910
Ref: 库<44>-Footnote-43049953
Ref: 库<44>-Footnote-53049996
Ref: 库<44>-Footnote-63050039
Ref: 库<44>-Footnote-73050082
Ref: 库<44>-Footnote-83050125
Ref: 库<44>-Footnote-93050168
Ref: 库<44>-Footnote-103050211
Ref: 库<44>-Footnote-113050255
Ref: 库<44>-Footnote-123050299
Ref: 库<44>-Footnote-133050343
Ref: 库<44>-Footnote-143050387
Ref: 库<44>-Footnote-153050431
Ref: 库<44>-Footnote-163050475
Ref: 库<44>-Footnote-173050518
Ref: 库<44>-Footnote-183050562
Ref: 库<44>-Footnote-193050606
Ref: 库<44>-Footnote-203050650
Ref: 库<44>-Footnote-213050694
Ref: 库<44>-Footnote-223050738
Ref: 库<44>-Footnote-233050782
Ref: 库<44>-Footnote-243050826
Ref: 库<44>-Footnote-253050870
Ref: 库<44>-Footnote-263050914
Ref: 库<44>-Footnote-273050958
Ref: 库<44>-Footnote-283051002
Ref: 库<44>-Footnote-293051046
Ref: 库<44>-Footnote-303051090
Ref: 库<44>-Footnote-313051134
Ref: 库<44>-Footnote-323051178
Ref: 库<44>-Footnote-333051222
Ref: 库<44>-Footnote-343051266
Ref: 库<44>-Footnote-353051310
Ref: 库<44>-Footnote-363051354
Ref: 库<44>-Footnote-373051398
Ref: 库<44>-Footnote-383051442
Ref: 库<44>-Footnote-393051486
Ref: 库<44>-Footnote-403051530
Ref: 库<44>-Footnote-413051574
Ref: 库<44>-Footnote-423051618
Ref: 库<44>-Footnote-433051662
Ref: 库<44>-Footnote-443051706
Ref: 库<44>-Footnote-453051750
Ref: 库<44>-Footnote-463051794
Ref: 库<44>-Footnote-473051838
Ref: 库<44>-Footnote-483051882
Ref: 库<44>-Footnote-493051926
Ref: 库<44>-Footnote-503051970
Ref: 库<44>-Footnote-513052014
Ref: 库<44>-Footnote-523052058
Node: 文档<38>3052102
Ref: whatsnew/changelog id3463052200
Ref: 12193052200
Ref: 文档<38>-Footnote-13052673
Ref: 文档<38>-Footnote-23052716
Ref: 文档<38>-Footnote-33052759
Node: 测试<36>3052802
Ref: whatsnew/changelog id3473052903
Ref: 121a3052903
Ref: 测试<36>-Footnote-13053575
Ref: 测试<36>-Footnote-23053618
Ref: 测试<36>-Footnote-33053661
Ref: 测试<36>-Footnote-43053704
Node: 构建<36>3053747
Ref: whatsnew/changelog id3483053849
Ref: 121b3053849
Ref: 构建<36>-Footnote-13054760
Ref: 构建<36>-Footnote-23054803
Ref: 构建<36>-Footnote-33054846
Ref: 构建<36>-Footnote-43054889
Ref: 构建<36>-Footnote-53054932
Ref: 构建<36>-Footnote-63054975
Ref: 构建<36>-Footnote-73055018
Ref: 构建<36>-Footnote-83055061
Ref: 构建<36>-Footnote-93055104
Node: Windows<35>3055147
Ref: whatsnew/changelog id3493055248
Ref: 121c3055248
Ref: Windows<35>-Footnote-13055566
Ref: Windows<35>-Footnote-23055608
Node: macOS<29>3055651
Ref: whatsnew/changelog id3503055750
Ref: 121d3055750
Ref: macOS<29>-Footnote-13055888
Node: IDLE<35>3055931
Ref: whatsnew/changelog id3513056036
Ref: 121e3056036
Ref: IDLE<35>-Footnote-13059373
Ref: IDLE<35>-Footnote-23059416
Ref: IDLE<35>-Footnote-33059459
Ref: IDLE<35>-Footnote-43059502
Ref: IDLE<35>-Footnote-53059545
Ref: IDLE<35>-Footnote-63059588
Ref: IDLE<35>-Footnote-73059631
Ref: IDLE<35>-Footnote-83059674
Ref: IDLE<35>-Footnote-93059717
Ref: IDLE<35>-Footnote-103059760
Ref: IDLE<35>-Footnote-113059804
Ref: IDLE<35>-Footnote-123059848
Ref: IDLE<35>-Footnote-133059892
Ref: IDLE<35>-Footnote-143059936
Node: 工具/示例<20>3059982
Ref: whatsnew/changelog id3523060087
Ref: 121f3060087
Ref: 工具/示例<20>-Footnote-13060377
Node: C API<30>3060420
Ref: whatsnew/changelog id3533060508
Ref: 12203060508
Ref: C API<30>-Footnote-13061236
Ref: C API<30>-Footnote-23061279
Ref: C API<30>-Footnote-33061322
Ref: C API<30>-Footnote-43061365
Node: Python 3 6 3 正式版3061408
Ref: whatsnew/changelog python-3-6-3-final3061544
Ref: 12213061544
Node: 库<45>3061680
Ref: whatsnew/changelog id3543061765
Ref: 12223061765
Ref: 库<45>-Footnote-13061969
Node: 构建<37>3062012
Ref: whatsnew/changelog id3553062097
Ref: 12243062097
Ref: 构建<37>-Footnote-13062388
Ref: 构建<37>-Footnote-23062431
Node: Python 3 6 3 rc13062474
Ref: whatsnew/changelog python-3-6-3-release-candidate-13062616
Ref: 12253062616
Node: 安全性<23>3062945
Ref: whatsnew/changelog id3563063045
Ref: 12263063045
Ref: 安全性<23>-Footnote-13063350
Ref: 安全性<23>-Footnote-23063393
Node: 核心与内置函数<42>3063436
Ref: whatsnew/changelog id3573063552
Ref: 12273063552
Ref: 核心与内置函数<42>-Footnote-13067100
Ref: 核心与内置函数<42>-Footnote-23067143
Ref: 核心与内置函数<42>-Footnote-33067186
Ref: 核心与内置函数<42>-Footnote-43067229
Ref: 核心与内置函数<42>-Footnote-53067272
Ref: 核心与内置函数<42>-Footnote-63067315
Ref: 核心与内置函数<42>-Footnote-73067358
Ref: 核心与内置函数<42>-Footnote-83067401
Ref: 核心与内置函数<42>-Footnote-93067444
Ref: 核心与内置函数<42>-Footnote-103067487
Ref: 核心与内置函数<42>-Footnote-113067531
Ref: 核心与内置函数<42>-Footnote-123067575
Ref: 核心与内置函数<42>-Footnote-133067619
Ref: 核心与内置函数<42>-Footnote-143067663
Ref: 核心与内置函数<42>-Footnote-153067707
Ref: 核心与内置函数<42>-Footnote-163067751
Ref: 核心与内置函数<42>-Footnote-173067795
Ref: 核心与内置函数<42>-Footnote-183067839
Ref: 核心与内置函数<42>-Footnote-193067883
Ref: 核心与内置函数<42>-Footnote-203067927
Ref: 核心与内置函数<42>-Footnote-213067971
Ref: 核心与内置函数<42>-Footnote-223068015
Node: 库<46>3068059
Ref: whatsnew/changelog id3583068172
Ref: 12283068172
Ref: 库<46>-Footnote-13074161
Ref: 库<46>-Footnote-23074204
Ref: 库<46>-Footnote-33074247
Ref: 库<46>-Footnote-43074290
Ref: 库<46>-Footnote-53074333
Ref: 库<46>-Footnote-63074376
Ref: 库<46>-Footnote-73074419
Ref: 库<46>-Footnote-83074462
Ref: 库<46>-Footnote-93074505
Ref: 库<46>-Footnote-103074548
Ref: 库<46>-Footnote-113074592
Ref: 库<46>-Footnote-123074636
Ref: 库<46>-Footnote-133074680
Ref: 库<46>-Footnote-143074724
Ref: 库<46>-Footnote-153074768
Ref: 库<46>-Footnote-163074811
Ref: 库<46>-Footnote-173074855
Ref: 库<46>-Footnote-183074899
Ref: 库<46>-Footnote-193074949
Ref: 库<46>-Footnote-203074993
Ref: 库<46>-Footnote-213075037
Ref: 库<46>-Footnote-223075081
Ref: 库<46>-Footnote-233075125
Ref: 库<46>-Footnote-243075169
Ref: 库<46>-Footnote-253075213
Ref: 库<46>-Footnote-263075257
Ref: 库<46>-Footnote-273075301
Ref: 库<46>-Footnote-283075345
Ref: 库<46>-Footnote-293075389
Ref: 库<46>-Footnote-303075433
Ref: 库<46>-Footnote-313075477
Ref: 库<46>-Footnote-323075521
Ref: 库<46>-Footnote-333075565
Ref: 库<46>-Footnote-343075609
Ref: 库<46>-Footnote-353075653
Ref: 库<46>-Footnote-363075697
Ref: 库<46>-Footnote-373075741
Ref: 库<46>-Footnote-383075785
Ref: 库<46>-Footnote-393075829
Ref: 库<46>-Footnote-403075873
Ref: 库<46>-Footnote-413075917
Ref: 库<46>-Footnote-423075961
Node: 文档<39>3076005
Ref: whatsnew/changelog id3593076103
Ref: 12293076103
Ref: 文档<39>-Footnote-13076510
Ref: 文档<39>-Footnote-23076553
Ref: 文档<39>-Footnote-33076596
Node: 测试<37>3076639
Ref: whatsnew/changelog id3603076740
Ref: 122a3076740
Ref: 测试<37>-Footnote-13077445
Ref: 测试<37>-Footnote-23077488
Ref: 测试<37>-Footnote-33077531
Ref: 测试<37>-Footnote-43077574
Node: 构建<38>3077617
Ref: whatsnew/changelog id3613077719
Ref: 122b3077719
Ref: 构建<38>-Footnote-13077894
Node: Windows<36>3077937
Ref: whatsnew/changelog id3623078037
Ref: 122c3078037
Ref: Windows<36>-Footnote-13078545
Ref: Windows<36>-Footnote-23078588
Ref: Windows<36>-Footnote-33078631
Ref: Windows<36>-Footnote-43078674
Node: IDLE<36>3078717
Ref: whatsnew/changelog id3633078824
Ref: 122d3078824
Ref: IDLE<36>-Footnote-13087673
Ref: IDLE<36>-Footnote-23087716
Ref: IDLE<36>-Footnote-33087759
Ref: IDLE<36>-Footnote-43087802
Ref: IDLE<36>-Footnote-53087845
Ref: IDLE<36>-Footnote-63087888
Ref: IDLE<36>-Footnote-73087931
Ref: IDLE<36>-Footnote-83087974
Ref: IDLE<36>-Footnote-93088017
Ref: IDLE<36>-Footnote-103088060
Ref: IDLE<36>-Footnote-113088104
Ref: IDLE<36>-Footnote-123088148
Ref: IDLE<36>-Footnote-133088192
Ref: IDLE<36>-Footnote-143088236
Ref: IDLE<36>-Footnote-153088280
Ref: IDLE<36>-Footnote-163088324
Ref: IDLE<36>-Footnote-173088368
Ref: IDLE<36>-Footnote-183088412
Ref: IDLE<36>-Footnote-193088456
Ref: IDLE<36>-Footnote-203088500
Ref: IDLE<36>-Footnote-213088544
Ref: IDLE<36>-Footnote-223088588
Ref: IDLE<36>-Footnote-233088632
Ref: IDLE<36>-Footnote-243088676
Ref: IDLE<36>-Footnote-253088720
Ref: IDLE<36>-Footnote-263088764
Ref: IDLE<36>-Footnote-273088808
Ref: IDLE<36>-Footnote-283088852
Ref: IDLE<36>-Footnote-293088896
Ref: IDLE<36>-Footnote-303088940
Ref: IDLE<36>-Footnote-313088984
Ref: IDLE<36>-Footnote-323089028
Ref: IDLE<36>-Footnote-333089072
Ref: IDLE<36>-Footnote-343089116
Ref: IDLE<36>-Footnote-353089159
Ref: IDLE<36>-Footnote-363089203
Ref: IDLE<36>-Footnote-373089247
Ref: IDLE<36>-Footnote-383089291
Ref: IDLE<36>-Footnote-393089335
Ref: IDLE<36>-Footnote-403089379
Ref: IDLE<36>-Footnote-413089423
Ref: IDLE<36>-Footnote-423089467
Ref: IDLE<36>-Footnote-433089511
Node: 工具/示例<21>3089554
Ref: whatsnew/changelog id3643089641
Ref: 122e3089641
Ref: 工具/示例<21>-Footnote-13090199
Ref: 工具/示例<21>-Footnote-23090242
Node: Python 3 6 2 正式版3090291
Ref: whatsnew/changelog python-3-6-2-final3090427
Ref: 122f3090427
Node: Python 3 6 2 rc23090538
Ref: whatsnew/changelog python-3-6-2-release-candidate-23090674
Ref: 12303090674
Node: 安全性<24>3090791
Ref: whatsnew/changelog id3653090857
Ref: 12313090857
Ref: 安全性<24>-Footnote-13091963
Ref: 安全性<24>-Footnote-23092006
Ref: 安全性<24>-Footnote-33092049
Node: Python 3 6 2 rc13092092
Ref: whatsnew/changelog python-3-6-2-release-candidate-13092228
Ref: 12323092228
Node: 核心与内置函数<43>3092593
Ref: whatsnew/changelog id3663092687
Ref: 12333092687
Ref: 核心与内置函数<43>-Footnote-13094681
Ref: 核心与内置函数<43>-Footnote-23094724
Ref: 核心与内置函数<43>-Footnote-33094767
Ref: 核心与内置函数<43>-Footnote-43094810
Ref: 核心与内置函数<43>-Footnote-53094853
Ref: 核心与内置函数<43>-Footnote-63094896
Ref: 核心与内置函数<43>-Footnote-73094939
Ref: 核心与内置函数<43>-Footnote-83094982
Ref: 核心与内置函数<43>-Footnote-93095025
Ref: 核心与内置函数<43>-Footnote-103095068
Ref: 核心与内置函数<43>-Footnote-113095112
Ref: 核心与内置函数<43>-Footnote-123095156
Ref: 核心与内置函数<43>-Footnote-133095200
Ref: 核心与内置函数<43>-Footnote-143095244
Ref: 核心与内置函数<43>-Footnote-153095288
Node: 库<47>3095332
Ref: whatsnew/changelog id3673095448
Ref: 12343095448
Ref: 库<47>-Footnote-13096573
Ref: 库<47>-Footnote-23096616
Ref: 库<47>-Footnote-33096659
Ref: 库<47>-Footnote-43096702
Ref: 库<47>-Footnote-53096745
Ref: 库<47>-Footnote-63096788
Ref: 库<47>-Footnote-73096831
Ref: 库<47>-Footnote-83096874
Node: 安全性<25>3096917
Ref: whatsnew/changelog id3683097015
Ref: 12353097015
Ref: 安全性<25>-Footnote-13097281
Node: 库<48>3097324
Ref: whatsnew/changelog id3693097423
Ref: 12363097423
Ref: 库<48>-Footnote-13104763
Ref: 库<48>-Footnote-23104806
Ref: 库<48>-Footnote-33104849
Ref: 库<48>-Footnote-43104892
Ref: 库<48>-Footnote-53104935
Ref: 库<48>-Footnote-63104978
Ref: 库<48>-Footnote-73105021
Ref: 库<48>-Footnote-83105064
Ref: 库<48>-Footnote-93105107
Ref: 库<48>-Footnote-103105150
Ref: 库<48>-Footnote-113105194
Ref: 库<48>-Footnote-123105238
Ref: 库<48>-Footnote-133105282
Ref: 库<48>-Footnote-143105326
Ref: 库<48>-Footnote-153105370
Ref: 库<48>-Footnote-163105414
Ref: 库<48>-Footnote-173105458
Ref: 库<48>-Footnote-183105502
Ref: 库<48>-Footnote-193105546
Ref: 库<48>-Footnote-203105590
Ref: 库<48>-Footnote-213105634
Ref: 库<48>-Footnote-223105678
Ref: 库<48>-Footnote-233105722
Ref: 库<48>-Footnote-243105766
Ref: 库<48>-Footnote-253105810
Ref: 库<48>-Footnote-263105854
Ref: 库<48>-Footnote-273105898
Ref: 库<48>-Footnote-283105942
Ref: 库<48>-Footnote-293105986
Ref: 库<48>-Footnote-303106030
Ref: 库<48>-Footnote-313106074
Ref: 库<48>-Footnote-323106118
Ref: 库<48>-Footnote-333106162
Ref: 库<48>-Footnote-343106206
Ref: 库<48>-Footnote-353106250
Ref: 库<48>-Footnote-363106294
Ref: 库<48>-Footnote-373106338
Ref: 库<48>-Footnote-383106382
Ref: 库<48>-Footnote-393106426
Ref: 库<48>-Footnote-403106470
Ref: 库<48>-Footnote-413106514
Ref: 库<48>-Footnote-423106558
Ref: 库<48>-Footnote-433106602
Ref: 库<48>-Footnote-443106646
Ref: 库<48>-Footnote-453106690
Ref: 库<48>-Footnote-463106734
Ref: 库<48>-Footnote-473106778
Ref: 库<48>-Footnote-483106821
Ref: 库<48>-Footnote-493106865
Ref: 库<48>-Footnote-503106909
Ref: 库<48>-Footnote-513106953
Ref: 库<48>-Footnote-523106997
Node: IDLE<37>3107041
Ref: whatsnew/changelog id3703107136
Ref: 12373107136
Ref: IDLE<37>-Footnote-13108141
Ref: IDLE<37>-Footnote-23108184
Ref: IDLE<37>-Footnote-33108227
Ref: IDLE<37>-Footnote-43108270
Ref: IDLE<37>-Footnote-53108313
Ref: IDLE<37>-Footnote-63108356
Node: C API<31>3108399
Ref: whatsnew/changelog id3713108497
Ref: 12383108497
Ref: C API<31>-Footnote-13108685
Node: 构建<39>3108728
Ref: whatsnew/changelog id3723108828
Ref: 12393108828
Ref: 构建<39>-Footnote-13109637
Ref: 构建<39>-Footnote-23109680
Ref: 构建<39>-Footnote-33109723
Ref: 构建<39>-Footnote-43109766
Ref: 构建<39>-Footnote-53109809
Node: 文档<40>3109852
Ref: whatsnew/changelog id3733109960
Ref: 123a3109960
Ref: 文档<40>-Footnote-13110673
Ref: 文档<40>-Footnote-23110716
Ref: 文档<40>-Footnote-33110759
Node: 工具/示例<22>3110802
Ref: whatsnew/changelog id3743110910
Ref: 123b3110910
Ref: 工具/示例<22>-Footnote-13111100
Node: 测试<38>3111143
Ref: whatsnew/changelog id3753111252
Ref: 123c3111252
Ref: 测试<38>-Footnote-13111911
Ref: 测试<38>-Footnote-23111954
Node: Windows<37>3111997
Ref: whatsnew/changelog id3763112080
Ref: 123d3112080
Ref: Windows<37>-Footnote-13112524
Ref: Windows<37>-Footnote-23112567
Node: Python 3 6 1 正式版3112610
Ref: whatsnew/changelog python-3-6-1-final3112746
Ref: 123e3112746
Node: 核心与内置函数<44>3112918
Ref: whatsnew/changelog id3773113021
Ref: 123f3113021
Ref: 核心与内置函数<44>-Footnote-13113641
Ref: 核心与内置函数<44>-Footnote-23113684
Node: 构建<40>3113727
Ref: whatsnew/changelog id3783113830
Ref: 12403113830
Ref: 构建<40>-Footnote-13114012
Node: Python 3 6 1 rc13114055
Ref: whatsnew/changelog python-3-6-1-release-candidate-13114197
Ref: 12413114197
Node: 核心与内置函数<45>3114482
Ref: whatsnew/changelog id3793114576
Ref: 12423114576
Ref: 核心与内置函数<45>-Footnote-13117409
Ref: 核心与内置函数<45>-Footnote-23117452
Ref: 核心与内置函数<45>-Footnote-33117495
Ref: 核心与内置函数<45>-Footnote-43117538
Ref: 核心与内置函数<45>-Footnote-53117581
Ref: 核心与内置函数<45>-Footnote-63117624
Ref: 核心与内置函数<45>-Footnote-73117667
Ref: 核心与内置函数<45>-Footnote-83117710
Ref: 核心与内置函数<45>-Footnote-93117753
Ref: 核心与内置函数<45>-Footnote-103117796
Ref: 核心与内置函数<45>-Footnote-113117840
Ref: 核心与内置函数<45>-Footnote-123117884
Ref: 核心与内置函数<45>-Footnote-133117928
Ref: 核心与内置函数<45>-Footnote-143117972
Ref: 核心与内置函数<45>-Footnote-153118016
Ref: 核心与内置函数<45>-Footnote-163118060
Ref: 核心与内置函数<45>-Footnote-173118104
Ref: 核心与内置函数<45>-Footnote-183118148
Ref: 核心与内置函数<45>-Footnote-193118192
Ref: 核心与内置函数<45>-Footnote-203118236
Ref: 核心与内置函数<45>-Footnote-213118280
Ref: 核心与内置函数<45>-Footnote-223118324
Node: 库<49>3118368
Ref: whatsnew/changelog id3803118479
Ref: 12433118479
Ref: 库<49>-Footnote-13124109
Ref: 库<49>-Footnote-23124152
Ref: 库<49>-Footnote-33124195
Ref: 库<49>-Footnote-43124238
Ref: 库<49>-Footnote-53124281
Ref: 库<49>-Footnote-63124324
Ref: 库<49>-Footnote-73124367
Ref: 库<49>-Footnote-83124410
Ref: 库<49>-Footnote-93124453
Ref: 库<49>-Footnote-103124496
Ref: 库<49>-Footnote-113124540
Ref: 库<49>-Footnote-123124584
Ref: 库<49>-Footnote-133124628
Ref: 库<49>-Footnote-143124672
Ref: 库<49>-Footnote-153124716
Ref: 库<49>-Footnote-163124760
Ref: 库<49>-Footnote-173124804
Ref: 库<49>-Footnote-183124848
Ref: 库<49>-Footnote-193124892
Ref: 库<49>-Footnote-203124936
Ref: 库<49>-Footnote-213124980
Ref: 库<49>-Footnote-223125024
Ref: 库<49>-Footnote-233125068
Ref: 库<49>-Footnote-243125112
Ref: 库<49>-Footnote-253125156
Ref: 库<49>-Footnote-263125200
Ref: 库<49>-Footnote-273125244
Ref: 库<49>-Footnote-283125294
Ref: 库<49>-Footnote-293125338
Ref: 库<49>-Footnote-303125382
Ref: 库<49>-Footnote-313125426
Ref: 库<49>-Footnote-323125470
Ref: 库<49>-Footnote-333125514
Ref: 库<49>-Footnote-343125558
Ref: 库<49>-Footnote-353125602
Ref: 库<49>-Footnote-363125645
Ref: 库<49>-Footnote-373125689
Ref: 库<49>-Footnote-383125733
Ref: 库<49>-Footnote-393125777
Ref: 库<49>-Footnote-403125821
Ref: 库<49>-Footnote-413125865
Ref: 库<49>-Footnote-423125909
Ref: 库<49>-Footnote-433125953
Ref: 库<49>-Footnote-443125997
Node: IDLE<38>3126041
Ref: whatsnew/changelog id3813126138
Ref: 12443126138
Ref: IDLE<38>-Footnote-13126427
Ref: IDLE<38>-Footnote-23126470
Node: Windows<38>3126513
Ref: whatsnew/changelog id3823126612
Ref: 12453126612
Ref: Windows<38>-Footnote-13127259
Ref: Windows<38>-Footnote-23127302
Ref: Windows<38>-Footnote-33127345
Ref: Windows<38>-Footnote-43127388
Ref: Windows<38>-Footnote-53127431
Ref: Windows<38>-Footnote-63127480
Ref: Windows<38>-Footnote-73127523
Ref: Windows<38>-Footnote-83127566
Node: C API<32>3127609
Ref: whatsnew/changelog id3833127710
Ref: 12463127710
Ref: C API<32>-Footnote-13128536
Ref: C API<32>-Footnote-23128579
Ref: C API<32>-Footnote-33128622
Node: 文档<41>3128665
Ref: whatsnew/changelog id3843128765
Ref: 12473128765
Ref: 文档<41>-Footnote-13129286
Ref: 文档<41>-Footnote-23129329
Ref: 文档<41>-Footnote-33129372
Ref: 文档<41>-Footnote-43129415
Node: 测试<39>3129458
Ref: whatsnew/changelog id3853129559
Ref: 12483129559
Ref: 测试<39>-Footnote-13130544
Ref: 测试<39>-Footnote-23130587
Ref: 测试<39>-Footnote-33130630
Ref: 测试<39>-Footnote-43130673
Ref: 测试<39>-Footnote-53130716
Node: 构建<41>3130759
Ref: whatsnew/changelog id3863130841
Ref: 12493130841
Ref: 构建<41>-Footnote-13132099
Ref: 构建<41>-Footnote-23132142
Ref: 构建<41>-Footnote-33132185
Ref: 构建<41>-Footnote-43132228
Ref: 构建<41>-Footnote-53132271
Ref: 构建<41>-Footnote-63132314
Ref: 构建<41>-Footnote-73132357
Ref: 构建<41>-Footnote-83132400
Ref: 构建<41>-Footnote-93132443
Ref: 构建<41>-Footnote-103132486
Node: Python 3 6 0 正式版3132530
Ref: whatsnew/changelog python-3-6-0-final3132666
Ref: 124a3132666
Node: Python 3 6 0 rc23132777
Ref: whatsnew/changelog python-3-6-0-release-candidate-23132913
Ref: 124b3132913
Node: 核心与内置函数<46>3133136
Ref: whatsnew/changelog id3873133240
Ref: 124c3133240
Ref: 核心与内置函数<46>-Footnote-13133626
Ref: 核心与内置函数<46>-Footnote-23133669
Node: 工具/示例<23>3133712
Ref: whatsnew/changelog id3883133836
Ref: 124d3133836
Ref: 工具/示例<23>-Footnote-13133970
Node: Windows<39>3134013
Ref: whatsnew/changelog id3893134122
Ref: 124e3134122
Ref: Windows<39>-Footnote-13134248
Node: 构建<42>3134291
Ref: whatsnew/changelog id3903134374
Ref: 124f3134374
Ref: 构建<42>-Footnote-13134529
Node: Python 3 6 0 rc13134572
Ref: whatsnew/changelog python-3-6-0-release-candidate-13134705
Ref: 12503134705
Node: 核心与内置函数<47>3134940
Ref: whatsnew/changelog id3913135034
Ref: 12513135034
Ref: 核心与内置函数<47>-Footnote-13135844
Ref: 核心与内置函数<47>-Footnote-23135887
Ref: 核心与内置函数<47>-Footnote-33135930
Ref: 核心与内置函数<47>-Footnote-43135973
Node: 库<50>3136016
Ref: whatsnew/changelog id3923136128
Ref: 12523136128
Ref: 库<50>-Footnote-13137158
Ref: 库<50>-Footnote-23137201
Ref: 库<50>-Footnote-33137244
Ref: 库<50>-Footnote-43137287
Ref: 库<50>-Footnote-53137330
Ref: 库<50>-Footnote-63137373
Node: C API<33>3137416
Ref: whatsnew/changelog id3933137513
Ref: 12533137513
Ref: C API<33>-Footnote-13137671
Node: 文档<42>3137714
Ref: whatsnew/changelog id3943137821
Ref: 12543137821
Ref: 文档<42>-Footnote-13138145
Ref: 文档<42>-Footnote-23138188
Node: 工具/示例<24>3138237
Ref: whatsnew/changelog id3953138326
Ref: 12553138326
Ref: 工具/示例<24>-Footnote-13138492
Node: Python 3 6 0 beta 43138535
Ref: whatsnew/changelog python-3-6-0-beta-43138671
Ref: 12563138671
Node: 核心与内置函数<48>3138900
Ref: whatsnew/changelog id3963138997
Ref: 12573138997
Ref: 核心与内置函数<48>-Footnote-13140550
Ref: 核心与内置函数<48>-Footnote-23140593
Ref: 核心与内置函数<48>-Footnote-33140636
Ref: 核心与内置函数<48>-Footnote-43140679
Ref: 核心与内置函数<48>-Footnote-53140722
Ref: 核心与内置函数<48>-Footnote-63140765
Ref: 核心与内置函数<48>-Footnote-73140808
Ref: 核心与内置函数<48>-Footnote-83140851
Ref: 核心与内置函数<48>-Footnote-93140894
Ref: 核心与内置函数<48>-Footnote-103140937
Ref: 核心与内置函数<48>-Footnote-113140981
Node: 库<51>3141025
Ref: whatsnew/changelog id3973141141
Ref: 12583141141
Ref: 库<51>-Footnote-13143134
Ref: 库<51>-Footnote-23143177
Ref: 库<51>-Footnote-33143220
Ref: 库<51>-Footnote-43143263
Ref: 库<51>-Footnote-53143306
Ref: 库<51>-Footnote-63143349
Ref: 库<51>-Footnote-73143392
Ref: 库<51>-Footnote-83143435
Ref: 库<51>-Footnote-93143478
Ref: 库<51>-Footnote-103143521
Ref: 库<51>-Footnote-113143565
Ref: 库<51>-Footnote-123143609
Ref: 库<51>-Footnote-133143653
Ref: 库<51>-Footnote-143143697
Ref: 库<51>-Footnote-153143741
Ref: 库<51>-Footnote-163143785
Ref: 库<51>-Footnote-173143829
Ref: 库<51>-Footnote-183143873
Node: 文档<43>3143917
Ref: whatsnew/changelog id3983144018
Ref: 12593144018
Ref: 文档<43>-Footnote-13144153
Node: 测试<40>3144196
Ref: whatsnew/changelog id3993144300
Ref: 125a3144300
Ref: 测试<40>-Footnote-13144562
Ref: 测试<40>-Footnote-23144605
Node: 构建<43>3144648
Ref: whatsnew/changelog id4003144733
Ref: 125b3144733
Ref: 构建<43>-Footnote-13145096
Ref: 构建<43>-Footnote-23145139
Ref: 构建<43>-Footnote-33145182
Node: Python 3 6 0 beta 33145225
Ref: whatsnew/changelog python-3-6-0-beta-33145364
Ref: 125c3145364
Node: 核心与内置函数<49>3145595
Ref: whatsnew/changelog id4013145692
Ref: 125d3145692
Ref: 核心与内置函数<49>-Footnote-13146596
Ref: 核心与内置函数<49>-Footnote-23146639
Ref: 核心与内置函数<49>-Footnote-33146682
Ref: 核心与内置函数<49>-Footnote-43146725
Ref: 核心与内置函数<49>-Footnote-53146768
Ref: 核心与内置函数<49>-Footnote-63146811
Ref: 核心与内置函数<49>-Footnote-73146854
Node: 库<52>3146897
Ref: whatsnew/changelog id4023147014
Ref: 125e3147014
Ref: 库<52>-Footnote-13150037
Ref: 库<52>-Footnote-23150080
Ref: 库<52>-Footnote-33150123
Ref: 库<52>-Footnote-43150166
Ref: 库<52>-Footnote-53150209
Ref: 库<52>-Footnote-63150252
Ref: 库<52>-Footnote-73150295
Ref: 库<52>-Footnote-83150338
Ref: 库<52>-Footnote-93150381
Ref: 库<52>-Footnote-103150424
Ref: 库<52>-Footnote-113150468
Ref: 库<52>-Footnote-123150512
Ref: 库<52>-Footnote-133150556
Ref: 库<52>-Footnote-143150600
Ref: 库<52>-Footnote-153150644
Ref: 库<52>-Footnote-163150688
Ref: 库<52>-Footnote-173150732
Ref: 库<52>-Footnote-183150776
Ref: 库<52>-Footnote-193150820
Ref: 库<52>-Footnote-203150864
Ref: 库<52>-Footnote-213150908
Ref: 库<52>-Footnote-223150952
Ref: 库<52>-Footnote-233150996
Ref: 库<52>-Footnote-243151040
Node: Windows<40>3151084
Ref: whatsnew/changelog id4033151186
Ref: 125f3151186
Ref: Windows<40>-Footnote-13151330
Node: 构建<44>3151373
Ref: whatsnew/changelog id4043151478
Ref: 12603151478
Ref: 构建<44>-Footnote-13151788
Ref: 构建<44>-Footnote-23151831
Ref: 构建<44>-Footnote-33151874
Node: 测试<41>3151917
Ref: whatsnew/changelog id4053152002
Ref: 12613152002
Ref: 测试<41>-Footnote-13152261
Ref: 测试<41>-Footnote-23152304
Node: Python 3 6 0 beta 23152347
Ref: whatsnew/changelog python-3-6-0-beta-23152486
Ref: 12623152486
Node: 核心与内置函数<50>3152737
Ref: whatsnew/changelog id4063152834
Ref: 12633152834
Ref: 核心与内置函数<50>-Footnote-13155575
Ref: 核心与内置函数<50>-Footnote-23155618
Ref: 核心与内置函数<50>-Footnote-33155661
Ref: 核心与内置函数<50>-Footnote-43155704
Ref: 核心与内置函数<50>-Footnote-53155747
Ref: 核心与内置函数<50>-Footnote-63155790
Ref: 核心与内置函数<50>-Footnote-73155833
Ref: 核心与内置函数<50>-Footnote-83155876
Ref: 核心与内置函数<50>-Footnote-93155919
Ref: 核心与内置函数<50>-Footnote-103155962
Ref: 核心与内置函数<50>-Footnote-113156006
Ref: 核心与内置函数<50>-Footnote-123156050
Ref: 核心与内置函数<50>-Footnote-133156094
Ref: 核心与内置函数<50>-Footnote-143156138
Ref: 核心与内置函数<50>-Footnote-153156182
Ref: 核心与内置函数<50>-Footnote-163156226
Ref: 核心与内置函数<50>-Footnote-173156270
Ref: 核心与内置函数<50>-Footnote-183156314
Ref: 核心与内置函数<50>-Footnote-193156358
Ref: 核心与内置函数<50>-Footnote-203156402
Ref: 核心与内置函数<50>-Footnote-213156446
Ref: 核心与内置函数<50>-Footnote-223156490
Ref: 核心与内置函数<50>-Footnote-233156534
Node: 库<53>3156578
Ref: whatsnew/changelog id4073156695
Ref: 12643156695
Ref: 库<53>-Footnote-13162472
Ref: 库<53>-Footnote-23162515
Ref: 库<53>-Footnote-33162558
Ref: 库<53>-Footnote-43162601
Ref: 库<53>-Footnote-53162644
Ref: 库<53>-Footnote-63162687
Ref: 库<53>-Footnote-73162730
Ref: 库<53>-Footnote-83162773
Ref: 库<53>-Footnote-93162816
Ref: 库<53>-Footnote-103162859
Ref: 库<53>-Footnote-113162903
Ref: 库<53>-Footnote-123162947
Ref: 库<53>-Footnote-133162991
Ref: 库<53>-Footnote-143163035
Ref: 库<53>-Footnote-153163079
Ref: 库<53>-Footnote-163163123
Ref: 库<53>-Footnote-173163167
Ref: 库<53>-Footnote-183163211
Ref: 库<53>-Footnote-193163255
Ref: 库<53>-Footnote-203163299
Ref: 库<53>-Footnote-213163343
Ref: 库<53>-Footnote-223163387
Ref: 库<53>-Footnote-233163431
Ref: 库<53>-Footnote-243163475
Ref: 库<53>-Footnote-253163519
Ref: 库<53>-Footnote-263163563
Ref: 库<53>-Footnote-273163607
Ref: 库<53>-Footnote-283163651
Ref: 库<53>-Footnote-293163695
Ref: 库<53>-Footnote-303163739
Ref: 库<53>-Footnote-313163783
Ref: 库<53>-Footnote-323163827
Ref: 库<53>-Footnote-333163871
Ref: 库<53>-Footnote-343163915
Ref: 库<53>-Footnote-353163959
Ref: 库<53>-Footnote-363164003
Ref: 库<53>-Footnote-373164047
Ref: 库<53>-Footnote-383164091
Ref: 库<53>-Footnote-393164135
Ref: 库<53>-Footnote-403164179
Ref: 库<53>-Footnote-413164223
Ref: 库<53>-Footnote-423164267
Ref: 库<53>-Footnote-433164311
Ref: 库<53>-Footnote-443164355
Ref: 库<53>-Footnote-453164399
Ref: 库<53>-Footnote-463164443
Ref: 库<53>-Footnote-473164487
Ref: 库<53>-Footnote-483164531
Node: Windows<41>3164575
Ref: whatsnew/changelog id4083164676
Ref: 12653164676
Ref: Windows<41>-Footnote-13165487
Ref: Windows<41>-Footnote-23165530
Ref: Windows<41>-Footnote-33165573
Ref: Windows<41>-Footnote-43165616
Ref: Windows<41>-Footnote-53165659
Ref: Windows<41>-Footnote-63165702
Ref: Windows<41>-Footnote-73165745
Ref: Windows<41>-Footnote-83165788
Ref: Windows<41>-Footnote-93165831
Ref: Windows<41>-Footnote-103165874
Node: C API<34>3165918
Ref: whatsnew/changelog id4093166022
Ref: 12663166022
Ref: C API<34>-Footnote-13166276
Node: 构建<45>3166319
Ref: whatsnew/changelog id4103166422
Ref: 12673166422
Ref: 构建<45>-Footnote-13166848
Ref: 构建<45>-Footnote-23166891
Ref: 构建<45>-Footnote-33166934
Node: 测试<42>3166977
Ref: whatsnew/changelog id4113167062
Ref: 12683167062
Ref: 测试<42>-Footnote-13167199
Node: Python 3 6 0 beta 13167242
Ref: whatsnew/changelog python-3-6-0-beta-13167382
Ref: 12693167382
Node: 核心与内置函数<51>3167689
Ref: whatsnew/changelog id4123167786
Ref: 126a3167786
Ref: 核心与内置函数<51>-Footnote-13173976
Ref: 核心与内置函数<51>-Footnote-23174019
Ref: 核心与内置函数<51>-Footnote-33174062
Ref: 核心与内置函数<51>-Footnote-43174105
Ref: 核心与内置函数<51>-Footnote-53174154
Ref: 核心与内置函数<51>-Footnote-63174197
Ref: 核心与内置函数<51>-Footnote-73174240
Ref: 核心与内置函数<51>-Footnote-83174283
Ref: 核心与内置函数<51>-Footnote-93174326
Ref: 核心与内置函数<51>-Footnote-103174369
Ref: 核心与内置函数<51>-Footnote-113174413
Ref: 核心与内置函数<51>-Footnote-123174457
Ref: 核心与内置函数<51>-Footnote-133174501
Ref: 核心与内置函数<51>-Footnote-143174551
Ref: 核心与内置函数<51>-Footnote-153174595
Ref: 核心与内置函数<51>-Footnote-163174639
Ref: 核心与内置函数<51>-Footnote-173174689
Ref: 核心与内置函数<51>-Footnote-183174733
Ref: 核心与内置函数<51>-Footnote-193174783
Ref: 核心与内置函数<51>-Footnote-203174827
Ref: 核心与内置函数<51>-Footnote-213174871
Ref: 核心与内置函数<51>-Footnote-223174915
Ref: 核心与内置函数<51>-Footnote-233174959
Ref: 核心与内置函数<51>-Footnote-243175003
Ref: 核心与内置函数<51>-Footnote-253175047
Ref: 核心与内置函数<51>-Footnote-263175091
Ref: 核心与内置函数<51>-Footnote-273175135
Ref: 核心与内置函数<51>-Footnote-283175185
Ref: 核心与内置函数<51>-Footnote-293175229
Ref: 核心与内置函数<51>-Footnote-303175273
Ref: 核心与内置函数<51>-Footnote-313175317
Ref: 核心与内置函数<51>-Footnote-323175361
Ref: 核心与内置函数<51>-Footnote-333175405
Ref: 核心与内置函数<51>-Footnote-343175449
Ref: 核心与内置函数<51>-Footnote-353175493
Ref: 核心与内置函数<51>-Footnote-363175537
Ref: 核心与内置函数<51>-Footnote-373175581
Ref: 核心与内置函数<51>-Footnote-383175625
Ref: 核心与内置函数<51>-Footnote-393175669
Ref: 核心与内置函数<51>-Footnote-403175713
Ref: 核心与内置函数<51>-Footnote-413175757
Ref: 核心与内置函数<51>-Footnote-423175801
Ref: 核心与内置函数<51>-Footnote-433175845
Ref: 核心与内置函数<51>-Footnote-443175889
Ref: 核心与内置函数<51>-Footnote-453175933
Ref: 核心与内置函数<51>-Footnote-463175977
Ref: 核心与内置函数<51>-Footnote-473176027
Node: 库<54>3176071
Ref: whatsnew/changelog id4133176185
Ref: 126b3176185
Ref: 库<54>-Footnote-13187155
Ref: 库<54>-Footnote-23187198
Ref: 库<54>-Footnote-33187241
Ref: 库<54>-Footnote-43187284
Ref: 库<54>-Footnote-53187327
Ref: 库<54>-Footnote-63187370
Ref: 库<54>-Footnote-73187413
Ref: 库<54>-Footnote-83187456
Ref: 库<54>-Footnote-93187499
Ref: 库<54>-Footnote-103187542
Ref: 库<54>-Footnote-113187586
Ref: 库<54>-Footnote-123187630
Ref: 库<54>-Footnote-133187674
Ref: 库<54>-Footnote-143187718
Ref: 库<54>-Footnote-153187762
Ref: 库<54>-Footnote-163187806
Ref: 库<54>-Footnote-173187850
Ref: 库<54>-Footnote-183187896
Ref: 库<54>-Footnote-193187940
Ref: 库<54>-Footnote-203187984
Ref: 库<54>-Footnote-213188028
Ref: 库<54>-Footnote-223188072
Ref: 库<54>-Footnote-233188116
Ref: 库<54>-Footnote-243188160
Ref: 库<54>-Footnote-253188204
Ref: 库<54>-Footnote-263188249
Ref: 库<54>-Footnote-273188293
Ref: 库<54>-Footnote-283188337
Ref: 库<54>-Footnote-293188381
Ref: 库<54>-Footnote-303188425
Ref: 库<54>-Footnote-313188469
Ref: 库<54>-Footnote-323188513
Ref: 库<54>-Footnote-333188557
Ref: 库<54>-Footnote-343188601
Ref: 库<54>-Footnote-353188645
Ref: 库<54>-Footnote-363188689
Ref: 库<54>-Footnote-373188733
Ref: 库<54>-Footnote-383188777
Ref: 库<54>-Footnote-393188821
Ref: 库<54>-Footnote-403188865
Ref: 库<54>-Footnote-413188909
Ref: 库<54>-Footnote-423188953
Ref: 库<54>-Footnote-433189003
Ref: 库<54>-Footnote-443189047
Ref: 库<54>-Footnote-453189097
Ref: 库<54>-Footnote-463189141
Ref: 库<54>-Footnote-473189185
Ref: 库<54>-Footnote-483189229
Ref: 库<54>-Footnote-493189273
Ref: 库<54>-Footnote-503189317
Ref: 库<54>-Footnote-513189361
Ref: 库<54>-Footnote-523189405
Ref: 库<54>-Footnote-533189449
Ref: 库<54>-Footnote-543189493
Ref: 库<54>-Footnote-553189537
Ref: 库<54>-Footnote-563189581
Ref: 库<54>-Footnote-573189625
Ref: 库<54>-Footnote-583189669
Ref: 库<54>-Footnote-593189713
Ref: 库<54>-Footnote-603189757
Ref: 库<54>-Footnote-613189801
Ref: 库<54>-Footnote-623189845
Ref: 库<54>-Footnote-633189889
Ref: 库<54>-Footnote-643189933
Ref: 库<54>-Footnote-653189977
Ref: 库<54>-Footnote-663190021
Ref: 库<54>-Footnote-673190065
Ref: 库<54>-Footnote-683190109
Ref: 库<54>-Footnote-693190153
Ref: 库<54>-Footnote-703190197
Ref: 库<54>-Footnote-713190241
Ref: 库<54>-Footnote-723190285
Ref: 库<54>-Footnote-733190329
Ref: 库<54>-Footnote-743190373
Ref: 库<54>-Footnote-753190417
Ref: 库<54>-Footnote-763190460
Ref: 库<54>-Footnote-773190503
Ref: 库<54>-Footnote-783190547
Ref: 库<54>-Footnote-793190591
Ref: 库<54>-Footnote-803190634
Ref: 库<54>-Footnote-813190678
Node: IDLE<39>3190722
Ref: whatsnew/changelog id4143190820
Ref: 126c3190820
Ref: IDLE<39>-Footnote-13191593
Ref: IDLE<39>-Footnote-23191636
Ref: IDLE<39>-Footnote-33191679
Ref: IDLE<39>-Footnote-43191722
Ref: IDLE<39>-Footnote-53191765
Ref: IDLE<39>-Footnote-63191808
Node: C API<35>3191851
Ref: whatsnew/changelog id4153191952
Ref: 126d3191952
Ref: C API<35>-Footnote-13192224
Ref: C API<35>-Footnote-23192267
Node: 测试<43>3192310
Ref: whatsnew/changelog id4163192413
Ref: 126e3192413
Ref: 测试<43>-Footnote-13192929
Ref: 测试<43>-Footnote-23192972
Ref: 测试<43>-Footnote-33193015
Ref: 测试<43>-Footnote-43193058
Node: 构建<46>3193101
Ref: whatsnew/changelog id4173193212
Ref: 126f3193212
Ref: 构建<46>-Footnote-13194606
Ref: 构建<46>-Footnote-23194649
Ref: 构建<46>-Footnote-33194692
Ref: 构建<46>-Footnote-43194735
Ref: 构建<46>-Footnote-53194778
Ref: 构建<46>-Footnote-63194821
Ref: 构建<46>-Footnote-73194864
Ref: 构建<46>-Footnote-83194907
Ref: 构建<46>-Footnote-93194950
Ref: 构建<46>-Footnote-103194993
Ref: 构建<46>-Footnote-113195037
Node: 工具/示例<25>3195081
Ref: whatsnew/changelog id4183195193
Ref: 12703195193
Ref: 工具/示例<25>-Footnote-13195468
Node: Windows<42>3195511
Ref: whatsnew/changelog id4193195604
Ref: 12713195604
Ref: Windows<42>-Footnote-13196575
Ref: Windows<42>-Footnote-23196618
Ref: Windows<42>-Footnote-33196661
Ref: Windows<42>-Footnote-43196703
Ref: Windows<42>-Footnote-53196746
Ref: Windows<42>-Footnote-63196789
Ref: Windows<42>-Footnote-73196831
Ref: Windows<42>-Footnote-83196874
Ref: Windows<42>-Footnote-93196917
Ref: Windows<42>-Footnote-103196960
Ref: Windows<42>-Footnote-113197004
Node: Python 3 6 0 alpha 43197048
Ref: whatsnew/changelog python-3-6-0-alpha-43197189
Ref: 12723197189
Node: 核心与内置函数<52>3197440
Ref: whatsnew/changelog id4203197538
Ref: 12733197538
Ref: 核心与内置函数<52>-Footnote-13199485
Ref: 核心与内置函数<52>-Footnote-23199528
Ref: 核心与内置函数<52>-Footnote-33199571
Ref: 核心与内置函数<52>-Footnote-43199614
Ref: 核心与内置函数<52>-Footnote-53199657
Ref: 核心与内置函数<52>-Footnote-63199700
Ref: 核心与内置函数<52>-Footnote-73199743
Ref: 核心与内置函数<52>-Footnote-83199786
Ref: 核心与内置函数<52>-Footnote-93199829
Ref: 核心与内置函数<52>-Footnote-103199871
Ref: 核心与内置函数<52>-Footnote-113199915
Ref: 核心与内置函数<52>-Footnote-123199959
Ref: 核心与内置函数<52>-Footnote-133200003
Ref: 核心与内置函数<52>-Footnote-143200047
Node: 库<55>3200097
Ref: whatsnew/changelog id4213200212
Ref: 12743200212
Ref: 库<55>-Footnote-13204692
Ref: 库<55>-Footnote-23204735
Ref: 库<55>-Footnote-33204784
Ref: 库<55>-Footnote-43204827
Ref: 库<55>-Footnote-53204870
Ref: 库<55>-Footnote-63204913
Ref: 库<55>-Footnote-73204956
Ref: 库<55>-Footnote-83204999
Ref: 库<55>-Footnote-93205042
Ref: 库<55>-Footnote-103205085
Ref: 库<55>-Footnote-113205129
Ref: 库<55>-Footnote-123205179
Ref: 库<55>-Footnote-133205223
Ref: 库<55>-Footnote-143205267
Ref: 库<55>-Footnote-153205311
Ref: 库<55>-Footnote-163205355
Ref: 库<55>-Footnote-173205398
Ref: 库<55>-Footnote-183205442
Ref: 库<55>-Footnote-193205486
Ref: 库<55>-Footnote-203205530
Ref: 库<55>-Footnote-213205574
Ref: 库<55>-Footnote-223205618
Ref: 库<55>-Footnote-233205662
Ref: 库<55>-Footnote-243205706
Ref: 库<55>-Footnote-253205750
Ref: 库<55>-Footnote-263205794
Ref: 库<55>-Footnote-273205838
Ref: 库<55>-Footnote-283205882
Ref: 库<55>-Footnote-293205925
Ref: 库<55>-Footnote-303205969
Ref: 库<55>-Footnote-313206013
Ref: 库<55>-Footnote-323206057
Ref: 库<55>-Footnote-333206107
Ref: 库<55>-Footnote-343206151
Ref: 库<55>-Footnote-353206194
Ref: 库<55>-Footnote-363206238
Ref: 库<55>-Footnote-373206282
Ref: 库<55>-Footnote-383206326
Node: IDLE<40>3206370
Ref: whatsnew/changelog id4223206470
Ref: 12753206470
Ref: IDLE<40>-Footnote-13207794
Ref: IDLE<40>-Footnote-23207837
Ref: IDLE<40>-Footnote-33207880
Ref: IDLE<40>-Footnote-43207923
Ref: IDLE<40>-Footnote-53207966
Ref: IDLE<40>-Footnote-63208009
Ref: IDLE<40>-Footnote-73208052
Ref: IDLE<40>-Footnote-83208095
Node: 测试<44>3208138
Ref: whatsnew/changelog id4233208242
Ref: 12763208242
Ref: 测试<44>-Footnote-13208831
Ref: 测试<44>-Footnote-23208874
Ref: 测试<44>-Footnote-33208917
Ref: 测试<44>-Footnote-43208960
Node: Windows<43>3209003
Ref: whatsnew/changelog id4243209109
Ref: 12773209109
Ref: Windows<43>-Footnote-13209485
Ref: Windows<43>-Footnote-23209528
Ref: Windows<43>-Footnote-33209571
Ref: Windows<43>-Footnote-43209620
Ref: Windows<43>-Footnote-53209663
Node: 构建<47>3209706
Ref: whatsnew/changelog id4253209793
Ref: 12783209793
Ref: 构建<47>-Footnote-13210694
Ref: 构建<47>-Footnote-23210737
Ref: 构建<47>-Footnote-33210780
Ref: 构建<47>-Footnote-43210823
Ref: 构建<47>-Footnote-53210866
Ref: 构建<47>-Footnote-63210909
Node: Python 3 6 0 alpha 33210952
Ref: whatsnew/changelog python-3-6-0-alpha-33211094
Ref: 12793211094
Node: 核心与内置函数<53>3211487
Ref: whatsnew/changelog id4263211585
Ref: 127a3211585
Ref: 核心与内置函数<53>-Footnote-13212333
Ref: 核心与内置函数<53>-Footnote-23212376
Ref: 核心与内置函数<53>-Footnote-33212419
Ref: 核心与内置函数<53>-Footnote-43212462
Node: 库<56>3212505
Ref: whatsnew/changelog id4273212625
Ref: 127b3212625
Ref: 库<56>-Footnote-13216126
Ref: 库<56>-Footnote-23216169
Ref: 库<56>-Footnote-33216212
Ref: 库<56>-Footnote-43216255
Ref: 库<56>-Footnote-53216298
Ref: 库<56>-Footnote-63216341
Ref: 库<56>-Footnote-73216384
Ref: 库<56>-Footnote-83216427
Ref: 库<56>-Footnote-93216470
Ref: 库<56>-Footnote-103216513
Ref: 库<56>-Footnote-113216557
Ref: 库<56>-Footnote-123216601
Ref: 库<56>-Footnote-133216645
Ref: 库<56>-Footnote-143216689
Ref: 库<56>-Footnote-153216733
Ref: 库<56>-Footnote-163216777
Ref: 库<56>-Footnote-173216821
Ref: 库<56>-Footnote-183216865
Ref: 库<56>-Footnote-193216909
Ref: 库<56>-Footnote-203216953
Ref: 库<56>-Footnote-213216997
Node: 安全性<26>3217047
Ref: whatsnew/changelog id4283217149
Ref: 127c3217149
Ref: 安全性<26>-Footnote-13217437
Node: 库<57>3217480
Ref: whatsnew/changelog id4293217588
Ref: 127d3217588
Ref: 库<57>-Footnote-13217986
Ref: 库<57>-Footnote-23218029
Ref: 库<57>-Footnote-33218072
Node: 安全性<27>3218114
Ref: whatsnew/changelog id4303218216
Ref: 127e3218216
Ref: 安全性<27>-Footnote-13218379
Node: 库<58>3218422
Ref: whatsnew/changelog id4313218525
Ref: 127f3218525
Ref: 库<58>-Footnote-13218845
Ref: 库<58>-Footnote-23218888
Node: IDLE<41>3218931
Ref: whatsnew/changelog id4323219030
Ref: 12803219030
Ref: IDLE<41>-Footnote-13220692
Ref: IDLE<41>-Footnote-23220735
Ref: IDLE<41>-Footnote-33220778
Ref: IDLE<41>-Footnote-43220821
Ref: IDLE<41>-Footnote-53220864
Ref: IDLE<41>-Footnote-63220907
Ref: IDLE<41>-Footnote-73220950
Ref: IDLE<41>-Footnote-83220993
Ref: IDLE<41>-Footnote-93221036
Ref: IDLE<41>-Footnote-103221079
Node: C API<36>3221123
Ref: whatsnew/changelog id4333221225
Ref: 12813221225
Ref: C API<36>-Footnote-13221465
Node: 构建<48>3221508
Ref: whatsnew/changelog id4343221619
Ref: 12823221619
Ref: 构建<48>-Footnote-13222610
Ref: 构建<48>-Footnote-23222653
Ref: 构建<48>-Footnote-33222696
Ref: 构建<48>-Footnote-43222739
Ref: 构建<48>-Footnote-53222782
Node: 工具/示例<26>3222825
Ref: whatsnew/changelog id4353222937
Ref: 12833222937
Ref: 工具/示例<26>-Footnote-13223223
Ref: 工具/示例<26>-Footnote-23223266
Node: 文档<44>3223309
Ref: whatsnew/changelog id4363223421
Ref: 12843223421
Ref: 文档<44>-Footnote-13223784
Ref: 文档<44>-Footnote-23223827
Node: 测试<45>3223870
Ref: whatsnew/changelog id4373223956
Ref: 12853223956
Ref: 测试<45>-Footnote-13224126
Node: Python 3 6 0 alpha 23224169
Ref: whatsnew/changelog python-3-6-0-alpha-23224311
Ref: 12863224311
Node: 核心与内置函数<54>3224752
Ref: whatsnew/changelog id4383224850
Ref: 12873224850
Ref: 核心与内置函数<54>-Footnote-13226483
Ref: 核心与内置函数<54>-Footnote-23226526
Ref: 核心与内置函数<54>-Footnote-33226569
Ref: 核心与内置函数<54>-Footnote-43226612
Ref: 核心与内置函数<54>-Footnote-53226655
Ref: 核心与内置函数<54>-Footnote-63226698
Ref: 核心与内置函数<54>-Footnote-73226747
Ref: 核心与内置函数<54>-Footnote-83226790
Ref: 核心与内置函数<54>-Footnote-93226833
Ref: 核心与内置函数<54>-Footnote-103226876
Ref: 核心与内置函数<54>-Footnote-113226920
Ref: 核心与内置函数<54>-Footnote-123226964
Node: 库<59>3227008
Ref: whatsnew/changelog id4393227128
Ref: 12883227128
Ref: 库<59>-Footnote-13227761
Ref: 库<59>-Footnote-23227804
Ref: 库<59>-Footnote-33227847
Ref: 库<59>-Footnote-43227890
Node: 安全性<28>3227933
Ref: whatsnew/changelog id4403228035
Ref: 12893228035
Ref: 安全性<28>-Footnote-13228270
Node: 库<60>3228313
Ref: whatsnew/changelog id4413228421
Ref: 128a3228421
Ref: 库<60>-Footnote-13230355
Ref: 库<60>-Footnote-23230398
Ref: 库<60>-Footnote-33230441
Ref: 库<60>-Footnote-43230484
Ref: 库<60>-Footnote-53230527
Ref: 库<60>-Footnote-63230576
Ref: 库<60>-Footnote-73230619
Ref: 库<60>-Footnote-83230662
Ref: 库<60>-Footnote-93230705
Ref: 库<60>-Footnote-103230754
Ref: 库<60>-Footnote-113230798
Ref: 库<60>-Footnote-123230848
Ref: 库<60>-Footnote-133230898
Ref: 库<60>-Footnote-143230942
Node: 安全性<29>3230986
Ref: whatsnew/changelog id4423231088
Ref: 128b3231088
Ref: 安全性<29>-Footnote-13231411
Node: 库<61>3231454
Ref: whatsnew/changelog id4433231557
Ref: 128c3231557
Ref: 库<61>-Footnote-13234303
Ref: 库<61>-Footnote-23234346
Ref: 库<61>-Footnote-33234389
Ref: 库<61>-Footnote-43234432
Ref: 库<61>-Footnote-53234475
Ref: 库<61>-Footnote-63234518
Ref: 库<61>-Footnote-73234561
Ref: 库<61>-Footnote-83234604
Ref: 库<61>-Footnote-93234647
Ref: 库<61>-Footnote-103234690
Ref: 库<61>-Footnote-113234734
Ref: 库<61>-Footnote-123234778
Ref: 库<61>-Footnote-133234822
Ref: 库<61>-Footnote-143234866
Ref: 库<61>-Footnote-153234910
Ref: 库<61>-Footnote-163234954
Ref: 库<61>-Footnote-173234998
Node: IDLE<42>3235042
Ref: whatsnew/changelog id4443235142
Ref: 128d3235142
Ref: IDLE<42>-Footnote-13237795
Ref: IDLE<42>-Footnote-23237837
Ref: IDLE<42>-Footnote-33237880
Ref: IDLE<42>-Footnote-43237923
Ref: IDLE<42>-Footnote-53237966
Ref: IDLE<42>-Footnote-63238009
Ref: IDLE<42>-Footnote-73238052
Ref: IDLE<42>-Footnote-83238095
Ref: IDLE<42>-Footnote-93238138
Ref: IDLE<42>-Footnote-103238181
Ref: IDLE<42>-Footnote-113238225
Ref: IDLE<42>-Footnote-123238269
Ref: IDLE<42>-Footnote-133238313
Ref: IDLE<42>-Footnote-143238357
Ref: IDLE<42>-Footnote-153238401
Ref: IDLE<42>-Footnote-163238445
Ref: IDLE<42>-Footnote-173238489
Ref: IDLE<42>-Footnote-183238533
Ref: IDLE<42>-Footnote-193238577
Node: 文档<45>3238621
Ref: whatsnew/changelog id4453238724
Ref: 128e3238724
Ref: 文档<45>-Footnote-13239151
Ref: 文档<45>-Footnote-23239194
Ref: 文档<45>-Footnote-33239237
Ref: 文档<45>-Footnote-43239286
Node: 测试<46>3239329
Ref: whatsnew/changelog id4463239435
Ref: 128f3239435
Ref: 测试<46>-Footnote-13239815
Ref: 测试<46>-Footnote-23239858
Node: Windows<44>3239901
Ref: whatsnew/changelog id4473240007
Ref: 12903240007
Ref: Windows<44>-Footnote-13240291
Node: 构建<49>3240334
Ref: whatsnew/changelog id4483240441
Ref: 12913240441
Ref: 构建<49>-Footnote-13240719
Ref: 构建<49>-Footnote-23240762
Node: Windows<45>3240805
Ref: whatsnew/changelog id4493240910
Ref: 12923240910
Ref: Windows<45>-Footnote-13241113
Node: C API<37>3241156
Ref: whatsnew/changelog id4503241268
Ref: 12933241268
Ref: C API<37>-Footnote-13241508
Ref: C API<37>-Footnote-23241551
Ref: C API<37>-Footnote-33241600
Node: 工具/示例<27>3241643
Ref: whatsnew/changelog id4513241735
Ref: 12943241735
Ref: 工具/示例<27>-Footnote-13241933
Node: Python 3 6 0 alpha 13241976
Ref: whatsnew/changelog python-3-6-0-alpha-13242120
Ref: 12953242120
Node: 核心与内置函数<55>3242581
Ref: whatsnew/changelog id4523242679
Ref: 12963242679
Ref: 核心与内置函数<55>-Footnote-13255853
Ref: 核心与内置函数<55>-Footnote-23255896
Ref: 核心与内置函数<55>-Footnote-33255939
Ref: 核心与内置函数<55>-Footnote-43255982
Ref: 核心与内置函数<55>-Footnote-53256025
Ref: 核心与内置函数<55>-Footnote-63256068
Ref: 核心与内置函数<55>-Footnote-73256111
Ref: 核心与内置函数<55>-Footnote-83256154
Ref: 核心与内置函数<55>-Footnote-93256197
Ref: 核心与内置函数<55>-Footnote-103256240
Ref: 核心与内置函数<55>-Footnote-113256284
Ref: 核心与内置函数<55>-Footnote-123256328
Ref: 核心与内置函数<55>-Footnote-133256372
Ref: 核心与内置函数<55>-Footnote-143256416
Ref: 核心与内置函数<55>-Footnote-153256460
Ref: 核心与内置函数<55>-Footnote-163256504
Ref: 核心与内置函数<55>-Footnote-173256554
Ref: 核心与内置函数<55>-Footnote-183256598
Ref: 核心与内置函数<55>-Footnote-193256642
Ref: 核心与内置函数<55>-Footnote-203256686
Ref: 核心与内置函数<55>-Footnote-213256730
Ref: 核心与内置函数<55>-Footnote-223256774
Ref: 核心与内置函数<55>-Footnote-233256818
Ref: 核心与内置函数<55>-Footnote-243256868
Ref: 核心与内置函数<55>-Footnote-253256912
Ref: 核心与内置函数<55>-Footnote-263256956
Ref: 核心与内置函数<55>-Footnote-273257000
Ref: 核心与内置函数<55>-Footnote-283257044
Ref: 核心与内置函数<55>-Footnote-293257088
Ref: 核心与内置函数<55>-Footnote-303257132
Ref: 核心与内置函数<55>-Footnote-313257176
Ref: 核心与内置函数<55>-Footnote-323257220
Ref: 核心与内置函数<55>-Footnote-333257264
Ref: 核心与内置函数<55>-Footnote-343257308
Ref: 核心与内置函数<55>-Footnote-353257352
Ref: 核心与内置函数<55>-Footnote-363257396
Ref: 核心与内置函数<55>-Footnote-373257439
Ref: 核心与内置函数<55>-Footnote-383257483
Ref: 核心与内置函数<55>-Footnote-393257527
Ref: 核心与内置函数<55>-Footnote-403257571
Ref: 核心与内置函数<55>-Footnote-413257615
Ref: 核心与内置函数<55>-Footnote-423257659
Ref: 核心与内置函数<55>-Footnote-433257703
Ref: 核心与内置函数<55>-Footnote-443257747
Ref: 核心与内置函数<55>-Footnote-453257791
Ref: 核心与内置函数<55>-Footnote-463257835
Ref: 核心与内置函数<55>-Footnote-473257879
Ref: 核心与内置函数<55>-Footnote-483257923
Ref: 核心与内置函数<55>-Footnote-493257967
Ref: 核心与内置函数<55>-Footnote-503258011
Ref: 核心与内置函数<55>-Footnote-513258055
Ref: 核心与内置函数<55>-Footnote-523258099
Ref: 核心与内置函数<55>-Footnote-533258142
Ref: 核心与内置函数<55>-Footnote-543258186
Ref: 核心与内置函数<55>-Footnote-553258230
Ref: 核心与内置函数<55>-Footnote-563258274
Ref: 核心与内置函数<55>-Footnote-573258318
Ref: 核心与内置函数<55>-Footnote-583258362
Ref: 核心与内置函数<55>-Footnote-593258406
Ref: 核心与内置函数<55>-Footnote-603258450
Ref: 核心与内置函数<55>-Footnote-613258494
Ref: 核心与内置函数<55>-Footnote-623258538
Ref: 核心与内置函数<55>-Footnote-633258582
Ref: 核心与内置函数<55>-Footnote-643258626
Ref: 核心与内置函数<55>-Footnote-653258670
Ref: 核心与内置函数<55>-Footnote-663258714
Ref: 核心与内置函数<55>-Footnote-673258758
Ref: 核心与内置函数<55>-Footnote-683258802
Ref: 核心与内置函数<55>-Footnote-693258846
Ref: 核心与内置函数<55>-Footnote-703258890
Ref: 核心与内置函数<55>-Footnote-713258934
Ref: 核心与内置函数<55>-Footnote-723258978
Ref: 核心与内置函数<55>-Footnote-733259022
Ref: 核心与内置函数<55>-Footnote-743259066
Ref: 核心与内置函数<55>-Footnote-753259110
Ref: 核心与内置函数<55>-Footnote-763259154
Ref: 核心与内置函数<55>-Footnote-773259198
Ref: 核心与内置函数<55>-Footnote-783259242
Ref: 核心与内置函数<55>-Footnote-793259285
Ref: 核心与内置函数<55>-Footnote-803259329
Ref: 核心与内置函数<55>-Footnote-813259379
Ref: 核心与内置函数<55>-Footnote-823259423
Ref: 核心与内置函数<55>-Footnote-833259467
Ref: 核心与内置函数<55>-Footnote-843259511
Ref: 核心与内置函数<55>-Footnote-853259555
Ref: 核心与内置函数<55>-Footnote-863259599
Ref: 核心与内置函数<55>-Footnote-873259643
Node: 库<62>3259687
Ref: whatsnew/changelog id4533259807
Ref: 12983259807
Ref: 库<62>-Footnote-13264966
Ref: 库<62>-Footnote-23265009
Ref: 库<62>-Footnote-33265052
Ref: 库<62>-Footnote-43265095
Ref: 库<62>-Footnote-53265138
Ref: 库<62>-Footnote-63265181
Ref: 库<62>-Footnote-73265224
Ref: 库<62>-Footnote-83265267
Ref: 库<62>-Footnote-93265310
Ref: 库<62>-Footnote-103265353
Ref: 库<62>-Footnote-113265397
Ref: 库<62>-Footnote-123265441
Ref: 库<62>-Footnote-133265485
Ref: 库<62>-Footnote-143265529
Ref: 库<62>-Footnote-153265573
Ref: 库<62>-Footnote-163265617
Ref: 库<62>-Footnote-173265661
Ref: 库<62>-Footnote-183265705
Ref: 库<62>-Footnote-193265755
Ref: 库<62>-Footnote-203265799
Ref: 库<62>-Footnote-213265843
Ref: 库<62>-Footnote-223265887
Ref: 库<62>-Footnote-233265931
Ref: 库<62>-Footnote-243265975
Ref: 库<62>-Footnote-253266019
Ref: 库<62>-Footnote-263266063
Ref: 库<62>-Footnote-273266107
Ref: 库<62>-Footnote-283266151
Ref: 库<62>-Footnote-293266195
Ref: 库<62>-Footnote-303266239
Ref: 库<62>-Footnote-313266283
Ref: 库<62>-Footnote-323266327
Ref: 库<62>-Footnote-333266371
Ref: 库<62>-Footnote-343266415
Ref: 库<62>-Footnote-353266459
Ref: 库<62>-Footnote-363266503
Node: 安全性<30>3266547
Ref: whatsnew/changelog id4543266649
Ref: 12993266649
Ref: 安全性<30>-Footnote-13266936
Node: 库<63>3266979
Ref: whatsnew/changelog id4553267087
Ref: 129a3267087
Ref: 库<63>-Footnote-13271792
Ref: 库<63>-Footnote-23271835
Ref: 库<63>-Footnote-33271878
Ref: 库<63>-Footnote-43271921
Ref: 库<63>-Footnote-53271964
Ref: 库<63>-Footnote-63272007
Ref: 库<63>-Footnote-73272050
Ref: 库<63>-Footnote-83272093
Ref: 库<63>-Footnote-93272136
Ref: 库<63>-Footnote-103272179
Ref: 库<63>-Footnote-113272223
Ref: 库<63>-Footnote-123272267
Ref: 库<63>-Footnote-133272311
Ref: 库<63>-Footnote-143272355
Ref: 库<63>-Footnote-153272399
Ref: 库<63>-Footnote-163272443
Ref: 库<63>-Footnote-173272487
Ref: 库<63>-Footnote-183272531
Ref: 库<63>-Footnote-193272575
Ref: 库<63>-Footnote-203272619
Ref: 库<63>-Footnote-213272663
Ref: 库<63>-Footnote-223272707
Ref: 库<63>-Footnote-233272751
Ref: 库<63>-Footnote-243272795
Ref: 库<63>-Footnote-253272839
Ref: 库<63>-Footnote-263272883
Ref: 库<63>-Footnote-273272927
Ref: 库<63>-Footnote-283272971
Ref: 库<63>-Footnote-293273015
Ref: 库<63>-Footnote-303273059
Ref: 库<63>-Footnote-313273103
Ref: 库<63>-Footnote-323273147
Node: 安全性<31>3273191
Ref: whatsnew/changelog id4563273293
Ref: 129c3273293
Ref: 安全性<31>-Footnote-13273479
Node: 库<64>3273522
Ref: whatsnew/changelog id4573273630
Ref: 129d3273630
Ref: 库<64>-Footnote-13277162
Ref: 库<64>-Footnote-23277205
Ref: 库<64>-Footnote-33277248
Ref: 库<64>-Footnote-43277291
Ref: 库<64>-Footnote-53277334
Ref: 库<64>-Footnote-63277377
Ref: 库<64>-Footnote-73277420
Ref: 库<64>-Footnote-83277463
Ref: 库<64>-Footnote-93277506
Ref: 库<64>-Footnote-103277549
Ref: 库<64>-Footnote-113277593
Ref: 库<64>-Footnote-123277637
Ref: 库<64>-Footnote-133277680
Ref: 库<64>-Footnote-143277724
Ref: 库<64>-Footnote-153277768
Ref: 库<64>-Footnote-163277812
Ref: 库<64>-Footnote-173277856
Ref: 库<64>-Footnote-183277900
Ref: 库<64>-Footnote-193277944
Ref: 库<64>-Footnote-203277988
Ref: 库<64>-Footnote-213278032
Ref: 库<64>-Footnote-223278076
Ref: 库<64>-Footnote-233278120
Ref: 库<64>-Footnote-243278164
Ref: 库<64>-Footnote-253278208
Node: 安全性<32>3278252
Ref: whatsnew/changelog id4583278354
Ref: 12a03278354
Ref: 安全性<32>-Footnote-13278519
Node: 库<65>3278562
Ref: whatsnew/changelog id4593278665
Ref: 12a13278665
Ref: 库<65>-Footnote-13296331
Ref: 库<65>-Footnote-23296374
Ref: 库<65>-Footnote-33296417
Ref: 库<65>-Footnote-43296460
Ref: 库<65>-Footnote-53296503
Ref: 库<65>-Footnote-63296546
Ref: 库<65>-Footnote-73296589
Ref: 库<65>-Footnote-83296632
Ref: 库<65>-Footnote-93296675
Ref: 库<65>-Footnote-103296718
Ref: 库<65>-Footnote-113296762
Ref: 库<65>-Footnote-123296806
Ref: 库<65>-Footnote-133296850
Ref: 库<65>-Footnote-143296894
Ref: 库<65>-Footnote-153296938
Ref: 库<65>-Footnote-163296982
Ref: 库<65>-Footnote-173297026
Ref: 库<65>-Footnote-183297070
Ref: 库<65>-Footnote-193297114
Ref: 库<65>-Footnote-203297158
Ref: 库<65>-Footnote-213297202
Ref: 库<65>-Footnote-223297246
Ref: 库<65>-Footnote-233297290
Ref: 库<65>-Footnote-243297334
Ref: 库<65>-Footnote-253297378
Ref: 库<65>-Footnote-263297422
Ref: 库<65>-Footnote-273297466
Ref: 库<65>-Footnote-283297510
Ref: 库<65>-Footnote-293297554
Ref: 库<65>-Footnote-303297598
Ref: 库<65>-Footnote-313297642
Ref: 库<65>-Footnote-323297686
Ref: 库<65>-Footnote-333297730
Ref: 库<65>-Footnote-343297774
Ref: 库<65>-Footnote-353297818
Ref: 库<65>-Footnote-363297862
Ref: 库<65>-Footnote-373297906
Ref: 库<65>-Footnote-383297950
Ref: 库<65>-Footnote-393297994
Ref: 库<65>-Footnote-403298038
Ref: 库<65>-Footnote-413298082
Ref: 库<65>-Footnote-423298126
Ref: 库<65>-Footnote-433298170
Ref: 库<65>-Footnote-443298214
Ref: 库<65>-Footnote-453298258
Ref: 库<65>-Footnote-463298302
Ref: 库<65>-Footnote-473298346
Ref: 库<65>-Footnote-483298390
Ref: 库<65>-Footnote-493298434
Ref: 库<65>-Footnote-503298478
Ref: 库<65>-Footnote-513298522
Ref: 库<65>-Footnote-523298565
Ref: 库<65>-Footnote-533298609
Ref: 库<65>-Footnote-543298653
Ref: 库<65>-Footnote-553298697
Ref: 库<65>-Footnote-563298741
Ref: 库<65>-Footnote-573298785
Ref: 库<65>-Footnote-583298828
Ref: 库<65>-Footnote-593298872
Ref: 库<65>-Footnote-603298916
Ref: 库<65>-Footnote-613298960
Ref: 库<65>-Footnote-623299004
Ref: 库<65>-Footnote-633299048
Ref: 库<65>-Footnote-643299092
Ref: 库<65>-Footnote-653299136
Ref: 库<65>-Footnote-663299180
Ref: 库<65>-Footnote-673299224
Ref: 库<65>-Footnote-683299267
Ref: 库<65>-Footnote-693299311
Ref: 库<65>-Footnote-703299355
Ref: 库<65>-Footnote-713299399
Ref: 库<65>-Footnote-723299443
Ref: 库<65>-Footnote-733299487
Ref: 库<65>-Footnote-743299531
Ref: 库<65>-Footnote-753299575
Ref: 库<65>-Footnote-763299619
Ref: 库<65>-Footnote-773299663
Ref: 库<65>-Footnote-783299707
Ref: 库<65>-Footnote-793299751
Ref: 库<65>-Footnote-803299795
Ref: 库<65>-Footnote-813299839
Ref: 库<65>-Footnote-823299883
Ref: 库<65>-Footnote-833299927
Ref: 库<65>-Footnote-843299971
Ref: 库<65>-Footnote-853300015
Ref: 库<65>-Footnote-863300059
Ref: 库<65>-Footnote-873300103
Ref: 库<65>-Footnote-883300147
Ref: 库<65>-Footnote-893300191
Ref: 库<65>-Footnote-903300235
Ref: 库<65>-Footnote-913300279
Ref: 库<65>-Footnote-923300323
Ref: 库<65>-Footnote-933300367
Ref: 库<65>-Footnote-943300411
Ref: 库<65>-Footnote-953300455
Ref: 库<65>-Footnote-963300499
Ref: 库<65>-Footnote-973300543
Ref: 库<65>-Footnote-983300587
Ref: 库<65>-Footnote-993300631
Ref: 库<65>-Footnote-1003300675
Ref: 库<65>-Footnote-1013300720
Ref: 库<65>-Footnote-1023300765
Ref: 库<65>-Footnote-1033300810
Ref: 库<65>-Footnote-1043300855
Ref: 库<65>-Footnote-1053300900
Ref: 库<65>-Footnote-1063300945
Ref: 库<65>-Footnote-1073300990
Ref: 库<65>-Footnote-1083301035
Ref: 库<65>-Footnote-1093301080
Ref: 库<65>-Footnote-1103301125
Ref: 库<65>-Footnote-1113301170
Ref: 库<65>-Footnote-1123301215
Ref: 库<65>-Footnote-1133301260
Ref: 库<65>-Footnote-1143301305
Ref: 库<65>-Footnote-1153301350
Ref: 库<65>-Footnote-1163301394
Ref: 库<65>-Footnote-1173301438
Ref: 库<65>-Footnote-1183301483
Ref: 库<65>-Footnote-1193301528
Ref: 库<65>-Footnote-1203301573
Ref: 库<65>-Footnote-1213301618
Ref: 库<65>-Footnote-1223301663
Ref: 库<65>-Footnote-1233301708
Ref: 库<65>-Footnote-1243301753
Ref: 库<65>-Footnote-1253301798
Ref: 库<65>-Footnote-1263301843
Ref: 库<65>-Footnote-1273301888
Ref: 库<65>-Footnote-1283301933
Ref: 库<65>-Footnote-1293301978
Ref: 库<65>-Footnote-1303302023
Ref: 库<65>-Footnote-1313302068
Node: IDLE<43>3302113
Ref: whatsnew/changelog id4603302213
Ref: 12a23302213
Ref: IDLE<43>-Footnote-13307794
Ref: IDLE<43>-Footnote-23307837
Ref: IDLE<43>-Footnote-33307880
Ref: IDLE<43>-Footnote-43307923
Ref: IDLE<43>-Footnote-53307966
Ref: IDLE<43>-Footnote-63308009
Ref: IDLE<43>-Footnote-73308052
Ref: IDLE<43>-Footnote-83308095
Ref: IDLE<43>-Footnote-93308138
Ref: IDLE<43>-Footnote-103308181
Ref: IDLE<43>-Footnote-113308225
Ref: IDLE<43>-Footnote-123308269
Ref: IDLE<43>-Footnote-133308313
Ref: IDLE<43>-Footnote-143308357
Ref: IDLE<43>-Footnote-153308401
Ref: IDLE<43>-Footnote-163308445
Ref: IDLE<43>-Footnote-173308489
Ref: IDLE<43>-Footnote-183308533
Ref: IDLE<43>-Footnote-193308577
Ref: IDLE<43>-Footnote-203308621
Ref: IDLE<43>-Footnote-213308665
Ref: IDLE<43>-Footnote-223308709
Ref: IDLE<43>-Footnote-233308753
Ref: IDLE<43>-Footnote-243308797
Ref: IDLE<43>-Footnote-253308841
Ref: IDLE<43>-Footnote-263308885
Ref: IDLE<43>-Footnote-273308929
Ref: IDLE<43>-Footnote-283308973
Node: 文档<46>3309017
Ref: whatsnew/changelog id4613309120
Ref: 12a33309120
Ref: 文档<46>-Footnote-13309890
Ref: 文档<46>-Footnote-23309933
Ref: 文档<46>-Footnote-33309975
Ref: 文档<46>-Footnote-43310018
Ref: 文档<46>-Footnote-53310061
Node: 测试<47>3310104
Ref: whatsnew/changelog id4623310209
Ref: 12a43310209
Ref: 测试<47>-Footnote-13311960
Ref: 测试<47>-Footnote-23312003
Ref: 测试<47>-Footnote-33312046
Ref: 测试<47>-Footnote-43312089
Ref: 测试<47>-Footnote-53312132
Ref: 测试<47>-Footnote-63312175
Ref: 测试<47>-Footnote-73312218
Ref: 测试<47>-Footnote-83312261
Ref: 测试<47>-Footnote-93312304
Ref: 测试<47>-Footnote-103312347
Ref: 测试<47>-Footnote-113312391
Ref: 测试<47>-Footnote-123312435
Ref: 测试<47>-Footnote-133312479
Node: 构建<50>3312523
Ref: whatsnew/changelog id4633312629
Ref: 12a53312629
Ref: 构建<50>-Footnote-13315342
Ref: 构建<50>-Footnote-23315385
Ref: 构建<50>-Footnote-33315428
Ref: 构建<50>-Footnote-43315471
Ref: 构建<50>-Footnote-53315514
Ref: 构建<50>-Footnote-63315557
Ref: 构建<50>-Footnote-73315600
Ref: 构建<50>-Footnote-83315643
Ref: 构建<50>-Footnote-93315686
Ref: 构建<50>-Footnote-103315729
Ref: 构建<50>-Footnote-113315773
Ref: 构建<50>-Footnote-123315817
Ref: 构建<50>-Footnote-133315861
Ref: 构建<50>-Footnote-143315905
Ref: 构建<50>-Footnote-153315949
Ref: 构建<50>-Footnote-163315993
Ref: 构建<50>-Footnote-173316037
Ref: 构建<50>-Footnote-183316081
Ref: 构建<50>-Footnote-193316125
Node: Windows<46>3316169
Ref: whatsnew/changelog id4643316282
Ref: 12a63316282
Ref: Windows<46>-Footnote-13316932
Ref: Windows<46>-Footnote-23316975
Ref: Windows<46>-Footnote-33317018
Ref: Windows<46>-Footnote-43317061
Ref: Windows<46>-Footnote-53317104
Ref: Windows<46>-Footnote-63317147
Node: 工具/示例<28>3317190
Ref: whatsnew/changelog id4653317302
Ref: 12a73317302
Ref: 工具/示例<28>-Footnote-13318094
Ref: 工具/示例<28>-Footnote-23318137
Ref: 工具/示例<28>-Footnote-33318180
Ref: 工具/示例<28>-Footnote-43318223
Ref: 工具/示例<28>-Footnote-53318266
Ref: 工具/示例<28>-Footnote-63318309
Node: C API<38>3318352
Ref: whatsnew/changelog id4663318444
Ref: 12a83318444
Ref: C API<38>-Footnote-13318933
Ref: C API<38>-Footnote-23318976
Node: Python 3 5 5 正式版3319019
Ref: whatsnew/changelog python-3-5-5-final3319159
Ref: 12a93319159
Node: Python 3 5 5 rc13319290
Ref: whatsnew/changelog python-3-5-5-release-candidate-13319432
Ref: 12aa3319432
Node: 安全性<33>3319617
Ref: whatsnew/changelog id4673319717
Ref: 12ab3319717
Ref: 安全性<33>-Footnote-13320984
Ref: 安全性<33>-Footnote-23321027
Ref: 安全性<33>-Footnote-33321070
Ref: 安全性<33>-Footnote-43321113
Ref: 安全性<33>-Footnote-53321156
Node: 核心与内置函数<56>3321199
Ref: whatsnew/changelog id4683321315
Ref: 12ac3321315
Ref: 核心与内置函数<56>-Footnote-13321541
Node: 库<66>3321584
Ref: whatsnew/changelog id4693321678
Ref: 12ad3321678
Ref: 库<66>-Footnote-13322196
Ref: 库<66>-Footnote-23322239
Node: Python 3 5 4 正式版3322282
Ref: whatsnew/changelog python-3-5-4-final3322418
Ref: 12ae3322418
Node: 库<67>3322532
Ref: whatsnew/changelog id4703322598
Ref: 12af3322598
Ref: 库<67>-Footnote-13322788
Node: Python 3 5 4 rc13322831
Ref: whatsnew/changelog python-3-5-4-release-candidate-13322973
Ref: 12b03322973
Node: 安全性<34>3323268
Ref: whatsnew/changelog id4713323368
Ref: 12b13323368
Ref: 安全性<34>-Footnote-13324666
Ref: 安全性<34>-Footnote-23324709
Ref: 安全性<34>-Footnote-33324752
Ref: 安全性<34>-Footnote-43324795
Node: 核心与内置函数<57>3324838
Ref: whatsnew/changelog id4723324954
Ref: 12b23324954
Ref: 核心与内置函数<57>-Footnote-13327210
Ref: 核心与内置函数<57>-Footnote-23327253
Ref: 核心与内置函数<57>-Footnote-33327296
Ref: 核心与内置函数<57>-Footnote-43327339
Ref: 核心与内置函数<57>-Footnote-53327382
Ref: 核心与内置函数<57>-Footnote-63327425
Ref: 核心与内置函数<57>-Footnote-73327468
Ref: 核心与内置函数<57>-Footnote-83327511
Ref: 核心与内置函数<57>-Footnote-93327554
Ref: 核心与内置函数<57>-Footnote-103327597
Ref: 核心与内置函数<57>-Footnote-113327641
Ref: 核心与内置函数<57>-Footnote-123327685
Ref: 核心与内置函数<57>-Footnote-133327729
Ref: 核心与内置函数<57>-Footnote-143327773
Ref: 核心与内置函数<57>-Footnote-153327817
Node: 库<68>3327861
Ref: whatsnew/changelog id4733327974
Ref: 12b33327974
Ref: 库<68>-Footnote-13338155
Ref: 库<68>-Footnote-23338198
Ref: 库<68>-Footnote-33338241
Ref: 库<68>-Footnote-43338284
Ref: 库<68>-Footnote-53338327
Ref: 库<68>-Footnote-63338370
Ref: 库<68>-Footnote-73338413
Ref: 库<68>-Footnote-83338456
Ref: 库<68>-Footnote-93338499
Ref: 库<68>-Footnote-103338542
Ref: 库<68>-Footnote-113338586
Ref: 库<68>-Footnote-123338630
Ref: 库<68>-Footnote-133338674
Ref: 库<68>-Footnote-143338718
Ref: 库<68>-Footnote-153338762
Ref: 库<68>-Footnote-163338806
Ref: 库<68>-Footnote-173338850
Ref: 库<68>-Footnote-183338894
Ref: 库<68>-Footnote-193338938
Ref: 库<68>-Footnote-203338982
Ref: 库<68>-Footnote-213339026
Ref: 库<68>-Footnote-223339070
Ref: 库<68>-Footnote-233339114
Ref: 库<68>-Footnote-243339158
Ref: 库<68>-Footnote-253339202
Ref: 库<68>-Footnote-263339246
Ref: 库<68>-Footnote-273339290
Ref: 库<68>-Footnote-283339334
Ref: 库<68>-Footnote-293339378
Ref: 库<68>-Footnote-303339422
Ref: 库<68>-Footnote-313339466
Ref: 库<68>-Footnote-323339510
Ref: 库<68>-Footnote-333339554
Ref: 库<68>-Footnote-343339598
Ref: 库<68>-Footnote-353339642
Ref: 库<68>-Footnote-363339686
Ref: 库<68>-Footnote-373339730
Ref: 库<68>-Footnote-383339774
Ref: 库<68>-Footnote-393339818
Ref: 库<68>-Footnote-403339862
Ref: 库<68>-Footnote-413339906
Ref: 库<68>-Footnote-423339950
Ref: 库<68>-Footnote-433339994
Ref: 库<68>-Footnote-443340038
Ref: 库<68>-Footnote-453340082
Ref: 库<68>-Footnote-463340126
Ref: 库<68>-Footnote-473340170
Ref: 库<68>-Footnote-483340214
Ref: 库<68>-Footnote-493340258
Ref: 库<68>-Footnote-503340302
Ref: 库<68>-Footnote-513340346
Ref: 库<68>-Footnote-523340390
Ref: 库<68>-Footnote-533340434
Ref: 库<68>-Footnote-543340478
Ref: 库<68>-Footnote-553340521
Ref: 库<68>-Footnote-563340565
Ref: 库<68>-Footnote-573340609
Ref: 库<68>-Footnote-583340653
Ref: 库<68>-Footnote-593340697
Ref: 库<68>-Footnote-603340741
Ref: 库<68>-Footnote-613340785
Ref: 库<68>-Footnote-623340829
Ref: 库<68>-Footnote-633340873
Ref: 库<68>-Footnote-643340917
Ref: 库<68>-Footnote-653340961
Ref: 库<68>-Footnote-663341005
Ref: 库<68>-Footnote-673341049
Ref: 库<68>-Footnote-683341093
Ref: 库<68>-Footnote-693341137
Ref: 库<68>-Footnote-703341181
Ref: 库<68>-Footnote-713341225
Ref: 库<68>-Footnote-723341269
Ref: 库<68>-Footnote-733341313
Ref: 库<68>-Footnote-743341357
Node: 文档<47>3341401
Ref: whatsnew/changelog id4743341499
Ref: 12b43341499
Ref: 文档<47>-Footnote-13342193
Ref: 文档<47>-Footnote-23342236
Ref: 文档<47>-Footnote-33342279
Ref: 文档<47>-Footnote-43342322
Ref: 文档<47>-Footnote-53342365
Ref: 文档<47>-Footnote-63342408
Node: 测试<48>3342451
Ref: whatsnew/changelog id4753342552
Ref: 12b53342552
Ref: 测试<48>-Footnote-13344651
Ref: 测试<48>-Footnote-23344694
Ref: 测试<48>-Footnote-33344737
Ref: 测试<48>-Footnote-43344780
Ref: 测试<48>-Footnote-53344823
Ref: 测试<48>-Footnote-63344866
Ref: 测试<48>-Footnote-73344909
Ref: 测试<48>-Footnote-83344952
Ref: 测试<48>-Footnote-93344995
Node: 构建<51>3345038
Ref: whatsnew/changelog id4763345140
Ref: 12b63345140
Ref: 构建<51>-Footnote-13345656
Ref: 构建<51>-Footnote-23345699
Ref: 构建<51>-Footnote-33345742
Node: Windows<47>3345785
Ref: whatsnew/changelog id4773345886
Ref: 12b73345886
Ref: Windows<47>-Footnote-13346144
Ref: Windows<47>-Footnote-23346187
Node: C API<39>3346230
Ref: whatsnew/changelog id4783346312
Ref: 12b83346312
Ref: C API<39>-Footnote-13346919
Ref: C API<39>-Footnote-23346962
Node: Python 3 5 3 正式版3347005
Ref: whatsnew/changelog python-3-5-3-final3347141
Ref: 12b93347141
Node: Python 3 5 3 rc13347291
Ref: whatsnew/changelog python-3-5-3-release-candidate-13347433
Ref: 12ba3347433
Node: 核心与内置函数<58>3347842
Ref: whatsnew/changelog id4793347936
Ref: 12bb3347936
Ref: 核心与内置函数<58>-Footnote-13353379
Ref: 核心与内置函数<58>-Footnote-23353422
Ref: 核心与内置函数<58>-Footnote-33353465
Ref: 核心与内置函数<58>-Footnote-43353508
Ref: 核心与内置函数<58>-Footnote-53353551
Ref: 核心与内置函数<58>-Footnote-63353594
Ref: 核心与内置函数<58>-Footnote-73353637
Ref: 核心与内置函数<58>-Footnote-83353680
Ref: 核心与内置函数<58>-Footnote-93353723
Ref: 核心与内置函数<58>-Footnote-103353766
Ref: 核心与内置函数<58>-Footnote-113353810
Ref: 核心与内置函数<58>-Footnote-123353854
Ref: 核心与内置函数<58>-Footnote-133353898
Ref: 核心与内置函数<58>-Footnote-143353942
Ref: 核心与内置函数<58>-Footnote-153353986
Ref: 核心与内置函数<58>-Footnote-163354030
Ref: 核心与内置函数<58>-Footnote-173354074
Ref: 核心与内置函数<58>-Footnote-183354118
Ref: 核心与内置函数<58>-Footnote-193354162
Ref: 核心与内置函数<58>-Footnote-203354206
Ref: 核心与内置函数<58>-Footnote-213354250
Ref: 核心与内置函数<58>-Footnote-223354294
Ref: 核心与内置函数<58>-Footnote-233354338
Ref: 核心与内置函数<58>-Footnote-243354382
Ref: 核心与内置函数<58>-Footnote-253354426
Ref: 核心与内置函数<58>-Footnote-263354470
Ref: 核心与内置函数<58>-Footnote-273354514
Ref: 核心与内置函数<58>-Footnote-283354558
Ref: 核心与内置函数<58>-Footnote-293354602
Ref: 核心与内置函数<58>-Footnote-303354646
Ref: 核心与内置函数<58>-Footnote-313354690
Ref: 核心与内置函数<58>-Footnote-323354734
Ref: 核心与内置函数<58>-Footnote-333354778
Ref: 核心与内置函数<58>-Footnote-343354822
Ref: 核心与内置函数<58>-Footnote-353354866
Ref: 核心与内置函数<58>-Footnote-363354910
Ref: 核心与内置函数<58>-Footnote-373354954
Ref: 核心与内置函数<58>-Footnote-383354998
Ref: 核心与内置函数<58>-Footnote-393355042
Ref: 核心与内置函数<58>-Footnote-403355086
Ref: 核心与内置函数<58>-Footnote-413355130
Ref: 核心与内置函数<58>-Footnote-423355174
Ref: 核心与内置函数<58>-Footnote-433355218
Node: 库<69>3355262
Ref: whatsnew/changelog id4803355378
Ref: 12bc3355378
Ref: 库<69>-Footnote-13368373
Ref: 库<69>-Footnote-23368416
Ref: 库<69>-Footnote-33368459
Ref: 库<69>-Footnote-43368502
Ref: 库<69>-Footnote-53368545
Ref: 库<69>-Footnote-63368587
Ref: 库<69>-Footnote-73368630
Ref: 库<69>-Footnote-83368673
Ref: 库<69>-Footnote-93368716
Ref: 库<69>-Footnote-103368759
Ref: 库<69>-Footnote-113368803
Ref: 库<69>-Footnote-123368847
Ref: 库<69>-Footnote-133368891
Ref: 库<69>-Footnote-143368935
Ref: 库<69>-Footnote-153368979
Ref: 库<69>-Footnote-163369023
Ref: 库<69>-Footnote-173369067
Ref: 库<69>-Footnote-183369111
Ref: 库<69>-Footnote-193369155
Ref: 库<69>-Footnote-203369199
Ref: 库<69>-Footnote-213369243
Ref: 库<69>-Footnote-223369287
Ref: 库<69>-Footnote-233369331
Ref: 库<69>-Footnote-243369375
Ref: 库<69>-Footnote-253369419
Ref: 库<69>-Footnote-263369463
Ref: 库<69>-Footnote-273369507
Ref: 库<69>-Footnote-283369551
Ref: 库<69>-Footnote-293369595
Ref: 库<69>-Footnote-303369639
Ref: 库<69>-Footnote-313369683
Ref: 库<69>-Footnote-323369727
Ref: 库<69>-Footnote-333369773
Ref: 库<69>-Footnote-343369817
Ref: 库<69>-Footnote-353369861
Ref: 库<69>-Footnote-363369905
Ref: 库<69>-Footnote-373369949
Ref: 库<69>-Footnote-383369993
Ref: 库<69>-Footnote-393370037
Ref: 库<69>-Footnote-403370081
Ref: 库<69>-Footnote-413370125
Ref: 库<69>-Footnote-423370169
Ref: 库<69>-Footnote-433370213
Ref: 库<69>-Footnote-443370257
Ref: 库<69>-Footnote-453370301
Ref: 库<69>-Footnote-463370345
Ref: 库<69>-Footnote-473370389
Ref: 库<69>-Footnote-483370433
Ref: 库<69>-Footnote-493370477
Ref: 库<69>-Footnote-503370521
Ref: 库<69>-Footnote-513370565
Ref: 库<69>-Footnote-523370609
Ref: 库<69>-Footnote-533370653
Ref: 库<69>-Footnote-543370697
Ref: 库<69>-Footnote-553370741
Ref: 库<69>-Footnote-563370785
Ref: 库<69>-Footnote-573370829
Ref: 库<69>-Footnote-583370873
Ref: 库<69>-Footnote-593370917
Ref: 库<69>-Footnote-603370961
Ref: 库<69>-Footnote-613371005
Ref: 库<69>-Footnote-623371049
Ref: 库<69>-Footnote-633371093
Ref: 库<69>-Footnote-643371137
Ref: 库<69>-Footnote-653371181
Ref: 库<69>-Footnote-663371225
Ref: 库<69>-Footnote-673371269
Ref: 库<69>-Footnote-683371313
Ref: 库<69>-Footnote-693371357
Ref: 库<69>-Footnote-703371401
Ref: 库<69>-Footnote-713371445
Ref: 库<69>-Footnote-723371488
Ref: 库<69>-Footnote-733371532
Ref: 库<69>-Footnote-743371576
Ref: 库<69>-Footnote-753371620
Ref: 库<69>-Footnote-763371664
Ref: 库<69>-Footnote-773371708
Ref: 库<69>-Footnote-783371752
Ref: 库<69>-Footnote-793371796
Ref: 库<69>-Footnote-803371840
Ref: 库<69>-Footnote-813371884
Ref: 库<69>-Footnote-823371928
Ref: 库<69>-Footnote-833371972
Ref: 库<69>-Footnote-843372016
Ref: 库<69>-Footnote-853372060
Ref: 库<69>-Footnote-863372104
Ref: 库<69>-Footnote-873372148
Ref: 库<69>-Footnote-883372192
Ref: 库<69>-Footnote-893372236
Ref: 库<69>-Footnote-903372280
Ref: 库<69>-Footnote-913372324
Ref: 库<69>-Footnote-923372368
Ref: 库<69>-Footnote-933372412
Ref: 库<69>-Footnote-943372456
Ref: 库<69>-Footnote-953372500
Node: 安全性<35>3372550
Ref: whatsnew/changelog id4813372648
Ref: 12bd3372648
Ref: 安全性<35>-Footnote-13372936
Node: 库<70>3372979
Ref: whatsnew/changelog id4823373083
Ref: 12be3373083
Ref: 库<70>-Footnote-13373248
Node: 安全性<36>3373291
Ref: whatsnew/changelog id4833373389
Ref: 12bf3373389
Ref: 安全性<36>-Footnote-13373552
Node: 库<71>3373595
Ref: whatsnew/changelog id4843373694
Ref: 12c03373694
Ref: 库<71>-Footnote-13376565
Ref: 库<71>-Footnote-23376608
Ref: 库<71>-Footnote-33376651
Ref: 库<71>-Footnote-43376694
Ref: 库<71>-Footnote-53376737
Ref: 库<71>-Footnote-63376780
Ref: 库<71>-Footnote-73376823
Ref: 库<71>-Footnote-83376866
Ref: 库<71>-Footnote-93376909
Ref: 库<71>-Footnote-103376952
Ref: 库<71>-Footnote-113376996
Ref: 库<71>-Footnote-123377040
Ref: 库<71>-Footnote-133377084
Ref: 库<71>-Footnote-143377128
Ref: 库<71>-Footnote-153377172
Ref: 库<71>-Footnote-163377216
Ref: 库<71>-Footnote-173377260
Ref: 库<71>-Footnote-183377304
Ref: 库<71>-Footnote-193377348
Ref: 库<71>-Footnote-203377392
Ref: 库<71>-Footnote-213377436
Ref: 库<71>-Footnote-223377480
Ref: 库<71>-Footnote-233377524
Ref: 库<71>-Footnote-243377568
Ref: 库<71>-Footnote-253377612
Ref: 库<71>-Footnote-263377656
Ref: 库<71>-Footnote-273377700
Ref: 库<71>-Footnote-283377744
Node: IDLE<44>3377788
Ref: whatsnew/changelog id4853377883
Ref: 12c13377883
Ref: IDLE<44>-Footnote-13379139
Ref: IDLE<44>-Footnote-23379182
Ref: IDLE<44>-Footnote-33379225
Ref: IDLE<44>-Footnote-43379268
Ref: IDLE<44>-Footnote-53379311
Ref: IDLE<44>-Footnote-63379354
Ref: IDLE<44>-Footnote-73379397
Ref: IDLE<44>-Footnote-83379440
Node: C API<40>3379483
Ref: whatsnew/changelog id4863379581
Ref: 12c23379581
Ref: C API<40>-Footnote-13379911
Ref: C API<40>-Footnote-23379954
Node: 文档<48>3379997
Ref: whatsnew/changelog id4873380097
Ref: 12c33380097
Ref: 文档<48>-Footnote-13380232
Node: 测试<49>3380275
Ref: whatsnew/changelog id4883380383
Ref: 12c43380383
Ref: 测试<49>-Footnote-13381072
Ref: 测试<49>-Footnote-23381115
Ref: 测试<49>-Footnote-33381158
Ref: 测试<49>-Footnote-43381201
Ref: 测试<49>-Footnote-53381244
Ref: 测试<49>-Footnote-63381287
Node: 工具/示例<29>3381330
Ref: whatsnew/changelog id4893381439
Ref: 12c53381439
Ref: 工具/示例<29>-Footnote-13381919
Ref: 工具/示例<29>-Footnote-23381962
Ref: 工具/示例<29>-Footnote-33382005
Node: Windows<48>3382048
Ref: whatsnew/changelog id4903382157
Ref: 12c63382157
Ref: Windows<48>-Footnote-13382659
Ref: Windows<48>-Footnote-23382702
Ref: Windows<48>-Footnote-33382745
Ref: Windows<48>-Footnote-43382788
Ref: Windows<48>-Footnote-53382831
Node: 构建<52>3382874
Ref: whatsnew/changelog id4913382957
Ref: 12c73382957
Ref: 构建<52>-Footnote-13385659
Ref: 构建<52>-Footnote-23385702
Ref: 构建<52>-Footnote-33385745
Ref: 构建<52>-Footnote-43385788
Ref: 构建<52>-Footnote-53385831
Ref: 构建<52>-Footnote-63385874
Ref: 构建<52>-Footnote-73385917
Ref: 构建<52>-Footnote-83385960
Ref: 构建<52>-Footnote-93386003
Ref: 构建<52>-Footnote-103386046
Ref: 构建<52>-Footnote-113386090
Ref: 构建<52>-Footnote-123386134
Ref: 构建<52>-Footnote-133386178
Ref: 构建<52>-Footnote-143386222
Ref: 构建<52>-Footnote-153386266
Ref: 构建<52>-Footnote-163386310
Ref: 构建<52>-Footnote-173386354
Ref: 构建<52>-Footnote-183386398
Ref: 构建<52>-Footnote-193386442
Ref: 构建<52>-Footnote-203386486
Ref: 构建<52>-Footnote-213386530
Ref: 构建<52>-Footnote-223386574
Node: Python 3 5 2 正式版3386618
Ref: whatsnew/changelog python-3-5-2-final3386754
Ref: 12c83386754
Node: 核心与内置函数<59>3386944
Ref: whatsnew/changelog id4923387047
Ref: 12c93387047
Ref: 核心与内置函数<59>-Footnote-13387214
Node: 测试<50>3387257
Ref: whatsnew/changelog id4933387377
Ref: 12ca3387377
Ref: 测试<50>-Footnote-13387537
Node: IDLE<45>3387580
Ref: whatsnew/changelog id4943387666
Ref: 12cb3387666
Ref: IDLE<45>-Footnote-13387820
Node: Python 3 5 2 rc13387863
Ref: whatsnew/changelog python-3-5-2-release-candidate-13388005
Ref: 12cc3388005
Node: 核心与内置函数<60>3388534
Ref: whatsnew/changelog id4953388634
Ref: 12cd3388634
Ref: 核心与内置函数<60>-Footnote-13394482
Ref: 核心与内置函数<60>-Footnote-23394525
Ref: 核心与内置函数<60>-Footnote-33394568
Ref: 核心与内置函数<60>-Footnote-43394611
Ref: 核心与内置函数<60>-Footnote-53394654
Ref: 核心与内置函数<60>-Footnote-63394697
Ref: 核心与内置函数<60>-Footnote-73394740
Ref: 核心与内置函数<60>-Footnote-83394783
Ref: 核心与内置函数<60>-Footnote-93394826
Ref: 核心与内置函数<60>-Footnote-103394869
Ref: 核心与内置函数<60>-Footnote-113394913
Ref: 核心与内置函数<60>-Footnote-123394957
Ref: 核心与内置函数<60>-Footnote-133395001
Ref: 核心与内置函数<60>-Footnote-143395045
Ref: 核心与内置函数<60>-Footnote-153395089
Ref: 核心与内置函数<60>-Footnote-163395133
Ref: 核心与内置函数<60>-Footnote-173395177
Ref: 核心与内置函数<60>-Footnote-183395220
Ref: 核心与内置函数<60>-Footnote-193395264
Ref: 核心与内置函数<60>-Footnote-203395308
Ref: 核心与内置函数<60>-Footnote-213395352
Ref: 核心与内置函数<60>-Footnote-223395396
Ref: 核心与内置函数<60>-Footnote-233395440
Ref: 核心与内置函数<60>-Footnote-243395484
Ref: 核心与内置函数<60>-Footnote-253395528
Ref: 核心与内置函数<60>-Footnote-263395572
Ref: 核心与内置函数<60>-Footnote-273395616
Ref: 核心与内置函数<60>-Footnote-283395660
Ref: 核心与内置函数<60>-Footnote-293395704
Ref: 核心与内置函数<60>-Footnote-303395748
Ref: 核心与内置函数<60>-Footnote-313395792
Ref: 核心与内置函数<60>-Footnote-323395842
Ref: 核心与内置函数<60>-Footnote-333395886
Ref: 核心与内置函数<60>-Footnote-343395930
Ref: 核心与内置函数<60>-Footnote-353395974
Ref: 核心与内置函数<60>-Footnote-363396018
Ref: 核心与内置函数<60>-Footnote-373396062
Ref: 核心与内置函数<60>-Footnote-383396106
Node: 安全性<37>3396150
Ref: whatsnew/changelog id4963396266
Ref: 12ce3396266
Ref: 安全性<37>-Footnote-13396500
Node: 库<72>3396543
Ref: whatsnew/changelog id4973396647
Ref: 12cf3396647
Ref: 库<72>-Footnote-13397814
Ref: 库<72>-Footnote-23397857
Ref: 库<72>-Footnote-33397900
Ref: 库<72>-Footnote-43397949
Ref: 库<72>-Footnote-53397992
Node: 安全性<38>3398035
Ref: whatsnew/changelog id4983398133
Ref: 12d03398133
Ref: 安全性<38>-Footnote-13398456
Node: 库<73>3398499
Ref: whatsnew/changelog id4993398603
Ref: 12d13398603
Ref: 库<73>-Footnote-13403318
Ref: 库<73>-Footnote-23403361
Ref: 库<73>-Footnote-33403404
Ref: 库<73>-Footnote-43403447
Ref: 库<73>-Footnote-53403490
Ref: 库<73>-Footnote-63403533
Ref: 库<73>-Footnote-73403576
Ref: 库<73>-Footnote-83403619
Ref: 库<73>-Footnote-93403662
Ref: 库<73>-Footnote-103403705
Ref: 库<73>-Footnote-113403749
Ref: 库<73>-Footnote-123403793
Ref: 库<73>-Footnote-133403837
Ref: 库<73>-Footnote-143403881
Ref: 库<73>-Footnote-153403925
Ref: 库<73>-Footnote-163403969
Ref: 库<73>-Footnote-173404013
Ref: 库<73>-Footnote-183404057
Ref: 库<73>-Footnote-193404101
Ref: 库<73>-Footnote-203404145
Ref: 库<73>-Footnote-213404189
Ref: 库<73>-Footnote-223404233
Ref: 库<73>-Footnote-233404277
Ref: 库<73>-Footnote-243404321
Ref: 库<73>-Footnote-253404365
Ref: 库<73>-Footnote-263404409
Ref: 库<73>-Footnote-273404453
Ref: 库<73>-Footnote-283404497
Ref: 库<73>-Footnote-293404541
Ref: 库<73>-Footnote-303404585
Ref: 库<73>-Footnote-313404629
Node: 安全性<39>3404673
Ref: whatsnew/changelog id5003404771
Ref: 12d23404771
Ref: 安全性<39>-Footnote-13405058
Node: 库<74>3405101
Ref: whatsnew/changelog id5013405205
Ref: 12d33405205
Ref: 库<74>-Footnote-13407269
Ref: 库<74>-Footnote-23407312
Ref: 库<74>-Footnote-33407355
Ref: 库<74>-Footnote-43407398
Ref: 库<74>-Footnote-53407441
Ref: 库<74>-Footnote-63407484
Ref: 库<74>-Footnote-73407527
Ref: 库<74>-Footnote-83407570
Ref: 库<74>-Footnote-93407613
Ref: 库<74>-Footnote-103407656
Ref: 库<74>-Footnote-113407700
Ref: 库<74>-Footnote-123407744
Ref: 库<74>-Footnote-133407788
Ref: 库<74>-Footnote-143407832
Ref: 库<74>-Footnote-153407876
Node: 安全性<40>3407920
Ref: whatsnew/changelog id5023408018
Ref: 12d43408018
Ref: 安全性<40>-Footnote-13408204
Node: 库<75>3408247
Ref: whatsnew/changelog id5033408351
Ref: 12d53408351
Ref: 库<75>-Footnote-13410895
Ref: 库<75>-Footnote-23410938
Ref: 库<75>-Footnote-33410981
Ref: 库<75>-Footnote-43411024
Ref: 库<75>-Footnote-53411067
Ref: 库<75>-Footnote-63411110
Ref: 库<75>-Footnote-73411153
Ref: 库<75>-Footnote-83411196
Ref: 库<75>-Footnote-93411239
Ref: 库<75>-Footnote-103411282
Ref: 库<75>-Footnote-113411325
Ref: 库<75>-Footnote-123411369
Ref: 库<75>-Footnote-133411413
Ref: 库<75>-Footnote-143411457
Ref: 库<75>-Footnote-153411501
Ref: 库<75>-Footnote-163411545
Ref: 库<75>-Footnote-173411589
Ref: 库<75>-Footnote-183411633
Ref: 库<75>-Footnote-193411677
Node: 安全性<41>3411721
Ref: whatsnew/changelog id5043411819
Ref: 12d63411819
Ref: 安全性<41>-Footnote-13411986
Node: 库<76>3412029
Ref: whatsnew/changelog id5053412128
Ref: 12d73412128
Ref: 库<76>-Footnote-13418611
Ref: 库<76>-Footnote-23418654
Ref: 库<76>-Footnote-33418697
Ref: 库<76>-Footnote-43418740
Ref: 库<76>-Footnote-53418783
Ref: 库<76>-Footnote-63418826
Ref: 库<76>-Footnote-73418869
Ref: 库<76>-Footnote-83418912
Ref: 库<76>-Footnote-93418955
Ref: 库<76>-Footnote-103418998
Ref: 库<76>-Footnote-113419042
Ref: 库<76>-Footnote-123419086
Ref: 库<76>-Footnote-133419130
Ref: 库<76>-Footnote-143419174
Ref: 库<76>-Footnote-153419218
Ref: 库<76>-Footnote-163419262
Ref: 库<76>-Footnote-173419306
Ref: 库<76>-Footnote-183419350
Ref: 库<76>-Footnote-193419394
Ref: 库<76>-Footnote-203419438
Ref: 库<76>-Footnote-213419482
Ref: 库<76>-Footnote-223419526
Ref: 库<76>-Footnote-233419570
Ref: 库<76>-Footnote-243419614
Ref: 库<76>-Footnote-253419658
Ref: 库<76>-Footnote-263419702
Ref: 库<76>-Footnote-273419746
Ref: 库<76>-Footnote-283419790
Ref: 库<76>-Footnote-293419834
Ref: 库<76>-Footnote-303419878
Ref: 库<76>-Footnote-313419922
Ref: 库<76>-Footnote-323419965
Ref: 库<76>-Footnote-333420009
Ref: 库<76>-Footnote-343420053
Ref: 库<76>-Footnote-353420097
Ref: 库<76>-Footnote-363420141
Ref: 库<76>-Footnote-373420185
Ref: 库<76>-Footnote-383420229
Ref: 库<76>-Footnote-393420273
Ref: 库<76>-Footnote-403420317
Ref: 库<76>-Footnote-413420361
Ref: 库<76>-Footnote-423420405
Ref: 库<76>-Footnote-433420449
Ref: 库<76>-Footnote-443420493
Ref: 库<76>-Footnote-453420537
Ref: 库<76>-Footnote-463420581
Ref: 库<76>-Footnote-473420625
Ref: 库<76>-Footnote-483420669
Ref: 库<76>-Footnote-493420713
Ref: 库<76>-Footnote-503420757
Node: IDLE<46>3420801
Ref: whatsnew/changelog id5063420897
Ref: 12d83420897
Ref: IDLE<46>-Footnote-13423260
Ref: IDLE<46>-Footnote-23423302
Ref: IDLE<46>-Footnote-33423345
Ref: IDLE<46>-Footnote-43423388
Ref: IDLE<46>-Footnote-53423431
Ref: IDLE<46>-Footnote-63423474
Ref: IDLE<46>-Footnote-73423517
Ref: IDLE<46>-Footnote-83423560
Ref: IDLE<46>-Footnote-93423603
Ref: IDLE<46>-Footnote-103423646
Ref: IDLE<46>-Footnote-113423690
Ref: IDLE<46>-Footnote-123423734
Ref: IDLE<46>-Footnote-133423778
Ref: IDLE<46>-Footnote-143423822
Ref: IDLE<46>-Footnote-153423866
Node: 文档<49>3423910
Ref: whatsnew/changelog id5073424009
Ref: 12d93424009
Ref: 文档<49>-Footnote-13424949
Ref: 文档<49>-Footnote-23424992
Ref: 文档<49>-Footnote-33425035
Ref: 文档<49>-Footnote-43425084
Ref: 文档<49>-Footnote-53425127
Ref: 文档<49>-Footnote-63425169
Ref: 文档<49>-Footnote-73425212
Ref: 文档<49>-Footnote-83425255
Node: 测试<51>3425298
Ref: whatsnew/changelog id5083425399
Ref: 12da3425399
Ref: 测试<51>-Footnote-13426274
Ref: 测试<51>-Footnote-23426317
Ref: 测试<51>-Footnote-33426360
Ref: 测试<51>-Footnote-43426403
Ref: 测试<51>-Footnote-53426446
Ref: 测试<51>-Footnote-63426489
Ref: 测试<51>-Footnote-73426532
Node: 构建<53>3426575
Ref: whatsnew/changelog id5093426677
Ref: 12db3426677
Ref: 构建<53>-Footnote-13429186
Ref: 构建<53>-Footnote-23429229
Ref: 构建<53>-Footnote-33429272
Ref: 构建<53>-Footnote-43429315
Ref: 构建<53>-Footnote-53429358
Ref: 构建<53>-Footnote-63429401
Ref: 构建<53>-Footnote-73429444
Ref: 构建<53>-Footnote-83429487
Ref: 构建<53>-Footnote-93429530
Ref: 构建<53>-Footnote-103429573
Ref: 构建<53>-Footnote-113429617
Ref: 构建<53>-Footnote-123429661
Ref: 构建<53>-Footnote-133429705
Ref: 构建<53>-Footnote-143429749
Ref: 构建<53>-Footnote-153429793
Ref: 构建<53>-Footnote-163429837
Ref: 构建<53>-Footnote-173429881
Node: Windows<49>3429925
Ref: whatsnew/changelog id5103430034
Ref: 12dc3430034
Ref: Windows<49>-Footnote-13430616
Ref: Windows<49>-Footnote-23430659
Ref: Windows<49>-Footnote-33430702
Ref: Windows<49>-Footnote-43430745
Ref: Windows<49>-Footnote-53430788
Node: 工具/示例<30>3430831
Ref: whatsnew/changelog id5113430941
Ref: 12dd3430941
Ref: 工具/示例<30>-Footnote-13431565
Ref: 工具/示例<30>-Footnote-23431608
Ref: 工具/示例<30>-Footnote-33431651
Ref: 工具/示例<30>-Footnote-43431694
Node: Windows<50>3431737
Ref: whatsnew/changelog id5123431827
Ref: 12de3431827
Ref: Windows<50>-Footnote-13432030
Node: Python 3 5 1 正式版3432073
Ref: whatsnew/changelog python-3-5-1-final3432209
Ref: 12df3432209
Node: 核心与内置函数<61>3432383
Ref: whatsnew/changelog id5133432487
Ref: 12e03432487
Ref: 核心与内置函数<61>-Footnote-13432672
Node: Windows<51>3432715
Ref: whatsnew/changelog id5143432819
Ref: 12e13432819
Ref: Windows<51>-Footnote-13433009
Node: Python 3 5 1 rc13433052
Ref: whatsnew/changelog python-3-5-1-release-candidate-13433194
Ref: 12e23433194
Node: 核心与内置函数<62>3433495
Ref: whatsnew/changelog id5153433589
Ref: 12e33433589
Ref: 核心与内置函数<62>-Footnote-13436722
Ref: 核心与内置函数<62>-Footnote-23436765
Ref: 核心与内置函数<62>-Footnote-33436808
Ref: 核心与内置函数<62>-Footnote-43436851
Ref: 核心与内置函数<62>-Footnote-53436894
Ref: 核心与内置函数<62>-Footnote-63436937
Ref: 核心与内置函数<62>-Footnote-73436980
Ref: 核心与内置函数<62>-Footnote-83437023
Ref: 核心与内置函数<62>-Footnote-93437066
Ref: 核心与内置函数<62>-Footnote-103437109
Ref: 核心与内置函数<62>-Footnote-113437153
Ref: 核心与内置函数<62>-Footnote-123437197
Ref: 核心与内置函数<62>-Footnote-133437241
Ref: 核心与内置函数<62>-Footnote-143437285
Ref: 核心与内置函数<62>-Footnote-153437329
Ref: 核心与内置函数<62>-Footnote-163437373
Ref: 核心与内置函数<62>-Footnote-173437417
Ref: 核心与内置函数<62>-Footnote-183437461
Ref: 核心与内置函数<62>-Footnote-193437505
Node: 库<77>3437549
Ref: whatsnew/changelog id5163437660
Ref: 12e43437660
Ref: 库<77>-Footnote-13448017
Ref: 库<77>-Footnote-23448060
Ref: 库<77>-Footnote-33448103
Ref: 库<77>-Footnote-43448146
Ref: 库<77>-Footnote-53448188
Ref: 库<77>-Footnote-63448231
Ref: 库<77>-Footnote-73448274
Ref: 库<77>-Footnote-83448317
Ref: 库<77>-Footnote-93448360
Ref: 库<77>-Footnote-103448403
Ref: 库<77>-Footnote-113448447
Ref: 库<77>-Footnote-123448491
Ref: 库<77>-Footnote-133448535
Ref: 库<77>-Footnote-143448579
Ref: 库<77>-Footnote-153448623
Ref: 库<77>-Footnote-163448667
Ref: 库<77>-Footnote-173448711
Ref: 库<77>-Footnote-183448755
Ref: 库<77>-Footnote-193448799
Ref: 库<77>-Footnote-203448843
Ref: 库<77>-Footnote-213448887
Ref: 库<77>-Footnote-223448931
Ref: 库<77>-Footnote-233448975
Ref: 库<77>-Footnote-243449019
Ref: 库<77>-Footnote-253449063
Ref: 库<77>-Footnote-263449107
Ref: 库<77>-Footnote-273449151
Ref: 库<77>-Footnote-283449195
Ref: 库<77>-Footnote-293449239
Ref: 库<77>-Footnote-303449283
Ref: 库<77>-Footnote-313449327
Ref: 库<77>-Footnote-323449371
Ref: 库<77>-Footnote-333449415
Ref: 库<77>-Footnote-343449459
Ref: 库<77>-Footnote-353449503
Ref: 库<77>-Footnote-363449547
Ref: 库<77>-Footnote-373449591
Ref: 库<77>-Footnote-383449635
Ref: 库<77>-Footnote-393449679
Ref: 库<77>-Footnote-403449723
Ref: 库<77>-Footnote-413449767
Ref: 库<77>-Footnote-423449811
Ref: 库<77>-Footnote-433449855
Ref: 库<77>-Footnote-443449899
Ref: 库<77>-Footnote-453449943
Ref: 库<77>-Footnote-463449987
Ref: 库<77>-Footnote-473450031
Ref: 库<77>-Footnote-483450075
Ref: 库<77>-Footnote-493450119
Ref: 库<77>-Footnote-503450163
Ref: 库<77>-Footnote-513450207
Ref: 库<77>-Footnote-523450251
Ref: 库<77>-Footnote-533450295
Ref: 库<77>-Footnote-543450339
Ref: 库<77>-Footnote-553450383
Ref: 库<77>-Footnote-563450427
Ref: 库<77>-Footnote-573450471
Ref: 库<77>-Footnote-583450515
Ref: 库<77>-Footnote-593450559
Ref: 库<77>-Footnote-603450603
Ref: 库<77>-Footnote-613450647
Ref: 库<77>-Footnote-623450691
Ref: 库<77>-Footnote-633450735
Ref: 库<77>-Footnote-643450779
Ref: 库<77>-Footnote-653450823
Ref: 库<77>-Footnote-663450867
Ref: 库<77>-Footnote-673450911
Ref: 库<77>-Footnote-683450955
Ref: 库<77>-Footnote-693450999
Ref: 库<77>-Footnote-703451043
Node: IDLE<47>3451087
Ref: whatsnew/changelog id5173451183
Ref: 12e53451183
Ref: IDLE<47>-Footnote-13456136
Ref: IDLE<47>-Footnote-23456179
Ref: IDLE<47>-Footnote-33456222
Ref: IDLE<47>-Footnote-43456265
Ref: IDLE<47>-Footnote-53456308
Ref: IDLE<47>-Footnote-63456351
Ref: IDLE<47>-Footnote-73456394
Ref: IDLE<47>-Footnote-83456437
Ref: IDLE<47>-Footnote-93456480
Ref: IDLE<47>-Footnote-103456523
Ref: IDLE<47>-Footnote-113456567
Ref: IDLE<47>-Footnote-123456611
Ref: IDLE<47>-Footnote-133456655
Ref: IDLE<47>-Footnote-143456699
Ref: IDLE<47>-Footnote-153456743
Ref: IDLE<47>-Footnote-163456787
Ref: IDLE<47>-Footnote-173456831
Ref: IDLE<47>-Footnote-183456875
Ref: IDLE<47>-Footnote-193456919
Ref: IDLE<47>-Footnote-203456963
Ref: IDLE<47>-Footnote-213457007
Ref: IDLE<47>-Footnote-223457051
Ref: IDLE<47>-Footnote-233457095
Ref: IDLE<47>-Footnote-243457139
Ref: IDLE<47>-Footnote-253457183
Node: 文档<50>3457227
Ref: whatsnew/changelog id5183457326
Ref: 12e63457326
Ref: 文档<50>-Footnote-13458383
Ref: 文档<50>-Footnote-23458426
Ref: 文档<50>-Footnote-33458469
Ref: 文档<50>-Footnote-43458512
Ref: 文档<50>-Footnote-53458555
Ref: 文档<50>-Footnote-63458598
Node: 测试<52>3458641
Ref: whatsnew/changelog id5193458742
Ref: 12e73458742
Ref: 测试<52>-Footnote-13459249
Ref: 测试<52>-Footnote-23459292
Ref: 测试<52>-Footnote-33459335
Node: 构建<54>3459378
Ref: whatsnew/changelog id5203459480
Ref: 12e83459480
Ref: 构建<54>-Footnote-13459905
Ref: 构建<54>-Footnote-23459948
Ref: 构建<54>-Footnote-33459991
Node: Windows<52>3460034
Ref: whatsnew/changelog id5213460143
Ref: 12e93460143
Ref: Windows<52>-Footnote-13461416
Ref: Windows<52>-Footnote-23461459
Ref: Windows<52>-Footnote-33461502
Ref: Windows<52>-Footnote-43461545
Ref: Windows<52>-Footnote-53461588
Ref: Windows<52>-Footnote-63461631
Ref: Windows<52>-Footnote-73461674
Ref: Windows<52>-Footnote-83461717
Ref: Windows<52>-Footnote-93461760
Ref: Windows<52>-Footnote-103461803
Ref: Windows<52>-Footnote-113461847
Ref: Windows<52>-Footnote-123461891
Ref: Windows<52>-Footnote-133461935
Ref: Windows<52>-Footnote-143461979
Node: 工具/示例<31>3462023
Ref: whatsnew/changelog id5223462113
Ref: 12ea3462113
Ref: 工具/示例<31>-Footnote-13462263
Node: Python 3 5 0 正式版3462306
Ref: whatsnew/changelog python-3-5-0-final3462442
Ref: 12eb3462442
Node: 构建<55>3462562
Ref: whatsnew/changelog id5233462631
Ref: 12ec3462631
Ref: 构建<55>-Footnote-13462807
Node: Python 3 5 0 rc43462850
Ref: whatsnew/changelog python-3-5-0-release-candidate-43462986
Ref: 12ed3462986
Node: 库<78>3463113
Ref: whatsnew/changelog id5243463192
Ref: 12ee3463192
Ref: 库<78>-Footnote-13463312
Node: 构建<56>3463355
Ref: whatsnew/changelog id5253463434
Ref: 12ef3463434
Ref: 构建<56>-Footnote-13463616
Node: Python 3 5 0 rc33463659
Ref: whatsnew/changelog python-3-5-0-release-candidate-33463789
Ref: 12f03463789
Node: 核心与内置函数<63>3463946
Ref: whatsnew/changelog id5263464040
Ref: 12f13464040
Ref: 核心与内置函数<63>-Footnote-13464409
Ref: 核心与内置函数<63>-Footnote-23464452
Ref: 核心与内置函数<63>-Footnote-33464495
Ref: 核心与内置函数<63>-Footnote-43464538
Node: 库<79>3464587
Ref: whatsnew/changelog id5273464681
Ref: 12f23464681
Ref: 库<79>-Footnote-13465446
Ref: 库<79>-Footnote-23465489
Ref: 库<79>-Footnote-33465532
Ref: 库<79>-Footnote-43465575
Ref: 库<79>-Footnote-53465618
Node: Python 3 5 0 rc23465661
Ref: whatsnew/changelog python-3-5-0-release-candidate-23465791
Ref: 12f33465791
Node: 核心与内置函数<64>3465948
Ref: whatsnew/changelog id5283466042
Ref: 12f43466042
Ref: 核心与内置函数<64>-Footnote-13466583
Ref: 核心与内置函数<64>-Footnote-23466626
Ref: 核心与内置函数<64>-Footnote-33466669
Node: 库<80>3466712
Ref: whatsnew/changelog id5293466806
Ref: 12f53466806
Ref: 库<80>-Footnote-13467078
Ref: 库<80>-Footnote-23467121
Ref: 库<80>-Footnote-33467164
Node: Python 3 5 0 rc13467207
Ref: whatsnew/changelog python-3-5-0-release-candidate-13467340
Ref: 12f63467340
Node: 核心与内置函数<65>3467559
Ref: whatsnew/changelog id5303467653
Ref: 12f73467653
Ref: 核心与内置函数<65>-Footnote-13467832
Node: 库<81>3467875
Ref: whatsnew/changelog id5313467986
Ref: 12f83467986
Ref: 库<81>-Footnote-13469546
Ref: 库<81>-Footnote-23469589
Ref: 库<81>-Footnote-33469632
Ref: 库<81>-Footnote-43469675
Ref: 库<81>-Footnote-53469717
Ref: 库<81>-Footnote-63469760
Ref: 库<81>-Footnote-73469803
Ref: 库<81>-Footnote-83469846
Ref: 库<81>-Footnote-93469889
Ref: 库<81>-Footnote-103469932
Ref: 库<81>-Footnote-113469976
Ref: 库<81>-Footnote-123470020
Ref: 库<81>-Footnote-133470064
Ref: 库<81>-Footnote-143470108
Ref: 库<81>-Footnote-153470152
Node: IDLE<48>3470196
Ref: whatsnew/changelog id5323470292
Ref: 12f93470292
Ref: IDLE<48>-Footnote-13471037
Ref: IDLE<48>-Footnote-23471080
Ref: IDLE<48>-Footnote-33471123
Ref: IDLE<48>-Footnote-43471166
Node: 文档<51>3471209
Ref: whatsnew/changelog id5333471308
Ref: 12fa3471308
Ref: 文档<51>-Footnote-13471952
Ref: 文档<51>-Footnote-23471995
Ref: 文档<51>-Footnote-33472038
Ref: 文档<51>-Footnote-43472081
Node: 测试<53>3472124
Ref: whatsnew/changelog id5343472206
Ref: 12fb3472206
Ref: 测试<53>-Footnote-13472444
Node: Python 3 5 0 beta 43472487
Ref: whatsnew/changelog python-3-5-0-beta-43472623
Ref: 12fc3472623
Node: 核心与内置函数<66>3472808
Ref: whatsnew/changelog id5353472905
Ref: 12fd3472905
Ref: 核心与内置函数<66>-Footnote-13473710
Ref: 核心与内置函数<66>-Footnote-23473753
Ref: 核心与内置函数<66>-Footnote-33473796
Ref: 核心与内置函数<66>-Footnote-43473845
Ref: 核心与内置函数<66>-Footnote-53473888
Ref: 核心与内置函数<66>-Footnote-63473931
Ref: 核心与内置函数<66>-Footnote-73473974
Ref: 核心与内置函数<66>-Footnote-83474017
Node: 库<82>3474060
Ref: whatsnew/changelog id5363474176
Ref: 12fe3474176
Ref: 库<82>-Footnote-13476454
Ref: 库<82>-Footnote-23476497
Ref: 库<82>-Footnote-33476540
Ref: 库<82>-Footnote-43476583
Ref: 库<82>-Footnote-53476626
Ref: 库<82>-Footnote-63476669
Ref: 库<82>-Footnote-73476712
Ref: 库<82>-Footnote-83476755
Ref: 库<82>-Footnote-93476798
Ref: 库<82>-Footnote-103476841
Ref: 库<82>-Footnote-113476885
Ref: 库<82>-Footnote-123476929
Ref: 库<82>-Footnote-133476973
Ref: 库<82>-Footnote-143477017
Ref: 库<82>-Footnote-153477061
Ref: 库<82>-Footnote-163477105
Ref: 库<82>-Footnote-173477149
Ref: 库<82>-Footnote-183477193
Ref: 库<82>-Footnote-193477237
Node: 构建<57>3477281
Ref: whatsnew/changelog id5373477363
Ref: 12ff3477363
Ref: 构建<57>-Footnote-13477527
Node: Python 3 5 0 beta 33477570
Ref: whatsnew/changelog python-3-5-0-beta-33477709
Ref: 13003477709
Node: 核心与内置函数<67>3477938
Ref: whatsnew/changelog id5383478035
Ref: 13013478035
Ref: 核心与内置函数<67>-Footnote-13479361
Ref: 核心与内置函数<67>-Footnote-23479404
Ref: 核心与内置函数<67>-Footnote-33479447
Ref: 核心与内置函数<67>-Footnote-43479490
Ref: 核心与内置函数<67>-Footnote-53479539
Ref: 核心与内置函数<67>-Footnote-63479582
Node: 库<83>3479625
Ref: whatsnew/changelog id5393479741
Ref: 13023479741
Ref: 库<83>-Footnote-13481684
Ref: 库<83>-Footnote-23481727
Ref: 库<83>-Footnote-33481770
Ref: 库<83>-Footnote-43481813
Ref: 库<83>-Footnote-53481856
Ref: 库<83>-Footnote-63481899
Ref: 库<83>-Footnote-73481942
Ref: 库<83>-Footnote-83481985
Ref: 库<83>-Footnote-93482028
Ref: 库<83>-Footnote-103482071
Ref: 库<83>-Footnote-113482115
Ref: 库<83>-Footnote-123482159
Ref: 库<83>-Footnote-133482203
Ref: 库<83>-Footnote-143482247
Ref: 库<83>-Footnote-153482291
Ref: 库<83>-Footnote-163482335
Ref: 库<83>-Footnote-173482379
Ref: 库<83>-Footnote-183482423
Node: 测试<54>3482467
Ref: whatsnew/changelog id5403482568
Ref: 13033482568
Ref: 测试<54>-Footnote-13482848
Ref: 测试<54>-Footnote-23482891
Node: 文档<52>3482934
Ref: whatsnew/changelog id5413483038
Ref: 13043483038
Ref: 文档<52>-Footnote-13483360
Ref: 文档<52>-Footnote-23483403
Node: 构建<58>3483446
Ref: whatsnew/changelog id5423483531
Ref: 13053483531
Ref: 构建<58>-Footnote-13483695
Node: Python 3 5 0 beta 23483738
Ref: whatsnew/changelog python-3-5-0-beta-23483877
Ref: 13063483877
Node: 核心与内置函数<68>3484040
Ref: whatsnew/changelog id5433484137
Ref: 13073484137
Ref: 核心与内置函数<68>-Footnote-13484889
Ref: 核心与内置函数<68>-Footnote-23484932
Ref: 核心与内置函数<68>-Footnote-33484975
Ref: 核心与内置函数<68>-Footnote-43485018
Ref: 核心与内置函数<68>-Footnote-53485061
Node: 库<84>3485104
Ref: whatsnew/changelog id5443485201
Ref: 13083485201
Ref: 库<84>-Footnote-13485897
Ref: 库<84>-Footnote-23485940
Ref: 库<84>-Footnote-33485983
Ref: 库<84>-Footnote-43486032
Ref: 库<84>-Footnote-53486074
Ref: 库<84>-Footnote-63486117
Ref: 库<84>-Footnote-73486160
Node: Python 3 5 0 beta 13486203
Ref: whatsnew/changelog python-3-5-0-beta-13486343
Ref: 13093486343
Node: 核心与内置函数<69>3486604
Ref: whatsnew/changelog id5453486701
Ref: 130a3486701
Ref: 核心与内置函数<69>-Footnote-13488573
Ref: 核心与内置函数<69>-Footnote-23488616
Ref: 核心与内置函数<69>-Footnote-33488659
Ref: 核心与内置函数<69>-Footnote-43488702
Ref: 核心与内置函数<69>-Footnote-53488745
Ref: 核心与内置函数<69>-Footnote-63488788
Ref: 核心与内置函数<69>-Footnote-73488831
Ref: 核心与内置函数<69>-Footnote-83488874
Ref: 核心与内置函数<69>-Footnote-93488917
Ref: 核心与内置函数<69>-Footnote-103488960
Ref: 核心与内置函数<69>-Footnote-113489003
Ref: 核心与内置函数<69>-Footnote-123489047
Ref: 核心与内置函数<69>-Footnote-133489091
Ref: 核心与内置函数<69>-Footnote-143489135
Ref: 核心与内置函数<69>-Footnote-153489179
Ref: 核心与内置函数<69>-Footnote-163489223
Ref: 核心与内置函数<69>-Footnote-173489267
Ref: 核心与内置函数<69>-Footnote-183489310
Ref: 核心与内置函数<69>-Footnote-193489354
Node: 库<85>3489398
Ref: whatsnew/changelog id5463489512
Ref: 130b3489512
Ref: 库<85>-Footnote-13497159
Ref: 库<85>-Footnote-23497202
Ref: 库<85>-Footnote-33497245
Ref: 库<85>-Footnote-43497288
Ref: 库<85>-Footnote-53497331
Ref: 库<85>-Footnote-63497374
Ref: 库<85>-Footnote-73497417
Ref: 库<85>-Footnote-83497460
Ref: 库<85>-Footnote-93497503
Ref: 库<85>-Footnote-103497546
Ref: 库<85>-Footnote-113497589
Ref: 库<85>-Footnote-123497633
Ref: 库<85>-Footnote-133497677
Ref: 库<85>-Footnote-143497721
Ref: 库<85>-Footnote-153497764
Ref: 库<85>-Footnote-163497808
Ref: 库<85>-Footnote-173497852
Ref: 库<85>-Footnote-183497896
Ref: 库<85>-Footnote-193497940
Ref: 库<85>-Footnote-203497984
Ref: 库<85>-Footnote-213498028
Ref: 库<85>-Footnote-223498072
Ref: 库<85>-Footnote-233498116
Ref: 库<85>-Footnote-243498160
Ref: 库<85>-Footnote-253498204
Ref: 库<85>-Footnote-263498247
Ref: 库<85>-Footnote-273498291
Ref: 库<85>-Footnote-283498335
Ref: 库<85>-Footnote-293498379
Ref: 库<85>-Footnote-303498423
Ref: 库<85>-Footnote-313498467
Ref: 库<85>-Footnote-323498511
Ref: 库<85>-Footnote-333498555
Ref: 库<85>-Footnote-343498599
Ref: 库<85>-Footnote-353498643
Ref: 库<85>-Footnote-363498687
Ref: 库<85>-Footnote-373498731
Ref: 库<85>-Footnote-383498775
Ref: 库<85>-Footnote-393498819
Ref: 库<85>-Footnote-403498863
Ref: 库<85>-Footnote-413498907
Ref: 库<85>-Footnote-423498950
Ref: 库<85>-Footnote-433498994
Ref: 库<85>-Footnote-443499038
Ref: 库<85>-Footnote-453499082
Ref: 库<85>-Footnote-463499126
Ref: 库<85>-Footnote-473499170
Ref: 库<85>-Footnote-483499214
Ref: 库<85>-Footnote-493499258
Ref: 库<85>-Footnote-503499302
Ref: 库<85>-Footnote-513499346
Ref: 库<85>-Footnote-523499390
Ref: 库<85>-Footnote-533499434
Ref: 库<85>-Footnote-543499478
Ref: 库<85>-Footnote-553499522
Ref: 库<85>-Footnote-563499566
Node: IDLE<49>3499610
Ref: whatsnew/changelog id5473499709
Ref: 130c3499709
Ref: IDLE<49>-Footnote-13499876
Node: 测试<55>3499919
Ref: whatsnew/changelog id5483500021
Ref: 130d3500021
Ref: 测试<55>-Footnote-13500317
Ref: 测试<55>-Footnote-23500360
Node: 文档<53>3500402
Ref: whatsnew/changelog id5493500513
Ref: 130e3500513
Ref: 文档<53>-Footnote-13500902
Ref: 文档<53>-Footnote-23500945
Ref: 文档<53>-Footnote-33500988
Node: 工具/示例<32>3501031
Ref: whatsnew/changelog id5503501123
Ref: 130f3501123
Ref: 工具/示例<32>-Footnote-13501636
Ref: 工具/示例<32>-Footnote-23501679
Ref: 工具/示例<32>-Footnote-33501722
Ref: 工具/示例<32>-Footnote-43501765
Node: Python 3 5 0 alpha 43501808
Ref: whatsnew/changelog python-3-5-0-alpha-43501949
Ref: 13103501949
Node: 核心与内置函数<70>3502214
Ref: whatsnew/changelog id5513502312
Ref: 13113502312
Ref: 核心与内置函数<70>-Footnote-13503680
Ref: 核心与内置函数<70>-Footnote-23503723
Ref: 核心与内置函数<70>-Footnote-33503772
Ref: 核心与内置函数<70>-Footnote-43503815
Ref: 核心与内置函数<70>-Footnote-53503858
Ref: 核心与内置函数<70>-Footnote-63503907
Ref: 核心与内置函数<70>-Footnote-73503950
Ref: 核心与内置函数<70>-Footnote-83503993
Ref: 核心与内置函数<70>-Footnote-93504036
Ref: 核心与内置函数<70>-Footnote-103504079
Ref: 核心与内置函数<70>-Footnote-113504123
Node: 库<86>3504167
Ref: whatsnew/changelog id5523504284
Ref: 13123504284
Ref: 库<86>-Footnote-13510986
Ref: 库<86>-Footnote-23511029
Ref: 库<86>-Footnote-33511072
Ref: 库<86>-Footnote-43511114
Ref: 库<86>-Footnote-53511157
Ref: 库<86>-Footnote-63511200
Ref: 库<86>-Footnote-73511242
Ref: 库<86>-Footnote-83511285
Ref: 库<86>-Footnote-93511328
Ref: 库<86>-Footnote-103511371
Ref: 库<86>-Footnote-113511415
Ref: 库<86>-Footnote-123511459
Ref: 库<86>-Footnote-133511503
Ref: 库<86>-Footnote-143511547
Ref: 库<86>-Footnote-153511591
Ref: 库<86>-Footnote-163511635
Ref: 库<86>-Footnote-173511679
Ref: 库<86>-Footnote-183511723
Ref: 库<86>-Footnote-193511767
Ref: 库<86>-Footnote-203511811
Ref: 库<86>-Footnote-213511855
Ref: 库<86>-Footnote-223511899
Ref: 库<86>-Footnote-233511943
Ref: 库<86>-Footnote-243511987
Ref: 库<86>-Footnote-253512031
Ref: 库<86>-Footnote-263512075
Ref: 库<86>-Footnote-273512119
Ref: 库<86>-Footnote-283512163
Ref: 库<86>-Footnote-293512207
Ref: 库<86>-Footnote-303512251
Ref: 库<86>-Footnote-313512294
Ref: 库<86>-Footnote-323512338
Ref: 库<86>-Footnote-333512382
Ref: 库<86>-Footnote-343512426
Ref: 库<86>-Footnote-353512470
Ref: 库<86>-Footnote-363512514
Ref: 库<86>-Footnote-373512558
Ref: 库<86>-Footnote-383512602
Ref: 库<86>-Footnote-393512646
Ref: 库<86>-Footnote-403512690
Ref: 库<86>-Footnote-413512734
Ref: 库<86>-Footnote-423512778
Ref: 库<86>-Footnote-433512828
Ref: 库<86>-Footnote-443512872
Ref: 库<86>-Footnote-453512916
Ref: 库<86>-Footnote-463512960
Ref: 库<86>-Footnote-473513004
Ref: 库<86>-Footnote-483513048
Node: 构建<59>3513092
Ref: whatsnew/changelog id5533513194
Ref: 13133513194
Ref: 构建<59>-Footnote-13513469
Ref: 构建<59>-Footnote-23513512
Node: 测试<56>3513555
Ref: whatsnew/changelog id5543513667
Ref: 13143513667
Ref: 测试<56>-Footnote-13513966
Ref: 测试<56>-Footnote-23514009
Node: 工具/示例<33>3514052
Ref: whatsnew/changelog id5553514163
Ref: 13153514163
Ref: 工具/示例<33>-Footnote-13515191
Ref: 工具/示例<33>-Footnote-23515234
Ref: 工具/示例<33>-Footnote-33515277
Ref: 工具/示例<33>-Footnote-43515320
Ref: 工具/示例<33>-Footnote-53515363
Ref: 工具/示例<33>-Footnote-63515406
Node: C API<41>3515449
Ref: whatsnew/changelog id5563515541
Ref: 13163515541
Ref: C API<41>-Footnote-13515694
Node: Python 3 5 0 alpha 33515737
Ref: whatsnew/changelog python-3-5-0-alpha-33515879
Ref: 13173515879
Node: 核心与内置函数<71>3516124
Ref: whatsnew/changelog id5573516222
Ref: 13183516222
Ref: 核心与内置函数<71>-Footnote-13517017
Ref: 核心与内置函数<71>-Footnote-23517060
Ref: 核心与内置函数<71>-Footnote-33517103
Ref: 核心与内置函数<71>-Footnote-43517146
Ref: 核心与内置函数<71>-Footnote-53517189
Ref: 核心与内置函数<71>-Footnote-63517232
Node: 库<87>3517275
Ref: whatsnew/changelog id5583517392
Ref: 13193517392
Ref: 库<87>-Footnote-13523797
Ref: 库<87>-Footnote-23523840
Ref: 库<87>-Footnote-33523883
Ref: 库<87>-Footnote-43523926
Ref: 库<87>-Footnote-53523969
Ref: 库<87>-Footnote-63524012
Ref: 库<87>-Footnote-73524055
Ref: 库<87>-Footnote-83524098
Ref: 库<87>-Footnote-93524141
Ref: 库<87>-Footnote-103524184
Ref: 库<87>-Footnote-113524228
Ref: 库<87>-Footnote-123524272
Ref: 库<87>-Footnote-133524316
Ref: 库<87>-Footnote-143524360
Ref: 库<87>-Footnote-153524403
Ref: 库<87>-Footnote-163524447
Ref: 库<87>-Footnote-173524491
Ref: 库<87>-Footnote-183524535
Ref: 库<87>-Footnote-193524579
Ref: 库<87>-Footnote-203524623
Ref: 库<87>-Footnote-213524667
Ref: 库<87>-Footnote-223524711
Ref: 库<87>-Footnote-233524755
Ref: 库<87>-Footnote-243524799
Ref: 库<87>-Footnote-253524843
Ref: 库<87>-Footnote-263524887
Ref: 库<87>-Footnote-273524931
Ref: 库<87>-Footnote-283524975
Ref: 库<87>-Footnote-293525019
Ref: 库<87>-Footnote-303525063
Ref: 库<87>-Footnote-313525106
Ref: 库<87>-Footnote-323525150
Ref: 库<87>-Footnote-333525194
Ref: 库<87>-Footnote-343525238
Ref: 库<87>-Footnote-353525281
Ref: 库<87>-Footnote-363525325
Ref: 库<87>-Footnote-373525369
Ref: 库<87>-Footnote-383525413
Ref: 库<87>-Footnote-393525457
Ref: 库<87>-Footnote-403525501
Ref: 库<87>-Footnote-413525545
Ref: 库<87>-Footnote-423525589
Node: 构建<60>3525633
Ref: whatsnew/changelog id5593525735
Ref: 131a3525735
Ref: 构建<60>-Footnote-13525878
Node: 测试<57>3525921
Ref: whatsnew/changelog id5603526033
Ref: 131b3526033
Ref: 测试<57>-Footnote-13526256
Ref: 测试<57>-Footnote-23526299
Node: 工具/示例<34>3526342
Ref: whatsnew/changelog id5613526435
Ref: 131c3526435
Ref: 工具/示例<34>-Footnote-13526702
Node: Python 3 5 0 alpha 23526745
Ref: whatsnew/changelog python-3-5-0-alpha-23526887
Ref: 131d3526887
Node: 核心与内置函数<72>3527118
Ref: whatsnew/changelog id5623527216
Ref: 131e3527216
Ref: 核心与内置函数<72>-Footnote-13527513
Node: 库<88>3527556
Ref: whatsnew/changelog id5633527673
Ref: 131f3527673
Ref: 库<88>-Footnote-13531975
Ref: 库<88>-Footnote-23532018
Ref: 库<88>-Footnote-33532067
Ref: 库<88>-Footnote-43532110
Ref: 库<88>-Footnote-53532153
Ref: 库<88>-Footnote-63532196
Ref: 库<88>-Footnote-73532239
Ref: 库<88>-Footnote-83532282
Ref: 库<88>-Footnote-93532325
Ref: 库<88>-Footnote-103532367
Ref: 库<88>-Footnote-113532411
Ref: 库<88>-Footnote-123532455
Ref: 库<88>-Footnote-133532499
Ref: 库<88>-Footnote-143532543
Ref: 库<88>-Footnote-153532587
Ref: 库<88>-Footnote-163532631
Ref: 库<88>-Footnote-173532674
Ref: 库<88>-Footnote-183532719
Ref: 库<88>-Footnote-193532762
Ref: 库<88>-Footnote-203532806
Ref: 库<88>-Footnote-213532849
Ref: 库<88>-Footnote-223532893
Ref: 库<88>-Footnote-233532937
Ref: 库<88>-Footnote-243532981
Ref: 库<88>-Footnote-253533025
Ref: 库<88>-Footnote-263533069
Ref: 库<88>-Footnote-273533113
Ref: 库<88>-Footnote-283533157
Ref: 库<88>-Footnote-293533201
Ref: 库<88>-Footnote-303533245
Ref: 库<88>-Footnote-313533289
Ref: 库<88>-Footnote-323533333
Ref: 库<88>-Footnote-333533377
Ref: 库<88>-Footnote-343533421
Ref: 库<88>-Footnote-353533465
Ref: 库<88>-Footnote-363533509
Ref: 库<88>-Footnote-373533553
Node: 构建<61>3533597
Ref: whatsnew/changelog id5643533698
Ref: 13203533698
Ref: 构建<61>-Footnote-13533955
Ref: 构建<61>-Footnote-23533998
Node: C API<42>3534041
Ref: whatsnew/changelog id5653534146
Ref: 13213534146
Ref: C API<42>-Footnote-13534326
Node: Windows<53>3534369
Ref: whatsnew/changelog id5663534455
Ref: 13223534455
Ref: Windows<53>-Footnote-13534750
Ref: Windows<53>-Footnote-23534793
Ref: Windows<53>-Footnote-33534842
Node: Python 3 5 0 alpha 13534885
Ref: whatsnew/changelog python-3-5-0-alpha-13534998
Ref: 13233534998
Node: 核心与内置函数<73>3535327
Ref: whatsnew/changelog id5673535425
Ref: 13243535425
Ref: 核心与内置函数<73>-Footnote-13545317
Ref: 核心与内置函数<73>-Footnote-23545360
Ref: 核心与内置函数<73>-Footnote-33545403
Ref: 核心与内置函数<73>-Footnote-43545446
Ref: 核心与内置函数<73>-Footnote-53545489
Ref: 核心与内置函数<73>-Footnote-63545532
Ref: 核心与内置函数<73>-Footnote-73545575
Ref: 核心与内置函数<73>-Footnote-83545618
Ref: 核心与内置函数<73>-Footnote-93545661
Ref: 核心与内置函数<73>-Footnote-103545704
Ref: 核心与内置函数<73>-Footnote-113545748
Ref: 核心与内置函数<73>-Footnote-123545792
Ref: 核心与内置函数<73>-Footnote-133545836
Ref: 核心与内置函数<73>-Footnote-143545880
Ref: 核心与内置函数<73>-Footnote-153545924
Ref: 核心与内置函数<73>-Footnote-163545968
Ref: 核心与内置函数<73>-Footnote-173546012
Ref: 核心与内置函数<73>-Footnote-183546056
Ref: 核心与内置函数<73>-Footnote-193546100
Ref: 核心与内置函数<73>-Footnote-203546144
Ref: 核心与内置函数<73>-Footnote-213546188
Ref: 核心与内置函数<73>-Footnote-223546232
Ref: 核心与内置函数<73>-Footnote-233546276
Ref: 核心与内置函数<73>-Footnote-243546320
Ref: 核心与内置函数<73>-Footnote-253546364
Ref: 核心与内置函数<73>-Footnote-263546408
Ref: 核心与内置函数<73>-Footnote-273546452
Ref: 核心与内置函数<73>-Footnote-283546496
Ref: 核心与内置函数<73>-Footnote-293546540
Ref: 核心与内置函数<73>-Footnote-303546584
Ref: 核心与内置函数<73>-Footnote-313546628
Ref: 核心与内置函数<73>-Footnote-323546672
Ref: 核心与内置函数<73>-Footnote-333546716
Ref: 核心与内置函数<73>-Footnote-343546762
Ref: 核心与内置函数<73>-Footnote-353546806
Ref: 核心与内置函数<73>-Footnote-363546850
Ref: 核心与内置函数<73>-Footnote-373546894
Ref: 核心与内置函数<73>-Footnote-383546938
Ref: 核心与内置函数<73>-Footnote-393546982
Ref: 核心与内置函数<73>-Footnote-403547026
Ref: 核心与内置函数<73>-Footnote-413547070
Ref: 核心与内置函数<73>-Footnote-423547114
Ref: 核心与内置函数<73>-Footnote-433547158
Ref: 核心与内置函数<73>-Footnote-443547202
Ref: 核心与内置函数<73>-Footnote-453547246
Ref: 核心与内置函数<73>-Footnote-463547290
Ref: 核心与内置函数<73>-Footnote-473547334
Ref: 核心与内置函数<73>-Footnote-483547378
Ref: 核心与内置函数<73>-Footnote-493547422
Ref: 核心与内置函数<73>-Footnote-503547466
Ref: 核心与内置函数<73>-Footnote-513547510
Ref: 核心与内置函数<73>-Footnote-523547554
Ref: 核心与内置函数<73>-Footnote-533547598
Ref: 核心与内置函数<73>-Footnote-543547642
Ref: 核心与内置函数<73>-Footnote-553547686
Ref: 核心与内置函数<73>-Footnote-563547730
Ref: 核心与内置函数<73>-Footnote-573547774
Ref: 核心与内置函数<73>-Footnote-583547818
Ref: 核心与内置函数<73>-Footnote-593547862
Ref: 核心与内置函数<73>-Footnote-603547906
Ref: 核心与内置函数<73>-Footnote-613547950
Ref: 核心与内置函数<73>-Footnote-623547994
Ref: 核心与内置函数<73>-Footnote-633548038
Ref: 核心与内置函数<73>-Footnote-643548082
Ref: 核心与内置函数<73>-Footnote-653548126
Ref: 核心与内置函数<73>-Footnote-663548170
Ref: 核心与内置函数<73>-Footnote-673548213
Ref: 核心与内置函数<73>-Footnote-683548257
Ref: 核心与内置函数<73>-Footnote-693548301
Ref: 核心与内置函数<73>-Footnote-703548345
Ref: 核心与内置函数<73>-Footnote-713548389
Ref: 核心与内置函数<73>-Footnote-723548433
Ref: 核心与内置函数<73>-Footnote-733548476
Node: 库<89>3548520
Ref: whatsnew/changelog id5683548635
Ref: 13253548635
Ref: 库<89>-Footnote-13601009
Ref: 库<89>-Footnote-23601052
Ref: 库<89>-Footnote-33601095
Ref: 库<89>-Footnote-43601138
Ref: 库<89>-Footnote-53601181
Ref: 库<89>-Footnote-63601224
Ref: 库<89>-Footnote-73601267
Ref: 库<89>-Footnote-83601310
Ref: 库<89>-Footnote-93601353
Ref: 库<89>-Footnote-103601396
Ref: 库<89>-Footnote-113601440
Ref: 库<89>-Footnote-123601484
Ref: 库<89>-Footnote-133601528
Ref: 库<89>-Footnote-143601572
Ref: 库<89>-Footnote-153601616
Ref: 库<89>-Footnote-163601660
Ref: 库<89>-Footnote-173601704
Ref: 库<89>-Footnote-183601748
Ref: 库<89>-Footnote-193601792
Ref: 库<89>-Footnote-203601836
Ref: 库<89>-Footnote-213601880
Ref: 库<89>-Footnote-223601924
Ref: 库<89>-Footnote-233601968
Ref: 库<89>-Footnote-243602012
Ref: 库<89>-Footnote-253602056
Ref: 库<89>-Footnote-263602100
Ref: 库<89>-Footnote-273602144
Ref: 库<89>-Footnote-283602188
Ref: 库<89>-Footnote-293602232
Ref: 库<89>-Footnote-303602276
Ref: 库<89>-Footnote-313602320
Ref: 库<89>-Footnote-323602364
Ref: 库<89>-Footnote-333602408
Ref: 库<89>-Footnote-343602452
Ref: 库<89>-Footnote-353602496
Ref: 库<89>-Footnote-363602540
Ref: 库<89>-Footnote-373602584
Ref: 库<89>-Footnote-383602628
Ref: 库<89>-Footnote-393602672
Ref: 库<89>-Footnote-403602716
Ref: 库<89>-Footnote-413602760
Ref: 库<89>-Footnote-423602804
Ref: 库<89>-Footnote-433602848
Ref: 库<89>-Footnote-443602892
Ref: 库<89>-Footnote-453602936
Ref: 库<89>-Footnote-463602980
Ref: 库<89>-Footnote-473603024
Ref: 库<89>-Footnote-483603068
Ref: 库<89>-Footnote-493603112
Ref: 库<89>-Footnote-503603156
Ref: 库<89>-Footnote-513603200
Ref: 库<89>-Footnote-523603244
Ref: 库<89>-Footnote-533603288
Ref: 库<89>-Footnote-543603332
Ref: 库<89>-Footnote-553603376
Ref: 库<89>-Footnote-563603422
Ref: 库<89>-Footnote-573603466
Ref: 库<89>-Footnote-583603510
Ref: 库<89>-Footnote-593603554
Ref: 库<89>-Footnote-603603598
Ref: 库<89>-Footnote-613603642
Ref: 库<89>-Footnote-623603686
Ref: 库<89>-Footnote-633603730
Ref: 库<89>-Footnote-643603774
Ref: 库<89>-Footnote-653603818
Ref: 库<89>-Footnote-663603862
Ref: 库<89>-Footnote-673603906
Ref: 库<89>-Footnote-683603950
Ref: 库<89>-Footnote-693603994
Ref: 库<89>-Footnote-703604038
Ref: 库<89>-Footnote-713604082
Ref: 库<89>-Footnote-723604126
Ref: 库<89>-Footnote-733604170
Ref: 库<89>-Footnote-743604214
Ref: 库<89>-Footnote-753604258
Ref: 库<89>-Footnote-763604302
Ref: 库<89>-Footnote-773604346
Ref: 库<89>-Footnote-783604390
Ref: 库<89>-Footnote-793604434
Ref: 库<89>-Footnote-803604478
Ref: 库<89>-Footnote-813604522
Ref: 库<89>-Footnote-823604566
Ref: 库<89>-Footnote-833604610
Ref: 库<89>-Footnote-843604654
Ref: 库<89>-Footnote-853604698
Ref: 库<89>-Footnote-863604742
Ref: 库<89>-Footnote-873604786
Ref: 库<89>-Footnote-883604830
Ref: 库<89>-Footnote-893604874
Ref: 库<89>-Footnote-903604918
Ref: 库<89>-Footnote-913604962
Ref: 库<89>-Footnote-923605006
Ref: 库<89>-Footnote-933605050
Ref: 库<89>-Footnote-943605094
Ref: 库<89>-Footnote-953605138
Ref: 库<89>-Footnote-963605181
Ref: 库<89>-Footnote-973605225
Ref: 库<89>-Footnote-983605269
Ref: 库<89>-Footnote-993605313
Ref: 库<89>-Footnote-1003605356
Ref: 库<89>-Footnote-1013605401
Ref: 库<89>-Footnote-1023605446
Ref: 库<89>-Footnote-1033605491
Ref: 库<89>-Footnote-1043605536
Ref: 库<89>-Footnote-1053605581
Ref: 库<89>-Footnote-1063605626
Ref: 库<89>-Footnote-1073605670
Ref: 库<89>-Footnote-1083605714
Ref: 库<89>-Footnote-1093605759
Ref: 库<89>-Footnote-1103605804
Ref: 库<89>-Footnote-1113605849
Ref: 库<89>-Footnote-1123605894
Ref: 库<89>-Footnote-1133605939
Ref: 库<89>-Footnote-1143605984
Ref: 库<89>-Footnote-1153606029
Ref: 库<89>-Footnote-1163606074
Ref: 库<89>-Footnote-1173606119
Ref: 库<89>-Footnote-1183606164
Ref: 库<89>-Footnote-1193606209
Ref: 库<89>-Footnote-1203606254
Ref: 库<89>-Footnote-1213606301
Ref: 库<89>-Footnote-1223606346
Ref: 库<89>-Footnote-1233606391
Ref: 库<89>-Footnote-1243606436
Ref: 库<89>-Footnote-1253606481
Ref: 库<89>-Footnote-1263606526
Ref: 库<89>-Footnote-1273606571
Ref: 库<89>-Footnote-1283606616
Ref: 库<89>-Footnote-1293606661
Ref: 库<89>-Footnote-1303606706
Ref: 库<89>-Footnote-1313606751
Ref: 库<89>-Footnote-1323606796
Ref: 库<89>-Footnote-1333606841
Ref: 库<89>-Footnote-1343606886
Ref: 库<89>-Footnote-1353606931
Ref: 库<89>-Footnote-1363606976
Ref: 库<89>-Footnote-1373607021
Ref: 库<89>-Footnote-1383607066
Ref: 库<89>-Footnote-1393607111
Ref: 库<89>-Footnote-1403607156
Ref: 库<89>-Footnote-1413607201
Ref: 库<89>-Footnote-1423607245
Ref: 库<89>-Footnote-1433607289
Ref: 库<89>-Footnote-1443607334
Ref: 库<89>-Footnote-1453607379
Ref: 库<89>-Footnote-1463607424
Ref: 库<89>-Footnote-1473607469
Ref: 库<89>-Footnote-1483607514
Ref: 库<89>-Footnote-1493607559
Ref: 库<89>-Footnote-1503607604
Ref: 库<89>-Footnote-1513607649
Ref: 库<89>-Footnote-1523607694
Ref: 库<89>-Footnote-1533607739
Ref: 库<89>-Footnote-1543607784
Ref: 库<89>-Footnote-1553607829
Ref: 库<89>-Footnote-1563607874
Ref: 库<89>-Footnote-1573607918
Ref: 库<89>-Footnote-1583607963
Ref: 库<89>-Footnote-1593608008
Ref: 库<89>-Footnote-1603608053
Ref: 库<89>-Footnote-1613608098
Ref: 库<89>-Footnote-1623608143
Ref: 库<89>-Footnote-1633608188
Ref: 库<89>-Footnote-1643608233
Ref: 库<89>-Footnote-1653608278
Ref: 库<89>-Footnote-1663608323
Ref: 库<89>-Footnote-1673608368
Ref: 库<89>-Footnote-1683608413
Ref: 库<89>-Footnote-1693608458
Ref: 库<89>-Footnote-1703608503
Ref: 库<89>-Footnote-1713608548
Ref: 库<89>-Footnote-1723608593
Ref: 库<89>-Footnote-1733608638
Ref: 库<89>-Footnote-1743608683
Ref: 库<89>-Footnote-1753608728
Ref: 库<89>-Footnote-1763608773
Ref: 库<89>-Footnote-1773608818
Ref: 库<89>-Footnote-1783608863
Ref: 库<89>-Footnote-1793608908
Ref: 库<89>-Footnote-1803608953
Ref: 库<89>-Footnote-1813608998
Ref: 库<89>-Footnote-1823609043
Ref: 库<89>-Footnote-1833609088
Ref: 库<89>-Footnote-1843609133
Ref: 库<89>-Footnote-1853609178
Ref: 库<89>-Footnote-1863609223
Ref: 库<89>-Footnote-1873609268
Ref: 库<89>-Footnote-1883609312
Ref: 库<89>-Footnote-1893609357
Ref: 库<89>-Footnote-1903609402
Ref: 库<89>-Footnote-1913609447
Ref: 库<89>-Footnote-1923609492
Ref: 库<89>-Footnote-1933609537
Ref: 库<89>-Footnote-1943609582
Ref: 库<89>-Footnote-1953609627
Ref: 库<89>-Footnote-1963609671
Ref: 库<89>-Footnote-1973609716
Ref: 库<89>-Footnote-1983609761
Ref: 库<89>-Footnote-1993609806
Ref: 库<89>-Footnote-2003609851
Ref: 库<89>-Footnote-2013609896
Ref: 库<89>-Footnote-2023609941
Ref: 库<89>-Footnote-2033609985
Ref: 库<89>-Footnote-2043610030
Ref: 库<89>-Footnote-2053610075
Ref: 库<89>-Footnote-2063610120
Ref: 库<89>-Footnote-2073610165
Ref: 库<89>-Footnote-2083610210
Ref: 库<89>-Footnote-2093610255
Ref: 库<89>-Footnote-2103610300
Ref: 库<89>-Footnote-2113610345
Ref: 库<89>-Footnote-2123610390
Ref: 库<89>-Footnote-2133610435
Ref: 库<89>-Footnote-2143610480
Ref: 库<89>-Footnote-2153610525
Ref: 库<89>-Footnote-2163610570
Ref: 库<89>-Footnote-2173610615
Ref: 库<89>-Footnote-2183610660
Ref: 库<89>-Footnote-2193610705
Ref: 库<89>-Footnote-2203610750
Ref: 库<89>-Footnote-2213610795
Ref: 库<89>-Footnote-2223610840
Ref: 库<89>-Footnote-2233610885
Ref: 库<89>-Footnote-2243610929
Ref: 库<89>-Footnote-2253610973
Ref: 库<89>-Footnote-2263611018
Ref: 库<89>-Footnote-2273611063
Ref: 库<89>-Footnote-2283611108
Ref: 库<89>-Footnote-2293611153
Ref: 库<89>-Footnote-2303611198
Ref: 库<89>-Footnote-2313611243
Ref: 库<89>-Footnote-2323611288
Ref: 库<89>-Footnote-2333611333
Ref: 库<89>-Footnote-2343611378
Ref: 库<89>-Footnote-2353611423
Ref: 库<89>-Footnote-2363611468
Ref: 库<89>-Footnote-2373611513
Ref: 库<89>-Footnote-2383611558
Ref: 库<89>-Footnote-2393611603
Ref: 库<89>-Footnote-2403611648
Ref: 库<89>-Footnote-2413611693
Ref: 库<89>-Footnote-2423611738
Ref: 库<89>-Footnote-2433611783
Ref: 库<89>-Footnote-2443611828
Ref: 库<89>-Footnote-2453611872
Ref: 库<89>-Footnote-2463611917
Ref: 库<89>-Footnote-2473611962
Ref: 库<89>-Footnote-2483612007
Ref: 库<89>-Footnote-2493612052
Ref: 库<89>-Footnote-2503612097
Ref: 库<89>-Footnote-2513612142
Ref: 库<89>-Footnote-2523612187
Ref: 库<89>-Footnote-2533612232
Ref: 库<89>-Footnote-2543612277
Ref: 库<89>-Footnote-2553612322
Ref: 库<89>-Footnote-2563612367
Ref: 库<89>-Footnote-2573612412
Ref: 库<89>-Footnote-2583612457
Ref: 库<89>-Footnote-2593612502
Ref: 库<89>-Footnote-2603612547
Ref: 库<89>-Footnote-2613612592
Ref: 库<89>-Footnote-2623612637
Ref: 库<89>-Footnote-2633612682
Ref: 库<89>-Footnote-2643612727
Ref: 库<89>-Footnote-2653612772
Ref: 库<89>-Footnote-2663612817
Ref: 库<89>-Footnote-2673612862
Ref: 库<89>-Footnote-2683612907
Ref: 库<89>-Footnote-2693612952
Ref: 库<89>-Footnote-2703612997
Ref: 库<89>-Footnote-2713613042
Ref: 库<89>-Footnote-2723613087
Ref: 库<89>-Footnote-2733613132
Ref: 库<89>-Footnote-2743613177
Ref: 库<89>-Footnote-2753613222
Ref: 库<89>-Footnote-2763613267
Ref: 库<89>-Footnote-2773613311
Ref: 库<89>-Footnote-2783613356
Ref: 库<89>-Footnote-2793613401
Ref: 库<89>-Footnote-2803613446
Ref: 库<89>-Footnote-2813613491
Ref: 库<89>-Footnote-2823613536
Ref: 库<89>-Footnote-2833613581
Ref: 库<89>-Footnote-2843613626
Ref: 库<89>-Footnote-2853613671
Ref: 库<89>-Footnote-2863613716
Ref: 库<89>-Footnote-2873613761
Ref: 库<89>-Footnote-2883613806
Ref: 库<89>-Footnote-2893613857
Ref: 库<89>-Footnote-2903613902
Ref: 库<89>-Footnote-2913613947
Ref: 库<89>-Footnote-2923613992
Ref: 库<89>-Footnote-2933614037
Ref: 库<89>-Footnote-2943614082
Ref: 库<89>-Footnote-2953614127
Ref: 库<89>-Footnote-2963614172
Ref: 库<89>-Footnote-2973614217
Ref: 库<89>-Footnote-2983614262
Ref: 库<89>-Footnote-2993614307
Ref: 库<89>-Footnote-3003614352
Ref: 库<89>-Footnote-3013614397
Ref: 库<89>-Footnote-3023614442
Ref: 库<89>-Footnote-3033614487
Ref: 库<89>-Footnote-3043614532
Ref: 库<89>-Footnote-3053614577
Ref: 库<89>-Footnote-3063614622
Ref: 库<89>-Footnote-3073614667
Ref: 库<89>-Footnote-3083614712
Ref: 库<89>-Footnote-3093614757
Ref: 库<89>-Footnote-3103614802
Ref: 库<89>-Footnote-3113614847
Ref: 库<89>-Footnote-3123614892
Ref: 库<89>-Footnote-3133614937
Ref: 库<89>-Footnote-3143614982
Ref: 库<89>-Footnote-3153615026
Ref: 库<89>-Footnote-3163615071
Ref: 库<89>-Footnote-3173615116
Ref: 库<89>-Footnote-3183615161
Ref: 库<89>-Footnote-3193615206
Ref: 库<89>-Footnote-3203615251
Ref: 库<89>-Footnote-3213615296
Ref: 库<89>-Footnote-3223615341
Ref: 库<89>-Footnote-3233615386
Ref: 库<89>-Footnote-3243615431
Ref: 库<89>-Footnote-3253615476
Ref: 库<89>-Footnote-3263615521
Ref: 库<89>-Footnote-3273615566
Ref: 库<89>-Footnote-3283615611
Ref: 库<89>-Footnote-3293615656
Ref: 库<89>-Footnote-3303615701
Ref: 库<89>-Footnote-3313615746
Ref: 库<89>-Footnote-3323615791
Ref: 库<89>-Footnote-3333615836
Ref: 库<89>-Footnote-3343615881
Ref: 库<89>-Footnote-3353615925
Ref: 库<89>-Footnote-3363615970
Ref: 库<89>-Footnote-3373616015
Ref: 库<89>-Footnote-3383616060
Ref: 库<89>-Footnote-3393616105
Ref: 库<89>-Footnote-3403616150
Ref: 库<89>-Footnote-3413616195
Ref: 库<89>-Footnote-3423616240
Ref: 库<89>-Footnote-3433616285
Ref: 库<89>-Footnote-3443616330
Ref: 库<89>-Footnote-3453616375
Ref: 库<89>-Footnote-3463616420
Ref: 库<89>-Footnote-3473616465
Ref: 库<89>-Footnote-3483616510
Ref: 库<89>-Footnote-3493616555
Ref: 库<89>-Footnote-3503616600
Ref: 库<89>-Footnote-3513616645
Ref: 库<89>-Footnote-3523616690
Ref: 库<89>-Footnote-3533616735
Ref: 库<89>-Footnote-3543616780
Ref: 库<89>-Footnote-3553616825
Ref: 库<89>-Footnote-3563616870
Ref: 库<89>-Footnote-3573616915
Ref: 库<89>-Footnote-3583616960
Ref: 库<89>-Footnote-3593617005
Ref: 库<89>-Footnote-3603617050
Ref: 库<89>-Footnote-3613617095
Ref: 库<89>-Footnote-3623617140
Ref: 库<89>-Footnote-3633617185
Ref: 库<89>-Footnote-3643617230
Ref: 库<89>-Footnote-3653617275
Ref: 库<89>-Footnote-3663617320
Ref: 库<89>-Footnote-3673617365
Ref: 库<89>-Footnote-3683617410
Ref: 库<89>-Footnote-3693617455
Ref: 库<89>-Footnote-3703617500
Ref: 库<89>-Footnote-3713617544
Ref: 库<89>-Footnote-3723617589
Ref: 库<89>-Footnote-3733617634
Ref: 库<89>-Footnote-3743617679
Ref: 库<89>-Footnote-3753617724
Ref: 库<89>-Footnote-3763617769
Ref: 库<89>-Footnote-3773617814
Ref: 库<89>-Footnote-3783617859
Ref: 库<89>-Footnote-3793617904
Ref: 库<89>-Footnote-3803617949
Ref: 库<89>-Footnote-3813617994
Ref: 库<89>-Footnote-3823618039
Ref: 库<89>-Footnote-3833618084
Ref: 库<89>-Footnote-3843618128
Ref: 库<89>-Footnote-3853618173
Ref: 库<89>-Footnote-3863618218
Ref: 库<89>-Footnote-3873618263
Ref: 库<89>-Footnote-3883618308
Ref: 库<89>-Footnote-3893618351
Ref: 库<89>-Footnote-3903618396
Ref: 库<89>-Footnote-3913618441
Ref: 库<89>-Footnote-3923618486
Ref: 库<89>-Footnote-3933618531
Ref: 库<89>-Footnote-3943618576
Ref: 库<89>-Footnote-3953618621
Ref: 库<89>-Footnote-3963618666
Node: IDLE<50>3618711
Ref: whatsnew/changelog id5693618811
Ref: 13263618811
Ref: IDLE<50>-Footnote-13622299
Ref: IDLE<50>-Footnote-23622342
Ref: IDLE<50>-Footnote-33622385
Ref: IDLE<50>-Footnote-43622427
Ref: IDLE<50>-Footnote-53622470
Ref: IDLE<50>-Footnote-63622512
Ref: IDLE<50>-Footnote-73622555
Ref: IDLE<50>-Footnote-83622598
Ref: IDLE<50>-Footnote-93622641
Ref: IDLE<50>-Footnote-103622684
Ref: IDLE<50>-Footnote-113622728
Ref: IDLE<50>-Footnote-123622772
Ref: IDLE<50>-Footnote-133622816
Ref: IDLE<50>-Footnote-143622860
Ref: IDLE<50>-Footnote-153622904
Ref: IDLE<50>-Footnote-163622948
Ref: IDLE<50>-Footnote-173622992
Ref: IDLE<50>-Footnote-183623036
Ref: IDLE<50>-Footnote-193623080
Ref: IDLE<50>-Footnote-203623124
Ref: IDLE<50>-Footnote-213623168
Ref: IDLE<50>-Footnote-223623212
Ref: IDLE<50>-Footnote-233623256
Ref: IDLE<50>-Footnote-243623306
Ref: IDLE<50>-Footnote-253623350
Ref: IDLE<50>-Footnote-263623394
Node: 构建<62>3623438
Ref: whatsnew/changelog id5703623540
Ref: 13273623540
Ref: 构建<62>-Footnote-13626937
Ref: 构建<62>-Footnote-23626980
Ref: 构建<62>-Footnote-33627023
Ref: 构建<62>-Footnote-43627066
Ref: 构建<62>-Footnote-53627109
Ref: 构建<62>-Footnote-63627152
Ref: 构建<62>-Footnote-73627195
Ref: 构建<62>-Footnote-83627238
Ref: 构建<62>-Footnote-93627281
Ref: 构建<62>-Footnote-103627324
Ref: 构建<62>-Footnote-113627368
Ref: 构建<62>-Footnote-123627412
Ref: 构建<62>-Footnote-133627456
Ref: 构建<62>-Footnote-143627500
Ref: 构建<62>-Footnote-153627544
Ref: 构建<62>-Footnote-163627588
Ref: 构建<62>-Footnote-173627632
Ref: 构建<62>-Footnote-183627676
Ref: 构建<62>-Footnote-193627720
Ref: 构建<62>-Footnote-203627764
Ref: 构建<62>-Footnote-213627808
Ref: 构建<62>-Footnote-223627852
Ref: 构建<62>-Footnote-233627896
Ref: 构建<62>-Footnote-243627940
Ref: 构建<62>-Footnote-253627984
Ref: 构建<62>-Footnote-263628028
Node: C API<43>3628072
Ref: whatsnew/changelog id5713628176
Ref: 13283628176
Ref: C API<43>-Footnote-13629541
Ref: C API<43>-Footnote-23629584
Ref: C API<43>-Footnote-33629627
Ref: C API<43>-Footnote-43629670
Ref: C API<43>-Footnote-53629713
Ref: C API<43>-Footnote-63629756
Ref: C API<43>-Footnote-73629799
Node: 文档<54>3629842
Ref: whatsnew/changelog id5723629946
Ref: 13293629946
Ref: 文档<54>-Footnote-13631737
Ref: 文档<54>-Footnote-23631780
Ref: 文档<54>-Footnote-33631823
Ref: 文档<54>-Footnote-43631866
Ref: 文档<54>-Footnote-53631909
Ref: 文档<54>-Footnote-63631951
Ref: 文档<54>-Footnote-73631994
Ref: 文档<54>-Footnote-83632037
Ref: 文档<54>-Footnote-93632080
Ref: 文档<54>-Footnote-103632123
Ref: 文档<54>-Footnote-113632167
Node: 测试<58>3632211
Ref: whatsnew/changelog id5733632323
Ref: 132a3632323
Ref: 测试<58>-Footnote-13636541
Ref: 测试<58>-Footnote-23636584
Ref: 测试<58>-Footnote-33636627
Ref: 测试<58>-Footnote-43636670
Ref: 测试<58>-Footnote-53636713
Ref: 测试<58>-Footnote-63636756
Ref: 测试<58>-Footnote-73636799
Ref: 测试<58>-Footnote-83636842
Ref: 测试<58>-Footnote-93636885
Ref: 测试<58>-Footnote-103636928
Ref: 测试<58>-Footnote-113636972
Ref: 测试<58>-Footnote-123637016
Ref: 测试<58>-Footnote-133637060
Ref: 测试<58>-Footnote-143637104
Ref: 测试<58>-Footnote-153637147
Ref: 测试<58>-Footnote-163637191
Ref: 测试<58>-Footnote-173637235
Ref: 测试<58>-Footnote-183637279
Ref: 测试<58>-Footnote-193637323
Ref: 测试<58>-Footnote-203637367
Ref: 测试<58>-Footnote-213637411
Ref: 测试<58>-Footnote-223637455
Ref: 测试<58>-Footnote-233637499
Ref: 测试<58>-Footnote-243637543
Ref: 测试<58>-Footnote-253637587
Ref: 测试<58>-Footnote-263637631
Ref: 测试<58>-Footnote-273637675
Ref: 测试<58>-Footnote-283637719
Ref: 测试<58>-Footnote-293637763
Ref: 测试<58>-Footnote-303637807
Ref: 测试<58>-Footnote-313637851
Ref: 测试<58>-Footnote-323637895
Ref: 测试<58>-Footnote-333637939
Ref: 测试<58>-Footnote-343637983
Ref: 测试<58>-Footnote-353638027
Ref: 测试<58>-Footnote-363638071
Ref: 测试<58>-Footnote-373638115
Node: 工具/示例<35>3638159
Ref: whatsnew/changelog id5743638272
Ref: 132b3638272
Ref: 工具/示例<35>-Footnote-13639935
Ref: 工具/示例<35>-Footnote-23639978
Ref: 工具/示例<35>-Footnote-33640021
Ref: 工具/示例<35>-Footnote-43640064
Ref: 工具/示例<35>-Footnote-53640107
Ref: 工具/示例<35>-Footnote-63640150
Ref: 工具/示例<35>-Footnote-73640193
Ref: 工具/示例<35>-Footnote-83640236
Ref: 工具/示例<35>-Footnote-93640279
Ref: 工具/示例<35>-Footnote-103640322
Ref: 工具/示例<35>-Footnote-113640366
Ref: 工具/示例<35>-Footnote-123640410
Node: Windows<54>3640454
Ref: whatsnew/changelog id5753640548
Ref: 132c3640548
Ref: Windows<54>-Footnote-13641724
Ref: Windows<54>-Footnote-23641767
Ref: Windows<54>-Footnote-33641810
Ref: Windows<54>-Footnote-43641853
Ref: Windows<54>-Footnote-53641896
Ref: Windows<54>-Footnote-63641939
Ref: Windows<54>-Footnote-73641982
Node: Python 教學3642025
Ref: tutorial/index doc3642149
Ref: 132d3642149
Ref: tutorial/index the-python-tutorial3642149
Ref: 132e3642149
Ref: tutorial/index tutorial-index3642149
Ref: 132f3642149
Node: 淺嘗滋味3644938
Ref: tutorial/appetite doc3645032
Ref: 13353645032
Ref: tutorial/appetite tut-intro3645032
Ref: 13363645032
Ref: tutorial/appetite whetting-your-appetite3645032
Ref: 13373645032
Node: 使用 Python 直譯器3649417
Ref: tutorial/interpreter doc3649552
Ref: 13383649552
Ref: tutorial/interpreter tut-using3649552
Ref: 13393649552
Ref: tutorial/interpreter using-the-python-interpreter3649552
Ref: 133a3649552
Node: 啟動直譯器3649663
Ref: tutorial/interpreter invoking-the-interpreter3649771
Ref: 133b3649771
Ref: tutorial/interpreter tut-invoking3649771
Ref: 133c3649771
Ref: 啟動直譯器-Footnote-13652471
Ref: 啟動直譯器-Footnote-23652636
Node: 傳遞引數3652697
Ref: tutorial/interpreter argument-passing3652782
Ref: 13413652782
Ref: tutorial/interpreter tut-argpassing3652782
Ref: 13423652782
Node: 互動模式3653612
Ref: tutorial/interpreter interactive-mode3653697
Ref: 13433653697
Ref: tutorial/interpreter tut-interactive3653697
Ref: 9c93653697
Node: 直譯器與它的環境3654695
Ref: tutorial/interpreter the-interpreter-and-its-environment3654803
Ref: 13453654803
Ref: tutorial/interpreter tut-interp3654803
Ref: 13463654803
Node: 原始碼的字元編碼 encoding3654942
Ref: tutorial/interpreter source-code-encoding3655036
Ref: 13473655036
Ref: tutorial/interpreter tut-source-encoding3655036
Ref: 13483655036
Node: 一個非正式的 Python 簡介3656161
Ref: tutorial/introduction doc3656308
Ref: 134a3656308
Ref: tutorial/introduction an-informal-introduction-to-python3656308
Ref: 134b3656308
Ref: tutorial/introduction tut-informal3656308
Ref: 134c3656308
Node: 把 Python 當作計算機使用3657577
Ref: tutorial/introduction tut-calculator3657717
Ref: 134f3657717
Ref: tutorial/introduction using-python-as-a-calculator3657717
Ref: 13503657717
Node: 數字 Number3658031
Ref: tutorial/introduction numbers3658135
Ref: 13513658135
Ref: tutorial/introduction tut-numbers3658135
Ref: 13523658135
Ref: 數字 Number-Footnote-13661139
Node: 字串 String3661358
Ref: tutorial/introduction strings3661487
Ref: 13543661487
Ref: tutorial/introduction tut-strings3661487
Ref: 13553661487
Ref: 字串 String-Footnote-13669347
Node: List（串列）3669608
Ref: tutorial/introduction lists3669715
Ref: 135a3669715
Ref: tutorial/introduction tut-lists3669715
Ref: 135b3669715
Node: 初探程式設計的前幾步3672339
Ref: tutorial/introduction first-steps-towards-programming3672479
Ref: 135f3672479
Ref: tutorial/introduction tut-firststeps3672479
Ref: 13603672479
Ref: 初探程式設計的前幾步-Footnote-13675395
Node: 深入了解流程控制3675490
Ref: tutorial/controlflow doc3675626
Ref: 13623675626
Ref: tutorial/controlflow more-control-flow-tools3675626
Ref: 13633675626
Ref: tutorial/controlflow tut-morecontrol3675626
Ref: 13643675626
Node: if 陳述式3676147
Ref: tutorial/controlflow if-statements3676242
Ref: 13653676242
Ref: tutorial/controlflow tut-if3676242
Ref: 13663676242
Node: for 陳述式3677043
Ref: tutorial/controlflow for-statements3677159
Ref: 13693677159
Ref: tutorial/controlflow tut-for3677159
Ref: 136a3677159
Node: range 函式3678304
Ref: tutorial/controlflow the-range-function3678464
Ref: 136b3678464
Ref: tutorial/controlflow tut-range3678464
Ref: 136c3678464
Node: 迴圈內的 break 和 continue 陳述式及 else 子句3680523
Ref: tutorial/controlflow break-and-continue-statements-and-else-clauses-on-loops3680684
Ref: 136f3680684
Ref: tutorial/controlflow tut-break3680684
Ref: 13703680684
Node: pass 陳述式3682865
Ref: tutorial/controlflow pass-statements3683035
Ref: 13723683035
Ref: tutorial/controlflow tut-pass3683035
Ref: 13733683035
Node: 定義函式 function3683717
Ref: tutorial/controlflow defining-functions3683855
Ref: 13753683855
Ref: tutorial/controlflow tut-functions3683855
Ref: 13763683855
Ref: 定義函式 function-Footnote-13688718
Node: 深入了解函式定義3688973
Ref: tutorial/controlflow more-on-defining-functions3689137
Ref: 137a3689137
Ref: tutorial/controlflow tut-defining3689137
Ref: 137b3689137
Node: 預設引數值3689700
Ref: tutorial/controlflow default-argument-values3689800
Ref: 137c3689800
Ref: tutorial/controlflow tut-defaultargs3689800
Ref: 137d3689800
Node: 關鍵字引數3691601
Ref: tutorial/controlflow keyword-arguments3691722
Ref: 137e3691722
Ref: tutorial/controlflow tut-keywordargs3691722
Ref: 137f3691722
Node: 特殊參數3695282
Ref: tutorial/controlflow special-parameters3695431
Ref: 13813695431
Node: 位置或關鍵字引數 Positional-or-Keyword Arguments3696688
Ref: tutorial/controlflow positional-or-keyword-arguments3696847
Ref: 13823696847
Node: 僅限位置參數 Positional-Only Parameters3697081
Ref: tutorial/controlflow positional-only-parameters3697293
Ref: 13833697293
Node: 僅限關鍵字引數 Keyword-Only Arguments3697870
Ref: tutorial/controlflow keyword-only-arguments3698038
Ref: 13843698038
Node: 函式範例3698307
Ref: tutorial/controlflow function-examples3698436
Ref: 13853698436
Node: 回顧3701309
Ref: tutorial/controlflow recap3701385
Ref: 13863701385
Node: 任意引數列表 Arbitrary Argument Lists3702114
Ref: tutorial/controlflow arbitrary-argument-lists3702296
Ref: 13873702296
Ref: tutorial/controlflow tut-arbitraryargs3702296
Ref: 13883702296
Node: 拆解引數列表（Unpacking Argument Lists）3703336
Ref: tutorial/controlflow tut-unpacking-arguments3703522
Ref: 13893703522
Ref: tutorial/controlflow unpacking-argument-lists3703522
Ref: 138a3703522
Node: Lambda 運算式3704773
Ref: tutorial/controlflow lambda-expressions3704956
Ref: 138b3704956
Ref: tutorial/controlflow tut-lambda3704956
Ref: 138c3704956
Node: 說明文件字串 Documentation Strings3705880
Ref: tutorial/controlflow documentation-strings3706048
Ref: 138d3706048
Ref: tutorial/controlflow tut-docstrings3706048
Ref: 13773706048
Node: 函式註釋 Function Annotations3707753
Ref: tutorial/controlflow function-annotations3707896
Ref: 138e3707896
Ref: tutorial/controlflow tut-annotations3707896
Ref: 138f3707896
Ref: 函式註釋 Function Annotations-Footnote-13709058
Ref: 函式註釋 Function Annotations-Footnote-23709107
Node: 間奏曲：程式碼風格 Coding Style3709156
Ref: tutorial/controlflow intermezzo-coding-style3709290
Ref: 13923709290
Ref: tutorial/controlflow tut-codingstyle3709290
Ref: 13933709290
Ref: 間奏曲：程式碼風格 Coding Style-Footnote-13711367
Node: 資料結構3711416
Ref: tutorial/datastructures doc3711533
Ref: 13953711533
Ref: tutorial/datastructures data-structures3711533
Ref: 13963711533
Ref: tutorial/datastructures tut-structures3711533
Ref: 136e3711533
Node: 進一步了解 List（串列）3712003
Ref: tutorial/datastructures more-on-lists3712106
Ref: 13973712106
Ref: tutorial/datastructures tut-morelists3712106
Ref: 13983712106
Ref: 進一步了解 List（串列）-Footnote-13715997
Node: 將 List 作為 Stack（堆疊）使用3716139
Ref: tutorial/datastructures tut-lists-as-stacks3716295
Ref: 13993716295
Ref: tutorial/datastructures using-lists-as-stacks3716295
Ref: 139a3716295
Node: 將 List 作為 Queue（佇列）使用3717020
Ref: tutorial/datastructures tut-lists-as-queues3717228
Ref: 139b3717228
Ref: tutorial/datastructures using-lists-as-queues3717228
Ref: 139c3717228
Node: List Comprehensions（串列綜合運算）3718366
Ref: tutorial/datastructures list-comprehensions3718564
Ref: 139d3718564
Ref: tutorial/datastructures tut-listcomps3718564
Ref: 139e3718564
Node: 巢狀的 List Comprehensions3721857
Ref: tutorial/datastructures nested-list-comprehensions3722007
Ref: 139f3722007
Node: del 陳述式3723714
Ref: tutorial/datastructures the-del-statement3723852
Ref: 13a03723852
Ref: tutorial/datastructures tut-del3723852
Ref: 13a13723852
Node: Tuples 和序列 Sequences3724689
Ref: tutorial/datastructures tuples-and-sequences3724806
Ref: 13a33724806
Ref: tutorial/datastructures tut-tuples3724806
Ref: 13803724806
Node: 集合 Sets3727841
Ref: tutorial/datastructures sets3727967
Ref: 13a53727967
Ref: tutorial/datastructures tut-sets3727967
Ref: 13a63727967
Node: 字典（Dictionary）3729710
Ref: tutorial/datastructures dictionaries3729822
Ref: 13a73729822
Ref: tutorial/datastructures tut-dictionaries3729822
Ref: 13a83729822
Node: 迴圈技巧3732632
Ref: tutorial/datastructures looping-techniques3732761
Ref: 13a93732761
Ref: tutorial/datastructures tut-loopidioms3732761
Ref: 136d3732761
Node: 深入了解條件 Condition3735233
Ref: tutorial/datastructures more-on-conditions3735376
Ref: 13aa3735376
Ref: tutorial/datastructures tut-conditions3735376
Ref: 13ab3735376
Node: 序列和其他資料類型之比較3737332
Ref: tutorial/datastructures comparing-sequences-and-other-types3737454
Ref: 13ad3737454
Ref: tutorial/datastructures tut-comparing3737454
Ref: 13ae3737454
Node: 模組 Module3738901
Ref: tutorial/modules doc3739009
Ref: 13af3739009
Ref: tutorial/modules modules3739009
Ref: 13b03739009
Ref: tutorial/modules tut-modules3739009
Ref: 13b13739009
Node: 深入了解模組3741419
Ref: tutorial/modules more-on-modules3741508
Ref: 13b23741508
Ref: tutorial/modules tut-moremodules3741508
Ref: 13b33741508
Ref: 深入了解模組-Footnote-13744652
Node: 把模組當作腳本執行3744825
Ref: tutorial/modules executing-modules-as-scripts3744937
Ref: 13b43744937
Ref: tutorial/modules tut-modulesasscripts3744937
Ref: 13b53744937
Node: 模組的搜尋路徑3745829
Ref: tutorial/modules the-module-search-path3745975
Ref: 13b63745975
Ref: tutorial/modules tut-searchpath3745975
Ref: 13b73745975
Node: 「編譯」Python 檔案3747341
Ref: tutorial/modules compiled-python-files3747451
Ref: 13b93747451
Ref: 「編譯」Python 檔案-Footnote-13749472
Node: 標準模組3749521
Ref: tutorial/modules standard-modules3749629
Ref: 13ba3749629
Ref: tutorial/modules tut-standardmodules3749629
Ref: 13b83749629
Node: dir 函式3750931
Ref: tutorial/modules the-dir-function3751035
Ref: 13bb3751035
Ref: tutorial/modules tut-dir3751035
Ref: 13bc3751035
Node: 套件 Package3755507
Ref: tutorial/modules packages3755590
Ref: 13bd3755590
Ref: tutorial/modules tut-packages3755590
Ref: 13be3755590
Node: 從套件中 import *3759589
Ref: tutorial/modules importing-from-a-package3759685
Ref: 13bf3759685
Ref: tutorial/modules tut-pkg-import-star3759685
Ref: 13c03759685
Node: 套件內引用3762193
Ref: tutorial/modules intra-package-references3762319
Ref: 13c13762319
Node: 多目錄中的套件3763290
Ref: tutorial/modules packages-in-multiple-directories3763386
Ref: 13c23763386
Node: 輸入和輸出3763872
Ref: tutorial/inputoutput doc3763983
Ref: 13c43763983
Ref: tutorial/inputoutput input-and-output3763983
Ref: 13c53763983
Ref: tutorial/inputoutput tut-io3763983
Ref: 13c63763983
Node: 更華麗的輸出格式3764252
Ref: tutorial/inputoutput fancier-output-formatting3764349
Ref: 13c73764349
Ref: tutorial/inputoutput tut-formatting3764349
Ref: 13c83764349
Node: 格式化的字串文本 Formatted String Literals3767927
Ref: tutorial/inputoutput formatted-string-literals3768070
Ref: 13ca3768070
Ref: tutorial/inputoutput tut-f-strings3768070
Ref: 13c93768070
Node: 字串的 format method3769601
Ref: tutorial/inputoutput the-string-format-method3769774
Ref: 13cb3769774
Ref: tutorial/inputoutput tut-string-format3769774
Ref: 13cc3769774
Node: 手動格式化字串3772290
Ref: tutorial/inputoutput manual-string-formatting3772440
Ref: 13cd3772440
Node: 格式化字串的舊方法3773910
Ref: tutorial/inputoutput old-string-formatting3774028
Ref: 13d23774028
Node: 讀寫檔案3774562
Ref: tutorial/inputoutput reading-and-writing-files3774659
Ref: 13d33774659
Ref: tutorial/inputoutput tut-files3774659
Ref: 13d43774659
Node: 檔案物件的 method3777544
Ref: tutorial/inputoutput methods-of-file-objects3777657
Ref: 13d53777657
Ref: tutorial/inputoutput tut-filemethods3777657
Ref: 13d63777657
Node: 使用 json 儲存結構化資料3781244
Ref: tutorial/inputoutput saving-structured-data-with-json3781357
Ref: 13d73781357
Ref: tutorial/inputoutput tut-json3781357
Ref: 13d83781357
Ref: 使用 json 儲存結構化資料-Footnote-13783976
Node: 錯誤和例外3784000
Ref: tutorial/errors doc3784115
Ref: 13da3784115
Ref: tutorial/errors errors-and-exceptions3784115
Ref: 13db3784115
Ref: tutorial/errors tut-errors3784115
Ref: 13dc3784115
Node: 語法錯誤 Syntax Error3784675
Ref: tutorial/errors syntax-errors3784777
Ref: 13dd3784777
Ref: tutorial/errors tut-syntaxerrors3784777
Ref: 13de3784777
Node: 例外 Exception3785584
Ref: tutorial/errors exceptions3785707
Ref: 13df3785707
Ref: tutorial/errors tut-exceptions3785707
Ref: 13e03785707
Node: 處理例外3787541
Ref: tutorial/errors handling-exceptions3787651
Ref: 13e13787651
Ref: tutorial/errors tut-handling3787651
Ref: 13713787651
Node: 引發例外3793396
Ref: tutorial/errors raising-exceptions3793521
Ref: 13e23793521
Ref: tutorial/errors tut-raising3793521
Ref: 13e33793521
Node: 例外鏈接 Exception Chaining3794612
Ref: tutorial/errors exception-chaining3794749
Ref: 13e43794749
Ref: tutorial/errors tut-exception-chaining3794749
Ref: 13e53794749
Node: 使用者自定的例外3796168
Ref: tutorial/errors tut-userexceptions3796311
Ref: 13e63796311
Ref: tutorial/errors user-defined-exceptions3796311
Ref: 13e73796311
Node: 定義清理動作3797125
Ref: tutorial/errors defining-clean-up-actions3797261
Ref: 13e83797261
Ref: tutorial/errors tut-cleanup3797261
Ref: 13e93797261
Node: 預定義的清理動作3800329
Ref: tutorial/errors predefined-clean-up-actions3800432
Ref: 13ea3800432
Ref: tutorial/errors tut-cleanup-with3800432
Ref: 13eb3800432
Node: Class（類別）3801400
Ref: tutorial/classes doc3801528
Ref: 13ec3801528
Ref: tutorial/classes classes3801528
Ref: 13ed3801528
Ref: tutorial/classes tut-classes3801528
Ref: 13793801528
Node: 關於名稱與物件的一段話3804079
Ref: tutorial/classes a-word-about-names-and-objects3804223
Ref: 13ef3804223
Ref: tutorial/classes tut-object3804223
Ref: 13f03804223
Node: Python 作用域 Scope 及命名空間 Namespace3805165
Ref: tutorial/classes python-scopes-and-namespaces3805330
Ref: 13f13805330
Ref: tutorial/classes tut-scopes3805330
Ref: 13f23805330
Ref: Python 作用域 Scope 及命名空間 Namespace-Footnote-13811470
Node: 作用域和命名空間的範例3811849
Ref: tutorial/classes scopes-and-namespaces-example3811967
Ref: 13f43811967
Ref: tutorial/classes tut-scopeexample3811967
Ref: 13f53811967
Node: 初見 class3813276
Ref: tutorial/classes a-first-look-at-classes3813423
Ref: 13f63813423
Ref: tutorial/classes tut-firstclasses3813423
Ref: 13943813423
Node: Class definition（類別定義）語法3813682
Ref: tutorial/classes class-definition-syntax3813792
Ref: 13f73813792
Ref: tutorial/classes tut-classdefinition3813792
Ref: 13f83813792
Node: Class 物件3815284
Ref: tutorial/classes class-objects3815415
Ref: 13f93815415
Ref: tutorial/classes tut-classobjects3815415
Ref: 13fa3815415
Node: 實例物件3817554
Ref: tutorial/classes instance-objects3817658
Ref: 13fb3817658
Ref: tutorial/classes tut-instanceobjects3817658
Ref: 13fc3817658
Node: Method 物件3819212
Ref: tutorial/classes method-objects3819325
Ref: 13fd3819325
Ref: tutorial/classes tut-methodobjects3819325
Ref: 13fe3819325
Node: Class 及實例變數3821204
Ref: tutorial/classes class-and-instance-variables3821296
Ref: 13ff3821296
Ref: tutorial/classes tut-class-and-instance-variables3821296
Ref: 14003821296
Node: 隨意的備註3823270
Ref: tutorial/classes random-remarks3823387
Ref: 14013823387
Ref: tutorial/classes tut-remarks3823387
Ref: 14023823387
Node: 繼承 Inheritance3827015
Ref: tutorial/classes inheritance3827132
Ref: 14033827132
Ref: tutorial/classes tut-inheritance3827132
Ref: 14043827132
Node: 多重繼承3829945
Ref: tutorial/classes multiple-inheritance3830012
Ref: 14053830012
Ref: tutorial/classes tut-multiple3830012
Ref: 14063830012
Node: 私有變數3831974
Ref: tutorial/classes private-variables3832088
Ref: 14073832088
Ref: tutorial/classes tut-private3832088
Ref: 13ee3832088
Node: 補充說明3834725
Ref: tutorial/classes odds-and-ends3834839
Ref: 14083834839
Ref: tutorial/classes tut-odds3834839
Ref: 14093834839
Node: 疊代器 Iterator3835914
Ref: tutorial/classes iterators3836035
Ref: 140a3836035
Ref: tutorial/classes tut-iterators3836035
Ref: 140b3836035
Node: 產生器 Generator3838334
Ref: tutorial/classes generators3838461
Ref: 140c3838461
Ref: tutorial/classes tut-generators3838461
Ref: 140d3838461
Node: 產生器運算式3839859
Ref: tutorial/classes generator-expressions3839959
Ref: 140f3839959
Ref: tutorial/classes tut-genexps3839959
Ref: 14103839959
Node: Python 標準函式庫概覽3840950
Ref: tutorial/stdlib doc3841109
Ref: 14113841109
Ref: tutorial/stdlib brief-tour-of-the-standard-library3841109
Ref: 14123841109
Ref: tutorial/stdlib tut-brieftour3841109
Ref: 14133841109
Node: 作業系統介面3841496
Ref: tutorial/stdlib operating-system-interface3841624
Ref: 14143841624
Ref: tutorial/stdlib tut-os-interface3841624
Ref: 14153841624
Node: 檔案之萬用字元 File Wildcards3842778
Ref: tutorial/stdlib file-wildcards3842930
Ref: 14163842930
Ref: tutorial/stdlib tut-file-wildcards3842930
Ref: 14173842930
Node: 命令列引數3843211
Ref: tutorial/stdlib command-line-arguments3843384
Ref: 14183843384
Ref: tutorial/stdlib tut-command-line-arguments3843384
Ref: 14193843384
Node: 錯誤輸出重新導向與程式終止3844411
Ref: tutorial/stdlib error-output-redirection-and-program-termination3844566
Ref: 141a3844566
Ref: tutorial/stdlib tut-stderr3844566
Ref: 141b3844566
Node: 字串樣式比對3845008
Ref: tutorial/stdlib string-pattern-matching3845160
Ref: 141c3845160
Ref: tutorial/stdlib tut-string-pattern-matching3845160
Ref: 141d3845160
Node: 數學相關3845799
Ref: tutorial/stdlib mathematics3845924
Ref: 141e3845924
Ref: tutorial/stdlib tut-mathematics3845924
Ref: 141f3845924
Node: 網路存取3847033
Ref: tutorial/stdlib internet-access3847155
Ref: 14203847155
Ref: tutorial/stdlib tut-internet-access3847155
Ref: 14213847155
Node: 日期與時間3848196
Ref: tutorial/stdlib dates-and-times3848318
Ref: 14223848318
Ref: tutorial/stdlib tut-dates-and-times3848318
Ref: 14233848318
Node: 資料壓縮3849085
Ref: tutorial/stdlib data-compression3849207
Ref: 14243849207
Ref: tutorial/stdlib tut-data-compression3849207
Ref: 14253849207
Node: 效能量測3849718
Ref: tutorial/stdlib performance-measurement3849837
Ref: 14263849837
Ref: tutorial/stdlib tut-performance-measurement3849837
Ref: 14273849837
Node: 品質控管3850602
Ref: tutorial/stdlib quality-control3850724
Ref: 14283850724
Ref: tutorial/stdlib tut-quality-control3850724
Ref: 14293850724
Node: 標準模組庫3852170
Ref: tutorial/stdlib batteries-included3852271
Ref: 142a3852271
Ref: tutorial/stdlib tut-batteries-included3852271
Ref: 142b3852271
Ref: 標準模組庫-Footnote-13853932
Node: Python 標準函式庫概覽——第二部份3853981
Ref: tutorial/stdlib2 doc3854144
Ref: 142c3854144
Ref: tutorial/stdlib2 brief-tour-of-the-standard-library-part-ii3854144
Ref: 142d3854144
Ref: tutorial/stdlib2 tut-brieftourtwo3854144
Ref: 142e3854144
Node: 輸出格式化 Output Formatting3854875
Ref: tutorial/stdlib2 output-formatting3855020
Ref: 142f3855020
Ref: tutorial/stdlib2 tut-output-formatting3855020
Ref: 14303855020
Node: 模板化 Templating3857128
Ref: tutorial/stdlib2 templating3857336
Ref: 14313857336
Ref: tutorial/stdlib2 tut-templating3857336
Ref: 14323857336
Node: 二進制資料記錄編排 Binary Data Record Layouts3859956
Ref: tutorial/stdlib2 tut-binary-formats3860159
Ref: 14353860159
Ref: tutorial/stdlib2 working-with-binary-data-record-layouts3860159
Ref: 14363860159
Node: 多執行緒 Multi-threading3861406
Ref: tutorial/stdlib2 multi-threading3861609
Ref: 14383861609
Ref: tutorial/stdlib2 tut-multi-threading3861609
Ref: 14393861609
Node: 日誌記錄 Logging3863594
Ref: tutorial/stdlib2 logging3863768
Ref: 143a3863768
Ref: tutorial/stdlib2 tut-logging3863768
Ref: 143b3863768
Node: 弱引用 Weak References3865031
Ref: tutorial/stdlib2 tut-weak-references3865201
Ref: 143c3865201
Ref: tutorial/stdlib2 weak-references3865201
Ref: 143d3865201
Node: 使用於 List 的工具3867015
Ref: tutorial/stdlib2 tools-for-working-with-lists3867198
Ref: 143e3867198
Ref: tutorial/stdlib2 tut-list-tools3867198
Ref: 143f3867198
Node: 十進制 Decimal 浮點數運算3869720
Ref: tutorial/stdlib2 decimal-floating-point-arithmetic3869869
Ref: 14403869869
Ref: tutorial/stdlib2 tut-decimal-fp3869869
Ref: 14413869869
Node: 虛擬環境與套件3871697
Ref: tutorial/venv doc3871865
Ref: 14423871865
Ref: tutorial/venv tut-venv3871865
Ref: 14433871865
Ref: tutorial/venv virtual-environments-and-packages3871865
Ref: 14443871865
Node: 簡介<4>3871992
Ref: tutorial/venv introduction3872086
Ref: 14453872086
Node: 建立虛擬環境3873267
Ref: tutorial/venv creating-virtual-environments3873390
Ref: 14473873390
Node: 用 pip 管理套件3875324
Ref: tutorial/venv managing-packages-with-pip3875429
Ref: 14483875429
Node: 現在可以來學習些什麼？3879148
Ref: tutorial/whatnow doc3879312
Ref: 14493879312
Ref: tutorial/whatnow tut-whatnow3879312
Ref: 144a3879312
Ref: tutorial/whatnow what-now3879312
Ref: 144b3879312
Ref: 現在可以來學習些什麼？-Footnote-13882729
Node: 互動式輸入編輯和歷史記錄替換3882900
Ref: tutorial/interactive doc3883076
Ref: 144d3883076
Ref: tutorial/interactive interactive-input-editing-and-history-substitution3883076
Ref: 144e3883076
Ref: tutorial/interactive tut-interacting3883076
Ref: 133f3883076
Ref: 互動式輸入編輯和歷史記錄替換-Footnote-13883738
Node: Tab 鍵自動完成 Tab Completion 和歷史記錄編輯 History Editing3883799
Ref: tutorial/interactive tab-completion-and-history-editing3883992
Ref: 144f3883992
Ref: tutorial/interactive tut-keybindings3883992
Ref: 14503883992
Node: 互動式直譯器的替代方案3885007
Ref: tutorial/interactive alternatives-to-the-interactive-interpreter3885200
Ref: 14513885200
Ref: tutorial/interactive tut-commentary3885200
Ref: 14523885200
Ref: 互動式直譯器的替代方案-Footnote-13886093
Ref: 互動式直譯器的替代方案-Footnote-23886122
Node: 浮點數運算：問題與限制3886167
Ref: tutorial/floatingpoint doc3886316
Ref: 14533886316
Ref: tutorial/floatingpoint bpython3886316
Ref: 14543886316
Ref: tutorial/floatingpoint floating-point-arithmetic-issues-and-limitations3886316
Ref: 14553886316
Ref: tutorial/floatingpoint tut-fp-issues3886316
Ref: 14563886316
Ref: 浮點數運算：問題與限制-Footnote-13894231
Node: 表示法誤差 Representation Error3894271
Ref: tutorial/floatingpoint representation-error3894377
Ref: 14593894377
Ref: tutorial/floatingpoint tut-fp-error3894377
Ref: 145a3894377
Node: 附錄3897619
Ref: tutorial/appendix doc3897717
Ref: 145b3897717
Ref: tutorial/appendix appendix3897717
Ref: 145c3897717
Ref: tutorial/appendix tut-appendix3897717
Ref: 145d3897717
Node: 互動模式<2>3897783
Ref: tutorial/appendix interactive-mode3897841
Ref: 145e3897841
Ref: tutorial/appendix tut-interac3897841
Ref: 13443897841
Node: 錯誤處理3897982
Ref: tutorial/appendix error-handling3898081
Ref: 145f3898081
Ref: tutorial/appendix tut-error3898081
Ref: 14603898081
Ref: 錯誤處理-Footnote-13899028
Node: 可執行的 Python 腳本3899102
Ref: tutorial/appendix executable-python-scripts3899231
Ref: 14613899231
Ref: tutorial/appendix tut-scripts3899231
Ref: 13493899231
Node: 互動式啟動檔案3900215
Ref: tutorial/appendix the-interactive-startup-file3900347
Ref: 14623900347
Ref: tutorial/appendix tut-startup3900347
Ref: 14633900347
Node: 客製化模組3901701
Ref: tutorial/appendix the-customization-modules3901798
Ref: 14643901798
Ref: tutorial/appendix tut-customize3901798
Ref: 14653901798
Node: Python 的設置與使用3902673
Ref: using/index doc3902794
Ref: 14663902794
Ref: using/index python-setup-and-usage3902794
Ref: 14673902794
Ref: using/index using-index3902794
Ref: 14683902794
Node: 命令行与环境3903173
Ref: using/cmdline doc3903290
Ref: 14693903290
Ref: using/cmdline command-line-and-environment3903290
Ref: 146a3903290
Ref: using/cmdline using-on-general3903290
Ref: 10bd3903290
Node: 命令行3903577
Ref: using/cmdline command-line3903662
Ref: 146c3903662
Ref: using/cmdline using-on-cmdline3903662
Ref: a103903662
Node: 接口选项3903994
Ref: using/cmdline interface-options3904073
Ref: 146d3904073
Ref: using/cmdline using-on-interface-options3904073
Ref: 146e3904073
Ref: using/cmdline cmdoption-c3905202
Ref: 13403905202
Ref: using/cmdline cmdoption-m3905755
Ref: 4433905755
Ref: using/cmdline cmdarg-dash3907821
Ref: 14703907821
Ref: using/cmdline cmdarg-script3908193
Ref: 14713908193
Ref: 接口选项-Footnote-13909837
Node: 通用选项3909886
Ref: using/cmdline generic-options3909986
Ref: 14723909986
Ref: using/cmdline cmdoption3910025
Ref: e513910025
Ref: using/cmdline cmdoption-h3910046
Ref: 14733910046
Ref: using/cmdline cmdoption-help3910067
Ref: e503910067
Ref: using/cmdline cmdoption-v3910139
Ref: 6c93910139
Ref: using/cmdline cmdoption-version3910160
Ref: 6c83910160
Node: 其他选项3910491
Ref: using/cmdline miscellaneous-options3910603
Ref: 14743910603
Ref: using/cmdline using-on-misc-options3910603
Ref: a113910603
Ref: using/cmdline cmdoption-b3910642
Ref: 5193910642
Ref: using/cmdline id13910963
Ref: dfe3910963
Ref: using/cmdline cmdoption-check-hash-based-pycs3911127
Ref: 14753911127
Ref: using/cmdline cmdoption-d3911823
Ref: 14763911823
Ref: using/cmdline cmdoption-e3911973
Ref: 2303911973
Ref: using/cmdline cmdoption-i3912123
Ref: ee13912123
Ref: using/cmdline id23912490
Ref: 2313912490
Ref: using/cmdline cmdoption-o3912866
Ref: 77e3912866
Ref: using/cmdline cmdoption-oo3913254
Ref: 77f3913254
Ref: using/cmdline cmdoption-q3913564
Ref: 14793913564
Ref: using/cmdline cmdoption-r3913677
Ref: 11c93913677
Ref: using/cmdline cmdoption-s3914633
Ref: ddb3914633
Ref: using/cmdline id33914834
Ref: bf73914834
Ref: using/cmdline cmdoption-u3915121
Ref: 109d3915121
Ref: using/cmdline id43915362
Ref: e4d3915362
Ref: using/cmdline using-on-warnings3915714
Ref: 147d3915714
Ref: using/cmdline cmdoption-w3915714
Ref: 15b3915714
Ref: using/cmdline cmdoption-x3917241
Ref: 147f3917241
Ref: using/cmdline id53917390
Ref: 2903917390
Ref: 其他选项-Footnote-13920227
Ref: 其他选项-Footnote-23920276
Ref: 其他选项-Footnote-33920325
Ref: 其他选项-Footnote-43920374
Ref: 其他选项-Footnote-53920423
Ref: 其他选项-Footnote-63920472
Node: 不应当使用的选项3920521
Ref: using/cmdline options-you-shouldn-t-use3920612
Ref: 14833920612
Ref: using/cmdline cmdoption-j3920671
Ref: dfd3920671
Ref: 不应当使用的选项-Footnote-13920765
Node: 环境变量3920796
Ref: using/cmdline environment-variables3920881
Ref: 14843920881
Ref: using/cmdline using-on-envvars3920881
Ref: 14853920881
Ref: using/cmdline envvar-PYTHONHOME3921118
Ref: 5d03921118
Ref: using/cmdline envvar-PYTHONPATH3921678
Ref: a343921678
Ref: using/cmdline envvar-PYTHONPLATLIBDIR3922647
Ref: 102c3922647
Ref: using/cmdline envvar-PYTHONSTARTUP3922796
Ref: 9cb3922796
Ref: using/cmdline envvar-PYTHONOPTIMIZE3923407
Ref: 14783923407
Ref: using/cmdline envvar-PYTHONBREAKPOINT3923618
Ref: 4243923618
Ref: using/cmdline envvar-PYTHONDEBUG3924211
Ref: 14773924211
Ref: using/cmdline envvar-PYTHONOLDPARSER3924427
Ref: 14803924427
Ref: using/cmdline envvar-PYTHONINSPECT3924691
Ref: ee03924691
Ref: using/cmdline envvar-PYTHONUNBUFFERED3924957
Ref: 109e3924957
Ref: using/cmdline envvar-PYTHONVERBOSE3925101
Ref: 147c3925101
Ref: using/cmdline envvar-PYTHONCASEOK3925317
Ref: 2323925317
Ref: using/cmdline envvar-PYTHONDONTWRITEBYTECODE3925469
Ref: dff3925469
Ref: using/cmdline envvar-PYTHONPYCACHEPREFIX3925686
Ref: 28f3925686
Ref: using/cmdline envvar-PYTHONHASHSEED3925987
Ref: aa43925987
Ref: using/cmdline envvar-PYTHONIOENCODING3926631
Ref: a143926631
Ref: using/cmdline envvar-PYTHONNOUSERSITE3927399
Ref: ddc3927399
Ref: using/cmdline envvar-PYTHONUSERBASE3927651
Ref: dda3927651
Ref: using/cmdline envvar-PYTHONEXECUTABLE3927994
Ref: 148b3927994
Ref: using/cmdline envvar-PYTHONWARNINGS3928196
Ref: 51b3928196
Ref: using/cmdline envvar-PYTHONFAULTHANDLER3929085
Ref: aa73929085
Ref: using/cmdline envvar-PYTHONTRACEMALLOC3929491
Ref: 148c3929491
Ref: using/cmdline envvar-PYTHONPROFILEIMPORTTIME3929903
Ref: 4443929903
Ref: using/cmdline envvar-PYTHONASYNCIODEBUG3930152
Ref: 148d3930152
Ref: using/cmdline envvar-PYTHONMALLOC3930343
Ref: 5fc3930343
Ref: using/cmdline envvar-PYTHONMALLOCSTATS3931531
Ref: 12973931531
Ref: using/cmdline envvar-PYTHONLEGACYWINDOWSFSENCODING3932118
Ref: 5f03932118
Ref: using/cmdline envvar-PYTHONLEGACYWINDOWSSTDIO3932635
Ref: 5f33932635
Ref: using/cmdline envvar-PYTHONCOERCECLOCALE3933070
Ref: 41d3933070
Ref: using/cmdline envvar-PYTHONDEVMODE3935548
Ref: 43c3935548
Ref: using/cmdline envvar-PYTHONUTF83935782
Ref: 4213935782
Ref: 环境变量-Footnote-13938372
Ref: 环境变量-Footnote-23938421
Ref: 环境变量-Footnote-33938470
Ref: 环境变量-Footnote-43938519
Ref: 环境变量-Footnote-53938568
Ref: 环境变量-Footnote-63938617
Node: 调试模式变量3938666
Ref: using/cmdline debug-mode-variables3938733
Ref: 14943938733
Ref: using/cmdline envvar-PYTHONTHREADDEBUG3938850
Ref: 14953938850
Ref: using/cmdline envvar-PYTHONDUMPREFS3939013
Ref: 2933939013
Node: 在Unix平台中使用Python3939221
Ref: using/unix doc3939375
Ref: 14963939375
Ref: using/unix using-on-unix3939375
Ref: 14973939375
Ref: using/unix using-python-on-unix-platforms3939375
Ref: 14983939375
Node: 获取最新版本的Python3939544
Ref: using/unix getting-and-installing-the-latest-version-of-python3939657
Ref: 14993939657
Node: 在Linux中3939801
Ref: using/unix on-linux3939908
Ref: 149a3939908
Node: 在FreeBSD和OpenBSD上3940780
Ref: using/unix on-freebsd-and-openbsd3940919
Ref: 149b3940919
Node: 在OpenSolaris系统上3941412
Ref: using/unix on-opensolaris3941531
Ref: 149c3941531
Ref: 在OpenSolaris系统上-Footnote-13941738
Node: 构建Python3941771
Ref: using/unix building-python3941926
Ref: 149d3941926
Ref: using/unix building-python-on-unix3941926
Ref: 8e03941926
Ref: 构建Python-Footnote-13942671
Ref: 构建Python-Footnote-23942720
Ref: 构建Python-Footnote-33942787
Node: 与Python相关的路径和文件3942849
Ref: using/unix python-related-paths-and-files3942983
Ref: 149e3942983
Node: 杂项3944186
Ref: using/unix miscellaneous3944299
Ref: 149f3944299
Node: 在 Windows 上使用 Python3944810
Ref: using/windows doc3944972
Ref: 14a03944972
Ref: using/windows using-on-windows3944972
Ref: 3f83944972
Ref: using/windows using-python-on-windows3944972
Ref: 14a13944972
Ref: 在 Windows 上使用 Python-Footnote-13946986
Ref: 在 Windows 上使用 Python-Footnote-23947036
Node: 完整安装程序3947085
Ref: using/windows the-full-installer3947195
Ref: 14a53947195
Ref: using/windows windows-full3947195
Ref: 14a23947195
Node: 安装步骤3947369
Ref: using/windows installation-steps3947467
Ref: 14a63947467
Node: 删除 MAX_PATH 限制3949263
Ref: using/windows max-path3949397
Ref: 5cf3949397
Ref: using/windows removing-the-max-path-limitation3949397
Ref: 14a83949397
Node: 安裝排除使用者介面3950119
Ref: using/windows install-quiet-option3950262
Ref: 14a93950262
Ref: using/windows installing-without-ui3950262
Ref: 14aa3950262
Node: 當安裝時不下載3959370
Ref: using/windows install-layout-option3959503
Ref: 14a73959503
Ref: using/windows installing-without-downloading3959503
Ref: 14ab3959503
Node: 修改安装3960366
Ref: using/windows modifying-an-install3960463
Ref: 14ac3960463
Node: Microsoft Store包3961215
Ref: using/windows the-microsoft-store-package3961353
Ref: 14ad3961353
Ref: using/windows windows-store3961353
Ref: 133d3961353
Node: 已知的问题3963289
Ref: using/windows known-issues3963359
Ref: 14ae3963359
Ref: 已知的问题-Footnote-13963901
Node: nuget org 安装包3963997
Ref: using/windows the-nuget-org-packages3964132
Ref: 14af3964132
Ref: using/windows windows-nuget3964132
Ref: 14a33964132
Ref: nuget org 安装包-Footnote-13966069
Ref: nuget org 安装包-Footnote-23966100
Ref: nuget org 安装包-Footnote-33966146
Node: 可嵌入的包3966195
Ref: using/windows the-embeddable-package3966327
Ref: 14b03966327
Ref: using/windows windows-embeddable3966327
Ref: 14a43966327
Ref: 可嵌入的包-Footnote-13967782
Node: Python应用程序3967853
Ref: using/windows python-application3967945
Ref: 14b13967945
Node: 嵌入 Python3969246
Ref: using/windows embedding-python3969338
Ref: 14b23969338
Node: 替代捆绑包3969980
Ref: using/windows alternative-bundles3970106
Ref: 14b33970106
Ref: 替代捆绑包-Footnote-13970834
Ref: 替代捆绑包-Footnote-23970884
Ref: 替代捆绑包-Footnote-33970927
Ref: 替代捆绑包-Footnote-43970977
Node: 設定 Python3971014
Ref: using/windows configuring-python3971137
Ref: 14b43971137
Node: 附录：设置环境变量3971587
Ref: using/windows excursus-setting-environment-variables3971700
Ref: 14b53971700
Ref: using/windows setting-envvars3971700
Ref: 133e3971700
Node: 查找Python可执行文件3973792
Ref: using/windows finding-the-python-executable3973905
Ref: 14b63973905
Ref: using/windows windows-path-mod3973905
Ref: a713973905
Node: UTF-8 模式3975029
Ref: using/windows utf-8-mode3975171
Ref: 14b73975171
Ref: using/windows win-utf8-mode3975171
Ref: 14b83975171
Ref: UTF-8 模式-Footnote-13976966
Ref: UTF-8 模式-Footnote-23977015
Node: 适用于Windows的Python启动器3977064
Ref: using/windows launcher3977205
Ref: a703977205
Ref: using/windows python-launcher-for-windows3977205
Ref: 14b93977205
Ref: 适用于Windows的Python启动器-Footnote-13977894
Node: 開始3977943
Ref: using/windows getting-started3978042
Ref: 14ba3978042
Node: 从命令行3978174
Ref: using/windows from-the-command-line3978275
Ref: 14bb3978275
Node: 虛擬環境（Virtual environment）3979339
Ref: using/windows virtual-environments3979458
Ref: 14bc3979458
Node: 从脚本3979904
Ref: using/windows from-a-script3980026
Ref: 14bd3980026
Node: 從檔案關聯3980954
Ref: using/windows from-file-associations3981030
Ref: 14be3981030
Node: Shebang Lines3981486
Ref: using/windows shebang-lines3981617
Ref: 14bf3981617
Node: shebang lines 的参数3983444
Ref: using/windows arguments-in-shebang-lines3983578
Ref: 14c03983578
Node: 自定义3983831
Ref: using/windows customization3983958
Ref: 14c13983958
Node: 通过INI文件自定义3984066
Ref: using/windows customization-via-ini-files3984175
Ref: 14c23984175
Node: 自定义默认的Python版本3984857
Ref: using/windows customizing-default-python-versions3984966
Ref: 14c33984966
Node: 诊断3988267
Ref: using/windows diagnostics3988362
Ref: 14c43988362
Node: 查找模块3988706
Ref: using/windows finding-modules3988847
Ref: 5aa3988847
Ref: using/windows id13988847
Ref: 14c53988847
Node: 附加模块3994685
Ref: using/windows additional-modules3994817
Ref: 14c63994817
Node: PyWin323995167
Ref: using/windows pywin323995241
Ref: 14c83995241
Ref: PyWin32-Footnote-13995833
Ref: PyWin32-Footnote-23995874
Ref: PyWin32-Footnote-33995974
Ref: PyWin32-Footnote-43996048
Ref: PyWin32-Footnote-53996142
Ref: PyWin32-Footnote-63996200
Node: cx_Freeze3996249
Ref: using/windows cx-freeze3996338
Ref: 14c93996338
Ref: cx_Freeze-Footnote-13996681
Node: WConio3996733
Ref: using/windows wconio3996806
Ref: 14cb3996806
Ref: WConio-Footnote-13997119
Node: 編譯 Python 在 Windows3997179
Ref: using/windows compiling-python-on-windows3997311
Ref: 14cc3997311
Ref: 編譯 Python 在 Windows-Footnote-13998219
Ref: 編譯 Python 在 Windows-Footnote-23998268
Ref: 編譯 Python 在 Windows-Footnote-33998335
Node: 其他平台3998383
Ref: using/windows other-platforms3998494
Ref: 14ce3998494
Ref: 其他平台-Footnote-13998998
Ref: 其他平台-Footnote-23999047
Ref: 其他平台-Footnote-33999088
Ref: 其他平台-Footnote-43999116
Ref: 其他平台-Footnote-53999204
Ref: 其他平台-Footnote-63999258
Node: 在 Mac 系統使用Python3999308
Ref: using/mac doc3999472
Ref: 14cf3999472
Ref: using/mac using-on-mac3999472
Ref: 14d03999472
Ref: using/mac using-python-on-a-mac3999472
Ref: 14d13999472
Node: 取得和安裝 MacPython4000003
Ref: using/mac getting-and-installing-macpython4000121
Ref: 14d24000121
Ref: using/mac getting-osx4000121
Ref: 14d34000121
Node: 如何執行Python腳本4001946
Ref: using/mac how-to-run-a-python-script4002080
Ref: 14d44002080
Node: 透過使用者圖形介面執行腳本4003506
Ref: using/mac osx-gui-scripts4003655
Ref: 14d64003655
Ref: using/mac running-scripts-with-a-gui4003655
Ref: 14d74003655
Node: 設定4004087
Ref: using/mac configuration4004203
Ref: 14d84004203
Node: 整合化開發工具4004716
Ref: using/mac ide4004869
Ref: 14d54004869
Ref: using/mac the-ide4004869
Ref: 14da4004869
Node: 安装额外的 Python 包4005085
Ref: using/mac installing-additional-python-packages4005260
Ref: 14db4005260
Ref: using/mac mac-package-manager4005260
Ref: 14d94005260
Node: 圖形化使用者介面 GUI 程式開發於Mac4005618
Ref: using/mac gui-programming-on-the-mac4005803
Ref: 14dc4005803
Node: 貢獻Python應用程式於 Mac4006814
Ref: using/mac distributing-python-applications-on-the-mac4006985
Ref: 14dd4006985
Node: 其他資源4007237
Ref: using/mac other-resources4007352
Ref: 14de4007352
Node: 编辑器和集成开发环境4007639
Ref: using/editors doc4007766
Ref: 14df4007766
Ref: using/editors editors4007766
Ref: 14e04007766
Ref: using/editors editors-and-ides4007766
Ref: 14e14007766
Ref: 编辑器和集成开发环境-Footnote-14008115
Ref: 编辑器和集成开发环境-Footnote-24008164
Ref: 编辑器和集成开发环境-Footnote-34008215
Node: Python 語言參考手冊4008286
Ref: reference/index doc4008433
Ref: 14e24008433
Ref: reference/index reference-index4008433
Ref: 13314008433
Ref: reference/index the-python-language-reference4008433
Ref: 14e34008433
Node: 簡介<5>4009312
Ref: reference/introduction doc4009404
Ref: 14e44009404
Ref: reference/introduction id14009404
Ref: 14e54009404
Ref: reference/introduction introduction4009404
Ref: 14e64009404
Node: 其他实现4010968
Ref: reference/introduction alternate-implementations4011041
Ref: 14e74011041
Ref: reference/introduction implementations4011041
Ref: 146b4011041
Ref: 其他实现-Footnote-14012828
Ref: 其他实现-Footnote-24012859
Ref: 其他实现-Footnote-34012896
Ref: 其他实现-Footnote-44012927
Node: 标注4012952
Ref: reference/introduction id24013025
Ref: 14e84013025
Ref: reference/introduction notation4013025
Ref: 14e94013025
Ref: reference/introduction grammar-token-name4013151
Ref: 14ea4013151
Ref: reference/introduction grammar-token-lc-letter4013199
Ref: 14eb4013199
Node: 词法分析4014876
Ref: reference/lexical_analysis doc4014989
Ref: 14ec4014989
Ref: reference/lexical_analysis lexical4014989
Ref: 14ed4014989
Ref: reference/lexical_analysis lexical-analysis4014989
Ref: 14ee4014989
Ref: 词法分析-Footnote-14015533
Node: 行结构4015582
Ref: reference/lexical_analysis id14015661
Ref: 14ef4015661
Ref: reference/lexical_analysis line-structure4015661
Ref: 14f04015661
Node: 逻辑行4015902
Ref: reference/lexical_analysis id24015975
Ref: 14f14015975
Ref: reference/lexical_analysis logical-lines4015975
Ref: 14f24015975
Node: 物理行4016259
Ref: reference/lexical_analysis id34016347
Ref: 14f34016347
Ref: reference/lexical_analysis physical-lines4016347
Ref: 14f44016347
Node: 注释4016918
Ref: reference/lexical_analysis comments4017009
Ref: 14f54017009
Ref: reference/lexical_analysis id44017009
Ref: 14f64017009
Node: 编码声明4017248
Ref: reference/lexical_analysis encoding-declarations4017345
Ref: 14f74017345
Ref: reference/lexical_analysis encodings4017345
Ref: 14f84017345
Node: 显式拼接行4018270
Ref: reference/lexical_analysis explicit-joining4018376
Ref: 14f94018376
Ref: reference/lexical_analysis explicit-line-joining4018376
Ref: 14fa4018376
Node: 隐式拼接行4019202
Ref: reference/lexical_analysis implicit-joining4019305
Ref: 14fb4019305
Ref: reference/lexical_analysis implicit-line-joining4019305
Ref: 14fc4019305
Node: 空白行4019970
Ref: reference/lexical_analysis blank-lines4020064
Ref: 14fd4020064
Ref: reference/lexical_analysis id54020064
Ref: 14fe4020064
Node: 缩进4020473
Ref: reference/lexical_analysis id64020576
Ref: 14ff4020576
Ref: reference/lexical_analysis indentation4020576
Ref: 15004020576
Node: 形符间的空白字符4023280
Ref: reference/lexical_analysis whitespace4023365
Ref: 15014023365
Ref: reference/lexical_analysis whitespace-between-tokens4023365
Ref: 15024023365
Node: 其他形符4023672
Ref: reference/lexical_analysis id74023781
Ref: 15034023781
Ref: reference/lexical_analysis other-tokens4023781
Ref: 15044023781
Node: 标识符和关键字4024113
Ref: reference/lexical_analysis identifiers4024222
Ref: 15054024222
Ref: reference/lexical_analysis identifiers-and-keywords4024222
Ref: 15064024222
Ref: reference/lexical_analysis grammar-token-identifier4024916
Ref: 15074024916
Ref: reference/lexical_analysis grammar-token-id-start4024962
Ref: 15084024962
Ref: reference/lexical_analysis grammar-token-id-continue4025111
Ref: 15094025111
Ref: reference/lexical_analysis grammar-token-xid-start4025259
Ref: 150a4025259
Ref: reference/lexical_analysis grammar-token-xid-continue4025366
Ref: 150b4025366
Ref: 标识符和关键字-Footnote-14026258
Ref: 标识符和关键字-Footnote-24026307
Ref: 标识符和关键字-Footnote-34026356
Node: 关键字4026419
Ref: reference/lexical_analysis id84026516
Ref: 150c4026516
Ref: reference/lexical_analysis keywords4026516
Ref: 150d4026516
Node: 保留的标识符类4027074
Ref: reference/lexical_analysis id-classes4027171
Ref: 150e4027171
Ref: reference/lexical_analysis reserved-classes-of-identifiers4027171
Ref: 150f4027171
Node: 字面值4028457
Ref: reference/lexical_analysis id94028563
Ref: 15114028563
Ref: reference/lexical_analysis literals4028563
Ref: 15124028563
Node: 字符串与字节串字面值4028829
Ref: reference/lexical_analysis string-and-bytes-literals4028938
Ref: 15134028938
Ref: reference/lexical_analysis strings4028938
Ref: 15144028938
Ref: reference/lexical_analysis grammar-token-stringliteral4029051
Ref: 15154029051
Ref: reference/lexical_analysis grammar-token-stringprefix4029117
Ref: 15164029117
Ref: reference/lexical_analysis grammar-token-shortstring4029257
Ref: 15174029257
Ref: reference/lexical_analysis grammar-token-longstring4029334
Ref: 15184029334
Ref: reference/lexical_analysis grammar-token-shortstringitem4029417
Ref: 15194029417
Ref: reference/lexical_analysis grammar-token-longstringitem4029476
Ref: 151a4029476
Ref: reference/lexical_analysis grammar-token-shortstringchar4029534
Ref: 151b4029534
Ref: reference/lexical_analysis grammar-token-longstringchar4029617
Ref: 151c4029617
Ref: reference/lexical_analysis grammar-token-stringescapeseq4029676
Ref: 151d4029676
Ref: reference/lexical_analysis grammar-token-bytesliteral4029729
Ref: 151e4029729
Ref: reference/lexical_analysis grammar-token-bytesprefix4029789
Ref: 151f4029789
Ref: reference/lexical_analysis grammar-token-shortbytes4029879
Ref: 15204029879
Ref: reference/lexical_analysis grammar-token-longbytes4029953
Ref: 15214029953
Ref: reference/lexical_analysis grammar-token-shortbytesitem4030033
Ref: 15224030033
Ref: reference/lexical_analysis grammar-token-longbytesitem4030089
Ref: 15234030089
Ref: reference/lexical_analysis grammar-token-shortbyteschar4030144
Ref: 15244030144
Ref: reference/lexical_analysis grammar-token-longbyteschar4030225
Ref: 15254030225
Ref: reference/lexical_analysis grammar-token-bytesescapeseq4030282
Ref: 15264030282
Ref: 字符串与字节串字面值-Footnote-14037035
Ref: 字符串与字节串字面值-Footnote-24037084
Node: 字符串字面值合并4037160
Ref: reference/lexical_analysis string-concatenation4037302
Ref: 15274037302
Ref: reference/lexical_analysis string-literal-concatenation4037302
Ref: 15284037302
Node: 格式字符串字面值4038157
Ref: reference/lexical_analysis f-strings4038284
Ref: 2964038284
Ref: reference/lexical_analysis formatted-string-literals4038284
Ref: 15294038284
Ref: reference/lexical_analysis grammar-token-f-string4038836
Ref: 152a4038836
Ref: reference/lexical_analysis grammar-token-replacement-field4038913
Ref: 152b4038913
Ref: reference/lexical_analysis grammar-token-f-expression4039002
Ref: 152c4039002
Ref: reference/lexical_analysis grammar-token-conversion4039197
Ref: 152d4039197
Ref: reference/lexical_analysis grammar-token-format-spec4039240
Ref: 152e4039240
Ref: reference/lexical_analysis grammar-token-literal-char4039310
Ref: 152f4039310
Ref: 格式字符串字面值-Footnote-14043750
Node: 数值字面值4043799
Ref: reference/lexical_analysis numbers4043917
Ref: 15304043917
Ref: reference/lexical_analysis numeric-literals4043917
Ref: 15314043917
Node: 整数字面值4044231
Ref: reference/lexical_analysis integer-literals4044343
Ref: 15324044343
Ref: reference/lexical_analysis integers4044343
Ref: 15334044343
Ref: reference/lexical_analysis grammar-token-integer4044425
Ref: 15344044425
Ref: reference/lexical_analysis grammar-token-decinteger4044497
Ref: 15354044497
Ref: reference/lexical_analysis grammar-token-bininteger4044567
Ref: 15364044567
Ref: reference/lexical_analysis grammar-token-octinteger4044623
Ref: 15374044623
Ref: reference/lexical_analysis grammar-token-hexinteger4044679
Ref: 15384044679
Ref: reference/lexical_analysis grammar-token-nonzerodigit4044735
Ref: 15394044735
Ref: reference/lexical_analysis grammar-token-digit4044767
Ref: 153a4044767
Ref: reference/lexical_analysis grammar-token-bindigit4044799
Ref: 153b4044799
Ref: reference/lexical_analysis grammar-token-octdigit4044831
Ref: 153c4044831
Ref: reference/lexical_analysis grammar-token-hexdigit4044863
Ref: 153d4044863
Node: 浮点数字面值4045623
Ref: reference/lexical_analysis floating4045735
Ref: 153e4045735
Ref: reference/lexical_analysis floating-point-literals4045735
Ref: 153f4045735
Ref: reference/lexical_analysis grammar-token-floatnumber4045825
Ref: 15404045825
Ref: reference/lexical_analysis grammar-token-pointfloat4045875
Ref: 15414045875
Ref: reference/lexical_analysis grammar-token-exponentfloat4045935
Ref: 15424045935
Ref: reference/lexical_analysis grammar-token-digitpart4045992
Ref: 15434045992
Ref: reference/lexical_analysis grammar-token-fraction4046036
Ref: 15444046036
Ref: reference/lexical_analysis grammar-token-exponent4046073
Ref: 15454046073
Node: 虚数字面值4046559
Ref: reference/lexical_analysis imaginary4046647
Ref: 15464046647
Ref: reference/lexical_analysis imaginary-literals4046647
Ref: 15474046647
Ref: reference/lexical_analysis grammar-token-imagnumber4046729
Ref: 15484046729
Node: 运算符4047082
Ref: reference/lexical_analysis id114047176
Ref: 15494047176
Ref: reference/lexical_analysis operators4047176
Ref: 154a4047176
Node: 分隔符4047399
Ref: reference/lexical_analysis delimiters4047475
Ref: 154b4047475
Ref: reference/lexical_analysis id124047475
Ref: 154c4047475
Node: 数据模型4048191
Ref: reference/datamodel doc4048307
Ref: 154d4048307
Ref: reference/datamodel data-model4048307
Ref: 154e4048307
Ref: reference/datamodel datamodel4048307
Ref: 10594048307
Node: 对象、值与类型4048437
Ref: reference/datamodel objects4048540
Ref: 154f4048540
Ref: reference/datamodel objects-values-and-types4048540
Ref: 15504048540
Ref: 对象、值与类型-Footnote-14052861
Node: 标准类型层级结构4053054
Ref: reference/datamodel the-standard-type-hierarchy4053184
Ref: 15524053184
Ref: reference/datamodel types4053184
Ref: 15534053184
Ref: reference/datamodel frame-objects4084363
Ref: 15654084363
Ref: reference/datamodel frame clear4086022
Ref: 8f84086022
Ref: reference/datamodel traceback-objects4086479
Ref: 4424086479
Ref: reference/datamodel slice indices4088849
Ref: a404088849
Node: 特殊方法名称4090319
Ref: reference/datamodel special-method-names4090434
Ref: 15664090434
Ref: reference/datamodel specialnames4090434
Ref: 6074090434
Ref: 特殊方法名称-Footnote-14092144
Node: 基本定制4092426
Ref: reference/datamodel basic-customization4092523
Ref: 15674092523
Ref: reference/datamodel customization4092523
Ref: 15684092523
Ref: reference/datamodel object __new__4092562
Ref: 9744092562
Ref: reference/datamodel object __init__4093947
Ref: e234093947
Ref: reference/datamodel object __del__4094717
Ref: a044094717
Ref: reference/datamodel object __repr__4097378
Ref: 44a4097378
Ref: reference/datamodel object __str__4098143
Ref: ef94098143
Ref: reference/datamodel object __bytes__4098751
Ref: 156a4098751
Ref: reference/datamodel object __format__4098930
Ref: a2f4098930
Ref: reference/datamodel richcmpfuncs4099910
Ref: 156b4099910
Ref: reference/datamodel object __lt__4099910
Ref: cfe4099910
Ref: reference/datamodel object __le__4099956
Ref: d684099956
Ref: reference/datamodel object __eq__4100002
Ref: 44b4100002
Ref: reference/datamodel object __ne__4100048
Ref: f184100048
Ref: reference/datamodel object __gt__4100094
Ref: d694100094
Ref: reference/datamodel object __ge__4100140
Ref: d6a4100140
Ref: reference/datamodel object __hash__4102361
Ref: 44c4102361
Ref: reference/datamodel object __bool__4106302
Ref: d304106302
Node: 自定义属性访问4106745
Ref: reference/datamodel attribute-access4106869
Ref: 156c4106869
Ref: reference/datamodel customizing-attribute-access4106869
Ref: 156d4106869
Ref: reference/datamodel object __getattr__4107048
Ref: 42a4107048
Ref: reference/datamodel object __getattribute__4108261
Ref: 5494108261
Ref: reference/datamodel object __setattr__4109225
Ref: eee4109225
Ref: reference/datamodel object __delattr__4109785
Ref: 15634109785
Ref: reference/datamodel object __dir__4110118
Ref: 42b4110118
Node: 自定义模块属性访问4110450
Ref: reference/datamodel customizing-module-attribute-access4110559
Ref: 15704110559
Ref: 自定义模块属性访问-Footnote-14112536
Node: 实现描述器4112585
Ref: reference/datamodel descriptors4112724
Ref: 5e34112724
Ref: reference/datamodel implementing-descriptors4112724
Ref: 15714112724
Ref: reference/datamodel object __get__4113112
Ref: 156e4113112
Ref: reference/datamodel object __set__4113927
Ref: 15724113927
Ref: reference/datamodel object __delete__4114287
Ref: 15734114287
Ref: reference/datamodel object __set_name__4114426
Ref: 5e24114426
Ref: 实现描述器-Footnote-14115518
Node: 发起调用描述器4115567
Ref: reference/datamodel descriptor-invocation4115688
Ref: 15744115688
Ref: reference/datamodel invoking-descriptors4115688
Ref: 15754115688
Node: __slots__4118840
Ref: reference/datamodel id34118937
Ref: 15764118937
Ref: reference/datamodel slots4118937
Ref: 15774118937
Ref: reference/datamodel object __slots__4119314
Ref: eef4119314
Node: 使用 __slots__ 的注意事项4119685
Ref: reference/datamodel notes-on-using-slots4119763
Ref: 15784119763
Node: 自定义类创建4122782
Ref: reference/datamodel class-customization4122924
Ref: 5df4122924
Ref: reference/datamodel customizing-class-creation4122924
Ref: 157a4122924
Ref: reference/datamodel object __init_subclass__4123381
Ref: 5dc4123381
Node: 元类4124716
Ref: reference/datamodel id44124803
Ref: 157b4124803
Ref: reference/datamodel metaclasses4124803
Ref: 157c4124803
Node: 解析 MRO 条目4125705
Ref: reference/datamodel resolving-mro-entries4125822
Ref: 157d4125822
Ref: 解析 MRO 条目-Footnote-14126322
Node: 确定适当的元类4126371
Ref: reference/datamodel determining-the-appropriate-metaclass4126503
Ref: 157e4126503
Node: 准备类命名空间4127281
Ref: reference/datamodel prepare4127411
Ref: 5f64127411
Ref: reference/datamodel preparing-the-class-namespace4127411
Ref: 157f4127411
Ref: 准备类命名空间-Footnote-14128270
Node: 执行类主体4128319
Ref: reference/datamodel executing-the-class-body4128443
Ref: 15804128443
Node: 创建类对象4129081
Ref: reference/datamodel class-object-creation4129199
Ref: 5de4129199
Ref: reference/datamodel creating-the-class-object4129199
Ref: 15814129199
Ref: 创建类对象-Footnote-14131407
Node: 元类的作用4131456
Ref: reference/datamodel uses-for-metaclasses4131550
Ref: 15824131550
Node: 自定义实例及子类检查4131795
Ref: reference/datamodel customizing-instance-and-subclass-checks4131934
Ref: 15834131934
Ref: reference/datamodel class __instancecheck__4132327
Ref: 15844132327
Ref: reference/datamodel class __subclasscheck__4132581
Ref: 15854132581
Ref: 自定义实例及子类检查-Footnote-14133486
Node: 模拟泛型类型4133535
Ref: reference/datamodel emulating-generic-types4133677
Ref: 15864133677
Ref: reference/datamodel object __class_getitem__4134588
Ref: 4374134588
Ref: 模拟泛型类型-Footnote-14135068
Node: The purpose of __class_getitem__4135117
Ref: reference/datamodel the-purpose-of-class-getitem4135249
Ref: 158a4135249
Node: __class_getitem__ versus __getitem__4136140
Ref: reference/datamodel class-getitem-versus-getitem4136272
Ref: 158c4136272
Ref: reference/datamodel classgetitem-versus-getitem4136272
Ref: 158d4136272
Ref: __class_getitem__ versus __getitem__-Footnote-14139602
Node: 模拟可调用对象4139651
Ref: reference/datamodel callable-types4139781
Ref: 15914139781
Ref: reference/datamodel emulating-callable-objects4139781
Ref: 15924139781
Ref: reference/datamodel object __call__4139837
Ref: 15604139837
Node: 模拟容器类型4140099
Ref: reference/datamodel emulating-container-types4140229
Ref: 15934140229
Ref: reference/datamodel sequence-types4140229
Ref: 15944140229
Ref: reference/datamodel object __len__4142528
Ref: e904142528
Ref: reference/datamodel object __length_hint__4143242
Ref: 8f94143242
Ref: reference/datamodel object __getitem__4143980
Ref: 3a54143980
Ref: reference/datamodel object __setitem__4145163
Ref: d2a4145163
Ref: reference/datamodel object __delitem__4145574
Ref: d2b4145574
Ref: reference/datamodel object __missing__4145953
Ref: c0d4145953
Ref: reference/datamodel object __iter__4146150
Ref: 6084146150
Ref: reference/datamodel object __reversed__4146587
Ref: 6284146587
Ref: reference/datamodel object __contains__4147469
Ref: dee4147469
Node: 模拟数字类型4148009
Ref: reference/datamodel emulating-numeric-types4148147
Ref: 159d4148147
Ref: reference/datamodel numeric-types4148147
Ref: 159e4148147
Ref: reference/datamodel object __add__4148375
Ref: 15954148375
Ref: reference/datamodel object __sub__4148422
Ref: 159f4148422
Ref: reference/datamodel object __mul__4148469
Ref: 15974148469
Ref: reference/datamodel object __matmul__4148516
Ref: 73b4148516
Ref: reference/datamodel object __truediv__4148566
Ref: 8754148566
Ref: reference/datamodel object __floordiv__4148617
Ref: ef74148617
Ref: reference/datamodel object __mod__4148669
Ref: 15a04148669
Ref: reference/datamodel object __divmod__4148716
Ref: 8764148716
Ref: reference/datamodel object __pow__4148766
Ref: 15a14148766
Ref: reference/datamodel object __lshift__4148823
Ref: 15a24148823
Ref: reference/datamodel object __rshift__4148873
Ref: 15a34148873
Ref: reference/datamodel object __and__4148923
Ref: 15a44148923
Ref: reference/datamodel object __xor__4148970
Ref: 15a54148970
Ref: reference/datamodel object __or__4149017
Ref: 15a64149017
Ref: reference/datamodel object __radd__4149906
Ref: 15964149906
Ref: reference/datamodel object __rsub__4149954
Ref: 15a74149954
Ref: reference/datamodel object __rmul__4150002
Ref: 15984150002
Ref: reference/datamodel object __rmatmul__4150050
Ref: 73c4150050
Ref: reference/datamodel object __rtruediv__4150101
Ref: 15a84150101
Ref: reference/datamodel object __rfloordiv__4150153
Ref: 15a94150153
Ref: reference/datamodel object __rmod__4150206
Ref: 7a24150206
Ref: reference/datamodel object __rdivmod__4150254
Ref: 15aa4150254
Ref: reference/datamodel object __rpow__4150305
Ref: 15ab4150305
Ref: reference/datamodel object __rlshift__4150363
Ref: 15ac4150363
Ref: reference/datamodel object __rrshift__4150414
Ref: 15ad4150414
Ref: reference/datamodel object __rand__4150465
Ref: 15ae4150465
Ref: reference/datamodel object __rxor__4150513
Ref: 15af4150513
Ref: reference/datamodel object __ror__4150561
Ref: 15b04150561
Ref: reference/datamodel object __iadd__4151631
Ref: f304151631
Ref: reference/datamodel object __isub__4151679
Ref: f314151679
Ref: reference/datamodel object __imul__4151727
Ref: 15994151727
Ref: reference/datamodel object __imatmul__4151775
Ref: 73d4151775
Ref: reference/datamodel object __itruediv__4151826
Ref: 15b14151826
Ref: reference/datamodel object __ifloordiv__4151878
Ref: 15b24151878
Ref: reference/datamodel object __imod__4151931
Ref: 15b34151931
Ref: reference/datamodel object __ipow__4151979
Ref: 15b44151979
Ref: reference/datamodel object __ilshift__4152037
Ref: 15b54152037
Ref: reference/datamodel object __irshift__4152088
Ref: 15b64152088
Ref: reference/datamodel object __iand__4152139
Ref: 15b74152139
Ref: reference/datamodel object __ixor__4152187
Ref: 15b84152187
Ref: reference/datamodel object __ior__4152235
Ref: 15b94152235
Ref: reference/datamodel object __neg__4153436
Ref: 15bb4153436
Ref: reference/datamodel object __pos__4153476
Ref: 15bc4153476
Ref: reference/datamodel object __abs__4153516
Ref: 15bd4153516
Ref: reference/datamodel object __invert__4153556
Ref: 15be4153556
Ref: reference/datamodel object __complex__4153703
Ref: 2c54153703
Ref: reference/datamodel object __int__4153747
Ref: 2c34153747
Ref: reference/datamodel object __float__4153787
Ref: 2c44153787
Ref: reference/datamodel object __index__4153987
Ref: 2c24153987
Ref: reference/datamodel object __round__4154607
Ref: 15c04154607
Ref: reference/datamodel object __trunc__4154660
Ref: 15c14154660
Ref: reference/datamodel object __floor__4154702
Ref: 15c24154702
Ref: reference/datamodel object __ceil__4154744
Ref: 15c34154744
Ref: 模拟数字类型-Footnote-14155336
Ref: 模拟数字类型-Footnote-24155599
Node: with 语句上下文管理器4155828
Ref: reference/datamodel context-managers4155966
Ref: 15c44155966
Ref: reference/datamodel with-statement-context-managers4155966
Ref: 15c54155966
Ref: reference/datamodel object __enter__4156613
Ref: d5d4156613
Ref: reference/datamodel object __exit__4156835
Ref: d5e4156835
Ref: with 语句上下文管理器-Footnote-14157579
Node: 特殊方法查找4157628
Ref: reference/datamodel special-lookup4157739
Ref: 156f4157739
Ref: reference/datamodel special-method-lookup4157739
Ref: 15c74157739
Node: 协程4160403
Ref: reference/datamodel coroutines4160485
Ref: 15c84160485
Node: 可等待对象4160606
Ref: reference/datamodel awaitable-objects4160685
Ref: 15c94160685
Ref: reference/datamodel object __await__4161157
Ref: 7354161157
Ref: 可等待对象-Footnote-14161547
Node: 协程对象4161596
Ref: reference/datamodel coroutine-objects4161699
Ref: 155e4161699
Ref: reference/datamodel id74161699
Ref: 15ca4161699
Ref: reference/datamodel coroutine send4162527
Ref: 15cc4162527
Ref: reference/datamodel coroutine throw4163072
Ref: 15ce4163072
Ref: reference/datamodel coroutine close4163673
Ref: 15cf4163673
Node: 异步迭代器4164181
Ref: reference/datamodel async-iterators4164293
Ref: 7394164293
Ref: reference/datamodel asynchronous-iterators4164293
Ref: 15d14164293
Ref: reference/datamodel object __aiter__4164480
Ref: 5824164480
Ref: reference/datamodel object __anext__4164576
Ref: 155f4164576
Node: 异步上下文管理器4165451
Ref: reference/datamodel async-context-managers4165542
Ref: 15d24165542
Ref: reference/datamodel asynchronous-context-managers4165542
Ref: 15d34165542
Ref: reference/datamodel object __aenter__4165818
Ref: 109a4165818
Ref: reference/datamodel object __aexit__4165982
Ref: 109b4165982
Node: 执行模型4166464
Ref: reference/executionmodel doc4166580
Ref: 15d44166580
Ref: reference/executionmodel execmodel4166580
Ref: 15d54166580
Ref: reference/executionmodel execution-model4166580
Ref: 15d64166580
Node: 程序的结构4166672
Ref: reference/executionmodel prog-structure4166760
Ref: 15d74166760
Ref: reference/executionmodel structure-of-a-program4166760
Ref: 15d84166760
Node: 命名与绑定4167696
Ref: reference/executionmodel naming4167799
Ref: 15d94167799
Ref: reference/executionmodel naming-and-binding4167799
Ref: 15da4167799
Node: 名称的绑定4167959
Ref: reference/executionmodel bind-names4168050
Ref: 15db4168050
Ref: reference/executionmodel binding-of-names4168050
Ref: 15dc4168050
Node: 名称的解析4169428
Ref: reference/executionmodel resolution-of-names4169564
Ref: 15dd4169564
Ref: reference/executionmodel resolve-names4169564
Ref: 15de4169564
Node: 内置命名空间和受限的执行4172836
Ref: reference/executionmodel builtins-and-restricted-execution4172981
Ref: 15df4172981
Ref: reference/executionmodel restrict-exec4172981
Ref: 15e04172981
Node: 与动态特性的交互4173804
Ref: reference/executionmodel dynamic-features4173925
Ref: 15e14173925
Ref: reference/executionmodel interaction-with-dynamic-features4173925
Ref: 15e24173925
Ref: 与动态特性的交互-Footnote-14174646
Node: 异常4174765
Ref: reference/executionmodel exceptions4174844
Ref: 15e34174844
Ref: reference/executionmodel id24174844
Ref: 15e44174844
Node: 导入系统4176710
Ref: reference/import doc4176823
Ref: 15e54176823
Ref: reference/import importsystem4176823
Ref: 15614176823
Ref: reference/import the-import-system4176823
Ref: 15e64176823
Ref: 导入系统-Footnote-14179209
Ref: 导入系统-Footnote-24179260
Ref: 导入系统-Footnote-34179309
Node: importlib<8>4179358
Ref: reference/import importlib4179431
Ref: 15e94179431
Node: 包4179782
Ref: reference/import packages4179870
Ref: 15ea4179870
Node: 常规包4181165
Ref: reference/import regular-packages4181238
Ref: 15ec4181238
Node: 命名空间包4182351
Ref: reference/import namespace-packages4182424
Ref: 15ef4182424
Ref: 命名空间包-Footnote-14183661
Node: 搜索4183710
Ref: reference/import searching4183792
Ref: 15f14183792
Node: 模块缓存4184578
Ref: reference/import the-module-cache4184663
Ref: 15f24184663
Node: 查找器和加载器4186123
Ref: reference/import finders-and-loaders4186229
Ref: 15f34186229
Ref: reference/import id24186229
Ref: 15f44186229
Node: 导入钩子4187877
Ref: reference/import import-hooks4187980
Ref: 15f94187980
Node: 元路径4188787
Ref: reference/import the-meta-path4188860
Ref: 15fa4188860
Node: 加载4191628
Ref: reference/import loading4191731
Ref: 15fc4191731
Ref: 加载-Footnote-14194893
Node: 加载器4195236
Ref: reference/import loaders4195306
Ref: 15fe4195306
Node: 子模块4198298
Ref: reference/import submodules4198395
Ref: 15ff4198395
Node: 模块规格说明4199652
Ref: reference/import module-spec4199767
Ref: 16004199767
Node: 导入相关的模块属性4200535
Ref: reference/import import-mod-attrs4200656
Ref: 15fd4200656
Ref: reference/import import-related-module-attributes4200656
Ref: 16024200656
Ref: reference/import __name__4200867
Ref: dd84200867
Ref: reference/import __loader__4201029
Ref: a374201029
Ref: reference/import __package__4201285
Ref: a364201285
Ref: reference/import __spec__4202001
Ref: 16034202001
Ref: reference/import __path__4202572
Ref: 13c34202572
Ref: reference/import __file__4203074
Ref: 15624203074
Ref: reference/import __cached__4203096
Ref: c044203096
Ref: 导入相关的模块属性-Footnote-14204006
Ref: 导入相关的模块属性-Footnote-24204055
Ref: 导入相关的模块属性-Footnote-34204104
Node: module __path__4204153
Ref: reference/import module-path4204270
Ref: 16074204270
Ref: reference/import package-path-rules4204270
Ref: 16064204270
Ref: module __path__-Footnote-14205347
Ref: module __path__-Footnote-24205396
Node: 模块的 repr4205445
Ref: reference/import module-reprs4205562
Ref: 16084205562
Node: 已缓存字节码的失效4207093
Ref: reference/import cached-bytecode-invalidation4207186
Ref: 16094207186
Ref: reference/import pyc-invalidation4207186
Ref: 4394207186
Node: 基于路径的查找器4208530
Ref: reference/import the-path-based-finder4208651
Ref: 160a4208651
Node: 路径条目查找器4210984
Ref: reference/import path-entry-finders4211102
Ref: 160c4211102
Ref: 路径条目查找器-Footnote-14215930
Node: 路径条目查找器协议4216171
Ref: reference/import path-entry-finder-protocol4216289
Ref: 160e4216289
Node: 替换标准导入系统4218344
Ref: reference/import replacing-the-standard-import-system4218474
Ref: 160f4218474
Node: 包相对导入4219300
Ref: reference/import package-relative-imports4219437
Ref: 16104219437
Ref: reference/import relativeimports4219437
Ref: 16114219437
Node: 有关 __main__ 的特殊事项4220566
Ref: reference/import special-considerations-for-main4220694
Ref: 16124220694
Node: __main__ __spec__4221261
Ref: reference/import id54221346
Ref: 16134221346
Ref: reference/import main-spec4221346
Ref: 16054221346
Node: 开放问题项4222697
Ref: reference/import open-issues4222822
Ref: 16144222822
Ref: 开放问题项-Footnote-14223428
Node: 参考文献4223477
Ref: reference/import references4223562
Ref: 16154223562
Ref: 参考文献-Footnote-14224669
Ref: 参考文献-Footnote-24224721
Ref: 参考文献-Footnote-34224770
Ref: 参考文献-Footnote-44224819
Ref: 参考文献-Footnote-54224868
Ref: 参考文献-Footnote-64224917
Ref: 参考文献-Footnote-74224966
Ref: 参考文献-Footnote-84225015
Ref: 参考文献-Footnote-94225064
Ref: 参考文献-Footnote-104225113
Node: 表达式4225163
Ref: reference/expressions doc4225276
Ref: 16164225276
Ref: reference/expressions expressions4225276
Ref: 16174225276
Ref: reference/expressions id14225276
Ref: 16184225276
Ref: reference/expressions grammar-token-name4225544
Ref: 16194225544
Node: 算术转换4226021
Ref: reference/expressions arithmetic-conversions4226094
Ref: 161a4226094
Ref: reference/expressions conversions4226094
Ref: 161b4226094
Node: 原子4226710
Ref: reference/expressions atoms4226798
Ref: 161c4226798
Ref: reference/expressions id24226798
Ref: 161d4226798
Ref: reference/expressions grammar-token-atom4227031
Ref: 161e4227031
Ref: reference/expressions grammar-token-enclosure4227083
Ref: 161f4227083
Node: 标识符（名称）4227436
Ref: reference/expressions atom-identifiers4227521
Ref: 15104227521
Ref: reference/expressions identifiers-names4227521
Ref: 16204227521
Ref: reference/expressions private-name-mangling4227943
Ref: 16214227943
Node: 字面值<2>4228658
Ref: reference/expressions atom-literals4228773
Ref: 16224228773
Ref: reference/expressions literals4228773
Ref: 16234228773
Ref: reference/expressions grammar-token-literal4228883
Ref: 16244228883
Node: 带圆括号的形式4229506
Ref: reference/expressions parenthesized4229633
Ref: 16254229633
Ref: reference/expressions parenthesized-forms4229633
Ref: 16264229633
Ref: reference/expressions grammar-token-parenth-form4229761
Ref: 16274229761
Node: 列表、集合与字典的显示4230533
Ref: reference/expressions comprehensions4230660
Ref: 16284230660
Ref: reference/expressions displays-for-lists-sets-and-dictionaries4230660
Ref: 16294230660
Ref: reference/expressions grammar-token-comprehension4231029
Ref: 162a4231029
Ref: reference/expressions grammar-token-comp-for4231083
Ref: 162b4231083
Ref: reference/expressions grammar-token-comp-iter4231159
Ref: 162c4231159
Ref: reference/expressions grammar-token-comp-if4231201
Ref: 162d4231201
Ref: 列表、集合与字典的显示-Footnote-14233196
Node: 列表显示4233245
Ref: reference/expressions list-displays4233363
Ref: 162e4233363
Ref: reference/expressions lists4233363
Ref: 162f4233363
Ref: reference/expressions grammar-token-list-display4233480
Ref: 16304233480
Node: 集合显示4233873
Ref: reference/expressions set4233970
Ref: 16314233970
Ref: reference/expressions set-displays4233970
Ref: 16324233970
Ref: reference/expressions grammar-token-set-display4234111
Ref: 16334234111
Node: 字典显示4234587
Ref: reference/expressions dict4234690
Ref: 7414234690
Ref: reference/expressions dictionary-displays4234690
Ref: 16344234690
Ref: reference/expressions grammar-token-dict-display4234811
Ref: 16354234811
Ref: reference/expressions grammar-token-key-datum-list4234885
Ref: 16364234885
Ref: reference/expressions grammar-token-key-datum4234946
Ref: 16374234946
Ref: reference/expressions grammar-token-dict-comprehension4235015
Ref: 16384235015
Ref: 字典显示-Footnote-14236630
Ref: 字典显示-Footnote-24236679
Node: 生成器表达式4236728
Ref: reference/expressions generator-expressions4236834
Ref: 16394236834
Ref: reference/expressions genexpr4236834
Ref: 163a4236834
Ref: reference/expressions grammar-token-generator-expression4236960
Ref: 163b4236960
Node: yield 表达式4238705
Ref: reference/expressions yield-expressions4238790
Ref: 163c4238790
Ref: reference/expressions yieldexpr4238790
Ref: 163d4238790
Ref: reference/expressions grammar-token-yield-atom4238836
Ref: 163e4238836
Ref: reference/expressions grammar-token-yield-expression4238887
Ref: 163f4238887
Ref: yield 表达式-Footnote-14243297
Ref: yield 表达式-Footnote-24243346
Ref: yield 表达式-Footnote-34243395
Ref: yield 表达式-Footnote-44243444
Ref: yield 表达式-Footnote-54243493
Node: 生成器-迭代器的方法4243542
Ref: reference/expressions generator-iterator-methods4243637
Ref: 16434243637
Ref: reference/expressions generator-methods4243637
Ref: 15cb4243637
Ref: reference/expressions generator __next__4243923
Ref: 140e4243923
Ref: reference/expressions generator send4244605
Ref: 15cd4244605
Ref: reference/expressions generator throw4245119
Ref: ff84245119
Ref: reference/expressions generator close4245545
Ref: 15d04245545
Node: 示例4246080
Ref: reference/expressions examples4246205
Ref: 16444246205
Node: 异步生成器函数4247242
Ref: reference/expressions asynchronous-generator-functions4247370
Ref: 16414247370
Ref: reference/expressions id34247370
Ref: 16454247370
Ref: 异步生成器函数-Footnote-14250114
Node: 异步生成器-迭代器方法4250193
Ref: reference/expressions asynchronous-generator-iterator-methods4250306
Ref: 16474250306
Ref: reference/expressions asynchronous-generator-methods4250306
Ref: 16484250306
Ref: reference/expressions agen __anext__4250493
Ref: 16464250493
Ref: reference/expressions agen asend4251341
Ref: 1774251341
Ref: reference/expressions agen athrow4252112
Ref: 1784252112
Ref: reference/expressions agen aclose4252733
Ref: 1764252733
Node: 原型4253603
Ref: reference/expressions id44253694
Ref: 16494253694
Ref: reference/expressions primaries4253694
Ref: 164a4253694
Ref: reference/expressions grammar-token-primary4253798
Ref: 164b4253798
Node: 属性引用4253928
Ref: reference/expressions attribute-references4253998
Ref: 164c4253998
Ref: reference/expressions id54253998
Ref: 164d4253998
Ref: reference/expressions grammar-token-attributeref4254103
Ref: 164e4254103
Node: 抽取4254636
Ref: reference/expressions id64254721
Ref: 164f4254721
Ref: reference/expressions subscriptions4254721
Ref: 158e4254721
Ref: reference/expressions grammar-token-subscription4254886
Ref: 16504254886
Node: 切片4256406
Ref: reference/expressions id74256485
Ref: 16514256485
Ref: reference/expressions slicings4256485
Ref: 16524256485
Ref: reference/expressions grammar-token-slicing4256712
Ref: 16534256712
Ref: reference/expressions grammar-token-slice-list4256761
Ref: 16544256761
Ref: reference/expressions grammar-token-slice-item4256818
Ref: 16554256818
Ref: reference/expressions grammar-token-proper-slice4256866
Ref: 16564256866
Ref: reference/expressions grammar-token-lower-bound4256937
Ref: 16574256937
Ref: reference/expressions grammar-token-upper-bound4256970
Ref: 16584256970
Ref: reference/expressions grammar-token-stride4257003
Ref: 16594257003
Node: 调用4258072
Ref: reference/expressions calls4258136
Ref: 73f4258136
Ref: reference/expressions id84258136
Ref: 165a4258136
Ref: reference/expressions grammar-token-call4258298
Ref: 165d4258298
Ref: reference/expressions grammar-token-argument-list4258382
Ref: 165e4258382
Ref: reference/expressions grammar-token-positional-arguments4258646
Ref: 165f4258646
Ref: reference/expressions grammar-token-positional-item4258715
Ref: 16604258715
Ref: reference/expressions grammar-token-starred-and-keywords4258784
Ref: 16614258784
Ref: reference/expressions grammar-token-keywords-arguments4258917
Ref: 16624258917
Ref: reference/expressions grammar-token-keyword-item4259052
Ref: 16634259052
Ref: 调用-Footnote-14264465
Node: await 表达式4264514
Ref: reference/expressions await4264611
Ref: 2d84264611
Ref: reference/expressions await-expression4264611
Ref: 16654264611
Ref: reference/expressions grammar-token-await-expr4264797
Ref: 16664264797
Node: 幂运算符4264853
Ref: reference/expressions power4264968
Ref: 16674264968
Ref: reference/expressions the-power-operator4264968
Ref: 16684264968
Ref: reference/expressions grammar-token-power4265146
Ref: 16694265146
Node: 一元算术和位运算4266224
Ref: reference/expressions unary4266345
Ref: 166a4266345
Ref: reference/expressions unary-arithmetic-and-bitwise-operations4266345
Ref: 166b4266345
Ref: reference/expressions grammar-token-u-expr4266451
Ref: 166c4266451
Node: 二元算术运算符4267118
Ref: reference/expressions binary4267239
Ref: 166d4267239
Ref: reference/expressions binary-arithmetic-operations4267239
Ref: 166e4267239
Ref: reference/expressions grammar-token-m-expr4267533
Ref: 166f4267533
Ref: reference/expressions grammar-token-a-expr4267689
Ref: 16704267689
Ref: 二元算术运算符-Footnote-14270580
Ref: 二元算术运算符-Footnote-24271182
Node: 移位运算4271443
Ref: reference/expressions shifting4271555
Ref: 16724271555
Ref: reference/expressions shifting-operations4271555
Ref: 16734271555
Ref: reference/expressions grammar-token-shift-expr4271635
Ref: 16744271635
Node: 二元位运算4272035
Ref: reference/expressions binary-bitwise-operations4272138
Ref: 16754272138
Ref: reference/expressions bitwise4272138
Ref: 16764272138
Ref: reference/expressions grammar-token-and-expr4272226
Ref: 16774272226
Ref: reference/expressions grammar-token-xor-expr4272281
Ref: 16784272281
Ref: reference/expressions grammar-token-or-expr4272332
Ref: 16794272332
Node: 比较运算4272998
Ref: reference/expressions comparisons4273101
Ref: 167a4273101
Ref: reference/expressions id114273101
Ref: 167b4273101
Ref: reference/expressions grammar-token-comparison4273351
Ref: 167c4273351
Ref: reference/expressions grammar-token-comp-operator4273407
Ref: 167d4273407
Node: 值比较4274475
Ref: reference/expressions value-comparisons4274560
Ref: 167e4274560
Ref: reference/expressions in4281438
Ref: 1794281438
Ref: reference/expressions not-in4281438
Ref: 159b4281438
Ref: 值比较-Footnote-14281476
Ref: 值比较-Footnote-24281525
Node: 成员检测运算4282515
Ref: reference/expressions membership-test-details4282624
Ref: 159c4282624
Ref: reference/expressions membership-test-operations4282624
Ref: 167f4282624
Ref: reference/expressions is4284453
Ref: 15514284453
Node: 标识号比较4284453
Ref: reference/expressions identity-comparisons4284544
Ref: 16804284544
Ref: reference/expressions is-not4284544
Ref: 16814284544
Ref: reference/expressions booleans4284862
Ref: 16824284862
Ref: reference/expressions and4284862
Ref: 16834284862
Ref: reference/expressions or4284862
Ref: 16844284862
Ref: 标识号比较-Footnote-14284900
Node: 布尔运算4285216
Ref: reference/expressions boolean-operations4285322
Ref: 16854285322
Ref: reference/expressions not4285322
Ref: 16864285322
Ref: reference/expressions grammar-token-or-test4285359
Ref: 16874285359
Ref: reference/expressions grammar-token-and-test4285410
Ref: 16884285410
Ref: reference/expressions grammar-token-not-test4285463
Ref: 16894285463
Node: 赋值表达式<2>4286800
Ref: reference/expressions assignment-expressions4286909
Ref: 168a4286909
Ref: reference/expressions grammar-token-assignment-expression4286951
Ref: 168b4286951
Ref: 赋值表达式<2>-Footnote-14287590
Node: 条件表达式4287639
Ref: reference/expressions conditional-expressions4287752
Ref: 168d4287752
Ref: reference/expressions if-expr4287752
Ref: 168e4287752
Ref: reference/expressions grammar-token-conditional-expression4287794
Ref: 168f4287794
Ref: reference/expressions grammar-token-expression4287867
Ref: 168c4287867
Ref: reference/expressions lambdas4288278
Ref: 16904288278
Ref: 条件表达式-Footnote-14288316
Node: lambda 表达式4288365
Ref: reference/expressions id144288475
Ref: 16914288475
Ref: reference/expressions lambda4288475
Ref: cf94288475
Ref: reference/expressions grammar-token-lambda-expr4288521
Ref: 16924288521
Node: 表达式列表4289022
Ref: reference/expressions expression-lists4289129
Ref: 16934289129
Ref: reference/expressions exprlists4289129
Ref: 7404289129
Ref: reference/expressions grammar-token-expression-list4289171
Ref: 16424289171
Ref: reference/expressions grammar-token-starred-list4289234
Ref: 16944289234
Ref: reference/expressions grammar-token-starred-expression4289301
Ref: 16954289301
Ref: reference/expressions grammar-token-starred-item4289377
Ref: 16964289377
Ref: 表达式列表-Footnote-14290310
Node: 求值顺序4290359
Ref: reference/expressions evalorder4290468
Ref: 16974290468
Ref: reference/expressions evaluation-order4290468
Ref: 16984290468
Node: 运算符优先级4290927
Ref: reference/expressions operator-precedence4291012
Ref: 16994291012
Ref: reference/expressions operator-summary4291012
Ref: 169a4291012
Ref: 运算符优先级-Footnote-14295192
Ref: 运算符优先级-Footnote-24295344
Node: 简单语句4295453
Ref: reference/simple_stmts doc4295566
Ref: 169b4295566
Ref: reference/simple_stmts simple4295566
Ref: 169c4295566
Ref: reference/simple_stmts simple-statements4295566
Ref: 169d4295566
Ref: reference/simple_stmts grammar-token-simple-stmt4295741
Ref: 169e4295741
Node: 表达式语句4296573
Ref: reference/simple_stmts expression-statements4296658
Ref: 169f4296658
Ref: reference/simple_stmts exprstmts4296658
Ref: 16a04296658
Ref: reference/simple_stmts grammar-token-expression-stmt4297024
Ref: 16a14297024
Node: 赋值语句4297453
Ref: reference/simple_stmts assignment4297560
Ref: 16a24297560
Ref: reference/simple_stmts assignment-statements4297560
Ref: 16a34297560
Ref: reference/simple_stmts grammar-token-assignment-stmt4297700
Ref: 16a44297700
Ref: reference/simple_stmts grammar-token-target-list4297784
Ref: 16a54297784
Ref: reference/simple_stmts grammar-token-target4297836
Ref: 16a64297836
Ref: reference/simple_stmts attr-target-note4301017
Ref: 16a74301017
Ref: 赋值语句-Footnote-14304457
Node: 增强赋值语句4304506
Ref: reference/simple_stmts augassign4304606
Ref: 16a84304606
Ref: reference/simple_stmts augmented-assignment-statements4304606
Ref: 16a94304606
Ref: reference/simple_stmts grammar-token-augmented-assignment-stmt4304742
Ref: 16aa4304742
Ref: reference/simple_stmts grammar-token-augtarget4304830
Ref: 16ab4304830
Ref: reference/simple_stmts grammar-token-augop4304916
Ref: 16ac4304916
Node: 带标注的赋值语句4306444
Ref: reference/simple_stmts annassign4306544
Ref: 16ad4306544
Ref: reference/simple_stmts annotated-assignment-statements4306544
Ref: 16ae4306544
Ref: reference/simple_stmts grammar-token-annotated-assignment-stmt4306716
Ref: 16af4306716
Ref: 带标注的赋值语句-Footnote-14308485
Ref: 带标注的赋值语句-Footnote-24308534
Node: assert 语句4308583
Ref: reference/simple_stmts assert4308686
Ref: 23f4308686
Ref: reference/simple_stmts the-assert-statement4308686
Ref: 16b04308686
Ref: reference/simple_stmts grammar-token-assert-stmt4308800
Ref: 16b14308800
Node: pass 语句4309741
Ref: reference/simple_stmts pass4309842
Ref: 13744309842
Ref: reference/simple_stmts the-pass-statement4309842
Ref: 16b24309842
Ref: reference/simple_stmts grammar-token-pass-stmt4309885
Ref: 16b34309885
Node: del 语句4310223
Ref: reference/simple_stmts del4310324
Ref: 13a24310324
Ref: reference/simple_stmts the-del-statement4310324
Ref: 16b44310324
Ref: reference/simple_stmts grammar-token-del-stmt4310365
Ref: 16b54310365
Node: return 语句4311224
Ref: reference/simple_stmts return4311326
Ref: 2c84311326
Ref: reference/simple_stmts the-return-statement4311326
Ref: 16b64311326
Ref: reference/simple_stmts grammar-token-return-stmt4311373
Ref: 16b74311373
Node: yield 语句4312451
Ref: reference/simple_stmts the-yield-statement4312555
Ref: 16b84312555
Ref: reference/simple_stmts yield4312555
Ref: 2c74312555
Ref: reference/simple_stmts grammar-token-yield-stmt4312600
Ref: 16b94312600
Node: raise 语句4313305
Ref: reference/simple_stmts raise4313408
Ref: d0a4313408
Ref: reference/simple_stmts the-raise-statement4313408
Ref: 16ba4313408
Ref: reference/simple_stmts grammar-token-raise-stmt4313453
Ref: 16bb4313453
Node: break 语句4316733
Ref: reference/simple_stmts break4316839
Ref: 3fa4316839
Ref: reference/simple_stmts the-break-statement4316839
Ref: 16bc4316839
Ref: reference/simple_stmts grammar-token-break-stmt4316884
Ref: 16bd4316884
Node: continue 语句4317516
Ref: reference/simple_stmts continue4317623
Ref: 2bb4317623
Ref: reference/simple_stmts the-continue-statement4317623
Ref: 16be4317623
Ref: reference/simple_stmts grammar-token-continue-stmt4317676
Ref: 16bf4317676
Ref: reference/simple_stmts import4318155
Ref: ce74318155
Node: import 语句4318157
Ref: reference/simple_stmts from4318265
Ref: d0d4318265
Ref: reference/simple_stmts the-import-statement4318265
Ref: 16c04318265
Ref: reference/simple_stmts grammar-token-import-stmt4318314
Ref: 16c14318314
Ref: reference/simple_stmts grammar-token-module4318780
Ref: 16c24318780
Ref: reference/simple_stmts grammar-token-relative-module4318834
Ref: 16c34318834
Node: future 语句4323676
Ref: reference/simple_stmts future4323739
Ref: 16c44323739
Ref: reference/simple_stmts future-statements4323739
Ref: 16c54323739
Ref: reference/simple_stmts grammar-token-future-stmt4324176
Ref: 16c64324176
Ref: reference/simple_stmts grammar-token-feature4324452
Ref: 16c74324452
Ref: future 语句-Footnote-14326992
Ref: future 语句-Footnote-24327041
Node: global 语句4327090
Ref: reference/simple_stmts global4327198
Ref: 13784327198
Ref: reference/simple_stmts the-global-statement4327198
Ref: 16c84327198
Ref: reference/simple_stmts grammar-token-global-stmt4327247
Ref: 16c94327247
Node: nonlocal 语句4328680
Ref: reference/simple_stmts nonlocal4328766
Ref: d074328766
Ref: reference/simple_stmts the-nonlocal-statement4328766
Ref: 16ca4328766
Ref: reference/simple_stmts grammar-token-nonlocal-stmt4328819
Ref: 16cb4328819
Ref: nonlocal 语句-Footnote-14329752
Node: 复合语句4329801
Ref: reference/compound_stmts doc4329917
Ref: 16cc4329917
Ref: reference/compound_stmts compound4329917
Ref: 16cd4329917
Ref: reference/compound_stmts compound-statements4329917
Ref: 16ce4329917
Ref: reference/compound_stmts grammar-token-compound-stmt4331517
Ref: 16cf4331517
Ref: reference/compound_stmts grammar-token-suite4331874
Ref: 16d04331874
Ref: reference/compound_stmts grammar-token-statement4331950
Ref: 16d14331950
Ref: reference/compound_stmts grammar-token-stmt-list4332007
Ref: 16d24332007
Ref: reference/compound_stmts if4332516
Ref: eab4332516
Ref: reference/compound_stmts elif4332516
Ref: 13674332516
Node: if 语句4332656
Ref: reference/compound_stmts else4332735
Ref: 13684332735
Ref: reference/compound_stmts the-if-statement4332735
Ref: 16d34332735
Ref: reference/compound_stmts grammar-token-if-stmt4332822
Ref: 16d44332822
Node: while 语句4333354
Ref: reference/compound_stmts the-while-statement4333452
Ref: 16d54333452
Ref: reference/compound_stmts while4333452
Ref: 13614333452
Ref: reference/compound_stmts grammar-token-while-stmt4333582
Ref: 16d64333582
Node: for 语句4334154
Ref: reference/compound_stmts for4334253
Ref: cfa4334253
Ref: reference/compound_stmts the-for-statement4334253
Ref: 16d74334253
Ref: reference/compound_stmts grammar-token-for-stmt4334422
Ref: 16d84334422
Ref: reference/compound_stmts try4336987
Ref: e374336987
Ref: reference/compound_stmts except4336987
Ref: c104336987
Node: try 语句4336988
Ref: reference/compound_stmts finally4337086
Ref: 2bc4337086
Ref: reference/compound_stmts the-try-statement4337086
Ref: 16d94337086
Ref: reference/compound_stmts grammar-token-try-stmt4337210
Ref: 16da4337210
Ref: reference/compound_stmts grammar-token-try1-stmt4337251
Ref: 16db4337251
Ref: reference/compound_stmts grammar-token-try2-stmt4337437
Ref: 16dc4337437
Ref: reference/compound_stmts with4342271
Ref: 7da4342271
Ref: try 语句-Footnote-14342307
Node: with 语句4342487
Ref: reference/compound_stmts as4342587
Ref: 16dd4342587
Ref: reference/compound_stmts the-with-statement4342587
Ref: 16de4342587
Ref: reference/compound_stmts grammar-token-with-stmt4342922
Ref: 16df4342922
Ref: reference/compound_stmts grammar-token-with-item4342985
Ref: 16e04342985
Ref: reference/compound_stmts function4345599
Ref: 13904345599
Ref: with 语句-Footnote-14345635
Node: 函数定义4345684
Ref: reference/compound_stmts def4345783
Ref: e834345783
Ref: reference/compound_stmts function-definitions4345783
Ref: 16e14345783
Ref: reference/compound_stmts grammar-token-funcdef4345930
Ref: 16e24345930
Ref: reference/compound_stmts grammar-token-decorators4346081
Ref: 16e34346081
Ref: reference/compound_stmts grammar-token-decorator4346127
Ref: 16e44346127
Ref: reference/compound_stmts grammar-token-parameter-list4346196
Ref: 16e54346196
Ref: reference/compound_stmts grammar-token-parameter-list-no-posonly4346371
Ref: 16e64346371
Ref: reference/compound_stmts grammar-token-parameter-list-starargs4346532
Ref: 16e74346532
Ref: reference/compound_stmts grammar-token-parameter4346690
Ref: 16e84346690
Ref: reference/compound_stmts grammar-token-defparameter4346753
Ref: 16e94346753
Ref: reference/compound_stmts grammar-token-funcname4346815
Ref: 16ea4346815
Ref: 函数定义-Footnote-14352282
Ref: 函数定义-Footnote-24352450
Ref: 函数定义-Footnote-34352499
Ref: 函数定义-Footnote-44352548
Ref: 函数定义-Footnote-54352597
Ref: 函数定义-Footnote-64352646
Ref: 函数定义-Footnote-74352695
Node: 类定义4352744
Ref: reference/compound_stmts class4352841
Ref: d324352841
Ref: reference/compound_stmts class-definitions4352841
Ref: 16ec4352841
Ref: reference/compound_stmts grammar-token-classdef4352964
Ref: 16ed4352964
Ref: reference/compound_stmts grammar-token-inheritance4353040
Ref: 16ee4353040
Ref: reference/compound_stmts grammar-token-classname4353085
Ref: 16ef4353085
Ref: 类定义-Footnote-14355544
Ref: 类定义-Footnote-24355712
Ref: 类定义-Footnote-34355761
Ref: 类定义-Footnote-44355810
Ref: 类定义-Footnote-54355859
Node: 协程<2>4355908
Ref: reference/compound_stmts async4355984
Ref: 2d74355984
Ref: reference/compound_stmts coroutines4355984
Ref: 16f04355984
Node: 协程函数定义4356104
Ref: reference/compound_stmts async-def4356193
Ref: 3a94356193
Ref: reference/compound_stmts coroutine-function-definition4356193
Ref: 16f14356193
Ref: reference/compound_stmts grammar-token-async-funcdef4356242
Ref: 16f24356242
Node: async for 语句4357021
Ref: reference/compound_stmts async-for4357136
Ref: 3fd4357136
Ref: reference/compound_stmts the-async-for-statement4357136
Ref: 16f34357136
Ref: reference/compound_stmts grammar-token-async-for-stmt4357193
Ref: 16f44357193
Node: async with 语句4358091
Ref: reference/compound_stmts async-with4358179
Ref: 7364358179
Ref: reference/compound_stmts the-async-with-statement4358179
Ref: 16f54358179
Ref: reference/compound_stmts grammar-token-async-with-stmt4358238
Ref: 16f64358238
Ref: async with 语句-Footnote-14359336
Node: 顶级组件4359385
Ref: reference/toplevel_components doc4359513
Ref: 16f74359513
Ref: reference/toplevel_components top-level4359513
Ref: 16f84359513
Ref: reference/toplevel_components top-level-components4359513
Ref: 16f94359513
Node: 完整的 Python 程序4359864
Ref: reference/toplevel_components complete-python-programs4359957
Ref: 16fa4359957
Ref: reference/toplevel_components programs4359957
Ref: 16044359957
Node: 文件输入4361265
Ref: reference/toplevel_components file-input4361382
Ref: 16fb4361382
Ref: reference/toplevel_components id14361382
Ref: 16fc4361382
Ref: reference/toplevel_components grammar-token-file-input4361486
Ref: 16fd4361486
Node: 交互式输入4361741
Ref: reference/toplevel_components interactive4361850
Ref: 16fe4361850
Ref: reference/toplevel_components interactive-input4361850
Ref: 16ff4361850
Ref: reference/toplevel_components grammar-token-interactive-input4361947
Ref: 17004361947
Node: 表达式输入4362172
Ref: reference/toplevel_components expression-input4362260
Ref: 17014362260
Ref: reference/toplevel_components id24362260
Ref: 17024362260
Ref: reference/toplevel_components grammar-token-eval-input4362452
Ref: 17034362452
Node: 完整的語法規格書4362498
Ref: reference/grammar doc4362605
Ref: 17044362605
Ref: reference/grammar full-grammar-specification4362605
Ref: 17054362605
Ref: 完整的語法規格書-Footnote-14398380
Ref: 完整的語法規格書-Footnote-24398451
Ref: 完整的語法規格書-Footnote-34398523
Node: Python 標準函式庫 Standard Library4398588
Ref: library/index doc4398742
Ref: 17064398742
Ref: library/index library-index4398742
Ref: 13304398742
Ref: library/index the-python-standard-library4398742
Ref: 17074398742
Ref: Python 標準函式庫 Standard Library-Footnote-14401075
Node: 簡介<6>4401100
Ref: library/intro doc4401206
Ref: 17084401206
Ref: library/intro introduction4401206
Ref: 17094401206
Ref: library/intro library-intro4401206
Ref: 170a4401206
Node: 可用性之註釋4403718
Ref: library/intro availability4403782
Ref: 14914403782
Ref: library/intro notes-on-availability4403782
Ref: 170b4403782
Node: 內建函式4404140
Ref: library/functions doc4404267
Ref: 170c4404267
Ref: library/functions built-in-funcs4404267
Ref: cbe4404267
Ref: library/functions built-in-functions4404267
Ref: 170d4404267
Ref: library/functions abs4408782
Ref: 13f34408782
Ref: library/functions all4408985
Ref: e4a4408985
Ref: library/functions any4409299
Ref: e494409299
Ref: library/functions ascii4409628
Ref: e114409628
Ref: library/functions bin4409984
Ref: d084409984
Ref: library/functions bool4410636
Ref: 2bd4410636
Ref: library/functions breakpoint4411199
Ref: 40b4411199
Ref: library/functions func-bytearray4411981
Ref: 11f34411981
Ref: library/functions func-bytes4413308
Ref: 11f24413308
Ref: library/functions callable4413967
Ref: c164413967
Ref: library/functions chr4414520
Ref: 155a4414520
Ref: library/functions classmethod4414924
Ref: 3094414924
Ref: library/functions compile4416030
Ref: 2e74416030
Ref: library/functions complex4419603
Ref: 2c14419603
Ref: library/functions delattr4420995
Ref: 170e4420995
Ref: library/functions func-dict4421300
Ref: 17114421300
Ref: library/functions dir4421721
Ref: df94421721
Ref: library/functions divmod4424120
Ref: 28d4424120
Ref: library/functions enumerate4424681
Ref: ea74424681
Ref: library/functions eval4425542
Ref: c614425542
Ref: library/functions exec4427559
Ref: d0c4427559
Ref: library/functions filter4429950
Ref: cf84429950
Ref: library/functions float4430762
Ref: 1fd4430762
Ref: library/functions grammar-token-sign4431242
Ref: 17234431242
Ref: library/functions grammar-token-infinity4431281
Ref: 17244431281
Ref: library/functions grammar-token-nan4431329
Ref: 17254431329
Ref: library/functions grammar-token-numeric-value4431364
Ref: 17264431364
Ref: library/functions grammar-token-numeric-string4431422
Ref: 17274431422
Ref: library/functions format4432779
Ref: 5d54432779
Ref: library/functions func-frozenset4433722
Ref: 17154433722
Ref: library/functions getattr4434203
Ref: 54b4434203
Ref: library/functions globals4434823
Ref: f554434823
Ref: library/functions hasattr4435061
Ref: 54a4435061
Ref: library/functions hash4435381
Ref: aa34435381
Ref: library/functions help4435877
Ref: 1754435877
Ref: library/functions hex4436790
Ref: d2e4436790
Ref: library/functions id4437811
Ref: e4b4437811
Ref: library/functions input4438228
Ref: d334438228
Ref: library/functions int4439015
Ref: 2044439015
Ref: library/functions isinstance4440979
Ref: 5514440979
Ref: library/functions issubclass4441583
Ref: 5524441583
Ref: library/functions iter4441994
Ref: ded4441994
Ref: library/functions len4443252
Ref: 28b4443252
Ref: library/functions func-list4443640
Ref: 17164443640
Ref: library/functions locals4443871
Ref: 5564443871
Ref: library/functions map4444300
Ref: cf74444300
Ref: library/functions max4444813
Ref: 8f74444813
Ref: library/functions func-memoryview4445888
Ref: 170f4445888
Ref: library/functions min4446049
Ref: 8f64446049
Ref: library/functions next4447105
Ref: 7754447105
Ref: library/functions object4447358
Ref: 3d24447358
Ref: library/functions oct4447711
Ref: d2d4447711
Ref: library/functions open4448462
Ref: 16f4448462
Ref: library/functions filemodes4449882
Ref: 172c4449882
Ref: library/functions open-newline-parameter4454582
Ref: 172e4454582
Ref: library/functions ord4459367
Ref: 15594459367
Ref: library/functions pow4459638
Ref: 2cf4459638
Ref: library/functions print4461386
Ref: 9714461386
Ref: library/functions property4462598
Ref: 3084462598
Ref: library/functions func-range4465205
Ref: 17174465205
Ref: library/functions repr4465491
Ref: 8b94465491
Ref: library/functions reversed4466042
Ref: 2c64466042
Ref: library/functions round4466362
Ref: d354466362
Ref: library/functions func-set4467592
Ref: 17104467592
Ref: library/functions setattr4468057
Ref: 17124468057
Ref: library/functions slice4468668
Ref: ec84468668
Ref: library/functions sorted4469433
Ref: 5464469433
Ref: library/functions staticmethod4470970
Ref: 30a4470970
Ref: library/functions func-str4472117
Ref: 17134472117
Ref: library/functions sum4472467
Ref: 3164472467
Ref: library/functions super4473081
Ref: 5dd4473081
Ref: library/functions func-tuple4476468
Ref: 17144476468
Ref: library/functions type4476714
Ref: 6ff4476714
Ref: library/functions vars4478217
Ref: 116d4478217
Ref: library/functions zip4479046
Ref: cfc4479046
Ref: library/functions __import__4480998
Ref: 16b4480998
Ref: 內建函式-Footnote-14484016
Ref: 內建函式-Footnote-24484191
Ref: 內建函式-Footnote-34484240
Ref: 內建函式-Footnote-44484289
Ref: 內建函式-Footnote-54484366
Ref: 內建函式-Footnote-64484415
Node: 內建常數4484464
Ref: library/constants doc4484594
Ref: 173d4484594
Ref: library/constants built-in-constants4484594
Ref: 173e4484594
Ref: library/constants built-in-consts4484594
Ref: 173f4484594
Ref: library/constants False4484691
Ref: 48e4484691
Ref: library/constants True4484829
Ref: 5934484829
Ref: library/constants None4484965
Ref: 2034484965
Ref: library/constants NotImplemented4485195
Ref: 2024485195
Ref: library/constants Ellipsis4486631
Ref: 17404486631
Ref: library/constants __debug__4486802
Ref: 11374486802
Node: 由 site 模块添加的常量4487280
Ref: library/constants constants-added-by-the-site-module4487359
Ref: 17414487359
Ref: library/constants quit4487664
Ref: 17424487664
Ref: library/constants exit4487691
Ref: 17434487691
Ref: library/constants copyright4487930
Ref: 17444487930
Ref: library/constants credits4487950
Ref: 17454487950
Ref: library/constants license4488039
Ref: 17464488039
Node: 內建型態4488275
Ref: library/stdtypes doc4488408
Ref: 17474488408
Ref: library/stdtypes bltin-types4488408
Ref: 17484488408
Ref: library/stdtypes built-in-types4488408
Ref: 17494488408
Node: 逻辑值检测4489725
Ref: library/stdtypes truth4489825
Ref: 17184489825
Ref: library/stdtypes truth-value-testing4489825
Ref: 174a4489825
Ref: 逻辑值检测-Footnote-14490874
Node: 布尔运算 --- and or not4490986
Ref: library/stdtypes boolean4491101
Ref: 174b4491101
Ref: library/stdtypes boolean-operations-and-or-not4491101
Ref: 174c4491101
Node: 比较4492407
Ref: library/stdtypes comparisons4492541
Ref: 174d4492541
Ref: library/stdtypes stdcomparisons4492541
Ref: 174e4492541
Node: 数字类型 --- int float complex4494844
Ref: library/stdtypes numeric-types-int-float-complex4494966
Ref: 174f4494966
Ref: library/stdtypes typesnumeric4494966
Ref: 13534494966
Ref: 数字类型 --- int float complex-Footnote-14502605
Node: 整数类型的按位运算4502717
Ref: library/stdtypes bitstring-ops4502851
Ref: 17504502851
Ref: library/stdtypes bitwise-operations-on-integer-types4502851
Ref: 17514502851
Node: 整数类型的附加方法4504983
Ref: library/stdtypes additional-methods-on-integer-types4505153
Ref: 17524505153
Ref: library/stdtypes int bit_length4505347
Ref: 17534505347
Ref: library/stdtypes int to_bytes4506220
Ref: 17544506220
Ref: library/stdtypes int from_bytes4507517
Ref: 17564507517
Ref: library/stdtypes int as_integer_ratio4508643
Ref: 2bf4508643
Node: 浮点类型的附加方法4508879
Ref: library/stdtypes additional-methods-on-float4509049
Ref: 17574509049
Ref: library/stdtypes float as_integer_ratio4509234
Ref: 14574509234
Ref: library/stdtypes float is_integer4509461
Ref: 17584509461
Ref: library/stdtypes float hex4510050
Ref: 14584510050
Ref: library/stdtypes float fromhex4510265
Ref: 17594510265
Node: 数字类型的哈希运算4511767
Ref: library/stdtypes hashing-of-numeric-types4511901
Ref: 175a4511901
Ref: library/stdtypes numeric-hash4511901
Ref: 175b4511901
Node: 迭代器类型4516115
Ref: library/stdtypes iterator-types4516264
Ref: 175c4516264
Ref: library/stdtypes typeiter4516264
Ref: 159a4516264
Ref: library/stdtypes container __iter__4516596
Ref: 175d4516596
Ref: library/stdtypes iterator __iter__4517183
Ref: 175e4517183
Ref: library/stdtypes iterator __next__4517474
Ref: d2c4517474
Node: 生成器类型4518205
Ref: library/stdtypes generator-types4518272
Ref: 175f4518272
Ref: library/stdtypes id34518272
Ref: 17604518272
Node: 序列类型 --- list tuple range4518733
Ref: library/stdtypes sequence-types-list-tuple-range4518874
Ref: 17614518874
Ref: library/stdtypes typesseq4518874
Ref: 13a44518874
Node: 通用序列操作4519334
Ref: library/stdtypes common-sequence-operations4519452
Ref: 17624519452
Ref: library/stdtypes typesseq-common4519452
Ref: 17634519452
Ref: 通用序列操作-Footnote-14527435
Node: 不可变序列类型4527523
Ref: library/stdtypes immutable-sequence-types4527668
Ref: 17684527668
Ref: library/stdtypes typesseq-immutable4527668
Ref: 17694527668
Node: 可变序列类型4528135
Ref: library/stdtypes mutable-sequence-types4528281
Ref: 176a4528281
Ref: library/stdtypes typesseq-mutable4528281
Ref: 171a4528281
Node: List（串列）<2>4533634
Ref: library/stdtypes lists4533765
Ref: 176b4533765
Ref: library/stdtypes typesseq-list4533765
Ref: 172a4533765
Ref: library/stdtypes list4533938
Ref: 1f84533938
Ref: library/stdtypes list sort4535020
Ref: 5474535020
Node: 元组4537074
Ref: library/stdtypes tuples4537199
Ref: 176c4537199
Ref: library/stdtypes typesseq-tuple4537199
Ref: 173b4537199
Ref: library/stdtypes tuple4537518
Ref: 1a24537518
Node: range 对象4538933
Ref: library/stdtypes ranges4539030
Ref: 176d4539030
Ref: library/stdtypes typesseq-range4539030
Ref: 17354539030
Ref: library/stdtypes range4539196
Ref: 1f54539196
Ref: library/stdtypes range start4541054
Ref: 176e4541054
Ref: library/stdtypes range stop4541151
Ref: 176f4541151
Ref: library/stdtypes range step4541205
Ref: 17704541205
Ref: range 对象-Footnote-14543079
Node: 文本序列类型 --- str4543131
Ref: library/stdtypes text-sequence-type-str4543309
Ref: 17714543309
Ref: library/stdtypes textseq4543309
Ref: 13574543309
Ref: library/stdtypes str4544970
Ref: 2054544970
Node: 字符串的方法<2>4547136
Ref: library/stdtypes id54547263
Ref: 17734547263
Ref: library/stdtypes string-methods4547263
Ref: 13584547263
Ref: library/stdtypes str capitalize4548089
Ref: 17764548089
Ref: library/stdtypes str casefold4548402
Ref: 7a34548402
Ref: library/stdtypes str center4549028
Ref: 13d04549028
Ref: library/stdtypes str count4549323
Ref: 17784549323
Ref: library/stdtypes str encode4549534
Ref: 1704549534
Ref: library/stdtypes str endswith4550565
Ref: 8b44550565
Ref: library/stdtypes str expandtabs4550932
Ref: 17794550932
Ref: library/stdtypes str find4551954
Ref: 88e4551954
Ref: library/stdtypes str format4552477
Ref: 5d44552477
Ref: library/stdtypes str format_map4553902
Ref: 7a44553902
Ref: library/stdtypes str index4554457
Ref: 177a4554457
Ref: library/stdtypes str isalnum4554610
Ref: 177b4554610
Ref: library/stdtypes str isalpha4554979
Ref: 177c4554979
Ref: library/stdtypes str isascii4555405
Ref: 4404555405
Ref: library/stdtypes str isdecimal4555640
Ref: 177d4555640
Ref: library/stdtypes str isdigit4556043
Ref: 177e4556043
Ref: library/stdtypes str isidentifier4556493
Ref: 103b4556493
Ref: library/stdtypes str islower4557040
Ref: 17804557040
Ref: library/stdtypes str isnumeric4557227
Ref: 17814557227
Ref: library/stdtypes str isprintable4557700
Ref: 7a54557700
Ref: library/stdtypes str isspace4558302
Ref: 17824558302
Ref: library/stdtypes str istitle4558672
Ref: 17834558672
Ref: library/stdtypes str isupper4558930
Ref: 17844558930
Ref: library/stdtypes str join4559308
Ref: 17664559308
Ref: library/stdtypes str ljust4559611
Ref: 13cf4559611
Ref: library/stdtypes str lower4559901
Ref: 17774559901
Ref: library/stdtypes str lstrip4560108
Ref: 17854560108
Ref: library/stdtypes str maketrans4560874
Ref: 7a64560874
Ref: library/stdtypes str partition4561602
Ref: 8914561602
Ref: library/stdtypes str removeprefix4561920
Ref: 1664561920
Ref: library/stdtypes str removesuffix4562269
Ref: 1674562269
Ref: library/stdtypes str replace4562644
Ref: 17874562644
Ref: library/stdtypes str rfind4562876
Ref: 88f4562876
Ref: library/stdtypes str rindex4563181
Ref: 17884563181
Ref: library/stdtypes str rjust4563349
Ref: 13ce4563349
Ref: library/stdtypes str rpartition4563639
Ref: 17894563639
Ref: library/stdtypes str rsplit4563967
Ref: 178a4563967
Ref: library/stdtypes str rstrip4564441
Ref: 178b4564441
Ref: library/stdtypes str split4565186
Ref: 8904565186
Ref: library/stdtypes str splitlines4566718
Ref: 178c4566718
Ref: library/stdtypes str startswith4569285
Ref: 8b34569285
Ref: library/stdtypes str strip4569657
Ref: 178d4569657
Ref: library/stdtypes str swapcase4570551
Ref: 178e4570551
Ref: library/stdtypes str title4570749
Ref: 178f4570749
Ref: library/stdtypes str translate4571749
Ref: 17864571749
Ref: library/stdtypes str upper4572605
Ref: 17914572605
Ref: library/stdtypes str zfill4573053
Ref: 13d14573053
Ref: 字符串的方法<2>-Footnote-14573536
Ref: 字符串的方法<2>-Footnote-24573706
Ref: 字符串的方法<2>-Footnote-34573876
Ref: 字符串的方法<2>-Footnote-44574046
Node: printf 风格的字符串格式化4574216
Ref: library/stdtypes old-string-formatting4574343
Ref: 13594574343
Ref: library/stdtypes printf-style-string-formatting4574343
Ref: 17924574343
Ref: printf 风格的字符串格式化-Footnote-14583066
Ref: printf 风格的字符串格式化-Footnote-24583206
Node: 二进制序列类型 --- bytes bytearray memoryview4583255
Ref: library/stdtypes binary-sequence-types-bytes-bytearray-memoryview4583430
Ref: 17944583430
Ref: library/stdtypes binaryseq4583430
Ref: 171d4583430
Node: bytes 对象4584087
Ref: library/stdtypes bytes-objects4584213
Ref: 17954584213
Ref: library/stdtypes typebytes4584213
Ref: 171f4584213
Ref: library/stdtypes bytes4584522
Ref: 1724584522
Ref: library/stdtypes bytes fromhex4586629
Ref: 43e4586629
Ref: library/stdtypes bytes hex4587220
Ref: 7244587220
Node: bytearray 对象4589393
Ref: library/stdtypes bytearray-objects4589554
Ref: 17964589554
Ref: library/stdtypes typebytearray4589554
Ref: 171e4589554
Ref: library/stdtypes bytearray4589682
Ref: 1734589682
Ref: library/stdtypes bytearray fromhex4590635
Ref: 43f4590635
Ref: library/stdtypes bytearray hex4591257
Ref: 7254591257
Node: bytes 和 bytearray 操作4592353
Ref: library/stdtypes bytes-and-bytearray-operations4592536
Ref: 17974592536
Ref: library/stdtypes bytes-methods4592536
Ref: 171b4592536
Ref: library/stdtypes bytes count4593684
Ref: 17984593684
Ref: library/stdtypes bytearray count4593736
Ref: 17994593736
Ref: library/stdtypes bytes removeprefix4594145
Ref: 179a4594145
Ref: library/stdtypes bytearray removeprefix4594194
Ref: 179b4594194
Ref: library/stdtypes bytes removesuffix4594780
Ref: 179c4594780
Ref: library/stdtypes bytearray removesuffix4594829
Ref: 179d4594829
Ref: library/stdtypes bytes decode4595441
Ref: 1714595441
Ref: library/stdtypes bytearray decode4595508
Ref: 179e4595508
Ref: library/stdtypes bytes endswith4596675
Ref: 179f4596675
Ref: library/stdtypes bytearray endswith4596733
Ref: 17a04596733
Ref: library/stdtypes bytes find4597189
Ref: 17a14597189
Ref: library/stdtypes bytearray find4597240
Ref: 17a24597240
Ref: library/stdtypes bytes index4597987
Ref: 17a34597987
Ref: library/stdtypes bytearray index4598039
Ref: 17a44598039
Ref: library/stdtypes bytes join4598397
Ref: 17674598397
Ref: library/stdtypes bytearray join4598437
Ref: 17a54598437
Ref: library/stdtypes bytes maketrans4598832
Ref: cd44598832
Ref: library/stdtypes bytearray maketrans4598884
Ref: cd54598884
Ref: library/stdtypes bytes partition4599240
Ref: 17a74599240
Ref: library/stdtypes bytearray partition4599280
Ref: 17a84599280
Ref: library/stdtypes bytes replace4599723
Ref: 17a94599723
Ref: library/stdtypes bytearray replace4599775
Ref: 17aa4599775
Ref: library/stdtypes bytes rfind4600255
Ref: 17ab4600255
Ref: library/stdtypes bytearray rfind4600307
Ref: 17ac4600307
Ref: library/stdtypes bytes rindex4600807
Ref: 17ad4600807
Ref: library/stdtypes bytearray rindex4600860
Ref: 17ae4600860
Ref: library/stdtypes bytes rpartition4601227
Ref: 17af4601227
Ref: library/stdtypes bytearray rpartition4601268
Ref: 17b04601268
Ref: library/stdtypes bytes startswith4601726
Ref: 17b14601726
Ref: library/stdtypes bytearray startswith4601786
Ref: 17b24601786
Ref: library/stdtypes bytes translate4602244
Ref: 17a64602244
Ref: library/stdtypes bytearray translate4602301
Ref: d594602301
Ref: library/stdtypes bytes center4603220
Ref: 17b34603220
Ref: library/stdtypes bytearray center4603271
Ref: 17b44603271
Ref: library/stdtypes bytes ljust4603763
Ref: 17b54603763
Ref: library/stdtypes bytearray ljust4603813
Ref: 17b64603813
Ref: library/stdtypes bytes lstrip4604296
Ref: 17b74604296
Ref: library/stdtypes bytearray lstrip4604337
Ref: 17b84604337
Ref: library/stdtypes bytes rjust4605433
Ref: 17b94605433
Ref: library/stdtypes bytearray rjust4605483
Ref: 17ba4605483
Ref: library/stdtypes bytes rsplit4605966
Ref: 17bb4605966
Ref: library/stdtypes bytearray rsplit4606021
Ref: 17bc4606021
Ref: library/stdtypes bytes rstrip4606523
Ref: 17be4606523
Ref: library/stdtypes bytearray rstrip4606564
Ref: 17bf4606564
Ref: library/stdtypes bytes split4607640
Ref: 17c04607640
Ref: library/stdtypes bytearray split4607694
Ref: 17bd4607694
Ref: library/stdtypes bytes strip4609411
Ref: 17c14609411
Ref: library/stdtypes bytearray strip4609451
Ref: 17c24609451
Ref: library/stdtypes bytes capitalize4610521
Ref: 17c34610521
Ref: library/stdtypes bytearray capitalize4610559
Ref: 17c44610559
Ref: library/stdtypes bytes expandtabs4610957
Ref: 17c54610957
Ref: library/stdtypes bytearray expandtabs4611004
Ref: 17c64611004
Ref: library/stdtypes bytes isalnum4612237
Ref: 17c74612237
Ref: library/stdtypes bytearray isalnum4612272
Ref: 17c84612272
Ref: library/stdtypes bytes isalpha4612828
Ref: 17c94612828
Ref: library/stdtypes bytearray isalpha4612863
Ref: 17ca4612863
Ref: library/stdtypes bytes isascii4613300
Ref: 17cb4613300
Ref: library/stdtypes bytearray isascii4613335
Ref: 17cc4613335
Ref: library/stdtypes bytes isdigit4613565
Ref: 17cd4613565
Ref: library/stdtypes bytearray isdigit4613600
Ref: 17ce4613600
Ref: library/stdtypes bytes islower4613981
Ref: 17cf4613981
Ref: library/stdtypes bytearray islower4614016
Ref: 17d04614016
Ref: library/stdtypes bytes isspace4614551
Ref: 17d14614551
Ref: library/stdtypes bytearray isspace4614586
Ref: 17d24614586
Ref: library/stdtypes bytes istitle4614903
Ref: 17d34614903
Ref: library/stdtypes bytearray istitle4614938
Ref: 17d44614938
Ref: library/stdtypes bytes isupper4615322
Ref: 17d64615322
Ref: library/stdtypes bytearray isupper4615357
Ref: 17d74615357
Ref: library/stdtypes bytes lower4615892
Ref: 17d84615892
Ref: library/stdtypes bytearray lower4615925
Ref: 17d94615925
Ref: library/stdtypes bytes splitlines4616511
Ref: 17da4616511
Ref: library/stdtypes bytearray splitlines4616563
Ref: 17db4616563
Ref: library/stdtypes bytes swapcase4617482
Ref: 17dc4617482
Ref: library/stdtypes bytearray swapcase4617518
Ref: 17dd4617518
Ref: library/stdtypes bytes title4618375
Ref: 17d54618375
Ref: library/stdtypes bytearray title4618408
Ref: 17de4618408
Ref: library/stdtypes bytes upper4619989
Ref: 17df4619989
Ref: library/stdtypes bytearray upper4620022
Ref: 17e04620022
Ref: library/stdtypes bytes zfill4620608
Ref: 17e14620608
Ref: library/stdtypes bytearray zfill4620646
Ref: 17e24620646
Node: printf 风格的字节串格式化4621275
Ref: library/stdtypes bytes-formatting4621454
Ref: 7434621454
Ref: library/stdtypes printf-style-bytes-formatting4621454
Ref: 17e34621454
Ref: printf 风格的字节串格式化-Footnote-14630576
Ref: printf 风格的字节串格式化-Footnote-24630716
Ref: printf 风格的字节串格式化-Footnote-34630765
Node: 内存视图4630814
Ref: library/stdtypes memory-views4630958
Ref: 17e44630958
Ref: library/stdtypes typememoryview4630958
Ref: 172b4630958
Ref: library/stdtypes memoryview4631160
Ref: 3864631160
Ref: library/stdtypes memoryview __eq__4634746
Ref: 17e84634746
Ref: library/stdtypes memoryview tobytes4636686
Ref: 17e94636686
Ref: library/stdtypes memoryview hex4637730
Ref: 7264637730
Ref: library/stdtypes memoryview tolist4638259
Ref: 17e54638259
Ref: library/stdtypes memoryview toreadonly4638794
Ref: 17ea4638794
Ref: library/stdtypes memoryview release4639402
Ref: c0f4639402
Ref: library/stdtypes memoryview cast4640684
Ref: 17eb4640684
Ref: library/stdtypes memoryview obj4643617
Ref: 17ed4643617
Ref: library/stdtypes memoryview nbytes4643838
Ref: 17ee4643838
Ref: library/stdtypes memoryview readonly4644900
Ref: 17ef4644900
Ref: library/stdtypes memoryview format4644984
Ref: 17e74644984
Ref: library/stdtypes memoryview itemsize4645463
Ref: 17e64645463
Ref: library/stdtypes memoryview ndim4645835
Ref: 17f04645835
Ref: library/stdtypes memoryview shape4645945
Ref: 17f14645945
Ref: library/stdtypes memoryview strides4646181
Ref: 17f24646181
Ref: library/stdtypes memoryview suboffsets4646456
Ref: 17f34646456
Ref: library/stdtypes memoryview c_contiguous4646566
Ref: 17f44646566
Ref: library/stdtypes memoryview f_contiguous4646707
Ref: 17f54646707
Ref: library/stdtypes memoryview contiguous4646854
Ref: 17f64646854
Ref: 内存视图-Footnote-14647027
Node: 集合类型 --- set frozenset4647076
Ref: library/stdtypes set-types-set-frozenset4647246
Ref: 17f74647246
Ref: library/stdtypes types-set4647246
Ref: 17284647246
Ref: library/stdtypes set4648736
Ref: 1f64648736
Ref: library/stdtypes frozenset4648765
Ref: 1f74648765
Ref: library/stdtypes frozenset isdisjoint4649783
Ref: 17f84649783
Ref: library/stdtypes frozenset issubset4649999
Ref: 17f94649999
Ref: library/stdtypes frozenset issuperset4650294
Ref: 17fa4650294
Ref: library/stdtypes frozenset union4650591
Ref: 17fb4650591
Ref: library/stdtypes frozenset intersection4650797
Ref: 17fc4650797
Ref: library/stdtypes frozenset difference4651010
Ref: 17fd4651010
Ref: library/stdtypes frozenset symmetric_difference4651224
Ref: 17fe4651224
Ref: library/stdtypes frozenset copy4651465
Ref: 17ff4651465
Ref: library/stdtypes frozenset update4653649
Ref: 18004653649
Ref: library/stdtypes frozenset intersection_update4653801
Ref: 18014653801
Ref: library/stdtypes frozenset difference_update4653981
Ref: 18024653981
Ref: library/stdtypes frozenset symmetric_difference_update4654150
Ref: 18034654150
Ref: library/stdtypes frozenset add4654337
Ref: 18044654337
Ref: library/stdtypes frozenset remove4654422
Ref: 18054654422
Ref: library/stdtypes frozenset discard4654588
Ref: 18064654588
Ref: library/stdtypes frozenset pop4654695
Ref: 18074654695
Ref: library/stdtypes frozenset clear4654851
Ref: 18084654851
Node: 映射类型 --- dict4655432
Ref: library/stdtypes mapping-types-dict4655574
Ref: 18094655574
Ref: library/stdtypes typesmapping4655574
Ref: 40e4655574
Ref: library/stdtypes dict4656697
Ref: 1644656697
Ref: library/stdtypes dict clear4660904
Ref: 10894660904
Ref: library/stdtypes dict copy4660982
Ref: 5484660982
Ref: library/stdtypes dict fromkeys4661056
Ref: 180a4661056
Ref: library/stdtypes dict get4661551
Ref: 180b4661551
Ref: library/stdtypes dict items4661816
Ref: cf54661816
Ref: library/stdtypes dict keys4661982
Ref: cf44661982
Ref: library/stdtypes dict pop4662113
Ref: 180d4662113
Ref: library/stdtypes dict popitem4662377
Ref: 180e4662377
Ref: library/stdtypes dict setdefault4663117
Ref: a9e4663117
Ref: library/stdtypes dict update4663364
Ref: e8e4663364
Ref: library/stdtypes dict values4663836
Ref: cf64663836
Node: 字典视图对象4666343
Ref: library/stdtypes dict-views4666419
Ref: 180c4666419
Ref: library/stdtypes dictionary-view-objects4666419
Ref: 180f4666419
Node: 上下文管理器类型4669144
Ref: library/stdtypes context-manager-types4669275
Ref: 18114669275
Ref: library/stdtypes typecontextmanager4669275
Ref: 15c64669275
Ref: library/stdtypes contextmanager __enter__4669641
Ref: 18124669641
Ref: library/stdtypes contextmanager __exit__4670566
Ref: 18144670566
Node: GenericAlias 类型4672651
Ref: library/stdtypes generic-alias-type4672779
Ref: 18154672779
Ref: library/stdtypes types-genericalias4672779
Ref: fe54672779
Node: 标准的泛型集合类4676305
Ref: library/stdtypes standard-generic-collections4676415
Ref: 18174676415
Node: 泛型的特殊属性4678069
Ref: library/stdtypes special-attributes-of-generic-alias4678179
Ref: 18214678179
Ref: library/stdtypes genericalias __origin__4678303
Ref: 18224678303
Ref: library/stdtypes genericalias __args__4678459
Ref: 18164678459
Ref: library/stdtypes genericalias __parameters__4678723
Ref: 18234678723
Ref: 泛型的特殊属性-Footnote-14679337
Node: 其他内置类型4679386
Ref: library/stdtypes other-built-in-types4679502
Ref: 18244679502
Ref: library/stdtypes typesother4679502
Ref: 18254679502
Node: 模块4679824
Ref: library/stdtypes modules4679909
Ref: 18264679909
Ref: library/stdtypes typesmodules4679909
Ref: 18274679909
Node: 类与类实例4680939
Ref: library/stdtypes classes-and-class-instances4681039
Ref: 18284681039
Ref: library/stdtypes typesobjects4681039
Ref: 18294681039
Node: 函数4681178
Ref: library/stdtypes functions4681278
Ref: 182a4681278
Ref: library/stdtypes typesfunctions4681278
Ref: 182b4681278
Node: 方法4681671
Ref: library/stdtypes methods4681768
Ref: 182c4681768
Ref: library/stdtypes typesmethods4681768
Ref: 182d4681768
Node: 代码对象4683386
Ref: library/stdtypes bltin-code-objects4683489
Ref: 182e4683489
Ref: library/stdtypes code-objects4683489
Ref: 182f4683489
Node: 类型对象4684229
Ref: library/stdtypes bltin-type-objects4684335
Ref: 173c4684335
Ref: library/stdtypes type-objects4684335
Ref: 18304684335
Node: 空对象4684658
Ref: library/stdtypes bltin-null-object4684767
Ref: 18314684767
Ref: library/stdtypes the-null-object4684767
Ref: 18324684767
Node: 省略符对象4685047
Ref: library/stdtypes bltin-ellipsis-object4685159
Ref: 18334685159
Ref: library/stdtypes the-ellipsis-object4685159
Ref: 18344685159
Node: 未实现对象4685504
Ref: library/stdtypes bltin-notimplemented-object4685616
Ref: 18354685616
Ref: library/stdtypes the-notimplemented-object4685616
Ref: 18364685616
Node: 布尔值4685978
Ref: library/stdtypes bltin-boolean-values4686087
Ref: 17194686087
Ref: library/stdtypes boolean-values4686087
Ref: 18374686087
Node: 内部对象4686649
Ref: library/stdtypes internal-objects4686734
Ref: 18384686734
Ref: library/stdtypes typesinternal4686734
Ref: 18394686734
Node: 特殊属性4686924
Ref: library/stdtypes special-attributes4687012
Ref: 183a4687012
Ref: library/stdtypes specialattrs4687012
Ref: 183b4687012
Ref: library/stdtypes object __dict__4687222
Ref: 5f54687222
Ref: library/stdtypes instance __class__4687345
Ref: ecc4687345
Ref: library/stdtypes class __bases__4687408
Ref: ecb4687408
Ref: library/stdtypes definition __name__4687486
Ref: d2f4687486
Ref: library/stdtypes definition __qualname__4687589
Ref: 155b4687589
Ref: library/stdtypes class __mro__4687742
Ref: 173a4687742
Ref: library/stdtypes class mro4687863
Ref: 183c4687863
Ref: library/stdtypes class __subclasses__4688075
Ref: 183d4688075
Node: 內建的例外4688360
Ref: library/exceptions doc4688516
Ref: 183e4688516
Ref: library/exceptions bltin-exceptions4688516
Ref: f734688516
Ref: library/exceptions built-in-exceptions4688516
Ref: 183f4688516
Node: Exception context4690013
Ref: library/exceptions exception-context4690115
Ref: 18404690115
Node: 繼承自內建的例外4691700
Ref: library/exceptions inheriting-from-built-in-exceptions4691817
Ref: 18414691817
Ref: 繼承自內建的例外-Footnote-14692669
Node: 基类4692741
Ref: library/exceptions base-classes4692853
Ref: 18424692853
Ref: library/exceptions BaseException4692931
Ref: 2db4692931
Ref: library/exceptions BaseException args4693237
Ref: 18434693237
Ref: library/exceptions BaseException with_traceback4693531
Ref: 18444693531
Ref: library/exceptions Exception4693919
Ref: 2dc4693919
Ref: library/exceptions ArithmeticError4694070
Ref: 18454694070
Ref: library/exceptions BufferError4694280
Ref: 18474694280
Ref: library/exceptions LookupError4694387
Ref: 17904694387
Node: 具体异常4694627
Ref: library/exceptions concrete-exceptions4694721
Ref: 18484694721
Ref: library/exceptions AssertionError4694803
Ref: 2404694803
Ref: library/exceptions AttributeError4694891
Ref: 4a14694891
Ref: library/exceptions EOFError4695125
Ref: d344695125
Ref: library/exceptions FloatingPointError4695398
Ref: 18464695398
Ref: library/exceptions GeneratorExit4695458
Ref: df84695458
Ref: library/exceptions ImportError4695800
Ref: 16c4695800
Ref: library/exceptions ModuleNotFoundError4696289
Ref: 4a04696289
Ref: library/exceptions IndexError4696543
Ref: f364696543
Ref: library/exceptions KeyError4696754
Ref: 3e94696754
Ref: library/exceptions KeyboardInterrupt4696864
Ref: 2cc4696864
Ref: library/exceptions MemoryError4697209
Ref: f694697209
Ref: library/exceptions NameError4697717
Ref: e404697717
Ref: library/exceptions NotImplementedError4697917
Ref: 7044697917
Ref: library/exceptions OSError4698660
Ref: 3044698660
Ref: library/exceptions OSError errno4699614
Ref: 184b4699614
Ref: library/exceptions OSError winerror4699702
Ref: 184c4699702
Ref: library/exceptions OSError strerror4700242
Ref: 184d4700242
Ref: library/exceptions OSError filename4700451
Ref: 184e4700451
Ref: library/exceptions OSError filename24700477
Ref: 184f4700477
Ref: library/exceptions OverflowError4701366
Ref: a414701366
Ref: library/exceptions RecursionError4701781
Ref: 7274701781
Ref: library/exceptions ReferenceError4702061
Ref: f0f4702061
Ref: library/exceptions RuntimeError4702330
Ref: 3dc4702330
Ref: library/exceptions StopIteration4702514
Ref: 5814702514
Ref: library/exceptions StopAsyncIteration4703691
Ref: 114a4703691
Ref: library/exceptions SyntaxError4703883
Ref: 5594703883
Ref: library/exceptions SyntaxError filename4704364
Ref: 18504704364
Ref: library/exceptions SyntaxError lineno4704445
Ref: 18514704445
Ref: library/exceptions SyntaxError offset4704599
Ref: 18524704599
Ref: library/exceptions SyntaxError text4704756
Ref: 18534704756
Ref: library/exceptions IndentationError4705112
Ref: f394705112
Ref: library/exceptions TabError4705259
Ref: f384705259
Ref: library/exceptions SystemError4705423
Ref: 6f24705423
Ref: library/exceptions SystemExit4705999
Ref: 6f34705999
Ref: library/exceptions SystemExit code4707185
Ref: 18554707185
Ref: library/exceptions TypeError4707297
Ref: 1fe4707297
Ref: library/exceptions UnboundLocalError4708031
Ref: f374708031
Ref: library/exceptions UnicodeError4708240
Ref: d034708240
Ref: library/exceptions UnicodeError encoding4708597
Ref: 18564708597
Ref: library/exceptions UnicodeError reason4708666
Ref: 18574708666
Ref: library/exceptions UnicodeError object4708748
Ref: 18584708748
Ref: library/exceptions UnicodeError start4708833
Ref: 18594708833
Ref: library/exceptions UnicodeError end4708927
Ref: 185a4708927
Ref: library/exceptions UnicodeEncodeError4709031
Ref: 32a4709031
Ref: library/exceptions UnicodeDecodeError4709204
Ref: 32b4709204
Ref: library/exceptions UnicodeTranslateError4709377
Ref: 185b4709377
Ref: library/exceptions ValueError4709550
Ref: 16d4709550
Ref: library/exceptions ZeroDivisionError4709755
Ref: 1fa4709755
Ref: library/exceptions EnvironmentError4710060
Ref: a744710060
Ref: library/exceptions IOError4710090
Ref: a734710090
Ref: library/exceptions WindowsError4710111
Ref: a754710111
Ref: 具体异常-Footnote-14710231
Ref: 具体异常-Footnote-24710280
Node: OS 异常4710329
Ref: library/exceptions os-exceptions4710387
Ref: 184a4710387
Ref: library/exceptions BlockingIOError4710520
Ref: a784710520
Ref: library/exceptions BlockingIOError characters_written4710883
Ref: 185c4710883
Ref: library/exceptions ChildProcessError4711086
Ref: a794711086
Ref: library/exceptions ConnectionError4711216
Ref: 7d74711216
Ref: library/exceptions BrokenPipeError4711452
Ref: a7e4711452
Ref: library/exceptions ConnectionAbortedError4711707
Ref: a7f4711707
Ref: library/exceptions ConnectionRefusedError4711888
Ref: a804711888
Ref: library/exceptions ConnectionResetError4712069
Ref: a814712069
Ref: library/exceptions FileExistsError4712240
Ref: a394712240
Ref: library/exceptions FileNotFoundError4712385
Ref: 8ad4712385
Ref: library/exceptions InterruptedError4712518
Ref: 74c4712518
Ref: library/exceptions IsADirectoryError4712894
Ref: a7a4712894
Ref: library/exceptions NotADirectoryError4713067
Ref: a7b4713067
Ref: library/exceptions PermissionError4713361
Ref: 6f64713361
Ref: library/exceptions ProcessLookupError4713579
Ref: a7c4713579
Ref: library/exceptions TimeoutError4713700
Ref: a7d4713700
Ref: OS 异常-Footnote-14714030
Ref: OS 异常-Footnote-24714079
Node: 警告4714128
Ref: library/exceptions warning-categories-as-exceptions4714234
Ref: 185d4714234
Ref: library/exceptions warnings4714234
Ref: 185e4714234
Ref: library/exceptions Warning4714354
Ref: 18604714354
Ref: library/exceptions UserWarning4714406
Ref: 18614714406
Ref: library/exceptions DeprecationWarning4714477
Ref: 15a4714477
Ref: library/exceptions PendingDeprecationWarning4714870
Ref: 15c4714870
Ref: library/exceptions SyntaxWarning4715370
Ref: 2c94715370
Ref: library/exceptions RuntimeWarning4715449
Ref: 3e24715449
Ref: library/exceptions FutureWarning4715538
Ref: 4354715538
Ref: library/exceptions ImportWarning4715715
Ref: 6cf4715715
Ref: library/exceptions UnicodeWarning4715925
Ref: e4c4715925
Ref: library/exceptions BytesWarning4715999
Ref: 5af4715999
Ref: library/exceptions ResourceWarning4716107
Ref: 5ca4716107
Ref: 警告-Footnote-14716352
Ref: 警告-Footnote-24716401
Ref: 警告-Footnote-34716450
Node: 异常层次结构4716499
Ref: library/exceptions exception-hierarchy4716584
Ref: 18624716584
Ref: library/text stringservices4718812
Ref: 17724718812
Node: 文本處理 Text Processing 服務4718813
Ref: library/text doc4718978
Ref: 18634718978
Ref: library/text text-processing-services4718978
Ref: 18644718978
Ref: library/text textservices4718978
Ref: 17754718978
Node: string --- 常见的字符串操作4719980
Ref: library/string doc4720124
Ref: 18664720124
Ref: library/string module-string4720124
Ref: f64720124
Ref: library/string string-common-string-operations4720124
Ref: 18674720124
Ref: string --- 常见的字符串操作-Footnote-14720561
Node: 字符串常量4720626
Ref: library/string string-constants4720749
Ref: 18684720749
Ref: library/string string ascii_letters4720828
Ref: d244720828
Ref: library/string string ascii_lowercase4720999
Ref: 18694720999
Ref: library/string string ascii_uppercase4721151
Ref: 186a4721151
Ref: library/string string digits4721303
Ref: 186b4721303
Ref: library/string string hexdigits4721366
Ref: 186c4721366
Ref: library/string string octdigits4721444
Ref: 186d4721444
Ref: library/string string punctuation4721508
Ref: 186e4721508
Ref: library/string string printable4721679
Ref: 186f4721679
Ref: library/string string whitespace4721907
Ref: 18704721907
Node: 自定义字符串格式化4722086
Ref: library/string custom-string-formatting4722239
Ref: 18714722239
Ref: library/string string-formatting4722239
Ref: 17744722239
Ref: library/string string Formatter4722634
Ref: 8a34722634
Ref: library/string string Formatter format4722723
Ref: 5864722723
Ref: library/string string Formatter vformat4723061
Ref: 18724723061
Ref: library/string string Formatter parse4723660
Ref: 18734723660
Ref: library/string string Formatter get_field4724357
Ref: 18744724357
Ref: library/string string Formatter get_value4724893
Ref: 18754724893
Ref: library/string string Formatter check_unused_args4725944
Ref: 18764725944
Ref: library/string string Formatter format_field4726470
Ref: 18774726470
Ref: library/string string Formatter convert_field4726690
Ref: 18784726690
Ref: 自定义字符串格式化-Footnote-14727053
Ref: 自定义字符串格式化-Footnote-24727102
Node: 格式字符串语法4727151
Ref: library/string format-string-syntax4727304
Ref: 18794727304
Ref: library/string formatstrings4727304
Ref: de04727304
Ref: library/string grammar-token-replacement-field4728030
Ref: 187a4728030
Ref: library/string grammar-token-field-name4728118
Ref: 187b4728118
Ref: library/string grammar-token-arg-name4728205
Ref: 187c4728205
Ref: library/string grammar-token-attribute-name4728259
Ref: 187d4728259
Ref: library/string grammar-token-element-index4728302
Ref: 187e4728302
Ref: library/string grammar-token-index-string4728356
Ref: 187f4728356
Ref: library/string grammar-token-conversion4728424
Ref: 18804728424
Ref: library/string grammar-token-format-spec4728472
Ref: 18814728472
Node: 格式规格迷你语言4732107
Ref: library/string format-specification-mini-language4732210
Ref: 18834732210
Ref: library/string formatspec4732210
Ref: 5d84732210
Ref: library/string id14732943
Ref: 18844732943
Ref: library/string grammar-token-fill4733036
Ref: 18854733036
Ref: library/string grammar-token-align4733077
Ref: 18864733077
Ref: library/string grammar-token-sign4733124
Ref: 18874733124
Ref: library/string grammar-token-width4733165
Ref: 18884733165
Ref: library/string grammar-token-grouping-option4733197
Ref: 18894733197
Ref: library/string grammar-token-precision4733232
Ref: 188a4733232
Ref: library/string grammar-token-type4733264
Ref: 188b4733264
Ref: 格式规格迷你语言-Footnote-14744540
Ref: 格式规格迷你语言-Footnote-24744589
Node: 格式示例4744638
Ref: library/string format-examples4744741
Ref: 188c4744741
Ref: library/string formatexamples4744741
Ref: 18824744741
Node: 模板字符串4749128
Ref: library/string id24749266
Ref: 188d4749266
Ref: library/string template-strings4749266
Ref: 17934749266
Ref: library/string string Template4750650
Ref: 4f04750650
Ref: library/string string Template substitute4750751
Ref: 14334750751
Ref: library/string string Template safe_substitute4751177
Ref: 14344751177
Ref: library/string string Template template4752205
Ref: 188e4752205
Ref: 模板字符串-Footnote-14755702
Ref: 模板字符串-Footnote-24755751
Node: 辅助函数4755802
Ref: library/string helper-functions4755910
Ref: 188f4755910
Ref: library/string string capwords4755949
Ref: 18904755949
Node: re --- 正则表达式操作4756430
Ref: library/re doc4756622
Ref: 18914756622
Ref: library/re module-re4756622
Ref: dd4756622
Ref: library/re re-regular-expression-operations4756622
Ref: 18924756622
Ref: re --- 正则表达式操作-Footnote-14758982
Ref: re --- 正则表达式操作-Footnote-24759043
Node: 正则表达式语法4759083
Ref: library/re re-syntax4759190
Ref: 18934759190
Ref: library/re regular-expression-syntax4759190
Ref: 18944759190
Ref: 正则表达式语法-Footnote-14780146
Node: 模块内容4780188
Ref: library/re contents-of-module-re4780344
Ref: 189f4780344
Ref: library/re module-contents4780344
Ref: 18a04780344
Ref: library/re re compile4780723
Ref: 54c4780723
Ref: library/re re A4781688
Ref: 18994781688
Ref: library/re re ASCII4781703
Ref: 4ce4781703
Ref: library/re re DEBUG4782255
Ref: 18a44782255
Ref: library/re re I4782335
Ref: 189a4782335
Ref: library/re re IGNORECASE4782350
Ref: 18a54782350
Ref: library/re re L4783247
Ref: 189b4783247
Ref: library/re re LOCALE4783262
Ref: 4cf4783262
Ref: library/re re M4784008
Ref: 189c4784008
Ref: library/re re MULTILINE4784023
Ref: 18984784023
Ref: library/re re S4784415
Ref: 189d4784415
Ref: library/re re DOTALL4784430
Ref: 18974784430
Ref: library/re re X4784650
Ref: 189e4784650
Ref: library/re re VERBOSE4784665
Ref: 18a64784665
Ref: library/re re search4785412
Ref: c824785412
Ref: library/re re match4785702
Ref: c834785702
Ref: library/re re fullmatch4786297
Ref: 9824786297
Ref: library/re re split4786579
Ref: 4d04786579
Ref: library/re re findall4788213
Ref: a444788213
Ref: library/re re finditer4789225
Ref: 18a84789225
Ref: library/re re sub4789606
Ref: 5794789606
Ref: library/re re subn4792425
Ref: 8234792425
Ref: library/re re escape4792711
Ref: 58f4792711
Ref: library/re re purge4794098
Ref: 18a94794098
Ref: library/re re error4794163
Ref: 8244794163
Ref: library/re re error msg4794477
Ref: 8254794477
Ref: library/re re error pattern4794541
Ref: 8264794541
Ref: library/re re error pos4794609
Ref: 8274794609
Ref: library/re re error lineno4794714
Ref: 8284794714
Ref: library/re re error colno4794799
Ref: 8294794799
Node: 正则表达式对象 （正则对象）4794932
Ref: library/re re-objects4795079
Ref: 9834795079
Ref: library/re regular-expression-objects4795079
Ref: 18aa4795079
Ref: library/re re Pattern search4795230
Ref: 18a34795230
Ref: library/re re Pattern match4796426
Ref: 18a24796426
Ref: library/re re Pattern fullmatch4797229
Ref: 18ab4797229
Ref: library/re re Pattern split4797942
Ref: 18ac4797942
Ref: library/re re Pattern findall4798072
Ref: 18ad4798072
Ref: library/re re Pattern finditer4798316
Ref: 18ae4798316
Ref: library/re re Pattern sub4798568
Ref: 18af4798568
Ref: library/re re Pattern subn4798697
Ref: 18b04798697
Ref: library/re re Pattern flags4798828
Ref: 18b14798828
Ref: library/re re Pattern groups4799024
Ref: 18b24799024
Ref: library/re re Pattern groupindex4799098
Ref: 18b34799098
Ref: library/re re Pattern pattern4799270
Ref: 18b44799270
Node: 匹配对象4799503
Ref: library/re id24799659
Ref: 18b54799659
Ref: library/re match-objects4799659
Ref: 9844799659
Ref: library/re re Match expand4800029
Ref: 18b64800029
Ref: library/re re Match group4800418
Ref: 18b74800418
Ref: library/re re Match __getitem__4802411
Ref: 18b84802411
Ref: library/re re Match groups4802857
Ref: 18b94802857
Ref: library/re re Match groupdict4803623
Ref: 18ba4803623
Ref: library/re re Match start4804022
Ref: 18bb4804022
Ref: library/re re Match end4804062
Ref: 18bc4804062
Ref: library/re re Match span4805061
Ref: 18bd4805061
Ref: library/re re Match pos4805327
Ref: 18be4805327
Ref: library/re re Match endpos4805558
Ref: 18bf4805558
Ref: library/re re Match lastindex4805795
Ref: 18c04805795
Ref: library/re re Match lastgroup4806124
Ref: 18c14806124
Ref: library/re re Match re4806250
Ref: 18c24806250
Ref: library/re re Match string4806441
Ref: 18c34806441
Node: 正则表达式例子4806683
Ref: library/re re-examples4806790
Ref: cbf4806790
Ref: library/re regular-expression-examples4806790
Ref: 18c44806790
Node: 检查对子4807103
Ref: library/re checking-for-a-pair4807194
Ref: 18c54807194
Node: 模拟 scanf4809126
Ref: library/re simulating-scanf4809241
Ref: 18c64809241
Node: search vs match4811234
Ref: library/re id34811358
Ref: 18c74811358
Ref: library/re search-vs-match4811358
Ref: 18a74811358
Node: 制作一个电话本4812411
Ref: library/re making-a-phonebook4812535
Ref: 18c84812535
Node: 文字整理4814613
Ref: library/re text-munging4814740
Ref: 18c94814740
Node: 查找所有副词4815462
Ref: library/re finding-all-adverbs4815601
Ref: 18ca4815601
Node: 查找所有的副词及其位置4816036
Ref: library/re finding-all-adverbs-and-their-positions4816184
Ref: 18cb4816184
Node: 原始字符串标记4816807
Ref: library/re raw-string-notation4816961
Ref: 18cc4816961
Node: 写一个词法分析器4817768
Ref: library/re writing-a-tokenizer4817880
Ref: 18cd4817880
Ref: library/re frie094821200
Ref: 18954821200
Ref: 写一个词法分析器-Footnote-14821440
Node: difflib --- 计算差异的辅助工具4821495
Ref: library/difflib doc4821692
Ref: 18ce4821692
Ref: library/difflib difflib-helpers-for-computing-deltas4821692
Ref: 18cf4821692
Ref: library/difflib module-difflib4821692
Ref: 364821692
Ref: library/difflib difflib Differ4823905
Ref: 18d04823905
Ref: library/difflib difflib HtmlDiff4824957
Ref: 18d14824957
Ref: library/difflib difflib HtmlDiff __init__4825263
Ref: 18d24825263
Ref: library/difflib difflib HtmlDiff make_file4826027
Ref: 7bc4826027
Ref: library/difflib difflib HtmlDiff make_table4827549
Ref: 18d44827549
Ref: library/difflib difflib context_diff4828071
Ref: 18d54828071
Ref: library/difflib difflib get_close_matches4829913
Ref: 18d94829913
Ref: library/difflib difflib ndiff4831053
Ref: 18d34831053
Ref: library/difflib difflib restore4832628
Ref: 18dc4832628
Ref: library/difflib difflib unified_diff4833352
Ref: 18de4833352
Ref: library/difflib difflib diff_bytes4835169
Ref: 7bd4835169
Ref: library/difflib difflib IS_LINE_JUNK4836060
Ref: 18da4836060
Ref: library/difflib difflib IS_CHARACTER_JUNK4836366
Ref: 18db4836366
Ref: difflib --- 计算差异的辅助工具-Footnote-14837020
Ref: difflib --- 计算差异的辅助工具-Footnote-24837086
Ref: difflib --- 计算差异的辅助工具-Footnote-34837175
Node: SequenceMatcher 对象4837207
Ref: library/difflib sequence-matcher4837339
Ref: 18df4837339
Ref: library/difflib sequencematcher-objects4837339
Ref: 18e04837339
Ref: library/difflib difflib SequenceMatcher4837460
Ref: a304837460
Ref: library/difflib difflib SequenceMatcher set_seqs4838862
Ref: 18e14838862
Ref: library/difflib difflib SequenceMatcher set_seq14839260
Ref: 18e34839260
Ref: library/difflib difflib SequenceMatcher set_seq24839388
Ref: 18e24839388
Ref: library/difflib difflib SequenceMatcher find_longest_match4839516
Ref: 10414839516
Ref: library/difflib difflib SequenceMatcher get_matching_blocks4841530
Ref: 18e44841530
Ref: library/difflib difflib SequenceMatcher get_opcodes4842419
Ref: 18e54842419
Ref: library/difflib difflib SequenceMatcher get_grouped_opcodes4844336
Ref: 18e64844336
Ref: library/difflib difflib SequenceMatcher ratio4844714
Ref: 18e74844714
Ref: library/difflib difflib SequenceMatcher quick_ratio4845670
Ref: 18e84845670
Ref: library/difflib difflib SequenceMatcher real_quick_ratio4845782
Ref: 18e94845782
Node: SequenceMatcher 的示例4846281
Ref: library/difflib id14846435
Ref: 18ea4846435
Ref: library/difflib sequencematcher-examples4846435
Ref: 18eb4846435
Ref: SequenceMatcher 的示例-Footnote-14848137
Node: Differ 对象4848190
Ref: library/difflib differ-objects4848335
Ref: 18ec4848335
Ref: library/difflib id24848335
Ref: 18ed4848335
Ref: library/difflib difflib Differ compare4849669
Ref: 18dd4849669
Node: Differ 示例4850161
Ref: library/difflib differ-example4850307
Ref: 18ee4850307
Ref: library/difflib differ-examples4850307
Ref: 18ef4850307
Node: difflib 的命令行接口4852574
Ref: library/difflib a-command-line-interface-to-difflib4852698
Ref: 18f04852698
Ref: library/difflib difflib-interface4852698
Ref: 18d84852698
Node: textwrap --- 文本自动换行与填充4855449
Ref: library/textwrap doc4855651
Ref: 18f14855651
Ref: library/textwrap module-textwrap4855651
Ref: 10a4855651
Ref: library/textwrap textwrap-text-wrapping-and-filling4855651
Ref: 18f24855651
Ref: library/textwrap textwrap wrap4856159
Ref: f864856159
Ref: library/textwrap textwrap fill4856854
Ref: f874856854
Ref: library/textwrap textwrap shorten4857474
Ref: 9d34857474
Ref: library/textwrap textwrap dedent4858634
Ref: 18f84858634
Ref: library/textwrap textwrap indent4859473
Ref: b804859473
Ref: library/textwrap textwrap TextWrapper4860786
Ref: 9d04860786
Ref: library/textwrap textwrap TextWrapper width4861401
Ref: 18fa4861401
Ref: library/textwrap textwrap TextWrapper expand_tabs4861674
Ref: 18f54861674
Ref: library/textwrap textwrap TextWrapper tabsize4861864
Ref: 18f44861864
Ref: library/textwrap textwrap TextWrapper replace_whitespace4862140
Ref: 18f74862140
Ref: library/textwrap textwrap TextWrapper drop_whitespace4863045
Ref: 18f64863045
Ref: library/textwrap textwrap TextWrapper initial_indent4863429
Ref: 18fb4863429
Ref: library/textwrap textwrap TextWrapper subsequent_indent4863647
Ref: 18fc4863647
Ref: library/textwrap textwrap TextWrapper fix_sentence_endings4863871
Ref: 18fd4863871
Ref: library/textwrap textwrap TextWrapper break_long_words4864922
Ref: 18f94864922
Ref: library/textwrap textwrap TextWrapper break_on_hyphens4865370
Ref: 18fe4865370
Ref: library/textwrap textwrap TextWrapper max_lines4865847
Ref: 9d14865847
Ref: library/textwrap textwrap TextWrapper placeholder4866076
Ref: 9d24866076
Ref: library/textwrap textwrap TextWrapper wrap4866344
Ref: 18f34866344
Ref: library/textwrap textwrap TextWrapper fill4866766
Ref: 18ff4866766
Ref: textwrap --- 文本自动换行与填充-Footnote-14866959
Node: unicodedata --- Unicode 数据库4867026
Ref: library/unicodedata doc4867228
Ref: 19004867228
Ref: library/unicodedata module-unicodedata4867228
Ref: 1234867228
Ref: library/unicodedata unicodedata-unicode-database4867228
Ref: 19014867228
Ref: library/unicodedata unicodedata lookup4867714
Ref: a9d4867714
Ref: library/unicodedata unicodedata name4868001
Ref: 19024868001
Ref: library/unicodedata unicodedata decimal4868225
Ref: 19034868225
Ref: library/unicodedata unicodedata digit4868463
Ref: 19044868463
Ref: library/unicodedata unicodedata numeric4868696
Ref: cc44868696
Ref: library/unicodedata unicodedata category4868931
Ref: 19054868931
Ref: library/unicodedata unicodedata bidirectional4869036
Ref: 19064869036
Ref: library/unicodedata unicodedata combining4869203
Ref: 19074869203
Ref: library/unicodedata unicodedata east_asian_width4869369
Ref: 19084869369
Ref: library/unicodedata unicodedata mirrored4869485
Ref: 19094869485
Ref: library/unicodedata unicodedata decomposition4869701
Ref: 190a4869701
Ref: library/unicodedata unicodedata normalize4869880
Ref: 11e44869880
Ref: library/unicodedata unicodedata is_normalized4871460
Ref: 3704871460
Ref: library/unicodedata unicodedata unidata_version4871734
Ref: 190b4871734
Ref: library/unicodedata unicodedata ucd_3_2_04871831
Ref: e614871831
Ref: unicodedata --- Unicode 数据库-Footnote-14872592
Ref: unicodedata --- Unicode 数据库-Footnote-24872642
Ref: unicodedata --- Unicode 数据库-Footnote-34872688
Ref: unicodedata --- Unicode 数据库-Footnote-44872764
Node: stringprep --- 因特网字符串预备4872843
Ref: library/stringprep doc4873037
Ref: 190c4873037
Ref: library/stringprep module-stringprep4873037
Ref: f74873037
Ref: library/stringprep stringprep-internet-string-preparation4873037
Ref: 190d4873037
Ref: library/stringprep stringprep in_table_a14874709
Ref: 190e4874709
Ref: library/stringprep stringprep in_table_b14874833
Ref: 190f4874833
Ref: library/stringprep stringprep map_table_b24874945
Ref: 19104874945
Ref: library/stringprep stringprep map_table_b34875095
Ref: 19114875095
Ref: library/stringprep stringprep in_table_c114875245
Ref: 19124875245
Ref: library/stringprep stringprep in_table_c124875357
Ref: 19134875357
Ref: library/stringprep stringprep in_table_c11_c124875473
Ref: 19144875473
Ref: library/stringprep stringprep in_table_c214875609
Ref: 19154875609
Ref: library/stringprep stringprep in_table_c224875721
Ref: 19164875721
Ref: library/stringprep stringprep in_table_c21_c224875837
Ref: 19174875837
Ref: library/stringprep stringprep in_table_c34875973
Ref: 19184875973
Ref: library/stringprep stringprep in_table_c44876076
Ref: 19194876076
Ref: library/stringprep stringprep in_table_c54876182
Ref: 191a4876182
Ref: library/stringprep stringprep in_table_c64876282
Ref: 191b4876282
Ref: library/stringprep stringprep in_table_c74876394
Ref: 191c4876394
Ref: library/stringprep stringprep in_table_c84876509
Ref: 191d4876509
Ref: library/stringprep stringprep in_table_c94876630
Ref: 191e4876630
Ref: library/stringprep stringprep in_table_d14876733
Ref: 191f4876733
Ref: library/stringprep stringprep in_table_d24876865
Ref: 19204876865
Ref: stringprep --- 因特网字符串预备-Footnote-14877024
Ref: stringprep --- 因特网字符串预备-Footnote-24877093
Ref: stringprep --- 因特网字符串预备-Footnote-34877142
Node: readline --- GNU readline 接口4877191
Ref: library/readline doc4877396
Ref: 19214877396
Ref: library/readline module-readline4877396
Ref: de4877396
Ref: library/readline readline-gnu-readline-interface4877396
Ref: 19224877396
Ref: readline --- GNU readline 接口-Footnote-14879150
Node: 初始化文件4879220
Ref: library/readline init-file4879325
Ref: 19234879325
Ref: library/readline readline parse_and_bind4879425
Ref: 19244879425
Ref: library/readline readline read_init_file4879598
Ref: 19254879598
Node: 行缓冲区4879813
Ref: library/readline line-buffer4879939
Ref: 19264879939
Ref: library/readline readline get_line_buffer4880022
Ref: 19274880022
Ref: library/readline readline insert_text4880145
Ref: 19284880145
Ref: library/readline readline redisplay4880338
Ref: 19294880338
Node: 历史文件4880503
Ref: library/readline history-file4880626
Ref: 192a4880626
Ref: library/readline readline read_history_file4880709
Ref: 192b4880709
Ref: library/readline readline write_history_file4880941
Ref: 192c4880941
Ref: library/readline readline append_history_file4881181
Ref: 82b4881181
Ref: library/readline readline get_history_length4881566
Ref: 192d4881566
Ref: library/readline readline set_history_length4881609
Ref: 192e4881609
Node: 历史列表4881921
Ref: library/readline history-list4882044
Ref: 192f4882044
Ref: library/readline readline clear_history4882133
Ref: 19304882133
Ref: library/readline readline get_current_history_length4882354
Ref: 19314882354
Ref: library/readline readline get_history_item4882573
Ref: 19324882573
Ref: library/readline readline remove_history_item4882775
Ref: 19334882775
Ref: library/readline readline replace_history_item4882981
Ref: 19344882981
Ref: library/readline readline add_history4883196
Ref: 19354883196
Ref: library/readline readline set_auto_history4883381
Ref: 66e4883381
Node: 启动钩子4883821
Ref: library/readline startup-hooks4883942
Ref: 19364883942
Ref: library/readline readline set_startup_hook4883981
Ref: 19374883981
Ref: library/readline readline set_pre_input_hook4884367
Ref: 19384884367
Node: Completion4884879
Ref: library/readline completion4884997
Ref: 19394884997
Ref: library/readline readline set_completer4885428
Ref: 193a4885428
Ref: library/readline readline get_completer4886155
Ref: 193b4886155
Ref: library/readline readline get_completion_type4886275
Ref: 193c4886275
Ref: library/readline readline get_begidx4886458
Ref: 193d4886458
Ref: library/readline readline get_endidx4886493
Ref: 193e4886493
Ref: library/readline readline set_completer_delims4886709
Ref: 193f4886709
Ref: library/readline readline get_completer_delims4886760
Ref: 19404886760
Ref: library/readline readline set_completion_display_matches_hook4887039
Ref: 19414887039
Node: 示例<2>4887576
Ref: library/readline example4887673
Ref: 19424887673
Ref: library/readline readline-example4887673
Ref: 19434887673
Node: rlcompleter --- GNU readline 的补全函数4890197
Ref: library/rlcompleter doc4890354
Ref: 19454890354
Ref: library/rlcompleter module-rlcompleter4890354
Ref: e14890354
Ref: library/rlcompleter rlcompleter-completion-function-for-gnu-readline4890354
Ref: 19464890354
Ref: rlcompleter --- GNU readline 的补全函数-Footnote-14891724
Node: Completer 对象4891794
Ref: library/rlcompleter completer-objects4891891
Ref: 19474891891
Ref: library/rlcompleter id14891891
Ref: 19484891891
Ref: library/rlcompleter rlcompleter Completer complete4891979
Ref: 19494891979
Node: 二进制数据服务4892710
Ref: library/binary doc4892872
Ref: 194a4892872
Ref: library/binary binary-data-services4892872
Ref: 194b4892872
Ref: library/binary binaryservices4892872
Ref: 18654892872
Node: struct --- 将字节串解读为打包的二进制数据4893692
Ref: library/struct doc4893859
Ref: 194c4893859
Ref: library/struct module-struct4893859
Ref: f84893859
Ref: library/struct struct-interpret-bytes-as-packed-binary-data4893859
Ref: 194d4893859
Ref: struct --- 将字节串解读为打包的二进制数据-Footnote-14895508
Node: 函数和异常4895573
Ref: library/struct functions-and-exceptions4895705
Ref: 19514895705
Ref: library/struct struct error4895793
Ref: d7c4895793
Ref: library/struct struct pack4895919
Ref: cd64895919
Ref: library/struct struct pack_into4896144
Ref: 19524896144
Ref: library/struct struct unpack4896418
Ref: 14374896418
Ref: library/struct struct unpack_from4896754
Ref: 19534896754
Ref: library/struct struct iter_unpack4897110
Ref: 9be4897110
Ref: library/struct struct calcsize4897570
Ref: 10c54897570
Node: 格式字符串4897757
Ref: library/struct format-strings4897901
Ref: 19544897901
Ref: library/struct struct-format-strings4897901
Ref: 194e4897901
Node: 字节顺序，大小和对齐方式4898310
Ref: library/struct byte-order-size-and-alignment4898419
Ref: 19564898419
Ref: library/struct struct-alignment4898419
Ref: 194f4898419
Ref: 字节顺序，大小和对齐方式-Footnote-14901473
Node: 格式字符4901517
Ref: library/struct format-characters4901644
Ref: 19554901644
Ref: library/struct id14901644
Ref: 19584901644
Ref: 格式字符-Footnote-14912170
Ref: 格式字符-Footnote-24912242
Node: 示例<3>4912318
Ref: library/struct examples4912400
Ref: 19594912400
Ref: library/struct struct-examples4912400
Ref: 19574912400
Node: 类4914069
Ref: library/struct classes4914189
Ref: 195a4914189
Ref: library/struct struct-objects4914189
Ref: 195b4914189
Ref: library/struct struct Struct4914266
Ref: 19504914266
Ref: library/struct struct Struct pack4914919
Ref: 195c4914919
Ref: library/struct struct Struct pack_into4915103
Ref: 195e4915103
Ref: library/struct struct Struct unpack4915253
Ref: 195f4915253
Ref: library/struct struct Struct unpack_from4915445
Ref: 19604915445
Ref: library/struct struct Struct iter_unpack4915695
Ref: 9bf4915695
Ref: library/struct struct Struct format4915929
Ref: 58c4915929
Ref: library/struct struct Struct size4916133
Ref: 195d4916133
Node: codecs --- 编解码器注册和相关基类4916308
Ref: library/codecs doc4916475
Ref: 19614916475
Ref: library/codecs codecs-codec-registry-and-base-classes4916475
Ref: 19624916475
Ref: library/codecs ietf-rfc-17004916475
Ref: 19634916475
Ref: library/codecs module-codecs4916475
Ref: 1b4916475
Ref: library/codecs codecs encode4917383
Ref: 8ef4917383
Ref: library/codecs codecs decode4917888
Ref: 8f04917888
Ref: library/codecs codecs lookup4918458
Ref: 2384918458
Ref: library/codecs codecs CodecInfo4918944
Ref: 19654918944
Ref: library/codecs codecs CodecInfo name4919235
Ref: 19664919235
Ref: library/codecs codecs CodecInfo encode4919282
Ref: 19674919282
Ref: library/codecs codecs CodecInfo decode4919306
Ref: 19684919306
Ref: library/codecs codecs CodecInfo incrementalencoder4919627
Ref: 196c4919627
Ref: library/codecs codecs CodecInfo incrementaldecoder4919663
Ref: 196d4919663
Ref: library/codecs codecs CodecInfo streamwriter4919971
Ref: 19704919971
Ref: library/codecs codecs CodecInfo streamreader4920001
Ref: 19714920001
Ref: library/codecs codecs getencoder4920427
Ref: 19744920427
Ref: library/codecs codecs getdecoder4920607
Ref: 19754920607
Ref: library/codecs codecs getincrementalencoder4920787
Ref: 19764920787
Ref: library/codecs codecs getincrementaldecoder4921046
Ref: 19774921046
Ref: library/codecs codecs getreader4921305
Ref: 19784921305
Ref: library/codecs codecs getwriter4921520
Ref: 19794921520
Ref: library/codecs codecs register4921818
Ref: 197a4921818
Ref: library/codecs codecs open4922685
Ref: 10c34922685
Ref: library/codecs codecs EncodedFile4923813
Ref: 197c4923813
Ref: library/codecs codecs iterencode4924589
Ref: 197d4924589
Ref: library/codecs codecs iterdecode4925086
Ref: 197e4925086
Ref: library/codecs codecs BOM4925745
Ref: 197f4925745
Ref: library/codecs codecs BOM_BE4925766
Ref: 19804925766
Ref: library/codecs codecs BOM_LE4925790
Ref: 19814925790
Ref: library/codecs codecs BOM_UTF84925814
Ref: 19824925814
Ref: library/codecs codecs BOM_UTF164925840
Ref: 19834925840
Ref: library/codecs codecs BOM_UTF16_BE4925867
Ref: 19844925867
Ref: library/codecs codecs BOM_UTF16_LE4925897
Ref: 19854925897
Ref: library/codecs codecs BOM_UTF324925927
Ref: 19864925927
Ref: library/codecs codecs BOM_UTF32_BE4925954
Ref: 19874925954
Ref: library/codecs codecs BOM_UTF32_LE4925984
Ref: 19884925984
Ref: codecs --- 编解码器注册和相关基类-Footnote-14927116
Node: 编解码器基类4927181
Ref: library/codecs codec-base-classes4927312
Ref: 19644927312
Ref: library/codecs id14927312
Ref: 19894927312
Ref: library/codecs surrogateescape4927861
Ref: 198a4927861
Node: 错误处理方案4927988
Ref: library/codecs error-handlers4928097
Ref: 14934928097
Ref: library/codecs id24928097
Ref: 198b4928097
Ref: library/codecs codecs register_error4931903
Ref: eb94931903
Ref: library/codecs codecs lookup_error4933358
Ref: eba4933358
Ref: library/codecs codecs strict_errors4933627
Ref: 198c4933627
Ref: library/codecs codecs replace_errors4933795
Ref: 198e4933795
Ref: library/codecs codecs ignore_errors4934065
Ref: 198d4934065
Ref: library/codecs codecs xmlcharrefreplace_errors4934239
Ref: 198f4934239
Ref: library/codecs codecs backslashreplace_errors4934484
Ref: 19904934484
Ref: library/codecs codecs namereplace_errors4934712
Ref: 19914934712
Ref: 错误处理方案-Footnote-14935007
Node: 无状态的编码和解码4935056
Ref: library/codecs codec-objects4935201
Ref: 196b4935201
Ref: library/codecs stateless-encoding-and-decoding4935201
Ref: 19924935201
Ref: library/codecs codecs Codec encode4935380
Ref: 19694935380
Ref: library/codecs codecs Codec decode4936085
Ref: 196a4936085
Node: 增量式的编码和解码4936977
Ref: library/codecs incremental-encoding-and-decoding4937128
Ref: 19934937128
Node: IncrementalEncoder 对象4937873
Ref: library/codecs incremental-encoder-objects4937996
Ref: 19964937996
Ref: library/codecs incrementalencoder-objects4937996
Ref: 19974937996
Ref: library/codecs codecs IncrementalEncoder4938273
Ref: 196e4938273
Ref: library/codecs codecs IncrementalEncoder encode4938996
Ref: 19944938996
Ref: library/codecs codecs IncrementalEncoder reset4939279
Ref: 19984939279
Ref: library/codecs codecs IncrementalEncoder getstate4939530
Ref: 19994939530
Ref: library/codecs codecs IncrementalEncoder setstate4939867
Ref: 199a4939867
Node: IncrementalDecoder 对象4940047
Ref: library/codecs incremental-decoder-objects4940170
Ref: 199b4940170
Ref: library/codecs incrementaldecoder-objects4940170
Ref: 199c4940170
Ref: library/codecs codecs IncrementalDecoder4940447
Ref: 196f4940447
Ref: library/codecs codecs IncrementalDecoder decode4941170
Ref: 19954941170
Ref: library/codecs codecs IncrementalDecoder reset4941777
Ref: 199d4941777
Ref: library/codecs codecs IncrementalDecoder getstate4941858
Ref: 199e4941858
Ref: library/codecs codecs IncrementalDecoder setstate4942654
Ref: 199f4942654
Node: 流式的编码和解码4942834
Ref: library/codecs stream-encoding-and-decoding4942949
Ref: 19a04942949
Node: StreamWriter 对象4943357
Ref: library/codecs stream-writer-objects4943465
Ref: 19a14943465
Ref: library/codecs streamwriter-objects4943465
Ref: 19a24943465
Ref: library/codecs codecs StreamWriter4943705
Ref: 19724943705
Ref: library/codecs codecs StreamWriter write4944603
Ref: 19a34944603
Ref: library/codecs codecs StreamWriter writelines4944696
Ref: 19a44944696
Ref: library/codecs codecs StreamWriter reset4944915
Ref: 19a54944915
Node: StreamReader 对象4945312
Ref: library/codecs stream-reader-objects4945454
Ref: 19a64945454
Ref: library/codecs streamreader-objects4945454
Ref: 19a74945454
Ref: library/codecs codecs StreamReader4945694
Ref: 19734945694
Ref: library/codecs codecs StreamReader read4946695
Ref: 19a84946695
Ref: library/codecs codecs StreamReader readline4947762
Ref: 19a94947762
Ref: library/codecs codecs StreamReader readlines4948088
Ref: 19aa4948088
Ref: library/codecs codecs StreamReader reset4948521
Ref: 19ab4948521
Node: StreamReaderWriter 对象4948877
Ref: library/codecs stream-reader-writer4949020
Ref: 19ac4949020
Ref: library/codecs streamreaderwriter-objects4949020
Ref: 19ad4949020
Ref: library/codecs codecs StreamReaderWriter4949323
Ref: 197b4949323
Node: StreamRecoder 对象4949949
Ref: library/codecs stream-recoder-objects4950064
Ref: 19ae4950064
Ref: library/codecs streamrecoder-objects4950064
Ref: 19af4950064
Ref: library/codecs codecs StreamRecoder4950376
Ref: 11084950376
Node: 编码格式与 Unicode4951414
Ref: library/codecs encodings-and-unicode4951566
Ref: 19b04951566
Ref: library/codecs encodings-overview4951566
Ref: 19b14951566
Ref: 编码格式与 Unicode-Footnote-14958130
Node: 标准编码4958179
Ref: library/codecs id34958341
Ref: 19b24958341
Ref: library/codecs standard-encodings4958341
Ref: 7824958341
Node: Python 专属的编码格式4980140
Ref: library/codecs python-specific-encodings4980331
Ref: 19b34980331
Node: 文字编码4980869
Ref: library/codecs text-encodings4980970
Ref: 19b44980970
Ref: 文字编码-Footnote-14984058
Ref: 文字编码-Footnote-24984107
Node: 二进制转换4984156
Ref: library/codecs binary-transforms4984278
Ref: 8f14984278
Ref: library/codecs id44984278
Ref: 19b54984278
Ref: 二进制转换-Footnote-14987995
Node: 文字转换4988129
Ref: library/codecs id64988230
Ref: 19bc4988230
Ref: library/codecs text-transforms4988230
Ref: 8f24988230
Node: encodings idna --- 应用程序中的国际化域名4988894
Ref: library/codecs encodings-idna-internationalized-domain-names-in-applications4989113
Ref: 19bd4989113
Ref: library/codecs module-encodings idna4989113
Ref: 754989113
Ref: library/codecs encodings idna nameprep4991532
Ref: 19be4991532
Ref: library/codecs encodings idna ToASCII4991722
Ref: 19bf4991722
Ref: library/codecs encodings idna ToUnicode4991879
Ref: 19c04991879
Ref: encodings idna --- 应用程序中的国际化域名-Footnote-14992027
Ref: encodings idna --- 应用程序中的国际化域名-Footnote-24992076
Ref: encodings idna --- 应用程序中的国际化域名-Footnote-34992125
Ref: encodings idna --- 应用程序中的国际化域名-Footnote-44992174
Ref: encodings idna --- 应用程序中的国际化域名-Footnote-54992223
Ref: encodings idna --- 应用程序中的国际化域名-Footnote-64992284
Ref: encodings idna --- 应用程序中的国际化域名-Footnote-74992333
Node: encodings mbcs --- Windows ANSI代码页4992382
Ref: library/codecs encodings-mbcs-windows-ansi-codepage4992629
Ref: 19c14992629
Ref: library/codecs module-encodings mbcs4992629
Ref: 764992629
Node: encodings utf_8_sig --- 带BOM签名的UTF-8编解码器4993019
Ref: library/codecs encodings-utf-8-sig-utf-8-codec-with-bom-signature4993205
Ref: 19c24993205
Ref: library/codecs module-encodings utf_8_sig4993205
Ref: 774993205
Node: 数据类型4993640
Ref: library/datatypes doc4993788
Ref: 19c34993788
Ref: library/datatypes data-types4993788
Ref: 19c44993788
Ref: library/datatypes datatypes4993788
Ref: 19c54993788
Node: datetime --- 基本日期和时间类型4995529
Ref: library/datetime doc4995657
Ref: 19c64995657
Ref: library/datetime datetime-basic-date-and-time-types4995657
Ref: 19c74995657
Ref: library/datetime module-datetime4995657
Ref: 304995657
Ref: datetime --- 基本日期和时间类型-Footnote-14996684
Ref: datetime --- 基本日期和时间类型-Footnote-24996751
Node: 感知型对象和简单型对象4996802
Ref: library/datetime aware-and-naive-objects4996927
Ref: 19c84996927
Ref: library/datetime datetime-naive-aware4996927
Ref: 19c94996927
Ref: 感知型对象和简单型对象-Footnote-14998698
Node: 常量4998762
Ref: library/datetime constants4998911
Ref: 19ca4998911
Ref: library/datetime datetime MINYEAR4999005
Ref: 19cb4999005
Ref: library/datetime datetime MAXYEAR4999165
Ref: 19cc4999165
Node: 有效的类型4999323
Ref: library/datetime available-types4999458
Ref: 19cd4999458
Node: 通用的特征属性5001139
Ref: library/datetime common-properties5001266
Ref: 19de5001266
Node: 确定一个对象是感知型还是简单型5001662
Ref: library/datetime determining-if-an-object-is-aware-or-naive5001789
Ref: 19df5001789
Node: timedelta 类对象5002586
Ref: library/datetime datetime-timedelta5002726
Ref: 19e05002726
Ref: library/datetime timedelta-objects5002726
Ref: 19e15002726
Ref: library/datetime datetime timedelta5002866
Ref: 2ca5002866
Ref: library/datetime datetime timedelta min5005065
Ref: 19e25005065
Ref: library/datetime datetime timedelta max5005180
Ref: 19e35005180
Ref: library/datetime datetime timedelta resolution5005359
Ref: 19e45005359
Ref: library/datetime datetime timedelta total_seconds5012257
Ref: d645012257
Node: class timedelta 用法示例5012775
Ref: library/datetime examples-of-usage-timedelta5012859
Ref: 19e55012859
Node: date 对象5013787
Ref: library/datetime date-objects5013927
Ref: 19e65013927
Ref: library/datetime datetime-date5013927
Ref: 19e75013927
Ref: library/datetime datetime date5014224
Ref: 19d5014224
Ref: library/datetime datetime date today5014617
Ref: 19e85014617
Ref: library/datetime datetime date fromtimestamp5014759
Ref: 19e95014759
Ref: library/datetime datetime date fromordinal5015646
Ref: 19ea5015646
Ref: library/datetime datetime date fromisoformat5015996
Ref: 11cc5015996
Ref: library/datetime datetime date fromisocalendar5016425
Ref: 2f55016425
Ref: library/datetime datetime date min5016686
Ref: 19ec5016686
Ref: library/datetime datetime date max5016760
Ref: 19ed5016760
Ref: library/datetime datetime date resolution5016838
Ref: 19ee5016838
Ref: library/datetime datetime date year5016965
Ref: 19ce5016965
Ref: library/datetime datetime date month5017069
Ref: 19cf5017069
Ref: library/datetime datetime date day5017117
Ref: 19d05017117
Ref: library/datetime datetime date replace5019567
Ref: 19ef5019567
Ref: library/datetime datetime date timetuple5019938
Ref: 19f05019938
Ref: library/datetime datetime date toordinal5020437
Ref: 19f15020437
Ref: library/datetime datetime date weekday5020673
Ref: 19f25020673
Ref: library/datetime datetime date isoweekday5020903
Ref: 19f35020903
Ref: library/datetime datetime date isocalendar5021153
Ref: 19e5021153
Ref: library/datetime datetime date isoformat5022220
Ref: 19eb5022220
Ref: library/datetime datetime date __str__5022512
Ref: 19f45022512
Ref: library/datetime datetime date ctime5022624
Ref: 19f55022624
Ref: library/datetime datetime date strftime5023073
Ref: 6315023073
Ref: library/datetime datetime date __format__5023357
Ref: 19f85023357
Ref: date 对象-Footnote-15023853
Ref: date 对象-Footnote-25024147
Node: class date 用法示例5024336
Ref: library/datetime examples-of-usage-date5024407
Ref: 19f95024407
Node: datetime 对象5026293
Ref: library/datetime datetime-datetime5026425
Ref: 19fa5026425
Ref: library/datetime datetime-objects5026425
Ref: 19fb5026425
Ref: library/datetime datetime datetime5026847
Ref: 19f5026847
Ref: library/datetime datetime datetime today5027673
Ref: 19fc5027673
Ref: library/datetime datetime datetime now5028048
Ref: 113b5028048
Ref: library/datetime datetime datetime utcnow5028727
Ref: 19fd5028727
Ref: library/datetime datetime datetime fromtimestamp5029497
Ref: 11c05029497
Ref: library/datetime datetime datetime utcfromtimestamp5031124
Ref: 19fe5031124
Ref: library/datetime datetime datetime fromordinal5032735
Ref: 19ff5032735
Ref: library/datetime datetime datetime combine5033146
Ref: 6335033146
Ref: library/datetime datetime datetime fromisoformat5033905
Ref: 4865033905
Ref: library/datetime datetime datetime fromisocalendar5035404
Ref: 2f65035404
Ref: library/datetime datetime datetime strptime5035754
Ref: f915035754
Ref: library/datetime datetime datetime min5036326
Ref: 1a005036326
Ref: library/datetime datetime datetime max5036451
Ref: 1a015036451
Ref: library/datetime datetime datetime resolution5036598
Ref: 1a025036598
Ref: library/datetime datetime datetime year5036783
Ref: 19d65036783
Ref: library/datetime datetime datetime month5036891
Ref: 19d75036891
Ref: library/datetime datetime datetime day5036943
Ref: 19d85036943
Ref: library/datetime datetime datetime hour5037022
Ref: 19d95037022
Ref: library/datetime datetime datetime minute5037090
Ref: 19da5037090
Ref: library/datetime datetime datetime second5037160
Ref: 19db5037160
Ref: library/datetime datetime datetime microsecond5037230
Ref: 19dc5037230
Ref: library/datetime datetime datetime tzinfo5037310
Ref: 19dd5037310
Ref: library/datetime datetime datetime fold5037467
Ref: 5ed5037467
Ref: library/datetime datetime datetime date5042054
Ref: 1a035042054
Ref: library/datetime datetime datetime time5042169
Ref: 1a045042169
Ref: library/datetime datetime datetime timetz5042484
Ref: 1a055042484
Ref: library/datetime datetime datetime replace5042767
Ref: 1a065042767
Ref: library/datetime datetime datetime astimezone5043334
Ref: 2cb5043334
Ref: library/datetime datetime datetime utcoffset5045610
Ref: 1a075045610
Ref: library/datetime datetime datetime dst5045975
Ref: 1a085045975
Ref: library/datetime datetime datetime tzname5046328
Ref: 1a0a5046328
Ref: library/datetime datetime datetime timetuple5046578
Ref: 1a0b5046578
Ref: library/datetime datetime datetime utctimetuple5047468
Ref: 1a0c5047468
Ref: library/datetime datetime datetime toordinal5048631
Ref: 1a0d5048631
Ref: library/datetime datetime datetime timestamp5048768
Ref: ac15048768
Ref: library/datetime datetime datetime weekday5050149
Ref: 1a0e5050149
Ref: library/datetime datetime datetime isoweekday5050353
Ref: 1a0f5050353
Ref: library/datetime datetime datetime isocalendar5050591
Ref: 1a05050591
Ref: library/datetime datetime datetime isoformat5050793
Ref: 6325050793
Ref: library/datetime datetime datetime __str__5053726
Ref: 1a105053726
Ref: library/datetime datetime datetime ctime5053866
Ref: 1a115053866
Ref: library/datetime datetime datetime strftime5054453
Ref: 6305054453
Ref: library/datetime datetime datetime __format__5054701
Ref: 1a125054701
Ref: datetime 对象-Footnote-15055211
Node: 用法示例 datetime5055299
Ref: library/datetime examples-of-usage-datetime5055372
Ref: 1a135055372
Node: time 对象5059675
Ref: library/datetime datetime-time5059809
Ref: 1a145059809
Ref: library/datetime time-objects5059809
Ref: 1a155059809
Ref: library/datetime datetime time5060010
Ref: 5ec5060010
Ref: library/datetime datetime time min5060670
Ref: 1a165060670
Ref: library/datetime datetime time max5060760
Ref: 1a175060760
Ref: library/datetime datetime time resolution5060858
Ref: 1a185060858
Ref: library/datetime datetime time hour5061107
Ref: 19d15061107
Ref: library/datetime datetime time minute5061171
Ref: 19d25061171
Ref: library/datetime datetime time second5061237
Ref: 19d35061237
Ref: library/datetime datetime time microsecond5061303
Ref: 19d45061303
Ref: library/datetime datetime time tzinfo5061379
Ref: 19d55061379
Ref: library/datetime datetime time fold5061526
Ref: 1a195061526
Ref: library/datetime datetime time fromisoformat5063386
Ref: 11cb5063386
Ref: library/datetime datetime time replace5064255
Ref: 1a1b5064255
Ref: library/datetime datetime time isoformat5064774
Ref: 1a1a5064774
Ref: library/datetime datetime time __str__5066740
Ref: 1a1d5066740
Ref: library/datetime datetime time strftime5066851
Ref: 1a1e5066851
Ref: library/datetime datetime time __format__5067082
Ref: 1a1f5067082
Ref: library/datetime datetime time utcoffset5067481
Ref: 1a1c5067481
Ref: library/datetime datetime time dst5067841
Ref: 1a205067841
Ref: library/datetime datetime time tzname5068190
Ref: 1a215068190
Ref: time 对象-Footnote-15068523
Node: 用法示例 time5068566
Ref: library/datetime examples-of-usage-time5068631
Ref: 1a225068631
Node: tzinfo 对象5069488
Ref: library/datetime datetime-tzinfo5069622
Ref: 1a235069622
Ref: library/datetime tzinfo-objects5069622
Ref: 1a245069622
Ref: library/datetime datetime tzinfo5069675
Ref: 1805069675
Ref: library/datetime datetime tzinfo utcoffset5071182
Ref: 1a255071182
Ref: library/datetime datetime tzinfo dst5072393
Ref: 1a265072393
Ref: library/datetime datetime tzinfo tzname5074835
Ref: 1a275074835
Ref: library/datetime datetime tzinfo fromutc5076820
Ref: 1a095076820
Ref: tzinfo 对象-Footnote-15089182
Node: timezone 对象5089222
Ref: library/datetime datetime-timezone5089376
Ref: 1a295089376
Ref: library/datetime timezone-objects5089376
Ref: 1a2a5089376
Ref: library/datetime datetime timezone5089764
Ref: ae05089764
Ref: library/datetime datetime timezone utcoffset5090318
Ref: 1a2b5090318
Ref: library/datetime datetime timezone tzname5090649
Ref: 1a2c5090649
Ref: library/datetime datetime timezone dst5091299
Ref: 1a2d5091299
Ref: library/datetime datetime timezone fromutc5091369
Ref: 1a2e5091369
Ref: library/datetime datetime timezone utc5091573
Ref: 1a285091573
Node: strftime 和 strptime 的行为5091650
Ref: library/datetime strftime-and-strptime-behavior5091782
Ref: 1a2f5091782
Ref: library/datetime strftime-strptime-behavior5091782
Ref: 19f75091782
Node: strftime 和 strptime Format Codes5093941
Ref: library/datetime strftime-and-strptime-format-codes5094064
Ref: 1a305094064
Node: 技术细节5104274
Ref: library/datetime technical-detail5104397
Ref: 1a315104397
Ref: 技术细节-Footnote-15109995
Node: zoneinfo --- IANA 时区支持5110109
Ref: library/zoneinfo doc5110277
Ref: 1a335110277
Ref: library/zoneinfo module-zoneinfo5110277
Ref: 14e5110277
Ref: library/zoneinfo zoneinfo-iana-time-zone-support5110277
Ref: 1a345110277
Ref: zoneinfo --- IANA 时区支持-Footnote-15111217
Ref: zoneinfo --- IANA 时区支持-Footnote-25111266
Ref: zoneinfo --- IANA 时区支持-Footnote-35111307
Node: 使用 ZoneInfo5111348
Ref: library/zoneinfo using-zoneinfo5111448
Ref: 1a355111448
Ref: 使用 ZoneInfo-Footnote-15113271
Node: 数据源5113320
Ref: library/zoneinfo data-sources5113441
Ref: 1a365113441
Ref: 数据源-Footnote-15114050
Node: 配置数据源5114091
Ref: library/zoneinfo configuring-the-data-sources5114152
Ref: 1a385114152
Ref: library/zoneinfo zoneinfo-data-configuration5114152
Ref: 1a395114152
Node: 编译时配置5114799
Ref: library/zoneinfo compile-time-configuration5114887
Ref: 1a3f5114887
Ref: library/zoneinfo zoneinfo-data-compile-time-config5114887
Ref: 1a3b5114887
Node: 环境配置5115556
Ref: library/zoneinfo environment-configuration5115668
Ref: 1a405115668
Ref: library/zoneinfo zoneinfo-data-environment-var5115668
Ref: 1a3c5115668
Ref: library/zoneinfo envvar-PYTHONTZPATH5115928
Ref: 1a415115928
Node: 运行时配置5116521
Ref: library/zoneinfo runtime-configuration5116609
Ref: 1a435116609
Ref: library/zoneinfo zoneinfo-data-runtime-config5116609
Ref: 1a3d5116609
Node: ZoneInfo 类5116903
Ref: library/zoneinfo the-zoneinfo-class5117018
Ref: 1a445117018
Ref: library/zoneinfo zoneinfo ZoneInfo5117068
Ref: 17f5117068
Ref: library/zoneinfo zoneinfo ZoneInfo from_file5117909
Ref: 1a465117909
Ref: library/zoneinfo zoneinfo ZoneInfo no_cache5118434
Ref: 1a485118434
Ref: library/zoneinfo zoneinfo ZoneInfo clear_cache5119055
Ref: 1a455119055
Ref: library/zoneinfo zoneinfo ZoneInfo key5119839
Ref: 1a495119839
Node: 字符串表示5120606
Ref: library/zoneinfo string-representations5120694
Ref: 1a4b5120694
Node: 封存序列化5121453
Ref: library/zoneinfo pickle-serialization5121541
Ref: 1a4c5121541
Ref: library/zoneinfo pickling5121541
Ref: 1a475121541
Node: 函数<2>5123650
Ref: library/zoneinfo functions5123768
Ref: 1a4d5123768
Ref: library/zoneinfo zoneinfo available_timezones5123799
Ref: 103e5123799
Ref: library/zoneinfo zoneinfo reset_tzpath5124695
Ref: 1a3e5124695
Node: 全局变量5125341
Ref: library/zoneinfo globals5125462
Ref: 1a4e5125462
Ref: library/zoneinfo zoneinfo TZPATH5125503
Ref: 1a3a5125503
Node: 异常与警告5126209
Ref: library/zoneinfo exceptions-and-warnings5126312
Ref: 1a4f5126312
Ref: library/zoneinfo zoneinfo ZoneInfoNotFoundError5126358
Ref: 1a375126358
Ref: library/zoneinfo zoneinfo InvalidTZPathWarning5126568
Ref: 1a425126568
Node: calendar --- 日历相关函数5126729
Ref: library/calendar doc5126891
Ref: 1a505126891
Ref: library/calendar calendar-general-calendar-related-functions5126891
Ref: 1a515126891
Ref: library/calendar module-calendar5126891
Ref: 145126891
Ref: library/calendar tzdata5126891
Ref: 1a525126891
Ref: library/calendar calendar Calendar5127957
Ref: 1a545127957
Ref: library/calendar calendar Calendar iterweekdays5128446
Ref: 1a555128446
Ref: library/calendar calendar Calendar itermonthdates5128649
Ref: 5a05128649
Ref: library/calendar calendar Calendar itermonthdays5128966
Ref: 1a575128966
Ref: library/calendar calendar Calendar itermonthdays25129345
Ref: 1a585129345
Ref: library/calendar calendar Calendar itermonthdays35129702
Ref: 5a15129702
Ref: library/calendar calendar Calendar itermonthdays45130053
Ref: 5a25130053
Ref: library/calendar calendar Calendar monthdatescalendar5130442
Ref: 1a595130442
Ref: library/calendar calendar Calendar monthdays2calendar5130626
Ref: 1a5a5130626
Ref: library/calendar calendar Calendar monthdayscalendar5130838
Ref: 1a5b5130838
Ref: library/calendar calendar Calendar yeardatescalendar5130999
Ref: 1a5c5130999
Ref: library/calendar calendar Calendar yeardays2calendar5131372
Ref: 1a5d5131372
Ref: library/calendar calendar Calendar yeardayscalendar5131683
Ref: 1a5e5131683
Ref: library/calendar calendar TextCalendar5131948
Ref: 1a5f5131948
Ref: library/calendar calendar TextCalendar formatmonth5132109
Ref: 1a605132109
Ref: library/calendar calendar TextCalendar prmonth5132491
Ref: 1a615132491
Ref: library/calendar calendar TextCalendar formatyear5132638
Ref: 1a625132638
Ref: library/calendar calendar TextCalendar pryear5133090
Ref: 1a635133090
Ref: library/calendar calendar HTMLCalendar5133235
Ref: 4775133235
Ref: library/calendar calendar HTMLCalendar formatmonth5133386
Ref: 1a645133386
Ref: library/calendar calendar HTMLCalendar formatyear5133612
Ref: 1a655133612
Ref: library/calendar calendar HTMLCalendar formatyearpage5133810
Ref: 1a665133810
Ref: library/calendar calendar HTMLCalendar cssclasses5134372
Ref: 1a675134372
Ref: library/calendar calendar HTMLCalendar cssclass_noday5134762
Ref: 1a685134762
Ref: library/calendar calendar HTMLCalendar cssclasses_weekday_head5134889
Ref: 1a695134889
Ref: library/calendar calendar HTMLCalendar cssclass_month_head5135085
Ref: 1a6a5135085
Ref: library/calendar calendar HTMLCalendar cssclass_month5135267
Ref: 1a6b5135267
Ref: library/calendar calendar HTMLCalendar cssclass_year5135457
Ref: 1a6c5135457
Ref: library/calendar calendar HTMLCalendar cssclass_year_head5135641
Ref: 1a6d5135641
Ref: library/calendar calendar LocaleTextCalendar5136495
Ref: 1a6e5136495
Ref: library/calendar calendar LocaleHTMLCalendar5136861
Ref: 1a6f5136861
Ref: library/calendar calendar setfirstweekday5137532
Ref: 1a535137532
Ref: library/calendar calendar firstweekday5137955
Ref: 1a565137955
Ref: library/calendar calendar isleap5138054
Ref: 1a705138054
Ref: library/calendar calendar leapdays5138186
Ref: 1a715138186
Ref: library/calendar calendar weekday5138412
Ref: 1a725138412
Ref: library/calendar calendar weekheader5138626
Ref: 1a735138626
Ref: library/calendar calendar monthrange5138762
Ref: 1a745138762
Ref: library/calendar calendar monthcalendar5138905
Ref: 1a755138905
Ref: library/calendar calendar prmonth5139161
Ref: 1a765139161
Ref: library/calendar calendar month5139289
Ref: 1a775139289
Ref: library/calendar calendar prcal5139465
Ref: 1a785139465
Ref: library/calendar calendar calendar5139586
Ref: 1a795139586
Ref: library/calendar calendar timegm5139774
Ref: 1a7a5139774
Ref: library/calendar calendar day_name5140200
Ref: 1a7b5140200
Ref: library/calendar calendar day_abbr5140287
Ref: 1a7c5140287
Ref: library/calendar calendar month_name5140380
Ref: 1a7d5140380
Ref: library/calendar calendar month_abbr5140596
Ref: 1a7e5140596
Ref: calendar --- 日历相关函数-Footnote-15141044
Node: collections --- 容器資料型態5141111
Ref: library/collections doc5141284
Ref: 1a7f5141284
Ref: library/collections collections-container-datatypes5141284
Ref: 1a805141284
Ref: library/collections module-collections5141284
Ref: 1d5141284
Ref: collections --- 容器資料型態-Footnote-15143480
Node: ChainMap objects5143560
Ref: library/collections chainmap-objects5143670
Ref: 1a825143670
Ref: library/collections collections ChainMap5144055
Ref: 5a35144055
Ref: library/collections collections ChainMap maps5144984
Ref: 1a835144984
Ref: library/collections collections ChainMap new_child5145236
Ref: 9165145236
Ref: library/collections collections ChainMap parents5145820
Ref: 1a845145820
Ref: ChainMap objects-Footnote-15147582
Ref: ChainMap objects-Footnote-25147631
Ref: ChainMap objects-Footnote-35147726
Ref: ChainMap objects-Footnote-45147773
Ref: ChainMap objects-Footnote-55147852
Ref: ChainMap objects-Footnote-65147905
Node: ChainMap 例子和方法5147958
Ref: library/collections chainmap-examples-and-recipes5148035
Ref: 1a855148035
Node: Counter 物件5150921
Ref: library/collections counter-objects5151052
Ref: 1a865151052
Ref: library/collections collections Counter5151739
Ref: ab95151739
Ref: library/collections collections Counter elements5153614
Ref: d625153614
Ref: library/collections collections Counter most_common5154030
Ref: d615154030
Ref: library/collections collections Counter subtract5154501
Ref: c2c5154501
Ref: library/collections collections Counter fromkeys5155118
Ref: 1a875155118
Ref: library/collections collections Counter update5155231
Ref: 1a885155231
Ref: Counter 物件-Footnote-15158953
Ref: Counter 物件-Footnote-25159032
Ref: Counter 物件-Footnote-35159079
Node: deque 对象5159172
Ref: library/collections deque-objects5159305
Ref: 1a895159305
Ref: library/collections collections deque5159354
Ref: 62a5159354
Ref: library/collections collections deque append5160583
Ref: 1a8a5160583
Ref: library/collections collections deque appendleft5160653
Ref: 1a8b5160653
Ref: library/collections collections deque clear5160727
Ref: 1a8c5160727
Ref: library/collections collections deque copy5160810
Ref: 79e5160810
Ref: library/collections collections deque count5160907
Ref: c2e5160907
Ref: library/collections collections deque extend5161027
Ref: 1a8d5161027
Ref: library/collections collections deque extendleft5161145
Ref: 1a8e5161145
Ref: library/collections collections deque index5161364
Ref: 79c5161364
Ref: library/collections collections deque insert5161644
Ref: 79d5161644
Ref: library/collections collections deque pop5161886
Ref: 1a8f5161886
Ref: library/collections collections deque popleft5162072
Ref: 1a905162072
Ref: library/collections collections deque remove5162256
Ref: 1a915162256
Ref: library/collections collections deque reverse5162406
Ref: c2f5162406
Ref: library/collections collections deque rotate5162526
Ref: 1a925162526
Ref: library/collections collections deque maxlen5162887
Ref: d635162887
Node: deque 用法5165528
Ref: library/collections deque-recipes5165589
Ref: 1a935165589
Ref: deque 用法-Footnote-15167877
Node: defaultdict 对象5167938
Ref: library/collections defaultdict-objects5168095
Ref: 1a945168095
Ref: library/collections collections defaultdict5168156
Ref: c0c5168156
Ref: library/collections collections defaultdict __missing__5168901
Ref: 1a965168901
Ref: library/collections collections defaultdict default_factory5170078
Ref: 1a955170078
Ref: defaultdict 对象-Footnote-15170543
Node: defaultdict 例子5170592
Ref: library/collections defaultdict-examples5170665
Ref: 1a975170665
Node: namedtuple 命名元组的工厂函数5173091
Ref: library/collections namedtuple-factory-function-for-tuples-with-named-fields5173254
Ref: 1a985173254
Ref: library/collections collections namedtuple5173550
Ref: 1a15173550
Ref: library/collections collections somenamedtuple _make5177160
Ref: 1a995177160
Ref: library/collections collections somenamedtuple _asdict5177381
Ref: 2e95177381
Ref: library/collections collections somenamedtuple _replace5178026
Ref: 1a9a5178026
Ref: library/collections collections somenamedtuple _fields5178415
Ref: 1a9b5178415
Ref: library/collections collections somenamedtuple _field_defaults5178880
Ref: 1a9c5178880
Node: OrderedDict 对象5181528
Ref: library/collections ordereddict-objects5181688
Ref: 1a9d5181688
Ref: library/collections collections OrderedDict5182938
Ref: 2ea5182938
Ref: library/collections collections OrderedDict popitem5183127
Ref: d4c5183127
Ref: library/collections collections OrderedDict move_to_end5183430
Ref: c2d5183430
Ref: OrderedDict 对象-Footnote-15184964
Ref: OrderedDict 对象-Footnote-25185049
Ref: OrderedDict 对象-Footnote-35185098
Node: OrderedDict 例子和用法5185147
Ref: library/collections ordereddict-examples-and-recipes5185229
Ref: 1a9f5185229
Node: UserDict 对象5186360
Ref: library/collections userdict-objects5186497
Ref: 1aa05186497
Ref: library/collections collections UserDict5186805
Ref: 10815186805
Ref: library/collections collections UserDict data5187308
Ref: 1aa15187308
Node: UserList 对象5187417
Ref: library/collections userlist-objects5187553
Ref: 1aa25187553
Ref: library/collections collections UserList5188031
Ref: 1a815188031
Ref: library/collections collections UserList data5188520
Ref: 1aa35188520
Node: UserString 对象5189097
Ref: library/collections userstring-objects5189209
Ref: 1aa45189209
Ref: library/collections collections UserString5189527
Ref: 7a05189527
Ref: library/collections collections UserString data5189998
Ref: 1aa55189998
Node: collections abc --- 容器的抽象基类5190282
Ref: library/collections abc doc5190467
Ref: 1aa65190467
Ref: library/collections abc collections-abc-abstract-base-classes-for-containers5190467
Ref: 1aa75190467
Ref: library/collections abc module-collections abc5190467
Ref: 1e5190467
Ref: collections abc --- 容器的抽象基类-Footnote-15191133
Ref: collections abc --- 容器的抽象基类-Footnote-25191209
Node: 容器抽象基类5191258
Ref: library/collections abc collections-abstract-base-classes5191354
Ref: 15e5191354
Ref: library/collections abc id15191354
Ref: 1aa85191354
Ref: library/collections abc collections abc Container5200297
Ref: 181a5200297
Ref: library/collections abc collections abc Hashable5200404
Ref: 1aa95200404
Ref: library/collections abc collections abc Sized5200506
Ref: 1aaa5200506
Ref: library/collections abc collections abc Callable5200604
Ref: 27a5200604
Ref: library/collections abc collections abc Iterable5200707
Ref: 18185200707
Ref: library/collections abc collections abc Collection5201190
Ref: 6265201190
Ref: library/collections abc collections abc Iterator5201311
Ref: 18195201311
Ref: library/collections abc collections abc Reversible5201488
Ref: 6275201488
Ref: library/collections abc collections abc Generator5201635
Ref: 7a85201635
Ref: library/collections abc collections abc Sequence5201928
Ref: 17645201928
Ref: library/collections abc collections abc MutableSequence5201965
Ref: 79f5201965
Ref: library/collections abc collections abc ByteString5202009
Ref: 181c5202009
Ref: library/collections abc collections abc Set5202685
Ref: 18105202685
Ref: library/collections abc collections abc MutableSet5202717
Ref: 181b5202717
Ref: library/collections abc collections abc Mapping5202806
Ref: 15f5202806
Ref: library/collections abc collections abc MutableMapping5202842
Ref: ace5202842
Ref: library/collections abc collections abc MappingView5202957
Ref: 181d5202957
Ref: library/collections abc collections abc ItemsView5202997
Ref: 181f5202997
Ref: library/collections abc collections abc KeysView5203035
Ref: 181e5203035
Ref: library/collections abc collections abc ValuesView5203072
Ref: 18205203072
Ref: library/collections abc collections abc Awaitable5203187
Ref: 7a95203187
Ref: library/collections abc collections abc Coroutine5203964
Ref: 7aa5203964
Ref: library/collections abc collections abc AsyncIterable5204861
Ref: 7ac5204861
Ref: library/collections abc collections abc AsyncIterator5205043
Ref: 7ab5205043
Ref: library/collections abc collections abc AsyncGenerator5205245
Ref: 6295205245
Ref: 容器抽象基类-Footnote-15208289
Ref: 容器抽象基类-Footnote-25208338
Ref: 容器抽象基类-Footnote-35208387
Ref: 容器抽象基类-Footnote-45208436
Ref: 容器抽象基类-Footnote-55208489
Node: heapq --- 堆積佇列 heap queue 演算法5208538
Ref: library/heapq doc5208747
Ref: 1aab5208747
Ref: library/heapq heapq-heap-queue-algorithm5208747
Ref: 1aac5208747
Ref: library/heapq module-heapq5208747
Ref: 8d5208747
Ref: library/heapq heapq heappush5210295
Ref: 1aae5210295
Ref: library/heapq heapq heappop5210400
Ref: 1aaf5210400
Ref: library/heapq heapq heappushpop5210656
Ref: 1ab05210656
Ref: library/heapq heapq heapify5210897
Ref: 1aad5210897
Ref: library/heapq heapq heapreplace5211019
Ref: 1ab15211019
Ref: library/heapq heapq merge5211860
Ref: 7d15211860
Ref: library/heapq heapq nlargest5212977
Ref: 1ab25212977
Ref: library/heapq heapq nsmallest5213354
Ref: 1ab35213354
Ref: heapq --- 堆積佇列 heap queue 演算法-Footnote-15214224
Node: 基礎範例5214288
Ref: library/heapq basic-examples5214429
Ref: 1ab45214429
Ref: 基礎範例-Footnote-15215371
Node: 優先佇列 Priority Queue 實作細節5215418
Ref: library/heapq priority-queue-implementation-notes5215574
Ref: 1ab55215574
Ref: 優先佇列 Priority Queue 實作細節-Footnote-15218467
Node: 原理5218520
Ref: library/heapq theory5218655
Ref: 1ab65218655
Ref: 原理-Footnote-15222671
Node: bisect --- 陣列二分演算法 Array bisection algorithm5223248
Ref: library/bisect doc5223456
Ref: 1ab75223456
Ref: library/bisect bisect-array-bisection-algorithm5223456
Ref: 1ab85223456
Ref: library/bisect module-bisect5223456
Ref: 115223456
Ref: library/bisect bisect bisect_left5224170
Ref: 1ab95224170
Ref: library/bisect bisect bisect_right5224822
Ref: 1aba5224822
Ref: library/bisect bisect bisect5224878
Ref: 1abb5224878
Ref: library/bisect bisect insort_left5225246
Ref: 1abc5225246
Ref: library/bisect bisect insort_right5225610
Ref: 1abd5225610
Ref: library/bisect bisect insort5225666
Ref: 1abe5225666
Ref: bisect --- 陣列二分演算法 Array bisection algorithm-Footnote-15226208
Ref: bisect --- 陣列二分演算法 Array bisection algorithm-Footnote-25226273
Node: 搜索有序列表5226343
Ref: library/bisect searching-sorted-lists5226477
Ref: 1abf5226477
Node: 其他示例5227654
Ref: library/bisect other-examples5227788
Ref: 1ac05227788
Ref: library/bisect bisect-example5227827
Ref: 1ac15227827
Node: array --- 高效率的數值型態陣列5229116
Ref: library/array doc5229302
Ref: 1ac25229302
Ref: library/array array-efficient-arrays-of-numeric-values5229302
Ref: 1ac35229302
Ref: library/array module-array5229302
Ref: 65229302
Ref: library/array array array5233788
Ref: 2165233788
Ref: library/array array typecodes5234494
Ref: 1ac85234494
Ref: library/array array array typecode5234954
Ref: 1ac95234954
Ref: library/array array array itemsize5235031
Ref: 1aca5235031
Ref: library/array array array append5235138
Ref: 1acb5235138
Ref: library/array array array buffer_info5235228
Ref: 1acc5235228
Ref: library/array array array byteswap5236102
Ref: 1acd5236102
Ref: library/array array array count5236383
Ref: 1ace5236383
Ref: library/array array array extend5236466
Ref: 1ac75236466
Ref: library/array array array frombytes5236855
Ref: 1ac55236855
Ref: library/array array array fromfile5237201
Ref: 1acf5237201
Ref: library/array array array fromlist5237517
Ref: 1ac45237517
Ref: library/array array array fromunicode5237719
Ref: 1ac65237719
Ref: library/array array array index5238044
Ref: 101c5238044
Ref: library/array array array insert5238167
Ref: 1ad05238167
Ref: library/array array array pop5238307
Ref: 1ad15238307
Ref: library/array array array remove5238498
Ref: 1ad25238498
Ref: library/array array array reverse5238585
Ref: 1ad35238585
Ref: library/array array array tobytes5238673
Ref: 1ad45238673
Ref: library/array array array tofile5238994
Ref: 1ad55238994
Ref: library/array array array tolist5239128
Ref: 1ad65239128
Ref: library/array array array tounicode5239221
Ref: 1ad75239221
Ref: array --- 高效率的數值型態陣列-Footnote-15240446
Node: weakref --- 弱引用5240473
Ref: library/weakref doc5240650
Ref: 1ad85240650
Ref: library/weakref module-weakref5240650
Ref: 1315240650
Ref: library/weakref weakref-weak-references5240650
Ref: 1ad95240650
Ref: library/weakref weakref ref5244187
Ref: 9f65244187
Ref: library/weakref weakref ref __callback__5245751
Ref: 9f75245751
Ref: library/weakref weakref proxy5246036
Ref: 37a5246036
Ref: library/weakref weakref getweakrefcount5246802
Ref: 1adb5246802
Ref: library/weakref weakref getweakrefs5246910
Ref: 1adc5246910
Ref: library/weakref weakref WeakKeyDictionary5247029
Ref: 10545247029
Ref: library/weakref weakref WeakKeyDictionary keyrefs5247832
Ref: 1add5247832
Ref: library/weakref weakref WeakValueDictionary5247938
Ref: 10535247938
Ref: library/weakref weakref WeakValueDictionary valuerefs5248383
Ref: 1ade5248383
Ref: library/weakref weakref WeakSet5248493
Ref: d805248493
Ref: library/weakref weakref WeakMethod5248654
Ref: 9f55248654
Ref: library/weakref weakref finalize5249536
Ref: 3c05249536
Ref: library/weakref weakref finalize __call__5250733
Ref: 1adf5250733
Ref: library/weakref weakref finalize detach5250969
Ref: 1ae05250969
Ref: library/weakref weakref finalize peek5251194
Ref: 1ae15251194
Ref: library/weakref weakref finalize alive5251380
Ref: 1ae25251380
Ref: library/weakref weakref finalize atexit5251494
Ref: 1ae35251494
Ref: library/weakref weakref ReferenceType5252086
Ref: 1ae45252086
Ref: library/weakref weakref ProxyType5252159
Ref: 1ae55252159
Ref: library/weakref weakref CallableProxyType5252240
Ref: 1ae65252240
Ref: library/weakref weakref ProxyTypes5252326
Ref: 1ae75252326
Ref: weakref --- 弱引用-Footnote-15252867
Ref: weakref --- 弱引用-Footnote-25252933
Ref: weakref --- 弱引用-Footnote-35252982
Ref: weakref --- 弱引用-Footnote-45253031
Node: 弱引用对象5253080
Ref: library/weakref weak-reference-objects5253171
Ref: 1ae85253171
Ref: library/weakref weakref-objects5253171
Ref: 1ae95253171
Node: 示例<4>5255448
Ref: library/weakref example5255563
Ref: 1aea5255563
Ref: library/weakref weakref-example5255563
Ref: 1aeb5255563
Node: 终结器对象5256088
Ref: library/weakref finalize-examples5256221
Ref: 1aec5256221
Ref: library/weakref finalizer-objects5256221
Ref: 1aed5256221
Node: 比较终结器与 __del__ 方法5258000
Ref: library/weakref comparing-finalizers-with-del-methods5258115
Ref: 1aee5258115
Node: types --- 动态类型创建和内置类型名称5260784
Ref: library/types doc5260972
Ref: 1aef5260972
Ref: library/types module-types5260972
Ref: 1215260972
Ref: library/types types-dynamic-type-creation-and-names-for-built-in-types5260972
Ref: 1af05260972
Ref: types --- 动态类型创建和内置类型名称-Footnote-15261699
Node: 动态类型创建5261763
Ref: library/types dynamic-type-creation5261897
Ref: 1af15261897
Ref: library/types types new_class5261948
Ref: b8f5261948
Ref: library/types types prepare_class5262528
Ref: b905262528
Ref: library/types types resolve_bases5263506
Ref: 50a5263506
Ref: 动态类型创建-Footnote-15264161
Ref: 动态类型创建-Footnote-25264210
Ref: 动态类型创建-Footnote-35264259
Node: 标准解释器类型5264308
Ref: library/types standard-interpreter-types5264475
Ref: 1af25264475
Ref: library/types types FunctionType5264993
Ref: 1af35264993
Ref: library/types types LambdaType5265022
Ref: 1af45265022
Ref: library/types types GeneratorType5265345
Ref: 1af55265345
Ref: library/types types CoroutineType5265459
Ref: 86c5265459
Ref: library/types types AsyncGeneratorType5265608
Ref: 1af65265608
Ref: library/types types CodeType5265777
Ref: 2cd5265777
Ref: library/types types CodeType replace5266322
Ref: 1af75266322
Ref: library/types types CellType5266472
Ref: 155d5266472
Ref: library/types types MethodType5266607
Ref: 1af85266607
Ref: library/types types BuiltinFunctionType5266684
Ref: 1af95266684
Ref: library/types types BuiltinMethodType5266720
Ref: 1afa5266720
Ref: library/types types WrapperDescriptorType5266932
Ref: 5065266932
Ref: library/types types MethodWrapperType5267132
Ref: 5075267132
Ref: library/types types MethodDescriptorType5267316
Ref: 5085267316
Ref: library/types types ClassMethodDescriptorType5267458
Ref: 5095267458
Ref: library/types types ModuleType5267635
Ref: 7e25267635
Ref: library/types types ModuleType __doc__5267987
Ref: 1afb5267987
Ref: library/types types ModuleType __loader__5268084
Ref: 1afc5268084
Ref: library/types types ModuleType __name__5268766
Ref: 1afe5268766
Ref: library/types types ModuleType __package__5268901
Ref: 1b005268901
Ref: library/types types ModuleType __spec__5269841
Ref: 1b025269841
Ref: library/types types GenericAlias5270037
Ref: 27c5270037
Ref: library/types types TracebackType5270656
Ref: 4415270656
Ref: library/types types FrameType5270939
Ref: 1b035270939
Ref: library/types types GetSetDescriptorType5271162
Ref: 1b045271162
Ref: library/types types MemberDescriptorType5271505
Ref: 1b055271505
Ref: library/types types MappingProxyType5271997
Ref: b8e5271997
Ref: library/types types MappingProxyType copy5272910
Ref: 1b065272910
Ref: library/types types MappingProxyType get5272987
Ref: 1b075272987
Ref: library/types types MappingProxyType items5273259
Ref: 1b085273259
Ref: library/types types MappingProxyType keys5273382
Ref: 1b095273382
Ref: library/types types MappingProxyType values5273480
Ref: 1b0a5273480
Ref: 标准解释器类型-Footnote-15273750
Node: 附加工具类和函数5273799
Ref: library/types additional-utility-classes-and-functions5273966
Ref: 1b0b5273966
Ref: library/types types SimpleNamespace5274027
Ref: 1d85274027
Ref: library/types types DynamicClassAttribute5275313
Ref: 9d95275313
Node: 协程工具函数5275909
Ref: library/types coroutine-utility-functions5276046
Ref: 1b0c5276046
Ref: library/types types coroutine5276097
Ref: 86b5276097
Node: copy --- 浅层 shallow 和深层 deep 复制操作5276868
Ref: library/copy doc5277064
Ref: 1b0d5277064
Ref: library/copy copy-shallow-and-deep-copy-operations5277064
Ref: 1b0e5277064
Ref: library/copy module-copy5277064
Ref: 255277064
Ref: library/copy copy copy5277598
Ref: 4d15277598
Ref: library/copy copy deepcopy5277661
Ref: 4d25277661
Ref: library/copy copy Error5277736
Ref: 1b0f5277736
Ref: library/copy shallow-vs-deep-copy5277799
Ref: 135d5277799
Ref: copy --- 浅层 shallow 和深层 deep 复制操作-Footnote-15280245
Node: pprint --- 数据美化输出5280308
Ref: library/pprint doc5280488
Ref: 1b105280488
Ref: library/pprint module-pprint5280488
Ref: d25280488
Ref: library/pprint pprint-data-pretty-printer5280488
Ref: 1b115280488
Ref: library/pprint pprint PrettyPrinter5281496
Ref: 97c5281496
Ref: library/pprint pprint pformat5283981
Ref: 97d5283981
Ref: library/pprint pprint pp5284396
Ref: 3405284396
Ref: library/pprint pprint pprint5284757
Ref: 3415284757
Ref: library/pprint pprint isreadable5285797
Ref: 1b125285797
Ref: library/pprint pprint isrecursive5286089
Ref: 1b135286089
Ref: library/pprint pprint saferepr5286221
Ref: 1b145286221
Ref: pprint --- 数据美化输出-Footnote-15286767
Node: PrettyPrinter 对象5286832
Ref: library/pprint id15286936
Ref: 1b155286936
Ref: library/pprint prettyprinter-objects5286936
Ref: 1b165286936
Ref: library/pprint pprint PrettyPrinter pformat5287053
Ref: 1b175287053
Ref: library/pprint pprint PrettyPrinter pprint5287226
Ref: 1b185287226
Ref: library/pprint pprint PrettyPrinter isreadable5287545
Ref: 1b195287545
Ref: library/pprint pprint PrettyPrinter isrecursive5287926
Ref: 1b1a5287926
Ref: library/pprint pprint PrettyPrinter format5288190
Ref: 1b1b5288190
Node: 示例<5>5289157
Ref: library/pprint example5289261
Ref: 1b1c5289261
Ref: library/pprint pprint-example5289261
Ref: 1b1d5289261
Ref: 示例<5>-Footnote-15296535
Node: reprlib --- 另一种 repr 实现5296560
Ref: library/reprlib doc5296716
Ref: 1b1e5296716
Ref: library/reprlib module-reprlib5296716
Ref: df5296716
Ref: library/reprlib reprlib-alternate-repr-implementation5296716
Ref: 1b1f5296716
Ref: library/reprlib reprlib Repr5297167
Ref: 1b205297167
Ref: library/reprlib reprlib aRepr5297389
Ref: 1b215297389
Ref: library/reprlib reprlib repr5297636
Ref: 1b225297636
Ref: library/reprlib reprlib recursive_repr5298021
Ref: c415298021
Ref: reprlib --- 另一种 repr 实现-Footnote-15298798
Node: Repr 对象5298864
Ref: library/reprlib id15298975
Ref: 1b245298975
Ref: library/reprlib repr-objects5298975
Ref: 1b255298975
Ref: library/reprlib reprlib Repr maxlevel5299190
Ref: 1b265299190
Ref: library/reprlib reprlib Repr maxdict5299287
Ref: 1b275299287
Ref: library/reprlib reprlib Repr maxlist5299312
Ref: 1b285299312
Ref: library/reprlib reprlib Repr maxtuple5299337
Ref: 1b295299337
Ref: library/reprlib reprlib Repr maxset5299363
Ref: 1b2a5299363
Ref: library/reprlib reprlib Repr maxfrozenset5299387
Ref: 1b2b5299387
Ref: library/reprlib reprlib Repr maxdeque5299417
Ref: 1b2c5299417
Ref: library/reprlib reprlib Repr maxarray5299443
Ref: 1b2d5299443
Ref: library/reprlib reprlib Repr maxlong5299658
Ref: 1b2e5299658
Ref: library/reprlib reprlib Repr maxstring5299783
Ref: 1b2f5299783
Ref: library/reprlib reprlib Repr maxother5300048
Ref: 1b305300048
Ref: library/reprlib reprlib Repr repr5300295
Ref: 1b235300295
Ref: library/reprlib reprlib Repr repr15300417
Ref: 1b315300417
Node: 子类化 Repr 对象5301201
Ref: library/reprlib subclassing-repr-objects5301312
Ref: 1b325301312
Ref: library/reprlib subclassing-reprs5301312
Ref: 1b335301312
Node: enum --- 对枚举的支持5301946
Ref: library/enum doc5302119
Ref: 1b345302119
Ref: library/enum enum-support-for-enumerations5302119
Ref: 1b355302119
Ref: library/enum module-enum5302119
Ref: 795302119
Ref: enum --- 对枚举的支持-Footnote-15303138
Node: 模块内容<2>5303201
Ref: library/enum module-contents5303300
Ref: 1b365303300
Ref: library/enum enum Enum5303611
Ref: 48d5303611
Ref: library/enum enum IntEnum5303760
Ref: 6845303760
Ref: library/enum enum IntFlag5303846
Ref: 18a15303846
Ref: library/enum enum Flag5304065
Ref: 63f5304065
Ref: library/enum enum auto5304307
Ref: 6405304307
Node: 创建 Enum5304470
Ref: library/enum creating-an-enum5304617
Ref: 1b395304617
Node: 枚举成员及其属性的编程访问5306773
Ref: library/enum programmatic-access-to-enumeration-members-and-their-attributes5306932
Ref: 1b3b5306932
Node: 重复的枚举成员和值5307562
Ref: library/enum duplicating-enum-members-and-values5307731
Ref: 1b3c5307731
Node: 确保唯一枚举值5308688
Ref: library/enum ensuring-unique-enumeration-values5308842
Ref: 1b3d5308842
Ref: library/enum enum unique5309057
Ref: 1b375309057
Node: 使用自动设定的值5309612
Ref: library/enum using-automatic-values5309745
Ref: 1b3e5309745
Node: 迭代5310940
Ref: library/enum iteration5311061
Ref: 1b3f5311061
Node: 比较<2>5311836
Ref: library/enum comparisons5311963
Ref: 1b405311963
Node: 允许的枚举成员和属性5312819
Ref: library/enum allowed-members-and-attributes-of-enumerations5312964
Ref: 1b425312964
Node: 受限的 Enum 子类化5314635
Ref: library/enum restricted-enum-subclassing5314777
Ref: 1b445314777
Node: 封存5315849
Ref: library/enum pickling5315974
Ref: 1b465315974
Node: 功能性 API5316555
Ref: library/enum functional-api5316671
Ref: 1b385316671
Node: 派生的枚举5319725
Ref: library/enum derived-enumerations5319868
Ref: 1b485319868
Node: IntEnum5319976
Ref: library/enum intenum5320051
Ref: 1b415320051
Node: IntFlag5321152
Ref: library/enum intflag5321240
Ref: 1b495321240
Node: Flag5322764
Ref: library/enum flag5322857
Ref: 1b4a5322857
Node: 其他事项5324861
Ref: library/enum others5324938
Ref: 1b4b5324938
Node: 何时使用 __new__ 与 __init__5326641
Ref: library/enum when-to-use-new-vs-init5326786
Ref: 1b4c5326786
Node: 有趣的示例5327864
Ref: library/enum interesting-examples5328021
Ref: 1b4d5328021
Node: 省略值5328433
Ref: library/enum omitting-values5328514
Ref: 1b4e5328514
Node: 使用 auto5329513
Ref: library/enum using-auto5329592
Ref: 1b4f5329592
Node: 使用 object5329847
Ref: library/enum using-object5329959
Ref: 1b505329959
Node: 使用描述性字符串5330226
Ref: library/enum using-a-descriptive-string5330353
Ref: 1b515330353
Node: 使用自定义的 __new__5330660
Ref: library/enum using-a-custom-new5330765
Ref: 1b525330765
Node: OrderedEnum5332454
Ref: library/enum orderedenum5332561
Ref: 1b455332561
Node: DuplicateFreeEnum5333729
Ref: library/enum duplicatefreeenum5333833
Ref: 1b535333833
Node: Planet5334869
Ref: library/enum planet5334972
Ref: 1b435334972
Node: TimePeriod5336023
Ref: library/enum timeperiod5336100
Ref: 1b545336100
Node: 各种枚举有何区别？5336716
Ref: library/enum how-are-enums-different5336831
Ref: 1b3a5336831
Node: 枚举类5337079
Ref: library/enum enum-classes5337188
Ref: 1b555337188
Node: 枚举成员（即实例）5337698
Ref: library/enum enum-members-aka-instances5337828
Ref: 1b565337828
Node: 细节要点5338188
Ref: library/enum finer-points5338300
Ref: 1b575338300
Node: 支持的 __dunder__ 名称5338546
Ref: library/enum supported-dunder-names5338656
Ref: 1b585338656
Node: 支持的 _sunder_ 名称5339066
Ref: library/enum supported-sunder-names5339200
Ref: 1b595339200
Node: _Private__names5340596
Ref: library/enum private-names5340720
Ref: 1b5a5340720
Node: Enum 成员类型5341012
Ref: library/enum enum-member-type5341140
Ref: 1b5b5341140
Node: Enum 类和成员的布尔值5341907
Ref: library/enum boolean-value-of-enum-classes-and-members5342044
Ref: 1b5c5342044
Node: 带有方法的 Enum 类5342577
Ref: library/enum enum-classes-with-methods5342718
Ref: 1b5d5342718
Node: 组合 Flag 的成员5343282
Ref: library/enum combining-members-of-flag5343385
Ref: 1b5e5343385
Node: graphlib --- 操作类似图的结构的功能5344194
Ref: library/graphlib doc5344325
Ref: 1b5f5344325
Ref: library/graphlib graphlib-functionality-to-operate-with-graph-like-structures5344325
Ref: 1b605344325
Ref: library/graphlib module-graphlib5344325
Ref: 895344325
Ref: library/graphlib graphlib TopologicalSorter5344530
Ref: 1825344530
Ref: library/graphlib graphlib TopologicalSorter add5347563
Ref: 1b615347563
Ref: library/graphlib graphlib TopologicalSorter prepare5348271
Ref: 1b625348271
Ref: library/graphlib graphlib TopologicalSorter is_active5348704
Ref: 1b635348704
Ref: library/graphlib graphlib TopologicalSorter done5349531
Ref: 1b655349531
Ref: library/graphlib graphlib TopologicalSorter get_ready5350255
Ref: 1b645350255
Ref: library/graphlib graphlib TopologicalSorter static_order5350805
Ref: 1b665350805
Ref: graphlib --- 操作类似图的结构的功能-Footnote-15352186
Node: 异常<2>5352253
Ref: library/graphlib exceptions5352345
Ref: 1b685352345
Ref: library/graphlib graphlib CycleError5352429
Ref: 1b675352429
Node: 數值與數學模組5353031
Ref: library/numeric doc5353176
Ref: 1b695353176
Ref: library/numeric numeric5353176
Ref: 1b6a5353176
Ref: library/numeric numeric-and-mathematical-modules5353176
Ref: 1b6b5353176
Node: numbers --- 数字的抽象基类5354039
Ref: library/numbers doc5354160
Ref: 1b6c5354160
Ref: library/numbers module-numbers5354160
Ref: c15354160
Ref: library/numbers numbers-numeric-abstract-base-classes5354160
Ref: 1b6d5354160
Ref: library/numbers numbers Number5354533
Ref: 15555354533
Ref: numbers --- 数字的抽象基类-Footnote-15354811
Ref: numbers --- 数字的抽象基类-Footnote-25354877
Node: 数字的层次5354926
Ref: library/numbers the-numeric-tower5355041
Ref: 1b6e5355041
Ref: library/numbers numbers Complex5355085
Ref: 15585355085
Ref: library/numbers numbers Complex real5355528
Ref: 1b6f5355528
Ref: library/numbers numbers Complex imag5355608
Ref: 1b705355608
Ref: library/numbers numbers Complex conjugate5355688
Ref: 1b715355688
Ref: library/numbers numbers Real5355829
Ref: 15575355829
Ref: library/numbers numbers Rational5356377
Ref: d205356377
Ref: library/numbers numbers Rational numerator5356625
Ref: 1b725356625
Ref: library/numbers numbers Rational denominator5356677
Ref: 1b735356677
Ref: library/numbers numbers Integral5356731
Ref: 15565356731
Node: 类型接口注释。5357108
Ref: library/numbers notes-for-type-implementors5357223
Ref: 1b745357223
Node: 加入更多数字的ABC5358008
Ref: library/numbers adding-more-numeric-abcs5358117
Ref: 1b755358117
Node: 实现算术运算5358424
Ref: library/numbers id15358533
Ref: 1b765358533
Ref: library/numbers implementing-the-arithmetic-operations5358533
Ref: 15545358533
Node: math --- 数学函数5363111
Ref: library/math doc5363278
Ref: 1b775363278
Ref: library/math math-mathematical-functions5363278
Ref: 1b785363278
Ref: library/math module-math5363278
Ref: b15363278
Node: 数论与表示函数5364138
Ref: library/math number-theoretic-and-representation-functions5364250
Ref: 1b795364250
Ref: library/math math ceil5364304
Ref: df35364304
Ref: library/math math comb5364529
Ref: 3185364529
Ref: library/math math copysign5365047
Ref: e035365047
Ref: library/math math fabs5365237
Ref: 1b7a5365237
Ref: library/math math factorial5365297
Ref: 1fc5365297
Ref: library/math math floor5365567
Ref: df25365567
Ref: library/math math fmod5365778
Ref: 16715365778
Ref: library/math math frexp5366641
Ref: 1b7b5366641
Ref: library/math math fsum5366990
Ref: e045366990
Ref: library/math math gcd5367679
Ref: 1be5367679
Ref: library/math math isclose5368114
Ref: 7795368114
Ref: library/math math isfinite5369274
Ref: c395369274
Ref: library/math math isinf5369489
Ref: e015369489
Ref: library/math math isnan5369611
Ref: e025369611
Ref: library/math math isqrt5369737
Ref: 3195369737
Ref: library/math math lcm5370210
Ref: 1bf5370210
Ref: library/math math ldexp5370532
Ref: 1b7c5370532
Ref: library/math math modf5370656
Ref: 1b7d5370656
Ref: library/math math nextafter5370784
Ref: 1c05370784
Ref: library/math math perm5371340
Ref: 3175371340
Ref: library/math math prod5371820
Ref: 3155371820
Ref: library/math math remainder5372118
Ref: 4b15372118
Ref: library/math math trunc5373052
Ref: df45373052
Ref: library/math math ulp5373222
Ref: 1c15373222
Ref: 数论与表示函数-Footnote-15374817
Ref: 数论与表示函数-Footnote-25374870
Node: 幂函数与对数函数5374919
Ref: library/math power-and-logarithmic-functions5375052
Ref: 1b7e5375052
Ref: library/math math exp5375111
Ref: d715375111
Ref: library/math math expm15375295
Ref: c3a5375295
Ref: library/math math log5375869
Ref: ed35375869
Ref: library/math math log1p5376086
Ref: e085376086
Ref: library/math math log25376235
Ref: afd5376235
Ref: library/math math log105376513
Ref: 1b7f5376513
Ref: library/math math pow5376621
Ref: 1b805376621
Ref: library/math math sqrt5377260
Ref: 31a5377260
Ref: 幂函数与对数函数-Footnote-15377356
Node: 三角函数5377415
Ref: library/math trigonometric-functions5377539
Ref: 1b815377539
Ref: library/math math acos5377578
Ref: 1b825377578
Ref: library/math math asin5377709
Ref: 1b835377709
Ref: library/math math atan5377852
Ref: 1b845377852
Ref: library/math math atan25377996
Ref: 1b855377996
Ref: library/math math cos5378453
Ref: ed25378453
Ref: library/math math dist5378518
Ref: 3135378518
Ref: library/math math hypot5378831
Ref: 3145378831
Ref: library/math math sin5379249
Ref: ed15379249
Ref: library/math math tan5379314
Ref: 1b865379314
Node: 角度转换5379379
Ref: library/math angular-conversion5379491
Ref: 1b875379491
Ref: library/math math degrees5379530
Ref: 1b885379530
Ref: library/math math radians5379608
Ref: 1b895379608
Node: 双曲函数5379686
Ref: library/math hyperbolic-functions5379798
Ref: 1b8a5379798
Ref: library/math math acosh5379915
Ref: e055379915
Ref: library/math math asinh5379985
Ref: e065379985
Ref: library/math math atanh5380055
Ref: e075380055
Ref: library/math math cosh5380125
Ref: 1b8b5380125
Ref: library/math math sinh5380191
Ref: 1b8c5380191
Ref: library/math math tanh5380257
Ref: 1b8d5380257
Ref: 双曲函数-Footnote-15380359
Node: 特殊函数5380417
Ref: library/math special-functions5380523
Ref: 1b8e5380523
Ref: library/math math erf5380562
Ref: 5535380562
Ref: library/math math erfc5380928
Ref: 5545380928
Ref: library/math math gamma5381165
Ref: c3b5381165
Ref: library/math math lgamma5381264
Ref: c3c5381264
Ref: 特殊函数-Footnote-15381412
Ref: 特殊函数-Footnote-25381465
Ref: 特殊函数-Footnote-35381557
Ref: 特殊函数-Footnote-45381610
Ref: 特殊函数-Footnote-55381669
Node: 常数5381722
Ref: library/math constants5381807
Ref: 1b8f5381807
Ref: library/math math pi5381836
Ref: 1b905381836
Ref: library/math math e5381920
Ref: 1b915381920
Ref: library/math math tau5382002
Ref: 1b925382002
Ref: library/math math inf5382320
Ref: 6215382320
Ref: library/math math nan5382492
Ref: 6225382492
Ref: 常数-Footnote-15383644
Ref: 常数-Footnote-25383696
Node: cmath --- 关于复数的数学函数5383724
Ref: library/cmath doc5383900
Ref: 1b935383900
Ref: library/cmath cmath-mathematical-functions-for-complex-numbers5383900
Ref: 1b945383900
Ref: library/cmath module-cmath5383900
Ref: 185383900
Node: 到极坐标和从极坐标的转换5384910
Ref: library/cmath conversions-to-and-from-polar-coordinates5385056
Ref: 1b955385056
Ref: library/cmath cmath phase5385726
Ref: 1b965385726
Ref: library/cmath cmath polar5386524
Ref: 1b975386524
Ref: library/cmath cmath rect5386756
Ref: 1b985386756
Node: 幂函数与对数函数<2>5386910
Ref: library/cmath power-and-logarithmic-functions5387080
Ref: 1b995387080
Ref: library/cmath cmath exp5387139
Ref: 1b9a5387139
Ref: library/cmath cmath log5387232
Ref: 1b9b5387232
Ref: library/cmath cmath log105387444
Ref: 1b9c5387444
Ref: library/cmath cmath sqrt5387578
Ref: 1b9d5387578
Node: 三角函数<2>5387693
Ref: library/cmath trigonometric-functions5387842
Ref: 1b9e5387842
Ref: library/cmath cmath acos5387881
Ref: 1b9f5387881
Ref: library/cmath cmath asin5388129
Ref: 1ba05388129
Ref: library/cmath cmath atan5388241
Ref: 1ba15388241
Ref: library/cmath cmath cos5388499
Ref: 1ba25388499
Ref: library/cmath cmath sin5388556
Ref: 1ba35388556
Ref: library/cmath cmath tan5388613
Ref: 1ba45388613
Node: 双曲函数<2>5388670
Ref: library/cmath hyperbolic-functions5388804
Ref: 1ba55388804
Ref: library/cmath cmath acosh5388843
Ref: 1ba65388843
Ref: library/cmath cmath asinh5389004
Ref: 1ba75389004
Ref: library/cmath cmath atanh5389242
Ref: 1ba85389242
Ref: library/cmath cmath cosh5389508
Ref: 1ba95389508
Ref: library/cmath cmath sinh5389575
Ref: 1baa5389575
Ref: library/cmath cmath tanh5389642
Ref: 1bab5389642
Node: 分类函数5389709
Ref: library/cmath classification-functions5389837
Ref: 1bac5389837
Ref: library/cmath cmath isfinite5389876
Ref: 1bad5389876
Ref: library/cmath cmath isinf5390036
Ref: 1bae5390036
Ref: library/cmath cmath isnan5390172
Ref: 1baf5390172
Ref: library/cmath cmath isclose5390301
Ref: 77a5390301
Ref: 分类函数-Footnote-15391503
Node: 常数<2>5391552
Ref: library/cmath constants5391656
Ref: 1bb05391656
Ref: library/cmath cmath pi5391685
Ref: 1bb15391685
Ref: library/cmath cmath e5391757
Ref: 1bb25391757
Ref: library/cmath cmath tau5391827
Ref: 61e5391827
Ref: library/cmath cmath inf5391924
Ref: 61f5391924
Ref: library/cmath cmath infj5392028
Ref: 6235392028
Ref: library/cmath cmath nan5392171
Ref: 6205392171
Ref: library/cmath cmath nanj5392290
Ref: 6245392290
Node: decimal --- 十进制定点和浮点运算5393545
Ref: library/decimal doc5393720
Ref: 1bb35393720
Ref: library/decimal decimal-decimal-fixed-point-and-floating-point-arithmetic5393720
Ref: 1bb45393720
Ref: library/decimal module-decimal5393720
Ref: 355393720
Ref: decimal --- 十进制定点和浮点运算-Footnote-15398174
Ref: decimal --- 十进制定点和浮点运算-Footnote-25398240
Node: 快速入门教程5398293
Ref: library/decimal decimal-tutorial5398413
Ref: 1bc45398413
Ref: library/decimal quick-start-tutorial5398413
Ref: 1bc55398413
Node: Decimal 对象5405147
Ref: library/decimal decimal-decimal5405291
Ref: 1bc85405291
Ref: library/decimal decimal-objects5405291
Ref: 1bc95405291
Ref: library/decimal decimal Decimal5405336
Ref: 2c05405336
Ref: library/decimal decimal Decimal adjusted5409903
Ref: 1bca5409903
Ref: library/decimal decimal Decimal as_integer_ratio5410174
Ref: 6355410174
Ref: library/decimal decimal Decimal as_tuple5410590
Ref: 1bcb5410590
Ref: library/decimal decimal Decimal canonical5410749
Ref: 1bcc5410749
Ref: library/decimal decimal Decimal compare5410951
Ref: 1bcd5410951
Ref: library/decimal decimal Decimal compare_signal5411368
Ref: 1bce5411368
Ref: library/decimal decimal Decimal compare_total5411662
Ref: 1bcf5411662
Ref: library/decimal decimal Decimal compare_total_mag5412811
Ref: 1bd05412811
Ref: library/decimal decimal Decimal conjugate5413372
Ref: 1bd15413372
Ref: library/decimal decimal Decimal copy_abs5413476
Ref: 1bd25413476
Ref: library/decimal decimal Decimal copy_negate5413653
Ref: 1bd35413653
Ref: library/decimal decimal Decimal copy_sign5413830
Ref: 1bd45413830
Ref: library/decimal decimal Decimal exp5414327
Ref: acc5414327
Ref: library/decimal decimal Decimal from_float5414723
Ref: c515414723
Ref: library/decimal decimal Decimal fma5415724
Ref: 1bd55415724
Ref: library/decimal decimal Decimal is_canonical5415962
Ref: 1bd65415962
Ref: library/decimal decimal Decimal is_finite5416230
Ref: 1bd75416230
Ref: library/decimal decimal Decimal is_infinite5416427
Ref: 1bd85416427
Ref: library/decimal decimal Decimal is_nan5416585
Ref: 1bd95416585
Ref: library/decimal decimal Decimal is_normal5416753
Ref: 1bda5416753
Ref: library/decimal decimal Decimal is_qnan5416981
Ref: 1bdb5416981
Ref: library/decimal decimal Decimal is_signed5417125
Ref: 1bdc5417125
Ref: library/decimal decimal Decimal is_snan5417316
Ref: 1bdd5417316
Ref: library/decimal decimal Decimal is_subnormal5417463
Ref: 1bde5417463
Ref: library/decimal decimal Decimal is_zero5417629
Ref: 1bdf5417629
Ref: library/decimal decimal Decimal ln5417785
Ref: acd5417785
Ref: library/decimal decimal Decimal log105417975
Ref: 1be05417975
Ref: library/decimal decimal Decimal logb5418159
Ref: 1be15418159
Ref: library/decimal decimal Decimal logical_and5418526
Ref: 1be25418526
Ref: library/decimal decimal Decimal logical_invert5418795
Ref: 1be45418795
Ref: library/decimal decimal Decimal logical_or5418962
Ref: 1be55418962
Ref: library/decimal decimal Decimal logical_xor5419232
Ref: 1be65419232
Ref: library/decimal decimal Decimal max5419499
Ref: 1be75419499
Ref: library/decimal decimal Decimal max_mag5419774
Ref: 1be85419774
Ref: library/decimal decimal Decimal min5419923
Ref: 1be95419923
Ref: library/decimal decimal Decimal min_mag5420198
Ref: 1bea5420198
Ref: library/decimal decimal Decimal next_minus5420347
Ref: 1beb5420347
Ref: library/decimal decimal Decimal next_plus5420582
Ref: 1bec5420582
Ref: library/decimal decimal Decimal next_toward5420816
Ref: 1bed5420816
Ref: library/decimal decimal Decimal normalize5421133
Ref: 1bee5421133
Ref: library/decimal decimal Decimal number_class5421516
Ref: 1bef5421516
Ref: library/decimal decimal Decimal quantize5422422
Ref: ad05422422
Ref: library/decimal decimal Decimal radix5423472
Ref: 1bf05423472
Ref: library/decimal decimal Decimal remainder_near5423694
Ref: 1bf15423694
Ref: library/decimal decimal Decimal rotate5424466
Ref: 1bf25424466
Ref: library/decimal decimal Decimal same_quantum5425051
Ref: 1bf35425051
Ref: library/decimal decimal Decimal scaleb5425422
Ref: 1bf45425422
Ref: library/decimal decimal Decimal shift5425696
Ref: 1bf55425696
Ref: library/decimal decimal Decimal sqrt5426189
Ref: 1bf65426189
Ref: library/decimal decimal Decimal to_eng_string5426293
Ref: 1bf75426293
Ref: library/decimal decimal Decimal to_integral5426703
Ref: 1bf85426703
Ref: library/decimal decimal Decimal to_integral_exact5426905
Ref: 1bfa5426905
Ref: library/decimal decimal Decimal to_integral_value5427343
Ref: 1bf95427343
Node: 逻辑操作数5427711
Ref: library/decimal logical-operands5427777
Ref: 1bfb5427777
Ref: library/decimal logical-operands-label5427777
Ref: 1be35427777
Node: 上下文对象5428089
Ref: library/decimal context-objects5428224
Ref: 1bfc5428224
Ref: library/decimal decimal-context5428224
Ref: 1bfd5428224
Ref: library/decimal decimal getcontext5428559
Ref: 1bc65428559
Ref: library/decimal decimal setcontext5428640
Ref: 1bc75428640
Ref: library/decimal decimal localcontext5428845
Ref: 18135428845
Ref: library/decimal decimal BasicContext5429694
Ref: ac85429694
Ref: library/decimal decimal ExtendedContext5430103
Ref: ac95430103
Ref: library/decimal decimal DefaultContext5430623
Ref: ac75430623
Ref: library/decimal decimal Context5431564
Ref: acf5431564
Ref: library/decimal decimal Context clear_flags5434216
Ref: 1c025434216
Ref: library/decimal decimal Context clear_traps5434302
Ref: 1c035434302
Ref: library/decimal decimal Context copy5434420
Ref: 1c045434420
Ref: library/decimal decimal Context copy_decimal5434497
Ref: 1c055434497
Ref: library/decimal decimal Context create_decimal5434596
Ref: acb5434596
Ref: library/decimal decimal Context create_decimal_from_float5435609
Ref: 1c065435609
Ref: library/decimal decimal Context Etiny5436362
Ref: 1c075436362
Ref: library/decimal decimal Context Etop5436575
Ref: 1c085436575
Ref: library/decimal decimal Context abs5437023
Ref: 1c095437023
Ref: library/decimal decimal Context add5437093
Ref: 1c0a5437093
Ref: library/decimal decimal Context canonical5437168
Ref: d655437168
Ref: library/decimal decimal Context compare5437255
Ref: 1c0b5437255
Ref: library/decimal decimal Context compare_signal5437343
Ref: 1c0c5437343
Ref: library/decimal decimal Context compare_total5437440
Ref: 1c0d5437440
Ref: library/decimal decimal Context compare_total_mag5437551
Ref: 1c0e5437551
Ref: library/decimal decimal Context copy_abs5437681
Ref: 1c0f5437681
Ref: library/decimal decimal Context copy_negate5437770
Ref: 1c105437770
Ref: library/decimal decimal Context copy_sign5437860
Ref: 1c115437860
Ref: library/decimal decimal Context divide5437943
Ref: 1c125437943
Ref: library/decimal decimal Context divide_int5438027
Ref: 1c135438027
Ref: library/decimal decimal Context divmod5438133
Ref: 1c145438133
Ref: library/decimal decimal Context exp5438234
Ref: 1c155438234
Ref: library/decimal decimal Context fma5438300
Ref: 1c165438300
Ref: library/decimal decimal Context is_canonical5438395
Ref: d665438395
Ref: library/decimal decimal Context is_finite5438521
Ref: 1c175438521
Ref: library/decimal decimal Context is_infinite5438649
Ref: 1c185438649
Ref: library/decimal decimal Context is_nan5438774
Ref: 1c195438774
Ref: library/decimal decimal Context is_normal5438900
Ref: 1c1a5438900
Ref: library/decimal decimal Context is_qnan5439023
Ref: 1c1b5439023
Ref: library/decimal decimal Context is_signed5439146
Ref: 1c1c5439146
Ref: library/decimal decimal Context is_snan5439259
Ref: 1c1d5439259
Ref: library/decimal decimal Context is_subnormal5439382
Ref: 1c1e5439382
Ref: library/decimal decimal Context is_zero5439511
Ref: 1c1f5439511
Ref: library/decimal decimal Context ln5439626
Ref: 1c205439626
Ref: library/decimal decimal Context log105439716
Ref: 1c215439716
Ref: library/decimal decimal Context logb5439801
Ref: 1c225439801
Ref: library/decimal decimal Context logical_and5439887
Ref: 1c235439887
Ref: library/decimal decimal Context logical_invert5439999
Ref: 1c245439999
Ref: library/decimal decimal Context logical_or5440086
Ref: 1c255440086
Ref: library/decimal decimal Context logical_xor5440196
Ref: 1c265440196
Ref: library/decimal decimal Context max5440308
Ref: 1c275440308
Ref: library/decimal decimal Context max_mag5440415
Ref: 1c285440415
Ref: library/decimal decimal Context min5440517
Ref: 1c295440517
Ref: library/decimal decimal Context min_mag5440624
Ref: 1c2a5440624
Ref: library/decimal decimal Context minus5440726
Ref: 1c2b5440726
Ref: library/decimal decimal Context multiply5440843
Ref: 1c2c5440843
Ref: library/decimal decimal Context next_minus5440923
Ref: 1c2d5440923
Ref: library/decimal decimal Context next_plus5441021
Ref: 1c2e5441021
Ref: library/decimal decimal Context next_toward5441118
Ref: 1c2f5441118
Ref: library/decimal decimal Context normalize5441222
Ref: 1c305441222
Ref: library/decimal decimal Context number_class5441304
Ref: 1c315441304
Ref: library/decimal decimal Context plus5441386
Ref: 1c325441386
Ref: library/decimal decimal Context power5441593
Ref: 1c335441593
Ref: library/decimal decimal Context quantize5443230
Ref: 1c345443230
Ref: library/decimal decimal Context radix5443341
Ref: 1c355443341
Ref: library/decimal decimal Context remainder5443434
Ref: 1c365443434
Ref: library/decimal decimal Context remainder_near5443604
Ref: 1c375443604
Ref: library/decimal decimal Context rotate5443814
Ref: 1c385443814
Ref: library/decimal decimal Context same_quantum5443901
Ref: 1c395443901
Ref: library/decimal decimal Context scaleb5444022
Ref: 1c3a5444022
Ref: library/decimal decimal Context shift5444138
Ref: 1c3b5444138
Ref: library/decimal decimal Context sqrt5444224
Ref: 1c3c5444224
Ref: library/decimal decimal Context subtract5444314
Ref: 1c3d5444314
Ref: library/decimal decimal Context to_eng_string5444394
Ref: 1c3e5444394
Ref: library/decimal decimal Context to_integral_exact5444685
Ref: 1c3f5444685
Ref: library/decimal decimal Context to_sci_string5444767
Ref: 1c405444767
Node: 常数<3>5444878
Ref: library/decimal constants5445011
Ref: 1c415445011
Ref: library/decimal decimal-rounding-modes5445011
Ref: 1c425445011
Ref: library/decimal decimal MAX_PREC5445407
Ref: 1bfe5445407
Ref: library/decimal decimal MAX_EMAX5445542
Ref: 1c015445542
Ref: library/decimal decimal MIN_EMIN5445677
Ref: 1c005445677
Ref: library/decimal decimal MIN_ETINY5445813
Ref: 1c435445813
Ref: library/decimal decimal HAVE_THREADS5445941
Ref: ac55445941
Ref: library/decimal decimal HAVE_CONTEXTVAR5446079
Ref: 1c445446079
Node: 舍入模式5446437
Ref: library/decimal rounding-modes5446561
Ref: 1bff5446561
Ref: library/decimal decimal ROUND_CEILING5446600
Ref: 1bb55446600
Ref: library/decimal decimal ROUND_DOWN5446673
Ref: 1bb65446673
Ref: library/decimal decimal ROUND_FLOOR5446731
Ref: 1bb75446731
Ref: library/decimal decimal ROUND_HALF_DOWN5446803
Ref: 1bb85446803
Ref: library/decimal decimal ROUND_HALF_EVEN5446908
Ref: 1bb95446908
Ref: library/decimal decimal ROUND_HALF_UP5447022
Ref: 1bba5447022
Ref: library/decimal decimal ROUND_UP5447131
Ref: 1bbb5447131
Ref: library/decimal decimal ROUND_05UP5447193
Ref: 1bbc5447193
Node: 信号5447347
Ref: library/decimal decimal-signals5447477
Ref: 1c455447477
Ref: library/decimal signals5447477
Ref: 1c465447477
Ref: library/decimal decimal Clamped5448127
Ref: 1bbd5448127
Ref: library/decimal decimal DecimalException5448402
Ref: 1c475448402
Ref: library/decimal decimal DivisionByZero5448531
Ref: 1bbe5448531
Ref: library/decimal decimal Inexact5448828
Ref: 1bbf5448828
Ref: library/decimal decimal InvalidOperation5449071
Ref: aca5449071
Ref: library/decimal decimal Overflow5449493
Ref: 1bc25449493
Ref: library/decimal decimal Rounded5449871
Ref: 1bc05449871
Ref: library/decimal decimal Subnormal5450210
Ref: 1bc15450210
Ref: library/decimal decimal Underflow5450441
Ref: 1bc35450441
Ref: library/decimal decimal FloatOperation5450688
Ref: ac45450688
Node: 浮点数说明5451930
Ref: library/decimal decimal-notes5452060
Ref: 1c485452060
Ref: library/decimal floating-point-notes5452060
Ref: 1c495452060
Node: 通过提升精度来解决舍入错误5452175
Ref: library/decimal mitigating-round-off-error-with-increased-precision5452287
Ref: 1c4a5452287
Node: 特殊的值5453774
Ref: library/decimal special-values5453886
Ref: 1c4b5453886
Node: 使用线程5456717
Ref: library/decimal decimal-threads5456847
Ref: 1c4c5456847
Ref: library/decimal working-with-threads5456847
Ref: 1c4d5456847
Node: 例程5458113
Ref: library/decimal decimal-recipes5458248
Ref: 1c4e5458248
Ref: library/decimal recipes5458248
Ref: 1c4f5458248
Node: Decimal 常见问题5463072
Ref: library/decimal decimal-faq5463186
Ref: 1c505463186
Ref: library/decimal id15463186
Ref: 1c515463186
Ref: Decimal 常见问题-Footnote-15470725
Ref: Decimal 常见问题-Footnote-25470792
Ref: Decimal 常见问题-Footnote-35470823
Ref: Decimal 常见问题-Footnote-45470881
Ref: Decimal 常见问题-Footnote-55470984
Node: fractions --- 分数5471088
Ref: library/fractions doc5471255
Ref: 1c525471255
Ref: library/fractions fractions-rational-numbers5471255
Ref: 1c535471255
Ref: library/fractions module-fractions5471255
Ref: 815471255
Ref: library/fractions fractions Fraction5471554
Ref: 2be5471554
Ref: library/fractions fractions Fraction numerator5474820
Ref: 1c555474820
Ref: library/fractions fractions Fraction denominator5474890
Ref: 1c565474890
Ref: library/fractions fractions Fraction as_integer_ratio5474962
Ref: 1c575474962
Ref: library/fractions fractions Fraction from_float5475154
Ref: c525475154
Ref: library/fractions fractions Fraction from_decimal5475582
Ref: c535475582
Ref: library/fractions fractions Fraction limit_denominator5475951
Ref: 1c545475951
Ref: library/fractions fractions Fraction __floor__5476782
Ref: 1c585476782
Ref: library/fractions fractions Fraction __ceil__5477060
Ref: 1c595477060
Ref: library/fractions fractions Fraction __round__5477231
Ref: 1c5a5477231
Ref: fractions --- 分数-Footnote-15477878
Node: random --- 生成伪随机数5477946
Ref: library/random doc5478104
Ref: 1c5b5478104
Ref: library/random module-random5478104
Ref: dc5478104
Ref: library/random random-generate-pseudo-random-numbers5478104
Ref: 1c5c5478104
Ref: random --- 生成伪随机数-Footnote-15480688
Ref: random --- 生成伪随机数-Footnote-25480753
Node: 簿记功能5480806
Ref: library/random bookkeeping-functions5480920
Ref: 1c605480920
Ref: library/random random seed5480959
Ref: cd35480959
Ref: library/random random getstate5481957
Ref: 1c615481957
Ref: library/random random setstate5482123
Ref: 1c625482123
Node: 用于字节数据的函数5482362
Ref: library/random functions-for-bytes5482500
Ref: 1c635482500
Ref: library/random random randbytes5482564
Ref: 104f5482564
Node: 整数用函数5482766
Ref: library/random functions-for-integers5482907
Ref: 1c655482907
Ref: library/random random randrange5482951
Ref: c8b5482951
Ref: library/random random randint5483594
Ref: c8c5483594
Ref: library/random random getrandbits5483722
Ref: a175483722
Node: 序列用函数5484148
Ref: library/random functions-for-sequences5484274
Ref: 1c665484274
Ref: library/random random choice5484318
Ref: c8d5484318
Ref: library/random random choices5484470
Ref: 66b5484470
Ref: library/random random shuffle5486249
Ref: 2125486249
Ref: library/random random sample5487051
Ref: c8e5487051
Node: 实值分布5488534
Ref: library/random id15488660
Ref: 1c675488660
Ref: library/random real-valued-distributions5488660
Ref: 1c685488660
Ref: library/random random random5488906
Ref: 1c5d5488906
Ref: library/random random uniform5489000
Ref: 1c695489000
Ref: library/random random triangular5489299
Ref: 1c6a5489299
Ref: library/random random betavariate5489595
Ref: 1c6b5489595
Ref: library/random random expovariate5489768
Ref: 1c6c5489768
Ref: library/random random gammavariate5490127
Ref: 1c6d5490127
Ref: library/random random gauss5490495
Ref: 1c6e5490495
Ref: library/random random lognormvariate5491023
Ref: 1c705491023
Ref: library/random random normalvariate5491287
Ref: 1c6f5491287
Ref: library/random random vonmisesvariate5491399
Ref: 1c715491399
Ref: library/random random paretovariate5491713
Ref: 1c725491713
Ref: library/random random weibullvariate5491807
Ref: 1c735491807
Node: 替代生成器5491933
Ref: library/random alternative-generator5492068
Ref: 1c745492068
Ref: library/random random Random5492112
Ref: 1c5e5492112
Ref: library/random random SystemRandom5492432
Ref: 1c5f5492432
Node: 关于再现性的说明5492864
Ref: library/random notes-on-reproducibility5492993
Ref: 1c755492993
Node: 例子5493583
Ref: library/random examples5493706
Ref: 1c765493706
Ref: library/random random-examples5493706
Ref: c2a5493706
Ref: 例子-Footnote-15498963
Ref: 例子-Footnote-25499028
Ref: 例子-Footnote-35499109
Ref: 例子-Footnote-45499155
Ref: 例子-Footnote-55499207
Ref: 例子-Footnote-65499262
Ref: 例子-Footnote-75499338
Ref: 例子-Footnote-85499373
Ref: 例子-Footnote-95499451
Node: 例程<2>5499486
Ref: library/random recipes5499576
Ref: 1c775499576
Ref: 例程<2>-Footnote-15501410
Node: statistics --- 數學統計函式5501478
Ref: library/statistics doc5501607
Ref: 1c785501607
Ref: library/statistics module-statistics5501607
Ref: f55501607
Ref: library/statistics statistics-mathematical-statistics-functions5501607
Ref: 1c795501607
Ref: statistics --- 數學統計函式-Footnote-15502771
Ref: statistics --- 數學統計函式-Footnote-25502840
Ref: statistics --- 數學統計函式-Footnote-35502866
Node: 平均值與中央位置量數5502897
Ref: library/statistics averages-and-measures-of-central-location5503029
Ref: 1c7a5503029
Node: 離度 spread 的測量5504540
Ref: library/statistics measures-of-spread5504693
Ref: 1c7f5504693
Node: 函式細節5505235
Ref: library/statistics function-details5505367
Ref: 1c845505367
Ref: library/statistics statistics mean5505559
Ref: 2ce5505559
Ref: library/statistics statistics fmean5506934
Ref: 3545506934
Ref: library/statistics statistics geometric_mean5507356
Ref: 3555507356
Ref: library/statistics statistics harmonic_mean5507961
Ref: 6865507961
Ref: library/statistics statistics median5509297
Ref: 1c7b5509297
Ref: library/statistics statistics median_low5510229
Ref: 1c7c5510229
Ref: library/statistics statistics median_high5510844
Ref: 1c7d5510844
Ref: library/statistics statistics median_grouped5511456
Ref: 1c7e5511456
Ref: library/statistics statistics mode5513032
Ref: 3dd5513032
Ref: library/statistics statistics multimode5514138
Ref: 3565514138
Ref: library/statistics statistics pstdev5514543
Ref: 1c805514543
Ref: library/statistics statistics pvariance5514807
Ref: 1c815514807
Ref: library/statistics statistics stdev5516914
Ref: 1c825516914
Ref: library/statistics statistics variance5517178
Ref: 1c835517178
Ref: library/statistics statistics quantiles5519316
Ref: 3575519316
Ref: 函式細節-Footnote-15521949
Ref: 函式細節-Footnote-25521995
Ref: 函式細節-Footnote-35522050
Ref: 函式細節-Footnote-45522145
Node: 异常<3>5522225
Ref: library/statistics exceptions5522351
Ref: 1c865522351
Ref: library/statistics statistics StatisticsError5522409
Ref: 1c855522409
Node: NormalDist 对象5522521
Ref: library/statistics normaldist-objects5522626
Ref: 1c875522626
Ref: library/statistics statistics NormalDist5522955
Ref: 3585522955
Ref: library/statistics statistics NormalDist mean5523210
Ref: 1c885523210
Ref: library/statistics statistics NormalDist median5523321
Ref: 1c895523321
Ref: library/statistics statistics NormalDist mode5523428
Ref: 1c8a5523428
Ref: library/statistics statistics NormalDist stdev5523530
Ref: 1c8b5523530
Ref: library/statistics statistics NormalDist variance5523636
Ref: 1c8c5523636
Ref: library/statistics statistics NormalDist from_samples5523781
Ref: 1c8d5523781
Ref: library/statistics statistics NormalDist samples5524328
Ref: 1c8e5524328
Ref: library/statistics statistics NormalDist pdf5524711
Ref: 1c8f5524711
Ref: library/statistics statistics NormalDist cdf5525240
Ref: 1c905525240
Ref: library/statistics statistics NormalDist inv_cdf5525437
Ref: 1c915525437
Ref: library/statistics statistics NormalDist overlap5525768
Ref: 1c925525768
Ref: library/statistics statistics NormalDist quantiles5525976
Ref: 1c935525976
Ref: library/statistics statistics NormalDist zscore5526422
Ref: 1c945526422
Ref: NormalDist 对象-Footnote-15527708
Ref: NormalDist 对象-Footnote-25527772
Ref: NormalDist 对象-Footnote-35527832
Ref: NormalDist 对象-Footnote-45527886
Ref: NormalDist 对象-Footnote-55527943
Ref: NormalDist 对象-Footnote-65527997
Ref: NormalDist 对象-Footnote-75528042
Ref: NormalDist 对象-Footnote-85528098
Ref: NormalDist 对象-Footnote-95528155
Ref: NormalDist 对象-Footnote-105528202
Ref: NormalDist 对象-Footnote-115528270
Ref: NormalDist 对象-Footnote-125528342
Ref: NormalDist 对象-Footnote-135528399
Ref: NormalDist 对象-Footnote-145528491
Ref: NormalDist 对象-Footnote-155528538
Ref: NormalDist 对象-Footnote-165528616
Node: NormalDist 示例和用法5528701
Ref: library/statistics normaldist-examples-and-recipes5528781
Ref: 1c955528781
Ref: NormalDist 示例和用法-Footnote-15533136
Ref: NormalDist 示例和用法-Footnote-25533207
Ref: NormalDist 示例和用法-Footnote-35533254
Ref: NormalDist 示例和用法-Footnote-45533299
Ref: NormalDist 示例和用法-Footnote-55533356
Ref: NormalDist 示例和用法-Footnote-65533419
Ref: NormalDist 示例和用法-Footnote-75533500
Ref: NormalDist 示例和用法-Footnote-85533556
Node: 函式編程模組5533626
Ref: library/functional doc5533780
Ref: 1c965533780
Ref: library/functional functional-programming-modules5533780
Ref: 1c975533780
Node: itertools --- 为高效循环而创建迭代器的函数5534304
Ref: library/itertools doc5534480
Ref: 1c985534480
Ref: library/itertools itertools-functions-creating-iterators-for-efficient-looping5534480
Ref: 1c995534480
Ref: library/itertools module-itertools5534480
Ref: a35534480
Node: Itertool函数5544700
Ref: library/itertools itertool-functions5544832
Ref: 1ca05544832
Ref: library/itertools itertools-functions5544832
Ref: 1ca15544832
Ref: library/itertools itertools accumulate5545041
Ref: 30e5545041
Ref: library/itertools itertools chain5548408
Ref: 17385548408
Ref: library/itertools itertools chain from_iterable5548906
Ref: 1c9b5548906
Ref: library/itertools itertools combinations5549367
Ref: d6e5549367
Ref: library/itertools itertools combinations_with_replacement5551221
Ref: ce35551221
Ref: library/itertools itertools compress5553050
Ref: ce45553050
Ref: library/itertools itertools count5553466
Ref: ce55553466
Ref: library/itertools itertools cycle5554199
Ref: 1c9a5554199
Ref: library/itertools itertools dropwhile5554872
Ref: 1c9c5554872
Ref: library/itertools itertools filterfalse5555543
Ref: 17225555543
Ref: library/itertools itertools groupby5556090
Ref: 1c9d5556090
Ref: library/itertools itertools islice5558718
Ref: 4a85558718
Ref: library/itertools itertools permutations5560647
Ref: fc95560647
Ref: library/itertools itertools product5562955
Ref: d6f5562955
Ref: library/itertools itertools repeat5564424
Ref: 11e75564424
Ref: library/itertools itertools starmap5565272
Ref: b055565272
Ref: library/itertools itertools takewhile5565921
Ref: 1c9e5565921
Ref: library/itertools itertools tee5566350
Ref: 1c9f5566350
Ref: library/itertools itertools zip_longest5568011
Ref: cfb5568011
Ref: Itertool函数-Footnote-15569411
Node: itertools 配方5569469
Ref: library/itertools id15569601
Ref: 1ca35569601
Ref: library/itertools itertools-recipes5569601
Ref: cc05569601
Ref: itertools 配方-Footnote-15579134
Node: functools --- 高阶函数和可调用对象上的操作5579183
Ref: library/functools doc5579408
Ref: 1ca45579408
Ref: library/functools functools-higher-order-functions-and-operations-on-callable-objects5579408
Ref: 1ca55579408
Ref: library/functools module-functools5579408
Ref: 835579408
Ref: library/functools functools cache5579860
Ref: 1ca65579860
Ref: library/functools functools cached_property5580652
Ref: 2f95580652
Ref: library/functools functools cmp_to_key5583031
Ref: c285583031
Ref: library/functools functools lru_cache5584024
Ref: 2f85584024
Ref: library/functools functools total_ordering5588168
Ref: 9385588168
Ref: library/functools functools partial5589929
Ref: 8b55589929
Ref: library/functools functools partialmethod5591237
Ref: 3bf5591237
Ref: library/functools functools reduce5592929
Ref: d375592929
Ref: library/functools functools singledispatch5594087
Ref: 4905594087
Ref: library/functools functools singledispatchmethod5598821
Ref: 2fa5598821
Ref: library/functools functools update_wrapper5600523
Ref: a3b5600523
Ref: library/functools functools wraps5602566
Ref: 9555602566
Ref: functools --- 高阶函数和可调用对象上的操作-Footnote-15603822
Ref: functools --- 高阶函数和可调用对象上的操作-Footnote-25603890
Ref: functools --- 高阶函数和可调用对象上的操作-Footnote-35603940
Ref: functools --- 高阶函数和可调用对象上的操作-Footnote-45603989
Ref: functools --- 高阶函数和可调用对象上的操作-Footnote-55604081
Ref: functools --- 高阶函数和可调用对象上的操作-Footnote-65604132
Ref: functools --- 高阶函数和可调用对象上的操作-Footnote-75604189
Node: partial 对象5604232
Ref: library/functools id15604339
Ref: 1ca95604339
Ref: library/functools partial-objects5604339
Ref: 1ca75604339
Ref: library/functools functools partial func5604513
Ref: 1caa5604513
Ref: library/functools functools partial args5604694
Ref: 1cab5604694
Ref: library/functools functools partial keywords5604835
Ref: 1cac5604835
Node: operator --- 标准运算符替代函数5605361
Ref: library/operator doc5605521
Ref: 1cad5605521
Ref: library/operator module-operator5605521
Ref: c25605521
Ref: library/operator operator-standard-operators-as-functions5605521
Ref: 1cae5605521
Ref: library/operator operator lt5606289
Ref: 1caf5606289
Ref: library/operator operator le5606320
Ref: 1cb05606320
Ref: library/operator operator eq5606351
Ref: 1cb15606351
Ref: library/operator operator ne5606382
Ref: 1cb25606382
Ref: library/operator operator ge5606413
Ref: 1cb35606413
Ref: library/operator operator gt5606444
Ref: 1cb45606444
Ref: library/operator operator __lt__5606475
Ref: 1cb55606475
Ref: library/operator operator __le__5606510
Ref: 1cb65606510
Ref: library/operator operator __eq__5606545
Ref: 1cb75606545
Ref: library/operator operator __ne__5606580
Ref: 1cb85606580
Ref: library/operator operator __ge__5606615
Ref: 1cb95606615
Ref: library/operator operator __gt__5606650
Ref: 1cba5606650
Ref: library/operator operator not_5607259
Ref: 1cbb5607259
Ref: library/operator operator __not__5607291
Ref: 1cbc5607291
Ref: library/operator operator truth5607576
Ref: 1cbd5607576
Ref: library/operator operator is_5607755
Ref: 1cbe5607755
Ref: library/operator operator is_not5607839
Ref: 1cbf5607839
Ref: library/operator operator abs5607977
Ref: 1cc05607977
Ref: library/operator operator __abs__5608008
Ref: 1cc15608008
Ref: library/operator operator add5608079
Ref: 1cc25608079
Ref: library/operator operator __add__5608111
Ref: 1cc35608111
Ref: library/operator operator and_5608203
Ref: 1cc45608203
Ref: library/operator operator __and__5608236
Ref: 1cc55608236
Ref: library/operator operator floordiv5608320
Ref: 1cc65608320
Ref: library/operator operator __floordiv__5608357
Ref: 1cc75608357
Ref: library/operator operator index5608428
Ref: 15bf5608428
Ref: library/operator operator __index__5608459
Ref: 1cc85608459
Ref: library/operator operator inv5608573
Ref: 1cc95608573
Ref: library/operator operator invert5608604
Ref: 1cca5608604
Ref: library/operator operator __inv__5608638
Ref: 1ccb5608638
Ref: library/operator operator __invert__5608673
Ref: 1ccc5608673
Ref: library/operator operator lshift5608789
Ref: 1ccd5608789
Ref: library/operator operator __lshift__5608824
Ref: 1cce5608824
Ref: library/operator operator mod5608908
Ref: 1ccf5608908
Ref: library/operator operator __mod__5608940
Ref: 1cd05608940
Ref: library/operator operator mul5609005
Ref: 1ca25609005
Ref: library/operator operator __mul__5609037
Ref: 1cd15609037
Ref: library/operator operator matmul5609129
Ref: 80c5609129
Ref: library/operator operator __matmul__5609164
Ref: 1cd25609164
Ref: library/operator operator neg5609256
Ref: 1cd35609256
Ref: library/operator operator __neg__5609287
Ref: 1cd45609287
Ref: library/operator operator or_5609374
Ref: 1cd55609374
Ref: library/operator operator __or__5609406
Ref: 1cd65609406
Ref: library/operator operator pos5609489
Ref: 1cd75609489
Ref: library/operator operator __pos__5609520
Ref: 1cd85609520
Ref: library/operator operator pow5609607
Ref: 1cd95609607
Ref: library/operator operator __pow__5609639
Ref: 1cda5609639
Ref: library/operator operator rshift5609732
Ref: 1cdb5609732
Ref: library/operator operator __rshift__5609767
Ref: 1cdc5609767
Ref: library/operator operator sub5609851
Ref: 1cdd5609851
Ref: library/operator operator __sub__5609883
Ref: 1cde5609883
Ref: library/operator operator truediv5609948
Ref: 1cdf5609948
Ref: library/operator operator __truediv__5609984
Ref: 1ce05609984
Ref: library/operator operator xor5610124
Ref: 1ce15610124
Ref: library/operator operator __xor__5610156
Ref: 1ce25610156
Ref: library/operator operator concat5610314
Ref: 1ce35610314
Ref: library/operator operator __concat__5610349
Ref: 1ce45610349
Ref: library/operator operator contains5610444
Ref: 17a5610444
Ref: library/operator operator __contains__5610481
Ref: 1ce55610481
Ref: library/operator operator countOf5610602
Ref: 17c5610602
Ref: library/operator operator delitem5610686
Ref: 1ce65610686
Ref: library/operator operator __delitem__5610722
Ref: 1ce75610722
Ref: library/operator operator getitem5610810
Ref: 1ce85610810
Ref: library/operator operator __getitem__5610846
Ref: 1ce95610846
Ref: library/operator operator indexOf5610931
Ref: 17b5610931
Ref: library/operator operator setitem5611030
Ref: 1cea5611030
Ref: library/operator operator __setitem__5611069
Ref: 1ceb5611069
Ref: library/operator operator length_hint5611167
Ref: 9685611167
Ref: library/operator operator attrgetter5611693
Ref: 80a5611693
Ref: library/operator operator itemgetter5612977
Ref: 38b5612977
Ref: library/operator operator methodcaller5614726
Ref: 80b5614726
Ref: operator --- 标准运算符替代函数-Footnote-15615503
Node: 将运算符映射到函数5615570
Ref: library/operator mapping-operators-to-functions5615698
Ref: 1cec5615698
Ref: library/operator operator-map5615698
Ref: 1ced5615698
Node: 原地运算符5623201
Ref: library/operator in-place-operators5623329
Ref: 1cee5623329
Ref: library/operator operator iadd5624473
Ref: 1cf05624473
Ref: library/operator operator __iadd__5624506
Ref: 1cf15624506
Ref: library/operator operator iand5624597
Ref: 1cf25624597
Ref: library/operator operator __iand__5624630
Ref: 1cf35624630
Ref: library/operator operator iconcat5624721
Ref: 1cf45624721
Ref: library/operator operator __iconcat__5624757
Ref: 1cf55624757
Ref: library/operator operator ifloordiv5624883
Ref: 1cf65624883
Ref: library/operator operator __ifloordiv__5624921
Ref: 1cf75624921
Ref: library/operator operator ilshift5625023
Ref: 1cf85625023
Ref: library/operator operator __ilshift__5625059
Ref: 1cf95625059
Ref: library/operator operator imod5625157
Ref: 1cfa5625157
Ref: library/operator operator __imod__5625190
Ref: 1cfb5625190
Ref: library/operator operator imul5625281
Ref: 1cfc5625281
Ref: library/operator operator __imul__5625314
Ref: 1cfd5625314
Ref: library/operator operator imatmul5625405
Ref: 80d5625405
Ref: library/operator operator __imatmul__5625441
Ref: 1cfe5625441
Ref: library/operator operator ior5625562
Ref: 1cff5625562
Ref: library/operator operator __ior__5625594
Ref: 1d005625594
Ref: library/operator operator ipow5625683
Ref: 1d015625683
Ref: library/operator operator __ipow__5625716
Ref: 1d025625716
Ref: library/operator operator irshift5625808
Ref: 1d035625808
Ref: library/operator operator __irshift__5625844
Ref: 1d045625844
Ref: library/operator operator isub5625942
Ref: 1d055625942
Ref: library/operator operator __isub__5625975
Ref: 1d065625975
Ref: library/operator operator itruediv5626066
Ref: 1d075626066
Ref: library/operator operator __itruediv__5626103
Ref: 1d085626103
Ref: library/operator operator ixor5626202
Ref: 1d095626202
Ref: library/operator operator __ixor__5626235
Ref: 1d0a5626235
Node: 檔案與目錄存取5626326
Ref: library/filesys doc5626474
Ref: 1d0b5626474
Ref: library/filesys file-and-directory-access5626474
Ref: 1d0c5626474
Ref: library/filesys filesys5626474
Ref: 1d0d5626474
Node: pathlib --- 面向对象的文件系统路径5627499
Ref: library/pathlib doc5627641
Ref: 1d0e5627641
Ref: library/pathlib module-pathlib5627641
Ref: c85627641
Ref: library/pathlib pathlib-object-oriented-filesystem-paths5627641
Ref: 1d0f5627641
Ref: pathlib --- 面向对象的文件系统路径-Footnote-15629121
Ref: pathlib --- 面向对象的文件系统路径-Footnote-25629187
Node: 基础使用5629236
Ref: library/pathlib basic-use5629348
Ref: 1d145629348
Node: 纯路径5630271
Ref: library/pathlib id15630404
Ref: 1d155630404
Ref: library/pathlib pure-paths5630404
Ref: 1d105630404
Ref: library/pathlib pathlib PurePath5630578
Ref: 2355630578
Ref: library/pathlib pathlib PurePosixPath5632651
Ref: 1d165632651
Ref: library/pathlib pathlib PureWindowsPath5632932
Ref: 1d135632932
Node: 通用性质5633469
Ref: library/pathlib general-properties5633548
Ref: 1d175633548
Node: 运算符<2>5634370
Ref: library/pathlib operators5634476
Ref: 1d185634476
Node: 访问个别部分5635669
Ref: library/pathlib accessing-individual-parts5635784
Ref: 1d195635784
Ref: library/pathlib pathlib PurePath parts5635913
Ref: 1d1a5635913
Node: 方法和特征属性5636291
Ref: library/pathlib methods-and-properties5636385
Ref: 1d1b5636385
Ref: library/pathlib pathlib PurePath drive5636488
Ref: 1d1c5636488
Ref: library/pathlib pathlib PurePath root5636909
Ref: 1d1d5636909
Ref: library/pathlib pathlib PurePath anchor5637300
Ref: 1d1e5637300
Ref: library/pathlib pathlib PurePath parents5637647
Ref: 1d1f5637647
Ref: library/pathlib pathlib PurePath parent5638011
Ref: 1d205638011
Ref: library/pathlib pathlib PurePath name5638767
Ref: 1d225638767
Ref: library/pathlib pathlib PurePath suffix5639156
Ref: 1d235639156
Ref: library/pathlib pathlib PurePath suffixes5639451
Ref: 1d245639451
Ref: library/pathlib pathlib PurePath stem5639753
Ref: 1d255639753
Ref: library/pathlib pathlib PurePath as_posix5640042
Ref: 1d265640042
Ref: library/pathlib pathlib PurePath as_uri5640287
Ref: 1d275640287
Ref: library/pathlib pathlib PurePath is_absolute5640640
Ref: 1d285640640
Ref: library/pathlib pathlib PurePath is_relative_to5641247
Ref: 1d295641247
Ref: library/pathlib pathlib PurePath is_reserved5641533
Ref: 1d2a5641533
Ref: library/pathlib pathlib PurePath joinpath5642015
Ref: 1d2b5642015
Ref: library/pathlib pathlib PurePath match5642570
Ref: 1d2c5642570
Ref: library/pathlib pathlib PurePath relative_to5643520
Ref: 1d2d5643520
Ref: library/pathlib pathlib PurePath with_name5644361
Ref: 1d2e5644361
Ref: library/pathlib pathlib PurePath with_stem5645069
Ref: 1d2f5645069
Ref: library/pathlib pathlib PurePath with_suffix5646086
Ref: 11665646086
Node: 具体路径5646744
Ref: library/pathlib concrete-paths5646893
Ref: 1d115646893
Ref: library/pathlib id25646893
Ref: 1d305646893
Ref: library/pathlib pathlib Path5647115
Ref: 32f5647115
Ref: library/pathlib pathlib PosixPath5647464
Ref: 1d315647464
Ref: library/pathlib pathlib WindowsPath5647781
Ref: 1d125647781
Node: 方法<2>5648735
Ref: library/pathlib methods5648793
Ref: 1d325648793
Ref: library/pathlib pathlib Path cwd5649340
Ref: 1d335649340
Ref: library/pathlib pathlib Path home5649569
Ref: 81a5649569
Ref: library/pathlib pathlib Path stat5650112
Ref: 1d345650112
Ref: library/pathlib pathlib Path chmod5650470
Ref: 1d355650470
Ref: library/pathlib pathlib Path exists5650740
Ref: 3305650740
Ref: library/pathlib pathlib Path expanduser5651206
Ref: 8195651206
Ref: library/pathlib pathlib Path glob5651779
Ref: 10845651779
Ref: library/pathlib pathlib Path group5652724
Ref: 1d365652724
Ref: library/pathlib pathlib Path is_dir5652896
Ref: 3315652896
Ref: library/pathlib pathlib Path is_file5653243
Ref: 3325653243
Ref: library/pathlib pathlib Path is_mount5653605
Ref: 3335653605
Ref: library/pathlib pathlib Path is_symlink5654102
Ref: 3345654102
Ref: library/pathlib pathlib Path is_socket5654322
Ref: 3385654322
Ref: library/pathlib pathlib Path is_fifo5654692
Ref: 3375654692
Ref: library/pathlib pathlib Path is_block_device5655053
Ref: 3355655053
Ref: library/pathlib pathlib Path is_char_device5655403
Ref: 3365655403
Ref: library/pathlib pathlib Path iterdir5655755
Ref: 1d375655755
Ref: library/pathlib pathlib Path lchmod5656463
Ref: 1d385656463
Ref: library/pathlib pathlib Path lstat5656658
Ref: 1d395656658
Ref: library/pathlib pathlib Path mkdir5656835
Ref: 8185656835
Ref: library/pathlib pathlib Path open5657895
Ref: 1d3a5657895
Ref: library/pathlib pathlib Path owner5658247
Ref: 1d3b5658247
Ref: library/pathlib pathlib Path read_bytes5658418
Ref: 81e5658418
Ref: library/pathlib pathlib Path read_text5658728
Ref: 81c5658728
Ref: library/pathlib pathlib Path readlink5659145
Ref: 1d05659145
Ref: library/pathlib pathlib Path rename5659429
Ref: 1d3c5659429
Ref: library/pathlib pathlib Path replace5660250
Ref: 1d3d5660250
Ref: library/pathlib pathlib Path resolve5660733
Ref: 1d215660733
Ref: library/pathlib pathlib Path rglob5661637
Ref: 10855661637
Ref: library/pathlib pathlib Path rmdir5662134
Ref: 1d3e5662134
Ref: library/pathlib pathlib Path samefile5662219
Ref: 8175662219
Ref: library/pathlib pathlib Path symlink_to5662740
Ref: 1d3f5662740
Ref: library/pathlib pathlib Path link_to5663419
Ref: 3395663419
Ref: library/pathlib pathlib Path touch5663803
Ref: 1d405663803
Ref: library/pathlib pathlib Path unlink5664206
Ref: 11095664206
Ref: library/pathlib pathlib Path write_bytes5664698
Ref: 81d5664698
Ref: library/pathlib pathlib Path write_text5665052
Ref: 81b5665052
Node: 对应的 os 模块的工具5665477
Ref: library/pathlib correspondence-to-tools-in-the-os-module5665608
Ref: 1d415665608
Node: os path --- 常用路径操作5670148
Ref: library/os path doc5670346
Ref: 1d475670346
Ref: library/os path module-os path5670346
Ref: c55670346
Ref: library/os path os-path-common-pathname-manipulations5670346
Ref: 1d485670346
Ref: library/os path os path abspath5672589
Ref: d785672589
Ref: library/os path os path basename5672891
Ref: 1d445672891
Ref: library/os path os path commonpath5673356
Ref: 8145673356
Ref: library/os path os path commonprefix5673876
Ref: 8155673876
Ref: library/os path os path dirname5674499
Ref: 1d455674499
Ref: library/os path os path exists5674752
Ref: 3255674752
Ref: library/os path os path lexists5675356
Ref: 3265675356
Ref: library/os path os path expanduser5675673
Ref: 32c5675673
Ref: library/os path os path expandvars5676600
Ref: e095676600
Ref: library/os path os path getatime5677066
Ref: 1d4a5677066
Ref: library/os path os path getmtime5677323
Ref: 1d4b5677323
Ref: library/os path os path getctime5677645
Ref: 1d4c5677645
Ref: library/os path os path getsize5678116
Ref: 1d4d5678116
Ref: library/os path os path isabs5678358
Ref: 1d435678358
Ref: library/os path os path isfile5678669
Ref: 3285678669
Ref: library/os path os path isdir5679000
Ref: 3275679000
Ref: library/os path os path islink5679323
Ref: 3235679323
Ref: library/os path os path ismount5679614
Ref: 3295679614
Ref: library/os path os path join5680447
Ref: 10c75680447
Ref: library/os path os path normcase5681424
Ref: 1d4e5681424
Ref: library/os path os path normpath5681710
Ref: d775681710
Ref: library/os path os path realpath5682605
Ref: 32d5682605
Ref: library/os path os path relpath5683092
Ref: 1d425683092
Ref: library/os path os path samefile5683626
Ref: 96d5683626
Ref: library/os path os path sameopenfile5684115
Ref: 1d505684115
Ref: library/os path os path samestat5684410
Ref: 96c5684410
Ref: library/os path os path split5684945
Ref: 1d495684945
Ref: library/os path os path splitdrive5685735
Ref: 57b5685735
Ref: library/os path os path splitext5686593
Ref: 1d465686593
Ref: library/os path os path supports_unicode_filenames5687522
Ref: eb15687522
Ref: os path --- 常用路径操作-Footnote-15687723
Ref: os path --- 常用路径操作-Footnote-25687791
Ref: os path --- 常用路径操作-Footnote-35687856
Node: fileinput --- 迭代来自多个输入流的行5687947
Ref: library/fileinput doc5688127
Ref: 1d515688127
Ref: library/fileinput fileinput-iterate-over-lines-from-multiple-input-streams5688127
Ref: 1d525688127
Ref: library/fileinput module-fileinput5688127
Ref: 7e5688127
Ref: library/fileinput fileinput input5690217
Ref: 3cf5690217
Ref: library/fileinput fileinput filename5691235
Ref: 1d535691235
Ref: library/fileinput fileinput fileno5691364
Ref: 1d545691364
Ref: library/fileinput fileinput lineno5691549
Ref: 1d555691549
Ref: library/fileinput fileinput filelineno5691758
Ref: 1d565691758
Ref: library/fileinput fileinput isfirstline5691980
Ref: 1d575691980
Ref: library/fileinput fileinput isstdin5692126
Ref: 1d585692126
Ref: library/fileinput fileinput nextfile5692264
Ref: 1d595692264
Ref: library/fileinput fileinput close5692741
Ref: 1d5a5692741
Ref: library/fileinput fileinput FileInput5692875
Ref: 3a45692875
Ref: library/fileinput fileinput hook_compressed5695350
Ref: 1d5c5695350
Ref: library/fileinput fileinput hook_encoded5695836
Ref: 6445695836
Ref: fileinput --- 迭代来自多个输入流的行-Footnote-15696251
Node: stat --- 解析 stat 结果5696319
Ref: library/stat doc5696505
Ref: 1d5d5696505
Ref: library/stat module-stat5696505
Ref: f45696505
Ref: library/stat stat-interpreting-stat-results5696505
Ref: 1d5e5696505
Ref: library/stat stat S_ISDIR5697113
Ref: 1d5f5697113
Ref: library/stat stat S_ISCHR5697204
Ref: 1d605697204
Ref: library/stat stat S_ISBLK5697313
Ref: 1d615697313
Ref: library/stat stat S_ISREG5697419
Ref: 1d625697419
Ref: library/stat stat S_ISFIFO5697516
Ref: 1d635697516
Ref: library/stat stat S_ISLNK5697623
Ref: 1d645697623
Ref: library/stat stat S_ISSOCK5697720
Ref: 1d655697720
Ref: library/stat stat S_ISDOOR5697815
Ref: 10c85697815
Ref: library/stat stat S_ISPORT5697928
Ref: 10c95697928
Ref: library/stat stat S_ISWHT5698050
Ref: 10ca5698050
Ref: library/stat stat S_IMODE5698248
Ref: 1d665698248
Ref: library/stat stat S_IFMT5698503
Ref: 1d675698503
Ref: library/stat stat filemode5699958
Ref: b755699958
Ref: library/stat stat ST_MODE5700366
Ref: 9b95700366
Ref: library/stat stat ST_INO5700418
Ref: 1d685700418
Ref: library/stat stat ST_DEV5700457
Ref: 1d695700457
Ref: library/stat stat ST_NLINK5700511
Ref: 1d6a5700511
Ref: library/stat stat ST_UID5700573
Ref: 1d6b5700573
Ref: library/stat stat ST_GID5700627
Ref: 1d6c5700627
Ref: library/stat stat ST_SIZE5700683
Ref: 1d6d5700683
Ref: library/stat stat ST_ATIME5700810
Ref: 1d6e5700810
Ref: library/stat stat ST_MTIME5700866
Ref: 1d6f5700866
Ref: library/stat stat ST_CTIME5700922
Ref: 1d705700922
Ref: library/stat stat S_IFSOCK5701916
Ref: 1d715701916
Ref: library/stat stat S_IFLNK5701960
Ref: 1d725701960
Ref: library/stat stat S_IFREG5702006
Ref: 1d735702006
Ref: library/stat stat S_IFBLK5702052
Ref: 1d745702052
Ref: library/stat stat S_IFDIR5702095
Ref: 1d755702095
Ref: library/stat stat S_IFCHR5702135
Ref: 1d765702135
Ref: library/stat stat S_IFIFO5702181
Ref: 1d775702181
Ref: library/stat stat S_IFDOOR5702227
Ref: 9ba5702227
Ref: library/stat stat S_IFPORT5702289
Ref: 9bb5702289
Ref: library/stat stat S_IFWHT5702360
Ref: 9bc5702360
Ref: library/stat stat S_ISUID5702656
Ref: 1d785702656
Ref: library/stat stat S_ISGID5702704
Ref: 1d795702704
Ref: library/stat stat S_ISVTX5703207
Ref: 1d7c5703207
Ref: library/stat stat S_IRWXU5703398
Ref: 1d7d5703398
Ref: library/stat stat S_IRUSR5703462
Ref: 1d7e5703462
Ref: library/stat stat S_IWUSR5703523
Ref: 1d7f5703523
Ref: library/stat stat S_IXUSR5703584
Ref: 1d805703584
Ref: library/stat stat S_IRWXG5703645
Ref: 1d815703645
Ref: library/stat stat S_IRGRP5703697
Ref: 1d825703697
Ref: library/stat stat S_IWGRP5703752
Ref: 1d835703752
Ref: library/stat stat S_IXGRP5703807
Ref: 1d7a5703807
Ref: library/stat stat S_IRWXO5703862
Ref: 1d845703862
Ref: library/stat stat S_IROTH5703938
Ref: 1d855703938
Ref: library/stat stat S_IWOTH5703999
Ref: 1d865703999
Ref: library/stat stat S_IXOTH5704060
Ref: 1d875704060
Ref: library/stat stat S_ENFMT5704121
Ref: 1d7b5704121
Ref: library/stat stat S_IREAD5704344
Ref: 1d885704344
Ref: library/stat stat S_IWRITE5704423
Ref: 1d895704423
Ref: library/stat stat S_IEXEC5704503
Ref: 1d8a5704503
Ref: library/stat stat UF_NODUMP5704661
Ref: 1d8b5704661
Ref: library/stat stat UF_IMMUTABLE5704715
Ref: 1d8c5704715
Ref: library/stat stat UF_APPEND5704775
Ref: 1d8d5704775
Ref: library/stat stat UF_OPAQUE5704832
Ref: 1d8e5704832
Ref: library/stat stat UF_NOUNLINK5704922
Ref: 1d8f5704922
Ref: library/stat stat UF_COMPRESSED5704990
Ref: 1d905704990
Ref: library/stat stat UF_HIDDEN5705071
Ref: 1d915705071
Ref: library/stat stat SF_ARCHIVED5705160
Ref: 1d925705160
Ref: library/stat stat SF_IMMUTABLE5705219
Ref: 1d935705219
Ref: library/stat stat SF_APPEND5705279
Ref: 1d945705279
Ref: library/stat stat SF_NOUNLINK5705336
Ref: 1d955705336
Ref: library/stat stat SF_SNAPSHOT5705404
Ref: 1d965705404
Ref: library/stat stat FILE_ATTRIBUTE_ARCHIVE5705763
Ref: 1d975705763
Ref: library/stat stat FILE_ATTRIBUTE_COMPRESSED5705801
Ref: 1d985705801
Ref: library/stat stat FILE_ATTRIBUTE_DEVICE5705842
Ref: 1d995705842
Ref: library/stat stat FILE_ATTRIBUTE_DIRECTORY5705879
Ref: 1d9a5705879
Ref: library/stat stat FILE_ATTRIBUTE_ENCRYPTED5705919
Ref: 1d9b5705919
Ref: library/stat stat FILE_ATTRIBUTE_HIDDEN5705959
Ref: 1d9c5705959
Ref: library/stat stat FILE_ATTRIBUTE_INTEGRITY_STREAM5705996
Ref: 1d9d5705996
Ref: library/stat stat FILE_ATTRIBUTE_NORMAL5706043
Ref: 1d9e5706043
Ref: library/stat stat FILE_ATTRIBUTE_NOT_CONTENT_INDEXED5706080
Ref: 1d9f5706080
Ref: library/stat stat FILE_ATTRIBUTE_NO_SCRUB_DATA5706130
Ref: 1da05706130
Ref: library/stat stat FILE_ATTRIBUTE_OFFLINE5706174
Ref: 1da15706174
Ref: library/stat stat FILE_ATTRIBUTE_READONLY5706212
Ref: 1da25706212
Ref: library/stat stat FILE_ATTRIBUTE_REPARSE_POINT5706251
Ref: 1da35706251
Ref: library/stat stat FILE_ATTRIBUTE_SPARSE_FILE5706295
Ref: 1da45706295
Ref: library/stat stat FILE_ATTRIBUTE_SYSTEM5706337
Ref: 1da55706337
Ref: library/stat stat FILE_ATTRIBUTE_TEMPORARY5706374
Ref: 1da65706374
Ref: library/stat stat FILE_ATTRIBUTE_VIRTUAL5706414
Ref: 1da75706414
Ref: library/stat stat IO_REPARSE_TAG_SYMLINK5706661
Ref: 1da85706661
Ref: library/stat stat IO_REPARSE_TAG_MOUNT_POINT5706699
Ref: 1da95706699
Ref: library/stat stat IO_REPARSE_TAG_APPEXECLINK5706741
Ref: 1daa5706741
Ref: stat --- 解析 stat 结果-Footnote-15706844
Ref: stat --- 解析 stat 结果-Footnote-25706907
Node: filecmp --- 文件及目录的比较5706987
Ref: library/filecmp doc5707166
Ref: 1dab5707166
Ref: library/filecmp filecmp-file-and-directory-comparisons5707166
Ref: 1dac5707166
Ref: library/filecmp module-filecmp5707166
Ref: 7d5707166
Ref: library/filecmp filecmp cmp5707606
Ref: f855707606
Ref: library/filecmp filecmp cmpfiles5708355
Ref: 1dad5708355
Ref: library/filecmp filecmp clear_cache5709272
Ref: 9345709272
Ref: filecmp --- 文件及目录的比较-Footnote-15709580
Node: dircmp 类5709646
Ref: library/filecmp dircmp-objects5709729
Ref: 1dae5709729
Ref: library/filecmp the-dircmp-class5709729
Ref: 1daf5709729
Ref: library/filecmp filecmp dircmp5709777
Ref: 9365709777
Ref: library/filecmp filecmp dircmp report5710285
Ref: 1db05710285
Ref: library/filecmp filecmp dircmp report_partial_closure5710404
Ref: 1db15710404
Ref: library/filecmp filecmp dircmp report_full_closure5710527
Ref: 1db25710527
Ref: library/filecmp filecmp dircmp left5710965
Ref: 1db35710965
Ref: library/filecmp filecmp dircmp right5711014
Ref: 1db45711014
Ref: library/filecmp filecmp dircmp left_list5711064
Ref: 1db55711064
Ref: library/filecmp filecmp dircmp right_list5711175
Ref: 1db65711175
Ref: library/filecmp filecmp dircmp common5711287
Ref: 1db75711287
Ref: library/filecmp filecmp dircmp left_only5711385
Ref: 1db85711385
Ref: library/filecmp filecmp dircmp right_only5711469
Ref: 1db95711469
Ref: library/filecmp filecmp dircmp common_dirs5711554
Ref: 1dba5711554
Ref: library/filecmp filecmp dircmp common_files5711648
Ref: 1dbb5711648
Ref: library/filecmp filecmp dircmp common_funny5711740
Ref: 1dbc5711740
Ref: library/filecmp filecmp dircmp same_files5711901
Ref: 1dbd5711901
Ref: library/filecmp filecmp dircmp diff_files5712018
Ref: 1dbe5712018
Ref: library/filecmp filecmp dircmp funny_files5712161
Ref: 1dbf5712161
Ref: library/filecmp filecmp dircmp subdirs5712252
Ref: 1dc05712252
Ref: library/filecmp filecmp DEFAULT_IGNORES5712391
Ref: 9355712391
Node: tempfile --- 生成临时文件和目录5713034
Ref: library/tempfile doc5713227
Ref: 1dc15713227
Ref: library/tempfile module-tempfile5713227
Ref: 1035713227
Ref: library/tempfile tempfile-generate-temporary-files-and-directories5713227
Ref: 1dc25713227
Ref: library/tempfile tempfile TemporaryFile5714245
Ref: 1dc35714245
Ref: library/tempfile tempfile NamedTemporaryFile5716212
Ref: e0e5716212
Ref: library/tempfile tempfile SpooledTemporaryFile5717348
Ref: b7e5717348
Ref: library/tempfile tempfile TemporaryDirectory5718523
Ref: c965718523
Ref: library/tempfile tempfile mkstemp5719387
Ref: 1dc45719387
Ref: library/tempfile tempfile mkdtemp5722193
Ref: 1dc55722193
Ref: library/tempfile tempfile gettempdir5723178
Ref: 1dcb5723178
Ref: library/tempfile tempfile gettempdirb5724052
Ref: 1dcd5724052
Ref: library/tempfile tempfile gettempprefix5724189
Ref: 1dc95724189
Ref: library/tempfile tempfile gettempprefixb5724313
Ref: 1dca5724313
Ref: library/tempfile tempfile tempdir5724780
Ref: 1dcc5724780
Ref: tempfile --- 生成临时文件和目录-Footnote-15725250
Node: 示例<6>5725317
Ref: library/tempfile examples5725439
Ref: 1dce5725439
Ref: library/tempfile tempfile-examples5725439
Ref: 1dc75725439
Node: 已弃用的函数和变量5726341
Ref: library/tempfile deprecated-functions-and-variables5726463
Ref: 1dcf5726463
Ref: library/tempfile tempfile-mktemp-deprecated5726463
Ref: 1dd05726463
Ref: library/tempfile tempfile mktemp5727004
Ref: f7d5727004
Node: glob --- Unix 风格路径名模式扩展5728114
Ref: library/glob doc5728309
Ref: 1dd15728309
Ref: library/glob glob-unix-style-pathname-pattern-expansion5728309
Ref: 1dd25728309
Ref: library/glob module-glob5728309
Ref: 885728309
Ref: library/glob glob glob5729376
Ref: 6bd5729376
Ref: library/glob glob iglob5730560
Ref: 6be5730560
Ref: library/glob glob escape5730869
Ref: 93c5730869
Ref: glob --- Unix 风格路径名模式扩展-Footnote-15732274
Node: fnmatch --- Unix 文件名模式匹配5732337
Ref: library/fnmatch doc5732527
Ref: 1dd65732527
Ref: library/fnmatch fnmatch-unix-filename-pattern-matching5732527
Ref: 1dd75732527
Ref: library/fnmatch module-fnmatch5732527
Ref: 7f5732527
Ref: library/fnmatch fnmatch fnmatch5733834
Ref: 1dd35733834
Ref: library/fnmatch fnmatch fnmatchcase5734481
Ref: 1dd95734481
Ref: library/fnmatch fnmatch filter5734728
Ref: 1dd85734728
Ref: library/fnmatch fnmatch translate5734957
Ref: 11735734957
Ref: fnmatch --- Unix 文件名模式匹配-Footnote-15735524
Node: linecache --- 随机读写文本行5735590
Ref: library/linecache doc5735768
Ref: 1dda5735768
Ref: library/linecache linecache-random-access-to-text-lines5735768
Ref: 1ddb5735768
Ref: library/linecache module-linecache5735768
Ref: a85735768
Ref: library/linecache linecache getline5736502
Ref: 7fa5736502
Ref: library/linecache linecache clearcache5737252
Ref: 1dde5737252
Ref: library/linecache linecache checkcache5737419
Ref: 1ddf5737419
Ref: library/linecache linecache lazycache5737690
Ref: 7f95737690
Ref: linecache --- 随机读写文本行-Footnote-15738236
Ref: linecache --- 随机读写文本行-Footnote-25738304
Node: shutil --- 高阶文件操作5738353
Ref: library/shutil doc5738484
Ref: 1de05738484
Ref: library/shutil module-shutil5738484
Ref: e95738484
Ref: library/shutil shutil-high-level-file-operations5738484
Ref: 1de15738484
Ref: shutil --- 高阶文件操作-Footnote-15739482
Node: 目录和文件操作5739547
Ref: library/shutil directory-and-files-operations5739655
Ref: 1de25739655
Ref: library/shutil file-operations5739655
Ref: 1de35739655
Ref: library/shutil shutil copyfileobj5739713
Ref: 3875739713
Ref: library/shutil shutil copyfile5740224
Ref: 3825740224
Ref: library/shutil shutil SameFileError5741729
Ref: 99a5741729
Ref: library/shutil shutil copymode5741881
Ref: 1de45741881
Ref: library/shutil shutil copystat5742729
Ref: b525742729
Ref: library/shutil shutil copy5744691
Ref: 3835744691
Ref: library/shutil shutil copy25746062
Ref: 3845746062
Ref: library/shutil shutil ignore_patterns5747483
Ref: 1de65747483
Ref: library/shutil shutil copytree5747775
Ref: 3475747775
Ref: library/shutil shutil rmtree5750762
Ref: 3495750762
Ref: library/shutil shutil rmtree avoids_symlink_attacks5752550
Ref: 1de75752550
Ref: library/shutil shutil move5752837
Ref: 3855752837
Ref: library/shutil shutil disk_usage5754742
Ref: b505754742
Ref: library/shutil shutil chown5755208
Ref: b515755208
Ref: library/shutil shutil which5755686
Ref: fe65755686
Ref: library/shutil shutil Error5756981
Ref: 9995756981
Node: 依赖于具体平台的高效拷贝操作5757309
Ref: library/shutil platform-dependent-efficient-copy-operations5757433
Ref: 1de85757433
Ref: library/shutil shutil-platform-dependent-efficient-copy-operations5757433
Ref: 3885757433
Ref: 依赖于具体平台的高效拷贝操作-Footnote-15758540
Ref: 依赖于具体平台的高效拷贝操作-Footnote-25758583
Node: copytree 示例5758631
Ref: library/shutil copytree-example5758777
Ref: 1de95758777
Ref: library/shutil shutil-copytree-example5758777
Ref: 1dea5758777
Node: rmtree 示例5760816
Ref: library/shutil rmtree-example5760911
Ref: 1deb5760911
Ref: library/shutil shutil-rmtree-example5760911
Ref: 1dec5760911
Node: 归档操作5761453
Ref: library/shutil archiving-operations5761597
Ref: c675761597
Ref: library/shutil id15761597
Ref: 1ded5761597
Ref: library/shutil shutil make_archive5761871
Ref: 3485761871
Ref: library/shutil shutil get_archive_formats5763859
Ref: 1def5763859
Ref: library/shutil shutil register_archive_format5764712
Ref: 1df05764712
Ref: library/shutil shutil unregister_archive_format5765561
Ref: 1df15765561
Ref: library/shutil shutil unpack_archive5765670
Ref: c685765670
Ref: library/shutil shutil register_unpack_format5766609
Ref: 1df25766609
Ref: library/shutil shutil unregister_unpack_format5767340
Ref: 1df45767340
Ref: library/shutil shutil get_unpack_formats5767461
Ref: 1df35767461
Ref: 归档操作-Footnote-15768394
Node: 归档程序示例5768443
Ref: library/shutil archiving-example5768556
Ref: 1df55768556
Ref: library/shutil shutil-archiving-example5768556
Ref: 1df65768556
Node: 使用 base_dir 的归档程序示例5769657
Ref: library/shutil archiving-example-with-base-dir5769770
Ref: 1df75769770
Ref: library/shutil shutil-archiving-example-with-basedir5769770
Ref: 1dee5769770
Node: 查询输出终端的尺寸5770881
Ref: library/shutil querying-the-size-of-the-output-terminal5770995
Ref: 1df85770995
Ref: library/shutil shutil get_terminal_size5771063
Ref: b255771063
Ref: 查询输出终端的尺寸-Footnote-15772451
Node: 数据持久化5772533
Ref: library/persistence doc5772684
Ref: 1dfb5772684
Ref: library/persistence data-persistence5772684
Ref: 1dfc5772684
Ref: library/persistence other-environment-variables5772684
Ref: 1dfd5772684
Ref: library/persistence persistence5772684
Ref: 1dfe5772684
Node: pickle --- Python 对象序列化5773627
Ref: library/pickle doc5773774
Ref: 1dff5773774
Ref: library/pickle module-pickle5773774
Ref: ca5773774
Ref: library/pickle pickle-python-object-serialization5773774
Ref: 1e005773774
Ref: pickle --- Python 对象序列化-Footnote-15775409
Ref: pickle --- Python 对象序列化-Footnote-25775474
Node: 与其他 Python 模块间的关系5775537
Ref: library/pickle relationship-to-other-python-modules5775666
Ref: 1e035775666
Node: 与 marshal 间的关系5775816
Ref: library/pickle comparison-with-marshal5775945
Ref: 1e045775945
Node: 与 json 模块的比较5777816
Ref: library/pickle comparison-with-json5777945
Ref: 1e025777945
Ref: library/pickle id25777945
Ref: 1e055777945
Ref: 与 json 模块的比较-Footnote-15779058
Node: 数据流格式5779082
Ref: library/pickle data-stream-format5779232
Ref: 1e075779232
Ref: library/pickle pickle-protocols5779232
Ref: 6665779232
Ref: 数据流格式-Footnote-15781881
Ref: 数据流格式-Footnote-25781930
Ref: 数据流格式-Footnote-35781979
Node: 模块接口5782028
Ref: library/pickle module-interface5782174
Ref: 1e0a5782174
Ref: library/pickle pickle HIGHEST_PROTOCOL5782587
Ref: ec45782587
Ref: library/pickle pickle DEFAULT_PROTOCOL5782830
Ref: 1e0d5782830
Ref: library/pickle pickle dump5783265
Ref: 1e0c5783265
Ref: library/pickle pickle dumps5783741
Ref: ec35783741
Ref: library/pickle pickle load5784169
Ref: 6b95784169
Ref: library/pickle pickle loads5784843
Ref: 6ba5784843
Ref: library/pickle pickle PickleError5785533
Ref: 1e0e5785533
Ref: library/pickle pickle PicklingError5785651
Ref: 1e0f5785651
Ref: library/pickle pickle UnpicklingError5785911
Ref: 1e115785911
Ref: library/pickle pickle Pickler5786348
Ref: 33b5786348
Ref: library/pickle pickle Pickler dump5787987
Ref: 11725787987
Ref: library/pickle pickle Pickler persistent_id5788154
Ref: 1e145788154
Ref: library/pickle pickle Pickler dispatch_table5789001
Ref: b445789001
Ref: library/pickle pickle Pickler reducer_override5790045
Ref: 33c5790045
Ref: library/pickle pickle Pickler fast5790636
Ref: 1e1a5790636
Ref: library/pickle pickle Unpickler5791098
Ref: 1e0b5791098
Ref: library/pickle pickle Unpickler load5793132
Ref: 1e1c5793132
Ref: library/pickle pickle Unpickler persistent_load5793355
Ref: 1e155793355
Ref: library/pickle pickle Unpickler find_class5793775
Ref: 1e1d5793775
Ref: library/pickle pickle PickleBuffer5794468
Ref: 1e125794468
Ref: library/pickle pickle PickleBuffer raw5795082
Ref: 1e1f5795082
Ref: library/pickle pickle PickleBuffer release5795442
Ref: 1e205795442
Node: 可以被封存/解封的对象5795539
Ref: library/pickle pickle-picklable5795685
Ref: 1e105795685
Ref: library/pickle what-can-be-pickled-and-unpickled5795685
Ref: 1e215795685
Ref: 可以被封存/解封的对象-Footnote-15798186
Ref: 可以被封存/解封的对象-Footnote-25798327
Node: 封存类实例5798452
Ref: library/pickle pickle-inst5798634
Ref: 1e065798634
Ref: library/pickle pickling-class-instances5798634
Ref: 1e225798634
Ref: library/pickle object __getnewargs_ex__5799441
Ref: 1e235799441
Ref: library/pickle object __getnewargs__5800219
Ref: 7a15800219
Ref: library/pickle object __getstate__5800784
Ref: ec55800784
Ref: library/pickle object __setstate__5801166
Ref: 2d15801166
Ref: library/pickle object __reduce__5802983
Ref: 2d05802983
Ref: library/pickle object __reduce_ex__5805490
Ref: 1b475805490
Ref: 封存类实例-Footnote-15806111
Node: 持久化外部对象5806219
Ref: library/pickle persistence-of-external-objects5806313
Ref: 1e255806313
Ref: library/pickle pickle-persistent5806313
Ref: 1e165806313
Ref: 持久化外部对象-Footnote-15810894
Node: Dispatch 表5811116
Ref: library/pickle dispatch-tables5811243
Ref: 1e265811243
Ref: library/pickle pickle-dispatch5811243
Ref: 1e185811243
Node: 处理有状态的对象5812407
Ref: library/pickle handling-stateful-objects5812504
Ref: 1e275812504
Ref: library/pickle pickle-state5812504
Ref: 1e245812504
Node: 类型，函数和其他对象的自定义归约5814733
Ref: library/pickle custom-reduction-for-types-functions-and-other-objects5814899
Ref: 1e285814899
Ref: library/pickle reducer-override5814899
Ref: 1e195814899
Node: 外部缓冲区5816910
Ref: library/pickle out-of-band-buffers5817079
Ref: 1e295817079
Ref: library/pickle pickle-oob5817079
Ref: 1e135817079
Node: 提供方 API5817739
Ref: library/pickle provider-api5817826
Ref: 1e2a5817826
Node: 使用方 API5818381
Ref: library/pickle consumer-api5818486
Ref: 1e2b5818486
Node: 示例<7>5819681
Ref: library/pickle example5819764
Ref: 1e2c5819764
Ref: 示例<7>-Footnote-15822054
Node: 限制全局变量5822103
Ref: library/pickle pickle-restrict5822233
Ref: 1e1e5822233
Ref: library/pickle restricting-globals5822233
Ref: 1e2d5822233
Node: 性能<2>5825031
Ref: library/pickle performance5825155
Ref: 1e2e5825155
Node: 示例<8>5825405
Ref: library/pickle examples5825502
Ref: 1e2f5825502
Ref: library/pickle pickle-example5825502
Ref: 1e305825502
Node: copyreg --- 注册配合 pickle 模块使用的函数5826757
Ref: library/copyreg doc5826946
Ref: 1e315826946
Ref: library/copyreg copyreg-register-pickle-support-functions5826946
Ref: 1e325826946
Ref: library/copyreg module-copyreg5826946
Ref: 265826946
Ref: library/copyreg copyreg constructor5827492
Ref: 1e335827492
Ref: library/copyreg copyreg pickle5827710
Ref: 1e175827710
Ref: copyreg --- 注册配合 pickle 模块使用的函数-Footnote-15828586
Node: 示例<9>5828652
Ref: library/copyreg example5828751
Ref: 1e345828751
Node: shelve --- Python 对象持久化5829280
Ref: library/shelve doc5829477
Ref: 1e355829477
Ref: library/shelve module-shelve5829477
Ref: e75829477
Ref: library/shelve shelve-python-object-persistence5829477
Ref: 1e365829477
Ref: library/shelve shelve open5830016
Ref: 1e375830016
Ref: library/shelve shelve-security5831707
Ref: 1e3b5831707
Ref: library/shelve shelve Shelf sync5832176
Ref: 1e395832176
Ref: library/shelve shelve Shelf close5832474
Ref: 1e3a5832474
Ref: shelve --- Python 对象持久化-Footnote-15832829
Ref: shelve --- Python 对象持久化-Footnote-25832894
Node: 限制5832947
Ref: library/shelve restrictions5833042
Ref: 1e3c5833042
Ref: library/shelve shelve Shelf5833955
Ref: 9975833955
Ref: library/shelve shelve BsdDbShelf5835067
Ref: 1e3d5835067
Ref: library/shelve shelve DbfilenameShelf5835736
Ref: 1e3e5835736
Ref: 限制-Footnote-15836269
Node: 示例<10>5836322
Ref: library/shelve example5836417
Ref: 1e3f5836417
Ref: library/shelve shelve-example5836417
Ref: 1e385836417
Node: marshal --- 内部 Python 对象序列化5838082
Ref: library/marshal doc5838257
Ref: 1e405838257
Ref: library/marshal marshal-internal-python-object-serialization5838257
Ref: 1e415838257
Ref: library/marshal module-marshal5838257
Ref: b05838257
Ref: library/marshal marshal dump5840412
Ref: 1e425840412
Ref: library/marshal marshal load5841031
Ref: 112b5841031
Ref: library/marshal marshal dumps5841848
Ref: 88b5841848
Ref: library/marshal marshal loads5842338
Ref: 1e435842338
Ref: library/marshal marshal version5842923
Ref: 1e445842923
Ref: marshal --- 内部 Python 对象序列化-Footnote-15843255
Node: dbm --- Unix "数据库" 接口5843580
Ref: library/dbm doc5843774
Ref: 1e455843774
Ref: library/dbm dbm-interfaces-to-unix-databases5843774
Ref: 1e465843774
Ref: library/dbm module-dbm5843774
Ref: 315843774
Ref: library/dbm dbm error5844268
Ref: 1e475844268
Ref: library/dbm dbm whichdb5844520
Ref: 1e485844520
Ref: library/dbm dbm open5845044
Ref: 91d5845044
Ref: dbm --- Unix "数据库" 接口-Footnote-15848320
Ref: dbm --- Unix "数据库" 接口-Footnote-25848391
Node: dbm gnu --- GNU 对 dbm 的重解析5848444
Ref: library/dbm dbm-gnu-gnu-s-reinterpretation-of-dbm5848591
Ref: 1e495848591
Ref: library/dbm module-dbm gnu5848591
Ref: 335848591
Ref: library/dbm dbm gnu error5849317
Ref: 3e75849317
Ref: library/dbm dbm gnu open5849511
Ref: 11675849511
Ref: library/dbm dbm gnu gdbm firstkey5851293
Ref: 1e4a5851293
Ref: library/dbm dbm gnu gdbm nextkey5851583
Ref: 1e4b5851583
Ref: library/dbm dbm gnu gdbm reorganize5851952
Ref: 1e4c5851952
Ref: library/dbm dbm gnu gdbm sync5852365
Ref: 1e4d5852365
Ref: library/dbm dbm gnu gdbm close5852521
Ref: 1e4e5852521
Ref: dbm gnu --- GNU 对 dbm 的重解析-Footnote-15852637
Node: dbm ndbm --- 基于 ndbm 的接口5852703
Ref: library/dbm dbm-ndbm-interface-based-on-ndbm5852892
Ref: 1e4f5852892
Ref: library/dbm module-dbm ndbm5852892
Ref: 345852892
Ref: library/dbm dbm ndbm error5853563
Ref: 3e85853563
Ref: library/dbm dbm ndbm library5853759
Ref: 1e505853759
Ref: library/dbm dbm ndbm open5853839
Ref: 11685853839
Ref: library/dbm dbm ndbm ndbm close5854954
Ref: 1e515854954
Ref: dbm ndbm --- 基于 ndbm 的接口-Footnote-15855070
Node: dbm dumb --- 便携式 DBM 实现5855137
Ref: library/dbm dbm-dumb-portable-dbm-implementation5855281
Ref: 1e525855281
Ref: library/dbm module-dbm dumb5855281
Ref: 325855281
Ref: library/dbm dbm dumb error5856010
Ref: 3e65856010
Ref: library/dbm dbm dumb open5856200
Ref: 3e15856200
Ref: library/dbm dbm dumb dumbdbm sync5857934
Ref: 1e535857934
Ref: library/dbm dbm dumb dumbdbm close5858094
Ref: 1e545858094
Ref: dbm dumb --- 便携式 DBM 实现-Footnote-15858216
Node: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块5858283
Ref: library/sqlite3 doc5858427
Ref: 1e555858427
Ref: library/sqlite3 module-sqlite35858427
Ref: f25858427
Ref: library/sqlite3 sqlite3-db-api-2-0-interface-for-sqlite-databases5858427
Ref: 1e565858427
Ref: library/sqlite3 sqlite3-placeholders5860930
Ref: 1e5b5860930
Ref: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块-Footnote-15863366
Ref: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块-Footnote-25863430
Ref: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块-Footnote-35863479
Ref: sqlite3 --- SQLite 数据库 DB-API 2 0 接口模块-Footnote-45863509
Node: 模块函数和常量5863558
Ref: library/sqlite3 module-functions-and-constants5863705
Ref: 1e5c5863705
Ref: library/sqlite3 sqlite3-module-contents5863705
Ref: 1e5d5863705
Ref: library/sqlite3 sqlite3 apilevel5863761
Ref: 1e5e5863761
Ref: library/sqlite3 sqlite3 paramstyle5863904
Ref: 1e5f5863904
Ref: library/sqlite3 sqlite3 version5864408
Ref: 1e605864408
Ref: library/sqlite3 sqlite3 version_info5864522
Ref: 1e615864522
Ref: library/sqlite3 sqlite3 sqlite_version5864656
Ref: 1e625864656
Ref: library/sqlite3 sqlite3 sqlite_version_info5864756
Ref: 1e635864756
Ref: library/sqlite3 sqlite3 threadsafety5864873
Ref: 1e645864873
Ref: library/sqlite3 sqlite3 PARSE_DECLTYPES5865628
Ref: 1e655865628
Ref: library/sqlite3 sqlite3 PARSE_COLNAMES5866134
Ref: 1e665866134
Ref: library/sqlite3 sqlite3 connect5866920
Ref: 4e05866920
Ref: library/sqlite3 sqlite3 register_converter5870253
Ref: 1e695870253
Ref: library/sqlite3 sqlite3 register_adapter5870724
Ref: 1e6b5870724
Ref: library/sqlite3 sqlite3 complete_statement5871050
Ref: 1e6c5871050
Ref: library/sqlite3 sqlite3 enable_callback_tracebacks5872320
Ref: 1e6d5872320
Ref: 模块函数和常量-Footnote-15872770
Node: 连接对象（Connection）5872821
Ref: library/sqlite3 connection-objects5872990
Ref: 1e6e5872990
Ref: library/sqlite3 sqlite3-connection-objects5872990
Ref: 1e6f5872990
Ref: library/sqlite3 sqlite3 Connection5873061
Ref: 4de5873061
Ref: library/sqlite3 sqlite3 Connection isolation_level5873158
Ref: 1e685873158
Ref: library/sqlite3 sqlite3 Connection in_transaction5873429
Ref: 1e715873429
Ref: library/sqlite3 sqlite3 Connection cursor5873660
Ref: 1e725873660
Ref: library/sqlite3 sqlite3 Connection commit5873929
Ref: 1e735873929
Ref: library/sqlite3 sqlite3 Connection rollback5874290
Ref: 1e745874290
Ref: library/sqlite3 sqlite3 Connection close5874441
Ref: 1e755874441
Ref: library/sqlite3 sqlite3 Connection execute5874700
Ref: 1e765874700
Ref: library/sqlite3 sqlite3 Connection executemany5875024
Ref: 1e775875024
Ref: library/sqlite3 sqlite3 Connection executescript5875356
Ref: 1e795875356
Ref: library/sqlite3 sqlite3 Connection create_function5875685
Ref: 10d45875685
Ref: library/sqlite3 sqlite3 Connection create_aggregate5877033
Ref: 10d35877033
Ref: library/sqlite3 sqlite3 Connection create_collation5878370
Ref: 1e7c5878370
Ref: library/sqlite3 sqlite3 Connection interrupt5879982
Ref: 1e7d5879982
Ref: library/sqlite3 sqlite3 Connection set_authorizer5880267
Ref: 10d55880267
Ref: library/sqlite3 sqlite3 Connection set_progress_handler5881488
Ref: 10d65881488
Ref: library/sqlite3 sqlite3 Connection set_trace_callback5882060
Ref: b655882060
Ref: library/sqlite3 sqlite3 Connection enable_load_extension5883135
Ref: c6a5883135
Ref: library/sqlite3 sqlite3 Connection load_extension5884865
Ref: c6b5884865
Ref: library/sqlite3 sqlite3 Connection row_factory5885162
Ref: 1e7f5885162
Ref: library/sqlite3 sqlite3 Connection text_factory5886422
Ref: 1e805886422
Ref: library/sqlite3 sqlite3 Connection total_changes5888148
Ref: 1e815888148
Ref: library/sqlite3 sqlite3 Connection iterdump5888282
Ref: 1e825888282
Ref: library/sqlite3 sqlite3 Connection backup5888889
Ref: 4df5888889
Ref: 连接对象（Connection）-Footnote-15891098
Ref: 连接对象（Connection）-Footnote-25891144
Ref: 连接对象（Connection）-Footnote-35891440
Node: Cursor 对象5891736
Ref: library/sqlite3 cursor-objects5891893
Ref: 1e835891893
Ref: library/sqlite3 sqlite3-cursor-objects5891893
Ref: 1e845891893
Ref: library/sqlite3 sqlite3 Cursor5891938
Ref: 1e575891938
Ref: library/sqlite3 sqlite3 Cursor execute5892035
Ref: 1e585892035
Ref: library/sqlite3 sqlite3 Cursor executemany5892488
Ref: 1e785892488
Ref: library/sqlite3 sqlite3 Cursor executescript5894274
Ref: 1e7a5894274
Ref: library/sqlite3 sqlite3 Cursor fetchone5895487
Ref: 1e595895487
Ref: library/sqlite3 sqlite3 Cursor fetchmany5895677
Ref: 1e865895677
Ref: library/sqlite3 sqlite3 Cursor fetchall5896494
Ref: 1e5a5896494
Ref: library/sqlite3 sqlite3 Cursor close5896758
Ref: 1e875896758
Ref: library/sqlite3 sqlite3 Cursor setinputsizes5897044
Ref: 1e885897044
Ref: library/sqlite3 sqlite3 Cursor setoutputsize5897158
Ref: 1e895897158
Ref: library/sqlite3 sqlite3 Cursor rowcount5897281
Ref: 1e8a5897281
Ref: library/sqlite3 sqlite3 Cursor lastrowid5898165
Ref: 6755898165
Ref: library/sqlite3 sqlite3 Cursor arraysize5898841
Ref: 1e8b5898841
Ref: library/sqlite3 sqlite3 Cursor description5899041
Ref: 1e675899041
Ref: library/sqlite3 sqlite3 Cursor connection5899392
Ref: 1e8c5899392
Node: 行对象5899861
Ref: library/sqlite3 row-objects5899999
Ref: 1e8d5899999
Ref: library/sqlite3 sqlite3-row-objects5899999
Ref: 1e8e5899999
Ref: library/sqlite3 sqlite3 Row5900035
Ref: 84d5900035
Ref: library/sqlite3 sqlite3 Row keys5900533
Ref: 1e8f5900533
Node: 异常<4>5901780
Ref: library/sqlite3 exceptions5901929
Ref: 1e905901929
Ref: library/sqlite3 sqlite3-exceptions5901929
Ref: 1e915901929
Ref: library/sqlite3 sqlite3 Warning5901960
Ref: 1e855901960
Ref: library/sqlite3 sqlite3 Error5902036
Ref: 1e925902036
Ref: library/sqlite3 sqlite3 DatabaseError5902154
Ref: 1e935902154
Ref: library/sqlite3 sqlite3 IntegrityError5902241
Ref: 1e945902241
Ref: library/sqlite3 sqlite3 ProgrammingError5902431
Ref: ff35902431
Ref: library/sqlite3 sqlite3 OperationalError5902656
Ref: 1e7e5902656
Ref: library/sqlite3 sqlite3 NotSupportedError5902936
Ref: 1e7b5902936
Node: SQLite 与 Python 类型5903226
Ref: library/sqlite3 sqlite-and-python-types5903378
Ref: 1e955903378
Ref: library/sqlite3 sqlite3-types5903378
Ref: 1e6a5903378
Node: 簡介<7>5903634
Ref: library/sqlite3 introduction5903786
Ref: 1e965903786
Node: 使用适配器将额外的 Python 类型保存在 SQLite 数据库中。5905661
Ref: library/sqlite3 using-adapters-to-store-additional-python-types-in-sqlite-databases5905866
Ref: 1e975905866
Node: 让对象自行适配5906436
Ref: library/sqlite3 letting-your-object-adapt-itself5906603
Ref: 1e985906603
Node: 注册可调用的适配器5907639
Ref: library/sqlite3 registering-an-adapter-callable5907806
Ref: 1e995907806
Node: 将SQLite 值转换为自定义Python 类型5909093
Ref: library/sqlite3 converting-sqlite-values-to-custom-python-types5909316
Ref: 1e9a5909316
Node: 默认适配器和转换器5911900
Ref: library/sqlite3 default-adapters-and-converters5912041
Ref: 1e9b5912041
Node: 控制事务5913861
Ref: library/sqlite3 controlling-transactions5914024
Ref: 1e9c5914024
Ref: library/sqlite3 sqlite3-controlling-transactions5914024
Ref: 1e705914024
Node: 有效使用 sqlite35915679
Ref: library/sqlite3 using-sqlite3-efficiently5915809
Ref: 1e9d5915809
Node: 使用快捷方式5915994
Ref: library/sqlite3 using-shortcut-methods5916117
Ref: 1e9e5916117
Node: 通过名称而不是索引访问索引5917306
Ref: library/sqlite3 accessing-columns-by-name-instead-of-by-index5917474
Ref: 1e9f5917474
Node: 使用连接作为上下文管理器5918144
Ref: library/sqlite3 using-the-connection-as-a-context-manager5918285
Ref: 1ea05918285
Node: 資料壓縮與保存5919335
Ref: library/archiving doc5919477
Ref: 1e085919477
Ref: library/archiving archiving5919477
Ref: 1ea15919477
Ref: library/archiving data-compression-and-archiving5919477
Ref: 1ea25919477
Node: zlib --- 与 gzip 兼容的压缩5920141
Ref: library/zlib doc5920274
Ref: 1ea35920274
Ref: library/zlib module-zlib5920274
Ref: 14d5920274
Ref: library/zlib zlib-compression-compatible-with-gzip5920274
Ref: 1ea45920274
Ref: library/zlib zlib error5921085
Ref: 1ea55921085
Ref: library/zlib zlib adler325921173
Ref: 1ea65921173
Ref: library/zlib zlib compress5921862
Ref: 6b55921862
Ref: library/zlib zlib compressobj5922576
Ref: 1ea75922576
Ref: library/zlib zlib crc325924894
Ref: 1ea85924894
Ref: library/zlib zlib decompress5925498
Ref: 6b65925498
Ref: library/zlib decompress-wbits5925853
Ref: 1ea95925853
Ref: library/zlib zlib decompressobj5927396
Ref: 1eaa5927396
Ref: library/zlib zlib Compress compress5928242
Ref: 1eab5928242
Ref: library/zlib zlib Compress flush5928573
Ref: 1eac5928573
Ref: library/zlib zlib Compress copy5929219
Ref: 1ead5929219
Ref: library/zlib zlib Decompress unused_data5929527
Ref: 1eae5929527
Ref: library/zlib zlib Decompress unconsumed_tail5929847
Ref: 1eaf5929847
Ref: library/zlib zlib Decompress eof5930206
Ref: b9d5930206
Ref: library/zlib zlib Decompress decompress5930446
Ref: 1eb05930446
Ref: library/zlib zlib Decompress flush5931376
Ref: 1eb15931376
Ref: library/zlib zlib Decompress copy5931748
Ref: 1eb25931748
Ref: library/zlib zlib ZLIB_VERSION5932152
Ref: 1eb35932152
Ref: library/zlib zlib ZLIB_RUNTIME_VERSION5932393
Ref: b9e5932393
Ref: zlib --- 与 gzip 兼容的压缩-Footnote-15932807
Node: gzip --- 对 gzip 格式的支持5932852
Ref: library/gzip doc5933033
Ref: 1eb45933033
Ref: library/gzip gzip-support-for-gzip-files5933033
Ref: 1eb55933033
Ref: library/gzip module-gzip5933033
Ref: 8b5933033
Ref: library/gzip gzip open5933947
Ref: 1eb65933947
Ref: library/gzip gzip BadGzipFile5935485
Ref: 3035935485
Ref: library/gzip gzip GzipFile5935727
Ref: 2065935727
Ref: library/gzip gzip GzipFile peek5938315
Ref: c595938315
Ref: library/gzip gzip GzipFile mtime5938845
Ref: 1eb75938845
Ref: library/gzip gzip compress5940038
Ref: 3025940038
Ref: library/gzip gzip decompress5940389
Ref: c5a5940389
Ref: gzip --- 对 gzip 格式的支持-Footnote-15940622
Node: 用法示例5940685
Ref: library/gzip examples-of-usage5940791
Ref: 1ebc5940791
Ref: library/gzip gzip-usage-examples5940791
Ref: 1ebd5940791
Node: 命令行界面5941621
Ref: library/gzip command-line-interface5941727
Ref: 1ebe5941727
Node: 命令行选项5942103
Ref: library/gzip command-line-options5942170
Ref: 1ebf5942170
Ref: library/gzip cmdoption-gzip-arg-file5942216
Ref: 1ec05942216
Ref: library/gzip cmdoption-gzip-fast5942311
Ref: 1ec15942311
Ref: library/gzip cmdoption-gzip-best5942398
Ref: 1ec25942398
Ref: library/gzip cmdoption-gzip-d5942485
Ref: 1ec35942485
Ref: library/gzip cmdoption-gzip-h5942555
Ref: 1ec45942555
Node: bz2 --- 对 bzip2 压缩算法的支持5942613
Ref: library/bz2 doc5942791
Ref: 1ec55942791
Ref: library/bz2 bz2-support-for-bzip2-compression5942791
Ref: 1ec65942791
Ref: library/bz2 module-bz25942791
Ref: 135942791
Ref: bz2 --- 对 bzip2 压缩算法的支持-Footnote-15943656
Node: 文件压缩和解压5943718
Ref: library/bz2 de-compression-of-files5943845
Ref: 1ec95943845
Ref: library/bz2 bz2 open5943901
Ref: ab55943901
Ref: library/bz2 bz2 BZ2File5945330
Ref: 2245945330
Ref: library/bz2 bz2 BZ2File peek5946712
Ref: 1eca5946712
Node: 增量压缩和解压5948148
Ref: library/bz2 incremental-de-compression5948311
Ref: 1ecb5948311
Ref: library/bz2 bz2 BZ2Compressor5948367
Ref: 1ec75948367
Ref: library/bz2 bz2 BZ2Compressor compress5948700
Ref: 1ecc5948700
Ref: library/bz2 bz2 BZ2Compressor flush5949004
Ref: 1ecd5949004
Ref: library/bz2 bz2 BZ2Decompressor5949196
Ref: 1ec85949196
Ref: library/bz2 bz2 BZ2Decompressor decompress5949738
Ref: 7965949738
Ref: library/bz2 bz2 BZ2Decompressor eof5951038
Ref: 1ed05951038
Ref: library/bz2 bz2 BZ2Decompressor unused_data5951157
Ref: 1ecf5951157
Ref: library/bz2 bz2 BZ2Decompressor needs_input5951341
Ref: 1ece5951341
Node: 一次性压缩或解压缩5951557
Ref: library/bz2 one-shot-de-compression5951714
Ref: 1ed15951714
Ref: library/bz2 bz2 compress5951780
Ref: 19b65951780
Ref: library/bz2 bz2 decompress5952087
Ref: ab65952087
Node: 用法示例<2>5952411
Ref: library/bz2 bz2-usage-examples5952538
Ref: 1ed25952538
Ref: library/bz2 examples-of-usage5952538
Ref: 1ed35952538
Node: lzma --- 用 LZMA 算法压缩5955408
Ref: library/lzma doc5955580
Ref: 1ed45955580
Ref: library/lzma lzma-compression-using-the-lzma-algorithm5955580
Ref: 1ed55955580
Ref: library/lzma module-lzma5955580
Ref: ad5955580
Ref: library/lzma lzma LZMAError5956328
Ref: 1ed65956328
Ref: lzma --- 用 LZMA 算法压缩-Footnote-15956681
Node: 读写压缩文件5956744
Ref: library/lzma reading-and-writing-compressed-files5956874
Ref: 1ed75956874
Ref: library/lzma lzma open5956925
Ref: 1ed85956925
Ref: library/lzma lzma LZMAFile5958689
Ref: a165958689
Ref: library/lzma lzma LZMAFile peek5960519
Ref: 1edb5960519
Node: 在内存中压缩和解压缩数据5961309
Ref: library/lzma compressing-and-decompressing-data-in-memory5961457
Ref: 1edc5961457
Ref: library/lzma lzma LZMACompressor5961538
Ref: 1eda5961538
Ref: library/lzma lzma LZMACompressor compress5964313
Ref: 1edf5964313
Ref: library/lzma lzma LZMACompressor flush5964767
Ref: 1ee05964767
Ref: library/lzma lzma LZMADecompressor5965006
Ref: 1ed95965006
Ref: library/lzma lzma LZMADecompressor decompress5966383
Ref: 8055966383
Ref: library/lzma lzma LZMADecompressor check5967685
Ref: 1ee45967685
Ref: library/lzma lzma LZMADecompressor eof5967889
Ref: 1ee55967889
Ref: library/lzma lzma LZMADecompressor unused_data5967979
Ref: 1ee35967979
Ref: library/lzma lzma LZMADecompressor needs_input5968133
Ref: 1ee25968133
Ref: library/lzma lzma compress5968349
Ref: 1edd5968349
Ref: library/lzma lzma decompress5968694
Ref: 1ee15968694
Node: 杂项<2>5969168
Ref: library/lzma miscellaneous5969328
Ref: 1ee65969328
Ref: library/lzma lzma is_check_supported5969359
Ref: 1ee75969359
Node: 指定自定义的过滤器链5969697
Ref: library/lzma filter-chain-specs5969831
Ref: 1ede5969831
Ref: library/lzma specifying-custom-filter-chains5969831
Ref: 1ee85969831
Node: 示例<11>5972452
Ref: library/lzma examples5972568
Ref: 1ee95972568
Node: zipfile --- 使用ZIP存档5973912
Ref: library/zipfile doc5974078
Ref: 1eea5974078
Ref: library/zipfile module-zipfile5974078
Ref: 14b5974078
Ref: library/zipfile zipfile-work-with-zip-archives5974078
Ref: 1eeb5974078
Ref: library/zipfile zipfile BadZipFile5974852
Ref: 1eec5974852
Ref: library/zipfile zipfile BadZipfile5974956
Ref: 1eed5974956
Ref: library/zipfile zipfile LargeZipFile5975096
Ref: 1eee5975096
Ref: library/zipfile zipfile ZipInfo5975602
Ref: 6b15975602
Ref: library/zipfile zipfile is_zipfile5976191
Ref: d825976191
Ref: library/zipfile zipfile ZIP_STORED5976493
Ref: 1ef45976493
Ref: library/zipfile zipfile ZIP_DEFLATED5976575
Ref: 1ef55976575
Ref: library/zipfile zipfile ZIP_BZIP25976691
Ref: 1ef65976691
Ref: library/zipfile zipfile ZIP_LZMA5976818
Ref: 1ef75976818
Ref: zipfile --- 使用ZIP存档-Footnote-15977702
Ref: zipfile --- 使用ZIP存档-Footnote-25977768
Ref: zipfile --- 使用ZIP存档-Footnote-35977836
Ref: zipfile --- 使用ZIP存档-Footnote-45977904
Node: ZipFile 对象5977937
Ref: library/zipfile id15978035
Ref: 1ef85978035
Ref: library/zipfile zipfile-objects5978035
Ref: 1eef5978035
Ref: library/zipfile zipfile ZipFile5978082
Ref: 5225978082
Ref: library/zipfile zipfile ZipFile close5981837
Ref: 1ef95981837
Ref: library/zipfile zipfile ZipFile getinfo5982008
Ref: 1ef15982008
Ref: library/zipfile zipfile ZipFile infolist5982278
Ref: 1ef25982278
Ref: library/zipfile zipfile ZipFile namelist5982558
Ref: 1efa5982558
Ref: library/zipfile zipfile ZipFile open5982649
Ref: 6b35982649
Ref: library/zipfile zipfile ZipFile extract5985005
Ref: 1efe5985005
Ref: library/zipfile zipfile ZipFile extractall5986374
Ref: 1eff5986374
Ref: library/zipfile zipfile ZipFile printdir5987341
Ref: 1f005987341
Ref: library/zipfile zipfile ZipFile setpassword5987437
Ref: 1f015987437
Ref: library/zipfile zipfile ZipFile read5987550
Ref: d815987550
Ref: library/zipfile zipfile ZipFile testzip5988460
Ref: 1f025988460
Ref: library/zipfile zipfile ZipFile write5988849
Ref: 7055988849
Ref: library/zipfile zipfile ZipFile writestr5990134
Ref: d835990134
Ref: library/zipfile zipfile ZipFile filename5991755
Ref: 1f035991755
Ref: library/zipfile zipfile ZipFile debug5991814
Ref: 1f045991814
Ref: library/zipfile zipfile ZipFile comment5992014
Ref: 1f055992014
Node: Path 对象5992314
Ref: library/zipfile id25992437
Ref: 1f065992437
Ref: library/zipfile path-objects5992437
Ref: 1ef05992437
Ref: library/zipfile zipfile Path5992478
Ref: 10675992478
Ref: library/zipfile zipfile Path name5992979
Ref: 1f075992979
Ref: library/zipfile zipfile Path open5993039
Ref: 1f085993039
Ref: library/zipfile zipfile Path iterdir5993623
Ref: 1f095993623
Ref: library/zipfile zipfile Path is_dir5993698
Ref: 1f0a5993698
Ref: library/zipfile zipfile Path is_file5993804
Ref: 1f0b5993804
Ref: library/zipfile zipfile Path exists5993911
Ref: 1f0c5993911
Ref: library/zipfile zipfile Path read_text5994043
Ref: 1f0d5994043
Ref: library/zipfile zipfile Path read_bytes5994257
Ref: 1f0e5994257
Node: PyZipFile 对象5994335
Ref: library/zipfile id35994458
Ref: 1f0f5994458
Ref: library/zipfile pyzipfile-objects5994458
Ref: 1f105994458
Ref: library/zipfile zipfile PyZipFile5994641
Ref: a005994641
Ref: library/zipfile zipfile PyZipFile writepy5994940
Ref: 9ff5994940
Node: ZipInfo 对象5997657
Ref: library/zipfile id45997787
Ref: 1f115997787
Ref: library/zipfile zipinfo-objects5997787
Ref: 1ef35997787
Ref: library/zipfile zipfile ZipInfo from_file5998122
Ref: 6b05998122
Ref: library/zipfile zipfile ZipInfo is_dir5999110
Ref: 6b25999110
Ref: library/zipfile zipfile ZipInfo filename5999313
Ref: 1f125999313
Ref: library/zipfile zipfile ZipInfo date_time5999377
Ref: 1f135999377
Ref: library/zipfile zipfile ZipInfo compress_type6000128
Ref: 1f146000128
Ref: library/zipfile zipfile ZipInfo comment6000200
Ref: 1f156000200
Ref: library/zipfile zipfile ZipInfo extra6000299
Ref: 1f166000299
Ref: library/zipfile zipfile ZipInfo create_system6000465
Ref: 1f176000465
Ref: library/zipfile zipfile ZipInfo create_version6000542
Ref: 1f186000542
Ref: library/zipfile zipfile ZipInfo extract_version6000627
Ref: 1f196000627
Ref: library/zipfile zipfile ZipInfo reserved6000714
Ref: 1f1a6000714
Ref: library/zipfile zipfile ZipInfo flag_bits6000766
Ref: 1f1b6000766
Ref: library/zipfile zipfile ZipInfo volume6000820
Ref: 1f1c6000820
Ref: library/zipfile zipfile ZipInfo internal_attr6000879
Ref: 1f1d6000879
Ref: library/zipfile zipfile ZipInfo external_attr6000936
Ref: 1f1e6000936
Ref: library/zipfile zipfile ZipInfo header_offset6000999
Ref: 1f1f6000999
Ref: library/zipfile zipfile ZipInfo CRC6001071
Ref: 1f206001071
Ref: library/zipfile zipfile ZipInfo compress_size6001131
Ref: 1f216001131
Ref: library/zipfile zipfile ZipInfo file_size6001200
Ref: 1efd6001200
Ref: ZipInfo 对象-Footnote-16001301
Node: 命令行界面<2>6001369
Ref: library/zipfile command-line-interface6001501
Ref: 1f226001501
Ref: library/zipfile zipfile-commandline6001501
Ref: 1f236001501
Node: 命令行选项<2>6002250
Ref: library/zipfile command-line-options6002323
Ref: 1f276002323
Ref: library/zipfile cmdoption-zipfile-l6002369
Ref: 1f266002369
Ref: library/zipfile cmdoption-zipfile-list6002400
Ref: 1f286002400
Ref: library/zipfile cmdoption-zipfile-c6002482
Ref: 1f246002482
Ref: library/zipfile cmdoption-zipfile-create6002537
Ref: 1f296002537
Ref: library/zipfile cmdoption-zipfile-e6002638
Ref: 1f256002638
Ref: library/zipfile cmdoption-zipfile-extract6002682
Ref: 1f2a6002682
Ref: library/zipfile cmdoption-zipfile-t6002780
Ref: 1f2b6002780
Ref: library/zipfile cmdoption-zipfile-test6002811
Ref: 1f2c6002811
Node: 解压缩的障碍6002884
Ref: library/zipfile decompression-pitfalls6002993
Ref: 1f2d6002993
Node: 由于文件本身6003233
Ref: library/zipfile from-file-itself6003333
Ref: 1f2e6003333
Node: 文件系统限制6003506
Ref: library/zipfile file-system-limitations6003627
Ref: 1f2f6003627
Node: 资源限制6003883
Ref: library/zipfile resources-limitations6003992
Ref: 1f306003992
Ref: library/zipfile zipfile-resources-limitations6003992
Ref: 1f316003992
Ref: 资源限制-Footnote-16004235
Node: 中断6004282
Ref: library/zipfile interruption6004394
Ref: 1f326004394
Node: 提取的默认行为6004558
Ref: library/zipfile default-behaviors-of-extraction6004649
Ref: 1f336004649
Node: tarfile --- 读写tar归档文件6004867
Ref: library/tarfile doc6004994
Ref: 1f346004994
Ref: library/tarfile module-tarfile6004994
Ref: 1016004994
Ref: library/tarfile pkzip-application-note6004994
Ref: 1f356004994
Ref: library/tarfile tarfile-read-and-write-tar-archive-files6004994
Ref: 1f366004994
Ref: library/tarfile tarfile open6006097
Ref: 8556006097
Ref: library/tarfile tarfile is_tarfile6012247
Ref: 10a06012247
Ref: library/tarfile tarfile TarError6012574
Ref: 1f3a6012574
Ref: library/tarfile tarfile ReadError6012656
Ref: f716012656
Ref: library/tarfile tarfile CompressionError6012821
Ref: 1f386012821
Ref: library/tarfile tarfile StreamError6012953
Ref: 1f3b6012953
Ref: library/tarfile tarfile ExtractError6013068
Ref: 1f3c6013068
Ref: library/tarfile tarfile HeaderError6013248
Ref: 1f3d6013248
Ref: library/tarfile tarfile ENCODING6013422
Ref: 1f3f6013422
Ref: library/tarfile tarfile USTAR_FORMAT6013773
Ref: 1f416013773
Ref: library/tarfile tarfile GNU_FORMAT6013842
Ref: 1f426013842
Ref: library/tarfile tarfile PAX_FORMAT6013896
Ref: 1f436013896
Ref: library/tarfile tarfile DEFAULT_FORMAT6013961
Ref: 1f446013961
Ref: tarfile --- 读写tar归档文件-Footnote-16014704
Ref: tarfile --- 读写tar归档文件-Footnote-26014770
Node: TarFile 对象6014842
Ref: library/tarfile id16014949
Ref: 1f456014949
Ref: library/tarfile tarfile-objects6014949
Ref: 1f376014949
Ref: library/tarfile tarfile TarFile6015761
Ref: c5d6015761
Ref: library/tarfile tarfile TarFile open6019043
Ref: 1f486019043
Ref: library/tarfile tarfile TarFile getmember6019212
Ref: 1f496019212
Ref: library/tarfile tarfile TarFile getmembers6019536
Ref: 8596019536
Ref: library/tarfile tarfile TarFile getnames6019711
Ref: 1f4a6019711
Ref: library/tarfile tarfile TarFile list6019877
Ref: 8586019877
Ref: library/tarfile tarfile TarFile next6020324
Ref: 1f4b6020324
Ref: library/tarfile tarfile TarFile extractall6020557
Ref: 8566020557
Ref: library/tarfile tarfile TarFile extract6021814
Ref: 8576021814
Ref: library/tarfile tarfile TarFile extractfile6022996
Ref: 1f4c6022996
Ref: library/tarfile tarfile TarFile add6023520
Ref: 57a6023520
Ref: library/tarfile tarfile TarFile addfile6024398
Ref: 1f4d6024398
Ref: library/tarfile tarfile TarFile gettarinfo6024781
Ref: 1f4e6024781
Ref: library/tarfile tarfile TarFile close6025912
Ref: 1f526025912
Ref: library/tarfile tarfile TarFile pax_headers6026066
Ref: 1f536026066
Node: TarInfo 对象6026159
Ref: library/tarfile id26026293
Ref: 1f546026293
Ref: library/tarfile tarinfo-objects6026293
Ref: 1f466026293
Ref: library/tarfile tarfile TarInfo6026772
Ref: c5e6026772
Ref: library/tarfile tarfile TarInfo frombuf6026860
Ref: 1f3e6026860
Ref: library/tarfile tarfile TarInfo fromtarfile6027088
Ref: 1f556027088
Ref: library/tarfile tarfile TarInfo tobuf6027274
Ref: 1f566027274
Ref: library/tarfile tarfile TarInfo name6027678
Ref: 1f516027678
Ref: library/tarfile tarfile TarInfo size6027735
Ref: 1f506027735
Ref: library/tarfile tarfile TarInfo mtime6027795
Ref: 1f576027795
Ref: library/tarfile tarfile TarInfo mode6027853
Ref: 1f586027853
Ref: library/tarfile tarfile TarInfo type6027898
Ref: 1f596027898
Ref: library/tarfile tarfile TarInfo linkname6028266
Ref: 1f5a6028266
Ref: library/tarfile tarfile TarInfo uid6028434
Ref: 1f5b6028434
Ref: library/tarfile tarfile TarInfo gid6028511
Ref: 1f5c6028511
Ref: library/tarfile tarfile TarInfo uname6028588
Ref: 1f5d6028588
Ref: library/tarfile tarfile TarInfo gname6028634
Ref: 1f5e6028634
Ref: library/tarfile tarfile TarInfo pax_headers6028680
Ref: 1f5f6028680
Ref: library/tarfile tarfile TarInfo isfile6028850
Ref: 1f606028850
Ref: library/tarfile tarfile TarInfo isreg6028965
Ref: 1f616028965
Ref: library/tarfile tarfile TarInfo isdir6029043
Ref: 1f626029043
Ref: library/tarfile tarfile TarInfo issym6029130
Ref: 1f636029130
Ref: library/tarfile tarfile TarInfo islnk6029223
Ref: 1f646029223
Ref: library/tarfile tarfile TarInfo ischr6029313
Ref: 1f656029313
Ref: library/tarfile tarfile TarInfo isblk6029406
Ref: 1f666029406
Ref: library/tarfile tarfile TarInfo isfifo6029496
Ref: 1f676029496
Ref: library/tarfile tarfile TarInfo isdev6029585
Ref: 1f686029585
Node: 命令行界面<3>6029705
Ref: library/tarfile command-line-interface6029835
Ref: 1f696029835
Ref: library/tarfile tarfile-commandline6029835
Ref: 9ce6029835
Node: 命令行选项<3>6030729
Ref: library/tarfile command-line-options6030802
Ref: 1f6d6030802
Ref: library/tarfile cmdoption-tarfile-l6030848
Ref: 1f6c6030848
Ref: library/tarfile cmdoption-tarfile-list6030879
Ref: 1f6e6030879
Ref: library/tarfile cmdoption-tarfile-c6030961
Ref: 1f6a6030961
Ref: library/tarfile cmdoption-tarfile-create6031016
Ref: 1f6f6031016
Ref: library/tarfile cmdoption-tarfile-e6031117
Ref: 1f6b6031117
Ref: library/tarfile cmdoption-tarfile-extract6031163
Ref: 1f706031163
Ref: library/tarfile cmdoption-tarfile-t6031295
Ref: 1f716031295
Ref: library/tarfile cmdoption-tarfile-test6031326
Ref: 1f726031326
Ref: library/tarfile cmdoption-tarfile-v6031399
Ref: 1f736031399
Node: 示例<12>6031466
Ref: library/tarfile examples6031605
Ref: 1f746031605
Ref: library/tarfile tar-examples6031605
Ref: 1f396031605
Node: 受支持的 tar 格式6033424
Ref: library/tarfile supported-tar-formats6033559
Ref: 1f756033559
Ref: library/tarfile tar-formats6033559
Ref: 1f406033559
Node: Unicode 问题6035581
Ref: library/tarfile tar-unicode6035697
Ref: 1f476035697
Ref: library/tarfile unicode-issues6035697
Ref: 1f766035697
Node: 檔案格式6037480
Ref: library/fileformats doc6037619
Ref: 1f786037619
Ref: library/fileformats file-formats6037619
Ref: 1f796037619
Ref: library/fileformats fileformats6037619
Ref: 1f7a6037619
Node: csv --- CSV 文件读写6038125
Ref: library/csv doc6038245
Ref: 1f7b6038245
Ref: library/csv csv-csv-file-reading-and-writing6038245
Ref: 1f7c6038245
Ref: library/csv module-csv6038245
Ref: 296038245
Ref: csv --- CSV 文件读写-Footnote-16039903
Ref: csv --- CSV 文件读写-Footnote-26039965
Node: 模块内容<3>6040014
Ref: library/csv csv-contents6040120
Ref: 1f7d6040120
Ref: library/csv module-contents6040120
Ref: 1f7e6040120
Ref: library/csv csv reader6040208
Ref: 101a6040208
Ref: library/csv csv writer6041733
Ref: ec06041733
Ref: library/csv csv register_dialect6043386
Ref: 1f816043386
Ref: library/csv csv unregister_dialect6043844
Ref: 1f826043844
Ref: library/csv csv get_dialect6044038
Ref: 1f846044038
Ref: library/csv csv list_dialects6044271
Ref: 1f7f6044271
Ref: library/csv csv field_size_limit6044351
Ref: 1f856044351
Ref: library/csv csv DictReader6044579
Ref: 2ee6044579
Ref: library/csv csv DictWriter6046092
Ref: c4b6046092
Ref: library/csv csv Dialect6047699
Ref: f6c6047699
Ref: library/csv csv excel6048534
Ref: 1f866048534
Ref: library/csv csv excel_tab6048699
Ref: 1f876048699
Ref: library/csv csv unix_dialect6048897
Ref: c4a6048897
Ref: library/csv csv Sniffer6049190
Ref: 1f886049190
Ref: library/csv csv Sniffer sniff6049336
Ref: 1f896049336
Ref: library/csv csv Sniffer has_header6049675
Ref: 1f8a6049675
Ref: library/csv csv QUOTE_ALL6050191
Ref: 1f8b6050191
Ref: library/csv csv QUOTE_MINIMAL6050285
Ref: 1f8c6050285
Ref: library/csv csv QUOTE_NONNUMERIC6050486
Ref: 1f8d6050486
Ref: library/csv csv QUOTE_NONE6050680
Ref: 1f8e6050680
Ref: library/csv csv Error6051106
Ref: 1f836051106
Ref: 模块内容<3>-Footnote-16051226
Ref: 模块内容<3>-Footnote-26051553
Node: 变种与格式参数6051880
Ref: library/csv csv-fmt-params6052008
Ref: 1f806052008
Ref: library/csv dialects-and-formatting-parameters6052008
Ref: 1f8f6052008
Ref: library/csv csv Dialect delimiter6052676
Ref: 1f906052676
Ref: library/csv csv Dialect doublequote6052775
Ref: 1f916052775
Ref: library/csv csv Dialect escapechar6053260
Ref: 1f926053260
Ref: library/csv csv Dialect lineterminator6053657
Ref: 1f936053657
Ref: library/csv csv Dialect quotechar6053959
Ref: 1f946053959
Ref: library/csv csv Dialect quoting6054147
Ref: 1f956054147
Ref: library/csv csv Dialect skipinitialspace6054399
Ref: 1f966054399
Ref: library/csv csv Dialect strict6054551
Ref: 1f976054551
Node: Reader 对象6054706
Ref: library/csv reader-objects6054832
Ref: 1f986054832
Ref: library/csv csv csvreader __next__6055002
Ref: 1f996055002
Ref: library/csv csv csvreader dialect6055402
Ref: 1f9a6055402
Ref: library/csv csv csvreader line_num6055485
Ref: 1f9b6055485
Ref: library/csv csv csvreader fieldnames6055681
Ref: 1f9c6055681
Node: Writer 对象6055872
Ref: library/csv writer-objects6055987
Ref: 1f9d6055987
Ref: library/csv csv csvwriter writerow6056585
Ref: 7b76056585
Ref: library/csv csv csvwriter writerows6056874
Ref: 1f9e6056874
Ref: library/csv csv csvwriter dialect6057140
Ref: 1f9f6057140
Ref: library/csv csv DictWriter writeheader6057268
Ref: c4c6057268
Node: 示例<13>6057743
Ref: library/csv csv-examples6057836
Ref: 1fa06057836
Ref: library/csv examples6057836
Ref: 1fa16057836
Node: configparser --- 配置文件解析器6059751
Ref: library/configparser doc6059908
Ref: 1fa26059908
Ref: library/configparser configparser-configuration-file-parser6059908
Ref: 1fa36059908
Ref: library/configparser module-configparser6059908
Ref: 226059908
Ref: configparser --- 配置文件解析器-Footnote-16061042
Node: 快速起步6061113
Ref: library/configparser quick-start6061230
Ref: 1fa46061230
Ref: 快速起步-Footnote-16063909
Ref: 快速起步-Footnote-26064081
Node: 支持的数据类型6064253
Ref: library/configparser supported-datatypes6064388
Ref: 1fa86064388
Ref: 支持的数据类型-Footnote-16065704
Ref: 支持的数据类型-Footnote-26065876
Node: 回退值6066048
Ref: library/configparser fallback-values6066200
Ref: 1fac6066200
Node: 受支持的 INI 文件结构6067609
Ref: library/configparser supported-ini-file-structure6067752
Ref: 1fa56067752
Ref: 受支持的 INI 文件结构-Footnote-16070038
Ref: 受支持的 INI 文件结构-Footnote-26070210
Ref: 受支持的 INI 文件结构-Footnote-36070382
Ref: 受支持的 INI 文件结构-Footnote-46070554
Ref: 受支持的 INI 文件结构-Footnote-56070726
Node: 值的插值6070898
Ref: library/configparser interpolation-of-values6071050
Ref: 1fad6071050
Ref: library/configparser configparser BasicInterpolation6071237
Ref: 1fae6071237
Ref: library/configparser configparser ExtendedInterpolation6072423
Ref: caa6072423
Ref: 值的插值-Footnote-16073799
Node: 映射协议访问6073971
Ref: library/configparser mapping-protocol-access6074115
Ref: 1fa66074115
Ref: 映射协议访问-Footnote-16076746
Node: 定制解析器行为6076918
Ref: library/configparser customizing-parser-behaviour6077067
Ref: 1fa76077067
Ref: library/configparser configparser ConfigParser BOOLEAN_STATES6087050
Ref: 1fb06087050
Ref: library/configparser configparser ConfigParser SECTCRE6089178
Ref: 1fb16089178
Node: 旧式 API 示例6090360
Ref: library/configparser legacy-api-examples6090510
Ref: 1fb26090510
Node: ConfigParser 对象6094259
Ref: library/configparser configparser-objects6094410
Ref: 1fb36094410
Ref: library/configparser id126094410
Ref: 1fb46094410
Ref: library/configparser configparser ConfigParser6094467
Ref: 5a46094467
Ref: library/configparser configparser ConfigParser defaults6097995
Ref: 1fb76097995
Ref: library/configparser configparser ConfigParser sections6098091
Ref: 1fb86098091
Ref: library/configparser configparser ConfigParser add_section6098211
Ref: ccf6098211
Ref: library/configparser configparser ConfigParser has_section6098681
Ref: 1fb96098681
Ref: library/configparser configparser ConfigParser options6098845
Ref: 1fba6098845
Ref: library/configparser configparser ConfigParser has_option6098949
Ref: 1fbb6098949
Ref: library/configparser configparser ConfigParser read6099248
Ref: 11d96099248
Ref: library/configparser configparser ConfigParser read_file6100938
Ref: 1fbc6100938
Ref: library/configparser configparser ConfigParser read_string6101413
Ref: 1fbe6101413
Ref: library/configparser configparser ConfigParser read_dict6101767
Ref: 1fb66101767
Ref: library/configparser configparser ConfigParser get6102399
Ref: ccd6102399
Ref: library/configparser configparser ConfigParser getint6103292
Ref: 1faa6103292
Ref: library/configparser configparser ConfigParser getfloat6103585
Ref: 1fab6103585
Ref: library/configparser configparser ConfigParser getboolean6103882
Ref: 1fa96103882
Ref: library/configparser configparser ConfigParser items6104589
Ref: 1fbf6104589
Ref: library/configparser configparser ConfigParser set6105217
Ref: cce6105217
Ref: library/configparser configparser ConfigParser write6105526
Ref: 1faf6105526
Ref: library/configparser configparser ConfigParser remove_option6106156
Ref: 1fc16106156
Ref: library/configparser configparser ConfigParser remove_section6106482
Ref: 1fc26106482
Ref: library/configparser configparser ConfigParser optionxform6106690
Ref: 1fb56106690
Ref: library/configparser configparser ConfigParser readfp6107586
Ref: 1fbd6107586
Ref: library/configparser configparser MAX_INTERPOLATION_DEPTH6108332
Ref: 1fc36108332
Node: RawConfigParser 对象6108536
Ref: library/configparser id146108679
Ref: 1fc46108679
Ref: library/configparser rawconfigparser-objects6108679
Ref: 1fc56108679
Ref: library/configparser configparser RawConfigParser6108744
Ref: 95c6108744
Ref: library/configparser configparser RawConfigParser add_section6109629
Ref: 1fc66109629
Ref: library/configparser configparser RawConfigParser set6110072
Ref: 1fc76110072
Node: 异常<5>6110834
Ref: library/configparser exceptions6110949
Ref: 1fc86110949
Ref: library/configparser configparser Error6110982
Ref: 1fc96110982
Ref: library/configparser configparser NoSectionError6111076
Ref: 1fc06111076
Ref: library/configparser configparser DuplicateSectionError6111166
Ref: cd06111166
Ref: library/configparser configparser DuplicateOptionError6111524
Ref: cd16111524
Ref: library/configparser configparser NoOptionError6111840
Ref: 1fca6111840
Ref: library/configparser configparser InterpolationError6111956
Ref: 1fcb6111956
Ref: library/configparser configparser InterpolationDepthError6112077
Ref: 1fcc6112077
Ref: library/configparser configparser InterpolationMissingOptionError6112305
Ref: 1fcd6112305
Ref: library/configparser configparser InterpolationSyntaxError6112487
Ref: 1fce6112487
Ref: library/configparser configparser MissingSectionHeaderError6112677
Ref: 1fcf6112677
Ref: library/configparser configparser ParsingError6112802
Ref: 1fd06112802
Node: netrc --- netrc 文件处理6113055
Ref: library/netrc doc6113225
Ref: 1fd16113225
Ref: library/netrc module-netrc6113225
Ref: be6113225
Ref: library/netrc netrc-netrc-file-processing6113225
Ref: 1fd26113225
Ref: library/netrc netrc netrc6113524
Ref: 11d56113524
Ref: library/netrc netrc NetrcParseError6114671
Ref: 1fd36114671
Ref: netrc --- netrc 文件处理-Footnote-16115045
Node: netrc 对象6115109
Ref: library/netrc id16115186
Ref: 1fd46115186
Ref: library/netrc netrc-objects6115186
Ref: 1fd56115186
Ref: library/netrc netrc netrc authenticators6115275
Ref: 1fd66115275
Ref: library/netrc netrc netrc __repr__6115618
Ref: 1fd76115618
Ref: library/netrc netrc netrc hosts6115848
Ref: 1fd86115848
Ref: library/netrc netrc netrc macros6116040
Ref: 1fd96116040
Node: xdrlib --- 编码与解码 XDR 数据6116396
Ref: library/xdrlib doc6116575
Ref: 1fda6116575
Ref: library/xdrlib module-xdrlib6116575
Ref: 13b6116575
Ref: library/xdrlib xdrlib-encode-and-decode-xdr-data6116575
Ref: 1fdb6116575
Ref: library/xdrlib xdrlib Packer6117152
Ref: 1fdc6117152
Ref: library/xdrlib xdrlib Unpacker6117318
Ref: 1fdd6117318
Ref: xdrlib --- 编码与解码 XDR 数据-Footnote-16117898
Ref: xdrlib --- 编码与解码 XDR 数据-Footnote-26117963
Ref: xdrlib --- 编码与解码 XDR 数据-Footnote-36118012
Ref: xdrlib --- 编码与解码 XDR 数据-Footnote-46118061
Ref: xdrlib --- 编码与解码 XDR 数据-Footnote-56118110
Node: Packer 对象6118159
Ref: library/xdrlib packer-objects6118270
Ref: 1fde6118270
Ref: library/xdrlib xdr-packer-objects6118270
Ref: 1fdf6118270
Ref: library/xdrlib xdrlib Packer get_buffer6118362
Ref: 1fe06118362
Ref: library/xdrlib xdrlib Packer reset6118463
Ref: 1fe16118463
Ref: library/xdrlib xdrlib Packer pack_float6118902
Ref: 1fe26118902
Ref: library/xdrlib xdrlib Packer pack_double6118989
Ref: 1fe36118989
Ref: library/xdrlib xdrlib Packer pack_fstring6119148
Ref: 1fe46119148
Ref: library/xdrlib xdrlib Packer pack_fopaque6119389
Ref: 1fe56119389
Ref: library/xdrlib xdrlib Packer pack_string6119524
Ref: 1fe66119524
Ref: library/xdrlib xdrlib Packer pack_opaque6119726
Ref: 1fe76119726
Ref: library/xdrlib xdrlib Packer pack_bytes6119856
Ref: 1fe86119856
Ref: library/xdrlib xdrlib Packer pack_list6120019
Ref: 1fe96120019
Ref: library/xdrlib xdrlib Packer pack_farray6120647
Ref: 1fea6120647
Ref: library/xdrlib xdrlib Packer pack_array6121010
Ref: 1feb6121010
Node: Unpacker 对象6121249
Ref: library/xdrlib unpacker-objects6121378
Ref: 1fec6121378
Ref: library/xdrlib xdr-unpacker-objects6121378
Ref: 1fed6121378
Ref: library/xdrlib xdrlib Unpacker reset6121473
Ref: 1fee6121473
Ref: library/xdrlib xdrlib Unpacker get_position6121571
Ref: 1fef6121571
Ref: library/xdrlib xdrlib Unpacker set_position6121670
Ref: 1ff06121670
Ref: library/xdrlib xdrlib Unpacker get_buffer6121872
Ref: 1ff16121872
Ref: library/xdrlib xdrlib Unpacker done6121981
Ref: 1ff26121981
Ref: library/xdrlib xdrlib Unpacker unpack_float6122362
Ref: 1ff46122362
Ref: library/xdrlib xdrlib Unpacker unpack_double6122440
Ref: 1ff56122440
Ref: library/xdrlib xdrlib Unpacker unpack_fstring6122640
Ref: 1ff66122640
Ref: library/xdrlib xdrlib Unpacker unpack_fopaque6122829
Ref: 1ff76122829
Ref: library/xdrlib xdrlib Unpacker unpack_string6122964
Ref: 1ff86122964
Ref: library/xdrlib xdrlib Unpacker unpack_opaque6123176
Ref: 1ff96123176
Ref: library/xdrlib xdrlib Unpacker unpack_bytes6123322
Ref: 1ffa6123322
Ref: library/xdrlib xdrlib Unpacker unpack_list6123495
Ref: 1ffb6123495
Ref: library/xdrlib xdrlib Unpacker unpack_farray6123845
Ref: 1ffc6123845
Ref: library/xdrlib xdrlib Unpacker unpack_array6124129
Ref: 1ffd6124129
Node: 异常<6>6124385
Ref: library/xdrlib exceptions6124492
Ref: 1ffe6124492
Ref: library/xdrlib xdr-exceptions6124492
Ref: 1fff6124492
Ref: library/xdrlib xdrlib Error6124574
Ref: 1ff36124574
Ref: library/xdrlib xdrlib ConversionError6124721
Ref: 20006124721
Node: plistlib --- 生成与解析 Apple plist 文件6125087
Ref: library/plistlib doc6125229
Ref: 20016125229
Ref: library/plistlib module-plistlib6125229
Ref: cf6125229
Ref: library/plistlib plistlib-generate-and-parse-apple-plist-files6125229
Ref: 20026125229
Ref: library/plistlib plistlib load6126658
Ref: 21e6126658
Ref: library/plistlib plistlib loads6127512
Ref: 21f6127512
Ref: library/plistlib plistlib dump6127716
Ref: 2206127716
Ref: library/plistlib plistlib dumps6128682
Ref: 2216128682
Ref: library/plistlib plistlib UID6128981
Ref: 33e6128981
Ref: library/plistlib plistlib FMT_XML6129389
Ref: 9766129389
Ref: library/plistlib plistlib FMT_BINARY6129484
Ref: 9776129484
Ref: plistlib --- 生成与解析 Apple plist 文件-Footnote-16129654
Ref: plistlib --- 生成与解析 Apple plist 文件-Footnote-26129721
Node: 示例<14>6129820
Ref: library/plistlib examples6129914
Ref: 20036129914
Node: 加密服务6130653
Ref: library/crypto doc6130795
Ref: 20046130795
Ref: library/crypto crypto6130795
Ref: 20056130795
Ref: library/crypto cryptographic-services6130795
Ref: 20066130795
Node: hashlib --- 安全哈希与消息摘要6131292
Ref: library/hashlib doc6131425
Ref: 20076131425
Ref: library/hashlib hashlib-secure-hashes-and-message-digests6131425
Ref: 20086131425
Ref: library/hashlib module-hashlib6131425
Ref: 8c6131425
Ref: hashlib --- 安全哈希与消息摘要-Footnote-16132328
Ref: hashlib --- 安全哈希与消息摘要-Footnote-26132394
Node: 哈希算法6132443
Ref: library/hashlib hash-algorithms6132564
Ref: 20096132564
Ref: library/hashlib id16132564
Ref: 200a6132564
Ref: library/hashlib hashlib-usedforsecurity6134176
Ref: 200b6134176
Ref: library/hashlib hashlib new6135161
Ref: 10306135161
Ref: library/hashlib hashlib algorithms_guaranteed6135831
Ref: dc26135831
Ref: library/hashlib hashlib algorithms_available6136159
Ref: dc36136159
Ref: library/hashlib hashlib hash digest_size6136653
Ref: 200c6136653
Ref: library/hashlib hashlib hash block_size6136736
Ref: 200d6136736
Ref: library/hashlib hashlib hash name6136855
Ref: 93e6136855
Ref: library/hashlib hashlib hash update6137249
Ref: 200e6137249
Ref: library/hashlib hashlib hash digest6137673
Ref: 200f6137673
Ref: library/hashlib hashlib hash hexdigest6137919
Ref: 20106137919
Ref: library/hashlib hashlib hash copy6138194
Ref: 20116138194
Node: SHAKE 可变长度摘要6138363
Ref: library/hashlib shake-variable-length-digests6138505
Ref: 20126138505
Ref: library/hashlib hashlib shake digest6138777
Ref: 115d6138777
Ref: library/hashlib hashlib shake hexdigest6138999
Ref: 115e6138999
Node: 密钥派生6139281
Ref: library/hashlib key-derivation6139417
Ref: 20136139417
Ref: library/hashlib hashlib pbkdf2_hmac6139687
Ref: 8d36139687
Ref: library/hashlib hashlib scrypt6141037
Ref: 5cc6141037
Ref: 密钥派生-Footnote-16141768
Ref: 密钥派生-Footnote-26141830
Node: BLAKE26141879
Ref: library/hashlib blake26141982
Ref: 20146141982
Ref: BLAKE2-Footnote-16142694
Ref: BLAKE2-Footnote-26142721
Ref: BLAKE2-Footnote-36142770
Node: 创建哈希对象6142848
Ref: library/hashlib creating-hash-objects6142927
Ref: 20156142927
Ref: library/hashlib hashlib blake2b6143035
Ref: 6466143035
Ref: library/hashlib hashlib blake2s6143269
Ref: 6476143269
Ref: 创建哈希对象-Footnote-16146292
Node: 常数<4>6146339
Ref: library/hashlib constants6146437
Ref: 20166146437
Ref: library/hashlib hashlib blake2b SALT_SIZE6146468
Ref: 20176146468
Ref: library/hashlib hashlib blake2s SALT_SIZE6146497
Ref: 20186146497
Ref: library/hashlib hashlib blake2b PERSON_SIZE6146582
Ref: 20196146582
Ref: library/hashlib hashlib blake2s PERSON_SIZE6146613
Ref: 201a6146613
Ref: library/hashlib hashlib blake2b MAX_KEY_SIZE6146712
Ref: 201b6146712
Ref: library/hashlib hashlib blake2s MAX_KEY_SIZE6146744
Ref: 201c6146744
Ref: library/hashlib hashlib blake2b MAX_DIGEST_SIZE6146799
Ref: 201d6146799
Ref: library/hashlib hashlib blake2s MAX_DIGEST_SIZE6146834
Ref: 201e6146834
Node: 示例<15>6146916
Ref: library/hashlib examples6147008
Ref: 201f6147008
Node: 简单哈希6147163
Ref: library/hashlib simple-hashing6147258
Ref: 20206147258
Node: 使用不同的摘要大小6148686
Ref: library/hashlib using-different-digest-sizes6148802
Ref: 20216148802
Node: 密钥哈希6149920
Ref: library/hashlib keyed-hashing6150036
Ref: 20226150036
Ref: 密钥哈希-Footnote-16152045
Node: 随机哈希6152088
Ref: library/hashlib randomized-hashing6152186
Ref: 20236152186
Ref: 随机哈希-Footnote-16154419
Ref: 随机哈希-Footnote-26154486
Node: 个性化6154517
Ref: library/hashlib personalization6154615
Ref: 20246154615
Ref: 个性化-Footnote-16156532
Node: 树形模式6156600
Ref: library/hashlib tree-mode6156677
Ref: 20256156677
Node: 开发人员6157925
Ref: library/hashlib credits6157999
Ref: 20266157999
Ref: 开发人员-Footnote-16160084
Ref: 开发人员-Footnote-26160111
Ref: 开发人员-Footnote-36160180
Ref: 开发人员-Footnote-46160214
Ref: 开发人员-Footnote-56160251
Ref: 开发人员-Footnote-66160294
Node: hmac --- 基于密钥的消息验证6160337
Ref: library/hmac doc6160530
Ref: 20276160530
Ref: library/hmac hmac-keyed-hashing-for-message-authentication6160530
Ref: 20286160530
Ref: library/hmac module-hmac6160530
Ref: 8e6160530
Ref: library/hmac hmac new6160784
Ref: 9406160784
Ref: library/hmac hmac digest6161701
Ref: 4966161701
Ref: library/hmac hmac HMAC update6162287
Ref: 9416162287
Ref: library/hmac hmac HMAC digest6162599
Ref: 20296162599
Ref: library/hmac hmac HMAC hexdigest6163146
Ref: 202a6163146
Ref: library/hmac hmac HMAC copy6163680
Ref: 202b6163680
Ref: library/hmac hmac HMAC digest_size6163880
Ref: 9446163880
Ref: library/hmac hmac HMAC block_size6163965
Ref: 9426163965
Ref: library/hmac hmac HMAC name6164076
Ref: 9436164076
Ref: library/hmac hmac compare_digest6164417
Ref: aea6164417
Ref: hmac --- 基于密钥的消息验证-Footnote-16165325
Ref: hmac --- 基于密钥的消息验证-Footnote-26165388
Node: secrets --- 產生用於管理機密的安全亂數6165437
Ref: library/secrets doc6165582
Ref: 202c6165582
Ref: library/secrets module-secrets6165582
Ref: e46165582
Ref: library/secrets secrets-generate-secure-random-numbers-for-managing-secrets6165582
Ref: 202d6165582
Ref: secrets --- 產生用於管理機密的安全亂數-Footnote-16166444
Ref: secrets --- 產生用於管理機密的安全亂數-Footnote-26166510
Node: 亂數6166559
Ref: library/secrets random-numbers6166685
Ref: 202e6166685
Ref: library/secrets secrets SystemRandom6166840
Ref: 202f6166840
Ref: library/secrets secrets choice6167041
Ref: 20306167041
Ref: library/secrets secrets randbelow6167147
Ref: 20316167147
Ref: library/secrets secrets randbits6167241
Ref: 20326167241
Node: 產生權杖（token）6167329
Ref: library/secrets generating-tokens6167476
Ref: 20336167476
Ref: library/secrets secrets token_bytes6167689
Ref: 1c646167689
Ref: library/secrets secrets token_hex6167997
Ref: 20346167997
Ref: library/secrets secrets token_urlsafe6168369
Ref: 20356168369
Node: 權杖應當使用多少個位元組？6168829
Ref: library/secrets how-many-bytes-should-tokens-use6168928
Ref: 20366168928
Ref: 權杖應當使用多少個位元組？-Footnote-16169928
Node: 其他函式6169985
Ref: library/secrets other-functions6170173
Ref: 20376170173
Ref: library/secrets secrets compare_digest6170214
Ref: 20386170214
Ref: 其他函式-Footnote-16170520
Node: 應用技巧和典範實務（best practices）6170577
Ref: library/secrets recipes-and-best-practices6170733
Ref: 20396170733
Ref: 應用技巧和典範實務（best practices）-Footnote-16172473
Ref: 應用技巧和典範實務（best practices）-Footnote-26172528
Node: 通用操作系统服务6172558
Ref: library/allos doc6172700
Ref: 203a6172700
Ref: library/allos allos6172700
Ref: 203b6172700
Ref: library/allos generic-operating-system-services6172700
Ref: 203c6172700
Node: os --- 多种操作系统接口6174393
Ref: library/os doc6174525
Ref: 203d6174525
Ref: library/os module-os6174525
Ref: c46174525
Ref: library/os os-miscellaneous-operating-system-interfaces6174525
Ref: 203e6174525
Ref: library/os os error6176181
Ref: 203f6176181
Ref: library/os os name6176264
Ref: 20406176264
Ref: library/os os-filenames6176645
Ref: 1f776176645
Ref: os --- 多种操作系统接口-Footnote-16176907
Node: 文件名，命令行参数，以及环境变量。6176968
Ref: library/os file-names-command-line-arguments-and-environment-variables6177108
Ref: 20416177108
Ref: library/os filesystem-encoding6177108
Ref: 20426177108
Node: 进程参数6178022
Ref: library/os os-procinfo6178189
Ref: 20436178189
Ref: library/os process-parameters6178189
Ref: 20446178189
Ref: library/os os ctermid6178304
Ref: 20456178304
Ref: library/os os environ6178424
Ref: c096178424
Ref: library/os os environb6179998
Ref: c656179998
Ref: library/os os fsencode6180752
Ref: 5e96180752
Ref: library/os os fsdecode6181185
Ref: 5e86181185
Ref: library/os os fspath6181659
Ref: 5e76181659
Ref: library/os os PathLike6182092
Ref: 5e56182092
Ref: library/os os PathLike __fspath__6182302
Ref: 5e66182302
Ref: library/os os getenv6182568
Ref: 20476182568
Ref: library/os os getenvb6183056
Ref: c646183056
Ref: library/os os get_exec_path6183434
Ref: 20486183434
Ref: library/os os getegid6183771
Ref: 20496183771
Ref: library/os os geteuid6183927
Ref: 204a6183927
Ref: library/os os getgid6184037
Ref: 204b6184037
Ref: library/os os getgrouplist6184143
Ref: b366184143
Ref: library/os os getgroups6184485
Ref: 204c6184485
Ref: library/os os getlogin6185550
Ref: 204e6185550
Ref: library/os os getpgid6185951
Ref: 20506185951
Ref: library/os os getpgrp6186148
Ref: 20516186148
Ref: library/os os getpid6186246
Ref: 20526186246
Ref: library/os os getppid6186299
Ref: 20536186299
Ref: library/os os getpriority6186635
Ref: b216186635
Ref: library/os os PRIO_PROCESS6187208
Ref: 20546187208
Ref: library/os os PRIO_PGRP6187234
Ref: 20556187234
Ref: library/os os PRIO_USER6187257
Ref: 20566187257
Ref: library/os os getresuid6187431
Ref: d736187431
Ref: library/os os getresgid6187672
Ref: d726187672
Ref: library/os os getuid6187901
Ref: 20576187901
Ref: library/os os initgroups6188010
Ref: d766188010
Ref: library/os os putenv6188245
Ref: 1cd6188245
Ref: library/os os setegid6189054
Ref: 20596189054
Ref: library/os os seteuid6189165
Ref: 205a6189165
Ref: library/os os setgid6189279
Ref: 205b6189279
Ref: library/os os setgroups6189382
Ref: 204d6189382
Ref: library/os os setpgrp6189935
Ref: 205c6189935
Ref: library/os os setpgid6190149
Ref: 205d6190149
Ref: library/os os setpriority6190361
Ref: b226190361
Ref: library/os os setregid6191046
Ref: 205e6191046
Ref: library/os os setresgid6191173
Ref: d746191173
Ref: library/os os setresuid6191340
Ref: d756191340
Ref: library/os os setreuid6191510
Ref: 205f6191510
Ref: library/os os getsid6191640
Ref: 20606191640
Ref: library/os os setsid6191789
Ref: 10e06191789
Ref: library/os os setuid6191935
Ref: 20616191935
Ref: library/os os strerror6192041
Ref: 20626192041
Ref: library/os os supports_bytes_environ6192258
Ref: c636192258
Ref: library/os os umask6192441
Ref: 20636192441
Ref: library/os os uname6192528
Ref: b386192528
Ref: library/os os unsetenv6193525
Ref: 1cc6193525
Ref: 进程参数-Footnote-16194217
Ref: 进程参数-Footnote-26194266
Node: 创建文件对象6194315
Ref: library/os file-object-creation6194452
Ref: 20656194452
Ref: library/os os-newstreams6194452
Ref: 20666194452
Ref: library/os os fdopen6194639
Ref: 15646194639
Node: 文件描述符操作6194904
Ref: library/os file-descriptor-operations6195044
Ref: 20676195044
Ref: library/os os-fd-ops6195044
Ref: 20686195044
Ref: library/os os close6195784
Ref: 4d86195784
Ref: library/os os closerange6196209
Ref: 206b6196209
Ref: library/os os copy_file_range6196536
Ref: 206c6196536
Ref: library/os os device_encoding6197498
Ref: f676197498
Ref: library/os os dup6197657
Ref: 10e96197657
Ref: library/os os dup26198019
Ref: 4c46198019
Ref: library/os os fchmod6198448
Ref: 74f6198448
Ref: library/os os fchown6198841
Ref: 7506198841
Ref: library/os os fdatasync6199313
Ref: 7516199313
Ref: library/os os fpathconf6199527
Ref: 206e6199527
Ref: library/os os fstat6200476
Ref: 7526200476
Ref: library/os os fstatvfs6200731
Ref: 7536200731
Ref: library/os os fsync6201020
Ref: 7546201020
Ref: library/os os ftruncate6201499
Ref: 7556201499
Ref: library/os os get_blocking6201902
Ref: 8106201902
Ref: library/os os isatty6202265
Ref: f666202265
Ref: library/os os lockf6202437
Ref: b356202437
Ref: library/os os F_LOCK6202978
Ref: 20706202978
Ref: library/os os F_TLOCK6202998
Ref: 20716202998
Ref: library/os os F_ULOCK6203019
Ref: 20726203019
Ref: library/os os F_TEST6203040
Ref: 20736203040
Ref: library/os os lseek6203199
Ref: b396203199
Ref: library/os os SEEK_SET6203665
Ref: e596203665
Ref: library/os os SEEK_CUR6203687
Ref: e5a6203687
Ref: library/os os SEEK_END6203709
Ref: e5b6203709
Ref: library/os os open6203936
Ref: 7586203936
Ref: library/os os O_RDONLY6205851
Ref: 20746205851
Ref: library/os os O_WRONLY6205873
Ref: 20756205873
Ref: library/os os O_RDWR6205895
Ref: 20776205895
Ref: library/os os O_APPEND6205915
Ref: 20786205915
Ref: library/os os O_CREAT6205937
Ref: 20796205937
Ref: library/os os O_EXCL6205958
Ref: 1dc86205958
Ref: library/os os O_TRUNC6205978
Ref: 207a6205978
Ref: library/os os O_DSYNC6206055
Ref: 207b6206055
Ref: library/os os O_RSYNC6206076
Ref: 207c6206076
Ref: library/os os O_SYNC6206097
Ref: 207d6206097
Ref: library/os os O_NDELAY6206117
Ref: 207e6206117
Ref: library/os os O_NONBLOCK6206139
Ref: 8126206139
Ref: library/os os O_NOCTTY6206163
Ref: 207f6206163
Ref: library/os os O_CLOEXEC6206185
Ref: aa26206185
Ref: library/os os O_BINARY6206318
Ref: 20766206318
Ref: library/os os O_NOINHERIT6206340
Ref: 20806206340
Ref: library/os os O_SHORT_LIVED6206365
Ref: 20816206365
Ref: library/os os O_TEMPORARY6206392
Ref: 20826206392
Ref: library/os os O_RANDOM6206417
Ref: 20836206417
Ref: library/os os O_SEQUENTIAL6206439
Ref: 20846206439
Ref: library/os os O_TEXT6206465
Ref: 20856206465
Ref: library/os os O_ASYNC6206538
Ref: 20866206538
Ref: library/os os O_DIRECT6206559
Ref: 20876206559
Ref: library/os os O_DIRECTORY6206581
Ref: 20886206581
Ref: library/os os O_NOFOLLOW6206606
Ref: 20896206606
Ref: library/os os O_NOATIME6206630
Ref: 208a6206630
Ref: library/os os O_PATH6206653
Ref: 96e6206653
Ref: library/os os O_TMPFILE6206673
Ref: 96f6206673
Ref: library/os os O_SHLOCK6206696
Ref: e5c6206696
Ref: library/os os O_EXLOCK6206718
Ref: e5d6206718
Ref: library/os os openpty6206979
Ref: 208b6206979
Ref: library/os os pipe6207368
Ref: 206a6207368
Ref: library/os os pipe26207663
Ref: b0a6207663
Ref: library/os os posix_fallocate6208028
Ref: 75a6208028
Ref: library/os os posix_fadvise6208280
Ref: 7596208280
Ref: library/os os POSIX_FADV_NORMAL6208832
Ref: 208c6208832
Ref: library/os os POSIX_FADV_SEQUENTIAL6208863
Ref: 208d6208863
Ref: library/os os POSIX_FADV_RANDOM6208898
Ref: 208e6208898
Ref: library/os os POSIX_FADV_NOREUSE6208929
Ref: 208f6208929
Ref: library/os os POSIX_FADV_WILLNEED6208961
Ref: 20906208961
Ref: library/os os POSIX_FADV_DONTNEED6208994
Ref: 20916208994
Ref: library/os os pread6209208
Ref: 4bf6209208
Ref: library/os os preadv6209589
Ref: 4bd6209589
Ref: library/os os RWF_NOWAIT6210695
Ref: 20936210695
Ref: library/os os RWF_HIPRI6211166
Ref: 20926211166
Ref: library/os os pwrite6211544
Ref: 4c26211544
Ref: library/os os pwritev6211826
Ref: 4c06211826
Ref: library/os os RWF_DSYNC6212892
Ref: 20966212892
Ref: library/os os RWF_SYNC6213145
Ref: 20976213145
Ref: library/os os read6213396
Ref: 75b6213396
Ref: library/os os sendfile6214247
Ref: 4616214247
Ref: library/os os set_blocking6215684
Ref: 8116215684
Ref: library/os os SF_NODISKIO6216065
Ref: 20986216065
Ref: library/os os SF_MNOWAIT6216090
Ref: 20996216090
Ref: library/os os SF_SYNC6216114
Ref: 209a6216114
Ref: library/os os readv6216288
Ref: 4be6216288
Ref: library/os os tcgetpgrp6216880
Ref: 209b6216880
Ref: library/os os tcsetpgrp6217091
Ref: 209c6217091
Ref: library/os os ttyname6217314
Ref: 209d6217314
Ref: library/os os write6217531
Ref: 7616217531
Ref: library/os os writev6218308
Ref: 4c16218308
Ref: 文件描述符操作-Footnote-16218973
Ref: 文件描述符操作-Footnote-26219022
Ref: 文件描述符操作-Footnote-36219085
Ref: 文件描述符操作-Footnote-46219134
Node: 查询终端的尺寸6219183
Ref: library/os querying-the-size-of-a-terminal6219295
Ref: 209e6219295
Ref: library/os terminal-size6219295
Ref: 209f6219295
Ref: library/os os get_terminal_size6219370
Ref: b246219370
Ref: library/os os terminal_size6219951
Ref: 1dfa6219951
Ref: library/os os terminal_size columns6220056
Ref: 20a06220056
Ref: library/os os terminal_size lines6220136
Ref: 20a16220136
Node: 文件描述符的继承6220214
Ref: library/os fd-inheritance6220326
Ref: 8e76220326
Ref: library/os inheritance-of-file-descriptors6220326
Ref: 20a26220326
Ref: library/os os get_inheritable6221259
Ref: 8e86221259
Ref: library/os os set_inheritable6221378
Ref: 8e96221378
Ref: library/os os get_handle_inheritable6221492
Ref: 8ea6221492
Ref: library/os os set_handle_inheritable6221654
Ref: 8eb6221654
Node: 文件和目录6221811
Ref: library/os files-and-directories6221945
Ref: 20a46221945
Ref: library/os os-file-dir6221945
Ref: 20466221945
Ref: library/os path-fd6222066
Ref: 4bb6222066
Ref: library/os dir-fd6222891
Ref: b0b6222891
Ref: library/os follow-symlinks6223576
Ref: b0c6223576
Ref: library/os os access6224112
Ref: b0d6224112
Ref: library/os os F_OK6226552
Ref: 20a56226552
Ref: library/os os R_OK6226570
Ref: 20a66226570
Ref: library/os os W_OK6226588
Ref: 20a76226588
Ref: library/os os X_OK6226606
Ref: 20a86226606
Ref: library/os os chdir6226772
Ref: 16e6226772
Ref: library/os os chflags6227440
Ref: b0e6227440
Ref: library/os os chmod6228491
Ref: b0f6228491
Ref: library/os os chown6230198
Ref: b106230198
Ref: library/os os chroot6231070
Ref: 107f6231070
Ref: library/os os fchdir6231256
Ref: 74e6231256
Ref: library/os os getcwd6231595
Ref: 11196231595
Ref: library/os os getcwdb6231673
Ref: 3da6231673
Ref: library/os os lchflags6231971
Ref: 20aa6231971
Ref: library/os os lchmod6232460
Ref: 11606232460
Ref: library/os os lchown6233022
Ref: 20ab6233022
Ref: library/os os link6233521
Ref: b116233521
Ref: library/os os listdir6234301
Ref: b1c6234301
Ref: library/os os lstat6235666
Ref: 3226235666
Ref: library/os os mkdir6236706
Ref: b126236706
Ref: library/os mkdir-modebits6236930
Ref: 20ac6236930
Ref: library/os os makedirs6237731
Ref: 4c36237731
Ref: library/os os mkfifo6239236
Ref: 7566239236
Ref: library/os os mknod6240109
Ref: 7576240109
Ref: library/os os major6240970
Ref: 20af6240970
Ref: library/os os minor6241132
Ref: 20b06241132
Ref: library/os os makedev6241294
Ref: 20ae6241294
Ref: library/os os pathconf6241397
Ref: b1d6241397
Ref: library/os os pathconf_names6242406
Ref: 20b16242406
Ref: library/os os readlink6242709
Ref: 1d16242709
Ref: library/os os remove6244062
Ref: b136244062
Ref: library/os os removedirs6244940
Ref: 20b26244940
Ref: library/os os rename6245757
Ref: b146245757
Ref: library/os os renames6247264
Ref: 20b36247264
Ref: library/os os replace6247908
Ref: b156247908
Ref: library/os os rmdir6248787
Ref: b166248787
Ref: library/os os scandir6249363
Ref: 3896249363
Ref: library/os os scandir close6251043
Ref: 6606251043
Ref: library/os os DirEntry6252448
Ref: 5ea6252448
Ref: library/os os DirEntry name6253555
Ref: 20b66253555
Ref: library/os os DirEntry path6253948
Ref: 20b76253948
Ref: library/os os DirEntry inode6254677
Ref: 20b86254677
Ref: library/os os DirEntry is_dir6255073
Ref: 20b46255073
Ref: library/os os DirEntry is_file6256501
Ref: 7486256501
Ref: library/os os DirEntry is_symlink6257222
Ref: 20b96257222
Ref: library/os os DirEntry stat6258056
Ref: 20b56258056
Ref: library/os os stat6259481
Ref: 3216259481
Ref: library/os os stat_result6261829
Ref: 11bf6261829
Ref: library/os os stat_result st_mode6262050
Ref: 20ba6262050
Ref: library/os os stat_result st_ino6262160
Ref: 20bb6262160
Ref: library/os os stat_result st_dev6262447
Ref: 20bc6262447
Ref: library/os os stat_result st_nlink6262520
Ref: 20bd6262520
Ref: library/os os stat_result st_uid6262580
Ref: 20be6262580
Ref: library/os os stat_result st_gid6262647
Ref: 20bf6262647
Ref: library/os os stat_result st_size6262717
Ref: 20c06262717
Ref: library/os os stat_result st_atime6262953
Ref: 20c16262953
Ref: library/os os stat_result st_mtime6263034
Ref: 1eb96263034
Ref: library/os os stat_result st_ctime6263115
Ref: 20c26263115
Ref: library/os os stat_result st_atime_ns6263311
Ref: 20c36263311
Ref: library/os os stat_result st_mtime_ns6263407
Ref: 20c46263407
Ref: library/os os stat_result st_ctime_ns6263503
Ref: 20c56263503
Ref: library/os os stat_result st_blocks6264771
Ref: 20c66264771
Ref: library/os os stat_result st_blksize6264945
Ref: 20c76264945
Ref: library/os os stat_result st_rdev6265143
Ref: 20c86265143
Ref: library/os os stat_result st_flags6265224
Ref: 20c96265224
Ref: library/os os stat_result st_gen6265431
Ref: 20ca6265431
Ref: library/os os stat_result st_birthtime6265486
Ref: 20cb6265486
Ref: library/os os stat_result st_fstype6265623
Ref: 4c56265623
Ref: library/os os stat_result st_rsize6265801
Ref: 20cc6265801
Ref: library/os os stat_result st_creator6265864
Ref: 20cd6265864
Ref: library/os os stat_result st_type6265926
Ref: 20ce6265926
Ref: library/os os stat_result st_file_attributes6266034
Ref: 80f6266034
Ref: library/os os stat_result st_reparse_tag6266341
Ref: 20cf6266341
Ref: library/os os statvfs6268126
Ref: b1e6268126
Ref: library/os os supports_dir_fd6270058
Ref: b1a6270058
Ref: library/os os supports_effective_ids6271097
Ref: b206271097
Ref: library/os os supports_fd6271755
Ref: b1f6271755
Ref: library/os os supports_follow_symlinks6272508
Ref: 1de56272508
Ref: library/os os symlink6273538
Ref: b176273538
Ref: library/os os sync6275167
Ref: b346275167
Ref: library/os os truncate6275296
Ref: 8136275296
Ref: library/os os unlink6275772
Ref: b186275772
Ref: library/os os utime6276251
Ref: b196276251
Ref: library/os os walk6277998
Ref: 7476277998
Ref: library/os os fwalk6282729
Ref: 4ba6282729
Ref: library/os os memfd_create6285213
Ref: 3206285213
Ref: library/os os MFD_CLOEXEC6286010
Ref: 20d06286010
Ref: library/os os MFD_ALLOW_SEALING6286035
Ref: 20d16286035
Ref: library/os os MFD_HUGETLB6286066
Ref: 20d26286066
Ref: library/os os MFD_HUGE_SHIFT6286091
Ref: 20d36286091
Ref: library/os os MFD_HUGE_MASK6286119
Ref: 20d46286119
Ref: library/os os MFD_HUGE_64KB6286146
Ref: 20d56286146
Ref: library/os os MFD_HUGE_512KB6286173
Ref: 20d66286173
Ref: library/os os MFD_HUGE_1MB6286201
Ref: 20d76286201
Ref: library/os os MFD_HUGE_2MB6286227
Ref: 20d86286227
Ref: library/os os MFD_HUGE_8MB6286253
Ref: 20d96286253
Ref: library/os os MFD_HUGE_16MB6286279
Ref: 20da6286279
Ref: library/os os MFD_HUGE_32MB6286306
Ref: 20db6286306
Ref: library/os os MFD_HUGE_256MB6286333
Ref: 20dc6286333
Ref: library/os os MFD_HUGE_512MB6286361
Ref: 20dd6286361
Ref: library/os os MFD_HUGE_1GB6286389
Ref: 20de6286389
Ref: library/os os MFD_HUGE_2GB6286415
Ref: 20df6286415
Ref: library/os os MFD_HUGE_16GB6286441
Ref: 20e06286441
Ref: 文件和目录-Footnote-16286793
Ref: 文件和目录-Footnote-26286842
Ref: 文件和目录-Footnote-36286885
Ref: 文件和目录-Footnote-46286964
Ref: 文件和目录-Footnote-56287045
Ref: 文件和目录-Footnote-66287134
Ref: 文件和目录-Footnote-76287223
Node: Linux 扩展属性6287281
Ref: library/os linux-extended-attributes6287351
Ref: 20e16287351
Ref: library/os os getxattr6287462
Ref: b266287462
Ref: library/os os listxattr6288107
Ref: b276288107
Ref: library/os os removexattr6288703
Ref: b286288703
Ref: library/os os setxattr6289350
Ref: b296289350
Ref: library/os os XATTR_SIZE_MAX6290522
Ref: 20e46290522
Ref: library/os os XATTR_CREATE6290635
Ref: 20e36290635
Ref: library/os os XATTR_REPLACE6290781
Ref: 20e26290781
Node: 进程管理6290928
Ref: library/os os-process6291056
Ref: 20e56291056
Ref: library/os process-management6291056
Ref: 20e66291056
Ref: library/os os abort6291598
Ref: 20e86291598
Ref: library/os os add_dll_directory6291983
Ref: 2f36291983
Ref: library/os os execl6293042
Ref: 20e76293042
Ref: library/os os execle6293087
Ref: 20e96293087
Ref: library/os os execlp6293138
Ref: 20ea6293138
Ref: library/os os execlpe6293184
Ref: 20eb6293184
Ref: library/os os execv6293236
Ref: 20586293236
Ref: library/os os execve6293270
Ref: b1b6293270
Ref: library/os os execvp6293310
Ref: 20ec6293310
Ref: library/os os execvpe6293345
Ref: 20ed6293345
Ref: library/os os _exit6296062
Ref: 18546296062
Ref: library/os os EX_OK6296760
Ref: 20ee6296760
Ref: library/os os EX_USAGE6296870
Ref: 20ef6296870
Ref: library/os os EX_DATAERR6297016
Ref: 20f06297016
Ref: library/os os EX_NOINPUT6297131
Ref: 20f16297131
Ref: library/os os EX_NOUSER6297264
Ref: 20f26297264
Ref: library/os os EX_NOHOST6297381
Ref: 20f36297381
Ref: library/os os EX_UNAVAILABLE6297498
Ref: 20f46297498
Ref: library/os os EX_SOFTWARE6297620
Ref: 20f56297620
Ref: library/os os EX_OSERR6297742
Ref: 20f66297742
Ref: library/os os EX_OSFILE6297897
Ref: 20f76297897
Ref: library/os os EX_CANTCREAT6298053
Ref: 20f86298053
Ref: library/os os EX_IOERR6298188
Ref: 20f96298188
Ref: library/os os EX_TEMPFAIL6298322
Ref: 20fa6298322
Ref: library/os os EX_PROTOCOL6298546
Ref: 20fb6298546
Ref: library/os os EX_NOPERM6298695
Ref: 20fc6298695
Ref: library/os os EX_CONFIG6298863
Ref: 20fd6298863
Ref: library/os os EX_NOTFOUND6298980
Ref: 20fe6298980
Ref: library/os os fork6299114
Ref: a426299114
Ref: library/os os forkpty6299797
Ref: 20ff6299797
Ref: library/os os kill6300489
Ref: db96300489
Ref: library/os os killpg6301262
Ref: 10e16301262
Ref: library/os os nice6301487
Ref: b236301487
Ref: library/os os pidfd_open6301645
Ref: 1586301645
Ref: library/os os plock6302035
Ref: 21026302035
Ref: library/os os popen6302225
Ref: 3cb6302225
Ref: library/os os posix_spawn6303619
Ref: 3816303619
Ref: library/os os POSIX_SPAWN_OPEN6304615
Ref: 21036304615
Ref: library/os os POSIX_SPAWN_CLOSE6304788
Ref: 21046304788
Ref: library/os os POSIX_SPAWN_DUP26304911
Ref: 21056304911
Ref: library/os os posix_spawnp6307271
Ref: 114d6307271
Ref: library/os os register_at_fork6307943
Ref: 4bc6307943
Ref: library/os os spawnl6309260
Ref: 20a36309260
Ref: library/os os spawnle6309300
Ref: 21076309300
Ref: library/os os spawnlp6309346
Ref: 21086309346
Ref: library/os os spawnlpe6309387
Ref: 21096309387
Ref: library/os os spawnv6309434
Ref: 210a6309434
Ref: library/os os spawnve6309475
Ref: 210b6309475
Ref: library/os os spawnvp6309522
Ref: 210c6309522
Ref: library/os os spawnvpe6309564
Ref: 210d6309564
Ref: library/os os P_NOWAIT6312897
Ref: 210e6312897
Ref: library/os os P_NOWAITO6312919
Ref: 21106312919
Ref: library/os os P_WAIT6313206
Ref: 210f6313206
Ref: library/os os P_DETACH6313542
Ref: 21116313542
Ref: library/os os P_OVERLAY6313564
Ref: 21126313564
Ref: library/os os startfile6313972
Ref: 21136313972
Ref: library/os os system6315558
Ref: e866315558
Ref: library/os os times6317083
Ref: b376317083
Ref: library/os os wait6318080
Ref: 75e6318080
Ref: library/os os waitid6318682
Ref: 75f6318682
Ref: library/os os P_PID6319514
Ref: 21146319514
Ref: library/os os P_PGID6319533
Ref: 21156319533
Ref: library/os os P_ALL6319553
Ref: 21166319553
Ref: library/os os P_PIDFD6319739
Ref: 1cb6319739
Ref: library/os os WEXITED6319942
Ref: 21176319942
Ref: library/os os WSTOPPED6319963
Ref: 21186319963
Ref: library/os os WNOWAIT6319985
Ref: 211b6319985
Ref: library/os os CLD_EXITED6320181
Ref: 211c6320181
Ref: library/os os CLD_KILLED6320205
Ref: 1c96320205
Ref: library/os os CLD_DUMPED6320229
Ref: 211d6320229
Ref: library/os os CLD_TRAPPED6320253
Ref: 211e6320253
Ref: library/os os CLD_STOPPED6320278
Ref: 1ca6320278
Ref: library/os os CLD_CONTINUED6320303
Ref: 211f6320303
Ref: library/os os waitpid6320565
Ref: 7606320565
Ref: library/os os wait36322280
Ref: 75c6322280
Ref: library/os os wait46322822
Ref: 75d6322822
Ref: library/os os waitstatus_to_exitcode6323333
Ref: 1ce6323333
Ref: library/os os WNOHANG6324502
Ref: 211a6324502
Ref: library/os os WCONTINUED6324728
Ref: 21196324728
Ref: library/os os WUNTRACED6324953
Ref: 21206324953
Ref: library/os os WCOREDUMP6325331
Ref: 21276325331
Ref: library/os os WIFCONTINUED6325577
Ref: 21286325577
Ref: library/os os WIFSTOPPED6325902
Ref: 21256325902
Ref: library/os os WIFSIGNALED6326305
Ref: 21236326305
Ref: library/os os WIFEXITED6326483
Ref: 21216326483
Ref: library/os os WEXITSTATUS6326759
Ref: 21226326759
Ref: library/os os WSTOPSIG6326943
Ref: 21266326943
Ref: library/os os WTERMSIG6327134
Ref: 21246327134
Ref: 进程管理-Footnote-16327371
Ref: 进程管理-Footnote-26327443
Ref: 进程管理-Footnote-36327552
Node: 调度器接口6327601
Ref: library/os interface-to-the-scheduler6327732
Ref: 212a6327732
Ref: library/os os SCHED_OTHER6328039
Ref: 212b6328039
Ref: library/os os SCHED_BATCH6328093
Ref: 212c6328093
Ref: library/os os SCHED_IDLE6328236
Ref: 212d6328236
Ref: library/os os SCHED_SPORADIC6328322
Ref: 212e6328322
Ref: library/os os SCHED_FIFO6328403
Ref: 212f6328403
Ref: library/os os SCHED_RR6328465
Ref: 21306328465
Ref: library/os os SCHED_RESET_ON_FORK6328522
Ref: 21316328522
Ref: library/os os sched_param6328739
Ref: 21066328739
Ref: library/os os sched_param sched_priority6329026
Ref: 21326329026
Ref: library/os os sched_get_priority_min6329110
Ref: b2b6329110
Ref: library/os os sched_get_priority_max6329254
Ref: b2a6329254
Ref: library/os os sched_setscheduler6329398
Ref: b326329398
Ref: library/os os sched_getscheduler6329665
Ref: b2e6329665
Ref: library/os os sched_setparam6329866
Ref: b316329866
Ref: library/os os sched_getparam6330060
Ref: b2d6330060
Ref: library/os os sched_rr_get_interval6330247
Ref: b2f6330247
Ref: library/os os sched_yield6330448
Ref: b336330448
Ref: library/os os sched_setaffinity6330505
Ref: b306330505
Ref: library/os os sched_getaffinity6330732
Ref: b2c6330732
Node: 其他系统信息6330870
Ref: library/os miscellaneous-system-information6330998
Ref: 21336330998
Ref: library/os os-path6330998
Ref: 21346330998
Ref: library/os os confstr6331051
Ref: 21356331051
Ref: library/os os confstr_names6331980
Ref: 21366331980
Ref: library/os os cpu_count6332254
Ref: 96a6332254
Ref: library/os os getloadavg6332522
Ref: 21376332522
Ref: library/os os sysconf6332743
Ref: 20946332743
Ref: library/os os sysconf_names6333077
Ref: 21386333077
Ref: library/os os curdir6333501
Ref: 1d4f6333501
Ref: library/os os pardir6333670
Ref: 20ad6333670
Ref: library/os os sep6333837
Ref: 1dd46333837
Ref: library/os os altsep6334191
Ref: 1dd56334191
Ref: library/os os extsep6334458
Ref: 21396334458
Ref: library/os os pathsep6334609
Ref: 14866334609
Ref: library/os os defpath6334826
Ref: 111a6334826
Ref: library/os os linesep6335034
Ref: 17326335034
Ref: library/os os devnull6335426
Ref: 11526335426
Ref: library/os os RTLD_LAZY6335591
Ref: b3a6335591
Ref: library/os os RTLD_NOW6335614
Ref: b3b6335614
Ref: library/os os RTLD_GLOBAL6335636
Ref: b3c6335636
Ref: library/os os RTLD_LOCAL6335661
Ref: b3d6335661
Ref: library/os os RTLD_NODELETE6335685
Ref: b3e6335685
Ref: library/os os RTLD_NOLOAD6335712
Ref: b3f6335712
Ref: library/os os RTLD_DEEPBIND6335737
Ref: b406335737
Node: 随机数6335962
Ref: library/os random-numbers6336066
Ref: 213a6336066
Ref: library/os os getrandom6336104
Ref: 6626336104
Ref: library/os os urandom6336895
Ref: 5cb6336895
Ref: library/os os GRND_NONBLOCK6338675
Ref: 213c6338675
Ref: library/os os GRND_RANDOM6339136
Ref: 213b6339136
Ref: 随机数-Footnote-16339354
Ref: 随机数-Footnote-26339416
Node: io --- 处理流的核心工具6339465
Ref: library/io doc6339639
Ref: 213d6339639
Ref: library/io io-core-tools-for-working-with-streams6339639
Ref: 213e6339639
Ref: library/io module-io6339639
Ref: a16339639
Ref: io --- 处理流的核心工具-Footnote-16339935
Node: 總覽6339996
Ref: library/io io-overview6340097
Ref: 172d6340097
Ref: library/io overview6340097
Ref: 213f6340097
Node: 文本 I/O6341264
Ref: library/io text-i-o6341339
Ref: 21406341339
Node: 二进制 I/O6341956
Ref: library/io binary-i-o6342050
Ref: 21416342050
Node: 原始 I/O6342871
Ref: library/io raw-i-o6342946
Ref: 21426342946
Node: 高阶模块接口6343354
Ref: library/io high-level-module-interface6343482
Ref: 21436343482
Ref: library/io io DEFAULT_BUFFER_SIZE6343533
Ref: 172f6343533
Ref: library/io io open6343749
Ref: 74d6343749
Ref: library/io io open_code6344051
Ref: 10506344051
Ref: library/io io BlockingIOError6344686
Ref: 21456344686
Ref: library/io io UnsupportedOperation6344796
Ref: 10836344796
Node: 类的层次结构6345096
Ref: library/io class-hierarchy6345227
Ref: 21466345227
Node: I/O 基类6349466
Ref: library/io i-o-base-classes6349556
Ref: 21486349556
Ref: library/io io IOBase6349595
Ref: 30c6349595
Ref: library/io io IOBase close6351291
Ref: 11476351291
Ref: library/io io IOBase closed6351642
Ref: 11486351642
Ref: library/io io IOBase fileno6351717
Ref: 20696351717
Ref: library/io io IOBase flush6351916
Ref: 21496351916
Ref: library/io io IOBase isatty6352051
Ref: 17306352051
Ref: library/io io IOBase readable6352182
Ref: 214a6352182
Ref: library/io io IOBase readline6352370
Ref: 18496352370
Ref: library/io io IOBase readlines6352737
Ref: 18d66352737
Ref: library/io io IOBase seek6353266
Ref: 1efb6353266
Ref: library/io io IOBase seekable6354153
Ref: 214b6354153
Ref: library/io io IOBase tell6354397
Ref: 1efc6354397
Ref: library/io io IOBase truncate6354468
Ref: d6d6354468
Ref: library/io io IOBase writable6354987
Ref: 214c6354987
Ref: library/io io IOBase writelines6355188
Ref: 18d76355188
Ref: library/io io IOBase __del__6355372
Ref: 214d6355372
Ref: library/io io RawIOBase6355574
Ref: af16355574
Ref: library/io io RawIOBase read6356067
Ref: 7f36356067
Ref: library/io io RawIOBase readall6356744
Ref: 214e6356744
Ref: library/io io RawIOBase readinto6356882
Ref: 7f46356882
Ref: library/io io RawIOBase write6357218
Ref: 214f6357218
Ref: library/io io BufferedIOBase6357774
Ref: 67f6357774
Ref: library/io io BufferedIOBase raw6358970
Ref: 21516358970
Ref: library/io io BufferedIOBase detach6359209
Ref: 21526359209
Ref: library/io io BufferedIOBase read6359597
Ref: 1ebb6359597
Ref: library/io io BufferedIOBase read16360330
Ref: 1eba6360330
Ref: library/io io BufferedIOBase readinto6360786
Ref: 21506360786
Ref: library/io io BufferedIOBase readinto16361287
Ref: 7f26361287
Ref: library/io io BufferedIOBase write6361746
Ref: 6806361746
Node: 原始文件 I/O6362470
Ref: library/io raw-file-i-o6362578
Ref: 21536362578
Ref: library/io io FileIO6362627
Ref: d6c6362627
Ref: library/io io FileIO mode6364788
Ref: 21546364788
Ref: library/io io FileIO name6364856
Ref: 1f4f6364856
Node: 缓冲流6364978
Ref: library/io buffered-streams6365089
Ref: 21556365089
Ref: library/io io BytesIO6365210
Ref: 88a6365210
Ref: library/io io BytesIO getbuffer6365674
Ref: c3f6365674
Ref: library/io io BytesIO getvalue6366210
Ref: 1eb86366210
Ref: library/io io BytesIO read16366315
Ref: 21566366315
Ref: library/io io BytesIO readinto16366493
Ref: 21576366493
Ref: library/io io BufferedReader6366642
Ref: c5b6366642
Ref: library/io io BufferedReader peek6367428
Ref: 21586367428
Ref: library/io io BufferedReader read6367644
Ref: 21596367644
Ref: library/io io BufferedReader read16367848
Ref: 215a6367848
Ref: library/io io BufferedWriter6368178
Ref: 17336368178
Ref: library/io io BufferedWriter flush6369233
Ref: 215b6369233
Ref: library/io io BufferedWriter write6369423
Ref: 215c6369423
Ref: library/io io BufferedRandom6369689
Ref: 17346369689
Ref: library/io io BufferedRWPair6370366
Ref: 21476370366
Node: 文本 I/O<2>6371277
Ref: library/io id16371363
Ref: 215d6371363
Ref: library/io io TextIOBase6371404
Ref: d016371404
Ref: library/io io TextIOBase encoding6371710
Ref: 215e6371710
Ref: library/io io TextIOBase errors6371862
Ref: 215f6371862
Ref: library/io io TextIOBase newlines6371938
Ref: 21606371938
Ref: library/io io TextIOBase buffer6372162
Ref: d026372162
Ref: library/io io TextIOBase detach6372423
Ref: 21616372423
Ref: library/io io TextIOBase read6372893
Ref: 21626372893
Ref: library/io io TextIOBase readline6373100
Ref: 1d5b6373100
Ref: library/io io TextIOBase seek6373355
Ref: 21636373355
Ref: library/io io TextIOBase tell6374255
Ref: 21646374255
Ref: library/io io TextIOBase write6374434
Ref: 21656374434
Ref: library/io io TextIOWrapper6374539
Ref: 6ea6374539
Ref: library/io io TextIOWrapper line_buffering6377828
Ref: 21676377828
Ref: library/io io TextIOWrapper write_through6377897
Ref: 21686377897
Ref: library/io io TextIOWrapper reconfigure6378024
Ref: 4a36378024
Ref: library/io io StringIO6378750
Ref: 91a6378750
Ref: library/io io StringIO getvalue6379582
Ref: 21696379582
Ref: library/io io IncrementalNewlineDecoder6380226
Ref: 216a6380226
Node: 性能<3>6380425
Ref: library/io performance6380529
Ref: 216b6380529
Node: 二进制 I/O<2>6380735
Ref: library/io id26380819
Ref: 216c6380819
Node: 文本 I/O<3>6381411
Ref: library/io id36381516
Ref: 216d6381516
Node: 多线程<2>6382035
Ref: library/io multi-threading6382136
Ref: 216e6382136
Node: 可重入性6382634
Ref: library/io reentrancy6382713
Ref: 216f6382713
Node: time --- 时间的访问和转换6383445
Ref: library/time doc6383646
Ref: 21706383646
Ref: library/time module-time6383646
Ref: 10c6383646
Ref: library/time time-time-access-and-conversions6383646
Ref: 21716383646
Ref: library/time epoch6384277
Ref: 21726384277
Ref: time --- 时间的访问和转换-Footnote-16388636
Node: 函数<3>6388686
Ref: library/time functions6388789
Ref: 21736388789
Ref: library/time time-functions6388789
Ref: 21746388789
Ref: library/time time asctime6388820
Ref: c356388820
Ref: library/time time pthread_getcpuclockid6389459
Ref: 4ff6389459
Ref: library/time time clock_getres6390036
Ref: b8a6390036
Ref: library/time time clock_gettime6390289
Ref: b8b6390289
Ref: library/time time clock_gettime_ns6390536
Ref: 42e6390536
Ref: library/time time clock_settime6390725
Ref: b8c6390725
Ref: library/time time clock_settime_ns6390969
Ref: 42f6390969
Ref: library/time time ctime6391162
Ref: 19f66391162
Ref: library/time time get_clock_info6391719
Ref: b896391719
Ref: library/time time gmtime6392777
Ref: c116392777
Ref: library/time time localtime6393243
Ref: 10806393243
Ref: library/time time mktime6393528
Ref: c366393528
Ref: library/time time monotonic6394143
Ref: 85e6394143
Ref: library/time time monotonic_ns6394541
Ref: 4306394541
Ref: library/time time perf_counter6394683
Ref: 3cc6394683
Ref: library/time time perf_counter_ns6395089
Ref: 4316395089
Ref: library/time time process_time6395234
Ref: 3cd6395234
Ref: library/time time process_time_ns6395600
Ref: 4326395600
Ref: library/time time sleep6395745
Ref: 7736395745
Ref: library/time time strftime6396484
Ref: c376396484
Ref: library/time time strptime6403183
Ref: e566403183
Ref: library/time time struct_time6404654
Ref: 6906404654
Ref: library/time time time6407370
Ref: 42d6407370
Ref: library/time time thread_time6408507
Ref: 1e76408507
Ref: library/time time thread_time_ns6408982
Ref: 4fe6408982
Ref: library/time time time_ns6409119
Ref: 4336409119
Ref: library/time time tzset6409312
Ref: 21776409312
Ref: 函数<3>-Footnote-16412867
Ref: 函数<3>-Footnote-26412916
Ref: 函数<3>-Footnote-36412966
Ref: 函数<3>-Footnote-46413015
Ref: 函数<3>-Footnote-56413607
Ref: 函数<3>-Footnote-66413657
Node: Clock ID 常量6413705
Ref: library/time clock-id-constants6413829
Ref: 21786413829
Ref: library/time time-clock-id-constants6413829
Ref: 21766413829
Ref: library/time time CLOCK_BOOTTIME6413971
Ref: 4fa6413971
Ref: library/time time CLOCK_HIGHRES6414411
Ref: 21796414411
Ref: library/time time CLOCK_MONOTONIC6414702
Ref: 4fb6414702
Ref: library/time time CLOCK_MONOTONIC_RAW6414885
Ref: 217a6414885
Ref: library/time time CLOCK_PROCESS_CPUTIME_ID6415158
Ref: 217b6415158
Ref: library/time time CLOCK_PROF6415314
Ref: 4fc6415314
Ref: library/time time CLOCK_TAI6415489
Ref: 10526415489
Ref: library/time time CLOCK_THREAD_CPUTIME_ID6415740
Ref: 217c6415740
Ref: library/time time CLOCK_UPTIME6415880
Ref: 4fd6415880
Ref: library/time time CLOCK_UPTIME_RAW6416144
Ref: 3656416144
Ref: library/time time CLOCK_REALTIME6416504
Ref: f6d6416504
Ref: Clock ID 常量-Footnote-16416711
Node: 时区常量6416818
Ref: library/time time-timezone-constants6416924
Ref: 217d6416924
Ref: library/time timezone-constants6416924
Ref: 217e6416924
Ref: library/time time altzone6416965
Ref: 217f6416965
Ref: library/time time daylight6417239
Ref: 21806417239
Ref: library/time time timezone6417335
Ref: 21816417335
Ref: library/time time tzname6417518
Ref: 21826417518
Node: argparse --- 命令行选项、参数和子命令解析器6418599
Ref: library/argparse doc6418815
Ref: 21836418815
Ref: library/argparse argparse-parser-for-command-line-options-arguments-and-sub-commands6418815
Ref: 21846418815
Ref: library/argparse module-argparse6418815
Ref: 56418815
Ref: argparse --- 命令行选项、参数和子命令解析器-Footnote-16419781
Node: 示例<16>6419848
Ref: library/argparse example6419983
Ref: 21866419983
Node: 创建一个解析器6421545
Ref: library/argparse creating-a-parser6421634
Ref: 21876421634
Node: 添加参数6421971
Ref: library/argparse adding-arguments6422081
Ref: 21886422081
Node: 解析参数6423140
Ref: library/argparse parsing-arguments6423220
Ref: 218b6423220
Node: ArgumentParser 对象6423870
Ref: library/argparse argumentparser-objects6424033
Ref: 218d6424033
Ref: library/argparse argparse ArgumentParser6424094
Ref: 7886424094
Node: prog6426716
Ref: library/argparse prog6426792
Ref: 218e6426792
Node: usage6428594
Ref: library/argparse usage6428690
Ref: 218f6428690
Node: description6429830
Ref: library/argparse description6429928
Ref: 21906429928
Node: epilog6430636
Ref: library/argparse epilog6430736
Ref: 21916430736
Node: parents6431486
Ref: library/argparse parents6431590
Ref: 21926431590
Node: formatter_class6432999
Ref: library/argparse formatter-class6433109
Ref: 21936433109
Ref: library/argparse argparse RawDescriptionHelpFormatter6433294
Ref: 219a6433294
Ref: library/argparse argparse RawTextHelpFormatter6433343
Ref: 219b6433343
Ref: library/argparse argparse ArgumentDefaultsHelpFormatter6433385
Ref: f806433385
Ref: library/argparse argparse MetavarTypeHelpFormatter6433436
Ref: 219c6433436
Node: prefix_chars6436843
Ref: library/argparse prefix-chars6436967
Ref: 21946436967
Node: fromfile_prefix_chars6437637
Ref: library/argparse fromfile-prefix-chars6437762
Ref: 21956437762
Node: argument_default6438905
Ref: library/argparse argument-default6439030
Ref: 21966439030
Node: allow_abbrev6439876
Ref: library/argparse allow-abbrev6439996
Ref: 78a6439996
Ref: library/argparse id16439996
Ref: 21a16439996
Node: conflict_handler6440638
Ref: library/argparse conflict-handler6440750
Ref: 21976440750
Node: add_help6442259
Ref: library/argparse add-help6442372
Ref: 21986442372
Node: exit_on_error6443880
Ref: library/argparse exit-on-error6443968
Ref: 21996443968
Node: add_argument 方法6444797
Ref: library/argparse the-add-argument-method6444967
Ref: 21a26444967
Ref: library/argparse argparse ArgumentParser add_argument6445030
Ref: 21896445030
Node: name or flags6446646
Ref: library/argparse name-or-flags6446730
Ref: 21a36446730
Node: action6447782
Ref: library/argparse action6447880
Ref: 21a46447880
Node: nargs6453508
Ref: library/argparse nargs6453598
Ref: 21a56453598
Node: const6457196
Ref: library/argparse const6457287
Ref: 21a66457287
Node: default6458271
Ref: library/argparse default6458361
Ref: 21a76458361
Node: type6460365
Ref: library/argparse type6460457
Ref: 219d6460457
Node: choices6463285
Ref: library/argparse choices6463378
Ref: 21a86463378
Node: required6465187
Ref: library/argparse required6465280
Ref: 21a96465280
Node: help6466247
Ref: library/argparse help6466340
Ref: 21aa6466340
Node: metavar6468410
Ref: library/argparse metavar6468499
Ref: 21ab6468499
Node: dest6470638
Ref: library/argparse dest6470733
Ref: 219e6470733
Node: Action 类6472268
Ref: library/argparse action-classes6472347
Ref: 21ad6472347
Ref: library/argparse argparse Action6472631
Ref: 21ac6472631
Node: parse_args 方法6474504
Ref: library/argparse the-parse-args-method6474671
Ref: 21ae6474671
Ref: library/argparse argparse ArgumentParser parse_args6474730
Ref: 218a6474730
Node: 选项值语法6475541
Ref: library/argparse option-value-syntax6475634
Ref: 21b16475634
Node: 无效的参数6476975
Ref: library/argparse invalid-arguments6477095
Ref: 21b26477095
Node: 包含 - 的参数6478049
Ref: library/argparse arguments-containing6478184
Ref: 21b36478184
Node: 参数缩写（前缀匹配）6480054
Ref: library/argparse argument-abbreviations-prefix-matching6480193
Ref: 21b46480193
Ref: library/argparse prefix-matching6480193
Ref: 7896480193
Node: 在 sys argv 以外6481057
Ref: library/argparse args6481196
Ref: 21af6481196
Ref: library/argparse beyond-sys-argv6481196
Ref: 21b56481196
Node: 命名空间对象6482123
Ref: library/argparse namespace6482223
Ref: 21b06482223
Ref: library/argparse the-namespace-object6482223
Ref: 21b66482223
Ref: library/argparse argparse Namespace6482276
Ref: 218c6482276
Node: 其它实用工具6483274
Ref: library/argparse other-utilities6483444
Ref: 21b76483444
Node: 子命令6483683
Ref: library/argparse sub-commands6483771
Ref: 21b86483771
Ref: library/argparse argparse ArgumentParser add_subparsers6483809
Ref: 59e6483809
Node: FileType 对象6492206
Ref: library/argparse filetype-objects6492312
Ref: 21b96492312
Ref: library/argparse argparse FileType6492363
Ref: 90d6492363
Node: 参数组6493769
Ref: library/argparse argument-groups6493872
Ref: 21ba6493872
Ref: library/argparse argparse ArgumentParser add_argument_group6493910
Ref: 21bb6493910
Node: 互斥6495910
Ref: library/argparse mutual-exclusion6496016
Ref: 21bc6496016
Ref: library/argparse argparse ArgumentParser add_mutually_exclusive_group6496049
Ref: 21bd6496049
Node: 解析器默认值6497528
Ref: library/argparse parser-defaults6497637
Ref: 21be6497637
Ref: library/argparse argparse ArgumentParser set_defaults6497690
Ref: 21a06497690
Ref: library/argparse argparse ArgumentParser get_default6498705
Ref: 21bf6498705
Node: 打印帮助6499068
Ref: library/argparse printing-help6499183
Ref: 21c06499183
Ref: library/argparse argparse ArgumentParser print_usage6499395
Ref: 21c16499395
Ref: library/argparse argparse ArgumentParser print_help6499645
Ref: 21c26499645
Ref: library/argparse argparse ArgumentParser format_usage6499995
Ref: 10d06499995
Ref: library/argparse argparse ArgumentParser format_help6500177
Ref: 21c36500177
Node: 部分解析6500368
Ref: library/argparse partial-parsing6500486
Ref: 21c46500486
Ref: library/argparse argparse ArgumentParser parse_known_args6500529
Ref: 21c56500529
Node: 自定义文件解析6501556
Ref: library/argparse customizing-file-parsing6501674
Ref: 21c66501674
Ref: library/argparse argparse ArgumentParser convert_arg_line_to_args6501732
Ref: 219f6501732
Node: 退出方法6502590
Ref: library/argparse exiting-methods6502708
Ref: 21c76502708
Ref: library/argparse argparse ArgumentParser exit6502751
Ref: 21c86502751
Ref: library/argparse argparse ArgumentParser error6503295
Ref: 21c96503295
Node: 混合解析6503459
Ref: library/argparse intermixed-parsing6503547
Ref: 21ca6503547
Ref: library/argparse argparse ArgumentParser parse_intermixed_args6503590
Ref: 4516503590
Ref: library/argparse argparse ArgumentParser parse_known_intermixed_args6503684
Ref: 21cb6503684
Node: 升级 optparse 代码6505175
Ref: library/argparse id26505319
Ref: 21cc6505319
Ref: library/argparse upgrading-optparse-code6505319
Ref: bfc6505319
Node: getopt --- C 风格的命令行选项解析器6507645
Ref: library/getopt doc6507868
Ref: 21cf6507868
Ref: library/getopt getopt-c-style-parser-for-command-line-options6507868
Ref: 21d06507868
Ref: library/getopt module-getopt6507868
Ref: 856507868
Ref: library/getopt getopt getopt6508743
Ref: 21d16508743
Ref: library/getopt getopt gnu_getopt6510649
Ref: 21d36510649
Ref: library/getopt getopt GetoptError6511157
Ref: 21d26511157
Ref: library/getopt getopt error6511657
Ref: 21d46511657
Ref: getopt --- C 风格的命令行选项解析器-Footnote-16514041
Node: logging --- Python 的日志记录工具6514106
Ref: library/logging doc6514308
Ref: 21d56514308
Ref: library/logging logging-logging-facility-for-python6514308
Ref: 21d66514308
Ref: library/logging module-logging6514308
Ref: aa6514308
Ref: logging --- Python 的日志记录工具-Footnote-16515834
Node: 记录器对象6515910
Ref: library/logging logger6516023
Ref: 21d76516023
Ref: library/logging logger-objects6516023
Ref: 21d86516023
Ref: library/logging logging Logger6516985
Ref: 4ad6516985
Ref: library/logging logging Logger propagate6517013
Ref: 21d96517013
Ref: library/logging logging Logger setLevel6518961
Ref: 21da6518961
Ref: library/logging logging Logger isEnabledFor6520540
Ref: 21dd6520540
Ref: library/logging logging Logger getEffectiveLevel6520849
Ref: 21dc6520849
Ref: library/logging logging Logger getChild6521272
Ref: d536521272
Ref: library/logging logging Logger debug6521705
Ref: 8016521705
Ref: library/logging logging Logger info6526085
Ref: 21e06526085
Ref: library/logging logging Logger warning6526252
Ref: 21e26526252
Ref: library/logging logging Logger error6526612
Ref: 21e36526612
Ref: library/logging logging Logger critical6526781
Ref: 8006526781
Ref: library/logging logging Logger log6526956
Ref: 7fe6526956
Ref: library/logging logging Logger exception6527141
Ref: 7ff6527141
Ref: library/logging logging Logger addFilter6527415
Ref: 21e46527415
Ref: library/logging logging Logger removeFilter6527525
Ref: 21e56527525
Ref: library/logging logging Logger filter6527637
Ref: 21e66527637
Ref: library/logging logging Logger addHandler6528036
Ref: 21e76528036
Ref: library/logging logging Logger removeHandler6528143
Ref: 21e86528143
Ref: library/logging logging Logger findCaller6528252
Ref: 21e96528252
Ref: library/logging logging Logger handle6528937
Ref: 21ea6528937
Ref: library/logging logging Logger makeRecord6529295
Ref: 21eb6529295
Ref: library/logging logging Logger hasHandlers6529559
Ref: 21ec6529559
Node: 日志级别6530154
Ref: library/logging levels6530291
Ref: 21db6530291
Ref: library/logging logging-levels6530291
Ref: 21ed6530291
Node: 处理器对象6531120
Ref: library/logging handler6531257
Ref: 21ee6531257
Ref: library/logging handler-objects6531257
Ref: 21ef6531257
Ref: library/logging logging Handler6531538
Ref: 21df6531538
Ref: library/logging logging Handler __init__6531567
Ref: 21f06531567
Ref: library/logging logging Handler createLock6531832
Ref: 21f16531832
Ref: library/logging logging Handler acquire6532019
Ref: 21f26532019
Ref: library/logging logging Handler release6532123
Ref: 21f36532123
Ref: library/logging logging Handler setLevel6532224
Ref: 21f46532224
Ref: library/logging logging Handler setFormatter6532719
Ref: 21f56532719
Ref: library/logging logging Handler addFilter6532834
Ref: 21f66532834
Ref: library/logging logging Handler removeFilter6532944
Ref: 21f76532944
Ref: library/logging logging Handler filter6533057
Ref: 21f86533057
Ref: library/logging logging Handler flush6533398
Ref: 21f96533398
Ref: library/logging logging Handler close6533556
Ref: 21fa6533556
Ref: library/logging logging Handler handle6533872
Ref: 21fc6533872
Ref: library/logging logging Handler handleError6534094
Ref: 21fd6534094
Ref: library/logging logging Handler format6534773
Ref: 21ff6534773
Ref: library/logging logging Handler emit6534938
Ref: 21fe6534938
Node: 格式器对象6535239
Ref: library/logging formatter-objects6535379
Ref: 22006535379
Ref: library/logging id16535379
Ref: 22016535379
Ref: library/logging logging Formatter6536361
Ref: 21de6536361
Ref: library/logging logging Formatter format6537581
Ref: 22056537581
Ref: library/logging logging Formatter formatTime6538736
Ref: 22036538736
Ref: library/logging logging Formatter formatException6540806
Ref: 22066540806
Ref: library/logging logging Formatter formatStack6541104
Ref: 22076541104
Node: 过滤器对象6541366
Ref: library/logging filter6541507
Ref: 22096541507
Ref: library/logging filter-objects6541507
Ref: 220a6541507
Ref: library/logging logging Filter6542025
Ref: c486542025
Ref: library/logging logging Filter filter6542328
Ref: 220b6542328
Node: LogRecord 属性6544192
Ref: library/logging log-record6544337
Ref: 220e6544337
Ref: library/logging logrecord-objects6544337
Ref: 220f6544337
Ref: library/logging logging LogRecord6544608
Ref: 9ec6544608
Ref: library/logging logging LogRecord getMessage6546166
Ref: 22116546166
Node: LogRecord 属性<2>6547538
Ref: library/logging id26547688
Ref: 22146547688
Ref: library/logging logrecord-attributes6547688
Ref: 22026547688
Node: LoggerAdapter 对象6554988
Ref: library/logging logger-adapter6555134
Ref: 22166555134
Ref: library/logging loggeradapter-objects6555134
Ref: 22176555134
Ref: library/logging logging LoggerAdapter6555400
Ref: d546555400
Ref: library/logging logging LoggerAdapter process6555607
Ref: 22196555607
Node: 线程安全6556903
Ref: library/logging thread-safety6557045
Ref: 221a6557045
Node: 模块级函数6557654
Ref: library/logging module-level-functions6557791
Ref: 221b6557791
Ref: library/logging logging getLogger6557898
Ref: 2346557898
Ref: library/logging logging getLoggerClass6558466
Ref: 221c6558466
Ref: library/logging logging getLogRecordFactory6558892
Ref: 22126558892
Ref: library/logging logging debug6559330
Ref: 21e16559330
Ref: library/logging logging info6562647
Ref: 220c6562647
Ref: library/logging logging warning6562814
Ref: 221e6562814
Ref: library/logging logging error6563178
Ref: 221f6563178
Ref: library/logging logging critical6563347
Ref: 22206563347
Ref: library/logging logging exception6563522
Ref: 22216563522
Ref: library/logging logging log6563799
Ref: 22226563799
Ref: library/logging logging disable6564616
Ref: fcc6564616
Ref: library/logging logging addLevelName6565711
Ref: 22236565711
Ref: library/logging logging getLevelName6566307
Ref: 22256566307
Ref: library/logging logging makeLogRecord6567709
Ref: 22106567709
Ref: library/logging logging basicConfig6568045
Ref: 3116568045
Ref: library/logging logging shutdown6572801
Ref: 21fb6572801
Ref: library/logging logging setLoggerClass6573201
Ref: 221d6573201
Ref: library/logging logging setLogRecordFactory6573823
Ref: 22136573823
Ref: 模块级函数-Footnote-16575047
Node: 模块级属性6575090
Ref: library/logging module-level-attributes6575236
Ref: 22266575236
Ref: library/logging logging lastResort6575284
Ref: c476575284
Node: 与警告模块集成6575840
Ref: library/logging integration-with-the-warnings-module6575962
Ref: 22276575962
Ref: library/logging logging captureWarnings6576131
Ref: 22286576131
Ref: 与警告模块集成-Footnote-16577348
Ref: 与警告模块集成-Footnote-26577397
Node: logging config --- 日志记录配置6577450
Ref: library/logging config doc6577645
Ref: 22296577645
Ref: library/logging config logging-config-logging-configuration6577645
Ref: 222a6577645
Ref: library/logging config module-logging config6577645
Ref: ab6577645
Ref: logging config --- 日志记录配置-Footnote-16578218
Node: 配置函数6578291
Ref: library/logging config configuration-functions6578409
Ref: 222b6578409
Ref: library/logging config logging-config-api6578409
Ref: d506578409
Ref: library/logging config logging config dictConfig6578790
Ref: bfe6578790
Ref: library/logging config logging config fileConfig6580653
Ref: 4af6580653
Ref: library/logging config logging config listen6582709
Ref: 95d6582709
Ref: library/logging config logging-eval-security6584383
Ref: 22306584383
Ref: library/logging config logging config stopListening6586001
Ref: 222f6586001
Node: Security considerations6586231
Ref: library/logging config security-considerations6586376
Ref: 22316586376
Node: 配置字典架构6587092
Ref: library/logging config configuration-dictionary-schema6587243
Ref: 22336587243
Ref: library/logging config logging-config-dictschema6587243
Ref: 222c6587243
Node: 字典架构细节6588049
Ref: library/logging config dictionary-schema-details6588143
Ref: 22356588143
Node: 增量配置6592624
Ref: library/logging config incremental-configuration6592739
Ref: 22386592739
Ref: library/logging config logging-config-dict-incremental6592739
Ref: 22376592739
Node: 对象连接6594021
Ref: library/logging config logging-config-dict-connections6594136
Ref: 22346594136
Ref: library/logging config object-connections6594136
Ref: 22396594136
Node: 用户定义对象6596258
Ref: library/logging config logging-config-dict-userdef6596379
Ref: 22326596379
Ref: library/logging config user-defined-objects6596379
Ref: 223a6596379
Node: 访问外部对象6599449
Ref: library/logging config access-to-external-objects6599576
Ref: 223b6599576
Ref: library/logging config logging-config-dict-externalobj6599576
Ref: 223c6599576
Node: 访问内部对象6600689
Ref: library/logging config access-to-internal-objects6600828
Ref: 223d6600828
Ref: library/logging config logging-config-dict-internalobj6600828
Ref: 223e6600828
Node: 导入解析与定制导入器6603942
Ref: library/logging config import-resolution-and-custom-importers6604054
Ref: 22406604054
Ref: library/logging config logging-import-resolution6604054
Ref: 22416604054
Node: 配置文件格式6604969
Ref: library/logging config configuration-file-format6605088
Ref: 22426605088
Ref: library/logging config logging-config-fileformat6605088
Ref: 222d6605088
Node: logging handlers --- 日志处理程序6612181
Ref: library/logging handlers doc6612375
Ref: 22436612375
Ref: library/logging handlers logging-handlers-logging-handlers6612375
Ref: 22446612375
Ref: library/logging handlers module-logging handlers6612375
Ref: ac6612375
Ref: logging handlers --- 日志处理程序-Footnote-16613403
Node: StreamHandler6613479
Ref: library/logging handlers stream-handler6613588
Ref: 22466613588
Ref: library/logging handlers streamhandler6613588
Ref: 22476613588
Ref: library/logging handlers logging StreamHandler6613902
Ref: c466613902
Ref: library/logging handlers logging StreamHandler emit6614131
Ref: 22486614131
Ref: library/logging handlers logging StreamHandler flush6614469
Ref: 224a6614469
Ref: library/logging handlers logging StreamHandler setStream6614748
Ref: 4ae6614748
Ref: library/logging handlers logging StreamHandler terminator6615123
Ref: 22496615123
Node: FileHandler6615521
Ref: library/logging handlers file-handler6615650
Ref: 224b6615650
Ref: library/logging handlers filehandler6615650
Ref: 224c6615650
Ref: library/logging handlers logging FileHandler6615868
Ref: 22456615868
Ref: library/logging handlers logging FileHandler close6616645
Ref: 224e6616645
Ref: library/logging handlers logging FileHandler emit6616705
Ref: 224d6616705
Node: NullHandler6616782
Ref: library/logging handlers null-handler6616916
Ref: 224f6616916
Ref: library/logging handlers nullhandler6616916
Ref: 22506616916
Ref: library/logging handlers logging NullHandler6617161
Ref: ce66617161
Ref: library/logging handlers logging NullHandler emit6617256
Ref: 22516617256
Ref: library/logging handlers logging NullHandler handle6617339
Ref: 22526617339
Ref: library/logging handlers logging NullHandler createLock6617424
Ref: 22536617424
Node: WatchedFileHandler6617682
Ref: library/logging handlers watched-file-handler6617824
Ref: 22556617824
Ref: library/logging handlers watchedfilehandler6617824
Ref: 22566617824
Ref: library/logging handlers logging handlers WatchedFileHandler6618838
Ref: 22576618838
Ref: library/logging handlers logging handlers WatchedFileHandler reopenIfNeeded6619638
Ref: 65b6619638
Ref: library/logging handlers logging handlers WatchedFileHandler emit6619892
Ref: 22586619892
Node: BaseRotatingHandler6620069
Ref: library/logging handlers base-rotating-handler6620219
Ref: 22596620219
Ref: library/logging handlers baserotatinghandler6620219
Ref: 225a6620219
Ref: library/logging handlers logging handlers BaseRotatingHandler6620570
Ref: 225b6620570
Ref: library/logging handlers logging handlers BaseRotatingHandler namer6620755
Ref: 225c6620755
Ref: library/logging handlers logging handlers BaseRotatingHandler rotator6622420
Ref: 225f6622420
Ref: library/logging handlers logging handlers BaseRotatingHandler rotation_filename6622699
Ref: 225d6622699
Ref: library/logging handlers logging handlers BaseRotatingHandler rotate6623232
Ref: 22606623232
Node: RotatingFileHandler6624490
Ref: library/logging handlers rotating-file-handler6624646
Ref: 22626624646
Ref: library/logging handlers rotatingfilehandler6624646
Ref: 22636624646
Ref: library/logging handlers logging handlers RotatingFileHandler6624827
Ref: 22366624827
Ref: library/logging handlers logging handlers RotatingFileHandler doRollover6626714
Ref: 22656626714
Ref: library/logging handlers logging handlers RotatingFileHandler emit6626797
Ref: 22646626797
Node: TimedRotatingFileHandler6626910
Ref: library/logging handlers timed-rotating-file-handler6627060
Ref: 22666627060
Ref: library/logging handlers timedrotatingfilehandler6627060
Ref: 22676627060
Ref: library/logging handlers logging handlers TimedRotatingFileHandler6627278
Ref: 9596627278
Ref: library/logging handlers logging handlers TimedRotatingFileHandler doRollover6632026
Ref: 22696632026
Ref: library/logging handlers logging handlers TimedRotatingFileHandler emit6632109
Ref: 22686632109
Ref: library/logging handlers logging handlers TimedRotatingFileHandler getFilesToDelete6632222
Ref: 225e6632222
Node: SocketHandler6632455
Ref: library/logging handlers socket-handler6632601
Ref: 226a6632601
Ref: library/logging handlers sockethandler6632601
Ref: 226b6632601
Ref: library/logging handlers logging handlers SocketHandler6632817
Ref: 95a6632817
Ref: library/logging handlers logging handlers SocketHandler close6633224
Ref: 226c6633224
Ref: library/logging handlers logging handlers SocketHandler emit6633287
Ref: 226d6633287
Ref: library/logging handlers logging handlers SocketHandler handleError6633679
Ref: 226e6633679
Ref: library/logging handlers logging handlers SocketHandler makeSocket6633896
Ref: 226f6633896
Ref: library/logging handlers logging handlers SocketHandler makePickle6634125
Ref: 22706634125
Ref: library/logging handlers logging handlers SocketHandler send6634839
Ref: 22716634839
Ref: library/logging handlers logging handlers SocketHandler createSocket6635120
Ref: 22726635120
Node: DatagramHandler6636143
Ref: library/logging handlers datagram-handler6636278
Ref: 22736636278
Ref: library/logging handlers datagramhandler6636278
Ref: 22746636278
Ref: library/logging handlers logging handlers DatagramHandler6636501
Ref: 95b6636501
Ref: library/logging handlers logging handlers DatagramHandler emit6636912
Ref: 22756636912
Ref: library/logging handlers logging handlers DatagramHandler makeSocket6637246
Ref: 22766637246
Ref: library/logging handlers logging handlers DatagramHandler send6637429
Ref: 22776637429
Node: SysLogHandler6637628
Ref: library/logging handlers syslog-handler6637767
Ref: 22786637767
Ref: library/logging handlers sysloghandler6637767
Ref: 22796637767
Ref: library/logging handlers logging handlers SysLogHandler6637961
Ref: afb6637961
Ref: library/logging handlers logging handlers SysLogHandler close6639625
Ref: 227a6639625
Ref: library/logging handlers logging handlers SysLogHandler emit6639709
Ref: 227b6639709
Ref: library/logging handlers logging handlers SysLogHandler encodePriority6641402
Ref: 227c6641402
Ref: library/logging handlers logging handlers SysLogHandler mapPriority6645401
Ref: 227d6645401
Ref: SysLogHandler-Footnote-16645886
Ref: SysLogHandler-Footnote-26645929
Ref: SysLogHandler-Footnote-36645978
Node: NTEventLogHandler6646021
Ref: library/logging handlers nt-eventlog-handler6646156
Ref: 227e6646156
Ref: library/logging handlers nteventloghandler6646156
Ref: 227f6646156
Ref: library/logging handlers logging handlers NTEventLogHandler6646476
Ref: 22806646476
Ref: library/logging handlers logging handlers NTEventLogHandler close6647430
Ref: 22816647430
Ref: library/logging handlers logging handlers NTEventLogHandler emit6647803
Ref: 22826647803
Ref: library/logging handlers logging handlers NTEventLogHandler getEventCategory6647958
Ref: 22836647958
Ref: library/logging handlers logging handlers NTEventLogHandler getEventType6648149
Ref: 22846648149
Ref: library/logging handlers logging handlers NTEventLogHandler getMessageID6648718
Ref: 22856648718
Node: SMTPHandler6649108
Ref: library/logging handlers smtp-handler6649243
Ref: 22866649243
Ref: library/logging handlers smtphandler6649243
Ref: 22876649243
Ref: library/logging handlers logging handlers SMTPHandler6649441
Ref: 22886649441
Ref: library/logging handlers logging handlers SMTPHandler emit6650612
Ref: 22896650612
Ref: library/logging handlers logging handlers SMTPHandler getSubject6650722
Ref: 228a6650722
Node: MemoryHandler6650853
Ref: library/logging handlers memory-handler6650982
Ref: 228b6650982
Ref: library/logging handlers memoryhandler6650982
Ref: 228c6650982
Ref: library/logging handlers logging handlers BufferingHandler6651645
Ref: 228d6651645
Ref: library/logging handlers logging handlers BufferingHandler emit6651827
Ref: 228e6651827
Ref: library/logging handlers logging handlers BufferingHandler flush6652023
Ref: 22906652023
Ref: library/logging handlers logging handlers BufferingHandler shouldFlush6652176
Ref: 228f6652176
Ref: library/logging handlers logging handlers MemoryHandler6652352
Ref: 223f6652352
Ref: library/logging handlers logging handlers MemoryHandler close6653133
Ref: 22926653133
Ref: library/logging handlers logging handlers MemoryHandler flush6653256
Ref: 22936653256
Ref: library/logging handlers logging handlers MemoryHandler setTarget6653535
Ref: 22916653535
Ref: library/logging handlers logging handlers MemoryHandler shouldFlush6653635
Ref: 22946653635
Node: HTTPHandler6653769
Ref: library/logging handlers http-handler6653899
Ref: 22956653899
Ref: library/logging handlers httphandler6653899
Ref: 22966653899
Ref: library/logging handlers logging handlers HTTPHandler6654112
Ref: 8026654112
Ref: library/logging handlers logging handlers HTTPHandler mapLogRecord6655017
Ref: 22976655017
Ref: library/logging handlers logging handlers HTTPHandler emit6655414
Ref: 22986655414
Node: QueueHandler6656135
Ref: library/logging handlers queue-handler6656265
Ref: 22996656265
Ref: library/logging handlers queuehandler6656265
Ref: 229a6656265
Ref: library/logging handlers logging handlers QueueHandler6656961
Ref: 229b6656961
Ref: library/logging handlers logging handlers QueueHandler emit6657411
Ref: 229d6657411
Ref: library/logging handlers logging handlers QueueHandler prepare6657866
Ref: 229e6657866
Ref: library/logging handlers logging handlers QueueHandler enqueue6658360
Ref: 229c6658360
Node: QueueListener6658597
Ref: library/logging handlers queue-listener6658707
Ref: 229f6658707
Ref: library/logging handlers queuelistener6658707
Ref: 22a06658707
Ref: library/logging handlers logging handlers QueueListener6659679
Ref: 8036659679
Ref: library/logging handlers logging handlers QueueListener dequeue6660701
Ref: 22a16660701
Ref: library/logging handlers logging handlers QueueListener prepare6660978
Ref: 22a26660978
Ref: library/logging handlers logging handlers QueueListener handle6661290
Ref: 22a36661290
Ref: library/logging handlers logging handlers QueueListener start6661552
Ref: 22a46661552
Ref: library/logging handlers logging handlers QueueListener stop6661705
Ref: 22a56661705
Ref: library/logging handlers logging handlers QueueListener enqueue_sentinel6662018
Ref: 22a66662018
Node: getpass --- 便携式密码输入工具6662485
Ref: library/getpass doc6662686
Ref: 22a76662686
Ref: library/getpass getpass-portable-password-input6662686
Ref: 22a86662686
Ref: library/getpass module-getpass6662686
Ref: 866662686
Ref: library/getpass getpass getpass6662929
Ref: 22a96662929
Ref: library/getpass getpass GetPassWarning6663735
Ref: 22aa6663735
Ref: library/getpass getpass getuser6663861
Ref: 204f6663861
Ref: getpass --- 便携式密码输入工具-Footnote-16664382
Node: curses --- 终端字符单元显示的处理6664448
Ref: library/curses doc6664670
Ref: 22ab6664670
Ref: library/curses curses-terminal-handling-for-character-cell-displays6664670
Ref: 22ac6664670
Ref: library/curses module-curses6664670
Ref: 2b6664670
Ref: curses --- 终端字符单元显示的处理-Footnote-16666742
Node: 函数<4>6666805
Ref: library/curses curses-functions6666917
Ref: 22ae6666917
Ref: library/curses functions6666917
Ref: 22af6666917
Ref: library/curses curses error6667000
Ref: 22b06667000
Ref: library/curses curses baudrate6667335
Ref: 22b16667335
Ref: library/curses curses beep6667655
Ref: 22b26667655
Ref: library/curses curses can_change_color6667720
Ref: 22b36667720
Ref: library/curses curses cbreak6667851
Ref: 22b46667851
Ref: library/curses curses color_content6668317
Ref: 22b66668317
Ref: library/curses curses color_pair6668667
Ref: 22b76668667
Ref: library/curses curses curs_set6668976
Ref: 22b96668976
Ref: library/curses curses def_prog_mode6669371
Ref: 22ba6669371
Ref: library/curses curses def_shell_mode6669669
Ref: 22bc6669669
Ref: library/curses curses delay_output6669969
Ref: 22be6669969
Ref: library/curses curses doupdate6670056
Ref: 22bf6670056
Ref: library/curses curses echo6670781
Ref: 22c36670781
Ref: library/curses curses endwin6670925
Ref: 22c46670925
Ref: library/curses curses erasechar6671016
Ref: 22c56671016
Ref: library/curses curses filter6671261
Ref: 22c66671261
Ref: library/curses curses flash6671827
Ref: 22c86671827
Ref: library/curses curses flushinp6672069
Ref: 22c96672069
Ref: library/curses curses getmouse6672226
Ref: 22ca6672226
Ref: library/curses curses getsyx6673001
Ref: 22cc6673001
Ref: library/curses curses getwin6673193
Ref: 22ce6673193
Ref: library/curses curses has_colors6673422
Ref: 22cf6673422
Ref: library/curses curses has_ic6673540
Ref: 22d06673540
Ref: library/curses curses has_il6673769
Ref: 22d16673769
Ref: library/curses curses has_key6674055
Ref: 22d26674055
Ref: library/curses curses halfdelay6674203
Ref: 22d36674203
Ref: library/curses curses init_color6674605
Ref: 22d56674605
Ref: library/curses curses init_pair6675201
Ref: 22d66675201
Ref: library/curses curses initscr6675846
Ref: 22c76675846
Ref: library/curses curses is_term_resized6676080
Ref: 22d96676080
Ref: library/curses curses isendwin6676250
Ref: 22db6676250
Ref: library/curses curses keyname6676403
Ref: 22dc6676403
Ref: library/curses curses killchar6676865
Ref: 22dd6676865
Ref: library/curses curses longname6677112
Ref: 22de6677112
Ref: library/curses curses meta6677366
Ref: 22df6677366
Ref: library/curses curses mouseinterval6677549
Ref: 22e06677549
Ref: library/curses curses mousemask6677793
Ref: 22e16677793
Ref: library/curses curses napms6678176
Ref: 22e26678176
Ref: library/curses curses newpad6678235
Ref: 22e36678235
Ref: library/curses curses newwin6679132
Ref: 22e46679132
Ref: library/curses curses nl6679460
Ref: 22e56679460
Ref: library/curses curses nocbreak6679671
Ref: 22d46679671
Ref: library/curses curses noecho6679783
Ref: 22e66679783
Ref: library/curses curses nonl6679872
Ref: 22e76679872
Ref: library/curses curses noqiflush6680305
Ref: 22e86680305
Ref: library/curses curses noraw6680686
Ref: 22e96680686
Ref: library/curses curses pair_content6680792
Ref: 22ea6680792
Ref: library/curses curses pair_number6680992
Ref: 22b86680992
Ref: library/curses curses putp6681162
Ref: 22eb6681162
Ref: library/curses curses qiflush6681366
Ref: 22ec6681366
Ref: library/curses curses raw6681612
Ref: 22b56681612
Ref: library/curses curses reset_prog_mode6681836
Ref: 22bb6681836
Ref: library/curses curses reset_shell_mode6681988
Ref: 22bd6681988
Ref: library/curses curses resetty6682141
Ref: 22ed6682141
Ref: library/curses curses resize_term6682260
Ref: 22da6682260
Ref: library/curses curses resizeterm6682755
Ref: 22ef6682755
Ref: library/curses curses savetty6682995
Ref: 22ee6682995
Ref: library/curses curses get_escdelay6683132
Ref: 1986683132
Ref: library/curses curses set_escdelay6683254
Ref: 1996683254
Ref: library/curses curses get_tabsize6683485
Ref: 19a6683485
Ref: library/curses curses set_tabsize6683605
Ref: 19b6683605
Ref: library/curses curses setsyx6683779
Ref: 22f06683779
Ref: library/curses curses setupterm6683953
Ref: 22f16683953
Ref: library/curses curses start_color6684329
Ref: 22f26684329
Ref: library/curses curses termattrs6684922
Ref: 22f36684922
Ref: library/curses curses termname6685116
Ref: 22f46685116
Ref: library/curses curses tigetflag6685243
Ref: 22f56685243
Ref: library/curses curses tigetnum6685522
Ref: 22f66685522
Ref: library/curses curses tigetstr6685801
Ref: 22f76685801
Ref: library/curses curses tparm6686096
Ref: 22f86686096
Ref: library/curses curses typeahead6686403
Ref: 22f96686403
Ref: library/curses curses unctrl6686930
Ref: 22fa6686930
Ref: library/curses curses ungetch6687166
Ref: 22fb6687166
Ref: library/curses curses update_lines_cols6687355
Ref: 7b96687355
Ref: library/curses curses unget_wch6687509
Ref: abf6687509
Ref: library/curses curses ungetmouse6687727
Ref: 22fc6687727
Ref: library/curses curses use_env6687882
Ref: 22fd6687882
Ref: library/curses curses use_default_colors6688366
Ref: 22d76688366
Ref: library/curses curses wrapper6688758
Ref: 3c46688758
Node: Window 对象6689558
Ref: library/curses curses-window-objects6689688
Ref: 22d86689688
Ref: library/curses window-objects6689688
Ref: 22fe6689688
Ref: library/curses curses window addch6689856
Ref: 22ff6689856
Ref: library/curses curses window addnstr6690385
Ref: 23006690385
Ref: library/curses curses window addstr6690640
Ref: 22c06690640
Ref: library/curses curses window attroff6691568
Ref: 23016691568
Ref: library/curses curses window attron6691694
Ref: 23026691694
Ref: library/curses curses window attrset6691819
Ref: 23036691819
Ref: library/curses curses window bkgd6691954
Ref: 23046691954
Ref: library/curses curses window bkgdset6692359
Ref: 23056692359
Ref: library/curses curses window border6692780
Ref: 23066692780
Ref: library/curses curses window box6694666
Ref: 23076694666
Ref: library/curses curses window chgat6694878
Ref: 23086694878
Ref: library/curses curses window clear6695459
Ref: 230a6695459
Ref: library/curses curses window clearok6695626
Ref: 230c6695626
Ref: library/curses curses window clrtobot6695780
Ref: 230d6695780
Ref: library/curses curses window clrtoeol6695979
Ref: 230e6695979
Ref: library/curses curses window cursyncup6696066
Ref: 230f6696066
Ref: library/curses curses window delch6696202
Ref: 23106696202
Ref: library/curses curses window deleteln6696294
Ref: 23116696294
Ref: library/curses curses window derwin6696409
Ref: 23126696409
Ref: library/curses curses window echochar6696801
Ref: 23146696801
Ref: library/curses curses window enclose6696954
Ref: 23156696954
Ref: library/curses curses window encoding6697222
Ref: abd6697222
Ref: library/curses curses window erase6697589
Ref: 230b6697589
Ref: library/curses curses window getbegyx6697646
Ref: 23166697646
Ref: library/curses curses window getbkgd6697737
Ref: 23176697737
Ref: library/curses curses window getch6697833
Ref: 22cb6697833
Ref: library/curses curses window get_wch6698169
Ref: abe6698169
Ref: library/curses curses window getkey6698467
Ref: 23186698467
Ref: library/curses curses window getmaxyx6698795
Ref: 23196698795
Ref: library/curses curses window getparyx6698892
Ref: 231a6698892
Ref: library/curses curses window getstr6699081
Ref: 231b6699081
Ref: library/curses curses window getyx6699316
Ref: 231c6699316
Ref: library/curses curses window hline6699434
Ref: 231d6699434
Ref: library/curses curses window idcok6699606
Ref: 231e6699606
Ref: library/curses curses window idlok6699904
Ref: 231f6699904
Ref: library/curses curses window immedok6700084
Ref: 23206700084
Ref: library/curses curses window inch6700393
Ref: 23216700393
Ref: library/curses curses window insch6700564
Ref: 23226700564
Ref: library/curses curses window insdelln6700786
Ref: 23236700786
Ref: library/curses curses window insertln6701142
Ref: 23246701142
Ref: library/curses curses window insnstr6701263
Ref: 23256701263
Ref: library/curses curses window insstr6701725
Ref: 23266701725
Ref: library/curses curses window instr6702090
Ref: 23276702090
Ref: library/curses curses window is_linetouched6702461
Ref: 23286702461
Ref: library/curses curses window is_wintouched6702744
Ref: 23296702744
Ref: library/curses curses window keypad6702927
Ref: 232a6702927
Ref: library/curses curses window leaveok6703201
Ref: 22cd6703201
Ref: library/curses curses window move6703540
Ref: 232b6703540
Ref: library/curses curses window mvderwin6703632
Ref: 232c6703632
Ref: library/curses curses window mvwin6703851
Ref: 232d6703851
Ref: library/curses curses window nodelay6703965
Ref: 232e6703965
Ref: library/curses curses window notimeout6704090
Ref: 232f6704090
Ref: library/curses curses window noutrefresh6704351
Ref: 22c16704351
Ref: library/curses curses window overlay6704590
Ref: 23306704590
Ref: library/curses curses window overwrite6705170
Ref: 23316705170
Ref: library/curses curses window putwin6705753
Ref: 23326705753
Ref: library/curses curses window redrawln6705943
Ref: 23336705943
Ref: library/curses curses window redrawwin6706129
Ref: 23346706129
Ref: library/curses curses window refresh6706262
Ref: 22c26706262
Ref: library/curses curses window resize6707121
Ref: 23356707121
Ref: library/curses curses window scroll6707431
Ref: 23366707431
Ref: library/curses curses window scrollok6707534
Ref: 23376707534
Ref: library/curses curses window setscrreg6708016
Ref: 23386708016
Ref: library/curses curses window standend6708178
Ref: 23396708178
Ref: library/curses curses window standout6708315
Ref: 233a6708315
Ref: library/curses curses window subpad6708388
Ref: 233b6708388
Ref: library/curses curses window subwin6708635
Ref: 23136708635
Ref: library/curses curses window syncdown6708964
Ref: 233c6708964
Ref: library/curses curses window syncok6709153
Ref: 233d6709153
Ref: library/curses curses window syncup6709320
Ref: 233e6709320
Ref: library/curses curses window timeout6709447
Ref: 233f6709447
Ref: library/curses curses window touchline6709929
Ref: 23096709929
Ref: library/curses curses window touchwin6710212
Ref: 23406710212
Ref: library/curses curses window untouchwin6710323
Ref: 23416710323
Ref: library/curses curses window vline6710466
Ref: 23426710466
Ref: Window 对象-Footnote-16710674
Node: 常量<2>6710717
Ref: library/curses constants6710829
Ref: 23436710829
Ref: library/curses curses ERR6710916
Ref: 23446710916
Ref: library/curses curses OK6711060
Ref: 23456711060
Ref: library/curses curses version6711202
Ref: 23466711202
Ref: library/curses curses ncurses_version6711314
Ref: 2f06711314
Node: curses textpad --- 用于 curses 程序的文本输入控件6729320
Ref: library/curses curses-textpad-text-input-widget-for-curses-programs6729548
Ref: 23476729548
Ref: library/curses module-curses textpad6729548
Ref: 2e6729548
Ref: library/curses curses textpad rectangle6730102
Ref: 23496730102
Node: 文本框对象6730691
Ref: library/curses curses-textpad-objects6730803
Ref: 234a6730803
Ref: library/curses textbox-objects6730803
Ref: 234b6730803
Ref: library/curses curses textpad Textbox6730917
Ref: 23486730917
Ref: library/curses curses textpad Textbox edit6731331
Ref: 234d6731331
Ref: library/curses curses textpad Textbox do_command6731831
Ref: 234e6731831
Ref: library/curses curses textpad Textbox gather6735137
Ref: 234f6735137
Ref: library/curses curses textpad Textbox stripspaces6735315
Ref: 234c6735315
Node: curses ascii --- 用于 ASCII 字符的工具6735629
Ref: library/curses ascii doc6735855
Ref: 23506735855
Ref: library/curses ascii curses-ascii-utilities-for-ascii-characters6735855
Ref: 23516735855
Ref: library/curses ascii module-curses ascii6735855
Ref: 2c6735855
Ref: library/curses ascii curses ascii isalnum6739390
Ref: 23526739390
Ref: library/curses ascii curses ascii isalpha6739519
Ref: 23536739519
Ref: library/curses ascii curses ascii isascii6739641
Ref: 23546739641
Ref: library/curses ascii curses ascii isblank6739738
Ref: 23556739738
Ref: library/curses ascii curses ascii iscntrl6739844
Ref: 23566739844
Ref: library/curses ascii curses ascii isdigit6739959
Ref: 23576739959
Ref: library/curses ascii curses ascii isgraph6740111
Ref: 23586740111
Ref: library/curses ascii curses ascii islower6740214
Ref: 23596740214
Ref: library/curses ascii curses ascii isprint6740293
Ref: 235a6740293
Ref: library/curses ascii curses ascii ispunct6740393
Ref: 235b6740393
Ref: library/curses ascii curses ascii isspace6740520
Ref: 235c6740520
Ref: library/curses ascii curses ascii isupper6740671
Ref: 235d6740671
Ref: library/curses ascii curses ascii isxdigit6740750
Ref: 235e6740750
Ref: library/curses ascii curses ascii isctrl6740874
Ref: 235f6740874
Ref: library/curses ascii curses ascii ismeta6740970
Ref: 23606740970
Ref: library/curses ascii curses ascii ascii6741480
Ref: 23616741480
Ref: library/curses ascii curses ascii ctrl6741580
Ref: 23626741580
Ref: library/curses ascii curses ascii alt6741727
Ref: 23636741727
Ref: library/curses ascii curses ascii unctrl6741969
Ref: 23646741969
Ref: library/curses ascii curses ascii controlnames6742476
Ref: 23656742476
Node: curses panel --- curses 的面板栈扩展6742708
Ref: library/curses panel doc6742920
Ref: 23666742920
Ref: library/curses panel curses-panel-a-panel-stack-extension-for-curses6742920
Ref: 23676742920
Ref: library/curses panel module-curses panel6742920
Ref: 2d6742920
Node: 函数<5>6743363
Ref: library/curses panel cursespanel-functions6743472
Ref: 23686743472
Ref: library/curses panel functions6743472
Ref: 23696743472
Ref: library/curses panel curses panel bottom_panel6743559
Ref: 236a6743559
Ref: library/curses panel curses panel new_panel6743644
Ref: 236b6743644
Ref: library/curses panel curses panel top_panel6743921
Ref: 236c6743921
Ref: library/curses panel curses panel update_panels6744003
Ref: 236d6744003
Node: Panel 对象6744195
Ref: library/curses panel curses-panel-objects6744304
Ref: 236e6744304
Ref: library/curses panel panel-objects6744304
Ref: 236f6744304
Ref: library/curses panel curses panel Panel above6744608
Ref: 23706744608
Ref: library/curses panel curses panel Panel below6744685
Ref: 23716744685
Ref: library/curses panel curses panel Panel bottom6744762
Ref: 23726744762
Ref: library/curses panel curses panel Panel hidden6744831
Ref: 23736744831
Ref: library/curses panel curses panel Panel hide6744959
Ref: 23746744959
Ref: library/curses panel curses panel Panel move6745081
Ref: 23756745081
Ref: library/curses panel curses panel Panel replace6745168
Ref: 23766745168
Ref: library/curses panel curses panel Panel set_userptr6745265
Ref: 23776745265
Ref: library/curses panel curses panel Panel show6745447
Ref: 23786745447
Ref: library/curses panel curses panel Panel top6745532
Ref: 23796745532
Ref: library/curses panel curses panel Panel userptr6745598
Ref: 237a6745598
Ref: library/curses panel curses panel Panel window6745707
Ref: 237b6745707
Node: platform --- 获取底层平台的标识数据6745791
Ref: library/platform doc6745993
Ref: 237c6745993
Ref: library/platform module-platform6745993
Ref: ce6745993
Ref: library/platform platform-access-to-underlying-platform-s-identifying-data6745993
Ref: 237d6745993
Ref: platform --- 获取底层平台的标识数据-Footnote-16746417
Node: 跨平台6746484
Ref: library/platform cross-platform6746595
Ref: 237e6746595
Ref: library/platform platform architecture6746633
Ref: 114e6746633
Ref: library/platform platform machine6747852
Ref: 237f6747852
Ref: library/platform platform node6747999
Ref: 23806747999
Ref: library/platform platform platform6748172
Ref: 11536748172
Ref: library/platform platform processor6748993
Ref: 23826748993
Ref: library/platform platform python_build6749305
Ref: 23836749305
Ref: library/platform platform python_compiler6749457
Ref: 23846749457
Ref: library/platform platform python_branch6749573
Ref: 23856749573
Ref: library/platform platform python_implementation6749680
Ref: 23866749680
Ref: library/platform platform python_revision6749870
Ref: 23876749870
Ref: library/platform platform python_version6749982
Ref: 23886749982
Ref: library/platform platform python_version_tuple6750221
Ref: 23896750221
Ref: library/platform platform release6750482
Ref: 238a6750482
Ref: library/platform platform system6750653
Ref: 238b6750653
Ref: library/platform platform system_alias6750858
Ref: 23816750858
Ref: library/platform platform version6751110
Ref: 238c6751110
Ref: library/platform platform uname6751279
Ref: 11516751279
Node: Java平台6751939
Ref: library/platform java-platform6752072
Ref: 238d6752072
Ref: library/platform platform java_ver6752113
Ref: 238e6752113
Node: Windows平台6752546
Ref: library/platform windows-platform6752684
Ref: 238f6752684
Ref: library/platform platform win32_ver6752731
Ref: 10406752731
Ref: library/platform platform win32_edition6753377
Ref: 23906753377
Ref: library/platform platform win32_is_iot6753622
Ref: 23916753622
Node: macOS Platform6753800
Ref: library/platform macos-platform6753939
Ref: 23926753939
Ref: library/platform platform mac_ver6753990
Ref: 11546753990
Node: Unix 平台6754359
Ref: library/platform unix-platforms6754476
Ref: 23936754476
Ref: library/platform platform libc_ver6754519
Ref: 11506754519
Node: errno --- 标准 errno 系统符号6755099
Ref: library/errno doc6755295
Ref: 23946755295
Ref: library/errno errno-standard-errno-system-symbols6755295
Ref: 23956755295
Ref: library/errno module-errno6755295
Ref: 7a6755295
Ref: library/errno errno errorcode6755640
Ref: 23966755640
Ref: library/errno errno EPERM6756112
Ref: 23976756112
Ref: library/errno errno ENOENT6756160
Ref: 23986756160
Ref: library/errno errno ESRCH6756212
Ref: 23996756212
Ref: library/errno errno EINTR6756254
Ref: 74b6756254
Ref: library/errno errno EIO6756399
Ref: 239a6756399
Ref: library/errno errno ENXIO6756437
Ref: 239b6756437
Ref: library/errno errno E2BIG6756488
Ref: 239c6756488
Ref: library/errno errno ENOEXEC6756536
Ref: 239d6756536
Ref: library/errno errno EBADF6756586
Ref: 22f6756586
Ref: library/errno errno ECHILD6756634
Ref: 239e6756634
Ref: library/errno errno EAGAIN6756680
Ref: 20956756680
Ref: library/errno errno ENOMEM6756717
Ref: 239f6756717
Ref: library/errno errno EACCES6756760
Ref: 23a06756760
Ref: library/errno errno EFAULT6756803
Ref: 23a16756803
Ref: library/errno errno ENOTBLK6756849
Ref: 23a26756849
Ref: library/errno errno EBUSY6756896
Ref: 23a36756896
Ref: library/errno errno EEXIST6756944
Ref: 23a46756944
Ref: library/errno errno EXDEV6756990
Ref: 206d6756990
Ref: library/errno errno ENODEV6757035
Ref: 23a56757035
Ref: library/errno errno ENOTDIR6757078
Ref: 23a66757078
Ref: library/errno errno EISDIR6757122
Ref: 23a76757122
Ref: library/errno errno EINVAL6757162
Ref: 11046757162
Ref: library/errno errno ENFILE6757208
Ref: 23a86757208
Ref: library/errno errno EMFILE6757254
Ref: 23a96757254
Ref: library/errno errno ENOTTY6757306
Ref: 23aa6757306
Ref: library/errno errno ETXTBSY6757352
Ref: 23ab6757352
Ref: library/errno errno EFBIG6757399
Ref: 23ac6757399
Ref: library/errno errno ENOSPC6757441
Ref: 23ad6757441
Ref: library/errno errno ESPIPE6757496
Ref: 23ae6757496
Ref: library/errno errno EROFS6757539
Ref: 23af6757539
Ref: library/errno errno EMLINK6757587
Ref: 23b06757587
Ref: library/errno errno EPIPE6757630
Ref: 23b16757630
Ref: library/errno errno EDOM6757675
Ref: 23b26757675
Ref: library/errno errno ERANGE6757734
Ref: 23b36757734
Ref: library/errno errno EDEADLK6757795
Ref: 23b46757795
Ref: library/errno errno ENAMETOOLONG6757848
Ref: 23b56757848
Ref: library/errno errno ENOLCK6757900
Ref: 23b66757900
Ref: library/errno errno ENOSYS6757955
Ref: 23b76757955
Ref: library/errno errno ENOTEMPTY6758001
Ref: 23b86758001
Ref: library/errno errno ELOOP6758047
Ref: 23b96758047
Ref: library/errno errno EWOULDBLOCK6758104
Ref: 23ba6758104
Ref: library/errno errno ENOMSG6758155
Ref: 23bb6758155
Ref: library/errno errno EIDRM6758213
Ref: 23bc6758213
Ref: library/errno errno ECHRNG6758261
Ref: 23bd6758261
Ref: library/errno errno EL2NSYNC6758316
Ref: 23be6758316
Ref: library/errno errno EL3HLT6758367
Ref: 23bf6758367
Ref: library/errno errno EL3RST6758416
Ref: 23c06758416
Ref: library/errno errno ELNRNG6758462
Ref: 23c16758462
Ref: library/errno errno EUNATCH6758517
Ref: 23c26758517
Ref: library/errno errno ENOCSI6758570
Ref: 23c36758570
Ref: library/errno errno EL2HLT6758627
Ref: 23c46758627
Ref: library/errno errno EBADE6758676
Ref: 23c56758676
Ref: library/errno errno EBADR6758721
Ref: 23c66758721
Ref: library/errno errno EXFULL6758775
Ref: 23c76758775
Ref: library/errno errno ENOANO6758818
Ref: 23c86758818
Ref: library/errno errno EBADRQC6758861
Ref: 23c96758861
Ref: library/errno errno EBADSLT6758913
Ref: 23ca6758913
Ref: library/errno errno EDEADLOCK6758960
Ref: 23cb6758960
Ref: library/errno errno EBFONT6759018
Ref: 23cc6759018
Ref: library/errno errno ENOSTR6759076
Ref: 23cd6759076
Ref: library/errno errno ENODATA6759122
Ref: 23ce6759122
Ref: library/errno errno ETIME6759175
Ref: 23cf6759175
Ref: library/errno errno ENOSR6759223
Ref: 23d06759223
Ref: library/errno errno ENONET6759268
Ref: 23d16759268
Ref: library/errno errno ENOPKG6759320
Ref: 23d26759320
Ref: library/errno errno EREMOTE6759363
Ref: 23d36759363
Ref: library/errno errno ENOLINK6759413
Ref: 23d46759413
Ref: library/errno errno EADV6759463
Ref: 23d56759463
Ref: library/errno errno ESRMNT6759504
Ref: 23d66759504
Ref: library/errno errno ECOMM6759547
Ref: 23d76759547
Ref: library/errno errno EPROTO6759598
Ref: 23d86759598
Ref: library/errno errno EMULTIHOP6759641
Ref: 23d96759641
Ref: library/errno errno EDOTDOT6759690
Ref: 23da6759690
Ref: library/errno errno EBADMSG6759738
Ref: 23db6759738
Ref: library/errno errno EOVERFLOW6759785
Ref: 23dc6759785
Ref: library/errno errno ENOTUNIQ6759858
Ref: 23dd6759858
Ref: library/errno errno EBADFD6759918
Ref: 23de6759918
Ref: library/errno errno EREMCHG6759982
Ref: 23df6759982
Ref: library/errno errno ELIBACC6760035
Ref: 23e06760035
Ref: library/errno errno ELIBBAD6760097
Ref: 23e16760097
Ref: library/errno errno ELIBSCN6760156
Ref: 23e26760156
Ref: library/errno errno ELIBMAX6760221
Ref: 23e36760221
Ref: library/errno errno ELIBEXEC6760283
Ref: 23e46760283
Ref: library/errno errno EILSEQ6760343
Ref: 23e56760343
Ref: library/errno errno ERESTART6760392
Ref: 23e66760392
Ref: library/errno errno ESTRPIPE6760458
Ref: 23e76760458
Ref: library/errno errno EUSERS6760506
Ref: 23e86760506
Ref: library/errno errno ENOTSOCK6760549
Ref: 23e96760549
Ref: library/errno errno EDESTADDRREQ6760621
Ref: 23ea6760621
Ref: library/errno errno EMSGSIZE6760676
Ref: 23eb6760676
Ref: library/errno errno EPROTOTYPE6760721
Ref: 23ec6760721
Ref: library/errno errno ENOPROTOOPT6760786
Ref: 23ed6760786
Ref: library/errno errno EPROTONOSUPPORT6760837
Ref: 23ee6760837
Ref: library/errno errno ESOCKTNOSUPPORT6760895
Ref: 23ef6760895
Ref: library/errno errno EOPNOTSUPP6760962
Ref: 23f06760962
Ref: library/errno errno EPFNOSUPPORT6761033
Ref: 23f16761033
Ref: library/errno errno EAFNOSUPPORT6761091
Ref: 23f26761091
Ref: library/errno errno EADDRINUSE6761155
Ref: 23f36761155
Ref: library/errno errno EADDRNOTAVAIL6761208
Ref: 23f46761208
Ref: library/errno errno ENETDOWN6761273
Ref: 23f56761273
Ref: library/errno errno ENETUNREACH6761321
Ref: 111f6761321
Ref: library/errno errno ENETRESET6761372
Ref: 23f66761372
Ref: library/errno errno ECONNABORTED6761436
Ref: 23f76761436
Ref: library/errno errno ECONNRESET6761497
Ref: 23f86761497
Ref: library/errno errno ENOBUFS6761553
Ref: 23f96761553
Ref: library/errno errno EISCONN6761615
Ref: 23fa6761615
Ref: library/errno errno ENOTCONN6761668
Ref: 23fb6761668
Ref: library/errno errno ESHUTDOWN6761722
Ref: 23fc6761722
Ref: library/errno errno ETOOMANYREFS6761789
Ref: 23fd6761789
Ref: library/errno errno ETIMEDOUT6761853
Ref: 23fe6761853
Ref: library/errno errno ECONNREFUSED6761899
Ref: 23ff6761899
Ref: library/errno errno EHOSTDOWN6761948
Ref: 24006761948
Ref: library/errno errno EHOSTUNREACH6761997
Ref: 24016761997
Ref: library/errno errno EALREADY6762058
Ref: 24026762058
Ref: library/errno errno EINPROGRESS6762109
Ref: 24036762109
Ref: library/errno errno ESTALE6762163
Ref: 24046762163
Ref: library/errno errno EUCLEAN6762220
Ref: 24056762220
Ref: library/errno errno ENOTNAM6762270
Ref: 24066762270
Ref: library/errno errno ENAVAIL6762333
Ref: 24076762333
Ref: library/errno errno EISNAM6762393
Ref: 24086762393
Ref: library/errno errno EREMOTEIO6762445
Ref: 24096762445
Ref: library/errno errno EDQUOT6762496
Ref: 240a6762496
Node: ctypes --- Python 的外部函数库6762539
Ref: library/ctypes doc6762680
Ref: 240b6762680
Ref: library/ctypes ctypes-a-foreign-function-library-for-python6762680
Ref: 240c6762680
Ref: library/ctypes module-ctypes6762680
Ref: 2a6762680
Node: ctypes 教程6763099
Ref: library/ctypes ctypes-ctypes-tutorial6763213
Ref: 240d6763213
Ref: library/ctypes ctypes-tutorial6763213
Ref: 240e6763213
Node: 载入动态连接库6764407
Ref: library/ctypes ctypes-loading-dynamic-link-libraries6764529
Ref: 24116764529
Ref: library/ctypes loading-dynamic-link-libraries6764529
Ref: 24126764529
Node: 操作导入的动态链接库中的函数6766440
Ref: library/ctypes accessing-functions-from-loaded-dlls6766583
Ref: 24136766583
Ref: library/ctypes ctypes-accessing-functions-from-loaded-dlls6766583
Ref: 24146766583
Node: 调用函数6768847
Ref: library/ctypes calling-functions6768987
Ref: 24156768987
Ref: library/ctypes ctypes-calling-functions6768987
Ref: 24166768987
Node: 基础数据类型6771394
Ref: library/ctypes ctypes-fundamental-data-types6771513
Ref: 24176771513
Ref: library/ctypes fundamental-data-types6771513
Ref: 24186771513
Node: 调用函数，继续6779479
Ref: library/ctypes calling-functions-continued6779628
Ref: 24296779628
Ref: library/ctypes ctypes-calling-functions-continued6779628
Ref: 242a6779628
Node: 使用自定义的数据类型调用函数6780708
Ref: library/ctypes calling-functions-with-your-own-custom-data-types6780879
Ref: 242b6780879
Ref: library/ctypes ctypes-calling-functions-with-own-custom-data-types6780879
Ref: 242c6780879
Node: 指定必选参数的类型 函数原型6781620
Ref: library/ctypes ctypes-specifying-required-argument-types6781782
Ref: 242d6781782
Ref: library/ctypes specifying-the-required-argument-types-function-prototypes6781782
Ref: 242e6781782
Node: 返回类型6783445
Ref: library/ctypes ctypes-return-types6783613
Ref: 242f6783613
Ref: library/ctypes return-types6783613
Ref: 24306783613
Node: 传递指针（或以引用方式传递形参）6786158
Ref: library/ctypes ctypes-passing-pointers6786304
Ref: 24326786304
Ref: library/ctypes passing-pointers-or-passing-parameters-by-reference6786304
Ref: 24336786304
Node: 结构体和联合6787344
Ref: library/ctypes ctypes-structures-unions6787521
Ref: 24366787521
Ref: library/ctypes structures-and-unions6787521
Ref: 24376787521
Ref: library/ctypes ctypes-structureunion-alignment-byte-order6789490
Ref: 243a6789490
Node: 结构体/联合字段对齐及字节顺序6789787
Ref: library/ctypes structure-union-alignment-and-byte-order6789946
Ref: 243b6789946
Node: 结构体和联合中的位域6790633
Ref: library/ctypes bit-fields-in-structures-and-unions6790780
Ref: 243e6790780
Ref: library/ctypes ctypes-bit-fields-in-structures-unions6790780
Ref: 243f6790780
Node: 数组6791300
Ref: library/ctypes arrays6791410
Ref: 24406791410
Ref: library/ctypes ctypes-arrays6791410
Ref: 24416791410
Node: 指针6792619
Ref: library/ctypes ctypes-pointers6792711
Ref: 24426792711
Ref: library/ctypes pointers6792711
Ref: 24436792711
Node: 类型转换6795282
Ref: library/ctypes ctypes-type-conversions6795383
Ref: 24466795383
Ref: library/ctypes type-conversions6795383
Ref: 24476795383
Node: 不完整类型6797819
Ref: library/ctypes ctypes-incomplete-types6797926
Ref: 24486797926
Ref: library/ctypes incomplete-types6797926
Ref: 24496797926
Node: 回调函数6799470
Ref: library/ctypes callback-functions6799591
Ref: 244a6799591
Ref: library/ctypes ctypes-callback-functions6799591
Ref: 244b6799591
Node: 访问 dll 的导出变量6803155
Ref: library/ctypes accessing-values-exported-from-dlls6803267
Ref: 244f6803267
Ref: library/ctypes ctypes-accessing-values-exported-from-dlls6803267
Ref: 24506803267
Node: 意外6805874
Ref: library/ctypes ctypes-surprises6805992
Ref: 24536805992
Ref: library/ctypes surprises6805992
Ref: 24546805992
Node: 变长数据类型6807984
Ref: library/ctypes ctypes-variable-sized-data-types6808067
Ref: 24556808067
Ref: library/ctypes variable-sized-data-types6808067
Ref: 24566808067
Node: ctypes 参考手册6809420
Ref: library/ctypes ctypes-ctypes-reference6809534
Ref: 24586809534
Ref: library/ctypes ctypes-reference6809534
Ref: 24596809534
Node: 寻找动态链接库6809830
Ref: library/ctypes ctypes-finding-shared-libraries6809937
Ref: 245a6809937
Ref: library/ctypes finding-shared-libraries6809937
Ref: 245b6809937
Node: 加载动态链接库6812259
Ref: library/ctypes ctypes-loading-shared-libraries6812387
Ref: 245c6812387
Ref: library/ctypes loading-shared-libraries6812387
Ref: 245d6812387
Ref: library/ctypes ctypes CDLL6812564
Ref: 2f26812564
Ref: library/ctypes ctypes OleDLL6813515
Ref: 245e6813515
Ref: library/ctypes ctypes WinDLL6814102
Ref: 24606814102
Ref: library/ctypes ctypes PyDLL6814699
Ref: 24616814699
Ref: library/ctypes ctypes PyDLL _handle6818023
Ref: 24666818023
Ref: library/ctypes ctypes PyDLL _name6818090
Ref: 24676818090
Ref: library/ctypes ctypes LibraryLoader6818396
Ref: 24686818396
Ref: library/ctypes ctypes LibraryLoader LoadLibrary6818842
Ref: 24696818842
Ref: 加载动态链接库-Footnote-16820031
Node: 外部函数6820097
Ref: library/ctypes ctypes-foreign-functions6820216
Ref: 246a6820216
Ref: library/ctypes foreign-functions6820216
Ref: 246b6820216
Ref: library/ctypes ctypes _FuncPtr6820564
Ref: 246c6820564
Ref: library/ctypes ctypes _FuncPtr restype6820808
Ref: 246d6820808
Ref: library/ctypes ctypes _FuncPtr argtypes6821476
Ref: 246f6821476
Ref: library/ctypes ctypes _FuncPtr errcheck6822549
Ref: 246e6822549
Ref: library/ctypes ctypes ArgumentError6823379
Ref: 24706823379
Node: 函数原型6823691
Ref: library/ctypes ctypes-function-prototypes6823801
Ref: 24716823801
Ref: library/ctypes function-prototypes6823801
Ref: 24726823801
Ref: library/ctypes ctypes CFUNCTYPE6824314
Ref: 244c6824314
Ref: library/ctypes ctypes WINFUNCTYPE6824781
Ref: 244d6824781
Ref: library/ctypes ctypes PYFUNCTYPE6825207
Ref: 24736825207
Node: 工具函数6830253
Ref: library/ctypes ctypes-utility-functions6830366
Ref: 24746830366
Ref: library/ctypes utility-functions6830366
Ref: 24756830366
Ref: library/ctypes ctypes addressof6830411
Ref: 24766830411
Ref: library/ctypes ctypes alignment6830642
Ref: 24776830642
Ref: library/ctypes ctypes byref6830799
Ref: 24346830799
Ref: library/ctypes ctypes cast6831265
Ref: 114b6831265
Ref: library/ctypes ctypes create_string_buffer6831547
Ref: 24286831547
Ref: library/ctypes ctypes create_unicode_buffer6832299
Ref: 10d76832299
Ref: library/ctypes ctypes DllCanUnloadNow6833051
Ref: 24786833051
Ref: library/ctypes ctypes DllGetClassObject6833273
Ref: 24796833273
Ref: library/ctypes ctypes util find_library6833511
Ref: 7016833511
Ref: library/ctypes ctypes util find_msvcrt6833879
Ref: 247a6833879
Ref: library/ctypes ctypes FormatError6834267
Ref: 247b6834267
Ref: library/ctypes ctypes GetLastError6834488
Ref: 24316834488
Ref: library/ctypes ctypes get_errno6834734
Ref: 24626834734
Ref: library/ctypes ctypes get_last_error6834963
Ref: 24646834963
Ref: library/ctypes ctypes memmove6835224
Ref: 247c6835224
Ref: library/ctypes ctypes memset6835445
Ref: 247d6835445
Ref: library/ctypes ctypes POINTER6835670
Ref: 24456835670
Ref: library/ctypes ctypes pointer6835914
Ref: 24356835914
Ref: library/ctypes ctypes resize6836212
Ref: 24576836212
Ref: library/ctypes ctypes set_errno6836523
Ref: 24636836523
Ref: library/ctypes ctypes set_last_error6836791
Ref: 24656836791
Ref: library/ctypes ctypes sizeof6837092
Ref: 247e6837092
Ref: library/ctypes ctypes string_at6837266
Ref: 247f6837266
Ref: library/ctypes ctypes WinError6837620
Ref: 24806837620
Ref: library/ctypes ctypes wstring_at6838076
Ref: 24816838076
Node: 数据类型<2>6838467
Ref: library/ctypes ctypes-data-types6838589
Ref: 24826838589
Ref: library/ctypes data-types6838589
Ref: 24836838589
Ref: library/ctypes ctypes _CData6838634
Ref: 11e56838634
Ref: library/ctypes ctypes _CData from_buffer6839210
Ref: 24856839210
Ref: library/ctypes ctypes _CData from_buffer_copy6839735
Ref: 24866839735
Ref: library/ctypes ctypes _CData from_address6840255
Ref: 24876840255
Ref: library/ctypes ctypes _CData from_param6840553
Ref: 24886840553
Ref: library/ctypes ctypes _CData in_dll6841089
Ref: 24896841089
Ref: library/ctypes ctypes _CData _b_base_6841344
Ref: 248a6841344
Ref: library/ctypes ctypes _CData _b_needsfree_6841606
Ref: 248b6841606
Ref: library/ctypes ctypes _CData _objects6841762
Ref: 24846841762
Node: 基础数据类型<2>6842056
Ref: library/ctypes ctypes-fundamental-data-types-26842187
Ref: 248c6842187
Ref: library/ctypes id16842187
Ref: 248d6842187
Ref: library/ctypes ctypes _SimpleCData6842242
Ref: 248e6842242
Ref: library/ctypes ctypes _SimpleCData value6842657
Ref: 248f6842657
Ref: library/ctypes ctypes c_byte6843909
Ref: 241c6843909
Ref: library/ctypes ctypes c_char6844109
Ref: 241a6844109
Ref: library/ctypes ctypes c_char_p6844323
Ref: 24266844323
Ref: library/ctypes ctypes c_double6844630
Ref: fc46844630
Ref: library/ctypes ctypes c_longdouble6844761
Ref: fc56844761
Ref: library/ctypes ctypes c_float6845019
Ref: 24256845019
Ref: library/ctypes ctypes c_int6845148
Ref: 240f6845148
Ref: library/ctypes ctypes c_int86845411
Ref: 24906845411
Ref: library/ctypes ctypes c_int166845547
Ref: 24916845547
Ref: library/ctypes ctypes c_int326845686
Ref: 24926845686
Ref: library/ctypes ctypes c_int646845823
Ref: 24936845823
Ref: library/ctypes ctypes c_long6845964
Ref: 24106845964
Ref: library/ctypes ctypes c_longlong6846128
Ref: 24226846128
Ref: library/ctypes ctypes c_short6846301
Ref: 241e6846301
Ref: library/ctypes ctypes c_size_t6846467
Ref: 24246846467
Ref: library/ctypes ctypes c_ssize_t6846540
Ref: c9f6846540
Ref: library/ctypes ctypes c_ubyte6846639
Ref: 241d6846639
Ref: library/ctypes ctypes c_uint6846842
Ref: 24206846842
Ref: library/ctypes ctypes c_uint86847109
Ref: 24946847109
Ref: library/ctypes ctypes c_uint166847249
Ref: 24956847249
Ref: library/ctypes ctypes c_uint326847391
Ref: 24966847391
Ref: library/ctypes ctypes c_uint646847532
Ref: 24976847532
Ref: library/ctypes ctypes c_ulong6847677
Ref: 24216847677
Ref: library/ctypes ctypes c_ulonglong6847844
Ref: 24236847844
Ref: library/ctypes ctypes c_ushort6848020
Ref: 241f6848020
Ref: library/ctypes ctypes c_void_p6848189
Ref: 24276848189
Ref: library/ctypes ctypes c_wchar6848351
Ref: 241b6848351
Ref: library/ctypes ctypes c_wchar_p6848599
Ref: fa96848599
Ref: library/ctypes ctypes c_bool6848806
Ref: 24196848806
Ref: library/ctypes ctypes HRESULT6849023
Ref: 245f6849023
Ref: library/ctypes ctypes py_object6849177
Ref: 24986849177
Node: 结构化数据类型6849565
Ref: library/ctypes ctypes-structured-data-types6849696
Ref: 24996849696
Ref: library/ctypes structured-data-types6849696
Ref: 249a6849696
Ref: library/ctypes ctypes Union6849756
Ref: 24396849756
Ref: library/ctypes ctypes BigEndianStructure6849854
Ref: 243c6849854
Ref: library/ctypes ctypes LittleEndianStructure6849971
Ref: 243d6849971
Ref: library/ctypes ctypes Structure6850214
Ref: 24386850214
Ref: library/ctypes ctypes Structure _fields_6850617
Ref: 249b6850617
Ref: library/ctypes ctypes Structure _pack_6852024
Ref: 249c6852024
Ref: library/ctypes ctypes Structure _anonymous_6852275
Ref: 249d6852275
Node: 数组与指针6854366
Ref: library/ctypes arrays-and-pointers6854467
Ref: 249e6854467
Ref: library/ctypes ctypes-arrays-pointers6854467
Ref: 249f6854467
Ref: library/ctypes ctypes Array6854517
Ref: 11456854517
Ref: library/ctypes ctypes Array _length_6854984
Ref: 24a06854984
Ref: library/ctypes ctypes Array _type_6855179
Ref: 24a16855179
Ref: library/ctypes ctypes _Pointer6855340
Ref: 24a26855340
Ref: library/ctypes ctypes _Pointer _type_6855967
Ref: 24a36855967
Ref: library/ctypes ctypes _Pointer contents6856031
Ref: 24446856031
Node: 并发执行6856178
Ref: library/concurrency doc6856332
Ref: 24a46856332
Ref: library/concurrency concurrency6856332
Ref: 24a56856332
Ref: library/concurrency concurrent-execution6856332
Ref: 24a66856332
Node: threading --- 基于线程的并行6857345
Ref: library/threading doc6857479
Ref: 24a76857479
Ref: library/threading module-threading6857479
Ref: 10b6857479
Ref: library/threading threading-thread-based-parallelism6857479
Ref: 24a86857479
Ref: library/threading threading active_count6858600
Ref: 24a96858600
Ref: library/threading threading current_thread6858781
Ref: 24aa6858781
Ref: library/threading threading excepthook6859040
Ref: 35e6859040
Ref: library/threading threading get_ident6860276
Ref: b876860276
Ref: library/threading threading get_native_id6860621
Ref: 3606860621
Ref: library/threading threading enumerate6861035
Ref: f906861035
Ref: library/threading threading main_thread6861381
Ref: 9d56861381
Ref: library/threading threading settrace6861566
Ref: 24ab6861566
Ref: library/threading threading setprofile6861808
Ref: 24ac6861808
Ref: library/threading threading stack_size6862060
Ref: 24ad6862060
Ref: library/threading threading TIMEOUT_MAX6863153
Ref: 24ae6863153
Ref: threading --- 基于线程的并行-Footnote-16864269
Node: 线程本地数据6864337
Ref: library/threading thread-local-data6864448
Ref: 24af6864448
Ref: library/threading threading local6864781
Ref: 244e6864781
Node: 线程对象6864947
Ref: library/threading id16865076
Ref: 24b06865076
Ref: library/threading thread-objects6865076
Ref: 24b16865076
Ref: library/threading threading Thread6867601
Ref: 21a6867601
Ref: library/threading threading Thread start6868736
Ref: 222e6868736
Ref: library/threading threading Thread run6869092
Ref: 35f6869092
Ref: library/threading threading Thread join6869477
Ref: c326869477
Ref: library/threading threading Thread name6870633
Ref: 24b26870633
Ref: library/threading threading Thread getName6870806
Ref: 24b46870806
Ref: library/threading threading Thread setName6870840
Ref: 24b56870840
Ref: library/threading threading Thread ident6870991
Ref: 21756870991
Ref: library/threading threading Thread native_id6871342
Ref: 3616871342
Ref: library/threading threading Thread is_alive6872095
Ref: 21b6872095
Ref: library/threading threading Thread daemon6872396
Ref: 24b36872396
Ref: library/threading threading Thread isDaemon6872884
Ref: 24b66872884
Ref: library/threading threading Thread setDaemon6872919
Ref: 24b76872919
Node: 锁对象6873074
Ref: library/threading id26873200
Ref: 24b86873200
Ref: library/threading lock-objects6873200
Ref: 24b96873200
Ref: library/threading threading Lock6874463
Ref: 24bc6874463
Ref: library/threading threading Lock acquire6874805
Ref: 85b6874805
Ref: library/threading threading Lock release6875946
Ref: 24ba6875946
Ref: library/threading threading Lock locked6876372
Ref: 24bd6876372
Node: 递归锁对象6876454
Ref: library/threading id36876580
Ref: 24be6876580
Ref: library/threading rlock-objects6876580
Ref: 24bf6876580
Ref: library/threading threading RLock6877372
Ref: cba6877372
Ref: library/threading threading RLock acquire6877770
Ref: 85c6877770
Ref: library/threading threading RLock release6879079
Ref: 24c06879079
Node: 条件对象6879663
Ref: library/threading condition-objects6879795
Ref: 24c16879795
Ref: library/threading id46879795
Ref: 24c26879795
Ref: library/threading threading Condition6882739
Ref: b826882739
Ref: library/threading threading Condition acquire6883229
Ref: 24c36883229
Ref: library/threading threading Condition release6883400
Ref: 24c46883400
Ref: library/threading threading Condition wait6883525
Ref: f976883525
Ref: library/threading threading Condition wait_for6884815
Ref: 24c76884815
Ref: library/threading threading Condition notify6885672
Ref: 24c56885672
Ref: library/threading threading Condition notify_all6886499
Ref: 24c66886499
Node: 信号量对象6886851
Ref: library/threading id56886980
Ref: 24c86886980
Ref: library/threading semaphore-objects6886980
Ref: 24c96886980
Ref: library/threading threading Semaphore6887660
Ref: b836887660
Ref: library/threading threading Semaphore acquire6888328
Ref: cb86888328
Ref: library/threading threading Semaphore release6889570
Ref: 24ca6889570
Ref: library/threading threading BoundedSemaphore6889889
Ref: b846889889
Node: Semaphore 例子6890402
Ref: library/threading semaphore-example6890470
Ref: 24cb6890470
Ref: library/threading semaphore-examples6890470
Ref: 24cc6890470
Node: 事件对象6891219
Ref: library/threading event-objects6891351
Ref: 24cd6891351
Ref: library/threading id66891351
Ref: 24ce6891351
Ref: library/threading threading Event6891751
Ref: b856891751
Ref: library/threading threading Event is_set6892140
Ref: 24d16892140
Ref: library/threading threading Event set6892243
Ref: 24cf6892243
Ref: library/threading threading Event clear6892481
Ref: 24d06892481
Ref: library/threading threading Event wait6892724
Ref: d7f6892724
Node: 定时器对象6893507
Ref: library/threading id76893636
Ref: 24d26893636
Ref: library/threading timer-objects6893636
Ref: 24d36893636
Ref: library/threading threading Timer6894310
Ref: b866894310
Ref: library/threading threading Timer cancel6894753
Ref: 24d46894753
Node: 栅栏对象6894921
Ref: library/threading barrier-objects6895086
Ref: 24d56895086
Ref: library/threading threading Barrier6895947
Ref: c316895947
Ref: library/threading threading Barrier wait6896322
Ref: 24d66896322
Ref: library/threading threading Barrier reset6897470
Ref: 24d76897470
Ref: library/threading threading Barrier abort6897861
Ref: 24d86897861
Ref: library/threading threading Barrier parties6898298
Ref: 24d96898298
Ref: library/threading threading Barrier n_waiting6898375
Ref: 24da6898375
Ref: library/threading threading Barrier broken6898466
Ref: 24db6898466
Ref: library/threading threading BrokenBarrierError6898566
Ref: c336898566
Node: 在 with 语句中使用锁、条件和信号量6898778
Ref: library/threading using-locks-conditions-and-semaphores-in-the-with-statement6898919
Ref: 24dc6898919
Ref: library/threading with-locks6898919
Ref: 24bb6898919
Node: multiprocessing --- 基于进程的并行6899679
Ref: library/multiprocessing doc6899895
Ref: 24dd6899895
Ref: library/multiprocessing module-multiprocessing6899895
Ref: b76899895
Ref: library/multiprocessing multiprocessing-process-based-parallelism6899895
Ref: 24de6899895
Ref: multiprocessing --- 基于进程的并行-Footnote-16900215
Node: 簡介<8>6900287
Ref: library/multiprocessing introduction6900389
Ref: 24df6900389
Node: Process 类6901727
Ref: library/multiprocessing the-process-class6901817
Ref: 24e06901817
Node: 上下文和启动方法6902958
Ref: library/multiprocessing contexts-and-start-methods6903084
Ref: 24e26903084
Ref: library/multiprocessing multiprocessing-start-methods6903145
Ref: 9616903145
Ref: 上下文和启动方法-Footnote-16907253
Node: 在进程之间交换对象6907296
Ref: library/multiprocessing exchanging-objects-between-processes6907426
Ref: 24e56907426
Node: 进程间同步6909018
Ref: library/multiprocessing synchronization-between-processes6909145
Ref: 24e86909145
Node: 进程间共享状态6909799
Ref: library/multiprocessing sharing-state-between-processes6909917
Ref: 24e96909917
Node: 使用工作进程6912820
Ref: library/multiprocessing using-a-pool-of-workers6912914
Ref: 24f46912914
Node: 参考6915884
Ref: library/multiprocessing reference6916007
Ref: 24f56916007
Node: Process 和异常6916433
Ref: library/multiprocessing process-and-exceptions6916517
Ref: 24f66916517
Ref: library/multiprocessing multiprocessing Process6916577
Ref: 4b86916577
Ref: library/multiprocessing multiprocessing Process run6917820
Ref: 24e36917820
Ref: library/multiprocessing multiprocessing Process start6918156
Ref: 24f96918156
Ref: library/multiprocessing multiprocessing Process join6918387
Ref: 24fa6918387
Ref: library/multiprocessing multiprocessing Process name6919017
Ref: 24f76919017
Ref: library/multiprocessing multiprocessing Process is_alive6919434
Ref: 24fc6919434
Ref: library/multiprocessing multiprocessing Process daemon6919650
Ref: 24f86919650
Ref: library/multiprocessing multiprocessing Process pid6920402
Ref: 24fd6920402
Ref: library/multiprocessing multiprocessing Process exitcode6920504
Ref: 24fb6920504
Ref: library/multiprocessing multiprocessing Process authkey6920681
Ref: 24fe6920681
Ref: library/multiprocessing multiprocessing Process sentinel6921169
Ref: b026921169
Ref: library/multiprocessing multiprocessing Process terminate6921784
Ref: 25006921784
Ref: library/multiprocessing multiprocessing Process kill6922443
Ref: 4b76922443
Ref: library/multiprocessing multiprocessing Process close6922608
Ref: 4b66922608
Ref: library/multiprocessing multiprocessing ProcessError6923779
Ref: 25016923779
Ref: library/multiprocessing multiprocessing BufferTooShort6923880
Ref: 25026923880
Ref: library/multiprocessing multiprocessing AuthenticationError6924189
Ref: 25036924189
Ref: library/multiprocessing multiprocessing TimeoutError6924281
Ref: 25046924281
Node: 管道和队列6924366
Ref: library/multiprocessing pipes-and-queues6924468
Ref: 25056924468
Ref: library/multiprocessing multiprocessing Pipe6927781
Ref: 24e76927781
Ref: library/multiprocessing multiprocessing Queue6928194
Ref: 24e66928194
Ref: library/multiprocessing multiprocessing Queue qsize6928772
Ref: 25126928772
Ref: library/multiprocessing multiprocessing Queue empty6929097
Ref: 250d6929097
Ref: library/multiprocessing multiprocessing Queue full6929293
Ref: 25136929293
Ref: library/multiprocessing multiprocessing Queue put6929488
Ref: 11636929488
Ref: library/multiprocessing multiprocessing Queue put_nowait6930260
Ref: 25146930260
Ref: library/multiprocessing multiprocessing Queue get6930347
Ref: 11646930347
Ref: library/multiprocessing multiprocessing Queue get_nowait6931128
Ref: 250e6931128
Ref: library/multiprocessing multiprocessing Queue close6931378
Ref: 25156931378
Ref: library/multiprocessing multiprocessing Queue join_thread6931639
Ref: 25166931639
Ref: library/multiprocessing multiprocessing Queue cancel_join_thread6932207
Ref: 250f6932207
Ref: library/multiprocessing multiprocessing SimpleQueue6933147
Ref: 1c36933147
Ref: library/multiprocessing multiprocessing SimpleQueue close6933293
Ref: 1c46933293
Ref: library/multiprocessing multiprocessing SimpleQueue empty6933568
Ref: 25196933568
Ref: library/multiprocessing multiprocessing SimpleQueue get6933680
Ref: 25176933680
Ref: library/multiprocessing multiprocessing SimpleQueue put6933765
Ref: 25186933765
Ref: library/multiprocessing multiprocessing JoinableQueue6933838
Ref: 25066933838
Ref: library/multiprocessing multiprocessing JoinableQueue task_done6934045
Ref: 25096934045
Ref: library/multiprocessing multiprocessing JoinableQueue join6934745
Ref: 251a6934745
Ref: 管道和队列-Footnote-16935234
Node: 杂项<3>6935276
Ref: library/multiprocessing miscellaneous6935389
Ref: 251b6935389
Ref: library/multiprocessing multiprocessing active_children6935422
Ref: 251c6935422
Ref: library/multiprocessing multiprocessing cpu_count6935598
Ref: 96b6935598
Ref: library/multiprocessing multiprocessing current_process6935983
Ref: 251d6935983
Ref: library/multiprocessing multiprocessing parent_process6936161
Ref: 251e6936161
Ref: library/multiprocessing multiprocessing freeze_support6936452
Ref: 251f6936452
Ref: library/multiprocessing multiprocessing get_all_start_methods6937422
Ref: 9626937422
Ref: library/multiprocessing multiprocessing get_context6937837
Ref: 9656937837
Ref: library/multiprocessing multiprocessing get_start_method6938283
Ref: 9636938283
Ref: library/multiprocessing multiprocessing set_executable6939071
Ref: 25206939071
Ref: library/multiprocessing multiprocessing set_start_method6939511
Ref: 9646939511
Ref: 杂项<3>-Footnote-16940200
Node: 连接（Connection）对象6940243
Ref: library/multiprocessing connection-objects6940353
Ref: 25216940353
Ref: library/multiprocessing multiprocessing connection Connection6940653
Ref: 25116940653
Ref: library/multiprocessing multiprocessing connection Connection send6940704
Ref: 25236940704
Ref: library/multiprocessing multiprocessing connection Connection recv6941032
Ref: 25246941032
Ref: library/multiprocessing multiprocessing connection Connection fileno6941315
Ref: 25256941315
Ref: library/multiprocessing multiprocessing connection Connection close6941415
Ref: 25266941415
Ref: library/multiprocessing multiprocessing connection Connection poll6941544
Ref: 25276941544
Ref: library/multiprocessing multiprocessing connection Connection send_bytes6942015
Ref: 25286942015
Ref: library/multiprocessing multiprocessing connection Connection recv_bytes6942534
Ref: 25296942534
Ref: library/multiprocessing multiprocessing connection Connection recv_bytes_into6943138
Ref: 252a6943138
Ref: library/multiprocessing multiprocessing-recv-pickle-security6944837
Ref: 252b6944837
Node: 同步原语6945420
Ref: library/multiprocessing synchronization-primitives6945541
Ref: 252c6945541
Ref: library/multiprocessing multiprocessing Barrier6945820
Ref: 24f36945820
Ref: library/multiprocessing multiprocessing BoundedSemaphore6945974
Ref: 24f06945974
Ref: library/multiprocessing multiprocessing Condition6946433
Ref: 24f16946433
Ref: library/multiprocessing multiprocessing Event6946753
Ref: 24f26946753
Ref: library/multiprocessing multiprocessing Lock6946833
Ref: 24ed6946833
Ref: library/multiprocessing multiprocessing Lock acquire6947592
Ref: 252d6947592
Ref: library/multiprocessing multiprocessing Lock release6948926
Ref: 252e6948926
Ref: library/multiprocessing multiprocessing RLock6949249
Ref: 24ee6949249
Ref: library/multiprocessing multiprocessing RLock acquire6949913
Ref: 252f6949913
Ref: library/multiprocessing multiprocessing RLock release6951200
Ref: 25306951200
Ref: library/multiprocessing multiprocessing Semaphore6952156
Ref: 24ef6952156
Ref: 同步原语-Footnote-16953421
Node: 共享 ctypes 对象6953463
Ref: library/multiprocessing shared-ctypes-objects6953565
Ref: 25316953565
Ref: library/multiprocessing multiprocessing Value6953712
Ref: 24ea6953712
Ref: library/multiprocessing multiprocessing Array6955204
Ref: 24eb6955204
Node: multiprocessing sharedctypes 模块6956637
Ref: library/multiprocessing module-multiprocessing sharedctypes6956729
Ref: bd6956729
Ref: library/multiprocessing the-multiprocessing-sharedctypes-module6956729
Ref: 25326956729
Ref: library/multiprocessing multiprocessing sharedctypes RawArray6957272
Ref: 25336957272
Ref: library/multiprocessing multiprocessing sharedctypes RawValue6958072
Ref: 25356958072
Ref: library/multiprocessing multiprocessing sharedctypes Array6958789
Ref: 25346958789
Ref: library/multiprocessing multiprocessing sharedctypes Value6959525
Ref: 25366959525
Ref: library/multiprocessing multiprocessing sharedctypes copy6960232
Ref: 25376960232
Ref: library/multiprocessing multiprocessing sharedctypes synchronized6960407
Ref: 8086960407
Node: 管理器6963345
Ref: library/multiprocessing managers6963447
Ref: 25386963447
Ref: library/multiprocessing multiprocessing-managers6963447
Ref: 250a6963447
Ref: library/multiprocessing multiprocessing sharedctypes multiprocessing Manager6963748
Ref: 25396963748
Ref: library/multiprocessing module-multiprocessing managers6964081
Ref: ba6964081
Ref: library/multiprocessing multiprocessing managers BaseManager6964236
Ref: 253b6964236
Ref: library/multiprocessing multiprocessing managers BaseManager start6964930
Ref: 253c6964930
Ref: library/multiprocessing multiprocessing managers BaseManager get_server6965154
Ref: 253d6965154
Ref: library/multiprocessing multiprocessing managers BaseManager connect6965674
Ref: 253f6965674
Ref: library/multiprocessing multiprocessing managers BaseManager shutdown6965963
Ref: 25406965963
Ref: library/multiprocessing multiprocessing managers BaseManager register6966169
Ref: 25416966169
Ref: library/multiprocessing multiprocessing managers BaseManager address6968241
Ref: 253e6968241
Ref: library/multiprocessing multiprocessing managers SyncManager6968730
Ref: 253a6968730
Ref: library/multiprocessing multiprocessing managers SyncManager Barrier6969111
Ref: 25446969111
Ref: library/multiprocessing multiprocessing managers SyncManager BoundedSemaphore6969308
Ref: 25456969308
Ref: library/multiprocessing multiprocessing managers SyncManager Condition6969473
Ref: 25466969473
Ref: library/multiprocessing multiprocessing managers SyncManager Event6969843
Ref: 25476969843
Ref: library/multiprocessing multiprocessing managers SyncManager Lock6969979
Ref: 25486969979
Ref: library/multiprocessing multiprocessing managers SyncManager Namespace6970114
Ref: 25496970114
Ref: library/multiprocessing multiprocessing managers SyncManager Queue6970238
Ref: 254a6970238
Ref: library/multiprocessing multiprocessing managers SyncManager RLock6970368
Ref: 254b6970368
Ref: library/multiprocessing multiprocessing managers SyncManager Semaphore6970504
Ref: 254c6970504
Ref: library/multiprocessing multiprocessing managers SyncManager Array6970655
Ref: 254d6970655
Ref: library/multiprocessing multiprocessing managers SyncManager Value6970760
Ref: 254e6970760
Ref: library/multiprocessing multiprocessing managers SyncManager dict6970896
Ref: 254f6970896
Ref: library/multiprocessing multiprocessing managers SyncManager list6971088
Ref: 25506971088
Ref: library/multiprocessing multiprocessing managers Namespace6971456
Ref: 24ec6971456
Node: 自定义管理器6972242
Ref: library/multiprocessing customized-managers6972336
Ref: 25516972336
Node: 使用远程管理器6973119
Ref: library/multiprocessing using-a-remote-manager6973213
Ref: 25526973213
Node: 代理对象6975340
Ref: library/multiprocessing multiprocessing-proxy-objects6975431
Ref: 65e6975431
Ref: library/multiprocessing proxy-objects6975431
Ref: 25536975431
Ref: library/multiprocessing multiprocessing managers BaseProxy6978572
Ref: 25426978572
Ref: library/multiprocessing multiprocessing managers BaseProxy _callmethod6978687
Ref: 25436978687
Ref: library/multiprocessing multiprocessing managers BaseProxy _getvalue6980190
Ref: 25546980190
Ref: library/multiprocessing multiprocessing managers BaseProxy __repr__6980350
Ref: 25556980350
Ref: library/multiprocessing multiprocessing managers BaseProxy __str__6980443
Ref: 25566980443
Node: 清理6980556
Ref: library/multiprocessing cleanup6980611
Ref: 25576980611
Node: 进程池6980871
Ref: library/multiprocessing module-multiprocessing pool6980974
Ref: bb6980974
Ref: library/multiprocessing process-pools6980974
Ref: 25586980974
Ref: library/multiprocessing multiprocessing pool Pool6981107
Ref: 9666981107
Ref: library/multiprocessing multiprocessing pool Pool apply6983408
Ref: 255b6983408
Ref: library/multiprocessing multiprocessing pool Pool apply_async6983733
Ref: 255c6983733
Ref: library/multiprocessing multiprocessing pool Pool map6984515
Ref: b066984515
Ref: library/multiprocessing multiprocessing pool Pool map_async6985214
Ref: b076985214
Ref: library/multiprocessing multiprocessing pool Pool imap6985998
Ref: 255e6985998
Ref: library/multiprocessing multiprocessing pool Pool imap_unordered6986684
Ref: 255f6986684
Ref: library/multiprocessing multiprocessing pool Pool starmap6986978
Ref: b036986978
Ref: library/multiprocessing multiprocessing pool Pool starmap_async6987356
Ref: b046987356
Ref: library/multiprocessing multiprocessing pool Pool close6987714
Ref: 25596987714
Ref: library/multiprocessing multiprocessing pool Pool terminate6987866
Ref: 255a6987866
Ref: library/multiprocessing multiprocessing pool Pool join6988068
Ref: 25606988068
Ref: library/multiprocessing multiprocessing pool AsyncResult6988498
Ref: 255d6988498
Ref: library/multiprocessing multiprocessing pool AsyncResult get6988649
Ref: 25616988649
Ref: library/multiprocessing multiprocessing pool AsyncResult wait6989006
Ref: 25626989006
Ref: library/multiprocessing multiprocessing pool AsyncResult ready6989121
Ref: 25636989121
Ref: library/multiprocessing multiprocessing pool AsyncResult successful6989208
Ref: 25646989208
Node: 监听器及客户端6990467
Ref: library/multiprocessing listeners-and-clients6990570
Ref: 25656990570
Ref: library/multiprocessing module-multiprocessing connection6990570
Ref: b86990570
Ref: library/multiprocessing multiprocessing-listeners-clients6990570
Ref: 25226990570
Ref: library/multiprocessing multiprocessing connection deliver_challenge6991070
Ref: 25666991070
Ref: library/multiprocessing multiprocessing connection answer_challenge6991443
Ref: 25676991443
Ref: library/multiprocessing multiprocessing connection Client6991741
Ref: 25686991741
Ref: library/multiprocessing multiprocessing connection Listener6992420
Ref: 106b6992420
Ref: library/multiprocessing multiprocessing connection Listener accept6994070
Ref: 256a6994070
Ref: library/multiprocessing multiprocessing connection Listener close6994374
Ref: 256b6994374
Ref: library/multiprocessing multiprocessing connection Listener address6994642
Ref: 256c6994642
Ref: library/multiprocessing multiprocessing connection Listener last_accepted6994713
Ref: 256d6994713
Ref: library/multiprocessing multiprocessing connection wait6995083
Ref: b016995083
Node: 地址格式6999077
Ref: library/multiprocessing address-formats6999147
Ref: 256e6999147
Ref: library/multiprocessing multiprocessing-address-formats6999147
Ref: 25696999147
Node: 认证密码6999800
Ref: library/multiprocessing authentication-keys6999900
Ref: 256f6999900
Ref: library/multiprocessing multiprocessing-auth-keys6999900
Ref: 24ff6999900
Node: 日志7000925
Ref: library/multiprocessing logging7001032
Ref: 25707001032
Ref: library/multiprocessing multiprocessing get_logger7001323
Ref: 25717001323
Ref: library/multiprocessing multiprocessing log_to_stderr7001779
Ref: 25727001779
Node: multiprocessing dummy 模块7002901
Ref: library/multiprocessing module-multiprocessing dummy7002987
Ref: b97002987
Ref: library/multiprocessing the-multiprocessing-dummy-module7002987
Ref: 25737002987
Ref: library/multiprocessing multiprocessing pool ThreadPool7003480
Ref: fce7003480
Node: 编程指导7005164
Ref: library/multiprocessing multiprocessing-programming7005288
Ref: 24e17005288
Ref: library/multiprocessing programming-guidelines7005288
Ref: 25747005288
Node: 所有start方法7005488
Ref: library/multiprocessing all-start-methods7005596
Ref: 25757005596
Ref: 所有start方法-Footnote-17011139
Ref: 所有start方法-Footnote-27011181
Ref: 所有start方法-Footnote-37011223
Node: spawn 和 forkserver 启动方式7011265
Ref: library/multiprocessing the-spawn-and-forkserver-start-methods7011373
Ref: 25767011373
Node: 示例<17>7013236
Ref: library/multiprocessing examples7013345
Ref: 25777013345
Ref: library/multiprocessing multiprocessing-examples7013345
Ref: 25107013345
Node: multiprocessing shared_memory --- 可从进程直接访问的共享内存7022214
Ref: library/multiprocessing shared_memory doc7022409
Ref: 25787022409
Ref: library/multiprocessing shared_memory module-multiprocessing shared_memory7022409
Ref: bc7022409
Ref: library/multiprocessing shared_memory multiprocessing-shared-memory-provides-shared-memory-for-direct-access-across-processes7022409
Ref: 25797022409
Ref: library/multiprocessing shared_memory multiprocessing shared_memory SharedMemory7023672
Ref: 24e47023672
Ref: library/multiprocessing shared_memory multiprocessing shared_memory SharedMemory close7025212
Ref: 257a7025212
Ref: library/multiprocessing shared_memory multiprocessing shared_memory SharedMemory unlink7025512
Ref: 257b7025512
Ref: library/multiprocessing shared_memory multiprocessing shared_memory SharedMemory buf7026161
Ref: 257c7026161
Ref: library/multiprocessing shared_memory multiprocessing shared_memory SharedMemory name7026234
Ref: 257d7026234
Ref: library/multiprocessing shared_memory multiprocessing shared_memory SharedMemory size7026317
Ref: 257e7026317
Ref: library/multiprocessing shared_memory multiprocessing managers SharedMemoryManager7029359
Ref: 257f7029359
Ref: library/multiprocessing shared_memory multiprocessing managers SharedMemoryManager SharedMemory7030580
Ref: 25807030580
Ref: library/multiprocessing shared_memory multiprocessing managers SharedMemoryManager ShareableList7030757
Ref: 25817030757
Ref: library/multiprocessing shared_memory multiprocessing shared_memory ShareableList7032515
Ref: 10557032515
Ref: library/multiprocessing shared_memory multiprocessing shared_memory ShareableList count7033618
Ref: 25827033618
Ref: library/multiprocessing shared_memory multiprocessing shared_memory ShareableList index7033705
Ref: 25837033705
Ref: library/multiprocessing shared_memory multiprocessing shared_memory ShareableList format7033880
Ref: 25847033880
Ref: library/multiprocessing shared_memory multiprocessing shared_memory ShareableList shm7034019
Ref: 25857034019
Ref: multiprocessing shared_memory --- 可从进程直接访问的共享内存-Footnote-17035635
Ref: multiprocessing shared_memory --- 可从进程直接访问的共享内存-Footnote-27035724
Node: concurrent 包7035755
Ref: library/concurrent doc7035950
Ref: 25867035950
Ref: library/concurrent the-concurrent-package7035950
Ref: 25877035950
Node: concurrent futures --- 启动并行任务7036105
Ref: library/concurrent futures doc7036257
Ref: 25887036257
Ref: library/concurrent futures concurrent-futures-launching-parallel-tasks7036257
Ref: 25897036257
Ref: library/concurrent futures module-concurrent futures7036257
Ref: 217036257
Ref: concurrent futures --- 启动并行任务-Footnote-17036982
Ref: concurrent futures --- 启动并行任务-Footnote-27037067
Node: Executor 对象7037153
Ref: library/concurrent futures executor-objects7037273
Ref: 258b7037273
Ref: library/concurrent futures concurrent futures Executor7037322
Ref: 258a7037322
Ref: library/concurrent futures concurrent futures Executor submit7037466
Ref: 3c67037466
Ref: library/concurrent futures concurrent futures Executor map7037916
Ref: 7b17037916
Ref: library/concurrent futures concurrent futures Executor shutdown7039424
Ref: 1957039424
Node: ThreadPoolExecutor7041476
Ref: library/concurrent futures threadpoolexecutor7041624
Ref: 258d7041624
Ref: library/concurrent futures concurrent futures ThreadPoolExecutor7042675
Ref: 18c7042675
Node: ThreadPoolExecutor 例子7044336
Ref: library/concurrent futures id17044416
Ref: 258f7044416
Ref: library/concurrent futures threadpoolexecutor-example7044416
Ref: c017044416
Node: ProcessPoolExecutor7045611
Ref: library/concurrent futures processpoolexecutor7045757
Ref: 25907045757
Ref: library/concurrent futures concurrent futures ProcessPoolExecutor7046414
Ref: 1967046414
Node: ProcessPoolExecutor 例子7048090
Ref: library/concurrent futures id27048172
Ref: 25927048172
Ref: library/concurrent futures processpoolexecutor-example7048172
Ref: c027048172
Node: Future 对象7049074
Ref: library/concurrent futures future-objects7049214
Ref: 25937049214
Ref: library/concurrent futures concurrent futures Future7049394
Ref: c007049394
Ref: library/concurrent futures concurrent futures Future cancel7049591
Ref: 25947049591
Ref: library/concurrent futures concurrent futures Future cancelled7049855
Ref: 25957049855
Ref: library/concurrent futures concurrent futures Future running7049958
Ref: 25967049958
Ref: library/concurrent futures concurrent futures Future done7050091
Ref: 25977050091
Ref: library/concurrent futures concurrent futures Future result7050210
Ref: 25987050210
Ref: library/concurrent futures concurrent futures Future exception7050878
Ref: 25997050878
Ref: library/concurrent futures concurrent futures Future add_done_callback7051527
Ref: 259a7051527
Ref: library/concurrent futures concurrent futures Future set_running_or_notify_cancel7052342
Ref: 259b7052342
Ref: library/concurrent futures concurrent futures Future set_result7053347
Ref: 259c7053347
Ref: library/concurrent futures concurrent futures Future set_exception7053749
Ref: 259d7053749
Node: 模块函数7054194
Ref: library/concurrent futures module-functions7054328
Ref: 259f7054328
Ref: library/concurrent futures concurrent futures wait7054369
Ref: f507054369
Ref: library/concurrent futures concurrent futures as_completed7056150
Ref: 12237056150
Ref: 模块函数-Footnote-17057173
Node: Exception 类7057222
Ref: library/concurrent futures exception-classes7057334
Ref: 25a07057334
Ref: library/concurrent futures concurrent futures CancelledError7057380
Ref: 2dd7057380
Ref: library/concurrent futures concurrent futures TimeoutError7057471
Ref: 258c7057471
Ref: library/concurrent futures concurrent futures BrokenExecutor7057581
Ref: 25a17057581
Ref: library/concurrent futures concurrent futures InvalidStateError7057808
Ref: 259e7057808
Ref: library/concurrent futures concurrent futures thread BrokenThreadPool7057975
Ref: 258e7057975
Ref: library/concurrent futures concurrent futures process BrokenProcessPool7058203
Ref: 25917058203
Node: subprocess --- 子进程管理7058501
Ref: library/subprocess doc7058664
Ref: 25a27058664
Ref: library/subprocess module-subprocess7058664
Ref: f97058664
Ref: library/subprocess subprocess-subprocess-management7058664
Ref: 25a37058664
Ref: subprocess --- 子进程管理-Footnote-17059512
Ref: subprocess --- 子进程管理-Footnote-27059581
Node: 使用 subprocess 模块7059630
Ref: library/subprocess using-the-subprocess-module7059742
Ref: 25a47059742
Ref: library/subprocess subprocess run7060148
Ref: 4f27060148
Ref: library/subprocess subprocess CompletedProcess7063713
Ref: 84f7063713
Ref: library/subprocess subprocess CompletedProcess args7063824
Ref: 25a97063824
Ref: library/subprocess subprocess CompletedProcess returncode7063925
Ref: 25aa7063925
Ref: library/subprocess subprocess CompletedProcess stdout7064155
Ref: 25ab7064155
Ref: library/subprocess subprocess CompletedProcess stderr7064626
Ref: 25ac7064626
Ref: library/subprocess subprocess CompletedProcess check_returncode7064901
Ref: 25ad7064901
Ref: library/subprocess subprocess DEVNULL7065067
Ref: b787065067
Ref: library/subprocess subprocess PIPE7065271
Ref: 4f37065271
Ref: library/subprocess subprocess STDOUT7065479
Ref: 25ae7065479
Ref: library/subprocess subprocess SubprocessError7065669
Ref: 25af7065669
Ref: library/subprocess subprocess TimeoutExpired7065776
Ref: 25a87065776
Ref: library/subprocess subprocess TimeoutExpired cmd7065923
Ref: 25b07065923
Ref: library/subprocess subprocess TimeoutExpired timeout7065990
Ref: 25b17065990
Ref: library/subprocess subprocess TimeoutExpired output7066043
Ref: 25b27066043
Ref: library/subprocess subprocess TimeoutExpired stdout7066203
Ref: 25b37066203
Ref: library/subprocess subprocess TimeoutExpired stderr7066298
Ref: 25b47066298
Ref: library/subprocess subprocess CalledProcessError7066526
Ref: d7d7066526
Ref: library/subprocess subprocess CalledProcessError returncode7066761
Ref: 25b67066761
Ref: library/subprocess subprocess CalledProcessError cmd7066918
Ref: 25b77066918
Ref: library/subprocess subprocess CalledProcessError output7066985
Ref: 25b87066985
Ref: library/subprocess subprocess CalledProcessError stdout7067145
Ref: 25b97067145
Ref: library/subprocess subprocess CalledProcessError stderr7067240
Ref: 25ba7067240
Node: 常用参数7067515
Ref: library/subprocess frequently-used-arguments7067615
Ref: 25a67067615
Ref: library/subprocess id17067615
Ref: 25bb7067615
Node: Popen 构造函数7071374
Ref: library/subprocess popen-constructor7071492
Ref: 25c07071492
Ref: library/subprocess subprocess Popen7071729
Ref: 3db7071729
Ref: Popen 构造函数-Footnote-17085831
Node: 异常<7>7085891
Ref: library/subprocess exceptions7085988
Ref: 25cf7085988
Node: 安全考量7087128
Ref: library/subprocess security-considerations7087261
Ref: 25bf7087261
Ref: library/subprocess subprocess-security7087261
Ref: 25d07087261
Ref: 安全考量-Footnote-17087898
Node: Popen 对象7087968
Ref: library/subprocess popen-objects7088097
Ref: 25d17088097
Ref: library/subprocess subprocess Popen poll7088193
Ref: 25d27088193
Ref: library/subprocess subprocess Popen wait7088350
Ref: 6897088350
Ref: library/subprocess subprocess Popen communicate7089177
Ref: 25a77089177
Ref: library/subprocess subprocess Popen send_signal7090844
Ref: 10a47090844
Ref: library/subprocess subprocess Popen terminate7091232
Ref: 25d37091232
Ref: library/subprocess subprocess Popen kill7091469
Ref: 25d47091469
Ref: library/subprocess subprocess Popen args7091722
Ref: 25d57091722
Ref: library/subprocess subprocess Popen stdin7091885
Ref: 25bc7091885
Ref: library/subprocess subprocess Popen stdout7092271
Ref: 25bd7092271
Ref: library/subprocess subprocess Popen stderr7092686
Ref: 25be7092686
Ref: library/subprocess subprocess Popen pid7093347
Ref: 25d67093347
Ref: library/subprocess subprocess Popen returncode7093513
Ref: 10a57093513
Node: Windows Popen 助手7093830
Ref: library/subprocess windows-popen-helpers7093966
Ref: 25d77093966
Ref: library/subprocess subprocess STARTUPINFO7094094
Ref: 25c27094094
Ref: library/subprocess subprocess STARTUPINFO dwFlags7094456
Ref: 25d87094456
Ref: library/subprocess subprocess STARTUPINFO hStdInput7094743
Ref: 25d97094743
Ref: library/subprocess subprocess STARTUPINFO hStdOutput7095028
Ref: 25db7095028
Ref: library/subprocess subprocess STARTUPINFO hStdError7095299
Ref: 25dc7095299
Ref: library/subprocess subprocess STARTUPINFO wShowWindow7095575
Ref: 25dd7095575
Ref: library/subprocess subprocess STARTUPINFO lpAttributeList7095997
Ref: 5947095997
Ref: Windows Popen 助手-Footnote-17097100
Ref: Windows Popen 助手-Footnote-27097172
Ref: Windows Popen 助手-Footnote-37097244
Node: Windows 常数7097333
Ref: library/subprocess windows-constants7097404
Ref: 25e07097404
Ref: library/subprocess subprocess STD_INPUT_HANDLE7097502
Ref: 25e17097502
Ref: library/subprocess subprocess STD_OUTPUT_HANDLE7097615
Ref: 25e27097615
Ref: library/subprocess subprocess STD_ERROR_HANDLE7097745
Ref: 25e37097745
Ref: library/subprocess subprocess SW_HIDE7097874
Ref: 25df7097874
Ref: library/subprocess subprocess STARTF_USESTDHANDLES7097956
Ref: 25da7097956
Ref: library/subprocess subprocess STARTF_USESHOWWINDOW7098163
Ref: 25de7098163
Ref: library/subprocess subprocess CREATE_NEW_CONSOLE7098287
Ref: 25c37098287
Ref: library/subprocess subprocess CREATE_NEW_PROCESS_GROUP7098422
Ref: 25c47098422
Ref: library/subprocess subprocess ABOVE_NORMAL_PRIORITY_CLASS7098750
Ref: 25c57098750
Ref: library/subprocess subprocess BELOW_NORMAL_PRIORITY_CLASS7098947
Ref: 25c67098947
Ref: library/subprocess subprocess HIGH_PRIORITY_CLASS7099144
Ref: 25c77099144
Ref: library/subprocess subprocess IDLE_PRIORITY_CLASS7099321
Ref: 25c87099321
Ref: library/subprocess subprocess NORMAL_PRIORITY_CLASS7099513
Ref: 25c97099513
Ref: library/subprocess subprocess REALTIME_PRIORITY_CLASS7099707
Ref: 25ca7099707
Ref: library/subprocess subprocess CREATE_NO_WINDOW7100165
Ref: 25cb7100165
Ref: library/subprocess subprocess DETACHED_PROCESS7100334
Ref: 25cc7100334
Ref: library/subprocess subprocess CREATE_DEFAULT_ERROR_MODE7100565
Ref: 25cd7100565
Ref: library/subprocess subprocess CREATE_BREAKAWAY_FROM_JOB7100898
Ref: 25ce7100898
Node: 较旧的高阶 API7101076
Ref: library/subprocess call-function-trio7101239
Ref: 25a57101239
Ref: library/subprocess older-high-level-api7101239
Ref: 25e47101239
Ref: library/subprocess subprocess call7101484
Ref: 4f47101484
Ref: library/subprocess subprocess check_call7102444
Ref: 25b57102444
Ref: library/subprocess subprocess check_output7103693
Ref: 9c17103693
Node: 使用 subprocess 模块替换旧函数7105797
Ref: library/subprocess replacing-older-functions-with-the-subprocess-module7105968
Ref: 25e57105968
Ref: library/subprocess subprocess-replacements7105968
Ref: bc17105968
Node: 替代 /bin/sh shell 命令替换7106995
Ref: library/subprocess replacing-bin-sh-shell-command-substitution7107132
Ref: 25e67107132
Node: 替代 shell 管道7107308
Ref: library/subprocess replacing-shell-pipeline7107470
Ref: 25e77107470
Node: 替代 os system7108104
Ref: library/subprocess replacing-os-system7108258
Ref: 25e87108258
Node: 替代 os spawn 函数族7109159
Ref: library/subprocess replacing-the-os-spawn-family7109329
Ref: 25e97109329
Node: 替代 os popen os popen2 os popen37109943
Ref: library/subprocess replacing-os-popen-os-popen2-os-popen37110132
Ref: 25ea7110132
Node: 来自 popen2 模块的替代函数7111413
Ref: library/subprocess replacing-functions-from-the-popen2-module7111568
Ref: 25eb7111568
Node: 旧式的 Shell 发起函数7112842
Ref: library/subprocess legacy-shell-invocation-functions7113000
Ref: 25ec7113000
Ref: library/subprocess subprocess getstatusoutput7113299
Ref: 9c27113299
Ref: library/subprocess subprocess getoutput7114461
Ref: 25ed7114461
Node: 註解7114888
Ref: library/subprocess notes7114998
Ref: 25ee7114998
Node: 在 Windows 上将参数列表转换为一个字符串7115100
Ref: library/subprocess converting-an-argument-sequence-to-a-string-on-windows7115197
Ref: 25ef7115197
Ref: library/subprocess converting-argument-sequence7115197
Ref: 25c17115197
Node: sched --- 事件调度器7116186
Ref: library/sched doc7116342
Ref: 25f07116342
Ref: library/sched module-sched7116342
Ref: e37116342
Ref: library/sched sched-event-scheduler7116342
Ref: 25f17116342
Ref: library/sched sched scheduler7116586
Ref: b497116586
Ref: sched --- 事件调度器-Footnote-17118127
Node: 调度器对象7118191
Ref: library/sched id17118268
Ref: 25f27118268
Ref: library/sched scheduler-objects7118268
Ref: 25f37118268
Ref: library/sched sched scheduler enterabs7118374
Ref: b4b7118374
Ref: library/sched sched scheduler enter7119161
Ref: b4a7119161
Ref: library/sched sched scheduler cancel7119512
Ref: 25f47119512
Ref: library/sched sched scheduler empty7119692
Ref: 25f57119692
Ref: library/sched sched scheduler run7119784
Ref: b487119784
Ref: library/sched sched scheduler queue7120743
Ref: 25f67120743
Node: queue --- 一个同步的队列类7120986
Ref: library/queue doc7121143
Ref: 25f77121143
Ref: library/queue module-queue7121143
Ref: da7121143
Ref: library/queue queue-a-synchronized-queue-class7121143
Ref: 25f87121143
Ref: library/queue queue Queue7122248
Ref: dde7122248
Ref: library/queue queue LifoQueue7122613
Ref: 25f97122613
Ref: library/queue queue PriorityQueue7122934
Ref: 25fa7122934
Ref: library/queue queue SimpleQueue7123825
Ref: 4cc7123825
Ref: library/queue queue Empty7123977
Ref: 250b7123977
Ref: library/queue queue Full7124144
Ref: 250c7124144
Ref: queue --- 一个同步的队列类-Footnote-17124395
Node: Queue对象7124459
Ref: library/queue queue-objects7124568
Ref: 25ff7124568
Ref: library/queue queueobjects7124568
Ref: 26007124568
Ref: library/queue queue Queue qsize7124737
Ref: 26017124737
Ref: library/queue queue Queue empty7124927
Ref: 26027124927
Ref: library/queue queue Queue full7125228
Ref: 26037125228
Ref: library/queue queue Queue put7125521
Ref: 25fd7125521
Ref: library/queue queue Queue put_nowait7126102
Ref: 25fe7126102
Ref: library/queue queue Queue get7126188
Ref: 25fb7126188
Ref: library/queue queue Queue get_nowait7127073
Ref: 25fc7127073
Ref: library/queue queue Queue task_done7127264
Ref: 25077127264
Ref: library/queue queue Queue join7127874
Ref: 25087127874
Node: SimpleQueue 对象7128911
Ref: library/queue simplequeue-objects7129020
Ref: 26047129020
Ref: library/queue queue SimpleQueue qsize7129143
Ref: 26057129143
Ref: library/queue queue SimpleQueue empty7129281
Ref: 26067129281
Ref: library/queue queue SimpleQueue put7129486
Ref: 26077129486
Ref: library/queue queue SimpleQueue put_nowait7130231
Ref: 26087130231
Ref: library/queue queue SimpleQueue get7130388
Ref: 26097130388
Ref: library/queue queue SimpleQueue get_nowait7130971
Ref: 260a7130971
Node: contextvars --- 上下文变量7131376
Ref: library/contextvars doc7131539
Ref: 260b7131539
Ref: library/contextvars contextvars-context-variables7131539
Ref: 260c7131539
Ref: library/contextvars module-contextvars7131539
Ref: 247131539
Ref: contextvars --- 上下文变量-Footnote-17132313
Node: 上下文变量7132362
Ref: library/contextvars context-variables7132475
Ref: 26107132475
Ref: library/contextvars contextvars ContextVar7132521
Ref: 260d7132521
Ref: library/contextvars contextvars ContextVar name7133146
Ref: 26127133146
Ref: library/contextvars contextvars ContextVar get7133254
Ref: 26117133254
Ref: library/contextvars contextvars ContextVar set7133704
Ref: 26137133704
Ref: library/contextvars contextvars ContextVar reset7134042
Ref: 26157134042
Ref: library/contextvars contextvars Token7134539
Ref: 26147134539
Ref: library/contextvars contextvars Token var7134772
Ref: 26167134772
Ref: library/contextvars contextvars Token old_value7134880
Ref: 26177134880
Ref: library/contextvars contextvars Token MISSING7135158
Ref: 26187135158
Node: 手动上下文管理7135258
Ref: library/contextvars manual-context-management7135394
Ref: 26197135394
Ref: library/contextvars contextvars copy_context7135450
Ref: 260e7135450
Ref: library/contextvars contextvars Context7135896
Ref: 260f7135896
Ref: library/contextvars contextvars Context run7136218
Ref: 261a7136218
Ref: library/contextvars contextvars Context copy7137591
Ref: 261b7137591
Ref: library/contextvars contextvars Context get7138038
Ref: 261c7138038
Ref: library/contextvars contextvars Context keys7138465
Ref: 261d7138465
Ref: library/contextvars contextvars Context values7138560
Ref: 261e7138560
Ref: library/contextvars contextvars Context items7138657
Ref: 261f7138657
Node: asyncio 支持7138777
Ref: library/contextvars asyncio-support7138889
Ref: 26207138889
Node: _thread --- 底层多线程 API7140415
Ref: library/_thread doc7140535
Ref: 26217140535
Ref: library/_thread module-_thread7140535
Ref: 27140535
Ref: library/_thread thread-low-level-threading-api7140535
Ref: 26227140535
Ref: library/_thread _thread error7141161
Ref: 26237141161
Ref: library/_thread _thread LockType7141312
Ref: 26247141312
Ref: library/_thread _thread start_new_thread7141368
Ref: 11007141368
Ref: library/_thread _thread interrupt_main7142161
Ref: 26257142161
Ref: library/_thread _thread exit7142517
Ref: 26297142517
Ref: library/_thread _thread allocate_lock7142658
Ref: 262a7142658
Ref: library/_thread _thread get_ident7142811
Ref: 262b7142811
Ref: library/_thread _thread get_native_id7143137
Ref: 262c7143137
Ref: library/_thread _thread stack_size7143549
Ref: 262d7143549
Ref: library/_thread _thread TIMEOUT_MAX7144591
Ref: 262e7144591
Ref: library/_thread _thread lock acquire7144834
Ref: 262f7144834
Ref: library/_thread _thread lock release7145796
Ref: 26307145796
Ref: library/_thread _thread lock locked7145922
Ref: 26317145922
Node: 网络和进程间通信7147206
Ref: library/ipc doc7147357
Ref: 26327147357
Ref: library/ipc ipc7147357
Ref: 26337147357
Ref: library/ipc networking-and-interprocess-communication7147357
Ref: 26347147357
Node: asyncio --- 异步 I/O7148378
Ref: library/asyncio doc7148499
Ref: 26357148499
Ref: library/asyncio asyncio-asynchronous-i-o7148499
Ref: 26367148499
Ref: library/asyncio module-asyncio7148499
Ref: 97148499
Node: 协程与任务7150173
Ref: library/asyncio-task doc7150259
Ref: 26407150259
Ref: library/asyncio-task coroutines-and-tasks7150259
Ref: 26417150259
Node: 协程<3>7150659
Ref: library/asyncio-task coroutine7150747
Ref: 26377150747
Ref: library/asyncio-task coroutines7150747
Ref: 26427150747
Node: 可等待对象<2>7153023
Ref: library/asyncio-task asyncio-awaitables7153141
Ref: 26437153141
Ref: library/asyncio-task awaitables7153141
Ref: 26447153141
Node: 运行 asyncio 程序7155670
Ref: library/asyncio-task running-an-asyncio-program7155791
Ref: 26467155791
Ref: library/asyncio-task asyncio run7155850
Ref: 18d7155850
Ref: 运行 asyncio 程序-Footnote-17156846
Node: 创建任务7156920
Ref: library/asyncio-task creating-tasks7157029
Ref: 26477157029
Ref: library/asyncio-task asyncio create_task7157070
Ref: 2e17157070
Node: 休眠7158130
Ref: library/asyncio-task sleeping7158236
Ref: 26487158236
Ref: library/asyncio-task asyncio sleep7158267
Ref: 3aa7158267
Ref: library/asyncio-task asyncio-example-sleep7158828
Ref: 26497158828
Node: 并发运行任务7159316
Ref: library/asyncio-task running-tasks-concurrently7159428
Ref: 264a7159428
Ref: library/asyncio-task asyncio gather7159479
Ref: 3ab7159479
Ref: library/asyncio-task asyncio-example-gather7160811
Ref: 264b7160811
Node: 屏蔽取消操作7162655
Ref: library/asyncio-task shielding-from-cancellation7162767
Ref: 264c7162767
Ref: library/asyncio-task asyncio shield7162818
Ref: 3ac7162818
Node: 超时7163932
Ref: library/asyncio-task timeouts7164038
Ref: 264e7164038
Ref: library/asyncio-task asyncio wait_for7164069
Ref: 1917164069
Ref: library/asyncio-task asyncio-example-waitfor7164967
Ref: 26507164967
Node: 简单等待7165617
Ref: library/asyncio-task waiting-primitives7165723
Ref: 26517165723
Ref: library/asyncio-task asyncio wait7165766
Ref: 2077165766
Ref: library/asyncio-task asyncio-example-wait-coroutine7167889
Ref: 26527167889
Ref: library/asyncio-task asyncio as_completed7168797
Ref: 3ad7168797
Node: 在线程中运行7169435
Ref: library/asyncio-task running-in-threads7169550
Ref: 26537169550
Ref: library/asyncio-task asyncio to_thread7169603
Ref: 18f7169603
Node: 跨线程调度7171638
Ref: library/asyncio-task scheduling-from-other-threads7171747
Ref: 26547171747
Ref: library/asyncio-task asyncio run_coroutine_threadsafe7171795
Ref: 6137171795
Node: 内省7173128
Ref: library/asyncio-task introspection7173230
Ref: 26567173230
Ref: library/asyncio-task asyncio current_task7173263
Ref: 2287173263
Ref: library/asyncio-task asyncio all_tasks7173562
Ref: 2297173562
Node: Task 对象7173829
Ref: library/asyncio-task task-object7173940
Ref: 26577173940
Ref: library/asyncio-task asyncio Task7173983
Ref: 2e07173983
Ref: library/asyncio-task asyncio Task cancel7175978
Ref: 264d7175978
Ref: library/asyncio-task asyncio-example-task-cancel7176630
Ref: 265c7176630
Ref: library/asyncio-task asyncio Task cancelled7177845
Ref: 26587177845
Ref: library/asyncio-task asyncio Task done7178124
Ref: 265d7178124
Ref: library/asyncio-task asyncio Task result7178368
Ref: 265e7178368
Ref: library/asyncio-task asyncio Task exception7178844
Ref: 26607178844
Ref: library/asyncio-task asyncio Task add_done_callback7179328
Ref: 26617179328
Ref: library/asyncio-task asyncio Task remove_done_callback7179657
Ref: 26627179657
Ref: library/asyncio-task asyncio Task get_stack7179965
Ref: 26647179965
Ref: library/asyncio-task asyncio Task print_stack7180723
Ref: 26657180723
Ref: library/asyncio-task asyncio Task get_coro7181157
Ref: 2df7181157
Ref: library/asyncio-task asyncio Task get_name7181285
Ref: 2e47181285
Ref: library/asyncio-task asyncio Task set_name7181537
Ref: 2e37181537
Node: 基于生成器的协程7181847
Ref: library/asyncio-task asyncio-generator-based-coro7181943
Ref: 26457181943
Ref: library/asyncio-task generator-based-coroutines7181943
Ref: 26667181943
Ref: library/asyncio-task asyncio coroutine7182384
Ref: 3a87182384
Ref: library/asyncio-task asyncio iscoroutine7182926
Ref: 26677182926
Ref: library/asyncio-task asyncio iscoroutinefunction7183166
Ref: 26687183166
Node: 流7183465
Ref: library/asyncio-stream doc7183575
Ref: 26697183575
Ref: library/asyncio-stream asyncio-streams7183575
Ref: 26387183575
Ref: library/asyncio-stream streams7183575
Ref: 266a7183575
Ref: library/asyncio-stream asyncio-example-stream7183867
Ref: 266b7183867
Ref: library/asyncio-stream asyncio open_connection7184581
Ref: 46b7184581
Ref: library/asyncio-stream asyncio start_server7185403
Ref: 46c7185403
Ref: library/asyncio-stream asyncio open_unix_connection7186701
Ref: 266d7186701
Ref: library/asyncio-stream asyncio start_unix_server7187302
Ref: 266f7187302
Ref: 流-Footnote-17188025
Node: StreamReader7188099
Ref: library/asyncio-stream streamreader7188172
Ref: 26707188172
Ref: library/asyncio-stream asyncio StreamReader7188219
Ref: 11057188219
Ref: library/asyncio-stream asyncio StreamReader read7188526
Ref: 26717188526
Ref: library/asyncio-stream asyncio StreamReader readline7188829
Ref: 26727188829
Ref: library/asyncio-stream asyncio StreamReader readexactly7189157
Ref: 6187189157
Ref: library/asyncio-stream asyncio StreamReader readuntil7189538
Ref: 6177189538
Ref: library/asyncio-stream asyncio StreamReader at_eof7190319
Ref: 26757190319
Node: StreamWriter7190446
Ref: library/asyncio-stream streamwriter7190538
Ref: 26767190538
Ref: library/asyncio-stream asyncio StreamWriter7190585
Ref: 11067190585
Ref: library/asyncio-stream asyncio StreamWriter write7190845
Ref: 26777190845
Ref: library/asyncio-stream asyncio StreamWriter writelines7191190
Ref: 26787191190
Ref: library/asyncio-stream asyncio StreamWriter close7191600
Ref: 26797191600
Ref: library/asyncio-stream asyncio StreamWriter can_write_eof7191833
Ref: 267a7191833
Ref: library/asyncio-stream asyncio StreamWriter write_eof7192011
Ref: 267b7192011
Ref: library/asyncio-stream asyncio StreamWriter transport7192123
Ref: 267c7192123
Ref: library/asyncio-stream asyncio StreamWriter get_extra_info7192196
Ref: 267d7192196
Ref: library/asyncio-stream asyncio StreamWriter drain7192366
Ref: 267e7192366
Ref: library/asyncio-stream asyncio StreamWriter is_closing7192884
Ref: 45f7192884
Ref: library/asyncio-stream asyncio StreamWriter wait_closed7193025
Ref: 45e7193025
Node: 示例<18>7193256
Ref: library/asyncio-stream examples7193327
Ref: 266c7193327
Node: 使用流的 TCP 回显客户端7193529
Ref: library/asyncio-stream asyncio-tcp-echo-client-streams7193649
Ref: 267f7193649
Ref: library/asyncio-stream tcp-echo-client-using-streams7193649
Ref: 26807193649
Node: 使用流的 TCP 回显服务器7194367
Ref: library/asyncio-stream asyncio-tcp-echo-server-streams7194514
Ref: 26827194514
Ref: library/asyncio-stream tcp-echo-server-using-streams7194514
Ref: 26837194514
Node: 获取 HTTP 标头7195513
Ref: library/asyncio-stream get-http-headers7195685
Ref: 26857195685
Node: 注册一个打开的套接字以等待使用流的数据7196905
Ref: library/asyncio-stream asyncio-example-create-connection-streams7197036
Ref: 26867197036
Ref: library/asyncio-stream register-an-open-socket-to-wait-for-data-using-streams7197036
Ref: 26877197036
Node: 同步原语<2>7198402
Ref: library/asyncio-sync doc7198506
Ref: 268b7198506
Ref: library/asyncio-sync asyncio-sync7198506
Ref: 263b7198506
Ref: library/asyncio-sync synchronization-primitives7198506
Ref: 268c7198506
Ref: 同步原语<2>-Footnote-17199411
Node: Lock7199483
Ref: library/asyncio-sync lock7199553
Ref: 268d7199553
Ref: library/asyncio-sync asyncio Lock7199584
Ref: 3ae7199584
Ref: library/asyncio-sync asyncio Lock acquire7200258
Ref: 268e7200258
Ref: library/asyncio-sync asyncio Lock release7200688
Ref: 268f7200688
Ref: library/asyncio-sync asyncio Lock locked7200898
Ref: 26907200898
Node: Event7200989
Ref: library/asyncio-sync event7201077
Ref: 26917201077
Ref: library/asyncio-sync asyncio Event7201110
Ref: 3af7201110
Ref: library/asyncio-sync asyncio-example-sync-event7201679
Ref: 26957201679
Ref: library/asyncio-sync asyncio Event wait7202307
Ref: 26947202307
Ref: library/asyncio-sync asyncio Event set7202535
Ref: 26927202535
Ref: library/asyncio-sync asyncio Event clear7202662
Ref: 26937202662
Ref: library/asyncio-sync asyncio Event is_set7202878
Ref: 26967202878
Node: Condition7202971
Ref: library/asyncio-sync condition7203064
Ref: 26977203064
Ref: library/asyncio-sync asyncio Condition7203105
Ref: 3b07203105
Ref: library/asyncio-sync asyncio Condition acquire7204256
Ref: 26987204256
Ref: library/asyncio-sync asyncio Condition notify7204463
Ref: 26997204463
Ref: library/asyncio-sync asyncio Condition locked7204829
Ref: 269a7204829
Ref: library/asyncio-sync asyncio Condition notify_all7204928
Ref: 269b7204928
Ref: library/asyncio-sync asyncio Condition release7205314
Ref: 269c7205314
Ref: library/asyncio-sync asyncio Condition wait7205473
Ref: 269d7205473
Ref: library/asyncio-sync asyncio Condition wait_for7205934
Ref: 269e7205934
Node: Semaphore7206173
Ref: library/asyncio-sync semaphore7206277
Ref: 269f7206277
Ref: library/asyncio-sync asyncio Semaphore7206318
Ref: 3b17206318
Ref: library/asyncio-sync asyncio Semaphore acquire7207470
Ref: 26a07207470
Ref: library/asyncio-sync asyncio Semaphore locked7207763
Ref: 26a27207763
Ref: library/asyncio-sync asyncio Semaphore release7207874
Ref: 26a17207874
Node: BoundedSemaphore7208215
Ref: library/asyncio-sync boundedsemaphore7208301
Ref: 26a37208301
Ref: library/asyncio-sync asyncio BoundedSemaphore7208356
Ref: 3b27208356
Node: 子进程7209081
Ref: library/asyncio-subprocess doc7209191
Ref: 26a47209191
Ref: library/asyncio-subprocess asyncio-subprocess7209191
Ref: 26397209191
Ref: library/asyncio-subprocess subprocesses7209191
Ref: 26a57209191
Ref: library/asyncio-subprocess asyncio-example-subprocess-shell7209459
Ref: 26a67209459
Ref: 子进程-Footnote-17210716
Ref: 子进程-Footnote-27210794
Node: 创建子进程7210877
Ref: library/asyncio-subprocess creating-subprocesses7210956
Ref: 26a87210956
Ref: library/asyncio-subprocess asyncio create_subprocess_exec7211004
Ref: 3b47211004
Ref: library/asyncio-subprocess asyncio create_subprocess_shell7211660
Ref: 3b57211660
Ref: 创建子进程-Footnote-17213116
Node: 常数<5>7213186
Ref: library/asyncio-subprocess constants7213292
Ref: 26b07213292
Ref: library/asyncio-subprocess asyncio asyncio subprocess PIPE7213325
Ref: 26b17213325
Ref: library/asyncio-subprocess asyncio asyncio subprocess STDOUT7213767
Ref: 26b57213767
Ref: library/asyncio-subprocess asyncio asyncio subprocess DEVNULL7213914
Ref: 26b67213914
Node: 与子进程交互7214132
Ref: library/asyncio-subprocess interacting-with-subprocesses7214214
Ref: 26b77214214
Ref: library/asyncio-subprocess asyncio asyncio subprocess Process7214485
Ref: 26a97214485
Ref: library/asyncio-subprocess asyncio asyncio subprocess Process wait7215373
Ref: 26b97215373
Ref: library/asyncio-subprocess asyncio asyncio subprocess Process communicate7215844
Ref: 26b87215844
Ref: library/asyncio-subprocess asyncio asyncio subprocess Process send_signal7217016
Ref: 26bc7217016
Ref: library/asyncio-subprocess asyncio asyncio subprocess Process terminate7217419
Ref: 26bd7217419
Ref: library/asyncio-subprocess asyncio asyncio subprocess Process kill7217701
Ref: 26bf7217701
Ref: library/asyncio-subprocess asyncio asyncio subprocess Process stdin7217919
Ref: 26b27217919
Ref: library/asyncio-subprocess asyncio asyncio subprocess Process stdout7218084
Ref: 26b37218084
Ref: library/asyncio-subprocess asyncio asyncio subprocess Process stderr7218251
Ref: 26b47218251
Ref: library/asyncio-subprocess asyncio asyncio subprocess Process pid7218732
Ref: 26c07218732
Ref: library/asyncio-subprocess asyncio asyncio subprocess Process returncode7218992
Ref: 26bb7218992
Node: 子进程和线程7219263
Ref: library/asyncio-subprocess asyncio-subprocess-threads7219355
Ref: 26ba7219355
Ref: library/asyncio-subprocess subprocess-and-threads7219355
Ref: 26c17219355
Node: 示例<19>7220141
Ref: library/asyncio-subprocess examples7220233
Ref: 26a77220233
Ref: library/asyncio-subprocess asyncio-example-create-subprocess-exec7220402
Ref: 26c57220402
Node: 队列集7221202
Ref: library/asyncio-queue doc7221306
Ref: 26c77221306
Ref: library/asyncio-queue asyncio-queues7221306
Ref: 263a7221306
Ref: library/asyncio-queue queues7221306
Ref: 26c87221306
Ref: 队列集-Footnote-17221932
Node: 队列7222005
Ref: library/asyncio-queue queue7222081
Ref: 26ca7222081
Ref: library/asyncio-queue asyncio Queue7222114
Ref: 3b37222114
Ref: library/asyncio-queue asyncio Queue maxsize7222734
Ref: 26cd7222734
Ref: library/asyncio-queue asyncio Queue empty7222808
Ref: 26ce7222808
Ref: library/asyncio-queue asyncio Queue full7222920
Ref: 26cf7222920
Ref: library/asyncio-queue asyncio Queue get7223179
Ref: 26cb7223179
Ref: library/asyncio-queue asyncio Queue get_nowait7223345
Ref: 26d07223345
Ref: library/asyncio-queue asyncio Queue join7223514
Ref: 7927223514
Ref: library/asyncio-queue asyncio Queue put7223978
Ref: 26d27223978
Ref: library/asyncio-queue asyncio Queue put_nowait7224157
Ref: 26d37224157
Ref: library/asyncio-queue asyncio Queue qsize7224340
Ref: 26cc7224340
Ref: library/asyncio-queue asyncio Queue task_done7224418
Ref: 7937224418
Node: 优先级队列7225103
Ref: library/asyncio-queue priority-queue7225206
Ref: 26d57225206
Ref: library/asyncio-queue asyncio PriorityQueue7225254
Ref: 26d67225254
Node: 后进先出队列7225451
Ref: library/asyncio-queue lifo-queue7225557
Ref: 26d77225557
Ref: library/asyncio-queue asyncio LifoQueue7225610
Ref: 26d87225610
Node: 异常<8>7225732
Ref: library/asyncio-queue exceptions7225833
Ref: 26d97225833
Ref: library/asyncio-queue asyncio QueueEmpty7225866
Ref: 26d17225866
Ref: library/asyncio-queue asyncio QueueFull7226001
Ref: 26d47226001
Node: 示例<20>7226169
Ref: library/asyncio-queue examples7226243
Ref: 26c97226243
Ref: library/asyncio-queue asyncio-example-queue-dist7226276
Ref: 26da7226276
Node: 异常<9>7228019
Ref: library/asyncio-exceptions doc7228126
Ref: 26db7228126
Ref: library/asyncio-exceptions asyncio-exceptions7228126
Ref: 26dc7228126
Ref: library/asyncio-exceptions exceptions7228126
Ref: 26dd7228126
Ref: library/asyncio-exceptions asyncio TimeoutError7228270
Ref: 264f7228270
Ref: library/asyncio-exceptions asyncio CancelledError7228435
Ref: 2da7228435
Ref: library/asyncio-exceptions asyncio InvalidStateError7228747
Ref: 265f7228747
Ref: library/asyncio-exceptions asyncio SendfileNotAvailableError7228957
Ref: 26de7228957
Ref: library/asyncio-exceptions asyncio IncompleteReadError7229124
Ref: fdb7229124
Ref: library/asyncio-exceptions asyncio IncompleteReadError expected7229314
Ref: 26df7229314
Ref: library/asyncio-exceptions asyncio IncompleteReadError partial7229400
Ref: 26737229400
Ref: library/asyncio-exceptions asyncio LimitOverrunError7229499
Ref: 26747229499
Ref: library/asyncio-exceptions asyncio LimitOverrunError consumed7229646
Ref: 26e07229646
Ref: 异常<9>-Footnote-17229748
Node: 事件循环7229826
Ref: library/asyncio-eventloop doc7229931
Ref: 26e17229931
Ref: library/asyncio-eventloop event-loop7229931
Ref: 26e27229931
Ref: library/asyncio-eventloop asyncio get_running_loop7230661
Ref: 45c7230661
Ref: library/asyncio-eventloop asyncio get_event_loop7230926
Ref: 45d7230926
Ref: library/asyncio-eventloop asyncio set_event_loop7231608
Ref: 26e37231608
Ref: library/asyncio-eventloop asyncio new_event_loop7231718
Ref: 26e47231718
Ref: 事件循环-Footnote-17232855
Ref: 事件循环-Footnote-27232928
Node: 事件循环方法集7233007
Ref: library/asyncio-eventloop asyncio-event-loop7233098
Ref: 7377233098
Ref: library/asyncio-eventloop event-loop-methods7233098
Ref: 26e67233098
Node: 运行和停止循环7233585
Ref: library/asyncio-eventloop running-and-stopping-the-loop7233685
Ref: 26ec7233685
Ref: library/asyncio-eventloop asyncio loop run_until_complete7233743
Ref: 6117233743
Ref: library/asyncio-eventloop asyncio loop run_forever7234047
Ref: 26ed7234047
Ref: library/asyncio-eventloop asyncio loop stop7234778
Ref: 6197234778
Ref: library/asyncio-eventloop asyncio loop is_running7234838
Ref: 26ee7234838
Ref: library/asyncio-eventloop asyncio loop is_closed7234940
Ref: 78e7234940
Ref: library/asyncio-eventloop asyncio loop close7235041
Ref: 26ef7235041
Ref: library/asyncio-eventloop asyncio loop shutdown_asyncgens7235418
Ref: 61a7235418
Ref: library/asyncio-eventloop asyncio loop shutdown_default_executor7236070
Ref: 18b7236070
Node: 安排回调7236498
Ref: library/asyncio-eventloop scheduling-callbacks7236625
Ref: 26f07236625
Ref: library/asyncio-eventloop asyncio loop call_soon7236668
Ref: 4557236668
Ref: library/asyncio-eventloop asyncio loop call_soon_threadsafe7237264
Ref: 4567237264
Ref: library/asyncio-eventloop asyncio-pass-keywords7237807
Ref: 26f27237807
Ref: 安排回调-Footnote-17238272
Node: 调度延迟回调7238321
Ref: library/asyncio-eventloop asyncio-delayed-calls7238449
Ref: 26f37238449
Ref: library/asyncio-eventloop scheduling-delayed-callbacks7238449
Ref: 26f47238449
Ref: library/asyncio-eventloop asyncio loop call_later7238628
Ref: 4577238628
Ref: library/asyncio-eventloop asyncio loop call_at7239720
Ref: 4587239720
Ref: library/asyncio-eventloop asyncio loop time7240421
Ref: 26f57240421
Ref: 调度延迟回调-Footnote-17240829
Ref: 调度延迟回调-Footnote-27240878
Node: 创建 Future 和 Task7240927
Ref: library/asyncio-eventloop creating-futures-and-tasks7241061
Ref: 26f67241061
Ref: library/asyncio-eventloop asyncio loop create_future7241125
Ref: 6157241125
Ref: library/asyncio-eventloop asyncio loop create_task7241437
Ref: 2e27241437
Ref: library/asyncio-eventloop asyncio loop set_task_factory7241959
Ref: 7907241959
Ref: library/asyncio-eventloop asyncio loop get_task_factory7242460
Ref: 7917242460
Node: 打开网络连接7242591
Ref: library/asyncio-eventloop opening-network-connections7242725
Ref: 26f77242725
Ref: library/asyncio-eventloop asyncio loop create_connection7242778
Ref: 2e57242778
Ref: library/asyncio-eventloop asyncio loop create_datagram_endpoint7248113
Ref: 1897248113
Ref: library/asyncio-eventloop asyncio loop create_unix_connection7251368
Ref: 266e7251368
Ref: 打开网络连接-Footnote-17252296
Ref: 打开网络连接-Footnote-27252345
Node: 创建网络服务7252394
Ref: library/asyncio-eventloop creating-network-servers7252518
Ref: 27017252518
Ref: library/asyncio-eventloop asyncio loop create_server7252571
Ref: 4657252571
Ref: library/asyncio-eventloop asyncio loop create_unix_server7256371
Ref: 4667256371
Ref: library/asyncio-eventloop asyncio loop connect_accepted_socket7257187
Ref: 46d7257187
Node: 传输文件7258199
Ref: library/asyncio-eventloop transferring-files7258315
Ref: 27027258315
Ref: library/asyncio-eventloop asyncio loop sendfile7258358
Ref: 27037258358
Node: TLS 升级7259376
Ref: library/asyncio-eventloop tls-upgrade7259495
Ref: 27047259495
Ref: library/asyncio-eventloop asyncio loop start_tls7259536
Ref: 45a7259536
Node: 监控文件描述符7260689
Ref: library/asyncio-eventloop watching-file-descriptors7260822
Ref: 27057260822
Ref: library/asyncio-eventloop asyncio loop add_reader7260880
Ref: 26897260880
Ref: library/asyncio-eventloop asyncio loop remove_reader7261085
Ref: 27067261085
Ref: library/asyncio-eventloop asyncio loop add_writer7261192
Ref: 27077261192
Ref: library/asyncio-eventloop asyncio loop remove_writer7261489
Ref: 27087261489
Node: 直接使用 socket 对象7261679
Ref: library/asyncio-eventloop working-with-socket-objects-directly7261805
Ref: 270a7261805
Ref: library/asyncio-eventloop asyncio loop sock_recv7262168
Ref: 5987262168
Ref: library/asyncio-eventloop asyncio loop sock_recv_into7262648
Ref: 45b7262648
Ref: library/asyncio-eventloop asyncio loop sock_sendall7262943
Ref: 5997262943
Ref: library/asyncio-eventloop asyncio loop sock_connect7263674
Ref: 7947263674
Ref: library/asyncio-eventloop asyncio loop sock_accept7264288
Ref: 59a7264288
Ref: library/asyncio-eventloop asyncio loop sock_sendfile7265068
Ref: 4607265068
Node: DNS7266255
Ref: library/asyncio-eventloop dns7266372
Ref: 270b7266372
Ref: library/asyncio-eventloop asyncio loop getaddrinfo7266401
Ref: 59b7266401
Ref: library/asyncio-eventloop asyncio loop getnameinfo7266566
Ref: 59c7266566
Node: 使用管道7266912
Ref: library/asyncio-eventloop working-with-pipes7267014
Ref: 270e7267014
Ref: library/asyncio-eventloop asyncio loop connect_read_pipe7267057
Ref: 26ac7267057
Ref: library/asyncio-eventloop asyncio loop connect_write_pipe7267640
Ref: 26ad7267640
Node: Unix 信号7268480
Ref: library/asyncio-eventloop unix-signals7268621
Ref: 27117268621
Ref: library/asyncio-eventloop asyncio loop add_signal_handler7268664
Ref: 263d7268664
Ref: library/asyncio-eventloop asyncio loop remove_signal_handler7269456
Ref: 27127269456
Node: 在线程或者进程池中执行代码。7269775
Ref: library/asyncio-eventloop executing-code-in-thread-or-process-pools7269919
Ref: 27137269919
Ref: library/asyncio-eventloop asyncio loop run_in_executor7270012
Ref: 1907270012
Ref: library/asyncio-eventloop asyncio loop set_default_executor7272122
Ref: 3a17272122
Node: 错误处理API7272640
Ref: library/asyncio-eventloop error-handling-api7272791
Ref: 27147272791
Ref: library/asyncio-eventloop asyncio loop set_exception_handler7272896
Ref: 27157272896
Ref: library/asyncio-eventloop asyncio loop get_exception_handler7273434
Ref: 6167273434
Ref: library/asyncio-eventloop asyncio loop default_exception_handler7273609
Ref: 27177273609
Ref: library/asyncio-eventloop asyncio loop call_exception_handler7274004
Ref: 27167274004
Node: 开启调试模式7274872
Ref: library/asyncio-eventloop enabling-debug-mode7274996
Ref: 27187274996
Ref: library/asyncio-eventloop asyncio loop get_debug7275049
Ref: 78d7275049
Ref: library/asyncio-eventloop asyncio loop set_debug7275300
Ref: 78c7275300
Node: 运行子进程7275559
Ref: library/asyncio-eventloop running-subprocesses7275659
Ref: 27197275659
Ref: library/asyncio-eventloop asyncio loop subprocess_exec7276155
Ref: 263c7276155
Ref: library/asyncio-eventloop asyncio loop subprocess_shell7279655
Ref: 26aa7279655
Ref: 运行子进程-Footnote-17280855
Node: 回调处理7280925
Ref: library/asyncio-eventloop callback-handles7281038
Ref: 26e77281038
Ref: library/asyncio-eventloop asyncio Handle7281081
Ref: 11d77281081
Ref: library/asyncio-eventloop asyncio Handle cancel7281230
Ref: 271c7281230
Ref: library/asyncio-eventloop asyncio Handle cancelled7281381
Ref: 46e7281381
Ref: library/asyncio-eventloop asyncio TimerHandle7281509
Ref: 26e87281509
Ref: library/asyncio-eventloop asyncio TimerHandle when7281708
Ref: 46a7281708
Node: Server 对象7281995
Ref: library/asyncio-eventloop server-objects7282105
Ref: 26e97282105
Ref: library/asyncio-eventloop asyncio Server7282368
Ref: 4647282368
Ref: library/asyncio-eventloop asyncio Server close7282901
Ref: 271d7282901
Ref: library/asyncio-eventloop asyncio Server get_loop7283259
Ref: 4637283259
Ref: library/asyncio-eventloop asyncio Server start_serving7283387
Ref: 4677283387
Ref: library/asyncio-eventloop asyncio Server serve_forever7284025
Ref: 4687284025
Ref: library/asyncio-eventloop asyncio Server is_serving7284882
Ref: 4697284882
Ref: library/asyncio-eventloop asyncio Server wait_closed7285030
Ref: 271e7285030
Ref: library/asyncio-eventloop asyncio Server sockets7285140
Ref: 59d7285140
Node: 事件循环实现7285415
Ref: library/asyncio-eventloop asyncio-event-loops7285523
Ref: 271f7285523
Ref: library/asyncio-eventloop event-loop-implementations7285523
Ref: 26ea7285523
Ref: library/asyncio-eventloop asyncio SelectorEventLoop7285839
Ref: 26c27285839
Ref: library/asyncio-eventloop asyncio ProactorEventLoop7286293
Ref: 2de7286293
Ref: library/asyncio-eventloop asyncio AbstractEventLoop7286534
Ref: 2337286534
Ref: 事件循环实现-Footnote-17286789
Node: 示例<21>7286875
Ref: library/asyncio-eventloop examples7286961
Ref: 26eb7286961
Node: call_soon 的 Hello World 示例。7287574
Ref: library/asyncio-eventloop asyncio-example-lowlevel-helloworld7287707
Ref: 27207287707
Ref: library/asyncio-eventloop hello-world-with-call-soon7287707
Ref: 27217287707
Node: 使用 call_later 来展示当前的日期7288474
Ref: library/asyncio-eventloop asyncio-example-call-later7288655
Ref: 27227288655
Ref: library/asyncio-eventloop display-the-current-date-with-call-later7288655
Ref: 27237288655
Node: 监控一个文件描述符的读事件7289612
Ref: library/asyncio-eventloop asyncio-example-watch-fd7289798
Ref: 268a7289798
Ref: library/asyncio-eventloop watch-a-file-descriptor-for-read-events7289798
Ref: 27247289798
Node: 为SIGINT和SIGTERM设置信号处理器7291097
Ref: library/asyncio-eventloop asyncio-example-unix-signals7291232
Ref: 27257291232
Ref: library/asyncio-eventloop set-signal-handlers-for-sigint-and-sigterm7291232
Ref: 27267291232
Node: Futures7292134
Ref: library/asyncio-future doc7292245
Ref: 27277292245
Ref: library/asyncio-future asyncio-futures7292245
Ref: 263f7292245
Ref: library/asyncio-future futures7292245
Ref: 27287292245
Ref: Futures-Footnote-17292609
Ref: Futures-Footnote-27292683
Node: Future 函数7292763
Ref: library/asyncio-future future-functions7292845
Ref: 27297292845
Ref: library/asyncio-future asyncio isfuture7292892
Ref: 272a7292892
Ref: library/asyncio-future asyncio ensure_future7293221
Ref: 6107293221
Ref: library/asyncio-future asyncio wrap_future7294261
Ref: 272b7294261
Node: Future 对象<2>7294432
Ref: library/asyncio-future future-object7294514
Ref: 272c7294514
Ref: library/asyncio-future asyncio Future7294561
Ref: 5457294561
Ref: library/asyncio-future asyncio Future result7295344
Ref: 272d7295344
Ref: library/asyncio-future asyncio Future set_result7295950
Ref: 26597295950
Ref: library/asyncio-future asyncio Future set_exception7296162
Ref: 265a7296162
Ref: library/asyncio-future asyncio Future done7296386
Ref: 272e7296386
Ref: library/asyncio-future asyncio Future cancelled7296680
Ref: 272f7296680
Ref: library/asyncio-future asyncio Future add_done_callback7296953
Ref: 4597296953
Ref: library/asyncio-future asyncio Future remove_done_callback7297900
Ref: 26637297900
Ref: library/asyncio-future asyncio Future cancel7298127
Ref: 265b7298127
Ref: library/asyncio-future asyncio Future exception7298452
Ref: 27307298452
Ref: library/asyncio-future asyncio Future get_loop7298890
Ref: 4627298890
Ref: library/asyncio-future asyncio-example-future7299014
Ref: 27317299014
Ref: Future 对象<2>-Footnote-17301087
Node: 传输和协议7301136
Ref: library/asyncio-protocol doc7301241
Ref: 27327301241
Ref: library/asyncio-protocol asyncio-transports-protocols7301241
Ref: 263e7301241
Ref: library/asyncio-protocol transports-and-protocols7301241
Ref: 27337301241
Node: 传输7303202
Ref: library/asyncio-protocol asyncio-transport7303275
Ref: 26fb7303275
Ref: library/asyncio-protocol transports7303275
Ref: 27347303275
Ref: 传输-Footnote-17303886
Node: 传输层级7303964
Ref: library/asyncio-protocol transports-hierarchy7304040
Ref: 273d7304040
Ref: library/asyncio-protocol asyncio BaseTransport7304083
Ref: 27367304083
Ref: library/asyncio-protocol asyncio WriteTransport7304193
Ref: 27107304193
Ref: library/asyncio-protocol asyncio ReadTransport7304477
Ref: 270f7304477
Ref: library/asyncio-protocol asyncio Transport7304759
Ref: 27377304759
Ref: library/asyncio-protocol asyncio DatagramTransport7305275
Ref: 27387305275
Ref: library/asyncio-protocol asyncio SubprocessTransport7305482
Ref: 271b7305482
Node: 基础传输7305756
Ref: library/asyncio-protocol base-transport7305853
Ref: 273e7305853
Ref: library/asyncio-protocol asyncio BaseTransport close7305896
Ref: 273f7305896
Ref: library/asyncio-protocol asyncio BaseTransport is_closing7306271
Ref: 6147306271
Ref: library/asyncio-protocol asyncio BaseTransport get_extra_info7306391
Ref: 3ea7306391
Ref: library/asyncio-protocol asyncio BaseTransport set_protocol7308247
Ref: 27447308247
Ref: library/asyncio-protocol asyncio BaseTransport get_protocol7308408
Ref: 27457308408
Node: 只读传输7308485
Ref: library/asyncio-protocol read-only-transports7308582
Ref: 27467308582
Ref: library/asyncio-protocol asyncio ReadTransport is_reading7308625
Ref: 46f7308625
Ref: library/asyncio-protocol asyncio ReadTransport pause_reading7308757
Ref: 4717308757
Ref: library/asyncio-protocol asyncio ReadTransport resume_reading7309063
Ref: 4707309063
Node: 只写传输7309350
Ref: library/asyncio-protocol write-only-transports7309450
Ref: 27487309450
Ref: library/asyncio-protocol asyncio WriteTransport abort7309493
Ref: 27497309493
Ref: library/asyncio-protocol asyncio WriteTransport can_write_eof7309791
Ref: 274a7309791
Ref: library/asyncio-protocol asyncio WriteTransport get_write_buffer_size7309957
Ref: 274c7309957
Ref: library/asyncio-protocol asyncio WriteTransport get_write_buffer_limits7310074
Ref: 78f7310074
Ref: library/asyncio-protocol asyncio WriteTransport set_write_buffer_limits7310368
Ref: 274d7310368
Ref: library/asyncio-protocol asyncio WriteTransport write7311649
Ref: 27507311649
Ref: library/asyncio-protocol asyncio WriteTransport writelines7311826
Ref: 27517311826
Ref: library/asyncio-protocol asyncio WriteTransport write_eof7312107
Ref: 274b7312107
Node: 数据报传输7312375
Ref: library/asyncio-protocol datagram-transports7312478
Ref: 27527312478
Ref: library/asyncio-protocol asyncio DatagramTransport sendto7312526
Ref: 27537312526
Ref: library/asyncio-protocol asyncio DatagramTransport abort7312884
Ref: 27547312884
Node: 子进程传输7313192
Ref: library/asyncio-protocol asyncio-subprocess-transports7313274
Ref: 26ae7313274
Ref: library/asyncio-protocol subprocess-transports7313274
Ref: 27557313274
Ref: library/asyncio-protocol asyncio SubprocessTransport get_pid7313322
Ref: 27567313322
Ref: library/asyncio-protocol asyncio SubprocessTransport get_pipe_transport7313428
Ref: 27577313428
Ref: library/asyncio-protocol asyncio SubprocessTransport get_returncode7314068
Ref: 27587314068
Ref: library/asyncio-protocol asyncio SubprocessTransport kill7314290
Ref: 27597314290
Ref: library/asyncio-protocol asyncio SubprocessTransport send_signal7314564
Ref: 275b7314564
Ref: library/asyncio-protocol asyncio SubprocessTransport terminate7314730
Ref: 275a7314730
Ref: library/asyncio-protocol asyncio SubprocessTransport close7315039
Ref: 275c7315039
Node: 协议7315256
Ref: library/asyncio-protocol asyncio-protocol7315348
Ref: 26fa7315348
Ref: library/asyncio-protocol protocols7315348
Ref: 27357315348
Ref: 协议-Footnote-17316048
Node: 基础协议7316125
Ref: library/asyncio-protocol base-protocols7316204
Ref: 275d7316204
Ref: library/asyncio-protocol asyncio BaseProtocol7316247
Ref: 27397316247
Ref: library/asyncio-protocol asyncio Protocol7316339
Ref: 273a7316339
Ref: library/asyncio-protocol asyncio BufferedProtocol7316458
Ref: 3eb7316458
Ref: library/asyncio-protocol asyncio DatagramProtocol7316596
Ref: 273b7316596
Ref: library/asyncio-protocol asyncio SubprocessProtocol7316704
Ref: 271a7316704
Node: 基础协议<2>7316835
Ref: library/asyncio-protocol base-protocol7316935
Ref: 275e7316935
Ref: library/asyncio-protocol asyncio BaseProtocol connection_made7317220
Ref: 26fc7317220
Ref: library/asyncio-protocol asyncio BaseProtocol connection_lost7317424
Ref: 27407317424
Ref: library/asyncio-protocol asyncio BaseProtocol pause_writing7317894
Ref: 274e7317894
Ref: library/asyncio-protocol asyncio BaseProtocol resume_writing7318010
Ref: 274f7318010
Node: 流式协议7318474
Ref: library/asyncio-protocol streaming-protocols7318577
Ref: 275f7318577
Ref: library/asyncio-protocol asyncio Protocol data_received7318959
Ref: 27477318959
Ref: library/asyncio-protocol asyncio Protocol eof_received7319578
Ref: 27607319578
Node: 缓冲流协议7320373
Ref: library/asyncio-protocol buffered-streaming-protocols7320476
Ref: 27617320476
Ref: library/asyncio-protocol asyncio BufferedProtocol get_buffer7321031
Ref: 27627321031
Ref: library/asyncio-protocol asyncio BufferedProtocol buffer_updated7321488
Ref: 27637321488
Ref: library/asyncio-protocol asyncio BufferedProtocol eof_received7321661
Ref: 27647321661
Node: 数据报协议7322227
Ref: library/asyncio-protocol datagram-protocols7322333
Ref: 27657322333
Ref: library/asyncio-protocol asyncio DatagramProtocol datagram_received7322501
Ref: 27667322501
Ref: library/asyncio-protocol asyncio DatagramProtocol error_received7322749
Ref: 27677322749
Node: 子进程协议7323652
Ref: library/asyncio-protocol asyncio-subprocess-protocols7323734
Ref: 26af7323734
Ref: library/asyncio-protocol subprocess-protocols7323734
Ref: 27687323734
Ref: library/asyncio-protocol asyncio SubprocessProtocol pipe_data_received7323940
Ref: 27697323940
Ref: library/asyncio-protocol asyncio SubprocessProtocol pipe_connection_lost7324207
Ref: 276a7324207
Ref: library/asyncio-protocol asyncio SubprocessProtocol process_exited7324400
Ref: 276b7324400
Node: 示例<22>7324493
Ref: library/asyncio-protocol examples7324570
Ref: 273c7324570
Node: TCP 回显服务器7324835
Ref: library/asyncio-protocol asyncio-example-tcp-echo-server-protocol7324929
Ref: 26847324929
Ref: library/asyncio-protocol tcp-echo-server7324929
Ref: 276c7324929
Node: TCP 回显客户端7326210
Ref: library/asyncio-protocol asyncio-example-tcp-echo-client-protocol7326332
Ref: 26817326332
Ref: library/asyncio-protocol tcp-echo-client7326332
Ref: 276d7326332
Node: UDP 回显服务器7327891
Ref: library/asyncio-protocol asyncio-udp-echo-server-protocol7328013
Ref: 27007328013
Ref: library/asyncio-protocol udp-echo-server7328013
Ref: 276e7328013
Node: UDP 回显客户端7329165
Ref: library/asyncio-protocol asyncio-udp-echo-client-protocol7329295
Ref: 26ff7329295
Ref: library/asyncio-protocol udp-echo-client7329295
Ref: 276f7329295
Node: 链接已存在的套接字7330815
Ref: library/asyncio-protocol asyncio-example-create-connection7330969
Ref: 26887330969
Ref: library/asyncio-protocol connecting-existing-sockets7330969
Ref: 27707330969
Node: loop subprocess_exec 与 SubprocessProtocol7332864
Ref: library/asyncio-protocol asyncio-example-subprocess-proto7332990
Ref: 26c67332990
Ref: library/asyncio-protocol loop-subprocess-exec-and-subprocessprotocol7332990
Ref: 27717332990
Node: 策略7334768
Ref: library/asyncio-policy doc7334878
Ref: 27727334878
Ref: library/asyncio-policy asyncio-policies7334878
Ref: 26e57334878
Ref: library/asyncio-policy policies7334878
Ref: 27737334878
Node: 获取和设置策略7335600
Ref: library/asyncio-policy getting-and-setting-the-policy7335685
Ref: 27757335685
Ref: library/asyncio-policy asyncio get_event_loop_policy7335806
Ref: 27767335806
Ref: library/asyncio-policy asyncio set_event_loop_policy7335892
Ref: 27777335892
Node: 策略对象7336062
Ref: library/asyncio-policy policy-objects7336171
Ref: 27787336171
Ref: library/asyncio-policy asyncio AbstractEventLoopPolicy7336259
Ref: 27747336259
Ref: library/asyncio-policy asyncio AbstractEventLoopPolicy get_event_loop7336341
Ref: 27797336341
Ref: library/asyncio-policy asyncio AbstractEventLoopPolicy set_event_loop7336615
Ref: 277a7336615
Ref: library/asyncio-policy asyncio AbstractEventLoopPolicy new_event_loop7336726
Ref: 277b7336726
Ref: library/asyncio-policy asyncio AbstractEventLoopPolicy get_child_watcher7336881
Ref: 277c7336881
Ref: library/asyncio-policy asyncio AbstractEventLoopPolicy set_child_watcher7337111
Ref: 277e7337111
Ref: library/asyncio-policy asyncio DefaultEventLoopPolicy7337296
Ref: 277f7337296
Ref: library/asyncio-policy asyncio WindowsSelectorEventLoopPolicy7337675
Ref: 27807337675
Ref: library/asyncio-policy asyncio WindowsProactorEventLoopPolicy7337873
Ref: 27817337873
Node: 进程监视器7338067
Ref: library/asyncio-policy asyncio-watchers7338170
Ref: 26c37338170
Ref: library/asyncio-policy process-watchers7338170
Ref: 27827338170
Ref: library/asyncio-policy asyncio get_child_watcher7338920
Ref: 27867338920
Ref: library/asyncio-policy asyncio set_child_watcher7339011
Ref: 27877339011
Ref: library/asyncio-policy asyncio AbstractChildWatcher7339387
Ref: 277d7339387
Ref: library/asyncio-policy asyncio AbstractChildWatcher add_child_handler7339429
Ref: 27887339429
Ref: library/asyncio-policy asyncio AbstractChildWatcher remove_child_handler7339795
Ref: 27897339795
Ref: library/asyncio-policy asyncio AbstractChildWatcher attach_loop7340013
Ref: 278a7340013
Ref: library/asyncio-policy asyncio AbstractChildWatcher is_active7340301
Ref: 278b7340301
Ref: library/asyncio-policy asyncio AbstractChildWatcher close7340549
Ref: 278c7340549
Ref: library/asyncio-policy asyncio ThreadedChildWatcher7340684
Ref: 26c47340684
Ref: library/asyncio-policy asyncio MultiLoopChildWatcher7341137
Ref: 27837341137
Ref: library/asyncio-policy asyncio SafeChildWatcher7341742
Ref: 27847341742
Ref: library/asyncio-policy asyncio FastChildWatcher7342325
Ref: 27857342325
Ref: library/asyncio-policy asyncio PidfdChildWatcher7342749
Ref: 18e7342749
Node: 自定义策略7343288
Ref: library/asyncio-policy custom-policies7343370
Ref: 278d7343370
Node: 平台支持7343941
Ref: library/asyncio-platforms doc7344056
Ref: 278e7344056
Ref: library/asyncio-platforms asyncio-platform-support7344056
Ref: 27097344056
Ref: library/asyncio-platforms platform-support7344056
Ref: 278f7344056
Node: 所有平台7344311
Ref: library/asyncio-platforms all-platforms7344392
Ref: 27907344392
Node: Windows<55>7344546
Ref: library/asyncio-platforms windows7344645
Ref: 27917344645
Ref: Windows<55>-Footnote-17346349
Ref: Windows<55>-Footnote-27346432
Ref: Windows<55>-Footnote-37346514
Ref: Windows<55>-Footnote-47346595
Node: Windows的子进程支持7346658
Ref: library/asyncio-platforms asyncio-windows-subprocess7346731
Ref: 26ab7346731
Ref: library/asyncio-platforms subprocess-support-on-windows7346731
Ref: 27937346731
Node: macOS<30>7347074
Ref: library/asyncio-platforms macos7347152
Ref: 27947347152
Node: 高层级 API 索引7347762
Ref: library/asyncio-api-index doc7347891
Ref: 27967347891
Ref: library/asyncio-api-index high-level-api-index7347891
Ref: 27977347891
Node: Tasks7348143
Ref: library/asyncio-api-index tasks7348226
Ref: 27987348226
Node: 队列集<2>7351198
Ref: library/asyncio-api-index queues7351302
Ref: 27997351302
Node: 子进程集7352089
Ref: library/asyncio-api-index subprocesses7352194
Ref: 279a7352194
Node: 流<2>7352750
Ref: library/asyncio-api-index streams7352849
Ref: 279b7352849
Node: 同步7354192
Ref: library/asyncio-api-index synchronization7354289
Ref: 279c7354289
Node: 异常<10>7355372
Ref: library/asyncio-api-index exceptions7355454
Ref: 279d7355454
Node: 低层级 API 索引7356348
Ref: library/asyncio-llapi-index doc7356483
Ref: 279e7356483
Ref: library/asyncio-llapi-index low-level-api-index7356483
Ref: 279f7356483
Node: 获取事件循环7356739
Ref: library/asyncio-llapi-index obtaining-the-event-loop7356847
Ref: 27a07356847
Node: 事件循环方法集<2>7357788
Ref: library/asyncio-llapi-index event-loop-methods7357914
Ref: 27a17357914
Node: 传输<2>7368891
Ref: library/asyncio-llapi-index transports7369008
Ref: 27a27369008
Node: 协议<2>7374438
Ref: library/asyncio-llapi-index protocols7374549
Ref: 27a37374549
Node: 事件循环策略7377592
Ref: library/asyncio-llapi-index event-loop-policies7377685
Ref: 27a47377685
Node: 用 asyncio 开发7378456
Ref: library/asyncio-dev doc7378562
Ref: 27a57378562
Ref: library/asyncio-dev asyncio-dev7378562
Ref: 27a67378562
Ref: library/asyncio-dev developing-with-asyncio7378562
Ref: 27a77378562
Node: Debug 模式7378911
Ref: library/asyncio-dev asyncio-debug-mode7379008
Ref: 148e7379008
Ref: library/asyncio-dev debug-mode7379008
Ref: 27a87379008
Node: 并发性和多线程7380500
Ref: library/asyncio-dev asyncio-multithreading7380627
Ref: 26557380627
Ref: library/asyncio-dev concurrency-and-multithreading7380627
Ref: 27ab7380627
Node: 运行阻塞的代码7382825
Ref: library/asyncio-dev asyncio-handle-blocking7382949
Ref: 27ac7382949
Ref: library/asyncio-dev running-blocking-code7382949
Ref: 27ad7382949
Node: 日志<2>7383376
Ref: library/asyncio-dev asyncio-logger7383512
Ref: 27a97383512
Ref: library/asyncio-dev logging7383512
Ref: 27ae7383512
Node: 检测 never-awaited 协同程序7383788
Ref: library/asyncio-dev asyncio-coroutine-not-scheduled7383927
Ref: 27aa7383927
Ref: library/asyncio-dev detect-never-awaited-coroutines7383927
Ref: 27af7383927
Node: 检测就再也没异常7384937
Ref: library/asyncio-dev detect-never-retrieved-exceptions7385058
Ref: 27b07385058
Ref: 检测就再也没异常-Footnote-17386591
Node: socket --- 底层网络接口7386655
Ref: library/socket doc7386829
Ref: 27b17386829
Ref: library/socket module-socket7386829
Ref: ef7386829
Ref: library/socket socket-low-level-networking-interface7386829
Ref: 27b27386829
Ref: socket --- 底层网络接口-Footnote-17388008
Node: 套接字协议族7388073
Ref: library/socket socket-families7388181
Ref: 27b37388181
Ref: library/socket host-port7389267
Ref: 27b47389267
Ref: 套接字协议族-Footnote-17397995
Node: 模块内容<4>7398044
Ref: library/socket module-contents7398176
Ref: 27ba7398176
Node: 异常<11>7398338
Ref: library/socket exceptions7398418
Ref: 27bb7398418
Ref: library/socket socket error7398449
Ref: a767398449
Ref: library/socket socket herror7398621
Ref: 27bc7398621
Ref: library/socket socket gaierror7399159
Ref: 27bd7399159
Ref: library/socket socket timeout7399659
Ref: cd97399659
Ref: 异常<11>-Footnote-17400076
Node: 常数<6>7400125
Ref: library/socket constants7400223
Ref: 27bf7400223
Ref: library/socket socket AF_UNIX7400408
Ref: 26fe7400408
Ref: library/socket socket AF_INET7400433
Ref: 26f87400433
Ref: library/socket socket AF_INET67400458
Ref: 26f97400458
Ref: library/socket socket SOCK_STREAM7400718
Ref: d527400718
Ref: library/socket socket SOCK_DGRAM7400747
Ref: d517400747
Ref: library/socket socket SOCK_RAW7400775
Ref: 27c07400775
Ref: library/socket socket SOCK_RDM7400801
Ref: 27c17400801
Ref: library/socket socket SOCK_SEQPACKET7400827
Ref: 27c27400827
Ref: library/socket socket SOCK_CLOEXEC7401084
Ref: 5917401084
Ref: library/socket socket SOCK_NONBLOCK7401114
Ref: 5907401114
Ref: library/socket socket SOMAXCONN7401585
Ref: 83b7401585
Ref: library/socket socket AF_CAN7402678
Ref: 27b57402678
Ref: library/socket socket PF_CAN7402702
Ref: 27c37402702
Ref: library/socket socket CAN_BCM7402952
Ref: 9a07402952
Ref: library/socket socket CAN_RAW_FD_FRAMES7403358
Ref: 8b27403358
Ref: library/socket socket CAN_RAW_JOIN_FILTERS7403730
Ref: 1e27403730
Ref: library/socket socket CAN_ISOTP7404021
Ref: 27b67404021
Ref: library/socket socket CAN_J19397404251
Ref: 1e37404251
Ref: library/socket socket AF_PACKET7404457
Ref: 27b77404457
Ref: library/socket socket PF_PACKET7404484
Ref: 27c47404484
Ref: library/socket socket AF_RDS7404692
Ref: 27c57404692
Ref: library/socket socket PF_RDS7404716
Ref: 27c67404716
Ref: library/socket socket SOL_RDS7404740
Ref: 27c77404740
Ref: library/socket socket SIO_RCVALL7404970
Ref: 27c87404970
Ref: library/socket socket SIO_KEEPALIVE_VALS7404998
Ref: 27c97404998
Ref: library/socket socket SIO_LOOPBACK_FAST_PATH7405034
Ref: 6787405034
Ref: library/socket socket AF_ALG7405407
Ref: 67b7405407
Ref: library/socket socket SOL_ALG7405431
Ref: 27ca7405431
Ref: library/socket socket AF_VSOCK7405599
Ref: 4d97405599
Ref: library/socket socket IOCTL_VM_SOCKETS_GET_LOCAL_CID7405625
Ref: 27cb7405625
Ref: library/socket socket AF_LINK7405840
Ref: 9a17405840
Ref: library/socket socket has_ipv67405935
Ref: 27cc7405935
Ref: library/socket socket BDADDR_ANY7406043
Ref: 27cd7406043
Ref: library/socket socket BDADDR_LOCAL7406071
Ref: 27ce7406071
Ref: library/socket socket HCI_FILTER7406317
Ref: 27cf7406317
Ref: library/socket socket HCI_TIME_STAMP7406345
Ref: 27d07406345
Ref: library/socket socket HCI_DATA_DIR7406377
Ref: 27d17406377
Ref: library/socket socket AF_QIPCRTR7406642
Ref: 27b87406642
Ref: 常数<6>-Footnote-17406851
Node: 函数<6>7406902
Ref: library/socket functions7406981
Ref: 27d27406981
Node: 创建套接字7407059
Ref: library/socket creating-sockets7407141
Ref: 27d37407141
Ref: library/socket socket socket7407242
Ref: 7677407242
Ref: library/socket socket socketpair7409661
Ref: 57c7409661
Ref: library/socket socket create_connection7410350
Ref: c6f7410350
Ref: library/socket socket create_server7411437
Ref: 34b7411437
Ref: library/socket socket has_dualstack_ipv67413050
Ref: 34c7413050
Ref: library/socket socket fromfd7413231
Ref: 27d57413231
Ref: library/socket socket fromshare7414067
Ref: 58e7414067
Ref: library/socket socket SocketType7414291
Ref: 27d77414291
Node: 其他功能7414439
Ref: library/socket other-functions7414521
Ref: 27d87414521
Ref: library/socket socket close7414624
Ref: 4d77414624
Ref: library/socket socket getaddrinfo7414908
Ref: 270c7414908
Ref: library/socket socket getfqdn7417434
Ref: 27d97417434
Ref: library/socket socket gethostbyname7418047
Ref: 27da7418047
Ref: library/socket socket gethostbyname_ex7418585
Ref: fae7418585
Ref: library/socket socket gethostname7419331
Ref: 20647419331
Ref: library/socket socket gethostbyaddr7419688
Ref: fad7419688
Ref: library/socket socket getnameinfo7420342
Ref: 270d7420342
Ref: library/socket socket getprotobyname7421037
Ref: 27db7421037
Ref: library/socket socket getservbyname7421443
Ref: 27dc7421443
Ref: library/socket socket getservbyport7421841
Ref: 27dd7421841
Ref: library/socket socket ntohl7422225
Ref: 27de7422225
Ref: library/socket socket ntohs7422464
Ref: 56e7422464
Ref: library/socket socket htonl7422953
Ref: 27df7422953
Ref: library/socket socket htons7423192
Ref: 56d7423192
Ref: library/socket socket inet_aton7423681
Ref: 2367423681
Ref: library/socket socket inet_ntoa7424542
Ref: 27e07424542
Ref: library/socket socket inet_pton7425278
Ref: 2377425278
Ref: library/socket socket inet_ntop7426048
Ref: 9a27426048
Ref: library/socket socket CMSG_LEN7426993
Ref: 11597426993
Ref: library/socket socket CMSG_SPACE7427587
Ref: 11587427587
Ref: library/socket socket getdefaulttimeout7428361
Ref: 27d67428361
Ref: library/socket socket setdefaulttimeout7428608
Ref: 27be7428608
Ref: library/socket socket sethostname7428886
Ref: b5f7428886
Ref: library/socket socket if_nameindex7429196
Ref: 34d7429196
Ref: library/socket socket if_nametoindex7429996
Ref: 34e7429996
Ref: library/socket socket if_indextoname7430396
Ref: 34f7430396
Ref: library/socket socket send_fds7430807
Ref: 1e47430807
Ref: library/socket socket recv_fds7431235
Ref: 1e57431235
Ref: 其他功能-Footnote-17431760
Node: 套接字对象7431809
Ref: library/socket id17431953
Ref: 27e17431953
Ref: library/socket socket-objects7431953
Ref: 27d47431953
Ref: library/socket socket socket accept7432273
Ref: 7687432273
Ref: library/socket socket socket bind7432954
Ref: 27e27432954
Ref: library/socket socket socket close7433249
Ref: 6f77433249
Ref: library/socket socket socket connect7434112
Ref: 7697434112
Ref: library/socket socket socket connect_ex7435090
Ref: 27e47435090
Ref: library/socket socket socket detach7435645
Ref: c6e7435645
Ref: library/socket socket socket dup7435871
Ref: 27e57435871
Ref: library/socket socket socket fileno7436061
Ref: 27e67436061
Ref: library/socket socket socket get_inheritable7436404
Ref: 8ec7436404
Ref: library/socket socket socket getpeername7436649
Ref: 27417436649
Ref: library/socket socket socket getsockname7436927
Ref: 27427436927
Ref: library/socket socket socket getsockopt7437151
Ref: 6797437151
Ref: library/socket socket socket getblocking7437796
Ref: 4d67437796
Ref: library/socket socket socket gettimeout7438019
Ref: 27e77438019
Ref: library/socket socket socket ioctl7438275
Ref: 6777438275
Ref: library/socket socket socket listen7438839
Ref: 83a7438839
Ref: library/socket socket socket makefile7439202
Ref: bec7439202
Ref: library/socket socket socket recv7440222
Ref: 76a7440222
Ref: library/socket socket socket recvfrom7440881
Ref: 76b7440881
Ref: library/socket socket socket recvmsg7441703
Ref: 76c7441703
Ref: library/socket socket socket recvmsg_into7445223
Ref: b5e7445223
Ref: library/socket socket socket recvfrom_into7446794
Ref: d7b7446794
Ref: library/socket socket socket recv_into7447255
Ref: d7a7447255
Ref: library/socket socket socket send7447662
Ref: 76d7447662
Ref: library/socket socket socket sendall7448368
Ref: 76e7448368
Ref: library/socket socket socket sendto7449233
Ref: 7707449233
Ref: library/socket socket socket sendmsg7450000
Ref: 76f7450000
Ref: library/socket socket socket sendmsg_afalg7452017
Ref: 67c7452017
Ref: library/socket socket socket sendfile7452371
Ref: 8397452371
Ref: library/socket socket socket set_inheritable7453213
Ref: 8ed7453213
Ref: library/socket socket socket setblocking7453382
Ref: 206f7453382
Ref: library/socket socket socket settimeout7453915
Ref: 27b97453915
Ref: library/socket socket socket setsockopt7454581
Ref: 67a7454581
Ref: library/socket socket socket shutdown7455630
Ref: 27e37455630
Ref: library/socket socket socket share7455925
Ref: 58d7455925
Ref: library/socket socket socket family7456757
Ref: 27eb7456757
Ref: library/socket socket socket type7456815
Ref: 5927456815
Ref: library/socket socket socket proto7456868
Ref: 27ec7456868
Ref: 套接字对象-Footnote-17456958
Ref: 套接字对象-Footnote-27457007
Ref: 套接字对象-Footnote-37457056
Ref: 套接字对象-Footnote-47457130
Ref: 套接字对象-Footnote-57457179
Ref: 套接字对象-Footnote-67457228
Ref: 套接字对象-Footnote-77457277
Ref: 套接字对象-Footnote-87457326
Ref: 套接字对象-Footnote-97457375
Ref: 套接字对象-Footnote-107457424
Node: 关于套接字超时的说明7457474
Ref: library/socket notes-on-socket-timeouts7457613
Ref: 27ed7457613
Ref: library/socket socket-timeouts7457613
Ref: 27ea7457613
Node: 超时与 connect 方法7458943
Ref: library/socket timeouts-and-the-connect-method7459066
Ref: 27ee7459066
Node: 超时与 accept 方法7459471
Ref: library/socket timeouts-and-the-accept-method7459594
Ref: 27ef7459594
Node: 示例<23>7460267
Ref: library/socket example7460382
Ref: 27f07460382
Ref: library/socket socket-example7460382
Ref: 27f17460382
Ref: 示例<23>-Footnote-17468013
Node: ssl --- 套接字对象的 TLS/SSL 包装器7468062
Ref: library/ssl doc7468242
Ref: 27f27468242
Ref: library/ssl module-ssl7468242
Ref: f37468242
Ref: library/ssl ssl-tls-ssl-wrapper-for-socket-objects7468242
Ref: 27f37468242
Ref: ssl --- 套接字对象的 TLS/SSL 包装器-Footnote-17470490
Node: 方法、常量和异常处理7470552
Ref: library/ssl functions-constants-and-exceptions7470685
Ref: 27f47470685
Node: 套接字创建7470883
Ref: library/ssl socket-creation7470989
Ref: 27f57470989
Node: 上下文创建7472732
Ref: library/ssl context-creation7472857
Ref: 27f67472857
Ref: library/ssl ssl create_default_context7472995
Ref: 9a77472995
Ref: 上下文创建-Footnote-17475596
Node: 异常<12>7475641
Ref: library/ssl exceptions7475763
Ref: 27fc7475763
Ref: library/ssl ssl SSLError7475794
Ref: cda7475794
Ref: library/ssl ssl SSLError library7476266
Ref: b707476266
Ref: library/ssl ssl SSLError reason7476536
Ref: b717476536
Ref: library/ssl ssl SSLZeroReturnError7476788
Ref: 27fd7476788
Ref: library/ssl ssl SSLWantReadError7477042
Ref: 8457477042
Ref: library/ssl ssl SSLWantWriteError7477323
Ref: 8467477323
Ref: library/ssl ssl SSLSyscallError7477605
Ref: 27ff7477605
Ref: library/ssl ssl SSLEOFError7477856
Ref: 28007477856
Ref: library/ssl ssl SSLCertVerificationError7478075
Ref: 4e37478075
Ref: library/ssl ssl SSLCertVerificationError verify_code7478220
Ref: 28017478220
Ref: library/ssl ssl SSLCertVerificationError verify_message7478325
Ref: 28027478325
Ref: library/ssl ssl CertificateError7478424
Ref: 28037478424
Node: 随机生成7478610
Ref: library/ssl random-generation7478729
Ref: 28047478729
Ref: library/ssl ssl RAND_bytes7478770
Ref: b677478770
Ref: library/ssl ssl RAND_pseudo_bytes7479424
Ref: b687479424
Ref: library/ssl ssl RAND_status7480220
Ref: 28057480220
Ref: library/ssl ssl RAND_egd7480519
Ref: 28077480519
Ref: library/ssl ssl RAND_add7481152
Ref: 28067481152
Ref: 随机生成-Footnote-17481553
Ref: 随机生成-Footnote-27481647
Node: 证书处理7481696
Ref: library/ssl certificate-handling7481814
Ref: 28087481814
Ref: library/ssl ssl match_hostname7481855
Ref: 4e27481855
Ref: library/ssl ssl cert_time_to_seconds7483593
Ref: 8477483593
Ref: library/ssl ssl get_server_certificate7484480
Ref: b727484480
Ref: library/ssl ssl DER_cert_to_PEM_cert7485402
Ref: 280a7485402
Ref: library/ssl ssl PEM_cert_to_DER_cert7485573
Ref: 280b7485573
Ref: library/ssl ssl get_default_verify_paths7485742
Ref: 9a87485742
Ref: library/ssl ssl enum_certificates7486681
Ref: 9b47486681
Ref: library/ssl ssl enum_crls7487556
Ref: 9b57487556
Ref: library/ssl ssl wrap_socket7488099
Ref: 5707488099
Ref: 证书处理-Footnote-17489617
Ref: 证书处理-Footnote-27489666
Ref: 证书处理-Footnote-37489715
Ref: 证书处理-Footnote-47489764
Ref: 证书处理-Footnote-57489813
Node: 常量<3>7489862
Ref: library/ssl constants7489959
Ref: 280e7489959
Ref: library/ssl ssl CERT_NONE7490127
Ref: 280f7490127
Ref: library/ssl ssl CERT_OPTIONAL7490747
Ref: 28117490747
Ref: library/ssl ssl CERT_REQUIRED7491556
Ref: 27fa7491556
Ref: library/ssl ssl VerifyMode7492564
Ref: 28137492564
Ref: library/ssl ssl VERIFY_DEFAULT7492677
Ref: 9ad7492677
Ref: library/ssl ssl VERIFY_CRL_CHECK_LEAF7492908
Ref: 9ae7492908
Ref: library/ssl ssl VERIFY_CRL_CHECK_CHAIN7493331
Ref: 9af7493331
Ref: library/ssl ssl VERIFY_X509_STRICT7493528
Ref: 9b07493528
Ref: library/ssl ssl VERIFY_X509_TRUSTED_FIRST7493704
Ref: 28147493704
Ref: library/ssl ssl VerifyFlags7493969
Ref: 28157493969
Ref: library/ssl ssl PROTOCOL_TLS7494086
Ref: 27f77494086
Ref: library/ssl ssl PROTOCOL_TLS_CLIENT7494291
Ref: 28107494291
Ref: library/ssl ssl PROTOCOL_TLS_SERVER7494583
Ref: 28167494583
Ref: library/ssl ssl PROTOCOL_SSLv237494783
Ref: 28177494783
Ref: library/ssl ssl PROTOCOL_SSLv27494925
Ref: 28187494925
Ref: library/ssl ssl PROTOCOL_SSLv37495251
Ref: 28097495251
Ref: library/ssl ssl PROTOCOL_TLSv17495702
Ref: 28197495702
Ref: library/ssl ssl PROTOCOL_TLSv1_17495985
Ref: 9a57495985
Ref: library/ssl ssl PROTOCOL_TLSv1_27496332
Ref: 9a67496332
Ref: library/ssl ssl OP_ALL7496802
Ref: 281a7496802
Ref: library/ssl ssl OP_NO_SSLv27497032
Ref: c717497032
Ref: library/ssl ssl OP_NO_SSLv37497280
Ref: 27f87497280
Ref: library/ssl ssl OP_NO_TLSv17497528
Ref: 281b7497528
Ref: library/ssl ssl OP_NO_TLSv1_17497913
Ref: 281c7497913
Ref: library/ssl ssl OP_NO_TLSv1_27498238
Ref: 281d7498238
Ref: library/ssl ssl OP_NO_TLSv1_37498563
Ref: 281e7498563
Ref: library/ssl ssl OP_NO_RENEGOTIATION7499076
Ref: 281f7499076
Ref: library/ssl ssl OP_CIPHER_SERVER_PREFERENCE7499358
Ref: b737499358
Ref: library/ssl ssl OP_SINGLE_DH_USE7499584
Ref: 28207499584
Ref: library/ssl ssl OP_SINGLE_ECDH_USE7499817
Ref: 28217499817
Ref: library/ssl ssl OP_ENABLE_MIDDLEBOX_COMPAT7500054
Ref: 28227500054
Ref: library/ssl ssl OP_NO_COMPRESSION7500323
Ref: b6e7500323
Ref: library/ssl ssl Options7500547
Ref: 28237500547
Ref: library/ssl ssl OP_NO_TICKET7500632
Ref: 28247500632
Ref: library/ssl ssl OP_IGNORE_UNEXPECTED_EOF7500727
Ref: fa57500727
Ref: library/ssl ssl HAS_ALPN7500898
Ref: 8427500898
Ref: library/ssl ssl HAS_NEVER_CHECK_COMMON_NAME7501063
Ref: 28257501063
Ref: library/ssl ssl HAS_ECDH7501283
Ref: 28267501283
Ref: library/ssl ssl HAS_SNI7501510
Ref: 28277501510
Ref: library/ssl ssl HAS_NPN7501676
Ref: 28287501676
Ref: library/ssl ssl HAS_SSLv27501974
Ref: 28297501974
Ref: library/ssl ssl HAS_SSLv37502089
Ref: 282a7502089
Ref: library/ssl ssl HAS_TLSv17502204
Ref: 282b7502204
Ref: library/ssl ssl HAS_TLSv1_17502319
Ref: 4ee7502319
Ref: library/ssl ssl HAS_TLSv1_27502436
Ref: 282c7502436
Ref: library/ssl ssl HAS_TLSv1_37502553
Ref: 282d7502553
Ref: library/ssl ssl CHANNEL_BINDING_TYPES7502670
Ref: 282e7502670
Ref: library/ssl ssl OPENSSL_VERSION7502896
Ref: c727502896
Ref: library/ssl ssl OPENSSL_VERSION_INFO7503085
Ref: c737503085
Ref: library/ssl ssl OPENSSL_VERSION_NUMBER7503287
Ref: c747503287
Ref: library/ssl ssl ALERT_DESCRIPTION_HANDSHAKE_FAILURE7503541
Ref: 282f7503541
Ref: library/ssl ssl ALERT_DESCRIPTION_INTERNAL_ERROR7503591
Ref: 28307503591
Ref: library/ssl ssl AlertDescription7503948
Ref: 28317503948
Ref: library/ssl ssl Purpose SERVER_AUTH7504080
Ref: 9b27504080
Ref: library/ssl ssl Purpose CLIENT_AUTH7504373
Ref: 9b37504373
Ref: library/ssl ssl SSLErrorNumber7504669
Ref: 28327504669
Ref: library/ssl ssl TLSVersion7504791
Ref: 28337504791
Ref: library/ssl ssl TLSVersion MINIMUM_SUPPORTED7505008
Ref: 28347505008
Ref: library/ssl ssl TLSVersion MAXIMUM_SUPPORTED7505050
Ref: 28357505050
Ref: library/ssl ssl TLSVersion SSLv37505258
Ref: 28367505258
Ref: library/ssl ssl TLSVersion TLSv17505288
Ref: 28377505288
Ref: library/ssl ssl TLSVersion TLSv1_17505318
Ref: 28387505318
Ref: library/ssl ssl TLSVersion TLSv1_27505350
Ref: 28397505350
Ref: library/ssl ssl TLSVersion TLSv1_37505382
Ref: 283a7505382
Ref: 常量<3>-Footnote-17505479
Ref: 常量<3>-Footnote-27505528
Ref: 常量<3>-Footnote-37505577
Ref: 常量<3>-Footnote-47505655
Ref: 常量<3>-Footnote-57505704
Node: SSL 套接字7505797
Ref: library/ssl ssl-sockets7505952
Ref: 283b7505952
Ref: library/ssl ssl SSLSocket7505996
Ref: 1927505996
Ref: library/ssl ssl SSLSocket read7508038
Ref: 84a7508038
Ref: library/ssl ssl SSLSocket write7508857
Ref: 84b7508857
Ref: library/ssl ssl SSLSocket do_handshake7510000
Ref: 8497510000
Ref: library/ssl ssl SSLSocket getpeercert7510695
Ref: 9b77510695
Ref: library/ssl ssl SSLSocket cipher7513967
Ref: 27437513967
Ref: library/ssl ssl SSLSocket shared_ciphers7514232
Ref: 8487514232
Ref: library/ssl ssl SSLSocket compression7514682
Ref: b6d7514682
Ref: library/ssl ssl SSLSocket get_channel_binding7515016
Ref: b6c7515016
Ref: library/ssl ssl SSLSocket selected_alpn_protocol7515584
Ref: 8417515584
Ref: library/ssl ssl SSLSocket selected_npn_protocol7515951
Ref: 283e7515951
Ref: library/ssl ssl SSLSocket unwrap7516334
Ref: 283c7516334
Ref: library/ssl ssl SSLSocket verify_client_post_handshake7516677
Ref: 3527516677
Ref: library/ssl ssl SSLSocket version7517529
Ref: 8447517529
Ref: library/ssl ssl SSLSocket pending7517941
Ref: 283f7517941
Ref: library/ssl ssl SSLSocket context7518045
Ref: 283d7518045
Ref: library/ssl ssl SSLSocket server_side7518388
Ref: 28407518388
Ref: library/ssl ssl SSLSocket server_hostname7518567
Ref: 4e67518567
Ref: library/ssl ssl SSLSocket session7519039
Ref: 28417519039
Ref: library/ssl ssl SSLSocket session_reused7519355
Ref: 28427519355
Ref: SSL 套接字-Footnote-17519453
Ref: SSL 套接字-Footnote-27519502
Node: SSL 上下文7519551
Ref: library/ssl ssl-contexts7519682
Ref: 28437519682
Ref: library/ssl ssl SSLContext7519965
Ref: 4e97519965
Ref: library/ssl ssl SSLContext cert_store_stats7523863
Ref: 9aa7523863
Ref: library/ssl ssl SSLContext load_cert_chain7524256
Ref: b697524256
Ref: library/ssl ssl SSLContext load_default_certs7525649
Ref: 9b17525649
Ref: library/ssl ssl SSLContext load_verify_locations7526431
Ref: 8d87526431
Ref: library/ssl ssl SSLContext get_ca_certs7527599
Ref: 9ab7527599
Ref: library/ssl ssl SSLContext get_ciphers7528224
Ref: 6837528224
Ref: library/ssl ssl SSLContext set_default_verify_paths7530378
Ref: 9a97530378
Ref: library/ssl ssl SSLContext set_ciphers7530811
Ref: 280d7530811
Ref: library/ssl ssl SSLContext set_alpn_protocols7531440
Ref: 8407531440
Ref: library/ssl ssl SSLContext set_npn_protocols7532268
Ref: b6f7532268
Ref: library/ssl ssl SSLContext sni_callback7532932
Ref: fba7532932
Ref: library/ssl ssl SSLContext set_servername_callback7535240
Ref: 9b67535240
Ref: library/ssl ssl SSLContext load_dh_params7535879
Ref: b6a7535879
Ref: library/ssl ssl SSLContext set_ecdh_curve7536382
Ref: b6b7536382
Ref: library/ssl ssl SSLContext wrap_socket7537095
Ref: 4ea7537095
Ref: library/ssl ssl SSLContext sslsocket_class7539653
Ref: 28457539653
Ref: library/ssl ssl SSLContext wrap_bio7539922
Ref: 4eb7539922
Ref: library/ssl ssl SSLContext sslobject_class7540611
Ref: 28467540611
Ref: library/ssl ssl SSLContext session_stats7540877
Ref: 28477540877
Ref: library/ssl ssl SSLContext check_hostname7541291
Ref: 28127541291
Ref: library/ssl ssl SSLContext keylog_filename7542818
Ref: 27fb7542818
Ref: library/ssl ssl SSLContext maximum_version7543321
Ref: 4ed7543321
Ref: library/ssl ssl SSLContext minimum_version7544249
Ref: 4ec7544249
Ref: library/ssl ssl SSLContext num_tickets7544598
Ref: 28487544598
Ref: library/ssl ssl SSLContext options7544923
Ref: 280c7544923
Ref: library/ssl ssl SSLContext post_handshake_auth7545620
Ref: 3517545620
Ref: library/ssl ssl SSLContext protocol7546572
Ref: 28497546572
Ref: library/ssl ssl SSLContext hostname_checks_common_name7546685
Ref: 4e47546685
Ref: library/ssl ssl SSLContext verify_flags7547154
Ref: 9ac7547154
Ref: library/ssl ssl SSLContext verify_mode7547706
Ref: 27f97547706
Ref: SSL 上下文-Footnote-17548199
Ref: SSL 上下文-Footnote-27548345
Ref: SSL 上下文-Footnote-37548437
Ref: SSL 上下文-Footnote-47548530
Ref: SSL 上下文-Footnote-57548676
Ref: SSL 上下文-Footnote-67548768
Ref: SSL 上下文-Footnote-77548861
Ref: SSL 上下文-Footnote-87548949
Ref: SSL 上下文-Footnote-97549014
Ref: SSL 上下文-Footnote-107549063
Ref: SSL 上下文-Footnote-117549142
Ref: SSL 上下文-Footnote-127549192
Ref: SSL 上下文-Footnote-137549269
Node: 证书7549346
Ref: library/ssl certificates7549474
Ref: 284a7549474
Ref: library/ssl ssl-certificates7549474
Ref: 28447549474
Ref: 证书-Footnote-17551562
Node: 证书链7551611
Ref: library/ssl certificate-chains7551681
Ref: 284b7551681
Node: CA 证书7552784
Ref: library/ssl ca-certificates7552887
Ref: 284c7552887
Node: 合并的密钥和证书7553442
Ref: library/ssl combined-key-and-certificate7553551
Ref: 284d7553551
Node: 自签名证书7554128
Ref: library/ssl self-signed-certificates7554219
Ref: 284e7554219
Node: 示例<24>7555785
Ref: library/ssl examples7555933
Ref: 284f7555933
Node: 检测 SSL 支持7556041
Ref: library/ssl testing-for-ssl-support7556129
Ref: 28507556129
Node: 客户端操作7556418
Ref: library/ssl client-side-operation7556533
Ref: 28517556533
Node: 服务器端操作7561118
Ref: library/ssl server-side-operation7561207
Ref: 28527561207
Node: 关于非阻塞套接字的说明7563186
Ref: library/ssl notes-on-non-blocking-sockets7563348
Ref: 28537563348
Ref: library/ssl ssl-nonblocking7563348
Ref: 27fe7563348
Node: 内存 BIO 支持<2>7566066
Ref: library/ssl memory-bio-support7566228
Ref: 28557566228
Ref: library/ssl ssl SSLObject7567297
Ref: 4e87567297
Ref: library/ssl ssl MemoryBIO7570755
Ref: 83e7570755
Ref: library/ssl ssl MemoryBIO pending7570877
Ref: 28567570877
Ref: library/ssl ssl MemoryBIO eof7570966
Ref: 28577570966
Ref: library/ssl ssl MemoryBIO read7571068
Ref: 28587571068
Ref: library/ssl ssl MemoryBIO write7571240
Ref: 28597571240
Ref: library/ssl ssl MemoryBIO write_eof7571483
Ref: 285a7571483
Node: SSL 会话7571774
Ref: library/ssl ssl-session7571918
Ref: 285b7571918
Ref: library/ssl ssl SSLSession7571978
Ref: 6827571978
Ref: library/ssl ssl SSLSession id7572061
Ref: 285c7572061
Ref: library/ssl ssl SSLSession time7572082
Ref: 285d7572082
Ref: library/ssl ssl SSLSession timeout7572105
Ref: 285e7572105
Ref: library/ssl ssl SSLSession ticket_lifetime_hint7572131
Ref: 285f7572131
Ref: library/ssl ssl SSLSession has_ticket7572170
Ref: 28607572170
Node: 安全考量<2>7572199
Ref: library/ssl security-considerations7572330
Ref: 28617572330
Ref: library/ssl ssl-security7572330
Ref: 26fd7572330
Node: 最佳默认值7572434
Ref: library/ssl best-defaults7572522
Ref: 28627572522
Node: 手动设置7573596
Ref: library/ssl manual-settings7573702
Ref: 28637573702
Node: 验证证书7573806
Ref: library/ssl verifying-certificates7573888
Ref: 28647573888
Node: 协议版本7575042
Ref: library/ssl protocol-versions7575145
Ref: 28657575145
Node: 密码选择7575893
Ref: library/ssl cipher-selection7575975
Ref: 28667575975
Ref: 密码选择-Footnote-17576586
Node: 多进程7576671
Ref: library/ssl multi-processing7576753
Ref: 28677576753
Node: TLS 1 37577277
Ref: library/ssl ssl-tlsv1-37577413
Ref: 4e77577413
Ref: library/ssl tls-1-37577413
Ref: 28687577413
Node: LibreSSL 支持7578503
Ref: library/ssl libressl-support7578615
Ref: 28697578615
Ref: library/ssl ssl-libressl7578615
Ref: 286a7578615
Ref: LibreSSL 支持-Footnote-17580089
Ref: LibreSSL 支持-Footnote-27580155
Ref: LibreSSL 支持-Footnote-37580204
Ref: LibreSSL 支持-Footnote-47580253
Ref: LibreSSL 支持-Footnote-57580302
Ref: LibreSSL 支持-Footnote-67580351
Ref: LibreSSL 支持-Footnote-77580400
Ref: LibreSSL 支持-Footnote-87580476
Ref: LibreSSL 支持-Footnote-97580525
Node: select --- 等待 I/O 完成7580583
Ref: library/select doc7580768
Ref: 286b7580768
Ref: library/select module-select7580768
Ref: e57580768
Ref: library/select select-waiting-for-i-o-completion7580768
Ref: 286c7580768
Ref: library/select select error7581764
Ref: a777581764
Ref: library/select select devpoll7581936
Ref: 9927581936
Ref: library/select select epoll7582602
Ref: 9907582602
Ref: library/select select poll7583982
Ref: 28547583982
Ref: library/select select kqueue7584269
Ref: 28707584269
Ref: library/select select kevent7584579
Ref: 28727584579
Ref: library/select select select7584839
Ref: 7667584839
Ref: library/select select PIPE_BUF7586955
Ref: c577586955
Ref: select --- 等待 I/O 完成-Footnote-17587588
Ref: select --- 等待 I/O 完成-Footnote-27587637
Node: /dev/poll 轮询对象7587686
Ref: library/select dev-poll-polling-objects7587831
Ref: 28747587831
Ref: library/select devpoll-objects7587831
Ref: 286d7587831
Ref: library/select select devpoll close7588191
Ref: 9947588191
Ref: library/select select devpoll closed7588297
Ref: 9957588297
Ref: library/select select devpoll fileno7588409
Ref: 9937588409
Ref: library/select select devpoll register7588531
Ref: 28757588531
Ref: library/select select devpoll modify7589420
Ref: 28767589420
Ref: library/select select devpoll unregister7589616
Ref: 28777589616
Ref: library/select select devpoll poll7589969
Ref: 7627589969
Ref: /dev/poll 轮询对象-Footnote-17591026
Node: 边缘触发和水平触发的轮询 epoll 对象7591075
Ref: library/select edge-and-level-trigger-polling-epoll-objects7591240
Ref: 28787591240
Ref: library/select epoll-objects7591240
Ref: 286e7591240
Ref: library/select select epoll close7594020
Ref: 9917594020
Ref: library/select select epoll closed7594113
Ref: 28797594113
Ref: library/select select epoll fileno7594200
Ref: 287a7594200
Ref: library/select select epoll fromfd7594321
Ref: 287b7594321
Ref: library/select select epoll register7594417
Ref: 287c7594417
Ref: library/select select epoll modify7594525
Ref: 287d7594525
Ref: library/select select epoll unregister7594622
Ref: 22e7594622
Ref: library/select select epoll poll7594805
Ref: 7637594805
Ref: 边缘触发和水平触发的轮询 epoll 对象-Footnote-17595206
Node: Poll 对象7595255
Ref: library/select poll-objects7595411
Ref: 286f7595411
Ref: library/select polling-objects7595411
Ref: 287e7595411
Ref: library/select select poll register7595959
Ref: 287f7595959
Ref: library/select select poll modify7597794
Ref: 28807597794
Ref: library/select select poll unregister7598049
Ref: 28817598049
Ref: library/select select poll poll7598415
Ref: 7657598415
Ref: Poll 对象-Footnote-17599473
Node: Kqueue 对象7599522
Ref: library/select id17599642
Ref: 28827599642
Ref: library/select kqueue-objects7599642
Ref: 28717599642
Ref: library/select select kqueue close7599687
Ref: 28837599687
Ref: library/select select kqueue closed7599782
Ref: 28847599782
Ref: library/select select kqueue fileno7599871
Ref: 28857599871
Ref: library/select select kqueue fromfd7599993
Ref: 28867599993
Ref: library/select select kqueue control7600091
Ref: 7647600091
Ref: Kqueue 对象-Footnote-17600763
Node: Kevent 对象7600812
Ref: library/select id27600912
Ref: 28877600912
Ref: library/select kevent-objects7600912
Ref: 28737600912
Ref: library/select select kevent ident7601023
Ref: 28887601023
Ref: library/select select kevent filter7601296
Ref: 28897601296
Ref: library/select select kevent flags7602886
Ref: 288a7602886
Ref: library/select select kevent fflags7604499
Ref: 288b7604499
Ref: library/select select kevent data7608185
Ref: 288c7608185
Ref: library/select select kevent udata7608238
Ref: 288d7608238
Node: selectors --- 高级 I/O 复用库7608292
Ref: library/selectors doc7608470
Ref: 288e7608470
Ref: library/selectors module-selectors7608470
Ref: e67608470
Ref: library/selectors selectors-high-level-i-o-multiplexing7608470
Ref: 288f7608470
Ref: selectors --- 高级 I/O 复用库-Footnote-17608778
Node: 簡介<9>7608846
Ref: library/selectors introduction7608941
Ref: 28907608941
Node: 类<2>7610037
Ref: library/selectors classes7610151
Ref: 28937610151
Ref: library/selectors selectors SelectorKey7610876
Ref: 28947610876
Ref: library/selectors selectors SelectorKey fileobj7611146
Ref: 28957611146
Ref: library/selectors selectors SelectorKey fd7611211
Ref: 28967611211
Ref: library/selectors selectors SelectorKey events7611271
Ref: 28977611271
Ref: library/selectors selectors SelectorKey data7611356
Ref: 28987611356
Ref: library/selectors selectors BaseSelector7611516
Ref: 28917611516
Ref: library/selectors selectors BaseSelector register7612104
Ref: 28997612104
Ref: library/selectors selectors BaseSelector unregister7612747
Ref: 289a7612747
Ref: library/selectors selectors BaseSelector modify7613331
Ref: 5507613331
Ref: library/selectors selectors BaseSelector select7613902
Ref: 289b7613902
Ref: library/selectors selectors BaseSelector close7615106
Ref: 289c7615106
Ref: library/selectors selectors BaseSelector get_key7615295
Ref: 289d7615295
Ref: library/selectors selectors BaseSelector get_map7615560
Ref: 289e7615560
Ref: library/selectors selectors DefaultSelector7615826
Ref: 28927615826
Ref: library/selectors selectors SelectSelector7615993
Ref: 27927615993
Ref: library/selectors selectors PollSelector7616088
Ref: 54e7616088
Ref: library/selectors selectors EpollSelector7616180
Ref: 54d7616180
Ref: library/selectors selectors EpollSelector fileno7616273
Ref: 289f7616273
Ref: library/selectors selectors DevpollSelector7616421
Ref: 54f7616421
Ref: library/selectors selectors DevpollSelector fileno7616518
Ref: 28a07616518
Ref: library/selectors selectors KqueueSelector7616692
Ref: 27957616692
Ref: library/selectors selectors KqueueSelector fileno7616788
Ref: 28a17616788
Ref: 类<2>-Footnote-17616974
Node: 示例<25>7617023
Ref: library/selectors examples7617119
Ref: 28a27617119
Node: asyncore --- 异步套接字处理器7618142
Ref: library/asyncore doc7618345
Ref: 28a37618345
Ref: library/asyncore asyncore-asynchronous-socket-handler7618345
Ref: 28a47618345
Ref: library/asyncore module-asyncore7618345
Ref: a7618345
Ref: library/asyncore asyncore loop7620412
Ref: 28a57620412
Ref: library/asyncore asyncore dispatcher7621318
Ref: c917621318
Ref: library/asyncore asyncore dispatcher handle_read7622984
Ref: 28a87622984
Ref: library/asyncore asyncore dispatcher handle_write7623144
Ref: 28a97623144
Ref: library/asyncore asyncore dispatcher handle_expt7623504
Ref: 28aa7623504
Ref: library/asyncore asyncore dispatcher handle_connect7623713
Ref: 28ab7623713
Ref: library/asyncore asyncore dispatcher handle_close7623932
Ref: 28ac7623932
Ref: library/asyncore asyncore dispatcher handle_error7624020
Ref: 28ad7624020
Ref: library/asyncore asyncore dispatcher handle_accept7624198
Ref: c937624198
Ref: library/asyncore asyncore dispatcher handle_accepted7624530
Ref: c927624530
Ref: library/asyncore asyncore dispatcher readable7624956
Ref: 28a67624956
Ref: library/asyncore asyncore dispatcher writable7625278
Ref: 28a77625278
Ref: library/asyncore asyncore dispatcher create_socket7625743
Ref: 28af7625743
Ref: library/asyncore asyncore dispatcher connect7626087
Ref: 28ae7626087
Ref: library/asyncore asyncore dispatcher send7626288
Ref: 28b07626288
Ref: library/asyncore asyncore dispatcher recv7626383
Ref: 28b17626383
Ref: library/asyncore asyncore dispatcher listen7626786
Ref: 28b27626786
Ref: library/asyncore asyncore dispatcher bind7627006
Ref: 28b37627006
Ref: library/asyncore asyncore dispatcher accept7627417
Ref: c947627417
Ref: library/asyncore asyncore dispatcher close7627971
Ref: 28b47627971
Ref: library/asyncore asyncore dispatcher_with_send7628248
Ref: 28b57628248
Ref: library/asyncore asyncore file_dispatcher7628477
Ref: 28b67628477
Ref: library/asyncore asyncore file_wrapper7628913
Ref: 28b77628913
Ref: asyncore --- 异步套接字处理器-Footnote-17629406
Node: asyncore 示例基本 HTTP 客户端7629473
Ref: library/asyncore asyncore-example-17629628
Ref: 28b87629628
Ref: library/asyncore asyncore-example-basic-http-client7629628
Ref: 28b97629628
Node: asyncore 示例基本回显服务器7630639
Ref: library/asyncore asyncore-example-27630794
Ref: 28ba7630794
Ref: library/asyncore asyncore-example-basic-echo-server7630794
Ref: 28bb7630794
Node: asynchat --- 异步套接字指令/响应处理程序7631707
Ref: library/asynchat doc7631917
Ref: 28bc7631917
Ref: library/asynchat asynchat-asynchronous-socket-command-response-handler7631917
Ref: 28bd7631917
Ref: library/asynchat module-asynchat7631917
Ref: 87631917
Ref: library/asynchat asynchat async_chat7633038
Ref: 99c7633038
Ref: library/asynchat asynchat async_chat ac_in_buffer_size7633896
Ref: 28c07633896
Ref: library/asynchat asynchat async_chat ac_out_buffer_size7633995
Ref: 28c17633995
Ref: library/asynchat asynchat async_chat close_when_done7635127
Ref: 28c37635127
Ref: library/asynchat asynchat async_chat collect_incoming_data7635292
Ref: 28be7635292
Ref: library/asynchat asynchat async_chat discard_buffers7635522
Ref: 28c47635522
Ref: library/asynchat asynchat async_chat found_terminator7635690
Ref: 28bf7635690
Ref: library/asynchat asynchat async_chat get_terminator7636019
Ref: 28c57636019
Ref: library/asynchat asynchat async_chat push7636107
Ref: 28c67636107
Ref: library/asynchat asynchat async_chat push_with_producer7636406
Ref: 28c77636406
Ref: library/asynchat asynchat async_chat set_terminator7636737
Ref: 28c27636737
Ref: asynchat --- 异步套接字指令/响应处理程序-Footnote-17637724
Node: asynchat 示例7637791
Ref: library/asynchat asynchat-example7637896
Ref: 28c87637896
Ref: library/asynchat id17637896
Ref: 28c97637896
Node: signal --- 设置异步事件处理程序7640175
Ref: library/signal doc7640381
Ref: 28ca7640381
Ref: library/signal module-signal7640381
Ref: ea7640381
Ref: library/signal signal-set-handlers-for-asynchronous-events7640381
Ref: 28cb7640381
Node: 一般规则7640725
Ref: library/signal general-rules7640839
Ref: 28cc7640839
Node: 执行 Python 信号处理程序7641550
Ref: library/signal execution-of-python-signal-handlers7641655
Ref: 28cf7641655
Node: 信号与线程7642661
Ref: library/signal id17642766
Ref: 28d37642766
Ref: library/signal signals-and-threads7642766
Ref: 28d47642766
Node: 模块内容<5>7643161
Ref: library/signal module-contents7643294
Ref: 28d57643294
Ref: library/signal signal SIG_DFL7643813
Ref: 26277643813
Ref: library/signal signal SIG_IGN7644108
Ref: 26287644108
Ref: library/signal signal SIGABRT7644222
Ref: 28da7644222
Ref: library/signal signal SIGALRM7644295
Ref: 28db7644295
Ref: library/signal signal SIGBREAK7644409
Ref: 28dc7644409
Ref: library/signal signal SIGBUS7644523
Ref: 28dd7644523
Ref: library/signal signal SIGCHLD7644632
Ref: 28ce7644632
Ref: library/signal signal SIGCLD7644733
Ref: 28de7644733
Ref: library/signal signal SIGCONT7644798
Ref: 21297644798
Ref: library/signal signal SIGFPE7644914
Ref: 28d17644914
Ref: library/signal signal SIGHUP7645114
Ref: 28df7645114
Ref: library/signal signal SIGILL7645244
Ref: 28e07645244
Ref: library/signal signal SIGINT7645291
Ref: 26267645291
Ref: library/signal signal SIGKILL7645422
Ref: 28e17645422
Ref: library/signal signal SIGPIPE7645554
Ref: 28cd7645554
Ref: library/signal signal SIGSEGV7645722
Ref: 28d27645722
Ref: library/signal signal SIGTERM7645791
Ref: 26be7645791
Ref: library/signal signal SIGUSR17645839
Ref: 28e27645839
Ref: library/signal signal SIGUSR27645936
Ref: 28e37645936
Ref: library/signal signal SIGWINCH7646033
Ref: 28e47646033
Ref: library/signal signal CTRL_C_EVENT7646674
Ref: 21007646674
Ref: library/signal signal CTRL_BREAK_EVENT7646876
Ref: 21017646876
Ref: library/signal signal NSIG7647086
Ref: 28e57647086
Ref: library/signal signal ITIMER_REAL7647143
Ref: 28e67647143
Ref: library/signal signal ITIMER_VIRTUAL7647256
Ref: 28e77647256
Ref: library/signal signal ITIMER_PROF7647376
Ref: 28e87647376
Ref: library/signal signal SIG_BLOCK7647666
Ref: 28d67647666
Ref: library/signal signal SIG_UNBLOCK7647831
Ref: 28d77647831
Ref: library/signal signal SIG_SETMASK7648001
Ref: 28d87648001
Ref: library/signal signal ItimerError7648222
Ref: 28e97648222
Ref: library/signal signal alarm7648706
Ref: 28ec7648706
Ref: library/signal signal getsignal7649366
Ref: 28d97649366
Ref: library/signal signal strsignal7649879
Ref: 11657649879
Ref: library/signal signal valid_signals7650107
Ref: 28ed7650107
Ref: library/signal signal pause7650329
Ref: 28ee7650329
Ref: library/signal signal raise_signal7650696
Ref: 28ef7650696
Ref: library/signal signal pidfd_send_signal7650824
Ref: 1dc7650824
Ref: library/signal signal pthread_kill7651262
Ref: b557651262
Ref: library/signal signal pthread_sigmask7652415
Ref: b547652415
Ref: library/signal signal setitimer7653726
Ref: 28ea7653726
Ref: library/signal signal getitimer7654738
Ref: 28eb7654738
Ref: library/signal signal set_wakeup_fd7654884
Ref: 4d47654884
Ref: library/signal signal siginterrupt7656944
Ref: b597656944
Ref: library/signal signal signal7657490
Ref: b587657490
Ref: library/signal signal sigpending7658875
Ref: b567658875
Ref: library/signal signal sigwait7659284
Ref: b577659284
Ref: library/signal signal sigwaitinfo7659805
Ref: 7727659805
Ref: library/signal signal sigtimedwait7660953
Ref: 7717660953
Ref: 模块内容<5>-Footnote-17661726
Ref: 模块内容<5>-Footnote-27661775
Node: 示例<26>7661824
Ref: library/signal example7661969
Ref: 28f07661969
Ref: library/signal signal-example7661969
Ref: 28f17661969
Node: 对于 SIGPIPE 的说明7662841
Ref: library/signal note-on-sigpipe7662962
Ref: 28f27662962
Node: mmap --- 内存映射文件支持7664345
Ref: library/mmap doc7664489
Ref: 28f37664489
Ref: library/mmap mmap-memory-mapped-file-support7664489
Ref: 28f47664489
Ref: library/mmap module-mmap7664489
Ref: b37664489
Ref: library/mmap mmap mmap7666747
Ref: 31c7666747
Ref: library/mmap mmap mmap close7671443
Ref: 28f57671443
Ref: library/mmap mmap mmap closed7671629
Ref: 28f67671629
Ref: library/mmap mmap mmap find7671739
Ref: 28f77671739
Ref: library/mmap mmap mmap flush7672124
Ref: 3e57672124
Ref: library/mmap mmap mmap madvise7672914
Ref: 31d7672914
Ref: library/mmap mmap mmap move7673454
Ref: 28f97673454
Ref: library/mmap mmap mmap read7673725
Ref: aff7673725
Ref: library/mmap mmap mmap read_byte7674152
Ref: 28fa7674152
Ref: library/mmap mmap mmap readline7674293
Ref: 28fb7674293
Ref: library/mmap mmap mmap resize7674497
Ref: 28fc7674497
Ref: library/mmap mmap mmap rfind7674770
Ref: 28fd7674770
Ref: library/mmap mmap mmap seek7675156
Ref: 28fe7675156
Ref: library/mmap mmap mmap size7675507
Ref: 28ff7675507
Ref: library/mmap mmap mmap tell7675626
Ref: 29007675626
Ref: library/mmap mmap mmap write7675706
Ref: 29017675706
Ref: library/mmap mmap mmap write_byte7676307
Ref: 29027676307
Node: MADV_* 常量7676608
Ref: library/mmap madv-constants7676691
Ref: 29037676691
Ref: library/mmap madvise-constants7676691
Ref: 28f87676691
Ref: library/mmap mmap MADV_NORMAL7676736
Ref: 29047676736
Ref: library/mmap mmap MADV_RANDOM7676763
Ref: 29057676763
Ref: library/mmap mmap MADV_SEQUENTIAL7676790
Ref: 29067676790
Ref: library/mmap mmap MADV_WILLNEED7676821
Ref: 29077676821
Ref: library/mmap mmap MADV_DONTNEED7676850
Ref: 29087676850
Ref: library/mmap mmap MADV_REMOVE7676879
Ref: 29097676879
Ref: library/mmap mmap MADV_DONTFORK7676906
Ref: 290a7676906
Ref: library/mmap mmap MADV_DOFORK7676935
Ref: 290b7676935
Ref: library/mmap mmap MADV_HWPOISON7676962
Ref: 290c7676962
Ref: library/mmap mmap MADV_MERGEABLE7676991
Ref: 290d7676991
Ref: library/mmap mmap MADV_UNMERGEABLE7677021
Ref: 290e7677021
Ref: library/mmap mmap MADV_SOFT_OFFLINE7677053
Ref: 290f7677053
Ref: library/mmap mmap MADV_HUGEPAGE7677086
Ref: 29107677086
Ref: library/mmap mmap MADV_NOHUGEPAGE7677115
Ref: 29117677115
Ref: library/mmap mmap MADV_DONTDUMP7677146
Ref: 29127677146
Ref: library/mmap mmap MADV_DODUMP7677175
Ref: 29137677175
Ref: library/mmap mmap MADV_FREE7677202
Ref: 29147677202
Ref: library/mmap mmap MADV_NOSYNC7677227
Ref: 29157677227
Ref: library/mmap mmap MADV_AUTOSYNC7677254
Ref: 29167677254
Ref: library/mmap mmap MADV_NOCORE7677283
Ref: 29177677283
Ref: library/mmap mmap MADV_CORE7677310
Ref: 29187677310
Ref: library/mmap mmap MADV_PROTECT7677335
Ref: 29197677335
Node: 互联网数据处理7677563
Ref: library/netdata doc7677729
Ref: 291a7677729
Ref: library/netdata internet-data-handling7677729
Ref: 291b7677729
Ref: library/netdata netdata7677729
Ref: 291c7677729
Node: email --- 电子邮件与 MIME 处理包7678711
Ref: library/email doc7678850
Ref: 291d7678850
Ref: library/email email-an-email-and-mime-handling-package7678850
Ref: 291e7678850
Ref: library/email module-email7678850
Ref: 677678850
Ref: email --- 电子邮件与 MIME 处理包-Footnote-17684894
Ref: email --- 电子邮件与 MIME 处理包-Footnote-27684967
Ref: email --- 电子邮件与 MIME 处理包-Footnote-37685016
Ref: email --- 电子邮件与 MIME 处理包-Footnote-47685065
Ref: email --- 电子邮件与 MIME 处理包-Footnote-57685114
Ref: email --- 电子邮件与 MIME 处理包-Footnote-67685163
Ref: email --- 电子邮件与 MIME 处理包-Footnote-77685212
Ref: email --- 电子邮件与 MIME 处理包-Footnote-87685261
Ref: email --- 电子邮件与 MIME 处理包-Footnote-97685310
Node: email message 表示一封电子邮件信息7685359
Ref: library/email message doc7685526
Ref: 291f7685526
Ref: library/email message email-message-representing-an-email-message7685526
Ref: 29207685526
Ref: library/email message module-email message7685526
Ref: 707685526
Ref: library/email message email message EmailMessage7687841
Ref: 63c7687841
Ref: library/email message email message EmailMessage as_string7688335
Ref: 29237688335
Ref: library/email message email message EmailMessage __str__7690052
Ref: 29247690052
Ref: library/email message email message EmailMessage as_bytes7690477
Ref: 29257690477
Ref: library/email message email message EmailMessage __bytes__7691581
Ref: 29267691581
Ref: library/email message email message EmailMessage is_multipart7691768
Ref: 29277691768
Ref: library/email message email message EmailMessage set_unixfrom7692503
Ref: 29287692503
Ref: library/email message email message EmailMessage get_unixfrom7692728
Ref: 292a7692728
Ref: library/email message email message EmailMessage __len__7693832
Ref: 292c7693832
Ref: library/email message email message EmailMessage __contains__7693933
Ref: 292d7693933
Ref: library/email message email message EmailMessage __getitem__7694345
Ref: 292e7694345
Ref: library/email message email message EmailMessage __setitem__7694954
Ref: 29317694954
Ref: library/email message email message EmailMessage __delitem__7696039
Ref: 29327696039
Ref: library/email message email message EmailMessage keys7696245
Ref: 292b7696245
Ref: library/email message email message EmailMessage values7696343
Ref: 29337696343
Ref: library/email message email message EmailMessage items7696443
Ref: 29347696443
Ref: library/email message email message EmailMessage get7696569
Ref: 29357696569
Ref: library/email message email message EmailMessage get_all7696945
Ref: 292f7696945
Ref: library/email message email message EmailMessage add_header7697172
Ref: 29367697172
Ref: library/email message email message EmailMessage replace_header7698983
Ref: 29377698983
Ref: library/email message email message EmailMessage get_content_type7699304
Ref: 29387699304
Ref: library/email message email message EmailMessage get_content_maintype7700184
Ref: 293a7700184
Ref: library/email message email message EmailMessage get_content_subtype7700463
Ref: 293b7700463
Ref: library/email message email message EmailMessage get_default_type7700737
Ref: 29397700737
Ref: library/email message email message EmailMessage set_default_type7701037
Ref: 293c7701037
Ref: library/email message email message EmailMessage set_param7701497
Ref: 293d7701497
Ref: library/email message email message EmailMessage del_param7703020
Ref: 293e7703020
Ref: library/email message email message EmailMessage get_filename7703464
Ref: 293f7703464
Ref: library/email message email message EmailMessage get_boundary7703969
Ref: 29417703969
Ref: library/email message email message EmailMessage set_boundary7704339
Ref: 29427704339
Ref: library/email message email message EmailMessage get_content_charset7705067
Ref: 29447705067
Ref: library/email message email message EmailMessage get_charsets7705321
Ref: 29457705321
Ref: library/email message email message EmailMessage is_attachment7705983
Ref: 29467705983
Ref: library/email message email message EmailMessage get_content_disposition7706403
Ref: 29487706403
Ref: library/email message email message EmailMessage walk7706886
Ref: 29497706886
Ref: library/email message email message EmailMessage get_body7708899
Ref: 294a7708899
Ref: library/email message email message EmailMessage iter_attachments7710923
Ref: 294b7710923
Ref: library/email message email message EmailMessage iter_parts7711815
Ref: 294c7711815
Ref: library/email message email message EmailMessage get_content7712019
Ref: 294d7712019
Ref: library/email message email message EmailMessage set_content7712405
Ref: f817712405
Ref: library/email message email message EmailMessage make_related7712785
Ref: 29507712785
Ref: library/email message email message EmailMessage make_alternative7713211
Ref: 29517713211
Ref: library/email message email message EmailMessage make_mixed7713671
Ref: 29527713671
Ref: library/email message email message EmailMessage add_related7714147
Ref: 29537714147
Ref: library/email message email message EmailMessage add_alternative7714920
Ref: 29557714920
Ref: library/email message email message EmailMessage add_attachment7715612
Ref: 29567715612
Ref: library/email message email message EmailMessage clear7716587
Ref: 29577716587
Ref: library/email message email message EmailMessage clear_content7716668
Ref: 29587716668
Ref: library/email message email message EmailMessage preamble7716898
Ref: 29597716898
Ref: library/email message email message EmailMessage epilogue7718049
Ref: 295a7718049
Ref: library/email message email message EmailMessage defects7718341
Ref: 295b7718341
Ref: library/email message email message MIMEPart7718542
Ref: 9307718542
Ref: email message 表示一封电子邮件信息-Footnote-17718924
Ref: email message 表示一封电子邮件信息-Footnote-27718996
Ref: email message 表示一封电子邮件信息-Footnote-37719190
Ref: email message 表示一封电子邮件信息-Footnote-47719239
Ref: email message 表示一封电子邮件信息-Footnote-57719288
Ref: email message 表示一封电子邮件信息-Footnote-67719337
Ref: email message 表示一封电子邮件信息-Footnote-77719386
Ref: email message 表示一封电子邮件信息-Footnote-87719435
Ref: email message 表示一封电子邮件信息-Footnote-97719484
Ref: email message 表示一封电子邮件信息-Footnote-107719533
Ref: email message 表示一封电子邮件信息-Footnote-117719583
Ref: email message 表示一封电子邮件信息-Footnote-127719633
Node: email parser 解析电子邮件信息7719683
Ref: library/email parser doc7719893
Ref: 295c7719893
Ref: library/email parser email-parser-parsing-email-messages7719893
Ref: 295d7719893
Ref: library/email parser module-email parser7719893
Ref: 727719893
Ref: email parser 解析电子邮件信息-Footnote-17722286
Node: FeedParser API7722357
Ref: library/email parser feedparser-api7722464
Ref: 295f7722464
Ref: library/email parser email parser BytesFeedParser7723759
Ref: c1b7723759
Ref: library/email parser email parser BytesFeedParser feed7724981
Ref: 29607724981
Ref: library/email parser email parser BytesFeedParser close7725462
Ref: 29617725462
Ref: library/email parser email parser FeedParser7725689
Ref: 295e7725689
Node: Parser API7726160
Ref: library/email parser parser-api7726288
Ref: 29627726288
Ref: library/email parser email parser BytesParser7726952
Ref: c1c7726952
Ref: library/email parser email parser BytesParser parse7727563
Ref: 29637727563
Ref: library/email parser email parser BytesParser parsebytes7728522
Ref: 29647728522
Ref: library/email parser email parser BytesHeaderParser7729078
Ref: adb7729078
Ref: library/email parser email parser Parser7729306
Ref: beb7729306
Ref: library/email parser email parser Parser parse7729615
Ref: 29657729615
Ref: library/email parser email parser Parser parsestr7730047
Ref: 29667730047
Ref: library/email parser email parser HeaderParser7730525
Ref: adc7730525
Ref: library/email parser email message_from_bytes7730924
Ref: c197730924
Ref: library/email parser email message_from_binary_file7731363
Ref: c1a7731363
Ref: library/email parser email message_from_string7731800
Ref: 29677731800
Ref: library/email parser email message_from_file7732172
Ref: 29687732172
Ref: Parser API-Footnote-17732861
Ref: Parser API-Footnote-27732910
Node: 附加说明7732959
Ref: library/email parser additional-notes7733064
Ref: 29697733064
Node: email generator 生成 MIME 文档7734662
Ref: library/email generator doc7734854
Ref: 296a7734854
Ref: library/email generator email-generator-generating-mime-documents7734854
Ref: 296b7734854
Ref: library/email generator module-email generator7734854
Ref: 6c7734854
Ref: library/email generator email generator BytesGenerator7736815
Ref: c1f7736815
Ref: library/email generator email generator BytesGenerator flatten7738656
Ref: 296c7738656
Ref: library/email generator email generator BytesGenerator clone7740410
Ref: 296f7740410
Ref: library/email generator email generator BytesGenerator write7740594
Ref: 296d7740594
Ref: library/email generator email generator Generator7741610
Ref: c1e7741610
Ref: library/email generator email generator Generator flatten7743381
Ref: 29707743381
Ref: library/email generator email generator Generator clone7745066
Ref: 29727745066
Ref: library/email generator email generator Generator write7745245
Ref: 29717745245
Ref: library/email generator email generator DecodedGenerator7746088
Ref: 6387746088
Ref: email generator 生成 MIME 文档-Footnote-17747482
Ref: email generator 生成 MIME 文档-Footnote-27747556
Ref: email generator 生成 MIME 文档-Footnote-37747982
Ref: email generator 生成 MIME 文档-Footnote-47748034
Ref: email generator 生成 MIME 文档-Footnote-57748083
Ref: email generator 生成 MIME 文档-Footnote-67748135
Node: email policy Policy 对象7748184
Ref: library/email policy doc7748370
Ref: 29737748370
Ref: library/email policy email-policy-policy-objects7748370
Ref: 29747748370
Ref: library/email policy module-email policy7748370
Ref: 737748370
Ref: library/email policy email policy Policy7753712
Ref: ad37753712
Ref: library/email policy email policy Policy max_line_length7754333
Ref: 29757754333
Ref: library/email policy email policy Policy linesep7754582
Ref: 29767754582
Ref: library/email policy email policy Policy cte_type7754797
Ref: 296e7754797
Ref: library/email policy email policy Policy raise_on_defect7755826
Ref: 29787755826
Ref: library/email policy email policy Policy mangle_from_7756068
Ref: 7c37756068
Ref: library/email policy email policy Policy message_factory7756405
Ref: 6397756405
Ref: library/email policy email policy Policy clone7756783
Ref: ad57756783
Ref: library/email policy email policy Policy handle_defect7757190
Ref: 297a7757190
Ref: library/email policy email policy Policy register_defect7757675
Ref: 29797757675
Ref: library/email policy email policy Policy header_max_count7758313
Ref: 297b7758313
Ref: library/email policy email policy Policy header_source_parse7759190
Ref: 297c7759190
Ref: library/email policy email policy Policy header_store_parse7760079
Ref: 297d7760079
Ref: library/email policy email policy Policy header_fetch_parse7760714
Ref: 297e7760714
Ref: library/email policy email policy Policy fold7761394
Ref: 297f7761394
Ref: library/email policy email policy Policy fold_binary7762031
Ref: 29777762031
Ref: library/email policy email policy EmailPolicy7762370
Ref: ad77762370
Ref: library/email policy email policy EmailPolicy utf87763080
Ref: 7c57763080
Ref: library/email policy email policy EmailPolicy refold_source7763467
Ref: 29807763467
Ref: library/email policy email policy EmailPolicy header_factory7764128
Ref: 29817764128
Ref: library/email policy email policy EmailPolicy content_manager7764678
Ref: 9317764678
Ref: library/email policy email policy EmailPolicy header_max_count7765310
Ref: 29837765310
Ref: library/email policy email policy EmailPolicy header_source_parse7765479
Ref: 29857765479
Ref: library/email policy email policy EmailPolicy header_store_parse7765800
Ref: 29867765800
Ref: library/email policy email policy EmailPolicy header_fetch_parse7766272
Ref: 29877766272
Ref: library/email policy email policy EmailPolicy fold7766655
Ref: 29887766655
Ref: library/email policy email policy EmailPolicy fold_binary7767718
Ref: 29897767718
Ref: library/email policy email policy default7768482
Ref: 29227768482
Ref: library/email policy email policy SMTP7768675
Ref: 298a7768675
Ref: library/email policy email policy SMTPUTF87768868
Ref: 298b7768868
Ref: library/email policy email policy HTTP7769230
Ref: 298c7769230
Ref: library/email policy email policy strict7769411
Ref: 298d7769411
Ref: library/email policy email policy Compat327770730
Ref: ad47770730
Ref: library/email policy email policy Compat32 mangle_from_7771150
Ref: 298e7771150
Ref: library/email policy email policy Compat32 header_source_parse7771304
Ref: 298f7771304
Ref: library/email policy email policy Compat32 header_store_parse7771625
Ref: 29907771625
Ref: library/email policy email policy Compat32 header_fetch_parse7771730
Ref: 29917771730
Ref: library/email policy email policy Compat32 fold7771989
Ref: 29927771989
Ref: library/email policy email policy Compat32 fold_binary7772328
Ref: 29937772328
Ref: library/email policy email policy compat327772882
Ref: 63a7772882
Ref: email policy Policy 对象-Footnote-17773074
Ref: email policy Policy 对象-Footnote-27773145
Ref: email policy Policy 对象-Footnote-37773194
Ref: email policy Policy 对象-Footnote-47773243
Ref: email policy Policy 对象-Footnote-57773292
Ref: email policy Policy 对象-Footnote-67773341
Ref: email policy Policy 对象-Footnote-77773390
Ref: email policy Policy 对象-Footnote-87773439
Ref: email policy Policy 对象-Footnote-97773510
Ref: email policy Policy 对象-Footnote-107773559
Ref: email policy Policy 对象-Footnote-117773609
Ref: email policy Policy 对象-Footnote-127773659
Node: email errors 异常和缺陷类7773709
Ref: library/email errors doc7773903
Ref: 29947773903
Ref: library/email errors email-errors-exception-and-defect-classes7773903
Ref: 29957773903
Ref: library/email errors module-email errors7773903
Ref: 6b7773903
Ref: library/email errors email errors MessageError7774158
Ref: 29967774158
Ref: library/email errors email errors MessageParseError7774362
Ref: 29977774362
Ref: library/email errors email errors HeaderParseError7774599
Ref: 29437774599
Ref: library/email errors email errors BoundaryError7775141
Ref: 29987775141
Ref: library/email errors email errors MultipartConversionError7775218
Ref: 29997775218
Ref: email errors 异常和缺陷类-Footnote-17778348
Ref: email errors 异常和缺陷类-Footnote-27778419
Node: email headerregistry 自定义标头对象7778468
Ref: library/email headerregistry doc7778675
Ref: 299b7778675
Ref: library/email headerregistry email-headerregistry-custom-header-objects7778675
Ref: 299c7778675
Ref: library/email headerregistry module-email headerregistry7778675
Ref: 6e7778675
Ref: library/email headerregistry email headerregistry BaseHeader7780195
Ref: 29307780195
Ref: library/email headerregistry email headerregistry BaseHeader name7780485
Ref: 299f7780485
Ref: library/email headerregistry email headerregistry BaseHeader defects7780711
Ref: 29a07780711
Ref: library/email headerregistry email headerregistry BaseHeader max_count7781050
Ref: 29847781050
Ref: library/email headerregistry email headerregistry BaseHeader fold7781442
Ref: 29a17781442
Ref: library/email headerregistry email headerregistry UnstructuredHeader7783460
Ref: 299e7783460
Ref: library/email headerregistry email headerregistry DateHeader7784420
Ref: 29a27784420
Ref: library/email headerregistry email headerregistry DateHeader datetime7784740
Ref: 29a37784740
Ref: library/email headerregistry email headerregistry AddressHeader7786122
Ref: 29a47786122
Ref: library/email headerregistry email headerregistry AddressHeader groups7786373
Ref: 29a57786373
Ref: library/email headerregistry email headerregistry AddressHeader addresses7786639
Ref: 29a87786639
Ref: library/email headerregistry email headerregistry SingleAddressHeader7787647
Ref: 29aa7787647
Ref: library/email headerregistry email headerregistry SingleAddressHeader address7787778
Ref: 29ab7787778
Ref: library/email headerregistry email headerregistry MIMEVersionHeader7788215
Ref: 29ac7788215
Ref: library/email headerregistry email headerregistry MIMEVersionHeader version7788557
Ref: 29ad7788557
Ref: library/email headerregistry email headerregistry MIMEVersionHeader major7788669
Ref: 29ae7788669
Ref: library/email headerregistry email headerregistry MIMEVersionHeader minor7788732
Ref: 29af7788732
Ref: library/email headerregistry email headerregistry ParameterizedMIMEHeader7788795
Ref: 29b07788795
Ref: library/email headerregistry email headerregistry ParameterizedMIMEHeader params7789133
Ref: 29b17789133
Ref: library/email headerregistry email headerregistry ContentTypeHeader7789218
Ref: 29b27789218
Ref: library/email headerregistry email headerregistry ContentTypeHeader content_type7789362
Ref: 29b37789362
Ref: library/email headerregistry email headerregistry ContentTypeHeader maintype7789461
Ref: 29b47789461
Ref: library/email headerregistry email headerregistry ContentTypeHeader subtype7789488
Ref: 29b57789488
Ref: library/email headerregistry email headerregistry ContentDispositionHeader7789514
Ref: 29b67789514
Ref: library/email headerregistry email headerregistry ContentDispositionHeader content_disposition7789671
Ref: 29b77789671
Ref: library/email headerregistry email headerregistry ContentTransferEncoding7789785
Ref: 29b87789785
Ref: library/email headerregistry email headerregistry ContentTransferEncoding cte7789898
Ref: 29b97789898
Ref: library/email headerregistry email headerregistry HeaderRegistry7790068
Ref: 299d7790068
Ref: library/email headerregistry email headerregistry HeaderRegistry map_to_type7791739
Ref: 29ba7791739
Ref: library/email headerregistry email headerregistry HeaderRegistry __getitem__7792028
Ref: 29bb7792028
Ref: library/email headerregistry email headerregistry HeaderRegistry __call__7792142
Ref: 29bc7792142
Ref: library/email headerregistry email headerregistry Address7792668
Ref: 29a97792668
Ref: library/email headerregistry email headerregistry Address display_name7793470
Ref: 29bd7793470
Ref: library/email headerregistry email headerregistry Address username7793666
Ref: 29be7793666
Ref: library/email headerregistry email headerregistry Address domain7793763
Ref: 29bf7793763
Ref: library/email headerregistry email headerregistry Address addr_spec7793832
Ref: 29c07793832
Ref: library/email headerregistry email headerregistry Address __str__7794033
Ref: 29c17794033
Ref: library/email headerregistry email headerregistry Group7794462
Ref: 29a67794462
Ref: library/email headerregistry email headerregistry Group display_name7794908
Ref: 29a77794908
Ref: library/email headerregistry email headerregistry Group addresses7795140
Ref: 29c27795140
Ref: library/email headerregistry email headerregistry Group __str__7795279
Ref: 29c37795279
Ref: email headerregistry 自定义标头对象-Footnote-17795714
Ref: email headerregistry 自定义标头对象-Footnote-27795794
Ref: email headerregistry 自定义标头对象-Footnote-37795862
Ref: email headerregistry 自定义标头对象-Footnote-47795911
Ref: email headerregistry 自定义标头对象-Footnote-57795960
Ref: email headerregistry 自定义标头对象-Footnote-67796009
Ref: email headerregistry 自定义标头对象-Footnote-77796058
Ref: email headerregistry 自定义标头对象-Footnote-87796107
Ref: email headerregistry 自定义标头对象-Footnote-97796156
Ref: email headerregistry 自定义标头对象-Footnote-107796205
Ref: email headerregistry 自定义标头对象-Footnote-117796255
Ref: email headerregistry 自定义标头对象-Footnote-127796305
Ref: email headerregistry 自定义标头对象-Footnote-137796355
Ref: email headerregistry 自定义标头对象-Footnote-147796405
Ref: email headerregistry 自定义标头对象-Footnote-157796455
Ref: email headerregistry 自定义标头对象-Footnote-167796505
Ref: email headerregistry 自定义标头对象-Footnote-177796555
Node: email contentmanager 管理 MIME 内容7796605
Ref: library/email contentmanager doc7796793
Ref: 29c47796793
Ref: library/email contentmanager email-contentmanager-managing-mime-content7796793
Ref: 29c57796793
Ref: library/email contentmanager module-email contentmanager7796793
Ref: 697796793
Ref: library/email contentmanager email contentmanager ContentManager7797036
Ref: 29c67797036
Ref: library/email contentmanager email contentmanager ContentManager get_content7797269
Ref: 294e7797269
Ref: library/email contentmanager email contentmanager ContentManager set_content7798019
Ref: 294f7798019
Ref: library/email contentmanager email contentmanager ContentManager add_get_handler7799551
Ref: 29c87799551
Ref: library/email contentmanager email contentmanager ContentManager add_set_handler7799751
Ref: 29ca7799751
Ref: email contentmanager 管理 MIME 内容-Footnote-17800117
Ref: email contentmanager 管理 MIME 内容-Footnote-27800197
Node: 内容管理器实例7800265
Ref: library/email contentmanager content-manager-instances7800362
Ref: 29cc7800362
Ref: library/email contentmanager email contentmanager raw_data_manager7800673
Ref: 29827800673
Ref: library/email contentmanager email contentmanager get_content7801314
Ref: 29c97801314
Ref: library/email contentmanager email contentmanager set_content7801972
Ref: 29cb7801972
Ref: 内容管理器实例-Footnote-17806337
Node: email 示例7806386
Ref: library/email examples doc7806601
Ref: 29cd7806601
Ref: library/email examples email-examples7806601
Ref: 9327806601
Ref: library/email examples id17806601
Ref: 29ce7806601
Ref: email 示例-Footnote-17821155
Ref: email 示例-Footnote-27821203
Node: email message Message 使用 compat32 API 来表示电子邮件消息7821277
Ref: library/email compat32-message doc7821503
Ref: 29cf7821503
Ref: library/email compat32-message compat32-message7821503
Ref: 29217821503
Ref: library/email compat32-message email-message-message-representing-an-email-message-using-the-compat32-api7821503
Ref: 29d07821503
Ref: library/email compat32-message email message Message7823755
Ref: 63b7823755
Ref: library/email compat32-message email message Message as_string7824222
Ref: 92c7824222
Ref: library/email compat32-message email message Message __str__7826191
Ref: 29d17826191
Ref: library/email compat32-message email message Message as_bytes7826363
Ref: 92d7826363
Ref: library/email compat32-message email message Message __bytes__7827788
Ref: 92e7827788
Ref: library/email compat32-message email message Message is_multipart7827998
Ref: 29477827998
Ref: library/email compat32-message email message Message set_unixfrom7828644
Ref: 29d27828644
Ref: library/email compat32-message email message Message get_unixfrom7828778
Ref: 29d37828778
Ref: library/email compat32-message email message Message attach7828920
Ref: 29547828920
Ref: library/email compat32-message email message Message get_payload7829536
Ref: c1d7829536
Ref: library/email compat32-message email message Message set_payload7832078
Ref: 29d47832078
Ref: library/email compat32-message email message Message set_charset7832516
Ref: 29d57832516
Ref: library/email compat32-message email message Message get_charset7834098
Ref: 29d67834098
Ref: library/email compat32-message email message Message __len__7835371
Ref: 29d87835371
Ref: library/email compat32-message email message Message __contains__7835460
Ref: 29d97835460
Ref: library/email compat32-message email message Message __getitem__7835838
Ref: 29da7835838
Ref: library/email compat32-message email message Message __setitem__7836333
Ref: 29dc7836333
Ref: library/email compat32-message email message Message __delitem__7836885
Ref: 29dd7836885
Ref: library/email compat32-message email message Message keys7837091
Ref: 29d77837091
Ref: library/email compat32-message email message Message values7837189
Ref: 29de7837189
Ref: library/email compat32-message email message Message items7837289
Ref: 29df7837289
Ref: library/email compat32-message email message Message get7837415
Ref: 29e07837415
Ref: library/email compat32-message email message Message get_all7837738
Ref: 29db7837738
Ref: library/email compat32-message email message Message add_header7837965
Ref: 29e17837965
Ref: library/email compat32-message email message Message replace_header7839783
Ref: 29e27839783
Ref: library/email compat32-message email message Message get_content_type7840078
Ref: 29e37840078
Ref: library/email compat32-message email message Message get_content_maintype7840882
Ref: 29e57840882
Ref: library/email compat32-message email message Message get_content_subtype7841161
Ref: 29e67841161
Ref: library/email compat32-message email message Message get_default_type7841435
Ref: 29e47841435
Ref: library/email compat32-message email message Message set_default_type7841735
Ref: 29e77841735
Ref: library/email compat32-message email message Message get_params7842005
Ref: 29e87842005
Ref: library/email compat32-message email message Message get_param7842878
Ref: 29e97842878
Ref: library/email compat32-message email message Message set_param7844744
Ref: 92f7844744
Ref: library/email compat32-message email message Message del_param7845906
Ref: 29eb7845906
Ref: library/email compat32-message email message Message set_type7846328
Ref: 29ec7846328
Ref: library/email compat32-message email message Message get_filename7847154
Ref: 29ed7847154
Ref: library/email compat32-message email message Message get_boundary7847659
Ref: 29ee7847659
Ref: library/email compat32-message email message Message set_boundary7848029
Ref: 29ef7848029
Ref: library/email compat32-message email message Message get_content_charset7848820
Ref: 29f07848820
Ref: library/email compat32-message email message Message get_charsets7849234
Ref: 29f17849234
Ref: library/email compat32-message email message Message get_content_disposition7849923
Ref: 7c47849923
Ref: library/email compat32-message email message Message walk7850321
Ref: 29f27850321
Ref: library/email compat32-message email message Message preamble7852411
Ref: 29f37852411
Ref: library/email compat32-message email message Message epilogue7853562
Ref: 29f47853562
Ref: library/email compat32-message email message Message defects7853892
Ref: 29f57853892
Ref: email message Message 使用 compat32 API 来表示电子邮件消息-Footnote-17854129
Ref: email message Message 使用 compat32 API 来表示电子邮件消息-Footnote-27854178
Ref: email message Message 使用 compat32 API 来表示电子邮件消息-Footnote-37854227
Ref: email message Message 使用 compat32 API 来表示电子邮件消息-Footnote-47854276
Ref: email message Message 使用 compat32 API 来表示电子邮件消息-Footnote-57854325
Ref: email message Message 使用 compat32 API 来表示电子邮件消息-Footnote-67854374
Ref: email message Message 使用 compat32 API 来表示电子邮件消息-Footnote-77854423
Ref: email message Message 使用 compat32 API 来表示电子邮件消息-Footnote-87854472
Ref: email message Message 使用 compat32 API 来表示电子邮件消息-Footnote-97854521
Ref: email message Message 使用 compat32 API 来表示电子邮件消息-Footnote-107854570
Ref: email message Message 使用 compat32 API 来表示电子邮件消息-Footnote-117854620
Ref: email message Message 使用 compat32 API 来表示电子邮件消息-Footnote-127854670
Node: email mime 从头创建电子邮件和 MIME 对象7854720
Ref: library/email mime doc7854962
Ref: 29f67854962
Ref: library/email mime email-mime-creating-email-and-mime-objects-from-scratch7854962
Ref: 29f77854962
Ref: library/email mime module-email mime7854962
Ref: 717854962
Ref: library/email mime email mime base MIMEBase7856158
Ref: 29f87856158
Ref: library/email mime email mime nonmultipart MIMENonMultipart7857243
Ref: f597857243
Ref: library/email mime email mime multipart MIMEMultipart7857685
Ref: 29f97857685
Ref: library/email mime email mime application MIMEApplication7858896
Ref: 29fa7858896
Ref: library/email mime email mime audio MIMEAudio7860175
Ref: 29fb7860175
Ref: library/email mime email mime image MIMEImage7861674
Ref: 299a7861674
Ref: library/email mime email mime message MIMEMessage7863192
Ref: 29fc7863192
Ref: library/email mime email mime text MIMEText7863841
Ref: 7c67863841
Ref: email mime 从头创建电子邮件和 MIME 对象-Footnote-17865375
Node: email header 国际化标头7865442
Ref: library/email header doc7865644
Ref: 29fd7865644
Ref: library/email header email-header-internationalized-headers7865644
Ref: 29fe7865644
Ref: library/email header module-email header7865644
Ref: 6d7865644
Ref: library/email header email header Header7868124
Ref: f837868124
Ref: library/email header email header Header append7869868
Ref: 29ff7869868
Ref: library/email header email header Header encode7871129
Ref: 2a007871129
Ref: library/email header email header Header __str__7872557
Ref: 2a017872557
Ref: library/email header email header Header __eq__7873016
Ref: 2a027873016
Ref: library/email header email header Header __ne__7873144
Ref: 2a037873144
Ref: library/email header email header decode_header7873337
Ref: ad87873337
Ref: library/email header email header make_header7873965
Ref: ad97873965
Ref: email header 国际化标头-Footnote-17874638
Ref: email header 国际化标头-Footnote-27874709
Ref: email header 国际化标头-Footnote-37874758
Ref: email header 国际化标头-Footnote-47874806
Ref: email header 国际化标头-Footnote-57874855
Ref: email header 国际化标头-Footnote-67874904
Ref: email header 国际化标头-Footnote-77874953
Ref: email header 国际化标头-Footnote-87875002
Ref: email header 国际化标头-Footnote-97875051
Ref: email header 国际化标头-Footnote-107875100
Ref: email header 国际化标头-Footnote-117875150
Ref: email header 国际化标头-Footnote-127875200
Ref: email header 国际化标头-Footnote-137875250
Ref: email header 国际化标头-Footnote-147875300
Ref: email header 国际化标头-Footnote-157875350
Node: email charset 表示字符集7875400
Ref: library/email charset doc7875576
Ref: 2a047875576
Ref: library/email charset email-charset-representing-character-sets7875576
Ref: 2a057875576
Ref: library/email charset module-email charset7875576
Ref: 687875576
Ref: library/email charset email charset Charset7876301
Ref: 7c77876301
Ref: library/email charset email charset Charset input_charset7877699
Ref: 2a067877699
Ref: library/email charset email charset Charset header_encoding7877952
Ref: 2a077877952
Ref: library/email charset email charset Charset body_encoding7878369
Ref: 2a087878369
Ref: library/email charset email charset Charset output_charset7878632
Ref: 2a097878632
Ref: library/email charset email charset Charset input_codec7878935
Ref: 2a0a7878935
Ref: library/email charset email charset Charset output_codec7879135
Ref: 2a0b7879135
Ref: library/email charset email charset Charset get_body_encoding7879423
Ref: 2a0c7879423
Ref: library/email charset email charset Charset get_output_charset7880106
Ref: 2a0d7880106
Ref: library/email charset email charset Charset header_encode7880310
Ref: 2a0e7880310
Ref: library/email charset email charset Charset header_encode_lines7880526
Ref: 2a0f7880526
Ref: library/email charset email charset Charset body_encode7880933
Ref: 2a107880933
Ref: library/email charset email charset Charset __str__7881241
Ref: 2a117881241
Ref: library/email charset email charset Charset __eq__7881429
Ref: 2a127881429
Ref: library/email charset email charset Charset __ne__7881558
Ref: 2a137881558
Ref: library/email charset email charset add_charset7881821
Ref: 2a147881821
Ref: library/email charset email charset add_alias7883111
Ref: 2a167883111
Ref: library/email charset email charset add_codec7883410
Ref: 2a157883410
Ref: email charset 表示字符集-Footnote-17883801
Node: email encoders 编码器7883873
Ref: library/email encoders doc7884045
Ref: 2a177884045
Ref: library/email encoders email-encoders-encoders7884045
Ref: 2a187884045
Ref: library/email encoders module-email encoders7884045
Ref: 6a7884045
Ref: library/email encoders email encoders encode_quopri7885634
Ref: 2a197885634
Ref: library/email encoders email encoders encode_base647885971
Ref: 2a1a7885971
Ref: library/email encoders email encoders encode_7or8bit7886362
Ref: 2a1b7886362
Ref: library/email encoders email encoders encode_noop7886587
Ref: 2a1c7886587
Ref: email encoders 编码器-Footnote-17886788
Ref: email encoders 编码器-Footnote-27886861
Node: email utils 其他工具7886995
Ref: library/email utils doc7887163
Ref: 2a1d7887163
Ref: library/email utils email-utils-miscellaneous-utilities7887163
Ref: 2a1e7887163
Ref: library/email utils module-email utils7887163
Ref: 747887163
Ref: library/email utils email utils localtime7887399
Ref: adf7887399
Ref: library/email utils email utils make_msgid7888059
Ref: 2a1f7888059
Ref: library/email utils email utils quote7888882
Ref: 2a207888882
Ref: library/email utils email utils unquote7889065
Ref: 29407889065
Ref: library/email utils email utils parseaddr7889339
Ref: 2a217889339
Ref: library/email utils email utils formataddr7889666
Ref: be87889666
Ref: library/email utils email utils getaddresses7890323
Ref: f827890323
Ref: library/email utils email utils parsedate7890943
Ref: 2a227890943
Ref: library/email utils email utils parsedate_tz7891547
Ref: f6a7891547
Ref: library/email utils email utils parsedate_to_datetime7892096
Ref: ade7892096
Ref: library/email utils email utils mktime_tz7892774
Ref: 2a237892774
Ref: library/email utils email utils formatdate7893030
Ref: 2a247893030
Ref: library/email utils email utils format_datetime7894004
Ref: add7894004
Ref: library/email utils email utils decode_rfc22317894680
Ref: 2a257894680
Ref: library/email utils email utils encode_rfc22317894772
Ref: 2a267894772
Ref: library/email utils email utils collapse_rfc2231_value7895205
Ref: 29ea7895205
Ref: library/email utils email utils decode_params7896057
Ref: 2a277896057
Ref: email utils 其他工具-Footnote-17896307
Ref: email utils 其他工具-Footnote-27896377
Ref: email utils 其他工具-Footnote-37896426
Ref: email utils 其他工具-Footnote-47896475
Ref: email utils 其他工具-Footnote-57896524
Ref: email utils 其他工具-Footnote-67896573
Ref: email utils 其他工具-Footnote-77896778
Ref: email utils 其他工具-Footnote-87896827
Ref: email utils 其他工具-Footnote-97896876
Ref: email utils 其他工具-Footnote-107896925
Ref: email utils 其他工具-Footnote-117896975
Ref: email utils 其他工具-Footnote-127897025
Node: email iterators 迭代器7897075
Ref: library/email iterators doc7897210
Ref: 2a287897210
Ref: library/email iterators email-iterators-iterators7897210
Ref: 2a297897210
Ref: library/email iterators module-email iterators7897210
Ref: 6f7897210
Ref: library/email iterators email iterators body_line_iterator7897581
Ref: 2a2a7897581
Ref: library/email iterators email iterators typed_subpart_iterator7898104
Ref: 2a2b7898104
Ref: library/email iterators email iterators _structure7898809
Ref: 2a2c7898809
Ref: email iterators 迭代器-Footnote-17900326
Node: json --- JSON 编码和解码器7900400
Ref: library/json doc7900580
Ref: 2a2d7900580
Ref: library/json json-json-encoder-and-decoder7900580
Ref: 2a2e7900580
Ref: library/json module-json7900580
Ref: a47900580
Ref: json --- JSON 编码和解码器-Footnote-17904602
Ref: json --- JSON 编码和解码器-Footnote-27904674
Ref: json --- JSON 编码和解码器-Footnote-37904699
Ref: json --- JSON 编码和解码器-Footnote-47904748
Ref: json --- JSON 编码和解码器-Footnote-57904797
Ref: json --- JSON 编码和解码器-Footnote-67904888
Ref: json --- JSON 编码和解码器-Footnote-77904937
Ref: json --- JSON 编码和解码器-Footnote-87905210
Node: 基本使用7905235
Ref: library/json basic-usage7905346
Ref: 2a307905346
Ref: library/json json dump7905387
Ref: 6fb7905387
Ref: library/json json dumps7908998
Ref: 6fc7908998
Ref: library/json json load7909777
Ref: 6597909777
Ref: library/json json loads7912281
Ref: 2257912281
Ref: 基本使用-Footnote-17913059
Node: 编码器和解码器7913090
Ref: library/json encoders-and-decoders7913216
Ref: 2a337913216
Ref: library/json json JSONDecoder7913272
Ref: 6fe7913272
Ref: library/json json-to-py-table7913516
Ref: 2a327913516
Ref: library/json json JSONDecoder decode7916369
Ref: 2a347916369
Ref: library/json json JSONDecoder raw_decode7916607
Ref: 2a357916607
Ref: library/json json JSONEncoder7916995
Ref: 6fd7916995
Ref: library/json py-to-json-table7917282
Ref: 2a317917282
Ref: library/json json JSONEncoder default7921541
Ref: 2a367921541
Ref: library/json json JSONEncoder encode7922211
Ref: 2a377922211
Ref: library/json json JSONEncoder iterencode7922440
Ref: 2a387922440
Ref: 编码器和解码器-Footnote-17922720
Node: 例外7922751
Ref: library/json exceptions7922895
Ref: 2a397922895
Ref: library/json json JSONDecodeError7922926
Ref: 7f77922926
Ref: library/json json JSONDecodeError msg7923046
Ref: 2a3a7923046
Ref: library/json json JSONDecodeError doc7923110
Ref: 2a3b7923110
Ref: library/json json JSONDecodeError pos7923174
Ref: 2a3c7923174
Ref: library/json json JSONDecodeError lineno7923254
Ref: 2a3d7923254
Ref: library/json json JSONDecodeError colno7923323
Ref: 2a3e7923323
Node: 标准符合性和互操作性7923417
Ref: library/json standard-compliance-and-interoperability7923558
Ref: 2a3f7923558
Ref: 标准符合性和互操作性-Footnote-17924521
Ref: 标准符合性和互操作性-Footnote-27924570
Node: 字符编码7924661
Ref: library/json character-encodings7924772
Ref: 2a407924772
Node: Infinite 和 NaN 数值7925924
Ref: library/json infinite-and-nan-number-values7926068
Ref: 2a417926068
Node: 对象中的重复名称7926798
Ref: library/json repeated-names-within-an-object7926960
Ref: 2a427926960
Node: 顶级非对象，非数组值7927430
Ref: library/json top-level-non-object-non-array-values7927581
Ref: 2a437927581
Ref: 顶级非对象，非数组值-Footnote-17928134
Ref: 顶级非对象，非数组值-Footnote-27928183
Node: 实现限制7928232
Ref: library/json implementation-limitations7928350
Ref: 2a447928350
Node: 命令行界面<4>7929157
Ref: library/json command-line-interface7929283
Ref: 2a457929283
Ref: library/json json-commandline7929283
Ref: 2a2f7929283
Ref: library/json module-json tool7929283
Ref: a57929283
Ref: 命令行界面<4>-Footnote-17930139
Node: 命令行选项<4>7930207
Ref: library/json command-line-options7930280
Ref: 2a477930280
Ref: library/json cmdoption-json-tool-arg-infile7930328
Ref: 2a487930328
Ref: library/json cmdoption-json-tool-arg-outfile7930812
Ref: 2a497930812
Ref: library/json cmdoption-json-tool-sort-keys7930955
Ref: 2a467930955
Ref: library/json cmdoption-json-tool-no-ensure-ascii7931065
Ref: 2a4a7931065
Ref: library/json cmdoption-json-tool-json-lines7931207
Ref: 2a4b7931207
Ref: library/json cmdoption-json-tool-indent7931321
Ref: 2a4c7931321
Ref: library/json cmdoption-json-tool-h7931450
Ref: 2a4d7931450
Node: mailcap --- Mailcap 文件处理7931521
Ref: library/mailcap doc7931700
Ref: 2a4e7931700
Ref: library/mailcap mailcap-mailcap-file-handling7931700
Ref: 2a4f7931700
Ref: library/mailcap module-mailcap7931700
Ref: af7931700
Ref: library/mailcap mailcap findmatch7932631
Ref: 2a507932631
Ref: library/mailcap mailcap getcaps7934480
Ref: 2a517934480
Ref: mailcap --- Mailcap 文件处理-Footnote-17935231
Ref: mailcap --- Mailcap 文件处理-Footnote-27935297
Ref: mailcap --- Mailcap 文件处理-Footnote-37935346
Node: mailbox --- 操作多种格式的邮箱7935395
Ref: library/mailbox doc7935586
Ref: 2a527935586
Ref: library/mailbox mailbox-manipulate-mailboxes-in-various-formats7935586
Ref: 2a537935586
Ref: library/mailbox module-mailbox7935586
Ref: ae7935586
Ref: mailbox --- 操作多种格式的邮箱-Footnote-17936409
Node: Mailbox 对象7936475
Ref: library/mailbox id17936588
Ref: 2a547936588
Ref: library/mailbox mailbox-objects7936588
Ref: 2a557936588
Ref: library/mailbox mailbox Mailbox7936643
Ref: cb17936643
Ref: library/mailbox mailbox Mailbox add7939117
Ref: cb07939117
Ref: library/mailbox mailbox Mailbox remove7939854
Ref: 2a567939854
Ref: library/mailbox mailbox Mailbox __delitem__7939890
Ref: 2a5b7939890
Ref: library/mailbox mailbox Mailbox discard7939931
Ref: 2a577939931
Ref: library/mailbox mailbox Mailbox __setitem__7940440
Ref: 2a5c7940440
Ref: library/mailbox mailbox Mailbox iterkeys7941257
Ref: 2a5d7941257
Ref: library/mailbox mailbox Mailbox keys7941292
Ref: 2a5e7941292
Ref: library/mailbox mailbox Mailbox itervalues7941507
Ref: 2a5f7941507
Ref: library/mailbox mailbox Mailbox __iter__7941544
Ref: 2a607941544
Ref: library/mailbox mailbox Mailbox values7941579
Ref: 2a617941579
Ref: library/mailbox mailbox Mailbox iteritems7942211
Ref: 2a627942211
Ref: library/mailbox mailbox Mailbox items7942247
Ref: 2a637942247
Ref: library/mailbox mailbox Mailbox get7942780
Ref: 2a647942780
Ref: library/mailbox mailbox Mailbox __getitem__7942827
Ref: 2a657942827
Ref: library/mailbox mailbox Mailbox get_message7943352
Ref: 2a667943352
Ref: library/mailbox mailbox Mailbox get_bytes7943620
Ref: cb37943620
Ref: library/mailbox mailbox Mailbox get_string7943846
Ref: cb47943846
Ref: library/mailbox mailbox Mailbox get_file7944170
Ref: cb27944170
Ref: library/mailbox mailbox Mailbox __contains__7945003
Ref: 2a677945003
Ref: library/mailbox mailbox Mailbox __len__7945139
Ref: 2a687945139
Ref: library/mailbox mailbox Mailbox clear7945219
Ref: 2a697945219
Ref: library/mailbox mailbox Mailbox pop7945297
Ref: 2a6a7945297
Ref: library/mailbox mailbox Mailbox popitem7945684
Ref: 2a6b7945684
Ref: library/mailbox mailbox Mailbox update7946147
Ref: 2a6c7946147
Ref: library/mailbox mailbox Mailbox flush7946848
Ref: 2a6d7946848
Ref: library/mailbox mailbox Mailbox lock7947141
Ref: 2a587947141
Ref: library/mailbox mailbox Mailbox unlock7947503
Ref: 2a597947503
Ref: library/mailbox mailbox Mailbox close7947594
Ref: 2a6f7947594
Node: Maildir7947867
Ref: library/mailbox mailbox-maildir7947938
Ref: 2a707947938
Ref: library/mailbox maildir7947938
Ref: 2a717947938
Ref: library/mailbox mailbox Maildir7947981
Ref: d707947981
Ref: library/mailbox mailbox Maildir list_folders7950605
Ref: 2a737950605
Ref: library/mailbox mailbox Maildir get_folder7950696
Ref: 2a747950696
Ref: library/mailbox mailbox Maildir add_folder7950928
Ref: 2a767950928
Ref: library/mailbox mailbox Maildir remove_folder7951082
Ref: 2a777951082
Ref: library/mailbox mailbox Maildir clean7951311
Ref: 2a797951311
Ref: library/mailbox mailbox Maildir add7951612
Ref: 2a7a7951612
Ref: library/mailbox mailbox Maildir __setitem__7951649
Ref: 2a7b7951649
Ref: library/mailbox mailbox Maildir update7951699
Ref: 2a7c7951699
Ref: library/mailbox mailbox Maildir flush7952035
Ref: 2a7d7952035
Ref: library/mailbox mailbox Maildir lock7952190
Ref: 2a7e7952190
Ref: library/mailbox mailbox Maildir unlock7952221
Ref: 2a7f7952221
Ref: library/mailbox mailbox Maildir close7952373
Ref: 2a807952373
Ref: library/mailbox mailbox Maildir get_file7952569
Ref: 2a817952569
Ref: Maildir-Footnote-17953068
Ref: Maildir-Footnote-27953116
Node: mbox7953160
Ref: library/mailbox mailbox-mbox7953242
Ref: 2a827953242
Ref: library/mailbox mbox7953242
Ref: 2a837953242
Ref: library/mailbox mailbox mbox7953279
Ref: 2a5a7953279
Ref: library/mailbox mailbox mbox get_file7954524
Ref: 2a847954524
Ref: library/mailbox mailbox mbox lock7954731
Ref: 2a857954731
Ref: library/mailbox mailbox mbox unlock7954762
Ref: 2a867954762
Ref: mbox-Footnote-17955323
Ref: mbox-Footnote-27955383
Ref: mbox-Footnote-37955435
Node: MH7955513
Ref: library/mailbox mailbox-mh7955593
Ref: 2a877955593
Ref: library/mailbox mh7955593
Ref: 2a887955593
Ref: library/mailbox mailbox MH7955626
Ref: 2a897955626
Ref: library/mailbox mailbox MH list_folders7957048
Ref: 2a8b7957048
Ref: library/mailbox mailbox MH get_folder7957139
Ref: 2a8c7957139
Ref: library/mailbox mailbox MH add_folder7957357
Ref: 2a8d7957357
Ref: library/mailbox mailbox MH remove_folder7957508
Ref: 2a8e7957508
Ref: library/mailbox mailbox MH get_sequences7957737
Ref: 2a8f7957737
Ref: library/mailbox mailbox MH set_sequences7957901
Ref: 2a907957901
Ref: library/mailbox mailbox MH pack7958154
Ref: 2a917958154
Ref: library/mailbox mailbox MH remove7958526
Ref: 2a927958526
Ref: library/mailbox mailbox MH __delitem__7958562
Ref: 2a937958562
Ref: library/mailbox mailbox MH discard7958603
Ref: 2a947958603
Ref: library/mailbox mailbox MH lock7958792
Ref: 2a957958792
Ref: library/mailbox mailbox MH unlock7958823
Ref: 2a967958823
Ref: library/mailbox mailbox MH get_file7959178
Ref: 2a977959178
Ref: library/mailbox mailbox MH flush7959345
Ref: 2a987959345
Ref: library/mailbox mailbox MH close7959495
Ref: 2a997959495
Ref: MH-Footnote-17959978
Ref: MH-Footnote-27960013
Node: Babyl7960058
Ref: library/mailbox babyl7960138
Ref: 2a9a7960138
Ref: library/mailbox mailbox-babyl7960138
Ref: 2a9b7960138
Ref: library/mailbox mailbox Babyl7960177
Ref: 2a9c7960177
Ref: library/mailbox mailbox Babyl get_labels7961601
Ref: 2a9e7961601
Ref: library/mailbox mailbox Babyl get_file7962039
Ref: 2a9f7962039
Ref: library/mailbox mailbox Babyl lock7962479
Ref: 2aa07962479
Ref: library/mailbox mailbox Babyl unlock7962510
Ref: 2aa17962510
Ref: Babyl-Footnote-17962906
Ref: Babyl-Footnote-27962950
Node: MMDF7963028
Ref: library/mailbox mailbox-mmdf7963097
Ref: 2aa27963097
Ref: library/mailbox mmdf7963097
Ref: 2aa37963097
Ref: library/mailbox mailbox MMDF7963134
Ref: 2aa47963134
Ref: library/mailbox mailbox MMDF get_file7964291
Ref: 2aa67964291
Ref: library/mailbox mailbox MMDF lock7964498
Ref: 2aa77964498
Ref: library/mailbox mailbox MMDF unlock7964529
Ref: 2aa87964529
Ref: MMDF-Footnote-17964959
Ref: MMDF-Footnote-27965019
Node: Message 对象7965062
Ref: library/mailbox mailbox-message-objects7965194
Ref: 2aa97965194
Ref: library/mailbox message-objects7965194
Ref: 2aaa7965194
Ref: library/mailbox mailbox Message7965249
Ref: cb57965249
Ref: Message 对象-Footnote-17967110
Node: MaildirMessage7967159
Ref: library/mailbox mailbox-maildirmessage7967244
Ref: 2aab7967244
Ref: library/mailbox maildirmessage7967244
Ref: 2aac7967244
Ref: library/mailbox mailbox MaildirMessage7967301
Ref: 2a727967301
Ref: library/mailbox mailbox MaildirMessage get_subdir7969068
Ref: 2aad7969068
Ref: library/mailbox mailbox MaildirMessage set_subdir7969535
Ref: 2aae7969535
Ref: library/mailbox mailbox MaildirMessage get_flags7969691
Ref: 2aaf7969691
Ref: library/mailbox mailbox MaildirMessage set_flags7970092
Ref: 2ab07970092
Ref: library/mailbox mailbox MaildirMessage add_flag7970212
Ref: 2ab17970212
Ref: library/mailbox mailbox MaildirMessage remove_flag7970529
Ref: 2ab27970529
Ref: library/mailbox mailbox MaildirMessage get_date7970854
Ref: 2ab37970854
Ref: library/mailbox mailbox MaildirMessage set_date7970977
Ref: 2ab47970977
Ref: library/mailbox mailbox MaildirMessage get_info7971114
Ref: 2ab57971114
Ref: library/mailbox mailbox MaildirMessage set_info7971309
Ref: 2ab67971309
Node: mboxMessage7974074
Ref: library/mailbox mailbox-mboxmessage7974177
Ref: 2ab77974177
Ref: library/mailbox mboxmessage7974177
Ref: 2ab87974177
Ref: library/mailbox mailbox mboxMessage7974228
Ref: 29297974228
Ref: library/mailbox mailbox mboxMessage get_from7975827
Ref: 2ab97975827
Ref: library/mailbox mailbox mboxMessage set_from7976024
Ref: 2aba7976024
Ref: library/mailbox mailbox mboxMessage get_flags7976517
Ref: 2abb7976517
Ref: library/mailbox mailbox mboxMessage set_flags7976797
Ref: 2abc7976797
Ref: library/mailbox mailbox mboxMessage add_flag7977076
Ref: 2abd7977076
Ref: library/mailbox mailbox mboxMessage remove_flag7977299
Ref: 2abe7977299
Node: MHMessage7980232
Ref: library/mailbox mailbox-mhmessage7980333
Ref: 2abf7980333
Ref: library/mailbox mhmessage7980333
Ref: 2ac07980333
Ref: library/mailbox mailbox MHMessage7980382
Ref: 2a8a7980382
Ref: library/mailbox mailbox MHMessage get_sequences7981265
Ref: 2ac17981265
Ref: library/mailbox mailbox MHMessage set_sequences7981375
Ref: 2ac27981375
Ref: library/mailbox mailbox MHMessage add_sequence7981479
Ref: 2ac37981479
Ref: library/mailbox mailbox MHMessage remove_sequence7981599
Ref: 2ac47981599
Node: BabylMessage7983409
Ref: library/mailbox babylmessage7983510
Ref: 2ac57983510
Ref: library/mailbox mailbox-babylmessage7983510
Ref: 2ac67983510
Ref: library/mailbox mailbox BabylMessage7983565
Ref: 2a9d7983565
Ref: library/mailbox mailbox BabylMessage get_labels7984835
Ref: 2ac77984835
Ref: library/mailbox mailbox BabylMessage set_labels7984918
Ref: 2ac87984918
Ref: library/mailbox mailbox BabylMessage add_label7985023
Ref: 2ac97985023
Ref: library/mailbox mailbox BabylMessage remove_label7985128
Ref: 2aca7985128
Ref: library/mailbox mailbox BabylMessage get_visible7985233
Ref: 2acb7985233
Ref: library/mailbox mailbox BabylMessage set_visible7985394
Ref: 2acc7985394
Ref: library/mailbox mailbox BabylMessage update_visible7985720
Ref: 2acd7985720
Node: MMDFMessage7988016
Ref: library/mailbox mailbox-mmdfmessage7988099
Ref: 2ace7988099
Ref: library/mailbox mmdfmessage7988099
Ref: 2acf7988099
Ref: library/mailbox mailbox MMDFMessage7988152
Ref: 2aa57988152
Ref: library/mailbox mailbox MMDFMessage get_from7989669
Ref: 2ad07989669
Ref: library/mailbox mailbox MMDFMessage set_from7989866
Ref: 2ad17989866
Ref: library/mailbox mailbox MMDFMessage get_flags7990359
Ref: 2ad27990359
Ref: library/mailbox mailbox MMDFMessage set_flags7990639
Ref: 2ad37990639
Ref: library/mailbox mailbox MMDFMessage add_flag7990918
Ref: 2ad47990918
Ref: library/mailbox mailbox MMDFMessage remove_flag7991141
Ref: 2ad57991141
Node: 异常<13>7994077
Ref: library/mailbox exceptions7994205
Ref: 2ad67994205
Ref: library/mailbox mailbox Error7994293
Ref: 2ad77994293
Ref: library/mailbox mailbox NoSuchMailboxError7994369
Ref: 2a757994369
Ref: library/mailbox mailbox NotEmptyError7994654
Ref: 2a787994654
Ref: library/mailbox mailbox ExternalClashError7994807
Ref: 2a6e7994807
Ref: library/mailbox mailbox FormatError7995073
Ref: 2ad87995073
Node: 示例<27>7995271
Ref: library/mailbox examples7995376
Ref: 2ad97995376
Ref: library/mailbox mailbox-examples7995376
Ref: 2ada7995376
Node: mimetypes --- 映射文件名到 MIME 类型7997567
Ref: library/mimetypes doc7997786
Ref: 2adb7997786
Ref: library/mimetypes mimetypes-map-filenames-to-mime-types7997786
Ref: 2adc7997786
Ref: library/mimetypes module-mimetypes7997786
Ref: b27997786
Ref: library/mimetypes mimetypes guess_type7998587
Ref: 10a17998587
Ref: library/mimetypes mimetypes guess_all_extensions7999863
Ref: f6f7999863
Ref: library/mimetypes mimetypes guess_extension8000360
Ref: 2add8000360
Ref: library/mimetypes mimetypes init8000977
Ref: 10a28000977
Ref: library/mimetypes mimetypes read_mime_types8001862
Ref: 10198001862
Ref: library/mimetypes mimetypes add_type8002254
Ref: 2adf8002254
Ref: library/mimetypes mimetypes inited8002658
Ref: 2ae08002658
Ref: library/mimetypes mimetypes knownfiles8002807
Ref: 2ade8002807
Ref: library/mimetypes mimetypes suffix_map8002994
Ref: 2ae18002994
Ref: library/mimetypes mimetypes encodings_map8003300
Ref: 2ae28003300
Ref: library/mimetypes mimetypes types_map8003396
Ref: 2ae38003396
Ref: library/mimetypes mimetypes common_types8003482
Ref: 2ae48003482
Ref: mimetypes --- 映射文件名到 MIME 类型-Footnote-18003998
Ref: mimetypes --- 映射文件名到 MIME 类型-Footnote-28004066
Node: MimeTypes 对象8004137
Ref: library/mimetypes id18004234
Ref: 2ae58004234
Ref: library/mimetypes mimetypes-objects8004234
Ref: 2ae68004234
Ref: library/mimetypes mimetypes MimeTypes8004456
Ref: 2ae78004456
Ref: library/mimetypes mimetypes MimeTypes suffix_map8005110
Ref: 2aea8005110
Ref: library/mimetypes mimetypes MimeTypes encodings_map8005517
Ref: 2aeb8005517
Ref: library/mimetypes mimetypes MimeTypes types_map8005705
Ref: 2aec8005705
Ref: library/mimetypes mimetypes MimeTypes types_map_inv8005995
Ref: 2aed8005995
Ref: library/mimetypes mimetypes MimeTypes guess_extension8006295
Ref: 2aee8006295
Ref: library/mimetypes mimetypes MimeTypes guess_type8006473
Ref: 115c8006473
Ref: library/mimetypes mimetypes MimeTypes guess_all_extensions8006640
Ref: 2aef8006640
Ref: library/mimetypes mimetypes MimeTypes read8006827
Ref: 2ae88006827
Ref: library/mimetypes mimetypes MimeTypes readfp8007150
Ref: 2ae98007150
Ref: library/mimetypes mimetypes MimeTypes read_windows_registry8007470
Ref: 2af08007470
Node: base64 —— Base16、Base32、Base64、Base85 資料編碼8007802
Ref: library/base64 doc8008030
Ref: 2af18008030
Ref: library/base64 base64-base16-base32-base64-base85-data-encodings8008030
Ref: 2af28008030
Ref: library/base64 module-base648008030
Ref: d8008030
Ref: library/base64 base64 b64encode8009649
Ref: 2af38009649
Ref: library/base64 base64 b64decode8010113
Ref: 10a38010113
Ref: library/base64 base64 standard_b64encode8010858
Ref: 2af48010858
Ref: library/base64 base64 standard_b64decode8011028
Ref: 2af58011028
Ref: library/base64 base64 urlsafe_b64encode8011217
Ref: 2af68011217
Ref: library/base64 base64 urlsafe_b64decode8011527
Ref: 2af78011527
Ref: library/base64 base64 b32encode8011821
Ref: 2af88011821
Ref: library/base64 base64 b32decode8011958
Ref: a3e8011958
Ref: library/base64 base64 b16encode8012839
Ref: 2af98012839
Ref: library/base64 base64 b16decode8012976
Ref: 2afa8012976
Ref: library/base64 base64 a85encode8013431
Ref: 9118013431
Ref: library/base64 base64 a85decode8014250
Ref: 9128014250
Ref: library/base64 base64 b85encode8015018
Ref: 9138015018
Ref: library/base64 base64 b85decode8015365
Ref: 9148015365
Ref: library/base64 base64 decode8015625
Ref: 2afb8015625
Ref: library/base64 base64 decodebytes8015912
Ref: 2238015912
Ref: library/base64 base64 encode8016131
Ref: 2afc8016131
Ref: library/base64 base64 encodebytes8016619
Ref: 2228016619
Ref: base64 —— Base16、Base32、Base64、Base85 資料編碼-Footnote-18017640
Ref: base64 —— Base16、Base32、Base64、Base85 資料編碼-Footnote-28017705
Ref: base64 —— Base16、Base32、Base64、Base85 資料編碼-Footnote-38017754
Ref: base64 —— Base16、Base32、Base64、Base85 資料編碼-Footnote-48017803
Ref: base64 —— Base16、Base32、Base64、Base85 資料編碼-Footnote-58017852
Ref: base64 —— Base16、Base32、Base64、Base85 資料編碼-Footnote-68017901
Ref: base64 —— Base16、Base32、Base64、Base85 資料編碼-Footnote-78017950
Ref: base64 —— Base16、Base32、Base64、Base85 資料編碼-Footnote-88017999
Ref: base64 —— Base16、Base32、Base64、Base85 資料編碼-Footnote-98018048
Ref: base64 —— Base16、Base32、Base64、Base85 資料編碼-Footnote-108018097
Node: binhex --- 对binhex4文件进行编码和解码8018147
Ref: library/binhex doc8018372
Ref: 2afd8018372
Ref: library/binhex binhex-encode-and-decode-binhex4-files8018372
Ref: 2afe8018372
Ref: library/binhex module-binhex8018372
Ref: 108018372
Ref: library/binhex binhex binhex8018789
Ref: 2aff8018789
Ref: library/binhex binhex hexbin8019042
Ref: 2b008019042
Ref: library/binhex binhex Error8019401
Ref: 2b018019401
Ref: binhex --- 对binhex4文件进行编码和解码-Footnote-18019806
Node: 註解<2>8019871
Ref: library/binhex binhex-notes8019965
Ref: 2b028019965
Ref: library/binhex notes8019965
Ref: 2b038019965
Node: binascii --- 二进制和 ASCII 码互转8020247
Ref: library/binascii doc8020474
Ref: 2b048020474
Ref: library/binascii binascii-convert-between-binary-and-ascii8020474
Ref: 2b058020474
Ref: library/binascii module-binascii8020474
Ref: f8020474
Ref: library/binascii binascii a2b_uu8021430
Ref: 2b068021430
Ref: library/binascii binascii b2a_uu8021668
Ref: 4758021668
Ref: library/binascii binascii a2b_base648021997
Ref: 10da8021997
Ref: library/binascii binascii b2a_base648022159
Ref: 61c8022159
Ref: library/binascii binascii a2b_qp8022492
Ref: 2b078022492
Ref: library/binascii binascii b2a_qp8022755
Ref: 2b088022755
Ref: library/binascii binascii a2b_hqx8023463
Ref: 2098023463
Ref: library/binascii binascii rledecode_hqx8023751
Ref: 20b8023751
Ref: library/binascii binascii rlecode_hqx8024254
Ref: 20a8024254
Ref: library/binascii binascii b2a_hqx8024394
Ref: 2088024394
Ref: library/binascii binascii crc_hqx8024646
Ref: 10868024646
Ref: library/binascii binascii crc328024918
Ref: 2b0a8024918
Ref: library/binascii binascii b2a_hex8025632
Ref: 19b78025632
Ref: library/binascii binascii hexlify8025694
Ref: 10f88025694
Ref: library/binascii binascii a2b_hex8026782
Ref: 19b88026782
Ref: library/binascii binascii unhexlify8026820
Ref: 11748026820
Ref: library/binascii binascii Error8027277
Ref: a3f8027277
Ref: library/binascii binascii Incomplete8027357
Ref: 2b098027357
Ref: binascii --- 二进制和 ASCII 码互转-Footnote-18027962
Node: quopri --- 编码与解码经过 MIME 转码的可打印数据8028011
Ref: library/quopri doc8028237
Ref: 2b0b8028237
Ref: library/quopri module-quopri8028237
Ref: db8028237
Ref: library/quopri quopri-encode-and-decode-mime-quoted-printable-data8028237
Ref: 2b0c8028237
Ref: library/quopri quopri decode8028955
Ref: 19ba8028955
Ref: library/quopri quopri encode8029477
Ref: 19b98029477
Ref: library/quopri quopri decodestring8030119
Ref: 2b0d8030119
Ref: library/quopri quopri encodestring8030310
Ref: 2b0e8030310
Ref: quopri --- 编码与解码经过 MIME 转码的可打印数据-Footnote-18030750
Ref: quopri --- 编码与解码经过 MIME 转码的可打印数据-Footnote-28030815
Ref: quopri --- 编码与解码经过 MIME 转码的可打印数据-Footnote-38030864
Ref: quopri --- 编码与解码经过 MIME 转码的可打印数据-Footnote-48030913
Ref: quopri --- 编码与解码经过 MIME 转码的可打印数据-Footnote-58030962
Node: uu --- 对 uuencode 文件进行编码与解码8031011
Ref: library/uu doc8031187
Ref: 2b0f8031187
Ref: library/uu module-uu8031187
Ref: 12c8031187
Ref: library/uu uu-encode-and-decode-uuencode-files8031187
Ref: 2b108031187
Ref: library/uu uu encode8032046
Ref: 5138032046
Ref: library/uu uu decode8032547
Ref: 19bb8032547
Ref: library/uu uu Error8033238
Ref: 2b118033238
Ref: uu --- 对 uuencode 文件进行编码与解码-Footnote-18033623
Node: 结构化标记处理工具8033684
Ref: library/markup doc8033850
Ref: 2b128033850
Ref: library/markup markup8033850
Ref: 2b138033850
Ref: library/markup structured-markup-processing-tools8033850
Ref: 2b148033850
Node: html --- 超文本标记语言支持8035231
Ref: library/html doc8035390
Ref: 2b158035390
Ref: library/html html-hypertext-markup-language-support8035390
Ref: 2b168035390
Ref: library/html module-html8035390
Ref: 8f8035390
Ref: library/html html escape8035623
Ref: a188035623
Ref: library/html html unescape8036075
Ref: 22b8036075
Ref: html --- 超文本标记语言支持-Footnote-18036694
Node: html parser --- 简单的 HTML 和 XHTML 解析器8036766
Ref: library/html parser doc8036978
Ref: 2b178036978
Ref: library/html parser html-parser-simple-html-and-xhtml-parser8036978
Ref: 2b188036978
Ref: library/html parser module-html parser8036978
Ref: 918036978
Ref: library/html parser html parser HTMLParser8037338
Ref: 22a8037338
Ref: html parser --- 简单的 HTML 和 XHTML 解析器-Footnote-18038370
Node: HTML 解析器的示例程序8038440
Ref: library/html parser example-html-parser-application8038582
Ref: 2b198038582
Node: HTMLParser 方法8039776
Ref: library/html parser htmlparser-methods8039937
Ref: 2b1a8039937
Ref: library/html parser html parser HTMLParser feed8040047
Ref: 2b1b8040047
Ref: library/html parser html parser HTMLParser close8040340
Ref: 2b1c8040340
Ref: library/html parser html parser HTMLParser reset8040681
Ref: 2b1d8040681
Ref: library/html parser html parser HTMLParser getpos8040811
Ref: 2b1e8040811
Ref: library/html parser html parser HTMLParser get_starttag_text8040891
Ref: 2b1f8040891
Ref: library/html parser html parser HTMLParser handle_starttag8041405
Ref: 2b218041405
Ref: library/html parser html parser HTMLParser handle_endtag8042104
Ref: 2b228042104
Ref: library/html parser html parser HTMLParser handle_startendtag8042281
Ref: 2b208042281
Ref: library/html parser html parser HTMLParser handle_data8042657
Ref: 2b238042657
Ref: library/html parser html parser HTMLParser handle_entityref8042862
Ref: 2b248042862
Ref: library/html parser html parser HTMLParser handle_charref8043170
Ref: 2b258043170
Ref: library/html parser html parser HTMLParser handle_comment8043603
Ref: 2b268043603
Ref: library/html parser html parser HTMLParser handle_decl8044110
Ref: 2b278044110
Ref: library/html parser html parser HTMLParser handle_pi8044355
Ref: 2b288044355
Ref: library/html parser html parser HTMLParser unknown_decl8044903
Ref: 2b298044903
Node: 示例<28>8045182
Ref: library/html parser examples8045305
Ref: 2b2a8045305
Ref: library/html parser htmlparser-examples8045305
Ref: 2b2b8045305
Node: html entities --- HTML 一般实体的定义8048670
Ref: library/html entities doc8048862
Ref: 2b2c8048862
Ref: library/html entities html-entities-definitions-of-html-general-entities8048862
Ref: 2b2d8048862
Ref: library/html entities module-html entities8048862
Ref: 908048862
Ref: library/html entities html entities html58049222
Ref: af38049222
Ref: library/html entities html entities entitydefs8049654
Ref: 2b308049654
Ref: library/html entities html entities name2codepoint8049775
Ref: 2b2e8049775
Ref: library/html entities html entities codepoint2name8049882
Ref: 2b2f8049882
Ref: html entities --- HTML 一般实体的定义-Footnote-18050038
Ref: html entities --- HTML 一般实体的定义-Footnote-28050110
Node: XML 處理模組8050210
Ref: library/xml doc8050397
Ref: 2b318050397
Ref: library/xml module-xml8050397
Ref: 13c8050397
Ref: library/xml xml8050397
Ref: 2b328050397
Ref: library/xml xml-processing-modules8050397
Ref: 2b338050397
Ref: XML 處理模組-Footnote-18051639
Node: XML 漏洞8051699
Ref: library/xml id18051785
Ref: 2b368051785
Ref: library/xml xml-vulnerabilities8051785
Ref: 2b348051785
Ref: XML 漏洞-Footnote-18056617
Ref: XML 漏洞-Footnote-28056680
Ref: XML 漏洞-Footnote-38056733
Ref: XML 漏洞-Footnote-48056786
Ref: XML 漏洞-Footnote-58056849
Ref: XML 漏洞-Footnote-68056896
Node: defusedxml 包8056941
Ref: library/xml defusedxml-package8057027
Ref: 2b358057027
Ref: library/xml the-defusedxml-package8057027
Ref: 2b378057027
Ref: defusedxml 包-Footnote-18057459
Node: xml etree ElementTree --- ElementTree XML API8057504
Ref: library/xml etree elementtree doc8057681
Ref: 2b388057681
Ref: library/xml etree elementtree dtd8057681
Ref: 2b398057681
Ref: library/xml etree elementtree module-xml etree ElementTree8057681
Ref: 1408057681
Ref: library/xml etree elementtree xml-etree-elementtree-the-elementtree-xml-api8057681
Ref: 2b3a8057681
Ref: xml etree ElementTree --- ElementTree XML API-Footnote-18058517
Node: 教程8058598
Ref: library/xml etree elementtree tutorial8058706
Ref: 2b3b8058706
Node: XML 树和元素8059099
Ref: library/xml etree elementtree xml-tree-and-elements8059177
Ref: 2b3c8059177
Node: 解析 XML8059650
Ref: library/xml etree elementtree elementtree-parsing-xml8059771
Ref: 2b3d8059771
Ref: library/xml etree elementtree parsing-xml8059771
Ref: 2b3e8059771
Node: 用于非阻塞解析的拉取 API8062115
Ref: library/xml etree elementtree elementtree-pull-parsing8062244
Ref: 9fa8062244
Ref: library/xml etree elementtree pull-api-for-non-blocking-parsing8062244
Ref: 2b408062244
Node: 查找感兴趣的元素8063962
Ref: library/xml etree elementtree finding-interesting-elements8064096
Ref: 2b438064096
Node: 修改XML文件8065264
Ref: library/xml etree elementtree modifying-an-xml-file8065381
Ref: 2b488065381
Node: 构建 XML 文档8068285
Ref: library/xml etree elementtree building-xml-documents8068409
Ref: 2b4c8068409
Node: 解析带有命名空间的 XML8068750
Ref: library/xml etree elementtree parsing-xml-with-namespaces8068871
Ref: 2b4e8068871
Ref: 解析带有命名空间的 XML-Footnote-18071166
Ref: 解析带有命名空间的 XML-Footnote-28071218
Node: 其他资源8071270
Ref: library/xml etree elementtree additional-resources8071365
Ref: 2b4f8071365
Node: XPath支持8071505
Ref: library/xml etree elementtree elementtree-xpath8071634
Ref: 51d8071634
Ref: library/xml etree elementtree xpath-support8071634
Ref: 2b508071634
Ref: XPath支持-Footnote-18071972
Node: 示例<29>8072008
Ref: library/xml etree elementtree example8072095
Ref: 2b518072095
Node: 支持的XPath语法8073092
Ref: library/xml etree elementtree supported-xpath-syntax8073179
Ref: 2b528073179
Node: 参考引用8076498
Ref: library/xml etree elementtree reference8076636
Ref: 2b538076636
Node: 函数<7>8076710
Ref: library/xml etree elementtree elementtree-functions8076768
Ref: 2b548076768
Ref: library/xml etree elementtree functions8076768
Ref: 2b558076768
Ref: library/xml etree elementtree xml etree ElementTree canonicalize8076801
Ref: 2b568076801
Ref: library/xml etree elementtree xml etree ElementTree Comment8079114
Ref: 2b578079114
Ref: library/xml etree elementtree xml etree ElementTree dump8079721
Ref: 2b588079721
Ref: library/xml etree elementtree xml etree ElementTree fromstring8080147
Ref: 2b3f8080147
Ref: library/xml etree elementtree xml etree ElementTree fromstringlist8080514
Ref: c218080514
Ref: library/xml etree elementtree xml etree ElementTree indent8080918
Ref: 2b5a8080918
Ref: library/xml etree elementtree xml etree ElementTree iselement8081380
Ref: 2b5b8081380
Ref: library/xml etree elementtree xml etree ElementTree iterparse8081591
Ref: a298081591
Ref: library/xml etree elementtree xml etree ElementTree parse8083306
Ref: 2b5c8083306
Ref: library/xml etree elementtree xml etree ElementTree ProcessingInstruction8083656
Ref: 2b5d8083656
Ref: library/xml etree elementtree xml etree ElementTree register_namespace8084302
Ref: c228084302
Ref: library/xml etree elementtree xml etree ElementTree SubElement8084735
Ref: 2b4d8084735
Ref: library/xml etree elementtree xml etree ElementTree tostring8085249
Ref: 9fb8085249
Ref: library/xml etree elementtree xml etree ElementTree tostringlist8086269
Ref: 9fc8086269
Ref: library/xml etree elementtree xml etree ElementTree XML8087446
Ref: 2b598087446
Ref: library/xml etree elementtree xml etree ElementTree XMLID8087848
Ref: 2b5e8087848
Ref: 函数<7>-Footnote-18088311
Ref: 函数<7>-Footnote-28088352
Ref: 函数<7>-Footnote-38088660
Node: XInclude 支持8088968
Ref: library/xml etree elementtree elementtree-xinclude8089110
Ref: 2b5f8089110
Ref: library/xml etree elementtree xinclude-support8089110
Ref: 2b608089110
Ref: XInclude 支持-Footnote-18089430
Node: 示例<30>8089470
Ref: library/xml etree elementtree id38089532
Ref: 2b618089532
Node: 参考引用<2>8091237
Ref: library/xml etree elementtree id48091358
Ref: 2b628091358
Node: 函数<8>8091578
Ref: library/xml etree elementtree elementinclude-functions8091660
Ref: 2b638091660
Ref: library/xml etree elementtree id58091660
Ref: 2b648091660
Ref: library/xml etree elementtree xml etree ElementTree xml etree ElementInclude default_loader8091693
Ref: 2b658091693
Ref: library/xml etree elementtree xml etree ElementTree xml etree ElementInclude include8092316
Ref: 2b668092316
Node: 元素对象8093279
Ref: library/xml etree elementtree element-objects8093388
Ref: 2b678093388
Ref: library/xml etree elementtree elementtree-element-objects8093388
Ref: 2b688093388
Ref: library/xml etree elementtree xml etree ElementTree Element8093431
Ref: 21d8093431
Ref: library/xml etree elementtree xml etree ElementTree Element tag8093844
Ref: 2b698093844
Ref: library/xml etree elementtree xml etree ElementTree Element text8093964
Ref: 2b468093964
Ref: library/xml etree elementtree xml etree ElementTree Element tail8093986
Ref: 2b6a8093986
Ref: library/xml etree elementtree xml etree ElementTree Element attrib8095038
Ref: 2b6b8095038
Ref: library/xml etree elementtree xml etree ElementTree Element clear8095460
Ref: 2b6c8095460
Ref: library/xml etree elementtree xml etree ElementTree Element get8095641
Ref: 2b478095641
Ref: library/xml etree elementtree xml etree ElementTree Element items8095820
Ref: 2b6d8095820
Ref: library/xml etree elementtree xml etree ElementTree Element keys8095970
Ref: 2b6e8095970
Ref: library/xml etree elementtree xml etree ElementTree Element set8096096
Ref: 2b498096096
Ref: library/xml etree elementtree xml etree ElementTree Element append8096252
Ref: 2b4a8096252
Ref: library/xml etree elementtree xml etree ElementTree Element extend8096487
Ref: c238096487
Ref: library/xml etree elementtree xml etree ElementTree Element find8096741
Ref: 2b458096741
Ref: library/xml etree elementtree xml etree ElementTree Element findall8097174
Ref: 2b448097174
Ref: library/xml etree elementtree xml etree ElementTree Element findtext8097607
Ref: 2b6f8097607
Ref: library/xml etree elementtree xml etree ElementTree Element insert8098228
Ref: 2b708098228
Ref: library/xml etree elementtree xml etree ElementTree Element iter8098449
Ref: daf8098449
Ref: library/xml etree elementtree xml etree ElementTree Element iterfind8098893
Ref: c248098893
Ref: library/xml etree elementtree xml etree ElementTree Element itertext8099238
Ref: c258099238
Ref: library/xml etree elementtree xml etree ElementTree Element makeelement8099456
Ref: 2b718099456
Ref: library/xml etree elementtree xml etree ElementTree Element remove8099668
Ref: 2b4b8099668
Ref: 元素对象-Footnote-18101934
Node: ElementTree 对象8101977
Ref: library/xml etree elementtree elementtree-elementtree-objects8102089
Ref: 2b728102089
Ref: library/xml etree elementtree elementtree-objects8102089
Ref: 2b738102089
Ref: library/xml etree elementtree xml etree ElementTree ElementTree8102146
Ref: 21c8102146
Ref: library/xml etree elementtree xml etree ElementTree ElementTree _setroot8102481
Ref: 2b748102481
Ref: library/xml etree elementtree xml etree ElementTree ElementTree find8102713
Ref: 2b758102713
Ref: library/xml etree elementtree xml etree ElementTree ElementTree findall8102847
Ref: 2b768102847
Ref: library/xml etree elementtree xml etree ElementTree ElementTree findtext8102987
Ref: 2b778102987
Ref: library/xml etree elementtree xml etree ElementTree ElementTree getroot8103143
Ref: 2b788103143
Ref: library/xml etree elementtree xml etree ElementTree ElementTree iter8103220
Ref: 2b798103220
Ref: library/xml etree elementtree xml etree ElementTree ElementTree iterfind8103453
Ref: 2b7a8103453
Ref: library/xml etree elementtree xml etree ElementTree ElementTree parse8103623
Ref: 2b7b8103623
Ref: library/xml etree elementtree xml etree ElementTree ElementTree write8103967
Ref: 9fd8103967
Ref: ElementTree 对象-Footnote-18106643
Node: QName 对象8106951
Ref: library/xml etree elementtree elementtree-qname-objects8107069
Ref: 2b7c8107069
Ref: library/xml etree elementtree qname-objects8107069
Ref: 2b7d8107069
Ref: library/xml etree elementtree xml etree ElementTree QName8107114
Ref: 2b7e8107114
Node: TreeBuilder 对象8107622
Ref: library/xml etree elementtree elementtree-treebuilder-objects8107737
Ref: 2b7f8107737
Ref: library/xml etree elementtree treebuilder-objects8107737
Ref: 2b808107737
Ref: library/xml etree elementtree xml etree ElementTree TreeBuilder8107794
Ref: 37d8107794
Ref: library/xml etree elementtree xml etree ElementTree TreeBuilder close8108867
Ref: 2b818108867
Ref: library/xml etree elementtree xml etree ElementTree TreeBuilder data8109028
Ref: 2b828109028
Ref: library/xml etree elementtree xml etree ElementTree TreeBuilder end8109204
Ref: c268109204
Ref: library/xml etree elementtree xml etree ElementTree TreeBuilder start8109324
Ref: 106d8109324
Ref: library/xml etree elementtree xml etree ElementTree TreeBuilder comment8109506
Ref: 2b838109506
Ref: library/xml etree elementtree xml etree ElementTree TreeBuilder pi8109722
Ref: 2b848109722
Ref: library/xml etree elementtree xml etree ElementTree TreeBuilder doctype8110038
Ref: 3e38110038
Ref: library/xml etree elementtree xml etree ElementTree TreeBuilder start_ns8110333
Ref: 2b858110333
Ref: library/xml etree elementtree xml etree ElementTree TreeBuilder end_ns8110736
Ref: 2b868110736
Ref: library/xml etree elementtree xml etree ElementTree C14NWriterTarget8110959
Ref: 2b878110959
Ref: TreeBuilder 对象-Footnote-18111473
Node: XMLParser对象8111514
Ref: library/xml etree elementtree elementtree-xmlparser-objects8111636
Ref: 2b888111636
Ref: library/xml etree elementtree xmlparser-objects8111636
Ref: 2b898111636
Ref: library/xml etree elementtree xml etree ElementTree XMLParser8111687
Ref: 37c8111687
Ref: library/xml etree elementtree xml etree ElementTree XMLParser close8112413
Ref: 2b8b8112413
Ref: library/xml etree elementtree xml etree ElementTree XMLParser feed8112641
Ref: 2b8a8112641
Ref: XMLParser对象-Footnote-18114530
Node: XMLPullParser对象8114838
Ref: library/xml etree elementtree elementtree-xmlpullparser-objects8114952
Ref: 2b8c8114952
Ref: library/xml etree elementtree xmlpullparser-objects8114952
Ref: 2b8d8114952
Ref: library/xml etree elementtree xml etree ElementTree XMLPullParser8115011
Ref: 9f98115011
Ref: library/xml etree elementtree xml etree ElementTree XMLPullParser feed8115645
Ref: 2b418115645
Ref: library/xml etree elementtree xml etree ElementTree XMLPullParser close8115735
Ref: 2b8e8115735
Ref: library/xml etree elementtree xml etree ElementTree XMLPullParser read_events8116029
Ref: 2b428116029
Node: 异常<14>8117564
Ref: library/xml etree elementtree exceptions8117654
Ref: 2b8f8117654
Ref: library/xml etree elementtree xml etree ElementTree ParseError8117687
Ref: cd78117687
Ref: library/xml etree elementtree xml etree ElementTree ParseError code8117954
Ref: 2b908117954
Ref: library/xml etree elementtree xml etree ElementTree ParseError position8118139
Ref: 2b918118139
Node: xml dom --- 文档对象模型 API8118269
Ref: library/xml dom doc8118473
Ref: 2b928118473
Ref: library/xml dom module-xml dom8118473
Ref: 13d8118473
Ref: library/xml dom xml-dom-the-document-object-model-api8118473
Ref: 2b938118473
Ref: xml dom --- 文档对象模型 API-Footnote-18121665
Ref: xml dom --- 文档对象模型 API-Footnote-28121741
Ref: xml dom --- 文档对象模型 API-Footnote-38121807
Ref: xml dom --- 文档对象模型 API-Footnote-48121854
Node: 模块内容<6>8121913
Ref: library/xml dom module-contents8122024
Ref: 2b968122024
Ref: library/xml dom xml dom registerDOMImplementation8122106
Ref: 2b978122106
Ref: library/xml dom xml dom getDOMImplementation8122499
Ref: 2b948122499
Ref: library/xml dom xml dom EMPTY_NAMESPACE8123325
Ref: 2b988123325
Ref: library/xml dom xml dom XML_NAMESPACE8123581
Ref: 2b998123581
Ref: library/xml dom xml dom XMLNS_NAMESPACE8123741
Ref: 2b9a8123741
Ref: library/xml dom xml dom XHTML_NAMESPACE8123922
Ref: 2b9b8123922
Ref: 模块内容<6>-Footnote-18124554
Ref: 模块内容<6>-Footnote-28124599
Ref: 模块内容<6>-Footnote-38124656
Node: DOM 中的对象8124694
Ref: library/xml dom dom-objects8124823
Ref: 2b9c8124823
Ref: library/xml dom objects-in-the-dom8124823
Ref: 2b9d8124823
Node: DOMImplementation 对象8128509
Ref: library/xml dom dom-implementation-objects8128607
Ref: 2b9e8128607
Ref: library/xml dom domimplementation-objects8128607
Ref: 2ba88128607
Ref: library/xml dom xml dom DOMImplementation hasFeature8128932
Ref: 2ba98128932
Ref: library/xml dom xml dom DOMImplementation createDocument8129107
Ref: 2baa8129107
Ref: library/xml dom xml dom DOMImplementation createDocumentType8129623
Ref: 2bab8129623
Node: 节点对象8129912
Ref: library/xml dom dom-node-objects8130037
Ref: 2b9f8130037
Ref: library/xml dom node-objects8130037
Ref: 2bac8130037
Ref: library/xml dom xml dom Node nodeType8130141
Ref: 2bad8130141
Ref: library/xml dom xml dom Node parentNode8130529
Ref: 2bae8130529
Ref: library/xml dom xml dom Node attributes8130920
Ref: 2baf8130920
Ref: library/xml dom xml dom Node previousSibling8131109
Ref: 2bb08131109
Ref: library/xml dom xml dom Node nextSibling8131528
Ref: 2bb18131528
Ref: library/xml dom xml dom Node childNodes8131787
Ref: 2bb28131787
Ref: library/xml dom xml dom Node firstChild8131890
Ref: 2bb38131890
Ref: library/xml dom xml dom Node lastChild8132019
Ref: 2bb48132019
Ref: library/xml dom xml dom Node localName8132150
Ref: 2bb58132150
Ref: library/xml dom xml dom Node prefix8132315
Ref: 2bb68132315
Ref: library/xml dom xml dom Node namespaceURI8132490
Ref: 2bb78132490
Ref: library/xml dom xml dom Node nodeName8132643
Ref: 2bb88132643
Ref: library/xml dom xml dom Node nodeValue8133061
Ref: 2bb98133061
Ref: library/xml dom xml dom Node hasAttributes8133298
Ref: 2bba8133298
Ref: library/xml dom xml dom Node hasChildNodes8133402
Ref: 2bbb8133402
Ref: library/xml dom xml dom Node isSameNode8133509
Ref: 2bbc8133509
Ref: library/xml dom xml dom Node appendChild8134072
Ref: 2bbd8134072
Ref: library/xml dom xml dom Node insertBefore8134267
Ref: 2bbe8134267
Ref: library/xml dom xml dom Node removeChild8134645
Ref: 2bbf8134645
Ref: library/xml dom xml dom Node replaceChild8134961
Ref: 2bc08134961
Ref: library/xml dom xml dom Node normalize8135194
Ref: 2bc18135194
Ref: library/xml dom xml dom Node cloneNode8135403
Ref: 2bc28135403
Node: 节点列表对象8135560
Ref: library/xml dom dom-nodelist-objects8135679
Ref: 2ba08135679
Ref: library/xml dom nodelist-objects8135679
Ref: 2bc38135679
Ref: library/xml dom xml dom NodeList item8136110
Ref: 2bc48136110
Ref: library/xml dom xml dom NodeList length8136313
Ref: 2bc58136313
Node: 文档类型对象8136888
Ref: library/xml dom documenttype-objects8137010
Ref: 2bc68137010
Ref: library/xml dom dom-documenttype-objects8137010
Ref: 2ba18137010
Ref: library/xml dom xml dom DocumentType publicId8137537
Ref: 2bc78137537
Ref: library/xml dom xml dom DocumentType systemId8137678
Ref: 2bc88137678
Ref: library/xml dom xml dom DocumentType internalSubset8137841
Ref: 2bc98137841
Ref: library/xml dom xml dom DocumentType name8138051
Ref: 2bca8138051
Ref: library/xml dom xml dom DocumentType entities8138157
Ref: 2bcb8138157
Ref: library/xml dom xml dom DocumentType notations8138484
Ref: 2bcc8138484
Node: Document 对象8138801
Ref: library/xml dom document-objects8138920
Ref: 2bcd8138920
Ref: library/xml dom dom-document-objects8138920
Ref: 2ba28138920
Ref: library/xml dom xml dom Document documentElement8139134
Ref: 2bce8139134
Ref: library/xml dom xml dom Document createElement8139206
Ref: 2bcf8139206
Ref: library/xml dom xml dom Document createElementNS8139481
Ref: 2bd08139481
Ref: library/xml dom xml dom Document createTextNode8139818
Ref: 2bd18139818
Ref: library/xml dom xml dom Document createComment8140029
Ref: 2bd28140029
Ref: library/xml dom xml dom Document createProcessingInstruction8140239
Ref: 2bd38140239
Ref: library/xml dom xml dom Document createAttribute8140492
Ref: 2bd48140492
Ref: library/xml dom xml dom Document createAttributeNS8140775
Ref: 2bd58140775
Ref: library/xml dom xml dom Document getElementsByTagName8141137
Ref: 2bd68141137
Ref: library/xml dom xml dom Document getElementsByTagNameNS8141311
Ref: 2bd78141311
Node: 元素对象<2>8141569
Ref: library/xml dom dom-element-objects8141681
Ref: 2ba38141681
Ref: library/xml dom element-objects8141681
Ref: 2bd88141681
Ref: library/xml dom xml dom Element tagName8141804
Ref: 2bd98141804
Ref: library/xml dom xml dom Element getElementsByTagName8141953
Ref: 2bda8141953
Ref: library/xml dom xml dom Element getElementsByTagNameNS8142067
Ref: 2bdb8142067
Ref: library/xml dom xml dom Element hasAttribute8142199
Ref: 2bdc8142199
Ref: library/xml dom xml dom Element hasAttributeNS8142320
Ref: 2bdd8142320
Ref: library/xml dom xml dom Element getAttribute8142491
Ref: 2bde8142491
Ref: library/xml dom xml dom Element getAttributeNode8142707
Ref: 2bdf8142707
Ref: library/xml dom xml dom Element getAttributeNS8142835
Ref: 2be08142835
Ref: library/xml dom xml dom Element getAttributeNodeNS8143096
Ref: 2be18143096
Ref: library/xml dom xml dom Element removeAttribute8143252
Ref: 2be28143252
Ref: library/xml dom xml dom Element removeAttributeNode8143415
Ref: 2be48143415
Ref: library/xml dom xml dom Element removeAttributeNS8143630
Ref: 2be58143630
Ref: library/xml dom xml dom Element setAttribute8143847
Ref: 2be68143847
Ref: library/xml dom xml dom Element setAttributeNode8143947
Ref: 2be78143947
Ref: library/xml dom xml dom Element setAttributeNodeNS8144274
Ref: 2be98144274
Ref: library/xml dom xml dom Element setAttributeNS8144635
Ref: 2bea8144635
Node: Attr 对象8144860
Ref: library/xml dom attr-objects8144976
Ref: 2beb8144976
Ref: library/xml dom dom-attr-objects8144976
Ref: 2ba48144976
Ref: library/xml dom xml dom Attr name8145086
Ref: 2bec8145086
Ref: library/xml dom xml dom Attr localName8145189
Ref: 2bed8145189
Ref: library/xml dom xml dom Attr prefix8145324
Ref: 2bee8145324
Ref: library/xml dom xml dom Attr value8145437
Ref: 2bef8145437
Node: NamedNodeMap 对象8145528
Ref: library/xml dom dom-attributelist-objects8145641
Ref: 2bf08145641
Ref: library/xml dom namednodemap-objects8145641
Ref: 2bf18145641
Ref: library/xml dom xml dom NamedNodeMap length8145753
Ref: 2bf28145753
Ref: library/xml dom xml dom NamedNodeMap item8145817
Ref: 2bf38145817
Node: 注释对象8146267
Ref: library/xml dom comment-objects8146397
Ref: 2bf48146397
Ref: library/xml dom dom-comment-objects8146397
Ref: 2ba58146397
Ref: library/xml dom xml dom Comment data8146550
Ref: 2bf58146550
Node: Text 和 CDATASection 对象8146748
Ref: library/xml dom dom-text-objects8146887
Ref: 2ba68146887
Ref: library/xml dom text-and-cdatasection-objects8146887
Ref: 2bf68146887
Ref: library/xml dom xml dom Text data8147320
Ref: 2bf78147320
Node: ProcessingInstruction 对象8147748
Ref: library/xml dom dom-pi-objects8147885
Ref: 2ba78147885
Ref: library/xml dom processinginstruction-objects8147885
Ref: 2bf88147885
Ref: library/xml dom xml dom ProcessingInstruction target8148066
Ref: 2bf98148066
Ref: library/xml dom xml dom ProcessingInstruction data8148191
Ref: 2bfa8148191
Node: 异常<15>8148289
Ref: library/xml dom dom-exceptions8148389
Ref: 2bfb8148389
Ref: library/xml dom exceptions8148389
Ref: 2bfc8148389
Ref: library/xml dom xml dom DOMException8148921
Ref: 2bfd8148921
Ref: library/xml dom xml dom DomstringSizeErr8149052
Ref: 2bfe8149052
Ref: library/xml dom xml dom HierarchyRequestErr8149276
Ref: 2bff8149276
Ref: library/xml dom xml dom IndexSizeErr8149396
Ref: 2c008149396
Ref: library/xml dom xml dom InuseAttributeErr8149527
Ref: 2be88149527
Ref: library/xml dom xml dom InvalidAccessErr8149669
Ref: 2c018149669
Ref: library/xml dom xml dom InvalidCharacterErr8149783
Ref: 2c028149783
Ref: library/xml dom xml dom InvalidModificationErr8150072
Ref: 2c038150072
Ref: library/xml dom xml dom InvalidStateErr8150174
Ref: 2c048150174
Ref: library/xml dom xml dom NamespaceErr8150284
Ref: 2c058150284
Ref: library/xml dom xml dom NotFoundErr8150445
Ref: 2be38150445
Ref: library/xml dom xml dom NotSupportedErr8150682
Ref: 2c068150682
Ref: library/xml dom xml dom NoDataAllowedErr8150798
Ref: 2c078150798
Ref: library/xml dom xml dom NoModificationAllowedErr8150907
Ref: 2c088150907
Ref: library/xml dom xml dom SyntaxErr8151044
Ref: 2c098151044
Ref: library/xml dom xml dom WrongDocumentErr8151136
Ref: 2c0a8151136
Ref: 异常<15>-Footnote-18154102
Node: 一致性8154147
Ref: library/xml dom conformance8154252
Ref: 2c0b8154252
Ref: library/xml dom dom-conformance8154252
Ref: 2b958154252
Node: 类型映射8154455
Ref: library/xml dom dom-type-mapping8154537
Ref: 2c0c8154537
Ref: library/xml dom type-mapping8154537
Ref: 2c0d8154537
Node: 访问器方法8155333
Ref: library/xml dom accessor-methods8155415
Ref: 2c0e8155415
Ref: library/xml dom dom-accessor-methods8155415
Ref: 2c0f8155415
Node: xml dom minidom --- 最小化的 DOM 实现8157088
Ref: library/xml dom minidom doc8157293
Ref: 2c108157293
Ref: library/xml dom minidom module-xml dom minidom8157293
Ref: 13e8157293
Ref: library/xml dom minidom xml-dom-minidom-minimal-dom-implementation8157293
Ref: 2c118157293
Ref: library/xml dom minidom xml dom minidom parse8158549
Ref: 2c128158549
Ref: library/xml dom minidom xml dom minidom parseString8159118
Ref: 2c138159118
Ref: xml dom minidom --- 最小化的 DOM 实现-Footnote-18161593
Ref: xml dom minidom --- 最小化的 DOM 实现-Footnote-28161667
Node: DOM 对象8161714
Ref: library/xml dom minidom dom-objects8161823
Ref: 2c148161823
Ref: library/xml dom minidom minidom-objects8161823
Ref: 2c158161823
Ref: library/xml dom minidom xml dom minidom Node unlink8162029
Ref: 2c168162029
Ref: library/xml dom minidom xml dom minidom Node writexml8162764
Ref: 2c178162764
Ref: library/xml dom minidom xml dom minidom Node toxml8163821
Ref: 2c188163821
Ref: library/xml dom minidom xml dom minidom Node toprettyxml8164576
Ref: 2c198164576
Ref: DOM 对象-Footnote-18165217
Node: DOM 示例8165605
Ref: library/xml dom minidom dom-example8165745
Ref: 2c1a8165745
Ref: library/xml dom minidom id28165745
Ref: 2c1b8165745
Node: minidom 和 DOM 标准8167757
Ref: library/xml dom minidom minidom-and-dom8167878
Ref: 2c1c8167878
Ref: library/xml dom minidom minidom-and-the-dom-standard8167878
Ref: 2c1d8167878
Node: xml dom pulldom --- 支持构建部分 DOM 树8170224
Ref: library/xml dom pulldom doc8170428
Ref: 2c1e8170428
Ref: library/xml dom pulldom module-xml dom pulldom8170428
Ref: 13f8170428
Ref: library/xml dom pulldom xml-dom-pulldom-support-for-building-partial-dom-trees8170428
Ref: 2c1f8170428
Ref: library/xml dom pulldom xml dom pulldom PullDom8172949
Ref: 2c218172949
Ref: library/xml dom pulldom xml dom pulldom SAX2DOM8173072
Ref: 2c238173072
Ref: library/xml dom pulldom xml dom pulldom parse8173195
Ref: 2c248173195
Ref: library/xml dom pulldom xml dom pulldom parseString8173781
Ref: 2c268173781
Ref: library/xml dom pulldom xml dom pulldom default_bufsize8173922
Ref: 2c278173922
Ref: xml dom pulldom --- 支持构建部分 DOM 树-Footnote-18174195
Node: DOMEventStream 对象8174269
Ref: library/xml dom pulldom domeventstream-objects8174373
Ref: 2c288174373
Ref: library/xml dom pulldom id18174373
Ref: 2c298174373
Ref: library/xml dom pulldom xml dom pulldom DOMEventStream8174434
Ref: 3a28174434
Ref: library/xml dom pulldom xml dom pulldom DOMEventStream getEvent8174585
Ref: 2c2a8174585
Ref: library/xml dom pulldom xml dom pulldom DOMEventStream expandNode8175096
Ref: 2c208175096
Ref: library/xml dom pulldom xml dom pulldom DOMEventStream reset8175823
Ref: 2c2b8175823
Node: xml sax --- 支持 SAX2 解析器8175856
Ref: library/xml sax doc8176062
Ref: 2c2c8176062
Ref: library/xml sax module-xml sax8176062
Ref: 1448176062
Ref: library/xml sax xml-sax-support-for-sax2-parsers8176062
Ref: 2c2d8176062
Ref: library/xml sax xml sax make_parser8177062
Ref: 115f8177062
Ref: library/xml sax xml sax parse8177600
Ref: 111c8177600
Ref: library/xml sax xml sax parseString8178211
Ref: 8828178211
Ref: library/xml sax xml sax SAXException8180026
Ref: 2c338180026
Ref: library/xml sax xml sax SAXParseException8180780
Ref: 2c318180780
Ref: library/xml sax xml sax SAXNotRecognizedException8181143
Ref: 2c348181143
Ref: library/xml sax xml sax SAXNotSupportedException8181422
Ref: 2c358181422
Ref: xml sax --- 支持 SAX2 解析器-Footnote-18182308
Ref: xml sax --- 支持 SAX2 解析器-Footnote-28182384
Node: SAXException 对象8182419
Ref: library/xml sax sax-exception-objects8182508
Ref: 2c368182508
Ref: library/xml sax saxexception-objects8182508
Ref: 2c378182508
Ref: library/xml sax xml sax SAXException getMessage8182621
Ref: 2c388182621
Ref: library/xml sax xml sax SAXException getException8182731
Ref: 2c398182731
Node: xml sax handler --- SAX 处理句柄的基类8182839
Ref: library/xml sax handler doc8183033
Ref: 2c3a8183033
Ref: library/xml sax handler module-xml sax handler8183033
Ref: 1458183033
Ref: library/xml sax handler xml-sax-handler-base-classes-for-sax-handlers8183033
Ref: 2c3b8183033
Ref: library/xml sax handler xml sax handler ContentHandler8183640
Ref: 2c228183640
Ref: library/xml sax handler xml sax handler DTDHandler8183850
Ref: 2c3c8183850
Ref: library/xml sax handler xml sax handler EntityResolver8184022
Ref: 2c3d8184022
Ref: library/xml sax handler xml sax handler ErrorHandler8184278
Ref: 2c308184278
Ref: library/xml sax handler xml sax handler feature_namespaces8184602
Ref: 2c3e8184602
Ref: library/xml sax handler xml sax handler feature_namespace_prefixes8184914
Ref: 2c3f8184914
Ref: library/xml sax handler xml sax handler feature_string_interning8185304
Ref: 2c408185304
Ref: library/xml sax handler xml sax handler feature_validation8185709
Ref: 2c418185709
Ref: library/xml sax handler xml sax handler feature_external_ges8186036
Ref: 2c2f8186036
Ref: library/xml sax handler xml sax handler feature_external_pes8186334
Ref: 2c428186334
Ref: library/xml sax handler xml sax handler all_features8186689
Ref: 2c438186689
Ref: library/xml sax handler xml sax handler property_lexical_handler8186757
Ref: 2c448186757
Ref: library/xml sax handler xml sax handler property_declaration_handler8187074
Ref: 2c458187074
Ref: library/xml sax handler xml sax handler property_dom_node8187425
Ref: 2c468187425
Ref: library/xml sax handler xml sax handler property_xml_string8187821
Ref: 2c478187821
Ref: library/xml sax handler xml sax handler all_properties8188060
Ref: 2c488188060
Ref: xml sax handler --- SAX 处理句柄的基类-Footnote-18188280
Node: ContentHandler 对象8188354
Ref: library/xml sax handler content-handler-objects8188483
Ref: 2c498188483
Ref: library/xml sax handler contenthandler-objects8188483
Ref: 2c4a8188483
Ref: library/xml sax handler xml sax handler ContentHandler setDocumentLocator8188700
Ref: 2c4b8188700
Ref: library/xml sax handler xml sax handler ContentHandler startDocument8189614
Ref: 2c4c8189614
Ref: library/xml sax handler xml sax handler ContentHandler endDocument8189898
Ref: 2c4d8189898
Ref: library/xml sax handler xml sax handler ContentHandler startPrefixMapping8190242
Ref: 2c4e8190242
Ref: library/xml sax handler xml sax handler ContentHandler endPrefixMapping8191358
Ref: 2c4f8191358
Ref: library/xml sax handler xml sax handler ContentHandler startElement8191697
Ref: 2c508191697
Ref: library/xml sax handler xml sax handler ContentHandler endElement8192265
Ref: 2c518192265
Ref: library/xml sax handler xml sax handler ContentHandler startElementNS8192487
Ref: 2c538192487
Ref: library/xml sax handler xml sax handler ContentHandler endElementNS8193370
Ref: 2c558193370
Ref: library/xml sax handler xml sax handler ContentHandler characters8193632
Ref: 2c568193632
Ref: library/xml sax handler xml sax handler ContentHandler ignorableWhitespace8194613
Ref: 2c578194613
Ref: library/xml sax handler xml sax handler ContentHandler processingInstruction8195221
Ref: 2c588195221
Ref: library/xml sax handler xml sax handler ContentHandler skippedEntity8195635
Ref: 2c598195635
Node: DTDHandler 对象8196161
Ref: library/xml sax handler dtd-handler-objects8196320
Ref: 2c5a8196320
Ref: library/xml sax handler dtdhandler-objects8196320
Ref: 2c5b8196320
Ref: library/xml sax handler xml sax handler DTDHandler notationDecl8196429
Ref: 2c5c8196429
Ref: library/xml sax handler xml sax handler DTDHandler unparsedEntityDecl8196533
Ref: 2c5d8196533
Node: EntityResolver 对象8196672
Ref: library/xml sax handler entity-resolver-objects8196829
Ref: 2c5e8196829
Ref: library/xml sax handler entityresolver-objects8196829
Ref: 2c5f8196829
Ref: library/xml sax handler xml sax handler EntityResolver resolveEntity8196892
Ref: 2c608196892
Node: ErrorHandler 对象8197158
Ref: library/xml sax handler errorhandler-objects8197289
Ref: 2c618197289
Ref: library/xml sax handler sax-error-handler8197289
Ref: 2c628197289
Ref: library/xml sax handler xml sax handler ErrorHandler error8197904
Ref: 2c638197904
Ref: library/xml sax handler xml sax handler ErrorHandler fatalError8198230
Ref: 2c648198230
Ref: library/xml sax handler xml sax handler ErrorHandler warning8198391
Ref: 2c658198391
Node: xml sax saxutils --- SAX 工具集8198674
Ref: library/xml sax utils doc8198886
Ref: 2c668198886
Ref: library/xml sax utils module-xml sax saxutils8198886
Ref: 1468198886
Ref: library/xml sax utils xml-sax-saxutils-sax-utilities8198886
Ref: 2c678198886
Ref: library/xml sax utils xml sax saxutils escape8199254
Ref: 2c688199254
Ref: library/xml sax utils xml sax saxutils unescape8199697
Ref: 2c698199697
Ref: library/xml sax utils xml sax saxutils quoteattr8200171
Ref: 2c6a8200171
Ref: library/xml sax utils xml sax saxutils XMLGenerator8200949
Ref: 2c6b8200949
Ref: library/xml sax utils xml sax saxutils XMLFilterBase8201762
Ref: 2c6c8201762
Ref: library/xml sax utils xml sax saxutils prepare_input_source8202148
Ref: 2c6d8202148
Ref: xml sax saxutils --- SAX 工具集-Footnote-18202607
Node: xml sax xmlreader --- 用于 XML 解析器的接口8202683
Ref: library/xml sax reader doc8202905
Ref: 2c6e8202905
Ref: library/xml sax reader module-xml sax xmlreader8202905
Ref: 1478202905
Ref: library/xml sax reader xml-sax-xmlreader-interface-for-xml-parsers8202905
Ref: 2c6f8202905
Ref: library/xml sax reader xml sax xmlreader XMLReader8203408
Ref: 2c258203408
Ref: library/xml sax reader xml sax xmlreader IncrementalParser8203494
Ref: 2c708203494
Ref: library/xml sax reader xml sax xmlreader Locator8204499
Ref: 2c328204499
Ref: library/xml sax reader xml sax xmlreader InputSource8204828
Ref: 8818204828
Ref: library/xml sax reader xml sax xmlreader AttributesImpl8205497
Ref: 2c728205497
Ref: library/xml sax reader xml sax xmlreader AttributesNSImpl8205973
Ref: 2c738205973
Ref: xml sax xmlreader --- 用于 XML 解析器的接口-Footnote-18206674
Node: XMLReader 对象8206751
Ref: library/xml sax reader id18206888
Ref: 2c748206888
Ref: library/xml sax reader xmlreader-objects8206888
Ref: 2c758206888
Ref: library/xml sax reader xml sax xmlreader XMLReader parse8206991
Ref: 2c718206991
Ref: library/xml sax reader xml sax xmlreader XMLReader getContentHandler8207545
Ref: 2c768207545
Ref: library/xml sax reader xml sax xmlreader XMLReader setContentHandler8207648
Ref: 2c778207648
Ref: library/xml sax reader xml sax xmlreader XMLReader getDTDHandler8207840
Ref: 2c788207840
Ref: library/xml sax reader xml sax xmlreader XMLReader setDTDHandler8207935
Ref: 2c798207935
Ref: library/xml sax reader xml sax xmlreader XMLReader getEntityResolver8208113
Ref: 2c7a8208113
Ref: library/xml sax reader xml sax xmlreader XMLReader setEntityResolver8208216
Ref: 2c7b8208216
Ref: library/xml sax reader xml sax xmlreader XMLReader getErrorHandler8208507
Ref: 2c7c8208507
Ref: library/xml sax reader xml sax xmlreader XMLReader setErrorHandler8208606
Ref: 2c7d8208606
Ref: library/xml sax reader xml sax xmlreader XMLReader setLocale8208818
Ref: 2c7e8208818
Ref: library/xml sax reader xml sax xmlreader XMLReader getFeature8209169
Ref: 2c7f8209169
Ref: library/xml sax reader xml sax xmlreader XMLReader setFeature8209439
Ref: 2c2e8209439
Ref: library/xml sax reader xml sax xmlreader XMLReader getProperty8209725
Ref: 2c808209725
Ref: library/xml sax reader xml sax xmlreader XMLReader setProperty8209998
Ref: 2c818209998
Node: IncrementalParser 对象8210287
Ref: library/xml sax reader incremental-parser-objects8210447
Ref: 2c828210447
Ref: library/xml sax reader incrementalparser-objects8210447
Ref: 2c838210447
Ref: library/xml sax reader xml sax xmlreader IncrementalParser feed8210586
Ref: 2c848210586
Ref: library/xml sax reader xml sax xmlreader IncrementalParser close8210674
Ref: 2c858210674
Ref: library/xml sax reader xml sax xmlreader IncrementalParser reset8210905
Ref: 2c868210905
Node: Locator 对象8211155
Ref: library/xml sax reader id28211317
Ref: 2c878211317
Ref: library/xml sax reader locator-objects8211317
Ref: 2c888211317
Ref: library/xml sax reader xml sax xmlreader Locator getColumnNumber8211420
Ref: 2c898211420
Ref: library/xml sax reader xml sax xmlreader Locator getLineNumber8211515
Ref: 2c8a8211515
Ref: library/xml sax reader xml sax xmlreader Locator getPublicId8211608
Ref: 2c8b8211608
Ref: library/xml sax reader xml sax xmlreader Locator getSystemId8211696
Ref: 2c8c8211696
Node: InputSource 对象8211784
Ref: library/xml sax reader input-source-objects8211939
Ref: 2c8d8211939
Ref: library/xml sax reader inputsource-objects8211939
Ref: 2c8e8211939
Ref: library/xml sax reader xml sax xmlreader InputSource setPublicId8211996
Ref: 2c8f8211996
Ref: library/xml sax reader xml sax xmlreader InputSource getPublicId8212106
Ref: 2c908212106
Ref: library/xml sax reader xml sax xmlreader InputSource setSystemId8212214
Ref: 2c918212214
Ref: library/xml sax reader xml sax xmlreader InputSource getSystemId8212324
Ref: 2c928212324
Ref: library/xml sax reader xml sax xmlreader InputSource setEncoding8212432
Ref: 2c938212432
Ref: library/xml sax reader xml sax xmlreader InputSource getEncoding8212796
Ref: 2c948212796
Ref: library/xml sax reader xml sax xmlreader InputSource setByteStream8212895
Ref: 2c958212895
Ref: library/xml sax reader xml sax xmlreader InputSource getByteStream8213309
Ref: 2c968213309
Ref: library/xml sax reader xml sax xmlreader InputSource setCharacterStream8213507
Ref: 2c978213507
Ref: library/xml sax reader xml sax xmlreader InputSource getCharacterStream8213795
Ref: 2c988213795
Node: Attributes 接口8213888
Ref: library/xml sax reader attributes-objects8214048
Ref: 2c528214048
Ref: library/xml sax reader the-attributes-interface8214048
Ref: 2c998214048
Ref: library/xml sax reader xml sax xmlreader Attributes getLength8214329
Ref: 2c9a8214329
Ref: library/xml sax reader xml sax xmlreader Attributes getNames8214403
Ref: 2c9b8214403
Ref: library/xml sax reader xml sax xmlreader Attributes getType8214476
Ref: 2c9c8214476
Ref: library/xml sax reader xml sax xmlreader Attributes getValue8214586
Ref: 2c9d8214586
Node: AttributesNS 接口8214668
Ref: library/xml sax reader attributes-ns-objects8214801
Ref: 2c548214801
Ref: library/xml sax reader the-attributesns-interface8214801
Ref: 2c9e8214801
Ref: library/xml sax reader xml sax xmlreader AttributesNS getValueByQName8215092
Ref: 2c9f8215092
Ref: library/xml sax reader xml sax xmlreader AttributesNS getNameByQName8215187
Ref: 2ca08215187
Ref: library/xml sax reader xml sax xmlreader AttributesNS getQNameByName8215313
Ref: 2ca18215313
Ref: library/xml sax reader xml sax xmlreader AttributesNS getQNames8215431
Ref: 2ca28215431
Node: xml parsers expat --- 使用 Expat 的快速 XML 解析8215519
Ref: library/pyexpat doc8215698
Ref: 2ca38215698
Ref: library/pyexpat module-xml parsers expat8215698
Ref: 1418215698
Ref: library/pyexpat xml-parsers-expat-fast-xml-parsing-using-expat8215698
Ref: 2ca48215698
Ref: library/pyexpat xml parsers expat ExpatError8216721
Ref: cd88216721
Ref: library/pyexpat xml parsers expat error8216915
Ref: 2ca68216915
Ref: library/pyexpat xml parsers expat XMLParserType8216994
Ref: 2ca78216994
Ref: library/pyexpat xml parsers expat ErrorString8217166
Ref: 2ca98217166
Ref: library/pyexpat xml parsers expat ParserCreate8217278
Ref: 2ca88217278
Ref: xml parsers expat --- 使用 Expat 的快速 XML 解析-Footnote-18219606
Ref: xml parsers expat --- 使用 Expat 的快速 XML 解析-Footnote-28219914
Node: XMLParser对象<2>8219947
Ref: library/pyexpat id28220083
Ref: 2caa8220083
Ref: library/pyexpat xmlparser-objects8220083
Ref: 2cab8220083
Ref: library/pyexpat xml parsers expat xmlparser Parse8220177
Ref: 2cac8220177
Ref: library/pyexpat xml parsers expat xmlparser ParseFile8220535
Ref: 2cad8220535
Ref: library/pyexpat xml parsers expat xmlparser SetBase8220742
Ref: 2cae8220742
Ref: library/pyexpat xml parsers expat xmlparser GetBase8221115
Ref: 2cb28221115
Ref: library/pyexpat xml parsers expat xmlparser GetInputContext8221323
Ref: 2cb38221323
Ref: library/pyexpat xml parsers expat xmlparser ExternalEntityParserCreate8221577
Ref: 2cb48221577
Ref: library/pyexpat xml parsers expat xmlparser SetParamEntityParsing8222047
Ref: 2cb78222047
Ref: library/pyexpat xml parsers expat xmlparser UseForeignDTD8222388
Ref: 2cb88222388
Ref: library/pyexpat xml parsers expat xmlparser buffer_size8223322
Ref: 2cbb8223322
Ref: library/pyexpat xml parsers expat xmlparser buffer_text8223587
Ref: 2cbc8223587
Ref: library/pyexpat xml parsers expat xmlparser buffer_used8223999
Ref: 2cbe8223999
Ref: library/pyexpat xml parsers expat xmlparser ordered_attributes8224261
Ref: 2cb58224261
Ref: library/pyexpat xml parsers expat xmlparser specified_attributes8224683
Ref: 2cb68224683
Ref: library/pyexpat xml parsers expat xmlparser ErrorByteIndex8225329
Ref: 2cbf8225329
Ref: library/pyexpat xml parsers expat xmlparser ErrorCode8225413
Ref: 2cc08225413
Ref: library/pyexpat xml parsers expat xmlparser ErrorColumnNumber8225619
Ref: 2cc18225619
Ref: library/pyexpat xml parsers expat xmlparser ErrorLineNumber8225697
Ref: 2cc28225697
Ref: library/pyexpat xml parsers expat xmlparser CurrentByteIndex8226103
Ref: 2cc38226103
Ref: library/pyexpat xml parsers expat xmlparser CurrentColumnNumber8226192
Ref: 2cc48226192
Ref: library/pyexpat xml parsers expat xmlparser CurrentLineNumber8226275
Ref: 2cc58226275
Ref: library/pyexpat xml parsers expat xmlparser XmlDeclHandler8226668
Ref: 2cc68226668
Ref: library/pyexpat xml parsers expat xmlparser StartDoctypeDeclHandler8227202
Ref: 2cb98227202
Ref: library/pyexpat xml parsers expat xmlparser EndDoctypeDeclHandler8227717
Ref: 2cba8227717
Ref: library/pyexpat xml parsers expat xmlparser ElementDeclHandler8227878
Ref: 2cc78227878
Ref: library/pyexpat xml parsers expat xmlparser AttlistDeclHandler8228072
Ref: 2cc88228072
Ref: library/pyexpat xml parsers expat xmlparser StartElementHandler8228881
Ref: 2cc98228881
Ref: library/pyexpat xml parsers expat xmlparser EndElementHandler8229265
Ref: 2cca8229265
Ref: library/pyexpat xml parsers expat xmlparser ProcessingInstructionHandler8229362
Ref: 2ccb8229362
Ref: library/pyexpat xml parsers expat xmlparser CharacterDataHandler8229475
Ref: 2cbd8229475
Ref: library/pyexpat xml parsers expat xmlparser UnparsedEntityDeclHandler8229872
Ref: 2cb18229872
Ref: library/pyexpat xml parsers expat xmlparser EntityDeclHandler8230235
Ref: 2cce8230235
Ref: library/pyexpat xml parsers expat xmlparser NotationDeclHandler8230903
Ref: 2cb08230903
Ref: library/pyexpat xml parsers expat xmlparser StartNamespaceDeclHandler8231203
Ref: 2ccf8231203
Ref: library/pyexpat xml parsers expat xmlparser EndNamespaceDeclHandler8231446
Ref: 2cd08231446
Ref: library/pyexpat xml parsers expat xmlparser CommentHandler8231906
Ref: 2cd18231906
Ref: library/pyexpat xml parsers expat xmlparser StartCdataSectionHandler8232094
Ref: 2ccc8232094
Ref: library/pyexpat xml parsers expat xmlparser EndCdataSectionHandler8232320
Ref: 2ccd8232320
Ref: library/pyexpat xml parsers expat xmlparser DefaultHandler8232422
Ref: 2cd28232422
Ref: library/pyexpat xml parsers expat xmlparser DefaultHandlerExpand8232660
Ref: 2cd38232660
Ref: library/pyexpat xml parsers expat xmlparser NotStandaloneHandler8232869
Ref: 2cd48232869
Ref: library/pyexpat xml parsers expat xmlparser ExternalEntityRefHandler8233368
Ref: 2caf8233368
Node: ExpatError 异常8234402
Ref: library/pyexpat expaterror-exceptions8234557
Ref: 2cd58234557
Ref: library/pyexpat expaterror-objects8234557
Ref: 2ca58234557
Ref: library/pyexpat xml parsers expat ExpatError code8234671
Ref: 2cd68234671
Ref: library/pyexpat xml parsers expat ExpatError lineno8235272
Ref: 2cd98235272
Ref: library/pyexpat xml parsers expat ExpatError offset8235373
Ref: 2cda8235373
Node: 示例<31>8235483
Ref: library/pyexpat example8235638
Ref: 2cdb8235638
Ref: library/pyexpat expat-example8235638
Ref: 2cdc8235638
Node: 内容模型描述8236732
Ref: library/pyexpat content-model-descriptions8236888
Ref: 2cdd8236888
Ref: library/pyexpat expat-content-models8236888
Ref: 2cde8236888
Ref: library/pyexpat module-xml parsers expat model8236888
Ref: 1438236888
Node: Expat 错误常量8238514
Ref: library/pyexpat expat-error-constants8238651
Ref: 2cdf8238651
Ref: library/pyexpat expat-errors8238651
Ref: 2ce08238651
Ref: library/pyexpat module-xml parsers expat errors8238651
Ref: 1428238651
Ref: library/pyexpat xml parsers expat errors codes8239179
Ref: 2cd88239179
Ref: library/pyexpat xml parsers expat errors messages8239306
Ref: 2cd78239306
Ref: library/pyexpat xml parsers expat errors XML_ERROR_ASYNC_ENTITY8239451
Ref: 2ce18239451
Ref: library/pyexpat xml parsers expat errors XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF8239510
Ref: 2ce28239510
Ref: library/pyexpat xml parsers expat errors XML_ERROR_BAD_CHAR_REF8239675
Ref: 2ce38239675
Ref: library/pyexpat xml parsers expat errors XML_ERROR_BINARY_ENTITY_REF8239844
Ref: 2ce48239844
Ref: library/pyexpat xml parsers expat errors XML_ERROR_DUPLICATE_ATTRIBUTE8239996
Ref: 2ce58239996
Ref: library/pyexpat xml parsers expat errors XML_ERROR_INCORRECT_ENCODING8240129
Ref: 2ce68240129
Ref: library/pyexpat xml parsers expat errors XML_ERROR_INVALID_TOKEN8240194
Ref: 2ce78240194
Ref: library/pyexpat xml parsers expat errors XML_ERROR_JUNK_AFTER_DOC_ELEMENT8240399
Ref: 2ce88240399
Ref: library/pyexpat xml parsers expat errors XML_ERROR_MISPLACED_XML_PI8240529
Ref: 2ce98240529
Ref: library/pyexpat xml parsers expat errors XML_ERROR_NO_ELEMENTS8240661
Ref: 2cea8240661
Ref: library/pyexpat xml parsers expat errors XML_ERROR_NO_MEMORY8240823
Ref: 2ceb8240823
Ref: library/pyexpat xml parsers expat errors XML_ERROR_PARAM_ENTITY_REF8240922
Ref: 2cec8240922
Ref: library/pyexpat xml parsers expat errors XML_ERROR_PARTIAL_CHAR8241049
Ref: 2ced8241049
Ref: library/pyexpat xml parsers expat errors XML_ERROR_RECURSIVE_ENTITY_REF8241160
Ref: 2cee8241160
Ref: library/pyexpat xml parsers expat errors XML_ERROR_SYNTAX8241366
Ref: 2cef8241366
Ref: library/pyexpat xml parsers expat errors XML_ERROR_TAG_MISMATCH8241468
Ref: 2cf08241468
Ref: library/pyexpat xml parsers expat errors XML_ERROR_UNCLOSED_TOKEN8241603
Ref: 2cf18241603
Ref: library/pyexpat xml parsers expat errors XML_ERROR_UNDEFINED_ENTITY8241764
Ref: 2cf28241764
Ref: library/pyexpat xml parsers expat errors XML_ERROR_UNKNOWN_ENCODING8241879
Ref: 2cf38241879
Ref: library/pyexpat xml parsers expat errors XML_ERROR_UNCLOSED_CDATA_SECTION8241992
Ref: 2cf48241992
Ref: library/pyexpat xml parsers expat errors XML_ERROR_EXTERNAL_ENTITY_HANDLING8242105
Ref: 2cf58242105
Ref: library/pyexpat xml parsers expat errors XML_ERROR_NOT_STANDALONE8242176
Ref: 2cf68242176
Ref: library/pyexpat xml parsers expat errors XML_ERROR_UNEXPECTED_STATE8242407
Ref: 2cf78242407
Ref: library/pyexpat xml parsers expat errors XML_ERROR_ENTITY_DECLARED_IN_PE8242470
Ref: 2cf88242470
Ref: library/pyexpat xml parsers expat errors XML_ERROR_FEATURE_REQUIRES_XML_DTD8242538
Ref: 2cf98242538
Ref: library/pyexpat xml parsers expat errors XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING8242824
Ref: 2cfa8242824
Ref: library/pyexpat xml parsers expat errors XML_ERROR_UNBOUND_PREFIX8243076
Ref: 2cfb8243076
Ref: library/pyexpat xml parsers expat errors XML_ERROR_UNDECLARING_PREFIX8243210
Ref: 2cfc8243210
Ref: library/pyexpat xml parsers expat errors XML_ERROR_INCOMPLETE_PE8243348
Ref: 2cfd8243348
Ref: library/pyexpat xml parsers expat errors XML_ERROR_XML_DECL8243460
Ref: 2cfe8243460
Ref: library/pyexpat xml parsers expat errors XML_ERROR_TEXT_DECL8243564
Ref: 2cff8243564
Ref: library/pyexpat xml parsers expat errors XML_ERROR_PUBLICID8243687
Ref: 2d008243687
Ref: library/pyexpat xml parsers expat errors XML_ERROR_SUSPENDED8243795
Ref: 2d018243795
Ref: library/pyexpat xml parsers expat errors XML_ERROR_NOT_SUSPENDED8243988
Ref: 2d028243988
Ref: library/pyexpat xml parsers expat errors XML_ERROR_ABORTED8244121
Ref: 2d038244121
Ref: library/pyexpat xml parsers expat errors XML_ERROR_FINISHED8244235
Ref: 2d048244235
Ref: library/pyexpat xml parsers expat errors XML_ERROR_SUSPEND_PE8244451
Ref: 2d058244451
Node: 互联网协议和支持8244521
Ref: library/internet doc8244681
Ref: 2d068244681
Ref: library/internet internet8244681
Ref: 2d078244681
Ref: library/internet internet-protocols-and-support8244681
Ref: 2d088244681
Node: webbrowser --- 方便的Web浏览器控制器8247138
Ref: library/webbrowser doc8247285
Ref: 2d098247285
Ref: library/webbrowser module-webbrowser8247285
Ref: 1328247285
Ref: library/webbrowser webbrowser-convenient-web-browser-controller8247285
Ref: 2d0a8247285
Ref: library/webbrowser webbrowser Error8249007
Ref: 2d0c8249007
Ref: library/webbrowser webbrowser open8249115
Ref: 2d0b8249115
Ref: library/webbrowser webbrowser open_new8249917
Ref: 2d0d8249917
Ref: library/webbrowser webbrowser open_new_tab8250086
Ref: 2d0e8250086
Ref: library/webbrowser webbrowser get8250264
Ref: 2d0f8250264
Ref: library/webbrowser webbrowser register8250477
Ref: 2d108250477
Ref: webbrowser --- 方便的Web浏览器控制器-Footnote-18256873
Ref: webbrowser --- 方便的Web浏览器控制器-Footnote-28256942
Node: 浏览器控制器对象8257064
Ref: library/webbrowser browser-controller-objects8257170
Ref: 2d118257170
Ref: library/webbrowser browser-controllers8257170
Ref: 2d128257170
Ref: library/webbrowser webbrowser controller open8257305
Ref: 2d138257305
Ref: library/webbrowser webbrowser controller open_new8257585
Ref: 2d148257585
Ref: library/webbrowser webbrowser controller open_new_tab8257811
Ref: 2d158257811
Node: cgi --- 通用网关接口支持8258024
Ref: library/cgi doc8258225
Ref: 2d168258225
Ref: library/cgi cgi-common-gateway-interface-support8258225
Ref: 2d178258225
Ref: library/cgi module-cgi8258225
Ref: 158258225
Ref: cgi --- 通用网关接口支持-Footnote-18258820
Node: 簡介<10>8258882
Ref: library/cgi introduction8258988
Ref: 2d188258988
Ref: library/cgi cgi-intro8259019
Ref: 2d198259019
Node: 使用cgi模块。8260613
Ref: library/cgi id18260749
Ref: 2d1a8260749
Ref: library/cgi using-the-cgi-module8260749
Ref: 2d1b8260749
Node: 更高层级的接口8266358
Ref: library/cgi higher-level-interface8266493
Ref: 2d1d8266493
Ref: library/cgi cgi FieldStorage getfirst8268604
Ref: 2d1e8268604
Ref: library/cgi cgi FieldStorage getlist8269110
Ref: 2d1c8269110
Ref: 更高层级的接口-Footnote-18269701
Node: 函数<9>8269917
Ref: library/cgi functions8270058
Ref: 2d1f8270058
Ref: library/cgi functions-in-cgi-module8270058
Ref: 2d208270058
Ref: library/cgi cgi parse8270227
Ref: 2818270227
Ref: library/cgi cgi parse_multipart8270576
Ref: 2828270576
Ref: library/cgi cgi parse_header8271505
Ref: 2d218271505
Ref: library/cgi cgi test8271652
Ref: 2d228271652
Ref: library/cgi cgi print_environ8271839
Ref: 2d238271839
Ref: library/cgi cgi print_form8271923
Ref: 2d248271923
Ref: library/cgi cgi print_directory8272001
Ref: 2d258272001
Ref: library/cgi cgi print_environ_usage8272086
Ref: 2d268272086
Node: 对于安全性的关注8272204
Ref: library/cgi caring-about-security8272365
Ref: 2d278272365
Ref: library/cgi cgi-security8272365
Ref: 2d288272365
Node: 在 Unix 系统上安装你的 CGI 脚本8273124
Ref: library/cgi installing-your-cgi-script-on-a-unix-system8273299
Ref: 2d298273299
Node: 测试你的 CGI 脚本8275132
Ref: library/cgi testing-your-cgi-script8275300
Ref: 2d2a8275300
Node: 调试 CGI 脚本8275889
Ref: library/cgi debugging-cgi-scripts8276043
Ref: 2d2b8276043
Node: 常见问题和解决方案8278855
Ref: library/cgi common-problems-and-solutions8278977
Ref: 2d2c8278977
Node: cgitb --- 用于 CGI 脚本的回溯管理器8280164
Ref: library/cgitb doc8280361
Ref: 2d2d8280361
Ref: library/cgitb cgitb-traceback-manager-for-cgi-scripts8280361
Ref: 2d2e8280361
Ref: library/cgitb module-cgitb8280361
Ref: 168280361
Ref: library/cgitb cgitb enable8281450
Ref: 2d2f8281450
Ref: library/cgitb cgitb text8282231
Ref: 2d308282231
Ref: library/cgitb cgitb html8282594
Ref: 2d318282594
Ref: library/cgitb cgitb handler8282957
Ref: 2d328282957
Ref: cgitb --- 用于 CGI 脚本的回溯管理器-Footnote-18283515
Node: wsgiref --- WSGI 工具和引用的实现8283579
Ref: library/wsgiref doc8283771
Ref: 2d338283771
Ref: library/wsgiref module-wsgiref8283771
Ref: 1358283771
Ref: library/wsgiref wsgiref-wsgi-utilities-and-reference-implementation8283771
Ref: 2d348283771
Ref: wsgiref --- WSGI 工具和引用的实现-Footnote-18285437
Ref: wsgiref --- WSGI 工具和引用的实现-Footnote-28285486
Node: wsgiref util -- WSGI 环境工具8285523
Ref: library/wsgiref module-wsgiref util8285685
Ref: 1398285685
Ref: library/wsgiref wsgiref-util-wsgi-environment-utilities8285685
Ref: 2d358285685
Ref: library/wsgiref wsgiref util guess_scheme8286073
Ref: 2d368286073
Ref: library/wsgiref wsgiref util request_uri8286650
Ref: 2d378286650
Ref: library/wsgiref wsgiref util application_uri8286939
Ref: 2d388286939
Ref: library/wsgiref wsgiref util shift_path_info8287182
Ref: 2d398287182
Ref: library/wsgiref wsgiref util setup_testing_defaults8288679
Ref: 2d3a8288679
Ref: library/wsgiref wsgiref util is_hop_by_hop8290278
Ref: 2d3b8290278
Ref: library/wsgiref wsgiref util FileWrapper8290450
Ref: 3a38290450
Ref: wsgiref util -- WSGI 环境工具-Footnote-18291640
Ref: wsgiref util -- WSGI 环境工具-Footnote-28291689
Ref: wsgiref util -- WSGI 环境工具-Footnote-38291738
Ref: wsgiref util -- WSGI 环境工具-Footnote-48291787
Ref: wsgiref util -- WSGI 环境工具-Footnote-58291836
Node: wsgiref headers -- WSGI 响应标头工具8291885
Ref: library/wsgiref module-wsgiref headers8292116
Ref: 1378292116
Ref: library/wsgiref wsgiref-headers-wsgi-response-header-tools8292116
Ref: 2d3c8292116
Ref: library/wsgiref wsgiref headers Headers8292354
Ref: 87e8292354
Ref: library/wsgiref wsgiref headers Headers get_all8294429
Ref: 2d3d8294429
Ref: library/wsgiref wsgiref headers Headers add_header8294854
Ref: 2d3e8294854
Ref: wsgiref headers -- WSGI 响应标头工具-Footnote-18295918
Node: wsgiref simple_server -- 一个简单的 WSGI HTTP 服务器8295967
Ref: library/wsgiref module-wsgiref simple_server8296209
Ref: 1388296209
Ref: library/wsgiref wsgiref-simple-server-a-simple-wsgi-http-server8296209
Ref: 2d3f8296209
Ref: library/wsgiref wsgiref simple_server make_server8296846
Ref: 2d408296846
Ref: library/wsgiref wsgiref simple_server demo_app8297686
Ref: 2d418297686
Ref: library/wsgiref wsgiref simple_server WSGIServer8298083
Ref: 2d428298083
Ref: library/wsgiref wsgiref simple_server WSGIServer set_app8298817
Ref: 2d448298817
Ref: library/wsgiref wsgiref simple_server WSGIServer get_app8298956
Ref: 2d458298956
Ref: library/wsgiref wsgiref simple_server WSGIRequestHandler8299283
Ref: 2d468299283
Ref: library/wsgiref wsgiref simple_server WSGIRequestHandler get_environ8299873
Ref: 2d478299873
Ref: library/wsgiref wsgiref simple_server WSGIRequestHandler get_stderr8300277
Ref: 2d488300277
Ref: library/wsgiref wsgiref simple_server WSGIRequestHandler handle8300434
Ref: 2d498300434
Ref: wsgiref simple_server -- 一个简单的 WSGI HTTP 服务器-Footnote-18300680
Ref: wsgiref simple_server -- 一个简单的 WSGI HTTP 服务器-Footnote-28300729
Node: wsgiref validate --- WSGI 一致性检查器8300778
Ref: library/wsgiref module-wsgiref validate8301020
Ref: 13a8301020
Ref: library/wsgiref wsgiref-validate-wsgi-conformance-checker8301020
Ref: 2d4a8301020
Ref: library/wsgiref wsgiref validate validator8301815
Ref: 2d4b8301815
Ref: wsgiref validate --- WSGI 一致性检查器-Footnote-18303916
Ref: wsgiref validate --- WSGI 一致性检查器-Footnote-28303965
Ref: wsgiref validate --- WSGI 一致性检查器-Footnote-38304014
Node: wsgiref handlers -- 服务器/网关基类8304063
Ref: library/wsgiref module-wsgiref handlers8304255
Ref: 1368304255
Ref: library/wsgiref wsgiref-handlers-server-gateway-base-classes8304255
Ref: 2d4c8304255
Ref: library/wsgiref wsgiref handlers CGIHandler8304589
Ref: 2d4d8304589
Ref: library/wsgiref wsgiref handlers IISCGIHandler8305243
Ref: 2d4f8305243
Ref: library/wsgiref wsgiref handlers BaseCGIHandler8306582
Ref: 2d4e8306582
Ref: library/wsgiref wsgiref handlers SimpleHandler8307365
Ref: 2d508307365
Ref: library/wsgiref wsgiref handlers BaseHandler8308208
Ref: 11078308208
Ref: library/wsgiref wsgiref handlers BaseHandler run8308530
Ref: 2d518308530
Ref: library/wsgiref wsgiref handlers BaseHandler _write8308839
Ref: 2d528308839
Ref: library/wsgiref wsgiref handlers BaseHandler _flush8309140
Ref: 2d538309140
Ref: library/wsgiref wsgiref handlers BaseHandler get_stdin8309355
Ref: 2d548309355
Ref: library/wsgiref wsgiref handlers BaseHandler get_stderr8309508
Ref: 2d558309508
Ref: library/wsgiref wsgiref handlers BaseHandler add_cgi_vars8309660
Ref: 2d568309660
Ref: library/wsgiref wsgiref handlers BaseHandler wsgi_multithread8310113
Ref: 2d578310113
Ref: library/wsgiref wsgiref handlers BaseHandler wsgi_multiprocess8310370
Ref: 2d588310370
Ref: library/wsgiref wsgiref handlers BaseHandler wsgi_run_once8310629
Ref: 2d598310629
Ref: library/wsgiref wsgiref handlers BaseHandler os_environ8310848
Ref: 2d5a8310848
Ref: library/wsgiref wsgiref handlers BaseHandler server_software8311269
Ref: 2d5b8311269
Ref: library/wsgiref wsgiref handlers BaseHandler get_scheme8311833
Ref: 2d5d8311833
Ref: library/wsgiref wsgiref handlers BaseHandler setup_environ8312126
Ref: 2d5e8312126
Ref: library/wsgiref wsgiref handlers BaseHandler log_exception8312750
Ref: 2d608312750
Ref: library/wsgiref wsgiref handlers BaseHandler traceback_limit8313216
Ref: 2d618313216
Ref: library/wsgiref wsgiref handlers BaseHandler error_output8313420
Ref: 2d628313420
Ref: library/wsgiref wsgiref handlers BaseHandler error_status8314375
Ref: 2d638314375
Ref: library/wsgiref wsgiref handlers BaseHandler error_headers8314568
Ref: 2d648314568
Ref: library/wsgiref wsgiref handlers BaseHandler error_body8314845
Ref: 2d658314845
Ref: library/wsgiref wsgiref handlers BaseHandler wsgi_file_wrapper8315135
Ref: 2d5f8315135
Ref: library/wsgiref wsgiref handlers BaseHandler sendfile8315329
Ref: 2d668315329
Ref: library/wsgiref wsgiref handlers BaseHandler origin_server8315763
Ref: 2d5c8315763
Ref: library/wsgiref wsgiref handlers BaseHandler http_version8316214
Ref: 2d678316214
Ref: library/wsgiref wsgiref handlers read_environ8316426
Ref: c088316426
Ref: wsgiref handlers -- 服务器/网关基类-Footnote-18317270
Ref: wsgiref handlers -- 服务器/网关基类-Footnote-28317319
Ref: wsgiref handlers -- 服务器/网关基类-Footnote-38317368
Ref: wsgiref handlers -- 服务器/网关基类-Footnote-48317417
Ref: wsgiref handlers -- 服务器/网关基类-Footnote-58317466
Node: 示例<32>8317515
Ref: library/wsgiref examples8317654
Ref: 2d688317654
Node: urllib --- URL 处理模块8320213
Ref: library/urllib doc8320411
Ref: 2d698320411
Ref: library/urllib module-urllib8320411
Ref: 1268320411
Ref: library/urllib urllib-url-handling-modules8320411
Ref: 2d6a8320411
Ref: urllib --- URL 处理模块-Footnote-18320941
Node: urllib request --- 用于打开 URL 的可扩展库8321004
Ref: library/urllib request doc8321210
Ref: 2d6b8321210
Ref: library/urllib request module-urllib request8321210
Ref: 1298321210
Ref: library/urllib request urllib-request-extensible-library-for-opening-urls8321210
Ref: 2d6c8321210
Ref: library/urllib request urllib request urlopen8321780
Ref: 87b8321780
Ref: library/urllib request urllib request install_opener8325594
Ref: 2d748325594
Ref: library/urllib request urllib request build_opener8326025
Ref: 2d758326025
Ref: library/urllib request urllib request pathname2url8327102
Ref: 2d7d8327102
Ref: library/urllib request urllib request url2pathname8327354
Ref: 2d7e8327354
Ref: library/urllib request urllib request getproxies8327599
Ref: 2d7f8327599
Ref: library/urllib request urllib request Request8328612
Ref: 9dc8328612
Ref: library/urllib request urllib request OpenerDirector8332610
Ref: 2d728332610
Ref: library/urllib request urllib request BaseHandler8332810
Ref: 2d768332810
Ref: library/urllib request urllib request HTTPDefaultErrorHandler8332932
Ref: 2d788332932
Ref: library/urllib request urllib request HTTPRedirectHandler8333105
Ref: 2d798333105
Ref: library/urllib request urllib request HTTPCookieProcessor8333196
Ref: 2d818333196
Ref: library/urllib request urllib request ProxyHandler8333309
Ref: 10d88333309
Ref: library/urllib request urllib request HTTPPasswordMgr8334343
Ref: 2d828334343
Ref: library/urllib request urllib request HTTPPasswordMgrWithDefaultRealm8334458
Ref: 2d838334458
Ref: library/urllib request urllib request HTTPPasswordMgrWithPriorAuth8334687
Ref: 8798334687
Ref: library/urllib request urllib request AbstractBasicAuthHandler8335028
Ref: fa28335028
Ref: library/urllib request urllib request HTTPBasicAuthHandler8336234
Ref: 2d868336234
Ref: library/urllib request urllib request ProxyBasicAuthHandler8336619
Ref: 2d878336619
Ref: library/urllib request urllib request AbstractDigestAuthHandler8336903
Ref: 106c8336903
Ref: library/urllib request urllib request HTTPDigestAuthHandler8337247
Ref: 2d888337247
Ref: library/urllib request urllib request ProxyDigestAuthHandler8337998
Ref: 2d898337998
Ref: library/urllib request urllib request HTTPHandler8338283
Ref: 2d778338283
Ref: library/urllib request urllib request HTTPSHandler8338370
Ref: c788338370
Ref: library/urllib request urllib request FileHandler8338690
Ref: 2d7b8338690
Ref: library/urllib request urllib request DataHandler8338758
Ref: 9db8338758
Ref: library/urllib request urllib request FTPHandler8338848
Ref: 2d7a8338848
Ref: library/urllib request urllib request CacheFTPHandler8338911
Ref: 2d8a8338911
Ref: library/urllib request urllib request UnknownHandler8339053
Ref: 2d738339053
Ref: library/urllib request urllib request HTTPErrorProcessor8339147
Ref: 2d7c8339147
Ref: urllib request --- 用于打开 URL 的可扩展库-Footnote-18339997
Ref: urllib request --- 用于打开 URL 的可扩展库-Footnote-28340070
Ref: urllib request --- 用于打开 URL 的可扩展库-Footnote-38340121
Ref: urllib request --- 用于打开 URL 的可扩展库-Footnote-48340170
Ref: urllib request --- 用于打开 URL 的可扩展库-Footnote-58340219
Node: Request 对象8340268
Ref: library/urllib request id18340400
Ref: 2d8b8340400
Ref: library/urllib request request-objects8340400
Ref: 2d8c8340400
Ref: library/urllib request urllib request Request full_url8340658
Ref: 9de8340658
Ref: library/urllib request urllib request Request type8340934
Ref: 2d8d8340934
Ref: library/urllib request urllib request Request host8340980
Ref: 2d8e8340980
Ref: library/urllib request urllib request Request origin_req_host8341098
Ref: 2d8f8341098
Ref: library/urllib request urllib request Request selector8341181
Ref: 2d908341181
Ref: library/urllib request urllib request Request data8341322
Ref: 9df8341322
Ref: library/urllib request urllib request Request unverifiable8341561
Ref: 2d918341561
Ref: library/urllib request urllib request Request method8341690
Ref: 9dd8341690
Ref: library/urllib request urllib request Request get_method8342260
Ref: b998342260
Ref: library/urllib request urllib request Request add_header8342663
Ref: 2d808342663
Ref: library/urllib request urllib request Request add_unredirected_header8343178
Ref: 2d928343178
Ref: library/urllib request urllib request Request has_header8343310
Ref: 2d938343310
Ref: library/urllib request urllib request Request remove_header8343472
Ref: 9e18343472
Ref: library/urllib request urllib request Request get_full_url8343670
Ref: 2d948343670
Ref: library/urllib request urllib request Request set_proxy8343817
Ref: 2d958343817
Ref: library/urllib request urllib request Request get_header8344044
Ref: 2d968344044
Ref: library/urllib request urllib request Request header_items8344204
Ref: 2d978344204
Ref: Request 对象-Footnote-18344539
Node: OpenerDirector 对象8344588
Ref: library/urllib request opener-director-objects8344747
Ref: 2d988344747
Ref: library/urllib request openerdirector-objects8344747
Ref: 2d998344747
Ref: library/urllib request urllib request OpenerDirector add_handler8344862
Ref: 2d9a8344862
Ref: library/urllib request urllib request OpenerDirector open8346341
Ref: 9e08346341
Ref: library/urllib request urllib request OpenerDirector error8347030
Ref: 2d9f8347030
Node: BaseHandler 对象8348522
Ref: library/urllib request base-handler-objects8348693
Ref: 2da08348693
Ref: library/urllib request basehandler-objects8348693
Ref: 2da18348693
Ref: library/urllib request urllib request BaseHandler add_parent8348911
Ref: 2da28348911
Ref: library/urllib request urllib request BaseHandler close8349011
Ref: 2da38349011
Ref: library/urllib request urllib request BaseHandler parent8349382
Ref: 2da48349382
Ref: library/urllib request urllib request BaseHandler default_open8349528
Ref: 2da58349528
Ref: library/urllib request protocol-open8350154
Ref: 2d9b8350154
Ref: library/urllib request urllib request BaseHandler unknown_open8350484
Ref: 2da68350484
Ref: library/urllib request urllib request BaseHandler http_error_default8350876
Ref: 2da78350876
Ref: library/urllib request http-error-nnn8351597
Ref: 2d9c8351597
Ref: library/urllib request protocol-request8352050
Ref: 2d9d8352050
Ref: library/urllib request protocol-response8352433
Ref: 2d9e8352433
Node: HTTPRedirectHandler 对象8352938
Ref: library/urllib request http-redirect-handler8353114
Ref: 2da88353114
Ref: library/urllib request httpredirecthandler-objects8353114
Ref: 2da98353114
Ref: library/urllib request urllib request HTTPRedirectHandler redirect_request8353551
Ref: 2daa8353551
Ref: library/urllib request urllib request HTTPRedirectHandler http_error_3018354584
Ref: 2dab8354584
Ref: library/urllib request urllib request HTTPRedirectHandler http_error_3028354851
Ref: 2dac8354851
Ref: library/urllib request urllib request HTTPRedirectHandler http_error_3038355045
Ref: 2dad8355045
Ref: library/urllib request urllib request HTTPRedirectHandler http_error_3078355243
Ref: 2dae8355243
Ref: HTTPRedirectHandler 对象-Footnote-18355485
Ref: HTTPRedirectHandler 对象-Footnote-28355534
Node: HTTPCookieProcessor 对象8355583
Ref: library/urllib request http-cookie-processor8355760
Ref: 2daf8355760
Ref: library/urllib request httpcookieprocessor-objects8355760
Ref: 2db08355760
Ref: library/urllib request urllib request HTTPCookieProcessor cookiejar8355896
Ref: 2db18355896
Node: ProxyHandler 对象8356007
Ref: library/urllib request proxy-handler8356180
Ref: 2db38356180
Ref: library/urllib request proxyhandler-objects8356180
Ref: 2db48356180
Node: HTTPPasswordMgr 对象8356661
Ref: library/urllib request http-password-mgr8356843
Ref: 2d848356843
Ref: library/urllib request httppasswordmgr-objects8356843
Ref: 2db58356843
Ref: library/urllib request urllib request HTTPPasswordMgr add_password8357020
Ref: 2db68357020
Ref: library/urllib request urllib request HTTPPasswordMgr find_user_password8357325
Ref: 2db78357325
Node: HTTPPasswordMgrWithPriorAuth 对象8357705
Ref: library/urllib request http-password-mgr-with-prior-auth8357899
Ref: 2d858357899
Ref: library/urllib request httppasswordmgrwithpriorauth-objects8357899
Ref: 2db88357899
Ref: library/urllib request urllib request HTTPPasswordMgrWithPriorAuth add_password8358123
Ref: 2db98358123
Ref: library/urllib request urllib request HTTPPasswordMgrWithPriorAuth find_user_password8358541
Ref: 2dba8358541
Ref: library/urllib request urllib request HTTPPasswordMgrWithPriorAuth update_authenticated8358709
Ref: 2dbb8358709
Ref: library/urllib request urllib request HTTPPasswordMgrWithPriorAuth is_authenticated8358900
Ref: 2dbc8358900
Node: AbstractBasicAuthHandler 对象8359062
Ref: library/urllib request abstract-basic-auth-handler8359261
Ref: 2dbd8359261
Ref: library/urllib request abstractbasicauthhandler-objects8359261
Ref: 2dbe8359261
Ref: library/urllib request urllib request AbstractBasicAuthHandler http_error_auth_reqed8359342
Ref: 2dbf8359342
Node: HTTPBasicAuthHandler 对象8360152
Ref: library/urllib request http-basic-auth-handler8360344
Ref: 2dc08360344
Ref: library/urllib request httpbasicauthhandler-objects8360344
Ref: 2dc18360344
Ref: library/urllib request urllib request HTTPBasicAuthHandler http_error_4018360419
Ref: 2dc28360419
Node: ProxyBasicAuthHandler 对象8360578
Ref: library/urllib request proxy-basic-auth-handler8360771
Ref: 2dc38360771
Ref: library/urllib request proxybasicauthhandler-objects8360771
Ref: 2dc48360771
Ref: library/urllib request urllib request ProxyBasicAuthHandler http_error_4078360848
Ref: 2dc58360848
Node: AbstractDigestAuthHandler 对象8361008
Ref: library/urllib request abstract-digest-auth-handler8361202
Ref: 2dc68361202
Ref: library/urllib request abstractdigestauthhandler-objects8361202
Ref: 2dc78361202
Ref: library/urllib request urllib request AbstractDigestAuthHandler http_error_auth_reqed8361287
Ref: 2dc88361287
Node: HTTPDigestAuthHandler 对象8361627
Ref: library/urllib request http-digest-auth-handler8361822
Ref: 2dc98361822
Ref: library/urllib request httpdigestauthhandler-objects8361822
Ref: 2dca8361822
Ref: library/urllib request urllib request HTTPDigestAuthHandler http_error_4018361899
Ref: 2dcb8361899
Node: ProxyDigestAuthHandler 对象8362059
Ref: library/urllib request proxy-digest-auth-handler8362240
Ref: 2dcc8362240
Ref: library/urllib request proxydigestauthhandler-objects8362240
Ref: 2dcd8362240
Ref: library/urllib request urllib request ProxyDigestAuthHandler http_error_4078362319
Ref: 2dce8362319
Node: HTTPHandler 对象8362480
Ref: library/urllib request http-handler-objects8362652
Ref: 2dcf8362652
Ref: library/urllib request httphandler-objects8362652
Ref: 2dd08362652
Ref: library/urllib request urllib request HTTPHandler http_open8362709
Ref: 2dd18362709
Node: HTTPSHandler 对象8362862
Ref: library/urllib request https-handler-objects8363023
Ref: 2dd28363023
Ref: library/urllib request httpshandler-objects8363023
Ref: 2dd38363023
Ref: library/urllib request urllib request HTTPSHandler https_open8363082
Ref: 2dd48363082
Node: FileHandler 对象8363238
Ref: library/urllib request file-handler-objects8363399
Ref: 2dd58363399
Ref: library/urllib request filehandler-objects8363399
Ref: 2dd68363399
Ref: library/urllib request urllib request FileHandler file_open8363456
Ref: 2dd78363456
Node: DataHandler 对象8363728
Ref: library/urllib request data-handler-objects8363887
Ref: 2dd88363887
Ref: library/urllib request datahandler-objects8363887
Ref: 2dd98363887
Ref: library/urllib request urllib request DataHandler data_open8363944
Ref: 2dda8363944
Ref: DataHandler 对象-Footnote-18364461
Node: FTPHandler 对象8364510
Ref: library/urllib request ftp-handler-objects8364673
Ref: 2ddb8364673
Ref: library/urllib request ftphandler-objects8364673
Ref: 2ddc8364673
Ref: library/urllib request urllib request FTPHandler ftp_open8364728
Ref: 2ddd8364728
Node: CacheFTPHandler 对象8364864
Ref: library/urllib request cacheftp-handler-objects8365030
Ref: 2dde8365030
Ref: library/urllib request cacheftphandler-objects8365030
Ref: 2ddf8365030
Ref: library/urllib request urllib request CacheFTPHandler setTimeout8365193
Ref: 2de08365193
Ref: library/urllib request urllib request CacheFTPHandler setMaxConns8365282
Ref: 2de18365282
Node: UnknownHandler 对象8365384
Ref: library/urllib request unknown-handler-objects8365558
Ref: 2de28365558
Ref: library/urllib request unknownhandler-objects8365558
Ref: 2de38365558
Ref: library/urllib request urllib request UnknownHandler unknown_open8365621
Ref: 2de48365621
Node: HTTPErrorProcessor 对象8365717
Ref: library/urllib request http-error-processor-objects8365879
Ref: 2de58365879
Ref: library/urllib request httperrorprocessor-objects8365879
Ref: 2de68365879
Ref: library/urllib request urllib request HTTPErrorProcessor http_response8365950
Ref: 2de78365950
Ref: library/urllib request urllib request HTTPErrorProcessor https_response8366397
Ref: 2de88366397
Node: 示例<33>8366562
Ref: library/urllib request examples8366718
Ref: 2de98366718
Ref: library/urllib request urllib-request-examples8366718
Ref: 2dea8366718
Ref: library/urllib request urllib-examples8372082
Ref: 2dec8372082
Node: 沿袭的接口8373489
Ref: library/urllib request legacy-interface8373644
Ref: 2ded8373644
Ref: library/urllib request urllib request urlretrieve8373833
Ref: 2dee8373833
Ref: library/urllib request urllib request urlcleanup8376246
Ref: 10e38376246
Ref: library/urllib request urllib request URLopener8376374
Ref: 2d6f8376374
Ref: library/urllib request urllib request URLopener open8377792
Ref: 2df08377792
Ref: library/urllib request urllib request URLopener open_unknown8378270
Ref: 2df18378270
Ref: library/urllib request urllib request URLopener retrieve8378390
Ref: 11038378390
Ref: library/urllib request urllib request URLopener version8379813
Ref: 2def8379813
Ref: library/urllib request urllib request FancyURLopener8380112
Ref: 2d708380112
Ref: library/urllib request urllib request FancyURLopener prompt_user_passwd8381623
Ref: 2df28381623
Ref: 沿袭的接口-Footnote-18382056
Node: urllib request 的限制8382105
Ref: library/urllib request urllib-request-restrictions8382241
Ref: 2df38382241
Node: urllib response --- urllib 使用的 Response 类8384538
Ref: library/urllib request module-urllib response8384746
Ref: 12a8384746
Ref: library/urllib request urllib-response-response-classes-used-by-urllib8384746
Ref: 2df48384746
Ref: library/urllib request urllib response addinfourl8385168
Ref: 2d6d8385168
Ref: library/urllib request urllib response addinfourl url8385208
Ref: 2df58385208
Ref: library/urllib request urllib response addinfourl headers8385312
Ref: 2df68385312
Ref: library/urllib request urllib response addinfourl status8385418
Ref: 2df78385418
Ref: library/urllib request urllib response addinfourl geturl8385517
Ref: 2df88385517
Ref: library/urllib request urllib response addinfourl info8385628
Ref: 2df98385628
Ref: library/urllib request urllib response addinfourl code8385741
Ref: 2dfa8385741
Ref: library/urllib request urllib response addinfourl getstatus8385844
Ref: 2dfb8385844
Node: urllib parse 用于解析 URL8385961
Ref: library/urllib parse doc8386168
Ref: 2dfc8386168
Ref: library/urllib parse module-urllib parse8386168
Ref: 1288386168
Ref: library/urllib parse urllib-parse-parse-urls-into-components8386168
Ref: 2dfd8386168
Ref: urllib parse 用于解析 URL-Footnote-18387304
Node: URL 解析8387375
Ref: library/urllib parse url-parsing8387483
Ref: 2dfe8387483
Ref: library/urllib parse urllib parse urlparse8387636
Ref: 6f18387636
Ref: library/urllib parse urllib parse parse_qs8395178
Ref: 27f8395178
Ref: library/urllib parse urllib parse parse_qsl8397175
Ref: 2808397175
Ref: library/urllib parse urllib parse urlunparse8399065
Ref: 2e008399065
Ref: library/urllib parse urllib parse urlsplit8399459
Ref: 6f08399459
Ref: library/urllib parse urllib parse urlunsplit8403625
Ref: 2e018403625
Ref: library/urllib parse urllib parse urljoin8404048
Ref: 87c8404048
Ref: library/urllib parse urllib parse urldefrag8405342
Ref: cac8405342
Ref: library/urllib parse urllib parse unwrap8406641
Ref: 2e028406641
Ref: URL 解析-Footnote-18406996
Ref: URL 解析-Footnote-28407045
Ref: URL 解析-Footnote-38407094
Ref: URL 解析-Footnote-48407143
Ref: URL 解析-Footnote-58407205
Node: 解析ASCII编码字节8407254
Ref: library/urllib parse id18407392
Ref: 2e038407392
Ref: library/urllib parse parsing-ascii-encoded-bytes8407392
Ref: cae8407392
Node: 结构化解析结果8409297
Ref: library/urllib parse structured-parse-results8409435
Ref: 2e048409435
Ref: library/urllib parse urlparse-result-object8409435
Ref: 2dff8409435
Ref: library/urllib parse urllib parse urllib parse SplitResult geturl8409772
Ref: 2e058409772
Ref: library/urllib parse urllib parse DefragResult8410838
Ref: 2e068410838
Ref: library/urllib parse urllib parse ParseResult8411101
Ref: 2e088411101
Ref: library/urllib parse urllib parse SplitResult8411373
Ref: 2e0a8411373
Ref: library/urllib parse urllib parse DefragResultBytes8411755
Ref: 2e078411755
Ref: library/urllib parse urllib parse ParseResultBytes8412013
Ref: 2e098412013
Ref: library/urllib parse urllib parse SplitResultBytes8412310
Ref: 2e0b8412310
Node: URL 转码8412599
Ref: library/urllib parse url-quoting8412705
Ref: 2e0c8412705
Ref: library/urllib parse urllib parse quote8413084
Ref: 5118413084
Ref: library/urllib parse urllib parse quote_plus8414362
Ref: cad8414362
Ref: library/urllib parse urllib parse quote_from_bytes8414866
Ref: 2e0d8414866
Ref: library/urllib parse urllib parse unquote8415158
Ref: 10db8415158
Ref: library/urllib parse urllib parse unquote_plus8415872
Ref: 2e0e8415872
Ref: library/urllib parse urllib parse unquote_to_bytes8416213
Ref: 2e0f8416213
Ref: library/urllib parse urllib parse urlencode8416650
Ref: 87a8416650
Ref: URL 转码-Footnote-18420012
Ref: URL 转码-Footnote-28420061
Ref: URL 转码-Footnote-38420110
Ref: URL 转码-Footnote-48420147
Ref: URL 转码-Footnote-58420196
Ref: URL 转码-Footnote-68420245
Ref: URL 转码-Footnote-78420294
Ref: URL 转码-Footnote-88420343
Ref: URL 转码-Footnote-98420392
Node: urllib error --- urllib request 引发的异常类8420441
Ref: library/urllib error doc8420651
Ref: 2e108420651
Ref: library/urllib error module-urllib error8420651
Ref: 1278420651
Ref: library/urllib error urllib-error-exception-classes-raised-by-urllib-request8420651
Ref: 2e118420651
Ref: library/urllib error whatwg8420651
Ref: 2e128420651
Ref: library/urllib error urllib error URLError8421084
Ref: 2d718421084
Ref: library/urllib error urllib error URLError reason8421255
Ref: 2e138421255
Ref: library/urllib error urllib error HTTPError8421499
Ref: 9e28421499
Ref: library/urllib error urllib error HTTPError code8421830
Ref: 2e148421830
Ref: library/urllib error urllib error HTTPError reason8422066
Ref: 2e168422066
Ref: library/urllib error urllib error HTTPError headers8422160
Ref: 9e38422160
Ref: library/urllib error urllib error ContentTooShortError8422298
Ref: 2e178422298
Ref: urllib error --- urllib request 引发的异常类-Footnote-18422644
Ref: urllib error --- urllib request 引发的异常类-Footnote-28422715
Node: urllib robotparser --- robots txt 语法分析程序8422764
Ref: library/urllib robotparser doc8422965
Ref: 2e188422965
Ref: library/urllib robotparser module-urllib robotparser8422965
Ref: 12b8422965
Ref: library/urllib robotparser urllib-robotparser-parser-for-robots-txt8422965
Ref: 2e198422965
Ref: library/urllib robotparser urllib robotparser RobotFileParser8423501
Ref: 6a48423501
Ref: library/urllib robotparser urllib robotparser RobotFileParser set_url8423689
Ref: 2e1a8423689
Ref: library/urllib robotparser urllib robotparser RobotFileParser read8423785
Ref: 2e1b8423785
Ref: library/urllib robotparser urllib robotparser RobotFileParser parse8423884
Ref: 11d68423884
Ref: library/urllib robotparser urllib robotparser RobotFileParser can_fetch8423952
Ref: 2e1c8423952
Ref: library/urllib robotparser urllib robotparser RobotFileParser mtime8424141
Ref: 2e1d8424141
Ref: library/urllib robotparser urllib robotparser RobotFileParser modified8424360
Ref: 2e1e8424360
Ref: library/urllib robotparser urllib robotparser RobotFileParser crawl_delay8424486
Ref: 2e1f8424486
Ref: library/urllib robotparser urllib robotparser RobotFileParser request_rate8424823
Ref: 2e208424823
Ref: library/urllib robotparser urllib robotparser RobotFileParser site_maps8425232
Ref: 116c8425232
Ref: urllib robotparser --- robots txt 语法分析程序-Footnote-18426109
Node: http --- HTTP 模块8426187
Ref: library/http doc8426374
Ref: 2e218426374
Ref: library/http http-http-modules8426374
Ref: 2e228426374
Ref: library/http module-http8426374
Ref: 928426374
Ref: library/http http HTTPStatus8427178
Ref: 1ac8427178
Ref: http --- HTTP 模块-Footnote-18427899
Node: HTTP 状态码8427971
Ref: library/http http-status-codes8428042
Ref: 2e238428042
Ref: library/http id18428042
Ref: 2e248428042
Ref: HTTP 状态码-Footnote-18441697
Ref: HTTP 状态码-Footnote-28441781
Ref: HTTP 状态码-Footnote-38441830
Ref: HTTP 状态码-Footnote-48441879
Ref: HTTP 状态码-Footnote-58441928
Ref: HTTP 状态码-Footnote-68441977
Ref: HTTP 状态码-Footnote-78442026
Ref: HTTP 状态码-Footnote-88442075
Ref: HTTP 状态码-Footnote-98442124
Ref: HTTP 状态码-Footnote-108442173
Ref: HTTP 状态码-Footnote-118442223
Ref: HTTP 状态码-Footnote-128442273
Node: http client --- HTTP 协议客户端8442323
Ref: library/http client doc8442488
Ref: 2e258442488
Ref: library/http client http-client-http-protocol-client8442488
Ref: 2e268442488
Ref: library/http client module-http client8442488
Ref: 938442488
Ref: library/http client http client HTTPConnection8443119
Ref: 4988443119
Ref: library/http client http client HTTPSConnection8444575
Ref: 4998444575
Ref: library/http client http client HTTPResponse8446241
Ref: aef8446241
Ref: library/http client http client parse_headers8446560
Ref: 11768446560
Ref: library/http client http client HTTPException8447459
Ref: 2e298447459
Ref: library/http client http client NotConnected8447589
Ref: 2e2a8447589
Ref: library/http client http client InvalidURL8447679
Ref: 2e2b8447679
Ref: library/http client http client UnknownProtocol8447842
Ref: 2e2c8447842
Ref: library/http client http client UnknownTransferEncoding8447935
Ref: 2e2d8447935
Ref: library/http client http client UnimplementedFileMode8448036
Ref: 2e2e8448036
Ref: library/http client http client IncompleteRead8448135
Ref: 2e2f8448135
Ref: library/http client http client ImproperConnectionState8448227
Ref: 2e308448227
Ref: library/http client http client CannotSendRequest8448328
Ref: 2e318448328
Ref: library/http client http client CannotSendHeader8448433
Ref: 2e328448433
Ref: library/http client http client ResponseNotReady8448537
Ref: 2e338448537
Ref: library/http client http client BadStatusLine8448641
Ref: 2e348448641
Ref: library/http client http client LineTooLong8448820
Ref: 2e358448820
Ref: library/http client http client RemoteDisconnected8448991
Ref: 7d68448991
Ref: library/http client http client HTTP_PORT8449421
Ref: 2e368449421
Ref: library/http client http client HTTPS_PORT8449511
Ref: 2e378449511
Ref: library/http client http client responses8449604
Ref: 2e388449604
Ref: http client --- HTTP 协议客户端-Footnote-18450041
Ref: http client --- HTTP 协议客户端-Footnote-28450111
Ref: http client --- HTTP 协议客户端-Footnote-38450162
Node: HTTPConnection 对象8450211
Ref: library/http client httpconnection-objects8450333
Ref: 2e398450333
Ref: library/http client id18450333
Ref: 2e3a8450333
Ref: library/http client http client HTTPConnection request8450452
Ref: 6498450452
Ref: library/http client http client HTTPConnection getresponse8453107
Ref: 7d58453107
Ref: library/http client http client HTTPConnection set_debuglevel8453574
Ref: 2e3b8453574
Ref: library/http client http client HTTPConnection set_tunnel8453941
Ref: c7d8453941
Ref: library/http client http client HTTPConnection connect8454842
Ref: 2e3c8454842
Ref: library/http client http client HTTPConnection close8455054
Ref: 2e3d8455054
Ref: library/http client http client HTTPConnection blocksize8455134
Ref: 2e3e8455134
Ref: library/http client http client HTTPConnection putrequest8455394
Ref: 2e3f8455394
Ref: library/http client http client HTTPConnection putheader8455903
Ref: 2e408455903
Ref: library/http client http client HTTPConnection endheaders8456245
Ref: 64a8456245
Ref: library/http client http client HTTPConnection send8457473
Ref: 2e418457473
Ref: HTTPConnection 对象-Footnote-18457714
Ref: HTTPConnection 对象-Footnote-28457762
Node: HTTPResponse 对象8457811
Ref: library/http client httpresponse-objects8457952
Ref: 2e428457952
Ref: library/http client id28457952
Ref: 2e438457952
Ref: library/http client http client HTTPResponse read8458301
Ref: 2e448458301
Ref: library/http client http client HTTPResponse readinto8458408
Ref: af08458408
Ref: library/http client http client HTTPResponse getheader8458571
Ref: 2e458458571
Ref: library/http client http client HTTPResponse getheaders8458975
Ref: 2e468458975
Ref: library/http client http client HTTPResponse fileno8459075
Ref: 2e478459075
Ref: library/http client http client HTTPResponse msg8459164
Ref: 2e278459164
Ref: library/http client http client HTTPResponse version8459336
Ref: 2e488459336
Ref: library/http client http client HTTPResponse url8459458
Ref: 2e498459458
Ref: library/http client http client HTTPResponse headers8459565
Ref: 2e4a8459565
Ref: library/http client http client HTTPResponse status8459697
Ref: 2e4b8459697
Ref: library/http client http client HTTPResponse reason8459770
Ref: 2d6e8459770
Ref: library/http client http client HTTPResponse debuglevel8459843
Ref: 2e4c8459843
Ref: library/http client http client HTTPResponse closed8460030
Ref: 2e4d8460030
Ref: library/http client http client HTTPResponse geturl8460116
Ref: 2e4e8460116
Ref: library/http client http client HTTPResponse info8460227
Ref: 2e4f8460227
Ref: library/http client http client HTTPResponse getstatus8460340
Ref: 2e508460340
Node: 示例<34>8460458
Ref: library/http client examples8460596
Ref: 2e518460596
Node: HTTPMessage 对象8463456
Ref: library/http client httpmessage-objects8463566
Ref: 2e528463566
Ref: library/http client id38463566
Ref: 2e538463566
Node: ftplib --- FTP 协议客户端8463753
Ref: library/ftplib doc8463929
Ref: 2e548463929
Ref: library/ftplib ftplib-ftp-protocol-client8463929
Ref: 2e558463929
Ref: library/ftplib module-ftplib8463929
Ref: 828463929
Ref: library/ftplib ftplib FTP8465501
Ref: 1a68465501
Ref: library/ftplib ftplib FTP_TLS8467214
Ref: 1a78467214
Ref: library/ftplib ftplib error_reply8469652
Ref: 2e578469652
Ref: library/ftplib ftplib error_temp8469748
Ref: 2e588469748
Ref: library/ftplib ftplib error_perm8469899
Ref: 2e598469899
Ref: library/ftplib ftplib error_proto8470053
Ref: 2e5a8470053
Ref: library/ftplib ftplib all_errors8470209
Ref: 2e5b8470209
Ref: ftplib --- FTP 协议客户端-Footnote-18470795
Ref: ftplib --- FTP 协议客户端-Footnote-28470860
Ref: ftplib --- FTP 协议客户端-Footnote-38470908
Ref: ftplib --- FTP 协议客户端-Footnote-48470957
Ref: ftplib --- FTP 协议客户端-Footnote-58471006
Ref: ftplib --- FTP 协议客户端-Footnote-68471055
Node: FTP 对象8471104
Ref: library/ftplib ftp-objects8471204
Ref: 2e5c8471204
Ref: library/ftplib id18471204
Ref: 2e5d8471204
Ref: library/ftplib ftplib FTP set_debuglevel8471533
Ref: 2e5e8471533
Ref: library/ftplib ftplib FTP connect8471922
Ref: 2e5f8471922
Ref: library/ftplib ftplib FTP getwelcome8472782
Ref: 2e608472782
Ref: library/ftplib ftplib FTP login8472976
Ref: 2e618472976
Ref: library/ftplib ftplib FTP abort8473631
Ref: 2e628473631
Ref: library/ftplib ftplib FTP sendcmd8473754
Ref: 2e638473754
Ref: library/ftplib ftplib FTP voidcmd8473989
Ref: 2e648473989
Ref: library/ftplib ftplib FTP retrbinary8474378
Ref: 2e658474378
Ref: library/ftplib ftplib FTP retrlines8475003
Ref: 2e678475003
Ref: library/ftplib ftplib FTP set_pasv8475631
Ref: 2e688475631
Ref: library/ftplib ftplib FTP storbinary8475799
Ref: d678475799
Ref: library/ftplib ftplib FTP storlines8476535
Ref: 2e698476535
Ref: library/ftplib ftplib FTP transfercmd8477033
Ref: 2e668477033
Ref: library/ftplib ftplib FTP ntransfercmd8478179
Ref: 2e6a8478179
Ref: library/ftplib ftplib FTP mlsd8478505
Ref: ae38478505
Ref: library/ftplib ftplib FTP nlst8479125
Ref: ae48479125
Ref: library/ftplib ftplib FTP dir8479540
Ref: ae58479540
Ref: library/ftplib ftplib FTP rename8480182
Ref: 2e6b8480182
Ref: library/ftplib ftplib FTP delete8480298
Ref: 2e6c8480298
Ref: library/ftplib ftplib FTP cwd8480575
Ref: 2e6d8480575
Ref: library/ftplib ftplib FTP mkd8480656
Ref: 2e6e8480656
Ref: library/ftplib ftplib FTP pwd8480740
Ref: 2e6f8480740
Ref: library/ftplib ftplib FTP rmd8480819
Ref: 2e708480819
Ref: library/ftplib ftplib FTP size8480913
Ref: 2e718480913
Ref: library/ftplib ftplib FTP quit8481191
Ref: 2e728481191
Ref: library/ftplib ftplib FTP close8481577
Ref: 2e738481577
Ref: FTP 对象-Footnote-18482008
Node: FTP_TLS 对象8482057
Ref: library/ftplib ftp-tls-objects8482157
Ref: 2e748482157
Ref: library/ftplib ftplib FTP_TLS ssl_version8482292
Ref: 2e758482292
Ref: library/ftplib ftplib FTP_TLS auth8482406
Ref: 2e768482406
Ref: library/ftplib ftplib FTP_TLS ccc8482772
Ref: ae28482772
Ref: library/ftplib ftplib FTP_TLS prot_p8482991
Ref: 2e568482991
Ref: library/ftplib ftplib FTP_TLS prot_c8483062
Ref: 2e778483062
Node: poplib --- POP3 协议客户端8483133
Ref: library/poplib doc8483306
Ref: 2e788483306
Ref: library/poplib module-poplib8483306
Ref: d08483306
Ref: library/poplib poplib-pop3-protocol-client8483306
Ref: 2e798483306
Ref: library/poplib poplib POP38484309
Ref: 1d58484309
Ref: library/poplib poplib POP3_SSL8485057
Ref: 1d68485057
Ref: library/poplib poplib error_proto8486837
Ref: bea8486837
Ref: poplib --- POP3 协议客户端-Footnote-18487468
Ref: poplib --- POP3 协议客户端-Footnote-28487533
Ref: poplib --- POP3 协议客户端-Footnote-38487582
Ref: poplib --- POP3 协议客户端-Footnote-48487631
Ref: poplib --- POP3 协议客户端-Footnote-58487680
Node: POP3 对象8487742
Ref: library/poplib id18487841
Ref: 2e7a8487841
Ref: library/poplib pop3-objects8487841
Ref: 2e7b8487841
Ref: library/poplib poplib POP3 set_debuglevel8488050
Ref: 2e7c8488050
Ref: library/poplib poplib POP3 getwelcome8488440
Ref: 2e7d8488440
Ref: library/poplib poplib POP3 capa8488536
Ref: 9798488536
Ref: library/poplib poplib POP3 user8488740
Ref: 2e7e8488740
Ref: library/poplib poplib POP3 pass_8488856
Ref: 2e7f8488856
Ref: library/poplib poplib POP3 apop8489042
Ref: 2e808489042
Ref: library/poplib poplib POP3 rpop8489156
Ref: 2e818489156
Ref: library/poplib poplib POP3 stat8489279
Ref: 2e828489279
Ref: library/poplib poplib POP3 list8489421
Ref: 2e838489421
Ref: library/poplib poplib POP3 retr8489624
Ref: 2e848489624
Ref: library/poplib poplib POP3 dele8489806
Ref: 2e858489806
Ref: library/poplib poplib POP3 rset8490072
Ref: 2e868490072
Ref: library/poplib poplib POP3 noop8490153
Ref: 2e878490153
Ref: library/poplib poplib POP3 quit8490243
Ref: be98490243
Ref: library/poplib poplib POP3 top8490342
Ref: 2e888490342
Ref: library/poplib poplib POP3 uidl8490852
Ref: 2e898490852
Ref: library/poplib poplib POP3 utf88491158
Ref: 8218491158
Ref: library/poplib poplib POP3 stls8491373
Ref: 97a8491373
Ref: POP3 对象-Footnote-18492119
Ref: POP3 对象-Footnote-28492168
Ref: POP3 对象-Footnote-38492217
Node: POP3 示例8492266
Ref: library/poplib id28492365
Ref: 2e8a8492365
Ref: library/poplib pop3-example8492365
Ref: 2e8b8492365
Node: imaplib --- IMAP4 协议客户端8492850
Ref: library/imaplib doc8493025
Ref: 2e8c8493025
Ref: library/imaplib imaplib-imap4-protocol-client8493025
Ref: 2e8d8493025
Ref: library/imaplib module-imaplib8493025
Ref: 978493025
Ref: library/imaplib imaplib IMAP48493634
Ref: 1af8493634
Ref: library/imaplib imaplib IMAP4 error8494676
Ref: 2e8e8494676
Ref: library/imaplib imaplib IMAP4 abort8494805
Ref: 2e8f8494805
Ref: library/imaplib imaplib IMAP4 readonly8495036
Ref: 2e908495036
Ref: library/imaplib imaplib IMAP4_SSL8495365
Ref: 1b08495365
Ref: library/imaplib imaplib IMAP4_stream8497217
Ref: 1b28497217
Ref: library/imaplib imaplib Internaldate2tuple8497496
Ref: 2e918497496
Ref: library/imaplib imaplib Int2AP8497752
Ref: 2e928497752
Ref: library/imaplib imaplib ParseFlags8497882
Ref: 2e938497882
Ref: library/imaplib imaplib Time2Internaldate8498004
Ref: 2e948498004
Ref: imaplib --- IMAP4 协议客户端-Footnote-18499262
Ref: imaplib --- IMAP4 协议客户端-Footnote-28499328
Ref: imaplib --- IMAP4 协议客户端-Footnote-38499377
Node: IMAP4 对象8499426
Ref: library/imaplib id18499529
Ref: 2e958499529
Ref: library/imaplib imap4-objects8499529
Ref: 2e968499529
Ref: library/imaplib imaplib IMAP4 append8500957
Ref: 2e978500957
Ref: library/imaplib imaplib IMAP4 authenticate8501074
Ref: 2e988501074
Ref: library/imaplib imaplib IMAP4 check8501851
Ref: 2e998501851
Ref: library/imaplib imaplib IMAP4 close8501934
Ref: 1b48501934
Ref: library/imaplib imaplib IMAP4 copy8502110
Ref: 2e9a8502110
Ref: library/imaplib imaplib IMAP4 create8502234
Ref: 2e9b8502234
Ref: library/imaplib imaplib IMAP4 delete8502318
Ref: 2e9c8502318
Ref: library/imaplib imaplib IMAP4 deleteacl8502405
Ref: 2e9d8502405
Ref: library/imaplib imaplib IMAP4 enable8502514
Ref: 7db8502514
Ref: library/imaplib imaplib IMAP4 expunge8502824
Ref: 2e9e8502824
Ref: library/imaplib imaplib IMAP4 fetch8503075
Ref: 2e9f8503075
Ref: library/imaplib imaplib IMAP4 getacl8503360
Ref: 2ea08503360
Ref: library/imaplib imaplib IMAP4 getannotation8503519
Ref: 2ea18503519
Ref: library/imaplib imaplib IMAP4 getquota8503715
Ref: 2ea28503715
Ref: library/imaplib imaplib IMAP4 getquotaroot8503889
Ref: 2ea38503889
Ref: library/imaplib imaplib IMAP4 list8504078
Ref: 2ea48504078
Ref: library/imaplib imaplib IMAP4 login8504363
Ref: 2ea58504363
Ref: library/imaplib imaplib IMAP4 login_cram_md58504481
Ref: 2ea68504481
Ref: library/imaplib imaplib IMAP4 logout8504711
Ref: 2ea78504711
Ref: library/imaplib imaplib IMAP4 lsub8504889
Ref: 2ea88504889
Ref: library/imaplib imaplib IMAP4 myrights8505172
Ref: 2ea98505172
Ref: library/imaplib imaplib IMAP4 namespace8505290
Ref: 2eaa8505290
Ref: library/imaplib imaplib IMAP4 noop8505387
Ref: 2eab8505387
Ref: library/imaplib imaplib IMAP4 open8505463
Ref: 1b18505463
Ref: library/imaplib imaplib IMAP4 partial8506325
Ref: 2eb08506325
Ref: library/imaplib imaplib IMAP4 proxyauth8506508
Ref: 2eb18506508
Ref: library/imaplib imaplib IMAP4 read8506662
Ref: 2eac8506662
Ref: library/imaplib imaplib IMAP4 readline8506775
Ref: 2ead8506775
Ref: library/imaplib imaplib IMAP4 recent8506880
Ref: 2eb28506880
Ref: library/imaplib imaplib IMAP4 rename8507052
Ref: 2eb38507052
Ref: library/imaplib imaplib IMAP4 response8507176
Ref: 2eb48507176
Ref: library/imaplib imaplib IMAP4 search8507355
Ref: 2eb58507355
Ref: library/imaplib imaplib IMAP4 select8507983
Ref: 2eb68507983
Ref: library/imaplib imaplib IMAP4 send8508270
Ref: 2eae8508270
Ref: library/imaplib imaplib IMAP4 setacl8508493
Ref: 2eb78508493
Ref: library/imaplib imaplib IMAP4 setannotation8508663
Ref: 2eb88508663
Ref: library/imaplib imaplib IMAP4 setquota8508861
Ref: 2eb98508861
Ref: library/imaplib imaplib IMAP4 shutdown8509046
Ref: 2eaf8509046
Ref: library/imaplib imaplib IMAP4 socket8509228
Ref: 2eba8509228
Ref: library/imaplib imaplib IMAP4 sort8509318
Ref: 2ebb8509318
Ref: library/imaplib imaplib IMAP4 starttls8510171
Ref: c7a8510171
Ref: library/imaplib imaplib IMAP4 status8510682
Ref: 2ebc8510682
Ref: library/imaplib imaplib IMAP4 store8510785
Ref: 2ebd8510785
Ref: library/imaplib imaplib IMAP4 subscribe8511901
Ref: 2ebe8511901
Ref: library/imaplib imaplib IMAP4 thread8511971
Ref: 2ebf8511971
Ref: library/imaplib imaplib IMAP4 uid8513001
Ref: 2ec08513001
Ref: library/imaplib imaplib IMAP4 unsubscribe8513295
Ref: 2ec18513295
Ref: library/imaplib imaplib IMAP4 unselect8513376
Ref: 1b38513376
Ref: library/imaplib imaplib IMAP4 xatom8513735
Ref: 2ec28513735
Ref: library/imaplib imaplib IMAP4 PROTOCOL_VERSION8513920
Ref: 2ec38513920
Ref: library/imaplib imaplib IMAP4 debug8514032
Ref: 2ec48514032
Ref: library/imaplib imaplib IMAP4 utf8_enabled8514205
Ref: 7dc8514205
Ref: IMAP4 对象-Footnote-18514470
Ref: IMAP4 对象-Footnote-28514519
Ref: IMAP4 对象-Footnote-38514568
Ref: IMAP4 对象-Footnote-48514617
Ref: IMAP4 对象-Footnote-58514666
Ref: IMAP4 对象-Footnote-68514715
Node: IMAP4 示例8514764
Ref: library/imaplib id28514867
Ref: 2ec58514867
Ref: library/imaplib imap4-example8514867
Ref: 2ec68514867
Node: nntplib --- NNTP 协议客户端8515351
Ref: library/nntplib doc8515525
Ref: 2ec78515525
Ref: library/nntplib module-nntplib8515525
Ref: c08515525
Ref: library/nntplib nntplib-nntp-protocol-client8515525
Ref: 2ec88515525
Ref: library/nntplib nntplib NNTP8517296
Ref: 1c68517296
Ref: library/nntplib nntplib NNTP_SSL8519240
Ref: 1c78519240
Ref: library/nntplib nntplib NNTPError8520661
Ref: 2eca8520661
Ref: library/nntplib nntplib NNTPError response8520854
Ref: 2ecb8520854
Ref: library/nntplib nntplib NNTPReplyError8520952
Ref: 2ecc8520952
Ref: library/nntplib nntplib NNTPTemporaryError8521052
Ref: 2ecd8521052
Ref: library/nntplib nntplib NNTPPermanentError8521164
Ref: 2ec98521164
Ref: library/nntplib nntplib NNTPProtocolError8521276
Ref: 2ece8521276
Ref: library/nntplib nntplib NNTPDataError8521404
Ref: 2ecf8521404
Ref: nntplib --- NNTP 协议客户端-Footnote-18521595
Ref: nntplib --- NNTP 协议客户端-Footnote-28521661
Ref: nntplib --- NNTP 协议客户端-Footnote-38521710
Ref: nntplib --- NNTP 协议客户端-Footnote-48521758
Ref: nntplib --- NNTP 协议客户端-Footnote-58521807
Node: NNTP 对象8521856
Ref: library/nntplib id18521960
Ref: 2ed08521960
Ref: library/nntplib nntp-objects8521960
Ref: 2ed18521960
Node: 属性8522141
Ref: library/nntplib attributes8522213
Ref: 2ed28522213
Ref: library/nntplib nntplib NNTP nntp_version8522246
Ref: 2ed38522246
Ref: library/nntplib nntplib NNTP nntp_implementation8522482
Ref: 2ed48522482
Ref: 属性-Footnote-18522708
Node: 方法<3>8522757
Ref: library/nntplib methods8522829
Ref: 2ed58522829
Ref: library/nntplib nntplib NNTP quit8523630
Ref: 2ed68523630
Ref: library/nntplib nntplib NNTP getwelcome8523795
Ref: 2ed78523795
Ref: library/nntplib nntplib NNTP getcapabilities8523990
Ref: 2ed88523990
Ref: library/nntplib nntplib NNTP login8524413
Ref: 2ed98524413
Ref: library/nntplib nntplib NNTP starttls8525005
Ref: c768525005
Ref: library/nntplib nntplib NNTP newgroups8525742
Ref: 2eda8525742
Ref: library/nntplib nntplib NNTP newnews8526388
Ref: 2edb8526388
Ref: library/nntplib nntplib NNTP list8526759
Ref: 2edc8526759
Ref: library/nntplib nntplib NNTP descriptions8528040
Ref: 2148528040
Ref: library/nntplib nntplib NNTP description8528636
Ref: 2158528636
Ref: library/nntplib nntplib NNTP group8529068
Ref: 2edd8529068
Ref: library/nntplib nntplib NNTP over8529523
Ref: 2ede8529523
Ref: library/nntplib nntplib NNTP help8531555
Ref: 2ee08531555
Ref: library/nntplib nntplib NNTP stat8531723
Ref: 2ee18531723
Ref: library/nntplib nntplib NNTP next8532386
Ref: 2ee28532386
Ref: library/nntplib nntplib NNTP last8532501
Ref: 2ee38532501
Ref: library/nntplib nntplib NNTP article8532616
Ref: 2ee48532616
Ref: library/nntplib nntplib NNTP head8533727
Ref: 2ee58533727
Ref: library/nntplib nntplib NNTP body8533960
Ref: 2ee68533960
Ref: library/nntplib nntplib NNTP post8534187
Ref: 2ee78534187
Ref: library/nntplib nntplib NNTP ihave8534796
Ref: 2ee88534796
Ref: library/nntplib nntplib NNTP date8535043
Ref: 2ee98535043
Ref: library/nntplib nntplib NNTP slave8535211
Ref: 2eea8535211
Ref: library/nntplib nntplib NNTP set_debuglevel8535310
Ref: 2eeb8535310
Ref: library/nntplib nntplib NNTP xhdr8535869
Ref: 2eec8535869
Ref: library/nntplib nntplib NNTP xover8536764
Ref: 2eed8536764
Ref: 方法<3>-Footnote-18537127
Ref: 方法<3>-Footnote-28537176
Ref: 方法<3>-Footnote-38537225
Ref: 方法<3>-Footnote-48537274
Node: 工具函数<2>8537323
Ref: library/nntplib utility-functions8537427
Ref: 2eee8537427
Ref: library/nntplib nntplib decode_header8537515
Ref: 2edf8537515
Node: smtplib ---SMTP协议客户端8538070
Ref: library/smtplib doc8538235
Ref: 2eef8538235
Ref: library/smtplib module-smtplib8538235
Ref: ed8538235
Ref: library/smtplib smtplib-smtp-protocol-client8538235
Ref: 2ef08538235
Ref: library/smtplib smtplib SMTP8538707
Ref: 1de8538707
Ref: library/smtplib smtplib SMTP_SSL8540942
Ref: 1df8540942
Ref: library/smtplib smtplib LMTP8542557
Ref: 1e08542557
Ref: library/smtplib smtplib SMTPException8543393
Ref: 99e8543393
Ref: library/smtplib smtplib SMTPServerDisconnected8543596
Ref: 2ef38543596
Ref: library/smtplib smtplib SMTPResponseException8543779
Ref: 2ef48543779
Ref: library/smtplib smtplib SMTPSenderRefused8544085
Ref: 2ef58544085
Ref: library/smtplib smtplib SMTPRecipientsRefused8544323
Ref: 2ef68544323
Ref: library/smtplib smtplib SMTPDataError8544583
Ref: 2ef78544583
Ref: library/smtplib smtplib SMTPConnectError8544666
Ref: 2ef18544666
Ref: library/smtplib smtplib SMTPHeloError8544765
Ref: 2ef88544765
Ref: library/smtplib smtplib SMTPNotSupportedError8544855
Ref: 10cb8544855
Ref: library/smtplib smtplib SMTPAuthenticationError8544980
Ref: 2ef98544980
Ref: smtplib ---SMTP协议客户端-Footnote-18545589
Ref: smtplib ---SMTP协议客户端-Footnote-28545655
Ref: smtplib ---SMTP协议客户端-Footnote-38545703
Ref: smtplib ---SMTP协议客户端-Footnote-48545752
Ref: smtplib ---SMTP协议客户端-Footnote-58545801
Ref: smtplib ---SMTP协议客户端-Footnote-68545849
Node: SMTP 对象8545898
Ref: library/smtplib id18545996
Ref: 2efa8545996
Ref: library/smtplib smtp-objects8545996
Ref: 2efb8545996
Ref: library/smtplib smtplib SMTP set_debuglevel8546092
Ref: 8328546092
Ref: library/smtplib smtplib SMTP docmd8546428
Ref: 2efc8546428
Ref: library/smtplib smtplib SMTP connect8547025
Ref: 10cd8547025
Ref: library/smtplib smtplib SMTP helo8547660
Ref: 2efd8547660
Ref: library/smtplib smtplib SMTP ehlo8548048
Ref: 2efe8548048
Ref: library/smtplib smtplib SMTP ehlo_or_helo_if_needed8548824
Ref: 2f008548824
Ref: library/smtplib smtplib SMTP has_extn8549157
Ref: 2eff8549157
Ref: library/smtplib smtplib SMTP verify8549353
Ref: 2f018549353
Ref: library/smtplib smtplib SMTP login8549764
Ref: 2f028549764
Ref: library/smtplib smtplib SMTP auth8551113
Ref: 8318551113
Ref: library/smtplib smtplib SMTP starttls8553176
Ref: b5c8553176
Ref: library/smtplib smtplib SMTP sendmail8554786
Ref: 8338554786
Ref: library/smtplib smtplib SMTP send_message8558068
Ref: 8348558068
Ref: library/smtplib smtplib SMTP quit8560060
Ref: 2ef28560060
Ref: SMTP 对象-Footnote-18560482
Ref: SMTP 对象-Footnote-28560530
Ref: SMTP 对象-Footnote-38560579
Ref: SMTP 对象-Footnote-48560628
Ref: SMTP 对象-Footnote-58560676
Ref: SMTP 对象-Footnote-68560724
Node: SMTP 示例8560773
Ref: library/smtplib id28560871
Ref: 2f038560871
Ref: library/smtplib smtp-example8560871
Ref: 2f048560871
Ref: SMTP 示例-Footnote-18562215
Node: smtpd --- SMTP 服务器8562263
Ref: library/smtpd doc8562425
Ref: 2f058562425
Ref: library/smtpd module-smtpd8562425
Ref: ec8562425
Ref: library/smtpd smtpd-smtp-server8562425
Ref: 2f068562425
Ref: smtpd --- SMTP 服务器-Footnote-18563367
Ref: smtpd --- SMTP 服务器-Footnote-28563431
Ref: smtpd --- SMTP 服务器-Footnote-38563471
Ref: smtpd --- SMTP 服务器-Footnote-48563520
Ref: smtpd --- SMTP 服务器-Footnote-58563569
Node: SMTPServer 对象8563618
Ref: library/smtpd smtpserver-objects8563727
Ref: 2f078563727
Ref: library/smtpd smtpd SMTPServer8563782
Ref: 6f98563782
Ref: library/smtpd smtpd SMTPServer process_message8565530
Ref: 6fa8565530
Ref: library/smtpd smtpd SMTPServer channel_class8567263
Ref: 2f088567263
Ref: SMTPServer 对象-Footnote-18567834
Ref: SMTPServer 对象-Footnote-28567883
Ref: SMTPServer 对象-Footnote-38567932
Ref: SMTPServer 对象-Footnote-48567981
Node: DebuggingServer 对象8568030
Ref: library/smtpd debuggingserver-objects8568163
Ref: 2f098568163
Ref: library/smtpd smtpd DebuggingServer8568228
Ref: 2f0a8568228
Node: PureProxy对象8568438
Ref: library/smtpd pureproxy-objects8568573
Ref: 2f0b8568573
Ref: library/smtpd smtpd PureProxy8568624
Ref: 2f0c8568624
Node: MailmanProxy 对象8568926
Ref: library/smtpd mailmanproxy-objects8569057
Ref: 2f0d8569057
Ref: library/smtpd smtpd MailmanProxy8569116
Ref: 2118569116
Node: SMTPChannel 对象8569733
Ref: library/smtpd smtpchannel-objects8569840
Ref: 2f0e8569840
Ref: library/smtpd smtpd SMTPChannel8569897
Ref: 6f88569897
Ref: library/smtpd smtpd SMTPChannel smtp_server8571231
Ref: 2f0f8571231
Ref: library/smtpd smtpd SMTPChannel conn8571323
Ref: 2f108571323
Ref: library/smtpd smtpd SMTPChannel addr8571403
Ref: 2f118571403
Ref: library/smtpd smtpd SMTPChannel received_lines8571518
Ref: 2f128571518
Ref: library/smtpd smtpd SMTPChannel smtp_state8571714
Ref: 2f138571714
Ref: library/smtpd smtpd SMTPChannel seen_greeting8571884
Ref: 2f148571884
Ref: library/smtpd smtpd SMTPChannel mailfrom8572002
Ref: 2f158572002
Ref: library/smtpd smtpd SMTPChannel rcpttos8572112
Ref: 2f168572112
Ref: library/smtpd smtpd SMTPChannel received_data8572222
Ref: 2f178572222
Ref: library/smtpd smtpd SMTPChannel fqdn8572397
Ref: 2f188572397
Ref: library/smtpd smtpd SMTPChannel peer8572525
Ref: 2f198572525
Ref: SMTPChannel 对象-Footnote-18574877
Ref: SMTPChannel 对象-Footnote-28574926
Node: telnetlib -- Telnet 客户端8574975
Ref: library/telnetlib doc8575144
Ref: 2f1a8575144
Ref: library/telnetlib module-telnetlib8575144
Ref: 1028575144
Ref: library/telnetlib telnetlib-telnet-client8575144
Ref: 2f1b8575144
Ref: library/telnetlib telnetlib Telnet8576043
Ref: 68e8576043
Ref: telnetlib -- Telnet 客户端-Footnote-18577446
Ref: telnetlib -- Telnet 客户端-Footnote-28577514
Ref: telnetlib -- Telnet 客户端-Footnote-38577562
Node: Telnet 对象8577610
Ref: library/telnetlib id18577711
Ref: 2f1e8577711
Ref: library/telnetlib telnet-objects8577711
Ref: 2f1f8577711
Ref: library/telnetlib telnetlib Telnet read_until8577809
Ref: 2f208577809
Ref: library/telnetlib telnetlib Telnet read_all8578130
Ref: 2f218578130
Ref: library/telnetlib telnetlib Telnet read_some8578245
Ref: 2f228578245
Ref: library/telnetlib telnetlib Telnet read_very_eager8578442
Ref: 2f238578442
Ref: library/telnetlib telnetlib Telnet read_eager8578780
Ref: 2f248578780
Ref: library/telnetlib telnetlib Telnet read_lazy8579073
Ref: 2f258579073
Ref: library/telnetlib telnetlib Telnet read_very_lazy8579396
Ref: 2f268579396
Ref: library/telnetlib telnetlib Telnet read_sb_data8579688
Ref: 2f278579688
Ref: library/telnetlib telnetlib Telnet open8579932
Ref: 2f1c8579932
Ref: library/telnetlib telnetlib Telnet msg8580456
Ref: 2f288580456
Ref: library/telnetlib telnetlib Telnet set_debuglevel8580673
Ref: 2f298580673
Ref: library/telnetlib telnetlib Telnet close8580845
Ref: 2f1d8580845
Ref: library/telnetlib telnetlib Telnet get_socket8580908
Ref: 2f2a8580908
Ref: library/telnetlib telnetlib Telnet fileno8580994
Ref: 2f2b8580994
Ref: library/telnetlib telnetlib Telnet write8581094
Ref: 2f2c8581094
Ref: library/telnetlib telnetlib Telnet interact8581557
Ref: 2f2d8581557
Ref: library/telnetlib telnetlib Telnet mt_interact8581664
Ref: 2f2e8581664
Ref: library/telnetlib telnetlib Telnet expect8581751
Ref: 2f2f8581751
Ref: library/telnetlib telnetlib Telnet set_option_negotiation_callback8582747
Ref: 2f308582747
Node: Telnet 示例8583066
Ref: library/telnetlib id28583167
Ref: 2f318583167
Ref: library/telnetlib telnet-example8583167
Ref: 2f328583167
Node: uuid --- RFC 4122 定义的UUID对象8583720
Ref: library/uuid doc8583912
Ref: 2f338583912
Ref: library/uuid module-uuid8583912
Ref: 12d8583912
Ref: library/uuid uuid-uuid-objects-according-to-rfc-41228583912
Ref: 2f348583912
Ref: library/uuid uuid SafeUUID8584981
Ref: 2f388584981
Ref: library/uuid uuid SafeUUID safe8585032
Ref: 2f398585032
Ref: library/uuid uuid SafeUUID unsafe8585125
Ref: 2f3a8585125
Ref: library/uuid uuid SafeUUID unknown8585211
Ref: 2f3b8585211
Ref: library/uuid uuid UUID8585301
Ref: 38a8585301
Ref: library/uuid uuid UUID bytes8587134
Ref: 2f3d8587134
Ref: library/uuid uuid UUID bytes_le8587255
Ref: 2f3e8587255
Ref: library/uuid uuid UUID fields8587413
Ref: 2f3f8587413
Ref: library/uuid uuid UUID hex8588877
Ref: 2f408588877
Ref: library/uuid uuid UUID int8588957
Ref: 2f3c8588957
Ref: library/uuid uuid UUID urn8589017
Ref: 2f418589017
Ref: library/uuid uuid UUID variant8589096
Ref: 2f428589096
Ref: library/uuid uuid UUID version8589331
Ref: 2f478589331
Ref: library/uuid uuid UUID is_safe8589459
Ref: 5158589459
Ref: library/uuid uuid getnode8589671
Ref: 5168589671
Ref: library/uuid uuid uuid18590498
Ref: 5178590498
Ref: library/uuid uuid uuid38590834
Ref: 2f358590834
Ref: library/uuid uuid uuid48591011
Ref: 2f368591011
Ref: library/uuid uuid uuid58591073
Ref: 2f378591073
Ref: library/uuid uuid NAMESPACE_DNS8591372
Ref: 2f488591372
Ref: library/uuid uuid NAMESPACE_URL8591491
Ref: 2f498591491
Ref: library/uuid uuid NAMESPACE_OID8591593
Ref: 2f4a8591593
Ref: library/uuid uuid NAMESPACE_X5008591699
Ref: 2f4b8591699
Ref: library/uuid uuid RESERVED_NCS8591918
Ref: 2f438591918
Ref: library/uuid uuid RFC_41228591978
Ref: 2f448591978
Ref: library/uuid uuid RESERVED_MICROSOFT8592056
Ref: 2f458592056
Ref: library/uuid uuid RESERVED_FUTURE8592128
Ref: 2f468592128
Ref: uuid --- RFC 4122 定义的UUID对象-Footnote-18592457
Ref: uuid --- RFC 4122 定义的UUID对象-Footnote-28592520
Ref: uuid --- RFC 4122 定义的UUID对象-Footnote-38592569
Ref: uuid --- RFC 4122 定义的UUID对象-Footnote-48592618
Ref: uuid --- RFC 4122 定义的UUID对象-Footnote-58592667
Ref: uuid --- RFC 4122 定义的UUID对象-Footnote-68592716
Ref: uuid --- RFC 4122 定义的UUID对象-Footnote-78592765
Node: 示例<35>8592814
Ref: library/uuid example8592898
Ref: 2f4c8592898
Ref: library/uuid uuid-example8592898
Ref: 2f4d8592898
Node: socketserver --- 用于网络服务器的框架8594143
Ref: library/socketserver doc8594336
Ref: 2f4e8594336
Ref: library/socketserver module-socketserver8594336
Ref: f08594336
Ref: library/socketserver socketserver-a-framework-for-network-servers8594336
Ref: 2f4f8594336
Ref: library/socketserver socketserver TCPServer8594672
Ref: 2f508594672
Ref: library/socketserver socketserver UDPServer8595144
Ref: 2f538595144
Ref: library/socketserver socketserver UnixStreamServer8595434
Ref: 2f548595434
Ref: library/socketserver socketserver UnixDatagramServer8595548
Ref: 2f558595548
Ref: socketserver --- 用于网络服务器的框架-Footnote-18597714
Node: 服务器创建的说明8597785
Ref: library/socketserver server-creation-notes8597918
Ref: 2f5a8597918
Ref: library/socketserver socketserver ForkingMixIn8598696
Ref: 4db8598696
Ref: library/socketserver socketserver ThreadingMixIn8598734
Ref: 4dc8598734
Ref: library/socketserver socketserver ForkingTCPServer8600117
Ref: 2f5c8600117
Ref: library/socketserver socketserver ForkingUDPServer8600159
Ref: 2f5d8600159
Ref: library/socketserver socketserver ThreadingTCPServer8600201
Ref: 2f5e8600201
Ref: library/socketserver socketserver ThreadingUDPServer8600245
Ref: 2f5b8600245
Node: Server 对象<2>8602368
Ref: library/socketserver server-objects8602534
Ref: 2f608602534
Ref: library/socketserver socketserver BaseServer8602581
Ref: b618602581
Ref: library/socketserver socketserver BaseServer fileno8602936
Ref: 2f638602936
Ref: library/socketserver socketserver BaseServer handle_request8603185
Ref: 2f588603185
Ref: library/socketserver socketserver BaseServer serve_forever8603749
Ref: b638603749
Ref: library/socketserver socketserver BaseServer service_actions8604375
Ref: b628604375
Ref: library/socketserver socketserver BaseServer shutdown8604659
Ref: 11558604659
Ref: library/socketserver socketserver BaseServer server_close8604919
Ref: 2f598604919
Ref: library/socketserver socketserver BaseServer address_family8605008
Ref: 2f698605008
Ref: library/socketserver socketserver BaseServer RequestHandlerClass8605184
Ref: 2f628605184
Ref: library/socketserver socketserver BaseServer server_address8605315
Ref: 2f618605315
Ref: library/socketserver socketserver BaseServer socket8605735
Ref: 2f6a8605735
Ref: library/socketserver socketserver BaseServer allow_reuse_address8605873
Ref: 2f6b8605873
Ref: library/socketserver socketserver BaseServer request_queue_size8606052
Ref: 2f6c8606052
Ref: library/socketserver socketserver BaseServer socket_type8606485
Ref: 2f6d8606485
Ref: library/socketserver socketserver BaseServer timeout8606666
Ref: 2f678606666
Ref: library/socketserver socketserver BaseServer finish_request8607111
Ref: 2f6e8607111
Ref: library/socketserver socketserver BaseServer get_request8607312
Ref: 2f648607312
Ref: library/socketserver socketserver BaseServer handle_error8607531
Ref: 6f48607531
Ref: library/socketserver socketserver BaseServer handle_timeout8607938
Ref: 2f688607938
Ref: library/socketserver socketserver BaseServer process_request8608300
Ref: 2f668608300
Ref: library/socketserver socketserver BaseServer server_activate8608660
Ref: 2f528608660
Ref: library/socketserver socketserver BaseServer server_bind8608894
Ref: 2f518608894
Ref: library/socketserver socketserver BaseServer verify_request8609036
Ref: 2f658609036
Node: 请求处理句柄对象8609537
Ref: library/socketserver request-handler-objects8609689
Ref: 2f6f8609689
Ref: library/socketserver socketserver BaseRequestHandler8609752
Ref: 2f568609752
Ref: library/socketserver socketserver BaseRequestHandler setup8610082
Ref: 2f708610082
Ref: library/socketserver socketserver BaseRequestHandler handle8610267
Ref: 2f578610267
Ref: library/socketserver socketserver BaseRequestHandler finish8610900
Ref: 2f718610900
Ref: library/socketserver socketserver StreamRequestHandler8611165
Ref: 67e8611165
Ref: library/socketserver socketserver DatagramRequestHandler8611211
Ref: 2f5f8611211
Node: 示例<36>8611899
Ref: library/socketserver examples8612026
Ref: 2f728612026
Node: socketserver TCPServer 示例8612217
Ref: library/socketserver socketserver-tcpserver-example8612331
Ref: 2f738612331
Node: socketserver UDPServer 示例8615398
Ref: library/socketserver socketserver-udpserver-example8615536
Ref: 2f748615536
Node: 异步混合类8617135
Ref: library/socketserver asynchronous-mixins8617235
Ref: 2f758617235
Node: http server --- HTTP 服务器8619546
Ref: library/http server doc8619735
Ref: 2f768619735
Ref: library/http server http-server-http-servers8619735
Ref: 2f778619735
Ref: library/http server module-http server8619735
Ref: 968619735
Ref: library/http server http server HTTPServer8620550
Ref: 2d438620550
Ref: library/http server http server ThreadingHTTPServer8620849
Ref: 49c8620849
Ref: library/http server http server BaseHTTPRequestHandler8621372
Ref: aec8621372
Ref: library/http server http server BaseHTTPRequestHandler client_address8622221
Ref: 2f788622221
Ref: library/http server http server BaseHTTPRequestHandler server8622334
Ref: 2f798622334
Ref: library/http server http server BaseHTTPRequestHandler close_connection8622395
Ref: 2f7a8622395
Ref: library/http server http server BaseHTTPRequestHandler requestline8622596
Ref: 2f7c8622596
Ref: library/http server http server BaseHTTPRequestHandler command8622872
Ref: 2f7d8622872
Ref: library/http server http server BaseHTTPRequestHandler path8622974
Ref: 2f7e8622974
Ref: library/http server http server BaseHTTPRequestHandler request_version8623229
Ref: 2f7f8623229
Ref: library/http server http server BaseHTTPRequestHandler headers8623335
Ref: 2e288623335
Ref: library/http server http server BaseHTTPRequestHandler rfile8623700
Ref: 2f818623700
Ref: library/http server http server BaseHTTPRequestHandler wfile8623850
Ref: 2f828623850
Ref: library/http server http server BaseHTTPRequestHandler server_version8624196
Ref: 2f838624196
Ref: library/http server http server BaseHTTPRequestHandler sys_version8624469
Ref: 2f848624469
Ref: library/http server http server BaseHTTPRequestHandler error_message_format8624692
Ref: 2f868624692
Ref: library/http server http server BaseHTTPRequestHandler error_content_type8625006
Ref: 2f878625006
Ref: library/http server http server BaseHTTPRequestHandler protocol_version8625169
Ref: 2f888625169
Ref: library/http server http server BaseHTTPRequestHandler MessageClass8625610
Ref: 2f808625610
Ref: library/http server http server BaseHTTPRequestHandler responses8625838
Ref: 2e158625838
Ref: library/http server http server BaseHTTPRequestHandler handle8626358
Ref: 2f8b8626358
Ref: library/http server http server BaseHTTPRequestHandler handle_one_request8626641
Ref: 2f7b8626641
Ref: library/http server http server BaseHTTPRequestHandler handle_expect_1008626818
Ref: 2f8c8626818
Ref: library/http server http server BaseHTTPRequestHandler send_error8627301
Ref: 9478627301
Ref: library/http server http server BaseHTTPRequestHandler send_response8628292
Ref: 2f8d8628292
Ref: library/http server http server BaseHTTPRequestHandler send_header8629017
Ref: 2f898629017
Ref: library/http server http server BaseHTTPRequestHandler send_response_only8629513
Ref: 2f8a8629513
Ref: library/http server http server BaseHTTPRequestHandler end_headers8629880
Ref: aed8629880
Ref: library/http server http server BaseHTTPRequestHandler flush_headers8630134
Ref: aee8630134
Ref: library/http server http server BaseHTTPRequestHandler log_request8630282
Ref: 2f8f8630282
Ref: library/http server http server BaseHTTPRequestHandler log_error8630534
Ref: 2f908630534
Ref: library/http server http server BaseHTTPRequestHandler log_message8630788
Ref: 2f918630788
Ref: library/http server http server BaseHTTPRequestHandler version_string8631263
Ref: 2f858631263
Ref: library/http server http server BaseHTTPRequestHandler date_time_string8631455
Ref: 2f8e8631455
Ref: library/http server http server BaseHTTPRequestHandler log_date_time_string8631844
Ref: 2f928631844
Ref: library/http server http server BaseHTTPRequestHandler address_string8631955
Ref: 2f938631955
Ref: library/http server http server SimpleHTTPRequestHandler8632193
Ref: 49b8632193
Ref: library/http server http server SimpleHTTPRequestHandler server_version8632880
Ref: 2f968632880
Ref: library/http server http server SimpleHTTPRequestHandler extensions_map8633031
Ref: 2f978633031
Ref: library/http server http server SimpleHTTPRequestHandler do_HEAD8633416
Ref: 2f958633416
Ref: library/http server http server SimpleHTTPRequestHandler do_GET8633670
Ref: 2f948633670
Ref: library/http server http-server-cli8635871
Ref: 9488635871
Ref: library/http server http server CGIHTTPRequestHandler8636728
Ref: 2f988636728
Ref: library/http server http server CGIHTTPRequestHandler cgi_directories8637845
Ref: 2f998637845
Ref: library/http server http server CGIHTTPRequestHandler do_POST8638030
Ref: 2f9a8638030
Ref: http server --- HTTP 服务器-Footnote-18638588
Ref: http server --- HTTP 服务器-Footnote-28638658
Ref: http server --- HTTP 服务器-Footnote-38638707
Node: http cookies --- HTTP状态管理8638756
Ref: library/http cookies doc8638951
Ref: 2f9b8638951
Ref: library/http cookies http-cookies-http-state-management8638951
Ref: 2f9c8638951
Ref: library/http cookies module-http cookies8638951
Ref: 958638951
Ref: library/http cookies http cookies CookieError8640185
Ref: 2f9d8640185
Ref: library/http cookies http cookies BaseCookie8640358
Ref: 2f9e8640358
Ref: library/http cookies http cookies SimpleCookie8640689
Ref: 116e8640689
Ref: http cookies --- HTTP状态管理-Footnote-18641458
Ref: http cookies --- HTTP状态管理-Footnote-28641529
Ref: http cookies --- HTTP状态管理-Footnote-38641578
Ref: http cookies --- HTTP状态管理-Footnote-48641627
Ref: http cookies --- HTTP状态管理-Footnote-58641676
Node: Cookie 对象8641725
Ref: library/http cookies cookie-objects8641830
Ref: 2fa08641830
Ref: library/http cookies id18641830
Ref: 2fa18641830
Ref: library/http cookies http cookies BaseCookie value_decode8641877
Ref: 2fa28641877
Ref: library/http cookies http cookies BaseCookie value_encode8642141
Ref: 2fa38642141
Ref: library/http cookies http cookies BaseCookie output8642570
Ref: 2fa48642570
Ref: library/http cookies http cookies BaseCookie js_output8642914
Ref: 2fa58642914
Ref: library/http cookies http cookies BaseCookie load8643186
Ref: 2f9f8643186
Node: Morsel 对象8643471
Ref: library/http cookies id28643595
Ref: 2fa68643595
Ref: library/http cookies morsel-objects8643595
Ref: 2fa78643595
Ref: library/http cookies http cookies Morsel8643642
Ref: 5878643642
Ref: library/http cookies http cookies Morsel value8644836
Ref: 5898644836
Ref: library/http cookies http cookies Morsel coded_value8644884
Ref: 58a8644884
Ref: library/http cookies http cookies Morsel key8644979
Ref: 5888644979
Ref: library/http cookies http cookies Morsel set8645023
Ref: 58b8645023
Ref: library/http cookies http cookies Morsel isReservedKey8645136
Ref: 2fa88645136
Ref: library/http cookies http cookies Morsel output8645232
Ref: 2fa98645232
Ref: library/http cookies http cookies Morsel js_output8645505
Ref: 2faa8645505
Ref: library/http cookies http cookies Morsel OutputString8645773
Ref: 2fab8645773
Ref: library/http cookies http cookies Morsel update8645965
Ref: 8b18645965
Ref: library/http cookies http cookies Morsel copy8646218
Ref: 8b08646218
Ref: library/http cookies http cookies Morsel setdefault8646374
Ref: 2fac8646374
Ref: Morsel 对象-Footnote-18646586
Ref: Morsel 对象-Footnote-28646635
Ref: Morsel 对象-Footnote-38646684
Ref: Morsel 对象-Footnote-48646733
Node: 示例<37>8646782
Ref: library/http cookies cookie-example8646884
Ref: 2fad8646884
Ref: library/http cookies example8646884
Ref: 2fae8646884
Node: http cookiejar —— HTTP 客户端的 Cookie 处理8648515
Ref: library/http cookiejar doc8648725
Ref: 2faf8648725
Ref: library/http cookiejar http-cookiejar-cookie-handling-for-http-clients8648725
Ref: 2fb08648725
Ref: library/http cookiejar module-http cookiejar8648725
Ref: 948648725
Ref: library/http cookiejar http cookiejar LoadError8650034
Ref: 2fb18650034
Ref: library/http cookiejar http cookiejar CookieJar8650369
Ref: 2db28650369
Ref: library/http cookiejar http cookiejar FileCookieJar8650794
Ref: 2fb28650794
Ref: library/http cookiejar http cookiejar CookiePolicy8651414
Ref: 2fb38651414
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy8651551
Ref: 11298651551
Ref: library/http cookiejar http cookiejar Cookie8653212
Ref: 2fb88653212
Ref: http cookiejar —— HTTP 客户端的 Cookie 处理-Footnote-18654795
Ref: http cookiejar —— HTTP 客户端的 Cookie 处理-Footnote-28654868
Ref: http cookiejar —— HTTP 客户端的 Cookie 处理-Footnote-38654917
Ref: http cookiejar —— HTTP 客户端的 Cookie 处理-Footnote-48654966
Ref: http cookiejar —— HTTP 客户端的 Cookie 处理-Footnote-58655015
Ref: http cookiejar —— HTTP 客户端的 Cookie 处理-Footnote-68655064
Ref: http cookiejar —— HTTP 客户端的 Cookie 处理-Footnote-78655113
Ref: http cookiejar —— HTTP 客户端的 Cookie 处理-Footnote-88655162
Ref: http cookiejar —— HTTP 客户端的 Cookie 处理-Footnote-98655211
Ref: http cookiejar —— HTTP 客户端的 Cookie 处理-Footnote-108655260
Node: CookieJar 和 FileCookieJar 对象8655310
Ref: library/http cookiejar cookie-jar-objects8655498
Ref: 2fb98655498
Ref: library/http cookiejar cookiejar-and-filecookiejar-objects8655498
Ref: 2fba8655498
Ref: library/http cookiejar http cookiejar CookieJar add_cookie_header8655750
Ref: 2fbb8655750
Ref: library/http cookiejar http cookiejar CookieJar extract_cookies8656631
Ref: 2fbc8656631
Ref: library/http cookiejar http cookiejar CookieJar set_policy8657777
Ref: 2fbe8657777
Ref: library/http cookiejar http cookiejar CookieJar make_cookies8657887
Ref: 2fbf8657887
Ref: library/http cookiejar http cookiejar CookieJar set_cookie_if_ok8658155
Ref: 2fc08658155
Ref: library/http cookiejar http cookiejar CookieJar set_cookie8658301
Ref: 2fc18658301
Ref: library/http cookiejar http cookiejar CookieJar clear8658437
Ref: 2fc28658437
Ref: library/http cookiejar http cookiejar CookieJar clear_session_cookies8658961
Ref: 2fc38658961
Ref: library/http cookiejar http cookiejar FileCookieJar save8659560
Ref: 2fc48659560
Ref: library/http cookiejar http cookiejar FileCookieJar load8660443
Ref: 2fb48660443
Ref: library/http cookiejar http cookiejar FileCookieJar revert8661007
Ref: 2fb58661007
Ref: library/http cookiejar http cookiejar FileCookieJar filename8661394
Ref: 2fc58661394
Ref: library/http cookiejar http cookiejar FileCookieJar delayload8661512
Ref: 2fc68661512
Node: FileCookieJar 的子类及其与 Web 浏览器的协同8661927
Ref: library/http cookiejar file-cookie-jar-classes8662143
Ref: 2fb68662143
Ref: library/http cookiejar filecookiejar-subclasses-and-co-operation-with-web-browsers8662143
Ref: 2fc78662143
Ref: library/http cookiejar http cookiejar MozillaCookieJar8662335
Ref: 2fc88662335
Ref: library/http cookiejar http cookiejar LWPCookieJar8663101
Ref: 2fc98663101
Ref: FileCookieJar 的子类及其与 Web 浏览器的协同-Footnote-18663526
Node: CookiePolicy 对象8663575
Ref: library/http cookiejar cookie-policy-objects8663783
Ref: 2fca8663783
Ref: library/http cookiejar cookiepolicy-objects8663783
Ref: 2fcb8663783
Ref: library/http cookiejar http cookiejar CookiePolicy set_ok8663914
Ref: 2fbd8663914
Ref: library/http cookiejar http cookiejar CookiePolicy return_ok8664216
Ref: 2fcc8664216
Ref: library/http cookiejar http cookiejar CookiePolicy domain_return_ok8664529
Ref: 2fcd8664529
Ref: library/http cookiejar http cookiejar CookiePolicy path_return_ok8665933
Ref: 2fce8665933
Ref: library/http cookiejar http cookiejar CookiePolicy netscape8666335
Ref: 2fcf8666335
Ref: library/http cookiejar http cookiejar CookiePolicy rfc29658666402
Ref: 2fd08666402
Ref: library/http cookiejar http cookiejar CookiePolicy hide_cookie28666471
Ref: 2fd18666471
Ref: CookiePolicy 对象-Footnote-18666959
Ref: CookiePolicy 对象-Footnote-28667008
Node: DefaultCookiePolicy 对象8667057
Ref: library/http cookiejar default-cookie-policy-objects8667226
Ref: 2fd28667226
Ref: library/http cookiejar defaultcookiepolicy-objects8667226
Ref: 2fd38667226
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy blocked_domains8669392
Ref: 2fd48669392
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy set_blocked_domains8669505
Ref: 2fd58669505
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy is_blocked8669619
Ref: 2fd68669619
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy allowed_domains8669767
Ref: 2fd78669767
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy set_allowed_domains8669906
Ref: 2fd88669906
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy is_not_allowed8670049
Ref: 2fd98670049
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy rfc2109_as_netscape8670355
Ref: 2fb78670355
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy strict_domain8670929
Ref: 2fda8670929
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy strict_rfc2965_unverifiable8671200
Ref: 2fdb8671200
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy strict_ns_unverifiable8671545
Ref: 2fdc8671545
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy strict_ns_domain8671671
Ref: 2fdd8671671
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy strict_ns_set_initial_dollar8671827
Ref: 2fde8671827
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy strict_ns_set_path8671992
Ref: 2fdf8671992
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy DomainStrictNoDots8672290
Ref: 2fe08672290
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy DomainStrictNonDomain8672540
Ref: 2fe18672540
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy DomainRFC2965Match8672914
Ref: 2fe28672914
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy DomainLiberal8673123
Ref: 2fe38673123
Ref: library/http cookiejar http cookiejar DefaultCookiePolicy DomainStrict8673246
Ref: 2fe48673246
Ref: DefaultCookiePolicy 对象-Footnote-18673394
Ref: DefaultCookiePolicy 对象-Footnote-28673443
Ref: DefaultCookiePolicy 对象-Footnote-38673492
Ref: DefaultCookiePolicy 对象-Footnote-48673541
Ref: DefaultCookiePolicy 对象-Footnote-58673590
Ref: DefaultCookiePolicy 对象-Footnote-68673639
Ref: DefaultCookiePolicy 对象-Footnote-78673688
Node: Cookie 对象<2>8673737
Ref: library/http cookiejar cookie-objects8673897
Ref: 2fe58673897
Ref: library/http cookiejar http cookiejar Cookie version8674546
Ref: 2fe68674546
Ref: library/http cookiejar http cookiejar Cookie name8674922
Ref: 2fe78674922
Ref: library/http cookiejar http cookiejar Cookie value8674991
Ref: 2fe88674991
Ref: library/http cookiejar http cookiejar Cookie port8675084
Ref: 2fe98675084
Ref: library/http cookiejar http cookiejar Cookie path8675234
Ref: 2fea8675234
Ref: library/http cookiejar http cookiejar Cookie secure8675340
Ref: 2feb8675340
Ref: library/http cookiejar http cookiejar Cookie expires8675444
Ref: 2fec8675444
Ref: library/http cookiejar http cookiejar Cookie discard8675631
Ref: 2fee8675631
Ref: library/http cookiejar http cookiejar Cookie comment8675709
Ref: 2fef8675709
Ref: library/http cookiejar http cookiejar Cookie comment_url8675849
Ref: 2ff08675849
Ref: library/http cookiejar http cookiejar Cookie rfc21098675991
Ref: 2ff18675991
Ref: library/http cookiejar http cookiejar Cookie port_specified8676407
Ref: 2ff28676407
Ref: library/http cookiejar http cookiejar Cookie domain_specified8676590
Ref: 2ff38676590
Ref: library/http cookiejar http cookiejar Cookie domain_initial_dot8676696
Ref: 2ff48676696
Ref: library/http cookiejar http cookiejar Cookie has_nonstandard_attr8676946
Ref: 2ff58676946
Ref: library/http cookiejar http cookiejar Cookie get_nonstandard_attr8677079
Ref: 2ff68677079
Ref: library/http cookiejar http cookiejar Cookie set_nonstandard_attr8677258
Ref: 2ff78677258
Ref: library/http cookiejar http cookiejar Cookie is_expired8677420
Ref: 2fed8677420
Ref: Cookie 对象<2>-Footnote-18677716
Ref: Cookie 对象<2>-Footnote-28677765
Ref: Cookie 对象<2>-Footnote-38677814
Ref: Cookie 对象<2>-Footnote-48677863
Node: 示例<38>8677912
Ref: library/http cookiejar examples8678037
Ref: 2ff88678037
Ref: 示例<38>-Footnote-18679438
Node: xmlrpc --- XMLRPC 服务端与客户端模块8679487
Ref: library/xmlrpc doc8679705
Ref: 2ff98679705
Ref: library/xmlrpc xmlrpc-xmlrpc-server-and-client-modules8679705
Ref: 2ffa8679705
Node: xmlrpc client --- XML-RPC 客户端访问8680206
Ref: library/xmlrpc client doc8680413
Ref: 2ffb8680413
Ref: library/xmlrpc client module-xmlrpc client8680413
Ref: 1488680413
Ref: library/xmlrpc client xmlrpc-client-xml-rpc-client-access8680413
Ref: 2ffc8680413
Ref: library/xmlrpc client xmlrpc client ServerProxy8681317
Ref: 37f8681317
Ref: xmlrpc client --- XML-RPC 客户端访问-Footnote-18688607
Ref: xmlrpc client --- XML-RPC 客户端访问-Footnote-28688679
Ref: xmlrpc client --- XML-RPC 客户端访问-Footnote-38688773
Ref: xmlrpc client --- XML-RPC 客户端访问-Footnote-48688832
Ref: xmlrpc client --- XML-RPC 客户端访问-Footnote-58688891
Ref: xmlrpc client --- XML-RPC 客户端访问-Footnote-68688937
Node: ServerProxy 对象8688986
Ref: library/xmlrpc client id18689109
Ref: 30018689109
Ref: library/xmlrpc client serverproxy-objects8689109
Ref: 30028689109
Ref: library/xmlrpc client xmlrpc client ServerProxy system listMethods8689686
Ref: 30038689686
Ref: library/xmlrpc client xmlrpc client ServerProxy system methodSignature8689875
Ref: 30048689875
Ref: library/xmlrpc client xmlrpc client ServerProxy system methodHelp8690820
Ref: 30058690820
Node: 日期時間物件8691845
Ref: library/xmlrpc client datetime-objects8691990
Ref: 30068691990
Ref: library/xmlrpc client id28691990
Ref: 30078691990
Ref: library/xmlrpc client xmlrpc client DateTime8692043
Ref: 2ffd8692043
Ref: library/xmlrpc client xmlrpc client DateTime decode8692344
Ref: 30088692344
Ref: library/xmlrpc client xmlrpc client DateTime encode8692447
Ref: 30098692447
Node: Binary 对象8693504
Ref: library/xmlrpc client binary-objects8693643
Ref: 300a8693643
Ref: library/xmlrpc client id38693643
Ref: 300b8693643
Ref: library/xmlrpc client xmlrpc client Binary8693690
Ref: 2ffe8693690
Ref: library/xmlrpc client xmlrpc client Binary data8693877
Ref: 300c8693877
Ref: library/xmlrpc client xmlrpc client Binary decode8694172
Ref: 300d8694172
Ref: library/xmlrpc client xmlrpc client Binary encode8694317
Ref: 300e8694317
Ref: Binary 对象-Footnote-18695509
Node: Fault 对象8695570
Ref: library/xmlrpc client fault-objects8695711
Ref: 300f8695711
Ref: library/xmlrpc client id48695711
Ref: 30108695711
Ref: library/xmlrpc client xmlrpc client Fault8695756
Ref: 2fff8695756
Ref: library/xmlrpc client xmlrpc client Fault faultCode8695901
Ref: 30118695901
Ref: library/xmlrpc client xmlrpc client Fault faultString8695976
Ref: 30128695976
Node: ProtocolError 对象8696908
Ref: library/xmlrpc client protocol-error-objects8697052
Ref: 30138697052
Ref: library/xmlrpc client protocolerror-objects8697052
Ref: 30148697052
Ref: library/xmlrpc client xmlrpc client ProtocolError8697113
Ref: 30008697113
Ref: library/xmlrpc client xmlrpc client ProtocolError url8697356
Ref: 30158697356
Ref: library/xmlrpc client xmlrpc client ProtocolError errcode8697420
Ref: 30168697420
Ref: library/xmlrpc client xmlrpc client ProtocolError errmsg8697473
Ref: 30178697473
Ref: library/xmlrpc client xmlrpc client ProtocolError headers8697543
Ref: 30188697543
Node: MultiCall 对象8698250
Ref: library/xmlrpc client multicall-objects8698394
Ref: 30198698394
Ref: library/xmlrpc client xmlrpc client MultiCall8698573
Ref: 301a8698573
Ref: MultiCall 对象-Footnote-18700219
Node: 便捷函数8700393
Ref: library/xmlrpc client convenience-functions8700541
Ref: 301b8700541
Ref: library/xmlrpc client xmlrpc client dumps8700584
Ref: 301c8700584
Ref: library/xmlrpc client xmlrpc client loads8701323
Ref: 301d8701323
Node: 客户端用法的示例8702142
Ref: library/xmlrpc client example-of-client-usage8702310
Ref: 301e8702310
Ref: library/xmlrpc client xmlrpc-client-example8702310
Ref: 301f8702310
Node: 客户端与服务器用法的示例8703618
Ref: library/xmlrpc client example-of-client-and-server-usage8703765
Ref: 30208703765
Node: xmlrpc server --- 基本 XML-RPC 服务器8703911
Ref: library/xmlrpc server doc8704106
Ref: 30228704106
Ref: library/xmlrpc server module-xmlrpc server8704106
Ref: 1498704106
Ref: library/xmlrpc server xmlrpc-server-basic-xml-rpc-servers8704106
Ref: 30238704106
Ref: library/xmlrpc server xmlrpc server SimpleXMLRPCServer8704786
Ref: 30248704786
Ref: library/xmlrpc server xmlrpc server CGIXMLRPCRequestHandler8706165
Ref: 30258706165
Ref: library/xmlrpc server xmlrpc server SimpleXMLRPCRequestHandler8706753
Ref: 30268706753
Ref: xmlrpc server --- 基本 XML-RPC 服务器-Footnote-18707222
Node: SimpleXMLRPCServer 对象8707294
Ref: library/xmlrpc server simple-xmlrpc-servers8707430
Ref: 30278707430
Ref: library/xmlrpc server simplexmlrpcserver-objects8707430
Ref: 30288707430
Ref: library/xmlrpc server xmlrpc server SimpleXMLRPCServer register_function8707656
Ref: 30298707656
Ref: library/xmlrpc server xmlrpc server SimpleXMLRPCServer register_instance8708368
Ref: 302a8708368
Ref: library/xmlrpc server xmlrpc server SimpleXMLRPCServer register_introspection_functions8709823
Ref: 302b8709823
Ref: library/xmlrpc server xmlrpc server SimpleXMLRPCServer register_multicall_functions8710022
Ref: 302c8710022
Ref: library/xmlrpc server xmlrpc server SimpleXMLRPCRequestHandler rpc_paths8710149
Ref: 302d8710149
Node: SimpleXMLRPCServer 示例8710535
Ref: library/xmlrpc server id18710622
Ref: 302e8710622
Ref: library/xmlrpc server simplexmlrpcserver-example8710622
Ref: 30218710622
Node: CGIXMLRPCRequestHandler8715082
Ref: library/xmlrpc server cgixmlrpcrequesthandler8715249
Ref: 302f8715249
Ref: library/xmlrpc server xmlrpc server CGIXMLRPCRequestHandler register_function8715427
Ref: 30308715427
Ref: library/xmlrpc server xmlrpc server CGIXMLRPCRequestHandler register_instance8716144
Ref: 30318716144
Ref: library/xmlrpc server xmlrpc server CGIXMLRPCRequestHandler register_introspection_functions8716865
Ref: 30328716865
Ref: library/xmlrpc server xmlrpc server CGIXMLRPCRequestHandler register_multicall_functions8717079
Ref: 30338717079
Ref: library/xmlrpc server xmlrpc server CGIXMLRPCRequestHandler handle_request8717217
Ref: 30348717217
Node: XMLRPC 服务器文档8717800
Ref: library/xmlrpc server documenting-xmlrpc-server8717964
Ref: 30358717964
Ref: library/xmlrpc server xmlrpc server DocXMLRPCServer8718261
Ref: 10bc8718261
Ref: library/xmlrpc server xmlrpc server DocCGIXMLRPCRequestHandler8718730
Ref: 30368718730
Ref: library/xmlrpc server xmlrpc server DocXMLRPCRequestHandler8718859
Ref: 30378718859
Node: DocXMLRPCServer 对象8719164
Ref: library/xmlrpc server doc-xmlrpc-servers8719331
Ref: 30388719331
Ref: library/xmlrpc server docxmlrpcserver-objects8719331
Ref: 30398719331
Ref: library/xmlrpc server xmlrpc server DocXMLRPCServer set_server_title8719748
Ref: 303a8719748
Ref: library/xmlrpc server xmlrpc server DocXMLRPCServer set_server_name8719924
Ref: 303b8719924
Ref: library/xmlrpc server xmlrpc server DocXMLRPCServer set_server_documentation8720113
Ref: 303c8720113
Node: DocCGIXMLRPCRequestHandler8720387
Ref: library/xmlrpc server doccgixmlrpcrequesthandler8720523
Ref: 303d8720523
Ref: library/xmlrpc server xmlrpc server DocCGIXMLRPCRequestHandler set_server_title8720953
Ref: 303e8720953
Ref: library/xmlrpc server xmlrpc server DocCGIXMLRPCRequestHandler set_server_name8721140
Ref: 303f8721140
Ref: library/xmlrpc server xmlrpc server DocCGIXMLRPCRequestHandler set_server_documentation8721340
Ref: 30408721340
Node: ipaddress --- IPv4/IPv6 操作库8721625
Ref: library/ipaddress doc8721770
Ref: 30418721770
Ref: library/ipaddress ipaddress-ipv4-ipv6-manipulation-library8721770
Ref: 30428721770
Ref: library/ipaddress module-ipaddress8721770
Ref: a28721770
Ref: ipaddress --- IPv4/IPv6 操作库-Footnote-18722607
Node: 方便的工厂函数8722675
Ref: library/ipaddress convenience-factory-functions8722784
Ref: 30448722784
Ref: library/ipaddress ipaddress ip_address8722942
Ref: 30458722942
Ref: library/ipaddress ipaddress ip_network8723526
Ref: 30478723526
Ref: library/ipaddress ipaddress ip_interface8724239
Ref: 30488724239
Node: IP 地址8725003
Ref: library/ipaddress ip-addresses8725138
Ref: 304b8725138
Node: 地址对象8725260
Ref: library/ipaddress address-objects8725351
Ref: 304c8725351
Ref: library/ipaddress ipaddress IPv4Address8725735
Ref: 30468725735
Ref: library/ipaddress ipaddress IPv4Address version8727166
Ref: 304e8727166
Ref: library/ipaddress ipaddress IPv4Address max_prefixlen8727263
Ref: 304f8727263
Ref: library/ipaddress ipaddress IPv4Address compressed8727543
Ref: 30508727543
Ref: library/ipaddress ipaddress IPv4Address exploded8727572
Ref: 30518727572
Ref: library/ipaddress ipaddress IPv4Address packed8727952
Ref: 30528727952
Ref: library/ipaddress ipaddress IPv4Address reverse_pointer8728193
Ref: 30538728193
Ref: library/ipaddress ipaddress IPv4Address is_multicast8728681
Ref: 30548728681
Ref: library/ipaddress ipaddress IPv4Address is_private8728883
Ref: 30558728883
Ref: library/ipaddress ipaddress IPv4Address is_global8729137
Ref: 9578729137
Ref: library/ipaddress ipaddress IPv4Address is_unspecified8729419
Ref: 30568729419
Ref: library/ipaddress ipaddress IPv4Address is_reserved8729568
Ref: 30578729568
Ref: library/ipaddress ipaddress IPv4Address is_loopback8729730
Ref: 30588729730
Ref: library/ipaddress ipaddress IPv4Address is_link_local8729922
Ref: 30598729922
Ref: library/ipaddress ipaddress IPv4Address __format__8730051
Ref: 305a8730051
Ref: library/ipaddress ipaddress IPv6Address8731258
Ref: 1bb8731258
Ref: library/ipaddress ipaddress IPv6Address compressed8732504
Ref: 305b8732504
Ref: library/ipaddress ipaddress IPv6Address exploded8732737
Ref: 305c8732737
Ref: library/ipaddress ipaddress IPv6Address packed8732942
Ref: 305d8732942
Ref: library/ipaddress ipaddress IPv6Address reverse_pointer8732967
Ref: 305e8732967
Ref: library/ipaddress ipaddress IPv6Address version8733001
Ref: 305f8733001
Ref: library/ipaddress ipaddress IPv6Address max_prefixlen8733027
Ref: 30608733027
Ref: library/ipaddress ipaddress IPv6Address is_multicast8733059
Ref: 30618733059
Ref: library/ipaddress ipaddress IPv6Address is_private8733090
Ref: 30628733090
Ref: library/ipaddress ipaddress IPv6Address is_global8733119
Ref: 30638733119
Ref: library/ipaddress ipaddress IPv6Address is_unspecified8733147
Ref: 30648733147
Ref: library/ipaddress ipaddress IPv6Address is_reserved8733180
Ref: 30658733180
Ref: library/ipaddress ipaddress IPv6Address is_loopback8733210
Ref: 30668733210
Ref: library/ipaddress ipaddress IPv6Address is_link_local8733240
Ref: 30678733240
Ref: library/ipaddress ipaddress IPv6Address is_site_local8733311
Ref: 30688733311
Ref: library/ipaddress ipaddress IPv6Address ipv4_mapped8733620
Ref: 30698733620
Ref: library/ipaddress ipaddress IPv6Address scope_id8733811
Ref: 1bc8733811
Ref: library/ipaddress ipaddress IPv6Address sixtofour8734062
Ref: 306a8734062
Ref: library/ipaddress ipaddress IPv6Address teredo8734327
Ref: 306b8734327
Ref: library/ipaddress ipaddress IPv6Address __format__8734619
Ref: 306c8734619
Ref: 地址对象-Footnote-18734796
Ref: 地址对象-Footnote-28734845
Ref: 地址对象-Footnote-38734894
Ref: 地址对象-Footnote-48734996
Ref: 地址对象-Footnote-58735098
Ref: 地址对象-Footnote-68735200
Ref: 地址对象-Footnote-78735302
Ref: 地址对象-Footnote-88735351
Ref: 地址对象-Footnote-98735400
Ref: 地址对象-Footnote-108735449
Ref: 地址对象-Footnote-118735499
Ref: 地址对象-Footnote-128735549
Ref: 地址对象-Footnote-138735599
Ref: 地址对象-Footnote-148735649
Node: 转换字符串和整数8735699
Ref: library/ipaddress conversion-to-strings-and-integers8735811
Ref: 306d8735811
Node: 运算符<3>8736349
Ref: library/ipaddress operators8736440
Ref: 306e8736440
Node: 比较运算符8736668
Ref: library/ipaddress comparison-operators8736756
Ref: 306f8736756
Node: 算术运算符8737321
Ref: library/ipaddress arithmetic-operators8737409
Ref: 30708737409
Node: IP网络的定义8737901
Ref: library/ipaddress ip-network-definitions8738027
Ref: 30718738027
Node: 前缀、网络掩码和主机掩码8738654
Ref: library/ipaddress prefix-net-mask-and-host-mask8738765
Ref: 30728738765
Node: 网络对象8739417
Ref: library/ipaddress network-objects8739549
Ref: 30738739549
Ref: library/ipaddress ipaddress IPv4Network8739966
Ref: 4a68739966
Ref: library/ipaddress ipaddress IPv4Network version8742162
Ref: 30758742162
Ref: library/ipaddress ipaddress IPv4Network max_prefixlen8742188
Ref: 30768742188
Ref: library/ipaddress ipaddress IPv4Network is_multicast8742294
Ref: 30778742294
Ref: library/ipaddress ipaddress IPv4Network is_private8742325
Ref: 30788742325
Ref: library/ipaddress ipaddress IPv4Network is_unspecified8742354
Ref: 30798742354
Ref: library/ipaddress ipaddress IPv4Network is_reserved8742387
Ref: 307a8742387
Ref: library/ipaddress ipaddress IPv4Network is_loopback8742417
Ref: 307b8742417
Ref: library/ipaddress ipaddress IPv4Network is_link_local8742447
Ref: 307c8742447
Ref: library/ipaddress ipaddress IPv4Network network_address8742619
Ref: 307d8742619
Ref: library/ipaddress ipaddress IPv4Network broadcast_address8742755
Ref: 307e8742755
Ref: library/ipaddress ipaddress IPv4Network hostmask8742916
Ref: 307f8742916
Ref: library/ipaddress ipaddress IPv4Network netmask8743017
Ref: 30808743017
Ref: library/ipaddress ipaddress IPv4Network with_prefixlen8743117
Ref: 30818743117
Ref: library/ipaddress ipaddress IPv4Network compressed8743150
Ref: 30828743150
Ref: library/ipaddress ipaddress IPv4Network exploded8743179
Ref: 30838743179
Ref: library/ipaddress ipaddress IPv4Network with_netmask8743429
Ref: 30848743429
Ref: library/ipaddress ipaddress IPv4Network with_hostmask8743531
Ref: 30858743531
Ref: library/ipaddress ipaddress IPv4Network num_addresses8743641
Ref: 30868743641
Ref: library/ipaddress ipaddress IPv4Network prefixlen8743712
Ref: 30878743712
Ref: library/ipaddress ipaddress IPv4Network hosts8743797
Ref: 30888743797
Ref: library/ipaddress ipaddress IPv4Network overlaps8744684
Ref: 30898744684
Ref: library/ipaddress ipaddress IPv4Network address_exclude8744874
Ref: 308a8744874
Ref: library/ipaddress ipaddress IPv4Network subnets8745463
Ref: 8868745463
Ref: library/ipaddress ipaddress IPv4Network supernet8746950
Ref: 8878746950
Ref: library/ipaddress ipaddress IPv4Network subnet_of8747714
Ref: 308b8747714
Ref: library/ipaddress ipaddress IPv4Network supernet_of8748026
Ref: 308c8748026
Ref: library/ipaddress ipaddress IPv4Network compare_networks8748342
Ref: 308d8748342
Ref: library/ipaddress ipaddress IPv6Network8748994
Ref: 4a58748994
Ref: library/ipaddress ipaddress IPv6Network version8750646
Ref: 308e8750646
Ref: library/ipaddress ipaddress IPv6Network max_prefixlen8750672
Ref: 308f8750672
Ref: library/ipaddress ipaddress IPv6Network is_multicast8750704
Ref: 30908750704
Ref: library/ipaddress ipaddress IPv6Network is_private8750735
Ref: 30918750735
Ref: library/ipaddress ipaddress IPv6Network is_unspecified8750764
Ref: 30928750764
Ref: library/ipaddress ipaddress IPv6Network is_reserved8750797
Ref: 30938750797
Ref: library/ipaddress ipaddress IPv6Network is_loopback8750827
Ref: 30948750827
Ref: library/ipaddress ipaddress IPv6Network is_link_local8750857
Ref: 30958750857
Ref: library/ipaddress ipaddress IPv6Network network_address8750889
Ref: 30968750889
Ref: library/ipaddress ipaddress IPv6Network broadcast_address8750923
Ref: 30978750923
Ref: library/ipaddress ipaddress IPv6Network hostmask8750959
Ref: 30988750959
Ref: library/ipaddress ipaddress IPv6Network netmask8750986
Ref: 30998750986
Ref: library/ipaddress ipaddress IPv6Network with_prefixlen8751012
Ref: 309a8751012
Ref: library/ipaddress ipaddress IPv6Network compressed8751045
Ref: 309b8751045
Ref: library/ipaddress ipaddress IPv6Network exploded8751074
Ref: 309c8751074
Ref: library/ipaddress ipaddress IPv6Network with_netmask8751101
Ref: 309d8751101
Ref: library/ipaddress ipaddress IPv6Network with_hostmask8751132
Ref: 309e8751132
Ref: library/ipaddress ipaddress IPv6Network num_addresses8751164
Ref: 309f8751164
Ref: library/ipaddress ipaddress IPv6Network prefixlen8751196
Ref: 30a08751196
Ref: library/ipaddress ipaddress IPv6Network hosts8751224
Ref: 30a18751224
Ref: library/ipaddress ipaddress IPv6Network overlaps8751602
Ref: 30a28751602
Ref: library/ipaddress ipaddress IPv6Network address_exclude8751643
Ref: 30a38751643
Ref: library/ipaddress ipaddress IPv6Network subnets8751693
Ref: 30a48751693
Ref: library/ipaddress ipaddress IPv6Network supernet8751761
Ref: 30a58751761
Ref: library/ipaddress ipaddress IPv6Network subnet_of8751830
Ref: 30a68751830
Ref: library/ipaddress ipaddress IPv6Network supernet_of8751872
Ref: 30a78751872
Ref: library/ipaddress ipaddress IPv6Network compare_networks8751916
Ref: 30a88751916
Ref: library/ipaddress ipaddress IPv6Network is_site_local8752038
Ref: 30a98752038
Node: 运算符<4>8752198
Ref: library/ipaddress id18752285
Ref: 30aa8752285
Node: 逻辑操作符8752557
Ref: library/ipaddress logical-operators8752639
Ref: 30ab8752639
Node: 迭代<2>8752827
Ref: library/ipaddress iteration8752945
Ref: 30ac8752945
Node: 作为地址容器的网络8753774
Ref: library/ipaddress networks-as-containers-of-addresses8753868
Ref: 30ad8753868
Node: 接口对象8754290
Ref: library/ipaddress interface-objects8754431
Ref: 30ae8754431
Ref: library/ipaddress ipaddress IPv4Interface8754569
Ref: 30498754569
Ref: library/ipaddress ipaddress IPv4Interface ip8754951
Ref: 30af8754951
Ref: library/ipaddress ipaddress IPv4Interface network8755175
Ref: 30b08755175
Ref: library/ipaddress ipaddress IPv4Interface with_prefixlen8755411
Ref: 30b18755411
Ref: library/ipaddress ipaddress IPv4Interface with_netmask8755646
Ref: 30b28755646
Ref: library/ipaddress ipaddress IPv4Interface with_hostmask8755882
Ref: 30b38755882
Ref: library/ipaddress ipaddress IPv6Interface8756116
Ref: 304a8756116
Ref: library/ipaddress ipaddress IPv6Interface ip8756497
Ref: 30b48756497
Ref: library/ipaddress ipaddress IPv6Interface network8756518
Ref: 30b58756518
Ref: library/ipaddress ipaddress IPv6Interface with_prefixlen8756544
Ref: 30b68756544
Ref: library/ipaddress ipaddress IPv6Interface with_netmask8756577
Ref: 30b78756577
Ref: library/ipaddress ipaddress IPv6Interface with_hostmask8756608
Ref: 30b88756608
Node: 运算符<5>8756753
Ref: library/ipaddress id28756814
Ref: 30b98756814
Node: 逻辑操作符<2>8757046
Ref: library/ipaddress id38757113
Ref: 30ba8757113
Node: 其他模块级别函数8757707
Ref: library/ipaddress other-module-level-functions8757846
Ref: 30bb8757846
Ref: library/ipaddress ipaddress v4_int_to_packed8757955
Ref: 30bc8757955
Ref: library/ipaddress ipaddress v6_int_to_packed8758428
Ref: 30bd8758428
Ref: library/ipaddress ipaddress summarize_address_range8758733
Ref: 8888758733
Ref: library/ipaddress ipaddress collapse_addresses8759591
Ref: 8898759591
Ref: library/ipaddress ipaddress get_mixed_type_key8760152
Ref: 30be8760152
Node: 自定义异常8760729
Ref: library/ipaddress custom-exceptions8760847
Ref: 30bf8760847
Ref: library/ipaddress ipaddress AddressValueError8760992
Ref: 304d8760992
Ref: library/ipaddress ipaddress NetmaskValueError8761092
Ref: 30748761092
Node: 多媒体服务8761195
Ref: library/mm doc8761337
Ref: 30c08761337
Ref: library/mm mmedia8761337
Ref: 30c18761337
Ref: library/mm multimedia-services8761337
Ref: 30c28761337
Node: audioop --- 处理原始音频数据8762179
Ref: library/audioop doc8762312
Ref: 30c38762312
Ref: library/audioop audioop-manipulate-raw-audio-data8762312
Ref: 30c48762312
Ref: library/audioop module-audioop8762312
Ref: c8762312
Ref: library/audioop audioop error8763162
Ref: 30c58763162
Ref: library/audioop audioop add8763274
Ref: 30c68763274
Ref: library/audioop audioop adpcm2lin8763619
Ref: 30c78763619
Ref: library/audioop audioop alaw2lin8763922
Ref: 30c98763922
Ref: library/audioop audioop avg8764156
Ref: 30ca8764156
Ref: library/audioop audioop avgpp8764251
Ref: 30cb8764251
Ref: library/audioop audioop bias8764426
Ref: 30cc8764426
Ref: library/audioop audioop byteswap8764623
Ref: 90f8764623
Ref: library/audioop audioop cross8764846
Ref: 30cd8764846
Ref: library/audioop audioop findfactor8764961
Ref: 30ce8764961
Ref: library/audioop audioop findfit8765300
Ref: 30cf8765300
Ref: library/audioop audioop findmax8765886
Ref: 30d08765886
Ref: library/audioop audioop getsample8766265
Ref: 30d18766265
Ref: library/audioop audioop lin2adpcm8766376
Ref: 30c88766376
Ref: library/audioop audioop lin2alaw8767089
Ref: 30d28767089
Ref: library/audioop audioop lin2lin8767384
Ref: 30d38767384
Ref: library/audioop audioop lin2ulaw8767997
Ref: 30d48767997
Ref: library/audioop audioop max8768292
Ref: 30d58768292
Ref: library/audioop audioop maxpp8768396
Ref: 30d68768396
Ref: library/audioop audioop minmax8768490
Ref: 30d78768490
Ref: library/audioop audioop mul8768621
Ref: 30d88768621
Ref: library/audioop audioop ratecv8768827
Ref: 30d98768827
Ref: library/audioop audioop reverse8769343
Ref: 30da8769343
Ref: library/audioop audioop rms8769457
Ref: 30db8769457
Ref: library/audioop audioop tomono8769605
Ref: 30dc8769605
Ref: library/audioop audioop tostereo8769830
Ref: 30dd8769830
Ref: library/audioop audioop ulaw2lin8770085
Ref: 30de8770085
Node: aifc --- 读写 AIFF 和 AIFC 文件8772661
Ref: library/aifc doc8772833
Ref: 30df8772833
Ref: library/aifc aifc-read-and-write-aiff-and-aifc-files8772833
Ref: 30e08772833
Ref: library/aifc module-aifc8772833
Ref: 48772833
Ref: library/aifc aifc open8774051
Ref: 55c8774051
Ref: library/aifc aifc aifc getnchannels8775031
Ref: 30e18775031
Ref: library/aifc aifc aifc getsampwidth8775142
Ref: 30e28775142
Ref: library/aifc aifc aifc getframerate8775237
Ref: 30e38775237
Ref: library/aifc aifc aifc getnframes8775329
Ref: 30e48775329
Ref: library/aifc aifc aifc getcomptype8775410
Ref: 30e58775410
Ref: library/aifc aifc aifc getcompname8775601
Ref: 30e68775601
Ref: library/aifc aifc aifc getparams8775827
Ref: 9088775827
Ref: library/aifc aifc aifc getmarkers8776032
Ref: 30e78776032
Ref: library/aifc aifc aifc getmark8776350
Ref: 30e88776350
Ref: library/aifc aifc aifc readframes8776499
Ref: 30e98776499
Ref: library/aifc aifc aifc rewind8776700
Ref: 30ea8776700
Ref: library/aifc aifc aifc setpos8776816
Ref: 30eb8776816
Ref: library/aifc aifc aifc tell8776899
Ref: 30ec8776899
Ref: library/aifc aifc aifc close8776962
Ref: 9098776962
Ref: library/aifc aifc aifc aiff8777454
Ref: 30ed8777454
Ref: library/aifc aifc aifc aifc8777642
Ref: 30ee8777642
Ref: library/aifc aifc aifc setnchannels8777832
Ref: 30ef8777832
Ref: library/aifc aifc aifc setsampwidth8777924
Ref: 30f08777924
Ref: library/aifc aifc aifc setframerate8778024
Ref: 30f18778024
Ref: library/aifc aifc aifc setnframes8778120
Ref: 30f28778120
Ref: library/aifc aifc aifc setcomptype8778305
Ref: 30f38778305
Ref: library/aifc aifc aifc setparams8778732
Ref: 30f48778732
Ref: library/aifc aifc aifc setmark8779039
Ref: 30f58779039
Ref: library/aifc aifc aifc writeframes8779401
Ref: 90b8779401
Ref: library/aifc aifc aifc writeframesraw8779624
Ref: 90a8779624
Ref: aifc --- 读写 AIFF 和 AIFC 文件-Footnote-18780082
Node: sunau --- 读写 Sun AU 文件8780145
Ref: library/sunau doc8780311
Ref: 30f68780311
Ref: library/sunau module-sunau8780311
Ref: fa8780311
Ref: library/sunau sunau-read-and-write-sun-au-files8780311
Ref: 30f78780311
Ref: library/sunau sunau open8781723
Ref: 5728781723
Ref: library/sunau sunau Error8782247
Ref: 30f88782247
Ref: library/sunau sunau AUDIO_FILE_MAGIC8782406
Ref: 30f98782406
Ref: library/sunau sunau AUDIO_FILE_ENCODING_MULAW_88782596
Ref: 30fa8782596
Ref: library/sunau sunau AUDIO_FILE_ENCODING_LINEAR_88782640
Ref: 30fb8782640
Ref: library/sunau sunau AUDIO_FILE_ENCODING_LINEAR_168782685
Ref: 30fc8782685
Ref: library/sunau sunau AUDIO_FILE_ENCODING_LINEAR_248782731
Ref: 30fd8782731
Ref: library/sunau sunau AUDIO_FILE_ENCODING_LINEAR_328782777
Ref: 30fe8782777
Ref: library/sunau sunau AUDIO_FILE_ENCODING_ALAW_88782823
Ref: 30ff8782823
Ref: library/sunau sunau AUDIO_FILE_ENCODING_FLOAT8782932
Ref: 31008782932
Ref: library/sunau sunau AUDIO_FILE_ENCODING_DOUBLE8782974
Ref: 31018782974
Ref: library/sunau sunau AUDIO_FILE_ENCODING_ADPCM_G7218783017
Ref: 31028783017
Ref: library/sunau sunau AUDIO_FILE_ENCODING_ADPCM_G7228783064
Ref: 31038783064
Ref: library/sunau sunau AUDIO_FILE_ENCODING_ADPCM_G723_38783111
Ref: 31048783111
Ref: library/sunau sunau AUDIO_FILE_ENCODING_ADPCM_G723_58783160
Ref: 31058783160
Ref: sunau --- 读写 Sun AU 文件-Footnote-18783381
Node: AU_read 对象8783445
Ref: library/sunau au-read-objects8783550
Ref: 31068783550
Ref: library/sunau id18783550
Ref: 31078783550
Ref: library/sunau sunau AU_read close8783683
Ref: 31088783683
Ref: library/sunau sunau AU_read getnchannels8783814
Ref: 31098783814
Ref: library/sunau sunau AU_read getsampwidth8783928
Ref: 310a8783928
Ref: library/sunau sunau AU_read getframerate8784005
Ref: 310b8784005
Ref: library/sunau sunau AU_read getnframes8784076
Ref: 310c8784076
Ref: library/sunau sunau AU_read getcomptype8784148
Ref: 310d8784148
Ref: library/sunau sunau AU_read getcompname8784293
Ref: 310e8784293
Ref: library/sunau sunau AU_read getparams8784530
Ref: 310f8784530
Ref: library/sunau sunau AU_read readframes8784738
Ref: 31108784738
Ref: library/sunau sunau AU_read rewind8784955
Ref: 31118784955
Ref: library/sunau sunau AU_read setpos8785103
Ref: 31128785103
Ref: library/sunau sunau AU_read tell8785259
Ref: 31138785259
Ref: library/sunau sunau AU_read getmarkers8785497
Ref: 31148785497
Ref: library/sunau sunau AU_read getmark8785565
Ref: 31158785565
Node: AU_write 对象8785633
Ref: library/sunau au-write-objects8785738
Ref: 31168785738
Ref: library/sunau id28785738
Ref: 31178785738
Ref: library/sunau sunau AU_write setnchannels8785874
Ref: 31188785874
Ref: library/sunau sunau AU_write setsampwidth8785944
Ref: 9c48785944
Ref: library/sunau sunau AU_write setframerate8786094
Ref: 31198786094
Ref: library/sunau sunau AU_write setnframes8786164
Ref: 311a8786164
Ref: library/sunau sunau AU_write setcomptype8786287
Ref: 311b8786287
Ref: library/sunau sunau AU_write setparams8786432
Ref: 311c8786432
Ref: library/sunau sunau AU_write tell8786645
Ref: 311d8786645
Ref: library/sunau sunau AU_write writeframesraw8786819
Ref: 9c58786819
Ref: library/sunau sunau AU_write writeframes8786995
Ref: 9c68786995
Ref: library/sunau sunau AU_write close8787165
Ref: 311e8787165
Node: wave --- 读写WAV格式文件8787410
Ref: library/wave doc8787573
Ref: 311f8787573
Ref: library/wave module-wave8787573
Ref: 1308787573
Ref: library/wave wave-read-and-write-wav-files8787573
Ref: 31208787573
Ref: library/wave wave open8787947
Ref: 2198787947
Ref: library/wave wave Error8789012
Ref: 31238789012
Ref: wave --- 读写WAV格式文件-Footnote-18789188
Node: Wave_read对象8789251
Ref: library/wave id18789359
Ref: 31248789359
Ref: library/wave wave-read-objects8789359
Ref: 31258789359
Ref: library/wave wave Wave_read close8789484
Ref: 31218789484
Ref: library/wave wave Wave_read getnchannels8789637
Ref: 31268789637
Ref: library/wave wave Wave_read getsampwidth8789756
Ref: 31278789756
Ref: library/wave wave Wave_read getframerate8789835
Ref: 31288789835
Ref: library/wave wave Wave_read getnframes8789908
Ref: 31298789908
Ref: library/wave wave Wave_read getcomptype8789982
Ref: 312a8789982
Ref: library/wave wave Wave_read getcompname8790086
Ref: 312b8790086
Ref: library/wave wave Wave_read getparams8790239
Ref: 312c8790239
Ref: library/wave wave Wave_read readframes8790449
Ref: 312d8790449
Ref: library/wave wave Wave_read rewind8790575
Ref: 312e8790575
Ref: library/wave wave Wave_read getmarkers8790744
Ref: 312f8790744
Ref: library/wave wave Wave_read getmark8790814
Ref: 31308790814
Ref: library/wave wave Wave_read setpos8790955
Ref: 31318790955
Ref: library/wave wave Wave_read tell8791040
Ref: 31328791040
Node: Wave_write 对象8791117
Ref: library/wave id28791225
Ref: 31338791225
Ref: library/wave wave-write-objects8791225
Ref: 9f18791225
Ref: library/wave wave Wave_write close8792035
Ref: 31228792035
Ref: library/wave wave Wave_write setnchannels8792314
Ref: 31368792314
Ref: library/wave wave Wave_write setsampwidth8792386
Ref: 31378792386
Ref: library/wave wave Wave_write setframerate8792474
Ref: 31388792474
Ref: library/wave wave Wave_write setnframes8792644
Ref: 31348792644
Ref: library/wave wave Wave_write setcomptype8792864
Ref: 31398792864
Ref: library/wave wave Wave_write setparams8792995
Ref: 31358792995
Ref: library/wave wave Wave_write tell8793218
Ref: 313a8793218
Ref: library/wave wave Wave_write writeframesraw8793398
Ref: 9f28793398
Ref: library/wave wave Wave_write writeframes8793576
Ref: 9f38793576
Node: chunk --- 读取 IFF 分块数据8794142
Ref: library/chunk doc8794312
Ref: 313b8794312
Ref: library/chunk chunk-read-iff-chunked-data8794312
Ref: 313c8794312
Ref: library/chunk module-chunk8794312
Ref: 178794312
Ref: library/chunk chunk Chunk8796031
Ref: 313d8796031
Ref: library/chunk chunk Chunk getname8797017
Ref: 313e8797017
Ref: library/chunk chunk Chunk getsize8797130
Ref: 313f8797130
Ref: library/chunk chunk Chunk close8797201
Ref: 31408797201
Ref: library/chunk chunk Chunk isatty8797543
Ref: 31418797543
Ref: library/chunk chunk Chunk seek8797610
Ref: 31428797610
Ref: library/chunk chunk Chunk tell8797980
Ref: 31438797980
Ref: library/chunk chunk Chunk read8798057
Ref: 31448798057
Ref: library/chunk chunk Chunk skip8798428
Ref: 31458798428
Ref: chunk --- 读取 IFF 分块数据-Footnote-18798742
Ref: chunk --- 读取 IFF 分块数据-Footnote-28798806
Node: colorsys --- 颜色系统间的转换8798907
Ref: library/colorsys doc8799076
Ref: 31468799076
Ref: library/colorsys colorsys-conversions-between-color-systems8799076
Ref: 31478799076
Ref: library/colorsys module-colorsys8799076
Ref: 1f8799076
Ref: library/colorsys colorsys rgb_to_yiq8799973
Ref: 31488799973
Ref: library/colorsys colorsys yiq_to_rgb8800056
Ref: 31498800056
Ref: library/colorsys colorsys rgb_to_hls8800139
Ref: 314a8800139
Ref: library/colorsys colorsys hls_to_rgb8800222
Ref: 314b8800222
Ref: library/colorsys colorsys rgb_to_hsv8800305
Ref: 314c8800305
Ref: library/colorsys colorsys hsv_to_rgb8800388
Ref: 314d8800388
Ref: colorsys --- 颜色系统间的转换-Footnote-18800672
Node: imghdr --- 推测图像类型8800739
Ref: library/imghdr doc8800913
Ref: 314e8800913
Ref: library/imghdr imghdr-determine-the-type-of-an-image8800913
Ref: 314f8800913
Ref: library/imghdr module-imghdr8800913
Ref: 988800913
Ref: library/imghdr imghdr what8801210
Ref: 7de8801210
Ref: library/imghdr imghdr tests8802895
Ref: 31508802895
Ref: imghdr --- 推测图像类型-Footnote-18803372
Node: sndhdr --- 推测声音文件的类型8803437
Ref: library/sndhdr doc8803620
Ref: 31518803620
Ref: library/sndhdr module-sndhdr8803620
Ref: ee8803620
Ref: library/sndhdr sndhdr-determine-type-of-sound-file8803620
Ref: 31528803620
Ref: library/sndhdr sndhdr what8804757
Ref: 8368804757
Ref: library/sndhdr sndhdr whathdr8805030
Ref: 8378805030
Ref: sndhdr --- 推测声音文件的类型-Footnote-18805364
Node: ossaudiodev --- 访问兼容OSS的音频设备8805429
Ref: library/ossaudiodev doc8805574
Ref: 31538805574
Ref: library/ossaudiodev module-ossaudiodev8805574
Ref: c68805574
Ref: library/ossaudiodev ossaudiodev-access-to-oss-compatible-audio-devices8805574
Ref: 31548805574
Ref: library/ossaudiodev ossaudiodev OSSAudioError8806327
Ref: 31558806327
Ref: library/ossaudiodev ossaudiodev open8806830
Ref: 31568806830
Ref: library/ossaudiodev ossaudiodev openmixer8808119
Ref: 31578808119
Ref: ossaudiodev --- 访问兼容OSS的音频设备-Footnote-18808538
Node: 音频设备对象8808586
Ref: library/ossaudiodev audio-device-objects8808716
Ref: 31588808716
Ref: library/ossaudiodev ossaudio-device-objects8808716
Ref: 31598808716
Ref: library/ossaudiodev ossaudiodev oss_audio_device close8809246
Ref: 315a8809246
Ref: library/ossaudiodev ossaudiodev oss_audio_device fileno8809453
Ref: 315b8809453
Ref: library/ossaudiodev ossaudiodev oss_audio_device read8809551
Ref: 315c8809551
Ref: library/ossaudiodev ossaudiodev oss_audio_device write8809857
Ref: 315d8809857
Ref: library/ossaudiodev ossaudiodev oss_audio_device writeall8810350
Ref: 315e8810350
Ref: library/ossaudiodev ossaudiodev oss_audio_device nonblock8811399
Ref: 315f8811399
Ref: library/ossaudiodev ossaudiodev oss_audio_device getfmts8811554
Ref: 31608811554
Ref: library/ossaudiodev ossaudiodev oss_audio_device setfmt8813716
Ref: 31618813716
Ref: library/ossaudiodev ossaudiodev oss_audio_device channels8814089
Ref: 31628814089
Ref: library/ossaudiodev ossaudiodev oss_audio_device speed8814423
Ref: 31638814423
Ref: library/ossaudiodev ossaudiodev oss_audio_device sync8815144
Ref: 31648815144
Ref: library/ossaudiodev ossaudiodev oss_audio_device reset8815433
Ref: 31658815433
Ref: library/ossaudiodev ossaudiodev oss_audio_device post8815703
Ref: 31668815703
Ref: library/ossaudiodev ossaudiodev oss_audio_device setparameters8816122
Ref: 31678816122
Ref: library/ossaudiodev ossaudiodev oss_audio_device bufsize8817191
Ref: 31688817191
Ref: library/ossaudiodev ossaudiodev oss_audio_device obufcount8817297
Ref: 31698817297
Ref: library/ossaudiodev ossaudiodev oss_audio_device obuffree8817437
Ref: 316a8817437
Ref: library/ossaudiodev ossaudiodev oss_audio_device closed8817668
Ref: 316b8817668
Ref: library/ossaudiodev ossaudiodev oss_audio_device name8817766
Ref: 316c8817766
Ref: library/ossaudiodev ossaudiodev oss_audio_device mode8817854
Ref: 316d8817854
Node: Mixer Device Objects8817966
Ref: library/ossaudiodev id18818096
Ref: 316e8818096
Ref: library/ossaudiodev mixer-device-objects8818096
Ref: 316f8818096
Ref: library/ossaudiodev ossaudiodev oss_mixer_device close8818207
Ref: 31708818207
Ref: library/ossaudiodev ossaudiodev oss_mixer_device fileno8818414
Ref: 31718818414
Ref: library/ossaudiodev ossaudiodev oss_mixer_device controls8818657
Ref: 31728818657
Ref: library/ossaudiodev ossaudiodev oss_mixer_device stereocontrols8819633
Ref: 31738819633
Ref: library/ossaudiodev ossaudiodev oss_mixer_device reccontrols8820084
Ref: 31748820084
Ref: library/ossaudiodev ossaudiodev oss_mixer_device get8820319
Ref: 31758820319
Ref: library/ossaudiodev ossaudiodev oss_mixer_device set8820820
Ref: 31768820820
Ref: library/ossaudiodev ossaudiodev oss_mixer_device get_recsrc8821389
Ref: 31778821389
Ref: library/ossaudiodev ossaudiodev oss_mixer_device set_recsrc8821556
Ref: 31788821556
Node: 國際化8821959
Ref: library/i18n doc8822089
Ref: 31798822089
Ref: library/i18n i18n8822089
Ref: 317a8822089
Ref: library/i18n internationalization8822089
Ref: 317b8822089
Node: gettext --- 多语种国际化服务8822488
Ref: library/gettext doc8822605
Ref: 317c8822605
Ref: library/gettext gettext-multilingual-internationalization-services8822605
Ref: 317d8822605
Ref: library/gettext module-gettext8822605
Ref: 878822605
Ref: gettext --- 多语种国际化服务-Footnote-18823508
Node: GNU gettext API8823574
Ref: library/gettext gnu-gettext-api8823687
Ref: 317e8823687
Ref: library/gettext gettext bindtextdomain8824185
Ref: 317f8824185
Ref: library/gettext gettext bind_textdomain_codeset8824744
Ref: 3ba8824744
Ref: library/gettext gettext textdomain8825152
Ref: 31818825152
Ref: library/gettext gettext gettext8825379
Ref: e928825379
Ref: library/gettext gettext dgettext8825621
Ref: 31828825621
Ref: library/gettext gettext ngettext8825756
Ref: 31838825756
Ref: library/gettext gettext dngettext8826419
Ref: 31848826419
Ref: library/gettext gettext pgettext8826574
Ref: 3008826574
Ref: library/gettext gettext dpgettext8826623
Ref: 31858826623
Ref: library/gettext gettext npgettext8826681
Ref: 31868826681
Ref: library/gettext gettext dnpgettext8826743
Ref: 31878826743
Ref: library/gettext gettext lgettext8827055
Ref: 3b68827055
Ref: library/gettext gettext ldgettext8827095
Ref: 3b78827095
Ref: library/gettext gettext lngettext8827144
Ref: 3b88827144
Ref: library/gettext gettext ldngettext8827197
Ref: 3b98827197
Ref: GNU gettext API-Footnote-18828515
Ref: GNU gettext API-Footnote-28828993
Node: 基于类的 API8829058
Ref: library/gettext class-based-api8829216
Ref: 31888829216
Ref: library/gettext gettext find8829716
Ref: 318a8829716
Ref: library/gettext gettext translation8831073
Ref: 3bd8831073
Ref: library/gettext gettext install8832476
Ref: 3be8832476
Ref: 基于类的 API-Footnote-18833427
Node: NullTranslations 类8833495
Ref: library/gettext the-nulltranslations-class8833596
Ref: 318f8833596
Ref: library/gettext gettext NullTranslations8833973
Ref: 318d8833973
Ref: library/gettext gettext NullTranslations _parse8834383
Ref: 31918834383
Ref: library/gettext gettext NullTranslations add_fallback8834677
Ref: 31908834677
Ref: library/gettext gettext NullTranslations gettext8834896
Ref: 31928834896
Ref: library/gettext gettext NullTranslations ngettext8835075
Ref: 31938835075
Ref: library/gettext gettext NullTranslations pgettext8835315
Ref: 31948835315
Ref: library/gettext gettext NullTranslations npgettext8835548
Ref: 31958835548
Ref: library/gettext gettext NullTranslations lgettext8835796
Ref: 318b8835796
Ref: library/gettext gettext NullTranslations lngettext8835839
Ref: 318c8835839
Ref: library/gettext gettext NullTranslations info8836370
Ref: 31968836370
Ref: library/gettext gettext NullTranslations charset8836556
Ref: 31978836556
Ref: library/gettext gettext NullTranslations output_charset8836639
Ref: 3bb8836639
Ref: library/gettext gettext NullTranslations set_output_charset8836871
Ref: 3bc8836871
Ref: library/gettext gettext NullTranslations install8837046
Ref: 318e8837046
Node: GNUTranslations 类8838200
Ref: library/gettext the-gnutranslations-class8838336
Ref: 31988838336
Ref: library/gettext gettext GNUTranslations8839814
Ref: 31898839814
Ref: library/gettext gettext GNUTranslations gettext8839903
Ref: 31998839903
Ref: library/gettext gettext GNUTranslations ngettext8840258
Ref: 319a8840258
Ref: library/gettext gettext GNUTranslations pgettext8841089
Ref: 319b8841089
Ref: library/gettext gettext GNUTranslations npgettext8841509
Ref: 319c8841509
Ref: library/gettext gettext GNUTranslations lgettext8842033
Ref: 319d8842033
Ref: library/gettext gettext GNUTranslations lngettext8842076
Ref: 319e8842076
Ref: GNUTranslations 类-Footnote-18842616
Node: Solaris 消息编目支持8842664
Ref: library/gettext solaris-message-catalog-support8842795
Ref: 319f8842795
Node: 编目构造器8843010
Ref: library/gettext the-catalog-constructor8843113
Ref: 31a08843113
Node: 国际化 I18N 你的程序和模块8843713
Ref: library/gettext internationalizing-your-programs-and-modules8843865
Ref: 31a18843865
Ref: 国际化 I18N 你的程序和模块-Footnote-18847006
Ref: 国际化 I18N 你的程序和模块-Footnote-28847038
Node: 本地化你的模块8847081
Ref: library/gettext localizing-your-module8847211
Ref: 31a28847211
Node: 本地化你的应用程序8847724
Ref: library/gettext localizing-your-application8847881
Ref: 31a38847881
Node: 即时更改语言8848534
Ref: library/gettext changing-languages-on-the-fly8848682
Ref: 31a48848682
Node: 延迟翻译8849307
Ref: library/gettext deferred-translations8849419
Ref: 31a58849419
Node: 致谢<9>8851468
Ref: library/gettext acknowledgements8851595
Ref: 31a68851595
Node: locale --- 国际化服务8851937
Ref: library/locale doc8852054
Ref: 31a78852054
Ref: library/locale locale-internationalization-services8852054
Ref: 31a88852054
Ref: library/locale module-locale8852054
Ref: a98852054
Ref: library/locale locale Error8852672
Ref: 31a98852672
Ref: library/locale locale setlocale8852787
Ref: 21668852787
Ref: library/locale locale localeconv8853910
Ref: 5848853910
Ref: library/locale locale nl_langinfo8860595
Ref: 31ad8860595
Ref: library/locale locale CODESET8860995
Ref: 31ae8860995
Ref: library/locale locale D_T_FMT8861110
Ref: 31af8861110
Ref: library/locale locale D_FMT8861292
Ref: 31b08861292
Ref: library/locale locale T_FMT8861463
Ref: 31b18861463
Ref: library/locale locale T_FMT_AMPM8861634
Ref: 31b28861634
Ref: library/locale locale RADIXCHAR8862311
Ref: 31b38862311
Ref: library/locale locale THOUSEP8862413
Ref: 31b48862413
Ref: library/locale locale YESEXPR8862507
Ref: 31b58862507
Ref: library/locale locale NOEXPR8862830
Ref: 31b68862830
Ref: library/locale locale CRNCYSTR8863004
Ref: 31b78863004
Ref: library/locale locale ERA8863277
Ref: 31b88863277
Ref: library/locale locale ERA_D_T_FMT8863818
Ref: 31b98863818
Ref: library/locale locale ERA_D_FMT8864016
Ref: 31ba8864016
Ref: library/locale locale ERA_T_FMT8864203
Ref: 31bb8864203
Ref: library/locale locale ALT_DIGITS8864390
Ref: 31bc8864390
Ref: library/locale locale getdefaultlocale8864496
Ref: 14928864496
Ref: library/locale locale getlocale8865533
Ref: 1a328865533
Ref: library/locale locale getpreferredencoding8865956
Ref: 4ab8865956
Ref: library/locale locale normalize8866778
Ref: 31bf8866778
Ref: library/locale locale resetlocale8867156
Ref: 31c08867156
Ref: library/locale locale strcoll8867377
Ref: 31c18867377
Ref: library/locale locale strxfrm8867660
Ref: 31c38867660
Ref: library/locale locale format_string8867951
Ref: 4aa8867951
Ref: library/locale locale format8868520
Ref: 5698868520
Ref: library/locale locale currency8868977
Ref: 31c48868977
Ref: library/locale locale str8869545
Ref: 31c58869545
Ref: library/locale locale delocalize8869698
Ref: 7fc8869698
Ref: library/locale locale atof8869872
Ref: 31c68869872
Ref: library/locale locale atoi8869989
Ref: 31c78869989
Ref: library/locale locale LC_CTYPE8870103
Ref: 31be8870103
Ref: library/locale locale LC_COLLATE8870279
Ref: 31c28870279
Ref: library/locale locale LC_TIME8870463
Ref: 31c88870463
Ref: library/locale locale LC_MONETARY8870606
Ref: 31ac8870606
Ref: library/locale locale LC_MESSAGES8870752
Ref: 31c98870752
Ref: library/locale locale LC_NUMERIC8871017
Ref: 31aa8871017
Ref: library/locale locale LC_ALL8871316
Ref: 31bd8871316
Ref: library/locale locale CHAR_MAX8871690
Ref: 31ab8871690
Ref: locale --- 国际化服务-Footnote-18872488
Ref: locale --- 国际化服务-Footnote-28872553
Ref: locale --- 国际化服务-Footnote-38872602
Node: 背景、细节、提示、技巧和注意事项8872651
Ref: library/locale background-details-hints-tips-and-caveats8872832
Ref: 31ca8872832
Node: 针对扩展程序编写人员和嵌入Python 运行的程序8874707
Ref: library/locale embedding-locale8874915
Ref: 31cb8874915
Ref: library/locale for-extension-writers-and-programs-that-embed-python8874915
Ref: 31cc8874915
Node: 访问信息目录8875616
Ref: library/locale access-to-message-catalogs8875767
Ref: 31cd8875767
Ref: library/locale locale-gettext8875767
Ref: 31ce8875767
Ref: library/locale locale gettext8875818
Ref: 31cf8875818
Ref: library/locale locale dgettext8875852
Ref: 31d08875852
Ref: library/locale locale dcgettext8875895
Ref: 31d18875895
Ref: library/locale locale textdomain8875949
Ref: 31d28875949
Ref: library/locale locale bindtextdomain8875989
Ref: 31d38875989
Node: 程式框架8876803
Ref: library/frameworks doc8876935
Ref: 31d48876935
Ref: library/frameworks frameworks8876935
Ref: 31d58876935
Ref: library/frameworks program-frameworks8876935
Ref: 31d68876935
Node: turtle --- 龜圖學8877326
Ref: library/turtle doc8877445
Ref: 31d78877445
Ref: library/turtle module-turtle8877445
Ref: 11f8877445
Ref: library/turtle turtle-turtle-graphics8877445
Ref: 31d88877445
Ref: turtle --- 龜圖學-Footnote-18878006
Node: 介紹8878071
Ref: library/turtle introduction8878183
Ref: 31d98878183
Node: 可用的 Turtle 和 Screen 方法概览8881494
Ref: library/turtle overview-of-available-turtle-and-screen-methods8881653
Ref: 31e08881653
Node: Turtle 方法8881805
Ref: library/turtle turtle-methods8881930
Ref: 31e18881930
Node: TurtleScreen/Screen 方法8885716
Ref: library/turtle methods-of-turtlescreen-screen8885841
Ref: 32318885841
Node: RawTurtle/Turtle 方法和对应函数8887491
Ref: library/turtle methods-of-rawturtle-turtle-and-corresponding-functions8887685
Ref: 32508887685
Node: 海龟动作8888034
Ref: library/turtle turtle-motion8888151
Ref: 32518888151
Ref: library/turtle turtle forward8888192
Ref: 31e28888192
Ref: library/turtle turtle fd8888230
Ref: 31e38888230
Ref: library/turtle turtle back8888641
Ref: 31e68888641
Ref: library/turtle turtle bk8888676
Ref: 31e58888676
Ref: library/turtle turtle backward8888709
Ref: 31e48888709
Ref: library/turtle turtle right8889056
Ref: 31e78889056
Ref: library/turtle turtle rt8889089
Ref: 31e88889089
Ref: library/turtle turtle left8889540
Ref: 31e98889540
Ref: library/turtle turtle lt8889572
Ref: 31ea8889572
Ref: library/turtle turtle goto8890021
Ref: 31eb8890021
Ref: library/turtle turtle setpos8890057
Ref: 31ec8890057
Ref: library/turtle turtle setposition8890095
Ref: 31ed8890095
Ref: library/turtle turtle setx8890861
Ref: 31ee8890861
Ref: library/turtle turtle sety8891160
Ref: 31ef8891160
Ref: library/turtle turtle setheading8891458
Ref: 31f08891458
Ref: library/turtle turtle seth8891499
Ref: 31f18891499
Ref: library/turtle turtle home8892307
Ref: 31f28892307
Ref: library/turtle turtle circle8892696
Ref: 31f38892696
Ref: library/turtle turtle dot8894002
Ref: 31f48894002
Ref: library/turtle turtle stamp8894573
Ref: 31f58894573
Ref: library/turtle turtle clearstamp8894863
Ref: 31f68894863
Ref: library/turtle turtle clearstamps8895372
Ref: 31f78895372
Ref: library/turtle turtle undo8895975
Ref: 31f88895975
Ref: library/turtle turtle speed8896298
Ref: 31f98896298
Node: 获取海龟的状态8897251
Ref: library/turtle tell-turtle-s-state8897395
Ref: 32538897395
Ref: library/turtle turtle position8897451
Ref: 31fa8897451
Ref: library/turtle turtle pos8897482
Ref: 31fb8897482
Ref: library/turtle turtle towards8897646
Ref: 31fc8897646
Ref: library/turtle turtle xcor8898172
Ref: 31fd8898172
Ref: library/turtle turtle ycor8898442
Ref: 31fe8898442
Ref: library/turtle turtle heading8898719
Ref: 31ff8898719
Ref: library/turtle turtle distance8898948
Ref: 32008898948
Node: 度量单位设置8899512
Ref: library/turtle settings-for-measurement8899656
Ref: 32548899656
Ref: library/turtle turtle degrees8899707
Ref: 32018899707
Ref: library/turtle turtle radians8900308
Ref: 32028900308
Node: 画笔控制8900621
Ref: library/turtle pen-control8900756
Ref: 32558900756
Node: 绘图状态8900875
Ref: library/turtle drawing-state8900957
Ref: 32568900957
Ref: library/turtle turtle pendown8901000
Ref: 32038901000
Ref: library/turtle turtle pd8901030
Ref: 32048901030
Ref: library/turtle turtle down8901055
Ref: 32058901055
Ref: library/turtle turtle penup8901128
Ref: 32068901128
Ref: library/turtle turtle pu8901156
Ref: 32078901156
Ref: library/turtle turtle up8901181
Ref: 32088901181
Ref: library/turtle turtle pensize8901252
Ref: 32098901252
Ref: library/turtle turtle width8901292
Ref: 320a8901292
Ref: library/turtle turtle pen8901734
Ref: 320b8901734
Ref: library/turtle turtle isdown8903486
Ref: 320c8903486
Node: 颜色控制8903752
Ref: library/turtle color-control8903849
Ref: 32578903849
Ref: library/turtle turtle pencolor8903892
Ref: 320e8903892
Ref: library/turtle turtle fillcolor8905428
Ref: 320f8905428
Ref: library/turtle turtle color8906841
Ref: 320d8906841
Node: 填充8908027
Ref: library/turtle filling8908130
Ref: 32588908130
Ref: library/turtle turtle filling8908163
Ref: 32108908163
Ref: library/turtle turtle begin_fill8908434
Ref: 32118908434
Ref: library/turtle turtle end_fill8908517
Ref: 32128908517
Node: 更多绘图控制8909029
Ref: library/turtle more-drawing-control8909111
Ref: 32598909111
Ref: library/turtle turtle reset8909164
Ref: 32138909164
Ref: library/turtle turtle clear8909586
Ref: 32148909586
Ref: library/turtle turtle write8909754
Ref: 32158909754
Node: 海龟状态8910479
Ref: library/turtle turtle-state8910608
Ref: 325a8910608
Node: 可见性8910686
Ref: library/turtle visibility8910759
Ref: 325b8910759
Ref: library/turtle turtle hideturtle8910797
Ref: 32188910797
Ref: library/turtle turtle ht8910830
Ref: 32198910830
Ref: library/turtle turtle showturtle8911021
Ref: 32168911021
Ref: library/turtle turtle st8911054
Ref: 32178911054
Ref: library/turtle turtle isvisible8911140
Ref: 321a8911140
Node: 外观8911423
Ref: library/turtle appearance8911496
Ref: 325c8911496
Ref: library/turtle turtle shape8911529
Ref: 321b8911529
Ref: library/turtle turtle resizemode8912159
Ref: 321c8912159
Ref: library/turtle turtle shapesize8912993
Ref: 321d8912993
Ref: library/turtle turtle turtlesize8913083
Ref: 321e8913083
Ref: library/turtle turtle shearfactor8913969
Ref: 321f8913969
Ref: library/turtle turtle tilt8914544
Ref: 32228914544
Ref: library/turtle turtle settiltangle8914968
Ref: 32208914968
Ref: library/turtle turtle tiltangle8915458
Ref: 32218915458
Ref: library/turtle turtle shapetransform8916062
Ref: 32238916062
Ref: library/turtle turtle get_shapepoly8917038
Ref: 32248917038
Node: 使用事件8917408
Ref: library/turtle using-events8917543
Ref: 325d8917543
Ref: library/turtle turtle onrelease8918374
Ref: 32268918374
Ref: library/turtle turtle ondrag8919341
Ref: 32278919341
Node: 特殊海龟方法8920109
Ref: library/turtle special-turtle-methods8920244
Ref: 325e8920244
Ref: library/turtle turtle begin_poly8920297
Ref: 32288920297
Ref: library/turtle turtle end_poly8920422
Ref: 32298920422
Ref: library/turtle turtle get_poly8920587
Ref: 322a8920587
Ref: library/turtle turtle clone8920987
Ref: 322b8920987
Ref: library/turtle turtle getturtle8921171
Ref: 322c8921171
Ref: library/turtle turtle getpen8921203
Ref: 322d8921203
Ref: library/turtle turtle getscreen8921451
Ref: 322e8921451
Ref: library/turtle turtle setundobuffer8921745
Ref: 322f8921745
Ref: library/turtle turtle undobufferentries8922177
Ref: 32308922177
Node: 复合形状8922331
Ref: library/turtle compound-shapes8922445
Ref: 325f8922445
Ref: library/turtle compoundshapes8922445
Ref: 32608922445
Node: TurtleScreen/Screen 方法及对应函数8923406
Ref: library/turtle methods-of-turtlescreen-screen-and-corresponding-functions8923569
Ref: 32628923569
Node: 窗口控制8923978
Ref: library/turtle window-control8924089
Ref: 32638924089
Ref: library/turtle turtle bgcolor8924132
Ref: 32328924132
Ref: library/turtle turtle bgpic8924561
Ref: 32338924561
Ref: library/turtle turtle clearscreen8925350
Ref: 32348925350
Ref: library/turtle turtle resetscreen8925775
Ref: 32358925775
Ref: library/turtle turtle screensize8925868
Ref: 32368925868
Ref: library/turtle turtle setworldcoordinates8926720
Ref: 32378926720
Node: 动画控制8927605
Ref: library/turtle animation-control8927743
Ref: 32648927743
Ref: library/turtle turtle delay8927786
Ref: 32388927786
Ref: library/turtle turtle tracer8928171
Ref: 32398928171
Ref: library/turtle turtle update8928823
Ref: 323a8928823
Node: 使用屏幕事件8928981
Ref: library/turtle using-screen-events8929119
Ref: 32658929119
Ref: library/turtle turtle listen8929172
Ref: 323b8929172
Ref: library/turtle turtle onkey8929384
Ref: 323c8929384
Ref: library/turtle turtle onkeyrelease8929420
Ref: 323d8929420
Ref: library/turtle turtle onkeypress8930030
Ref: 323e8930030
Ref: library/turtle turtle onclick8930600
Ref: 32258930600
Ref: library/turtle turtle onscreenclick8930650
Ref: 323f8930650
Ref: library/turtle turtle ontimer8931739
Ref: 32408931739
Ref: library/turtle turtle mainloop8932224
Ref: 32418932224
Ref: library/turtle turtle done8932255
Ref: 32428932255
Node: 输入方法8932589
Ref: library/turtle input-methods8932736
Ref: 32668932736
Ref: library/turtle turtle textinput8932779
Ref: fa68932779
Ref: library/turtle turtle numinput8933240
Ref: fa78933240
Node: 设置与特殊方法8934123
Ref: library/turtle settings-and-special-methods8934300
Ref: 32678934300
Ref: library/turtle turtle mode8934358
Ref: 32438934358
Ref: library/turtle turtle colormode8935534
Ref: 32448935534
Ref: library/turtle turtle getcanvas8936163
Ref: 32458936163
Ref: library/turtle turtle getshapes8936418
Ref: 32468936418
Ref: library/turtle turtle register_shape8936594
Ref: 32478936594
Ref: library/turtle turtle addshape8936647
Ref: 32488936647
Ref: library/turtle turtle turtles8937546
Ref: 32498937546
Ref: library/turtle turtle window_height8937702
Ref: 324a8937702
Ref: library/turtle turtle window_width8937829
Ref: 324b8937829
Node: Screen 专有方法 而非继承自 TurtleScreen8937954
Ref: library/turtle methods-specific-to-screen-not-inherited-from-turtlescreen8938110
Ref: 32688938110
Ref: library/turtle screenspecific8938110
Ref: 32698938110
Ref: library/turtle turtle bye8938222
Ref: 324c8938222
Ref: library/turtle turtle exitonclick8938283
Ref: 324d8938283
Ref: library/turtle turtle setup8938717
Ref: 324e8938717
Ref: library/turtle turtle title8940015
Ref: 324f8940015
Node: 公共类8940281
Ref: library/turtle public-classes8940421
Ref: 326a8940421
Ref: library/turtle turtle RawTurtle8940459
Ref: 31dd8940459
Ref: library/turtle turtle RawPen8940497
Ref: 31de8940497
Ref: library/turtle turtle Turtle8940777
Ref: 31df8940777
Ref: library/turtle turtle TurtleScreen8940958
Ref: 31da8940958
Ref: library/turtle turtle Screen8941141
Ref: 31dc8941141
Ref: library/turtle turtle ScrolledCanvas8941234
Ref: 31db8941234
Ref: library/turtle turtle Shape8941514
Ref: 32618941514
Ref: library/turtle turtle Shape addcomponent8942258
Ref: 326b8942258
Ref: library/turtle turtle Vec2D8942895
Ref: 32528942895
Node: 帮助与配置8943393
Ref: library/turtle help-and-configuration8943522
Ref: 326c8943522
Node: 如何使用帮助8943682
Ref: library/turtle how-to-use-help8943800
Ref: 326d8943800
Node: 文档字符串翻译为不同的语言8946044
Ref: library/turtle translation-of-docstrings-into-different-languages8946201
Ref: 326e8946201
Ref: library/turtle turtle write_docstringdict8946407
Ref: 326f8946407
Node: 如何配置 Screen 和 Turtle8947353
Ref: library/turtle how-to-configure-screen-and-turtles8947483
Ref: 32708947483
Node: turtledemo --- 演示脚本集8950020
Ref: library/turtle module-turtledemo8950166
Ref: 1208950166
Ref: library/turtle turtledemo-demo-scripts8950166
Ref: 32718950166
Node: Python 2 6 之后的变化8955590
Ref: library/turtle changes-since-python-2-68955747
Ref: 32728955747
Node: Python 3 0 之后的变化8956634
Ref: library/turtle changes-since-python-3-08956752
Ref: 32738956752
Node: cmd --- 支持面向行的命令解释器8957815
Ref: library/cmd doc8957977
Ref: 32748957977
Ref: library/cmd cmd-support-for-line-oriented-command-interpreters8957977
Ref: 32758957977
Ref: library/cmd module-cmd8957977
Ref: 198957977
Ref: library/cmd cmd Cmd8958368
Ref: 32768958368
Ref: cmd --- 支持面向行的命令解释器-Footnote-18959428
Node: Cmd 对象8959490
Ref: library/cmd cmd-objects8959597
Ref: 32788959597
Ref: library/cmd id18959597
Ref: 32798959597
Ref: library/cmd cmd Cmd cmdloop8959679
Ref: 327a8959679
Ref: library/cmd cmd Cmd onecmd8961906
Ref: 327d8961906
Ref: library/cmd cmd Cmd emptyline8962420
Ref: 32808962420
Ref: library/cmd cmd Cmd default8962592
Ref: 327f8962592
Ref: library/cmd cmd Cmd completedefault8962784
Ref: 32818962784
Ref: library/cmd cmd Cmd precmd8963008
Ref: 327e8963008
Ref: library/cmd cmd Cmd postcmd8963419
Ref: 327c8963419
Ref: library/cmd cmd Cmd preloop8963933
Ref: 32828963933
Ref: library/cmd cmd Cmd postloop8964132
Ref: 32838964132
Ref: library/cmd cmd Cmd prompt8964421
Ref: 32848964421
Ref: library/cmd cmd Cmd identchars8964482
Ref: 32858964482
Ref: library/cmd cmd Cmd lastcmd8964550
Ref: 32868964550
Ref: library/cmd cmd Cmd cmdqueue8964621
Ref: 32878964621
Ref: library/cmd cmd Cmd intro8964871
Ref: 327b8964871
Ref: library/cmd cmd Cmd doc_header8965025
Ref: 32888965025
Ref: library/cmd cmd Cmd misc_header8965129
Ref: 32898965129
Ref: library/cmd cmd Cmd undoc_header8965308
Ref: 328a8965308
Ref: library/cmd cmd Cmd ruler8965488
Ref: 328b8965488
Ref: library/cmd cmd Cmd use_rawinput8965662
Ref: 32778965662
Node: Cmd 例子8966134
Ref: library/cmd cmd-example8966241
Ref: 328c8966241
Ref: library/cmd id28966241
Ref: 328d8966241
Node: shlex —— 简单的词义分析8971470
Ref: library/shlex doc8971603
Ref: 328e8971603
Ref: library/shlex module-shlex8971603
Ref: e88971603
Ref: library/shlex shlex-simple-lexical-analysis8971603
Ref: 328f8971603
Ref: library/shlex shlex split8972047
Ref: 2108972047
Ref: library/shlex shlex join8972765
Ref: 3458972765
Ref: library/shlex shlex quote8973205
Ref: b4e8973205
Ref: library/shlex shlex shlex8974470
Ref: 6718974470
Ref: shlex —— 简单的词义分析-Footnote-18976469
Node: shlex 对象8976533
Ref: library/shlex id18976637
Ref: 32938976637
Ref: library/shlex shlex-objects8976637
Ref: 32948976637
Ref: library/shlex shlex shlex get_token8976727
Ref: 32958976727
Ref: library/shlex shlex shlex push_token8977108
Ref: 32968977108
Ref: library/shlex shlex shlex read_token8977190
Ref: 32978977190
Ref: library/shlex shlex shlex sourcehook8977359
Ref: 32988977359
Ref: library/shlex shlex shlex push_source8978688
Ref: 329a8978688
Ref: library/shlex shlex shlex pop_source8978932
Ref: 329b8978932
Ref: library/shlex shlex shlex error_leader8979094
Ref: 329c8979094
Ref: library/shlex shlex shlex commenters8979731
Ref: 32908979731
Ref: library/shlex shlex shlex wordchars8979913
Ref: 32928979913
Ref: library/shlex shlex shlex whitespace8980444
Ref: 329e8980444
Ref: library/shlex shlex shlex escape8980616
Ref: 329f8980616
Ref: library/shlex shlex shlex quotes8980729
Ref: 32a08980729
Ref: library/shlex shlex shlex escapedquotes8980971
Ref: 32a18980971
Ref: library/shlex shlex shlex whitespace_split8981168
Ref: 329d8981168
Ref: library/shlex shlex shlex infile8981616
Ref: 32918981616
Ref: library/shlex shlex shlex instream8981820
Ref: 32a28981820
Ref: library/shlex shlex shlex source8981915
Ref: 32998981915
Ref: library/shlex shlex shlex debug8982363
Ref: 32a38982363
Ref: library/shlex shlex shlex lineno8982576
Ref: 32a48982576
Ref: library/shlex shlex shlex token8982674
Ref: 32a58982674
Ref: library/shlex shlex shlex eof8982760
Ref: 32a68982760
Ref: library/shlex shlex shlex punctuation_chars8982931
Ref: 10d98982931
Node: 解析规则8983248
Ref: library/shlex parsing-rules8983386
Ref: 32a78983386
Ref: library/shlex shlex-parsing-rules8983386
Ref: 32a88983386
Node: 改进的 shell 兼容性8985049
Ref: library/shlex improved-compatibility-with-shells8985166
Ref: 32a98985166
Ref: library/shlex improved-shell-compatibility8985166
Ref: 6728985166
Node: 以 Tk 打造 GUI8987666
Ref: library/tk doc8987801
Ref: 32aa8987801
Ref: library/tk graphical-user-interfaces-with-tk8987801
Ref: 32ab8987801
Ref: library/tk tkinter8987801
Ref: 32ac8987801
Ref: 以 Tk 打造 GUI-Footnote-18989566
Node: tkinter --- Tcl/Tk的Python接口8989618
Ref: library/tkinter doc8989760
Ref: 32ad8989760
Ref: library/tkinter module-tkinter8989760
Ref: 10e8989760
Ref: library/tkinter tkinter-python-interface-to-tcl-tk8989760
Ref: 32ae8989760
Ref: tkinter --- Tcl/Tk的Python接口-Footnote-18991818
Ref: tkinter --- Tcl/Tk的Python接口-Footnote-28991894
Ref: tkinter --- Tcl/Tk的Python接口-Footnote-38991921
Ref: tkinter --- Tcl/Tk的Python接口-Footnote-48991961
Ref: tkinter --- Tcl/Tk的Python接口-Footnote-58992018
Ref: tkinter --- Tcl/Tk的Python接口-Footnote-68992045
Ref: tkinter --- Tcl/Tk的Python接口-Footnote-78992082
Ref: tkinter --- Tcl/Tk的Python接口-Footnote-88992174
Ref: tkinter --- Tcl/Tk的Python接口-Footnote-98992225
Node: Tkinter 模块8992284
Ref: library/tkinter tkinter-modules8992391
Ref: 32af8992391
Ref: library/tkinter tkinter Tk8992716
Ref: 32b08992716
Ref: library/tkinter tkinter Tcl8992993
Ref: 32b18992993
Node: Tkinter 拾遗8995563
Ref: library/tkinter tkinter-life-preserver8995692
Ref: 32b28995692
Node: 本节内容的用法8996433
Ref: library/tkinter how-to-use-this-section8996542
Ref: 32b38996542
Node: 简单的 Hello World 程序8997816
Ref: library/tkinter a-simple-hello-world-program8997925
Ref: 32b48997925
Node: Tcl/Tk 速览8998792
Ref: library/tkinter a-very-quick-look-at-tcl-tk8998940
Ref: 32b58998940
Node: 将简单的 Tk 映射到 Tkinter9001990
Ref: library/tkinter mapping-basic-tk-into-tkinter9002151
Ref: 32b79002151
Ref: library/tkinter tkinter-basic-mapping9002151
Ref: 32b69002151
Node: Tk 和 Tkinter 如何关联9003891
Ref: library/tkinter how-tk-and-tkinter-are-related9004051
Ref: 32b99004051
Node: 快速参考9005124
Ref: library/tkinter handy-reference9005264
Ref: 32ba9005264
Node: 可选配置项9005506
Ref: library/tkinter setting-options9005589
Ref: 32bb9005589
Ref: library/tkinter tkinter-setting-options9005589
Ref: 32b89005589
Node: The Packer9008495
Ref: library/tkinter the-packer9008605
Ref: 32bc9008605
Node: 包装器的参数9009947
Ref: library/tkinter packer-options9010066
Ref: 32bd9010066
Node: 部件与变量的关联9010701
Ref: library/tkinter coupling-widget-variables9010825
Ref: 32be9010825
Node: 窗口管理器9012841
Ref: library/tkinter the-window-manager9012971
Ref: 32bf9012971
Node: Tk 参数的数据类型9014181
Ref: library/tkinter tk-option-data-types9014302
Ref: 32c09014302
Node: 绑定和事件9017286
Ref: library/tkinter bindings-and-events9017411
Ref: 32c19017411
Ref: library/tkinter id19017411
Ref: 32c29017411
Node: The index Parameter9020084
Ref: library/tkinter the-index-parameter9020191
Ref: 32c39020191
Node: Images9022122
Ref: library/tkinter images9022205
Ref: 32c49022205
Ref: Images-Footnote-19023138
Node: File Handlers9023172
Ref: library/tkinter file-handlers9023276
Ref: 32c59023276
Ref: library/tkinter tkinter-file-handlers9023276
Ref: 32c69023276
Ref: library/tkinter tkinter Widget tk createfilehandler9024218
Ref: 32c79024218
Ref: library/tkinter tkinter Widget tk deletefilehandler9024659
Ref: 32c89024659
Ref: library/tkinter tkinter READABLE9024747
Ref: 32c99024747
Ref: library/tkinter tkinter WRITABLE9024774
Ref: 32ca9024774
Ref: library/tkinter tkinter EXCEPTION9024801
Ref: 32cb9024801
Node: tkinter colorchooser --- 颜色选择对话框9024876
Ref: library/tkinter colorchooser doc9025064
Ref: 32cc9025064
Ref: library/tkinter colorchooser module-tkinter colorchooser9025064
Ref: 10f9025064
Ref: library/tkinter colorchooser tkinter-colorchooser-color-choosing-dialog9025064
Ref: 32cd9025064
Ref: library/tkinter colorchooser tkinter colorchooser Chooser9025526
Ref: 32ce9025526
Ref: library/tkinter colorchooser tkinter colorchooser askcolor9025593
Ref: 32d09025593
Ref: tkinter colorchooser --- 颜色选择对话框-Footnote-19025967
Node: tkinter font --- Tkinter 字体封装9026047
Ref: library/tkinter font doc9026219
Ref: 32d19026219
Ref: library/tkinter font module-tkinter font9026219
Ref: 1139026219
Ref: library/tkinter font tkinter-font-tkinter-font-wrapper9026219
Ref: 32d29026219
Ref: library/tkinter font tkinter font NORMAL9026554
Ref: 32d39026554
Ref: library/tkinter font tkinter font BOLD9026584
Ref: 32d49026584
Ref: library/tkinter font tkinter font ITALIC9026612
Ref: 32d59026612
Ref: library/tkinter font tkinter font ROMAN9026642
Ref: 32d69026642
Ref: library/tkinter font tkinter font Font9026672
Ref: fcb9026672
Ref: library/tkinter font tkinter font Font actual9028023
Ref: 32d79028023
Ref: library/tkinter font tkinter font Font cget9028120
Ref: 32d89028120
Ref: library/tkinter font tkinter font Font config9028206
Ref: 32d99028206
Ref: library/tkinter font tkinter font Font copy9028297
Ref: 32da9028297
Ref: library/tkinter font tkinter font Font measure9028374
Ref: 32db9028374
Ref: library/tkinter font tkinter font Font metrics9028593
Ref: 32dc9028593
Ref: library/tkinter font tkinter font families9029198
Ref: 32dd9029198
Ref: library/tkinter font tkinter font names9029298
Ref: 32de9029298
Ref: library/tkinter font tkinter font nametofont9029379
Ref: 32df9029379
Ref: tkinter font --- Tkinter 字体封装-Footnote-19029536
Node: Tkinter 对话框9029607
Ref: library/dialog doc9029776
Ref: 32e09029776
Ref: library/dialog tkinter-dialogs9029776
Ref: 32e19029776
Node: tkinter simpledialog --- 标准 Tkinter 输入对话框9030125
Ref: library/dialog module-tkinter simpledialog9030287
Ref: 1169030287
Ref: library/dialog tkinter-simpledialog-standard-tkinter-input-dialogs9030287
Ref: 32e29030287
Ref: library/dialog tkinter simpledialog askfloat9030677
Ref: 32e39030677
Ref: library/dialog tkinter simpledialog askinteger9030741
Ref: 32e49030741
Ref: library/dialog tkinter simpledialog askstring9030807
Ref: 32e59030807
Ref: library/dialog tkinter simpledialog Dialog9030950
Ref: 32e69030950
Ref: library/dialog tkinter simpledialog Dialog body9031047
Ref: 32e79031047
Ref: library/dialog tkinter simpledialog Dialog buttonbox9031210
Ref: 32e89031210
Ref: tkinter simpledialog --- 标准 Tkinter 输入对话框-Footnote-19031377
Node: tkinter filedialog --- 文件选择对话框9031457
Ref: library/dialog module-tkinter filedialog9031671
Ref: 1129031671
Ref: library/dialog tkinter-filedialog-file-selection-dialogs9031671
Ref: 32e99031671
Ref: tkinter filedialog --- 文件选择对话框-Footnote-19032112
Node: 原生 加载/保存 对话框9032190
Ref: library/dialog native-load-save-dialogs9032301
Ref: 32ea9032301
Ref: library/dialog tkinter filedialog askopenfile9033227
Ref: 32eb9033227
Ref: library/dialog tkinter filedialog askopenfiles9033292
Ref: 32ec9033292
Ref: library/dialog tkinter filedialog asksaveasfile9033478
Ref: 32ee9033478
Ref: library/dialog tkinter filedialog askopenfilename9033640
Ref: 32f09033640
Ref: library/dialog tkinter filedialog askopenfilenames9033699
Ref: 32f19033699
Ref: library/dialog tkinter filedialog asksaveasfilename9033891
Ref: 32f29033891
Ref: library/dialog tkinter filedialog askdirectory9034029
Ref: 32f39034029
Ref: library/dialog tkinter filedialog Open9034244
Ref: 32ed9034244
Ref: library/dialog tkinter filedialog SaveAs9034305
Ref: 32ef9034305
Ref: library/dialog tkinter filedialog Directory9034567
Ref: 32f49034567
Ref: library/dialog tkinter filedialog FileDialog9034784
Ref: 32f59034784
Ref: library/dialog tkinter filedialog FileDialog cancel_command9034900
Ref: 32f69034900
Ref: library/dialog tkinter filedialog FileDialog dirs_double_event9034994
Ref: 32f79034994
Ref: library/dialog tkinter filedialog FileDialog dirs_select_event9035092
Ref: 32f89035092
Ref: library/dialog tkinter filedialog FileDialog files_double_event9035190
Ref: 32f99035190
Ref: library/dialog tkinter filedialog FileDialog files_select_event9035289
Ref: 32fa9035289
Ref: library/dialog tkinter filedialog FileDialog filter_command9035388
Ref: 32fb9035388
Ref: library/dialog tkinter filedialog FileDialog get_filter9035474
Ref: 32fc9035474
Ref: library/dialog tkinter filedialog FileDialog get_selection9035561
Ref: 32fd9035561
Ref: library/dialog tkinter filedialog FileDialog go9035642
Ref: 32fe9035642
Ref: library/dialog tkinter filedialog FileDialog ok_event9035789
Ref: 32ff9035789
Ref: library/dialog tkinter filedialog FileDialog quit9035873
Ref: 33009035873
Ref: library/dialog tkinter filedialog FileDialog set_filter9035970
Ref: 33019035970
Ref: library/dialog tkinter filedialog FileDialog set_selection9036050
Ref: 33029036050
Ref: library/dialog tkinter filedialog LoadFileDialog9036147
Ref: 33039036147
Ref: library/dialog tkinter filedialog LoadFileDialog ok_command9036293
Ref: 33049036293
Ref: library/dialog tkinter filedialog SaveFileDialog9036406
Ref: 33059036406
Ref: library/dialog tkinter filedialog SaveFileDialog ok_command9036558
Ref: 33069036558
Node: tkinter commondialog --- 对话窗口模板9036698
Ref: library/dialog module-tkinter commondialog9036848
Ref: 1109036848
Ref: library/dialog tkinter-commondialog-dialog-window-templates9036848
Ref: 33079036848
Ref: library/dialog tkinter commondialog Dialog9037188
Ref: 32cf9037188
Ref: library/dialog tkinter commondialog Dialog show9037254
Ref: 33089037254
Ref: tkinter commondialog --- 对话窗口模板-Footnote-19037457
Node: tkinter messagebox --- Tkinter 消息提示9037537
Ref: library/tkinter messagebox doc9037712
Ref: 33099037712
Ref: library/tkinter messagebox module-tkinter messagebox9037712
Ref: 1149037712
Ref: library/tkinter messagebox tkinter-messagebox-tkinter-message-prompts9037712
Ref: 330a9037712
Ref: library/tkinter messagebox tkinter messagebox Message9038229
Ref: 330b9038229
Ref: library/tkinter messagebox tkinter messagebox showinfo9038356
Ref: 330c9038356
Ref: library/tkinter messagebox tkinter messagebox showwarning9038470
Ref: 330d9038470
Ref: library/tkinter messagebox tkinter messagebox showerror9038567
Ref: 330e9038567
Ref: library/tkinter messagebox tkinter messagebox askquestion9038682
Ref: 330f9038682
Ref: library/tkinter messagebox tkinter messagebox askokcancel9038779
Ref: 33109038779
Ref: library/tkinter messagebox tkinter messagebox askretrycancel9038876
Ref: 33119038876
Ref: library/tkinter messagebox tkinter messagebox askyesno9038976
Ref: 33129038976
Ref: library/tkinter messagebox tkinter messagebox askyesnocancel9039070
Ref: 33139039070
Ref: tkinter messagebox --- Tkinter 消息提示-Footnote-19039207
Node: tkinter scrolledtext --- 滚动文字控件9039285
Ref: library/tkinter scrolledtext doc9039477
Ref: 33149039477
Ref: library/tkinter scrolledtext module-tkinter scrolledtext9039477
Ref: 1159039477
Ref: library/tkinter scrolledtext tkinter-scrolledtext-scrolled-text-widget9039477
Ref: 33159039477
Ref: library/tkinter scrolledtext tkinter scrolledtext ScrolledText9040281
Ref: 33169040281
Ref: library/tkinter scrolledtext tkinter scrolledtext ScrolledText frame9040348
Ref: 33179040348
Ref: library/tkinter scrolledtext tkinter scrolledtext ScrolledText vbar9040426
Ref: 33189040426
Ref: tkinter scrolledtext --- 滚动文字控件-Footnote-19040515
Node: tkinter dnd --- 拖放操作支持9040595
Ref: library/tkinter dnd doc9040774
Ref: 33199040774
Ref: library/tkinter dnd module-tkinter dnd9040774
Ref: 1119040774
Ref: library/tkinter dnd tkinter-dnd-drag-and-drop-support9040774
Ref: 331a9040774
Ref: library/tkinter dnd tkinter dnd DndHandler9042142
Ref: 331c9042142
Ref: library/tkinter dnd tkinter dnd DndHandler cancel9042314
Ref: 331d9042314
Ref: library/tkinter dnd tkinter dnd DndHandler finish9042391
Ref: 331e9042391
Ref: library/tkinter dnd tkinter dnd DndHandler on_motion9042479
Ref: 331f9042479
Ref: library/tkinter dnd tkinter dnd DndHandler on_release9042599
Ref: 33209042599
Ref: library/tkinter dnd tkinter dnd dnd_start9042705
Ref: 331b9042705
Ref: tkinter dnd --- 拖放操作支持-Footnote-19042883
Node: tkinter ttk --- Tk主题部件9042953
Ref: library/tkinter ttk doc9043116
Ref: 33219043116
Ref: library/tkinter ttk module-tkinter ttk9043116
Ref: 1189043116
Ref: library/tkinter ttk tkinter-ttk-tk-themed-widgets9043116
Ref: 33229043116
Ref: tkinter ttk --- Tk主题部件-Footnote-19044062
Ref: tkinter ttk --- Tk主题部件-Footnote-29044132
Node: 使用 Ttk9044185
Ref: library/tkinter ttk using-ttk9044281
Ref: 33239044281
Ref: 使用 Ttk-Footnote-19045281
Node: Ttk 控件9045344
Ref: library/tkinter ttk ttk-widgets9045455
Ref: 33249045455
Node: 控件9046534
Ref: library/tkinter ttk widget9046644
Ref: 332b9046644
Node: 标准选项9046931
Ref: library/tkinter ttk standard-options9047016
Ref: 332c9047016
Node: 可滚动控件选项9048332
Ref: library/tkinter ttk scrollable-widget-options9048438
Ref: 332d9048438
Node: 标签选项9049320
Ref: library/tkinter ttk label-options9049429
Ref: 332e9049429
Node: 兼容性选项9051604
Ref: library/tkinter ttk compatibility-options9051704
Ref: 332f9051704
Node: 控件状态9052184
Ref: library/tkinter ttk widget-states9052282
Ref: 33319052282
Node: ttk Widget9053773
Ref: library/tkinter ttk ttk-widget9053847
Ref: 33329053847
Ref: library/tkinter ttk tkinter ttk Widget9054018
Ref: 33289054018
Ref: library/tkinter ttk tkinter ttk Widget identify9054050
Ref: 33339054050
Ref: library/tkinter ttk tkinter ttk Widget instate9054290
Ref: 33349054290
Ref: library/tkinter ttk tkinter ttk Widget state9054676
Ref: 33309054676
Node: 组合框9055039
Ref: library/tkinter ttk combobox9055146
Ref: 33359055146
Node: 选项9055821
Ref: library/tkinter ttk options9055894
Ref: 33369055894
Node: 虚拟事件9057944
Ref: library/tkinter ttk virtual-events9058038
Ref: 33379058038
Node: ttk Combobox9058194
Ref: library/tkinter ttk ttk-combobox9058273
Ref: 33389058273
Ref: library/tkinter ttk tkinter ttk Combobox9058320
Ref: 33259058320
Ref: library/tkinter ttk tkinter ttk Combobox current9058354
Ref: 33399058354
Ref: library/tkinter ttk tkinter ttk Combobox get9058583
Ref: 333a9058583
Ref: library/tkinter ttk tkinter ttk Combobox set9058653
Ref: 333b9058653
Node: Spinbox9058734
Ref: library/tkinter ttk spinbox9058844
Ref: 333c9058844
Node: 选项<2>9059578
Ref: library/tkinter ttk id19059655
Ref: 333d9059655
Node: 虚拟事件<2>9061450
Ref: library/tkinter ttk id29061547
Ref: 333e9061547
Node: ttk Spinbox9061722
Ref: library/tkinter ttk ttk-spinbox9061801
Ref: 333f9061801
Ref: library/tkinter ttk tkinter ttk Spinbox9061846
Ref: 5019061846
Ref: library/tkinter ttk tkinter ttk Spinbox get9061879
Ref: 33409061879
Ref: library/tkinter ttk tkinter ttk Spinbox set9061944
Ref: 33419061944
Node: 笔记本9062020
Ref: library/tkinter ttk notebook9062132
Ref: 33429062132
Node: 选项<3>9062471
Ref: library/tkinter ttk id39062545
Ref: 33439062545
Node: Tab 选项9063531
Ref: library/tkinter ttk tab-options9063624
Ref: 33449063624
Node: Tab 标识9065312
Ref: library/tkinter ttk tab-identifiers9065411
Ref: 33469065411
Node: 虚拟事件<3>9065867
Ref: library/tkinter ttk id49065968
Ref: 33489065968
Node: ttk Notebook9066111
Ref: library/tkinter ttk ttk-notebook9066193
Ref: 33499066193
Ref: library/tkinter ttk tkinter ttk Notebook9066240
Ref: 33269066240
Ref: library/tkinter ttk tkinter ttk Notebook add9066274
Ref: 334a9066274
Ref: library/tkinter ttk tkinter ttk Notebook forget9066530
Ref: 334b9066530
Ref: library/tkinter ttk tkinter ttk Notebook hide9066648
Ref: 334c9066648
Ref: library/tkinter ttk tkinter ttk Notebook identify9066919
Ref: 334d9066919
Ref: library/tkinter ttk tkinter ttk Notebook index9067073
Ref: 33479067073
Ref: library/tkinter ttk tkinter ttk Notebook insert9067232
Ref: 334e9067232
Ref: library/tkinter ttk tkinter ttk Notebook select9067555
Ref: 334f9067555
Ref: library/tkinter ttk tkinter ttk Notebook tab9067805
Ref: 33509067805
Ref: library/tkinter ttk tkinter ttk Notebook tabs9068080
Ref: 33519068080
Ref: library/tkinter ttk tkinter ttk Notebook enable_traversal9068164
Ref: 33459068164
Node: Progressbar9068868
Ref: library/tkinter ttk progressbar9068982
Ref: 33529068982
Node: 选项<4>9069308
Ref: library/tkinter ttk id59069389
Ref: 33539069389
Node: ttk Progressbar9070824
Ref: library/tkinter ttk ttk-progressbar9070905
Ref: 33549070905
Ref: library/tkinter ttk tkinter ttk Progressbar9070958
Ref: 33279070958
Ref: library/tkinter ttk tkinter ttk Progressbar start9070995
Ref: 33559070995
Ref: library/tkinter ttk tkinter ttk Progressbar step9071256
Ref: 33569071256
Ref: library/tkinter ttk tkinter ttk Progressbar stop9071396
Ref: 33579071396
Node: Separator9071554
Ref: library/tkinter ttk separator9071667
Ref: 33589071667
Node: 选项<5>9071900
Ref: library/tkinter ttk id69071955
Ref: 33599071955
Node: Sizegrip9072250
Ref: library/tkinter ttk sizegrip9072360
Ref: 335a9072360
Node: 与平台相关的注意事项9072635
Ref: library/tkinter ttk platform-specific-notes9072722
Ref: 335b9072722
Node: Bug9072982
Ref: library/tkinter ttk bugs9073069
Ref: 335c9073069
Node: Treeview9073298
Ref: library/tkinter ttk treeview9073409
Ref: 335d9073409
Node: 选项<6>9074561
Ref: library/tkinter ttk id79074642
Ref: 33619074642
Node: 数据项的属性9076689
Ref: library/tkinter ttk item-options9076789
Ref: 33629076789
Node: tag 属性9077795
Ref: library/tkinter ttk tag-options9077895
Ref: 33639077895
Node: 列标识9078539
Ref: library/tkinter ttk column-identifiers9078636
Ref: 335e9078636
Node: 虚拟事件<4>9079312
Ref: library/tkinter ttk id89079411
Ref: 33649079411
Node: ttk Treeview9080188
Ref: library/tkinter ttk ttk-treeview9080269
Ref: 33669080269
Ref: library/tkinter ttk tkinter ttk Treeview9080316
Ref: 3de9080316
Ref: library/tkinter ttk tkinter ttk Treeview bbox9080350
Ref: 33679080350
Ref: library/tkinter ttk tkinter ttk Treeview get_children9080712
Ref: 33689080712
Ref: library/tkinter ttk tkinter ttk Treeview set_children9080882
Ref: 33699080882
Ref: library/tkinter ttk tkinter ttk Treeview column9081250
Ref: 336a9081250
Ref: library/tkinter ttk tkinter ttk Treeview delete9082353
Ref: 336b9082353
Ref: library/tkinter ttk tkinter ttk Treeview detach9082471
Ref: 336c9082471
Ref: library/tkinter ttk tkinter ttk Treeview exists9082703
Ref: 336d9082703
Ref: library/tkinter ttk tkinter ttk Treeview focus9082814
Ref: 33659082814
Ref: library/tkinter ttk tkinter ttk Treeview heading9082990
Ref: 336e9082990
Ref: library/tkinter ttk tkinter ttk Treeview identify9083860
Ref: 336f9083860
Ref: library/tkinter ttk tkinter ttk Treeview identify_row9084054
Ref: 33709084054
Ref: library/tkinter ttk tkinter ttk Treeview identify_column9084145
Ref: 33719084145
Ref: library/tkinter ttk tkinter ttk Treeview identify_region9084294
Ref: 33729084294
Ref: library/tkinter ttk tkinter ttk Treeview identify_element9084961
Ref: 33739084961
Ref: library/tkinter ttk tkinter ttk Treeview index9085093
Ref: 33749085093
Ref: library/tkinter ttk tkinter ttk Treeview insert9085198
Ref: 33759085198
Ref: library/tkinter ttk tkinter ttk Treeview item9085852
Ref: 33769085852
Ref: library/tkinter ttk tkinter ttk Treeview move9086140
Ref: 33779086140
Ref: library/tkinter ttk tkinter ttk Treeview next9086552
Ref: 33789086552
Ref: library/tkinter ttk tkinter ttk Treeview parent9086715
Ref: 33799086715
Ref: library/tkinter ttk tkinter ttk Treeview prev9086845
Ref: 337a9086845
Ref: library/tkinter ttk tkinter ttk Treeview reattach9087002
Ref: 337b9087002
Ref: library/tkinter ttk tkinter ttk Treeview see9087110
Ref: 337c9087110
Ref: library/tkinter ttk tkinter ttk Treeview selection9087326
Ref: 3df9087326
Ref: library/tkinter ttk tkinter ttk Treeview selection_set9087545
Ref: 3e09087545
Ref: library/tkinter ttk tkinter ttk Treeview selection_add9087755
Ref: 337d9087755
Ref: library/tkinter ttk tkinter ttk Treeview selection_remove9087959
Ref: 337e9087959
Ref: library/tkinter ttk tkinter ttk Treeview selection_toggle9088170
Ref: 337f9088170
Ref: library/tkinter ttk tkinter ttk Treeview set9088389
Ref: 33809088389
Ref: library/tkinter ttk tkinter ttk Treeview tag_bind9088665
Ref: 33819088665
Ref: library/tkinter ttk tkinter ttk Treeview tag_configure9088956
Ref: 33829088956
Ref: library/tkinter ttk tkinter ttk Treeview tag_has9089297
Ref: 33839089297
Ref: library/tkinter ttk tkinter ttk Treeview xview9089562
Ref: 335f9089562
Ref: library/tkinter ttk tkinter ttk Treeview yview9089655
Ref: 33609089655
Node: Ttk 风格9089748
Ref: library/tkinter ttk ttk-styling9089842
Ref: 33849089842
Ref: library/tkinter ttk ttkstyling9089842
Ref: 33299089842
Ref: library/tkinter ttk tkinter ttk Style9090338
Ref: 332a9090338
Ref: library/tkinter ttk tkinter ttk Style configure9090412
Ref: 33859090412
Ref: library/tkinter ttk tkinter ttk Style map9091067
Ref: fe49091067
Ref: library/tkinter ttk tkinter ttk Style lookup9092315
Ref: 33869092315
Ref: library/tkinter ttk tkinter ttk Style layout9092842
Ref: 33879092842
Ref: library/tkinter ttk tkinter ttk Style element_create9094160
Ref: 33899094160
Ref: library/tkinter ttk tkinter ttk Style element_names9096252
Ref: 338a9096252
Ref: library/tkinter ttk tkinter ttk Style element_options9096363
Ref: 338b9096363
Ref: library/tkinter ttk tkinter ttk Style theme_create9096475
Ref: 338c9096475
Ref: library/tkinter ttk tkinter ttk Style theme_settings9096894
Ref: 338d9096894
Ref: library/tkinter ttk tkinter ttk Style theme_names9098376
Ref: 338e9098376
Ref: library/tkinter ttk tkinter ttk Style theme_use9098462
Ref: 338f9098462
Ref: Ttk 风格-Footnote-19098765
Node: Layouts9098826
Ref: library/tkinter ttk layouts9098880
Ref: 33889098880
Node: tkinter tix --- TK扩展包9100164
Ref: library/tkinter tix doc9100301
Ref: 33909100301
Ref: library/tkinter tix layout9100301
Ref: 33919100301
Ref: library/tkinter tix layouts9100301
Ref: 33929100301
Ref: library/tkinter tix module-tkinter tix9100301
Ref: 1179100301
Ref: library/tkinter tix tkinter-tix-extension-widgets-for-tk9100301
Ref: 33939100301
Ref: tkinter tix --- TK扩展包-Footnote-19102204
Ref: tkinter tix --- TK扩展包-Footnote-29102274
Ref: tkinter tix --- TK扩展包-Footnote-39102310
Ref: tkinter tix --- TK扩展包-Footnote-49102363
Ref: tkinter tix --- TK扩展包-Footnote-59102440
Node: Using Tix9102497
Ref: library/tkinter tix using-tix9102590
Ref: 339a9102590
Ref: library/tkinter tix tkinter tix Tk9102629
Ref: 339b9102629
Node: Tix Widgets9103603
Ref: library/tkinter tix tix-widgets9103717
Ref: 339c9103717
Ref: Tix Widgets-Footnote-19104057
Node: Basic Widgets9104135
Ref: library/tkinter tix basic-widgets9104219
Ref: 339d9104219
Ref: library/tkinter tix tkinter tix Balloon9104266
Ref: 339e9104266
Ref: library/tkinter tix tkinter tix ButtonBox9104545
Ref: 339f9104545
Ref: library/tkinter tix tkinter tix ComboBox9104687
Ref: 33959104687
Ref: library/tkinter tix tkinter tix Control9104922
Ref: 33969104922
Ref: library/tkinter tix tkinter tix LabelEntry9105171
Ref: 33a09105171
Ref: library/tkinter tix tkinter tix LabelFrame9105383
Ref: 33a19105383
Ref: library/tkinter tix tkinter tix Meter9105686
Ref: 33a29105686
Ref: library/tkinter tix tkinter tix OptionMenu9105840
Ref: 33a39105840
Ref: library/tkinter tix tkinter tix PopupMenu9105934
Ref: 33a49105934
Ref: library/tkinter tix tkinter tix Select9106183
Ref: 33a59106183
Ref: library/tkinter tix tkinter tix StdButtonBox9106381
Ref: 33a69106381
Ref: Basic Widgets-Footnote-19106554
Ref: Basic Widgets-Footnote-29106634
Ref: Basic Widgets-Footnote-39106716
Ref: Basic Widgets-Footnote-49106797
Ref: Basic Widgets-Footnote-59106877
Ref: Basic Widgets-Footnote-69106960
Ref: Basic Widgets-Footnote-79107043
Ref: Basic Widgets-Footnote-89107121
Ref: Basic Widgets-Footnote-99107204
Ref: Basic Widgets-Footnote-109107286
Ref: Basic Widgets-Footnote-119107366
Node: File Selectors9107452
Ref: library/tkinter tix file-selectors9107565
Ref: 33a79107565
Ref: library/tkinter tix tkinter tix DirList9107614
Ref: 33a89107614
Ref: library/tkinter tix tkinter tix DirTree9107875
Ref: 33a99107875
Ref: library/tkinter tix tkinter tix DirSelectDialog9108136
Ref: 33aa9108136
Ref: library/tkinter tix tkinter tix DirSelectBox9108393
Ref: 33ab9108393
Ref: library/tkinter tix tkinter tix ExFileSelectBox9108736
Ref: 33ac9108736
Ref: library/tkinter tix tkinter tix FileSelectBox9109068
Ref: 33ad9109068
Ref: library/tkinter tix tkinter tix FileEntry9109401
Ref: 33989109401
Ref: File Selectors-Footnote-19109722
Ref: File Selectors-Footnote-29109802
Ref: File Selectors-Footnote-39109882
Ref: File Selectors-Footnote-49109970
Ref: File Selectors-Footnote-59110058
Ref: File Selectors-Footnote-69110144
Node: Hierarchical ListBox9110226
Ref: library/tkinter tix hierarchical-listbox9110341
Ref: 33ae9110341
Ref: library/tkinter tix tkinter tix HList9110402
Ref: 33949110402
Ref: library/tkinter tix tkinter tix CheckList9110688
Ref: 33af9110688
Ref: library/tkinter tix tkinter tix Tree9110977
Ref: 33b09110977
Ref: Hierarchical ListBox-Footnote-19111218
Ref: Hierarchical ListBox-Footnote-29111296
Ref: Hierarchical ListBox-Footnote-39111378
Node: Tabular ListBox9111455
Ref: library/tkinter tix tabular-listbox9111571
Ref: 33b19111571
Ref: library/tkinter tix tkinter tix TList9111622
Ref: 33b29111622
Ref: Tabular ListBox-Footnote-19112109
Node: Manager Widgets9112187
Ref: library/tkinter tix manager-widgets9112294
Ref: 33b39112294
Ref: library/tkinter tix tkinter tix PanedWindow9112345
Ref: 33999112345
Ref: library/tkinter tix tkinter tix ListNoteBook9112653
Ref: 33b49112653
Ref: library/tkinter tix tkinter tix NoteBook9113105
Ref: 33979113105
Ref: Manager Widgets-Footnote-19113513
Ref: Manager Widgets-Footnote-29113597
Ref: Manager Widgets-Footnote-39113682
Node: Image Types9113763
Ref: library/tkinter tix image-types9113876
Ref: 33b59113876
Ref: Image Types-Footnote-19114488
Ref: Image Types-Footnote-29114564
Node: Miscellaneous Widgets9114642
Ref: library/tkinter tix miscellaneous-widgets9114761
Ref: 33b69114761
Ref: library/tkinter tix tkinter tix InputOnly9114824
Ref: 33b79114824
Ref: Miscellaneous Widgets-Footnote-19115026
Node: Form Geometry Manager9115108
Ref: library/tkinter tix form-geometry-manager9115207
Ref: 33b89115207
Ref: library/tkinter tix tkinter tix Form9115353
Ref: 33b99115353
Ref: Form Geometry Manager-Footnote-19115505
Node: Tix Commands9115582
Ref: library/tkinter tix tix-commands9115678
Ref: 33ba9115678
Ref: library/tkinter tix tkinter tix tixCommand9115725
Ref: 33bb9115725
Ref: library/tkinter tix tkinter tix tixCommand tix_configure9116232
Ref: 33bc9116232
Ref: library/tkinter tix tkinter tix tixCommand tix_cget9116923
Ref: 33bd9116923
Ref: library/tkinter tix tkinter tix tixCommand tix_getbitmap9117104
Ref: 33be9117104
Ref: library/tkinter tix tkinter tix tixCommand tix_addbitmapdir9117661
Ref: 33bf9117661
Ref: library/tkinter tix tkinter tix tixCommand tix_filedialog9118201
Ref: 33c19118201
Ref: library/tkinter tix tkinter tix tixCommand tix_getimage9118787
Ref: 33c09118787
Ref: library/tkinter tix tkinter tix tixCommand tix_option_get9119583
Ref: 33c29119583
Ref: library/tkinter tix tkinter tix tixCommand tix_resetoptions9119698
Ref: 33c39119698
Ref: Tix Commands-Footnote-19120537
Node: IDLE<51>9120609
Ref: library/idle doc9120707
Ref: 33c49120707
Ref: library/idle id19120707
Ref: 33c59120707
Ref: library/idle idle9120707
Ref: a2b9120707
Ref: IDLE<51>-Footnote-19121726
Node: 目录9121790
Ref: library/idle menus9121865
Ref: 33c69121865
Node: 文件菜单 （命令行和编辑器）9122976
Ref: library/idle file-menu-shell-and-editor9123107
Ref: 33c79123107
Node: 编辑菜单（命令行和编辑器）9124434
Ref: library/idle edit-menu-shell-and-editor9124612
Ref: 33c89124612
Node: 格式菜单（仅 window 编辑器）9126247
Ref: library/idle format-menu9126423
Ref: 33cb9126423
Ref: library/idle format-menu-editor-window-only9126423
Ref: 33cc9126423
Node: 运行菜单（仅 window 编辑器）9127647
Ref: library/idle run-menu-editor-window-only9127822
Ref: 33cd9127822
Ref: library/idle run-module9127911
Ref: 33ce9127911
Ref: library/idle run-custom9128342
Ref: 33d09128342
Ref: library/idle check-module9128620
Ref: 33cf9128620
Ref: library/idle python-shell9128968
Ref: 33d19128968
Node: Shell 菜单（仅 window 编辑器）9129026
Ref: library/idle shell-menu-shell-window-only9129201
Ref: 33d29129201
Node: 调试菜单（仅 window 编辑器）9129689
Ref: library/idle debug-menu-shell-window-only9129865
Ref: 33d39129865
Node: 选项菜单（命令行和编辑器）9130787
Ref: library/idle options-menu-shell-and-editor9130965
Ref: 33d49130965
Node: Window 菜单（命令行和编辑器）9132547
Ref: library/idle window-menu-shell-and-editor9132726
Ref: 33d79132726
Node: 帮助菜单（命令行和编辑器）9132932
Ref: library/idle help-menu-shell-and-editor9133087
Ref: 33d89133087
Node: 上下文菜单9133789
Ref: library/idle context-menus9133895
Ref: 33da9133895
Node: 编辑和导航9134982
Ref: library/idle editing-and-navigation9135087
Ref: 33db9135087
Ref: library/idle id29135087
Ref: 33dc9135087
Node: 编辑窗口9135281
Ref: library/idle editor-windows9135366
Ref: 33dd9135366
Node: 按键绑定9135982
Ref: library/idle key-bindings9136088
Ref: 33de9136088
Node: 自动缩进9137423
Ref: library/idle automatic-indentation9137523
Ref: 33df9137523
Node: 完成9138083
Ref: library/idle completions9138177
Ref: 33c99138177
Ref: library/idle id39138177
Ref: 33e09138177
Node: 提示9140815
Ref: library/idle calltips9140912
Ref: 33ca9140912
Ref: library/idle id49140912
Ref: 33e19140912
Node: 代码上下文9142530
Ref: library/idle code-context9142640
Ref: 33d69142640
Ref: library/idle id59142640
Ref: 33e29142640
Node: Python Shell 窗口9143531
Ref: library/idle python-shell-window9143647
Ref: 33e39143647
Node: 文本颜色9144760
Ref: library/idle text-colors9144852
Ref: 33e49144852
Node: 启动和代码执行9145615
Ref: library/idle startup-and-code-execution9145729
Ref: 33e59145729
Node: 命令行语法9146847
Ref: library/idle command-line-usage9146941
Ref: 33e69146941
Node: 启动失败9147967
Ref: library/idle startup-failure9148088
Ref: 33e79148088
Node: 运行用户代码9151267
Ref: library/idle running-user-code9151396
Ref: 33e89151396
Node: Shell中的用户输出9154094
Ref: library/idle user-output-in-shell9154238
Ref: 33e99154238
Node: 开发 tkinter 应用程序9157326
Ref: library/idle developing-tkinter-applications9157488
Ref: 33ea9157488
Node: 在没有子进程的情况下运行9158725
Ref: library/idle running-without-a-subprocess9158855
Ref: 33eb9158855
Node: 帮助和偏好9160234
Ref: library/idle help-and-preferences9160324
Ref: 33ec9160324
Node: 帮助源9160450
Ref: library/idle help-sources9160535
Ref: 33d99160535
Ref: library/idle id69160535
Ref: 33ed9160535
Node: 首选项设置9161390
Ref: library/idle preferences9161500
Ref: 33d59161500
Ref: library/idle setting-preferences9161500
Ref: 33ee9161500
Node: macOS 上的IDLE9162498
Ref: library/idle idle-on-macos9162605
Ref: 33ef9162605
Node: 扩展9162870
Ref: library/idle extensions9162953
Ref: 33f09162953
Node: 開發工具9163296
Ref: library/development doc9163434
Ref: 33f19163434
Ref: library/development development9163434
Ref: 33f29163434
Ref: library/development development-tools9163434
Ref: 33f39163434
Node: typing --- 类型提示支持9165181
Ref: library/typing doc9165314
Ref: 33f49165314
Ref: library/typing module-typing9165314
Ref: 1229165314
Ref: library/typing typing-support-for-type-hints9165314
Ref: 33f59165314
Ref: typing --- 类型提示支持-Footnote-19166550
Ref: typing --- 类型提示支持-Footnote-29166615
Ref: typing --- 类型提示支持-Footnote-39166664
Node: Relevant PEPs9166713
Ref: library/typing id19166813
Ref: 33f69166813
Ref: library/typing relevant-peps9166813
Ref: 33f79166813
Ref: Relevant PEPs-Footnote-19168132
Ref: Relevant PEPs-Footnote-29168181
Ref: Relevant PEPs-Footnote-39168230
Ref: Relevant PEPs-Footnote-49168279
Ref: Relevant PEPs-Footnote-59168328
Ref: Relevant PEPs-Footnote-69168377
Ref: Relevant PEPs-Footnote-79168426
Ref: Relevant PEPs-Footnote-89168475
Ref: Relevant PEPs-Footnote-99168524
Node: 类型别名9168573
Ref: library/typing type-aliases9168689
Ref: 33f89168689
Node: NewType9169765
Ref: library/typing distinct9169894
Ref: 33f99169894
Ref: library/typing newtype9169894
Ref: 33fa9169894
Ref: NewType-Footnote-19172463
Node: 可调对象（Callable）9172512
Ref: library/typing callable9172648
Ref: 33fb9172648
Node: 泛型（Generic）9173282
Ref: library/typing generics9173438
Ref: 15889173438
Ref: library/typing id29173438
Ref: 33fc9173438
Node: 用户定义的泛型类型9174121
Ref: library/typing user-defined-generic-types9174261
Ref: 33fd9174261
Ref: library/typing user-defined-generics9174261
Ref: 15899174261
Node: Any 类型9177480
Ref: library/typing the-any-type9177635
Ref: 33fe9177635
Node: 名义子类型 vs 结构子类型9179995
Ref: library/typing nominal-vs-structural-subtyping9180138
Ref: 33ff9180138
Ref: 名义子类型 vs 结构子类型-Footnote-19181678
Ref: 名义子类型 vs 结构子类型-Footnote-29181727
Ref: 名义子类型 vs 结构子类型-Footnote-39181776
Node: 模块内容<7>9181825
Ref: library/typing module-contents9181949
Ref: 34009181949
Ref: 模块内容<7>-Footnote-19182905
Node: 特殊类型原语9182954
Ref: library/typing special-typing-primitives9183051
Ref: 34019183051
Node: 特殊类型9183194
Ref: library/typing special-types9183282
Ref: 34029183282
Ref: library/typing typing Any9183387
Ref: 7459183387
Ref: library/typing typing NoReturn9183554
Ref: 34039183554
Node: 特殊形式9183814
Ref: library/typing special-forms9183929
Ref: 34049183929
Ref: library/typing typing Tuple9184059
Ref: 34059184059
Ref: library/typing typing Union9184775
Ref: 116a9184775
Ref: library/typing typing Optional9185785
Ref: 34069185785
Ref: library/typing typing Callable9186351
Ref: 27b9186351
Ref: library/typing typing Type9187193
Ref: 34079187193
Ref: library/typing typing Literal9188836
Ref: 2759188836
Ref: library/typing typing ClassVar9189877
Ref: 69a9189877
Ref: library/typing typing Final9190832
Ref: 3689190832
Ref: library/typing typing Annotated9191325
Ref: 1ee9191325
Ref: 特殊形式-Footnote-19194600
Ref: 特殊形式-Footnote-29194649
Ref: 特殊形式-Footnote-39194698
Ref: 特殊形式-Footnote-49194747
Ref: 特殊形式-Footnote-59194796
Ref: 特殊形式-Footnote-69194845
Ref: 特殊形式-Footnote-79194894
Ref: 特殊形式-Footnote-89194943
Node: 构建泛型类型9194992
Ref: library/typing building-generic-types9195113
Ref: 34089195113
Ref: library/typing typing Generic9195240
Ref: 100b9195240
Ref: library/typing typing TypeVar9195879
Ref: 104e9195879
Ref: library/typing typing AnyStr9197353
Ref: 34099197353
Ref: library/typing typing Protocol9197879
Ref: 36a9197879
Ref: library/typing typing runtime_checkable9198771
Ref: 36b9198771
Ref: 构建泛型类型-Footnote-19199840
Ref: 构建泛型类型-Footnote-29199889
Ref: 构建泛型类型-Footnote-39199938
Node: 其他特殊指令9199987
Ref: library/typing other-special-directives9200087
Ref: 340b9200087
Ref: library/typing typing NamedTuple9200214
Ref: 2279200214
Ref: library/typing typing NewType9201923
Ref: 69c9201923
Ref: library/typing typing TypedDict9202239
Ref: 3679202239
Ref: 其他特殊指令-Footnote-19203975
Ref: 其他特殊指令-Footnote-29204024
Ref: 其他特殊指令-Footnote-39204073
Node: 泛型具象容器9204122
Ref: library/typing generic-concrete-collections9204240
Ref: 340c9204240
Node: 对应的内置类型9204381
Ref: library/typing corresponding-to-built-in-types9204490
Ref: 340d9204490
Ref: library/typing typing Dict9204548
Ref: 340e9204548
Ref: library/typing typing List9205003
Ref: 34109205003
Ref: library/typing typing Set9205640
Ref: 34139205640
Ref: library/typing typing FrozenSet9205989
Ref: 34159205989
Ref: 对应的内置类型-Footnote-19206344
Ref: 对应的内置类型-Footnote-29206393
Ref: 对应的内置类型-Footnote-39206442
Ref: 对应的内置类型-Footnote-49206491
Node: collections 对应类型9206540
Ref: library/typing corresponding-to-types-in-collections9206676
Ref: 34169206676
Ref: library/typing typing DefaultDict9206751
Ref: 34179206751
Ref: library/typing typing OrderedDict9207080
Ref: 34189207080
Ref: library/typing typing ChainMap9207409
Ref: 34199207409
Ref: library/typing typing Counter9207742
Ref: 341a9207742
Ref: library/typing typing Deque9208060
Ref: 341b9208060
Ref: collections 对应类型-Footnote-19208400
Ref: collections 对应类型-Footnote-29208449
Ref: collections 对应类型-Footnote-39208498
Ref: collections 对应类型-Footnote-49208547
Ref: collections 对应类型-Footnote-59208596
Node: 其他具象类型9208645
Ref: library/typing other-concrete-types9208751
Ref: 341c9208751
Ref: library/typing typing IO9208804
Ref: 341d9208804
Ref: library/typing typing TextIO9208826
Ref: 341e9208826
Ref: library/typing typing BinaryIO9208852
Ref: 341f9208852
Ref: library/typing typing Pattern9209259
Ref: 34209209259
Ref: library/typing typing Match9209286
Ref: 34219209286
Ref: library/typing typing Text9209984
Ref: 34229209984
Ref: 其他具象类型-Footnote-19210428
Node: 抽象基类9210477
Ref: library/typing abstract-base-classes9210586
Ref: 34239210586
Node: collections abc 对应的容器9210861
Ref: library/typing corresponding-to-collections-in-collections-abc9210987
Ref: 34249210987
Ref: library/typing typing AbstractSet9211075
Ref: 34149211075
Ref: library/typing typing ByteString9211338
Ref: 34259211338
Ref: library/typing typing Collection9211822
Ref: 6999211822
Ref: library/typing typing Container9212136
Ref: 34269212136
Ref: library/typing typing ItemsView9212398
Ref: 34279212398
Ref: library/typing typing KeysView9212681
Ref: 34289212681
Ref: library/typing typing Mapping9212965
Ref: 340f9212965
Ref: library/typing typing MappingView9213382
Ref: 34299213382
Ref: library/typing typing MutableMapping9213658
Ref: 342a9213658
Ref: library/typing typing MutableSequence9213935
Ref: 342b9213935
Ref: library/typing typing MutableSet9214213
Ref: 342c9214213
Ref: library/typing typing Sequence9214480
Ref: 34119214480
Ref: library/typing typing ValuesView9214761
Ref: 342d9214761
Ref: collections abc 对应的容器-Footnote-19215068
Ref: collections abc 对应的容器-Footnote-29215117
Ref: collections abc 对应的容器-Footnote-39215166
Ref: collections abc 对应的容器-Footnote-49215215
Ref: collections abc 对应的容器-Footnote-59215264
Ref: collections abc 对应的容器-Footnote-69215313
Ref: collections abc 对应的容器-Footnote-79215362
Ref: collections abc 对应的容器-Footnote-89215411
Ref: collections abc 对应的容器-Footnote-99215460
Ref: collections abc 对应的容器-Footnote-109215509
Ref: collections abc 对应的容器-Footnote-119215559
Ref: collections abc 对应的容器-Footnote-129215609
Ref: collections abc 对应的容器-Footnote-139215659
Node: collections abc 对应的其他类型9215709
Ref: library/typing corresponding-to-other-types-in-collections-abc9215856
Ref: 342e9215856
Ref: library/typing typing Iterable9215954
Ref: 34129215954
Ref: library/typing typing Iterator9216213
Ref: 342f9216213
Ref: library/typing typing Generator9216473
Ref: 34309216473
Ref: library/typing typing Hashable9217714
Ref: 34319217714
Ref: library/typing typing Reversible9217800
Ref: 34329217800
Ref: library/typing typing Sized9218064
Ref: 34339218064
Ref: collections abc 对应的其他类型-Footnote-19218180
Ref: collections abc 对应的其他类型-Footnote-29218229
Ref: collections abc 对应的其他类型-Footnote-39218278
Ref: collections abc 对应的其他类型-Footnote-49218327
Node: 异步编程9218376
Ref: library/typing asynchronous-programming9218519
Ref: 34349218519
Ref: library/typing typing Coroutine9218562
Ref: ffb9218562
Ref: library/typing typing AsyncGenerator9219304
Ref: 34359219304
Ref: library/typing typing AsyncIterable9220661
Ref: 34369220661
Ref: library/typing typing AsyncIterator9220959
Ref: 34379220959
Ref: library/typing typing Awaitable9221263
Ref: 34389221263
Ref: 异步编程-Footnote-19221585
Ref: 异步编程-Footnote-29221634
Ref: 异步编程-Footnote-39221683
Ref: 异步编程-Footnote-49221732
Ref: 异步编程-Footnote-59221781
Node: 上下文管理器类型<2>9221830
Ref: library/typing context-manager-types9221927
Ref: 34399221927
Ref: library/typing typing ContextManager9221990
Ref: 62e9221990
Ref: library/typing typing AsyncContextManager9222324
Ref: 343a9222324
Ref: 上下文管理器类型<2>-Footnote-19222708
Ref: 上下文管理器类型<2>-Footnote-29222757
Node: 协议<3>9222806
Ref: library/typing protocols9222915
Ref: 343b9222915
Ref: library/typing typing SupportsAbs9223007
Ref: 343c9223007
Ref: library/typing typing SupportsBytes9223130
Ref: 343d9223130
Ref: library/typing typing SupportsComplex9223221
Ref: 343e9223221
Ref: library/typing typing SupportsFloat9223316
Ref: 340a9223316
Ref: library/typing typing SupportsIndex9223407
Ref: 36d9223407
Ref: library/typing typing SupportsInt9223522
Ref: 36c9223522
Ref: library/typing typing SupportsRound9223609
Ref: 343f9223609
Node: 函数与装饰器9223733
Ref: library/typing functions-and-decorators9223845
Ref: 34409223845
Ref: library/typing typing cast9223898
Ref: 34419223898
Ref: library/typing typing overload9224149
Ref: 34429224149
Ref: library/typing typing final9225212
Ref: 3699225212
Ref: library/typing typing no_type_check9225822
Ref: 34439225822
Ref: library/typing typing no_type_check_decorator9226128
Ref: 34449226128
Ref: library/typing typing type_check_only9226355
Ref: 34459226355
Ref: 函数与装饰器-Footnote-19226958
Ref: 函数与装饰器-Footnote-29227007
Node: 内省辅助器9227056
Ref: library/typing introspection-helpers9227168
Ref: 34469227168
Ref: library/typing typing get_type_hints9227216
Ref: 1ef9227216
Ref: library/typing typing get_args9228470
Ref: 27d9228470
Ref: library/typing typing get_origin9228504
Ref: 36e9228504
Ref: library/typing typing ForwardRef9229390
Ref: f709229390
Ref: 内省辅助器-Footnote-19229943
Ref: 内省辅助器-Footnote-29229992
Node: 常量<4>9230041
Ref: library/typing constant9230126
Ref: 34479230126
Ref: library/typing typing TYPE_CHECKING9230159
Ref: 69b9230159
Ref: 常量<4>-Footnote-19231125
Node: pydoc --- 文档生成器和在线帮助系统9231174
Ref: library/pydoc doc9231335
Ref: 34489231335
Ref: library/pydoc module-pydoc9231335
Ref: d99231335
Ref: library/pydoc pydoc-documentation-generator-and-online-help-system9231335
Ref: 34499231335
Ref: pydoc --- 文档生成器和在线帮助系统-Footnote-19235775
Node: Python 开发模式9235839
Ref: library/devmode doc9235999
Ref: 344b9235999
Ref: library/devmode devmode9235999
Ref: 1609235999
Ref: library/devmode python-development-mode9235999
Ref: 344c9235999
Node: Python 开发模式的效果9236450
Ref: library/devmode effects-of-the-python-development-mode9236586
Ref: 344d9236586
Node: ResourceWarning 示例9239835
Ref: library/devmode resourcewarning-example9239979
Ref: 344e9239979
Node: 文件描述符错误示例9241823
Ref: library/devmode bad-file-descriptor-error-example9241981
Ref: 344f9241981
Ref: 文件描述符错误示例-Footnote-19243489
Node: doctest --- 测试交互性的Python示例9243532
Ref: library/doctest doc9243699
Ref: 34509243699
Ref: library/doctest doctest-test-interactive-python-examples9243699
Ref: 34519243699
Ref: library/doctest module-doctest9243699
Ref: 669243699
Ref: doctest --- 测试交互性的Python示例-Footnote-19247588
Node: 简单用法：检查Docstrings中的示例9247654
Ref: library/doctest doctest-simple-testmod9247833
Ref: 34529247833
Ref: library/doctest simple-usage-checking-examples-in-docstrings9247833
Ref: 34539247833
Node: 简单的用法：检查文本文件中的例子9249574
Ref: library/doctest doctest-simple-testfile9249783
Ref: 34559249783
Ref: library/doctest simple-usage-checking-examples-in-a-text-file9249783
Ref: 34569249783
Node: 它是如何工作的9252014
Ref: library/doctest doctest-how-it-works9252189
Ref: 34589252189
Ref: library/doctest how-it-works9252189
Ref: 34599252189
Node: 哪些文件串被检查了？9252791
Ref: library/doctest doctest-which-docstrings9252930
Ref: 345a9252930
Ref: library/doctest which-docstrings-are-examined9252930
Ref: 345b9252930
Node: 文档串的例子是如何被识别的？9253808
Ref: library/doctest doctest-finding-examples9253980
Ref: 345c9253980
Ref: library/doctest how-are-docstring-examples-recognized9253980
Ref: 345d9253980
Node: 什么是执行上下文9256858
Ref: library/doctest doctest-execution-context9257021
Ref: 34619257021
Ref: library/doctest what-s-the-execution-context9257021
Ref: 34629257021
Node: 异常如何处理？9257727
Ref: library/doctest doctest-exceptions9257860
Ref: 34639257860
Ref: library/doctest what-about-exceptions9257860
Ref: 34649257860
Ref: library/doctest option-flags-and-directives9261875
Ref: 34669261875
Ref: 异常如何处理？-Footnote-19261912
Node: 选项标记9262103
Ref: library/doctest doctest-options9262218
Ref: 9299262218
Ref: library/doctest option-flags9262218
Ref: 34679262218
Ref: library/doctest doctest DONT_ACCEPT_TRUE_FOR_19262761
Ref: 34689262761
Ref: library/doctest doctest DONT_ACCEPT_BLANKLINE9263352
Ref: 34699263352
Ref: library/doctest doctest NORMALIZE_WHITESPACE9263765
Ref: 345e9263765
Ref: library/doctest doctest ELLIPSIS9264171
Ref: e969264171
Ref: library/doctest doctest IGNORE_EXCEPTION_DETAIL9264531
Ref: 34659264531
Ref: library/doctest doctest SKIP9266384
Ref: 346a9266384
Ref: library/doctest doctest COMPARISON_FLAGS9266798
Ref: 346b9266798
Ref: library/doctest doctest REPORT_UDIFF9266960
Ref: e979266960
Ref: library/doctest doctest REPORT_CDIFF9267092
Ref: e989267092
Ref: library/doctest doctest REPORT_NDIFF9267224
Ref: e999267224
Ref: library/doctest doctest REPORT_ONLY_FIRST_FAILURE9267633
Ref: 346c9267633
Ref: library/doctest doctest FAIL_FAST9268116
Ref: 92a9268116
Ref: library/doctest doctest REPORTING_FLAGS9268523
Ref: 346d9268523
Ref: library/doctest doctest register_optionflag9268783
Ref: 346e9268783
Node: 指令9269217
Ref: library/doctest directives9269320
Ref: 34719269320
Ref: library/doctest doctest-directives9269320
Ref: 345f9269320
Ref: library/doctest grammar-token-directive9269503
Ref: 34729269503
Ref: library/doctest grammar-token-directive-options9269567
Ref: 34739269567
Ref: library/doctest grammar-token-directive-option9269640
Ref: 34749269640
Ref: library/doctest grammar-token-on-or-off9269703
Ref: 34759269703
Ref: library/doctest grammar-token-directive-option-name9269745
Ref: 34769269745
Node: 警告<2>9271558
Ref: library/doctest doctest-warnings9271640
Ref: 34779271640
Ref: library/doctest warnings9271640
Ref: 34789271640
Node: 基本API9273437
Ref: library/doctest basic-api9273576
Ref: 34799273576
Ref: library/doctest doctest-basic-api9273576
Ref: 34549273576
Ref: library/doctest doctest testfile9273953
Ref: 34579273953
Ref: library/doctest doctest testmod9277896
Ref: e959277896
Ref: library/doctest doctest run_docstring_examples9279586
Ref: 347b9279586
Node: Unittest API9280501
Ref: library/doctest doctest-unittest-api9280629
Ref: 347c9280629
Ref: library/doctest unittest-api9280629
Ref: 347d9280629
Ref: library/doctest doctest DocFileSuite9281271
Ref: 347e9281271
Ref: library/doctest doctest DocTestSuite9284836
Ref: 7c09284836
Ref: library/doctest doctest set_unittest_reportflags9287903
Ref: 34809287903
Node: 高级 API9288990
Ref: library/doctest advanced-api9289115
Ref: 34819289115
Ref: library/doctest doctest-advanced-api9289115
Ref: 34829289115
Node: DocTest 对象9291127
Ref: library/doctest doctest-doctest9291211
Ref: 34849291211
Ref: library/doctest doctest-objects9291211
Ref: 34859291211
Ref: library/doctest doctest DocTest9291260
Ref: 347f9291260
Ref: library/doctest doctest DocTest examples9291608
Ref: 34869291608
Ref: library/doctest doctest DocTest globs9291775
Ref: 34879291775
Ref: library/doctest doctest DocTest name9292060
Ref: 34889292060
Ref: library/doctest doctest DocTest filename9292228
Ref: 34899292228
Ref: library/doctest doctest DocTest lineno9292437
Ref: 348a9292437
Ref: library/doctest doctest DocTest docstring9292680
Ref: 348b9292680
Node: Example 对象9292863
Ref: library/doctest doctest-example9292976
Ref: 348c9292976
Ref: library/doctest example-objects9292976
Ref: 348d9292976
Ref: library/doctest doctest Example9293025
Ref: 34839293025
Ref: library/doctest doctest Example source9293394
Ref: 348e9293394
Ref: library/doctest doctest Example want9293598
Ref: 348f9293598
Ref: library/doctest doctest Example exc_msg9293940
Ref: 34909293940
Ref: library/doctest doctest Example lineno9294313
Ref: 34929294313
Ref: library/doctest doctest Example indent9294494
Ref: 34939294494
Ref: library/doctest doctest Example options9294641
Ref: 34949294641
Node: DocTestFinder 对象9295007
Ref: library/doctest doctest-doctestfinder9295126
Ref: 34959295126
Ref: library/doctest doctestfinder-objects9295126
Ref: 34969295126
Ref: library/doctest doctest DocTestFinder9295187
Ref: 347a9295187
Ref: library/doctest doctest DocTestFinder find9296250
Ref: 34979296250
Node: DocTestParser 对象9298141
Ref: library/doctest doctest-doctestparser9298266
Ref: 34989298266
Ref: library/doctest doctestparser-objects9298266
Ref: 34999298266
Ref: library/doctest doctest DocTestParser9298327
Ref: 34609298327
Ref: library/doctest doctest DocTestParser get_doctest9298566
Ref: 349a9298566
Ref: library/doctest doctest DocTestParser get_examples9298963
Ref: 349b9298963
Ref: library/doctest doctest DocTestParser parse9299459
Ref: 349c9299459
Node: DocTestRunner 对象9300003
Ref: library/doctest doctest-doctestrunner9300128
Ref: 349d9300128
Ref: library/doctest doctestrunner-objects9300128
Ref: 349e9300128
Ref: library/doctest doctest DocTestRunner9300189
Ref: 34709300189
Ref: library/doctest doctest DocTestRunner report_start9303302
Ref: 349f9303302
Ref: library/doctest doctest DocTestRunner report_success9303740
Ref: 34a09303740
Ref: library/doctest doctest DocTestRunner report_failure9304225
Ref: 34a29304225
Ref: library/doctest doctest DocTestRunner report_unexpected_exception9304710
Ref: 34a19304710
Ref: library/doctest doctest DocTestRunner run9305315
Ref: 34a39305315
Ref: library/doctest doctest DocTestRunner summarize9306271
Ref: 34a49306271
Node: OutputChecker 对象9306658
Ref: library/doctest doctest-outputchecker9306754
Ref: 34a59306754
Ref: library/doctest outputchecker-objects9306754
Ref: 34a69306754
Ref: library/doctest doctest OutputChecker9306815
Ref: 346f9306815
Ref: library/doctest doctest OutputChecker check_output9307265
Ref: 34a79307265
Ref: library/doctest doctest OutputChecker output_difference9307724
Ref: 34a89307724
Node: 调试9308016
Ref: library/doctest debugging9308138
Ref: 34a99308138
Ref: library/doctest doctest-debugging9308138
Ref: 34aa9308138
Ref: library/doctest doctest script_from_examples9310142
Ref: 34ad9310142
Ref: library/doctest doctest testsource9311080
Ref: 34ae9311080
Ref: library/doctest doctest debug9311825
Ref: 34ac9311825
Ref: library/doctest doctest debug_src9312809
Ref: 34b09312809
Ref: library/doctest doctest DebugRunner9313629
Ref: 34ab9313629
Ref: library/doctest doctest DocTestFailure9314303
Ref: 34b29314303
Ref: library/doctest doctest DocTestFailure test9314599
Ref: 34b39314599
Ref: library/doctest doctest DocTestFailure example9314706
Ref: 34b49314706
Ref: library/doctest doctest DocTestFailure got9314783
Ref: 34b59314783
Ref: library/doctest doctest UnexpectedException9314846
Ref: 34b19314846
Ref: library/doctest doctest UnexpectedException test9315162
Ref: 34b69315162
Ref: library/doctest doctest UnexpectedException example9315274
Ref: 34b79315274
Ref: library/doctest doctest UnexpectedException exc_info9315356
Ref: 34b89315356
Node: 肥皂盒9315480
Ref: library/doctest doctest-soapbox9315583
Ref: 34b99315583
Ref: library/doctest soapbox9315583
Ref: 34ba9315583
Node: unittest --- 單元測試框架9319194
Ref: library/unittest doc9319365
Ref: 34bb9319365
Ref: library/unittest module-unittest9319365
Ref: 1249319365
Ref: library/unittest unittest-unit-testing-framework9319365
Ref: 34bc9319365
Ref: unittest --- 單元測試框架-Footnote-19322490
Ref: unittest --- 單元測試框架-Footnote-29322567
Ref: unittest --- 單元測試框架-Footnote-39322660
Ref: unittest --- 單元測試框架-Footnote-49322693
Ref: unittest --- 單元測試框架-Footnote-59322757
Ref: unittest --- 單元測試框架-Footnote-69322815
Ref: unittest --- 單元測試框架-Footnote-79322845
Ref: unittest --- 單元測試框架-Footnote-89322873
Ref: unittest --- 單元測試框架-Footnote-99322903
Node: 簡單範例9322937
Ref: library/unittest basic-example9323070
Ref: 34be9323070
Ref: library/unittest unittest-minimal-example9323070
Ref: 34bf9323070
Node: 命令執行列介面 Command-Line Interface9325743
Ref: library/unittest command-line-interface9325917
Ref: 34c19325917
Ref: library/unittest unittest-command-line-interface9325917
Ref: 34c29325917
Node: 命令列模式選項9327308
Ref: library/unittest command-line-options9327410
Ref: 34c49327410
Ref: library/unittest cmdoption-unittest-b9327519
Ref: d8b9327519
Ref: library/unittest cmdoption-unittest-c9327797
Ref: d8c9327797
Ref: library/unittest cmdoption-unittest-f9328105
Ref: d8e9328105
Ref: library/unittest cmdoption-unittest-k9328197
Ref: 34c69328197
Ref: library/unittest cmdoption-unittest-locals9328858
Ref: 34c79328858
Node: Test Discovery（測試探索）9329227
Ref: library/unittest test-discovery9329413
Ref: 34c89329413
Ref: library/unittest unittest-test-discovery9329413
Ref: 34c39329413
Ref: library/unittest cmdoption-unittest-discover-v9330341
Ref: 34c99330341
Ref: library/unittest cmdoption-unittest-discover-s9330406
Ref: 34ca9330406
Ref: library/unittest cmdoption-unittest-discover-p9330511
Ref: 34cb9330511
Ref: library/unittest cmdoption-unittest-discover-t9330616
Ref: 34cc9330616
Node: 组织你的测试代码9332153
Ref: library/unittest organizing-test-code9332322
Ref: 34ce9332322
Ref: library/unittest organizing-tests9332322
Ref: 34c09332322
Node: 复用已有的测试代码9336821
Ref: library/unittest legacy-unit-tests9336988
Ref: 34d09336988
Ref: library/unittest re-using-old-test-code9336988
Ref: 34d19336988
Node: 跳过测试与预计的失败9338376
Ref: library/unittest skipping-tests-and-expected-failures9338564
Ref: 34d29338564
Ref: library/unittest unittest-skipping9338564
Ref: 34d39338564
Ref: library/unittest unittest skip9341600
Ref: 10e59341600
Ref: library/unittest unittest skipIf9341723
Ref: 34d69341723
Ref: library/unittest unittest skipUnless9341835
Ref: 34d79341835
Ref: library/unittest unittest expectedFailure9341951
Ref: 34d59341951
Ref: library/unittest unittest SkipTest9342258
Ref: 9e99342258
Node: Distinguishing test iterations using subtests9342796
Ref: library/unittest distinguishing-test-iterations-using-subtests9342969
Ref: 34d89342969
Ref: library/unittest subtests9342969
Ref: 9e79342969
Node: 类与函数9345213
Ref: library/unittest classes-and-functions9345381
Ref: 34d99345381
Ref: library/unittest unittest-contents9345381
Ref: 34da9345381
Node: 测试用例9345553
Ref: library/unittest test-cases9345637
Ref: 34db9345637
Ref: library/unittest testcase-objects9345637
Ref: 34dc9345637
Ref: library/unittest unittest TestCase9345680
Ref: 9e59345680
Ref: library/unittest unittest TestCase setUp9346992
Ref: d939346992
Ref: library/unittest unittest TestCase tearDown9347375
Ref: d949347375
Ref: library/unittest unittest TestCase setUpClass9348154
Ref: 3769348154
Ref: library/unittest unittest TestCase tearDownClass9348610
Ref: d919348610
Ref: library/unittest unittest TestCase run9349075
Ref: b969349075
Ref: library/unittest unittest TestCase skipTest9349699
Ref: 34d49349699
Ref: library/unittest unittest TestCase subTest9349953
Ref: 9e69349953
Ref: library/unittest unittest TestCase debug9350521
Ref: f6e9350521
Ref: library/unittest assert-methods9350762
Ref: 34bd9350762
Ref: library/unittest unittest TestCase assertEqual9354609
Ref: c859354609
Ref: library/unittest unittest TestCase assertNotEqual9355457
Ref: c869355457
Ref: library/unittest unittest TestCase assertTrue9355642
Ref: c849355642
Ref: library/unittest unittest TestCase assertFalse9355693
Ref: d8f9355693
Ref: library/unittest unittest TestCase assertIs9356200
Ref: d979356200
Ref: library/unittest unittest TestCase assertIsNot9356258
Ref: d989356258
Ref: library/unittest unittest TestCase assertIsNone9356435
Ref: d959356435
Ref: library/unittest unittest TestCase assertIsNotNone9356488
Ref: d969356488
Ref: library/unittest unittest TestCase assertIn9356629
Ref: da09356629
Ref: library/unittest unittest TestCase assertNotIn9356691
Ref: da19356691
Ref: library/unittest unittest TestCase assertIsInstance9356847
Ref: d999356847
Ref: library/unittest unittest TestCase assertNotIsInstance9356908
Ref: d9a9356908
Ref: library/unittest unittest TestCase assertRaises9359585
Ref: b929359585
Ref: library/unittest unittest TestCase assertRaisesRegex9361297
Ref: b939361297
Ref: library/unittest unittest TestCase assertWarns9362287
Ref: b949362287
Ref: library/unittest unittest TestCase assertWarnsRegex9363999
Ref: b959363999
Ref: library/unittest unittest TestCase assertLogs9364941
Ref: 9eb9364941
Ref: library/unittest unittest TestCase records9366000
Ref: 34e09366000
Ref: library/unittest unittest TestCase output9366140
Ref: 34e19366140
Ref: library/unittest unittest TestCase assertAlmostEqual9369459
Ref: c879369459
Ref: library/unittest unittest TestCase assertNotAlmostEqual9369563
Ref: c889369563
Ref: library/unittest unittest TestCase assertGreater9370621
Ref: d9b9370621
Ref: library/unittest unittest TestCase assertGreaterEqual9370684
Ref: d9c9370684
Ref: library/unittest unittest TestCase assertLess9370752
Ref: d9d9370752
Ref: library/unittest unittest TestCase assertLessEqual9370812
Ref: d9e9370812
Ref: library/unittest unittest TestCase assertRegex9371181
Ref: c819371181
Ref: library/unittest unittest TestCase assertNotRegex9371240
Ref: 34e29371240
Ref: library/unittest unittest TestCase assertCountEqual9372017
Ref: c7f9372017
Ref: library/unittest type-specific-methods9372682
Ref: 34df9372682
Ref: library/unittest unittest TestCase addTypeEqualityFunc9373000
Ref: da99373000
Ref: library/unittest unittest TestCase assertMultiLineEqual9375711
Ref: d9f9375711
Ref: library/unittest unittest TestCase assertSequenceEqual9376130
Ref: da59376130
Ref: library/unittest unittest TestCase assertListEqual9376759
Ref: da39376759
Ref: library/unittest unittest TestCase assertTupleEqual9376824
Ref: da49376824
Ref: library/unittest unittest TestCase assertSetEqual9377276
Ref: da29377276
Ref: library/unittest unittest TestCase assertDictEqual9377732
Ref: da69377732
Ref: library/unittest other-methods-and-attrs9378094
Ref: 34e49378094
Ref: library/unittest unittest TestCase fail9378185
Ref: 34e59378185
Ref: library/unittest unittest TestCase failureException9378334
Ref: 34e39378334
Ref: library/unittest unittest TestCase longMessage9378742
Ref: d909378742
Ref: library/unittest unittest TestCase maxDiff9379475
Ref: c809379475
Ref: library/unittest unittest TestCase countTestCases9380151
Ref: 34e69380151
Ref: library/unittest unittest TestCase defaultTestResult9380339
Ref: 34de9380339
Ref: library/unittest unittest TestCase id9380775
Ref: 34e79380775
Ref: library/unittest unittest TestCase shortDescription9380976
Ref: 34e89380976
Ref: library/unittest unittest TestCase addCleanup9381591
Ref: 3c59381591
Ref: library/unittest unittest TestCase doCleanups9382198
Ref: d929382198
Ref: library/unittest unittest TestCase addClassCleanup9382840
Ref: 3759382840
Ref: library/unittest unittest TestCase doClassCleanups9383516
Ref: 34e99383516
Ref: library/unittest unittest IsolatedAsyncioTestCase9384222
Ref: 3779384222
Ref: library/unittest unittest IsolatedAsyncioTestCase asyncSetUp9384432
Ref: 34ea9384432
Ref: library/unittest unittest IsolatedAsyncioTestCase asyncTearDown9384877
Ref: 34eb9384877
Ref: library/unittest unittest IsolatedAsyncioTestCase addAsyncCleanup9385728
Ref: 34ec9385728
Ref: library/unittest unittest IsolatedAsyncioTestCase run9385892
Ref: 34ed9385892
Ref: library/unittest unittest FunctionTestCase9387635
Ref: 34cf9387635
Node: Deprecated aliases9388147
Ref: library/unittest deprecated-aliases9388214
Ref: c899388214
Ref: library/unittest id19388214
Ref: 34ee9388214
Node: Grouping tests9391310
Ref: library/unittest grouping-tests9391428
Ref: 34ef9391428
Ref: library/unittest testsuite-objects9391428
Ref: 34f09391428
Ref: library/unittest unittest TestSuite9391479
Ref: 7c19391479
Ref: library/unittest unittest TestSuite addTest9392427
Ref: 34f19392427
Ref: library/unittest unittest TestSuite addTests9392553
Ref: 34f29392553
Ref: library/unittest unittest TestSuite run9392935
Ref: 34f39392935
Ref: library/unittest unittest TestSuite debug9393243
Ref: 34f49393243
Ref: library/unittest unittest TestSuite countTestCases9393522
Ref: 34f59393522
Ref: library/unittest unittest TestSuite __iter__9393692
Ref: a439393692
Node: Loading and running tests9395136
Ref: library/unittest loading-and-running-tests9395233
Ref: 34f69395233
Ref: library/unittest unittest TestLoader9395306
Ref: 8719395306
Ref: library/unittest unittest TestLoader errors9395801
Ref: 8709395801
Ref: library/unittest unittest TestLoader loadTestsFromTestCase9396265
Ref: 34f89396265
Ref: library/unittest unittest TestLoader loadTestsFromModule9396822
Ref: 86f9396822
Ref: library/unittest unittest TestLoader loadTestsFromName9398317
Ref: da79398317
Ref: library/unittest unittest TestLoader loadTestsFromNames9400102
Ref: 34fa9400102
Ref: library/unittest unittest TestLoader getTestCaseNames9400393
Ref: 34f99400393
Ref: library/unittest unittest TestLoader discover9400602
Ref: 9ea9400602
Ref: library/unittest unittest TestLoader testMethodPrefix9403426
Ref: 34fb9403426
Ref: library/unittest unittest TestLoader sortTestMethodsUsing9403712
Ref: 34fc9403712
Ref: library/unittest unittest TestLoader suiteClass9403923
Ref: da89403923
Ref: library/unittest unittest TestLoader testNamePatterns9404217
Ref: 34fd9404217
Ref: library/unittest unittest TestResult9404926
Ref: b979404926
Ref: library/unittest unittest TestResult errors9405789
Ref: 34fe9405789
Ref: library/unittest unittest TestResult failures9406016
Ref: 34ff9406016
Ref: library/unittest unittest TestResult skipped9406302
Ref: 35009406302
Ref: library/unittest unittest TestResult expectedFailures9406493
Ref: 35019406493
Ref: library/unittest unittest TestResult unexpectedSuccesses9406732
Ref: 35029406732
Ref: library/unittest unittest TestResult shouldStop9406894
Ref: 35039406894
Ref: library/unittest unittest TestResult testsRun9407025
Ref: 35059407025
Ref: library/unittest unittest TestResult buffer9407101
Ref: 35069407101
Ref: library/unittest unittest TestResult failfast9407545
Ref: 35099407545
Ref: library/unittest unittest TestResult tb_locals9407725
Ref: 350a9407725
Ref: library/unittest unittest TestResult wasSuccessful9407868
Ref: 350b9407868
Ref: library/unittest unittest TestResult stop9408202
Ref: 35049408202
Ref: library/unittest unittest TestResult startTest9409156
Ref: 35079409156
Ref: library/unittest unittest TestResult stopTest9409261
Ref: 35089409261
Ref: library/unittest unittest TestResult startTestRun9409402
Ref: dab9409402
Ref: library/unittest unittest TestResult stopTestRun9409525
Ref: dac9409525
Ref: library/unittest unittest TestResult addError9409646
Ref: 350c9409646
Ref: library/unittest unittest TestResult addFailure9410119
Ref: 350d9410119
Ref: library/unittest unittest TestResult addSuccess9410583
Ref: 350e9410583
Ref: library/unittest unittest TestResult addSkip9410731
Ref: 350f9410731
Ref: library/unittest unittest TestResult addExpectedFailure9411033
Ref: 35109411033
Ref: library/unittest unittest TestResult addUnexpectedSuccess9411465
Ref: 35119411465
Ref: library/unittest unittest TestResult addSubTest9411777
Ref: 35129411777
Ref: library/unittest unittest TextTestResult9412453
Ref: f519412453
Ref: library/unittest unittest defaultTestLoader9412767
Ref: 34f79412767
Ref: library/unittest unittest TextTestRunner9413022
Ref: f529413022
Ref: library/unittest unittest TextTestRunner _makeResult9414598
Ref: 35149414598
Ref: library/unittest unittest TextTestRunner run9415255
Ref: 35159415255
Ref: library/unittest unittest main9415622
Ref: 9e89415622
Node: load_tests Protocol9418462
Ref: library/unittest load-tests-protocol9418543
Ref: 34cd9418543
Node: Class and Module Fixtures9421204
Ref: library/unittest class-and-module-fixtures9421339
Ref: 34dd9421339
Node: setUpClass and tearDownClass9423227
Ref: library/unittest setupclass-and-teardownclass9423356
Ref: 35169423356
Node: setUpModule and tearDownModule9424270
Ref: library/unittest setupmodule-and-teardownmodule9424399
Ref: 35179424399
Ref: library/unittest unittest addModuleCleanup9425012
Ref: 3749425012
Ref: library/unittest unittest doModuleCleanups9425586
Ref: 35189425586
Node: 信号处理9426195
Ref: library/unittest signal-handling9426309
Ref: 34c59426309
Ref: library/unittest unittest installHandler9427531
Ref: 35199427531
Ref: library/unittest unittest registerResult9427774
Ref: 351a9427774
Ref: library/unittest unittest removeResult9428266
Ref: 351b9428266
Ref: library/unittest unittest removeHandler9428486
Ref: d8d9428486
Node: unittest mock --- mock对象库9428874
Ref: library/unittest mock doc9429029
Ref: 351c9429029
Ref: library/unittest mock module-unittest mock9429029
Ref: 1259429029
Ref: library/unittest mock unittest-mock-mock-object-library9429029
Ref: 351d9429029
Ref: unittest mock --- mock对象库-Footnote-19430376
Ref: unittest mock --- mock对象库-Footnote-29430448
Node: 快速上手9430486
Ref: library/unittest mock quick-guide9430583
Ref: 351e9430583
Node: Mock 类9435480
Ref: library/unittest mock the-mock-class9435598
Ref: 35229435598
Ref: library/unittest mock unittest mock Mock9436428
Ref: 3739436428
Ref: library/unittest mock unittest mock Mock assert_called9439451
Ref: 69f9439451
Ref: library/unittest mock unittest mock Mock assert_called_once9439732
Ref: 6a09439732
Ref: library/unittest mock unittest mock Mock assert_called_with9440314
Ref: 113a9440314
Ref: library/unittest mock unittest mock Mock assert_called_once_with9440674
Ref: 35299440674
Ref: library/unittest mock unittest mock Mock assert_any_call9441284
Ref: 352a9441284
Ref: library/unittest mock unittest mock Mock assert_has_calls9441931
Ref: 352b9441931
Ref: library/unittest mock unittest mock Mock assert_not_called9442782
Ref: 8739442782
Ref: library/unittest mock unittest mock Mock reset_mock9443221
Ref: 6a19443221
Ref: library/unittest mock unittest mock Mock mock_add_spec9444356
Ref: 352d9444356
Ref: library/unittest mock unittest mock Mock attach_mock9444687
Ref: 352e9444687
Ref: library/unittest mock unittest mock Mock configure_mock9444986
Ref: 35289444986
Ref: library/unittest mock unittest mock Mock __dir__9446226
Ref: 35309446226
Ref: library/unittest mock unittest mock Mock _get_child_mock9446565
Ref: 35329446565
Ref: library/unittest mock unittest mock Mock called9446971
Ref: 35339446971
Ref: library/unittest mock unittest mock Mock call_count9447268
Ref: 35349447268
Ref: library/unittest mock unittest mock Mock return_value9447596
Ref: 35279447596
Ref: library/unittest mock unittest mock Mock side_effect9448399
Ref: 35259448399
Ref: library/unittest mock unittest mock Mock call_args9450866
Ref: 106a9450866
Ref: library/unittest mock unittest mock Mock call_args_list9452681
Ref: 35359452681
Ref: library/unittest mock unittest mock Mock method_calls9453721
Ref: 352f9453721
Ref: library/unittest mock unittest mock Mock mock_calls9454456
Ref: 352c9454456
Ref: library/unittest mock unittest mock Mock __class__9455993
Ref: 35379455993
Ref: library/unittest mock unittest mock NonCallableMock9456763
Ref: 35239456763
Ref: library/unittest mock unittest mock PropertyMock9459283
Ref: 35389459283
Ref: library/unittest mock unittest mock AsyncMock9460658
Ref: 3729460658
Ref: library/unittest mock unittest mock AsyncMock assert_awaited9463518
Ref: 35399463518
Ref: library/unittest mock unittest mock AsyncMock assert_awaited_once9464259
Ref: 353a9464259
Ref: library/unittest mock unittest mock AsyncMock assert_awaited_with9464830
Ref: 353b9464830
Ref: library/unittest mock unittest mock AsyncMock assert_awaited_once_with9465505
Ref: 353c9465505
Ref: library/unittest mock unittest mock AsyncMock assert_any_await9466236
Ref: 353d9466236
Ref: library/unittest mock unittest mock AsyncMock assert_has_awaits9466885
Ref: 353e9466885
Ref: library/unittest mock unittest mock AsyncMock assert_not_awaited9467986
Ref: 353f9467986
Ref: library/unittest mock unittest mock AsyncMock reset_mock9468167
Ref: 35409468167
Ref: library/unittest mock unittest mock AsyncMock await_count9468404
Ref: 35419468404
Ref: library/unittest mock unittest mock AsyncMock await_args9468847
Ref: 35429468847
Ref: library/unittest mock unittest mock AsyncMock await_args_list9469463
Ref: 10699469463
Ref: Mock 类-Footnote-19470326
Node: Calling9470752
Ref: library/unittest mock calling9470832
Ref: 35439470832
Node: Deleting Attributes9474074
Ref: library/unittest mock deleting-attributes9474196
Ref: 35449474196
Ref: library/unittest mock id29474196
Ref: 35459474196
Node: Mock names and the name attribute9474969
Ref: library/unittest mock mock-names-and-the-name-attribute9475113
Ref: 35469475113
Node: Attaching Mocks as Attributes9475691
Ref: library/unittest mock attaching-mocks-as-attributes9475807
Ref: 35479475807
Node: The patchers9477663
Ref: library/unittest mock the-patchers9477803
Ref: 35489477803
Node: patch9478418
Ref: library/unittest mock patch9478493
Ref: 35499478493
Ref: library/unittest mock unittest mock patch9478642
Ref: 8779478642
Node: patch object9487536
Ref: library/unittest mock patch-object9487630
Ref: 354b9487630
Ref: library/unittest mock unittest mock patch object9487675
Ref: 10b49487675
Node: patch dict9489152
Ref: library/unittest mock patch-dict9489255
Ref: 354c9489255
Ref: library/unittest mock unittest mock patch dict9489298
Ref: 110a9489298
Node: patch multiple9493407
Ref: library/unittest mock patch-multiple9493526
Ref: 354e9493526
Ref: library/unittest mock unittest mock patch multiple9493577
Ref: 354f9493577
Node: patch methods start and stop9496283
Ref: library/unittest mock patch-methods-start-and-stop9496406
Ref: 35509496406
Ref: library/unittest mock start-and-stop9496406
Ref: 35519496406
Ref: library/unittest mock unittest mock patch stopall9499138
Ref: 35529499138
Node: patch builtins9499245
Ref: library/unittest mock id49499365
Ref: 35539499365
Ref: library/unittest mock patch-builtins9499365
Ref: 35549499365
Node: TEST_PREFIX9499686
Ref: library/unittest mock id59499802
Ref: 35559499802
Ref: library/unittest mock test-prefix9499802
Ref: 354d9499802
Node: Nesting Patch Decorators9500685
Ref: library/unittest mock nesting-patch-decorators9500801
Ref: 35569500801
Node: Where to patch9501718
Ref: library/unittest mock id69501861
Ref: 354a9501861
Ref: library/unittest mock where-to-patch9501861
Ref: 351f9501861
Node: Patching Descriptors and Proxy Objects9503627
Ref: library/unittest mock patching-descriptors-and-proxy-objects9503737
Ref: 35579503737
Ref: Patching Descriptors and Proxy Objects-Footnote-19504178
Node: MagicMock and magic method support9504260
Ref: library/unittest mock magicmock-and-magic-method-support9504399
Ref: 35589504399
Node: Mocking Magic Methods9504541
Ref: library/unittest mock magic-methods9504652
Ref: 35209504652
Ref: library/unittest mock mocking-magic-methods9504652
Ref: 35599504652
Ref: Mocking Magic Methods-Footnote-19508530
Ref: Mocking Magic Methods-Footnote-29508773
Node: Magic Mock9508898
Ref: library/unittest mock magic-mock9509009
Ref: 355a9509009
Ref: library/unittest mock unittest mock MagicMock9509153
Ref: 8749509153
Ref: library/unittest mock unittest mock NonCallableMagicMock9509621
Ref: 35249509621
Node: Helpers9512987
Ref: library/unittest mock helpers9513105
Ref: 355b9513105
Node: sentinel9513278
Ref: library/unittest mock sentinel9513346
Ref: 355c9513346
Ref: library/unittest mock unittest mock sentinel9513385
Ref: 50e9513385
Node: DEFAULT9514532
Ref: library/unittest mock default9514613
Ref: 355d9514613
Ref: library/unittest mock unittest mock DEFAULT9514650
Ref: 35269514650
Node: call9514903
Ref: library/unittest mock call9514991
Ref: 355e9514991
Ref: library/unittest mock unittest mock call9515022
Ref: 10cc9515022
Ref: library/unittest mock unittest mock call call_list9515561
Ref: 355f9515561
Ref: library/unittest mock calls-as-tuples9516515
Ref: 35369516515
Node: create_autospec9518137
Ref: library/unittest mock create-autospec9518221
Ref: 35609518221
Ref: library/unittest mock unittest mock create_autospec9518274
Ref: 10879518274
Node: ANY9519563
Ref: library/unittest mock any9519653
Ref: 35619519653
Ref: library/unittest mock unittest mock ANY9519682
Ref: 10d19519682
Node: FILTER_DIR9520564
Ref: library/unittest mock filter-dir9520648
Ref: 35629520648
Ref: library/unittest mock unittest mock FILTER_DIR9520691
Ref: 35319520691
Node: mock_open9522744
Ref: library/unittest mock mock-open9522837
Ref: 35639522837
Ref: library/unittest mock unittest mock mock_open9522878
Ref: 11029522878
Ref: mock_open-Footnote-19525661
Node: Autospeccing9525686
Ref: library/unittest mock auto-speccing9525782
Ref: 35219525782
Ref: library/unittest mock autospeccing9525782
Ref: 35649525782
Ref: Autospeccing-Footnote-19535284
Node: Sealing mocks9535529
Ref: library/unittest mock sealing-mocks9535607
Ref: 35659535607
Ref: library/unittest mock unittest mock seal9535656
Ref: 50f9535656
Node: unittest mock 上手指南9536464
Ref: library/unittest mock-examples doc9536640
Ref: 35669536640
Ref: library/unittest mock-examples unittest-mock-getting-started9536640
Ref: 35679536640
Ref: library/unittest mock-examples getting-started9536734
Ref: 35689536734
Node: 使用 mock9536802
Ref: library/unittest mock-examples using-mock9536901
Ref: 35699536901
Node: 模拟方法调用9537314
Ref: library/unittest mock-examples mock-patching-methods9537421
Ref: 356a9537421
Node: 对象上的方法调用的 mock9538966
Ref: library/unittest mock-examples mock-for-method-calls-on-an-object9539097
Ref: 356b9539097
Node: Mocking Classes9540187
Ref: library/unittest mock-examples mocking-classes9540317
Ref: 356c9540317
Node: Naming your mocks9541312
Ref: library/unittest mock-examples naming-your-mocks9541428
Ref: 356d9541428
Node: Tracking all Calls9541862
Ref: library/unittest mock-examples tracking-all-calls9541999
Ref: 356e9541999
Node: Setting Return Values and Attributes9543408
Ref: library/unittest mock-examples setting-return-values-and-attributes9543557
Ref: 356f9543557
Node: Raising exceptions with mocks9545066
Ref: library/unittest mock-examples raising-exceptions-with-mocks9545232
Ref: 35709545232
Node: Side effect functions and iterables9545614
Ref: library/unittest mock-examples side-effect-functions-and-iterables9545774
Ref: 35719545774
Node: Mocking asynchronous iterators9546816
Ref: library/unittest mock-examples mocking-asynchronous-iterators9546983
Ref: 35729546983
Node: Mocking asynchronous context manager9547551
Ref: library/unittest mock-examples mocking-asynchronous-context-manager9547722
Ref: 35739547722
Node: Creating a Mock from an Existing Object9548621
Ref: library/unittest mock-examples creating-a-mock-from-an-existing-object9548753
Ref: 35749548753
Node: Patch Decorators9550565
Ref: library/unittest mock-examples patch-decorators9550689
Ref: 35759550689
Node: Further Examples9555894
Ref: library/unittest mock-examples further-examples9555998
Ref: 35769555998
Ref: library/unittest mock-examples id19555998
Ref: 35779555998
Node: Mocking chained calls9556628
Ref: library/unittest mock-examples mocking-chained-calls9556726
Ref: 35789556726
Node: Partial mocking9559839
Ref: library/unittest mock-examples partial-mocking9559972
Ref: 35799559972
Ref: Partial mocking-Footnote-19561982
Node: Mocking a Generator Method9562083
Ref: library/unittest mock-examples mocking-a-generator-method9562239
Ref: 357a9562239
Ref: Mocking a Generator Method-Footnote-19563367
Node: Applying the same patch to every test method9563691
Ref: library/unittest mock-examples applying-the-same-patch-to-every-test-method9563855
Ref: 357b9563855
Node: Mocking Unbound Methods9566171
Ref: library/unittest mock-examples mocking-unbound-methods9566342
Ref: 357c9566342
Node: Checking multiple calls with mock9568112
Ref: library/unittest mock-examples checking-multiple-calls-with-mock9568268
Ref: 357d9568268
Node: Coping with mutable arguments9569814
Ref: library/unittest mock-examples coping-with-mutable-arguments9569962
Ref: 357e9569962
Node: Nesting Patches9574124
Ref: library/unittest mock-examples nesting-patches9574274
Ref: 357f9574274
Node: Mocking a dictionary with MagicMock9576083
Ref: library/unittest mock-examples mocking-a-dictionary-with-magicmock9576240
Ref: 35809576240
Node: Mock subclasses and their attributes9578890
Ref: library/unittest mock-examples mock-subclasses-and-their-attributes9579063
Ref: 35819579063
Ref: Mock subclasses and their attributes-Footnote-19581197
Ref: Mock subclasses and their attributes-Footnote-29581370
Ref: Mock subclasses and their attributes-Footnote-39581428
Node: Mocking imports with patch dict9581515
Ref: library/unittest mock-examples mocking-imports-with-patch-dict9581709
Ref: 35829581709
Node: Tracking order of calls and less verbose call assertions9584355
Ref: library/unittest mock-examples tracking-order-of-calls-and-less-verbose-call-assertions9584543
Ref: 35839584543
Node: More complex argument matching9587884
Ref: library/unittest mock-examples more-complex-argument-matching9588032
Ref: 35849588032
Ref: More complex argument matching-Footnote-19591081
Ref: More complex argument matching-Footnote-29591124
Node: 2to3 - 自動將 Python 2的程式碼轉成 Python 39591246
Ref: library/2to3 doc9591421
Ref: 35859591421
Ref: library/2to3 to3-automated-python-2-to-3-code-translation9591421
Ref: 35869591421
Ref: library/2to3 to3-reference9591421
Ref: d3e9591421
Node: 使用 2to39591974
Ref: library/2to3 to3-using9592092
Ref: 35879592092
Ref: library/2to3 using-2to39592092
Ref: 35889592092
Node: 修复器9596374
Ref: library/2to3 fixers9596530
Ref: 358a9596530
Ref: library/2to3 to3-fixers9596530
Ref: 35899596530
Ref: library/2to3 2to3fixer-apply9596825
Ref: 358b9596825
Ref: library/2to3 2to3fixer-asserts9596999
Ref: 358c9596999
Ref: library/2to3 2to3fixer-basestring9599249
Ref: 358d9599249
Ref: library/2to3 2to3fixer-buffer9599332
Ref: 358e9599332
Ref: library/2to3 2to3fixer-dict9599533
Ref: 358f9599533
Ref: library/2to3 2to3fixer-except9600159
Ref: 35909600159
Ref: library/2to3 2to3fixer-exec9600243
Ref: 35919600243
Ref: library/2to3 2to3fixer-execfile9600336
Ref: 115b9600336
Ref: library/2to3 2to3fixer-exitfunc9600520
Ref: 35929600520
Ref: library/2to3 2to3fixer-filter9600632
Ref: 35939600632
Ref: library/2to3 2to3fixer-funcattrs9600729
Ref: 35949600729
Ref: library/2to3 2to3fixer-future9600893
Ref: 35959600893
Ref: library/2to3 2to3fixer-getcwdu9600980
Ref: 35969600980
Ref: library/2to3 2to3fixer-has_key9601074
Ref: 35979601074
Ref: library/2to3 2to3fixer-idioms9601163
Ref: 35989601163
Ref: library/2to3 2to3fixer-import9601720
Ref: 35999601720
Ref: library/2to3 2to3fixer-imports9601809
Ref: 359a9601809
Ref: library/2to3 2to3fixer-imports29601876
Ref: 359b9601876
Ref: library/2to3 2to3fixer-input9602053
Ref: 359c9602053
Ref: library/2to3 2to3fixer-intern9602144
Ref: 359d9602144
Ref: library/2to3 2to3fixer-isinstance9602230
Ref: 359e9602230
Ref: library/2to3 2to3fixer-itertools_imports9602528
Ref: 359f9602528
Ref: library/2to3 2to3fixer-itertools9602781
Ref: 35a09602781
Ref: library/2to3 2to3fixer-long9603034
Ref: 35a19603034
Ref: library/2to3 2to3fixer-map9603108
Ref: 35a29603108
Ref: library/2to3 2to3fixer-metaclass9603324
Ref: 35a39603324
Ref: library/2to3 2to3fixer-methodattrs9603481
Ref: 35a49603481
Ref: library/2to3 2to3fixer-ne9603610
Ref: 35a59603610
Ref: library/2to3 2to3fixer-next9603694
Ref: 35a69603694
Ref: library/2to3 2to3fixer-nonzero9603876
Ref: 35a79603876
Ref: library/2to3 2to3fixer-numliterals9603995
Ref: 35a89603995
Ref: library/2to3 2to3fixer-operator9604072
Ref: 35a99604072
Ref: library/2to3 2to3fixer-paren9605719
Ref: 35aa9605719
Ref: library/2to3 2to3fixer-print9605870
Ref: 35ab9605870
Ref: library/2to3 2to3fixer-raise9605960
Ref: 35ac9605960
Ref: library/2to3 2to3fixer-raw_input9606246
Ref: 35ad9606246
Ref: library/2to3 2to3fixer-reduce9606333
Ref: 35ae9606333
Ref: library/2to3 2to3fixer-reload9606425
Ref: 11699606425
Ref: library/2to3 2to3fixer-renames9606517
Ref: 35af9606517
Ref: library/2to3 2to3fixer-repr9606605
Ref: 35b09606605
Ref: library/2to3 2to3fixer-set_literal9606698
Ref: 35b19606698
Ref: library/2to3 2to3fixer-standarderror9606833
Ref: 35b29606833
Ref: library/2to3 2to3fixer-sys_exc9606931
Ref: 35b39606931
Ref: library/2to3 2to3fixer-throw9607097
Ref: 35b49607097
Ref: library/2to3 2to3fixer-tuple_params9607182
Ref: 35b59607182
Ref: library/2to3 2to3fixer-types9607293
Ref: 35b69607293
Ref: library/2to3 2to3fixer-unicode9607400
Ref: 35b79607400
Ref: library/2to3 2to3fixer-urllib9607480
Ref: 35b89607480
Ref: library/2to3 2to3fixer-ws_comma9607589
Ref: 35b99607589
Ref: library/2to3 2to3fixer-xrange9607702
Ref: 35ba9607702
Ref: library/2to3 2to3fixer-xreadlines9607854
Ref: 35bb9607854
Ref: library/2to3 2to3fixer-zip9607957
Ref: 35bc9607957
Node: lib2to3 —— 2to3 支持库9608109
Ref: library/2to3 lib2to3-2to3-s-library9608245
Ref: 35bd9608245
Ref: library/2to3 module-lib2to39608245
Ref: a79608245
Ref: lib2to3 —— 2to3 支持库-Footnote-19608863
Ref: lib2to3 —— 2to3 支持库-Footnote-29608927
Ref: lib2to3 —— 2to3 支持库-Footnote-39608976
Ref: lib2to3 —— 2to3 支持库-Footnote-49609015
Node: test --- Python回归测试包9609053
Ref: library/test doc9609254
Ref: 35be9609254
Ref: library/test module-test9609254
Ref: 1059609254
Ref: library/test parso9609254
Ref: 35bf9609254
Ref: library/test test-regression-tests-package-for-python9609254
Ref: 35c09609254
Node: Writing Unit Tests for the test package9610564
Ref: library/test writing-tests9610725
Ref: 35c19610725
Ref: library/test writing-unit-tests-for-the-test-package9610725
Ref: 35c29610725
Node: Running tests using the command-line interface9615267
Ref: library/test regrtest9615428
Ref: a129615428
Ref: library/test running-tests-using-the-command-line-interface9615428
Ref: 35c39615428
Node: test support --- Utilities for the Python test suite9617368
Ref: library/test module-test support9617574
Ref: 1069617574
Ref: library/test test-support-utilities-for-the-python-test-suite9617574
Ref: 35c49617574
Ref: library/test test support TestFailed9618086
Ref: 35c59618086
Ref: library/test test support ResourceDenied9618303
Ref: 35c69618303
Ref: library/test test support verbose9618594
Ref: 35c89618594
Ref: library/test test support is_jython9618810
Ref: 35c99618810
Ref: library/test test support is_android9618899
Ref: 35ca9618899
Ref: library/test test support unix_shell9618977
Ref: 35cb9618977
Ref: library/test test support FS_NONASCII9619074
Ref: 35cc9619074
Ref: library/test test support TESTFN9619177
Ref: 101d9619177
Ref: library/test test support TESTFN_UNICODE9619367
Ref: 35cd9619367
Ref: library/test test support TESTFN_ENCODING9619458
Ref: 35ce9619458
Ref: library/test test support TESTFN_UNENCODABLE9619551
Ref: 35cf9619551
Ref: library/test test support TESTFN_UNDECODABLE9619791
Ref: 35d09619791
Ref: library/test test support TESTFN_NONASCII9620033
Ref: 35d19620033
Ref: library/test test support LOOPBACK_TIMEOUT9620153
Ref: 10b19620153
Ref: library/test test support INTERNET_TIMEOUT9620738
Ref: 10b29620738
Ref: library/test test support SHORT_TIMEOUT9621230
Ref: f949621230
Ref: library/test test support LONG_TIMEOUT9621608
Ref: 10b39621608
Ref: library/test test support SAVEDCWD9622106
Ref: 35d39622106
Ref: library/test test support PGO9622177
Ref: 35d49622177
Ref: library/test test support PIPE_MAX_SIZE9622275
Ref: 35d59622275
Ref: library/test test support SOCK_MAX_SIZE9622423
Ref: 35d69622423
Ref: library/test test support TEST_SUPPORT_DIR9622573
Ref: 35d79622573
Ref: library/test test support TEST_HOME_DIR9622695
Ref: 35d89622695
Ref: library/test test support TEST_DATA_DIR9622792
Ref: 35d99622792
Ref: library/test test support MAX_Py_ssize_t9622893
Ref: 35da9622893
Ref: library/test test support max_memuse9622991
Ref: 35db9622991
Ref: library/test test support real_max_memuse9623154
Ref: 35dd9623154
Ref: library/test test support MISSING_C_DOCSTRINGS9623326
Ref: 35de9623326
Ref: library/test test support HAVE_DOCSTRINGS9623494
Ref: 35df9623494
Ref: library/test test support TEST_HTTP_URL9623574
Ref: 35e09623574
Ref: library/test test support ALWAYS_EQ9623683
Ref: 35e19623683
Ref: library/test test support NEVER_EQ9623799
Ref: 35e29623799
Ref: library/test test support LARGEST9623951
Ref: 35e39623951
Ref: library/test test support SMALLEST9624085
Ref: 35e49624085
Ref: library/test test support forget9624287
Ref: 35e59624287
Ref: library/test test support unload9624456
Ref: 35e69624456
Ref: library/test test support unlink9624540
Ref: 35e79624540
Ref: library/test test support rmdir9624743
Ref: 35e89624743
Ref: library/test test support rmtree9624944
Ref: 35e99624944
Ref: library/test test support make_legacy_pyc9625241
Ref: 35ea9625241
Ref: library/test test support is_resource_enabled9625574
Ref: 35eb9625574
Ref: library/test test support python_is_optimized9625799
Ref: 35ec9625799
Ref: library/test test support with_pymalloc9625925
Ref: 35ed9625925
Ref: library/test test support requires9626012
Ref: 35c79626012
Ref: library/test test support system_must_validate_cert9626377
Ref: 35ee9626377
Ref: library/test test support sortdict9626522
Ref: 35ef9626522
Ref: library/test test support findfile9626612
Ref: 35f09626612
Ref: library/test test support create_empty_file9626982
Ref: 35f19626982
Ref: library/test test support fd_count9627122
Ref: 35f29627122
Ref: library/test test support match_test9627209
Ref: 35f39627209
Ref: library/test test support set_match_tests9627322
Ref: 35f49627322
Ref: library/test test support run_unittest9627435
Ref: 11789627435
Ref: library/test test support run_doctest9628095
Ref: 35f59628095
Ref: library/test test support setswitchinterval9628560
Ref: 35f69628560
Ref: library/test test support check_impl_detail9628784
Ref: 35f79628784
Ref: library/test test support check_warnings9629194
Ref: 35f89629194
Ref: library/test test support check_no_resource_warning9632224
Ref: 35fb9632224
Ref: library/test test support set_memlimit9632486
Ref: 35dc9632486
Ref: library/test test support record_original_stdout9632642
Ref: 35fc9632642
Ref: library/test test support get_original_stdout9632806
Ref: 35fd9632806
Ref: library/test test support args_from_interpreter_flags9632977
Ref: 35fe9632977
Ref: library/test test support optim_args_from_interpreter_flags9633164
Ref: 35ff9633164
Ref: library/test test support captured_stdin9633344
Ref: 36009633344
Ref: library/test test support captured_stdout9633387
Ref: 36019633387
Ref: library/test test support captured_stderr9633431
Ref: 110d9633431
Ref: library/test test support temp_dir9634154
Ref: 36029634154
Ref: library/test test support change_cwd9634595
Ref: 36039634595
Ref: library/test test support temp_cwd9634952
Ref: 36049634952
Ref: library/test test support temp_umask9635588
Ref: 36059635588
Ref: library/test test support disable_faulthandler9635698
Ref: 36069635698
Ref: library/test test support gc_collect9635830
Ref: 36079635830
Ref: library/test test support disable_gc9636164
Ref: 36089636164
Ref: library/test test support swap_attr9636308
Ref: 36099636308
Ref: library/test test support swap_item9636889
Ref: 360a9636889
Ref: library/test test support print_warning9637468
Ref: 360b9637468
Ref: library/test test support wait_process9637736
Ref: 105c9637736
Ref: library/test test support wait_threads_exit9638248
Ref: 360d9638248
Ref: library/test test support start_threads9638402
Ref: 360e9638402
Ref: library/test test support calcobjsize9638556
Ref: 360f9638556
Ref: library/test test support calcvobjsize9638726
Ref: 36109638726
Ref: library/test test support checksizeof9638899
Ref: 36119638899
Ref: library/test test support can_symlink9639068
Ref: 36129639068
Ref: library/test test support can_xattr9639191
Ref: 36139639191
Ref: library/test test support skip_unless_symlink9639303
Ref: 36149639303
Ref: library/test test support skip_unless_xattr9639432
Ref: 36159639432
Ref: library/test test support anticipate_failure9639545
Ref: 36169639545
Ref: library/test test support run_with_locale9639805
Ref: 36179639805
Ref: library/test test support run_with_tz9640163
Ref: 36189640163
Ref: library/test test support requires_freebsd_version9640323
Ref: 36199640323
Ref: library/test test support requires_linux_version9640555
Ref: 361a9640555
Ref: library/test test support requires_mac_version9640782
Ref: 361b9640782
Ref: library/test test support requires_IEEE_7549641006
Ref: 361c9641006
Ref: library/test test support requires_zlib9641113
Ref: 361d9641113
Ref: library/test test support requires_gzip9641226
Ref: 361e9641226
Ref: library/test test support requires_bz29641338
Ref: 361f9641338
Ref: library/test test support requires_lzma9641448
Ref: 36209641448
Ref: library/test test support requires_resource9641560
Ref: 36219641560
Ref: library/test test support requires_docstrings9641683
Ref: 36229641683
Ref: library/test test support cpython_only9641804
Ref: 36239641804
Ref: library/test test support impl_detail9641905
Ref: 36249641905
Ref: library/test test support no_tracing9642133
Ref: 36259642133
Ref: library/test test support refcount_test9642261
Ref: 36269642261
Ref: library/test test support reap_threads9642570
Ref: 36279642570
Ref: library/test test support bigmemtest9642699
Ref: 36289642699
Ref: library/test test support bigaddrspacetest9643444
Ref: 36299643444
Ref: library/test test support make_bad_fd9643582
Ref: 362a9643582
Ref: library/test test support check_syntax_error9643739
Ref: 362b9643739
Ref: library/test test support check_syntax_warning9644291
Ref: 113e9644291
Ref: library/test test support open_urlresource9645088
Ref: 362c9645088
Ref: library/test test support import_module9645215
Ref: 362d9645215
Ref: library/test test support import_fresh_module9645815
Ref: 362e9645815
Ref: library/test test support modules_setup9647412
Ref: 362f9647412
Ref: library/test test support modules_cleanup9647503
Ref: 36309647503
Ref: library/test test support threading_setup9647665
Ref: 36319647665
Ref: library/test test support threading_cleanup9647774
Ref: 36329647774
Ref: library/test test support join_thread9647983
Ref: 36339647983
Ref: library/test test support reap_children9648176
Ref: 36349648176
Ref: library/test test support get_attribute9648448
Ref: 36359648448
Ref: library/test test support catch_threading_exception9648608
Ref: 10e29648608
Ref: library/test test support catch_unraisable_exception9649538
Ref: 10e49649538
Ref: library/test test support load_package_tests9650421
Ref: 36369650421
Ref: library/test test support fs_is_case_insensitive9651049
Ref: 36379651049
Ref: library/test test support detect_api_mismatch9651195
Ref: 36389651195
Ref: library/test test support patch9651660
Ref: 36399651660
Ref: library/test test support run_in_subinterp9651994
Ref: 363a9651994
Ref: library/test test support check_free_after_iterating9652161
Ref: 363b9652161
Ref: library/test test support missing_compiler_executable9652308
Ref: 363c9652308
Ref: library/test test support check__all__9652628
Ref: 363d9652628
Ref: library/test test support TransientResource9654484
Ref: 363e9654484
Ref: library/test test support EnvironmentVarGuard9654941
Ref: 363f9654941
Ref: library/test test support EnvironmentVarGuard set9655391
Ref: 36409655391
Ref: library/test test support EnvironmentVarGuard unset9655544
Ref: 36419655544
Ref: library/test test support SuppressCrashReport9655661
Ref: 36429655661
Ref: library/test test support CleanImport9656164
Ref: 36459656164
Ref: library/test test support DirsOnSysPath9656524
Ref: 36469656524
Ref: library/test test support SaveSignals9657016
Ref: 36479657016
Ref: library/test test support Matcher9657148
Ref: 36489657148
Ref: library/test test support Matcher matches9657182
Ref: 36499657182
Ref: library/test test support Matcher match_value9657301
Ref: 364a9657301
Ref: library/test test support WarningsRecorder9657446
Ref: 364b9657446
Ref: library/test test support BasicTestRunner9657622
Ref: 364c9657622
Ref: library/test test support BasicTestRunner run9657664
Ref: 364d9657664
Ref: library/test test support FakePath9657744
Ref: 364e9657744
Ref: test support --- Utilities for the Python test suite-Footnote-19658028
Ref: test support --- Utilities for the Python test suite-Footnote-29658077
Ref: test support --- Utilities for the Python test suite-Footnote-39658126
Node: test support socket_helper --- Utilities for socket tests9658206
Ref: library/test module-test support socket_helper9658453
Ref: 1099658453
Ref: library/test test-support-socket-helper-utilities-for-socket-tests9658453
Ref: 364f9658453
Ref: library/test test support socket_helper IPV6_ENABLED9658697
Ref: 36509658697
Ref: library/test test support socket_helper find_unused_port9658820
Ref: 36519658820
Ref: library/test test support socket_helper bind_port9660140
Ref: 36529660140
Ref: library/test test support socket_helper bind_unix_socket9661082
Ref: 36539661082
Ref: library/test test support socket_helper skip_unless_bind_unix_socket9661263
Ref: 36549661263
Ref: library/test test support socket_helper transient_internet9661431
Ref: 35d29661431
Node: test support script_helper --- Utilities for the Python execution tests9661702
Ref: library/test module-test support script_helper9661983
Ref: 1089661983
Ref: library/test test-support-script-helper-utilities-for-the-python-execution-tests9661983
Ref: 36559661983
Ref: library/test test support script_helper interpreter_requires_environment9662257
Ref: 36569662257
Ref: library/test test support script_helper run_python_until_end9663220
Ref: 36579663220
Ref: library/test test support script_helper assert_python_ok9663587
Ref: 36589663587
Ref: library/test test support script_helper assert_python_failure9664182
Ref: 36599664182
Ref: library/test test support script_helper spawn_python9664605
Ref: 365a9664605
Ref: library/test test support script_helper kill_python9664916
Ref: 365b9664916
Ref: library/test test support script_helper make_script9665070
Ref: 365c9665070
Ref: library/test test support script_helper make_zip_script9665377
Ref: 365d9665377
Ref: library/test test support script_helper make_pkg9665744
Ref: 365e9665744
Ref: library/test test support script_helper make_zip_pkg9665935
Ref: 365f9665935
Node: test support bytecode_helper --- Support tools for testing correct bytecode generation9666463
Ref: library/test module-test support bytecode_helper9666678
Ref: 1079666678
Ref: library/test test-support-bytecode-helper-support-tools-for-testing-correct-bytecode-generation9666678
Ref: 36609666678
Ref: library/test test support bytecode_helper BytecodeTestCase9667053
Ref: 36619667053
Ref: library/test test support bytecode_helper BytecodeTestCase get_disassembly_as_string9667213
Ref: 36629667213
Ref: library/test test support bytecode_helper BytecodeTestCase assertInBytecode9667328
Ref: 36639667328
Ref: library/test test support bytecode_helper BytecodeTestCase assertNotInBytecode9667514
Ref: 36649667514
Node: 调试和分析9667675
Ref: library/debug doc9667817
Ref: 36659667817
Ref: library/debug debugging-and-profiling9667817
Ref: 36669667817
Ref: library/audit_events audit-events9668224
Ref: 36679668224
Node: 审计事件表9668687
Ref: library/audit_events doc9668789
Ref: 36689668789
Ref: library/audit_events audit-events-table9668789
Ref: 36699668789
Ref: 审计事件表-Footnote-19724098
Node: bdb --- Debugger framework9724147
Ref: library/bdb doc9724307
Ref: 368d9724307
Ref: library/bdb bdb-debugger-framework9724307
Ref: 368e9724307
Ref: library/bdb module-bdb9724307
Ref: e9724307
Ref: library/bdb bdb BdbQuit9724631
Ref: 368f9724631
Ref: library/bdb bdb Breakpoint9724792
Ref: 36909724792
Ref: library/bdb bdb Breakpoint deleteMe9725661
Ref: 36919725661
Ref: library/bdb bdb Breakpoint enable9725883
Ref: 36929725883
Ref: library/bdb bdb Breakpoint disable9725960
Ref: 36939725960
Ref: library/bdb bdb Breakpoint bpformat9726039
Ref: 36949726039
Ref: library/bdb bdb Breakpoint bpprint9726477
Ref: 36959726477
Ref: library/bdb bdb Bdb9726648
Ref: d609726648
Ref: library/bdb bdb Bdb canonic9727428
Ref: 36969727428
Ref: library/bdb bdb Bdb reset9727692
Ref: 36979727692
Ref: library/bdb bdb Bdb trace_dispatch9727873
Ref: 36989727873
Ref: library/bdb bdb Bdb dispatch_line9729284
Ref: 36999729284
Ref: library/bdb bdb Bdb dispatch_call9729764
Ref: 369b9729764
Ref: library/bdb bdb Bdb dispatch_return9730251
Ref: 369d9730251
Ref: library/bdb bdb Bdb dispatch_exception9730746
Ref: 369f9730746
Ref: library/bdb bdb Bdb stop_here9731408
Ref: 36a19731408
Ref: library/bdb bdb Bdb break_here9731625
Ref: 36a29731625
Ref: library/bdb bdb Bdb break_anywhere9731901
Ref: 36a39731901
Ref: library/bdb bdb Bdb user_call9732149
Ref: 369c9732149
Ref: library/bdb bdb Bdb user_line9732392
Ref: 369a9732392
Ref: library/bdb bdb Bdb user_return9732606
Ref: 369e9732606
Ref: library/bdb bdb Bdb user_exception9732792
Ref: 36a09732792
Ref: library/bdb bdb Bdb do_clear9732980
Ref: 36a49732980
Ref: library/bdb bdb Bdb set_step9733271
Ref: 36a59733271
Ref: library/bdb bdb Bdb set_next9733347
Ref: 36a69733347
Ref: library/bdb bdb Bdb set_return9733450
Ref: 36a79733450
Ref: library/bdb bdb Bdb set_until9733546
Ref: 36a89733546
Ref: library/bdb bdb Bdb set_trace9733723
Ref: 36a99733723
Ref: library/bdb bdb Bdb set_continue9733888
Ref: 36aa9733888
Ref: library/bdb bdb Bdb set_quit9734067
Ref: 36ab9734067
Ref: library/bdb bdb Bdb set_break9734491
Ref: 36ac9734491
Ref: library/bdb bdb Bdb clear_break9734848
Ref: 36ad9734848
Ref: library/bdb bdb Bdb clear_bpbynumber9735024
Ref: 36ae9735024
Ref: library/bdb bdb Bdb clear_all_file_breaks9735253
Ref: 36af9735253
Ref: library/bdb bdb Bdb clear_all_breaks9735418
Ref: 36b09735418
Ref: library/bdb bdb Bdb get_bpbynumber9735506
Ref: 36b19735506
Ref: library/bdb bdb Bdb get_break9735859
Ref: 36b29735859
Ref: library/bdb bdb Bdb get_breaks9735982
Ref: 36b39735982
Ref: library/bdb bdb Bdb get_file_breaks9736142
Ref: 36b49736142
Ref: library/bdb bdb Bdb get_all_breaks9736286
Ref: 36b59736286
Ref: library/bdb bdb Bdb get_stack9736498
Ref: 36b69736498
Ref: library/bdb bdb Bdb format_stack_entry9736670
Ref: 36b79736670
Ref: library/bdb bdb Bdb run9737263
Ref: 36b89737263
Ref: library/bdb bdb Bdb runeval9737499
Ref: 36b99737499
Ref: library/bdb bdb Bdb runctx9737733
Ref: 36ba9737733
Ref: library/bdb bdb Bdb runcall9737875
Ref: 3c29737875
Ref: library/bdb bdb checkfuncname9738050
Ref: 36bb9738050
Ref: library/bdb bdb effective9738486
Ref: 36bc9738486
Ref: library/bdb bdb set_trace9738803
Ref: 36bd9738803
Ref: bdb --- Debugger framework-Footnote-19738951
Node: faulthandler —— 转储 Python 的跟踪信息9739013
Ref: library/faulthandler doc9739185
Ref: 36be9739185
Ref: library/faulthandler faulthandler-dump-the-python-traceback9739185
Ref: 36bf9739185
Ref: library/faulthandler module-faulthandler9739185
Ref: 7b9739185
Node: 转储跟踪信息9741229
Ref: library/faulthandler dumping-the-traceback9741369
Ref: 36c09741369
Ref: library/faulthandler faulthandler dump_traceback9741420
Ref: 7cb9741420
Node: 错误处理程序的状态9741714
Ref: library/faulthandler fault-handler-state9741899
Ref: 36c19741899
Ref: library/faulthandler faulthandler enable9741965
Ref: 6429741965
Ref: library/faulthandler faulthandler disable9742672
Ref: 36c39742672
Ref: library/faulthandler faulthandler is_enabled9742804
Ref: 36c49742804
Node: 一定时间后转储跟踪数据。9742893
Ref: library/faulthandler dumping-the-tracebacks-after-a-timeout9743096
Ref: 36c59743096
Ref: library/faulthandler faulthandler dump_traceback_later9743177
Ref: 7cc9743177
Ref: library/faulthandler faulthandler cancel_dump_traceback_later9744177
Ref: 36c69744177
Node: 转储用户信号的跟踪信息。9744307
Ref: library/faulthandler dumping-the-traceback-on-a-user-signal9744510
Ref: 36c79744510
Ref: library/faulthandler faulthandler register9744591
Ref: 7ca9744591
Ref: library/faulthandler faulthandler unregister9745209
Ref: 36c89745209
Node: 文件描述符相关话题9745469
Ref: library/faulthandler faulthandler-fd9745646
Ref: 36c29745646
Ref: library/faulthandler issue-with-file-descriptors9745646
Ref: 36c99745646
Node: 示例<39>9746092
Ref: library/faulthandler example9746224
Ref: 36ca9746224
Node: pdb --- Python 的调试器9746748
Ref: library/pdb doc9746920
Ref: 36cb9746920
Ref: library/pdb debugger9746920
Ref: 36cc9746920
Ref: library/pdb module-pdb9746920
Ref: c99746920
Ref: library/pdb pdb-the-python-debugger9746920
Ref: 36cd9746920
Ref: library/pdb pdb run9749981
Ref: 34af9749981
Ref: library/pdb pdb runeval9750598
Ref: 36d29750598
Ref: library/pdb pdb runcall9750895
Ref: 36d39750895
Ref: library/pdb pdb set_trace9751192
Ref: 4c89751192
Ref: library/pdb pdb post_mortem9751547
Ref: e0a9751547
Ref: library/pdb pdb pm9751781
Ref: 36d49751781
Ref: library/pdb pdb Pdb9752089
Ref: 1d39752089
Ref: library/pdb pdb Pdb run9753449
Ref: 36d69753449
Ref: library/pdb pdb Pdb runeval9753515
Ref: 36d79753515
Ref: library/pdb pdb Pdb runcall9753586
Ref: 36d89753586
Ref: library/pdb pdb Pdb set_trace9753643
Ref: 36d99753643
Ref: pdb --- Python 的调试器-Footnote-19753803
Ref: pdb --- Python 的调试器-Footnote-29753865
Node: 调试器命令9753976
Ref: library/pdb debugger-commands9754055
Ref: 36ce9754055
Ref: library/pdb id29754055
Ref: 36da9754055
Ref: library/pdb pdbcommand-help9756034
Ref: 36dd9756034
Ref: library/pdb pdbcommand-where9756393
Ref: 36de9756393
Ref: library/pdb pdbcommand-down9756554
Ref: 36df9756554
Ref: library/pdb pdbcommand-up9756701
Ref: 36e09756701
Ref: library/pdb pdbcommand-break9756846
Ref: 36e19756846
Ref: library/pdb pdbcommand-tbreak9757714
Ref: 36e29757714
Ref: library/pdb pdbcommand-clear9757896
Ref: 36e39757896
Ref: library/pdb pdbcommand-disable9758192
Ref: 36e49758192
Ref: library/pdb pdbcommand-enable9758476
Ref: 36e59758476
Ref: library/pdb pdbcommand-ignore9758546
Ref: 36e69758546
Ref: library/pdb pdbcommand-condition9758896
Ref: 36e79758896
Ref: library/pdb pdbcommand-commands9759170
Ref: 36e89759170
Ref: library/pdb pdbcommand-step9760688
Ref: 36d09760688
Ref: library/pdb pdbcommand-next9760848
Ref: 36d19760848
Ref: library/pdb pdbcommand-until9761213
Ref: 36ec9761213
Ref: library/pdb pdbcommand-return9761538
Ref: 36e99761538
Ref: library/pdb pdbcommand-continue9761613
Ref: 36cf9761613
Ref: library/pdb pdbcommand-jump9761695
Ref: 36ea9761695
Ref: library/pdb pdbcommand-list9762070
Ref: 36db9762070
Ref: library/pdb pdbcommand-ll9762766
Ref: 36ed9762766
Ref: library/pdb pdbcommand-args9762928
Ref: 36ee9762928
Ref: library/pdb pdbcommand-p9762995
Ref: 9729762995
Ref: library/pdb pdbcommand-pp9763240
Ref: 36ef9763240
Ref: library/pdb pdbcommand-whatis9763384
Ref: 36f09763384
Ref: library/pdb pdbcommand-source9763458
Ref: 36f19763458
Ref: library/pdb pdbcommand-display9763578
Ref: 36f29763578
Ref: library/pdb pdbcommand-undisplay9763801
Ref: 36f39763801
Ref: library/pdb pdbcommand-interact9763972
Ref: 36f49763972
Ref: library/pdb debugger-aliases9764193
Ref: 36dc9764193
Ref: library/pdb pdbcommand-alias9764193
Ref: 36f59764193
Ref: library/pdb pdbcommand-unalias9765213
Ref: 36f69765213
Ref: library/pdb pdbcommand-!9765274
Ref: 36f79765274
Ref: library/pdb pdbcommand-run9765662
Ref: 36f89765662
Ref: library/pdb pdbcommand-restart9765693
Ref: 36f99765693
Ref: library/pdb pdbcommand-quit9766027
Ref: 36eb9766027
Ref: library/pdb pdbcommand-debug9766110
Ref: 36fa9766110
Ref: library/pdb pdbcommand-retval9766280
Ref: 36fb9766280
Node: Python Profilers 分析器9766369
Ref: library/profile doc9766539
Ref: 36fc9766539
Ref: library/profile profile9766539
Ref: 36fd9766539
Ref: library/profile the-python-profilers9766539
Ref: 36fe9766539
Ref: Python Profilers 分析器-Footnote-19766974
Ref: Python Profilers 分析器-Footnote-29767040
Node: profile分析器简介9767105
Ref: library/profile introduction-to-the-profilers9767217
Ref: 36ff9767217
Ref: library/profile profiler-introduction9767217
Ref: 37009767217
Node: 实时用户手册9768661
Ref: library/profile instant-user-s-manual9768815
Ref: 37019768815
Ref: library/profile profile-instant9768815
Ref: 37029768815
Node: profile 和 cProfile 模块参考9774708
Ref: library/profile module-cProfile9774849
Ref: 279774849
Ref: library/profile profile-and-cprofile-module-reference9774849
Ref: 37079774849
Ref: library/profile module-profile9774947
Ref: d39774947
Ref: library/profile profile run9775022
Ref: 37089775022
Ref: library/profile profile runctx9775655
Ref: 37099775655
Ref: library/profile profile Profile9776055
Ref: 2ec9776055
Ref: library/profile profile Profile enable9777624
Ref: 370a9777624
Ref: library/profile profile Profile disable9777733
Ref: 370b9777733
Ref: library/profile profile Profile create_stats9777843
Ref: 370c9777843
Ref: library/profile profile Profile print_stats9777969
Ref: 370d9777969
Ref: library/profile profile Profile dump_stats9778133
Ref: 370e9778133
Ref: library/profile profile Profile run9778238
Ref: 370f9778238
Ref: library/profile profile Profile runctx9778322
Ref: 37109778322
Ref: library/profile profile Profile runcall9778485
Ref: 3c19778485
Node: Stats 类9778835
Ref: library/profile profile-stats9778991
Ref: 37119778991
Ref: library/profile the-stats-class9778991
Ref: 37129778991
Ref: library/profile module-pstats9779110
Ref: d49779110
Ref: library/profile pstats Stats9779112
Ref: 37039779112
Ref: library/profile pstats Stats strip_dirs9780359
Ref: 37059780359
Ref: library/profile pstats Stats add9781183
Ref: 37139781183
Ref: library/profile pstats Stats dump_stats9781682
Ref: 37149781682
Ref: library/profile pstats Stats sort_stats9782069
Ref: 37049782069
Ref: library/profile pstats Stats reverse_order9787432
Ref: 37159787432
Ref: library/profile pstats Stats print_stats9787724
Ref: 37069787724
Ref: library/profile pstats Stats print_callers9789174
Ref: 37169789174
Ref: library/profile pstats Stats print_callees9790296
Ref: 37179790296
Ref: library/profile pstats Stats get_stats_profile9790683
Ref: 37189790683
Node: 什么是确定性性能分析？9791232
Ref: library/profile deterministic-profiling9791364
Ref: 37199791364
Ref: library/profile what-is-deterministic-profiling9791364
Ref: 371a9791364
Node: 局限性9792853
Ref: library/profile limitations9792988
Ref: 371b9792988
Ref: library/profile profile-limitations9792988
Ref: 371c9792988
Node: 准确估量9794505
Ref: library/profile calibration9794631
Ref: 371d9794631
Ref: library/profile profile-calibration9794631
Ref: 371e9794631
Node: 使用自定义计时器9796253
Ref: library/profile profile-timers9796361
Ref: 371f9796361
Ref: library/profile using-a-custom-timer9796361
Ref: 37209796361
Node: timeit --- 测量小代码片段的执行时间9798812
Ref: library/timeit doc9798989
Ref: 37219798989
Ref: library/timeit module-timeit9798989
Ref: 10d9798989
Ref: library/timeit timeit-measure-execution-time-of-small-code-snippets9798989
Ref: 37229798989
Ref: timeit --- 测量小代码片段的执行时间-Footnote-19799664
Node: 基礎範例<2>9799729
Ref: library/timeit basic-examples9799850
Ref: 37259799850
Node: Python 接口9801046
Ref: library/timeit id19801197
Ref: 37279801197
Ref: library/timeit python-interface9801197
Ref: 37249801197
Ref: library/timeit timeit timeit9801301
Ref: 8609801301
Ref: library/timeit timeit repeat9801709
Ref: 37299801709
Ref: library/timeit timeit default_timer9802235
Ref: 372b9802235
Ref: library/timeit timeit Timer9802423
Ref: 37289802423
Ref: library/timeit timeit Timer timeit9803701
Ref: 6939803701
Ref: library/timeit timeit Timer autorange9804564
Ref: 6929804564
Ref: library/timeit timeit Timer repeat9805193
Ref: 372a9805193
Ref: library/timeit timeit Timer print_exc9806194
Ref: 372c9806194
Node: 命令執行列介面9806724
Ref: library/timeit command-line-interface9806870
Ref: 372d9806870
Ref: library/timeit timeit-command-line-interface9806870
Ref: 37239806870
Ref: library/timeit cmdoption-timeit-n9807078
Ref: 372e9807078
Ref: library/timeit cmdoption-timeit-r9807150
Ref: 372f9807150
Ref: library/timeit cmdoption-timeit-s9807233
Ref: 37309807233
Ref: library/timeit cmdoption-timeit-p9807332
Ref: 37319807332
Ref: library/timeit cmdoption-timeit-u9807556
Ref: 37329807556
Ref: library/timeit cmdoption-timeit-v9807695
Ref: 37339807695
Ref: library/timeit cmdoption-timeit-h9807786
Ref: 37349807786
Node: 示例<40>9808861
Ref: library/timeit examples9808985
Ref: 37359808985
Ref: library/timeit timeit-examples9808985
Ref: 37269808985
Node: trace --- 跟踪Python语句执行9812060
Ref: library/trace doc9812245
Ref: 37369812245
Ref: library/trace module-trace9812245
Ref: 11b9812245
Ref: library/trace trace-trace-or-track-python-statement-execution9812245
Ref: 37379812245
Ref: trace --- 跟踪Python语句执行-Footnote-19812895
Ref: trace --- 跟踪Python语句执行-Footnote-29812959
Node: 命令行用法9813000
Ref: library/trace command-line-usage9813107
Ref: 37389813107
Ref: library/trace trace-cli9813107
Ref: 37399813107
Ref: library/trace cmdoption-trace-help9813406
Ref: 373a9813406
Ref: library/trace cmdoption-trace-version9813463
Ref: 373b9813463
Node: 主要的可选参数9813677
Ref: library/trace main-options9813768
Ref: 373c9813768
Ref: library/trace cmdoption-trace-c9814117
Ref: 373f9814117
Ref: library/trace cmdoption-trace-t9814356
Ref: 373e9814356
Ref: library/trace cmdoption-trace-l9814415
Ref: 373d9814415
Ref: library/trace cmdoption-trace-r9814499
Ref: 37439814499
Ref: library/trace cmdoption-trace-trackcalls9814680
Ref: 37449814680
Node: 修饰器9814774
Ref: library/trace modifiers9814883
Ref: 37459814883
Ref: library/trace cmdoption-trace-f9814919
Ref: 37419814919
Ref: library/trace cmdoption-trace-coverdir9815064
Ref: 37409815064
Ref: library/trace cmdoption-trace-m9815243
Ref: 37469815243
Ref: library/trace cmdoption-trace-s9815354
Ref: 37479815354
Ref: library/trace cmdoption-trace-no-report9815511
Ref: 37429815511
Ref: library/trace cmdoption-trace-g9815720
Ref: 37489815720
Node: 过滤器9815840
Ref: library/trace filters9815919
Ref: 37499815919
Ref: library/trace cmdoption-trace-ignore-module9815987
Ref: 374a9815987
Ref: library/trace cmdoption-trace-ignore-dir9816134
Ref: 374b9816134
Node: 编程接口9816305
Ref: library/trace programmatic-interface9816412
Ref: 374c9816412
Ref: library/trace trace-api9816412
Ref: 374d9816412
Ref: library/trace trace Trace9816453
Ref: 374e9816453
Ref: library/trace trace Trace run9817218
Ref: 374f9817218
Ref: library/trace trace Trace runctx9817433
Ref: 37509817433
Ref: library/trace trace Trace runfunc9817691
Ref: 3c39817691
Ref: library/trace trace Trace results9817882
Ref: 37519817882
Ref: library/trace trace CoverageResults9818153
Ref: 37529818153
Ref: library/trace trace CoverageResults update9818309
Ref: 37539818309
Ref: library/trace trace CoverageResults write_results9818432
Ref: 37549818432
Node: tracemalloc --- 跟踪内存分配9819390
Ref: library/tracemalloc doc9819519
Ref: 37559819519
Ref: library/tracemalloc module-tracemalloc9819519
Ref: 11d9819519
Ref: library/tracemalloc tracemalloc-trace-memory-allocations9819519
Ref: 37569819519
Ref: tracemalloc --- 跟踪内存分配-Footnote-19820835
Node: 示例<41>9820905
Ref: library/tracemalloc examples9820998
Ref: 37579820998
Node: 显示前10项9821130
Ref: library/tracemalloc display-the-top-109821212
Ref: 37589821212
Node: 计算差异9822670
Ref: library/tracemalloc compute-differences9822796
Ref: 375a9822796
Node: Get the traceback of a memory block9824957
Ref: library/tracemalloc get-the-traceback-of-a-memory-block9825079
Ref: 375d9825079
Node: Pretty top9827711
Ref: library/tracemalloc pretty-top9827812
Ref: 375e9827812
Node: Record the current and peak size of all traced memory blocks9830267
Ref: library/tracemalloc record-the-current-and-peak-size-of-all-traced-memory-blocks9830374
Ref: 375f9830374
Node: API9832066
Ref: library/tracemalloc api9832159
Ref: 37619832159
Node: 函数<10>9832334
Ref: library/tracemalloc functions9832405
Ref: 37629832405
Ref: library/tracemalloc tracemalloc clear_traces9832436
Ref: 37639832436
Ref: library/tracemalloc tracemalloc get_object_traceback9832569
Ref: 129b9832569
Ref: library/tracemalloc tracemalloc get_traceback_limit9832974
Ref: 37669832974
Ref: library/tracemalloc tracemalloc get_traced_memory9833296
Ref: 37609833296
Ref: library/tracemalloc tracemalloc reset_peak9833500
Ref: 1ec9833500
Ref: library/tracemalloc tracemalloc get_tracemalloc_memory9834128
Ref: 37689834128
Ref: library/tracemalloc tracemalloc is_tracing9834324
Ref: 37699834324
Ref: library/tracemalloc tracemalloc start9834555
Ref: 14819834555
Ref: library/tracemalloc tracemalloc stop9835917
Ref: 37649835917
Ref: library/tracemalloc tracemalloc take_snapshot9836349
Ref: 37679836349
Node: 域过滤器9837047
Ref: library/tracemalloc domainfilter9837139
Ref: 376d9837139
Ref: library/tracemalloc tracemalloc DomainFilter9837180
Ref: 6979837180
Ref: library/tracemalloc tracemalloc DomainFilter inclusive9837343
Ref: 376e9837343
Ref: library/tracemalloc tracemalloc DomainFilter domain9837640
Ref: 376f9837640
Node: 过滤器<2>9837742
Ref: library/tracemalloc filter9837829
Ref: 37709837829
Ref: library/tracemalloc tracemalloc Filter9837867
Ref: 37719837867
Ref: library/tracemalloc tracemalloc Filter domain9838699
Ref: 37729838699
Ref: library/tracemalloc tracemalloc Filter inclusive9838967
Ref: 37739838967
Ref: library/tracemalloc tracemalloc Filter lineno9839396
Ref: 37759839396
Ref: library/tracemalloc tracemalloc Filter filename_pattern9839545
Ref: 37749839545
Ref: library/tracemalloc tracemalloc Filter all_frames9839656
Ref: 37769839656
Node: Frame9840060
Ref: library/tracemalloc frame9840141
Ref: 37789840141
Ref: library/tracemalloc tracemalloc Frame9840174
Ref: 37799840174
Ref: library/tracemalloc tracemalloc Frame filename9840323
Ref: 377a9840323
Ref: library/tracemalloc tracemalloc Frame lineno9840392
Ref: 377b9840392
Node: 快照9840453
Ref: library/tracemalloc snapshot9840528
Ref: 377c9840528
Ref: library/tracemalloc tracemalloc Snapshot9840561
Ref: 376c9840561
Ref: library/tracemalloc tracemalloc Snapshot compare_to9840740
Ref: 376b9840740
Ref: library/tracemalloc tracemalloc Snapshot dump9841472
Ref: 375b9841472
Ref: library/tracemalloc tracemalloc Snapshot filter_traces9841599
Ref: 37839841599
Ref: library/tracemalloc tracemalloc Snapshot load9842273
Ref: 375c9842273
Ref: library/tracemalloc tracemalloc Snapshot statistics9842399
Ref: 37599842399
Ref: library/tracemalloc tracemalloc Snapshot traceback_limit9843566
Ref: 37779843566
Ref: library/tracemalloc tracemalloc Snapshot traces9843782
Ref: 37849843782
Node: 统计9844074
Ref: library/tracemalloc statistic9844157
Ref: 37899844157
Ref: library/tracemalloc tracemalloc Statistic9844190
Ref: 37859844190
Ref: library/tracemalloc tracemalloc Statistic count9844394
Ref: 37819844394
Ref: library/tracemalloc tracemalloc Statistic size9844463
Ref: 37869844463
Ref: library/tracemalloc tracemalloc Statistic traceback9844547
Ref: 37879844547
Node: StatisticDiff9844676
Ref: library/tracemalloc statisticdiff9844759
Ref: 378a9844759
Ref: library/tracemalloc tracemalloc StatisticDiff9844808
Ref: 377d9844808
Ref: library/tracemalloc tracemalloc StatisticDiff count9845109
Ref: 378b9845109
Ref: library/tracemalloc tracemalloc StatisticDiff count_diff9845280
Ref: 37809845280
Ref: library/tracemalloc tracemalloc StatisticDiff size9845499
Ref: 377f9845499
Ref: library/tracemalloc tracemalloc StatisticDiff size_diff9845692
Ref: 377e9845692
Ref: library/tracemalloc tracemalloc StatisticDiff traceback9845923
Ref: 37829845923
Node: 跟踪9846054
Ref: library/tracemalloc trace9846137
Ref: 378c9846137
Ref: library/tracemalloc tracemalloc Trace9846170
Ref: 37889846170
Ref: library/tracemalloc tracemalloc Trace domain9846395
Ref: 378d9846395
Ref: library/tracemalloc tracemalloc Trace size9846670
Ref: 378e9846670
Ref: library/tracemalloc tracemalloc Trace traceback9846751
Ref: 378f9846751
Node: 回溯9846880
Ref: library/tracemalloc traceback9846941
Ref: 37909846941
Ref: library/tracemalloc tracemalloc Traceback9846974
Ref: 5039846974
Ref: library/tracemalloc tracemalloc Traceback total_nframe9847893
Ref: 376a9847893
Ref: library/tracemalloc tracemalloc Traceback format9848190
Ref: 5049848190
Node: 軟體封裝與發布9849263
Ref: library/distribution doc9849414
Ref: 37929849414
Ref: library/distribution software-packaging-and-distribution9849414
Ref: 37939849414
Node: distutils --- 构建和安装 Python 模块9850023
Ref: library/distutils doc9850178
Ref: 37949850178
Ref: library/distutils distutils-building-and-installing-python-modules9850178
Ref: 37959850178
Ref: library/distutils module-distutils9850178
Ref: 389850178
Ref: distutils --- 构建和安装 Python 模块-Footnote-19851792
Ref: distutils --- 构建和安装 Python 模块-Footnote-29851845
Ref: distutils --- 构建和安装 Python 模块-Footnote-39851874
Node: ensurepip --- Bootstrapping the pip installer9851911
Ref: library/ensurepip doc9852102
Ref: 37969852102
Ref: library/ensurepip ensurepip-bootstrapping-the-pip-installer9852102
Ref: 37979852102
Ref: library/ensurepip module-ensurepip9852102
Ref: 789852102
Ref: ensurepip --- Bootstrapping the pip installer-Footnote-19853501
Node: Command line interface9853550
Ref: library/ensurepip command-line-interface9853673
Ref: 37989853673
Node: Module API9855450
Ref: library/ensurepip module-api9855573
Ref: 37999855573
Ref: library/ensurepip ensurepip version9855680
Ref: 379a9855680
Ref: library/ensurepip ensurepip bootstrap9855838
Ref: 36709855838
Node: venv --- 创建虚拟环境9857615
Ref: library/venv doc9857819
Ref: 379b9857819
Ref: library/venv module-venv9857819
Ref: 12e9857819
Ref: library/venv venv-creation-of-virtual-environments9857819
Ref: 379c9857819
Ref: venv --- 创建虚拟环境-Footnote-19858620
Ref: venv --- 创建虚拟环境-Footnote-29858681
Ref: venv --- 创建虚拟环境-Footnote-39858730
Node: 创建虚拟环境9858853
Ref: library/venv creating-virtual-environments9858950
Ref: 379d9858950
Ref: library/venv venv-def9865705
Ref: 379e9865705
Ref: 创建虚拟环境-Footnote-19868120
Ref: 创建虚拟环境-Footnote-29868194
Ref: 创建虚拟环境-Footnote-39868249
Ref: 创建虚拟环境-Footnote-49868294
Ref: 创建虚拟环境-Footnote-59868332
Node: API<2>9868381
Ref: library/venv api9868520
Ref: 37a29868520
Ref: library/venv venv-api9868520
Ref: 8df9868520
Ref: library/venv venv EnvBuilder9868756
Ref: 9ee9868756
Ref: library/venv venv EnvBuilder create9870591
Ref: 37a39870591
Ref: library/venv venv EnvBuilder ensure_directories9871756
Ref: 37a49871756
Ref: library/venv venv EnvBuilder create_configuration9872137
Ref: 37a59872137
Ref: library/venv venv EnvBuilder setup_python9872255
Ref: 37a69872255
Ref: library/venv venv EnvBuilder setup_scripts9872599
Ref: 37a79872599
Ref: library/venv venv EnvBuilder upgrade_dependencies9872719
Ref: 37a99872719
Ref: library/venv venv EnvBuilder post_setup9872981
Ref: 37a89872981
Ref: library/venv venv EnvBuilder install_scripts9873911
Ref: 37aa9873911
Ref: library/venv venv create9874960
Ref: 9ef9874960
Node: 一个扩展 EnvBuilder 的例子9875363
Ref: library/venv an-example-of-extending-envbuilder9875475
Ref: 37ab9875475
Ref: 一个扩展 EnvBuilder 的例子-Footnote-19886201
Node: zipapp —— 管理可执行的 Python zip 打包文件9886248
Ref: library/zipapp doc9886398
Ref: 37ac9886398
Ref: library/zipapp module-zipapp9886398
Ref: 14a9886398
Ref: library/zipapp pip9886398
Ref: 37ad9886398
Ref: library/zipapp zipapp-manage-executable-python-zip-archives9886398
Ref: 37ae9886398
Ref: zipapp —— 管理可执行的 Python zip 打包文件-Footnote-19887147
Node: 简单示例9887212
Ref: library/zipapp basic-example9887350
Ref: 37b19887350
Node: 命令執行列介面<2>9887713
Ref: library/zipapp command-line-interface9887870
Ref: 37b29887870
Ref: library/zipapp zipapp-command-line-interface9887870
Ref: 37af9887870
Ref: library/zipapp cmdoption-zipapp-o9888309
Ref: 37b39888309
Ref: library/zipapp cmdoption-zipapp-p9888778
Ref: 37b49888778
Ref: library/zipapp cmdoption-zipapp-m9889065
Ref: 37b59889065
Ref: library/zipapp cmdoption-zipapp-c9889514
Ref: 37b69889514
Ref: library/zipapp cmdoption-zipapp-info9889779
Ref: 37b79889779
Ref: library/zipapp cmdoption-zipapp-h9889978
Ref: 37b89889978
Node: Python API9890054
Ref: library/zipapp python-api9890209
Ref: 37b99890209
Ref: library/zipapp zipapp-python-api9890209
Ref: 37b09890209
Ref: library/zipapp zipapp create_archive9890291
Ref: 5209890291
Ref: library/zipapp zipapp get_interpreter9893552
Ref: 37ba9893552
Node: 示例<42>9893874
Ref: library/zipapp examples9894026
Ref: 37bb9894026
Ref: library/zipapp zipapp-examples9894026
Ref: 37bc9894026
Node: 指定解释器程序9895317
Ref: library/zipapp specifying-the-interpreter9895503
Ref: 37bd9895503
Ref: library/zipapp zipapp-specifying-the-interpreter9895503
Ref: 37be9895503
Node: 用 zipapp 创建独立运行的应用程序9896611
Ref: library/zipapp creating-standalone-applications-with-zipapp9896821
Ref: 37bf9896821
Node: 制作 Windows 可执行文件9898631
Ref: library/zipapp making-a-windows-executable9898763
Ref: 37c09898763
Node: 注意事项9901775
Ref: library/zipapp caveats9901907
Ref: 37c19901907
Node: Python 打包应用程序的格式9903405
Ref: library/zipapp the-python-zip-application-archive-format9903585
Ref: 37c29903585
Node: Python运行时服务9905332
Ref: library/python doc9905494
Ref: 37c39905494
Ref: library/python python9905494
Ref: 37c49905494
Ref: library/python python-runtime-services9905494
Ref: 37c59905494
Node: sys --- 系统相关的参数和函数9906599
Ref: library/sys doc9906770
Ref: 37c69906770
Ref: library/sys module-sys9906770
Ref: fd9906770
Ref: library/sys sys-system-specific-parameters-and-functions9906770
Ref: 37c79906770
Ref: library/sys sys abiflags9907101
Ref: 38d9907101
Ref: library/sys sys addaudithook9907415
Ref: 366a9907415
Ref: library/sys sys argv9908962
Ref: cc69908962
Ref: library/sys auditing9909829
Ref: fa19909829
Ref: library/sys sys audit9909829
Ref: 10569909829
Ref: library/sys sys base_exec_prefix9911134
Ref: 37a19911134
Ref: library/sys sys base_prefix9911705
Ref: 31809911705
Ref: library/sys sys byteorder9912265
Ref: 17559912265
Ref: library/sys sys builtin_module_names9912487
Ref: 37c89912487
Ref: library/sys sys call_tracing9912746
Ref: 37c99912746
Ref: library/sys sys copyright9912980
Ref: 37ca9912980
Ref: library/sys sys _clear_type_cache9913077
Ref: 37cb9913077
Ref: library/sys sys _current_frames9913370
Ref: e609913370
Ref: library/sys sys breakpointhook9914147
Ref: 4239914147
Ref: library/sys sys _debugmallocstats9915942
Ref: 37cc9915942
Ref: library/sys sys dllhandle9916346
Ref: 37cd9916346
Ref: library/sys sys displayhook9916455
Ref: f209916455
Ref: library/sys sys dont_write_bytecode9918004
Ref: 37ce9918004
Ref: library/sys sys pycache_prefix9918380
Ref: 2919918380
Ref: library/sys sys excepthook9919297
Ref: f249919297
Ref: library/sys sys __breakpointhook__9920230
Ref: 37cf9920230
Ref: library/sys sys __displayhook__9920263
Ref: 37d09920263
Ref: library/sys sys __excepthook__9920293
Ref: 37d19920293
Ref: library/sys sys __unraisablehook__9920322
Ref: 37d29920322
Ref: library/sys sys exc_info9920758
Ref: d279920758
Ref: library/sys sys exec_prefix9921744
Ref: 37a09921744
Ref: library/sys sys executable9922562
Ref: 39d9922562
Ref: library/sys sys exit9922859
Ref: daa9922859
Ref: library/sys sys flags9924281
Ref: c0e9924281
Ref: library/sys sys float_info9927227
Ref: 10fc9927227
Ref: library/sys sys float_repr_style9931896
Ref: d589931896
Ref: library/sys sys getallocatedblocks9932436
Ref: 9c89932436
Ref: library/sys sys getandroidapilevel9932963
Ref: 4f69932963
Ref: library/sys sys getdefaultencoding9933134
Ref: 37d49933134
Ref: library/sys sys getdlopenflags9933249
Ref: f109933249
Ref: library/sys sys getfilesystemencoding9933545
Ref: 5ef9933545
Ref: library/sys sys getfilesystemencodeerrors9934870
Ref: 68b9934870
Ref: library/sys sys getrefcount9935291
Ref: 37d59935291
Ref: library/sys sys getrecursionlimit9935509
Ref: f3b9935509
Ref: library/sys sys getsizeof9935776
Ref: 37659935776
Ref: library/sys sys getswitchinterval9936626
Ref: 2179936626
Ref: library/sys sys _getframe9936795
Ref: f259936795
Ref: library/sys sys getprofile9937360
Ref: e0c9937360
Ref: library/sys sys gettrace9937463
Ref: e0d9937463
Ref: library/sys sys getwindowsversion9937828
Ref: 68c9937828
Ref: library/sys sys get_asyncgen_hooks9940146
Ref: 37d69940146
Ref: library/sys sys get_coroutine_origin_tracking_depth9940663
Ref: 4f79940663
Ref: library/sys sys hash_info9940988
Ref: a069940988
Ref: library/sys sys hexversion9942533
Ref: 37d89942533
Ref: library/sys sys implementation9943362
Ref: a8b9943362
Ref: library/sys sys int_info9945206
Ref: ceb9945206
Ref: library/sys sys __interactivehook__9945948
Ref: 9ca9945948
Ref: library/sys sys intern9946451
Ref: d369946451
Ref: library/sys sys is_finalizing9947126
Ref: 8519947126
Ref: library/sys sys last_type9947308
Ref: d229947308
Ref: library/sys sys last_value9947332
Ref: 37da9947332
Ref: library/sys sys last_traceback9947357
Ref: 36d59947357
Ref: library/sys sys maxsize9947900
Ref: c159947900
Ref: library/sys sys maxunicode9948111
Ref: a6c9948111
Ref: library/sys sys meta_path9948471
Ref: 6dd9948471
Ref: library/sys sys modules9949638
Ref: 10519949638
Ref: library/sys sys path9949943
Ref: 2619949943
Ref: library/sys sys path_hooks9950906
Ref: a3d9950906
Ref: library/sys sys path_importer_cache9951262
Ref: 5979951262
Ref: library/sys sys platform9951773
Ref: 3d39951773
Ref: library/sys sys platlibdir9953999
Ref: 1e99953999
Ref: library/sys sys prefix9954880
Ref: 379f9954880
Ref: library/sys sys ps19955456
Ref: 14879955456
Ref: library/sys sys ps29955474
Ref: 14889955474
Ref: library/sys sys setdlopenflags9955917
Ref: b419955917
Ref: library/sys sys setprofile9956444
Ref: eff9956444
Ref: library/sys sys setrecursionlimit9958600
Ref: f3c9958600
Ref: library/sys sys setswitchinterval9959268
Ref: 2189959268
Ref: library/sys sys settrace9959752
Ref: f009959752
Ref: library/sys sys set_asyncgen_hooks9964021
Ref: 10579964021
Ref: library/sys sys set_coroutine_origin_tracking_depth9965034
Ref: 4f89965034
Ref: library/sys sys _enablelegacywindowsfsencoding9965829
Ref: 5f19965829
Ref: library/sys sys stdin9966258
Ref: 41e9966258
Ref: library/sys sys stdout9966278
Ref: 41f9966278
Ref: library/sys sys stderr9966299
Ref: 1ea9966299
Ref: library/sys sys __stdin__9969162
Ref: 37dd9969162
Ref: library/sys sys __stdout__9969186
Ref: 1df99969186
Ref: library/sys sys __stderr__9969211
Ref: 360c9969211
Ref: library/sys sys thread_info9970126
Ref: b7a9970126
Ref: library/sys sys tracebacklimit9971460
Ref: 37de9971460
Ref: library/sys sys unraisablehook9971765
Ref: 35a9971765
Ref: library/sys sys version9973268
Ref: 6ca9973268
Ref: library/sys sys api_version9973610
Ref: 37df9973610
Ref: library/sys sys version_info9973766
Ref: bed9973766
Ref: library/sys sys warnoptions9974350
Ref: 51a9974350
Ref: library/sys sys winver9974530
Ref: 37e09974530
Ref: library/sys sys _xoptions9974921
Ref: 14829974921
Ref: library/sys c999975708
Ref: 37d39975708
Ref: sys --- 系统相关的参数和函数-Footnote-19975907
Ref: sys --- 系统相关的参数和函数-Footnote-29975956
Ref: sys --- 系统相关的参数和函数-Footnote-39976005
Ref: sys --- 系统相关的参数和函数-Footnote-49976054
Ref: sys --- 系统相关的参数和函数-Footnote-59976106
Ref: sys --- 系统相关的参数和函数-Footnote-69976155
Ref: sys --- 系统相关的参数和函数-Footnote-79976204
Ref: sys --- 系统相关的参数和函数-Footnote-89976253
Ref: sys --- 系统相关的参数和函数-Footnote-99976302
Ref: sys --- 系统相关的参数和函数-Footnote-109976351
Ref: sys --- 系统相关的参数和函数-Footnote-119976401
Ref: sys --- 系统相关的参数和函数-Footnote-129976451
Ref: sys --- 系统相关的参数和函数-Footnote-139976501
Ref: sys --- 系统相关的参数和函数-Footnote-149976551
Ref: sys --- 系统相关的参数和函数-Footnote-159976601
Ref: sys --- 系统相关的参数和函数-Footnote-169976681
Ref: sys --- 系统相关的参数和函数-Footnote-179976731
Ref: sys --- 系统相关的参数和函数-Footnote-189976781
Node: sysconfig --- Provide access to Python's configuration information9976831
Ref: library/sysconfig doc9977036
Ref: 37e19977036
Ref: library/sysconfig module-sysconfig9977036
Ref: fe9977036
Ref: library/sysconfig sysconfig-provide-access-to-python-s-configuration-information9977036
Ref: 37e29977036
Ref: sysconfig --- Provide access to Python's configuration information-Footnote-19977653
Node: 配置变量9977721
Ref: library/sysconfig configuration-variables9977857
Ref: 37e39977857
Ref: library/sysconfig sysconfig get_config_vars9978324
Ref: a469978324
Ref: library/sysconfig sysconfig get_config_var9978693
Ref: a459978693
Node: 安装路径9979130
Ref: library/sysconfig id19979290
Ref: 37e49979290
Ref: library/sysconfig installation-paths9979290
Ref: 37dc9979290
Ref: library/sysconfig sysconfig get_scheme_names9981327
Ref: 37e59981327
Ref: library/sysconfig sysconfig get_path_names9981463
Ref: 37e69981463
Ref: library/sysconfig sysconfig get_path9981600
Ref: d869981600
Ref: library/sysconfig sysconfig get_paths9982817
Ref: ca79982817
Node: 其他功能<2>9983438
Ref: library/sysconfig other-functions9983613
Ref: 37e79983613
Ref: library/sysconfig sysconfig get_python_version9983654
Ref: ca69983654
Ref: library/sysconfig sysconfig get_platform9983823
Ref: ca59983823
Ref: library/sysconfig sysconfig is_python_build9984824
Ref: d879984824
Ref: library/sysconfig sysconfig parse_config_h9985113
Ref: 37e89985113
Ref: library/sysconfig sysconfig get_config_h_filename9985505
Ref: 37e99985505
Ref: library/sysconfig sysconfig get_makefile_filename9985593
Ref: 37ea9985593
Node: Using sysconfig as a script9985679
Ref: library/sysconfig using-sysconfig-as-a-script9985833
Ref: 37eb9985833
Node: builtins --- 内建对象9986906
Ref: library/builtins doc9987104
Ref: 37ec9987104
Ref: library/builtins builtins-built-in-objects9987104
Ref: 37ed9987104
Ref: library/builtins module-builtins9987104
Ref: 129987104
Node: __main__ --- 顶层脚本环境9988456
Ref: library/__main__ doc9988625
Ref: 37ee9988625
Ref: library/__main__ main-top-level-script-environment9988625
Ref: 37ef9988625
Ref: library/__main__ module-__main__9988625
Ref: 19988625
Node: warnings —— 警告信息的控制9989446
Ref: library/warnings doc9989615
Ref: 37f09989615
Ref: library/warnings module-warnings9989615
Ref: 12f9989615
Ref: library/warnings warnings-warning-control9989615
Ref: 37f19989615
Ref: warnings —— 警告信息的控制-Footnote-19991583
Node: 警告类别9991650
Ref: library/warnings id19991760
Ref: 37f59991760
Ref: library/warnings warning-categories9991760
Ref: 185f9991760
Node: 警告过滤器9995004
Ref: library/warnings the-warnings-filter9995141
Ref: 37f69995141
Ref: library/warnings warning-filter9995141
Ref: 15d9995141
Node: 警告过滤器的介绍9997547
Ref: library/warnings describing-warning-filters9997653
Ref: 147e9997653
Ref: library/warnings id29997653
Ref: 37f79997653
Node: 默认警告过滤器9999223
Ref: library/warnings default-warning-filter9999362
Ref: 37f89999362
Ref: library/warnings id39999362
Ref: 37f99999362
Node: 重写默认的过滤器10000369
Ref: library/warnings overriding-the-default-filter10000475
Ref: 37fa10000475
Ref: library/warnings warning-disable10000475
Ref: 37fb10000475
Node: 暂时禁止警告10001737
Ref: library/warnings temporarily-suppressing-warnings10001874
Ref: 37fc10001874
Ref: library/warnings warning-suppress10001874
Ref: 37fd10001874
Node: 测试警告10002726
Ref: library/warnings testing-warnings10002887
Ref: 37fe10002887
Ref: library/warnings warning-testing10002887
Ref: 37ff10002887
Node: 为新版本的依赖关系更新代码10004667
Ref: library/warnings updating-code-for-new-versions-of-dependencies10004825
Ref: 380010004825
Ref: library/warnings warning-ignored10004825
Ref: 351310004825
Node: 可用的函数10006085
Ref: library/warnings available-functions10006258
Ref: 380110006258
Ref: library/warnings warning-functions10006258
Ref: 380210006258
Ref: library/warnings warnings warn10006304
Ref: f1a10006304
Ref: library/warnings warnings warn_explicit10007352
Ref: 6a710007352
Ref: library/warnings warnings showwarning10008305
Ref: 37f410008305
Ref: library/warnings warnings formatwarning10008907
Ref: 112d10008907
Ref: library/warnings warnings filterwarnings10009261
Ref: eca10009261
Ref: library/warnings warnings simplefilter10009871
Ref: 35fa10009871
Ref: library/warnings warnings resetwarnings10010261
Ref: 37f310010261
Node: 可用的上下文管理器10010501
Ref: library/warnings available-context-managers10010626
Ref: 380310010626
Ref: library/warnings warnings catch_warnings10010694
Ref: 35f910010694
Node: dataclasses --- 数据类10011809
Ref: library/dataclasses doc10012000
Ref: 380410012000
Ref: library/dataclasses dataclasses-data-classes10012000
Ref: 380510012000
Ref: library/dataclasses module-dataclasses10012000
Ref: 2f10012000
Ref: dataclasses --- 数据类-Footnote-110013504
Ref: dataclasses --- 数据类-Footnote-210013574
Ref: dataclasses --- 数据类-Footnote-310013623
Node: 模块级装饰器、类和函数10013672
Ref: library/dataclasses module-level-decorators-classes-and-functions10013794
Ref: 380710013794
Ref: library/dataclasses dataclasses dataclass10013870
Ref: 44910013870
Ref: library/dataclasses dataclasses field10020261
Ref: 113910020261
Ref: library/dataclasses dataclasses Field10024032
Ref: 380810024032
Ref: library/dataclasses dataclasses fields10024749
Ref: 380910024749
Ref: library/dataclasses dataclasses asdict10025075
Ref: f5710025075
Ref: library/dataclasses dataclasses astuple10026145
Ref: f5610026145
Ref: library/dataclasses dataclasses make_dataclass10026885
Ref: 380a10026885
Ref: library/dataclasses dataclasses replace10028379
Ref: fa810028379
Ref: library/dataclasses dataclasses is_dataclass10029670
Ref: f5310029670
Node: 初始化后处理10030100
Ref: library/dataclasses post-init-processing10030240
Ref: 380b10030240
Node: 类变量10031903
Ref: library/dataclasses class-variables10032028
Ref: 380c10032028
Ref: 类变量-Footnote-110032529
Node: 仅初始化变量10032578
Ref: library/dataclasses init-only-variables10032700
Ref: 380d10032700
Node: 冻结的实例10033877
Ref: library/dataclasses frozen-instances10033996
Ref: 380e10033996
Node: 继承10034562
Ref: library/dataclasses inheritance10034681
Ref: 381010034681
Node: 默认工厂函数10035654
Ref: library/dataclasses default-factory-functions10035776
Ref: 381110035776
Node: 可变的默认值10036412
Ref: library/dataclasses mutable-default-values10036538
Ref: 381210036538
Node: 异常<16>10038327
Ref: library/dataclasses exceptions10038426
Ref: 381310038426
Ref: library/dataclasses dataclasses FrozenInstanceError10038457
Ref: 380f10038457
Node: contextlib --- 为 with语句上下文提供的工具10038712
Ref: library/contextlib doc10038886
Ref: 381410038886
Ref: library/contextlib contextlib-utilities-for-with-statement-contexts10038886
Ref: 381510038886
Ref: library/contextlib module-contextlib10038886
Ref: 2310038886
Ref: contextlib --- 为 with语句上下文提供的工具-Footnote-110039494
Node: 工具10039563
Ref: library/contextlib utilities10039683
Ref: 381610039683
Ref: library/contextlib contextlib AbstractContextManager10039740
Ref: 62d10039740
Ref: library/contextlib contextlib AbstractAsyncContextManager10040200
Ref: 48010040200
Ref: library/contextlib contextlib contextmanager10040673
Ref: c4f10040673
Ref: library/contextlib contextlib asynccontextmanager10043474
Ref: 47f10043474
Ref: library/contextlib contextlib closing10044474
Ref: 381710044474
Ref: library/contextlib simplifying-support-for-single-optional-context-managers10045259
Ref: 381810045259
Ref: library/contextlib contextlib nullcontext10045259
Ref: 47d10045259
Ref: library/contextlib contextlib suppress10046362
Ref: 91910046362
Ref: library/contextlib contextlib redirect_stdout10047431
Ref: 7b510047431
Ref: library/contextlib contextlib redirect_stderr10048925
Ref: 7b410048925
Ref: library/contextlib contextlib ContextDecorator10049196
Ref: c4e10049196
Ref: library/contextlib contextlib ExitStack10051494
Ref: 47e10051494
Ref: library/contextlib contextlib ExitStack enter_context10053237
Ref: 381a10053237
Ref: library/contextlib contextlib ExitStack push10053675
Ref: 381b10053675
Ref: library/contextlib contextlib ExitStack callback10054569
Ref: 3c710054569
Ref: library/contextlib contextlib ExitStack pop_all10055031
Ref: 381c10055031
Ref: library/contextlib contextlib ExitStack close10056085
Ref: 381d10056085
Ref: library/contextlib contextlib AsyncExitStack10056379
Ref: 48110056379
Ref: library/contextlib contextlib AsyncExitStack enter_async_context10056741
Ref: 381f10056741
Ref: library/contextlib contextlib AsyncExitStack push_async_exit10056899
Ref: 382010056899
Ref: library/contextlib contextlib AsyncExitStack push_async_callback10057067
Ref: 3c810057067
Ref: library/contextlib contextlib AsyncExitStack aclose10057213
Ref: 381e10057213
Node: 例子和配方10057801
Ref: library/contextlib examples-and-recipes10057980
Ref: 382110057980
Node: Supporting a variable number of context managers10058413
Ref: library/contextlib supporting-a-variable-number-of-context-managers10058564
Ref: 382210058564
Node: Catching exceptions from __enter__ methods10059606
Ref: library/contextlib catching-exceptions-from-enter-methods10059808
Ref: 382310059808
Node: Cleaning up in an __enter__ implementation10060956
Ref: library/contextlib cleaning-up-in-an-enter-implementation10061161
Ref: 382410061161
Node: Replacing any use of try-finally and flag variables10063064
Ref: library/contextlib replacing-any-use-of-try-finally-and-flag-variables10063274
Ref: 382510063274
Node: Using a context manager as a function decorator10065789
Ref: library/contextlib using-a-context-manager-as-a-function-decorator10065948
Ref: 382610065948
Ref: Using a context manager as a function decorator-Footnote-110067745
Node: Single use reusable and reentrant context managers10067794
Ref: library/contextlib single-use-reusable-and-reentrant-cms10067958
Ref: 91b10067958
Ref: library/contextlib single-use-reusable-and-reentrant-context-managers10067958
Ref: 382710067958
Node: Reentrant context managers10069495
Ref: library/contextlib reentrant-cms10069642
Ref: 381910069642
Ref: library/contextlib reentrant-context-managers10069642
Ref: 382810069642
Node: Reusable context managers10071154
Ref: library/contextlib reusable-cms10071301
Ref: 382910071301
Ref: library/contextlib reusable-context-managers10071301
Ref: 382a10071301
Node: abc --- 抽象基类10073971
Ref: library/abc doc10074146
Ref: 382b10074146
Ref: library/abc abc-abstract-base-classes10074146
Ref: 382c10074146
Ref: library/abc module-abc10074146
Ref: 310074146
Ref: library/abc abc ABC10075090
Ref: 90510075090
Ref: library/abc abc ABCMeta10075850
Ref: 90610075850
Ref: library/abc abc ABCMeta register10076570
Ref: ab010076570
Ref: library/abc abc ABCMeta __subclasshook__10077199
Ref: 382d10077199
Ref: library/abc abc abstractmethod10079950
Ref: aad10079950
Ref: library/abc abc abstractclassmethod10082718
Ref: aae10082718
Ref: library/abc abc abstractstaticmethod10083391
Ref: aaf10083391
Ref: library/abc abc abstractproperty10084068
Ref: aac10084068
Ref: library/abc abc get_cache_token10085376
Ref: 90410085376
Ref: abc --- 抽象基类-Footnote-110085764
Ref: abc --- 抽象基类-Footnote-210085826
Ref: abc --- 抽象基类-Footnote-310085875
Ref: abc --- 抽象基类-Footnote-410085924
Node: atexit --- 退出处理器10086023
Ref: library/atexit doc10086186
Ref: 382e10086186
Ref: library/atexit atexit-exit-handlers10086186
Ref: 382f10086186
Ref: library/atexit module-atexit10086186
Ref: b10086186
Ref: library/atexit atexit register10086964
Ref: f4610086964
Ref: library/atexit atexit unregister10087876
Ref: 383010087876
Node: atexit 示例10088514
Ref: library/atexit atexit-example10088590
Ref: 383110088590
Ref: library/atexit id110088590
Ref: 383210088590
Node: traceback --- 打印或检索堆栈回溯10089847
Ref: library/traceback doc10090024
Ref: 383310090024
Ref: library/traceback module-traceback10090024
Ref: 11c10090024
Ref: library/traceback traceback-print-or-retrieve-a-stack-traceback10090024
Ref: 383410090024
Ref: library/traceback traceback print_tb10090747
Ref: 86810090747
Ref: library/traceback traceback print_exception10091380
Ref: 220810091380
Ref: library/traceback traceback print_exc10092501
Ref: 383510092501
Ref: library/traceback traceback print_last10092665
Ref: 383610092665
Ref: library/traceback traceback print_stack10092990
Ref: 86910092990
Ref: library/traceback traceback extract_tb10093532
Ref: 383710093532
Ref: library/traceback traceback extract_stack10094263
Ref: 383810094263
Ref: library/traceback traceback format_list10094564
Ref: 383910094564
Ref: library/traceback traceback format_exception_only10095071
Ref: 349110095071
Ref: library/traceback traceback format_exception10095688
Ref: 383a10095688
Ref: library/traceback traceback format_exc10096286
Ref: 383b10096286
Ref: library/traceback traceback format_tb10096444
Ref: 379110096444
Ref: library/traceback traceback format_stack10096558
Ref: 383c10096558
Ref: library/traceback traceback clear_frames10096681
Ref: 9d710096681
Ref: library/traceback traceback walk_stack10096886
Ref: 86310096886
Ref: library/traceback traceback walk_tb10097192
Ref: 86410097192
Ref: traceback --- 打印或检索堆栈回溯-Footnote-110097620
Node: TracebackException Objects10097688
Ref: library/traceback tracebackexception-objects10097821
Ref: 383e10097821
Ref: library/traceback traceback TracebackException10098059
Ref: 86510098059
Ref: library/traceback traceback TracebackException __cause__10098445
Ref: 383f10098445
Ref: library/traceback traceback TracebackException __context__10098550
Ref: 384010098550
Ref: library/traceback traceback TracebackException __suppress_context__10098669
Ref: 384110098669
Ref: library/traceback traceback TracebackException stack10098785
Ref: 384210098785
Ref: library/traceback traceback TracebackException exc_type10098875
Ref: 384310098875
Ref: library/traceback traceback TracebackException filename10098950
Ref: 384410098950
Ref: library/traceback traceback TracebackException lineno10099048
Ref: 384510099048
Ref: library/traceback traceback TracebackException text10099146
Ref: 384610099146
Ref: library/traceback traceback TracebackException offset10099235
Ref: 384710099235
Ref: library/traceback traceback TracebackException msg10099352
Ref: 384810099352
Ref: library/traceback traceback TracebackException from_exception10099433
Ref: 384910099433
Ref: library/traceback traceback TracebackException format10099822
Ref: 384a10099822
Ref: library/traceback traceback TracebackException format_exception_only10100376
Ref: 384b10100376
Node: StackSummary Objects10100929
Ref: library/traceback stacksummary-objects10101091
Ref: 384c10101091
Ref: library/traceback traceback StackSummary10101260
Ref: 86610101260
Ref: library/traceback traceback StackSummary extract10101296
Ref: 383d10101296
Ref: library/traceback traceback StackSummary from_list10102127
Ref: 384d10102127
Ref: library/traceback traceback StackSummary format10102436
Ref: 384e10102436
Node: FrameSummary Objects10103053
Ref: library/traceback framesummary-objects10103207
Ref: 384f10103207
Ref: library/traceback traceback FrameSummary10103372
Ref: 86710103372
Node: Traceback Examples10104118
Ref: library/traceback traceback-example10104243
Ref: 385010104243
Ref: library/traceback traceback-examples10104243
Ref: 385110104243
Node: __future__ --- Future 语句定义10109639
Ref: library/__future__ doc10109818
Ref: 385210109818
Ref: library/__future__ future-future-statement-definitions10109818
Ref: 385310109818
Ref: library/__future__ module-__future__10109818
Ref: 010109818
Ref: __future__ --- Future 语句定义-Footnote-110114781
Ref: __future__ --- Future 语句定义-Footnote-210114850
Ref: __future__ --- Future 语句定义-Footnote-310114899
Ref: __future__ --- Future 语句定义-Footnote-410114948
Ref: __future__ --- Future 语句定义-Footnote-510114997
Ref: __future__ --- Future 语句定义-Footnote-610115046
Ref: __future__ --- Future 语句定义-Footnote-710115095
Ref: __future__ --- Future 语句定义-Footnote-810115144
Ref: __future__ --- Future 语句定义-Footnote-910115193
Ref: __future__ --- Future 语句定义-Footnote-1010115242
Node: gc --- 垃圾回收器接口10115292
Ref: library/gc doc10115454
Ref: 385410115454
Ref: library/gc gc-garbage-collector-interface10115454
Ref: 385510115454
Ref: library/gc module-gc10115454
Ref: 8410115454
Ref: library/gc gc enable10116288
Ref: 385610116288
Ref: library/gc gc disable10116345
Ref: 385710116345
Ref: library/gc gc isenabled10116403
Ref: 385810116403
Ref: library/gc gc collect10116489
Ref: 35b10116489
Ref: library/gc gc set_debug10117094
Ref: 385910117094
Ref: library/gc gc get_debug10117360
Ref: 385a10117360
Ref: library/gc gc get_objects10117426
Ref: 2fe10117426
Ref: library/gc gc get_stats10117819
Ref: 93a10117819
Ref: library/gc gc set_threshold10118401
Ref: 385b10118401
Ref: library/gc gc get_count10119460
Ref: 385c10119460
Ref: library/gc gc get_threshold10119576
Ref: 385d10119576
Ref: library/gc gc get_referrers10119714
Ref: fb610119714
Ref: library/gc gc get_referents10120643
Ref: fb710120643
Ref: library/gc gc is_tracked10121374
Ref: d6b10121374
Ref: library/gc gc is_finalized10122117
Ref: 1a910122117
Ref: library/gc gc freeze10122607
Ref: 49210122607
Ref: library/gc gc unfreeze10123102
Ref: 49310123102
Ref: library/gc gc get_freeze_count10123227
Ref: 49410123227
Ref: library/gc gc garbage10123419
Ref: c1210123419
Ref: library/gc gc callbacks10124303
Ref: ae810124303
Ref: library/gc gc DEBUG_STATS10125511
Ref: 385f10125511
Ref: library/gc gc DEBUG_COLLECTABLE10125652
Ref: 386010125652
Ref: library/gc gc DEBUG_UNCOLLECTABLE10125733
Ref: c1310125733
Ref: library/gc gc DEBUG_SAVEALL10126109
Ref: 385e10126109
Ref: library/gc gc DEBUG_LEAK10126311
Ref: 386110126311
Ref: gc --- 垃圾回收器接口-Footnote-110126543
Ref: gc --- 垃圾回收器接口-Footnote-210126632
Node: inspect --- 检查对象10126681
Ref: library/inspect doc10126845
Ref: 386210126845
Ref: library/inspect inspect-inspect-live-objects10126845
Ref: 386310126845
Ref: library/inspect module-inspect10126845
Ref: a010126845
Ref: inspect --- 检查对象-Footnote-110127846
Node: 类型和成员10127912
Ref: library/inspect inspect-types10128019
Ref: 386410128019
Ref: library/inspect types-and-members10128019
Ref: 386510128019
Ref: library/inspect inspect getmembers10140782
Ref: 386610140782
Ref: library/inspect inspect getmodulename10141394
Ref: 6e910141394
Ref: library/inspect inspect ismodule10142055
Ref: 386910142055
Ref: library/inspect inspect isclass10142145
Ref: 386a10142145
Ref: library/inspect inspect ismethod10142282
Ref: 386b10142282
Ref: library/inspect inspect isfunction10142396
Ref: 386c10142396
Ref: library/inspect inspect isgeneratorfunction10142572
Ref: 115610142572
Ref: library/inspect inspect isgenerator10142854
Ref: 386d10142854
Ref: library/inspect inspect iscoroutinefunction10142950
Ref: 7e910142950
Ref: library/inspect inspect iscoroutine10143328
Ref: 7e810143328
Ref: library/inspect inspect isawaitable10143510
Ref: 7ea10143510
Ref: library/inspect inspect isasyncgenfunction10143956
Ref: 115710143956
Ref: library/inspect inspect isasyncgen10144453
Ref: 386e10144453
Ref: library/inspect inspect istraceback10144677
Ref: 386f10144677
Ref: library/inspect inspect isframe10144773
Ref: 387010144773
Ref: library/inspect inspect iscode10144861
Ref: 387110144861
Ref: library/inspect inspect isbuiltin10144947
Ref: 387210144947
Ref: library/inspect inspect isroutine10145081
Ref: 387310145081
Ref: library/inspect inspect isabstract10145214
Ref: 387410145214
Ref: library/inspect inspect ismethoddescriptor10145320
Ref: 387510145320
Ref: library/inspect inspect isdatadescriptor10146201
Ref: 387610146201
Ref: library/inspect inspect isgetsetdescriptor10146828
Ref: 387710146828
Ref: library/inspect inspect ismemberdescriptor10147177
Ref: 387810147177
Node: Retrieving source code10147537
Ref: library/inspect inspect-source10147702
Ref: 387910147702
Ref: library/inspect retrieving-source-code10147702
Ref: 387a10147702
Ref: library/inspect inspect getdoc10147769
Ref: 30710147769
Ref: library/inspect inspect getcomments10148191
Ref: 344a10148191
Ref: library/inspect inspect getfile10148613
Ref: 11d810148613
Ref: library/inspect inspect getmodule10148845
Ref: f6b10148845
Ref: library/inspect inspect getsourcefile10148943
Ref: 387c10148943
Ref: library/inspect inspect getsourcelines10149178
Ref: 387d10149178
Ref: library/inspect inspect getsource10149786
Ref: fda10149786
Ref: library/inspect inspect cleandoc10150225
Ref: 387b10150225
Node: Introspecting callables with the Signature object10150634
Ref: library/inspect inspect-signature-object10150799
Ref: 387e10150799
Ref: library/inspect introspecting-callables-with-the-signature-object10150799
Ref: 387f10150799
Ref: library/inspect inspect signature10151114
Ref: 65510151114
Ref: library/inspect inspect Signature10152504
Ref: 7e410152504
Ref: library/inspect inspect Signature empty10153518
Ref: 388110153518
Ref: library/inspect inspect Signature parameters10153635
Ref: 108810153635
Ref: library/inspect inspect Signature return_annotation10154118
Ref: 388210154118
Ref: library/inspect inspect Signature bind10154326
Ref: 388310154326
Ref: library/inspect inspect Signature bind_partial10154609
Ref: 388410154609
Ref: library/inspect inspect Signature replace10154991
Ref: 388010154991
Ref: library/inspect inspect Signature from_callable10155700
Ref: 7e710155700
Ref: library/inspect inspect Parameter10156301
Ref: 7e510156301
Ref: library/inspect inspect Parameter empty10156643
Ref: 388610156643
Ref: library/inspect inspect Parameter name10156771
Ref: 388710156771
Ref: library/inspect inspect Parameter default10157223
Ref: 388810157223
Ref: library/inspect inspect Parameter annotation10157411
Ref: 388910157411
Ref: library/inspect inspect Parameter kind10157596
Ref: 388a10157596
Ref: library/inspect inspect Parameter kind description10160418
Ref: 388b10160418
Ref: library/inspect inspect Parameter replace10160948
Ref: 388510160948
Ref: library/inspect inspect BoundArguments10161932
Ref: a8910161932
Ref: library/inspect inspect BoundArguments arguments10162137
Ref: 1b910162137
Ref: library/inspect inspect BoundArguments args10162976
Ref: 388c10162976
Ref: library/inspect inspect BoundArguments kwargs10163124
Ref: 388d10163124
Ref: library/inspect inspect BoundArguments signature10163270
Ref: 388e10163270
Ref: library/inspect inspect BoundArguments apply_defaults10163365
Ref: 7e610163365
Ref: Introspecting callables with the Signature object-Footnote-110164345
Node: 类与函数<2>10164394
Ref: library/inspect classes-and-functions10164558
Ref: 388f10164558
Ref: library/inspect inspect-classes-functions10164558
Ref: 389010164558
Ref: library/inspect inspect getclasstree10164601
Ref: 389110164601
Ref: library/inspect inspect getargspec10165178
Ref: 65610165178
Ref: library/inspect inspect getfullargspec10166104
Ref: 65710166104
Ref: library/inspect inspect getargvalues10168444
Ref: 8a610168444
Ref: library/inspect inspect formatargspec10168949
Ref: 8a510168949
Ref: library/inspect inspect formatargvalues10170058
Ref: 8a710170058
Ref: library/inspect inspect getmro10170528
Ref: 389210170528
Ref: library/inspect inspect getcallargs10170890
Ref: 8a410170890
Ref: library/inspect inspect getclosurevars10172226
Ref: af610172226
Ref: library/inspect inspect unwrap10172938
Ref: 95410172938
Node: The interpreter stack10173668
Ref: library/inspect inspect-stack10173813
Ref: 389310173813
Ref: library/inspect the-interpreter-stack10173813
Ref: 389410173813
Ref: library/inspect inspect getframeinfo10175802
Ref: 389510175802
Ref: library/inspect inspect getouterframes10176027
Ref: 7ef10176027
Ref: library/inspect inspect getinnerframes10176507
Ref: 7f010176507
Ref: library/inspect inspect currentframe10176984
Ref: 389610176984
Ref: library/inspect inspect stack10177383
Ref: 7ed10177383
Ref: library/inspect inspect trace10177761
Ref: 7ee10177761
Node: Fetching attributes statically10178223
Ref: library/inspect fetching-attributes-statically10178395
Ref: 389710178395
Ref: library/inspect inspect getattr_static10178977
Ref: c9910178977
Node: Current State of Generators and Coroutines10180778
Ref: library/inspect current-state-of-generators-and-coroutines10180951
Ref: 389810180951
Ref: library/inspect inspect getgeneratorstate10181380
Ref: c9810181380
Ref: library/inspect inspect getcoroutinestate10181789
Ref: 7ec10181789
Ref: library/inspect inspect getgeneratorlocals10182620
Ref: af710182620
Ref: library/inspect inspect getcoroutinelocals10183490
Ref: 7eb10183490
Node: Code Objects Bit Flags10183721
Ref: library/inspect code-objects-bit-flags10183882
Ref: 389910183882
Ref: library/inspect inspect-module-co-flags10183882
Ref: 386710183882
Ref: library/inspect inspect CO_OPTIMIZED10184045
Ref: 389a10184045
Ref: library/inspect inspect CO_NEWLOCALS10184132
Ref: 389b10184132
Ref: library/inspect inspect CO_VARARGS10184277
Ref: 389c10184277
Ref: library/inspect inspect CO_VARKEYWORDS10184385
Ref: 389d10184385
Ref: library/inspect inspect CO_NESTED10184497
Ref: 389e10184497
Ref: library/inspect inspect CO_GENERATOR10184591
Ref: 389f10184591
Ref: library/inspect inspect CO_NOFREE10184766
Ref: 38a010184766
Ref: library/inspect inspect CO_COROUTINE10184857
Ref: 38a110184857
Ref: library/inspect inspect CO_ITERABLE_COROUTINE10185090
Ref: 38a210185090
Ref: library/inspect inspect CO_ASYNC_GENERATOR10185401
Ref: 38a310185401
Ref: Code Objects Bit Flags-Footnote-110186046
Ref: Code Objects Bit Flags-Footnote-210186095
Ref: Code Objects Bit Flags-Footnote-310186144
Node: 命令行界面<5>10186193
Ref: library/inspect command-line-interface10186303
Ref: 38a410186303
Ref: library/inspect inspect-module-cli10186303
Ref: 95310186303
Ref: library/inspect cmdoption-inspect-details10186659
Ref: 38a510186659
Node: site —— 指定域的配置钩子10186772
Ref: library/site doc10186899
Ref: 38a610186899
Ref: library/site module-site10186899
Ref: eb10186899
Ref: library/site site-site-specific-configuration-hook10186899
Ref: 38a710186899
Ref: site —— 指定域的配置钩子-Footnote-110192294
Node: Readline 配置10192357
Ref: library/site readline-configuration10192469
Ref: 38a910192469
Ref: library/site rlcompleter-config10192469
Ref: 9cc10192469
Node: 模块内容<8>10193077
Ref: library/site module-contents10193216
Ref: 38aa10193216
Ref: library/site site PREFIXES10193259
Ref: 38ab10193259
Ref: library/site site ENABLE_USER_SITE10193329
Ref: 38a810193329
Ref: library/site site USER_SITE10193746
Ref: 147a10193746
Ref: library/site site USER_BASE10194297
Ref: 148910194297
Ref: library/site site main10194867
Ref: 147b10194867
Ref: library/site site addsitedir10195151
Ref: 38ac10195151
Ref: library/site site getsitepackages10195362
Ref: ca110195362
Ref: library/site site getuserbase10195487
Ref: ca210195487
Ref: library/site site getusersitepackages10195714
Ref: ca310195714
Node: 命令行界面<6>10196092
Ref: library/site command-line-interface10196207
Ref: 38ad10196207
Ref: library/site site-commandline10196207
Ref: 38ae10196207
Ref: library/site cmdoption-site-user-base10196700
Ref: 38af10196700
Ref: library/site cmdoption-site-user-site10196768
Ref: 38b010196768
Ref: 命令行界面<6>-Footnote-110197404
Node: 自定义 Python 解释器10197453
Ref: library/custominterp doc10197606
Ref: 38b110197606
Ref: library/custominterp custom-python-interpreters10197606
Ref: 38b210197606
Ref: library/custominterp custominterp10197606
Ref: 38b310197606
Node: code --- 解释器基类10198158
Ref: library/code doc10198283
Ref: 38b410198283
Ref: library/code code-interpreter-base-classes10198283
Ref: 38b510198283
Ref: library/code module-code10198283
Ref: 1a10198283
Ref: library/code code InteractiveInterpreter10198631
Ref: 38b610198631
Ref: library/code code InteractiveConsole10199112
Ref: 194410199112
Ref: library/code code interact10199415
Ref: 38b710199415
Ref: library/code code compile_command10200122
Ref: 38b910200122
Ref: code --- 解释器基类-Footnote-110201245
Node: 交互解释器对象10201308
Ref: library/code interactive-interpreter-objects10201423
Ref: 38ba10201423
Ref: library/code interpreter-objects10201423
Ref: 38bb10201423
Ref: library/code code InteractiveInterpreter runsource10201479
Ref: 38bc10201479
Ref: library/code code InteractiveInterpreter runcode10202704
Ref: 38be10202704
Ref: library/code code InteractiveInterpreter showsyntaxerror10203145
Ref: 38bd10203145
Ref: library/code code InteractiveInterpreter showtraceback10203577
Ref: 79a10203577
Ref: library/code code InteractiveInterpreter write10203890
Ref: 38bf10203890
Node: 交互式控制台对象10204098
Ref: library/code console-objects10204213
Ref: 38c010204213
Ref: library/code interactive-console-objects10204213
Ref: 38c110204213
Ref: library/code code InteractiveConsole interact10204444
Ref: 38c210204444
Ref: library/code code InteractiveConsole push10205205
Ref: 38c310205205
Ref: library/code code InteractiveConsole resetbuffer10205843
Ref: 38c410205843
Ref: library/code code InteractiveConsole raw_input10205957
Ref: 38b810205957
Node: codeop --- 编译Python代码10206263
Ref: library/codeop doc10206388
Ref: 38c510206388
Ref: library/codeop codeop-compile-python-code10206388
Ref: 38c610206388
Ref: library/codeop module-codeop10206388
Ref: 1c10206388
Ref: library/codeop codeop compile_command10207278
Ref: 103c10207278
Ref: library/codeop codeop Compile10208666
Ref: 38c710208666
Ref: library/codeop codeop CommandCompiler10209003
Ref: 38c810209003
Ref: codeop --- 编译Python代码-Footnote-110209383
Node: 匯入模組10209448
Ref: library/modules doc10209599
Ref: 38c910209599
Ref: library/modules importing-modules10209599
Ref: 38ca10209599
Ref: library/modules modules10209599
Ref: 38cb10209599
Node: zipimport --- 从 Zip 存档中导入模块10210189
Ref: library/zipimport doc10210317
Ref: 38cc10210317
Ref: library/zipimport module-zipimport10210317
Ref: 14c10210317
Ref: library/zipimport zipimport-import-modules-from-zip-archives10210317
Ref: 38cd10210317
Ref: library/zipimport zipimport ZipImportError10212214
Ref: 38ce10212214
Ref: zipimport --- 从 Zip 存档中导入模块-Footnote-110212491
Ref: zipimport --- 从 Zip 存档中导入模块-Footnote-210212559
Ref: zipimport --- 从 Zip 存档中导入模块-Footnote-310212627
Ref: zipimport --- 从 Zip 存档中导入模块-Footnote-410212676
Ref: zipimport --- 从 Zip 存档中导入模块-Footnote-510212725
Ref: zipimport --- 从 Zip 存档中导入模块-Footnote-610212774
Node: zipimporter 对象10212823
Ref: library/zipimport id110212940
Ref: 38cf10212940
Ref: library/zipimport zipimporter-objects10212940
Ref: 38d010212940
Ref: library/zipimport zipimport zipimporter10213057
Ref: 38d110213057
Ref: library/zipimport zipimport zipimporter find_module10213515
Ref: 38d210213515
Ref: library/zipimport zipimport zipimporter get_code10213903
Ref: 38d310213903
Ref: library/zipimport zipimport zipimporter get_data10214076
Ref: 11ef10214076
Ref: library/zipimport zipimport zipimporter get_filename10214356
Ref: 38d410214356
Ref: library/zipimport zipimport zipimporter get_source10214609
Ref: 38d510214609
Ref: library/zipimport zipimport zipimporter is_package10214860
Ref: 38d610214860
Ref: library/zipimport zipimport zipimporter load_module10215072
Ref: 38d710215072
Ref: library/zipimport zipimport zipimporter archive10215352
Ref: 38d810215352
Ref: library/zipimport zipimport zipimporter prefix10215461
Ref: 38d910215461
Node: 示例<43>10215813
Ref: library/zipimport examples10215930
Ref: 38da10215930
Ref: library/zipimport zipimport-examples10215930
Ref: 38db10215930
Node: pkgutil --- 包扩展工具10216595
Ref: library/pkgutil doc10216776
Ref: 38dc10216776
Ref: library/pkgutil module-pkgutil10216776
Ref: cd10216776
Ref: library/pkgutil pkgutil-package-extension-utility10216776
Ref: 38dd10216776
Ref: library/pkgutil pkgutil ModuleInfo10217022
Ref: 70310217022
Ref: library/pkgutil pkgutil extend_path10217171
Ref: 38de10217171
Ref: library/pkgutil pkgutil ImpImporter10218841
Ref: 38df10218841
Ref: library/pkgutil pkgutil ImpLoader10219528
Ref: 38e010219528
Ref: library/pkgutil pkgutil find_loader10219845
Ref: 38e110219845
Ref: library/pkgutil pkgutil get_importer10220402
Ref: 38e210220402
Ref: library/pkgutil pkgutil get_loader10220906
Ref: 38e310220906
Ref: library/pkgutil pkgutil iter_importers10221603
Ref: be710221603
Ref: library/pkgutil pkgutil iter_modules10222291
Ref: 70210222291
Ref: library/pkgutil pkgutil walk_packages10223128
Ref: 58510223128
Ref: library/pkgutil pkgutil get_data10224695
Ref: 10cf10224695
Ref: library/pkgutil pkgutil resolve_name10225827
Ref: 38e510225827
Ref: pkgutil --- 包扩展工具-Footnote-110227689
Ref: pkgutil --- 包扩展工具-Footnote-210227755
Ref: pkgutil --- 包扩展工具-Footnote-310227804
Ref: pkgutil --- 包扩展工具-Footnote-410227853
Ref: pkgutil --- 包扩展工具-Footnote-510227902
Ref: pkgutil --- 包扩展工具-Footnote-610227951
Ref: pkgutil --- 包扩展工具-Footnote-710228000
Ref: pkgutil --- 包扩展工具-Footnote-810228049
Ref: pkgutil --- 包扩展工具-Footnote-910228098
Ref: pkgutil --- 包扩展工具-Footnote-1010228147
Ref: pkgutil --- 包扩展工具-Footnote-1110228197
Ref: pkgutil --- 包扩展工具-Footnote-1210228247
Ref: pkgutil --- 包扩展工具-Footnote-1310228297
Ref: pkgutil --- 包扩展工具-Footnote-1410228347
Ref: pkgutil --- 包扩展工具-Footnote-1510228397
Node: modulefinder --- 查找脚本使用的模块10228441
Ref: library/modulefinder doc10228620
Ref: 38e610228620
Ref: library/modulefinder module-modulefinder10228620
Ref: b410228620
Ref: library/modulefinder modulefinder-find-modules-used-by-a-script10228620
Ref: 38e710228620
Ref: library/modulefinder modulefinder AddPackagePath10229068
Ref: 38e810229068
Ref: library/modulefinder modulefinder ReplacePackage10229201
Ref: 38e910229201
Ref: library/modulefinder modulefinder ModuleFinder10229344
Ref: 111b10229344
Ref: library/modulefinder modulefinder ModuleFinder report10229940
Ref: 38eb10229940
Ref: library/modulefinder modulefinder ModuleFinder run_script10230111
Ref: 38ea10230111
Ref: library/modulefinder modulefinder ModuleFinder modules10230243
Ref: 38ec10230243
Ref: modulefinder --- 查找脚本使用的模块-Footnote-110230473
Node: ModuleFinder 的示例用法10230544
Ref: library/modulefinder example-usage-of-modulefinder10230653
Ref: 38ee10230653
Ref: library/modulefinder modulefinder-example10230653
Ref: 38ed10230653
Node: runpy ——查找并执行 Python 模块10231964
Ref: library/runpy doc10232146
Ref: 38ef10232146
Ref: library/runpy module-runpy10232146
Ref: e210232146
Ref: library/runpy runpy-locating-and-executing-python-modules10232146
Ref: 38f010232146
Ref: library/runpy runpy run_module10233028
Ref: 146f10233028
Ref: library/runpy runpy run_path10235871
Ref: d7910235871
Ref: runpy ——查找并执行 Python 模块-Footnote-110239799
Ref: runpy ——查找并执行 Python 模块-Footnote-210239863
Ref: runpy ——查找并执行 Python 模块-Footnote-310239912
Ref: runpy ——查找并执行 Python 模块-Footnote-410239961
Ref: runpy ——查找并执行 Python 模块-Footnote-510240010
Ref: runpy ——查找并执行 Python 模块-Footnote-610240059
Ref: runpy ——查找并执行 Python 模块-Footnote-710240108
Ref: runpy ——查找并执行 Python 模块-Footnote-810240157
Node: importlib --- import 的实现10240206
Ref: library/importlib doc10240368
Ref: 38f110240368
Ref: library/importlib importlib-the-implementation-of-import10240368
Ref: 38f210240368
Ref: library/importlib module-importlib10240368
Ref: 9a10240368
Ref: importlib --- import 的实现-Footnote-110241096
Node: 簡介<11>10241174
Ref: library/importlib introduction10241270
Ref: 38f310241270
Ref: 簡介<11>-Footnote-110242852
Ref: 簡介<11>-Footnote-210242904
Ref: 簡介<11>-Footnote-310242953
Ref: 簡介<11>-Footnote-410243002
Ref: 簡介<11>-Footnote-510243051
Ref: 簡介<11>-Footnote-610243100
Ref: 簡介<11>-Footnote-710243149
Ref: 簡介<11>-Footnote-810243198
Ref: 簡介<11>-Footnote-910243247
Ref: 簡介<11>-Footnote-1010243296
Ref: 簡介<11>-Footnote-1110243346
Ref: 簡介<11>-Footnote-1210243396
Ref: 簡介<11>-Footnote-1310243446
Node: 函数<11>10243496
Ref: library/importlib functions10243649
Ref: 38f410243649
Ref: library/importlib importlib __import__10243680
Ref: a8e10243680
Ref: library/importlib importlib import_module10243957
Ref: be610243957
Ref: library/importlib importlib find_loader10245182
Ref: a1b10245182
Ref: library/importlib importlib invalidate_caches10246224
Ref: 59610246224
Ref: library/importlib importlib reload10246657
Ref: 49f10246657
Node: importlib abc —— 关于导入的抽象基类10249853
Ref: library/importlib importlib-abc-abstract-base-classes-related-to-import10250025
Ref: 38f510250025
Ref: library/importlib module-importlib abc10250025
Ref: 9b10250025
Ref: library/importlib importlib abc Finder10250840
Ref: a9510250840
Ref: library/importlib importlib abc Finder find_module10251040
Ref: 38f610251040
Ref: library/importlib importlib abc MetaPathFinder10251470
Ref: a9310251470
Ref: library/importlib importlib abc MetaPathFinder find_spec10251678
Ref: 56410251678
Ref: library/importlib importlib abc MetaPathFinder find_module10252316
Ref: 56310252316
Ref: library/importlib importlib abc MetaPathFinder invalidate_caches10253126
Ref: 38f810253126
Ref: library/importlib importlib abc PathEntryFinder10253605
Ref: a9410253605
Ref: library/importlib importlib abc PathEntryFinder find_spec10254018
Ref: 56610254018
Ref: library/importlib importlib abc PathEntryFinder find_loader10254445
Ref: 56510254445
Ref: library/importlib importlib abc PathEntryFinder find_module10255585
Ref: a1f10255585
Ref: library/importlib importlib abc PathEntryFinder invalidate_caches10255829
Ref: 38f910255829
Ref: library/importlib importlib abc Loader10256134
Ref: 8af10256134
Ref: library/importlib importlib abc Loader create_module10256530
Ref: 64e10256530
Ref: library/importlib importlib abc Loader exec_module10256959
Ref: 6db10256959
Ref: library/importlib importlib abc Loader load_module10257423
Ref: 6da10257423
Ref: library/importlib importlib abc Loader module_repr10260450
Ref: a2510260450
Ref: library/importlib importlib abc ResourceReader10260866
Ref: 44e10260866
Ref: library/importlib importlib abc ResourceReader open_resource10262304
Ref: 38fa10262304
Ref: library/importlib importlib abc ResourceReader resource_path10262566
Ref: 38fb10262566
Ref: library/importlib importlib abc ResourceReader is_resource10262802
Ref: 38fc10262802
Ref: library/importlib importlib abc ResourceReader contents10263002
Ref: 117010263002
Ref: library/importlib importlib abc ResourceLoader10263751
Ref: 56710263751
Ref: library/importlib importlib abc ResourceLoader get_data10264081
Ref: 38e410264081
Ref: library/importlib importlib abc InspectLoader10264704
Ref: 94b10264704
Ref: library/importlib importlib abc InspectLoader get_code10264859
Ref: 94c10264859
Ref: library/importlib importlib abc InspectLoader get_source10265429
Ref: 95010265429
Ref: library/importlib importlib abc InspectLoader is_package10265988
Ref: 38fd10265988
Ref: library/importlib importlib abc InspectLoader source_to_code10266337
Ref: 7e010266337
Ref: library/importlib importlib abc InspectLoader exec_module10266975
Ref: a2310266975
Ref: library/importlib importlib abc InspectLoader load_module10267106
Ref: a2010267106
Ref: library/importlib importlib abc ExecutionLoader10267288
Ref: 38fe10267288
Ref: library/importlib importlib abc ExecutionLoader get_filename10267519
Ref: 38ff10267519
Ref: library/importlib importlib abc FileLoader10267997
Ref: a9710267997
Ref: library/importlib importlib abc FileLoader name10268420
Ref: 390010268420
Ref: library/importlib importlib abc FileLoader path10268497
Ref: 390110268497
Ref: library/importlib importlib abc FileLoader load_module10268553
Ref: a2110268553
Ref: library/importlib importlib abc FileLoader get_filename10268739
Ref: 390210268739
Ref: library/importlib importlib abc FileLoader get_data10268841
Ref: 390310268841
Ref: library/importlib importlib abc SourceLoader10268982
Ref: 390410268982
Ref: library/importlib importlib abc SourceLoader path_stats10269948
Ref: bc310269948
Ref: library/importlib importlib abc SourceLoader path_mtime10270587
Ref: bc210270587
Ref: library/importlib importlib abc SourceLoader set_data10271108
Ref: 390510271108
Ref: library/importlib importlib abc SourceLoader get_code10271574
Ref: 390610271574
Ref: library/importlib importlib abc SourceLoader exec_module10271685
Ref: a2410271685
Ref: library/importlib importlib abc SourceLoader load_module10271822
Ref: a2210271822
Ref: library/importlib importlib abc SourceLoader get_source10272018
Ref: a3a10272018
Ref: library/importlib importlib abc SourceLoader is_package10272133
Ref: 390710272133
Ref: library/importlib importlib abc Traversable10272565
Ref: f7410272565
Ref: library/importlib importlib abc Traversable name10272718
Ref: 390810272718
Ref: library/importlib importlib abc Traversable iterdir10272836
Ref: 390910272836
Ref: library/importlib importlib abc Traversable is_dir10272932
Ref: 390a10272932
Ref: library/importlib importlib abc Traversable is_file10273028
Ref: 390b10273028
Ref: library/importlib importlib abc Traversable joinpath10273120
Ref: 390c10273120
Ref: library/importlib importlib abc Traversable __truediv__10273221
Ref: 390d10273221
Ref: library/importlib importlib abc Traversable open10273325
Ref: 390e10273325
Ref: library/importlib importlib abc Traversable read_bytes10273695
Ref: 390f10273695
Ref: library/importlib importlib abc Traversable read_text10273776
Ref: 391010273776
Ref: library/importlib importlib abc TraversableResources10273868
Ref: 391110273868
Ref: importlib abc —— 关于导入的抽象基类-Footnote-110274241
Ref: importlib abc —— 关于导入的抽象基类-Footnote-210274313
Ref: importlib abc —— 关于导入的抽象基类-Footnote-310274362
Ref: importlib abc —— 关于导入的抽象基类-Footnote-410274411
Ref: importlib abc —— 关于导入的抽象基类-Footnote-510274460
Ref: importlib abc —— 关于导入的抽象基类-Footnote-610274509
Node: importlib resources -- 资源10274558
Ref: library/importlib importlib-resources-resources10274780
Ref: 391210274780
Ref: library/importlib module-importlib resources10274780
Ref: 9e10274780
Ref: library/importlib importlib resources Package10275966
Ref: 391310275966
Ref: library/importlib importlib resources Resource10276295
Ref: 391410276295
Ref: library/importlib importlib resources files10276472
Ref: 1b710276472
Ref: library/importlib importlib resources as_file10276846
Ref: 391510276846
Ref: library/importlib importlib resources open_binary10277499
Ref: 391610277499
Ref: library/importlib importlib resources open_text10277968
Ref: 391710277968
Ref: library/importlib importlib resources read_binary10278622
Ref: 10ce10278622
Ref: library/importlib importlib resources read_text10279042
Ref: 391810279042
Ref: library/importlib importlib resources path10279656
Ref: 391910279656
Ref: library/importlib importlib resources is_resource10280290
Ref: 391a10280290
Ref: library/importlib importlib resources contents10280576
Ref: 116f10280576
Ref: importlib resources -- 资源-Footnote-110280956
Ref: importlib resources -- 资源-Footnote-210281035
Ref: importlib resources -- 资源-Footnote-310281106
Ref: importlib resources -- 资源-Footnote-410281199
Ref: importlib resources -- 资源-Footnote-510281270
Node: importlib machinery —— 导入器和路径钩子函数。10281346
Ref: library/importlib importlib-machinery-importers-and-path-hooks10281572
Ref: 391b10281572
Ref: library/importlib module-importlib machinery10281572
Ref: 9c10281572
Ref: library/importlib importlib machinery SOURCE_SUFFIXES10281905
Ref: 391c10281905
Ref: library/importlib importlib machinery DEBUG_BYTECODE_SUFFIXES10282054
Ref: 391d10282054
Ref: library/importlib importlib machinery OPTIMIZED_BYTECODE_SUFFIXES10282286
Ref: 391f10282286
Ref: library/importlib importlib machinery BYTECODE_SUFFIXES10282519
Ref: 391e10282519
Ref: library/importlib importlib machinery EXTENSION_SUFFIXES10282778
Ref: 392010282778
Ref: library/importlib importlib machinery all_suffixes10282933
Ref: 386810282933
Ref: library/importlib importlib machinery BuiltinImporter10283301
Ref: 64f10283301
Ref: library/importlib importlib machinery FrozenImporter10283849
Ref: a3810283849
Ref: library/importlib importlib machinery WindowsRegistryFinder10284231
Ref: 6dc10284231
Ref: library/importlib importlib machinery PathFinder10284661
Ref: a3c10284661
Ref: library/importlib importlib machinery PathFinder find_spec10284938
Ref: a1e10284938
Ref: library/importlib importlib machinery PathFinder find_module10286000
Ref: a1d10286000
Ref: library/importlib importlib machinery PathFinder invalidate_caches10286213
Ref: 59510286213
Ref: library/importlib importlib machinery FileFinder10286786
Ref: a9610286786
Ref: library/importlib importlib machinery FileFinder path10287869
Ref: 392110287869
Ref: library/importlib importlib machinery FileFinder find_spec10287937
Ref: 8ae10287937
Ref: library/importlib importlib machinery FileFinder find_loader10288103
Ref: 392210288103
Ref: library/importlib importlib machinery FileFinder invalidate_caches10288232
Ref: 392310288232
Ref: library/importlib importlib machinery FileFinder path_hook10288310
Ref: 392410288310
Ref: library/importlib importlib machinery SourceFileLoader10288721
Ref: a9810288721
Ref: library/importlib importlib machinery SourceFileLoader name10289002
Ref: 392510289002
Ref: library/importlib importlib machinery SourceFileLoader path10289079
Ref: 392610289079
Ref: library/importlib importlib machinery SourceFileLoader is_package10289132
Ref: 392710289132
Ref: library/importlib importlib machinery SourceFileLoader path_stats10289259
Ref: 392810289259
Ref: library/importlib importlib machinery SourceFileLoader set_data10289400
Ref: 392910289400
Ref: library/importlib importlib machinery SourceFileLoader load_module10289544
Ref: 6d810289544
Ref: library/importlib importlib machinery SourcelessFileLoader10289828
Ref: a9910289828
Ref: library/importlib importlib machinery SourcelessFileLoader name10290244
Ref: 392a10290244
Ref: library/importlib importlib machinery SourcelessFileLoader path10290315
Ref: 392b10290315
Ref: library/importlib importlib machinery SourcelessFileLoader is_package10290380
Ref: 392c10290380
Ref: library/importlib importlib machinery SourcelessFileLoader get_code10290493
Ref: 392d10290493
Ref: library/importlib importlib machinery SourcelessFileLoader get_source10290623
Ref: 392e10290623
Ref: library/importlib importlib machinery SourcelessFileLoader load_module10290767
Ref: 6d910290767
Ref: library/importlib importlib machinery ExtensionFileLoader10291031
Ref: 65010291031
Ref: library/importlib importlib machinery ExtensionFileLoader name10291352
Ref: 392f10291352
Ref: library/importlib importlib machinery ExtensionFileLoader path10291417
Ref: 393010291417
Ref: library/importlib importlib machinery ExtensionFileLoader create_module10291476
Ref: 393110291476
Ref: library/importlib importlib machinery ExtensionFileLoader exec_module10291619
Ref: 393210291619
Ref: library/importlib importlib machinery ExtensionFileLoader is_package10291758
Ref: 393310291758
Ref: library/importlib importlib machinery ExtensionFileLoader get_code10291953
Ref: 393410291953
Ref: library/importlib importlib machinery ExtensionFileLoader get_source10292068
Ref: 393510292068
Ref: library/importlib importlib machinery ExtensionFileLoader get_filename10292182
Ref: 95110292182
Ref: library/importlib importlib machinery ModuleSpec10292298
Ref: 160110292298
Ref: library/importlib importlib machinery ModuleSpec name10292992
Ref: 1aff10292992
Ref: library/importlib importlib machinery ModuleSpec loader10293103
Ref: 1afd10293103
Ref: library/importlib importlib machinery ModuleSpec origin10293270
Ref: 393610293270
Ref: library/importlib importlib machinery ModuleSpec submodule_search_locations10293566
Ref: 393710293566
Ref: library/importlib importlib machinery ModuleSpec loader_state10293744
Ref: 393810293744
Ref: library/importlib importlib machinery ModuleSpec cached10293874
Ref: 393910293874
Ref: library/importlib importlib machinery ModuleSpec parent10294006
Ref: 1b0110294006
Ref: library/importlib importlib machinery ModuleSpec has_location10294255
Ref: 393a10294255
Ref: importlib machinery —— 导入器和路径钩子函数。-Footnote-110294407
Ref: importlib machinery —— 导入器和路径钩子函数。-Footnote-210294486
Ref: importlib machinery —— 导入器和路径钩子函数。-Footnote-310294535
Ref: importlib machinery —— 导入器和路径钩子函数。-Footnote-410294584
Node: importlib util —— 导入器的工具程序代码10294633
Ref: library/importlib importlib-util-utility-code-for-importers10294840
Ref: 393b10294840
Ref: library/importlib module-importlib util10294840
Ref: 9f10294840
Ref: library/importlib importlib util MAGIC_NUMBER10295141
Ref: 94d10295141
Ref: library/importlib importlib util cache_from_source10295355
Ref: 65110295355
Ref: library/importlib importlib util source_from_cache10297028
Ref: 65210297028
Ref: library/importlib importlib util decode_source10297661
Ref: 94f10297661
Ref: library/importlib importlib util resolve_name10297935
Ref: 1b610297935
Ref: library/importlib importlib util find_spec10298783
Ref: a1c10298783
Ref: library/importlib importlib util module_from_spec10299614
Ref: 7e110299614
Ref: library/importlib importlib util module_for_loader10300185
Ref: a2610300185
Ref: library/importlib importlib util set_loader10301747
Ref: a2710301747
Ref: library/importlib importlib util set_package10302333
Ref: a2810302333
Ref: library/importlib importlib util spec_from_loader10302699
Ref: 38f710302699
Ref: library/importlib importlib util spec_from_file_location10303107
Ref: 65310303107
Ref: library/importlib importlib util source_hash10303538
Ref: 393c10303538
Ref: library/importlib importlib util LazyLoader10303796
Ref: 64d10303796
Ref: library/importlib importlib util LazyLoader factory10304986
Ref: 393e10304986
Ref: importlib util —— 导入器的工具程序代码-Footnote-110305505
Ref: importlib util —— 导入器的工具程序代码-Footnote-210305578
Ref: importlib util —— 导入器的工具程序代码-Footnote-310305627
Ref: importlib util —— 导入器的工具程序代码-Footnote-410305676
Ref: importlib util —— 导入器的工具程序代码-Footnote-510305725
Ref: importlib util —— 导入器的工具程序代码-Footnote-610305774
Node: 示例<44>10305823
Ref: library/importlib examples10305961
Ref: 393f10305961
Ref: library/importlib importlib-examples10305961
Ref: 394010305961
Node: 用编程方式导入10306198
Ref: library/importlib importing-programmatically10306305
Ref: 394110306305
Node: 检查某模块可否导入。10306531
Ref: library/importlib checking-if-a-module-can-be-imported10306671
Ref: 394210306671
Node: 直接导入源文件。10307419
Ref: library/importlib importing-a-source-file-directly10307553
Ref: 394310307553
Node: 设置导入器10308099
Ref: library/importlib setting-up-an-importer10308242
Ref: 394410308242
Node: importlib import_module 的近似实现10309660
Ref: library/importlib approximating-importlib-import-module10309770
Ref: 394510309770
Node: Using importlib metadata10311342
Ref: library/importlib metadata doc10311454
Ref: 394610311454
Ref: library/importlib metadata module-importlib metadata10311454
Ref: 9d10311454
Ref: library/importlib metadata using10311454
Ref: 394710311454
Ref: library/importlib metadata using-importlib-metadata10311454
Ref: 394810311454
Ref: Using importlib metadata-Footnote-110312823
Ref: Using importlib metadata-Footnote-210312901
Ref: Using importlib metadata-Footnote-310312986
Ref: Using importlib metadata-Footnote-410313071
Ref: Using importlib metadata-Footnote-510313143
Ref: Using importlib metadata-Footnote-610313181
Node: 概述10313230
Ref: library/importlib metadata overview10313316
Ref: 394910313316
Node: 可用 API10314732
Ref: library/importlib metadata functional-api10314840
Ref: 394f10314840
Node: Entry points10315082
Ref: library/importlib metadata entry-points10315171
Ref: 394a10315171
Ref: library/importlib metadata id110315171
Ref: 395010315171
Ref: Entry points-Footnote-110316484
Node: Distribution metadata10316595
Ref: library/importlib metadata distribution-metadata10316714
Ref: 395110316714
Ref: library/importlib metadata metadata10316714
Ref: 394b10316714
Ref: Distribution metadata-Footnote-110317198
Node: Distribution versions10317478
Ref: library/importlib metadata distribution-versions10317603
Ref: 395210317603
Ref: library/importlib metadata version10317603
Ref: 394c10317603
Node: Distribution files10317812
Ref: library/importlib metadata distribution-files10317941
Ref: 395310317941
Ref: library/importlib metadata files10317941
Ref: 394d10317941
Ref: Distribution files-Footnote-110319512
Node: Distribution requirements10319609
Ref: library/importlib metadata distribution-requirements10319708
Ref: 395410319708
Ref: library/importlib metadata requirements10319708
Ref: 394e10319708
Node: Distributions10319975
Ref: library/importlib metadata distributions10320107
Ref: 395510320107
Ref: Distributions-Footnote-110321014
Node: Extending the search algorithm10321063
Ref: library/importlib metadata extending-the-search-algorithm10321176
Ref: 395610321176
Node: Python 语言服务10322955
Ref: library/language doc10323092
Ref: 395710323092
Ref: library/language language10323092
Ref: 395810323092
Ref: library/language python-language-services10323092
Ref: 395910323092
Node: parser --- 访问 Python 解析树10324358
Ref: library/parser doc10324480
Ref: 395a10324480
Ref: library/parser module-parser10324480
Ref: c710324480
Ref: library/parser parser-access-python-parse-trees10324480
Ref: 395b10324480
Node: 创建 ST 对象10329629
Ref: library/parser creating-st-objects10329741
Ref: 396110329741
Ref: library/parser creating-sts10329741
Ref: 396210329741
Ref: library/parser parser expr10329977
Ref: 395c10329977
Ref: library/parser parser suite10330310
Ref: 395d10330310
Ref: library/parser parser sequence2st10330645
Ref: 395e10330645
Ref: library/parser parser tuple2st10332057
Ref: 396510332057
Node: 转换 ST 对象10332224
Ref: library/parser converting-st-objects10332366
Ref: 396610332366
Ref: library/parser converting-sts10332366
Ref: 396710332366
Ref: library/parser parser st2list10332666
Ref: 395f10332666
Ref: library/parser parser st2tuple10333738
Ref: 396010333738
Ref: library/parser parser compilest10334280
Ref: 396410334280
Node: Queries on ST Objects10335441
Ref: library/parser queries-on-st-objects10335588
Ref: 396810335588
Ref: library/parser querying-sts10335588
Ref: 396910335588
Ref: library/parser parser isexpr10335960
Ref: 396a10335960
Ref: library/parser parser issuite10336441
Ref: 396b10336441
Node: 异常和错误处理10336796
Ref: library/parser exceptions-and-error-handling10336936
Ref: 396c10336936
Ref: library/parser st-errors10336936
Ref: 396d10336936
Ref: library/parser parser ParserError10337208
Ref: 396310337208
Node: ST 对象10338366
Ref: library/parser id110338509
Ref: 396e10338509
Ref: library/parser st-objects10338509
Ref: 396f10338509
Ref: library/parser parser STType10338693
Ref: 397010338693
Ref: library/parser parser ST compile10338869
Ref: 397110338869
Ref: library/parser parser ST isexpr10338974
Ref: 397210338974
Ref: library/parser parser ST issuite10339043
Ref: 397310339043
Ref: library/parser parser ST tolist10339114
Ref: 397410339114
Ref: library/parser parser ST totuple10339236
Ref: 397510339236
Node: 示例 compile 的模拟10339360
Ref: library/parser example-emulation-of-compile10339473
Ref: 397610339473
Node: ast --- 抽象语法树10340554
Ref: library/ast doc10340727
Ref: 397710340727
Ref: library/ast ast-abstract-syntax-trees10340727
Ref: 397810340727
Ref: library/ast module-ast10340727
Ref: 710340727
Ref: ast --- 抽象语法树-Footnote-110341646
Node: 抽象文法10341708
Ref: library/ast abstract-grammar10341798
Ref: 397a10341798
Ref: library/ast id110341798
Ref: 397b10341798
Node: 节点类10347691
Ref: library/ast node-classes10347812
Ref: 397c10347812
Ref: library/ast ast AST10347848
Ref: 18710347848
Ref: library/ast ast AST _fields10348589
Ref: 397d10348589
Ref: library/ast ast AST lineno10349304
Ref: 397e10349304
Ref: library/ast ast AST col_offset10349328
Ref: 397f10349328
Ref: library/ast ast AST end_lineno10349356
Ref: 398010349356
Ref: library/ast ast AST end_col_offset10349384
Ref: 398110349384
Ref: 节点类-Footnote-110352303
Node: 字面值<3>10352361
Ref: library/ast literals10352437
Ref: 398310352437
Ref: library/ast ast Constant10352473
Ref: 3a610352473
Ref: library/ast ast FormattedValue10352966
Ref: 398410352966
Ref: library/ast ast JoinedStr10353822
Ref: 398510353822
Ref: library/ast ast List10354841
Ref: 398610354841
Ref: library/ast ast Tuple10354874
Ref: 398710354874
Ref: library/ast ast Set10355756
Ref: 398a10355756
Ref: library/ast ast Dict10356145
Ref: 103f10356145
Node: Variables10356969
Ref: library/ast variables10357066
Ref: 398b10357066
Ref: library/ast ast Name10357105
Ref: 102b10357105
Ref: library/ast ast Load10357248
Ref: 398910357248
Ref: library/ast ast Store10357269
Ref: 398810357269
Ref: library/ast ast Del10357291
Ref: 398c10357291
Ref: library/ast ast Starred10358250
Ref: 398d10358250
Node: 表达式<2>10359081
Ref: library/ast expressions10359176
Ref: 398f10359176
Ref: library/ast ast Expr10359212
Ref: 399010359212
Ref: library/ast ast UnaryOp10359887
Ref: 398210359887
Ref: library/ast ast UAdd10360022
Ref: 399410360022
Ref: library/ast ast USub10360043
Ref: 399510360043
Ref: library/ast ast Not10360064
Ref: 399610360064
Ref: library/ast ast Invert10360084
Ref: 399710360084
Ref: library/ast ast BinOp10360436
Ref: 10d210360436
Ref: library/ast ast Add10360870
Ref: 399810360870
Ref: library/ast ast Sub10360890
Ref: 399910360890
Ref: library/ast ast Mult10360910
Ref: 399a10360910
Ref: library/ast ast Div10360931
Ref: 399b10360931
Ref: library/ast ast FloorDiv10360951
Ref: 399c10360951
Ref: library/ast ast Mod10360976
Ref: 399d10360976
Ref: library/ast ast Pow10360996
Ref: 399e10360996
Ref: library/ast ast LShift10361016
Ref: 399f10361016
Ref: library/ast ast RShift10361039
Ref: 39a010361039
Ref: library/ast ast BitOr10361062
Ref: 39a110361062
Ref: library/ast ast BitXor10361084
Ref: 39a210361084
Ref: library/ast ast BitAnd10361107
Ref: 39a310361107
Ref: library/ast ast MatMult10361130
Ref: 39a410361130
Ref: library/ast ast BoolOp10361185
Ref: 39a510361185
Ref: library/ast ast And10361847
Ref: 39a710361847
Ref: library/ast ast Or10361867
Ref: 39a610361867
Ref: library/ast ast Compare10361918
Ref: 39a810361918
Ref: library/ast ast Eq10362565
Ref: 39a910362565
Ref: library/ast ast NotEq10362584
Ref: 39aa10362584
Ref: library/ast ast Lt10362606
Ref: 39ab10362606
Ref: library/ast ast LtE10362625
Ref: 39ac10362625
Ref: library/ast ast Gt10362645
Ref: 39ad10362645
Ref: library/ast ast GtE10362664
Ref: 39ae10362664
Ref: library/ast ast Is10362684
Ref: 39af10362684
Ref: library/ast ast IsNot10362703
Ref: 39b010362703
Ref: library/ast ast In10362725
Ref: 39b110362725
Ref: library/ast ast NotIn10362744
Ref: 39b210362744
Ref: library/ast ast Call10362801
Ref: 398e10362801
Ref: library/ast ast keyword10364013
Ref: 39b410364013
Ref: library/ast ast IfExp10364210
Ref: 39b510364210
Ref: library/ast ast Attribute10364694
Ref: 39b310364694
Ref: library/ast ast NamedExpr10365285
Ref: 39b610365285
Node: Subscripting10365937
Ref: library/ast subscripting10366021
Ref: 39b810366021
Ref: library/ast ast Subscript10366066
Ref: 39b910366066
Ref: library/ast ast Slice10366966
Ref: 39ba10366966
Node: Comprehensions10367556
Ref: library/ast comprehensions10367640
Ref: 39bb10367640
Ref: library/ast ast ListComp10367689
Ref: 39bc10367689
Ref: library/ast ast SetComp10367732
Ref: 39bd10367732
Ref: library/ast ast GeneratorExp10367774
Ref: 39be10367774
Ref: library/ast ast DictComp10367821
Ref: 39bf10367821
Ref: library/ast ast comprehension10369689
Ref: 39c010369689
Node: Statements10372869
Ref: library/ast statements10372967
Ref: 39c110372967
Ref: library/ast ast Assign10373008
Ref: 39b710373008
Ref: library/ast ast Assign type_comment10373352
Ref: 39c210373352
Ref: library/ast ast AnnAssign10374352
Ref: 39c310374352
Ref: library/ast ast AugAssign10376552
Ref: 39c410376552
Ref: library/ast ast Raise10377309
Ref: 39c510377309
Ref: library/ast ast Assert10377878
Ref: 39c610377878
Ref: library/ast ast Delete10378316
Ref: 39c710378316
Ref: library/ast ast Pass10378866
Ref: 39c810378866
Node: Imports10379200
Ref: library/ast imports10379254
Ref: 39c910379254
Ref: library/ast ast Import10379289
Ref: 39ca10379289
Ref: library/ast ast ImportFrom10379731
Ref: 39cc10379731
Ref: library/ast ast alias10380476
Ref: 39cb10380476
Node: Control flow10381027
Ref: library/ast control-flow10381143
Ref: 39cd10381143
Ref: library/ast ast If10381299
Ref: 39ce10381299
Ref: library/ast ast For10382588
Ref: 39cf10382588
Ref: library/ast ast For type_comment10383076
Ref: 39d010383076
Ref: library/ast ast While10383829
Ref: 39d110383829
Ref: library/ast ast Break10384535
Ref: 39d210384535
Ref: library/ast ast Continue10384557
Ref: 39d310384557
Ref: library/ast ast Try10385629
Ref: 39d410385629
Ref: library/ast ast ExceptHandler10387238
Ref: 39d510387238
Ref: library/ast ast With10388473
Ref: 39d610388473
Ref: library/ast ast With type_comment10388705
Ref: 39d810388705
Ref: library/ast ast withitem10388837
Ref: 39d710388837
Node: Function and class definitions10390206
Ref: library/ast function-and-class-definitions10390327
Ref: 39d910390327
Ref: library/ast ast FunctionDef10390410
Ref: 39da10390410
Ref: library/ast ast FunctionDef type_comment10390936
Ref: 39dc10390936
Ref: library/ast ast Lambda10391068
Ref: 399110391068
Ref: library/ast ast arguments10391889
Ref: 39db10391889
Ref: library/ast ast arg10392637
Ref: 39dd10392637
Ref: library/ast ast arg type_comment10392867
Ref: 39de10392867
Ref: library/ast ast Return10394505
Ref: 39df10394505
Ref: library/ast ast Yield10394778
Ref: 399210394778
Ref: library/ast ast YieldFrom10394808
Ref: 399310394808
Ref: library/ast ast Global10395537
Ref: 39e010395537
Ref: library/ast ast Nonlocal10395568
Ref: 39e110395568
Ref: library/ast ast ClassDef10396280
Ref: 39e210396280
Ref: Function and class definitions-Footnote-110398078
Node: Async and await10398128
Ref: library/ast async-and-await10398228
Ref: 39e310398228
Ref: library/ast ast AsyncFunctionDef10398281
Ref: 39e410398281
Ref: library/ast ast Await10398483
Ref: 39e510398483
Ref: library/ast ast AsyncFor10399423
Ref: 39e610399423
Ref: library/ast ast AsyncWith10399491
Ref: 39e710399491
Node: ast 中的辅助函数10400129
Ref: library/ast ast-helpers10400252
Ref: 39e810400252
Ref: library/ast ast parse10400423
Ref: 2d610400423
Ref: library/ast ast unparse10402931
Ref: 18610402931
Ref: library/ast ast literal_eval10403545
Ref: 59f10403545
Ref: library/ast ast get_docstring10404442
Ref: 118a10404442
Ref: library/ast ast get_source_segment10404875
Ref: 2d510404875
Ref: library/ast ast fix_missing_locations10405321
Ref: 39ea10405321
Ref: library/ast ast increment_lineno10405775
Ref: 100310405775
Ref: library/ast ast copy_location10406001
Ref: 39eb10406001
Ref: library/ast ast iter_fields10406233
Ref: 39ec10406233
Ref: library/ast ast iter_child_nodes10406386
Ref: 39ed10406386
Ref: library/ast ast walk10406562
Ref: 39ee10406562
Ref: library/ast ast NodeVisitor10406826
Ref: 3a710406826
Ref: library/ast ast NodeVisitor visit10407169
Ref: 39ef10407169
Ref: library/ast ast NodeVisitor generic_visit10407455
Ref: 39f010407455
Ref: library/ast ast NodeTransformer10408287
Ref: 39f110408287
Ref: library/ast ast dump10409937
Ref: 18510409937
Ref: ast 中的辅助函数-Footnote-110411049
Ref: ast 中的辅助函数-Footnote-210411098
Ref: ast 中的辅助函数-Footnote-310411147
Node: Compiler Flags10411196
Ref: library/ast ast-compiler-flags10411328
Ref: 172010411328
Ref: library/ast compiler-flags10411328
Ref: 39f210411328
Ref: library/ast ast PyCF_ALLOW_TOP_LEVEL_AWAIT10411499
Ref: 39f310411499
Ref: library/ast ast PyCF_ONLY_AST10411679
Ref: 397910411679
Ref: library/ast ast PyCF_TYPE_COMMENTS10411810
Ref: 39e910411810
Ref: Compiler Flags-Footnote-110412035
Ref: Compiler Flags-Footnote-210412084
Node: 命令行用法<2>10412133
Ref: library/ast ast-cli10412234
Ref: 39f410412234
Ref: library/ast command-line-usage10412234
Ref: 39f510412234
Ref: library/ast cmdoption-ast-h10412474
Ref: 39f610412474
Ref: library/ast cmdoption-ast-m10412542
Ref: 39f710412542
Ref: library/ast cmdoption-ast-mode10412570
Ref: 39f810412570
Ref: library/ast cmdoption-ast-no-type-comments10412706
Ref: 39f910412706
Ref: library/ast cmdoption-ast-a10412779
Ref: 39fa10412779
Ref: library/ast cmdoption-ast-i10412889
Ref: 39fb10412889
Ref: library/ast cmdoption-ast-indent10412919
Ref: 39fc10412919
Ref: 命令行用法<2>-Footnote-110414027
Ref: 命令行用法<2>-Footnote-210414075
Ref: 命令行用法<2>-Footnote-310414142
Ref: 命令行用法<2>-Footnote-410414197
Ref: 命令行用法<2>-Footnote-510414236
Node: symtable ——访问编译器的符号表10414273
Ref: library/symtable doc10414464
Ref: 39fd10414464
Ref: library/symtable module-symtable10414464
Ref: fc10414464
Ref: library/symtable symtable-access-to-the-compiler-s-symbol-tables10414464
Ref: 39fe10414464
Ref: symtable ——访问编译器的符号表-Footnote-110414948
Node: 符号表的生成10415015
Ref: library/symtable generating-symbol-tables10415139
Ref: 39ff10415139
Ref: library/symtable symtable symtable10415190
Ref: 110110415190
Node: 符号表的查看10415440
Ref: library/symtable examining-symbol-tables10415564
Ref: 3a0110415564
Ref: library/symtable symtable SymbolTable10415615
Ref: 3a0010415615
Ref: library/symtable symtable SymbolTable get_type10415716
Ref: 3a0210415716
Ref: library/symtable symtable SymbolTable get_id10415866
Ref: 3a0310415866
Ref: library/symtable symtable SymbolTable get_name10415939
Ref: 3a0410415939
Ref: library/symtable symtable SymbolTable get_lineno10416207
Ref: 3a0510416207
Ref: library/symtable symtable SymbolTable is_optimized10416317
Ref: 3a0610416317
Ref: library/symtable symtable SymbolTable is_nested10416446
Ref: 3a0710416446
Ref: library/symtable symtable SymbolTable has_children10416557
Ref: 3a0810416557
Ref: library/symtable symtable SymbolTable get_identifiers10416734
Ref: 3a0a10416734
Ref: library/symtable symtable SymbolTable lookup10416828
Ref: 3a0b10416828
Ref: library/symtable symtable SymbolTable get_symbols10416952
Ref: 3a0d10416952
Ref: library/symtable symtable SymbolTable get_children10417075
Ref: 3a0910417075
Ref: library/symtable symtable Function10417160
Ref: 3a0e10417160
Ref: library/symtable symtable Function get_parameters10417274
Ref: 3a0f10417274
Ref: library/symtable symtable Function get_locals10417373
Ref: 3a1010417373
Ref: library/symtable symtable Function get_globals10417471
Ref: 3a1110417471
Ref: library/symtable symtable Function get_nonlocals10417570
Ref: 3a1210417570
Ref: library/symtable symtable Function get_frees10417674
Ref: 3a1310417674
Ref: library/symtable symtable Class10417771
Ref: 3a1410417771
Ref: library/symtable symtable Class get_methods10417864
Ref: 3a1510417864
Ref: library/symtable symtable Symbol10417963
Ref: 3a0c10417963
Ref: library/symtable symtable Symbol get_name10418111
Ref: 3a1610418111
Ref: library/symtable symtable Symbol is_referenced10418174
Ref: 3a1710418174
Ref: library/symtable symtable Symbol is_imported10418292
Ref: 3a1810418292
Ref: library/symtable symtable Symbol is_parameter10418408
Ref: 3a1910418408
Ref: library/symtable symtable Symbol is_global10418504
Ref: 3a1a10418504
Ref: library/symtable symtable Symbol is_nonlocal10418606
Ref: 114610418606
Ref: library/symtable symtable Symbol is_declared_global10418713
Ref: d7e10418713
Ref: library/symtable symtable Symbol is_local10418841
Ref: 3a1b10418841
Ref: library/symtable symtable Symbol is_annotated10418957
Ref: 3a1c10418957
Ref: library/symtable symtable Symbol is_free10419088
Ref: 3a1d10419088
Ref: library/symtable symtable Symbol is_assigned10419212
Ref: 3a1e10419212
Ref: library/symtable symtable Symbol is_namespace10419322
Ref: 3a1f10419322
Ref: library/symtable symtable Symbol get_namespaces10419939
Ref: 3a2010419939
Ref: library/symtable symtable Symbol get_namespace10420044
Ref: 3a2110420044
Node: symbol --- 与 Python 解析树一起使用的常量10420230
Ref: library/symbol doc10420447
Ref: 3a2210420447
Ref: library/symbol module-symbol10420447
Ref: fb10420447
Ref: library/symbol symbol-constants-used-with-python-parse-trees10420447
Ref: 3a2310420447
Ref: library/symbol symbol sym_name10421143
Ref: 3a2410421143
Ref: symbol --- 与 Python 解析树一起使用的常量-Footnote-110421345
Node: token --- 与Python解析树一起使用的常量10421410
Ref: library/token doc10421618
Ref: 3a2510421618
Ref: library/token module-token10421618
Ref: 11910421618
Ref: library/token token-constants-used-with-python-parse-trees10421618
Ref: 3a2610421618
Ref: library/token token tok_name10422226
Ref: 3a2710422226
Ref: library/token token ISTERMINAL10422391
Ref: 3a2810422391
Ref: library/token token ISNONTERMINAL10422470
Ref: 3a2910422470
Ref: library/token token ISEOF10422555
Ref: 3a2a10422555
Ref: library/token token ENDMARKER10422675
Ref: 3a2b10422675
Ref: library/token token NAME10422702
Ref: 3a2c10422702
Ref: library/token token NUMBER10422724
Ref: 3a2d10422724
Ref: library/token token STRING10422748
Ref: 3a2e10422748
Ref: library/token token NEWLINE10422772
Ref: 3a2f10422772
Ref: library/token token INDENT10422797
Ref: 3a3010422797
Ref: library/token token DEDENT10422821
Ref: 3a3110422821
Ref: library/token token LPAR10422845
Ref: 3a3210422845
Ref: library/token token RPAR10422899
Ref: 3a3310422899
Ref: library/token token LSQB10422953
Ref: 3a3410422953
Ref: library/token token RSQB10423007
Ref: 3a3510423007
Ref: library/token token COLON10423061
Ref: 3a3610423061
Ref: library/token token COMMA10423116
Ref: 3a3710423116
Ref: library/token token SEMI10423171
Ref: 3a3810423171
Ref: library/token token PLUS10423225
Ref: 3a3910423225
Ref: library/token token MINUS10423279
Ref: 3a3a10423279
Ref: library/token token STAR10423334
Ref: 3a3b10423334
Ref: library/token token SLASH10423388
Ref: 3a3c10423388
Ref: library/token token VBAR10423443
Ref: 3a3d10423443
Ref: library/token token AMPER10423497
Ref: 3a3e10423497
Ref: library/token token LESS10423552
Ref: 3a3f10423552
Ref: library/token token GREATER10423606
Ref: 3a4010423606
Ref: library/token token EQUAL10423663
Ref: 3a4110423663
Ref: library/token token DOT10423719
Ref: 3a4210423719
Ref: library/token token PERCENT10423773
Ref: 3a4310423773
Ref: library/token token LBRACE10423831
Ref: 3a4410423831
Ref: library/token token RBRACE10423888
Ref: 3a4510423888
Ref: library/token token EQEQUAL10423945
Ref: 3a4610423945
Ref: library/token token NOTEQUAL10424004
Ref: 3a4710424004
Ref: library/token token LESSEQUAL10424064
Ref: 3a4810424064
Ref: library/token token GREATEREQUAL10424125
Ref: 3a4910424125
Ref: library/token token TILDE10424189
Ref: 3a4a10424189
Ref: library/token token CIRCUMFLEX10424245
Ref: 3a4b10424245
Ref: library/token token LEFTSHIFT10424306
Ref: 3a4c10424306
Ref: library/token token RIGHTSHIFT10424367
Ref: 3a4d10424367
Ref: library/token token DOUBLESTAR10424429
Ref: 3a4e10424429
Ref: library/token token PLUSEQUAL10424491
Ref: 3a4f10424491
Ref: library/token token MINEQUAL10424552
Ref: 3a5010424552
Ref: library/token token STAREQUAL10424612
Ref: 3a5110424612
Ref: library/token token SLASHEQUAL10424673
Ref: 3a5210424673
Ref: library/token token PERCENTEQUAL10424735
Ref: 3a5310424735
Ref: library/token token AMPEREQUAL10424799
Ref: 3a5410424799
Ref: library/token token VBAREQUAL10424861
Ref: 3a5510424861
Ref: library/token token CIRCUMFLEXEQUAL10424922
Ref: 3a5610424922
Ref: library/token token LEFTSHIFTEQUAL10424989
Ref: 3a5710424989
Ref: library/token token RIGHTSHIFTEQUAL10425056
Ref: 3a5810425056
Ref: library/token token DOUBLESTAREQUAL10425124
Ref: 3a5910425124
Ref: library/token token DOUBLESLASH10425192
Ref: 3a5a10425192
Ref: library/token token DOUBLESLASHEQUAL10425255
Ref: 3a5b10425255
Ref: library/token token AT10425324
Ref: 3a5c10425324
Ref: library/token token ATEQUAL10425377
Ref: 3a5d10425377
Ref: library/token token RARROW10425436
Ref: 3a5e10425436
Ref: library/token token ELLIPSIS10425494
Ref: 3a5f10425494
Ref: library/token token COLONEQUAL10425555
Ref: 3a6010425555
Ref: library/token token OP10425617
Ref: 3a6110425617
Ref: library/token token AWAIT10425637
Ref: 3a6210425637
Ref: library/token token ASYNC10425660
Ref: 3a6310425660
Ref: library/token token TYPE_IGNORE10425683
Ref: 3a6410425683
Ref: library/token token TYPE_COMMENT10425712
Ref: 3a6510425712
Ref: library/token token ERRORTOKEN10425742
Ref: 3a6610425742
Ref: library/token token N_TOKENS10425770
Ref: 3a6710425770
Ref: library/token token NT_OFFSET10425796
Ref: 3a6810425796
Ref: library/token token COMMENT10425937
Ref: 3a6910425937
Ref: library/token token NL10425999
Ref: 3a6a10425999
Ref: library/token token ENCODING10426236
Ref: 3a6b10426236
Ref: token --- 与Python解析树一起使用的常量-Footnote-110427295
Node: keyword --- 检验Python关键字10427359
Ref: library/keyword doc10427569
Ref: 3a6c10427569
Ref: library/keyword keyword-testing-for-python-keywords10427569
Ref: 3a6d10427569
Ref: library/keyword module-keyword10427569
Ref: a610427569
Ref: library/keyword keyword iskeyword10427839
Ref: 177f10427839
Ref: library/keyword keyword kwlist10427955
Ref: 3a6e10427955
Ref: library/keyword keyword issoftkeyword10428191
Ref: 3a6f10428191
Ref: library/keyword keyword softkwlist10428342
Ref: 3a7010428342
Ref: keyword --- 检验Python关键字-Footnote-110428648
Node: tokenize --- 对 Python 代码使用的标记解析器10428714
Ref: library/tokenize doc10428906
Ref: 3a7110428906
Ref: library/tokenize module-tokenize10428906
Ref: 11a10428906
Ref: library/tokenize tokenize-tokenizer-for-python-source10428906
Ref: 3a7210428906
Ref: tokenize --- 对 Python 代码使用的标记解析器-Footnote-110429855
Node: 对输入进行解析标记10429922
Ref: library/tokenize tokenizing-input10430067
Ref: 3a7310430067
Ref: library/tokenize tokenize tokenize10430191
Ref: d2310430191
Ref: library/tokenize tokenize generate_tokens10431506
Ref: 116b10431506
Ref: library/tokenize tokenize untokenize10432243
Ref: 3a7410432243
Ref: library/tokenize tokenize detect_encoding10433095
Ref: 1ddd10433095
Ref: library/tokenize tokenize open10434031
Ref: 1ddc10434031
Ref: library/tokenize tokenize TokenError10434204
Ref: 3a7510434204
Ref: 对输入进行解析标记-Footnote-110434643
Node: 命令行用法<3>10434692
Ref: library/tokenize command-line-usage10434856
Ref: 3a7610434856
Ref: library/tokenize tokenize-cli10434856
Ref: 3a7710434856
Ref: library/tokenize cmdoption-tokenize-h10435083
Ref: 3a7810435083
Ref: library/tokenize cmdoption-tokenize-e10435150
Ref: 3a7910435150
Node: 示例<45>10435344
Ref: library/tokenize examples10435472
Ref: 3a7a10435472
Node: tabnanny --- 模糊缩进检测10439877
Ref: library/tabnanny doc10440075
Ref: 3a7b10440075
Ref: library/tabnanny module-tabnanny10440075
Ref: 10010440075
Ref: library/tabnanny tabnanny-detection-of-ambiguous-indentation10440075
Ref: 3a7c10440075
Ref: library/tabnanny tabnanny check10440501
Ref: 3a7d10440501
Ref: library/tabnanny tabnanny verbose10440884
Ref: 3a7e10440884
Ref: library/tabnanny tabnanny filename_only10441032
Ref: 3a7f10441032
Ref: library/tabnanny tabnanny NannyNag10441225
Ref: 3a8010441225
Ref: library/tabnanny tabnanny process_tokens10441388
Ref: 3a8110441388
Ref: tabnanny --- 模糊缩进检测-Footnote-110441680
Node: pyclbr --- Python 模块浏览器支持10441747
Ref: library/pyclbr doc10441929
Ref: 3a8210441929
Ref: library/pyclbr module-pyclbr10441929
Ref: d810441929
Ref: library/pyclbr pyclbr-python-module-browser-support10441929
Ref: 3a8310441929
Ref: library/pyclbr pyclbr readmodule10442547
Ref: 129e10442547
Ref: library/pyclbr pyclbr readmodule_ex10443081
Ref: 129f10443081
Ref: pyclbr --- Python 模块浏览器支持-Footnote-110444045
Node: 函式物件10444110
Ref: library/pyclbr function-objects10444219
Ref: 3a8410444219
Ref: library/pyclbr pyclbr-function-objects10444219
Ref: 3a8510444219
Ref: library/pyclbr pyclbr Function file10444359
Ref: 3a8610444359
Ref: library/pyclbr pyclbr Function module10444429
Ref: 3a8710444429
Ref: library/pyclbr pyclbr Function name10444507
Ref: 3a8810444507
Ref: library/pyclbr pyclbr Function lineno10444556
Ref: 3a8910444556
Ref: library/pyclbr pyclbr Function parent10444634
Ref: 3a8a10444634
Ref: library/pyclbr pyclbr Function children10444769
Ref: 3a8b10444769
Node: Class 对象10444888
Ref: library/pyclbr class-objects10444997
Ref: 3a8c10444997
Ref: library/pyclbr pyclbr-class-objects10444997
Ref: 3a8d10444997
Ref: library/pyclbr pyclbr Class file10445184
Ref: 3a8e10445184
Ref: library/pyclbr pyclbr Class module10445248
Ref: 3a8f10445248
Ref: library/pyclbr pyclbr Class name10445320
Ref: 3a9010445320
Ref: library/pyclbr pyclbr Class lineno10445363
Ref: 3a9110445363
Ref: library/pyclbr pyclbr Class parent10445438
Ref: 3a9210445438
Ref: library/pyclbr pyclbr Class children10445561
Ref: 3a9310445561
Ref: library/pyclbr pyclbr Class super10445677
Ref: 3a9410445677
Ref: library/pyclbr pyclbr Class methods10445934
Ref: 3a9510445934
Node: py_compile --- 编译 Python 源文件10446095
Ref: library/py_compile doc10446290
Ref: 3a9610446290
Ref: library/py_compile module-py_compile10446290
Ref: d710446290
Ref: library/py_compile py-compile-compile-python-source-files10446290
Ref: 3a9710446290
Ref: library/py_compile py_compile PyCompileError10446829
Ref: 3a9810446829
Ref: library/py_compile py_compile compile10446935
Ref: 34310446935
Ref: library/py_compile py_compile PycInvalidationMode10450364
Ref: 3a9910450364
Ref: library/py_compile py_compile PycInvalidationMode TIMESTAMP10450770
Ref: 3a9b10450770
Ref: library/py_compile py_compile PycInvalidationMode CHECKED_HASH10450995
Ref: 3a9a10450995
Ref: library/py_compile py_compile PycInvalidationMode UNCHECKED_HASH10451214
Ref: 3a9c10451214
Ref: library/py_compile py_compile main10451628
Ref: 3a9d10451628
Ref: py_compile --- 编译 Python 源文件-Footnote-110452435
Ref: py_compile --- 编译 Python 源文件-Footnote-210452504
Ref: py_compile --- 编译 Python 源文件-Footnote-310452553
Ref: py_compile --- 编译 Python 源文件-Footnote-410452602
Ref: py_compile --- 编译 Python 源文件-Footnote-510452651
Node: compileall --- Byte-compile Python libraries10452700
Ref: library/compileall doc10452894
Ref: 3a9e10452894
Ref: library/compileall compileall-byte-compile-python-libraries10452894
Ref: 3a9f10452894
Ref: library/compileall module-compileall10452894
Ref: 2010452894
Ref: compileall --- Byte-compile Python libraries-Footnote-110453554
Node: Command-line use10453623
Ref: library/compileall command-line-use10453745
Ref: 3aa010453745
Ref: library/compileall cmdoption-compileall-arg-directory10453896
Ref: 3aa110453896
Ref: library/compileall cmdoption-compileall-arg-file10453928
Ref: 3aa210453928
Ref: library/compileall cmdoption-compileall-l10454182
Ref: 3aa310454182
Ref: library/compileall cmdoption-compileall-f10454338
Ref: 3aa410454338
Ref: library/compileall cmdoption-compileall-q10454415
Ref: 3aa510454415
Ref: library/compileall cmdoption-compileall-d10454605
Ref: 3aa610454605
Ref: library/compileall cmdoption-compileall-s10454964
Ref: 3aa710454964
Ref: library/compileall cmdoption-compileall-p10454999
Ref: 3aa810454999
Ref: library/compileall cmdoption-compileall-x10455181
Ref: 3aa910455181
Ref: library/compileall cmdoption-compileall-i10455360
Ref: 3aaa10455360
Ref: library/compileall cmdoption-compileall-b10455568
Ref: 3aab10455568
Ref: library/compileall cmdoption-compileall-r10455900
Ref: 3aac10455900
Ref: library/compileall cmdoption-compileall-j10456176
Ref: 3aad10456176
Ref: library/compileall cmdoption-compileall-invalidation-mode10456361
Ref: 3aae10456361
Ref: library/compileall cmdoption-compileall-o10457175
Ref: 3aaf10457175
Ref: library/compileall cmdoption-compileall-e10457374
Ref: 3ab010457374
Ref: library/compileall cmdoption-compileall-hardlink-dupes10457460
Ref: 3ab110457460
Ref: Command-line use-Footnote-110458724
Node: Public functions10458773
Ref: library/compileall public-functions10458895
Ref: 3ab210458895
Ref: library/compileall compileall compile_dir10458950
Ref: 47a10458950
Ref: library/compileall compileall compile_file10463005
Ref: 7ae10463005
Ref: library/compileall compileall compile_path10465944
Ref: 7af10465944
Ref: Public functions-Footnote-110467604
Ref: Public functions-Footnote-210467653
Node: dis --- Python bytecode的反組譯器10467702
Ref: library/dis doc10467899
Ref: 3ab310467899
Ref: library/dis dis-disassembler-for-python-bytecode10467899
Ref: 3ab410467899
Ref: library/dis module-dis10467899
Ref: 3710467899
Ref: dis --- Python bytecode的反組譯器-Footnote-110469110
Node: 字节码分析10469172
Ref: library/dis bytecode-analysis10469283
Ref: 3ab510469283
Ref: library/dis dis Bytecode10469496
Ref: 92410469496
Ref: library/dis dis Bytecode from_traceback10470395
Ref: 92610470395
Ref: library/dis dis Bytecode codeobj10470585
Ref: 3ab610470585
Ref: library/dis dis Bytecode first_line10470648
Ref: 3ab710470648
Ref: library/dis dis Bytecode dis10470741
Ref: 92510470741
Ref: library/dis dis Bytecode info10470914
Ref: 3ab810470914
Node: 分析函数10471341
Ref: library/dis analysis-functions10471482
Ref: 3ab910471482
Ref: library/dis dis code_info10471717
Ref: c9c10471717
Ref: library/dis dis show_code10472192
Ref: 91f10472192
Ref: library/dis dis dis10472613
Ref: 48a10472613
Ref: library/dis dis distb10473856
Ref: 92010473856
Ref: library/dis dis disassemble10474207
Ref: 92110474207
Ref: library/dis dis disco10474266
Ref: 3aba10474266
Ref: library/dis dis get_instructions10474996
Ref: 92310474996
Ref: library/dis dis findlinestarts10475552
Ref: 3abb10475552
Ref: library/dis dis findlabels10475974
Ref: 3abc10475974
Ref: library/dis dis stack_effect10476150
Ref: 92710476150
Ref: 分析函数-Footnote-110476696
Node: Python字节码说明10476773
Ref: library/dis bytecodes10476914
Ref: 3abd10476914
Ref: library/dis python-bytecode-instructions10476914
Ref: 3abe10476914
Ref: library/dis dis Instruction10477115
Ref: 92210477115
Ref: library/dis dis Instruction opcode10477181
Ref: 3abf10477181
Ref: library/dis dis Instruction opname10477340
Ref: 3ac110477340
Ref: library/dis dis Instruction arg10477402
Ref: 3ac210477402
Ref: library/dis dis Instruction argval10477499
Ref: 3ac310477499
Ref: library/dis dis Instruction argrepr10477595
Ref: 3ac410477595
Ref: library/dis dis Instruction offset10477664
Ref: 3ac510477664
Ref: library/dis dis Instruction starts_line10477738
Ref: 3ac610477738
Ref: library/dis dis Instruction is_jump_target10477840
Ref: 3ac710477840
Ref: library/dis opcode-NOP10478051
Ref: 3ac810478051
Ref: library/dis opcode-POP_TOP10478133
Ref: 3ac910478133
Ref: library/dis opcode-ROT_TWO10478194
Ref: 3aca10478194
Ref: library/dis opcode-ROT_THREE10478258
Ref: 3acb10478258
Ref: library/dis opcode-ROT_FOUR10478375
Ref: 3fb10478375
Ref: library/dis opcode-DUP_TOP10478542
Ref: 3acc10478542
Ref: library/dis opcode-DUP_TOP_TWO10478624
Ref: 3acd10478624
Ref: library/dis opcode-UNARY_POSITIVE10478848
Ref: 3ace10478848
Ref: library/dis opcode-UNARY_NEGATIVE10478910
Ref: 3acf10478910
Ref: library/dis opcode-UNARY_NOT10478972
Ref: 3ad010478972
Ref: library/dis opcode-UNARY_INVERT10479032
Ref: 3ad110479032
Ref: library/dis opcode-GET_ITER10479092
Ref: 3ad210479092
Ref: library/dis opcode-GET_YIELD_FROM_ITER10479153
Ref: 3ad310479153
Ref: library/dis opcode-BINARY_POWER10479530
Ref: 3ad410479530
Ref: library/dis opcode-BINARY_MULTIPLY10479597
Ref: 3ad510479597
Ref: library/dis opcode-BINARY_MATRIX_MULTIPLY10479666
Ref: 3ad610479666
Ref: library/dis opcode-BINARY_FLOOR_DIVIDE10479766
Ref: 3ad710479766
Ref: library/dis opcode-BINARY_TRUE_DIVIDE10479839
Ref: 3ad810479839
Ref: library/dis opcode-BINARY_MODULO10479911
Ref: 3ad910479911
Ref: library/dis opcode-BINARY_ADD10479978
Ref: 3ada10479978
Ref: library/dis opcode-BINARY_SUBTRACT10480042
Ref: 3adb10480042
Ref: library/dis opcode-BINARY_SUBSCR10480111
Ref: 3adc10480111
Ref: library/dis opcode-BINARY_LSHIFT10480177
Ref: 3add10480177
Ref: library/dis opcode-BINARY_RSHIFT10480245
Ref: 3ade10480245
Ref: library/dis opcode-BINARY_AND10480313
Ref: 3adf10480313
Ref: library/dis opcode-BINARY_XOR10480377
Ref: 3ae010480377
Ref: library/dis opcode-BINARY_OR10480441
Ref: 3ae110480441
Ref: library/dis opcode-INPLACE_POWER10480735
Ref: 3ae210480735
Ref: library/dis opcode-INPLACE_MULTIPLY10480809
Ref: 3ae310480809
Ref: library/dis opcode-INPLACE_MATRIX_MULTIPLY10480885
Ref: 3ae410480885
Ref: library/dis opcode-INPLACE_FLOOR_DIVIDE10480992
Ref: 3ae510480992
Ref: library/dis opcode-INPLACE_TRUE_DIVIDE10481073
Ref: 3ae610481073
Ref: library/dis opcode-INPLACE_MODULO10481152
Ref: 3ae710481152
Ref: library/dis opcode-INPLACE_ADD10481226
Ref: 3ae810481226
Ref: library/dis opcode-INPLACE_SUBTRACT10481297
Ref: 3ae910481297
Ref: library/dis opcode-INPLACE_LSHIFT10481373
Ref: 3aea10481373
Ref: library/dis opcode-INPLACE_RSHIFT10481448
Ref: 3aeb10481448
Ref: library/dis opcode-INPLACE_AND10481523
Ref: 3aec10481523
Ref: library/dis opcode-INPLACE_XOR10481594
Ref: 3aed10481594
Ref: library/dis opcode-INPLACE_OR10481665
Ref: 3aee10481665
Ref: library/dis opcode-STORE_SUBSCR10481735
Ref: 3aef10481735
Ref: library/dis opcode-DELETE_SUBSCR10481801
Ref: 3af010481801
Ref: library/dis opcode-GET_AWAITABLE10481884
Ref: 3af110481884
Ref: library/dis opcode-GET_AITER10482165
Ref: 3af210482165
Ref: library/dis opcode-GET_ANEXT10482341
Ref: 3af310482341
Ref: library/dis opcode-END_ASYNC_FOR10482522
Ref: 3fc10482522
Ref: library/dis opcode-BEFORE_ASYNC_WITH10482906
Ref: 3af410482906
Ref: library/dis opcode-SETUP_ASYNC_WITH10483102
Ref: 3af510483102
Ref: library/dis opcode-PRINT_EXPR10483212
Ref: 3af610483212
Ref: library/dis opcode-SET_ADD10483397
Ref: 3af710483397
Ref: library/dis opcode-LIST_APPEND10483496
Ref: 3af810483496
Ref: library/dis opcode-MAP_ADD10483605
Ref: 3fe10483605
Ref: library/dis opcode-RETURN_VALUE10484052
Ref: 3af910484052
Ref: library/dis opcode-YIELD_VALUE10484120
Ref: 3afa10484120
Ref: library/dis opcode-YIELD_FROM10484210
Ref: 3afb10484210
Ref: library/dis opcode-SETUP_ANNOTATIONS10484344
Ref: 71110484344
Ref: library/dis opcode-IMPORT_STAR10484634
Ref: 3afc10484634
Ref: library/dis opcode-POP_BLOCK10484857
Ref: 3afd10484857
Ref: library/dis opcode-POP_EXCEPT10484991
Ref: 3afe10484991
Ref: library/dis opcode-RERAISE10485252
Ref: 3aff10485252
Ref: library/dis opcode-WITH_EXCEPT_START10485346
Ref: 3b0010485346
Ref: library/dis opcode-LOAD_ASSERTION_ERROR10485613
Ref: 23e10485613
Ref: library/dis opcode-LOAD_BUILD_CLASS10485769
Ref: 3b0110485769
Ref: library/dis opcode-SETUP_WITH10485934
Ref: 3b0210485934
Ref: library/dis opcode-STORE_NAME10486627
Ref: 3b0410486627
Ref: library/dis opcode-DELETE_NAME10486884
Ref: 3b0710486884
Ref: library/dis opcode-UNPACK_SEQUENCE10487016
Ref: 3b0510487016
Ref: library/dis opcode-UNPACK_EX10487161
Ref: 3b0810487161
Ref: library/dis opcode-STORE_ATTR10487594
Ref: 3b0910487594
Ref: library/dis opcode-DELETE_ATTR10487731
Ref: 3b0a10487731
Ref: library/dis opcode-STORE_GLOBAL10487854
Ref: 3b0610487854
Ref: library/dis opcode-DELETE_GLOBAL10487968
Ref: 3b0b10487968
Ref: library/dis opcode-LOAD_CONST10488078
Ref: 3b0c10488078
Ref: library/dis opcode-LOAD_NAME10488161
Ref: 3b0d10488161
Ref: library/dis opcode-BUILD_TUPLE10488258
Ref: 3b0e10488258
Ref: library/dis opcode-BUILD_LIST10488391
Ref: 3b0f10488391
Ref: library/dis opcode-BUILD_SET10488492
Ref: 3b1010488492
Ref: library/dis opcode-BUILD_MAP10488592
Ref: 3b1110488592
Ref: library/dis opcode-BUILD_CONST_KEY_MAP10488902
Ref: 70c10488902
Ref: library/dis opcode-BUILD_STRING10489163
Ref: 70b10489163
Ref: library/dis opcode-LIST_TO_TUPLE10489303
Ref: 3b1210489303
Ref: library/dis opcode-LIST_EXTEND10489433
Ref: 3b1310489433
Ref: library/dis opcode-SET_UPDATE10489557
Ref: 3b1410489557
Ref: library/dis opcode-DICT_UPDATE10489679
Ref: 3b1510489679
Ref: library/dis opcode-DICT_MERGE10489803
Ref: 3b1610489803
Ref: library/dis opcode-LOAD_ATTR10489932
Ref: 3b1710489932
Ref: library/dis opcode-COMPARE_OP10490026
Ref: 24110490026
Ref: library/dis opcode-IS_OP10490146
Ref: 3b1810490146
Ref: library/dis opcode-CONTAINS_OP10490287
Ref: 3b1910490287
Ref: library/dis opcode-IMPORT_NAME10490434
Ref: 3b1a10490434
Ref: library/dis opcode-IMPORT_FROM10490797
Ref: 3b1b10490797
Ref: library/dis opcode-JUMP_FORWARD10491007
Ref: 3b1c10491007
Ref: library/dis opcode-POP_JUMP_IF_TRUE10491092
Ref: 3b1d10491092
Ref: library/dis opcode-POP_JUMP_IF_FALSE10491253
Ref: 3b1e10491253
Ref: library/dis opcode-JUMP_IF_NOT_EXC_MATCH10491415
Ref: 3b1f10491415
Ref: library/dis opcode-JUMP_IF_TRUE_OR_POP10491616
Ref: 3b2010491616
Ref: library/dis opcode-JUMP_IF_FALSE_OR_POP10491842
Ref: 3b2110491842
Ref: library/dis opcode-JUMP_ABSOLUTE10492069
Ref: 3b2210492069
Ref: library/dis opcode-FOR_ITER10492157
Ref: 3b2310492157
Ref: library/dis opcode-LOAD_GLOBAL10492488
Ref: 3b2410492488
Ref: library/dis opcode-SETUP_FINALLY10492596
Ref: 3b2510492596
Ref: library/dis opcode-LOAD_FAST10492809
Ref: 3b2610492809
Ref: library/dis opcode-STORE_FAST10492922
Ref: 3b0310492922
Ref: library/dis opcode-DELETE_FAST10493022
Ref: 3b2710493022
Ref: library/dis opcode-LOAD_CLOSURE10493112
Ref: 3b2810493112
Ref: library/dis opcode-LOAD_DEREF10493413
Ref: 3b2910493413
Ref: library/dis opcode-LOAD_CLASSDEREF10493598
Ref: a1310493598
Ref: library/dis opcode-STORE_DEREF10493814
Ref: 3b2a10493814
Ref: library/dis opcode-DELETE_DEREF10493953
Ref: 3b2b10493953
Ref: library/dis opcode-RAISE_VARARGS10494139
Ref: 3b2c10494139
Ref: library/dis opcode-CALL_FUNCTION10494555
Ref: 70e10494555
Ref: library/dis opcode-CALL_FUNCTION_KW10495075
Ref: 70f10495075
Ref: library/dis opcode-CALL_FUNCTION_EX10495873
Ref: 71010495873
Ref: library/dis opcode-LOAD_METHOD10496501
Ref: 5a710496501
Ref: library/dis opcode-CALL_METHOD10496985
Ref: 5a810496985
Ref: library/dis opcode-MAKE_FUNCTION10497510
Ref: 70d10497510
Ref: library/dis opcode-BUILD_SLICE10498149
Ref: 3b2d10498149
Ref: library/dis opcode-EXTENDED_ARG10498432
Ref: 3b2e10498432
Ref: library/dis opcode-FORMAT_VALUE10498744
Ref: 70a10498744
Ref: library/dis opcode-HAVE_ARGUMENT10499598
Ref: 3b2f10499598
Node: 操作码集合10499990
Ref: library/dis id110500110
Ref: 3b3010500110
Ref: library/dis opcode-collections10500110
Ref: 3ac010500110
Ref: library/dis dis opname10500217
Ref: 3b3110500217
Ref: library/dis dis opmap10500300
Ref: 3b3210500300
Ref: library/dis dis cmp_op10500367
Ref: 3b3310500367
Ref: library/dis dis hasconst10500432
Ref: 3b3410500432
Ref: library/dis dis hasfree10500496
Ref: 3b3510500496
Ref: library/dis dis hasname10500800
Ref: 3b3610500800
Ref: library/dis dis hasjrel10500872
Ref: 3b3710500872
Ref: library/dis dis hasjabs10500947
Ref: 3b3810500947
Ref: library/dis dis haslocal10501022
Ref: 3b3910501022
Ref: library/dis dis hascompare10501092
Ref: 3b3a10501092
Node: pickletools --- pickle 开发者工具集10501158
Ref: library/pickletools doc10501302
Ref: 3b3b10501302
Ref: library/pickletools module-pickletools10501302
Ref: cb10501302
Ref: library/pickletools pickletools-tools-for-pickle-developers10501302
Ref: 3b3c10501302
Ref: pickletools --- pickle 开发者工具集-Footnote-110502003
Node: 命令行语法<2>10502073
Ref: library/pickletools command-line-usage10502193
Ref: 3b3d10502193
Node: 命令行选项<5>10503099
Ref: library/pickletools command-line-options10503172
Ref: 3b3e10503172
Ref: library/pickletools cmdoption-pickletools-a10503220
Ref: 3b3f10503220
Ref: library/pickletools cmdoption-pickletools-o10503312
Ref: 3b4010503312
Ref: library/pickletools cmdoption-pickletools-l10503397
Ref: 3b4110503397
Ref: library/pickletools cmdoption-pickletools-m10503498
Ref: 3b4210503498
Ref: library/pickletools cmdoption-pickletools-p10503604
Ref: 3b4310503604
Node: 编程接口<2>10503748
Ref: library/pickletools programmatic-interface10503868
Ref: 3b4410503868
Ref: library/pickletools pickletools dis10503911
Ref: 66810503911
Ref: library/pickletools pickletools genops10504686
Ref: 3b4510504686
Ref: library/pickletools pickletools optimize10505087
Ref: 1e1b10505087
Node: 杂项服务10505369
Ref: library/misc doc10505519
Ref: 3b4610505519
Ref: library/misc misc10505519
Ref: 3b4710505519
Ref: library/misc miscellaneous-services10505519
Ref: 3b4810505519
Node: formatter --- 通用格式化输出10505745
Ref: library/formatter doc10505829
Ref: 3b4910505829
Ref: library/formatter formatter-generic-output-formatting10505829
Ref: 3b4a10505829
Ref: library/formatter module-formatter10505829
Ref: 8010505829
Node: The Formatter Interface10507393
Ref: library/formatter formatter-interface10507522
Ref: 3b4b10507522
Ref: library/formatter the-formatter-interface10507522
Ref: 3b4c10507522
Ref: library/formatter formatter AS_IS10507850
Ref: 3b4d10507850
Ref: library/formatter formatter formatter writer10508297
Ref: 3b4e10508297
Ref: library/formatter formatter formatter end_paragraph10508389
Ref: 3b4f10508389
Ref: library/formatter formatter formatter add_line_break10508542
Ref: 3b5010508542
Ref: library/formatter formatter formatter add_hor_rule10508697
Ref: 3b5110508697
Ref: library/formatter formatter formatter add_flowing_data10509016
Ref: 3b5210509016
Ref: library/formatter formatter formatter add_literal_data10509542
Ref: 3b5310509542
Ref: library/formatter formatter formatter add_label_data10509767
Ref: 3b5410509767
Ref: library/formatter formatter formatter flush_softspace10511200
Ref: 3b5510511200
Ref: library/formatter formatter formatter push_alignment10511471
Ref: 3b5610511471
Ref: library/formatter formatter formatter pop_alignment10511796
Ref: 3b5710511796
Ref: library/formatter formatter formatter push_font10511880
Ref: 3b5810511880
Ref: library/formatter formatter formatter pop_font10512267
Ref: 3b5910512267
Ref: library/formatter formatter formatter push_margin10512341
Ref: 3b5a10512341
Ref: library/formatter formatter formatter pop_margin10512714
Ref: 3b5b10512714
Ref: library/formatter formatter formatter push_style10512792
Ref: 3b5c10512792
Ref: library/formatter formatter formatter pop_style10513101
Ref: 3b5d10513101
Ref: library/formatter formatter formatter set_spacing10513374
Ref: 3b5e10513374
Ref: library/formatter formatter formatter assert_line_data10513469
Ref: 3b5f10513469
Node: Formatter Implementations10513833
Ref: library/formatter formatter-implementations10513991
Ref: 3b6010513991
Ref: library/formatter formatter-impls10513991
Ref: 3b6110513991
Ref: library/formatter formatter NullFormatter10514217
Ref: 3b6210514217
Ref: library/formatter formatter AbstractFormatter10514606
Ref: 3b6410514606
Node: The Writer Interface10514894
Ref: library/formatter the-writer-interface10515051
Ref: 3b6510515051
Ref: library/formatter writer-interface10515051
Ref: 3b6610515051
Ref: library/formatter formatter writer flush10515472
Ref: 3b6710515472
Ref: library/formatter formatter writer new_alignment10515565
Ref: 3b6810515565
Ref: library/formatter formatter writer new_font10515931
Ref: 3b6910515931
Ref: library/formatter formatter writer new_margin10516463
Ref: 3b6a10516463
Ref: library/formatter formatter writer new_spacing10516799
Ref: 3b6b10516799
Ref: library/formatter formatter writer new_styles10516889
Ref: 3b6c10516889
Ref: library/formatter formatter writer send_line_break10517229
Ref: 3b6d10517229
Ref: library/formatter formatter writer send_paragraph10517304
Ref: 3b6e10517304
Ref: library/formatter formatter writer send_hor_rule10517786
Ref: 3b6f10517786
Ref: library/formatter formatter writer send_flowing_data10518143
Ref: 3b7010518143
Ref: library/formatter formatter writer send_literal_data10518449
Ref: 3b7110518449
Ref: library/formatter formatter writer send_label_data10518885
Ref: 3b7210518885
Node: Writer Implementations10519197
Ref: library/formatter writer-implementations10519320
Ref: 3b7310519320
Ref: library/formatter writer-impls10519320
Ref: 3b7410519320
Ref: library/formatter formatter NullWriter10519578
Ref: 3b6310519578
Ref: library/formatter formatter AbstractWriter10519824
Ref: 3b7510519824
Ref: library/formatter formatter DumbWriter10520041
Ref: 3b7610520041
Node: Windows系统相关模块10520408
Ref: library/windows doc10520556
Ref: 3b7710520556
Ref: library/windows ms-windows-specific-services10520556
Ref: 3b7810520556
Ref: library/windows mswin-specific-services10520556
Ref: 14c710520556
Node: msilib --- Read and write Microsoft Installer files10521014
Ref: library/msilib doc10521186
Ref: 3b7910521186
Ref: library/msilib module-msilib10521186
Ref: b510521186
Ref: library/msilib msilib-read-and-write-microsoft-installer-files10521186
Ref: 3b7a10521186
Ref: library/msilib msilib FCICreate10522256
Ref: 3b7b10522256
Ref: library/msilib msilib UuidCreate10522755
Ref: 3b7c10522755
Ref: library/msilib msilib OpenDatabase10522949
Ref: 102010522949
Ref: library/msilib msilib CreateRecord10523499
Ref: 3b7d10523499
Ref: library/msilib msilib init_database10523662
Ref: 102110523662
Ref: library/msilib msilib add_data10524231
Ref: 3b7f10524231
Ref: library/msilib msilib Binary10524803
Ref: 3b8010524803
Ref: library/msilib msilib add_tables10525000
Ref: 3b8110525000
Ref: library/msilib msilib add_stream10525339
Ref: 3b8210525339
Ref: library/msilib msilib gen_uuid10525497
Ref: 3b8310525497
Ref: msilib --- Read and write Microsoft Installer files-Footnote-110525981
Ref: msilib --- Read and write Microsoft Installer files-Footnote-210526055
Ref: msilib --- Read and write Microsoft Installer files-Footnote-310526118
Ref: msilib --- Read and write Microsoft Installer files-Footnote-410526198
Node: Database Objects10526278
Ref: library/msilib database-objects10526403
Ref: 3b8410526403
Ref: library/msilib id110526403
Ref: 3b8510526403
Ref: library/msilib msilib Database OpenView10526456
Ref: 102210526456
Ref: library/msilib msilib Database Commit10526612
Ref: 3b8610526612
Ref: library/msilib msilib Database GetSummaryInformation10526754
Ref: 3b8710526754
Ref: library/msilib msilib Database Close10526964
Ref: 4b410526964
Ref: Database Objects-Footnote-110527235
Ref: Database Objects-Footnote-210527315
Ref: Database Objects-Footnote-310527395
Ref: Database Objects-Footnote-410527475
Node: View Objects10527555
Ref: library/msilib id210527716
Ref: 3b8810527716
Ref: library/msilib view-objects10527716
Ref: 3b8910527716
Ref: library/msilib msilib View Execute10527761
Ref: 3b8a10527761
Ref: library/msilib msilib View GetColumnInfo10527995
Ref: 3b8b10527995
Ref: library/msilib msilib View Fetch10528226
Ref: 3b8c10528226
Ref: library/msilib msilib View Modify10528345
Ref: 3b8d10528345
Ref: library/msilib msilib View Close10528902
Ref: 3b8e10528902
Ref: View Objects-Footnote-110529133
Ref: View Objects-Footnote-210529213
Ref: View Objects-Footnote-310529293
Ref: View Objects-Footnote-410529373
Ref: View Objects-Footnote-510529453
Node: Summary Information Objects10529533
Ref: library/msilib summary-information-objects10529692
Ref: 3b8f10529692
Ref: library/msilib summary-objects10529692
Ref: 3b9010529692
Ref: library/msilib msilib SummaryInformation GetProperty10529767
Ref: 10fe10529767
Ref: library/msilib msilib SummaryInformation GetPropertyCount10530364
Ref: 3b9110530364
Ref: library/msilib msilib SummaryInformation SetProperty10530522
Ref: 3b9210530522
Ref: library/msilib msilib SummaryInformation Persist10530821
Ref: 3b9310530821
Ref: Summary Information Objects-Footnote-110531155
Ref: Summary Information Objects-Footnote-210531235
Ref: Summary Information Objects-Footnote-310531315
Ref: Summary Information Objects-Footnote-410531395
Node: Record Objects10531475
Ref: library/msilib id310531628
Ref: 3b9410531628
Ref: library/msilib record-objects10531628
Ref: 3b9510531628
Ref: library/msilib msilib Record GetFieldCount10531677
Ref: 3b9610531677
Ref: library/msilib msilib Record GetInteger10531814
Ref: 3b9710531814
Ref: library/msilib msilib Record GetString10531957
Ref: 3b9810531957
Ref: library/msilib msilib Record SetString10532097
Ref: 3b9910532097
Ref: library/msilib msilib Record SetStream10532265
Ref: 3b9a10532265
Ref: library/msilib msilib Record SetInteger10532470
Ref: 3b9b10532470
Ref: library/msilib msilib Record ClearData10532639
Ref: 3b9c10532639
Ref: Record Objects-Footnote-110532925
Ref: Record Objects-Footnote-210533005
Ref: Record Objects-Footnote-310533085
Ref: Record Objects-Footnote-410533165
Ref: Record Objects-Footnote-510533245
Node: Errors10533325
Ref: library/msilib errors10533462
Ref: 3b9d10533462
Ref: library/msilib msi-errors10533462
Ref: 3b9e10533462
Node: CAB Objects10533610
Ref: library/msilib cab10533750
Ref: 3b9f10533750
Ref: library/msilib cab-objects10533750
Ref: 3ba010533750
Ref: library/msilib msilib CAB10533793
Ref: 3ba110533793
Ref: library/msilib msilib CAB append10534155
Ref: 3ba210534155
Ref: library/msilib msilib CAB commit10534510
Ref: 3ba310534510
Node: Directory Objects10534720
Ref: library/msilib directory-objects10534869
Ref: 3ba410534869
Ref: library/msilib msi-directory10534869
Ref: 3ba510534869
Ref: library/msilib msilib Directory10534924
Ref: 3ba610534924
Ref: library/msilib msilib Directory start_component10535694
Ref: 10ff10535694
Ref: library/msilib msilib Directory add_file10536241
Ref: 3ba710536241
Ref: library/msilib msilib Directory glob10536759
Ref: 3ba810536759
Ref: library/msilib msilib Directory remove_pyc10536979
Ref: 3ba910536979
Ref: Directory Objects-Footnote-110537200
Ref: Directory Objects-Footnote-210537280
Ref: Directory Objects-Footnote-310537360
Ref: Directory Objects-Footnote-410537440
Node: 相关特性<3>10537520
Ref: library/msilib features10537669
Ref: 3baa10537669
Ref: library/msilib id410537669
Ref: 3bab10537669
Ref: library/msilib msilib Feature10537710
Ref: 3bac10537710
Ref: library/msilib msilib Feature set_current10538109
Ref: 3bad10538109
Ref: 相关特性<3>-Footnote-110538415
Node: GUI classes10538495
Ref: library/msilib gui-classes10538645
Ref: 3bae10538645
Ref: library/msilib msi-gui10538645
Ref: 3baf10538645
Ref: library/msilib msilib Control10538926
Ref: 3bb010538926
Ref: library/msilib msilib Control event10539100
Ref: 3bb110539100
Ref: library/msilib msilib Control mapping10539253
Ref: 3bb210539253
Ref: library/msilib msilib Control condition10539381
Ref: 3bb310539381
Ref: library/msilib msilib RadioButtonGroup10539526
Ref: 3bb410539526
Ref: library/msilib msilib RadioButtonGroup add10539725
Ref: 3bb510539725
Ref: library/msilib msilib Dialog10540001
Ref: 3bb610540001
Ref: library/msilib msilib Dialog control10540307
Ref: 3bb710540307
Ref: library/msilib msilib Dialog text10540676
Ref: 3bb810540676
Ref: library/msilib msilib Dialog bitmap10540799
Ref: 3bb910540799
Ref: library/msilib msilib Dialog line10540914
Ref: 3bba10540914
Ref: library/msilib msilib Dialog pushbutton10541019
Ref: 3bbb10541019
Ref: library/msilib msilib Dialog radiogroup10541183
Ref: 3bbc10541183
Ref: library/msilib msilib Dialog checkbox10541363
Ref: 3bbd10541363
Ref: GUI classes-Footnote-110541729
Ref: GUI classes-Footnote-210541809
Ref: GUI classes-Footnote-310541889
Ref: GUI classes-Footnote-410541969
Ref: GUI classes-Footnote-510542049
Ref: GUI classes-Footnote-610542129
Ref: GUI classes-Footnote-710542209
Node: Precomputed tables10542289
Ref: library/msilib msi-tables10542415
Ref: 3bbe10542415
Ref: library/msilib precomputed-tables10542415
Ref: 3bbf10542415
Ref: library/msilib msilib schema10542628
Ref: 3b7e10542628
Ref: library/msilib msilib sequence10542845
Ref: 3bc010542845
Ref: library/msilib msilib text10543080
Ref: 3bc110543080
Node: msvcrt --- 来自 MS VC++ 运行时的有用例程10543221
Ref: library/msvcrt doc10543436
Ref: 3bc210543436
Ref: library/msvcrt module-msvcrt10543436
Ref: b610543436
Ref: library/msvcrt msvcrt-useful-routines-from-the-ms-vc-runtime10543436
Ref: 3bc310543436
Node: 文件操作10544295
Ref: library/msvcrt file-operations10544416
Ref: 3bc410544416
Ref: library/msvcrt msvcrt-files10544416
Ref: 3bc510544416
Ref: library/msvcrt msvcrt locking10544457
Ref: 367310544457
Ref: library/msvcrt msvcrt LK_LOCK10545073
Ref: 3bc610545073
Ref: library/msvcrt msvcrt LK_RLCK10545098
Ref: 3bc710545098
Ref: library/msvcrt msvcrt LK_NBLCK10545342
Ref: 3bc810545342
Ref: library/msvcrt msvcrt LK_NBRLCK10545368
Ref: 3bc910545368
Ref: library/msvcrt msvcrt LK_UNLCK10545510
Ref: 3bca10545510
Ref: library/msvcrt msvcrt setmode10545610
Ref: 3bcb10545610
Ref: library/msvcrt msvcrt open_osfhandle10545866
Ref: 367410545866
Ref: library/msvcrt msvcrt get_osfhandle10546357
Ref: 367210546357
Node: 控制台 I/O10546619
Ref: library/msvcrt console-i-o10546761
Ref: 3bcc10546761
Ref: library/msvcrt msvcrt-console10546761
Ref: 3bcd10546761
Ref: library/msvcrt msvcrt kbhit10546805
Ref: 3bce10546805
Ref: library/msvcrt msvcrt getch10546906
Ref: 3bcf10546906
Ref: library/msvcrt msvcrt getwch10547352
Ref: 3bd010547352
Ref: library/msvcrt msvcrt getche10547458
Ref: 3bd110547458
Ref: library/msvcrt msvcrt getwche10547597
Ref: 3bd210547597
Ref: library/msvcrt msvcrt putch10547705
Ref: 3bd310547705
Ref: library/msvcrt msvcrt putwch10547804
Ref: 3bd410547804
Ref: library/msvcrt msvcrt ungetch10547922
Ref: 3bd510547922
Ref: library/msvcrt msvcrt ungetwch10548112
Ref: 3bd610548112
Node: 其他函数10548234
Ref: library/msvcrt msvcrt-other10548355
Ref: 3bd710548355
Ref: library/msvcrt other-functions10548355
Ref: 3bd810548355
Ref: library/msvcrt msvcrt heapmin10548396
Ref: 3bd910548396
Node: winreg --- Windows 注册表访问10548570
Ref: library/winreg doc10548785
Ref: 3bda10548785
Ref: library/winreg module-winreg10548785
Ref: 13310548785
Ref: library/winreg winreg-windows-registry-access10548785
Ref: 3bdb10548785
Ref: library/winreg exception-changed10549178
Ref: 3bdd10549178
Node: 函数<12>10549398
Ref: library/winreg functions10549497
Ref: 3bde10549497
Ref: library/winreg id110549497
Ref: 3bdf10549497
Ref: library/winreg winreg CloseKey10549563
Ref: 3be010549563
Ref: library/winreg winreg ConnectRegistry10549860
Ref: 367810549860
Ref: library/winreg winreg CreateKey10550534
Ref: 367910550534
Ref: library/winreg winreg CreateKeyEx10551460
Ref: 367a10551460
Ref: library/winreg winreg DeleteKey10552726
Ref: 367b10552726
Ref: library/winreg winreg DeleteKeyEx10553449
Ref: 367c10553449
Ref: library/winreg winreg DeleteValue10554835
Ref: 367d10554835
Ref: library/winreg winreg EnumKey10555211
Ref: 368010555211
Ref: library/winreg winreg EnumValue10555855
Ref: 368110555855
Ref: library/winreg winreg ExpandEnvironmentStrings10557069
Ref: 368210557069
Ref: library/winreg winreg FlushKey10557422
Ref: 3be610557422
Ref: library/winreg winreg LoadKey10558195
Ref: 368310558195
Ref: library/winreg winreg OpenKey10559295
Ref: 368410559295
Ref: library/winreg winreg OpenKeyEx10559366
Ref: 3be910559366
Ref: library/winreg winreg QueryInfoKey10560424
Ref: 368610560424
Ref: library/winreg winreg QueryValue10561289
Ref: 368810561289
Ref: library/winreg winreg QueryValueEx10562109
Ref: 368910562109
Ref: library/winreg winreg SaveKey10562930
Ref: 368a10562930
Ref: library/winreg winreg SetValue10563887
Ref: 368b10563887
Ref: library/winreg winreg SetValueEx10564960
Ref: 368c10564960
Ref: library/winreg winreg DisableReflectionKey10566093
Ref: 367e10566093
Ref: library/winreg winreg EnableReflectionKey10566714
Ref: 367f10566714
Ref: library/winreg winreg QueryReflectionKey10567202
Ref: 368710567202
Ref: 函数<12>-Footnote-110567704
Ref: 函数<12>-Footnote-210567778
Ref: 函数<12>-Footnote-310567855
Node: 常数<7>10567932
Ref: library/winreg constants10568061
Ref: 3bee10568061
Ref: library/winreg id210568061
Ref: 3bef10568061
Node: HKEY_* 常量10568228
Ref: library/winreg hkey-constants10568308
Ref: 3be210568308
Ref: library/winreg id310568308
Ref: 3bf010568308
Ref: library/winreg winreg HKEY_CLASSES_ROOT10568353
Ref: 3bf110568353
Ref: library/winreg winreg HKEY_CURRENT_USER10568562
Ref: 3bf210568562
Ref: library/winreg winreg HKEY_LOCAL_MACHINE10568791
Ref: 3be810568791
Ref: library/winreg winreg HKEY_USERS10568973
Ref: 3be710568973
Ref: library/winreg winreg HKEY_PERFORMANCE_DATA10569120
Ref: 3bf310569120
Ref: library/winreg winreg HKEY_CURRENT_CONFIG10569326
Ref: 3bf410569326
Ref: library/winreg winreg HKEY_DYN_DATA10569434
Ref: 3bf510569434
Node: 访问权限10569523
Ref: library/winreg access-rights10569633
Ref: 3be410569633
Ref: library/winreg id410569633
Ref: 3bf610569633
Ref: library/winreg winreg KEY_ALL_ACCESS10569737
Ref: 3bf710569737
Ref: library/winreg winreg KEY_WRITE10570042
Ref: 3be310570042
Ref: library/winreg winreg KEY_READ10570196
Ref: 3bea10570196
Ref: library/winreg winreg KEY_EXECUTE10570370
Ref: 3bfd10570370
Ref: library/winreg winreg KEY_QUERY_VALUE10570441
Ref: 3bf810570441
Ref: library/winreg winreg KEY_SET_VALUE10570521
Ref: 3bec10570521
Ref: library/winreg winreg KEY_CREATE_SUB_KEY10570614
Ref: 3bf910570614
Ref: library/winreg winreg KEY_ENUMERATE_SUB_KEYS10570703
Ref: 3bfa10570703
Ref: library/winreg winreg KEY_NOTIFY10570796
Ref: 3bfb10570796
Ref: library/winreg winreg KEY_CREATE_LINK10570892
Ref: 3bfc10570892
Ref: 访问权限-Footnote-110571026
Node: 64 位系统特有10571103
Ref: library/winreg bit-access-rights10571170
Ref: 3bfe10571170
Ref: library/winreg bit-specific10571170
Ref: 3bff10571170
Ref: library/winreg winreg KEY_WOW64_64KEY10571282
Ref: 3c0010571282
Ref: library/winreg winreg KEY_WOW64_32KEY10571403
Ref: 3c0110571403
Ref: 64 位系统特有-Footnote-110571560
Node: 注册表值的类型10571632
Ref: library/winreg id510571720
Ref: 3c0210571720
Ref: library/winreg value-types10571720
Ref: 3bed10571720
Ref: library/winreg winreg REG_BINARY10571820
Ref: 3c0310571820
Ref: library/winreg winreg REG_DWORD10571889
Ref: 3c0410571889
Ref: library/winreg winreg REG_DWORD_LITTLE_ENDIAN10571939
Ref: 3c0510571939
Ref: library/winreg winreg REG_DWORD_BIG_ENDIAN10572059
Ref: 3c0610572059
Ref: library/winreg winreg REG_EXPAND_SZ10572141
Ref: 3be510572141
Ref: library/winreg winreg REG_LINK10572252
Ref: 3c0710572252
Ref: library/winreg winreg REG_MULTI_SZ10572309
Ref: 10ea10572309
Ref: library/winreg winreg REG_NONE10572468
Ref: 3c0810572468
Ref: library/winreg winreg REG_QWORD10572523
Ref: 6a910572523
Ref: library/winreg winreg REG_QWORD_LITTLE_ENDIAN10572597
Ref: 3c0910572597
Ref: library/winreg winreg REG_RESOURCE_LIST10572740
Ref: 3c0a10572740
Ref: library/winreg winreg REG_FULL_RESOURCE_DESCRIPTOR10572816
Ref: 3c0b10572816
Ref: library/winreg winreg REG_RESOURCE_REQUIREMENTS_LIST10572885
Ref: 3c0c10572885
Ref: library/winreg winreg REG_SZ10572962
Ref: 3beb10572962
Ref: 注册表值的类型-Footnote-110573060
Node: 注册表句柄对象10573137
Ref: library/winreg handle-object10573247
Ref: 3bdc10573247
Ref: library/winreg registry-handle-objects10573247
Ref: 3c0d10573247
Ref: library/winreg winreg PyHKEY Close10574216
Ref: 3be110574216
Ref: library/winreg winreg PyHKEY Detach10574343
Ref: 368510574343
Ref: library/winreg winreg PyHKEY __enter__10574863
Ref: 3c0e10574863
Ref: library/winreg winreg PyHKEY __exit__10574901
Ref: 3c0f10574901
Node: winsound —— Windows 系统的声音播放接口10575266
Ref: library/winsound doc10575422
Ref: 3c1010575422
Ref: library/winsound module-winsound10575422
Ref: 13410575422
Ref: library/winsound winsound-sound-playing-interface-for-windows10575422
Ref: 3c1110575422
Ref: library/winsound winsound Beep10575731
Ref: 6ab10575731
Ref: library/winsound winsound PlaySound10576075
Ref: 6ad10576075
Ref: library/winsound winsound MessageBeep10576570
Ref: 6ac10576570
Ref: library/winsound winsound SND_FILENAME10577117
Ref: 3c1210577117
Ref: library/winsound winsound SND_ALIAS10577249
Ref: 3c1310577249
Ref: library/winsound winsound SND_LOOP10578875
Ref: 3c1510578875
Ref: library/winsound winsound SND_MEMORY10579056
Ref: 3c1710579056
Ref: library/winsound winsound SND_PURGE10579397
Ref: 3c1810579397
Ref: library/winsound winsound SND_ASYNC10579538
Ref: 3c1610579538
Ref: library/winsound winsound SND_NODEFAULT10579617
Ref: 3c1410579617
Ref: library/winsound winsound SND_NOSTOP10579724
Ref: 3c1910579724
Ref: library/winsound winsound SND_NOWAIT10579795
Ref: 3c1a10579795
Ref: library/winsound winsound MB_ICONASTERISK10579943
Ref: 3c1b10579943
Ref: library/winsound winsound MB_ICONEXCLAMATION10580022
Ref: 3c1c10580022
Ref: library/winsound winsound MB_ICONHAND10580108
Ref: 3c1d10580108
Ref: library/winsound winsound MB_ICONQUESTION10580180
Ref: 3c1e10580180
Ref: library/winsound winsound MB_OK10580260
Ref: 3c1f10580260
Node: Unix 专有服务10580329
Ref: library/unix doc10580483
Ref: 3c2010580483
Ref: library/unix unix10580483
Ref: 3c2110580483
Ref: library/unix unix-specific-services10580483
Ref: 3c2210580483
Node: posix --- 最常见的 POSIX 系统调用10581407
Ref: library/posix doc10581540
Ref: 3c2310581540
Ref: library/posix module-posix10581540
Ref: d110581540
Ref: library/posix posix-the-most-common-posix-system-calls10581540
Ref: 3c2410581540
Node: 大文件支持10582632
Ref: library/posix large-file-support10582755
Ref: 3c2510582755
Ref: library/posix posix-large-files10582755
Ref: 3c2610582755
Node: 重要的模块内容10583756
Ref: library/posix notable-module-contents10583879
Ref: 3c2710583879
Ref: library/posix posix-contents10583879
Ref: 3c2810583879
Ref: library/posix posix environ10584043
Ref: 3c2910584043
Node: pwd --- 用户密码数据库10585093
Ref: library/pwd doc10585263
Ref: 3c2a10585263
Ref: library/pwd module-pwd10585263
Ref: d610585263
Ref: library/pwd pwd-the-password-database10585263
Ref: 3c2b10585263
Ref: library/pwd pwd getpwuid10587359
Ref: 114f10587359
Ref: library/pwd pwd getpwnam10587464
Ref: 116110587464
Ref: library/pwd pwd getpwall10587561
Ref: 3c2c10587561
Node: spwd —— shadow 密码库10587865
Ref: library/spwd doc10588014
Ref: 3c2d10588014
Ref: library/spwd module-spwd10588014
Ref: f110588014
Ref: library/spwd spwd-the-shadow-password-database10588014
Ref: 3c2e10588014
Ref: library/spwd spwd getspnam10590025
Ref: 6f510590025
Ref: library/spwd spwd getspall10590246
Ref: 3c2f10590246
Node: grp --- 组数据库10590540
Ref: library/grp doc10590700
Ref: 3c3010590700
Ref: library/grp grp-the-group-database10590700
Ref: 3c3110590700
Ref: library/grp module-grp10590700
Ref: 8a10590700
Ref: library/grp grp getgrgid10592078
Ref: 6d610592078
Ref: library/grp grp getgrnam10592394
Ref: 116210592394
Ref: library/grp grp getgrall10592558
Ref: 3c3210592558
Node: crypt —— 检查 Unix 口令的函数10592829
Ref: library/crypt doc10592999
Ref: 3c3310592999
Ref: library/crypt crypt-function-to-check-unix-passwords10592999
Ref: 3c3410592999
Ref: library/crypt module-crypt10592999
Ref: 2810592999
Ref: crypt —— 检查 Unix 口令的函数-Footnote-110593872
Node: 哈希方法10593937
Ref: library/crypt hashing-methods10594047
Ref: 3c3510594047
Ref: library/crypt crypt METHOD_SHA51210594220
Ref: 3c3610594220
Ref: library/crypt crypt METHOD_SHA25610594414
Ref: 3c3710594414
Ref: library/crypt crypt METHOD_BLOWFISH10594588
Ref: 3c3810594588
Ref: library/crypt crypt METHOD_MD510594774
Ref: 3c3910594774
Ref: library/crypt crypt METHOD_CRYPT10594940
Ref: 70010594940
Node: 模块属性10595086
Ref: library/crypt module-attributes10595220
Ref: 3c3a10595220
Ref: library/crypt crypt methods10595280
Ref: 3c3b10595280
Node: 模块函数<2>10595438
Ref: library/crypt module-functions10595570
Ref: 3c3c10595570
Ref: library/crypt crypt crypt10595660
Ref: 3c3d10595660
Ref: library/crypt crypt mksalt10596975
Ref: 48410596975
Node: 示例<46>10597765
Ref: library/crypt examples10597876
Ref: 3c3e10597876
Node: termios --- POSIX 风格的 tty 控制10598973
Ref: library/termios doc10599149
Ref: 3c3f10599149
Ref: library/termios module-termios10599149
Ref: 10410599149
Ref: library/termios termios-posix-style-tty-control10599149
Ref: 3c4010599149
Ref: library/termios termios tcgetattr10600112
Ref: 3c4110600112
Ref: library/termios termios tcsetattr10600651
Ref: 3c4210600651
Ref: library/termios termios tcsendbreak10601098
Ref: 3c4310601098
Ref: library/termios termios tcdrain10601325
Ref: 3c4410601325
Ref: library/termios termios tcflush10601450
Ref: 3c4510601450
Ref: library/termios termios tcflow10601714
Ref: 3c4610601714
Node: 示例<47>10602129
Ref: library/termios example10602214
Ref: 3c4710602214
Ref: library/termios termios-example10602214
Ref: 3c4810602214
Node: tty --- 终端控制功能10602958
Ref: library/tty doc10603117
Ref: 3c4910603117
Ref: library/tty module-tty10603117
Ref: 11e10603117
Ref: library/tty tty-terminal-control-functions10603117
Ref: 3c4a10603117
Ref: library/tty tty setraw10603493
Ref: 3c4b10603493
Ref: library/tty tty setcbreak10603723
Ref: 3c4c10603723
Ref: tty --- 终端控制功能-Footnote-110604081
Node: pty --- 伪终端工具10604143
Ref: library/pty doc10604305
Ref: 3c4d10604305
Ref: library/pty module-pty10604305
Ref: d510604305
Ref: library/pty pty-pseudo-terminal-utilities10604305
Ref: 3c4e10604305
Ref: library/pty pty fork10604839
Ref: 3c4f10604839
Ref: library/pty pty openpty10605213
Ref: 3c5010605213
Ref: library/pty pty spawn10605473
Ref: 97f10605473
Ref: pty --- 伪终端工具-Footnote-110607468
Ref: pty --- 伪终端工具-Footnote-210607530
Node: 示例<48>10607573
Ref: library/pty example10607643
Ref: 3c5110607643
Node: fcntl —— 系统调用 fcntl 和 ioctl10608810
Ref: library/fcntl doc10608974
Ref: 3c5210608974
Ref: library/fcntl fcntl-the-fcntl-and-ioctl-system-calls10608974
Ref: 3c5310608974
Ref: library/fcntl module-fcntl10608974
Ref: 7c10608974
Ref: library/fcntl fcntl fcntl10610319
Ref: 27e810610319
Ref: library/fcntl fcntl ioctl10611565
Ref: ea210611565
Ref: library/fcntl fcntl flock10613587
Ref: 367110613587
Ref: library/fcntl fcntl lockf10614076
Ref: e1710614076
Node: pipes --- 终端管道接口10616571
Ref: library/pipes doc10616743
Ref: 3c5410616743
Ref: library/pipes module-pipes10616743
Ref: cc10616743
Ref: library/pipes pipes-interface-to-shell-pipelines10616743
Ref: 3c5510616743
Ref: library/pipes pipes Template10617255
Ref: 3c5610617255
Ref: pipes --- 终端管道接口-Footnote-110617614
Node: 模板对象10617678
Ref: library/pipes id110617755
Ref: 3c5710617755
Ref: library/pipes template-objects10617755
Ref: 3c5810617755
Ref: library/pipes pipes Template reset10617828
Ref: 3c5910617828
Ref: library/pipes pipes Template clone10617917
Ref: 3c5a10617917
Ref: library/pipes pipes Template debug10618003
Ref: 3c5b10618003
Ref: library/pipes pipes Template append10618261
Ref: 3c5c10618261
Ref: library/pipes pipes Template prepend10618952
Ref: 3c5d10618952
Ref: library/pipes pipes Template open10619112
Ref: 3c5e10619112
Ref: library/pipes pipes Template copy10619315
Ref: 3c5f10619315
Node: resource --- 资源使用信息10619420
Ref: library/resource doc10619584
Ref: 3c6010619584
Ref: library/resource module-resource10619584
Ref: e010619584
Ref: library/resource resource-resource-usage-information10619584
Ref: 3c6110619584
Ref: library/resource resource error10620004
Ref: 3c6210620004
Ref: resource --- 资源使用信息-Footnote-110620274
Node: 资源限制<2>10620323
Ref: library/resource resource-limits10620427
Ref: 3c6310620427
Ref: library/resource resource RLIM_INFINITY10621189
Ref: 3c6410621189
Ref: library/resource resource getrlimit10621275
Ref: 3c6510621275
Ref: library/resource resource setrlimit10621552
Ref: 364310621552
Ref: library/resource resource prlimit10622669
Ref: 98610622669
Ref: library/resource resource RLIMIT_CORE10624144
Ref: 364410624144
Ref: library/resource resource RLIMIT_CPU10624387
Ref: 3c6710624387
Ref: library/resource resource RLIMIT_FSIZE10624753
Ref: 3c6810624753
Ref: library/resource resource RLIMIT_DATA10624838
Ref: 3c6910624838
Ref: library/resource resource RLIMIT_STACK10624931
Ref: 3c6a10624931
Ref: library/resource resource RLIMIT_RSS10625089
Ref: 3c6b10625089
Ref: library/resource resource RLIMIT_NPROC10625178
Ref: 3c6c10625178
Ref: library/resource resource RLIMIT_NOFILE10625263
Ref: 3c6610625263
Ref: library/resource resource RLIMIT_OFILE10625358
Ref: 3c6d10625358
Ref: library/resource resource RLIMIT_MEMLOCK10625445
Ref: 3c6e10625445
Ref: library/resource resource RLIMIT_VMEM10625538
Ref: 3c6f10625538
Ref: library/resource resource RLIMIT_AS10625625
Ref: 3c7010625625
Ref: library/resource resource RLIMIT_MSGQUEUE10625737
Ref: 98710625737
Ref: library/resource resource RLIMIT_NICE10625914
Ref: 98810625914
Ref: library/resource resource RLIMIT_RTPRIO10626102
Ref: 98910626102
Ref: library/resource resource RLIMIT_RTTIME10626256
Ref: 98a10626256
Ref: library/resource resource RLIMIT_SIGPENDING10626522
Ref: 98b10626522
Ref: library/resource resource RLIMIT_SBSIZE10626691
Ref: 98c10626691
Ref: library/resource resource RLIMIT_SWAP10627008
Ref: 98d10627008
Ref: library/resource resource RLIMIT_NPTS10627409
Ref: 98e10627409
Ref: 资源限制<2>-Footnote-110627616
Node: 资源用量10627683
Ref: library/resource resource-usage10627787
Ref: 3c7110627787
Ref: library/resource resource getrusage10627880
Ref: e5e10627880
Ref: library/resource resource getpagesize10632133
Ref: 3c7210632133
Ref: library/resource resource RUSAGE_SELF10632389
Ref: 3c7310632389
Ref: library/resource resource RUSAGE_CHILDREN10632558
Ref: 3c7410632558
Ref: library/resource resource RUSAGE_BOTH10632716
Ref: 3c7510632716
Ref: library/resource resource RUSAGE_THREAD10632882
Ref: 3c7610632882
Node: nis --- Sun 的 NIS 黄页 接口10633063
Ref: library/nis doc10633220
Ref: 3c7710633220
Ref: library/nis module-nis10633220
Ref: bf10633220
Ref: library/nis nis-interface-to-sun-s-nis-yellow-pages10633220
Ref: 3c7810633220
Ref: library/nis nis match10633602
Ref: e5710633602
Ref: library/nis nis cat10634136
Ref: 3c7a10634136
Ref: library/nis nis maps10634563
Ref: e5810634563
Ref: library/nis nis get_default_domain10634774
Ref: 3c7b10634774
Ref: library/nis nis error10634899
Ref: 3c7910634899
Node: Unix syslog 库例程10634985
Ref: library/syslog doc10635102
Ref: 3c7c10635102
Ref: library/syslog module-syslog10635102
Ref: ff10635102
Ref: library/syslog syslog-unix-syslog-library-routines10635102
Ref: 3c7d10635102
Ref: library/syslog syslog syslog10635585
Ref: 367710635585
Ref: library/syslog syslog openlog10636386
Ref: 10a610636386
Ref: library/syslog syslog closelog10637437
Ref: 367510637437
Ref: library/syslog syslog setlogmask10637924
Ref: 367610637924
Node: 示例<49>10639178
Ref: library/syslog examples10639246
Ref: 3c7e10639246
Node: 简单示例<2>10639322
Ref: library/syslog simple-example10639384
Ref: 3c7f10639384
Node: 被取代的模块10639872
Ref: library/superseded doc10640025
Ref: 3c8010640025
Ref: library/superseded superseded10640025
Ref: 3c8110640025
Ref: library/superseded superseded-modules10640025
Ref: 3c8210640025
Node: optparse --- 解析器的命令行选项10640320
Ref: library/optparse doc10640467
Ref: 3c8310640467
Ref: library/optparse module-optparse10640467
Ref: c310640467
Ref: library/optparse optparse-parser-for-command-line-options10640467
Ref: 3c8410640467
Ref: optparse --- 解析器的命令行选项-Footnote-110643254
Node: 背景10643321
Ref: library/optparse background10643422
Ref: 3c8610643422
Ref: library/optparse optparse-background10643422
Ref: 3c8710643422
Node: 术语10643870
Ref: library/optparse optparse-terminology10643949
Ref: 3c8810643949
Ref: library/optparse terminology10643949
Ref: 3c8910643949
Node: What are options for?10647732
Ref: library/optparse optparse-what-options-for10647832
Ref: 3c8a10647832
Ref: library/optparse what-are-options-for10647832
Ref: 3c8b10647832
Node: 位置位置10649513
Ref: library/optparse optparse-what-positional-arguments-for10649598
Ref: 3c8c10649598
Ref: library/optparse what-are-positional-arguments-for10649598
Ref: 3c8d10649598
Node: 教程<2>10650881
Ref: library/optparse optparse-tutorial10651003
Ref: 3c8e10651003
Ref: library/optparse tutorial10651003
Ref: 3c8f10651003
Node: Understanding option actions10653597
Ref: library/optparse optparse-understanding-option-actions10653696
Ref: 3c9410653696
Ref: library/optparse understanding-option-actions10653696
Ref: 3c9510653696
Node: The store action10654287
Ref: library/optparse optparse-store-action10654424
Ref: 3c9710654424
Ref: library/optparse the-store-action10654424
Ref: 3c9810654424
Node: Handling boolean flag options10656609
Ref: library/optparse handling-boolean-flag-options10656731
Ref: 3c9910656731
Ref: library/optparse optparse-handling-boolean-options10656731
Ref: 3c9a10656731
Node: Other actions10657614
Ref: library/optparse optparse-other-actions10657729
Ref: 3c9b10657729
Ref: library/optparse other-actions10657729
Ref: 3c9c10657729
Node: 默认值10658137
Ref: library/optparse default-values10658238
Ref: 3c9f10658238
Ref: library/optparse optparse-default-values10658238
Ref: 3ca010658238
Node: Generating help10660110
Ref: library/optparse generating-help10660223
Ref: 3ca110660223
Ref: library/optparse optparse-generating-help10660223
Ref: 3ca210660223
Node: Grouping Options10664384
Ref: library/optparse grouping-options10664452
Ref: 3ca310664452
Ref: library/optparse optparse OptionGroup10664783
Ref: 3ca410664783
Ref: library/optparse optparse OptionParser get_option_group10668282
Ref: 3ca510668282
Node: Printing a version string10668558
Ref: library/optparse optparse-printing-version-string10668689
Ref: 3ca610668689
Ref: library/optparse printing-a-version-string10668689
Ref: 3ca710668689
Ref: library/optparse optparse OptionParser print_version10669573
Ref: 3ca810669573
Ref: library/optparse optparse OptionParser get_version10669953
Ref: 3caa10669953
Node: How optparse handles errors10670103
Ref: library/optparse how-optparse-handles-errors10670242
Ref: 3cab10670242
Ref: library/optparse optparse-how-optparse-handles-errors10670242
Ref: 3cac10670242
Node: Putting it all together10672325
Ref: library/optparse optparse-putting-it-all-together10672430
Ref: 3cad10672430
Ref: library/optparse putting-it-all-together10672430
Ref: 3cae10672430
Node: 参考指南10673348
Ref: library/optparse optparse-reference-guide10673480
Ref: 3c9d10673480
Ref: library/optparse reference-guide10673480
Ref: 3caf10673480
Node: 创建解析器10673817
Ref: library/optparse creating-the-parser10673905
Ref: 3cb010673905
Ref: library/optparse optparse-creating-parser10673905
Ref: 3cb110673905
Ref: library/optparse optparse OptionParser10674037
Ref: 3c8510674037
Node: 填充解析器10677036
Ref: library/optparse optparse-populating-parser10677145
Ref: 3cb310677145
Ref: library/optparse populating-the-parser10677145
Ref: 3cb410677145
Node: 定义选项10678412
Ref: library/optparse defining-options10678523
Ref: 3cb510678523
Ref: library/optparse optparse-defining-options10678523
Ref: 3cb610678523
Ref: library/optparse optparse OptionParser add_option10678920
Ref: 21cd10678920
Node: Option attributes10681752
Ref: library/optparse option-attributes10681871
Ref: 3cb810681871
Ref: library/optparse optparse-option-attributes10681871
Ref: 3cb910681871
Ref: library/optparse optparse Option action10682207
Ref: 3c9010682207
Ref: library/optparse optparse Option type10682426
Ref: 3c9110682426
Ref: library/optparse optparse Option dest10682639
Ref: 3c9210682639
Ref: library/optparse optparse Option default10682981
Ref: 3cbb10682981
Ref: library/optparse optparse Option nargs10683172
Ref: 3cbd10683172
Ref: library/optparse optparse Option const10683401
Ref: 3cbe10683401
Ref: library/optparse optparse Option choices10683508
Ref: 3cbf10683508
Ref: library/optparse optparse Option callback10683629
Ref: 3cc010683629
Ref: library/optparse optparse Option callback_args10683858
Ref: 3cc110683858
Ref: library/optparse optparse Option callback_kwargs10683891
Ref: 3cc210683891
Ref: library/optparse optparse Option help10684052
Ref: 3c9310684052
Ref: library/optparse optparse Option metavar10684397
Ref: 3cc310684397
Node: Standard option actions10684597
Ref: library/optparse optparse-standard-option-actions10684725
Ref: 3cb710684725
Ref: library/optparse standard-option-actions10684725
Ref: 3cc410684725
Node: Standard option types10692806
Ref: library/optparse optparse-standard-option-types10692932
Ref: 3cba10692932
Ref: library/optparse standard-option-types10692932
Ref: 3cc510692932
Node: 解析参数<2>10694403
Ref: library/optparse optparse-parsing-arguments10694550
Ref: 3cc610694550
Ref: library/optparse parsing-arguments10694550
Ref: 3cc710694550
Node: Querying and manipulating your option parser10695897
Ref: library/optparse optparse-querying-manipulating-option-parser10696048
Ref: 3cc810696048
Ref: library/optparse querying-and-manipulating-your-option-parser10696048
Ref: 3cc910696048
Ref: library/optparse optparse OptionParser disable_interspersed_args10696357
Ref: 21ce10696357
Ref: library/optparse optparse OptionParser enable_interspersed_args10697153
Ref: 3cca10697153
Ref: library/optparse optparse OptionParser get_option10697365
Ref: 3ccb10697365
Ref: library/optparse optparse OptionParser has_option10697544
Ref: 3ccc10697544
Ref: library/optparse optparse OptionParser remove_option10697726
Ref: 3ccd10697726
Node: Conflicts between options10698118
Ref: library/optparse conflicts-between-options10698263
Ref: 3cce10698263
Ref: library/optparse optparse-conflicts-between-options10698263
Ref: 3cb210698263
Node: 清理<2>10700726
Ref: library/optparse cleanup10700840
Ref: 3ccf10700840
Ref: library/optparse optparse-cleanup10700840
Ref: 3cd010700840
Node: Other methods10701249
Ref: library/optparse optparse-other-methods10701329
Ref: 3cd110701329
Ref: library/optparse other-methods10701329
Ref: 3cd210701329
Ref: library/optparse optparse OptionParser set_usage10701431
Ref: 3cd310701431
Ref: library/optparse optparse OptionParser print_usage10701726
Ref: 3ca910701726
Ref: library/optparse optparse OptionParser get_usage10702068
Ref: 3cd410702068
Ref: library/optparse optparse OptionParser set_defaults10702212
Ref: 3cbc10702212
Node: Option Callbacks10703382
Ref: library/optparse option-callbacks10703523
Ref: 3cd510703523
Ref: library/optparse optparse-option-callbacks10703523
Ref: 3c9e10703523
Node: Defining a callback option10704740
Ref: library/optparse defining-a-callback-option10704852
Ref: 3cd610704852
Ref: library/optparse optparse-defining-callback-option10704852
Ref: 3cd710704852
Node: How callbacks are called10707077
Ref: library/optparse how-callbacks-are-called10707226
Ref: 3cd810707226
Ref: library/optparse optparse-how-callbacks-called10707226
Ref: 3cd910707226
Node: Raising errors in a callback10709836
Ref: library/optparse optparse-raising-errors-in-callback10709994
Ref: 3cda10709994
Ref: library/optparse raising-errors-in-a-callback10709994
Ref: 3cdb10709994
Node: Callback example 1 trivial callback10710465
Ref: library/optparse callback-example-1-trivial-callback10710636
Ref: 3cdc10710636
Ref: library/optparse optparse-callback-example-110710636
Ref: 3cdd10710636
Node: Callback example 2 check option order10711084
Ref: library/optparse callback-example-2-check-option-order10711276
Ref: 3cde10711276
Ref: library/optparse optparse-callback-example-210711276
Ref: 3cdf10711276
Node: Callback example 3 check option order generalized10711834
Ref: library/optparse callback-example-3-check-option-order-generalized10712035
Ref: 3ce010712035
Ref: library/optparse optparse-callback-example-310712035
Ref: 3ce110712035
Node: Callback example 4 check arbitrary condition10712809
Ref: library/optparse callback-example-4-check-arbitrary-condition10713007
Ref: 3ce210713007
Ref: library/optparse optparse-callback-example-410713007
Ref: 3ce310713007
Node: Callback example 5 fixed arguments10713802
Ref: library/optparse callback-example-5-fixed-arguments10713988
Ref: 3ce410713988
Ref: library/optparse optparse-callback-example-510713988
Ref: 3ce510713988
Node: Callback example 6 variable arguments10715062
Ref: library/optparse callback-example-6-variable-arguments10715195
Ref: 3ce610715195
Ref: library/optparse optparse-callback-example-610715195
Ref: 3ce710715195
Node: Extending optparse10717300
Ref: library/optparse extending-optparse10717420
Ref: 3ce810717420
Ref: library/optparse optparse-extending-optparse10717420
Ref: 3c9610717420
Node: Adding new types10717757
Ref: library/optparse adding-new-types10717855
Ref: 3ce910717855
Ref: library/optparse optparse-adding-new-types10717855
Ref: 3cea10717855
Ref: library/optparse optparse Option TYPES10718144
Ref: 3ceb10718144
Ref: library/optparse optparse Option TYPE_CHECKER10718300
Ref: 3cec10718300
Node: Adding new actions10721308
Ref: library/optparse adding-new-actions10721406
Ref: 3ced10721406
Ref: library/optparse optparse-adding-new-actions10721406
Ref: 3cee10721406
Ref: library/optparse optparse Option ACTIONS10722493
Ref: 3cef10722493
Ref: library/optparse optparse Option STORE_ACTIONS10722566
Ref: 3cf010722566
Ref: library/optparse optparse Option TYPED_ACTIONS10722652
Ref: 3cf110722652
Ref: library/optparse optparse Option ALWAYS_TYPED_ACTIONS10722738
Ref: 3cf210722738
Node: imp —— 由代码内部访问 import 。10726037
Ref: library/imp doc10726184
Ref: 3cf310726184
Ref: library/imp imp-access-the-import-internals10726184
Ref: 3cf410726184
Ref: library/imp module-imp10726184
Ref: 9910726184
Ref: library/imp imp get_magic10726598
Ref: 94e10726598
Ref: library/imp imp get_suffixes10726878
Ref: 3cf510726878
Ref: library/imp imp find_module10727605
Ref: 3cf910727605
Ref: library/imp imp load_module10730105
Ref: 3cfd10730105
Ref: library/imp imp new_module10731964
Ref: 3cfe10731964
Ref: library/imp imp reload10732202
Ref: d3810732202
Ref: library/imp imp cache_from_source10735317
Ref: 3cff10735317
Ref: library/imp imp source_from_cache10736344
Ref: 3d0110736344
Ref: library/imp imp get_tag10737059
Ref: 3d0010737059
Ref: library/imp imp lock_held10737599
Ref: 3d0210737599
Ref: library/imp imp acquire_lock10738513
Ref: 3d0310738513
Ref: library/imp imp release_lock10739194
Ref: 3d0410739194
Ref: library/imp imp PY_SOURCE10739710
Ref: 3cf610739710
Ref: library/imp imp PY_COMPILED10739807
Ref: 3cf710739807
Ref: library/imp imp C_EXTENSION10739920
Ref: 3cf810739920
Ref: library/imp imp PKG_DIRECTORY10740041
Ref: 3cfc10740041
Ref: library/imp imp C_BUILTIN10740148
Ref: 3cfa10740148
Ref: library/imp imp PY_FROZEN10740249
Ref: 3cfb10740249
Ref: library/imp imp NullImporter10740348
Ref: a9b10740348
Ref: library/imp imp NullImporter find_module10740743
Ref: 3d0510740743
Ref: imp —— 由代码内部访问 import 。-Footnote-110741212
Ref: imp —— 由代码内部访问 import 。-Footnote-210741274
Ref: imp —— 由代码内部访问 import 。-Footnote-310741323
Ref: imp —— 由代码内部访问 import 。-Footnote-410741372
Ref: imp —— 由代码内部访问 import 。-Footnote-510741421
Ref: imp —— 由代码内部访问 import 。-Footnote-610741470
Ref: imp —— 由代码内部访问 import 。-Footnote-710741519
Node: 示例<50>10741568
Ref: library/imp examples10741658
Ref: 3d0610741658
Ref: library/imp examples-imp10741658
Ref: 3d0710741658
Node: 未创建文档的模块10742658
Ref: library/undoc doc10742817
Ref: 3d0810742817
Ref: library/undoc undoc10742817
Ref: 3d0910742817
Ref: library/undoc undocumented-modules10742817
Ref: 3d0a10742817
Node: 平台特定模块10743170
Ref: library/undoc platform-specific-modules10743249
Ref: 3d0b10743249
Ref: library/security_warnings security-warnings10743570
Ref: 3d0c10743570
Node: Security Considerations10743571
Ref: library/security_warnings doc10743703
Ref: 3d0d10743703
Ref: library/security_warnings security-considerations10743703
Ref: 3d0e10743703
Node: 擴充和嵌入 Python 直譯器10745030
Ref: extending/index doc10745184
Ref: 3d0f10745184
Ref: extending/index extending-and-embedding-the-python-interpreter10745184
Ref: 3d1010745184
Ref: extending/index extending-index10745184
Ref: 133210745184
Node: 推薦的第三方工具10746498
Ref: extending/index recommended-third-party-tools10746636
Ref: 3d1110746636
Ref: 推薦的第三方工具-Footnote-110747285
Ref: 推薦的第三方工具-Footnote-210747312
Ref: 推薦的第三方工具-Footnote-310747348
Ref: 推薦的第三方工具-Footnote-410747376
Ref: 推薦的第三方工具-Footnote-510747410
Node: 不使用第三方工具建立擴充10747483
Ref: extending/index creating-extensions-without-third-party-tools10747692
Ref: 3d1210747692
Node: 以 C 或 C++ 擴充 Python10748169
Ref: extending/extending doc10748308
Ref: 3d1310748308
Ref: extending/extending extending-intro10748308
Ref: 3d1410748308
Ref: extending/extending extending-python-with-c-or-c10748308
Ref: 3d1510748308
Ref: 以 C 或 C++ 擴充 Python-Footnote-110749794
Node: 一个简单的例子10749831
Ref: extending/extending a-simple-example10749946
Ref: 3d1610749946
Ref: extending/extending extending-simpleexample10749946
Ref: 3d1710749946
Ref: 一个简单的例子-Footnote-110753328
Node: 关于错误和异常10753453
Ref: extending/extending extending-errors10753589
Ref: 3d1910753589
Ref: extending/extending intermezzo-errors-and-exceptions10753589
Ref: 3d1a10753589
Node: 回到例子10759770
Ref: extending/extending back-to-the-example10759918
Ref: 3d2110759918
Ref: extending/extending backtoexample10759918
Ref: 3d2210759918
Node: 模块方法表和初始化函数10761486
Ref: extending/extending methodtable10761628
Ref: 3d2410761628
Ref: extending/extending the-module-s-method-table-and-initialization-function10761628
Ref: 3d2510761628
Ref: 模块方法表和初始化函数-Footnote-110766705
Node: 编译和链接10766754
Ref: extending/extending compilation10766909
Ref: 3d2710766909
Ref: extending/extending compilation-and-linkage10766909
Ref: 3d2810766909
Node: 在C中调用Python函数10768201
Ref: extending/extending calling-python-functions-from-c10768350
Ref: 3d2a10768350
Ref: extending/extending callingpython10768350
Ref: 3d2b10768350
Node: 提取扩展函数的参数10774145
Ref: extending/extending extracting-parameters-in-extension-functions10774312
Ref: 3d2e10774312
Ref: extending/extending parsetuple10774312
Ref: 3d1810774312
Node: 给扩展函数的关键字参数10776751
Ref: extending/extending keyword-parameters-for-extension-functions10776908
Ref: 3d2f10776908
Ref: extending/extending parsetupleandkeywords10776908
Ref: 3d3010776908
Node: 构造任意值10779460
Ref: extending/extending building-arbitrary-values10779602
Ref: 3d3110779602
Ref: extending/extending buildvalue10779602
Ref: 3d3210779602
Node: 引用计数10781532
Ref: extending/extending refcounts10781662
Ref: 3d2c10781662
Ref: extending/extending reference-counts10781662
Ref: 3d3310781662
Node: Python中的引用计数10785231
Ref: extending/extending refcountsinpython10785325
Ref: 3d3410785325
Ref: extending/extending reference-counting-in-python10785325
Ref: 3d3510785325
Ref: Python中的引用计数-Footnote-110787150
Ref: Python中的引用计数-Footnote-210787249
Node: 拥有规则10787397
Ref: extending/extending ownership-rules10787515
Ref: 3d3610787515
Ref: extending/extending ownershiprules10787515
Ref: 3d3710787515
Node: 危险的薄冰10789580
Ref: extending/extending thin-ice10789684
Ref: 3d4110789684
Ref: extending/extending thinice10789684
Ref: 3d4210789684
Node: NULL指针10792597
Ref: extending/extending null-pointers10792680
Ref: 3d4410792680
Ref: extending/extending nullpointers10792680
Ref: 3d4510792680
Ref: NULL指针-Footnote-110794188
Node: 在C++中编写扩展10794317
Ref: extending/extending cplusplus10794458
Ref: 3d4610794458
Ref: extending/extending writing-extensions-in-c10794458
Ref: 3d4710794458
Node: 给扩展模块提供C API10795085
Ref: extending/extending providing-a-c-api-for-an-extension-module10795205
Ref: 3d4810795205
Ref: extending/extending using-capsules10795205
Ref: db710795205
Node: 自定义扩展类型：教程10802781
Ref: extending/newtypes_tutorial doc10802965
Ref: 3d4c10802965
Ref: extending/newtypes_tutorial defining-extension-types-tutorial10802965
Ref: 3d4d10802965
Ref: extending/newtypes_tutorial defining-new-types10802965
Ref: 3d4e10802965
Node: 基础10803522
Ref: extending/newtypes_tutorial dnt-basics10803648
Ref: 3d4f10803648
Ref: extending/newtypes_tutorial the-basics10803648
Ref: 3d5010803648
Ref: 基础-Footnote-110812423
Node: Adding data and methods to the Basic example10812493
Ref: extending/newtypes_tutorial adding-data-and-methods-to-the-basic-example10812672
Ref: 3d5910812672
Ref: Adding data and methods to the Basic example-Footnote-110828923
Ref: Adding data and methods to the Basic example-Footnote-210829020
Node: Providing finer control over data attributes10829161
Ref: extending/newtypes_tutorial providing-finer-control-over-data-attributes10829370
Ref: 3d6310829370
Ref: Providing finer control over data attributes-Footnote-110839273
Node: Supporting cyclic garbage collection10839657
Ref: extending/newtypes_tutorial supporting-cyclic-garbage-collection10839845
Ref: 3d6510839845
Ref: Supporting cyclic garbage collection-Footnote-110850487
Node: Subclassing other types10850665
Ref: extending/newtypes_tutorial subclassing-other-types10850800
Ref: 3d6910850800
Node: 定义扩展类型：已分类主题10856062
Ref: extending/newtypes doc10856236
Ref: 3d6c10856236
Ref: extending/newtypes defining-extension-types-assorted-topics10856236
Ref: 3d6d10856236
Ref: extending/newtypes new-types-topics10856236
Ref: 3d6e10856236
Ref: extending/newtypes dnt-type-methods10856311
Ref: 3d6f10856311
Node: 终结和内存释放10860506
Ref: extending/newtypes finalization-and-de-allocation10860621
Ref: 3d7010860621
Ref: 终结和内存释放-Footnote-110863827
Node: 对象展示10863876
Ref: extending/newtypes object-presentation10864012
Ref: 3d7310864012
Node: 属性管理10865594
Ref: extending/newtypes attribute-management10865726
Ref: 3d7710865726
Node: 泛型属性管理10867250
Ref: extending/newtypes generic-attribute-management10867360
Ref: 3d6010867360
Ref: extending/newtypes id110867360
Ref: 3d7810867360
Node: Type-specific Attribute Management10871477
Ref: extending/newtypes type-specific-attribute-management10871587
Ref: 3d7b10871587
Node: Object Comparison10873345
Ref: extending/newtypes object-comparison10873490
Ref: 3d7e10873490
Node: Abstract Protocol Support10875260
Ref: extending/newtypes abstract-protocol-support10875415
Ref: 3d8110875415
Node: Weak Reference Support10881083
Ref: extending/newtypes weak-reference-support10881233
Ref: 3d8710881233
Ref: extending/newtypes weakref-support10881233
Ref: 1ada10881233
Node: 更多建议10883147
Ref: extending/newtypes more-suggestions10883263
Ref: 3d8810883263
Node: 构建C/C++扩展10884194
Ref: extending/building doc10884376
Ref: 3d8a10884376
Ref: extending/building building10884376
Ref: 3d2910884376
Ref: extending/building building-c-and-c-extensions10884376
Ref: 3d8b10884376
Ref: extending/building c PyInit_modulename10884807
Ref: 3d8c10884807
Ref: 构建C/C++扩展-Footnote-110886061
Node: 使用distutils构建C和C++扩展10886110
Ref: extending/building building-c-and-c-extensions-with-distutils10886231
Ref: 3d8f10886231
Node: 发布你的扩展模块10889783
Ref: extending/building distributing10889904
Ref: 3d9110889904
Ref: extending/building distributing-your-extension-modules10889904
Ref: 3d9210889904
Node: 在 Windows 上构建 C 和 C++ 扩展10890669
Ref: extending/windows doc10890806
Ref: 3d9410890806
Ref: extending/windows building-c-and-c-extensions-on-windows10890806
Ref: 3d9510890806
Ref: extending/windows building-on-windows10890806
Ref: 14cd10890806
Node: 菜谱式说明10891861
Ref: extending/windows a-cookbook-approach10891992
Ref: 3d9610891992
Ref: extending/windows win-cookbook10891992
Ref: 3d9710891992
Ref: 菜谱式说明-Footnote-110892506
Node: Unix 和 Windows 之间的差异10892583
Ref: extending/windows differences-between-unix-and-windows10892742
Ref: 3d9810892742
Ref: extending/windows dynamic-linking10892742
Ref: 3d9910892742
Node: DLL 的实际使用10895475
Ref: extending/windows using-dlls-in-practice10895610
Ref: 3d9a10895610
Ref: extending/windows win-dlls10895610
Ref: 3d9b10895610
Node: 在更大的應用程式中嵌入 CPython 運行環境 runtime10897171
Ref: extending/index embedding-the-cpython-runtime-in-a-larger-application10897347
Ref: 3d9c10897347
Node: 在其它 App 內嵌入 Python10897774
Ref: extending/embedding doc10897903
Ref: 3d9d10897903
Ref: extending/embedding embedding10897903
Ref: 3d9e10897903
Ref: extending/embedding embedding-python-in-another-application10897903
Ref: 3d9f10897903
Node: 高层次的嵌入10899795
Ref: extending/embedding high-level-embedding10899928
Ref: 3da210899928
Ref: extending/embedding very-high-level-embedding10899928
Ref: 3da310899928
Node: 突破高层次嵌入的限制：概述10901532
Ref: extending/embedding beyond-very-high-level-embedding-an-overview10901683
Ref: 3da410901683
Ref: extending/embedding lower-level-embedding10901683
Ref: 3da510901683
Node: 纯嵌入10903152
Ref: extending/embedding id110903320
Ref: 3da610903320
Ref: extending/embedding pure-embedding10903320
Ref: 3da710903320
Node: 对嵌入 Python 功能进行扩展10907741
Ref: extending/embedding extending-embedded-python10907894
Ref: 3daa10907894
Ref: extending/embedding extending-with-embedding10907894
Ref: 3dab10907894
Node: 在 C++ 中嵌入 Python10909791
Ref: extending/embedding embedding-python-in-c10909971
Ref: 3dac10909971
Ref: extending/embedding embeddingincplusplus10909971
Ref: 3dad10909971
Node: 在类 Unix 系统中编译和链接10910284
Ref: extending/embedding compiling10910420
Ref: 3da810910420
Ref: extending/embedding compiling-and-linking-under-unix-like-systems10910420
Ref: 3dae10910420
Node: Python/C API 參考手冊10912276
Ref: c-api/index doc10912411
Ref: 3db010912411
Ref: c-api/index c-api-index10912411
Ref: 133310912411
Ref: c-api/index python-c-api-reference-manual10912411
Ref: 3db110912411
Node: 簡介<12>10913102
Ref: c-api/intro doc10913219
Ref: 3db210913219
Ref: c-api/intro api-intro10913219
Ref: 3db310913219
Ref: c-api/intro introduction10913219
Ref: 3db410913219
Node: 代码标准10914522
Ref: c-api/intro coding-standards10914602
Ref: 3db510914602
Ref: 代码标准-Footnote-110915004
Node: 包含文件10915053
Ref: c-api/intro api-includes10915154
Ref: 3db610915154
Ref: c-api/intro include-files10915154
Ref: 3db710915154
Node: 有用的宏10917515
Ref: c-api/intro useful-macros10917634
Ref: 3db810917634
Ref: c-api/intro c Py_UNREACHABLE10917908
Ref: 52610917908
Ref: c-api/intro c Py_ABS10919026
Ref: 3db910919026
Ref: c-api/intro c Py_MIN10919113
Ref: 3dba10919113
Ref: c-api/intro c Py_MAX10919221
Ref: 3dbb10919221
Ref: c-api/intro c Py_STRINGIFY10919329
Ref: 3dbc10919329
Ref: c-api/intro c Py_MEMBER_SIZE10919480
Ref: 3dbd10919480
Ref: c-api/intro c Py_CHARMASK10919625
Ref: 3dbe10919625
Ref: c-api/intro c Py_GETENV10919811
Ref: 3dbf10919811
Ref: c-api/intro c Py_UNUSED10920013
Ref: 3dc010920013
Ref: c-api/intro c Py_DEPRECATED10920219
Ref: 3dc110920219
Ref: c-api/intro c PyDoc_STRVAR10920447
Ref: 105a10920447
Ref: c-api/intro c PyDoc_STR10921070
Ref: 3dc210921070
Ref: 有用的宏-Footnote-110921665
Ref: 有用的宏-Footnote-210921714
Node: 对象、类型和引用计数10921763
Ref: c-api/intro api-objects10921880
Ref: 3dc310921880
Ref: c-api/intro objects-types-and-reference-counts10921880
Ref: 3dc410921880
Node: 引用计数<2>10923161
Ref: c-api/intro api-refcounts10923258
Ref: 3dc510923258
Ref: c-api/intro reference-counts10923258
Ref: 3dc610923258
Node: 引用计数细节10926342
Ref: c-api/intro api-refcountdetails10926412
Ref: 3dc710926412
Ref: c-api/intro reference-count-details10926412
Ref: 3dc810926412
Node: 类型10933596
Ref: c-api/intro api-types10933693
Ref: 3dcc10933693
Ref: c-api/intro types10933693
Ref: 3dcd10933693
Node: 异常<17>10934171
Ref: c-api/intro api-exceptions10934291
Ref: 3dce10934291
Ref: c-api/intro exceptions10934291
Ref: 3dcf10934291
Node: 嵌入式Python10940360
Ref: c-api/intro api-embedding10940462
Ref: 3dd110940462
Ref: c-api/intro embedding-python10940462
Ref: 3dd210940462
Node: 调试构建10943644
Ref: c-api/intro api-debugging10943727
Ref: 3dd710943727
Ref: c-api/intro debugging-builds10943727
Ref: 3dd810943727
Node: 稳定的应用程序二进制接口10946010
Ref: c-api/stable doc10946161
Ref: 3dd910946161
Ref: c-api/stable stable10946161
Ref: 3dda10946161
Ref: c-api/stable stable-application-binary-interface10946161
Ref: 3ddb10946161
Ref: 稳定的应用程序二进制接口-Footnote-110947888
Node: The Very High Level Layer10947937
Ref: c-api/veryhigh doc10948090
Ref: 3ddc10948090
Ref: c-api/veryhigh the-very-high-level-layer10948090
Ref: 3ddd10948090
Ref: c-api/veryhigh veryhigh10948090
Ref: 3dde10948090
Ref: c-api/veryhigh c Py_Main10949111
Ref: 5b110949111
Ref: c-api/veryhigh c Py_BytesMain10950068
Ref: 2af10950068
Ref: c-api/veryhigh c PyRun_AnyFile10950233
Ref: 3ddf10950233
Ref: c-api/veryhigh c PyRun_AnyFileFlags10950456
Ref: 3de110950456
Ref: c-api/veryhigh c PyRun_AnyFileEx10950696
Ref: 3de210950696
Ref: c-api/veryhigh c PyRun_AnyFileExFlags10950923
Ref: 3de010950923
Ref: c-api/veryhigh c PyRun_SimpleString10951488
Ref: 3da010951488
Ref: c-api/veryhigh c PyRun_SimpleStringFlags10951713
Ref: 3de410951713
Ref: c-api/veryhigh c PyRun_SimpleFile10952394
Ref: 3da110952394
Ref: c-api/veryhigh c PyRun_SimpleFileEx10952617
Ref: 3de510952617
Ref: c-api/veryhigh c PyRun_SimpleFileExFlags10952836
Ref: fc710952836
Ref: c-api/veryhigh c PyRun_InteractiveOne10953529
Ref: 3de610953529
Ref: c-api/veryhigh c PyRun_InteractiveOneFlags10953735
Ref: 3de710953735
Ref: c-api/veryhigh c PyRun_InteractiveLoop10954495
Ref: 3de310954495
Ref: c-api/veryhigh c PyRun_InteractiveLoopFlags10954703
Ref: 3de810954703
Ref: c-api/veryhigh c PyOS_InputHook10955161
Ref: 3de910955161
Ref: c-api/veryhigh c PyOS_ReadlineFunctionPointer10955642
Ref: a4d10955642
Ref: c-api/veryhigh c PyParser_SimpleParseString10956661
Ref: 3dea10956661
Ref: c-api/veryhigh c PyParser_SimpleParseStringFlags10957001
Ref: 1ff10957001
Ref: c-api/veryhigh c PyParser_SimpleParseStringFlagsFilename10957330
Ref: 20010957330
Ref: c-api/veryhigh c PyParser_SimpleParseFile10957916
Ref: 3deb10957916
Ref: c-api/veryhigh c PyParser_SimpleParseFileFlags10958226
Ref: 20110958226
Ref: c-api/veryhigh c PyRun_String10958577
Ref: 10e710958577
Ref: c-api/veryhigh c PyRun_StringFlags10958847
Ref: 3dec10958847
Ref: c-api/veryhigh c PyRun_File10959506
Ref: 3ded10959506
Ref: c-api/veryhigh c PyRun_FileEx10959818
Ref: 3def10959818
Ref: c-api/veryhigh c PyRun_FileFlags10960116
Ref: 3df010960116
Ref: c-api/veryhigh c PyRun_FileExFlags10960437
Ref: 3dee10960437
Ref: c-api/veryhigh c Py_CompileString10961022
Ref: 3df110961022
Ref: c-api/veryhigh c Py_CompileStringFlags10961285
Ref: 3df210961285
Ref: c-api/veryhigh c Py_CompileStringObject10961577
Ref: 3df410961577
Ref: c-api/veryhigh c Py_CompileStringExFlags10962690
Ref: 3df310962690
Ref: c-api/veryhigh c PyEval_EvalCode10963060
Ref: 3df510963060
Ref: c-api/veryhigh c PyEval_EvalCodeEx10963380
Ref: 3df610963380
Ref: c-api/veryhigh c PyFrameObject10964055
Ref: a5210964055
Ref: c-api/veryhigh c PyEval_EvalFrame10964218
Ref: 3df710964218
Ref: c-api/veryhigh c PyEval_EvalFrameEx10964451
Ref: a4810964451
Ref: c-api/veryhigh c PyEval_MergeCompilerFlags10965111
Ref: 3df810965111
Ref: c-api/veryhigh c Py_eval_input10965301
Ref: 3df910965301
Ref: c-api/veryhigh c Py_file_input10965457
Ref: 3dfa10965457
Ref: c-api/veryhigh c Py_single_input10965741
Ref: 3dfb10965741
Ref: c-api/veryhigh c PyCompilerFlags10965965
Ref: 3ee10965965
Ref: c-api/veryhigh c PyCompilerFlags cf_flags10966498
Ref: 3dfc10966498
Ref: c-api/veryhigh c PyCompilerFlags cf_feature_version10966564
Ref: 3dfd10966564
Ref: c-api/veryhigh c CO_FUTURE_DIVISION10966919
Ref: 3dfe10966919
Ref: The Very High Level Layer-Footnote-110967132
Node: 參照計數10967181
Ref: c-api/refcounting doc10967310
Ref: 3dff10967310
Ref: c-api/refcounting countingrefs10967310
Ref: 3e0010967310
Ref: c-api/refcounting reference-counting10967310
Ref: 3e0110967310
Ref: c-api/refcounting c Py_INCREF10967408
Ref: 38e10967408
Ref: c-api/refcounting c Py_XINCREF10967610
Ref: 39010967610
Ref: c-api/refcounting c Py_DECREF10967778
Ref: 38f10967778
Ref: c-api/refcounting c Py_XDECREF10968791
Ref: 39110968791
Ref: c-api/refcounting c Py_CLEAR10969059
Ref: 3d6710969059
Node: 例外處理10970066
Ref: c-api/exceptions doc10970179
Ref: 3e0210970179
Ref: c-api/exceptions exception-handling10970179
Ref: 3e0310970179
Ref: c-api/exceptions exceptionhandling10970179
Ref: 37f210970179
Node: 打印和清理10972237
Ref: c-api/exceptions printing-and-clearing10972322
Ref: 3e0410972322
Ref: c-api/exceptions c PyErr_Clear10972362
Ref: a4c10972362
Ref: c-api/exceptions c PyErr_PrintEx10972485
Ref: 3e0510972485
Ref: c-api/exceptions c PyErr_Print10973110
Ref: 102f10973110
Ref: c-api/exceptions c PyErr_WriteUnraisable10973187
Ref: 10f910973187
Node: 抛出异常10973789
Ref: c-api/exceptions raising-exceptions10973895
Ref: 3e0610973895
Ref: c-api/exceptions c PyErr_SetString10974100
Ref: 3d1b10974100
Ref: c-api/exceptions c PyErr_SetObject10974506
Ref: 3d1d10974506
Ref: c-api/exceptions c PyErr_Format10974712
Ref: 89810974712
Ref: c-api/exceptions c PyErr_FormatV10975176
Ref: 89710975176
Ref: c-api/exceptions c PyErr_SetNone10975471
Ref: 3e0710975471
Ref: c-api/exceptions c PyErr_BadArgument10975585
Ref: 3e0810975585
Ref: c-api/exceptions c PyErr_NoMemory10975799
Ref: 3d1f10975799
Ref: c-api/exceptions c PyErr_SetFromErrno10976059
Ref: 3d1c10976059
Ref: c-api/exceptions c PyErr_SetFromErrnoWithFilenameObject10976863
Ref: 3e0a10976863
Ref: c-api/exceptions c PyErr_SetFromErrnoWithFilenameObjects10977324
Ref: 3e0b10977324
Ref: c-api/exceptions c PyErr_SetFromErrnoWithFilename10977718
Ref: 3e0c10977718
Ref: c-api/exceptions c PyErr_SetFromWindowsErr10978067
Ref: 3e0d10978067
Ref: c-api/exceptions c PyErr_SetExcFromWindowsErr10978754
Ref: 3e0e10978754
Ref: c-api/exceptions c PyErr_SetFromWindowsErrWithFilename10979024
Ref: 3e0f10979024
Ref: c-api/exceptions c PyErr_SetExcFromWindowsErrWithFilenameObject10979419
Ref: 3e1010979419
Ref: c-api/exceptions c PyErr_SetExcFromWindowsErrWithFilenameObjects10979741
Ref: 3e1110979741
Ref: c-api/exceptions c PyErr_SetExcFromWindowsErrWithFilename10980124
Ref: 3e1210980124
Ref: c-api/exceptions c PyErr_SetImportError10980443
Ref: 6ef10980443
Ref: c-api/exceptions c PyErr_SyntaxLocationObject10980866
Ref: 3e1310980866
Ref: c-api/exceptions c PyErr_SyntaxLocationEx10981212
Ref: 3e1410981212
Ref: c-api/exceptions c PyErr_SyntaxLocation10981524
Ref: 3e1510981524
Ref: c-api/exceptions c PyErr_BadInternalCall10981695
Ref: 3e1610981695
Node: 发出警告10981956
Ref: c-api/exceptions issuing-warnings10982068
Ref: 3e1710982068
Ref: c-api/exceptions c PyErr_WarnEx10982830
Ref: e7610982830
Ref: c-api/exceptions c PyErr_SetImportErrorSubclass10983811
Ref: 6c210983811
Ref: c-api/exceptions c PyErr_WarnExplicitObject10984144
Ref: 3e1910984144
Ref: c-api/exceptions c PyErr_WarnExplicit10984681
Ref: 3e1a10984681
Ref: c-api/exceptions c PyErr_WarnFormat10985068
Ref: 3e1b10985068
Ref: c-api/exceptions c PyErr_ResourceWarning10985382
Ref: 6c310985382
Node: 查询错误指示器10985698
Ref: c-api/exceptions querying-the-error-indicator10985813
Ref: 3e1c10985813
Ref: c-api/exceptions c PyErr_Occurred10985863
Ref: 3d1e10985863
Ref: c-api/exceptions c PyErr_ExceptionMatches10986693
Ref: 3dd010986693
Ref: c-api/exceptions c PyErr_GivenExceptionMatches10986971
Ref: 3e1d10986971
Ref: c-api/exceptions c PyErr_Fetch10987368
Ref: a4b10987368
Ref: c-api/exceptions c PyErr_Restore10988288
Ref: 3d7110988288
Ref: c-api/exceptions c PyErr_NormalizeException10989281
Ref: 10fa10989281
Ref: c-api/exceptions c PyErr_GetExcInfo10990148
Ref: 3e1e10990148
Ref: c-api/exceptions c PyErr_SetExcInfo10990900
Ref: 3e1f10990900
Node: 信号处理<2>10991708
Ref: c-api/exceptions signal-handling10991827
Ref: 3e2010991827
Ref: c-api/exceptions c PyErr_CheckSignals10991862
Ref: 3e0910991862
Ref: c-api/exceptions c PyErr_SetInterrupt10992526
Ref: 3e2110992526
Ref: c-api/exceptions c PySignal_SetWakeupFd10992937
Ref: e0b10992937
Node: Exception 类<2>10993593
Ref: c-api/exceptions exception-classes10993703
Ref: 3e2210993703
Ref: c-api/exceptions c PyErr_NewException10993743
Ref: ccb10993743
Ref: c-api/exceptions c PyErr_NewExceptionWithDoc10994679
Ref: cca10994679
Node: 异常对象10995059
Ref: c-api/exceptions exception-objects10995174
Ref: 3e2310995174
Ref: c-api/exceptions c PyException_GetTraceback10995209
Ref: 3e2410995209
Ref: c-api/exceptions c PyException_SetTraceback10995515
Ref: 10fb10995515
Ref: c-api/exceptions c PyException_GetContext10995674
Ref: 3e2510995674
Ref: c-api/exceptions c PyException_SetContext10996044
Ref: 3e2610996044
Ref: c-api/exceptions c PyException_GetCause10996327
Ref: 3e2710996327
Ref: c-api/exceptions c PyException_SetCause10996642
Ref: 3e2810996642
Node: Unicode 异常对象10997048
Ref: c-api/exceptions unicode-exception-objects10997159
Ref: 3e2910997159
Ref: c-api/exceptions unicodeexceptions10997159
Ref: 3e2a10997159
Ref: c-api/exceptions c PyUnicodeDecodeError_Create10997292
Ref: 3e2b10997292
Ref: c-api/exceptions c PyUnicodeEncodeError_Create10997713
Ref: 3e2c10997713
Ref: c-api/exceptions c PyUnicodeTranslateError_Create10998320
Ref: 3e2d10998320
Ref: c-api/exceptions c PyUnicodeDecodeError_GetEncoding10998887
Ref: 3e2e10998887
Ref: c-api/exceptions c PyUnicodeEncodeError_GetEncoding10998960
Ref: 3e2f10998960
Ref: c-api/exceptions c PyUnicodeDecodeError_GetObject10999116
Ref: 3e3010999116
Ref: c-api/exceptions c PyUnicodeEncodeError_GetObject10999187
Ref: 3e3110999187
Ref: c-api/exceptions c PyUnicodeTranslateError_GetObject10999258
Ref: 3e3210999258
Ref: c-api/exceptions c PyUnicodeDecodeError_GetStart10999413
Ref: 3e3310999413
Ref: c-api/exceptions c PyUnicodeEncodeError_GetStart10999506
Ref: 3e3410999506
Ref: c-api/exceptions c PyUnicodeTranslateError_GetStart10999599
Ref: 3e3510999599
Ref: c-api/exceptions c PyUnicodeDecodeError_SetStart10999878
Ref: 3e3610999878
Ref: c-api/exceptions c PyUnicodeEncodeError_SetStart10999970
Ref: 3e3710999970
Ref: c-api/exceptions c PyUnicodeTranslateError_SetStart11000062
Ref: 3e3811000062
Ref: c-api/exceptions c PyUnicodeDecodeError_GetEnd11000285
Ref: 3e3911000285
Ref: c-api/exceptions c PyUnicodeEncodeError_GetEnd11000374
Ref: 3e3a11000374
Ref: c-api/exceptions c PyUnicodeTranslateError_GetEnd11000463
Ref: 3e3b11000463
Ref: c-api/exceptions c PyUnicodeDecodeError_SetEnd11000732
Ref: 3e3c11000732
Ref: c-api/exceptions c PyUnicodeEncodeError_SetEnd11000820
Ref: 3e3d11000820
Ref: c-api/exceptions c PyUnicodeTranslateError_SetEnd11000908
Ref: 3e3e11000908
Ref: c-api/exceptions c PyUnicodeDecodeError_GetReason11001123
Ref: 3e3f11001123
Ref: c-api/exceptions c PyUnicodeEncodeError_GetReason11001194
Ref: 3e4011001194
Ref: c-api/exceptions c PyUnicodeTranslateError_GetReason11001265
Ref: 3e4111001265
Ref: c-api/exceptions c PyUnicodeDecodeError_SetReason11001420
Ref: 3e4211001420
Ref: c-api/exceptions c PyUnicodeEncodeError_SetReason11001515
Ref: 3e4311001515
Ref: c-api/exceptions c PyUnicodeTranslateError_SetReason11001610
Ref: 3e4411001610
Node: 递归控制11001839
Ref: c-api/exceptions recursion11001950
Ref: 3e4511001950
Ref: c-api/exceptions recursion-control11001950
Ref: 3e4611001950
Ref: c-api/exceptions c Py_EnterRecursiveCall11002369
Ref: 25111002369
Ref: c-api/exceptions c Py_LeaveRecursiveCall11003210
Ref: 25211003210
Ref: c-api/exceptions c Py_ReprEnter11003831
Ref: 3e4911003831
Ref: c-api/exceptions c Py_ReprLeave11004597
Ref: 3e4a11004597
Node: 标准异常11004786
Ref: c-api/exceptions standard-exceptions11004895
Ref: 3e4b11004895
Ref: c-api/exceptions standardexceptions11004895
Ref: 3e4c11004895
Ref: 标准异常-Footnote-111018207
Node: 标准警告类别11018256
Ref: c-api/exceptions standard-warning-categories11018344
Ref: 3e4d11018344
Ref: c-api/exceptions standardwarningcategories11018344
Ref: 3e1811018344
Node: 工具<2>11021438
Ref: c-api/utilities doc11021554
Ref: 3e4e11021554
Ref: c-api/utilities id111021554
Ref: 3e4f11021554
Ref: c-api/utilities utilities11021554
Ref: 3e5011021554
Node: 作業系統工具11022044
Ref: c-api/sys doc11022129
Ref: 3e5111022129
Ref: c-api/sys operating-system-utilities11022129
Ref: 3e5211022129
Ref: c-api/sys os11022129
Ref: 3e5311022129
Ref: c-api/sys c PyOS_FSPath11022174
Ref: 6c411022174
Ref: c-api/sys c Py_FdIsInteractive11022716
Ref: 3e5411022716
Ref: c-api/sys c PyOS_BeforeFork11023197
Ref: 53511023197
Ref: c-api/sys c PyOS_AfterFork_Parent11023716
Ref: 53611023716
Ref: c-api/sys c PyOS_AfterFork_Child11024328
Ref: 3ef11024328
Ref: c-api/sys c PyOS_AfterFork11025214
Ref: 53411025214
Ref: c-api/sys c PyOS_CheckStack11025620
Ref: 3e4811025620
Ref: c-api/sys c PyOS_getsig11026002
Ref: 3e5811026002
Ref: c-api/sys c PyOS_setsig11026309
Ref: 3e5911026309
Ref: c-api/sys c Py_DecodeLocale11026666
Ref: 53e11026666
Ref: c-api/sys c Py_EncodeLocale11028692
Ref: 53f11028692
Node: 系統函式11030469
Ref: c-api/sys system-functions11030588
Ref: 3e5d11030588
Ref: c-api/sys systemfunctions11030588
Ref: 3e5e11030588
Ref: c-api/sys c PySys_GetObject11030875
Ref: 3e5f11030875
Ref: c-api/sys c PySys_SetObject11031109
Ref: 3e6011031109
Ref: c-api/sys c PySys_ResetWarnOptions11031365
Ref: 3e6111031365
Ref: c-api/sys c PySys_AddWarnOption11031540
Ref: 5ad11031540
Ref: c-api/sys c PySys_AddWarnOptionUnicode11031769
Ref: 5ac11031769
Ref: c-api/sys c PySys_SetPath11032237
Ref: 3e6211032237
Ref: c-api/sys c PySys_WriteStdout11032501
Ref: 3e6311032501
Ref: c-api/sys c PySys_WriteStderr11033363
Ref: 3e6411033363
Ref: c-api/sys c PySys_FormatStdout11033531
Ref: 3e6511033531
Ref: c-api/sys c PySys_FormatStderr11033799
Ref: 3e6711033799
Ref: c-api/sys c PySys_AddXOption11033993
Ref: 3e6811033993
Ref: c-api/sys c PySys_GetXOptions11034297
Ref: 3e6911034297
Ref: c-api/sys c PySys_Audit11034574
Ref: 106811034574
Ref: c-api/sys c PySys_AddAuditHook11035674
Ref: 366b11035674
Ref: 系統函式-Footnote-111037187
Node: 行程（Process）控制11037236
Ref: c-api/sys process-control11037352
Ref: 3e6b11037352
Ref: c-api/sys processcontrol11037352
Ref: 3e6c11037352
Ref: c-api/sys c Py_FatalError11037411
Ref: 26611037411
Ref: c-api/sys c Py_Exit11038132
Ref: 70711038132
Ref: c-api/sys c Py_AtExit11038475
Ref: 3e6d11038475
Node: 匯入模組<2>11039123
Ref: c-api/import doc11039254
Ref: 3e6e11039254
Ref: c-api/import importing11039254
Ref: 3e6f11039254
Ref: c-api/import importing-modules11039254
Ref: 3e7011039254
Ref: c-api/import c PyImport_ImportModule11039289
Ref: d3b11039289
Ref: c-api/import c PyImport_ImportModuleNoBlock11040317
Ref: aa011040317
Ref: c-api/import c PyImport_ImportModuleEx11040788
Ref: bf411040788
Ref: c-api/import c PyImport_ImportModuleLevelObject11041514
Ref: 3e7111041514
Ref: c-api/import c PyImport_ImportModuleLevel11042270
Ref: bf311042270
Ref: c-api/import c PyImport_Import11042676
Ref: e2411042676
Ref: c-api/import c PyImport_ReloadModule11043190
Ref: 3e7211043190
Ref: c-api/import c PyImport_AddModuleObject11043450
Ref: 3e7311043450
Ref: c-api/import c PyImport_AddModule11044275
Ref: 3d3d11044275
Ref: c-api/import c PyImport_ExecCodeModule11044509
Ref: 3e7411044509
Ref: c-api/import c PyImport_ExecCodeModuleEx11046288
Ref: 3e7511046288
Ref: c-api/import c PyImport_ExecCodeModuleObject11046675
Ref: 3e7711046675
Ref: c-api/import c PyImport_ExecCodeModuleWithPathnames11047107
Ref: 3e7611047107
Ref: c-api/import c PyImport_GetMagicNumber11047733
Ref: bf211047733
Ref: c-api/import c PyImport_GetMagicTag11048069
Ref: 3e7811048069
Ref: c-api/import c PyImport_GetModuleDict11048374
Ref: 3e7911048374
Ref: c-api/import c PyImport_GetModule11048610
Ref: 52411048610
Ref: c-api/import c PyImport_GetImporter11048955
Ref: 3e7a11048955
Ref: c-api/import c PyImport_ImportFrozenModuleObject11049615
Ref: 3e7b11049615
Ref: c-api/import c PyImport_ImportFrozenModule11050206
Ref: 3e7c11050206
Ref: c-api/import c _frozen11050411
Ref: 3e7d11050411
Ref: c-api/import c PyImport_FrozenModules11050825
Ref: 245211050825
Ref: c-api/import c PyImport_AppendInittab11051145
Ref: f9c11051145
Ref: c-api/import c _inittab11051685
Ref: 3e7e11051685
Ref: c-api/import c PyImport_ExtendInittab11052341
Ref: f9d11052341
Ref: 匯入模組<2>-Footnote-111053141
Node: 数据 marshal 操作支持11053190
Ref: c-api/marshal doc11053323
Ref: 3e7f11053323
Ref: c-api/marshal data-marshalling-support11053323
Ref: 3e8011053323
Ref: c-api/marshal marshalling-utils11053323
Ref: 3e8111053323
Ref: c-api/marshal c PyMarshal_WriteLongToFile11054027
Ref: 3e8211054027
Ref: c-api/marshal c PyMarshal_WriteObjectToFile11054342
Ref: 3e8311054342
Ref: c-api/marshal c PyMarshal_WriteObjectToString11054563
Ref: 3e8411054563
Ref: c-api/marshal c PyMarshal_ReadLongFromFile11054883
Ref: 3e8511054883
Ref: c-api/marshal c PyMarshal_ReadShortFromFile11055225
Ref: 3e8611055225
Ref: c-api/marshal c PyMarshal_ReadObjectFromFile11055569
Ref: 3e8711055569
Ref: c-api/marshal c PyMarshal_ReadLastObjectFromFile11055913
Ref: 3e8811055913
Ref: c-api/marshal c PyMarshal_ReadObjectFromString11056636
Ref: 3e8911056636
Node: 语句解释及变量编译11057037
Ref: c-api/arg doc11057179
Ref: 3e8a11057179
Ref: c-api/arg arg-parsing11057179
Ref: 3f211057179
Ref: c-api/arg parsing-arguments-and-building-values11057179
Ref: 3e8b11057179
Node: 解析参数<3>11057757
Ref: c-api/arg parsing-arguments11057857
Ref: 3e8c11057857
Node: 字符串和缓存区11058483
Ref: c-api/arg strings-and-buffers11058571
Ref: 3e8d11058571
Node: 數字11070151
Ref: c-api/arg numbers11070260
Ref: 3e8f11070260
Node: 其他对象11072782
Ref: c-api/arg other-objects11072880
Ref: 3e9111072880
Ref: c-api/arg o-ampersand11073563
Ref: 3e9211073563
Node: API 函数11077680
Ref: c-api/arg api-functions11077763
Ref: 3e9311077763
Ref: c-api/arg c PyArg_ParseTuple11077800
Ref: 39311077800
Ref: c-api/arg c PyArg_VaParse11078066
Ref: 3e9411078066
Ref: c-api/arg c PyArg_ParseTupleAndKeywords11078299
Ref: 6c111078299
Ref: c-api/arg c PyArg_VaParseTupleAndKeywords11078838
Ref: e9e11078838
Ref: c-api/arg c PyArg_ValidateKeywordArguments11079138
Ref: 3e9511079138
Ref: c-api/arg c PyArg_Parse11079430
Ref: 10f011079430
Ref: c-api/arg c PyArg_UnpackTuple11079899
Ref: f0811079899
Node: 创建变量11081626
Ref: c-api/arg building-values11081726
Ref: 3e9611081726
Ref: c-api/arg c Py_BuildValue11081765
Ref: 3f011081765
Ref: c-api/arg c Py_VaBuildValue11089337
Ref: 3e9711089337
Node: 字串轉換與格式化11089589
Ref: c-api/conversion doc11089710
Ref: 3e9811089710
Ref: c-api/conversion string-conversion11089710
Ref: 3e9911089710
Ref: c-api/conversion string-conversion-and-formatting11089710
Ref: 3e9a11089710
Ref: c-api/conversion c PyOS_snprintf11089818
Ref: f0b11089818
Ref: c-api/conversion c PyOS_vsnprintf11090062
Ref: f0c11090062
Ref: c-api/conversion c PyOS_string_to_double11091671
Ref: ced11091671
Ref: c-api/conversion c PyOS_double_to_string11093316
Ref: 3e9b11093316
Ref: c-api/conversion c PyOS_stricmp11094798
Ref: 3e9c11094798
Ref: c-api/conversion c PyOS_strnicmp11094994
Ref: 3e9d11094994
Node: 反射11095220
Ref: c-api/reflection doc11095347
Ref: 3e9e11095347
Ref: c-api/reflection id111095347
Ref: 3e9f11095347
Ref: c-api/reflection reflection11095347
Ref: 3ea011095347
Ref: c-api/reflection c PyEval_GetBuiltins11095372
Ref: 3ea111095372
Ref: c-api/reflection c PyEval_GetLocals11095591
Ref: 3ea211095591
Ref: c-api/reflection c PyEval_GetGlobals11095789
Ref: 3ea311095789
Ref: c-api/reflection c PyEval_GetFrame11095988
Ref: 3ea411095988
Ref: c-api/reflection c PyFrame_GetBack11096234
Ref: 24a11096234
Ref: c-api/reflection c PyFrame_GetCode11096487
Ref: 24911096487
Ref: c-api/reflection c PyFrame_GetLineNumber11096723
Ref: 24b11096723
Ref: c-api/reflection c PyEval_GetFuncName11096880
Ref: 3ea511096880
Ref: c-api/reflection c PyEval_GetFuncDesc11097068
Ref: 3ea611097068
Node: 编解码器注册与支持功能11097369
Ref: c-api/codec doc11097463
Ref: 3ea711097463
Ref: c-api/codec codec-registry11097463
Ref: 6e511097463
Ref: c-api/codec codec-registry-and-support-functions11097463
Ref: 3ea811097463
Ref: c-api/codec c PyCodec_Register11097533
Ref: 3ea911097533
Ref: c-api/codec c PyCodec_KnownEncoding11097796
Ref: 3eaa11097796
Ref: c-api/codec c PyCodec_Encode11097992
Ref: 3eab11097992
Ref: c-api/codec c PyCodec_Decode11098446
Ref: 3eac11098446
Node: Codec 查找API11098993
Ref: c-api/codec codec-lookup-api11099139
Ref: 3ead11099139
Ref: c-api/codec c PyCodec_Encoder11099445
Ref: 3eae11099445
Ref: c-api/codec c PyCodec_Decoder11099606
Ref: 3eaf11099606
Ref: c-api/codec c PyCodec_IncrementalEncoder11099767
Ref: 3eb011099767
Ref: c-api/codec c PyCodec_IncrementalDecoder11099992
Ref: 3eb111099992
Ref: c-api/codec c PyCodec_StreamReader11100217
Ref: 3eb211100217
Ref: c-api/codec c PyCodec_StreamWriter11100454
Ref: 3eb311100454
Node: 用于Unicode编码错误处理程序的注册表API11100691
Ref: c-api/codec registry-api-for-unicode-encoding-error-handlers11100837
Ref: 3eb411100837
Ref: c-api/codec c PyCodec_RegisterError11100946
Ref: 3eb511100946
Ref: c-api/codec c PyCodec_LookupError11101987
Ref: 3eb611101987
Ref: c-api/codec c PyCodec_StrictErrors11102271
Ref: 3eb711102271
Ref: c-api/codec c PyCodec_IgnoreErrors11102396
Ref: 3eb811102396
Ref: c-api/codec c PyCodec_ReplaceErrors11102543
Ref: 3eb911102543
Ref: c-api/codec c PyCodec_XMLCharRefReplaceErrors11102711
Ref: 3eba11102711
Ref: c-api/codec c PyCodec_BackslashReplaceErrors11102880
Ref: 3ebb11102880
Ref: c-api/codec c PyCodec_NameReplaceErrors11103083
Ref: 89611103083
Node: 抽象物件層11103277
Ref: c-api/abstract doc11103399
Ref: 3ebc11103399
Ref: c-api/abstract abstract11103399
Ref: 3d8211103399
Ref: c-api/abstract abstract-objects-layer11103399
Ref: 3ebd11103399
Node: 对象协议11104017
Ref: c-api/object doc11104102
Ref: 3ebe11104102
Ref: c-api/object object11104102
Ref: 3ebf11104102
Ref: c-api/object object-protocol11104102
Ref: 3ec011104102
Ref: c-api/object c Py_NotImplemented11104137
Ref: 3ec111104137
Ref: c-api/object c Py_RETURN_NOTIMPLEMENTED11104283
Ref: 3ec211104283
Ref: c-api/object c PyObject_Print11104473
Ref: 118111104473
Ref: c-api/object c PyObject_HasAttr11104827
Ref: 3ec311104827
Ref: c-api/object c PyObject_HasAttrString11105284
Ref: 3ec511105284
Ref: c-api/object c PyObject_GetAttr11105796
Ref: 3ec411105796
Ref: c-api/object c PyObject_GetAttrString11106089
Ref: 3d3811106089
Ref: c-api/object c PyObject_GenericGetAttr11106397
Ref: 3ec611106397
Ref: c-api/object c PyObject_SetAttr11106934
Ref: 3ec711106934
Ref: c-api/object c PyObject_SetAttrString11107367
Ref: 3ec811107367
Ref: c-api/object c PyObject_GenericSetAttr11107811
Ref: 3ec911107811
Ref: c-api/object c PyObject_DelAttr11108359
Ref: 3eca11108359
Ref: c-api/object c PyObject_DelAttrString11108571
Ref: 3ecb11108571
Ref: c-api/object c PyObject_GenericGetDict11108801
Ref: 3ecc11108801
Ref: c-api/object c PyObject_GenericSetDict11109047
Ref: 3ecd11109047
Ref: c-api/object c PyObject_RichCompare11109267
Ref: 3d8011109267
Ref: c-api/object c PyObject_RichCompareBool11109821
Ref: 109c11109821
Ref: c-api/object c PyObject_Repr11110563
Ref: a4911110563
Ref: c-api/object c PyObject_ASCII11110979
Ref: 3ece11110979
Ref: c-api/object c PyObject_Str11111432
Ref: a4a11111432
Ref: c-api/object c PyObject_Bytes11111892
Ref: 3ecf11111892
Ref: c-api/object c PyObject_IsSubclass11112298
Ref: 88d11112298
Ref: c-api/object c PyObject_IsInstance11113189
Ref: 88c11113189
Ref: c-api/object c PyObject_Hash11114068
Ref: 3ed011114068
Ref: c-api/object c PyObject_HashNotImplemented11114373
Ref: df711114373
Ref: c-api/object c PyObject_IsTrue11114683
Ref: 3ed111114683
Ref: c-api/object c PyObject_Not11114900
Ref: 3ed211114900
Ref: c-api/object c PyObject_Type11115114
Ref: 3ed311115114
Ref: c-api/object c PyObject_TypeCheck11115667
Ref: 3d8911115667
Ref: c-api/object c PyObject_Size11115866
Ref: 3ed411115866
Ref: c-api/object c PyObject_Length11115919
Ref: 3ed511115919
Ref: c-api/object c PyObject_LengthHint11116162
Ref: a0d11116162
Ref: c-api/object c PyObject_GetItem11116559
Ref: 3dcb11116559
Ref: c-api/object c PyObject_SetItem11116795
Ref: 3dc911116795
Ref: c-api/object c PyObject_DelItem11117094
Ref: 3ed611117094
Ref: c-api/object c PyObject_Dir11117293
Ref: 3ed711117293
Ref: c-api/object c PyObject_GetIter11117765
Ref: 3ed811117765
Ref: 对象协议-Footnote-111118153
Ref: 对象协议-Footnote-211118202
Node: 调用协议11118251
Ref: c-api/call doc11118357
Ref: 3ed911118357
Ref: c-api/call call11118357
Ref: 3e4711118357
Ref: c-api/call call-protocol11118357
Ref: 3eda11118357
Node: tp_call 协议11118562
Ref: c-api/call the-tp-call-protocol11118651
Ref: 3edb11118651
Node: Vectorcall 协议11119368
Ref: c-api/call the-vectorcall-protocol11119485
Ref: 3edd11119485
Ref: c-api/call vectorcall11119485
Ref: 2b811119485
Ref: c-api/call c vectorcallfunc11120744
Ref: 3ee111120744
Ref: c-api/call c PY_VECTORCALL_ARGUMENTS_OFFSET11121624
Ref: 3ee311121624
Ref: Vectorcall 协议-Footnote-111123226
Node: 递归控制<2>11123275
Ref: c-api/call recursion-control11123374
Ref: 3ee611123374
Node: Vectorcall 支持 API11123778
Ref: c-api/call vectorcall-support-api11123877
Ref: 3ee711123877
Ref: c-api/call c PyVectorcall_NARGS11123936
Ref: 3ee211123936
Ref: c-api/call c PyVectorcall_Function11124327
Ref: 3ee811124327
Ref: c-api/call c PyVectorcall_Call11124866
Ref: 3ede11124866
Node: 调用对象的 API11125436
Ref: c-api/call capi-call11125555
Ref: 3edc11125555
Ref: c-api/call object-calling-api11125555
Ref: 3ee911125555
Ref: c-api/call c PyObject_Call11130248
Ref: 23c11130248
Ref: c-api/call c PyObject_CallNoArgs11130858
Ref: 25011130858
Ref: c-api/call c PyObject_CallOneArg11131187
Ref: 25611131187
Ref: c-api/call c PyObject_CallObject11131577
Ref: 3d2d11131577
Ref: c-api/call c PyObject_CallFunction11132014
Ref: 3f111132014
Ref: c-api/call c PyObject_CallMethod11132762
Ref: 3eea11132762
Ref: c-api/call c PyObject_CallFunctionObjArgs11133563
Ref: 3eeb11133563
Ref: c-api/call c PyObject_CallMethodObjArgs11134042
Ref: 111411134042
Ref: c-api/call c PyObject_CallMethodNoArgs11134536
Ref: 3eec11134536
Ref: c-api/call c PyObject_CallMethodOneArg11134950
Ref: 3eed11134950
Ref: c-api/call c PyObject_Vectorcall11135409
Ref: 3ee511135409
Ref: c-api/call c PyObject_VectorcallDict11135958
Ref: 3eee11135958
Ref: c-api/call c PyObject_VectorcallMethod11136639
Ref: 3ee411136639
Node: 调用支持 API11137675
Ref: c-api/call call-support-api11137768
Ref: 3ef011137768
Ref: c-api/call c PyCallable_Check11137815
Ref: 3ef111137815
Node: 数字协议11138024
Ref: c-api/number doc11138130
Ref: 3ef211138130
Ref: c-api/number number11138130
Ref: 3ef311138130
Ref: c-api/number number-protocol11138130
Ref: 3ef411138130
Ref: c-api/number c PyNumber_Check11138165
Ref: 39411138165
Ref: c-api/number c PyNumber_Add11138412
Ref: 3ef511138412
Ref: c-api/number c PyNumber_Subtract11138638
Ref: 3ef611138638
Ref: c-api/number c PyNumber_Multiply11138867
Ref: 3ef711138867
Ref: c-api/number c PyNumber_MatrixMultiply11139099
Ref: 89c11139099
Ref: c-api/number c PyNumber_FloorDivide11139379
Ref: 3ef811139379
Ref: c-api/number c PyNumber_TrueDivide11139625
Ref: 3ef911139625
Ref: c-api/number c PyNumber_Remainder11140015
Ref: 3efa11140015
Ref: c-api/number c PyNumber_Divmod11140251
Ref: 3efb11140251
Ref: c-api/number c PyNumber_Power11140496
Ref: 3efc11140496
Ref: c-api/number c PyNumber_Negative11140940
Ref: 3efd11140940
Ref: c-api/number c PyNumber_Positive11141136
Ref: 3efe11141136
Ref: c-api/number c PyNumber_Absolute11141323
Ref: 3eff11141323
Ref: c-api/number c PyNumber_Invert11141531
Ref: 3f0011141531
Ref: c-api/number c PyNumber_Lshift11141743
Ref: 3f0111141743
Ref: c-api/number c PyNumber_Rshift11141983
Ref: 3f0211141983
Ref: c-api/number c PyNumber_And11142224
Ref: 3f0311142224
Ref: c-api/number c PyNumber_Xor11142461
Ref: 3f0411142461
Ref: c-api/number c PyNumber_Or11142701
Ref: 3f0511142701
Ref: c-api/number c PyNumber_InPlaceAdd11142937
Ref: 3f0611142937
Ref: c-api/number c PyNumber_InPlaceSubtract11143238
Ref: 3f0711143238
Ref: c-api/number c PyNumber_InPlaceMultiply11143555
Ref: 3f0811143555
Ref: c-api/number c PyNumber_InPlaceMatrixMultiply11143877
Ref: 89d11143877
Ref: c-api/number c PyNumber_InPlaceFloorDivide11144236
Ref: 3f0911144236
Ref: c-api/number c PyNumber_InPlaceTrueDivide11144569
Ref: 3f0a11144569
Ref: c-api/number c PyNumber_InPlaceRemainder11145039
Ref: 3f0b11145039
Ref: c-api/number c PyNumber_InPlacePower11145360
Ref: 3f0c11145360
Ref: c-api/number c PyNumber_InPlaceLshift11145930
Ref: 3f0d11145930
Ref: c-api/number c PyNumber_InPlaceRshift11146254
Ref: 3f0e11146254
Ref: c-api/number c PyNumber_InPlaceAnd11146578
Ref: 3f0f11146578
Ref: c-api/number c PyNumber_InPlaceXor11146885
Ref: 3f1011146885
Ref: c-api/number c PyNumber_InPlaceOr11147193
Ref: 3f1111147193
Ref: c-api/number c PyNumber_Long11147499
Ref: 39511147499
Ref: c-api/number c PyNumber_Float11147728
Ref: 39611147728
Ref: c-api/number c PyNumber_Index11147960
Ref: 3f1211147960
Ref: c-api/number c PyNumber_ToBase11148187
Ref: 107711148187
Ref: c-api/number c PyNumber_AsSsize_t11148681
Ref: 3f1311148681
Ref: c-api/number c PyIndex_Check11149338
Ref: 26e11149338
Node: 序列协议11149567
Ref: c-api/sequence doc11149673
Ref: 3f1411149673
Ref: c-api/sequence sequence11149673
Ref: 3f1511149673
Ref: c-api/sequence sequence-protocol11149673
Ref: 3f1611149673
Ref: c-api/sequence c PySequence_Check11149708
Ref: 3f1711149708
Ref: c-api/sequence c PySequence_Size11150088
Ref: 118211150088
Ref: c-api/sequence c PySequence_Length11150143
Ref: 3f1811150143
Ref: c-api/sequence c PySequence_Concat11150339
Ref: 3f1911150339
Ref: c-api/sequence c PySequence_Repeat11150572
Ref: 3f1a11150572
Ref: c-api/sequence c PySequence_InPlaceConcat11150821
Ref: 3f1b11150821
Ref: c-api/sequence c PySequence_InPlaceRepeat11151133
Ref: 3f1c11151133
Ref: c-api/sequence c PySequence_GetItem11151514
Ref: 118311151514
Ref: c-api/sequence c PySequence_GetSlice11151739
Ref: 3f1d11151739
Ref: c-api/sequence c PySequence_SetItem11152011
Ref: 118411152011
Ref: c-api/sequence c PySequence_DelItem11152472
Ref: 118511152472
Ref: c-api/sequence c PySequence_SetSlice11152664
Ref: 3f1e11152664
Ref: c-api/sequence c PySequence_DelSlice11152907
Ref: 3f1f11152907
Ref: c-api/sequence c PySequence_Count11153146
Ref: 3f2011153146
Ref: c-api/sequence c PySequence_Contains11153415
Ref: 3f2111153415
Ref: c-api/sequence c PySequence_Index11153704
Ref: 3f2211153704
Ref: c-api/sequence c PySequence_List11153922
Ref: 3f2311153922
Ref: c-api/sequence c PySequence_Tuple11154222
Ref: 3f2411154222
Ref: c-api/sequence c PySequence_Fast11154606
Ref: 3f2511154606
Ref: c-api/sequence c PySequence_Fast_GET_SIZE11155295
Ref: 3f2711155295
Ref: c-api/sequence c PySequence_Fast_GET_ITEM11155691
Ref: 3f2811155691
Ref: c-api/sequence c PySequence_Fast_ITEMS11155982
Ref: 3f2911155982
Ref: c-api/sequence c PySequence_ITEM11156341
Ref: 3f2a11156341
Node: 映射协议11156701
Ref: c-api/mapping doc11156810
Ref: 3f2b11156810
Ref: c-api/mapping mapping11156810
Ref: 3f2c11156810
Ref: c-api/mapping mapping-protocol11156810
Ref: 3f2d11156810
Ref: c-api/mapping c PyMapping_Check11156958
Ref: 3f2e11156958
Ref: c-api/mapping c PyMapping_Size11157300
Ref: 118611157300
Ref: c-api/mapping c PyMapping_Length11157354
Ref: 3f2f11157354
Ref: c-api/mapping c PyMapping_GetItemString11157541
Ref: 3f3011157541
Ref: c-api/mapping c PyMapping_SetItemString11157865
Ref: 3f3111157865
Ref: c-api/mapping c PyMapping_DelItem11158204
Ref: 3f3211158204
Ref: c-api/mapping c PyMapping_DelItemString11158469
Ref: 3f3311158469
Ref: c-api/mapping c PyMapping_HasKey11158681
Ref: 3f3411158681
Ref: c-api/mapping c PyMapping_HasKeyString11159086
Ref: 3f3511159086
Ref: c-api/mapping c PyMapping_Keys11159506
Ref: 52f11159506
Ref: c-api/mapping c PyMapping_Values11159767
Ref: 53011159767
Ref: c-api/mapping c PyMapping_Items11160030
Ref: 53111160030
Node: 迭代器协议11160347
Ref: c-api/iter doc11160456
Ref: 3f3611160456
Ref: c-api/iter iterator11160456
Ref: 3f3711160456
Ref: c-api/iter iterator-protocol11160456
Ref: 3f3811160456
Ref: c-api/iter c PyIter_Check11160525
Ref: 114911160525
Ref: c-api/iter c PyIter_Next11160668
Ref: 3f3911160668
Node: 缓冲协议11161577
Ref: c-api/buffer doc11161689
Ref: 3f3a11161689
Ref: c-api/buffer buffer-protocol11161689
Ref: 3f3b11161689
Ref: c-api/buffer bufferobjects11161689
Ref: 171c11161689
Node: 缓冲区结构11164040
Ref: c-api/buffer buffer-structure11164137
Ref: 3f3d11164137
Ref: c-api/buffer id111164137
Ref: 3f3e11164137
Ref: c-api/buffer c Py_buffer11165128
Ref: bee11165128
Ref: c-api/buffer c Py_buffer buf11165153
Ref: 3f4011165153
Ref: c-api/buffer c Py_buffer obj11165540
Ref: 3f4211165540
Ref: c-api/buffer c Py_buffer len11166054
Ref: 3f4511166054
Ref: c-api/buffer c Py_buffer readonly11166603
Ref: 3f4811166603
Ref: c-api/buffer c Py_buffer itemsize11166759
Ref: 3f4911166759
Ref: c-api/buffer c Py_buffer format11167632
Ref: 3f4a11167632
Ref: c-api/buffer c Py_buffer ndim11167930
Ref: 3f4d11167930
Ref: c-api/buffer c Py_buffer shape11168452
Ref: 3f4c11168452
Ref: c-api/buffer c Py_buffer strides11168987
Ref: 3f4111168987
Ref: c-api/buffer c Py_buffer suboffsets11169490
Ref: 3f4e11169490
Ref: c-api/buffer c Py_buffer internal11170289
Ref: 3f5011170289
Node: 缓冲区请求的类型11170594
Ref: c-api/buffer buffer-request-types11170712
Ref: 3f5111170712
Ref: c-api/buffer id211170712
Ref: 3f5211170712
Node: 与请求无关的字段11171240
Ref: c-api/buffer request-independent-fields11171349
Ref: 3f5311171349
Node: 只读，格式11171590
Ref: c-api/buffer readonly-format11171738
Ref: 3f5411171738
Ref: c-api/buffer c PyBUF_WRITABLE11171782
Ref: 3f4711171782
Ref: c-api/buffer c PyBUF_FORMAT11172108
Ref: 3f4b11172108
Node: 形状，步幅，子偏移量11172708
Ref: c-api/buffer shape-strides-suboffsets11172850
Ref: 3f5511172850
Ref: c-api/buffer c PyBUF_INDIRECT11173355
Ref: 3f5611173355
Ref: c-api/buffer c PyBUF_STRIDES11173559
Ref: 3f5711173559
Ref: c-api/buffer c PyBUF_ND11173745
Ref: 3f5811173745
Ref: c-api/buffer c PyBUF_SIMPLE11173939
Ref: 3f4611173939
Node: 连续性的请求11174042
Ref: c-api/buffer contiguity-requests11174181
Ref: 3f5911174181
Ref: c-api/buffer c PyBUF_C_CONTIGUOUS11174778
Ref: 3f5a11174778
Ref: c-api/buffer c PyBUF_F_CONTIGUOUS11175035
Ref: 3f5b11175035
Ref: c-api/buffer c PyBUF_ANY_CONTIGUOUS11175294
Ref: 3f5c11175294
Node: 复合请求11175694
Ref: c-api/buffer compound-requests11175794
Ref: 3f5d11175794
Ref: c-api/buffer c PyBUF_FULL11176609
Ref: 3f5f11176609
Ref: c-api/buffer c PyBUF_FULL_RO11176949
Ref: 3f6011176949
Ref: c-api/buffer c PyBUF_RECORDS11177287
Ref: 3f6111177287
Ref: c-api/buffer c PyBUF_RECORDS_RO11177621
Ref: 3f6211177621
Ref: c-api/buffer c PyBUF_STRIDED11177950
Ref: 3f6311177950
Ref: c-api/buffer c PyBUF_STRIDED_RO11178285
Ref: 3f6411178285
Ref: c-api/buffer c PyBUF_CONTIG11178614
Ref: 3f6511178614
Ref: c-api/buffer c PyBUF_CONTIG_RO11178948
Ref: 3f6611178948
Node: 复杂数组11179144
Ref: c-api/buffer complex-arrays11179268
Ref: 3f4f11179268
Node: NumPy-风格：形状和步幅11179400
Ref: c-api/buffer numpy-style-shape-and-strides11179531
Ref: 3f6711179531
Node: PIL-风格：形状，步幅和子偏移量11181377
Ref: c-api/buffer pil-style-shape-strides-and-suboffsets11181508
Ref: 3f6811181508
Node: 缓冲区相关函数11182630
Ref: c-api/buffer buffer-related-functions11182721
Ref: 3f6911182721
Ref: c-api/buffer c PyObject_CheckBuffer11182777
Ref: 26c11182777
Ref: c-api/buffer c PyObject_GetBuffer11183039
Ref: deb11183039
Ref: c-api/buffer c PyBuffer_Release11183952
Ref: e1911183952
Ref: c-api/buffer c PyBuffer_SizeFromFormat11184296
Ref: 10c411184296
Ref: c-api/buffer c PyBuffer_IsContiguous11184514
Ref: 3f5e11184514
Ref: c-api/buffer c PyBuffer_GetPointer11184853
Ref: 3f6a11184853
Ref: c-api/buffer c PyBuffer_FromContiguous11185084
Ref: 3f6b11185084
Ref: c-api/buffer c PyBuffer_ToContiguous11185408
Ref: 3f6c11185408
Ref: c-api/buffer c PyBuffer_FillContiguousStrides11185847
Ref: 3f6d11185847
Ref: c-api/buffer c PyBuffer_FillInfo11186240
Ref: 3f4411186240
Node: 旧缓冲协议11187195
Ref: c-api/objbuffer doc11187283
Ref: 3f6e11187283
Ref: c-api/objbuffer old-buffer-protocol11187283
Ref: 3f6f11187283
Ref: c-api/objbuffer c PyObject_AsCharBuffer11187965
Ref: 3f7011187965
Ref: c-api/objbuffer c PyObject_AsReadBuffer11188402
Ref: 3f7111188402
Ref: c-api/objbuffer c PyObject_CheckReadBuffer11188826
Ref: 3f7211188826
Ref: c-api/objbuffer c PyObject_AsWriteBuffer11189227
Ref: 3f7311189227
Node: 具体的对象层11189615
Ref: c-api/concrete doc11189755
Ref: 3f7411189755
Ref: c-api/concrete concrete11189755
Ref: 3f7511189755
Ref: c-api/concrete concrete-objects-layer11189755
Ref: 3f7611189755
Node: 基本对象11190601
Ref: c-api/concrete fundamental11190689
Ref: 3f7811190689
Ref: c-api/concrete fundamental-objects11190689
Ref: 3f7911190689
Node: Type 对象11190831
Ref: c-api/type doc11190911
Ref: 3f7a11190911
Ref: c-api/type type-objects11190911
Ref: 3f7b11190911
Ref: c-api/type typeobjects11190911
Ref: 3f7c11190911
Ref: c-api/type c PyTypeObject11190950
Ref: 3f511190950
Ref: c-api/type c PyType_Type11191034
Ref: 3f7d11191034
Ref: c-api/type c PyType_Check11191190
Ref: 109411191190
Ref: c-api/type c PyType_CheckExact11191434
Ref: 109511191434
Ref: c-api/type c PyType_ClearCache11191661
Ref: 3f7e11191661
Ref: c-api/type c PyType_GetFlags11191782
Ref: 101211191782
Ref: c-api/type c PyType_Modified11192263
Ref: 3f7f11192263
Ref: c-api/type c PyType_HasFeature11192518
Ref: 101011192518
Ref: c-api/type c PyType_IS_GC11192711
Ref: 3f8011192711
Ref: c-api/type c PyType_IsSubtype11192901
Ref: 3f8111192901
Ref: c-api/type c PyType_GenericAlloc11193259
Ref: 39911193259
Ref: c-api/type c PyType_GenericNew11193601
Ref: 3d5811193601
Ref: c-api/type c PyType_Ready11193891
Ref: 3d5d11193891
Ref: c-api/type c PyType_GetSlot11194745
Ref: a0911194745
Ref: c-api/type c PyType_GetModule11195274
Ref: 24611195274
Ref: c-api/type c PyType_GetModuleState11196042
Ref: 24711196042
Node: Creating Heap-Allocated Types11196610
Ref: c-api/type creating-heap-allocated-types11196687
Ref: 3f8211196687
Ref: c-api/type c PyType_FromModuleAndSpec11196844
Ref: 24511196844
Ref: c-api/type c PyType_FromSpecWithBases11197912
Ref: 102d11197912
Ref: c-api/type c PyType_FromSpec11198140
Ref: 23a11198140
Ref: c-api/type c PyType_Spec11198301
Ref: 3f8511198301
Ref: c-api/type c PyType_Spec PyType_Spec name11198374
Ref: 3f8611198374
Ref: c-api/type c PyType_Spec PyType_Spec basicsize11198514
Ref: 3f8711198514
Ref: c-api/type c PyType_Spec PyType_Spec itemsize11198566
Ref: 3f8811198566
Ref: c-api/type c PyType_Spec PyType_Spec flags11198771
Ref: 3f8911198771
Ref: c-api/type c PyType_Spec PyType_Spec slots11199023
Ref: 3f8a11199023
Ref: c-api/type c PyType_Slot11199202
Ref: 3f8b11199202
Ref: c-api/type c PyType_Slot PyType_Slot slot11199335
Ref: 3f8c11199335
Ref: c-api/type c PyType_Slot PyType_Slot pfunc11201350
Ref: 3f9a11201350
Node: None 对象11201535
Ref: c-api/none doc11201615
Ref: 3f9b11201615
Ref: c-api/none noneobject11201615
Ref: 3f9c11201615
Ref: c-api/none the-none-object11201615
Ref: 3f9d11201615
Ref: c-api/none c Py_None11201917
Ref: 3d2311201917
Ref: c-api/none c Py_RETURN_NONE11202094
Ref: e9b11202094
Node: 数值对象11202264
Ref: c-api/concrete numeric-objects11202373
Ref: 3f9e11202373
Ref: c-api/concrete numericobjects11202373
Ref: 3f9f11202373
Node: 整數物件11202509
Ref: c-api/long doc11202591
Ref: 3fa011202591
Ref: c-api/long integer-objects11202591
Ref: 3fa111202591
Ref: c-api/long longobjects11202591
Ref: 3fa211202591
Ref: c-api/long c PyLongObject11202867
Ref: 3fa311202867
Ref: c-api/long c PyLong_Type11202965
Ref: 3fa411202965
Ref: c-api/long c PyLong_Check11203135
Ref: 3fa511203135
Ref: c-api/long c PyLong_CheckExact11203335
Ref: 3fa611203335
Ref: c-api/long c PyLong_FromLong11203548
Ref: 3d2011203548
Ref: c-api/long c PyLong_FromUnsignedLong11203963
Ref: 10c011203963
Ref: c-api/long c PyLong_FromSsize_t11204189
Ref: 3fa711204189
Ref: c-api/long c PyLong_FromSize_t11204409
Ref: 10c211204409
Ref: c-api/long c PyLong_FromLongLong11204614
Ref: 3fa811204614
Ref: c-api/long c PyLong_FromUnsignedLongLong11204821
Ref: 10c111204821
Ref: c-api/long c PyLong_FromDouble11205055
Ref: 1f411205055
Ref: c-api/long c PyLong_FromString11205264
Ref: 3fa911205264
Ref: c-api/long c PyLong_FromUnicode11206072
Ref: 3faa11206072
Ref: c-api/long c PyLong_FromUnicodeObject11206455
Ref: 3fab11206455
Ref: c-api/long c PyLong_FromVoidPtr11206669
Ref: 3fac11206669
Ref: c-api/long c PyLong_AsLong11206875
Ref: 39211206875
Ref: c-api/long c PyLong_AsLongAndOverflow11207509
Ref: cc811207509
Ref: c-api/long c PyLong_AsLongLong11208372
Ref: 3fae11208372
Ref: c-api/long c PyLong_AsLongLongAndOverflow11209000
Ref: cc711209000
Ref: c-api/long c PyLong_AsSsize_t11209914
Ref: 3faf11209914
Ref: c-api/long c PyLong_AsUnsignedLong11210303
Ref: 3fb011210303
Ref: c-api/long c PyLong_AsSize_t11210718
Ref: 3fb111210718
Ref: c-api/long c PyLong_AsUnsignedLongLong11211099
Ref: cec11211099
Ref: c-api/long c PyLong_AsUnsignedLongMask11211657
Ref: 3fb211211657
Ref: c-api/long c PyLong_AsUnsignedLongLongMask11212372
Ref: 10f411212372
Ref: c-api/long c PyLong_AsDouble11213122
Ref: 3fb311213122
Ref: c-api/long c PyLong_AsVoidPtr11213497
Ref: 3fad11213497
Node: 布林物件11213926
Ref: c-api/bool doc11214052
Ref: 3fb411214052
Ref: c-api/bool boolean-objects11214052
Ref: 3fb511214052
Ref: c-api/bool boolobjects11214052
Ref: 3fb611214052
Ref: c-api/bool c PyBool_Check11214300
Ref: 3fb711214300
Ref: c-api/bool c Py_False11214447
Ref: 3fb811214447
Ref: c-api/bool c Py_True11214595
Ref: 3fb911214595
Ref: c-api/bool c Py_RETURN_FALSE11214741
Ref: e9d11214741
Ref: c-api/bool c Py_RETURN_TRUE11214849
Ref: e9c11214849
Ref: c-api/bool c PyBool_FromLong11214955
Ref: 3fba11214955
Node: 浮點數（Floating Point）物件11215137
Ref: c-api/float doc11215263
Ref: 3fbb11215263
Ref: c-api/float floating-point-objects11215263
Ref: 3fbc11215263
Ref: c-api/float floatobjects11215263
Ref: 3fbd11215263
Ref: c-api/float c PyFloatObject11215345
Ref: 3fbe11215345
Ref: c-api/float c PyFloat_Type11215464
Ref: 3fbf11215464
Ref: c-api/float c PyFloat_Check11215669
Ref: 3fc011215669
Ref: c-api/float c PyFloat_CheckExact11215881
Ref: 3fc111215881
Ref: c-api/float c PyFloat_FromString11216101
Ref: 3fc211216101
Ref: c-api/float c PyFloat_FromDouble11216302
Ref: 3fc311216302
Ref: c-api/float c PyFloat_AsDouble11216488
Ref: 39711216488
Ref: c-api/float c PyFloat_AS_DOUBLE11217075
Ref: 3fc411217075
Ref: c-api/float c PyFloat_GetInfo11217223
Ref: e1c11217223
Ref: c-api/float c PyFloat_GetMax11217477
Ref: e1a11217477
Ref: c-api/float c PyFloat_GetMin11217596
Ref: e1b11217596
Node: 复数对象11217718
Ref: c-api/complex doc11217823
Ref: 3fc511217823
Ref: c-api/complex complex-number-objects11217823
Ref: 3fc611217823
Ref: c-api/complex complexobjects11217823
Ref: 3fc711217823
Node: 表示复数的C结构体11218148
Ref: c-api/complex complex-numbers-as-c-structures11218258
Ref: 3fc811218258
Ref: c-api/complex c Py_complex11218484
Ref: 3e9011218484
Ref: c-api/complex c _Py_c_sum11218814
Ref: 3fc911218814
Ref: c-api/complex c _Py_c_diff11218966
Ref: 3fca11218966
Ref: c-api/complex c _Py_c_neg11219119
Ref: 3fcb11219119
Ref: c-api/complex c _Py_c_prod11219249
Ref: 3fcc11219249
Ref: c-api/complex c _Py_c_quot11219405
Ref: 3fcd11219405
Ref: c-api/complex c _Py_c_pow11219667
Ref: 3fce11219667
Node: 表示复数的Python对象11219940
Ref: c-api/complex complex-numbers-as-python-objects11220050
Ref: 3fcf11220050
Ref: c-api/complex c PyComplexObject11220116
Ref: 3fd011220116
Ref: c-api/complex c PyComplex_Type11220236
Ref: 3fd111220236
Ref: c-api/complex c PyComplex_Check11220447
Ref: 3fd211220447
Ref: c-api/complex c PyComplex_CheckExact11220665
Ref: 3fd311220665
Ref: c-api/complex c PyComplex_FromCComplex11220891
Ref: 3fd411220891
Ref: c-api/complex c PyComplex_FromDoubles11221080
Ref: 3fd511221080
Ref: c-api/complex c PyComplex_RealAsDouble11221286
Ref: 3fd611221286
Ref: c-api/complex c PyComplex_ImagAsDouble11221401
Ref: 3fd711221401
Ref: c-api/complex c PyComplex_AsCComplex11221516
Ref: e1d11221516
Node: 序列对象11222133
Ref: c-api/concrete sequence-objects11222242
Ref: 3fd811222242
Ref: c-api/concrete sequenceobjects11222242
Ref: 3fd911222242
Node: 字节对象11222550
Ref: c-api/bytes doc11222638
Ref: 3fda11222638
Ref: c-api/bytes bytes-objects11222638
Ref: 3fdb11222638
Ref: c-api/bytes bytesobjects11222638
Ref: 3fdc11222638
Ref: c-api/bytes c PyBytesObject11222806
Ref: de411222806
Ref: c-api/bytes c PyBytes_Type11222917
Ref: 3fdd11222917
Ref: c-api/bytes c PyBytes_Check11223102
Ref: de511223102
Ref: c-api/bytes c PyBytes_CheckExact11223293
Ref: 3fde11223293
Ref: c-api/bytes c PyBytes_FromString11223492
Ref: 3fdf11223492
Ref: c-api/bytes c PyBytes_FromStringAndSize11223763
Ref: de611223763
Ref: c-api/bytes c PyBytes_FromFormat11224100
Ref: 114411224100
Ref: c-api/bytes c PyBytes_FromFormatV11227533
Ref: 3fe011227533
Ref: c-api/bytes c PyBytes_FromObject11227749
Ref: 3fe111227749
Ref: c-api/bytes c PyBytes_Size11227904
Ref: 3fe211227904
Ref: c-api/bytes c PyBytes_GET_SIZE11228006
Ref: 3fe311228006
Ref: c-api/bytes c PyBytes_AsString11228138
Ref: 3fe411228138
Ref: c-api/bytes c PyBytes_AS_STRING11228722
Ref: 3fe511228722
Ref: c-api/bytes c PyBytes_AsStringAndSize11228859
Ref: 3fe611228859
Ref: c-api/bytes c PyBytes_Concat11229817
Ref: 3fe711229817
Ref: c-api/bytes c PyBytes_ConcatAndDel11230236
Ref: 3fe811230236
Ref: c-api/bytes c _PyBytes_Resize11230487
Ref: 117f11230487
Ref: 字节对象-Footnote-111231359
Ref: 字节对象-Footnote-211231485
Ref: 字节对象-Footnote-311231611
Ref: 字节对象-Footnote-411231737
Ref: 字节对象-Footnote-511231863
Ref: 字节对象-Footnote-611231989
Ref: 字节对象-Footnote-711232115
Ref: 字节对象-Footnote-811232241
Node: 字节数组对象11232367
Ref: c-api/bytearray doc11232486
Ref: 3fe911232486
Ref: c-api/bytearray byte-array-objects11232486
Ref: 3fea11232486
Ref: c-api/bytearray bytearrayobjects11232486
Ref: 3feb11232486
Ref: c-api/bytearray c PyByteArrayObject11232535
Ref: 3fec11232535
Ref: c-api/bytearray c PyByteArray_Type11232656
Ref: 3fed11232656
Node: 类型检查宏11232909
Ref: c-api/bytearray type-check-macros11233005
Ref: 3fee11233005
Ref: c-api/bytearray c PyByteArray_Check11233049
Ref: 3fef11233049
Ref: c-api/bytearray c PyByteArray_CheckExact11233252
Ref: 3ff011233252
Node: 直接 API 函数11233463
Ref: c-api/bytearray direct-api-functions11233571
Ref: 3ff111233571
Ref: c-api/bytearray c PyByteArray_FromObject11233620
Ref: de711233620
Ref: c-api/bytearray c PyByteArray_FromStringAndSize11233830
Ref: de811233830
Ref: c-api/bytearray c PyByteArray_Concat11234081
Ref: 3ff211234081
Ref: c-api/bytearray c PyByteArray_Size11234277
Ref: 3ff311234277
Ref: c-api/bytearray c PyByteArray_AsString11234410
Ref: 3ff411234410
Ref: c-api/bytearray c PyByteArray_Resize11234627
Ref: 3ff511234627
Node: 宏11234771
Ref: c-api/bytearray macros11234855
Ref: 3ff611234855
Ref: c-api/bytearray c PyByteArray_AS_STRING11234947
Ref: 3ff711234947
Ref: c-api/bytearray c PyByteArray_GET_SIZE11235078
Ref: 3ff811235078
Node: Unicode物件與編碼11235209
Ref: c-api/unicode doc11235339
Ref: bef11235339
Ref: c-api/unicode unicode-objects-and-codecs11235339
Ref: 3ff911235339
Ref: c-api/unicode unicodeobjects11235339
Ref: 3ffa11235339
Node: Unicode对象11235476
Ref: c-api/unicode unicode-objects11235572
Ref: 3ffb11235572
Ref: Unicode对象-Footnote-111237176
Ref: Unicode对象-Footnote-211237225
Node: Unicode类型11237274
Ref: c-api/unicode unicode-type11237365
Ref: 3ffc11237365
Ref: c-api/unicode c Py_UCS411237497
Ref: baa11237497
Ref: c-api/unicode c Py_UCS211237519
Ref: ba911237519
Ref: c-api/unicode c Py_UCS111237541
Ref: ba811237541
Ref: c-api/unicode c Py_UNICODE11237810
Ref: bc511237810
Ref: c-api/unicode c PyASCIIObject11238137
Ref: bab11238137
Ref: c-api/unicode c PyCompactUnicodeObject11238165
Ref: bac11238165
Ref: c-api/unicode c PyUnicodeObject11238202
Ref: 3ffd11238202
Ref: c-api/unicode c PyUnicode_Type11238511
Ref: 3ffe11238511
Ref: c-api/unicode c PyUnicode_Check11238819
Ref: 3fff11238819
Ref: c-api/unicode c PyUnicode_CheckExact11238998
Ref: 400011238998
Ref: c-api/unicode c PyUnicode_READY11239180
Ref: bad11239180
Ref: c-api/unicode c PyUnicode_GET_LENGTH11239690
Ref: ba311239690
Ref: c-api/unicode c PyUnicode_1BYTE_DATA11239929
Ref: bb211239929
Ref: c-api/unicode c PyUnicode_2BYTE_DATA11239987
Ref: bb311239987
Ref: c-api/unicode c PyUnicode_4BYTE_DATA11240045
Ref: bb411240045
Ref: c-api/unicode c PyUnicode_WCHAR_KIND11240506
Ref: bb611240506
Ref: c-api/unicode c PyUnicode_1BYTE_KIND11240541
Ref: bb711240541
Ref: c-api/unicode c PyUnicode_2BYTE_KIND11240576
Ref: bb811240576
Ref: c-api/unicode c PyUnicode_4BYTE_KIND11240611
Ref: bb911240611
Ref: c-api/unicode c PyUnicode_KIND11240851
Ref: bb511240851
Ref: c-api/unicode c PyUnicode_DATA11241176
Ref: bb111241176
Ref: c-api/unicode c PyUnicode_WRITE11241391
Ref: bbc11241391
Ref: c-api/unicode c PyUnicode_READ11241954
Ref: bba11241954
Ref: c-api/unicode c PyUnicode_READ_CHAR11242230
Ref: bbb11242230
Ref: c-api/unicode c PyUnicode_MAX_CHAR_VALUE11242534
Ref: bbd11242534
Ref: c-api/unicode c PyUnicode_GET_SIZE11242845
Ref: bc911242845
Ref: c-api/unicode c PyUnicode_GET_DATA_SIZE11243271
Ref: bcb11243271
Ref: c-api/unicode c PyUnicode_AS_UNICODE11243653
Ref: bc711243653
Ref: c-api/unicode c PyUnicode_AS_DATA11243714
Ref: bc811243714
Ref: c-api/unicode c PyUnicode_IsIdentifier11244773
Ref: 109111244773
Node: Unicode字符属性11245121
Ref: c-api/unicode unicode-character-properties11245259
Ref: 400111245259
Ref: c-api/unicode c Py_UNICODE_ISSPACE11245501
Ref: fd611245501
Ref: c-api/unicode c Py_UNICODE_ISLOWER11245642
Ref: 400211245642
Ref: c-api/unicode c Py_UNICODE_ISUPPER11245782
Ref: 400311245782
Ref: c-api/unicode c Py_UNICODE_ISTITLE11245923
Ref: 400411245923
Ref: c-api/unicode c Py_UNICODE_ISLINEBREAK11246063
Ref: 400511246063
Ref: c-api/unicode c Py_UNICODE_ISDECIMAL11246207
Ref: 400611246207
Ref: c-api/unicode c Py_UNICODE_ISDIGIT11246342
Ref: 400711246342
Ref: c-api/unicode c Py_UNICODE_ISNUMERIC11246473
Ref: 400811246473
Ref: c-api/unicode c Py_UNICODE_ISALPHA11246608
Ref: 400911246608
Ref: c-api/unicode c Py_UNICODE_ISALNUM11246750
Ref: 400a11246750
Ref: c-api/unicode c Py_UNICODE_ISPRINTABLE11246894
Ref: 400b11246894
Ref: c-api/unicode c Py_UNICODE_TOLOWER11247552
Ref: 400c11247552
Ref: c-api/unicode c Py_UNICODE_TOUPPER11247732
Ref: 400d11247732
Ref: c-api/unicode c Py_UNICODE_TOTITLE11247912
Ref: 400e11247912
Ref: c-api/unicode c Py_UNICODE_TODECIMAL11248092
Ref: 400f11248092
Ref: c-api/unicode c Py_UNICODE_TODIGIT11248308
Ref: 401011248308
Ref: c-api/unicode c Py_UNICODE_TONUMERIC11248518
Ref: 401111248518
Ref: c-api/unicode c Py_UNICODE_IS_SURROGATE11248766
Ref: 401211248766
Ref: c-api/unicode c Py_UNICODE_IS_HIGH_SURROGATE11248877
Ref: 401311248877
Ref: c-api/unicode c Py_UNICODE_IS_LOW_SURROGATE11248998
Ref: 401411248998
Ref: c-api/unicode c Py_UNICODE_JOIN_SURROGATES11249117
Ref: 401511249117
Node: Creating and accessing Unicode strings11249343
Ref: c-api/unicode creating-and-accessing-unicode-strings11249494
Ref: 401611249494
Ref: c-api/unicode c PyUnicode_New11249678
Ref: ba411249678
Ref: c-api/unicode c PyUnicode_FromKindAndData11250167
Ref: bae11250167
Ref: c-api/unicode c PyUnicode_FromStringAndSize11250622
Ref: 401711250622
Ref: c-api/unicode c PyUnicode_FromString11251289
Ref: 3da911251289
Ref: c-api/unicode c PyUnicode_FromFormat11251471
Ref: 8b811251471
Ref: c-api/unicode c PyUnicode_FromFormatV11258416
Ref: 3e6611258416
Ref: c-api/unicode c PyUnicode_FromEncodedObject11258648
Ref: 401811258648
Ref: c-api/unicode c PyUnicode_GetLength11259408
Ref: ba211259408
Ref: c-api/unicode c PyUnicode_CopyCharacters11259561
Ref: ba111259561
Ref: c-api/unicode c PyUnicode_Fill11260034
Ref: bce11260034
Ref: c-api/unicode c PyUnicode_WriteChar11260509
Ref: ba711260509
Ref: c-api/unicode c PyUnicode_ReadChar11261068
Ref: ba611261068
Ref: c-api/unicode c PyUnicode_Substring11261390
Ref: ba511261390
Ref: c-api/unicode c PyUnicode_AsUCS411261709
Ref: baf11261709
Ref: c-api/unicode c PyUnicode_AsUCS4Copy11262136
Ref: bb011262136
Ref: Creating and accessing Unicode strings-Footnote-111262512
Ref: Creating and accessing Unicode strings-Footnote-211262665
Ref: Creating and accessing Unicode strings-Footnote-311262818
Ref: Creating and accessing Unicode strings-Footnote-411262971
Ref: Creating and accessing Unicode strings-Footnote-511263124
Ref: Creating and accessing Unicode strings-Footnote-611263277
Ref: Creating and accessing Unicode strings-Footnote-711263430
Ref: Creating and accessing Unicode strings-Footnote-811263583
Ref: Creating and accessing Unicode strings-Footnote-911263736
Ref: Creating and accessing Unicode strings-Footnote-1011263889
Ref: Creating and accessing Unicode strings-Footnote-1111264043
Ref: Creating and accessing Unicode strings-Footnote-1211264197
Ref: Creating and accessing Unicode strings-Footnote-1311264351
Node: Deprecated Py_UNICODE APIs11264505
Ref: c-api/unicode deprecated-py-unicode-apis11264652
Ref: 401a11264652
Ref: c-api/unicode c PyUnicode_FromUnicode11265030
Ref: 26311265030
Ref: c-api/unicode c PyUnicode_AsUnicode11266074
Ref: 26411266074
Ref: c-api/unicode c PyUnicode_TransformDecimalToASCII11266969
Ref: be211266969
Ref: c-api/unicode c PyUnicode_AsUnicodeAndSize11267520
Ref: 26511267520
Ref: c-api/unicode c PyUnicode_AsUnicodeCopy11268252
Ref: bcc11268252
Ref: c-api/unicode c PyUnicode_GetSize11268895
Ref: bca11268895
Ref: c-api/unicode c PyUnicode_FromObject11269279
Ref: 401b11269279
Ref: Deprecated Py_UNICODE APIs-Footnote-111269707
Node: Locale Encoding11269756
Ref: c-api/unicode locale-encoding11269885
Ref: 401c11269885
Ref: c-api/unicode c PyUnicode_DecodeLocaleAndSize11270019
Ref: 54011270019
Ref: c-api/unicode c PyUnicode_DecodeLocale11271183
Ref: 401d11271183
Ref: c-api/unicode c PyUnicode_EncodeLocale11271457
Ref: 54111271457
Ref: Locale Encoding-Footnote-111272636
Ref: Locale Encoding-Footnote-211272685
Node: File System Encoding11272734
Ref: c-api/unicode file-system-encoding11272852
Ref: 401e11272852
Ref: c-api/unicode c PyUnicode_FSConverter11273334
Ref: 6c511273334
Ref: c-api/unicode c PyUnicode_FSDecoder11274040
Ref: 6c611274040
Ref: c-api/unicode c PyUnicode_DecodeFSDefaultAndSize11274593
Ref: 3e5c11274593
Ref: c-api/unicode c PyUnicode_DecodeFSDefault11275363
Ref: 401f11275363
Ref: c-api/unicode c PyUnicode_EncodeFSDefault11275880
Ref: 118011275880
Ref: File System Encoding-Footnote-111276790
Ref: File System Encoding-Footnote-211276839
Node: wchar_t Support11276888
Ref: c-api/unicode wchar-t-support11276982
Ref: 402011276982
Ref: c-api/unicode c PyUnicode_FromWideChar11277088
Ref: bc611277088
Ref: c-api/unicode c PyUnicode_AsWideChar11277450
Ref: 118711277450
Ref: c-api/unicode c PyUnicode_AsWideCharString11278255
Ref: 53b11278255
Node: Built-in Codecs11279316
Ref: c-api/unicode built-in-codecs11279447
Ref: 402111279447
Ref: c-api/unicode builtincodecs11279447
Ref: 401911279447
Node: Generic Codecs11280872
Ref: c-api/unicode generic-codecs11280959
Ref: 402211280959
Ref: c-api/unicode c PyUnicode_Decode11281043
Ref: 10ee11281043
Ref: c-api/unicode c PyUnicode_AsEncodedString11281562
Ref: 402311281562
Ref: c-api/unicode c PyUnicode_Encode11282071
Ref: bcf11282071
Node: UTF-8 Codecs11282811
Ref: c-api/unicode utf-8-codecs11282920
Ref: 402411282920
Ref: c-api/unicode c PyUnicode_DecodeUTF811282998
Ref: 402511282998
Ref: c-api/unicode c PyUnicode_DecodeUTF8Stateful11283296
Ref: 402611283296
Ref: c-api/unicode c PyUnicode_AsUTF8String11283792
Ref: bd211283792
Ref: c-api/unicode c PyUnicode_AsUTF8AndSize11284078
Ref: 52d11284078
Ref: c-api/unicode c PyUnicode_AsUTF811284998
Ref: 52e11284998
Ref: c-api/unicode c PyUnicode_EncodeUTF811285259
Ref: bd111285259
Node: UTF-32 Codecs11285879
Ref: c-api/unicode utf-32-codecs11285987
Ref: 402711285987
Ref: c-api/unicode c PyUnicode_DecodeUTF3211286068
Ref: 402811286068
Ref: c-api/unicode c PyUnicode_DecodeUTF32Stateful11287212
Ref: 402911287212
Ref: c-api/unicode c PyUnicode_AsUTF32String11287832
Ref: 402a11287832
Ref: c-api/unicode c PyUnicode_EncodeUTF3211288161
Ref: bd311288161
Node: UTF-16 Codecs11289207
Ref: c-api/unicode utf-16-codecs11289315
Ref: 402b11289315
Ref: c-api/unicode c PyUnicode_DecodeUTF1611289396
Ref: 402c11289396
Ref: c-api/unicode c PyUnicode_DecodeUTF16Stateful11290620
Ref: 402d11290620
Ref: c-api/unicode c PyUnicode_AsUTF16String11291249
Ref: 402e11291249
Ref: c-api/unicode c PyUnicode_EncodeUTF1611291578
Ref: bd411291578
Node: UTF-7 Codecs11292749
Ref: c-api/unicode utf-7-codecs11292865
Ref: 402f11292865
Ref: c-api/unicode c PyUnicode_DecodeUTF711292943
Ref: 403011292943
Ref: c-api/unicode c PyUnicode_DecodeUTF7Stateful11293241
Ref: 403111293241
Ref: c-api/unicode c PyUnicode_EncodeUTF711293739
Ref: bd011293739
Node: Unicode-Escape Codecs11294571
Ref: c-api/unicode unicode-escape-codecs11294699
Ref: 403211294699
Ref: c-api/unicode c PyUnicode_DecodeUnicodeEscape11294806
Ref: 403311294806
Ref: c-api/unicode c PyUnicode_AsUnicodeEscapeString11295122
Ref: bd611295122
Ref: c-api/unicode c PyUnicode_EncodeUnicodeEscape11295436
Ref: bd511295436
Node: Raw-Unicode-Escape Codecs11295955
Ref: c-api/unicode raw-unicode-escape-codecs11296085
Ref: 403411296085
Ref: c-api/unicode c PyUnicode_DecodeRawUnicodeEscape11296204
Ref: 403511296204
Ref: c-api/unicode c PyUnicode_AsRawUnicodeEscapeString11296527
Ref: bd811296527
Ref: c-api/unicode c PyUnicode_EncodeRawUnicodeEscape11296848
Ref: bd711296848
Node: Latin-1 Codecs11297431
Ref: c-api/unicode latin-1-codecs11297552
Ref: 403611297552
Ref: c-api/unicode c PyUnicode_DecodeLatin111297749
Ref: 403711297749
Ref: c-api/unicode c PyUnicode_AsLatin1String11298051
Ref: bda11298051
Ref: c-api/unicode c PyUnicode_EncodeLatin111298346
Ref: bd911298346
Node: ASCII Codecs11298920
Ref: c-api/unicode ascii-codecs11299036
Ref: 403811299036
Ref: c-api/unicode c PyUnicode_DecodeASCII11299184
Ref: 403911299184
Ref: c-api/unicode c PyUnicode_AsASCIIString11299483
Ref: bdc11299483
Ref: c-api/unicode c PyUnicode_EncodeASCII11299770
Ref: bdb11299770
Node: Character Map Codecs11300340
Ref: c-api/unicode character-map-codecs11300465
Ref: 403a11300465
Ref: c-api/unicode c PyUnicode_DecodeCharmap11300944
Ref: 403b11300944
Ref: c-api/unicode c PyUnicode_AsCharmapString11301766
Ref: 403c11301766
Ref: c-api/unicode c PyUnicode_EncodeCharmap11302416
Ref: bdd11302416
Ref: c-api/unicode c PyUnicode_Translate11303112
Ref: 403d11303112
Ref: c-api/unicode c PyUnicode_TranslateCharmap11303949
Ref: bde11303949
Node: MBCS codecs for Windows11304585
Ref: c-api/unicode mbcs-codecs-for-windows11304713
Ref: 403e11304713
Ref: c-api/unicode c PyUnicode_DecodeMBCS11305073
Ref: 403f11305073
Ref: c-api/unicode c PyUnicode_DecodeMBCSStateful11305370
Ref: 404011305370
Ref: c-api/unicode c PyUnicode_AsMBCSString11305833
Ref: be011305833
Ref: c-api/unicode c PyUnicode_EncodeCodePage11306118
Ref: be111306118
Ref: c-api/unicode c PyUnicode_EncodeMBCS11306512
Ref: bdf11306512
Node: Methods & Slots11307122
Ref: c-api/unicode methods-slots11307221
Ref: 404111307221
Node: Methods and Slot Functions11307272
Ref: c-api/unicode methods-and-slot-functions11307381
Ref: 404211307381
Ref: c-api/unicode unicodemethodsandslots11307381
Ref: 404311307381
Ref: c-api/unicode c PyUnicode_Concat11307704
Ref: bf011307704
Ref: c-api/unicode c PyUnicode_Split11307870
Ref: 404411307870
Ref: c-api/unicode c PyUnicode_Splitlines11308333
Ref: 404511308333
Ref: c-api/unicode c PyUnicode_Join11308671
Ref: bf111308671
Ref: c-api/unicode c PyUnicode_Tailmatch11308896
Ref: 27211308896
Ref: c-api/unicode c PyUnicode_Find11309295
Ref: 404611309295
Ref: c-api/unicode c PyUnicode_FindChar11309831
Ref: 54211309831
Ref: c-api/unicode c PyUnicode_Count11310497
Ref: 404711310497
Ref: c-api/unicode c PyUnicode_Replace11310753
Ref: 404811310753
Ref: c-api/unicode c PyUnicode_Compare11311103
Ref: bcd11311103
Ref: c-api/unicode c PyUnicode_CompareWithASCIIString11311423
Ref: cc911311423
Ref: c-api/unicode c PyUnicode_RichCompare11311877
Ref: 404911311877
Ref: c-api/unicode c PyUnicode_Format11312405
Ref: 404a11312405
Ref: c-api/unicode c PyUnicode_Contains11312629
Ref: 404b11312629
Ref: c-api/unicode c PyUnicode_InternInPlace11312932
Ref: 404c11312932
Ref: c-api/unicode c PyUnicode_InternFromString11313705
Ref: 404d11313705
Node: 元組（Tuple）物件11314082
Ref: c-api/tuple doc11314212
Ref: 404e11314212
Ref: c-api/tuple tuple-objects11314212
Ref: 404f11314212
Ref: c-api/tuple tupleobjects11314212
Ref: 405011314212
Ref: c-api/tuple c PyTupleObject11314273
Ref: 3e6a11314273
Ref: c-api/tuple c PyTuple_Type11314387
Ref: 405111314387
Ref: c-api/tuple c PyTuple_Check11314572
Ref: 405211314572
Ref: c-api/tuple c PyTuple_CheckExact11314756
Ref: 405311314756
Ref: c-api/tuple c PyTuple_New11314949
Ref: 405411314949
Ref: c-api/tuple c PyTuple_Pack11315139
Ref: 405511315139
Ref: c-api/tuple c PyTuple_Size11315484
Ref: 405611315484
Ref: c-api/tuple c PyTuple_GET_SIZE11315610
Ref: 405711315610
Ref: c-api/tuple c PyTuple_GetItem11315787
Ref: 3d3911315787
Ref: c-api/tuple c PyTuple_GET_ITEM11316070
Ref: 405811316070
Ref: c-api/tuple c PyTuple_GetSlice11316256
Ref: 405911316256
Ref: c-api/tuple c PyTuple_SetItem11316597
Ref: 3d3e11316597
Ref: c-api/tuple c PyTuple_SET_ITEM11317029
Ref: 405a11317029
Ref: c-api/tuple c _PyTuple_Resize11317507
Ref: f0d11317507
Node: 结构序列对象11318347
Ref: c-api/tuple struct-sequence-objects11318477
Ref: 405b11318477
Ref: c-api/tuple c PyStructSequence_NewType11318742
Ref: f9e11318742
Ref: c-api/tuple c PyStructSequence_InitType11319045
Ref: a0c11319045
Ref: c-api/tuple c PyStructSequence_InitType211319212
Ref: a0b11319212
Ref: c-api/tuple c PyStructSequence_Desc11319457
Ref: 52c11319457
Ref: c-api/tuple c PyStructSequence_Field11320956
Ref: 52b11320956
Ref: c-api/tuple c PyStructSequence_UnnamedField11322066
Ref: 26211322066
Ref: c-api/tuple c PyStructSequence_New11322248
Ref: 405c11322248
Ref: c-api/tuple c PyStructSequence_GetItem11322453
Ref: 405d11322453
Ref: c-api/tuple c PyStructSequence_GET_ITEM11322690
Ref: 405e11322690
Ref: c-api/tuple c PyStructSequence_SetItem11322884
Ref: 405f11322884
Ref: c-api/tuple c PyStructSequence_SET_ITEM11323225
Ref: 406011323225
Node: List（串列）物件11323463
Ref: c-api/list doc11323561
Ref: 406111323561
Ref: c-api/list list-objects11323561
Ref: 406211323561
Ref: c-api/list listobjects11323561
Ref: 406311323561
Ref: c-api/list c PyListObject11323620
Ref: 3f2611323620
Ref: c-api/list c PyList_Type11323735
Ref: 3d6b11323735
Ref: c-api/list c PyList_Check11323931
Ref: 406411323931
Ref: c-api/list c PyList_CheckExact11324113
Ref: 406511324113
Ref: c-api/list c PyList_New11324302
Ref: 3dca11324302
Ref: c-api/list c PyList_Size11324810
Ref: e4311324810
Ref: c-api/list c PyList_GET_SIZE11324963
Ref: 406611324963
Ref: c-api/list c PyList_GetItem11325099
Ref: 3d3a11325099
Ref: c-api/list c PyList_GET_ITEM11325478
Ref: 406711325478
Ref: c-api/list c PyList_SetItem11325671
Ref: 3d3f11325671
Ref: c-api/list c PyList_SET_ITEM11326099
Ref: 406811326099
Ref: c-api/list c PyList_Insert11326597
Ref: 406911326597
Ref: c-api/list c PyList_Append11326920
Ref: 406a11326920
Ref: c-api/list c PyList_GetSlice11327179
Ref: 406b11327179
Ref: c-api/list c PyList_SetSlice11327550
Ref: 406c11327550
Ref: c-api/list c PyList_Sort11328001
Ref: 406d11328001
Ref: c-api/list c PyList_Reverse11328193
Ref: 406e11328193
Ref: c-api/list c PyList_AsTuple11328391
Ref: 406f11328391
Node: 容器对象11328586
Ref: c-api/concrete container-objects11328698
Ref: 407011328698
Ref: c-api/concrete mapobjects11328698
Ref: 407111328698
Node: 字典物件11328777
Ref: c-api/dict doc11328859
Ref: 407211328859
Ref: c-api/dict dictionary-objects11328859
Ref: 407311328859
Ref: c-api/dict dictobjects11328859
Ref: 407411328859
Ref: c-api/dict c PyDictObject11328898
Ref: 407511328898
Ref: c-api/dict c PyDict_Type11328998
Ref: 407611328998
Ref: c-api/dict c PyDict_Check11329178
Ref: 3f7711329178
Ref: c-api/dict c PyDict_CheckExact11329349
Ref: 407711329349
Ref: c-api/dict c PyDict_New11329540
Ref: 407811329540
Ref: c-api/dict c PyDictProxy_New11329680
Ref: 407911329680
Ref: c-api/dict c PyDict_Clear11329954
Ref: 407a11329954
Ref: c-api/dict c PyDict_Contains11330047
Ref: 407b11330047
Ref: c-api/dict c PyDict_Copy11330339
Ref: 407c11330339
Ref: c-api/dict c PyDict_SetItem11330477
Ref: 3d4011330477
Ref: c-api/dict c PyDict_SetItemString11330828
Ref: 407d11330828
Ref: c-api/dict c PyDict_DelItem11331199
Ref: 407e11331199
Ref: c-api/dict c PyDict_DelItemString11331529
Ref: 407f11331529
Ref: c-api/dict c PyDict_GetItem11331801
Ref: 3d3b11331801
Ref: c-api/dict c PyDict_GetItemWithError11332252
Ref: 408011332252
Ref: c-api/dict c PyDict_GetItemString11332606
Ref: 3d3c11332606
Ref: c-api/dict c PyDict_SetDefault11333113
Ref: 408111333113
Ref: c-api/dict c PyDict_Items11333622
Ref: 408211333622
Ref: c-api/dict c PyDict_Keys11333790
Ref: 408311333790
Ref: c-api/dict c PyDict_Values11333957
Ref: 408411333957
Ref: c-api/dict c PyDict_Size11334128
Ref: 408511334128
Ref: c-api/dict c PyDict_Next11334259
Ref: 408611334259
Ref: c-api/dict c PyDict_Merge11336001
Ref: 408711336001
Ref: c-api/dict c PyDict_Update11336559
Ref: 408811336559
Ref: c-api/dict c PyDict_MergeFromSeq211336938
Ref: 408911336938
Node: 集合对象11337571
Ref: c-api/set doc11337653
Ref: 408a11337653
Ref: c-api/set set-objects11337653
Ref: 408b11337653
Ref: c-api/set setobjects11337653
Ref: 408c11337653
Ref: c-api/set c PySetObject11338408
Ref: 408d11338408
Ref: c-api/set c PySet_Type11339019
Ref: 408e11339019
Ref: c-api/set c PyFrozenSet_Type11339156
Ref: 408f11339156
Ref: c-api/set c PySet_Check11339454
Ref: 409011339454
Ref: c-api/set c PyFrozenSet_Check11339637
Ref: 409111339637
Ref: c-api/set c PyAnySet_Check11339832
Ref: 409211339832
Ref: c-api/set c PyAnySet_CheckExact11340049
Ref: 409311340049
Ref: c-api/set c PyFrozenSet_CheckExact11340266
Ref: 409411340266
Ref: c-api/set c PySet_New11340466
Ref: e7011340466
Ref: c-api/set c PyFrozenSet_New11340933
Ref: e7111340933
Ref: c-api/set c PySet_Size11341473
Ref: e7511341473
Ref: c-api/set c PySet_GET_SIZE11341769
Ref: 409511341769
Ref: c-api/set c PySet_Contains11341897
Ref: e7411341897
Ref: c-api/set c PySet_Add11342423
Ref: e7211342423
Ref: c-api/set c PySet_Discard11343170
Ref: e7311343170
Ref: c-api/set c PySet_Pop11343743
Ref: 409611343743
Ref: c-api/set c PySet_Clear11344109
Ref: 409711344109
Node: 函式物件<2>11344202
Ref: c-api/concrete function-objects11344317
Ref: 409811344317
Ref: c-api/concrete otherobjects11344317
Ref: 409911344317
Node: 函式（Function）物件11344482
Ref: c-api/function doc11344587
Ref: 409a11344587
Ref: c-api/function function-objects11344587
Ref: 409b11344587
Ref: c-api/function id111344587
Ref: 409c11344587
Ref: c-api/function c PyFunctionObject11344705
Ref: 409d11344705
Ref: c-api/function c PyFunction_Type11344774
Ref: 409e11344774
Ref: c-api/function c PyFunction_Check11344972
Ref: 409f11344972
Ref: c-api/function c PyFunction_New11345194
Ref: 40a011345194
Ref: c-api/function c PyFunction_NewWithQualName11345674
Ref: 40a111345674
Ref: c-api/function c PyFunction_GetCode11346122
Ref: 40a211346122
Ref: c-api/function c PyFunction_GetGlobals11346281
Ref: 40a311346281
Ref: c-api/function c PyFunction_GetModule11346447
Ref: 40a411346447
Ref: c-api/function c PyFunction_GetDefaults11346723
Ref: 40a511346723
Ref: c-api/function c PyFunction_SetDefaults11346927
Ref: 40a611346927
Ref: c-api/function c PyFunction_GetClosure11347201
Ref: 40a711347201
Ref: c-api/function c PyFunction_SetClosure11347408
Ref: 40a811347408
Ref: c-api/function c PyFunction_GetAnnotations11347677
Ref: 40a911347677
Ref: c-api/function c PyFunction_SetAnnotations11347875
Ref: 40aa11347875
Node: 實體方法物件11348147
Ref: c-api/method doc11348273
Ref: 40ab11348273
Ref: c-api/method instance-method-objects11348273
Ref: 40ac11348273
Ref: c-api/method instancemethod-objects11348273
Ref: 40ad11348273
Ref: c-api/method c PyInstanceMethod_Type11348521
Ref: 40ae11348521
Ref: c-api/method c PyInstanceMethod_Check11348693
Ref: 40af11348693
Ref: c-api/method c PyInstanceMethod_New11348932
Ref: 40b011348932
Ref: c-api/method c PyInstanceMethod_Function11349175
Ref: 40b111349175
Ref: c-api/method c PyInstanceMethod_GET_FUNCTION11349340
Ref: 40b211349340
Node: 方法对象11349537
Ref: c-api/method id111349648
Ref: 40b311349648
Ref: c-api/method method-objects11349648
Ref: 40b411349648
Ref: c-api/method c PyMethod_Type11349854
Ref: 40b511349854
Ref: c-api/method c PyMethod_Check11350035
Ref: 40b611350035
Ref: c-api/method c PyMethod_New11350253
Ref: 40b711350253
Ref: c-api/method c PyMethod_Function11350574
Ref: 40b811350574
Ref: c-api/method c PyMethod_GET_FUNCTION11350729
Ref: 40b911350729
Ref: c-api/method c PyMethod_Self11350912
Ref: 40ba11350912
Ref: c-api/method c PyMethod_GET_SELF11351051
Ref: 40bb11351051
Node: Cell 物件11351226
Ref: c-api/cell doc11351334
Ref: 40bc11351334
Ref: c-api/cell cell-objects11351334
Ref: 40bd11351334
Ref: c-api/cell id111351334
Ref: 40be11351334
Ref: c-api/cell c PyCellObject11351918
Ref: 40bf11351918
Ref: c-api/cell c PyCell_Type11351976
Ref: 40c011351976
Ref: c-api/cell c PyCell_Check11352059
Ref: 40c111352059
Ref: c-api/cell c PyCell_New11352225
Ref: 40c211352225
Ref: c-api/cell c PyCell_Get11352404
Ref: 40c311352404
Ref: c-api/cell c PyCell_GET11352528
Ref: 40c411352528
Ref: c-api/cell c PyCell_Set11352741
Ref: 40c511352741
Ref: c-api/cell c PyCell_SET11353096
Ref: 40c611353096
Ref: c-api/code codeobjects11353350
Ref: 40c711353350
Node: 代码对象<2>11353351
Ref: c-api/code doc11353438
Ref: 40c811353438
Ref: c-api/code code-objects11353438
Ref: 40c911353438
Ref: c-api/code c PyCodeObject11353592
Ref: 40ca11353592
Ref: c-api/code c PyCode_Type11353709
Ref: 40cb11353709
Ref: c-api/code c PyCode_Check11353852
Ref: 40cc11353852
Ref: c-api/code c PyCode_GetNumFree11354008
Ref: 40cd11354008
Ref: c-api/code c PyCode_New11354107
Ref: 39b11354107
Ref: c-api/code c PyCode_NewWithPosOnlyArgs11354758
Ref: 39a11354758
Ref: c-api/code c PyCode_NewEmpty11355314
Ref: db111355314
Node: 其他对象<2>11355644
Ref: c-api/concrete other-objects11355738
Ref: 40ce11355738
Node: 檔案（File）物件11356107
Ref: c-api/file doc11356208
Ref: 40cf11356208
Ref: c-api/file file-objects11356208
Ref: 40d011356208
Ref: c-api/file fileobjects11356208
Ref: 40d111356208
Ref: c-api/file c PyFile_FromFd11356725
Ref: 40d211356725
Ref: c-api/file c PyObject_AsFileDescriptor11357597
Ref: 40d311357597
Ref: c-api/file c PyFile_GetLine11357989
Ref: 40d411357989
Ref: c-api/file c PyFile_SetOpenCodeHook11358716
Ref: 214411358716
Ref: c-api/file c PyFile_WriteObject11359850
Ref: 40d511359850
Ref: c-api/file c PyFile_WriteString11360222
Ref: 40d611360222
Node: 模組物件模組11360428
Ref: c-api/module doc11360567
Ref: 40d711360567
Ref: c-api/module module-objects11360567
Ref: 40d811360567
Ref: c-api/module moduleobjects11360567
Ref: 40d911360567
Ref: c-api/module c PyModule_Type11360616
Ref: 40da11360616
Ref: c-api/module c PyModule_Check11360814
Ref: 40db11360814
Ref: c-api/module c PyModule_CheckExact11360977
Ref: 40dc11360977
Ref: c-api/module c PyModule_NewObject11361160
Ref: 40dd11361160
Ref: c-api/module c PyModule_New11361746
Ref: 40de11361746
Ref: c-api/module c PyModule_GetDict11361963
Ref: 40df11361963
Ref: c-api/module c PyModule_GetNameObject11362550
Ref: 40e011362550
Ref: c-api/module c PyModule_GetName11362866
Ref: 40e111362866
Ref: c-api/module c PyModule_GetState11363035
Ref: 25e11363035
Ref: c-api/module c PyModule_GetDef11363271
Ref: 40e211363271
Ref: c-api/module c PyModule_GetFilenameObject11363504
Ref: 40e311363504
Ref: c-api/module c PyModule_GetFilename11363934
Ref: 40e411363934
Node: Initializing C modules11364354
Ref: c-api/module initializing-c-modules11364453
Ref: 40e511364453
Ref: c-api/module initializing-modules11364453
Ref: 3d8d11364453
Ref: c-api/module c PyModuleDef11365080
Ref: 25811365080
Ref: c-api/module c PyModuleDef m_base11365304
Ref: 40e611365304
Ref: c-api/module c PyModuleDef m_name11365427
Ref: 40e711365427
Ref: c-api/module c PyModuleDef m_doc11365508
Ref: 40e811365508
Ref: c-api/module c PyModuleDef m_size11365676
Ref: 25d11365676
Ref: c-api/module c PyModuleDef m_methods11366625
Ref: 40e911366625
Ref: c-api/module c PyModuleDef m_slots11366846
Ref: 40ea11366846
Ref: c-api/module c PyModuleDef m_reload11367220
Ref: 40eb11367220
Ref: c-api/module c PyModuleDef m_traverse11367273
Ref: 25911367273
Ref: c-api/module c PyModuleDef m_clear11367976
Ref: 25a11367976
Ref: c-api/module c PyModuleDef m_free11369009
Ref: 25b11369009
Ref: Initializing C modules-Footnote-111369865
Node: Single-phase initialization11369914
Ref: c-api/module single-phase-initialization11370035
Ref: 40ec11370035
Ref: c-api/module c PyModule_Create11370310
Ref: 3d2611370310
Ref: c-api/module c PyModule_Create211370591
Ref: 40ed11370591
Node: Multi-phase initialization11371293
Ref: c-api/module id111371458
Ref: 40ee11371458
Ref: c-api/module multi-phase-initialization11371458
Ref: 3d8e11371458
Ref: c-api/module c PyModuleDef_Init11373049
Ref: 40ef11373049
Ref: c-api/module c PyModuleDef_Slot11373496
Ref: 40f011373496
Ref: c-api/module c PyModuleDef_Slot slot11373528
Ref: 40f111373528
Ref: c-api/module c PyModuleDef_Slot value11373635
Ref: 40f211373635
Ref: c-api/module c Py_mod_create11373857
Ref: 40f311373857
Ref: c-api/module c create_module11374051
Ref: 40f411374051
Ref: c-api/module c Py_mod_exec11375468
Ref: 25c11375468
Ref: c-api/module c exec_module11375741
Ref: 40f511375741
Ref: Multi-phase initialization-Footnote-111376026
Ref: Multi-phase initialization-Footnote-211376075
Node: Low-level module creation functions11376124
Ref: c-api/module low-level-module-creation-functions11376279
Ref: 40f611376279
Ref: c-api/module c PyModule_FromDefAndSpec11376658
Ref: 89911376658
Ref: c-api/module c PyModule_FromDefAndSpec211377034
Ref: 89a11377034
Ref: c-api/module c PyModule_ExecDef11377655
Ref: 89b11377655
Ref: c-api/module c PyModule_SetDocString11377833
Ref: 40f711377833
Ref: c-api/module c PyModule_AddFunctions11378168
Ref: 40f811378168
Node: Support functions11378852
Ref: c-api/module support-functions11378972
Ref: 40f911378972
Ref: c-api/module c PyModule_AddObject11379258
Ref: 10dd11379258
Ref: c-api/module c PyModule_AddIntConstant11380173
Ref: 40fa11380173
Ref: c-api/module c PyModule_AddStringConstant11380468
Ref: 40fb11380468
Ref: c-api/module c PyModule_AddIntMacro11380827
Ref: 40fc11380827
Ref: c-api/module c PyModule_AddStringMacro11381172
Ref: e1e11381172
Ref: c-api/module c PyModule_AddType11381282
Ref: 25311381282
Node: Module lookup11381657
Ref: c-api/module module-lookup11381756
Ref: 40fd11381756
Ref: c-api/module c PyState_FindModule11382175
Ref: 40fe11382175
Ref: c-api/module c PyState_AddModule11382657
Ref: 40ff11382657
Ref: c-api/module c PyState_RemoveModule11383587
Ref: 410011383587
Node: 迭代器（Iterator）物件11383827
Ref: c-api/iterator doc11383959
Ref: 410111383959
Ref: c-api/iterator id111383959
Ref: 410211383959
Ref: c-api/iterator iterator-objects11383959
Ref: 410311383959
Ref: c-api/iterator c PySeqIter_Type11384321
Ref: 410411384321
Ref: c-api/iterator c PySeqIter_Check11384516
Ref: 410611384516
Ref: c-api/iterator c PySeqIter_New11384674
Ref: 410511384674
Ref: c-api/iterator c PyCallIter_Type11384911
Ref: 410711384911
Ref: c-api/iterator c PyCallIter_Check11385100
Ref: 410911385100
Ref: c-api/iterator c PyCallIter_New11385260
Ref: 410811385260
Node: 修飾器物件11385672
Ref: c-api/descriptor doc11385798
Ref: 410a11385798
Ref: c-api/descriptor descriptor-objects11385798
Ref: 410b11385798
Ref: c-api/descriptor id111385798
Ref: 410c11385798
Ref: c-api/descriptor c PyProperty_Type11385945
Ref: 410d11385945
Ref: c-api/descriptor c PyDescr_NewGetSet11386035
Ref: 410e11386035
Ref: c-api/descriptor c PyDescr_NewMember11386173
Ref: 410f11386173
Ref: c-api/descriptor c PyDescr_NewMethod11386309
Ref: 107611386309
Ref: c-api/descriptor c PyDescr_NewWrapper11386445
Ref: 411011386445
Ref: c-api/descriptor c PyDescr_NewClassMethod11386600
Ref: 411111386600
Ref: c-api/descriptor c PyDescr_IsData11386736
Ref: 411211386736
Ref: c-api/descriptor c PyWrapper_New11386963
Ref: 411311386963
Node: 切片物件11387063
Ref: c-api/slice doc11387175
Ref: 411411387175
Ref: c-api/slice id111387175
Ref: 411511387175
Ref: c-api/slice slice-objects11387175
Ref: 411611387175
Ref: c-api/slice c PySlice_Type11387216
Ref: 411711387216
Ref: c-api/slice c PySlice_Check11387364
Ref: 411811387364
Ref: c-api/slice c PySlice_New11387542
Ref: 411911387542
Ref: c-api/slice c PySlice_GetIndices11388004
Ref: 411a11388004
Ref: c-api/slice c PySlice_GetIndicesEx11388669
Ref: 57611388669
Ref: c-api/slice c PySlice_Unpack11390525
Ref: 53211390525
Ref: c-api/slice c PySlice_AdjustIndices11391096
Ref: 53311391096
Node: Ellipsis 对象11391503
Ref: c-api/slice ellipsis-object11391617
Ref: 411b11391617
Ref: c-api/slice c Py_Ellipsis11391666
Ref: 411c11391666
Ref: c-api/memoryview memoryview-objects11391913
Ref: 3f3f11391913
Node: MemoryView 对象11391914
Ref: c-api/memoryview doc11392031
Ref: 411d11392031
Ref: c-api/memoryview id111392031
Ref: 411e11392031
Ref: c-api/memoryview c PyMemoryView_FromObject11392237
Ref: 411f11392237
Ref: c-api/memoryview c PyMemoryView_FromMemory11392573
Ref: ba011392573
Ref: c-api/memoryview c PyMemoryView_FromBuffer11392879
Ref: 3f4311392879
Ref: c-api/memoryview c PyMemoryView_GetContiguous11393154
Ref: 412011393154
Ref: c-api/memoryview c PyMemoryView_Check11393592
Ref: 412111393592
Ref: c-api/memoryview c PyMemoryView_GET_BUFFER11393808
Ref: 412211393808
Ref: c-api/memoryview c PyMemoryView_GET_BASE11394099
Ref: 412311394099
Node: 弱參照物件11394437
Ref: c-api/weakref doc11394553
Ref: 412411394553
Ref: c-api/weakref weak-reference-objects11394553
Ref: 412511394553
Ref: c-api/weakref weakrefobjects11394553
Ref: 412611394553
Ref: c-api/weakref c PyWeakref_Check11394806
Ref: 412711394806
Ref: c-api/weakref c PyWeakref_CheckRef11394947
Ref: 412811394947
Ref: c-api/weakref c PyWeakref_CheckProxy11395082
Ref: 412911395082
Ref: c-api/weakref c PyWeakref_NewRef11395219
Ref: 412a11395219
Ref: c-api/weakref c PyWeakref_NewProxy11395964
Ref: 412b11395964
Ref: c-api/weakref c PyWeakref_GetObject11396720
Ref: 412c11396720
Ref: c-api/weakref c PyWeakref_GET_OBJECT11397188
Ref: 412d11397188
Node: Capsule 对象11397386
Ref: c-api/capsule doc11397500
Ref: 412e11397500
Ref: c-api/capsule capsules11397500
Ref: 3d4b11397500
Ref: c-api/capsule id111397500
Ref: 412f11397500
Ref: c-api/capsule c PyCapsule11397658
Ref: cd211397658
Ref: c-api/capsule c PyCapsule_Destructor11398082
Ref: 413011398082
Ref: c-api/capsule c PyCapsule_CheckExact11398341
Ref: 413111398341
Ref: c-api/capsule c PyCapsule_New11398504
Ref: 3d4911398504
Ref: c-api/capsule c PyCapsule_GetPointer11399394
Ref: 413211399394
Ref: c-api/capsule c PyCapsule_GetDestructor11399852
Ref: 413311399852
Ref: c-api/capsule c PyCapsule_GetContext11400267
Ref: 413411400267
Ref: c-api/capsule c PyCapsule_GetName11400654
Ref: 413511400654
Ref: c-api/capsule c PyCapsule_Import11401038
Ref: 3d4a11401038
Ref: c-api/capsule c PyCapsule_IsValid11401708
Ref: db611401708
Ref: c-api/capsule c PyCapsule_SetContext11402480
Ref: 413611402480
Ref: c-api/capsule c PyCapsule_SetDestructor11402701
Ref: 413711402701
Ref: c-api/capsule c PyCapsule_SetName11402950
Ref: 413811402950
Ref: c-api/capsule c PyCapsule_SetPointer11403337
Ref: 413911403337
Node: 產生器物件11403582
Ref: c-api/gen doc11403696
Ref: 413a11403696
Ref: c-api/gen gen-objects11403696
Ref: 413b11403696
Ref: c-api/gen generator-objects11403696
Ref: 413c11403696
Ref: c-api/gen c PyGenObject11403955
Ref: 413f11403955
Ref: c-api/gen c PyGen_Type11404026
Ref: 414011404026
Ref: c-api/gen c PyGen_Check11404120
Ref: 414111404120
Ref: c-api/gen c PyGen_CheckExact11404300
Ref: 414211404300
Ref: c-api/gen c PyGen_New11404496
Ref: 413d11404496
Ref: c-api/gen c PyGen_NewWithQualName11404750
Ref: 413e11404750
Node: 协程对象<2>11405152
Ref: c-api/coro doc11405273
Ref: 414311405273
Ref: c-api/coro coro-objects11405273
Ref: 8ba11405273
Ref: c-api/coro coroutine-objects11405273
Ref: 414411405273
Ref: c-api/coro c PyCoroObject11405405
Ref: 414511405405
Ref: c-api/coro c PyCoro_Type11405474
Ref: 414611405474
Ref: c-api/coro c PyCoro_CheckExact11405566
Ref: 414711405566
Ref: c-api/coro c PyCoro_New11405764
Ref: 414811405764
Node: 上下文变量对象11406152
Ref: c-api/contextvars doc11406273
Ref: 414911406273
Ref: c-api/contextvars context-variables-objects11406273
Ref: 414a11406273
Ref: c-api/contextvars contextvarsobjects11406273
Ref: 44711406273
Ref: c-api/contextvars contextvarsobjects-pointertype-change11406329
Ref: 5b311406329
Ref: c-api/contextvars c PyContext11406858
Ref: 414b11406858
Ref: c-api/contextvars c PyContextVar11406960
Ref: 414c11406960
Ref: c-api/contextvars c PyContextToken11407068
Ref: 414d11407068
Ref: c-api/contextvars c PyContext_Type11407173
Ref: 414e11407173
Ref: c-api/contextvars c PyContextVar_Type11407264
Ref: 414f11407264
Ref: c-api/contextvars c PyContextToken_Type11407367
Ref: 415011407367
Ref: c-api/contextvars c PyContext_CheckExact11407498
Ref: 415111407498
Ref: c-api/contextvars c PyContextVar_CheckExact11407700
Ref: 415211407700
Ref: c-api/contextvars c PyContextToken_CheckExact11407908
Ref: 415311407908
Ref: c-api/contextvars c PyContext_New11408149
Ref: 415411408149
Ref: c-api/contextvars c PyContext_Copy11408319
Ref: 415511408319
Ref: c-api/contextvars c PyContext_CopyCurrent11408515
Ref: 415611408515
Ref: c-api/contextvars c PyContext_Enter11408696
Ref: 415711408696
Ref: c-api/contextvars c PyContext_Exit11408862
Ref: 415811408862
Ref: c-api/contextvars c PyContextVar_New11409097
Ref: 415911409097
Ref: c-api/contextvars c PyContextVar_Get11409464
Ref: 415a11409464
Ref: c-api/contextvars c PyContextVar_Set11410109
Ref: 415b11410109
Ref: c-api/contextvars c PyContextVar_Reset11410364
Ref: 415c11410364
Ref: 上下文变量对象-Footnote-111410679
Node: DateTime 物件11410722
Ref: c-api/datetime doc11410846
Ref: 415d11410846
Ref: c-api/datetime datetime-objects11410846
Ref: 415e11410846
Ref: c-api/datetime datetimeobjects11410846
Ref: 415f11410846
Ref: c-api/datetime c PyDateTime_TimeZone_UTC11411375
Ref: 53911411375
Ref: c-api/datetime c PyDate_Check11411573
Ref: 416011411573
Ref: c-api/datetime c PyDate_CheckExact11411810
Ref: 416111411810
Ref: c-api/datetime c PyDateTime_Check11412003
Ref: 416211412003
Ref: c-api/datetime c PyDateTime_CheckExact11412256
Ref: 416311412256
Ref: c-api/datetime c PyTime_Check11412457
Ref: 416411412457
Ref: c-api/datetime c PyTime_CheckExact11412696
Ref: 416511412696
Ref: c-api/datetime c PyDelta_Check11412889
Ref: 416611412889
Ref: c-api/datetime c PyDelta_CheckExact11413129
Ref: 416711413129
Ref: c-api/datetime c PyTZInfo_Check11413324
Ref: 416811413324
Ref: c-api/datetime c PyTZInfo_CheckExact11413574
Ref: 416911413574
Ref: c-api/datetime c PyDate_FromDate11413800
Ref: 416a11413800
Ref: c-api/datetime c PyDateTime_FromDateAndTime11413980
Ref: 416b11413980
Ref: c-api/datetime c PyDateTime_FromDateAndTimeAndFold11414290
Ref: 416c11414290
Ref: c-api/datetime c PyTime_FromTime11414657
Ref: 416d11414657
Ref: c-api/datetime c PyTime_FromTimeAndFold11414899
Ref: 416e11414899
Ref: c-api/datetime c PyDelta_FromDSU11415188
Ref: 416f11415188
Ref: c-api/datetime c PyTimeZone_FromOffset11415540
Ref: 53711415540
Ref: c-api/datetime c PyTimeZone_FromOffsetAndName11415814
Ref: 53811415814
Ref: c-api/datetime c PyDateTime_GET_YEAR11416347
Ref: 417011416347
Ref: c-api/datetime c PyDateTime_GET_MONTH11416444
Ref: 417111416444
Ref: c-api/datetime c PyDateTime_GET_DAY11416557
Ref: 417211416557
Ref: c-api/datetime c PyDateTime_DATE_GET_HOUR11416857
Ref: 417311416857
Ref: c-api/datetime c PyDateTime_DATE_GET_MINUTE11416978
Ref: 417411416978
Ref: c-api/datetime c PyDateTime_DATE_GET_SECOND11417101
Ref: 417511417101
Ref: c-api/datetime c PyDateTime_DATE_GET_MICROSECOND11417219
Ref: 417611417219
Ref: c-api/datetime c PyDateTime_TIME_GET_HOUR11417532
Ref: 417711417532
Ref: c-api/datetime c PyDateTime_TIME_GET_MINUTE11417649
Ref: 417811417649
Ref: c-api/datetime c PyDateTime_TIME_GET_SECOND11417768
Ref: 417911417768
Ref: c-api/datetime c PyDateTime_TIME_GET_MICROSECOND11417882
Ref: 417a11417882
Ref: c-api/datetime c PyDateTime_DELTA_GET_DAYS11418196
Ref: 417b11418196
Ref: c-api/datetime c PyDateTime_DELTA_GET_SECONDS11418346
Ref: 417c11418346
Ref: c-api/datetime c PyDateTime_DELTA_GET_MICROSECONDS11418486
Ref: 417d11418486
Ref: c-api/datetime c PyDateTime_FromTimestamp11418676
Ref: 417e11418676
Ref: c-api/datetime c PyDate_FromTimestamp11418937
Ref: 112611418937
Node: 类型注解对象11419186
Ref: c-api/typehints doc11419280
Ref: 417f11419280
Ref: c-api/typehints objects-for-type-hinting11419280
Ref: 418011419280
Ref: c-api/typehints typehintobjects11419280
Ref: 418111419280
Ref: c-api/typehints c Py_GenericAlias11419441
Ref: 418211419441
Ref: c-api/typehints c Py_GenericAliasType11420736
Ref: 418311420736
Node: 初始化，终结和线程11420946
Ref: c-api/init doc11421092
Ref: 418411421092
Ref: c-api/init initialization11421092
Ref: 418511421092
Ref: c-api/init initialization-finalization-and-threads11421092
Ref: 418611421092
Node: 在Python初始化之前11421509
Ref: c-api/init before-python-initialization11421624
Ref: 418711421624
Ref: c-api/init pre-init-safe11421624
Ref: 53c11421624
Node: 全局配置变量11423548
Ref: c-api/init global-conf-vars11423715
Ref: 418811423715
Ref: c-api/init global-configuration-variables11423715
Ref: 419211423715
Ref: c-api/init c Py_BytesWarningFlag11424100
Ref: 5ae11424100
Ref: c-api/init c Py_DebugFlag11424381
Ref: 419311424381
Ref: c-api/init c Py_DontWriteBytecodeFlag11424609
Ref: 419411424609
Ref: c-api/init c Py_FrozenFlag11424872
Ref: 419511424872
Ref: c-api/init c Py_HashRandomizationFlag11425091
Ref: 419611425091
Ref: c-api/init c Py_IgnoreEnvironmentFlag11425375
Ref: 5b211425375
Ref: c-api/init c Py_InspectFlag11425610
Ref: 419711425610
Ref: c-api/init c Py_InteractiveFlag11425978
Ref: 3e5511425978
Ref: c-api/init c Py_IsolatedFlag11426057
Ref: 419811426057
Ref: c-api/init c Py_LegacyWindowsFSEncodingFlag11426325
Ref: 3e5a11426325
Ref: c-api/init c Py_LegacyWindowsStdioFlag11426722
Ref: 419911426722
Ref: c-api/init c Py_NoSiteFlag11427119
Ref: 419a11427119
Ref: c-api/init c Py_NoUserSiteDirectory11427458
Ref: 419b11427458
Ref: c-api/init c Py_OptimizeFlag11427720
Ref: 245111427720
Ref: c-api/init c Py_QuietFlag11427857
Ref: 419c11427857
Ref: c-api/init c Py_UnbufferedStdioFlag11428022
Ref: 419d11428022
Ref: c-api/init c Py_VerboseFlag11428229
Ref: 419e11428229
Ref: 全局配置变量-Footnote-111428716
Ref: 全局配置变量-Footnote-211428765
Node: Initializing and finalizing the interpreter11428814
Ref: c-api/init initializing-and-finalizing-the-interpreter11428980
Ref: 419f11428980
Ref: c-api/init c Py_Initialize11429081
Ref: 20f11429081
Ref: c-api/init c Py_InitializeEx11430052
Ref: 41a011430052
Ref: c-api/init c Py_IsInitialized11430329
Ref: 3dd611430329
Ref: c-api/init c Py_FinalizeEx11430598
Ref: 6c011430598
Ref: c-api/init c Py_Finalize11432729
Ref: db311432729
Node: Process-wide parameters11432879
Ref: c-api/init process-wide-parameters11433071
Ref: 41a211433071
Ref: c-api/init c Py_SetStandardStreamEncoding11433132
Ref: a0a11433132
Ref: c-api/init c Py_SetProgramName11434245
Ref: 10f211434245
Ref: c-api/init c Py_GetProgramName11435157
Ref: 39f11435157
Ref: c-api/init c Py_GetPrefix11435387
Ref: 3dd411435387
Ref: c-api/init c Py_GetExecPrefix11436159
Ref: 3dd511436159
Ref: c-api/init c Py_GetProgramFullPath11438327
Ref: 39e11438327
Ref: c-api/init c Py_GetPath11438763
Ref: 3dd311438763
Ref: c-api/init c Py_SetPath11439469
Ref: 39c11439469
Ref: c-api/init c Py_GetVersion11440675
Ref: 419011440675
Ref: c-api/init c Py_GetPlatform11441235
Ref: 418f11441235
Ref: c-api/init c Py_GetCopyright11441819
Ref: 418e11441819
Ref: c-api/init c Py_GetCompiler11442200
Ref: 418d11442200
Ref: c-api/init c Py_GetBuildInfo11442581
Ref: e5f11442581
Ref: c-api/init c PySys_SetArgvEx11442989
Ref: cc511442989
Ref: c-api/init c PySys_SetArgv11444963
Ref: db211444963
Ref: c-api/init c Py_SetPythonHome11445371
Ref: 10f111445371
Ref: c-api/init c Py_GetPythonHome11445963
Ref: 419111445963
Ref: Process-wide parameters-Footnote-111446240
Node: Thread State and the Global Interpreter Lock11446309
Ref: c-api/init thread-state-and-the-global-interpreter-lock11446481
Ref: 41a311446481
Ref: c-api/init threads11446481
Ref: 41a411446481
Node: Releasing the GIL from extension code11448018
Ref: c-api/init releasing-the-gil-from-extension-code11448169
Ref: 41a711448169
Node: 非Python创建的线程11450046
Ref: c-api/init gilstate11450225
Ref: 41a811450225
Ref: c-api/init non-python-created-threads11450225
Ref: 41a911450225
Node: Cautions about fork11451973
Ref: c-api/init cautions-about-fork11452125
Ref: 41ab11452125
Ref: c-api/init fork-and-threads11452125
Ref: 3e5611452125
Node: 高阶 API11454049
Ref: c-api/init high-level-api11454190
Ref: 41ac11454190
Ref: c-api/init c PyInterpreterState11454354
Ref: 3e411454354
Ref: c-api/init c PyThreadState11454923
Ref: 41a511454923
Ref: c-api/init c PyEval_InitThreads11455161
Ref: 20c11455161
Ref: c-api/init c PyEval_ThreadsInitialized11455693
Ref: 20d11455693
Ref: c-api/init c PyEval_SaveThread11456149
Ref: cdc11456149
Ref: c-api/init c PyEval_RestoreThread11456460
Ref: 3d611456460
Ref: c-api/init c PyThreadState_Get11457182
Ref: 41a611457182
Ref: c-api/init c PyThreadState_Swap11457450
Ref: 41ad11457450
Ref: c-api/init c PyGILState_Ensure11457808
Ref: 3d811457808
Ref: c-api/init c PyGILState_Release11459533
Ref: 41aa11459533
Ref: c-api/init c PyGILState_GetThisThreadState11460019
Ref: 41ae11460019
Ref: c-api/init c PyGILState_Check11460406
Ref: 41af11460406
Ref: c-api/init c Py_BEGIN_ALLOW_THREADS11461135
Ref: 3d4311461135
Ref: c-api/init c Py_END_ALLOW_THREADS11461442
Ref: 3d711461442
Ref: c-api/init c Py_BLOCK_THREADS11461702
Ref: 41b011461702
Ref: c-api/init c Py_UNBLOCK_THREADS11461888
Ref: 41b111461888
Node: Low-level API11462104
Ref: c-api/init low-level-api11462217
Ref: 41b211462217
Ref: c-api/init c PyInterpreterState_New11462423
Ref: 366d11462423
Ref: c-api/init c PyInterpreterState_Clear11462762
Ref: 366c11462762
Ref: c-api/init c PyInterpreterState_Delete11463050
Ref: 41b311463050
Ref: c-api/init c PyThreadState_New11463333
Ref: 41b411463333
Ref: c-api/init c PyThreadState_Clear11463631
Ref: 104c11463631
Ref: c-api/init c PyThreadState_Delete11463962
Ref: 109711463962
Ref: c-api/init c PyThreadState_DeleteCurrent11464219
Ref: 10de11464219
Ref: c-api/init c PyThreadState_GetFrame11464555
Ref: 24e11464555
Ref: c-api/init c PyThreadState_GetID11464909
Ref: 24f11464909
Ref: c-api/init c PyThreadState_GetInterpreter11465127
Ref: 24c11465127
Ref: c-api/init c PyInterpreterState_Get11465351
Ref: 24d11465351
Ref: c-api/init c PyInterpreterState_GetID11465631
Ref: 53d11465631
Ref: c-api/init c PyInterpreterState_GetDict11465907
Ref: 41b511465907
Ref: c-api/init c _PyFrameEvalFunction11466411
Ref: 107a11466411
Ref: c-api/init c _PyInterpreterState_GetEvalFrameFunc11466771
Ref: 107811466771
Ref: c-api/init c _PyInterpreterState_SetEvalFrameFunc11467017
Ref: 107911467017
Ref: c-api/init c PyThreadState_GetDict11467280
Ref: 41b611467280
Ref: c-api/init c PyThreadState_SetAsyncExc11467779
Ref: 53a11467779
Ref: c-api/init c PyEval_AcquireThread11468563
Ref: 3d511468563
Ref: c-api/init c PyEval_ReleaseThread11469659
Ref: 41b711469659
Ref: c-api/init c PyEval_AcquireLock11470226
Ref: 3d411470226
Ref: c-api/init c PyEval_ReleaseLock11471262
Ref: cdb11471262
Ref: Low-level API-Footnote-111471615
Ref: Low-level API-Footnote-211471664
Node: Sub-interpreter support11471713
Ref: c-api/init id111471874
Ref: 41b811471874
Ref: c-api/init sub-interpreter-support11471874
Ref: 3e5711471874
Ref: c-api/init c Py_NewInterpreter11472801
Ref: 41a111472801
Ref: c-api/init c Py_EndInterpreter11475811
Ref: f4e11475811
Node: 错误和警告11476477
Ref: c-api/init bugs-and-caveats11476552
Ref: 41ba11476552
Node: 异步通知11478154
Ref: c-api/init asynchronous-notifications11478286
Ref: 41bb11478286
Ref: c-api/init c Py_AddPendingCall11478499
Ref: 25f11478499
Node: 分析和跟踪11480603
Ref: c-api/init profiling11480733
Ref: 41bc11480733
Ref: c-api/init profiling-and-tracing11480733
Ref: 41bd11480733
Ref: c-api/init c Py_tracefunc11481395
Ref: 41be11481395
Ref: c-api/init c PyTrace_CALL11483626
Ref: 41bf11483626
Ref: c-api/init c PyTrace_EXCEPTION11484014
Ref: 41c011484014
Ref: c-api/init c PyTrace_LINE11484622
Ref: 41c111484622
Ref: c-api/init c PyTrace_RETURN11484916
Ref: 41c211484916
Ref: c-api/init c PyTrace_C_CALL11485067
Ref: 41c311485067
Ref: c-api/init c PyTrace_C_EXCEPTION11485227
Ref: 41c411485227
Ref: c-api/init c PyTrace_C_RETURN11485394
Ref: 41c511485394
Ref: c-api/init c PyTrace_OPCODE11485547
Ref: 41c611485547
Ref: c-api/init c PyEval_SetProfile11485879
Ref: efd11485879
Ref: c-api/init c PyEval_SetTrace11486478
Ref: efe11486478
Node: 高级调试器支持11487073
Ref: c-api/init advanced-debugger-support11487219
Ref: 41c711487219
Ref: c-api/init advanced-debugging11487219
Ref: 41c811487219
Ref: c-api/init c PyInterpreterState_Head11487344
Ref: f0111487344
Ref: c-api/init c PyInterpreterState_Main11487498
Ref: 41b911487498
Ref: c-api/init c PyInterpreterState_Next11487608
Ref: f0211487608
Ref: c-api/init c PyInterpreterState_ThreadHead11487808
Ref: f0311487808
Ref: c-api/init c PyThreadState_Next11488050
Ref: f0411488050
Node: Thread Local Storage Support11488285
Ref: c-api/init thread-local-storage11488407
Ref: 41c911488407
Ref: c-api/init thread-local-storage-support11488407
Ref: 41ca11488407
Node: Thread Specific Storage TSS API11489535
Ref: c-api/init thread-specific-storage-api11489668
Ref: 42711489668
Ref: c-api/init thread-specific-storage-tss-api11489668
Ref: 41cb11489668
Ref: c-api/init c Py_tss_t11490051
Ref: 42811490051
Ref: c-api/init c Py_tss_NEEDS_INIT11490493
Ref: 41cc11490493
Ref: Thread Specific Storage TSS API-Footnote-111490780
Node: Dynamic Allocation11490829
Ref: c-api/init dynamic-allocation11490933
Ref: 41cd11490933
Ref: c-api/init c PyThread_tss_alloc11491214
Ref: 41ce11491214
Ref: c-api/init c PyThread_tss_free11491432
Ref: 41cf11491432
Node: 方法<4>11491854
Ref: c-api/init methods11491958
Ref: 41d111491958
Ref: c-api/init c PyThread_tss_is_created11492260
Ref: 41d511492260
Ref: c-api/init c PyThread_tss_create11492447
Ref: 41d411492447
Ref: c-api/init c PyThread_tss_delete11492862
Ref: 41d011492862
Ref: c-api/init c PyThread_tss_set11493292
Ref: 41d211493292
Ref: c-api/init c PyThread_tss_get11493559
Ref: 41d311493559
Node: Thread Local Storage TLS API11493794
Ref: c-api/init thread-local-storage-api11493927
Ref: 42611493927
Ref: c-api/init thread-local-storage-tls-api11493927
Ref: 41d611493927
Ref: c-api/init c PyThread_create_key11494527
Ref: 41d711494527
Ref: c-api/init c PyThread_delete_key11494569
Ref: 41d811494569
Ref: c-api/init c PyThread_set_key_value11494619
Ref: a5111494619
Ref: c-api/init c PyThread_get_key_value11494684
Ref: 41d911494684
Ref: c-api/init c PyThread_delete_key_value11494738
Ref: 41da11494738
Ref: c-api/init c PyThread_ReInitTLS11494794
Ref: 41db11494794
Node: Python初始化配置11494836
Ref: c-api/init_config doc11494979
Ref: 41dc11494979
Ref: c-api/init_config init-config11494979
Ref: 2b611494979
Ref: c-api/init_config python-initialization-configuration11494979
Ref: 41dd11494979
Ref: Python初始化配置-Footnote-111496948
Node: PyWideStringList11496997
Ref: c-api/init_config pywidestringlist11497088
Ref: 41df11497088
Ref: c-api/init_config c PyWideStringList11497137
Ref: 29b11497137
Ref: c-api/init_config c PyWideStringList_Append11497327
Ref: 2ad11497327
Ref: c-api/init_config c PyWideStringList_Insert11497541
Ref: 2ae11497541
Ref: c-api/init_config c PyWideStringList length11497980
Ref: 41e011497980
Ref: c-api/init_config c PyWideStringList items11498050
Ref: 41e111498050
Node: PyStatus11498119
Ref: c-api/init_config pystatus11498230
Ref: 41e211498230
Ref: c-api/init_config c PyStatus11498263
Ref: 29a11498263
Ref: c-api/init_config c PyStatus exitcode11498483
Ref: 41e311498483
Ref: c-api/init_config c PyStatus err_msg11498578
Ref: 41e411498578
Ref: c-api/init_config c PyStatus func11498648
Ref: 41e511498648
Ref: c-api/init_config c PyStatus_Ok11498802
Ref: 2ac11498802
Ref: c-api/init_config c PyStatus_Error11498871
Ref: 2a611498871
Ref: c-api/init_config c PyStatus_NoMemory11498985
Ref: 2ab11498985
Ref: c-api/init_config c PyStatus_Exit11499093
Ref: 2a811499093
Ref: c-api/init_config c PyStatus_Exception11499239
Ref: 2a711499239
Ref: c-api/init_config c PyStatus_IsError11499468
Ref: 2a911499468
Ref: c-api/init_config c PyStatus_IsExit11499557
Ref: 2aa11499557
Ref: c-api/init_config c Py_ExitStatusException11499648
Ref: 2b011499648
Node: PyPreConfig11500588
Ref: c-api/init_config pypreconfig11500717
Ref: 41e611500717
Ref: c-api/init_config c PyPreConfig11500756
Ref: 29911500756
Ref: c-api/init_config c PyPreConfig_InitPythonConfig11500996
Ref: 2a511500996
Ref: c-api/init_config c PyPreConfig_InitIsolatedConfig11501182
Ref: 2a411501182
Ref: c-api/init_config c PyPreConfig allocator11501396
Ref: 41e911501396
Ref: c-api/init_config c PyPreConfig configure_locale11502499
Ref: 41eb11502499
Ref: c-api/init_config c PyPreConfig coerce_c_locale11502711
Ref: 41ec11502711
Ref: c-api/init_config c PyPreConfig coerce_c_locale_warn11502891
Ref: 41ed11502891
Ref: c-api/init_config c PyPreConfig dev_mode11503009
Ref: 41ee11503009
Ref: c-api/init_config c PyPreConfig isolated11503097
Ref: 41f011503097
Ref: c-api/init_config c PyPreConfig legacy_windows_fs_encoding11503185
Ref: 41f211503185
Ref: c-api/init_config c PyPreConfig parse_argv11503540
Ref: 41f311503540
Ref: c-api/init_config c PyPreConfig use_environment11503856
Ref: 41f411503856
Ref: c-api/init_config c PyPreConfig utf8_mode11503957
Ref: 41f511503957
Node: Preinitialization with PyPreConfig11504044
Ref: c-api/init_config preinitialization-with-pypreconfig11504173
Ref: 41f611504173
Ref: c-api/init_config c Py_PreInitialize11504294
Ref: 2b211504294
Ref: c-api/init_config c Py_PreInitializeFromBytesArgs11504428
Ref: 2b411504428
Ref: c-api/init_config c Py_PreInitializeFromArgs11504663
Ref: 2b311504663
Node: PyConfig11506432
Ref: c-api/init_config pyconfig11506578
Ref: 41f711506578
Ref: c-api/init_config c PyConfig11506611
Ref: 22611506611
Ref: c-api/init_config c PyConfig_InitPythonConfig11506724
Ref: 29e11506724
Ref: c-api/init_config c PyConfig_InitIsolatedConfig11506879
Ref: 29d11506879
Ref: c-api/init_config c PyConfig_SetString11507038
Ref: 2a311507038
Ref: c-api/init_config c PyConfig_SetBytesString11507284
Ref: 2a211507284
Ref: c-api/init_config c PyConfig_SetArgv11507567
Ref: 2a011507567
Ref: c-api/init_config c PyConfig_SetBytesArgv11507790
Ref: 2a111507790
Ref: c-api/init_config c PyConfig_SetWideStringList11508046
Ref: 41de11508046
Ref: c-api/init_config c PyConfig_Read11508326
Ref: 29f11508326
Ref: c-api/init_config c PyConfig_Clear11508541
Ref: 29c11508541
Ref: c-api/init_config c PyConfig argv11509584
Ref: 41f911509584
Ref: c-api/init_config c PyConfig base_exec_prefix11509981
Ref: 41fa11509981
Ref: c-api/init_config c PyConfig base_executable11510078
Ref: 41fb11510078
Ref: c-api/init_config c PyConfig base_prefix11510276
Ref: 41fd11510276
Ref: c-api/init_config c PyConfig platlibdir11510363
Ref: 101711510363
Ref: c-api/init_config c PyConfig buffered_stdio11510645
Ref: 41fe11510645
Ref: c-api/init_config c PyConfig bytes_warning11510852
Ref: 41ff11510852
Ref: c-api/init_config c PyConfig check_hash_pycs_mode11511171
Ref: 420011511171
Ref: c-api/init_config c PyConfig configure_c_stdio11511514
Ref: 420111511514
Ref: c-api/init_config c PyConfig dev_mode11511737
Ref: 41ef11511737
Ref: c-api/init_config c PyConfig dump_refs11511847
Ref: 420211511847
Ref: c-api/init_config c PyConfig exec_prefix11512022
Ref: 420311512022
Ref: c-api/init_config c PyConfig executable11512109
Ref: 41fc11512109
Ref: c-api/init_config c PyConfig faulthandler11512193
Ref: 420411512193
Ref: c-api/init_config c PyConfig filesystem_encoding11512321
Ref: 420511512321
Ref: c-api/init_config c PyConfig filesystem_errors11512448
Ref: 420611512448
Ref: c-api/init_config c PyConfig hash_seed11512594
Ref: 420711512594
Ref: c-api/init_config c PyConfig use_hash_seed11512644
Ref: 420811512644
Ref: c-api/init_config c PyConfig home11512883
Ref: 420911512883
Ref: c-api/init_config c PyConfig import_time11513057
Ref: 420a11513057
Ref: c-api/init_config c PyConfig inspect11513144
Ref: 420b11513144
Ref: c-api/init_config c PyConfig install_signal_handlers11513255
Ref: fe211513255
Ref: c-api/init_config c PyConfig interactive11513345
Ref: 420c11513345
Ref: c-api/init_config c PyConfig isolated11513411
Ref: 41f111513411
Ref: c-api/init_config c PyConfig legacy_windows_stdio11513960
Ref: 420e11513960
Ref: c-api/init_config c PyConfig malloc_stats11514312
Ref: 420f11514312
Ref: c-api/init_config c PyConfig pythonpath_env11514556
Ref: 421011514556
Ref: c-api/init_config c PyConfig module_search_paths11514809
Ref: 421111514809
Ref: c-api/init_config c PyConfig module_search_paths_set11514872
Ref: 421211514872
Ref: c-api/init_config c PyConfig optimization_level11515159
Ref: 421311515159
Ref: c-api/init_config c PyConfig parse_argv11515441
Ref: 41f811515441
Ref: c-api/init_config c PyConfig parser_debug11515696
Ref: 421411515696
Ref: c-api/init_config c PyConfig pathconfig_warnings11515858
Ref: 421511515858
Ref: c-api/init_config c PyConfig prefix11516124
Ref: 421611516124
Ref: c-api/init_config c PyConfig program_name11516201
Ref: 421711516201
Ref: c-api/init_config c PyConfig pycache_prefix11516357
Ref: 421811516357
Ref: c-api/init_config c PyConfig quiet11516554
Ref: 421911516554
Ref: c-api/init_config c PyConfig run_command11516709
Ref: 421a11516709
Ref: c-api/init_config c PyConfig run_filename11516846
Ref: 421b11516846
Ref: c-api/init_config c PyConfig run_module11516972
Ref: 421c11516972
Ref: c-api/init_config c PyConfig show_ref_count11517107
Ref: 421d11517107
Ref: c-api/init_config c PyConfig site_import11517365
Ref: 421e11517365
Ref: c-api/init_config c PyConfig skip_source_first_line11517464
Ref: 421f11517464
Ref: c-api/init_config c PyConfig stdio_encoding11517563
Ref: 422011517563
Ref: c-api/init_config c PyConfig stdio_errors11517613
Ref: 422111517613
Ref: c-api/init_config c PyConfig tracemalloc11517786
Ref: 422211517786
Ref: c-api/init_config c PyConfig use_environment11517902
Ref: 26011517902
Ref: c-api/init_config c PyConfig user_site_directory11518017
Ref: 420d11518017
Ref: c-api/init_config c PyConfig verbose11518139
Ref: 422311518139
Ref: c-api/init_config c PyConfig warnoptions11518222
Ref: 422411518222
Ref: c-api/init_config c PyConfig write_bytecode11518703
Ref: 422511518703
Ref: c-api/init_config c PyConfig xoptions11518922
Ref: 422611518922
Ref: c-api/init_config c PyConfig _use_peg_parser11519012
Ref: 422711519012
Ref: PyConfig-Footnote-111519708
Ref: PyConfig-Footnote-211519757
Node: Initialization with PyConfig11519806
Ref: c-api/init_config initialization-with-pyconfig11519940
Ref: 422811519940
Ref: c-api/init_config c Py_InitializeFromConfig11520045
Ref: 2b111520045
Node: Isolated Configuration11522936
Ref: c-api/init_config init-isolated-conf11523082
Ref: 41e811523082
Ref: c-api/init_config isolated-configuration11523082
Ref: 422911523082
Node: Python Configuration11523873
Ref: c-api/init_config init-python-config11524003
Ref: 41e711524003
Ref: c-api/init_config python-configuration11524003
Ref: 422a11524003
Ref: Python Configuration-Footnote-111525579
Ref: Python Configuration-Footnote-211525628
Node: 路径配置11525677
Ref: c-api/init_config init-path-config11525795
Ref: 101611525795
Ref: c-api/init_config path-configuration11525795
Ref: 422b11525795
Node: Py_RunMain11529238
Ref: c-api/init_config py-runmain11529350
Ref: 422c11529350
Ref: c-api/init_config c Py_RunMain11529393
Ref: 2b511529393
Node: Py_GetArgcArgv11529985
Ref: c-api/init_config py-getargcargv11530135
Ref: 422d11530135
Ref: c-api/init_config c Py_GetArgcArgv11530186
Ref: 103711530186
Node: Multi-Phase Initialization Private Provisional API11530331
Ref: c-api/init_config multi-phase-initialization-private-provisional-api11530462
Ref: 422e11530462
Ref: c-api/init_config c _Py_InitializeMain11531743
Ref: 422f11531743
Ref: Multi-Phase Initialization Private Provisional API-Footnote-111533736
Ref: Multi-Phase Initialization Private Provisional API-Footnote-211533785
Node: 記憶體管理11533834
Ref: c-api/memory doc11533968
Ref: 423011533968
Ref: c-api/memory memory11533968
Ref: 41ea11533968
Ref: c-api/memory memory-management11533968
Ref: 423111533968
Node: 總覽<2>11534219
Ref: c-api/memory memoryoverview11534307
Ref: 423211534307
Ref: c-api/memory overview11534307
Ref: 423311534307
Node: 原始内存接口11537671
Ref: c-api/memory raw-memory-interface11537780
Ref: 423411537780
Ref: c-api/memory c PyMem_RawMalloc11538181
Ref: a4e11538181
Ref: c-api/memory c PyMem_RawCalloc11538546
Ref: 89311538546
Ref: c-api/memory c PyMem_RawRealloc11538990
Ref: a4f11538990
Ref: c-api/memory c PyMem_RawFree11539719
Ref: 3e5b11539719
Node: 内存接口11540140
Ref: c-api/memory memory-interface11540255
Ref: 423511540255
Ref: c-api/memory memoryinterface11540255
Ref: 423611540255
Ref: c-api/memory c PyMem_Malloc11540692
Ref: 5fe11540692
Ref: c-api/memory c PyMem_Calloc11541051
Ref: 89411541051
Ref: c-api/memory c PyMem_Realloc11541489
Ref: a5011541489
Ref: c-api/memory c PyMem_Free11542200
Ref: e6e11542200
Ref: c-api/memory c PyMem_New11542696
Ref: 423711542696
Ref: c-api/memory c PyMem_Resize11542952
Ref: 423811542952
Ref: c-api/memory c PyMem_Del11543426
Ref: 423911543426
Node: 对象分配器11543956
Ref: c-api/memory object-allocators11544074
Ref: 423a11544074
Ref: c-api/memory c PyObject_Malloc11544425
Ref: 60111544425
Ref: c-api/memory c PyObject_Calloc11544790
Ref: 89511544790
Ref: c-api/memory c PyObject_Realloc11545234
Ref: e6f11545234
Ref: c-api/memory c PyObject_Free11545965
Ref: 5fd11545965
Node: 默认内存分配器11546383
Ref: c-api/memory default-memory-allocators11546513
Ref: 148f11546513
Ref: c-api/memory id111546513
Ref: 423b11546513
Node: 自定义内存分配器11548784
Ref: c-api/memory customize-memory-allocators11548917
Ref: 423c11548917
Ref: c-api/memory c PyMemAllocatorEx11548993
Ref: 8b711548993
Ref: c-api/memory c PyMemAllocatorDomain11550722
Ref: 423d11550722
Ref: c-api/memory c PYMEM_DOMAIN_RAW11550813
Ref: 149011550813
Ref: c-api/memory c PYMEM_DOMAIN_MEM11551052
Ref: 60211551052
Ref: c-api/memory c PYMEM_DOMAIN_OBJ11551278
Ref: 60011551278
Ref: c-api/memory c PyMem_GetAllocator11551516
Ref: 418b11551516
Ref: c-api/memory c PyMem_SetAllocator11551670
Ref: 418911551670
Ref: c-api/memory c PyMem_SetupDebugHooks11552265
Ref: 60311552265
Node: pymalloc 分配器11554292
Ref: c-api/memory pymalloc11554421
Ref: 6b811554421
Ref: c-api/memory the-pymalloc-allocator11554421
Ref: 423e11554421
Node: 自定义 pymalloc Arena 分配器11555231
Ref: c-api/memory customize-pymalloc-arena-allocator11555320
Ref: 423f11555320
Ref: c-api/memory c PyObjectArenaAllocator11555422
Ref: 424011555422
Ref: c-api/memory c PyObject_GetArenaAllocator11556441
Ref: 418c11556441
Ref: c-api/memory c PyObject_SetArenaAllocator11556563
Ref: 418a11556563
Node: tracemalloc C API11556685
Ref: c-api/memory tracemalloc-c-api11556800
Ref: 424111556800
Ref: c-api/memory c PyTraceMalloc_Track11556870
Ref: 52711556870
Ref: c-api/memory c PyTraceMalloc_Untrack11557274
Ref: 52811557274
Node: 示例<51>11557588
Ref: c-api/memory examples11557676
Ref: 424211557676
Ref: c-api/memory memoryexamples11557676
Ref: 424311557676
Node: 对象实现支持11559504
Ref: c-api/objimpl doc11559641
Ref: 424411559641
Ref: c-api/objimpl newtypes11559641
Ref: 424511559641
Ref: c-api/objimpl object-implementation-support11559641
Ref: 424611559641
Node: 在堆中分配对象11560086
Ref: c-api/allocation doc11560189
Ref: 424711560189
Ref: c-api/allocation allocating-objects11560189
Ref: 424811560189
Ref: c-api/allocation allocating-objects-on-the-heap11560189
Ref: 424911560189
Ref: c-api/allocation c _PyObject_New11560241
Ref: 424a11560241
Ref: c-api/allocation c _PyObject_NewVar11560337
Ref: 424b11560337
Ref: c-api/allocation c PyObject_Init11560466
Ref: 39811560466
Ref: c-api/allocation c PyObject_InitVar11560857
Ref: 109611560857
Ref: c-api/allocation c PyObject_New11561115
Ref: 26811561115
Ref: c-api/allocation c PyObject_NewVar11561506
Ref: 26911561506
Ref: c-api/allocation c PyObject_Del11562186
Ref: ed811562186
Ref: c-api/allocation c _Py_NoneStruct11562580
Ref: 424c11562580
Node: 通用物件結構11562869
Ref: c-api/structures doc11562995
Ref: 424d11562995
Ref: c-api/structures common-object-structures11562995
Ref: 424e11562995
Ref: c-api/structures common-structs11562995
Ref: 424f11562995
Node: 基本的对象类型和宏11563290
Ref: c-api/structures base-object-types-and-macros11563415
Ref: 425011563415
Ref: c-api/structures c PyObject11563769
Ref: 5b411563769
Ref: c-api/structures c PyVarObject11564351
Ref: 425111564351
Ref: c-api/structures c PyObject_HEAD11564733
Ref: d3a11564733
Ref: c-api/structures c PyObject_VAR_HEAD11564995
Ref: 425311564995
Ref: c-api/structures c Py_TYPE11565299
Ref: 3d5311565299
Ref: c-api/structures c Py_IS_TYPE11565466
Ref: 107e11565466
Ref: c-api/structures c Py_SET_TYPE11565681
Ref: 109211565681
Ref: c-api/structures c Py_REFCNT11565812
Ref: 3d5211565812
Ref: c-api/structures c Py_SET_REFCNT11565985
Ref: 109311565985
Ref: c-api/structures c Py_SIZE11566132
Ref: 425211566132
Ref: c-api/structures c Py_SET_SIZE11566302
Ref: 109011566302
Ref: c-api/structures c PyObject_HEAD_INIT11566433
Ref: 425411566433
Ref: c-api/structures c PyVarObject_HEAD_INIT11566652
Ref: 425511566652
Node: Implementing functions and methods11566930
Ref: c-api/structures implementing-functions-and-methods11567103
Ref: 425611567103
Ref: c-api/structures c PyCFunction11567192
Ref: e9f11567192
Ref: c-api/structures c PyCFunctionWithKeywords11567764
Ref: 425711567764
Ref: c-api/structures c _PyCFunctionFast11568144
Ref: 425811568144
Ref: c-api/structures c _PyCFunctionFastWithKeywords11568489
Ref: 425911568489
Ref: c-api/structures c PyCMethod11568965
Ref: 24811568965
Ref: c-api/structures c PyMethodDef11569443
Ref: edd11569443
Ref: c-api/structures METH_VARARGS11571228
Ref: f0a11571228
Ref: c-api/structures METH_FASTCALL11572157
Ref: 10f311572157
Ref: c-api/structures METH_NOARGS11573796
Ref: eda11573796
Ref: c-api/structures METH_O11574195
Ref: f0911574195
Ref: c-api/structures METH_CLASS11574784
Ref: edb11574784
Ref: c-api/structures METH_STATIC11575057
Ref: edc11575057
Ref: c-api/structures METH_COEXIST11575442
Ref: 425a11575442
Node: Accessing attributes of extension types11576108
Ref: c-api/structures accessing-attributes-of-extension-types11576245
Ref: 425b11576245
Ref: c-api/structures c PyMemberDef11576344
Ref: 52911576344
Ref: c-api/structures pymemberdef-offsets11580481
Ref: 3f9611580481
Ref: c-api/structures c PyMember_GetOne11581134
Ref: 425c11581134
Ref: c-api/structures c PyMember_SetOne11581394
Ref: 425d11581394
Ref: c-api/structures c PyGetSetDef11581711
Ref: 52a11581711
Node: Type 对象<2>11583847
Ref: c-api/typeobj doc11583976
Ref: 425e11583976
Ref: c-api/typeobj type-objects11583976
Ref: 425f11583976
Ref: c-api/typeobj type-structs11583976
Ref: 27111583976
Node: 快速参考<2>11585023
Ref: c-api/typeobj quick-reference11585121
Ref: 426111585121
Node: "tp 槽"11585235
Ref: c-api/typeobj tp-slots11585331
Ref: 426211585331
Ref: c-api/typeobj tp-slots-table11585331
Ref: 426311585331
Ref: "tp 槽"-Footnote-111598576
Ref: "tp 槽"-Footnote-211598801
Node: 子方法槽（方法域）11599573
Ref: c-api/typeobj id311599691
Ref: 428211599691
Ref: c-api/typeobj sub-slots11599691
Ref: 426911599691
Node: slot typedefs11609860
Ref: c-api/typeobj slot-typedefs11609961
Ref: 42bb11609961
Ref: c-api/typeobj slot-typedefs-table11609961
Ref: 426411609961
Node: PyTypeObject Definition11617813
Ref: c-api/typeobj pytypeobject-definition11617934
Ref: 42be11617934
Node: PyObject Slots11620733
Ref: c-api/typeobj pyobject-slots11620856
Ref: 42bf11620856
Ref: c-api/typeobj c PyObject _ob_next11621246
Ref: 42c011621246
Ref: c-api/typeobj c PyObject _ob_prev11621294
Ref: 42c111621294
Ref: c-api/typeobj c PyObject ob_refcnt11622050
Ref: 42c211622050
Ref: c-api/typeobj c PyObject ob_type11622465
Ref: 42c311622465
Node: PyVarObject Slots11623558
Ref: c-api/typeobj pyvarobject-slots11623676
Ref: 42c411623676
Ref: c-api/typeobj c PyVarObject ob_size11623731
Ref: 42c511623731
Node: PyTypeObject Slots11624016
Ref: c-api/typeobj pytypeobject-slots11624130
Ref: 42c611624130
Ref: c-api/typeobj c PyTypeObject tp_name11624479
Ref: 3d7511624479
Ref: c-api/typeobj c PyTypeObject tp_basicsize11626180
Ref: 26a11626180
Ref: c-api/typeobj c PyTypeObject tp_itemsize11626237
Ref: 3d5411626237
Ref: c-api/typeobj c PyTypeObject tp_dealloc11628887
Ref: 3d5a11628887
Ref: c-api/typeobj c PyTypeObject tp_vectorcall_offset11631357
Ref: 3ee011631357
Ref: c-api/typeobj c PyTypeObject tp_getattr11633421
Ref: 3d7c11633421
Ref: c-api/typeobj c PyTypeObject tp_setattr11634148
Ref: 3d7d11634148
Ref: c-api/typeobj c PyTypeObject tp_as_async11634895
Ref: 426811634895
Ref: c-api/typeobj c PyTypeObject tp_repr11635436
Ref: 3d7411635436
Ref: c-api/typeobj c PyTypeObject tp_as_number11636391
Ref: 26f11636391
Ref: c-api/typeobj c PyTypeObject tp_as_sequence11636797
Ref: 426b11636797
Ref: c-api/typeobj c PyTypeObject tp_as_mapping11637214
Ref: 426c11637214
Ref: c-api/typeobj c PyTypeObject tp_hash11637626
Ref: 3d8511637626
Ref: c-api/typeobj c PyTypeObject tp_call11639220
Ref: 3d8611639220
Ref: c-api/typeobj c PyTypeObject tp_str11639625
Ref: 3d7611639625
Ref: c-api/typeobj c PyTypeObject tp_getattro11640574
Ref: 3d7911640574
Ref: c-api/typeobj c PyTypeObject tp_setattro11641443
Ref: 3d7a11641443
Ref: c-api/typeobj c PyTypeObject tp_as_buffer11642437
Ref: 26d11642437
Ref: c-api/typeobj c PyTypeObject tp_flags11642842
Ref: 101111642842
Ref: c-api/typeobj Py_TPFLAGS_HEAPTYPE11644736
Ref: 3f8411644736
Ref: c-api/typeobj Py_TPFLAGS_BASETYPE11645381
Ref: 3d6211645381
Ref: c-api/typeobj Py_TPFLAGS_READY11645654
Ref: 42cc11645654
Ref: c-api/typeobj Py_TPFLAGS_READYING11645844
Ref: 42cd11645844
Ref: c-api/typeobj Py_TPFLAGS_HAVE_GC11646043
Ref: 3d6811646043
Ref: c-api/typeobj Py_TPFLAGS_DEFAULT11647026
Ref: 3d5511647026
Ref: c-api/typeobj Py_TPFLAGS_METHOD_DESCRIPTOR11647406
Ref: 3eef11647406
Ref: c-api/typeobj Py_TPFLAGS_LONG_SUBCLASS11648265
Ref: 42cf11648265
Ref: c-api/typeobj Py_TPFLAGS_LIST_SUBCLASS11648306
Ref: 42d011648306
Ref: c-api/typeobj Py_TPFLAGS_TUPLE_SUBCLASS11648347
Ref: 42d111648347
Ref: c-api/typeobj Py_TPFLAGS_BYTES_SUBCLASS11648389
Ref: 42d211648389
Ref: c-api/typeobj Py_TPFLAGS_UNICODE_SUBCLASS11648431
Ref: 42d311648431
Ref: c-api/typeobj Py_TPFLAGS_DICT_SUBCLASS11648475
Ref: 42d411648475
Ref: c-api/typeobj Py_TPFLAGS_BASE_EXC_SUBCLASS11648516
Ref: 42d511648516
Ref: c-api/typeobj Py_TPFLAGS_TYPE_SUBCLASS11648561
Ref: 42d611648561
Ref: c-api/typeobj Py_TPFLAGS_HAVE_FINALIZE11649119
Ref: 3f711649119
Ref: c-api/typeobj Py_TPFLAGS_HAVE_VECTORCALL11649488
Ref: 3edf11649488
Ref: c-api/typeobj c PyTypeObject tp_doc11649939
Ref: 3d5611649939
Ref: c-api/typeobj c PyTypeObject tp_traverse11650257
Ref: 23b11650257
Ref: c-api/typeobj c PyTypeObject tp_clear11653864
Ref: 3d7211653864
Ref: c-api/typeobj c PyTypeObject tp_richcompare11657502
Ref: 3d7f11657502
Ref: c-api/typeobj c Py_RETURN_RICHCOMPARE11659013
Ref: 52511659013
Ref: c-api/typeobj c PyTypeObject tp_weaklistoffset11660247
Ref: 26b11660247
Ref: c-api/typeobj c PyTypeObject tp_iter11662032
Ref: ef211662032
Ref: c-api/typeobj c PyTypeObject tp_iternext11662512
Ref: ef311662512
Ref: c-api/typeobj c PyTypeObject tp_methods11663310
Ref: 3d6111663310
Ref: c-api/typeobj c PyTypeObject tp_members11663812
Ref: 3d5f11663812
Ref: c-api/typeobj c PyTypeObject tp_getset11664350
Ref: 3d6411664350
Ref: c-api/typeobj c PyTypeObject tp_base11664880
Ref: 3d6a11664880
Ref: c-api/typeobj c PyTypeObject tp_dict11666178
Ref: 3f9011666178
Ref: c-api/typeobj c PyTypeObject tp_descr_get11667161
Ref: 427611667161
Ref: c-api/typeobj c PyTypeObject tp_descr_set11667459
Ref: 427811667459
Ref: c-api/typeobj c PyTypeObject tp_dictoffset11667856
Ref: 3f9711667856
Ref: c-api/typeobj c PyTypeObject tp_init11671118
Ref: 3d5e11671118
Ref: c-api/typeobj c PyTypeObject tp_alloc11672580
Ref: 3d5c11672580
Ref: c-api/typeobj c PyTypeObject tp_new11673271
Ref: 3d5711673271
Ref: c-api/typeobj c PyTypeObject tp_free11674850
Ref: 3d5b11674850
Ref: c-api/typeobj c PyTypeObject tp_is_gc11675540
Ref: 427e11675540
Ref: c-api/typeobj c PyTypeObject tp_bases11676697
Ref: 427f11676697
Ref: c-api/typeobj c PyTypeObject tp_mro11676951
Ref: 3f9111676951
Ref: c-api/typeobj c PyTypeObject tp_cache11677275
Ref: 3f9211677275
Ref: c-api/typeobj c PyTypeObject tp_subclasses11677418
Ref: 3f9311677418
Ref: c-api/typeobj c PyTypeObject tp_weaklist11677597
Ref: 3f9411677597
Ref: c-api/typeobj c PyTypeObject tp_del11677822
Ref: 428011677822
Ref: c-api/typeobj c PyTypeObject tp_version_tag11677944
Ref: 428111677944
Ref: c-api/typeobj c PyTypeObject tp_finalize11678125
Ref: 3f611678125
Ref: c-api/typeobj c PyTypeObject tp_vectorcall11679628
Ref: 3f9511679628
Ref: PyTypeObject Slots-Footnote-111680835
Ref: PyTypeObject Slots-Footnote-211680878
Node: Heap Types11680927
Ref: c-api/typeobj heap-types11681015
Ref: 3f8311681015
Ref: c-api/typeobj id411681015
Ref: 42c711681015
Node: Number Object Structures11682179
Ref: c-api/typeobj number-object-structures11682315
Ref: 42d711682315
Ref: c-api/typeobj number-structs11682315
Ref: 42c911682315
Ref: c-api/typeobj c PyNumberMethods11682380
Ref: e4611682380
Ref: c-api/typeobj c PyNumberMethods nb_add11684809
Ref: 3f8e11684809
Ref: c-api/typeobj c PyNumberMethods nb_subtract11684864
Ref: 428911684864
Ref: c-api/typeobj c PyNumberMethods nb_multiply11684924
Ref: 428b11684924
Ref: c-api/typeobj c PyNumberMethods nb_remainder11684984
Ref: 428d11684984
Ref: c-api/typeobj c PyNumberMethods nb_divmod11685045
Ref: 428f11685045
Ref: c-api/typeobj c PyNumberMethods nb_power11685103
Ref: 429011685103
Ref: c-api/typeobj c PyNumberMethods nb_negative11685161
Ref: 429211685161
Ref: c-api/typeobj c PyNumberMethods nb_positive11685220
Ref: 429311685220
Ref: c-api/typeobj c PyNumberMethods nb_absolute11685279
Ref: 429411685279
Ref: c-api/typeobj c PyNumberMethods nb_bool11685338
Ref: 429511685338
Ref: c-api/typeobj c PyNumberMethods nb_invert11685391
Ref: 429611685391
Ref: c-api/typeobj c PyNumberMethods nb_lshift11685448
Ref: 429711685448
Ref: c-api/typeobj c PyNumberMethods nb_rshift11685506
Ref: 429911685506
Ref: c-api/typeobj c PyNumberMethods nb_and11685564
Ref: 429b11685564
Ref: c-api/typeobj c PyNumberMethods nb_xor11685619
Ref: 429d11685619
Ref: c-api/typeobj c PyNumberMethods nb_or11685674
Ref: 429f11685674
Ref: c-api/typeobj c PyNumberMethods nb_int11685728
Ref: 42a111685728
Ref: c-api/typeobj c PyNumberMethods nb_reserved11685782
Ref: 42a211685782
Ref: c-api/typeobj c PyNumberMethods nb_float11685837
Ref: 42a311685837
Ref: c-api/typeobj c PyNumberMethods nb_inplace_add11685893
Ref: 428811685893
Ref: c-api/typeobj c PyNumberMethods nb_inplace_subtract11685956
Ref: 428a11685956
Ref: c-api/typeobj c PyNumberMethods nb_inplace_multiply11686024
Ref: 428c11686024
Ref: c-api/typeobj c PyNumberMethods nb_inplace_remainder11686092
Ref: 428e11686092
Ref: c-api/typeobj c PyNumberMethods nb_inplace_power11686161
Ref: 429111686161
Ref: c-api/typeobj c PyNumberMethods nb_inplace_lshift11686227
Ref: 429811686227
Ref: c-api/typeobj c PyNumberMethods nb_inplace_rshift11686293
Ref: 429a11686293
Ref: c-api/typeobj c PyNumberMethods nb_inplace_and11686359
Ref: 429c11686359
Ref: c-api/typeobj c PyNumberMethods nb_inplace_xor11686422
Ref: 429e11686422
Ref: c-api/typeobj c PyNumberMethods nb_inplace_or11686485
Ref: 42a011686485
Ref: c-api/typeobj c PyNumberMethods nb_floor_divide11686547
Ref: 42a411686547
Ref: c-api/typeobj c PyNumberMethods nb_true_divide11686611
Ref: 42a611686611
Ref: c-api/typeobj c PyNumberMethods nb_inplace_floor_divide11686674
Ref: 42a511686674
Ref: c-api/typeobj c PyNumberMethods nb_inplace_true_divide11686746
Ref: 42a711686746
Ref: c-api/typeobj c PyNumberMethods nb_index11686817
Ref: 42a811686817
Ref: c-api/typeobj c PyNumberMethods nb_matrix_multiply11686873
Ref: 42a911686873
Ref: c-api/typeobj c PyNumberMethods nb_inplace_matrix_multiply11686940
Ref: 42aa11686940
Node: Mapping Object Structures11687015
Ref: c-api/typeobj mapping-object-structures11687163
Ref: 42d811687163
Ref: c-api/typeobj mapping-structs11687163
Ref: 42cb11687163
Ref: c-api/typeobj c PyMappingMethods11687230
Ref: 3d8411687230
Ref: c-api/typeobj c PyMappingMethods mp_length11687399
Ref: 42ab11687399
Ref: c-api/typeobj c PyMappingMethods mp_subscript11687660
Ref: 42ad11687660
Ref: c-api/typeobj c PyMappingMethods mp_ass_subscript11688025
Ref: 42ae11688025
Node: Sequence Object Structures11688471
Ref: c-api/typeobj sequence-object-structures11688619
Ref: 42d911688619
Ref: c-api/typeobj sequence-structs11688619
Ref: 42ca11688619
Ref: c-api/typeobj c PySequenceMethods11688688
Ref: 3d8311688688
Ref: c-api/typeobj c PySequenceMethods sq_length11688836
Ref: 3f8f11688836
Ref: c-api/typeobj c PySequenceMethods sq_concat11689147
Ref: 42b011689147
Ref: c-api/typeobj c PySequenceMethods sq_repeat11689419
Ref: 42b111689419
Ref: c-api/typeobj c PySequenceMethods sq_item11689705
Ref: 10bf11689705
Ref: c-api/typeobj c PySequenceMethods sq_ass_item11690417
Ref: 42b311690417
Ref: c-api/typeobj c PySequenceMethods sq_contains11690877
Ref: 42b511690877
Ref: c-api/typeobj c PySequenceMethods sq_inplace_concat11691185
Ref: 42b711691185
Ref: c-api/typeobj c PySequenceMethods sq_inplace_repeat11691705
Ref: 42b811691705
Node: Buffer Object Structures11692238
Ref: c-api/typeobj buffer-object-structures11692384
Ref: 42da11692384
Ref: c-api/typeobj buffer-structs11692384
Ref: 3f3c11692384
Ref: c-api/typeobj c PyBufferProcs11692449
Ref: 3f9911692449
Ref: c-api/typeobj c PyBufferProcs bf_getbuffer11692681
Ref: 3f9811692681
Ref: c-api/typeobj c PyBufferProcs bf_releasebuffer11694579
Ref: 3e8e11694579
Node: Async Object Structures11695697
Ref: c-api/typeobj async-object-structures11695835
Ref: 42db11695835
Ref: c-api/typeobj async-structs11695835
Ref: 42c811695835
Ref: c-api/typeobj c PyAsyncMethods11695917
Ref: 3f8d11695917
Ref: c-api/typeobj c PyAsyncMethods am_await11696299
Ref: 428311696299
Ref: c-api/typeobj c PyAsyncMethods am_aiter11696647
Ref: 428511696647
Ref: c-api/typeobj c PyAsyncMethods am_anext11697000
Ref: 428611697000
Node: Slot Type typedefs11697279
Ref: c-api/typeobj id511697402
Ref: 42bd11697402
Ref: c-api/typeobj slot-type-typedefs11697402
Ref: 42dc11697402
Ref: c-api/typeobj c allocfunc11697455
Ref: 427b11697455
Ref: c-api/typeobj c destructor11698423
Ref: 426511698423
Ref: c-api/typeobj c freefunc11698470
Ref: 427d11698470
Ref: c-api/typeobj c newfunc11698542
Ref: 427c11698542
Ref: c-api/typeobj c initproc11698645
Ref: 427a11698645
Ref: c-api/typeobj c reprfunc11698744
Ref: 426a11698744
Ref: c-api/typeobj c getattrfunc11698825
Ref: 426611698825
Ref: c-api/typeobj c setattrfunc11698956
Ref: 426711698956
Ref: c-api/typeobj c getattrofunc11699176
Ref: 426f11699176
Ref: c-api/typeobj c setattrofunc11699347
Ref: 427011699347
Ref: c-api/typeobj c descrgetfunc11699607
Ref: 427711699607
Ref: c-api/typeobj c descrsetfunc11699724
Ref: 427911699724
Ref: c-api/typeobj c hashfunc11699825
Ref: 426d11699825
Ref: c-api/typeobj c richcmpfunc11699906
Ref: 427311699906
Ref: c-api/typeobj c getiterfunc11700014
Ref: 427411700014
Ref: c-api/typeobj c iternextfunc11700097
Ref: 427511700097
Ref: c-api/typeobj c lenfunc11700185
Ref: 42ac11700185
Ref: c-api/typeobj c getbufferproc11700235
Ref: 42b911700235
Ref: c-api/typeobj c releasebufferproc11700302
Ref: 42ba11700302
Ref: c-api/typeobj c unaryfunc11700369
Ref: 428411700369
Ref: c-api/typeobj c binaryfunc11700420
Ref: 428711700420
Ref: c-api/typeobj c ternaryfunc11700484
Ref: 426e11700484
Ref: c-api/typeobj c ssizeargfunc11700571
Ref: 42b211700571
Ref: c-api/typeobj c ssizeobjargproc11700637
Ref: 42b411700637
Ref: c-api/typeobj c objobjproc11700700
Ref: 42b611700700
Ref: c-api/typeobj c objobjargproc11700758
Ref: 42af11700758
Node: 例子<2>11700831
Ref: c-api/typeobj examples11700970
Ref: 42dd11700970
Ref: c-api/typeobj typedef-examples11700970
Ref: 426011700970
Node: 使对象类型支持循环垃圾回收11706292
Ref: c-api/gcsupport doc11706404
Ref: 42de11706404
Ref: c-api/gcsupport supporting-cycle-detection11706404
Ref: 42ce11706404
Ref: c-api/gcsupport supporting-cyclic-garbage-collection11706404
Ref: 42df11706404
Ref: c-api/gcsupport c PyObject_GC_New11708488
Ref: 3f311708488
Ref: c-api/gcsupport c PyObject_GC_NewVar11708679
Ref: 3f411708679
Ref: c-api/gcsupport c PyObject_GC_Resize11708903
Ref: 42e011708903
Ref: c-api/gcsupport c PyObject_GC_Track11709191
Ref: f0611709191
Ref: c-api/gcsupport c PyObject_IS_GC11709578
Ref: 26711709578
Ref: c-api/gcsupport c PyObject_GC_IsTracked11709788
Ref: 25411709788
Ref: c-api/gcsupport c PyObject_GC_IsFinalized11710065
Ref: 25511710065
Ref: c-api/gcsupport c PyObject_GC_Del11710343
Ref: f0511710343
Ref: c-api/gcsupport c PyObject_GC_UnTrack11710533
Ref: f0711710533
Ref: c-api/gcsupport c visitproc11711115
Ref: 42bc11711115
Ref: c-api/gcsupport c traverseproc11711564
Ref: 427111711564
Ref: c-api/gcsupport c Py_VISIT11712211
Ref: 3d6611712211
Ref: c-api/gcsupport c inquiry11712818
Ref: 427211712818
Node: API 和 ABI 版本管理11713233
Ref: c-api/apiabiversion doc11713346
Ref: 42e111713346
Ref: c-api/apiabiversion api-and-abi-versioning11713346
Ref: 42e211713346
Ref: c-api/apiabiversion apiabiversion11713346
Ref: 37d911713346
Ref: API 和 ABI 版本管理-Footnote-111715339
Node: 發布 Python 模組11715411
Ref: distributing/index doc11715534
Ref: 42e311715534
Ref: distributing/index distributing-index11715534
Ref: 8e311715534
Ref: distributing/index distributing-python-modules11715534
Ref: 42e411715534
Node: 關鍵術語11716620
Ref: distributing/index key-terms11716725
Ref: 42e511716725
Ref: 關鍵術語-Footnote-111718685
Ref: 關鍵術語-Footnote-211718710
Ref: 關鍵術語-Footnote-311718739
Ref: 關鍵術語-Footnote-411718771
Ref: 關鍵術語-Footnote-511718807
Ref: 關鍵術語-Footnote-611718860
Ref: 關鍵術語-Footnote-711718898
Ref: 關鍵術語-Footnote-811718951
Node: 開源授權與協同合作11719000
Ref: distributing/index open-source-licensing-and-collaboration11719126
Ref: 42e611719126
Ref: distributing/index wheel11719126
Ref: 42e711719126
Node: 安裝工具11719998
Ref: distributing/index installing-the-tools11720147
Ref: 42e811720147
Ref: 安裝工具-Footnote-111720982
Node: 閱讀 Python 封裝使用者指南11721080
Ref: distributing/index publishing-python-packages11721218
Ref: 42e911721218
Ref: distributing/index reading-the-python-packaging-user-guide11721218
Ref: 42ea11721218
Ref: 閱讀 Python 封裝使用者指南-Footnote-111721576
Ref: 閱讀 Python 封裝使用者指南-Footnote-211721670
Ref: 閱讀 Python 封裝使用者指南-Footnote-311721765
Ref: 閱讀 Python 封裝使用者指南-Footnote-411721869
Node: 我該如何 ？11721929
Ref: distributing/index how-do-i11722046
Ref: 42eb11722046
Ref: distributing/index the-pypirc-file11722046
Ref: 42ec11722046
Node: 為我的專案選擇一個名稱？11722319
Ref: distributing/index choose-a-name-for-my-project11722450
Ref: 42ed11722450
Node: 建立和發布二進制擴充？11723021
Ref: distributing/index create-and-distribute-binary-extensions11723152
Ref: 42ee11723152
Ref: 建立和發布二進制擴充？-Footnote-111723539
Node: 安裝 Python 模組11723612
Ref: installing/index doc11723735
Ref: 42ef11723735
Ref: installing/index installing-index11723735
Ref: 8e211723735
Ref: installing/index installing-python-modules11723735
Ref: 42f011723735
Node: 關鍵術語<2>11724806
Ref: installing/index key-terms11724899
Ref: 42f111724899
Ref: 關鍵術語<2>-Footnote-111726904
Ref: 關鍵術語<2>-Footnote-211726929
Ref: 關鍵術語<2>-Footnote-311726958
Ref: 關鍵術語<2>-Footnote-411726990
Ref: 關鍵術語<2>-Footnote-511727026
Node: 基本用法11727106
Ref: installing/index basic-usage11727227
Ref: 42f211727227
Ref: 基本用法-Footnote-111728770
Ref: 基本用法-Footnote-211728807
Node: 我該如何 ？<2>11728856
Ref: installing/index how-do-i11728983
Ref: 42f311728983
Node: 在 Python 3 4 之前的 Python 版本中安裝 pip？11729486
Ref: installing/index install-pip-in-versions-of-python-prior-to-python-3-411729644
Ref: 42f411729644
Ref: 在 Python 3 4 之前的 Python 版本中安裝 pip？-Footnote-111730074
Node: 只為目前的使用者安裝套件？11730161
Ref: installing/index install-packages-just-for-the-current-user11730360
Ref: 42f511730360
Node: 安裝科學的 Python 套件？11730587
Ref: installing/index install-scientific-python-packages11730782
Ref: 42f611730782
Ref: 安裝科學的 Python 套件？-Footnote-111731210
Ref: 安裝科學的 Python 套件？-Footnote-211731256
Node: 平行安裝多個 Python 版本並使用它們？11731302
Ref: installing/index work-with-multiple-versions-of-python-installed-in-parallel11731449
Ref: 42f711731449
Node: 常見的安裝問題11732420
Ref: installing/index common-installation-issues11732526
Ref: 42f811732526
Node: 在 Linux 上安裝套件至系統 Python11732730
Ref: installing/index installing-into-the-system-python-on-linux11732851
Ref: 42f911732851
Node: 未安裝 pip11733397
Ref: installing/index pip-not-installed11733565
Ref: 42fa11733565
Ref: 未安裝 pip-Footnote-111733811
Node: 安裝二進制擴充 binary extension11733913
Ref: installing/index installing-binary-extensions11734031
Ref: 42fb11734031
Ref: 安裝二進制擴充 binary extension-Footnote-111734902
Ref: 安裝二進制擴充 binary extension-Footnote-211734948
Node: Python 如何達成任務11734997
Ref: howto/index doc11735119
Ref: 42fc11735119
Ref: howto/index python-howtos11735119
Ref: 42fd11735119
Node: Python 2 的程式碼移植到Python 311735981
Ref: howto/pyporting doc11736120
Ref: 42fe11736120
Ref: howto/pyporting porting-python-2-code-to-python-311736120
Ref: 42ff11736120
Ref: howto/pyporting pyporting-howto11736120
Ref: d4511736120
Ref: Python 2 的程式碼移植到Python 3-Footnote-111736925
Ref: Python 2 的程式碼移植到Python 3-Footnote-211737029
Ref: Python 2 的程式碼移植到Python 3-Footnote-311737075
Node: 簡短的說明11737133
Ref: howto/pyporting the-short-explanation11737241
Ref: 430011737241
Ref: 簡短的說明-Footnote-111738662
Ref: 簡短的說明-Footnote-211738704
Ref: 簡短的說明-Footnote-311738763
Ref: 簡短的說明-Footnote-411738812
Ref: 簡短的說明-Footnote-511738852
Ref: 簡短的說明-Footnote-611738900
Ref: 簡短的說明-Footnote-711738937
Node: 詳細的11738967
Ref: howto/pyporting details11739075
Ref: 430111739075
Node: 向下支援Python 2 6和更舊的版本11740522
Ref: howto/pyporting drop-support-for-python-2-6-and-older11740683
Ref: 430211740683
Ref: 向下支援Python 2 6和更舊的版本-Footnote-111741991
Ref: 向下支援Python 2 6和更舊的版本-Footnote-211742028
Node: 确保你在你的``setup py``文件中指定适当的版本支持11742068
Ref: howto/pyporting make-sure-you-specify-the-proper-version-support-in-your-setup-py-file11742262
Ref: 430311742262
Ref: 确保你在你的``setup py``文件中指定适当的版本支持-Footnote-111742834
Node: 有好的測試覆蓋率11742871
Ref: howto/pyporting have-good-test-coverage11743052
Ref: 430411743052
Ref: 有好的測試覆蓋率-Footnote-111743730
Node: 瞭解Python 2 & 3的差異11743772
Ref: howto/pyporting learn-the-differences-between-python-2-311743908
Ref: 430511743908
Ref: 瞭解Python 2 & 3的差異-Footnote-111744515
Ref: 瞭解Python 2 & 3的差異-Footnote-211744550
Node: 更新你的程式碼11744606
Ref: howto/pyporting update-your-code11744739
Ref: 430611744739
Ref: 更新你的程式碼-Footnote-111746791
Ref: 更新你的程式碼-Footnote-211746850
Ref: 更新你的程式碼-Footnote-311746899
Ref: 更新你的程式碼-Footnote-411746958
Ref: 更新你的程式碼-Footnote-511747007
Node: 除法11747044
Ref: howto/pyporting division11747141
Ref: 430711747141
Node: 文本与二进制数据11748244
Ref: howto/pyporting text-versus-binary-data11748389
Ref: 430811748389
Ref: 文本与二进制数据-Footnote-111754781
Node: 使用特征检测而不是版本检测11754818
Ref: howto/pyporting use-feature-detection-instead-of-version-detection11754948
Ref: 430911754948
Ref: 使用特征检测而不是版本检测-Footnote-111756494
Node: 防止兼容性退步11756538
Ref: howto/pyporting prevent-compatibility-regressions11756686
Ref: 430a11756686
Ref: 防止兼容性退步-Footnote-111757930
Ref: 防止兼容性退步-Footnote-211757970
Ref: 防止兼容性退步-Footnote-311758019
Node: 检查哪些依赖性会阻碍你的过渡11758078
Ref: howto/pyporting check-which-dependencies-block-your-transition11758264
Ref: 430b11758264
Ref: 检查哪些依赖性会阻碍你的过渡-Footnote-111759037
Node: 更新你的``setup py``文件以表示对Python 3的兼容11759085
Ref: howto/pyporting update-your-setup-py-file-to-denote-python-3-compatibility11759283
Ref: 430c11759283
Node: 使用持续集成以保持兼容11759792
Ref: howto/pyporting use-continuous-integration-to-stay-compatible11759987
Ref: 430d11759987
Ref: 使用持续集成以保持兼容-Footnote-111761154
Node: 考虑使用可选的静态类型检查11761191
Ref: howto/pyporting consider-using-optional-static-type-checking11761318
Ref: 430e11761318
Ref: 考虑使用可选的静态类型检查-Footnote-111762138
Ref: 考虑使用可选的静态类型检查-Footnote-211762168
Node: 遷移延伸模組到 Python 311762209
Ref: howto/cporting doc11762388
Ref: 430f11762388
Ref: howto/cporting cporting-howto11762388
Ref: d3f11762388
Ref: howto/cporting porting-extension-modules-to-python-311762388
Ref: 431011762388
Ref: howto/cporting why-python-3-exists11762388
Ref: 431111762388
Ref: 遷移延伸模組到 Python 3-Footnote-111763090
Ref: 遷移延伸模組到 Python 3-Footnote-211763141
Ref: 遷移延伸模組到 Python 3-Footnote-311763198
Ref: 遷移延伸模組到 Python 3-Footnote-411763225
Node: 用 Python 进行 Curses 编程11763272
Ref: howto/curses doc11763435
Ref: 431211763435
Ref: howto/curses cffi11763435
Ref: 431311763435
Ref: howto/curses curses-howto11763435
Ref: 22ad11763435
Ref: howto/curses curses-programming-with-python11763435
Ref: 431411763435
Node: curses 是什么？11763821
Ref: howto/curses what-is-curses11763952
Ref: 431511763952
Ref: curses 是什么？-Footnote-111766201
Ref: curses 是什么？-Footnote-211766241
Ref: curses 是什么？-Footnote-311766284
Node: Python 的 curses 模块11766333
Ref: howto/curses the-python-curses-module11766413
Ref: 431611766413
Node: 开始和结束 curses 应用程序11767223
Ref: howto/curses starting-and-ending-a-curses-application11767378
Ref: 431711767378
Node: 窗口和面板11770404
Ref: howto/curses windows-and-pads11770552
Ref: 431811770552
Node: 显示文字11774588
Ref: howto/curses displaying-text11774713
Ref: 431911774713
Node: 属性和颜色11778118
Ref: howto/curses attributes-and-color11778182
Ref: 431a11778182
Node: 用户输入11782487
Ref: howto/curses user-input11782612
Ref: 431b11782612
Ref: 用户输入-Footnote-111786188
Node: 更多的信息11786228
Ref: howto/curses for-more-information11786332
Ref: 431c11786332
Ref: 更多的信息-Footnote-111787832
Ref: 更多的信息-Footnote-211787869
Ref: 更多的信息-Footnote-311787932
Ref: 更多的信息-Footnote-411787984
Node: 修飾器 HowTo 指南11788058
Ref: howto/descriptor doc11788209
Ref: 431d11788209
Ref: howto/descriptor descriptor-howto-guide11788209
Ref: 431e11788209
Ref: howto/descriptor descriptorhowto11788209
Ref: 431f11788209
Node: 入门11789361
Ref: howto/descriptor primer11789456
Ref: 432011789456
Node: 简单示例：返回常量的描述器11789682
Ref: howto/descriptor simple-example-a-descriptor-that-returns-a-constant11789785
Ref: 432111789785
Node: 动态查找11791186
Ref: howto/descriptor dynamic-lookups11791310
Ref: 432211791310
Node: 托管属性11792662
Ref: howto/descriptor managed-attributes11792759
Ref: 432311792759
Node: 定制名称11795233
Ref: howto/descriptor customized-names11795327
Ref: 432411795327
Node: 结束语11797606
Ref: howto/descriptor closing-thoughts11797679
Ref: 432511797679
Node: 完整的实际例子11798893
Ref: howto/descriptor complete-practical-example11799009
Ref: 432611799009
Node: 验证器类11799238
Ref: howto/descriptor validator-class11799335
Ref: 432711799335
Node: 自定义验证器11800323
Ref: howto/descriptor custom-validators11800441
Ref: 432811800441
Ref: 自定义验证器-Footnote-111802986
Node: 实际应用11803055
Ref: howto/descriptor practical-application11803152
Ref: 432911803152
Node: 技术教程11804490
Ref: howto/descriptor technical-tutorial11804623
Ref: 432a11804623
Node: 摘要11804991
Ref: howto/descriptor abstract11805070
Ref: 432b11805070
Node: 定义与介绍11805346
Ref: howto/descriptor definition-and-introduction11805449
Ref: 432c11805449
Node: 描述器协议11806630
Ref: howto/descriptor descriptor-protocol11806748
Ref: 432d11806748
Node: 描述器调用概述11807929
Ref: howto/descriptor overview-of-descriptor-invocation11808050
Ref: 432e11808050
Node: 通过实例调用11808570
Ref: howto/descriptor invocation-from-an-instance11808691
Ref: 432f11808691
Node: 通过类调用11810945
Ref: howto/descriptor invocation-from-a-class11811064
Ref: 433011811064
Ref: 通过类调用-Footnote-111811584
Node: 通过 super 调用11811656
Ref: howto/descriptor invocation-from-super11811775
Ref: 433111811775
Ref: 通过 super 调用-Footnote-111812403
Ref: 通过 super 调用-Footnote-211812475
Node: 调用逻辑总结11812555
Ref: howto/descriptor summary-of-invocation-logic11812677
Ref: 433211812677
Node: 自动名称通知11813558
Ref: howto/descriptor automatic-name-notification11813695
Ref: 433311813695
Ref: 自动名称通知-Footnote-111814388
Node: ORM （对象关系映射）示例11814460
Ref: howto/descriptor orm-example11814570
Ref: 433411814570
Ref: ORM （对象关系映射）示例-Footnote-111816549
Ref: ORM （对象关系映射）示例-Footnote-211816621
Node: 纯 Python 等价实现11816674
Ref: howto/descriptor pure-python-equivalents11816777
Ref: 433511816777
Node: 属性<2>11817209
Ref: howto/descriptor properties11817302
Ref: 433611817302
Node: 函数和方法11819966
Ref: howto/descriptor functions-and-methods11820083
Ref: 433711820083
Node: 方法的种类11822665
Ref: howto/descriptor kinds-of-methods11822785
Ref: 433811822785
Node: 静态方法11824009
Ref: howto/descriptor static-methods11824123
Ref: 433911824123
Node: 类方法11825523
Ref: howto/descriptor class-methods11825647
Ref: 433a11825647
Node: 成员对象和 __slots__11827632
Ref: howto/descriptor member-objects-and-slots11827735
Ref: 433b11827735
Ref: 成员对象和 __slots__-Footnote-111835022
Node: 函式編程 HOWTO11835078
Ref: howto/functional doc11835225
Ref: 433c11835225
Ref: howto/functional functional-programming-howto11835225
Ref: 433d11835225
Node: 簡介<13>11835837
Ref: howto/functional introduction11835920
Ref: 433e11835920
Node: 形式证明11839927
Ref: howto/functional formal-provability11840004
Ref: 434011840004
Node: 模块化11841635
Ref: howto/functional modularity11841742
Ref: 434111841742
Node: 易于调试和测试11842045
Ref: howto/functional ease-of-debugging-and-testing11842149
Ref: 434211842149
Node: 组合性11842749
Ref: howto/functional composability11842835
Ref: 434311842835
Node: 迭代器11843449
Ref: howto/functional functional-howto-iterators11843577
Ref: 433f11843577
Ref: howto/functional iterators11843577
Ref: 434411843577
Node: 支持迭代器的数据类型11846738
Ref: howto/functional data-types-that-support-iterators11846814
Ref: 434511846814
Node: 生成器表达式和列表推导式11848562
Ref: howto/functional generator-expressions-and-list-comprehensions11848689
Ref: 434611848689
Node: 生成器11852740
Ref: howto/functional generators11852870
Ref: 434711852870
Ref: 生成器-Footnote-111856341
Node: 向生成器传递值11856421
Ref: howto/functional passing-values-into-a-generator11856488
Ref: 434811856488
Ref: 向生成器传递值-Footnote-111860078
Node: 内置函数11860127
Ref: howto/functional built-in-functions11860237
Ref: 434911860237
Ref: 内置函数-Footnote-111864074
Node: itertools 模块11864128
Ref: howto/functional the-itertools-module11864245
Ref: 434a11864245
Node: 创建新的迭代器11864822
Ref: howto/functional creating-new-iterators11864926
Ref: 434b11864926
Node: 对元素使用函数11867592
Ref: howto/functional calling-functions-on-elements11867717
Ref: 434c11867717
Node: 选择元素11868495
Ref: howto/functional selecting-elements11868611
Ref: 434d11868611
Node: 组合函数11870015
Ref: howto/functional combinatoric-functions11870125
Ref: 434e11870125
Node: 为元素分组11872349
Ref: howto/functional grouping-elements11872438
Ref: 434f11872438
Node: functools 模块11873950
Ref: howto/functional the-functools-module11874084
Ref: 435011874084
Node: operator 模块11877565
Ref: howto/functional the-operator-module11877633
Ref: 435111877633
Node: 小函数和 lambda 表达式11878425
Ref: howto/functional small-functions-and-the-lambda-expression11878564
Ref: 435211878564
Node: 修订记录和致谢11881264
Ref: howto/functional revision-history-and-acknowledgements11881399
Ref: 435311881399
Node: 引用文献11882128
Ref: howto/functional references11882225
Ref: 435411882225
Node: 通用文献11882327
Ref: howto/functional general11882410
Ref: 435511882410
Node: Python 相关11883280
Ref: howto/functional python-specific11883385
Ref: 435611883385
Ref: Python 相关-Footnote-111883822
Ref: Python 相关-Footnote-211883873
Ref: Python 相关-Footnote-311883926
Node: Python 文档11883979
Ref: howto/functional python-documentation11884063
Ref: 435711884063
Ref: Python 文档-Footnote-111884396
Ref: Python 文档-Footnote-211884445
Node: 如何使用 Logging 模組11884494
Ref: howto/logging doc11884637
Ref: 435811884637
Ref: howto/logging logging-howto11884637
Ref: 435911884637
Node: 基礎 Logging 指南11884963
Ref: howto/logging basic-logging-tutorial11885075
Ref: 435a11885075
Ref: howto/logging logging-basic-tutorial11885075
Ref: c4311885075
Node: 什麼時候使用 logging11885804
Ref: howto/logging when-to-use-logging11885921
Ref: 435b11885921
Node: 一个简单的例子<2>11889324
Ref: howto/logging a-simple-example11889471
Ref: 435c11889471
Ref: howto/logging howto-minimal-example11889471
Ref: 435d11889471
Node: 记录日志到文件11890181
Ref: howto/logging logging-to-a-file11890329
Ref: 435e11890329
Node: 从多个模块记录日志11893080
Ref: howto/logging logging-from-multiple-modules11893222
Ref: 435f11893222
Node: 记录变量数据11894311
Ref: howto/logging logging-variable-data11894459
Ref: 436011894459
Node: 更改显示消息的格式11895217
Ref: howto/logging changing-the-format-of-displayed-messages11895369
Ref: 436111895369
Node: 在消息中显示日期/时间11896242
Ref: howto/logging displaying-the-date-time-in-messages11896388
Ref: 436211896388
Ref: 在消息中显示日期/时间-Footnote-111897372
Node: 后续步骤11897421
Ref: howto/logging next-steps11897531
Ref: 436311897531
Node: 进阶日志教程11898385
Ref: howto/logging advanced-logging-tutorial11898521
Ref: 436411898521
Ref: howto/logging logging-advanced-tutorial11898521
Ref: c4411898521
Node: 记录流程11901666
Ref: howto/logging logging-flow11901751
Ref: 436511901751
Node: 记录器11901893
Ref: howto/logging loggers11901996
Ref: 436611901996
Node: 处理器11905920
Ref: howto/logging handler-basic11906020
Ref: 436711906020
Ref: howto/logging handlers11906020
Ref: 436811906020
Node: 格式器11907821
Ref: howto/logging formatters11907930
Ref: 436a11907930
Ref: howto/logging logging logging Formatter __init__11908336
Ref: 436b11908336
Node: 配置日志记录11909874
Ref: howto/logging configuring-logging11910013
Ref: 436c11910013
Node: 如果没有提供配置会发生什么11916068
Ref: howto/logging what-happens-if-no-configuration-is-provided11916222
Ref: 436d11916222
Node: 配置库的日志记录11917503
Ref: howto/logging configuring-logging-for-a-library11917630
Ref: 436e11917630
Ref: howto/logging library-config11917630
Ref: 225411917630
Node: 日志级别<2>11919780
Ref: howto/logging logging-levels11919913
Ref: 436f11919913
Node: 自定义级别11922470
Ref: howto/logging custom-levels11922537
Ref: 222411922537
Ref: howto/logging id111922537
Ref: 437011922537
Node: 有用的处理器11923129
Ref: howto/logging id211923274
Ref: 437111923274
Ref: howto/logging useful-handlers11923274
Ref: 436911923274
Node: 记录日志时引发的异常11927035
Ref: howto/logging exceptions-raised-during-logging11927195
Ref: 437211927195
Ref: howto/logging logging-exceptions11927195
Ref: 437311927195
Node: 使用任意对象作为消息11928196
Ref: howto/logging arbitrary-object-messages11928344
Ref: 221511928344
Ref: howto/logging using-arbitrary-objects-as-messages11928344
Ref: 437411928344
Node: 优化11928858
Ref: howto/logging optimization11928967
Ref: 437511928967
Node: 日志操作手册11932335
Ref: howto/logging-cookbook doc11932487
Ref: 437611932487
Ref: howto/logging-cookbook id111932487
Ref: 437711932487
Ref: howto/logging-cookbook logging-cookbook11932487
Ref: c4511932487
Node: 在多个模块中使用日志11933970
Ref: howto/logging-cookbook using-logging-in-multiple-modules11934094
Ref: 437811934094
Node: 在多个线程中记录日志11937620
Ref: howto/logging-cookbook logging-from-multiple-threads11937787
Ref: 437911937787
Node: 多个 handler 和多种 formatter11939461
Ref: howto/logging-cookbook multiple-handlers-and-formatters11939625
Ref: 437a11939625
Node: 在多个地方记录日志11941600
Ref: howto/logging-cookbook logging-to-multiple-destinations11941761
Ref: 437b11941761
Ref: howto/logging-cookbook multiple-destinations11941761
Ref: 437c11941761
Node: 日志配置服务器示例11944514
Ref: howto/logging-cookbook configuration-server-example11944671
Ref: 437d11944671
Node: 处理日志 handler 的阻塞11946211
Ref: howto/logging-cookbook dealing-with-handlers-that-block11946371
Ref: 437e11946371
Node: 通过网络收发日志事件11949682
Ref: howto/logging-cookbook network-logging11949863
Ref: 437f11949863
Ref: howto/logging-cookbook sending-and-receiving-logging-events-across-a-network11949863
Ref: 438011949863
Node: Running a logging socket listener in production11955185
Ref: howto/logging-cookbook running-a-logging-socket-listener-in-production11955299
Ref: 438111955299
Ref: Running a logging socket listener in production-Footnote-111955772
Ref: Running a logging socket listener in production-Footnote-211955804
Node: 在自己的输出日志中添加上下文信息11955876
Ref: howto/logging-cookbook adding-contextual-information-to-your-logging-output11956072
Ref: 438211956072
Ref: howto/logging-cookbook context-info11956072
Ref: 221811956072
Node: 利用 LoggerAdapter 传递上下文信息11956956
Ref: howto/logging-cookbook using-loggeradapters-to-impart-contextual-information11957127
Ref: 438311957127
Node: 利用非字典对象传入上下文信息11959950
Ref: howto/logging-cookbook using-objects-other-than-dicts-to-pass-contextual-information11960071
Ref: 438411960071
Node: 利用 Filter 传递上下文信息11960448
Ref: howto/logging-cookbook filters-contextual11960619
Ref: 220d11960619
Ref: howto/logging-cookbook using-filters-to-impart-contextual-information11960619
Ref: 438511960619
Node: 在单个文件中记录多个进程的日志11964352
Ref: howto/logging-cookbook logging-to-a-single-file-from-multiple-processes11964548
Ref: 438611964548
Ref: howto/logging-cookbook multiple-processes11964548
Ref: 438711964548
Node: concurrent futures ProcessPoolExecutor 的用法11974664
Ref: howto/logging-cookbook using-concurrent-futures-processpoolexecutor11974854
Ref: 438811974854
Node: Deploying Web applications using Gunicorn and uWSGI11975825
Ref: howto/logging-cookbook deploying-web-applications-using-gunicorn-and-uwsgi11976015
Ref: 438911976015
Ref: Deploying Web applications using Gunicorn and uWSGI-Footnote-111976675
Ref: Deploying Web applications using Gunicorn and uWSGI-Footnote-211976705
Node: 利用日志文件轮换机制11976758
Ref: howto/logging-cookbook using-file-rotation11976927
Ref: 438a11976927
Node: 日志的其他格式11978797
Ref: howto/logging-cookbook format-styles11978940
Ref: 438b11978940
Ref: howto/logging-cookbook use-of-alternative-formatting-styles11978940
Ref: 438c11978940
Node: 自定义 LogRecord11985402
Ref: howto/logging-cookbook custom-logrecord11985553
Ref: 438d11985553
Ref: howto/logging-cookbook customizing-logrecord11985553
Ref: 438e11985553
Node: 子类化 QueueHandler - ZeroMQ 示例11989034
Ref: howto/logging-cookbook subclassing-queuehandler-a-zeromq-example11989208
Ref: 438f11989208
Ref: howto/logging-cookbook zeromq-handlers11989208
Ref: 439011989208
Node: 子类化 QueueListener —— ZeroMQ 示例11990480
Ref: howto/logging-cookbook subclassing-queuelistener-a-zeromq-example11990674
Ref: 439111990674
Node: 基于字典进行日志配置的示例11991767
Ref: howto/logging-cookbook an-example-dictionary-based-configuration11991975
Ref: 439211991975
Ref: 基于字典进行日志配置的示例-Footnote-111993993
Node: 利用 rotator 和 namer 自定义日志轮换操作11994079
Ref: howto/logging-cookbook cookbook-rotator-namer11994276
Ref: 226111994276
Ref: howto/logging-cookbook using-a-rotator-and-namer-to-customize-log-rotation-processing11994276
Ref: 439311994276
Node: 更详细的多进程日志示例11995075
Ref: howto/logging-cookbook a-more-elaborate-multiprocessing-example11995291
Ref: 439411995291
Node: 在发送给 SysLogHandler 的信息中插入一个 BOM。12004772
Ref: howto/logging-cookbook inserting-a-bom-into-messages-sent-to-a-sysloghandler12004966
Ref: 439512004966
Ref: 在发送给 SysLogHandler 的信息中插入一个 BOM。-Footnote-112006879
Ref: 在发送给 SysLogHandler 的信息中插入一个 BOM。-Footnote-212006928
Ref: 在发送给 SysLogHandler 的信息中插入一个 BOM。-Footnote-312006987
Ref: 在发送给 SysLogHandler 的信息中插入一个 BOM。-Footnote-412007036
Node: 结构化日志的实现代码12007085
Ref: howto/logging-cookbook implementing-structured-logging12007281
Ref: 439612007281
Node: 利用 dictConfig 自定义 handler12009844
Ref: howto/logging-cookbook custom-handlers12010027
Ref: 439712010027
Ref: howto/logging-cookbook customizing-handlers-with-dictconfig12010027
Ref: 439812010027
Node: 生效于整个应用程序的格式化样式12014960
Ref: howto/logging-cookbook formatting-styles12015143
Ref: 220412015143
Ref: howto/logging-cookbook using-particular-formatting-styles-throughout-your-application12015143
Ref: 439912015143
Node: LogRecord 工厂的用法12016793
Ref: howto/logging-cookbook using-logrecord-factories12016945
Ref: 439a12016945
Node: 自定义日志信息对象的使用12017846
Ref: howto/logging-cookbook using-custom-message-objects12017998
Ref: 439b12017998
Node: 用 dictConfig 配置过滤器12020407
Ref: howto/logging-cookbook configuring-filters-with-dictconfig12020588
Ref: 439c12020588
Ref: howto/logging-cookbook filters-dictconfig12020588
Ref: 439d12020588
Node: 异常信息的自定义格式化12023333
Ref: howto/logging-cookbook custom-format-exception12023493
Ref: 439e12023493
Ref: howto/logging-cookbook customized-exception-formatting12023493
Ref: 439f12023493
Node: 语音播报日志信息12025481
Ref: howto/logging-cookbook speaking-logging-messages12025647
Ref: 43a012025647
Ref: howto/logging-cookbook spoken-messages12025647
Ref: 43a112025647
Node: 缓冲日志信息并按条件输出12027431
Ref: howto/logging-cookbook buffered-logging12027616
Ref: 43a212027616
Ref: howto/logging-cookbook buffering-logging-messages-and-outputting-them-conditionally12027616
Ref: 43a312027616
Node: 通过配置将时间格式化为 UTC（GMT）格式12032670
Ref: howto/logging-cookbook formatting-times-using-utc-gmt-via-configuration12032873
Ref: 43a412032873
Ref: howto/logging-cookbook utc-formatting12032873
Ref: 43a512032873
Node: 用上下文管理器选择性记录日志12034752
Ref: howto/logging-cookbook context-manager12034946
Ref: 43a612034946
Ref: howto/logging-cookbook using-a-context-manager-for-selective-logging12034946
Ref: 43a712034946
Node: 命令行日志应用起步12039262
Ref: howto/logging-cookbook a-cli-application-starter-template12039433
Ref: 43a812039433
Ref: howto/logging-cookbook starter-template12039433
Ref: 43a912039433
Node: 用作日志的 Qt GUI 程序12045208
Ref: howto/logging-cookbook a-qt-gui-for-logging12045358
Ref: 43aa12045358
Ref: howto/logging-cookbook qt-gui12045358
Ref: 43ab12045358
Ref: 用作日志的 Qt GUI 程序-Footnote-112054612
Ref: 用作日志的 Qt GUI 程序-Footnote-212054639
Ref: 用作日志的 Qt GUI 程序-Footnote-312054681
Node: 理应避免的用法12054721
Ref: howto/logging-cookbook patterns-to-avoid12054835
Ref: 43ac12054835
Node: 多次打开同一个日志文件12055295
Ref: howto/logging-cookbook opening-the-same-log-file-multiple-times12055437
Ref: 43ad12055437
Node: 将日志对象用作属性或传递参数12057013
Ref: howto/logging-cookbook using-loggers-as-attributes-in-a-class-or-passing-them-as-parameters12057224
Ref: 43ae12057224
Node: 给日志库代码添加 NullHandler 之外的其他 handler12057809
Ref: howto/logging-cookbook adding-handlers-other-than-nullhandler-to-a-logger-in-a-library12058014
Ref: 43af12058014
Node: 创建大量的日志对象12058419
Ref: howto/logging-cookbook creating-a-lot-of-loggers12058573
Ref: 43b012058573
Node: 如何使用正規表達式12059079
Ref: howto/regex doc12059225
Ref: 43b112059225
Ref: howto/regex regex-howto12059225
Ref: 189612059225
Ref: howto/regex regular-expression-howto12059225
Ref: 43b212059225
Node: 簡介<14>12059642
Ref: howto/regex introduction12059737
Ref: 43b312059737
Node: 简单模式12061050
Ref: howto/regex simple-patterns12061175
Ref: 43b412061175
Node: 匹配字符12061587
Ref: howto/regex matching-characters12061663
Ref: 43b512061663
Node: 重复12065676
Ref: howto/regex repeating-things12065752
Ref: 43b612065752
Node: 使用正则表达式12070020
Ref: howto/regex using-regular-expressions12070153
Ref: 43b712070153
Node: 编译正则表达式12070554
Ref: howto/regex compiling-regular-expressions12070657
Ref: 43b812070657
Node: 反斜杠灾难12071717
Ref: howto/regex id112071841
Ref: 43b912071841
Ref: howto/regex the-backslash-plague12071841
Ref: 43ba12071841
Node: 应用匹配12074522
Ref: howto/regex performing-matches12074643
Ref: 43bb12074643
Ref: 应用匹配-Footnote-112080100
Node: 模块级别函数12080172
Ref: howto/regex module-level-functions12080290
Ref: 43bc12080290
Node: 编译标志12081374
Ref: howto/regex compilation-flags12081471
Ref: 43bd12081471
Node: 更多模式能力12087857
Ref: howto/regex more-pattern-power12087993
Ref: 43bf12087993
Node: 更多元字符12088308
Ref: howto/regex id212088393
Ref: 43c012088393
Ref: howto/regex more-metacharacters12088393
Ref: 43be12088393
Node: 分组12092560
Ref: howto/regex grouping12092675
Ref: 43c112092675
Node: 非捕获和命名组12095727
Ref: howto/regex non-capturing-and-named-groups12095839
Ref: 43c212095839
Node: 前向断言12100229
Ref: howto/regex lookahead-assertions12100326
Ref: 43c312100326
Node: 修改字符串12103472
Ref: howto/regex modifying-strings12103599
Ref: 43c412103599
Node: 分割字符串12104479
Ref: howto/regex splitting-strings12104570
Ref: 43c512104570
Node: 搜索和替换12106743
Ref: howto/regex search-and-replace12106834
Ref: 43c612106834
Node: 常见问题12110941
Ref: howto/regex common-problems12111056
Ref: 43c712111056
Node: 使用字符串方法12111455
Ref: howto/regex use-string-methods12111550
Ref: 43c812111550
Node: match 和 search12113108
Ref: howto/regex match-versus-search12113230
Ref: 43c912113230
Node: 贪婪与非贪婪12114735
Ref: howto/regex greedy-versus-non-greedy12114853
Ref: 43ca12114853
Node: 使用 re VERBOSE12116609
Ref: howto/regex using-re-verbose12116702
Ref: 43cb12116702
Node: 反馈12118112
Ref: howto/regex feedback12118203
Ref: 43cc12118203
Node: 套接字编程指南12118876
Ref: howto/sockets doc12119016
Ref: 43cd12119016
Ref: howto/sockets socket-howto12119016
Ref: 27e912119016
Ref: howto/sockets socket-programming-howto12119016
Ref: 43ce12119016
Node: 套接字12119602
Ref: howto/sockets sockets12119696
Ref: 43cf12119696
Node: 历史12120843
Ref: howto/sockets history12120895
Ref: 43d012120895
Node: 创建套接字<2>12121442
Ref: howto/sockets creating-a-socket12121566
Ref: 43d112121566
Node: 进程间通信12124783
Ref: howto/sockets ipc12124853
Ref: 43d212124853
Node: 使用一个套接字12125361
Ref: howto/sockets using-a-socket12125488
Ref: 43d312125488
Node: 二进制数据12131286
Ref: howto/sockets binary-data12131359
Ref: 43d412131359
Node: 断开连接12132350
Ref: howto/sockets disconnecting12132480
Ref: 43d512132480
Node: 套接字何时销毁12133871
Ref: howto/sockets when-sockets-die12133941
Ref: 43d612133941
Node: 非阻塞的套接字12134674
Ref: howto/sockets non-blocking-sockets12134774
Ref: 43d712134774
Node: 如何排序12138600
Ref: howto/sorting doc12138727
Ref: 43d812138727
Ref: howto/sorting sorting-how-to12138727
Ref: 43d912138727
Ref: howto/sorting sortinghowto12138727
Ref: 173712138727
Node: 排序 基本12139317
Ref: howto/sorting sorting-basics12139400
Ref: 43da12139400
Node: 关键函数12140178
Ref: howto/sorting key-functions12140291
Ref: 43db12140291
Node: Operator 模块函数12141959
Ref: howto/sorting operator-module-functions12142074
Ref: 43dc12142074
Node: 升冪與降冪12143085
Ref: howto/sorting ascending-and-descending12143221
Ref: 43dd12143221
Node: 排序稳定性和排序复杂度12143704
Ref: howto/sorting sort-stability-and-complex-sorts12143860
Ref: 43de12143860
Ref: 排序稳定性和排序复杂度-Footnote-112145442
Ref: 排序稳定性和排序复杂度-Footnote-212145508
Node: 使用装饰-排序-去装饰的旧方法12145554
Ref: howto/sorting the-old-way-using-decorate-sort-undecorate12145724
Ref: 43df12145724
Ref: 使用装饰-排序-去装饰的旧方法-Footnote-112147178
Node: 使用 cmp 参数的旧方法12147238
Ref: howto/sorting the-old-way-using-the-cmp-parameter12147381
Ref: 43e012147381
Node: 其它12149693
Ref: howto/sorting odd-and-ends12149786
Ref: 43e112149786
Node: Unicode 指南12151421
Ref: howto/unicode doc12151569
Ref: 43e212151569
Ref: howto/unicode id112151569
Ref: 43e312151569
Ref: howto/unicode unicode-howto12151569
Ref: d0412151569
Node: Unicode 概述12151870
Ref: howto/unicode introduction-to-unicode12151969
Ref: 43e412151969
Node: 定义12152079
Ref: howto/unicode definitions12152151
Ref: 43e512152151
Ref: 定义-Footnote-112154812
Node: 编码12154869
Ref: howto/unicode encodings12154965
Ref: 43e612154965
Node: 引用文献<2>12158084
Ref: howto/unicode references12158165
Ref: 43e712158165
Ref: 引用文献<2>-Footnote-112159266
Ref: 引用文献<2>-Footnote-212159298
Ref: 引用文献<2>-Footnote-312159355
Node: Python对Unicode的支持12159399
Ref: howto/unicode python-s-unicode-support12159530
Ref: 43e812159530
Node: 字符串类型12159880
Ref: howto/unicode the-string-type12159981
Ref: 43e912159981
Node: 转换为字节12162945
Ref: howto/unicode converting-to-bytes12163092
Ref: 43ea12163092
Node: Python 源代码中的 Unicode 文字12164797
Ref: howto/unicode unicode-literals-in-python-source-code12164942
Ref: 43eb12164942
Ref: Python 源代码中的 Unicode 文字-Footnote-112166847
Node: Unicode属性12166896
Ref: howto/unicode unicode-properties12167041
Ref: 43ec12167041
Node: 字符串比较12168588
Ref: howto/unicode comparing-strings12168719
Ref: 43ed12168719
Node: Unicode 正则表达式12171384
Ref: howto/unicode unicode-regular-expressions12171517
Ref: 43ee12171517
Node: 引用文献<3>12172576
Ref: howto/unicode id212172685
Ref: 43ef12172685
Ref: 引用文献<3>-Footnote-112173511
Ref: 引用文献<3>-Footnote-212173606
Node: Unicode 数据的读写12173658
Ref: howto/unicode reading-and-writing-unicode-data12173785
Ref: 43f012173785
Node: Unicode 文件名12177018
Ref: howto/unicode unicode-filenames12177134
Ref: 43f112177134
Node: 识别 Unicode 的编程技巧12179287
Ref: howto/unicode tips-for-writing-unicode-aware-programs12179427
Ref: 43f212179427
Node: 在文件编码格式之间进行转换12180668
Ref: howto/unicode converting-between-file-encodings12180810
Ref: 43f312180810
Node: 编码格式未知的文件12181555
Ref: howto/unicode files-in-an-unknown-encoding12181697
Ref: 43f412181697
Node: 引用文献<4>12182520
Ref: howto/unicode id312182634
Ref: 43f512182634
Ref: 引用文献<4>-Footnote-112183207
Ref: 引用文献<4>-Footnote-212183279
Ref: 引用文献<4>-Footnote-312183384
Node: 致谢<10>12183452
Ref: howto/unicode acknowledgements12183545
Ref: 43f612183545
Node: 如何使用urllib套件取得網路資源12183993
Ref: howto/urllib2 doc12184144
Ref: 43f712184144
Ref: howto/urllib2 howto-fetch-internet-resources-using-the-urllib-package12184144
Ref: 43f812184144
Ref: howto/urllib2 urllib-howto12184144
Ref: 2deb12184144
Ref: 如何使用urllib套件取得網路資源-Footnote-112184605
Ref: 如何使用urllib套件取得網路資源-Footnote-212184660
Node: 簡介<15>12184736
Ref: howto/urllib2 introduction12184852
Ref: 43f912184852
Ref: 簡介<15>-Footnote-112186207
Ref: 簡介<15>-Footnote-212186280
Node: 從URL取得資源12186329
Ref: howto/urllib2 fetching-urls12186469
Ref: 43fa12186469
Node: 数据12188511
Ref: howto/urllib2 data12188598
Ref: 43fb12188598
Ref: 数据-Footnote-112191065
Node: HTTP 头部信息12191134
Ref: howto/urllib2 headers12191221
Ref: 43fc12191221
Ref: HTTP 头部信息-Footnote-112192731
Ref: HTTP 头部信息-Footnote-212192760
Ref: HTTP 头部信息-Footnote-312192996
Ref: HTTP 头部信息-Footnote-412193123
Node: 异常的处理12193235
Ref: howto/urllib2 handling-exceptions12193387
Ref: 43ff12193387
Node: URLError12193841
Ref: howto/urllib2 urlerror12193919
Ref: 440012193919
Node: HTTPError12194446
Ref: howto/urllib2 httperror12194539
Ref: 440112194539
Ref: HTTPError-Footnote-112195330
Node: 错误代码12195379
Ref: howto/urllib2 error-codes12195437
Ref: 440212195437
Ref: 错误代码-Footnote-112200146
Node: 总之12200195
Ref: howto/urllib2 wrapping-it-up12200271
Ref: 440312200271
Node: 第一种方案12200475
Ref: howto/urllib2 number-112200557
Ref: 440412200557
Node: 第二种方案12201194
Ref: howto/urllib2 number-212201276
Ref: 440512201276
Node: info 和 geturl 方法12201819
Ref: howto/urllib2 info-and-geturl12201971
Ref: 43fe12201971
Ref: info 和 geturl 方法-Footnote-112202872
Node: Opener 和 Handler12202909
Ref: howto/urllib2 openers-and-handlers12203058
Ref: 440612203058
Node: 基本认证12204606
Ref: howto/urllib2 id512204739
Ref: 440712204739
Ref: 基本认证-Footnote-112208051
Node: 代理12208124
Ref: howto/urllib2 proxies12208257
Ref: 440812208257
Ref: 代理-Footnote-112209194
Ref: 代理-Footnote-212209484
Ref: 代理-Footnote-312209557
Node: 套接字与分层12209695
Ref: howto/urllib2 sockets-and-layers12209825
Ref: 440912209825
Node: 註解<3>12210795
Ref: howto/urllib2 footnotes12210910
Ref: 440a12210910
Node: Argparse 教學12210975
Ref: howto/argparse doc12211133
Ref: 440b12211133
Ref: howto/argparse argparse-tutorial12211133
Ref: 440c12211133
Ref: howto/argparse id112211207
Ref: 218512211207
Node: 概念12211799
Ref: howto/argparse concepts12211881
Ref: 440d12211881
Node: 基本用法<2>12213655
Ref: howto/argparse the-basics12213764
Ref: 440e12213764
Node: 介紹位置參數12214996
Ref: howto/argparse introducing-positional-arguments12215117
Ref: 440f12215117
Node: 介紹選項參數12218262
Ref: howto/argparse introducing-optional-arguments12218401
Ref: 441012218401
Node: 短选项12221352
Ref: howto/argparse short-options12221416
Ref: 441112221416
Node: 現在結合位置與選項參數12222165
Ref: howto/argparse combining-positional-and-optional-arguments12222313
Ref: 441212222313
Node: 进行一些小小的改进12230496
Ref: howto/argparse getting-a-little-more-advanced12230632
Ref: 441312230632
Node: 矛盾的选项12232601
Ref: howto/argparse conflicting-options12232680
Ref: 441412232680
Node: 結論12235769
Ref: howto/argparse conclusion12235863
Ref: 441512235863
Node: ipaddress模組介紹12236073
Ref: howto/ipaddress doc12236211
Ref: 441612236211
Ref: howto/ipaddress an-introduction-to-the-ipaddress-module12236211
Ref: 441712236211
Ref: howto/ipaddress ipaddress-howto12236211
Ref: 304312236211
Node: 创建 Address/Network/Interface 对象12236797
Ref: howto/ipaddress creating-address-network-interface-objects12236942
Ref: 441812236942
Node: 关于IP版本的说明12237335
Ref: howto/ipaddress a-note-on-ip-versions12237457
Ref: 441912237457
Node: IP主机地址12238017
Ref: howto/ipaddress ip-host-addresses12238160
Ref: 441a12238160
Node: 定义网络12239175
Ref: howto/ipaddress defining-networks12239307
Ref: 441b12239307
Node: 主机接口12241334
Ref: howto/ipaddress host-interfaces12241443
Ref: 441c12241443
Node: 审查 Address/Network/Interface 对象12242276
Ref: howto/ipaddress inspecting-address-network-interface-objects12242459
Ref: 441d12242459
Node: Network 作为 Address 列表12244612
Ref: howto/ipaddress networks-as-lists-of-addresses12244765
Ref: 441e12244765
Node: 比较<3>12245493
Ref: howto/ipaddress comparisons12245645
Ref: 441f12245645
Node: 将IP地址与其他模块一起使用12245967
Ref: howto/ipaddress using-ip-addresses-with-other-modules12246135
Ref: 442012246135
Node: 实例创建失败时获取更多详细信息12246543
Ref: howto/ipaddress getting-more-detail-when-instance-creation-fails12246693
Ref: 442112246693
Node: Argument Clinic How-To12248513
Ref: howto/clinic doc12248677
Ref: 442212248677
Ref: howto/clinic argument-clinic-how-to12248677
Ref: 442312248677
Node: The Goals Of Argument Clinic12249704
Ref: howto/clinic the-goals-of-argument-clinic12249824
Ref: 442412249824
Node: Basic Concepts And Usage12252182
Ref: howto/clinic basic-concepts-and-usage12252341
Ref: 442512252341
Node: Converting Your First Function12254772
Ref: howto/clinic converting-your-first-function12254918
Ref: 442612254918
Node: Advanced Topics12271015
Ref: howto/clinic advanced-topics12271128
Ref: 442812271128
Node: Symbolic default values12272094
Ref: howto/clinic symbolic-default-values12272245
Ref: 442912272245
Node: Renaming the C functions and variables generated by Argument Clinic12272874
Ref: howto/clinic renaming-the-c-functions-and-variables-generated-by-argument-clinic12273078
Ref: 442a12273078
Node: Converting functions using PyArg_UnpackTuple12274741
Ref: howto/clinic converting-functions-using-pyarg-unpacktuple12274937
Ref: 442b12274937
Node: Optional Groups12275482
Ref: howto/clinic optional-groups12275679
Ref: 442c12275679
Node: Using real Argument Clinic converters instead of "legacy converters"12279733
Ref: howto/clinic using-real-argument-clinic-converters-instead-of-legacy-converters12279895
Ref: 442d12279895
Ref: Using real Argument Clinic converters instead of "legacy converters"-Footnote-112288753
Node: Py_buffer12288802
Ref: howto/clinic py-buffer12288968
Ref: 442e12288968
Node: Advanced converters12289284
Ref: howto/clinic advanced-converters12289406
Ref: 442f12289406
Node: Parameter default values12291107
Ref: howto/clinic default-values12291242
Ref: 442712291242
Ref: howto/clinic parameter-default-values12291242
Ref: 443012291242
Node: The NULL default value12291771
Ref: howto/clinic the-null-default-value12291926
Ref: 443112291926
Node: Expressions specified as default values12292400
Ref: howto/clinic expressions-specified-as-default-values12292555
Ref: 443212292555
Node: Using a return converter12294946
Ref: howto/clinic using-a-return-converter12295105
Ref: 443312295105
Node: Cloning existing functions12297746
Ref: howto/clinic cloning-existing-functions12297885
Ref: 443412297885
Node: Calling Python code12299205
Ref: howto/clinic calling-python-code12299344
Ref: 443512299344
Node: Using a "self converter"12300259
Ref: howto/clinic using-a-self-converter12300398
Ref: 443612300398
Node: Writing a custom converter12302132
Ref: howto/clinic writing-a-custom-converter12302285
Ref: 443712302285
Node: Writing a custom return converter12305978
Ref: howto/clinic writing-a-custom-return-converter12306129
Ref: 443812306129
Node: METH_O and METH_NOARGS12306708
Ref: howto/clinic meth-o-and-meth-noargs12306861
Ref: 443912306861
Node: tp_new and tp_init functions12307432
Ref: howto/clinic tp-new-and-tp-init-functions12307592
Ref: 443a12307592
Node: Changing and redirecting Clinic's output12308537
Ref: howto/clinic changing-and-redirecting-clinic-s-output12308691
Ref: 443b12308691
Node: The #ifdef trick12319945
Ref: howto/clinic the-ifdef-trick12320108
Ref: 443c12320108
Node: Using Argument Clinic in Python files12322882
Ref: howto/clinic using-argument-clinic-in-python-files12322996
Ref: 443d12322996
Node: 使用 DTrace 和 SystemTap 检测CPython12323692
Ref: howto/instrumentation doc12323826
Ref: 443e12323826
Ref: howto/instrumentation instrumentation12323826
Ref: 60512323826
Ref: howto/instrumentation instrumenting-cpython-with-dtrace-and-systemtap12323826
Ref: 443f12323826
Node: 启用静态标记12324876
Ref: howto/instrumentation enabling-the-static-markers12324999
Ref: 444012324999
Node: 静态DTrace探针12329027
Ref: howto/instrumentation static-dtrace-probes12329180
Ref: 444112329180
Node: 静态SystemTap标记12331568
Ref: howto/instrumentation static-systemtap-markers12331724
Ref: 444212331724
Node: 可用的静态标记12333666
Ref: howto/instrumentation available-static-markers12333821
Ref: 444312333821
Node: SystemTap Tapsets12336109
Ref: howto/instrumentation systemtap-tapsets12336253
Ref: 444412336253
Node: 示例<52>12337814
Ref: howto/instrumentation examples12337928
Ref: 444512337928
Node: Python 常見問題12339194
Ref: faq/index doc12339305
Ref: 444612339305
Ref: faq/index faq-index12339305
Ref: 144c12339305
Ref: faq/index python-frequently-asked-questions12339305
Ref: 444712339305
Node: 常見Python問答集12339665
Ref: faq/general doc12339778
Ref: 444812339778
Ref: faq/general general-python-faq12339778
Ref: 444912339778
Node: 常見資訊12339881
Ref: faq/general general-information12339981
Ref: 444a12339981
Node: 什麼是Python?12340870
Ref: faq/general what-is-python12340975
Ref: 444b12340975
Ref: 什麼是Python?-Footnote-112341854
Node: 什麼是Python軟體基金會?12341906
Ref: faq/general what-is-the-python-software-foundation12342063
Ref: 444c12342063
Node: 當使用Python時有任何版權限制嗎?12342646
Ref: faq/general are-there-copyright-restrictions-on-the-use-of-python12342817
Ref: 444d12342817
Ref: 當使用Python時有任何版權限制嗎?-Footnote-112343609
Node: 為什麼Python被創造出來12343656
Ref: faq/general why-was-python-created-in-the-first-place12343826
Ref: 444e12343826
Node: 什麼是Python擅長的事情12346020
Ref: faq/general what-is-python-good-for12346190
Ref: 444f12346190
Ref: 什麼是Python擅長的事情-Footnote-112347022
Node: Python 版本的编号形式是怎样的？12347047
Ref: faq/general how-does-the-python-version-numbering-scheme-work12347220
Ref: 445012347220
Ref: Python 版本的编号形式是怎样的？-Footnote-112349126
Node: 我如何拿到Python的原始碼12349175
Ref: faq/general how-do-i-obtain-a-copy-of-the-python-source12349351
Ref: 445112349351
Ref: 我如何拿到Python的原始碼-Footnote-112350071
Node: 如何取得Python的相關文件12350114
Ref: faq/general how-do-i-get-documentation-on-python12350298
Ref: 445212350298
Ref: 如何取得Python的相關文件-Footnote-112350787
Node: 我從來沒寫過程式，有沒有Python的教學12350818
Ref: faq/general i-ve-never-programmed-before-is-there-a-python-tutorial12351023
Ref: 445312351023
Ref: 我從來沒寫過程式，有沒有Python的教學-Footnote-112351368
Node: 有沒有新手的群組或是郵件群組討論Python12351420
Ref: faq/general is-there-a-newsgroup-or-mailing-list-devoted-to-python12351642
Ref: 445412351642
Ref: 有沒有新手的群組或是郵件群組討論Python-Footnote-112352479
Ref: 有沒有新手的群組或是郵件群組討論Python-Footnote-212352540
Node: 我应如何获取 Python 的公开测试版本？12352610
Ref: faq/general how-do-i-get-a-beta-test-version-of-python12352834
Ref: 445512352834
Ref: 我应如何获取 Python 的公开测试版本？-Footnote-112353357
Node: 我应如何为 Python 提交错误报告和补丁？12353394
Ref: faq/general how-do-i-submit-bug-reports-and-patches-for-python12353641
Ref: 445612353641
Ref: 我应如何为 Python 提交错误报告和补丁？-Footnote-112354331
Ref: 我应如何为 Python 提交错误报告和补丁？-Footnote-212354388
Node: 是否有任何公开发表的 Python 相关文章可以供我参考引用？12354425
Ref: faq/general are-there-any-published-articles-about-python-that-i-can-reference12354649
Ref: 445712354649
Node: 有沒有關於Python的書12355173
Ref: faq/general are-there-any-books-on-python12355392
Ref: 445812355392
Node: www python org 這個非營利組織位於哪裡12355729
Ref: faq/general where-in-the-world-is-www-python-org-located12355898
Ref: 445912355898
Ref: www python org 這個非營利組織位於哪裡-Footnote-112356170
Node: 為什麼要取名為Python12356198
Ref: faq/general why-is-it-called-python12356402
Ref: 445a12356402
Ref: 為什麼要取名為Python-Footnote-112356844
Node: 我需要喜歡蒙提·派森的飛行馬戲團這個節目嗎12356895
Ref: faq/general do-i-have-to-like-monty-python-s-flying-circus12357042
Ref: 445b12357042
Node: Python在真實世界12357200
Ref: faq/general python-in-the-real-world12357300
Ref: 445c12357300
Node: Python穩定性如何12357672
Ref: faq/general how-stable-is-python12357784
Ref: 445d12357784
Ref: Python穩定性如何-Footnote-112358769
Ref: Python穩定性如何-Footnote-212358818
Ref: Python穩定性如何-Footnote-312358860
Node: 有多少人使用Python12358910
Ref: faq/general how-many-people-are-using-python12359085
Ref: 445e12359085
Node: 有沒有任何重要的案子使用Python完成開發12359589
Ref: faq/general have-any-significant-projects-been-done-in-python12359797
Ref: 445f12359797
Ref: 有沒有任何重要的案子使用Python完成開發-Footnote-112360473
Ref: 有沒有任何重要的案子使用Python完成開發-Footnote-212360525
Ref: 有沒有任何重要的案子使用Python完成開發-Footnote-312360553
Ref: 有沒有任何重要的案子使用Python完成開發-Footnote-412360581
Node: 對於程式開發者Python對於未來有什麼期待12360612
Ref: faq/general what-new-developments-are-expected-for-python-in-the-future12360852
Ref: 446012360852
Ref: 對於程式開發者Python對於未來有什麼期待-Footnote-112361417
Node: 提议对 Python 加入不兼容的更改是否合理？12361478
Ref: faq/general is-it-reasonable-to-propose-incompatible-changes-to-python12361733
Ref: 446112361733
Ref: 提议对 Python 加入不兼容的更改是否合理？-Footnote-112362483
Node: Python對於入門的程式設計者而言是否為好的程式語言12362532
Ref: faq/general is-python-a-good-language-for-beginning-programmers12362724
Ref: 446212362724
Ref: Python對於入門的程式設計者而言是否為好的程式語言-Footnote-112366396
Ref: Python對於入門的程式設計者而言是否為好的程式語言-Footnote-212366447
Node: 程式開發常見問答集12366509
Ref: faq/programming doc12366658
Ref: 446312366658
Ref: faq/programming programming-faq12366658
Ref: 446412366658
Node: 常見問題12366872
Ref: faq/programming general-questions12366975
Ref: 446512366975
Node: 是否有可以使用在程式碼階段 具有中斷點 步驟執行等功能的除錯器？12367398
Ref: faq/programming is-there-a-source-code-level-debugger-with-breakpoints-single-stepping-etc12367607
Ref: 446612367607
Ref: 是否有可以使用在程式碼階段 具有中斷點 步驟執行等功能的除錯器？-Footnote-112368996
Ref: 是否有可以使用在程式碼階段 具有中斷點 步驟執行等功能的除錯器？-Footnote-212369040
Ref: 是否有可以使用在程式碼階段 具有中斷點 步驟執行等功能的除錯器？-Footnote-312369093
Ref: 是否有可以使用在程式碼階段 具有中斷點 步驟執行等功能的除錯器？-Footnote-412369138
Ref: 是否有可以使用在程式碼階段 具有中斷點 步驟執行等功能的除錯器？-Footnote-512369187
Ref: 是否有可以使用在程式碼階段 具有中斷點 步驟執行等功能的除錯器？-Footnote-612369226
Ref: 是否有可以使用在程式碼階段 具有中斷點 步驟執行等功能的除錯器？-Footnote-712369256
Ref: 是否有可以使用在程式碼階段 具有中斷點 步驟執行等功能的除錯器？-Footnote-812369313
Node: 有沒有工具能夠幫忙找 bug 或執行靜態分析？12369356
Ref: faq/programming are-there-tools-to-help-find-bugs-or-perform-static-analysis12369639
Ref: 446712369639
Ref: 有沒有工具能夠幫忙找 bug 或執行靜態分析？-Footnote-112370002
Ref: 有沒有工具能夠幫忙找 bug 或執行靜態分析？-Footnote-212370034
Ref: 有沒有工具能夠幫忙找 bug 或執行靜態分析？-Footnote-312370076
Ref: 有沒有工具能夠幫忙找 bug 或執行靜態分析？-Footnote-412370106
Ref: 有沒有工具能夠幫忙找 bug 或執行靜態分析？-Footnote-512370138
Node: 如何由 Python 脚本创建能独立运行的二进制程序？12370179
Ref: faq/programming faq-create-standalone-binary12370417
Ref: 446812370417
Ref: faq/programming how-can-i-create-a-stand-alone-binary-from-a-python-script12370417
Ref: 446912370417
Ref: 如何由 Python 脚本创建能独立运行的二进制程序？-Footnote-112372011
Ref: 如何由 Python 脚本创建能独立运行的二进制程序？-Footnote-212372039
Ref: 如何由 Python 脚本创建能独立运行的二进制程序？-Footnote-312372075
Ref: 如何由 Python 脚本创建能独立运行的二进制程序？-Footnote-412372128
Ref: 如何由 Python 脚本创建能独立运行的二进制程序？-Footnote-512372180
Ref: 如何由 Python 脚本创建能独立运行的二进制程序？-Footnote-612372229
Node: 是否有 Python 编码标准或风格指南？12372260
Ref: faq/programming are-there-coding-standards-or-a-style-guide-for-python-programs12372430
Ref: 446a12372430
Ref: 是否有 Python 编码标准或风格指南？-Footnote-112372647
Node: 语言核心内容12372696
Ref: faq/programming core-language12372826
Ref: 446b12372826
Node: 為什麼當變數有值時我得到錯誤訊息 UnboundLocalError12373960
Ref: faq/programming why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value12374145
Ref: 446c12374145
Node: Python 的區域變數和全域變數有什麼規則？12375898
Ref: faq/programming what-are-the-rules-for-local-and-global-variables-in-python12376172
Ref: 446d12376172
Node: 为什么在循环中定义的参数各异的 lambda 都返回相同的结果？12376945
Ref: faq/programming why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result12377189
Ref: 446e12377189
Node: 如何跨模块共享全局变量？12379043
Ref: faq/programming how-do-i-share-global-variables-across-modules12379277
Ref: 446f12379277
Node: 导入模块的“最佳实践”是什么？12380012
Ref: faq/programming what-are-the-best-practices-for-using-import-in-a-module12380208
Ref: 447012380208
Node: 为什么对象之间会共享默认值？12382705
Ref: faq/programming why-are-default-values-shared-between-objects12382946
Ref: 447112382946
Node: 如何将可选参数或关键字参数从一个函数传递到另一个函数？12385193
Ref: faq/programming how-can-i-pass-optional-or-keyword-parameters-from-one-function-to-another12385428
Ref: 447212385428
Node: 形参和实参之间有什么区别？12385952
Ref: faq/programming faq-argument-vs-parameter12386196
Ref: 447312386196
Ref: faq/programming what-is-the-difference-between-arguments-and-parameters12386196
Ref: 447412386196
Node: 为什么修改列表 'y' 也会更改列表 'x'？12386767
Ref: faq/programming why-did-changing-list-y-also-change-list-x12386996
Ref: 447512386996
Node: 如何编写带有输出参数的函数（按照引用调用）？12390253
Ref: faq/programming how-do-i-write-a-function-with-output-parameters-call-by-reference12390484
Ref: 447612390484
Node: 如何在 Python 中创建高阶函数？12392819
Ref: faq/programming how-do-you-make-a-higher-order-function-in-python12393028
Ref: 447712393028
Node: 如何复制 Python 对象？12394580
Ref: faq/programming how-do-i-copy-an-object-in-python12394762
Ref: 447812394762
Node: 如何找到对象的方法或属性？12395210
Ref: faq/programming how-can-i-find-the-methods-or-attributes-of-an-object12395390
Ref: 447912395390
Node: 如何用代码获取对象的名称？12395656
Ref: faq/programming how-can-my-code-discover-the-name-of-an-object12395846
Ref: 447a12395846
Node: 逗号运算符的优先级是什么？12397321
Ref: faq/programming what-s-up-with-the-comma-operator-s-precedence12397535
Ref: 447b12397535
Node: 是否提供等价于 C 语言 "? " 三目运算符的东西？12398055
Ref: faq/programming is-there-an-equivalent-of-c-s-ternary-operator12398287
Ref: 447c12398287
Node: 是否可以用 Python 编写让人眼晕的单行程序?12398846
Ref: faq/programming is-it-possible-to-write-obfuscated-one-liners-in-python12399094
Ref: 447d12399094
Node: 函数形参列表中的斜杠（/）是什么意思？12400570
Ref: faq/programming faq-positional-only-arguments12400746
Ref: 172912400746
Ref: faq/programming what-does-the-slash-in-the-parameter-list-of-a-function-mean12400746
Ref: 447e12400746
Node: 数字和字符串12401685
Ref: faq/programming numbers-and-strings12401812
Ref: 447f12401812
Node: 如何给出十六进制和八进制整数？12402543
Ref: faq/programming how-do-i-specify-hexadecimal-and-octal-integers12402688
Ref: 448012402688
Node: 为什么 -22 // 10 会返回 -3 ？12403314
Ref: faq/programming why-does-22-10-return-312403526
Ref: 448112403526
Node: How do I get int literal attribute instead of SyntaxError?12404354
Ref: faq/programming how-do-i-get-int-literal-attribute-instead-of-syntaxerror12404557
Ref: 448212404557
Node: 如何将字符串转换为数字？12405132
Ref: faq/programming how-do-i-convert-a-string-to-a-number12405335
Ref: 448312405335
Node: 如何将数字转换为字符串？12406572
Ref: faq/programming how-do-i-convert-a-number-to-a-string12406741
Ref: 448412406741
Node: 如何修改字符串？12407293
Ref: faq/programming how-do-i-modify-a-string-in-place12407469
Ref: 448512407469
Node: 如何使用字符串调用函数/方法？12408261
Ref: faq/programming how-do-i-use-strings-to-call-functions-methods12408490
Ref: 448612408490
Node: 是否有与Perl 的chomp 等效的方法，用于从字符串中删除尾随换行符？12409684
Ref: faq/programming is-there-an-equivalent-to-perl-s-chomp-for-removing-trailing-newlines-from-strings12409934
Ref: 448712409934
Node: 是否有 scanf 或 sscanf 的等价函数？12410604
Ref: faq/programming is-there-a-scanf-or-sscanf-equivalent12410881
Ref: 448812410881
Node: 'UnicodeDecodeError' 或 'UnicodeEncodeError' 错误是什么意思？12411493
Ref: faq/programming what-does-unicodedecodeerror-or-unicodeencodeerror-error-mean12411672
Ref: 448912411672
Node: 性能<4>12411866
Ref: faq/programming performance12412000
Ref: 448a12412000
Node: 我的程序太慢了。该如何加快速度？12412158
Ref: faq/programming my-program-is-too-slow-how-do-i-speed-it-up12412324
Ref: 448b12412324
Ref: 我的程序太慢了。该如何加快速度？-Footnote-112414916
Ref: 我的程序太慢了。该如何加快速度？-Footnote-212414942
Node: 将多个字符串连接在一起的最有效方法是什么？12415007
Ref: faq/programming efficient-string-concatenation12415173
Ref: 448c12415173
Ref: faq/programming what-is-the-most-efficient-way-to-concatenate-many-strings-together12415173
Ref: 448d12415173
Node: 序列（元组/列表）12416100
Ref: faq/programming sequences-tuples-lists12416222
Ref: 448e12416222
Node: 如何在元组和列表之间进行转换？12416806
Ref: faq/programming how-do-i-convert-between-tuples-and-lists12416946
Ref: 448f12416946
Node: 什么是负数索引？12417807
Ref: faq/programming what-s-a-negative-index12417986
Ref: 449012417986
Node: 序列如何以逆序遍历？12418502
Ref: faq/programming how-do-i-iterate-over-a-sequence-in-reverse-order12418672
Ref: 449112418672
Node: 如何从列表中删除重复项？12418942
Ref: faq/programming how-do-you-remove-duplicates-from-a-list12419124
Ref: 449212419124
Node: 如何从列表中删除多个项？12419939
Ref: faq/programming how-do-you-remove-multiple-items-from-a-list12420126
Ref: 449312420126
Node: 如何在 Python 中创建数组？12420616
Ref: faq/programming how-do-you-make-an-array-in-python12420794
Ref: 449412420794
Node: 如何创建多维列表？12421734
Ref: faq/programming faq-multidimensional-list12421918
Ref: 176512421918
Ref: faq/programming how-do-i-create-a-multidimensional-list12421918
Ref: 449512421918
Ref: 如何创建多维列表？-Footnote-112423085
Node: 如何将方法应用于一系列对象？12423115
Ref: faq/programming how-do-i-apply-a-method-to-a-sequence-of-objects12423315
Ref: 449612423315
Node: 为什么 a_tuple[i] += ['item'] 会引发异常？12423486
Ref: faq/programming faq-augmented-assignment-tuple-error12423733
Ref: 15ba12423733
Ref: faq/programming why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works12423733
Ref: 449712423733
Node: 我想做一个复杂的排序：能用 Python 进行施瓦茨变换吗？12426572
Ref: faq/programming i-want-to-do-a-complicated-sort-can-you-do-a-schwartzian-transform-in-python12426837
Ref: 449812426837
Node: 如何根据另一个列表的值对某列表进行排序？12427282
Ref: faq/programming how-can-i-sort-one-list-by-values-from-another-list12427487
Ref: 449912427487
Node: 对象12428077
Ref: faq/programming objects12428199
Ref: 449a12428199
Node: 什么是类？12429100
Ref: faq/programming what-is-a-class12429185
Ref: 449b12429185
Node: 什么是方法？12429834
Ref: faq/programming what-is-a-method12429946
Ref: 449c12429946
Node: 什么是 self ？12430265
Ref: faq/programming what-is-self12430428
Ref: 449d12430428
Node: 如何检查对象是否为给定类或其子类的一个实例？12430866
Ref: faq/programming how-do-i-check-if-an-object-is-an-instance-of-a-given-class-or-of-a-subclass-of-it12431029
Ref: 449f12431029
Node: 什么是委托？12433180
Ref: faq/programming what-is-delegation12433377
Ref: 44a012433377
Node: 如何在派生类中调用被重载的基类方法?12435053
Ref: faq/programming how-do-i-call-a-method-defined-in-a-base-class-from-a-derived-class-that-overrides-it12435232
Ref: 44a112435232
Node: 如何让代码更容易对基类进行修改？12435853
Ref: faq/programming how-can-i-organize-my-code-to-make-it-easier-to-change-the-base-class12436062
Ref: 44a212436062
Node: 如何创建静态类数据和静态类方法？12436512
Ref: faq/programming how-do-i-create-static-class-data-and-static-class-methods12436725
Ref: 44a312436725
Node: 在 Python 中如何重载构造函数（或方法）？12438259
Ref: faq/programming how-can-i-overload-constructors-or-methods-in-python12438505
Ref: 44a412438505
Node: 在用 __spam 的时候得到一个类似 _SomeClassName__spam 的错误信息。12439377
Ref: faq/programming i-try-to-use-spam-and-i-get-an-error-about-someclassname-spam12439644
Ref: 44a512439644
Node: 类定义了 __del__ 方法，但是删除对象时没有调用它。12440382
Ref: faq/programming my-class-defines-del-but-it-is-not-called-when-i-delete-the-object12440641
Ref: 44a612440641
Node: 如何获取给定类的所有实例的列表？12442492
Ref: faq/programming how-do-i-get-a-list-of-all-instances-of-a-given-class12442719
Ref: 44a712442719
Node: 为什么 id 的结果看起来不是唯一的？12442991
Ref: faq/programming why-does-the-result-of-id-appear-to-be-not-unique12443228
Ref: 44a812443228
Node: 什么情况下可以依靠 is 运算符进行对象的身份相等性测试？12444031
Ref: faq/programming when-can-i-rely-on-identity-tests-with-the-is-operator12444292
Ref: 44a912444292
Ref: 什么情况下可以依靠 is 运算符进行对象的身份相等性测试？-Footnote-112447377
Node: How can a subclass control what data is stored in an immutable instance?12447426
Ref: faq/programming how-can-a-subclass-control-what-data-is-stored-in-an-immutable-instance12447629
Ref: 44aa12447629
Node: 模块<2>12449105
Ref: faq/programming modules12449193
Ref: 44ab12449193
Node: 如何创建 pyc 文件？12449628
Ref: faq/programming how-do-i-create-a-pyc-file12449742
Ref: 44ac12449742
Ref: 如何创建 pyc 文件？-Footnote-112452151
Node: 如何找到当前模块名称？12452200
Ref: faq/programming how-do-i-find-the-current-module-name12452353
Ref: 44ad12452353
Node: 如何让模块相互导入？12452851
Ref: faq/programming how-can-i-have-modules-that-mutually-import-each-other12453050
Ref: 44ae12453050
Node: __import__ 'x y z' 返回的是 <module 'x'> ；该如何得到 z 呢？12454700
Ref: faq/programming import-x-y-z-returns-module-x-how-do-i-get-z12454968
Ref: 44af12454968
Node: 对已导入的模块进行了编辑并重新导入，但变动没有得以体现。这是为什么？12455260
Ref: faq/programming when-i-edit-an-imported-module-and-reimport-it-the-changes-don-t-show-up-why-does-this-happen12455489
Ref: 44b012455489
Node: 设计和历史常见问题12456797
Ref: faq/design doc12456964
Ref: 44b112456964
Ref: faq/design design-and-history-faq12456964
Ref: 44b212456964
Node: 为什么Python使用缩进来分组语句？12458900
Ref: faq/design why-does-python-use-indentation-for-grouping-of-statements12459072
Ref: 44b312459072
Node: 为什么简单的算术运算得到奇怪的结果？12460581
Ref: faq/design why-am-i-getting-strange-results-with-simple-arithmetic-operations12460799
Ref: 44b412460799
Node: 為何浮點數運算如此不精確?12460932
Ref: faq/design why-are-floating-point-calculations-so-inaccurate12461138
Ref: 44b512461138
Node: 為何Python字串為不可變動12462513
Ref: faq/design why-are-python-strings-immutable12462732
Ref: 44b612462732
Node: 为什么必须在方法定义和调用中显式使用“self”？12463241
Ref: faq/design why-must-self-be-used-explicitly-in-method-definitions-and-calls12463462
Ref: 44b712463462
Ref: faq/design why-self12463462
Ref: 449e12463462
Node: 为什么不能在表达式中赋值？12465535
Ref: faq/design id212465857
Ref: 44b812465857
Ref: faq/design why-can-t-i-use-an-assignment-in-an-expression12465857
Ref: 13ac12465857
Ref: 为什么不能在表达式中赋值？-Footnote-112466192
Node: 为什么Python对某些功能（例如list index ）使用方法来实现，而其他功能（例如len List ）使用函数实现？12466241
Ref: faq/design why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list12466568
Ref: 44b912466568
Node: 为什么 join 是一个字符串方法而不是列表或元组方法？12467739
Ref: faq/design why-is-join-a-string-method-instead-of-a-list-or-tuple-method12468045
Ref: 44ba12468045
Node: 异常有多快？12469708
Ref: faq/design how-fast-are-exceptions12469926
Ref: 44bb12469926
Node: 为什么Python中没有switch或case语句？12470710
Ref: faq/design why-isn-t-there-a-switch-or-case-statement-in-python12470955
Ref: 44bc12470955
Ref: 为什么Python中没有switch或case语句？-Footnote-112472209
Node: 难道不能在解释器中模拟线程，而非得依赖特定于操作系统的线程实现吗？12472258
Ref: faq/design can-t-you-emulate-threads-in-the-interpreter-instead-of-relying-on-an-os-specific-thread-implementation12472530
Ref: 44bd12472530
Ref: 难道不能在解释器中模拟线程，而非得依赖特定于操作系统的线程实现吗？-Footnote-112473069
Node: 為何lambda表示式不能包含在敘述內12473125
Ref: faq/design why-can-t-lambda-expressions-contain-statements12473419
Ref: 44be12473419
Node: Python可以被編譯成機器語言或C語言或其他種語言嗎?12474138
Ref: faq/design can-python-be-compiled-to-machine-code-c-or-some-other-language12474361
Ref: 44bf12474361
Ref: Python可以被編譯成機器語言或C語言或其他種語言嗎?-Footnote-112474758
Ref: Python可以被編譯成機器語言或C語言或其他種語言嗎?-Footnote-212474785
Ref: Python可以被編譯成機器語言或C語言或其他種語言嗎?-Footnote-312474816
Node: Python如何管理記憶體?12474851
Ref: faq/design how-does-python-manage-memory12475085
Ref: 44c012475085
Ref: Python如何管理記憶體?-Footnote-112476550
Ref: Python如何管理記憶體?-Footnote-212476580
Node: 為何CPython不使用更多傳統的垃圾回收機制?12476608
Ref: faq/design why-doesn-t-cpython-use-a-more-traditional-garbage-collection-scheme12476836
Ref: 44c112476836
Node: 當CPython結束時，為何所有的記憶體不會被釋放?12477576
Ref: faq/design why-isn-t-all-memory-freed-when-cpython-exits12477827
Ref: 44c212477827
Node: 为什么有单独的元组和列表数据类型？12478428
Ref: faq/design why-are-there-separate-tuple-and-list-data-types12478663
Ref: 44c312478663
Node: 列表是如何在CPython中实现的？12479729
Ref: faq/design how-are-lists-implemented-in-cpython12479942
Ref: 44c412479942
Node: 字典是如何在CPython中实现的？12480590
Ref: faq/design how-are-dictionaries-implemented-in-cpython12480794
Ref: 44c512480794
Node: 为什么字典key必须是不可变的？12481578
Ref: faq/design why-must-dictionary-keys-be-immutable12481789
Ref: 44c612481789
Node: 為何list sort 不是回傳排序過的串列?12485553
Ref: faq/design why-doesn-t-list-sort-return-the-sorted-list12485772
Ref: 44c712485772
Node: 如何在Python中指定和实施接口规范？12486526
Ref: faq/design how-do-you-specify-and-enforce-an-interface-spec-in-python12486726
Ref: 44c812486726
Node: 為何沒有goto語法?12488713
Ref: faq/design why-is-there-no-goto12488932
Ref: 44c912488932
Node: 为什么原始字符串（r-strings）不能以反斜杠结尾？12489939
Ref: faq/design why-can-t-raw-strings-r-strings-end-with-a-backslash12490165
Ref: 44ca12490165
Node: 为什么Python没有属性赋值的“with”语句？12491191
Ref: faq/design why-doesn-t-python-have-a-with-statement-for-attribute-assignments12491436
Ref: 44cb12491436
Node: 生成器为什么不支持 with 语句？12493326
Ref: faq/design why-don-t-generators-support-the-with-statement12493554
Ref: 44cc12493554
Node: 为什么 if/while/def/class语句需要冒号？12493929
Ref: faq/design why-are-colons-required-for-the-if-while-def-class-statements12494165
Ref: 44cd12494165
Node: 为什么Python在列表和元组的末尾允许使用逗号？12494795
Ref: faq/design why-does-python-allow-commas-at-the-end-of-lists-and-tuples12494980
Ref: 44ce12494980
Node: 函式庫和擴充功能的常見問題12495931
Ref: faq/library doc12496096
Ref: 44cf12496096
Ref: faq/library library-and-extension-faq12496096
Ref: 44d012496096
Node: 常見函式問題12496327
Ref: faq/library general-library-questions12496448
Ref: 44d112496448
Node: 如何找到可以用来做 XXX 的模块或应用？12496962
Ref: faq/library how-do-i-find-a-module-or-application-to-perform-task-x12497140
Ref: 44d212497140
Ref: 如何找到可以用来做 XXX 的模块或应用？-Footnote-112497626
Ref: 如何找到可以用来做 XXX 的模块或应用？-Footnote-212497651
Node: 哪裡可以找到math py socket py regex py 等 原始檔案12497682
Ref: faq/library where-is-the-math-py-socket-py-regex-py-etc-source-file12497910
Ref: 44d312497910
Node: 我如何使Python script 執行在Unix ?12498663
Ref: faq/library how-do-i-make-a-python-script-executable-on-unix12498876
Ref: 44d412498876
Node: Python 中有 curses/termcap 包吗？12500249
Ref: faq/library is-there-a-curses-termcap-package-for-python12500458
Ref: 44d512500458
Ref: Python 中有 curses/termcap 包吗？-Footnote-112501199
Ref: Python 中有 curses/termcap 包吗？-Footnote-212501258
Node: Python 中存在类似 C 的 onexit 函数的东西吗？12501307
Ref: faq/library is-there-an-equivalent-to-c-s-onexit-in-python12501523
Ref: 44d612501523
Node: 为什么我的信号处理函数不能工作？12501744
Ref: faq/library why-don-t-my-signal-handlers-work12501913
Ref: 44d712501913
Node: 一般性的工作12502233
Ref: faq/library common-tasks12502375
Ref: 44d812502375
Node: 我如何測試Python程式12502545
Ref: faq/library how-do-i-test-a-python-program-or-component12502671
Ref: 44d912502671
Node: 怎样用 docstring 创建文档？12504307
Ref: faq/library how-do-i-create-documentation-from-doc-strings12504478
Ref: 44da12504478
Ref: 怎样用 docstring 创建文档？-Footnote-112504802
Ref: 怎样用 docstring 创建文档？-Footnote-212504841
Node: 怎样一次只获取一个按键？12504871
Ref: faq/library how-do-i-get-a-single-keypress-at-a-time12505006
Ref: 44db12505006
Node: 线程相关12505213
Ref: faq/library threads12505349
Ref: 44dc12505349
Node: 程序中怎样使用线程？12505619
Ref: faq/library how-do-i-program-using-threads12505749
Ref: 44dd12505749
Node: 我的线程都没有运行，为什么？12506021
Ref: faq/library none-of-my-threads-seem-to-run-why12506205
Ref: 44de12506205
Node: 如何将任务分配给多个工作线程？12507705
Ref: faq/library how-do-i-parcel-out-work-among-a-bunch-of-worker-threads12507904
Ref: 44df12507904
Node: 怎样修改全局变量是线程安全的？12510384
Ref: faq/library what-kinds-of-global-value-mutation-are-thread-safe12510577
Ref: 44e012510577
Node: 不能删除全局解释器锁吗？12511920
Ref: faq/library can-t-we-get-rid-of-the-global-interpreter-lock12512059
Ref: 44e112512059
Ref: 不能删除全局解释器锁吗？-Footnote-112514323
Node: 输入输出12514383
Ref: faq/library input-and-output12514525
Ref: 44e212514525
Node: 怎样删除文件？（以及其他文件相关的问题……）12515063
Ref: faq/library how-do-i-delete-a-file-and-other-file-questions12515208
Ref: 44e312515208
Node: 怎样复制文件？12516462
Ref: faq/library how-do-i-copy-a-file12516661
Ref: 44e412516661
Node: 怎样读取（或写入）二进制数据？12516851
Ref: faq/library how-do-i-read-or-write-binary-data12517057
Ref: 44e512517057
Node: 似乎 os popen 创建的管道不能使用 os read ，这是为什么？12518253
Ref: faq/library i-can-t-seem-to-use-os-read-on-a-pipe-created-with-os-popen-why12518470
Ref: 44e612518470
Node: 怎样访问（RS232）串口？12519010
Ref: faq/library how-do-i-access-the-serial-rs232-port12519255
Ref: 44e712519255
Node: 为什么关闭 sys stdout（stdin，stderr）并不会真正关掉它？12519556
Ref: faq/library why-doesn-t-closing-sys-stdout-stdin-stderr-really-close-it12519719
Ref: 44e812519719
Node: 网络 / Internet 编程12520852
Ref: faq/library network-internet-programming12520991
Ref: 44e912520991
Node: Python 中的 WWW 工具是什么？12521347
Ref: faq/library what-www-tools-are-there-for-python12521502
Ref: 44ea12521502
Node: 怎样模拟发送 CGI 表单（METHOD=POST）？12522053
Ref: faq/library how-can-i-mimic-cgi-form-submission-method-post12522256
Ref: 44eb12522256
Node: 生成 HTML 需要使用什么模块？12523325
Ref: faq/library what-module-should-i-use-to-help-with-generating-html12523533
Ref: 44ec12523533
Ref: 生成 HTML 需要使用什么模块？-Footnote-112523728
Node: 怎样使用 Python 脚本发送邮件？12523780
Ref: faq/library how-do-i-send-mail-from-a-python-script12523985
Ref: 44ed12523985
Node: socket 的 connect 方法怎样避免阻塞？12525300
Ref: faq/library how-do-i-avoid-blocking-in-the-connect-method-of-a-socket12525457
Ref: 44ee12525457
Ref: socket 的 connect 方法怎样避免阻塞？-Footnote-112526627
Node: 数据库12526667
Ref: faq/library databases12526809
Ref: 44ef12526809
Node: Python 中有数据库包的接口吗？12526945
Ref: faq/library are-there-any-interfaces-to-database-packages-in-python12527084
Ref: 44f012527084
Ref: Python 中有数据库包的接口吗？-Footnote-112527545
Node: 在 Python 中如何实现持久化对象？12527602
Ref: faq/library how-do-you-implement-persistent-objects-in-python12527741
Ref: 44f112527741
Node: 数学和数字12528131
Ref: faq/library mathematics-and-numerics12528240
Ref: 44f212528240
Node: Python 中怎样生成随机数？12528331
Ref: faq/library how-do-i-generate-random-numbers-in-python12528417
Ref: 44f312528417
Node: 扩展/嵌入常见问题12529295
Ref: faq/extending doc12529464
Ref: 44f412529464
Ref: faq/extending extending-embedding-faq12529464
Ref: 44f512529464
Node: 可以使用 C 语言创建自己的函数吗？12530709
Ref: faq/extending can-i-create-my-own-functions-in-c12530878
Ref: 44f612530878
Node: 可以使用 C++ 语言创建自己的函数吗？12531208
Ref: faq/extending id212531423
Ref: 44f712531423
Node: C很难写，有没有其他选择？12531800
Ref: faq/extending c-wrapper-software12532011
Ref: 44f812532011
Ref: faq/extending writing-c-is-hard-are-there-any-alternatives12532011
Ref: 44f912532011
Ref: C很难写，有没有其他选择？-Footnote-112532609
Ref: C很难写，有没有其他选择？-Footnote-212532635
Ref: C很难写，有没有其他选择？-Footnote-312532702
Ref: C很难写，有没有其他选择？-Footnote-412532730
Ref: C很难写，有没有其他选择？-Footnote-512532788
Ref: C很难写，有没有其他选择？-Footnote-612532824
Ref: C很难写，有没有其他选择？-Footnote-712532880
Node: 如何在 C 中执行任意 Python 语句？12532919
Ref: faq/extending how-can-i-execute-arbitrary-python-statements-from-c12533130
Ref: 44fa12533130
Node: 如何在 C 中对任意 Python 表达式求值？12533655
Ref: faq/extending how-can-i-evaluate-an-arbitrary-python-expression-from-c12533869
Ref: 44fb12533869
Node: 如何从Python对象中提取C的值？12534158
Ref: faq/extending how-do-i-extract-c-values-from-a-python-object12534384
Ref: 44fc12534384
Node: 如何使用Py_BuildValue 创建任意长度的元组？12535590
Ref: faq/extending how-do-i-use-py-buildvalue-to-create-a-tuple-of-arbitrary-length12535800
Ref: 44fd12535800
Node: 如何从C调用对象的方法？12535975
Ref: faq/extending how-do-i-call-an-object-s-method-from-c12536229
Ref: 44fe12536229
Node: 如何捕获PyErr_Print （或打印到stdout / stderr的任何内容）的输出？12537401
Ref: faq/extending how-do-i-catch-the-output-from-pyerr-print-or-anything-that-prints-to-stdout-stderr12537642
Ref: 44ff12537642
Node: 如何从C访问用Python编写的模块？12538852
Ref: faq/extending how-do-i-access-a-module-written-in-python-from-c12539100
Ref: 450012539100
Node: 如何在 Python 中对接 C ++ 对象？12539901
Ref: faq/extending how-do-i-interface-to-c-objects-from-python12540134
Ref: 450112540134
Node: 我使用Setup文件添加了一个模块，为什么make失败了？12540646
Ref: faq/extending i-added-a-module-using-the-setup-file-and-the-make-fails-why12540857
Ref: 450212540857
Node: 如何调试扩展？12541209
Ref: faq/extending how-do-i-debug-an-extension12541466
Ref: 450312541466
Node: 我想在Linux系统上编译一个Python模块，但是缺少一些文件。为什么?12541980
Ref: faq/extending i-want-to-compile-a-python-module-on-my-linux-system-but-some-files-are-missing-why12542225
Ref: 450412542225
Node: 如何区分“输入不完整”和“输入无效”？12542667
Ref: faq/extending how-do-i-tell-incomplete-input-from-invalid-input12542957
Ref: 450512542957
Node: 如何找到未定义的g++符号__builtin_new或__pure_virtual？12548925
Ref: faq/extending how-do-i-find-undefined-g-symbols-builtin-new-or-pure-virtual12549252
Ref: 450612549252
Node: 能否创建一个对象类，其中部分方法在C中实现，而其他方法在Python中实现（例如通过继承）？12549613
Ref: faq/extending can-i-create-an-object-class-with-some-methods-implemented-in-c-and-others-in-python-e-g-through-inheritance12549874
Ref: 450712549874
Node: FAQ：在 Windows 使用 Python12550402
Ref: faq/windows doc12550571
Ref: 450812550571
Ref: faq/windows python-on-windows-faq12550571
Ref: 450912550571
Ref: faq/windows windows-faq12550571
Ref: 450a12550571
Node: 在 Windows 作業系統裡我想執行 Python 程式，要怎麼做？12551143
Ref: faq/windows faq-run-program-under-windows12551329
Ref: 450b12551329
Ref: faq/windows how-do-i-run-a-python-program-under-windows12551329
Ref: 450c12551329
Node: 我怎么让 Python 脚本可执行？12554508
Ref: faq/windows how-do-i-make-python-scripts-executable12554753
Ref: 450d12554753
Node: 为什么有时候 Python 程序会启动缓慢？12555278
Ref: faq/windows why-does-python-sometimes-take-so-long-to-start12555505
Ref: 450e12555505
Node: 我怎样使用 Python 脚本制作可执行文件？12556267
Ref: faq/windows how-do-i-make-an-executable-from-a-python-script12556494
Ref: 450f12556494
Node: * pyd 文件和 DLL 文件相同吗？12556748
Ref: faq/windows is-a-pyd-file-the-same-as-a-dll12556975
Ref: 451012556975
Node: 我怎样将 Python 嵌入一个 Windows 程序？12557919
Ref: faq/windows how-can-i-embed-python-into-a-windows-application12558160
Ref: 451112558160
Node: 如何让编辑器不要在我的 Python 源代码中插入 tab ？12562276
Ref: faq/windows how-do-i-keep-editors-from-inserting-tabs-into-my-python-source12562524
Ref: 451212562524
Ref: 如何让编辑器不要在我的 Python 源代码中插入 tab ？-Footnote-112563390
Node: 如何在不阻塞的情况下检查按键？12563439
Ref: faq/windows how-do-i-check-for-a-keypress-without-blocking12563628
Ref: 451312563628
Node: 圖形化使用者界面常見問答集12563969
Ref: faq/gui doc12564171
Ref: 451412564171
Ref: faq/gui graphic-user-interface-faq12564171
Ref: 451512564171
Node: 常見圖形化使用者界面 GUI 問題12564413
Ref: faq/gui general-gui-questions12564572
Ref: 451612564572
Node: Python 有哪些 GUI 工具包？12564661
Ref: faq/gui what-gui-toolkits-exist-for-python12564851
Ref: 451712564851
Ref: Python 有哪些 GUI 工具包？-Footnote-112565506
Ref: Python 有哪些 GUI 工具包？-Footnote-212565548
Ref: Python 有哪些 GUI 工具包？-Footnote-312565575
Ref: Python 有哪些 GUI 工具包？-Footnote-412565654
Node: 有关Tkinter的问题12565736
Ref: faq/gui tkinter-questions12565876
Ref: 451812565876
Node: 我怎样“冻结”Tkinter程序？12566091
Ref: faq/gui how-do-i-freeze-tkinter-applications12566247
Ref: 451912566247
Node: 在等待 I/O 操作时能够处理 Tk 事件吗？12567164
Ref: faq/gui can-i-have-tk-events-handled-while-waiting-for-i-o12567375
Ref: 451a12567375
Node: 在Tkinter中键绑定不工作：为什么？12567856
Ref: faq/gui i-can-t-get-key-bindings-to-work-in-tkinter-why12568021
Ref: 451b12568021
Node: 為什麼Python被安裝在我的機器上?常見問答集12568532
Ref: faq/installed doc12568694
Ref: 451c12568694
Ref: faq/installed why-is-python-installed-on-my-computer-faq12568694
Ref: 451d12568694
Node: 什麼是Python?<2>12568941
Ref: faq/installed what-is-python12569107
Ref: 451e12569107
Node: 為什麼Python被安裝在我的機器上?12569623
Ref: faq/installed why-is-python-installed-on-my-machine12569829
Ref: 451f12569829
Node: 我能夠自行刪除Python嗎?12570746
Ref: faq/installed can-i-delete-python12570924
Ref: 452012570924
Node: 術語表12571655
Ref: glossary doc12571765
Ref: 452112571765
Ref: glossary glossary12571765
Ref: 133412571765
Ref: glossary id112571765
Ref: 452212571765
Ref: glossary term-012571789
Ref: 134d12571789
Ref: glossary term-112571931
Ref: 134e12571931
Ref: glossary term-2to312572334
Ref: 115a12572334
Ref: glossary term-abstract-base-class12572818
Ref: c0512572818
Ref: glossary term-annotation12573749
Ref: 158712573749
Ref: glossary term-argument12574322
Ref: 165b12574322
Ref: glossary term-asynchronous-context-manager12575732
Ref: 73412575732
Ref: glossary term-asynchronous-generator12576022
Ref: 164012576022
Ref: glossary term-asynchronous-generator-iterator12576845
Ref: 37d712576845
Ref: glossary term-asynchronous-iterable12577682
Ref: 73312577682
Ref: glossary term-asynchronous-iterator12577970
Ref: 73812577970
Ref: glossary term-attribute12578406
Ref: 1a4a12578406
Ref: glossary term-awaitable12578649
Ref: 61212578649
Ref: glossary term-bdfl12578905
Ref: 452512578905
Ref: glossary term-binary-file12579033
Ref: 1e0112579033
Ref: glossary term-bytes-like-object12579603
Ref: 6df12579603
Ref: glossary term-bytecode12580581
Ref: 70912580581
Ref: glossary term-callback12581396
Ref: 26f112581396
Ref: glossary term-class12581535
Ref: fe812581535
Ref: glossary term-class-variable12581725
Ref: 452612581725
Ref: glossary term-coercion12581895
Ref: 452712581895
Ref: glossary term-complex-number12582595
Ref: 452812582595
Ref: glossary term-context-manager12583336
Ref: 66112583336
Ref: glossary term-context-variable12583584
Ref: 452912583584
Ref: glossary term-contiguous12584092
Ref: 17ec12584092
Ref: glossary term-coroutine12584701
Ref: 18a12584701
Ref: glossary term-coroutine-function12585043
Ref: 73212585043
Ref: glossary term-cpython12585377
Ref: 156912585377
Ref: glossary term-decorator12585627
Ref: 17412585627
Ref: glossary term-descriptor12586324
Ref: 157912586324
Ref: glossary term-dictionary12587185
Ref: 452a12587185
Ref: glossary term-dictionary-comprehension12587437
Ref: 452b12587437
Ref: glossary term-dictionary-view12587821
Ref: 1a9e12587821
Ref: glossary term-docstring12588261
Ref: 16eb12588261
Ref: glossary term-duck-typing12588667
Ref: 452312588667
Ref: glossary term-eafp12589485
Ref: 20a912589485
Ref: glossary term-expression12589946
Ref: 158f12589946
Ref: glossary term-extension-module12590463
Ref: 452d12590463
Ref: glossary term-f-string12590625
Ref: 29512590625
Ref: glossary term-file-object12590826
Ref: c1412590826
Ref: glossary term-file-like-object12591638
Ref: 1dc612591638
Ref: glossary term-finder12591740
Ref: 15f512591740
Ref: glossary term-floor-division12592220
Ref: 1f912592220
Ref: glossary term-function12592642
Ref: 165c12592642
Ref: glossary term-function-annotation12592983
Ref: 139112592983
Ref: glossary term-future12593545
Ref: 77612593545
Ref: glossary term-garbage-collection12594196
Ref: fc812594196
Ref: glossary term-generator12594586
Ref: a8312594586
Ref: glossary term-generator-iterator12595168
Ref: 55812595168
Ref: glossary term-generator-expression12595588
Ref: 452e12595588
Ref: glossary term-generic-function12596004
Ref: 2fc12596004
Ref: glossary term-generic-type12596393
Ref: fea12596393
Ref: glossary term-gil12596774
Ref: 20e12596774
Ref: glossary term-global-interpreter-lock12596858
Ref: 5ff12596858
Ref: glossary term-hash-based-pyc12598065
Ref: 452f12598065
Ref: glossary term-hashable12598305
Ref: 27612598305
Ref: glossary term-idle12599416
Ref: 453012599416
Ref: glossary term-immutable12599618
Ref: 135612599618
Ref: glossary term-import-path12599994
Ref: 15f812599994
Ref: glossary term-importing12600419
Ref: 15e812600419
Ref: glossary term-importer12600579
Ref: 15f712600579
Ref: glossary term-interactive12600756
Ref: 453112600756
Ref: glossary term-interpreted12601166
Ref: 453212601166
Ref: glossary term-interpreter-shutdown12601655
Ref: 85212601655
Ref: glossary term-iterable12602388
Ref: c7c12602388
Ref: glossary term-iterator12603678
Ref: 117112603678
Ref: glossary term-key-function12604921
Ref: 7d212604921
Ref: glossary term-keyword-argument12606140
Ref: 6bb12606140
Ref: glossary term-lambda12606232
Ref: 1ca812606232
Ref: glossary term-lbyl12606468
Ref: 452c12606468
Ref: glossary term-list12607171
Ref: 453312607171
Ref: glossary term-list-comprehension12607447
Ref: 453412607447
Ref: glossary term-loader12607927
Ref: 15f612607927
Ref: glossary term-magic-method12608294
Ref: 453512608294
Ref: glossary term-mapping12608408
Ref: c0b12608408
Ref: glossary term-meta-path-finder12608801
Ref: a9112608801
Ref: glossary term-metaclass12609159
Ref: 159012609159
Ref: glossary term-method12609922
Ref: 452412609922
Ref: glossary term-method-resolution-order12610302
Ref: 173912610302
Ref: glossary term-module12610596
Ref: 15e712610596
Ref: glossary term-module-spec12610906
Ref: 37db12610906
Ref: glossary term-mro12611092
Ref: 29c712611092
Ref: glossary term-mutable12611177
Ref: 135e12611177
Ref: glossary term-named-tuple12611352
Ref: b7b12611352
Ref: glossary term-namespace12612584
Ref: 453612612584
Ref: glossary term-namespace-package12613323
Ref: 15ee12613323
Ref: glossary term-nested-scope12613749
Ref: 172112613749
Ref: glossary term-new-style-class12614283
Ref: 1e0912614283
Ref: glossary term-object12614705
Ref: 453712614705
Ref: glossary term-package12614927
Ref: 15eb12614927
Ref: glossary term-parameter12615310
Ref: 166412615310
Ref: glossary positional-only-parameter12615901
Ref: 3c912615901
Ref: glossary keyword-only-parameter12616261
Ref: 3ce12616261
Ref: glossary term-path-entry12617686
Ref: 160b12617686
Ref: glossary term-path-entry-finder12617915
Ref: a9212617915
Ref: glossary term-path-entry-hook12618312
Ref: 160d12618312
Ref: glossary term-path-based-finder12618596
Ref: 15fb12618596
Ref: glossary term-path-like-object12618784
Ref: 47212618784
Ref: glossary term-pep12619393
Ref: 453812619393
Ref: glossary term-portion12620004
Ref: 15f012620004
Ref: glossary term-positional-argument12620233
Ref: 6bc12620233
Ref: glossary term-provisional-api12620325
Ref: 45412620325
Ref: glossary term-provisional-package12621250
Ref: a6112621250
Ref: glossary term-python-300012621352
Ref: 453912621352
Ref: glossary term-pythonic12621519
Ref: 453a12621519
Ref: glossary term-qualified-name12622200
Ref: 155c12622200
Ref: glossary term-reference-count12623076
Ref: 3d5112623076
Ref: glossary term-regular-package12623533
Ref: 15ed12623533
Ref: glossary term-slots12623763
Ref: 393d12623763
Ref: glossary term-sequence12624123
Ref: 135c12624123
Ref: glossary term-set-comprehension12625202
Ref: 453b12625202
Ref: glossary term-single-dispatch12625562
Ref: 2fb12625562
Ref: glossary term-slice12625737
Ref: 173612625737
Ref: glossary term-special-method12626133
Ref: 380612626133
Ref: glossary term-statement12626421
Ref: 1cef12626421
Ref: glossary term-text-encoding12626733
Ref: 173112626733
Ref: glossary term-text-file12626841
Ref: 13d912626841
Ref: glossary term-triple-quoted-string12627526
Ref: 453c12627526
Ref: glossary term-type12628028
Ref: fe912628028
Ref: glossary term-type-alias12628277
Ref: 453d12628277
Ref: glossary term-type-hint12628892
Ref: 158b12628892
Ref: glossary term-universal-newlines12629517
Ref: 6eb12629517
Ref: glossary term-variable-annotation12629889
Ref: 71212629889
Ref: glossary term-virtual-environment12630525
Ref: 144612630525
Ref: glossary term-virtual-machine12630858
Ref: 28d012630858
Ref: glossary term-zen-of-python12631067
Ref: 453e12631067
Ref: 術語表-Footnote-112631329
Ref: 術語表-Footnote-212631378
Ref: 術語表-Footnote-312631427
Ref: 術語表-Footnote-412631476
Ref: 術語表-Footnote-512631525
Ref: 術語表-Footnote-612631574
Ref: 術語表-Footnote-712631623
Ref: 術語表-Footnote-812631672
Ref: 術語表-Footnote-912631721
Ref: 術語表-Footnote-1012631770
Ref: 術語表-Footnote-1112631809
Ref: 術語表-Footnote-1212631859
Ref: 術語表-Footnote-1312631909
Ref: 術語表-Footnote-1412631959
Ref: 術語表-Footnote-1512631991
Ref: 術語表-Footnote-1612632041
Ref: 術語表-Footnote-1712632091
Ref: 術語表-Footnote-1812632141
Ref: 術語表-Footnote-1912632191
Ref: 術語表-Footnote-2012632241
Ref: 術語表-Footnote-2112632291
Ref: 術語表-Footnote-2212632341
Ref: 術語表-Footnote-2312632391
Ref: 術語表-Footnote-2412632441
Ref: 術語表-Footnote-2512632491
Ref: 術語表-Footnote-2612632541
Ref: 術語表-Footnote-2712632600
Ref: 術語表-Footnote-2812632650
Ref: 術語表-Footnote-2912632700
Ref: 術語表-Footnote-3012632750
Ref: 術語表-Footnote-3112632800
Ref: 術語表-Footnote-3212632850
Ref: 術語表-Footnote-3312632900
Ref: 術語表-Footnote-3412632950
Ref: 術語表-Footnote-3512633000
Ref: 術語表-Footnote-3612633050
Ref: 術語表-Footnote-3712633100
Ref: 術語表-Footnote-3812633150
Ref: 術語表-Footnote-3912633200
Node: 關於這些說明文件12633250
Ref: about doc12633357
Ref: 453f12633357
Ref: about about-these-documents12633357
Ref: 454012633357
Ref: 關於這些說明文件-Footnote-112634212
Ref: 關於這些說明文件-Footnote-212634243
Ref: 關於這些說明文件-Footnote-312634292
Ref: 關於這些說明文件-Footnote-412634333
Node: Python 文件的貢獻者們12634374
Ref: about contributors-to-the-python-documentation12634463
Ref: 454112634463
Ref: Python 文件的貢獻者們-Footnote-112634867
Node: 處理錯誤 Bug12634928
Ref: bugs doc12635038
Ref: 454212635038
Ref: bugs dealing-with-bugs12635038
Ref: 454312635038
Ref: bugs reporting-bugs12635038
Ref: 3daf12635038
Node: 說明文件的錯誤12635537
Ref: bugs documentation-bugs12635652
Ref: 454512635652
Ref: 說明文件的錯誤-Footnote-112636704
Ref: 說明文件的錯誤-Footnote-212636849
Ref: 說明文件的錯誤-Footnote-312636894
Node: 使用 Python 問題追蹤系統12636970
Ref: bugs using-the-python-issue-tracker12637122
Ref: 454712637122
Ref: bugs using-the-tracker12637122
Ref: 454612637122
Ref: 使用 Python 問題追蹤系統-Footnote-112639577
Ref: 使用 Python 問題追蹤系統-Footnote-212639640
Node: 開始讓自己貢獻 Python12639706
Ref: bugs contributing-to-python12639828
Ref: 454412639828
Ref: bugs getting-started-contributing-to-python-yourself12639828
Ref: 454812639828
Ref: 開始讓自己貢獻 Python-Footnote-112640304
Ref: 開始讓自己貢獻 Python-Footnote-212640341
Node: 版權宣告12640417
Ref: copyright doc12640518
Ref: 454912640518
Ref: copyright copyright12640518
Ref: 454a12640518
Ref: copyright core-mentorship-mailing-list12640518
Ref: 454b12640518
Node: 沿革與授權12641022
Ref: license doc12641139
Ref: 454d12641139
Ref: license history-and-license12641139
Ref: 454c12641139
Ref: license id112641139
Ref: 454e12641139
Node: 軟體沿革12641302
Ref: license history-of-the-software12641434
Ref: 454f12641434
Node: 關於存取或以其他方式使用 Python 的合約條款12645891
Ref: license terms-and-conditions-for-accessing-or-otherwise-using-python12646065
Ref: 455012646065
Node: 用於 PYTHON 3 9 9 的 PSF 授權合約12647195
Ref: license psf-license12647385
Ref: 455112647385
Ref: license psf-license-agreement-for-python-release12647385
Ref: 455412647385
Node: 用於 PYTHON 2 0 的 BEOPEN COM 授權合約12650051
Ref: license beopen-com-license-agreement-for-python-2-012650291
Ref: 455512650291
Node: 用於 PYTHON 1 6 1 的 CNRI 授權合約12652984
Ref: license cnri-license-agreement-for-python-1-6-112653232
Ref: 455612653232
Node: 用於 PYTHON 0 9 0 至 1 2 的 CWI 授權合約12657407
Ref: license cwi-license-agreement-for-python-0-9-0-through-1-212657680
Ref: 455712657680
Node: 用於 PYTHON 3 9 9 說明文件內程式碼的 ZERO-CLAUSE BSD 授權12658938
Ref: license bsd012659161
Ref: 455212659161
Ref: license zero-clause-bsd-license-for-code-in-the-python-release-documentation12659161
Ref: 455812659161
Node: 被收錄軟體的授權與致謝12659958
Ref: license licenses-and-acknowledgements-for-incorporated-software12660111
Ref: 455912660111
Ref: license otherlicenses12660111
Ref: 455312660111
Node: Mersenne Twister12660647
Ref: license mersenne-twister12660749
Ref: 455a12660749
Node: Sockets12663009
Ref: license sockets12663143
Ref: 455b12663143
Node: 非同步 socket 服務12664974
Ref: license asynchronous-socket-services12665105
Ref: 455c12665105
Node: Cookie 管理12666296
Ref: license cookie-management12666432
Ref: 455d12666432
Node: 執行追蹤12667625
Ref: license execution-tracing12667766
Ref: 455e12667766
Node: UUencode 與 UUdecode 函式12668998
Ref: license uuencode-and-uudecode-functions12669148
Ref: 455f12669148
Node: XML 遠端程序呼叫12670707
Ref: license xml-remote-procedure-calls12670855
Ref: 456012670855
Node: test_epoll12672352
Ref: license test-epoll12672485
Ref: 456112672485
Node: Select kqueue12673731
Ref: license select-kqueue12673851
Ref: 456212673851
Node: SipHash2412675386
Ref: license siphash2412675511
Ref: 456312675511
Node: strtod 與 dtoa12676680
Ref: license strtod-and-dtoa12676799
Ref: 456412676799
Node: OpenSSL12678136
Ref: license openssl12678251
Ref: 456512678251
Node: expat12685792
Ref: license expat12685898
Ref: 456612685898
Node: libffi12687308
Ref: license libffi12687414
Ref: 456712687414
Node: zlib<3>12688767
Ref: license zlib12688875
Ref: 456812688875
Node: cfuhash12690115
Ref: license cfuhash12690225
Ref: 456912690225
Node: libmpdec12692036
Ref: license libmpdec12692160
Ref: 456a12692160
Node: W3C C14N 測試套件12693737
Ref: license w3c-c14n-test-suite12693845
Ref: 456b12693845
Node: 發布 Python 模組（舊版）12695733
Ref: distutils/index doc12695870
Ref: 456c12695870
Ref: distutils/index distributing-python-modules-legacy-version12695870
Ref: 456d12695870
Ref: distutils/index distutils-index12695870
Ref: 8e512695870
Ref: 發布 Python 模組（舊版）-Footnote-112697131
Node: Distutils 模块介绍12697197
Ref: distutils/introduction doc12697315
Ref: 456e12697315
Ref: distutils/introduction an-introduction-to-distutils12697315
Ref: 456f12697315
Ref: distutils/introduction distutils-intro12697315
Ref: 457012697315
Node: 概念和术语12698020
Ref: distutils/introduction concepts-terminology12698127
Ref: 457112698127
Ref: distutils/introduction distutils-concepts12698127
Ref: 457212698127
Node: 一个简单的例子<3>12699149
Ref: distutils/introduction a-simple-example12699288
Ref: 457312699288
Ref: distutils/introduction distutils-simple-example12699288
Ref: 457412699288
Node: 通用的 Python 术语12702780
Ref: distutils/introduction general-python-terminology12702929
Ref: 457612702929
Ref: distutils/introduction python-terms12702929
Ref: 457712702929
Node: Distutils 特定的术语12704584
Ref: distutils/introduction distutils-specific-terminology12704700
Ref: 457812704700
Ref: distutils/introduction distutils-term12704700
Ref: 457912704700
Node: 编写安装脚本12705612
Ref: distutils/setupscript doc12705772
Ref: 457a12705772
Ref: distutils/setupscript setup-script12705772
Ref: 457512705772
Ref: distutils/setupscript writing-the-setup-script12705772
Ref: 457b12705772
Node: Listing whole packages12709118
Ref: distutils/setupscript listing-packages12709230
Ref: 457d12709230
Ref: distutils/setupscript listing-whole-packages12709230
Ref: 457e12709230
Node: Listing individual modules12711686
Ref: distutils/setupscript listing-individual-modules12711835
Ref: 457f12711835
Ref: distutils/setupscript listing-modules12711835
Ref: 458012711835
Node: Describing extension modules12712641
Ref: distutils/setupscript describing-extension-modules12712816
Ref: 458112712816
Ref: distutils/setupscript describing-extensions12712816
Ref: 458212712816
Node: 扩展名和软件包12714563
Ref: distutils/setupscript extension-names-and-packages12714680
Ref: 458412714680
Node: Extension source files12715758
Ref: distutils/setupscript extension-source-files12715904
Ref: 458512715904
Node: Preprocessor options12717300
Ref: distutils/setupscript preprocessor-options12717440
Ref: 458612717440
Node: Library options12720453
Ref: distutils/setupscript library-options12720586
Ref: 458712720586
Node: 其他选项<2>12721564
Ref: distutils/setupscript other-options12721668
Ref: 458812721668
Node: Relationships between Distributions and Packages12722817
Ref: distutils/setupscript relationships-between-distributions-and-packages12722984
Ref: 458912722984
Node: Installing Scripts12726352
Ref: distutils/setupscript distutils-installing-scripts12726514
Ref: 458a12726514
Ref: distutils/setupscript installing-scripts12726514
Ref: 458b12726514
Node: Installing Package Data12727608
Ref: distutils/setupscript distutils-installing-package-data12727749
Ref: 458c12727749
Ref: distutils/setupscript installing-package-data12727749
Ref: 458d12727749
Node: Installing Additional Files12729447
Ref: distutils/setupscript distutils-additional-files12729590
Ref: 458e12729590
Ref: distutils/setupscript installing-additional-files12729590
Ref: 458f12729590
Node: Additional meta-data12731470
Ref: distutils/setupscript additional-meta-data12731616
Ref: 459012731616
Ref: distutils/setupscript meta-data12731616
Ref: 457c12731616
Ref: Additional meta-data-Footnote-112738943
Node: Debugging the setup script12738980
Ref: distutils/setupscript debug-setup-script12739090
Ref: 459112739090
Ref: distutils/setupscript debugging-the-setup-script12739090
Ref: 459212739090
Node: 编写设置脚本的配置文件12740165
Ref: distutils/configfile doc12740333
Ref: 459312740333
Ref: distutils/configfile setup-config12740333
Ref: 459412740333
Ref: distutils/configfile writing-the-setup-configuration-file12740333
Ref: 459512740333
Ref: distutils/configfile distutils-build-ext-inplace12743241
Ref: 459612743241
Ref: 编写设置脚本的配置文件-Footnote-112745476
Node: Creating a Source Distribution12745575
Ref: distutils/sourcedist doc12745743
Ref: 459812745743
Ref: distutils/sourcedist creating-a-source-distribution12745743
Ref: 459912745743
Ref: distutils/sourcedist source-dist12745743
Ref: 459a12745743
Ref: Creating a Source Distribution-Footnote-112748790
Ref: Creating a Source Distribution-Footnote-212748840
Node: Specifying the files to distribute12748865
Ref: distutils/sourcedist manifest12748999
Ref: 3d9312748999
Ref: distutils/sourcedist specifying-the-files-to-distribute12748999
Ref: 459b12748999
Node: Manifest-related options12754914
Ref: distutils/sourcedist manifest-options12755048
Ref: 459d12755048
Ref: distutils/sourcedist manifest-related-options12755048
Ref: 459e12755048
Node: 创建构建分布12756143
Ref: distutils/builtdist doc12756294
Ref: 459f12756294
Ref: distutils/builtdist built-dist12756294
Ref: 45a012756294
Ref: distutils/builtdist creating-built-distributions12756294
Ref: 45a112756294
Node: 创建RPM软件包12763841
Ref: distutils/builtdist creating-rpm-packages12763950
Ref: 45a212763950
Ref: distutils/builtdist creating-rpms12763950
Ref: 45a312763950
Node: Creating Windows Installers12771565
Ref: distutils/builtdist creating-windows-installers12771709
Ref: 45a412771709
Ref: distutils/builtdist creating-wininst12771709
Ref: 45a512771709
Node: Cross-compiling on Windows12773990
Ref: distutils/builtdist cross-compile-windows12774145
Ref: 45a612774145
Ref: distutils/builtdist cross-compiling-on-windows12774145
Ref: 45a712774145
Node: The Postinstallation script12775827
Ref: distutils/builtdist postinstallation-script12775917
Ref: 45a812775917
Ref: distutils/builtdist the-postinstallation-script12775917
Ref: 45a912775917
Ref: distutils/builtdist directory_created12776822
Ref: 45aa12776822
Ref: distutils/builtdist file_created12776859
Ref: 45ab12776859
Ref: distutils/builtdist get_special_folder_path12777208
Ref: 45ac12777208
Ref: distutils/builtdist create_shortcut12778100
Ref: 45ad12778100
Node: Vista User Access Control UAC12778815
Ref: distutils/builtdist vista-user-access-control-uac12778934
Ref: 45ae12778934
Node: Distutils 示例12779447
Ref: distutils/examples doc12779584
Ref: 45af12779584
Ref: distutils/examples distutils-examples12779584
Ref: 45b012779584
Ref: distutils/examples id112779584
Ref: 45b112779584
Ref: Distutils 示例-Footnote-112780291
Node: 纯 Python 分发（通过 module）12780347
Ref: distutils/examples pure-mod12780478
Ref: 45b212780478
Ref: distutils/examples pure-python-distribution-by-module12780478
Ref: 45b312780478
Node: 纯 Python 分发（通过 包）12782006
Ref: distutils/examples pure-pkg12782164
Ref: 45b412782164
Ref: distutils/examples pure-python-distribution-by-package12782164
Ref: 45b512782164
Node: 单个扩展模块12785620
Ref: distutils/examples single-ext12785757
Ref: 45b612785757
Ref: distutils/examples single-extension-module12785757
Ref: 45b712785757
Node: 检查一个包12786745
Ref: distutils/examples checking-a-package12786864
Ref: 45b812786864
Ref: 检查一个包-Footnote-112788411
Node: 读取元数据12788451
Ref: distutils/examples reading-the-metadata12788543
Ref: 45b912788543
Node: 扩展 Distutils12790032
Ref: distutils/extending doc12790163
Ref: 45ba12790163
Ref: distutils/extending docutils12790163
Ref: 45bb12790163
Ref: distutils/extending extending-distutils12790163
Ref: 14ca12790163
Ref: distutils/extending id112790163
Ref: 45bc12790163
Node: 集成新的命令12791270
Ref: distutils/extending integrating-new-commands12791374
Ref: 45be12791374
Node: 添加新的发布类型12793894
Ref: distutils/extending adding-new-distribution-types12793998
Ref: 45bf12793998
Node: 指令參照12794422
Ref: distutils/commandref doc12794546
Ref: 45c012794546
Ref: distutils/commandref command-reference12794546
Ref: 45c112794546
Ref: distutils/commandref reference12794546
Ref: 45c212794546
Node: 安装模块 install 命令族12794949
Ref: distutils/commandref install-cmd12795071
Ref: 45c312795071
Ref: distutils/commandref installing-modules-the-install-command-family12795071
Ref: 45c412795071
Node: install_data12795339
Ref: distutils/commandref install-data12795442
Ref: 45c512795442
Ref: distutils/commandref install-data-cmd12795442
Ref: 45c612795442
Node: install_scripts12795563
Ref: distutils/commandref install-scripts12795666
Ref: 45c712795666
Ref: distutils/commandref install-scripts-cmd12795666
Ref: 45c812795666
Node: 创建源码发行包 sdist 命令12795787
Ref: distutils/commandref creating-a-source-distribution-the-sdist-command12795909
Ref: 45c912795909
Ref: distutils/commandref sdist-cmd12795909
Ref: 459c12795909
Node: API參照12798268
Ref: distutils/apiref doc12798367
Ref: 45ca12798367
Ref: distutils/apiref api-reference12798367
Ref: 45cb12798367
Ref: distutils/apiref id112798367
Ref: 45cc12798367
Ref: API參照-Footnote-112804063
Node: distutils core --- 分发包功能的核心12804163
Ref: distutils/apiref distutils-core-core-distutils-functionality12804300
Ref: 45cd12804300
Ref: distutils/apiref module-distutils core12804300
Ref: 5312804300
Ref: distutils/apiref distutils core setup12804662
Ref: 3d9012804662
Ref: distutils/apiref distutils core run_setup12811429
Ref: 45d012811429
Ref: distutils/apiref distutils core Extension12813843
Ref: 458312813843
Ref: distutils/apiref distutils core Distribution12821079
Ref: 45ce12821079
Ref: distutils/apiref distutils core Command12821588
Ref: 45cf12821588
Ref: distutils core --- 分发包功能的核心-Footnote-112821788
Ref: distutils core --- 分发包功能的核心-Footnote-212821825
Node: distutils ccompiler --- CCompiler基类12821874
Ref: distutils/apiref distutils-ccompiler-ccompiler-base-class12822063
Ref: 45d112822063
Ref: distutils/apiref module-distutils ccompiler12822063
Ref: 3b12822063
Ref: distutils/apiref distutils ccompiler gen_lib_options12822544
Ref: 45d312822544
Ref: distutils/apiref distutils ccompiler gen_preprocess_options12823028
Ref: 45d412823028
Ref: distutils/apiref distutils ccompiler get_default_compiler12823692
Ref: 45d512823692
Ref: distutils/apiref distutils ccompiler new_compiler12824149
Ref: 45d612824149
Ref: distutils/apiref distutils ccompiler show_compilers12824943
Ref: 45d712824943
Ref: distutils/apiref distutils ccompiler CCompiler12825134
Ref: 45d212825134
Ref: distutils/apiref distutils ccompiler CCompiler add_include_dir12826572
Ref: 45d812826572
Ref: distutils/apiref distutils ccompiler CCompiler set_include_dirs12826880
Ref: 45d912826880
Ref: distutils/apiref distutils ccompiler CCompiler add_library12827359
Ref: 45da12827359
Ref: distutils/apiref distutils ccompiler CCompiler set_libraries12828152
Ref: 45db12828152
Ref: distutils/apiref distutils ccompiler CCompiler add_library_dir12828453
Ref: 45dc12828453
Ref: distutils/apiref distutils ccompiler CCompiler set_library_dirs12828865
Ref: 45dd12828865
Ref: distutils/apiref distutils ccompiler CCompiler add_runtime_library_dir12829112
Ref: 45de12829112
Ref: distutils/apiref distutils ccompiler CCompiler set_runtime_library_dirs12829279
Ref: 45df12829279
Ref: distutils/apiref distutils ccompiler CCompiler define_macro12829571
Ref: 45e012829571
Ref: distutils/apiref distutils ccompiler CCompiler undefine_macro12829945
Ref: 45e112829945
Ref: distutils/apiref distutils ccompiler CCompiler add_link_object12830474
Ref: 45e212830474
Ref: distutils/apiref distutils ccompiler CCompiler set_link_objects12830759
Ref: 45e312830759
Ref: distutils/apiref distutils ccompiler CCompiler detect_language12831208
Ref: 45e412831208
Ref: distutils/apiref distutils ccompiler CCompiler find_library_file12831458
Ref: 45e512831458
Ref: distutils/apiref distutils ccompiler CCompiler has_function12831873
Ref: 45e612831873
Ref: distutils/apiref distutils ccompiler CCompiler library_dir_option12832281
Ref: 45e712832281
Ref: distutils/apiref distutils ccompiler CCompiler library_option12832442
Ref: 45e812832442
Ref: distutils/apiref distutils ccompiler CCompiler runtime_library_dir_option12832619
Ref: 45e912832619
Ref: distutils/apiref distutils ccompiler CCompiler set_executables12832796
Ref: 45ea12832796
Ref: distutils/apiref distutils ccompiler CCompiler compile12834260
Ref: 45ec12834260
Ref: distutils/apiref distutils ccompiler CCompiler create_static_lib12837048
Ref: 45ed12837048
Ref: distutils/apiref distutils ccompiler CCompiler link12838334
Ref: 45ee12838334
Ref: distutils/apiref distutils ccompiler CCompiler link_executable12840996
Ref: 45ef12840996
Ref: distutils/apiref distutils ccompiler CCompiler link_shared_lib12841492
Ref: 45f012841492
Ref: distutils/apiref distutils ccompiler CCompiler link_shared_object12842040
Ref: 45f112842040
Ref: distutils/apiref distutils ccompiler CCompiler preprocess12842612
Ref: 45f212842612
Ref: distutils/apiref distutils ccompiler CCompiler executable_filename12843505
Ref: 45f312843505
Ref: distutils/apiref distutils ccompiler CCompiler library_filename12843815
Ref: 45f412843815
Ref: distutils/apiref distutils ccompiler CCompiler object_filenames12844226
Ref: 45f512844226
Ref: distutils/apiref distutils ccompiler CCompiler shared_object_filename12844468
Ref: 45f612844468
Ref: distutils/apiref distutils ccompiler CCompiler execute12844669
Ref: 45f712844669
Ref: distutils/apiref distutils ccompiler CCompiler spawn12844959
Ref: 45f912844959
Ref: distutils/apiref distutils ccompiler CCompiler mkpath12845114
Ref: 45fa12845114
Ref: distutils/apiref distutils ccompiler CCompiler move_file12845298
Ref: 45fc12845298
Ref: distutils/apiref distutils ccompiler CCompiler announce12845442
Ref: 45fe12845442
Ref: distutils/apiref distutils ccompiler CCompiler warn12845554
Ref: 45ff12845554
Ref: distutils/apiref distutils ccompiler CCompiler debug_print12845649
Ref: 460012845649
Node: distutils unixccompiler --- Unix C Compiler12845844
Ref: distutils/apiref distutils-unixccompiler-unix-c-compiler12846035
Ref: 460112846035
Ref: distutils/apiref module-distutils unixccompiler12846035
Ref: 6312846035
Node: distutils msvccompiler --- Microsoft Compiler12846802
Ref: distutils/apiref distutils-msvccompiler-microsoft-compiler12846997
Ref: 460212846997
Ref: distutils/apiref module-distutils msvccompiler12846997
Ref: 5f12846997
Node: distutils bcppcompiler --- Borland Compiler12847985
Ref: distutils/apiref distutils-bcppcompiler-borland-compiler12848181
Ref: 460312848181
Ref: distutils/apiref module-distutils bcppcompiler12848181
Ref: 3a12848181
Node: distutils cygwincompiler --- Cygwin Compiler12848415
Ref: distutils/apiref distutils-cygwincompiler-cygwin-compiler12848612
Ref: 460412848612
Ref: distutils/apiref module-distutils cygwinccompiler12848612
Ref: 5412848612
Node: distutils archive_util --- Archiving utilities12848994
Ref: distutils/apiref distutils-archive-util-archiving-utilities12849190
Ref: 460512849190
Ref: distutils/apiref module-distutils archive_util12849190
Ref: 3912849190
Ref: distutils/apiref distutils archive_util make_archive12849401
Ref: 460612849401
Ref: distutils/apiref distutils archive_util make_tarball12850301
Ref: 460712850301
Ref: distutils/apiref distutils archive_util make_zipfile12851078
Ref: 460812851078
Node: distutils dep_util --- Dependency checking12851590
Ref: distutils/apiref distutils-dep-util-dependency-checking12851790
Ref: 460912851790
Ref: distutils/apiref module-distutils dep_util12851790
Ref: 5612851790
Ref: distutils/apiref distutils dep_util newer12852079
Ref: 460a12852079
Ref: distutils/apiref distutils dep_util newer_pairwise12852417
Ref: 460b12852417
Ref: distutils/apiref distutils dep_util newer_group12852737
Ref: 460c12852737
Node: distutils dir_util --- Directory tree operations12853632
Ref: distutils/apiref distutils-dir-util-directory-tree-operations12853832
Ref: 460d12853832
Ref: distutils/apiref module-distutils dir_util12853832
Ref: 5712853832
Ref: distutils/apiref distutils dir_util mkpath12854038
Ref: 45fb12854038
Ref: distutils/apiref distutils dir_util create_tree12854645
Ref: 460e12854645
Ref: distutils/apiref distutils dir_util copy_tree12855204
Ref: 460f12855204
Ref: distutils/apiref distutils dir_util remove_tree12856672
Ref: 461112856672
Ref: distutils dir_util --- Directory tree operations-Footnote-112856984
Node: distutils file_util --- Single file operations12857030
Ref: distutils/apiref distutils-file-util-single-file-operations12857244
Ref: 461212857244
Ref: distutils/apiref module-distutils file_util12857244
Ref: 5c12857244
Ref: distutils/apiref distutils file_util copy_file12857441
Ref: 461012857441
Ref: distutils/apiref distutils file_util move_file12858859
Ref: 45fd12858859
Ref: distutils/apiref distutils file_util write_file12859257
Ref: 461312859257
Node: distutils util --- Miscellaneous other utility functions12859442
Ref: distutils/apiref distutils-util-miscellaneous-other-utility-functions12859649
Ref: 461412859649
Ref: distutils/apiref module-distutils util12859649
Ref: 6412859649
Ref: distutils/apiref distutils util get_platform12859887
Ref: 461512859887
Ref: distutils/apiref distutils util convert_path12862421
Ref: 461612862421
Ref: distutils/apiref distutils util change_root12862964
Ref: 461712862964
Ref: distutils/apiref distutils util check_environ12863287
Ref: 461812863287
Ref: distutils/apiref distutils util subst_vars12863704
Ref: 461912863704
Ref: distutils/apiref distutils util split_quoted12864518
Ref: 45eb12864518
Ref: distutils/apiref distutils util execute12865091
Ref: 45f812865091
Ref: distutils/apiref distutils util strtobool12865605
Ref: 461a12865605
Ref: distutils/apiref distutils util byte_compile12865956
Ref: 461b12865956
Ref: distutils/apiref distutils util rfc822_escape12867959
Ref: 461c12867959
Ref: distutils util --- Miscellaneous other utility functions-Footnote-112868250
Ref: distutils util --- Miscellaneous other utility functions-Footnote-212868299
Ref: distutils util --- Miscellaneous other utility functions-Footnote-312868348
Ref: distutils util --- Miscellaneous other utility functions-Footnote-412868397
Node: distutils dist --- The Distribution class12868445
Ref: distutils/apiref distutils-dist-the-distribution-class12868649
Ref: 461d12868649
Ref: distutils/apiref module-distutils dist12868649
Ref: 5812868649
Node: distutils extension --- The Extension class12868891
Ref: distutils/apiref distutils-extension-the-extension-class12869079
Ref: 461e12869079
Ref: distutils/apiref module-distutils extension12869079
Ref: 5a12869079
Node: distutils debug --- Distutils debug mode12869298
Ref: distutils/apiref distutils-debug-distutils-debug-mode12869486
Ref: 461f12869486
Ref: distutils/apiref module-distutils debug12869486
Ref: 5512869486
Node: distutils errors --- Distutils exceptions12869622
Ref: distutils/apiref distutils-errors-distutils-exceptions12869835
Ref: 462012869835
Ref: distutils/apiref module-distutils errors12869835
Ref: 5912869835
Node: distutils fancy_getopt --- Wrapper around the standard getopt module12870335
Ref: distutils/apiref distutils-fancy-getopt-wrapper-around-the-standard-getopt-module12870549
Ref: 462112870549
Ref: distutils/apiref module-distutils fancy_getopt12870549
Ref: 5b12870549
Ref: distutils/apiref distutils fancy_getopt fancy_getopt12871247
Ref: 462212871247
Ref: distutils/apiref distutils fancy_getopt wrap_text12871903
Ref: 462412871903
Ref: distutils/apiref distutils fancy_getopt FancyGetopt12872009
Ref: 462312872009
Ref: distutils/apiref distutils fancy_getopt FancyGetopt getopt12872575
Ref: 462512872575
Ref: distutils/apiref distutils fancy_getopt FancyGetopt get_option_order12873183
Ref: 462612873183
Ref: distutils/apiref distutils fancy_getopt FancyGetopt generate_help12873433
Ref: 462712873433
Node: distutils filelist --- The FileList class12873719
Ref: distutils/apiref distutils-filelist-the-filelist-class12873938
Ref: 462812873938
Ref: distutils/apiref module-distutils filelist12873938
Ref: 5d12873938
Node: distutils log --- Simple PEP 282-style logging12874159
Ref: distutils/apiref distutils-log-simple-pep-282-style-logging12874349
Ref: 462912874349
Ref: distutils/apiref module-distutils log12874349
Ref: 5e12874349
Node: distutils spawn --- Spawn a sub-process12874470
Ref: distutils/apiref distutils-spawn-spawn-a-sub-process12874675
Ref: 462a12874675
Ref: distutils/apiref module-distutils spawn12874675
Ref: 6012874675
Node: distutils sysconfig --- System configuration information12875014
Ref: distutils/apiref distutils-sysconfig-system-configuration-information12875215
Ref: 462b12875215
Ref: distutils/apiref module-distutils sysconfig12875215
Ref: 6112875215
Ref: distutils/apiref distutils sysconfig PREFIX12876058
Ref: 462c12876058
Ref: distutils/apiref distutils sysconfig EXEC_PREFIX12876152
Ref: 462d12876152
Ref: distutils/apiref distutils sysconfig get_config_var12876256
Ref: 462e12876256
Ref: distutils/apiref distutils sysconfig get_config_vars12876419
Ref: 462f12876419
Ref: distutils/apiref distutils sysconfig get_config_h_filename12876871
Ref: 463012876871
Ref: distutils/apiref distutils sysconfig get_makefile_filename12877229
Ref: 463112877229
Ref: distutils/apiref distutils sysconfig get_python_inc12877605
Ref: 463212877605
Ref: distutils/apiref distutils sysconfig get_python_lib12878124
Ref: 463312878124
Ref: distutils/apiref distutils sysconfig customize_compiler12878927
Ref: 463412878927
Ref: distutils/apiref distutils sysconfig set_python_build12879595
Ref: 463512879595
Node: distutils text_file --- The TextFile class12879916
Ref: distutils/apiref distutils-text-file-the-textfile-class12880122
Ref: 463612880122
Ref: distutils/apiref module-distutils text_file12880122
Ref: 6212880122
Ref: distutils/apiref distutils text_file TextFile12880435
Ref: 463712880435
Ref: distutils/apiref distutils text_file TextFile open12884962
Ref: 463b12884962
Ref: distutils/apiref distutils text_file TextFile close12885115
Ref: 463a12885115
Ref: distutils/apiref distutils text_file TextFile warn12885285
Ref: 463812885285
Ref: distutils/apiref distutils text_file TextFile readline12885801
Ref: 463c12885801
Ref: distutils/apiref distutils text_file TextFile readlines12886485
Ref: 463d12886485
Ref: distutils/apiref distutils text_file TextFile unreadline12886698
Ref: 463912886698
Node: distutils version --- Version number classes12887329
Ref: distutils/apiref distutils-version-version-number-classes12887539
Ref: 463e12887539
Ref: distutils/apiref module-distutils version12887539
Ref: 6512887539
Node: distutils cmd --- Abstract base class for Distutils commands12887652
Ref: distutils/apiref distutils-cmd-abstract-base-class-for-distutils-commands12887852
Ref: 463f12887852
Ref: distutils/apiref module-distutils cmd12887852
Ref: 3c12887852
Ref: distutils/apiref distutils cmd Command12888064
Ref: 45bd12888064
Node: Creating a new Distutils command12889139
Ref: distutils/apiref creating-a-new-distutils-command12889346
Ref: 464312889346
Ref: distutils/apiref distutils cmd Command initialize_options12890215
Ref: 464012890215
Ref: distutils/apiref distutils cmd Command finalize_options12890669
Ref: 464112890669
Ref: distutils/apiref distutils cmd Command run12891171
Ref: 464212891171
Ref: distutils/apiref distutils cmd Command sub_commands12891603
Ref: 464412891603
Node: distutils command --- Individual Distutils commands12892587
Ref: distutils/apiref distutils-command-individual-distutils-commands12892786
Ref: 464512892786
Ref: distutils/apiref module-distutils command12892786
Ref: 3d12892786
Node: distutils command bdist --- Build a binary installer12892913
Ref: distutils/apiref distutils-command-bdist-build-a-binary-installer12893150
Ref: 464612893150
Ref: distutils/apiref module-distutils command bdist12893150
Ref: 3e12893150
Node: distutils command bdist_packager --- Abstract base class for packagers12893279
Ref: distutils/apiref distutils-command-bdist-packager-abstract-base-class-for-packagers12893522
Ref: 464712893522
Ref: distutils/apiref module-distutils command bdist_packager12893522
Ref: 4112893522
Node: distutils command bdist_dumb --- Build a "dumb" installer12893687
Ref: distutils/apiref distutils-command-bdist-dumb-build-a-dumb-installer12893952
Ref: 464812893952
Ref: distutils/apiref module-distutils command bdist_dumb12893952
Ref: 3f12893952
Node: distutils command bdist_msi --- Build a Microsoft Installer binary package12894091
Ref: distutils/apiref distutils-command-bdist-msi-build-a-microsoft-installer-binary-package12894370
Ref: 464912894370
Ref: distutils/apiref module-distutils command bdist_msi12894370
Ref: 4012894370
Ref: distutils/apiref distutils command bdist_msi bdist_msi12894543
Ref: 464a12894543
Ref: distutils command bdist_msi --- Build a Microsoft Installer binary package-Footnote-112895021
Node: distutils command bdist_rpm --- Build a binary distribution as a Redhat RPM and SRPM12895091
Ref: distutils/apiref distutils-command-bdist-rpm-build-a-binary-distribution-as-a-redhat-rpm-and-srpm12895374
Ref: 464b12895374
Ref: distutils/apiref module-distutils command bdist_rpm12895374
Ref: 4212895374
Node: distutils command bdist_wininst --- Build a Windows installer12895567
Ref: distutils/apiref distutils-command-bdist-wininst-build-a-windows-installer12895831
Ref: 464c12895831
Ref: distutils/apiref module-distutils command bdist_wininst12895831
Ref: 4312895831
Node: distutils command sdist --- Build a source distribution12896042
Ref: distutils/apiref distutils-command-sdist-build-a-source-distribution12896278
Ref: 464d12896278
Ref: distutils/apiref module-distutils command sdist12896278
Ref: 5212896278
Node: distutils command build --- Build all files of a package12896413
Ref: distutils/apiref distutils-command-build-build-all-files-of-a-package12896655
Ref: 464e12896655
Ref: distutils/apiref module-distutils command build12896655
Ref: 4412896655
Node: distutils command build_clib --- Build any C libraries in a package12896792
Ref: distutils/apiref distutils-command-build-clib-build-any-c-libraries-in-a-package12897044
Ref: 464f12897044
Ref: distutils/apiref module-distutils command build_clib12897044
Ref: 4512897044
Node: distutils command build_ext --- Build any extensions in a package12897203
Ref: distutils/apiref distutils-command-build-ext-build-any-extensions-in-a-package12897466
Ref: 465012897466
Ref: distutils/apiref module-distutils command build_ext12897466
Ref: 4612897466
Node: distutils command build_py --- Build the py/ pyc files of a package12897621
Ref: distutils/apiref distutils-command-build-py-build-the-py-pyc-files-of-a-package12897883
Ref: 465112897883
Ref: distutils/apiref module-distutils command build_py12897883
Ref: 4712897883
Ref: distutils/apiref distutils command build_py build_py12898044
Ref: 465212898044
Ref: distutils/apiref distutils command build_py build_py_2to312898093
Ref: 465312898093
Node: distutils command build_scripts --- Build the scripts of a package12898711
Ref: distutils/apiref distutils-command-build-scripts-build-the-scripts-of-a-package12898962
Ref: 465412898962
Ref: distutils/apiref module-distutils command build_scripts12898962
Ref: 4812898962
Node: distutils command clean --- Clean a package build area12899119
Ref: distutils/apiref distutils-command-clean-clean-a-package-build-area12899361
Ref: 465512899361
Ref: distutils/apiref module-distutils command clean12899361
Ref: 4a12899361
Node: distutils command config --- Perform package configuration12899805
Ref: distutils/apiref distutils-command-config-perform-package-configuration12900028
Ref: 465612900028
Ref: distutils/apiref module-distutils command config12900028
Ref: 4b12900028
Node: distutils command install --- Install a package12900169
Ref: distutils/apiref distutils-command-install-install-a-package12900406
Ref: 465712900406
Ref: distutils/apiref module-distutils command install12900406
Ref: 4c12900406
Node: distutils command install_data --- Install data files from a package12900525
Ref: distutils/apiref distutils-command-install-data-install-data-files-from-a-package12900783
Ref: 465812900783
Ref: distutils/apiref module-distutils command install_data12900783
Ref: 4d12900783
Node: distutils command install_headers --- Install C/C++ header files from a package12900944
Ref: distutils/apiref distutils-command-install-headers-install-c-c-header-files-from-a-package12901225
Ref: 465912901225
Ref: distutils/apiref module-distutils command install_headers12901225
Ref: 4e12901225
Node: distutils command install_lib --- Install library files from a package12901408
Ref: distutils/apiref distutils-command-install-lib-install-library-files-from-a-package12901694
Ref: 465a12901694
Ref: distutils/apiref module-distutils command install_lib12901694
Ref: 4f12901694
Node: distutils command install_scripts --- Install script files from a package12901859
Ref: distutils/apiref distutils-command-install-scripts-install-script-files-from-a-package12902144
Ref: 465b12902144
Ref: distutils/apiref module-distutils command install_scripts12902144
Ref: 5012902144
Node: distutils command register --- Register a module with the Python Package Index12902315
Ref: distutils/apiref distutils-command-register-register-a-module-with-the-python-package-index12902590
Ref: 465c12902590
Ref: distutils/apiref module-distutils command register12902590
Ref: 5112902590
Ref: distutils command register --- Register a module with the Python Package Index-Footnote-112902937
Node: distutils command check --- Check the meta-data of a package12902986
Ref: distutils/apiref distutils-command-check-check-the-meta-data-of-a-package12903179
Ref: 465d12903179
Ref: distutils/apiref module-distutils command check12903179
Ref: 4912903179
Node: 安裝 Python 模組（舊版）12903521
Ref: install/index doc12903662
Ref: 465e12903662
Ref: install/index install-index12903662
Ref: 8e412903662
Ref: install/index installing-python-modules-legacy-version12903662
Ref: 465f12903662
Ref: 安裝 Python 模組（舊版）-Footnote-112904691
Node: 簡介<16>12904757
Ref: install/index inst-intro12904871
Ref: 466012904871
Ref: install/index introduction12904871
Ref: 466112904871
Node: 基于分布式系统的源代码分发12905712
Ref: install/index distutils-based-source-distributions12905798
Ref: 466212905798
Ref: install/index inst-new-standard12905798
Ref: 466312905798
Node: Standard Build and Install12907065
Ref: install/index inst-standard-install12907210
Ref: 466412907210
Ref: install/index standard-build-and-install12907210
Ref: 466512907210
Node: Platform variations12907612
Ref: install/index inst-platform-variations12907723
Ref: 466612907723
Ref: install/index platform-variations12907723
Ref: 466712907723
Node: Splitting the job up12908638
Ref: install/index inst-splitting-up12908776
Ref: 466812908776
Ref: install/index splitting-the-job-up12908776
Ref: 466912908776
Node: How building works12910080
Ref: install/index how-building-works12910221
Ref: 466a12910221
Ref: install/index inst-how-build-works12910221
Ref: 466b12910221
Node: How installation works12911946
Ref: install/index how-installation-works12912058
Ref: 466d12912058
Ref: install/index inst-how-install-works12912058
Ref: 466e12912058
Node: Alternate Installation12916864
Ref: install/index alternate-installation12917014
Ref: 467112917014
Ref: install/index inst-alt-install12917014
Ref: 466f12917014
Node: Alternate installation the user scheme12918702
Ref: install/index alternate-installation-the-user-scheme12918846
Ref: 467212918846
Ref: install/index inst-alt-install-user12918846
Ref: 148a12918846
Node: Alternate installation the home scheme12921242
Ref: install/index alternate-installation-the-home-scheme12921440
Ref: 467312921440
Ref: install/index inst-alt-install-home12921440
Ref: 467412921440
Node: Alternate installation Unix the prefix scheme12923236
Ref: install/index alternate-installation-unix-the-prefix-scheme12923444
Ref: 467612923444
Ref: install/index inst-alt-install-prefix-unix12923444
Ref: 467712923444
Node: Alternate installation Windows the prefix scheme12927478
Ref: install/index alternate-installation-windows-the-prefix-scheme12927639
Ref: 467812927639
Ref: install/index inst-alt-install-prefix-windows12927639
Ref: 467912927639
Node: 自定义安装12928909
Ref: install/index custom-installation12929062
Ref: 467a12929062
Ref: install/index inst-custom-install12929062
Ref: 467012929062
Node: Modifying Python's Search Path12936053
Ref: install/index inst-search-path12936135
Ref: 467512936135
Ref: install/index modifying-python-s-search-path12936135
Ref: 467b12936135
Node: Distutils Configuration Files12939857
Ref: install/index distutils-configuration-files12940023
Ref: 467c12940023
Ref: install/index inst-config-files12940023
Ref: 466c12940023
Node: Location and names of config files12940726
Ref: install/index inst-config-filenames12940857
Ref: 467d12940857
Ref: install/index location-and-names-of-config-files12940857
Ref: 467e12940857
Node: Syntax of config files12944799
Ref: install/index inst-config-syntax12944930
Ref: 459712944930
Ref: install/index syntax-of-config-files12944930
Ref: 467f12944930
Node: Building Extensions Tips and Tricks12946844
Ref: install/index building-extensions-tips-and-tricks12946986
Ref: 468012946986
Ref: install/index inst-building-ext12946986
Ref: 468112946986
Node: Tweaking compiler/linker flags12947592
Ref: install/index inst-tweak-flags12947743
Ref: 468212947743
Ref: install/index tweaking-compiler-linker-flags12947743
Ref: 468312947743
Node: Using non-Microsoft compilers on Windows12950812
Ref: install/index inst-non-ms-compilers12950963
Ref: 468412950963
Ref: install/index using-non-microsoft-compilers-on-windows12950963
Ref: 468512950963
Node: Borland/CodeGear C++12951122
Ref: install/index borland-codegear-c12951250
Ref: 468612951250
Ref: Borland/CodeGear C++-Footnote-112953206
Ref: Borland/CodeGear C++-Footnote-212953317
Ref: Borland/CodeGear C++-Footnote-312953362
Node: GNU C / Cygwin / MinGW12953416
Ref: install/index gnu-c-cygwin-mingw12953544
Ref: 468712953544
Ref: GNU C / Cygwin / MinGW-Footnote-112954552
Ref: GNU C / Cygwin / MinGW-Footnote-212954632
Node: Older Versions of Python and MinGW12954733
Ref: install/index older-versions-of-python-and-mingw12954826
Ref: 468812954826
Ref: Older Versions of Python and MinGW-Footnote-112956490
Node: Python 模組索引12956555
Node: 索引12979674
Ref: using/cmdline audit_event_cpython_run_file_014624132
Ref: 43fd14624162
Ref: howto/urllib2 quick-reference-to-http-headers14624193
Ref: 366e14624224
Ref: 366f14624255
Ref: using/cmdline audit_event_cpython_run_stdin_014624286

End Tag Table


Local Variables:
coding: utf-8
End:
